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