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