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