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