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