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