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_NETFILTER:
2485 if (expected_attach_type == BPF_NETFILTER)
2488 case BPF_PROG_TYPE_SYSCALL:
2489 case BPF_PROG_TYPE_EXT:
2490 if (expected_attach_type)
2498 static bool is_net_admin_prog_type(enum bpf_prog_type prog_type)
2500 switch (prog_type) {
2501 case BPF_PROG_TYPE_SCHED_CLS:
2502 case BPF_PROG_TYPE_SCHED_ACT:
2503 case BPF_PROG_TYPE_XDP:
2504 case BPF_PROG_TYPE_LWT_IN:
2505 case BPF_PROG_TYPE_LWT_OUT:
2506 case BPF_PROG_TYPE_LWT_XMIT:
2507 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
2508 case BPF_PROG_TYPE_SK_SKB:
2509 case BPF_PROG_TYPE_SK_MSG:
2510 case BPF_PROG_TYPE_FLOW_DISSECTOR:
2511 case BPF_PROG_TYPE_CGROUP_DEVICE:
2512 case BPF_PROG_TYPE_CGROUP_SOCK:
2513 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
2514 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
2515 case BPF_PROG_TYPE_CGROUP_SYSCTL:
2516 case BPF_PROG_TYPE_SOCK_OPS:
2517 case BPF_PROG_TYPE_EXT: /* extends any prog */
2518 case BPF_PROG_TYPE_NETFILTER:
2520 case BPF_PROG_TYPE_CGROUP_SKB:
2522 case BPF_PROG_TYPE_SK_REUSEPORT:
2523 /* equivalent to SOCKET_FILTER. need CAP_BPF only */
2529 static bool is_perfmon_prog_type(enum bpf_prog_type prog_type)
2531 switch (prog_type) {
2532 case BPF_PROG_TYPE_KPROBE:
2533 case BPF_PROG_TYPE_TRACEPOINT:
2534 case BPF_PROG_TYPE_PERF_EVENT:
2535 case BPF_PROG_TYPE_RAW_TRACEPOINT:
2536 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
2537 case BPF_PROG_TYPE_TRACING:
2538 case BPF_PROG_TYPE_LSM:
2539 case BPF_PROG_TYPE_STRUCT_OPS: /* has access to struct sock */
2540 case BPF_PROG_TYPE_EXT: /* extends any prog */
2547 /* last field in 'union bpf_attr' used by this command */
2548 #define BPF_PROG_LOAD_LAST_FIELD log_true_size
2550 static int bpf_prog_load(union bpf_attr *attr, bpfptr_t uattr, u32 uattr_size)
2552 enum bpf_prog_type type = attr->prog_type;
2553 struct bpf_prog *prog, *dst_prog = NULL;
2554 struct btf *attach_btf = NULL;
2558 if (CHECK_ATTR(BPF_PROG_LOAD))
2561 if (attr->prog_flags & ~(BPF_F_STRICT_ALIGNMENT |
2562 BPF_F_ANY_ALIGNMENT |
2563 BPF_F_TEST_STATE_FREQ |
2565 BPF_F_TEST_RND_HI32 |
2566 BPF_F_XDP_HAS_FRAGS |
2567 BPF_F_XDP_DEV_BOUND_ONLY))
2570 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS) &&
2571 (attr->prog_flags & BPF_F_ANY_ALIGNMENT) &&
2575 /* Intent here is for unprivileged_bpf_disabled to block BPF program
2576 * creation for unprivileged users; other actions depend
2577 * on fd availability and access to bpffs, so are dependent on
2578 * object creation success. Even with unprivileged BPF disabled,
2579 * capability checks are still carried out for these
2580 * and other operations.
2582 if (sysctl_unprivileged_bpf_disabled && !bpf_capable())
2585 if (attr->insn_cnt == 0 ||
2586 attr->insn_cnt > (bpf_capable() ? BPF_COMPLEXITY_LIMIT_INSNS : BPF_MAXINSNS))
2588 if (type != BPF_PROG_TYPE_SOCKET_FILTER &&
2589 type != BPF_PROG_TYPE_CGROUP_SKB &&
2593 if (is_net_admin_prog_type(type) && !capable(CAP_NET_ADMIN) && !capable(CAP_SYS_ADMIN))
2595 if (is_perfmon_prog_type(type) && !perfmon_capable())
2598 /* attach_prog_fd/attach_btf_obj_fd can specify fd of either bpf_prog
2599 * or btf, we need to check which one it is
2601 if (attr->attach_prog_fd) {
2602 dst_prog = bpf_prog_get(attr->attach_prog_fd);
2603 if (IS_ERR(dst_prog)) {
2605 attach_btf = btf_get_by_fd(attr->attach_btf_obj_fd);
2606 if (IS_ERR(attach_btf))
2608 if (!btf_is_kernel(attach_btf)) {
2609 /* attaching through specifying bpf_prog's BTF
2610 * objects directly might be supported eventually
2612 btf_put(attach_btf);
2616 } else if (attr->attach_btf_id) {
2617 /* fall back to vmlinux BTF, if BTF type ID is specified */
2618 attach_btf = bpf_get_btf_vmlinux();
2619 if (IS_ERR(attach_btf))
2620 return PTR_ERR(attach_btf);
2623 btf_get(attach_btf);
2626 bpf_prog_load_fixup_attach_type(attr);
2627 if (bpf_prog_load_check_attach(type, attr->expected_attach_type,
2628 attach_btf, attr->attach_btf_id,
2631 bpf_prog_put(dst_prog);
2633 btf_put(attach_btf);
2637 /* plain bpf_prog allocation */
2638 prog = bpf_prog_alloc(bpf_prog_size(attr->insn_cnt), GFP_USER);
2641 bpf_prog_put(dst_prog);
2643 btf_put(attach_btf);
2647 prog->expected_attach_type = attr->expected_attach_type;
2648 prog->aux->attach_btf = attach_btf;
2649 prog->aux->attach_btf_id = attr->attach_btf_id;
2650 prog->aux->dst_prog = dst_prog;
2651 prog->aux->dev_bound = !!attr->prog_ifindex;
2652 prog->aux->sleepable = attr->prog_flags & BPF_F_SLEEPABLE;
2653 prog->aux->xdp_has_frags = attr->prog_flags & BPF_F_XDP_HAS_FRAGS;
2655 err = security_bpf_prog_alloc(prog->aux);
2659 prog->aux->user = get_current_user();
2660 prog->len = attr->insn_cnt;
2663 if (copy_from_bpfptr(prog->insns,
2664 make_bpfptr(attr->insns, uattr.is_kernel),
2665 bpf_prog_insn_size(prog)) != 0)
2667 /* copy eBPF program license from user space */
2668 if (strncpy_from_bpfptr(license,
2669 make_bpfptr(attr->license, uattr.is_kernel),
2670 sizeof(license) - 1) < 0)
2672 license[sizeof(license) - 1] = 0;
2674 /* eBPF programs must be GPL compatible to use GPL-ed functions */
2675 prog->gpl_compatible = license_is_gpl_compatible(license) ? 1 : 0;
2677 prog->orig_prog = NULL;
2680 atomic64_set(&prog->aux->refcnt, 1);
2682 if (bpf_prog_is_dev_bound(prog->aux)) {
2683 err = bpf_prog_dev_bound_init(prog, attr);
2688 if (type == BPF_PROG_TYPE_EXT && dst_prog &&
2689 bpf_prog_is_dev_bound(dst_prog->aux)) {
2690 err = bpf_prog_dev_bound_inherit(prog, dst_prog);
2695 /* find program type: socket_filter vs tracing_filter */
2696 err = find_prog_type(type, prog);
2700 prog->aux->load_time = ktime_get_boottime_ns();
2701 err = bpf_obj_name_cpy(prog->aux->name, attr->prog_name,
2702 sizeof(attr->prog_name));
2706 /* run eBPF verifier */
2707 err = bpf_check(&prog, attr, uattr, uattr_size);
2709 goto free_used_maps;
2711 prog = bpf_prog_select_runtime(prog, &err);
2713 goto free_used_maps;
2715 err = bpf_prog_alloc_id(prog);
2717 goto free_used_maps;
2719 /* Upon success of bpf_prog_alloc_id(), the BPF prog is
2720 * effectively publicly exposed. However, retrieving via
2721 * bpf_prog_get_fd_by_id() will take another reference,
2722 * therefore it cannot be gone underneath us.
2724 * Only for the time /after/ successful bpf_prog_new_fd()
2725 * and before returning to userspace, we might just hold
2726 * one reference and any parallel close on that fd could
2727 * rip everything out. Hence, below notifications must
2728 * happen before bpf_prog_new_fd().
2730 * Also, any failure handling from this point onwards must
2731 * be using bpf_prog_put() given the program is exposed.
2733 bpf_prog_kallsyms_add(prog);
2734 perf_event_bpf_event(prog, PERF_BPF_EVENT_PROG_LOAD, 0);
2735 bpf_audit_prog(prog, BPF_AUDIT_LOAD);
2737 err = bpf_prog_new_fd(prog);
2743 /* In case we have subprogs, we need to wait for a grace
2744 * period before we can tear down JIT memory since symbols
2745 * are already exposed under kallsyms.
2747 __bpf_prog_put_noref(prog, prog->aux->func_cnt);
2750 free_uid(prog->aux->user);
2751 security_bpf_prog_free(prog->aux);
2753 if (prog->aux->attach_btf)
2754 btf_put(prog->aux->attach_btf);
2755 bpf_prog_free(prog);
2759 #define BPF_OBJ_LAST_FIELD path_fd
2761 static int bpf_obj_pin(const union bpf_attr *attr)
2765 if (CHECK_ATTR(BPF_OBJ) || attr->file_flags & ~BPF_F_PATH_FD)
2768 /* path_fd has to be accompanied by BPF_F_PATH_FD flag */
2769 if (!(attr->file_flags & BPF_F_PATH_FD) && attr->path_fd)
2772 path_fd = attr->file_flags & BPF_F_PATH_FD ? attr->path_fd : AT_FDCWD;
2773 return bpf_obj_pin_user(attr->bpf_fd, path_fd,
2774 u64_to_user_ptr(attr->pathname));
2777 static int bpf_obj_get(const union bpf_attr *attr)
2781 if (CHECK_ATTR(BPF_OBJ) || attr->bpf_fd != 0 ||
2782 attr->file_flags & ~(BPF_OBJ_FLAG_MASK | BPF_F_PATH_FD))
2785 /* path_fd has to be accompanied by BPF_F_PATH_FD flag */
2786 if (!(attr->file_flags & BPF_F_PATH_FD) && attr->path_fd)
2789 path_fd = attr->file_flags & BPF_F_PATH_FD ? attr->path_fd : AT_FDCWD;
2790 return bpf_obj_get_user(path_fd, u64_to_user_ptr(attr->pathname),
2794 void bpf_link_init(struct bpf_link *link, enum bpf_link_type type,
2795 const struct bpf_link_ops *ops, struct bpf_prog *prog)
2797 atomic64_set(&link->refcnt, 1);
2804 static void bpf_link_free_id(int id)
2809 spin_lock_bh(&link_idr_lock);
2810 idr_remove(&link_idr, id);
2811 spin_unlock_bh(&link_idr_lock);
2814 /* Clean up bpf_link and corresponding anon_inode file and FD. After
2815 * anon_inode is created, bpf_link can't be just kfree()'d due to deferred
2816 * anon_inode's release() call. This helper marksbpf_link as
2817 * defunct, releases anon_inode file and puts reserved FD. bpf_prog's refcnt
2818 * is not decremented, it's the responsibility of a calling code that failed
2819 * to complete bpf_link initialization.
2821 void bpf_link_cleanup(struct bpf_link_primer *primer)
2823 primer->link->prog = NULL;
2824 bpf_link_free_id(primer->id);
2826 put_unused_fd(primer->fd);
2829 void bpf_link_inc(struct bpf_link *link)
2831 atomic64_inc(&link->refcnt);
2834 /* bpf_link_free is guaranteed to be called from process context */
2835 static void bpf_link_free(struct bpf_link *link)
2837 bpf_link_free_id(link->id);
2839 /* detach BPF program, clean up used resources */
2840 link->ops->release(link);
2841 bpf_prog_put(link->prog);
2843 /* free bpf_link and its containing memory */
2844 link->ops->dealloc(link);
2847 static void bpf_link_put_deferred(struct work_struct *work)
2849 struct bpf_link *link = container_of(work, struct bpf_link, work);
2851 bpf_link_free(link);
2854 /* bpf_link_put might be called from atomic context. It needs to be called
2855 * from sleepable context in order to acquire sleeping locks during the process.
2857 void bpf_link_put(struct bpf_link *link)
2859 if (!atomic64_dec_and_test(&link->refcnt))
2862 INIT_WORK(&link->work, bpf_link_put_deferred);
2863 schedule_work(&link->work);
2865 EXPORT_SYMBOL(bpf_link_put);
2867 static void bpf_link_put_direct(struct bpf_link *link)
2869 if (!atomic64_dec_and_test(&link->refcnt))
2871 bpf_link_free(link);
2874 static int bpf_link_release(struct inode *inode, struct file *filp)
2876 struct bpf_link *link = filp->private_data;
2878 bpf_link_put_direct(link);
2882 #ifdef CONFIG_PROC_FS
2883 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type)
2884 #define BPF_MAP_TYPE(_id, _ops)
2885 #define BPF_LINK_TYPE(_id, _name) [_id] = #_name,
2886 static const char *bpf_link_type_strs[] = {
2887 [BPF_LINK_TYPE_UNSPEC] = "<invalid>",
2888 #include <linux/bpf_types.h>
2890 #undef BPF_PROG_TYPE
2892 #undef BPF_LINK_TYPE
2894 static void bpf_link_show_fdinfo(struct seq_file *m, struct file *filp)
2896 const struct bpf_link *link = filp->private_data;
2897 const struct bpf_prog *prog = link->prog;
2898 char prog_tag[sizeof(prog->tag) * 2 + 1] = { };
2903 bpf_link_type_strs[link->type],
2906 bin2hex(prog_tag, prog->tag, sizeof(prog->tag));
2913 if (link->ops->show_fdinfo)
2914 link->ops->show_fdinfo(link, m);
2918 static const struct file_operations bpf_link_fops = {
2919 #ifdef CONFIG_PROC_FS
2920 .show_fdinfo = bpf_link_show_fdinfo,
2922 .release = bpf_link_release,
2923 .read = bpf_dummy_read,
2924 .write = bpf_dummy_write,
2927 static int bpf_link_alloc_id(struct bpf_link *link)
2931 idr_preload(GFP_KERNEL);
2932 spin_lock_bh(&link_idr_lock);
2933 id = idr_alloc_cyclic(&link_idr, link, 1, INT_MAX, GFP_ATOMIC);
2934 spin_unlock_bh(&link_idr_lock);
2940 /* Prepare bpf_link to be exposed to user-space by allocating anon_inode file,
2941 * reserving unused FD and allocating ID from link_idr. This is to be paired
2942 * with bpf_link_settle() to install FD and ID and expose bpf_link to
2943 * user-space, if bpf_link is successfully attached. If not, bpf_link and
2944 * pre-allocated resources are to be freed with bpf_cleanup() call. All the
2945 * transient state is passed around in struct bpf_link_primer.
2946 * This is preferred way to create and initialize bpf_link, especially when
2947 * there are complicated and expensive operations in between creating bpf_link
2948 * itself and attaching it to BPF hook. By using bpf_link_prime() and
2949 * bpf_link_settle() kernel code using bpf_link doesn't have to perform
2950 * expensive (and potentially failing) roll back operations in a rare case
2951 * that file, FD, or ID can't be allocated.
2953 int bpf_link_prime(struct bpf_link *link, struct bpf_link_primer *primer)
2958 fd = get_unused_fd_flags(O_CLOEXEC);
2963 id = bpf_link_alloc_id(link);
2969 file = anon_inode_getfile("bpf_link", &bpf_link_fops, link, O_CLOEXEC);
2971 bpf_link_free_id(id);
2973 return PTR_ERR(file);
2976 primer->link = link;
2977 primer->file = file;
2983 int bpf_link_settle(struct bpf_link_primer *primer)
2985 /* make bpf_link fetchable by ID */
2986 spin_lock_bh(&link_idr_lock);
2987 primer->link->id = primer->id;
2988 spin_unlock_bh(&link_idr_lock);
2989 /* make bpf_link fetchable by FD */
2990 fd_install(primer->fd, primer->file);
2991 /* pass through installed FD */
2995 int bpf_link_new_fd(struct bpf_link *link)
2997 return anon_inode_getfd("bpf-link", &bpf_link_fops, link, O_CLOEXEC);
3000 struct bpf_link *bpf_link_get_from_fd(u32 ufd)
3002 struct fd f = fdget(ufd);
3003 struct bpf_link *link;
3006 return ERR_PTR(-EBADF);
3007 if (f.file->f_op != &bpf_link_fops) {
3009 return ERR_PTR(-EINVAL);
3012 link = f.file->private_data;
3018 EXPORT_SYMBOL(bpf_link_get_from_fd);
3020 static void bpf_tracing_link_release(struct bpf_link *link)
3022 struct bpf_tracing_link *tr_link =
3023 container_of(link, struct bpf_tracing_link, link.link);
3025 WARN_ON_ONCE(bpf_trampoline_unlink_prog(&tr_link->link,
3026 tr_link->trampoline));
3028 bpf_trampoline_put(tr_link->trampoline);
3030 /* tgt_prog is NULL if target is a kernel function */
3031 if (tr_link->tgt_prog)
3032 bpf_prog_put(tr_link->tgt_prog);
3035 static void bpf_tracing_link_dealloc(struct bpf_link *link)
3037 struct bpf_tracing_link *tr_link =
3038 container_of(link, struct bpf_tracing_link, link.link);
3043 static void bpf_tracing_link_show_fdinfo(const struct bpf_link *link,
3044 struct seq_file *seq)
3046 struct bpf_tracing_link *tr_link =
3047 container_of(link, struct bpf_tracing_link, link.link);
3048 u32 target_btf_id, target_obj_id;
3050 bpf_trampoline_unpack_key(tr_link->trampoline->key,
3051 &target_obj_id, &target_btf_id);
3053 "attach_type:\t%d\n"
3054 "target_obj_id:\t%u\n"
3055 "target_btf_id:\t%u\n",
3056 tr_link->attach_type,
3061 static int bpf_tracing_link_fill_link_info(const struct bpf_link *link,
3062 struct bpf_link_info *info)
3064 struct bpf_tracing_link *tr_link =
3065 container_of(link, struct bpf_tracing_link, link.link);
3067 info->tracing.attach_type = tr_link->attach_type;
3068 bpf_trampoline_unpack_key(tr_link->trampoline->key,
3069 &info->tracing.target_obj_id,
3070 &info->tracing.target_btf_id);
3075 static const struct bpf_link_ops bpf_tracing_link_lops = {
3076 .release = bpf_tracing_link_release,
3077 .dealloc = bpf_tracing_link_dealloc,
3078 .show_fdinfo = bpf_tracing_link_show_fdinfo,
3079 .fill_link_info = bpf_tracing_link_fill_link_info,
3082 static int bpf_tracing_prog_attach(struct bpf_prog *prog,
3087 struct bpf_link_primer link_primer;
3088 struct bpf_prog *tgt_prog = NULL;
3089 struct bpf_trampoline *tr = NULL;
3090 struct bpf_tracing_link *link;
3094 switch (prog->type) {
3095 case BPF_PROG_TYPE_TRACING:
3096 if (prog->expected_attach_type != BPF_TRACE_FENTRY &&
3097 prog->expected_attach_type != BPF_TRACE_FEXIT &&
3098 prog->expected_attach_type != BPF_MODIFY_RETURN) {
3103 case BPF_PROG_TYPE_EXT:
3104 if (prog->expected_attach_type != 0) {
3109 case BPF_PROG_TYPE_LSM:
3110 if (prog->expected_attach_type != BPF_LSM_MAC) {
3120 if (!!tgt_prog_fd != !!btf_id) {
3126 /* For now we only allow new targets for BPF_PROG_TYPE_EXT */
3127 if (prog->type != BPF_PROG_TYPE_EXT) {
3132 tgt_prog = bpf_prog_get(tgt_prog_fd);
3133 if (IS_ERR(tgt_prog)) {
3134 err = PTR_ERR(tgt_prog);
3139 key = bpf_trampoline_compute_key(tgt_prog, NULL, btf_id);
3142 link = kzalloc(sizeof(*link), GFP_USER);
3147 bpf_link_init(&link->link.link, BPF_LINK_TYPE_TRACING,
3148 &bpf_tracing_link_lops, prog);
3149 link->attach_type = prog->expected_attach_type;
3150 link->link.cookie = bpf_cookie;
3152 mutex_lock(&prog->aux->dst_mutex);
3154 /* There are a few possible cases here:
3156 * - if prog->aux->dst_trampoline is set, the program was just loaded
3157 * and not yet attached to anything, so we can use the values stored
3160 * - if prog->aux->dst_trampoline is NULL, the program has already been
3161 * attached to a target and its initial target was cleared (below)
3163 * - if tgt_prog != NULL, the caller specified tgt_prog_fd +
3164 * target_btf_id using the link_create API.
3166 * - if tgt_prog == NULL when this function was called using the old
3167 * raw_tracepoint_open API, and we need a target from prog->aux
3169 * - if prog->aux->dst_trampoline and tgt_prog is NULL, the program
3170 * was detached and is going for re-attachment.
3172 if (!prog->aux->dst_trampoline && !tgt_prog) {
3174 * Allow re-attach for TRACING and LSM programs. If it's
3175 * currently linked, bpf_trampoline_link_prog will fail.
3176 * EXT programs need to specify tgt_prog_fd, so they
3177 * re-attach in separate code path.
3179 if (prog->type != BPF_PROG_TYPE_TRACING &&
3180 prog->type != BPF_PROG_TYPE_LSM) {
3184 btf_id = prog->aux->attach_btf_id;
3185 key = bpf_trampoline_compute_key(NULL, prog->aux->attach_btf, btf_id);
3188 if (!prog->aux->dst_trampoline ||
3189 (key && key != prog->aux->dst_trampoline->key)) {
3190 /* If there is no saved target, or the specified target is
3191 * different from the destination specified at load time, we
3192 * need a new trampoline and a check for compatibility
3194 struct bpf_attach_target_info tgt_info = {};
3196 err = bpf_check_attach_target(NULL, prog, tgt_prog, btf_id,
3201 if (tgt_info.tgt_mod) {
3202 module_put(prog->aux->mod);
3203 prog->aux->mod = tgt_info.tgt_mod;
3206 tr = bpf_trampoline_get(key, &tgt_info);
3212 /* The caller didn't specify a target, or the target was the
3213 * same as the destination supplied during program load. This
3214 * means we can reuse the trampoline and reference from program
3215 * load time, and there is no need to allocate a new one. This
3216 * can only happen once for any program, as the saved values in
3217 * prog->aux are cleared below.
3219 tr = prog->aux->dst_trampoline;
3220 tgt_prog = prog->aux->dst_prog;
3223 err = bpf_link_prime(&link->link.link, &link_primer);
3227 err = bpf_trampoline_link_prog(&link->link, tr);
3229 bpf_link_cleanup(&link_primer);
3234 link->tgt_prog = tgt_prog;
3235 link->trampoline = tr;
3237 /* Always clear the trampoline and target prog from prog->aux to make
3238 * sure the original attach destination is not kept alive after a
3239 * program is (re-)attached to another target.
3241 if (prog->aux->dst_prog &&
3242 (tgt_prog_fd || tr != prog->aux->dst_trampoline))
3243 /* got extra prog ref from syscall, or attaching to different prog */
3244 bpf_prog_put(prog->aux->dst_prog);
3245 if (prog->aux->dst_trampoline && tr != prog->aux->dst_trampoline)
3246 /* we allocated a new trampoline, so free the old one */
3247 bpf_trampoline_put(prog->aux->dst_trampoline);
3249 prog->aux->dst_prog = NULL;
3250 prog->aux->dst_trampoline = NULL;
3251 mutex_unlock(&prog->aux->dst_mutex);
3253 return bpf_link_settle(&link_primer);
3255 if (tr && tr != prog->aux->dst_trampoline)
3256 bpf_trampoline_put(tr);
3257 mutex_unlock(&prog->aux->dst_mutex);
3260 if (tgt_prog_fd && tgt_prog)
3261 bpf_prog_put(tgt_prog);
3265 struct bpf_raw_tp_link {
3266 struct bpf_link link;
3267 struct bpf_raw_event_map *btp;
3270 static void bpf_raw_tp_link_release(struct bpf_link *link)
3272 struct bpf_raw_tp_link *raw_tp =
3273 container_of(link, struct bpf_raw_tp_link, link);
3275 bpf_probe_unregister(raw_tp->btp, raw_tp->link.prog);
3276 bpf_put_raw_tracepoint(raw_tp->btp);
3279 static void bpf_raw_tp_link_dealloc(struct bpf_link *link)
3281 struct bpf_raw_tp_link *raw_tp =
3282 container_of(link, struct bpf_raw_tp_link, link);
3287 static void bpf_raw_tp_link_show_fdinfo(const struct bpf_link *link,
3288 struct seq_file *seq)
3290 struct bpf_raw_tp_link *raw_tp_link =
3291 container_of(link, struct bpf_raw_tp_link, link);
3295 raw_tp_link->btp->tp->name);
3298 static int bpf_raw_tp_link_fill_link_info(const struct bpf_link *link,
3299 struct bpf_link_info *info)
3301 struct bpf_raw_tp_link *raw_tp_link =
3302 container_of(link, struct bpf_raw_tp_link, link);
3303 char __user *ubuf = u64_to_user_ptr(info->raw_tracepoint.tp_name);
3304 const char *tp_name = raw_tp_link->btp->tp->name;
3305 u32 ulen = info->raw_tracepoint.tp_name_len;
3306 size_t tp_len = strlen(tp_name);
3311 info->raw_tracepoint.tp_name_len = tp_len + 1;
3316 if (ulen >= tp_len + 1) {
3317 if (copy_to_user(ubuf, tp_name, tp_len + 1))
3322 if (copy_to_user(ubuf, tp_name, ulen - 1))
3324 if (put_user(zero, ubuf + ulen - 1))
3332 static const struct bpf_link_ops bpf_raw_tp_link_lops = {
3333 .release = bpf_raw_tp_link_release,
3334 .dealloc = bpf_raw_tp_link_dealloc,
3335 .show_fdinfo = bpf_raw_tp_link_show_fdinfo,
3336 .fill_link_info = bpf_raw_tp_link_fill_link_info,
3339 #ifdef CONFIG_PERF_EVENTS
3340 struct bpf_perf_link {
3341 struct bpf_link link;
3342 struct file *perf_file;
3345 static void bpf_perf_link_release(struct bpf_link *link)
3347 struct bpf_perf_link *perf_link = container_of(link, struct bpf_perf_link, link);
3348 struct perf_event *event = perf_link->perf_file->private_data;
3350 perf_event_free_bpf_prog(event);
3351 fput(perf_link->perf_file);
3354 static void bpf_perf_link_dealloc(struct bpf_link *link)
3356 struct bpf_perf_link *perf_link = container_of(link, struct bpf_perf_link, link);
3361 static const struct bpf_link_ops bpf_perf_link_lops = {
3362 .release = bpf_perf_link_release,
3363 .dealloc = bpf_perf_link_dealloc,
3366 static int bpf_perf_link_attach(const union bpf_attr *attr, struct bpf_prog *prog)
3368 struct bpf_link_primer link_primer;
3369 struct bpf_perf_link *link;
3370 struct perf_event *event;
3371 struct file *perf_file;
3374 if (attr->link_create.flags)
3377 perf_file = perf_event_get(attr->link_create.target_fd);
3378 if (IS_ERR(perf_file))
3379 return PTR_ERR(perf_file);
3381 link = kzalloc(sizeof(*link), GFP_USER);
3386 bpf_link_init(&link->link, BPF_LINK_TYPE_PERF_EVENT, &bpf_perf_link_lops, prog);
3387 link->perf_file = perf_file;
3389 err = bpf_link_prime(&link->link, &link_primer);
3395 event = perf_file->private_data;
3396 err = perf_event_set_bpf_prog(event, prog, attr->link_create.perf_event.bpf_cookie);
3398 bpf_link_cleanup(&link_primer);
3401 /* perf_event_set_bpf_prog() doesn't take its own refcnt on prog */
3404 return bpf_link_settle(&link_primer);
3411 static int bpf_perf_link_attach(const union bpf_attr *attr, struct bpf_prog *prog)
3415 #endif /* CONFIG_PERF_EVENTS */
3417 static int bpf_raw_tp_link_attach(struct bpf_prog *prog,
3418 const char __user *user_tp_name)
3420 struct bpf_link_primer link_primer;
3421 struct bpf_raw_tp_link *link;
3422 struct bpf_raw_event_map *btp;
3423 const char *tp_name;
3427 switch (prog->type) {
3428 case BPF_PROG_TYPE_TRACING:
3429 case BPF_PROG_TYPE_EXT:
3430 case BPF_PROG_TYPE_LSM:
3432 /* The attach point for this category of programs
3433 * should be specified via btf_id during program load.
3436 if (prog->type == BPF_PROG_TYPE_TRACING &&
3437 prog->expected_attach_type == BPF_TRACE_RAW_TP) {
3438 tp_name = prog->aux->attach_func_name;
3441 return bpf_tracing_prog_attach(prog, 0, 0, 0);
3442 case BPF_PROG_TYPE_RAW_TRACEPOINT:
3443 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
3444 if (strncpy_from_user(buf, user_tp_name, sizeof(buf) - 1) < 0)
3446 buf[sizeof(buf) - 1] = 0;
3453 btp = bpf_get_raw_tracepoint(tp_name);
3457 link = kzalloc(sizeof(*link), GFP_USER);
3462 bpf_link_init(&link->link, BPF_LINK_TYPE_RAW_TRACEPOINT,
3463 &bpf_raw_tp_link_lops, prog);
3466 err = bpf_link_prime(&link->link, &link_primer);
3472 err = bpf_probe_register(link->btp, prog);
3474 bpf_link_cleanup(&link_primer);
3478 return bpf_link_settle(&link_primer);
3481 bpf_put_raw_tracepoint(btp);
3485 #define BPF_RAW_TRACEPOINT_OPEN_LAST_FIELD raw_tracepoint.prog_fd
3487 static int bpf_raw_tracepoint_open(const union bpf_attr *attr)
3489 struct bpf_prog *prog;
3492 if (CHECK_ATTR(BPF_RAW_TRACEPOINT_OPEN))
3495 prog = bpf_prog_get(attr->raw_tracepoint.prog_fd);
3497 return PTR_ERR(prog);
3499 fd = bpf_raw_tp_link_attach(prog, u64_to_user_ptr(attr->raw_tracepoint.name));
3505 static int bpf_prog_attach_check_attach_type(const struct bpf_prog *prog,
3506 enum bpf_attach_type attach_type)
3508 switch (prog->type) {
3509 case BPF_PROG_TYPE_CGROUP_SOCK:
3510 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
3511 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3512 case BPF_PROG_TYPE_SK_LOOKUP:
3513 return attach_type == prog->expected_attach_type ? 0 : -EINVAL;
3514 case BPF_PROG_TYPE_CGROUP_SKB:
3515 if (!capable(CAP_NET_ADMIN))
3516 /* cg-skb progs can be loaded by unpriv user.
3517 * check permissions at attach time.
3520 return prog->enforce_expected_attach_type &&
3521 prog->expected_attach_type != attach_type ?
3523 case BPF_PROG_TYPE_KPROBE:
3524 if (prog->expected_attach_type == BPF_TRACE_KPROBE_MULTI &&
3525 attach_type != BPF_TRACE_KPROBE_MULTI)
3533 static enum bpf_prog_type
3534 attach_type_to_prog_type(enum bpf_attach_type attach_type)
3536 switch (attach_type) {
3537 case BPF_CGROUP_INET_INGRESS:
3538 case BPF_CGROUP_INET_EGRESS:
3539 return BPF_PROG_TYPE_CGROUP_SKB;
3540 case BPF_CGROUP_INET_SOCK_CREATE:
3541 case BPF_CGROUP_INET_SOCK_RELEASE:
3542 case BPF_CGROUP_INET4_POST_BIND:
3543 case BPF_CGROUP_INET6_POST_BIND:
3544 return BPF_PROG_TYPE_CGROUP_SOCK;
3545 case BPF_CGROUP_INET4_BIND:
3546 case BPF_CGROUP_INET6_BIND:
3547 case BPF_CGROUP_INET4_CONNECT:
3548 case BPF_CGROUP_INET6_CONNECT:
3549 case BPF_CGROUP_INET4_GETPEERNAME:
3550 case BPF_CGROUP_INET6_GETPEERNAME:
3551 case BPF_CGROUP_INET4_GETSOCKNAME:
3552 case BPF_CGROUP_INET6_GETSOCKNAME:
3553 case BPF_CGROUP_UDP4_SENDMSG:
3554 case BPF_CGROUP_UDP6_SENDMSG:
3555 case BPF_CGROUP_UDP4_RECVMSG:
3556 case BPF_CGROUP_UDP6_RECVMSG:
3557 return BPF_PROG_TYPE_CGROUP_SOCK_ADDR;
3558 case BPF_CGROUP_SOCK_OPS:
3559 return BPF_PROG_TYPE_SOCK_OPS;
3560 case BPF_CGROUP_DEVICE:
3561 return BPF_PROG_TYPE_CGROUP_DEVICE;
3562 case BPF_SK_MSG_VERDICT:
3563 return BPF_PROG_TYPE_SK_MSG;
3564 case BPF_SK_SKB_STREAM_PARSER:
3565 case BPF_SK_SKB_STREAM_VERDICT:
3566 case BPF_SK_SKB_VERDICT:
3567 return BPF_PROG_TYPE_SK_SKB;
3568 case BPF_LIRC_MODE2:
3569 return BPF_PROG_TYPE_LIRC_MODE2;
3570 case BPF_FLOW_DISSECTOR:
3571 return BPF_PROG_TYPE_FLOW_DISSECTOR;
3572 case BPF_CGROUP_SYSCTL:
3573 return BPF_PROG_TYPE_CGROUP_SYSCTL;
3574 case BPF_CGROUP_GETSOCKOPT:
3575 case BPF_CGROUP_SETSOCKOPT:
3576 return BPF_PROG_TYPE_CGROUP_SOCKOPT;
3577 case BPF_TRACE_ITER:
3578 case BPF_TRACE_RAW_TP:
3579 case BPF_TRACE_FENTRY:
3580 case BPF_TRACE_FEXIT:
3581 case BPF_MODIFY_RETURN:
3582 return BPF_PROG_TYPE_TRACING;
3584 return BPF_PROG_TYPE_LSM;
3586 return BPF_PROG_TYPE_SK_LOOKUP;
3588 return BPF_PROG_TYPE_XDP;
3589 case BPF_LSM_CGROUP:
3590 return BPF_PROG_TYPE_LSM;
3592 return BPF_PROG_TYPE_UNSPEC;
3596 #define BPF_PROG_ATTACH_LAST_FIELD replace_bpf_fd
3598 #define BPF_F_ATTACH_MASK \
3599 (BPF_F_ALLOW_OVERRIDE | BPF_F_ALLOW_MULTI | BPF_F_REPLACE)
3601 static int bpf_prog_attach(const union bpf_attr *attr)
3603 enum bpf_prog_type ptype;
3604 struct bpf_prog *prog;
3607 if (CHECK_ATTR(BPF_PROG_ATTACH))
3610 if (attr->attach_flags & ~BPF_F_ATTACH_MASK)
3613 ptype = attach_type_to_prog_type(attr->attach_type);
3614 if (ptype == BPF_PROG_TYPE_UNSPEC)
3617 prog = bpf_prog_get_type(attr->attach_bpf_fd, ptype);
3619 return PTR_ERR(prog);
3621 if (bpf_prog_attach_check_attach_type(prog, attr->attach_type)) {
3627 case BPF_PROG_TYPE_SK_SKB:
3628 case BPF_PROG_TYPE_SK_MSG:
3629 ret = sock_map_get_from_fd(attr, prog);
3631 case BPF_PROG_TYPE_LIRC_MODE2:
3632 ret = lirc_prog_attach(attr, prog);
3634 case BPF_PROG_TYPE_FLOW_DISSECTOR:
3635 ret = netns_bpf_prog_attach(attr, prog);
3637 case BPF_PROG_TYPE_CGROUP_DEVICE:
3638 case BPF_PROG_TYPE_CGROUP_SKB:
3639 case BPF_PROG_TYPE_CGROUP_SOCK:
3640 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
3641 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3642 case BPF_PROG_TYPE_CGROUP_SYSCTL:
3643 case BPF_PROG_TYPE_SOCK_OPS:
3644 case BPF_PROG_TYPE_LSM:
3645 if (ptype == BPF_PROG_TYPE_LSM &&
3646 prog->expected_attach_type != BPF_LSM_CGROUP)
3649 ret = cgroup_bpf_prog_attach(attr, ptype, prog);
3660 #define BPF_PROG_DETACH_LAST_FIELD attach_type
3662 static int bpf_prog_detach(const union bpf_attr *attr)
3664 enum bpf_prog_type ptype;
3666 if (CHECK_ATTR(BPF_PROG_DETACH))
3669 ptype = attach_type_to_prog_type(attr->attach_type);
3672 case BPF_PROG_TYPE_SK_MSG:
3673 case BPF_PROG_TYPE_SK_SKB:
3674 return sock_map_prog_detach(attr, ptype);
3675 case BPF_PROG_TYPE_LIRC_MODE2:
3676 return lirc_prog_detach(attr);
3677 case BPF_PROG_TYPE_FLOW_DISSECTOR:
3678 return netns_bpf_prog_detach(attr, ptype);
3679 case BPF_PROG_TYPE_CGROUP_DEVICE:
3680 case BPF_PROG_TYPE_CGROUP_SKB:
3681 case BPF_PROG_TYPE_CGROUP_SOCK:
3682 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
3683 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3684 case BPF_PROG_TYPE_CGROUP_SYSCTL:
3685 case BPF_PROG_TYPE_SOCK_OPS:
3686 case BPF_PROG_TYPE_LSM:
3687 return cgroup_bpf_prog_detach(attr, ptype);
3693 #define BPF_PROG_QUERY_LAST_FIELD query.prog_attach_flags
3695 static int bpf_prog_query(const union bpf_attr *attr,
3696 union bpf_attr __user *uattr)
3698 if (!capable(CAP_NET_ADMIN))
3700 if (CHECK_ATTR(BPF_PROG_QUERY))
3702 if (attr->query.query_flags & ~BPF_F_QUERY_EFFECTIVE)
3705 switch (attr->query.attach_type) {
3706 case BPF_CGROUP_INET_INGRESS:
3707 case BPF_CGROUP_INET_EGRESS:
3708 case BPF_CGROUP_INET_SOCK_CREATE:
3709 case BPF_CGROUP_INET_SOCK_RELEASE:
3710 case BPF_CGROUP_INET4_BIND:
3711 case BPF_CGROUP_INET6_BIND:
3712 case BPF_CGROUP_INET4_POST_BIND:
3713 case BPF_CGROUP_INET6_POST_BIND:
3714 case BPF_CGROUP_INET4_CONNECT:
3715 case BPF_CGROUP_INET6_CONNECT:
3716 case BPF_CGROUP_INET4_GETPEERNAME:
3717 case BPF_CGROUP_INET6_GETPEERNAME:
3718 case BPF_CGROUP_INET4_GETSOCKNAME:
3719 case BPF_CGROUP_INET6_GETSOCKNAME:
3720 case BPF_CGROUP_UDP4_SENDMSG:
3721 case BPF_CGROUP_UDP6_SENDMSG:
3722 case BPF_CGROUP_UDP4_RECVMSG:
3723 case BPF_CGROUP_UDP6_RECVMSG:
3724 case BPF_CGROUP_SOCK_OPS:
3725 case BPF_CGROUP_DEVICE:
3726 case BPF_CGROUP_SYSCTL:
3727 case BPF_CGROUP_GETSOCKOPT:
3728 case BPF_CGROUP_SETSOCKOPT:
3729 case BPF_LSM_CGROUP:
3730 return cgroup_bpf_prog_query(attr, uattr);
3731 case BPF_LIRC_MODE2:
3732 return lirc_prog_query(attr, uattr);
3733 case BPF_FLOW_DISSECTOR:
3735 return netns_bpf_prog_query(attr, uattr);
3736 case BPF_SK_SKB_STREAM_PARSER:
3737 case BPF_SK_SKB_STREAM_VERDICT:
3738 case BPF_SK_MSG_VERDICT:
3739 case BPF_SK_SKB_VERDICT:
3740 return sock_map_bpf_prog_query(attr, uattr);
3746 #define BPF_PROG_TEST_RUN_LAST_FIELD test.batch_size
3748 static int bpf_prog_test_run(const union bpf_attr *attr,
3749 union bpf_attr __user *uattr)
3751 struct bpf_prog *prog;
3752 int ret = -ENOTSUPP;
3754 if (CHECK_ATTR(BPF_PROG_TEST_RUN))
3757 if ((attr->test.ctx_size_in && !attr->test.ctx_in) ||
3758 (!attr->test.ctx_size_in && attr->test.ctx_in))
3761 if ((attr->test.ctx_size_out && !attr->test.ctx_out) ||
3762 (!attr->test.ctx_size_out && attr->test.ctx_out))
3765 prog = bpf_prog_get(attr->test.prog_fd);
3767 return PTR_ERR(prog);
3769 if (prog->aux->ops->test_run)
3770 ret = prog->aux->ops->test_run(prog, attr, uattr);
3776 #define BPF_OBJ_GET_NEXT_ID_LAST_FIELD next_id
3778 static int bpf_obj_get_next_id(const union bpf_attr *attr,
3779 union bpf_attr __user *uattr,
3783 u32 next_id = attr->start_id;
3786 if (CHECK_ATTR(BPF_OBJ_GET_NEXT_ID) || next_id >= INT_MAX)
3789 if (!capable(CAP_SYS_ADMIN))
3794 if (!idr_get_next(idr, &next_id))
3796 spin_unlock_bh(lock);
3799 err = put_user(next_id, &uattr->next_id);
3804 struct bpf_map *bpf_map_get_curr_or_next(u32 *id)
3806 struct bpf_map *map;
3808 spin_lock_bh(&map_idr_lock);
3810 map = idr_get_next(&map_idr, id);
3812 map = __bpf_map_inc_not_zero(map, false);
3818 spin_unlock_bh(&map_idr_lock);
3823 struct bpf_prog *bpf_prog_get_curr_or_next(u32 *id)
3825 struct bpf_prog *prog;
3827 spin_lock_bh(&prog_idr_lock);
3829 prog = idr_get_next(&prog_idr, id);
3831 prog = bpf_prog_inc_not_zero(prog);
3837 spin_unlock_bh(&prog_idr_lock);
3842 #define BPF_PROG_GET_FD_BY_ID_LAST_FIELD prog_id
3844 struct bpf_prog *bpf_prog_by_id(u32 id)
3846 struct bpf_prog *prog;
3849 return ERR_PTR(-ENOENT);
3851 spin_lock_bh(&prog_idr_lock);
3852 prog = idr_find(&prog_idr, id);
3854 prog = bpf_prog_inc_not_zero(prog);
3856 prog = ERR_PTR(-ENOENT);
3857 spin_unlock_bh(&prog_idr_lock);
3861 static int bpf_prog_get_fd_by_id(const union bpf_attr *attr)
3863 struct bpf_prog *prog;
3864 u32 id = attr->prog_id;
3867 if (CHECK_ATTR(BPF_PROG_GET_FD_BY_ID))
3870 if (!capable(CAP_SYS_ADMIN))
3873 prog = bpf_prog_by_id(id);
3875 return PTR_ERR(prog);
3877 fd = bpf_prog_new_fd(prog);
3884 #define BPF_MAP_GET_FD_BY_ID_LAST_FIELD open_flags
3886 static int bpf_map_get_fd_by_id(const union bpf_attr *attr)
3888 struct bpf_map *map;
3889 u32 id = attr->map_id;
3893 if (CHECK_ATTR(BPF_MAP_GET_FD_BY_ID) ||
3894 attr->open_flags & ~BPF_OBJ_FLAG_MASK)
3897 if (!capable(CAP_SYS_ADMIN))
3900 f_flags = bpf_get_file_flag(attr->open_flags);
3904 spin_lock_bh(&map_idr_lock);
3905 map = idr_find(&map_idr, id);
3907 map = __bpf_map_inc_not_zero(map, true);
3909 map = ERR_PTR(-ENOENT);
3910 spin_unlock_bh(&map_idr_lock);
3913 return PTR_ERR(map);
3915 fd = bpf_map_new_fd(map, f_flags);
3917 bpf_map_put_with_uref(map);
3922 static const struct bpf_map *bpf_map_from_imm(const struct bpf_prog *prog,
3923 unsigned long addr, u32 *off,
3926 const struct bpf_map *map;
3929 mutex_lock(&prog->aux->used_maps_mutex);
3930 for (i = 0, *off = 0; i < prog->aux->used_map_cnt; i++) {
3931 map = prog->aux->used_maps[i];
3932 if (map == (void *)addr) {
3933 *type = BPF_PSEUDO_MAP_FD;
3936 if (!map->ops->map_direct_value_meta)
3938 if (!map->ops->map_direct_value_meta(map, addr, off)) {
3939 *type = BPF_PSEUDO_MAP_VALUE;
3946 mutex_unlock(&prog->aux->used_maps_mutex);
3950 static struct bpf_insn *bpf_insn_prepare_dump(const struct bpf_prog *prog,
3951 const struct cred *f_cred)
3953 const struct bpf_map *map;
3954 struct bpf_insn *insns;
3960 insns = kmemdup(prog->insnsi, bpf_prog_insn_size(prog),
3965 for (i = 0; i < prog->len; i++) {
3966 code = insns[i].code;
3968 if (code == (BPF_JMP | BPF_TAIL_CALL)) {
3969 insns[i].code = BPF_JMP | BPF_CALL;
3970 insns[i].imm = BPF_FUNC_tail_call;
3973 if (code == (BPF_JMP | BPF_CALL) ||
3974 code == (BPF_JMP | BPF_CALL_ARGS)) {
3975 if (code == (BPF_JMP | BPF_CALL_ARGS))
3976 insns[i].code = BPF_JMP | BPF_CALL;
3977 if (!bpf_dump_raw_ok(f_cred))
3981 if (BPF_CLASS(code) == BPF_LDX && BPF_MODE(code) == BPF_PROBE_MEM) {
3982 insns[i].code = BPF_LDX | BPF_SIZE(code) | BPF_MEM;
3986 if (code != (BPF_LD | BPF_IMM | BPF_DW))
3989 imm = ((u64)insns[i + 1].imm << 32) | (u32)insns[i].imm;
3990 map = bpf_map_from_imm(prog, imm, &off, &type);
3992 insns[i].src_reg = type;
3993 insns[i].imm = map->id;
3994 insns[i + 1].imm = off;
4002 static int set_info_rec_size(struct bpf_prog_info *info)
4005 * Ensure info.*_rec_size is the same as kernel expected size
4009 * Only allow zero *_rec_size if both _rec_size and _cnt are
4010 * zero. In this case, the kernel will set the expected
4011 * _rec_size back to the info.
4014 if ((info->nr_func_info || info->func_info_rec_size) &&
4015 info->func_info_rec_size != sizeof(struct bpf_func_info))
4018 if ((info->nr_line_info || info->line_info_rec_size) &&
4019 info->line_info_rec_size != sizeof(struct bpf_line_info))
4022 if ((info->nr_jited_line_info || info->jited_line_info_rec_size) &&
4023 info->jited_line_info_rec_size != sizeof(__u64))
4026 info->func_info_rec_size = sizeof(struct bpf_func_info);
4027 info->line_info_rec_size = sizeof(struct bpf_line_info);
4028 info->jited_line_info_rec_size = sizeof(__u64);
4033 static int bpf_prog_get_info_by_fd(struct file *file,
4034 struct bpf_prog *prog,
4035 const union bpf_attr *attr,
4036 union bpf_attr __user *uattr)
4038 struct bpf_prog_info __user *uinfo = u64_to_user_ptr(attr->info.info);
4039 struct btf *attach_btf = bpf_prog_get_target_btf(prog);
4040 struct bpf_prog_info info;
4041 u32 info_len = attr->info.info_len;
4042 struct bpf_prog_kstats stats;
4043 char __user *uinsns;
4047 err = bpf_check_uarg_tail_zero(USER_BPFPTR(uinfo), sizeof(info), info_len);
4050 info_len = min_t(u32, sizeof(info), info_len);
4052 memset(&info, 0, sizeof(info));
4053 if (copy_from_user(&info, uinfo, info_len))
4056 info.type = prog->type;
4057 info.id = prog->aux->id;
4058 info.load_time = prog->aux->load_time;
4059 info.created_by_uid = from_kuid_munged(current_user_ns(),
4060 prog->aux->user->uid);
4061 info.gpl_compatible = prog->gpl_compatible;
4063 memcpy(info.tag, prog->tag, sizeof(prog->tag));
4064 memcpy(info.name, prog->aux->name, sizeof(prog->aux->name));
4066 mutex_lock(&prog->aux->used_maps_mutex);
4067 ulen = info.nr_map_ids;
4068 info.nr_map_ids = prog->aux->used_map_cnt;
4069 ulen = min_t(u32, info.nr_map_ids, ulen);
4071 u32 __user *user_map_ids = u64_to_user_ptr(info.map_ids);
4074 for (i = 0; i < ulen; i++)
4075 if (put_user(prog->aux->used_maps[i]->id,
4076 &user_map_ids[i])) {
4077 mutex_unlock(&prog->aux->used_maps_mutex);
4081 mutex_unlock(&prog->aux->used_maps_mutex);
4083 err = set_info_rec_size(&info);
4087 bpf_prog_get_stats(prog, &stats);
4088 info.run_time_ns = stats.nsecs;
4089 info.run_cnt = stats.cnt;
4090 info.recursion_misses = stats.misses;
4092 info.verified_insns = prog->aux->verified_insns;
4094 if (!bpf_capable()) {
4095 info.jited_prog_len = 0;
4096 info.xlated_prog_len = 0;
4097 info.nr_jited_ksyms = 0;
4098 info.nr_jited_func_lens = 0;
4099 info.nr_func_info = 0;
4100 info.nr_line_info = 0;
4101 info.nr_jited_line_info = 0;
4105 ulen = info.xlated_prog_len;
4106 info.xlated_prog_len = bpf_prog_insn_size(prog);
4107 if (info.xlated_prog_len && ulen) {
4108 struct bpf_insn *insns_sanitized;
4111 if (prog->blinded && !bpf_dump_raw_ok(file->f_cred)) {
4112 info.xlated_prog_insns = 0;
4115 insns_sanitized = bpf_insn_prepare_dump(prog, file->f_cred);
4116 if (!insns_sanitized)
4118 uinsns = u64_to_user_ptr(info.xlated_prog_insns);
4119 ulen = min_t(u32, info.xlated_prog_len, ulen);
4120 fault = copy_to_user(uinsns, insns_sanitized, ulen);
4121 kfree(insns_sanitized);
4126 if (bpf_prog_is_offloaded(prog->aux)) {
4127 err = bpf_prog_offload_info_fill(&info, prog);
4133 /* NOTE: the following code is supposed to be skipped for offload.
4134 * bpf_prog_offload_info_fill() is the place to fill similar fields
4137 ulen = info.jited_prog_len;
4138 if (prog->aux->func_cnt) {
4141 info.jited_prog_len = 0;
4142 for (i = 0; i < prog->aux->func_cnt; i++)
4143 info.jited_prog_len += prog->aux->func[i]->jited_len;
4145 info.jited_prog_len = prog->jited_len;
4148 if (info.jited_prog_len && ulen) {
4149 if (bpf_dump_raw_ok(file->f_cred)) {
4150 uinsns = u64_to_user_ptr(info.jited_prog_insns);
4151 ulen = min_t(u32, info.jited_prog_len, ulen);
4153 /* for multi-function programs, copy the JITed
4154 * instructions for all the functions
4156 if (prog->aux->func_cnt) {
4161 for (i = 0; i < prog->aux->func_cnt; i++) {
4162 len = prog->aux->func[i]->jited_len;
4163 len = min_t(u32, len, free);
4164 img = (u8 *) prog->aux->func[i]->bpf_func;
4165 if (copy_to_user(uinsns, img, len))
4173 if (copy_to_user(uinsns, prog->bpf_func, ulen))
4177 info.jited_prog_insns = 0;
4181 ulen = info.nr_jited_ksyms;
4182 info.nr_jited_ksyms = prog->aux->func_cnt ? : 1;
4184 if (bpf_dump_raw_ok(file->f_cred)) {
4185 unsigned long ksym_addr;
4186 u64 __user *user_ksyms;
4189 /* copy the address of the kernel symbol
4190 * corresponding to each function
4192 ulen = min_t(u32, info.nr_jited_ksyms, ulen);
4193 user_ksyms = u64_to_user_ptr(info.jited_ksyms);
4194 if (prog->aux->func_cnt) {
4195 for (i = 0; i < ulen; i++) {
4196 ksym_addr = (unsigned long)
4197 prog->aux->func[i]->bpf_func;
4198 if (put_user((u64) ksym_addr,
4203 ksym_addr = (unsigned long) prog->bpf_func;
4204 if (put_user((u64) ksym_addr, &user_ksyms[0]))
4208 info.jited_ksyms = 0;
4212 ulen = info.nr_jited_func_lens;
4213 info.nr_jited_func_lens = prog->aux->func_cnt ? : 1;
4215 if (bpf_dump_raw_ok(file->f_cred)) {
4216 u32 __user *user_lens;
4219 /* copy the JITed image lengths for each function */
4220 ulen = min_t(u32, info.nr_jited_func_lens, ulen);
4221 user_lens = u64_to_user_ptr(info.jited_func_lens);
4222 if (prog->aux->func_cnt) {
4223 for (i = 0; i < ulen; i++) {
4225 prog->aux->func[i]->jited_len;
4226 if (put_user(func_len, &user_lens[i]))
4230 func_len = prog->jited_len;
4231 if (put_user(func_len, &user_lens[0]))
4235 info.jited_func_lens = 0;
4240 info.btf_id = btf_obj_id(prog->aux->btf);
4241 info.attach_btf_id = prog->aux->attach_btf_id;
4243 info.attach_btf_obj_id = btf_obj_id(attach_btf);
4245 ulen = info.nr_func_info;
4246 info.nr_func_info = prog->aux->func_info_cnt;
4247 if (info.nr_func_info && ulen) {
4248 char __user *user_finfo;
4250 user_finfo = u64_to_user_ptr(info.func_info);
4251 ulen = min_t(u32, info.nr_func_info, ulen);
4252 if (copy_to_user(user_finfo, prog->aux->func_info,
4253 info.func_info_rec_size * ulen))
4257 ulen = info.nr_line_info;
4258 info.nr_line_info = prog->aux->nr_linfo;
4259 if (info.nr_line_info && ulen) {
4260 __u8 __user *user_linfo;
4262 user_linfo = u64_to_user_ptr(info.line_info);
4263 ulen = min_t(u32, info.nr_line_info, ulen);
4264 if (copy_to_user(user_linfo, prog->aux->linfo,
4265 info.line_info_rec_size * ulen))
4269 ulen = info.nr_jited_line_info;
4270 if (prog->aux->jited_linfo)
4271 info.nr_jited_line_info = prog->aux->nr_linfo;
4273 info.nr_jited_line_info = 0;
4274 if (info.nr_jited_line_info && ulen) {
4275 if (bpf_dump_raw_ok(file->f_cred)) {
4276 unsigned long line_addr;
4277 __u64 __user *user_linfo;
4280 user_linfo = u64_to_user_ptr(info.jited_line_info);
4281 ulen = min_t(u32, info.nr_jited_line_info, ulen);
4282 for (i = 0; i < ulen; i++) {
4283 line_addr = (unsigned long)prog->aux->jited_linfo[i];
4284 if (put_user((__u64)line_addr, &user_linfo[i]))
4288 info.jited_line_info = 0;
4292 ulen = info.nr_prog_tags;
4293 info.nr_prog_tags = prog->aux->func_cnt ? : 1;
4295 __u8 __user (*user_prog_tags)[BPF_TAG_SIZE];
4298 user_prog_tags = u64_to_user_ptr(info.prog_tags);
4299 ulen = min_t(u32, info.nr_prog_tags, ulen);
4300 if (prog->aux->func_cnt) {
4301 for (i = 0; i < ulen; i++) {
4302 if (copy_to_user(user_prog_tags[i],
4303 prog->aux->func[i]->tag,
4308 if (copy_to_user(user_prog_tags[0],
4309 prog->tag, BPF_TAG_SIZE))
4315 if (copy_to_user(uinfo, &info, info_len) ||
4316 put_user(info_len, &uattr->info.info_len))
4322 static int bpf_map_get_info_by_fd(struct file *file,
4323 struct bpf_map *map,
4324 const union bpf_attr *attr,
4325 union bpf_attr __user *uattr)
4327 struct bpf_map_info __user *uinfo = u64_to_user_ptr(attr->info.info);
4328 struct bpf_map_info info;
4329 u32 info_len = attr->info.info_len;
4332 err = bpf_check_uarg_tail_zero(USER_BPFPTR(uinfo), sizeof(info), info_len);
4335 info_len = min_t(u32, sizeof(info), info_len);
4337 memset(&info, 0, sizeof(info));
4338 info.type = map->map_type;
4340 info.key_size = map->key_size;
4341 info.value_size = map->value_size;
4342 info.max_entries = map->max_entries;
4343 info.map_flags = map->map_flags;
4344 info.map_extra = map->map_extra;
4345 memcpy(info.name, map->name, sizeof(map->name));
4348 info.btf_id = btf_obj_id(map->btf);
4349 info.btf_key_type_id = map->btf_key_type_id;
4350 info.btf_value_type_id = map->btf_value_type_id;
4352 info.btf_vmlinux_value_type_id = map->btf_vmlinux_value_type_id;
4354 if (bpf_map_is_offloaded(map)) {
4355 err = bpf_map_offload_info_fill(&info, map);
4360 if (copy_to_user(uinfo, &info, info_len) ||
4361 put_user(info_len, &uattr->info.info_len))
4367 static int bpf_btf_get_info_by_fd(struct file *file,
4369 const union bpf_attr *attr,
4370 union bpf_attr __user *uattr)
4372 struct bpf_btf_info __user *uinfo = u64_to_user_ptr(attr->info.info);
4373 u32 info_len = attr->info.info_len;
4376 err = bpf_check_uarg_tail_zero(USER_BPFPTR(uinfo), sizeof(*uinfo), info_len);
4380 return btf_get_info_by_fd(btf, attr, uattr);
4383 static int bpf_link_get_info_by_fd(struct file *file,
4384 struct bpf_link *link,
4385 const union bpf_attr *attr,
4386 union bpf_attr __user *uattr)
4388 struct bpf_link_info __user *uinfo = u64_to_user_ptr(attr->info.info);
4389 struct bpf_link_info info;
4390 u32 info_len = attr->info.info_len;
4393 err = bpf_check_uarg_tail_zero(USER_BPFPTR(uinfo), sizeof(info), info_len);
4396 info_len = min_t(u32, sizeof(info), info_len);
4398 memset(&info, 0, sizeof(info));
4399 if (copy_from_user(&info, uinfo, info_len))
4402 info.type = link->type;
4405 info.prog_id = link->prog->aux->id;
4407 if (link->ops->fill_link_info) {
4408 err = link->ops->fill_link_info(link, &info);
4413 if (copy_to_user(uinfo, &info, info_len) ||
4414 put_user(info_len, &uattr->info.info_len))
4421 #define BPF_OBJ_GET_INFO_BY_FD_LAST_FIELD info.info
4423 static int bpf_obj_get_info_by_fd(const union bpf_attr *attr,
4424 union bpf_attr __user *uattr)
4426 int ufd = attr->info.bpf_fd;
4430 if (CHECK_ATTR(BPF_OBJ_GET_INFO_BY_FD))
4437 if (f.file->f_op == &bpf_prog_fops)
4438 err = bpf_prog_get_info_by_fd(f.file, f.file->private_data, attr,
4440 else if (f.file->f_op == &bpf_map_fops)
4441 err = bpf_map_get_info_by_fd(f.file, f.file->private_data, attr,
4443 else if (f.file->f_op == &btf_fops)
4444 err = bpf_btf_get_info_by_fd(f.file, f.file->private_data, attr, uattr);
4445 else if (f.file->f_op == &bpf_link_fops)
4446 err = bpf_link_get_info_by_fd(f.file, f.file->private_data,
4455 #define BPF_BTF_LOAD_LAST_FIELD btf_log_true_size
4457 static int bpf_btf_load(const union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size)
4459 if (CHECK_ATTR(BPF_BTF_LOAD))
4465 return btf_new_fd(attr, uattr, uattr_size);
4468 #define BPF_BTF_GET_FD_BY_ID_LAST_FIELD btf_id
4470 static int bpf_btf_get_fd_by_id(const union bpf_attr *attr)
4472 if (CHECK_ATTR(BPF_BTF_GET_FD_BY_ID))
4475 if (!capable(CAP_SYS_ADMIN))
4478 return btf_get_fd_by_id(attr->btf_id);
4481 static int bpf_task_fd_query_copy(const union bpf_attr *attr,
4482 union bpf_attr __user *uattr,
4483 u32 prog_id, u32 fd_type,
4484 const char *buf, u64 probe_offset,
4487 char __user *ubuf = u64_to_user_ptr(attr->task_fd_query.buf);
4488 u32 len = buf ? strlen(buf) : 0, input_len;
4491 if (put_user(len, &uattr->task_fd_query.buf_len))
4493 input_len = attr->task_fd_query.buf_len;
4494 if (input_len && ubuf) {
4496 /* nothing to copy, just make ubuf NULL terminated */
4499 if (put_user(zero, ubuf))
4501 } else if (input_len >= len + 1) {
4502 /* ubuf can hold the string with NULL terminator */
4503 if (copy_to_user(ubuf, buf, len + 1))
4506 /* ubuf cannot hold the string with NULL terminator,
4507 * do a partial copy with NULL terminator.
4512 if (copy_to_user(ubuf, buf, input_len - 1))
4514 if (put_user(zero, ubuf + input_len - 1))
4519 if (put_user(prog_id, &uattr->task_fd_query.prog_id) ||
4520 put_user(fd_type, &uattr->task_fd_query.fd_type) ||
4521 put_user(probe_offset, &uattr->task_fd_query.probe_offset) ||
4522 put_user(probe_addr, &uattr->task_fd_query.probe_addr))
4528 #define BPF_TASK_FD_QUERY_LAST_FIELD task_fd_query.probe_addr
4530 static int bpf_task_fd_query(const union bpf_attr *attr,
4531 union bpf_attr __user *uattr)
4533 pid_t pid = attr->task_fd_query.pid;
4534 u32 fd = attr->task_fd_query.fd;
4535 const struct perf_event *event;
4536 struct task_struct *task;
4540 if (CHECK_ATTR(BPF_TASK_FD_QUERY))
4543 if (!capable(CAP_SYS_ADMIN))
4546 if (attr->task_fd_query.flags != 0)
4550 task = get_pid_task(find_vpid(pid), PIDTYPE_PID);
4556 file = fget_task(task, fd);
4557 put_task_struct(task);
4561 if (file->f_op == &bpf_link_fops) {
4562 struct bpf_link *link = file->private_data;
4564 if (link->ops == &bpf_raw_tp_link_lops) {
4565 struct bpf_raw_tp_link *raw_tp =
4566 container_of(link, struct bpf_raw_tp_link, link);
4567 struct bpf_raw_event_map *btp = raw_tp->btp;
4569 err = bpf_task_fd_query_copy(attr, uattr,
4570 raw_tp->link.prog->aux->id,
4571 BPF_FD_TYPE_RAW_TRACEPOINT,
4572 btp->tp->name, 0, 0);
4578 event = perf_get_event(file);
4579 if (!IS_ERR(event)) {
4580 u64 probe_offset, probe_addr;
4581 u32 prog_id, fd_type;
4584 err = bpf_get_perf_event_info(event, &prog_id, &fd_type,
4585 &buf, &probe_offset,
4588 err = bpf_task_fd_query_copy(attr, uattr, prog_id,
4602 #define BPF_MAP_BATCH_LAST_FIELD batch.flags
4604 #define BPF_DO_BATCH(fn, ...) \
4610 err = fn(__VA_ARGS__); \
4613 static int bpf_map_do_batch(const union bpf_attr *attr,
4614 union bpf_attr __user *uattr,
4617 bool has_read = cmd == BPF_MAP_LOOKUP_BATCH ||
4618 cmd == BPF_MAP_LOOKUP_AND_DELETE_BATCH;
4619 bool has_write = cmd != BPF_MAP_LOOKUP_BATCH;
4620 struct bpf_map *map;
4624 if (CHECK_ATTR(BPF_MAP_BATCH))
4627 ufd = attr->batch.map_fd;
4629 map = __bpf_map_get(f);
4631 return PTR_ERR(map);
4633 bpf_map_write_active_inc(map);
4634 if (has_read && !(map_get_sys_perms(map, f) & FMODE_CAN_READ)) {
4638 if (has_write && !(map_get_sys_perms(map, f) & FMODE_CAN_WRITE)) {
4643 if (cmd == BPF_MAP_LOOKUP_BATCH)
4644 BPF_DO_BATCH(map->ops->map_lookup_batch, map, attr, uattr);
4645 else if (cmd == BPF_MAP_LOOKUP_AND_DELETE_BATCH)
4646 BPF_DO_BATCH(map->ops->map_lookup_and_delete_batch, map, attr, uattr);
4647 else if (cmd == BPF_MAP_UPDATE_BATCH)
4648 BPF_DO_BATCH(map->ops->map_update_batch, map, f.file, attr, uattr);
4650 BPF_DO_BATCH(map->ops->map_delete_batch, map, attr, uattr);
4653 bpf_map_write_active_dec(map);
4658 #define BPF_LINK_CREATE_LAST_FIELD link_create.kprobe_multi.cookies
4659 static int link_create(union bpf_attr *attr, bpfptr_t uattr)
4661 enum bpf_prog_type ptype;
4662 struct bpf_prog *prog;
4665 if (CHECK_ATTR(BPF_LINK_CREATE))
4668 if (attr->link_create.attach_type == BPF_STRUCT_OPS)
4669 return bpf_struct_ops_link_create(attr);
4671 prog = bpf_prog_get(attr->link_create.prog_fd);
4673 return PTR_ERR(prog);
4675 ret = bpf_prog_attach_check_attach_type(prog,
4676 attr->link_create.attach_type);
4680 switch (prog->type) {
4681 case BPF_PROG_TYPE_EXT:
4683 case BPF_PROG_TYPE_NETFILTER:
4684 if (attr->link_create.attach_type != BPF_NETFILTER) {
4689 case BPF_PROG_TYPE_PERF_EVENT:
4690 case BPF_PROG_TYPE_TRACEPOINT:
4691 if (attr->link_create.attach_type != BPF_PERF_EVENT) {
4696 case BPF_PROG_TYPE_KPROBE:
4697 if (attr->link_create.attach_type != BPF_PERF_EVENT &&
4698 attr->link_create.attach_type != BPF_TRACE_KPROBE_MULTI) {
4704 ptype = attach_type_to_prog_type(attr->link_create.attach_type);
4705 if (ptype == BPF_PROG_TYPE_UNSPEC || ptype != prog->type) {
4712 switch (prog->type) {
4713 case BPF_PROG_TYPE_CGROUP_SKB:
4714 case BPF_PROG_TYPE_CGROUP_SOCK:
4715 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
4716 case BPF_PROG_TYPE_SOCK_OPS:
4717 case BPF_PROG_TYPE_CGROUP_DEVICE:
4718 case BPF_PROG_TYPE_CGROUP_SYSCTL:
4719 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
4720 ret = cgroup_bpf_link_attach(attr, prog);
4722 case BPF_PROG_TYPE_EXT:
4723 ret = bpf_tracing_prog_attach(prog,
4724 attr->link_create.target_fd,
4725 attr->link_create.target_btf_id,
4726 attr->link_create.tracing.cookie);
4728 case BPF_PROG_TYPE_LSM:
4729 case BPF_PROG_TYPE_TRACING:
4730 if (attr->link_create.attach_type != prog->expected_attach_type) {
4734 if (prog->expected_attach_type == BPF_TRACE_RAW_TP)
4735 ret = bpf_raw_tp_link_attach(prog, NULL);
4736 else if (prog->expected_attach_type == BPF_TRACE_ITER)
4737 ret = bpf_iter_link_attach(attr, uattr, prog);
4738 else if (prog->expected_attach_type == BPF_LSM_CGROUP)
4739 ret = cgroup_bpf_link_attach(attr, prog);
4741 ret = bpf_tracing_prog_attach(prog,
4742 attr->link_create.target_fd,
4743 attr->link_create.target_btf_id,
4744 attr->link_create.tracing.cookie);
4746 case BPF_PROG_TYPE_FLOW_DISSECTOR:
4747 case BPF_PROG_TYPE_SK_LOOKUP:
4748 ret = netns_bpf_link_create(attr, prog);
4751 case BPF_PROG_TYPE_XDP:
4752 ret = bpf_xdp_link_attach(attr, prog);
4754 case BPF_PROG_TYPE_NETFILTER:
4755 ret = bpf_nf_link_attach(attr, prog);
4758 case BPF_PROG_TYPE_PERF_EVENT:
4759 case BPF_PROG_TYPE_TRACEPOINT:
4760 ret = bpf_perf_link_attach(attr, prog);
4762 case BPF_PROG_TYPE_KPROBE:
4763 if (attr->link_create.attach_type == BPF_PERF_EVENT)
4764 ret = bpf_perf_link_attach(attr, prog);
4766 ret = bpf_kprobe_multi_link_attach(attr, prog);
4778 static int link_update_map(struct bpf_link *link, union bpf_attr *attr)
4780 struct bpf_map *new_map, *old_map = NULL;
4783 new_map = bpf_map_get(attr->link_update.new_map_fd);
4784 if (IS_ERR(new_map))
4785 return PTR_ERR(new_map);
4787 if (attr->link_update.flags & BPF_F_REPLACE) {
4788 old_map = bpf_map_get(attr->link_update.old_map_fd);
4789 if (IS_ERR(old_map)) {
4790 ret = PTR_ERR(old_map);
4793 } else if (attr->link_update.old_map_fd) {
4798 ret = link->ops->update_map(link, new_map, old_map);
4801 bpf_map_put(old_map);
4803 bpf_map_put(new_map);
4807 #define BPF_LINK_UPDATE_LAST_FIELD link_update.old_prog_fd
4809 static int link_update(union bpf_attr *attr)
4811 struct bpf_prog *old_prog = NULL, *new_prog;
4812 struct bpf_link *link;
4816 if (CHECK_ATTR(BPF_LINK_UPDATE))
4819 flags = attr->link_update.flags;
4820 if (flags & ~BPF_F_REPLACE)
4823 link = bpf_link_get_from_fd(attr->link_update.link_fd);
4825 return PTR_ERR(link);
4827 if (link->ops->update_map) {
4828 ret = link_update_map(link, attr);
4832 new_prog = bpf_prog_get(attr->link_update.new_prog_fd);
4833 if (IS_ERR(new_prog)) {
4834 ret = PTR_ERR(new_prog);
4838 if (flags & BPF_F_REPLACE) {
4839 old_prog = bpf_prog_get(attr->link_update.old_prog_fd);
4840 if (IS_ERR(old_prog)) {
4841 ret = PTR_ERR(old_prog);
4845 } else if (attr->link_update.old_prog_fd) {
4850 if (link->ops->update_prog)
4851 ret = link->ops->update_prog(link, new_prog, old_prog);
4857 bpf_prog_put(old_prog);
4859 bpf_prog_put(new_prog);
4861 bpf_link_put_direct(link);
4865 #define BPF_LINK_DETACH_LAST_FIELD link_detach.link_fd
4867 static int link_detach(union bpf_attr *attr)
4869 struct bpf_link *link;
4872 if (CHECK_ATTR(BPF_LINK_DETACH))
4875 link = bpf_link_get_from_fd(attr->link_detach.link_fd);
4877 return PTR_ERR(link);
4879 if (link->ops->detach)
4880 ret = link->ops->detach(link);
4884 bpf_link_put_direct(link);
4888 static struct bpf_link *bpf_link_inc_not_zero(struct bpf_link *link)
4890 return atomic64_fetch_add_unless(&link->refcnt, 1, 0) ? link : ERR_PTR(-ENOENT);
4893 struct bpf_link *bpf_link_by_id(u32 id)
4895 struct bpf_link *link;
4898 return ERR_PTR(-ENOENT);
4900 spin_lock_bh(&link_idr_lock);
4901 /* before link is "settled", ID is 0, pretend it doesn't exist yet */
4902 link = idr_find(&link_idr, id);
4905 link = bpf_link_inc_not_zero(link);
4907 link = ERR_PTR(-EAGAIN);
4909 link = ERR_PTR(-ENOENT);
4911 spin_unlock_bh(&link_idr_lock);
4915 struct bpf_link *bpf_link_get_curr_or_next(u32 *id)
4917 struct bpf_link *link;
4919 spin_lock_bh(&link_idr_lock);
4921 link = idr_get_next(&link_idr, id);
4923 link = bpf_link_inc_not_zero(link);
4929 spin_unlock_bh(&link_idr_lock);
4934 #define BPF_LINK_GET_FD_BY_ID_LAST_FIELD link_id
4936 static int bpf_link_get_fd_by_id(const union bpf_attr *attr)
4938 struct bpf_link *link;
4939 u32 id = attr->link_id;
4942 if (CHECK_ATTR(BPF_LINK_GET_FD_BY_ID))
4945 if (!capable(CAP_SYS_ADMIN))
4948 link = bpf_link_by_id(id);
4950 return PTR_ERR(link);
4952 fd = bpf_link_new_fd(link);
4954 bpf_link_put_direct(link);
4959 DEFINE_MUTEX(bpf_stats_enabled_mutex);
4961 static int bpf_stats_release(struct inode *inode, struct file *file)
4963 mutex_lock(&bpf_stats_enabled_mutex);
4964 static_key_slow_dec(&bpf_stats_enabled_key.key);
4965 mutex_unlock(&bpf_stats_enabled_mutex);
4969 static const struct file_operations bpf_stats_fops = {
4970 .release = bpf_stats_release,
4973 static int bpf_enable_runtime_stats(void)
4977 mutex_lock(&bpf_stats_enabled_mutex);
4979 /* Set a very high limit to avoid overflow */
4980 if (static_key_count(&bpf_stats_enabled_key.key) > INT_MAX / 2) {
4981 mutex_unlock(&bpf_stats_enabled_mutex);
4985 fd = anon_inode_getfd("bpf-stats", &bpf_stats_fops, NULL, O_CLOEXEC);
4987 static_key_slow_inc(&bpf_stats_enabled_key.key);
4989 mutex_unlock(&bpf_stats_enabled_mutex);
4993 #define BPF_ENABLE_STATS_LAST_FIELD enable_stats.type
4995 static int bpf_enable_stats(union bpf_attr *attr)
4998 if (CHECK_ATTR(BPF_ENABLE_STATS))
5001 if (!capable(CAP_SYS_ADMIN))
5004 switch (attr->enable_stats.type) {
5005 case BPF_STATS_RUN_TIME:
5006 return bpf_enable_runtime_stats();
5013 #define BPF_ITER_CREATE_LAST_FIELD iter_create.flags
5015 static int bpf_iter_create(union bpf_attr *attr)
5017 struct bpf_link *link;
5020 if (CHECK_ATTR(BPF_ITER_CREATE))
5023 if (attr->iter_create.flags)
5026 link = bpf_link_get_from_fd(attr->iter_create.link_fd);
5028 return PTR_ERR(link);
5030 err = bpf_iter_new_fd(link);
5031 bpf_link_put_direct(link);
5036 #define BPF_PROG_BIND_MAP_LAST_FIELD prog_bind_map.flags
5038 static int bpf_prog_bind_map(union bpf_attr *attr)
5040 struct bpf_prog *prog;
5041 struct bpf_map *map;
5042 struct bpf_map **used_maps_old, **used_maps_new;
5045 if (CHECK_ATTR(BPF_PROG_BIND_MAP))
5048 if (attr->prog_bind_map.flags)
5051 prog = bpf_prog_get(attr->prog_bind_map.prog_fd);
5053 return PTR_ERR(prog);
5055 map = bpf_map_get(attr->prog_bind_map.map_fd);
5061 mutex_lock(&prog->aux->used_maps_mutex);
5063 used_maps_old = prog->aux->used_maps;
5065 for (i = 0; i < prog->aux->used_map_cnt; i++)
5066 if (used_maps_old[i] == map) {
5071 used_maps_new = kmalloc_array(prog->aux->used_map_cnt + 1,
5072 sizeof(used_maps_new[0]),
5074 if (!used_maps_new) {
5079 memcpy(used_maps_new, used_maps_old,
5080 sizeof(used_maps_old[0]) * prog->aux->used_map_cnt);
5081 used_maps_new[prog->aux->used_map_cnt] = map;
5083 prog->aux->used_map_cnt++;
5084 prog->aux->used_maps = used_maps_new;
5086 kfree(used_maps_old);
5089 mutex_unlock(&prog->aux->used_maps_mutex);
5098 static int __sys_bpf(int cmd, bpfptr_t uattr, unsigned int size)
5100 union bpf_attr attr;
5103 err = bpf_check_uarg_tail_zero(uattr, sizeof(attr), size);
5106 size = min_t(u32, size, sizeof(attr));
5108 /* copy attributes from user space, may be less than sizeof(bpf_attr) */
5109 memset(&attr, 0, sizeof(attr));
5110 if (copy_from_bpfptr(&attr, uattr, size) != 0)
5113 err = security_bpf(cmd, &attr, size);
5118 case BPF_MAP_CREATE:
5119 err = map_create(&attr);
5121 case BPF_MAP_LOOKUP_ELEM:
5122 err = map_lookup_elem(&attr);
5124 case BPF_MAP_UPDATE_ELEM:
5125 err = map_update_elem(&attr, uattr);
5127 case BPF_MAP_DELETE_ELEM:
5128 err = map_delete_elem(&attr, uattr);
5130 case BPF_MAP_GET_NEXT_KEY:
5131 err = map_get_next_key(&attr);
5133 case BPF_MAP_FREEZE:
5134 err = map_freeze(&attr);
5137 err = bpf_prog_load(&attr, uattr, size);
5140 err = bpf_obj_pin(&attr);
5143 err = bpf_obj_get(&attr);
5145 case BPF_PROG_ATTACH:
5146 err = bpf_prog_attach(&attr);
5148 case BPF_PROG_DETACH:
5149 err = bpf_prog_detach(&attr);
5151 case BPF_PROG_QUERY:
5152 err = bpf_prog_query(&attr, uattr.user);
5154 case BPF_PROG_TEST_RUN:
5155 err = bpf_prog_test_run(&attr, uattr.user);
5157 case BPF_PROG_GET_NEXT_ID:
5158 err = bpf_obj_get_next_id(&attr, uattr.user,
5159 &prog_idr, &prog_idr_lock);
5161 case BPF_MAP_GET_NEXT_ID:
5162 err = bpf_obj_get_next_id(&attr, uattr.user,
5163 &map_idr, &map_idr_lock);
5165 case BPF_BTF_GET_NEXT_ID:
5166 err = bpf_obj_get_next_id(&attr, uattr.user,
5167 &btf_idr, &btf_idr_lock);
5169 case BPF_PROG_GET_FD_BY_ID:
5170 err = bpf_prog_get_fd_by_id(&attr);
5172 case BPF_MAP_GET_FD_BY_ID:
5173 err = bpf_map_get_fd_by_id(&attr);
5175 case BPF_OBJ_GET_INFO_BY_FD:
5176 err = bpf_obj_get_info_by_fd(&attr, uattr.user);
5178 case BPF_RAW_TRACEPOINT_OPEN:
5179 err = bpf_raw_tracepoint_open(&attr);
5182 err = bpf_btf_load(&attr, uattr, size);
5184 case BPF_BTF_GET_FD_BY_ID:
5185 err = bpf_btf_get_fd_by_id(&attr);
5187 case BPF_TASK_FD_QUERY:
5188 err = bpf_task_fd_query(&attr, uattr.user);
5190 case BPF_MAP_LOOKUP_AND_DELETE_ELEM:
5191 err = map_lookup_and_delete_elem(&attr);
5193 case BPF_MAP_LOOKUP_BATCH:
5194 err = bpf_map_do_batch(&attr, uattr.user, BPF_MAP_LOOKUP_BATCH);
5196 case BPF_MAP_LOOKUP_AND_DELETE_BATCH:
5197 err = bpf_map_do_batch(&attr, uattr.user,
5198 BPF_MAP_LOOKUP_AND_DELETE_BATCH);
5200 case BPF_MAP_UPDATE_BATCH:
5201 err = bpf_map_do_batch(&attr, uattr.user, BPF_MAP_UPDATE_BATCH);
5203 case BPF_MAP_DELETE_BATCH:
5204 err = bpf_map_do_batch(&attr, uattr.user, BPF_MAP_DELETE_BATCH);
5206 case BPF_LINK_CREATE:
5207 err = link_create(&attr, uattr);
5209 case BPF_LINK_UPDATE:
5210 err = link_update(&attr);
5212 case BPF_LINK_GET_FD_BY_ID:
5213 err = bpf_link_get_fd_by_id(&attr);
5215 case BPF_LINK_GET_NEXT_ID:
5216 err = bpf_obj_get_next_id(&attr, uattr.user,
5217 &link_idr, &link_idr_lock);
5219 case BPF_ENABLE_STATS:
5220 err = bpf_enable_stats(&attr);
5222 case BPF_ITER_CREATE:
5223 err = bpf_iter_create(&attr);
5225 case BPF_LINK_DETACH:
5226 err = link_detach(&attr);
5228 case BPF_PROG_BIND_MAP:
5229 err = bpf_prog_bind_map(&attr);
5239 SYSCALL_DEFINE3(bpf, int, cmd, union bpf_attr __user *, uattr, unsigned int, size)
5241 return __sys_bpf(cmd, USER_BPFPTR(uattr), size);
5244 static bool syscall_prog_is_valid_access(int off, int size,
5245 enum bpf_access_type type,
5246 const struct bpf_prog *prog,
5247 struct bpf_insn_access_aux *info)
5249 if (off < 0 || off >= U16_MAX)
5251 if (off % size != 0)
5256 BPF_CALL_3(bpf_sys_bpf, int, cmd, union bpf_attr *, attr, u32, attr_size)
5259 case BPF_MAP_CREATE:
5260 case BPF_MAP_DELETE_ELEM:
5261 case BPF_MAP_UPDATE_ELEM:
5262 case BPF_MAP_FREEZE:
5263 case BPF_MAP_GET_FD_BY_ID:
5266 case BPF_LINK_CREATE:
5267 case BPF_RAW_TRACEPOINT_OPEN:
5272 return __sys_bpf(cmd, KERNEL_BPFPTR(attr), attr_size);
5276 /* To shut up -Wmissing-prototypes.
5277 * This function is used by the kernel light skeleton
5278 * to load bpf programs when modules are loaded or during kernel boot.
5279 * See tools/lib/bpf/skel_internal.h
5281 int kern_sys_bpf(int cmd, union bpf_attr *attr, unsigned int size);
5283 int kern_sys_bpf(int cmd, union bpf_attr *attr, unsigned int size)
5285 struct bpf_prog * __maybe_unused prog;
5286 struct bpf_tramp_run_ctx __maybe_unused run_ctx;
5289 #ifdef CONFIG_BPF_JIT /* __bpf_prog_enter_sleepable used by trampoline and JIT */
5290 case BPF_PROG_TEST_RUN:
5291 if (attr->test.data_in || attr->test.data_out ||
5292 attr->test.ctx_out || attr->test.duration ||
5293 attr->test.repeat || attr->test.flags)
5296 prog = bpf_prog_get_type(attr->test.prog_fd, BPF_PROG_TYPE_SYSCALL);
5298 return PTR_ERR(prog);
5300 if (attr->test.ctx_size_in < prog->aux->max_ctx_offset ||
5301 attr->test.ctx_size_in > U16_MAX) {
5306 run_ctx.bpf_cookie = 0;
5307 run_ctx.saved_run_ctx = NULL;
5308 if (!__bpf_prog_enter_sleepable_recur(prog, &run_ctx)) {
5309 /* recursion detected */
5313 attr->test.retval = bpf_prog_run(prog, (void *) (long) attr->test.ctx_in);
5314 __bpf_prog_exit_sleepable_recur(prog, 0 /* bpf_prog_run does runtime stats */,
5320 return ____bpf_sys_bpf(cmd, attr, size);
5323 EXPORT_SYMBOL(kern_sys_bpf);
5325 static const struct bpf_func_proto bpf_sys_bpf_proto = {
5326 .func = bpf_sys_bpf,
5328 .ret_type = RET_INTEGER,
5329 .arg1_type = ARG_ANYTHING,
5330 .arg2_type = ARG_PTR_TO_MEM | MEM_RDONLY,
5331 .arg3_type = ARG_CONST_SIZE,
5334 const struct bpf_func_proto * __weak
5335 tracing_prog_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
5337 return bpf_base_func_proto(func_id);
5340 BPF_CALL_1(bpf_sys_close, u32, fd)
5342 /* When bpf program calls this helper there should not be
5343 * an fdget() without matching completed fdput().
5344 * This helper is allowed in the following callchain only:
5345 * sys_bpf->prog_test_run->bpf_prog->bpf_sys_close
5347 return close_fd(fd);
5350 static const struct bpf_func_proto bpf_sys_close_proto = {
5351 .func = bpf_sys_close,
5353 .ret_type = RET_INTEGER,
5354 .arg1_type = ARG_ANYTHING,
5357 BPF_CALL_4(bpf_kallsyms_lookup_name, const char *, name, int, name_sz, int, flags, u64 *, res)
5362 if (name_sz <= 1 || name[name_sz - 1])
5365 if (!bpf_dump_raw_ok(current_cred()))
5368 *res = kallsyms_lookup_name(name);
5369 return *res ? 0 : -ENOENT;
5372 static const struct bpf_func_proto bpf_kallsyms_lookup_name_proto = {
5373 .func = bpf_kallsyms_lookup_name,
5375 .ret_type = RET_INTEGER,
5376 .arg1_type = ARG_PTR_TO_MEM,
5377 .arg2_type = ARG_CONST_SIZE_OR_ZERO,
5378 .arg3_type = ARG_ANYTHING,
5379 .arg4_type = ARG_PTR_TO_LONG,
5382 static const struct bpf_func_proto *
5383 syscall_prog_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
5386 case BPF_FUNC_sys_bpf:
5387 return !perfmon_capable() ? NULL : &bpf_sys_bpf_proto;
5388 case BPF_FUNC_btf_find_by_name_kind:
5389 return &bpf_btf_find_by_name_kind_proto;
5390 case BPF_FUNC_sys_close:
5391 return &bpf_sys_close_proto;
5392 case BPF_FUNC_kallsyms_lookup_name:
5393 return &bpf_kallsyms_lookup_name_proto;
5395 return tracing_prog_func_proto(func_id, prog);
5399 const struct bpf_verifier_ops bpf_syscall_verifier_ops = {
5400 .get_func_proto = syscall_prog_func_proto,
5401 .is_valid_access = syscall_prog_is_valid_access,
5404 const struct bpf_prog_ops bpf_syscall_prog_ops = {
5405 .test_run = bpf_prog_test_run_syscall,
5408 #ifdef CONFIG_SYSCTL
5409 static int bpf_stats_handler(struct ctl_table *table, int write,
5410 void *buffer, size_t *lenp, loff_t *ppos)
5412 struct static_key *key = (struct static_key *)table->data;
5413 static int saved_val;
5415 struct ctl_table tmp = {
5417 .maxlen = sizeof(val),
5418 .mode = table->mode,
5419 .extra1 = SYSCTL_ZERO,
5420 .extra2 = SYSCTL_ONE,
5423 if (write && !capable(CAP_SYS_ADMIN))
5426 mutex_lock(&bpf_stats_enabled_mutex);
5428 ret = proc_dointvec_minmax(&tmp, write, buffer, lenp, ppos);
5429 if (write && !ret && val != saved_val) {
5431 static_key_slow_inc(key);
5433 static_key_slow_dec(key);
5436 mutex_unlock(&bpf_stats_enabled_mutex);
5440 void __weak unpriv_ebpf_notify(int new_state)
5444 static int bpf_unpriv_handler(struct ctl_table *table, int write,
5445 void *buffer, size_t *lenp, loff_t *ppos)
5447 int ret, unpriv_enable = *(int *)table->data;
5448 bool locked_state = unpriv_enable == 1;
5449 struct ctl_table tmp = *table;
5451 if (write && !capable(CAP_SYS_ADMIN))
5454 tmp.data = &unpriv_enable;
5455 ret = proc_dointvec_minmax(&tmp, write, buffer, lenp, ppos);
5456 if (write && !ret) {
5457 if (locked_state && unpriv_enable != 1)
5459 *(int *)table->data = unpriv_enable;
5463 unpriv_ebpf_notify(unpriv_enable);
5468 static struct ctl_table bpf_syscall_table[] = {
5470 .procname = "unprivileged_bpf_disabled",
5471 .data = &sysctl_unprivileged_bpf_disabled,
5472 .maxlen = sizeof(sysctl_unprivileged_bpf_disabled),
5474 .proc_handler = bpf_unpriv_handler,
5475 .extra1 = SYSCTL_ZERO,
5476 .extra2 = SYSCTL_TWO,
5479 .procname = "bpf_stats_enabled",
5480 .data = &bpf_stats_enabled_key.key,
5482 .proc_handler = bpf_stats_handler,
5487 static int __init bpf_syscall_sysctl_init(void)
5489 register_sysctl_init("kernel", bpf_syscall_table);
5492 late_initcall(bpf_syscall_sysctl_init);
5493 #endif /* CONFIG_SYSCTL */