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