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