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