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