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