xref: /openbmc/linux/kernel/bpf/syscall.c (revision ac33d7ae)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
3  */
4 #include <linux/bpf.h>
5 #include <linux/bpf-cgroup.h>
6 #include <linux/bpf_trace.h>
7 #include <linux/bpf_lirc.h>
8 #include <linux/bpf_verifier.h>
9 #include <linux/bsearch.h>
10 #include <linux/btf.h>
11 #include <linux/syscalls.h>
12 #include <linux/slab.h>
13 #include <linux/sched/signal.h>
14 #include <linux/vmalloc.h>
15 #include <linux/mmzone.h>
16 #include <linux/anon_inodes.h>
17 #include <linux/fdtable.h>
18 #include <linux/file.h>
19 #include <linux/fs.h>
20 #include <linux/license.h>
21 #include <linux/filter.h>
22 #include <linux/kernel.h>
23 #include <linux/idr.h>
24 #include <linux/cred.h>
25 #include <linux/timekeeping.h>
26 #include <linux/ctype.h>
27 #include <linux/nospec.h>
28 #include <linux/audit.h>
29 #include <uapi/linux/btf.h>
30 #include <linux/pgtable.h>
31 #include <linux/bpf_lsm.h>
32 #include <linux/poll.h>
33 #include <linux/sort.h>
34 #include <linux/bpf-netns.h>
35 #include <linux/rcupdate_trace.h>
36 #include <linux/memcontrol.h>
37 #include <linux/trace_events.h>
38 
39 #define IS_FD_ARRAY(map) ((map)->map_type == BPF_MAP_TYPE_PERF_EVENT_ARRAY || \
40 			  (map)->map_type == BPF_MAP_TYPE_CGROUP_ARRAY || \
41 			  (map)->map_type == BPF_MAP_TYPE_ARRAY_OF_MAPS)
42 #define IS_FD_PROG_ARRAY(map) ((map)->map_type == BPF_MAP_TYPE_PROG_ARRAY)
43 #define IS_FD_HASH(map) ((map)->map_type == BPF_MAP_TYPE_HASH_OF_MAPS)
44 #define IS_FD_MAP(map) (IS_FD_ARRAY(map) || IS_FD_PROG_ARRAY(map) || \
45 			IS_FD_HASH(map))
46 
47 #define BPF_OBJ_FLAG_MASK   (BPF_F_RDONLY | BPF_F_WRONLY)
48 
49 DEFINE_PER_CPU(int, bpf_prog_active);
50 static DEFINE_IDR(prog_idr);
51 static DEFINE_SPINLOCK(prog_idr_lock);
52 static DEFINE_IDR(map_idr);
53 static DEFINE_SPINLOCK(map_idr_lock);
54 static DEFINE_IDR(link_idr);
55 static DEFINE_SPINLOCK(link_idr_lock);
56 
57 int sysctl_unprivileged_bpf_disabled __read_mostly =
58 	IS_BUILTIN(CONFIG_BPF_UNPRIV_DEFAULT_OFF) ? 2 : 0;
59 
60 static const struct bpf_map_ops * const bpf_map_types[] = {
61 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type)
62 #define BPF_MAP_TYPE(_id, _ops) \
63 	[_id] = &_ops,
64 #define BPF_LINK_TYPE(_id, _name)
65 #include <linux/bpf_types.h>
66 #undef BPF_PROG_TYPE
67 #undef BPF_MAP_TYPE
68 #undef BPF_LINK_TYPE
69 };
70 
71 /*
72  * If we're handed a bigger struct than we know of, ensure all the unknown bits
73  * are 0 - i.e. new user-space does not rely on any kernel feature extensions
74  * we don't know about yet.
75  *
76  * There is a ToCToU between this function call and the following
77  * copy_from_user() call. However, this is not a concern since this function is
78  * meant to be a future-proofing of bits.
79  */
80 int bpf_check_uarg_tail_zero(bpfptr_t uaddr,
81 			     size_t expected_size,
82 			     size_t actual_size)
83 {
84 	int res;
85 
86 	if (unlikely(actual_size > PAGE_SIZE))	/* silly large */
87 		return -E2BIG;
88 
89 	if (actual_size <= expected_size)
90 		return 0;
91 
92 	if (uaddr.is_kernel)
93 		res = memchr_inv(uaddr.kernel + expected_size, 0,
94 				 actual_size - expected_size) == NULL;
95 	else
96 		res = check_zeroed_user(uaddr.user + expected_size,
97 					actual_size - expected_size);
98 	if (res < 0)
99 		return res;
100 	return res ? 0 : -E2BIG;
101 }
102 
103 const struct bpf_map_ops bpf_map_offload_ops = {
104 	.map_meta_equal = bpf_map_meta_equal,
105 	.map_alloc = bpf_map_offload_map_alloc,
106 	.map_free = bpf_map_offload_map_free,
107 	.map_check_btf = map_check_no_btf,
108 };
109 
110 static struct bpf_map *find_and_alloc_map(union bpf_attr *attr)
111 {
112 	const struct bpf_map_ops *ops;
113 	u32 type = attr->map_type;
114 	struct bpf_map *map;
115 	int err;
116 
117 	if (type >= ARRAY_SIZE(bpf_map_types))
118 		return ERR_PTR(-EINVAL);
119 	type = array_index_nospec(type, ARRAY_SIZE(bpf_map_types));
120 	ops = bpf_map_types[type];
121 	if (!ops)
122 		return ERR_PTR(-EINVAL);
123 
124 	if (ops->map_alloc_check) {
125 		err = ops->map_alloc_check(attr);
126 		if (err)
127 			return ERR_PTR(err);
128 	}
129 	if (attr->map_ifindex)
130 		ops = &bpf_map_offload_ops;
131 	map = ops->map_alloc(attr);
132 	if (IS_ERR(map))
133 		return map;
134 	map->ops = ops;
135 	map->map_type = type;
136 	return map;
137 }
138 
139 static void bpf_map_write_active_inc(struct bpf_map *map)
140 {
141 	atomic64_inc(&map->writecnt);
142 }
143 
144 static void bpf_map_write_active_dec(struct bpf_map *map)
145 {
146 	atomic64_dec(&map->writecnt);
147 }
148 
149 bool bpf_map_write_active(const struct bpf_map *map)
150 {
151 	return atomic64_read(&map->writecnt) != 0;
152 }
153 
154 static u32 bpf_map_value_size(const struct bpf_map *map)
155 {
156 	if (map->map_type == BPF_MAP_TYPE_PERCPU_HASH ||
157 	    map->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH ||
158 	    map->map_type == BPF_MAP_TYPE_PERCPU_ARRAY ||
159 	    map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
160 		return round_up(map->value_size, 8) * num_possible_cpus();
161 	else if (IS_FD_MAP(map))
162 		return sizeof(u32);
163 	else
164 		return  map->value_size;
165 }
166 
167 static void maybe_wait_bpf_programs(struct bpf_map *map)
168 {
169 	/* Wait for any running BPF programs to complete so that
170 	 * userspace, when we return to it, knows that all programs
171 	 * that could be running use the new map value.
172 	 */
173 	if (map->map_type == BPF_MAP_TYPE_HASH_OF_MAPS ||
174 	    map->map_type == BPF_MAP_TYPE_ARRAY_OF_MAPS)
175 		synchronize_rcu();
176 }
177 
178 static int bpf_map_update_value(struct bpf_map *map, struct fd f, void *key,
179 				void *value, __u64 flags)
180 {
181 	int err;
182 
183 	/* Need to create a kthread, thus must support schedule */
184 	if (bpf_map_is_dev_bound(map)) {
185 		return bpf_map_offload_update_elem(map, key, value, flags);
186 	} else if (map->map_type == BPF_MAP_TYPE_CPUMAP ||
187 		   map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
188 		return map->ops->map_update_elem(map, key, value, flags);
189 	} else if (map->map_type == BPF_MAP_TYPE_SOCKHASH ||
190 		   map->map_type == BPF_MAP_TYPE_SOCKMAP) {
191 		return sock_map_update_elem_sys(map, key, value, flags);
192 	} else if (IS_FD_PROG_ARRAY(map)) {
193 		return bpf_fd_array_map_update_elem(map, f.file, key, value,
194 						    flags);
195 	}
196 
197 	bpf_disable_instrumentation();
198 	if (map->map_type == BPF_MAP_TYPE_PERCPU_HASH ||
199 	    map->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH) {
200 		err = bpf_percpu_hash_update(map, key, value, flags);
201 	} else if (map->map_type == BPF_MAP_TYPE_PERCPU_ARRAY) {
202 		err = bpf_percpu_array_update(map, key, value, flags);
203 	} else if (map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE) {
204 		err = bpf_percpu_cgroup_storage_update(map, key, value,
205 						       flags);
206 	} else if (IS_FD_ARRAY(map)) {
207 		rcu_read_lock();
208 		err = bpf_fd_array_map_update_elem(map, f.file, key, value,
209 						   flags);
210 		rcu_read_unlock();
211 	} else if (map->map_type == BPF_MAP_TYPE_HASH_OF_MAPS) {
212 		rcu_read_lock();
213 		err = bpf_fd_htab_map_update_elem(map, f.file, key, value,
214 						  flags);
215 		rcu_read_unlock();
216 	} else if (map->map_type == BPF_MAP_TYPE_REUSEPORT_SOCKARRAY) {
217 		/* rcu_read_lock() is not needed */
218 		err = bpf_fd_reuseport_array_update_elem(map, key, value,
219 							 flags);
220 	} else if (map->map_type == BPF_MAP_TYPE_QUEUE ||
221 		   map->map_type == BPF_MAP_TYPE_STACK ||
222 		   map->map_type == BPF_MAP_TYPE_BLOOM_FILTER) {
223 		err = map->ops->map_push_elem(map, value, flags);
224 	} else {
225 		rcu_read_lock();
226 		err = map->ops->map_update_elem(map, key, value, flags);
227 		rcu_read_unlock();
228 	}
229 	bpf_enable_instrumentation();
230 	maybe_wait_bpf_programs(map);
231 
232 	return err;
233 }
234 
235 static int bpf_map_copy_value(struct bpf_map *map, void *key, void *value,
236 			      __u64 flags)
237 {
238 	void *ptr;
239 	int err;
240 
241 	if (bpf_map_is_dev_bound(map))
242 		return bpf_map_offload_lookup_elem(map, key, value);
243 
244 	bpf_disable_instrumentation();
245 	if (map->map_type == BPF_MAP_TYPE_PERCPU_HASH ||
246 	    map->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH) {
247 		err = bpf_percpu_hash_copy(map, key, value);
248 	} else if (map->map_type == BPF_MAP_TYPE_PERCPU_ARRAY) {
249 		err = bpf_percpu_array_copy(map, key, value);
250 	} else if (map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE) {
251 		err = bpf_percpu_cgroup_storage_copy(map, key, value);
252 	} else if (map->map_type == BPF_MAP_TYPE_STACK_TRACE) {
253 		err = bpf_stackmap_copy(map, key, value);
254 	} else if (IS_FD_ARRAY(map) || IS_FD_PROG_ARRAY(map)) {
255 		err = bpf_fd_array_map_lookup_elem(map, key, value);
256 	} else if (IS_FD_HASH(map)) {
257 		err = bpf_fd_htab_map_lookup_elem(map, key, value);
258 	} else if (map->map_type == BPF_MAP_TYPE_REUSEPORT_SOCKARRAY) {
259 		err = bpf_fd_reuseport_array_lookup_elem(map, key, value);
260 	} else if (map->map_type == BPF_MAP_TYPE_QUEUE ||
261 		   map->map_type == BPF_MAP_TYPE_STACK ||
262 		   map->map_type == BPF_MAP_TYPE_BLOOM_FILTER) {
263 		err = map->ops->map_peek_elem(map, value);
264 	} else if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
265 		/* struct_ops map requires directly updating "value" */
266 		err = bpf_struct_ops_map_sys_lookup_elem(map, key, value);
267 	} else {
268 		rcu_read_lock();
269 		if (map->ops->map_lookup_elem_sys_only)
270 			ptr = map->ops->map_lookup_elem_sys_only(map, key);
271 		else
272 			ptr = map->ops->map_lookup_elem(map, key);
273 		if (IS_ERR(ptr)) {
274 			err = PTR_ERR(ptr);
275 		} else if (!ptr) {
276 			err = -ENOENT;
277 		} else {
278 			err = 0;
279 			if (flags & BPF_F_LOCK)
280 				/* lock 'ptr' and copy everything but lock */
281 				copy_map_value_locked(map, value, ptr, true);
282 			else
283 				copy_map_value(map, value, ptr);
284 			/* mask lock and timer, since value wasn't zero inited */
285 			check_and_init_map_value(map, value);
286 		}
287 		rcu_read_unlock();
288 	}
289 
290 	bpf_enable_instrumentation();
291 	maybe_wait_bpf_programs(map);
292 
293 	return err;
294 }
295 
296 /* Please, do not use this function outside from the map creation path
297  * (e.g. in map update path) without taking care of setting the active
298  * memory cgroup (see at bpf_map_kmalloc_node() for example).
299  */
300 static void *__bpf_map_area_alloc(u64 size, int numa_node, bool mmapable)
301 {
302 	/* We really just want to fail instead of triggering OOM killer
303 	 * under memory pressure, therefore we set __GFP_NORETRY to kmalloc,
304 	 * which is used for lower order allocation requests.
305 	 *
306 	 * It has been observed that higher order allocation requests done by
307 	 * vmalloc with __GFP_NORETRY being set might fail due to not trying
308 	 * to reclaim memory from the page cache, thus we set
309 	 * __GFP_RETRY_MAYFAIL to avoid such situations.
310 	 */
311 
312 	const gfp_t gfp = __GFP_NOWARN | __GFP_ZERO | __GFP_ACCOUNT;
313 	unsigned int flags = 0;
314 	unsigned long align = 1;
315 	void *area;
316 
317 	if (size >= SIZE_MAX)
318 		return NULL;
319 
320 	/* kmalloc()'ed memory can't be mmap()'ed */
321 	if (mmapable) {
322 		BUG_ON(!PAGE_ALIGNED(size));
323 		align = SHMLBA;
324 		flags = VM_USERMAP;
325 	} else if (size <= (PAGE_SIZE << PAGE_ALLOC_COSTLY_ORDER)) {
326 		area = kmalloc_node(size, gfp | GFP_USER | __GFP_NORETRY,
327 				    numa_node);
328 		if (area != NULL)
329 			return area;
330 	}
331 
332 	return __vmalloc_node_range(size, align, VMALLOC_START, VMALLOC_END,
333 			gfp | GFP_KERNEL | __GFP_RETRY_MAYFAIL, PAGE_KERNEL,
334 			flags, numa_node, __builtin_return_address(0));
335 }
336 
337 void *bpf_map_area_alloc(u64 size, int numa_node)
338 {
339 	return __bpf_map_area_alloc(size, numa_node, false);
340 }
341 
342 void *bpf_map_area_mmapable_alloc(u64 size, int numa_node)
343 {
344 	return __bpf_map_area_alloc(size, numa_node, true);
345 }
346 
347 void bpf_map_area_free(void *area)
348 {
349 	kvfree(area);
350 }
351 
352 static u32 bpf_map_flags_retain_permanent(u32 flags)
353 {
354 	/* Some map creation flags are not tied to the map object but
355 	 * rather to the map fd instead, so they have no meaning upon
356 	 * map object inspection since multiple file descriptors with
357 	 * different (access) properties can exist here. Thus, given
358 	 * this has zero meaning for the map itself, lets clear these
359 	 * from here.
360 	 */
361 	return flags & ~(BPF_F_RDONLY | BPF_F_WRONLY);
362 }
363 
364 void bpf_map_init_from_attr(struct bpf_map *map, union bpf_attr *attr)
365 {
366 	map->map_type = attr->map_type;
367 	map->key_size = attr->key_size;
368 	map->value_size = attr->value_size;
369 	map->max_entries = attr->max_entries;
370 	map->map_flags = bpf_map_flags_retain_permanent(attr->map_flags);
371 	map->numa_node = bpf_map_attr_numa_node(attr);
372 	map->map_extra = attr->map_extra;
373 }
374 
375 static int bpf_map_alloc_id(struct bpf_map *map)
376 {
377 	int id;
378 
379 	idr_preload(GFP_KERNEL);
380 	spin_lock_bh(&map_idr_lock);
381 	id = idr_alloc_cyclic(&map_idr, map, 1, INT_MAX, GFP_ATOMIC);
382 	if (id > 0)
383 		map->id = id;
384 	spin_unlock_bh(&map_idr_lock);
385 	idr_preload_end();
386 
387 	if (WARN_ON_ONCE(!id))
388 		return -ENOSPC;
389 
390 	return id > 0 ? 0 : id;
391 }
392 
393 void bpf_map_free_id(struct bpf_map *map, bool do_idr_lock)
394 {
395 	unsigned long flags;
396 
397 	/* Offloaded maps are removed from the IDR store when their device
398 	 * disappears - even if someone holds an fd to them they are unusable,
399 	 * the memory is gone, all ops will fail; they are simply waiting for
400 	 * refcnt to drop to be freed.
401 	 */
402 	if (!map->id)
403 		return;
404 
405 	if (do_idr_lock)
406 		spin_lock_irqsave(&map_idr_lock, flags);
407 	else
408 		__acquire(&map_idr_lock);
409 
410 	idr_remove(&map_idr, map->id);
411 	map->id = 0;
412 
413 	if (do_idr_lock)
414 		spin_unlock_irqrestore(&map_idr_lock, flags);
415 	else
416 		__release(&map_idr_lock);
417 }
418 
419 #ifdef CONFIG_MEMCG_KMEM
420 static void bpf_map_save_memcg(struct bpf_map *map)
421 {
422 	/* Currently if a map is created by a process belonging to the root
423 	 * memory cgroup, get_obj_cgroup_from_current() will return NULL.
424 	 * So we have to check map->objcg for being NULL each time it's
425 	 * being used.
426 	 */
427 	map->objcg = get_obj_cgroup_from_current();
428 }
429 
430 static void bpf_map_release_memcg(struct bpf_map *map)
431 {
432 	if (map->objcg)
433 		obj_cgroup_put(map->objcg);
434 }
435 
436 static struct mem_cgroup *bpf_map_get_memcg(const struct bpf_map *map)
437 {
438 	if (map->objcg)
439 		return get_mem_cgroup_from_objcg(map->objcg);
440 
441 	return root_mem_cgroup;
442 }
443 
444 void *bpf_map_kmalloc_node(const struct bpf_map *map, size_t size, gfp_t flags,
445 			   int node)
446 {
447 	struct mem_cgroup *memcg, *old_memcg;
448 	void *ptr;
449 
450 	memcg = bpf_map_get_memcg(map);
451 	old_memcg = set_active_memcg(memcg);
452 	ptr = kmalloc_node(size, flags | __GFP_ACCOUNT, node);
453 	set_active_memcg(old_memcg);
454 	mem_cgroup_put(memcg);
455 
456 	return ptr;
457 }
458 
459 void *bpf_map_kzalloc(const struct bpf_map *map, size_t size, gfp_t flags)
460 {
461 	struct mem_cgroup *memcg, *old_memcg;
462 	void *ptr;
463 
464 	memcg = bpf_map_get_memcg(map);
465 	old_memcg = set_active_memcg(memcg);
466 	ptr = kzalloc(size, flags | __GFP_ACCOUNT);
467 	set_active_memcg(old_memcg);
468 	mem_cgroup_put(memcg);
469 
470 	return ptr;
471 }
472 
473 void __percpu *bpf_map_alloc_percpu(const struct bpf_map *map, size_t size,
474 				    size_t align, gfp_t flags)
475 {
476 	struct mem_cgroup *memcg, *old_memcg;
477 	void __percpu *ptr;
478 
479 	memcg = bpf_map_get_memcg(map);
480 	old_memcg = set_active_memcg(memcg);
481 	ptr = __alloc_percpu_gfp(size, align, flags | __GFP_ACCOUNT);
482 	set_active_memcg(old_memcg);
483 	mem_cgroup_put(memcg);
484 
485 	return ptr;
486 }
487 
488 #else
489 static void bpf_map_save_memcg(struct bpf_map *map)
490 {
491 }
492 
493 static void bpf_map_release_memcg(struct bpf_map *map)
494 {
495 }
496 #endif
497 
498 static int bpf_map_kptr_off_cmp(const void *a, const void *b)
499 {
500 	const struct bpf_map_value_off_desc *off_desc1 = a, *off_desc2 = b;
501 
502 	if (off_desc1->offset < off_desc2->offset)
503 		return -1;
504 	else if (off_desc1->offset > off_desc2->offset)
505 		return 1;
506 	return 0;
507 }
508 
509 struct bpf_map_value_off_desc *bpf_map_kptr_off_contains(struct bpf_map *map, u32 offset)
510 {
511 	/* Since members are iterated in btf_find_field in increasing order,
512 	 * offsets appended to kptr_off_tab are in increasing order, so we can
513 	 * do bsearch to find exact match.
514 	 */
515 	struct bpf_map_value_off *tab;
516 
517 	if (!map_value_has_kptrs(map))
518 		return NULL;
519 	tab = map->kptr_off_tab;
520 	return bsearch(&offset, tab->off, tab->nr_off, sizeof(tab->off[0]), bpf_map_kptr_off_cmp);
521 }
522 
523 void bpf_map_free_kptr_off_tab(struct bpf_map *map)
524 {
525 	struct bpf_map_value_off *tab = map->kptr_off_tab;
526 	int i;
527 
528 	if (!map_value_has_kptrs(map))
529 		return;
530 	for (i = 0; i < tab->nr_off; i++) {
531 		if (tab->off[i].kptr.module)
532 			module_put(tab->off[i].kptr.module);
533 		btf_put(tab->off[i].kptr.btf);
534 	}
535 	kfree(tab);
536 	map->kptr_off_tab = NULL;
537 }
538 
539 struct bpf_map_value_off *bpf_map_copy_kptr_off_tab(const struct bpf_map *map)
540 {
541 	struct bpf_map_value_off *tab = map->kptr_off_tab, *new_tab;
542 	int size, i;
543 
544 	if (!map_value_has_kptrs(map))
545 		return ERR_PTR(-ENOENT);
546 	size = offsetof(struct bpf_map_value_off, off[tab->nr_off]);
547 	new_tab = kmemdup(tab, size, GFP_KERNEL | __GFP_NOWARN);
548 	if (!new_tab)
549 		return ERR_PTR(-ENOMEM);
550 	/* Do a deep copy of the kptr_off_tab */
551 	for (i = 0; i < tab->nr_off; i++) {
552 		btf_get(tab->off[i].kptr.btf);
553 		if (tab->off[i].kptr.module && !try_module_get(tab->off[i].kptr.module)) {
554 			while (i--) {
555 				if (tab->off[i].kptr.module)
556 					module_put(tab->off[i].kptr.module);
557 				btf_put(tab->off[i].kptr.btf);
558 			}
559 			kfree(new_tab);
560 			return ERR_PTR(-ENXIO);
561 		}
562 	}
563 	return new_tab;
564 }
565 
566 bool bpf_map_equal_kptr_off_tab(const struct bpf_map *map_a, const struct bpf_map *map_b)
567 {
568 	struct bpf_map_value_off *tab_a = map_a->kptr_off_tab, *tab_b = map_b->kptr_off_tab;
569 	bool a_has_kptr = map_value_has_kptrs(map_a), b_has_kptr = map_value_has_kptrs(map_b);
570 	int size;
571 
572 	if (!a_has_kptr && !b_has_kptr)
573 		return true;
574 	if (a_has_kptr != b_has_kptr)
575 		return false;
576 	if (tab_a->nr_off != tab_b->nr_off)
577 		return false;
578 	size = offsetof(struct bpf_map_value_off, off[tab_a->nr_off]);
579 	return !memcmp(tab_a, tab_b, size);
580 }
581 
582 /* Caller must ensure map_value_has_kptrs is true. Note that this function can
583  * be called on a map value while the map_value is visible to BPF programs, as
584  * it ensures the correct synchronization, and we already enforce the same using
585  * the bpf_kptr_xchg helper on the BPF program side for referenced kptrs.
586  */
587 void bpf_map_free_kptrs(struct bpf_map *map, void *map_value)
588 {
589 	struct bpf_map_value_off *tab = map->kptr_off_tab;
590 	unsigned long *btf_id_ptr;
591 	int i;
592 
593 	for (i = 0; i < tab->nr_off; i++) {
594 		struct bpf_map_value_off_desc *off_desc = &tab->off[i];
595 		unsigned long old_ptr;
596 
597 		btf_id_ptr = map_value + off_desc->offset;
598 		if (off_desc->type == BPF_KPTR_UNREF) {
599 			u64 *p = (u64 *)btf_id_ptr;
600 
601 			WRITE_ONCE(*p, 0);
602 			continue;
603 		}
604 		old_ptr = xchg(btf_id_ptr, 0);
605 		off_desc->kptr.dtor((void *)old_ptr);
606 	}
607 }
608 
609 /* called from workqueue */
610 static void bpf_map_free_deferred(struct work_struct *work)
611 {
612 	struct bpf_map *map = container_of(work, struct bpf_map, work);
613 
614 	security_bpf_map_free(map);
615 	kfree(map->off_arr);
616 	bpf_map_release_memcg(map);
617 	/* implementation dependent freeing, map_free callback also does
618 	 * bpf_map_free_kptr_off_tab, if needed.
619 	 */
620 	map->ops->map_free(map);
621 }
622 
623 static void bpf_map_put_uref(struct bpf_map *map)
624 {
625 	if (atomic64_dec_and_test(&map->usercnt)) {
626 		if (map->ops->map_release_uref)
627 			map->ops->map_release_uref(map);
628 	}
629 }
630 
631 /* decrement map refcnt and schedule it for freeing via workqueue
632  * (unrelying map implementation ops->map_free() might sleep)
633  */
634 static void __bpf_map_put(struct bpf_map *map, bool do_idr_lock)
635 {
636 	if (atomic64_dec_and_test(&map->refcnt)) {
637 		/* bpf_map_free_id() must be called first */
638 		bpf_map_free_id(map, do_idr_lock);
639 		btf_put(map->btf);
640 		INIT_WORK(&map->work, bpf_map_free_deferred);
641 		/* Avoid spawning kworkers, since they all might contend
642 		 * for the same mutex like slab_mutex.
643 		 */
644 		queue_work(system_unbound_wq, &map->work);
645 	}
646 }
647 
648 void bpf_map_put(struct bpf_map *map)
649 {
650 	__bpf_map_put(map, true);
651 }
652 EXPORT_SYMBOL_GPL(bpf_map_put);
653 
654 void bpf_map_put_with_uref(struct bpf_map *map)
655 {
656 	bpf_map_put_uref(map);
657 	bpf_map_put(map);
658 }
659 
660 static int bpf_map_release(struct inode *inode, struct file *filp)
661 {
662 	struct bpf_map *map = filp->private_data;
663 
664 	if (map->ops->map_release)
665 		map->ops->map_release(map, filp);
666 
667 	bpf_map_put_with_uref(map);
668 	return 0;
669 }
670 
671 static fmode_t map_get_sys_perms(struct bpf_map *map, struct fd f)
672 {
673 	fmode_t mode = f.file->f_mode;
674 
675 	/* Our file permissions may have been overridden by global
676 	 * map permissions facing syscall side.
677 	 */
678 	if (READ_ONCE(map->frozen))
679 		mode &= ~FMODE_CAN_WRITE;
680 	return mode;
681 }
682 
683 #ifdef CONFIG_PROC_FS
684 /* Provides an approximation of the map's memory footprint.
685  * Used only to provide a backward compatibility and display
686  * a reasonable "memlock" info.
687  */
688 static unsigned long bpf_map_memory_footprint(const struct bpf_map *map)
689 {
690 	unsigned long size;
691 
692 	size = round_up(map->key_size + bpf_map_value_size(map), 8);
693 
694 	return round_up(map->max_entries * size, PAGE_SIZE);
695 }
696 
697 static void bpf_map_show_fdinfo(struct seq_file *m, struct file *filp)
698 {
699 	struct bpf_map *map = filp->private_data;
700 	u32 type = 0, jited = 0;
701 
702 	if (map_type_contains_progs(map)) {
703 		spin_lock(&map->owner.lock);
704 		type  = map->owner.type;
705 		jited = map->owner.jited;
706 		spin_unlock(&map->owner.lock);
707 	}
708 
709 	seq_printf(m,
710 		   "map_type:\t%u\n"
711 		   "key_size:\t%u\n"
712 		   "value_size:\t%u\n"
713 		   "max_entries:\t%u\n"
714 		   "map_flags:\t%#x\n"
715 		   "map_extra:\t%#llx\n"
716 		   "memlock:\t%lu\n"
717 		   "map_id:\t%u\n"
718 		   "frozen:\t%u\n",
719 		   map->map_type,
720 		   map->key_size,
721 		   map->value_size,
722 		   map->max_entries,
723 		   map->map_flags,
724 		   (unsigned long long)map->map_extra,
725 		   bpf_map_memory_footprint(map),
726 		   map->id,
727 		   READ_ONCE(map->frozen));
728 	if (type) {
729 		seq_printf(m, "owner_prog_type:\t%u\n", type);
730 		seq_printf(m, "owner_jited:\t%u\n", jited);
731 	}
732 }
733 #endif
734 
735 static ssize_t bpf_dummy_read(struct file *filp, char __user *buf, size_t siz,
736 			      loff_t *ppos)
737 {
738 	/* We need this handler such that alloc_file() enables
739 	 * f_mode with FMODE_CAN_READ.
740 	 */
741 	return -EINVAL;
742 }
743 
744 static ssize_t bpf_dummy_write(struct file *filp, const char __user *buf,
745 			       size_t siz, loff_t *ppos)
746 {
747 	/* We need this handler such that alloc_file() enables
748 	 * f_mode with FMODE_CAN_WRITE.
749 	 */
750 	return -EINVAL;
751 }
752 
753 /* called for any extra memory-mapped regions (except initial) */
754 static void bpf_map_mmap_open(struct vm_area_struct *vma)
755 {
756 	struct bpf_map *map = vma->vm_file->private_data;
757 
758 	if (vma->vm_flags & VM_MAYWRITE)
759 		bpf_map_write_active_inc(map);
760 }
761 
762 /* called for all unmapped memory region (including initial) */
763 static void bpf_map_mmap_close(struct vm_area_struct *vma)
764 {
765 	struct bpf_map *map = vma->vm_file->private_data;
766 
767 	if (vma->vm_flags & VM_MAYWRITE)
768 		bpf_map_write_active_dec(map);
769 }
770 
771 static const struct vm_operations_struct bpf_map_default_vmops = {
772 	.open		= bpf_map_mmap_open,
773 	.close		= bpf_map_mmap_close,
774 };
775 
776 static int bpf_map_mmap(struct file *filp, struct vm_area_struct *vma)
777 {
778 	struct bpf_map *map = filp->private_data;
779 	int err;
780 
781 	if (!map->ops->map_mmap || map_value_has_spin_lock(map) ||
782 	    map_value_has_timer(map) || map_value_has_kptrs(map))
783 		return -ENOTSUPP;
784 
785 	if (!(vma->vm_flags & VM_SHARED))
786 		return -EINVAL;
787 
788 	mutex_lock(&map->freeze_mutex);
789 
790 	if (vma->vm_flags & VM_WRITE) {
791 		if (map->frozen) {
792 			err = -EPERM;
793 			goto out;
794 		}
795 		/* map is meant to be read-only, so do not allow mapping as
796 		 * writable, because it's possible to leak a writable page
797 		 * reference and allows user-space to still modify it after
798 		 * freezing, while verifier will assume contents do not change
799 		 */
800 		if (map->map_flags & BPF_F_RDONLY_PROG) {
801 			err = -EACCES;
802 			goto out;
803 		}
804 	}
805 
806 	/* set default open/close callbacks */
807 	vma->vm_ops = &bpf_map_default_vmops;
808 	vma->vm_private_data = map;
809 	vma->vm_flags &= ~VM_MAYEXEC;
810 	if (!(vma->vm_flags & VM_WRITE))
811 		/* disallow re-mapping with PROT_WRITE */
812 		vma->vm_flags &= ~VM_MAYWRITE;
813 
814 	err = map->ops->map_mmap(map, vma);
815 	if (err)
816 		goto out;
817 
818 	if (vma->vm_flags & VM_MAYWRITE)
819 		bpf_map_write_active_inc(map);
820 out:
821 	mutex_unlock(&map->freeze_mutex);
822 	return err;
823 }
824 
825 static __poll_t bpf_map_poll(struct file *filp, struct poll_table_struct *pts)
826 {
827 	struct bpf_map *map = filp->private_data;
828 
829 	if (map->ops->map_poll)
830 		return map->ops->map_poll(map, filp, pts);
831 
832 	return EPOLLERR;
833 }
834 
835 const struct file_operations bpf_map_fops = {
836 #ifdef CONFIG_PROC_FS
837 	.show_fdinfo	= bpf_map_show_fdinfo,
838 #endif
839 	.release	= bpf_map_release,
840 	.read		= bpf_dummy_read,
841 	.write		= bpf_dummy_write,
842 	.mmap		= bpf_map_mmap,
843 	.poll		= bpf_map_poll,
844 };
845 
846 int bpf_map_new_fd(struct bpf_map *map, int flags)
847 {
848 	int ret;
849 
850 	ret = security_bpf_map(map, OPEN_FMODE(flags));
851 	if (ret < 0)
852 		return ret;
853 
854 	return anon_inode_getfd("bpf-map", &bpf_map_fops, map,
855 				flags | O_CLOEXEC);
856 }
857 
858 int bpf_get_file_flag(int flags)
859 {
860 	if ((flags & BPF_F_RDONLY) && (flags & BPF_F_WRONLY))
861 		return -EINVAL;
862 	if (flags & BPF_F_RDONLY)
863 		return O_RDONLY;
864 	if (flags & BPF_F_WRONLY)
865 		return O_WRONLY;
866 	return O_RDWR;
867 }
868 
869 /* helper macro to check that unused fields 'union bpf_attr' are zero */
870 #define CHECK_ATTR(CMD) \
871 	memchr_inv((void *) &attr->CMD##_LAST_FIELD + \
872 		   sizeof(attr->CMD##_LAST_FIELD), 0, \
873 		   sizeof(*attr) - \
874 		   offsetof(union bpf_attr, CMD##_LAST_FIELD) - \
875 		   sizeof(attr->CMD##_LAST_FIELD)) != NULL
876 
877 /* dst and src must have at least "size" number of bytes.
878  * Return strlen on success and < 0 on error.
879  */
880 int bpf_obj_name_cpy(char *dst, const char *src, unsigned int size)
881 {
882 	const char *end = src + size;
883 	const char *orig_src = src;
884 
885 	memset(dst, 0, size);
886 	/* Copy all isalnum(), '_' and '.' chars. */
887 	while (src < end && *src) {
888 		if (!isalnum(*src) &&
889 		    *src != '_' && *src != '.')
890 			return -EINVAL;
891 		*dst++ = *src++;
892 	}
893 
894 	/* No '\0' found in "size" number of bytes */
895 	if (src == end)
896 		return -EINVAL;
897 
898 	return src - orig_src;
899 }
900 
901 int map_check_no_btf(const struct bpf_map *map,
902 		     const struct btf *btf,
903 		     const struct btf_type *key_type,
904 		     const struct btf_type *value_type)
905 {
906 	return -ENOTSUPP;
907 }
908 
909 static int map_off_arr_cmp(const void *_a, const void *_b, const void *priv)
910 {
911 	const u32 a = *(const u32 *)_a;
912 	const u32 b = *(const u32 *)_b;
913 
914 	if (a < b)
915 		return -1;
916 	else if (a > b)
917 		return 1;
918 	return 0;
919 }
920 
921 static void map_off_arr_swap(void *_a, void *_b, int size, const void *priv)
922 {
923 	struct bpf_map *map = (struct bpf_map *)priv;
924 	u32 *off_base = map->off_arr->field_off;
925 	u32 *a = _a, *b = _b;
926 	u8 *sz_a, *sz_b;
927 
928 	sz_a = map->off_arr->field_sz + (a - off_base);
929 	sz_b = map->off_arr->field_sz + (b - off_base);
930 
931 	swap(*a, *b);
932 	swap(*sz_a, *sz_b);
933 }
934 
935 static int bpf_map_alloc_off_arr(struct bpf_map *map)
936 {
937 	bool has_spin_lock = map_value_has_spin_lock(map);
938 	bool has_timer = map_value_has_timer(map);
939 	bool has_kptrs = map_value_has_kptrs(map);
940 	struct bpf_map_off_arr *off_arr;
941 	u32 i;
942 
943 	if (!has_spin_lock && !has_timer && !has_kptrs) {
944 		map->off_arr = NULL;
945 		return 0;
946 	}
947 
948 	off_arr = kmalloc(sizeof(*map->off_arr), GFP_KERNEL | __GFP_NOWARN);
949 	if (!off_arr)
950 		return -ENOMEM;
951 	map->off_arr = off_arr;
952 
953 	off_arr->cnt = 0;
954 	if (has_spin_lock) {
955 		i = off_arr->cnt;
956 
957 		off_arr->field_off[i] = map->spin_lock_off;
958 		off_arr->field_sz[i] = sizeof(struct bpf_spin_lock);
959 		off_arr->cnt++;
960 	}
961 	if (has_timer) {
962 		i = off_arr->cnt;
963 
964 		off_arr->field_off[i] = map->timer_off;
965 		off_arr->field_sz[i] = sizeof(struct bpf_timer);
966 		off_arr->cnt++;
967 	}
968 	if (has_kptrs) {
969 		struct bpf_map_value_off *tab = map->kptr_off_tab;
970 		u32 *off = &off_arr->field_off[off_arr->cnt];
971 		u8 *sz = &off_arr->field_sz[off_arr->cnt];
972 
973 		for (i = 0; i < tab->nr_off; i++) {
974 			*off++ = tab->off[i].offset;
975 			*sz++ = sizeof(u64);
976 		}
977 		off_arr->cnt += tab->nr_off;
978 	}
979 
980 	if (off_arr->cnt == 1)
981 		return 0;
982 	sort_r(off_arr->field_off, off_arr->cnt, sizeof(off_arr->field_off[0]),
983 	       map_off_arr_cmp, map_off_arr_swap, map);
984 	return 0;
985 }
986 
987 static int map_check_btf(struct bpf_map *map, const struct btf *btf,
988 			 u32 btf_key_id, u32 btf_value_id)
989 {
990 	const struct btf_type *key_type, *value_type;
991 	u32 key_size, value_size;
992 	int ret = 0;
993 
994 	/* Some maps allow key to be unspecified. */
995 	if (btf_key_id) {
996 		key_type = btf_type_id_size(btf, &btf_key_id, &key_size);
997 		if (!key_type || key_size != map->key_size)
998 			return -EINVAL;
999 	} else {
1000 		key_type = btf_type_by_id(btf, 0);
1001 		if (!map->ops->map_check_btf)
1002 			return -EINVAL;
1003 	}
1004 
1005 	value_type = btf_type_id_size(btf, &btf_value_id, &value_size);
1006 	if (!value_type || value_size != map->value_size)
1007 		return -EINVAL;
1008 
1009 	map->spin_lock_off = btf_find_spin_lock(btf, value_type);
1010 
1011 	if (map_value_has_spin_lock(map)) {
1012 		if (map->map_flags & BPF_F_RDONLY_PROG)
1013 			return -EACCES;
1014 		if (map->map_type != BPF_MAP_TYPE_HASH &&
1015 		    map->map_type != BPF_MAP_TYPE_ARRAY &&
1016 		    map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
1017 		    map->map_type != BPF_MAP_TYPE_SK_STORAGE &&
1018 		    map->map_type != BPF_MAP_TYPE_INODE_STORAGE &&
1019 		    map->map_type != BPF_MAP_TYPE_TASK_STORAGE &&
1020 		    map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
1021 			return -ENOTSUPP;
1022 		if (map->spin_lock_off + sizeof(struct bpf_spin_lock) >
1023 		    map->value_size) {
1024 			WARN_ONCE(1,
1025 				  "verifier bug spin_lock_off %d value_size %d\n",
1026 				  map->spin_lock_off, map->value_size);
1027 			return -EFAULT;
1028 		}
1029 	}
1030 
1031 	map->timer_off = btf_find_timer(btf, value_type);
1032 	if (map_value_has_timer(map)) {
1033 		if (map->map_flags & BPF_F_RDONLY_PROG)
1034 			return -EACCES;
1035 		if (map->map_type != BPF_MAP_TYPE_HASH &&
1036 		    map->map_type != BPF_MAP_TYPE_LRU_HASH &&
1037 		    map->map_type != BPF_MAP_TYPE_ARRAY)
1038 			return -EOPNOTSUPP;
1039 	}
1040 
1041 	map->kptr_off_tab = btf_parse_kptrs(btf, value_type);
1042 	if (map_value_has_kptrs(map)) {
1043 		if (!bpf_capable()) {
1044 			ret = -EPERM;
1045 			goto free_map_tab;
1046 		}
1047 		if (map->map_flags & (BPF_F_RDONLY_PROG | BPF_F_WRONLY_PROG)) {
1048 			ret = -EACCES;
1049 			goto free_map_tab;
1050 		}
1051 		if (map->map_type != BPF_MAP_TYPE_HASH &&
1052 		    map->map_type != BPF_MAP_TYPE_LRU_HASH &&
1053 		    map->map_type != BPF_MAP_TYPE_ARRAY &&
1054 		    map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY) {
1055 			ret = -EOPNOTSUPP;
1056 			goto free_map_tab;
1057 		}
1058 	}
1059 
1060 	if (map->ops->map_check_btf) {
1061 		ret = map->ops->map_check_btf(map, btf, key_type, value_type);
1062 		if (ret < 0)
1063 			goto free_map_tab;
1064 	}
1065 
1066 	return ret;
1067 free_map_tab:
1068 	bpf_map_free_kptr_off_tab(map);
1069 	return ret;
1070 }
1071 
1072 #define BPF_MAP_CREATE_LAST_FIELD map_extra
1073 /* called via syscall */
1074 static int map_create(union bpf_attr *attr)
1075 {
1076 	int numa_node = bpf_map_attr_numa_node(attr);
1077 	struct bpf_map *map;
1078 	int f_flags;
1079 	int err;
1080 
1081 	err = CHECK_ATTR(BPF_MAP_CREATE);
1082 	if (err)
1083 		return -EINVAL;
1084 
1085 	if (attr->btf_vmlinux_value_type_id) {
1086 		if (attr->map_type != BPF_MAP_TYPE_STRUCT_OPS ||
1087 		    attr->btf_key_type_id || attr->btf_value_type_id)
1088 			return -EINVAL;
1089 	} else if (attr->btf_key_type_id && !attr->btf_value_type_id) {
1090 		return -EINVAL;
1091 	}
1092 
1093 	if (attr->map_type != BPF_MAP_TYPE_BLOOM_FILTER &&
1094 	    attr->map_extra != 0)
1095 		return -EINVAL;
1096 
1097 	f_flags = bpf_get_file_flag(attr->map_flags);
1098 	if (f_flags < 0)
1099 		return f_flags;
1100 
1101 	if (numa_node != NUMA_NO_NODE &&
1102 	    ((unsigned int)numa_node >= nr_node_ids ||
1103 	     !node_online(numa_node)))
1104 		return -EINVAL;
1105 
1106 	/* find map type and init map: hashtable vs rbtree vs bloom vs ... */
1107 	map = find_and_alloc_map(attr);
1108 	if (IS_ERR(map))
1109 		return PTR_ERR(map);
1110 
1111 	err = bpf_obj_name_cpy(map->name, attr->map_name,
1112 			       sizeof(attr->map_name));
1113 	if (err < 0)
1114 		goto free_map;
1115 
1116 	atomic64_set(&map->refcnt, 1);
1117 	atomic64_set(&map->usercnt, 1);
1118 	mutex_init(&map->freeze_mutex);
1119 	spin_lock_init(&map->owner.lock);
1120 
1121 	map->spin_lock_off = -EINVAL;
1122 	map->timer_off = -EINVAL;
1123 	if (attr->btf_key_type_id || attr->btf_value_type_id ||
1124 	    /* Even the map's value is a kernel's struct,
1125 	     * the bpf_prog.o must have BTF to begin with
1126 	     * to figure out the corresponding kernel's
1127 	     * counter part.  Thus, attr->btf_fd has
1128 	     * to be valid also.
1129 	     */
1130 	    attr->btf_vmlinux_value_type_id) {
1131 		struct btf *btf;
1132 
1133 		btf = btf_get_by_fd(attr->btf_fd);
1134 		if (IS_ERR(btf)) {
1135 			err = PTR_ERR(btf);
1136 			goto free_map;
1137 		}
1138 		if (btf_is_kernel(btf)) {
1139 			btf_put(btf);
1140 			err = -EACCES;
1141 			goto free_map;
1142 		}
1143 		map->btf = btf;
1144 
1145 		if (attr->btf_value_type_id) {
1146 			err = map_check_btf(map, btf, attr->btf_key_type_id,
1147 					    attr->btf_value_type_id);
1148 			if (err)
1149 				goto free_map;
1150 		}
1151 
1152 		map->btf_key_type_id = attr->btf_key_type_id;
1153 		map->btf_value_type_id = attr->btf_value_type_id;
1154 		map->btf_vmlinux_value_type_id =
1155 			attr->btf_vmlinux_value_type_id;
1156 	}
1157 
1158 	err = bpf_map_alloc_off_arr(map);
1159 	if (err)
1160 		goto free_map;
1161 
1162 	err = security_bpf_map_alloc(map);
1163 	if (err)
1164 		goto free_map_off_arr;
1165 
1166 	err = bpf_map_alloc_id(map);
1167 	if (err)
1168 		goto free_map_sec;
1169 
1170 	bpf_map_save_memcg(map);
1171 
1172 	err = bpf_map_new_fd(map, f_flags);
1173 	if (err < 0) {
1174 		/* failed to allocate fd.
1175 		 * bpf_map_put_with_uref() is needed because the above
1176 		 * bpf_map_alloc_id() has published the map
1177 		 * to the userspace and the userspace may
1178 		 * have refcnt-ed it through BPF_MAP_GET_FD_BY_ID.
1179 		 */
1180 		bpf_map_put_with_uref(map);
1181 		return err;
1182 	}
1183 
1184 	return err;
1185 
1186 free_map_sec:
1187 	security_bpf_map_free(map);
1188 free_map_off_arr:
1189 	kfree(map->off_arr);
1190 free_map:
1191 	btf_put(map->btf);
1192 	map->ops->map_free(map);
1193 	return err;
1194 }
1195 
1196 /* if error is returned, fd is released.
1197  * On success caller should complete fd access with matching fdput()
1198  */
1199 struct bpf_map *__bpf_map_get(struct fd f)
1200 {
1201 	if (!f.file)
1202 		return ERR_PTR(-EBADF);
1203 	if (f.file->f_op != &bpf_map_fops) {
1204 		fdput(f);
1205 		return ERR_PTR(-EINVAL);
1206 	}
1207 
1208 	return f.file->private_data;
1209 }
1210 
1211 void bpf_map_inc(struct bpf_map *map)
1212 {
1213 	atomic64_inc(&map->refcnt);
1214 }
1215 EXPORT_SYMBOL_GPL(bpf_map_inc);
1216 
1217 void bpf_map_inc_with_uref(struct bpf_map *map)
1218 {
1219 	atomic64_inc(&map->refcnt);
1220 	atomic64_inc(&map->usercnt);
1221 }
1222 EXPORT_SYMBOL_GPL(bpf_map_inc_with_uref);
1223 
1224 struct bpf_map *bpf_map_get(u32 ufd)
1225 {
1226 	struct fd f = fdget(ufd);
1227 	struct bpf_map *map;
1228 
1229 	map = __bpf_map_get(f);
1230 	if (IS_ERR(map))
1231 		return map;
1232 
1233 	bpf_map_inc(map);
1234 	fdput(f);
1235 
1236 	return map;
1237 }
1238 EXPORT_SYMBOL(bpf_map_get);
1239 
1240 struct bpf_map *bpf_map_get_with_uref(u32 ufd)
1241 {
1242 	struct fd f = fdget(ufd);
1243 	struct bpf_map *map;
1244 
1245 	map = __bpf_map_get(f);
1246 	if (IS_ERR(map))
1247 		return map;
1248 
1249 	bpf_map_inc_with_uref(map);
1250 	fdput(f);
1251 
1252 	return map;
1253 }
1254 
1255 /* map_idr_lock should have been held */
1256 static struct bpf_map *__bpf_map_inc_not_zero(struct bpf_map *map, bool uref)
1257 {
1258 	int refold;
1259 
1260 	refold = atomic64_fetch_add_unless(&map->refcnt, 1, 0);
1261 	if (!refold)
1262 		return ERR_PTR(-ENOENT);
1263 	if (uref)
1264 		atomic64_inc(&map->usercnt);
1265 
1266 	return map;
1267 }
1268 
1269 struct bpf_map *bpf_map_inc_not_zero(struct bpf_map *map)
1270 {
1271 	spin_lock_bh(&map_idr_lock);
1272 	map = __bpf_map_inc_not_zero(map, false);
1273 	spin_unlock_bh(&map_idr_lock);
1274 
1275 	return map;
1276 }
1277 EXPORT_SYMBOL_GPL(bpf_map_inc_not_zero);
1278 
1279 int __weak bpf_stackmap_copy(struct bpf_map *map, void *key, void *value)
1280 {
1281 	return -ENOTSUPP;
1282 }
1283 
1284 static void *__bpf_copy_key(void __user *ukey, u64 key_size)
1285 {
1286 	if (key_size)
1287 		return vmemdup_user(ukey, key_size);
1288 
1289 	if (ukey)
1290 		return ERR_PTR(-EINVAL);
1291 
1292 	return NULL;
1293 }
1294 
1295 static void *___bpf_copy_key(bpfptr_t ukey, u64 key_size)
1296 {
1297 	if (key_size)
1298 		return kvmemdup_bpfptr(ukey, key_size);
1299 
1300 	if (!bpfptr_is_null(ukey))
1301 		return ERR_PTR(-EINVAL);
1302 
1303 	return NULL;
1304 }
1305 
1306 /* last field in 'union bpf_attr' used by this command */
1307 #define BPF_MAP_LOOKUP_ELEM_LAST_FIELD flags
1308 
1309 static int map_lookup_elem(union bpf_attr *attr)
1310 {
1311 	void __user *ukey = u64_to_user_ptr(attr->key);
1312 	void __user *uvalue = u64_to_user_ptr(attr->value);
1313 	int ufd = attr->map_fd;
1314 	struct bpf_map *map;
1315 	void *key, *value;
1316 	u32 value_size;
1317 	struct fd f;
1318 	int err;
1319 
1320 	if (CHECK_ATTR(BPF_MAP_LOOKUP_ELEM))
1321 		return -EINVAL;
1322 
1323 	if (attr->flags & ~BPF_F_LOCK)
1324 		return -EINVAL;
1325 
1326 	f = fdget(ufd);
1327 	map = __bpf_map_get(f);
1328 	if (IS_ERR(map))
1329 		return PTR_ERR(map);
1330 	if (!(map_get_sys_perms(map, f) & FMODE_CAN_READ)) {
1331 		err = -EPERM;
1332 		goto err_put;
1333 	}
1334 
1335 	if ((attr->flags & BPF_F_LOCK) &&
1336 	    !map_value_has_spin_lock(map)) {
1337 		err = -EINVAL;
1338 		goto err_put;
1339 	}
1340 
1341 	key = __bpf_copy_key(ukey, map->key_size);
1342 	if (IS_ERR(key)) {
1343 		err = PTR_ERR(key);
1344 		goto err_put;
1345 	}
1346 
1347 	value_size = bpf_map_value_size(map);
1348 
1349 	err = -ENOMEM;
1350 	value = kvmalloc(value_size, GFP_USER | __GFP_NOWARN);
1351 	if (!value)
1352 		goto free_key;
1353 
1354 	if (map->map_type == BPF_MAP_TYPE_BLOOM_FILTER) {
1355 		if (copy_from_user(value, uvalue, value_size))
1356 			err = -EFAULT;
1357 		else
1358 			err = bpf_map_copy_value(map, key, value, attr->flags);
1359 		goto free_value;
1360 	}
1361 
1362 	err = bpf_map_copy_value(map, key, value, attr->flags);
1363 	if (err)
1364 		goto free_value;
1365 
1366 	err = -EFAULT;
1367 	if (copy_to_user(uvalue, value, value_size) != 0)
1368 		goto free_value;
1369 
1370 	err = 0;
1371 
1372 free_value:
1373 	kvfree(value);
1374 free_key:
1375 	kvfree(key);
1376 err_put:
1377 	fdput(f);
1378 	return err;
1379 }
1380 
1381 
1382 #define BPF_MAP_UPDATE_ELEM_LAST_FIELD flags
1383 
1384 static int map_update_elem(union bpf_attr *attr, bpfptr_t uattr)
1385 {
1386 	bpfptr_t ukey = make_bpfptr(attr->key, uattr.is_kernel);
1387 	bpfptr_t uvalue = make_bpfptr(attr->value, uattr.is_kernel);
1388 	int ufd = attr->map_fd;
1389 	struct bpf_map *map;
1390 	void *key, *value;
1391 	u32 value_size;
1392 	struct fd f;
1393 	int err;
1394 
1395 	if (CHECK_ATTR(BPF_MAP_UPDATE_ELEM))
1396 		return -EINVAL;
1397 
1398 	f = fdget(ufd);
1399 	map = __bpf_map_get(f);
1400 	if (IS_ERR(map))
1401 		return PTR_ERR(map);
1402 	bpf_map_write_active_inc(map);
1403 	if (!(map_get_sys_perms(map, f) & FMODE_CAN_WRITE)) {
1404 		err = -EPERM;
1405 		goto err_put;
1406 	}
1407 
1408 	if ((attr->flags & BPF_F_LOCK) &&
1409 	    !map_value_has_spin_lock(map)) {
1410 		err = -EINVAL;
1411 		goto err_put;
1412 	}
1413 
1414 	key = ___bpf_copy_key(ukey, map->key_size);
1415 	if (IS_ERR(key)) {
1416 		err = PTR_ERR(key);
1417 		goto err_put;
1418 	}
1419 
1420 	value_size = bpf_map_value_size(map);
1421 	value = kvmemdup_bpfptr(uvalue, value_size);
1422 	if (IS_ERR(value)) {
1423 		err = PTR_ERR(value);
1424 		goto free_key;
1425 	}
1426 
1427 	err = bpf_map_update_value(map, f, key, value, attr->flags);
1428 
1429 	kvfree(value);
1430 free_key:
1431 	kvfree(key);
1432 err_put:
1433 	bpf_map_write_active_dec(map);
1434 	fdput(f);
1435 	return err;
1436 }
1437 
1438 #define BPF_MAP_DELETE_ELEM_LAST_FIELD key
1439 
1440 static int map_delete_elem(union bpf_attr *attr, bpfptr_t uattr)
1441 {
1442 	bpfptr_t ukey = make_bpfptr(attr->key, uattr.is_kernel);
1443 	int ufd = attr->map_fd;
1444 	struct bpf_map *map;
1445 	struct fd f;
1446 	void *key;
1447 	int err;
1448 
1449 	if (CHECK_ATTR(BPF_MAP_DELETE_ELEM))
1450 		return -EINVAL;
1451 
1452 	f = fdget(ufd);
1453 	map = __bpf_map_get(f);
1454 	if (IS_ERR(map))
1455 		return PTR_ERR(map);
1456 	bpf_map_write_active_inc(map);
1457 	if (!(map_get_sys_perms(map, f) & FMODE_CAN_WRITE)) {
1458 		err = -EPERM;
1459 		goto err_put;
1460 	}
1461 
1462 	key = ___bpf_copy_key(ukey, map->key_size);
1463 	if (IS_ERR(key)) {
1464 		err = PTR_ERR(key);
1465 		goto err_put;
1466 	}
1467 
1468 	if (bpf_map_is_dev_bound(map)) {
1469 		err = bpf_map_offload_delete_elem(map, key);
1470 		goto out;
1471 	} else if (IS_FD_PROG_ARRAY(map) ||
1472 		   map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
1473 		/* These maps require sleepable context */
1474 		err = map->ops->map_delete_elem(map, key);
1475 		goto out;
1476 	}
1477 
1478 	bpf_disable_instrumentation();
1479 	rcu_read_lock();
1480 	err = map->ops->map_delete_elem(map, key);
1481 	rcu_read_unlock();
1482 	bpf_enable_instrumentation();
1483 	maybe_wait_bpf_programs(map);
1484 out:
1485 	kvfree(key);
1486 err_put:
1487 	bpf_map_write_active_dec(map);
1488 	fdput(f);
1489 	return err;
1490 }
1491 
1492 /* last field in 'union bpf_attr' used by this command */
1493 #define BPF_MAP_GET_NEXT_KEY_LAST_FIELD next_key
1494 
1495 static int map_get_next_key(union bpf_attr *attr)
1496 {
1497 	void __user *ukey = u64_to_user_ptr(attr->key);
1498 	void __user *unext_key = u64_to_user_ptr(attr->next_key);
1499 	int ufd = attr->map_fd;
1500 	struct bpf_map *map;
1501 	void *key, *next_key;
1502 	struct fd f;
1503 	int err;
1504 
1505 	if (CHECK_ATTR(BPF_MAP_GET_NEXT_KEY))
1506 		return -EINVAL;
1507 
1508 	f = fdget(ufd);
1509 	map = __bpf_map_get(f);
1510 	if (IS_ERR(map))
1511 		return PTR_ERR(map);
1512 	if (!(map_get_sys_perms(map, f) & FMODE_CAN_READ)) {
1513 		err = -EPERM;
1514 		goto err_put;
1515 	}
1516 
1517 	if (ukey) {
1518 		key = __bpf_copy_key(ukey, map->key_size);
1519 		if (IS_ERR(key)) {
1520 			err = PTR_ERR(key);
1521 			goto err_put;
1522 		}
1523 	} else {
1524 		key = NULL;
1525 	}
1526 
1527 	err = -ENOMEM;
1528 	next_key = kvmalloc(map->key_size, GFP_USER);
1529 	if (!next_key)
1530 		goto free_key;
1531 
1532 	if (bpf_map_is_dev_bound(map)) {
1533 		err = bpf_map_offload_get_next_key(map, key, next_key);
1534 		goto out;
1535 	}
1536 
1537 	rcu_read_lock();
1538 	err = map->ops->map_get_next_key(map, key, next_key);
1539 	rcu_read_unlock();
1540 out:
1541 	if (err)
1542 		goto free_next_key;
1543 
1544 	err = -EFAULT;
1545 	if (copy_to_user(unext_key, next_key, map->key_size) != 0)
1546 		goto free_next_key;
1547 
1548 	err = 0;
1549 
1550 free_next_key:
1551 	kvfree(next_key);
1552 free_key:
1553 	kvfree(key);
1554 err_put:
1555 	fdput(f);
1556 	return err;
1557 }
1558 
1559 int generic_map_delete_batch(struct bpf_map *map,
1560 			     const union bpf_attr *attr,
1561 			     union bpf_attr __user *uattr)
1562 {
1563 	void __user *keys = u64_to_user_ptr(attr->batch.keys);
1564 	u32 cp, max_count;
1565 	int err = 0;
1566 	void *key;
1567 
1568 	if (attr->batch.elem_flags & ~BPF_F_LOCK)
1569 		return -EINVAL;
1570 
1571 	if ((attr->batch.elem_flags & BPF_F_LOCK) &&
1572 	    !map_value_has_spin_lock(map)) {
1573 		return -EINVAL;
1574 	}
1575 
1576 	max_count = attr->batch.count;
1577 	if (!max_count)
1578 		return 0;
1579 
1580 	key = kvmalloc(map->key_size, GFP_USER | __GFP_NOWARN);
1581 	if (!key)
1582 		return -ENOMEM;
1583 
1584 	for (cp = 0; cp < max_count; cp++) {
1585 		err = -EFAULT;
1586 		if (copy_from_user(key, keys + cp * map->key_size,
1587 				   map->key_size))
1588 			break;
1589 
1590 		if (bpf_map_is_dev_bound(map)) {
1591 			err = bpf_map_offload_delete_elem(map, key);
1592 			break;
1593 		}
1594 
1595 		bpf_disable_instrumentation();
1596 		rcu_read_lock();
1597 		err = map->ops->map_delete_elem(map, key);
1598 		rcu_read_unlock();
1599 		bpf_enable_instrumentation();
1600 		if (err)
1601 			break;
1602 		cond_resched();
1603 	}
1604 	if (copy_to_user(&uattr->batch.count, &cp, sizeof(cp)))
1605 		err = -EFAULT;
1606 
1607 	kvfree(key);
1608 
1609 	maybe_wait_bpf_programs(map);
1610 	return err;
1611 }
1612 
1613 int generic_map_update_batch(struct bpf_map *map,
1614 			     const union bpf_attr *attr,
1615 			     union bpf_attr __user *uattr)
1616 {
1617 	void __user *values = u64_to_user_ptr(attr->batch.values);
1618 	void __user *keys = u64_to_user_ptr(attr->batch.keys);
1619 	u32 value_size, cp, max_count;
1620 	int ufd = attr->batch.map_fd;
1621 	void *key, *value;
1622 	struct fd f;
1623 	int err = 0;
1624 
1625 	if (attr->batch.elem_flags & ~BPF_F_LOCK)
1626 		return -EINVAL;
1627 
1628 	if ((attr->batch.elem_flags & BPF_F_LOCK) &&
1629 	    !map_value_has_spin_lock(map)) {
1630 		return -EINVAL;
1631 	}
1632 
1633 	value_size = bpf_map_value_size(map);
1634 
1635 	max_count = attr->batch.count;
1636 	if (!max_count)
1637 		return 0;
1638 
1639 	key = kvmalloc(map->key_size, GFP_USER | __GFP_NOWARN);
1640 	if (!key)
1641 		return -ENOMEM;
1642 
1643 	value = kvmalloc(value_size, GFP_USER | __GFP_NOWARN);
1644 	if (!value) {
1645 		kvfree(key);
1646 		return -ENOMEM;
1647 	}
1648 
1649 	f = fdget(ufd); /* bpf_map_do_batch() guarantees ufd is valid */
1650 	for (cp = 0; cp < max_count; cp++) {
1651 		err = -EFAULT;
1652 		if (copy_from_user(key, keys + cp * map->key_size,
1653 		    map->key_size) ||
1654 		    copy_from_user(value, values + cp * value_size, value_size))
1655 			break;
1656 
1657 		err = bpf_map_update_value(map, f, key, value,
1658 					   attr->batch.elem_flags);
1659 
1660 		if (err)
1661 			break;
1662 		cond_resched();
1663 	}
1664 
1665 	if (copy_to_user(&uattr->batch.count, &cp, sizeof(cp)))
1666 		err = -EFAULT;
1667 
1668 	kvfree(value);
1669 	kvfree(key);
1670 	fdput(f);
1671 	return err;
1672 }
1673 
1674 #define MAP_LOOKUP_RETRIES 3
1675 
1676 int generic_map_lookup_batch(struct bpf_map *map,
1677 				    const union bpf_attr *attr,
1678 				    union bpf_attr __user *uattr)
1679 {
1680 	void __user *uobatch = u64_to_user_ptr(attr->batch.out_batch);
1681 	void __user *ubatch = u64_to_user_ptr(attr->batch.in_batch);
1682 	void __user *values = u64_to_user_ptr(attr->batch.values);
1683 	void __user *keys = u64_to_user_ptr(attr->batch.keys);
1684 	void *buf, *buf_prevkey, *prev_key, *key, *value;
1685 	int err, retry = MAP_LOOKUP_RETRIES;
1686 	u32 value_size, cp, max_count;
1687 
1688 	if (attr->batch.elem_flags & ~BPF_F_LOCK)
1689 		return -EINVAL;
1690 
1691 	if ((attr->batch.elem_flags & BPF_F_LOCK) &&
1692 	    !map_value_has_spin_lock(map))
1693 		return -EINVAL;
1694 
1695 	value_size = bpf_map_value_size(map);
1696 
1697 	max_count = attr->batch.count;
1698 	if (!max_count)
1699 		return 0;
1700 
1701 	if (put_user(0, &uattr->batch.count))
1702 		return -EFAULT;
1703 
1704 	buf_prevkey = kvmalloc(map->key_size, GFP_USER | __GFP_NOWARN);
1705 	if (!buf_prevkey)
1706 		return -ENOMEM;
1707 
1708 	buf = kvmalloc(map->key_size + value_size, GFP_USER | __GFP_NOWARN);
1709 	if (!buf) {
1710 		kvfree(buf_prevkey);
1711 		return -ENOMEM;
1712 	}
1713 
1714 	err = -EFAULT;
1715 	prev_key = NULL;
1716 	if (ubatch && copy_from_user(buf_prevkey, ubatch, map->key_size))
1717 		goto free_buf;
1718 	key = buf;
1719 	value = key + map->key_size;
1720 	if (ubatch)
1721 		prev_key = buf_prevkey;
1722 
1723 	for (cp = 0; cp < max_count;) {
1724 		rcu_read_lock();
1725 		err = map->ops->map_get_next_key(map, prev_key, key);
1726 		rcu_read_unlock();
1727 		if (err)
1728 			break;
1729 		err = bpf_map_copy_value(map, key, value,
1730 					 attr->batch.elem_flags);
1731 
1732 		if (err == -ENOENT) {
1733 			if (retry) {
1734 				retry--;
1735 				continue;
1736 			}
1737 			err = -EINTR;
1738 			break;
1739 		}
1740 
1741 		if (err)
1742 			goto free_buf;
1743 
1744 		if (copy_to_user(keys + cp * map->key_size, key,
1745 				 map->key_size)) {
1746 			err = -EFAULT;
1747 			goto free_buf;
1748 		}
1749 		if (copy_to_user(values + cp * value_size, value, value_size)) {
1750 			err = -EFAULT;
1751 			goto free_buf;
1752 		}
1753 
1754 		if (!prev_key)
1755 			prev_key = buf_prevkey;
1756 
1757 		swap(prev_key, key);
1758 		retry = MAP_LOOKUP_RETRIES;
1759 		cp++;
1760 		cond_resched();
1761 	}
1762 
1763 	if (err == -EFAULT)
1764 		goto free_buf;
1765 
1766 	if ((copy_to_user(&uattr->batch.count, &cp, sizeof(cp)) ||
1767 		    (cp && copy_to_user(uobatch, prev_key, map->key_size))))
1768 		err = -EFAULT;
1769 
1770 free_buf:
1771 	kvfree(buf_prevkey);
1772 	kvfree(buf);
1773 	return err;
1774 }
1775 
1776 #define BPF_MAP_LOOKUP_AND_DELETE_ELEM_LAST_FIELD flags
1777 
1778 static int map_lookup_and_delete_elem(union bpf_attr *attr)
1779 {
1780 	void __user *ukey = u64_to_user_ptr(attr->key);
1781 	void __user *uvalue = u64_to_user_ptr(attr->value);
1782 	int ufd = attr->map_fd;
1783 	struct bpf_map *map;
1784 	void *key, *value;
1785 	u32 value_size;
1786 	struct fd f;
1787 	int err;
1788 
1789 	if (CHECK_ATTR(BPF_MAP_LOOKUP_AND_DELETE_ELEM))
1790 		return -EINVAL;
1791 
1792 	if (attr->flags & ~BPF_F_LOCK)
1793 		return -EINVAL;
1794 
1795 	f = fdget(ufd);
1796 	map = __bpf_map_get(f);
1797 	if (IS_ERR(map))
1798 		return PTR_ERR(map);
1799 	bpf_map_write_active_inc(map);
1800 	if (!(map_get_sys_perms(map, f) & FMODE_CAN_READ) ||
1801 	    !(map_get_sys_perms(map, f) & FMODE_CAN_WRITE)) {
1802 		err = -EPERM;
1803 		goto err_put;
1804 	}
1805 
1806 	if (attr->flags &&
1807 	    (map->map_type == BPF_MAP_TYPE_QUEUE ||
1808 	     map->map_type == BPF_MAP_TYPE_STACK)) {
1809 		err = -EINVAL;
1810 		goto err_put;
1811 	}
1812 
1813 	if ((attr->flags & BPF_F_LOCK) &&
1814 	    !map_value_has_spin_lock(map)) {
1815 		err = -EINVAL;
1816 		goto err_put;
1817 	}
1818 
1819 	key = __bpf_copy_key(ukey, map->key_size);
1820 	if (IS_ERR(key)) {
1821 		err = PTR_ERR(key);
1822 		goto err_put;
1823 	}
1824 
1825 	value_size = bpf_map_value_size(map);
1826 
1827 	err = -ENOMEM;
1828 	value = kvmalloc(value_size, GFP_USER | __GFP_NOWARN);
1829 	if (!value)
1830 		goto free_key;
1831 
1832 	err = -ENOTSUPP;
1833 	if (map->map_type == BPF_MAP_TYPE_QUEUE ||
1834 	    map->map_type == BPF_MAP_TYPE_STACK) {
1835 		err = map->ops->map_pop_elem(map, value);
1836 	} else if (map->map_type == BPF_MAP_TYPE_HASH ||
1837 		   map->map_type == BPF_MAP_TYPE_PERCPU_HASH ||
1838 		   map->map_type == BPF_MAP_TYPE_LRU_HASH ||
1839 		   map->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH) {
1840 		if (!bpf_map_is_dev_bound(map)) {
1841 			bpf_disable_instrumentation();
1842 			rcu_read_lock();
1843 			err = map->ops->map_lookup_and_delete_elem(map, key, value, attr->flags);
1844 			rcu_read_unlock();
1845 			bpf_enable_instrumentation();
1846 		}
1847 	}
1848 
1849 	if (err)
1850 		goto free_value;
1851 
1852 	if (copy_to_user(uvalue, value, value_size) != 0) {
1853 		err = -EFAULT;
1854 		goto free_value;
1855 	}
1856 
1857 	err = 0;
1858 
1859 free_value:
1860 	kvfree(value);
1861 free_key:
1862 	kvfree(key);
1863 err_put:
1864 	bpf_map_write_active_dec(map);
1865 	fdput(f);
1866 	return err;
1867 }
1868 
1869 #define BPF_MAP_FREEZE_LAST_FIELD map_fd
1870 
1871 static int map_freeze(const union bpf_attr *attr)
1872 {
1873 	int err = 0, ufd = attr->map_fd;
1874 	struct bpf_map *map;
1875 	struct fd f;
1876 
1877 	if (CHECK_ATTR(BPF_MAP_FREEZE))
1878 		return -EINVAL;
1879 
1880 	f = fdget(ufd);
1881 	map = __bpf_map_get(f);
1882 	if (IS_ERR(map))
1883 		return PTR_ERR(map);
1884 
1885 	if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS ||
1886 	    map_value_has_timer(map) || map_value_has_kptrs(map)) {
1887 		fdput(f);
1888 		return -ENOTSUPP;
1889 	}
1890 
1891 	mutex_lock(&map->freeze_mutex);
1892 	if (bpf_map_write_active(map)) {
1893 		err = -EBUSY;
1894 		goto err_put;
1895 	}
1896 	if (READ_ONCE(map->frozen)) {
1897 		err = -EBUSY;
1898 		goto err_put;
1899 	}
1900 	if (!bpf_capable()) {
1901 		err = -EPERM;
1902 		goto err_put;
1903 	}
1904 
1905 	WRITE_ONCE(map->frozen, true);
1906 err_put:
1907 	mutex_unlock(&map->freeze_mutex);
1908 	fdput(f);
1909 	return err;
1910 }
1911 
1912 static const struct bpf_prog_ops * const bpf_prog_types[] = {
1913 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
1914 	[_id] = & _name ## _prog_ops,
1915 #define BPF_MAP_TYPE(_id, _ops)
1916 #define BPF_LINK_TYPE(_id, _name)
1917 #include <linux/bpf_types.h>
1918 #undef BPF_PROG_TYPE
1919 #undef BPF_MAP_TYPE
1920 #undef BPF_LINK_TYPE
1921 };
1922 
1923 static int find_prog_type(enum bpf_prog_type type, struct bpf_prog *prog)
1924 {
1925 	const struct bpf_prog_ops *ops;
1926 
1927 	if (type >= ARRAY_SIZE(bpf_prog_types))
1928 		return -EINVAL;
1929 	type = array_index_nospec(type, ARRAY_SIZE(bpf_prog_types));
1930 	ops = bpf_prog_types[type];
1931 	if (!ops)
1932 		return -EINVAL;
1933 
1934 	if (!bpf_prog_is_dev_bound(prog->aux))
1935 		prog->aux->ops = ops;
1936 	else
1937 		prog->aux->ops = &bpf_offload_prog_ops;
1938 	prog->type = type;
1939 	return 0;
1940 }
1941 
1942 enum bpf_audit {
1943 	BPF_AUDIT_LOAD,
1944 	BPF_AUDIT_UNLOAD,
1945 	BPF_AUDIT_MAX,
1946 };
1947 
1948 static const char * const bpf_audit_str[BPF_AUDIT_MAX] = {
1949 	[BPF_AUDIT_LOAD]   = "LOAD",
1950 	[BPF_AUDIT_UNLOAD] = "UNLOAD",
1951 };
1952 
1953 static void bpf_audit_prog(const struct bpf_prog *prog, unsigned int op)
1954 {
1955 	struct audit_context *ctx = NULL;
1956 	struct audit_buffer *ab;
1957 
1958 	if (WARN_ON_ONCE(op >= BPF_AUDIT_MAX))
1959 		return;
1960 	if (audit_enabled == AUDIT_OFF)
1961 		return;
1962 	if (op == BPF_AUDIT_LOAD)
1963 		ctx = audit_context();
1964 	ab = audit_log_start(ctx, GFP_ATOMIC, AUDIT_BPF);
1965 	if (unlikely(!ab))
1966 		return;
1967 	audit_log_format(ab, "prog-id=%u op=%s",
1968 			 prog->aux->id, bpf_audit_str[op]);
1969 	audit_log_end(ab);
1970 }
1971 
1972 static int bpf_prog_alloc_id(struct bpf_prog *prog)
1973 {
1974 	int id;
1975 
1976 	idr_preload(GFP_KERNEL);
1977 	spin_lock_bh(&prog_idr_lock);
1978 	id = idr_alloc_cyclic(&prog_idr, prog, 1, INT_MAX, GFP_ATOMIC);
1979 	if (id > 0)
1980 		prog->aux->id = id;
1981 	spin_unlock_bh(&prog_idr_lock);
1982 	idr_preload_end();
1983 
1984 	/* id is in [1, INT_MAX) */
1985 	if (WARN_ON_ONCE(!id))
1986 		return -ENOSPC;
1987 
1988 	return id > 0 ? 0 : id;
1989 }
1990 
1991 void bpf_prog_free_id(struct bpf_prog *prog, bool do_idr_lock)
1992 {
1993 	unsigned long flags;
1994 
1995 	/* cBPF to eBPF migrations are currently not in the idr store.
1996 	 * Offloaded programs are removed from the store when their device
1997 	 * disappears - even if someone grabs an fd to them they are unusable,
1998 	 * simply waiting for refcnt to drop to be freed.
1999 	 */
2000 	if (!prog->aux->id)
2001 		return;
2002 
2003 	if (do_idr_lock)
2004 		spin_lock_irqsave(&prog_idr_lock, flags);
2005 	else
2006 		__acquire(&prog_idr_lock);
2007 
2008 	idr_remove(&prog_idr, prog->aux->id);
2009 	prog->aux->id = 0;
2010 
2011 	if (do_idr_lock)
2012 		spin_unlock_irqrestore(&prog_idr_lock, flags);
2013 	else
2014 		__release(&prog_idr_lock);
2015 }
2016 
2017 static void __bpf_prog_put_rcu(struct rcu_head *rcu)
2018 {
2019 	struct bpf_prog_aux *aux = container_of(rcu, struct bpf_prog_aux, rcu);
2020 
2021 	kvfree(aux->func_info);
2022 	kfree(aux->func_info_aux);
2023 	free_uid(aux->user);
2024 	security_bpf_prog_free(aux);
2025 	bpf_prog_free(aux->prog);
2026 }
2027 
2028 static void __bpf_prog_put_noref(struct bpf_prog *prog, bool deferred)
2029 {
2030 	bpf_prog_kallsyms_del_all(prog);
2031 	btf_put(prog->aux->btf);
2032 	kvfree(prog->aux->jited_linfo);
2033 	kvfree(prog->aux->linfo);
2034 	kfree(prog->aux->kfunc_tab);
2035 	if (prog->aux->attach_btf)
2036 		btf_put(prog->aux->attach_btf);
2037 
2038 	if (deferred) {
2039 		if (prog->aux->sleepable)
2040 			call_rcu_tasks_trace(&prog->aux->rcu, __bpf_prog_put_rcu);
2041 		else
2042 			call_rcu(&prog->aux->rcu, __bpf_prog_put_rcu);
2043 	} else {
2044 		__bpf_prog_put_rcu(&prog->aux->rcu);
2045 	}
2046 }
2047 
2048 static void bpf_prog_put_deferred(struct work_struct *work)
2049 {
2050 	struct bpf_prog_aux *aux;
2051 	struct bpf_prog *prog;
2052 
2053 	aux = container_of(work, struct bpf_prog_aux, work);
2054 	prog = aux->prog;
2055 	perf_event_bpf_event(prog, PERF_BPF_EVENT_PROG_UNLOAD, 0);
2056 	bpf_audit_prog(prog, BPF_AUDIT_UNLOAD);
2057 	__bpf_prog_put_noref(prog, true);
2058 }
2059 
2060 static void __bpf_prog_put(struct bpf_prog *prog, bool do_idr_lock)
2061 {
2062 	struct bpf_prog_aux *aux = prog->aux;
2063 
2064 	if (atomic64_dec_and_test(&aux->refcnt)) {
2065 		/* bpf_prog_free_id() must be called first */
2066 		bpf_prog_free_id(prog, do_idr_lock);
2067 
2068 		if (in_irq() || irqs_disabled()) {
2069 			INIT_WORK(&aux->work, bpf_prog_put_deferred);
2070 			schedule_work(&aux->work);
2071 		} else {
2072 			bpf_prog_put_deferred(&aux->work);
2073 		}
2074 	}
2075 }
2076 
2077 void bpf_prog_put(struct bpf_prog *prog)
2078 {
2079 	__bpf_prog_put(prog, true);
2080 }
2081 EXPORT_SYMBOL_GPL(bpf_prog_put);
2082 
2083 static int bpf_prog_release(struct inode *inode, struct file *filp)
2084 {
2085 	struct bpf_prog *prog = filp->private_data;
2086 
2087 	bpf_prog_put(prog);
2088 	return 0;
2089 }
2090 
2091 struct bpf_prog_kstats {
2092 	u64 nsecs;
2093 	u64 cnt;
2094 	u64 misses;
2095 };
2096 
2097 void notrace bpf_prog_inc_misses_counter(struct bpf_prog *prog)
2098 {
2099 	struct bpf_prog_stats *stats;
2100 	unsigned int flags;
2101 
2102 	stats = this_cpu_ptr(prog->stats);
2103 	flags = u64_stats_update_begin_irqsave(&stats->syncp);
2104 	u64_stats_inc(&stats->misses);
2105 	u64_stats_update_end_irqrestore(&stats->syncp, flags);
2106 }
2107 
2108 static void bpf_prog_get_stats(const struct bpf_prog *prog,
2109 			       struct bpf_prog_kstats *stats)
2110 {
2111 	u64 nsecs = 0, cnt = 0, misses = 0;
2112 	int cpu;
2113 
2114 	for_each_possible_cpu(cpu) {
2115 		const struct bpf_prog_stats *st;
2116 		unsigned int start;
2117 		u64 tnsecs, tcnt, tmisses;
2118 
2119 		st = per_cpu_ptr(prog->stats, cpu);
2120 		do {
2121 			start = u64_stats_fetch_begin(&st->syncp);
2122 			tnsecs = u64_stats_read(&st->nsecs);
2123 			tcnt = u64_stats_read(&st->cnt);
2124 			tmisses = u64_stats_read(&st->misses);
2125 		} while (u64_stats_fetch_retry(&st->syncp, start));
2126 		nsecs += tnsecs;
2127 		cnt += tcnt;
2128 		misses += tmisses;
2129 	}
2130 	stats->nsecs = nsecs;
2131 	stats->cnt = cnt;
2132 	stats->misses = misses;
2133 }
2134 
2135 #ifdef CONFIG_PROC_FS
2136 static void bpf_prog_show_fdinfo(struct seq_file *m, struct file *filp)
2137 {
2138 	const struct bpf_prog *prog = filp->private_data;
2139 	char prog_tag[sizeof(prog->tag) * 2 + 1] = { };
2140 	struct bpf_prog_kstats stats;
2141 
2142 	bpf_prog_get_stats(prog, &stats);
2143 	bin2hex(prog_tag, prog->tag, sizeof(prog->tag));
2144 	seq_printf(m,
2145 		   "prog_type:\t%u\n"
2146 		   "prog_jited:\t%u\n"
2147 		   "prog_tag:\t%s\n"
2148 		   "memlock:\t%llu\n"
2149 		   "prog_id:\t%u\n"
2150 		   "run_time_ns:\t%llu\n"
2151 		   "run_cnt:\t%llu\n"
2152 		   "recursion_misses:\t%llu\n"
2153 		   "verified_insns:\t%u\n",
2154 		   prog->type,
2155 		   prog->jited,
2156 		   prog_tag,
2157 		   prog->pages * 1ULL << PAGE_SHIFT,
2158 		   prog->aux->id,
2159 		   stats.nsecs,
2160 		   stats.cnt,
2161 		   stats.misses,
2162 		   prog->aux->verified_insns);
2163 }
2164 #endif
2165 
2166 const struct file_operations bpf_prog_fops = {
2167 #ifdef CONFIG_PROC_FS
2168 	.show_fdinfo	= bpf_prog_show_fdinfo,
2169 #endif
2170 	.release	= bpf_prog_release,
2171 	.read		= bpf_dummy_read,
2172 	.write		= bpf_dummy_write,
2173 };
2174 
2175 int bpf_prog_new_fd(struct bpf_prog *prog)
2176 {
2177 	int ret;
2178 
2179 	ret = security_bpf_prog(prog);
2180 	if (ret < 0)
2181 		return ret;
2182 
2183 	return anon_inode_getfd("bpf-prog", &bpf_prog_fops, prog,
2184 				O_RDWR | O_CLOEXEC);
2185 }
2186 
2187 static struct bpf_prog *____bpf_prog_get(struct fd f)
2188 {
2189 	if (!f.file)
2190 		return ERR_PTR(-EBADF);
2191 	if (f.file->f_op != &bpf_prog_fops) {
2192 		fdput(f);
2193 		return ERR_PTR(-EINVAL);
2194 	}
2195 
2196 	return f.file->private_data;
2197 }
2198 
2199 void bpf_prog_add(struct bpf_prog *prog, int i)
2200 {
2201 	atomic64_add(i, &prog->aux->refcnt);
2202 }
2203 EXPORT_SYMBOL_GPL(bpf_prog_add);
2204 
2205 void bpf_prog_sub(struct bpf_prog *prog, int i)
2206 {
2207 	/* Only to be used for undoing previous bpf_prog_add() in some
2208 	 * error path. We still know that another entity in our call
2209 	 * path holds a reference to the program, thus atomic_sub() can
2210 	 * be safely used in such cases!
2211 	 */
2212 	WARN_ON(atomic64_sub_return(i, &prog->aux->refcnt) == 0);
2213 }
2214 EXPORT_SYMBOL_GPL(bpf_prog_sub);
2215 
2216 void bpf_prog_inc(struct bpf_prog *prog)
2217 {
2218 	atomic64_inc(&prog->aux->refcnt);
2219 }
2220 EXPORT_SYMBOL_GPL(bpf_prog_inc);
2221 
2222 /* prog_idr_lock should have been held */
2223 struct bpf_prog *bpf_prog_inc_not_zero(struct bpf_prog *prog)
2224 {
2225 	int refold;
2226 
2227 	refold = atomic64_fetch_add_unless(&prog->aux->refcnt, 1, 0);
2228 
2229 	if (!refold)
2230 		return ERR_PTR(-ENOENT);
2231 
2232 	return prog;
2233 }
2234 EXPORT_SYMBOL_GPL(bpf_prog_inc_not_zero);
2235 
2236 bool bpf_prog_get_ok(struct bpf_prog *prog,
2237 			    enum bpf_prog_type *attach_type, bool attach_drv)
2238 {
2239 	/* not an attachment, just a refcount inc, always allow */
2240 	if (!attach_type)
2241 		return true;
2242 
2243 	if (prog->type != *attach_type)
2244 		return false;
2245 	if (bpf_prog_is_dev_bound(prog->aux) && !attach_drv)
2246 		return false;
2247 
2248 	return true;
2249 }
2250 
2251 static struct bpf_prog *__bpf_prog_get(u32 ufd, enum bpf_prog_type *attach_type,
2252 				       bool attach_drv)
2253 {
2254 	struct fd f = fdget(ufd);
2255 	struct bpf_prog *prog;
2256 
2257 	prog = ____bpf_prog_get(f);
2258 	if (IS_ERR(prog))
2259 		return prog;
2260 	if (!bpf_prog_get_ok(prog, attach_type, attach_drv)) {
2261 		prog = ERR_PTR(-EINVAL);
2262 		goto out;
2263 	}
2264 
2265 	bpf_prog_inc(prog);
2266 out:
2267 	fdput(f);
2268 	return prog;
2269 }
2270 
2271 struct bpf_prog *bpf_prog_get(u32 ufd)
2272 {
2273 	return __bpf_prog_get(ufd, NULL, false);
2274 }
2275 
2276 struct bpf_prog *bpf_prog_get_type_dev(u32 ufd, enum bpf_prog_type type,
2277 				       bool attach_drv)
2278 {
2279 	return __bpf_prog_get(ufd, &type, attach_drv);
2280 }
2281 EXPORT_SYMBOL_GPL(bpf_prog_get_type_dev);
2282 
2283 /* Initially all BPF programs could be loaded w/o specifying
2284  * expected_attach_type. Later for some of them specifying expected_attach_type
2285  * at load time became required so that program could be validated properly.
2286  * Programs of types that are allowed to be loaded both w/ and w/o (for
2287  * backward compatibility) expected_attach_type, should have the default attach
2288  * type assigned to expected_attach_type for the latter case, so that it can be
2289  * validated later at attach time.
2290  *
2291  * bpf_prog_load_fixup_attach_type() sets expected_attach_type in @attr if
2292  * prog type requires it but has some attach types that have to be backward
2293  * compatible.
2294  */
2295 static void bpf_prog_load_fixup_attach_type(union bpf_attr *attr)
2296 {
2297 	switch (attr->prog_type) {
2298 	case BPF_PROG_TYPE_CGROUP_SOCK:
2299 		/* Unfortunately BPF_ATTACH_TYPE_UNSPEC enumeration doesn't
2300 		 * exist so checking for non-zero is the way to go here.
2301 		 */
2302 		if (!attr->expected_attach_type)
2303 			attr->expected_attach_type =
2304 				BPF_CGROUP_INET_SOCK_CREATE;
2305 		break;
2306 	case BPF_PROG_TYPE_SK_REUSEPORT:
2307 		if (!attr->expected_attach_type)
2308 			attr->expected_attach_type =
2309 				BPF_SK_REUSEPORT_SELECT;
2310 		break;
2311 	}
2312 }
2313 
2314 static int
2315 bpf_prog_load_check_attach(enum bpf_prog_type prog_type,
2316 			   enum bpf_attach_type expected_attach_type,
2317 			   struct btf *attach_btf, u32 btf_id,
2318 			   struct bpf_prog *dst_prog)
2319 {
2320 	if (btf_id) {
2321 		if (btf_id > BTF_MAX_TYPE)
2322 			return -EINVAL;
2323 
2324 		if (!attach_btf && !dst_prog)
2325 			return -EINVAL;
2326 
2327 		switch (prog_type) {
2328 		case BPF_PROG_TYPE_TRACING:
2329 		case BPF_PROG_TYPE_LSM:
2330 		case BPF_PROG_TYPE_STRUCT_OPS:
2331 		case BPF_PROG_TYPE_EXT:
2332 			break;
2333 		default:
2334 			return -EINVAL;
2335 		}
2336 	}
2337 
2338 	if (attach_btf && (!btf_id || dst_prog))
2339 		return -EINVAL;
2340 
2341 	if (dst_prog && prog_type != BPF_PROG_TYPE_TRACING &&
2342 	    prog_type != BPF_PROG_TYPE_EXT)
2343 		return -EINVAL;
2344 
2345 	switch (prog_type) {
2346 	case BPF_PROG_TYPE_CGROUP_SOCK:
2347 		switch (expected_attach_type) {
2348 		case BPF_CGROUP_INET_SOCK_CREATE:
2349 		case BPF_CGROUP_INET_SOCK_RELEASE:
2350 		case BPF_CGROUP_INET4_POST_BIND:
2351 		case BPF_CGROUP_INET6_POST_BIND:
2352 			return 0;
2353 		default:
2354 			return -EINVAL;
2355 		}
2356 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
2357 		switch (expected_attach_type) {
2358 		case BPF_CGROUP_INET4_BIND:
2359 		case BPF_CGROUP_INET6_BIND:
2360 		case BPF_CGROUP_INET4_CONNECT:
2361 		case BPF_CGROUP_INET6_CONNECT:
2362 		case BPF_CGROUP_INET4_GETPEERNAME:
2363 		case BPF_CGROUP_INET6_GETPEERNAME:
2364 		case BPF_CGROUP_INET4_GETSOCKNAME:
2365 		case BPF_CGROUP_INET6_GETSOCKNAME:
2366 		case BPF_CGROUP_UDP4_SENDMSG:
2367 		case BPF_CGROUP_UDP6_SENDMSG:
2368 		case BPF_CGROUP_UDP4_RECVMSG:
2369 		case BPF_CGROUP_UDP6_RECVMSG:
2370 			return 0;
2371 		default:
2372 			return -EINVAL;
2373 		}
2374 	case BPF_PROG_TYPE_CGROUP_SKB:
2375 		switch (expected_attach_type) {
2376 		case BPF_CGROUP_INET_INGRESS:
2377 		case BPF_CGROUP_INET_EGRESS:
2378 			return 0;
2379 		default:
2380 			return -EINVAL;
2381 		}
2382 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
2383 		switch (expected_attach_type) {
2384 		case BPF_CGROUP_SETSOCKOPT:
2385 		case BPF_CGROUP_GETSOCKOPT:
2386 			return 0;
2387 		default:
2388 			return -EINVAL;
2389 		}
2390 	case BPF_PROG_TYPE_SK_LOOKUP:
2391 		if (expected_attach_type == BPF_SK_LOOKUP)
2392 			return 0;
2393 		return -EINVAL;
2394 	case BPF_PROG_TYPE_SK_REUSEPORT:
2395 		switch (expected_attach_type) {
2396 		case BPF_SK_REUSEPORT_SELECT:
2397 		case BPF_SK_REUSEPORT_SELECT_OR_MIGRATE:
2398 			return 0;
2399 		default:
2400 			return -EINVAL;
2401 		}
2402 	case BPF_PROG_TYPE_SYSCALL:
2403 	case BPF_PROG_TYPE_EXT:
2404 		if (expected_attach_type)
2405 			return -EINVAL;
2406 		fallthrough;
2407 	default:
2408 		return 0;
2409 	}
2410 }
2411 
2412 static bool is_net_admin_prog_type(enum bpf_prog_type prog_type)
2413 {
2414 	switch (prog_type) {
2415 	case BPF_PROG_TYPE_SCHED_CLS:
2416 	case BPF_PROG_TYPE_SCHED_ACT:
2417 	case BPF_PROG_TYPE_XDP:
2418 	case BPF_PROG_TYPE_LWT_IN:
2419 	case BPF_PROG_TYPE_LWT_OUT:
2420 	case BPF_PROG_TYPE_LWT_XMIT:
2421 	case BPF_PROG_TYPE_LWT_SEG6LOCAL:
2422 	case BPF_PROG_TYPE_SK_SKB:
2423 	case BPF_PROG_TYPE_SK_MSG:
2424 	case BPF_PROG_TYPE_LIRC_MODE2:
2425 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
2426 	case BPF_PROG_TYPE_CGROUP_DEVICE:
2427 	case BPF_PROG_TYPE_CGROUP_SOCK:
2428 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
2429 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
2430 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
2431 	case BPF_PROG_TYPE_SOCK_OPS:
2432 	case BPF_PROG_TYPE_EXT: /* extends any prog */
2433 		return true;
2434 	case BPF_PROG_TYPE_CGROUP_SKB:
2435 		/* always unpriv */
2436 	case BPF_PROG_TYPE_SK_REUSEPORT:
2437 		/* equivalent to SOCKET_FILTER. need CAP_BPF only */
2438 	default:
2439 		return false;
2440 	}
2441 }
2442 
2443 static bool is_perfmon_prog_type(enum bpf_prog_type prog_type)
2444 {
2445 	switch (prog_type) {
2446 	case BPF_PROG_TYPE_KPROBE:
2447 	case BPF_PROG_TYPE_TRACEPOINT:
2448 	case BPF_PROG_TYPE_PERF_EVENT:
2449 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
2450 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
2451 	case BPF_PROG_TYPE_TRACING:
2452 	case BPF_PROG_TYPE_LSM:
2453 	case BPF_PROG_TYPE_STRUCT_OPS: /* has access to struct sock */
2454 	case BPF_PROG_TYPE_EXT: /* extends any prog */
2455 		return true;
2456 	default:
2457 		return false;
2458 	}
2459 }
2460 
2461 /* last field in 'union bpf_attr' used by this command */
2462 #define	BPF_PROG_LOAD_LAST_FIELD core_relo_rec_size
2463 
2464 static int bpf_prog_load(union bpf_attr *attr, bpfptr_t uattr)
2465 {
2466 	enum bpf_prog_type type = attr->prog_type;
2467 	struct bpf_prog *prog, *dst_prog = NULL;
2468 	struct btf *attach_btf = NULL;
2469 	int err;
2470 	char license[128];
2471 	bool is_gpl;
2472 
2473 	if (CHECK_ATTR(BPF_PROG_LOAD))
2474 		return -EINVAL;
2475 
2476 	if (attr->prog_flags & ~(BPF_F_STRICT_ALIGNMENT |
2477 				 BPF_F_ANY_ALIGNMENT |
2478 				 BPF_F_TEST_STATE_FREQ |
2479 				 BPF_F_SLEEPABLE |
2480 				 BPF_F_TEST_RND_HI32 |
2481 				 BPF_F_XDP_HAS_FRAGS))
2482 		return -EINVAL;
2483 
2484 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS) &&
2485 	    (attr->prog_flags & BPF_F_ANY_ALIGNMENT) &&
2486 	    !bpf_capable())
2487 		return -EPERM;
2488 
2489 	/* copy eBPF program license from user space */
2490 	if (strncpy_from_bpfptr(license,
2491 				make_bpfptr(attr->license, uattr.is_kernel),
2492 				sizeof(license) - 1) < 0)
2493 		return -EFAULT;
2494 	license[sizeof(license) - 1] = 0;
2495 
2496 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
2497 	is_gpl = license_is_gpl_compatible(license);
2498 
2499 	if (attr->insn_cnt == 0 ||
2500 	    attr->insn_cnt > (bpf_capable() ? BPF_COMPLEXITY_LIMIT_INSNS : BPF_MAXINSNS))
2501 		return -E2BIG;
2502 	if (type != BPF_PROG_TYPE_SOCKET_FILTER &&
2503 	    type != BPF_PROG_TYPE_CGROUP_SKB &&
2504 	    !bpf_capable())
2505 		return -EPERM;
2506 
2507 	if (is_net_admin_prog_type(type) && !capable(CAP_NET_ADMIN) && !capable(CAP_SYS_ADMIN))
2508 		return -EPERM;
2509 	if (is_perfmon_prog_type(type) && !perfmon_capable())
2510 		return -EPERM;
2511 
2512 	/* attach_prog_fd/attach_btf_obj_fd can specify fd of either bpf_prog
2513 	 * or btf, we need to check which one it is
2514 	 */
2515 	if (attr->attach_prog_fd) {
2516 		dst_prog = bpf_prog_get(attr->attach_prog_fd);
2517 		if (IS_ERR(dst_prog)) {
2518 			dst_prog = NULL;
2519 			attach_btf = btf_get_by_fd(attr->attach_btf_obj_fd);
2520 			if (IS_ERR(attach_btf))
2521 				return -EINVAL;
2522 			if (!btf_is_kernel(attach_btf)) {
2523 				/* attaching through specifying bpf_prog's BTF
2524 				 * objects directly might be supported eventually
2525 				 */
2526 				btf_put(attach_btf);
2527 				return -ENOTSUPP;
2528 			}
2529 		}
2530 	} else if (attr->attach_btf_id) {
2531 		/* fall back to vmlinux BTF, if BTF type ID is specified */
2532 		attach_btf = bpf_get_btf_vmlinux();
2533 		if (IS_ERR(attach_btf))
2534 			return PTR_ERR(attach_btf);
2535 		if (!attach_btf)
2536 			return -EINVAL;
2537 		btf_get(attach_btf);
2538 	}
2539 
2540 	bpf_prog_load_fixup_attach_type(attr);
2541 	if (bpf_prog_load_check_attach(type, attr->expected_attach_type,
2542 				       attach_btf, attr->attach_btf_id,
2543 				       dst_prog)) {
2544 		if (dst_prog)
2545 			bpf_prog_put(dst_prog);
2546 		if (attach_btf)
2547 			btf_put(attach_btf);
2548 		return -EINVAL;
2549 	}
2550 
2551 	/* plain bpf_prog allocation */
2552 	prog = bpf_prog_alloc(bpf_prog_size(attr->insn_cnt), GFP_USER);
2553 	if (!prog) {
2554 		if (dst_prog)
2555 			bpf_prog_put(dst_prog);
2556 		if (attach_btf)
2557 			btf_put(attach_btf);
2558 		return -ENOMEM;
2559 	}
2560 
2561 	prog->expected_attach_type = attr->expected_attach_type;
2562 	prog->aux->attach_btf = attach_btf;
2563 	prog->aux->attach_btf_id = attr->attach_btf_id;
2564 	prog->aux->dst_prog = dst_prog;
2565 	prog->aux->offload_requested = !!attr->prog_ifindex;
2566 	prog->aux->sleepable = attr->prog_flags & BPF_F_SLEEPABLE;
2567 	prog->aux->xdp_has_frags = attr->prog_flags & BPF_F_XDP_HAS_FRAGS;
2568 
2569 	err = security_bpf_prog_alloc(prog->aux);
2570 	if (err)
2571 		goto free_prog;
2572 
2573 	prog->aux->user = get_current_user();
2574 	prog->len = attr->insn_cnt;
2575 
2576 	err = -EFAULT;
2577 	if (copy_from_bpfptr(prog->insns,
2578 			     make_bpfptr(attr->insns, uattr.is_kernel),
2579 			     bpf_prog_insn_size(prog)) != 0)
2580 		goto free_prog_sec;
2581 
2582 	prog->orig_prog = NULL;
2583 	prog->jited = 0;
2584 
2585 	atomic64_set(&prog->aux->refcnt, 1);
2586 	prog->gpl_compatible = is_gpl ? 1 : 0;
2587 
2588 	if (bpf_prog_is_dev_bound(prog->aux)) {
2589 		err = bpf_prog_offload_init(prog, attr);
2590 		if (err)
2591 			goto free_prog_sec;
2592 	}
2593 
2594 	/* find program type: socket_filter vs tracing_filter */
2595 	err = find_prog_type(type, prog);
2596 	if (err < 0)
2597 		goto free_prog_sec;
2598 
2599 	prog->aux->load_time = ktime_get_boottime_ns();
2600 	err = bpf_obj_name_cpy(prog->aux->name, attr->prog_name,
2601 			       sizeof(attr->prog_name));
2602 	if (err < 0)
2603 		goto free_prog_sec;
2604 
2605 	/* run eBPF verifier */
2606 	err = bpf_check(&prog, attr, uattr);
2607 	if (err < 0)
2608 		goto free_used_maps;
2609 
2610 	prog = bpf_prog_select_runtime(prog, &err);
2611 	if (err < 0)
2612 		goto free_used_maps;
2613 
2614 	err = bpf_prog_alloc_id(prog);
2615 	if (err)
2616 		goto free_used_maps;
2617 
2618 	/* Upon success of bpf_prog_alloc_id(), the BPF prog is
2619 	 * effectively publicly exposed. However, retrieving via
2620 	 * bpf_prog_get_fd_by_id() will take another reference,
2621 	 * therefore it cannot be gone underneath us.
2622 	 *
2623 	 * Only for the time /after/ successful bpf_prog_new_fd()
2624 	 * and before returning to userspace, we might just hold
2625 	 * one reference and any parallel close on that fd could
2626 	 * rip everything out. Hence, below notifications must
2627 	 * happen before bpf_prog_new_fd().
2628 	 *
2629 	 * Also, any failure handling from this point onwards must
2630 	 * be using bpf_prog_put() given the program is exposed.
2631 	 */
2632 	bpf_prog_kallsyms_add(prog);
2633 	perf_event_bpf_event(prog, PERF_BPF_EVENT_PROG_LOAD, 0);
2634 	bpf_audit_prog(prog, BPF_AUDIT_LOAD);
2635 
2636 	err = bpf_prog_new_fd(prog);
2637 	if (err < 0)
2638 		bpf_prog_put(prog);
2639 	return err;
2640 
2641 free_used_maps:
2642 	/* In case we have subprogs, we need to wait for a grace
2643 	 * period before we can tear down JIT memory since symbols
2644 	 * are already exposed under kallsyms.
2645 	 */
2646 	__bpf_prog_put_noref(prog, prog->aux->func_cnt);
2647 	return err;
2648 free_prog_sec:
2649 	free_uid(prog->aux->user);
2650 	security_bpf_prog_free(prog->aux);
2651 free_prog:
2652 	if (prog->aux->attach_btf)
2653 		btf_put(prog->aux->attach_btf);
2654 	bpf_prog_free(prog);
2655 	return err;
2656 }
2657 
2658 #define BPF_OBJ_LAST_FIELD file_flags
2659 
2660 static int bpf_obj_pin(const union bpf_attr *attr)
2661 {
2662 	if (CHECK_ATTR(BPF_OBJ) || attr->file_flags != 0)
2663 		return -EINVAL;
2664 
2665 	return bpf_obj_pin_user(attr->bpf_fd, u64_to_user_ptr(attr->pathname));
2666 }
2667 
2668 static int bpf_obj_get(const union bpf_attr *attr)
2669 {
2670 	if (CHECK_ATTR(BPF_OBJ) || attr->bpf_fd != 0 ||
2671 	    attr->file_flags & ~BPF_OBJ_FLAG_MASK)
2672 		return -EINVAL;
2673 
2674 	return bpf_obj_get_user(u64_to_user_ptr(attr->pathname),
2675 				attr->file_flags);
2676 }
2677 
2678 void bpf_link_init(struct bpf_link *link, enum bpf_link_type type,
2679 		   const struct bpf_link_ops *ops, struct bpf_prog *prog)
2680 {
2681 	atomic64_set(&link->refcnt, 1);
2682 	link->type = type;
2683 	link->id = 0;
2684 	link->ops = ops;
2685 	link->prog = prog;
2686 }
2687 
2688 static void bpf_link_free_id(int id)
2689 {
2690 	if (!id)
2691 		return;
2692 
2693 	spin_lock_bh(&link_idr_lock);
2694 	idr_remove(&link_idr, id);
2695 	spin_unlock_bh(&link_idr_lock);
2696 }
2697 
2698 /* Clean up bpf_link and corresponding anon_inode file and FD. After
2699  * anon_inode is created, bpf_link can't be just kfree()'d due to deferred
2700  * anon_inode's release() call. This helper marksbpf_link as
2701  * defunct, releases anon_inode file and puts reserved FD. bpf_prog's refcnt
2702  * is not decremented, it's the responsibility of a calling code that failed
2703  * to complete bpf_link initialization.
2704  */
2705 void bpf_link_cleanup(struct bpf_link_primer *primer)
2706 {
2707 	primer->link->prog = NULL;
2708 	bpf_link_free_id(primer->id);
2709 	fput(primer->file);
2710 	put_unused_fd(primer->fd);
2711 }
2712 
2713 void bpf_link_inc(struct bpf_link *link)
2714 {
2715 	atomic64_inc(&link->refcnt);
2716 }
2717 
2718 /* bpf_link_free is guaranteed to be called from process context */
2719 static void bpf_link_free(struct bpf_link *link)
2720 {
2721 	bpf_link_free_id(link->id);
2722 	if (link->prog) {
2723 		/* detach BPF program, clean up used resources */
2724 		link->ops->release(link);
2725 		bpf_prog_put(link->prog);
2726 	}
2727 	/* free bpf_link and its containing memory */
2728 	link->ops->dealloc(link);
2729 }
2730 
2731 static void bpf_link_put_deferred(struct work_struct *work)
2732 {
2733 	struct bpf_link *link = container_of(work, struct bpf_link, work);
2734 
2735 	bpf_link_free(link);
2736 }
2737 
2738 /* bpf_link_put can be called from atomic context, but ensures that resources
2739  * are freed from process context
2740  */
2741 void bpf_link_put(struct bpf_link *link)
2742 {
2743 	if (!atomic64_dec_and_test(&link->refcnt))
2744 		return;
2745 
2746 	if (in_atomic()) {
2747 		INIT_WORK(&link->work, bpf_link_put_deferred);
2748 		schedule_work(&link->work);
2749 	} else {
2750 		bpf_link_free(link);
2751 	}
2752 }
2753 EXPORT_SYMBOL(bpf_link_put);
2754 
2755 static int bpf_link_release(struct inode *inode, struct file *filp)
2756 {
2757 	struct bpf_link *link = filp->private_data;
2758 
2759 	bpf_link_put(link);
2760 	return 0;
2761 }
2762 
2763 #ifdef CONFIG_PROC_FS
2764 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type)
2765 #define BPF_MAP_TYPE(_id, _ops)
2766 #define BPF_LINK_TYPE(_id, _name) [_id] = #_name,
2767 static const char *bpf_link_type_strs[] = {
2768 	[BPF_LINK_TYPE_UNSPEC] = "<invalid>",
2769 #include <linux/bpf_types.h>
2770 };
2771 #undef BPF_PROG_TYPE
2772 #undef BPF_MAP_TYPE
2773 #undef BPF_LINK_TYPE
2774 
2775 static void bpf_link_show_fdinfo(struct seq_file *m, struct file *filp)
2776 {
2777 	const struct bpf_link *link = filp->private_data;
2778 	const struct bpf_prog *prog = link->prog;
2779 	char prog_tag[sizeof(prog->tag) * 2 + 1] = { };
2780 
2781 	bin2hex(prog_tag, prog->tag, sizeof(prog->tag));
2782 	seq_printf(m,
2783 		   "link_type:\t%s\n"
2784 		   "link_id:\t%u\n"
2785 		   "prog_tag:\t%s\n"
2786 		   "prog_id:\t%u\n",
2787 		   bpf_link_type_strs[link->type],
2788 		   link->id,
2789 		   prog_tag,
2790 		   prog->aux->id);
2791 	if (link->ops->show_fdinfo)
2792 		link->ops->show_fdinfo(link, m);
2793 }
2794 #endif
2795 
2796 static const struct file_operations bpf_link_fops = {
2797 #ifdef CONFIG_PROC_FS
2798 	.show_fdinfo	= bpf_link_show_fdinfo,
2799 #endif
2800 	.release	= bpf_link_release,
2801 	.read		= bpf_dummy_read,
2802 	.write		= bpf_dummy_write,
2803 };
2804 
2805 static int bpf_link_alloc_id(struct bpf_link *link)
2806 {
2807 	int id;
2808 
2809 	idr_preload(GFP_KERNEL);
2810 	spin_lock_bh(&link_idr_lock);
2811 	id = idr_alloc_cyclic(&link_idr, link, 1, INT_MAX, GFP_ATOMIC);
2812 	spin_unlock_bh(&link_idr_lock);
2813 	idr_preload_end();
2814 
2815 	return id;
2816 }
2817 
2818 /* Prepare bpf_link to be exposed to user-space by allocating anon_inode file,
2819  * reserving unused FD and allocating ID from link_idr. This is to be paired
2820  * with bpf_link_settle() to install FD and ID and expose bpf_link to
2821  * user-space, if bpf_link is successfully attached. If not, bpf_link and
2822  * pre-allocated resources are to be freed with bpf_cleanup() call. All the
2823  * transient state is passed around in struct bpf_link_primer.
2824  * This is preferred way to create and initialize bpf_link, especially when
2825  * there are complicated and expensive operations in between creating bpf_link
2826  * itself and attaching it to BPF hook. By using bpf_link_prime() and
2827  * bpf_link_settle() kernel code using bpf_link doesn't have to perform
2828  * expensive (and potentially failing) roll back operations in a rare case
2829  * that file, FD, or ID can't be allocated.
2830  */
2831 int bpf_link_prime(struct bpf_link *link, struct bpf_link_primer *primer)
2832 {
2833 	struct file *file;
2834 	int fd, id;
2835 
2836 	fd = get_unused_fd_flags(O_CLOEXEC);
2837 	if (fd < 0)
2838 		return fd;
2839 
2840 
2841 	id = bpf_link_alloc_id(link);
2842 	if (id < 0) {
2843 		put_unused_fd(fd);
2844 		return id;
2845 	}
2846 
2847 	file = anon_inode_getfile("bpf_link", &bpf_link_fops, link, O_CLOEXEC);
2848 	if (IS_ERR(file)) {
2849 		bpf_link_free_id(id);
2850 		put_unused_fd(fd);
2851 		return PTR_ERR(file);
2852 	}
2853 
2854 	primer->link = link;
2855 	primer->file = file;
2856 	primer->fd = fd;
2857 	primer->id = id;
2858 	return 0;
2859 }
2860 
2861 int bpf_link_settle(struct bpf_link_primer *primer)
2862 {
2863 	/* make bpf_link fetchable by ID */
2864 	spin_lock_bh(&link_idr_lock);
2865 	primer->link->id = primer->id;
2866 	spin_unlock_bh(&link_idr_lock);
2867 	/* make bpf_link fetchable by FD */
2868 	fd_install(primer->fd, primer->file);
2869 	/* pass through installed FD */
2870 	return primer->fd;
2871 }
2872 
2873 int bpf_link_new_fd(struct bpf_link *link)
2874 {
2875 	return anon_inode_getfd("bpf-link", &bpf_link_fops, link, O_CLOEXEC);
2876 }
2877 
2878 struct bpf_link *bpf_link_get_from_fd(u32 ufd)
2879 {
2880 	struct fd f = fdget(ufd);
2881 	struct bpf_link *link;
2882 
2883 	if (!f.file)
2884 		return ERR_PTR(-EBADF);
2885 	if (f.file->f_op != &bpf_link_fops) {
2886 		fdput(f);
2887 		return ERR_PTR(-EINVAL);
2888 	}
2889 
2890 	link = f.file->private_data;
2891 	bpf_link_inc(link);
2892 	fdput(f);
2893 
2894 	return link;
2895 }
2896 EXPORT_SYMBOL(bpf_link_get_from_fd);
2897 
2898 static void bpf_tracing_link_release(struct bpf_link *link)
2899 {
2900 	struct bpf_tracing_link *tr_link =
2901 		container_of(link, struct bpf_tracing_link, link.link);
2902 
2903 	WARN_ON_ONCE(bpf_trampoline_unlink_prog(&tr_link->link,
2904 						tr_link->trampoline));
2905 
2906 	bpf_trampoline_put(tr_link->trampoline);
2907 
2908 	/* tgt_prog is NULL if target is a kernel function */
2909 	if (tr_link->tgt_prog)
2910 		bpf_prog_put(tr_link->tgt_prog);
2911 }
2912 
2913 static void bpf_tracing_link_dealloc(struct bpf_link *link)
2914 {
2915 	struct bpf_tracing_link *tr_link =
2916 		container_of(link, struct bpf_tracing_link, link.link);
2917 
2918 	kfree(tr_link);
2919 }
2920 
2921 static void bpf_tracing_link_show_fdinfo(const struct bpf_link *link,
2922 					 struct seq_file *seq)
2923 {
2924 	struct bpf_tracing_link *tr_link =
2925 		container_of(link, struct bpf_tracing_link, link.link);
2926 
2927 	seq_printf(seq,
2928 		   "attach_type:\t%d\n",
2929 		   tr_link->attach_type);
2930 }
2931 
2932 static int bpf_tracing_link_fill_link_info(const struct bpf_link *link,
2933 					   struct bpf_link_info *info)
2934 {
2935 	struct bpf_tracing_link *tr_link =
2936 		container_of(link, struct bpf_tracing_link, link.link);
2937 
2938 	info->tracing.attach_type = tr_link->attach_type;
2939 	bpf_trampoline_unpack_key(tr_link->trampoline->key,
2940 				  &info->tracing.target_obj_id,
2941 				  &info->tracing.target_btf_id);
2942 
2943 	return 0;
2944 }
2945 
2946 static const struct bpf_link_ops bpf_tracing_link_lops = {
2947 	.release = bpf_tracing_link_release,
2948 	.dealloc = bpf_tracing_link_dealloc,
2949 	.show_fdinfo = bpf_tracing_link_show_fdinfo,
2950 	.fill_link_info = bpf_tracing_link_fill_link_info,
2951 };
2952 
2953 static int bpf_tracing_prog_attach(struct bpf_prog *prog,
2954 				   int tgt_prog_fd,
2955 				   u32 btf_id,
2956 				   u64 bpf_cookie)
2957 {
2958 	struct bpf_link_primer link_primer;
2959 	struct bpf_prog *tgt_prog = NULL;
2960 	struct bpf_trampoline *tr = NULL;
2961 	struct bpf_tracing_link *link;
2962 	u64 key = 0;
2963 	int err;
2964 
2965 	switch (prog->type) {
2966 	case BPF_PROG_TYPE_TRACING:
2967 		if (prog->expected_attach_type != BPF_TRACE_FENTRY &&
2968 		    prog->expected_attach_type != BPF_TRACE_FEXIT &&
2969 		    prog->expected_attach_type != BPF_MODIFY_RETURN) {
2970 			err = -EINVAL;
2971 			goto out_put_prog;
2972 		}
2973 		break;
2974 	case BPF_PROG_TYPE_EXT:
2975 		if (prog->expected_attach_type != 0) {
2976 			err = -EINVAL;
2977 			goto out_put_prog;
2978 		}
2979 		break;
2980 	case BPF_PROG_TYPE_LSM:
2981 		if (prog->expected_attach_type != BPF_LSM_MAC) {
2982 			err = -EINVAL;
2983 			goto out_put_prog;
2984 		}
2985 		break;
2986 	default:
2987 		err = -EINVAL;
2988 		goto out_put_prog;
2989 	}
2990 
2991 	if (!!tgt_prog_fd != !!btf_id) {
2992 		err = -EINVAL;
2993 		goto out_put_prog;
2994 	}
2995 
2996 	if (tgt_prog_fd) {
2997 		/* For now we only allow new targets for BPF_PROG_TYPE_EXT */
2998 		if (prog->type != BPF_PROG_TYPE_EXT) {
2999 			err = -EINVAL;
3000 			goto out_put_prog;
3001 		}
3002 
3003 		tgt_prog = bpf_prog_get(tgt_prog_fd);
3004 		if (IS_ERR(tgt_prog)) {
3005 			err = PTR_ERR(tgt_prog);
3006 			tgt_prog = NULL;
3007 			goto out_put_prog;
3008 		}
3009 
3010 		key = bpf_trampoline_compute_key(tgt_prog, NULL, btf_id);
3011 	}
3012 
3013 	link = kzalloc(sizeof(*link), GFP_USER);
3014 	if (!link) {
3015 		err = -ENOMEM;
3016 		goto out_put_prog;
3017 	}
3018 	bpf_link_init(&link->link.link, BPF_LINK_TYPE_TRACING,
3019 		      &bpf_tracing_link_lops, prog);
3020 	link->attach_type = prog->expected_attach_type;
3021 	link->link.cookie = bpf_cookie;
3022 
3023 	mutex_lock(&prog->aux->dst_mutex);
3024 
3025 	/* There are a few possible cases here:
3026 	 *
3027 	 * - if prog->aux->dst_trampoline is set, the program was just loaded
3028 	 *   and not yet attached to anything, so we can use the values stored
3029 	 *   in prog->aux
3030 	 *
3031 	 * - if prog->aux->dst_trampoline is NULL, the program has already been
3032          *   attached to a target and its initial target was cleared (below)
3033 	 *
3034 	 * - if tgt_prog != NULL, the caller specified tgt_prog_fd +
3035 	 *   target_btf_id using the link_create API.
3036 	 *
3037 	 * - if tgt_prog == NULL when this function was called using the old
3038 	 *   raw_tracepoint_open API, and we need a target from prog->aux
3039 	 *
3040 	 * - if prog->aux->dst_trampoline and tgt_prog is NULL, the program
3041 	 *   was detached and is going for re-attachment.
3042 	 */
3043 	if (!prog->aux->dst_trampoline && !tgt_prog) {
3044 		/*
3045 		 * Allow re-attach for TRACING and LSM programs. If it's
3046 		 * currently linked, bpf_trampoline_link_prog will fail.
3047 		 * EXT programs need to specify tgt_prog_fd, so they
3048 		 * re-attach in separate code path.
3049 		 */
3050 		if (prog->type != BPF_PROG_TYPE_TRACING &&
3051 		    prog->type != BPF_PROG_TYPE_LSM) {
3052 			err = -EINVAL;
3053 			goto out_unlock;
3054 		}
3055 		btf_id = prog->aux->attach_btf_id;
3056 		key = bpf_trampoline_compute_key(NULL, prog->aux->attach_btf, btf_id);
3057 	}
3058 
3059 	if (!prog->aux->dst_trampoline ||
3060 	    (key && key != prog->aux->dst_trampoline->key)) {
3061 		/* If there is no saved target, or the specified target is
3062 		 * different from the destination specified at load time, we
3063 		 * need a new trampoline and a check for compatibility
3064 		 */
3065 		struct bpf_attach_target_info tgt_info = {};
3066 
3067 		err = bpf_check_attach_target(NULL, prog, tgt_prog, btf_id,
3068 					      &tgt_info);
3069 		if (err)
3070 			goto out_unlock;
3071 
3072 		tr = bpf_trampoline_get(key, &tgt_info);
3073 		if (!tr) {
3074 			err = -ENOMEM;
3075 			goto out_unlock;
3076 		}
3077 	} else {
3078 		/* The caller didn't specify a target, or the target was the
3079 		 * same as the destination supplied during program load. This
3080 		 * means we can reuse the trampoline and reference from program
3081 		 * load time, and there is no need to allocate a new one. This
3082 		 * can only happen once for any program, as the saved values in
3083 		 * prog->aux are cleared below.
3084 		 */
3085 		tr = prog->aux->dst_trampoline;
3086 		tgt_prog = prog->aux->dst_prog;
3087 	}
3088 
3089 	err = bpf_link_prime(&link->link.link, &link_primer);
3090 	if (err)
3091 		goto out_unlock;
3092 
3093 	err = bpf_trampoline_link_prog(&link->link, tr);
3094 	if (err) {
3095 		bpf_link_cleanup(&link_primer);
3096 		link = NULL;
3097 		goto out_unlock;
3098 	}
3099 
3100 	link->tgt_prog = tgt_prog;
3101 	link->trampoline = tr;
3102 
3103 	/* Always clear the trampoline and target prog from prog->aux to make
3104 	 * sure the original attach destination is not kept alive after a
3105 	 * program is (re-)attached to another target.
3106 	 */
3107 	if (prog->aux->dst_prog &&
3108 	    (tgt_prog_fd || tr != prog->aux->dst_trampoline))
3109 		/* got extra prog ref from syscall, or attaching to different prog */
3110 		bpf_prog_put(prog->aux->dst_prog);
3111 	if (prog->aux->dst_trampoline && tr != prog->aux->dst_trampoline)
3112 		/* we allocated a new trampoline, so free the old one */
3113 		bpf_trampoline_put(prog->aux->dst_trampoline);
3114 
3115 	prog->aux->dst_prog = NULL;
3116 	prog->aux->dst_trampoline = NULL;
3117 	mutex_unlock(&prog->aux->dst_mutex);
3118 
3119 	return bpf_link_settle(&link_primer);
3120 out_unlock:
3121 	if (tr && tr != prog->aux->dst_trampoline)
3122 		bpf_trampoline_put(tr);
3123 	mutex_unlock(&prog->aux->dst_mutex);
3124 	kfree(link);
3125 out_put_prog:
3126 	if (tgt_prog_fd && tgt_prog)
3127 		bpf_prog_put(tgt_prog);
3128 	return err;
3129 }
3130 
3131 struct bpf_raw_tp_link {
3132 	struct bpf_link link;
3133 	struct bpf_raw_event_map *btp;
3134 };
3135 
3136 static void bpf_raw_tp_link_release(struct bpf_link *link)
3137 {
3138 	struct bpf_raw_tp_link *raw_tp =
3139 		container_of(link, struct bpf_raw_tp_link, link);
3140 
3141 	bpf_probe_unregister(raw_tp->btp, raw_tp->link.prog);
3142 	bpf_put_raw_tracepoint(raw_tp->btp);
3143 }
3144 
3145 static void bpf_raw_tp_link_dealloc(struct bpf_link *link)
3146 {
3147 	struct bpf_raw_tp_link *raw_tp =
3148 		container_of(link, struct bpf_raw_tp_link, link);
3149 
3150 	kfree(raw_tp);
3151 }
3152 
3153 static void bpf_raw_tp_link_show_fdinfo(const struct bpf_link *link,
3154 					struct seq_file *seq)
3155 {
3156 	struct bpf_raw_tp_link *raw_tp_link =
3157 		container_of(link, struct bpf_raw_tp_link, link);
3158 
3159 	seq_printf(seq,
3160 		   "tp_name:\t%s\n",
3161 		   raw_tp_link->btp->tp->name);
3162 }
3163 
3164 static int bpf_raw_tp_link_fill_link_info(const struct bpf_link *link,
3165 					  struct bpf_link_info *info)
3166 {
3167 	struct bpf_raw_tp_link *raw_tp_link =
3168 		container_of(link, struct bpf_raw_tp_link, link);
3169 	char __user *ubuf = u64_to_user_ptr(info->raw_tracepoint.tp_name);
3170 	const char *tp_name = raw_tp_link->btp->tp->name;
3171 	u32 ulen = info->raw_tracepoint.tp_name_len;
3172 	size_t tp_len = strlen(tp_name);
3173 
3174 	if (!ulen ^ !ubuf)
3175 		return -EINVAL;
3176 
3177 	info->raw_tracepoint.tp_name_len = tp_len + 1;
3178 
3179 	if (!ubuf)
3180 		return 0;
3181 
3182 	if (ulen >= tp_len + 1) {
3183 		if (copy_to_user(ubuf, tp_name, tp_len + 1))
3184 			return -EFAULT;
3185 	} else {
3186 		char zero = '\0';
3187 
3188 		if (copy_to_user(ubuf, tp_name, ulen - 1))
3189 			return -EFAULT;
3190 		if (put_user(zero, ubuf + ulen - 1))
3191 			return -EFAULT;
3192 		return -ENOSPC;
3193 	}
3194 
3195 	return 0;
3196 }
3197 
3198 static const struct bpf_link_ops bpf_raw_tp_link_lops = {
3199 	.release = bpf_raw_tp_link_release,
3200 	.dealloc = bpf_raw_tp_link_dealloc,
3201 	.show_fdinfo = bpf_raw_tp_link_show_fdinfo,
3202 	.fill_link_info = bpf_raw_tp_link_fill_link_info,
3203 };
3204 
3205 #ifdef CONFIG_PERF_EVENTS
3206 struct bpf_perf_link {
3207 	struct bpf_link link;
3208 	struct file *perf_file;
3209 };
3210 
3211 static void bpf_perf_link_release(struct bpf_link *link)
3212 {
3213 	struct bpf_perf_link *perf_link = container_of(link, struct bpf_perf_link, link);
3214 	struct perf_event *event = perf_link->perf_file->private_data;
3215 
3216 	perf_event_free_bpf_prog(event);
3217 	fput(perf_link->perf_file);
3218 }
3219 
3220 static void bpf_perf_link_dealloc(struct bpf_link *link)
3221 {
3222 	struct bpf_perf_link *perf_link = container_of(link, struct bpf_perf_link, link);
3223 
3224 	kfree(perf_link);
3225 }
3226 
3227 static const struct bpf_link_ops bpf_perf_link_lops = {
3228 	.release = bpf_perf_link_release,
3229 	.dealloc = bpf_perf_link_dealloc,
3230 };
3231 
3232 static int bpf_perf_link_attach(const union bpf_attr *attr, struct bpf_prog *prog)
3233 {
3234 	struct bpf_link_primer link_primer;
3235 	struct bpf_perf_link *link;
3236 	struct perf_event *event;
3237 	struct file *perf_file;
3238 	int err;
3239 
3240 	if (attr->link_create.flags)
3241 		return -EINVAL;
3242 
3243 	perf_file = perf_event_get(attr->link_create.target_fd);
3244 	if (IS_ERR(perf_file))
3245 		return PTR_ERR(perf_file);
3246 
3247 	link = kzalloc(sizeof(*link), GFP_USER);
3248 	if (!link) {
3249 		err = -ENOMEM;
3250 		goto out_put_file;
3251 	}
3252 	bpf_link_init(&link->link, BPF_LINK_TYPE_PERF_EVENT, &bpf_perf_link_lops, prog);
3253 	link->perf_file = perf_file;
3254 
3255 	err = bpf_link_prime(&link->link, &link_primer);
3256 	if (err) {
3257 		kfree(link);
3258 		goto out_put_file;
3259 	}
3260 
3261 	event = perf_file->private_data;
3262 	err = perf_event_set_bpf_prog(event, prog, attr->link_create.perf_event.bpf_cookie);
3263 	if (err) {
3264 		bpf_link_cleanup(&link_primer);
3265 		goto out_put_file;
3266 	}
3267 	/* perf_event_set_bpf_prog() doesn't take its own refcnt on prog */
3268 	bpf_prog_inc(prog);
3269 
3270 	return bpf_link_settle(&link_primer);
3271 
3272 out_put_file:
3273 	fput(perf_file);
3274 	return err;
3275 }
3276 #else
3277 static int bpf_perf_link_attach(const union bpf_attr *attr, struct bpf_prog *prog)
3278 {
3279 	return -EOPNOTSUPP;
3280 }
3281 #endif /* CONFIG_PERF_EVENTS */
3282 
3283 static int bpf_raw_tp_link_attach(struct bpf_prog *prog,
3284 				  const char __user *user_tp_name)
3285 {
3286 	struct bpf_link_primer link_primer;
3287 	struct bpf_raw_tp_link *link;
3288 	struct bpf_raw_event_map *btp;
3289 	const char *tp_name;
3290 	char buf[128];
3291 	int err;
3292 
3293 	switch (prog->type) {
3294 	case BPF_PROG_TYPE_TRACING:
3295 	case BPF_PROG_TYPE_EXT:
3296 	case BPF_PROG_TYPE_LSM:
3297 		if (user_tp_name)
3298 			/* The attach point for this category of programs
3299 			 * should be specified via btf_id during program load.
3300 			 */
3301 			return -EINVAL;
3302 		if (prog->type == BPF_PROG_TYPE_TRACING &&
3303 		    prog->expected_attach_type == BPF_TRACE_RAW_TP) {
3304 			tp_name = prog->aux->attach_func_name;
3305 			break;
3306 		}
3307 		return bpf_tracing_prog_attach(prog, 0, 0, 0);
3308 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
3309 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
3310 		if (strncpy_from_user(buf, user_tp_name, sizeof(buf) - 1) < 0)
3311 			return -EFAULT;
3312 		buf[sizeof(buf) - 1] = 0;
3313 		tp_name = buf;
3314 		break;
3315 	default:
3316 		return -EINVAL;
3317 	}
3318 
3319 	btp = bpf_get_raw_tracepoint(tp_name);
3320 	if (!btp)
3321 		return -ENOENT;
3322 
3323 	link = kzalloc(sizeof(*link), GFP_USER);
3324 	if (!link) {
3325 		err = -ENOMEM;
3326 		goto out_put_btp;
3327 	}
3328 	bpf_link_init(&link->link, BPF_LINK_TYPE_RAW_TRACEPOINT,
3329 		      &bpf_raw_tp_link_lops, prog);
3330 	link->btp = btp;
3331 
3332 	err = bpf_link_prime(&link->link, &link_primer);
3333 	if (err) {
3334 		kfree(link);
3335 		goto out_put_btp;
3336 	}
3337 
3338 	err = bpf_probe_register(link->btp, prog);
3339 	if (err) {
3340 		bpf_link_cleanup(&link_primer);
3341 		goto out_put_btp;
3342 	}
3343 
3344 	return bpf_link_settle(&link_primer);
3345 
3346 out_put_btp:
3347 	bpf_put_raw_tracepoint(btp);
3348 	return err;
3349 }
3350 
3351 #define BPF_RAW_TRACEPOINT_OPEN_LAST_FIELD raw_tracepoint.prog_fd
3352 
3353 static int bpf_raw_tracepoint_open(const union bpf_attr *attr)
3354 {
3355 	struct bpf_prog *prog;
3356 	int fd;
3357 
3358 	if (CHECK_ATTR(BPF_RAW_TRACEPOINT_OPEN))
3359 		return -EINVAL;
3360 
3361 	prog = bpf_prog_get(attr->raw_tracepoint.prog_fd);
3362 	if (IS_ERR(prog))
3363 		return PTR_ERR(prog);
3364 
3365 	fd = bpf_raw_tp_link_attach(prog, u64_to_user_ptr(attr->raw_tracepoint.name));
3366 	if (fd < 0)
3367 		bpf_prog_put(prog);
3368 	return fd;
3369 }
3370 
3371 static int bpf_prog_attach_check_attach_type(const struct bpf_prog *prog,
3372 					     enum bpf_attach_type attach_type)
3373 {
3374 	switch (prog->type) {
3375 	case BPF_PROG_TYPE_CGROUP_SOCK:
3376 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
3377 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3378 	case BPF_PROG_TYPE_SK_LOOKUP:
3379 		return attach_type == prog->expected_attach_type ? 0 : -EINVAL;
3380 	case BPF_PROG_TYPE_CGROUP_SKB:
3381 		if (!capable(CAP_NET_ADMIN))
3382 			/* cg-skb progs can be loaded by unpriv user.
3383 			 * check permissions at attach time.
3384 			 */
3385 			return -EPERM;
3386 		return prog->enforce_expected_attach_type &&
3387 			prog->expected_attach_type != attach_type ?
3388 			-EINVAL : 0;
3389 	default:
3390 		return 0;
3391 	}
3392 }
3393 
3394 static enum bpf_prog_type
3395 attach_type_to_prog_type(enum bpf_attach_type attach_type)
3396 {
3397 	switch (attach_type) {
3398 	case BPF_CGROUP_INET_INGRESS:
3399 	case BPF_CGROUP_INET_EGRESS:
3400 		return BPF_PROG_TYPE_CGROUP_SKB;
3401 	case BPF_CGROUP_INET_SOCK_CREATE:
3402 	case BPF_CGROUP_INET_SOCK_RELEASE:
3403 	case BPF_CGROUP_INET4_POST_BIND:
3404 	case BPF_CGROUP_INET6_POST_BIND:
3405 		return BPF_PROG_TYPE_CGROUP_SOCK;
3406 	case BPF_CGROUP_INET4_BIND:
3407 	case BPF_CGROUP_INET6_BIND:
3408 	case BPF_CGROUP_INET4_CONNECT:
3409 	case BPF_CGROUP_INET6_CONNECT:
3410 	case BPF_CGROUP_INET4_GETPEERNAME:
3411 	case BPF_CGROUP_INET6_GETPEERNAME:
3412 	case BPF_CGROUP_INET4_GETSOCKNAME:
3413 	case BPF_CGROUP_INET6_GETSOCKNAME:
3414 	case BPF_CGROUP_UDP4_SENDMSG:
3415 	case BPF_CGROUP_UDP6_SENDMSG:
3416 	case BPF_CGROUP_UDP4_RECVMSG:
3417 	case BPF_CGROUP_UDP6_RECVMSG:
3418 		return BPF_PROG_TYPE_CGROUP_SOCK_ADDR;
3419 	case BPF_CGROUP_SOCK_OPS:
3420 		return BPF_PROG_TYPE_SOCK_OPS;
3421 	case BPF_CGROUP_DEVICE:
3422 		return BPF_PROG_TYPE_CGROUP_DEVICE;
3423 	case BPF_SK_MSG_VERDICT:
3424 		return BPF_PROG_TYPE_SK_MSG;
3425 	case BPF_SK_SKB_STREAM_PARSER:
3426 	case BPF_SK_SKB_STREAM_VERDICT:
3427 	case BPF_SK_SKB_VERDICT:
3428 		return BPF_PROG_TYPE_SK_SKB;
3429 	case BPF_LIRC_MODE2:
3430 		return BPF_PROG_TYPE_LIRC_MODE2;
3431 	case BPF_FLOW_DISSECTOR:
3432 		return BPF_PROG_TYPE_FLOW_DISSECTOR;
3433 	case BPF_CGROUP_SYSCTL:
3434 		return BPF_PROG_TYPE_CGROUP_SYSCTL;
3435 	case BPF_CGROUP_GETSOCKOPT:
3436 	case BPF_CGROUP_SETSOCKOPT:
3437 		return BPF_PROG_TYPE_CGROUP_SOCKOPT;
3438 	case BPF_TRACE_ITER:
3439 	case BPF_TRACE_RAW_TP:
3440 	case BPF_TRACE_FENTRY:
3441 	case BPF_TRACE_FEXIT:
3442 	case BPF_MODIFY_RETURN:
3443 		return BPF_PROG_TYPE_TRACING;
3444 	case BPF_LSM_MAC:
3445 		return BPF_PROG_TYPE_LSM;
3446 	case BPF_SK_LOOKUP:
3447 		return BPF_PROG_TYPE_SK_LOOKUP;
3448 	case BPF_XDP:
3449 		return BPF_PROG_TYPE_XDP;
3450 	case BPF_LSM_CGROUP:
3451 		return BPF_PROG_TYPE_LSM;
3452 	default:
3453 		return BPF_PROG_TYPE_UNSPEC;
3454 	}
3455 }
3456 
3457 #define BPF_PROG_ATTACH_LAST_FIELD replace_bpf_fd
3458 
3459 #define BPF_F_ATTACH_MASK \
3460 	(BPF_F_ALLOW_OVERRIDE | BPF_F_ALLOW_MULTI | BPF_F_REPLACE)
3461 
3462 static int bpf_prog_attach(const union bpf_attr *attr)
3463 {
3464 	enum bpf_prog_type ptype;
3465 	struct bpf_prog *prog;
3466 	int ret;
3467 
3468 	if (CHECK_ATTR(BPF_PROG_ATTACH))
3469 		return -EINVAL;
3470 
3471 	if (attr->attach_flags & ~BPF_F_ATTACH_MASK)
3472 		return -EINVAL;
3473 
3474 	ptype = attach_type_to_prog_type(attr->attach_type);
3475 	if (ptype == BPF_PROG_TYPE_UNSPEC)
3476 		return -EINVAL;
3477 
3478 	prog = bpf_prog_get_type(attr->attach_bpf_fd, ptype);
3479 	if (IS_ERR(prog))
3480 		return PTR_ERR(prog);
3481 
3482 	if (bpf_prog_attach_check_attach_type(prog, attr->attach_type)) {
3483 		bpf_prog_put(prog);
3484 		return -EINVAL;
3485 	}
3486 
3487 	switch (ptype) {
3488 	case BPF_PROG_TYPE_SK_SKB:
3489 	case BPF_PROG_TYPE_SK_MSG:
3490 		ret = sock_map_get_from_fd(attr, prog);
3491 		break;
3492 	case BPF_PROG_TYPE_LIRC_MODE2:
3493 		ret = lirc_prog_attach(attr, prog);
3494 		break;
3495 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
3496 		ret = netns_bpf_prog_attach(attr, prog);
3497 		break;
3498 	case BPF_PROG_TYPE_CGROUP_DEVICE:
3499 	case BPF_PROG_TYPE_CGROUP_SKB:
3500 	case BPF_PROG_TYPE_CGROUP_SOCK:
3501 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
3502 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3503 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
3504 	case BPF_PROG_TYPE_SOCK_OPS:
3505 	case BPF_PROG_TYPE_LSM:
3506 		if (ptype == BPF_PROG_TYPE_LSM &&
3507 		    prog->expected_attach_type != BPF_LSM_CGROUP)
3508 			return -EINVAL;
3509 
3510 		ret = cgroup_bpf_prog_attach(attr, ptype, prog);
3511 		break;
3512 	default:
3513 		ret = -EINVAL;
3514 	}
3515 
3516 	if (ret)
3517 		bpf_prog_put(prog);
3518 	return ret;
3519 }
3520 
3521 #define BPF_PROG_DETACH_LAST_FIELD attach_type
3522 
3523 static int bpf_prog_detach(const union bpf_attr *attr)
3524 {
3525 	enum bpf_prog_type ptype;
3526 
3527 	if (CHECK_ATTR(BPF_PROG_DETACH))
3528 		return -EINVAL;
3529 
3530 	ptype = attach_type_to_prog_type(attr->attach_type);
3531 
3532 	switch (ptype) {
3533 	case BPF_PROG_TYPE_SK_MSG:
3534 	case BPF_PROG_TYPE_SK_SKB:
3535 		return sock_map_prog_detach(attr, ptype);
3536 	case BPF_PROG_TYPE_LIRC_MODE2:
3537 		return lirc_prog_detach(attr);
3538 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
3539 		return netns_bpf_prog_detach(attr, ptype);
3540 	case BPF_PROG_TYPE_CGROUP_DEVICE:
3541 	case BPF_PROG_TYPE_CGROUP_SKB:
3542 	case BPF_PROG_TYPE_CGROUP_SOCK:
3543 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
3544 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3545 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
3546 	case BPF_PROG_TYPE_SOCK_OPS:
3547 	case BPF_PROG_TYPE_LSM:
3548 		return cgroup_bpf_prog_detach(attr, ptype);
3549 	default:
3550 		return -EINVAL;
3551 	}
3552 }
3553 
3554 #define BPF_PROG_QUERY_LAST_FIELD query.prog_attach_flags
3555 
3556 static int bpf_prog_query(const union bpf_attr *attr,
3557 			  union bpf_attr __user *uattr)
3558 {
3559 	if (!capable(CAP_NET_ADMIN))
3560 		return -EPERM;
3561 	if (CHECK_ATTR(BPF_PROG_QUERY))
3562 		return -EINVAL;
3563 	if (attr->query.query_flags & ~BPF_F_QUERY_EFFECTIVE)
3564 		return -EINVAL;
3565 
3566 	switch (attr->query.attach_type) {
3567 	case BPF_CGROUP_INET_INGRESS:
3568 	case BPF_CGROUP_INET_EGRESS:
3569 	case BPF_CGROUP_INET_SOCK_CREATE:
3570 	case BPF_CGROUP_INET_SOCK_RELEASE:
3571 	case BPF_CGROUP_INET4_BIND:
3572 	case BPF_CGROUP_INET6_BIND:
3573 	case BPF_CGROUP_INET4_POST_BIND:
3574 	case BPF_CGROUP_INET6_POST_BIND:
3575 	case BPF_CGROUP_INET4_CONNECT:
3576 	case BPF_CGROUP_INET6_CONNECT:
3577 	case BPF_CGROUP_INET4_GETPEERNAME:
3578 	case BPF_CGROUP_INET6_GETPEERNAME:
3579 	case BPF_CGROUP_INET4_GETSOCKNAME:
3580 	case BPF_CGROUP_INET6_GETSOCKNAME:
3581 	case BPF_CGROUP_UDP4_SENDMSG:
3582 	case BPF_CGROUP_UDP6_SENDMSG:
3583 	case BPF_CGROUP_UDP4_RECVMSG:
3584 	case BPF_CGROUP_UDP6_RECVMSG:
3585 	case BPF_CGROUP_SOCK_OPS:
3586 	case BPF_CGROUP_DEVICE:
3587 	case BPF_CGROUP_SYSCTL:
3588 	case BPF_CGROUP_GETSOCKOPT:
3589 	case BPF_CGROUP_SETSOCKOPT:
3590 	case BPF_LSM_CGROUP:
3591 		return cgroup_bpf_prog_query(attr, uattr);
3592 	case BPF_LIRC_MODE2:
3593 		return lirc_prog_query(attr, uattr);
3594 	case BPF_FLOW_DISSECTOR:
3595 	case BPF_SK_LOOKUP:
3596 		return netns_bpf_prog_query(attr, uattr);
3597 	case BPF_SK_SKB_STREAM_PARSER:
3598 	case BPF_SK_SKB_STREAM_VERDICT:
3599 	case BPF_SK_MSG_VERDICT:
3600 	case BPF_SK_SKB_VERDICT:
3601 		return sock_map_bpf_prog_query(attr, uattr);
3602 	default:
3603 		return -EINVAL;
3604 	}
3605 }
3606 
3607 #define BPF_PROG_TEST_RUN_LAST_FIELD test.batch_size
3608 
3609 static int bpf_prog_test_run(const union bpf_attr *attr,
3610 			     union bpf_attr __user *uattr)
3611 {
3612 	struct bpf_prog *prog;
3613 	int ret = -ENOTSUPP;
3614 
3615 	if (CHECK_ATTR(BPF_PROG_TEST_RUN))
3616 		return -EINVAL;
3617 
3618 	if ((attr->test.ctx_size_in && !attr->test.ctx_in) ||
3619 	    (!attr->test.ctx_size_in && attr->test.ctx_in))
3620 		return -EINVAL;
3621 
3622 	if ((attr->test.ctx_size_out && !attr->test.ctx_out) ||
3623 	    (!attr->test.ctx_size_out && attr->test.ctx_out))
3624 		return -EINVAL;
3625 
3626 	prog = bpf_prog_get(attr->test.prog_fd);
3627 	if (IS_ERR(prog))
3628 		return PTR_ERR(prog);
3629 
3630 	if (prog->aux->ops->test_run)
3631 		ret = prog->aux->ops->test_run(prog, attr, uattr);
3632 
3633 	bpf_prog_put(prog);
3634 	return ret;
3635 }
3636 
3637 #define BPF_OBJ_GET_NEXT_ID_LAST_FIELD next_id
3638 
3639 static int bpf_obj_get_next_id(const union bpf_attr *attr,
3640 			       union bpf_attr __user *uattr,
3641 			       struct idr *idr,
3642 			       spinlock_t *lock)
3643 {
3644 	u32 next_id = attr->start_id;
3645 	int err = 0;
3646 
3647 	if (CHECK_ATTR(BPF_OBJ_GET_NEXT_ID) || next_id >= INT_MAX)
3648 		return -EINVAL;
3649 
3650 	if (!capable(CAP_SYS_ADMIN))
3651 		return -EPERM;
3652 
3653 	next_id++;
3654 	spin_lock_bh(lock);
3655 	if (!idr_get_next(idr, &next_id))
3656 		err = -ENOENT;
3657 	spin_unlock_bh(lock);
3658 
3659 	if (!err)
3660 		err = put_user(next_id, &uattr->next_id);
3661 
3662 	return err;
3663 }
3664 
3665 struct bpf_map *bpf_map_get_curr_or_next(u32 *id)
3666 {
3667 	struct bpf_map *map;
3668 
3669 	spin_lock_bh(&map_idr_lock);
3670 again:
3671 	map = idr_get_next(&map_idr, id);
3672 	if (map) {
3673 		map = __bpf_map_inc_not_zero(map, false);
3674 		if (IS_ERR(map)) {
3675 			(*id)++;
3676 			goto again;
3677 		}
3678 	}
3679 	spin_unlock_bh(&map_idr_lock);
3680 
3681 	return map;
3682 }
3683 
3684 struct bpf_prog *bpf_prog_get_curr_or_next(u32 *id)
3685 {
3686 	struct bpf_prog *prog;
3687 
3688 	spin_lock_bh(&prog_idr_lock);
3689 again:
3690 	prog = idr_get_next(&prog_idr, id);
3691 	if (prog) {
3692 		prog = bpf_prog_inc_not_zero(prog);
3693 		if (IS_ERR(prog)) {
3694 			(*id)++;
3695 			goto again;
3696 		}
3697 	}
3698 	spin_unlock_bh(&prog_idr_lock);
3699 
3700 	return prog;
3701 }
3702 
3703 #define BPF_PROG_GET_FD_BY_ID_LAST_FIELD prog_id
3704 
3705 struct bpf_prog *bpf_prog_by_id(u32 id)
3706 {
3707 	struct bpf_prog *prog;
3708 
3709 	if (!id)
3710 		return ERR_PTR(-ENOENT);
3711 
3712 	spin_lock_bh(&prog_idr_lock);
3713 	prog = idr_find(&prog_idr, id);
3714 	if (prog)
3715 		prog = bpf_prog_inc_not_zero(prog);
3716 	else
3717 		prog = ERR_PTR(-ENOENT);
3718 	spin_unlock_bh(&prog_idr_lock);
3719 	return prog;
3720 }
3721 
3722 static int bpf_prog_get_fd_by_id(const union bpf_attr *attr)
3723 {
3724 	struct bpf_prog *prog;
3725 	u32 id = attr->prog_id;
3726 	int fd;
3727 
3728 	if (CHECK_ATTR(BPF_PROG_GET_FD_BY_ID))
3729 		return -EINVAL;
3730 
3731 	if (!capable(CAP_SYS_ADMIN))
3732 		return -EPERM;
3733 
3734 	prog = bpf_prog_by_id(id);
3735 	if (IS_ERR(prog))
3736 		return PTR_ERR(prog);
3737 
3738 	fd = bpf_prog_new_fd(prog);
3739 	if (fd < 0)
3740 		bpf_prog_put(prog);
3741 
3742 	return fd;
3743 }
3744 
3745 #define BPF_MAP_GET_FD_BY_ID_LAST_FIELD open_flags
3746 
3747 static int bpf_map_get_fd_by_id(const union bpf_attr *attr)
3748 {
3749 	struct bpf_map *map;
3750 	u32 id = attr->map_id;
3751 	int f_flags;
3752 	int fd;
3753 
3754 	if (CHECK_ATTR(BPF_MAP_GET_FD_BY_ID) ||
3755 	    attr->open_flags & ~BPF_OBJ_FLAG_MASK)
3756 		return -EINVAL;
3757 
3758 	if (!capable(CAP_SYS_ADMIN))
3759 		return -EPERM;
3760 
3761 	f_flags = bpf_get_file_flag(attr->open_flags);
3762 	if (f_flags < 0)
3763 		return f_flags;
3764 
3765 	spin_lock_bh(&map_idr_lock);
3766 	map = idr_find(&map_idr, id);
3767 	if (map)
3768 		map = __bpf_map_inc_not_zero(map, true);
3769 	else
3770 		map = ERR_PTR(-ENOENT);
3771 	spin_unlock_bh(&map_idr_lock);
3772 
3773 	if (IS_ERR(map))
3774 		return PTR_ERR(map);
3775 
3776 	fd = bpf_map_new_fd(map, f_flags);
3777 	if (fd < 0)
3778 		bpf_map_put_with_uref(map);
3779 
3780 	return fd;
3781 }
3782 
3783 static const struct bpf_map *bpf_map_from_imm(const struct bpf_prog *prog,
3784 					      unsigned long addr, u32 *off,
3785 					      u32 *type)
3786 {
3787 	const struct bpf_map *map;
3788 	int i;
3789 
3790 	mutex_lock(&prog->aux->used_maps_mutex);
3791 	for (i = 0, *off = 0; i < prog->aux->used_map_cnt; i++) {
3792 		map = prog->aux->used_maps[i];
3793 		if (map == (void *)addr) {
3794 			*type = BPF_PSEUDO_MAP_FD;
3795 			goto out;
3796 		}
3797 		if (!map->ops->map_direct_value_meta)
3798 			continue;
3799 		if (!map->ops->map_direct_value_meta(map, addr, off)) {
3800 			*type = BPF_PSEUDO_MAP_VALUE;
3801 			goto out;
3802 		}
3803 	}
3804 	map = NULL;
3805 
3806 out:
3807 	mutex_unlock(&prog->aux->used_maps_mutex);
3808 	return map;
3809 }
3810 
3811 static struct bpf_insn *bpf_insn_prepare_dump(const struct bpf_prog *prog,
3812 					      const struct cred *f_cred)
3813 {
3814 	const struct bpf_map *map;
3815 	struct bpf_insn *insns;
3816 	u32 off, type;
3817 	u64 imm;
3818 	u8 code;
3819 	int i;
3820 
3821 	insns = kmemdup(prog->insnsi, bpf_prog_insn_size(prog),
3822 			GFP_USER);
3823 	if (!insns)
3824 		return insns;
3825 
3826 	for (i = 0; i < prog->len; i++) {
3827 		code = insns[i].code;
3828 
3829 		if (code == (BPF_JMP | BPF_TAIL_CALL)) {
3830 			insns[i].code = BPF_JMP | BPF_CALL;
3831 			insns[i].imm = BPF_FUNC_tail_call;
3832 			/* fall-through */
3833 		}
3834 		if (code == (BPF_JMP | BPF_CALL) ||
3835 		    code == (BPF_JMP | BPF_CALL_ARGS)) {
3836 			if (code == (BPF_JMP | BPF_CALL_ARGS))
3837 				insns[i].code = BPF_JMP | BPF_CALL;
3838 			if (!bpf_dump_raw_ok(f_cred))
3839 				insns[i].imm = 0;
3840 			continue;
3841 		}
3842 		if (BPF_CLASS(code) == BPF_LDX && BPF_MODE(code) == BPF_PROBE_MEM) {
3843 			insns[i].code = BPF_LDX | BPF_SIZE(code) | BPF_MEM;
3844 			continue;
3845 		}
3846 
3847 		if (code != (BPF_LD | BPF_IMM | BPF_DW))
3848 			continue;
3849 
3850 		imm = ((u64)insns[i + 1].imm << 32) | (u32)insns[i].imm;
3851 		map = bpf_map_from_imm(prog, imm, &off, &type);
3852 		if (map) {
3853 			insns[i].src_reg = type;
3854 			insns[i].imm = map->id;
3855 			insns[i + 1].imm = off;
3856 			continue;
3857 		}
3858 	}
3859 
3860 	return insns;
3861 }
3862 
3863 static int set_info_rec_size(struct bpf_prog_info *info)
3864 {
3865 	/*
3866 	 * Ensure info.*_rec_size is the same as kernel expected size
3867 	 *
3868 	 * or
3869 	 *
3870 	 * Only allow zero *_rec_size if both _rec_size and _cnt are
3871 	 * zero.  In this case, the kernel will set the expected
3872 	 * _rec_size back to the info.
3873 	 */
3874 
3875 	if ((info->nr_func_info || info->func_info_rec_size) &&
3876 	    info->func_info_rec_size != sizeof(struct bpf_func_info))
3877 		return -EINVAL;
3878 
3879 	if ((info->nr_line_info || info->line_info_rec_size) &&
3880 	    info->line_info_rec_size != sizeof(struct bpf_line_info))
3881 		return -EINVAL;
3882 
3883 	if ((info->nr_jited_line_info || info->jited_line_info_rec_size) &&
3884 	    info->jited_line_info_rec_size != sizeof(__u64))
3885 		return -EINVAL;
3886 
3887 	info->func_info_rec_size = sizeof(struct bpf_func_info);
3888 	info->line_info_rec_size = sizeof(struct bpf_line_info);
3889 	info->jited_line_info_rec_size = sizeof(__u64);
3890 
3891 	return 0;
3892 }
3893 
3894 static int bpf_prog_get_info_by_fd(struct file *file,
3895 				   struct bpf_prog *prog,
3896 				   const union bpf_attr *attr,
3897 				   union bpf_attr __user *uattr)
3898 {
3899 	struct bpf_prog_info __user *uinfo = u64_to_user_ptr(attr->info.info);
3900 	struct btf *attach_btf = bpf_prog_get_target_btf(prog);
3901 	struct bpf_prog_info info;
3902 	u32 info_len = attr->info.info_len;
3903 	struct bpf_prog_kstats stats;
3904 	char __user *uinsns;
3905 	u32 ulen;
3906 	int err;
3907 
3908 	err = bpf_check_uarg_tail_zero(USER_BPFPTR(uinfo), sizeof(info), info_len);
3909 	if (err)
3910 		return err;
3911 	info_len = min_t(u32, sizeof(info), info_len);
3912 
3913 	memset(&info, 0, sizeof(info));
3914 	if (copy_from_user(&info, uinfo, info_len))
3915 		return -EFAULT;
3916 
3917 	info.type = prog->type;
3918 	info.id = prog->aux->id;
3919 	info.load_time = prog->aux->load_time;
3920 	info.created_by_uid = from_kuid_munged(current_user_ns(),
3921 					       prog->aux->user->uid);
3922 	info.gpl_compatible = prog->gpl_compatible;
3923 
3924 	memcpy(info.tag, prog->tag, sizeof(prog->tag));
3925 	memcpy(info.name, prog->aux->name, sizeof(prog->aux->name));
3926 
3927 	mutex_lock(&prog->aux->used_maps_mutex);
3928 	ulen = info.nr_map_ids;
3929 	info.nr_map_ids = prog->aux->used_map_cnt;
3930 	ulen = min_t(u32, info.nr_map_ids, ulen);
3931 	if (ulen) {
3932 		u32 __user *user_map_ids = u64_to_user_ptr(info.map_ids);
3933 		u32 i;
3934 
3935 		for (i = 0; i < ulen; i++)
3936 			if (put_user(prog->aux->used_maps[i]->id,
3937 				     &user_map_ids[i])) {
3938 				mutex_unlock(&prog->aux->used_maps_mutex);
3939 				return -EFAULT;
3940 			}
3941 	}
3942 	mutex_unlock(&prog->aux->used_maps_mutex);
3943 
3944 	err = set_info_rec_size(&info);
3945 	if (err)
3946 		return err;
3947 
3948 	bpf_prog_get_stats(prog, &stats);
3949 	info.run_time_ns = stats.nsecs;
3950 	info.run_cnt = stats.cnt;
3951 	info.recursion_misses = stats.misses;
3952 
3953 	info.verified_insns = prog->aux->verified_insns;
3954 
3955 	if (!bpf_capable()) {
3956 		info.jited_prog_len = 0;
3957 		info.xlated_prog_len = 0;
3958 		info.nr_jited_ksyms = 0;
3959 		info.nr_jited_func_lens = 0;
3960 		info.nr_func_info = 0;
3961 		info.nr_line_info = 0;
3962 		info.nr_jited_line_info = 0;
3963 		goto done;
3964 	}
3965 
3966 	ulen = info.xlated_prog_len;
3967 	info.xlated_prog_len = bpf_prog_insn_size(prog);
3968 	if (info.xlated_prog_len && ulen) {
3969 		struct bpf_insn *insns_sanitized;
3970 		bool fault;
3971 
3972 		if (prog->blinded && !bpf_dump_raw_ok(file->f_cred)) {
3973 			info.xlated_prog_insns = 0;
3974 			goto done;
3975 		}
3976 		insns_sanitized = bpf_insn_prepare_dump(prog, file->f_cred);
3977 		if (!insns_sanitized)
3978 			return -ENOMEM;
3979 		uinsns = u64_to_user_ptr(info.xlated_prog_insns);
3980 		ulen = min_t(u32, info.xlated_prog_len, ulen);
3981 		fault = copy_to_user(uinsns, insns_sanitized, ulen);
3982 		kfree(insns_sanitized);
3983 		if (fault)
3984 			return -EFAULT;
3985 	}
3986 
3987 	if (bpf_prog_is_dev_bound(prog->aux)) {
3988 		err = bpf_prog_offload_info_fill(&info, prog);
3989 		if (err)
3990 			return err;
3991 		goto done;
3992 	}
3993 
3994 	/* NOTE: the following code is supposed to be skipped for offload.
3995 	 * bpf_prog_offload_info_fill() is the place to fill similar fields
3996 	 * for offload.
3997 	 */
3998 	ulen = info.jited_prog_len;
3999 	if (prog->aux->func_cnt) {
4000 		u32 i;
4001 
4002 		info.jited_prog_len = 0;
4003 		for (i = 0; i < prog->aux->func_cnt; i++)
4004 			info.jited_prog_len += prog->aux->func[i]->jited_len;
4005 	} else {
4006 		info.jited_prog_len = prog->jited_len;
4007 	}
4008 
4009 	if (info.jited_prog_len && ulen) {
4010 		if (bpf_dump_raw_ok(file->f_cred)) {
4011 			uinsns = u64_to_user_ptr(info.jited_prog_insns);
4012 			ulen = min_t(u32, info.jited_prog_len, ulen);
4013 
4014 			/* for multi-function programs, copy the JITed
4015 			 * instructions for all the functions
4016 			 */
4017 			if (prog->aux->func_cnt) {
4018 				u32 len, free, i;
4019 				u8 *img;
4020 
4021 				free = ulen;
4022 				for (i = 0; i < prog->aux->func_cnt; i++) {
4023 					len = prog->aux->func[i]->jited_len;
4024 					len = min_t(u32, len, free);
4025 					img = (u8 *) prog->aux->func[i]->bpf_func;
4026 					if (copy_to_user(uinsns, img, len))
4027 						return -EFAULT;
4028 					uinsns += len;
4029 					free -= len;
4030 					if (!free)
4031 						break;
4032 				}
4033 			} else {
4034 				if (copy_to_user(uinsns, prog->bpf_func, ulen))
4035 					return -EFAULT;
4036 			}
4037 		} else {
4038 			info.jited_prog_insns = 0;
4039 		}
4040 	}
4041 
4042 	ulen = info.nr_jited_ksyms;
4043 	info.nr_jited_ksyms = prog->aux->func_cnt ? : 1;
4044 	if (ulen) {
4045 		if (bpf_dump_raw_ok(file->f_cred)) {
4046 			unsigned long ksym_addr;
4047 			u64 __user *user_ksyms;
4048 			u32 i;
4049 
4050 			/* copy the address of the kernel symbol
4051 			 * corresponding to each function
4052 			 */
4053 			ulen = min_t(u32, info.nr_jited_ksyms, ulen);
4054 			user_ksyms = u64_to_user_ptr(info.jited_ksyms);
4055 			if (prog->aux->func_cnt) {
4056 				for (i = 0; i < ulen; i++) {
4057 					ksym_addr = (unsigned long)
4058 						prog->aux->func[i]->bpf_func;
4059 					if (put_user((u64) ksym_addr,
4060 						     &user_ksyms[i]))
4061 						return -EFAULT;
4062 				}
4063 			} else {
4064 				ksym_addr = (unsigned long) prog->bpf_func;
4065 				if (put_user((u64) ksym_addr, &user_ksyms[0]))
4066 					return -EFAULT;
4067 			}
4068 		} else {
4069 			info.jited_ksyms = 0;
4070 		}
4071 	}
4072 
4073 	ulen = info.nr_jited_func_lens;
4074 	info.nr_jited_func_lens = prog->aux->func_cnt ? : 1;
4075 	if (ulen) {
4076 		if (bpf_dump_raw_ok(file->f_cred)) {
4077 			u32 __user *user_lens;
4078 			u32 func_len, i;
4079 
4080 			/* copy the JITed image lengths for each function */
4081 			ulen = min_t(u32, info.nr_jited_func_lens, ulen);
4082 			user_lens = u64_to_user_ptr(info.jited_func_lens);
4083 			if (prog->aux->func_cnt) {
4084 				for (i = 0; i < ulen; i++) {
4085 					func_len =
4086 						prog->aux->func[i]->jited_len;
4087 					if (put_user(func_len, &user_lens[i]))
4088 						return -EFAULT;
4089 				}
4090 			} else {
4091 				func_len = prog->jited_len;
4092 				if (put_user(func_len, &user_lens[0]))
4093 					return -EFAULT;
4094 			}
4095 		} else {
4096 			info.jited_func_lens = 0;
4097 		}
4098 	}
4099 
4100 	if (prog->aux->btf)
4101 		info.btf_id = btf_obj_id(prog->aux->btf);
4102 	info.attach_btf_id = prog->aux->attach_btf_id;
4103 	if (attach_btf)
4104 		info.attach_btf_obj_id = btf_obj_id(attach_btf);
4105 
4106 	ulen = info.nr_func_info;
4107 	info.nr_func_info = prog->aux->func_info_cnt;
4108 	if (info.nr_func_info && ulen) {
4109 		char __user *user_finfo;
4110 
4111 		user_finfo = u64_to_user_ptr(info.func_info);
4112 		ulen = min_t(u32, info.nr_func_info, ulen);
4113 		if (copy_to_user(user_finfo, prog->aux->func_info,
4114 				 info.func_info_rec_size * ulen))
4115 			return -EFAULT;
4116 	}
4117 
4118 	ulen = info.nr_line_info;
4119 	info.nr_line_info = prog->aux->nr_linfo;
4120 	if (info.nr_line_info && ulen) {
4121 		__u8 __user *user_linfo;
4122 
4123 		user_linfo = u64_to_user_ptr(info.line_info);
4124 		ulen = min_t(u32, info.nr_line_info, ulen);
4125 		if (copy_to_user(user_linfo, prog->aux->linfo,
4126 				 info.line_info_rec_size * ulen))
4127 			return -EFAULT;
4128 	}
4129 
4130 	ulen = info.nr_jited_line_info;
4131 	if (prog->aux->jited_linfo)
4132 		info.nr_jited_line_info = prog->aux->nr_linfo;
4133 	else
4134 		info.nr_jited_line_info = 0;
4135 	if (info.nr_jited_line_info && ulen) {
4136 		if (bpf_dump_raw_ok(file->f_cred)) {
4137 			unsigned long line_addr;
4138 			__u64 __user *user_linfo;
4139 			u32 i;
4140 
4141 			user_linfo = u64_to_user_ptr(info.jited_line_info);
4142 			ulen = min_t(u32, info.nr_jited_line_info, ulen);
4143 			for (i = 0; i < ulen; i++) {
4144 				line_addr = (unsigned long)prog->aux->jited_linfo[i];
4145 				if (put_user((__u64)line_addr, &user_linfo[i]))
4146 					return -EFAULT;
4147 			}
4148 		} else {
4149 			info.jited_line_info = 0;
4150 		}
4151 	}
4152 
4153 	ulen = info.nr_prog_tags;
4154 	info.nr_prog_tags = prog->aux->func_cnt ? : 1;
4155 	if (ulen) {
4156 		__u8 __user (*user_prog_tags)[BPF_TAG_SIZE];
4157 		u32 i;
4158 
4159 		user_prog_tags = u64_to_user_ptr(info.prog_tags);
4160 		ulen = min_t(u32, info.nr_prog_tags, ulen);
4161 		if (prog->aux->func_cnt) {
4162 			for (i = 0; i < ulen; i++) {
4163 				if (copy_to_user(user_prog_tags[i],
4164 						 prog->aux->func[i]->tag,
4165 						 BPF_TAG_SIZE))
4166 					return -EFAULT;
4167 			}
4168 		} else {
4169 			if (copy_to_user(user_prog_tags[0],
4170 					 prog->tag, BPF_TAG_SIZE))
4171 				return -EFAULT;
4172 		}
4173 	}
4174 
4175 done:
4176 	if (copy_to_user(uinfo, &info, info_len) ||
4177 	    put_user(info_len, &uattr->info.info_len))
4178 		return -EFAULT;
4179 
4180 	return 0;
4181 }
4182 
4183 static int bpf_map_get_info_by_fd(struct file *file,
4184 				  struct bpf_map *map,
4185 				  const union bpf_attr *attr,
4186 				  union bpf_attr __user *uattr)
4187 {
4188 	struct bpf_map_info __user *uinfo = u64_to_user_ptr(attr->info.info);
4189 	struct bpf_map_info info;
4190 	u32 info_len = attr->info.info_len;
4191 	int err;
4192 
4193 	err = bpf_check_uarg_tail_zero(USER_BPFPTR(uinfo), sizeof(info), info_len);
4194 	if (err)
4195 		return err;
4196 	info_len = min_t(u32, sizeof(info), info_len);
4197 
4198 	memset(&info, 0, sizeof(info));
4199 	info.type = map->map_type;
4200 	info.id = map->id;
4201 	info.key_size = map->key_size;
4202 	info.value_size = map->value_size;
4203 	info.max_entries = map->max_entries;
4204 	info.map_flags = map->map_flags;
4205 	info.map_extra = map->map_extra;
4206 	memcpy(info.name, map->name, sizeof(map->name));
4207 
4208 	if (map->btf) {
4209 		info.btf_id = btf_obj_id(map->btf);
4210 		info.btf_key_type_id = map->btf_key_type_id;
4211 		info.btf_value_type_id = map->btf_value_type_id;
4212 	}
4213 	info.btf_vmlinux_value_type_id = map->btf_vmlinux_value_type_id;
4214 
4215 	if (bpf_map_is_dev_bound(map)) {
4216 		err = bpf_map_offload_info_fill(&info, map);
4217 		if (err)
4218 			return err;
4219 	}
4220 
4221 	if (copy_to_user(uinfo, &info, info_len) ||
4222 	    put_user(info_len, &uattr->info.info_len))
4223 		return -EFAULT;
4224 
4225 	return 0;
4226 }
4227 
4228 static int bpf_btf_get_info_by_fd(struct file *file,
4229 				  struct btf *btf,
4230 				  const union bpf_attr *attr,
4231 				  union bpf_attr __user *uattr)
4232 {
4233 	struct bpf_btf_info __user *uinfo = u64_to_user_ptr(attr->info.info);
4234 	u32 info_len = attr->info.info_len;
4235 	int err;
4236 
4237 	err = bpf_check_uarg_tail_zero(USER_BPFPTR(uinfo), sizeof(*uinfo), info_len);
4238 	if (err)
4239 		return err;
4240 
4241 	return btf_get_info_by_fd(btf, attr, uattr);
4242 }
4243 
4244 static int bpf_link_get_info_by_fd(struct file *file,
4245 				  struct bpf_link *link,
4246 				  const union bpf_attr *attr,
4247 				  union bpf_attr __user *uattr)
4248 {
4249 	struct bpf_link_info __user *uinfo = u64_to_user_ptr(attr->info.info);
4250 	struct bpf_link_info info;
4251 	u32 info_len = attr->info.info_len;
4252 	int err;
4253 
4254 	err = bpf_check_uarg_tail_zero(USER_BPFPTR(uinfo), sizeof(info), info_len);
4255 	if (err)
4256 		return err;
4257 	info_len = min_t(u32, sizeof(info), info_len);
4258 
4259 	memset(&info, 0, sizeof(info));
4260 	if (copy_from_user(&info, uinfo, info_len))
4261 		return -EFAULT;
4262 
4263 	info.type = link->type;
4264 	info.id = link->id;
4265 	info.prog_id = link->prog->aux->id;
4266 
4267 	if (link->ops->fill_link_info) {
4268 		err = link->ops->fill_link_info(link, &info);
4269 		if (err)
4270 			return err;
4271 	}
4272 
4273 	if (copy_to_user(uinfo, &info, info_len) ||
4274 	    put_user(info_len, &uattr->info.info_len))
4275 		return -EFAULT;
4276 
4277 	return 0;
4278 }
4279 
4280 
4281 #define BPF_OBJ_GET_INFO_BY_FD_LAST_FIELD info.info
4282 
4283 static int bpf_obj_get_info_by_fd(const union bpf_attr *attr,
4284 				  union bpf_attr __user *uattr)
4285 {
4286 	int ufd = attr->info.bpf_fd;
4287 	struct fd f;
4288 	int err;
4289 
4290 	if (CHECK_ATTR(BPF_OBJ_GET_INFO_BY_FD))
4291 		return -EINVAL;
4292 
4293 	f = fdget(ufd);
4294 	if (!f.file)
4295 		return -EBADFD;
4296 
4297 	if (f.file->f_op == &bpf_prog_fops)
4298 		err = bpf_prog_get_info_by_fd(f.file, f.file->private_data, attr,
4299 					      uattr);
4300 	else if (f.file->f_op == &bpf_map_fops)
4301 		err = bpf_map_get_info_by_fd(f.file, f.file->private_data, attr,
4302 					     uattr);
4303 	else if (f.file->f_op == &btf_fops)
4304 		err = bpf_btf_get_info_by_fd(f.file, f.file->private_data, attr, uattr);
4305 	else if (f.file->f_op == &bpf_link_fops)
4306 		err = bpf_link_get_info_by_fd(f.file, f.file->private_data,
4307 					      attr, uattr);
4308 	else
4309 		err = -EINVAL;
4310 
4311 	fdput(f);
4312 	return err;
4313 }
4314 
4315 #define BPF_BTF_LOAD_LAST_FIELD btf_log_level
4316 
4317 static int bpf_btf_load(const union bpf_attr *attr, bpfptr_t uattr)
4318 {
4319 	if (CHECK_ATTR(BPF_BTF_LOAD))
4320 		return -EINVAL;
4321 
4322 	if (!bpf_capable())
4323 		return -EPERM;
4324 
4325 	return btf_new_fd(attr, uattr);
4326 }
4327 
4328 #define BPF_BTF_GET_FD_BY_ID_LAST_FIELD btf_id
4329 
4330 static int bpf_btf_get_fd_by_id(const union bpf_attr *attr)
4331 {
4332 	if (CHECK_ATTR(BPF_BTF_GET_FD_BY_ID))
4333 		return -EINVAL;
4334 
4335 	if (!capable(CAP_SYS_ADMIN))
4336 		return -EPERM;
4337 
4338 	return btf_get_fd_by_id(attr->btf_id);
4339 }
4340 
4341 static int bpf_task_fd_query_copy(const union bpf_attr *attr,
4342 				    union bpf_attr __user *uattr,
4343 				    u32 prog_id, u32 fd_type,
4344 				    const char *buf, u64 probe_offset,
4345 				    u64 probe_addr)
4346 {
4347 	char __user *ubuf = u64_to_user_ptr(attr->task_fd_query.buf);
4348 	u32 len = buf ? strlen(buf) : 0, input_len;
4349 	int err = 0;
4350 
4351 	if (put_user(len, &uattr->task_fd_query.buf_len))
4352 		return -EFAULT;
4353 	input_len = attr->task_fd_query.buf_len;
4354 	if (input_len && ubuf) {
4355 		if (!len) {
4356 			/* nothing to copy, just make ubuf NULL terminated */
4357 			char zero = '\0';
4358 
4359 			if (put_user(zero, ubuf))
4360 				return -EFAULT;
4361 		} else if (input_len >= len + 1) {
4362 			/* ubuf can hold the string with NULL terminator */
4363 			if (copy_to_user(ubuf, buf, len + 1))
4364 				return -EFAULT;
4365 		} else {
4366 			/* ubuf cannot hold the string with NULL terminator,
4367 			 * do a partial copy with NULL terminator.
4368 			 */
4369 			char zero = '\0';
4370 
4371 			err = -ENOSPC;
4372 			if (copy_to_user(ubuf, buf, input_len - 1))
4373 				return -EFAULT;
4374 			if (put_user(zero, ubuf + input_len - 1))
4375 				return -EFAULT;
4376 		}
4377 	}
4378 
4379 	if (put_user(prog_id, &uattr->task_fd_query.prog_id) ||
4380 	    put_user(fd_type, &uattr->task_fd_query.fd_type) ||
4381 	    put_user(probe_offset, &uattr->task_fd_query.probe_offset) ||
4382 	    put_user(probe_addr, &uattr->task_fd_query.probe_addr))
4383 		return -EFAULT;
4384 
4385 	return err;
4386 }
4387 
4388 #define BPF_TASK_FD_QUERY_LAST_FIELD task_fd_query.probe_addr
4389 
4390 static int bpf_task_fd_query(const union bpf_attr *attr,
4391 			     union bpf_attr __user *uattr)
4392 {
4393 	pid_t pid = attr->task_fd_query.pid;
4394 	u32 fd = attr->task_fd_query.fd;
4395 	const struct perf_event *event;
4396 	struct task_struct *task;
4397 	struct file *file;
4398 	int err;
4399 
4400 	if (CHECK_ATTR(BPF_TASK_FD_QUERY))
4401 		return -EINVAL;
4402 
4403 	if (!capable(CAP_SYS_ADMIN))
4404 		return -EPERM;
4405 
4406 	if (attr->task_fd_query.flags != 0)
4407 		return -EINVAL;
4408 
4409 	rcu_read_lock();
4410 	task = get_pid_task(find_vpid(pid), PIDTYPE_PID);
4411 	rcu_read_unlock();
4412 	if (!task)
4413 		return -ENOENT;
4414 
4415 	err = 0;
4416 	file = fget_task(task, fd);
4417 	put_task_struct(task);
4418 	if (!file)
4419 		return -EBADF;
4420 
4421 	if (file->f_op == &bpf_link_fops) {
4422 		struct bpf_link *link = file->private_data;
4423 
4424 		if (link->ops == &bpf_raw_tp_link_lops) {
4425 			struct bpf_raw_tp_link *raw_tp =
4426 				container_of(link, struct bpf_raw_tp_link, link);
4427 			struct bpf_raw_event_map *btp = raw_tp->btp;
4428 
4429 			err = bpf_task_fd_query_copy(attr, uattr,
4430 						     raw_tp->link.prog->aux->id,
4431 						     BPF_FD_TYPE_RAW_TRACEPOINT,
4432 						     btp->tp->name, 0, 0);
4433 			goto put_file;
4434 		}
4435 		goto out_not_supp;
4436 	}
4437 
4438 	event = perf_get_event(file);
4439 	if (!IS_ERR(event)) {
4440 		u64 probe_offset, probe_addr;
4441 		u32 prog_id, fd_type;
4442 		const char *buf;
4443 
4444 		err = bpf_get_perf_event_info(event, &prog_id, &fd_type,
4445 					      &buf, &probe_offset,
4446 					      &probe_addr);
4447 		if (!err)
4448 			err = bpf_task_fd_query_copy(attr, uattr, prog_id,
4449 						     fd_type, buf,
4450 						     probe_offset,
4451 						     probe_addr);
4452 		goto put_file;
4453 	}
4454 
4455 out_not_supp:
4456 	err = -ENOTSUPP;
4457 put_file:
4458 	fput(file);
4459 	return err;
4460 }
4461 
4462 #define BPF_MAP_BATCH_LAST_FIELD batch.flags
4463 
4464 #define BPF_DO_BATCH(fn)			\
4465 	do {					\
4466 		if (!fn) {			\
4467 			err = -ENOTSUPP;	\
4468 			goto err_put;		\
4469 		}				\
4470 		err = fn(map, attr, uattr);	\
4471 	} while (0)
4472 
4473 static int bpf_map_do_batch(const union bpf_attr *attr,
4474 			    union bpf_attr __user *uattr,
4475 			    int cmd)
4476 {
4477 	bool has_read  = cmd == BPF_MAP_LOOKUP_BATCH ||
4478 			 cmd == BPF_MAP_LOOKUP_AND_DELETE_BATCH;
4479 	bool has_write = cmd != BPF_MAP_LOOKUP_BATCH;
4480 	struct bpf_map *map;
4481 	int err, ufd;
4482 	struct fd f;
4483 
4484 	if (CHECK_ATTR(BPF_MAP_BATCH))
4485 		return -EINVAL;
4486 
4487 	ufd = attr->batch.map_fd;
4488 	f = fdget(ufd);
4489 	map = __bpf_map_get(f);
4490 	if (IS_ERR(map))
4491 		return PTR_ERR(map);
4492 	if (has_write)
4493 		bpf_map_write_active_inc(map);
4494 	if (has_read && !(map_get_sys_perms(map, f) & FMODE_CAN_READ)) {
4495 		err = -EPERM;
4496 		goto err_put;
4497 	}
4498 	if (has_write && !(map_get_sys_perms(map, f) & FMODE_CAN_WRITE)) {
4499 		err = -EPERM;
4500 		goto err_put;
4501 	}
4502 
4503 	if (cmd == BPF_MAP_LOOKUP_BATCH)
4504 		BPF_DO_BATCH(map->ops->map_lookup_batch);
4505 	else if (cmd == BPF_MAP_LOOKUP_AND_DELETE_BATCH)
4506 		BPF_DO_BATCH(map->ops->map_lookup_and_delete_batch);
4507 	else if (cmd == BPF_MAP_UPDATE_BATCH)
4508 		BPF_DO_BATCH(map->ops->map_update_batch);
4509 	else
4510 		BPF_DO_BATCH(map->ops->map_delete_batch);
4511 err_put:
4512 	if (has_write)
4513 		bpf_map_write_active_dec(map);
4514 	fdput(f);
4515 	return err;
4516 }
4517 
4518 #define BPF_LINK_CREATE_LAST_FIELD link_create.kprobe_multi.cookies
4519 static int link_create(union bpf_attr *attr, bpfptr_t uattr)
4520 {
4521 	enum bpf_prog_type ptype;
4522 	struct bpf_prog *prog;
4523 	int ret;
4524 
4525 	if (CHECK_ATTR(BPF_LINK_CREATE))
4526 		return -EINVAL;
4527 
4528 	prog = bpf_prog_get(attr->link_create.prog_fd);
4529 	if (IS_ERR(prog))
4530 		return PTR_ERR(prog);
4531 
4532 	ret = bpf_prog_attach_check_attach_type(prog,
4533 						attr->link_create.attach_type);
4534 	if (ret)
4535 		goto out;
4536 
4537 	switch (prog->type) {
4538 	case BPF_PROG_TYPE_EXT:
4539 		break;
4540 	case BPF_PROG_TYPE_PERF_EVENT:
4541 	case BPF_PROG_TYPE_TRACEPOINT:
4542 		if (attr->link_create.attach_type != BPF_PERF_EVENT) {
4543 			ret = -EINVAL;
4544 			goto out;
4545 		}
4546 		break;
4547 	case BPF_PROG_TYPE_KPROBE:
4548 		if (attr->link_create.attach_type != BPF_PERF_EVENT &&
4549 		    attr->link_create.attach_type != BPF_TRACE_KPROBE_MULTI) {
4550 			ret = -EINVAL;
4551 			goto out;
4552 		}
4553 		break;
4554 	default:
4555 		ptype = attach_type_to_prog_type(attr->link_create.attach_type);
4556 		if (ptype == BPF_PROG_TYPE_UNSPEC || ptype != prog->type) {
4557 			ret = -EINVAL;
4558 			goto out;
4559 		}
4560 		break;
4561 	}
4562 
4563 	switch (prog->type) {
4564 	case BPF_PROG_TYPE_CGROUP_SKB:
4565 	case BPF_PROG_TYPE_CGROUP_SOCK:
4566 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
4567 	case BPF_PROG_TYPE_SOCK_OPS:
4568 	case BPF_PROG_TYPE_CGROUP_DEVICE:
4569 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
4570 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
4571 		ret = cgroup_bpf_link_attach(attr, prog);
4572 		break;
4573 	case BPF_PROG_TYPE_EXT:
4574 		ret = bpf_tracing_prog_attach(prog,
4575 					      attr->link_create.target_fd,
4576 					      attr->link_create.target_btf_id,
4577 					      attr->link_create.tracing.cookie);
4578 		break;
4579 	case BPF_PROG_TYPE_LSM:
4580 	case BPF_PROG_TYPE_TRACING:
4581 		if (attr->link_create.attach_type != prog->expected_attach_type) {
4582 			ret = -EINVAL;
4583 			goto out;
4584 		}
4585 		if (prog->expected_attach_type == BPF_TRACE_RAW_TP)
4586 			ret = bpf_raw_tp_link_attach(prog, NULL);
4587 		else if (prog->expected_attach_type == BPF_TRACE_ITER)
4588 			ret = bpf_iter_link_attach(attr, uattr, prog);
4589 		else if (prog->expected_attach_type == BPF_LSM_CGROUP)
4590 			ret = cgroup_bpf_link_attach(attr, prog);
4591 		else
4592 			ret = bpf_tracing_prog_attach(prog,
4593 						      attr->link_create.target_fd,
4594 						      attr->link_create.target_btf_id,
4595 						      attr->link_create.tracing.cookie);
4596 		break;
4597 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
4598 	case BPF_PROG_TYPE_SK_LOOKUP:
4599 		ret = netns_bpf_link_create(attr, prog);
4600 		break;
4601 #ifdef CONFIG_NET
4602 	case BPF_PROG_TYPE_XDP:
4603 		ret = bpf_xdp_link_attach(attr, prog);
4604 		break;
4605 #endif
4606 	case BPF_PROG_TYPE_PERF_EVENT:
4607 	case BPF_PROG_TYPE_TRACEPOINT:
4608 		ret = bpf_perf_link_attach(attr, prog);
4609 		break;
4610 	case BPF_PROG_TYPE_KPROBE:
4611 		if (attr->link_create.attach_type == BPF_PERF_EVENT)
4612 			ret = bpf_perf_link_attach(attr, prog);
4613 		else
4614 			ret = bpf_kprobe_multi_link_attach(attr, prog);
4615 		break;
4616 	default:
4617 		ret = -EINVAL;
4618 	}
4619 
4620 out:
4621 	if (ret < 0)
4622 		bpf_prog_put(prog);
4623 	return ret;
4624 }
4625 
4626 #define BPF_LINK_UPDATE_LAST_FIELD link_update.old_prog_fd
4627 
4628 static int link_update(union bpf_attr *attr)
4629 {
4630 	struct bpf_prog *old_prog = NULL, *new_prog;
4631 	struct bpf_link *link;
4632 	u32 flags;
4633 	int ret;
4634 
4635 	if (CHECK_ATTR(BPF_LINK_UPDATE))
4636 		return -EINVAL;
4637 
4638 	flags = attr->link_update.flags;
4639 	if (flags & ~BPF_F_REPLACE)
4640 		return -EINVAL;
4641 
4642 	link = bpf_link_get_from_fd(attr->link_update.link_fd);
4643 	if (IS_ERR(link))
4644 		return PTR_ERR(link);
4645 
4646 	new_prog = bpf_prog_get(attr->link_update.new_prog_fd);
4647 	if (IS_ERR(new_prog)) {
4648 		ret = PTR_ERR(new_prog);
4649 		goto out_put_link;
4650 	}
4651 
4652 	if (flags & BPF_F_REPLACE) {
4653 		old_prog = bpf_prog_get(attr->link_update.old_prog_fd);
4654 		if (IS_ERR(old_prog)) {
4655 			ret = PTR_ERR(old_prog);
4656 			old_prog = NULL;
4657 			goto out_put_progs;
4658 		}
4659 	} else if (attr->link_update.old_prog_fd) {
4660 		ret = -EINVAL;
4661 		goto out_put_progs;
4662 	}
4663 
4664 	if (link->ops->update_prog)
4665 		ret = link->ops->update_prog(link, new_prog, old_prog);
4666 	else
4667 		ret = -EINVAL;
4668 
4669 out_put_progs:
4670 	if (old_prog)
4671 		bpf_prog_put(old_prog);
4672 	if (ret)
4673 		bpf_prog_put(new_prog);
4674 out_put_link:
4675 	bpf_link_put(link);
4676 	return ret;
4677 }
4678 
4679 #define BPF_LINK_DETACH_LAST_FIELD link_detach.link_fd
4680 
4681 static int link_detach(union bpf_attr *attr)
4682 {
4683 	struct bpf_link *link;
4684 	int ret;
4685 
4686 	if (CHECK_ATTR(BPF_LINK_DETACH))
4687 		return -EINVAL;
4688 
4689 	link = bpf_link_get_from_fd(attr->link_detach.link_fd);
4690 	if (IS_ERR(link))
4691 		return PTR_ERR(link);
4692 
4693 	if (link->ops->detach)
4694 		ret = link->ops->detach(link);
4695 	else
4696 		ret = -EOPNOTSUPP;
4697 
4698 	bpf_link_put(link);
4699 	return ret;
4700 }
4701 
4702 static struct bpf_link *bpf_link_inc_not_zero(struct bpf_link *link)
4703 {
4704 	return atomic64_fetch_add_unless(&link->refcnt, 1, 0) ? link : ERR_PTR(-ENOENT);
4705 }
4706 
4707 struct bpf_link *bpf_link_by_id(u32 id)
4708 {
4709 	struct bpf_link *link;
4710 
4711 	if (!id)
4712 		return ERR_PTR(-ENOENT);
4713 
4714 	spin_lock_bh(&link_idr_lock);
4715 	/* before link is "settled", ID is 0, pretend it doesn't exist yet */
4716 	link = idr_find(&link_idr, id);
4717 	if (link) {
4718 		if (link->id)
4719 			link = bpf_link_inc_not_zero(link);
4720 		else
4721 			link = ERR_PTR(-EAGAIN);
4722 	} else {
4723 		link = ERR_PTR(-ENOENT);
4724 	}
4725 	spin_unlock_bh(&link_idr_lock);
4726 	return link;
4727 }
4728 
4729 struct bpf_link *bpf_link_get_curr_or_next(u32 *id)
4730 {
4731 	struct bpf_link *link;
4732 
4733 	spin_lock_bh(&link_idr_lock);
4734 again:
4735 	link = idr_get_next(&link_idr, id);
4736 	if (link) {
4737 		link = bpf_link_inc_not_zero(link);
4738 		if (IS_ERR(link)) {
4739 			(*id)++;
4740 			goto again;
4741 		}
4742 	}
4743 	spin_unlock_bh(&link_idr_lock);
4744 
4745 	return link;
4746 }
4747 
4748 #define BPF_LINK_GET_FD_BY_ID_LAST_FIELD link_id
4749 
4750 static int bpf_link_get_fd_by_id(const union bpf_attr *attr)
4751 {
4752 	struct bpf_link *link;
4753 	u32 id = attr->link_id;
4754 	int fd;
4755 
4756 	if (CHECK_ATTR(BPF_LINK_GET_FD_BY_ID))
4757 		return -EINVAL;
4758 
4759 	if (!capable(CAP_SYS_ADMIN))
4760 		return -EPERM;
4761 
4762 	link = bpf_link_by_id(id);
4763 	if (IS_ERR(link))
4764 		return PTR_ERR(link);
4765 
4766 	fd = bpf_link_new_fd(link);
4767 	if (fd < 0)
4768 		bpf_link_put(link);
4769 
4770 	return fd;
4771 }
4772 
4773 DEFINE_MUTEX(bpf_stats_enabled_mutex);
4774 
4775 static int bpf_stats_release(struct inode *inode, struct file *file)
4776 {
4777 	mutex_lock(&bpf_stats_enabled_mutex);
4778 	static_key_slow_dec(&bpf_stats_enabled_key.key);
4779 	mutex_unlock(&bpf_stats_enabled_mutex);
4780 	return 0;
4781 }
4782 
4783 static const struct file_operations bpf_stats_fops = {
4784 	.release = bpf_stats_release,
4785 };
4786 
4787 static int bpf_enable_runtime_stats(void)
4788 {
4789 	int fd;
4790 
4791 	mutex_lock(&bpf_stats_enabled_mutex);
4792 
4793 	/* Set a very high limit to avoid overflow */
4794 	if (static_key_count(&bpf_stats_enabled_key.key) > INT_MAX / 2) {
4795 		mutex_unlock(&bpf_stats_enabled_mutex);
4796 		return -EBUSY;
4797 	}
4798 
4799 	fd = anon_inode_getfd("bpf-stats", &bpf_stats_fops, NULL, O_CLOEXEC);
4800 	if (fd >= 0)
4801 		static_key_slow_inc(&bpf_stats_enabled_key.key);
4802 
4803 	mutex_unlock(&bpf_stats_enabled_mutex);
4804 	return fd;
4805 }
4806 
4807 #define BPF_ENABLE_STATS_LAST_FIELD enable_stats.type
4808 
4809 static int bpf_enable_stats(union bpf_attr *attr)
4810 {
4811 
4812 	if (CHECK_ATTR(BPF_ENABLE_STATS))
4813 		return -EINVAL;
4814 
4815 	if (!capable(CAP_SYS_ADMIN))
4816 		return -EPERM;
4817 
4818 	switch (attr->enable_stats.type) {
4819 	case BPF_STATS_RUN_TIME:
4820 		return bpf_enable_runtime_stats();
4821 	default:
4822 		break;
4823 	}
4824 	return -EINVAL;
4825 }
4826 
4827 #define BPF_ITER_CREATE_LAST_FIELD iter_create.flags
4828 
4829 static int bpf_iter_create(union bpf_attr *attr)
4830 {
4831 	struct bpf_link *link;
4832 	int err;
4833 
4834 	if (CHECK_ATTR(BPF_ITER_CREATE))
4835 		return -EINVAL;
4836 
4837 	if (attr->iter_create.flags)
4838 		return -EINVAL;
4839 
4840 	link = bpf_link_get_from_fd(attr->iter_create.link_fd);
4841 	if (IS_ERR(link))
4842 		return PTR_ERR(link);
4843 
4844 	err = bpf_iter_new_fd(link);
4845 	bpf_link_put(link);
4846 
4847 	return err;
4848 }
4849 
4850 #define BPF_PROG_BIND_MAP_LAST_FIELD prog_bind_map.flags
4851 
4852 static int bpf_prog_bind_map(union bpf_attr *attr)
4853 {
4854 	struct bpf_prog *prog;
4855 	struct bpf_map *map;
4856 	struct bpf_map **used_maps_old, **used_maps_new;
4857 	int i, ret = 0;
4858 
4859 	if (CHECK_ATTR(BPF_PROG_BIND_MAP))
4860 		return -EINVAL;
4861 
4862 	if (attr->prog_bind_map.flags)
4863 		return -EINVAL;
4864 
4865 	prog = bpf_prog_get(attr->prog_bind_map.prog_fd);
4866 	if (IS_ERR(prog))
4867 		return PTR_ERR(prog);
4868 
4869 	map = bpf_map_get(attr->prog_bind_map.map_fd);
4870 	if (IS_ERR(map)) {
4871 		ret = PTR_ERR(map);
4872 		goto out_prog_put;
4873 	}
4874 
4875 	mutex_lock(&prog->aux->used_maps_mutex);
4876 
4877 	used_maps_old = prog->aux->used_maps;
4878 
4879 	for (i = 0; i < prog->aux->used_map_cnt; i++)
4880 		if (used_maps_old[i] == map) {
4881 			bpf_map_put(map);
4882 			goto out_unlock;
4883 		}
4884 
4885 	used_maps_new = kmalloc_array(prog->aux->used_map_cnt + 1,
4886 				      sizeof(used_maps_new[0]),
4887 				      GFP_KERNEL);
4888 	if (!used_maps_new) {
4889 		ret = -ENOMEM;
4890 		goto out_unlock;
4891 	}
4892 
4893 	memcpy(used_maps_new, used_maps_old,
4894 	       sizeof(used_maps_old[0]) * prog->aux->used_map_cnt);
4895 	used_maps_new[prog->aux->used_map_cnt] = map;
4896 
4897 	prog->aux->used_map_cnt++;
4898 	prog->aux->used_maps = used_maps_new;
4899 
4900 	kfree(used_maps_old);
4901 
4902 out_unlock:
4903 	mutex_unlock(&prog->aux->used_maps_mutex);
4904 
4905 	if (ret)
4906 		bpf_map_put(map);
4907 out_prog_put:
4908 	bpf_prog_put(prog);
4909 	return ret;
4910 }
4911 
4912 static int __sys_bpf(int cmd, bpfptr_t uattr, unsigned int size)
4913 {
4914 	union bpf_attr attr;
4915 	bool capable;
4916 	int err;
4917 
4918 	capable = bpf_capable() || !sysctl_unprivileged_bpf_disabled;
4919 
4920 	/* Intent here is for unprivileged_bpf_disabled to block key object
4921 	 * creation commands for unprivileged users; other actions depend
4922 	 * of fd availability and access to bpffs, so are dependent on
4923 	 * object creation success.  Capabilities are later verified for
4924 	 * operations such as load and map create, so even with unprivileged
4925 	 * BPF disabled, capability checks are still carried out for these
4926 	 * and other operations.
4927 	 */
4928 	if (!capable &&
4929 	    (cmd == BPF_MAP_CREATE || cmd == BPF_PROG_LOAD))
4930 		return -EPERM;
4931 
4932 	err = bpf_check_uarg_tail_zero(uattr, sizeof(attr), size);
4933 	if (err)
4934 		return err;
4935 	size = min_t(u32, size, sizeof(attr));
4936 
4937 	/* copy attributes from user space, may be less than sizeof(bpf_attr) */
4938 	memset(&attr, 0, sizeof(attr));
4939 	if (copy_from_bpfptr(&attr, uattr, size) != 0)
4940 		return -EFAULT;
4941 
4942 	err = security_bpf(cmd, &attr, size);
4943 	if (err < 0)
4944 		return err;
4945 
4946 	switch (cmd) {
4947 	case BPF_MAP_CREATE:
4948 		err = map_create(&attr);
4949 		break;
4950 	case BPF_MAP_LOOKUP_ELEM:
4951 		err = map_lookup_elem(&attr);
4952 		break;
4953 	case BPF_MAP_UPDATE_ELEM:
4954 		err = map_update_elem(&attr, uattr);
4955 		break;
4956 	case BPF_MAP_DELETE_ELEM:
4957 		err = map_delete_elem(&attr, uattr);
4958 		break;
4959 	case BPF_MAP_GET_NEXT_KEY:
4960 		err = map_get_next_key(&attr);
4961 		break;
4962 	case BPF_MAP_FREEZE:
4963 		err = map_freeze(&attr);
4964 		break;
4965 	case BPF_PROG_LOAD:
4966 		err = bpf_prog_load(&attr, uattr);
4967 		break;
4968 	case BPF_OBJ_PIN:
4969 		err = bpf_obj_pin(&attr);
4970 		break;
4971 	case BPF_OBJ_GET:
4972 		err = bpf_obj_get(&attr);
4973 		break;
4974 	case BPF_PROG_ATTACH:
4975 		err = bpf_prog_attach(&attr);
4976 		break;
4977 	case BPF_PROG_DETACH:
4978 		err = bpf_prog_detach(&attr);
4979 		break;
4980 	case BPF_PROG_QUERY:
4981 		err = bpf_prog_query(&attr, uattr.user);
4982 		break;
4983 	case BPF_PROG_TEST_RUN:
4984 		err = bpf_prog_test_run(&attr, uattr.user);
4985 		break;
4986 	case BPF_PROG_GET_NEXT_ID:
4987 		err = bpf_obj_get_next_id(&attr, uattr.user,
4988 					  &prog_idr, &prog_idr_lock);
4989 		break;
4990 	case BPF_MAP_GET_NEXT_ID:
4991 		err = bpf_obj_get_next_id(&attr, uattr.user,
4992 					  &map_idr, &map_idr_lock);
4993 		break;
4994 	case BPF_BTF_GET_NEXT_ID:
4995 		err = bpf_obj_get_next_id(&attr, uattr.user,
4996 					  &btf_idr, &btf_idr_lock);
4997 		break;
4998 	case BPF_PROG_GET_FD_BY_ID:
4999 		err = bpf_prog_get_fd_by_id(&attr);
5000 		break;
5001 	case BPF_MAP_GET_FD_BY_ID:
5002 		err = bpf_map_get_fd_by_id(&attr);
5003 		break;
5004 	case BPF_OBJ_GET_INFO_BY_FD:
5005 		err = bpf_obj_get_info_by_fd(&attr, uattr.user);
5006 		break;
5007 	case BPF_RAW_TRACEPOINT_OPEN:
5008 		err = bpf_raw_tracepoint_open(&attr);
5009 		break;
5010 	case BPF_BTF_LOAD:
5011 		err = bpf_btf_load(&attr, uattr);
5012 		break;
5013 	case BPF_BTF_GET_FD_BY_ID:
5014 		err = bpf_btf_get_fd_by_id(&attr);
5015 		break;
5016 	case BPF_TASK_FD_QUERY:
5017 		err = bpf_task_fd_query(&attr, uattr.user);
5018 		break;
5019 	case BPF_MAP_LOOKUP_AND_DELETE_ELEM:
5020 		err = map_lookup_and_delete_elem(&attr);
5021 		break;
5022 	case BPF_MAP_LOOKUP_BATCH:
5023 		err = bpf_map_do_batch(&attr, uattr.user, BPF_MAP_LOOKUP_BATCH);
5024 		break;
5025 	case BPF_MAP_LOOKUP_AND_DELETE_BATCH:
5026 		err = bpf_map_do_batch(&attr, uattr.user,
5027 				       BPF_MAP_LOOKUP_AND_DELETE_BATCH);
5028 		break;
5029 	case BPF_MAP_UPDATE_BATCH:
5030 		err = bpf_map_do_batch(&attr, uattr.user, BPF_MAP_UPDATE_BATCH);
5031 		break;
5032 	case BPF_MAP_DELETE_BATCH:
5033 		err = bpf_map_do_batch(&attr, uattr.user, BPF_MAP_DELETE_BATCH);
5034 		break;
5035 	case BPF_LINK_CREATE:
5036 		err = link_create(&attr, uattr);
5037 		break;
5038 	case BPF_LINK_UPDATE:
5039 		err = link_update(&attr);
5040 		break;
5041 	case BPF_LINK_GET_FD_BY_ID:
5042 		err = bpf_link_get_fd_by_id(&attr);
5043 		break;
5044 	case BPF_LINK_GET_NEXT_ID:
5045 		err = bpf_obj_get_next_id(&attr, uattr.user,
5046 					  &link_idr, &link_idr_lock);
5047 		break;
5048 	case BPF_ENABLE_STATS:
5049 		err = bpf_enable_stats(&attr);
5050 		break;
5051 	case BPF_ITER_CREATE:
5052 		err = bpf_iter_create(&attr);
5053 		break;
5054 	case BPF_LINK_DETACH:
5055 		err = link_detach(&attr);
5056 		break;
5057 	case BPF_PROG_BIND_MAP:
5058 		err = bpf_prog_bind_map(&attr);
5059 		break;
5060 	default:
5061 		err = -EINVAL;
5062 		break;
5063 	}
5064 
5065 	return err;
5066 }
5067 
5068 SYSCALL_DEFINE3(bpf, int, cmd, union bpf_attr __user *, uattr, unsigned int, size)
5069 {
5070 	return __sys_bpf(cmd, USER_BPFPTR(uattr), size);
5071 }
5072 
5073 static bool syscall_prog_is_valid_access(int off, int size,
5074 					 enum bpf_access_type type,
5075 					 const struct bpf_prog *prog,
5076 					 struct bpf_insn_access_aux *info)
5077 {
5078 	if (off < 0 || off >= U16_MAX)
5079 		return false;
5080 	if (off % size != 0)
5081 		return false;
5082 	return true;
5083 }
5084 
5085 BPF_CALL_3(bpf_sys_bpf, int, cmd, union bpf_attr *, attr, u32, attr_size)
5086 {
5087 	switch (cmd) {
5088 	case BPF_MAP_CREATE:
5089 	case BPF_MAP_DELETE_ELEM:
5090 	case BPF_MAP_UPDATE_ELEM:
5091 	case BPF_MAP_FREEZE:
5092 	case BPF_MAP_GET_FD_BY_ID:
5093 	case BPF_PROG_LOAD:
5094 	case BPF_BTF_LOAD:
5095 	case BPF_LINK_CREATE:
5096 	case BPF_RAW_TRACEPOINT_OPEN:
5097 		break;
5098 	default:
5099 		return -EINVAL;
5100 	}
5101 	return __sys_bpf(cmd, KERNEL_BPFPTR(attr), attr_size);
5102 }
5103 
5104 
5105 /* To shut up -Wmissing-prototypes.
5106  * This function is used by the kernel light skeleton
5107  * to load bpf programs when modules are loaded or during kernel boot.
5108  * See tools/lib/bpf/skel_internal.h
5109  */
5110 int kern_sys_bpf(int cmd, union bpf_attr *attr, unsigned int size);
5111 
5112 int kern_sys_bpf(int cmd, union bpf_attr *attr, unsigned int size)
5113 {
5114 	struct bpf_prog * __maybe_unused prog;
5115 	struct bpf_tramp_run_ctx __maybe_unused run_ctx;
5116 
5117 	switch (cmd) {
5118 #ifdef CONFIG_BPF_JIT /* __bpf_prog_enter_sleepable used by trampoline and JIT */
5119 	case BPF_PROG_TEST_RUN:
5120 		if (attr->test.data_in || attr->test.data_out ||
5121 		    attr->test.ctx_out || attr->test.duration ||
5122 		    attr->test.repeat || attr->test.flags)
5123 			return -EINVAL;
5124 
5125 		prog = bpf_prog_get_type(attr->test.prog_fd, BPF_PROG_TYPE_SYSCALL);
5126 		if (IS_ERR(prog))
5127 			return PTR_ERR(prog);
5128 
5129 		if (attr->test.ctx_size_in < prog->aux->max_ctx_offset ||
5130 		    attr->test.ctx_size_in > U16_MAX) {
5131 			bpf_prog_put(prog);
5132 			return -EINVAL;
5133 		}
5134 
5135 		run_ctx.bpf_cookie = 0;
5136 		run_ctx.saved_run_ctx = NULL;
5137 		if (!__bpf_prog_enter_sleepable_recur(prog, &run_ctx)) {
5138 			/* recursion detected */
5139 			bpf_prog_put(prog);
5140 			return -EBUSY;
5141 		}
5142 		attr->test.retval = bpf_prog_run(prog, (void *) (long) attr->test.ctx_in);
5143 		__bpf_prog_exit_sleepable_recur(prog, 0 /* bpf_prog_run does runtime stats */,
5144 						&run_ctx);
5145 		bpf_prog_put(prog);
5146 		return 0;
5147 #endif
5148 	default:
5149 		return ____bpf_sys_bpf(cmd, attr, size);
5150 	}
5151 }
5152 EXPORT_SYMBOL(kern_sys_bpf);
5153 
5154 static const struct bpf_func_proto bpf_sys_bpf_proto = {
5155 	.func		= bpf_sys_bpf,
5156 	.gpl_only	= false,
5157 	.ret_type	= RET_INTEGER,
5158 	.arg1_type	= ARG_ANYTHING,
5159 	.arg2_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
5160 	.arg3_type	= ARG_CONST_SIZE,
5161 };
5162 
5163 const struct bpf_func_proto * __weak
5164 tracing_prog_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
5165 {
5166 	return bpf_base_func_proto(func_id);
5167 }
5168 
5169 BPF_CALL_1(bpf_sys_close, u32, fd)
5170 {
5171 	/* When bpf program calls this helper there should not be
5172 	 * an fdget() without matching completed fdput().
5173 	 * This helper is allowed in the following callchain only:
5174 	 * sys_bpf->prog_test_run->bpf_prog->bpf_sys_close
5175 	 */
5176 	return close_fd(fd);
5177 }
5178 
5179 static const struct bpf_func_proto bpf_sys_close_proto = {
5180 	.func		= bpf_sys_close,
5181 	.gpl_only	= false,
5182 	.ret_type	= RET_INTEGER,
5183 	.arg1_type	= ARG_ANYTHING,
5184 };
5185 
5186 BPF_CALL_4(bpf_kallsyms_lookup_name, const char *, name, int, name_sz, int, flags, u64 *, res)
5187 {
5188 	if (flags)
5189 		return -EINVAL;
5190 
5191 	if (name_sz <= 1 || name[name_sz - 1])
5192 		return -EINVAL;
5193 
5194 	if (!bpf_dump_raw_ok(current_cred()))
5195 		return -EPERM;
5196 
5197 	*res = kallsyms_lookup_name(name);
5198 	return *res ? 0 : -ENOENT;
5199 }
5200 
5201 static const struct bpf_func_proto bpf_kallsyms_lookup_name_proto = {
5202 	.func		= bpf_kallsyms_lookup_name,
5203 	.gpl_only	= false,
5204 	.ret_type	= RET_INTEGER,
5205 	.arg1_type	= ARG_PTR_TO_MEM,
5206 	.arg2_type	= ARG_CONST_SIZE_OR_ZERO,
5207 	.arg3_type	= ARG_ANYTHING,
5208 	.arg4_type	= ARG_PTR_TO_LONG,
5209 };
5210 
5211 static const struct bpf_func_proto *
5212 syscall_prog_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
5213 {
5214 	switch (func_id) {
5215 	case BPF_FUNC_sys_bpf:
5216 		return !perfmon_capable() ? NULL : &bpf_sys_bpf_proto;
5217 	case BPF_FUNC_btf_find_by_name_kind:
5218 		return &bpf_btf_find_by_name_kind_proto;
5219 	case BPF_FUNC_sys_close:
5220 		return &bpf_sys_close_proto;
5221 	case BPF_FUNC_kallsyms_lookup_name:
5222 		return &bpf_kallsyms_lookup_name_proto;
5223 	default:
5224 		return tracing_prog_func_proto(func_id, prog);
5225 	}
5226 }
5227 
5228 const struct bpf_verifier_ops bpf_syscall_verifier_ops = {
5229 	.get_func_proto  = syscall_prog_func_proto,
5230 	.is_valid_access = syscall_prog_is_valid_access,
5231 };
5232 
5233 const struct bpf_prog_ops bpf_syscall_prog_ops = {
5234 	.test_run = bpf_prog_test_run_syscall,
5235 };
5236 
5237 #ifdef CONFIG_SYSCTL
5238 static int bpf_stats_handler(struct ctl_table *table, int write,
5239 			     void *buffer, size_t *lenp, loff_t *ppos)
5240 {
5241 	struct static_key *key = (struct static_key *)table->data;
5242 	static int saved_val;
5243 	int val, ret;
5244 	struct ctl_table tmp = {
5245 		.data   = &val,
5246 		.maxlen = sizeof(val),
5247 		.mode   = table->mode,
5248 		.extra1 = SYSCTL_ZERO,
5249 		.extra2 = SYSCTL_ONE,
5250 	};
5251 
5252 	if (write && !capable(CAP_SYS_ADMIN))
5253 		return -EPERM;
5254 
5255 	mutex_lock(&bpf_stats_enabled_mutex);
5256 	val = saved_val;
5257 	ret = proc_dointvec_minmax(&tmp, write, buffer, lenp, ppos);
5258 	if (write && !ret && val != saved_val) {
5259 		if (val)
5260 			static_key_slow_inc(key);
5261 		else
5262 			static_key_slow_dec(key);
5263 		saved_val = val;
5264 	}
5265 	mutex_unlock(&bpf_stats_enabled_mutex);
5266 	return ret;
5267 }
5268 
5269 void __weak unpriv_ebpf_notify(int new_state)
5270 {
5271 }
5272 
5273 static int bpf_unpriv_handler(struct ctl_table *table, int write,
5274 			      void *buffer, size_t *lenp, loff_t *ppos)
5275 {
5276 	int ret, unpriv_enable = *(int *)table->data;
5277 	bool locked_state = unpriv_enable == 1;
5278 	struct ctl_table tmp = *table;
5279 
5280 	if (write && !capable(CAP_SYS_ADMIN))
5281 		return -EPERM;
5282 
5283 	tmp.data = &unpriv_enable;
5284 	ret = proc_dointvec_minmax(&tmp, write, buffer, lenp, ppos);
5285 	if (write && !ret) {
5286 		if (locked_state && unpriv_enable != 1)
5287 			return -EPERM;
5288 		*(int *)table->data = unpriv_enable;
5289 	}
5290 
5291 	unpriv_ebpf_notify(unpriv_enable);
5292 
5293 	return ret;
5294 }
5295 
5296 static struct ctl_table bpf_syscall_table[] = {
5297 	{
5298 		.procname	= "unprivileged_bpf_disabled",
5299 		.data		= &sysctl_unprivileged_bpf_disabled,
5300 		.maxlen		= sizeof(sysctl_unprivileged_bpf_disabled),
5301 		.mode		= 0644,
5302 		.proc_handler	= bpf_unpriv_handler,
5303 		.extra1		= SYSCTL_ZERO,
5304 		.extra2		= SYSCTL_TWO,
5305 	},
5306 	{
5307 		.procname	= "bpf_stats_enabled",
5308 		.data		= &bpf_stats_enabled_key.key,
5309 		.maxlen		= sizeof(bpf_stats_enabled_key),
5310 		.mode		= 0644,
5311 		.proc_handler	= bpf_stats_handler,
5312 	},
5313 	{ }
5314 };
5315 
5316 static int __init bpf_syscall_sysctl_init(void)
5317 {
5318 	register_sysctl_init("kernel", bpf_syscall_table);
5319 	return 0;
5320 }
5321 late_initcall(bpf_syscall_sysctl_init);
5322 #endif /* CONFIG_SYSCTL */
5323