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