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