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