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