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