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