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>
39 #include <net/netfilter/nf_bpf_link.h>
40 #include <net/netkit.h>
43 #define IS_FD_ARRAY(map) ((map)->map_type == BPF_MAP_TYPE_PERF_EVENT_ARRAY || \
44 (map)->map_type == BPF_MAP_TYPE_CGROUP_ARRAY || \
45 (map)->map_type == BPF_MAP_TYPE_ARRAY_OF_MAPS)
46 #define IS_FD_PROG_ARRAY(map) ((map)->map_type == BPF_MAP_TYPE_PROG_ARRAY)
47 #define IS_FD_HASH(map) ((map)->map_type == BPF_MAP_TYPE_HASH_OF_MAPS)
48 #define IS_FD_MAP(map) (IS_FD_ARRAY(map) || IS_FD_PROG_ARRAY(map) || \
51 #define BPF_OBJ_FLAG_MASK (BPF_F_RDONLY | BPF_F_WRONLY)
53 DEFINE_PER_CPU(int, bpf_prog_active);
54 static DEFINE_IDR(prog_idr);
55 static DEFINE_SPINLOCK(prog_idr_lock);
56 static DEFINE_IDR(map_idr);
57 static DEFINE_SPINLOCK(map_idr_lock);
58 static DEFINE_IDR(link_idr);
59 static DEFINE_SPINLOCK(link_idr_lock);
61 int sysctl_unprivileged_bpf_disabled __read_mostly =
62 IS_BUILTIN(CONFIG_BPF_UNPRIV_DEFAULT_OFF) ? 2 : 0;
64 static const struct bpf_map_ops * const bpf_map_types[] = {
65 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type)
66 #define BPF_MAP_TYPE(_id, _ops) \
68 #define BPF_LINK_TYPE(_id, _name)
69 #include <linux/bpf_types.h>
76 * If we're handed a bigger struct than we know of, ensure all the unknown bits
77 * are 0 - i.e. new user-space does not rely on any kernel feature extensions
78 * we don't know about yet.
80 * There is a ToCToU between this function call and the following
81 * copy_from_user() call. However, this is not a concern since this function is
82 * meant to be a future-proofing of bits.
84 int bpf_check_uarg_tail_zero(bpfptr_t uaddr,
90 if (unlikely(actual_size > PAGE_SIZE)) /* silly large */
93 if (actual_size <= expected_size)
97 res = memchr_inv(uaddr.kernel + expected_size, 0,
98 actual_size - expected_size) == NULL;
100 res = check_zeroed_user(uaddr.user + expected_size,
101 actual_size - expected_size);
104 return res ? 0 : -E2BIG;
107 const struct bpf_map_ops bpf_map_offload_ops = {
108 .map_meta_equal = bpf_map_meta_equal,
109 .map_alloc = bpf_map_offload_map_alloc,
110 .map_free = bpf_map_offload_map_free,
111 .map_check_btf = map_check_no_btf,
112 .map_mem_usage = bpf_map_offload_map_mem_usage,
115 static void bpf_map_write_active_inc(struct bpf_map *map)
117 atomic64_inc(&map->writecnt);
120 static void bpf_map_write_active_dec(struct bpf_map *map)
122 atomic64_dec(&map->writecnt);
125 bool bpf_map_write_active(const struct bpf_map *map)
127 return atomic64_read(&map->writecnt) != 0;
130 static u32 bpf_map_value_size(const struct bpf_map *map)
132 if (map->map_type == BPF_MAP_TYPE_PERCPU_HASH ||
133 map->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH ||
134 map->map_type == BPF_MAP_TYPE_PERCPU_ARRAY ||
135 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
136 return round_up(map->value_size, 8) * num_possible_cpus();
137 else if (IS_FD_MAP(map))
140 return map->value_size;
143 static void maybe_wait_bpf_programs(struct bpf_map *map)
145 /* Wait for any running non-sleepable BPF programs to complete so that
146 * userspace, when we return to it, knows that all non-sleepable
147 * programs that could be running use the new map value. For sleepable
148 * BPF programs, synchronize_rcu_tasks_trace() should be used to wait
149 * for the completions of these programs, but considering the waiting
150 * time can be very long and userspace may think it will hang forever,
151 * so don't handle sleepable BPF programs now.
153 if (map->map_type == BPF_MAP_TYPE_HASH_OF_MAPS ||
154 map->map_type == BPF_MAP_TYPE_ARRAY_OF_MAPS)
158 static int bpf_map_update_value(struct bpf_map *map, struct file *map_file,
159 void *key, void *value, __u64 flags)
163 /* Need to create a kthread, thus must support schedule */
164 if (bpf_map_is_offloaded(map)) {
165 return bpf_map_offload_update_elem(map, key, value, flags);
166 } else if (map->map_type == BPF_MAP_TYPE_CPUMAP ||
167 map->map_type == BPF_MAP_TYPE_ARENA ||
168 map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
169 return map->ops->map_update_elem(map, key, value, flags);
170 } else if (map->map_type == BPF_MAP_TYPE_SOCKHASH ||
171 map->map_type == BPF_MAP_TYPE_SOCKMAP) {
172 return sock_map_update_elem_sys(map, key, value, flags);
173 } else if (IS_FD_PROG_ARRAY(map)) {
174 return bpf_fd_array_map_update_elem(map, map_file, key, value,
178 bpf_disable_instrumentation();
179 if (map->map_type == BPF_MAP_TYPE_PERCPU_HASH ||
180 map->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH) {
181 err = bpf_percpu_hash_update(map, key, value, flags);
182 } else if (map->map_type == BPF_MAP_TYPE_PERCPU_ARRAY) {
183 err = bpf_percpu_array_update(map, key, value, flags);
184 } else if (map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE) {
185 err = bpf_percpu_cgroup_storage_update(map, key, value,
187 } else if (IS_FD_ARRAY(map)) {
188 err = bpf_fd_array_map_update_elem(map, map_file, key, value,
190 } else if (map->map_type == BPF_MAP_TYPE_HASH_OF_MAPS) {
191 err = bpf_fd_htab_map_update_elem(map, map_file, key, value,
193 } else if (map->map_type == BPF_MAP_TYPE_REUSEPORT_SOCKARRAY) {
194 /* rcu_read_lock() is not needed */
195 err = bpf_fd_reuseport_array_update_elem(map, key, value,
197 } else if (map->map_type == BPF_MAP_TYPE_QUEUE ||
198 map->map_type == BPF_MAP_TYPE_STACK ||
199 map->map_type == BPF_MAP_TYPE_BLOOM_FILTER) {
200 err = map->ops->map_push_elem(map, value, flags);
203 err = map->ops->map_update_elem(map, key, value, flags);
206 bpf_enable_instrumentation();
211 static int bpf_map_copy_value(struct bpf_map *map, void *key, void *value,
217 if (bpf_map_is_offloaded(map))
218 return bpf_map_offload_lookup_elem(map, key, value);
220 bpf_disable_instrumentation();
221 if (map->map_type == BPF_MAP_TYPE_PERCPU_HASH ||
222 map->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH) {
223 err = bpf_percpu_hash_copy(map, key, value);
224 } else if (map->map_type == BPF_MAP_TYPE_PERCPU_ARRAY) {
225 err = bpf_percpu_array_copy(map, key, value);
226 } else if (map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE) {
227 err = bpf_percpu_cgroup_storage_copy(map, key, value);
228 } else if (map->map_type == BPF_MAP_TYPE_STACK_TRACE) {
229 err = bpf_stackmap_copy(map, key, value);
230 } else if (IS_FD_ARRAY(map) || IS_FD_PROG_ARRAY(map)) {
231 err = bpf_fd_array_map_lookup_elem(map, key, value);
232 } else if (IS_FD_HASH(map)) {
233 err = bpf_fd_htab_map_lookup_elem(map, key, value);
234 } else if (map->map_type == BPF_MAP_TYPE_REUSEPORT_SOCKARRAY) {
235 err = bpf_fd_reuseport_array_lookup_elem(map, key, value);
236 } else if (map->map_type == BPF_MAP_TYPE_QUEUE ||
237 map->map_type == BPF_MAP_TYPE_STACK ||
238 map->map_type == BPF_MAP_TYPE_BLOOM_FILTER) {
239 err = map->ops->map_peek_elem(map, value);
240 } else if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
241 /* struct_ops map requires directly updating "value" */
242 err = bpf_struct_ops_map_sys_lookup_elem(map, key, value);
245 if (map->ops->map_lookup_elem_sys_only)
246 ptr = map->ops->map_lookup_elem_sys_only(map, key);
248 ptr = map->ops->map_lookup_elem(map, key);
255 if (flags & BPF_F_LOCK)
256 /* lock 'ptr' and copy everything but lock */
257 copy_map_value_locked(map, value, ptr, true);
259 copy_map_value(map, value, ptr);
260 /* mask lock and timer, since value wasn't zero inited */
261 check_and_init_map_value(map, value);
266 bpf_enable_instrumentation();
271 /* Please, do not use this function outside from the map creation path
272 * (e.g. in map update path) without taking care of setting the active
273 * memory cgroup (see at bpf_map_kmalloc_node() for example).
275 static void *__bpf_map_area_alloc(u64 size, int numa_node, bool mmapable)
277 /* We really just want to fail instead of triggering OOM killer
278 * under memory pressure, therefore we set __GFP_NORETRY to kmalloc,
279 * which is used for lower order allocation requests.
281 * It has been observed that higher order allocation requests done by
282 * vmalloc with __GFP_NORETRY being set might fail due to not trying
283 * to reclaim memory from the page cache, thus we set
284 * __GFP_RETRY_MAYFAIL to avoid such situations.
287 gfp_t gfp = bpf_memcg_flags(__GFP_NOWARN | __GFP_ZERO);
288 unsigned int flags = 0;
289 unsigned long align = 1;
292 if (size >= SIZE_MAX)
295 /* kmalloc()'ed memory can't be mmap()'ed */
297 BUG_ON(!PAGE_ALIGNED(size));
300 } else if (size <= (PAGE_SIZE << PAGE_ALLOC_COSTLY_ORDER)) {
301 area = kmalloc_node(size, gfp | GFP_USER | __GFP_NORETRY,
307 return __vmalloc_node_range(size, align, VMALLOC_START, VMALLOC_END,
308 gfp | GFP_KERNEL | __GFP_RETRY_MAYFAIL, PAGE_KERNEL,
309 flags, numa_node, __builtin_return_address(0));
312 void *bpf_map_area_alloc(u64 size, int numa_node)
314 return __bpf_map_area_alloc(size, numa_node, false);
317 void *bpf_map_area_mmapable_alloc(u64 size, int numa_node)
319 return __bpf_map_area_alloc(size, numa_node, true);
322 void bpf_map_area_free(void *area)
327 static u32 bpf_map_flags_retain_permanent(u32 flags)
329 /* Some map creation flags are not tied to the map object but
330 * rather to the map fd instead, so they have no meaning upon
331 * map object inspection since multiple file descriptors with
332 * different (access) properties can exist here. Thus, given
333 * this has zero meaning for the map itself, lets clear these
336 return flags & ~(BPF_F_RDONLY | BPF_F_WRONLY);
339 void bpf_map_init_from_attr(struct bpf_map *map, union bpf_attr *attr)
341 map->map_type = attr->map_type;
342 map->key_size = attr->key_size;
343 map->value_size = attr->value_size;
344 map->max_entries = attr->max_entries;
345 map->map_flags = bpf_map_flags_retain_permanent(attr->map_flags);
346 map->numa_node = bpf_map_attr_numa_node(attr);
347 map->map_extra = attr->map_extra;
350 static int bpf_map_alloc_id(struct bpf_map *map)
354 idr_preload(GFP_KERNEL);
355 spin_lock_bh(&map_idr_lock);
356 id = idr_alloc_cyclic(&map_idr, map, 1, INT_MAX, GFP_ATOMIC);
359 spin_unlock_bh(&map_idr_lock);
362 if (WARN_ON_ONCE(!id))
365 return id > 0 ? 0 : id;
368 void bpf_map_free_id(struct bpf_map *map)
372 /* Offloaded maps are removed from the IDR store when their device
373 * disappears - even if someone holds an fd to them they are unusable,
374 * the memory is gone, all ops will fail; they are simply waiting for
375 * refcnt to drop to be freed.
380 spin_lock_irqsave(&map_idr_lock, flags);
382 idr_remove(&map_idr, map->id);
385 spin_unlock_irqrestore(&map_idr_lock, flags);
389 static void bpf_map_save_memcg(struct bpf_map *map)
391 /* Currently if a map is created by a process belonging to the root
392 * memory cgroup, get_obj_cgroup_from_current() will return NULL.
393 * So we have to check map->objcg for being NULL each time it's
396 if (memcg_bpf_enabled())
397 map->objcg = get_obj_cgroup_from_current();
400 static void bpf_map_release_memcg(struct bpf_map *map)
403 obj_cgroup_put(map->objcg);
406 static struct mem_cgroup *bpf_map_get_memcg(const struct bpf_map *map)
409 return get_mem_cgroup_from_objcg(map->objcg);
411 return root_mem_cgroup;
414 void *bpf_map_kmalloc_node(const struct bpf_map *map, size_t size, gfp_t flags,
417 struct mem_cgroup *memcg, *old_memcg;
420 memcg = bpf_map_get_memcg(map);
421 old_memcg = set_active_memcg(memcg);
422 ptr = kmalloc_node(size, flags | __GFP_ACCOUNT, node);
423 set_active_memcg(old_memcg);
424 mem_cgroup_put(memcg);
429 void *bpf_map_kzalloc(const struct bpf_map *map, size_t size, gfp_t flags)
431 struct mem_cgroup *memcg, *old_memcg;
434 memcg = bpf_map_get_memcg(map);
435 old_memcg = set_active_memcg(memcg);
436 ptr = kzalloc(size, flags | __GFP_ACCOUNT);
437 set_active_memcg(old_memcg);
438 mem_cgroup_put(memcg);
443 void *bpf_map_kvcalloc(struct bpf_map *map, size_t n, size_t size,
446 struct mem_cgroup *memcg, *old_memcg;
449 memcg = bpf_map_get_memcg(map);
450 old_memcg = set_active_memcg(memcg);
451 ptr = kvcalloc(n, size, flags | __GFP_ACCOUNT);
452 set_active_memcg(old_memcg);
453 mem_cgroup_put(memcg);
458 void __percpu *bpf_map_alloc_percpu(const struct bpf_map *map, size_t size,
459 size_t align, gfp_t flags)
461 struct mem_cgroup *memcg, *old_memcg;
464 memcg = bpf_map_get_memcg(map);
465 old_memcg = set_active_memcg(memcg);
466 ptr = __alloc_percpu_gfp(size, align, flags | __GFP_ACCOUNT);
467 set_active_memcg(old_memcg);
468 mem_cgroup_put(memcg);
474 static void bpf_map_save_memcg(struct bpf_map *map)
478 static void bpf_map_release_memcg(struct bpf_map *map)
483 int bpf_map_alloc_pages(const struct bpf_map *map, gfp_t gfp, int nid,
484 unsigned long nr_pages, struct page **pages)
490 struct mem_cgroup *memcg, *old_memcg;
492 memcg = bpf_map_get_memcg(map);
493 old_memcg = set_active_memcg(memcg);
495 for (i = 0; i < nr_pages; i++) {
496 pg = alloc_pages_node(nid, gfp | __GFP_ACCOUNT, 0);
502 for (j = 0; j < i; j++)
503 __free_page(pages[j]);
509 set_active_memcg(old_memcg);
510 mem_cgroup_put(memcg);
516 static int btf_field_cmp(const void *a, const void *b)
518 const struct btf_field *f1 = a, *f2 = b;
520 if (f1->offset < f2->offset)
522 else if (f1->offset > f2->offset)
527 struct btf_field *btf_record_find(const struct btf_record *rec, u32 offset,
530 struct btf_field *field;
532 if (IS_ERR_OR_NULL(rec) || !(rec->field_mask & field_mask))
534 field = bsearch(&offset, rec->fields, rec->cnt, sizeof(rec->fields[0]), btf_field_cmp);
535 if (!field || !(field->type & field_mask))
540 void btf_record_free(struct btf_record *rec)
544 if (IS_ERR_OR_NULL(rec))
546 for (i = 0; i < rec->cnt; i++) {
547 switch (rec->fields[i].type) {
550 case BPF_KPTR_PERCPU:
551 if (rec->fields[i].kptr.module)
552 module_put(rec->fields[i].kptr.module);
553 if (btf_is_kernel(rec->fields[i].kptr.btf))
554 btf_put(rec->fields[i].kptr.btf);
564 /* Nothing to release */
574 void bpf_map_free_record(struct bpf_map *map)
576 btf_record_free(map->record);
580 struct btf_record *btf_record_dup(const struct btf_record *rec)
582 const struct btf_field *fields;
583 struct btf_record *new_rec;
586 if (IS_ERR_OR_NULL(rec))
588 size = offsetof(struct btf_record, fields[rec->cnt]);
589 new_rec = kmemdup(rec, size, GFP_KERNEL | __GFP_NOWARN);
591 return ERR_PTR(-ENOMEM);
592 /* Do a deep copy of the btf_record */
593 fields = rec->fields;
595 for (i = 0; i < rec->cnt; i++) {
596 switch (fields[i].type) {
599 case BPF_KPTR_PERCPU:
600 if (btf_is_kernel(fields[i].kptr.btf))
601 btf_get(fields[i].kptr.btf);
602 if (fields[i].kptr.module && !try_module_get(fields[i].kptr.module)) {
615 /* Nothing to acquire */
626 btf_record_free(new_rec);
630 bool btf_record_equal(const struct btf_record *rec_a, const struct btf_record *rec_b)
632 bool a_has_fields = !IS_ERR_OR_NULL(rec_a), b_has_fields = !IS_ERR_OR_NULL(rec_b);
635 if (!a_has_fields && !b_has_fields)
637 if (a_has_fields != b_has_fields)
639 if (rec_a->cnt != rec_b->cnt)
641 size = offsetof(struct btf_record, fields[rec_a->cnt]);
642 /* btf_parse_fields uses kzalloc to allocate a btf_record, so unused
643 * members are zeroed out. So memcmp is safe to do without worrying
644 * about padding/unused fields.
646 * While spin_lock, timer, and kptr have no relation to map BTF,
647 * list_head metadata is specific to map BTF, the btf and value_rec
648 * members in particular. btf is the map BTF, while value_rec points to
649 * btf_record in that map BTF.
651 * So while by default, we don't rely on the map BTF (which the records
652 * were parsed from) matching for both records, which is not backwards
653 * compatible, in case list_head is part of it, we implicitly rely on
654 * that by way of depending on memcmp succeeding for it.
656 return !memcmp(rec_a, rec_b, size);
659 void bpf_obj_free_timer(const struct btf_record *rec, void *obj)
661 if (WARN_ON_ONCE(!btf_record_has_field(rec, BPF_TIMER)))
663 bpf_timer_cancel_and_free(obj + rec->timer_off);
666 void bpf_obj_free_workqueue(const struct btf_record *rec, void *obj)
668 if (WARN_ON_ONCE(!btf_record_has_field(rec, BPF_WORKQUEUE)))
670 bpf_wq_cancel_and_free(obj + rec->wq_off);
673 void bpf_obj_free_fields(const struct btf_record *rec, void *obj)
675 const struct btf_field *fields;
678 if (IS_ERR_OR_NULL(rec))
680 fields = rec->fields;
681 for (i = 0; i < rec->cnt; i++) {
682 struct btf_struct_meta *pointee_struct_meta;
683 const struct btf_field *field = &fields[i];
684 void *field_ptr = obj + field->offset;
687 switch (fields[i].type) {
691 bpf_timer_cancel_and_free(field_ptr);
694 bpf_wq_cancel_and_free(field_ptr);
697 WRITE_ONCE(*(u64 *)field_ptr, 0);
700 case BPF_KPTR_PERCPU:
701 xchgd_field = (void *)xchg((unsigned long *)field_ptr, 0);
705 if (!btf_is_kernel(field->kptr.btf)) {
706 pointee_struct_meta = btf_find_struct_meta(field->kptr.btf,
709 __bpf_obj_drop_impl(xchgd_field, pointee_struct_meta ?
710 pointee_struct_meta->record : NULL,
711 fields[i].type == BPF_KPTR_PERCPU);
714 field->kptr.dtor(xchgd_field);
718 if (WARN_ON_ONCE(rec->spin_lock_off < 0))
720 bpf_list_head_free(field, field_ptr, obj + rec->spin_lock_off);
723 if (WARN_ON_ONCE(rec->spin_lock_off < 0))
725 bpf_rb_root_free(field, field_ptr, obj + rec->spin_lock_off);
738 static void bpf_map_free(struct bpf_map *map)
740 struct btf_record *rec = map->record;
741 struct btf *btf = map->btf;
743 /* implementation dependent freeing */
744 map->ops->map_free(map);
745 /* Delay freeing of btf_record for maps, as map_free
746 * callback usually needs access to them. It is better to do it here
747 * than require each callback to do the free itself manually.
749 * Note that the btf_record stashed in map->inner_map_meta->record was
750 * already freed using the map_free callback for map in map case which
751 * eventually calls bpf_map_free_meta, since inner_map_meta is only a
752 * template bpf_map struct used during verification.
754 btf_record_free(rec);
755 /* Delay freeing of btf for maps, as map_free callback may need
756 * struct_meta info which will be freed with btf_put().
761 /* called from workqueue */
762 static void bpf_map_free_deferred(struct work_struct *work)
764 struct bpf_map *map = container_of(work, struct bpf_map, work);
766 security_bpf_map_free(map);
767 bpf_map_release_memcg(map);
771 static void bpf_map_put_uref(struct bpf_map *map)
773 if (atomic64_dec_and_test(&map->usercnt)) {
774 if (map->ops->map_release_uref)
775 map->ops->map_release_uref(map);
779 static void bpf_map_free_in_work(struct bpf_map *map)
781 INIT_WORK(&map->work, bpf_map_free_deferred);
782 /* Avoid spawning kworkers, since they all might contend
783 * for the same mutex like slab_mutex.
785 queue_work(system_unbound_wq, &map->work);
788 static void bpf_map_free_rcu_gp(struct rcu_head *rcu)
790 bpf_map_free_in_work(container_of(rcu, struct bpf_map, rcu));
793 static void bpf_map_free_mult_rcu_gp(struct rcu_head *rcu)
795 if (rcu_trace_implies_rcu_gp())
796 bpf_map_free_rcu_gp(rcu);
798 call_rcu(rcu, bpf_map_free_rcu_gp);
801 /* decrement map refcnt and schedule it for freeing via workqueue
802 * (underlying map implementation ops->map_free() might sleep)
804 void bpf_map_put(struct bpf_map *map)
806 if (atomic64_dec_and_test(&map->refcnt)) {
807 /* bpf_map_free_id() must be called first */
808 bpf_map_free_id(map);
810 WARN_ON_ONCE(atomic64_read(&map->sleepable_refcnt));
811 if (READ_ONCE(map->free_after_mult_rcu_gp))
812 call_rcu_tasks_trace(&map->rcu, bpf_map_free_mult_rcu_gp);
813 else if (READ_ONCE(map->free_after_rcu_gp))
814 call_rcu(&map->rcu, bpf_map_free_rcu_gp);
816 bpf_map_free_in_work(map);
819 EXPORT_SYMBOL_GPL(bpf_map_put);
821 void bpf_map_put_with_uref(struct bpf_map *map)
823 bpf_map_put_uref(map);
827 static int bpf_map_release(struct inode *inode, struct file *filp)
829 struct bpf_map *map = filp->private_data;
831 if (map->ops->map_release)
832 map->ops->map_release(map, filp);
834 bpf_map_put_with_uref(map);
838 static fmode_t map_get_sys_perms(struct bpf_map *map, struct fd f)
840 fmode_t mode = fd_file(f)->f_mode;
842 /* Our file permissions may have been overridden by global
843 * map permissions facing syscall side.
845 if (READ_ONCE(map->frozen))
846 mode &= ~FMODE_CAN_WRITE;
850 #ifdef CONFIG_PROC_FS
851 /* Show the memory usage of a bpf map */
852 static u64 bpf_map_memory_usage(const struct bpf_map *map)
854 return map->ops->map_mem_usage(map);
857 static void bpf_map_show_fdinfo(struct seq_file *m, struct file *filp)
859 struct bpf_map *map = filp->private_data;
860 u32 type = 0, jited = 0;
862 if (map_type_contains_progs(map)) {
863 spin_lock(&map->owner.lock);
864 type = map->owner.type;
865 jited = map->owner.jited;
866 spin_unlock(&map->owner.lock);
875 "map_extra:\t%#llx\n"
884 (unsigned long long)map->map_extra,
885 bpf_map_memory_usage(map),
887 READ_ONCE(map->frozen));
889 seq_printf(m, "owner_prog_type:\t%u\n", type);
890 seq_printf(m, "owner_jited:\t%u\n", jited);
895 static ssize_t bpf_dummy_read(struct file *filp, char __user *buf, size_t siz,
898 /* We need this handler such that alloc_file() enables
899 * f_mode with FMODE_CAN_READ.
904 static ssize_t bpf_dummy_write(struct file *filp, const char __user *buf,
905 size_t siz, loff_t *ppos)
907 /* We need this handler such that alloc_file() enables
908 * f_mode with FMODE_CAN_WRITE.
913 /* called for any extra memory-mapped regions (except initial) */
914 static void bpf_map_mmap_open(struct vm_area_struct *vma)
916 struct bpf_map *map = vma->vm_file->private_data;
918 if (vma->vm_flags & VM_MAYWRITE)
919 bpf_map_write_active_inc(map);
922 /* called for all unmapped memory region (including initial) */
923 static void bpf_map_mmap_close(struct vm_area_struct *vma)
925 struct bpf_map *map = vma->vm_file->private_data;
927 if (vma->vm_flags & VM_MAYWRITE)
928 bpf_map_write_active_dec(map);
931 static const struct vm_operations_struct bpf_map_default_vmops = {
932 .open = bpf_map_mmap_open,
933 .close = bpf_map_mmap_close,
936 static int bpf_map_mmap(struct file *filp, struct vm_area_struct *vma)
938 struct bpf_map *map = filp->private_data;
941 if (!map->ops->map_mmap || !IS_ERR_OR_NULL(map->record))
944 if (!(vma->vm_flags & VM_SHARED))
947 mutex_lock(&map->freeze_mutex);
949 if (vma->vm_flags & VM_WRITE) {
954 /* map is meant to be read-only, so do not allow mapping as
955 * writable, because it's possible to leak a writable page
956 * reference and allows user-space to still modify it after
957 * freezing, while verifier will assume contents do not change
959 if (map->map_flags & BPF_F_RDONLY_PROG) {
965 /* set default open/close callbacks */
966 vma->vm_ops = &bpf_map_default_vmops;
967 vma->vm_private_data = map;
968 vm_flags_clear(vma, VM_MAYEXEC);
969 if (!(vma->vm_flags & VM_WRITE))
970 /* disallow re-mapping with PROT_WRITE */
971 vm_flags_clear(vma, VM_MAYWRITE);
973 err = map->ops->map_mmap(map, vma);
977 if (vma->vm_flags & VM_MAYWRITE)
978 bpf_map_write_active_inc(map);
980 mutex_unlock(&map->freeze_mutex);
984 static __poll_t bpf_map_poll(struct file *filp, struct poll_table_struct *pts)
986 struct bpf_map *map = filp->private_data;
988 if (map->ops->map_poll)
989 return map->ops->map_poll(map, filp, pts);
994 static unsigned long bpf_get_unmapped_area(struct file *filp, unsigned long addr,
995 unsigned long len, unsigned long pgoff,
998 struct bpf_map *map = filp->private_data;
1000 if (map->ops->map_get_unmapped_area)
1001 return map->ops->map_get_unmapped_area(filp, addr, len, pgoff, flags);
1003 return mm_get_unmapped_area(current->mm, filp, addr, len, pgoff, flags);
1009 const struct file_operations bpf_map_fops = {
1010 #ifdef CONFIG_PROC_FS
1011 .show_fdinfo = bpf_map_show_fdinfo,
1013 .release = bpf_map_release,
1014 .read = bpf_dummy_read,
1015 .write = bpf_dummy_write,
1016 .mmap = bpf_map_mmap,
1017 .poll = bpf_map_poll,
1018 .get_unmapped_area = bpf_get_unmapped_area,
1021 int bpf_map_new_fd(struct bpf_map *map, int flags)
1025 ret = security_bpf_map(map, OPEN_FMODE(flags));
1029 return anon_inode_getfd("bpf-map", &bpf_map_fops, map,
1033 int bpf_get_file_flag(int flags)
1035 if ((flags & BPF_F_RDONLY) && (flags & BPF_F_WRONLY))
1037 if (flags & BPF_F_RDONLY)
1039 if (flags & BPF_F_WRONLY)
1044 /* helper macro to check that unused fields 'union bpf_attr' are zero */
1045 #define CHECK_ATTR(CMD) \
1046 memchr_inv((void *) &attr->CMD##_LAST_FIELD + \
1047 sizeof(attr->CMD##_LAST_FIELD), 0, \
1049 offsetof(union bpf_attr, CMD##_LAST_FIELD) - \
1050 sizeof(attr->CMD##_LAST_FIELD)) != NULL
1052 /* dst and src must have at least "size" number of bytes.
1053 * Return strlen on success and < 0 on error.
1055 int bpf_obj_name_cpy(char *dst, const char *src, unsigned int size)
1057 const char *end = src + size;
1058 const char *orig_src = src;
1060 memset(dst, 0, size);
1061 /* Copy all isalnum(), '_' and '.' chars. */
1062 while (src < end && *src) {
1063 if (!isalnum(*src) &&
1064 *src != '_' && *src != '.')
1069 /* No '\0' found in "size" number of bytes */
1073 return src - orig_src;
1076 int map_check_no_btf(const struct bpf_map *map,
1077 const struct btf *btf,
1078 const struct btf_type *key_type,
1079 const struct btf_type *value_type)
1084 static int map_check_btf(struct bpf_map *map, struct bpf_token *token,
1085 const struct btf *btf, u32 btf_key_id, u32 btf_value_id)
1087 const struct btf_type *key_type, *value_type;
1088 u32 key_size, value_size;
1091 /* Some maps allow key to be unspecified. */
1093 key_type = btf_type_id_size(btf, &btf_key_id, &key_size);
1094 if (!key_type || key_size != map->key_size)
1097 key_type = btf_type_by_id(btf, 0);
1098 if (!map->ops->map_check_btf)
1102 value_type = btf_type_id_size(btf, &btf_value_id, &value_size);
1103 if (!value_type || value_size != map->value_size)
1106 map->record = btf_parse_fields(btf, value_type,
1107 BPF_SPIN_LOCK | BPF_TIMER | BPF_KPTR | BPF_LIST_HEAD |
1108 BPF_RB_ROOT | BPF_REFCOUNT | BPF_WORKQUEUE,
1110 if (!IS_ERR_OR_NULL(map->record)) {
1113 if (!bpf_token_capable(token, CAP_BPF)) {
1117 if (map->map_flags & (BPF_F_RDONLY_PROG | BPF_F_WRONLY_PROG)) {
1121 for (i = 0; i < sizeof(map->record->field_mask) * 8; i++) {
1122 switch (map->record->field_mask & (1 << i)) {
1126 if (map->map_type != BPF_MAP_TYPE_HASH &&
1127 map->map_type != BPF_MAP_TYPE_ARRAY &&
1128 map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
1129 map->map_type != BPF_MAP_TYPE_SK_STORAGE &&
1130 map->map_type != BPF_MAP_TYPE_INODE_STORAGE &&
1131 map->map_type != BPF_MAP_TYPE_TASK_STORAGE &&
1132 map->map_type != BPF_MAP_TYPE_CGRP_STORAGE) {
1139 if (map->map_type != BPF_MAP_TYPE_HASH &&
1140 map->map_type != BPF_MAP_TYPE_LRU_HASH &&
1141 map->map_type != BPF_MAP_TYPE_ARRAY) {
1146 case BPF_KPTR_UNREF:
1148 case BPF_KPTR_PERCPU:
1150 if (map->map_type != BPF_MAP_TYPE_HASH &&
1151 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
1152 map->map_type != BPF_MAP_TYPE_LRU_HASH &&
1153 map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH &&
1154 map->map_type != BPF_MAP_TYPE_ARRAY &&
1155 map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
1156 map->map_type != BPF_MAP_TYPE_SK_STORAGE &&
1157 map->map_type != BPF_MAP_TYPE_INODE_STORAGE &&
1158 map->map_type != BPF_MAP_TYPE_TASK_STORAGE &&
1159 map->map_type != BPF_MAP_TYPE_CGRP_STORAGE) {
1166 if (map->map_type != BPF_MAP_TYPE_HASH &&
1167 map->map_type != BPF_MAP_TYPE_LRU_HASH &&
1168 map->map_type != BPF_MAP_TYPE_ARRAY) {
1174 /* Fail if map_type checks are missing for a field type */
1181 ret = btf_check_and_fixup_fields(btf, map->record);
1185 if (map->ops->map_check_btf) {
1186 ret = map->ops->map_check_btf(map, btf, key_type, value_type);
1193 bpf_map_free_record(map);
1197 static bool bpf_net_capable(void)
1199 return capable(CAP_NET_ADMIN) || capable(CAP_SYS_ADMIN);
1202 #define BPF_MAP_CREATE_LAST_FIELD map_token_fd
1203 /* called via syscall */
1204 static int map_create(union bpf_attr *attr)
1206 const struct bpf_map_ops *ops;
1207 struct bpf_token *token = NULL;
1208 int numa_node = bpf_map_attr_numa_node(attr);
1209 u32 map_type = attr->map_type;
1210 struct bpf_map *map;
1215 err = CHECK_ATTR(BPF_MAP_CREATE);
1219 /* check BPF_F_TOKEN_FD flag, remember if it's set, and then clear it
1220 * to avoid per-map type checks tripping on unknown flag
1222 token_flag = attr->map_flags & BPF_F_TOKEN_FD;
1223 attr->map_flags &= ~BPF_F_TOKEN_FD;
1225 if (attr->btf_vmlinux_value_type_id) {
1226 if (attr->map_type != BPF_MAP_TYPE_STRUCT_OPS ||
1227 attr->btf_key_type_id || attr->btf_value_type_id)
1229 } else if (attr->btf_key_type_id && !attr->btf_value_type_id) {
1233 if (attr->map_type != BPF_MAP_TYPE_BLOOM_FILTER &&
1234 attr->map_type != BPF_MAP_TYPE_ARENA &&
1235 attr->map_extra != 0)
1238 f_flags = bpf_get_file_flag(attr->map_flags);
1242 if (numa_node != NUMA_NO_NODE &&
1243 ((unsigned int)numa_node >= nr_node_ids ||
1244 !node_online(numa_node)))
1247 /* find map type and init map: hashtable vs rbtree vs bloom vs ... */
1248 map_type = attr->map_type;
1249 if (map_type >= ARRAY_SIZE(bpf_map_types))
1251 map_type = array_index_nospec(map_type, ARRAY_SIZE(bpf_map_types));
1252 ops = bpf_map_types[map_type];
1256 if (ops->map_alloc_check) {
1257 err = ops->map_alloc_check(attr);
1261 if (attr->map_ifindex)
1262 ops = &bpf_map_offload_ops;
1263 if (!ops->map_mem_usage)
1267 token = bpf_token_get_from_fd(attr->map_token_fd);
1269 return PTR_ERR(token);
1271 /* if current token doesn't grant map creation permissions,
1272 * then we can't use this token, so ignore it and rely on
1273 * system-wide capabilities checks
1275 if (!bpf_token_allow_cmd(token, BPF_MAP_CREATE) ||
1276 !bpf_token_allow_map_type(token, attr->map_type)) {
1277 bpf_token_put(token);
1284 /* Intent here is for unprivileged_bpf_disabled to block BPF map
1285 * creation for unprivileged users; other actions depend
1286 * on fd availability and access to bpffs, so are dependent on
1287 * object creation success. Even with unprivileged BPF disabled,
1288 * capability checks are still carried out.
1290 if (sysctl_unprivileged_bpf_disabled && !bpf_token_capable(token, CAP_BPF))
1293 /* check privileged map type permissions */
1295 case BPF_MAP_TYPE_ARRAY:
1296 case BPF_MAP_TYPE_PERCPU_ARRAY:
1297 case BPF_MAP_TYPE_PROG_ARRAY:
1298 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
1299 case BPF_MAP_TYPE_CGROUP_ARRAY:
1300 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
1301 case BPF_MAP_TYPE_HASH:
1302 case BPF_MAP_TYPE_PERCPU_HASH:
1303 case BPF_MAP_TYPE_HASH_OF_MAPS:
1304 case BPF_MAP_TYPE_RINGBUF:
1305 case BPF_MAP_TYPE_USER_RINGBUF:
1306 case BPF_MAP_TYPE_CGROUP_STORAGE:
1307 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
1310 case BPF_MAP_TYPE_SK_STORAGE:
1311 case BPF_MAP_TYPE_INODE_STORAGE:
1312 case BPF_MAP_TYPE_TASK_STORAGE:
1313 case BPF_MAP_TYPE_CGRP_STORAGE:
1314 case BPF_MAP_TYPE_BLOOM_FILTER:
1315 case BPF_MAP_TYPE_LPM_TRIE:
1316 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
1317 case BPF_MAP_TYPE_STACK_TRACE:
1318 case BPF_MAP_TYPE_QUEUE:
1319 case BPF_MAP_TYPE_STACK:
1320 case BPF_MAP_TYPE_LRU_HASH:
1321 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
1322 case BPF_MAP_TYPE_STRUCT_OPS:
1323 case BPF_MAP_TYPE_CPUMAP:
1324 case BPF_MAP_TYPE_ARENA:
1325 if (!bpf_token_capable(token, CAP_BPF))
1328 case BPF_MAP_TYPE_SOCKMAP:
1329 case BPF_MAP_TYPE_SOCKHASH:
1330 case BPF_MAP_TYPE_DEVMAP:
1331 case BPF_MAP_TYPE_DEVMAP_HASH:
1332 case BPF_MAP_TYPE_XSKMAP:
1333 if (!bpf_token_capable(token, CAP_NET_ADMIN))
1337 WARN(1, "unsupported map type %d", map_type);
1341 map = ops->map_alloc(attr);
1347 map->map_type = map_type;
1349 err = bpf_obj_name_cpy(map->name, attr->map_name,
1350 sizeof(attr->map_name));
1354 atomic64_set(&map->refcnt, 1);
1355 atomic64_set(&map->usercnt, 1);
1356 mutex_init(&map->freeze_mutex);
1357 spin_lock_init(&map->owner.lock);
1359 if (attr->btf_key_type_id || attr->btf_value_type_id ||
1360 /* Even the map's value is a kernel's struct,
1361 * the bpf_prog.o must have BTF to begin with
1362 * to figure out the corresponding kernel's
1363 * counter part. Thus, attr->btf_fd has
1366 attr->btf_vmlinux_value_type_id) {
1369 btf = btf_get_by_fd(attr->btf_fd);
1374 if (btf_is_kernel(btf)) {
1381 if (attr->btf_value_type_id) {
1382 err = map_check_btf(map, token, btf, attr->btf_key_type_id,
1383 attr->btf_value_type_id);
1388 map->btf_key_type_id = attr->btf_key_type_id;
1389 map->btf_value_type_id = attr->btf_value_type_id;
1390 map->btf_vmlinux_value_type_id =
1391 attr->btf_vmlinux_value_type_id;
1394 err = security_bpf_map_create(map, attr, token);
1398 err = bpf_map_alloc_id(map);
1402 bpf_map_save_memcg(map);
1403 bpf_token_put(token);
1405 err = bpf_map_new_fd(map, f_flags);
1407 /* failed to allocate fd.
1408 * bpf_map_put_with_uref() is needed because the above
1409 * bpf_map_alloc_id() has published the map
1410 * to the userspace and the userspace may
1411 * have refcnt-ed it through BPF_MAP_GET_FD_BY_ID.
1413 bpf_map_put_with_uref(map);
1420 security_bpf_map_free(map);
1424 bpf_token_put(token);
1428 void bpf_map_inc(struct bpf_map *map)
1430 atomic64_inc(&map->refcnt);
1432 EXPORT_SYMBOL_GPL(bpf_map_inc);
1434 void bpf_map_inc_with_uref(struct bpf_map *map)
1436 atomic64_inc(&map->refcnt);
1437 atomic64_inc(&map->usercnt);
1439 EXPORT_SYMBOL_GPL(bpf_map_inc_with_uref);
1441 struct bpf_map *bpf_map_get(u32 ufd)
1444 struct bpf_map *map = __bpf_map_get(f);
1451 EXPORT_SYMBOL(bpf_map_get);
1453 struct bpf_map *bpf_map_get_with_uref(u32 ufd)
1456 struct bpf_map *map = __bpf_map_get(f);
1459 bpf_map_inc_with_uref(map);
1464 /* map_idr_lock should have been held or the map should have been
1465 * protected by rcu read lock.
1467 struct bpf_map *__bpf_map_inc_not_zero(struct bpf_map *map, bool uref)
1471 refold = atomic64_fetch_add_unless(&map->refcnt, 1, 0);
1473 return ERR_PTR(-ENOENT);
1475 atomic64_inc(&map->usercnt);
1480 struct bpf_map *bpf_map_inc_not_zero(struct bpf_map *map)
1482 spin_lock_bh(&map_idr_lock);
1483 map = __bpf_map_inc_not_zero(map, false);
1484 spin_unlock_bh(&map_idr_lock);
1488 EXPORT_SYMBOL_GPL(bpf_map_inc_not_zero);
1490 int __weak bpf_stackmap_copy(struct bpf_map *map, void *key, void *value)
1495 static void *__bpf_copy_key(void __user *ukey, u64 key_size)
1498 return vmemdup_user(ukey, key_size);
1501 return ERR_PTR(-EINVAL);
1506 static void *___bpf_copy_key(bpfptr_t ukey, u64 key_size)
1509 return kvmemdup_bpfptr(ukey, key_size);
1511 if (!bpfptr_is_null(ukey))
1512 return ERR_PTR(-EINVAL);
1517 /* last field in 'union bpf_attr' used by this command */
1518 #define BPF_MAP_LOOKUP_ELEM_LAST_FIELD flags
1520 static int map_lookup_elem(union bpf_attr *attr)
1522 void __user *ukey = u64_to_user_ptr(attr->key);
1523 void __user *uvalue = u64_to_user_ptr(attr->value);
1524 struct bpf_map *map;
1529 if (CHECK_ATTR(BPF_MAP_LOOKUP_ELEM))
1532 if (attr->flags & ~BPF_F_LOCK)
1535 CLASS(fd, f)(attr->map_fd);
1536 map = __bpf_map_get(f);
1538 return PTR_ERR(map);
1539 if (!(map_get_sys_perms(map, f) & FMODE_CAN_READ))
1542 if ((attr->flags & BPF_F_LOCK) &&
1543 !btf_record_has_field(map->record, BPF_SPIN_LOCK))
1546 key = __bpf_copy_key(ukey, map->key_size);
1548 return PTR_ERR(key);
1550 value_size = bpf_map_value_size(map);
1553 value = kvmalloc(value_size, GFP_USER | __GFP_NOWARN);
1557 if (map->map_type == BPF_MAP_TYPE_BLOOM_FILTER) {
1558 if (copy_from_user(value, uvalue, value_size))
1561 err = bpf_map_copy_value(map, key, value, attr->flags);
1565 err = bpf_map_copy_value(map, key, value, attr->flags);
1570 if (copy_to_user(uvalue, value, value_size) != 0)
1583 #define BPF_MAP_UPDATE_ELEM_LAST_FIELD flags
1585 static int map_update_elem(union bpf_attr *attr, bpfptr_t uattr)
1587 bpfptr_t ukey = make_bpfptr(attr->key, uattr.is_kernel);
1588 bpfptr_t uvalue = make_bpfptr(attr->value, uattr.is_kernel);
1589 struct bpf_map *map;
1594 if (CHECK_ATTR(BPF_MAP_UPDATE_ELEM))
1597 CLASS(fd, f)(attr->map_fd);
1598 map = __bpf_map_get(f);
1600 return PTR_ERR(map);
1601 bpf_map_write_active_inc(map);
1602 if (!(map_get_sys_perms(map, f) & FMODE_CAN_WRITE)) {
1607 if ((attr->flags & BPF_F_LOCK) &&
1608 !btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
1613 key = ___bpf_copy_key(ukey, map->key_size);
1619 value_size = bpf_map_value_size(map);
1620 value = kvmemdup_bpfptr(uvalue, value_size);
1621 if (IS_ERR(value)) {
1622 err = PTR_ERR(value);
1626 err = bpf_map_update_value(map, fd_file(f), key, value, attr->flags);
1628 maybe_wait_bpf_programs(map);
1634 bpf_map_write_active_dec(map);
1638 #define BPF_MAP_DELETE_ELEM_LAST_FIELD key
1640 static int map_delete_elem(union bpf_attr *attr, bpfptr_t uattr)
1642 bpfptr_t ukey = make_bpfptr(attr->key, uattr.is_kernel);
1643 struct bpf_map *map;
1647 if (CHECK_ATTR(BPF_MAP_DELETE_ELEM))
1650 CLASS(fd, f)(attr->map_fd);
1651 map = __bpf_map_get(f);
1653 return PTR_ERR(map);
1654 bpf_map_write_active_inc(map);
1655 if (!(map_get_sys_perms(map, f) & FMODE_CAN_WRITE)) {
1660 key = ___bpf_copy_key(ukey, map->key_size);
1666 if (bpf_map_is_offloaded(map)) {
1667 err = bpf_map_offload_delete_elem(map, key);
1669 } else if (IS_FD_PROG_ARRAY(map) ||
1670 map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
1671 /* These maps require sleepable context */
1672 err = map->ops->map_delete_elem(map, key);
1676 bpf_disable_instrumentation();
1678 err = map->ops->map_delete_elem(map, key);
1680 bpf_enable_instrumentation();
1682 maybe_wait_bpf_programs(map);
1686 bpf_map_write_active_dec(map);
1690 /* last field in 'union bpf_attr' used by this command */
1691 #define BPF_MAP_GET_NEXT_KEY_LAST_FIELD next_key
1693 static int map_get_next_key(union bpf_attr *attr)
1695 void __user *ukey = u64_to_user_ptr(attr->key);
1696 void __user *unext_key = u64_to_user_ptr(attr->next_key);
1697 struct bpf_map *map;
1698 void *key, *next_key;
1701 if (CHECK_ATTR(BPF_MAP_GET_NEXT_KEY))
1704 CLASS(fd, f)(attr->map_fd);
1705 map = __bpf_map_get(f);
1707 return PTR_ERR(map);
1708 if (!(map_get_sys_perms(map, f) & FMODE_CAN_READ))
1712 key = __bpf_copy_key(ukey, map->key_size);
1714 return PTR_ERR(key);
1720 next_key = kvmalloc(map->key_size, GFP_USER);
1724 if (bpf_map_is_offloaded(map)) {
1725 err = bpf_map_offload_get_next_key(map, key, next_key);
1730 err = map->ops->map_get_next_key(map, key, next_key);
1737 if (copy_to_user(unext_key, next_key, map->key_size) != 0)
1749 int generic_map_delete_batch(struct bpf_map *map,
1750 const union bpf_attr *attr,
1751 union bpf_attr __user *uattr)
1753 void __user *keys = u64_to_user_ptr(attr->batch.keys);
1758 if (attr->batch.elem_flags & ~BPF_F_LOCK)
1761 if ((attr->batch.elem_flags & BPF_F_LOCK) &&
1762 !btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
1766 max_count = attr->batch.count;
1770 if (put_user(0, &uattr->batch.count))
1773 key = kvmalloc(map->key_size, GFP_USER | __GFP_NOWARN);
1777 for (cp = 0; cp < max_count; cp++) {
1779 if (copy_from_user(key, keys + cp * map->key_size,
1783 if (bpf_map_is_offloaded(map)) {
1784 err = bpf_map_offload_delete_elem(map, key);
1788 bpf_disable_instrumentation();
1790 err = map->ops->map_delete_elem(map, key);
1792 bpf_enable_instrumentation();
1797 if (copy_to_user(&uattr->batch.count, &cp, sizeof(cp)))
1805 int generic_map_update_batch(struct bpf_map *map, struct file *map_file,
1806 const union bpf_attr *attr,
1807 union bpf_attr __user *uattr)
1809 void __user *values = u64_to_user_ptr(attr->batch.values);
1810 void __user *keys = u64_to_user_ptr(attr->batch.keys);
1811 u32 value_size, cp, max_count;
1815 if (attr->batch.elem_flags & ~BPF_F_LOCK)
1818 if ((attr->batch.elem_flags & BPF_F_LOCK) &&
1819 !btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
1823 value_size = bpf_map_value_size(map);
1825 max_count = attr->batch.count;
1829 if (put_user(0, &uattr->batch.count))
1832 key = kvmalloc(map->key_size, GFP_USER | __GFP_NOWARN);
1836 value = kvmalloc(value_size, GFP_USER | __GFP_NOWARN);
1842 for (cp = 0; cp < max_count; cp++) {
1844 if (copy_from_user(key, keys + cp * map->key_size,
1846 copy_from_user(value, values + cp * value_size, value_size))
1849 err = bpf_map_update_value(map, map_file, key, value,
1850 attr->batch.elem_flags);
1857 if (copy_to_user(&uattr->batch.count, &cp, sizeof(cp)))
1866 #define MAP_LOOKUP_RETRIES 3
1868 int generic_map_lookup_batch(struct bpf_map *map,
1869 const union bpf_attr *attr,
1870 union bpf_attr __user *uattr)
1872 void __user *uobatch = u64_to_user_ptr(attr->batch.out_batch);
1873 void __user *ubatch = u64_to_user_ptr(attr->batch.in_batch);
1874 void __user *values = u64_to_user_ptr(attr->batch.values);
1875 void __user *keys = u64_to_user_ptr(attr->batch.keys);
1876 void *buf, *buf_prevkey, *prev_key, *key, *value;
1877 int err, retry = MAP_LOOKUP_RETRIES;
1878 u32 value_size, cp, max_count;
1880 if (attr->batch.elem_flags & ~BPF_F_LOCK)
1883 if ((attr->batch.elem_flags & BPF_F_LOCK) &&
1884 !btf_record_has_field(map->record, BPF_SPIN_LOCK))
1887 value_size = bpf_map_value_size(map);
1889 max_count = attr->batch.count;
1893 if (put_user(0, &uattr->batch.count))
1896 buf_prevkey = kvmalloc(map->key_size, GFP_USER | __GFP_NOWARN);
1900 buf = kvmalloc(map->key_size + value_size, GFP_USER | __GFP_NOWARN);
1902 kvfree(buf_prevkey);
1908 if (ubatch && copy_from_user(buf_prevkey, ubatch, map->key_size))
1911 value = key + map->key_size;
1913 prev_key = buf_prevkey;
1915 for (cp = 0; cp < max_count;) {
1917 err = map->ops->map_get_next_key(map, prev_key, key);
1921 err = bpf_map_copy_value(map, key, value,
1922 attr->batch.elem_flags);
1924 if (err == -ENOENT) {
1936 if (copy_to_user(keys + cp * map->key_size, key,
1941 if (copy_to_user(values + cp * value_size, value, value_size)) {
1947 prev_key = buf_prevkey;
1949 swap(prev_key, key);
1950 retry = MAP_LOOKUP_RETRIES;
1958 if ((copy_to_user(&uattr->batch.count, &cp, sizeof(cp)) ||
1959 (cp && copy_to_user(uobatch, prev_key, map->key_size))))
1963 kvfree(buf_prevkey);
1968 #define BPF_MAP_LOOKUP_AND_DELETE_ELEM_LAST_FIELD flags
1970 static int map_lookup_and_delete_elem(union bpf_attr *attr)
1972 void __user *ukey = u64_to_user_ptr(attr->key);
1973 void __user *uvalue = u64_to_user_ptr(attr->value);
1974 struct bpf_map *map;
1979 if (CHECK_ATTR(BPF_MAP_LOOKUP_AND_DELETE_ELEM))
1982 if (attr->flags & ~BPF_F_LOCK)
1985 CLASS(fd, f)(attr->map_fd);
1986 map = __bpf_map_get(f);
1988 return PTR_ERR(map);
1989 bpf_map_write_active_inc(map);
1990 if (!(map_get_sys_perms(map, f) & FMODE_CAN_READ) ||
1991 !(map_get_sys_perms(map, f) & FMODE_CAN_WRITE)) {
1997 (map->map_type == BPF_MAP_TYPE_QUEUE ||
1998 map->map_type == BPF_MAP_TYPE_STACK)) {
2003 if ((attr->flags & BPF_F_LOCK) &&
2004 !btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
2009 key = __bpf_copy_key(ukey, map->key_size);
2015 value_size = bpf_map_value_size(map);
2018 value = kvmalloc(value_size, GFP_USER | __GFP_NOWARN);
2023 if (map->map_type == BPF_MAP_TYPE_QUEUE ||
2024 map->map_type == BPF_MAP_TYPE_STACK) {
2025 err = map->ops->map_pop_elem(map, value);
2026 } else if (map->map_type == BPF_MAP_TYPE_HASH ||
2027 map->map_type == BPF_MAP_TYPE_PERCPU_HASH ||
2028 map->map_type == BPF_MAP_TYPE_LRU_HASH ||
2029 map->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH) {
2030 if (!bpf_map_is_offloaded(map)) {
2031 bpf_disable_instrumentation();
2033 err = map->ops->map_lookup_and_delete_elem(map, key, value, attr->flags);
2035 bpf_enable_instrumentation();
2042 if (copy_to_user(uvalue, value, value_size) != 0) {
2054 bpf_map_write_active_dec(map);
2058 #define BPF_MAP_FREEZE_LAST_FIELD map_fd
2060 static int map_freeze(const union bpf_attr *attr)
2063 struct bpf_map *map;
2065 if (CHECK_ATTR(BPF_MAP_FREEZE))
2068 CLASS(fd, f)(attr->map_fd);
2069 map = __bpf_map_get(f);
2071 return PTR_ERR(map);
2073 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS || !IS_ERR_OR_NULL(map->record))
2076 if (!(map_get_sys_perms(map, f) & FMODE_CAN_WRITE))
2079 mutex_lock(&map->freeze_mutex);
2080 if (bpf_map_write_active(map)) {
2084 if (READ_ONCE(map->frozen)) {
2089 WRITE_ONCE(map->frozen, true);
2091 mutex_unlock(&map->freeze_mutex);
2095 static const struct bpf_prog_ops * const bpf_prog_types[] = {
2096 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
2097 [_id] = & _name ## _prog_ops,
2098 #define BPF_MAP_TYPE(_id, _ops)
2099 #define BPF_LINK_TYPE(_id, _name)
2100 #include <linux/bpf_types.h>
2101 #undef BPF_PROG_TYPE
2103 #undef BPF_LINK_TYPE
2106 static int find_prog_type(enum bpf_prog_type type, struct bpf_prog *prog)
2108 const struct bpf_prog_ops *ops;
2110 if (type >= ARRAY_SIZE(bpf_prog_types))
2112 type = array_index_nospec(type, ARRAY_SIZE(bpf_prog_types));
2113 ops = bpf_prog_types[type];
2117 if (!bpf_prog_is_offloaded(prog->aux))
2118 prog->aux->ops = ops;
2120 prog->aux->ops = &bpf_offload_prog_ops;
2131 static const char * const bpf_audit_str[BPF_AUDIT_MAX] = {
2132 [BPF_AUDIT_LOAD] = "LOAD",
2133 [BPF_AUDIT_UNLOAD] = "UNLOAD",
2136 static void bpf_audit_prog(const struct bpf_prog *prog, unsigned int op)
2138 struct audit_context *ctx = NULL;
2139 struct audit_buffer *ab;
2141 if (WARN_ON_ONCE(op >= BPF_AUDIT_MAX))
2143 if (audit_enabled == AUDIT_OFF)
2145 if (!in_irq() && !irqs_disabled())
2146 ctx = audit_context();
2147 ab = audit_log_start(ctx, GFP_ATOMIC, AUDIT_BPF);
2150 audit_log_format(ab, "prog-id=%u op=%s",
2151 prog->aux->id, bpf_audit_str[op]);
2155 static int bpf_prog_alloc_id(struct bpf_prog *prog)
2159 idr_preload(GFP_KERNEL);
2160 spin_lock_bh(&prog_idr_lock);
2161 id = idr_alloc_cyclic(&prog_idr, prog, 1, INT_MAX, GFP_ATOMIC);
2164 spin_unlock_bh(&prog_idr_lock);
2167 /* id is in [1, INT_MAX) */
2168 if (WARN_ON_ONCE(!id))
2171 return id > 0 ? 0 : id;
2174 void bpf_prog_free_id(struct bpf_prog *prog)
2176 unsigned long flags;
2178 /* cBPF to eBPF migrations are currently not in the idr store.
2179 * Offloaded programs are removed from the store when their device
2180 * disappears - even if someone grabs an fd to them they are unusable,
2181 * simply waiting for refcnt to drop to be freed.
2186 spin_lock_irqsave(&prog_idr_lock, flags);
2187 idr_remove(&prog_idr, prog->aux->id);
2189 spin_unlock_irqrestore(&prog_idr_lock, flags);
2192 static void __bpf_prog_put_rcu(struct rcu_head *rcu)
2194 struct bpf_prog_aux *aux = container_of(rcu, struct bpf_prog_aux, rcu);
2196 kvfree(aux->func_info);
2197 kfree(aux->func_info_aux);
2198 free_uid(aux->user);
2199 security_bpf_prog_free(aux->prog);
2200 bpf_prog_free(aux->prog);
2203 static void __bpf_prog_put_noref(struct bpf_prog *prog, bool deferred)
2205 bpf_prog_kallsyms_del_all(prog);
2206 btf_put(prog->aux->btf);
2207 module_put(prog->aux->mod);
2208 kvfree(prog->aux->jited_linfo);
2209 kvfree(prog->aux->linfo);
2210 kfree(prog->aux->kfunc_tab);
2211 if (prog->aux->attach_btf)
2212 btf_put(prog->aux->attach_btf);
2215 if (prog->sleepable)
2216 call_rcu_tasks_trace(&prog->aux->rcu, __bpf_prog_put_rcu);
2218 call_rcu(&prog->aux->rcu, __bpf_prog_put_rcu);
2220 __bpf_prog_put_rcu(&prog->aux->rcu);
2224 static void bpf_prog_put_deferred(struct work_struct *work)
2226 struct bpf_prog_aux *aux;
2227 struct bpf_prog *prog;
2229 aux = container_of(work, struct bpf_prog_aux, work);
2231 perf_event_bpf_event(prog, PERF_BPF_EVENT_PROG_UNLOAD, 0);
2232 bpf_audit_prog(prog, BPF_AUDIT_UNLOAD);
2233 bpf_prog_free_id(prog);
2234 __bpf_prog_put_noref(prog, true);
2237 static void __bpf_prog_put(struct bpf_prog *prog)
2239 struct bpf_prog_aux *aux = prog->aux;
2241 if (atomic64_dec_and_test(&aux->refcnt)) {
2242 if (in_irq() || irqs_disabled()) {
2243 INIT_WORK(&aux->work, bpf_prog_put_deferred);
2244 schedule_work(&aux->work);
2246 bpf_prog_put_deferred(&aux->work);
2251 void bpf_prog_put(struct bpf_prog *prog)
2253 __bpf_prog_put(prog);
2255 EXPORT_SYMBOL_GPL(bpf_prog_put);
2257 static int bpf_prog_release(struct inode *inode, struct file *filp)
2259 struct bpf_prog *prog = filp->private_data;
2265 struct bpf_prog_kstats {
2271 void notrace bpf_prog_inc_misses_counter(struct bpf_prog *prog)
2273 struct bpf_prog_stats *stats;
2276 stats = this_cpu_ptr(prog->stats);
2277 flags = u64_stats_update_begin_irqsave(&stats->syncp);
2278 u64_stats_inc(&stats->misses);
2279 u64_stats_update_end_irqrestore(&stats->syncp, flags);
2282 static void bpf_prog_get_stats(const struct bpf_prog *prog,
2283 struct bpf_prog_kstats *stats)
2285 u64 nsecs = 0, cnt = 0, misses = 0;
2288 for_each_possible_cpu(cpu) {
2289 const struct bpf_prog_stats *st;
2291 u64 tnsecs, tcnt, tmisses;
2293 st = per_cpu_ptr(prog->stats, cpu);
2295 start = u64_stats_fetch_begin(&st->syncp);
2296 tnsecs = u64_stats_read(&st->nsecs);
2297 tcnt = u64_stats_read(&st->cnt);
2298 tmisses = u64_stats_read(&st->misses);
2299 } while (u64_stats_fetch_retry(&st->syncp, start));
2304 stats->nsecs = nsecs;
2306 stats->misses = misses;
2309 #ifdef CONFIG_PROC_FS
2310 static void bpf_prog_show_fdinfo(struct seq_file *m, struct file *filp)
2312 const struct bpf_prog *prog = filp->private_data;
2313 char prog_tag[sizeof(prog->tag) * 2 + 1] = { };
2314 struct bpf_prog_kstats stats;
2316 bpf_prog_get_stats(prog, &stats);
2317 bin2hex(prog_tag, prog->tag, sizeof(prog->tag));
2324 "run_time_ns:\t%llu\n"
2326 "recursion_misses:\t%llu\n"
2327 "verified_insns:\t%u\n",
2331 prog->pages * 1ULL << PAGE_SHIFT,
2336 prog->aux->verified_insns);
2340 const struct file_operations bpf_prog_fops = {
2341 #ifdef CONFIG_PROC_FS
2342 .show_fdinfo = bpf_prog_show_fdinfo,
2344 .release = bpf_prog_release,
2345 .read = bpf_dummy_read,
2346 .write = bpf_dummy_write,
2349 int bpf_prog_new_fd(struct bpf_prog *prog)
2353 ret = security_bpf_prog(prog);
2357 return anon_inode_getfd("bpf-prog", &bpf_prog_fops, prog,
2358 O_RDWR | O_CLOEXEC);
2361 void bpf_prog_add(struct bpf_prog *prog, int i)
2363 atomic64_add(i, &prog->aux->refcnt);
2365 EXPORT_SYMBOL_GPL(bpf_prog_add);
2367 void bpf_prog_sub(struct bpf_prog *prog, int i)
2369 /* Only to be used for undoing previous bpf_prog_add() in some
2370 * error path. We still know that another entity in our call
2371 * path holds a reference to the program, thus atomic_sub() can
2372 * be safely used in such cases!
2374 WARN_ON(atomic64_sub_return(i, &prog->aux->refcnt) == 0);
2376 EXPORT_SYMBOL_GPL(bpf_prog_sub);
2378 void bpf_prog_inc(struct bpf_prog *prog)
2380 atomic64_inc(&prog->aux->refcnt);
2382 EXPORT_SYMBOL_GPL(bpf_prog_inc);
2384 /* prog_idr_lock should have been held */
2385 struct bpf_prog *bpf_prog_inc_not_zero(struct bpf_prog *prog)
2389 refold = atomic64_fetch_add_unless(&prog->aux->refcnt, 1, 0);
2392 return ERR_PTR(-ENOENT);
2396 EXPORT_SYMBOL_GPL(bpf_prog_inc_not_zero);
2398 bool bpf_prog_get_ok(struct bpf_prog *prog,
2399 enum bpf_prog_type *attach_type, bool attach_drv)
2401 /* not an attachment, just a refcount inc, always allow */
2405 if (prog->type != *attach_type)
2407 if (bpf_prog_is_offloaded(prog->aux) && !attach_drv)
2413 static struct bpf_prog *__bpf_prog_get(u32 ufd, enum bpf_prog_type *attach_type,
2417 struct bpf_prog *prog;
2420 return ERR_PTR(-EBADF);
2421 if (fd_file(f)->f_op != &bpf_prog_fops)
2422 return ERR_PTR(-EINVAL);
2424 prog = fd_file(f)->private_data;
2425 if (!bpf_prog_get_ok(prog, attach_type, attach_drv))
2426 return ERR_PTR(-EINVAL);
2432 struct bpf_prog *bpf_prog_get(u32 ufd)
2434 return __bpf_prog_get(ufd, NULL, false);
2437 struct bpf_prog *bpf_prog_get_type_dev(u32 ufd, enum bpf_prog_type type,
2440 return __bpf_prog_get(ufd, &type, attach_drv);
2442 EXPORT_SYMBOL_GPL(bpf_prog_get_type_dev);
2444 /* Initially all BPF programs could be loaded w/o specifying
2445 * expected_attach_type. Later for some of them specifying expected_attach_type
2446 * at load time became required so that program could be validated properly.
2447 * Programs of types that are allowed to be loaded both w/ and w/o (for
2448 * backward compatibility) expected_attach_type, should have the default attach
2449 * type assigned to expected_attach_type for the latter case, so that it can be
2450 * validated later at attach time.
2452 * bpf_prog_load_fixup_attach_type() sets expected_attach_type in @attr if
2453 * prog type requires it but has some attach types that have to be backward
2456 static void bpf_prog_load_fixup_attach_type(union bpf_attr *attr)
2458 switch (attr->prog_type) {
2459 case BPF_PROG_TYPE_CGROUP_SOCK:
2460 /* Unfortunately BPF_ATTACH_TYPE_UNSPEC enumeration doesn't
2461 * exist so checking for non-zero is the way to go here.
2463 if (!attr->expected_attach_type)
2464 attr->expected_attach_type =
2465 BPF_CGROUP_INET_SOCK_CREATE;
2467 case BPF_PROG_TYPE_SK_REUSEPORT:
2468 if (!attr->expected_attach_type)
2469 attr->expected_attach_type =
2470 BPF_SK_REUSEPORT_SELECT;
2476 bpf_prog_load_check_attach(enum bpf_prog_type prog_type,
2477 enum bpf_attach_type expected_attach_type,
2478 struct btf *attach_btf, u32 btf_id,
2479 struct bpf_prog *dst_prog)
2482 if (btf_id > BTF_MAX_TYPE)
2485 if (!attach_btf && !dst_prog)
2488 switch (prog_type) {
2489 case BPF_PROG_TYPE_TRACING:
2490 case BPF_PROG_TYPE_LSM:
2491 case BPF_PROG_TYPE_STRUCT_OPS:
2492 case BPF_PROG_TYPE_EXT:
2499 if (attach_btf && (!btf_id || dst_prog))
2502 if (dst_prog && prog_type != BPF_PROG_TYPE_TRACING &&
2503 prog_type != BPF_PROG_TYPE_EXT)
2506 switch (prog_type) {
2507 case BPF_PROG_TYPE_CGROUP_SOCK:
2508 switch (expected_attach_type) {
2509 case BPF_CGROUP_INET_SOCK_CREATE:
2510 case BPF_CGROUP_INET_SOCK_RELEASE:
2511 case BPF_CGROUP_INET4_POST_BIND:
2512 case BPF_CGROUP_INET6_POST_BIND:
2517 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
2518 switch (expected_attach_type) {
2519 case BPF_CGROUP_INET4_BIND:
2520 case BPF_CGROUP_INET6_BIND:
2521 case BPF_CGROUP_INET4_CONNECT:
2522 case BPF_CGROUP_INET6_CONNECT:
2523 case BPF_CGROUP_UNIX_CONNECT:
2524 case BPF_CGROUP_INET4_GETPEERNAME:
2525 case BPF_CGROUP_INET6_GETPEERNAME:
2526 case BPF_CGROUP_UNIX_GETPEERNAME:
2527 case BPF_CGROUP_INET4_GETSOCKNAME:
2528 case BPF_CGROUP_INET6_GETSOCKNAME:
2529 case BPF_CGROUP_UNIX_GETSOCKNAME:
2530 case BPF_CGROUP_UDP4_SENDMSG:
2531 case BPF_CGROUP_UDP6_SENDMSG:
2532 case BPF_CGROUP_UNIX_SENDMSG:
2533 case BPF_CGROUP_UDP4_RECVMSG:
2534 case BPF_CGROUP_UDP6_RECVMSG:
2535 case BPF_CGROUP_UNIX_RECVMSG:
2540 case BPF_PROG_TYPE_CGROUP_SKB:
2541 switch (expected_attach_type) {
2542 case BPF_CGROUP_INET_INGRESS:
2543 case BPF_CGROUP_INET_EGRESS:
2548 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
2549 switch (expected_attach_type) {
2550 case BPF_CGROUP_SETSOCKOPT:
2551 case BPF_CGROUP_GETSOCKOPT:
2556 case BPF_PROG_TYPE_SK_LOOKUP:
2557 if (expected_attach_type == BPF_SK_LOOKUP)
2560 case BPF_PROG_TYPE_SK_REUSEPORT:
2561 switch (expected_attach_type) {
2562 case BPF_SK_REUSEPORT_SELECT:
2563 case BPF_SK_REUSEPORT_SELECT_OR_MIGRATE:
2568 case BPF_PROG_TYPE_NETFILTER:
2569 if (expected_attach_type == BPF_NETFILTER)
2572 case BPF_PROG_TYPE_SYSCALL:
2573 case BPF_PROG_TYPE_EXT:
2574 if (expected_attach_type)
2582 static bool is_net_admin_prog_type(enum bpf_prog_type prog_type)
2584 switch (prog_type) {
2585 case BPF_PROG_TYPE_SCHED_CLS:
2586 case BPF_PROG_TYPE_SCHED_ACT:
2587 case BPF_PROG_TYPE_XDP:
2588 case BPF_PROG_TYPE_LWT_IN:
2589 case BPF_PROG_TYPE_LWT_OUT:
2590 case BPF_PROG_TYPE_LWT_XMIT:
2591 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
2592 case BPF_PROG_TYPE_SK_SKB:
2593 case BPF_PROG_TYPE_SK_MSG:
2594 case BPF_PROG_TYPE_FLOW_DISSECTOR:
2595 case BPF_PROG_TYPE_CGROUP_DEVICE:
2596 case BPF_PROG_TYPE_CGROUP_SOCK:
2597 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
2598 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
2599 case BPF_PROG_TYPE_CGROUP_SYSCTL:
2600 case BPF_PROG_TYPE_SOCK_OPS:
2601 case BPF_PROG_TYPE_EXT: /* extends any prog */
2602 case BPF_PROG_TYPE_NETFILTER:
2604 case BPF_PROG_TYPE_CGROUP_SKB:
2606 case BPF_PROG_TYPE_SK_REUSEPORT:
2607 /* equivalent to SOCKET_FILTER. need CAP_BPF only */
2613 static bool is_perfmon_prog_type(enum bpf_prog_type prog_type)
2615 switch (prog_type) {
2616 case BPF_PROG_TYPE_KPROBE:
2617 case BPF_PROG_TYPE_TRACEPOINT:
2618 case BPF_PROG_TYPE_PERF_EVENT:
2619 case BPF_PROG_TYPE_RAW_TRACEPOINT:
2620 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
2621 case BPF_PROG_TYPE_TRACING:
2622 case BPF_PROG_TYPE_LSM:
2623 case BPF_PROG_TYPE_STRUCT_OPS: /* has access to struct sock */
2624 case BPF_PROG_TYPE_EXT: /* extends any prog */
2631 /* last field in 'union bpf_attr' used by this command */
2632 #define BPF_PROG_LOAD_LAST_FIELD prog_token_fd
2634 static int bpf_prog_load(union bpf_attr *attr, bpfptr_t uattr, u32 uattr_size)
2636 enum bpf_prog_type type = attr->prog_type;
2637 struct bpf_prog *prog, *dst_prog = NULL;
2638 struct btf *attach_btf = NULL;
2639 struct bpf_token *token = NULL;
2644 if (CHECK_ATTR(BPF_PROG_LOAD))
2647 if (attr->prog_flags & ~(BPF_F_STRICT_ALIGNMENT |
2648 BPF_F_ANY_ALIGNMENT |
2649 BPF_F_TEST_STATE_FREQ |
2651 BPF_F_TEST_RND_HI32 |
2652 BPF_F_XDP_HAS_FRAGS |
2653 BPF_F_XDP_DEV_BOUND_ONLY |
2654 BPF_F_TEST_REG_INVARIANTS |
2658 bpf_prog_load_fixup_attach_type(attr);
2660 if (attr->prog_flags & BPF_F_TOKEN_FD) {
2661 token = bpf_token_get_from_fd(attr->prog_token_fd);
2663 return PTR_ERR(token);
2664 /* if current token doesn't grant prog loading permissions,
2665 * then we can't use this token, so ignore it and rely on
2666 * system-wide capabilities checks
2668 if (!bpf_token_allow_cmd(token, BPF_PROG_LOAD) ||
2669 !bpf_token_allow_prog_type(token, attr->prog_type,
2670 attr->expected_attach_type)) {
2671 bpf_token_put(token);
2676 bpf_cap = bpf_token_capable(token, CAP_BPF);
2679 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS) &&
2680 (attr->prog_flags & BPF_F_ANY_ALIGNMENT) &&
2684 /* Intent here is for unprivileged_bpf_disabled to block BPF program
2685 * creation for unprivileged users; other actions depend
2686 * on fd availability and access to bpffs, so are dependent on
2687 * object creation success. Even with unprivileged BPF disabled,
2688 * capability checks are still carried out for these
2689 * and other operations.
2691 if (sysctl_unprivileged_bpf_disabled && !bpf_cap)
2694 if (attr->insn_cnt == 0 ||
2695 attr->insn_cnt > (bpf_cap ? BPF_COMPLEXITY_LIMIT_INSNS : BPF_MAXINSNS)) {
2699 if (type != BPF_PROG_TYPE_SOCKET_FILTER &&
2700 type != BPF_PROG_TYPE_CGROUP_SKB &&
2704 if (is_net_admin_prog_type(type) && !bpf_token_capable(token, CAP_NET_ADMIN))
2706 if (is_perfmon_prog_type(type) && !bpf_token_capable(token, CAP_PERFMON))
2709 /* attach_prog_fd/attach_btf_obj_fd can specify fd of either bpf_prog
2710 * or btf, we need to check which one it is
2712 if (attr->attach_prog_fd) {
2713 dst_prog = bpf_prog_get(attr->attach_prog_fd);
2714 if (IS_ERR(dst_prog)) {
2716 attach_btf = btf_get_by_fd(attr->attach_btf_obj_fd);
2717 if (IS_ERR(attach_btf)) {
2721 if (!btf_is_kernel(attach_btf)) {
2722 /* attaching through specifying bpf_prog's BTF
2723 * objects directly might be supported eventually
2725 btf_put(attach_btf);
2730 } else if (attr->attach_btf_id) {
2731 /* fall back to vmlinux BTF, if BTF type ID is specified */
2732 attach_btf = bpf_get_btf_vmlinux();
2733 if (IS_ERR(attach_btf)) {
2734 err = PTR_ERR(attach_btf);
2741 btf_get(attach_btf);
2744 if (bpf_prog_load_check_attach(type, attr->expected_attach_type,
2745 attach_btf, attr->attach_btf_id,
2748 bpf_prog_put(dst_prog);
2750 btf_put(attach_btf);
2755 /* plain bpf_prog allocation */
2756 prog = bpf_prog_alloc(bpf_prog_size(attr->insn_cnt), GFP_USER);
2759 bpf_prog_put(dst_prog);
2761 btf_put(attach_btf);
2766 prog->expected_attach_type = attr->expected_attach_type;
2767 prog->sleepable = !!(attr->prog_flags & BPF_F_SLEEPABLE);
2768 prog->aux->attach_btf = attach_btf;
2769 prog->aux->attach_btf_id = attr->attach_btf_id;
2770 prog->aux->dst_prog = dst_prog;
2771 prog->aux->dev_bound = !!attr->prog_ifindex;
2772 prog->aux->xdp_has_frags = attr->prog_flags & BPF_F_XDP_HAS_FRAGS;
2774 /* move token into prog->aux, reuse taken refcnt */
2775 prog->aux->token = token;
2778 prog->aux->user = get_current_user();
2779 prog->len = attr->insn_cnt;
2782 if (copy_from_bpfptr(prog->insns,
2783 make_bpfptr(attr->insns, uattr.is_kernel),
2784 bpf_prog_insn_size(prog)) != 0)
2786 /* copy eBPF program license from user space */
2787 if (strncpy_from_bpfptr(license,
2788 make_bpfptr(attr->license, uattr.is_kernel),
2789 sizeof(license) - 1) < 0)
2791 license[sizeof(license) - 1] = 0;
2793 /* eBPF programs must be GPL compatible to use GPL-ed functions */
2794 prog->gpl_compatible = license_is_gpl_compatible(license) ? 1 : 0;
2796 prog->orig_prog = NULL;
2799 atomic64_set(&prog->aux->refcnt, 1);
2801 if (bpf_prog_is_dev_bound(prog->aux)) {
2802 err = bpf_prog_dev_bound_init(prog, attr);
2807 if (type == BPF_PROG_TYPE_EXT && dst_prog &&
2808 bpf_prog_is_dev_bound(dst_prog->aux)) {
2809 err = bpf_prog_dev_bound_inherit(prog, dst_prog);
2815 * Bookkeeping for managing the program attachment chain.
2817 * It might be tempting to set attach_tracing_prog flag at the attachment
2818 * time, but this will not prevent from loading bunch of tracing prog
2819 * first, then attach them one to another.
2821 * The flag attach_tracing_prog is set for the whole program lifecycle, and
2822 * doesn't have to be cleared in bpf_tracing_link_release, since tracing
2823 * programs cannot change attachment target.
2825 if (type == BPF_PROG_TYPE_TRACING && dst_prog &&
2826 dst_prog->type == BPF_PROG_TYPE_TRACING) {
2827 prog->aux->attach_tracing_prog = true;
2830 /* find program type: socket_filter vs tracing_filter */
2831 err = find_prog_type(type, prog);
2835 prog->aux->load_time = ktime_get_boottime_ns();
2836 err = bpf_obj_name_cpy(prog->aux->name, attr->prog_name,
2837 sizeof(attr->prog_name));
2841 err = security_bpf_prog_load(prog, attr, token);
2845 /* run eBPF verifier */
2846 err = bpf_check(&prog, attr, uattr, uattr_size);
2848 goto free_used_maps;
2850 prog = bpf_prog_select_runtime(prog, &err);
2852 goto free_used_maps;
2854 err = bpf_prog_alloc_id(prog);
2856 goto free_used_maps;
2858 /* Upon success of bpf_prog_alloc_id(), the BPF prog is
2859 * effectively publicly exposed. However, retrieving via
2860 * bpf_prog_get_fd_by_id() will take another reference,
2861 * therefore it cannot be gone underneath us.
2863 * Only for the time /after/ successful bpf_prog_new_fd()
2864 * and before returning to userspace, we might just hold
2865 * one reference and any parallel close on that fd could
2866 * rip everything out. Hence, below notifications must
2867 * happen before bpf_prog_new_fd().
2869 * Also, any failure handling from this point onwards must
2870 * be using bpf_prog_put() given the program is exposed.
2872 bpf_prog_kallsyms_add(prog);
2873 perf_event_bpf_event(prog, PERF_BPF_EVENT_PROG_LOAD, 0);
2874 bpf_audit_prog(prog, BPF_AUDIT_LOAD);
2876 err = bpf_prog_new_fd(prog);
2882 /* In case we have subprogs, we need to wait for a grace
2883 * period before we can tear down JIT memory since symbols
2884 * are already exposed under kallsyms.
2886 __bpf_prog_put_noref(prog, prog->aux->real_func_cnt);
2890 security_bpf_prog_free(prog);
2892 free_uid(prog->aux->user);
2893 if (prog->aux->attach_btf)
2894 btf_put(prog->aux->attach_btf);
2895 bpf_prog_free(prog);
2897 bpf_token_put(token);
2901 #define BPF_OBJ_LAST_FIELD path_fd
2903 static int bpf_obj_pin(const union bpf_attr *attr)
2907 if (CHECK_ATTR(BPF_OBJ) || attr->file_flags & ~BPF_F_PATH_FD)
2910 /* path_fd has to be accompanied by BPF_F_PATH_FD flag */
2911 if (!(attr->file_flags & BPF_F_PATH_FD) && attr->path_fd)
2914 path_fd = attr->file_flags & BPF_F_PATH_FD ? attr->path_fd : AT_FDCWD;
2915 return bpf_obj_pin_user(attr->bpf_fd, path_fd,
2916 u64_to_user_ptr(attr->pathname));
2919 static int bpf_obj_get(const union bpf_attr *attr)
2923 if (CHECK_ATTR(BPF_OBJ) || attr->bpf_fd != 0 ||
2924 attr->file_flags & ~(BPF_OBJ_FLAG_MASK | BPF_F_PATH_FD))
2927 /* path_fd has to be accompanied by BPF_F_PATH_FD flag */
2928 if (!(attr->file_flags & BPF_F_PATH_FD) && attr->path_fd)
2931 path_fd = attr->file_flags & BPF_F_PATH_FD ? attr->path_fd : AT_FDCWD;
2932 return bpf_obj_get_user(path_fd, u64_to_user_ptr(attr->pathname),
2936 void bpf_link_init(struct bpf_link *link, enum bpf_link_type type,
2937 const struct bpf_link_ops *ops, struct bpf_prog *prog)
2939 WARN_ON(ops->dealloc && ops->dealloc_deferred);
2940 atomic64_set(&link->refcnt, 1);
2947 static void bpf_link_free_id(int id)
2952 spin_lock_bh(&link_idr_lock);
2953 idr_remove(&link_idr, id);
2954 spin_unlock_bh(&link_idr_lock);
2957 /* Clean up bpf_link and corresponding anon_inode file and FD. After
2958 * anon_inode is created, bpf_link can't be just kfree()'d due to deferred
2959 * anon_inode's release() call. This helper marks bpf_link as
2960 * defunct, releases anon_inode file and puts reserved FD. bpf_prog's refcnt
2961 * is not decremented, it's the responsibility of a calling code that failed
2962 * to complete bpf_link initialization.
2963 * This helper eventually calls link's dealloc callback, but does not call
2964 * link's release callback.
2966 void bpf_link_cleanup(struct bpf_link_primer *primer)
2968 primer->link->prog = NULL;
2969 bpf_link_free_id(primer->id);
2971 put_unused_fd(primer->fd);
2974 void bpf_link_inc(struct bpf_link *link)
2976 atomic64_inc(&link->refcnt);
2979 static void bpf_link_defer_dealloc_rcu_gp(struct rcu_head *rcu)
2981 struct bpf_link *link = container_of(rcu, struct bpf_link, rcu);
2983 /* free bpf_link and its containing memory */
2984 link->ops->dealloc_deferred(link);
2987 static void bpf_link_defer_dealloc_mult_rcu_gp(struct rcu_head *rcu)
2989 if (rcu_trace_implies_rcu_gp())
2990 bpf_link_defer_dealloc_rcu_gp(rcu);
2992 call_rcu(rcu, bpf_link_defer_dealloc_rcu_gp);
2995 /* bpf_link_free is guaranteed to be called from process context */
2996 static void bpf_link_free(struct bpf_link *link)
2998 const struct bpf_link_ops *ops = link->ops;
2999 bool sleepable = false;
3001 bpf_link_free_id(link->id);
3003 sleepable = link->prog->sleepable;
3004 /* detach BPF program, clean up used resources */
3006 bpf_prog_put(link->prog);
3008 if (ops->dealloc_deferred) {
3009 /* schedule BPF link deallocation; if underlying BPF program
3010 * is sleepable, we need to first wait for RCU tasks trace
3011 * sync, then go through "classic" RCU grace period
3014 call_rcu_tasks_trace(&link->rcu, bpf_link_defer_dealloc_mult_rcu_gp);
3016 call_rcu(&link->rcu, bpf_link_defer_dealloc_rcu_gp);
3017 } else if (ops->dealloc)
3021 static void bpf_link_put_deferred(struct work_struct *work)
3023 struct bpf_link *link = container_of(work, struct bpf_link, work);
3025 bpf_link_free(link);
3028 /* bpf_link_put might be called from atomic context. It needs to be called
3029 * from sleepable context in order to acquire sleeping locks during the process.
3031 void bpf_link_put(struct bpf_link *link)
3033 if (!atomic64_dec_and_test(&link->refcnt))
3036 INIT_WORK(&link->work, bpf_link_put_deferred);
3037 schedule_work(&link->work);
3039 EXPORT_SYMBOL(bpf_link_put);
3041 static void bpf_link_put_direct(struct bpf_link *link)
3043 if (!atomic64_dec_and_test(&link->refcnt))
3045 bpf_link_free(link);
3048 static int bpf_link_release(struct inode *inode, struct file *filp)
3050 struct bpf_link *link = filp->private_data;
3052 bpf_link_put_direct(link);
3056 #ifdef CONFIG_PROC_FS
3057 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type)
3058 #define BPF_MAP_TYPE(_id, _ops)
3059 #define BPF_LINK_TYPE(_id, _name) [_id] = #_name,
3060 static const char *bpf_link_type_strs[] = {
3061 [BPF_LINK_TYPE_UNSPEC] = "<invalid>",
3062 #include <linux/bpf_types.h>
3064 #undef BPF_PROG_TYPE
3066 #undef BPF_LINK_TYPE
3068 static void bpf_link_show_fdinfo(struct seq_file *m, struct file *filp)
3070 const struct bpf_link *link = filp->private_data;
3071 const struct bpf_prog *prog = link->prog;
3072 char prog_tag[sizeof(prog->tag) * 2 + 1] = { };
3077 bpf_link_type_strs[link->type],
3080 bin2hex(prog_tag, prog->tag, sizeof(prog->tag));
3087 if (link->ops->show_fdinfo)
3088 link->ops->show_fdinfo(link, m);
3092 static __poll_t bpf_link_poll(struct file *file, struct poll_table_struct *pts)
3094 struct bpf_link *link = file->private_data;
3096 return link->ops->poll(file, pts);
3099 static const struct file_operations bpf_link_fops = {
3100 #ifdef CONFIG_PROC_FS
3101 .show_fdinfo = bpf_link_show_fdinfo,
3103 .release = bpf_link_release,
3104 .read = bpf_dummy_read,
3105 .write = bpf_dummy_write,
3108 static const struct file_operations bpf_link_fops_poll = {
3109 #ifdef CONFIG_PROC_FS
3110 .show_fdinfo = bpf_link_show_fdinfo,
3112 .release = bpf_link_release,
3113 .read = bpf_dummy_read,
3114 .write = bpf_dummy_write,
3115 .poll = bpf_link_poll,
3118 static int bpf_link_alloc_id(struct bpf_link *link)
3122 idr_preload(GFP_KERNEL);
3123 spin_lock_bh(&link_idr_lock);
3124 id = idr_alloc_cyclic(&link_idr, link, 1, INT_MAX, GFP_ATOMIC);
3125 spin_unlock_bh(&link_idr_lock);
3131 /* Prepare bpf_link to be exposed to user-space by allocating anon_inode file,
3132 * reserving unused FD and allocating ID from link_idr. This is to be paired
3133 * with bpf_link_settle() to install FD and ID and expose bpf_link to
3134 * user-space, if bpf_link is successfully attached. If not, bpf_link and
3135 * pre-allocated resources are to be freed with bpf_cleanup() call. All the
3136 * transient state is passed around in struct bpf_link_primer.
3137 * This is preferred way to create and initialize bpf_link, especially when
3138 * there are complicated and expensive operations in between creating bpf_link
3139 * itself and attaching it to BPF hook. By using bpf_link_prime() and
3140 * bpf_link_settle() kernel code using bpf_link doesn't have to perform
3141 * expensive (and potentially failing) roll back operations in a rare case
3142 * that file, FD, or ID can't be allocated.
3144 int bpf_link_prime(struct bpf_link *link, struct bpf_link_primer *primer)
3149 fd = get_unused_fd_flags(O_CLOEXEC);
3154 id = bpf_link_alloc_id(link);
3160 file = anon_inode_getfile("bpf_link",
3161 link->ops->poll ? &bpf_link_fops_poll : &bpf_link_fops,
3164 bpf_link_free_id(id);
3166 return PTR_ERR(file);
3169 primer->link = link;
3170 primer->file = file;
3176 int bpf_link_settle(struct bpf_link_primer *primer)
3178 /* make bpf_link fetchable by ID */
3179 spin_lock_bh(&link_idr_lock);
3180 primer->link->id = primer->id;
3181 spin_unlock_bh(&link_idr_lock);
3182 /* make bpf_link fetchable by FD */
3183 fd_install(primer->fd, primer->file);
3184 /* pass through installed FD */
3188 int bpf_link_new_fd(struct bpf_link *link)
3190 return anon_inode_getfd("bpf-link",
3191 link->ops->poll ? &bpf_link_fops_poll : &bpf_link_fops,
3195 struct bpf_link *bpf_link_get_from_fd(u32 ufd)
3198 struct bpf_link *link;
3201 return ERR_PTR(-EBADF);
3202 if (fd_file(f)->f_op != &bpf_link_fops && fd_file(f)->f_op != &bpf_link_fops_poll)
3203 return ERR_PTR(-EINVAL);
3205 link = fd_file(f)->private_data;
3209 EXPORT_SYMBOL(bpf_link_get_from_fd);
3211 static void bpf_tracing_link_release(struct bpf_link *link)
3213 struct bpf_tracing_link *tr_link =
3214 container_of(link, struct bpf_tracing_link, link.link);
3216 WARN_ON_ONCE(bpf_trampoline_unlink_prog(&tr_link->link,
3217 tr_link->trampoline));
3219 bpf_trampoline_put(tr_link->trampoline);
3221 /* tgt_prog is NULL if target is a kernel function */
3222 if (tr_link->tgt_prog)
3223 bpf_prog_put(tr_link->tgt_prog);
3226 static void bpf_tracing_link_dealloc(struct bpf_link *link)
3228 struct bpf_tracing_link *tr_link =
3229 container_of(link, struct bpf_tracing_link, link.link);
3234 static void bpf_tracing_link_show_fdinfo(const struct bpf_link *link,
3235 struct seq_file *seq)
3237 struct bpf_tracing_link *tr_link =
3238 container_of(link, struct bpf_tracing_link, link.link);
3239 u32 target_btf_id, target_obj_id;
3241 bpf_trampoline_unpack_key(tr_link->trampoline->key,
3242 &target_obj_id, &target_btf_id);
3244 "attach_type:\t%d\n"
3245 "target_obj_id:\t%u\n"
3246 "target_btf_id:\t%u\n",
3247 tr_link->attach_type,
3252 static int bpf_tracing_link_fill_link_info(const struct bpf_link *link,
3253 struct bpf_link_info *info)
3255 struct bpf_tracing_link *tr_link =
3256 container_of(link, struct bpf_tracing_link, link.link);
3258 info->tracing.attach_type = tr_link->attach_type;
3259 bpf_trampoline_unpack_key(tr_link->trampoline->key,
3260 &info->tracing.target_obj_id,
3261 &info->tracing.target_btf_id);
3266 static const struct bpf_link_ops bpf_tracing_link_lops = {
3267 .release = bpf_tracing_link_release,
3268 .dealloc = bpf_tracing_link_dealloc,
3269 .show_fdinfo = bpf_tracing_link_show_fdinfo,
3270 .fill_link_info = bpf_tracing_link_fill_link_info,
3273 static int bpf_tracing_prog_attach(struct bpf_prog *prog,
3278 struct bpf_link_primer link_primer;
3279 struct bpf_prog *tgt_prog = NULL;
3280 struct bpf_trampoline *tr = NULL;
3281 struct bpf_tracing_link *link;
3285 switch (prog->type) {
3286 case BPF_PROG_TYPE_TRACING:
3287 if (prog->expected_attach_type != BPF_TRACE_FENTRY &&
3288 prog->expected_attach_type != BPF_TRACE_FEXIT &&
3289 prog->expected_attach_type != BPF_MODIFY_RETURN) {
3294 case BPF_PROG_TYPE_EXT:
3295 if (prog->expected_attach_type != 0) {
3300 case BPF_PROG_TYPE_LSM:
3301 if (prog->expected_attach_type != BPF_LSM_MAC) {
3311 if (!!tgt_prog_fd != !!btf_id) {
3318 * For now we only allow new targets for BPF_PROG_TYPE_EXT. If this
3319 * part would be changed to implement the same for
3320 * BPF_PROG_TYPE_TRACING, do not forget to update the way how
3321 * attach_tracing_prog flag is set.
3323 if (prog->type != BPF_PROG_TYPE_EXT) {
3328 tgt_prog = bpf_prog_get(tgt_prog_fd);
3329 if (IS_ERR(tgt_prog)) {
3330 err = PTR_ERR(tgt_prog);
3335 key = bpf_trampoline_compute_key(tgt_prog, NULL, btf_id);
3338 link = kzalloc(sizeof(*link), GFP_USER);
3343 bpf_link_init(&link->link.link, BPF_LINK_TYPE_TRACING,
3344 &bpf_tracing_link_lops, prog);
3345 link->attach_type = prog->expected_attach_type;
3346 link->link.cookie = bpf_cookie;
3348 mutex_lock(&prog->aux->dst_mutex);
3350 /* There are a few possible cases here:
3352 * - if prog->aux->dst_trampoline is set, the program was just loaded
3353 * and not yet attached to anything, so we can use the values stored
3356 * - if prog->aux->dst_trampoline is NULL, the program has already been
3357 * attached to a target and its initial target was cleared (below)
3359 * - if tgt_prog != NULL, the caller specified tgt_prog_fd +
3360 * target_btf_id using the link_create API.
3362 * - if tgt_prog == NULL when this function was called using the old
3363 * raw_tracepoint_open API, and we need a target from prog->aux
3365 * - if prog->aux->dst_trampoline and tgt_prog is NULL, the program
3366 * was detached and is going for re-attachment.
3368 * - if prog->aux->dst_trampoline is NULL and tgt_prog and prog->aux->attach_btf
3369 * are NULL, then program was already attached and user did not provide
3370 * tgt_prog_fd so we have no way to find out or create trampoline
3372 if (!prog->aux->dst_trampoline && !tgt_prog) {
3374 * Allow re-attach for TRACING and LSM programs. If it's
3375 * currently linked, bpf_trampoline_link_prog will fail.
3376 * EXT programs need to specify tgt_prog_fd, so they
3377 * re-attach in separate code path.
3379 if (prog->type != BPF_PROG_TYPE_TRACING &&
3380 prog->type != BPF_PROG_TYPE_LSM) {
3384 /* We can allow re-attach only if we have valid attach_btf. */
3385 if (!prog->aux->attach_btf) {
3389 btf_id = prog->aux->attach_btf_id;
3390 key = bpf_trampoline_compute_key(NULL, prog->aux->attach_btf, btf_id);
3393 if (!prog->aux->dst_trampoline ||
3394 (key && key != prog->aux->dst_trampoline->key)) {
3395 /* If there is no saved target, or the specified target is
3396 * different from the destination specified at load time, we
3397 * need a new trampoline and a check for compatibility
3399 struct bpf_attach_target_info tgt_info = {};
3401 err = bpf_check_attach_target(NULL, prog, tgt_prog, btf_id,
3406 if (tgt_info.tgt_mod) {
3407 module_put(prog->aux->mod);
3408 prog->aux->mod = tgt_info.tgt_mod;
3411 tr = bpf_trampoline_get(key, &tgt_info);
3417 /* The caller didn't specify a target, or the target was the
3418 * same as the destination supplied during program load. This
3419 * means we can reuse the trampoline and reference from program
3420 * load time, and there is no need to allocate a new one. This
3421 * can only happen once for any program, as the saved values in
3422 * prog->aux are cleared below.
3424 tr = prog->aux->dst_trampoline;
3425 tgt_prog = prog->aux->dst_prog;
3428 err = bpf_link_prime(&link->link.link, &link_primer);
3432 err = bpf_trampoline_link_prog(&link->link, tr);
3434 bpf_link_cleanup(&link_primer);
3439 link->tgt_prog = tgt_prog;
3440 link->trampoline = tr;
3442 /* Always clear the trampoline and target prog from prog->aux to make
3443 * sure the original attach destination is not kept alive after a
3444 * program is (re-)attached to another target.
3446 if (prog->aux->dst_prog &&
3447 (tgt_prog_fd || tr != prog->aux->dst_trampoline))
3448 /* got extra prog ref from syscall, or attaching to different prog */
3449 bpf_prog_put(prog->aux->dst_prog);
3450 if (prog->aux->dst_trampoline && tr != prog->aux->dst_trampoline)
3451 /* we allocated a new trampoline, so free the old one */
3452 bpf_trampoline_put(prog->aux->dst_trampoline);
3454 prog->aux->dst_prog = NULL;
3455 prog->aux->dst_trampoline = NULL;
3456 mutex_unlock(&prog->aux->dst_mutex);
3458 return bpf_link_settle(&link_primer);
3460 if (tr && tr != prog->aux->dst_trampoline)
3461 bpf_trampoline_put(tr);
3462 mutex_unlock(&prog->aux->dst_mutex);
3465 if (tgt_prog_fd && tgt_prog)
3466 bpf_prog_put(tgt_prog);
3470 static void bpf_raw_tp_link_release(struct bpf_link *link)
3472 struct bpf_raw_tp_link *raw_tp =
3473 container_of(link, struct bpf_raw_tp_link, link);
3475 bpf_probe_unregister(raw_tp->btp, raw_tp);
3476 bpf_put_raw_tracepoint(raw_tp->btp);
3479 static void bpf_raw_tp_link_dealloc(struct bpf_link *link)
3481 struct bpf_raw_tp_link *raw_tp =
3482 container_of(link, struct bpf_raw_tp_link, link);
3487 static void bpf_raw_tp_link_show_fdinfo(const struct bpf_link *link,
3488 struct seq_file *seq)
3490 struct bpf_raw_tp_link *raw_tp_link =
3491 container_of(link, struct bpf_raw_tp_link, link);
3495 raw_tp_link->btp->tp->name);
3498 static int bpf_copy_to_user(char __user *ubuf, const char *buf, u32 ulen,
3501 if (ulen >= len + 1) {
3502 if (copy_to_user(ubuf, buf, len + 1))
3507 if (copy_to_user(ubuf, buf, ulen - 1))
3509 if (put_user(zero, ubuf + ulen - 1))
3517 static int bpf_raw_tp_link_fill_link_info(const struct bpf_link *link,
3518 struct bpf_link_info *info)
3520 struct bpf_raw_tp_link *raw_tp_link =
3521 container_of(link, struct bpf_raw_tp_link, link);
3522 char __user *ubuf = u64_to_user_ptr(info->raw_tracepoint.tp_name);
3523 const char *tp_name = raw_tp_link->btp->tp->name;
3524 u32 ulen = info->raw_tracepoint.tp_name_len;
3525 size_t tp_len = strlen(tp_name);
3530 info->raw_tracepoint.tp_name_len = tp_len + 1;
3535 return bpf_copy_to_user(ubuf, tp_name, ulen, tp_len);
3538 static const struct bpf_link_ops bpf_raw_tp_link_lops = {
3539 .release = bpf_raw_tp_link_release,
3540 .dealloc_deferred = bpf_raw_tp_link_dealloc,
3541 .show_fdinfo = bpf_raw_tp_link_show_fdinfo,
3542 .fill_link_info = bpf_raw_tp_link_fill_link_info,
3545 #ifdef CONFIG_PERF_EVENTS
3546 struct bpf_perf_link {
3547 struct bpf_link link;
3548 struct file *perf_file;
3551 static void bpf_perf_link_release(struct bpf_link *link)
3553 struct bpf_perf_link *perf_link = container_of(link, struct bpf_perf_link, link);
3554 struct perf_event *event = perf_link->perf_file->private_data;
3556 perf_event_free_bpf_prog(event);
3557 fput(perf_link->perf_file);
3560 static void bpf_perf_link_dealloc(struct bpf_link *link)
3562 struct bpf_perf_link *perf_link = container_of(link, struct bpf_perf_link, link);
3567 static int bpf_perf_link_fill_common(const struct perf_event *event,
3568 char __user *uname, u32 ulen,
3569 u64 *probe_offset, u64 *probe_addr,
3570 u32 *fd_type, unsigned long *missed)
3580 err = bpf_get_perf_event_info(event, &prog_id, fd_type, &buf,
3581 probe_offset, probe_addr, missed);
3588 err = bpf_copy_to_user(uname, buf, ulen, len);
3594 if (put_user(zero, uname))
3600 #ifdef CONFIG_KPROBE_EVENTS
3601 static int bpf_perf_link_fill_kprobe(const struct perf_event *event,
3602 struct bpf_link_info *info)
3604 unsigned long missed;
3610 uname = u64_to_user_ptr(info->perf_event.kprobe.func_name);
3611 ulen = info->perf_event.kprobe.name_len;
3612 err = bpf_perf_link_fill_common(event, uname, ulen, &offset, &addr,
3616 if (type == BPF_FD_TYPE_KRETPROBE)
3617 info->perf_event.type = BPF_PERF_EVENT_KRETPROBE;
3619 info->perf_event.type = BPF_PERF_EVENT_KPROBE;
3621 info->perf_event.kprobe.offset = offset;
3622 info->perf_event.kprobe.missed = missed;
3623 if (!kallsyms_show_value(current_cred()))
3625 info->perf_event.kprobe.addr = addr;
3626 info->perf_event.kprobe.cookie = event->bpf_cookie;
3631 #ifdef CONFIG_UPROBE_EVENTS
3632 static int bpf_perf_link_fill_uprobe(const struct perf_event *event,
3633 struct bpf_link_info *info)
3640 uname = u64_to_user_ptr(info->perf_event.uprobe.file_name);
3641 ulen = info->perf_event.uprobe.name_len;
3642 err = bpf_perf_link_fill_common(event, uname, ulen, &offset, &addr,
3647 if (type == BPF_FD_TYPE_URETPROBE)
3648 info->perf_event.type = BPF_PERF_EVENT_URETPROBE;
3650 info->perf_event.type = BPF_PERF_EVENT_UPROBE;
3651 info->perf_event.uprobe.offset = offset;
3652 info->perf_event.uprobe.cookie = event->bpf_cookie;
3657 static int bpf_perf_link_fill_probe(const struct perf_event *event,
3658 struct bpf_link_info *info)
3660 #ifdef CONFIG_KPROBE_EVENTS
3661 if (event->tp_event->flags & TRACE_EVENT_FL_KPROBE)
3662 return bpf_perf_link_fill_kprobe(event, info);
3664 #ifdef CONFIG_UPROBE_EVENTS
3665 if (event->tp_event->flags & TRACE_EVENT_FL_UPROBE)
3666 return bpf_perf_link_fill_uprobe(event, info);
3671 static int bpf_perf_link_fill_tracepoint(const struct perf_event *event,
3672 struct bpf_link_info *info)
3677 uname = u64_to_user_ptr(info->perf_event.tracepoint.tp_name);
3678 ulen = info->perf_event.tracepoint.name_len;
3679 info->perf_event.type = BPF_PERF_EVENT_TRACEPOINT;
3680 info->perf_event.tracepoint.cookie = event->bpf_cookie;
3681 return bpf_perf_link_fill_common(event, uname, ulen, NULL, NULL, NULL, NULL);
3684 static int bpf_perf_link_fill_perf_event(const struct perf_event *event,
3685 struct bpf_link_info *info)
3687 info->perf_event.event.type = event->attr.type;
3688 info->perf_event.event.config = event->attr.config;
3689 info->perf_event.event.cookie = event->bpf_cookie;
3690 info->perf_event.type = BPF_PERF_EVENT_EVENT;
3694 static int bpf_perf_link_fill_link_info(const struct bpf_link *link,
3695 struct bpf_link_info *info)
3697 struct bpf_perf_link *perf_link;
3698 const struct perf_event *event;
3700 perf_link = container_of(link, struct bpf_perf_link, link);
3701 event = perf_get_event(perf_link->perf_file);
3703 return PTR_ERR(event);
3705 switch (event->prog->type) {
3706 case BPF_PROG_TYPE_PERF_EVENT:
3707 return bpf_perf_link_fill_perf_event(event, info);
3708 case BPF_PROG_TYPE_TRACEPOINT:
3709 return bpf_perf_link_fill_tracepoint(event, info);
3710 case BPF_PROG_TYPE_KPROBE:
3711 return bpf_perf_link_fill_probe(event, info);
3717 static const struct bpf_link_ops bpf_perf_link_lops = {
3718 .release = bpf_perf_link_release,
3719 .dealloc = bpf_perf_link_dealloc,
3720 .fill_link_info = bpf_perf_link_fill_link_info,
3723 static int bpf_perf_link_attach(const union bpf_attr *attr, struct bpf_prog *prog)
3725 struct bpf_link_primer link_primer;
3726 struct bpf_perf_link *link;
3727 struct perf_event *event;
3728 struct file *perf_file;
3731 if (attr->link_create.flags)
3734 perf_file = perf_event_get(attr->link_create.target_fd);
3735 if (IS_ERR(perf_file))
3736 return PTR_ERR(perf_file);
3738 link = kzalloc(sizeof(*link), GFP_USER);
3743 bpf_link_init(&link->link, BPF_LINK_TYPE_PERF_EVENT, &bpf_perf_link_lops, prog);
3744 link->perf_file = perf_file;
3746 err = bpf_link_prime(&link->link, &link_primer);
3752 event = perf_file->private_data;
3753 err = perf_event_set_bpf_prog(event, prog, attr->link_create.perf_event.bpf_cookie);
3755 bpf_link_cleanup(&link_primer);
3758 /* perf_event_set_bpf_prog() doesn't take its own refcnt on prog */
3761 return bpf_link_settle(&link_primer);
3768 static int bpf_perf_link_attach(const union bpf_attr *attr, struct bpf_prog *prog)
3772 #endif /* CONFIG_PERF_EVENTS */
3774 static int bpf_raw_tp_link_attach(struct bpf_prog *prog,
3775 const char __user *user_tp_name, u64 cookie)
3777 struct bpf_link_primer link_primer;
3778 struct bpf_raw_tp_link *link;
3779 struct bpf_raw_event_map *btp;
3780 const char *tp_name;
3784 switch (prog->type) {
3785 case BPF_PROG_TYPE_TRACING:
3786 case BPF_PROG_TYPE_EXT:
3787 case BPF_PROG_TYPE_LSM:
3789 /* The attach point for this category of programs
3790 * should be specified via btf_id during program load.
3793 if (prog->type == BPF_PROG_TYPE_TRACING &&
3794 prog->expected_attach_type == BPF_TRACE_RAW_TP) {
3795 tp_name = prog->aux->attach_func_name;
3798 return bpf_tracing_prog_attach(prog, 0, 0, 0);
3799 case BPF_PROG_TYPE_RAW_TRACEPOINT:
3800 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
3801 if (strncpy_from_user(buf, user_tp_name, sizeof(buf) - 1) < 0)
3803 buf[sizeof(buf) - 1] = 0;
3810 btp = bpf_get_raw_tracepoint(tp_name);
3814 link = kzalloc(sizeof(*link), GFP_USER);
3819 bpf_link_init(&link->link, BPF_LINK_TYPE_RAW_TRACEPOINT,
3820 &bpf_raw_tp_link_lops, prog);
3822 link->cookie = cookie;
3824 err = bpf_link_prime(&link->link, &link_primer);
3830 err = bpf_probe_register(link->btp, link);
3832 bpf_link_cleanup(&link_primer);
3836 return bpf_link_settle(&link_primer);
3839 bpf_put_raw_tracepoint(btp);
3843 #define BPF_RAW_TRACEPOINT_OPEN_LAST_FIELD raw_tracepoint.cookie
3845 static int bpf_raw_tracepoint_open(const union bpf_attr *attr)
3847 struct bpf_prog *prog;
3848 void __user *tp_name;
3852 if (CHECK_ATTR(BPF_RAW_TRACEPOINT_OPEN))
3855 prog = bpf_prog_get(attr->raw_tracepoint.prog_fd);
3857 return PTR_ERR(prog);
3859 tp_name = u64_to_user_ptr(attr->raw_tracepoint.name);
3860 cookie = attr->raw_tracepoint.cookie;
3861 fd = bpf_raw_tp_link_attach(prog, tp_name, cookie);
3867 static enum bpf_prog_type
3868 attach_type_to_prog_type(enum bpf_attach_type attach_type)
3870 switch (attach_type) {
3871 case BPF_CGROUP_INET_INGRESS:
3872 case BPF_CGROUP_INET_EGRESS:
3873 return BPF_PROG_TYPE_CGROUP_SKB;
3874 case BPF_CGROUP_INET_SOCK_CREATE:
3875 case BPF_CGROUP_INET_SOCK_RELEASE:
3876 case BPF_CGROUP_INET4_POST_BIND:
3877 case BPF_CGROUP_INET6_POST_BIND:
3878 return BPF_PROG_TYPE_CGROUP_SOCK;
3879 case BPF_CGROUP_INET4_BIND:
3880 case BPF_CGROUP_INET6_BIND:
3881 case BPF_CGROUP_INET4_CONNECT:
3882 case BPF_CGROUP_INET6_CONNECT:
3883 case BPF_CGROUP_UNIX_CONNECT:
3884 case BPF_CGROUP_INET4_GETPEERNAME:
3885 case BPF_CGROUP_INET6_GETPEERNAME:
3886 case BPF_CGROUP_UNIX_GETPEERNAME:
3887 case BPF_CGROUP_INET4_GETSOCKNAME:
3888 case BPF_CGROUP_INET6_GETSOCKNAME:
3889 case BPF_CGROUP_UNIX_GETSOCKNAME:
3890 case BPF_CGROUP_UDP4_SENDMSG:
3891 case BPF_CGROUP_UDP6_SENDMSG:
3892 case BPF_CGROUP_UNIX_SENDMSG:
3893 case BPF_CGROUP_UDP4_RECVMSG:
3894 case BPF_CGROUP_UDP6_RECVMSG:
3895 case BPF_CGROUP_UNIX_RECVMSG:
3896 return BPF_PROG_TYPE_CGROUP_SOCK_ADDR;
3897 case BPF_CGROUP_SOCK_OPS:
3898 return BPF_PROG_TYPE_SOCK_OPS;
3899 case BPF_CGROUP_DEVICE:
3900 return BPF_PROG_TYPE_CGROUP_DEVICE;
3901 case BPF_SK_MSG_VERDICT:
3902 return BPF_PROG_TYPE_SK_MSG;
3903 case BPF_SK_SKB_STREAM_PARSER:
3904 case BPF_SK_SKB_STREAM_VERDICT:
3905 case BPF_SK_SKB_VERDICT:
3906 return BPF_PROG_TYPE_SK_SKB;
3907 case BPF_LIRC_MODE2:
3908 return BPF_PROG_TYPE_LIRC_MODE2;
3909 case BPF_FLOW_DISSECTOR:
3910 return BPF_PROG_TYPE_FLOW_DISSECTOR;
3911 case BPF_CGROUP_SYSCTL:
3912 return BPF_PROG_TYPE_CGROUP_SYSCTL;
3913 case BPF_CGROUP_GETSOCKOPT:
3914 case BPF_CGROUP_SETSOCKOPT:
3915 return BPF_PROG_TYPE_CGROUP_SOCKOPT;
3916 case BPF_TRACE_ITER:
3917 case BPF_TRACE_RAW_TP:
3918 case BPF_TRACE_FENTRY:
3919 case BPF_TRACE_FEXIT:
3920 case BPF_MODIFY_RETURN:
3921 return BPF_PROG_TYPE_TRACING;
3923 return BPF_PROG_TYPE_LSM;
3925 return BPF_PROG_TYPE_SK_LOOKUP;
3927 return BPF_PROG_TYPE_XDP;
3928 case BPF_LSM_CGROUP:
3929 return BPF_PROG_TYPE_LSM;
3930 case BPF_TCX_INGRESS:
3931 case BPF_TCX_EGRESS:
3932 case BPF_NETKIT_PRIMARY:
3933 case BPF_NETKIT_PEER:
3934 return BPF_PROG_TYPE_SCHED_CLS;
3936 return BPF_PROG_TYPE_UNSPEC;
3940 static int bpf_prog_attach_check_attach_type(const struct bpf_prog *prog,
3941 enum bpf_attach_type attach_type)
3943 enum bpf_prog_type ptype;
3945 switch (prog->type) {
3946 case BPF_PROG_TYPE_CGROUP_SOCK:
3947 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
3948 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3949 case BPF_PROG_TYPE_SK_LOOKUP:
3950 return attach_type == prog->expected_attach_type ? 0 : -EINVAL;
3951 case BPF_PROG_TYPE_CGROUP_SKB:
3952 if (!bpf_token_capable(prog->aux->token, CAP_NET_ADMIN))
3953 /* cg-skb progs can be loaded by unpriv user.
3954 * check permissions at attach time.
3958 ptype = attach_type_to_prog_type(attach_type);
3959 if (prog->type != ptype)
3962 return prog->enforce_expected_attach_type &&
3963 prog->expected_attach_type != attach_type ?
3965 case BPF_PROG_TYPE_EXT:
3967 case BPF_PROG_TYPE_NETFILTER:
3968 if (attach_type != BPF_NETFILTER)
3971 case BPF_PROG_TYPE_PERF_EVENT:
3972 case BPF_PROG_TYPE_TRACEPOINT:
3973 if (attach_type != BPF_PERF_EVENT)
3976 case BPF_PROG_TYPE_KPROBE:
3977 if (prog->expected_attach_type == BPF_TRACE_KPROBE_MULTI &&
3978 attach_type != BPF_TRACE_KPROBE_MULTI)
3980 if (prog->expected_attach_type == BPF_TRACE_KPROBE_SESSION &&
3981 attach_type != BPF_TRACE_KPROBE_SESSION)
3983 if (prog->expected_attach_type == BPF_TRACE_UPROBE_MULTI &&
3984 attach_type != BPF_TRACE_UPROBE_MULTI)
3986 if (attach_type != BPF_PERF_EVENT &&
3987 attach_type != BPF_TRACE_KPROBE_MULTI &&
3988 attach_type != BPF_TRACE_KPROBE_SESSION &&
3989 attach_type != BPF_TRACE_UPROBE_MULTI)
3992 case BPF_PROG_TYPE_SCHED_CLS:
3993 if (attach_type != BPF_TCX_INGRESS &&
3994 attach_type != BPF_TCX_EGRESS &&
3995 attach_type != BPF_NETKIT_PRIMARY &&
3996 attach_type != BPF_NETKIT_PEER)
4000 ptype = attach_type_to_prog_type(attach_type);
4001 if (ptype == BPF_PROG_TYPE_UNSPEC || ptype != prog->type)
4007 #define BPF_PROG_ATTACH_LAST_FIELD expected_revision
4009 #define BPF_F_ATTACH_MASK_BASE \
4010 (BPF_F_ALLOW_OVERRIDE | \
4011 BPF_F_ALLOW_MULTI | \
4014 #define BPF_F_ATTACH_MASK_MPROG \
4021 static int bpf_prog_attach(const union bpf_attr *attr)
4023 enum bpf_prog_type ptype;
4024 struct bpf_prog *prog;
4027 if (CHECK_ATTR(BPF_PROG_ATTACH))
4030 ptype = attach_type_to_prog_type(attr->attach_type);
4031 if (ptype == BPF_PROG_TYPE_UNSPEC)
4033 if (bpf_mprog_supported(ptype)) {
4034 if (attr->attach_flags & ~BPF_F_ATTACH_MASK_MPROG)
4037 if (attr->attach_flags & ~BPF_F_ATTACH_MASK_BASE)
4039 if (attr->relative_fd ||
4040 attr->expected_revision)
4044 prog = bpf_prog_get_type(attr->attach_bpf_fd, ptype);
4046 return PTR_ERR(prog);
4048 if (bpf_prog_attach_check_attach_type(prog, attr->attach_type)) {
4054 case BPF_PROG_TYPE_SK_SKB:
4055 case BPF_PROG_TYPE_SK_MSG:
4056 ret = sock_map_get_from_fd(attr, prog);
4058 case BPF_PROG_TYPE_LIRC_MODE2:
4059 ret = lirc_prog_attach(attr, prog);
4061 case BPF_PROG_TYPE_FLOW_DISSECTOR:
4062 ret = netns_bpf_prog_attach(attr, prog);
4064 case BPF_PROG_TYPE_CGROUP_DEVICE:
4065 case BPF_PROG_TYPE_CGROUP_SKB:
4066 case BPF_PROG_TYPE_CGROUP_SOCK:
4067 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
4068 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
4069 case BPF_PROG_TYPE_CGROUP_SYSCTL:
4070 case BPF_PROG_TYPE_SOCK_OPS:
4071 case BPF_PROG_TYPE_LSM:
4072 if (ptype == BPF_PROG_TYPE_LSM &&
4073 prog->expected_attach_type != BPF_LSM_CGROUP)
4076 ret = cgroup_bpf_prog_attach(attr, ptype, prog);
4078 case BPF_PROG_TYPE_SCHED_CLS:
4079 if (attr->attach_type == BPF_TCX_INGRESS ||
4080 attr->attach_type == BPF_TCX_EGRESS)
4081 ret = tcx_prog_attach(attr, prog);
4083 ret = netkit_prog_attach(attr, prog);
4094 #define BPF_PROG_DETACH_LAST_FIELD expected_revision
4096 static int bpf_prog_detach(const union bpf_attr *attr)
4098 struct bpf_prog *prog = NULL;
4099 enum bpf_prog_type ptype;
4102 if (CHECK_ATTR(BPF_PROG_DETACH))
4105 ptype = attach_type_to_prog_type(attr->attach_type);
4106 if (bpf_mprog_supported(ptype)) {
4107 if (ptype == BPF_PROG_TYPE_UNSPEC)
4109 if (attr->attach_flags & ~BPF_F_ATTACH_MASK_MPROG)
4111 if (attr->attach_bpf_fd) {
4112 prog = bpf_prog_get_type(attr->attach_bpf_fd, ptype);
4114 return PTR_ERR(prog);
4116 } else if (attr->attach_flags ||
4117 attr->relative_fd ||
4118 attr->expected_revision) {
4123 case BPF_PROG_TYPE_SK_MSG:
4124 case BPF_PROG_TYPE_SK_SKB:
4125 ret = sock_map_prog_detach(attr, ptype);
4127 case BPF_PROG_TYPE_LIRC_MODE2:
4128 ret = lirc_prog_detach(attr);
4130 case BPF_PROG_TYPE_FLOW_DISSECTOR:
4131 ret = netns_bpf_prog_detach(attr, ptype);
4133 case BPF_PROG_TYPE_CGROUP_DEVICE:
4134 case BPF_PROG_TYPE_CGROUP_SKB:
4135 case BPF_PROG_TYPE_CGROUP_SOCK:
4136 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
4137 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
4138 case BPF_PROG_TYPE_CGROUP_SYSCTL:
4139 case BPF_PROG_TYPE_SOCK_OPS:
4140 case BPF_PROG_TYPE_LSM:
4141 ret = cgroup_bpf_prog_detach(attr, ptype);
4143 case BPF_PROG_TYPE_SCHED_CLS:
4144 if (attr->attach_type == BPF_TCX_INGRESS ||
4145 attr->attach_type == BPF_TCX_EGRESS)
4146 ret = tcx_prog_detach(attr, prog);
4148 ret = netkit_prog_detach(attr, prog);
4159 #define BPF_PROG_QUERY_LAST_FIELD query.revision
4161 static int bpf_prog_query(const union bpf_attr *attr,
4162 union bpf_attr __user *uattr)
4164 if (!bpf_net_capable())
4166 if (CHECK_ATTR(BPF_PROG_QUERY))
4168 if (attr->query.query_flags & ~BPF_F_QUERY_EFFECTIVE)
4171 switch (attr->query.attach_type) {
4172 case BPF_CGROUP_INET_INGRESS:
4173 case BPF_CGROUP_INET_EGRESS:
4174 case BPF_CGROUP_INET_SOCK_CREATE:
4175 case BPF_CGROUP_INET_SOCK_RELEASE:
4176 case BPF_CGROUP_INET4_BIND:
4177 case BPF_CGROUP_INET6_BIND:
4178 case BPF_CGROUP_INET4_POST_BIND:
4179 case BPF_CGROUP_INET6_POST_BIND:
4180 case BPF_CGROUP_INET4_CONNECT:
4181 case BPF_CGROUP_INET6_CONNECT:
4182 case BPF_CGROUP_UNIX_CONNECT:
4183 case BPF_CGROUP_INET4_GETPEERNAME:
4184 case BPF_CGROUP_INET6_GETPEERNAME:
4185 case BPF_CGROUP_UNIX_GETPEERNAME:
4186 case BPF_CGROUP_INET4_GETSOCKNAME:
4187 case BPF_CGROUP_INET6_GETSOCKNAME:
4188 case BPF_CGROUP_UNIX_GETSOCKNAME:
4189 case BPF_CGROUP_UDP4_SENDMSG:
4190 case BPF_CGROUP_UDP6_SENDMSG:
4191 case BPF_CGROUP_UNIX_SENDMSG:
4192 case BPF_CGROUP_UDP4_RECVMSG:
4193 case BPF_CGROUP_UDP6_RECVMSG:
4194 case BPF_CGROUP_UNIX_RECVMSG:
4195 case BPF_CGROUP_SOCK_OPS:
4196 case BPF_CGROUP_DEVICE:
4197 case BPF_CGROUP_SYSCTL:
4198 case BPF_CGROUP_GETSOCKOPT:
4199 case BPF_CGROUP_SETSOCKOPT:
4200 case BPF_LSM_CGROUP:
4201 return cgroup_bpf_prog_query(attr, uattr);
4202 case BPF_LIRC_MODE2:
4203 return lirc_prog_query(attr, uattr);
4204 case BPF_FLOW_DISSECTOR:
4206 return netns_bpf_prog_query(attr, uattr);
4207 case BPF_SK_SKB_STREAM_PARSER:
4208 case BPF_SK_SKB_STREAM_VERDICT:
4209 case BPF_SK_MSG_VERDICT:
4210 case BPF_SK_SKB_VERDICT:
4211 return sock_map_bpf_prog_query(attr, uattr);
4212 case BPF_TCX_INGRESS:
4213 case BPF_TCX_EGRESS:
4214 return tcx_prog_query(attr, uattr);
4215 case BPF_NETKIT_PRIMARY:
4216 case BPF_NETKIT_PEER:
4217 return netkit_prog_query(attr, uattr);
4223 #define BPF_PROG_TEST_RUN_LAST_FIELD test.batch_size
4225 static int bpf_prog_test_run(const union bpf_attr *attr,
4226 union bpf_attr __user *uattr)
4228 struct bpf_prog *prog;
4229 int ret = -ENOTSUPP;
4231 if (CHECK_ATTR(BPF_PROG_TEST_RUN))
4234 if ((attr->test.ctx_size_in && !attr->test.ctx_in) ||
4235 (!attr->test.ctx_size_in && attr->test.ctx_in))
4238 if ((attr->test.ctx_size_out && !attr->test.ctx_out) ||
4239 (!attr->test.ctx_size_out && attr->test.ctx_out))
4242 prog = bpf_prog_get(attr->test.prog_fd);
4244 return PTR_ERR(prog);
4246 if (prog->aux->ops->test_run)
4247 ret = prog->aux->ops->test_run(prog, attr, uattr);
4253 #define BPF_OBJ_GET_NEXT_ID_LAST_FIELD next_id
4255 static int bpf_obj_get_next_id(const union bpf_attr *attr,
4256 union bpf_attr __user *uattr,
4260 u32 next_id = attr->start_id;
4263 if (CHECK_ATTR(BPF_OBJ_GET_NEXT_ID) || next_id >= INT_MAX)
4266 if (!capable(CAP_SYS_ADMIN))
4271 if (!idr_get_next(idr, &next_id))
4273 spin_unlock_bh(lock);
4276 err = put_user(next_id, &uattr->next_id);
4281 struct bpf_map *bpf_map_get_curr_or_next(u32 *id)
4283 struct bpf_map *map;
4285 spin_lock_bh(&map_idr_lock);
4287 map = idr_get_next(&map_idr, id);
4289 map = __bpf_map_inc_not_zero(map, false);
4295 spin_unlock_bh(&map_idr_lock);
4300 struct bpf_prog *bpf_prog_get_curr_or_next(u32 *id)
4302 struct bpf_prog *prog;
4304 spin_lock_bh(&prog_idr_lock);
4306 prog = idr_get_next(&prog_idr, id);
4308 prog = bpf_prog_inc_not_zero(prog);
4314 spin_unlock_bh(&prog_idr_lock);
4319 #define BPF_PROG_GET_FD_BY_ID_LAST_FIELD prog_id
4321 struct bpf_prog *bpf_prog_by_id(u32 id)
4323 struct bpf_prog *prog;
4326 return ERR_PTR(-ENOENT);
4328 spin_lock_bh(&prog_idr_lock);
4329 prog = idr_find(&prog_idr, id);
4331 prog = bpf_prog_inc_not_zero(prog);
4333 prog = ERR_PTR(-ENOENT);
4334 spin_unlock_bh(&prog_idr_lock);
4338 static int bpf_prog_get_fd_by_id(const union bpf_attr *attr)
4340 struct bpf_prog *prog;
4341 u32 id = attr->prog_id;
4344 if (CHECK_ATTR(BPF_PROG_GET_FD_BY_ID))
4347 if (!capable(CAP_SYS_ADMIN))
4350 prog = bpf_prog_by_id(id);
4352 return PTR_ERR(prog);
4354 fd = bpf_prog_new_fd(prog);
4361 #define BPF_MAP_GET_FD_BY_ID_LAST_FIELD open_flags
4363 static int bpf_map_get_fd_by_id(const union bpf_attr *attr)
4365 struct bpf_map *map;
4366 u32 id = attr->map_id;
4370 if (CHECK_ATTR(BPF_MAP_GET_FD_BY_ID) ||
4371 attr->open_flags & ~BPF_OBJ_FLAG_MASK)
4374 if (!capable(CAP_SYS_ADMIN))
4377 f_flags = bpf_get_file_flag(attr->open_flags);
4381 spin_lock_bh(&map_idr_lock);
4382 map = idr_find(&map_idr, id);
4384 map = __bpf_map_inc_not_zero(map, true);
4386 map = ERR_PTR(-ENOENT);
4387 spin_unlock_bh(&map_idr_lock);
4390 return PTR_ERR(map);
4392 fd = bpf_map_new_fd(map, f_flags);
4394 bpf_map_put_with_uref(map);
4399 static const struct bpf_map *bpf_map_from_imm(const struct bpf_prog *prog,
4400 unsigned long addr, u32 *off,
4403 const struct bpf_map *map;
4406 mutex_lock(&prog->aux->used_maps_mutex);
4407 for (i = 0, *off = 0; i < prog->aux->used_map_cnt; i++) {
4408 map = prog->aux->used_maps[i];
4409 if (map == (void *)addr) {
4410 *type = BPF_PSEUDO_MAP_FD;
4413 if (!map->ops->map_direct_value_meta)
4415 if (!map->ops->map_direct_value_meta(map, addr, off)) {
4416 *type = BPF_PSEUDO_MAP_VALUE;
4423 mutex_unlock(&prog->aux->used_maps_mutex);
4427 static struct bpf_insn *bpf_insn_prepare_dump(const struct bpf_prog *prog,
4428 const struct cred *f_cred)
4430 const struct bpf_map *map;
4431 struct bpf_insn *insns;
4437 insns = kmemdup(prog->insnsi, bpf_prog_insn_size(prog),
4442 for (i = 0; i < prog->len; i++) {
4443 code = insns[i].code;
4445 if (code == (BPF_JMP | BPF_TAIL_CALL)) {
4446 insns[i].code = BPF_JMP | BPF_CALL;
4447 insns[i].imm = BPF_FUNC_tail_call;
4450 if (code == (BPF_JMP | BPF_CALL) ||
4451 code == (BPF_JMP | BPF_CALL_ARGS)) {
4452 if (code == (BPF_JMP | BPF_CALL_ARGS))
4453 insns[i].code = BPF_JMP | BPF_CALL;
4454 if (!bpf_dump_raw_ok(f_cred))
4458 if (BPF_CLASS(code) == BPF_LDX && BPF_MODE(code) == BPF_PROBE_MEM) {
4459 insns[i].code = BPF_LDX | BPF_SIZE(code) | BPF_MEM;
4463 if ((BPF_CLASS(code) == BPF_LDX || BPF_CLASS(code) == BPF_STX ||
4464 BPF_CLASS(code) == BPF_ST) && BPF_MODE(code) == BPF_PROBE_MEM32) {
4465 insns[i].code = BPF_CLASS(code) | BPF_SIZE(code) | BPF_MEM;
4469 if (code != (BPF_LD | BPF_IMM | BPF_DW))
4472 imm = ((u64)insns[i + 1].imm << 32) | (u32)insns[i].imm;
4473 map = bpf_map_from_imm(prog, imm, &off, &type);
4475 insns[i].src_reg = type;
4476 insns[i].imm = map->id;
4477 insns[i + 1].imm = off;
4485 static int set_info_rec_size(struct bpf_prog_info *info)
4488 * Ensure info.*_rec_size is the same as kernel expected size
4492 * Only allow zero *_rec_size if both _rec_size and _cnt are
4493 * zero. In this case, the kernel will set the expected
4494 * _rec_size back to the info.
4497 if ((info->nr_func_info || info->func_info_rec_size) &&
4498 info->func_info_rec_size != sizeof(struct bpf_func_info))
4501 if ((info->nr_line_info || info->line_info_rec_size) &&
4502 info->line_info_rec_size != sizeof(struct bpf_line_info))
4505 if ((info->nr_jited_line_info || info->jited_line_info_rec_size) &&
4506 info->jited_line_info_rec_size != sizeof(__u64))
4509 info->func_info_rec_size = sizeof(struct bpf_func_info);
4510 info->line_info_rec_size = sizeof(struct bpf_line_info);
4511 info->jited_line_info_rec_size = sizeof(__u64);
4516 static int bpf_prog_get_info_by_fd(struct file *file,
4517 struct bpf_prog *prog,
4518 const union bpf_attr *attr,
4519 union bpf_attr __user *uattr)
4521 struct bpf_prog_info __user *uinfo = u64_to_user_ptr(attr->info.info);
4522 struct btf *attach_btf = bpf_prog_get_target_btf(prog);
4523 struct bpf_prog_info info;
4524 u32 info_len = attr->info.info_len;
4525 struct bpf_prog_kstats stats;
4526 char __user *uinsns;
4530 err = bpf_check_uarg_tail_zero(USER_BPFPTR(uinfo), sizeof(info), info_len);
4533 info_len = min_t(u32, sizeof(info), info_len);
4535 memset(&info, 0, sizeof(info));
4536 if (copy_from_user(&info, uinfo, info_len))
4539 info.type = prog->type;
4540 info.id = prog->aux->id;
4541 info.load_time = prog->aux->load_time;
4542 info.created_by_uid = from_kuid_munged(current_user_ns(),
4543 prog->aux->user->uid);
4544 info.gpl_compatible = prog->gpl_compatible;
4546 memcpy(info.tag, prog->tag, sizeof(prog->tag));
4547 memcpy(info.name, prog->aux->name, sizeof(prog->aux->name));
4549 mutex_lock(&prog->aux->used_maps_mutex);
4550 ulen = info.nr_map_ids;
4551 info.nr_map_ids = prog->aux->used_map_cnt;
4552 ulen = min_t(u32, info.nr_map_ids, ulen);
4554 u32 __user *user_map_ids = u64_to_user_ptr(info.map_ids);
4557 for (i = 0; i < ulen; i++)
4558 if (put_user(prog->aux->used_maps[i]->id,
4559 &user_map_ids[i])) {
4560 mutex_unlock(&prog->aux->used_maps_mutex);
4564 mutex_unlock(&prog->aux->used_maps_mutex);
4566 err = set_info_rec_size(&info);
4570 bpf_prog_get_stats(prog, &stats);
4571 info.run_time_ns = stats.nsecs;
4572 info.run_cnt = stats.cnt;
4573 info.recursion_misses = stats.misses;
4575 info.verified_insns = prog->aux->verified_insns;
4577 if (!bpf_capable()) {
4578 info.jited_prog_len = 0;
4579 info.xlated_prog_len = 0;
4580 info.nr_jited_ksyms = 0;
4581 info.nr_jited_func_lens = 0;
4582 info.nr_func_info = 0;
4583 info.nr_line_info = 0;
4584 info.nr_jited_line_info = 0;
4588 ulen = info.xlated_prog_len;
4589 info.xlated_prog_len = bpf_prog_insn_size(prog);
4590 if (info.xlated_prog_len && ulen) {
4591 struct bpf_insn *insns_sanitized;
4594 if (prog->blinded && !bpf_dump_raw_ok(file->f_cred)) {
4595 info.xlated_prog_insns = 0;
4598 insns_sanitized = bpf_insn_prepare_dump(prog, file->f_cred);
4599 if (!insns_sanitized)
4601 uinsns = u64_to_user_ptr(info.xlated_prog_insns);
4602 ulen = min_t(u32, info.xlated_prog_len, ulen);
4603 fault = copy_to_user(uinsns, insns_sanitized, ulen);
4604 kfree(insns_sanitized);
4609 if (bpf_prog_is_offloaded(prog->aux)) {
4610 err = bpf_prog_offload_info_fill(&info, prog);
4616 /* NOTE: the following code is supposed to be skipped for offload.
4617 * bpf_prog_offload_info_fill() is the place to fill similar fields
4620 ulen = info.jited_prog_len;
4621 if (prog->aux->func_cnt) {
4624 info.jited_prog_len = 0;
4625 for (i = 0; i < prog->aux->func_cnt; i++)
4626 info.jited_prog_len += prog->aux->func[i]->jited_len;
4628 info.jited_prog_len = prog->jited_len;
4631 if (info.jited_prog_len && ulen) {
4632 if (bpf_dump_raw_ok(file->f_cred)) {
4633 uinsns = u64_to_user_ptr(info.jited_prog_insns);
4634 ulen = min_t(u32, info.jited_prog_len, ulen);
4636 /* for multi-function programs, copy the JITed
4637 * instructions for all the functions
4639 if (prog->aux->func_cnt) {
4644 for (i = 0; i < prog->aux->func_cnt; i++) {
4645 len = prog->aux->func[i]->jited_len;
4646 len = min_t(u32, len, free);
4647 img = (u8 *) prog->aux->func[i]->bpf_func;
4648 if (copy_to_user(uinsns, img, len))
4656 if (copy_to_user(uinsns, prog->bpf_func, ulen))
4660 info.jited_prog_insns = 0;
4664 ulen = info.nr_jited_ksyms;
4665 info.nr_jited_ksyms = prog->aux->func_cnt ? : 1;
4667 if (bpf_dump_raw_ok(file->f_cred)) {
4668 unsigned long ksym_addr;
4669 u64 __user *user_ksyms;
4672 /* copy the address of the kernel symbol
4673 * corresponding to each function
4675 ulen = min_t(u32, info.nr_jited_ksyms, ulen);
4676 user_ksyms = u64_to_user_ptr(info.jited_ksyms);
4677 if (prog->aux->func_cnt) {
4678 for (i = 0; i < ulen; i++) {
4679 ksym_addr = (unsigned long)
4680 prog->aux->func[i]->bpf_func;
4681 if (put_user((u64) ksym_addr,
4686 ksym_addr = (unsigned long) prog->bpf_func;
4687 if (put_user((u64) ksym_addr, &user_ksyms[0]))
4691 info.jited_ksyms = 0;
4695 ulen = info.nr_jited_func_lens;
4696 info.nr_jited_func_lens = prog->aux->func_cnt ? : 1;
4698 if (bpf_dump_raw_ok(file->f_cred)) {
4699 u32 __user *user_lens;
4702 /* copy the JITed image lengths for each function */
4703 ulen = min_t(u32, info.nr_jited_func_lens, ulen);
4704 user_lens = u64_to_user_ptr(info.jited_func_lens);
4705 if (prog->aux->func_cnt) {
4706 for (i = 0; i < ulen; i++) {
4708 prog->aux->func[i]->jited_len;
4709 if (put_user(func_len, &user_lens[i]))
4713 func_len = prog->jited_len;
4714 if (put_user(func_len, &user_lens[0]))
4718 info.jited_func_lens = 0;
4723 info.btf_id = btf_obj_id(prog->aux->btf);
4724 info.attach_btf_id = prog->aux->attach_btf_id;
4726 info.attach_btf_obj_id = btf_obj_id(attach_btf);
4728 ulen = info.nr_func_info;
4729 info.nr_func_info = prog->aux->func_info_cnt;
4730 if (info.nr_func_info && ulen) {
4731 char __user *user_finfo;
4733 user_finfo = u64_to_user_ptr(info.func_info);
4734 ulen = min_t(u32, info.nr_func_info, ulen);
4735 if (copy_to_user(user_finfo, prog->aux->func_info,
4736 info.func_info_rec_size * ulen))
4740 ulen = info.nr_line_info;
4741 info.nr_line_info = prog->aux->nr_linfo;
4742 if (info.nr_line_info && ulen) {
4743 __u8 __user *user_linfo;
4745 user_linfo = u64_to_user_ptr(info.line_info);
4746 ulen = min_t(u32, info.nr_line_info, ulen);
4747 if (copy_to_user(user_linfo, prog->aux->linfo,
4748 info.line_info_rec_size * ulen))
4752 ulen = info.nr_jited_line_info;
4753 if (prog->aux->jited_linfo)
4754 info.nr_jited_line_info = prog->aux->nr_linfo;
4756 info.nr_jited_line_info = 0;
4757 if (info.nr_jited_line_info && ulen) {
4758 if (bpf_dump_raw_ok(file->f_cred)) {
4759 unsigned long line_addr;
4760 __u64 __user *user_linfo;
4763 user_linfo = u64_to_user_ptr(info.jited_line_info);
4764 ulen = min_t(u32, info.nr_jited_line_info, ulen);
4765 for (i = 0; i < ulen; i++) {
4766 line_addr = (unsigned long)prog->aux->jited_linfo[i];
4767 if (put_user((__u64)line_addr, &user_linfo[i]))
4771 info.jited_line_info = 0;
4775 ulen = info.nr_prog_tags;
4776 info.nr_prog_tags = prog->aux->func_cnt ? : 1;
4778 __u8 __user (*user_prog_tags)[BPF_TAG_SIZE];
4781 user_prog_tags = u64_to_user_ptr(info.prog_tags);
4782 ulen = min_t(u32, info.nr_prog_tags, ulen);
4783 if (prog->aux->func_cnt) {
4784 for (i = 0; i < ulen; i++) {
4785 if (copy_to_user(user_prog_tags[i],
4786 prog->aux->func[i]->tag,
4791 if (copy_to_user(user_prog_tags[0],
4792 prog->tag, BPF_TAG_SIZE))
4798 if (copy_to_user(uinfo, &info, info_len) ||
4799 put_user(info_len, &uattr->info.info_len))
4805 static int bpf_map_get_info_by_fd(struct file *file,
4806 struct bpf_map *map,
4807 const union bpf_attr *attr,
4808 union bpf_attr __user *uattr)
4810 struct bpf_map_info __user *uinfo = u64_to_user_ptr(attr->info.info);
4811 struct bpf_map_info info;
4812 u32 info_len = attr->info.info_len;
4815 err = bpf_check_uarg_tail_zero(USER_BPFPTR(uinfo), sizeof(info), info_len);
4818 info_len = min_t(u32, sizeof(info), info_len);
4820 memset(&info, 0, sizeof(info));
4821 info.type = map->map_type;
4823 info.key_size = map->key_size;
4824 info.value_size = map->value_size;
4825 info.max_entries = map->max_entries;
4826 info.map_flags = map->map_flags;
4827 info.map_extra = map->map_extra;
4828 memcpy(info.name, map->name, sizeof(map->name));
4831 info.btf_id = btf_obj_id(map->btf);
4832 info.btf_key_type_id = map->btf_key_type_id;
4833 info.btf_value_type_id = map->btf_value_type_id;
4835 info.btf_vmlinux_value_type_id = map->btf_vmlinux_value_type_id;
4836 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS)
4837 bpf_map_struct_ops_info_fill(&info, map);
4839 if (bpf_map_is_offloaded(map)) {
4840 err = bpf_map_offload_info_fill(&info, map);
4845 if (copy_to_user(uinfo, &info, info_len) ||
4846 put_user(info_len, &uattr->info.info_len))
4852 static int bpf_btf_get_info_by_fd(struct file *file,
4854 const union bpf_attr *attr,
4855 union bpf_attr __user *uattr)
4857 struct bpf_btf_info __user *uinfo = u64_to_user_ptr(attr->info.info);
4858 u32 info_len = attr->info.info_len;
4861 err = bpf_check_uarg_tail_zero(USER_BPFPTR(uinfo), sizeof(*uinfo), info_len);
4865 return btf_get_info_by_fd(btf, attr, uattr);
4868 static int bpf_link_get_info_by_fd(struct file *file,
4869 struct bpf_link *link,
4870 const union bpf_attr *attr,
4871 union bpf_attr __user *uattr)
4873 struct bpf_link_info __user *uinfo = u64_to_user_ptr(attr->info.info);
4874 struct bpf_link_info info;
4875 u32 info_len = attr->info.info_len;
4878 err = bpf_check_uarg_tail_zero(USER_BPFPTR(uinfo), sizeof(info), info_len);
4881 info_len = min_t(u32, sizeof(info), info_len);
4883 memset(&info, 0, sizeof(info));
4884 if (copy_from_user(&info, uinfo, info_len))
4887 info.type = link->type;
4890 info.prog_id = link->prog->aux->id;
4892 if (link->ops->fill_link_info) {
4893 err = link->ops->fill_link_info(link, &info);
4898 if (copy_to_user(uinfo, &info, info_len) ||
4899 put_user(info_len, &uattr->info.info_len))
4906 #define BPF_OBJ_GET_INFO_BY_FD_LAST_FIELD info.info
4908 static int bpf_obj_get_info_by_fd(const union bpf_attr *attr,
4909 union bpf_attr __user *uattr)
4911 if (CHECK_ATTR(BPF_OBJ_GET_INFO_BY_FD))
4914 CLASS(fd, f)(attr->info.bpf_fd);
4918 if (fd_file(f)->f_op == &bpf_prog_fops)
4919 return bpf_prog_get_info_by_fd(fd_file(f), fd_file(f)->private_data, attr,
4921 else if (fd_file(f)->f_op == &bpf_map_fops)
4922 return bpf_map_get_info_by_fd(fd_file(f), fd_file(f)->private_data, attr,
4924 else if (fd_file(f)->f_op == &btf_fops)
4925 return bpf_btf_get_info_by_fd(fd_file(f), fd_file(f)->private_data, attr, uattr);
4926 else if (fd_file(f)->f_op == &bpf_link_fops || fd_file(f)->f_op == &bpf_link_fops_poll)
4927 return bpf_link_get_info_by_fd(fd_file(f), fd_file(f)->private_data,
4932 #define BPF_BTF_LOAD_LAST_FIELD btf_token_fd
4934 static int bpf_btf_load(const union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size)
4936 struct bpf_token *token = NULL;
4938 if (CHECK_ATTR(BPF_BTF_LOAD))
4941 if (attr->btf_flags & ~BPF_F_TOKEN_FD)
4944 if (attr->btf_flags & BPF_F_TOKEN_FD) {
4945 token = bpf_token_get_from_fd(attr->btf_token_fd);
4947 return PTR_ERR(token);
4948 if (!bpf_token_allow_cmd(token, BPF_BTF_LOAD)) {
4949 bpf_token_put(token);
4954 if (!bpf_token_capable(token, CAP_BPF)) {
4955 bpf_token_put(token);
4959 bpf_token_put(token);
4961 return btf_new_fd(attr, uattr, uattr_size);
4964 #define BPF_BTF_GET_FD_BY_ID_LAST_FIELD btf_id
4966 static int bpf_btf_get_fd_by_id(const union bpf_attr *attr)
4968 if (CHECK_ATTR(BPF_BTF_GET_FD_BY_ID))
4971 if (!capable(CAP_SYS_ADMIN))
4974 return btf_get_fd_by_id(attr->btf_id);
4977 static int bpf_task_fd_query_copy(const union bpf_attr *attr,
4978 union bpf_attr __user *uattr,
4979 u32 prog_id, u32 fd_type,
4980 const char *buf, u64 probe_offset,
4983 char __user *ubuf = u64_to_user_ptr(attr->task_fd_query.buf);
4984 u32 len = buf ? strlen(buf) : 0, input_len;
4987 if (put_user(len, &uattr->task_fd_query.buf_len))
4989 input_len = attr->task_fd_query.buf_len;
4990 if (input_len && ubuf) {
4992 /* nothing to copy, just make ubuf NULL terminated */
4995 if (put_user(zero, ubuf))
4997 } else if (input_len >= len + 1) {
4998 /* ubuf can hold the string with NULL terminator */
4999 if (copy_to_user(ubuf, buf, len + 1))
5002 /* ubuf cannot hold the string with NULL terminator,
5003 * do a partial copy with NULL terminator.
5008 if (copy_to_user(ubuf, buf, input_len - 1))
5010 if (put_user(zero, ubuf + input_len - 1))
5015 if (put_user(prog_id, &uattr->task_fd_query.prog_id) ||
5016 put_user(fd_type, &uattr->task_fd_query.fd_type) ||
5017 put_user(probe_offset, &uattr->task_fd_query.probe_offset) ||
5018 put_user(probe_addr, &uattr->task_fd_query.probe_addr))
5024 #define BPF_TASK_FD_QUERY_LAST_FIELD task_fd_query.probe_addr
5026 static int bpf_task_fd_query(const union bpf_attr *attr,
5027 union bpf_attr __user *uattr)
5029 pid_t pid = attr->task_fd_query.pid;
5030 u32 fd = attr->task_fd_query.fd;
5031 const struct perf_event *event;
5032 struct task_struct *task;
5036 if (CHECK_ATTR(BPF_TASK_FD_QUERY))
5039 if (!capable(CAP_SYS_ADMIN))
5042 if (attr->task_fd_query.flags != 0)
5046 task = get_pid_task(find_vpid(pid), PIDTYPE_PID);
5052 file = fget_task(task, fd);
5053 put_task_struct(task);
5057 if (file->f_op == &bpf_link_fops || file->f_op == &bpf_link_fops_poll) {
5058 struct bpf_link *link = file->private_data;
5060 if (link->ops == &bpf_raw_tp_link_lops) {
5061 struct bpf_raw_tp_link *raw_tp =
5062 container_of(link, struct bpf_raw_tp_link, link);
5063 struct bpf_raw_event_map *btp = raw_tp->btp;
5065 err = bpf_task_fd_query_copy(attr, uattr,
5066 raw_tp->link.prog->aux->id,
5067 BPF_FD_TYPE_RAW_TRACEPOINT,
5068 btp->tp->name, 0, 0);
5074 event = perf_get_event(file);
5075 if (!IS_ERR(event)) {
5076 u64 probe_offset, probe_addr;
5077 u32 prog_id, fd_type;
5080 err = bpf_get_perf_event_info(event, &prog_id, &fd_type,
5081 &buf, &probe_offset,
5084 err = bpf_task_fd_query_copy(attr, uattr, prog_id,
5098 #define BPF_MAP_BATCH_LAST_FIELD batch.flags
5100 #define BPF_DO_BATCH(fn, ...) \
5106 err = fn(__VA_ARGS__); \
5109 static int bpf_map_do_batch(const union bpf_attr *attr,
5110 union bpf_attr __user *uattr,
5113 bool has_read = cmd == BPF_MAP_LOOKUP_BATCH ||
5114 cmd == BPF_MAP_LOOKUP_AND_DELETE_BATCH;
5115 bool has_write = cmd != BPF_MAP_LOOKUP_BATCH;
5116 struct bpf_map *map;
5119 if (CHECK_ATTR(BPF_MAP_BATCH))
5122 CLASS(fd, f)(attr->batch.map_fd);
5124 map = __bpf_map_get(f);
5126 return PTR_ERR(map);
5128 bpf_map_write_active_inc(map);
5129 if (has_read && !(map_get_sys_perms(map, f) & FMODE_CAN_READ)) {
5133 if (has_write && !(map_get_sys_perms(map, f) & FMODE_CAN_WRITE)) {
5138 if (cmd == BPF_MAP_LOOKUP_BATCH)
5139 BPF_DO_BATCH(map->ops->map_lookup_batch, map, attr, uattr);
5140 else if (cmd == BPF_MAP_LOOKUP_AND_DELETE_BATCH)
5141 BPF_DO_BATCH(map->ops->map_lookup_and_delete_batch, map, attr, uattr);
5142 else if (cmd == BPF_MAP_UPDATE_BATCH)
5143 BPF_DO_BATCH(map->ops->map_update_batch, map, fd_file(f), attr, uattr);
5145 BPF_DO_BATCH(map->ops->map_delete_batch, map, attr, uattr);
5148 maybe_wait_bpf_programs(map);
5149 bpf_map_write_active_dec(map);
5154 #define BPF_LINK_CREATE_LAST_FIELD link_create.uprobe_multi.pid
5155 static int link_create(union bpf_attr *attr, bpfptr_t uattr)
5157 struct bpf_prog *prog;
5160 if (CHECK_ATTR(BPF_LINK_CREATE))
5163 if (attr->link_create.attach_type == BPF_STRUCT_OPS)
5164 return bpf_struct_ops_link_create(attr);
5166 prog = bpf_prog_get(attr->link_create.prog_fd);
5168 return PTR_ERR(prog);
5170 ret = bpf_prog_attach_check_attach_type(prog,
5171 attr->link_create.attach_type);
5175 switch (prog->type) {
5176 case BPF_PROG_TYPE_CGROUP_SKB:
5177 case BPF_PROG_TYPE_CGROUP_SOCK:
5178 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
5179 case BPF_PROG_TYPE_SOCK_OPS:
5180 case BPF_PROG_TYPE_CGROUP_DEVICE:
5181 case BPF_PROG_TYPE_CGROUP_SYSCTL:
5182 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
5183 ret = cgroup_bpf_link_attach(attr, prog);
5185 case BPF_PROG_TYPE_EXT:
5186 ret = bpf_tracing_prog_attach(prog,
5187 attr->link_create.target_fd,
5188 attr->link_create.target_btf_id,
5189 attr->link_create.tracing.cookie);
5191 case BPF_PROG_TYPE_LSM:
5192 case BPF_PROG_TYPE_TRACING:
5193 if (attr->link_create.attach_type != prog->expected_attach_type) {
5197 if (prog->expected_attach_type == BPF_TRACE_RAW_TP)
5198 ret = bpf_raw_tp_link_attach(prog, NULL, attr->link_create.tracing.cookie);
5199 else if (prog->expected_attach_type == BPF_TRACE_ITER)
5200 ret = bpf_iter_link_attach(attr, uattr, prog);
5201 else if (prog->expected_attach_type == BPF_LSM_CGROUP)
5202 ret = cgroup_bpf_link_attach(attr, prog);
5204 ret = bpf_tracing_prog_attach(prog,
5205 attr->link_create.target_fd,
5206 attr->link_create.target_btf_id,
5207 attr->link_create.tracing.cookie);
5209 case BPF_PROG_TYPE_FLOW_DISSECTOR:
5210 case BPF_PROG_TYPE_SK_LOOKUP:
5211 ret = netns_bpf_link_create(attr, prog);
5213 case BPF_PROG_TYPE_SK_MSG:
5214 case BPF_PROG_TYPE_SK_SKB:
5215 ret = sock_map_link_create(attr, prog);
5218 case BPF_PROG_TYPE_XDP:
5219 ret = bpf_xdp_link_attach(attr, prog);
5221 case BPF_PROG_TYPE_SCHED_CLS:
5222 if (attr->link_create.attach_type == BPF_TCX_INGRESS ||
5223 attr->link_create.attach_type == BPF_TCX_EGRESS)
5224 ret = tcx_link_attach(attr, prog);
5226 ret = netkit_link_attach(attr, prog);
5228 case BPF_PROG_TYPE_NETFILTER:
5229 ret = bpf_nf_link_attach(attr, prog);
5232 case BPF_PROG_TYPE_PERF_EVENT:
5233 case BPF_PROG_TYPE_TRACEPOINT:
5234 ret = bpf_perf_link_attach(attr, prog);
5236 case BPF_PROG_TYPE_KPROBE:
5237 if (attr->link_create.attach_type == BPF_PERF_EVENT)
5238 ret = bpf_perf_link_attach(attr, prog);
5239 else if (attr->link_create.attach_type == BPF_TRACE_KPROBE_MULTI ||
5240 attr->link_create.attach_type == BPF_TRACE_KPROBE_SESSION)
5241 ret = bpf_kprobe_multi_link_attach(attr, prog);
5242 else if (attr->link_create.attach_type == BPF_TRACE_UPROBE_MULTI)
5243 ret = bpf_uprobe_multi_link_attach(attr, prog);
5255 static int link_update_map(struct bpf_link *link, union bpf_attr *attr)
5257 struct bpf_map *new_map, *old_map = NULL;
5260 new_map = bpf_map_get(attr->link_update.new_map_fd);
5261 if (IS_ERR(new_map))
5262 return PTR_ERR(new_map);
5264 if (attr->link_update.flags & BPF_F_REPLACE) {
5265 old_map = bpf_map_get(attr->link_update.old_map_fd);
5266 if (IS_ERR(old_map)) {
5267 ret = PTR_ERR(old_map);
5270 } else if (attr->link_update.old_map_fd) {
5275 ret = link->ops->update_map(link, new_map, old_map);
5278 bpf_map_put(old_map);
5280 bpf_map_put(new_map);
5284 #define BPF_LINK_UPDATE_LAST_FIELD link_update.old_prog_fd
5286 static int link_update(union bpf_attr *attr)
5288 struct bpf_prog *old_prog = NULL, *new_prog;
5289 struct bpf_link *link;
5293 if (CHECK_ATTR(BPF_LINK_UPDATE))
5296 flags = attr->link_update.flags;
5297 if (flags & ~BPF_F_REPLACE)
5300 link = bpf_link_get_from_fd(attr->link_update.link_fd);
5302 return PTR_ERR(link);
5304 if (link->ops->update_map) {
5305 ret = link_update_map(link, attr);
5309 new_prog = bpf_prog_get(attr->link_update.new_prog_fd);
5310 if (IS_ERR(new_prog)) {
5311 ret = PTR_ERR(new_prog);
5315 if (flags & BPF_F_REPLACE) {
5316 old_prog = bpf_prog_get(attr->link_update.old_prog_fd);
5317 if (IS_ERR(old_prog)) {
5318 ret = PTR_ERR(old_prog);
5322 } else if (attr->link_update.old_prog_fd) {
5327 if (link->ops->update_prog)
5328 ret = link->ops->update_prog(link, new_prog, old_prog);
5334 bpf_prog_put(old_prog);
5336 bpf_prog_put(new_prog);
5338 bpf_link_put_direct(link);
5342 #define BPF_LINK_DETACH_LAST_FIELD link_detach.link_fd
5344 static int link_detach(union bpf_attr *attr)
5346 struct bpf_link *link;
5349 if (CHECK_ATTR(BPF_LINK_DETACH))
5352 link = bpf_link_get_from_fd(attr->link_detach.link_fd);
5354 return PTR_ERR(link);
5356 if (link->ops->detach)
5357 ret = link->ops->detach(link);
5361 bpf_link_put_direct(link);
5365 struct bpf_link *bpf_link_inc_not_zero(struct bpf_link *link)
5367 return atomic64_fetch_add_unless(&link->refcnt, 1, 0) ? link : ERR_PTR(-ENOENT);
5369 EXPORT_SYMBOL(bpf_link_inc_not_zero);
5371 struct bpf_link *bpf_link_by_id(u32 id)
5373 struct bpf_link *link;
5376 return ERR_PTR(-ENOENT);
5378 spin_lock_bh(&link_idr_lock);
5379 /* before link is "settled", ID is 0, pretend it doesn't exist yet */
5380 link = idr_find(&link_idr, id);
5383 link = bpf_link_inc_not_zero(link);
5385 link = ERR_PTR(-EAGAIN);
5387 link = ERR_PTR(-ENOENT);
5389 spin_unlock_bh(&link_idr_lock);
5393 struct bpf_link *bpf_link_get_curr_or_next(u32 *id)
5395 struct bpf_link *link;
5397 spin_lock_bh(&link_idr_lock);
5399 link = idr_get_next(&link_idr, id);
5401 link = bpf_link_inc_not_zero(link);
5407 spin_unlock_bh(&link_idr_lock);
5412 #define BPF_LINK_GET_FD_BY_ID_LAST_FIELD link_id
5414 static int bpf_link_get_fd_by_id(const union bpf_attr *attr)
5416 struct bpf_link *link;
5417 u32 id = attr->link_id;
5420 if (CHECK_ATTR(BPF_LINK_GET_FD_BY_ID))
5423 if (!capable(CAP_SYS_ADMIN))
5426 link = bpf_link_by_id(id);
5428 return PTR_ERR(link);
5430 fd = bpf_link_new_fd(link);
5432 bpf_link_put_direct(link);
5437 DEFINE_MUTEX(bpf_stats_enabled_mutex);
5439 static int bpf_stats_release(struct inode *inode, struct file *file)
5441 mutex_lock(&bpf_stats_enabled_mutex);
5442 static_key_slow_dec(&bpf_stats_enabled_key.key);
5443 mutex_unlock(&bpf_stats_enabled_mutex);
5447 static const struct file_operations bpf_stats_fops = {
5448 .release = bpf_stats_release,
5451 static int bpf_enable_runtime_stats(void)
5455 mutex_lock(&bpf_stats_enabled_mutex);
5457 /* Set a very high limit to avoid overflow */
5458 if (static_key_count(&bpf_stats_enabled_key.key) > INT_MAX / 2) {
5459 mutex_unlock(&bpf_stats_enabled_mutex);
5463 fd = anon_inode_getfd("bpf-stats", &bpf_stats_fops, NULL, O_CLOEXEC);
5465 static_key_slow_inc(&bpf_stats_enabled_key.key);
5467 mutex_unlock(&bpf_stats_enabled_mutex);
5471 #define BPF_ENABLE_STATS_LAST_FIELD enable_stats.type
5473 static int bpf_enable_stats(union bpf_attr *attr)
5476 if (CHECK_ATTR(BPF_ENABLE_STATS))
5479 if (!capable(CAP_SYS_ADMIN))
5482 switch (attr->enable_stats.type) {
5483 case BPF_STATS_RUN_TIME:
5484 return bpf_enable_runtime_stats();
5491 #define BPF_ITER_CREATE_LAST_FIELD iter_create.flags
5493 static int bpf_iter_create(union bpf_attr *attr)
5495 struct bpf_link *link;
5498 if (CHECK_ATTR(BPF_ITER_CREATE))
5501 if (attr->iter_create.flags)
5504 link = bpf_link_get_from_fd(attr->iter_create.link_fd);
5506 return PTR_ERR(link);
5508 err = bpf_iter_new_fd(link);
5509 bpf_link_put_direct(link);
5514 #define BPF_PROG_BIND_MAP_LAST_FIELD prog_bind_map.flags
5516 static int bpf_prog_bind_map(union bpf_attr *attr)
5518 struct bpf_prog *prog;
5519 struct bpf_map *map;
5520 struct bpf_map **used_maps_old, **used_maps_new;
5523 if (CHECK_ATTR(BPF_PROG_BIND_MAP))
5526 if (attr->prog_bind_map.flags)
5529 prog = bpf_prog_get(attr->prog_bind_map.prog_fd);
5531 return PTR_ERR(prog);
5533 map = bpf_map_get(attr->prog_bind_map.map_fd);
5539 mutex_lock(&prog->aux->used_maps_mutex);
5541 used_maps_old = prog->aux->used_maps;
5543 for (i = 0; i < prog->aux->used_map_cnt; i++)
5544 if (used_maps_old[i] == map) {
5549 used_maps_new = kmalloc_array(prog->aux->used_map_cnt + 1,
5550 sizeof(used_maps_new[0]),
5552 if (!used_maps_new) {
5557 /* The bpf program will not access the bpf map, but for the sake of
5558 * simplicity, increase sleepable_refcnt for sleepable program as well.
5560 if (prog->sleepable)
5561 atomic64_inc(&map->sleepable_refcnt);
5562 memcpy(used_maps_new, used_maps_old,
5563 sizeof(used_maps_old[0]) * prog->aux->used_map_cnt);
5564 used_maps_new[prog->aux->used_map_cnt] = map;
5566 prog->aux->used_map_cnt++;
5567 prog->aux->used_maps = used_maps_new;
5569 kfree(used_maps_old);
5572 mutex_unlock(&prog->aux->used_maps_mutex);
5581 #define BPF_TOKEN_CREATE_LAST_FIELD token_create.bpffs_fd
5583 static int token_create(union bpf_attr *attr)
5585 if (CHECK_ATTR(BPF_TOKEN_CREATE))
5588 /* no flags are supported yet */
5589 if (attr->token_create.flags)
5592 return bpf_token_create(attr);
5595 static int __sys_bpf(enum bpf_cmd cmd, bpfptr_t uattr, unsigned int size)
5597 union bpf_attr attr;
5600 err = bpf_check_uarg_tail_zero(uattr, sizeof(attr), size);
5603 size = min_t(u32, size, sizeof(attr));
5605 /* copy attributes from user space, may be less than sizeof(bpf_attr) */
5606 memset(&attr, 0, sizeof(attr));
5607 if (copy_from_bpfptr(&attr, uattr, size) != 0)
5610 err = security_bpf(cmd, &attr, size);
5615 case BPF_MAP_CREATE:
5616 err = map_create(&attr);
5618 case BPF_MAP_LOOKUP_ELEM:
5619 err = map_lookup_elem(&attr);
5621 case BPF_MAP_UPDATE_ELEM:
5622 err = map_update_elem(&attr, uattr);
5624 case BPF_MAP_DELETE_ELEM:
5625 err = map_delete_elem(&attr, uattr);
5627 case BPF_MAP_GET_NEXT_KEY:
5628 err = map_get_next_key(&attr);
5630 case BPF_MAP_FREEZE:
5631 err = map_freeze(&attr);
5634 err = bpf_prog_load(&attr, uattr, size);
5637 err = bpf_obj_pin(&attr);
5640 err = bpf_obj_get(&attr);
5642 case BPF_PROG_ATTACH:
5643 err = bpf_prog_attach(&attr);
5645 case BPF_PROG_DETACH:
5646 err = bpf_prog_detach(&attr);
5648 case BPF_PROG_QUERY:
5649 err = bpf_prog_query(&attr, uattr.user);
5651 case BPF_PROG_TEST_RUN:
5652 err = bpf_prog_test_run(&attr, uattr.user);
5654 case BPF_PROG_GET_NEXT_ID:
5655 err = bpf_obj_get_next_id(&attr, uattr.user,
5656 &prog_idr, &prog_idr_lock);
5658 case BPF_MAP_GET_NEXT_ID:
5659 err = bpf_obj_get_next_id(&attr, uattr.user,
5660 &map_idr, &map_idr_lock);
5662 case BPF_BTF_GET_NEXT_ID:
5663 err = bpf_obj_get_next_id(&attr, uattr.user,
5664 &btf_idr, &btf_idr_lock);
5666 case BPF_PROG_GET_FD_BY_ID:
5667 err = bpf_prog_get_fd_by_id(&attr);
5669 case BPF_MAP_GET_FD_BY_ID:
5670 err = bpf_map_get_fd_by_id(&attr);
5672 case BPF_OBJ_GET_INFO_BY_FD:
5673 err = bpf_obj_get_info_by_fd(&attr, uattr.user);
5675 case BPF_RAW_TRACEPOINT_OPEN:
5676 err = bpf_raw_tracepoint_open(&attr);
5679 err = bpf_btf_load(&attr, uattr, size);
5681 case BPF_BTF_GET_FD_BY_ID:
5682 err = bpf_btf_get_fd_by_id(&attr);
5684 case BPF_TASK_FD_QUERY:
5685 err = bpf_task_fd_query(&attr, uattr.user);
5687 case BPF_MAP_LOOKUP_AND_DELETE_ELEM:
5688 err = map_lookup_and_delete_elem(&attr);
5690 case BPF_MAP_LOOKUP_BATCH:
5691 err = bpf_map_do_batch(&attr, uattr.user, BPF_MAP_LOOKUP_BATCH);
5693 case BPF_MAP_LOOKUP_AND_DELETE_BATCH:
5694 err = bpf_map_do_batch(&attr, uattr.user,
5695 BPF_MAP_LOOKUP_AND_DELETE_BATCH);
5697 case BPF_MAP_UPDATE_BATCH:
5698 err = bpf_map_do_batch(&attr, uattr.user, BPF_MAP_UPDATE_BATCH);
5700 case BPF_MAP_DELETE_BATCH:
5701 err = bpf_map_do_batch(&attr, uattr.user, BPF_MAP_DELETE_BATCH);
5703 case BPF_LINK_CREATE:
5704 err = link_create(&attr, uattr);
5706 case BPF_LINK_UPDATE:
5707 err = link_update(&attr);
5709 case BPF_LINK_GET_FD_BY_ID:
5710 err = bpf_link_get_fd_by_id(&attr);
5712 case BPF_LINK_GET_NEXT_ID:
5713 err = bpf_obj_get_next_id(&attr, uattr.user,
5714 &link_idr, &link_idr_lock);
5716 case BPF_ENABLE_STATS:
5717 err = bpf_enable_stats(&attr);
5719 case BPF_ITER_CREATE:
5720 err = bpf_iter_create(&attr);
5722 case BPF_LINK_DETACH:
5723 err = link_detach(&attr);
5725 case BPF_PROG_BIND_MAP:
5726 err = bpf_prog_bind_map(&attr);
5728 case BPF_TOKEN_CREATE:
5729 err = token_create(&attr);
5739 SYSCALL_DEFINE3(bpf, int, cmd, union bpf_attr __user *, uattr, unsigned int, size)
5741 return __sys_bpf(cmd, USER_BPFPTR(uattr), size);
5744 static bool syscall_prog_is_valid_access(int off, int size,
5745 enum bpf_access_type type,
5746 const struct bpf_prog *prog,
5747 struct bpf_insn_access_aux *info)
5749 if (off < 0 || off >= U16_MAX)
5751 if (off % size != 0)
5756 BPF_CALL_3(bpf_sys_bpf, int, cmd, union bpf_attr *, attr, u32, attr_size)
5759 case BPF_MAP_CREATE:
5760 case BPF_MAP_DELETE_ELEM:
5761 case BPF_MAP_UPDATE_ELEM:
5762 case BPF_MAP_FREEZE:
5763 case BPF_MAP_GET_FD_BY_ID:
5766 case BPF_LINK_CREATE:
5767 case BPF_RAW_TRACEPOINT_OPEN:
5772 return __sys_bpf(cmd, KERNEL_BPFPTR(attr), attr_size);
5776 /* To shut up -Wmissing-prototypes.
5777 * This function is used by the kernel light skeleton
5778 * to load bpf programs when modules are loaded or during kernel boot.
5779 * See tools/lib/bpf/skel_internal.h
5781 int kern_sys_bpf(int cmd, union bpf_attr *attr, unsigned int size);
5783 int kern_sys_bpf(int cmd, union bpf_attr *attr, unsigned int size)
5785 struct bpf_prog * __maybe_unused prog;
5786 struct bpf_tramp_run_ctx __maybe_unused run_ctx;
5789 #ifdef CONFIG_BPF_JIT /* __bpf_prog_enter_sleepable used by trampoline and JIT */
5790 case BPF_PROG_TEST_RUN:
5791 if (attr->test.data_in || attr->test.data_out ||
5792 attr->test.ctx_out || attr->test.duration ||
5793 attr->test.repeat || attr->test.flags)
5796 prog = bpf_prog_get_type(attr->test.prog_fd, BPF_PROG_TYPE_SYSCALL);
5798 return PTR_ERR(prog);
5800 if (attr->test.ctx_size_in < prog->aux->max_ctx_offset ||
5801 attr->test.ctx_size_in > U16_MAX) {
5806 run_ctx.bpf_cookie = 0;
5807 if (!__bpf_prog_enter_sleepable_recur(prog, &run_ctx)) {
5808 /* recursion detected */
5809 __bpf_prog_exit_sleepable_recur(prog, 0, &run_ctx);
5813 attr->test.retval = bpf_prog_run(prog, (void *) (long) attr->test.ctx_in);
5814 __bpf_prog_exit_sleepable_recur(prog, 0 /* bpf_prog_run does runtime stats */,
5820 return ____bpf_sys_bpf(cmd, attr, size);
5823 EXPORT_SYMBOL(kern_sys_bpf);
5825 static const struct bpf_func_proto bpf_sys_bpf_proto = {
5826 .func = bpf_sys_bpf,
5828 .ret_type = RET_INTEGER,
5829 .arg1_type = ARG_ANYTHING,
5830 .arg2_type = ARG_PTR_TO_MEM | MEM_RDONLY,
5831 .arg3_type = ARG_CONST_SIZE,
5834 const struct bpf_func_proto * __weak
5835 tracing_prog_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
5837 return bpf_base_func_proto(func_id, prog);
5840 BPF_CALL_1(bpf_sys_close, u32, fd)
5842 /* When bpf program calls this helper there should not be
5843 * an fdget() without matching completed fdput().
5844 * This helper is allowed in the following callchain only:
5845 * sys_bpf->prog_test_run->bpf_prog->bpf_sys_close
5847 return close_fd(fd);
5850 static const struct bpf_func_proto bpf_sys_close_proto = {
5851 .func = bpf_sys_close,
5853 .ret_type = RET_INTEGER,
5854 .arg1_type = ARG_ANYTHING,
5857 BPF_CALL_4(bpf_kallsyms_lookup_name, const char *, name, int, name_sz, int, flags, u64 *, res)
5863 if (name_sz <= 1 || name[name_sz - 1])
5866 if (!bpf_dump_raw_ok(current_cred()))
5869 *res = kallsyms_lookup_name(name);
5870 return *res ? 0 : -ENOENT;
5873 static const struct bpf_func_proto bpf_kallsyms_lookup_name_proto = {
5874 .func = bpf_kallsyms_lookup_name,
5876 .ret_type = RET_INTEGER,
5877 .arg1_type = ARG_PTR_TO_MEM,
5878 .arg2_type = ARG_CONST_SIZE_OR_ZERO,
5879 .arg3_type = ARG_ANYTHING,
5880 .arg4_type = ARG_PTR_TO_FIXED_SIZE_MEM | MEM_UNINIT | MEM_ALIGNED,
5881 .arg4_size = sizeof(u64),
5884 static const struct bpf_func_proto *
5885 syscall_prog_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
5888 case BPF_FUNC_sys_bpf:
5889 return !bpf_token_capable(prog->aux->token, CAP_PERFMON)
5890 ? NULL : &bpf_sys_bpf_proto;
5891 case BPF_FUNC_btf_find_by_name_kind:
5892 return &bpf_btf_find_by_name_kind_proto;
5893 case BPF_FUNC_sys_close:
5894 return &bpf_sys_close_proto;
5895 case BPF_FUNC_kallsyms_lookup_name:
5896 return &bpf_kallsyms_lookup_name_proto;
5898 return tracing_prog_func_proto(func_id, prog);
5902 const struct bpf_verifier_ops bpf_syscall_verifier_ops = {
5903 .get_func_proto = syscall_prog_func_proto,
5904 .is_valid_access = syscall_prog_is_valid_access,
5907 const struct bpf_prog_ops bpf_syscall_prog_ops = {
5908 .test_run = bpf_prog_test_run_syscall,
5911 #ifdef CONFIG_SYSCTL
5912 static int bpf_stats_handler(const struct ctl_table *table, int write,
5913 void *buffer, size_t *lenp, loff_t *ppos)
5915 struct static_key *key = (struct static_key *)table->data;
5916 static int saved_val;
5918 struct ctl_table tmp = {
5920 .maxlen = sizeof(val),
5921 .mode = table->mode,
5922 .extra1 = SYSCTL_ZERO,
5923 .extra2 = SYSCTL_ONE,
5926 if (write && !capable(CAP_SYS_ADMIN))
5929 mutex_lock(&bpf_stats_enabled_mutex);
5931 ret = proc_dointvec_minmax(&tmp, write, buffer, lenp, ppos);
5932 if (write && !ret && val != saved_val) {
5934 static_key_slow_inc(key);
5936 static_key_slow_dec(key);
5939 mutex_unlock(&bpf_stats_enabled_mutex);
5943 void __weak unpriv_ebpf_notify(int new_state)
5947 static int bpf_unpriv_handler(const struct ctl_table *table, int write,
5948 void *buffer, size_t *lenp, loff_t *ppos)
5950 int ret, unpriv_enable = *(int *)table->data;
5951 bool locked_state = unpriv_enable == 1;
5952 struct ctl_table tmp = *table;
5954 if (write && !capable(CAP_SYS_ADMIN))
5957 tmp.data = &unpriv_enable;
5958 ret = proc_dointvec_minmax(&tmp, write, buffer, lenp, ppos);
5959 if (write && !ret) {
5960 if (locked_state && unpriv_enable != 1)
5962 *(int *)table->data = unpriv_enable;
5966 unpriv_ebpf_notify(unpriv_enable);
5971 static struct ctl_table bpf_syscall_table[] = {
5973 .procname = "unprivileged_bpf_disabled",
5974 .data = &sysctl_unprivileged_bpf_disabled,
5975 .maxlen = sizeof(sysctl_unprivileged_bpf_disabled),
5977 .proc_handler = bpf_unpriv_handler,
5978 .extra1 = SYSCTL_ZERO,
5979 .extra2 = SYSCTL_TWO,
5982 .procname = "bpf_stats_enabled",
5983 .data = &bpf_stats_enabled_key.key,
5985 .proc_handler = bpf_stats_handler,
5989 static int __init bpf_syscall_sysctl_init(void)
5991 register_sysctl_init("kernel", bpf_syscall_table);
5994 late_initcall(bpf_syscall_sysctl_init);
5995 #endif /* CONFIG_SYSCTL */