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