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