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