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