xref: /linux/kernel/bpf/syscall.c (revision 02d3452bdd80cf645694110128db2ed67da96490)
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 = type != BPF_PROG_TYPE_STRUCT_OPS &&
3029 		     is_tracing_multi(attr->expected_attach_type);
3030 
3031 	/* attach_prog_fd/attach_btf_obj_fd can specify fd of either bpf_prog
3032 	 * or btf, we need to check which one it is
3033 	 */
3034 	if (attr->attach_prog_fd) {
3035 		dst_prog = bpf_prog_get(attr->attach_prog_fd);
3036 		if (IS_ERR(dst_prog)) {
3037 			dst_prog = NULL;
3038 			attach_btf = btf_get_by_fd(attr->attach_btf_obj_fd);
3039 			if (IS_ERR(attach_btf)) {
3040 				err = -EINVAL;
3041 				goto put_token;
3042 			}
3043 			if (!btf_is_kernel(attach_btf)) {
3044 				/* attaching through specifying bpf_prog's BTF
3045 				 * objects directly might be supported eventually
3046 				 */
3047 				btf_put(attach_btf);
3048 				err = -ENOTSUPP;
3049 				goto put_token;
3050 			}
3051 		}
3052 	} else if (attr->attach_btf_id || multi_func) {
3053 		/* fall back to vmlinux BTF, if BTF type ID is specified */
3054 		attach_btf = bpf_get_btf_vmlinux();
3055 		if (IS_ERR(attach_btf)) {
3056 			err = PTR_ERR(attach_btf);
3057 			goto put_token;
3058 		}
3059 		if (!attach_btf) {
3060 			err = -EINVAL;
3061 			goto put_token;
3062 		}
3063 		btf_get(attach_btf);
3064 	}
3065 
3066 	if (bpf_prog_load_check_attach(type, attr->expected_attach_type,
3067 				       attach_btf, attr->attach_btf_id,
3068 				       dst_prog, multi_func)) {
3069 		if (dst_prog)
3070 			bpf_prog_put(dst_prog);
3071 		if (attach_btf)
3072 			btf_put(attach_btf);
3073 		err = -EINVAL;
3074 		goto put_token;
3075 	}
3076 
3077 	/* plain bpf_prog allocation */
3078 	prog = bpf_prog_alloc(bpf_prog_size(attr->insn_cnt), GFP_USER);
3079 	if (!prog) {
3080 		if (dst_prog)
3081 			bpf_prog_put(dst_prog);
3082 		if (attach_btf)
3083 			btf_put(attach_btf);
3084 		err = -EINVAL;
3085 		goto put_token;
3086 	}
3087 
3088 	prog->expected_attach_type = attr->expected_attach_type;
3089 	prog->sleepable = !!(attr->prog_flags & BPF_F_SLEEPABLE);
3090 	prog->aux->attach_btf = attach_btf;
3091 	prog->aux->attach_btf_id = multi_func ? bpf_multi_func_btf_id[0] : attr->attach_btf_id;
3092 	prog->aux->dst_prog = dst_prog;
3093 	if (dst_prog) {
3094 		prog->aux->saved_dst_ctx_type = resolve_prog_type(dst_prog);
3095 		prog->aux->saved_dst_prog_type = dst_prog->type;
3096 		prog->aux->saved_dst_attach_type = dst_prog->expected_attach_type;
3097 	}
3098 	prog->aux->dev_bound = !!attr->prog_ifindex;
3099 	prog->aux->xdp_has_frags = attr->prog_flags & BPF_F_XDP_HAS_FRAGS;
3100 
3101 	/* move token into prog->aux, reuse taken refcnt */
3102 	prog->aux->token = token;
3103 	token = NULL;
3104 
3105 	prog->aux->user = get_current_user();
3106 	prog->len = attr->insn_cnt;
3107 
3108 	err = bpf_prog_stream_init(prog, GFP_USER);
3109 	if (err)
3110 		goto free_prog;
3111 
3112 	err = -EFAULT;
3113 	if (copy_from_bpfptr(prog->insns,
3114 			     make_bpfptr(attr->insns, uattr.is_kernel),
3115 			     bpf_prog_insn_size(prog)) != 0)
3116 		goto free_prog;
3117 	/* copy eBPF program license from user space */
3118 	if (strncpy_from_bpfptr(license,
3119 				make_bpfptr(attr->license, uattr.is_kernel),
3120 				sizeof(license) - 1) < 0)
3121 		goto free_prog;
3122 	license[sizeof(license) - 1] = 0;
3123 
3124 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
3125 	prog->gpl_compatible = license_is_gpl_compatible(license) ? 1 : 0;
3126 	prog->aux->sig.keyring_type = BPF_SIG_KEYRING_NONE;
3127 	prog->aux->sig.verdict = BPF_SIG_UNSIGNED;
3128 	prog->orig_prog = NULL;
3129 	prog->jited = 0;
3130 
3131 	atomic64_set(&prog->aux->refcnt, 1);
3132 
3133 	if (bpf_prog_is_dev_bound(prog->aux)) {
3134 		err = bpf_prog_dev_bound_init(prog, attr);
3135 		if (err)
3136 			goto free_prog;
3137 	}
3138 
3139 	if (type == BPF_PROG_TYPE_EXT && dst_prog &&
3140 	    bpf_prog_is_dev_bound(dst_prog->aux)) {
3141 		err = bpf_prog_dev_bound_inherit(prog, dst_prog);
3142 		if (err)
3143 			goto free_prog;
3144 	}
3145 
3146 	/*
3147 	 * Bookkeeping for managing the program attachment chain.
3148 	 *
3149 	 * It might be tempting to set attach_tracing_prog flag at the attachment
3150 	 * time, but this will not prevent from loading bunch of tracing prog
3151 	 * first, then attach them one to another.
3152 	 *
3153 	 * The flag attach_tracing_prog is set for the whole program lifecycle, and
3154 	 * doesn't have to be cleared in bpf_tracing_link_release, since tracing
3155 	 * programs cannot change attachment target.
3156 	 */
3157 	if (type == BPF_PROG_TYPE_TRACING && dst_prog &&
3158 	    dst_prog->type == BPF_PROG_TYPE_TRACING) {
3159 		prog->aux->attach_tracing_prog = true;
3160 	}
3161 
3162 	/* find program type: socket_filter vs tracing_filter */
3163 	err = find_prog_type(type, prog);
3164 	if (err < 0)
3165 		goto free_prog;
3166 
3167 	prog->aux->load_time = ktime_get_boottime_ns();
3168 	err = bpf_obj_name_cpy(prog->aux->name, attr->prog_name,
3169 			       sizeof(attr->prog_name));
3170 	if (err < 0)
3171 		goto free_prog;
3172 
3173 	/* run eBPF verifier */
3174 	err = bpf_check(&prog, attr, uattr, attr_log);
3175 	if (err < 0)
3176 		goto free_used_maps;
3177 
3178 	err = bpf_prog_mark_insn_arrays_ready(prog);
3179 	if (err < 0)
3180 		goto free_used_maps;
3181 
3182 	/* bpf_throw() and faults look for the symbol. The prog can run once it has the id. */
3183 	bpf_prog_kallsyms_add(prog);
3184 
3185 	err = bpf_prog_alloc_id(prog);
3186 	if (err)
3187 		goto free_used_maps;
3188 
3189 	/* Upon success of bpf_prog_alloc_id(), the BPF prog is
3190 	 * effectively publicly exposed. However, retrieving via
3191 	 * bpf_prog_get_fd_by_id() will take another reference,
3192 	 * therefore it cannot be gone underneath us.
3193 	 *
3194 	 * Only for the time /after/ successful bpf_prog_new_fd()
3195 	 * and before returning to userspace, we might just hold
3196 	 * one reference and any parallel close on that fd could
3197 	 * rip everything out. Hence, below notifications must
3198 	 * happen before bpf_prog_new_fd().
3199 	 *
3200 	 * Also, any failure handling from this point onwards must
3201 	 * be using bpf_prog_put() given the program is exposed.
3202 	 */
3203 	perf_event_bpf_event(prog, PERF_BPF_EVENT_PROG_LOAD, 0);
3204 	bpf_audit_prog(prog, BPF_AUDIT_LOAD);
3205 
3206 	err = bpf_prog_new_fd(prog);
3207 	if (err < 0)
3208 		bpf_prog_put(prog);
3209 	return err;
3210 
3211 free_used_maps:
3212 	/* In case we have subprogs, we need to wait for a grace
3213 	 * period before we can tear down JIT memory since symbols
3214 	 * are already exposed under kallsyms.
3215 	 */
3216 	__bpf_prog_put_noref(prog, prog->aux->real_func_cnt);
3217 	return err;
3218 
3219 free_prog:
3220 	free_uid(prog->aux->user);
3221 	if (prog->aux->attach_btf)
3222 		btf_put(prog->aux->attach_btf);
3223 	bpf_prog_free(prog);
3224 put_token:
3225 	bpf_token_put(token);
3226 	return err;
3227 }
3228 
3229 #define BPF_OBJ_LAST_FIELD path_fd
3230 
3231 static int bpf_obj_pin(const union bpf_attr *attr)
3232 {
3233 	int path_fd;
3234 
3235 	if (CHECK_ATTR(BPF_OBJ) || attr->file_flags & ~BPF_F_PATH_FD)
3236 		return -EINVAL;
3237 
3238 	/* path_fd has to be accompanied by BPF_F_PATH_FD flag */
3239 	if (!(attr->file_flags & BPF_F_PATH_FD) && attr->path_fd)
3240 		return -EINVAL;
3241 
3242 	path_fd = attr->file_flags & BPF_F_PATH_FD ? attr->path_fd : AT_FDCWD;
3243 	return bpf_obj_pin_user(attr->bpf_fd, path_fd,
3244 				u64_to_user_ptr(attr->pathname));
3245 }
3246 
3247 static int bpf_obj_get(const union bpf_attr *attr)
3248 {
3249 	int path_fd;
3250 
3251 	if (CHECK_ATTR(BPF_OBJ) || attr->bpf_fd != 0 ||
3252 	    attr->file_flags & ~(BPF_OBJ_FLAG_MASK | BPF_F_PATH_FD))
3253 		return -EINVAL;
3254 
3255 	/* path_fd has to be accompanied by BPF_F_PATH_FD flag */
3256 	if (!(attr->file_flags & BPF_F_PATH_FD) && attr->path_fd)
3257 		return -EINVAL;
3258 
3259 	path_fd = attr->file_flags & BPF_F_PATH_FD ? attr->path_fd : AT_FDCWD;
3260 	return bpf_obj_get_user(path_fd, u64_to_user_ptr(attr->pathname),
3261 				attr->file_flags);
3262 }
3263 
3264 /* bpf_link_init_sleepable() allows to specify whether BPF link itself has
3265  * "sleepable" semantics, which normally would mean that BPF link's attach
3266  * hook can dereference link or link's underlying program for some time after
3267  * detachment due to RCU Tasks Trace-based lifetime protection scheme.
3268  * BPF program itself can be non-sleepable, yet, because it's transitively
3269  * reachable through BPF link, its freeing has to be delayed until after RCU
3270  * Tasks Trace GP.
3271  */
3272 void bpf_link_init_sleepable(struct bpf_link *link, enum bpf_link_type type,
3273 			     const struct bpf_link_ops *ops, struct bpf_prog *prog,
3274 			     enum bpf_attach_type attach_type, bool sleepable)
3275 {
3276 	WARN_ON(ops->dealloc && ops->dealloc_deferred);
3277 	atomic64_set(&link->refcnt, 1);
3278 	link->type = type;
3279 	link->sleepable = sleepable;
3280 	link->id = 0;
3281 	link->ops = ops;
3282 	link->prog = prog;
3283 	link->attach_type = attach_type;
3284 }
3285 
3286 void bpf_link_init(struct bpf_link *link, enum bpf_link_type type,
3287 		   const struct bpf_link_ops *ops, struct bpf_prog *prog,
3288 		   enum bpf_attach_type attach_type)
3289 {
3290 	bpf_link_init_sleepable(link, type, ops, prog, attach_type, false);
3291 }
3292 
3293 void bpf_tramp_link_init(struct bpf_tramp_link *link, enum bpf_link_type type,
3294 			 const struct bpf_link_ops *ops, struct bpf_prog *prog,
3295 			 enum bpf_attach_type attach_type, u64 cookie)
3296 {
3297 	bpf_link_init(&link->link, type, ops, prog, attach_type);
3298 	link->node.link = &link->link;
3299 	link->node.cookie = cookie;
3300 }
3301 
3302 static void bpf_link_free_id(int id)
3303 {
3304 	if (!id)
3305 		return;
3306 
3307 	spin_lock_bh(&link_idr_lock);
3308 	idr_remove(&link_idr, id);
3309 	spin_unlock_bh(&link_idr_lock);
3310 }
3311 
3312 /* Clean up bpf_link and corresponding anon_inode file and FD. After
3313  * anon_inode is created, bpf_link can't be just kfree()'d due to deferred
3314  * anon_inode's release() call. This helper marks bpf_link as
3315  * defunct, releases anon_inode file and puts reserved FD. bpf_prog's refcnt
3316  * is not decremented, it's the responsibility of a calling code that failed
3317  * to complete bpf_link initialization.
3318  * This helper eventually calls link's dealloc callback, but does not call
3319  * link's release callback.
3320  */
3321 void bpf_link_cleanup(struct bpf_link_primer *primer)
3322 {
3323 	primer->link->prog = NULL;
3324 	bpf_link_free_id(primer->id);
3325 	fput(primer->file);
3326 	put_unused_fd(primer->fd);
3327 }
3328 
3329 void bpf_link_inc(struct bpf_link *link)
3330 {
3331 	atomic64_inc(&link->refcnt);
3332 }
3333 
3334 static void bpf_link_dealloc(struct bpf_link *link)
3335 {
3336 	/* now that we know that bpf_link itself can't be reached, put underlying BPF program */
3337 	if (link->prog)
3338 		bpf_prog_put(link->prog);
3339 
3340 	/* free bpf_link and its containing memory */
3341 	if (link->ops->dealloc_deferred)
3342 		link->ops->dealloc_deferred(link);
3343 	else
3344 		link->ops->dealloc(link);
3345 }
3346 
3347 static void bpf_link_defer_dealloc_rcu_gp(struct rcu_head *rcu)
3348 {
3349 	struct bpf_link *link = container_of(rcu, struct bpf_link, rcu);
3350 
3351 	bpf_link_dealloc(link);
3352 }
3353 
3354 static bool bpf_link_is_tracepoint(struct bpf_link *link)
3355 {
3356 	/*
3357 	 * Only these combinations support a tracepoint bpf_link.
3358 	 * BPF_LINK_TYPE_TRACING raw_tp progs are hardcoded to use
3359 	 * bpf_raw_tp_link_lops and thus dealloc_deferred(), see
3360 	 * bpf_raw_tp_link_attach().
3361 	 */
3362 	return link->type == BPF_LINK_TYPE_RAW_TRACEPOINT ||
3363 	       (link->type == BPF_LINK_TYPE_TRACING && link->attach_type == BPF_TRACE_RAW_TP);
3364 }
3365 
3366 /* bpf_link_free is guaranteed to be called from process context */
3367 static void bpf_link_free(struct bpf_link *link)
3368 {
3369 	const struct bpf_link_ops *ops = link->ops;
3370 
3371 	bpf_link_free_id(link->id);
3372 	/* detach BPF program, clean up used resources */
3373 	if (link->prog)
3374 		ops->release(link);
3375 	if (ops->dealloc_deferred) {
3376 		/*
3377 		 * Schedule BPF link deallocation, which will only then
3378 		 * trigger putting BPF program refcount.
3379 		 * If underlying BPF program is sleepable or BPF link's target
3380 		 * attach hookpoint is sleepable or otherwise requires RCU GPs
3381 		 * to ensure link and its underlying BPF program is not
3382 		 * reachable anymore, we need to first wait for RCU tasks
3383 		 * trace sync, and then go through "classic" RCU grace period.
3384 		 *
3385 		 * For tracepoint BPF links, we need to go through SRCU grace
3386 		 * period wait instead when non-faultable tracepoint is used. We
3387 		 * don't need to chain SRCU grace period waits, however, for the
3388 		 * faultable case, since it exclusively uses RCU Tasks Trace.
3389 		 */
3390 		if (link->sleepable || (link->prog && link->prog->sleepable))
3391 			/* RCU Tasks Trace grace period implies RCU grace period. */
3392 			call_rcu_tasks_trace(&link->rcu, bpf_link_defer_dealloc_rcu_gp);
3393 		/* We need to do a SRCU grace period wait for non-faultable tracepoint BPF links. */
3394 		else if (bpf_link_is_tracepoint(link))
3395 			call_tracepoint_unregister_atomic(&link->rcu, bpf_link_defer_dealloc_rcu_gp);
3396 		else
3397 			call_rcu(&link->rcu, bpf_link_defer_dealloc_rcu_gp);
3398 	} else if (ops->dealloc) {
3399 		bpf_link_dealloc(link);
3400 	}
3401 }
3402 
3403 static void bpf_link_put_deferred(struct work_struct *work)
3404 {
3405 	struct bpf_link *link = container_of(work, struct bpf_link, work);
3406 
3407 	bpf_link_free(link);
3408 }
3409 
3410 /* bpf_link_put might be called from atomic context. It needs to be called
3411  * from sleepable context in order to acquire sleeping locks during the process.
3412  */
3413 void bpf_link_put(struct bpf_link *link)
3414 {
3415 	if (!atomic64_dec_and_test(&link->refcnt))
3416 		return;
3417 
3418 	INIT_WORK(&link->work, bpf_link_put_deferred);
3419 	schedule_work(&link->work);
3420 }
3421 EXPORT_SYMBOL(bpf_link_put);
3422 
3423 static void bpf_link_put_direct(struct bpf_link *link)
3424 {
3425 	if (!atomic64_dec_and_test(&link->refcnt))
3426 		return;
3427 	bpf_link_free(link);
3428 }
3429 
3430 static int bpf_link_release(struct inode *inode, struct file *filp)
3431 {
3432 	struct bpf_link *link = filp->private_data;
3433 
3434 	bpf_link_put_direct(link);
3435 	return 0;
3436 }
3437 
3438 #ifdef CONFIG_PROC_FS
3439 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type)
3440 #define BPF_MAP_TYPE(_id, _ops)
3441 #define BPF_LINK_TYPE(_id, _name) [_id] = #_name,
3442 static const char *bpf_link_type_strs[] = {
3443 	[BPF_LINK_TYPE_UNSPEC] = "<invalid>",
3444 #include <linux/bpf_types.h>
3445 };
3446 #undef BPF_PROG_TYPE
3447 #undef BPF_MAP_TYPE
3448 #undef BPF_LINK_TYPE
3449 
3450 static void bpf_link_show_fdinfo(struct seq_file *m, struct file *filp)
3451 {
3452 	const struct bpf_link *link = filp->private_data;
3453 	const struct bpf_prog *prog;
3454 	enum bpf_link_type type = link->type;
3455 	char prog_tag[sizeof(prog->tag) * 2 + 1] = { };
3456 	u32 prog_id = 0;
3457 
3458 	if (type < ARRAY_SIZE(bpf_link_type_strs) && bpf_link_type_strs[type]) {
3459 		if (link->type == BPF_LINK_TYPE_KPROBE_MULTI)
3460 			seq_printf(m, "link_type:\t%s\n", link->flags == BPF_F_KPROBE_MULTI_RETURN ?
3461 				   "kretprobe_multi" : "kprobe_multi");
3462 		else if (link->type == BPF_LINK_TYPE_UPROBE_MULTI)
3463 			seq_printf(m, "link_type:\t%s\n", link->flags & BPF_F_UPROBE_MULTI_RETURN ?
3464 				   "uretprobe_multi" : "uprobe_multi");
3465 		else
3466 			seq_printf(m, "link_type:\t%s\n", bpf_link_type_strs[type]);
3467 	} else {
3468 		WARN_ONCE(1, "missing BPF_LINK_TYPE(...) for link type %u\n", type);
3469 		seq_printf(m, "link_type:\t<%u>\n", type);
3470 	}
3471 	seq_printf(m, "link_id:\t%u\n", link->id);
3472 
3473 	rcu_read_lock();
3474 	prog = READ_ONCE(link->prog);
3475 	if (prog) {
3476 		bin2hex(prog_tag, prog->tag, sizeof(prog->tag));
3477 		prog_id = prog->aux->id;
3478 	}
3479 	rcu_read_unlock();
3480 
3481 	if (prog) {
3482 		seq_printf(m,
3483 			   "prog_tag:\t%s\n"
3484 			   "prog_id:\t%u\n",
3485 			   prog_tag,
3486 			   prog_id);
3487 	}
3488 	if (link->ops->show_fdinfo)
3489 		link->ops->show_fdinfo(link, m);
3490 }
3491 #endif
3492 
3493 static __poll_t bpf_link_poll(struct file *file, struct poll_table_struct *pts)
3494 {
3495 	struct bpf_link *link = file->private_data;
3496 
3497 	return link->ops->poll(file, pts);
3498 }
3499 
3500 static const struct file_operations bpf_link_fops = {
3501 #ifdef CONFIG_PROC_FS
3502 	.show_fdinfo	= bpf_link_show_fdinfo,
3503 #endif
3504 	.release	= bpf_link_release,
3505 	.read		= bpf_dummy_read,
3506 	.write		= bpf_dummy_write,
3507 };
3508 
3509 static const struct file_operations bpf_link_fops_poll = {
3510 #ifdef CONFIG_PROC_FS
3511 	.show_fdinfo	= bpf_link_show_fdinfo,
3512 #endif
3513 	.release	= bpf_link_release,
3514 	.read		= bpf_dummy_read,
3515 	.write		= bpf_dummy_write,
3516 	.poll		= bpf_link_poll,
3517 };
3518 
3519 static int bpf_link_alloc_id(struct bpf_link *link)
3520 {
3521 	int id;
3522 
3523 	idr_preload(GFP_KERNEL);
3524 	spin_lock_bh(&link_idr_lock);
3525 	id = idr_alloc_cyclic(&link_idr, link, 1, INT_MAX, GFP_ATOMIC);
3526 	spin_unlock_bh(&link_idr_lock);
3527 	idr_preload_end();
3528 
3529 	return id;
3530 }
3531 
3532 /* Prepare bpf_link to be exposed to user-space by allocating anon_inode file,
3533  * reserving unused FD and allocating ID from link_idr. This is to be paired
3534  * with bpf_link_settle() to install FD and ID and expose bpf_link to
3535  * user-space, if bpf_link is successfully attached. If not, bpf_link and
3536  * pre-allocated resources are to be freed with bpf_cleanup() call. All the
3537  * transient state is passed around in struct bpf_link_primer.
3538  * This is preferred way to create and initialize bpf_link, especially when
3539  * there are complicated and expensive operations in between creating bpf_link
3540  * itself and attaching it to BPF hook. By using bpf_link_prime() and
3541  * bpf_link_settle() kernel code using bpf_link doesn't have to perform
3542  * expensive (and potentially failing) roll back operations in a rare case
3543  * that file, FD, or ID can't be allocated.
3544  */
3545 int bpf_link_prime(struct bpf_link *link, struct bpf_link_primer *primer)
3546 {
3547 	struct file *file;
3548 	int fd, id;
3549 
3550 	fd = get_unused_fd_flags(O_CLOEXEC);
3551 	if (fd < 0)
3552 		return fd;
3553 
3554 	id = bpf_link_alloc_id(link);
3555 	if (id < 0) {
3556 		put_unused_fd(fd);
3557 		return id;
3558 	}
3559 
3560 	file = anon_inode_getfile("bpf_link",
3561 				  link->ops->poll ? &bpf_link_fops_poll : &bpf_link_fops,
3562 				  link, O_CLOEXEC);
3563 	if (IS_ERR(file)) {
3564 		bpf_link_free_id(id);
3565 		put_unused_fd(fd);
3566 		return PTR_ERR(file);
3567 	}
3568 
3569 	primer->link = link;
3570 	primer->file = file;
3571 	primer->fd = fd;
3572 	primer->id = id;
3573 	return 0;
3574 }
3575 
3576 int bpf_link_settle(struct bpf_link_primer *primer)
3577 {
3578 	/* make bpf_link fetchable by ID */
3579 	spin_lock_bh(&link_idr_lock);
3580 	primer->link->id = primer->id;
3581 	spin_unlock_bh(&link_idr_lock);
3582 	/* make bpf_link fetchable by FD */
3583 	fd_install(primer->fd, primer->file);
3584 	/* pass through installed FD */
3585 	return primer->fd;
3586 }
3587 
3588 int bpf_link_new_fd(struct bpf_link *link)
3589 {
3590 	return anon_inode_getfd("bpf-link",
3591 				link->ops->poll ? &bpf_link_fops_poll : &bpf_link_fops,
3592 				link, O_CLOEXEC);
3593 }
3594 
3595 struct bpf_link *bpf_link_get_from_fd(u32 ufd)
3596 {
3597 	CLASS(fd, f)(ufd);
3598 	struct bpf_link *link;
3599 
3600 	if (fd_empty(f))
3601 		return ERR_PTR(-EBADF);
3602 	if (fd_file(f)->f_op != &bpf_link_fops && fd_file(f)->f_op != &bpf_link_fops_poll)
3603 		return ERR_PTR(-EINVAL);
3604 
3605 	link = fd_file(f)->private_data;
3606 	bpf_link_inc(link);
3607 	return link;
3608 }
3609 EXPORT_SYMBOL_NS(bpf_link_get_from_fd, "BPF_INTERNAL");
3610 
3611 static void bpf_tracing_link_release(struct bpf_link *link)
3612 {
3613 	struct bpf_tracing_link *tr_link =
3614 		container_of(link, struct bpf_tracing_link, link.link);
3615 	int err;
3616 
3617 	err = bpf_trampoline_unlink_prog(&tr_link->link.node,
3618 					tr_link->trampoline,
3619 					tr_link->tgt_prog);
3620 	WARN_ONCE(err, "bpf_trampoline_unlink_prog failed: %d\n", err);
3621 
3622 	bpf_trampoline_put(tr_link->trampoline);
3623 
3624 	/* tgt_prog is NULL if target is a kernel function */
3625 	if (tr_link->tgt_prog)
3626 		bpf_prog_put(tr_link->tgt_prog);
3627 }
3628 
3629 static void bpf_tracing_link_dealloc(struct bpf_link *link)
3630 {
3631 	struct bpf_tracing_link *tr_link = container_of(link, struct bpf_tracing_link, link.link);
3632 
3633 	kfree(tr_link);
3634 }
3635 
3636 static void bpf_tracing_link_show_fdinfo(const struct bpf_link *link,
3637 					 struct seq_file *seq)
3638 {
3639 	struct bpf_tracing_link *tr_link = container_of(link, struct bpf_tracing_link, link.link);
3640 
3641 	u32 target_btf_id, target_obj_id;
3642 
3643 	bpf_trampoline_unpack_key(tr_link->trampoline->key,
3644 				  &target_obj_id, &target_btf_id);
3645 	seq_printf(seq,
3646 		   "attach_type:\t%d\n"
3647 		   "target_obj_id:\t%u\n"
3648 		   "target_btf_id:\t%u\n"
3649 		   "cookie:\t%llu\n",
3650 		   link->attach_type,
3651 		   target_obj_id,
3652 		   target_btf_id,
3653 		   tr_link->link.node.cookie);
3654 }
3655 
3656 static int bpf_tracing_link_fill_link_info(const struct bpf_link *link,
3657 					   struct bpf_link_info *info)
3658 {
3659 	struct bpf_tracing_link *tr_link = container_of(link, struct bpf_tracing_link, link.link);
3660 
3661 	info->tracing.attach_type = link->attach_type;
3662 	info->tracing.cookie = tr_link->link.node.cookie;
3663 	bpf_trampoline_unpack_key(tr_link->trampoline->key,
3664 				  &info->tracing.target_obj_id,
3665 				  &info->tracing.target_btf_id);
3666 
3667 	return 0;
3668 }
3669 
3670 static const struct bpf_link_ops bpf_tracing_link_lops = {
3671 	.release = bpf_tracing_link_release,
3672 	.dealloc = bpf_tracing_link_dealloc,
3673 	.show_fdinfo = bpf_tracing_link_show_fdinfo,
3674 	.fill_link_info = bpf_tracing_link_fill_link_info,
3675 };
3676 
3677 static int bpf_tracing_prog_attach(struct bpf_prog *prog,
3678 				   int tgt_prog_fd,
3679 				   u32 btf_id,
3680 				   u64 bpf_cookie,
3681 				   enum bpf_attach_type attach_type)
3682 {
3683 	struct bpf_link_primer link_primer;
3684 	struct bpf_prog *tgt_prog = NULL;
3685 	struct bpf_trampoline *tr = NULL;
3686 	struct bpf_tracing_link *link;
3687 	u64 key = 0;
3688 	int err;
3689 
3690 	switch (prog->type) {
3691 	case BPF_PROG_TYPE_TRACING:
3692 		if (prog->expected_attach_type != BPF_TRACE_FENTRY &&
3693 		    prog->expected_attach_type != BPF_TRACE_FEXIT &&
3694 		    prog->expected_attach_type != BPF_TRACE_FSESSION &&
3695 		    prog->expected_attach_type != BPF_MODIFY_RETURN) {
3696 			err = -EINVAL;
3697 			goto out_put_prog;
3698 		}
3699 		break;
3700 	case BPF_PROG_TYPE_EXT:
3701 		if (prog->expected_attach_type != 0) {
3702 			err = -EINVAL;
3703 			goto out_put_prog;
3704 		}
3705 		break;
3706 	case BPF_PROG_TYPE_LSM:
3707 		if (prog->expected_attach_type != BPF_LSM_MAC) {
3708 			err = -EINVAL;
3709 			goto out_put_prog;
3710 		}
3711 		break;
3712 	default:
3713 		err = -EINVAL;
3714 		goto out_put_prog;
3715 	}
3716 
3717 	if (!!tgt_prog_fd != !!btf_id) {
3718 		err = -EINVAL;
3719 		goto out_put_prog;
3720 	}
3721 
3722 	if (tgt_prog_fd) {
3723 		/*
3724 		 * For now we only allow new targets for BPF_PROG_TYPE_EXT. If this
3725 		 * part would be changed to implement the same for
3726 		 * BPF_PROG_TYPE_TRACING, do not forget to update the way how
3727 		 * attach_tracing_prog flag is set.
3728 		 */
3729 		if (prog->type != BPF_PROG_TYPE_EXT) {
3730 			err = -EINVAL;
3731 			goto out_put_prog;
3732 		}
3733 
3734 		tgt_prog = bpf_prog_get(tgt_prog_fd);
3735 		if (IS_ERR(tgt_prog)) {
3736 			err = PTR_ERR(tgt_prog);
3737 			tgt_prog = NULL;
3738 			goto out_put_prog;
3739 		}
3740 
3741 		key = bpf_trampoline_compute_key(tgt_prog, NULL, btf_id);
3742 	}
3743 
3744 	link = kzalloc_obj(*link, GFP_USER);
3745 	if (!link) {
3746 		err = -ENOMEM;
3747 		goto out_put_prog;
3748 	}
3749 	bpf_tramp_link_init(&link->link, BPF_LINK_TYPE_TRACING,
3750 			    &bpf_tracing_link_lops, prog, attach_type, bpf_cookie);
3751 
3752 	if (prog->expected_attach_type == BPF_TRACE_FSESSION) {
3753 		link->fexit.link = &link->link.link;
3754 		link->fexit.cookie = bpf_cookie;
3755 	}
3756 
3757 	mutex_lock(&prog->aux->dst_mutex);
3758 
3759 	/* There are a few possible cases here:
3760 	 *
3761 	 * - if prog->aux->dst_trampoline is set, the program was just loaded
3762 	 *   and not yet attached to anything, so we can use the values stored
3763 	 *   in prog->aux
3764 	 *
3765 	 * - if prog->aux->dst_trampoline is NULL, the program has already been
3766 	 *   attached to a target and its initial target was cleared (below)
3767 	 *
3768 	 * - if tgt_prog != NULL, the caller specified tgt_prog_fd +
3769 	 *   target_btf_id using the link_create API.
3770 	 *
3771 	 * - if tgt_prog == NULL when this function was called using the old
3772 	 *   raw_tracepoint_open API, and we need a target from prog->aux
3773 	 *
3774 	 * - if prog->aux->dst_trampoline and tgt_prog is NULL, the program
3775 	 *   was detached and is going for re-attachment.
3776 	 *
3777 	 * - if prog->aux->dst_trampoline is NULL and tgt_prog and prog->aux->attach_btf
3778 	 *   are NULL, then program was already attached and user did not provide
3779 	 *   tgt_prog_fd so we have no way to find out or create trampoline
3780 	 */
3781 	if (!prog->aux->dst_trampoline && !tgt_prog) {
3782 		/*
3783 		 * Allow re-attach for TRACING and LSM programs. If it's
3784 		 * currently linked, bpf_trampoline_link_prog will fail.
3785 		 * EXT programs need to specify tgt_prog_fd, so they
3786 		 * re-attach in separate code path.
3787 		 */
3788 		if (prog->type != BPF_PROG_TYPE_TRACING &&
3789 		    prog->type != BPF_PROG_TYPE_LSM) {
3790 			err = -EINVAL;
3791 			goto out_unlock;
3792 		}
3793 		/* We can allow re-attach only if we have valid attach_btf. */
3794 		if (!prog->aux->attach_btf) {
3795 			err = -EINVAL;
3796 			goto out_unlock;
3797 		}
3798 		btf_id = prog->aux->attach_btf_id;
3799 		key = bpf_trampoline_compute_key(NULL, prog->aux->attach_btf, btf_id);
3800 	}
3801 
3802 	if (!prog->aux->dst_trampoline ||
3803 	    (key && key != prog->aux->dst_trampoline->key)) {
3804 		/* If there is no saved target, or the specified target is
3805 		 * different from the destination specified at load time, we
3806 		 * need a new trampoline and a check for compatibility
3807 		 */
3808 		struct bpf_attach_target_info tgt_info = {};
3809 
3810 		err = bpf_check_attach_target(NULL, prog, tgt_prog, btf_id,
3811 					      &tgt_info);
3812 		if (err)
3813 			goto out_unlock;
3814 
3815 		if (tgt_info.tgt_mod) {
3816 			module_put(prog->aux->mod);
3817 			prog->aux->mod = tgt_info.tgt_mod;
3818 		}
3819 
3820 		tr = bpf_trampoline_get(key, &tgt_info);
3821 		if (!tr) {
3822 			err = -ENOMEM;
3823 			goto out_unlock;
3824 		}
3825 	} else {
3826 		/* The caller didn't specify a target, or the target was the
3827 		 * same as the destination supplied during program load. This
3828 		 * means we can reuse the trampoline and reference from program
3829 		 * load time, and there is no need to allocate a new one. This
3830 		 * can only happen once for any program, as the saved values in
3831 		 * prog->aux are cleared below.
3832 		 */
3833 		tr = prog->aux->dst_trampoline;
3834 		tgt_prog = prog->aux->dst_prog;
3835 	}
3836 	/*
3837 	 * It is to prevent modifying struct pt_regs via kprobe_write_ctx=true
3838 	 * freplace prog. Without this check, kprobe_write_ctx=true freplace
3839 	 * prog is allowed to attach to kprobe_write_ctx=false kprobe prog, and
3840 	 * then modify the registers of the kprobe prog's target kernel
3841 	 * function.
3842 	 *
3843 	 * This also blocks the combination of uprobe+freplace, because it is
3844 	 * unable to recognize the use of the tgt_prog as an uprobe or a kprobe
3845 	 * by tgt_prog itself. At attach time, uprobe/kprobe is recognized by
3846 	 * the target perf event flags in __perf_event_set_bpf_prog().
3847 	 */
3848 	if (prog->type == BPF_PROG_TYPE_EXT &&
3849 	    prog->aux->kprobe_write_ctx != tgt_prog->aux->kprobe_write_ctx) {
3850 		err = -EINVAL;
3851 		goto out_unlock;
3852 	}
3853 	/* Where the return can be overridden is checked for the target only */
3854 	if (prog->type == BPF_PROG_TYPE_EXT &&
3855 	    prog->kprobe_override && !tgt_prog->kprobe_override) {
3856 		err = -EINVAL;
3857 		goto out_unlock;
3858 	}
3859 	/* bpf_prog_run_save_cb() and bpf_prog_run_clear_cb() look at the target only */
3860 	if (prog->type == BPF_PROG_TYPE_EXT &&
3861 	    (tgt_prog->type == BPF_PROG_TYPE_SOCKET_FILTER ||
3862 	     tgt_prog->type == BPF_PROG_TYPE_CGROUP_SKB ||
3863 	     tgt_prog->type == BPF_PROG_TYPE_LWT_IN ||
3864 	     tgt_prog->type == BPF_PROG_TYPE_LWT_OUT ||
3865 	     tgt_prog->type == BPF_PROG_TYPE_LWT_XMIT ||
3866 	     tgt_prog->type == BPF_PROG_TYPE_LWT_SEG6LOCAL) &&
3867 	    prog->cb_access && !tgt_prog->cb_access) {
3868 		err = -EINVAL;
3869 		goto out_unlock;
3870 	}
3871 	/*
3872 	 * The size of these contexts depends on what the program is attached
3873 	 * to, or run with. That is compared with max_ctx_offset of the program,
3874 	 * and nobody looks at the one of its extensions.
3875 	 */
3876 	if (prog->type == BPF_PROG_TYPE_EXT &&
3877 	    (tgt_prog->type == BPF_PROG_TYPE_RAW_TRACEPOINT ||
3878 	     tgt_prog->type == BPF_PROG_TYPE_TRACEPOINT ||
3879 	     tgt_prog->type == BPF_PROG_TYPE_SYSCALL) &&
3880 	    prog->aux->max_ctx_offset > tgt_prog->aux->max_ctx_offset) {
3881 		err = -EINVAL;
3882 		goto out_unlock;
3883 	}
3884 
3885 	err = bpf_link_prime(&link->link.link, &link_primer);
3886 	if (err)
3887 		goto out_unlock;
3888 
3889 	err = bpf_trampoline_link_prog(&link->link.node, tr, tgt_prog);
3890 	if (err) {
3891 		bpf_link_cleanup(&link_primer);
3892 		link = NULL;
3893 		goto out_unlock;
3894 	}
3895 
3896 	link->tgt_prog = tgt_prog;
3897 	link->trampoline = tr;
3898 
3899 	/* Always clear the trampoline and target prog from prog->aux to make
3900 	 * sure the original attach destination is not kept alive after a
3901 	 * program is (re-)attached to another target.
3902 	 */
3903 	if (prog->aux->dst_prog &&
3904 	    (tgt_prog_fd || tr != prog->aux->dst_trampoline))
3905 		/* got extra prog ref from syscall, or attaching to different prog */
3906 		bpf_prog_put(prog->aux->dst_prog);
3907 	if (prog->aux->dst_trampoline && tr != prog->aux->dst_trampoline)
3908 		/* we allocated a new trampoline, so free the old one */
3909 		bpf_trampoline_put(prog->aux->dst_trampoline);
3910 
3911 	prog->aux->dst_prog = NULL;
3912 	prog->aux->dst_trampoline = NULL;
3913 	mutex_unlock(&prog->aux->dst_mutex);
3914 
3915 	return bpf_link_settle(&link_primer);
3916 out_unlock:
3917 	if (tr && tr != prog->aux->dst_trampoline)
3918 		bpf_trampoline_put(tr);
3919 	mutex_unlock(&prog->aux->dst_mutex);
3920 	kfree(link);
3921 out_put_prog:
3922 	if (tgt_prog_fd && tgt_prog)
3923 		bpf_prog_put(tgt_prog);
3924 	return err;
3925 }
3926 
3927 static void bpf_raw_tp_link_release(struct bpf_link *link)
3928 {
3929 	struct bpf_raw_tp_link *raw_tp =
3930 		container_of(link, struct bpf_raw_tp_link, link);
3931 
3932 	bpf_probe_unregister(raw_tp->btp, raw_tp);
3933 	bpf_put_raw_tracepoint(raw_tp->btp);
3934 }
3935 
3936 static void bpf_raw_tp_link_dealloc(struct bpf_link *link)
3937 {
3938 	struct bpf_raw_tp_link *raw_tp =
3939 		container_of(link, struct bpf_raw_tp_link, link);
3940 
3941 	kfree(raw_tp);
3942 }
3943 
3944 static void bpf_raw_tp_link_show_fdinfo(const struct bpf_link *link,
3945 					struct seq_file *seq)
3946 {
3947 	struct bpf_raw_tp_link *raw_tp_link =
3948 		container_of(link, struct bpf_raw_tp_link, link);
3949 
3950 	seq_printf(seq,
3951 		   "tp_name:\t%s\n"
3952 		   "cookie:\t%llu\n",
3953 		   raw_tp_link->btp->tp->name,
3954 		   raw_tp_link->cookie);
3955 }
3956 
3957 static int bpf_copy_to_user(char __user *ubuf, const char *buf, u32 ulen,
3958 			    u32 len)
3959 {
3960 	if (ulen >= len + 1) {
3961 		if (copy_to_user(ubuf, buf, len + 1))
3962 			return -EFAULT;
3963 	} else {
3964 		char zero = '\0';
3965 
3966 		if (copy_to_user(ubuf, buf, ulen - 1))
3967 			return -EFAULT;
3968 		if (put_user(zero, ubuf + ulen - 1))
3969 			return -EFAULT;
3970 		return -ENOSPC;
3971 	}
3972 
3973 	return 0;
3974 }
3975 
3976 static int bpf_raw_tp_link_fill_link_info(const struct bpf_link *link,
3977 					  struct bpf_link_info *info)
3978 {
3979 	struct bpf_raw_tp_link *raw_tp_link =
3980 		container_of(link, struct bpf_raw_tp_link, link);
3981 	char __user *ubuf = u64_to_user_ptr(info->raw_tracepoint.tp_name);
3982 	const char *tp_name = raw_tp_link->btp->tp->name;
3983 	u32 ulen = info->raw_tracepoint.tp_name_len;
3984 	size_t tp_len = strlen(tp_name);
3985 
3986 	if (!ulen ^ !ubuf)
3987 		return -EINVAL;
3988 
3989 	info->raw_tracepoint.tp_name_len = tp_len + 1;
3990 	info->raw_tracepoint.cookie = raw_tp_link->cookie;
3991 
3992 	if (!ubuf)
3993 		return 0;
3994 
3995 	return bpf_copy_to_user(ubuf, tp_name, ulen, tp_len);
3996 }
3997 
3998 static const struct bpf_link_ops bpf_raw_tp_link_lops = {
3999 	.release = bpf_raw_tp_link_release,
4000 	.dealloc_deferred = bpf_raw_tp_link_dealloc,
4001 	.show_fdinfo = bpf_raw_tp_link_show_fdinfo,
4002 	.fill_link_info = bpf_raw_tp_link_fill_link_info,
4003 };
4004 
4005 #ifdef CONFIG_PERF_EVENTS
4006 struct bpf_perf_link {
4007 	struct bpf_link link;
4008 	struct file *perf_file;
4009 };
4010 
4011 static void bpf_perf_link_release(struct bpf_link *link)
4012 {
4013 	struct bpf_perf_link *perf_link = container_of(link, struct bpf_perf_link, link);
4014 	struct perf_event *event = perf_link->perf_file->private_data;
4015 
4016 	perf_event_free_bpf_prog(event);
4017 	fput(perf_link->perf_file);
4018 }
4019 
4020 static void bpf_perf_link_dealloc(struct bpf_link *link)
4021 {
4022 	struct bpf_perf_link *perf_link = container_of(link, struct bpf_perf_link, link);
4023 
4024 	kfree(perf_link);
4025 }
4026 
4027 static int bpf_perf_link_fill_common(const struct perf_event *event,
4028 				     char __user *uname, u32 *ulenp,
4029 				     u64 *probe_offset, u64 *probe_addr,
4030 				     u32 *fd_type, unsigned long *missed)
4031 {
4032 	const char *buf;
4033 	u32 prog_id, ulen;
4034 	size_t len;
4035 	int err;
4036 
4037 	ulen = *ulenp;
4038 	if (!ulen ^ !uname)
4039 		return -EINVAL;
4040 
4041 	err = bpf_get_perf_event_info(event, &prog_id, fd_type, &buf,
4042 				      probe_offset, probe_addr, missed);
4043 	if (err)
4044 		return err;
4045 
4046 	if (buf) {
4047 		len = strlen(buf);
4048 		*ulenp = len + 1;
4049 	} else {
4050 		*ulenp = 1;
4051 	}
4052 	if (!uname)
4053 		goto out;
4054 
4055 	if (buf) {
4056 		err = bpf_copy_to_user(uname, buf, ulen, len);
4057 	} else {
4058 		char zero = '\0';
4059 
4060 		if (put_user(zero, uname))
4061 			err = -EFAULT;
4062 	}
4063 out:
4064 	kfree_const(buf);
4065 	return err;
4066 }
4067 
4068 #ifdef CONFIG_KPROBE_EVENTS
4069 static int bpf_perf_link_fill_kprobe(const struct perf_event *event,
4070 				     struct bpf_link_info *info)
4071 {
4072 	unsigned long missed;
4073 	char __user *uname;
4074 	u64 addr, offset;
4075 	u32 ulen, type;
4076 	int err;
4077 
4078 	uname = u64_to_user_ptr(info->perf_event.kprobe.func_name);
4079 	ulen = info->perf_event.kprobe.name_len;
4080 	err = bpf_perf_link_fill_common(event, uname, &ulen, &offset, &addr,
4081 					&type, &missed);
4082 	if (err)
4083 		return err;
4084 	if (type == BPF_FD_TYPE_KRETPROBE)
4085 		info->perf_event.type = BPF_PERF_EVENT_KRETPROBE;
4086 	else
4087 		info->perf_event.type = BPF_PERF_EVENT_KPROBE;
4088 	info->perf_event.kprobe.name_len = ulen;
4089 	info->perf_event.kprobe.offset = offset;
4090 	info->perf_event.kprobe.missed = missed;
4091 	if (!kallsyms_show_value(current_cred()))
4092 		addr = 0;
4093 	info->perf_event.kprobe.addr = addr;
4094 	info->perf_event.kprobe.cookie = event->bpf_cookie;
4095 	return 0;
4096 }
4097 
4098 static void bpf_perf_link_fdinfo_kprobe(const struct perf_event *event,
4099 					struct seq_file *seq)
4100 {
4101 	const char *name;
4102 	int err;
4103 	u32 prog_id, type;
4104 	u64 offset, addr;
4105 	unsigned long missed;
4106 
4107 	err = bpf_get_perf_event_info(event, &prog_id, &type, &name,
4108 				      &offset, &addr, &missed);
4109 	if (err)
4110 		return;
4111 
4112 	seq_printf(seq,
4113 		   "name:\t%s\n"
4114 		   "offset:\t%#llx\n"
4115 		   "missed:\t%lu\n"
4116 		   "addr:\t%#llx\n"
4117 		   "event_type:\t%s\n"
4118 		   "cookie:\t%llu\n",
4119 		   name, offset, missed, addr,
4120 		   type == BPF_FD_TYPE_KRETPROBE ?  "kretprobe" : "kprobe",
4121 		   event->bpf_cookie);
4122 	kfree_const(name);
4123 }
4124 #endif
4125 
4126 #ifdef CONFIG_UPROBE_EVENTS
4127 static int bpf_perf_link_fill_uprobe(const struct perf_event *event,
4128 				     struct bpf_link_info *info)
4129 {
4130 	u64 ref_ctr_offset, offset;
4131 	char __user *uname;
4132 	u32 ulen, type;
4133 	int err;
4134 
4135 	uname = u64_to_user_ptr(info->perf_event.uprobe.file_name);
4136 	ulen = info->perf_event.uprobe.name_len;
4137 	err = bpf_perf_link_fill_common(event, uname, &ulen, &offset, &ref_ctr_offset,
4138 					&type, NULL);
4139 	if (err)
4140 		return err;
4141 
4142 	if (type == BPF_FD_TYPE_URETPROBE)
4143 		info->perf_event.type = BPF_PERF_EVENT_URETPROBE;
4144 	else
4145 		info->perf_event.type = BPF_PERF_EVENT_UPROBE;
4146 	info->perf_event.uprobe.name_len = ulen;
4147 	info->perf_event.uprobe.offset = offset;
4148 	info->perf_event.uprobe.cookie = event->bpf_cookie;
4149 	info->perf_event.uprobe.ref_ctr_offset = ref_ctr_offset;
4150 	return 0;
4151 }
4152 
4153 static void bpf_perf_link_fdinfo_uprobe(const struct perf_event *event,
4154 					struct seq_file *seq)
4155 {
4156 	const char *name;
4157 	int err;
4158 	u32 prog_id, type;
4159 	u64 offset, ref_ctr_offset;
4160 	unsigned long missed;
4161 
4162 	err = bpf_get_perf_event_info(event, &prog_id, &type, &name,
4163 				      &offset, &ref_ctr_offset, &missed);
4164 	if (err)
4165 		return;
4166 
4167 	seq_printf(seq,
4168 		   "name:\t%s\n"
4169 		   "offset:\t%#llx\n"
4170 		   "ref_ctr_offset:\t%#llx\n"
4171 		   "event_type:\t%s\n"
4172 		   "cookie:\t%llu\n",
4173 		   name, offset, ref_ctr_offset,
4174 		   type == BPF_FD_TYPE_URETPROBE ?  "uretprobe" : "uprobe",
4175 		   event->bpf_cookie);
4176 	kfree_const(name);
4177 }
4178 #endif
4179 
4180 static int bpf_perf_link_fill_probe(const struct perf_event *event,
4181 				    struct bpf_link_info *info)
4182 {
4183 #ifdef CONFIG_KPROBE_EVENTS
4184 	if (event->tp_event->flags & TRACE_EVENT_FL_KPROBE)
4185 		return bpf_perf_link_fill_kprobe(event, info);
4186 #endif
4187 #ifdef CONFIG_UPROBE_EVENTS
4188 	if (event->tp_event->flags & TRACE_EVENT_FL_UPROBE)
4189 		return bpf_perf_link_fill_uprobe(event, info);
4190 #endif
4191 	return -EOPNOTSUPP;
4192 }
4193 
4194 static int bpf_perf_link_fill_tracepoint(const struct perf_event *event,
4195 					 struct bpf_link_info *info)
4196 {
4197 	char __user *uname;
4198 	u32 ulen;
4199 	int err;
4200 
4201 	uname = u64_to_user_ptr(info->perf_event.tracepoint.tp_name);
4202 	ulen = info->perf_event.tracepoint.name_len;
4203 	err = bpf_perf_link_fill_common(event, uname, &ulen, NULL, NULL, NULL, NULL);
4204 	if (err)
4205 		return err;
4206 
4207 	info->perf_event.type = BPF_PERF_EVENT_TRACEPOINT;
4208 	info->perf_event.tracepoint.name_len = ulen;
4209 	info->perf_event.tracepoint.cookie = event->bpf_cookie;
4210 	return 0;
4211 }
4212 
4213 static int bpf_perf_link_fill_perf_event(const struct perf_event *event,
4214 					 struct bpf_link_info *info)
4215 {
4216 	info->perf_event.event.type = event->attr.type;
4217 	info->perf_event.event.config = event->attr.config;
4218 	info->perf_event.event.cookie = event->bpf_cookie;
4219 	info->perf_event.type = BPF_PERF_EVENT_EVENT;
4220 	return 0;
4221 }
4222 
4223 static int bpf_perf_link_fill_link_info(const struct bpf_link *link,
4224 					struct bpf_link_info *info)
4225 {
4226 	struct bpf_perf_link *perf_link;
4227 	const struct perf_event *event;
4228 
4229 	perf_link = container_of(link, struct bpf_perf_link, link);
4230 	event = perf_get_event(perf_link->perf_file);
4231 	if (IS_ERR(event))
4232 		return PTR_ERR(event);
4233 
4234 	switch (event->prog->type) {
4235 	case BPF_PROG_TYPE_PERF_EVENT:
4236 		return bpf_perf_link_fill_perf_event(event, info);
4237 	case BPF_PROG_TYPE_TRACEPOINT:
4238 		return bpf_perf_link_fill_tracepoint(event, info);
4239 	case BPF_PROG_TYPE_KPROBE:
4240 		return bpf_perf_link_fill_probe(event, info);
4241 	default:
4242 		return -EOPNOTSUPP;
4243 	}
4244 }
4245 
4246 static void bpf_perf_event_link_show_fdinfo(const struct perf_event *event,
4247 					    struct seq_file *seq)
4248 {
4249 	seq_printf(seq,
4250 		   "type:\t%u\n"
4251 		   "config:\t%llu\n"
4252 		   "event_type:\t%s\n"
4253 		   "cookie:\t%llu\n",
4254 		   event->attr.type, event->attr.config,
4255 		   "event", event->bpf_cookie);
4256 }
4257 
4258 static void bpf_tracepoint_link_show_fdinfo(const struct perf_event *event,
4259 					    struct seq_file *seq)
4260 {
4261 	int err;
4262 	const char *name;
4263 	u32 prog_id;
4264 
4265 	err = bpf_get_perf_event_info(event, &prog_id, NULL, &name, NULL,
4266 				      NULL, NULL);
4267 	if (err)
4268 		return;
4269 
4270 	seq_printf(seq,
4271 		   "tp_name:\t%s\n"
4272 		   "event_type:\t%s\n"
4273 		   "cookie:\t%llu\n",
4274 		   name, "tracepoint", event->bpf_cookie);
4275 	kfree_const(name);
4276 }
4277 
4278 static void bpf_probe_link_show_fdinfo(const struct perf_event *event,
4279 				       struct seq_file *seq)
4280 {
4281 #ifdef CONFIG_KPROBE_EVENTS
4282 	if (event->tp_event->flags & TRACE_EVENT_FL_KPROBE)
4283 		return bpf_perf_link_fdinfo_kprobe(event, seq);
4284 #endif
4285 
4286 #ifdef CONFIG_UPROBE_EVENTS
4287 	if (event->tp_event->flags & TRACE_EVENT_FL_UPROBE)
4288 		return bpf_perf_link_fdinfo_uprobe(event, seq);
4289 #endif
4290 }
4291 
4292 static void bpf_perf_link_show_fdinfo(const struct bpf_link *link,
4293 				      struct seq_file *seq)
4294 {
4295 	struct bpf_perf_link *perf_link;
4296 	const struct perf_event *event;
4297 
4298 	perf_link = container_of(link, struct bpf_perf_link, link);
4299 	event = perf_get_event(perf_link->perf_file);
4300 	if (IS_ERR(event))
4301 		return;
4302 
4303 	switch (event->prog->type) {
4304 	case BPF_PROG_TYPE_PERF_EVENT:
4305 		return bpf_perf_event_link_show_fdinfo(event, seq);
4306 	case BPF_PROG_TYPE_TRACEPOINT:
4307 		return bpf_tracepoint_link_show_fdinfo(event, seq);
4308 	case BPF_PROG_TYPE_KPROBE:
4309 		return bpf_probe_link_show_fdinfo(event, seq);
4310 	default:
4311 		return;
4312 	}
4313 }
4314 
4315 static const struct bpf_link_ops bpf_perf_link_lops = {
4316 	.release = bpf_perf_link_release,
4317 	.dealloc = bpf_perf_link_dealloc,
4318 	.fill_link_info = bpf_perf_link_fill_link_info,
4319 	.show_fdinfo = bpf_perf_link_show_fdinfo,
4320 };
4321 
4322 static int bpf_perf_link_attach(const union bpf_attr *attr, struct bpf_prog *prog)
4323 {
4324 	struct bpf_link_primer link_primer;
4325 	struct bpf_perf_link *link;
4326 	struct perf_event *event;
4327 	struct file *perf_file;
4328 	int err;
4329 
4330 	if (attr->link_create.flags)
4331 		return -EINVAL;
4332 
4333 	perf_file = perf_event_get(attr->link_create.target_fd);
4334 	if (IS_ERR(perf_file))
4335 		return PTR_ERR(perf_file);
4336 
4337 	link = kzalloc_obj(*link, GFP_USER);
4338 	if (!link) {
4339 		err = -ENOMEM;
4340 		goto out_put_file;
4341 	}
4342 	bpf_link_init(&link->link, BPF_LINK_TYPE_PERF_EVENT, &bpf_perf_link_lops, prog,
4343 		      attr->link_create.attach_type);
4344 	link->perf_file = perf_file;
4345 
4346 	err = bpf_link_prime(&link->link, &link_primer);
4347 	if (err) {
4348 		kfree(link);
4349 		goto out_put_file;
4350 	}
4351 
4352 	event = perf_file->private_data;
4353 	err = perf_event_set_bpf_prog(event, prog, attr->link_create.perf_event.bpf_cookie);
4354 	if (err) {
4355 		bpf_link_cleanup(&link_primer);
4356 		goto out_put_file;
4357 	}
4358 	/* perf_event_set_bpf_prog() doesn't take its own refcnt on prog */
4359 	bpf_prog_inc(prog);
4360 
4361 	return bpf_link_settle(&link_primer);
4362 
4363 out_put_file:
4364 	fput(perf_file);
4365 	return err;
4366 }
4367 #else
4368 static int bpf_perf_link_attach(const union bpf_attr *attr, struct bpf_prog *prog)
4369 {
4370 	return -EOPNOTSUPP;
4371 }
4372 #endif /* CONFIG_PERF_EVENTS */
4373 
4374 static int bpf_raw_tp_link_attach(struct bpf_prog *prog,
4375 				  const char __user *user_tp_name, u64 cookie,
4376 				  enum bpf_attach_type attach_type)
4377 {
4378 	struct bpf_link_primer link_primer;
4379 	struct bpf_raw_tp_link *link;
4380 	struct bpf_raw_event_map *btp;
4381 	const char *tp_name;
4382 	char buf[128];
4383 	int err;
4384 
4385 	switch (prog->type) {
4386 	case BPF_PROG_TYPE_TRACING:
4387 	case BPF_PROG_TYPE_EXT:
4388 	case BPF_PROG_TYPE_LSM:
4389 		if (user_tp_name)
4390 			/* The attach point for this category of programs
4391 			 * should be specified via btf_id during program load.
4392 			 */
4393 			return -EINVAL;
4394 		if (prog->type == BPF_PROG_TYPE_TRACING &&
4395 		    prog->expected_attach_type == BPF_TRACE_RAW_TP) {
4396 			tp_name = prog->aux->attach_func_name;
4397 			break;
4398 		}
4399 		return bpf_tracing_prog_attach(prog, 0, 0, 0, attach_type);
4400 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
4401 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
4402 		if (strncpy_from_user(buf, user_tp_name, sizeof(buf) - 1) < 0)
4403 			return -EFAULT;
4404 		buf[sizeof(buf) - 1] = 0;
4405 		tp_name = buf;
4406 		break;
4407 	default:
4408 		return -EINVAL;
4409 	}
4410 
4411 	btp = bpf_get_raw_tracepoint(tp_name);
4412 	if (!btp)
4413 		return -ENOENT;
4414 
4415 	if (prog->sleepable && !tracepoint_is_faultable(btp->tp)) {
4416 		bpf_put_raw_tracepoint(btp);
4417 		return -EINVAL;
4418 	}
4419 
4420 	link = kzalloc_obj(*link, GFP_USER);
4421 	if (!link) {
4422 		err = -ENOMEM;
4423 		goto out_put_btp;
4424 	}
4425 	bpf_link_init_sleepable(&link->link, BPF_LINK_TYPE_RAW_TRACEPOINT,
4426 				&bpf_raw_tp_link_lops, prog, attach_type,
4427 				tracepoint_is_faultable(btp->tp));
4428 	link->btp = btp;
4429 	link->cookie = cookie;
4430 
4431 	err = bpf_link_prime(&link->link, &link_primer);
4432 	if (err) {
4433 		kfree(link);
4434 		goto out_put_btp;
4435 	}
4436 
4437 	err = bpf_probe_register(link->btp, link);
4438 	if (err) {
4439 		bpf_link_cleanup(&link_primer);
4440 		goto out_put_btp;
4441 	}
4442 
4443 	return bpf_link_settle(&link_primer);
4444 
4445 out_put_btp:
4446 	bpf_put_raw_tracepoint(btp);
4447 	return err;
4448 }
4449 
4450 #define BPF_RAW_TRACEPOINT_OPEN_LAST_FIELD raw_tracepoint.cookie
4451 
4452 static int bpf_raw_tracepoint_open(const union bpf_attr *attr)
4453 {
4454 	struct bpf_prog *prog;
4455 	void __user *tp_name;
4456 	__u64 cookie;
4457 	int fd;
4458 
4459 	if (CHECK_ATTR(BPF_RAW_TRACEPOINT_OPEN))
4460 		return -EINVAL;
4461 
4462 	prog = bpf_prog_get(attr->raw_tracepoint.prog_fd);
4463 	if (IS_ERR(prog))
4464 		return PTR_ERR(prog);
4465 
4466 	tp_name = u64_to_user_ptr(attr->raw_tracepoint.name);
4467 	cookie = attr->raw_tracepoint.cookie;
4468 	fd = bpf_raw_tp_link_attach(prog, tp_name, cookie, prog->expected_attach_type);
4469 	if (fd < 0)
4470 		bpf_prog_put(prog);
4471 	return fd;
4472 }
4473 
4474 static enum bpf_prog_type
4475 attach_type_to_prog_type(enum bpf_attach_type attach_type)
4476 {
4477 	switch (attach_type) {
4478 	case BPF_CGROUP_INET_INGRESS:
4479 	case BPF_CGROUP_INET_EGRESS:
4480 		return BPF_PROG_TYPE_CGROUP_SKB;
4481 	case BPF_CGROUP_INET_SOCK_CREATE:
4482 	case BPF_CGROUP_INET_SOCK_RELEASE:
4483 	case BPF_CGROUP_INET4_POST_BIND:
4484 	case BPF_CGROUP_INET6_POST_BIND:
4485 		return BPF_PROG_TYPE_CGROUP_SOCK;
4486 	case BPF_CGROUP_INET4_BIND:
4487 	case BPF_CGROUP_INET6_BIND:
4488 	case BPF_CGROUP_INET4_CONNECT:
4489 	case BPF_CGROUP_INET6_CONNECT:
4490 	case BPF_CGROUP_UNIX_CONNECT:
4491 	case BPF_CGROUP_INET4_GETPEERNAME:
4492 	case BPF_CGROUP_INET6_GETPEERNAME:
4493 	case BPF_CGROUP_UNIX_GETPEERNAME:
4494 	case BPF_CGROUP_INET4_GETSOCKNAME:
4495 	case BPF_CGROUP_INET6_GETSOCKNAME:
4496 	case BPF_CGROUP_UNIX_GETSOCKNAME:
4497 	case BPF_CGROUP_UDP4_SENDMSG:
4498 	case BPF_CGROUP_UDP6_SENDMSG:
4499 	case BPF_CGROUP_UNIX_SENDMSG:
4500 	case BPF_CGROUP_UDP4_RECVMSG:
4501 	case BPF_CGROUP_UDP6_RECVMSG:
4502 	case BPF_CGROUP_UNIX_RECVMSG:
4503 		return BPF_PROG_TYPE_CGROUP_SOCK_ADDR;
4504 	case BPF_CGROUP_SOCK_OPS:
4505 		return BPF_PROG_TYPE_SOCK_OPS;
4506 	case BPF_CGROUP_DEVICE:
4507 		return BPF_PROG_TYPE_CGROUP_DEVICE;
4508 	case BPF_SK_MSG_VERDICT:
4509 		return BPF_PROG_TYPE_SK_MSG;
4510 	case BPF_SK_SKB_STREAM_PARSER:
4511 	case BPF_SK_SKB_STREAM_VERDICT:
4512 	case BPF_SK_SKB_VERDICT:
4513 		return BPF_PROG_TYPE_SK_SKB;
4514 	case BPF_LIRC_MODE2:
4515 		return BPF_PROG_TYPE_LIRC_MODE2;
4516 	case BPF_FLOW_DISSECTOR:
4517 		return BPF_PROG_TYPE_FLOW_DISSECTOR;
4518 	case BPF_CGROUP_SYSCTL:
4519 		return BPF_PROG_TYPE_CGROUP_SYSCTL;
4520 	case BPF_CGROUP_GETSOCKOPT:
4521 	case BPF_CGROUP_SETSOCKOPT:
4522 		return BPF_PROG_TYPE_CGROUP_SOCKOPT;
4523 	case BPF_TRACE_ITER:
4524 	case BPF_TRACE_RAW_TP:
4525 	case BPF_TRACE_FENTRY:
4526 	case BPF_TRACE_FEXIT:
4527 	case BPF_TRACE_FSESSION:
4528 	case BPF_TRACE_FSESSION_MULTI:
4529 	case BPF_TRACE_FENTRY_MULTI:
4530 	case BPF_TRACE_FEXIT_MULTI:
4531 	case BPF_MODIFY_RETURN:
4532 		return BPF_PROG_TYPE_TRACING;
4533 	case BPF_LSM_MAC:
4534 		return BPF_PROG_TYPE_LSM;
4535 	case BPF_SK_LOOKUP:
4536 		return BPF_PROG_TYPE_SK_LOOKUP;
4537 	case BPF_XDP:
4538 		return BPF_PROG_TYPE_XDP;
4539 	case BPF_LSM_CGROUP:
4540 		return BPF_PROG_TYPE_LSM;
4541 	case BPF_TCX_INGRESS:
4542 	case BPF_TCX_EGRESS:
4543 	case BPF_NETKIT_PRIMARY:
4544 	case BPF_NETKIT_PEER:
4545 		return BPF_PROG_TYPE_SCHED_CLS;
4546 	default:
4547 		return BPF_PROG_TYPE_UNSPEC;
4548 	}
4549 }
4550 
4551 static int bpf_prog_attach_check_attach_type(const struct bpf_prog *prog,
4552 					     enum bpf_attach_type attach_type)
4553 {
4554 	enum bpf_prog_type ptype;
4555 
4556 	switch (prog->type) {
4557 	case BPF_PROG_TYPE_CGROUP_SOCK:
4558 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
4559 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
4560 	case BPF_PROG_TYPE_SK_LOOKUP:
4561 		return attach_type == prog->expected_attach_type ? 0 : -EINVAL;
4562 	case BPF_PROG_TYPE_CGROUP_SKB:
4563 		if (!bpf_token_capable(prog->aux->token, CAP_NET_ADMIN))
4564 			/* cg-skb progs can be loaded by unpriv user.
4565 			 * check permissions at attach time.
4566 			 */
4567 			return -EPERM;
4568 
4569 		ptype = attach_type_to_prog_type(attach_type);
4570 		if (prog->type != ptype)
4571 			return -EINVAL;
4572 
4573 		return prog->enforce_expected_attach_type &&
4574 			prog->expected_attach_type != attach_type ?
4575 			-EINVAL : 0;
4576 	case BPF_PROG_TYPE_EXT:
4577 		return 0;
4578 	case BPF_PROG_TYPE_NETFILTER:
4579 		if (attach_type != BPF_NETFILTER)
4580 			return -EINVAL;
4581 		return 0;
4582 	case BPF_PROG_TYPE_PERF_EVENT:
4583 	case BPF_PROG_TYPE_TRACEPOINT:
4584 		if (attach_type != BPF_PERF_EVENT)
4585 			return -EINVAL;
4586 		return 0;
4587 	case BPF_PROG_TYPE_KPROBE:
4588 		if (prog->expected_attach_type == BPF_TRACE_KPROBE_MULTI &&
4589 		    attach_type != BPF_TRACE_KPROBE_MULTI)
4590 			return -EINVAL;
4591 		if (prog->expected_attach_type == BPF_TRACE_KPROBE_SESSION &&
4592 		    attach_type != BPF_TRACE_KPROBE_SESSION)
4593 			return -EINVAL;
4594 		if (prog->expected_attach_type == BPF_TRACE_UPROBE_MULTI &&
4595 		    attach_type != BPF_TRACE_UPROBE_MULTI)
4596 			return -EINVAL;
4597 		if (prog->expected_attach_type == BPF_TRACE_UPROBE_SESSION &&
4598 		    attach_type != BPF_TRACE_UPROBE_SESSION)
4599 			return -EINVAL;
4600 		if (attach_type != BPF_PERF_EVENT &&
4601 		    attach_type != BPF_TRACE_KPROBE_MULTI &&
4602 		    attach_type != BPF_TRACE_KPROBE_SESSION &&
4603 		    attach_type != BPF_TRACE_UPROBE_MULTI &&
4604 		    attach_type != BPF_TRACE_UPROBE_SESSION)
4605 			return -EINVAL;
4606 		return 0;
4607 	case BPF_PROG_TYPE_SCHED_CLS:
4608 		if (attach_type != BPF_TCX_INGRESS &&
4609 		    attach_type != BPF_TCX_EGRESS &&
4610 		    attach_type != BPF_NETKIT_PRIMARY &&
4611 		    attach_type != BPF_NETKIT_PEER)
4612 			return -EINVAL;
4613 		return 0;
4614 	default:
4615 		ptype = attach_type_to_prog_type(attach_type);
4616 		if (ptype == BPF_PROG_TYPE_UNSPEC || ptype != prog->type)
4617 			return -EINVAL;
4618 		return 0;
4619 	}
4620 }
4621 
4622 static bool is_cgroup_prog_type(enum bpf_prog_type ptype, enum bpf_attach_type atype,
4623 				bool check_atype)
4624 {
4625 	switch (ptype) {
4626 	case BPF_PROG_TYPE_CGROUP_DEVICE:
4627 	case BPF_PROG_TYPE_CGROUP_SKB:
4628 	case BPF_PROG_TYPE_CGROUP_SOCK:
4629 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
4630 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
4631 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
4632 	case BPF_PROG_TYPE_SOCK_OPS:
4633 		return true;
4634 	case BPF_PROG_TYPE_LSM:
4635 		return check_atype ? atype == BPF_LSM_CGROUP : true;
4636 	default:
4637 		return false;
4638 	}
4639 }
4640 
4641 #define BPF_PROG_ATTACH_LAST_FIELD expected_revision
4642 
4643 #define BPF_F_ATTACH_MASK_BASE	\
4644 	(BPF_F_ALLOW_OVERRIDE |	\
4645 	 BPF_F_ALLOW_MULTI |	\
4646 	 BPF_F_REPLACE |	\
4647 	 BPF_F_PREORDER)
4648 
4649 #define BPF_F_ATTACH_MASK_MPROG	\
4650 	(BPF_F_REPLACE |	\
4651 	 BPF_F_BEFORE |		\
4652 	 BPF_F_AFTER |		\
4653 	 BPF_F_ID |		\
4654 	 BPF_F_LINK)
4655 
4656 static int bpf_prog_attach(const union bpf_attr *attr)
4657 {
4658 	enum bpf_prog_type ptype;
4659 	struct bpf_prog *prog;
4660 	int ret;
4661 
4662 	if (CHECK_ATTR(BPF_PROG_ATTACH))
4663 		return -EINVAL;
4664 
4665 	ptype = attach_type_to_prog_type(attr->attach_type);
4666 	if (ptype == BPF_PROG_TYPE_UNSPEC)
4667 		return -EINVAL;
4668 	if (bpf_mprog_supported(ptype)) {
4669 		if (attr->attach_flags & ~BPF_F_ATTACH_MASK_MPROG)
4670 			return -EINVAL;
4671 	} else if (is_cgroup_prog_type(ptype, 0, false)) {
4672 		if (attr->attach_flags & ~(BPF_F_ATTACH_MASK_BASE | BPF_F_ATTACH_MASK_MPROG))
4673 			return -EINVAL;
4674 	} else {
4675 		if (attr->attach_flags & ~BPF_F_ATTACH_MASK_BASE)
4676 			return -EINVAL;
4677 		if (attr->relative_fd ||
4678 		    attr->expected_revision)
4679 			return -EINVAL;
4680 	}
4681 
4682 	prog = bpf_prog_get_type(attr->attach_bpf_fd, ptype);
4683 	if (IS_ERR(prog))
4684 		return PTR_ERR(prog);
4685 
4686 	if (bpf_prog_attach_check_attach_type(prog, attr->attach_type)) {
4687 		bpf_prog_put(prog);
4688 		return -EINVAL;
4689 	}
4690 
4691 	if (is_cgroup_prog_type(ptype, prog->expected_attach_type, true)) {
4692 		ret = cgroup_bpf_prog_attach(attr, ptype, prog);
4693 		goto out;
4694 	}
4695 
4696 	switch (ptype) {
4697 	case BPF_PROG_TYPE_SK_SKB:
4698 	case BPF_PROG_TYPE_SK_MSG:
4699 		ret = sock_map_get_from_fd(attr, prog);
4700 		break;
4701 	case BPF_PROG_TYPE_LIRC_MODE2:
4702 		ret = lirc_prog_attach(attr, prog);
4703 		break;
4704 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
4705 		ret = netns_bpf_prog_attach(attr, prog);
4706 		break;
4707 	case BPF_PROG_TYPE_SCHED_CLS:
4708 		if (attr->attach_type == BPF_TCX_INGRESS ||
4709 		    attr->attach_type == BPF_TCX_EGRESS)
4710 			ret = tcx_prog_attach(attr, prog);
4711 		else
4712 			ret = netkit_prog_attach(attr, prog);
4713 		break;
4714 	default:
4715 		ret = -EINVAL;
4716 	}
4717 out:
4718 	if (ret)
4719 		bpf_prog_put(prog);
4720 	return ret;
4721 }
4722 
4723 #define BPF_PROG_DETACH_LAST_FIELD expected_revision
4724 
4725 static int bpf_prog_detach(const union bpf_attr *attr)
4726 {
4727 	struct bpf_prog *prog = NULL;
4728 	enum bpf_prog_type ptype;
4729 	int ret;
4730 
4731 	if (CHECK_ATTR(BPF_PROG_DETACH))
4732 		return -EINVAL;
4733 
4734 	ptype = attach_type_to_prog_type(attr->attach_type);
4735 	if (bpf_mprog_supported(ptype)) {
4736 		if (ptype == BPF_PROG_TYPE_UNSPEC)
4737 			return -EINVAL;
4738 		if (attr->attach_flags & ~BPF_F_ATTACH_MASK_MPROG)
4739 			return -EINVAL;
4740 		if (attr->attach_bpf_fd) {
4741 			prog = bpf_prog_get_type(attr->attach_bpf_fd, ptype);
4742 			if (IS_ERR(prog))
4743 				return PTR_ERR(prog);
4744 		} else if (!bpf_mprog_detach_empty(ptype)) {
4745 			return -EPERM;
4746 		}
4747 	} else if (is_cgroup_prog_type(ptype, 0, false)) {
4748 		if (attr->attach_flags || attr->relative_fd)
4749 			return -EINVAL;
4750 	} else if (attr->attach_flags ||
4751 		   attr->relative_fd ||
4752 		   attr->expected_revision) {
4753 		return -EINVAL;
4754 	}
4755 
4756 	switch (ptype) {
4757 	case BPF_PROG_TYPE_SK_MSG:
4758 	case BPF_PROG_TYPE_SK_SKB:
4759 		ret = sock_map_prog_detach(attr, ptype);
4760 		break;
4761 	case BPF_PROG_TYPE_LIRC_MODE2:
4762 		ret = lirc_prog_detach(attr);
4763 		break;
4764 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
4765 		ret = netns_bpf_prog_detach(attr, ptype);
4766 		break;
4767 	case BPF_PROG_TYPE_CGROUP_DEVICE:
4768 	case BPF_PROG_TYPE_CGROUP_SKB:
4769 	case BPF_PROG_TYPE_CGROUP_SOCK:
4770 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
4771 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
4772 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
4773 	case BPF_PROG_TYPE_SOCK_OPS:
4774 	case BPF_PROG_TYPE_LSM:
4775 		ret = cgroup_bpf_prog_detach(attr, ptype);
4776 		break;
4777 	case BPF_PROG_TYPE_SCHED_CLS:
4778 		if (attr->attach_type == BPF_TCX_INGRESS ||
4779 		    attr->attach_type == BPF_TCX_EGRESS)
4780 			ret = tcx_prog_detach(attr, prog);
4781 		else
4782 			ret = netkit_prog_detach(attr, prog);
4783 		break;
4784 	default:
4785 		ret = -EINVAL;
4786 	}
4787 
4788 	if (prog)
4789 		bpf_prog_put(prog);
4790 	return ret;
4791 }
4792 
4793 #define BPF_PROG_QUERY_LAST_FIELD query.revision
4794 
4795 static int bpf_prog_query(const union bpf_attr *attr,
4796 			  union bpf_attr __user *uattr, u32 uattr_size)
4797 {
4798 	if (!bpf_net_capable())
4799 		return -EPERM;
4800 	if (CHECK_ATTR(BPF_PROG_QUERY))
4801 		return -EINVAL;
4802 	if (attr->query.query_flags & ~BPF_F_QUERY_EFFECTIVE)
4803 		return -EINVAL;
4804 
4805 	switch (attr->query.attach_type) {
4806 	case BPF_CGROUP_INET_INGRESS:
4807 	case BPF_CGROUP_INET_EGRESS:
4808 	case BPF_CGROUP_INET_SOCK_CREATE:
4809 	case BPF_CGROUP_INET_SOCK_RELEASE:
4810 	case BPF_CGROUP_INET4_BIND:
4811 	case BPF_CGROUP_INET6_BIND:
4812 	case BPF_CGROUP_INET4_POST_BIND:
4813 	case BPF_CGROUP_INET6_POST_BIND:
4814 	case BPF_CGROUP_INET4_CONNECT:
4815 	case BPF_CGROUP_INET6_CONNECT:
4816 	case BPF_CGROUP_UNIX_CONNECT:
4817 	case BPF_CGROUP_INET4_GETPEERNAME:
4818 	case BPF_CGROUP_INET6_GETPEERNAME:
4819 	case BPF_CGROUP_UNIX_GETPEERNAME:
4820 	case BPF_CGROUP_INET4_GETSOCKNAME:
4821 	case BPF_CGROUP_INET6_GETSOCKNAME:
4822 	case BPF_CGROUP_UNIX_GETSOCKNAME:
4823 	case BPF_CGROUP_UDP4_SENDMSG:
4824 	case BPF_CGROUP_UDP6_SENDMSG:
4825 	case BPF_CGROUP_UNIX_SENDMSG:
4826 	case BPF_CGROUP_UDP4_RECVMSG:
4827 	case BPF_CGROUP_UDP6_RECVMSG:
4828 	case BPF_CGROUP_UNIX_RECVMSG:
4829 	case BPF_CGROUP_SOCK_OPS:
4830 	case BPF_CGROUP_DEVICE:
4831 	case BPF_CGROUP_SYSCTL:
4832 	case BPF_CGROUP_GETSOCKOPT:
4833 	case BPF_CGROUP_SETSOCKOPT:
4834 	case BPF_LSM_CGROUP:
4835 	case BPF_STRUCT_OPS:
4836 		return cgroup_bpf_prog_query(attr, uattr, uattr_size);
4837 	case BPF_LIRC_MODE2:
4838 		return lirc_prog_query(attr, uattr);
4839 	case BPF_FLOW_DISSECTOR:
4840 	case BPF_SK_LOOKUP:
4841 		return netns_bpf_prog_query(attr, uattr);
4842 	case BPF_SK_SKB_STREAM_PARSER:
4843 	case BPF_SK_SKB_STREAM_VERDICT:
4844 	case BPF_SK_MSG_VERDICT:
4845 	case BPF_SK_SKB_VERDICT:
4846 		return sock_map_bpf_prog_query(attr, uattr);
4847 	case BPF_TCX_INGRESS:
4848 	case BPF_TCX_EGRESS:
4849 		return tcx_prog_query(attr, uattr);
4850 	case BPF_NETKIT_PRIMARY:
4851 	case BPF_NETKIT_PEER:
4852 		return netkit_prog_query(attr, uattr);
4853 	default:
4854 		return -EINVAL;
4855 	}
4856 }
4857 
4858 #define BPF_PROG_TEST_RUN_LAST_FIELD test.batch_size
4859 
4860 static int bpf_prog_test_run(const union bpf_attr *attr,
4861 			     union bpf_attr __user *uattr)
4862 {
4863 	struct bpf_prog *prog;
4864 	int ret = -ENOTSUPP;
4865 
4866 	if (CHECK_ATTR(BPF_PROG_TEST_RUN))
4867 		return -EINVAL;
4868 
4869 	if ((attr->test.ctx_size_in && !attr->test.ctx_in) ||
4870 	    (!attr->test.ctx_size_in && attr->test.ctx_in))
4871 		return -EINVAL;
4872 
4873 	if ((attr->test.ctx_size_out && !attr->test.ctx_out) ||
4874 	    (!attr->test.ctx_size_out && attr->test.ctx_out))
4875 		return -EINVAL;
4876 
4877 	prog = bpf_prog_get(attr->test.prog_fd);
4878 	if (IS_ERR(prog))
4879 		return PTR_ERR(prog);
4880 
4881 	if (prog->aux->ops->test_run)
4882 		ret = prog->aux->ops->test_run(prog, attr, uattr);
4883 
4884 	bpf_prog_put(prog);
4885 	return ret;
4886 }
4887 
4888 #define BPF_OBJ_GET_NEXT_ID_LAST_FIELD next_id
4889 
4890 static int bpf_obj_get_next_id(const union bpf_attr *attr,
4891 			       union bpf_attr __user *uattr,
4892 			       struct idr *idr,
4893 			       spinlock_t *lock)
4894 {
4895 	u32 next_id = attr->start_id;
4896 	int err = 0;
4897 
4898 	if (CHECK_ATTR(BPF_OBJ_GET_NEXT_ID) || next_id >= INT_MAX)
4899 		return -EINVAL;
4900 
4901 	if (!capable(CAP_SYS_ADMIN))
4902 		return -EPERM;
4903 
4904 	next_id++;
4905 	spin_lock_bh(lock);
4906 	if (!idr_get_next(idr, &next_id))
4907 		err = -ENOENT;
4908 	spin_unlock_bh(lock);
4909 
4910 	if (!err)
4911 		err = put_user(next_id, &uattr->next_id);
4912 
4913 	return err;
4914 }
4915 
4916 struct bpf_map *bpf_map_get_curr_or_next(u32 *id)
4917 {
4918 	struct bpf_map *map;
4919 
4920 	spin_lock_bh(&map_idr_lock);
4921 again:
4922 	map = idr_get_next(&map_idr, id);
4923 	if (map) {
4924 		map = __bpf_map_inc_not_zero(map, false);
4925 		if (IS_ERR(map)) {
4926 			(*id)++;
4927 			goto again;
4928 		}
4929 	}
4930 	spin_unlock_bh(&map_idr_lock);
4931 
4932 	return map;
4933 }
4934 
4935 struct bpf_prog *bpf_prog_get_curr_or_next(u32 *id)
4936 {
4937 	struct bpf_prog *prog;
4938 
4939 	spin_lock_bh(&prog_idr_lock);
4940 again:
4941 	prog = idr_get_next(&prog_idr, id);
4942 	if (prog) {
4943 		prog = bpf_prog_inc_not_zero(prog);
4944 		if (IS_ERR(prog)) {
4945 			(*id)++;
4946 			goto again;
4947 		}
4948 	}
4949 	spin_unlock_bh(&prog_idr_lock);
4950 
4951 	return prog;
4952 }
4953 
4954 #define BPF_PROG_GET_FD_BY_ID_LAST_FIELD prog_id
4955 
4956 struct bpf_prog *bpf_prog_by_id(u32 id)
4957 {
4958 	struct bpf_prog *prog;
4959 
4960 	if (!id)
4961 		return ERR_PTR(-ENOENT);
4962 
4963 	spin_lock_bh(&prog_idr_lock);
4964 	prog = idr_find(&prog_idr, id);
4965 	if (prog)
4966 		prog = bpf_prog_inc_not_zero(prog);
4967 	else
4968 		prog = ERR_PTR(-ENOENT);
4969 	spin_unlock_bh(&prog_idr_lock);
4970 	return prog;
4971 }
4972 
4973 static int bpf_prog_get_fd_by_id(const union bpf_attr *attr)
4974 {
4975 	struct bpf_prog *prog;
4976 	u32 id = attr->prog_id;
4977 	int fd;
4978 
4979 	if (CHECK_ATTR(BPF_PROG_GET_FD_BY_ID))
4980 		return -EINVAL;
4981 
4982 	if (!capable(CAP_SYS_ADMIN))
4983 		return -EPERM;
4984 
4985 	prog = bpf_prog_by_id(id);
4986 	if (IS_ERR(prog))
4987 		return PTR_ERR(prog);
4988 
4989 	fd = bpf_prog_new_fd(prog);
4990 	if (fd < 0)
4991 		bpf_prog_put(prog);
4992 
4993 	return fd;
4994 }
4995 
4996 #define BPF_MAP_GET_FD_BY_ID_LAST_FIELD open_flags
4997 
4998 static int bpf_map_get_fd_by_id(const union bpf_attr *attr)
4999 {
5000 	struct bpf_map *map;
5001 	u32 id = attr->map_id;
5002 	int f_flags;
5003 	int fd;
5004 
5005 	if (CHECK_ATTR(BPF_MAP_GET_FD_BY_ID) ||
5006 	    attr->open_flags & ~BPF_OBJ_FLAG_MASK)
5007 		return -EINVAL;
5008 
5009 	if (!capable(CAP_SYS_ADMIN))
5010 		return -EPERM;
5011 
5012 	f_flags = bpf_get_file_flag(attr->open_flags);
5013 	if (f_flags < 0)
5014 		return f_flags;
5015 
5016 	spin_lock_bh(&map_idr_lock);
5017 	map = idr_find(&map_idr, id);
5018 	if (map)
5019 		map = __bpf_map_inc_not_zero(map, true);
5020 	else
5021 		map = ERR_PTR(-ENOENT);
5022 	spin_unlock_bh(&map_idr_lock);
5023 
5024 	if (IS_ERR(map))
5025 		return PTR_ERR(map);
5026 
5027 	fd = bpf_map_new_fd(map, f_flags);
5028 	if (fd < 0)
5029 		bpf_map_put_with_uref(map);
5030 
5031 	return fd;
5032 }
5033 
5034 static const struct bpf_map *bpf_map_from_imm(const struct bpf_prog *prog,
5035 					      unsigned long addr, u32 *off,
5036 					      u32 *type)
5037 {
5038 	const struct bpf_map *map;
5039 	int i;
5040 
5041 	mutex_lock(&prog->aux->used_maps_mutex);
5042 	for (i = 0, *off = 0; i < prog->aux->used_map_cnt; i++) {
5043 		map = prog->aux->used_maps[i];
5044 		if (map == (void *)addr) {
5045 			*type = BPF_PSEUDO_MAP_FD;
5046 			goto out;
5047 		}
5048 		if (!map->ops->map_direct_value_meta)
5049 			continue;
5050 		if (!map->ops->map_direct_value_meta(map, addr, off)) {
5051 			*type = BPF_PSEUDO_MAP_VALUE;
5052 			goto out;
5053 		}
5054 	}
5055 	map = NULL;
5056 
5057 out:
5058 	mutex_unlock(&prog->aux->used_maps_mutex);
5059 	return map;
5060 }
5061 
5062 static void prepare_dump_pseudo_call(struct bpf_insn *insn)
5063 {
5064 	s32 call_off = insn->imm;
5065 
5066 	/*
5067 	 * BPF_CALL_ARGS only exists for interpreter fallback.
5068 	 * 1. For interpreter (BPF_CALL_ARGS): insn->off is the index of
5069 	 *    interpreters_args array, so here using bpf_call_args_imm()
5070 	 *    to get the real address offset.
5071 	 * 2. For JIT (BPF_CALL): insn->off is the subprog id.
5072 	 */
5073 	if (insn->code == (BPF_JMP | BPF_CALL_ARGS))
5074 		insn->imm = bpf_call_args_imm(insn->off);
5075 	else
5076 		insn->imm = insn->off;
5077 
5078 	/* Avoid dumping a truncated and misleading pc-relative offset. */
5079 	if (call_off > S16_MAX || call_off < S16_MIN)
5080 		insn->off = 0;
5081 	else
5082 		insn->off = call_off;
5083 }
5084 
5085 static struct bpf_insn *bpf_insn_prepare_dump(const struct bpf_prog *prog,
5086 					      const struct cred *f_cred)
5087 {
5088 	const struct bpf_map *map;
5089 	struct bpf_insn *insns;
5090 	u32 off, type;
5091 	u64 imm;
5092 	u8 code;
5093 	int i;
5094 
5095 	insns = kmemdup(prog->insnsi, bpf_prog_insn_size(prog),
5096 			GFP_USER);
5097 	if (!insns)
5098 		return insns;
5099 
5100 	for (i = 0; i < prog->len; i++) {
5101 		code = insns[i].code;
5102 
5103 		if (code == (BPF_JMP | BPF_TAIL_CALL)) {
5104 			insns[i].code = BPF_JMP | BPF_CALL;
5105 			insns[i].imm = BPF_FUNC_tail_call;
5106 			/* fall-through */
5107 		}
5108 		/*
5109 		 * BPF_JCOND is the same opcode as BPF_CALL_ARGS. The latter is for
5110 		 * the interpreter, and a prog with unwind_goto is always JITed.
5111 		 */
5112 		if (prog->jited && bpf_is_unwind_goto(&insns[i]))
5113 			continue;
5114 		if (code == (BPF_JMP | BPF_CALL) ||
5115 		    code == (BPF_JMP | BPF_CALL_ARGS)) {
5116 			/* Restore the legacy xlated dump layout. */
5117 			if (insns[i].src_reg == BPF_PSEUDO_CALL)
5118 				prepare_dump_pseudo_call(&insns[i]);
5119 			if (code == (BPF_JMP | BPF_CALL_ARGS))
5120 				insns[i].code = BPF_JMP | BPF_CALL;
5121 			if (!bpf_dump_raw_ok(f_cred))
5122 				insns[i].imm = 0;
5123 			continue;
5124 		}
5125 		if (BPF_CLASS(code) == BPF_LDX && BPF_MODE(code) == BPF_PROBE_MEM) {
5126 			insns[i].code = BPF_LDX | BPF_SIZE(code) | BPF_MEM;
5127 			continue;
5128 		}
5129 
5130 		if ((BPF_CLASS(code) == BPF_LDX || BPF_CLASS(code) == BPF_STX ||
5131 		     BPF_CLASS(code) == BPF_ST) && BPF_MODE(code) == BPF_PROBE_MEM32) {
5132 			insns[i].code = BPF_CLASS(code) | BPF_SIZE(code) | BPF_MEM;
5133 			continue;
5134 		}
5135 
5136 		if (code != (BPF_LD | BPF_IMM | BPF_DW))
5137 			continue;
5138 
5139 		imm = ((u64)insns[i + 1].imm << 32) | (u32)insns[i].imm;
5140 		map = bpf_map_from_imm(prog, imm, &off, &type);
5141 		if (map) {
5142 			insns[i].src_reg = type;
5143 			insns[i].imm = map->id;
5144 			insns[i + 1].imm = off;
5145 			continue;
5146 		}
5147 	}
5148 
5149 	return insns;
5150 }
5151 
5152 static int set_info_rec_size(struct bpf_prog_info *info)
5153 {
5154 	/*
5155 	 * Ensure info.*_rec_size is the same as kernel expected size
5156 	 *
5157 	 * or
5158 	 *
5159 	 * Only allow zero *_rec_size if both _rec_size and _cnt are
5160 	 * zero.  In this case, the kernel will set the expected
5161 	 * _rec_size back to the info.
5162 	 */
5163 
5164 	if ((info->nr_func_info || info->func_info_rec_size) &&
5165 	    info->func_info_rec_size != sizeof(struct bpf_func_info))
5166 		return -EINVAL;
5167 
5168 	if ((info->nr_line_info || info->line_info_rec_size) &&
5169 	    info->line_info_rec_size != sizeof(struct bpf_line_info))
5170 		return -EINVAL;
5171 
5172 	if ((info->nr_jited_line_info || info->jited_line_info_rec_size) &&
5173 	    info->jited_line_info_rec_size != sizeof(__u64))
5174 		return -EINVAL;
5175 
5176 	info->func_info_rec_size = sizeof(struct bpf_func_info);
5177 	info->line_info_rec_size = sizeof(struct bpf_line_info);
5178 	info->jited_line_info_rec_size = sizeof(__u64);
5179 
5180 	return 0;
5181 }
5182 
5183 static int bpf_prog_get_info_by_fd(struct file *file,
5184 				   struct bpf_prog *prog,
5185 				   const union bpf_attr *attr,
5186 				   union bpf_attr __user *uattr)
5187 {
5188 	struct bpf_prog_info __user *uinfo = u64_to_user_ptr(attr->info.info);
5189 	struct btf *attach_btf = bpf_prog_get_target_btf(prog);
5190 	struct bpf_prog_info info;
5191 	u32 info_len = attr->info.info_len;
5192 	struct bpf_prog_kstats stats;
5193 	char __user *uinsns;
5194 	u32 ulen, len;
5195 	int err;
5196 
5197 	len = offsetofend(struct bpf_prog_info, attach_btf_id);
5198 	err = bpf_check_uarg_tail_zero(USER_BPFPTR(uinfo), len, info_len);
5199 	if (err)
5200 		return err;
5201 	info_len = min_t(u32, sizeof(info), info_len);
5202 
5203 	memset(&info, 0, sizeof(info));
5204 	if (copy_from_user(&info, uinfo, info_len))
5205 		return -EFAULT;
5206 
5207 	info.type = prog->type;
5208 	info.id = prog->aux->id;
5209 	info.load_time = prog->aux->load_time;
5210 	info.created_by_uid = from_kuid_munged(current_user_ns(),
5211 					       prog->aux->user->uid);
5212 	info.gpl_compatible = prog->gpl_compatible;
5213 
5214 	memcpy(info.tag, prog->tag, sizeof(prog->tag));
5215 	memcpy(info.name, prog->aux->name, sizeof(prog->aux->name));
5216 
5217 	mutex_lock(&prog->aux->used_maps_mutex);
5218 	ulen = info.nr_map_ids;
5219 	info.nr_map_ids = prog->aux->used_map_cnt;
5220 	ulen = min_t(u32, info.nr_map_ids, ulen);
5221 	if (ulen) {
5222 		u32 __user *user_map_ids = u64_to_user_ptr(info.map_ids);
5223 		u32 i;
5224 
5225 		for (i = 0; i < ulen; i++)
5226 			if (put_user(prog->aux->used_maps[i]->id,
5227 				     &user_map_ids[i])) {
5228 				mutex_unlock(&prog->aux->used_maps_mutex);
5229 				return -EFAULT;
5230 			}
5231 	}
5232 	mutex_unlock(&prog->aux->used_maps_mutex);
5233 
5234 	err = set_info_rec_size(&info);
5235 	if (err)
5236 		return err;
5237 
5238 	bpf_prog_get_stats(prog, &stats);
5239 	info.run_time_ns = stats.nsecs;
5240 	info.run_cnt = stats.cnt;
5241 	info.recursion_misses = stats.misses;
5242 
5243 	info.verified_insns = prog->aux->verified_insns;
5244 	if (prog->aux->btf)
5245 		info.btf_id = btf_obj_id(prog->aux->btf);
5246 
5247 	if (!bpf_capable()) {
5248 		info.jited_prog_len = 0;
5249 		info.xlated_prog_len = 0;
5250 		info.nr_jited_ksyms = 0;
5251 		info.nr_jited_func_lens = 0;
5252 		info.nr_func_info = 0;
5253 		info.nr_line_info = 0;
5254 		info.nr_jited_line_info = 0;
5255 		goto done;
5256 	}
5257 
5258 	ulen = info.xlated_prog_len;
5259 	info.xlated_prog_len = bpf_prog_insn_size(prog);
5260 	if (info.xlated_prog_len && ulen) {
5261 		struct bpf_insn *insns_sanitized;
5262 		bool fault;
5263 
5264 		/* The verifier puts addresses to ld_imm64 and mov insns */
5265 		if (bpf_dump_raw_ok(file->f_cred) || (!prog->blinded && perfmon_capable())) {
5266 			insns_sanitized = bpf_insn_prepare_dump(prog, file->f_cred);
5267 			if (!insns_sanitized)
5268 				return -ENOMEM;
5269 			uinsns = u64_to_user_ptr(info.xlated_prog_insns);
5270 			ulen = min_t(u32, info.xlated_prog_len, ulen);
5271 			fault = copy_to_user(uinsns, insns_sanitized, ulen);
5272 			kfree(insns_sanitized);
5273 			if (fault)
5274 				return -EFAULT;
5275 		} else {
5276 			info.xlated_prog_insns = 0;
5277 		}
5278 	}
5279 
5280 	if (bpf_prog_is_offloaded(prog->aux)) {
5281 		err = bpf_prog_offload_info_fill(&info, prog);
5282 		if (err)
5283 			return err;
5284 		goto done;
5285 	}
5286 
5287 	/* NOTE: the following code is supposed to be skipped for offload.
5288 	 * bpf_prog_offload_info_fill() is the place to fill similar fields
5289 	 * for offload.
5290 	 */
5291 	ulen = info.jited_prog_len;
5292 	if (prog->aux->func_cnt) {
5293 		u32 i;
5294 
5295 		info.jited_prog_len = 0;
5296 		for (i = 0; i < prog->aux->func_cnt; i++)
5297 			info.jited_prog_len += prog->aux->func[i]->jited_len;
5298 	} else {
5299 		info.jited_prog_len = prog->jited_len;
5300 	}
5301 
5302 	if (info.jited_prog_len && ulen) {
5303 		if (bpf_dump_raw_ok(file->f_cred)) {
5304 			uinsns = u64_to_user_ptr(info.jited_prog_insns);
5305 			ulen = min_t(u32, info.jited_prog_len, ulen);
5306 
5307 			/* for multi-function programs, copy the JITed
5308 			 * instructions for all the functions
5309 			 */
5310 			if (prog->aux->func_cnt) {
5311 				u32 len, free, i;
5312 				u8 *img;
5313 
5314 				free = ulen;
5315 				for (i = 0; i < prog->aux->func_cnt; i++) {
5316 					len = prog->aux->func[i]->jited_len;
5317 					len = min_t(u32, len, free);
5318 					img = (u8 *) prog->aux->func[i]->bpf_func;
5319 					if (copy_to_user(uinsns, img, len))
5320 						return -EFAULT;
5321 					uinsns += len;
5322 					free -= len;
5323 					if (!free)
5324 						break;
5325 				}
5326 			} else {
5327 				if (copy_to_user(uinsns, prog->bpf_func, ulen))
5328 					return -EFAULT;
5329 			}
5330 		} else {
5331 			info.jited_prog_insns = 0;
5332 		}
5333 	}
5334 
5335 	ulen = info.nr_jited_ksyms;
5336 	info.nr_jited_ksyms = prog->aux->func_cnt ? : 1;
5337 	if (ulen) {
5338 		if (bpf_dump_raw_ok(file->f_cred)) {
5339 			unsigned long ksym_addr;
5340 			u64 __user *user_ksyms;
5341 			u32 i;
5342 
5343 			/* copy the address of the kernel symbol
5344 			 * corresponding to each function
5345 			 */
5346 			ulen = min_t(u32, info.nr_jited_ksyms, ulen);
5347 			user_ksyms = u64_to_user_ptr(info.jited_ksyms);
5348 			if (prog->aux->func_cnt) {
5349 				for (i = 0; i < ulen; i++) {
5350 					ksym_addr = (unsigned long)
5351 						prog->aux->func[i]->bpf_func;
5352 					if (put_user((u64) ksym_addr,
5353 						     &user_ksyms[i]))
5354 						return -EFAULT;
5355 				}
5356 			} else {
5357 				ksym_addr = (unsigned long) prog->bpf_func;
5358 				if (put_user((u64) ksym_addr, &user_ksyms[0]))
5359 					return -EFAULT;
5360 			}
5361 		} else {
5362 			info.jited_ksyms = 0;
5363 		}
5364 	}
5365 
5366 	ulen = info.nr_jited_func_lens;
5367 	info.nr_jited_func_lens = prog->aux->func_cnt ? : 1;
5368 	if (ulen) {
5369 		if (bpf_dump_raw_ok(file->f_cred)) {
5370 			u32 __user *user_lens;
5371 			u32 func_len, i;
5372 
5373 			/* copy the JITed image lengths for each function */
5374 			ulen = min_t(u32, info.nr_jited_func_lens, ulen);
5375 			user_lens = u64_to_user_ptr(info.jited_func_lens);
5376 			if (prog->aux->func_cnt) {
5377 				for (i = 0; i < ulen; i++) {
5378 					func_len =
5379 						prog->aux->func[i]->jited_len;
5380 					if (put_user(func_len, &user_lens[i]))
5381 						return -EFAULT;
5382 				}
5383 			} else {
5384 				func_len = prog->jited_len;
5385 				if (put_user(func_len, &user_lens[0]))
5386 					return -EFAULT;
5387 			}
5388 		} else {
5389 			info.jited_func_lens = 0;
5390 		}
5391 	}
5392 
5393 	info.attach_btf_id = prog->aux->attach_btf_id;
5394 	if (attach_btf)
5395 		info.attach_btf_obj_id = btf_obj_id(attach_btf);
5396 
5397 	ulen = info.nr_func_info;
5398 	info.nr_func_info = prog->aux->func_info_cnt;
5399 	if (info.nr_func_info && ulen) {
5400 		char __user *user_finfo;
5401 
5402 		user_finfo = u64_to_user_ptr(info.func_info);
5403 		ulen = min_t(u32, info.nr_func_info, ulen);
5404 		if (copy_to_user(user_finfo, prog->aux->func_info,
5405 				 info.func_info_rec_size * ulen))
5406 			return -EFAULT;
5407 	}
5408 
5409 	ulen = info.nr_line_info;
5410 	info.nr_line_info = prog->aux->nr_linfo;
5411 	if (info.nr_line_info && ulen) {
5412 		__u8 __user *user_linfo;
5413 
5414 		user_linfo = u64_to_user_ptr(info.line_info);
5415 		ulen = min_t(u32, info.nr_line_info, ulen);
5416 		if (copy_to_user(user_linfo, prog->aux->linfo,
5417 				 info.line_info_rec_size * ulen))
5418 			return -EFAULT;
5419 	}
5420 
5421 	ulen = info.nr_jited_line_info;
5422 	if (prog->aux->jited_linfo)
5423 		info.nr_jited_line_info = prog->aux->nr_linfo;
5424 	else
5425 		info.nr_jited_line_info = 0;
5426 	if (info.nr_jited_line_info && ulen) {
5427 		if (bpf_dump_raw_ok(file->f_cred)) {
5428 			unsigned long line_addr;
5429 			__u64 __user *user_linfo;
5430 			u32 i;
5431 
5432 			user_linfo = u64_to_user_ptr(info.jited_line_info);
5433 			ulen = min_t(u32, info.nr_jited_line_info, ulen);
5434 			for (i = 0; i < ulen; i++) {
5435 				line_addr = (unsigned long)prog->aux->jited_linfo[i];
5436 				if (put_user((__u64)line_addr, &user_linfo[i]))
5437 					return -EFAULT;
5438 			}
5439 		} else {
5440 			info.jited_line_info = 0;
5441 		}
5442 	}
5443 
5444 	ulen = info.nr_prog_tags;
5445 	info.nr_prog_tags = prog->aux->func_cnt ? : 1;
5446 	if (ulen) {
5447 		__u8 __user (*user_prog_tags)[BPF_TAG_SIZE];
5448 		u32 i;
5449 
5450 		user_prog_tags = u64_to_user_ptr(info.prog_tags);
5451 		ulen = min_t(u32, info.nr_prog_tags, ulen);
5452 		if (prog->aux->func_cnt) {
5453 			for (i = 0; i < ulen; i++) {
5454 				if (copy_to_user(user_prog_tags[i],
5455 						 prog->aux->func[i]->tag,
5456 						 BPF_TAG_SIZE))
5457 					return -EFAULT;
5458 			}
5459 		} else {
5460 			if (copy_to_user(user_prog_tags[0],
5461 					 prog->tag, BPF_TAG_SIZE))
5462 				return -EFAULT;
5463 		}
5464 	}
5465 
5466 done:
5467 	if (copy_to_user(uinfo, &info, info_len) ||
5468 	    put_user(info_len, &uattr->info.info_len))
5469 		return -EFAULT;
5470 
5471 	return 0;
5472 }
5473 
5474 static int bpf_map_get_info_by_fd(struct file *file,
5475 				  struct bpf_map *map,
5476 				  const union bpf_attr *attr,
5477 				  union bpf_attr __user *uattr)
5478 {
5479 	struct bpf_map_info __user *uinfo = u64_to_user_ptr(attr->info.info);
5480 	struct bpf_map_info info;
5481 	u32 info_len = attr->info.info_len, len;
5482 	int err;
5483 
5484 	len = offsetofend(struct bpf_map_info, hash_size);
5485 	err = bpf_check_uarg_tail_zero(USER_BPFPTR(uinfo), len, info_len);
5486 	if (err)
5487 		return err;
5488 	info_len = min_t(u32, sizeof(info), info_len);
5489 
5490 	memset(&info, 0, sizeof(info));
5491 	if (info_len >= offsetofend(struct bpf_map_info, hash) &&
5492 	    get_user(info.hash, &uinfo->hash))
5493 		return -EFAULT;
5494 	if (info_len >= offsetofend(struct bpf_map_info, hash_size) &&
5495 	    get_user(info.hash_size, &uinfo->hash_size))
5496 		return -EFAULT;
5497 
5498 	info.type = map->map_type;
5499 	info.id = map->id;
5500 	info.key_size = map->key_size;
5501 	info.value_size = map->value_size;
5502 	info.max_entries = map->max_entries;
5503 	info.map_flags = map->map_flags;
5504 	info.map_extra = map->map_extra;
5505 	memcpy(info.name, map->name, sizeof(map->name));
5506 
5507 	if (map->btf) {
5508 		info.btf_id = btf_obj_id(map->btf);
5509 		info.btf_key_type_id = map->btf_key_type_id;
5510 		info.btf_value_type_id = map->btf_value_type_id;
5511 	}
5512 	info.btf_vmlinux_value_type_id = map->btf_vmlinux_value_type_id;
5513 	if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS)
5514 		bpf_map_struct_ops_info_fill(&info, map);
5515 
5516 	if (bpf_map_is_offloaded(map)) {
5517 		err = bpf_map_offload_info_fill(&info, map);
5518 		if (err)
5519 			return err;
5520 	}
5521 
5522 	if (info.hash) {
5523 		char __user *uhash = u64_to_user_ptr(info.hash);
5524 
5525 		if (!map->ops->map_get_hash)
5526 			return -EINVAL;
5527 		if (info.hash_size != sizeof(map->sha))
5528 			return -EINVAL;
5529 		if (!READ_ONCE(map->frozen))
5530 			return -EPERM;
5531 
5532 		err = map->ops->map_get_hash(map);
5533 		if (err != 0)
5534 			return err;
5535 
5536 		if (copy_to_user(uhash, map->sha, sizeof(map->sha)) != 0)
5537 			return -EFAULT;
5538 	} else if (info.hash_size) {
5539 		return -EINVAL;
5540 	}
5541 
5542 	if (copy_to_user(uinfo, &info, info_len) ||
5543 	    put_user(info_len, &uattr->info.info_len))
5544 		return -EFAULT;
5545 
5546 	return 0;
5547 }
5548 
5549 static int bpf_btf_get_info_by_fd(struct file *file,
5550 				  struct btf *btf,
5551 				  const union bpf_attr *attr,
5552 				  union bpf_attr __user *uattr)
5553 {
5554 	struct bpf_btf_info __user *uinfo = u64_to_user_ptr(attr->info.info);
5555 	u32 info_len = attr->info.info_len;
5556 	int err;
5557 
5558 	err = bpf_check_uarg_tail_zero(USER_BPFPTR(uinfo), sizeof(*uinfo), info_len);
5559 	if (err)
5560 		return err;
5561 
5562 	return btf_get_info_by_fd(btf, attr, uattr);
5563 }
5564 
5565 static int bpf_link_get_info_by_fd(struct file *file,
5566 				  struct bpf_link *link,
5567 				  const union bpf_attr *attr,
5568 				  union bpf_attr __user *uattr)
5569 {
5570 	struct bpf_link_info __user *uinfo = u64_to_user_ptr(attr->info.info);
5571 	struct bpf_link_info info;
5572 	const struct bpf_prog *prog;
5573 	u32 info_len = attr->info.info_len;
5574 	int err;
5575 
5576 	err = bpf_check_uarg_tail_zero(USER_BPFPTR(uinfo), sizeof(info), info_len);
5577 	if (err)
5578 		return err;
5579 	info_len = min_t(u32, sizeof(info), info_len);
5580 
5581 	memset(&info, 0, sizeof(info));
5582 	if (copy_from_user(&info, uinfo, info_len))
5583 		return -EFAULT;
5584 
5585 	info.type = link->type;
5586 	info.id = link->id;
5587 
5588 	rcu_read_lock();
5589 	prog = READ_ONCE(link->prog);
5590 	if (prog)
5591 		info.prog_id = prog->aux->id;
5592 	rcu_read_unlock();
5593 
5594 	if (link->ops->fill_link_info) {
5595 		err = link->ops->fill_link_info(link, &info);
5596 		if (err)
5597 			return err;
5598 	}
5599 
5600 	if (copy_to_user(uinfo, &info, info_len) ||
5601 	    put_user(info_len, &uattr->info.info_len))
5602 		return -EFAULT;
5603 
5604 	return 0;
5605 }
5606 
5607 static int token_get_info_by_fd(struct file *file,
5608 				struct bpf_token *token,
5609 				const union bpf_attr *attr,
5610 				union bpf_attr __user *uattr)
5611 {
5612 	struct bpf_token_info __user *uinfo = u64_to_user_ptr(attr->info.info);
5613 	u32 info_len = attr->info.info_len;
5614 	int err;
5615 
5616 	err = bpf_check_uarg_tail_zero(USER_BPFPTR(uinfo), sizeof(*uinfo), info_len);
5617 	if (err)
5618 		return err;
5619 	return bpf_token_get_info_by_fd(token, attr, uattr);
5620 }
5621 
5622 #define BPF_OBJ_GET_INFO_BY_FD_LAST_FIELD info.info
5623 
5624 static int bpf_obj_get_info_by_fd(const union bpf_attr *attr,
5625 				  union bpf_attr __user *uattr)
5626 {
5627 	if (CHECK_ATTR(BPF_OBJ_GET_INFO_BY_FD))
5628 		return -EINVAL;
5629 
5630 	CLASS(fd, f)(attr->info.bpf_fd);
5631 	if (fd_empty(f))
5632 		return -EBADFD;
5633 
5634 	if (fd_file(f)->f_op == &bpf_prog_fops)
5635 		return bpf_prog_get_info_by_fd(fd_file(f), fd_file(f)->private_data, attr,
5636 					      uattr);
5637 	else if (fd_file(f)->f_op == &bpf_map_fops)
5638 		return bpf_map_get_info_by_fd(fd_file(f), fd_file(f)->private_data, attr,
5639 					     uattr);
5640 	else if (fd_file(f)->f_op == &btf_fops)
5641 		return bpf_btf_get_info_by_fd(fd_file(f), fd_file(f)->private_data, attr, uattr);
5642 	else if (fd_file(f)->f_op == &bpf_link_fops || fd_file(f)->f_op == &bpf_link_fops_poll)
5643 		return bpf_link_get_info_by_fd(fd_file(f), fd_file(f)->private_data,
5644 					      attr, uattr);
5645 	else if (fd_file(f)->f_op == &bpf_token_fops)
5646 		return token_get_info_by_fd(fd_file(f), fd_file(f)->private_data,
5647 					    attr, uattr);
5648 	return -EINVAL;
5649 }
5650 
5651 #define BPF_BTF_LOAD_LAST_FIELD btf_token_fd
5652 
5653 static int bpf_btf_load(const union bpf_attr *attr, bpfptr_t uattr, struct bpf_log_attr *attr_log)
5654 {
5655 	struct bpf_token *token = NULL;
5656 
5657 	if (CHECK_ATTR(BPF_BTF_LOAD))
5658 		return -EINVAL;
5659 
5660 	if (attr->btf_flags & ~BPF_F_TOKEN_FD)
5661 		return -EINVAL;
5662 
5663 	if (attr->btf_flags & BPF_F_TOKEN_FD) {
5664 		token = bpf_token_get_from_fd(attr->btf_token_fd);
5665 		if (IS_ERR(token))
5666 			return PTR_ERR(token);
5667 		if (!bpf_token_allow_cmd(token, BPF_BTF_LOAD)) {
5668 			bpf_token_put(token);
5669 			token = NULL;
5670 		}
5671 	}
5672 
5673 	if (!bpf_token_capable(token, CAP_BPF)) {
5674 		bpf_token_put(token);
5675 		return -EPERM;
5676 	}
5677 
5678 	bpf_token_put(token);
5679 
5680 	return btf_new_fd(attr, uattr, attr_log);
5681 }
5682 
5683 #define BPF_BTF_GET_FD_BY_ID_LAST_FIELD fd_by_id_token_fd
5684 
5685 static int bpf_btf_get_fd_by_id(const union bpf_attr *attr)
5686 {
5687 	struct bpf_token *token = NULL;
5688 
5689 	if (CHECK_ATTR(BPF_BTF_GET_FD_BY_ID))
5690 		return -EINVAL;
5691 
5692 	if (attr->open_flags & ~BPF_F_TOKEN_FD)
5693 		return -EINVAL;
5694 
5695 	if (attr->open_flags & BPF_F_TOKEN_FD) {
5696 		token = bpf_token_get_from_fd(attr->fd_by_id_token_fd);
5697 		if (IS_ERR(token))
5698 			return PTR_ERR(token);
5699 		if (!bpf_token_allow_cmd(token, BPF_BTF_GET_FD_BY_ID)) {
5700 			bpf_token_put(token);
5701 			token = NULL;
5702 		}
5703 	}
5704 
5705 	if (!bpf_token_capable(token, CAP_SYS_ADMIN)) {
5706 		bpf_token_put(token);
5707 		return -EPERM;
5708 	}
5709 
5710 	bpf_token_put(token);
5711 
5712 	return btf_get_fd_by_id(attr->btf_id);
5713 }
5714 
5715 static int bpf_task_fd_query_copy(const union bpf_attr *attr,
5716 				    union bpf_attr __user *uattr,
5717 				    u32 prog_id, u32 fd_type,
5718 				    const char *buf, u64 probe_offset,
5719 				    u64 probe_addr)
5720 {
5721 	char __user *ubuf = u64_to_user_ptr(attr->task_fd_query.buf);
5722 	u32 len = buf ? strlen(buf) : 0, input_len;
5723 	int err = 0;
5724 
5725 	if (put_user(len, &uattr->task_fd_query.buf_len))
5726 		return -EFAULT;
5727 	input_len = attr->task_fd_query.buf_len;
5728 	if (input_len && ubuf) {
5729 		if (!len) {
5730 			/* nothing to copy, just make ubuf NULL terminated */
5731 			char zero = '\0';
5732 
5733 			if (put_user(zero, ubuf))
5734 				return -EFAULT;
5735 		} else {
5736 			err = bpf_copy_to_user(ubuf, buf, input_len, len);
5737 			if (err == -EFAULT)
5738 				return err;
5739 		}
5740 	}
5741 
5742 	if (put_user(prog_id, &uattr->task_fd_query.prog_id) ||
5743 	    put_user(fd_type, &uattr->task_fd_query.fd_type) ||
5744 	    put_user(probe_offset, &uattr->task_fd_query.probe_offset) ||
5745 	    put_user(probe_addr, &uattr->task_fd_query.probe_addr))
5746 		return -EFAULT;
5747 
5748 	return err;
5749 }
5750 
5751 #define BPF_TASK_FD_QUERY_LAST_FIELD task_fd_query.probe_addr
5752 
5753 static int bpf_task_fd_query(const union bpf_attr *attr,
5754 			     union bpf_attr __user *uattr)
5755 {
5756 	pid_t pid = attr->task_fd_query.pid;
5757 	u32 fd = attr->task_fd_query.fd;
5758 	const struct perf_event *event;
5759 	struct task_struct *task;
5760 	struct file *file;
5761 	int err;
5762 
5763 	if (CHECK_ATTR(BPF_TASK_FD_QUERY))
5764 		return -EINVAL;
5765 
5766 	if (!capable(CAP_SYS_ADMIN))
5767 		return -EPERM;
5768 
5769 	if (attr->task_fd_query.flags != 0)
5770 		return -EINVAL;
5771 
5772 	rcu_read_lock();
5773 	task = get_pid_task(find_vpid(pid), PIDTYPE_PID);
5774 	rcu_read_unlock();
5775 	if (!task)
5776 		return -ENOENT;
5777 
5778 	err = 0;
5779 	file = fget_task(task, fd);
5780 	put_task_struct(task);
5781 	if (!file)
5782 		return -EBADF;
5783 
5784 	if (file->f_op == &bpf_link_fops || file->f_op == &bpf_link_fops_poll) {
5785 		struct bpf_link *link = file->private_data;
5786 
5787 		if (link->ops == &bpf_raw_tp_link_lops) {
5788 			struct bpf_raw_tp_link *raw_tp =
5789 				container_of(link, struct bpf_raw_tp_link, link);
5790 			struct bpf_raw_event_map *btp = raw_tp->btp;
5791 
5792 			err = bpf_task_fd_query_copy(attr, uattr,
5793 						     raw_tp->link.prog->aux->id,
5794 						     BPF_FD_TYPE_RAW_TRACEPOINT,
5795 						     btp->tp->name, 0, 0);
5796 			goto put_file;
5797 		}
5798 		goto out_not_supp;
5799 	}
5800 
5801 	event = perf_get_event(file);
5802 	if (!IS_ERR(event)) {
5803 		u64 probe_offset, probe_addr;
5804 		u32 prog_id, fd_type;
5805 		const char *buf;
5806 
5807 		err = bpf_get_perf_event_info(event, &prog_id, &fd_type,
5808 					      &buf, &probe_offset,
5809 					      &probe_addr, NULL);
5810 		if (!err) {
5811 			err = bpf_task_fd_query_copy(attr, uattr, prog_id,
5812 						     fd_type, buf,
5813 						     probe_offset,
5814 						     probe_addr);
5815 			kfree_const(buf);
5816 		}
5817 		goto put_file;
5818 	}
5819 
5820 out_not_supp:
5821 	err = -ENOTSUPP;
5822 put_file:
5823 	fput(file);
5824 	return err;
5825 }
5826 
5827 #define BPF_MAP_BATCH_LAST_FIELD batch.flags
5828 
5829 #define BPF_DO_BATCH(fn, ...)			\
5830 	do {					\
5831 		if (!fn) {			\
5832 			err = -ENOTSUPP;	\
5833 			goto err_put;		\
5834 		}				\
5835 		err = fn(__VA_ARGS__);		\
5836 	} while (0)
5837 
5838 static int bpf_map_do_batch(const union bpf_attr *attr,
5839 			    union bpf_attr __user *uattr,
5840 			    int cmd)
5841 {
5842 	bool has_read  = cmd == BPF_MAP_LOOKUP_BATCH ||
5843 			 cmd == BPF_MAP_LOOKUP_AND_DELETE_BATCH;
5844 	bool has_write = cmd != BPF_MAP_LOOKUP_BATCH;
5845 	struct bpf_map *map;
5846 	int err;
5847 
5848 	if (CHECK_ATTR(BPF_MAP_BATCH))
5849 		return -EINVAL;
5850 
5851 	CLASS(fd, f)(attr->batch.map_fd);
5852 
5853 	map = __bpf_map_get(f);
5854 	if (IS_ERR(map))
5855 		return PTR_ERR(map);
5856 	if (has_write)
5857 		bpf_map_write_active_inc(map);
5858 	if (has_read && !(map_get_sys_perms(map, f) & FMODE_CAN_READ)) {
5859 		err = -EPERM;
5860 		goto err_put;
5861 	}
5862 	if (has_write && !(map_get_sys_perms(map, f) & FMODE_CAN_WRITE)) {
5863 		err = -EPERM;
5864 		goto err_put;
5865 	}
5866 
5867 	if (cmd == BPF_MAP_LOOKUP_BATCH)
5868 		BPF_DO_BATCH(map->ops->map_lookup_batch, map, attr, uattr);
5869 	else if (cmd == BPF_MAP_LOOKUP_AND_DELETE_BATCH)
5870 		BPF_DO_BATCH(map->ops->map_lookup_and_delete_batch, map, attr, uattr);
5871 	else if (cmd == BPF_MAP_UPDATE_BATCH)
5872 		BPF_DO_BATCH(map->ops->map_update_batch, map, fd_file(f), attr, uattr);
5873 	else
5874 		BPF_DO_BATCH(map->ops->map_delete_batch, map, attr, uattr);
5875 err_put:
5876 	if (has_write) {
5877 		maybe_wait_bpf_programs(map);
5878 		bpf_map_write_active_dec(map);
5879 	}
5880 	return err;
5881 }
5882 
5883 #define BPF_LINK_CREATE_LAST_FIELD link_create.uprobe_multi.path_fd
5884 static int link_create(union bpf_attr *attr, bpfptr_t uattr)
5885 {
5886 	struct bpf_prog *prog;
5887 	int ret;
5888 
5889 	if (CHECK_ATTR(BPF_LINK_CREATE))
5890 		return -EINVAL;
5891 
5892 	if (attr->link_create.attach_type == BPF_STRUCT_OPS)
5893 		return bpf_struct_ops_link_create(attr);
5894 
5895 	prog = bpf_prog_get(attr->link_create.prog_fd);
5896 	if (IS_ERR(prog))
5897 		return PTR_ERR(prog);
5898 
5899 	ret = bpf_prog_attach_check_attach_type(prog,
5900 						attr->link_create.attach_type);
5901 	if (ret)
5902 		goto out;
5903 
5904 	switch (prog->type) {
5905 	case BPF_PROG_TYPE_CGROUP_SKB:
5906 	case BPF_PROG_TYPE_CGROUP_SOCK:
5907 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
5908 	case BPF_PROG_TYPE_SOCK_OPS:
5909 	case BPF_PROG_TYPE_CGROUP_DEVICE:
5910 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
5911 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
5912 		ret = cgroup_bpf_link_attach(attr, prog);
5913 		break;
5914 	case BPF_PROG_TYPE_EXT:
5915 		ret = bpf_tracing_prog_attach(prog,
5916 					      attr->link_create.target_fd,
5917 					      attr->link_create.target_btf_id,
5918 					      attr->link_create.tracing.cookie,
5919 					      attr->link_create.attach_type);
5920 		break;
5921 	case BPF_PROG_TYPE_LSM:
5922 	case BPF_PROG_TYPE_TRACING:
5923 		if (attr->link_create.attach_type != prog->expected_attach_type) {
5924 			ret = -EINVAL;
5925 			goto out;
5926 		}
5927 		if (prog->expected_attach_type == BPF_TRACE_RAW_TP)
5928 			ret = bpf_raw_tp_link_attach(prog, NULL, attr->link_create.tracing.cookie,
5929 						     attr->link_create.attach_type);
5930 		else if (prog->expected_attach_type == BPF_TRACE_ITER)
5931 			ret = bpf_iter_link_attach(attr, uattr, prog);
5932 		else if (prog->expected_attach_type == BPF_LSM_CGROUP)
5933 			ret = cgroup_bpf_link_attach(attr, prog);
5934 		else if (is_tracing_multi(prog->expected_attach_type))
5935 			ret = bpf_tracing_multi_attach(prog, attr);
5936 		else
5937 			ret = bpf_tracing_prog_attach(prog,
5938 						      attr->link_create.target_fd,
5939 						      attr->link_create.target_btf_id,
5940 						      attr->link_create.tracing.cookie,
5941 						      attr->link_create.attach_type);
5942 		break;
5943 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
5944 	case BPF_PROG_TYPE_SK_LOOKUP:
5945 		ret = netns_bpf_link_create(attr, prog);
5946 		break;
5947 	case BPF_PROG_TYPE_SK_MSG:
5948 	case BPF_PROG_TYPE_SK_SKB:
5949 		ret = sock_map_link_create(attr, prog);
5950 		break;
5951 #ifdef CONFIG_NET
5952 	case BPF_PROG_TYPE_XDP:
5953 		ret = bpf_xdp_link_attach(attr, prog);
5954 		break;
5955 	case BPF_PROG_TYPE_SCHED_CLS:
5956 		if (attr->link_create.attach_type == BPF_TCX_INGRESS ||
5957 		    attr->link_create.attach_type == BPF_TCX_EGRESS)
5958 			ret = tcx_link_attach(attr, prog);
5959 		else
5960 			ret = netkit_link_attach(attr, prog);
5961 		break;
5962 	case BPF_PROG_TYPE_NETFILTER:
5963 		ret = bpf_nf_link_attach(attr, prog);
5964 		break;
5965 #endif
5966 	case BPF_PROG_TYPE_PERF_EVENT:
5967 	case BPF_PROG_TYPE_TRACEPOINT:
5968 		ret = bpf_perf_link_attach(attr, prog);
5969 		break;
5970 	case BPF_PROG_TYPE_KPROBE:
5971 		if (attr->link_create.attach_type == BPF_PERF_EVENT)
5972 			ret = bpf_perf_link_attach(attr, prog);
5973 		else if (attr->link_create.attach_type == BPF_TRACE_KPROBE_MULTI ||
5974 			 attr->link_create.attach_type == BPF_TRACE_KPROBE_SESSION)
5975 			ret = bpf_kprobe_multi_link_attach(attr, prog);
5976 		else if (attr->link_create.attach_type == BPF_TRACE_UPROBE_MULTI ||
5977 			 attr->link_create.attach_type == BPF_TRACE_UPROBE_SESSION)
5978 			ret = bpf_uprobe_multi_link_attach(attr, prog);
5979 		break;
5980 	default:
5981 		ret = -EINVAL;
5982 	}
5983 
5984 out:
5985 	if (ret < 0)
5986 		bpf_prog_put(prog);
5987 	return ret;
5988 }
5989 
5990 static int link_update_map(struct bpf_link *link, union bpf_attr *attr)
5991 {
5992 	struct bpf_map *new_map, *old_map = NULL;
5993 	int ret;
5994 
5995 	new_map = bpf_map_get(attr->link_update.new_map_fd);
5996 	if (IS_ERR(new_map))
5997 		return PTR_ERR(new_map);
5998 
5999 	if (attr->link_update.flags & BPF_F_REPLACE) {
6000 		old_map = bpf_map_get(attr->link_update.old_map_fd);
6001 		if (IS_ERR(old_map)) {
6002 			ret = PTR_ERR(old_map);
6003 			goto out_put;
6004 		}
6005 	} else if (attr->link_update.old_map_fd) {
6006 		ret = -EINVAL;
6007 		goto out_put;
6008 	}
6009 
6010 	ret = link->ops->update_map(link, new_map, old_map);
6011 
6012 	if (old_map)
6013 		bpf_map_put(old_map);
6014 out_put:
6015 	bpf_map_put(new_map);
6016 	return ret;
6017 }
6018 
6019 #define BPF_LINK_UPDATE_LAST_FIELD link_update.old_prog_fd
6020 
6021 static int link_update(union bpf_attr *attr)
6022 {
6023 	struct bpf_prog *old_prog = NULL, *new_prog;
6024 	struct bpf_link *link;
6025 	u32 flags;
6026 	int ret;
6027 
6028 	if (CHECK_ATTR(BPF_LINK_UPDATE))
6029 		return -EINVAL;
6030 
6031 	flags = attr->link_update.flags;
6032 	if (flags & ~BPF_F_REPLACE)
6033 		return -EINVAL;
6034 
6035 	link = bpf_link_get_from_fd(attr->link_update.link_fd);
6036 	if (IS_ERR(link))
6037 		return PTR_ERR(link);
6038 
6039 	if (link->ops->update_map) {
6040 		ret = link_update_map(link, attr);
6041 		goto out_put_link;
6042 	}
6043 
6044 	new_prog = bpf_prog_get(attr->link_update.new_prog_fd);
6045 	if (IS_ERR(new_prog)) {
6046 		ret = PTR_ERR(new_prog);
6047 		goto out_put_link;
6048 	}
6049 
6050 	if (flags & BPF_F_REPLACE) {
6051 		old_prog = bpf_prog_get(attr->link_update.old_prog_fd);
6052 		if (IS_ERR(old_prog)) {
6053 			ret = PTR_ERR(old_prog);
6054 			old_prog = NULL;
6055 			goto out_put_progs;
6056 		}
6057 	} else if (attr->link_update.old_prog_fd) {
6058 		ret = -EINVAL;
6059 		goto out_put_progs;
6060 	}
6061 
6062 	if (link->ops->update_prog)
6063 		ret = link->ops->update_prog(link, new_prog, old_prog);
6064 	else
6065 		ret = -EINVAL;
6066 
6067 out_put_progs:
6068 	if (old_prog)
6069 		bpf_prog_put(old_prog);
6070 	if (ret)
6071 		bpf_prog_put(new_prog);
6072 out_put_link:
6073 	bpf_link_put_direct(link);
6074 	return ret;
6075 }
6076 
6077 #define BPF_LINK_DETACH_LAST_FIELD link_detach.link_fd
6078 
6079 static int link_detach(union bpf_attr *attr)
6080 {
6081 	struct bpf_link *link;
6082 	int ret;
6083 
6084 	if (CHECK_ATTR(BPF_LINK_DETACH))
6085 		return -EINVAL;
6086 
6087 	link = bpf_link_get_from_fd(attr->link_detach.link_fd);
6088 	if (IS_ERR(link))
6089 		return PTR_ERR(link);
6090 
6091 	if (link->ops->detach)
6092 		ret = link->ops->detach(link);
6093 	else
6094 		ret = -EOPNOTSUPP;
6095 
6096 	bpf_link_put_direct(link);
6097 	return ret;
6098 }
6099 
6100 struct bpf_link *bpf_link_inc_not_zero(struct bpf_link *link)
6101 {
6102 	return atomic64_fetch_add_unless(&link->refcnt, 1, 0) ? link : ERR_PTR(-ENOENT);
6103 }
6104 EXPORT_SYMBOL(bpf_link_inc_not_zero);
6105 
6106 struct bpf_link *bpf_link_by_id(u32 id)
6107 {
6108 	struct bpf_link *link;
6109 
6110 	if (!id)
6111 		return ERR_PTR(-ENOENT);
6112 
6113 	spin_lock_bh(&link_idr_lock);
6114 	/* before link is "settled", ID is 0, pretend it doesn't exist yet */
6115 	link = idr_find(&link_idr, id);
6116 	if (link) {
6117 		if (link->id)
6118 			link = bpf_link_inc_not_zero(link);
6119 		else
6120 			link = ERR_PTR(-EAGAIN);
6121 	} else {
6122 		link = ERR_PTR(-ENOENT);
6123 	}
6124 	spin_unlock_bh(&link_idr_lock);
6125 	return link;
6126 }
6127 
6128 struct bpf_link *bpf_link_get_curr_or_next(u32 *id)
6129 {
6130 	struct bpf_link *link;
6131 
6132 	spin_lock_bh(&link_idr_lock);
6133 again:
6134 	link = idr_get_next(&link_idr, id);
6135 	if (link) {
6136 		if (link->id)
6137 			link = bpf_link_inc_not_zero(link);
6138 		else
6139 			link = ERR_PTR(-EAGAIN);
6140 		if (IS_ERR(link)) {
6141 			(*id)++;
6142 			goto again;
6143 		}
6144 	}
6145 	spin_unlock_bh(&link_idr_lock);
6146 
6147 	return link;
6148 }
6149 
6150 #define BPF_LINK_GET_FD_BY_ID_LAST_FIELD link_id
6151 
6152 static int bpf_link_get_fd_by_id(const union bpf_attr *attr)
6153 {
6154 	struct bpf_link *link;
6155 	u32 id = attr->link_id;
6156 	int fd;
6157 
6158 	if (CHECK_ATTR(BPF_LINK_GET_FD_BY_ID))
6159 		return -EINVAL;
6160 
6161 	if (!capable(CAP_SYS_ADMIN))
6162 		return -EPERM;
6163 
6164 	link = bpf_link_by_id(id);
6165 	if (IS_ERR(link))
6166 		return PTR_ERR(link);
6167 
6168 	fd = bpf_link_new_fd(link);
6169 	if (fd < 0)
6170 		bpf_link_put_direct(link);
6171 
6172 	return fd;
6173 }
6174 
6175 DEFINE_MUTEX(bpf_stats_enabled_mutex);
6176 
6177 static int bpf_stats_release(struct inode *inode, struct file *file)
6178 {
6179 	mutex_lock(&bpf_stats_enabled_mutex);
6180 	static_key_slow_dec(&bpf_stats_enabled_key.key);
6181 	mutex_unlock(&bpf_stats_enabled_mutex);
6182 	return 0;
6183 }
6184 
6185 static const struct file_operations bpf_stats_fops = {
6186 	.release = bpf_stats_release,
6187 };
6188 
6189 static int bpf_enable_runtime_stats(void)
6190 {
6191 	int fd;
6192 
6193 	mutex_lock(&bpf_stats_enabled_mutex);
6194 
6195 	/* Set a very high limit to avoid overflow */
6196 	if (static_key_count(&bpf_stats_enabled_key.key) > INT_MAX / 2) {
6197 		mutex_unlock(&bpf_stats_enabled_mutex);
6198 		return -EBUSY;
6199 	}
6200 
6201 	fd = anon_inode_getfd("bpf-stats", &bpf_stats_fops, NULL, O_CLOEXEC);
6202 	if (fd >= 0)
6203 		static_key_slow_inc(&bpf_stats_enabled_key.key);
6204 
6205 	mutex_unlock(&bpf_stats_enabled_mutex);
6206 	return fd;
6207 }
6208 
6209 #define BPF_ENABLE_STATS_LAST_FIELD enable_stats.type
6210 
6211 static int bpf_enable_stats(union bpf_attr *attr)
6212 {
6213 
6214 	if (CHECK_ATTR(BPF_ENABLE_STATS))
6215 		return -EINVAL;
6216 
6217 	if (!capable(CAP_SYS_ADMIN))
6218 		return -EPERM;
6219 
6220 	switch (attr->enable_stats.type) {
6221 	case BPF_STATS_RUN_TIME:
6222 		return bpf_enable_runtime_stats();
6223 	default:
6224 		break;
6225 	}
6226 	return -EINVAL;
6227 }
6228 
6229 #define BPF_ITER_CREATE_LAST_FIELD iter_create.flags
6230 
6231 static int bpf_iter_create(union bpf_attr *attr)
6232 {
6233 	struct bpf_link *link;
6234 	int err;
6235 
6236 	if (CHECK_ATTR(BPF_ITER_CREATE))
6237 		return -EINVAL;
6238 
6239 	if (attr->iter_create.flags)
6240 		return -EINVAL;
6241 
6242 	link = bpf_link_get_from_fd(attr->iter_create.link_fd);
6243 	if (IS_ERR(link))
6244 		return PTR_ERR(link);
6245 
6246 	err = bpf_iter_new_fd(link);
6247 	bpf_link_put_direct(link);
6248 
6249 	return err;
6250 }
6251 
6252 #define BPF_PROG_BIND_MAP_LAST_FIELD prog_bind_map.flags
6253 
6254 static int bpf_prog_bind_map(union bpf_attr *attr)
6255 {
6256 	struct bpf_prog *prog;
6257 	struct bpf_map *map;
6258 	struct bpf_map **used_maps_old, **used_maps_new;
6259 	int i, ret = 0;
6260 
6261 	if (CHECK_ATTR(BPF_PROG_BIND_MAP))
6262 		return -EINVAL;
6263 
6264 	if (attr->prog_bind_map.flags)
6265 		return -EINVAL;
6266 
6267 	prog = bpf_prog_get(attr->prog_bind_map.prog_fd);
6268 	if (IS_ERR(prog))
6269 		return PTR_ERR(prog);
6270 
6271 	map = bpf_map_get(attr->prog_bind_map.map_fd);
6272 	if (IS_ERR(map)) {
6273 		ret = PTR_ERR(map);
6274 		goto out_prog_put;
6275 	}
6276 
6277 	mutex_lock(&prog->aux->used_maps_mutex);
6278 
6279 	used_maps_old = prog->aux->used_maps;
6280 
6281 	for (i = 0; i < prog->aux->used_map_cnt; i++)
6282 		if (used_maps_old[i] == map) {
6283 			bpf_map_put(map);
6284 			goto out_unlock;
6285 		}
6286 
6287 	used_maps_new = kmalloc_objs(used_maps_new[0],
6288 				     prog->aux->used_map_cnt + 1);
6289 	if (!used_maps_new) {
6290 		ret = -ENOMEM;
6291 		goto out_unlock;
6292 	}
6293 
6294 	/* The bpf program will not access the bpf map, but for the sake of
6295 	 * simplicity, increase sleepable_refcnt for sleepable program as well.
6296 	 */
6297 	if (bpf_prog_runs_sleepable(prog))
6298 		atomic64_inc(&map->sleepable_refcnt);
6299 	memcpy(used_maps_new, used_maps_old,
6300 	       sizeof(used_maps_old[0]) * prog->aux->used_map_cnt);
6301 	used_maps_new[prog->aux->used_map_cnt] = map;
6302 
6303 	prog->aux->used_map_cnt++;
6304 	prog->aux->used_maps = used_maps_new;
6305 
6306 	kfree(used_maps_old);
6307 
6308 out_unlock:
6309 	mutex_unlock(&prog->aux->used_maps_mutex);
6310 
6311 	if (ret)
6312 		bpf_map_put(map);
6313 out_prog_put:
6314 	bpf_prog_put(prog);
6315 	return ret;
6316 }
6317 
6318 #define BPF_TOKEN_CREATE_LAST_FIELD token_create.bpffs_fd
6319 
6320 static int token_create(union bpf_attr *attr)
6321 {
6322 	if (CHECK_ATTR(BPF_TOKEN_CREATE))
6323 		return -EINVAL;
6324 
6325 	/* no flags are supported yet */
6326 	if (attr->token_create.flags)
6327 		return -EINVAL;
6328 
6329 	return bpf_token_create(attr);
6330 }
6331 
6332 #define BPF_PROG_STREAM_READ_BY_FD_LAST_FIELD prog_stream_read.prog_fd
6333 
6334 static int prog_stream_read(union bpf_attr *attr)
6335 {
6336 	char __user *buf = u64_to_user_ptr(attr->prog_stream_read.stream_buf);
6337 	u32 len = attr->prog_stream_read.stream_buf_len;
6338 	struct bpf_prog *prog;
6339 	int ret;
6340 
6341 	if (CHECK_ATTR(BPF_PROG_STREAM_READ_BY_FD))
6342 		return -EINVAL;
6343 
6344 	prog = bpf_prog_get(attr->prog_stream_read.prog_fd);
6345 	if (IS_ERR(prog))
6346 		return PTR_ERR(prog);
6347 
6348 	ret = bpf_prog_stream_read(prog, attr->prog_stream_read.stream_id, buf, len);
6349 	bpf_prog_put(prog);
6350 
6351 	return ret;
6352 }
6353 
6354 #define BPF_PROG_ASSOC_STRUCT_OPS_LAST_FIELD prog_assoc_struct_ops.flags
6355 
6356 static int prog_assoc_struct_ops(union bpf_attr *attr)
6357 {
6358 	struct bpf_prog *prog;
6359 	struct bpf_map *map;
6360 	int ret;
6361 
6362 	if (CHECK_ATTR(BPF_PROG_ASSOC_STRUCT_OPS))
6363 		return -EINVAL;
6364 
6365 	if (attr->prog_assoc_struct_ops.flags)
6366 		return -EINVAL;
6367 
6368 	prog = bpf_prog_get(attr->prog_assoc_struct_ops.prog_fd);
6369 	if (IS_ERR(prog))
6370 		return PTR_ERR(prog);
6371 
6372 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS) {
6373 		ret = -EINVAL;
6374 		goto put_prog;
6375 	}
6376 
6377 	map = bpf_map_get(attr->prog_assoc_struct_ops.map_fd);
6378 	if (IS_ERR(map)) {
6379 		ret = PTR_ERR(map);
6380 		goto put_prog;
6381 	}
6382 
6383 	if (map->map_type != BPF_MAP_TYPE_STRUCT_OPS) {
6384 		ret = -EINVAL;
6385 		goto put_map;
6386 	}
6387 
6388 	ret = bpf_prog_assoc_struct_ops(prog, map);
6389 
6390 put_map:
6391 	bpf_map_put(map);
6392 put_prog:
6393 	bpf_prog_put(prog);
6394 	return ret;
6395 }
6396 
6397 #define BPF_PROG_STREAM_OPEN_LAST_FIELD prog_stream_open.flags
6398 
6399 static int prog_stream_open(union bpf_attr *attr)
6400 {
6401 	struct bpf_prog *prog;
6402 	u32 flags = attr->prog_stream_open.flags;
6403 	int ret;
6404 
6405 	if (CHECK_ATTR(BPF_PROG_STREAM_OPEN))
6406 		return -EINVAL;
6407 	if (flags & ~BPF_F_STREAM_NONBLOCK)
6408 		return -EINVAL;
6409 
6410 	prog = bpf_prog_get(attr->prog_stream_open.prog_fd);
6411 	if (IS_ERR(prog))
6412 		return PTR_ERR(prog);
6413 
6414 	ret = bpf_prog_stream_new_fd(prog, attr->prog_stream_open.stream_id, flags);
6415 	bpf_prog_put(prog);
6416 	return ret;
6417 }
6418 
6419 static int __sys_bpf(enum bpf_cmd cmd, bpfptr_t uattr, unsigned int size,
6420 		     bpfptr_t uattr_common, unsigned int size_common)
6421 {
6422 	struct bpf_common_attr attr_common;
6423 	u32 offsetof_log_true_size = 0;
6424 	struct bpf_log_attr attr_log;
6425 	union bpf_attr attr;
6426 	int err;
6427 
6428 	err = bpf_check_uarg_tail_zero(uattr, sizeof(attr), size);
6429 	if (err)
6430 		return err;
6431 	size = min_t(u32, size, sizeof(attr));
6432 
6433 	/* copy attributes from user space, may be less than sizeof(bpf_attr) */
6434 	memset(&attr, 0, sizeof(attr));
6435 	if (copy_from_bpfptr(&attr, uattr, size) != 0)
6436 		return -EFAULT;
6437 
6438 	memset(&attr_common, 0, sizeof(attr_common));
6439 	if (cmd & BPF_COMMON_ATTRS) {
6440 		err = bpf_check_uarg_tail_zero(uattr_common,
6441 					       offsetofend(struct bpf_common_attr, log_true_size),
6442 					       size_common);
6443 		if (err)
6444 			return err;
6445 
6446 		cmd &= ~BPF_COMMON_ATTRS;
6447 		size_common = min_t(u32, size_common, sizeof(attr_common));
6448 		if (copy_from_bpfptr(&attr_common, uattr_common, size_common) != 0)
6449 			return -EFAULT;
6450 	} else {
6451 		size_common = 0;
6452 	}
6453 
6454 	err = security_bpf(cmd, &attr, size, uattr.is_kernel);
6455 	if (err < 0)
6456 		return err;
6457 
6458 	switch (cmd) {
6459 	case BPF_MAP_CREATE:
6460 		err = map_create(&attr, uattr, &attr_common, uattr_common, size_common);
6461 		break;
6462 	case BPF_MAP_LOOKUP_ELEM:
6463 		err = map_lookup_elem(&attr);
6464 		break;
6465 	case BPF_MAP_UPDATE_ELEM:
6466 		err = map_update_elem(&attr, uattr);
6467 		break;
6468 	case BPF_MAP_DELETE_ELEM:
6469 		err = map_delete_elem(&attr, uattr);
6470 		break;
6471 	case BPF_MAP_GET_NEXT_KEY:
6472 		err = map_get_next_key(&attr);
6473 		break;
6474 	case BPF_MAP_FREEZE:
6475 		err = map_freeze(&attr);
6476 		break;
6477 	case BPF_PROG_LOAD:
6478 		if (size >= offsetofend(union bpf_attr, log_true_size))
6479 			offsetof_log_true_size = offsetof(union bpf_attr, log_true_size);
6480 		err = bpf_log_attr_init(&attr_log, attr.log_buf, attr.log_size, attr.log_level,
6481 					offsetof_log_true_size, uattr, &attr_common, uattr_common,
6482 					size_common);
6483 		err = err ?: bpf_prog_load(&attr, uattr, &attr_log);
6484 		break;
6485 	case BPF_OBJ_PIN:
6486 		err = bpf_obj_pin(&attr);
6487 		break;
6488 	case BPF_OBJ_GET:
6489 		err = bpf_obj_get(&attr);
6490 		break;
6491 	case BPF_PROG_ATTACH:
6492 		err = bpf_prog_attach(&attr);
6493 		break;
6494 	case BPF_PROG_DETACH:
6495 		err = bpf_prog_detach(&attr);
6496 		break;
6497 	case BPF_PROG_QUERY:
6498 		err = bpf_prog_query(&attr, uattr.user, size);
6499 		break;
6500 	case BPF_PROG_TEST_RUN:
6501 		err = bpf_prog_test_run(&attr, uattr.user);
6502 		break;
6503 	case BPF_PROG_GET_NEXT_ID:
6504 		err = bpf_obj_get_next_id(&attr, uattr.user,
6505 					  &prog_idr, &prog_idr_lock);
6506 		break;
6507 	case BPF_MAP_GET_NEXT_ID:
6508 		err = bpf_obj_get_next_id(&attr, uattr.user,
6509 					  &map_idr, &map_idr_lock);
6510 		break;
6511 	case BPF_BTF_GET_NEXT_ID:
6512 		err = bpf_obj_get_next_id(&attr, uattr.user,
6513 					  &btf_idr, &btf_idr_lock);
6514 		break;
6515 	case BPF_PROG_GET_FD_BY_ID:
6516 		err = bpf_prog_get_fd_by_id(&attr);
6517 		break;
6518 	case BPF_MAP_GET_FD_BY_ID:
6519 		err = bpf_map_get_fd_by_id(&attr);
6520 		break;
6521 	case BPF_OBJ_GET_INFO_BY_FD:
6522 		err = bpf_obj_get_info_by_fd(&attr, uattr.user);
6523 		break;
6524 	case BPF_RAW_TRACEPOINT_OPEN:
6525 		err = bpf_raw_tracepoint_open(&attr);
6526 		break;
6527 	case BPF_BTF_LOAD:
6528 		if (size >= offsetofend(union bpf_attr, btf_log_true_size))
6529 			offsetof_log_true_size = offsetof(union bpf_attr, btf_log_true_size);
6530 		err = bpf_log_attr_init(&attr_log, attr.btf_log_buf, attr.btf_log_size,
6531 					attr.btf_log_level, offsetof_log_true_size, uattr,
6532 					&attr_common, uattr_common, size_common);
6533 		err = err ?: bpf_btf_load(&attr, uattr, &attr_log);
6534 		break;
6535 	case BPF_BTF_GET_FD_BY_ID:
6536 		err = bpf_btf_get_fd_by_id(&attr);
6537 		break;
6538 	case BPF_TASK_FD_QUERY:
6539 		err = bpf_task_fd_query(&attr, uattr.user);
6540 		break;
6541 	case BPF_MAP_LOOKUP_AND_DELETE_ELEM:
6542 		err = map_lookup_and_delete_elem(&attr);
6543 		break;
6544 	case BPF_MAP_LOOKUP_BATCH:
6545 		err = bpf_map_do_batch(&attr, uattr.user, BPF_MAP_LOOKUP_BATCH);
6546 		break;
6547 	case BPF_MAP_LOOKUP_AND_DELETE_BATCH:
6548 		err = bpf_map_do_batch(&attr, uattr.user,
6549 				       BPF_MAP_LOOKUP_AND_DELETE_BATCH);
6550 		break;
6551 	case BPF_MAP_UPDATE_BATCH:
6552 		err = bpf_map_do_batch(&attr, uattr.user, BPF_MAP_UPDATE_BATCH);
6553 		break;
6554 	case BPF_MAP_DELETE_BATCH:
6555 		err = bpf_map_do_batch(&attr, uattr.user, BPF_MAP_DELETE_BATCH);
6556 		break;
6557 	case BPF_LINK_CREATE:
6558 		err = link_create(&attr, uattr);
6559 		break;
6560 	case BPF_LINK_UPDATE:
6561 		err = link_update(&attr);
6562 		break;
6563 	case BPF_LINK_GET_FD_BY_ID:
6564 		err = bpf_link_get_fd_by_id(&attr);
6565 		break;
6566 	case BPF_LINK_GET_NEXT_ID:
6567 		err = bpf_obj_get_next_id(&attr, uattr.user,
6568 					  &link_idr, &link_idr_lock);
6569 		break;
6570 	case BPF_ENABLE_STATS:
6571 		err = bpf_enable_stats(&attr);
6572 		break;
6573 	case BPF_ITER_CREATE:
6574 		err = bpf_iter_create(&attr);
6575 		break;
6576 	case BPF_LINK_DETACH:
6577 		err = link_detach(&attr);
6578 		break;
6579 	case BPF_PROG_BIND_MAP:
6580 		err = bpf_prog_bind_map(&attr);
6581 		break;
6582 	case BPF_TOKEN_CREATE:
6583 		err = token_create(&attr);
6584 		break;
6585 	case BPF_PROG_STREAM_READ_BY_FD:
6586 		err = prog_stream_read(&attr);
6587 		break;
6588 	case BPF_PROG_ASSOC_STRUCT_OPS:
6589 		err = prog_assoc_struct_ops(&attr);
6590 		break;
6591 	case BPF_PROG_STREAM_OPEN:
6592 		err = prog_stream_open(&attr);
6593 		break;
6594 	default:
6595 		err = -EINVAL;
6596 		break;
6597 	}
6598 
6599 	return err;
6600 }
6601 
6602 SYSCALL_DEFINE5(bpf, int, cmd, union bpf_attr __user *, uattr, unsigned int, size,
6603 		struct bpf_common_attr __user *, uattr_common, unsigned int, size_common)
6604 {
6605 	return __sys_bpf(cmd, USER_BPFPTR(uattr), size, USER_BPFPTR(uattr_common), size_common);
6606 }
6607 
6608 static bool syscall_prog_is_valid_access(int off, int size,
6609 					 enum bpf_access_type type,
6610 					 const struct bpf_prog *prog,
6611 					 struct bpf_insn_access_aux *info)
6612 {
6613 	if (off < 0 || off >= U16_MAX)
6614 		return false;
6615 	/* No alignment requirements for syscall ctx accesses. */
6616 	return true;
6617 }
6618 
6619 BPF_CALL_3(bpf_sys_bpf, int, cmd, union bpf_attr *, attr, u32, attr_size)
6620 {
6621 	if (bpf_in_async_cb())
6622 		return -EPERM;
6623 
6624 	switch (cmd) {
6625 	case BPF_MAP_CREATE:
6626 	case BPF_MAP_DELETE_ELEM:
6627 	case BPF_MAP_UPDATE_ELEM:
6628 	case BPF_MAP_FREEZE:
6629 	case BPF_MAP_GET_FD_BY_ID:
6630 	case BPF_PROG_LOAD:
6631 	case BPF_BTF_LOAD:
6632 	case BPF_LINK_CREATE:
6633 	case BPF_RAW_TRACEPOINT_OPEN:
6634 		break;
6635 	default:
6636 		return -EINVAL;
6637 	}
6638 	return __sys_bpf(cmd, KERNEL_BPFPTR(attr), attr_size, KERNEL_BPFPTR(NULL), 0);
6639 }
6640 
6641 /* To shut up -Wmissing-prototypes.
6642  * This function is used by the kernel light skeleton
6643  * to load bpf programs when modules are loaded or during kernel boot.
6644  * See tools/lib/bpf/skel_internal.h
6645  */
6646 int kern_sys_bpf(int cmd, union bpf_attr *attr, unsigned int size);
6647 
6648 int kern_sys_bpf(int cmd, union bpf_attr *attr, unsigned int size)
6649 {
6650 	struct bpf_prog * __maybe_unused prog;
6651 	struct bpf_tramp_run_ctx __maybe_unused run_ctx;
6652 
6653 	switch (cmd) {
6654 #ifdef CONFIG_BPF_JIT /* __bpf_prog_enter_sleepable used by trampoline and JIT */
6655 	case BPF_PROG_TEST_RUN:
6656 		if (attr->test.data_in || attr->test.data_out ||
6657 		    attr->test.ctx_out || attr->test.duration ||
6658 		    attr->test.repeat || attr->test.flags)
6659 			return -EINVAL;
6660 
6661 		prog = bpf_prog_get_type(attr->test.prog_fd, BPF_PROG_TYPE_SYSCALL);
6662 		if (IS_ERR(prog))
6663 			return PTR_ERR(prog);
6664 
6665 		if (attr->test.ctx_size_in < prog->aux->max_ctx_offset ||
6666 		    attr->test.ctx_size_in > U16_MAX) {
6667 			bpf_prog_put(prog);
6668 			return -EINVAL;
6669 		}
6670 
6671 		run_ctx.bpf_cookie = 0;
6672 		if (!__bpf_prog_enter_sleepable_recur(prog, &run_ctx)) {
6673 			/* recursion detected */
6674 			__bpf_prog_exit_sleepable_recur(prog, 0, &run_ctx);
6675 			bpf_prog_put(prog);
6676 			return -EBUSY;
6677 		}
6678 		attr->test.retval = bpf_prog_run(prog, (void *) (long) attr->test.ctx_in);
6679 		__bpf_prog_exit_sleepable_recur(prog, 0 /* bpf_prog_run does runtime stats */,
6680 						&run_ctx);
6681 		bpf_prog_put(prog);
6682 		return 0;
6683 #endif
6684 	default:
6685 		return ____bpf_sys_bpf(cmd, attr, size);
6686 	}
6687 }
6688 EXPORT_SYMBOL_NS(kern_sys_bpf, "BPF_INTERNAL");
6689 
6690 static const struct bpf_func_proto bpf_sys_bpf_proto = {
6691 	.func		= bpf_sys_bpf,
6692 	.gpl_only	= false,
6693 	.might_sleep	= true,
6694 	.ret_type	= RET_INTEGER,
6695 	.arg1_type	= ARG_ANYTHING,
6696 	.arg2_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
6697 	.arg3_type	= ARG_MEM_SIZE,
6698 };
6699 
6700 const struct bpf_func_proto * __weak
6701 tracing_prog_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
6702 {
6703 	return bpf_base_func_proto(func_id, prog);
6704 }
6705 
6706 BPF_CALL_1(bpf_sys_close, u32, fd)
6707 {
6708 	/* When bpf program calls this helper there should not be
6709 	 * an fdget() without matching completed fdput().
6710 	 * This helper is allowed in the following callchain only:
6711 	 * sys_bpf->prog_test_run->bpf_prog->bpf_sys_close
6712 	 */
6713 	return bpf_in_async_cb() ? -EPERM : close_fd(fd);
6714 }
6715 
6716 static const struct bpf_func_proto bpf_sys_close_proto = {
6717 	.func		= bpf_sys_close,
6718 	.gpl_only	= false,
6719 	.might_sleep	= true,
6720 	.ret_type	= RET_INTEGER,
6721 	.arg1_type	= ARG_ANYTHING,
6722 };
6723 
6724 BPF_CALL_4(bpf_kallsyms_lookup_name, const char *, name, int, name_sz, int, flags, u64 *, res)
6725 {
6726 	*res = 0;
6727 	if (flags)
6728 		return -EINVAL;
6729 
6730 	if (name_sz <= 1 || name[name_sz - 1])
6731 		return -EINVAL;
6732 
6733 	if (bpf_in_async_cb() || !bpf_dump_raw_ok(current_cred()))
6734 		return -EPERM;
6735 
6736 	*res = kallsyms_lookup_name(name);
6737 	return *res ? 0 : -ENOENT;
6738 }
6739 
6740 static const struct bpf_func_proto bpf_kallsyms_lookup_name_proto = {
6741 	.func		= bpf_kallsyms_lookup_name,
6742 	.gpl_only	= false,
6743 	.ret_type	= RET_INTEGER,
6744 	.arg1_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
6745 	.arg2_type	= ARG_MEM_SIZE_OR_ZERO,
6746 	.arg3_type	= ARG_ANYTHING,
6747 	.arg4_type	= ARG_PTR_TO_FIXED_SIZE_MEM | MEM_UNINIT | MEM_WRITE | MEM_ALIGNED,
6748 	.arg4_size	= sizeof(u64),
6749 };
6750 
6751 static const struct bpf_func_proto *
6752 syscall_prog_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
6753 {
6754 	if (!bpf_token_capable(prog->aux->token, CAP_PERFMON))
6755 		return bpf_base_func_proto(func_id, prog);
6756 
6757 	switch (func_id) {
6758 	case BPF_FUNC_sys_bpf:
6759 		return &bpf_sys_bpf_proto;
6760 	case BPF_FUNC_btf_find_by_name_kind:
6761 		return &bpf_btf_find_by_name_kind_proto;
6762 	case BPF_FUNC_sys_close:
6763 		return &bpf_sys_close_proto;
6764 	case BPF_FUNC_kallsyms_lookup_name:
6765 		return &bpf_kallsyms_lookup_name_proto;
6766 	default:
6767 		return tracing_prog_func_proto(func_id, prog);
6768 	}
6769 }
6770 
6771 const struct bpf_verifier_ops bpf_syscall_verifier_ops = {
6772 	.get_func_proto  = syscall_prog_func_proto,
6773 	.is_valid_access = syscall_prog_is_valid_access,
6774 };
6775 
6776 const struct bpf_prog_ops bpf_syscall_prog_ops = {
6777 	.test_run = bpf_prog_test_run_syscall,
6778 };
6779 
6780 #ifdef CONFIG_SYSCTL
6781 static int bpf_stats_handler(const struct ctl_table *table, int write,
6782 			     void *buffer, size_t *lenp, loff_t *ppos)
6783 {
6784 	struct static_key *key = (struct static_key *)table->data;
6785 	static int saved_val;
6786 	int val, ret;
6787 	struct ctl_table tmp = {
6788 		.data   = &val,
6789 		.maxlen = sizeof(val),
6790 		.mode   = table->mode,
6791 		.extra1 = SYSCTL_ZERO,
6792 		.extra2 = SYSCTL_ONE,
6793 	};
6794 
6795 	if (write && !capable(CAP_SYS_ADMIN))
6796 		return -EPERM;
6797 
6798 	mutex_lock(&bpf_stats_enabled_mutex);
6799 	val = saved_val;
6800 	ret = proc_dointvec_minmax(&tmp, write, buffer, lenp, ppos);
6801 	if (write && !ret && val != saved_val) {
6802 		if (val)
6803 			static_key_slow_inc(key);
6804 		else
6805 			static_key_slow_dec(key);
6806 		saved_val = val;
6807 	}
6808 	mutex_unlock(&bpf_stats_enabled_mutex);
6809 	return ret;
6810 }
6811 
6812 void __weak unpriv_ebpf_notify(int new_state)
6813 {
6814 }
6815 
6816 static int bpf_unpriv_handler(const struct ctl_table *table, int write,
6817 			      void *buffer, size_t *lenp, loff_t *ppos)
6818 {
6819 	int ret, unpriv_enable = *(int *)table->data;
6820 	bool locked_state = unpriv_enable == 1;
6821 	struct ctl_table tmp = *table;
6822 
6823 	if (write && !capable(CAP_SYS_ADMIN))
6824 		return -EPERM;
6825 
6826 	tmp.data = &unpriv_enable;
6827 	ret = proc_dointvec_minmax(&tmp, write, buffer, lenp, ppos);
6828 	if (write && !ret) {
6829 		if (locked_state && unpriv_enable != 1)
6830 			return -EPERM;
6831 		*(int *)table->data = unpriv_enable;
6832 	}
6833 
6834 	if (write)
6835 		unpriv_ebpf_notify(unpriv_enable);
6836 
6837 	return ret;
6838 }
6839 
6840 static const struct ctl_table bpf_syscall_table[] = {
6841 	{
6842 		.procname	= "unprivileged_bpf_disabled",
6843 		.data		= &sysctl_unprivileged_bpf_disabled,
6844 		.maxlen		= sizeof(sysctl_unprivileged_bpf_disabled),
6845 		.mode		= 0644,
6846 		.proc_handler	= bpf_unpriv_handler,
6847 		.extra1		= SYSCTL_ZERO,
6848 		.extra2		= SYSCTL_TWO,
6849 	},
6850 	{
6851 		.procname	= "bpf_stats_enabled",
6852 		.data		= &bpf_stats_enabled_key.key,
6853 		.mode		= 0644,
6854 		.proc_handler	= bpf_stats_handler,
6855 	},
6856 };
6857 
6858 static int __init bpf_syscall_sysctl_init(void)
6859 {
6860 	register_sysctl_init("kernel", bpf_syscall_table);
6861 	return 0;
6862 }
6863 late_initcall(bpf_syscall_sysctl_init);
6864 #endif /* CONFIG_SYSCTL */
6865