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