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