xref: /linux/kernel/bpf/syscall.c (revision f6f3bac08ff9855d803081a353a1fafaa8845739)
1 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
2  *
3  * This program is free software; you can redistribute it and/or
4  * modify it under the terms of version 2 of the GNU General Public
5  * License as published by the Free Software Foundation.
6  *
7  * This program is distributed in the hope that it will be useful, but
8  * WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
10  * General Public License for more details.
11  */
12 #include <linux/bpf.h>
13 #include <linux/bpf_trace.h>
14 #include <linux/bpf_lirc.h>
15 #include <linux/btf.h>
16 #include <linux/syscalls.h>
17 #include <linux/slab.h>
18 #include <linux/sched/signal.h>
19 #include <linux/vmalloc.h>
20 #include <linux/mmzone.h>
21 #include <linux/anon_inodes.h>
22 #include <linux/fdtable.h>
23 #include <linux/file.h>
24 #include <linux/fs.h>
25 #include <linux/license.h>
26 #include <linux/filter.h>
27 #include <linux/version.h>
28 #include <linux/kernel.h>
29 #include <linux/idr.h>
30 #include <linux/cred.h>
31 #include <linux/timekeeping.h>
32 #include <linux/ctype.h>
33 #include <linux/nospec.h>
34 
35 #define IS_FD_ARRAY(map) ((map)->map_type == BPF_MAP_TYPE_PROG_ARRAY || \
36 			   (map)->map_type == BPF_MAP_TYPE_PERF_EVENT_ARRAY || \
37 			   (map)->map_type == BPF_MAP_TYPE_CGROUP_ARRAY || \
38 			   (map)->map_type == BPF_MAP_TYPE_ARRAY_OF_MAPS)
39 #define IS_FD_HASH(map) ((map)->map_type == BPF_MAP_TYPE_HASH_OF_MAPS)
40 #define IS_FD_MAP(map) (IS_FD_ARRAY(map) || IS_FD_HASH(map))
41 
42 #define BPF_OBJ_FLAG_MASK   (BPF_F_RDONLY | BPF_F_WRONLY)
43 
44 DEFINE_PER_CPU(int, bpf_prog_active);
45 static DEFINE_IDR(prog_idr);
46 static DEFINE_SPINLOCK(prog_idr_lock);
47 static DEFINE_IDR(map_idr);
48 static DEFINE_SPINLOCK(map_idr_lock);
49 
50 int sysctl_unprivileged_bpf_disabled __read_mostly;
51 
52 static const struct bpf_map_ops * const bpf_map_types[] = {
53 #define BPF_PROG_TYPE(_id, _ops)
54 #define BPF_MAP_TYPE(_id, _ops) \
55 	[_id] = &_ops,
56 #include <linux/bpf_types.h>
57 #undef BPF_PROG_TYPE
58 #undef BPF_MAP_TYPE
59 };
60 
61 /*
62  * If we're handed a bigger struct than we know of, ensure all the unknown bits
63  * are 0 - i.e. new user-space does not rely on any kernel feature extensions
64  * we don't know about yet.
65  *
66  * There is a ToCToU between this function call and the following
67  * copy_from_user() call. However, this is not a concern since this function is
68  * meant to be a future-proofing of bits.
69  */
70 int bpf_check_uarg_tail_zero(void __user *uaddr,
71 			     size_t expected_size,
72 			     size_t actual_size)
73 {
74 	unsigned char __user *addr;
75 	unsigned char __user *end;
76 	unsigned char val;
77 	int err;
78 
79 	if (unlikely(actual_size > PAGE_SIZE))	/* silly large */
80 		return -E2BIG;
81 
82 	if (unlikely(!access_ok(VERIFY_READ, uaddr, actual_size)))
83 		return -EFAULT;
84 
85 	if (actual_size <= expected_size)
86 		return 0;
87 
88 	addr = uaddr + expected_size;
89 	end  = uaddr + actual_size;
90 
91 	for (; addr < end; addr++) {
92 		err = get_user(val, addr);
93 		if (err)
94 			return err;
95 		if (val)
96 			return -E2BIG;
97 	}
98 
99 	return 0;
100 }
101 
102 const struct bpf_map_ops bpf_map_offload_ops = {
103 	.map_alloc = bpf_map_offload_map_alloc,
104 	.map_free = bpf_map_offload_map_free,
105 	.map_check_btf = map_check_no_btf,
106 };
107 
108 static struct bpf_map *find_and_alloc_map(union bpf_attr *attr)
109 {
110 	const struct bpf_map_ops *ops;
111 	u32 type = attr->map_type;
112 	struct bpf_map *map;
113 	int err;
114 
115 	if (type >= ARRAY_SIZE(bpf_map_types))
116 		return ERR_PTR(-EINVAL);
117 	type = array_index_nospec(type, ARRAY_SIZE(bpf_map_types));
118 	ops = bpf_map_types[type];
119 	if (!ops)
120 		return ERR_PTR(-EINVAL);
121 
122 	if (ops->map_alloc_check) {
123 		err = ops->map_alloc_check(attr);
124 		if (err)
125 			return ERR_PTR(err);
126 	}
127 	if (attr->map_ifindex)
128 		ops = &bpf_map_offload_ops;
129 	map = ops->map_alloc(attr);
130 	if (IS_ERR(map))
131 		return map;
132 	map->ops = ops;
133 	map->map_type = type;
134 	return map;
135 }
136 
137 void *bpf_map_area_alloc(size_t size, int numa_node)
138 {
139 	/* We definitely need __GFP_NORETRY, so OOM killer doesn't
140 	 * trigger under memory pressure as we really just want to
141 	 * fail instead.
142 	 */
143 	const gfp_t flags = __GFP_NOWARN | __GFP_NORETRY | __GFP_ZERO;
144 	void *area;
145 
146 	if (size <= (PAGE_SIZE << PAGE_ALLOC_COSTLY_ORDER)) {
147 		area = kmalloc_node(size, GFP_USER | flags, numa_node);
148 		if (area != NULL)
149 			return area;
150 	}
151 
152 	return __vmalloc_node_flags_caller(size, numa_node, GFP_KERNEL | flags,
153 					   __builtin_return_address(0));
154 }
155 
156 void bpf_map_area_free(void *area)
157 {
158 	kvfree(area);
159 }
160 
161 void bpf_map_init_from_attr(struct bpf_map *map, union bpf_attr *attr)
162 {
163 	map->map_type = attr->map_type;
164 	map->key_size = attr->key_size;
165 	map->value_size = attr->value_size;
166 	map->max_entries = attr->max_entries;
167 	map->map_flags = attr->map_flags;
168 	map->numa_node = bpf_map_attr_numa_node(attr);
169 }
170 
171 int bpf_map_precharge_memlock(u32 pages)
172 {
173 	struct user_struct *user = get_current_user();
174 	unsigned long memlock_limit, cur;
175 
176 	memlock_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
177 	cur = atomic_long_read(&user->locked_vm);
178 	free_uid(user);
179 	if (cur + pages > memlock_limit)
180 		return -EPERM;
181 	return 0;
182 }
183 
184 static int bpf_charge_memlock(struct user_struct *user, u32 pages)
185 {
186 	unsigned long memlock_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
187 
188 	if (atomic_long_add_return(pages, &user->locked_vm) > memlock_limit) {
189 		atomic_long_sub(pages, &user->locked_vm);
190 		return -EPERM;
191 	}
192 	return 0;
193 }
194 
195 static void bpf_uncharge_memlock(struct user_struct *user, u32 pages)
196 {
197 	atomic_long_sub(pages, &user->locked_vm);
198 }
199 
200 static int bpf_map_init_memlock(struct bpf_map *map)
201 {
202 	struct user_struct *user = get_current_user();
203 	int ret;
204 
205 	ret = bpf_charge_memlock(user, map->pages);
206 	if (ret) {
207 		free_uid(user);
208 		return ret;
209 	}
210 	map->user = user;
211 	return ret;
212 }
213 
214 static void bpf_map_release_memlock(struct bpf_map *map)
215 {
216 	struct user_struct *user = map->user;
217 	bpf_uncharge_memlock(user, map->pages);
218 	free_uid(user);
219 }
220 
221 int bpf_map_charge_memlock(struct bpf_map *map, u32 pages)
222 {
223 	int ret;
224 
225 	ret = bpf_charge_memlock(map->user, pages);
226 	if (ret)
227 		return ret;
228 	map->pages += pages;
229 	return ret;
230 }
231 
232 void bpf_map_uncharge_memlock(struct bpf_map *map, u32 pages)
233 {
234 	bpf_uncharge_memlock(map->user, pages);
235 	map->pages -= pages;
236 }
237 
238 static int bpf_map_alloc_id(struct bpf_map *map)
239 {
240 	int id;
241 
242 	idr_preload(GFP_KERNEL);
243 	spin_lock_bh(&map_idr_lock);
244 	id = idr_alloc_cyclic(&map_idr, map, 1, INT_MAX, GFP_ATOMIC);
245 	if (id > 0)
246 		map->id = id;
247 	spin_unlock_bh(&map_idr_lock);
248 	idr_preload_end();
249 
250 	if (WARN_ON_ONCE(!id))
251 		return -ENOSPC;
252 
253 	return id > 0 ? 0 : id;
254 }
255 
256 void bpf_map_free_id(struct bpf_map *map, bool do_idr_lock)
257 {
258 	unsigned long flags;
259 
260 	/* Offloaded maps are removed from the IDR store when their device
261 	 * disappears - even if someone holds an fd to them they are unusable,
262 	 * the memory is gone, all ops will fail; they are simply waiting for
263 	 * refcnt to drop to be freed.
264 	 */
265 	if (!map->id)
266 		return;
267 
268 	if (do_idr_lock)
269 		spin_lock_irqsave(&map_idr_lock, flags);
270 	else
271 		__acquire(&map_idr_lock);
272 
273 	idr_remove(&map_idr, map->id);
274 	map->id = 0;
275 
276 	if (do_idr_lock)
277 		spin_unlock_irqrestore(&map_idr_lock, flags);
278 	else
279 		__release(&map_idr_lock);
280 }
281 
282 /* called from workqueue */
283 static void bpf_map_free_deferred(struct work_struct *work)
284 {
285 	struct bpf_map *map = container_of(work, struct bpf_map, work);
286 
287 	bpf_map_release_memlock(map);
288 	security_bpf_map_free(map);
289 	/* implementation dependent freeing */
290 	map->ops->map_free(map);
291 }
292 
293 static void bpf_map_put_uref(struct bpf_map *map)
294 {
295 	if (atomic_dec_and_test(&map->usercnt)) {
296 		if (map->ops->map_release_uref)
297 			map->ops->map_release_uref(map);
298 	}
299 }
300 
301 /* decrement map refcnt and schedule it for freeing via workqueue
302  * (unrelying map implementation ops->map_free() might sleep)
303  */
304 static void __bpf_map_put(struct bpf_map *map, bool do_idr_lock)
305 {
306 	if (atomic_dec_and_test(&map->refcnt)) {
307 		/* bpf_map_free_id() must be called first */
308 		bpf_map_free_id(map, do_idr_lock);
309 		btf_put(map->btf);
310 		INIT_WORK(&map->work, bpf_map_free_deferred);
311 		schedule_work(&map->work);
312 	}
313 }
314 
315 void bpf_map_put(struct bpf_map *map)
316 {
317 	__bpf_map_put(map, true);
318 }
319 EXPORT_SYMBOL_GPL(bpf_map_put);
320 
321 void bpf_map_put_with_uref(struct bpf_map *map)
322 {
323 	bpf_map_put_uref(map);
324 	bpf_map_put(map);
325 }
326 
327 static int bpf_map_release(struct inode *inode, struct file *filp)
328 {
329 	struct bpf_map *map = filp->private_data;
330 
331 	if (map->ops->map_release)
332 		map->ops->map_release(map, filp);
333 
334 	bpf_map_put_with_uref(map);
335 	return 0;
336 }
337 
338 #ifdef CONFIG_PROC_FS
339 static void bpf_map_show_fdinfo(struct seq_file *m, struct file *filp)
340 {
341 	const struct bpf_map *map = filp->private_data;
342 	const struct bpf_array *array;
343 	u32 owner_prog_type = 0;
344 	u32 owner_jited = 0;
345 
346 	if (map->map_type == BPF_MAP_TYPE_PROG_ARRAY) {
347 		array = container_of(map, struct bpf_array, map);
348 		owner_prog_type = array->owner_prog_type;
349 		owner_jited = array->owner_jited;
350 	}
351 
352 	seq_printf(m,
353 		   "map_type:\t%u\n"
354 		   "key_size:\t%u\n"
355 		   "value_size:\t%u\n"
356 		   "max_entries:\t%u\n"
357 		   "map_flags:\t%#x\n"
358 		   "memlock:\t%llu\n"
359 		   "map_id:\t%u\n",
360 		   map->map_type,
361 		   map->key_size,
362 		   map->value_size,
363 		   map->max_entries,
364 		   map->map_flags,
365 		   map->pages * 1ULL << PAGE_SHIFT,
366 		   map->id);
367 
368 	if (owner_prog_type) {
369 		seq_printf(m, "owner_prog_type:\t%u\n",
370 			   owner_prog_type);
371 		seq_printf(m, "owner_jited:\t%u\n",
372 			   owner_jited);
373 	}
374 }
375 #endif
376 
377 static ssize_t bpf_dummy_read(struct file *filp, char __user *buf, size_t siz,
378 			      loff_t *ppos)
379 {
380 	/* We need this handler such that alloc_file() enables
381 	 * f_mode with FMODE_CAN_READ.
382 	 */
383 	return -EINVAL;
384 }
385 
386 static ssize_t bpf_dummy_write(struct file *filp, const char __user *buf,
387 			       size_t siz, loff_t *ppos)
388 {
389 	/* We need this handler such that alloc_file() enables
390 	 * f_mode with FMODE_CAN_WRITE.
391 	 */
392 	return -EINVAL;
393 }
394 
395 const struct file_operations bpf_map_fops = {
396 #ifdef CONFIG_PROC_FS
397 	.show_fdinfo	= bpf_map_show_fdinfo,
398 #endif
399 	.release	= bpf_map_release,
400 	.read		= bpf_dummy_read,
401 	.write		= bpf_dummy_write,
402 };
403 
404 int bpf_map_new_fd(struct bpf_map *map, int flags)
405 {
406 	int ret;
407 
408 	ret = security_bpf_map(map, OPEN_FMODE(flags));
409 	if (ret < 0)
410 		return ret;
411 
412 	return anon_inode_getfd("bpf-map", &bpf_map_fops, map,
413 				flags | O_CLOEXEC);
414 }
415 
416 int bpf_get_file_flag(int flags)
417 {
418 	if ((flags & BPF_F_RDONLY) && (flags & BPF_F_WRONLY))
419 		return -EINVAL;
420 	if (flags & BPF_F_RDONLY)
421 		return O_RDONLY;
422 	if (flags & BPF_F_WRONLY)
423 		return O_WRONLY;
424 	return O_RDWR;
425 }
426 
427 /* helper macro to check that unused fields 'union bpf_attr' are zero */
428 #define CHECK_ATTR(CMD) \
429 	memchr_inv((void *) &attr->CMD##_LAST_FIELD + \
430 		   sizeof(attr->CMD##_LAST_FIELD), 0, \
431 		   sizeof(*attr) - \
432 		   offsetof(union bpf_attr, CMD##_LAST_FIELD) - \
433 		   sizeof(attr->CMD##_LAST_FIELD)) != NULL
434 
435 /* dst and src must have at least BPF_OBJ_NAME_LEN number of bytes.
436  * Return 0 on success and < 0 on error.
437  */
438 static int bpf_obj_name_cpy(char *dst, const char *src)
439 {
440 	const char *end = src + BPF_OBJ_NAME_LEN;
441 
442 	memset(dst, 0, BPF_OBJ_NAME_LEN);
443 
444 	/* Copy all isalnum() and '_' char */
445 	while (src < end && *src) {
446 		if (!isalnum(*src) && *src != '_')
447 			return -EINVAL;
448 		*dst++ = *src++;
449 	}
450 
451 	/* No '\0' found in BPF_OBJ_NAME_LEN number of bytes */
452 	if (src == end)
453 		return -EINVAL;
454 
455 	return 0;
456 }
457 
458 int map_check_no_btf(const struct bpf_map *map,
459 		     const struct btf_type *key_type,
460 		     const struct btf_type *value_type)
461 {
462 	return -ENOTSUPP;
463 }
464 
465 static int map_check_btf(const struct bpf_map *map, const struct btf *btf,
466 			 u32 btf_key_id, u32 btf_value_id)
467 {
468 	const struct btf_type *key_type, *value_type;
469 	u32 key_size, value_size;
470 	int ret = 0;
471 
472 	key_type = btf_type_id_size(btf, &btf_key_id, &key_size);
473 	if (!key_type || key_size != map->key_size)
474 		return -EINVAL;
475 
476 	value_type = btf_type_id_size(btf, &btf_value_id, &value_size);
477 	if (!value_type || value_size != map->value_size)
478 		return -EINVAL;
479 
480 	if (map->ops->map_check_btf)
481 		ret = map->ops->map_check_btf(map, key_type, value_type);
482 
483 	return ret;
484 }
485 
486 #define BPF_MAP_CREATE_LAST_FIELD btf_value_type_id
487 /* called via syscall */
488 static int map_create(union bpf_attr *attr)
489 {
490 	int numa_node = bpf_map_attr_numa_node(attr);
491 	struct bpf_map *map;
492 	int f_flags;
493 	int err;
494 
495 	err = CHECK_ATTR(BPF_MAP_CREATE);
496 	if (err)
497 		return -EINVAL;
498 
499 	f_flags = bpf_get_file_flag(attr->map_flags);
500 	if (f_flags < 0)
501 		return f_flags;
502 
503 	if (numa_node != NUMA_NO_NODE &&
504 	    ((unsigned int)numa_node >= nr_node_ids ||
505 	     !node_online(numa_node)))
506 		return -EINVAL;
507 
508 	/* find map type and init map: hashtable vs rbtree vs bloom vs ... */
509 	map = find_and_alloc_map(attr);
510 	if (IS_ERR(map))
511 		return PTR_ERR(map);
512 
513 	err = bpf_obj_name_cpy(map->name, attr->map_name);
514 	if (err)
515 		goto free_map_nouncharge;
516 
517 	atomic_set(&map->refcnt, 1);
518 	atomic_set(&map->usercnt, 1);
519 
520 	if (attr->btf_key_type_id || attr->btf_value_type_id) {
521 		struct btf *btf;
522 
523 		if (!attr->btf_key_type_id || !attr->btf_value_type_id) {
524 			err = -EINVAL;
525 			goto free_map_nouncharge;
526 		}
527 
528 		btf = btf_get_by_fd(attr->btf_fd);
529 		if (IS_ERR(btf)) {
530 			err = PTR_ERR(btf);
531 			goto free_map_nouncharge;
532 		}
533 
534 		err = map_check_btf(map, btf, attr->btf_key_type_id,
535 				    attr->btf_value_type_id);
536 		if (err) {
537 			btf_put(btf);
538 			goto free_map_nouncharge;
539 		}
540 
541 		map->btf = btf;
542 		map->btf_key_type_id = attr->btf_key_type_id;
543 		map->btf_value_type_id = attr->btf_value_type_id;
544 	}
545 
546 	err = security_bpf_map_alloc(map);
547 	if (err)
548 		goto free_map_nouncharge;
549 
550 	err = bpf_map_init_memlock(map);
551 	if (err)
552 		goto free_map_sec;
553 
554 	err = bpf_map_alloc_id(map);
555 	if (err)
556 		goto free_map;
557 
558 	err = bpf_map_new_fd(map, f_flags);
559 	if (err < 0) {
560 		/* failed to allocate fd.
561 		 * bpf_map_put() is needed because the above
562 		 * bpf_map_alloc_id() has published the map
563 		 * to the userspace and the userspace may
564 		 * have refcnt-ed it through BPF_MAP_GET_FD_BY_ID.
565 		 */
566 		bpf_map_put(map);
567 		return err;
568 	}
569 
570 	return err;
571 
572 free_map:
573 	bpf_map_release_memlock(map);
574 free_map_sec:
575 	security_bpf_map_free(map);
576 free_map_nouncharge:
577 	btf_put(map->btf);
578 	map->ops->map_free(map);
579 	return err;
580 }
581 
582 /* if error is returned, fd is released.
583  * On success caller should complete fd access with matching fdput()
584  */
585 struct bpf_map *__bpf_map_get(struct fd f)
586 {
587 	if (!f.file)
588 		return ERR_PTR(-EBADF);
589 	if (f.file->f_op != &bpf_map_fops) {
590 		fdput(f);
591 		return ERR_PTR(-EINVAL);
592 	}
593 
594 	return f.file->private_data;
595 }
596 
597 /* prog's and map's refcnt limit */
598 #define BPF_MAX_REFCNT 32768
599 
600 struct bpf_map *bpf_map_inc(struct bpf_map *map, bool uref)
601 {
602 	if (atomic_inc_return(&map->refcnt) > BPF_MAX_REFCNT) {
603 		atomic_dec(&map->refcnt);
604 		return ERR_PTR(-EBUSY);
605 	}
606 	if (uref)
607 		atomic_inc(&map->usercnt);
608 	return map;
609 }
610 EXPORT_SYMBOL_GPL(bpf_map_inc);
611 
612 struct bpf_map *bpf_map_get_with_uref(u32 ufd)
613 {
614 	struct fd f = fdget(ufd);
615 	struct bpf_map *map;
616 
617 	map = __bpf_map_get(f);
618 	if (IS_ERR(map))
619 		return map;
620 
621 	map = bpf_map_inc(map, true);
622 	fdput(f);
623 
624 	return map;
625 }
626 
627 /* map_idr_lock should have been held */
628 static struct bpf_map *bpf_map_inc_not_zero(struct bpf_map *map,
629 					    bool uref)
630 {
631 	int refold;
632 
633 	refold = atomic_fetch_add_unless(&map->refcnt, 1, 0);
634 
635 	if (refold >= BPF_MAX_REFCNT) {
636 		__bpf_map_put(map, false);
637 		return ERR_PTR(-EBUSY);
638 	}
639 
640 	if (!refold)
641 		return ERR_PTR(-ENOENT);
642 
643 	if (uref)
644 		atomic_inc(&map->usercnt);
645 
646 	return map;
647 }
648 
649 int __weak bpf_stackmap_copy(struct bpf_map *map, void *key, void *value)
650 {
651 	return -ENOTSUPP;
652 }
653 
654 /* last field in 'union bpf_attr' used by this command */
655 #define BPF_MAP_LOOKUP_ELEM_LAST_FIELD value
656 
657 static int map_lookup_elem(union bpf_attr *attr)
658 {
659 	void __user *ukey = u64_to_user_ptr(attr->key);
660 	void __user *uvalue = u64_to_user_ptr(attr->value);
661 	int ufd = attr->map_fd;
662 	struct bpf_map *map;
663 	void *key, *value, *ptr;
664 	u32 value_size;
665 	struct fd f;
666 	int err;
667 
668 	if (CHECK_ATTR(BPF_MAP_LOOKUP_ELEM))
669 		return -EINVAL;
670 
671 	f = fdget(ufd);
672 	map = __bpf_map_get(f);
673 	if (IS_ERR(map))
674 		return PTR_ERR(map);
675 
676 	if (!(f.file->f_mode & FMODE_CAN_READ)) {
677 		err = -EPERM;
678 		goto err_put;
679 	}
680 
681 	key = memdup_user(ukey, map->key_size);
682 	if (IS_ERR(key)) {
683 		err = PTR_ERR(key);
684 		goto err_put;
685 	}
686 
687 	if (map->map_type == BPF_MAP_TYPE_PERCPU_HASH ||
688 	    map->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH ||
689 	    map->map_type == BPF_MAP_TYPE_PERCPU_ARRAY)
690 		value_size = round_up(map->value_size, 8) * num_possible_cpus();
691 	else if (IS_FD_MAP(map))
692 		value_size = sizeof(u32);
693 	else
694 		value_size = map->value_size;
695 
696 	err = -ENOMEM;
697 	value = kmalloc(value_size, GFP_USER | __GFP_NOWARN);
698 	if (!value)
699 		goto free_key;
700 
701 	if (bpf_map_is_dev_bound(map)) {
702 		err = bpf_map_offload_lookup_elem(map, key, value);
703 	} else if (map->map_type == BPF_MAP_TYPE_PERCPU_HASH ||
704 		   map->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH) {
705 		err = bpf_percpu_hash_copy(map, key, value);
706 	} else if (map->map_type == BPF_MAP_TYPE_PERCPU_ARRAY) {
707 		err = bpf_percpu_array_copy(map, key, value);
708 	} else if (map->map_type == BPF_MAP_TYPE_STACK_TRACE) {
709 		err = bpf_stackmap_copy(map, key, value);
710 	} else if (IS_FD_ARRAY(map)) {
711 		err = bpf_fd_array_map_lookup_elem(map, key, value);
712 	} else if (IS_FD_HASH(map)) {
713 		err = bpf_fd_htab_map_lookup_elem(map, key, value);
714 	} else if (map->map_type == BPF_MAP_TYPE_REUSEPORT_SOCKARRAY) {
715 		err = bpf_fd_reuseport_array_lookup_elem(map, key, value);
716 	} else {
717 		rcu_read_lock();
718 		ptr = map->ops->map_lookup_elem(map, key);
719 		if (ptr)
720 			memcpy(value, ptr, value_size);
721 		rcu_read_unlock();
722 		err = ptr ? 0 : -ENOENT;
723 	}
724 
725 	if (err)
726 		goto free_value;
727 
728 	err = -EFAULT;
729 	if (copy_to_user(uvalue, value, value_size) != 0)
730 		goto free_value;
731 
732 	err = 0;
733 
734 free_value:
735 	kfree(value);
736 free_key:
737 	kfree(key);
738 err_put:
739 	fdput(f);
740 	return err;
741 }
742 
743 #define BPF_MAP_UPDATE_ELEM_LAST_FIELD flags
744 
745 static int map_update_elem(union bpf_attr *attr)
746 {
747 	void __user *ukey = u64_to_user_ptr(attr->key);
748 	void __user *uvalue = u64_to_user_ptr(attr->value);
749 	int ufd = attr->map_fd;
750 	struct bpf_map *map;
751 	void *key, *value;
752 	u32 value_size;
753 	struct fd f;
754 	int err;
755 
756 	if (CHECK_ATTR(BPF_MAP_UPDATE_ELEM))
757 		return -EINVAL;
758 
759 	f = fdget(ufd);
760 	map = __bpf_map_get(f);
761 	if (IS_ERR(map))
762 		return PTR_ERR(map);
763 
764 	if (!(f.file->f_mode & FMODE_CAN_WRITE)) {
765 		err = -EPERM;
766 		goto err_put;
767 	}
768 
769 	key = memdup_user(ukey, map->key_size);
770 	if (IS_ERR(key)) {
771 		err = PTR_ERR(key);
772 		goto err_put;
773 	}
774 
775 	if (map->map_type == BPF_MAP_TYPE_PERCPU_HASH ||
776 	    map->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH ||
777 	    map->map_type == BPF_MAP_TYPE_PERCPU_ARRAY)
778 		value_size = round_up(map->value_size, 8) * num_possible_cpus();
779 	else
780 		value_size = map->value_size;
781 
782 	err = -ENOMEM;
783 	value = kmalloc(value_size, GFP_USER | __GFP_NOWARN);
784 	if (!value)
785 		goto free_key;
786 
787 	err = -EFAULT;
788 	if (copy_from_user(value, uvalue, value_size) != 0)
789 		goto free_value;
790 
791 	/* Need to create a kthread, thus must support schedule */
792 	if (bpf_map_is_dev_bound(map)) {
793 		err = bpf_map_offload_update_elem(map, key, value, attr->flags);
794 		goto out;
795 	} else if (map->map_type == BPF_MAP_TYPE_CPUMAP ||
796 		   map->map_type == BPF_MAP_TYPE_SOCKHASH ||
797 		   map->map_type == BPF_MAP_TYPE_SOCKMAP) {
798 		err = map->ops->map_update_elem(map, key, value, attr->flags);
799 		goto out;
800 	}
801 
802 	/* must increment bpf_prog_active to avoid kprobe+bpf triggering from
803 	 * inside bpf map update or delete otherwise deadlocks are possible
804 	 */
805 	preempt_disable();
806 	__this_cpu_inc(bpf_prog_active);
807 	if (map->map_type == BPF_MAP_TYPE_PERCPU_HASH ||
808 	    map->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH) {
809 		err = bpf_percpu_hash_update(map, key, value, attr->flags);
810 	} else if (map->map_type == BPF_MAP_TYPE_PERCPU_ARRAY) {
811 		err = bpf_percpu_array_update(map, key, value, attr->flags);
812 	} else if (IS_FD_ARRAY(map)) {
813 		rcu_read_lock();
814 		err = bpf_fd_array_map_update_elem(map, f.file, key, value,
815 						   attr->flags);
816 		rcu_read_unlock();
817 	} else if (map->map_type == BPF_MAP_TYPE_HASH_OF_MAPS) {
818 		rcu_read_lock();
819 		err = bpf_fd_htab_map_update_elem(map, f.file, key, value,
820 						  attr->flags);
821 		rcu_read_unlock();
822 	} else if (map->map_type == BPF_MAP_TYPE_REUSEPORT_SOCKARRAY) {
823 		/* rcu_read_lock() is not needed */
824 		err = bpf_fd_reuseport_array_update_elem(map, key, value,
825 							 attr->flags);
826 	} else {
827 		rcu_read_lock();
828 		err = map->ops->map_update_elem(map, key, value, attr->flags);
829 		rcu_read_unlock();
830 	}
831 	__this_cpu_dec(bpf_prog_active);
832 	preempt_enable();
833 out:
834 free_value:
835 	kfree(value);
836 free_key:
837 	kfree(key);
838 err_put:
839 	fdput(f);
840 	return err;
841 }
842 
843 #define BPF_MAP_DELETE_ELEM_LAST_FIELD key
844 
845 static int map_delete_elem(union bpf_attr *attr)
846 {
847 	void __user *ukey = u64_to_user_ptr(attr->key);
848 	int ufd = attr->map_fd;
849 	struct bpf_map *map;
850 	struct fd f;
851 	void *key;
852 	int err;
853 
854 	if (CHECK_ATTR(BPF_MAP_DELETE_ELEM))
855 		return -EINVAL;
856 
857 	f = fdget(ufd);
858 	map = __bpf_map_get(f);
859 	if (IS_ERR(map))
860 		return PTR_ERR(map);
861 
862 	if (!(f.file->f_mode & FMODE_CAN_WRITE)) {
863 		err = -EPERM;
864 		goto err_put;
865 	}
866 
867 	key = memdup_user(ukey, map->key_size);
868 	if (IS_ERR(key)) {
869 		err = PTR_ERR(key);
870 		goto err_put;
871 	}
872 
873 	if (bpf_map_is_dev_bound(map)) {
874 		err = bpf_map_offload_delete_elem(map, key);
875 		goto out;
876 	}
877 
878 	preempt_disable();
879 	__this_cpu_inc(bpf_prog_active);
880 	rcu_read_lock();
881 	err = map->ops->map_delete_elem(map, key);
882 	rcu_read_unlock();
883 	__this_cpu_dec(bpf_prog_active);
884 	preempt_enable();
885 out:
886 	kfree(key);
887 err_put:
888 	fdput(f);
889 	return err;
890 }
891 
892 /* last field in 'union bpf_attr' used by this command */
893 #define BPF_MAP_GET_NEXT_KEY_LAST_FIELD next_key
894 
895 static int map_get_next_key(union bpf_attr *attr)
896 {
897 	void __user *ukey = u64_to_user_ptr(attr->key);
898 	void __user *unext_key = u64_to_user_ptr(attr->next_key);
899 	int ufd = attr->map_fd;
900 	struct bpf_map *map;
901 	void *key, *next_key;
902 	struct fd f;
903 	int err;
904 
905 	if (CHECK_ATTR(BPF_MAP_GET_NEXT_KEY))
906 		return -EINVAL;
907 
908 	f = fdget(ufd);
909 	map = __bpf_map_get(f);
910 	if (IS_ERR(map))
911 		return PTR_ERR(map);
912 
913 	if (!(f.file->f_mode & FMODE_CAN_READ)) {
914 		err = -EPERM;
915 		goto err_put;
916 	}
917 
918 	if (ukey) {
919 		key = memdup_user(ukey, map->key_size);
920 		if (IS_ERR(key)) {
921 			err = PTR_ERR(key);
922 			goto err_put;
923 		}
924 	} else {
925 		key = NULL;
926 	}
927 
928 	err = -ENOMEM;
929 	next_key = kmalloc(map->key_size, GFP_USER);
930 	if (!next_key)
931 		goto free_key;
932 
933 	if (bpf_map_is_dev_bound(map)) {
934 		err = bpf_map_offload_get_next_key(map, key, next_key);
935 		goto out;
936 	}
937 
938 	rcu_read_lock();
939 	err = map->ops->map_get_next_key(map, key, next_key);
940 	rcu_read_unlock();
941 out:
942 	if (err)
943 		goto free_next_key;
944 
945 	err = -EFAULT;
946 	if (copy_to_user(unext_key, next_key, map->key_size) != 0)
947 		goto free_next_key;
948 
949 	err = 0;
950 
951 free_next_key:
952 	kfree(next_key);
953 free_key:
954 	kfree(key);
955 err_put:
956 	fdput(f);
957 	return err;
958 }
959 
960 static const struct bpf_prog_ops * const bpf_prog_types[] = {
961 #define BPF_PROG_TYPE(_id, _name) \
962 	[_id] = & _name ## _prog_ops,
963 #define BPF_MAP_TYPE(_id, _ops)
964 #include <linux/bpf_types.h>
965 #undef BPF_PROG_TYPE
966 #undef BPF_MAP_TYPE
967 };
968 
969 static int find_prog_type(enum bpf_prog_type type, struct bpf_prog *prog)
970 {
971 	const struct bpf_prog_ops *ops;
972 
973 	if (type >= ARRAY_SIZE(bpf_prog_types))
974 		return -EINVAL;
975 	type = array_index_nospec(type, ARRAY_SIZE(bpf_prog_types));
976 	ops = bpf_prog_types[type];
977 	if (!ops)
978 		return -EINVAL;
979 
980 	if (!bpf_prog_is_dev_bound(prog->aux))
981 		prog->aux->ops = ops;
982 	else
983 		prog->aux->ops = &bpf_offload_prog_ops;
984 	prog->type = type;
985 	return 0;
986 }
987 
988 /* drop refcnt on maps used by eBPF program and free auxilary data */
989 static void free_used_maps(struct bpf_prog_aux *aux)
990 {
991 	int i;
992 
993 	if (aux->cgroup_storage)
994 		bpf_cgroup_storage_release(aux->prog, aux->cgroup_storage);
995 
996 	for (i = 0; i < aux->used_map_cnt; i++)
997 		bpf_map_put(aux->used_maps[i]);
998 
999 	kfree(aux->used_maps);
1000 }
1001 
1002 int __bpf_prog_charge(struct user_struct *user, u32 pages)
1003 {
1004 	unsigned long memlock_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
1005 	unsigned long user_bufs;
1006 
1007 	if (user) {
1008 		user_bufs = atomic_long_add_return(pages, &user->locked_vm);
1009 		if (user_bufs > memlock_limit) {
1010 			atomic_long_sub(pages, &user->locked_vm);
1011 			return -EPERM;
1012 		}
1013 	}
1014 
1015 	return 0;
1016 }
1017 
1018 void __bpf_prog_uncharge(struct user_struct *user, u32 pages)
1019 {
1020 	if (user)
1021 		atomic_long_sub(pages, &user->locked_vm);
1022 }
1023 
1024 static int bpf_prog_charge_memlock(struct bpf_prog *prog)
1025 {
1026 	struct user_struct *user = get_current_user();
1027 	int ret;
1028 
1029 	ret = __bpf_prog_charge(user, prog->pages);
1030 	if (ret) {
1031 		free_uid(user);
1032 		return ret;
1033 	}
1034 
1035 	prog->aux->user = user;
1036 	return 0;
1037 }
1038 
1039 static void bpf_prog_uncharge_memlock(struct bpf_prog *prog)
1040 {
1041 	struct user_struct *user = prog->aux->user;
1042 
1043 	__bpf_prog_uncharge(user, prog->pages);
1044 	free_uid(user);
1045 }
1046 
1047 static int bpf_prog_alloc_id(struct bpf_prog *prog)
1048 {
1049 	int id;
1050 
1051 	idr_preload(GFP_KERNEL);
1052 	spin_lock_bh(&prog_idr_lock);
1053 	id = idr_alloc_cyclic(&prog_idr, prog, 1, INT_MAX, GFP_ATOMIC);
1054 	if (id > 0)
1055 		prog->aux->id = id;
1056 	spin_unlock_bh(&prog_idr_lock);
1057 	idr_preload_end();
1058 
1059 	/* id is in [1, INT_MAX) */
1060 	if (WARN_ON_ONCE(!id))
1061 		return -ENOSPC;
1062 
1063 	return id > 0 ? 0 : id;
1064 }
1065 
1066 void bpf_prog_free_id(struct bpf_prog *prog, bool do_idr_lock)
1067 {
1068 	/* cBPF to eBPF migrations are currently not in the idr store.
1069 	 * Offloaded programs are removed from the store when their device
1070 	 * disappears - even if someone grabs an fd to them they are unusable,
1071 	 * simply waiting for refcnt to drop to be freed.
1072 	 */
1073 	if (!prog->aux->id)
1074 		return;
1075 
1076 	if (do_idr_lock)
1077 		spin_lock_bh(&prog_idr_lock);
1078 	else
1079 		__acquire(&prog_idr_lock);
1080 
1081 	idr_remove(&prog_idr, prog->aux->id);
1082 	prog->aux->id = 0;
1083 
1084 	if (do_idr_lock)
1085 		spin_unlock_bh(&prog_idr_lock);
1086 	else
1087 		__release(&prog_idr_lock);
1088 }
1089 
1090 static void __bpf_prog_put_rcu(struct rcu_head *rcu)
1091 {
1092 	struct bpf_prog_aux *aux = container_of(rcu, struct bpf_prog_aux, rcu);
1093 
1094 	free_used_maps(aux);
1095 	bpf_prog_uncharge_memlock(aux->prog);
1096 	security_bpf_prog_free(aux);
1097 	bpf_prog_free(aux->prog);
1098 }
1099 
1100 static void __bpf_prog_put(struct bpf_prog *prog, bool do_idr_lock)
1101 {
1102 	if (atomic_dec_and_test(&prog->aux->refcnt)) {
1103 		/* bpf_prog_free_id() must be called first */
1104 		bpf_prog_free_id(prog, do_idr_lock);
1105 		bpf_prog_kallsyms_del_all(prog);
1106 
1107 		call_rcu(&prog->aux->rcu, __bpf_prog_put_rcu);
1108 	}
1109 }
1110 
1111 void bpf_prog_put(struct bpf_prog *prog)
1112 {
1113 	__bpf_prog_put(prog, true);
1114 }
1115 EXPORT_SYMBOL_GPL(bpf_prog_put);
1116 
1117 static int bpf_prog_release(struct inode *inode, struct file *filp)
1118 {
1119 	struct bpf_prog *prog = filp->private_data;
1120 
1121 	bpf_prog_put(prog);
1122 	return 0;
1123 }
1124 
1125 #ifdef CONFIG_PROC_FS
1126 static void bpf_prog_show_fdinfo(struct seq_file *m, struct file *filp)
1127 {
1128 	const struct bpf_prog *prog = filp->private_data;
1129 	char prog_tag[sizeof(prog->tag) * 2 + 1] = { };
1130 
1131 	bin2hex(prog_tag, prog->tag, sizeof(prog->tag));
1132 	seq_printf(m,
1133 		   "prog_type:\t%u\n"
1134 		   "prog_jited:\t%u\n"
1135 		   "prog_tag:\t%s\n"
1136 		   "memlock:\t%llu\n"
1137 		   "prog_id:\t%u\n",
1138 		   prog->type,
1139 		   prog->jited,
1140 		   prog_tag,
1141 		   prog->pages * 1ULL << PAGE_SHIFT,
1142 		   prog->aux->id);
1143 }
1144 #endif
1145 
1146 const struct file_operations bpf_prog_fops = {
1147 #ifdef CONFIG_PROC_FS
1148 	.show_fdinfo	= bpf_prog_show_fdinfo,
1149 #endif
1150 	.release	= bpf_prog_release,
1151 	.read		= bpf_dummy_read,
1152 	.write		= bpf_dummy_write,
1153 };
1154 
1155 int bpf_prog_new_fd(struct bpf_prog *prog)
1156 {
1157 	int ret;
1158 
1159 	ret = security_bpf_prog(prog);
1160 	if (ret < 0)
1161 		return ret;
1162 
1163 	return anon_inode_getfd("bpf-prog", &bpf_prog_fops, prog,
1164 				O_RDWR | O_CLOEXEC);
1165 }
1166 
1167 static struct bpf_prog *____bpf_prog_get(struct fd f)
1168 {
1169 	if (!f.file)
1170 		return ERR_PTR(-EBADF);
1171 	if (f.file->f_op != &bpf_prog_fops) {
1172 		fdput(f);
1173 		return ERR_PTR(-EINVAL);
1174 	}
1175 
1176 	return f.file->private_data;
1177 }
1178 
1179 struct bpf_prog *bpf_prog_add(struct bpf_prog *prog, int i)
1180 {
1181 	if (atomic_add_return(i, &prog->aux->refcnt) > BPF_MAX_REFCNT) {
1182 		atomic_sub(i, &prog->aux->refcnt);
1183 		return ERR_PTR(-EBUSY);
1184 	}
1185 	return prog;
1186 }
1187 EXPORT_SYMBOL_GPL(bpf_prog_add);
1188 
1189 void bpf_prog_sub(struct bpf_prog *prog, int i)
1190 {
1191 	/* Only to be used for undoing previous bpf_prog_add() in some
1192 	 * error path. We still know that another entity in our call
1193 	 * path holds a reference to the program, thus atomic_sub() can
1194 	 * be safely used in such cases!
1195 	 */
1196 	WARN_ON(atomic_sub_return(i, &prog->aux->refcnt) == 0);
1197 }
1198 EXPORT_SYMBOL_GPL(bpf_prog_sub);
1199 
1200 struct bpf_prog *bpf_prog_inc(struct bpf_prog *prog)
1201 {
1202 	return bpf_prog_add(prog, 1);
1203 }
1204 EXPORT_SYMBOL_GPL(bpf_prog_inc);
1205 
1206 /* prog_idr_lock should have been held */
1207 struct bpf_prog *bpf_prog_inc_not_zero(struct bpf_prog *prog)
1208 {
1209 	int refold;
1210 
1211 	refold = atomic_fetch_add_unless(&prog->aux->refcnt, 1, 0);
1212 
1213 	if (refold >= BPF_MAX_REFCNT) {
1214 		__bpf_prog_put(prog, false);
1215 		return ERR_PTR(-EBUSY);
1216 	}
1217 
1218 	if (!refold)
1219 		return ERR_PTR(-ENOENT);
1220 
1221 	return prog;
1222 }
1223 EXPORT_SYMBOL_GPL(bpf_prog_inc_not_zero);
1224 
1225 bool bpf_prog_get_ok(struct bpf_prog *prog,
1226 			    enum bpf_prog_type *attach_type, bool attach_drv)
1227 {
1228 	/* not an attachment, just a refcount inc, always allow */
1229 	if (!attach_type)
1230 		return true;
1231 
1232 	if (prog->type != *attach_type)
1233 		return false;
1234 	if (bpf_prog_is_dev_bound(prog->aux) && !attach_drv)
1235 		return false;
1236 
1237 	return true;
1238 }
1239 
1240 static struct bpf_prog *__bpf_prog_get(u32 ufd, enum bpf_prog_type *attach_type,
1241 				       bool attach_drv)
1242 {
1243 	struct fd f = fdget(ufd);
1244 	struct bpf_prog *prog;
1245 
1246 	prog = ____bpf_prog_get(f);
1247 	if (IS_ERR(prog))
1248 		return prog;
1249 	if (!bpf_prog_get_ok(prog, attach_type, attach_drv)) {
1250 		prog = ERR_PTR(-EINVAL);
1251 		goto out;
1252 	}
1253 
1254 	prog = bpf_prog_inc(prog);
1255 out:
1256 	fdput(f);
1257 	return prog;
1258 }
1259 
1260 struct bpf_prog *bpf_prog_get(u32 ufd)
1261 {
1262 	return __bpf_prog_get(ufd, NULL, false);
1263 }
1264 
1265 struct bpf_prog *bpf_prog_get_type_dev(u32 ufd, enum bpf_prog_type type,
1266 				       bool attach_drv)
1267 {
1268 	return __bpf_prog_get(ufd, &type, attach_drv);
1269 }
1270 EXPORT_SYMBOL_GPL(bpf_prog_get_type_dev);
1271 
1272 /* Initially all BPF programs could be loaded w/o specifying
1273  * expected_attach_type. Later for some of them specifying expected_attach_type
1274  * at load time became required so that program could be validated properly.
1275  * Programs of types that are allowed to be loaded both w/ and w/o (for
1276  * backward compatibility) expected_attach_type, should have the default attach
1277  * type assigned to expected_attach_type for the latter case, so that it can be
1278  * validated later at attach time.
1279  *
1280  * bpf_prog_load_fixup_attach_type() sets expected_attach_type in @attr if
1281  * prog type requires it but has some attach types that have to be backward
1282  * compatible.
1283  */
1284 static void bpf_prog_load_fixup_attach_type(union bpf_attr *attr)
1285 {
1286 	switch (attr->prog_type) {
1287 	case BPF_PROG_TYPE_CGROUP_SOCK:
1288 		/* Unfortunately BPF_ATTACH_TYPE_UNSPEC enumeration doesn't
1289 		 * exist so checking for non-zero is the way to go here.
1290 		 */
1291 		if (!attr->expected_attach_type)
1292 			attr->expected_attach_type =
1293 				BPF_CGROUP_INET_SOCK_CREATE;
1294 		break;
1295 	}
1296 }
1297 
1298 static int
1299 bpf_prog_load_check_attach_type(enum bpf_prog_type prog_type,
1300 				enum bpf_attach_type expected_attach_type)
1301 {
1302 	switch (prog_type) {
1303 	case BPF_PROG_TYPE_CGROUP_SOCK:
1304 		switch (expected_attach_type) {
1305 		case BPF_CGROUP_INET_SOCK_CREATE:
1306 		case BPF_CGROUP_INET4_POST_BIND:
1307 		case BPF_CGROUP_INET6_POST_BIND:
1308 			return 0;
1309 		default:
1310 			return -EINVAL;
1311 		}
1312 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
1313 		switch (expected_attach_type) {
1314 		case BPF_CGROUP_INET4_BIND:
1315 		case BPF_CGROUP_INET6_BIND:
1316 		case BPF_CGROUP_INET4_CONNECT:
1317 		case BPF_CGROUP_INET6_CONNECT:
1318 		case BPF_CGROUP_UDP4_SENDMSG:
1319 		case BPF_CGROUP_UDP6_SENDMSG:
1320 			return 0;
1321 		default:
1322 			return -EINVAL;
1323 		}
1324 	default:
1325 		return 0;
1326 	}
1327 }
1328 
1329 /* last field in 'union bpf_attr' used by this command */
1330 #define	BPF_PROG_LOAD_LAST_FIELD expected_attach_type
1331 
1332 static int bpf_prog_load(union bpf_attr *attr)
1333 {
1334 	enum bpf_prog_type type = attr->prog_type;
1335 	struct bpf_prog *prog;
1336 	int err;
1337 	char license[128];
1338 	bool is_gpl;
1339 
1340 	if (CHECK_ATTR(BPF_PROG_LOAD))
1341 		return -EINVAL;
1342 
1343 	if (attr->prog_flags & ~BPF_F_STRICT_ALIGNMENT)
1344 		return -EINVAL;
1345 
1346 	/* copy eBPF program license from user space */
1347 	if (strncpy_from_user(license, u64_to_user_ptr(attr->license),
1348 			      sizeof(license) - 1) < 0)
1349 		return -EFAULT;
1350 	license[sizeof(license) - 1] = 0;
1351 
1352 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
1353 	is_gpl = license_is_gpl_compatible(license);
1354 
1355 	if (attr->insn_cnt == 0 || attr->insn_cnt > BPF_MAXINSNS)
1356 		return -E2BIG;
1357 
1358 	if (type == BPF_PROG_TYPE_KPROBE &&
1359 	    attr->kern_version != LINUX_VERSION_CODE)
1360 		return -EINVAL;
1361 
1362 	if (type != BPF_PROG_TYPE_SOCKET_FILTER &&
1363 	    type != BPF_PROG_TYPE_CGROUP_SKB &&
1364 	    !capable(CAP_SYS_ADMIN))
1365 		return -EPERM;
1366 
1367 	bpf_prog_load_fixup_attach_type(attr);
1368 	if (bpf_prog_load_check_attach_type(type, attr->expected_attach_type))
1369 		return -EINVAL;
1370 
1371 	/* plain bpf_prog allocation */
1372 	prog = bpf_prog_alloc(bpf_prog_size(attr->insn_cnt), GFP_USER);
1373 	if (!prog)
1374 		return -ENOMEM;
1375 
1376 	prog->expected_attach_type = attr->expected_attach_type;
1377 
1378 	prog->aux->offload_requested = !!attr->prog_ifindex;
1379 
1380 	err = security_bpf_prog_alloc(prog->aux);
1381 	if (err)
1382 		goto free_prog_nouncharge;
1383 
1384 	err = bpf_prog_charge_memlock(prog);
1385 	if (err)
1386 		goto free_prog_sec;
1387 
1388 	prog->len = attr->insn_cnt;
1389 
1390 	err = -EFAULT;
1391 	if (copy_from_user(prog->insns, u64_to_user_ptr(attr->insns),
1392 			   bpf_prog_insn_size(prog)) != 0)
1393 		goto free_prog;
1394 
1395 	prog->orig_prog = NULL;
1396 	prog->jited = 0;
1397 
1398 	atomic_set(&prog->aux->refcnt, 1);
1399 	prog->gpl_compatible = is_gpl ? 1 : 0;
1400 
1401 	if (bpf_prog_is_dev_bound(prog->aux)) {
1402 		err = bpf_prog_offload_init(prog, attr);
1403 		if (err)
1404 			goto free_prog;
1405 	}
1406 
1407 	/* find program type: socket_filter vs tracing_filter */
1408 	err = find_prog_type(type, prog);
1409 	if (err < 0)
1410 		goto free_prog;
1411 
1412 	prog->aux->load_time = ktime_get_boot_ns();
1413 	err = bpf_obj_name_cpy(prog->aux->name, attr->prog_name);
1414 	if (err)
1415 		goto free_prog;
1416 
1417 	/* run eBPF verifier */
1418 	err = bpf_check(&prog, attr);
1419 	if (err < 0)
1420 		goto free_used_maps;
1421 
1422 	prog = bpf_prog_select_runtime(prog, &err);
1423 	if (err < 0)
1424 		goto free_used_maps;
1425 
1426 	err = bpf_prog_alloc_id(prog);
1427 	if (err)
1428 		goto free_used_maps;
1429 
1430 	err = bpf_prog_new_fd(prog);
1431 	if (err < 0) {
1432 		/* failed to allocate fd.
1433 		 * bpf_prog_put() is needed because the above
1434 		 * bpf_prog_alloc_id() has published the prog
1435 		 * to the userspace and the userspace may
1436 		 * have refcnt-ed it through BPF_PROG_GET_FD_BY_ID.
1437 		 */
1438 		bpf_prog_put(prog);
1439 		return err;
1440 	}
1441 
1442 	bpf_prog_kallsyms_add(prog);
1443 	return err;
1444 
1445 free_used_maps:
1446 	bpf_prog_kallsyms_del_subprogs(prog);
1447 	free_used_maps(prog->aux);
1448 free_prog:
1449 	bpf_prog_uncharge_memlock(prog);
1450 free_prog_sec:
1451 	security_bpf_prog_free(prog->aux);
1452 free_prog_nouncharge:
1453 	bpf_prog_free(prog);
1454 	return err;
1455 }
1456 
1457 #define BPF_OBJ_LAST_FIELD file_flags
1458 
1459 static int bpf_obj_pin(const union bpf_attr *attr)
1460 {
1461 	if (CHECK_ATTR(BPF_OBJ) || attr->file_flags != 0)
1462 		return -EINVAL;
1463 
1464 	return bpf_obj_pin_user(attr->bpf_fd, u64_to_user_ptr(attr->pathname));
1465 }
1466 
1467 static int bpf_obj_get(const union bpf_attr *attr)
1468 {
1469 	if (CHECK_ATTR(BPF_OBJ) || attr->bpf_fd != 0 ||
1470 	    attr->file_flags & ~BPF_OBJ_FLAG_MASK)
1471 		return -EINVAL;
1472 
1473 	return bpf_obj_get_user(u64_to_user_ptr(attr->pathname),
1474 				attr->file_flags);
1475 }
1476 
1477 struct bpf_raw_tracepoint {
1478 	struct bpf_raw_event_map *btp;
1479 	struct bpf_prog *prog;
1480 };
1481 
1482 static int bpf_raw_tracepoint_release(struct inode *inode, struct file *filp)
1483 {
1484 	struct bpf_raw_tracepoint *raw_tp = filp->private_data;
1485 
1486 	if (raw_tp->prog) {
1487 		bpf_probe_unregister(raw_tp->btp, raw_tp->prog);
1488 		bpf_prog_put(raw_tp->prog);
1489 	}
1490 	kfree(raw_tp);
1491 	return 0;
1492 }
1493 
1494 static const struct file_operations bpf_raw_tp_fops = {
1495 	.release	= bpf_raw_tracepoint_release,
1496 	.read		= bpf_dummy_read,
1497 	.write		= bpf_dummy_write,
1498 };
1499 
1500 #define BPF_RAW_TRACEPOINT_OPEN_LAST_FIELD raw_tracepoint.prog_fd
1501 
1502 static int bpf_raw_tracepoint_open(const union bpf_attr *attr)
1503 {
1504 	struct bpf_raw_tracepoint *raw_tp;
1505 	struct bpf_raw_event_map *btp;
1506 	struct bpf_prog *prog;
1507 	char tp_name[128];
1508 	int tp_fd, err;
1509 
1510 	if (strncpy_from_user(tp_name, u64_to_user_ptr(attr->raw_tracepoint.name),
1511 			      sizeof(tp_name) - 1) < 0)
1512 		return -EFAULT;
1513 	tp_name[sizeof(tp_name) - 1] = 0;
1514 
1515 	btp = bpf_find_raw_tracepoint(tp_name);
1516 	if (!btp)
1517 		return -ENOENT;
1518 
1519 	raw_tp = kzalloc(sizeof(*raw_tp), GFP_USER);
1520 	if (!raw_tp)
1521 		return -ENOMEM;
1522 	raw_tp->btp = btp;
1523 
1524 	prog = bpf_prog_get_type(attr->raw_tracepoint.prog_fd,
1525 				 BPF_PROG_TYPE_RAW_TRACEPOINT);
1526 	if (IS_ERR(prog)) {
1527 		err = PTR_ERR(prog);
1528 		goto out_free_tp;
1529 	}
1530 
1531 	err = bpf_probe_register(raw_tp->btp, prog);
1532 	if (err)
1533 		goto out_put_prog;
1534 
1535 	raw_tp->prog = prog;
1536 	tp_fd = anon_inode_getfd("bpf-raw-tracepoint", &bpf_raw_tp_fops, raw_tp,
1537 				 O_CLOEXEC);
1538 	if (tp_fd < 0) {
1539 		bpf_probe_unregister(raw_tp->btp, prog);
1540 		err = tp_fd;
1541 		goto out_put_prog;
1542 	}
1543 	return tp_fd;
1544 
1545 out_put_prog:
1546 	bpf_prog_put(prog);
1547 out_free_tp:
1548 	kfree(raw_tp);
1549 	return err;
1550 }
1551 
1552 static int bpf_prog_attach_check_attach_type(const struct bpf_prog *prog,
1553 					     enum bpf_attach_type attach_type)
1554 {
1555 	switch (prog->type) {
1556 	case BPF_PROG_TYPE_CGROUP_SOCK:
1557 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
1558 		return attach_type == prog->expected_attach_type ? 0 : -EINVAL;
1559 	default:
1560 		return 0;
1561 	}
1562 }
1563 
1564 #define BPF_PROG_ATTACH_LAST_FIELD attach_flags
1565 
1566 #define BPF_F_ATTACH_MASK \
1567 	(BPF_F_ALLOW_OVERRIDE | BPF_F_ALLOW_MULTI)
1568 
1569 static int bpf_prog_attach(const union bpf_attr *attr)
1570 {
1571 	enum bpf_prog_type ptype;
1572 	struct bpf_prog *prog;
1573 	int ret;
1574 
1575 	if (!capable(CAP_NET_ADMIN))
1576 		return -EPERM;
1577 
1578 	if (CHECK_ATTR(BPF_PROG_ATTACH))
1579 		return -EINVAL;
1580 
1581 	if (attr->attach_flags & ~BPF_F_ATTACH_MASK)
1582 		return -EINVAL;
1583 
1584 	switch (attr->attach_type) {
1585 	case BPF_CGROUP_INET_INGRESS:
1586 	case BPF_CGROUP_INET_EGRESS:
1587 		ptype = BPF_PROG_TYPE_CGROUP_SKB;
1588 		break;
1589 	case BPF_CGROUP_INET_SOCK_CREATE:
1590 	case BPF_CGROUP_INET4_POST_BIND:
1591 	case BPF_CGROUP_INET6_POST_BIND:
1592 		ptype = BPF_PROG_TYPE_CGROUP_SOCK;
1593 		break;
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 		ptype = BPF_PROG_TYPE_CGROUP_SOCK_ADDR;
1601 		break;
1602 	case BPF_CGROUP_SOCK_OPS:
1603 		ptype = BPF_PROG_TYPE_SOCK_OPS;
1604 		break;
1605 	case BPF_CGROUP_DEVICE:
1606 		ptype = BPF_PROG_TYPE_CGROUP_DEVICE;
1607 		break;
1608 	case BPF_SK_MSG_VERDICT:
1609 		ptype = BPF_PROG_TYPE_SK_MSG;
1610 		break;
1611 	case BPF_SK_SKB_STREAM_PARSER:
1612 	case BPF_SK_SKB_STREAM_VERDICT:
1613 		ptype = BPF_PROG_TYPE_SK_SKB;
1614 		break;
1615 	case BPF_LIRC_MODE2:
1616 		ptype = BPF_PROG_TYPE_LIRC_MODE2;
1617 		break;
1618 	default:
1619 		return -EINVAL;
1620 	}
1621 
1622 	prog = bpf_prog_get_type(attr->attach_bpf_fd, ptype);
1623 	if (IS_ERR(prog))
1624 		return PTR_ERR(prog);
1625 
1626 	if (bpf_prog_attach_check_attach_type(prog, attr->attach_type)) {
1627 		bpf_prog_put(prog);
1628 		return -EINVAL;
1629 	}
1630 
1631 	switch (ptype) {
1632 	case BPF_PROG_TYPE_SK_SKB:
1633 	case BPF_PROG_TYPE_SK_MSG:
1634 		ret = sockmap_get_from_fd(attr, ptype, prog);
1635 		break;
1636 	case BPF_PROG_TYPE_LIRC_MODE2:
1637 		ret = lirc_prog_attach(attr, prog);
1638 		break;
1639 	default:
1640 		ret = cgroup_bpf_prog_attach(attr, ptype, prog);
1641 	}
1642 
1643 	if (ret)
1644 		bpf_prog_put(prog);
1645 	return ret;
1646 }
1647 
1648 #define BPF_PROG_DETACH_LAST_FIELD attach_type
1649 
1650 static int bpf_prog_detach(const union bpf_attr *attr)
1651 {
1652 	enum bpf_prog_type ptype;
1653 
1654 	if (!capable(CAP_NET_ADMIN))
1655 		return -EPERM;
1656 
1657 	if (CHECK_ATTR(BPF_PROG_DETACH))
1658 		return -EINVAL;
1659 
1660 	switch (attr->attach_type) {
1661 	case BPF_CGROUP_INET_INGRESS:
1662 	case BPF_CGROUP_INET_EGRESS:
1663 		ptype = BPF_PROG_TYPE_CGROUP_SKB;
1664 		break;
1665 	case BPF_CGROUP_INET_SOCK_CREATE:
1666 	case BPF_CGROUP_INET4_POST_BIND:
1667 	case BPF_CGROUP_INET6_POST_BIND:
1668 		ptype = BPF_PROG_TYPE_CGROUP_SOCK;
1669 		break;
1670 	case BPF_CGROUP_INET4_BIND:
1671 	case BPF_CGROUP_INET6_BIND:
1672 	case BPF_CGROUP_INET4_CONNECT:
1673 	case BPF_CGROUP_INET6_CONNECT:
1674 	case BPF_CGROUP_UDP4_SENDMSG:
1675 	case BPF_CGROUP_UDP6_SENDMSG:
1676 		ptype = BPF_PROG_TYPE_CGROUP_SOCK_ADDR;
1677 		break;
1678 	case BPF_CGROUP_SOCK_OPS:
1679 		ptype = BPF_PROG_TYPE_SOCK_OPS;
1680 		break;
1681 	case BPF_CGROUP_DEVICE:
1682 		ptype = BPF_PROG_TYPE_CGROUP_DEVICE;
1683 		break;
1684 	case BPF_SK_MSG_VERDICT:
1685 		return sockmap_get_from_fd(attr, BPF_PROG_TYPE_SK_MSG, NULL);
1686 	case BPF_SK_SKB_STREAM_PARSER:
1687 	case BPF_SK_SKB_STREAM_VERDICT:
1688 		return sockmap_get_from_fd(attr, BPF_PROG_TYPE_SK_SKB, NULL);
1689 	case BPF_LIRC_MODE2:
1690 		return lirc_prog_detach(attr);
1691 	default:
1692 		return -EINVAL;
1693 	}
1694 
1695 	return cgroup_bpf_prog_detach(attr, ptype);
1696 }
1697 
1698 #define BPF_PROG_QUERY_LAST_FIELD query.prog_cnt
1699 
1700 static int bpf_prog_query(const union bpf_attr *attr,
1701 			  union bpf_attr __user *uattr)
1702 {
1703 	if (!capable(CAP_NET_ADMIN))
1704 		return -EPERM;
1705 	if (CHECK_ATTR(BPF_PROG_QUERY))
1706 		return -EINVAL;
1707 	if (attr->query.query_flags & ~BPF_F_QUERY_EFFECTIVE)
1708 		return -EINVAL;
1709 
1710 	switch (attr->query.attach_type) {
1711 	case BPF_CGROUP_INET_INGRESS:
1712 	case BPF_CGROUP_INET_EGRESS:
1713 	case BPF_CGROUP_INET_SOCK_CREATE:
1714 	case BPF_CGROUP_INET4_BIND:
1715 	case BPF_CGROUP_INET6_BIND:
1716 	case BPF_CGROUP_INET4_POST_BIND:
1717 	case BPF_CGROUP_INET6_POST_BIND:
1718 	case BPF_CGROUP_INET4_CONNECT:
1719 	case BPF_CGROUP_INET6_CONNECT:
1720 	case BPF_CGROUP_UDP4_SENDMSG:
1721 	case BPF_CGROUP_UDP6_SENDMSG:
1722 	case BPF_CGROUP_SOCK_OPS:
1723 	case BPF_CGROUP_DEVICE:
1724 		break;
1725 	case BPF_LIRC_MODE2:
1726 		return lirc_prog_query(attr, uattr);
1727 	default:
1728 		return -EINVAL;
1729 	}
1730 
1731 	return cgroup_bpf_prog_query(attr, uattr);
1732 }
1733 
1734 #define BPF_PROG_TEST_RUN_LAST_FIELD test.duration
1735 
1736 static int bpf_prog_test_run(const union bpf_attr *attr,
1737 			     union bpf_attr __user *uattr)
1738 {
1739 	struct bpf_prog *prog;
1740 	int ret = -ENOTSUPP;
1741 
1742 	if (!capable(CAP_SYS_ADMIN))
1743 		return -EPERM;
1744 	if (CHECK_ATTR(BPF_PROG_TEST_RUN))
1745 		return -EINVAL;
1746 
1747 	prog = bpf_prog_get(attr->test.prog_fd);
1748 	if (IS_ERR(prog))
1749 		return PTR_ERR(prog);
1750 
1751 	if (prog->aux->ops->test_run)
1752 		ret = prog->aux->ops->test_run(prog, attr, uattr);
1753 
1754 	bpf_prog_put(prog);
1755 	return ret;
1756 }
1757 
1758 #define BPF_OBJ_GET_NEXT_ID_LAST_FIELD next_id
1759 
1760 static int bpf_obj_get_next_id(const union bpf_attr *attr,
1761 			       union bpf_attr __user *uattr,
1762 			       struct idr *idr,
1763 			       spinlock_t *lock)
1764 {
1765 	u32 next_id = attr->start_id;
1766 	int err = 0;
1767 
1768 	if (CHECK_ATTR(BPF_OBJ_GET_NEXT_ID) || next_id >= INT_MAX)
1769 		return -EINVAL;
1770 
1771 	if (!capable(CAP_SYS_ADMIN))
1772 		return -EPERM;
1773 
1774 	next_id++;
1775 	spin_lock_bh(lock);
1776 	if (!idr_get_next(idr, &next_id))
1777 		err = -ENOENT;
1778 	spin_unlock_bh(lock);
1779 
1780 	if (!err)
1781 		err = put_user(next_id, &uattr->next_id);
1782 
1783 	return err;
1784 }
1785 
1786 #define BPF_PROG_GET_FD_BY_ID_LAST_FIELD prog_id
1787 
1788 static int bpf_prog_get_fd_by_id(const union bpf_attr *attr)
1789 {
1790 	struct bpf_prog *prog;
1791 	u32 id = attr->prog_id;
1792 	int fd;
1793 
1794 	if (CHECK_ATTR(BPF_PROG_GET_FD_BY_ID))
1795 		return -EINVAL;
1796 
1797 	if (!capable(CAP_SYS_ADMIN))
1798 		return -EPERM;
1799 
1800 	spin_lock_bh(&prog_idr_lock);
1801 	prog = idr_find(&prog_idr, id);
1802 	if (prog)
1803 		prog = bpf_prog_inc_not_zero(prog);
1804 	else
1805 		prog = ERR_PTR(-ENOENT);
1806 	spin_unlock_bh(&prog_idr_lock);
1807 
1808 	if (IS_ERR(prog))
1809 		return PTR_ERR(prog);
1810 
1811 	fd = bpf_prog_new_fd(prog);
1812 	if (fd < 0)
1813 		bpf_prog_put(prog);
1814 
1815 	return fd;
1816 }
1817 
1818 #define BPF_MAP_GET_FD_BY_ID_LAST_FIELD open_flags
1819 
1820 static int bpf_map_get_fd_by_id(const union bpf_attr *attr)
1821 {
1822 	struct bpf_map *map;
1823 	u32 id = attr->map_id;
1824 	int f_flags;
1825 	int fd;
1826 
1827 	if (CHECK_ATTR(BPF_MAP_GET_FD_BY_ID) ||
1828 	    attr->open_flags & ~BPF_OBJ_FLAG_MASK)
1829 		return -EINVAL;
1830 
1831 	if (!capable(CAP_SYS_ADMIN))
1832 		return -EPERM;
1833 
1834 	f_flags = bpf_get_file_flag(attr->open_flags);
1835 	if (f_flags < 0)
1836 		return f_flags;
1837 
1838 	spin_lock_bh(&map_idr_lock);
1839 	map = idr_find(&map_idr, id);
1840 	if (map)
1841 		map = bpf_map_inc_not_zero(map, true);
1842 	else
1843 		map = ERR_PTR(-ENOENT);
1844 	spin_unlock_bh(&map_idr_lock);
1845 
1846 	if (IS_ERR(map))
1847 		return PTR_ERR(map);
1848 
1849 	fd = bpf_map_new_fd(map, f_flags);
1850 	if (fd < 0)
1851 		bpf_map_put(map);
1852 
1853 	return fd;
1854 }
1855 
1856 static const struct bpf_map *bpf_map_from_imm(const struct bpf_prog *prog,
1857 					      unsigned long addr)
1858 {
1859 	int i;
1860 
1861 	for (i = 0; i < prog->aux->used_map_cnt; i++)
1862 		if (prog->aux->used_maps[i] == (void *)addr)
1863 			return prog->aux->used_maps[i];
1864 	return NULL;
1865 }
1866 
1867 static struct bpf_insn *bpf_insn_prepare_dump(const struct bpf_prog *prog)
1868 {
1869 	const struct bpf_map *map;
1870 	struct bpf_insn *insns;
1871 	u64 imm;
1872 	int i;
1873 
1874 	insns = kmemdup(prog->insnsi, bpf_prog_insn_size(prog),
1875 			GFP_USER);
1876 	if (!insns)
1877 		return insns;
1878 
1879 	for (i = 0; i < prog->len; i++) {
1880 		if (insns[i].code == (BPF_JMP | BPF_TAIL_CALL)) {
1881 			insns[i].code = BPF_JMP | BPF_CALL;
1882 			insns[i].imm = BPF_FUNC_tail_call;
1883 			/* fall-through */
1884 		}
1885 		if (insns[i].code == (BPF_JMP | BPF_CALL) ||
1886 		    insns[i].code == (BPF_JMP | BPF_CALL_ARGS)) {
1887 			if (insns[i].code == (BPF_JMP | BPF_CALL_ARGS))
1888 				insns[i].code = BPF_JMP | BPF_CALL;
1889 			if (!bpf_dump_raw_ok())
1890 				insns[i].imm = 0;
1891 			continue;
1892 		}
1893 
1894 		if (insns[i].code != (BPF_LD | BPF_IMM | BPF_DW))
1895 			continue;
1896 
1897 		imm = ((u64)insns[i + 1].imm << 32) | (u32)insns[i].imm;
1898 		map = bpf_map_from_imm(prog, imm);
1899 		if (map) {
1900 			insns[i].src_reg = BPF_PSEUDO_MAP_FD;
1901 			insns[i].imm = map->id;
1902 			insns[i + 1].imm = 0;
1903 			continue;
1904 		}
1905 
1906 		if (!bpf_dump_raw_ok() &&
1907 		    imm == (unsigned long)prog->aux) {
1908 			insns[i].imm = 0;
1909 			insns[i + 1].imm = 0;
1910 			continue;
1911 		}
1912 	}
1913 
1914 	return insns;
1915 }
1916 
1917 static int bpf_prog_get_info_by_fd(struct bpf_prog *prog,
1918 				   const union bpf_attr *attr,
1919 				   union bpf_attr __user *uattr)
1920 {
1921 	struct bpf_prog_info __user *uinfo = u64_to_user_ptr(attr->info.info);
1922 	struct bpf_prog_info info = {};
1923 	u32 info_len = attr->info.info_len;
1924 	char __user *uinsns;
1925 	u32 ulen;
1926 	int err;
1927 
1928 	err = bpf_check_uarg_tail_zero(uinfo, sizeof(info), info_len);
1929 	if (err)
1930 		return err;
1931 	info_len = min_t(u32, sizeof(info), info_len);
1932 
1933 	if (copy_from_user(&info, uinfo, info_len))
1934 		return -EFAULT;
1935 
1936 	info.type = prog->type;
1937 	info.id = prog->aux->id;
1938 	info.load_time = prog->aux->load_time;
1939 	info.created_by_uid = from_kuid_munged(current_user_ns(),
1940 					       prog->aux->user->uid);
1941 	info.gpl_compatible = prog->gpl_compatible;
1942 
1943 	memcpy(info.tag, prog->tag, sizeof(prog->tag));
1944 	memcpy(info.name, prog->aux->name, sizeof(prog->aux->name));
1945 
1946 	ulen = info.nr_map_ids;
1947 	info.nr_map_ids = prog->aux->used_map_cnt;
1948 	ulen = min_t(u32, info.nr_map_ids, ulen);
1949 	if (ulen) {
1950 		u32 __user *user_map_ids = u64_to_user_ptr(info.map_ids);
1951 		u32 i;
1952 
1953 		for (i = 0; i < ulen; i++)
1954 			if (put_user(prog->aux->used_maps[i]->id,
1955 				     &user_map_ids[i]))
1956 				return -EFAULT;
1957 	}
1958 
1959 	if (!capable(CAP_SYS_ADMIN)) {
1960 		info.jited_prog_len = 0;
1961 		info.xlated_prog_len = 0;
1962 		info.nr_jited_ksyms = 0;
1963 		goto done;
1964 	}
1965 
1966 	ulen = info.xlated_prog_len;
1967 	info.xlated_prog_len = bpf_prog_insn_size(prog);
1968 	if (info.xlated_prog_len && ulen) {
1969 		struct bpf_insn *insns_sanitized;
1970 		bool fault;
1971 
1972 		if (prog->blinded && !bpf_dump_raw_ok()) {
1973 			info.xlated_prog_insns = 0;
1974 			goto done;
1975 		}
1976 		insns_sanitized = bpf_insn_prepare_dump(prog);
1977 		if (!insns_sanitized)
1978 			return -ENOMEM;
1979 		uinsns = u64_to_user_ptr(info.xlated_prog_insns);
1980 		ulen = min_t(u32, info.xlated_prog_len, ulen);
1981 		fault = copy_to_user(uinsns, insns_sanitized, ulen);
1982 		kfree(insns_sanitized);
1983 		if (fault)
1984 			return -EFAULT;
1985 	}
1986 
1987 	if (bpf_prog_is_dev_bound(prog->aux)) {
1988 		err = bpf_prog_offload_info_fill(&info, prog);
1989 		if (err)
1990 			return err;
1991 		goto done;
1992 	}
1993 
1994 	/* NOTE: the following code is supposed to be skipped for offload.
1995 	 * bpf_prog_offload_info_fill() is the place to fill similar fields
1996 	 * for offload.
1997 	 */
1998 	ulen = info.jited_prog_len;
1999 	if (prog->aux->func_cnt) {
2000 		u32 i;
2001 
2002 		info.jited_prog_len = 0;
2003 		for (i = 0; i < prog->aux->func_cnt; i++)
2004 			info.jited_prog_len += prog->aux->func[i]->jited_len;
2005 	} else {
2006 		info.jited_prog_len = prog->jited_len;
2007 	}
2008 
2009 	if (info.jited_prog_len && ulen) {
2010 		if (bpf_dump_raw_ok()) {
2011 			uinsns = u64_to_user_ptr(info.jited_prog_insns);
2012 			ulen = min_t(u32, info.jited_prog_len, ulen);
2013 
2014 			/* for multi-function programs, copy the JITed
2015 			 * instructions for all the functions
2016 			 */
2017 			if (prog->aux->func_cnt) {
2018 				u32 len, free, i;
2019 				u8 *img;
2020 
2021 				free = ulen;
2022 				for (i = 0; i < prog->aux->func_cnt; i++) {
2023 					len = prog->aux->func[i]->jited_len;
2024 					len = min_t(u32, len, free);
2025 					img = (u8 *) prog->aux->func[i]->bpf_func;
2026 					if (copy_to_user(uinsns, img, len))
2027 						return -EFAULT;
2028 					uinsns += len;
2029 					free -= len;
2030 					if (!free)
2031 						break;
2032 				}
2033 			} else {
2034 				if (copy_to_user(uinsns, prog->bpf_func, ulen))
2035 					return -EFAULT;
2036 			}
2037 		} else {
2038 			info.jited_prog_insns = 0;
2039 		}
2040 	}
2041 
2042 	ulen = info.nr_jited_ksyms;
2043 	info.nr_jited_ksyms = prog->aux->func_cnt;
2044 	if (info.nr_jited_ksyms && ulen) {
2045 		if (bpf_dump_raw_ok()) {
2046 			u64 __user *user_ksyms;
2047 			ulong ksym_addr;
2048 			u32 i;
2049 
2050 			/* copy the address of the kernel symbol
2051 			 * corresponding to each function
2052 			 */
2053 			ulen = min_t(u32, info.nr_jited_ksyms, ulen);
2054 			user_ksyms = u64_to_user_ptr(info.jited_ksyms);
2055 			for (i = 0; i < ulen; i++) {
2056 				ksym_addr = (ulong) prog->aux->func[i]->bpf_func;
2057 				ksym_addr &= PAGE_MASK;
2058 				if (put_user((u64) ksym_addr, &user_ksyms[i]))
2059 					return -EFAULT;
2060 			}
2061 		} else {
2062 			info.jited_ksyms = 0;
2063 		}
2064 	}
2065 
2066 	ulen = info.nr_jited_func_lens;
2067 	info.nr_jited_func_lens = prog->aux->func_cnt;
2068 	if (info.nr_jited_func_lens && ulen) {
2069 		if (bpf_dump_raw_ok()) {
2070 			u32 __user *user_lens;
2071 			u32 func_len, i;
2072 
2073 			/* copy the JITed image lengths for each function */
2074 			ulen = min_t(u32, info.nr_jited_func_lens, ulen);
2075 			user_lens = u64_to_user_ptr(info.jited_func_lens);
2076 			for (i = 0; i < ulen; i++) {
2077 				func_len = prog->aux->func[i]->jited_len;
2078 				if (put_user(func_len, &user_lens[i]))
2079 					return -EFAULT;
2080 			}
2081 		} else {
2082 			info.jited_func_lens = 0;
2083 		}
2084 	}
2085 
2086 done:
2087 	if (copy_to_user(uinfo, &info, info_len) ||
2088 	    put_user(info_len, &uattr->info.info_len))
2089 		return -EFAULT;
2090 
2091 	return 0;
2092 }
2093 
2094 static int bpf_map_get_info_by_fd(struct bpf_map *map,
2095 				  const union bpf_attr *attr,
2096 				  union bpf_attr __user *uattr)
2097 {
2098 	struct bpf_map_info __user *uinfo = u64_to_user_ptr(attr->info.info);
2099 	struct bpf_map_info info = {};
2100 	u32 info_len = attr->info.info_len;
2101 	int err;
2102 
2103 	err = bpf_check_uarg_tail_zero(uinfo, sizeof(info), info_len);
2104 	if (err)
2105 		return err;
2106 	info_len = min_t(u32, sizeof(info), info_len);
2107 
2108 	info.type = map->map_type;
2109 	info.id = map->id;
2110 	info.key_size = map->key_size;
2111 	info.value_size = map->value_size;
2112 	info.max_entries = map->max_entries;
2113 	info.map_flags = map->map_flags;
2114 	memcpy(info.name, map->name, sizeof(map->name));
2115 
2116 	if (map->btf) {
2117 		info.btf_id = btf_id(map->btf);
2118 		info.btf_key_type_id = map->btf_key_type_id;
2119 		info.btf_value_type_id = map->btf_value_type_id;
2120 	}
2121 
2122 	if (bpf_map_is_dev_bound(map)) {
2123 		err = bpf_map_offload_info_fill(&info, map);
2124 		if (err)
2125 			return err;
2126 	}
2127 
2128 	if (copy_to_user(uinfo, &info, info_len) ||
2129 	    put_user(info_len, &uattr->info.info_len))
2130 		return -EFAULT;
2131 
2132 	return 0;
2133 }
2134 
2135 static int bpf_btf_get_info_by_fd(struct btf *btf,
2136 				  const union bpf_attr *attr,
2137 				  union bpf_attr __user *uattr)
2138 {
2139 	struct bpf_btf_info __user *uinfo = u64_to_user_ptr(attr->info.info);
2140 	u32 info_len = attr->info.info_len;
2141 	int err;
2142 
2143 	err = bpf_check_uarg_tail_zero(uinfo, sizeof(*uinfo), info_len);
2144 	if (err)
2145 		return err;
2146 
2147 	return btf_get_info_by_fd(btf, attr, uattr);
2148 }
2149 
2150 #define BPF_OBJ_GET_INFO_BY_FD_LAST_FIELD info.info
2151 
2152 static int bpf_obj_get_info_by_fd(const union bpf_attr *attr,
2153 				  union bpf_attr __user *uattr)
2154 {
2155 	int ufd = attr->info.bpf_fd;
2156 	struct fd f;
2157 	int err;
2158 
2159 	if (CHECK_ATTR(BPF_OBJ_GET_INFO_BY_FD))
2160 		return -EINVAL;
2161 
2162 	f = fdget(ufd);
2163 	if (!f.file)
2164 		return -EBADFD;
2165 
2166 	if (f.file->f_op == &bpf_prog_fops)
2167 		err = bpf_prog_get_info_by_fd(f.file->private_data, attr,
2168 					      uattr);
2169 	else if (f.file->f_op == &bpf_map_fops)
2170 		err = bpf_map_get_info_by_fd(f.file->private_data, attr,
2171 					     uattr);
2172 	else if (f.file->f_op == &btf_fops)
2173 		err = bpf_btf_get_info_by_fd(f.file->private_data, attr, uattr);
2174 	else
2175 		err = -EINVAL;
2176 
2177 	fdput(f);
2178 	return err;
2179 }
2180 
2181 #define BPF_BTF_LOAD_LAST_FIELD btf_log_level
2182 
2183 static int bpf_btf_load(const union bpf_attr *attr)
2184 {
2185 	if (CHECK_ATTR(BPF_BTF_LOAD))
2186 		return -EINVAL;
2187 
2188 	if (!capable(CAP_SYS_ADMIN))
2189 		return -EPERM;
2190 
2191 	return btf_new_fd(attr);
2192 }
2193 
2194 #define BPF_BTF_GET_FD_BY_ID_LAST_FIELD btf_id
2195 
2196 static int bpf_btf_get_fd_by_id(const union bpf_attr *attr)
2197 {
2198 	if (CHECK_ATTR(BPF_BTF_GET_FD_BY_ID))
2199 		return -EINVAL;
2200 
2201 	if (!capable(CAP_SYS_ADMIN))
2202 		return -EPERM;
2203 
2204 	return btf_get_fd_by_id(attr->btf_id);
2205 }
2206 
2207 static int bpf_task_fd_query_copy(const union bpf_attr *attr,
2208 				    union bpf_attr __user *uattr,
2209 				    u32 prog_id, u32 fd_type,
2210 				    const char *buf, u64 probe_offset,
2211 				    u64 probe_addr)
2212 {
2213 	char __user *ubuf = u64_to_user_ptr(attr->task_fd_query.buf);
2214 	u32 len = buf ? strlen(buf) : 0, input_len;
2215 	int err = 0;
2216 
2217 	if (put_user(len, &uattr->task_fd_query.buf_len))
2218 		return -EFAULT;
2219 	input_len = attr->task_fd_query.buf_len;
2220 	if (input_len && ubuf) {
2221 		if (!len) {
2222 			/* nothing to copy, just make ubuf NULL terminated */
2223 			char zero = '\0';
2224 
2225 			if (put_user(zero, ubuf))
2226 				return -EFAULT;
2227 		} else if (input_len >= len + 1) {
2228 			/* ubuf can hold the string with NULL terminator */
2229 			if (copy_to_user(ubuf, buf, len + 1))
2230 				return -EFAULT;
2231 		} else {
2232 			/* ubuf cannot hold the string with NULL terminator,
2233 			 * do a partial copy with NULL terminator.
2234 			 */
2235 			char zero = '\0';
2236 
2237 			err = -ENOSPC;
2238 			if (copy_to_user(ubuf, buf, input_len - 1))
2239 				return -EFAULT;
2240 			if (put_user(zero, ubuf + input_len - 1))
2241 				return -EFAULT;
2242 		}
2243 	}
2244 
2245 	if (put_user(prog_id, &uattr->task_fd_query.prog_id) ||
2246 	    put_user(fd_type, &uattr->task_fd_query.fd_type) ||
2247 	    put_user(probe_offset, &uattr->task_fd_query.probe_offset) ||
2248 	    put_user(probe_addr, &uattr->task_fd_query.probe_addr))
2249 		return -EFAULT;
2250 
2251 	return err;
2252 }
2253 
2254 #define BPF_TASK_FD_QUERY_LAST_FIELD task_fd_query.probe_addr
2255 
2256 static int bpf_task_fd_query(const union bpf_attr *attr,
2257 			     union bpf_attr __user *uattr)
2258 {
2259 	pid_t pid = attr->task_fd_query.pid;
2260 	u32 fd = attr->task_fd_query.fd;
2261 	const struct perf_event *event;
2262 	struct files_struct *files;
2263 	struct task_struct *task;
2264 	struct file *file;
2265 	int err;
2266 
2267 	if (CHECK_ATTR(BPF_TASK_FD_QUERY))
2268 		return -EINVAL;
2269 
2270 	if (!capable(CAP_SYS_ADMIN))
2271 		return -EPERM;
2272 
2273 	if (attr->task_fd_query.flags != 0)
2274 		return -EINVAL;
2275 
2276 	task = get_pid_task(find_vpid(pid), PIDTYPE_PID);
2277 	if (!task)
2278 		return -ENOENT;
2279 
2280 	files = get_files_struct(task);
2281 	put_task_struct(task);
2282 	if (!files)
2283 		return -ENOENT;
2284 
2285 	err = 0;
2286 	spin_lock(&files->file_lock);
2287 	file = fcheck_files(files, fd);
2288 	if (!file)
2289 		err = -EBADF;
2290 	else
2291 		get_file(file);
2292 	spin_unlock(&files->file_lock);
2293 	put_files_struct(files);
2294 
2295 	if (err)
2296 		goto out;
2297 
2298 	if (file->f_op == &bpf_raw_tp_fops) {
2299 		struct bpf_raw_tracepoint *raw_tp = file->private_data;
2300 		struct bpf_raw_event_map *btp = raw_tp->btp;
2301 
2302 		err = bpf_task_fd_query_copy(attr, uattr,
2303 					     raw_tp->prog->aux->id,
2304 					     BPF_FD_TYPE_RAW_TRACEPOINT,
2305 					     btp->tp->name, 0, 0);
2306 		goto put_file;
2307 	}
2308 
2309 	event = perf_get_event(file);
2310 	if (!IS_ERR(event)) {
2311 		u64 probe_offset, probe_addr;
2312 		u32 prog_id, fd_type;
2313 		const char *buf;
2314 
2315 		err = bpf_get_perf_event_info(event, &prog_id, &fd_type,
2316 					      &buf, &probe_offset,
2317 					      &probe_addr);
2318 		if (!err)
2319 			err = bpf_task_fd_query_copy(attr, uattr, prog_id,
2320 						     fd_type, buf,
2321 						     probe_offset,
2322 						     probe_addr);
2323 		goto put_file;
2324 	}
2325 
2326 	err = -ENOTSUPP;
2327 put_file:
2328 	fput(file);
2329 out:
2330 	return err;
2331 }
2332 
2333 SYSCALL_DEFINE3(bpf, int, cmd, union bpf_attr __user *, uattr, unsigned int, size)
2334 {
2335 	union bpf_attr attr = {};
2336 	int err;
2337 
2338 	if (sysctl_unprivileged_bpf_disabled && !capable(CAP_SYS_ADMIN))
2339 		return -EPERM;
2340 
2341 	err = bpf_check_uarg_tail_zero(uattr, sizeof(attr), size);
2342 	if (err)
2343 		return err;
2344 	size = min_t(u32, size, sizeof(attr));
2345 
2346 	/* copy attributes from user space, may be less than sizeof(bpf_attr) */
2347 	if (copy_from_user(&attr, uattr, size) != 0)
2348 		return -EFAULT;
2349 
2350 	err = security_bpf(cmd, &attr, size);
2351 	if (err < 0)
2352 		return err;
2353 
2354 	switch (cmd) {
2355 	case BPF_MAP_CREATE:
2356 		err = map_create(&attr);
2357 		break;
2358 	case BPF_MAP_LOOKUP_ELEM:
2359 		err = map_lookup_elem(&attr);
2360 		break;
2361 	case BPF_MAP_UPDATE_ELEM:
2362 		err = map_update_elem(&attr);
2363 		break;
2364 	case BPF_MAP_DELETE_ELEM:
2365 		err = map_delete_elem(&attr);
2366 		break;
2367 	case BPF_MAP_GET_NEXT_KEY:
2368 		err = map_get_next_key(&attr);
2369 		break;
2370 	case BPF_PROG_LOAD:
2371 		err = bpf_prog_load(&attr);
2372 		break;
2373 	case BPF_OBJ_PIN:
2374 		err = bpf_obj_pin(&attr);
2375 		break;
2376 	case BPF_OBJ_GET:
2377 		err = bpf_obj_get(&attr);
2378 		break;
2379 	case BPF_PROG_ATTACH:
2380 		err = bpf_prog_attach(&attr);
2381 		break;
2382 	case BPF_PROG_DETACH:
2383 		err = bpf_prog_detach(&attr);
2384 		break;
2385 	case BPF_PROG_QUERY:
2386 		err = bpf_prog_query(&attr, uattr);
2387 		break;
2388 	case BPF_PROG_TEST_RUN:
2389 		err = bpf_prog_test_run(&attr, uattr);
2390 		break;
2391 	case BPF_PROG_GET_NEXT_ID:
2392 		err = bpf_obj_get_next_id(&attr, uattr,
2393 					  &prog_idr, &prog_idr_lock);
2394 		break;
2395 	case BPF_MAP_GET_NEXT_ID:
2396 		err = bpf_obj_get_next_id(&attr, uattr,
2397 					  &map_idr, &map_idr_lock);
2398 		break;
2399 	case BPF_PROG_GET_FD_BY_ID:
2400 		err = bpf_prog_get_fd_by_id(&attr);
2401 		break;
2402 	case BPF_MAP_GET_FD_BY_ID:
2403 		err = bpf_map_get_fd_by_id(&attr);
2404 		break;
2405 	case BPF_OBJ_GET_INFO_BY_FD:
2406 		err = bpf_obj_get_info_by_fd(&attr, uattr);
2407 		break;
2408 	case BPF_RAW_TRACEPOINT_OPEN:
2409 		err = bpf_raw_tracepoint_open(&attr);
2410 		break;
2411 	case BPF_BTF_LOAD:
2412 		err = bpf_btf_load(&attr);
2413 		break;
2414 	case BPF_BTF_GET_FD_BY_ID:
2415 		err = bpf_btf_get_fd_by_id(&attr);
2416 		break;
2417 	case BPF_TASK_FD_QUERY:
2418 		err = bpf_task_fd_query(&attr, uattr);
2419 		break;
2420 	default:
2421 		err = -EINVAL;
2422 		break;
2423 	}
2424 
2425 	return err;
2426 }
2427