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