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