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