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