xref: /openbmc/linux/kernel/bpf/syscall.c (revision aeb64ff3)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
3  */
4 #include <linux/bpf.h>
5 #include <linux/bpf_trace.h>
6 #include <linux/bpf_lirc.h>
7 #include <linux/btf.h>
8 #include <linux/syscalls.h>
9 #include <linux/slab.h>
10 #include <linux/sched/signal.h>
11 #include <linux/vmalloc.h>
12 #include <linux/mmzone.h>
13 #include <linux/anon_inodes.h>
14 #include <linux/fdtable.h>
15 #include <linux/file.h>
16 #include <linux/fs.h>
17 #include <linux/license.h>
18 #include <linux/filter.h>
19 #include <linux/version.h>
20 #include <linux/kernel.h>
21 #include <linux/idr.h>
22 #include <linux/cred.h>
23 #include <linux/timekeeping.h>
24 #include <linux/ctype.h>
25 #include <linux/nospec.h>
26 #include <uapi/linux/btf.h>
27 
28 #define IS_FD_ARRAY(map) ((map)->map_type == BPF_MAP_TYPE_PERF_EVENT_ARRAY || \
29 			  (map)->map_type == BPF_MAP_TYPE_CGROUP_ARRAY || \
30 			  (map)->map_type == BPF_MAP_TYPE_ARRAY_OF_MAPS)
31 #define IS_FD_PROG_ARRAY(map) ((map)->map_type == BPF_MAP_TYPE_PROG_ARRAY)
32 #define IS_FD_HASH(map) ((map)->map_type == BPF_MAP_TYPE_HASH_OF_MAPS)
33 #define IS_FD_MAP(map) (IS_FD_ARRAY(map) || IS_FD_PROG_ARRAY(map) || \
34 			IS_FD_HASH(map))
35 
36 #define BPF_OBJ_FLAG_MASK   (BPF_F_RDONLY | BPF_F_WRONLY)
37 
38 DEFINE_PER_CPU(int, bpf_prog_active);
39 static DEFINE_IDR(prog_idr);
40 static DEFINE_SPINLOCK(prog_idr_lock);
41 static DEFINE_IDR(map_idr);
42 static DEFINE_SPINLOCK(map_idr_lock);
43 
44 int sysctl_unprivileged_bpf_disabled __read_mostly;
45 
46 static const struct bpf_map_ops * const bpf_map_types[] = {
47 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type)
48 #define BPF_MAP_TYPE(_id, _ops) \
49 	[_id] = &_ops,
50 #include <linux/bpf_types.h>
51 #undef BPF_PROG_TYPE
52 #undef BPF_MAP_TYPE
53 };
54 
55 /*
56  * If we're handed a bigger struct than we know of, ensure all the unknown bits
57  * are 0 - i.e. new user-space does not rely on any kernel feature extensions
58  * we don't know about yet.
59  *
60  * There is a ToCToU between this function call and the following
61  * copy_from_user() call. However, this is not a concern since this function is
62  * meant to be a future-proofing of bits.
63  */
64 int bpf_check_uarg_tail_zero(void __user *uaddr,
65 			     size_t expected_size,
66 			     size_t actual_size)
67 {
68 	unsigned char __user *addr;
69 	unsigned char __user *end;
70 	unsigned char val;
71 	int err;
72 
73 	if (unlikely(actual_size > PAGE_SIZE))	/* silly large */
74 		return -E2BIG;
75 
76 	if (unlikely(!access_ok(uaddr, actual_size)))
77 		return -EFAULT;
78 
79 	if (actual_size <= expected_size)
80 		return 0;
81 
82 	addr = uaddr + expected_size;
83 	end  = uaddr + actual_size;
84 
85 	for (; addr < end; addr++) {
86 		err = get_user(val, addr);
87 		if (err)
88 			return err;
89 		if (val)
90 			return -E2BIG;
91 	}
92 
93 	return 0;
94 }
95 
96 const struct bpf_map_ops bpf_map_offload_ops = {
97 	.map_alloc = bpf_map_offload_map_alloc,
98 	.map_free = bpf_map_offload_map_free,
99 	.map_check_btf = map_check_no_btf,
100 };
101 
102 static struct bpf_map *find_and_alloc_map(union bpf_attr *attr)
103 {
104 	const struct bpf_map_ops *ops;
105 	u32 type = attr->map_type;
106 	struct bpf_map *map;
107 	int err;
108 
109 	if (type >= ARRAY_SIZE(bpf_map_types))
110 		return ERR_PTR(-EINVAL);
111 	type = array_index_nospec(type, ARRAY_SIZE(bpf_map_types));
112 	ops = bpf_map_types[type];
113 	if (!ops)
114 		return ERR_PTR(-EINVAL);
115 
116 	if (ops->map_alloc_check) {
117 		err = ops->map_alloc_check(attr);
118 		if (err)
119 			return ERR_PTR(err);
120 	}
121 	if (attr->map_ifindex)
122 		ops = &bpf_map_offload_ops;
123 	map = ops->map_alloc(attr);
124 	if (IS_ERR(map))
125 		return map;
126 	map->ops = ops;
127 	map->map_type = type;
128 	return map;
129 }
130 
131 static void *__bpf_map_area_alloc(u64 size, int numa_node, bool mmapable)
132 {
133 	/* We really just want to fail instead of triggering OOM killer
134 	 * under memory pressure, therefore we set __GFP_NORETRY to kmalloc,
135 	 * which is used for lower order allocation requests.
136 	 *
137 	 * It has been observed that higher order allocation requests done by
138 	 * vmalloc with __GFP_NORETRY being set might fail due to not trying
139 	 * to reclaim memory from the page cache, thus we set
140 	 * __GFP_RETRY_MAYFAIL to avoid such situations.
141 	 */
142 
143 	const gfp_t flags = __GFP_NOWARN | __GFP_ZERO;
144 	void *area;
145 
146 	if (size >= SIZE_MAX)
147 		return NULL;
148 
149 	/* kmalloc()'ed memory can't be mmap()'ed */
150 	if (!mmapable && size <= (PAGE_SIZE << PAGE_ALLOC_COSTLY_ORDER)) {
151 		area = kmalloc_node(size, GFP_USER | __GFP_NORETRY | flags,
152 				    numa_node);
153 		if (area != NULL)
154 			return area;
155 	}
156 	if (mmapable) {
157 		BUG_ON(!PAGE_ALIGNED(size));
158 		return vmalloc_user_node_flags(size, numa_node, GFP_KERNEL |
159 					       __GFP_RETRY_MAYFAIL | flags);
160 	}
161 	return __vmalloc_node_flags_caller(size, numa_node,
162 					   GFP_KERNEL | __GFP_RETRY_MAYFAIL |
163 					   flags, __builtin_return_address(0));
164 }
165 
166 void *bpf_map_area_alloc(u64 size, int numa_node)
167 {
168 	return __bpf_map_area_alloc(size, numa_node, false);
169 }
170 
171 void *bpf_map_area_mmapable_alloc(u64 size, int numa_node)
172 {
173 	return __bpf_map_area_alloc(size, numa_node, true);
174 }
175 
176 void bpf_map_area_free(void *area)
177 {
178 	kvfree(area);
179 }
180 
181 static u32 bpf_map_flags_retain_permanent(u32 flags)
182 {
183 	/* Some map creation flags are not tied to the map object but
184 	 * rather to the map fd instead, so they have no meaning upon
185 	 * map object inspection since multiple file descriptors with
186 	 * different (access) properties can exist here. Thus, given
187 	 * this has zero meaning for the map itself, lets clear these
188 	 * from here.
189 	 */
190 	return flags & ~(BPF_F_RDONLY | BPF_F_WRONLY);
191 }
192 
193 void bpf_map_init_from_attr(struct bpf_map *map, union bpf_attr *attr)
194 {
195 	map->map_type = attr->map_type;
196 	map->key_size = attr->key_size;
197 	map->value_size = attr->value_size;
198 	map->max_entries = attr->max_entries;
199 	map->map_flags = bpf_map_flags_retain_permanent(attr->map_flags);
200 	map->numa_node = bpf_map_attr_numa_node(attr);
201 }
202 
203 static int bpf_charge_memlock(struct user_struct *user, u32 pages)
204 {
205 	unsigned long memlock_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
206 
207 	if (atomic_long_add_return(pages, &user->locked_vm) > memlock_limit) {
208 		atomic_long_sub(pages, &user->locked_vm);
209 		return -EPERM;
210 	}
211 	return 0;
212 }
213 
214 static void bpf_uncharge_memlock(struct user_struct *user, u32 pages)
215 {
216 	if (user)
217 		atomic_long_sub(pages, &user->locked_vm);
218 }
219 
220 int bpf_map_charge_init(struct bpf_map_memory *mem, u64 size)
221 {
222 	u32 pages = round_up(size, PAGE_SIZE) >> PAGE_SHIFT;
223 	struct user_struct *user;
224 	int ret;
225 
226 	if (size >= U32_MAX - PAGE_SIZE)
227 		return -E2BIG;
228 
229 	user = get_current_user();
230 	ret = bpf_charge_memlock(user, pages);
231 	if (ret) {
232 		free_uid(user);
233 		return ret;
234 	}
235 
236 	mem->pages = pages;
237 	mem->user = user;
238 
239 	return 0;
240 }
241 
242 void bpf_map_charge_finish(struct bpf_map_memory *mem)
243 {
244 	bpf_uncharge_memlock(mem->user, mem->pages);
245 	free_uid(mem->user);
246 }
247 
248 void bpf_map_charge_move(struct bpf_map_memory *dst,
249 			 struct bpf_map_memory *src)
250 {
251 	*dst = *src;
252 
253 	/* Make sure src will not be used for the redundant uncharging. */
254 	memset(src, 0, sizeof(struct bpf_map_memory));
255 }
256 
257 int bpf_map_charge_memlock(struct bpf_map *map, u32 pages)
258 {
259 	int ret;
260 
261 	ret = bpf_charge_memlock(map->memory.user, pages);
262 	if (ret)
263 		return ret;
264 	map->memory.pages += pages;
265 	return ret;
266 }
267 
268 void bpf_map_uncharge_memlock(struct bpf_map *map, u32 pages)
269 {
270 	bpf_uncharge_memlock(map->memory.user, pages);
271 	map->memory.pages -= pages;
272 }
273 
274 static int bpf_map_alloc_id(struct bpf_map *map)
275 {
276 	int id;
277 
278 	idr_preload(GFP_KERNEL);
279 	spin_lock_bh(&map_idr_lock);
280 	id = idr_alloc_cyclic(&map_idr, map, 1, INT_MAX, GFP_ATOMIC);
281 	if (id > 0)
282 		map->id = id;
283 	spin_unlock_bh(&map_idr_lock);
284 	idr_preload_end();
285 
286 	if (WARN_ON_ONCE(!id))
287 		return -ENOSPC;
288 
289 	return id > 0 ? 0 : id;
290 }
291 
292 void bpf_map_free_id(struct bpf_map *map, bool do_idr_lock)
293 {
294 	unsigned long flags;
295 
296 	/* Offloaded maps are removed from the IDR store when their device
297 	 * disappears - even if someone holds an fd to them they are unusable,
298 	 * the memory is gone, all ops will fail; they are simply waiting for
299 	 * refcnt to drop to be freed.
300 	 */
301 	if (!map->id)
302 		return;
303 
304 	if (do_idr_lock)
305 		spin_lock_irqsave(&map_idr_lock, flags);
306 	else
307 		__acquire(&map_idr_lock);
308 
309 	idr_remove(&map_idr, map->id);
310 	map->id = 0;
311 
312 	if (do_idr_lock)
313 		spin_unlock_irqrestore(&map_idr_lock, flags);
314 	else
315 		__release(&map_idr_lock);
316 }
317 
318 /* called from workqueue */
319 static void bpf_map_free_deferred(struct work_struct *work)
320 {
321 	struct bpf_map *map = container_of(work, struct bpf_map, work);
322 	struct bpf_map_memory mem;
323 
324 	bpf_map_charge_move(&mem, &map->memory);
325 	security_bpf_map_free(map);
326 	/* implementation dependent freeing */
327 	map->ops->map_free(map);
328 	bpf_map_charge_finish(&mem);
329 }
330 
331 static void bpf_map_put_uref(struct bpf_map *map)
332 {
333 	if (atomic64_dec_and_test(&map->usercnt)) {
334 		if (map->ops->map_release_uref)
335 			map->ops->map_release_uref(map);
336 	}
337 }
338 
339 /* decrement map refcnt and schedule it for freeing via workqueue
340  * (unrelying map implementation ops->map_free() might sleep)
341  */
342 static void __bpf_map_put(struct bpf_map *map, bool do_idr_lock)
343 {
344 	if (atomic64_dec_and_test(&map->refcnt)) {
345 		/* bpf_map_free_id() must be called first */
346 		bpf_map_free_id(map, do_idr_lock);
347 		btf_put(map->btf);
348 		INIT_WORK(&map->work, bpf_map_free_deferred);
349 		schedule_work(&map->work);
350 	}
351 }
352 
353 void bpf_map_put(struct bpf_map *map)
354 {
355 	__bpf_map_put(map, true);
356 }
357 EXPORT_SYMBOL_GPL(bpf_map_put);
358 
359 void bpf_map_put_with_uref(struct bpf_map *map)
360 {
361 	bpf_map_put_uref(map);
362 	bpf_map_put(map);
363 }
364 
365 static int bpf_map_release(struct inode *inode, struct file *filp)
366 {
367 	struct bpf_map *map = filp->private_data;
368 
369 	if (map->ops->map_release)
370 		map->ops->map_release(map, filp);
371 
372 	bpf_map_put_with_uref(map);
373 	return 0;
374 }
375 
376 static fmode_t map_get_sys_perms(struct bpf_map *map, struct fd f)
377 {
378 	fmode_t mode = f.file->f_mode;
379 
380 	/* Our file permissions may have been overridden by global
381 	 * map permissions facing syscall side.
382 	 */
383 	if (READ_ONCE(map->frozen))
384 		mode &= ~FMODE_CAN_WRITE;
385 	return mode;
386 }
387 
388 #ifdef CONFIG_PROC_FS
389 static void bpf_map_show_fdinfo(struct seq_file *m, struct file *filp)
390 {
391 	const struct bpf_map *map = filp->private_data;
392 	const struct bpf_array *array;
393 	u32 type = 0, jited = 0;
394 
395 	if (map->map_type == BPF_MAP_TYPE_PROG_ARRAY) {
396 		array = container_of(map, struct bpf_array, map);
397 		type  = array->aux->type;
398 		jited = array->aux->jited;
399 	}
400 
401 	seq_printf(m,
402 		   "map_type:\t%u\n"
403 		   "key_size:\t%u\n"
404 		   "value_size:\t%u\n"
405 		   "max_entries:\t%u\n"
406 		   "map_flags:\t%#x\n"
407 		   "memlock:\t%llu\n"
408 		   "map_id:\t%u\n"
409 		   "frozen:\t%u\n",
410 		   map->map_type,
411 		   map->key_size,
412 		   map->value_size,
413 		   map->max_entries,
414 		   map->map_flags,
415 		   map->memory.pages * 1ULL << PAGE_SHIFT,
416 		   map->id,
417 		   READ_ONCE(map->frozen));
418 	if (type) {
419 		seq_printf(m, "owner_prog_type:\t%u\n", type);
420 		seq_printf(m, "owner_jited:\t%u\n", jited);
421 	}
422 }
423 #endif
424 
425 static ssize_t bpf_dummy_read(struct file *filp, char __user *buf, size_t siz,
426 			      loff_t *ppos)
427 {
428 	/* We need this handler such that alloc_file() enables
429 	 * f_mode with FMODE_CAN_READ.
430 	 */
431 	return -EINVAL;
432 }
433 
434 static ssize_t bpf_dummy_write(struct file *filp, const char __user *buf,
435 			       size_t siz, loff_t *ppos)
436 {
437 	/* We need this handler such that alloc_file() enables
438 	 * f_mode with FMODE_CAN_WRITE.
439 	 */
440 	return -EINVAL;
441 }
442 
443 /* called for any extra memory-mapped regions (except initial) */
444 static void bpf_map_mmap_open(struct vm_area_struct *vma)
445 {
446 	struct bpf_map *map = vma->vm_file->private_data;
447 
448 	bpf_map_inc_with_uref(map);
449 
450 	if (vma->vm_flags & VM_WRITE) {
451 		mutex_lock(&map->freeze_mutex);
452 		map->writecnt++;
453 		mutex_unlock(&map->freeze_mutex);
454 	}
455 }
456 
457 /* called for all unmapped memory region (including initial) */
458 static void bpf_map_mmap_close(struct vm_area_struct *vma)
459 {
460 	struct bpf_map *map = vma->vm_file->private_data;
461 
462 	if (vma->vm_flags & VM_WRITE) {
463 		mutex_lock(&map->freeze_mutex);
464 		map->writecnt--;
465 		mutex_unlock(&map->freeze_mutex);
466 	}
467 
468 	bpf_map_put_with_uref(map);
469 }
470 
471 static const struct vm_operations_struct bpf_map_default_vmops = {
472 	.open		= bpf_map_mmap_open,
473 	.close		= bpf_map_mmap_close,
474 };
475 
476 static int bpf_map_mmap(struct file *filp, struct vm_area_struct *vma)
477 {
478 	struct bpf_map *map = filp->private_data;
479 	int err;
480 
481 	if (!map->ops->map_mmap || map_value_has_spin_lock(map))
482 		return -ENOTSUPP;
483 
484 	if (!(vma->vm_flags & VM_SHARED))
485 		return -EINVAL;
486 
487 	mutex_lock(&map->freeze_mutex);
488 
489 	if ((vma->vm_flags & VM_WRITE) && map->frozen) {
490 		err = -EPERM;
491 		goto out;
492 	}
493 
494 	/* set default open/close callbacks */
495 	vma->vm_ops = &bpf_map_default_vmops;
496 	vma->vm_private_data = map;
497 
498 	err = map->ops->map_mmap(map, vma);
499 	if (err)
500 		goto out;
501 
502 	bpf_map_inc_with_uref(map);
503 
504 	if (vma->vm_flags & VM_WRITE)
505 		map->writecnt++;
506 out:
507 	mutex_unlock(&map->freeze_mutex);
508 	return err;
509 }
510 
511 const struct file_operations bpf_map_fops = {
512 #ifdef CONFIG_PROC_FS
513 	.show_fdinfo	= bpf_map_show_fdinfo,
514 #endif
515 	.release	= bpf_map_release,
516 	.read		= bpf_dummy_read,
517 	.write		= bpf_dummy_write,
518 	.mmap		= bpf_map_mmap,
519 };
520 
521 int bpf_map_new_fd(struct bpf_map *map, int flags)
522 {
523 	int ret;
524 
525 	ret = security_bpf_map(map, OPEN_FMODE(flags));
526 	if (ret < 0)
527 		return ret;
528 
529 	return anon_inode_getfd("bpf-map", &bpf_map_fops, map,
530 				flags | O_CLOEXEC);
531 }
532 
533 int bpf_get_file_flag(int flags)
534 {
535 	if ((flags & BPF_F_RDONLY) && (flags & BPF_F_WRONLY))
536 		return -EINVAL;
537 	if (flags & BPF_F_RDONLY)
538 		return O_RDONLY;
539 	if (flags & BPF_F_WRONLY)
540 		return O_WRONLY;
541 	return O_RDWR;
542 }
543 
544 /* helper macro to check that unused fields 'union bpf_attr' are zero */
545 #define CHECK_ATTR(CMD) \
546 	memchr_inv((void *) &attr->CMD##_LAST_FIELD + \
547 		   sizeof(attr->CMD##_LAST_FIELD), 0, \
548 		   sizeof(*attr) - \
549 		   offsetof(union bpf_attr, CMD##_LAST_FIELD) - \
550 		   sizeof(attr->CMD##_LAST_FIELD)) != NULL
551 
552 /* dst and src must have at least BPF_OBJ_NAME_LEN number of bytes.
553  * Return 0 on success and < 0 on error.
554  */
555 static int bpf_obj_name_cpy(char *dst, const char *src)
556 {
557 	const char *end = src + BPF_OBJ_NAME_LEN;
558 
559 	memset(dst, 0, BPF_OBJ_NAME_LEN);
560 	/* Copy all isalnum(), '_' and '.' chars. */
561 	while (src < end && *src) {
562 		if (!isalnum(*src) &&
563 		    *src != '_' && *src != '.')
564 			return -EINVAL;
565 		*dst++ = *src++;
566 	}
567 
568 	/* No '\0' found in BPF_OBJ_NAME_LEN number of bytes */
569 	if (src == end)
570 		return -EINVAL;
571 
572 	return 0;
573 }
574 
575 int map_check_no_btf(const struct bpf_map *map,
576 		     const struct btf *btf,
577 		     const struct btf_type *key_type,
578 		     const struct btf_type *value_type)
579 {
580 	return -ENOTSUPP;
581 }
582 
583 static int map_check_btf(struct bpf_map *map, const struct btf *btf,
584 			 u32 btf_key_id, u32 btf_value_id)
585 {
586 	const struct btf_type *key_type, *value_type;
587 	u32 key_size, value_size;
588 	int ret = 0;
589 
590 	/* Some maps allow key to be unspecified. */
591 	if (btf_key_id) {
592 		key_type = btf_type_id_size(btf, &btf_key_id, &key_size);
593 		if (!key_type || key_size != map->key_size)
594 			return -EINVAL;
595 	} else {
596 		key_type = btf_type_by_id(btf, 0);
597 		if (!map->ops->map_check_btf)
598 			return -EINVAL;
599 	}
600 
601 	value_type = btf_type_id_size(btf, &btf_value_id, &value_size);
602 	if (!value_type || value_size != map->value_size)
603 		return -EINVAL;
604 
605 	map->spin_lock_off = btf_find_spin_lock(btf, value_type);
606 
607 	if (map_value_has_spin_lock(map)) {
608 		if (map->map_flags & BPF_F_RDONLY_PROG)
609 			return -EACCES;
610 		if (map->map_type != BPF_MAP_TYPE_HASH &&
611 		    map->map_type != BPF_MAP_TYPE_ARRAY &&
612 		    map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
613 		    map->map_type != BPF_MAP_TYPE_SK_STORAGE)
614 			return -ENOTSUPP;
615 		if (map->spin_lock_off + sizeof(struct bpf_spin_lock) >
616 		    map->value_size) {
617 			WARN_ONCE(1,
618 				  "verifier bug spin_lock_off %d value_size %d\n",
619 				  map->spin_lock_off, map->value_size);
620 			return -EFAULT;
621 		}
622 	}
623 
624 	if (map->ops->map_check_btf)
625 		ret = map->ops->map_check_btf(map, btf, key_type, value_type);
626 
627 	return ret;
628 }
629 
630 #define BPF_MAP_CREATE_LAST_FIELD btf_value_type_id
631 /* called via syscall */
632 static int map_create(union bpf_attr *attr)
633 {
634 	int numa_node = bpf_map_attr_numa_node(attr);
635 	struct bpf_map_memory mem;
636 	struct bpf_map *map;
637 	int f_flags;
638 	int err;
639 
640 	err = CHECK_ATTR(BPF_MAP_CREATE);
641 	if (err)
642 		return -EINVAL;
643 
644 	f_flags = bpf_get_file_flag(attr->map_flags);
645 	if (f_flags < 0)
646 		return f_flags;
647 
648 	if (numa_node != NUMA_NO_NODE &&
649 	    ((unsigned int)numa_node >= nr_node_ids ||
650 	     !node_online(numa_node)))
651 		return -EINVAL;
652 
653 	/* find map type and init map: hashtable vs rbtree vs bloom vs ... */
654 	map = find_and_alloc_map(attr);
655 	if (IS_ERR(map))
656 		return PTR_ERR(map);
657 
658 	err = bpf_obj_name_cpy(map->name, attr->map_name);
659 	if (err)
660 		goto free_map;
661 
662 	atomic64_set(&map->refcnt, 1);
663 	atomic64_set(&map->usercnt, 1);
664 	mutex_init(&map->freeze_mutex);
665 
666 	if (attr->btf_key_type_id || attr->btf_value_type_id) {
667 		struct btf *btf;
668 
669 		if (!attr->btf_value_type_id) {
670 			err = -EINVAL;
671 			goto free_map;
672 		}
673 
674 		btf = btf_get_by_fd(attr->btf_fd);
675 		if (IS_ERR(btf)) {
676 			err = PTR_ERR(btf);
677 			goto free_map;
678 		}
679 
680 		err = map_check_btf(map, btf, attr->btf_key_type_id,
681 				    attr->btf_value_type_id);
682 		if (err) {
683 			btf_put(btf);
684 			goto free_map;
685 		}
686 
687 		map->btf = btf;
688 		map->btf_key_type_id = attr->btf_key_type_id;
689 		map->btf_value_type_id = attr->btf_value_type_id;
690 	} else {
691 		map->spin_lock_off = -EINVAL;
692 	}
693 
694 	err = security_bpf_map_alloc(map);
695 	if (err)
696 		goto free_map;
697 
698 	err = bpf_map_alloc_id(map);
699 	if (err)
700 		goto free_map_sec;
701 
702 	err = bpf_map_new_fd(map, f_flags);
703 	if (err < 0) {
704 		/* failed to allocate fd.
705 		 * bpf_map_put_with_uref() is needed because the above
706 		 * bpf_map_alloc_id() has published the map
707 		 * to the userspace and the userspace may
708 		 * have refcnt-ed it through BPF_MAP_GET_FD_BY_ID.
709 		 */
710 		bpf_map_put_with_uref(map);
711 		return err;
712 	}
713 
714 	return err;
715 
716 free_map_sec:
717 	security_bpf_map_free(map);
718 free_map:
719 	btf_put(map->btf);
720 	bpf_map_charge_move(&mem, &map->memory);
721 	map->ops->map_free(map);
722 	bpf_map_charge_finish(&mem);
723 	return err;
724 }
725 
726 /* if error is returned, fd is released.
727  * On success caller should complete fd access with matching fdput()
728  */
729 struct bpf_map *__bpf_map_get(struct fd f)
730 {
731 	if (!f.file)
732 		return ERR_PTR(-EBADF);
733 	if (f.file->f_op != &bpf_map_fops) {
734 		fdput(f);
735 		return ERR_PTR(-EINVAL);
736 	}
737 
738 	return f.file->private_data;
739 }
740 
741 void bpf_map_inc(struct bpf_map *map)
742 {
743 	atomic64_inc(&map->refcnt);
744 }
745 EXPORT_SYMBOL_GPL(bpf_map_inc);
746 
747 void bpf_map_inc_with_uref(struct bpf_map *map)
748 {
749 	atomic64_inc(&map->refcnt);
750 	atomic64_inc(&map->usercnt);
751 }
752 EXPORT_SYMBOL_GPL(bpf_map_inc_with_uref);
753 
754 struct bpf_map *bpf_map_get_with_uref(u32 ufd)
755 {
756 	struct fd f = fdget(ufd);
757 	struct bpf_map *map;
758 
759 	map = __bpf_map_get(f);
760 	if (IS_ERR(map))
761 		return map;
762 
763 	bpf_map_inc_with_uref(map);
764 	fdput(f);
765 
766 	return map;
767 }
768 
769 /* map_idr_lock should have been held */
770 static struct bpf_map *__bpf_map_inc_not_zero(struct bpf_map *map, bool uref)
771 {
772 	int refold;
773 
774 	refold = atomic64_fetch_add_unless(&map->refcnt, 1, 0);
775 	if (!refold)
776 		return ERR_PTR(-ENOENT);
777 	if (uref)
778 		atomic64_inc(&map->usercnt);
779 
780 	return map;
781 }
782 
783 struct bpf_map *bpf_map_inc_not_zero(struct bpf_map *map)
784 {
785 	spin_lock_bh(&map_idr_lock);
786 	map = __bpf_map_inc_not_zero(map, false);
787 	spin_unlock_bh(&map_idr_lock);
788 
789 	return map;
790 }
791 EXPORT_SYMBOL_GPL(bpf_map_inc_not_zero);
792 
793 int __weak bpf_stackmap_copy(struct bpf_map *map, void *key, void *value)
794 {
795 	return -ENOTSUPP;
796 }
797 
798 static void *__bpf_copy_key(void __user *ukey, u64 key_size)
799 {
800 	if (key_size)
801 		return memdup_user(ukey, key_size);
802 
803 	if (ukey)
804 		return ERR_PTR(-EINVAL);
805 
806 	return NULL;
807 }
808 
809 /* last field in 'union bpf_attr' used by this command */
810 #define BPF_MAP_LOOKUP_ELEM_LAST_FIELD flags
811 
812 static int map_lookup_elem(union bpf_attr *attr)
813 {
814 	void __user *ukey = u64_to_user_ptr(attr->key);
815 	void __user *uvalue = u64_to_user_ptr(attr->value);
816 	int ufd = attr->map_fd;
817 	struct bpf_map *map;
818 	void *key, *value, *ptr;
819 	u32 value_size;
820 	struct fd f;
821 	int err;
822 
823 	if (CHECK_ATTR(BPF_MAP_LOOKUP_ELEM))
824 		return -EINVAL;
825 
826 	if (attr->flags & ~BPF_F_LOCK)
827 		return -EINVAL;
828 
829 	f = fdget(ufd);
830 	map = __bpf_map_get(f);
831 	if (IS_ERR(map))
832 		return PTR_ERR(map);
833 	if (!(map_get_sys_perms(map, f) & FMODE_CAN_READ)) {
834 		err = -EPERM;
835 		goto err_put;
836 	}
837 
838 	if ((attr->flags & BPF_F_LOCK) &&
839 	    !map_value_has_spin_lock(map)) {
840 		err = -EINVAL;
841 		goto err_put;
842 	}
843 
844 	key = __bpf_copy_key(ukey, map->key_size);
845 	if (IS_ERR(key)) {
846 		err = PTR_ERR(key);
847 		goto err_put;
848 	}
849 
850 	if (map->map_type == BPF_MAP_TYPE_PERCPU_HASH ||
851 	    map->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH ||
852 	    map->map_type == BPF_MAP_TYPE_PERCPU_ARRAY ||
853 	    map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
854 		value_size = round_up(map->value_size, 8) * num_possible_cpus();
855 	else if (IS_FD_MAP(map))
856 		value_size = sizeof(u32);
857 	else
858 		value_size = map->value_size;
859 
860 	err = -ENOMEM;
861 	value = kmalloc(value_size, GFP_USER | __GFP_NOWARN);
862 	if (!value)
863 		goto free_key;
864 
865 	if (bpf_map_is_dev_bound(map)) {
866 		err = bpf_map_offload_lookup_elem(map, key, value);
867 		goto done;
868 	}
869 
870 	preempt_disable();
871 	this_cpu_inc(bpf_prog_active);
872 	if (map->map_type == BPF_MAP_TYPE_PERCPU_HASH ||
873 	    map->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH) {
874 		err = bpf_percpu_hash_copy(map, key, value);
875 	} else if (map->map_type == BPF_MAP_TYPE_PERCPU_ARRAY) {
876 		err = bpf_percpu_array_copy(map, key, value);
877 	} else if (map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE) {
878 		err = bpf_percpu_cgroup_storage_copy(map, key, value);
879 	} else if (map->map_type == BPF_MAP_TYPE_STACK_TRACE) {
880 		err = bpf_stackmap_copy(map, key, value);
881 	} else if (IS_FD_ARRAY(map) || IS_FD_PROG_ARRAY(map)) {
882 		err = bpf_fd_array_map_lookup_elem(map, key, value);
883 	} else if (IS_FD_HASH(map)) {
884 		err = bpf_fd_htab_map_lookup_elem(map, key, value);
885 	} else if (map->map_type == BPF_MAP_TYPE_REUSEPORT_SOCKARRAY) {
886 		err = bpf_fd_reuseport_array_lookup_elem(map, key, value);
887 	} else if (map->map_type == BPF_MAP_TYPE_QUEUE ||
888 		   map->map_type == BPF_MAP_TYPE_STACK) {
889 		err = map->ops->map_peek_elem(map, value);
890 	} else {
891 		rcu_read_lock();
892 		if (map->ops->map_lookup_elem_sys_only)
893 			ptr = map->ops->map_lookup_elem_sys_only(map, key);
894 		else
895 			ptr = map->ops->map_lookup_elem(map, key);
896 		if (IS_ERR(ptr)) {
897 			err = PTR_ERR(ptr);
898 		} else if (!ptr) {
899 			err = -ENOENT;
900 		} else {
901 			err = 0;
902 			if (attr->flags & BPF_F_LOCK)
903 				/* lock 'ptr' and copy everything but lock */
904 				copy_map_value_locked(map, value, ptr, true);
905 			else
906 				copy_map_value(map, value, ptr);
907 			/* mask lock, since value wasn't zero inited */
908 			check_and_init_map_lock(map, value);
909 		}
910 		rcu_read_unlock();
911 	}
912 	this_cpu_dec(bpf_prog_active);
913 	preempt_enable();
914 
915 done:
916 	if (err)
917 		goto free_value;
918 
919 	err = -EFAULT;
920 	if (copy_to_user(uvalue, value, value_size) != 0)
921 		goto free_value;
922 
923 	err = 0;
924 
925 free_value:
926 	kfree(value);
927 free_key:
928 	kfree(key);
929 err_put:
930 	fdput(f);
931 	return err;
932 }
933 
934 static void maybe_wait_bpf_programs(struct bpf_map *map)
935 {
936 	/* Wait for any running BPF programs to complete so that
937 	 * userspace, when we return to it, knows that all programs
938 	 * that could be running use the new map value.
939 	 */
940 	if (map->map_type == BPF_MAP_TYPE_HASH_OF_MAPS ||
941 	    map->map_type == BPF_MAP_TYPE_ARRAY_OF_MAPS)
942 		synchronize_rcu();
943 }
944 
945 #define BPF_MAP_UPDATE_ELEM_LAST_FIELD flags
946 
947 static int map_update_elem(union bpf_attr *attr)
948 {
949 	void __user *ukey = u64_to_user_ptr(attr->key);
950 	void __user *uvalue = u64_to_user_ptr(attr->value);
951 	int ufd = attr->map_fd;
952 	struct bpf_map *map;
953 	void *key, *value;
954 	u32 value_size;
955 	struct fd f;
956 	int err;
957 
958 	if (CHECK_ATTR(BPF_MAP_UPDATE_ELEM))
959 		return -EINVAL;
960 
961 	f = fdget(ufd);
962 	map = __bpf_map_get(f);
963 	if (IS_ERR(map))
964 		return PTR_ERR(map);
965 	if (!(map_get_sys_perms(map, f) & FMODE_CAN_WRITE)) {
966 		err = -EPERM;
967 		goto err_put;
968 	}
969 
970 	if ((attr->flags & BPF_F_LOCK) &&
971 	    !map_value_has_spin_lock(map)) {
972 		err = -EINVAL;
973 		goto err_put;
974 	}
975 
976 	key = __bpf_copy_key(ukey, map->key_size);
977 	if (IS_ERR(key)) {
978 		err = PTR_ERR(key);
979 		goto err_put;
980 	}
981 
982 	if (map->map_type == BPF_MAP_TYPE_PERCPU_HASH ||
983 	    map->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH ||
984 	    map->map_type == BPF_MAP_TYPE_PERCPU_ARRAY ||
985 	    map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
986 		value_size = round_up(map->value_size, 8) * num_possible_cpus();
987 	else
988 		value_size = map->value_size;
989 
990 	err = -ENOMEM;
991 	value = kmalloc(value_size, GFP_USER | __GFP_NOWARN);
992 	if (!value)
993 		goto free_key;
994 
995 	err = -EFAULT;
996 	if (copy_from_user(value, uvalue, value_size) != 0)
997 		goto free_value;
998 
999 	/* Need to create a kthread, thus must support schedule */
1000 	if (bpf_map_is_dev_bound(map)) {
1001 		err = bpf_map_offload_update_elem(map, key, value, attr->flags);
1002 		goto out;
1003 	} else if (map->map_type == BPF_MAP_TYPE_CPUMAP ||
1004 		   map->map_type == BPF_MAP_TYPE_SOCKHASH ||
1005 		   map->map_type == BPF_MAP_TYPE_SOCKMAP) {
1006 		err = map->ops->map_update_elem(map, key, value, attr->flags);
1007 		goto out;
1008 	} else if (IS_FD_PROG_ARRAY(map)) {
1009 		err = bpf_fd_array_map_update_elem(map, f.file, key, value,
1010 						   attr->flags);
1011 		goto out;
1012 	}
1013 
1014 	/* must increment bpf_prog_active to avoid kprobe+bpf triggering from
1015 	 * inside bpf map update or delete otherwise deadlocks are possible
1016 	 */
1017 	preempt_disable();
1018 	__this_cpu_inc(bpf_prog_active);
1019 	if (map->map_type == BPF_MAP_TYPE_PERCPU_HASH ||
1020 	    map->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH) {
1021 		err = bpf_percpu_hash_update(map, key, value, attr->flags);
1022 	} else if (map->map_type == BPF_MAP_TYPE_PERCPU_ARRAY) {
1023 		err = bpf_percpu_array_update(map, key, value, attr->flags);
1024 	} else if (map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE) {
1025 		err = bpf_percpu_cgroup_storage_update(map, key, value,
1026 						       attr->flags);
1027 	} else if (IS_FD_ARRAY(map)) {
1028 		rcu_read_lock();
1029 		err = bpf_fd_array_map_update_elem(map, f.file, key, value,
1030 						   attr->flags);
1031 		rcu_read_unlock();
1032 	} else if (map->map_type == BPF_MAP_TYPE_HASH_OF_MAPS) {
1033 		rcu_read_lock();
1034 		err = bpf_fd_htab_map_update_elem(map, f.file, key, value,
1035 						  attr->flags);
1036 		rcu_read_unlock();
1037 	} else if (map->map_type == BPF_MAP_TYPE_REUSEPORT_SOCKARRAY) {
1038 		/* rcu_read_lock() is not needed */
1039 		err = bpf_fd_reuseport_array_update_elem(map, key, value,
1040 							 attr->flags);
1041 	} else if (map->map_type == BPF_MAP_TYPE_QUEUE ||
1042 		   map->map_type == BPF_MAP_TYPE_STACK) {
1043 		err = map->ops->map_push_elem(map, value, attr->flags);
1044 	} else {
1045 		rcu_read_lock();
1046 		err = map->ops->map_update_elem(map, key, value, attr->flags);
1047 		rcu_read_unlock();
1048 	}
1049 	__this_cpu_dec(bpf_prog_active);
1050 	preempt_enable();
1051 	maybe_wait_bpf_programs(map);
1052 out:
1053 free_value:
1054 	kfree(value);
1055 free_key:
1056 	kfree(key);
1057 err_put:
1058 	fdput(f);
1059 	return err;
1060 }
1061 
1062 #define BPF_MAP_DELETE_ELEM_LAST_FIELD key
1063 
1064 static int map_delete_elem(union bpf_attr *attr)
1065 {
1066 	void __user *ukey = u64_to_user_ptr(attr->key);
1067 	int ufd = attr->map_fd;
1068 	struct bpf_map *map;
1069 	struct fd f;
1070 	void *key;
1071 	int err;
1072 
1073 	if (CHECK_ATTR(BPF_MAP_DELETE_ELEM))
1074 		return -EINVAL;
1075 
1076 	f = fdget(ufd);
1077 	map = __bpf_map_get(f);
1078 	if (IS_ERR(map))
1079 		return PTR_ERR(map);
1080 	if (!(map_get_sys_perms(map, f) & FMODE_CAN_WRITE)) {
1081 		err = -EPERM;
1082 		goto err_put;
1083 	}
1084 
1085 	key = __bpf_copy_key(ukey, map->key_size);
1086 	if (IS_ERR(key)) {
1087 		err = PTR_ERR(key);
1088 		goto err_put;
1089 	}
1090 
1091 	if (bpf_map_is_dev_bound(map)) {
1092 		err = bpf_map_offload_delete_elem(map, key);
1093 		goto out;
1094 	} else if (IS_FD_PROG_ARRAY(map)) {
1095 		err = map->ops->map_delete_elem(map, key);
1096 		goto out;
1097 	}
1098 
1099 	preempt_disable();
1100 	__this_cpu_inc(bpf_prog_active);
1101 	rcu_read_lock();
1102 	err = map->ops->map_delete_elem(map, key);
1103 	rcu_read_unlock();
1104 	__this_cpu_dec(bpf_prog_active);
1105 	preempt_enable();
1106 	maybe_wait_bpf_programs(map);
1107 out:
1108 	kfree(key);
1109 err_put:
1110 	fdput(f);
1111 	return err;
1112 }
1113 
1114 /* last field in 'union bpf_attr' used by this command */
1115 #define BPF_MAP_GET_NEXT_KEY_LAST_FIELD next_key
1116 
1117 static int map_get_next_key(union bpf_attr *attr)
1118 {
1119 	void __user *ukey = u64_to_user_ptr(attr->key);
1120 	void __user *unext_key = u64_to_user_ptr(attr->next_key);
1121 	int ufd = attr->map_fd;
1122 	struct bpf_map *map;
1123 	void *key, *next_key;
1124 	struct fd f;
1125 	int err;
1126 
1127 	if (CHECK_ATTR(BPF_MAP_GET_NEXT_KEY))
1128 		return -EINVAL;
1129 
1130 	f = fdget(ufd);
1131 	map = __bpf_map_get(f);
1132 	if (IS_ERR(map))
1133 		return PTR_ERR(map);
1134 	if (!(map_get_sys_perms(map, f) & FMODE_CAN_READ)) {
1135 		err = -EPERM;
1136 		goto err_put;
1137 	}
1138 
1139 	if (ukey) {
1140 		key = __bpf_copy_key(ukey, map->key_size);
1141 		if (IS_ERR(key)) {
1142 			err = PTR_ERR(key);
1143 			goto err_put;
1144 		}
1145 	} else {
1146 		key = NULL;
1147 	}
1148 
1149 	err = -ENOMEM;
1150 	next_key = kmalloc(map->key_size, GFP_USER);
1151 	if (!next_key)
1152 		goto free_key;
1153 
1154 	if (bpf_map_is_dev_bound(map)) {
1155 		err = bpf_map_offload_get_next_key(map, key, next_key);
1156 		goto out;
1157 	}
1158 
1159 	rcu_read_lock();
1160 	err = map->ops->map_get_next_key(map, key, next_key);
1161 	rcu_read_unlock();
1162 out:
1163 	if (err)
1164 		goto free_next_key;
1165 
1166 	err = -EFAULT;
1167 	if (copy_to_user(unext_key, next_key, map->key_size) != 0)
1168 		goto free_next_key;
1169 
1170 	err = 0;
1171 
1172 free_next_key:
1173 	kfree(next_key);
1174 free_key:
1175 	kfree(key);
1176 err_put:
1177 	fdput(f);
1178 	return err;
1179 }
1180 
1181 #define BPF_MAP_LOOKUP_AND_DELETE_ELEM_LAST_FIELD value
1182 
1183 static int map_lookup_and_delete_elem(union bpf_attr *attr)
1184 {
1185 	void __user *ukey = u64_to_user_ptr(attr->key);
1186 	void __user *uvalue = u64_to_user_ptr(attr->value);
1187 	int ufd = attr->map_fd;
1188 	struct bpf_map *map;
1189 	void *key, *value;
1190 	u32 value_size;
1191 	struct fd f;
1192 	int err;
1193 
1194 	if (CHECK_ATTR(BPF_MAP_LOOKUP_AND_DELETE_ELEM))
1195 		return -EINVAL;
1196 
1197 	f = fdget(ufd);
1198 	map = __bpf_map_get(f);
1199 	if (IS_ERR(map))
1200 		return PTR_ERR(map);
1201 	if (!(map_get_sys_perms(map, f) & FMODE_CAN_WRITE)) {
1202 		err = -EPERM;
1203 		goto err_put;
1204 	}
1205 
1206 	key = __bpf_copy_key(ukey, map->key_size);
1207 	if (IS_ERR(key)) {
1208 		err = PTR_ERR(key);
1209 		goto err_put;
1210 	}
1211 
1212 	value_size = map->value_size;
1213 
1214 	err = -ENOMEM;
1215 	value = kmalloc(value_size, GFP_USER | __GFP_NOWARN);
1216 	if (!value)
1217 		goto free_key;
1218 
1219 	if (map->map_type == BPF_MAP_TYPE_QUEUE ||
1220 	    map->map_type == BPF_MAP_TYPE_STACK) {
1221 		err = map->ops->map_pop_elem(map, value);
1222 	} else {
1223 		err = -ENOTSUPP;
1224 	}
1225 
1226 	if (err)
1227 		goto free_value;
1228 
1229 	if (copy_to_user(uvalue, value, value_size) != 0)
1230 		goto free_value;
1231 
1232 	err = 0;
1233 
1234 free_value:
1235 	kfree(value);
1236 free_key:
1237 	kfree(key);
1238 err_put:
1239 	fdput(f);
1240 	return err;
1241 }
1242 
1243 #define BPF_MAP_FREEZE_LAST_FIELD map_fd
1244 
1245 static int map_freeze(const union bpf_attr *attr)
1246 {
1247 	int err = 0, ufd = attr->map_fd;
1248 	struct bpf_map *map;
1249 	struct fd f;
1250 
1251 	if (CHECK_ATTR(BPF_MAP_FREEZE))
1252 		return -EINVAL;
1253 
1254 	f = fdget(ufd);
1255 	map = __bpf_map_get(f);
1256 	if (IS_ERR(map))
1257 		return PTR_ERR(map);
1258 
1259 	mutex_lock(&map->freeze_mutex);
1260 
1261 	if (map->writecnt) {
1262 		err = -EBUSY;
1263 		goto err_put;
1264 	}
1265 	if (READ_ONCE(map->frozen)) {
1266 		err = -EBUSY;
1267 		goto err_put;
1268 	}
1269 	if (!capable(CAP_SYS_ADMIN)) {
1270 		err = -EPERM;
1271 		goto err_put;
1272 	}
1273 
1274 	WRITE_ONCE(map->frozen, true);
1275 err_put:
1276 	mutex_unlock(&map->freeze_mutex);
1277 	fdput(f);
1278 	return err;
1279 }
1280 
1281 static const struct bpf_prog_ops * const bpf_prog_types[] = {
1282 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
1283 	[_id] = & _name ## _prog_ops,
1284 #define BPF_MAP_TYPE(_id, _ops)
1285 #include <linux/bpf_types.h>
1286 #undef BPF_PROG_TYPE
1287 #undef BPF_MAP_TYPE
1288 };
1289 
1290 static int find_prog_type(enum bpf_prog_type type, struct bpf_prog *prog)
1291 {
1292 	const struct bpf_prog_ops *ops;
1293 
1294 	if (type >= ARRAY_SIZE(bpf_prog_types))
1295 		return -EINVAL;
1296 	type = array_index_nospec(type, ARRAY_SIZE(bpf_prog_types));
1297 	ops = bpf_prog_types[type];
1298 	if (!ops)
1299 		return -EINVAL;
1300 
1301 	if (!bpf_prog_is_dev_bound(prog->aux))
1302 		prog->aux->ops = ops;
1303 	else
1304 		prog->aux->ops = &bpf_offload_prog_ops;
1305 	prog->type = type;
1306 	return 0;
1307 }
1308 
1309 int __bpf_prog_charge(struct user_struct *user, u32 pages)
1310 {
1311 	unsigned long memlock_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
1312 	unsigned long user_bufs;
1313 
1314 	if (user) {
1315 		user_bufs = atomic_long_add_return(pages, &user->locked_vm);
1316 		if (user_bufs > memlock_limit) {
1317 			atomic_long_sub(pages, &user->locked_vm);
1318 			return -EPERM;
1319 		}
1320 	}
1321 
1322 	return 0;
1323 }
1324 
1325 void __bpf_prog_uncharge(struct user_struct *user, u32 pages)
1326 {
1327 	if (user)
1328 		atomic_long_sub(pages, &user->locked_vm);
1329 }
1330 
1331 static int bpf_prog_charge_memlock(struct bpf_prog *prog)
1332 {
1333 	struct user_struct *user = get_current_user();
1334 	int ret;
1335 
1336 	ret = __bpf_prog_charge(user, prog->pages);
1337 	if (ret) {
1338 		free_uid(user);
1339 		return ret;
1340 	}
1341 
1342 	prog->aux->user = user;
1343 	return 0;
1344 }
1345 
1346 static void bpf_prog_uncharge_memlock(struct bpf_prog *prog)
1347 {
1348 	struct user_struct *user = prog->aux->user;
1349 
1350 	__bpf_prog_uncharge(user, prog->pages);
1351 	free_uid(user);
1352 }
1353 
1354 static int bpf_prog_alloc_id(struct bpf_prog *prog)
1355 {
1356 	int id;
1357 
1358 	idr_preload(GFP_KERNEL);
1359 	spin_lock_bh(&prog_idr_lock);
1360 	id = idr_alloc_cyclic(&prog_idr, prog, 1, INT_MAX, GFP_ATOMIC);
1361 	if (id > 0)
1362 		prog->aux->id = id;
1363 	spin_unlock_bh(&prog_idr_lock);
1364 	idr_preload_end();
1365 
1366 	/* id is in [1, INT_MAX) */
1367 	if (WARN_ON_ONCE(!id))
1368 		return -ENOSPC;
1369 
1370 	return id > 0 ? 0 : id;
1371 }
1372 
1373 void bpf_prog_free_id(struct bpf_prog *prog, bool do_idr_lock)
1374 {
1375 	/* cBPF to eBPF migrations are currently not in the idr store.
1376 	 * Offloaded programs are removed from the store when their device
1377 	 * disappears - even if someone grabs an fd to them they are unusable,
1378 	 * simply waiting for refcnt to drop to be freed.
1379 	 */
1380 	if (!prog->aux->id)
1381 		return;
1382 
1383 	if (do_idr_lock)
1384 		spin_lock_bh(&prog_idr_lock);
1385 	else
1386 		__acquire(&prog_idr_lock);
1387 
1388 	idr_remove(&prog_idr, prog->aux->id);
1389 	prog->aux->id = 0;
1390 
1391 	if (do_idr_lock)
1392 		spin_unlock_bh(&prog_idr_lock);
1393 	else
1394 		__release(&prog_idr_lock);
1395 }
1396 
1397 static void __bpf_prog_put_rcu(struct rcu_head *rcu)
1398 {
1399 	struct bpf_prog_aux *aux = container_of(rcu, struct bpf_prog_aux, rcu);
1400 
1401 	kvfree(aux->func_info);
1402 	kfree(aux->func_info_aux);
1403 	bpf_prog_uncharge_memlock(aux->prog);
1404 	security_bpf_prog_free(aux);
1405 	bpf_prog_free(aux->prog);
1406 }
1407 
1408 static void __bpf_prog_put_noref(struct bpf_prog *prog, bool deferred)
1409 {
1410 	bpf_prog_kallsyms_del_all(prog);
1411 	btf_put(prog->aux->btf);
1412 	bpf_prog_free_linfo(prog);
1413 
1414 	if (deferred)
1415 		call_rcu(&prog->aux->rcu, __bpf_prog_put_rcu);
1416 	else
1417 		__bpf_prog_put_rcu(&prog->aux->rcu);
1418 }
1419 
1420 static void __bpf_prog_put(struct bpf_prog *prog, bool do_idr_lock)
1421 {
1422 	if (atomic64_dec_and_test(&prog->aux->refcnt)) {
1423 		perf_event_bpf_event(prog, PERF_BPF_EVENT_PROG_UNLOAD, 0);
1424 		/* bpf_prog_free_id() must be called first */
1425 		bpf_prog_free_id(prog, do_idr_lock);
1426 		__bpf_prog_put_noref(prog, true);
1427 	}
1428 }
1429 
1430 void bpf_prog_put(struct bpf_prog *prog)
1431 {
1432 	__bpf_prog_put(prog, true);
1433 }
1434 EXPORT_SYMBOL_GPL(bpf_prog_put);
1435 
1436 static int bpf_prog_release(struct inode *inode, struct file *filp)
1437 {
1438 	struct bpf_prog *prog = filp->private_data;
1439 
1440 	bpf_prog_put(prog);
1441 	return 0;
1442 }
1443 
1444 static void bpf_prog_get_stats(const struct bpf_prog *prog,
1445 			       struct bpf_prog_stats *stats)
1446 {
1447 	u64 nsecs = 0, cnt = 0;
1448 	int cpu;
1449 
1450 	for_each_possible_cpu(cpu) {
1451 		const struct bpf_prog_stats *st;
1452 		unsigned int start;
1453 		u64 tnsecs, tcnt;
1454 
1455 		st = per_cpu_ptr(prog->aux->stats, cpu);
1456 		do {
1457 			start = u64_stats_fetch_begin_irq(&st->syncp);
1458 			tnsecs = st->nsecs;
1459 			tcnt = st->cnt;
1460 		} while (u64_stats_fetch_retry_irq(&st->syncp, start));
1461 		nsecs += tnsecs;
1462 		cnt += tcnt;
1463 	}
1464 	stats->nsecs = nsecs;
1465 	stats->cnt = cnt;
1466 }
1467 
1468 #ifdef CONFIG_PROC_FS
1469 static void bpf_prog_show_fdinfo(struct seq_file *m, struct file *filp)
1470 {
1471 	const struct bpf_prog *prog = filp->private_data;
1472 	char prog_tag[sizeof(prog->tag) * 2 + 1] = { };
1473 	struct bpf_prog_stats stats;
1474 
1475 	bpf_prog_get_stats(prog, &stats);
1476 	bin2hex(prog_tag, prog->tag, sizeof(prog->tag));
1477 	seq_printf(m,
1478 		   "prog_type:\t%u\n"
1479 		   "prog_jited:\t%u\n"
1480 		   "prog_tag:\t%s\n"
1481 		   "memlock:\t%llu\n"
1482 		   "prog_id:\t%u\n"
1483 		   "run_time_ns:\t%llu\n"
1484 		   "run_cnt:\t%llu\n",
1485 		   prog->type,
1486 		   prog->jited,
1487 		   prog_tag,
1488 		   prog->pages * 1ULL << PAGE_SHIFT,
1489 		   prog->aux->id,
1490 		   stats.nsecs,
1491 		   stats.cnt);
1492 }
1493 #endif
1494 
1495 const struct file_operations bpf_prog_fops = {
1496 #ifdef CONFIG_PROC_FS
1497 	.show_fdinfo	= bpf_prog_show_fdinfo,
1498 #endif
1499 	.release	= bpf_prog_release,
1500 	.read		= bpf_dummy_read,
1501 	.write		= bpf_dummy_write,
1502 };
1503 
1504 int bpf_prog_new_fd(struct bpf_prog *prog)
1505 {
1506 	int ret;
1507 
1508 	ret = security_bpf_prog(prog);
1509 	if (ret < 0)
1510 		return ret;
1511 
1512 	return anon_inode_getfd("bpf-prog", &bpf_prog_fops, prog,
1513 				O_RDWR | O_CLOEXEC);
1514 }
1515 
1516 static struct bpf_prog *____bpf_prog_get(struct fd f)
1517 {
1518 	if (!f.file)
1519 		return ERR_PTR(-EBADF);
1520 	if (f.file->f_op != &bpf_prog_fops) {
1521 		fdput(f);
1522 		return ERR_PTR(-EINVAL);
1523 	}
1524 
1525 	return f.file->private_data;
1526 }
1527 
1528 void bpf_prog_add(struct bpf_prog *prog, int i)
1529 {
1530 	atomic64_add(i, &prog->aux->refcnt);
1531 }
1532 EXPORT_SYMBOL_GPL(bpf_prog_add);
1533 
1534 void bpf_prog_sub(struct bpf_prog *prog, int i)
1535 {
1536 	/* Only to be used for undoing previous bpf_prog_add() in some
1537 	 * error path. We still know that another entity in our call
1538 	 * path holds a reference to the program, thus atomic_sub() can
1539 	 * be safely used in such cases!
1540 	 */
1541 	WARN_ON(atomic64_sub_return(i, &prog->aux->refcnt) == 0);
1542 }
1543 EXPORT_SYMBOL_GPL(bpf_prog_sub);
1544 
1545 void bpf_prog_inc(struct bpf_prog *prog)
1546 {
1547 	atomic64_inc(&prog->aux->refcnt);
1548 }
1549 EXPORT_SYMBOL_GPL(bpf_prog_inc);
1550 
1551 /* prog_idr_lock should have been held */
1552 struct bpf_prog *bpf_prog_inc_not_zero(struct bpf_prog *prog)
1553 {
1554 	int refold;
1555 
1556 	refold = atomic64_fetch_add_unless(&prog->aux->refcnt, 1, 0);
1557 
1558 	if (!refold)
1559 		return ERR_PTR(-ENOENT);
1560 
1561 	return prog;
1562 }
1563 EXPORT_SYMBOL_GPL(bpf_prog_inc_not_zero);
1564 
1565 bool bpf_prog_get_ok(struct bpf_prog *prog,
1566 			    enum bpf_prog_type *attach_type, bool attach_drv)
1567 {
1568 	/* not an attachment, just a refcount inc, always allow */
1569 	if (!attach_type)
1570 		return true;
1571 
1572 	if (prog->type != *attach_type)
1573 		return false;
1574 	if (bpf_prog_is_dev_bound(prog->aux) && !attach_drv)
1575 		return false;
1576 
1577 	return true;
1578 }
1579 
1580 static struct bpf_prog *__bpf_prog_get(u32 ufd, enum bpf_prog_type *attach_type,
1581 				       bool attach_drv)
1582 {
1583 	struct fd f = fdget(ufd);
1584 	struct bpf_prog *prog;
1585 
1586 	prog = ____bpf_prog_get(f);
1587 	if (IS_ERR(prog))
1588 		return prog;
1589 	if (!bpf_prog_get_ok(prog, attach_type, attach_drv)) {
1590 		prog = ERR_PTR(-EINVAL);
1591 		goto out;
1592 	}
1593 
1594 	bpf_prog_inc(prog);
1595 out:
1596 	fdput(f);
1597 	return prog;
1598 }
1599 
1600 struct bpf_prog *bpf_prog_get(u32 ufd)
1601 {
1602 	return __bpf_prog_get(ufd, NULL, false);
1603 }
1604 
1605 struct bpf_prog *bpf_prog_get_type_dev(u32 ufd, enum bpf_prog_type type,
1606 				       bool attach_drv)
1607 {
1608 	return __bpf_prog_get(ufd, &type, attach_drv);
1609 }
1610 EXPORT_SYMBOL_GPL(bpf_prog_get_type_dev);
1611 
1612 /* Initially all BPF programs could be loaded w/o specifying
1613  * expected_attach_type. Later for some of them specifying expected_attach_type
1614  * at load time became required so that program could be validated properly.
1615  * Programs of types that are allowed to be loaded both w/ and w/o (for
1616  * backward compatibility) expected_attach_type, should have the default attach
1617  * type assigned to expected_attach_type for the latter case, so that it can be
1618  * validated later at attach time.
1619  *
1620  * bpf_prog_load_fixup_attach_type() sets expected_attach_type in @attr if
1621  * prog type requires it but has some attach types that have to be backward
1622  * compatible.
1623  */
1624 static void bpf_prog_load_fixup_attach_type(union bpf_attr *attr)
1625 {
1626 	switch (attr->prog_type) {
1627 	case BPF_PROG_TYPE_CGROUP_SOCK:
1628 		/* Unfortunately BPF_ATTACH_TYPE_UNSPEC enumeration doesn't
1629 		 * exist so checking for non-zero is the way to go here.
1630 		 */
1631 		if (!attr->expected_attach_type)
1632 			attr->expected_attach_type =
1633 				BPF_CGROUP_INET_SOCK_CREATE;
1634 		break;
1635 	}
1636 }
1637 
1638 static int
1639 bpf_prog_load_check_attach(enum bpf_prog_type prog_type,
1640 			   enum bpf_attach_type expected_attach_type,
1641 			   u32 btf_id, u32 prog_fd)
1642 {
1643 	switch (prog_type) {
1644 	case BPF_PROG_TYPE_TRACING:
1645 		if (btf_id > BTF_MAX_TYPE)
1646 			return -EINVAL;
1647 		break;
1648 	default:
1649 		if (btf_id || prog_fd)
1650 			return -EINVAL;
1651 		break;
1652 	}
1653 
1654 	switch (prog_type) {
1655 	case BPF_PROG_TYPE_CGROUP_SOCK:
1656 		switch (expected_attach_type) {
1657 		case BPF_CGROUP_INET_SOCK_CREATE:
1658 		case BPF_CGROUP_INET4_POST_BIND:
1659 		case BPF_CGROUP_INET6_POST_BIND:
1660 			return 0;
1661 		default:
1662 			return -EINVAL;
1663 		}
1664 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
1665 		switch (expected_attach_type) {
1666 		case BPF_CGROUP_INET4_BIND:
1667 		case BPF_CGROUP_INET6_BIND:
1668 		case BPF_CGROUP_INET4_CONNECT:
1669 		case BPF_CGROUP_INET6_CONNECT:
1670 		case BPF_CGROUP_UDP4_SENDMSG:
1671 		case BPF_CGROUP_UDP6_SENDMSG:
1672 		case BPF_CGROUP_UDP4_RECVMSG:
1673 		case BPF_CGROUP_UDP6_RECVMSG:
1674 			return 0;
1675 		default:
1676 			return -EINVAL;
1677 		}
1678 	case BPF_PROG_TYPE_CGROUP_SKB:
1679 		switch (expected_attach_type) {
1680 		case BPF_CGROUP_INET_INGRESS:
1681 		case BPF_CGROUP_INET_EGRESS:
1682 			return 0;
1683 		default:
1684 			return -EINVAL;
1685 		}
1686 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
1687 		switch (expected_attach_type) {
1688 		case BPF_CGROUP_SETSOCKOPT:
1689 		case BPF_CGROUP_GETSOCKOPT:
1690 			return 0;
1691 		default:
1692 			return -EINVAL;
1693 		}
1694 	default:
1695 		return 0;
1696 	}
1697 }
1698 
1699 /* last field in 'union bpf_attr' used by this command */
1700 #define	BPF_PROG_LOAD_LAST_FIELD attach_prog_fd
1701 
1702 static int bpf_prog_load(union bpf_attr *attr, union bpf_attr __user *uattr)
1703 {
1704 	enum bpf_prog_type type = attr->prog_type;
1705 	struct bpf_prog *prog;
1706 	int err;
1707 	char license[128];
1708 	bool is_gpl;
1709 
1710 	if (CHECK_ATTR(BPF_PROG_LOAD))
1711 		return -EINVAL;
1712 
1713 	if (attr->prog_flags & ~(BPF_F_STRICT_ALIGNMENT |
1714 				 BPF_F_ANY_ALIGNMENT |
1715 				 BPF_F_TEST_STATE_FREQ |
1716 				 BPF_F_TEST_RND_HI32))
1717 		return -EINVAL;
1718 
1719 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS) &&
1720 	    (attr->prog_flags & BPF_F_ANY_ALIGNMENT) &&
1721 	    !capable(CAP_SYS_ADMIN))
1722 		return -EPERM;
1723 
1724 	/* copy eBPF program license from user space */
1725 	if (strncpy_from_user(license, u64_to_user_ptr(attr->license),
1726 			      sizeof(license) - 1) < 0)
1727 		return -EFAULT;
1728 	license[sizeof(license) - 1] = 0;
1729 
1730 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
1731 	is_gpl = license_is_gpl_compatible(license);
1732 
1733 	if (attr->insn_cnt == 0 ||
1734 	    attr->insn_cnt > (capable(CAP_SYS_ADMIN) ? BPF_COMPLEXITY_LIMIT_INSNS : BPF_MAXINSNS))
1735 		return -E2BIG;
1736 	if (type != BPF_PROG_TYPE_SOCKET_FILTER &&
1737 	    type != BPF_PROG_TYPE_CGROUP_SKB &&
1738 	    !capable(CAP_SYS_ADMIN))
1739 		return -EPERM;
1740 
1741 	bpf_prog_load_fixup_attach_type(attr);
1742 	if (bpf_prog_load_check_attach(type, attr->expected_attach_type,
1743 				       attr->attach_btf_id,
1744 				       attr->attach_prog_fd))
1745 		return -EINVAL;
1746 
1747 	/* plain bpf_prog allocation */
1748 	prog = bpf_prog_alloc(bpf_prog_size(attr->insn_cnt), GFP_USER);
1749 	if (!prog)
1750 		return -ENOMEM;
1751 
1752 	prog->expected_attach_type = attr->expected_attach_type;
1753 	prog->aux->attach_btf_id = attr->attach_btf_id;
1754 	if (attr->attach_prog_fd) {
1755 		struct bpf_prog *tgt_prog;
1756 
1757 		tgt_prog = bpf_prog_get(attr->attach_prog_fd);
1758 		if (IS_ERR(tgt_prog)) {
1759 			err = PTR_ERR(tgt_prog);
1760 			goto free_prog_nouncharge;
1761 		}
1762 		prog->aux->linked_prog = tgt_prog;
1763 	}
1764 
1765 	prog->aux->offload_requested = !!attr->prog_ifindex;
1766 
1767 	err = security_bpf_prog_alloc(prog->aux);
1768 	if (err)
1769 		goto free_prog_nouncharge;
1770 
1771 	err = bpf_prog_charge_memlock(prog);
1772 	if (err)
1773 		goto free_prog_sec;
1774 
1775 	prog->len = attr->insn_cnt;
1776 
1777 	err = -EFAULT;
1778 	if (copy_from_user(prog->insns, u64_to_user_ptr(attr->insns),
1779 			   bpf_prog_insn_size(prog)) != 0)
1780 		goto free_prog;
1781 
1782 	prog->orig_prog = NULL;
1783 	prog->jited = 0;
1784 
1785 	atomic64_set(&prog->aux->refcnt, 1);
1786 	prog->gpl_compatible = is_gpl ? 1 : 0;
1787 
1788 	if (bpf_prog_is_dev_bound(prog->aux)) {
1789 		err = bpf_prog_offload_init(prog, attr);
1790 		if (err)
1791 			goto free_prog;
1792 	}
1793 
1794 	/* find program type: socket_filter vs tracing_filter */
1795 	err = find_prog_type(type, prog);
1796 	if (err < 0)
1797 		goto free_prog;
1798 
1799 	prog->aux->load_time = ktime_get_boottime_ns();
1800 	err = bpf_obj_name_cpy(prog->aux->name, attr->prog_name);
1801 	if (err)
1802 		goto free_prog;
1803 
1804 	/* run eBPF verifier */
1805 	err = bpf_check(&prog, attr, uattr);
1806 	if (err < 0)
1807 		goto free_used_maps;
1808 
1809 	prog = bpf_prog_select_runtime(prog, &err);
1810 	if (err < 0)
1811 		goto free_used_maps;
1812 
1813 	err = bpf_prog_alloc_id(prog);
1814 	if (err)
1815 		goto free_used_maps;
1816 
1817 	/* Upon success of bpf_prog_alloc_id(), the BPF prog is
1818 	 * effectively publicly exposed. However, retrieving via
1819 	 * bpf_prog_get_fd_by_id() will take another reference,
1820 	 * therefore it cannot be gone underneath us.
1821 	 *
1822 	 * Only for the time /after/ successful bpf_prog_new_fd()
1823 	 * and before returning to userspace, we might just hold
1824 	 * one reference and any parallel close on that fd could
1825 	 * rip everything out. Hence, below notifications must
1826 	 * happen before bpf_prog_new_fd().
1827 	 *
1828 	 * Also, any failure handling from this point onwards must
1829 	 * be using bpf_prog_put() given the program is exposed.
1830 	 */
1831 	bpf_prog_kallsyms_add(prog);
1832 	perf_event_bpf_event(prog, PERF_BPF_EVENT_PROG_LOAD, 0);
1833 
1834 	err = bpf_prog_new_fd(prog);
1835 	if (err < 0)
1836 		bpf_prog_put(prog);
1837 	return err;
1838 
1839 free_used_maps:
1840 	/* In case we have subprogs, we need to wait for a grace
1841 	 * period before we can tear down JIT memory since symbols
1842 	 * are already exposed under kallsyms.
1843 	 */
1844 	__bpf_prog_put_noref(prog, prog->aux->func_cnt);
1845 	return err;
1846 free_prog:
1847 	bpf_prog_uncharge_memlock(prog);
1848 free_prog_sec:
1849 	security_bpf_prog_free(prog->aux);
1850 free_prog_nouncharge:
1851 	bpf_prog_free(prog);
1852 	return err;
1853 }
1854 
1855 #define BPF_OBJ_LAST_FIELD file_flags
1856 
1857 static int bpf_obj_pin(const union bpf_attr *attr)
1858 {
1859 	if (CHECK_ATTR(BPF_OBJ) || attr->file_flags != 0)
1860 		return -EINVAL;
1861 
1862 	return bpf_obj_pin_user(attr->bpf_fd, u64_to_user_ptr(attr->pathname));
1863 }
1864 
1865 static int bpf_obj_get(const union bpf_attr *attr)
1866 {
1867 	if (CHECK_ATTR(BPF_OBJ) || attr->bpf_fd != 0 ||
1868 	    attr->file_flags & ~BPF_OBJ_FLAG_MASK)
1869 		return -EINVAL;
1870 
1871 	return bpf_obj_get_user(u64_to_user_ptr(attr->pathname),
1872 				attr->file_flags);
1873 }
1874 
1875 static int bpf_tracing_prog_release(struct inode *inode, struct file *filp)
1876 {
1877 	struct bpf_prog *prog = filp->private_data;
1878 
1879 	WARN_ON_ONCE(bpf_trampoline_unlink_prog(prog));
1880 	bpf_prog_put(prog);
1881 	return 0;
1882 }
1883 
1884 static const struct file_operations bpf_tracing_prog_fops = {
1885 	.release	= bpf_tracing_prog_release,
1886 	.read		= bpf_dummy_read,
1887 	.write		= bpf_dummy_write,
1888 };
1889 
1890 static int bpf_tracing_prog_attach(struct bpf_prog *prog)
1891 {
1892 	int tr_fd, err;
1893 
1894 	if (prog->expected_attach_type != BPF_TRACE_FENTRY &&
1895 	    prog->expected_attach_type != BPF_TRACE_FEXIT) {
1896 		err = -EINVAL;
1897 		goto out_put_prog;
1898 	}
1899 
1900 	err = bpf_trampoline_link_prog(prog);
1901 	if (err)
1902 		goto out_put_prog;
1903 
1904 	tr_fd = anon_inode_getfd("bpf-tracing-prog", &bpf_tracing_prog_fops,
1905 				 prog, O_CLOEXEC);
1906 	if (tr_fd < 0) {
1907 		WARN_ON_ONCE(bpf_trampoline_unlink_prog(prog));
1908 		err = tr_fd;
1909 		goto out_put_prog;
1910 	}
1911 	return tr_fd;
1912 
1913 out_put_prog:
1914 	bpf_prog_put(prog);
1915 	return err;
1916 }
1917 
1918 struct bpf_raw_tracepoint {
1919 	struct bpf_raw_event_map *btp;
1920 	struct bpf_prog *prog;
1921 };
1922 
1923 static int bpf_raw_tracepoint_release(struct inode *inode, struct file *filp)
1924 {
1925 	struct bpf_raw_tracepoint *raw_tp = filp->private_data;
1926 
1927 	if (raw_tp->prog) {
1928 		bpf_probe_unregister(raw_tp->btp, raw_tp->prog);
1929 		bpf_prog_put(raw_tp->prog);
1930 	}
1931 	bpf_put_raw_tracepoint(raw_tp->btp);
1932 	kfree(raw_tp);
1933 	return 0;
1934 }
1935 
1936 static const struct file_operations bpf_raw_tp_fops = {
1937 	.release	= bpf_raw_tracepoint_release,
1938 	.read		= bpf_dummy_read,
1939 	.write		= bpf_dummy_write,
1940 };
1941 
1942 #define BPF_RAW_TRACEPOINT_OPEN_LAST_FIELD raw_tracepoint.prog_fd
1943 
1944 static int bpf_raw_tracepoint_open(const union bpf_attr *attr)
1945 {
1946 	struct bpf_raw_tracepoint *raw_tp;
1947 	struct bpf_raw_event_map *btp;
1948 	struct bpf_prog *prog;
1949 	const char *tp_name;
1950 	char buf[128];
1951 	int tp_fd, err;
1952 
1953 	if (CHECK_ATTR(BPF_RAW_TRACEPOINT_OPEN))
1954 		return -EINVAL;
1955 
1956 	prog = bpf_prog_get(attr->raw_tracepoint.prog_fd);
1957 	if (IS_ERR(prog))
1958 		return PTR_ERR(prog);
1959 
1960 	if (prog->type != BPF_PROG_TYPE_RAW_TRACEPOINT &&
1961 	    prog->type != BPF_PROG_TYPE_TRACING &&
1962 	    prog->type != BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE) {
1963 		err = -EINVAL;
1964 		goto out_put_prog;
1965 	}
1966 
1967 	if (prog->type == BPF_PROG_TYPE_TRACING) {
1968 		if (attr->raw_tracepoint.name) {
1969 			/* The attach point for this category of programs
1970 			 * should be specified via btf_id during program load.
1971 			 */
1972 			err = -EINVAL;
1973 			goto out_put_prog;
1974 		}
1975 		if (prog->expected_attach_type == BPF_TRACE_RAW_TP)
1976 			tp_name = prog->aux->attach_func_name;
1977 		else
1978 			return bpf_tracing_prog_attach(prog);
1979 	} else {
1980 		if (strncpy_from_user(buf,
1981 				      u64_to_user_ptr(attr->raw_tracepoint.name),
1982 				      sizeof(buf) - 1) < 0) {
1983 			err = -EFAULT;
1984 			goto out_put_prog;
1985 		}
1986 		buf[sizeof(buf) - 1] = 0;
1987 		tp_name = buf;
1988 	}
1989 
1990 	btp = bpf_get_raw_tracepoint(tp_name);
1991 	if (!btp) {
1992 		err = -ENOENT;
1993 		goto out_put_prog;
1994 	}
1995 
1996 	raw_tp = kzalloc(sizeof(*raw_tp), GFP_USER);
1997 	if (!raw_tp) {
1998 		err = -ENOMEM;
1999 		goto out_put_btp;
2000 	}
2001 	raw_tp->btp = btp;
2002 	raw_tp->prog = prog;
2003 
2004 	err = bpf_probe_register(raw_tp->btp, prog);
2005 	if (err)
2006 		goto out_free_tp;
2007 
2008 	tp_fd = anon_inode_getfd("bpf-raw-tracepoint", &bpf_raw_tp_fops, raw_tp,
2009 				 O_CLOEXEC);
2010 	if (tp_fd < 0) {
2011 		bpf_probe_unregister(raw_tp->btp, prog);
2012 		err = tp_fd;
2013 		goto out_free_tp;
2014 	}
2015 	return tp_fd;
2016 
2017 out_free_tp:
2018 	kfree(raw_tp);
2019 out_put_btp:
2020 	bpf_put_raw_tracepoint(btp);
2021 out_put_prog:
2022 	bpf_prog_put(prog);
2023 	return err;
2024 }
2025 
2026 static int bpf_prog_attach_check_attach_type(const struct bpf_prog *prog,
2027 					     enum bpf_attach_type attach_type)
2028 {
2029 	switch (prog->type) {
2030 	case BPF_PROG_TYPE_CGROUP_SOCK:
2031 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
2032 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
2033 		return attach_type == prog->expected_attach_type ? 0 : -EINVAL;
2034 	case BPF_PROG_TYPE_CGROUP_SKB:
2035 		return prog->enforce_expected_attach_type &&
2036 			prog->expected_attach_type != attach_type ?
2037 			-EINVAL : 0;
2038 	default:
2039 		return 0;
2040 	}
2041 }
2042 
2043 #define BPF_PROG_ATTACH_LAST_FIELD attach_flags
2044 
2045 #define BPF_F_ATTACH_MASK \
2046 	(BPF_F_ALLOW_OVERRIDE | BPF_F_ALLOW_MULTI)
2047 
2048 static int bpf_prog_attach(const union bpf_attr *attr)
2049 {
2050 	enum bpf_prog_type ptype;
2051 	struct bpf_prog *prog;
2052 	int ret;
2053 
2054 	if (!capable(CAP_NET_ADMIN))
2055 		return -EPERM;
2056 
2057 	if (CHECK_ATTR(BPF_PROG_ATTACH))
2058 		return -EINVAL;
2059 
2060 	if (attr->attach_flags & ~BPF_F_ATTACH_MASK)
2061 		return -EINVAL;
2062 
2063 	switch (attr->attach_type) {
2064 	case BPF_CGROUP_INET_INGRESS:
2065 	case BPF_CGROUP_INET_EGRESS:
2066 		ptype = BPF_PROG_TYPE_CGROUP_SKB;
2067 		break;
2068 	case BPF_CGROUP_INET_SOCK_CREATE:
2069 	case BPF_CGROUP_INET4_POST_BIND:
2070 	case BPF_CGROUP_INET6_POST_BIND:
2071 		ptype = BPF_PROG_TYPE_CGROUP_SOCK;
2072 		break;
2073 	case BPF_CGROUP_INET4_BIND:
2074 	case BPF_CGROUP_INET6_BIND:
2075 	case BPF_CGROUP_INET4_CONNECT:
2076 	case BPF_CGROUP_INET6_CONNECT:
2077 	case BPF_CGROUP_UDP4_SENDMSG:
2078 	case BPF_CGROUP_UDP6_SENDMSG:
2079 	case BPF_CGROUP_UDP4_RECVMSG:
2080 	case BPF_CGROUP_UDP6_RECVMSG:
2081 		ptype = BPF_PROG_TYPE_CGROUP_SOCK_ADDR;
2082 		break;
2083 	case BPF_CGROUP_SOCK_OPS:
2084 		ptype = BPF_PROG_TYPE_SOCK_OPS;
2085 		break;
2086 	case BPF_CGROUP_DEVICE:
2087 		ptype = BPF_PROG_TYPE_CGROUP_DEVICE;
2088 		break;
2089 	case BPF_SK_MSG_VERDICT:
2090 		ptype = BPF_PROG_TYPE_SK_MSG;
2091 		break;
2092 	case BPF_SK_SKB_STREAM_PARSER:
2093 	case BPF_SK_SKB_STREAM_VERDICT:
2094 		ptype = BPF_PROG_TYPE_SK_SKB;
2095 		break;
2096 	case BPF_LIRC_MODE2:
2097 		ptype = BPF_PROG_TYPE_LIRC_MODE2;
2098 		break;
2099 	case BPF_FLOW_DISSECTOR:
2100 		ptype = BPF_PROG_TYPE_FLOW_DISSECTOR;
2101 		break;
2102 	case BPF_CGROUP_SYSCTL:
2103 		ptype = BPF_PROG_TYPE_CGROUP_SYSCTL;
2104 		break;
2105 	case BPF_CGROUP_GETSOCKOPT:
2106 	case BPF_CGROUP_SETSOCKOPT:
2107 		ptype = BPF_PROG_TYPE_CGROUP_SOCKOPT;
2108 		break;
2109 	default:
2110 		return -EINVAL;
2111 	}
2112 
2113 	prog = bpf_prog_get_type(attr->attach_bpf_fd, ptype);
2114 	if (IS_ERR(prog))
2115 		return PTR_ERR(prog);
2116 
2117 	if (bpf_prog_attach_check_attach_type(prog, attr->attach_type)) {
2118 		bpf_prog_put(prog);
2119 		return -EINVAL;
2120 	}
2121 
2122 	switch (ptype) {
2123 	case BPF_PROG_TYPE_SK_SKB:
2124 	case BPF_PROG_TYPE_SK_MSG:
2125 		ret = sock_map_get_from_fd(attr, prog);
2126 		break;
2127 	case BPF_PROG_TYPE_LIRC_MODE2:
2128 		ret = lirc_prog_attach(attr, prog);
2129 		break;
2130 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
2131 		ret = skb_flow_dissector_bpf_prog_attach(attr, prog);
2132 		break;
2133 	default:
2134 		ret = cgroup_bpf_prog_attach(attr, ptype, prog);
2135 	}
2136 
2137 	if (ret)
2138 		bpf_prog_put(prog);
2139 	return ret;
2140 }
2141 
2142 #define BPF_PROG_DETACH_LAST_FIELD attach_type
2143 
2144 static int bpf_prog_detach(const union bpf_attr *attr)
2145 {
2146 	enum bpf_prog_type ptype;
2147 
2148 	if (!capable(CAP_NET_ADMIN))
2149 		return -EPERM;
2150 
2151 	if (CHECK_ATTR(BPF_PROG_DETACH))
2152 		return -EINVAL;
2153 
2154 	switch (attr->attach_type) {
2155 	case BPF_CGROUP_INET_INGRESS:
2156 	case BPF_CGROUP_INET_EGRESS:
2157 		ptype = BPF_PROG_TYPE_CGROUP_SKB;
2158 		break;
2159 	case BPF_CGROUP_INET_SOCK_CREATE:
2160 	case BPF_CGROUP_INET4_POST_BIND:
2161 	case BPF_CGROUP_INET6_POST_BIND:
2162 		ptype = BPF_PROG_TYPE_CGROUP_SOCK;
2163 		break;
2164 	case BPF_CGROUP_INET4_BIND:
2165 	case BPF_CGROUP_INET6_BIND:
2166 	case BPF_CGROUP_INET4_CONNECT:
2167 	case BPF_CGROUP_INET6_CONNECT:
2168 	case BPF_CGROUP_UDP4_SENDMSG:
2169 	case BPF_CGROUP_UDP6_SENDMSG:
2170 	case BPF_CGROUP_UDP4_RECVMSG:
2171 	case BPF_CGROUP_UDP6_RECVMSG:
2172 		ptype = BPF_PROG_TYPE_CGROUP_SOCK_ADDR;
2173 		break;
2174 	case BPF_CGROUP_SOCK_OPS:
2175 		ptype = BPF_PROG_TYPE_SOCK_OPS;
2176 		break;
2177 	case BPF_CGROUP_DEVICE:
2178 		ptype = BPF_PROG_TYPE_CGROUP_DEVICE;
2179 		break;
2180 	case BPF_SK_MSG_VERDICT:
2181 		return sock_map_get_from_fd(attr, NULL);
2182 	case BPF_SK_SKB_STREAM_PARSER:
2183 	case BPF_SK_SKB_STREAM_VERDICT:
2184 		return sock_map_get_from_fd(attr, NULL);
2185 	case BPF_LIRC_MODE2:
2186 		return lirc_prog_detach(attr);
2187 	case BPF_FLOW_DISSECTOR:
2188 		return skb_flow_dissector_bpf_prog_detach(attr);
2189 	case BPF_CGROUP_SYSCTL:
2190 		ptype = BPF_PROG_TYPE_CGROUP_SYSCTL;
2191 		break;
2192 	case BPF_CGROUP_GETSOCKOPT:
2193 	case BPF_CGROUP_SETSOCKOPT:
2194 		ptype = BPF_PROG_TYPE_CGROUP_SOCKOPT;
2195 		break;
2196 	default:
2197 		return -EINVAL;
2198 	}
2199 
2200 	return cgroup_bpf_prog_detach(attr, ptype);
2201 }
2202 
2203 #define BPF_PROG_QUERY_LAST_FIELD query.prog_cnt
2204 
2205 static int bpf_prog_query(const union bpf_attr *attr,
2206 			  union bpf_attr __user *uattr)
2207 {
2208 	if (!capable(CAP_NET_ADMIN))
2209 		return -EPERM;
2210 	if (CHECK_ATTR(BPF_PROG_QUERY))
2211 		return -EINVAL;
2212 	if (attr->query.query_flags & ~BPF_F_QUERY_EFFECTIVE)
2213 		return -EINVAL;
2214 
2215 	switch (attr->query.attach_type) {
2216 	case BPF_CGROUP_INET_INGRESS:
2217 	case BPF_CGROUP_INET_EGRESS:
2218 	case BPF_CGROUP_INET_SOCK_CREATE:
2219 	case BPF_CGROUP_INET4_BIND:
2220 	case BPF_CGROUP_INET6_BIND:
2221 	case BPF_CGROUP_INET4_POST_BIND:
2222 	case BPF_CGROUP_INET6_POST_BIND:
2223 	case BPF_CGROUP_INET4_CONNECT:
2224 	case BPF_CGROUP_INET6_CONNECT:
2225 	case BPF_CGROUP_UDP4_SENDMSG:
2226 	case BPF_CGROUP_UDP6_SENDMSG:
2227 	case BPF_CGROUP_UDP4_RECVMSG:
2228 	case BPF_CGROUP_UDP6_RECVMSG:
2229 	case BPF_CGROUP_SOCK_OPS:
2230 	case BPF_CGROUP_DEVICE:
2231 	case BPF_CGROUP_SYSCTL:
2232 	case BPF_CGROUP_GETSOCKOPT:
2233 	case BPF_CGROUP_SETSOCKOPT:
2234 		break;
2235 	case BPF_LIRC_MODE2:
2236 		return lirc_prog_query(attr, uattr);
2237 	case BPF_FLOW_DISSECTOR:
2238 		return skb_flow_dissector_prog_query(attr, uattr);
2239 	default:
2240 		return -EINVAL;
2241 	}
2242 
2243 	return cgroup_bpf_prog_query(attr, uattr);
2244 }
2245 
2246 #define BPF_PROG_TEST_RUN_LAST_FIELD test.ctx_out
2247 
2248 static int bpf_prog_test_run(const union bpf_attr *attr,
2249 			     union bpf_attr __user *uattr)
2250 {
2251 	struct bpf_prog *prog;
2252 	int ret = -ENOTSUPP;
2253 
2254 	if (!capable(CAP_SYS_ADMIN))
2255 		return -EPERM;
2256 	if (CHECK_ATTR(BPF_PROG_TEST_RUN))
2257 		return -EINVAL;
2258 
2259 	if ((attr->test.ctx_size_in && !attr->test.ctx_in) ||
2260 	    (!attr->test.ctx_size_in && attr->test.ctx_in))
2261 		return -EINVAL;
2262 
2263 	if ((attr->test.ctx_size_out && !attr->test.ctx_out) ||
2264 	    (!attr->test.ctx_size_out && attr->test.ctx_out))
2265 		return -EINVAL;
2266 
2267 	prog = bpf_prog_get(attr->test.prog_fd);
2268 	if (IS_ERR(prog))
2269 		return PTR_ERR(prog);
2270 
2271 	if (prog->aux->ops->test_run)
2272 		ret = prog->aux->ops->test_run(prog, attr, uattr);
2273 
2274 	bpf_prog_put(prog);
2275 	return ret;
2276 }
2277 
2278 #define BPF_OBJ_GET_NEXT_ID_LAST_FIELD next_id
2279 
2280 static int bpf_obj_get_next_id(const union bpf_attr *attr,
2281 			       union bpf_attr __user *uattr,
2282 			       struct idr *idr,
2283 			       spinlock_t *lock)
2284 {
2285 	u32 next_id = attr->start_id;
2286 	int err = 0;
2287 
2288 	if (CHECK_ATTR(BPF_OBJ_GET_NEXT_ID) || next_id >= INT_MAX)
2289 		return -EINVAL;
2290 
2291 	if (!capable(CAP_SYS_ADMIN))
2292 		return -EPERM;
2293 
2294 	next_id++;
2295 	spin_lock_bh(lock);
2296 	if (!idr_get_next(idr, &next_id))
2297 		err = -ENOENT;
2298 	spin_unlock_bh(lock);
2299 
2300 	if (!err)
2301 		err = put_user(next_id, &uattr->next_id);
2302 
2303 	return err;
2304 }
2305 
2306 #define BPF_PROG_GET_FD_BY_ID_LAST_FIELD prog_id
2307 
2308 static int bpf_prog_get_fd_by_id(const union bpf_attr *attr)
2309 {
2310 	struct bpf_prog *prog;
2311 	u32 id = attr->prog_id;
2312 	int fd;
2313 
2314 	if (CHECK_ATTR(BPF_PROG_GET_FD_BY_ID))
2315 		return -EINVAL;
2316 
2317 	if (!capable(CAP_SYS_ADMIN))
2318 		return -EPERM;
2319 
2320 	spin_lock_bh(&prog_idr_lock);
2321 	prog = idr_find(&prog_idr, id);
2322 	if (prog)
2323 		prog = bpf_prog_inc_not_zero(prog);
2324 	else
2325 		prog = ERR_PTR(-ENOENT);
2326 	spin_unlock_bh(&prog_idr_lock);
2327 
2328 	if (IS_ERR(prog))
2329 		return PTR_ERR(prog);
2330 
2331 	fd = bpf_prog_new_fd(prog);
2332 	if (fd < 0)
2333 		bpf_prog_put(prog);
2334 
2335 	return fd;
2336 }
2337 
2338 #define BPF_MAP_GET_FD_BY_ID_LAST_FIELD open_flags
2339 
2340 static int bpf_map_get_fd_by_id(const union bpf_attr *attr)
2341 {
2342 	struct bpf_map *map;
2343 	u32 id = attr->map_id;
2344 	int f_flags;
2345 	int fd;
2346 
2347 	if (CHECK_ATTR(BPF_MAP_GET_FD_BY_ID) ||
2348 	    attr->open_flags & ~BPF_OBJ_FLAG_MASK)
2349 		return -EINVAL;
2350 
2351 	if (!capable(CAP_SYS_ADMIN))
2352 		return -EPERM;
2353 
2354 	f_flags = bpf_get_file_flag(attr->open_flags);
2355 	if (f_flags < 0)
2356 		return f_flags;
2357 
2358 	spin_lock_bh(&map_idr_lock);
2359 	map = idr_find(&map_idr, id);
2360 	if (map)
2361 		map = __bpf_map_inc_not_zero(map, true);
2362 	else
2363 		map = ERR_PTR(-ENOENT);
2364 	spin_unlock_bh(&map_idr_lock);
2365 
2366 	if (IS_ERR(map))
2367 		return PTR_ERR(map);
2368 
2369 	fd = bpf_map_new_fd(map, f_flags);
2370 	if (fd < 0)
2371 		bpf_map_put_with_uref(map);
2372 
2373 	return fd;
2374 }
2375 
2376 static const struct bpf_map *bpf_map_from_imm(const struct bpf_prog *prog,
2377 					      unsigned long addr, u32 *off,
2378 					      u32 *type)
2379 {
2380 	const struct bpf_map *map;
2381 	int i;
2382 
2383 	for (i = 0, *off = 0; i < prog->aux->used_map_cnt; i++) {
2384 		map = prog->aux->used_maps[i];
2385 		if (map == (void *)addr) {
2386 			*type = BPF_PSEUDO_MAP_FD;
2387 			return map;
2388 		}
2389 		if (!map->ops->map_direct_value_meta)
2390 			continue;
2391 		if (!map->ops->map_direct_value_meta(map, addr, off)) {
2392 			*type = BPF_PSEUDO_MAP_VALUE;
2393 			return map;
2394 		}
2395 	}
2396 
2397 	return NULL;
2398 }
2399 
2400 static struct bpf_insn *bpf_insn_prepare_dump(const struct bpf_prog *prog)
2401 {
2402 	const struct bpf_map *map;
2403 	struct bpf_insn *insns;
2404 	u32 off, type;
2405 	u64 imm;
2406 	int i;
2407 
2408 	insns = kmemdup(prog->insnsi, bpf_prog_insn_size(prog),
2409 			GFP_USER);
2410 	if (!insns)
2411 		return insns;
2412 
2413 	for (i = 0; i < prog->len; i++) {
2414 		if (insns[i].code == (BPF_JMP | BPF_TAIL_CALL)) {
2415 			insns[i].code = BPF_JMP | BPF_CALL;
2416 			insns[i].imm = BPF_FUNC_tail_call;
2417 			/* fall-through */
2418 		}
2419 		if (insns[i].code == (BPF_JMP | BPF_CALL) ||
2420 		    insns[i].code == (BPF_JMP | BPF_CALL_ARGS)) {
2421 			if (insns[i].code == (BPF_JMP | BPF_CALL_ARGS))
2422 				insns[i].code = BPF_JMP | BPF_CALL;
2423 			if (!bpf_dump_raw_ok())
2424 				insns[i].imm = 0;
2425 			continue;
2426 		}
2427 
2428 		if (insns[i].code != (BPF_LD | BPF_IMM | BPF_DW))
2429 			continue;
2430 
2431 		imm = ((u64)insns[i + 1].imm << 32) | (u32)insns[i].imm;
2432 		map = bpf_map_from_imm(prog, imm, &off, &type);
2433 		if (map) {
2434 			insns[i].src_reg = type;
2435 			insns[i].imm = map->id;
2436 			insns[i + 1].imm = off;
2437 			continue;
2438 		}
2439 	}
2440 
2441 	return insns;
2442 }
2443 
2444 static int set_info_rec_size(struct bpf_prog_info *info)
2445 {
2446 	/*
2447 	 * Ensure info.*_rec_size is the same as kernel expected size
2448 	 *
2449 	 * or
2450 	 *
2451 	 * Only allow zero *_rec_size if both _rec_size and _cnt are
2452 	 * zero.  In this case, the kernel will set the expected
2453 	 * _rec_size back to the info.
2454 	 */
2455 
2456 	if ((info->nr_func_info || info->func_info_rec_size) &&
2457 	    info->func_info_rec_size != sizeof(struct bpf_func_info))
2458 		return -EINVAL;
2459 
2460 	if ((info->nr_line_info || info->line_info_rec_size) &&
2461 	    info->line_info_rec_size != sizeof(struct bpf_line_info))
2462 		return -EINVAL;
2463 
2464 	if ((info->nr_jited_line_info || info->jited_line_info_rec_size) &&
2465 	    info->jited_line_info_rec_size != sizeof(__u64))
2466 		return -EINVAL;
2467 
2468 	info->func_info_rec_size = sizeof(struct bpf_func_info);
2469 	info->line_info_rec_size = sizeof(struct bpf_line_info);
2470 	info->jited_line_info_rec_size = sizeof(__u64);
2471 
2472 	return 0;
2473 }
2474 
2475 static int bpf_prog_get_info_by_fd(struct bpf_prog *prog,
2476 				   const union bpf_attr *attr,
2477 				   union bpf_attr __user *uattr)
2478 {
2479 	struct bpf_prog_info __user *uinfo = u64_to_user_ptr(attr->info.info);
2480 	struct bpf_prog_info info = {};
2481 	u32 info_len = attr->info.info_len;
2482 	struct bpf_prog_stats stats;
2483 	char __user *uinsns;
2484 	u32 ulen;
2485 	int err;
2486 
2487 	err = bpf_check_uarg_tail_zero(uinfo, sizeof(info), info_len);
2488 	if (err)
2489 		return err;
2490 	info_len = min_t(u32, sizeof(info), info_len);
2491 
2492 	if (copy_from_user(&info, uinfo, info_len))
2493 		return -EFAULT;
2494 
2495 	info.type = prog->type;
2496 	info.id = prog->aux->id;
2497 	info.load_time = prog->aux->load_time;
2498 	info.created_by_uid = from_kuid_munged(current_user_ns(),
2499 					       prog->aux->user->uid);
2500 	info.gpl_compatible = prog->gpl_compatible;
2501 
2502 	memcpy(info.tag, prog->tag, sizeof(prog->tag));
2503 	memcpy(info.name, prog->aux->name, sizeof(prog->aux->name));
2504 
2505 	ulen = info.nr_map_ids;
2506 	info.nr_map_ids = prog->aux->used_map_cnt;
2507 	ulen = min_t(u32, info.nr_map_ids, ulen);
2508 	if (ulen) {
2509 		u32 __user *user_map_ids = u64_to_user_ptr(info.map_ids);
2510 		u32 i;
2511 
2512 		for (i = 0; i < ulen; i++)
2513 			if (put_user(prog->aux->used_maps[i]->id,
2514 				     &user_map_ids[i]))
2515 				return -EFAULT;
2516 	}
2517 
2518 	err = set_info_rec_size(&info);
2519 	if (err)
2520 		return err;
2521 
2522 	bpf_prog_get_stats(prog, &stats);
2523 	info.run_time_ns = stats.nsecs;
2524 	info.run_cnt = stats.cnt;
2525 
2526 	if (!capable(CAP_SYS_ADMIN)) {
2527 		info.jited_prog_len = 0;
2528 		info.xlated_prog_len = 0;
2529 		info.nr_jited_ksyms = 0;
2530 		info.nr_jited_func_lens = 0;
2531 		info.nr_func_info = 0;
2532 		info.nr_line_info = 0;
2533 		info.nr_jited_line_info = 0;
2534 		goto done;
2535 	}
2536 
2537 	ulen = info.xlated_prog_len;
2538 	info.xlated_prog_len = bpf_prog_insn_size(prog);
2539 	if (info.xlated_prog_len && ulen) {
2540 		struct bpf_insn *insns_sanitized;
2541 		bool fault;
2542 
2543 		if (prog->blinded && !bpf_dump_raw_ok()) {
2544 			info.xlated_prog_insns = 0;
2545 			goto done;
2546 		}
2547 		insns_sanitized = bpf_insn_prepare_dump(prog);
2548 		if (!insns_sanitized)
2549 			return -ENOMEM;
2550 		uinsns = u64_to_user_ptr(info.xlated_prog_insns);
2551 		ulen = min_t(u32, info.xlated_prog_len, ulen);
2552 		fault = copy_to_user(uinsns, insns_sanitized, ulen);
2553 		kfree(insns_sanitized);
2554 		if (fault)
2555 			return -EFAULT;
2556 	}
2557 
2558 	if (bpf_prog_is_dev_bound(prog->aux)) {
2559 		err = bpf_prog_offload_info_fill(&info, prog);
2560 		if (err)
2561 			return err;
2562 		goto done;
2563 	}
2564 
2565 	/* NOTE: the following code is supposed to be skipped for offload.
2566 	 * bpf_prog_offload_info_fill() is the place to fill similar fields
2567 	 * for offload.
2568 	 */
2569 	ulen = info.jited_prog_len;
2570 	if (prog->aux->func_cnt) {
2571 		u32 i;
2572 
2573 		info.jited_prog_len = 0;
2574 		for (i = 0; i < prog->aux->func_cnt; i++)
2575 			info.jited_prog_len += prog->aux->func[i]->jited_len;
2576 	} else {
2577 		info.jited_prog_len = prog->jited_len;
2578 	}
2579 
2580 	if (info.jited_prog_len && ulen) {
2581 		if (bpf_dump_raw_ok()) {
2582 			uinsns = u64_to_user_ptr(info.jited_prog_insns);
2583 			ulen = min_t(u32, info.jited_prog_len, ulen);
2584 
2585 			/* for multi-function programs, copy the JITed
2586 			 * instructions for all the functions
2587 			 */
2588 			if (prog->aux->func_cnt) {
2589 				u32 len, free, i;
2590 				u8 *img;
2591 
2592 				free = ulen;
2593 				for (i = 0; i < prog->aux->func_cnt; i++) {
2594 					len = prog->aux->func[i]->jited_len;
2595 					len = min_t(u32, len, free);
2596 					img = (u8 *) prog->aux->func[i]->bpf_func;
2597 					if (copy_to_user(uinsns, img, len))
2598 						return -EFAULT;
2599 					uinsns += len;
2600 					free -= len;
2601 					if (!free)
2602 						break;
2603 				}
2604 			} else {
2605 				if (copy_to_user(uinsns, prog->bpf_func, ulen))
2606 					return -EFAULT;
2607 			}
2608 		} else {
2609 			info.jited_prog_insns = 0;
2610 		}
2611 	}
2612 
2613 	ulen = info.nr_jited_ksyms;
2614 	info.nr_jited_ksyms = prog->aux->func_cnt ? : 1;
2615 	if (ulen) {
2616 		if (bpf_dump_raw_ok()) {
2617 			unsigned long ksym_addr;
2618 			u64 __user *user_ksyms;
2619 			u32 i;
2620 
2621 			/* copy the address of the kernel symbol
2622 			 * corresponding to each function
2623 			 */
2624 			ulen = min_t(u32, info.nr_jited_ksyms, ulen);
2625 			user_ksyms = u64_to_user_ptr(info.jited_ksyms);
2626 			if (prog->aux->func_cnt) {
2627 				for (i = 0; i < ulen; i++) {
2628 					ksym_addr = (unsigned long)
2629 						prog->aux->func[i]->bpf_func;
2630 					if (put_user((u64) ksym_addr,
2631 						     &user_ksyms[i]))
2632 						return -EFAULT;
2633 				}
2634 			} else {
2635 				ksym_addr = (unsigned long) prog->bpf_func;
2636 				if (put_user((u64) ksym_addr, &user_ksyms[0]))
2637 					return -EFAULT;
2638 			}
2639 		} else {
2640 			info.jited_ksyms = 0;
2641 		}
2642 	}
2643 
2644 	ulen = info.nr_jited_func_lens;
2645 	info.nr_jited_func_lens = prog->aux->func_cnt ? : 1;
2646 	if (ulen) {
2647 		if (bpf_dump_raw_ok()) {
2648 			u32 __user *user_lens;
2649 			u32 func_len, i;
2650 
2651 			/* copy the JITed image lengths for each function */
2652 			ulen = min_t(u32, info.nr_jited_func_lens, ulen);
2653 			user_lens = u64_to_user_ptr(info.jited_func_lens);
2654 			if (prog->aux->func_cnt) {
2655 				for (i = 0; i < ulen; i++) {
2656 					func_len =
2657 						prog->aux->func[i]->jited_len;
2658 					if (put_user(func_len, &user_lens[i]))
2659 						return -EFAULT;
2660 				}
2661 			} else {
2662 				func_len = prog->jited_len;
2663 				if (put_user(func_len, &user_lens[0]))
2664 					return -EFAULT;
2665 			}
2666 		} else {
2667 			info.jited_func_lens = 0;
2668 		}
2669 	}
2670 
2671 	if (prog->aux->btf)
2672 		info.btf_id = btf_id(prog->aux->btf);
2673 
2674 	ulen = info.nr_func_info;
2675 	info.nr_func_info = prog->aux->func_info_cnt;
2676 	if (info.nr_func_info && ulen) {
2677 		char __user *user_finfo;
2678 
2679 		user_finfo = u64_to_user_ptr(info.func_info);
2680 		ulen = min_t(u32, info.nr_func_info, ulen);
2681 		if (copy_to_user(user_finfo, prog->aux->func_info,
2682 				 info.func_info_rec_size * ulen))
2683 			return -EFAULT;
2684 	}
2685 
2686 	ulen = info.nr_line_info;
2687 	info.nr_line_info = prog->aux->nr_linfo;
2688 	if (info.nr_line_info && ulen) {
2689 		__u8 __user *user_linfo;
2690 
2691 		user_linfo = u64_to_user_ptr(info.line_info);
2692 		ulen = min_t(u32, info.nr_line_info, ulen);
2693 		if (copy_to_user(user_linfo, prog->aux->linfo,
2694 				 info.line_info_rec_size * ulen))
2695 			return -EFAULT;
2696 	}
2697 
2698 	ulen = info.nr_jited_line_info;
2699 	if (prog->aux->jited_linfo)
2700 		info.nr_jited_line_info = prog->aux->nr_linfo;
2701 	else
2702 		info.nr_jited_line_info = 0;
2703 	if (info.nr_jited_line_info && ulen) {
2704 		if (bpf_dump_raw_ok()) {
2705 			__u64 __user *user_linfo;
2706 			u32 i;
2707 
2708 			user_linfo = u64_to_user_ptr(info.jited_line_info);
2709 			ulen = min_t(u32, info.nr_jited_line_info, ulen);
2710 			for (i = 0; i < ulen; i++) {
2711 				if (put_user((__u64)(long)prog->aux->jited_linfo[i],
2712 					     &user_linfo[i]))
2713 					return -EFAULT;
2714 			}
2715 		} else {
2716 			info.jited_line_info = 0;
2717 		}
2718 	}
2719 
2720 	ulen = info.nr_prog_tags;
2721 	info.nr_prog_tags = prog->aux->func_cnt ? : 1;
2722 	if (ulen) {
2723 		__u8 __user (*user_prog_tags)[BPF_TAG_SIZE];
2724 		u32 i;
2725 
2726 		user_prog_tags = u64_to_user_ptr(info.prog_tags);
2727 		ulen = min_t(u32, info.nr_prog_tags, ulen);
2728 		if (prog->aux->func_cnt) {
2729 			for (i = 0; i < ulen; i++) {
2730 				if (copy_to_user(user_prog_tags[i],
2731 						 prog->aux->func[i]->tag,
2732 						 BPF_TAG_SIZE))
2733 					return -EFAULT;
2734 			}
2735 		} else {
2736 			if (copy_to_user(user_prog_tags[0],
2737 					 prog->tag, BPF_TAG_SIZE))
2738 				return -EFAULT;
2739 		}
2740 	}
2741 
2742 done:
2743 	if (copy_to_user(uinfo, &info, info_len) ||
2744 	    put_user(info_len, &uattr->info.info_len))
2745 		return -EFAULT;
2746 
2747 	return 0;
2748 }
2749 
2750 static int bpf_map_get_info_by_fd(struct bpf_map *map,
2751 				  const union bpf_attr *attr,
2752 				  union bpf_attr __user *uattr)
2753 {
2754 	struct bpf_map_info __user *uinfo = u64_to_user_ptr(attr->info.info);
2755 	struct bpf_map_info info = {};
2756 	u32 info_len = attr->info.info_len;
2757 	int err;
2758 
2759 	err = bpf_check_uarg_tail_zero(uinfo, sizeof(info), info_len);
2760 	if (err)
2761 		return err;
2762 	info_len = min_t(u32, sizeof(info), info_len);
2763 
2764 	info.type = map->map_type;
2765 	info.id = map->id;
2766 	info.key_size = map->key_size;
2767 	info.value_size = map->value_size;
2768 	info.max_entries = map->max_entries;
2769 	info.map_flags = map->map_flags;
2770 	memcpy(info.name, map->name, sizeof(map->name));
2771 
2772 	if (map->btf) {
2773 		info.btf_id = btf_id(map->btf);
2774 		info.btf_key_type_id = map->btf_key_type_id;
2775 		info.btf_value_type_id = map->btf_value_type_id;
2776 	}
2777 
2778 	if (bpf_map_is_dev_bound(map)) {
2779 		err = bpf_map_offload_info_fill(&info, map);
2780 		if (err)
2781 			return err;
2782 	}
2783 
2784 	if (copy_to_user(uinfo, &info, info_len) ||
2785 	    put_user(info_len, &uattr->info.info_len))
2786 		return -EFAULT;
2787 
2788 	return 0;
2789 }
2790 
2791 static int bpf_btf_get_info_by_fd(struct btf *btf,
2792 				  const union bpf_attr *attr,
2793 				  union bpf_attr __user *uattr)
2794 {
2795 	struct bpf_btf_info __user *uinfo = u64_to_user_ptr(attr->info.info);
2796 	u32 info_len = attr->info.info_len;
2797 	int err;
2798 
2799 	err = bpf_check_uarg_tail_zero(uinfo, sizeof(*uinfo), info_len);
2800 	if (err)
2801 		return err;
2802 
2803 	return btf_get_info_by_fd(btf, attr, uattr);
2804 }
2805 
2806 #define BPF_OBJ_GET_INFO_BY_FD_LAST_FIELD info.info
2807 
2808 static int bpf_obj_get_info_by_fd(const union bpf_attr *attr,
2809 				  union bpf_attr __user *uattr)
2810 {
2811 	int ufd = attr->info.bpf_fd;
2812 	struct fd f;
2813 	int err;
2814 
2815 	if (CHECK_ATTR(BPF_OBJ_GET_INFO_BY_FD))
2816 		return -EINVAL;
2817 
2818 	f = fdget(ufd);
2819 	if (!f.file)
2820 		return -EBADFD;
2821 
2822 	if (f.file->f_op == &bpf_prog_fops)
2823 		err = bpf_prog_get_info_by_fd(f.file->private_data, attr,
2824 					      uattr);
2825 	else if (f.file->f_op == &bpf_map_fops)
2826 		err = bpf_map_get_info_by_fd(f.file->private_data, attr,
2827 					     uattr);
2828 	else if (f.file->f_op == &btf_fops)
2829 		err = bpf_btf_get_info_by_fd(f.file->private_data, attr, uattr);
2830 	else
2831 		err = -EINVAL;
2832 
2833 	fdput(f);
2834 	return err;
2835 }
2836 
2837 #define BPF_BTF_LOAD_LAST_FIELD btf_log_level
2838 
2839 static int bpf_btf_load(const union bpf_attr *attr)
2840 {
2841 	if (CHECK_ATTR(BPF_BTF_LOAD))
2842 		return -EINVAL;
2843 
2844 	if (!capable(CAP_SYS_ADMIN))
2845 		return -EPERM;
2846 
2847 	return btf_new_fd(attr);
2848 }
2849 
2850 #define BPF_BTF_GET_FD_BY_ID_LAST_FIELD btf_id
2851 
2852 static int bpf_btf_get_fd_by_id(const union bpf_attr *attr)
2853 {
2854 	if (CHECK_ATTR(BPF_BTF_GET_FD_BY_ID))
2855 		return -EINVAL;
2856 
2857 	if (!capable(CAP_SYS_ADMIN))
2858 		return -EPERM;
2859 
2860 	return btf_get_fd_by_id(attr->btf_id);
2861 }
2862 
2863 static int bpf_task_fd_query_copy(const union bpf_attr *attr,
2864 				    union bpf_attr __user *uattr,
2865 				    u32 prog_id, u32 fd_type,
2866 				    const char *buf, u64 probe_offset,
2867 				    u64 probe_addr)
2868 {
2869 	char __user *ubuf = u64_to_user_ptr(attr->task_fd_query.buf);
2870 	u32 len = buf ? strlen(buf) : 0, input_len;
2871 	int err = 0;
2872 
2873 	if (put_user(len, &uattr->task_fd_query.buf_len))
2874 		return -EFAULT;
2875 	input_len = attr->task_fd_query.buf_len;
2876 	if (input_len && ubuf) {
2877 		if (!len) {
2878 			/* nothing to copy, just make ubuf NULL terminated */
2879 			char zero = '\0';
2880 
2881 			if (put_user(zero, ubuf))
2882 				return -EFAULT;
2883 		} else if (input_len >= len + 1) {
2884 			/* ubuf can hold the string with NULL terminator */
2885 			if (copy_to_user(ubuf, buf, len + 1))
2886 				return -EFAULT;
2887 		} else {
2888 			/* ubuf cannot hold the string with NULL terminator,
2889 			 * do a partial copy with NULL terminator.
2890 			 */
2891 			char zero = '\0';
2892 
2893 			err = -ENOSPC;
2894 			if (copy_to_user(ubuf, buf, input_len - 1))
2895 				return -EFAULT;
2896 			if (put_user(zero, ubuf + input_len - 1))
2897 				return -EFAULT;
2898 		}
2899 	}
2900 
2901 	if (put_user(prog_id, &uattr->task_fd_query.prog_id) ||
2902 	    put_user(fd_type, &uattr->task_fd_query.fd_type) ||
2903 	    put_user(probe_offset, &uattr->task_fd_query.probe_offset) ||
2904 	    put_user(probe_addr, &uattr->task_fd_query.probe_addr))
2905 		return -EFAULT;
2906 
2907 	return err;
2908 }
2909 
2910 #define BPF_TASK_FD_QUERY_LAST_FIELD task_fd_query.probe_addr
2911 
2912 static int bpf_task_fd_query(const union bpf_attr *attr,
2913 			     union bpf_attr __user *uattr)
2914 {
2915 	pid_t pid = attr->task_fd_query.pid;
2916 	u32 fd = attr->task_fd_query.fd;
2917 	const struct perf_event *event;
2918 	struct files_struct *files;
2919 	struct task_struct *task;
2920 	struct file *file;
2921 	int err;
2922 
2923 	if (CHECK_ATTR(BPF_TASK_FD_QUERY))
2924 		return -EINVAL;
2925 
2926 	if (!capable(CAP_SYS_ADMIN))
2927 		return -EPERM;
2928 
2929 	if (attr->task_fd_query.flags != 0)
2930 		return -EINVAL;
2931 
2932 	task = get_pid_task(find_vpid(pid), PIDTYPE_PID);
2933 	if (!task)
2934 		return -ENOENT;
2935 
2936 	files = get_files_struct(task);
2937 	put_task_struct(task);
2938 	if (!files)
2939 		return -ENOENT;
2940 
2941 	err = 0;
2942 	spin_lock(&files->file_lock);
2943 	file = fcheck_files(files, fd);
2944 	if (!file)
2945 		err = -EBADF;
2946 	else
2947 		get_file(file);
2948 	spin_unlock(&files->file_lock);
2949 	put_files_struct(files);
2950 
2951 	if (err)
2952 		goto out;
2953 
2954 	if (file->f_op == &bpf_raw_tp_fops) {
2955 		struct bpf_raw_tracepoint *raw_tp = file->private_data;
2956 		struct bpf_raw_event_map *btp = raw_tp->btp;
2957 
2958 		err = bpf_task_fd_query_copy(attr, uattr,
2959 					     raw_tp->prog->aux->id,
2960 					     BPF_FD_TYPE_RAW_TRACEPOINT,
2961 					     btp->tp->name, 0, 0);
2962 		goto put_file;
2963 	}
2964 
2965 	event = perf_get_event(file);
2966 	if (!IS_ERR(event)) {
2967 		u64 probe_offset, probe_addr;
2968 		u32 prog_id, fd_type;
2969 		const char *buf;
2970 
2971 		err = bpf_get_perf_event_info(event, &prog_id, &fd_type,
2972 					      &buf, &probe_offset,
2973 					      &probe_addr);
2974 		if (!err)
2975 			err = bpf_task_fd_query_copy(attr, uattr, prog_id,
2976 						     fd_type, buf,
2977 						     probe_offset,
2978 						     probe_addr);
2979 		goto put_file;
2980 	}
2981 
2982 	err = -ENOTSUPP;
2983 put_file:
2984 	fput(file);
2985 out:
2986 	return err;
2987 }
2988 
2989 SYSCALL_DEFINE3(bpf, int, cmd, union bpf_attr __user *, uattr, unsigned int, size)
2990 {
2991 	union bpf_attr attr = {};
2992 	int err;
2993 
2994 	if (sysctl_unprivileged_bpf_disabled && !capable(CAP_SYS_ADMIN))
2995 		return -EPERM;
2996 
2997 	err = bpf_check_uarg_tail_zero(uattr, sizeof(attr), size);
2998 	if (err)
2999 		return err;
3000 	size = min_t(u32, size, sizeof(attr));
3001 
3002 	/* copy attributes from user space, may be less than sizeof(bpf_attr) */
3003 	if (copy_from_user(&attr, uattr, size) != 0)
3004 		return -EFAULT;
3005 
3006 	err = security_bpf(cmd, &attr, size);
3007 	if (err < 0)
3008 		return err;
3009 
3010 	switch (cmd) {
3011 	case BPF_MAP_CREATE:
3012 		err = map_create(&attr);
3013 		break;
3014 	case BPF_MAP_LOOKUP_ELEM:
3015 		err = map_lookup_elem(&attr);
3016 		break;
3017 	case BPF_MAP_UPDATE_ELEM:
3018 		err = map_update_elem(&attr);
3019 		break;
3020 	case BPF_MAP_DELETE_ELEM:
3021 		err = map_delete_elem(&attr);
3022 		break;
3023 	case BPF_MAP_GET_NEXT_KEY:
3024 		err = map_get_next_key(&attr);
3025 		break;
3026 	case BPF_MAP_FREEZE:
3027 		err = map_freeze(&attr);
3028 		break;
3029 	case BPF_PROG_LOAD:
3030 		err = bpf_prog_load(&attr, uattr);
3031 		break;
3032 	case BPF_OBJ_PIN:
3033 		err = bpf_obj_pin(&attr);
3034 		break;
3035 	case BPF_OBJ_GET:
3036 		err = bpf_obj_get(&attr);
3037 		break;
3038 	case BPF_PROG_ATTACH:
3039 		err = bpf_prog_attach(&attr);
3040 		break;
3041 	case BPF_PROG_DETACH:
3042 		err = bpf_prog_detach(&attr);
3043 		break;
3044 	case BPF_PROG_QUERY:
3045 		err = bpf_prog_query(&attr, uattr);
3046 		break;
3047 	case BPF_PROG_TEST_RUN:
3048 		err = bpf_prog_test_run(&attr, uattr);
3049 		break;
3050 	case BPF_PROG_GET_NEXT_ID:
3051 		err = bpf_obj_get_next_id(&attr, uattr,
3052 					  &prog_idr, &prog_idr_lock);
3053 		break;
3054 	case BPF_MAP_GET_NEXT_ID:
3055 		err = bpf_obj_get_next_id(&attr, uattr,
3056 					  &map_idr, &map_idr_lock);
3057 		break;
3058 	case BPF_BTF_GET_NEXT_ID:
3059 		err = bpf_obj_get_next_id(&attr, uattr,
3060 					  &btf_idr, &btf_idr_lock);
3061 		break;
3062 	case BPF_PROG_GET_FD_BY_ID:
3063 		err = bpf_prog_get_fd_by_id(&attr);
3064 		break;
3065 	case BPF_MAP_GET_FD_BY_ID:
3066 		err = bpf_map_get_fd_by_id(&attr);
3067 		break;
3068 	case BPF_OBJ_GET_INFO_BY_FD:
3069 		err = bpf_obj_get_info_by_fd(&attr, uattr);
3070 		break;
3071 	case BPF_RAW_TRACEPOINT_OPEN:
3072 		err = bpf_raw_tracepoint_open(&attr);
3073 		break;
3074 	case BPF_BTF_LOAD:
3075 		err = bpf_btf_load(&attr);
3076 		break;
3077 	case BPF_BTF_GET_FD_BY_ID:
3078 		err = bpf_btf_get_fd_by_id(&attr);
3079 		break;
3080 	case BPF_TASK_FD_QUERY:
3081 		err = bpf_task_fd_query(&attr, uattr);
3082 		break;
3083 	case BPF_MAP_LOOKUP_AND_DELETE_ELEM:
3084 		err = map_lookup_and_delete_elem(&attr);
3085 		break;
3086 	default:
3087 		err = -EINVAL;
3088 		break;
3089 	}
3090 
3091 	return err;
3092 }
3093