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