1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
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>
20 #include <linux/license.h>
21 #include <linux/filter.h>
22 #include <linux/kernel.h>
23 #include <linux/idr.h>
24 #include <linux/cred.h>
25 #include <linux/timekeeping.h>
26 #include <linux/ctype.h>
27 #include <linux/nospec.h>
28 #include <linux/audit.h>
29 #include <uapi/linux/btf.h>
30 #include <linux/pgtable.h>
31 #include <linux/bpf_lsm.h>
32 #include <linux/poll.h>
33 #include <linux/sort.h>
34 #include <linux/bpf-netns.h>
35 #include <linux/rcupdate_trace.h>
36 #include <linux/memcontrol.h>
37 #include <linux/trace_events.h>
38 #include <net/netfilter/nf_bpf_link.h>
40 #define IS_FD_ARRAY(map) ((map)->map_type == BPF_MAP_TYPE_PERF_EVENT_ARRAY || \
41 (map)->map_type == BPF_MAP_TYPE_CGROUP_ARRAY || \
42 (map)->map_type == BPF_MAP_TYPE_ARRAY_OF_MAPS)
43 #define IS_FD_PROG_ARRAY(map) ((map)->map_type == BPF_MAP_TYPE_PROG_ARRAY)
44 #define IS_FD_HASH(map) ((map)->map_type == BPF_MAP_TYPE_HASH_OF_MAPS)
45 #define IS_FD_MAP(map) (IS_FD_ARRAY(map) || IS_FD_PROG_ARRAY(map) || \
48 #define BPF_OBJ_FLAG_MASK (BPF_F_RDONLY | BPF_F_WRONLY)
50 DEFINE_PER_CPU(int, bpf_prog_active);
51 static DEFINE_IDR(prog_idr);
52 static DEFINE_SPINLOCK(prog_idr_lock);
53 static DEFINE_IDR(map_idr);
54 static DEFINE_SPINLOCK(map_idr_lock);
55 static DEFINE_IDR(link_idr);
56 static DEFINE_SPINLOCK(link_idr_lock);
58 int sysctl_unprivileged_bpf_disabled __read_mostly =
59 IS_BUILTIN(CONFIG_BPF_UNPRIV_DEFAULT_OFF) ? 2 : 0;
61 static const struct bpf_map_ops * const bpf_map_types[] = {
62 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type)
63 #define BPF_MAP_TYPE(_id, _ops) \
65 #define BPF_LINK_TYPE(_id, _name)
66 #include <linux/bpf_types.h>
73 * If we're handed a bigger struct than we know of, ensure all the unknown bits
74 * are 0 - i.e. new user-space does not rely on any kernel feature extensions
75 * we don't know about yet.
77 * There is a ToCToU between this function call and the following
78 * copy_from_user() call. However, this is not a concern since this function is
79 * meant to be a future-proofing of bits.
81 int bpf_check_uarg_tail_zero(bpfptr_t uaddr,
87 if (unlikely(actual_size > PAGE_SIZE)) /* silly large */
90 if (actual_size <= expected_size)
94 res = memchr_inv(uaddr.kernel + expected_size, 0,
95 actual_size - expected_size) == NULL;
97 res = check_zeroed_user(uaddr.user + expected_size,
98 actual_size - expected_size);
101 return res ? 0 : -E2BIG;
104 const struct bpf_map_ops bpf_map_offload_ops = {
105 .map_meta_equal = bpf_map_meta_equal,
106 .map_alloc = bpf_map_offload_map_alloc,
107 .map_free = bpf_map_offload_map_free,
108 .map_check_btf = map_check_no_btf,
109 .map_mem_usage = bpf_map_offload_map_mem_usage,
112 static void bpf_map_write_active_inc(struct bpf_map *map)
114 atomic64_inc(&map->writecnt);
117 static void bpf_map_write_active_dec(struct bpf_map *map)
119 atomic64_dec(&map->writecnt);
122 bool bpf_map_write_active(const struct bpf_map *map)
124 return atomic64_read(&map->writecnt) != 0;
127 static u32 bpf_map_value_size(const struct bpf_map *map)
129 if (map->map_type == BPF_MAP_TYPE_PERCPU_HASH ||
130 map->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH ||
131 map->map_type == BPF_MAP_TYPE_PERCPU_ARRAY ||
132 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
133 return round_up(map->value_size, 8) * num_possible_cpus();
134 else if (IS_FD_MAP(map))
137 return map->value_size;
140 static void maybe_wait_bpf_programs(struct bpf_map *map)
142 /* Wait for any running BPF programs to complete so that
143 * userspace, when we return to it, knows that all programs
144 * that could be running use the new map value.
146 if (map->map_type == BPF_MAP_TYPE_HASH_OF_MAPS ||
147 map->map_type == BPF_MAP_TYPE_ARRAY_OF_MAPS)
151 static int bpf_map_update_value(struct bpf_map *map, struct file *map_file,
152 void *key, void *value, __u64 flags)
156 /* Need to create a kthread, thus must support schedule */
157 if (bpf_map_is_offloaded(map)) {
158 return bpf_map_offload_update_elem(map, key, value, flags);
159 } else if (map->map_type == BPF_MAP_TYPE_CPUMAP ||
160 map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
161 return map->ops->map_update_elem(map, key, value, flags);
162 } else if (map->map_type == BPF_MAP_TYPE_SOCKHASH ||
163 map->map_type == BPF_MAP_TYPE_SOCKMAP) {
164 return sock_map_update_elem_sys(map, key, value, flags);
165 } else if (IS_FD_PROG_ARRAY(map)) {
166 return bpf_fd_array_map_update_elem(map, map_file, key, value,
170 bpf_disable_instrumentation();
171 if (map->map_type == BPF_MAP_TYPE_PERCPU_HASH ||
172 map->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH) {
173 err = bpf_percpu_hash_update(map, key, value, flags);
174 } else if (map->map_type == BPF_MAP_TYPE_PERCPU_ARRAY) {
175 err = bpf_percpu_array_update(map, key, value, flags);
176 } else if (map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE) {
177 err = bpf_percpu_cgroup_storage_update(map, key, value,
179 } else if (IS_FD_ARRAY(map)) {
181 err = bpf_fd_array_map_update_elem(map, map_file, key, value,
184 } else if (map->map_type == BPF_MAP_TYPE_HASH_OF_MAPS) {
186 err = bpf_fd_htab_map_update_elem(map, map_file, key, value,
189 } else if (map->map_type == BPF_MAP_TYPE_REUSEPORT_SOCKARRAY) {
190 /* rcu_read_lock() is not needed */
191 err = bpf_fd_reuseport_array_update_elem(map, key, value,
193 } else if (map->map_type == BPF_MAP_TYPE_QUEUE ||
194 map->map_type == BPF_MAP_TYPE_STACK ||
195 map->map_type == BPF_MAP_TYPE_BLOOM_FILTER) {
196 err = map->ops->map_push_elem(map, value, flags);
199 err = map->ops->map_update_elem(map, key, value, flags);
202 bpf_enable_instrumentation();
203 maybe_wait_bpf_programs(map);
208 static int bpf_map_copy_value(struct bpf_map *map, void *key, void *value,
214 if (bpf_map_is_offloaded(map))
215 return bpf_map_offload_lookup_elem(map, key, value);
217 bpf_disable_instrumentation();
218 if (map->map_type == BPF_MAP_TYPE_PERCPU_HASH ||
219 map->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH) {
220 err = bpf_percpu_hash_copy(map, key, value);
221 } else if (map->map_type == BPF_MAP_TYPE_PERCPU_ARRAY) {
222 err = bpf_percpu_array_copy(map, key, value);
223 } else if (map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE) {
224 err = bpf_percpu_cgroup_storage_copy(map, key, value);
225 } else if (map->map_type == BPF_MAP_TYPE_STACK_TRACE) {
226 err = bpf_stackmap_copy(map, key, value);
227 } else if (IS_FD_ARRAY(map) || IS_FD_PROG_ARRAY(map)) {
228 err = bpf_fd_array_map_lookup_elem(map, key, value);
229 } else if (IS_FD_HASH(map)) {
230 err = bpf_fd_htab_map_lookup_elem(map, key, value);
231 } else if (map->map_type == BPF_MAP_TYPE_REUSEPORT_SOCKARRAY) {
232 err = bpf_fd_reuseport_array_lookup_elem(map, key, value);
233 } else if (map->map_type == BPF_MAP_TYPE_QUEUE ||
234 map->map_type == BPF_MAP_TYPE_STACK ||
235 map->map_type == BPF_MAP_TYPE_BLOOM_FILTER) {
236 err = map->ops->map_peek_elem(map, value);
237 } else if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
238 /* struct_ops map requires directly updating "value" */
239 err = bpf_struct_ops_map_sys_lookup_elem(map, key, value);
242 if (map->ops->map_lookup_elem_sys_only)
243 ptr = map->ops->map_lookup_elem_sys_only(map, key);
245 ptr = map->ops->map_lookup_elem(map, key);
252 if (flags & BPF_F_LOCK)
253 /* lock 'ptr' and copy everything but lock */
254 copy_map_value_locked(map, value, ptr, true);
256 copy_map_value(map, value, ptr);
257 /* mask lock and timer, since value wasn't zero inited */
258 check_and_init_map_value(map, value);
263 bpf_enable_instrumentation();
264 maybe_wait_bpf_programs(map);
269 /* Please, do not use this function outside from the map creation path
270 * (e.g. in map update path) without taking care of setting the active
271 * memory cgroup (see at bpf_map_kmalloc_node() for example).
273 static void *__bpf_map_area_alloc(u64 size, int numa_node, bool mmapable)
275 /* We really just want to fail instead of triggering OOM killer
276 * under memory pressure, therefore we set __GFP_NORETRY to kmalloc,
277 * which is used for lower order allocation requests.
279 * It has been observed that higher order allocation requests done by
280 * vmalloc with __GFP_NORETRY being set might fail due to not trying
281 * to reclaim memory from the page cache, thus we set
282 * __GFP_RETRY_MAYFAIL to avoid such situations.
285 gfp_t gfp = bpf_memcg_flags(__GFP_NOWARN | __GFP_ZERO);
286 unsigned int flags = 0;
287 unsigned long align = 1;
290 if (size >= SIZE_MAX)
293 /* kmalloc()'ed memory can't be mmap()'ed */
295 BUG_ON(!PAGE_ALIGNED(size));
298 } else if (size <= (PAGE_SIZE << PAGE_ALLOC_COSTLY_ORDER)) {
299 area = kmalloc_node(size, gfp | GFP_USER | __GFP_NORETRY,
305 return __vmalloc_node_range(size, align, VMALLOC_START, VMALLOC_END,
306 gfp | GFP_KERNEL | __GFP_RETRY_MAYFAIL, PAGE_KERNEL,
307 flags, numa_node, __builtin_return_address(0));
310 void *bpf_map_area_alloc(u64 size, int numa_node)
312 return __bpf_map_area_alloc(size, numa_node, false);
315 void *bpf_map_area_mmapable_alloc(u64 size, int numa_node)
317 return __bpf_map_area_alloc(size, numa_node, true);
320 void bpf_map_area_free(void *area)
325 static u32 bpf_map_flags_retain_permanent(u32 flags)
327 /* Some map creation flags are not tied to the map object but
328 * rather to the map fd instead, so they have no meaning upon
329 * map object inspection since multiple file descriptors with
330 * different (access) properties can exist here. Thus, given
331 * this has zero meaning for the map itself, lets clear these
334 return flags & ~(BPF_F_RDONLY | BPF_F_WRONLY);
337 void bpf_map_init_from_attr(struct bpf_map *map, union bpf_attr *attr)
339 map->map_type = attr->map_type;
340 map->key_size = attr->key_size;
341 map->value_size = attr->value_size;
342 map->max_entries = attr->max_entries;
343 map->map_flags = bpf_map_flags_retain_permanent(attr->map_flags);
344 map->numa_node = bpf_map_attr_numa_node(attr);
345 map->map_extra = attr->map_extra;
348 static int bpf_map_alloc_id(struct bpf_map *map)
352 idr_preload(GFP_KERNEL);
353 spin_lock_bh(&map_idr_lock);
354 id = idr_alloc_cyclic(&map_idr, map, 1, INT_MAX, GFP_ATOMIC);
357 spin_unlock_bh(&map_idr_lock);
360 if (WARN_ON_ONCE(!id))
363 return id > 0 ? 0 : id;
366 void bpf_map_free_id(struct bpf_map *map)
370 /* Offloaded maps are removed from the IDR store when their device
371 * disappears - even if someone holds an fd to them they are unusable,
372 * the memory is gone, all ops will fail; they are simply waiting for
373 * refcnt to drop to be freed.
378 spin_lock_irqsave(&map_idr_lock, flags);
380 idr_remove(&map_idr, map->id);
383 spin_unlock_irqrestore(&map_idr_lock, flags);
386 #ifdef CONFIG_MEMCG_KMEM
387 static void bpf_map_save_memcg(struct bpf_map *map)
389 /* Currently if a map is created by a process belonging to the root
390 * memory cgroup, get_obj_cgroup_from_current() will return NULL.
391 * So we have to check map->objcg for being NULL each time it's
394 if (memcg_bpf_enabled())
395 map->objcg = get_obj_cgroup_from_current();
398 static void bpf_map_release_memcg(struct bpf_map *map)
401 obj_cgroup_put(map->objcg);
404 static struct mem_cgroup *bpf_map_get_memcg(const struct bpf_map *map)
407 return get_mem_cgroup_from_objcg(map->objcg);
409 return root_mem_cgroup;
412 void *bpf_map_kmalloc_node(const struct bpf_map *map, size_t size, gfp_t flags,
415 struct mem_cgroup *memcg, *old_memcg;
418 memcg = bpf_map_get_memcg(map);
419 old_memcg = set_active_memcg(memcg);
420 ptr = kmalloc_node(size, flags | __GFP_ACCOUNT, node);
421 set_active_memcg(old_memcg);
422 mem_cgroup_put(memcg);
427 void *bpf_map_kzalloc(const struct bpf_map *map, size_t size, gfp_t flags)
429 struct mem_cgroup *memcg, *old_memcg;
432 memcg = bpf_map_get_memcg(map);
433 old_memcg = set_active_memcg(memcg);
434 ptr = kzalloc(size, flags | __GFP_ACCOUNT);
435 set_active_memcg(old_memcg);
436 mem_cgroup_put(memcg);
441 void *bpf_map_kvcalloc(struct bpf_map *map, size_t n, size_t size,
444 struct mem_cgroup *memcg, *old_memcg;
447 memcg = bpf_map_get_memcg(map);
448 old_memcg = set_active_memcg(memcg);
449 ptr = kvcalloc(n, size, flags | __GFP_ACCOUNT);
450 set_active_memcg(old_memcg);
451 mem_cgroup_put(memcg);
456 void __percpu *bpf_map_alloc_percpu(const struct bpf_map *map, size_t size,
457 size_t align, gfp_t flags)
459 struct mem_cgroup *memcg, *old_memcg;
462 memcg = bpf_map_get_memcg(map);
463 old_memcg = set_active_memcg(memcg);
464 ptr = __alloc_percpu_gfp(size, align, flags | __GFP_ACCOUNT);
465 set_active_memcg(old_memcg);
466 mem_cgroup_put(memcg);
472 static void bpf_map_save_memcg(struct bpf_map *map)
476 static void bpf_map_release_memcg(struct bpf_map *map)
481 static int btf_field_cmp(const void *a, const void *b)
483 const struct btf_field *f1 = a, *f2 = b;
485 if (f1->offset < f2->offset)
487 else if (f1->offset > f2->offset)
492 struct btf_field *btf_record_find(const struct btf_record *rec, u32 offset,
495 struct btf_field *field;
497 if (IS_ERR_OR_NULL(rec) || !(rec->field_mask & field_mask))
499 field = bsearch(&offset, rec->fields, rec->cnt, sizeof(rec->fields[0]), btf_field_cmp);
500 if (!field || !(field->type & field_mask))
505 void btf_record_free(struct btf_record *rec)
509 if (IS_ERR_OR_NULL(rec))
511 for (i = 0; i < rec->cnt; i++) {
512 switch (rec->fields[i].type) {
515 if (rec->fields[i].kptr.module)
516 module_put(rec->fields[i].kptr.module);
517 btf_put(rec->fields[i].kptr.btf);
526 /* Nothing to release */
536 void bpf_map_free_record(struct bpf_map *map)
538 btf_record_free(map->record);
542 struct btf_record *btf_record_dup(const struct btf_record *rec)
544 const struct btf_field *fields;
545 struct btf_record *new_rec;
548 if (IS_ERR_OR_NULL(rec))
550 size = offsetof(struct btf_record, fields[rec->cnt]);
551 new_rec = kmemdup(rec, size, GFP_KERNEL | __GFP_NOWARN);
553 return ERR_PTR(-ENOMEM);
554 /* Do a deep copy of the btf_record */
555 fields = rec->fields;
557 for (i = 0; i < rec->cnt; i++) {
558 switch (fields[i].type) {
561 btf_get(fields[i].kptr.btf);
562 if (fields[i].kptr.module && !try_module_get(fields[i].kptr.module)) {
574 /* Nothing to acquire */
585 btf_record_free(new_rec);
589 bool btf_record_equal(const struct btf_record *rec_a, const struct btf_record *rec_b)
591 bool a_has_fields = !IS_ERR_OR_NULL(rec_a), b_has_fields = !IS_ERR_OR_NULL(rec_b);
594 if (!a_has_fields && !b_has_fields)
596 if (a_has_fields != b_has_fields)
598 if (rec_a->cnt != rec_b->cnt)
600 size = offsetof(struct btf_record, fields[rec_a->cnt]);
601 /* btf_parse_fields uses kzalloc to allocate a btf_record, so unused
602 * members are zeroed out. So memcmp is safe to do without worrying
603 * about padding/unused fields.
605 * While spin_lock, timer, and kptr have no relation to map BTF,
606 * list_head metadata is specific to map BTF, the btf and value_rec
607 * members in particular. btf is the map BTF, while value_rec points to
608 * btf_record in that map BTF.
610 * So while by default, we don't rely on the map BTF (which the records
611 * were parsed from) matching for both records, which is not backwards
612 * compatible, in case list_head is part of it, we implicitly rely on
613 * that by way of depending on memcmp succeeding for it.
615 return !memcmp(rec_a, rec_b, size);
618 void bpf_obj_free_timer(const struct btf_record *rec, void *obj)
620 if (WARN_ON_ONCE(!btf_record_has_field(rec, BPF_TIMER)))
622 bpf_timer_cancel_and_free(obj + rec->timer_off);
625 extern void __bpf_obj_drop_impl(void *p, const struct btf_record *rec);
627 void bpf_obj_free_fields(const struct btf_record *rec, void *obj)
629 const struct btf_field *fields;
632 if (IS_ERR_OR_NULL(rec))
634 fields = rec->fields;
635 for (i = 0; i < rec->cnt; i++) {
636 struct btf_struct_meta *pointee_struct_meta;
637 const struct btf_field *field = &fields[i];
638 void *field_ptr = obj + field->offset;
641 switch (fields[i].type) {
645 bpf_timer_cancel_and_free(field_ptr);
648 WRITE_ONCE(*(u64 *)field_ptr, 0);
651 xchgd_field = (void *)xchg((unsigned long *)field_ptr, 0);
655 if (!btf_is_kernel(field->kptr.btf)) {
656 pointee_struct_meta = btf_find_struct_meta(field->kptr.btf,
658 WARN_ON_ONCE(!pointee_struct_meta);
660 __bpf_obj_drop_impl(xchgd_field, pointee_struct_meta ?
661 pointee_struct_meta->record :
665 field->kptr.dtor(xchgd_field);
669 if (WARN_ON_ONCE(rec->spin_lock_off < 0))
671 bpf_list_head_free(field, field_ptr, obj + rec->spin_lock_off);
674 if (WARN_ON_ONCE(rec->spin_lock_off < 0))
676 bpf_rb_root_free(field, field_ptr, obj + rec->spin_lock_off);
689 /* called from workqueue */
690 static void bpf_map_free_deferred(struct work_struct *work)
692 struct bpf_map *map = container_of(work, struct bpf_map, work);
693 struct btf_record *rec = map->record;
695 security_bpf_map_free(map);
696 bpf_map_release_memcg(map);
697 /* implementation dependent freeing */
698 map->ops->map_free(map);
699 /* Delay freeing of btf_record for maps, as map_free
700 * callback usually needs access to them. It is better to do it here
701 * than require each callback to do the free itself manually.
703 * Note that the btf_record stashed in map->inner_map_meta->record was
704 * already freed using the map_free callback for map in map case which
705 * eventually calls bpf_map_free_meta, since inner_map_meta is only a
706 * template bpf_map struct used during verification.
708 btf_record_free(rec);
711 static void bpf_map_put_uref(struct bpf_map *map)
713 if (atomic64_dec_and_test(&map->usercnt)) {
714 if (map->ops->map_release_uref)
715 map->ops->map_release_uref(map);
719 /* decrement map refcnt and schedule it for freeing via workqueue
720 * (underlying map implementation ops->map_free() might sleep)
722 void bpf_map_put(struct bpf_map *map)
724 if (atomic64_dec_and_test(&map->refcnt)) {
725 /* bpf_map_free_id() must be called first */
726 bpf_map_free_id(map);
728 INIT_WORK(&map->work, bpf_map_free_deferred);
729 /* Avoid spawning kworkers, since they all might contend
730 * for the same mutex like slab_mutex.
732 queue_work(system_unbound_wq, &map->work);
735 EXPORT_SYMBOL_GPL(bpf_map_put);
737 void bpf_map_put_with_uref(struct bpf_map *map)
739 bpf_map_put_uref(map);
743 static int bpf_map_release(struct inode *inode, struct file *filp)
745 struct bpf_map *map = filp->private_data;
747 if (map->ops->map_release)
748 map->ops->map_release(map, filp);
750 bpf_map_put_with_uref(map);
754 static fmode_t map_get_sys_perms(struct bpf_map *map, struct fd f)
756 fmode_t mode = f.file->f_mode;
758 /* Our file permissions may have been overridden by global
759 * map permissions facing syscall side.
761 if (READ_ONCE(map->frozen))
762 mode &= ~FMODE_CAN_WRITE;
766 #ifdef CONFIG_PROC_FS
767 /* Show the memory usage of a bpf map */
768 static u64 bpf_map_memory_usage(const struct bpf_map *map)
770 return map->ops->map_mem_usage(map);
773 static void bpf_map_show_fdinfo(struct seq_file *m, struct file *filp)
775 struct bpf_map *map = filp->private_data;
776 u32 type = 0, jited = 0;
778 if (map_type_contains_progs(map)) {
779 spin_lock(&map->owner.lock);
780 type = map->owner.type;
781 jited = map->owner.jited;
782 spin_unlock(&map->owner.lock);
791 "map_extra:\t%#llx\n"
800 (unsigned long long)map->map_extra,
801 bpf_map_memory_usage(map),
803 READ_ONCE(map->frozen));
805 seq_printf(m, "owner_prog_type:\t%u\n", type);
806 seq_printf(m, "owner_jited:\t%u\n", jited);
811 static ssize_t bpf_dummy_read(struct file *filp, char __user *buf, size_t siz,
814 /* We need this handler such that alloc_file() enables
815 * f_mode with FMODE_CAN_READ.
820 static ssize_t bpf_dummy_write(struct file *filp, const char __user *buf,
821 size_t siz, loff_t *ppos)
823 /* We need this handler such that alloc_file() enables
824 * f_mode with FMODE_CAN_WRITE.
829 /* called for any extra memory-mapped regions (except initial) */
830 static void bpf_map_mmap_open(struct vm_area_struct *vma)
832 struct bpf_map *map = vma->vm_file->private_data;
834 if (vma->vm_flags & VM_MAYWRITE)
835 bpf_map_write_active_inc(map);
838 /* called for all unmapped memory region (including initial) */
839 static void bpf_map_mmap_close(struct vm_area_struct *vma)
841 struct bpf_map *map = vma->vm_file->private_data;
843 if (vma->vm_flags & VM_MAYWRITE)
844 bpf_map_write_active_dec(map);
847 static const struct vm_operations_struct bpf_map_default_vmops = {
848 .open = bpf_map_mmap_open,
849 .close = bpf_map_mmap_close,
852 static int bpf_map_mmap(struct file *filp, struct vm_area_struct *vma)
854 struct bpf_map *map = filp->private_data;
857 if (!map->ops->map_mmap || !IS_ERR_OR_NULL(map->record))
860 if (!(vma->vm_flags & VM_SHARED))
863 mutex_lock(&map->freeze_mutex);
865 if (vma->vm_flags & VM_WRITE) {
870 /* map is meant to be read-only, so do not allow mapping as
871 * writable, because it's possible to leak a writable page
872 * reference and allows user-space to still modify it after
873 * freezing, while verifier will assume contents do not change
875 if (map->map_flags & BPF_F_RDONLY_PROG) {
881 /* set default open/close callbacks */
882 vma->vm_ops = &bpf_map_default_vmops;
883 vma->vm_private_data = map;
884 vm_flags_clear(vma, VM_MAYEXEC);
885 if (!(vma->vm_flags & VM_WRITE))
886 /* disallow re-mapping with PROT_WRITE */
887 vm_flags_clear(vma, VM_MAYWRITE);
889 err = map->ops->map_mmap(map, vma);
893 if (vma->vm_flags & VM_MAYWRITE)
894 bpf_map_write_active_inc(map);
896 mutex_unlock(&map->freeze_mutex);
900 static __poll_t bpf_map_poll(struct file *filp, struct poll_table_struct *pts)
902 struct bpf_map *map = filp->private_data;
904 if (map->ops->map_poll)
905 return map->ops->map_poll(map, filp, pts);
910 const struct file_operations bpf_map_fops = {
911 #ifdef CONFIG_PROC_FS
912 .show_fdinfo = bpf_map_show_fdinfo,
914 .release = bpf_map_release,
915 .read = bpf_dummy_read,
916 .write = bpf_dummy_write,
917 .mmap = bpf_map_mmap,
918 .poll = bpf_map_poll,
921 int bpf_map_new_fd(struct bpf_map *map, int flags)
925 ret = security_bpf_map(map, OPEN_FMODE(flags));
929 return anon_inode_getfd("bpf-map", &bpf_map_fops, map,
933 int bpf_get_file_flag(int flags)
935 if ((flags & BPF_F_RDONLY) && (flags & BPF_F_WRONLY))
937 if (flags & BPF_F_RDONLY)
939 if (flags & BPF_F_WRONLY)
944 /* helper macro to check that unused fields 'union bpf_attr' are zero */
945 #define CHECK_ATTR(CMD) \
946 memchr_inv((void *) &attr->CMD##_LAST_FIELD + \
947 sizeof(attr->CMD##_LAST_FIELD), 0, \
949 offsetof(union bpf_attr, CMD##_LAST_FIELD) - \
950 sizeof(attr->CMD##_LAST_FIELD)) != NULL
952 /* dst and src must have at least "size" number of bytes.
953 * Return strlen on success and < 0 on error.
955 int bpf_obj_name_cpy(char *dst, const char *src, unsigned int size)
957 const char *end = src + size;
958 const char *orig_src = src;
960 memset(dst, 0, size);
961 /* Copy all isalnum(), '_' and '.' chars. */
962 while (src < end && *src) {
963 if (!isalnum(*src) &&
964 *src != '_' && *src != '.')
969 /* No '\0' found in "size" number of bytes */
973 return src - orig_src;
976 int map_check_no_btf(const struct bpf_map *map,
977 const struct btf *btf,
978 const struct btf_type *key_type,
979 const struct btf_type *value_type)
984 static int map_check_btf(struct bpf_map *map, const struct btf *btf,
985 u32 btf_key_id, u32 btf_value_id)
987 const struct btf_type *key_type, *value_type;
988 u32 key_size, value_size;
991 /* Some maps allow key to be unspecified. */
993 key_type = btf_type_id_size(btf, &btf_key_id, &key_size);
994 if (!key_type || key_size != map->key_size)
997 key_type = btf_type_by_id(btf, 0);
998 if (!map->ops->map_check_btf)
1002 value_type = btf_type_id_size(btf, &btf_value_id, &value_size);
1003 if (!value_type || value_size != map->value_size)
1006 map->record = btf_parse_fields(btf, value_type,
1007 BPF_SPIN_LOCK | BPF_TIMER | BPF_KPTR | BPF_LIST_HEAD |
1008 BPF_RB_ROOT | BPF_REFCOUNT,
1010 if (!IS_ERR_OR_NULL(map->record)) {
1013 if (!bpf_capable()) {
1017 if (map->map_flags & (BPF_F_RDONLY_PROG | BPF_F_WRONLY_PROG)) {
1021 for (i = 0; i < sizeof(map->record->field_mask) * 8; i++) {
1022 switch (map->record->field_mask & (1 << i)) {
1026 if (map->map_type != BPF_MAP_TYPE_HASH &&
1027 map->map_type != BPF_MAP_TYPE_ARRAY &&
1028 map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
1029 map->map_type != BPF_MAP_TYPE_SK_STORAGE &&
1030 map->map_type != BPF_MAP_TYPE_INODE_STORAGE &&
1031 map->map_type != BPF_MAP_TYPE_TASK_STORAGE &&
1032 map->map_type != BPF_MAP_TYPE_CGRP_STORAGE) {
1038 if (map->map_type != BPF_MAP_TYPE_HASH &&
1039 map->map_type != BPF_MAP_TYPE_LRU_HASH &&
1040 map->map_type != BPF_MAP_TYPE_ARRAY) {
1045 case BPF_KPTR_UNREF:
1048 if (map->map_type != BPF_MAP_TYPE_HASH &&
1049 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
1050 map->map_type != BPF_MAP_TYPE_LRU_HASH &&
1051 map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH &&
1052 map->map_type != BPF_MAP_TYPE_ARRAY &&
1053 map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
1054 map->map_type != BPF_MAP_TYPE_SK_STORAGE &&
1055 map->map_type != BPF_MAP_TYPE_INODE_STORAGE &&
1056 map->map_type != BPF_MAP_TYPE_TASK_STORAGE &&
1057 map->map_type != BPF_MAP_TYPE_CGRP_STORAGE) {
1064 if (map->map_type != BPF_MAP_TYPE_HASH &&
1065 map->map_type != BPF_MAP_TYPE_LRU_HASH &&
1066 map->map_type != BPF_MAP_TYPE_ARRAY) {
1072 /* Fail if map_type checks are missing for a field type */
1079 ret = btf_check_and_fixup_fields(btf, map->record);
1083 if (map->ops->map_check_btf) {
1084 ret = map->ops->map_check_btf(map, btf, key_type, value_type);
1091 bpf_map_free_record(map);
1095 #define BPF_MAP_CREATE_LAST_FIELD map_extra
1096 /* called via syscall */
1097 static int map_create(union bpf_attr *attr)
1099 const struct bpf_map_ops *ops;
1100 int numa_node = bpf_map_attr_numa_node(attr);
1101 u32 map_type = attr->map_type;
1102 struct bpf_map *map;
1106 err = CHECK_ATTR(BPF_MAP_CREATE);
1110 if (attr->btf_vmlinux_value_type_id) {
1111 if (attr->map_type != BPF_MAP_TYPE_STRUCT_OPS ||
1112 attr->btf_key_type_id || attr->btf_value_type_id)
1114 } else if (attr->btf_key_type_id && !attr->btf_value_type_id) {
1118 if (attr->map_type != BPF_MAP_TYPE_BLOOM_FILTER &&
1119 attr->map_extra != 0)
1122 f_flags = bpf_get_file_flag(attr->map_flags);
1126 if (numa_node != NUMA_NO_NODE &&
1127 ((unsigned int)numa_node >= nr_node_ids ||
1128 !node_online(numa_node)))
1131 /* find map type and init map: hashtable vs rbtree vs bloom vs ... */
1132 map_type = attr->map_type;
1133 if (map_type >= ARRAY_SIZE(bpf_map_types))
1135 map_type = array_index_nospec(map_type, ARRAY_SIZE(bpf_map_types));
1136 ops = bpf_map_types[map_type];
1140 if (ops->map_alloc_check) {
1141 err = ops->map_alloc_check(attr);
1145 if (attr->map_ifindex)
1146 ops = &bpf_map_offload_ops;
1147 if (!ops->map_mem_usage)
1150 /* Intent here is for unprivileged_bpf_disabled to block BPF map
1151 * creation for unprivileged users; other actions depend
1152 * on fd availability and access to bpffs, so are dependent on
1153 * object creation success. Even with unprivileged BPF disabled,
1154 * capability checks are still carried out.
1156 if (sysctl_unprivileged_bpf_disabled && !bpf_capable())
1159 /* check privileged map type permissions */
1161 case BPF_MAP_TYPE_ARRAY:
1162 case BPF_MAP_TYPE_PERCPU_ARRAY:
1163 case BPF_MAP_TYPE_PROG_ARRAY:
1164 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
1165 case BPF_MAP_TYPE_CGROUP_ARRAY:
1166 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
1167 case BPF_MAP_TYPE_HASH:
1168 case BPF_MAP_TYPE_PERCPU_HASH:
1169 case BPF_MAP_TYPE_HASH_OF_MAPS:
1170 case BPF_MAP_TYPE_RINGBUF:
1171 case BPF_MAP_TYPE_USER_RINGBUF:
1172 case BPF_MAP_TYPE_CGROUP_STORAGE:
1173 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
1176 case BPF_MAP_TYPE_SK_STORAGE:
1177 case BPF_MAP_TYPE_INODE_STORAGE:
1178 case BPF_MAP_TYPE_TASK_STORAGE:
1179 case BPF_MAP_TYPE_CGRP_STORAGE:
1180 case BPF_MAP_TYPE_BLOOM_FILTER:
1181 case BPF_MAP_TYPE_LPM_TRIE:
1182 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
1183 case BPF_MAP_TYPE_STACK_TRACE:
1184 case BPF_MAP_TYPE_QUEUE:
1185 case BPF_MAP_TYPE_STACK:
1186 case BPF_MAP_TYPE_LRU_HASH:
1187 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
1188 case BPF_MAP_TYPE_STRUCT_OPS:
1189 case BPF_MAP_TYPE_CPUMAP:
1193 case BPF_MAP_TYPE_SOCKMAP:
1194 case BPF_MAP_TYPE_SOCKHASH:
1195 case BPF_MAP_TYPE_DEVMAP:
1196 case BPF_MAP_TYPE_DEVMAP_HASH:
1197 case BPF_MAP_TYPE_XSKMAP:
1198 if (!capable(CAP_NET_ADMIN))
1202 WARN(1, "unsupported map type %d", map_type);
1206 map = ops->map_alloc(attr);
1208 return PTR_ERR(map);
1210 map->map_type = map_type;
1212 err = bpf_obj_name_cpy(map->name, attr->map_name,
1213 sizeof(attr->map_name));
1217 atomic64_set(&map->refcnt, 1);
1218 atomic64_set(&map->usercnt, 1);
1219 mutex_init(&map->freeze_mutex);
1220 spin_lock_init(&map->owner.lock);
1222 if (attr->btf_key_type_id || attr->btf_value_type_id ||
1223 /* Even the map's value is a kernel's struct,
1224 * the bpf_prog.o must have BTF to begin with
1225 * to figure out the corresponding kernel's
1226 * counter part. Thus, attr->btf_fd has
1229 attr->btf_vmlinux_value_type_id) {
1232 btf = btf_get_by_fd(attr->btf_fd);
1237 if (btf_is_kernel(btf)) {
1244 if (attr->btf_value_type_id) {
1245 err = map_check_btf(map, btf, attr->btf_key_type_id,
1246 attr->btf_value_type_id);
1251 map->btf_key_type_id = attr->btf_key_type_id;
1252 map->btf_value_type_id = attr->btf_value_type_id;
1253 map->btf_vmlinux_value_type_id =
1254 attr->btf_vmlinux_value_type_id;
1257 err = security_bpf_map_alloc(map);
1261 err = bpf_map_alloc_id(map);
1265 bpf_map_save_memcg(map);
1267 err = bpf_map_new_fd(map, f_flags);
1269 /* failed to allocate fd.
1270 * bpf_map_put_with_uref() is needed because the above
1271 * bpf_map_alloc_id() has published the map
1272 * to the userspace and the userspace may
1273 * have refcnt-ed it through BPF_MAP_GET_FD_BY_ID.
1275 bpf_map_put_with_uref(map);
1282 security_bpf_map_free(map);
1285 map->ops->map_free(map);
1289 /* if error is returned, fd is released.
1290 * On success caller should complete fd access with matching fdput()
1292 struct bpf_map *__bpf_map_get(struct fd f)
1295 return ERR_PTR(-EBADF);
1296 if (f.file->f_op != &bpf_map_fops) {
1298 return ERR_PTR(-EINVAL);
1301 return f.file->private_data;
1304 void bpf_map_inc(struct bpf_map *map)
1306 atomic64_inc(&map->refcnt);
1308 EXPORT_SYMBOL_GPL(bpf_map_inc);
1310 void bpf_map_inc_with_uref(struct bpf_map *map)
1312 atomic64_inc(&map->refcnt);
1313 atomic64_inc(&map->usercnt);
1315 EXPORT_SYMBOL_GPL(bpf_map_inc_with_uref);
1317 struct bpf_map *bpf_map_get(u32 ufd)
1319 struct fd f = fdget(ufd);
1320 struct bpf_map *map;
1322 map = __bpf_map_get(f);
1331 EXPORT_SYMBOL(bpf_map_get);
1333 struct bpf_map *bpf_map_get_with_uref(u32 ufd)
1335 struct fd f = fdget(ufd);
1336 struct bpf_map *map;
1338 map = __bpf_map_get(f);
1342 bpf_map_inc_with_uref(map);
1348 /* map_idr_lock should have been held or the map should have been
1349 * protected by rcu read lock.
1351 struct bpf_map *__bpf_map_inc_not_zero(struct bpf_map *map, bool uref)
1355 refold = atomic64_fetch_add_unless(&map->refcnt, 1, 0);
1357 return ERR_PTR(-ENOENT);
1359 atomic64_inc(&map->usercnt);
1364 struct bpf_map *bpf_map_inc_not_zero(struct bpf_map *map)
1366 spin_lock_bh(&map_idr_lock);
1367 map = __bpf_map_inc_not_zero(map, false);
1368 spin_unlock_bh(&map_idr_lock);
1372 EXPORT_SYMBOL_GPL(bpf_map_inc_not_zero);
1374 int __weak bpf_stackmap_copy(struct bpf_map *map, void *key, void *value)
1379 static void *__bpf_copy_key(void __user *ukey, u64 key_size)
1382 return vmemdup_user(ukey, key_size);
1385 return ERR_PTR(-EINVAL);
1390 static void *___bpf_copy_key(bpfptr_t ukey, u64 key_size)
1393 return kvmemdup_bpfptr(ukey, key_size);
1395 if (!bpfptr_is_null(ukey))
1396 return ERR_PTR(-EINVAL);
1401 /* last field in 'union bpf_attr' used by this command */
1402 #define BPF_MAP_LOOKUP_ELEM_LAST_FIELD flags
1404 static int map_lookup_elem(union bpf_attr *attr)
1406 void __user *ukey = u64_to_user_ptr(attr->key);
1407 void __user *uvalue = u64_to_user_ptr(attr->value);
1408 int ufd = attr->map_fd;
1409 struct bpf_map *map;
1415 if (CHECK_ATTR(BPF_MAP_LOOKUP_ELEM))
1418 if (attr->flags & ~BPF_F_LOCK)
1422 map = __bpf_map_get(f);
1424 return PTR_ERR(map);
1425 if (!(map_get_sys_perms(map, f) & FMODE_CAN_READ)) {
1430 if ((attr->flags & BPF_F_LOCK) &&
1431 !btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
1436 key = __bpf_copy_key(ukey, map->key_size);
1442 value_size = bpf_map_value_size(map);
1445 value = kvmalloc(value_size, GFP_USER | __GFP_NOWARN);
1449 if (map->map_type == BPF_MAP_TYPE_BLOOM_FILTER) {
1450 if (copy_from_user(value, uvalue, value_size))
1453 err = bpf_map_copy_value(map, key, value, attr->flags);
1457 err = bpf_map_copy_value(map, key, value, attr->flags);
1462 if (copy_to_user(uvalue, value, value_size) != 0)
1477 #define BPF_MAP_UPDATE_ELEM_LAST_FIELD flags
1479 static int map_update_elem(union bpf_attr *attr, bpfptr_t uattr)
1481 bpfptr_t ukey = make_bpfptr(attr->key, uattr.is_kernel);
1482 bpfptr_t uvalue = make_bpfptr(attr->value, uattr.is_kernel);
1483 int ufd = attr->map_fd;
1484 struct bpf_map *map;
1490 if (CHECK_ATTR(BPF_MAP_UPDATE_ELEM))
1494 map = __bpf_map_get(f);
1496 return PTR_ERR(map);
1497 bpf_map_write_active_inc(map);
1498 if (!(map_get_sys_perms(map, f) & FMODE_CAN_WRITE)) {
1503 if ((attr->flags & BPF_F_LOCK) &&
1504 !btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
1509 key = ___bpf_copy_key(ukey, map->key_size);
1515 value_size = bpf_map_value_size(map);
1516 value = kvmemdup_bpfptr(uvalue, value_size);
1517 if (IS_ERR(value)) {
1518 err = PTR_ERR(value);
1522 err = bpf_map_update_value(map, f.file, key, value, attr->flags);
1528 bpf_map_write_active_dec(map);
1533 #define BPF_MAP_DELETE_ELEM_LAST_FIELD key
1535 static int map_delete_elem(union bpf_attr *attr, bpfptr_t uattr)
1537 bpfptr_t ukey = make_bpfptr(attr->key, uattr.is_kernel);
1538 int ufd = attr->map_fd;
1539 struct bpf_map *map;
1544 if (CHECK_ATTR(BPF_MAP_DELETE_ELEM))
1548 map = __bpf_map_get(f);
1550 return PTR_ERR(map);
1551 bpf_map_write_active_inc(map);
1552 if (!(map_get_sys_perms(map, f) & FMODE_CAN_WRITE)) {
1557 key = ___bpf_copy_key(ukey, map->key_size);
1563 if (bpf_map_is_offloaded(map)) {
1564 err = bpf_map_offload_delete_elem(map, key);
1566 } else if (IS_FD_PROG_ARRAY(map) ||
1567 map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
1568 /* These maps require sleepable context */
1569 err = map->ops->map_delete_elem(map, key);
1573 bpf_disable_instrumentation();
1575 err = map->ops->map_delete_elem(map, key);
1577 bpf_enable_instrumentation();
1578 maybe_wait_bpf_programs(map);
1582 bpf_map_write_active_dec(map);
1587 /* last field in 'union bpf_attr' used by this command */
1588 #define BPF_MAP_GET_NEXT_KEY_LAST_FIELD next_key
1590 static int map_get_next_key(union bpf_attr *attr)
1592 void __user *ukey = u64_to_user_ptr(attr->key);
1593 void __user *unext_key = u64_to_user_ptr(attr->next_key);
1594 int ufd = attr->map_fd;
1595 struct bpf_map *map;
1596 void *key, *next_key;
1600 if (CHECK_ATTR(BPF_MAP_GET_NEXT_KEY))
1604 map = __bpf_map_get(f);
1606 return PTR_ERR(map);
1607 if (!(map_get_sys_perms(map, f) & FMODE_CAN_READ)) {
1613 key = __bpf_copy_key(ukey, map->key_size);
1623 next_key = kvmalloc(map->key_size, GFP_USER);
1627 if (bpf_map_is_offloaded(map)) {
1628 err = bpf_map_offload_get_next_key(map, key, next_key);
1633 err = map->ops->map_get_next_key(map, key, next_key);
1640 if (copy_to_user(unext_key, next_key, map->key_size) != 0)
1654 int generic_map_delete_batch(struct bpf_map *map,
1655 const union bpf_attr *attr,
1656 union bpf_attr __user *uattr)
1658 void __user *keys = u64_to_user_ptr(attr->batch.keys);
1663 if (attr->batch.elem_flags & ~BPF_F_LOCK)
1666 if ((attr->batch.elem_flags & BPF_F_LOCK) &&
1667 !btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
1671 max_count = attr->batch.count;
1675 key = kvmalloc(map->key_size, GFP_USER | __GFP_NOWARN);
1679 for (cp = 0; cp < max_count; cp++) {
1681 if (copy_from_user(key, keys + cp * map->key_size,
1685 if (bpf_map_is_offloaded(map)) {
1686 err = bpf_map_offload_delete_elem(map, key);
1690 bpf_disable_instrumentation();
1692 err = map->ops->map_delete_elem(map, key);
1694 bpf_enable_instrumentation();
1699 if (copy_to_user(&uattr->batch.count, &cp, sizeof(cp)))
1704 maybe_wait_bpf_programs(map);
1708 int generic_map_update_batch(struct bpf_map *map, struct file *map_file,
1709 const union bpf_attr *attr,
1710 union bpf_attr __user *uattr)
1712 void __user *values = u64_to_user_ptr(attr->batch.values);
1713 void __user *keys = u64_to_user_ptr(attr->batch.keys);
1714 u32 value_size, cp, max_count;
1718 if (attr->batch.elem_flags & ~BPF_F_LOCK)
1721 if ((attr->batch.elem_flags & BPF_F_LOCK) &&
1722 !btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
1726 value_size = bpf_map_value_size(map);
1728 max_count = attr->batch.count;
1732 key = kvmalloc(map->key_size, GFP_USER | __GFP_NOWARN);
1736 value = kvmalloc(value_size, GFP_USER | __GFP_NOWARN);
1742 for (cp = 0; cp < max_count; cp++) {
1744 if (copy_from_user(key, keys + cp * map->key_size,
1746 copy_from_user(value, values + cp * value_size, value_size))
1749 err = bpf_map_update_value(map, map_file, key, value,
1750 attr->batch.elem_flags);
1757 if (copy_to_user(&uattr->batch.count, &cp, sizeof(cp)))
1765 #define MAP_LOOKUP_RETRIES 3
1767 int generic_map_lookup_batch(struct bpf_map *map,
1768 const union bpf_attr *attr,
1769 union bpf_attr __user *uattr)
1771 void __user *uobatch = u64_to_user_ptr(attr->batch.out_batch);
1772 void __user *ubatch = u64_to_user_ptr(attr->batch.in_batch);
1773 void __user *values = u64_to_user_ptr(attr->batch.values);
1774 void __user *keys = u64_to_user_ptr(attr->batch.keys);
1775 void *buf, *buf_prevkey, *prev_key, *key, *value;
1776 int err, retry = MAP_LOOKUP_RETRIES;
1777 u32 value_size, cp, max_count;
1779 if (attr->batch.elem_flags & ~BPF_F_LOCK)
1782 if ((attr->batch.elem_flags & BPF_F_LOCK) &&
1783 !btf_record_has_field(map->record, BPF_SPIN_LOCK))
1786 value_size = bpf_map_value_size(map);
1788 max_count = attr->batch.count;
1792 if (put_user(0, &uattr->batch.count))
1795 buf_prevkey = kvmalloc(map->key_size, GFP_USER | __GFP_NOWARN);
1799 buf = kvmalloc(map->key_size + value_size, GFP_USER | __GFP_NOWARN);
1801 kvfree(buf_prevkey);
1807 if (ubatch && copy_from_user(buf_prevkey, ubatch, map->key_size))
1810 value = key + map->key_size;
1812 prev_key = buf_prevkey;
1814 for (cp = 0; cp < max_count;) {
1816 err = map->ops->map_get_next_key(map, prev_key, key);
1820 err = bpf_map_copy_value(map, key, value,
1821 attr->batch.elem_flags);
1823 if (err == -ENOENT) {
1835 if (copy_to_user(keys + cp * map->key_size, key,
1840 if (copy_to_user(values + cp * value_size, value, value_size)) {
1846 prev_key = buf_prevkey;
1848 swap(prev_key, key);
1849 retry = MAP_LOOKUP_RETRIES;
1857 if ((copy_to_user(&uattr->batch.count, &cp, sizeof(cp)) ||
1858 (cp && copy_to_user(uobatch, prev_key, map->key_size))))
1862 kvfree(buf_prevkey);
1867 #define BPF_MAP_LOOKUP_AND_DELETE_ELEM_LAST_FIELD flags
1869 static int map_lookup_and_delete_elem(union bpf_attr *attr)
1871 void __user *ukey = u64_to_user_ptr(attr->key);
1872 void __user *uvalue = u64_to_user_ptr(attr->value);
1873 int ufd = attr->map_fd;
1874 struct bpf_map *map;
1880 if (CHECK_ATTR(BPF_MAP_LOOKUP_AND_DELETE_ELEM))
1883 if (attr->flags & ~BPF_F_LOCK)
1887 map = __bpf_map_get(f);
1889 return PTR_ERR(map);
1890 bpf_map_write_active_inc(map);
1891 if (!(map_get_sys_perms(map, f) & FMODE_CAN_READ) ||
1892 !(map_get_sys_perms(map, f) & FMODE_CAN_WRITE)) {
1898 (map->map_type == BPF_MAP_TYPE_QUEUE ||
1899 map->map_type == BPF_MAP_TYPE_STACK)) {
1904 if ((attr->flags & BPF_F_LOCK) &&
1905 !btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
1910 key = __bpf_copy_key(ukey, map->key_size);
1916 value_size = bpf_map_value_size(map);
1919 value = kvmalloc(value_size, GFP_USER | __GFP_NOWARN);
1924 if (map->map_type == BPF_MAP_TYPE_QUEUE ||
1925 map->map_type == BPF_MAP_TYPE_STACK) {
1926 err = map->ops->map_pop_elem(map, value);
1927 } else if (map->map_type == BPF_MAP_TYPE_HASH ||
1928 map->map_type == BPF_MAP_TYPE_PERCPU_HASH ||
1929 map->map_type == BPF_MAP_TYPE_LRU_HASH ||
1930 map->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH) {
1931 if (!bpf_map_is_offloaded(map)) {
1932 bpf_disable_instrumentation();
1934 err = map->ops->map_lookup_and_delete_elem(map, key, value, attr->flags);
1936 bpf_enable_instrumentation();
1943 if (copy_to_user(uvalue, value, value_size) != 0) {
1955 bpf_map_write_active_dec(map);
1960 #define BPF_MAP_FREEZE_LAST_FIELD map_fd
1962 static int map_freeze(const union bpf_attr *attr)
1964 int err = 0, ufd = attr->map_fd;
1965 struct bpf_map *map;
1968 if (CHECK_ATTR(BPF_MAP_FREEZE))
1972 map = __bpf_map_get(f);
1974 return PTR_ERR(map);
1976 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS || !IS_ERR_OR_NULL(map->record)) {
1981 if (!(map_get_sys_perms(map, f) & FMODE_CAN_WRITE)) {
1986 mutex_lock(&map->freeze_mutex);
1987 if (bpf_map_write_active(map)) {
1991 if (READ_ONCE(map->frozen)) {
1996 WRITE_ONCE(map->frozen, true);
1998 mutex_unlock(&map->freeze_mutex);
2003 static const struct bpf_prog_ops * const bpf_prog_types[] = {
2004 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
2005 [_id] = & _name ## _prog_ops,
2006 #define BPF_MAP_TYPE(_id, _ops)
2007 #define BPF_LINK_TYPE(_id, _name)
2008 #include <linux/bpf_types.h>
2009 #undef BPF_PROG_TYPE
2011 #undef BPF_LINK_TYPE
2014 static int find_prog_type(enum bpf_prog_type type, struct bpf_prog *prog)
2016 const struct bpf_prog_ops *ops;
2018 if (type >= ARRAY_SIZE(bpf_prog_types))
2020 type = array_index_nospec(type, ARRAY_SIZE(bpf_prog_types));
2021 ops = bpf_prog_types[type];
2025 if (!bpf_prog_is_offloaded(prog->aux))
2026 prog->aux->ops = ops;
2028 prog->aux->ops = &bpf_offload_prog_ops;
2039 static const char * const bpf_audit_str[BPF_AUDIT_MAX] = {
2040 [BPF_AUDIT_LOAD] = "LOAD",
2041 [BPF_AUDIT_UNLOAD] = "UNLOAD",
2044 static void bpf_audit_prog(const struct bpf_prog *prog, unsigned int op)
2046 struct audit_context *ctx = NULL;
2047 struct audit_buffer *ab;
2049 if (WARN_ON_ONCE(op >= BPF_AUDIT_MAX))
2051 if (audit_enabled == AUDIT_OFF)
2053 if (!in_irq() && !irqs_disabled())
2054 ctx = audit_context();
2055 ab = audit_log_start(ctx, GFP_ATOMIC, AUDIT_BPF);
2058 audit_log_format(ab, "prog-id=%u op=%s",
2059 prog->aux->id, bpf_audit_str[op]);
2063 static int bpf_prog_alloc_id(struct bpf_prog *prog)
2067 idr_preload(GFP_KERNEL);
2068 spin_lock_bh(&prog_idr_lock);
2069 id = idr_alloc_cyclic(&prog_idr, prog, 1, INT_MAX, GFP_ATOMIC);
2072 spin_unlock_bh(&prog_idr_lock);
2075 /* id is in [1, INT_MAX) */
2076 if (WARN_ON_ONCE(!id))
2079 return id > 0 ? 0 : id;
2082 void bpf_prog_free_id(struct bpf_prog *prog)
2084 unsigned long flags;
2086 /* cBPF to eBPF migrations are currently not in the idr store.
2087 * Offloaded programs are removed from the store when their device
2088 * disappears - even if someone grabs an fd to them they are unusable,
2089 * simply waiting for refcnt to drop to be freed.
2094 spin_lock_irqsave(&prog_idr_lock, flags);
2095 idr_remove(&prog_idr, prog->aux->id);
2097 spin_unlock_irqrestore(&prog_idr_lock, flags);
2100 static void __bpf_prog_put_rcu(struct rcu_head *rcu)
2102 struct bpf_prog_aux *aux = container_of(rcu, struct bpf_prog_aux, rcu);
2104 kvfree(aux->func_info);
2105 kfree(aux->func_info_aux);
2106 free_uid(aux->user);
2107 security_bpf_prog_free(aux);
2108 bpf_prog_free(aux->prog);
2111 static void __bpf_prog_put_noref(struct bpf_prog *prog, bool deferred)
2113 bpf_prog_kallsyms_del_all(prog);
2114 btf_put(prog->aux->btf);
2115 module_put(prog->aux->mod);
2116 kvfree(prog->aux->jited_linfo);
2117 kvfree(prog->aux->linfo);
2118 kfree(prog->aux->kfunc_tab);
2119 if (prog->aux->attach_btf)
2120 btf_put(prog->aux->attach_btf);
2123 if (prog->aux->sleepable)
2124 call_rcu_tasks_trace(&prog->aux->rcu, __bpf_prog_put_rcu);
2126 call_rcu(&prog->aux->rcu, __bpf_prog_put_rcu);
2128 __bpf_prog_put_rcu(&prog->aux->rcu);
2132 static void bpf_prog_put_deferred(struct work_struct *work)
2134 struct bpf_prog_aux *aux;
2135 struct bpf_prog *prog;
2137 aux = container_of(work, struct bpf_prog_aux, work);
2139 perf_event_bpf_event(prog, PERF_BPF_EVENT_PROG_UNLOAD, 0);
2140 bpf_audit_prog(prog, BPF_AUDIT_UNLOAD);
2141 bpf_prog_free_id(prog);
2142 __bpf_prog_put_noref(prog, true);
2145 static void __bpf_prog_put(struct bpf_prog *prog)
2147 struct bpf_prog_aux *aux = prog->aux;
2149 if (atomic64_dec_and_test(&aux->refcnt)) {
2150 if (in_irq() || irqs_disabled()) {
2151 INIT_WORK(&aux->work, bpf_prog_put_deferred);
2152 schedule_work(&aux->work);
2154 bpf_prog_put_deferred(&aux->work);
2159 void bpf_prog_put(struct bpf_prog *prog)
2161 __bpf_prog_put(prog);
2163 EXPORT_SYMBOL_GPL(bpf_prog_put);
2165 static int bpf_prog_release(struct inode *inode, struct file *filp)
2167 struct bpf_prog *prog = filp->private_data;
2173 struct bpf_prog_kstats {
2179 void notrace bpf_prog_inc_misses_counter(struct bpf_prog *prog)
2181 struct bpf_prog_stats *stats;
2184 stats = this_cpu_ptr(prog->stats);
2185 flags = u64_stats_update_begin_irqsave(&stats->syncp);
2186 u64_stats_inc(&stats->misses);
2187 u64_stats_update_end_irqrestore(&stats->syncp, flags);
2190 static void bpf_prog_get_stats(const struct bpf_prog *prog,
2191 struct bpf_prog_kstats *stats)
2193 u64 nsecs = 0, cnt = 0, misses = 0;
2196 for_each_possible_cpu(cpu) {
2197 const struct bpf_prog_stats *st;
2199 u64 tnsecs, tcnt, tmisses;
2201 st = per_cpu_ptr(prog->stats, cpu);
2203 start = u64_stats_fetch_begin(&st->syncp);
2204 tnsecs = u64_stats_read(&st->nsecs);
2205 tcnt = u64_stats_read(&st->cnt);
2206 tmisses = u64_stats_read(&st->misses);
2207 } while (u64_stats_fetch_retry(&st->syncp, start));
2212 stats->nsecs = nsecs;
2214 stats->misses = misses;
2217 #ifdef CONFIG_PROC_FS
2218 static void bpf_prog_show_fdinfo(struct seq_file *m, struct file *filp)
2220 const struct bpf_prog *prog = filp->private_data;
2221 char prog_tag[sizeof(prog->tag) * 2 + 1] = { };
2222 struct bpf_prog_kstats stats;
2224 bpf_prog_get_stats(prog, &stats);
2225 bin2hex(prog_tag, prog->tag, sizeof(prog->tag));
2232 "run_time_ns:\t%llu\n"
2234 "recursion_misses:\t%llu\n"
2235 "verified_insns:\t%u\n",
2239 prog->pages * 1ULL << PAGE_SHIFT,
2244 prog->aux->verified_insns);
2248 const struct file_operations bpf_prog_fops = {
2249 #ifdef CONFIG_PROC_FS
2250 .show_fdinfo = bpf_prog_show_fdinfo,
2252 .release = bpf_prog_release,
2253 .read = bpf_dummy_read,
2254 .write = bpf_dummy_write,
2257 int bpf_prog_new_fd(struct bpf_prog *prog)
2261 ret = security_bpf_prog(prog);
2265 return anon_inode_getfd("bpf-prog", &bpf_prog_fops, prog,
2266 O_RDWR | O_CLOEXEC);
2269 static struct bpf_prog *____bpf_prog_get(struct fd f)
2272 return ERR_PTR(-EBADF);
2273 if (f.file->f_op != &bpf_prog_fops) {
2275 return ERR_PTR(-EINVAL);
2278 return f.file->private_data;
2281 void bpf_prog_add(struct bpf_prog *prog, int i)
2283 atomic64_add(i, &prog->aux->refcnt);
2285 EXPORT_SYMBOL_GPL(bpf_prog_add);
2287 void bpf_prog_sub(struct bpf_prog *prog, int i)
2289 /* Only to be used for undoing previous bpf_prog_add() in some
2290 * error path. We still know that another entity in our call
2291 * path holds a reference to the program, thus atomic_sub() can
2292 * be safely used in such cases!
2294 WARN_ON(atomic64_sub_return(i, &prog->aux->refcnt) == 0);
2296 EXPORT_SYMBOL_GPL(bpf_prog_sub);
2298 void bpf_prog_inc(struct bpf_prog *prog)
2300 atomic64_inc(&prog->aux->refcnt);
2302 EXPORT_SYMBOL_GPL(bpf_prog_inc);
2304 /* prog_idr_lock should have been held */
2305 struct bpf_prog *bpf_prog_inc_not_zero(struct bpf_prog *prog)
2309 refold = atomic64_fetch_add_unless(&prog->aux->refcnt, 1, 0);
2312 return ERR_PTR(-ENOENT);
2316 EXPORT_SYMBOL_GPL(bpf_prog_inc_not_zero);
2318 bool bpf_prog_get_ok(struct bpf_prog *prog,
2319 enum bpf_prog_type *attach_type, bool attach_drv)
2321 /* not an attachment, just a refcount inc, always allow */
2325 if (prog->type != *attach_type)
2327 if (bpf_prog_is_offloaded(prog->aux) && !attach_drv)
2333 static struct bpf_prog *__bpf_prog_get(u32 ufd, enum bpf_prog_type *attach_type,
2336 struct fd f = fdget(ufd);
2337 struct bpf_prog *prog;
2339 prog = ____bpf_prog_get(f);
2342 if (!bpf_prog_get_ok(prog, attach_type, attach_drv)) {
2343 prog = ERR_PTR(-EINVAL);
2353 struct bpf_prog *bpf_prog_get(u32 ufd)
2355 return __bpf_prog_get(ufd, NULL, false);
2358 struct bpf_prog *bpf_prog_get_type_dev(u32 ufd, enum bpf_prog_type type,
2361 return __bpf_prog_get(ufd, &type, attach_drv);
2363 EXPORT_SYMBOL_GPL(bpf_prog_get_type_dev);
2365 /* Initially all BPF programs could be loaded w/o specifying
2366 * expected_attach_type. Later for some of them specifying expected_attach_type
2367 * at load time became required so that program could be validated properly.
2368 * Programs of types that are allowed to be loaded both w/ and w/o (for
2369 * backward compatibility) expected_attach_type, should have the default attach
2370 * type assigned to expected_attach_type for the latter case, so that it can be
2371 * validated later at attach time.
2373 * bpf_prog_load_fixup_attach_type() sets expected_attach_type in @attr if
2374 * prog type requires it but has some attach types that have to be backward
2377 static void bpf_prog_load_fixup_attach_type(union bpf_attr *attr)
2379 switch (attr->prog_type) {
2380 case BPF_PROG_TYPE_CGROUP_SOCK:
2381 /* Unfortunately BPF_ATTACH_TYPE_UNSPEC enumeration doesn't
2382 * exist so checking for non-zero is the way to go here.
2384 if (!attr->expected_attach_type)
2385 attr->expected_attach_type =
2386 BPF_CGROUP_INET_SOCK_CREATE;
2388 case BPF_PROG_TYPE_SK_REUSEPORT:
2389 if (!attr->expected_attach_type)
2390 attr->expected_attach_type =
2391 BPF_SK_REUSEPORT_SELECT;
2397 bpf_prog_load_check_attach(enum bpf_prog_type prog_type,
2398 enum bpf_attach_type expected_attach_type,
2399 struct btf *attach_btf, u32 btf_id,
2400 struct bpf_prog *dst_prog)
2403 if (btf_id > BTF_MAX_TYPE)
2406 if (!attach_btf && !dst_prog)
2409 switch (prog_type) {
2410 case BPF_PROG_TYPE_TRACING:
2411 case BPF_PROG_TYPE_LSM:
2412 case BPF_PROG_TYPE_STRUCT_OPS:
2413 case BPF_PROG_TYPE_EXT:
2420 if (attach_btf && (!btf_id || dst_prog))
2423 if (dst_prog && prog_type != BPF_PROG_TYPE_TRACING &&
2424 prog_type != BPF_PROG_TYPE_EXT)
2427 switch (prog_type) {
2428 case BPF_PROG_TYPE_CGROUP_SOCK:
2429 switch (expected_attach_type) {
2430 case BPF_CGROUP_INET_SOCK_CREATE:
2431 case BPF_CGROUP_INET_SOCK_RELEASE:
2432 case BPF_CGROUP_INET4_POST_BIND:
2433 case BPF_CGROUP_INET6_POST_BIND:
2438 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
2439 switch (expected_attach_type) {
2440 case BPF_CGROUP_INET4_BIND:
2441 case BPF_CGROUP_INET6_BIND:
2442 case BPF_CGROUP_INET4_CONNECT:
2443 case BPF_CGROUP_INET6_CONNECT:
2444 case BPF_CGROUP_INET4_GETPEERNAME:
2445 case BPF_CGROUP_INET6_GETPEERNAME:
2446 case BPF_CGROUP_INET4_GETSOCKNAME:
2447 case BPF_CGROUP_INET6_GETSOCKNAME:
2448 case BPF_CGROUP_UDP4_SENDMSG:
2449 case BPF_CGROUP_UDP6_SENDMSG:
2450 case BPF_CGROUP_UDP4_RECVMSG:
2451 case BPF_CGROUP_UDP6_RECVMSG:
2456 case BPF_PROG_TYPE_CGROUP_SKB:
2457 switch (expected_attach_type) {
2458 case BPF_CGROUP_INET_INGRESS:
2459 case BPF_CGROUP_INET_EGRESS:
2464 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
2465 switch (expected_attach_type) {
2466 case BPF_CGROUP_SETSOCKOPT:
2467 case BPF_CGROUP_GETSOCKOPT:
2472 case BPF_PROG_TYPE_SK_LOOKUP:
2473 if (expected_attach_type == BPF_SK_LOOKUP)
2476 case BPF_PROG_TYPE_SK_REUSEPORT:
2477 switch (expected_attach_type) {
2478 case BPF_SK_REUSEPORT_SELECT:
2479 case BPF_SK_REUSEPORT_SELECT_OR_MIGRATE:
2484 case BPF_PROG_TYPE_SYSCALL:
2485 case BPF_PROG_TYPE_EXT:
2486 if (expected_attach_type)
2494 static bool is_net_admin_prog_type(enum bpf_prog_type prog_type)
2496 switch (prog_type) {
2497 case BPF_PROG_TYPE_SCHED_CLS:
2498 case BPF_PROG_TYPE_SCHED_ACT:
2499 case BPF_PROG_TYPE_XDP:
2500 case BPF_PROG_TYPE_LWT_IN:
2501 case BPF_PROG_TYPE_LWT_OUT:
2502 case BPF_PROG_TYPE_LWT_XMIT:
2503 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
2504 case BPF_PROG_TYPE_SK_SKB:
2505 case BPF_PROG_TYPE_SK_MSG:
2506 case BPF_PROG_TYPE_FLOW_DISSECTOR:
2507 case BPF_PROG_TYPE_CGROUP_DEVICE:
2508 case BPF_PROG_TYPE_CGROUP_SOCK:
2509 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
2510 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
2511 case BPF_PROG_TYPE_CGROUP_SYSCTL:
2512 case BPF_PROG_TYPE_SOCK_OPS:
2513 case BPF_PROG_TYPE_EXT: /* extends any prog */
2514 case BPF_PROG_TYPE_NETFILTER:
2516 case BPF_PROG_TYPE_CGROUP_SKB:
2518 case BPF_PROG_TYPE_SK_REUSEPORT:
2519 /* equivalent to SOCKET_FILTER. need CAP_BPF only */
2525 static bool is_perfmon_prog_type(enum bpf_prog_type prog_type)
2527 switch (prog_type) {
2528 case BPF_PROG_TYPE_KPROBE:
2529 case BPF_PROG_TYPE_TRACEPOINT:
2530 case BPF_PROG_TYPE_PERF_EVENT:
2531 case BPF_PROG_TYPE_RAW_TRACEPOINT:
2532 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
2533 case BPF_PROG_TYPE_TRACING:
2534 case BPF_PROG_TYPE_LSM:
2535 case BPF_PROG_TYPE_STRUCT_OPS: /* has access to struct sock */
2536 case BPF_PROG_TYPE_EXT: /* extends any prog */
2543 /* last field in 'union bpf_attr' used by this command */
2544 #define BPF_PROG_LOAD_LAST_FIELD log_true_size
2546 static int bpf_prog_load(union bpf_attr *attr, bpfptr_t uattr, u32 uattr_size)
2548 enum bpf_prog_type type = attr->prog_type;
2549 struct bpf_prog *prog, *dst_prog = NULL;
2550 struct btf *attach_btf = NULL;
2555 if (CHECK_ATTR(BPF_PROG_LOAD))
2558 if (attr->prog_flags & ~(BPF_F_STRICT_ALIGNMENT |
2559 BPF_F_ANY_ALIGNMENT |
2560 BPF_F_TEST_STATE_FREQ |
2562 BPF_F_TEST_RND_HI32 |
2563 BPF_F_XDP_HAS_FRAGS |
2564 BPF_F_XDP_DEV_BOUND_ONLY))
2567 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS) &&
2568 (attr->prog_flags & BPF_F_ANY_ALIGNMENT) &&
2572 /* copy eBPF program license from user space */
2573 if (strncpy_from_bpfptr(license,
2574 make_bpfptr(attr->license, uattr.is_kernel),
2575 sizeof(license) - 1) < 0)
2577 license[sizeof(license) - 1] = 0;
2579 /* eBPF programs must be GPL compatible to use GPL-ed functions */
2580 is_gpl = license_is_gpl_compatible(license);
2582 /* Intent here is for unprivileged_bpf_disabled to block BPF program
2583 * creation for unprivileged users; other actions depend
2584 * on fd availability and access to bpffs, so are dependent on
2585 * object creation success. Even with unprivileged BPF disabled,
2586 * capability checks are still carried out for these
2587 * and other operations.
2589 if (sysctl_unprivileged_bpf_disabled && !bpf_capable())
2592 if (attr->insn_cnt == 0 ||
2593 attr->insn_cnt > (bpf_capable() ? BPF_COMPLEXITY_LIMIT_INSNS : BPF_MAXINSNS))
2595 if (type != BPF_PROG_TYPE_SOCKET_FILTER &&
2596 type != BPF_PROG_TYPE_CGROUP_SKB &&
2600 if (is_net_admin_prog_type(type) && !capable(CAP_NET_ADMIN) && !capable(CAP_SYS_ADMIN))
2602 if (is_perfmon_prog_type(type) && !perfmon_capable())
2605 /* attach_prog_fd/attach_btf_obj_fd can specify fd of either bpf_prog
2606 * or btf, we need to check which one it is
2608 if (attr->attach_prog_fd) {
2609 dst_prog = bpf_prog_get(attr->attach_prog_fd);
2610 if (IS_ERR(dst_prog)) {
2612 attach_btf = btf_get_by_fd(attr->attach_btf_obj_fd);
2613 if (IS_ERR(attach_btf))
2615 if (!btf_is_kernel(attach_btf)) {
2616 /* attaching through specifying bpf_prog's BTF
2617 * objects directly might be supported eventually
2619 btf_put(attach_btf);
2623 } else if (attr->attach_btf_id) {
2624 /* fall back to vmlinux BTF, if BTF type ID is specified */
2625 attach_btf = bpf_get_btf_vmlinux();
2626 if (IS_ERR(attach_btf))
2627 return PTR_ERR(attach_btf);
2630 btf_get(attach_btf);
2633 bpf_prog_load_fixup_attach_type(attr);
2634 if (bpf_prog_load_check_attach(type, attr->expected_attach_type,
2635 attach_btf, attr->attach_btf_id,
2638 bpf_prog_put(dst_prog);
2640 btf_put(attach_btf);
2644 /* plain bpf_prog allocation */
2645 prog = bpf_prog_alloc(bpf_prog_size(attr->insn_cnt), GFP_USER);
2648 bpf_prog_put(dst_prog);
2650 btf_put(attach_btf);
2654 prog->expected_attach_type = attr->expected_attach_type;
2655 prog->aux->attach_btf = attach_btf;
2656 prog->aux->attach_btf_id = attr->attach_btf_id;
2657 prog->aux->dst_prog = dst_prog;
2658 prog->aux->dev_bound = !!attr->prog_ifindex;
2659 prog->aux->sleepable = attr->prog_flags & BPF_F_SLEEPABLE;
2660 prog->aux->xdp_has_frags = attr->prog_flags & BPF_F_XDP_HAS_FRAGS;
2662 err = security_bpf_prog_alloc(prog->aux);
2666 prog->aux->user = get_current_user();
2667 prog->len = attr->insn_cnt;
2670 if (copy_from_bpfptr(prog->insns,
2671 make_bpfptr(attr->insns, uattr.is_kernel),
2672 bpf_prog_insn_size(prog)) != 0)
2675 prog->orig_prog = NULL;
2678 atomic64_set(&prog->aux->refcnt, 1);
2679 prog->gpl_compatible = is_gpl ? 1 : 0;
2681 if (bpf_prog_is_dev_bound(prog->aux)) {
2682 err = bpf_prog_dev_bound_init(prog, attr);
2687 if (type == BPF_PROG_TYPE_EXT && dst_prog &&
2688 bpf_prog_is_dev_bound(dst_prog->aux)) {
2689 err = bpf_prog_dev_bound_inherit(prog, dst_prog);
2694 /* find program type: socket_filter vs tracing_filter */
2695 err = find_prog_type(type, prog);
2699 prog->aux->load_time = ktime_get_boottime_ns();
2700 err = bpf_obj_name_cpy(prog->aux->name, attr->prog_name,
2701 sizeof(attr->prog_name));
2705 /* run eBPF verifier */
2706 err = bpf_check(&prog, attr, uattr, uattr_size);
2708 goto free_used_maps;
2710 prog = bpf_prog_select_runtime(prog, &err);
2712 goto free_used_maps;
2714 err = bpf_prog_alloc_id(prog);
2716 goto free_used_maps;
2718 /* Upon success of bpf_prog_alloc_id(), the BPF prog is
2719 * effectively publicly exposed. However, retrieving via
2720 * bpf_prog_get_fd_by_id() will take another reference,
2721 * therefore it cannot be gone underneath us.
2723 * Only for the time /after/ successful bpf_prog_new_fd()
2724 * and before returning to userspace, we might just hold
2725 * one reference and any parallel close on that fd could
2726 * rip everything out. Hence, below notifications must
2727 * happen before bpf_prog_new_fd().
2729 * Also, any failure handling from this point onwards must
2730 * be using bpf_prog_put() given the program is exposed.
2732 bpf_prog_kallsyms_add(prog);
2733 perf_event_bpf_event(prog, PERF_BPF_EVENT_PROG_LOAD, 0);
2734 bpf_audit_prog(prog, BPF_AUDIT_LOAD);
2736 err = bpf_prog_new_fd(prog);
2742 /* In case we have subprogs, we need to wait for a grace
2743 * period before we can tear down JIT memory since symbols
2744 * are already exposed under kallsyms.
2746 __bpf_prog_put_noref(prog, prog->aux->func_cnt);
2749 free_uid(prog->aux->user);
2750 security_bpf_prog_free(prog->aux);
2752 if (prog->aux->attach_btf)
2753 btf_put(prog->aux->attach_btf);
2754 bpf_prog_free(prog);
2758 #define BPF_OBJ_LAST_FIELD path_fd
2760 static int bpf_obj_pin(const union bpf_attr *attr)
2764 if (CHECK_ATTR(BPF_OBJ) || attr->file_flags & ~BPF_F_PATH_FD)
2767 /* path_fd has to be accompanied by BPF_F_PATH_FD flag */
2768 if (!(attr->file_flags & BPF_F_PATH_FD) && attr->path_fd)
2771 path_fd = attr->file_flags & BPF_F_PATH_FD ? attr->path_fd : AT_FDCWD;
2772 return bpf_obj_pin_user(attr->bpf_fd, path_fd,
2773 u64_to_user_ptr(attr->pathname));
2776 static int bpf_obj_get(const union bpf_attr *attr)
2780 if (CHECK_ATTR(BPF_OBJ) || attr->bpf_fd != 0 ||
2781 attr->file_flags & ~(BPF_OBJ_FLAG_MASK | BPF_F_PATH_FD))
2784 /* path_fd has to be accompanied by BPF_F_PATH_FD flag */
2785 if (!(attr->file_flags & BPF_F_PATH_FD) && attr->path_fd)
2788 path_fd = attr->file_flags & BPF_F_PATH_FD ? attr->path_fd : AT_FDCWD;
2789 return bpf_obj_get_user(path_fd, u64_to_user_ptr(attr->pathname),
2793 void bpf_link_init(struct bpf_link *link, enum bpf_link_type type,
2794 const struct bpf_link_ops *ops, struct bpf_prog *prog)
2796 atomic64_set(&link->refcnt, 1);
2803 static void bpf_link_free_id(int id)
2808 spin_lock_bh(&link_idr_lock);
2809 idr_remove(&link_idr, id);
2810 spin_unlock_bh(&link_idr_lock);
2813 /* Clean up bpf_link and corresponding anon_inode file and FD. After
2814 * anon_inode is created, bpf_link can't be just kfree()'d due to deferred
2815 * anon_inode's release() call. This helper marksbpf_link as
2816 * defunct, releases anon_inode file and puts reserved FD. bpf_prog's refcnt
2817 * is not decremented, it's the responsibility of a calling code that failed
2818 * to complete bpf_link initialization.
2820 void bpf_link_cleanup(struct bpf_link_primer *primer)
2822 primer->link->prog = NULL;
2823 bpf_link_free_id(primer->id);
2825 put_unused_fd(primer->fd);
2828 void bpf_link_inc(struct bpf_link *link)
2830 atomic64_inc(&link->refcnt);
2833 /* bpf_link_free is guaranteed to be called from process context */
2834 static void bpf_link_free(struct bpf_link *link)
2836 bpf_link_free_id(link->id);
2838 /* detach BPF program, clean up used resources */
2839 link->ops->release(link);
2840 bpf_prog_put(link->prog);
2842 /* free bpf_link and its containing memory */
2843 link->ops->dealloc(link);
2846 static void bpf_link_put_deferred(struct work_struct *work)
2848 struct bpf_link *link = container_of(work, struct bpf_link, work);
2850 bpf_link_free(link);
2853 /* bpf_link_put might be called from atomic context. It needs to be called
2854 * from sleepable context in order to acquire sleeping locks during the process.
2856 void bpf_link_put(struct bpf_link *link)
2858 if (!atomic64_dec_and_test(&link->refcnt))
2861 INIT_WORK(&link->work, bpf_link_put_deferred);
2862 schedule_work(&link->work);
2864 EXPORT_SYMBOL(bpf_link_put);
2866 static void bpf_link_put_direct(struct bpf_link *link)
2868 if (!atomic64_dec_and_test(&link->refcnt))
2870 bpf_link_free(link);
2873 static int bpf_link_release(struct inode *inode, struct file *filp)
2875 struct bpf_link *link = filp->private_data;
2877 bpf_link_put_direct(link);
2881 #ifdef CONFIG_PROC_FS
2882 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type)
2883 #define BPF_MAP_TYPE(_id, _ops)
2884 #define BPF_LINK_TYPE(_id, _name) [_id] = #_name,
2885 static const char *bpf_link_type_strs[] = {
2886 [BPF_LINK_TYPE_UNSPEC] = "<invalid>",
2887 #include <linux/bpf_types.h>
2889 #undef BPF_PROG_TYPE
2891 #undef BPF_LINK_TYPE
2893 static void bpf_link_show_fdinfo(struct seq_file *m, struct file *filp)
2895 const struct bpf_link *link = filp->private_data;
2896 const struct bpf_prog *prog = link->prog;
2897 char prog_tag[sizeof(prog->tag) * 2 + 1] = { };
2902 bpf_link_type_strs[link->type],
2905 bin2hex(prog_tag, prog->tag, sizeof(prog->tag));
2912 if (link->ops->show_fdinfo)
2913 link->ops->show_fdinfo(link, m);
2917 static const struct file_operations bpf_link_fops = {
2918 #ifdef CONFIG_PROC_FS
2919 .show_fdinfo = bpf_link_show_fdinfo,
2921 .release = bpf_link_release,
2922 .read = bpf_dummy_read,
2923 .write = bpf_dummy_write,
2926 static int bpf_link_alloc_id(struct bpf_link *link)
2930 idr_preload(GFP_KERNEL);
2931 spin_lock_bh(&link_idr_lock);
2932 id = idr_alloc_cyclic(&link_idr, link, 1, INT_MAX, GFP_ATOMIC);
2933 spin_unlock_bh(&link_idr_lock);
2939 /* Prepare bpf_link to be exposed to user-space by allocating anon_inode file,
2940 * reserving unused FD and allocating ID from link_idr. This is to be paired
2941 * with bpf_link_settle() to install FD and ID and expose bpf_link to
2942 * user-space, if bpf_link is successfully attached. If not, bpf_link and
2943 * pre-allocated resources are to be freed with bpf_cleanup() call. All the
2944 * transient state is passed around in struct bpf_link_primer.
2945 * This is preferred way to create and initialize bpf_link, especially when
2946 * there are complicated and expensive operations in between creating bpf_link
2947 * itself and attaching it to BPF hook. By using bpf_link_prime() and
2948 * bpf_link_settle() kernel code using bpf_link doesn't have to perform
2949 * expensive (and potentially failing) roll back operations in a rare case
2950 * that file, FD, or ID can't be allocated.
2952 int bpf_link_prime(struct bpf_link *link, struct bpf_link_primer *primer)
2957 fd = get_unused_fd_flags(O_CLOEXEC);
2962 id = bpf_link_alloc_id(link);
2968 file = anon_inode_getfile("bpf_link", &bpf_link_fops, link, O_CLOEXEC);
2970 bpf_link_free_id(id);
2972 return PTR_ERR(file);
2975 primer->link = link;
2976 primer->file = file;
2982 int bpf_link_settle(struct bpf_link_primer *primer)
2984 /* make bpf_link fetchable by ID */
2985 spin_lock_bh(&link_idr_lock);
2986 primer->link->id = primer->id;
2987 spin_unlock_bh(&link_idr_lock);
2988 /* make bpf_link fetchable by FD */
2989 fd_install(primer->fd, primer->file);
2990 /* pass through installed FD */
2994 int bpf_link_new_fd(struct bpf_link *link)
2996 return anon_inode_getfd("bpf-link", &bpf_link_fops, link, O_CLOEXEC);
2999 struct bpf_link *bpf_link_get_from_fd(u32 ufd)
3001 struct fd f = fdget(ufd);
3002 struct bpf_link *link;
3005 return ERR_PTR(-EBADF);
3006 if (f.file->f_op != &bpf_link_fops) {
3008 return ERR_PTR(-EINVAL);
3011 link = f.file->private_data;
3017 EXPORT_SYMBOL(bpf_link_get_from_fd);
3019 static void bpf_tracing_link_release(struct bpf_link *link)
3021 struct bpf_tracing_link *tr_link =
3022 container_of(link, struct bpf_tracing_link, link.link);
3024 WARN_ON_ONCE(bpf_trampoline_unlink_prog(&tr_link->link,
3025 tr_link->trampoline));
3027 bpf_trampoline_put(tr_link->trampoline);
3029 /* tgt_prog is NULL if target is a kernel function */
3030 if (tr_link->tgt_prog)
3031 bpf_prog_put(tr_link->tgt_prog);
3034 static void bpf_tracing_link_dealloc(struct bpf_link *link)
3036 struct bpf_tracing_link *tr_link =
3037 container_of(link, struct bpf_tracing_link, link.link);
3042 static void bpf_tracing_link_show_fdinfo(const struct bpf_link *link,
3043 struct seq_file *seq)
3045 struct bpf_tracing_link *tr_link =
3046 container_of(link, struct bpf_tracing_link, link.link);
3047 u32 target_btf_id, target_obj_id;
3049 bpf_trampoline_unpack_key(tr_link->trampoline->key,
3050 &target_obj_id, &target_btf_id);
3052 "attach_type:\t%d\n"
3053 "target_obj_id:\t%u\n"
3054 "target_btf_id:\t%u\n",
3055 tr_link->attach_type,
3060 static int bpf_tracing_link_fill_link_info(const struct bpf_link *link,
3061 struct bpf_link_info *info)
3063 struct bpf_tracing_link *tr_link =
3064 container_of(link, struct bpf_tracing_link, link.link);
3066 info->tracing.attach_type = tr_link->attach_type;
3067 bpf_trampoline_unpack_key(tr_link->trampoline->key,
3068 &info->tracing.target_obj_id,
3069 &info->tracing.target_btf_id);
3074 static const struct bpf_link_ops bpf_tracing_link_lops = {
3075 .release = bpf_tracing_link_release,
3076 .dealloc = bpf_tracing_link_dealloc,
3077 .show_fdinfo = bpf_tracing_link_show_fdinfo,
3078 .fill_link_info = bpf_tracing_link_fill_link_info,
3081 static int bpf_tracing_prog_attach(struct bpf_prog *prog,
3086 struct bpf_link_primer link_primer;
3087 struct bpf_prog *tgt_prog = NULL;
3088 struct bpf_trampoline *tr = NULL;
3089 struct bpf_tracing_link *link;
3093 switch (prog->type) {
3094 case BPF_PROG_TYPE_TRACING:
3095 if (prog->expected_attach_type != BPF_TRACE_FENTRY &&
3096 prog->expected_attach_type != BPF_TRACE_FEXIT &&
3097 prog->expected_attach_type != BPF_MODIFY_RETURN) {
3102 case BPF_PROG_TYPE_EXT:
3103 if (prog->expected_attach_type != 0) {
3108 case BPF_PROG_TYPE_LSM:
3109 if (prog->expected_attach_type != BPF_LSM_MAC) {
3119 if (!!tgt_prog_fd != !!btf_id) {
3125 /* For now we only allow new targets for BPF_PROG_TYPE_EXT */
3126 if (prog->type != BPF_PROG_TYPE_EXT) {
3131 tgt_prog = bpf_prog_get(tgt_prog_fd);
3132 if (IS_ERR(tgt_prog)) {
3133 err = PTR_ERR(tgt_prog);
3138 key = bpf_trampoline_compute_key(tgt_prog, NULL, btf_id);
3141 link = kzalloc(sizeof(*link), GFP_USER);
3146 bpf_link_init(&link->link.link, BPF_LINK_TYPE_TRACING,
3147 &bpf_tracing_link_lops, prog);
3148 link->attach_type = prog->expected_attach_type;
3149 link->link.cookie = bpf_cookie;
3151 mutex_lock(&prog->aux->dst_mutex);
3153 /* There are a few possible cases here:
3155 * - if prog->aux->dst_trampoline is set, the program was just loaded
3156 * and not yet attached to anything, so we can use the values stored
3159 * - if prog->aux->dst_trampoline is NULL, the program has already been
3160 * attached to a target and its initial target was cleared (below)
3162 * - if tgt_prog != NULL, the caller specified tgt_prog_fd +
3163 * target_btf_id using the link_create API.
3165 * - if tgt_prog == NULL when this function was called using the old
3166 * raw_tracepoint_open API, and we need a target from prog->aux
3168 * - if prog->aux->dst_trampoline and tgt_prog is NULL, the program
3169 * was detached and is going for re-attachment.
3171 if (!prog->aux->dst_trampoline && !tgt_prog) {
3173 * Allow re-attach for TRACING and LSM programs. If it's
3174 * currently linked, bpf_trampoline_link_prog will fail.
3175 * EXT programs need to specify tgt_prog_fd, so they
3176 * re-attach in separate code path.
3178 if (prog->type != BPF_PROG_TYPE_TRACING &&
3179 prog->type != BPF_PROG_TYPE_LSM) {
3183 btf_id = prog->aux->attach_btf_id;
3184 key = bpf_trampoline_compute_key(NULL, prog->aux->attach_btf, btf_id);
3187 if (!prog->aux->dst_trampoline ||
3188 (key && key != prog->aux->dst_trampoline->key)) {
3189 /* If there is no saved target, or the specified target is
3190 * different from the destination specified at load time, we
3191 * need a new trampoline and a check for compatibility
3193 struct bpf_attach_target_info tgt_info = {};
3195 err = bpf_check_attach_target(NULL, prog, tgt_prog, btf_id,
3200 if (tgt_info.tgt_mod) {
3201 module_put(prog->aux->mod);
3202 prog->aux->mod = tgt_info.tgt_mod;
3205 tr = bpf_trampoline_get(key, &tgt_info);
3211 /* The caller didn't specify a target, or the target was the
3212 * same as the destination supplied during program load. This
3213 * means we can reuse the trampoline and reference from program
3214 * load time, and there is no need to allocate a new one. This
3215 * can only happen once for any program, as the saved values in
3216 * prog->aux are cleared below.
3218 tr = prog->aux->dst_trampoline;
3219 tgt_prog = prog->aux->dst_prog;
3222 err = bpf_link_prime(&link->link.link, &link_primer);
3226 err = bpf_trampoline_link_prog(&link->link, tr);
3228 bpf_link_cleanup(&link_primer);
3233 link->tgt_prog = tgt_prog;
3234 link->trampoline = tr;
3236 /* Always clear the trampoline and target prog from prog->aux to make
3237 * sure the original attach destination is not kept alive after a
3238 * program is (re-)attached to another target.
3240 if (prog->aux->dst_prog &&
3241 (tgt_prog_fd || tr != prog->aux->dst_trampoline))
3242 /* got extra prog ref from syscall, or attaching to different prog */
3243 bpf_prog_put(prog->aux->dst_prog);
3244 if (prog->aux->dst_trampoline && tr != prog->aux->dst_trampoline)
3245 /* we allocated a new trampoline, so free the old one */
3246 bpf_trampoline_put(prog->aux->dst_trampoline);
3248 prog->aux->dst_prog = NULL;
3249 prog->aux->dst_trampoline = NULL;
3250 mutex_unlock(&prog->aux->dst_mutex);
3252 return bpf_link_settle(&link_primer);
3254 if (tr && tr != prog->aux->dst_trampoline)
3255 bpf_trampoline_put(tr);
3256 mutex_unlock(&prog->aux->dst_mutex);
3259 if (tgt_prog_fd && tgt_prog)
3260 bpf_prog_put(tgt_prog);
3264 struct bpf_raw_tp_link {
3265 struct bpf_link link;
3266 struct bpf_raw_event_map *btp;
3269 static void bpf_raw_tp_link_release(struct bpf_link *link)
3271 struct bpf_raw_tp_link *raw_tp =
3272 container_of(link, struct bpf_raw_tp_link, link);
3274 bpf_probe_unregister(raw_tp->btp, raw_tp->link.prog);
3275 bpf_put_raw_tracepoint(raw_tp->btp);
3278 static void bpf_raw_tp_link_dealloc(struct bpf_link *link)
3280 struct bpf_raw_tp_link *raw_tp =
3281 container_of(link, struct bpf_raw_tp_link, link);
3286 static void bpf_raw_tp_link_show_fdinfo(const struct bpf_link *link,
3287 struct seq_file *seq)
3289 struct bpf_raw_tp_link *raw_tp_link =
3290 container_of(link, struct bpf_raw_tp_link, link);
3294 raw_tp_link->btp->tp->name);
3297 static int bpf_raw_tp_link_fill_link_info(const struct bpf_link *link,
3298 struct bpf_link_info *info)
3300 struct bpf_raw_tp_link *raw_tp_link =
3301 container_of(link, struct bpf_raw_tp_link, link);
3302 char __user *ubuf = u64_to_user_ptr(info->raw_tracepoint.tp_name);
3303 const char *tp_name = raw_tp_link->btp->tp->name;
3304 u32 ulen = info->raw_tracepoint.tp_name_len;
3305 size_t tp_len = strlen(tp_name);
3310 info->raw_tracepoint.tp_name_len = tp_len + 1;
3315 if (ulen >= tp_len + 1) {
3316 if (copy_to_user(ubuf, tp_name, tp_len + 1))
3321 if (copy_to_user(ubuf, tp_name, ulen - 1))
3323 if (put_user(zero, ubuf + ulen - 1))
3331 static const struct bpf_link_ops bpf_raw_tp_link_lops = {
3332 .release = bpf_raw_tp_link_release,
3333 .dealloc = bpf_raw_tp_link_dealloc,
3334 .show_fdinfo = bpf_raw_tp_link_show_fdinfo,
3335 .fill_link_info = bpf_raw_tp_link_fill_link_info,
3338 #ifdef CONFIG_PERF_EVENTS
3339 struct bpf_perf_link {
3340 struct bpf_link link;
3341 struct file *perf_file;
3344 static void bpf_perf_link_release(struct bpf_link *link)
3346 struct bpf_perf_link *perf_link = container_of(link, struct bpf_perf_link, link);
3347 struct perf_event *event = perf_link->perf_file->private_data;
3349 perf_event_free_bpf_prog(event);
3350 fput(perf_link->perf_file);
3353 static void bpf_perf_link_dealloc(struct bpf_link *link)
3355 struct bpf_perf_link *perf_link = container_of(link, struct bpf_perf_link, link);
3360 static const struct bpf_link_ops bpf_perf_link_lops = {
3361 .release = bpf_perf_link_release,
3362 .dealloc = bpf_perf_link_dealloc,
3365 static int bpf_perf_link_attach(const union bpf_attr *attr, struct bpf_prog *prog)
3367 struct bpf_link_primer link_primer;
3368 struct bpf_perf_link *link;
3369 struct perf_event *event;
3370 struct file *perf_file;
3373 if (attr->link_create.flags)
3376 perf_file = perf_event_get(attr->link_create.target_fd);
3377 if (IS_ERR(perf_file))
3378 return PTR_ERR(perf_file);
3380 link = kzalloc(sizeof(*link), GFP_USER);
3385 bpf_link_init(&link->link, BPF_LINK_TYPE_PERF_EVENT, &bpf_perf_link_lops, prog);
3386 link->perf_file = perf_file;
3388 err = bpf_link_prime(&link->link, &link_primer);
3394 event = perf_file->private_data;
3395 err = perf_event_set_bpf_prog(event, prog, attr->link_create.perf_event.bpf_cookie);
3397 bpf_link_cleanup(&link_primer);
3400 /* perf_event_set_bpf_prog() doesn't take its own refcnt on prog */
3403 return bpf_link_settle(&link_primer);
3410 static int bpf_perf_link_attach(const union bpf_attr *attr, struct bpf_prog *prog)
3414 #endif /* CONFIG_PERF_EVENTS */
3416 static int bpf_raw_tp_link_attach(struct bpf_prog *prog,
3417 const char __user *user_tp_name)
3419 struct bpf_link_primer link_primer;
3420 struct bpf_raw_tp_link *link;
3421 struct bpf_raw_event_map *btp;
3422 const char *tp_name;
3426 switch (prog->type) {
3427 case BPF_PROG_TYPE_TRACING:
3428 case BPF_PROG_TYPE_EXT:
3429 case BPF_PROG_TYPE_LSM:
3431 /* The attach point for this category of programs
3432 * should be specified via btf_id during program load.
3435 if (prog->type == BPF_PROG_TYPE_TRACING &&
3436 prog->expected_attach_type == BPF_TRACE_RAW_TP) {
3437 tp_name = prog->aux->attach_func_name;
3440 return bpf_tracing_prog_attach(prog, 0, 0, 0);
3441 case BPF_PROG_TYPE_RAW_TRACEPOINT:
3442 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
3443 if (strncpy_from_user(buf, user_tp_name, sizeof(buf) - 1) < 0)
3445 buf[sizeof(buf) - 1] = 0;
3452 btp = bpf_get_raw_tracepoint(tp_name);
3456 link = kzalloc(sizeof(*link), GFP_USER);
3461 bpf_link_init(&link->link, BPF_LINK_TYPE_RAW_TRACEPOINT,
3462 &bpf_raw_tp_link_lops, prog);
3465 err = bpf_link_prime(&link->link, &link_primer);
3471 err = bpf_probe_register(link->btp, prog);
3473 bpf_link_cleanup(&link_primer);
3477 return bpf_link_settle(&link_primer);
3480 bpf_put_raw_tracepoint(btp);
3484 #define BPF_RAW_TRACEPOINT_OPEN_LAST_FIELD raw_tracepoint.prog_fd
3486 static int bpf_raw_tracepoint_open(const union bpf_attr *attr)
3488 struct bpf_prog *prog;
3491 if (CHECK_ATTR(BPF_RAW_TRACEPOINT_OPEN))
3494 prog = bpf_prog_get(attr->raw_tracepoint.prog_fd);
3496 return PTR_ERR(prog);
3498 fd = bpf_raw_tp_link_attach(prog, u64_to_user_ptr(attr->raw_tracepoint.name));
3504 static int bpf_prog_attach_check_attach_type(const struct bpf_prog *prog,
3505 enum bpf_attach_type attach_type)
3507 switch (prog->type) {
3508 case BPF_PROG_TYPE_CGROUP_SOCK:
3509 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
3510 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3511 case BPF_PROG_TYPE_SK_LOOKUP:
3512 return attach_type == prog->expected_attach_type ? 0 : -EINVAL;
3513 case BPF_PROG_TYPE_CGROUP_SKB:
3514 if (!capable(CAP_NET_ADMIN))
3515 /* cg-skb progs can be loaded by unpriv user.
3516 * check permissions at attach time.
3519 return prog->enforce_expected_attach_type &&
3520 prog->expected_attach_type != attach_type ?
3527 static enum bpf_prog_type
3528 attach_type_to_prog_type(enum bpf_attach_type attach_type)
3530 switch (attach_type) {
3531 case BPF_CGROUP_INET_INGRESS:
3532 case BPF_CGROUP_INET_EGRESS:
3533 return BPF_PROG_TYPE_CGROUP_SKB;
3534 case BPF_CGROUP_INET_SOCK_CREATE:
3535 case BPF_CGROUP_INET_SOCK_RELEASE:
3536 case BPF_CGROUP_INET4_POST_BIND:
3537 case BPF_CGROUP_INET6_POST_BIND:
3538 return BPF_PROG_TYPE_CGROUP_SOCK;
3539 case BPF_CGROUP_INET4_BIND:
3540 case BPF_CGROUP_INET6_BIND:
3541 case BPF_CGROUP_INET4_CONNECT:
3542 case BPF_CGROUP_INET6_CONNECT:
3543 case BPF_CGROUP_INET4_GETPEERNAME:
3544 case BPF_CGROUP_INET6_GETPEERNAME:
3545 case BPF_CGROUP_INET4_GETSOCKNAME:
3546 case BPF_CGROUP_INET6_GETSOCKNAME:
3547 case BPF_CGROUP_UDP4_SENDMSG:
3548 case BPF_CGROUP_UDP6_SENDMSG:
3549 case BPF_CGROUP_UDP4_RECVMSG:
3550 case BPF_CGROUP_UDP6_RECVMSG:
3551 return BPF_PROG_TYPE_CGROUP_SOCK_ADDR;
3552 case BPF_CGROUP_SOCK_OPS:
3553 return BPF_PROG_TYPE_SOCK_OPS;
3554 case BPF_CGROUP_DEVICE:
3555 return BPF_PROG_TYPE_CGROUP_DEVICE;
3556 case BPF_SK_MSG_VERDICT:
3557 return BPF_PROG_TYPE_SK_MSG;
3558 case BPF_SK_SKB_STREAM_PARSER:
3559 case BPF_SK_SKB_STREAM_VERDICT:
3560 case BPF_SK_SKB_VERDICT:
3561 return BPF_PROG_TYPE_SK_SKB;
3562 case BPF_LIRC_MODE2:
3563 return BPF_PROG_TYPE_LIRC_MODE2;
3564 case BPF_FLOW_DISSECTOR:
3565 return BPF_PROG_TYPE_FLOW_DISSECTOR;
3566 case BPF_CGROUP_SYSCTL:
3567 return BPF_PROG_TYPE_CGROUP_SYSCTL;
3568 case BPF_CGROUP_GETSOCKOPT:
3569 case BPF_CGROUP_SETSOCKOPT:
3570 return BPF_PROG_TYPE_CGROUP_SOCKOPT;
3571 case BPF_TRACE_ITER:
3572 case BPF_TRACE_RAW_TP:
3573 case BPF_TRACE_FENTRY:
3574 case BPF_TRACE_FEXIT:
3575 case BPF_MODIFY_RETURN:
3576 return BPF_PROG_TYPE_TRACING;
3578 return BPF_PROG_TYPE_LSM;
3580 return BPF_PROG_TYPE_SK_LOOKUP;
3582 return BPF_PROG_TYPE_XDP;
3583 case BPF_LSM_CGROUP:
3584 return BPF_PROG_TYPE_LSM;
3586 return BPF_PROG_TYPE_UNSPEC;
3590 #define BPF_PROG_ATTACH_LAST_FIELD replace_bpf_fd
3592 #define BPF_F_ATTACH_MASK \
3593 (BPF_F_ALLOW_OVERRIDE | BPF_F_ALLOW_MULTI | BPF_F_REPLACE)
3595 static int bpf_prog_attach(const union bpf_attr *attr)
3597 enum bpf_prog_type ptype;
3598 struct bpf_prog *prog;
3601 if (CHECK_ATTR(BPF_PROG_ATTACH))
3604 if (attr->attach_flags & ~BPF_F_ATTACH_MASK)
3607 ptype = attach_type_to_prog_type(attr->attach_type);
3608 if (ptype == BPF_PROG_TYPE_UNSPEC)
3611 prog = bpf_prog_get_type(attr->attach_bpf_fd, ptype);
3613 return PTR_ERR(prog);
3615 if (bpf_prog_attach_check_attach_type(prog, attr->attach_type)) {
3621 case BPF_PROG_TYPE_SK_SKB:
3622 case BPF_PROG_TYPE_SK_MSG:
3623 ret = sock_map_get_from_fd(attr, prog);
3625 case BPF_PROG_TYPE_LIRC_MODE2:
3626 ret = lirc_prog_attach(attr, prog);
3628 case BPF_PROG_TYPE_FLOW_DISSECTOR:
3629 ret = netns_bpf_prog_attach(attr, prog);
3631 case BPF_PROG_TYPE_CGROUP_DEVICE:
3632 case BPF_PROG_TYPE_CGROUP_SKB:
3633 case BPF_PROG_TYPE_CGROUP_SOCK:
3634 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
3635 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3636 case BPF_PROG_TYPE_CGROUP_SYSCTL:
3637 case BPF_PROG_TYPE_SOCK_OPS:
3638 case BPF_PROG_TYPE_LSM:
3639 if (ptype == BPF_PROG_TYPE_LSM &&
3640 prog->expected_attach_type != BPF_LSM_CGROUP)
3643 ret = cgroup_bpf_prog_attach(attr, ptype, prog);
3654 #define BPF_PROG_DETACH_LAST_FIELD attach_type
3656 static int bpf_prog_detach(const union bpf_attr *attr)
3658 enum bpf_prog_type ptype;
3660 if (CHECK_ATTR(BPF_PROG_DETACH))
3663 ptype = attach_type_to_prog_type(attr->attach_type);
3666 case BPF_PROG_TYPE_SK_MSG:
3667 case BPF_PROG_TYPE_SK_SKB:
3668 return sock_map_prog_detach(attr, ptype);
3669 case BPF_PROG_TYPE_LIRC_MODE2:
3670 return lirc_prog_detach(attr);
3671 case BPF_PROG_TYPE_FLOW_DISSECTOR:
3672 return netns_bpf_prog_detach(attr, ptype);
3673 case BPF_PROG_TYPE_CGROUP_DEVICE:
3674 case BPF_PROG_TYPE_CGROUP_SKB:
3675 case BPF_PROG_TYPE_CGROUP_SOCK:
3676 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
3677 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3678 case BPF_PROG_TYPE_CGROUP_SYSCTL:
3679 case BPF_PROG_TYPE_SOCK_OPS:
3680 case BPF_PROG_TYPE_LSM:
3681 return cgroup_bpf_prog_detach(attr, ptype);
3687 #define BPF_PROG_QUERY_LAST_FIELD query.prog_attach_flags
3689 static int bpf_prog_query(const union bpf_attr *attr,
3690 union bpf_attr __user *uattr)
3692 if (!capable(CAP_NET_ADMIN))
3694 if (CHECK_ATTR(BPF_PROG_QUERY))
3696 if (attr->query.query_flags & ~BPF_F_QUERY_EFFECTIVE)
3699 switch (attr->query.attach_type) {
3700 case BPF_CGROUP_INET_INGRESS:
3701 case BPF_CGROUP_INET_EGRESS:
3702 case BPF_CGROUP_INET_SOCK_CREATE:
3703 case BPF_CGROUP_INET_SOCK_RELEASE:
3704 case BPF_CGROUP_INET4_BIND:
3705 case BPF_CGROUP_INET6_BIND:
3706 case BPF_CGROUP_INET4_POST_BIND:
3707 case BPF_CGROUP_INET6_POST_BIND:
3708 case BPF_CGROUP_INET4_CONNECT:
3709 case BPF_CGROUP_INET6_CONNECT:
3710 case BPF_CGROUP_INET4_GETPEERNAME:
3711 case BPF_CGROUP_INET6_GETPEERNAME:
3712 case BPF_CGROUP_INET4_GETSOCKNAME:
3713 case BPF_CGROUP_INET6_GETSOCKNAME:
3714 case BPF_CGROUP_UDP4_SENDMSG:
3715 case BPF_CGROUP_UDP6_SENDMSG:
3716 case BPF_CGROUP_UDP4_RECVMSG:
3717 case BPF_CGROUP_UDP6_RECVMSG:
3718 case BPF_CGROUP_SOCK_OPS:
3719 case BPF_CGROUP_DEVICE:
3720 case BPF_CGROUP_SYSCTL:
3721 case BPF_CGROUP_GETSOCKOPT:
3722 case BPF_CGROUP_SETSOCKOPT:
3723 case BPF_LSM_CGROUP:
3724 return cgroup_bpf_prog_query(attr, uattr);
3725 case BPF_LIRC_MODE2:
3726 return lirc_prog_query(attr, uattr);
3727 case BPF_FLOW_DISSECTOR:
3729 return netns_bpf_prog_query(attr, uattr);
3730 case BPF_SK_SKB_STREAM_PARSER:
3731 case BPF_SK_SKB_STREAM_VERDICT:
3732 case BPF_SK_MSG_VERDICT:
3733 case BPF_SK_SKB_VERDICT:
3734 return sock_map_bpf_prog_query(attr, uattr);
3740 #define BPF_PROG_TEST_RUN_LAST_FIELD test.batch_size
3742 static int bpf_prog_test_run(const union bpf_attr *attr,
3743 union bpf_attr __user *uattr)
3745 struct bpf_prog *prog;
3746 int ret = -ENOTSUPP;
3748 if (CHECK_ATTR(BPF_PROG_TEST_RUN))
3751 if ((attr->test.ctx_size_in && !attr->test.ctx_in) ||
3752 (!attr->test.ctx_size_in && attr->test.ctx_in))
3755 if ((attr->test.ctx_size_out && !attr->test.ctx_out) ||
3756 (!attr->test.ctx_size_out && attr->test.ctx_out))
3759 prog = bpf_prog_get(attr->test.prog_fd);
3761 return PTR_ERR(prog);
3763 if (prog->aux->ops->test_run)
3764 ret = prog->aux->ops->test_run(prog, attr, uattr);
3770 #define BPF_OBJ_GET_NEXT_ID_LAST_FIELD next_id
3772 static int bpf_obj_get_next_id(const union bpf_attr *attr,
3773 union bpf_attr __user *uattr,
3777 u32 next_id = attr->start_id;
3780 if (CHECK_ATTR(BPF_OBJ_GET_NEXT_ID) || next_id >= INT_MAX)
3783 if (!capable(CAP_SYS_ADMIN))
3788 if (!idr_get_next(idr, &next_id))
3790 spin_unlock_bh(lock);
3793 err = put_user(next_id, &uattr->next_id);
3798 struct bpf_map *bpf_map_get_curr_or_next(u32 *id)
3800 struct bpf_map *map;
3802 spin_lock_bh(&map_idr_lock);
3804 map = idr_get_next(&map_idr, id);
3806 map = __bpf_map_inc_not_zero(map, false);
3812 spin_unlock_bh(&map_idr_lock);
3817 struct bpf_prog *bpf_prog_get_curr_or_next(u32 *id)
3819 struct bpf_prog *prog;
3821 spin_lock_bh(&prog_idr_lock);
3823 prog = idr_get_next(&prog_idr, id);
3825 prog = bpf_prog_inc_not_zero(prog);
3831 spin_unlock_bh(&prog_idr_lock);
3836 #define BPF_PROG_GET_FD_BY_ID_LAST_FIELD prog_id
3838 struct bpf_prog *bpf_prog_by_id(u32 id)
3840 struct bpf_prog *prog;
3843 return ERR_PTR(-ENOENT);
3845 spin_lock_bh(&prog_idr_lock);
3846 prog = idr_find(&prog_idr, id);
3848 prog = bpf_prog_inc_not_zero(prog);
3850 prog = ERR_PTR(-ENOENT);
3851 spin_unlock_bh(&prog_idr_lock);
3855 static int bpf_prog_get_fd_by_id(const union bpf_attr *attr)
3857 struct bpf_prog *prog;
3858 u32 id = attr->prog_id;
3861 if (CHECK_ATTR(BPF_PROG_GET_FD_BY_ID))
3864 if (!capable(CAP_SYS_ADMIN))
3867 prog = bpf_prog_by_id(id);
3869 return PTR_ERR(prog);
3871 fd = bpf_prog_new_fd(prog);
3878 #define BPF_MAP_GET_FD_BY_ID_LAST_FIELD open_flags
3880 static int bpf_map_get_fd_by_id(const union bpf_attr *attr)
3882 struct bpf_map *map;
3883 u32 id = attr->map_id;
3887 if (CHECK_ATTR(BPF_MAP_GET_FD_BY_ID) ||
3888 attr->open_flags & ~BPF_OBJ_FLAG_MASK)
3891 if (!capable(CAP_SYS_ADMIN))
3894 f_flags = bpf_get_file_flag(attr->open_flags);
3898 spin_lock_bh(&map_idr_lock);
3899 map = idr_find(&map_idr, id);
3901 map = __bpf_map_inc_not_zero(map, true);
3903 map = ERR_PTR(-ENOENT);
3904 spin_unlock_bh(&map_idr_lock);
3907 return PTR_ERR(map);
3909 fd = bpf_map_new_fd(map, f_flags);
3911 bpf_map_put_with_uref(map);
3916 static const struct bpf_map *bpf_map_from_imm(const struct bpf_prog *prog,
3917 unsigned long addr, u32 *off,
3920 const struct bpf_map *map;
3923 mutex_lock(&prog->aux->used_maps_mutex);
3924 for (i = 0, *off = 0; i < prog->aux->used_map_cnt; i++) {
3925 map = prog->aux->used_maps[i];
3926 if (map == (void *)addr) {
3927 *type = BPF_PSEUDO_MAP_FD;
3930 if (!map->ops->map_direct_value_meta)
3932 if (!map->ops->map_direct_value_meta(map, addr, off)) {
3933 *type = BPF_PSEUDO_MAP_VALUE;
3940 mutex_unlock(&prog->aux->used_maps_mutex);
3944 static struct bpf_insn *bpf_insn_prepare_dump(const struct bpf_prog *prog,
3945 const struct cred *f_cred)
3947 const struct bpf_map *map;
3948 struct bpf_insn *insns;
3954 insns = kmemdup(prog->insnsi, bpf_prog_insn_size(prog),
3959 for (i = 0; i < prog->len; i++) {
3960 code = insns[i].code;
3962 if (code == (BPF_JMP | BPF_TAIL_CALL)) {
3963 insns[i].code = BPF_JMP | BPF_CALL;
3964 insns[i].imm = BPF_FUNC_tail_call;
3967 if (code == (BPF_JMP | BPF_CALL) ||
3968 code == (BPF_JMP | BPF_CALL_ARGS)) {
3969 if (code == (BPF_JMP | BPF_CALL_ARGS))
3970 insns[i].code = BPF_JMP | BPF_CALL;
3971 if (!bpf_dump_raw_ok(f_cred))
3975 if (BPF_CLASS(code) == BPF_LDX && BPF_MODE(code) == BPF_PROBE_MEM) {
3976 insns[i].code = BPF_LDX | BPF_SIZE(code) | BPF_MEM;
3980 if (code != (BPF_LD | BPF_IMM | BPF_DW))
3983 imm = ((u64)insns[i + 1].imm << 32) | (u32)insns[i].imm;
3984 map = bpf_map_from_imm(prog, imm, &off, &type);
3986 insns[i].src_reg = type;
3987 insns[i].imm = map->id;
3988 insns[i + 1].imm = off;
3996 static int set_info_rec_size(struct bpf_prog_info *info)
3999 * Ensure info.*_rec_size is the same as kernel expected size
4003 * Only allow zero *_rec_size if both _rec_size and _cnt are
4004 * zero. In this case, the kernel will set the expected
4005 * _rec_size back to the info.
4008 if ((info->nr_func_info || info->func_info_rec_size) &&
4009 info->func_info_rec_size != sizeof(struct bpf_func_info))
4012 if ((info->nr_line_info || info->line_info_rec_size) &&
4013 info->line_info_rec_size != sizeof(struct bpf_line_info))
4016 if ((info->nr_jited_line_info || info->jited_line_info_rec_size) &&
4017 info->jited_line_info_rec_size != sizeof(__u64))
4020 info->func_info_rec_size = sizeof(struct bpf_func_info);
4021 info->line_info_rec_size = sizeof(struct bpf_line_info);
4022 info->jited_line_info_rec_size = sizeof(__u64);
4027 static int bpf_prog_get_info_by_fd(struct file *file,
4028 struct bpf_prog *prog,
4029 const union bpf_attr *attr,
4030 union bpf_attr __user *uattr)
4032 struct bpf_prog_info __user *uinfo = u64_to_user_ptr(attr->info.info);
4033 struct btf *attach_btf = bpf_prog_get_target_btf(prog);
4034 struct bpf_prog_info info;
4035 u32 info_len = attr->info.info_len;
4036 struct bpf_prog_kstats stats;
4037 char __user *uinsns;
4041 err = bpf_check_uarg_tail_zero(USER_BPFPTR(uinfo), sizeof(info), info_len);
4044 info_len = min_t(u32, sizeof(info), info_len);
4046 memset(&info, 0, sizeof(info));
4047 if (copy_from_user(&info, uinfo, info_len))
4050 info.type = prog->type;
4051 info.id = prog->aux->id;
4052 info.load_time = prog->aux->load_time;
4053 info.created_by_uid = from_kuid_munged(current_user_ns(),
4054 prog->aux->user->uid);
4055 info.gpl_compatible = prog->gpl_compatible;
4057 memcpy(info.tag, prog->tag, sizeof(prog->tag));
4058 memcpy(info.name, prog->aux->name, sizeof(prog->aux->name));
4060 mutex_lock(&prog->aux->used_maps_mutex);
4061 ulen = info.nr_map_ids;
4062 info.nr_map_ids = prog->aux->used_map_cnt;
4063 ulen = min_t(u32, info.nr_map_ids, ulen);
4065 u32 __user *user_map_ids = u64_to_user_ptr(info.map_ids);
4068 for (i = 0; i < ulen; i++)
4069 if (put_user(prog->aux->used_maps[i]->id,
4070 &user_map_ids[i])) {
4071 mutex_unlock(&prog->aux->used_maps_mutex);
4075 mutex_unlock(&prog->aux->used_maps_mutex);
4077 err = set_info_rec_size(&info);
4081 bpf_prog_get_stats(prog, &stats);
4082 info.run_time_ns = stats.nsecs;
4083 info.run_cnt = stats.cnt;
4084 info.recursion_misses = stats.misses;
4086 info.verified_insns = prog->aux->verified_insns;
4088 if (!bpf_capable()) {
4089 info.jited_prog_len = 0;
4090 info.xlated_prog_len = 0;
4091 info.nr_jited_ksyms = 0;
4092 info.nr_jited_func_lens = 0;
4093 info.nr_func_info = 0;
4094 info.nr_line_info = 0;
4095 info.nr_jited_line_info = 0;
4099 ulen = info.xlated_prog_len;
4100 info.xlated_prog_len = bpf_prog_insn_size(prog);
4101 if (info.xlated_prog_len && ulen) {
4102 struct bpf_insn *insns_sanitized;
4105 if (prog->blinded && !bpf_dump_raw_ok(file->f_cred)) {
4106 info.xlated_prog_insns = 0;
4109 insns_sanitized = bpf_insn_prepare_dump(prog, file->f_cred);
4110 if (!insns_sanitized)
4112 uinsns = u64_to_user_ptr(info.xlated_prog_insns);
4113 ulen = min_t(u32, info.xlated_prog_len, ulen);
4114 fault = copy_to_user(uinsns, insns_sanitized, ulen);
4115 kfree(insns_sanitized);
4120 if (bpf_prog_is_offloaded(prog->aux)) {
4121 err = bpf_prog_offload_info_fill(&info, prog);
4127 /* NOTE: the following code is supposed to be skipped for offload.
4128 * bpf_prog_offload_info_fill() is the place to fill similar fields
4131 ulen = info.jited_prog_len;
4132 if (prog->aux->func_cnt) {
4135 info.jited_prog_len = 0;
4136 for (i = 0; i < prog->aux->func_cnt; i++)
4137 info.jited_prog_len += prog->aux->func[i]->jited_len;
4139 info.jited_prog_len = prog->jited_len;
4142 if (info.jited_prog_len && ulen) {
4143 if (bpf_dump_raw_ok(file->f_cred)) {
4144 uinsns = u64_to_user_ptr(info.jited_prog_insns);
4145 ulen = min_t(u32, info.jited_prog_len, ulen);
4147 /* for multi-function programs, copy the JITed
4148 * instructions for all the functions
4150 if (prog->aux->func_cnt) {
4155 for (i = 0; i < prog->aux->func_cnt; i++) {
4156 len = prog->aux->func[i]->jited_len;
4157 len = min_t(u32, len, free);
4158 img = (u8 *) prog->aux->func[i]->bpf_func;
4159 if (copy_to_user(uinsns, img, len))
4167 if (copy_to_user(uinsns, prog->bpf_func, ulen))
4171 info.jited_prog_insns = 0;
4175 ulen = info.nr_jited_ksyms;
4176 info.nr_jited_ksyms = prog->aux->func_cnt ? : 1;
4178 if (bpf_dump_raw_ok(file->f_cred)) {
4179 unsigned long ksym_addr;
4180 u64 __user *user_ksyms;
4183 /* copy the address of the kernel symbol
4184 * corresponding to each function
4186 ulen = min_t(u32, info.nr_jited_ksyms, ulen);
4187 user_ksyms = u64_to_user_ptr(info.jited_ksyms);
4188 if (prog->aux->func_cnt) {
4189 for (i = 0; i < ulen; i++) {
4190 ksym_addr = (unsigned long)
4191 prog->aux->func[i]->bpf_func;
4192 if (put_user((u64) ksym_addr,
4197 ksym_addr = (unsigned long) prog->bpf_func;
4198 if (put_user((u64) ksym_addr, &user_ksyms[0]))
4202 info.jited_ksyms = 0;
4206 ulen = info.nr_jited_func_lens;
4207 info.nr_jited_func_lens = prog->aux->func_cnt ? : 1;
4209 if (bpf_dump_raw_ok(file->f_cred)) {
4210 u32 __user *user_lens;
4213 /* copy the JITed image lengths for each function */
4214 ulen = min_t(u32, info.nr_jited_func_lens, ulen);
4215 user_lens = u64_to_user_ptr(info.jited_func_lens);
4216 if (prog->aux->func_cnt) {
4217 for (i = 0; i < ulen; i++) {
4219 prog->aux->func[i]->jited_len;
4220 if (put_user(func_len, &user_lens[i]))
4224 func_len = prog->jited_len;
4225 if (put_user(func_len, &user_lens[0]))
4229 info.jited_func_lens = 0;
4234 info.btf_id = btf_obj_id(prog->aux->btf);
4235 info.attach_btf_id = prog->aux->attach_btf_id;
4237 info.attach_btf_obj_id = btf_obj_id(attach_btf);
4239 ulen = info.nr_func_info;
4240 info.nr_func_info = prog->aux->func_info_cnt;
4241 if (info.nr_func_info && ulen) {
4242 char __user *user_finfo;
4244 user_finfo = u64_to_user_ptr(info.func_info);
4245 ulen = min_t(u32, info.nr_func_info, ulen);
4246 if (copy_to_user(user_finfo, prog->aux->func_info,
4247 info.func_info_rec_size * ulen))
4251 ulen = info.nr_line_info;
4252 info.nr_line_info = prog->aux->nr_linfo;
4253 if (info.nr_line_info && ulen) {
4254 __u8 __user *user_linfo;
4256 user_linfo = u64_to_user_ptr(info.line_info);
4257 ulen = min_t(u32, info.nr_line_info, ulen);
4258 if (copy_to_user(user_linfo, prog->aux->linfo,
4259 info.line_info_rec_size * ulen))
4263 ulen = info.nr_jited_line_info;
4264 if (prog->aux->jited_linfo)
4265 info.nr_jited_line_info = prog->aux->nr_linfo;
4267 info.nr_jited_line_info = 0;
4268 if (info.nr_jited_line_info && ulen) {
4269 if (bpf_dump_raw_ok(file->f_cred)) {
4270 unsigned long line_addr;
4271 __u64 __user *user_linfo;
4274 user_linfo = u64_to_user_ptr(info.jited_line_info);
4275 ulen = min_t(u32, info.nr_jited_line_info, ulen);
4276 for (i = 0; i < ulen; i++) {
4277 line_addr = (unsigned long)prog->aux->jited_linfo[i];
4278 if (put_user((__u64)line_addr, &user_linfo[i]))
4282 info.jited_line_info = 0;
4286 ulen = info.nr_prog_tags;
4287 info.nr_prog_tags = prog->aux->func_cnt ? : 1;
4289 __u8 __user (*user_prog_tags)[BPF_TAG_SIZE];
4292 user_prog_tags = u64_to_user_ptr(info.prog_tags);
4293 ulen = min_t(u32, info.nr_prog_tags, ulen);
4294 if (prog->aux->func_cnt) {
4295 for (i = 0; i < ulen; i++) {
4296 if (copy_to_user(user_prog_tags[i],
4297 prog->aux->func[i]->tag,
4302 if (copy_to_user(user_prog_tags[0],
4303 prog->tag, BPF_TAG_SIZE))
4309 if (copy_to_user(uinfo, &info, info_len) ||
4310 put_user(info_len, &uattr->info.info_len))
4316 static int bpf_map_get_info_by_fd(struct file *file,
4317 struct bpf_map *map,
4318 const union bpf_attr *attr,
4319 union bpf_attr __user *uattr)
4321 struct bpf_map_info __user *uinfo = u64_to_user_ptr(attr->info.info);
4322 struct bpf_map_info info;
4323 u32 info_len = attr->info.info_len;
4326 err = bpf_check_uarg_tail_zero(USER_BPFPTR(uinfo), sizeof(info), info_len);
4329 info_len = min_t(u32, sizeof(info), info_len);
4331 memset(&info, 0, sizeof(info));
4332 info.type = map->map_type;
4334 info.key_size = map->key_size;
4335 info.value_size = map->value_size;
4336 info.max_entries = map->max_entries;
4337 info.map_flags = map->map_flags;
4338 info.map_extra = map->map_extra;
4339 memcpy(info.name, map->name, sizeof(map->name));
4342 info.btf_id = btf_obj_id(map->btf);
4343 info.btf_key_type_id = map->btf_key_type_id;
4344 info.btf_value_type_id = map->btf_value_type_id;
4346 info.btf_vmlinux_value_type_id = map->btf_vmlinux_value_type_id;
4348 if (bpf_map_is_offloaded(map)) {
4349 err = bpf_map_offload_info_fill(&info, map);
4354 if (copy_to_user(uinfo, &info, info_len) ||
4355 put_user(info_len, &uattr->info.info_len))
4361 static int bpf_btf_get_info_by_fd(struct file *file,
4363 const union bpf_attr *attr,
4364 union bpf_attr __user *uattr)
4366 struct bpf_btf_info __user *uinfo = u64_to_user_ptr(attr->info.info);
4367 u32 info_len = attr->info.info_len;
4370 err = bpf_check_uarg_tail_zero(USER_BPFPTR(uinfo), sizeof(*uinfo), info_len);
4374 return btf_get_info_by_fd(btf, attr, uattr);
4377 static int bpf_link_get_info_by_fd(struct file *file,
4378 struct bpf_link *link,
4379 const union bpf_attr *attr,
4380 union bpf_attr __user *uattr)
4382 struct bpf_link_info __user *uinfo = u64_to_user_ptr(attr->info.info);
4383 struct bpf_link_info info;
4384 u32 info_len = attr->info.info_len;
4387 err = bpf_check_uarg_tail_zero(USER_BPFPTR(uinfo), sizeof(info), info_len);
4390 info_len = min_t(u32, sizeof(info), info_len);
4392 memset(&info, 0, sizeof(info));
4393 if (copy_from_user(&info, uinfo, info_len))
4396 info.type = link->type;
4399 info.prog_id = link->prog->aux->id;
4401 if (link->ops->fill_link_info) {
4402 err = link->ops->fill_link_info(link, &info);
4407 if (copy_to_user(uinfo, &info, info_len) ||
4408 put_user(info_len, &uattr->info.info_len))
4415 #define BPF_OBJ_GET_INFO_BY_FD_LAST_FIELD info.info
4417 static int bpf_obj_get_info_by_fd(const union bpf_attr *attr,
4418 union bpf_attr __user *uattr)
4420 int ufd = attr->info.bpf_fd;
4424 if (CHECK_ATTR(BPF_OBJ_GET_INFO_BY_FD))
4431 if (f.file->f_op == &bpf_prog_fops)
4432 err = bpf_prog_get_info_by_fd(f.file, f.file->private_data, attr,
4434 else if (f.file->f_op == &bpf_map_fops)
4435 err = bpf_map_get_info_by_fd(f.file, f.file->private_data, attr,
4437 else if (f.file->f_op == &btf_fops)
4438 err = bpf_btf_get_info_by_fd(f.file, f.file->private_data, attr, uattr);
4439 else if (f.file->f_op == &bpf_link_fops)
4440 err = bpf_link_get_info_by_fd(f.file, f.file->private_data,
4449 #define BPF_BTF_LOAD_LAST_FIELD btf_log_true_size
4451 static int bpf_btf_load(const union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size)
4453 if (CHECK_ATTR(BPF_BTF_LOAD))
4459 return btf_new_fd(attr, uattr, uattr_size);
4462 #define BPF_BTF_GET_FD_BY_ID_LAST_FIELD btf_id
4464 static int bpf_btf_get_fd_by_id(const union bpf_attr *attr)
4466 if (CHECK_ATTR(BPF_BTF_GET_FD_BY_ID))
4469 if (!capable(CAP_SYS_ADMIN))
4472 return btf_get_fd_by_id(attr->btf_id);
4475 static int bpf_task_fd_query_copy(const union bpf_attr *attr,
4476 union bpf_attr __user *uattr,
4477 u32 prog_id, u32 fd_type,
4478 const char *buf, u64 probe_offset,
4481 char __user *ubuf = u64_to_user_ptr(attr->task_fd_query.buf);
4482 u32 len = buf ? strlen(buf) : 0, input_len;
4485 if (put_user(len, &uattr->task_fd_query.buf_len))
4487 input_len = attr->task_fd_query.buf_len;
4488 if (input_len && ubuf) {
4490 /* nothing to copy, just make ubuf NULL terminated */
4493 if (put_user(zero, ubuf))
4495 } else if (input_len >= len + 1) {
4496 /* ubuf can hold the string with NULL terminator */
4497 if (copy_to_user(ubuf, buf, len + 1))
4500 /* ubuf cannot hold the string with NULL terminator,
4501 * do a partial copy with NULL terminator.
4506 if (copy_to_user(ubuf, buf, input_len - 1))
4508 if (put_user(zero, ubuf + input_len - 1))
4513 if (put_user(prog_id, &uattr->task_fd_query.prog_id) ||
4514 put_user(fd_type, &uattr->task_fd_query.fd_type) ||
4515 put_user(probe_offset, &uattr->task_fd_query.probe_offset) ||
4516 put_user(probe_addr, &uattr->task_fd_query.probe_addr))
4522 #define BPF_TASK_FD_QUERY_LAST_FIELD task_fd_query.probe_addr
4524 static int bpf_task_fd_query(const union bpf_attr *attr,
4525 union bpf_attr __user *uattr)
4527 pid_t pid = attr->task_fd_query.pid;
4528 u32 fd = attr->task_fd_query.fd;
4529 const struct perf_event *event;
4530 struct task_struct *task;
4534 if (CHECK_ATTR(BPF_TASK_FD_QUERY))
4537 if (!capable(CAP_SYS_ADMIN))
4540 if (attr->task_fd_query.flags != 0)
4544 task = get_pid_task(find_vpid(pid), PIDTYPE_PID);
4550 file = fget_task(task, fd);
4551 put_task_struct(task);
4555 if (file->f_op == &bpf_link_fops) {
4556 struct bpf_link *link = file->private_data;
4558 if (link->ops == &bpf_raw_tp_link_lops) {
4559 struct bpf_raw_tp_link *raw_tp =
4560 container_of(link, struct bpf_raw_tp_link, link);
4561 struct bpf_raw_event_map *btp = raw_tp->btp;
4563 err = bpf_task_fd_query_copy(attr, uattr,
4564 raw_tp->link.prog->aux->id,
4565 BPF_FD_TYPE_RAW_TRACEPOINT,
4566 btp->tp->name, 0, 0);
4572 event = perf_get_event(file);
4573 if (!IS_ERR(event)) {
4574 u64 probe_offset, probe_addr;
4575 u32 prog_id, fd_type;
4578 err = bpf_get_perf_event_info(event, &prog_id, &fd_type,
4579 &buf, &probe_offset,
4582 err = bpf_task_fd_query_copy(attr, uattr, prog_id,
4596 #define BPF_MAP_BATCH_LAST_FIELD batch.flags
4598 #define BPF_DO_BATCH(fn, ...) \
4604 err = fn(__VA_ARGS__); \
4607 static int bpf_map_do_batch(const union bpf_attr *attr,
4608 union bpf_attr __user *uattr,
4611 bool has_read = cmd == BPF_MAP_LOOKUP_BATCH ||
4612 cmd == BPF_MAP_LOOKUP_AND_DELETE_BATCH;
4613 bool has_write = cmd != BPF_MAP_LOOKUP_BATCH;
4614 struct bpf_map *map;
4618 if (CHECK_ATTR(BPF_MAP_BATCH))
4621 ufd = attr->batch.map_fd;
4623 map = __bpf_map_get(f);
4625 return PTR_ERR(map);
4627 bpf_map_write_active_inc(map);
4628 if (has_read && !(map_get_sys_perms(map, f) & FMODE_CAN_READ)) {
4632 if (has_write && !(map_get_sys_perms(map, f) & FMODE_CAN_WRITE)) {
4637 if (cmd == BPF_MAP_LOOKUP_BATCH)
4638 BPF_DO_BATCH(map->ops->map_lookup_batch, map, attr, uattr);
4639 else if (cmd == BPF_MAP_LOOKUP_AND_DELETE_BATCH)
4640 BPF_DO_BATCH(map->ops->map_lookup_and_delete_batch, map, attr, uattr);
4641 else if (cmd == BPF_MAP_UPDATE_BATCH)
4642 BPF_DO_BATCH(map->ops->map_update_batch, map, f.file, attr, uattr);
4644 BPF_DO_BATCH(map->ops->map_delete_batch, map, attr, uattr);
4647 bpf_map_write_active_dec(map);
4652 #define BPF_LINK_CREATE_LAST_FIELD link_create.kprobe_multi.cookies
4653 static int link_create(union bpf_attr *attr, bpfptr_t uattr)
4655 enum bpf_prog_type ptype;
4656 struct bpf_prog *prog;
4659 if (CHECK_ATTR(BPF_LINK_CREATE))
4662 if (attr->link_create.attach_type == BPF_STRUCT_OPS)
4663 return bpf_struct_ops_link_create(attr);
4665 prog = bpf_prog_get(attr->link_create.prog_fd);
4667 return PTR_ERR(prog);
4669 ret = bpf_prog_attach_check_attach_type(prog,
4670 attr->link_create.attach_type);
4674 switch (prog->type) {
4675 case BPF_PROG_TYPE_EXT:
4676 case BPF_PROG_TYPE_NETFILTER:
4678 case BPF_PROG_TYPE_PERF_EVENT:
4679 case BPF_PROG_TYPE_TRACEPOINT:
4680 if (attr->link_create.attach_type != BPF_PERF_EVENT) {
4685 case BPF_PROG_TYPE_KPROBE:
4686 if (attr->link_create.attach_type != BPF_PERF_EVENT &&
4687 attr->link_create.attach_type != BPF_TRACE_KPROBE_MULTI) {
4693 ptype = attach_type_to_prog_type(attr->link_create.attach_type);
4694 if (ptype == BPF_PROG_TYPE_UNSPEC || ptype != prog->type) {
4701 switch (prog->type) {
4702 case BPF_PROG_TYPE_CGROUP_SKB:
4703 case BPF_PROG_TYPE_CGROUP_SOCK:
4704 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
4705 case BPF_PROG_TYPE_SOCK_OPS:
4706 case BPF_PROG_TYPE_CGROUP_DEVICE:
4707 case BPF_PROG_TYPE_CGROUP_SYSCTL:
4708 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
4709 ret = cgroup_bpf_link_attach(attr, prog);
4711 case BPF_PROG_TYPE_EXT:
4712 ret = bpf_tracing_prog_attach(prog,
4713 attr->link_create.target_fd,
4714 attr->link_create.target_btf_id,
4715 attr->link_create.tracing.cookie);
4717 case BPF_PROG_TYPE_LSM:
4718 case BPF_PROG_TYPE_TRACING:
4719 if (attr->link_create.attach_type != prog->expected_attach_type) {
4723 if (prog->expected_attach_type == BPF_TRACE_RAW_TP)
4724 ret = bpf_raw_tp_link_attach(prog, NULL);
4725 else if (prog->expected_attach_type == BPF_TRACE_ITER)
4726 ret = bpf_iter_link_attach(attr, uattr, prog);
4727 else if (prog->expected_attach_type == BPF_LSM_CGROUP)
4728 ret = cgroup_bpf_link_attach(attr, prog);
4730 ret = bpf_tracing_prog_attach(prog,
4731 attr->link_create.target_fd,
4732 attr->link_create.target_btf_id,
4733 attr->link_create.tracing.cookie);
4735 case BPF_PROG_TYPE_FLOW_DISSECTOR:
4736 case BPF_PROG_TYPE_SK_LOOKUP:
4737 ret = netns_bpf_link_create(attr, prog);
4740 case BPF_PROG_TYPE_XDP:
4741 ret = bpf_xdp_link_attach(attr, prog);
4743 case BPF_PROG_TYPE_NETFILTER:
4744 ret = bpf_nf_link_attach(attr, prog);
4747 case BPF_PROG_TYPE_PERF_EVENT:
4748 case BPF_PROG_TYPE_TRACEPOINT:
4749 ret = bpf_perf_link_attach(attr, prog);
4751 case BPF_PROG_TYPE_KPROBE:
4752 if (attr->link_create.attach_type == BPF_PERF_EVENT)
4753 ret = bpf_perf_link_attach(attr, prog);
4755 ret = bpf_kprobe_multi_link_attach(attr, prog);
4767 static int link_update_map(struct bpf_link *link, union bpf_attr *attr)
4769 struct bpf_map *new_map, *old_map = NULL;
4772 new_map = bpf_map_get(attr->link_update.new_map_fd);
4773 if (IS_ERR(new_map))
4774 return PTR_ERR(new_map);
4776 if (attr->link_update.flags & BPF_F_REPLACE) {
4777 old_map = bpf_map_get(attr->link_update.old_map_fd);
4778 if (IS_ERR(old_map)) {
4779 ret = PTR_ERR(old_map);
4782 } else if (attr->link_update.old_map_fd) {
4787 ret = link->ops->update_map(link, new_map, old_map);
4790 bpf_map_put(old_map);
4792 bpf_map_put(new_map);
4796 #define BPF_LINK_UPDATE_LAST_FIELD link_update.old_prog_fd
4798 static int link_update(union bpf_attr *attr)
4800 struct bpf_prog *old_prog = NULL, *new_prog;
4801 struct bpf_link *link;
4805 if (CHECK_ATTR(BPF_LINK_UPDATE))
4808 flags = attr->link_update.flags;
4809 if (flags & ~BPF_F_REPLACE)
4812 link = bpf_link_get_from_fd(attr->link_update.link_fd);
4814 return PTR_ERR(link);
4816 if (link->ops->update_map) {
4817 ret = link_update_map(link, attr);
4821 new_prog = bpf_prog_get(attr->link_update.new_prog_fd);
4822 if (IS_ERR(new_prog)) {
4823 ret = PTR_ERR(new_prog);
4827 if (flags & BPF_F_REPLACE) {
4828 old_prog = bpf_prog_get(attr->link_update.old_prog_fd);
4829 if (IS_ERR(old_prog)) {
4830 ret = PTR_ERR(old_prog);
4834 } else if (attr->link_update.old_prog_fd) {
4839 if (link->ops->update_prog)
4840 ret = link->ops->update_prog(link, new_prog, old_prog);
4846 bpf_prog_put(old_prog);
4848 bpf_prog_put(new_prog);
4850 bpf_link_put_direct(link);
4854 #define BPF_LINK_DETACH_LAST_FIELD link_detach.link_fd
4856 static int link_detach(union bpf_attr *attr)
4858 struct bpf_link *link;
4861 if (CHECK_ATTR(BPF_LINK_DETACH))
4864 link = bpf_link_get_from_fd(attr->link_detach.link_fd);
4866 return PTR_ERR(link);
4868 if (link->ops->detach)
4869 ret = link->ops->detach(link);
4873 bpf_link_put_direct(link);
4877 static struct bpf_link *bpf_link_inc_not_zero(struct bpf_link *link)
4879 return atomic64_fetch_add_unless(&link->refcnt, 1, 0) ? link : ERR_PTR(-ENOENT);
4882 struct bpf_link *bpf_link_by_id(u32 id)
4884 struct bpf_link *link;
4887 return ERR_PTR(-ENOENT);
4889 spin_lock_bh(&link_idr_lock);
4890 /* before link is "settled", ID is 0, pretend it doesn't exist yet */
4891 link = idr_find(&link_idr, id);
4894 link = bpf_link_inc_not_zero(link);
4896 link = ERR_PTR(-EAGAIN);
4898 link = ERR_PTR(-ENOENT);
4900 spin_unlock_bh(&link_idr_lock);
4904 struct bpf_link *bpf_link_get_curr_or_next(u32 *id)
4906 struct bpf_link *link;
4908 spin_lock_bh(&link_idr_lock);
4910 link = idr_get_next(&link_idr, id);
4912 link = bpf_link_inc_not_zero(link);
4918 spin_unlock_bh(&link_idr_lock);
4923 #define BPF_LINK_GET_FD_BY_ID_LAST_FIELD link_id
4925 static int bpf_link_get_fd_by_id(const union bpf_attr *attr)
4927 struct bpf_link *link;
4928 u32 id = attr->link_id;
4931 if (CHECK_ATTR(BPF_LINK_GET_FD_BY_ID))
4934 if (!capable(CAP_SYS_ADMIN))
4937 link = bpf_link_by_id(id);
4939 return PTR_ERR(link);
4941 fd = bpf_link_new_fd(link);
4943 bpf_link_put_direct(link);
4948 DEFINE_MUTEX(bpf_stats_enabled_mutex);
4950 static int bpf_stats_release(struct inode *inode, struct file *file)
4952 mutex_lock(&bpf_stats_enabled_mutex);
4953 static_key_slow_dec(&bpf_stats_enabled_key.key);
4954 mutex_unlock(&bpf_stats_enabled_mutex);
4958 static const struct file_operations bpf_stats_fops = {
4959 .release = bpf_stats_release,
4962 static int bpf_enable_runtime_stats(void)
4966 mutex_lock(&bpf_stats_enabled_mutex);
4968 /* Set a very high limit to avoid overflow */
4969 if (static_key_count(&bpf_stats_enabled_key.key) > INT_MAX / 2) {
4970 mutex_unlock(&bpf_stats_enabled_mutex);
4974 fd = anon_inode_getfd("bpf-stats", &bpf_stats_fops, NULL, O_CLOEXEC);
4976 static_key_slow_inc(&bpf_stats_enabled_key.key);
4978 mutex_unlock(&bpf_stats_enabled_mutex);
4982 #define BPF_ENABLE_STATS_LAST_FIELD enable_stats.type
4984 static int bpf_enable_stats(union bpf_attr *attr)
4987 if (CHECK_ATTR(BPF_ENABLE_STATS))
4990 if (!capable(CAP_SYS_ADMIN))
4993 switch (attr->enable_stats.type) {
4994 case BPF_STATS_RUN_TIME:
4995 return bpf_enable_runtime_stats();
5002 #define BPF_ITER_CREATE_LAST_FIELD iter_create.flags
5004 static int bpf_iter_create(union bpf_attr *attr)
5006 struct bpf_link *link;
5009 if (CHECK_ATTR(BPF_ITER_CREATE))
5012 if (attr->iter_create.flags)
5015 link = bpf_link_get_from_fd(attr->iter_create.link_fd);
5017 return PTR_ERR(link);
5019 err = bpf_iter_new_fd(link);
5020 bpf_link_put_direct(link);
5025 #define BPF_PROG_BIND_MAP_LAST_FIELD prog_bind_map.flags
5027 static int bpf_prog_bind_map(union bpf_attr *attr)
5029 struct bpf_prog *prog;
5030 struct bpf_map *map;
5031 struct bpf_map **used_maps_old, **used_maps_new;
5034 if (CHECK_ATTR(BPF_PROG_BIND_MAP))
5037 if (attr->prog_bind_map.flags)
5040 prog = bpf_prog_get(attr->prog_bind_map.prog_fd);
5042 return PTR_ERR(prog);
5044 map = bpf_map_get(attr->prog_bind_map.map_fd);
5050 mutex_lock(&prog->aux->used_maps_mutex);
5052 used_maps_old = prog->aux->used_maps;
5054 for (i = 0; i < prog->aux->used_map_cnt; i++)
5055 if (used_maps_old[i] == map) {
5060 used_maps_new = kmalloc_array(prog->aux->used_map_cnt + 1,
5061 sizeof(used_maps_new[0]),
5063 if (!used_maps_new) {
5068 memcpy(used_maps_new, used_maps_old,
5069 sizeof(used_maps_old[0]) * prog->aux->used_map_cnt);
5070 used_maps_new[prog->aux->used_map_cnt] = map;
5072 prog->aux->used_map_cnt++;
5073 prog->aux->used_maps = used_maps_new;
5075 kfree(used_maps_old);
5078 mutex_unlock(&prog->aux->used_maps_mutex);
5087 static int __sys_bpf(int cmd, bpfptr_t uattr, unsigned int size)
5089 union bpf_attr attr;
5092 err = bpf_check_uarg_tail_zero(uattr, sizeof(attr), size);
5095 size = min_t(u32, size, sizeof(attr));
5097 /* copy attributes from user space, may be less than sizeof(bpf_attr) */
5098 memset(&attr, 0, sizeof(attr));
5099 if (copy_from_bpfptr(&attr, uattr, size) != 0)
5102 err = security_bpf(cmd, &attr, size);
5107 case BPF_MAP_CREATE:
5108 err = map_create(&attr);
5110 case BPF_MAP_LOOKUP_ELEM:
5111 err = map_lookup_elem(&attr);
5113 case BPF_MAP_UPDATE_ELEM:
5114 err = map_update_elem(&attr, uattr);
5116 case BPF_MAP_DELETE_ELEM:
5117 err = map_delete_elem(&attr, uattr);
5119 case BPF_MAP_GET_NEXT_KEY:
5120 err = map_get_next_key(&attr);
5122 case BPF_MAP_FREEZE:
5123 err = map_freeze(&attr);
5126 err = bpf_prog_load(&attr, uattr, size);
5129 err = bpf_obj_pin(&attr);
5132 err = bpf_obj_get(&attr);
5134 case BPF_PROG_ATTACH:
5135 err = bpf_prog_attach(&attr);
5137 case BPF_PROG_DETACH:
5138 err = bpf_prog_detach(&attr);
5140 case BPF_PROG_QUERY:
5141 err = bpf_prog_query(&attr, uattr.user);
5143 case BPF_PROG_TEST_RUN:
5144 err = bpf_prog_test_run(&attr, uattr.user);
5146 case BPF_PROG_GET_NEXT_ID:
5147 err = bpf_obj_get_next_id(&attr, uattr.user,
5148 &prog_idr, &prog_idr_lock);
5150 case BPF_MAP_GET_NEXT_ID:
5151 err = bpf_obj_get_next_id(&attr, uattr.user,
5152 &map_idr, &map_idr_lock);
5154 case BPF_BTF_GET_NEXT_ID:
5155 err = bpf_obj_get_next_id(&attr, uattr.user,
5156 &btf_idr, &btf_idr_lock);
5158 case BPF_PROG_GET_FD_BY_ID:
5159 err = bpf_prog_get_fd_by_id(&attr);
5161 case BPF_MAP_GET_FD_BY_ID:
5162 err = bpf_map_get_fd_by_id(&attr);
5164 case BPF_OBJ_GET_INFO_BY_FD:
5165 err = bpf_obj_get_info_by_fd(&attr, uattr.user);
5167 case BPF_RAW_TRACEPOINT_OPEN:
5168 err = bpf_raw_tracepoint_open(&attr);
5171 err = bpf_btf_load(&attr, uattr, size);
5173 case BPF_BTF_GET_FD_BY_ID:
5174 err = bpf_btf_get_fd_by_id(&attr);
5176 case BPF_TASK_FD_QUERY:
5177 err = bpf_task_fd_query(&attr, uattr.user);
5179 case BPF_MAP_LOOKUP_AND_DELETE_ELEM:
5180 err = map_lookup_and_delete_elem(&attr);
5182 case BPF_MAP_LOOKUP_BATCH:
5183 err = bpf_map_do_batch(&attr, uattr.user, BPF_MAP_LOOKUP_BATCH);
5185 case BPF_MAP_LOOKUP_AND_DELETE_BATCH:
5186 err = bpf_map_do_batch(&attr, uattr.user,
5187 BPF_MAP_LOOKUP_AND_DELETE_BATCH);
5189 case BPF_MAP_UPDATE_BATCH:
5190 err = bpf_map_do_batch(&attr, uattr.user, BPF_MAP_UPDATE_BATCH);
5192 case BPF_MAP_DELETE_BATCH:
5193 err = bpf_map_do_batch(&attr, uattr.user, BPF_MAP_DELETE_BATCH);
5195 case BPF_LINK_CREATE:
5196 err = link_create(&attr, uattr);
5198 case BPF_LINK_UPDATE:
5199 err = link_update(&attr);
5201 case BPF_LINK_GET_FD_BY_ID:
5202 err = bpf_link_get_fd_by_id(&attr);
5204 case BPF_LINK_GET_NEXT_ID:
5205 err = bpf_obj_get_next_id(&attr, uattr.user,
5206 &link_idr, &link_idr_lock);
5208 case BPF_ENABLE_STATS:
5209 err = bpf_enable_stats(&attr);
5211 case BPF_ITER_CREATE:
5212 err = bpf_iter_create(&attr);
5214 case BPF_LINK_DETACH:
5215 err = link_detach(&attr);
5217 case BPF_PROG_BIND_MAP:
5218 err = bpf_prog_bind_map(&attr);
5228 SYSCALL_DEFINE3(bpf, int, cmd, union bpf_attr __user *, uattr, unsigned int, size)
5230 return __sys_bpf(cmd, USER_BPFPTR(uattr), size);
5233 static bool syscall_prog_is_valid_access(int off, int size,
5234 enum bpf_access_type type,
5235 const struct bpf_prog *prog,
5236 struct bpf_insn_access_aux *info)
5238 if (off < 0 || off >= U16_MAX)
5240 if (off % size != 0)
5245 BPF_CALL_3(bpf_sys_bpf, int, cmd, union bpf_attr *, attr, u32, attr_size)
5248 case BPF_MAP_CREATE:
5249 case BPF_MAP_DELETE_ELEM:
5250 case BPF_MAP_UPDATE_ELEM:
5251 case BPF_MAP_FREEZE:
5252 case BPF_MAP_GET_FD_BY_ID:
5255 case BPF_LINK_CREATE:
5256 case BPF_RAW_TRACEPOINT_OPEN:
5261 return __sys_bpf(cmd, KERNEL_BPFPTR(attr), attr_size);
5265 /* To shut up -Wmissing-prototypes.
5266 * This function is used by the kernel light skeleton
5267 * to load bpf programs when modules are loaded or during kernel boot.
5268 * See tools/lib/bpf/skel_internal.h
5270 int kern_sys_bpf(int cmd, union bpf_attr *attr, unsigned int size);
5272 int kern_sys_bpf(int cmd, union bpf_attr *attr, unsigned int size)
5274 struct bpf_prog * __maybe_unused prog;
5275 struct bpf_tramp_run_ctx __maybe_unused run_ctx;
5278 #ifdef CONFIG_BPF_JIT /* __bpf_prog_enter_sleepable used by trampoline and JIT */
5279 case BPF_PROG_TEST_RUN:
5280 if (attr->test.data_in || attr->test.data_out ||
5281 attr->test.ctx_out || attr->test.duration ||
5282 attr->test.repeat || attr->test.flags)
5285 prog = bpf_prog_get_type(attr->test.prog_fd, BPF_PROG_TYPE_SYSCALL);
5287 return PTR_ERR(prog);
5289 if (attr->test.ctx_size_in < prog->aux->max_ctx_offset ||
5290 attr->test.ctx_size_in > U16_MAX) {
5295 run_ctx.bpf_cookie = 0;
5296 run_ctx.saved_run_ctx = NULL;
5297 if (!__bpf_prog_enter_sleepable_recur(prog, &run_ctx)) {
5298 /* recursion detected */
5302 attr->test.retval = bpf_prog_run(prog, (void *) (long) attr->test.ctx_in);
5303 __bpf_prog_exit_sleepable_recur(prog, 0 /* bpf_prog_run does runtime stats */,
5309 return ____bpf_sys_bpf(cmd, attr, size);
5312 EXPORT_SYMBOL(kern_sys_bpf);
5314 static const struct bpf_func_proto bpf_sys_bpf_proto = {
5315 .func = bpf_sys_bpf,
5317 .ret_type = RET_INTEGER,
5318 .arg1_type = ARG_ANYTHING,
5319 .arg2_type = ARG_PTR_TO_MEM | MEM_RDONLY,
5320 .arg3_type = ARG_CONST_SIZE,
5323 const struct bpf_func_proto * __weak
5324 tracing_prog_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
5326 return bpf_base_func_proto(func_id);
5329 BPF_CALL_1(bpf_sys_close, u32, fd)
5331 /* When bpf program calls this helper there should not be
5332 * an fdget() without matching completed fdput().
5333 * This helper is allowed in the following callchain only:
5334 * sys_bpf->prog_test_run->bpf_prog->bpf_sys_close
5336 return close_fd(fd);
5339 static const struct bpf_func_proto bpf_sys_close_proto = {
5340 .func = bpf_sys_close,
5342 .ret_type = RET_INTEGER,
5343 .arg1_type = ARG_ANYTHING,
5346 BPF_CALL_4(bpf_kallsyms_lookup_name, const char *, name, int, name_sz, int, flags, u64 *, res)
5351 if (name_sz <= 1 || name[name_sz - 1])
5354 if (!bpf_dump_raw_ok(current_cred()))
5357 *res = kallsyms_lookup_name(name);
5358 return *res ? 0 : -ENOENT;
5361 static const struct bpf_func_proto bpf_kallsyms_lookup_name_proto = {
5362 .func = bpf_kallsyms_lookup_name,
5364 .ret_type = RET_INTEGER,
5365 .arg1_type = ARG_PTR_TO_MEM,
5366 .arg2_type = ARG_CONST_SIZE_OR_ZERO,
5367 .arg3_type = ARG_ANYTHING,
5368 .arg4_type = ARG_PTR_TO_LONG,
5371 static const struct bpf_func_proto *
5372 syscall_prog_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
5375 case BPF_FUNC_sys_bpf:
5376 return !perfmon_capable() ? NULL : &bpf_sys_bpf_proto;
5377 case BPF_FUNC_btf_find_by_name_kind:
5378 return &bpf_btf_find_by_name_kind_proto;
5379 case BPF_FUNC_sys_close:
5380 return &bpf_sys_close_proto;
5381 case BPF_FUNC_kallsyms_lookup_name:
5382 return &bpf_kallsyms_lookup_name_proto;
5384 return tracing_prog_func_proto(func_id, prog);
5388 const struct bpf_verifier_ops bpf_syscall_verifier_ops = {
5389 .get_func_proto = syscall_prog_func_proto,
5390 .is_valid_access = syscall_prog_is_valid_access,
5393 const struct bpf_prog_ops bpf_syscall_prog_ops = {
5394 .test_run = bpf_prog_test_run_syscall,
5397 #ifdef CONFIG_SYSCTL
5398 static int bpf_stats_handler(struct ctl_table *table, int write,
5399 void *buffer, size_t *lenp, loff_t *ppos)
5401 struct static_key *key = (struct static_key *)table->data;
5402 static int saved_val;
5404 struct ctl_table tmp = {
5406 .maxlen = sizeof(val),
5407 .mode = table->mode,
5408 .extra1 = SYSCTL_ZERO,
5409 .extra2 = SYSCTL_ONE,
5412 if (write && !capable(CAP_SYS_ADMIN))
5415 mutex_lock(&bpf_stats_enabled_mutex);
5417 ret = proc_dointvec_minmax(&tmp, write, buffer, lenp, ppos);
5418 if (write && !ret && val != saved_val) {
5420 static_key_slow_inc(key);
5422 static_key_slow_dec(key);
5425 mutex_unlock(&bpf_stats_enabled_mutex);
5429 void __weak unpriv_ebpf_notify(int new_state)
5433 static int bpf_unpriv_handler(struct ctl_table *table, int write,
5434 void *buffer, size_t *lenp, loff_t *ppos)
5436 int ret, unpriv_enable = *(int *)table->data;
5437 bool locked_state = unpriv_enable == 1;
5438 struct ctl_table tmp = *table;
5440 if (write && !capable(CAP_SYS_ADMIN))
5443 tmp.data = &unpriv_enable;
5444 ret = proc_dointvec_minmax(&tmp, write, buffer, lenp, ppos);
5445 if (write && !ret) {
5446 if (locked_state && unpriv_enable != 1)
5448 *(int *)table->data = unpriv_enable;
5452 unpriv_ebpf_notify(unpriv_enable);
5457 static struct ctl_table bpf_syscall_table[] = {
5459 .procname = "unprivileged_bpf_disabled",
5460 .data = &sysctl_unprivileged_bpf_disabled,
5461 .maxlen = sizeof(sysctl_unprivileged_bpf_disabled),
5463 .proc_handler = bpf_unpriv_handler,
5464 .extra1 = SYSCTL_ZERO,
5465 .extra2 = SYSCTL_TWO,
5468 .procname = "bpf_stats_enabled",
5469 .data = &bpf_stats_enabled_key.key,
5471 .proc_handler = bpf_stats_handler,
5476 static int __init bpf_syscall_sysctl_init(void)
5478 register_sysctl_init("kernel", bpf_syscall_table);
5481 late_initcall(bpf_syscall_sysctl_init);
5482 #endif /* CONFIG_SYSCTL */