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