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