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