xref: /linux/kernel/bpf/syscall.c (revision c76fef7dcd9372e3476d4df5e0a72ed5919a814b)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
3  */
4 #include <crypto/sha2.h>
5 #include <linux/bpf.h>
6 #include <linux/bpf-cgroup.h>
7 #include <linux/bpf_trace.h>
8 #include <linux/bpf_lirc.h>
9 #include <linux/bpf_verifier.h>
10 #include <linux/bsearch.h>
11 #include <linux/btf.h>
12 #include <linux/hex.h>
13 #include <linux/syscalls.h>
14 #include <linux/slab.h>
15 #include <linux/sched/signal.h>
16 #include <linux/vmalloc.h>
17 #include <linux/mmzone.h>
18 #include <linux/anon_inodes.h>
19 #include <linux/fdtable.h>
20 #include <linux/file.h>
21 #include <linux/fs.h>
22 #include <linux/license.h>
23 #include <linux/filter.h>
24 #include <linux/kernel.h>
25 #include <linux/idr.h>
26 #include <linux/cred.h>
27 #include <linux/timekeeping.h>
28 #include <linux/ctype.h>
29 #include <linux/nospec.h>
30 #include <linux/audit.h>
31 #include <uapi/linux/btf.h>
32 #include <linux/pgtable.h>
33 #include <linux/bpf_lsm.h>
34 #include <linux/poll.h>
35 #include <linux/sort.h>
36 #include <linux/bpf-netns.h>
37 #include <linux/rcupdate_trace.h>
38 #include <linux/memcontrol.h>
39 #include <linux/trace_events.h>
40 #include <linux/tracepoint.h>
41 #include <linux/overflow.h>
42 #include <linux/cookie.h>
43 #include <linux/verification.h>
44 
45 #include <net/netfilter/nf_bpf_link.h>
46 #include <net/netkit.h>
47 #include <net/tcx.h>
48 
49 #define IS_FD_ARRAY(map) ((map)->map_type == BPF_MAP_TYPE_PERF_EVENT_ARRAY || \
50 			  (map)->map_type == BPF_MAP_TYPE_CGROUP_ARRAY || \
51 			  (map)->map_type == BPF_MAP_TYPE_ARRAY_OF_MAPS)
52 #define IS_FD_PROG_ARRAY(map) ((map)->map_type == BPF_MAP_TYPE_PROG_ARRAY)
53 #define IS_FD_HASH(map) ((map)->map_type == BPF_MAP_TYPE_HASH_OF_MAPS)
54 #define IS_FD_MAP(map) (IS_FD_ARRAY(map) || IS_FD_PROG_ARRAY(map) || \
55 			IS_FD_HASH(map))
56 
57 #define BPF_OBJ_FLAG_MASK   (BPF_F_RDONLY | BPF_F_WRONLY)
58 
59 DEFINE_PER_CPU(int, bpf_prog_active);
60 DEFINE_COOKIE(bpf_map_cookie);
61 static DEFINE_IDR(prog_idr);
62 static DEFINE_SPINLOCK(prog_idr_lock);
63 static DEFINE_IDR(map_idr);
64 static DEFINE_SPINLOCK(map_idr_lock);
65 static DEFINE_IDR(link_idr);
66 static DEFINE_SPINLOCK(link_idr_lock);
67 
68 int sysctl_unprivileged_bpf_disabled __read_mostly =
69 	IS_BUILTIN(CONFIG_BPF_UNPRIV_DEFAULT_OFF) ? 2 : 0;
70 
71 static const struct bpf_map_ops * const bpf_map_types[] = {
72 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type)
73 #define BPF_MAP_TYPE(_id, _ops) \
74 	[_id] = &_ops,
75 #define BPF_LINK_TYPE(_id, _name)
76 #include <linux/bpf_types.h>
77 #undef BPF_PROG_TYPE
78 #undef BPF_MAP_TYPE
79 #undef BPF_LINK_TYPE
80 };
81 
82 /*
83  * If we're handed a bigger struct than we know of, ensure all the unknown bits
84  * are 0 - i.e. new user-space does not rely on any kernel feature extensions
85  * we don't know about yet.
86  *
87  * There is a ToCToU between this function call and the following
88  * copy_from_user() call. However, this is not a concern since this function is
89  * meant to be a future-proofing of bits.
90  */
91 int bpf_check_uarg_tail_zero(bpfptr_t uaddr,
92 			     size_t expected_size,
93 			     size_t actual_size)
94 {
95 	int res;
96 
97 	if (unlikely(actual_size > PAGE_SIZE))	/* silly large */
98 		return -E2BIG;
99 
100 	if (actual_size <= expected_size)
101 		return 0;
102 
103 	if (uaddr.is_kernel)
104 		res = memchr_inv(uaddr.kernel + expected_size, 0,
105 				 actual_size - expected_size) == NULL;
106 	else
107 		res = check_zeroed_user(uaddr.user + expected_size,
108 					actual_size - expected_size);
109 	if (res < 0)
110 		return res;
111 	return res ? 0 : -E2BIG;
112 }
113 
114 const struct bpf_map_ops bpf_map_offload_ops = {
115 	.map_meta_equal = bpf_map_meta_equal,
116 	.map_alloc = bpf_map_offload_map_alloc,
117 	.map_free = bpf_map_offload_map_free,
118 	.map_check_btf = map_check_no_btf,
119 	.map_mem_usage = bpf_map_offload_map_mem_usage,
120 };
121 
122 static void bpf_map_write_active_inc(struct bpf_map *map)
123 {
124 	atomic64_inc(&map->writecnt);
125 }
126 
127 static void bpf_map_write_active_dec(struct bpf_map *map)
128 {
129 	atomic64_dec(&map->writecnt);
130 }
131 
132 bool bpf_map_write_active(const struct bpf_map *map)
133 {
134 	return atomic64_read(&map->writecnt) != 0;
135 }
136 
137 static u32 bpf_map_value_size(const struct bpf_map *map, u64 flags)
138 {
139 	if (flags & (BPF_F_CPU | BPF_F_ALL_CPUS))
140 		return map->value_size;
141 	else if (map->map_type == BPF_MAP_TYPE_PERCPU_HASH ||
142 		 map->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH ||
143 		 map->map_type == BPF_MAP_TYPE_PERCPU_ARRAY ||
144 		 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
145 		return round_up(map->value_size, 8) * num_possible_cpus();
146 	else if (IS_FD_MAP(map))
147 		return sizeof(u32);
148 	else
149 		return  map->value_size;
150 }
151 
152 static void maybe_wait_bpf_programs(struct bpf_map *map)
153 {
154 	/* Wait for any running non-sleepable BPF programs to complete so that
155 	 * userspace, when we return to it, knows that all non-sleepable
156 	 * programs that could be running use the new map value. For sleepable
157 	 * BPF programs, synchronize_rcu_tasks_trace() should be used to wait
158 	 * for the completions of these programs, but considering the waiting
159 	 * time can be very long and userspace may think it will hang forever,
160 	 * so don't handle sleepable BPF programs now.
161 	 */
162 	if (map->map_type == BPF_MAP_TYPE_HASH_OF_MAPS ||
163 	    map->map_type == BPF_MAP_TYPE_ARRAY_OF_MAPS)
164 		synchronize_rcu_expedited();
165 }
166 
167 static void unpin_uptr_kaddr(void *kaddr)
168 {
169 	if (kaddr)
170 		unpin_user_page(virt_to_page(kaddr));
171 }
172 
173 static void __bpf_obj_unpin_uptrs(struct btf_record *rec, u32 cnt, void *obj)
174 {
175 	const struct btf_field *field;
176 	void **uptr_addr;
177 	int i;
178 
179 	for (i = 0, field = rec->fields; i < cnt; i++, field++) {
180 		if (field->type != BPF_UPTR)
181 			continue;
182 
183 		uptr_addr = obj + field->offset;
184 		unpin_uptr_kaddr(*uptr_addr);
185 	}
186 }
187 
188 static void bpf_obj_unpin_uptrs(struct btf_record *rec, void *obj)
189 {
190 	if (!btf_record_has_field(rec, BPF_UPTR))
191 		return;
192 
193 	__bpf_obj_unpin_uptrs(rec, rec->cnt, obj);
194 }
195 
196 static int bpf_obj_pin_uptrs(struct btf_record *rec, void *obj)
197 {
198 	const struct btf_field *field;
199 	const struct btf_type *t;
200 	unsigned long start, end;
201 	struct page *page;
202 	void **uptr_addr;
203 	int i, err;
204 
205 	if (!btf_record_has_field(rec, BPF_UPTR))
206 		return 0;
207 
208 	for (i = 0, field = rec->fields; i < rec->cnt; i++, field++) {
209 		if (field->type != BPF_UPTR)
210 			continue;
211 
212 		uptr_addr = obj + field->offset;
213 		start = *(unsigned long *)uptr_addr;
214 		if (!start)
215 			continue;
216 
217 		t = btf_type_by_id(field->kptr.btf, field->kptr.btf_id);
218 		/* t->size was checked for zero before */
219 		if (check_add_overflow(start, t->size - 1, &end)) {
220 			err = -EFAULT;
221 			goto unpin_all;
222 		}
223 
224 		/* The uptr's struct cannot span across two pages */
225 		if ((start & PAGE_MASK) != (end & PAGE_MASK)) {
226 			err = -EOPNOTSUPP;
227 			goto unpin_all;
228 		}
229 
230 		err = pin_user_pages_fast(start, 1, FOLL_LONGTERM | FOLL_WRITE, &page);
231 		if (err != 1)
232 			goto unpin_all;
233 
234 		if (PageHighMem(page)) {
235 			err = -EOPNOTSUPP;
236 			unpin_user_page(page);
237 			goto unpin_all;
238 		}
239 
240 		*uptr_addr = page_address(page) + offset_in_page(start);
241 	}
242 
243 	return 0;
244 
245 unpin_all:
246 	__bpf_obj_unpin_uptrs(rec, i, obj);
247 	return err;
248 }
249 
250 static int bpf_map_update_value(struct bpf_map *map, struct file *map_file,
251 				void *key, void *value, __u64 flags)
252 {
253 	int err;
254 
255 	/* Need to create a kthread, thus must support schedule */
256 	if (bpf_map_is_offloaded(map)) {
257 		return bpf_map_offload_update_elem(map, key, value, flags);
258 	} else if (map->map_type == BPF_MAP_TYPE_CPUMAP ||
259 		   map->map_type == BPF_MAP_TYPE_ARENA ||
260 		   map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
261 		return map->ops->map_update_elem(map, key, value, flags);
262 	} else if (map->map_type == BPF_MAP_TYPE_SOCKHASH ||
263 		   map->map_type == BPF_MAP_TYPE_SOCKMAP) {
264 		return sock_map_update_elem_sys(map, key, value, flags);
265 	} else if (IS_FD_PROG_ARRAY(map)) {
266 		return bpf_fd_array_map_update_elem(map, map_file, key, value,
267 						    flags);
268 	}
269 
270 	bpf_disable_instrumentation();
271 	if (map->map_type == BPF_MAP_TYPE_PERCPU_HASH ||
272 	    map->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH) {
273 		err = bpf_percpu_hash_update(map, key, value, flags);
274 	} else if (map->map_type == BPF_MAP_TYPE_PERCPU_ARRAY) {
275 		err = bpf_percpu_array_update(map, key, value, flags);
276 	} else if (map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE) {
277 		err = bpf_percpu_cgroup_storage_update(map, key, value,
278 						       flags);
279 	} else if (IS_FD_ARRAY(map)) {
280 		err = bpf_fd_array_map_update_elem(map, map_file, key, value,
281 						   flags);
282 	} else if (map->map_type == BPF_MAP_TYPE_HASH_OF_MAPS) {
283 		err = bpf_fd_htab_map_update_elem(map, map_file, key, value,
284 						  flags);
285 	} else if (map->map_type == BPF_MAP_TYPE_REUSEPORT_SOCKARRAY) {
286 		/* rcu_read_lock() is not needed */
287 		err = bpf_fd_reuseport_array_update_elem(map, key, value,
288 							 flags);
289 	} else if (map->map_type == BPF_MAP_TYPE_QUEUE ||
290 		   map->map_type == BPF_MAP_TYPE_STACK ||
291 		   map->map_type == BPF_MAP_TYPE_BLOOM_FILTER) {
292 		err = map->ops->map_push_elem(map, value, flags);
293 	} else {
294 		err = bpf_obj_pin_uptrs(map->record, value);
295 		if (!err) {
296 			rcu_read_lock();
297 			err = map->ops->map_update_elem(map, key, value, flags);
298 			rcu_read_unlock();
299 			if (err)
300 				bpf_obj_unpin_uptrs(map->record, value);
301 		}
302 	}
303 	bpf_enable_instrumentation();
304 
305 	return err;
306 }
307 
308 static int bpf_map_copy_value(struct bpf_map *map, void *key, void *value,
309 			      __u64 flags)
310 {
311 	void *ptr;
312 	int err;
313 
314 	if (bpf_map_is_offloaded(map))
315 		return bpf_map_offload_lookup_elem(map, key, value);
316 
317 	bpf_disable_instrumentation();
318 	if (map->map_type == BPF_MAP_TYPE_PERCPU_HASH ||
319 	    map->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH) {
320 		err = bpf_percpu_hash_copy(map, key, value, flags);
321 	} else if (map->map_type == BPF_MAP_TYPE_PERCPU_ARRAY) {
322 		err = bpf_percpu_array_copy(map, key, value, flags);
323 	} else if (map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE) {
324 		err = bpf_percpu_cgroup_storage_copy(map, key, value, flags);
325 	} else if (map->map_type == BPF_MAP_TYPE_STACK_TRACE) {
326 		err = bpf_stackmap_extract(map, key, value, false);
327 	} else if (IS_FD_ARRAY(map) || IS_FD_PROG_ARRAY(map)) {
328 		err = bpf_fd_array_map_lookup_elem(map, key, value);
329 	} else if (IS_FD_HASH(map)) {
330 		err = bpf_fd_htab_map_lookup_elem(map, key, value);
331 	} else if (map->map_type == BPF_MAP_TYPE_REUSEPORT_SOCKARRAY) {
332 		err = bpf_fd_reuseport_array_lookup_elem(map, key, value);
333 	} else if (map->map_type == BPF_MAP_TYPE_QUEUE ||
334 		   map->map_type == BPF_MAP_TYPE_STACK ||
335 		   map->map_type == BPF_MAP_TYPE_BLOOM_FILTER) {
336 		err = map->ops->map_peek_elem(map, value);
337 	} else if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
338 		/* struct_ops map requires directly updating "value" */
339 		err = bpf_struct_ops_map_sys_lookup_elem(map, key, value);
340 	} else {
341 		rcu_read_lock();
342 		if (map->ops->map_lookup_elem_sys_only)
343 			ptr = map->ops->map_lookup_elem_sys_only(map, key);
344 		else
345 			ptr = map->ops->map_lookup_elem(map, key);
346 		if (IS_ERR(ptr)) {
347 			err = PTR_ERR(ptr);
348 		} else if (!ptr) {
349 			err = -ENOENT;
350 		} else {
351 			err = 0;
352 			if (flags & BPF_F_LOCK)
353 				/* lock 'ptr' and copy everything but lock */
354 				copy_map_value_locked(map, value, ptr, true);
355 			else
356 				copy_map_value(map, value, ptr);
357 			/* mask lock and timer, since value wasn't zero inited */
358 			check_and_init_map_value(map, value);
359 		}
360 		rcu_read_unlock();
361 	}
362 
363 	bpf_enable_instrumentation();
364 
365 	return err;
366 }
367 
368 /* Please, do not use this function outside from the map creation path
369  * (e.g. in map update path) without taking care of setting the active
370  * memory cgroup (see at bpf_map_kmalloc_node() for example).
371  */
372 static void *__bpf_map_area_alloc(u64 size, int numa_node, bool mmapable)
373 {
374 	/* We really just want to fail instead of triggering OOM killer
375 	 * under memory pressure, therefore we set __GFP_NORETRY to kmalloc,
376 	 * which is used for lower order allocation requests.
377 	 *
378 	 * It has been observed that higher order allocation requests done by
379 	 * vmalloc with __GFP_NORETRY being set might fail due to not trying
380 	 * to reclaim memory from the page cache, thus we set
381 	 * __GFP_RETRY_MAYFAIL to avoid such situations.
382 	 */
383 
384 	gfp_t gfp = bpf_memcg_flags(__GFP_NOWARN | __GFP_ZERO);
385 	unsigned int flags = 0;
386 	unsigned long align = 1;
387 	void *area;
388 
389 	if (size >= SIZE_MAX)
390 		return NULL;
391 
392 	/* kmalloc()'ed memory can't be mmap()'ed */
393 	if (mmapable) {
394 		BUG_ON(!PAGE_ALIGNED(size));
395 		align = SHMLBA;
396 		flags = VM_USERMAP;
397 	} else if (size <= (PAGE_SIZE << PAGE_ALLOC_COSTLY_ORDER)) {
398 		area = kmalloc_node(size, gfp | GFP_USER | __GFP_NORETRY,
399 				    numa_node);
400 		if (area != NULL)
401 			return area;
402 	}
403 
404 	return __vmalloc_node_range(size, align, VMALLOC_START, VMALLOC_END,
405 			gfp | GFP_KERNEL | __GFP_RETRY_MAYFAIL, PAGE_KERNEL,
406 			flags, numa_node, __builtin_return_address(0));
407 }
408 
409 void *bpf_map_area_alloc(u64 size, int numa_node)
410 {
411 	return __bpf_map_area_alloc(size, numa_node, false);
412 }
413 
414 void *bpf_map_area_mmapable_alloc(u64 size, int numa_node)
415 {
416 	return __bpf_map_area_alloc(size, numa_node, true);
417 }
418 
419 void bpf_map_area_free(void *area)
420 {
421 	kvfree(area);
422 }
423 
424 static u32 bpf_map_flags_retain_permanent(u32 flags)
425 {
426 	/* Some map creation flags are not tied to the map object but
427 	 * rather to the map fd instead, so they have no meaning upon
428 	 * map object inspection since multiple file descriptors with
429 	 * different (access) properties can exist here. Thus, given
430 	 * this has zero meaning for the map itself, lets clear these
431 	 * from here.
432 	 */
433 	return flags & ~(BPF_F_RDONLY | BPF_F_WRONLY);
434 }
435 
436 void bpf_map_init_from_attr(struct bpf_map *map, union bpf_attr *attr)
437 {
438 	map->map_type = attr->map_type;
439 	map->key_size = attr->key_size;
440 	map->value_size = attr->value_size;
441 	map->max_entries = attr->max_entries;
442 	map->map_flags = bpf_map_flags_retain_permanent(attr->map_flags);
443 	map->numa_node = bpf_map_attr_numa_node(attr);
444 	map->map_extra = attr->map_extra;
445 }
446 
447 static int bpf_map_alloc_id(struct bpf_map *map)
448 {
449 	int id;
450 
451 	idr_preload(GFP_KERNEL);
452 	spin_lock_bh(&map_idr_lock);
453 	id = idr_alloc_cyclic(&map_idr, map, 1, INT_MAX, GFP_ATOMIC);
454 	if (id > 0)
455 		map->id = id;
456 	spin_unlock_bh(&map_idr_lock);
457 	idr_preload_end();
458 
459 	if (WARN_ON_ONCE(!id))
460 		return -ENOSPC;
461 
462 	return id > 0 ? 0 : id;
463 }
464 
465 void bpf_map_free_id(struct bpf_map *map)
466 {
467 	unsigned long flags;
468 
469 	/* Offloaded maps are removed from the IDR store when their device
470 	 * disappears - even if someone holds an fd to them they are unusable,
471 	 * the memory is gone, all ops will fail; they are simply waiting for
472 	 * refcnt to drop to be freed.
473 	 */
474 	if (!map->id)
475 		return;
476 
477 	spin_lock_irqsave(&map_idr_lock, flags);
478 
479 	idr_remove(&map_idr, map->id);
480 	map->id = 0;
481 
482 	spin_unlock_irqrestore(&map_idr_lock, flags);
483 }
484 
485 #ifdef CONFIG_MEMCG
486 static void bpf_map_save_memcg(struct bpf_map *map)
487 {
488 	/* Currently if a map is created by a process belonging to the root
489 	 * memory cgroup, get_obj_cgroup_from_current() will return NULL.
490 	 * So we have to check map->objcg for being NULL each time it's
491 	 * being used.
492 	 */
493 	if (memcg_bpf_enabled())
494 		map->objcg = get_obj_cgroup_from_current();
495 }
496 
497 static void bpf_map_release_memcg(struct bpf_map *map)
498 {
499 	if (map->objcg)
500 		obj_cgroup_put(map->objcg);
501 }
502 
503 static struct mem_cgroup *bpf_map_get_memcg(const struct bpf_map *map)
504 {
505 	if (map->objcg)
506 		return get_mem_cgroup_from_objcg(map->objcg);
507 
508 	return root_mem_cgroup;
509 }
510 
511 void bpf_map_memcg_enter(const struct bpf_map *map, struct mem_cgroup **old_memcg,
512 			 struct mem_cgroup **new_memcg)
513 {
514 	*new_memcg = bpf_map_get_memcg(map);
515 	*old_memcg = set_active_memcg(*new_memcg);
516 }
517 
518 void bpf_map_memcg_exit(struct mem_cgroup *old_memcg,
519 			struct mem_cgroup *new_memcg)
520 {
521 	set_active_memcg(old_memcg);
522 	mem_cgroup_put(new_memcg);
523 }
524 
525 void *bpf_map_kmalloc_node(const struct bpf_map *map, size_t size, gfp_t flags,
526 			   int node)
527 {
528 	struct mem_cgroup *memcg, *old_memcg;
529 	void *ptr;
530 
531 	bpf_map_memcg_enter(map, &old_memcg, &memcg);
532 	ptr = kmalloc_node(size, flags | __GFP_ACCOUNT, node);
533 	bpf_map_memcg_exit(old_memcg, memcg);
534 
535 	return ptr;
536 }
537 
538 void *bpf_map_kmalloc_nolock(const struct bpf_map *map, size_t size, gfp_t flags,
539 			     int node)
540 {
541 	struct mem_cgroup *memcg, *old_memcg;
542 	void *ptr;
543 
544 	bpf_map_memcg_enter(map, &old_memcg, &memcg);
545 	ptr = kmalloc_nolock(size, flags | __GFP_ACCOUNT, node);
546 	bpf_map_memcg_exit(old_memcg, memcg);
547 
548 	return ptr;
549 }
550 
551 void *bpf_map_kzalloc(const struct bpf_map *map, size_t size, gfp_t flags)
552 {
553 	struct mem_cgroup *memcg, *old_memcg;
554 	void *ptr;
555 
556 	bpf_map_memcg_enter(map, &old_memcg, &memcg);
557 	ptr = kzalloc(size, flags | __GFP_ACCOUNT);
558 	bpf_map_memcg_exit(old_memcg, memcg);
559 
560 	return ptr;
561 }
562 
563 void *bpf_map_kvcalloc(struct bpf_map *map, size_t n, size_t size,
564 		       gfp_t flags)
565 {
566 	struct mem_cgroup *memcg, *old_memcg;
567 	void *ptr;
568 
569 	bpf_map_memcg_enter(map, &old_memcg, &memcg);
570 	ptr = kvcalloc(n, size, flags | __GFP_ACCOUNT);
571 	bpf_map_memcg_exit(old_memcg, memcg);
572 
573 	return ptr;
574 }
575 
576 void __percpu *bpf_map_alloc_percpu(const struct bpf_map *map, size_t size,
577 				    size_t align, gfp_t flags)
578 {
579 	struct mem_cgroup *memcg, *old_memcg;
580 	void __percpu *ptr;
581 
582 	bpf_map_memcg_enter(map, &old_memcg, &memcg);
583 	ptr = __alloc_percpu_gfp(size, align, flags | __GFP_ACCOUNT);
584 	bpf_map_memcg_exit(old_memcg, memcg);
585 
586 	return ptr;
587 }
588 
589 #else
590 static void bpf_map_save_memcg(struct bpf_map *map)
591 {
592 }
593 
594 static void bpf_map_release_memcg(struct bpf_map *map)
595 {
596 }
597 #endif
598 
599 static bool can_alloc_pages(void)
600 {
601 	return preempt_count() == 0 && !irqs_disabled() &&
602 		!IS_ENABLED(CONFIG_PREEMPT_RT);
603 }
604 
605 static struct page *__bpf_alloc_page(int nid)
606 {
607 	if (!can_alloc_pages())
608 		return alloc_pages_nolock(__GFP_ACCOUNT, nid, 0);
609 
610 	return alloc_pages_node(nid,
611 				GFP_KERNEL | __GFP_ZERO | __GFP_ACCOUNT
612 				| __GFP_NOWARN,
613 				0);
614 }
615 
616 int bpf_map_alloc_pages(const struct bpf_map *map, int nid,
617 			unsigned long nr_pages, struct page **pages)
618 {
619 	unsigned long i, j;
620 	struct page *pg;
621 	int ret = 0;
622 
623 	for (i = 0; i < nr_pages; i++) {
624 		pg = __bpf_alloc_page(nid);
625 
626 		if (pg) {
627 			pages[i] = pg;
628 			continue;
629 		}
630 		for (j = 0; j < i; j++)
631 			free_pages_nolock(pages[j], 0);
632 		ret = -ENOMEM;
633 		break;
634 	}
635 
636 	return ret;
637 }
638 
639 
640 static int btf_field_cmp(const void *a, const void *b)
641 {
642 	const struct btf_field *f1 = a, *f2 = b;
643 
644 	if (f1->offset < f2->offset)
645 		return -1;
646 	else if (f1->offset > f2->offset)
647 		return 1;
648 	return 0;
649 }
650 
651 struct btf_field *btf_record_find(const struct btf_record *rec, u32 offset,
652 				  u32 field_mask)
653 {
654 	struct btf_field *field;
655 
656 	if (IS_ERR_OR_NULL(rec) || !(rec->field_mask & field_mask))
657 		return NULL;
658 	field = bsearch(&offset, rec->fields, rec->cnt, sizeof(rec->fields[0]), btf_field_cmp);
659 	if (!field || !(field->type & field_mask))
660 		return NULL;
661 	return field;
662 }
663 
664 void btf_record_free(struct btf_record *rec)
665 {
666 	int i;
667 
668 	if (IS_ERR_OR_NULL(rec))
669 		return;
670 	for (i = 0; i < rec->cnt; i++) {
671 		switch (rec->fields[i].type) {
672 		case BPF_KPTR_UNREF:
673 		case BPF_KPTR_REF:
674 		case BPF_KPTR_PERCPU:
675 		case BPF_UPTR:
676 			if (rec->fields[i].kptr.module)
677 				module_put(rec->fields[i].kptr.module);
678 			if (btf_is_kernel(rec->fields[i].kptr.btf))
679 				btf_put(rec->fields[i].kptr.btf);
680 			break;
681 		case BPF_LIST_HEAD:
682 		case BPF_LIST_NODE:
683 		case BPF_RB_ROOT:
684 		case BPF_RB_NODE:
685 		case BPF_SPIN_LOCK:
686 		case BPF_RES_SPIN_LOCK:
687 		case BPF_TIMER:
688 		case BPF_REFCOUNT:
689 		case BPF_WORKQUEUE:
690 		case BPF_TASK_WORK:
691 			/* Nothing to release */
692 			break;
693 		default:
694 			WARN_ON_ONCE(1);
695 			continue;
696 		}
697 	}
698 	kfree(rec);
699 }
700 
701 void bpf_map_free_record(struct bpf_map *map)
702 {
703 	btf_record_free(map->record);
704 	map->record = NULL;
705 }
706 
707 struct btf_record *btf_record_dup(const struct btf_record *rec)
708 {
709 	const struct btf_field *fields;
710 	struct btf_record *new_rec;
711 	int ret, size, i;
712 
713 	if (IS_ERR_OR_NULL(rec))
714 		return NULL;
715 	size = struct_size(rec, fields, rec->cnt);
716 	new_rec = kmemdup(rec, size, GFP_KERNEL | __GFP_NOWARN);
717 	if (!new_rec)
718 		return ERR_PTR(-ENOMEM);
719 	/* Do a deep copy of the btf_record */
720 	fields = rec->fields;
721 	new_rec->cnt = 0;
722 	for (i = 0; i < rec->cnt; i++) {
723 		switch (fields[i].type) {
724 		case BPF_KPTR_UNREF:
725 		case BPF_KPTR_REF:
726 		case BPF_KPTR_PERCPU:
727 		case BPF_UPTR:
728 			if (btf_is_kernel(fields[i].kptr.btf))
729 				btf_get(fields[i].kptr.btf);
730 			if (fields[i].kptr.module && !try_module_get(fields[i].kptr.module)) {
731 				ret = -ENXIO;
732 				goto free;
733 			}
734 			break;
735 		case BPF_LIST_HEAD:
736 		case BPF_LIST_NODE:
737 		case BPF_RB_ROOT:
738 		case BPF_RB_NODE:
739 		case BPF_SPIN_LOCK:
740 		case BPF_RES_SPIN_LOCK:
741 		case BPF_TIMER:
742 		case BPF_REFCOUNT:
743 		case BPF_WORKQUEUE:
744 		case BPF_TASK_WORK:
745 			/* Nothing to acquire */
746 			break;
747 		default:
748 			ret = -EFAULT;
749 			WARN_ON_ONCE(1);
750 			goto free;
751 		}
752 		new_rec->cnt++;
753 	}
754 	return new_rec;
755 free:
756 	btf_record_free(new_rec);
757 	return ERR_PTR(ret);
758 }
759 
760 bool btf_record_equal(const struct btf_record *rec_a, const struct btf_record *rec_b)
761 {
762 	bool a_has_fields = !IS_ERR_OR_NULL(rec_a), b_has_fields = !IS_ERR_OR_NULL(rec_b);
763 	int size;
764 
765 	if (!a_has_fields && !b_has_fields)
766 		return true;
767 	if (a_has_fields != b_has_fields)
768 		return false;
769 	if (rec_a->cnt != rec_b->cnt)
770 		return false;
771 	size = struct_size(rec_a, fields, rec_a->cnt);
772 	/* btf_parse_fields uses kzalloc to allocate a btf_record, so unused
773 	 * members are zeroed out. So memcmp is safe to do without worrying
774 	 * about padding/unused fields.
775 	 *
776 	 * While spin_lock, timer, and kptr have no relation to map BTF,
777 	 * list_head metadata is specific to map BTF, the btf and value_rec
778 	 * members in particular. btf is the map BTF, while value_rec points to
779 	 * btf_record in that map BTF.
780 	 *
781 	 * So while by default, we don't rely on the map BTF (which the records
782 	 * were parsed from) matching for both records, which is not backwards
783 	 * compatible, in case list_head is part of it, we implicitly rely on
784 	 * that by way of depending on memcmp succeeding for it.
785 	 */
786 	return !memcmp(rec_a, rec_b, size);
787 }
788 
789 void bpf_obj_free_timer(const struct btf_record *rec, void *obj)
790 {
791 	if (WARN_ON_ONCE(!btf_record_has_field(rec, BPF_TIMER)))
792 		return;
793 	bpf_timer_cancel_and_free(obj + rec->timer_off);
794 }
795 
796 void bpf_obj_free_workqueue(const struct btf_record *rec, void *obj)
797 {
798 	if (WARN_ON_ONCE(!btf_record_has_field(rec, BPF_WORKQUEUE)))
799 		return;
800 	bpf_wq_cancel_and_free(obj + rec->wq_off);
801 }
802 
803 void bpf_obj_free_task_work(const struct btf_record *rec, void *obj)
804 {
805 	if (WARN_ON_ONCE(!btf_record_has_field(rec, BPF_TASK_WORK)))
806 		return;
807 	bpf_task_work_cancel_and_free(obj + rec->task_work_off);
808 }
809 
810 void bpf_obj_free_fields(const struct btf_record *rec, void *obj)
811 {
812 	const struct btf_field *fields;
813 	int i;
814 
815 	if (IS_ERR_OR_NULL(rec))
816 		return;
817 	fields = rec->fields;
818 	for (i = 0; i < rec->cnt; i++) {
819 		struct btf_struct_meta *pointee_struct_meta;
820 		const struct btf_field *field = &fields[i];
821 		void *field_ptr = obj + field->offset;
822 		void *xchgd_field;
823 
824 		switch (fields[i].type) {
825 		case BPF_SPIN_LOCK:
826 		case BPF_RES_SPIN_LOCK:
827 			break;
828 		case BPF_TIMER:
829 			bpf_timer_cancel_and_free(field_ptr);
830 			break;
831 		case BPF_WORKQUEUE:
832 			bpf_wq_cancel_and_free(field_ptr);
833 			break;
834 		case BPF_TASK_WORK:
835 			bpf_task_work_cancel_and_free(field_ptr);
836 			break;
837 		case BPF_KPTR_UNREF:
838 			WRITE_ONCE(*(u64 *)field_ptr, 0);
839 			break;
840 		case BPF_KPTR_REF:
841 		case BPF_KPTR_PERCPU:
842 			xchgd_field = (void *)xchg((unsigned long *)field_ptr, 0);
843 			if (!xchgd_field)
844 				break;
845 
846 			if (!btf_is_kernel(field->kptr.btf)) {
847 				pointee_struct_meta = btf_find_struct_meta(field->kptr.btf,
848 									   field->kptr.btf_id);
849 				__bpf_obj_drop_impl(xchgd_field, pointee_struct_meta ?
850 								 pointee_struct_meta->record : NULL,
851 								 fields[i].type == BPF_KPTR_PERCPU);
852 			} else {
853 				field->kptr.dtor(xchgd_field);
854 			}
855 			break;
856 		case BPF_UPTR:
857 			/* The caller ensured that no one is using the uptr */
858 			unpin_uptr_kaddr(*(void **)field_ptr);
859 			break;
860 		case BPF_LIST_HEAD:
861 			if (WARN_ON_ONCE(rec->spin_lock_off < 0))
862 				continue;
863 			bpf_list_head_free(field, field_ptr, obj + rec->spin_lock_off);
864 			break;
865 		case BPF_RB_ROOT:
866 			if (WARN_ON_ONCE(rec->spin_lock_off < 0))
867 				continue;
868 			bpf_rb_root_free(field, field_ptr, obj + rec->spin_lock_off);
869 			break;
870 		case BPF_LIST_NODE:
871 		case BPF_RB_NODE:
872 		case BPF_REFCOUNT:
873 			break;
874 		default:
875 			WARN_ON_ONCE(1);
876 			continue;
877 		}
878 	}
879 }
880 
881 static void bpf_map_free(struct bpf_map *map)
882 {
883 	struct btf_record *rec = map->record;
884 	struct btf *btf = map->btf;
885 
886 	/* implementation dependent freeing. Disabling migration to simplify
887 	 * the free of values or special fields allocated from bpf memory
888 	 * allocator.
889 	 */
890 	kfree(map->excl_prog_sha);
891 	migrate_disable();
892 	map->ops->map_free(map);
893 	migrate_enable();
894 
895 	/* Delay freeing of btf_record for maps, as map_free
896 	 * callback usually needs access to them. It is better to do it here
897 	 * than require each callback to do the free itself manually.
898 	 *
899 	 * Note that the btf_record stashed in map->inner_map_meta->record was
900 	 * already freed using the map_free callback for map in map case which
901 	 * eventually calls bpf_map_free_meta, since inner_map_meta is only a
902 	 * template bpf_map struct used during verification.
903 	 */
904 	btf_record_free(rec);
905 	/* Delay freeing of btf for maps, as map_free callback may need
906 	 * struct_meta info which will be freed with btf_put().
907 	 */
908 	btf_put(btf);
909 }
910 
911 /* called from workqueue */
912 static void bpf_map_free_deferred(struct work_struct *work)
913 {
914 	struct bpf_map *map = container_of(work, struct bpf_map, work);
915 
916 	security_bpf_map_free(map);
917 	bpf_map_release_memcg(map);
918 	bpf_map_owner_free(map);
919 	bpf_map_free(map);
920 }
921 
922 static void bpf_map_put_uref(struct bpf_map *map)
923 {
924 	if (atomic64_dec_and_test(&map->usercnt)) {
925 		if (map->ops->map_release_uref)
926 			map->ops->map_release_uref(map);
927 	}
928 }
929 
930 static void bpf_map_free_in_work(struct bpf_map *map)
931 {
932 	INIT_WORK(&map->work, bpf_map_free_deferred);
933 	/* Avoid spawning kworkers, since they all might contend
934 	 * for the same mutex like slab_mutex.
935 	 */
936 	queue_work(system_dfl_wq, &map->work);
937 }
938 
939 static void bpf_map_free_rcu_gp(struct rcu_head *rcu)
940 {
941 	bpf_map_free_in_work(container_of(rcu, struct bpf_map, rcu));
942 }
943 
944 static void bpf_map_free_mult_rcu_gp(struct rcu_head *rcu)
945 {
946 	if (rcu_trace_implies_rcu_gp())
947 		bpf_map_free_rcu_gp(rcu);
948 	else
949 		call_rcu(rcu, bpf_map_free_rcu_gp);
950 }
951 
952 /* decrement map refcnt and schedule it for freeing via workqueue
953  * (underlying map implementation ops->map_free() might sleep)
954  */
955 void bpf_map_put(struct bpf_map *map)
956 {
957 	if (atomic64_dec_and_test(&map->refcnt)) {
958 		/* bpf_map_free_id() must be called first */
959 		bpf_map_free_id(map);
960 
961 		WARN_ON_ONCE(atomic64_read(&map->sleepable_refcnt));
962 		if (READ_ONCE(map->free_after_mult_rcu_gp))
963 			call_rcu_tasks_trace(&map->rcu, bpf_map_free_mult_rcu_gp);
964 		else if (READ_ONCE(map->free_after_rcu_gp))
965 			call_rcu(&map->rcu, bpf_map_free_rcu_gp);
966 		else
967 			bpf_map_free_in_work(map);
968 	}
969 }
970 EXPORT_SYMBOL_GPL(bpf_map_put);
971 
972 void bpf_map_put_with_uref(struct bpf_map *map)
973 {
974 	bpf_map_put_uref(map);
975 	bpf_map_put(map);
976 }
977 
978 static int bpf_map_release(struct inode *inode, struct file *filp)
979 {
980 	struct bpf_map *map = filp->private_data;
981 
982 	if (map->ops->map_release)
983 		map->ops->map_release(map, filp);
984 
985 	bpf_map_put_with_uref(map);
986 	return 0;
987 }
988 
989 static fmode_t map_get_sys_perms(struct bpf_map *map, struct fd f)
990 {
991 	fmode_t mode = fd_file(f)->f_mode;
992 
993 	/* Our file permissions may have been overridden by global
994 	 * map permissions facing syscall side.
995 	 */
996 	if (READ_ONCE(map->frozen))
997 		mode &= ~FMODE_CAN_WRITE;
998 	return mode;
999 }
1000 
1001 #ifdef CONFIG_PROC_FS
1002 /* Show the memory usage of a bpf map */
1003 static u64 bpf_map_memory_usage(const struct bpf_map *map)
1004 {
1005 	return map->ops->map_mem_usage(map);
1006 }
1007 
1008 static void bpf_map_show_fdinfo(struct seq_file *m, struct file *filp)
1009 {
1010 	struct bpf_map *map = filp->private_data;
1011 	u32 type = 0, jited = 0;
1012 
1013 	spin_lock(&map->owner_lock);
1014 	if (map->owner) {
1015 		type  = map->owner->type;
1016 		jited = map->owner->jited;
1017 	}
1018 	spin_unlock(&map->owner_lock);
1019 
1020 	seq_printf(m,
1021 		   "map_type:\t%u\n"
1022 		   "key_size:\t%u\n"
1023 		   "value_size:\t%u\n"
1024 		   "max_entries:\t%u\n"
1025 		   "map_flags:\t%#x\n"
1026 		   "map_extra:\t%#llx\n"
1027 		   "memlock:\t%llu\n"
1028 		   "map_id:\t%u\n"
1029 		   "frozen:\t%u\n",
1030 		   map->map_type,
1031 		   map->key_size,
1032 		   map->value_size,
1033 		   map->max_entries,
1034 		   map->map_flags,
1035 		   (unsigned long long)map->map_extra,
1036 		   bpf_map_memory_usage(map),
1037 		   map->id,
1038 		   READ_ONCE(map->frozen));
1039 	if (type) {
1040 		seq_printf(m, "owner_prog_type:\t%u\n", type);
1041 		seq_printf(m, "owner_jited:\t%u\n", jited);
1042 	}
1043 }
1044 #endif
1045 
1046 static ssize_t bpf_dummy_read(struct file *filp, char __user *buf, size_t siz,
1047 			      loff_t *ppos)
1048 {
1049 	/* We need this handler such that alloc_file() enables
1050 	 * f_mode with FMODE_CAN_READ.
1051 	 */
1052 	return -EINVAL;
1053 }
1054 
1055 static ssize_t bpf_dummy_write(struct file *filp, const char __user *buf,
1056 			       size_t siz, loff_t *ppos)
1057 {
1058 	/* We need this handler such that alloc_file() enables
1059 	 * f_mode with FMODE_CAN_WRITE.
1060 	 */
1061 	return -EINVAL;
1062 }
1063 
1064 /* called for any extra memory-mapped regions (except initial) */
1065 static void bpf_map_mmap_open(struct vm_area_struct *vma)
1066 {
1067 	struct bpf_map *map = vma->vm_file->private_data;
1068 
1069 	if (vma->vm_flags & VM_MAYWRITE)
1070 		bpf_map_write_active_inc(map);
1071 }
1072 
1073 /* called for all unmapped memory region (including initial) */
1074 static void bpf_map_mmap_close(struct vm_area_struct *vma)
1075 {
1076 	struct bpf_map *map = vma->vm_file->private_data;
1077 
1078 	if (vma->vm_flags & VM_MAYWRITE)
1079 		bpf_map_write_active_dec(map);
1080 }
1081 
1082 static const struct vm_operations_struct bpf_map_default_vmops = {
1083 	.open		= bpf_map_mmap_open,
1084 	.close		= bpf_map_mmap_close,
1085 };
1086 
1087 static int bpf_map_mmap(struct file *filp, struct vm_area_struct *vma)
1088 {
1089 	struct bpf_map *map = filp->private_data;
1090 	int err = 0;
1091 
1092 	if (!map->ops->map_mmap || !IS_ERR_OR_NULL(map->record))
1093 		return -ENOTSUPP;
1094 
1095 	if (!(vma->vm_flags & VM_SHARED))
1096 		return -EINVAL;
1097 
1098 	mutex_lock(&map->freeze_mutex);
1099 
1100 	if (vma->vm_flags & VM_WRITE) {
1101 		if (map->frozen) {
1102 			err = -EPERM;
1103 			goto out;
1104 		}
1105 		/* map is meant to be read-only, so do not allow mapping as
1106 		 * writable, because it's possible to leak a writable page
1107 		 * reference and allows user-space to still modify it after
1108 		 * freezing, while verifier will assume contents do not change
1109 		 */
1110 		if (map->map_flags & BPF_F_RDONLY_PROG) {
1111 			err = -EACCES;
1112 			goto out;
1113 		}
1114 		bpf_map_write_active_inc(map);
1115 	}
1116 out:
1117 	mutex_unlock(&map->freeze_mutex);
1118 	if (err)
1119 		return err;
1120 
1121 	/* set default open/close callbacks */
1122 	vma->vm_ops = &bpf_map_default_vmops;
1123 	vma->vm_private_data = map;
1124 	vm_flags_clear(vma, VM_MAYEXEC);
1125 	/* If mapping is read-only, then disallow potentially re-mapping with
1126 	 * PROT_WRITE by dropping VM_MAYWRITE flag. This VM_MAYWRITE clearing
1127 	 * means that as far as BPF map's memory-mapped VMAs are concerned,
1128 	 * VM_WRITE and VM_MAYWRITE and equivalent, if one of them is set,
1129 	 * both should be set, so we can forget about VM_MAYWRITE and always
1130 	 * check just VM_WRITE
1131 	 */
1132 	if (!(vma->vm_flags & VM_WRITE))
1133 		vm_flags_clear(vma, VM_MAYWRITE);
1134 
1135 	err = map->ops->map_mmap(map, vma);
1136 	if (err) {
1137 		if (vma->vm_flags & VM_WRITE)
1138 			bpf_map_write_active_dec(map);
1139 	}
1140 
1141 	return err;
1142 }
1143 
1144 static __poll_t bpf_map_poll(struct file *filp, struct poll_table_struct *pts)
1145 {
1146 	struct bpf_map *map = filp->private_data;
1147 
1148 	if (map->ops->map_poll)
1149 		return map->ops->map_poll(map, filp, pts);
1150 
1151 	return EPOLLERR;
1152 }
1153 
1154 static unsigned long bpf_get_unmapped_area(struct file *filp, unsigned long addr,
1155 					   unsigned long len, unsigned long pgoff,
1156 					   unsigned long flags)
1157 {
1158 	struct bpf_map *map = filp->private_data;
1159 
1160 	if (map->ops->map_get_unmapped_area)
1161 		return map->ops->map_get_unmapped_area(filp, addr, len, pgoff, flags);
1162 #ifdef CONFIG_MMU
1163 	return mm_get_unmapped_area(filp, addr, len, pgoff, flags);
1164 #else
1165 	return addr;
1166 #endif
1167 }
1168 
1169 const struct file_operations bpf_map_fops = {
1170 #ifdef CONFIG_PROC_FS
1171 	.show_fdinfo	= bpf_map_show_fdinfo,
1172 #endif
1173 	.release	= bpf_map_release,
1174 	.read		= bpf_dummy_read,
1175 	.write		= bpf_dummy_write,
1176 	.mmap		= bpf_map_mmap,
1177 	.poll		= bpf_map_poll,
1178 	.get_unmapped_area = bpf_get_unmapped_area,
1179 };
1180 
1181 int bpf_map_new_fd(struct bpf_map *map, int flags)
1182 {
1183 	int ret;
1184 
1185 	ret = security_bpf_map(map, OPEN_FMODE(flags));
1186 	if (ret < 0)
1187 		return ret;
1188 
1189 	return anon_inode_getfd("bpf-map", &bpf_map_fops, map,
1190 				flags | O_CLOEXEC);
1191 }
1192 
1193 int bpf_get_file_flag(int flags)
1194 {
1195 	if ((flags & BPF_F_RDONLY) && (flags & BPF_F_WRONLY))
1196 		return -EINVAL;
1197 	if (flags & BPF_F_RDONLY)
1198 		return O_RDONLY;
1199 	if (flags & BPF_F_WRONLY)
1200 		return O_WRONLY;
1201 	return O_RDWR;
1202 }
1203 
1204 /* helper macro to check that unused fields 'union bpf_attr' are zero */
1205 #define CHECK_ATTR(CMD) \
1206 	memchr_inv((void *) &attr->CMD##_LAST_FIELD + \
1207 		   sizeof(attr->CMD##_LAST_FIELD), 0, \
1208 		   sizeof(*attr) - \
1209 		   offsetof(union bpf_attr, CMD##_LAST_FIELD) - \
1210 		   sizeof(attr->CMD##_LAST_FIELD)) != NULL
1211 
1212 /* dst and src must have at least "size" number of bytes.
1213  * Return strlen on success and < 0 on error.
1214  */
1215 int bpf_obj_name_cpy(char *dst, const char *src, unsigned int size)
1216 {
1217 	const char *end = src + size;
1218 	const char *orig_src = src;
1219 
1220 	memset(dst, 0, size);
1221 	/* Copy all isalnum(), '_' and '.' chars. */
1222 	while (src < end && *src) {
1223 		if (!isalnum(*src) &&
1224 		    *src != '_' && *src != '.')
1225 			return -EINVAL;
1226 		*dst++ = *src++;
1227 	}
1228 
1229 	/* No '\0' found in "size" number of bytes */
1230 	if (src == end)
1231 		return -EINVAL;
1232 
1233 	return src - orig_src;
1234 }
1235 EXPORT_SYMBOL_GPL(bpf_obj_name_cpy);
1236 
1237 int map_check_no_btf(struct bpf_map *map,
1238 		     const struct btf *btf,
1239 		     const struct btf_type *key_type,
1240 		     const struct btf_type *value_type)
1241 {
1242 	return -ENOTSUPP;
1243 }
1244 
1245 static int map_check_btf(struct bpf_map *map, struct bpf_token *token,
1246 			 const struct btf *btf, u32 btf_key_id, u32 btf_value_id)
1247 {
1248 	const struct btf_type *key_type, *value_type;
1249 	u32 key_size, value_size;
1250 	int ret = 0;
1251 
1252 	/* Some maps allow key to be unspecified. */
1253 	if (btf_key_id) {
1254 		key_type = btf_type_id_size(btf, &btf_key_id, &key_size);
1255 		if (!key_type || key_size != map->key_size)
1256 			return -EINVAL;
1257 	} else {
1258 		key_type = btf_type_by_id(btf, 0);
1259 		if (!map->ops->map_check_btf)
1260 			return -EINVAL;
1261 	}
1262 
1263 	value_type = btf_type_id_size(btf, &btf_value_id, &value_size);
1264 	if (!value_type || value_size != map->value_size)
1265 		return -EINVAL;
1266 
1267 	map->record = btf_parse_fields(btf, value_type,
1268 				       BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK | BPF_TIMER | BPF_KPTR | BPF_LIST_HEAD |
1269 				       BPF_RB_ROOT | BPF_REFCOUNT | BPF_WORKQUEUE | BPF_UPTR |
1270 				       BPF_TASK_WORK,
1271 				       map->value_size);
1272 	if (!IS_ERR_OR_NULL(map->record)) {
1273 		int i;
1274 
1275 		if (!bpf_token_capable(token, CAP_BPF)) {
1276 			ret = -EPERM;
1277 			goto free_map_tab;
1278 		}
1279 		if (map->map_flags & (BPF_F_RDONLY_PROG | BPF_F_WRONLY_PROG)) {
1280 			ret = -EACCES;
1281 			goto free_map_tab;
1282 		}
1283 		for (i = 0; i < sizeof(map->record->field_mask) * 8; i++) {
1284 			switch (map->record->field_mask & (1 << i)) {
1285 			case 0:
1286 				continue;
1287 			case BPF_SPIN_LOCK:
1288 			case BPF_RES_SPIN_LOCK:
1289 				if (map->map_type != BPF_MAP_TYPE_HASH &&
1290 				    map->map_type != BPF_MAP_TYPE_ARRAY &&
1291 				    map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
1292 				    map->map_type != BPF_MAP_TYPE_SK_STORAGE &&
1293 				    map->map_type != BPF_MAP_TYPE_INODE_STORAGE &&
1294 				    map->map_type != BPF_MAP_TYPE_TASK_STORAGE &&
1295 				    map->map_type != BPF_MAP_TYPE_CGRP_STORAGE) {
1296 					ret = -EOPNOTSUPP;
1297 					goto free_map_tab;
1298 				}
1299 				break;
1300 			case BPF_TIMER:
1301 			case BPF_WORKQUEUE:
1302 			case BPF_TASK_WORK:
1303 				if (map->map_type != BPF_MAP_TYPE_HASH &&
1304 				    map->map_type != BPF_MAP_TYPE_LRU_HASH &&
1305 				    map->map_type != BPF_MAP_TYPE_ARRAY) {
1306 					ret = -EOPNOTSUPP;
1307 					goto free_map_tab;
1308 				}
1309 				break;
1310 			case BPF_KPTR_UNREF:
1311 			case BPF_KPTR_REF:
1312 			case BPF_KPTR_PERCPU:
1313 			case BPF_REFCOUNT:
1314 				if (map->map_type != BPF_MAP_TYPE_HASH &&
1315 				    map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
1316 				    map->map_type != BPF_MAP_TYPE_LRU_HASH &&
1317 				    map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH &&
1318 				    map->map_type != BPF_MAP_TYPE_ARRAY &&
1319 				    map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
1320 				    map->map_type != BPF_MAP_TYPE_SK_STORAGE &&
1321 				    map->map_type != BPF_MAP_TYPE_INODE_STORAGE &&
1322 				    map->map_type != BPF_MAP_TYPE_TASK_STORAGE &&
1323 				    map->map_type != BPF_MAP_TYPE_CGRP_STORAGE) {
1324 					ret = -EOPNOTSUPP;
1325 					goto free_map_tab;
1326 				}
1327 				break;
1328 			case BPF_UPTR:
1329 				if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE) {
1330 					ret = -EOPNOTSUPP;
1331 					goto free_map_tab;
1332 				}
1333 				break;
1334 			case BPF_LIST_HEAD:
1335 			case BPF_RB_ROOT:
1336 				if (map->map_type != BPF_MAP_TYPE_HASH &&
1337 				    map->map_type != BPF_MAP_TYPE_LRU_HASH &&
1338 				    map->map_type != BPF_MAP_TYPE_ARRAY) {
1339 					ret = -EOPNOTSUPP;
1340 					goto free_map_tab;
1341 				}
1342 				break;
1343 			default:
1344 				/* Fail if map_type checks are missing for a field type */
1345 				ret = -EOPNOTSUPP;
1346 				goto free_map_tab;
1347 			}
1348 		}
1349 	}
1350 
1351 	ret = btf_check_and_fixup_fields(btf, map->record);
1352 	if (ret < 0)
1353 		goto free_map_tab;
1354 
1355 	if (map->ops->map_check_btf) {
1356 		ret = map->ops->map_check_btf(map, btf, key_type, value_type);
1357 		if (ret < 0)
1358 			goto free_map_tab;
1359 	}
1360 
1361 	return ret;
1362 free_map_tab:
1363 	bpf_map_free_record(map);
1364 	return ret;
1365 }
1366 
1367 #define BPF_MAP_CREATE_LAST_FIELD excl_prog_hash_size
1368 /* called via syscall */
1369 static int map_create(union bpf_attr *attr, bpfptr_t uattr)
1370 {
1371 	const struct bpf_map_ops *ops;
1372 	struct bpf_token *token = NULL;
1373 	int numa_node = bpf_map_attr_numa_node(attr);
1374 	u32 map_type = attr->map_type;
1375 	struct bpf_map *map;
1376 	bool token_flag;
1377 	int f_flags;
1378 	int err;
1379 
1380 	err = CHECK_ATTR(BPF_MAP_CREATE);
1381 	if (err)
1382 		return -EINVAL;
1383 
1384 	/* check BPF_F_TOKEN_FD flag, remember if it's set, and then clear it
1385 	 * to avoid per-map type checks tripping on unknown flag
1386 	 */
1387 	token_flag = attr->map_flags & BPF_F_TOKEN_FD;
1388 	attr->map_flags &= ~BPF_F_TOKEN_FD;
1389 
1390 	if (attr->btf_vmlinux_value_type_id) {
1391 		if (attr->map_type != BPF_MAP_TYPE_STRUCT_OPS ||
1392 		    attr->btf_key_type_id || attr->btf_value_type_id)
1393 			return -EINVAL;
1394 	} else if (attr->btf_key_type_id && !attr->btf_value_type_id) {
1395 		return -EINVAL;
1396 	}
1397 
1398 	if (attr->map_type != BPF_MAP_TYPE_BLOOM_FILTER &&
1399 	    attr->map_type != BPF_MAP_TYPE_ARENA &&
1400 	    attr->map_extra != 0)
1401 		return -EINVAL;
1402 
1403 	f_flags = bpf_get_file_flag(attr->map_flags);
1404 	if (f_flags < 0)
1405 		return f_flags;
1406 
1407 	if (numa_node != NUMA_NO_NODE &&
1408 	    ((unsigned int)numa_node >= nr_node_ids ||
1409 	     !node_online(numa_node)))
1410 		return -EINVAL;
1411 
1412 	/* find map type and init map: hashtable vs rbtree vs bloom vs ... */
1413 	map_type = attr->map_type;
1414 	if (map_type >= ARRAY_SIZE(bpf_map_types))
1415 		return -EINVAL;
1416 	map_type = array_index_nospec(map_type, ARRAY_SIZE(bpf_map_types));
1417 	ops = bpf_map_types[map_type];
1418 	if (!ops)
1419 		return -EINVAL;
1420 
1421 	if (ops->map_alloc_check) {
1422 		err = ops->map_alloc_check(attr);
1423 		if (err)
1424 			return err;
1425 	}
1426 	if (attr->map_ifindex)
1427 		ops = &bpf_map_offload_ops;
1428 	if (!ops->map_mem_usage)
1429 		return -EINVAL;
1430 
1431 	if (token_flag) {
1432 		token = bpf_token_get_from_fd(attr->map_token_fd);
1433 		if (IS_ERR(token))
1434 			return PTR_ERR(token);
1435 
1436 		/* if current token doesn't grant map creation permissions,
1437 		 * then we can't use this token, so ignore it and rely on
1438 		 * system-wide capabilities checks
1439 		 */
1440 		if (!bpf_token_allow_cmd(token, BPF_MAP_CREATE) ||
1441 		    !bpf_token_allow_map_type(token, attr->map_type)) {
1442 			bpf_token_put(token);
1443 			token = NULL;
1444 		}
1445 	}
1446 
1447 	err = -EPERM;
1448 
1449 	/* Intent here is for unprivileged_bpf_disabled to block BPF map
1450 	 * creation for unprivileged users; other actions depend
1451 	 * on fd availability and access to bpffs, so are dependent on
1452 	 * object creation success. Even with unprivileged BPF disabled,
1453 	 * capability checks are still carried out.
1454 	 */
1455 	if (sysctl_unprivileged_bpf_disabled && !bpf_token_capable(token, CAP_BPF))
1456 		goto put_token;
1457 
1458 	/* check privileged map type permissions */
1459 	switch (map_type) {
1460 	case BPF_MAP_TYPE_ARRAY:
1461 	case BPF_MAP_TYPE_PERCPU_ARRAY:
1462 	case BPF_MAP_TYPE_PROG_ARRAY:
1463 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
1464 	case BPF_MAP_TYPE_CGROUP_ARRAY:
1465 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
1466 	case BPF_MAP_TYPE_HASH:
1467 	case BPF_MAP_TYPE_PERCPU_HASH:
1468 	case BPF_MAP_TYPE_HASH_OF_MAPS:
1469 	case BPF_MAP_TYPE_RINGBUF:
1470 	case BPF_MAP_TYPE_USER_RINGBUF:
1471 	case BPF_MAP_TYPE_CGROUP_STORAGE:
1472 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
1473 		/* unprivileged */
1474 		break;
1475 	case BPF_MAP_TYPE_SK_STORAGE:
1476 	case BPF_MAP_TYPE_INODE_STORAGE:
1477 	case BPF_MAP_TYPE_TASK_STORAGE:
1478 	case BPF_MAP_TYPE_CGRP_STORAGE:
1479 	case BPF_MAP_TYPE_BLOOM_FILTER:
1480 	case BPF_MAP_TYPE_LPM_TRIE:
1481 	case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
1482 	case BPF_MAP_TYPE_STACK_TRACE:
1483 	case BPF_MAP_TYPE_QUEUE:
1484 	case BPF_MAP_TYPE_STACK:
1485 	case BPF_MAP_TYPE_LRU_HASH:
1486 	case BPF_MAP_TYPE_LRU_PERCPU_HASH:
1487 	case BPF_MAP_TYPE_STRUCT_OPS:
1488 	case BPF_MAP_TYPE_CPUMAP:
1489 	case BPF_MAP_TYPE_ARENA:
1490 	case BPF_MAP_TYPE_INSN_ARRAY:
1491 		if (!bpf_token_capable(token, CAP_BPF))
1492 			goto put_token;
1493 		break;
1494 	case BPF_MAP_TYPE_SOCKMAP:
1495 	case BPF_MAP_TYPE_SOCKHASH:
1496 	case BPF_MAP_TYPE_DEVMAP:
1497 	case BPF_MAP_TYPE_DEVMAP_HASH:
1498 	case BPF_MAP_TYPE_XSKMAP:
1499 		if (!bpf_token_capable(token, CAP_NET_ADMIN))
1500 			goto put_token;
1501 		break;
1502 	default:
1503 		WARN(1, "unsupported map type %d", map_type);
1504 		goto put_token;
1505 	}
1506 
1507 	map = ops->map_alloc(attr);
1508 	if (IS_ERR(map)) {
1509 		err = PTR_ERR(map);
1510 		goto put_token;
1511 	}
1512 	map->ops = ops;
1513 	map->map_type = map_type;
1514 
1515 	err = bpf_obj_name_cpy(map->name, attr->map_name,
1516 			       sizeof(attr->map_name));
1517 	if (err < 0)
1518 		goto free_map;
1519 
1520 	preempt_disable();
1521 	map->cookie = gen_cookie_next(&bpf_map_cookie);
1522 	preempt_enable();
1523 
1524 	atomic64_set(&map->refcnt, 1);
1525 	atomic64_set(&map->usercnt, 1);
1526 	mutex_init(&map->freeze_mutex);
1527 	spin_lock_init(&map->owner_lock);
1528 
1529 	if (attr->btf_key_type_id || attr->btf_value_type_id ||
1530 	    /* Even the map's value is a kernel's struct,
1531 	     * the bpf_prog.o must have BTF to begin with
1532 	     * to figure out the corresponding kernel's
1533 	     * counter part.  Thus, attr->btf_fd has
1534 	     * to be valid also.
1535 	     */
1536 	    attr->btf_vmlinux_value_type_id) {
1537 		struct btf *btf;
1538 
1539 		btf = btf_get_by_fd(attr->btf_fd);
1540 		if (IS_ERR(btf)) {
1541 			err = PTR_ERR(btf);
1542 			goto free_map;
1543 		}
1544 		if (btf_is_kernel(btf)) {
1545 			btf_put(btf);
1546 			err = -EACCES;
1547 			goto free_map;
1548 		}
1549 		map->btf = btf;
1550 
1551 		if (attr->btf_value_type_id) {
1552 			err = map_check_btf(map, token, btf, attr->btf_key_type_id,
1553 					    attr->btf_value_type_id);
1554 			if (err)
1555 				goto free_map;
1556 		}
1557 
1558 		map->btf_key_type_id = attr->btf_key_type_id;
1559 		map->btf_value_type_id = attr->btf_value_type_id;
1560 		map->btf_vmlinux_value_type_id =
1561 			attr->btf_vmlinux_value_type_id;
1562 	}
1563 
1564 	if (attr->excl_prog_hash) {
1565 		bpfptr_t uprog_hash = make_bpfptr(attr->excl_prog_hash, uattr.is_kernel);
1566 
1567 		if (attr->excl_prog_hash_size != SHA256_DIGEST_SIZE) {
1568 			err = -EINVAL;
1569 			goto free_map;
1570 		}
1571 
1572 		map->excl_prog_sha = kzalloc(SHA256_DIGEST_SIZE, GFP_KERNEL);
1573 		if (!map->excl_prog_sha) {
1574 			err = -ENOMEM;
1575 			goto free_map;
1576 		}
1577 
1578 		if (copy_from_bpfptr(map->excl_prog_sha, uprog_hash, SHA256_DIGEST_SIZE)) {
1579 			err = -EFAULT;
1580 			goto free_map;
1581 		}
1582 	} else if (attr->excl_prog_hash_size) {
1583 		err = -EINVAL;
1584 		goto free_map;
1585 	}
1586 
1587 	err = security_bpf_map_create(map, attr, token, uattr.is_kernel);
1588 	if (err)
1589 		goto free_map_sec;
1590 
1591 	err = bpf_map_alloc_id(map);
1592 	if (err)
1593 		goto free_map_sec;
1594 
1595 	bpf_map_save_memcg(map);
1596 	bpf_token_put(token);
1597 
1598 	err = bpf_map_new_fd(map, f_flags);
1599 	if (err < 0) {
1600 		/* failed to allocate fd.
1601 		 * bpf_map_put_with_uref() is needed because the above
1602 		 * bpf_map_alloc_id() has published the map
1603 		 * to the userspace and the userspace may
1604 		 * have refcnt-ed it through BPF_MAP_GET_FD_BY_ID.
1605 		 */
1606 		bpf_map_put_with_uref(map);
1607 		return err;
1608 	}
1609 
1610 	return err;
1611 
1612 free_map_sec:
1613 	security_bpf_map_free(map);
1614 free_map:
1615 	bpf_map_free(map);
1616 put_token:
1617 	bpf_token_put(token);
1618 	return err;
1619 }
1620 
1621 void bpf_map_inc(struct bpf_map *map)
1622 {
1623 	atomic64_inc(&map->refcnt);
1624 }
1625 EXPORT_SYMBOL_GPL(bpf_map_inc);
1626 
1627 void bpf_map_inc_with_uref(struct bpf_map *map)
1628 {
1629 	atomic64_inc(&map->refcnt);
1630 	atomic64_inc(&map->usercnt);
1631 }
1632 EXPORT_SYMBOL_GPL(bpf_map_inc_with_uref);
1633 
1634 struct bpf_map *bpf_map_get(u32 ufd)
1635 {
1636 	CLASS(fd, f)(ufd);
1637 	struct bpf_map *map = __bpf_map_get(f);
1638 
1639 	if (!IS_ERR(map))
1640 		bpf_map_inc(map);
1641 
1642 	return map;
1643 }
1644 EXPORT_SYMBOL_NS(bpf_map_get, "BPF_INTERNAL");
1645 
1646 struct bpf_map *bpf_map_get_with_uref(u32 ufd)
1647 {
1648 	CLASS(fd, f)(ufd);
1649 	struct bpf_map *map = __bpf_map_get(f);
1650 
1651 	if (!IS_ERR(map))
1652 		bpf_map_inc_with_uref(map);
1653 
1654 	return map;
1655 }
1656 
1657 /* map_idr_lock should have been held or the map should have been
1658  * protected by rcu read lock.
1659  */
1660 struct bpf_map *__bpf_map_inc_not_zero(struct bpf_map *map, bool uref)
1661 {
1662 	int refold;
1663 
1664 	refold = atomic64_fetch_add_unless(&map->refcnt, 1, 0);
1665 	if (!refold)
1666 		return ERR_PTR(-ENOENT);
1667 	if (uref)
1668 		atomic64_inc(&map->usercnt);
1669 
1670 	return map;
1671 }
1672 
1673 struct bpf_map *bpf_map_inc_not_zero(struct bpf_map *map)
1674 {
1675 	lockdep_assert(rcu_read_lock_held());
1676 	return __bpf_map_inc_not_zero(map, false);
1677 }
1678 EXPORT_SYMBOL_GPL(bpf_map_inc_not_zero);
1679 
1680 int __weak bpf_stackmap_extract(struct bpf_map *map, void *key, void *value,
1681 				bool delete)
1682 {
1683 	return -ENOTSUPP;
1684 }
1685 
1686 static void *__bpf_copy_key(void __user *ukey, u64 key_size)
1687 {
1688 	if (key_size)
1689 		return vmemdup_user(ukey, key_size);
1690 
1691 	if (ukey)
1692 		return ERR_PTR(-EINVAL);
1693 
1694 	return NULL;
1695 }
1696 
1697 static void *___bpf_copy_key(bpfptr_t ukey, u64 key_size)
1698 {
1699 	if (key_size)
1700 		return kvmemdup_bpfptr(ukey, key_size);
1701 
1702 	if (!bpfptr_is_null(ukey))
1703 		return ERR_PTR(-EINVAL);
1704 
1705 	return NULL;
1706 }
1707 
1708 /* last field in 'union bpf_attr' used by this command */
1709 #define BPF_MAP_LOOKUP_ELEM_LAST_FIELD flags
1710 
1711 static int map_lookup_elem(union bpf_attr *attr)
1712 {
1713 	void __user *ukey = u64_to_user_ptr(attr->key);
1714 	void __user *uvalue = u64_to_user_ptr(attr->value);
1715 	struct bpf_map *map;
1716 	void *key, *value;
1717 	u32 value_size;
1718 	int err;
1719 
1720 	if (CHECK_ATTR(BPF_MAP_LOOKUP_ELEM))
1721 		return -EINVAL;
1722 
1723 	CLASS(fd, f)(attr->map_fd);
1724 	map = __bpf_map_get(f);
1725 	if (IS_ERR(map))
1726 		return PTR_ERR(map);
1727 	if (!(map_get_sys_perms(map, f) & FMODE_CAN_READ))
1728 		return -EPERM;
1729 
1730 	err = bpf_map_check_op_flags(map, attr->flags, BPF_F_LOCK | BPF_F_CPU);
1731 	if (err)
1732 		return err;
1733 
1734 	key = __bpf_copy_key(ukey, map->key_size);
1735 	if (IS_ERR(key))
1736 		return PTR_ERR(key);
1737 
1738 	value_size = bpf_map_value_size(map, attr->flags);
1739 
1740 	err = -ENOMEM;
1741 	value = kvmalloc(value_size, GFP_USER | __GFP_NOWARN);
1742 	if (!value)
1743 		goto free_key;
1744 
1745 	if (map->map_type == BPF_MAP_TYPE_BLOOM_FILTER) {
1746 		if (copy_from_user(value, uvalue, value_size))
1747 			err = -EFAULT;
1748 		else
1749 			err = bpf_map_copy_value(map, key, value, attr->flags);
1750 		goto free_value;
1751 	}
1752 
1753 	err = bpf_map_copy_value(map, key, value, attr->flags);
1754 	if (err)
1755 		goto free_value;
1756 
1757 	err = -EFAULT;
1758 	if (copy_to_user(uvalue, value, value_size) != 0)
1759 		goto free_value;
1760 
1761 	err = 0;
1762 
1763 free_value:
1764 	kvfree(value);
1765 free_key:
1766 	kvfree(key);
1767 	return err;
1768 }
1769 
1770 
1771 #define BPF_MAP_UPDATE_ELEM_LAST_FIELD flags
1772 
1773 static int map_update_elem(union bpf_attr *attr, bpfptr_t uattr)
1774 {
1775 	bpfptr_t ukey = make_bpfptr(attr->key, uattr.is_kernel);
1776 	bpfptr_t uvalue = make_bpfptr(attr->value, uattr.is_kernel);
1777 	struct bpf_map *map;
1778 	void *key, *value;
1779 	u32 value_size;
1780 	int err;
1781 
1782 	if (CHECK_ATTR(BPF_MAP_UPDATE_ELEM))
1783 		return -EINVAL;
1784 
1785 	CLASS(fd, f)(attr->map_fd);
1786 	map = __bpf_map_get(f);
1787 	if (IS_ERR(map))
1788 		return PTR_ERR(map);
1789 	bpf_map_write_active_inc(map);
1790 	if (!(map_get_sys_perms(map, f) & FMODE_CAN_WRITE)) {
1791 		err = -EPERM;
1792 		goto err_put;
1793 	}
1794 
1795 	err = bpf_map_check_op_flags(map, attr->flags, ~0);
1796 	if (err)
1797 		goto err_put;
1798 
1799 	key = ___bpf_copy_key(ukey, map->key_size);
1800 	if (IS_ERR(key)) {
1801 		err = PTR_ERR(key);
1802 		goto err_put;
1803 	}
1804 
1805 	value_size = bpf_map_value_size(map, attr->flags);
1806 	value = kvmemdup_bpfptr(uvalue, value_size);
1807 	if (IS_ERR(value)) {
1808 		err = PTR_ERR(value);
1809 		goto free_key;
1810 	}
1811 
1812 	err = bpf_map_update_value(map, fd_file(f), key, value, attr->flags);
1813 	if (!err)
1814 		maybe_wait_bpf_programs(map);
1815 
1816 	kvfree(value);
1817 free_key:
1818 	kvfree(key);
1819 err_put:
1820 	bpf_map_write_active_dec(map);
1821 	return err;
1822 }
1823 
1824 #define BPF_MAP_DELETE_ELEM_LAST_FIELD key
1825 
1826 static int map_delete_elem(union bpf_attr *attr, bpfptr_t uattr)
1827 {
1828 	bpfptr_t ukey = make_bpfptr(attr->key, uattr.is_kernel);
1829 	struct bpf_map *map;
1830 	void *key;
1831 	int err;
1832 
1833 	if (CHECK_ATTR(BPF_MAP_DELETE_ELEM))
1834 		return -EINVAL;
1835 
1836 	CLASS(fd, f)(attr->map_fd);
1837 	map = __bpf_map_get(f);
1838 	if (IS_ERR(map))
1839 		return PTR_ERR(map);
1840 	bpf_map_write_active_inc(map);
1841 	if (!(map_get_sys_perms(map, f) & FMODE_CAN_WRITE)) {
1842 		err = -EPERM;
1843 		goto err_put;
1844 	}
1845 
1846 	key = ___bpf_copy_key(ukey, map->key_size);
1847 	if (IS_ERR(key)) {
1848 		err = PTR_ERR(key);
1849 		goto err_put;
1850 	}
1851 
1852 	if (bpf_map_is_offloaded(map)) {
1853 		err = bpf_map_offload_delete_elem(map, key);
1854 		goto out;
1855 	} else if (IS_FD_PROG_ARRAY(map) ||
1856 		   map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
1857 		/* These maps require sleepable context */
1858 		err = map->ops->map_delete_elem(map, key);
1859 		goto out;
1860 	}
1861 
1862 	bpf_disable_instrumentation();
1863 	rcu_read_lock();
1864 	err = map->ops->map_delete_elem(map, key);
1865 	rcu_read_unlock();
1866 	bpf_enable_instrumentation();
1867 	if (!err)
1868 		maybe_wait_bpf_programs(map);
1869 out:
1870 	kvfree(key);
1871 err_put:
1872 	bpf_map_write_active_dec(map);
1873 	return err;
1874 }
1875 
1876 /* last field in 'union bpf_attr' used by this command */
1877 #define BPF_MAP_GET_NEXT_KEY_LAST_FIELD next_key
1878 
1879 static int map_get_next_key(union bpf_attr *attr)
1880 {
1881 	void __user *ukey = u64_to_user_ptr(attr->key);
1882 	void __user *unext_key = u64_to_user_ptr(attr->next_key);
1883 	struct bpf_map *map;
1884 	void *key, *next_key;
1885 	int err;
1886 
1887 	if (CHECK_ATTR(BPF_MAP_GET_NEXT_KEY))
1888 		return -EINVAL;
1889 
1890 	CLASS(fd, f)(attr->map_fd);
1891 	map = __bpf_map_get(f);
1892 	if (IS_ERR(map))
1893 		return PTR_ERR(map);
1894 	if (!(map_get_sys_perms(map, f) & FMODE_CAN_READ))
1895 		return -EPERM;
1896 
1897 	if (ukey) {
1898 		key = __bpf_copy_key(ukey, map->key_size);
1899 		if (IS_ERR(key))
1900 			return PTR_ERR(key);
1901 	} else {
1902 		key = NULL;
1903 	}
1904 
1905 	err = -ENOMEM;
1906 	next_key = kvmalloc(map->key_size, GFP_USER);
1907 	if (!next_key)
1908 		goto free_key;
1909 
1910 	if (bpf_map_is_offloaded(map)) {
1911 		err = bpf_map_offload_get_next_key(map, key, next_key);
1912 		goto out;
1913 	}
1914 
1915 	rcu_read_lock();
1916 	err = map->ops->map_get_next_key(map, key, next_key);
1917 	rcu_read_unlock();
1918 out:
1919 	if (err)
1920 		goto free_next_key;
1921 
1922 	err = -EFAULT;
1923 	if (copy_to_user(unext_key, next_key, map->key_size) != 0)
1924 		goto free_next_key;
1925 
1926 	err = 0;
1927 
1928 free_next_key:
1929 	kvfree(next_key);
1930 free_key:
1931 	kvfree(key);
1932 	return err;
1933 }
1934 
1935 int generic_map_delete_batch(struct bpf_map *map,
1936 			     const union bpf_attr *attr,
1937 			     union bpf_attr __user *uattr)
1938 {
1939 	void __user *keys = u64_to_user_ptr(attr->batch.keys);
1940 	u32 cp, max_count;
1941 	int err = 0;
1942 	void *key;
1943 
1944 	if (attr->batch.elem_flags & ~BPF_F_LOCK)
1945 		return -EINVAL;
1946 
1947 	if ((attr->batch.elem_flags & BPF_F_LOCK) &&
1948 	    !btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
1949 		return -EINVAL;
1950 	}
1951 
1952 	max_count = attr->batch.count;
1953 	if (!max_count)
1954 		return 0;
1955 
1956 	if (put_user(0, &uattr->batch.count))
1957 		return -EFAULT;
1958 
1959 	key = kvmalloc(map->key_size, GFP_USER | __GFP_NOWARN);
1960 	if (!key)
1961 		return -ENOMEM;
1962 
1963 	for (cp = 0; cp < max_count; cp++) {
1964 		err = -EFAULT;
1965 		if (copy_from_user(key, keys + cp * map->key_size,
1966 				   map->key_size))
1967 			break;
1968 
1969 		if (bpf_map_is_offloaded(map)) {
1970 			err = bpf_map_offload_delete_elem(map, key);
1971 			break;
1972 		}
1973 
1974 		bpf_disable_instrumentation();
1975 		rcu_read_lock();
1976 		err = map->ops->map_delete_elem(map, key);
1977 		rcu_read_unlock();
1978 		bpf_enable_instrumentation();
1979 		if (err)
1980 			break;
1981 		cond_resched();
1982 	}
1983 	if (copy_to_user(&uattr->batch.count, &cp, sizeof(cp)))
1984 		err = -EFAULT;
1985 
1986 	kvfree(key);
1987 
1988 	return err;
1989 }
1990 
1991 int generic_map_update_batch(struct bpf_map *map, struct file *map_file,
1992 			     const union bpf_attr *attr,
1993 			     union bpf_attr __user *uattr)
1994 {
1995 	void __user *values = u64_to_user_ptr(attr->batch.values);
1996 	void __user *keys = u64_to_user_ptr(attr->batch.keys);
1997 	u32 value_size, cp, max_count;
1998 	void *key, *value;
1999 	int err = 0;
2000 
2001 	err = bpf_map_check_op_flags(map, attr->batch.elem_flags,
2002 				     BPF_F_LOCK | BPF_F_CPU | BPF_F_ALL_CPUS);
2003 	if (err)
2004 		return err;
2005 
2006 	value_size = bpf_map_value_size(map, attr->batch.elem_flags);
2007 
2008 	max_count = attr->batch.count;
2009 	if (!max_count)
2010 		return 0;
2011 
2012 	if (put_user(0, &uattr->batch.count))
2013 		return -EFAULT;
2014 
2015 	key = kvmalloc(map->key_size, GFP_USER | __GFP_NOWARN);
2016 	if (!key)
2017 		return -ENOMEM;
2018 
2019 	value = kvmalloc(value_size, GFP_USER | __GFP_NOWARN);
2020 	if (!value) {
2021 		kvfree(key);
2022 		return -ENOMEM;
2023 	}
2024 
2025 	for (cp = 0; cp < max_count; cp++) {
2026 		err = -EFAULT;
2027 		if (copy_from_user(key, keys + cp * map->key_size,
2028 		    map->key_size) ||
2029 		    copy_from_user(value, values + cp * value_size, value_size))
2030 			break;
2031 
2032 		err = bpf_map_update_value(map, map_file, key, value,
2033 					   attr->batch.elem_flags);
2034 
2035 		if (err)
2036 			break;
2037 		cond_resched();
2038 	}
2039 
2040 	if (copy_to_user(&uattr->batch.count, &cp, sizeof(cp)))
2041 		err = -EFAULT;
2042 
2043 	kvfree(value);
2044 	kvfree(key);
2045 
2046 	return err;
2047 }
2048 
2049 int generic_map_lookup_batch(struct bpf_map *map,
2050 				    const union bpf_attr *attr,
2051 				    union bpf_attr __user *uattr)
2052 {
2053 	void __user *uobatch = u64_to_user_ptr(attr->batch.out_batch);
2054 	void __user *ubatch = u64_to_user_ptr(attr->batch.in_batch);
2055 	void __user *values = u64_to_user_ptr(attr->batch.values);
2056 	void __user *keys = u64_to_user_ptr(attr->batch.keys);
2057 	void *buf, *buf_prevkey, *prev_key, *key, *value;
2058 	u32 value_size, cp, max_count;
2059 	int err;
2060 
2061 	err = bpf_map_check_op_flags(map, attr->batch.elem_flags, BPF_F_LOCK | BPF_F_CPU);
2062 	if (err)
2063 		return err;
2064 
2065 	value_size = bpf_map_value_size(map, attr->batch.elem_flags);
2066 
2067 	max_count = attr->batch.count;
2068 	if (!max_count)
2069 		return 0;
2070 
2071 	if (put_user(0, &uattr->batch.count))
2072 		return -EFAULT;
2073 
2074 	buf_prevkey = kvmalloc(map->key_size, GFP_USER | __GFP_NOWARN);
2075 	if (!buf_prevkey)
2076 		return -ENOMEM;
2077 
2078 	buf = kvmalloc(map->key_size + value_size, GFP_USER | __GFP_NOWARN);
2079 	if (!buf) {
2080 		kvfree(buf_prevkey);
2081 		return -ENOMEM;
2082 	}
2083 
2084 	err = -EFAULT;
2085 	prev_key = NULL;
2086 	if (ubatch && copy_from_user(buf_prevkey, ubatch, map->key_size))
2087 		goto free_buf;
2088 	key = buf;
2089 	value = key + map->key_size;
2090 	if (ubatch)
2091 		prev_key = buf_prevkey;
2092 
2093 	for (cp = 0; cp < max_count;) {
2094 		rcu_read_lock();
2095 		err = map->ops->map_get_next_key(map, prev_key, key);
2096 		rcu_read_unlock();
2097 		if (err)
2098 			break;
2099 		err = bpf_map_copy_value(map, key, value,
2100 					 attr->batch.elem_flags);
2101 
2102 		if (err == -ENOENT)
2103 			goto next_key;
2104 
2105 		if (err)
2106 			goto free_buf;
2107 
2108 		if (copy_to_user(keys + cp * map->key_size, key,
2109 				 map->key_size)) {
2110 			err = -EFAULT;
2111 			goto free_buf;
2112 		}
2113 		if (copy_to_user(values + cp * value_size, value, value_size)) {
2114 			err = -EFAULT;
2115 			goto free_buf;
2116 		}
2117 
2118 		cp++;
2119 next_key:
2120 		if (!prev_key)
2121 			prev_key = buf_prevkey;
2122 
2123 		swap(prev_key, key);
2124 		cond_resched();
2125 	}
2126 
2127 	if (err == -EFAULT)
2128 		goto free_buf;
2129 
2130 	if ((copy_to_user(&uattr->batch.count, &cp, sizeof(cp)) ||
2131 		    (cp && copy_to_user(uobatch, prev_key, map->key_size))))
2132 		err = -EFAULT;
2133 
2134 free_buf:
2135 	kvfree(buf_prevkey);
2136 	kvfree(buf);
2137 	return err;
2138 }
2139 
2140 #define BPF_MAP_LOOKUP_AND_DELETE_ELEM_LAST_FIELD flags
2141 
2142 static int map_lookup_and_delete_elem(union bpf_attr *attr)
2143 {
2144 	void __user *ukey = u64_to_user_ptr(attr->key);
2145 	void __user *uvalue = u64_to_user_ptr(attr->value);
2146 	struct bpf_map *map;
2147 	void *key, *value;
2148 	u32 value_size;
2149 	int err;
2150 
2151 	if (CHECK_ATTR(BPF_MAP_LOOKUP_AND_DELETE_ELEM))
2152 		return -EINVAL;
2153 
2154 	if (attr->flags & ~BPF_F_LOCK)
2155 		return -EINVAL;
2156 
2157 	CLASS(fd, f)(attr->map_fd);
2158 	map = __bpf_map_get(f);
2159 	if (IS_ERR(map))
2160 		return PTR_ERR(map);
2161 	bpf_map_write_active_inc(map);
2162 	if (!(map_get_sys_perms(map, f) & FMODE_CAN_READ) ||
2163 	    !(map_get_sys_perms(map, f) & FMODE_CAN_WRITE)) {
2164 		err = -EPERM;
2165 		goto err_put;
2166 	}
2167 
2168 	if (attr->flags &&
2169 	    (map->map_type == BPF_MAP_TYPE_QUEUE ||
2170 	     map->map_type == BPF_MAP_TYPE_STACK)) {
2171 		err = -EINVAL;
2172 		goto err_put;
2173 	}
2174 
2175 	if ((attr->flags & BPF_F_LOCK) &&
2176 	    !btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
2177 		err = -EINVAL;
2178 		goto err_put;
2179 	}
2180 
2181 	key = __bpf_copy_key(ukey, map->key_size);
2182 	if (IS_ERR(key)) {
2183 		err = PTR_ERR(key);
2184 		goto err_put;
2185 	}
2186 
2187 	value_size = bpf_map_value_size(map, 0);
2188 
2189 	err = -ENOMEM;
2190 	value = kvmalloc(value_size, GFP_USER | __GFP_NOWARN);
2191 	if (!value)
2192 		goto free_key;
2193 
2194 	err = -ENOTSUPP;
2195 	if (map->map_type == BPF_MAP_TYPE_QUEUE ||
2196 	    map->map_type == BPF_MAP_TYPE_STACK) {
2197 		err = map->ops->map_pop_elem(map, value);
2198 	} else if (map->map_type == BPF_MAP_TYPE_HASH ||
2199 		   map->map_type == BPF_MAP_TYPE_PERCPU_HASH ||
2200 		   map->map_type == BPF_MAP_TYPE_LRU_HASH ||
2201 		   map->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH ||
2202 		   map->map_type == BPF_MAP_TYPE_STACK_TRACE) {
2203 		if (!bpf_map_is_offloaded(map)) {
2204 			bpf_disable_instrumentation();
2205 			rcu_read_lock();
2206 			err = map->ops->map_lookup_and_delete_elem(map, key, value, attr->flags);
2207 			rcu_read_unlock();
2208 			bpf_enable_instrumentation();
2209 		}
2210 	}
2211 
2212 	if (err)
2213 		goto free_value;
2214 
2215 	if (copy_to_user(uvalue, value, value_size) != 0) {
2216 		err = -EFAULT;
2217 		goto free_value;
2218 	}
2219 
2220 	err = 0;
2221 
2222 free_value:
2223 	kvfree(value);
2224 free_key:
2225 	kvfree(key);
2226 err_put:
2227 	bpf_map_write_active_dec(map);
2228 	return err;
2229 }
2230 
2231 #define BPF_MAP_FREEZE_LAST_FIELD map_fd
2232 
2233 static int map_freeze(const union bpf_attr *attr)
2234 {
2235 	int err = 0;
2236 	struct bpf_map *map;
2237 
2238 	if (CHECK_ATTR(BPF_MAP_FREEZE))
2239 		return -EINVAL;
2240 
2241 	CLASS(fd, f)(attr->map_fd);
2242 	map = __bpf_map_get(f);
2243 	if (IS_ERR(map))
2244 		return PTR_ERR(map);
2245 
2246 	if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS || !IS_ERR_OR_NULL(map->record))
2247 		return -ENOTSUPP;
2248 
2249 	if (!(map_get_sys_perms(map, f) & FMODE_CAN_WRITE))
2250 		return -EPERM;
2251 
2252 	mutex_lock(&map->freeze_mutex);
2253 	if (bpf_map_write_active(map)) {
2254 		err = -EBUSY;
2255 		goto err_put;
2256 	}
2257 	if (READ_ONCE(map->frozen)) {
2258 		err = -EBUSY;
2259 		goto err_put;
2260 	}
2261 
2262 	WRITE_ONCE(map->frozen, true);
2263 err_put:
2264 	mutex_unlock(&map->freeze_mutex);
2265 	return err;
2266 }
2267 
2268 static const struct bpf_prog_ops * const bpf_prog_types[] = {
2269 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
2270 	[_id] = & _name ## _prog_ops,
2271 #define BPF_MAP_TYPE(_id, _ops)
2272 #define BPF_LINK_TYPE(_id, _name)
2273 #include <linux/bpf_types.h>
2274 #undef BPF_PROG_TYPE
2275 #undef BPF_MAP_TYPE
2276 #undef BPF_LINK_TYPE
2277 };
2278 
2279 static int find_prog_type(enum bpf_prog_type type, struct bpf_prog *prog)
2280 {
2281 	const struct bpf_prog_ops *ops;
2282 
2283 	if (type >= ARRAY_SIZE(bpf_prog_types))
2284 		return -EINVAL;
2285 	type = array_index_nospec(type, ARRAY_SIZE(bpf_prog_types));
2286 	ops = bpf_prog_types[type];
2287 	if (!ops)
2288 		return -EINVAL;
2289 
2290 	if (!bpf_prog_is_offloaded(prog->aux))
2291 		prog->aux->ops = ops;
2292 	else
2293 		prog->aux->ops = &bpf_offload_prog_ops;
2294 	prog->type = type;
2295 	return 0;
2296 }
2297 
2298 enum bpf_audit {
2299 	BPF_AUDIT_LOAD,
2300 	BPF_AUDIT_UNLOAD,
2301 	BPF_AUDIT_MAX,
2302 };
2303 
2304 static const char * const bpf_audit_str[BPF_AUDIT_MAX] = {
2305 	[BPF_AUDIT_LOAD]   = "LOAD",
2306 	[BPF_AUDIT_UNLOAD] = "UNLOAD",
2307 };
2308 
2309 static void bpf_audit_prog(const struct bpf_prog *prog, unsigned int op)
2310 {
2311 	struct audit_context *ctx = NULL;
2312 	struct audit_buffer *ab;
2313 
2314 	if (WARN_ON_ONCE(op >= BPF_AUDIT_MAX))
2315 		return;
2316 	if (audit_enabled == AUDIT_OFF)
2317 		return;
2318 	if (!in_hardirq() && !irqs_disabled())
2319 		ctx = audit_context();
2320 	ab = audit_log_start(ctx, GFP_ATOMIC, AUDIT_BPF);
2321 	if (unlikely(!ab))
2322 		return;
2323 	audit_log_format(ab, "prog-id=%u op=%s",
2324 			 prog->aux->id, bpf_audit_str[op]);
2325 	audit_log_end(ab);
2326 }
2327 
2328 static int bpf_prog_alloc_id(struct bpf_prog *prog)
2329 {
2330 	int id;
2331 
2332 	idr_preload(GFP_KERNEL);
2333 	spin_lock_bh(&prog_idr_lock);
2334 	id = idr_alloc_cyclic(&prog_idr, prog, 1, INT_MAX, GFP_ATOMIC);
2335 	if (id > 0)
2336 		prog->aux->id = id;
2337 	spin_unlock_bh(&prog_idr_lock);
2338 	idr_preload_end();
2339 
2340 	/* id is in [1, INT_MAX) */
2341 	if (WARN_ON_ONCE(!id))
2342 		return -ENOSPC;
2343 
2344 	return id > 0 ? 0 : id;
2345 }
2346 
2347 void bpf_prog_free_id(struct bpf_prog *prog)
2348 {
2349 	unsigned long flags;
2350 
2351 	/* cBPF to eBPF migrations are currently not in the idr store.
2352 	 * Offloaded programs are removed from the store when their device
2353 	 * disappears - even if someone grabs an fd to them they are unusable,
2354 	 * simply waiting for refcnt to drop to be freed.
2355 	 */
2356 	if (!prog->aux->id)
2357 		return;
2358 
2359 	spin_lock_irqsave(&prog_idr_lock, flags);
2360 	idr_remove(&prog_idr, prog->aux->id);
2361 	prog->aux->id = 0;
2362 	spin_unlock_irqrestore(&prog_idr_lock, flags);
2363 }
2364 
2365 static void __bpf_prog_put_rcu(struct rcu_head *rcu)
2366 {
2367 	struct bpf_prog_aux *aux = container_of(rcu, struct bpf_prog_aux, rcu);
2368 
2369 	kvfree(aux->func_info);
2370 	kfree(aux->func_info_aux);
2371 	free_uid(aux->user);
2372 	security_bpf_prog_free(aux->prog);
2373 	bpf_prog_free(aux->prog);
2374 }
2375 
2376 static void __bpf_prog_put_noref(struct bpf_prog *prog, bool deferred)
2377 {
2378 	bpf_prog_kallsyms_del_all(prog);
2379 	btf_put(prog->aux->btf);
2380 	module_put(prog->aux->mod);
2381 	kvfree(prog->aux->jited_linfo);
2382 	kvfree(prog->aux->linfo);
2383 	kfree(prog->aux->kfunc_tab);
2384 	kfree(prog->aux->ctx_arg_info);
2385 	if (prog->aux->attach_btf)
2386 		btf_put(prog->aux->attach_btf);
2387 
2388 	if (deferred) {
2389 		if (prog->sleepable)
2390 			call_rcu_tasks_trace(&prog->aux->rcu, __bpf_prog_put_rcu);
2391 		else
2392 			call_rcu(&prog->aux->rcu, __bpf_prog_put_rcu);
2393 	} else {
2394 		__bpf_prog_put_rcu(&prog->aux->rcu);
2395 	}
2396 }
2397 
2398 static void bpf_prog_put_deferred(struct work_struct *work)
2399 {
2400 	struct bpf_prog_aux *aux;
2401 	struct bpf_prog *prog;
2402 
2403 	aux = container_of(work, struct bpf_prog_aux, work);
2404 	prog = aux->prog;
2405 	perf_event_bpf_event(prog, PERF_BPF_EVENT_PROG_UNLOAD, 0);
2406 	bpf_audit_prog(prog, BPF_AUDIT_UNLOAD);
2407 	bpf_prog_free_id(prog);
2408 	__bpf_prog_put_noref(prog, true);
2409 }
2410 
2411 static void __bpf_prog_put(struct bpf_prog *prog)
2412 {
2413 	struct bpf_prog_aux *aux = prog->aux;
2414 
2415 	if (atomic64_dec_and_test(&aux->refcnt)) {
2416 		if (in_hardirq() || irqs_disabled()) {
2417 			INIT_WORK(&aux->work, bpf_prog_put_deferred);
2418 			schedule_work(&aux->work);
2419 		} else {
2420 			bpf_prog_put_deferred(&aux->work);
2421 		}
2422 	}
2423 }
2424 
2425 void bpf_prog_put(struct bpf_prog *prog)
2426 {
2427 	__bpf_prog_put(prog);
2428 }
2429 EXPORT_SYMBOL_GPL(bpf_prog_put);
2430 
2431 static int bpf_prog_release(struct inode *inode, struct file *filp)
2432 {
2433 	struct bpf_prog *prog = filp->private_data;
2434 
2435 	bpf_prog_put(prog);
2436 	return 0;
2437 }
2438 
2439 struct bpf_prog_kstats {
2440 	u64 nsecs;
2441 	u64 cnt;
2442 	u64 misses;
2443 };
2444 
2445 void notrace bpf_prog_inc_misses_counter(struct bpf_prog *prog)
2446 {
2447 	struct bpf_prog_stats *stats;
2448 	unsigned int flags;
2449 
2450 	if (unlikely(!prog->stats))
2451 		return;
2452 
2453 	stats = this_cpu_ptr(prog->stats);
2454 	flags = u64_stats_update_begin_irqsave(&stats->syncp);
2455 	u64_stats_inc(&stats->misses);
2456 	u64_stats_update_end_irqrestore(&stats->syncp, flags);
2457 }
2458 
2459 static void bpf_prog_get_stats(const struct bpf_prog *prog,
2460 			       struct bpf_prog_kstats *stats)
2461 {
2462 	u64 nsecs = 0, cnt = 0, misses = 0;
2463 	int cpu;
2464 
2465 	for_each_possible_cpu(cpu) {
2466 		const struct bpf_prog_stats *st;
2467 		unsigned int start;
2468 		u64 tnsecs, tcnt, tmisses;
2469 
2470 		st = per_cpu_ptr(prog->stats, cpu);
2471 		do {
2472 			start = u64_stats_fetch_begin(&st->syncp);
2473 			tnsecs = u64_stats_read(&st->nsecs);
2474 			tcnt = u64_stats_read(&st->cnt);
2475 			tmisses = u64_stats_read(&st->misses);
2476 		} while (u64_stats_fetch_retry(&st->syncp, start));
2477 		nsecs += tnsecs;
2478 		cnt += tcnt;
2479 		misses += tmisses;
2480 	}
2481 	stats->nsecs = nsecs;
2482 	stats->cnt = cnt;
2483 	stats->misses = misses;
2484 }
2485 
2486 #ifdef CONFIG_PROC_FS
2487 static void bpf_prog_show_fdinfo(struct seq_file *m, struct file *filp)
2488 {
2489 	const struct bpf_prog *prog = filp->private_data;
2490 	char prog_tag[sizeof(prog->tag) * 2 + 1] = { };
2491 	struct bpf_prog_kstats stats;
2492 
2493 	bpf_prog_get_stats(prog, &stats);
2494 	bin2hex(prog_tag, prog->tag, sizeof(prog->tag));
2495 	seq_printf(m,
2496 		   "prog_type:\t%u\n"
2497 		   "prog_jited:\t%u\n"
2498 		   "prog_tag:\t%s\n"
2499 		   "memlock:\t%llu\n"
2500 		   "prog_id:\t%u\n"
2501 		   "run_time_ns:\t%llu\n"
2502 		   "run_cnt:\t%llu\n"
2503 		   "recursion_misses:\t%llu\n"
2504 		   "verified_insns:\t%u\n",
2505 		   prog->type,
2506 		   prog->jited,
2507 		   prog_tag,
2508 		   prog->pages * 1ULL << PAGE_SHIFT,
2509 		   prog->aux->id,
2510 		   stats.nsecs,
2511 		   stats.cnt,
2512 		   stats.misses,
2513 		   prog->aux->verified_insns);
2514 }
2515 #endif
2516 
2517 const struct file_operations bpf_prog_fops = {
2518 #ifdef CONFIG_PROC_FS
2519 	.show_fdinfo	= bpf_prog_show_fdinfo,
2520 #endif
2521 	.release	= bpf_prog_release,
2522 	.read		= bpf_dummy_read,
2523 	.write		= bpf_dummy_write,
2524 };
2525 
2526 int bpf_prog_new_fd(struct bpf_prog *prog)
2527 {
2528 	int ret;
2529 
2530 	ret = security_bpf_prog(prog);
2531 	if (ret < 0)
2532 		return ret;
2533 
2534 	return anon_inode_getfd("bpf-prog", &bpf_prog_fops, prog,
2535 				O_RDWR | O_CLOEXEC);
2536 }
2537 
2538 void bpf_prog_add(struct bpf_prog *prog, int i)
2539 {
2540 	atomic64_add(i, &prog->aux->refcnt);
2541 }
2542 EXPORT_SYMBOL_GPL(bpf_prog_add);
2543 
2544 void bpf_prog_sub(struct bpf_prog *prog, int i)
2545 {
2546 	/* Only to be used for undoing previous bpf_prog_add() in some
2547 	 * error path. We still know that another entity in our call
2548 	 * path holds a reference to the program, thus atomic_sub() can
2549 	 * be safely used in such cases!
2550 	 */
2551 	WARN_ON(atomic64_sub_return(i, &prog->aux->refcnt) == 0);
2552 }
2553 EXPORT_SYMBOL_GPL(bpf_prog_sub);
2554 
2555 void bpf_prog_inc(struct bpf_prog *prog)
2556 {
2557 	atomic64_inc(&prog->aux->refcnt);
2558 }
2559 EXPORT_SYMBOL_GPL(bpf_prog_inc);
2560 
2561 /* prog_idr_lock should have been held */
2562 struct bpf_prog *bpf_prog_inc_not_zero(struct bpf_prog *prog)
2563 {
2564 	int refold;
2565 
2566 	refold = atomic64_fetch_add_unless(&prog->aux->refcnt, 1, 0);
2567 
2568 	if (!refold)
2569 		return ERR_PTR(-ENOENT);
2570 
2571 	return prog;
2572 }
2573 EXPORT_SYMBOL_GPL(bpf_prog_inc_not_zero);
2574 
2575 bool bpf_prog_get_ok(struct bpf_prog *prog,
2576 			    enum bpf_prog_type *attach_type, bool attach_drv)
2577 {
2578 	/* not an attachment, just a refcount inc, always allow */
2579 	if (!attach_type)
2580 		return true;
2581 
2582 	if (prog->type != *attach_type)
2583 		return false;
2584 	if (bpf_prog_is_offloaded(prog->aux) && !attach_drv)
2585 		return false;
2586 
2587 	return true;
2588 }
2589 
2590 static struct bpf_prog *__bpf_prog_get(u32 ufd, enum bpf_prog_type *attach_type,
2591 				       bool attach_drv)
2592 {
2593 	CLASS(fd, f)(ufd);
2594 	struct bpf_prog *prog;
2595 
2596 	if (fd_empty(f))
2597 		return ERR_PTR(-EBADF);
2598 	if (fd_file(f)->f_op != &bpf_prog_fops)
2599 		return ERR_PTR(-EINVAL);
2600 
2601 	prog = fd_file(f)->private_data;
2602 	if (!bpf_prog_get_ok(prog, attach_type, attach_drv))
2603 		return ERR_PTR(-EINVAL);
2604 
2605 	bpf_prog_inc(prog);
2606 	return prog;
2607 }
2608 
2609 struct bpf_prog *bpf_prog_get(u32 ufd)
2610 {
2611 	return __bpf_prog_get(ufd, NULL, false);
2612 }
2613 
2614 struct bpf_prog *bpf_prog_get_type_dev(u32 ufd, enum bpf_prog_type type,
2615 				       bool attach_drv)
2616 {
2617 	return __bpf_prog_get(ufd, &type, attach_drv);
2618 }
2619 EXPORT_SYMBOL_GPL(bpf_prog_get_type_dev);
2620 
2621 /* Initially all BPF programs could be loaded w/o specifying
2622  * expected_attach_type. Later for some of them specifying expected_attach_type
2623  * at load time became required so that program could be validated properly.
2624  * Programs of types that are allowed to be loaded both w/ and w/o (for
2625  * backward compatibility) expected_attach_type, should have the default attach
2626  * type assigned to expected_attach_type for the latter case, so that it can be
2627  * validated later at attach time.
2628  *
2629  * bpf_prog_load_fixup_attach_type() sets expected_attach_type in @attr if
2630  * prog type requires it but has some attach types that have to be backward
2631  * compatible.
2632  */
2633 static void bpf_prog_load_fixup_attach_type(union bpf_attr *attr)
2634 {
2635 	switch (attr->prog_type) {
2636 	case BPF_PROG_TYPE_CGROUP_SOCK:
2637 		/* Unfortunately BPF_ATTACH_TYPE_UNSPEC enumeration doesn't
2638 		 * exist so checking for non-zero is the way to go here.
2639 		 */
2640 		if (!attr->expected_attach_type)
2641 			attr->expected_attach_type =
2642 				BPF_CGROUP_INET_SOCK_CREATE;
2643 		break;
2644 	case BPF_PROG_TYPE_SK_REUSEPORT:
2645 		if (!attr->expected_attach_type)
2646 			attr->expected_attach_type =
2647 				BPF_SK_REUSEPORT_SELECT;
2648 		break;
2649 	}
2650 }
2651 
2652 static int
2653 bpf_prog_load_check_attach(enum bpf_prog_type prog_type,
2654 			   enum bpf_attach_type expected_attach_type,
2655 			   struct btf *attach_btf, u32 btf_id,
2656 			   struct bpf_prog *dst_prog)
2657 {
2658 	if (btf_id) {
2659 		if (btf_id > BTF_MAX_TYPE)
2660 			return -EINVAL;
2661 
2662 		if (!attach_btf && !dst_prog)
2663 			return -EINVAL;
2664 
2665 		switch (prog_type) {
2666 		case BPF_PROG_TYPE_TRACING:
2667 		case BPF_PROG_TYPE_LSM:
2668 		case BPF_PROG_TYPE_STRUCT_OPS:
2669 		case BPF_PROG_TYPE_EXT:
2670 			break;
2671 		default:
2672 			return -EINVAL;
2673 		}
2674 	}
2675 
2676 	if (attach_btf && (!btf_id || dst_prog))
2677 		return -EINVAL;
2678 
2679 	if (dst_prog && prog_type != BPF_PROG_TYPE_TRACING &&
2680 	    prog_type != BPF_PROG_TYPE_EXT)
2681 		return -EINVAL;
2682 
2683 	switch (prog_type) {
2684 	case BPF_PROG_TYPE_CGROUP_SOCK:
2685 		switch (expected_attach_type) {
2686 		case BPF_CGROUP_INET_SOCK_CREATE:
2687 		case BPF_CGROUP_INET_SOCK_RELEASE:
2688 		case BPF_CGROUP_INET4_POST_BIND:
2689 		case BPF_CGROUP_INET6_POST_BIND:
2690 			return 0;
2691 		default:
2692 			return -EINVAL;
2693 		}
2694 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
2695 		switch (expected_attach_type) {
2696 		case BPF_CGROUP_INET4_BIND:
2697 		case BPF_CGROUP_INET6_BIND:
2698 		case BPF_CGROUP_INET4_CONNECT:
2699 		case BPF_CGROUP_INET6_CONNECT:
2700 		case BPF_CGROUP_UNIX_CONNECT:
2701 		case BPF_CGROUP_INET4_GETPEERNAME:
2702 		case BPF_CGROUP_INET6_GETPEERNAME:
2703 		case BPF_CGROUP_UNIX_GETPEERNAME:
2704 		case BPF_CGROUP_INET4_GETSOCKNAME:
2705 		case BPF_CGROUP_INET6_GETSOCKNAME:
2706 		case BPF_CGROUP_UNIX_GETSOCKNAME:
2707 		case BPF_CGROUP_UDP4_SENDMSG:
2708 		case BPF_CGROUP_UDP6_SENDMSG:
2709 		case BPF_CGROUP_UNIX_SENDMSG:
2710 		case BPF_CGROUP_UDP4_RECVMSG:
2711 		case BPF_CGROUP_UDP6_RECVMSG:
2712 		case BPF_CGROUP_UNIX_RECVMSG:
2713 			return 0;
2714 		default:
2715 			return -EINVAL;
2716 		}
2717 	case BPF_PROG_TYPE_CGROUP_SKB:
2718 		switch (expected_attach_type) {
2719 		case BPF_CGROUP_INET_INGRESS:
2720 		case BPF_CGROUP_INET_EGRESS:
2721 			return 0;
2722 		default:
2723 			return -EINVAL;
2724 		}
2725 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
2726 		switch (expected_attach_type) {
2727 		case BPF_CGROUP_SETSOCKOPT:
2728 		case BPF_CGROUP_GETSOCKOPT:
2729 			return 0;
2730 		default:
2731 			return -EINVAL;
2732 		}
2733 	case BPF_PROG_TYPE_SK_LOOKUP:
2734 		if (expected_attach_type == BPF_SK_LOOKUP)
2735 			return 0;
2736 		return -EINVAL;
2737 	case BPF_PROG_TYPE_SK_REUSEPORT:
2738 		switch (expected_attach_type) {
2739 		case BPF_SK_REUSEPORT_SELECT:
2740 		case BPF_SK_REUSEPORT_SELECT_OR_MIGRATE:
2741 			return 0;
2742 		default:
2743 			return -EINVAL;
2744 		}
2745 	case BPF_PROG_TYPE_NETFILTER:
2746 		if (expected_attach_type == BPF_NETFILTER)
2747 			return 0;
2748 		return -EINVAL;
2749 	case BPF_PROG_TYPE_SYSCALL:
2750 	case BPF_PROG_TYPE_EXT:
2751 		if (expected_attach_type)
2752 			return -EINVAL;
2753 		fallthrough;
2754 	default:
2755 		return 0;
2756 	}
2757 }
2758 
2759 static bool is_net_admin_prog_type(enum bpf_prog_type prog_type)
2760 {
2761 	switch (prog_type) {
2762 	case BPF_PROG_TYPE_SCHED_CLS:
2763 	case BPF_PROG_TYPE_SCHED_ACT:
2764 	case BPF_PROG_TYPE_XDP:
2765 	case BPF_PROG_TYPE_LWT_IN:
2766 	case BPF_PROG_TYPE_LWT_OUT:
2767 	case BPF_PROG_TYPE_LWT_XMIT:
2768 	case BPF_PROG_TYPE_LWT_SEG6LOCAL:
2769 	case BPF_PROG_TYPE_SK_SKB:
2770 	case BPF_PROG_TYPE_SK_MSG:
2771 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
2772 	case BPF_PROG_TYPE_CGROUP_DEVICE:
2773 	case BPF_PROG_TYPE_CGROUP_SOCK:
2774 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
2775 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
2776 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
2777 	case BPF_PROG_TYPE_SOCK_OPS:
2778 	case BPF_PROG_TYPE_EXT: /* extends any prog */
2779 	case BPF_PROG_TYPE_NETFILTER:
2780 		return true;
2781 	case BPF_PROG_TYPE_CGROUP_SKB:
2782 		/* always unpriv */
2783 	case BPF_PROG_TYPE_SK_REUSEPORT:
2784 		/* equivalent to SOCKET_FILTER. need CAP_BPF only */
2785 	default:
2786 		return false;
2787 	}
2788 }
2789 
2790 static bool is_perfmon_prog_type(enum bpf_prog_type prog_type)
2791 {
2792 	switch (prog_type) {
2793 	case BPF_PROG_TYPE_KPROBE:
2794 	case BPF_PROG_TYPE_TRACEPOINT:
2795 	case BPF_PROG_TYPE_PERF_EVENT:
2796 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
2797 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
2798 	case BPF_PROG_TYPE_TRACING:
2799 	case BPF_PROG_TYPE_LSM:
2800 	case BPF_PROG_TYPE_STRUCT_OPS: /* has access to struct sock */
2801 	case BPF_PROG_TYPE_EXT: /* extends any prog */
2802 		return true;
2803 	default:
2804 		return false;
2805 	}
2806 }
2807 
2808 static int bpf_prog_verify_signature(struct bpf_prog *prog, union bpf_attr *attr,
2809 				     bool is_kernel)
2810 {
2811 	bpfptr_t usig = make_bpfptr(attr->signature, is_kernel);
2812 	struct bpf_dynptr_kern sig_ptr, insns_ptr;
2813 	struct bpf_key *key = NULL;
2814 	void *sig;
2815 	int err = 0;
2816 
2817 	/*
2818 	 * Don't attempt to use kmalloc_large or vmalloc for signatures.
2819 	 * Practical signature for BPF program should be below this limit.
2820 	 */
2821 	if (attr->signature_size > KMALLOC_MAX_CACHE_SIZE)
2822 		return -EINVAL;
2823 
2824 	if (system_keyring_id_check(attr->keyring_id) == 0)
2825 		key = bpf_lookup_system_key(attr->keyring_id);
2826 	else
2827 		key = bpf_lookup_user_key(attr->keyring_id, 0);
2828 
2829 	if (!key)
2830 		return -EINVAL;
2831 
2832 	sig = kvmemdup_bpfptr(usig, attr->signature_size);
2833 	if (IS_ERR(sig)) {
2834 		bpf_key_put(key);
2835 		return -ENOMEM;
2836 	}
2837 
2838 	bpf_dynptr_init(&sig_ptr, sig, BPF_DYNPTR_TYPE_LOCAL, 0,
2839 			attr->signature_size);
2840 	bpf_dynptr_init(&insns_ptr, prog->insnsi, BPF_DYNPTR_TYPE_LOCAL, 0,
2841 			prog->len * sizeof(struct bpf_insn));
2842 
2843 	err = bpf_verify_pkcs7_signature((struct bpf_dynptr *)&insns_ptr,
2844 					 (struct bpf_dynptr *)&sig_ptr, key);
2845 
2846 	bpf_key_put(key);
2847 	kvfree(sig);
2848 	return err;
2849 }
2850 
2851 static int bpf_prog_mark_insn_arrays_ready(struct bpf_prog *prog)
2852 {
2853 	int err;
2854 	int i;
2855 
2856 	for (i = 0; i < prog->aux->used_map_cnt; i++) {
2857 		if (prog->aux->used_maps[i]->map_type != BPF_MAP_TYPE_INSN_ARRAY)
2858 			continue;
2859 
2860 		err = bpf_insn_array_ready(prog->aux->used_maps[i]);
2861 		if (err)
2862 			return err;
2863 	}
2864 
2865 	return 0;
2866 }
2867 
2868 /* last field in 'union bpf_attr' used by this command */
2869 #define BPF_PROG_LOAD_LAST_FIELD keyring_id
2870 
2871 static int bpf_prog_load(union bpf_attr *attr, bpfptr_t uattr, u32 uattr_size)
2872 {
2873 	enum bpf_prog_type type = attr->prog_type;
2874 	struct bpf_prog *prog, *dst_prog = NULL;
2875 	struct btf *attach_btf = NULL;
2876 	struct bpf_token *token = NULL;
2877 	bool bpf_cap;
2878 	int err;
2879 	char license[128];
2880 
2881 	if (CHECK_ATTR(BPF_PROG_LOAD))
2882 		return -EINVAL;
2883 
2884 	if (attr->prog_flags & ~(BPF_F_STRICT_ALIGNMENT |
2885 				 BPF_F_ANY_ALIGNMENT |
2886 				 BPF_F_TEST_STATE_FREQ |
2887 				 BPF_F_SLEEPABLE |
2888 				 BPF_F_TEST_RND_HI32 |
2889 				 BPF_F_XDP_HAS_FRAGS |
2890 				 BPF_F_XDP_DEV_BOUND_ONLY |
2891 				 BPF_F_TEST_REG_INVARIANTS |
2892 				 BPF_F_TOKEN_FD))
2893 		return -EINVAL;
2894 
2895 	bpf_prog_load_fixup_attach_type(attr);
2896 
2897 	if (attr->prog_flags & BPF_F_TOKEN_FD) {
2898 		token = bpf_token_get_from_fd(attr->prog_token_fd);
2899 		if (IS_ERR(token))
2900 			return PTR_ERR(token);
2901 		/* if current token doesn't grant prog loading permissions,
2902 		 * then we can't use this token, so ignore it and rely on
2903 		 * system-wide capabilities checks
2904 		 */
2905 		if (!bpf_token_allow_cmd(token, BPF_PROG_LOAD) ||
2906 		    !bpf_token_allow_prog_type(token, attr->prog_type,
2907 					       attr->expected_attach_type)) {
2908 			bpf_token_put(token);
2909 			token = NULL;
2910 		}
2911 	}
2912 
2913 	bpf_cap = bpf_token_capable(token, CAP_BPF);
2914 	err = -EPERM;
2915 
2916 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS) &&
2917 	    (attr->prog_flags & BPF_F_ANY_ALIGNMENT) &&
2918 	    !bpf_cap)
2919 		goto put_token;
2920 
2921 	/* Intent here is for unprivileged_bpf_disabled to block BPF program
2922 	 * creation for unprivileged users; other actions depend
2923 	 * on fd availability and access to bpffs, so are dependent on
2924 	 * object creation success. Even with unprivileged BPF disabled,
2925 	 * capability checks are still carried out for these
2926 	 * and other operations.
2927 	 */
2928 	if (sysctl_unprivileged_bpf_disabled && !bpf_cap)
2929 		goto put_token;
2930 
2931 	if (attr->insn_cnt == 0 ||
2932 	    attr->insn_cnt > (bpf_cap ? BPF_COMPLEXITY_LIMIT_INSNS : BPF_MAXINSNS)) {
2933 		err = -E2BIG;
2934 		goto put_token;
2935 	}
2936 	if (type != BPF_PROG_TYPE_SOCKET_FILTER &&
2937 	    type != BPF_PROG_TYPE_CGROUP_SKB &&
2938 	    !bpf_cap)
2939 		goto put_token;
2940 
2941 	if (is_net_admin_prog_type(type) && !bpf_token_capable(token, CAP_NET_ADMIN))
2942 		goto put_token;
2943 	if (is_perfmon_prog_type(type) && !bpf_token_capable(token, CAP_PERFMON))
2944 		goto put_token;
2945 
2946 	/* attach_prog_fd/attach_btf_obj_fd can specify fd of either bpf_prog
2947 	 * or btf, we need to check which one it is
2948 	 */
2949 	if (attr->attach_prog_fd) {
2950 		dst_prog = bpf_prog_get(attr->attach_prog_fd);
2951 		if (IS_ERR(dst_prog)) {
2952 			dst_prog = NULL;
2953 			attach_btf = btf_get_by_fd(attr->attach_btf_obj_fd);
2954 			if (IS_ERR(attach_btf)) {
2955 				err = -EINVAL;
2956 				goto put_token;
2957 			}
2958 			if (!btf_is_kernel(attach_btf)) {
2959 				/* attaching through specifying bpf_prog's BTF
2960 				 * objects directly might be supported eventually
2961 				 */
2962 				btf_put(attach_btf);
2963 				err = -ENOTSUPP;
2964 				goto put_token;
2965 			}
2966 		}
2967 	} else if (attr->attach_btf_id) {
2968 		/* fall back to vmlinux BTF, if BTF type ID is specified */
2969 		attach_btf = bpf_get_btf_vmlinux();
2970 		if (IS_ERR(attach_btf)) {
2971 			err = PTR_ERR(attach_btf);
2972 			goto put_token;
2973 		}
2974 		if (!attach_btf) {
2975 			err = -EINVAL;
2976 			goto put_token;
2977 		}
2978 		btf_get(attach_btf);
2979 	}
2980 
2981 	if (bpf_prog_load_check_attach(type, attr->expected_attach_type,
2982 				       attach_btf, attr->attach_btf_id,
2983 				       dst_prog)) {
2984 		if (dst_prog)
2985 			bpf_prog_put(dst_prog);
2986 		if (attach_btf)
2987 			btf_put(attach_btf);
2988 		err = -EINVAL;
2989 		goto put_token;
2990 	}
2991 
2992 	/* plain bpf_prog allocation */
2993 	prog = bpf_prog_alloc(bpf_prog_size(attr->insn_cnt), GFP_USER);
2994 	if (!prog) {
2995 		if (dst_prog)
2996 			bpf_prog_put(dst_prog);
2997 		if (attach_btf)
2998 			btf_put(attach_btf);
2999 		err = -EINVAL;
3000 		goto put_token;
3001 	}
3002 
3003 	prog->expected_attach_type = attr->expected_attach_type;
3004 	prog->sleepable = !!(attr->prog_flags & BPF_F_SLEEPABLE);
3005 	prog->aux->attach_btf = attach_btf;
3006 	prog->aux->attach_btf_id = attr->attach_btf_id;
3007 	prog->aux->dst_prog = dst_prog;
3008 	prog->aux->dev_bound = !!attr->prog_ifindex;
3009 	prog->aux->xdp_has_frags = attr->prog_flags & BPF_F_XDP_HAS_FRAGS;
3010 
3011 	/* move token into prog->aux, reuse taken refcnt */
3012 	prog->aux->token = token;
3013 	token = NULL;
3014 
3015 	prog->aux->user = get_current_user();
3016 	prog->len = attr->insn_cnt;
3017 
3018 	err = -EFAULT;
3019 	if (copy_from_bpfptr(prog->insns,
3020 			     make_bpfptr(attr->insns, uattr.is_kernel),
3021 			     bpf_prog_insn_size(prog)) != 0)
3022 		goto free_prog;
3023 	/* copy eBPF program license from user space */
3024 	if (strncpy_from_bpfptr(license,
3025 				make_bpfptr(attr->license, uattr.is_kernel),
3026 				sizeof(license) - 1) < 0)
3027 		goto free_prog;
3028 	license[sizeof(license) - 1] = 0;
3029 
3030 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
3031 	prog->gpl_compatible = license_is_gpl_compatible(license) ? 1 : 0;
3032 
3033 	if (attr->signature) {
3034 		err = bpf_prog_verify_signature(prog, attr, uattr.is_kernel);
3035 		if (err)
3036 			goto free_prog;
3037 	}
3038 
3039 	prog->orig_prog = NULL;
3040 	prog->jited = 0;
3041 
3042 	atomic64_set(&prog->aux->refcnt, 1);
3043 
3044 	if (bpf_prog_is_dev_bound(prog->aux)) {
3045 		err = bpf_prog_dev_bound_init(prog, attr);
3046 		if (err)
3047 			goto free_prog;
3048 	}
3049 
3050 	if (type == BPF_PROG_TYPE_EXT && dst_prog &&
3051 	    bpf_prog_is_dev_bound(dst_prog->aux)) {
3052 		err = bpf_prog_dev_bound_inherit(prog, dst_prog);
3053 		if (err)
3054 			goto free_prog;
3055 	}
3056 
3057 	/*
3058 	 * Bookkeeping for managing the program attachment chain.
3059 	 *
3060 	 * It might be tempting to set attach_tracing_prog flag at the attachment
3061 	 * time, but this will not prevent from loading bunch of tracing prog
3062 	 * first, then attach them one to another.
3063 	 *
3064 	 * The flag attach_tracing_prog is set for the whole program lifecycle, and
3065 	 * doesn't have to be cleared in bpf_tracing_link_release, since tracing
3066 	 * programs cannot change attachment target.
3067 	 */
3068 	if (type == BPF_PROG_TYPE_TRACING && dst_prog &&
3069 	    dst_prog->type == BPF_PROG_TYPE_TRACING) {
3070 		prog->aux->attach_tracing_prog = true;
3071 	}
3072 
3073 	/* find program type: socket_filter vs tracing_filter */
3074 	err = find_prog_type(type, prog);
3075 	if (err < 0)
3076 		goto free_prog;
3077 
3078 	prog->aux->load_time = ktime_get_boottime_ns();
3079 	err = bpf_obj_name_cpy(prog->aux->name, attr->prog_name,
3080 			       sizeof(attr->prog_name));
3081 	if (err < 0)
3082 		goto free_prog;
3083 
3084 	err = security_bpf_prog_load(prog, attr, token, uattr.is_kernel);
3085 	if (err)
3086 		goto free_prog_sec;
3087 
3088 	/* run eBPF verifier */
3089 	err = bpf_check(&prog, attr, uattr, uattr_size);
3090 	if (err < 0)
3091 		goto free_used_maps;
3092 
3093 	prog = bpf_prog_select_runtime(prog, &err);
3094 	if (err < 0)
3095 		goto free_used_maps;
3096 
3097 	err = bpf_prog_mark_insn_arrays_ready(prog);
3098 	if (err < 0)
3099 		goto free_used_maps;
3100 
3101 	err = bpf_prog_alloc_id(prog);
3102 	if (err)
3103 		goto free_used_maps;
3104 
3105 	/* Upon success of bpf_prog_alloc_id(), the BPF prog is
3106 	 * effectively publicly exposed. However, retrieving via
3107 	 * bpf_prog_get_fd_by_id() will take another reference,
3108 	 * therefore it cannot be gone underneath us.
3109 	 *
3110 	 * Only for the time /after/ successful bpf_prog_new_fd()
3111 	 * and before returning to userspace, we might just hold
3112 	 * one reference and any parallel close on that fd could
3113 	 * rip everything out. Hence, below notifications must
3114 	 * happen before bpf_prog_new_fd().
3115 	 *
3116 	 * Also, any failure handling from this point onwards must
3117 	 * be using bpf_prog_put() given the program is exposed.
3118 	 */
3119 	bpf_prog_kallsyms_add(prog);
3120 	perf_event_bpf_event(prog, PERF_BPF_EVENT_PROG_LOAD, 0);
3121 	bpf_audit_prog(prog, BPF_AUDIT_LOAD);
3122 
3123 	err = bpf_prog_new_fd(prog);
3124 	if (err < 0)
3125 		bpf_prog_put(prog);
3126 	return err;
3127 
3128 free_used_maps:
3129 	/* In case we have subprogs, we need to wait for a grace
3130 	 * period before we can tear down JIT memory since symbols
3131 	 * are already exposed under kallsyms.
3132 	 */
3133 	__bpf_prog_put_noref(prog, prog->aux->real_func_cnt);
3134 	return err;
3135 
3136 free_prog_sec:
3137 	security_bpf_prog_free(prog);
3138 free_prog:
3139 	free_uid(prog->aux->user);
3140 	if (prog->aux->attach_btf)
3141 		btf_put(prog->aux->attach_btf);
3142 	bpf_prog_free(prog);
3143 put_token:
3144 	bpf_token_put(token);
3145 	return err;
3146 }
3147 
3148 #define BPF_OBJ_LAST_FIELD path_fd
3149 
3150 static int bpf_obj_pin(const union bpf_attr *attr)
3151 {
3152 	int path_fd;
3153 
3154 	if (CHECK_ATTR(BPF_OBJ) || attr->file_flags & ~BPF_F_PATH_FD)
3155 		return -EINVAL;
3156 
3157 	/* path_fd has to be accompanied by BPF_F_PATH_FD flag */
3158 	if (!(attr->file_flags & BPF_F_PATH_FD) && attr->path_fd)
3159 		return -EINVAL;
3160 
3161 	path_fd = attr->file_flags & BPF_F_PATH_FD ? attr->path_fd : AT_FDCWD;
3162 	return bpf_obj_pin_user(attr->bpf_fd, path_fd,
3163 				u64_to_user_ptr(attr->pathname));
3164 }
3165 
3166 static int bpf_obj_get(const union bpf_attr *attr)
3167 {
3168 	int path_fd;
3169 
3170 	if (CHECK_ATTR(BPF_OBJ) || attr->bpf_fd != 0 ||
3171 	    attr->file_flags & ~(BPF_OBJ_FLAG_MASK | BPF_F_PATH_FD))
3172 		return -EINVAL;
3173 
3174 	/* path_fd has to be accompanied by BPF_F_PATH_FD flag */
3175 	if (!(attr->file_flags & BPF_F_PATH_FD) && attr->path_fd)
3176 		return -EINVAL;
3177 
3178 	path_fd = attr->file_flags & BPF_F_PATH_FD ? attr->path_fd : AT_FDCWD;
3179 	return bpf_obj_get_user(path_fd, u64_to_user_ptr(attr->pathname),
3180 				attr->file_flags);
3181 }
3182 
3183 /* bpf_link_init_sleepable() allows to specify whether BPF link itself has
3184  * "sleepable" semantics, which normally would mean that BPF link's attach
3185  * hook can dereference link or link's underlying program for some time after
3186  * detachment due to RCU Tasks Trace-based lifetime protection scheme.
3187  * BPF program itself can be non-sleepable, yet, because it's transitively
3188  * reachable through BPF link, its freeing has to be delayed until after RCU
3189  * Tasks Trace GP.
3190  */
3191 void bpf_link_init_sleepable(struct bpf_link *link, enum bpf_link_type type,
3192 			     const struct bpf_link_ops *ops, struct bpf_prog *prog,
3193 			     enum bpf_attach_type attach_type, bool sleepable)
3194 {
3195 	WARN_ON(ops->dealloc && ops->dealloc_deferred);
3196 	atomic64_set(&link->refcnt, 1);
3197 	link->type = type;
3198 	link->sleepable = sleepable;
3199 	link->id = 0;
3200 	link->ops = ops;
3201 	link->prog = prog;
3202 	link->attach_type = attach_type;
3203 }
3204 
3205 void bpf_link_init(struct bpf_link *link, enum bpf_link_type type,
3206 		   const struct bpf_link_ops *ops, struct bpf_prog *prog,
3207 		   enum bpf_attach_type attach_type)
3208 {
3209 	bpf_link_init_sleepable(link, type, ops, prog, attach_type, false);
3210 }
3211 
3212 static void bpf_link_free_id(int id)
3213 {
3214 	if (!id)
3215 		return;
3216 
3217 	spin_lock_bh(&link_idr_lock);
3218 	idr_remove(&link_idr, id);
3219 	spin_unlock_bh(&link_idr_lock);
3220 }
3221 
3222 /* Clean up bpf_link and corresponding anon_inode file and FD. After
3223  * anon_inode is created, bpf_link can't be just kfree()'d due to deferred
3224  * anon_inode's release() call. This helper marks bpf_link as
3225  * defunct, releases anon_inode file and puts reserved FD. bpf_prog's refcnt
3226  * is not decremented, it's the responsibility of a calling code that failed
3227  * to complete bpf_link initialization.
3228  * This helper eventually calls link's dealloc callback, but does not call
3229  * link's release callback.
3230  */
3231 void bpf_link_cleanup(struct bpf_link_primer *primer)
3232 {
3233 	primer->link->prog = NULL;
3234 	bpf_link_free_id(primer->id);
3235 	fput(primer->file);
3236 	put_unused_fd(primer->fd);
3237 }
3238 
3239 void bpf_link_inc(struct bpf_link *link)
3240 {
3241 	atomic64_inc(&link->refcnt);
3242 }
3243 
3244 static void bpf_link_dealloc(struct bpf_link *link)
3245 {
3246 	/* now that we know that bpf_link itself can't be reached, put underlying BPF program */
3247 	if (link->prog)
3248 		bpf_prog_put(link->prog);
3249 
3250 	/* free bpf_link and its containing memory */
3251 	if (link->ops->dealloc_deferred)
3252 		link->ops->dealloc_deferred(link);
3253 	else
3254 		link->ops->dealloc(link);
3255 }
3256 
3257 static void bpf_link_defer_dealloc_rcu_gp(struct rcu_head *rcu)
3258 {
3259 	struct bpf_link *link = container_of(rcu, struct bpf_link, rcu);
3260 
3261 	bpf_link_dealloc(link);
3262 }
3263 
3264 static bool bpf_link_is_tracepoint(struct bpf_link *link)
3265 {
3266 	/*
3267 	 * Only these combinations support a tracepoint bpf_link.
3268 	 * BPF_LINK_TYPE_TRACING raw_tp progs are hardcoded to use
3269 	 * bpf_raw_tp_link_lops and thus dealloc_deferred(), see
3270 	 * bpf_raw_tp_link_attach().
3271 	 */
3272 	return link->type == BPF_LINK_TYPE_RAW_TRACEPOINT ||
3273 	       (link->type == BPF_LINK_TYPE_TRACING && link->attach_type == BPF_TRACE_RAW_TP);
3274 }
3275 
3276 static void bpf_link_defer_dealloc_mult_rcu_gp(struct rcu_head *rcu)
3277 {
3278 	if (rcu_trace_implies_rcu_gp())
3279 		bpf_link_defer_dealloc_rcu_gp(rcu);
3280 	else
3281 		call_rcu(rcu, bpf_link_defer_dealloc_rcu_gp);
3282 }
3283 
3284 /* bpf_link_free is guaranteed to be called from process context */
3285 static void bpf_link_free(struct bpf_link *link)
3286 {
3287 	const struct bpf_link_ops *ops = link->ops;
3288 
3289 	bpf_link_free_id(link->id);
3290 	/* detach BPF program, clean up used resources */
3291 	if (link->prog)
3292 		ops->release(link);
3293 	if (ops->dealloc_deferred) {
3294 		/*
3295 		 * Schedule BPF link deallocation, which will only then
3296 		 * trigger putting BPF program refcount.
3297 		 * If underlying BPF program is sleepable or BPF link's target
3298 		 * attach hookpoint is sleepable or otherwise requires RCU GPs
3299 		 * to ensure link and its underlying BPF program is not
3300 		 * reachable anymore, we need to first wait for RCU tasks
3301 		 * trace sync, and then go through "classic" RCU grace period.
3302 		 *
3303 		 * For tracepoint BPF links, we need to go through SRCU grace
3304 		 * period wait instead when non-faultable tracepoint is used. We
3305 		 * don't need to chain SRCU grace period waits, however, for the
3306 		 * faultable case, since it exclusively uses RCU Tasks Trace.
3307 		 */
3308 		if (link->sleepable || (link->prog && link->prog->sleepable))
3309 			call_rcu_tasks_trace(&link->rcu, bpf_link_defer_dealloc_mult_rcu_gp);
3310 		/* We need to do a SRCU grace period wait for non-faultable tracepoint BPF links. */
3311 		else if (bpf_link_is_tracepoint(link))
3312 			call_tracepoint_unregister_atomic(&link->rcu, bpf_link_defer_dealloc_rcu_gp);
3313 		else
3314 			call_rcu(&link->rcu, bpf_link_defer_dealloc_rcu_gp);
3315 	} else if (ops->dealloc) {
3316 		bpf_link_dealloc(link);
3317 	}
3318 }
3319 
3320 static void bpf_link_put_deferred(struct work_struct *work)
3321 {
3322 	struct bpf_link *link = container_of(work, struct bpf_link, work);
3323 
3324 	bpf_link_free(link);
3325 }
3326 
3327 /* bpf_link_put might be called from atomic context. It needs to be called
3328  * from sleepable context in order to acquire sleeping locks during the process.
3329  */
3330 void bpf_link_put(struct bpf_link *link)
3331 {
3332 	if (!atomic64_dec_and_test(&link->refcnt))
3333 		return;
3334 
3335 	INIT_WORK(&link->work, bpf_link_put_deferred);
3336 	schedule_work(&link->work);
3337 }
3338 EXPORT_SYMBOL(bpf_link_put);
3339 
3340 static void bpf_link_put_direct(struct bpf_link *link)
3341 {
3342 	if (!atomic64_dec_and_test(&link->refcnt))
3343 		return;
3344 	bpf_link_free(link);
3345 }
3346 
3347 static int bpf_link_release(struct inode *inode, struct file *filp)
3348 {
3349 	struct bpf_link *link = filp->private_data;
3350 
3351 	bpf_link_put_direct(link);
3352 	return 0;
3353 }
3354 
3355 #ifdef CONFIG_PROC_FS
3356 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type)
3357 #define BPF_MAP_TYPE(_id, _ops)
3358 #define BPF_LINK_TYPE(_id, _name) [_id] = #_name,
3359 static const char *bpf_link_type_strs[] = {
3360 	[BPF_LINK_TYPE_UNSPEC] = "<invalid>",
3361 #include <linux/bpf_types.h>
3362 };
3363 #undef BPF_PROG_TYPE
3364 #undef BPF_MAP_TYPE
3365 #undef BPF_LINK_TYPE
3366 
3367 static void bpf_link_show_fdinfo(struct seq_file *m, struct file *filp)
3368 {
3369 	const struct bpf_link *link = filp->private_data;
3370 	const struct bpf_prog *prog = link->prog;
3371 	enum bpf_link_type type = link->type;
3372 	char prog_tag[sizeof(prog->tag) * 2 + 1] = { };
3373 
3374 	if (type < ARRAY_SIZE(bpf_link_type_strs) && bpf_link_type_strs[type]) {
3375 		if (link->type == BPF_LINK_TYPE_KPROBE_MULTI)
3376 			seq_printf(m, "link_type:\t%s\n", link->flags == BPF_F_KPROBE_MULTI_RETURN ?
3377 				   "kretprobe_multi" : "kprobe_multi");
3378 		else if (link->type == BPF_LINK_TYPE_UPROBE_MULTI)
3379 			seq_printf(m, "link_type:\t%s\n", link->flags == BPF_F_UPROBE_MULTI_RETURN ?
3380 				   "uretprobe_multi" : "uprobe_multi");
3381 		else
3382 			seq_printf(m, "link_type:\t%s\n", bpf_link_type_strs[type]);
3383 	} else {
3384 		WARN_ONCE(1, "missing BPF_LINK_TYPE(...) for link type %u\n", type);
3385 		seq_printf(m, "link_type:\t<%u>\n", type);
3386 	}
3387 	seq_printf(m, "link_id:\t%u\n", link->id);
3388 
3389 	if (prog) {
3390 		bin2hex(prog_tag, prog->tag, sizeof(prog->tag));
3391 		seq_printf(m,
3392 			   "prog_tag:\t%s\n"
3393 			   "prog_id:\t%u\n",
3394 			   prog_tag,
3395 			   prog->aux->id);
3396 	}
3397 	if (link->ops->show_fdinfo)
3398 		link->ops->show_fdinfo(link, m);
3399 }
3400 #endif
3401 
3402 static __poll_t bpf_link_poll(struct file *file, struct poll_table_struct *pts)
3403 {
3404 	struct bpf_link *link = file->private_data;
3405 
3406 	return link->ops->poll(file, pts);
3407 }
3408 
3409 static const struct file_operations bpf_link_fops = {
3410 #ifdef CONFIG_PROC_FS
3411 	.show_fdinfo	= bpf_link_show_fdinfo,
3412 #endif
3413 	.release	= bpf_link_release,
3414 	.read		= bpf_dummy_read,
3415 	.write		= bpf_dummy_write,
3416 };
3417 
3418 static const struct file_operations bpf_link_fops_poll = {
3419 #ifdef CONFIG_PROC_FS
3420 	.show_fdinfo	= bpf_link_show_fdinfo,
3421 #endif
3422 	.release	= bpf_link_release,
3423 	.read		= bpf_dummy_read,
3424 	.write		= bpf_dummy_write,
3425 	.poll		= bpf_link_poll,
3426 };
3427 
3428 static int bpf_link_alloc_id(struct bpf_link *link)
3429 {
3430 	int id;
3431 
3432 	idr_preload(GFP_KERNEL);
3433 	spin_lock_bh(&link_idr_lock);
3434 	id = idr_alloc_cyclic(&link_idr, link, 1, INT_MAX, GFP_ATOMIC);
3435 	spin_unlock_bh(&link_idr_lock);
3436 	idr_preload_end();
3437 
3438 	return id;
3439 }
3440 
3441 /* Prepare bpf_link to be exposed to user-space by allocating anon_inode file,
3442  * reserving unused FD and allocating ID from link_idr. This is to be paired
3443  * with bpf_link_settle() to install FD and ID and expose bpf_link to
3444  * user-space, if bpf_link is successfully attached. If not, bpf_link and
3445  * pre-allocated resources are to be freed with bpf_cleanup() call. All the
3446  * transient state is passed around in struct bpf_link_primer.
3447  * This is preferred way to create and initialize bpf_link, especially when
3448  * there are complicated and expensive operations in between creating bpf_link
3449  * itself and attaching it to BPF hook. By using bpf_link_prime() and
3450  * bpf_link_settle() kernel code using bpf_link doesn't have to perform
3451  * expensive (and potentially failing) roll back operations in a rare case
3452  * that file, FD, or ID can't be allocated.
3453  */
3454 int bpf_link_prime(struct bpf_link *link, struct bpf_link_primer *primer)
3455 {
3456 	struct file *file;
3457 	int fd, id;
3458 
3459 	fd = get_unused_fd_flags(O_CLOEXEC);
3460 	if (fd < 0)
3461 		return fd;
3462 
3463 
3464 	id = bpf_link_alloc_id(link);
3465 	if (id < 0) {
3466 		put_unused_fd(fd);
3467 		return id;
3468 	}
3469 
3470 	file = anon_inode_getfile("bpf_link",
3471 				  link->ops->poll ? &bpf_link_fops_poll : &bpf_link_fops,
3472 				  link, O_CLOEXEC);
3473 	if (IS_ERR(file)) {
3474 		bpf_link_free_id(id);
3475 		put_unused_fd(fd);
3476 		return PTR_ERR(file);
3477 	}
3478 
3479 	primer->link = link;
3480 	primer->file = file;
3481 	primer->fd = fd;
3482 	primer->id = id;
3483 	return 0;
3484 }
3485 
3486 int bpf_link_settle(struct bpf_link_primer *primer)
3487 {
3488 	/* make bpf_link fetchable by ID */
3489 	spin_lock_bh(&link_idr_lock);
3490 	primer->link->id = primer->id;
3491 	spin_unlock_bh(&link_idr_lock);
3492 	/* make bpf_link fetchable by FD */
3493 	fd_install(primer->fd, primer->file);
3494 	/* pass through installed FD */
3495 	return primer->fd;
3496 }
3497 
3498 int bpf_link_new_fd(struct bpf_link *link)
3499 {
3500 	return anon_inode_getfd("bpf-link",
3501 				link->ops->poll ? &bpf_link_fops_poll : &bpf_link_fops,
3502 				link, O_CLOEXEC);
3503 }
3504 
3505 struct bpf_link *bpf_link_get_from_fd(u32 ufd)
3506 {
3507 	CLASS(fd, f)(ufd);
3508 	struct bpf_link *link;
3509 
3510 	if (fd_empty(f))
3511 		return ERR_PTR(-EBADF);
3512 	if (fd_file(f)->f_op != &bpf_link_fops && fd_file(f)->f_op != &bpf_link_fops_poll)
3513 		return ERR_PTR(-EINVAL);
3514 
3515 	link = fd_file(f)->private_data;
3516 	bpf_link_inc(link);
3517 	return link;
3518 }
3519 EXPORT_SYMBOL_NS(bpf_link_get_from_fd, "BPF_INTERNAL");
3520 
3521 static void bpf_tracing_link_release(struct bpf_link *link)
3522 {
3523 	struct bpf_tracing_link *tr_link =
3524 		container_of(link, struct bpf_tracing_link, link.link);
3525 
3526 	WARN_ON_ONCE(bpf_trampoline_unlink_prog(&tr_link->link,
3527 						tr_link->trampoline,
3528 						tr_link->tgt_prog));
3529 
3530 	bpf_trampoline_put(tr_link->trampoline);
3531 
3532 	/* tgt_prog is NULL if target is a kernel function */
3533 	if (tr_link->tgt_prog)
3534 		bpf_prog_put(tr_link->tgt_prog);
3535 }
3536 
3537 static void bpf_tracing_link_dealloc(struct bpf_link *link)
3538 {
3539 	struct bpf_tracing_link *tr_link =
3540 		container_of(link, struct bpf_tracing_link, link.link);
3541 
3542 	kfree(tr_link);
3543 }
3544 
3545 static void bpf_tracing_link_show_fdinfo(const struct bpf_link *link,
3546 					 struct seq_file *seq)
3547 {
3548 	struct bpf_tracing_link *tr_link =
3549 		container_of(link, struct bpf_tracing_link, link.link);
3550 	u32 target_btf_id, target_obj_id;
3551 
3552 	bpf_trampoline_unpack_key(tr_link->trampoline->key,
3553 				  &target_obj_id, &target_btf_id);
3554 	seq_printf(seq,
3555 		   "attach_type:\t%d\n"
3556 		   "target_obj_id:\t%u\n"
3557 		   "target_btf_id:\t%u\n"
3558 		   "cookie:\t%llu\n",
3559 		   link->attach_type,
3560 		   target_obj_id,
3561 		   target_btf_id,
3562 		   tr_link->link.cookie);
3563 }
3564 
3565 static int bpf_tracing_link_fill_link_info(const struct bpf_link *link,
3566 					   struct bpf_link_info *info)
3567 {
3568 	struct bpf_tracing_link *tr_link =
3569 		container_of(link, struct bpf_tracing_link, link.link);
3570 
3571 	info->tracing.attach_type = link->attach_type;
3572 	info->tracing.cookie = tr_link->link.cookie;
3573 	bpf_trampoline_unpack_key(tr_link->trampoline->key,
3574 				  &info->tracing.target_obj_id,
3575 				  &info->tracing.target_btf_id);
3576 
3577 	return 0;
3578 }
3579 
3580 static const struct bpf_link_ops bpf_tracing_link_lops = {
3581 	.release = bpf_tracing_link_release,
3582 	.dealloc = bpf_tracing_link_dealloc,
3583 	.show_fdinfo = bpf_tracing_link_show_fdinfo,
3584 	.fill_link_info = bpf_tracing_link_fill_link_info,
3585 };
3586 
3587 static int bpf_tracing_prog_attach(struct bpf_prog *prog,
3588 				   int tgt_prog_fd,
3589 				   u32 btf_id,
3590 				   u64 bpf_cookie,
3591 				   enum bpf_attach_type attach_type)
3592 {
3593 	struct bpf_link_primer link_primer;
3594 	struct bpf_prog *tgt_prog = NULL;
3595 	struct bpf_trampoline *tr = NULL;
3596 	struct bpf_tracing_link *link;
3597 	u64 key = 0;
3598 	int err;
3599 
3600 	switch (prog->type) {
3601 	case BPF_PROG_TYPE_TRACING:
3602 		if (prog->expected_attach_type != BPF_TRACE_FENTRY &&
3603 		    prog->expected_attach_type != BPF_TRACE_FEXIT &&
3604 		    prog->expected_attach_type != BPF_TRACE_FSESSION &&
3605 		    prog->expected_attach_type != BPF_MODIFY_RETURN) {
3606 			err = -EINVAL;
3607 			goto out_put_prog;
3608 		}
3609 		break;
3610 	case BPF_PROG_TYPE_EXT:
3611 		if (prog->expected_attach_type != 0) {
3612 			err = -EINVAL;
3613 			goto out_put_prog;
3614 		}
3615 		break;
3616 	case BPF_PROG_TYPE_LSM:
3617 		if (prog->expected_attach_type != BPF_LSM_MAC) {
3618 			err = -EINVAL;
3619 			goto out_put_prog;
3620 		}
3621 		break;
3622 	default:
3623 		err = -EINVAL;
3624 		goto out_put_prog;
3625 	}
3626 
3627 	if (!!tgt_prog_fd != !!btf_id) {
3628 		err = -EINVAL;
3629 		goto out_put_prog;
3630 	}
3631 
3632 	if (tgt_prog_fd) {
3633 		/*
3634 		 * For now we only allow new targets for BPF_PROG_TYPE_EXT. If this
3635 		 * part would be changed to implement the same for
3636 		 * BPF_PROG_TYPE_TRACING, do not forget to update the way how
3637 		 * attach_tracing_prog flag is set.
3638 		 */
3639 		if (prog->type != BPF_PROG_TYPE_EXT) {
3640 			err = -EINVAL;
3641 			goto out_put_prog;
3642 		}
3643 
3644 		tgt_prog = bpf_prog_get(tgt_prog_fd);
3645 		if (IS_ERR(tgt_prog)) {
3646 			err = PTR_ERR(tgt_prog);
3647 			tgt_prog = NULL;
3648 			goto out_put_prog;
3649 		}
3650 
3651 		key = bpf_trampoline_compute_key(tgt_prog, NULL, btf_id);
3652 	}
3653 
3654 	if (prog->expected_attach_type == BPF_TRACE_FSESSION) {
3655 		struct bpf_fsession_link *fslink;
3656 
3657 		fslink = kzalloc_obj(*fslink, GFP_USER);
3658 		if (fslink) {
3659 			bpf_link_init(&fslink->fexit.link, BPF_LINK_TYPE_TRACING,
3660 				      &bpf_tracing_link_lops, prog, attach_type);
3661 			fslink->fexit.cookie = bpf_cookie;
3662 			link = &fslink->link;
3663 		} else {
3664 			link = NULL;
3665 		}
3666 	} else {
3667 		link = kzalloc_obj(*link, GFP_USER);
3668 	}
3669 	if (!link) {
3670 		err = -ENOMEM;
3671 		goto out_put_prog;
3672 	}
3673 	bpf_link_init(&link->link.link, BPF_LINK_TYPE_TRACING,
3674 		      &bpf_tracing_link_lops, prog, attach_type);
3675 
3676 	link->link.cookie = bpf_cookie;
3677 
3678 	mutex_lock(&prog->aux->dst_mutex);
3679 
3680 	/* There are a few possible cases here:
3681 	 *
3682 	 * - if prog->aux->dst_trampoline is set, the program was just loaded
3683 	 *   and not yet attached to anything, so we can use the values stored
3684 	 *   in prog->aux
3685 	 *
3686 	 * - if prog->aux->dst_trampoline is NULL, the program has already been
3687 	 *   attached to a target and its initial target was cleared (below)
3688 	 *
3689 	 * - if tgt_prog != NULL, the caller specified tgt_prog_fd +
3690 	 *   target_btf_id using the link_create API.
3691 	 *
3692 	 * - if tgt_prog == NULL when this function was called using the old
3693 	 *   raw_tracepoint_open API, and we need a target from prog->aux
3694 	 *
3695 	 * - if prog->aux->dst_trampoline and tgt_prog is NULL, the program
3696 	 *   was detached and is going for re-attachment.
3697 	 *
3698 	 * - if prog->aux->dst_trampoline is NULL and tgt_prog and prog->aux->attach_btf
3699 	 *   are NULL, then program was already attached and user did not provide
3700 	 *   tgt_prog_fd so we have no way to find out or create trampoline
3701 	 */
3702 	if (!prog->aux->dst_trampoline && !tgt_prog) {
3703 		/*
3704 		 * Allow re-attach for TRACING and LSM programs. If it's
3705 		 * currently linked, bpf_trampoline_link_prog will fail.
3706 		 * EXT programs need to specify tgt_prog_fd, so they
3707 		 * re-attach in separate code path.
3708 		 */
3709 		if (prog->type != BPF_PROG_TYPE_TRACING &&
3710 		    prog->type != BPF_PROG_TYPE_LSM) {
3711 			err = -EINVAL;
3712 			goto out_unlock;
3713 		}
3714 		/* We can allow re-attach only if we have valid attach_btf. */
3715 		if (!prog->aux->attach_btf) {
3716 			err = -EINVAL;
3717 			goto out_unlock;
3718 		}
3719 		btf_id = prog->aux->attach_btf_id;
3720 		key = bpf_trampoline_compute_key(NULL, prog->aux->attach_btf, btf_id);
3721 	}
3722 
3723 	if (!prog->aux->dst_trampoline ||
3724 	    (key && key != prog->aux->dst_trampoline->key)) {
3725 		/* If there is no saved target, or the specified target is
3726 		 * different from the destination specified at load time, we
3727 		 * need a new trampoline and a check for compatibility
3728 		 */
3729 		struct bpf_attach_target_info tgt_info = {};
3730 
3731 		err = bpf_check_attach_target(NULL, prog, tgt_prog, btf_id,
3732 					      &tgt_info);
3733 		if (err)
3734 			goto out_unlock;
3735 
3736 		if (tgt_info.tgt_mod) {
3737 			module_put(prog->aux->mod);
3738 			prog->aux->mod = tgt_info.tgt_mod;
3739 		}
3740 
3741 		tr = bpf_trampoline_get(key, &tgt_info);
3742 		if (!tr) {
3743 			err = -ENOMEM;
3744 			goto out_unlock;
3745 		}
3746 	} else {
3747 		/* The caller didn't specify a target, or the target was the
3748 		 * same as the destination supplied during program load. This
3749 		 * means we can reuse the trampoline and reference from program
3750 		 * load time, and there is no need to allocate a new one. This
3751 		 * can only happen once for any program, as the saved values in
3752 		 * prog->aux are cleared below.
3753 		 */
3754 		tr = prog->aux->dst_trampoline;
3755 		tgt_prog = prog->aux->dst_prog;
3756 	}
3757 
3758 	err = bpf_link_prime(&link->link.link, &link_primer);
3759 	if (err)
3760 		goto out_unlock;
3761 
3762 	err = bpf_trampoline_link_prog(&link->link, tr, tgt_prog);
3763 	if (err) {
3764 		bpf_link_cleanup(&link_primer);
3765 		link = NULL;
3766 		goto out_unlock;
3767 	}
3768 
3769 	link->tgt_prog = tgt_prog;
3770 	link->trampoline = tr;
3771 
3772 	/* Always clear the trampoline and target prog from prog->aux to make
3773 	 * sure the original attach destination is not kept alive after a
3774 	 * program is (re-)attached to another target.
3775 	 */
3776 	if (prog->aux->dst_prog &&
3777 	    (tgt_prog_fd || tr != prog->aux->dst_trampoline))
3778 		/* got extra prog ref from syscall, or attaching to different prog */
3779 		bpf_prog_put(prog->aux->dst_prog);
3780 	if (prog->aux->dst_trampoline && tr != prog->aux->dst_trampoline)
3781 		/* we allocated a new trampoline, so free the old one */
3782 		bpf_trampoline_put(prog->aux->dst_trampoline);
3783 
3784 	prog->aux->dst_prog = NULL;
3785 	prog->aux->dst_trampoline = NULL;
3786 	mutex_unlock(&prog->aux->dst_mutex);
3787 
3788 	return bpf_link_settle(&link_primer);
3789 out_unlock:
3790 	if (tr && tr != prog->aux->dst_trampoline)
3791 		bpf_trampoline_put(tr);
3792 	mutex_unlock(&prog->aux->dst_mutex);
3793 	kfree(link);
3794 out_put_prog:
3795 	if (tgt_prog_fd && tgt_prog)
3796 		bpf_prog_put(tgt_prog);
3797 	return err;
3798 }
3799 
3800 static void bpf_raw_tp_link_release(struct bpf_link *link)
3801 {
3802 	struct bpf_raw_tp_link *raw_tp =
3803 		container_of(link, struct bpf_raw_tp_link, link);
3804 
3805 	bpf_probe_unregister(raw_tp->btp, raw_tp);
3806 	bpf_put_raw_tracepoint(raw_tp->btp);
3807 }
3808 
3809 static void bpf_raw_tp_link_dealloc(struct bpf_link *link)
3810 {
3811 	struct bpf_raw_tp_link *raw_tp =
3812 		container_of(link, struct bpf_raw_tp_link, link);
3813 
3814 	kfree(raw_tp);
3815 }
3816 
3817 static void bpf_raw_tp_link_show_fdinfo(const struct bpf_link *link,
3818 					struct seq_file *seq)
3819 {
3820 	struct bpf_raw_tp_link *raw_tp_link =
3821 		container_of(link, struct bpf_raw_tp_link, link);
3822 
3823 	seq_printf(seq,
3824 		   "tp_name:\t%s\n"
3825 		   "cookie:\t%llu\n",
3826 		   raw_tp_link->btp->tp->name,
3827 		   raw_tp_link->cookie);
3828 }
3829 
3830 static int bpf_copy_to_user(char __user *ubuf, const char *buf, u32 ulen,
3831 			    u32 len)
3832 {
3833 	if (ulen >= len + 1) {
3834 		if (copy_to_user(ubuf, buf, len + 1))
3835 			return -EFAULT;
3836 	} else {
3837 		char zero = '\0';
3838 
3839 		if (copy_to_user(ubuf, buf, ulen - 1))
3840 			return -EFAULT;
3841 		if (put_user(zero, ubuf + ulen - 1))
3842 			return -EFAULT;
3843 		return -ENOSPC;
3844 	}
3845 
3846 	return 0;
3847 }
3848 
3849 static int bpf_raw_tp_link_fill_link_info(const struct bpf_link *link,
3850 					  struct bpf_link_info *info)
3851 {
3852 	struct bpf_raw_tp_link *raw_tp_link =
3853 		container_of(link, struct bpf_raw_tp_link, link);
3854 	char __user *ubuf = u64_to_user_ptr(info->raw_tracepoint.tp_name);
3855 	const char *tp_name = raw_tp_link->btp->tp->name;
3856 	u32 ulen = info->raw_tracepoint.tp_name_len;
3857 	size_t tp_len = strlen(tp_name);
3858 
3859 	if (!ulen ^ !ubuf)
3860 		return -EINVAL;
3861 
3862 	info->raw_tracepoint.tp_name_len = tp_len + 1;
3863 	info->raw_tracepoint.cookie = raw_tp_link->cookie;
3864 
3865 	if (!ubuf)
3866 		return 0;
3867 
3868 	return bpf_copy_to_user(ubuf, tp_name, ulen, tp_len);
3869 }
3870 
3871 static const struct bpf_link_ops bpf_raw_tp_link_lops = {
3872 	.release = bpf_raw_tp_link_release,
3873 	.dealloc_deferred = bpf_raw_tp_link_dealloc,
3874 	.show_fdinfo = bpf_raw_tp_link_show_fdinfo,
3875 	.fill_link_info = bpf_raw_tp_link_fill_link_info,
3876 };
3877 
3878 #ifdef CONFIG_PERF_EVENTS
3879 struct bpf_perf_link {
3880 	struct bpf_link link;
3881 	struct file *perf_file;
3882 };
3883 
3884 static void bpf_perf_link_release(struct bpf_link *link)
3885 {
3886 	struct bpf_perf_link *perf_link = container_of(link, struct bpf_perf_link, link);
3887 	struct perf_event *event = perf_link->perf_file->private_data;
3888 
3889 	perf_event_free_bpf_prog(event);
3890 	fput(perf_link->perf_file);
3891 }
3892 
3893 static void bpf_perf_link_dealloc(struct bpf_link *link)
3894 {
3895 	struct bpf_perf_link *perf_link = container_of(link, struct bpf_perf_link, link);
3896 
3897 	kfree(perf_link);
3898 }
3899 
3900 static int bpf_perf_link_fill_common(const struct perf_event *event,
3901 				     char __user *uname, u32 *ulenp,
3902 				     u64 *probe_offset, u64 *probe_addr,
3903 				     u32 *fd_type, unsigned long *missed)
3904 {
3905 	const char *buf;
3906 	u32 prog_id, ulen;
3907 	size_t len;
3908 	int err;
3909 
3910 	ulen = *ulenp;
3911 	if (!ulen ^ !uname)
3912 		return -EINVAL;
3913 
3914 	err = bpf_get_perf_event_info(event, &prog_id, fd_type, &buf,
3915 				      probe_offset, probe_addr, missed);
3916 	if (err)
3917 		return err;
3918 
3919 	if (buf) {
3920 		len = strlen(buf);
3921 		*ulenp = len + 1;
3922 	} else {
3923 		*ulenp = 1;
3924 	}
3925 	if (!uname)
3926 		return 0;
3927 
3928 	if (buf) {
3929 		err = bpf_copy_to_user(uname, buf, ulen, len);
3930 		if (err)
3931 			return err;
3932 	} else {
3933 		char zero = '\0';
3934 
3935 		if (put_user(zero, uname))
3936 			return -EFAULT;
3937 	}
3938 	return 0;
3939 }
3940 
3941 #ifdef CONFIG_KPROBE_EVENTS
3942 static int bpf_perf_link_fill_kprobe(const struct perf_event *event,
3943 				     struct bpf_link_info *info)
3944 {
3945 	unsigned long missed;
3946 	char __user *uname;
3947 	u64 addr, offset;
3948 	u32 ulen, type;
3949 	int err;
3950 
3951 	uname = u64_to_user_ptr(info->perf_event.kprobe.func_name);
3952 	ulen = info->perf_event.kprobe.name_len;
3953 	err = bpf_perf_link_fill_common(event, uname, &ulen, &offset, &addr,
3954 					&type, &missed);
3955 	if (err)
3956 		return err;
3957 	if (type == BPF_FD_TYPE_KRETPROBE)
3958 		info->perf_event.type = BPF_PERF_EVENT_KRETPROBE;
3959 	else
3960 		info->perf_event.type = BPF_PERF_EVENT_KPROBE;
3961 	info->perf_event.kprobe.name_len = ulen;
3962 	info->perf_event.kprobe.offset = offset;
3963 	info->perf_event.kprobe.missed = missed;
3964 	if (!kallsyms_show_value(current_cred()))
3965 		addr = 0;
3966 	info->perf_event.kprobe.addr = addr;
3967 	info->perf_event.kprobe.cookie = event->bpf_cookie;
3968 	return 0;
3969 }
3970 
3971 static void bpf_perf_link_fdinfo_kprobe(const struct perf_event *event,
3972 					struct seq_file *seq)
3973 {
3974 	const char *name;
3975 	int err;
3976 	u32 prog_id, type;
3977 	u64 offset, addr;
3978 	unsigned long missed;
3979 
3980 	err = bpf_get_perf_event_info(event, &prog_id, &type, &name,
3981 				      &offset, &addr, &missed);
3982 	if (err)
3983 		return;
3984 
3985 	seq_printf(seq,
3986 		   "name:\t%s\n"
3987 		   "offset:\t%#llx\n"
3988 		   "missed:\t%lu\n"
3989 		   "addr:\t%#llx\n"
3990 		   "event_type:\t%s\n"
3991 		   "cookie:\t%llu\n",
3992 		   name, offset, missed, addr,
3993 		   type == BPF_FD_TYPE_KRETPROBE ?  "kretprobe" : "kprobe",
3994 		   event->bpf_cookie);
3995 }
3996 #endif
3997 
3998 #ifdef CONFIG_UPROBE_EVENTS
3999 static int bpf_perf_link_fill_uprobe(const struct perf_event *event,
4000 				     struct bpf_link_info *info)
4001 {
4002 	u64 ref_ctr_offset, offset;
4003 	char __user *uname;
4004 	u32 ulen, type;
4005 	int err;
4006 
4007 	uname = u64_to_user_ptr(info->perf_event.uprobe.file_name);
4008 	ulen = info->perf_event.uprobe.name_len;
4009 	err = bpf_perf_link_fill_common(event, uname, &ulen, &offset, &ref_ctr_offset,
4010 					&type, NULL);
4011 	if (err)
4012 		return err;
4013 
4014 	if (type == BPF_FD_TYPE_URETPROBE)
4015 		info->perf_event.type = BPF_PERF_EVENT_URETPROBE;
4016 	else
4017 		info->perf_event.type = BPF_PERF_EVENT_UPROBE;
4018 	info->perf_event.uprobe.name_len = ulen;
4019 	info->perf_event.uprobe.offset = offset;
4020 	info->perf_event.uprobe.cookie = event->bpf_cookie;
4021 	info->perf_event.uprobe.ref_ctr_offset = ref_ctr_offset;
4022 	return 0;
4023 }
4024 
4025 static void bpf_perf_link_fdinfo_uprobe(const struct perf_event *event,
4026 					struct seq_file *seq)
4027 {
4028 	const char *name;
4029 	int err;
4030 	u32 prog_id, type;
4031 	u64 offset, ref_ctr_offset;
4032 	unsigned long missed;
4033 
4034 	err = bpf_get_perf_event_info(event, &prog_id, &type, &name,
4035 				      &offset, &ref_ctr_offset, &missed);
4036 	if (err)
4037 		return;
4038 
4039 	seq_printf(seq,
4040 		   "name:\t%s\n"
4041 		   "offset:\t%#llx\n"
4042 		   "ref_ctr_offset:\t%#llx\n"
4043 		   "event_type:\t%s\n"
4044 		   "cookie:\t%llu\n",
4045 		   name, offset, ref_ctr_offset,
4046 		   type == BPF_FD_TYPE_URETPROBE ?  "uretprobe" : "uprobe",
4047 		   event->bpf_cookie);
4048 }
4049 #endif
4050 
4051 static int bpf_perf_link_fill_probe(const struct perf_event *event,
4052 				    struct bpf_link_info *info)
4053 {
4054 #ifdef CONFIG_KPROBE_EVENTS
4055 	if (event->tp_event->flags & TRACE_EVENT_FL_KPROBE)
4056 		return bpf_perf_link_fill_kprobe(event, info);
4057 #endif
4058 #ifdef CONFIG_UPROBE_EVENTS
4059 	if (event->tp_event->flags & TRACE_EVENT_FL_UPROBE)
4060 		return bpf_perf_link_fill_uprobe(event, info);
4061 #endif
4062 	return -EOPNOTSUPP;
4063 }
4064 
4065 static int bpf_perf_link_fill_tracepoint(const struct perf_event *event,
4066 					 struct bpf_link_info *info)
4067 {
4068 	char __user *uname;
4069 	u32 ulen;
4070 	int err;
4071 
4072 	uname = u64_to_user_ptr(info->perf_event.tracepoint.tp_name);
4073 	ulen = info->perf_event.tracepoint.name_len;
4074 	err = bpf_perf_link_fill_common(event, uname, &ulen, NULL, NULL, NULL, NULL);
4075 	if (err)
4076 		return err;
4077 
4078 	info->perf_event.type = BPF_PERF_EVENT_TRACEPOINT;
4079 	info->perf_event.tracepoint.name_len = ulen;
4080 	info->perf_event.tracepoint.cookie = event->bpf_cookie;
4081 	return 0;
4082 }
4083 
4084 static int bpf_perf_link_fill_perf_event(const struct perf_event *event,
4085 					 struct bpf_link_info *info)
4086 {
4087 	info->perf_event.event.type = event->attr.type;
4088 	info->perf_event.event.config = event->attr.config;
4089 	info->perf_event.event.cookie = event->bpf_cookie;
4090 	info->perf_event.type = BPF_PERF_EVENT_EVENT;
4091 	return 0;
4092 }
4093 
4094 static int bpf_perf_link_fill_link_info(const struct bpf_link *link,
4095 					struct bpf_link_info *info)
4096 {
4097 	struct bpf_perf_link *perf_link;
4098 	const struct perf_event *event;
4099 
4100 	perf_link = container_of(link, struct bpf_perf_link, link);
4101 	event = perf_get_event(perf_link->perf_file);
4102 	if (IS_ERR(event))
4103 		return PTR_ERR(event);
4104 
4105 	switch (event->prog->type) {
4106 	case BPF_PROG_TYPE_PERF_EVENT:
4107 		return bpf_perf_link_fill_perf_event(event, info);
4108 	case BPF_PROG_TYPE_TRACEPOINT:
4109 		return bpf_perf_link_fill_tracepoint(event, info);
4110 	case BPF_PROG_TYPE_KPROBE:
4111 		return bpf_perf_link_fill_probe(event, info);
4112 	default:
4113 		return -EOPNOTSUPP;
4114 	}
4115 }
4116 
4117 static void bpf_perf_event_link_show_fdinfo(const struct perf_event *event,
4118 					    struct seq_file *seq)
4119 {
4120 	seq_printf(seq,
4121 		   "type:\t%u\n"
4122 		   "config:\t%llu\n"
4123 		   "event_type:\t%s\n"
4124 		   "cookie:\t%llu\n",
4125 		   event->attr.type, event->attr.config,
4126 		   "event", event->bpf_cookie);
4127 }
4128 
4129 static void bpf_tracepoint_link_show_fdinfo(const struct perf_event *event,
4130 					    struct seq_file *seq)
4131 {
4132 	int err;
4133 	const char *name;
4134 	u32 prog_id;
4135 
4136 	err = bpf_get_perf_event_info(event, &prog_id, NULL, &name, NULL,
4137 				      NULL, NULL);
4138 	if (err)
4139 		return;
4140 
4141 	seq_printf(seq,
4142 		   "tp_name:\t%s\n"
4143 		   "event_type:\t%s\n"
4144 		   "cookie:\t%llu\n",
4145 		   name, "tracepoint", event->bpf_cookie);
4146 }
4147 
4148 static void bpf_probe_link_show_fdinfo(const struct perf_event *event,
4149 				       struct seq_file *seq)
4150 {
4151 #ifdef CONFIG_KPROBE_EVENTS
4152 	if (event->tp_event->flags & TRACE_EVENT_FL_KPROBE)
4153 		return bpf_perf_link_fdinfo_kprobe(event, seq);
4154 #endif
4155 
4156 #ifdef CONFIG_UPROBE_EVENTS
4157 	if (event->tp_event->flags & TRACE_EVENT_FL_UPROBE)
4158 		return bpf_perf_link_fdinfo_uprobe(event, seq);
4159 #endif
4160 }
4161 
4162 static void bpf_perf_link_show_fdinfo(const struct bpf_link *link,
4163 				      struct seq_file *seq)
4164 {
4165 	struct bpf_perf_link *perf_link;
4166 	const struct perf_event *event;
4167 
4168 	perf_link = container_of(link, struct bpf_perf_link, link);
4169 	event = perf_get_event(perf_link->perf_file);
4170 	if (IS_ERR(event))
4171 		return;
4172 
4173 	switch (event->prog->type) {
4174 	case BPF_PROG_TYPE_PERF_EVENT:
4175 		return bpf_perf_event_link_show_fdinfo(event, seq);
4176 	case BPF_PROG_TYPE_TRACEPOINT:
4177 		return bpf_tracepoint_link_show_fdinfo(event, seq);
4178 	case BPF_PROG_TYPE_KPROBE:
4179 		return bpf_probe_link_show_fdinfo(event, seq);
4180 	default:
4181 		return;
4182 	}
4183 }
4184 
4185 static const struct bpf_link_ops bpf_perf_link_lops = {
4186 	.release = bpf_perf_link_release,
4187 	.dealloc = bpf_perf_link_dealloc,
4188 	.fill_link_info = bpf_perf_link_fill_link_info,
4189 	.show_fdinfo = bpf_perf_link_show_fdinfo,
4190 };
4191 
4192 static int bpf_perf_link_attach(const union bpf_attr *attr, struct bpf_prog *prog)
4193 {
4194 	struct bpf_link_primer link_primer;
4195 	struct bpf_perf_link *link;
4196 	struct perf_event *event;
4197 	struct file *perf_file;
4198 	int err;
4199 
4200 	if (attr->link_create.flags)
4201 		return -EINVAL;
4202 
4203 	perf_file = perf_event_get(attr->link_create.target_fd);
4204 	if (IS_ERR(perf_file))
4205 		return PTR_ERR(perf_file);
4206 
4207 	link = kzalloc_obj(*link, GFP_USER);
4208 	if (!link) {
4209 		err = -ENOMEM;
4210 		goto out_put_file;
4211 	}
4212 	bpf_link_init(&link->link, BPF_LINK_TYPE_PERF_EVENT, &bpf_perf_link_lops, prog,
4213 		      attr->link_create.attach_type);
4214 	link->perf_file = perf_file;
4215 
4216 	err = bpf_link_prime(&link->link, &link_primer);
4217 	if (err) {
4218 		kfree(link);
4219 		goto out_put_file;
4220 	}
4221 
4222 	event = perf_file->private_data;
4223 	err = perf_event_set_bpf_prog(event, prog, attr->link_create.perf_event.bpf_cookie);
4224 	if (err) {
4225 		bpf_link_cleanup(&link_primer);
4226 		goto out_put_file;
4227 	}
4228 	/* perf_event_set_bpf_prog() doesn't take its own refcnt on prog */
4229 	bpf_prog_inc(prog);
4230 
4231 	return bpf_link_settle(&link_primer);
4232 
4233 out_put_file:
4234 	fput(perf_file);
4235 	return err;
4236 }
4237 #else
4238 static int bpf_perf_link_attach(const union bpf_attr *attr, struct bpf_prog *prog)
4239 {
4240 	return -EOPNOTSUPP;
4241 }
4242 #endif /* CONFIG_PERF_EVENTS */
4243 
4244 static int bpf_raw_tp_link_attach(struct bpf_prog *prog,
4245 				  const char __user *user_tp_name, u64 cookie,
4246 				  enum bpf_attach_type attach_type)
4247 {
4248 	struct bpf_link_primer link_primer;
4249 	struct bpf_raw_tp_link *link;
4250 	struct bpf_raw_event_map *btp;
4251 	const char *tp_name;
4252 	char buf[128];
4253 	int err;
4254 
4255 	switch (prog->type) {
4256 	case BPF_PROG_TYPE_TRACING:
4257 	case BPF_PROG_TYPE_EXT:
4258 	case BPF_PROG_TYPE_LSM:
4259 		if (user_tp_name)
4260 			/* The attach point for this category of programs
4261 			 * should be specified via btf_id during program load.
4262 			 */
4263 			return -EINVAL;
4264 		if (prog->type == BPF_PROG_TYPE_TRACING &&
4265 		    prog->expected_attach_type == BPF_TRACE_RAW_TP) {
4266 			tp_name = prog->aux->attach_func_name;
4267 			break;
4268 		}
4269 		return bpf_tracing_prog_attach(prog, 0, 0, 0, attach_type);
4270 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
4271 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
4272 		if (strncpy_from_user(buf, user_tp_name, sizeof(buf) - 1) < 0)
4273 			return -EFAULT;
4274 		buf[sizeof(buf) - 1] = 0;
4275 		tp_name = buf;
4276 		break;
4277 	default:
4278 		return -EINVAL;
4279 	}
4280 
4281 	btp = bpf_get_raw_tracepoint(tp_name);
4282 	if (!btp)
4283 		return -ENOENT;
4284 
4285 	link = kzalloc_obj(*link, GFP_USER);
4286 	if (!link) {
4287 		err = -ENOMEM;
4288 		goto out_put_btp;
4289 	}
4290 	bpf_link_init_sleepable(&link->link, BPF_LINK_TYPE_RAW_TRACEPOINT,
4291 				&bpf_raw_tp_link_lops, prog, attach_type,
4292 				tracepoint_is_faultable(btp->tp));
4293 	link->btp = btp;
4294 	link->cookie = cookie;
4295 
4296 	err = bpf_link_prime(&link->link, &link_primer);
4297 	if (err) {
4298 		kfree(link);
4299 		goto out_put_btp;
4300 	}
4301 
4302 	err = bpf_probe_register(link->btp, link);
4303 	if (err) {
4304 		bpf_link_cleanup(&link_primer);
4305 		goto out_put_btp;
4306 	}
4307 
4308 	return bpf_link_settle(&link_primer);
4309 
4310 out_put_btp:
4311 	bpf_put_raw_tracepoint(btp);
4312 	return err;
4313 }
4314 
4315 #define BPF_RAW_TRACEPOINT_OPEN_LAST_FIELD raw_tracepoint.cookie
4316 
4317 static int bpf_raw_tracepoint_open(const union bpf_attr *attr)
4318 {
4319 	struct bpf_prog *prog;
4320 	void __user *tp_name;
4321 	__u64 cookie;
4322 	int fd;
4323 
4324 	if (CHECK_ATTR(BPF_RAW_TRACEPOINT_OPEN))
4325 		return -EINVAL;
4326 
4327 	prog = bpf_prog_get(attr->raw_tracepoint.prog_fd);
4328 	if (IS_ERR(prog))
4329 		return PTR_ERR(prog);
4330 
4331 	tp_name = u64_to_user_ptr(attr->raw_tracepoint.name);
4332 	cookie = attr->raw_tracepoint.cookie;
4333 	fd = bpf_raw_tp_link_attach(prog, tp_name, cookie, prog->expected_attach_type);
4334 	if (fd < 0)
4335 		bpf_prog_put(prog);
4336 	return fd;
4337 }
4338 
4339 static enum bpf_prog_type
4340 attach_type_to_prog_type(enum bpf_attach_type attach_type)
4341 {
4342 	switch (attach_type) {
4343 	case BPF_CGROUP_INET_INGRESS:
4344 	case BPF_CGROUP_INET_EGRESS:
4345 		return BPF_PROG_TYPE_CGROUP_SKB;
4346 	case BPF_CGROUP_INET_SOCK_CREATE:
4347 	case BPF_CGROUP_INET_SOCK_RELEASE:
4348 	case BPF_CGROUP_INET4_POST_BIND:
4349 	case BPF_CGROUP_INET6_POST_BIND:
4350 		return BPF_PROG_TYPE_CGROUP_SOCK;
4351 	case BPF_CGROUP_INET4_BIND:
4352 	case BPF_CGROUP_INET6_BIND:
4353 	case BPF_CGROUP_INET4_CONNECT:
4354 	case BPF_CGROUP_INET6_CONNECT:
4355 	case BPF_CGROUP_UNIX_CONNECT:
4356 	case BPF_CGROUP_INET4_GETPEERNAME:
4357 	case BPF_CGROUP_INET6_GETPEERNAME:
4358 	case BPF_CGROUP_UNIX_GETPEERNAME:
4359 	case BPF_CGROUP_INET4_GETSOCKNAME:
4360 	case BPF_CGROUP_INET6_GETSOCKNAME:
4361 	case BPF_CGROUP_UNIX_GETSOCKNAME:
4362 	case BPF_CGROUP_UDP4_SENDMSG:
4363 	case BPF_CGROUP_UDP6_SENDMSG:
4364 	case BPF_CGROUP_UNIX_SENDMSG:
4365 	case BPF_CGROUP_UDP4_RECVMSG:
4366 	case BPF_CGROUP_UDP6_RECVMSG:
4367 	case BPF_CGROUP_UNIX_RECVMSG:
4368 		return BPF_PROG_TYPE_CGROUP_SOCK_ADDR;
4369 	case BPF_CGROUP_SOCK_OPS:
4370 		return BPF_PROG_TYPE_SOCK_OPS;
4371 	case BPF_CGROUP_DEVICE:
4372 		return BPF_PROG_TYPE_CGROUP_DEVICE;
4373 	case BPF_SK_MSG_VERDICT:
4374 		return BPF_PROG_TYPE_SK_MSG;
4375 	case BPF_SK_SKB_STREAM_PARSER:
4376 	case BPF_SK_SKB_STREAM_VERDICT:
4377 	case BPF_SK_SKB_VERDICT:
4378 		return BPF_PROG_TYPE_SK_SKB;
4379 	case BPF_LIRC_MODE2:
4380 		return BPF_PROG_TYPE_LIRC_MODE2;
4381 	case BPF_FLOW_DISSECTOR:
4382 		return BPF_PROG_TYPE_FLOW_DISSECTOR;
4383 	case BPF_CGROUP_SYSCTL:
4384 		return BPF_PROG_TYPE_CGROUP_SYSCTL;
4385 	case BPF_CGROUP_GETSOCKOPT:
4386 	case BPF_CGROUP_SETSOCKOPT:
4387 		return BPF_PROG_TYPE_CGROUP_SOCKOPT;
4388 	case BPF_TRACE_ITER:
4389 	case BPF_TRACE_RAW_TP:
4390 	case BPF_TRACE_FENTRY:
4391 	case BPF_TRACE_FEXIT:
4392 	case BPF_TRACE_FSESSION:
4393 	case BPF_MODIFY_RETURN:
4394 		return BPF_PROG_TYPE_TRACING;
4395 	case BPF_LSM_MAC:
4396 		return BPF_PROG_TYPE_LSM;
4397 	case BPF_SK_LOOKUP:
4398 		return BPF_PROG_TYPE_SK_LOOKUP;
4399 	case BPF_XDP:
4400 		return BPF_PROG_TYPE_XDP;
4401 	case BPF_LSM_CGROUP:
4402 		return BPF_PROG_TYPE_LSM;
4403 	case BPF_TCX_INGRESS:
4404 	case BPF_TCX_EGRESS:
4405 	case BPF_NETKIT_PRIMARY:
4406 	case BPF_NETKIT_PEER:
4407 		return BPF_PROG_TYPE_SCHED_CLS;
4408 	default:
4409 		return BPF_PROG_TYPE_UNSPEC;
4410 	}
4411 }
4412 
4413 static int bpf_prog_attach_check_attach_type(const struct bpf_prog *prog,
4414 					     enum bpf_attach_type attach_type)
4415 {
4416 	enum bpf_prog_type ptype;
4417 
4418 	switch (prog->type) {
4419 	case BPF_PROG_TYPE_CGROUP_SOCK:
4420 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
4421 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
4422 	case BPF_PROG_TYPE_SK_LOOKUP:
4423 		return attach_type == prog->expected_attach_type ? 0 : -EINVAL;
4424 	case BPF_PROG_TYPE_CGROUP_SKB:
4425 		if (!bpf_token_capable(prog->aux->token, CAP_NET_ADMIN))
4426 			/* cg-skb progs can be loaded by unpriv user.
4427 			 * check permissions at attach time.
4428 			 */
4429 			return -EPERM;
4430 
4431 		ptype = attach_type_to_prog_type(attach_type);
4432 		if (prog->type != ptype)
4433 			return -EINVAL;
4434 
4435 		return prog->enforce_expected_attach_type &&
4436 			prog->expected_attach_type != attach_type ?
4437 			-EINVAL : 0;
4438 	case BPF_PROG_TYPE_EXT:
4439 		return 0;
4440 	case BPF_PROG_TYPE_NETFILTER:
4441 		if (attach_type != BPF_NETFILTER)
4442 			return -EINVAL;
4443 		return 0;
4444 	case BPF_PROG_TYPE_PERF_EVENT:
4445 	case BPF_PROG_TYPE_TRACEPOINT:
4446 		if (attach_type != BPF_PERF_EVENT)
4447 			return -EINVAL;
4448 		return 0;
4449 	case BPF_PROG_TYPE_KPROBE:
4450 		if (prog->expected_attach_type == BPF_TRACE_KPROBE_MULTI &&
4451 		    attach_type != BPF_TRACE_KPROBE_MULTI)
4452 			return -EINVAL;
4453 		if (prog->expected_attach_type == BPF_TRACE_KPROBE_SESSION &&
4454 		    attach_type != BPF_TRACE_KPROBE_SESSION)
4455 			return -EINVAL;
4456 		if (prog->expected_attach_type == BPF_TRACE_UPROBE_MULTI &&
4457 		    attach_type != BPF_TRACE_UPROBE_MULTI)
4458 			return -EINVAL;
4459 		if (prog->expected_attach_type == BPF_TRACE_UPROBE_SESSION &&
4460 		    attach_type != BPF_TRACE_UPROBE_SESSION)
4461 			return -EINVAL;
4462 		if (attach_type != BPF_PERF_EVENT &&
4463 		    attach_type != BPF_TRACE_KPROBE_MULTI &&
4464 		    attach_type != BPF_TRACE_KPROBE_SESSION &&
4465 		    attach_type != BPF_TRACE_UPROBE_MULTI &&
4466 		    attach_type != BPF_TRACE_UPROBE_SESSION)
4467 			return -EINVAL;
4468 		return 0;
4469 	case BPF_PROG_TYPE_SCHED_CLS:
4470 		if (attach_type != BPF_TCX_INGRESS &&
4471 		    attach_type != BPF_TCX_EGRESS &&
4472 		    attach_type != BPF_NETKIT_PRIMARY &&
4473 		    attach_type != BPF_NETKIT_PEER)
4474 			return -EINVAL;
4475 		return 0;
4476 	default:
4477 		ptype = attach_type_to_prog_type(attach_type);
4478 		if (ptype == BPF_PROG_TYPE_UNSPEC || ptype != prog->type)
4479 			return -EINVAL;
4480 		return 0;
4481 	}
4482 }
4483 
4484 static bool is_cgroup_prog_type(enum bpf_prog_type ptype, enum bpf_attach_type atype,
4485 				bool check_atype)
4486 {
4487 	switch (ptype) {
4488 	case BPF_PROG_TYPE_CGROUP_DEVICE:
4489 	case BPF_PROG_TYPE_CGROUP_SKB:
4490 	case BPF_PROG_TYPE_CGROUP_SOCK:
4491 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
4492 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
4493 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
4494 	case BPF_PROG_TYPE_SOCK_OPS:
4495 		return true;
4496 	case BPF_PROG_TYPE_LSM:
4497 		return check_atype ? atype == BPF_LSM_CGROUP : true;
4498 	default:
4499 		return false;
4500 	}
4501 }
4502 
4503 #define BPF_PROG_ATTACH_LAST_FIELD expected_revision
4504 
4505 #define BPF_F_ATTACH_MASK_BASE	\
4506 	(BPF_F_ALLOW_OVERRIDE |	\
4507 	 BPF_F_ALLOW_MULTI |	\
4508 	 BPF_F_REPLACE |	\
4509 	 BPF_F_PREORDER)
4510 
4511 #define BPF_F_ATTACH_MASK_MPROG	\
4512 	(BPF_F_REPLACE |	\
4513 	 BPF_F_BEFORE |		\
4514 	 BPF_F_AFTER |		\
4515 	 BPF_F_ID |		\
4516 	 BPF_F_LINK)
4517 
4518 static int bpf_prog_attach(const union bpf_attr *attr)
4519 {
4520 	enum bpf_prog_type ptype;
4521 	struct bpf_prog *prog;
4522 	int ret;
4523 
4524 	if (CHECK_ATTR(BPF_PROG_ATTACH))
4525 		return -EINVAL;
4526 
4527 	ptype = attach_type_to_prog_type(attr->attach_type);
4528 	if (ptype == BPF_PROG_TYPE_UNSPEC)
4529 		return -EINVAL;
4530 	if (bpf_mprog_supported(ptype)) {
4531 		if (attr->attach_flags & ~BPF_F_ATTACH_MASK_MPROG)
4532 			return -EINVAL;
4533 	} else if (is_cgroup_prog_type(ptype, 0, false)) {
4534 		if (attr->attach_flags & ~(BPF_F_ATTACH_MASK_BASE | BPF_F_ATTACH_MASK_MPROG))
4535 			return -EINVAL;
4536 	} else {
4537 		if (attr->attach_flags & ~BPF_F_ATTACH_MASK_BASE)
4538 			return -EINVAL;
4539 		if (attr->relative_fd ||
4540 		    attr->expected_revision)
4541 			return -EINVAL;
4542 	}
4543 
4544 	prog = bpf_prog_get_type(attr->attach_bpf_fd, ptype);
4545 	if (IS_ERR(prog))
4546 		return PTR_ERR(prog);
4547 
4548 	if (bpf_prog_attach_check_attach_type(prog, attr->attach_type)) {
4549 		bpf_prog_put(prog);
4550 		return -EINVAL;
4551 	}
4552 
4553 	if (is_cgroup_prog_type(ptype, prog->expected_attach_type, true)) {
4554 		ret = cgroup_bpf_prog_attach(attr, ptype, prog);
4555 		goto out;
4556 	}
4557 
4558 	switch (ptype) {
4559 	case BPF_PROG_TYPE_SK_SKB:
4560 	case BPF_PROG_TYPE_SK_MSG:
4561 		ret = sock_map_get_from_fd(attr, prog);
4562 		break;
4563 	case BPF_PROG_TYPE_LIRC_MODE2:
4564 		ret = lirc_prog_attach(attr, prog);
4565 		break;
4566 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
4567 		ret = netns_bpf_prog_attach(attr, prog);
4568 		break;
4569 	case BPF_PROG_TYPE_SCHED_CLS:
4570 		if (attr->attach_type == BPF_TCX_INGRESS ||
4571 		    attr->attach_type == BPF_TCX_EGRESS)
4572 			ret = tcx_prog_attach(attr, prog);
4573 		else
4574 			ret = netkit_prog_attach(attr, prog);
4575 		break;
4576 	default:
4577 		ret = -EINVAL;
4578 	}
4579 out:
4580 	if (ret)
4581 		bpf_prog_put(prog);
4582 	return ret;
4583 }
4584 
4585 #define BPF_PROG_DETACH_LAST_FIELD expected_revision
4586 
4587 static int bpf_prog_detach(const union bpf_attr *attr)
4588 {
4589 	struct bpf_prog *prog = NULL;
4590 	enum bpf_prog_type ptype;
4591 	int ret;
4592 
4593 	if (CHECK_ATTR(BPF_PROG_DETACH))
4594 		return -EINVAL;
4595 
4596 	ptype = attach_type_to_prog_type(attr->attach_type);
4597 	if (bpf_mprog_supported(ptype)) {
4598 		if (ptype == BPF_PROG_TYPE_UNSPEC)
4599 			return -EINVAL;
4600 		if (attr->attach_flags & ~BPF_F_ATTACH_MASK_MPROG)
4601 			return -EINVAL;
4602 		if (attr->attach_bpf_fd) {
4603 			prog = bpf_prog_get_type(attr->attach_bpf_fd, ptype);
4604 			if (IS_ERR(prog))
4605 				return PTR_ERR(prog);
4606 		} else if (!bpf_mprog_detach_empty(ptype)) {
4607 			return -EPERM;
4608 		}
4609 	} else if (is_cgroup_prog_type(ptype, 0, false)) {
4610 		if (attr->attach_flags || attr->relative_fd)
4611 			return -EINVAL;
4612 	} else if (attr->attach_flags ||
4613 		   attr->relative_fd ||
4614 		   attr->expected_revision) {
4615 		return -EINVAL;
4616 	}
4617 
4618 	switch (ptype) {
4619 	case BPF_PROG_TYPE_SK_MSG:
4620 	case BPF_PROG_TYPE_SK_SKB:
4621 		ret = sock_map_prog_detach(attr, ptype);
4622 		break;
4623 	case BPF_PROG_TYPE_LIRC_MODE2:
4624 		ret = lirc_prog_detach(attr);
4625 		break;
4626 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
4627 		ret = netns_bpf_prog_detach(attr, ptype);
4628 		break;
4629 	case BPF_PROG_TYPE_CGROUP_DEVICE:
4630 	case BPF_PROG_TYPE_CGROUP_SKB:
4631 	case BPF_PROG_TYPE_CGROUP_SOCK:
4632 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
4633 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
4634 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
4635 	case BPF_PROG_TYPE_SOCK_OPS:
4636 	case BPF_PROG_TYPE_LSM:
4637 		ret = cgroup_bpf_prog_detach(attr, ptype);
4638 		break;
4639 	case BPF_PROG_TYPE_SCHED_CLS:
4640 		if (attr->attach_type == BPF_TCX_INGRESS ||
4641 		    attr->attach_type == BPF_TCX_EGRESS)
4642 			ret = tcx_prog_detach(attr, prog);
4643 		else
4644 			ret = netkit_prog_detach(attr, prog);
4645 		break;
4646 	default:
4647 		ret = -EINVAL;
4648 	}
4649 
4650 	if (prog)
4651 		bpf_prog_put(prog);
4652 	return ret;
4653 }
4654 
4655 #define BPF_PROG_QUERY_LAST_FIELD query.revision
4656 
4657 static int bpf_prog_query(const union bpf_attr *attr,
4658 			  union bpf_attr __user *uattr)
4659 {
4660 	if (!bpf_net_capable())
4661 		return -EPERM;
4662 	if (CHECK_ATTR(BPF_PROG_QUERY))
4663 		return -EINVAL;
4664 	if (attr->query.query_flags & ~BPF_F_QUERY_EFFECTIVE)
4665 		return -EINVAL;
4666 
4667 	switch (attr->query.attach_type) {
4668 	case BPF_CGROUP_INET_INGRESS:
4669 	case BPF_CGROUP_INET_EGRESS:
4670 	case BPF_CGROUP_INET_SOCK_CREATE:
4671 	case BPF_CGROUP_INET_SOCK_RELEASE:
4672 	case BPF_CGROUP_INET4_BIND:
4673 	case BPF_CGROUP_INET6_BIND:
4674 	case BPF_CGROUP_INET4_POST_BIND:
4675 	case BPF_CGROUP_INET6_POST_BIND:
4676 	case BPF_CGROUP_INET4_CONNECT:
4677 	case BPF_CGROUP_INET6_CONNECT:
4678 	case BPF_CGROUP_UNIX_CONNECT:
4679 	case BPF_CGROUP_INET4_GETPEERNAME:
4680 	case BPF_CGROUP_INET6_GETPEERNAME:
4681 	case BPF_CGROUP_UNIX_GETPEERNAME:
4682 	case BPF_CGROUP_INET4_GETSOCKNAME:
4683 	case BPF_CGROUP_INET6_GETSOCKNAME:
4684 	case BPF_CGROUP_UNIX_GETSOCKNAME:
4685 	case BPF_CGROUP_UDP4_SENDMSG:
4686 	case BPF_CGROUP_UDP6_SENDMSG:
4687 	case BPF_CGROUP_UNIX_SENDMSG:
4688 	case BPF_CGROUP_UDP4_RECVMSG:
4689 	case BPF_CGROUP_UDP6_RECVMSG:
4690 	case BPF_CGROUP_UNIX_RECVMSG:
4691 	case BPF_CGROUP_SOCK_OPS:
4692 	case BPF_CGROUP_DEVICE:
4693 	case BPF_CGROUP_SYSCTL:
4694 	case BPF_CGROUP_GETSOCKOPT:
4695 	case BPF_CGROUP_SETSOCKOPT:
4696 	case BPF_LSM_CGROUP:
4697 		return cgroup_bpf_prog_query(attr, uattr);
4698 	case BPF_LIRC_MODE2:
4699 		return lirc_prog_query(attr, uattr);
4700 	case BPF_FLOW_DISSECTOR:
4701 	case BPF_SK_LOOKUP:
4702 		return netns_bpf_prog_query(attr, uattr);
4703 	case BPF_SK_SKB_STREAM_PARSER:
4704 	case BPF_SK_SKB_STREAM_VERDICT:
4705 	case BPF_SK_MSG_VERDICT:
4706 	case BPF_SK_SKB_VERDICT:
4707 		return sock_map_bpf_prog_query(attr, uattr);
4708 	case BPF_TCX_INGRESS:
4709 	case BPF_TCX_EGRESS:
4710 		return tcx_prog_query(attr, uattr);
4711 	case BPF_NETKIT_PRIMARY:
4712 	case BPF_NETKIT_PEER:
4713 		return netkit_prog_query(attr, uattr);
4714 	default:
4715 		return -EINVAL;
4716 	}
4717 }
4718 
4719 #define BPF_PROG_TEST_RUN_LAST_FIELD test.batch_size
4720 
4721 static int bpf_prog_test_run(const union bpf_attr *attr,
4722 			     union bpf_attr __user *uattr)
4723 {
4724 	struct bpf_prog *prog;
4725 	int ret = -ENOTSUPP;
4726 
4727 	if (CHECK_ATTR(BPF_PROG_TEST_RUN))
4728 		return -EINVAL;
4729 
4730 	if ((attr->test.ctx_size_in && !attr->test.ctx_in) ||
4731 	    (!attr->test.ctx_size_in && attr->test.ctx_in))
4732 		return -EINVAL;
4733 
4734 	if ((attr->test.ctx_size_out && !attr->test.ctx_out) ||
4735 	    (!attr->test.ctx_size_out && attr->test.ctx_out))
4736 		return -EINVAL;
4737 
4738 	prog = bpf_prog_get(attr->test.prog_fd);
4739 	if (IS_ERR(prog))
4740 		return PTR_ERR(prog);
4741 
4742 	if (prog->aux->ops->test_run)
4743 		ret = prog->aux->ops->test_run(prog, attr, uattr);
4744 
4745 	bpf_prog_put(prog);
4746 	return ret;
4747 }
4748 
4749 #define BPF_OBJ_GET_NEXT_ID_LAST_FIELD next_id
4750 
4751 static int bpf_obj_get_next_id(const union bpf_attr *attr,
4752 			       union bpf_attr __user *uattr,
4753 			       struct idr *idr,
4754 			       spinlock_t *lock)
4755 {
4756 	u32 next_id = attr->start_id;
4757 	int err = 0;
4758 
4759 	if (CHECK_ATTR(BPF_OBJ_GET_NEXT_ID) || next_id >= INT_MAX)
4760 		return -EINVAL;
4761 
4762 	if (!capable(CAP_SYS_ADMIN))
4763 		return -EPERM;
4764 
4765 	next_id++;
4766 	spin_lock_bh(lock);
4767 	if (!idr_get_next(idr, &next_id))
4768 		err = -ENOENT;
4769 	spin_unlock_bh(lock);
4770 
4771 	if (!err)
4772 		err = put_user(next_id, &uattr->next_id);
4773 
4774 	return err;
4775 }
4776 
4777 struct bpf_map *bpf_map_get_curr_or_next(u32 *id)
4778 {
4779 	struct bpf_map *map;
4780 
4781 	spin_lock_bh(&map_idr_lock);
4782 again:
4783 	map = idr_get_next(&map_idr, id);
4784 	if (map) {
4785 		map = __bpf_map_inc_not_zero(map, false);
4786 		if (IS_ERR(map)) {
4787 			(*id)++;
4788 			goto again;
4789 		}
4790 	}
4791 	spin_unlock_bh(&map_idr_lock);
4792 
4793 	return map;
4794 }
4795 
4796 struct bpf_prog *bpf_prog_get_curr_or_next(u32 *id)
4797 {
4798 	struct bpf_prog *prog;
4799 
4800 	spin_lock_bh(&prog_idr_lock);
4801 again:
4802 	prog = idr_get_next(&prog_idr, id);
4803 	if (prog) {
4804 		prog = bpf_prog_inc_not_zero(prog);
4805 		if (IS_ERR(prog)) {
4806 			(*id)++;
4807 			goto again;
4808 		}
4809 	}
4810 	spin_unlock_bh(&prog_idr_lock);
4811 
4812 	return prog;
4813 }
4814 
4815 #define BPF_PROG_GET_FD_BY_ID_LAST_FIELD prog_id
4816 
4817 struct bpf_prog *bpf_prog_by_id(u32 id)
4818 {
4819 	struct bpf_prog *prog;
4820 
4821 	if (!id)
4822 		return ERR_PTR(-ENOENT);
4823 
4824 	spin_lock_bh(&prog_idr_lock);
4825 	prog = idr_find(&prog_idr, id);
4826 	if (prog)
4827 		prog = bpf_prog_inc_not_zero(prog);
4828 	else
4829 		prog = ERR_PTR(-ENOENT);
4830 	spin_unlock_bh(&prog_idr_lock);
4831 	return prog;
4832 }
4833 
4834 static int bpf_prog_get_fd_by_id(const union bpf_attr *attr)
4835 {
4836 	struct bpf_prog *prog;
4837 	u32 id = attr->prog_id;
4838 	int fd;
4839 
4840 	if (CHECK_ATTR(BPF_PROG_GET_FD_BY_ID))
4841 		return -EINVAL;
4842 
4843 	if (!capable(CAP_SYS_ADMIN))
4844 		return -EPERM;
4845 
4846 	prog = bpf_prog_by_id(id);
4847 	if (IS_ERR(prog))
4848 		return PTR_ERR(prog);
4849 
4850 	fd = bpf_prog_new_fd(prog);
4851 	if (fd < 0)
4852 		bpf_prog_put(prog);
4853 
4854 	return fd;
4855 }
4856 
4857 #define BPF_MAP_GET_FD_BY_ID_LAST_FIELD open_flags
4858 
4859 static int bpf_map_get_fd_by_id(const union bpf_attr *attr)
4860 {
4861 	struct bpf_map *map;
4862 	u32 id = attr->map_id;
4863 	int f_flags;
4864 	int fd;
4865 
4866 	if (CHECK_ATTR(BPF_MAP_GET_FD_BY_ID) ||
4867 	    attr->open_flags & ~BPF_OBJ_FLAG_MASK)
4868 		return -EINVAL;
4869 
4870 	if (!capable(CAP_SYS_ADMIN))
4871 		return -EPERM;
4872 
4873 	f_flags = bpf_get_file_flag(attr->open_flags);
4874 	if (f_flags < 0)
4875 		return f_flags;
4876 
4877 	spin_lock_bh(&map_idr_lock);
4878 	map = idr_find(&map_idr, id);
4879 	if (map)
4880 		map = __bpf_map_inc_not_zero(map, true);
4881 	else
4882 		map = ERR_PTR(-ENOENT);
4883 	spin_unlock_bh(&map_idr_lock);
4884 
4885 	if (IS_ERR(map))
4886 		return PTR_ERR(map);
4887 
4888 	fd = bpf_map_new_fd(map, f_flags);
4889 	if (fd < 0)
4890 		bpf_map_put_with_uref(map);
4891 
4892 	return fd;
4893 }
4894 
4895 static const struct bpf_map *bpf_map_from_imm(const struct bpf_prog *prog,
4896 					      unsigned long addr, u32 *off,
4897 					      u32 *type)
4898 {
4899 	const struct bpf_map *map;
4900 	int i;
4901 
4902 	mutex_lock(&prog->aux->used_maps_mutex);
4903 	for (i = 0, *off = 0; i < prog->aux->used_map_cnt; i++) {
4904 		map = prog->aux->used_maps[i];
4905 		if (map == (void *)addr) {
4906 			*type = BPF_PSEUDO_MAP_FD;
4907 			goto out;
4908 		}
4909 		if (!map->ops->map_direct_value_meta)
4910 			continue;
4911 		if (!map->ops->map_direct_value_meta(map, addr, off)) {
4912 			*type = BPF_PSEUDO_MAP_VALUE;
4913 			goto out;
4914 		}
4915 	}
4916 	map = NULL;
4917 
4918 out:
4919 	mutex_unlock(&prog->aux->used_maps_mutex);
4920 	return map;
4921 }
4922 
4923 static struct bpf_insn *bpf_insn_prepare_dump(const struct bpf_prog *prog,
4924 					      const struct cred *f_cred)
4925 {
4926 	const struct bpf_map *map;
4927 	struct bpf_insn *insns;
4928 	u32 off, type;
4929 	u64 imm;
4930 	u8 code;
4931 	int i;
4932 
4933 	insns = kmemdup(prog->insnsi, bpf_prog_insn_size(prog),
4934 			GFP_USER);
4935 	if (!insns)
4936 		return insns;
4937 
4938 	for (i = 0; i < prog->len; i++) {
4939 		code = insns[i].code;
4940 
4941 		if (code == (BPF_JMP | BPF_TAIL_CALL)) {
4942 			insns[i].code = BPF_JMP | BPF_CALL;
4943 			insns[i].imm = BPF_FUNC_tail_call;
4944 			/* fall-through */
4945 		}
4946 		if (code == (BPF_JMP | BPF_CALL) ||
4947 		    code == (BPF_JMP | BPF_CALL_ARGS)) {
4948 			if (code == (BPF_JMP | BPF_CALL_ARGS))
4949 				insns[i].code = BPF_JMP | BPF_CALL;
4950 			if (!bpf_dump_raw_ok(f_cred))
4951 				insns[i].imm = 0;
4952 			continue;
4953 		}
4954 		if (BPF_CLASS(code) == BPF_LDX && BPF_MODE(code) == BPF_PROBE_MEM) {
4955 			insns[i].code = BPF_LDX | BPF_SIZE(code) | BPF_MEM;
4956 			continue;
4957 		}
4958 
4959 		if ((BPF_CLASS(code) == BPF_LDX || BPF_CLASS(code) == BPF_STX ||
4960 		     BPF_CLASS(code) == BPF_ST) && BPF_MODE(code) == BPF_PROBE_MEM32) {
4961 			insns[i].code = BPF_CLASS(code) | BPF_SIZE(code) | BPF_MEM;
4962 			continue;
4963 		}
4964 
4965 		if (code != (BPF_LD | BPF_IMM | BPF_DW))
4966 			continue;
4967 
4968 		imm = ((u64)insns[i + 1].imm << 32) | (u32)insns[i].imm;
4969 		map = bpf_map_from_imm(prog, imm, &off, &type);
4970 		if (map) {
4971 			insns[i].src_reg = type;
4972 			insns[i].imm = map->id;
4973 			insns[i + 1].imm = off;
4974 			continue;
4975 		}
4976 	}
4977 
4978 	return insns;
4979 }
4980 
4981 static int set_info_rec_size(struct bpf_prog_info *info)
4982 {
4983 	/*
4984 	 * Ensure info.*_rec_size is the same as kernel expected size
4985 	 *
4986 	 * or
4987 	 *
4988 	 * Only allow zero *_rec_size if both _rec_size and _cnt are
4989 	 * zero.  In this case, the kernel will set the expected
4990 	 * _rec_size back to the info.
4991 	 */
4992 
4993 	if ((info->nr_func_info || info->func_info_rec_size) &&
4994 	    info->func_info_rec_size != sizeof(struct bpf_func_info))
4995 		return -EINVAL;
4996 
4997 	if ((info->nr_line_info || info->line_info_rec_size) &&
4998 	    info->line_info_rec_size != sizeof(struct bpf_line_info))
4999 		return -EINVAL;
5000 
5001 	if ((info->nr_jited_line_info || info->jited_line_info_rec_size) &&
5002 	    info->jited_line_info_rec_size != sizeof(__u64))
5003 		return -EINVAL;
5004 
5005 	info->func_info_rec_size = sizeof(struct bpf_func_info);
5006 	info->line_info_rec_size = sizeof(struct bpf_line_info);
5007 	info->jited_line_info_rec_size = sizeof(__u64);
5008 
5009 	return 0;
5010 }
5011 
5012 static int bpf_prog_get_info_by_fd(struct file *file,
5013 				   struct bpf_prog *prog,
5014 				   const union bpf_attr *attr,
5015 				   union bpf_attr __user *uattr)
5016 {
5017 	struct bpf_prog_info __user *uinfo = u64_to_user_ptr(attr->info.info);
5018 	struct btf *attach_btf = bpf_prog_get_target_btf(prog);
5019 	struct bpf_prog_info info;
5020 	u32 info_len = attr->info.info_len;
5021 	struct bpf_prog_kstats stats;
5022 	char __user *uinsns;
5023 	u32 ulen;
5024 	int err;
5025 
5026 	err = bpf_check_uarg_tail_zero(USER_BPFPTR(uinfo), sizeof(info), info_len);
5027 	if (err)
5028 		return err;
5029 	info_len = min_t(u32, sizeof(info), info_len);
5030 
5031 	memset(&info, 0, sizeof(info));
5032 	if (copy_from_user(&info, uinfo, info_len))
5033 		return -EFAULT;
5034 
5035 	info.type = prog->type;
5036 	info.id = prog->aux->id;
5037 	info.load_time = prog->aux->load_time;
5038 	info.created_by_uid = from_kuid_munged(current_user_ns(),
5039 					       prog->aux->user->uid);
5040 	info.gpl_compatible = prog->gpl_compatible;
5041 
5042 	memcpy(info.tag, prog->tag, sizeof(prog->tag));
5043 	memcpy(info.name, prog->aux->name, sizeof(prog->aux->name));
5044 
5045 	mutex_lock(&prog->aux->used_maps_mutex);
5046 	ulen = info.nr_map_ids;
5047 	info.nr_map_ids = prog->aux->used_map_cnt;
5048 	ulen = min_t(u32, info.nr_map_ids, ulen);
5049 	if (ulen) {
5050 		u32 __user *user_map_ids = u64_to_user_ptr(info.map_ids);
5051 		u32 i;
5052 
5053 		for (i = 0; i < ulen; i++)
5054 			if (put_user(prog->aux->used_maps[i]->id,
5055 				     &user_map_ids[i])) {
5056 				mutex_unlock(&prog->aux->used_maps_mutex);
5057 				return -EFAULT;
5058 			}
5059 	}
5060 	mutex_unlock(&prog->aux->used_maps_mutex);
5061 
5062 	err = set_info_rec_size(&info);
5063 	if (err)
5064 		return err;
5065 
5066 	bpf_prog_get_stats(prog, &stats);
5067 	info.run_time_ns = stats.nsecs;
5068 	info.run_cnt = stats.cnt;
5069 	info.recursion_misses = stats.misses;
5070 
5071 	info.verified_insns = prog->aux->verified_insns;
5072 	if (prog->aux->btf)
5073 		info.btf_id = btf_obj_id(prog->aux->btf);
5074 
5075 	if (!bpf_capable()) {
5076 		info.jited_prog_len = 0;
5077 		info.xlated_prog_len = 0;
5078 		info.nr_jited_ksyms = 0;
5079 		info.nr_jited_func_lens = 0;
5080 		info.nr_func_info = 0;
5081 		info.nr_line_info = 0;
5082 		info.nr_jited_line_info = 0;
5083 		goto done;
5084 	}
5085 
5086 	ulen = info.xlated_prog_len;
5087 	info.xlated_prog_len = bpf_prog_insn_size(prog);
5088 	if (info.xlated_prog_len && ulen) {
5089 		struct bpf_insn *insns_sanitized;
5090 		bool fault;
5091 
5092 		if (!prog->blinded || bpf_dump_raw_ok(file->f_cred)) {
5093 			insns_sanitized = bpf_insn_prepare_dump(prog, file->f_cred);
5094 			if (!insns_sanitized)
5095 				return -ENOMEM;
5096 			uinsns = u64_to_user_ptr(info.xlated_prog_insns);
5097 			ulen = min_t(u32, info.xlated_prog_len, ulen);
5098 			fault = copy_to_user(uinsns, insns_sanitized, ulen);
5099 			kfree(insns_sanitized);
5100 			if (fault)
5101 				return -EFAULT;
5102 		} else {
5103 			info.xlated_prog_insns = 0;
5104 		}
5105 	}
5106 
5107 	if (bpf_prog_is_offloaded(prog->aux)) {
5108 		err = bpf_prog_offload_info_fill(&info, prog);
5109 		if (err)
5110 			return err;
5111 		goto done;
5112 	}
5113 
5114 	/* NOTE: the following code is supposed to be skipped for offload.
5115 	 * bpf_prog_offload_info_fill() is the place to fill similar fields
5116 	 * for offload.
5117 	 */
5118 	ulen = info.jited_prog_len;
5119 	if (prog->aux->func_cnt) {
5120 		u32 i;
5121 
5122 		info.jited_prog_len = 0;
5123 		for (i = 0; i < prog->aux->func_cnt; i++)
5124 			info.jited_prog_len += prog->aux->func[i]->jited_len;
5125 	} else {
5126 		info.jited_prog_len = prog->jited_len;
5127 	}
5128 
5129 	if (info.jited_prog_len && ulen) {
5130 		if (bpf_dump_raw_ok(file->f_cred)) {
5131 			uinsns = u64_to_user_ptr(info.jited_prog_insns);
5132 			ulen = min_t(u32, info.jited_prog_len, ulen);
5133 
5134 			/* for multi-function programs, copy the JITed
5135 			 * instructions for all the functions
5136 			 */
5137 			if (prog->aux->func_cnt) {
5138 				u32 len, free, i;
5139 				u8 *img;
5140 
5141 				free = ulen;
5142 				for (i = 0; i < prog->aux->func_cnt; i++) {
5143 					len = prog->aux->func[i]->jited_len;
5144 					len = min_t(u32, len, free);
5145 					img = (u8 *) prog->aux->func[i]->bpf_func;
5146 					if (copy_to_user(uinsns, img, len))
5147 						return -EFAULT;
5148 					uinsns += len;
5149 					free -= len;
5150 					if (!free)
5151 						break;
5152 				}
5153 			} else {
5154 				if (copy_to_user(uinsns, prog->bpf_func, ulen))
5155 					return -EFAULT;
5156 			}
5157 		} else {
5158 			info.jited_prog_insns = 0;
5159 		}
5160 	}
5161 
5162 	ulen = info.nr_jited_ksyms;
5163 	info.nr_jited_ksyms = prog->aux->func_cnt ? : 1;
5164 	if (ulen) {
5165 		if (bpf_dump_raw_ok(file->f_cred)) {
5166 			unsigned long ksym_addr;
5167 			u64 __user *user_ksyms;
5168 			u32 i;
5169 
5170 			/* copy the address of the kernel symbol
5171 			 * corresponding to each function
5172 			 */
5173 			ulen = min_t(u32, info.nr_jited_ksyms, ulen);
5174 			user_ksyms = u64_to_user_ptr(info.jited_ksyms);
5175 			if (prog->aux->func_cnt) {
5176 				for (i = 0; i < ulen; i++) {
5177 					ksym_addr = (unsigned long)
5178 						prog->aux->func[i]->bpf_func;
5179 					if (put_user((u64) ksym_addr,
5180 						     &user_ksyms[i]))
5181 						return -EFAULT;
5182 				}
5183 			} else {
5184 				ksym_addr = (unsigned long) prog->bpf_func;
5185 				if (put_user((u64) ksym_addr, &user_ksyms[0]))
5186 					return -EFAULT;
5187 			}
5188 		} else {
5189 			info.jited_ksyms = 0;
5190 		}
5191 	}
5192 
5193 	ulen = info.nr_jited_func_lens;
5194 	info.nr_jited_func_lens = prog->aux->func_cnt ? : 1;
5195 	if (ulen) {
5196 		if (bpf_dump_raw_ok(file->f_cred)) {
5197 			u32 __user *user_lens;
5198 			u32 func_len, i;
5199 
5200 			/* copy the JITed image lengths for each function */
5201 			ulen = min_t(u32, info.nr_jited_func_lens, ulen);
5202 			user_lens = u64_to_user_ptr(info.jited_func_lens);
5203 			if (prog->aux->func_cnt) {
5204 				for (i = 0; i < ulen; i++) {
5205 					func_len =
5206 						prog->aux->func[i]->jited_len;
5207 					if (put_user(func_len, &user_lens[i]))
5208 						return -EFAULT;
5209 				}
5210 			} else {
5211 				func_len = prog->jited_len;
5212 				if (put_user(func_len, &user_lens[0]))
5213 					return -EFAULT;
5214 			}
5215 		} else {
5216 			info.jited_func_lens = 0;
5217 		}
5218 	}
5219 
5220 	info.attach_btf_id = prog->aux->attach_btf_id;
5221 	if (attach_btf)
5222 		info.attach_btf_obj_id = btf_obj_id(attach_btf);
5223 
5224 	ulen = info.nr_func_info;
5225 	info.nr_func_info = prog->aux->func_info_cnt;
5226 	if (info.nr_func_info && ulen) {
5227 		char __user *user_finfo;
5228 
5229 		user_finfo = u64_to_user_ptr(info.func_info);
5230 		ulen = min_t(u32, info.nr_func_info, ulen);
5231 		if (copy_to_user(user_finfo, prog->aux->func_info,
5232 				 info.func_info_rec_size * ulen))
5233 			return -EFAULT;
5234 	}
5235 
5236 	ulen = info.nr_line_info;
5237 	info.nr_line_info = prog->aux->nr_linfo;
5238 	if (info.nr_line_info && ulen) {
5239 		__u8 __user *user_linfo;
5240 
5241 		user_linfo = u64_to_user_ptr(info.line_info);
5242 		ulen = min_t(u32, info.nr_line_info, ulen);
5243 		if (copy_to_user(user_linfo, prog->aux->linfo,
5244 				 info.line_info_rec_size * ulen))
5245 			return -EFAULT;
5246 	}
5247 
5248 	ulen = info.nr_jited_line_info;
5249 	if (prog->aux->jited_linfo)
5250 		info.nr_jited_line_info = prog->aux->nr_linfo;
5251 	else
5252 		info.nr_jited_line_info = 0;
5253 	if (info.nr_jited_line_info && ulen) {
5254 		if (bpf_dump_raw_ok(file->f_cred)) {
5255 			unsigned long line_addr;
5256 			__u64 __user *user_linfo;
5257 			u32 i;
5258 
5259 			user_linfo = u64_to_user_ptr(info.jited_line_info);
5260 			ulen = min_t(u32, info.nr_jited_line_info, ulen);
5261 			for (i = 0; i < ulen; i++) {
5262 				line_addr = (unsigned long)prog->aux->jited_linfo[i];
5263 				if (put_user((__u64)line_addr, &user_linfo[i]))
5264 					return -EFAULT;
5265 			}
5266 		} else {
5267 			info.jited_line_info = 0;
5268 		}
5269 	}
5270 
5271 	ulen = info.nr_prog_tags;
5272 	info.nr_prog_tags = prog->aux->func_cnt ? : 1;
5273 	if (ulen) {
5274 		__u8 __user (*user_prog_tags)[BPF_TAG_SIZE];
5275 		u32 i;
5276 
5277 		user_prog_tags = u64_to_user_ptr(info.prog_tags);
5278 		ulen = min_t(u32, info.nr_prog_tags, ulen);
5279 		if (prog->aux->func_cnt) {
5280 			for (i = 0; i < ulen; i++) {
5281 				if (copy_to_user(user_prog_tags[i],
5282 						 prog->aux->func[i]->tag,
5283 						 BPF_TAG_SIZE))
5284 					return -EFAULT;
5285 			}
5286 		} else {
5287 			if (copy_to_user(user_prog_tags[0],
5288 					 prog->tag, BPF_TAG_SIZE))
5289 				return -EFAULT;
5290 		}
5291 	}
5292 
5293 done:
5294 	if (copy_to_user(uinfo, &info, info_len) ||
5295 	    put_user(info_len, &uattr->info.info_len))
5296 		return -EFAULT;
5297 
5298 	return 0;
5299 }
5300 
5301 static int bpf_map_get_info_by_fd(struct file *file,
5302 				  struct bpf_map *map,
5303 				  const union bpf_attr *attr,
5304 				  union bpf_attr __user *uattr)
5305 {
5306 	struct bpf_map_info __user *uinfo = u64_to_user_ptr(attr->info.info);
5307 	struct bpf_map_info info;
5308 	u32 info_len = attr->info.info_len;
5309 	int err;
5310 
5311 	err = bpf_check_uarg_tail_zero(USER_BPFPTR(uinfo), sizeof(info), info_len);
5312 	if (err)
5313 		return err;
5314 	info_len = min_t(u32, sizeof(info), info_len);
5315 
5316 	memset(&info, 0, sizeof(info));
5317 	if (copy_from_user(&info, uinfo, info_len))
5318 		return -EFAULT;
5319 
5320 	info.type = map->map_type;
5321 	info.id = map->id;
5322 	info.key_size = map->key_size;
5323 	info.value_size = map->value_size;
5324 	info.max_entries = map->max_entries;
5325 	info.map_flags = map->map_flags;
5326 	info.map_extra = map->map_extra;
5327 	memcpy(info.name, map->name, sizeof(map->name));
5328 
5329 	if (map->btf) {
5330 		info.btf_id = btf_obj_id(map->btf);
5331 		info.btf_key_type_id = map->btf_key_type_id;
5332 		info.btf_value_type_id = map->btf_value_type_id;
5333 	}
5334 	info.btf_vmlinux_value_type_id = map->btf_vmlinux_value_type_id;
5335 	if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS)
5336 		bpf_map_struct_ops_info_fill(&info, map);
5337 
5338 	if (bpf_map_is_offloaded(map)) {
5339 		err = bpf_map_offload_info_fill(&info, map);
5340 		if (err)
5341 			return err;
5342 	}
5343 
5344 	if (info.hash) {
5345 		char __user *uhash = u64_to_user_ptr(info.hash);
5346 
5347 		if (!map->ops->map_get_hash)
5348 			return -EINVAL;
5349 
5350 		if (info.hash_size != SHA256_DIGEST_SIZE)
5351 			return -EINVAL;
5352 
5353 		if (!READ_ONCE(map->frozen))
5354 			return -EPERM;
5355 
5356 		err = map->ops->map_get_hash(map, SHA256_DIGEST_SIZE, map->sha);
5357 		if (err != 0)
5358 			return err;
5359 
5360 		if (copy_to_user(uhash, map->sha, SHA256_DIGEST_SIZE) != 0)
5361 			return -EFAULT;
5362 	} else if (info.hash_size) {
5363 		return -EINVAL;
5364 	}
5365 
5366 	if (copy_to_user(uinfo, &info, info_len) ||
5367 	    put_user(info_len, &uattr->info.info_len))
5368 		return -EFAULT;
5369 
5370 	return 0;
5371 }
5372 
5373 static int bpf_btf_get_info_by_fd(struct file *file,
5374 				  struct btf *btf,
5375 				  const union bpf_attr *attr,
5376 				  union bpf_attr __user *uattr)
5377 {
5378 	struct bpf_btf_info __user *uinfo = u64_to_user_ptr(attr->info.info);
5379 	u32 info_len = attr->info.info_len;
5380 	int err;
5381 
5382 	err = bpf_check_uarg_tail_zero(USER_BPFPTR(uinfo), sizeof(*uinfo), info_len);
5383 	if (err)
5384 		return err;
5385 
5386 	return btf_get_info_by_fd(btf, attr, uattr);
5387 }
5388 
5389 static int bpf_link_get_info_by_fd(struct file *file,
5390 				  struct bpf_link *link,
5391 				  const union bpf_attr *attr,
5392 				  union bpf_attr __user *uattr)
5393 {
5394 	struct bpf_link_info __user *uinfo = u64_to_user_ptr(attr->info.info);
5395 	struct bpf_link_info info;
5396 	u32 info_len = attr->info.info_len;
5397 	int err;
5398 
5399 	err = bpf_check_uarg_tail_zero(USER_BPFPTR(uinfo), sizeof(info), info_len);
5400 	if (err)
5401 		return err;
5402 	info_len = min_t(u32, sizeof(info), info_len);
5403 
5404 	memset(&info, 0, sizeof(info));
5405 	if (copy_from_user(&info, uinfo, info_len))
5406 		return -EFAULT;
5407 
5408 	info.type = link->type;
5409 	info.id = link->id;
5410 	if (link->prog)
5411 		info.prog_id = link->prog->aux->id;
5412 
5413 	if (link->ops->fill_link_info) {
5414 		err = link->ops->fill_link_info(link, &info);
5415 		if (err)
5416 			return err;
5417 	}
5418 
5419 	if (copy_to_user(uinfo, &info, info_len) ||
5420 	    put_user(info_len, &uattr->info.info_len))
5421 		return -EFAULT;
5422 
5423 	return 0;
5424 }
5425 
5426 
5427 static int token_get_info_by_fd(struct file *file,
5428 				struct bpf_token *token,
5429 				const union bpf_attr *attr,
5430 				union bpf_attr __user *uattr)
5431 {
5432 	struct bpf_token_info __user *uinfo = u64_to_user_ptr(attr->info.info);
5433 	u32 info_len = attr->info.info_len;
5434 	int err;
5435 
5436 	err = bpf_check_uarg_tail_zero(USER_BPFPTR(uinfo), sizeof(*uinfo), info_len);
5437 	if (err)
5438 		return err;
5439 	return bpf_token_get_info_by_fd(token, attr, uattr);
5440 }
5441 
5442 #define BPF_OBJ_GET_INFO_BY_FD_LAST_FIELD info.info
5443 
5444 static int bpf_obj_get_info_by_fd(const union bpf_attr *attr,
5445 				  union bpf_attr __user *uattr)
5446 {
5447 	if (CHECK_ATTR(BPF_OBJ_GET_INFO_BY_FD))
5448 		return -EINVAL;
5449 
5450 	CLASS(fd, f)(attr->info.bpf_fd);
5451 	if (fd_empty(f))
5452 		return -EBADFD;
5453 
5454 	if (fd_file(f)->f_op == &bpf_prog_fops)
5455 		return bpf_prog_get_info_by_fd(fd_file(f), fd_file(f)->private_data, attr,
5456 					      uattr);
5457 	else if (fd_file(f)->f_op == &bpf_map_fops)
5458 		return bpf_map_get_info_by_fd(fd_file(f), fd_file(f)->private_data, attr,
5459 					     uattr);
5460 	else if (fd_file(f)->f_op == &btf_fops)
5461 		return bpf_btf_get_info_by_fd(fd_file(f), fd_file(f)->private_data, attr, uattr);
5462 	else if (fd_file(f)->f_op == &bpf_link_fops || fd_file(f)->f_op == &bpf_link_fops_poll)
5463 		return bpf_link_get_info_by_fd(fd_file(f), fd_file(f)->private_data,
5464 					      attr, uattr);
5465 	else if (fd_file(f)->f_op == &bpf_token_fops)
5466 		return token_get_info_by_fd(fd_file(f), fd_file(f)->private_data,
5467 					    attr, uattr);
5468 	return -EINVAL;
5469 }
5470 
5471 #define BPF_BTF_LOAD_LAST_FIELD btf_token_fd
5472 
5473 static int bpf_btf_load(const union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size)
5474 {
5475 	struct bpf_token *token = NULL;
5476 
5477 	if (CHECK_ATTR(BPF_BTF_LOAD))
5478 		return -EINVAL;
5479 
5480 	if (attr->btf_flags & ~BPF_F_TOKEN_FD)
5481 		return -EINVAL;
5482 
5483 	if (attr->btf_flags & BPF_F_TOKEN_FD) {
5484 		token = bpf_token_get_from_fd(attr->btf_token_fd);
5485 		if (IS_ERR(token))
5486 			return PTR_ERR(token);
5487 		if (!bpf_token_allow_cmd(token, BPF_BTF_LOAD)) {
5488 			bpf_token_put(token);
5489 			token = NULL;
5490 		}
5491 	}
5492 
5493 	if (!bpf_token_capable(token, CAP_BPF)) {
5494 		bpf_token_put(token);
5495 		return -EPERM;
5496 	}
5497 
5498 	bpf_token_put(token);
5499 
5500 	return btf_new_fd(attr, uattr, uattr_size);
5501 }
5502 
5503 #define BPF_BTF_GET_FD_BY_ID_LAST_FIELD fd_by_id_token_fd
5504 
5505 static int bpf_btf_get_fd_by_id(const union bpf_attr *attr)
5506 {
5507 	struct bpf_token *token = NULL;
5508 
5509 	if (CHECK_ATTR(BPF_BTF_GET_FD_BY_ID))
5510 		return -EINVAL;
5511 
5512 	if (attr->open_flags & ~BPF_F_TOKEN_FD)
5513 		return -EINVAL;
5514 
5515 	if (attr->open_flags & BPF_F_TOKEN_FD) {
5516 		token = bpf_token_get_from_fd(attr->fd_by_id_token_fd);
5517 		if (IS_ERR(token))
5518 			return PTR_ERR(token);
5519 		if (!bpf_token_allow_cmd(token, BPF_BTF_GET_FD_BY_ID)) {
5520 			bpf_token_put(token);
5521 			token = NULL;
5522 		}
5523 	}
5524 
5525 	if (!bpf_token_capable(token, CAP_SYS_ADMIN)) {
5526 		bpf_token_put(token);
5527 		return -EPERM;
5528 	}
5529 
5530 	bpf_token_put(token);
5531 
5532 	return btf_get_fd_by_id(attr->btf_id);
5533 }
5534 
5535 static int bpf_task_fd_query_copy(const union bpf_attr *attr,
5536 				    union bpf_attr __user *uattr,
5537 				    u32 prog_id, u32 fd_type,
5538 				    const char *buf, u64 probe_offset,
5539 				    u64 probe_addr)
5540 {
5541 	char __user *ubuf = u64_to_user_ptr(attr->task_fd_query.buf);
5542 	u32 len = buf ? strlen(buf) : 0, input_len;
5543 	int err = 0;
5544 
5545 	if (put_user(len, &uattr->task_fd_query.buf_len))
5546 		return -EFAULT;
5547 	input_len = attr->task_fd_query.buf_len;
5548 	if (input_len && ubuf) {
5549 		if (!len) {
5550 			/* nothing to copy, just make ubuf NULL terminated */
5551 			char zero = '\0';
5552 
5553 			if (put_user(zero, ubuf))
5554 				return -EFAULT;
5555 		} else {
5556 			err = bpf_copy_to_user(ubuf, buf, input_len, len);
5557 			if (err == -EFAULT)
5558 				return err;
5559 		}
5560 	}
5561 
5562 	if (put_user(prog_id, &uattr->task_fd_query.prog_id) ||
5563 	    put_user(fd_type, &uattr->task_fd_query.fd_type) ||
5564 	    put_user(probe_offset, &uattr->task_fd_query.probe_offset) ||
5565 	    put_user(probe_addr, &uattr->task_fd_query.probe_addr))
5566 		return -EFAULT;
5567 
5568 	return err;
5569 }
5570 
5571 #define BPF_TASK_FD_QUERY_LAST_FIELD task_fd_query.probe_addr
5572 
5573 static int bpf_task_fd_query(const union bpf_attr *attr,
5574 			     union bpf_attr __user *uattr)
5575 {
5576 	pid_t pid = attr->task_fd_query.pid;
5577 	u32 fd = attr->task_fd_query.fd;
5578 	const struct perf_event *event;
5579 	struct task_struct *task;
5580 	struct file *file;
5581 	int err;
5582 
5583 	if (CHECK_ATTR(BPF_TASK_FD_QUERY))
5584 		return -EINVAL;
5585 
5586 	if (!capable(CAP_SYS_ADMIN))
5587 		return -EPERM;
5588 
5589 	if (attr->task_fd_query.flags != 0)
5590 		return -EINVAL;
5591 
5592 	rcu_read_lock();
5593 	task = get_pid_task(find_vpid(pid), PIDTYPE_PID);
5594 	rcu_read_unlock();
5595 	if (!task)
5596 		return -ENOENT;
5597 
5598 	err = 0;
5599 	file = fget_task(task, fd);
5600 	put_task_struct(task);
5601 	if (!file)
5602 		return -EBADF;
5603 
5604 	if (file->f_op == &bpf_link_fops || file->f_op == &bpf_link_fops_poll) {
5605 		struct bpf_link *link = file->private_data;
5606 
5607 		if (link->ops == &bpf_raw_tp_link_lops) {
5608 			struct bpf_raw_tp_link *raw_tp =
5609 				container_of(link, struct bpf_raw_tp_link, link);
5610 			struct bpf_raw_event_map *btp = raw_tp->btp;
5611 
5612 			err = bpf_task_fd_query_copy(attr, uattr,
5613 						     raw_tp->link.prog->aux->id,
5614 						     BPF_FD_TYPE_RAW_TRACEPOINT,
5615 						     btp->tp->name, 0, 0);
5616 			goto put_file;
5617 		}
5618 		goto out_not_supp;
5619 	}
5620 
5621 	event = perf_get_event(file);
5622 	if (!IS_ERR(event)) {
5623 		u64 probe_offset, probe_addr;
5624 		u32 prog_id, fd_type;
5625 		const char *buf;
5626 
5627 		err = bpf_get_perf_event_info(event, &prog_id, &fd_type,
5628 					      &buf, &probe_offset,
5629 					      &probe_addr, NULL);
5630 		if (!err)
5631 			err = bpf_task_fd_query_copy(attr, uattr, prog_id,
5632 						     fd_type, buf,
5633 						     probe_offset,
5634 						     probe_addr);
5635 		goto put_file;
5636 	}
5637 
5638 out_not_supp:
5639 	err = -ENOTSUPP;
5640 put_file:
5641 	fput(file);
5642 	return err;
5643 }
5644 
5645 #define BPF_MAP_BATCH_LAST_FIELD batch.flags
5646 
5647 #define BPF_DO_BATCH(fn, ...)			\
5648 	do {					\
5649 		if (!fn) {			\
5650 			err = -ENOTSUPP;	\
5651 			goto err_put;		\
5652 		}				\
5653 		err = fn(__VA_ARGS__);		\
5654 	} while (0)
5655 
5656 static int bpf_map_do_batch(const union bpf_attr *attr,
5657 			    union bpf_attr __user *uattr,
5658 			    int cmd)
5659 {
5660 	bool has_read  = cmd == BPF_MAP_LOOKUP_BATCH ||
5661 			 cmd == BPF_MAP_LOOKUP_AND_DELETE_BATCH;
5662 	bool has_write = cmd != BPF_MAP_LOOKUP_BATCH;
5663 	struct bpf_map *map;
5664 	int err;
5665 
5666 	if (CHECK_ATTR(BPF_MAP_BATCH))
5667 		return -EINVAL;
5668 
5669 	CLASS(fd, f)(attr->batch.map_fd);
5670 
5671 	map = __bpf_map_get(f);
5672 	if (IS_ERR(map))
5673 		return PTR_ERR(map);
5674 	if (has_write)
5675 		bpf_map_write_active_inc(map);
5676 	if (has_read && !(map_get_sys_perms(map, f) & FMODE_CAN_READ)) {
5677 		err = -EPERM;
5678 		goto err_put;
5679 	}
5680 	if (has_write && !(map_get_sys_perms(map, f) & FMODE_CAN_WRITE)) {
5681 		err = -EPERM;
5682 		goto err_put;
5683 	}
5684 
5685 	if (cmd == BPF_MAP_LOOKUP_BATCH)
5686 		BPF_DO_BATCH(map->ops->map_lookup_batch, map, attr, uattr);
5687 	else if (cmd == BPF_MAP_LOOKUP_AND_DELETE_BATCH)
5688 		BPF_DO_BATCH(map->ops->map_lookup_and_delete_batch, map, attr, uattr);
5689 	else if (cmd == BPF_MAP_UPDATE_BATCH)
5690 		BPF_DO_BATCH(map->ops->map_update_batch, map, fd_file(f), attr, uattr);
5691 	else
5692 		BPF_DO_BATCH(map->ops->map_delete_batch, map, attr, uattr);
5693 err_put:
5694 	if (has_write) {
5695 		maybe_wait_bpf_programs(map);
5696 		bpf_map_write_active_dec(map);
5697 	}
5698 	return err;
5699 }
5700 
5701 #define BPF_LINK_CREATE_LAST_FIELD link_create.uprobe_multi.pid
5702 static int link_create(union bpf_attr *attr, bpfptr_t uattr)
5703 {
5704 	struct bpf_prog *prog;
5705 	int ret;
5706 
5707 	if (CHECK_ATTR(BPF_LINK_CREATE))
5708 		return -EINVAL;
5709 
5710 	if (attr->link_create.attach_type == BPF_STRUCT_OPS)
5711 		return bpf_struct_ops_link_create(attr);
5712 
5713 	prog = bpf_prog_get(attr->link_create.prog_fd);
5714 	if (IS_ERR(prog))
5715 		return PTR_ERR(prog);
5716 
5717 	ret = bpf_prog_attach_check_attach_type(prog,
5718 						attr->link_create.attach_type);
5719 	if (ret)
5720 		goto out;
5721 
5722 	switch (prog->type) {
5723 	case BPF_PROG_TYPE_CGROUP_SKB:
5724 	case BPF_PROG_TYPE_CGROUP_SOCK:
5725 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
5726 	case BPF_PROG_TYPE_SOCK_OPS:
5727 	case BPF_PROG_TYPE_CGROUP_DEVICE:
5728 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
5729 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
5730 		ret = cgroup_bpf_link_attach(attr, prog);
5731 		break;
5732 	case BPF_PROG_TYPE_EXT:
5733 		ret = bpf_tracing_prog_attach(prog,
5734 					      attr->link_create.target_fd,
5735 					      attr->link_create.target_btf_id,
5736 					      attr->link_create.tracing.cookie,
5737 					      attr->link_create.attach_type);
5738 		break;
5739 	case BPF_PROG_TYPE_LSM:
5740 	case BPF_PROG_TYPE_TRACING:
5741 		if (attr->link_create.attach_type != prog->expected_attach_type) {
5742 			ret = -EINVAL;
5743 			goto out;
5744 		}
5745 		if (prog->expected_attach_type == BPF_TRACE_RAW_TP)
5746 			ret = bpf_raw_tp_link_attach(prog, NULL, attr->link_create.tracing.cookie,
5747 						     attr->link_create.attach_type);
5748 		else if (prog->expected_attach_type == BPF_TRACE_ITER)
5749 			ret = bpf_iter_link_attach(attr, uattr, prog);
5750 		else if (prog->expected_attach_type == BPF_LSM_CGROUP)
5751 			ret = cgroup_bpf_link_attach(attr, prog);
5752 		else
5753 			ret = bpf_tracing_prog_attach(prog,
5754 						      attr->link_create.target_fd,
5755 						      attr->link_create.target_btf_id,
5756 						      attr->link_create.tracing.cookie,
5757 						      attr->link_create.attach_type);
5758 		break;
5759 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
5760 	case BPF_PROG_TYPE_SK_LOOKUP:
5761 		ret = netns_bpf_link_create(attr, prog);
5762 		break;
5763 	case BPF_PROG_TYPE_SK_MSG:
5764 	case BPF_PROG_TYPE_SK_SKB:
5765 		ret = sock_map_link_create(attr, prog);
5766 		break;
5767 #ifdef CONFIG_NET
5768 	case BPF_PROG_TYPE_XDP:
5769 		ret = bpf_xdp_link_attach(attr, prog);
5770 		break;
5771 	case BPF_PROG_TYPE_SCHED_CLS:
5772 		if (attr->link_create.attach_type == BPF_TCX_INGRESS ||
5773 		    attr->link_create.attach_type == BPF_TCX_EGRESS)
5774 			ret = tcx_link_attach(attr, prog);
5775 		else
5776 			ret = netkit_link_attach(attr, prog);
5777 		break;
5778 	case BPF_PROG_TYPE_NETFILTER:
5779 		ret = bpf_nf_link_attach(attr, prog);
5780 		break;
5781 #endif
5782 	case BPF_PROG_TYPE_PERF_EVENT:
5783 	case BPF_PROG_TYPE_TRACEPOINT:
5784 		ret = bpf_perf_link_attach(attr, prog);
5785 		break;
5786 	case BPF_PROG_TYPE_KPROBE:
5787 		if (attr->link_create.attach_type == BPF_PERF_EVENT)
5788 			ret = bpf_perf_link_attach(attr, prog);
5789 		else if (attr->link_create.attach_type == BPF_TRACE_KPROBE_MULTI ||
5790 			 attr->link_create.attach_type == BPF_TRACE_KPROBE_SESSION)
5791 			ret = bpf_kprobe_multi_link_attach(attr, prog);
5792 		else if (attr->link_create.attach_type == BPF_TRACE_UPROBE_MULTI ||
5793 			 attr->link_create.attach_type == BPF_TRACE_UPROBE_SESSION)
5794 			ret = bpf_uprobe_multi_link_attach(attr, prog);
5795 		break;
5796 	default:
5797 		ret = -EINVAL;
5798 	}
5799 
5800 out:
5801 	if (ret < 0)
5802 		bpf_prog_put(prog);
5803 	return ret;
5804 }
5805 
5806 static int link_update_map(struct bpf_link *link, union bpf_attr *attr)
5807 {
5808 	struct bpf_map *new_map, *old_map = NULL;
5809 	int ret;
5810 
5811 	new_map = bpf_map_get(attr->link_update.new_map_fd);
5812 	if (IS_ERR(new_map))
5813 		return PTR_ERR(new_map);
5814 
5815 	if (attr->link_update.flags & BPF_F_REPLACE) {
5816 		old_map = bpf_map_get(attr->link_update.old_map_fd);
5817 		if (IS_ERR(old_map)) {
5818 			ret = PTR_ERR(old_map);
5819 			goto out_put;
5820 		}
5821 	} else if (attr->link_update.old_map_fd) {
5822 		ret = -EINVAL;
5823 		goto out_put;
5824 	}
5825 
5826 	ret = link->ops->update_map(link, new_map, old_map);
5827 
5828 	if (old_map)
5829 		bpf_map_put(old_map);
5830 out_put:
5831 	bpf_map_put(new_map);
5832 	return ret;
5833 }
5834 
5835 #define BPF_LINK_UPDATE_LAST_FIELD link_update.old_prog_fd
5836 
5837 static int link_update(union bpf_attr *attr)
5838 {
5839 	struct bpf_prog *old_prog = NULL, *new_prog;
5840 	struct bpf_link *link;
5841 	u32 flags;
5842 	int ret;
5843 
5844 	if (CHECK_ATTR(BPF_LINK_UPDATE))
5845 		return -EINVAL;
5846 
5847 	flags = attr->link_update.flags;
5848 	if (flags & ~BPF_F_REPLACE)
5849 		return -EINVAL;
5850 
5851 	link = bpf_link_get_from_fd(attr->link_update.link_fd);
5852 	if (IS_ERR(link))
5853 		return PTR_ERR(link);
5854 
5855 	if (link->ops->update_map) {
5856 		ret = link_update_map(link, attr);
5857 		goto out_put_link;
5858 	}
5859 
5860 	new_prog = bpf_prog_get(attr->link_update.new_prog_fd);
5861 	if (IS_ERR(new_prog)) {
5862 		ret = PTR_ERR(new_prog);
5863 		goto out_put_link;
5864 	}
5865 
5866 	if (flags & BPF_F_REPLACE) {
5867 		old_prog = bpf_prog_get(attr->link_update.old_prog_fd);
5868 		if (IS_ERR(old_prog)) {
5869 			ret = PTR_ERR(old_prog);
5870 			old_prog = NULL;
5871 			goto out_put_progs;
5872 		}
5873 	} else if (attr->link_update.old_prog_fd) {
5874 		ret = -EINVAL;
5875 		goto out_put_progs;
5876 	}
5877 
5878 	if (link->ops->update_prog)
5879 		ret = link->ops->update_prog(link, new_prog, old_prog);
5880 	else
5881 		ret = -EINVAL;
5882 
5883 out_put_progs:
5884 	if (old_prog)
5885 		bpf_prog_put(old_prog);
5886 	if (ret)
5887 		bpf_prog_put(new_prog);
5888 out_put_link:
5889 	bpf_link_put_direct(link);
5890 	return ret;
5891 }
5892 
5893 #define BPF_LINK_DETACH_LAST_FIELD link_detach.link_fd
5894 
5895 static int link_detach(union bpf_attr *attr)
5896 {
5897 	struct bpf_link *link;
5898 	int ret;
5899 
5900 	if (CHECK_ATTR(BPF_LINK_DETACH))
5901 		return -EINVAL;
5902 
5903 	link = bpf_link_get_from_fd(attr->link_detach.link_fd);
5904 	if (IS_ERR(link))
5905 		return PTR_ERR(link);
5906 
5907 	if (link->ops->detach)
5908 		ret = link->ops->detach(link);
5909 	else
5910 		ret = -EOPNOTSUPP;
5911 
5912 	bpf_link_put_direct(link);
5913 	return ret;
5914 }
5915 
5916 struct bpf_link *bpf_link_inc_not_zero(struct bpf_link *link)
5917 {
5918 	return atomic64_fetch_add_unless(&link->refcnt, 1, 0) ? link : ERR_PTR(-ENOENT);
5919 }
5920 EXPORT_SYMBOL(bpf_link_inc_not_zero);
5921 
5922 struct bpf_link *bpf_link_by_id(u32 id)
5923 {
5924 	struct bpf_link *link;
5925 
5926 	if (!id)
5927 		return ERR_PTR(-ENOENT);
5928 
5929 	spin_lock_bh(&link_idr_lock);
5930 	/* before link is "settled", ID is 0, pretend it doesn't exist yet */
5931 	link = idr_find(&link_idr, id);
5932 	if (link) {
5933 		if (link->id)
5934 			link = bpf_link_inc_not_zero(link);
5935 		else
5936 			link = ERR_PTR(-EAGAIN);
5937 	} else {
5938 		link = ERR_PTR(-ENOENT);
5939 	}
5940 	spin_unlock_bh(&link_idr_lock);
5941 	return link;
5942 }
5943 
5944 struct bpf_link *bpf_link_get_curr_or_next(u32 *id)
5945 {
5946 	struct bpf_link *link;
5947 
5948 	spin_lock_bh(&link_idr_lock);
5949 again:
5950 	link = idr_get_next(&link_idr, id);
5951 	if (link) {
5952 		link = bpf_link_inc_not_zero(link);
5953 		if (IS_ERR(link)) {
5954 			(*id)++;
5955 			goto again;
5956 		}
5957 	}
5958 	spin_unlock_bh(&link_idr_lock);
5959 
5960 	return link;
5961 }
5962 
5963 #define BPF_LINK_GET_FD_BY_ID_LAST_FIELD link_id
5964 
5965 static int bpf_link_get_fd_by_id(const union bpf_attr *attr)
5966 {
5967 	struct bpf_link *link;
5968 	u32 id = attr->link_id;
5969 	int fd;
5970 
5971 	if (CHECK_ATTR(BPF_LINK_GET_FD_BY_ID))
5972 		return -EINVAL;
5973 
5974 	if (!capable(CAP_SYS_ADMIN))
5975 		return -EPERM;
5976 
5977 	link = bpf_link_by_id(id);
5978 	if (IS_ERR(link))
5979 		return PTR_ERR(link);
5980 
5981 	fd = bpf_link_new_fd(link);
5982 	if (fd < 0)
5983 		bpf_link_put_direct(link);
5984 
5985 	return fd;
5986 }
5987 
5988 DEFINE_MUTEX(bpf_stats_enabled_mutex);
5989 
5990 static int bpf_stats_release(struct inode *inode, struct file *file)
5991 {
5992 	mutex_lock(&bpf_stats_enabled_mutex);
5993 	static_key_slow_dec(&bpf_stats_enabled_key.key);
5994 	mutex_unlock(&bpf_stats_enabled_mutex);
5995 	return 0;
5996 }
5997 
5998 static const struct file_operations bpf_stats_fops = {
5999 	.release = bpf_stats_release,
6000 };
6001 
6002 static int bpf_enable_runtime_stats(void)
6003 {
6004 	int fd;
6005 
6006 	mutex_lock(&bpf_stats_enabled_mutex);
6007 
6008 	/* Set a very high limit to avoid overflow */
6009 	if (static_key_count(&bpf_stats_enabled_key.key) > INT_MAX / 2) {
6010 		mutex_unlock(&bpf_stats_enabled_mutex);
6011 		return -EBUSY;
6012 	}
6013 
6014 	fd = anon_inode_getfd("bpf-stats", &bpf_stats_fops, NULL, O_CLOEXEC);
6015 	if (fd >= 0)
6016 		static_key_slow_inc(&bpf_stats_enabled_key.key);
6017 
6018 	mutex_unlock(&bpf_stats_enabled_mutex);
6019 	return fd;
6020 }
6021 
6022 #define BPF_ENABLE_STATS_LAST_FIELD enable_stats.type
6023 
6024 static int bpf_enable_stats(union bpf_attr *attr)
6025 {
6026 
6027 	if (CHECK_ATTR(BPF_ENABLE_STATS))
6028 		return -EINVAL;
6029 
6030 	if (!capable(CAP_SYS_ADMIN))
6031 		return -EPERM;
6032 
6033 	switch (attr->enable_stats.type) {
6034 	case BPF_STATS_RUN_TIME:
6035 		return bpf_enable_runtime_stats();
6036 	default:
6037 		break;
6038 	}
6039 	return -EINVAL;
6040 }
6041 
6042 #define BPF_ITER_CREATE_LAST_FIELD iter_create.flags
6043 
6044 static int bpf_iter_create(union bpf_attr *attr)
6045 {
6046 	struct bpf_link *link;
6047 	int err;
6048 
6049 	if (CHECK_ATTR(BPF_ITER_CREATE))
6050 		return -EINVAL;
6051 
6052 	if (attr->iter_create.flags)
6053 		return -EINVAL;
6054 
6055 	link = bpf_link_get_from_fd(attr->iter_create.link_fd);
6056 	if (IS_ERR(link))
6057 		return PTR_ERR(link);
6058 
6059 	err = bpf_iter_new_fd(link);
6060 	bpf_link_put_direct(link);
6061 
6062 	return err;
6063 }
6064 
6065 #define BPF_PROG_BIND_MAP_LAST_FIELD prog_bind_map.flags
6066 
6067 static int bpf_prog_bind_map(union bpf_attr *attr)
6068 {
6069 	struct bpf_prog *prog;
6070 	struct bpf_map *map;
6071 	struct bpf_map **used_maps_old, **used_maps_new;
6072 	int i, ret = 0;
6073 
6074 	if (CHECK_ATTR(BPF_PROG_BIND_MAP))
6075 		return -EINVAL;
6076 
6077 	if (attr->prog_bind_map.flags)
6078 		return -EINVAL;
6079 
6080 	prog = bpf_prog_get(attr->prog_bind_map.prog_fd);
6081 	if (IS_ERR(prog))
6082 		return PTR_ERR(prog);
6083 
6084 	map = bpf_map_get(attr->prog_bind_map.map_fd);
6085 	if (IS_ERR(map)) {
6086 		ret = PTR_ERR(map);
6087 		goto out_prog_put;
6088 	}
6089 
6090 	mutex_lock(&prog->aux->used_maps_mutex);
6091 
6092 	used_maps_old = prog->aux->used_maps;
6093 
6094 	for (i = 0; i < prog->aux->used_map_cnt; i++)
6095 		if (used_maps_old[i] == map) {
6096 			bpf_map_put(map);
6097 			goto out_unlock;
6098 		}
6099 
6100 	used_maps_new = kmalloc_objs(used_maps_new[0],
6101 				     prog->aux->used_map_cnt + 1);
6102 	if (!used_maps_new) {
6103 		ret = -ENOMEM;
6104 		goto out_unlock;
6105 	}
6106 
6107 	/* The bpf program will not access the bpf map, but for the sake of
6108 	 * simplicity, increase sleepable_refcnt for sleepable program as well.
6109 	 */
6110 	if (prog->sleepable)
6111 		atomic64_inc(&map->sleepable_refcnt);
6112 	memcpy(used_maps_new, used_maps_old,
6113 	       sizeof(used_maps_old[0]) * prog->aux->used_map_cnt);
6114 	used_maps_new[prog->aux->used_map_cnt] = map;
6115 
6116 	prog->aux->used_map_cnt++;
6117 	prog->aux->used_maps = used_maps_new;
6118 
6119 	kfree(used_maps_old);
6120 
6121 out_unlock:
6122 	mutex_unlock(&prog->aux->used_maps_mutex);
6123 
6124 	if (ret)
6125 		bpf_map_put(map);
6126 out_prog_put:
6127 	bpf_prog_put(prog);
6128 	return ret;
6129 }
6130 
6131 #define BPF_TOKEN_CREATE_LAST_FIELD token_create.bpffs_fd
6132 
6133 static int token_create(union bpf_attr *attr)
6134 {
6135 	if (CHECK_ATTR(BPF_TOKEN_CREATE))
6136 		return -EINVAL;
6137 
6138 	/* no flags are supported yet */
6139 	if (attr->token_create.flags)
6140 		return -EINVAL;
6141 
6142 	return bpf_token_create(attr);
6143 }
6144 
6145 #define BPF_PROG_STREAM_READ_BY_FD_LAST_FIELD prog_stream_read.prog_fd
6146 
6147 static int prog_stream_read(union bpf_attr *attr)
6148 {
6149 	char __user *buf = u64_to_user_ptr(attr->prog_stream_read.stream_buf);
6150 	u32 len = attr->prog_stream_read.stream_buf_len;
6151 	struct bpf_prog *prog;
6152 	int ret;
6153 
6154 	if (CHECK_ATTR(BPF_PROG_STREAM_READ_BY_FD))
6155 		return -EINVAL;
6156 
6157 	prog = bpf_prog_get(attr->prog_stream_read.prog_fd);
6158 	if (IS_ERR(prog))
6159 		return PTR_ERR(prog);
6160 
6161 	ret = bpf_prog_stream_read(prog, attr->prog_stream_read.stream_id, buf, len);
6162 	bpf_prog_put(prog);
6163 
6164 	return ret;
6165 }
6166 
6167 #define BPF_PROG_ASSOC_STRUCT_OPS_LAST_FIELD prog_assoc_struct_ops.prog_fd
6168 
6169 static int prog_assoc_struct_ops(union bpf_attr *attr)
6170 {
6171 	struct bpf_prog *prog;
6172 	struct bpf_map *map;
6173 	int ret;
6174 
6175 	if (CHECK_ATTR(BPF_PROG_ASSOC_STRUCT_OPS))
6176 		return -EINVAL;
6177 
6178 	if (attr->prog_assoc_struct_ops.flags)
6179 		return -EINVAL;
6180 
6181 	prog = bpf_prog_get(attr->prog_assoc_struct_ops.prog_fd);
6182 	if (IS_ERR(prog))
6183 		return PTR_ERR(prog);
6184 
6185 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS) {
6186 		ret = -EINVAL;
6187 		goto put_prog;
6188 	}
6189 
6190 	map = bpf_map_get(attr->prog_assoc_struct_ops.map_fd);
6191 	if (IS_ERR(map)) {
6192 		ret = PTR_ERR(map);
6193 		goto put_prog;
6194 	}
6195 
6196 	if (map->map_type != BPF_MAP_TYPE_STRUCT_OPS) {
6197 		ret = -EINVAL;
6198 		goto put_map;
6199 	}
6200 
6201 	ret = bpf_prog_assoc_struct_ops(prog, map);
6202 
6203 put_map:
6204 	bpf_map_put(map);
6205 put_prog:
6206 	bpf_prog_put(prog);
6207 	return ret;
6208 }
6209 
6210 static int __sys_bpf(enum bpf_cmd cmd, bpfptr_t uattr, unsigned int size)
6211 {
6212 	union bpf_attr attr;
6213 	int err;
6214 
6215 	err = bpf_check_uarg_tail_zero(uattr, sizeof(attr), size);
6216 	if (err)
6217 		return err;
6218 	size = min_t(u32, size, sizeof(attr));
6219 
6220 	/* copy attributes from user space, may be less than sizeof(bpf_attr) */
6221 	memset(&attr, 0, sizeof(attr));
6222 	if (copy_from_bpfptr(&attr, uattr, size) != 0)
6223 		return -EFAULT;
6224 
6225 	err = security_bpf(cmd, &attr, size, uattr.is_kernel);
6226 	if (err < 0)
6227 		return err;
6228 
6229 	switch (cmd) {
6230 	case BPF_MAP_CREATE:
6231 		err = map_create(&attr, uattr);
6232 		break;
6233 	case BPF_MAP_LOOKUP_ELEM:
6234 		err = map_lookup_elem(&attr);
6235 		break;
6236 	case BPF_MAP_UPDATE_ELEM:
6237 		err = map_update_elem(&attr, uattr);
6238 		break;
6239 	case BPF_MAP_DELETE_ELEM:
6240 		err = map_delete_elem(&attr, uattr);
6241 		break;
6242 	case BPF_MAP_GET_NEXT_KEY:
6243 		err = map_get_next_key(&attr);
6244 		break;
6245 	case BPF_MAP_FREEZE:
6246 		err = map_freeze(&attr);
6247 		break;
6248 	case BPF_PROG_LOAD:
6249 		err = bpf_prog_load(&attr, uattr, size);
6250 		break;
6251 	case BPF_OBJ_PIN:
6252 		err = bpf_obj_pin(&attr);
6253 		break;
6254 	case BPF_OBJ_GET:
6255 		err = bpf_obj_get(&attr);
6256 		break;
6257 	case BPF_PROG_ATTACH:
6258 		err = bpf_prog_attach(&attr);
6259 		break;
6260 	case BPF_PROG_DETACH:
6261 		err = bpf_prog_detach(&attr);
6262 		break;
6263 	case BPF_PROG_QUERY:
6264 		err = bpf_prog_query(&attr, uattr.user);
6265 		break;
6266 	case BPF_PROG_TEST_RUN:
6267 		err = bpf_prog_test_run(&attr, uattr.user);
6268 		break;
6269 	case BPF_PROG_GET_NEXT_ID:
6270 		err = bpf_obj_get_next_id(&attr, uattr.user,
6271 					  &prog_idr, &prog_idr_lock);
6272 		break;
6273 	case BPF_MAP_GET_NEXT_ID:
6274 		err = bpf_obj_get_next_id(&attr, uattr.user,
6275 					  &map_idr, &map_idr_lock);
6276 		break;
6277 	case BPF_BTF_GET_NEXT_ID:
6278 		err = bpf_obj_get_next_id(&attr, uattr.user,
6279 					  &btf_idr, &btf_idr_lock);
6280 		break;
6281 	case BPF_PROG_GET_FD_BY_ID:
6282 		err = bpf_prog_get_fd_by_id(&attr);
6283 		break;
6284 	case BPF_MAP_GET_FD_BY_ID:
6285 		err = bpf_map_get_fd_by_id(&attr);
6286 		break;
6287 	case BPF_OBJ_GET_INFO_BY_FD:
6288 		err = bpf_obj_get_info_by_fd(&attr, uattr.user);
6289 		break;
6290 	case BPF_RAW_TRACEPOINT_OPEN:
6291 		err = bpf_raw_tracepoint_open(&attr);
6292 		break;
6293 	case BPF_BTF_LOAD:
6294 		err = bpf_btf_load(&attr, uattr, size);
6295 		break;
6296 	case BPF_BTF_GET_FD_BY_ID:
6297 		err = bpf_btf_get_fd_by_id(&attr);
6298 		break;
6299 	case BPF_TASK_FD_QUERY:
6300 		err = bpf_task_fd_query(&attr, uattr.user);
6301 		break;
6302 	case BPF_MAP_LOOKUP_AND_DELETE_ELEM:
6303 		err = map_lookup_and_delete_elem(&attr);
6304 		break;
6305 	case BPF_MAP_LOOKUP_BATCH:
6306 		err = bpf_map_do_batch(&attr, uattr.user, BPF_MAP_LOOKUP_BATCH);
6307 		break;
6308 	case BPF_MAP_LOOKUP_AND_DELETE_BATCH:
6309 		err = bpf_map_do_batch(&attr, uattr.user,
6310 				       BPF_MAP_LOOKUP_AND_DELETE_BATCH);
6311 		break;
6312 	case BPF_MAP_UPDATE_BATCH:
6313 		err = bpf_map_do_batch(&attr, uattr.user, BPF_MAP_UPDATE_BATCH);
6314 		break;
6315 	case BPF_MAP_DELETE_BATCH:
6316 		err = bpf_map_do_batch(&attr, uattr.user, BPF_MAP_DELETE_BATCH);
6317 		break;
6318 	case BPF_LINK_CREATE:
6319 		err = link_create(&attr, uattr);
6320 		break;
6321 	case BPF_LINK_UPDATE:
6322 		err = link_update(&attr);
6323 		break;
6324 	case BPF_LINK_GET_FD_BY_ID:
6325 		err = bpf_link_get_fd_by_id(&attr);
6326 		break;
6327 	case BPF_LINK_GET_NEXT_ID:
6328 		err = bpf_obj_get_next_id(&attr, uattr.user,
6329 					  &link_idr, &link_idr_lock);
6330 		break;
6331 	case BPF_ENABLE_STATS:
6332 		err = bpf_enable_stats(&attr);
6333 		break;
6334 	case BPF_ITER_CREATE:
6335 		err = bpf_iter_create(&attr);
6336 		break;
6337 	case BPF_LINK_DETACH:
6338 		err = link_detach(&attr);
6339 		break;
6340 	case BPF_PROG_BIND_MAP:
6341 		err = bpf_prog_bind_map(&attr);
6342 		break;
6343 	case BPF_TOKEN_CREATE:
6344 		err = token_create(&attr);
6345 		break;
6346 	case BPF_PROG_STREAM_READ_BY_FD:
6347 		err = prog_stream_read(&attr);
6348 		break;
6349 	case BPF_PROG_ASSOC_STRUCT_OPS:
6350 		err = prog_assoc_struct_ops(&attr);
6351 		break;
6352 	default:
6353 		err = -EINVAL;
6354 		break;
6355 	}
6356 
6357 	return err;
6358 }
6359 
6360 SYSCALL_DEFINE3(bpf, int, cmd, union bpf_attr __user *, uattr, unsigned int, size)
6361 {
6362 	return __sys_bpf(cmd, USER_BPFPTR(uattr), size);
6363 }
6364 
6365 static bool syscall_prog_is_valid_access(int off, int size,
6366 					 enum bpf_access_type type,
6367 					 const struct bpf_prog *prog,
6368 					 struct bpf_insn_access_aux *info)
6369 {
6370 	if (off < 0 || off >= U16_MAX)
6371 		return false;
6372 	if (off % size != 0)
6373 		return false;
6374 	return true;
6375 }
6376 
6377 BPF_CALL_3(bpf_sys_bpf, int, cmd, union bpf_attr *, attr, u32, attr_size)
6378 {
6379 	switch (cmd) {
6380 	case BPF_MAP_CREATE:
6381 	case BPF_MAP_DELETE_ELEM:
6382 	case BPF_MAP_UPDATE_ELEM:
6383 	case BPF_MAP_FREEZE:
6384 	case BPF_MAP_GET_FD_BY_ID:
6385 	case BPF_PROG_LOAD:
6386 	case BPF_BTF_LOAD:
6387 	case BPF_LINK_CREATE:
6388 	case BPF_RAW_TRACEPOINT_OPEN:
6389 		break;
6390 	default:
6391 		return -EINVAL;
6392 	}
6393 	return __sys_bpf(cmd, KERNEL_BPFPTR(attr), attr_size);
6394 }
6395 
6396 
6397 /* To shut up -Wmissing-prototypes.
6398  * This function is used by the kernel light skeleton
6399  * to load bpf programs when modules are loaded or during kernel boot.
6400  * See tools/lib/bpf/skel_internal.h
6401  */
6402 int kern_sys_bpf(int cmd, union bpf_attr *attr, unsigned int size);
6403 
6404 int kern_sys_bpf(int cmd, union bpf_attr *attr, unsigned int size)
6405 {
6406 	struct bpf_prog * __maybe_unused prog;
6407 	struct bpf_tramp_run_ctx __maybe_unused run_ctx;
6408 
6409 	switch (cmd) {
6410 #ifdef CONFIG_BPF_JIT /* __bpf_prog_enter_sleepable used by trampoline and JIT */
6411 	case BPF_PROG_TEST_RUN:
6412 		if (attr->test.data_in || attr->test.data_out ||
6413 		    attr->test.ctx_out || attr->test.duration ||
6414 		    attr->test.repeat || attr->test.flags)
6415 			return -EINVAL;
6416 
6417 		prog = bpf_prog_get_type(attr->test.prog_fd, BPF_PROG_TYPE_SYSCALL);
6418 		if (IS_ERR(prog))
6419 			return PTR_ERR(prog);
6420 
6421 		if (attr->test.ctx_size_in < prog->aux->max_ctx_offset ||
6422 		    attr->test.ctx_size_in > U16_MAX) {
6423 			bpf_prog_put(prog);
6424 			return -EINVAL;
6425 		}
6426 
6427 		run_ctx.bpf_cookie = 0;
6428 		if (!__bpf_prog_enter_sleepable_recur(prog, &run_ctx)) {
6429 			/* recursion detected */
6430 			__bpf_prog_exit_sleepable_recur(prog, 0, &run_ctx);
6431 			bpf_prog_put(prog);
6432 			return -EBUSY;
6433 		}
6434 		attr->test.retval = bpf_prog_run(prog, (void *) (long) attr->test.ctx_in);
6435 		__bpf_prog_exit_sleepable_recur(prog, 0 /* bpf_prog_run does runtime stats */,
6436 						&run_ctx);
6437 		bpf_prog_put(prog);
6438 		return 0;
6439 #endif
6440 	default:
6441 		return ____bpf_sys_bpf(cmd, attr, size);
6442 	}
6443 }
6444 EXPORT_SYMBOL_NS(kern_sys_bpf, "BPF_INTERNAL");
6445 
6446 static const struct bpf_func_proto bpf_sys_bpf_proto = {
6447 	.func		= bpf_sys_bpf,
6448 	.gpl_only	= false,
6449 	.ret_type	= RET_INTEGER,
6450 	.arg1_type	= ARG_ANYTHING,
6451 	.arg2_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
6452 	.arg3_type	= ARG_CONST_SIZE,
6453 };
6454 
6455 const struct bpf_func_proto * __weak
6456 tracing_prog_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
6457 {
6458 	return bpf_base_func_proto(func_id, prog);
6459 }
6460 
6461 BPF_CALL_1(bpf_sys_close, u32, fd)
6462 {
6463 	/* When bpf program calls this helper there should not be
6464 	 * an fdget() without matching completed fdput().
6465 	 * This helper is allowed in the following callchain only:
6466 	 * sys_bpf->prog_test_run->bpf_prog->bpf_sys_close
6467 	 */
6468 	return close_fd(fd);
6469 }
6470 
6471 static const struct bpf_func_proto bpf_sys_close_proto = {
6472 	.func		= bpf_sys_close,
6473 	.gpl_only	= false,
6474 	.ret_type	= RET_INTEGER,
6475 	.arg1_type	= ARG_ANYTHING,
6476 };
6477 
6478 BPF_CALL_4(bpf_kallsyms_lookup_name, const char *, name, int, name_sz, int, flags, u64 *, res)
6479 {
6480 	*res = 0;
6481 	if (flags)
6482 		return -EINVAL;
6483 
6484 	if (name_sz <= 1 || name[name_sz - 1])
6485 		return -EINVAL;
6486 
6487 	if (!bpf_dump_raw_ok(current_cred()))
6488 		return -EPERM;
6489 
6490 	*res = kallsyms_lookup_name(name);
6491 	return *res ? 0 : -ENOENT;
6492 }
6493 
6494 static const struct bpf_func_proto bpf_kallsyms_lookup_name_proto = {
6495 	.func		= bpf_kallsyms_lookup_name,
6496 	.gpl_only	= false,
6497 	.ret_type	= RET_INTEGER,
6498 	.arg1_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
6499 	.arg2_type	= ARG_CONST_SIZE_OR_ZERO,
6500 	.arg3_type	= ARG_ANYTHING,
6501 	.arg4_type	= ARG_PTR_TO_FIXED_SIZE_MEM | MEM_UNINIT | MEM_WRITE | MEM_ALIGNED,
6502 	.arg4_size	= sizeof(u64),
6503 };
6504 
6505 static const struct bpf_func_proto *
6506 syscall_prog_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
6507 {
6508 	switch (func_id) {
6509 	case BPF_FUNC_sys_bpf:
6510 		return !bpf_token_capable(prog->aux->token, CAP_PERFMON)
6511 		       ? NULL : &bpf_sys_bpf_proto;
6512 	case BPF_FUNC_btf_find_by_name_kind:
6513 		return &bpf_btf_find_by_name_kind_proto;
6514 	case BPF_FUNC_sys_close:
6515 		return &bpf_sys_close_proto;
6516 	case BPF_FUNC_kallsyms_lookup_name:
6517 		return &bpf_kallsyms_lookup_name_proto;
6518 	default:
6519 		return tracing_prog_func_proto(func_id, prog);
6520 	}
6521 }
6522 
6523 const struct bpf_verifier_ops bpf_syscall_verifier_ops = {
6524 	.get_func_proto  = syscall_prog_func_proto,
6525 	.is_valid_access = syscall_prog_is_valid_access,
6526 };
6527 
6528 const struct bpf_prog_ops bpf_syscall_prog_ops = {
6529 	.test_run = bpf_prog_test_run_syscall,
6530 };
6531 
6532 #ifdef CONFIG_SYSCTL
6533 static int bpf_stats_handler(const struct ctl_table *table, int write,
6534 			     void *buffer, size_t *lenp, loff_t *ppos)
6535 {
6536 	struct static_key *key = (struct static_key *)table->data;
6537 	static int saved_val;
6538 	int val, ret;
6539 	struct ctl_table tmp = {
6540 		.data   = &val,
6541 		.maxlen = sizeof(val),
6542 		.mode   = table->mode,
6543 		.extra1 = SYSCTL_ZERO,
6544 		.extra2 = SYSCTL_ONE,
6545 	};
6546 
6547 	if (write && !capable(CAP_SYS_ADMIN))
6548 		return -EPERM;
6549 
6550 	mutex_lock(&bpf_stats_enabled_mutex);
6551 	val = saved_val;
6552 	ret = proc_dointvec_minmax(&tmp, write, buffer, lenp, ppos);
6553 	if (write && !ret && val != saved_val) {
6554 		if (val)
6555 			static_key_slow_inc(key);
6556 		else
6557 			static_key_slow_dec(key);
6558 		saved_val = val;
6559 	}
6560 	mutex_unlock(&bpf_stats_enabled_mutex);
6561 	return ret;
6562 }
6563 
6564 void __weak unpriv_ebpf_notify(int new_state)
6565 {
6566 }
6567 
6568 static int bpf_unpriv_handler(const struct ctl_table *table, int write,
6569 			      void *buffer, size_t *lenp, loff_t *ppos)
6570 {
6571 	int ret, unpriv_enable = *(int *)table->data;
6572 	bool locked_state = unpriv_enable == 1;
6573 	struct ctl_table tmp = *table;
6574 
6575 	if (write && !capable(CAP_SYS_ADMIN))
6576 		return -EPERM;
6577 
6578 	tmp.data = &unpriv_enable;
6579 	ret = proc_dointvec_minmax(&tmp, write, buffer, lenp, ppos);
6580 	if (write && !ret) {
6581 		if (locked_state && unpriv_enable != 1)
6582 			return -EPERM;
6583 		*(int *)table->data = unpriv_enable;
6584 	}
6585 
6586 	if (write)
6587 		unpriv_ebpf_notify(unpriv_enable);
6588 
6589 	return ret;
6590 }
6591 
6592 static const struct ctl_table bpf_syscall_table[] = {
6593 	{
6594 		.procname	= "unprivileged_bpf_disabled",
6595 		.data		= &sysctl_unprivileged_bpf_disabled,
6596 		.maxlen		= sizeof(sysctl_unprivileged_bpf_disabled),
6597 		.mode		= 0644,
6598 		.proc_handler	= bpf_unpriv_handler,
6599 		.extra1		= SYSCTL_ZERO,
6600 		.extra2		= SYSCTL_TWO,
6601 	},
6602 	{
6603 		.procname	= "bpf_stats_enabled",
6604 		.data		= &bpf_stats_enabled_key.key,
6605 		.mode		= 0644,
6606 		.proc_handler	= bpf_stats_handler,
6607 	},
6608 };
6609 
6610 static int __init bpf_syscall_sysctl_init(void)
6611 {
6612 	register_sysctl_init("kernel", bpf_syscall_table);
6613 	return 0;
6614 }
6615 late_initcall(bpf_syscall_sysctl_init);
6616 #endif /* CONFIG_SYSCTL */
6617