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