1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
5 #include <linux/bpf-cgroup.h>
6 #include <linux/bpf_trace.h>
7 #include <linux/bpf_lirc.h>
8 #include <linux/bpf_verifier.h>
9 #include <linux/bsearch.h>
10 #include <linux/btf.h>
11 #include <linux/syscalls.h>
12 #include <linux/slab.h>
13 #include <linux/sched/signal.h>
14 #include <linux/vmalloc.h>
15 #include <linux/mmzone.h>
16 #include <linux/anon_inodes.h>
17 #include <linux/fdtable.h>
18 #include <linux/file.h>
20 #include <linux/license.h>
21 #include <linux/filter.h>
22 #include <linux/kernel.h>
23 #include <linux/idr.h>
24 #include <linux/cred.h>
25 #include <linux/timekeeping.h>
26 #include <linux/ctype.h>
27 #include <linux/nospec.h>
28 #include <linux/audit.h>
29 #include <uapi/linux/btf.h>
30 #include <linux/pgtable.h>
31 #include <linux/bpf_lsm.h>
32 #include <linux/poll.h>
33 #include <linux/sort.h>
34 #include <linux/bpf-netns.h>
35 #include <linux/rcupdate_trace.h>
36 #include <linux/memcontrol.h>
37 #include <linux/trace_events.h>
38 #include <linux/tracepoint.h>
40 #include <net/netfilter/nf_bpf_link.h>
41 #include <net/netkit.h>
44 #define IS_FD_ARRAY(map) ((map)->map_type == BPF_MAP_TYPE_PERF_EVENT_ARRAY || \
45 (map)->map_type == BPF_MAP_TYPE_CGROUP_ARRAY || \
46 (map)->map_type == BPF_MAP_TYPE_ARRAY_OF_MAPS)
47 #define IS_FD_PROG_ARRAY(map) ((map)->map_type == BPF_MAP_TYPE_PROG_ARRAY)
48 #define IS_FD_HASH(map) ((map)->map_type == BPF_MAP_TYPE_HASH_OF_MAPS)
49 #define IS_FD_MAP(map) (IS_FD_ARRAY(map) || IS_FD_PROG_ARRAY(map) || \
52 #define BPF_OBJ_FLAG_MASK (BPF_F_RDONLY | BPF_F_WRONLY)
54 DEFINE_PER_CPU(int, bpf_prog_active);
55 static DEFINE_IDR(prog_idr);
56 static DEFINE_SPINLOCK(prog_idr_lock);
57 static DEFINE_IDR(map_idr);
58 static DEFINE_SPINLOCK(map_idr_lock);
59 static DEFINE_IDR(link_idr);
60 static DEFINE_SPINLOCK(link_idr_lock);
62 int sysctl_unprivileged_bpf_disabled __read_mostly =
63 IS_BUILTIN(CONFIG_BPF_UNPRIV_DEFAULT_OFF) ? 2 : 0;
65 static const struct bpf_map_ops * const bpf_map_types[] = {
66 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type)
67 #define BPF_MAP_TYPE(_id, _ops) \
69 #define BPF_LINK_TYPE(_id, _name)
70 #include <linux/bpf_types.h>
77 * If we're handed a bigger struct than we know of, ensure all the unknown bits
78 * are 0 - i.e. new user-space does not rely on any kernel feature extensions
79 * we don't know about yet.
81 * There is a ToCToU between this function call and the following
82 * copy_from_user() call. However, this is not a concern since this function is
83 * meant to be a future-proofing of bits.
85 int bpf_check_uarg_tail_zero(bpfptr_t uaddr,
91 if (unlikely(actual_size > PAGE_SIZE)) /* silly large */
94 if (actual_size <= expected_size)
98 res = memchr_inv(uaddr.kernel + expected_size, 0,
99 actual_size - expected_size) == NULL;
101 res = check_zeroed_user(uaddr.user + expected_size,
102 actual_size - expected_size);
105 return res ? 0 : -E2BIG;
108 const struct bpf_map_ops bpf_map_offload_ops = {
109 .map_meta_equal = bpf_map_meta_equal,
110 .map_alloc = bpf_map_offload_map_alloc,
111 .map_free = bpf_map_offload_map_free,
112 .map_check_btf = map_check_no_btf,
113 .map_mem_usage = bpf_map_offload_map_mem_usage,
116 static void bpf_map_write_active_inc(struct bpf_map *map)
118 atomic64_inc(&map->writecnt);
121 static void bpf_map_write_active_dec(struct bpf_map *map)
123 atomic64_dec(&map->writecnt);
126 bool bpf_map_write_active(const struct bpf_map *map)
128 return atomic64_read(&map->writecnt) != 0;
131 static u32 bpf_map_value_size(const struct bpf_map *map)
133 if (map->map_type == BPF_MAP_TYPE_PERCPU_HASH ||
134 map->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH ||
135 map->map_type == BPF_MAP_TYPE_PERCPU_ARRAY ||
136 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
137 return round_up(map->value_size, 8) * num_possible_cpus();
138 else if (IS_FD_MAP(map))
141 return map->value_size;
144 static void maybe_wait_bpf_programs(struct bpf_map *map)
146 /* Wait for any running non-sleepable BPF programs to complete so that
147 * userspace, when we return to it, knows that all non-sleepable
148 * programs that could be running use the new map value. For sleepable
149 * BPF programs, synchronize_rcu_tasks_trace() should be used to wait
150 * for the completions of these programs, but considering the waiting
151 * time can be very long and userspace may think it will hang forever,
152 * so don't handle sleepable BPF programs now.
154 if (map->map_type == BPF_MAP_TYPE_HASH_OF_MAPS ||
155 map->map_type == BPF_MAP_TYPE_ARRAY_OF_MAPS)
159 static void unpin_uptr_kaddr(void *kaddr)
162 unpin_user_page(virt_to_page(kaddr));
165 static void __bpf_obj_unpin_uptrs(struct btf_record *rec, u32 cnt, void *obj)
167 const struct btf_field *field;
171 for (i = 0, field = rec->fields; i < cnt; i++, field++) {
172 if (field->type != BPF_UPTR)
175 uptr_addr = obj + field->offset;
176 unpin_uptr_kaddr(*uptr_addr);
180 static void bpf_obj_unpin_uptrs(struct btf_record *rec, void *obj)
182 if (!btf_record_has_field(rec, BPF_UPTR))
185 __bpf_obj_unpin_uptrs(rec, rec->cnt, obj);
188 static int bpf_obj_pin_uptrs(struct btf_record *rec, void *obj)
190 const struct btf_field *field;
191 const struct btf_type *t;
192 unsigned long start, end;
197 if (!btf_record_has_field(rec, BPF_UPTR))
200 for (i = 0, field = rec->fields; i < rec->cnt; i++, field++) {
201 if (field->type != BPF_UPTR)
204 uptr_addr = obj + field->offset;
205 start = *(unsigned long *)uptr_addr;
209 t = btf_type_by_id(field->kptr.btf, field->kptr.btf_id);
210 /* t->size was checked for zero before */
211 if (check_add_overflow(start, t->size - 1, &end)) {
216 /* The uptr's struct cannot span across two pages */
217 if ((start & PAGE_MASK) != (end & PAGE_MASK)) {
222 err = pin_user_pages_fast(start, 1, FOLL_LONGTERM | FOLL_WRITE, &page);
226 if (PageHighMem(page)) {
228 unpin_user_page(page);
232 *uptr_addr = page_address(page) + offset_in_page(start);
238 __bpf_obj_unpin_uptrs(rec, i, obj);
242 static int bpf_map_update_value(struct bpf_map *map, struct file *map_file,
243 void *key, void *value, __u64 flags)
247 /* Need to create a kthread, thus must support schedule */
248 if (bpf_map_is_offloaded(map)) {
249 return bpf_map_offload_update_elem(map, key, value, flags);
250 } else if (map->map_type == BPF_MAP_TYPE_CPUMAP ||
251 map->map_type == BPF_MAP_TYPE_ARENA ||
252 map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
253 return map->ops->map_update_elem(map, key, value, flags);
254 } else if (map->map_type == BPF_MAP_TYPE_SOCKHASH ||
255 map->map_type == BPF_MAP_TYPE_SOCKMAP) {
256 return sock_map_update_elem_sys(map, key, value, flags);
257 } else if (IS_FD_PROG_ARRAY(map)) {
258 return bpf_fd_array_map_update_elem(map, map_file, key, value,
262 bpf_disable_instrumentation();
263 if (map->map_type == BPF_MAP_TYPE_PERCPU_HASH ||
264 map->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH) {
265 err = bpf_percpu_hash_update(map, key, value, flags);
266 } else if (map->map_type == BPF_MAP_TYPE_PERCPU_ARRAY) {
267 err = bpf_percpu_array_update(map, key, value, flags);
268 } else if (map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE) {
269 err = bpf_percpu_cgroup_storage_update(map, key, value,
271 } else if (IS_FD_ARRAY(map)) {
272 err = bpf_fd_array_map_update_elem(map, map_file, key, value,
274 } else if (map->map_type == BPF_MAP_TYPE_HASH_OF_MAPS) {
275 err = bpf_fd_htab_map_update_elem(map, map_file, key, value,
277 } else if (map->map_type == BPF_MAP_TYPE_REUSEPORT_SOCKARRAY) {
278 /* rcu_read_lock() is not needed */
279 err = bpf_fd_reuseport_array_update_elem(map, key, value,
281 } else if (map->map_type == BPF_MAP_TYPE_QUEUE ||
282 map->map_type == BPF_MAP_TYPE_STACK ||
283 map->map_type == BPF_MAP_TYPE_BLOOM_FILTER) {
284 err = map->ops->map_push_elem(map, value, flags);
286 err = bpf_obj_pin_uptrs(map->record, value);
289 err = map->ops->map_update_elem(map, key, value, flags);
292 bpf_obj_unpin_uptrs(map->record, value);
295 bpf_enable_instrumentation();
300 static int bpf_map_copy_value(struct bpf_map *map, void *key, void *value,
306 if (bpf_map_is_offloaded(map))
307 return bpf_map_offload_lookup_elem(map, key, value);
309 bpf_disable_instrumentation();
310 if (map->map_type == BPF_MAP_TYPE_PERCPU_HASH ||
311 map->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH) {
312 err = bpf_percpu_hash_copy(map, key, value);
313 } else if (map->map_type == BPF_MAP_TYPE_PERCPU_ARRAY) {
314 err = bpf_percpu_array_copy(map, key, value);
315 } else if (map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE) {
316 err = bpf_percpu_cgroup_storage_copy(map, key, value);
317 } else if (map->map_type == BPF_MAP_TYPE_STACK_TRACE) {
318 err = bpf_stackmap_copy(map, key, value);
319 } else if (IS_FD_ARRAY(map) || IS_FD_PROG_ARRAY(map)) {
320 err = bpf_fd_array_map_lookup_elem(map, key, value);
321 } else if (IS_FD_HASH(map)) {
322 err = bpf_fd_htab_map_lookup_elem(map, key, value);
323 } else if (map->map_type == BPF_MAP_TYPE_REUSEPORT_SOCKARRAY) {
324 err = bpf_fd_reuseport_array_lookup_elem(map, key, value);
325 } else if (map->map_type == BPF_MAP_TYPE_QUEUE ||
326 map->map_type == BPF_MAP_TYPE_STACK ||
327 map->map_type == BPF_MAP_TYPE_BLOOM_FILTER) {
328 err = map->ops->map_peek_elem(map, value);
329 } else if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
330 /* struct_ops map requires directly updating "value" */
331 err = bpf_struct_ops_map_sys_lookup_elem(map, key, value);
334 if (map->ops->map_lookup_elem_sys_only)
335 ptr = map->ops->map_lookup_elem_sys_only(map, key);
337 ptr = map->ops->map_lookup_elem(map, key);
344 if (flags & BPF_F_LOCK)
345 /* lock 'ptr' and copy everything but lock */
346 copy_map_value_locked(map, value, ptr, true);
348 copy_map_value(map, value, ptr);
349 /* mask lock and timer, since value wasn't zero inited */
350 check_and_init_map_value(map, value);
355 bpf_enable_instrumentation();
360 /* Please, do not use this function outside from the map creation path
361 * (e.g. in map update path) without taking care of setting the active
362 * memory cgroup (see at bpf_map_kmalloc_node() for example).
364 static void *__bpf_map_area_alloc(u64 size, int numa_node, bool mmapable)
366 /* We really just want to fail instead of triggering OOM killer
367 * under memory pressure, therefore we set __GFP_NORETRY to kmalloc,
368 * which is used for lower order allocation requests.
370 * It has been observed that higher order allocation requests done by
371 * vmalloc with __GFP_NORETRY being set might fail due to not trying
372 * to reclaim memory from the page cache, thus we set
373 * __GFP_RETRY_MAYFAIL to avoid such situations.
376 gfp_t gfp = bpf_memcg_flags(__GFP_NOWARN | __GFP_ZERO);
377 unsigned int flags = 0;
378 unsigned long align = 1;
381 if (size >= SIZE_MAX)
384 /* kmalloc()'ed memory can't be mmap()'ed */
386 BUG_ON(!PAGE_ALIGNED(size));
389 } else if (size <= (PAGE_SIZE << PAGE_ALLOC_COSTLY_ORDER)) {
390 area = kmalloc_node(size, gfp | GFP_USER | __GFP_NORETRY,
396 return __vmalloc_node_range(size, align, VMALLOC_START, VMALLOC_END,
397 gfp | GFP_KERNEL | __GFP_RETRY_MAYFAIL, PAGE_KERNEL,
398 flags, numa_node, __builtin_return_address(0));
401 void *bpf_map_area_alloc(u64 size, int numa_node)
403 return __bpf_map_area_alloc(size, numa_node, false);
406 void *bpf_map_area_mmapable_alloc(u64 size, int numa_node)
408 return __bpf_map_area_alloc(size, numa_node, true);
411 void bpf_map_area_free(void *area)
416 static u32 bpf_map_flags_retain_permanent(u32 flags)
418 /* Some map creation flags are not tied to the map object but
419 * rather to the map fd instead, so they have no meaning upon
420 * map object inspection since multiple file descriptors with
421 * different (access) properties can exist here. Thus, given
422 * this has zero meaning for the map itself, lets clear these
425 return flags & ~(BPF_F_RDONLY | BPF_F_WRONLY);
428 void bpf_map_init_from_attr(struct bpf_map *map, union bpf_attr *attr)
430 map->map_type = attr->map_type;
431 map->key_size = attr->key_size;
432 map->value_size = attr->value_size;
433 map->max_entries = attr->max_entries;
434 map->map_flags = bpf_map_flags_retain_permanent(attr->map_flags);
435 map->numa_node = bpf_map_attr_numa_node(attr);
436 map->map_extra = attr->map_extra;
439 static int bpf_map_alloc_id(struct bpf_map *map)
443 idr_preload(GFP_KERNEL);
444 spin_lock_bh(&map_idr_lock);
445 id = idr_alloc_cyclic(&map_idr, map, 1, INT_MAX, GFP_ATOMIC);
448 spin_unlock_bh(&map_idr_lock);
451 if (WARN_ON_ONCE(!id))
454 return id > 0 ? 0 : id;
457 void bpf_map_free_id(struct bpf_map *map)
461 /* Offloaded maps are removed from the IDR store when their device
462 * disappears - even if someone holds an fd to them they are unusable,
463 * the memory is gone, all ops will fail; they are simply waiting for
464 * refcnt to drop to be freed.
469 spin_lock_irqsave(&map_idr_lock, flags);
471 idr_remove(&map_idr, map->id);
474 spin_unlock_irqrestore(&map_idr_lock, flags);
478 static void bpf_map_save_memcg(struct bpf_map *map)
480 /* Currently if a map is created by a process belonging to the root
481 * memory cgroup, get_obj_cgroup_from_current() will return NULL.
482 * So we have to check map->objcg for being NULL each time it's
485 if (memcg_bpf_enabled())
486 map->objcg = get_obj_cgroup_from_current();
489 static void bpf_map_release_memcg(struct bpf_map *map)
492 obj_cgroup_put(map->objcg);
495 static struct mem_cgroup *bpf_map_get_memcg(const struct bpf_map *map)
498 return get_mem_cgroup_from_objcg(map->objcg);
500 return root_mem_cgroup;
503 void *bpf_map_kmalloc_node(const struct bpf_map *map, size_t size, gfp_t flags,
506 struct mem_cgroup *memcg, *old_memcg;
509 memcg = bpf_map_get_memcg(map);
510 old_memcg = set_active_memcg(memcg);
511 ptr = kmalloc_node(size, flags | __GFP_ACCOUNT, node);
512 set_active_memcg(old_memcg);
513 mem_cgroup_put(memcg);
518 void *bpf_map_kzalloc(const struct bpf_map *map, size_t size, gfp_t flags)
520 struct mem_cgroup *memcg, *old_memcg;
523 memcg = bpf_map_get_memcg(map);
524 old_memcg = set_active_memcg(memcg);
525 ptr = kzalloc(size, flags | __GFP_ACCOUNT);
526 set_active_memcg(old_memcg);
527 mem_cgroup_put(memcg);
532 void *bpf_map_kvcalloc(struct bpf_map *map, size_t n, size_t size,
535 struct mem_cgroup *memcg, *old_memcg;
538 memcg = bpf_map_get_memcg(map);
539 old_memcg = set_active_memcg(memcg);
540 ptr = kvcalloc(n, size, flags | __GFP_ACCOUNT);
541 set_active_memcg(old_memcg);
542 mem_cgroup_put(memcg);
547 void __percpu *bpf_map_alloc_percpu(const struct bpf_map *map, size_t size,
548 size_t align, gfp_t flags)
550 struct mem_cgroup *memcg, *old_memcg;
553 memcg = bpf_map_get_memcg(map);
554 old_memcg = set_active_memcg(memcg);
555 ptr = __alloc_percpu_gfp(size, align, flags | __GFP_ACCOUNT);
556 set_active_memcg(old_memcg);
557 mem_cgroup_put(memcg);
563 static void bpf_map_save_memcg(struct bpf_map *map)
567 static void bpf_map_release_memcg(struct bpf_map *map)
572 int bpf_map_alloc_pages(const struct bpf_map *map, gfp_t gfp, int nid,
573 unsigned long nr_pages, struct page **pages)
579 struct mem_cgroup *memcg, *old_memcg;
581 memcg = bpf_map_get_memcg(map);
582 old_memcg = set_active_memcg(memcg);
584 for (i = 0; i < nr_pages; i++) {
585 pg = alloc_pages_node(nid, gfp | __GFP_ACCOUNT, 0);
591 for (j = 0; j < i; j++)
592 __free_page(pages[j]);
598 set_active_memcg(old_memcg);
599 mem_cgroup_put(memcg);
605 static int btf_field_cmp(const void *a, const void *b)
607 const struct btf_field *f1 = a, *f2 = b;
609 if (f1->offset < f2->offset)
611 else if (f1->offset > f2->offset)
616 struct btf_field *btf_record_find(const struct btf_record *rec, u32 offset,
619 struct btf_field *field;
621 if (IS_ERR_OR_NULL(rec) || !(rec->field_mask & field_mask))
623 field = bsearch(&offset, rec->fields, rec->cnt, sizeof(rec->fields[0]), btf_field_cmp);
624 if (!field || !(field->type & field_mask))
629 void btf_record_free(struct btf_record *rec)
633 if (IS_ERR_OR_NULL(rec))
635 for (i = 0; i < rec->cnt; i++) {
636 switch (rec->fields[i].type) {
639 case BPF_KPTR_PERCPU:
641 if (rec->fields[i].kptr.module)
642 module_put(rec->fields[i].kptr.module);
643 if (btf_is_kernel(rec->fields[i].kptr.btf))
644 btf_put(rec->fields[i].kptr.btf);
654 /* Nothing to release */
664 void bpf_map_free_record(struct bpf_map *map)
666 btf_record_free(map->record);
670 struct btf_record *btf_record_dup(const struct btf_record *rec)
672 const struct btf_field *fields;
673 struct btf_record *new_rec;
676 if (IS_ERR_OR_NULL(rec))
678 size = offsetof(struct btf_record, fields[rec->cnt]);
679 new_rec = kmemdup(rec, size, GFP_KERNEL | __GFP_NOWARN);
681 return ERR_PTR(-ENOMEM);
682 /* Do a deep copy of the btf_record */
683 fields = rec->fields;
685 for (i = 0; i < rec->cnt; i++) {
686 switch (fields[i].type) {
689 case BPF_KPTR_PERCPU:
691 if (btf_is_kernel(fields[i].kptr.btf))
692 btf_get(fields[i].kptr.btf);
693 if (fields[i].kptr.module && !try_module_get(fields[i].kptr.module)) {
706 /* Nothing to acquire */
717 btf_record_free(new_rec);
721 bool btf_record_equal(const struct btf_record *rec_a, const struct btf_record *rec_b)
723 bool a_has_fields = !IS_ERR_OR_NULL(rec_a), b_has_fields = !IS_ERR_OR_NULL(rec_b);
726 if (!a_has_fields && !b_has_fields)
728 if (a_has_fields != b_has_fields)
730 if (rec_a->cnt != rec_b->cnt)
732 size = offsetof(struct btf_record, fields[rec_a->cnt]);
733 /* btf_parse_fields uses kzalloc to allocate a btf_record, so unused
734 * members are zeroed out. So memcmp is safe to do without worrying
735 * about padding/unused fields.
737 * While spin_lock, timer, and kptr have no relation to map BTF,
738 * list_head metadata is specific to map BTF, the btf and value_rec
739 * members in particular. btf is the map BTF, while value_rec points to
740 * btf_record in that map BTF.
742 * So while by default, we don't rely on the map BTF (which the records
743 * were parsed from) matching for both records, which is not backwards
744 * compatible, in case list_head is part of it, we implicitly rely on
745 * that by way of depending on memcmp succeeding for it.
747 return !memcmp(rec_a, rec_b, size);
750 void bpf_obj_free_timer(const struct btf_record *rec, void *obj)
752 if (WARN_ON_ONCE(!btf_record_has_field(rec, BPF_TIMER)))
754 bpf_timer_cancel_and_free(obj + rec->timer_off);
757 void bpf_obj_free_workqueue(const struct btf_record *rec, void *obj)
759 if (WARN_ON_ONCE(!btf_record_has_field(rec, BPF_WORKQUEUE)))
761 bpf_wq_cancel_and_free(obj + rec->wq_off);
764 void bpf_obj_free_fields(const struct btf_record *rec, void *obj)
766 const struct btf_field *fields;
769 if (IS_ERR_OR_NULL(rec))
771 fields = rec->fields;
772 for (i = 0; i < rec->cnt; i++) {
773 struct btf_struct_meta *pointee_struct_meta;
774 const struct btf_field *field = &fields[i];
775 void *field_ptr = obj + field->offset;
778 switch (fields[i].type) {
782 bpf_timer_cancel_and_free(field_ptr);
785 bpf_wq_cancel_and_free(field_ptr);
788 WRITE_ONCE(*(u64 *)field_ptr, 0);
791 case BPF_KPTR_PERCPU:
792 xchgd_field = (void *)xchg((unsigned long *)field_ptr, 0);
796 if (!btf_is_kernel(field->kptr.btf)) {
797 pointee_struct_meta = btf_find_struct_meta(field->kptr.btf,
800 __bpf_obj_drop_impl(xchgd_field, pointee_struct_meta ?
801 pointee_struct_meta->record : NULL,
802 fields[i].type == BPF_KPTR_PERCPU);
805 field->kptr.dtor(xchgd_field);
809 /* The caller ensured that no one is using the uptr */
810 unpin_uptr_kaddr(*(void **)field_ptr);
813 if (WARN_ON_ONCE(rec->spin_lock_off < 0))
815 bpf_list_head_free(field, field_ptr, obj + rec->spin_lock_off);
818 if (WARN_ON_ONCE(rec->spin_lock_off < 0))
820 bpf_rb_root_free(field, field_ptr, obj + rec->spin_lock_off);
833 static void bpf_map_free(struct bpf_map *map)
835 struct btf_record *rec = map->record;
836 struct btf *btf = map->btf;
838 /* implementation dependent freeing */
839 map->ops->map_free(map);
840 /* Delay freeing of btf_record for maps, as map_free
841 * callback usually needs access to them. It is better to do it here
842 * than require each callback to do the free itself manually.
844 * Note that the btf_record stashed in map->inner_map_meta->record was
845 * already freed using the map_free callback for map in map case which
846 * eventually calls bpf_map_free_meta, since inner_map_meta is only a
847 * template bpf_map struct used during verification.
849 btf_record_free(rec);
850 /* Delay freeing of btf for maps, as map_free callback may need
851 * struct_meta info which will be freed with btf_put().
856 /* called from workqueue */
857 static void bpf_map_free_deferred(struct work_struct *work)
859 struct bpf_map *map = container_of(work, struct bpf_map, work);
861 security_bpf_map_free(map);
862 bpf_map_release_memcg(map);
866 static void bpf_map_put_uref(struct bpf_map *map)
868 if (atomic64_dec_and_test(&map->usercnt)) {
869 if (map->ops->map_release_uref)
870 map->ops->map_release_uref(map);
874 static void bpf_map_free_in_work(struct bpf_map *map)
876 INIT_WORK(&map->work, bpf_map_free_deferred);
877 /* Avoid spawning kworkers, since they all might contend
878 * for the same mutex like slab_mutex.
880 queue_work(system_unbound_wq, &map->work);
883 static void bpf_map_free_rcu_gp(struct rcu_head *rcu)
885 bpf_map_free_in_work(container_of(rcu, struct bpf_map, rcu));
888 static void bpf_map_free_mult_rcu_gp(struct rcu_head *rcu)
890 if (rcu_trace_implies_rcu_gp())
891 bpf_map_free_rcu_gp(rcu);
893 call_rcu(rcu, bpf_map_free_rcu_gp);
896 /* decrement map refcnt and schedule it for freeing via workqueue
897 * (underlying map implementation ops->map_free() might sleep)
899 void bpf_map_put(struct bpf_map *map)
901 if (atomic64_dec_and_test(&map->refcnt)) {
902 /* bpf_map_free_id() must be called first */
903 bpf_map_free_id(map);
905 WARN_ON_ONCE(atomic64_read(&map->sleepable_refcnt));
906 if (READ_ONCE(map->free_after_mult_rcu_gp))
907 call_rcu_tasks_trace(&map->rcu, bpf_map_free_mult_rcu_gp);
908 else if (READ_ONCE(map->free_after_rcu_gp))
909 call_rcu(&map->rcu, bpf_map_free_rcu_gp);
911 bpf_map_free_in_work(map);
914 EXPORT_SYMBOL_GPL(bpf_map_put);
916 void bpf_map_put_with_uref(struct bpf_map *map)
918 bpf_map_put_uref(map);
922 static int bpf_map_release(struct inode *inode, struct file *filp)
924 struct bpf_map *map = filp->private_data;
926 if (map->ops->map_release)
927 map->ops->map_release(map, filp);
929 bpf_map_put_with_uref(map);
933 static fmode_t map_get_sys_perms(struct bpf_map *map, struct fd f)
935 fmode_t mode = fd_file(f)->f_mode;
937 /* Our file permissions may have been overridden by global
938 * map permissions facing syscall side.
940 if (READ_ONCE(map->frozen))
941 mode &= ~FMODE_CAN_WRITE;
945 #ifdef CONFIG_PROC_FS
946 /* Show the memory usage of a bpf map */
947 static u64 bpf_map_memory_usage(const struct bpf_map *map)
949 return map->ops->map_mem_usage(map);
952 static void bpf_map_show_fdinfo(struct seq_file *m, struct file *filp)
954 struct bpf_map *map = filp->private_data;
955 u32 type = 0, jited = 0;
957 if (map_type_contains_progs(map)) {
958 spin_lock(&map->owner.lock);
959 type = map->owner.type;
960 jited = map->owner.jited;
961 spin_unlock(&map->owner.lock);
970 "map_extra:\t%#llx\n"
979 (unsigned long long)map->map_extra,
980 bpf_map_memory_usage(map),
982 READ_ONCE(map->frozen));
984 seq_printf(m, "owner_prog_type:\t%u\n", type);
985 seq_printf(m, "owner_jited:\t%u\n", jited);
990 static ssize_t bpf_dummy_read(struct file *filp, char __user *buf, size_t siz,
993 /* We need this handler such that alloc_file() enables
994 * f_mode with FMODE_CAN_READ.
999 static ssize_t bpf_dummy_write(struct file *filp, const char __user *buf,
1000 size_t siz, loff_t *ppos)
1002 /* We need this handler such that alloc_file() enables
1003 * f_mode with FMODE_CAN_WRITE.
1008 /* called for any extra memory-mapped regions (except initial) */
1009 static void bpf_map_mmap_open(struct vm_area_struct *vma)
1011 struct bpf_map *map = vma->vm_file->private_data;
1013 if (vma->vm_flags & VM_MAYWRITE)
1014 bpf_map_write_active_inc(map);
1017 /* called for all unmapped memory region (including initial) */
1018 static void bpf_map_mmap_close(struct vm_area_struct *vma)
1020 struct bpf_map *map = vma->vm_file->private_data;
1022 if (vma->vm_flags & VM_MAYWRITE)
1023 bpf_map_write_active_dec(map);
1026 static const struct vm_operations_struct bpf_map_default_vmops = {
1027 .open = bpf_map_mmap_open,
1028 .close = bpf_map_mmap_close,
1031 static int bpf_map_mmap(struct file *filp, struct vm_area_struct *vma)
1033 struct bpf_map *map = filp->private_data;
1036 if (!map->ops->map_mmap || !IS_ERR_OR_NULL(map->record))
1039 if (!(vma->vm_flags & VM_SHARED))
1042 mutex_lock(&map->freeze_mutex);
1044 if (vma->vm_flags & VM_WRITE) {
1049 /* map is meant to be read-only, so do not allow mapping as
1050 * writable, because it's possible to leak a writable page
1051 * reference and allows user-space to still modify it after
1052 * freezing, while verifier will assume contents do not change
1054 if (map->map_flags & BPF_F_RDONLY_PROG) {
1060 /* set default open/close callbacks */
1061 vma->vm_ops = &bpf_map_default_vmops;
1062 vma->vm_private_data = map;
1063 vm_flags_clear(vma, VM_MAYEXEC);
1064 if (!(vma->vm_flags & VM_WRITE))
1065 /* disallow re-mapping with PROT_WRITE */
1066 vm_flags_clear(vma, VM_MAYWRITE);
1068 err = map->ops->map_mmap(map, vma);
1072 if (vma->vm_flags & VM_MAYWRITE)
1073 bpf_map_write_active_inc(map);
1075 mutex_unlock(&map->freeze_mutex);
1079 static __poll_t bpf_map_poll(struct file *filp, struct poll_table_struct *pts)
1081 struct bpf_map *map = filp->private_data;
1083 if (map->ops->map_poll)
1084 return map->ops->map_poll(map, filp, pts);
1089 static unsigned long bpf_get_unmapped_area(struct file *filp, unsigned long addr,
1090 unsigned long len, unsigned long pgoff,
1091 unsigned long flags)
1093 struct bpf_map *map = filp->private_data;
1095 if (map->ops->map_get_unmapped_area)
1096 return map->ops->map_get_unmapped_area(filp, addr, len, pgoff, flags);
1098 return mm_get_unmapped_area(current->mm, filp, addr, len, pgoff, flags);
1104 const struct file_operations bpf_map_fops = {
1105 #ifdef CONFIG_PROC_FS
1106 .show_fdinfo = bpf_map_show_fdinfo,
1108 .release = bpf_map_release,
1109 .read = bpf_dummy_read,
1110 .write = bpf_dummy_write,
1111 .mmap = bpf_map_mmap,
1112 .poll = bpf_map_poll,
1113 .get_unmapped_area = bpf_get_unmapped_area,
1116 int bpf_map_new_fd(struct bpf_map *map, int flags)
1120 ret = security_bpf_map(map, OPEN_FMODE(flags));
1124 return anon_inode_getfd("bpf-map", &bpf_map_fops, map,
1128 int bpf_get_file_flag(int flags)
1130 if ((flags & BPF_F_RDONLY) && (flags & BPF_F_WRONLY))
1132 if (flags & BPF_F_RDONLY)
1134 if (flags & BPF_F_WRONLY)
1139 /* helper macro to check that unused fields 'union bpf_attr' are zero */
1140 #define CHECK_ATTR(CMD) \
1141 memchr_inv((void *) &attr->CMD##_LAST_FIELD + \
1142 sizeof(attr->CMD##_LAST_FIELD), 0, \
1144 offsetof(union bpf_attr, CMD##_LAST_FIELD) - \
1145 sizeof(attr->CMD##_LAST_FIELD)) != NULL
1147 /* dst and src must have at least "size" number of bytes.
1148 * Return strlen on success and < 0 on error.
1150 int bpf_obj_name_cpy(char *dst, const char *src, unsigned int size)
1152 const char *end = src + size;
1153 const char *orig_src = src;
1155 memset(dst, 0, size);
1156 /* Copy all isalnum(), '_' and '.' chars. */
1157 while (src < end && *src) {
1158 if (!isalnum(*src) &&
1159 *src != '_' && *src != '.')
1164 /* No '\0' found in "size" number of bytes */
1168 return src - orig_src;
1171 int map_check_no_btf(const struct bpf_map *map,
1172 const struct btf *btf,
1173 const struct btf_type *key_type,
1174 const struct btf_type *value_type)
1179 static int map_check_btf(struct bpf_map *map, struct bpf_token *token,
1180 const struct btf *btf, u32 btf_key_id, u32 btf_value_id)
1182 const struct btf_type *key_type, *value_type;
1183 u32 key_size, value_size;
1186 /* Some maps allow key to be unspecified. */
1188 key_type = btf_type_id_size(btf, &btf_key_id, &key_size);
1189 if (!key_type || key_size != map->key_size)
1192 key_type = btf_type_by_id(btf, 0);
1193 if (!map->ops->map_check_btf)
1197 value_type = btf_type_id_size(btf, &btf_value_id, &value_size);
1198 if (!value_type || value_size != map->value_size)
1201 map->record = btf_parse_fields(btf, value_type,
1202 BPF_SPIN_LOCK | BPF_TIMER | BPF_KPTR | BPF_LIST_HEAD |
1203 BPF_RB_ROOT | BPF_REFCOUNT | BPF_WORKQUEUE | BPF_UPTR,
1205 if (!IS_ERR_OR_NULL(map->record)) {
1208 if (!bpf_token_capable(token, CAP_BPF)) {
1212 if (map->map_flags & (BPF_F_RDONLY_PROG | BPF_F_WRONLY_PROG)) {
1216 for (i = 0; i < sizeof(map->record->field_mask) * 8; i++) {
1217 switch (map->record->field_mask & (1 << i)) {
1221 if (map->map_type != BPF_MAP_TYPE_HASH &&
1222 map->map_type != BPF_MAP_TYPE_ARRAY &&
1223 map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
1224 map->map_type != BPF_MAP_TYPE_SK_STORAGE &&
1225 map->map_type != BPF_MAP_TYPE_INODE_STORAGE &&
1226 map->map_type != BPF_MAP_TYPE_TASK_STORAGE &&
1227 map->map_type != BPF_MAP_TYPE_CGRP_STORAGE) {
1234 if (map->map_type != BPF_MAP_TYPE_HASH &&
1235 map->map_type != BPF_MAP_TYPE_LRU_HASH &&
1236 map->map_type != BPF_MAP_TYPE_ARRAY) {
1241 case BPF_KPTR_UNREF:
1243 case BPF_KPTR_PERCPU:
1245 if (map->map_type != BPF_MAP_TYPE_HASH &&
1246 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
1247 map->map_type != BPF_MAP_TYPE_LRU_HASH &&
1248 map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH &&
1249 map->map_type != BPF_MAP_TYPE_ARRAY &&
1250 map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
1251 map->map_type != BPF_MAP_TYPE_SK_STORAGE &&
1252 map->map_type != BPF_MAP_TYPE_INODE_STORAGE &&
1253 map->map_type != BPF_MAP_TYPE_TASK_STORAGE &&
1254 map->map_type != BPF_MAP_TYPE_CGRP_STORAGE) {
1260 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE) {
1267 if (map->map_type != BPF_MAP_TYPE_HASH &&
1268 map->map_type != BPF_MAP_TYPE_LRU_HASH &&
1269 map->map_type != BPF_MAP_TYPE_ARRAY) {
1275 /* Fail if map_type checks are missing for a field type */
1282 ret = btf_check_and_fixup_fields(btf, map->record);
1286 if (map->ops->map_check_btf) {
1287 ret = map->ops->map_check_btf(map, btf, key_type, value_type);
1294 bpf_map_free_record(map);
1298 static bool bpf_net_capable(void)
1300 return capable(CAP_NET_ADMIN) || capable(CAP_SYS_ADMIN);
1303 #define BPF_MAP_CREATE_LAST_FIELD map_token_fd
1304 /* called via syscall */
1305 static int map_create(union bpf_attr *attr)
1307 const struct bpf_map_ops *ops;
1308 struct bpf_token *token = NULL;
1309 int numa_node = bpf_map_attr_numa_node(attr);
1310 u32 map_type = attr->map_type;
1311 struct bpf_map *map;
1316 err = CHECK_ATTR(BPF_MAP_CREATE);
1320 /* check BPF_F_TOKEN_FD flag, remember if it's set, and then clear it
1321 * to avoid per-map type checks tripping on unknown flag
1323 token_flag = attr->map_flags & BPF_F_TOKEN_FD;
1324 attr->map_flags &= ~BPF_F_TOKEN_FD;
1326 if (attr->btf_vmlinux_value_type_id) {
1327 if (attr->map_type != BPF_MAP_TYPE_STRUCT_OPS ||
1328 attr->btf_key_type_id || attr->btf_value_type_id)
1330 } else if (attr->btf_key_type_id && !attr->btf_value_type_id) {
1334 if (attr->map_type != BPF_MAP_TYPE_BLOOM_FILTER &&
1335 attr->map_type != BPF_MAP_TYPE_ARENA &&
1336 attr->map_extra != 0)
1339 f_flags = bpf_get_file_flag(attr->map_flags);
1343 if (numa_node != NUMA_NO_NODE &&
1344 ((unsigned int)numa_node >= nr_node_ids ||
1345 !node_online(numa_node)))
1348 /* find map type and init map: hashtable vs rbtree vs bloom vs ... */
1349 map_type = attr->map_type;
1350 if (map_type >= ARRAY_SIZE(bpf_map_types))
1352 map_type = array_index_nospec(map_type, ARRAY_SIZE(bpf_map_types));
1353 ops = bpf_map_types[map_type];
1357 if (ops->map_alloc_check) {
1358 err = ops->map_alloc_check(attr);
1362 if (attr->map_ifindex)
1363 ops = &bpf_map_offload_ops;
1364 if (!ops->map_mem_usage)
1368 token = bpf_token_get_from_fd(attr->map_token_fd);
1370 return PTR_ERR(token);
1372 /* if current token doesn't grant map creation permissions,
1373 * then we can't use this token, so ignore it and rely on
1374 * system-wide capabilities checks
1376 if (!bpf_token_allow_cmd(token, BPF_MAP_CREATE) ||
1377 !bpf_token_allow_map_type(token, attr->map_type)) {
1378 bpf_token_put(token);
1385 /* Intent here is for unprivileged_bpf_disabled to block BPF map
1386 * creation for unprivileged users; other actions depend
1387 * on fd availability and access to bpffs, so are dependent on
1388 * object creation success. Even with unprivileged BPF disabled,
1389 * capability checks are still carried out.
1391 if (sysctl_unprivileged_bpf_disabled && !bpf_token_capable(token, CAP_BPF))
1394 /* check privileged map type permissions */
1396 case BPF_MAP_TYPE_ARRAY:
1397 case BPF_MAP_TYPE_PERCPU_ARRAY:
1398 case BPF_MAP_TYPE_PROG_ARRAY:
1399 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
1400 case BPF_MAP_TYPE_CGROUP_ARRAY:
1401 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
1402 case BPF_MAP_TYPE_HASH:
1403 case BPF_MAP_TYPE_PERCPU_HASH:
1404 case BPF_MAP_TYPE_HASH_OF_MAPS:
1405 case BPF_MAP_TYPE_RINGBUF:
1406 case BPF_MAP_TYPE_USER_RINGBUF:
1407 case BPF_MAP_TYPE_CGROUP_STORAGE:
1408 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
1411 case BPF_MAP_TYPE_SK_STORAGE:
1412 case BPF_MAP_TYPE_INODE_STORAGE:
1413 case BPF_MAP_TYPE_TASK_STORAGE:
1414 case BPF_MAP_TYPE_CGRP_STORAGE:
1415 case BPF_MAP_TYPE_BLOOM_FILTER:
1416 case BPF_MAP_TYPE_LPM_TRIE:
1417 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
1418 case BPF_MAP_TYPE_STACK_TRACE:
1419 case BPF_MAP_TYPE_QUEUE:
1420 case BPF_MAP_TYPE_STACK:
1421 case BPF_MAP_TYPE_LRU_HASH:
1422 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
1423 case BPF_MAP_TYPE_STRUCT_OPS:
1424 case BPF_MAP_TYPE_CPUMAP:
1425 case BPF_MAP_TYPE_ARENA:
1426 if (!bpf_token_capable(token, CAP_BPF))
1429 case BPF_MAP_TYPE_SOCKMAP:
1430 case BPF_MAP_TYPE_SOCKHASH:
1431 case BPF_MAP_TYPE_DEVMAP:
1432 case BPF_MAP_TYPE_DEVMAP_HASH:
1433 case BPF_MAP_TYPE_XSKMAP:
1434 if (!bpf_token_capable(token, CAP_NET_ADMIN))
1438 WARN(1, "unsupported map type %d", map_type);
1442 map = ops->map_alloc(attr);
1448 map->map_type = map_type;
1450 err = bpf_obj_name_cpy(map->name, attr->map_name,
1451 sizeof(attr->map_name));
1455 atomic64_set(&map->refcnt, 1);
1456 atomic64_set(&map->usercnt, 1);
1457 mutex_init(&map->freeze_mutex);
1458 spin_lock_init(&map->owner.lock);
1460 if (attr->btf_key_type_id || attr->btf_value_type_id ||
1461 /* Even the map's value is a kernel's struct,
1462 * the bpf_prog.o must have BTF to begin with
1463 * to figure out the corresponding kernel's
1464 * counter part. Thus, attr->btf_fd has
1467 attr->btf_vmlinux_value_type_id) {
1470 btf = btf_get_by_fd(attr->btf_fd);
1475 if (btf_is_kernel(btf)) {
1482 if (attr->btf_value_type_id) {
1483 err = map_check_btf(map, token, btf, attr->btf_key_type_id,
1484 attr->btf_value_type_id);
1489 map->btf_key_type_id = attr->btf_key_type_id;
1490 map->btf_value_type_id = attr->btf_value_type_id;
1491 map->btf_vmlinux_value_type_id =
1492 attr->btf_vmlinux_value_type_id;
1495 err = security_bpf_map_create(map, attr, token);
1499 err = bpf_map_alloc_id(map);
1503 bpf_map_save_memcg(map);
1504 bpf_token_put(token);
1506 err = bpf_map_new_fd(map, f_flags);
1508 /* failed to allocate fd.
1509 * bpf_map_put_with_uref() is needed because the above
1510 * bpf_map_alloc_id() has published the map
1511 * to the userspace and the userspace may
1512 * have refcnt-ed it through BPF_MAP_GET_FD_BY_ID.
1514 bpf_map_put_with_uref(map);
1521 security_bpf_map_free(map);
1525 bpf_token_put(token);
1529 void bpf_map_inc(struct bpf_map *map)
1531 atomic64_inc(&map->refcnt);
1533 EXPORT_SYMBOL_GPL(bpf_map_inc);
1535 void bpf_map_inc_with_uref(struct bpf_map *map)
1537 atomic64_inc(&map->refcnt);
1538 atomic64_inc(&map->usercnt);
1540 EXPORT_SYMBOL_GPL(bpf_map_inc_with_uref);
1542 struct bpf_map *bpf_map_get(u32 ufd)
1545 struct bpf_map *map = __bpf_map_get(f);
1552 EXPORT_SYMBOL(bpf_map_get);
1554 struct bpf_map *bpf_map_get_with_uref(u32 ufd)
1557 struct bpf_map *map = __bpf_map_get(f);
1560 bpf_map_inc_with_uref(map);
1565 /* map_idr_lock should have been held or the map should have been
1566 * protected by rcu read lock.
1568 struct bpf_map *__bpf_map_inc_not_zero(struct bpf_map *map, bool uref)
1572 refold = atomic64_fetch_add_unless(&map->refcnt, 1, 0);
1574 return ERR_PTR(-ENOENT);
1576 atomic64_inc(&map->usercnt);
1581 struct bpf_map *bpf_map_inc_not_zero(struct bpf_map *map)
1583 spin_lock_bh(&map_idr_lock);
1584 map = __bpf_map_inc_not_zero(map, false);
1585 spin_unlock_bh(&map_idr_lock);
1589 EXPORT_SYMBOL_GPL(bpf_map_inc_not_zero);
1591 int __weak bpf_stackmap_copy(struct bpf_map *map, void *key, void *value)
1596 static void *__bpf_copy_key(void __user *ukey, u64 key_size)
1599 return vmemdup_user(ukey, key_size);
1602 return ERR_PTR(-EINVAL);
1607 static void *___bpf_copy_key(bpfptr_t ukey, u64 key_size)
1610 return kvmemdup_bpfptr(ukey, key_size);
1612 if (!bpfptr_is_null(ukey))
1613 return ERR_PTR(-EINVAL);
1618 /* last field in 'union bpf_attr' used by this command */
1619 #define BPF_MAP_LOOKUP_ELEM_LAST_FIELD flags
1621 static int map_lookup_elem(union bpf_attr *attr)
1623 void __user *ukey = u64_to_user_ptr(attr->key);
1624 void __user *uvalue = u64_to_user_ptr(attr->value);
1625 struct bpf_map *map;
1630 if (CHECK_ATTR(BPF_MAP_LOOKUP_ELEM))
1633 if (attr->flags & ~BPF_F_LOCK)
1636 CLASS(fd, f)(attr->map_fd);
1637 map = __bpf_map_get(f);
1639 return PTR_ERR(map);
1640 if (!(map_get_sys_perms(map, f) & FMODE_CAN_READ))
1643 if ((attr->flags & BPF_F_LOCK) &&
1644 !btf_record_has_field(map->record, BPF_SPIN_LOCK))
1647 key = __bpf_copy_key(ukey, map->key_size);
1649 return PTR_ERR(key);
1651 value_size = bpf_map_value_size(map);
1654 value = kvmalloc(value_size, GFP_USER | __GFP_NOWARN);
1658 if (map->map_type == BPF_MAP_TYPE_BLOOM_FILTER) {
1659 if (copy_from_user(value, uvalue, value_size))
1662 err = bpf_map_copy_value(map, key, value, attr->flags);
1666 err = bpf_map_copy_value(map, key, value, attr->flags);
1671 if (copy_to_user(uvalue, value, value_size) != 0)
1684 #define BPF_MAP_UPDATE_ELEM_LAST_FIELD flags
1686 static int map_update_elem(union bpf_attr *attr, bpfptr_t uattr)
1688 bpfptr_t ukey = make_bpfptr(attr->key, uattr.is_kernel);
1689 bpfptr_t uvalue = make_bpfptr(attr->value, uattr.is_kernel);
1690 struct bpf_map *map;
1695 if (CHECK_ATTR(BPF_MAP_UPDATE_ELEM))
1698 CLASS(fd, f)(attr->map_fd);
1699 map = __bpf_map_get(f);
1701 return PTR_ERR(map);
1702 bpf_map_write_active_inc(map);
1703 if (!(map_get_sys_perms(map, f) & FMODE_CAN_WRITE)) {
1708 if ((attr->flags & BPF_F_LOCK) &&
1709 !btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
1714 key = ___bpf_copy_key(ukey, map->key_size);
1720 value_size = bpf_map_value_size(map);
1721 value = kvmemdup_bpfptr(uvalue, value_size);
1722 if (IS_ERR(value)) {
1723 err = PTR_ERR(value);
1727 err = bpf_map_update_value(map, fd_file(f), key, value, attr->flags);
1729 maybe_wait_bpf_programs(map);
1735 bpf_map_write_active_dec(map);
1739 #define BPF_MAP_DELETE_ELEM_LAST_FIELD key
1741 static int map_delete_elem(union bpf_attr *attr, bpfptr_t uattr)
1743 bpfptr_t ukey = make_bpfptr(attr->key, uattr.is_kernel);
1744 struct bpf_map *map;
1748 if (CHECK_ATTR(BPF_MAP_DELETE_ELEM))
1751 CLASS(fd, f)(attr->map_fd);
1752 map = __bpf_map_get(f);
1754 return PTR_ERR(map);
1755 bpf_map_write_active_inc(map);
1756 if (!(map_get_sys_perms(map, f) & FMODE_CAN_WRITE)) {
1761 key = ___bpf_copy_key(ukey, map->key_size);
1767 if (bpf_map_is_offloaded(map)) {
1768 err = bpf_map_offload_delete_elem(map, key);
1770 } else if (IS_FD_PROG_ARRAY(map) ||
1771 map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
1772 /* These maps require sleepable context */
1773 err = map->ops->map_delete_elem(map, key);
1777 bpf_disable_instrumentation();
1779 err = map->ops->map_delete_elem(map, key);
1781 bpf_enable_instrumentation();
1783 maybe_wait_bpf_programs(map);
1787 bpf_map_write_active_dec(map);
1791 /* last field in 'union bpf_attr' used by this command */
1792 #define BPF_MAP_GET_NEXT_KEY_LAST_FIELD next_key
1794 static int map_get_next_key(union bpf_attr *attr)
1796 void __user *ukey = u64_to_user_ptr(attr->key);
1797 void __user *unext_key = u64_to_user_ptr(attr->next_key);
1798 struct bpf_map *map;
1799 void *key, *next_key;
1802 if (CHECK_ATTR(BPF_MAP_GET_NEXT_KEY))
1805 CLASS(fd, f)(attr->map_fd);
1806 map = __bpf_map_get(f);
1808 return PTR_ERR(map);
1809 if (!(map_get_sys_perms(map, f) & FMODE_CAN_READ))
1813 key = __bpf_copy_key(ukey, map->key_size);
1815 return PTR_ERR(key);
1821 next_key = kvmalloc(map->key_size, GFP_USER);
1825 if (bpf_map_is_offloaded(map)) {
1826 err = bpf_map_offload_get_next_key(map, key, next_key);
1831 err = map->ops->map_get_next_key(map, key, next_key);
1838 if (copy_to_user(unext_key, next_key, map->key_size) != 0)
1850 int generic_map_delete_batch(struct bpf_map *map,
1851 const union bpf_attr *attr,
1852 union bpf_attr __user *uattr)
1854 void __user *keys = u64_to_user_ptr(attr->batch.keys);
1859 if (attr->batch.elem_flags & ~BPF_F_LOCK)
1862 if ((attr->batch.elem_flags & BPF_F_LOCK) &&
1863 !btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
1867 max_count = attr->batch.count;
1871 if (put_user(0, &uattr->batch.count))
1874 key = kvmalloc(map->key_size, GFP_USER | __GFP_NOWARN);
1878 for (cp = 0; cp < max_count; cp++) {
1880 if (copy_from_user(key, keys + cp * map->key_size,
1884 if (bpf_map_is_offloaded(map)) {
1885 err = bpf_map_offload_delete_elem(map, key);
1889 bpf_disable_instrumentation();
1891 err = map->ops->map_delete_elem(map, key);
1893 bpf_enable_instrumentation();
1898 if (copy_to_user(&uattr->batch.count, &cp, sizeof(cp)))
1906 int generic_map_update_batch(struct bpf_map *map, struct file *map_file,
1907 const union bpf_attr *attr,
1908 union bpf_attr __user *uattr)
1910 void __user *values = u64_to_user_ptr(attr->batch.values);
1911 void __user *keys = u64_to_user_ptr(attr->batch.keys);
1912 u32 value_size, cp, max_count;
1916 if (attr->batch.elem_flags & ~BPF_F_LOCK)
1919 if ((attr->batch.elem_flags & BPF_F_LOCK) &&
1920 !btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
1924 value_size = bpf_map_value_size(map);
1926 max_count = attr->batch.count;
1930 if (put_user(0, &uattr->batch.count))
1933 key = kvmalloc(map->key_size, GFP_USER | __GFP_NOWARN);
1937 value = kvmalloc(value_size, GFP_USER | __GFP_NOWARN);
1943 for (cp = 0; cp < max_count; cp++) {
1945 if (copy_from_user(key, keys + cp * map->key_size,
1947 copy_from_user(value, values + cp * value_size, value_size))
1950 err = bpf_map_update_value(map, map_file, key, value,
1951 attr->batch.elem_flags);
1958 if (copy_to_user(&uattr->batch.count, &cp, sizeof(cp)))
1967 #define MAP_LOOKUP_RETRIES 3
1969 int generic_map_lookup_batch(struct bpf_map *map,
1970 const union bpf_attr *attr,
1971 union bpf_attr __user *uattr)
1973 void __user *uobatch = u64_to_user_ptr(attr->batch.out_batch);
1974 void __user *ubatch = u64_to_user_ptr(attr->batch.in_batch);
1975 void __user *values = u64_to_user_ptr(attr->batch.values);
1976 void __user *keys = u64_to_user_ptr(attr->batch.keys);
1977 void *buf, *buf_prevkey, *prev_key, *key, *value;
1978 int err, retry = MAP_LOOKUP_RETRIES;
1979 u32 value_size, cp, max_count;
1981 if (attr->batch.elem_flags & ~BPF_F_LOCK)
1984 if ((attr->batch.elem_flags & BPF_F_LOCK) &&
1985 !btf_record_has_field(map->record, BPF_SPIN_LOCK))
1988 value_size = bpf_map_value_size(map);
1990 max_count = attr->batch.count;
1994 if (put_user(0, &uattr->batch.count))
1997 buf_prevkey = kvmalloc(map->key_size, GFP_USER | __GFP_NOWARN);
2001 buf = kvmalloc(map->key_size + value_size, GFP_USER | __GFP_NOWARN);
2003 kvfree(buf_prevkey);
2009 if (ubatch && copy_from_user(buf_prevkey, ubatch, map->key_size))
2012 value = key + map->key_size;
2014 prev_key = buf_prevkey;
2016 for (cp = 0; cp < max_count;) {
2018 err = map->ops->map_get_next_key(map, prev_key, key);
2022 err = bpf_map_copy_value(map, key, value,
2023 attr->batch.elem_flags);
2025 if (err == -ENOENT) {
2037 if (copy_to_user(keys + cp * map->key_size, key,
2042 if (copy_to_user(values + cp * value_size, value, value_size)) {
2048 prev_key = buf_prevkey;
2050 swap(prev_key, key);
2051 retry = MAP_LOOKUP_RETRIES;
2059 if ((copy_to_user(&uattr->batch.count, &cp, sizeof(cp)) ||
2060 (cp && copy_to_user(uobatch, prev_key, map->key_size))))
2064 kvfree(buf_prevkey);
2069 #define BPF_MAP_LOOKUP_AND_DELETE_ELEM_LAST_FIELD flags
2071 static int map_lookup_and_delete_elem(union bpf_attr *attr)
2073 void __user *ukey = u64_to_user_ptr(attr->key);
2074 void __user *uvalue = u64_to_user_ptr(attr->value);
2075 struct bpf_map *map;
2080 if (CHECK_ATTR(BPF_MAP_LOOKUP_AND_DELETE_ELEM))
2083 if (attr->flags & ~BPF_F_LOCK)
2086 CLASS(fd, f)(attr->map_fd);
2087 map = __bpf_map_get(f);
2089 return PTR_ERR(map);
2090 bpf_map_write_active_inc(map);
2091 if (!(map_get_sys_perms(map, f) & FMODE_CAN_READ) ||
2092 !(map_get_sys_perms(map, f) & FMODE_CAN_WRITE)) {
2098 (map->map_type == BPF_MAP_TYPE_QUEUE ||
2099 map->map_type == BPF_MAP_TYPE_STACK)) {
2104 if ((attr->flags & BPF_F_LOCK) &&
2105 !btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
2110 key = __bpf_copy_key(ukey, map->key_size);
2116 value_size = bpf_map_value_size(map);
2119 value = kvmalloc(value_size, GFP_USER | __GFP_NOWARN);
2124 if (map->map_type == BPF_MAP_TYPE_QUEUE ||
2125 map->map_type == BPF_MAP_TYPE_STACK) {
2126 err = map->ops->map_pop_elem(map, value);
2127 } else if (map->map_type == BPF_MAP_TYPE_HASH ||
2128 map->map_type == BPF_MAP_TYPE_PERCPU_HASH ||
2129 map->map_type == BPF_MAP_TYPE_LRU_HASH ||
2130 map->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH) {
2131 if (!bpf_map_is_offloaded(map)) {
2132 bpf_disable_instrumentation();
2134 err = map->ops->map_lookup_and_delete_elem(map, key, value, attr->flags);
2136 bpf_enable_instrumentation();
2143 if (copy_to_user(uvalue, value, value_size) != 0) {
2155 bpf_map_write_active_dec(map);
2159 #define BPF_MAP_FREEZE_LAST_FIELD map_fd
2161 static int map_freeze(const union bpf_attr *attr)
2164 struct bpf_map *map;
2166 if (CHECK_ATTR(BPF_MAP_FREEZE))
2169 CLASS(fd, f)(attr->map_fd);
2170 map = __bpf_map_get(f);
2172 return PTR_ERR(map);
2174 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS || !IS_ERR_OR_NULL(map->record))
2177 if (!(map_get_sys_perms(map, f) & FMODE_CAN_WRITE))
2180 mutex_lock(&map->freeze_mutex);
2181 if (bpf_map_write_active(map)) {
2185 if (READ_ONCE(map->frozen)) {
2190 WRITE_ONCE(map->frozen, true);
2192 mutex_unlock(&map->freeze_mutex);
2196 static const struct bpf_prog_ops * const bpf_prog_types[] = {
2197 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
2198 [_id] = & _name ## _prog_ops,
2199 #define BPF_MAP_TYPE(_id, _ops)
2200 #define BPF_LINK_TYPE(_id, _name)
2201 #include <linux/bpf_types.h>
2202 #undef BPF_PROG_TYPE
2204 #undef BPF_LINK_TYPE
2207 static int find_prog_type(enum bpf_prog_type type, struct bpf_prog *prog)
2209 const struct bpf_prog_ops *ops;
2211 if (type >= ARRAY_SIZE(bpf_prog_types))
2213 type = array_index_nospec(type, ARRAY_SIZE(bpf_prog_types));
2214 ops = bpf_prog_types[type];
2218 if (!bpf_prog_is_offloaded(prog->aux))
2219 prog->aux->ops = ops;
2221 prog->aux->ops = &bpf_offload_prog_ops;
2232 static const char * const bpf_audit_str[BPF_AUDIT_MAX] = {
2233 [BPF_AUDIT_LOAD] = "LOAD",
2234 [BPF_AUDIT_UNLOAD] = "UNLOAD",
2237 static void bpf_audit_prog(const struct bpf_prog *prog, unsigned int op)
2239 struct audit_context *ctx = NULL;
2240 struct audit_buffer *ab;
2242 if (WARN_ON_ONCE(op >= BPF_AUDIT_MAX))
2244 if (audit_enabled == AUDIT_OFF)
2246 if (!in_irq() && !irqs_disabled())
2247 ctx = audit_context();
2248 ab = audit_log_start(ctx, GFP_ATOMIC, AUDIT_BPF);
2251 audit_log_format(ab, "prog-id=%u op=%s",
2252 prog->aux->id, bpf_audit_str[op]);
2256 static int bpf_prog_alloc_id(struct bpf_prog *prog)
2260 idr_preload(GFP_KERNEL);
2261 spin_lock_bh(&prog_idr_lock);
2262 id = idr_alloc_cyclic(&prog_idr, prog, 1, INT_MAX, GFP_ATOMIC);
2265 spin_unlock_bh(&prog_idr_lock);
2268 /* id is in [1, INT_MAX) */
2269 if (WARN_ON_ONCE(!id))
2272 return id > 0 ? 0 : id;
2275 void bpf_prog_free_id(struct bpf_prog *prog)
2277 unsigned long flags;
2279 /* cBPF to eBPF migrations are currently not in the idr store.
2280 * Offloaded programs are removed from the store when their device
2281 * disappears - even if someone grabs an fd to them they are unusable,
2282 * simply waiting for refcnt to drop to be freed.
2287 spin_lock_irqsave(&prog_idr_lock, flags);
2288 idr_remove(&prog_idr, prog->aux->id);
2290 spin_unlock_irqrestore(&prog_idr_lock, flags);
2293 static void __bpf_prog_put_rcu(struct rcu_head *rcu)
2295 struct bpf_prog_aux *aux = container_of(rcu, struct bpf_prog_aux, rcu);
2297 kvfree(aux->func_info);
2298 kfree(aux->func_info_aux);
2299 free_uid(aux->user);
2300 security_bpf_prog_free(aux->prog);
2301 bpf_prog_free(aux->prog);
2304 static void __bpf_prog_put_noref(struct bpf_prog *prog, bool deferred)
2306 bpf_prog_kallsyms_del_all(prog);
2307 btf_put(prog->aux->btf);
2308 module_put(prog->aux->mod);
2309 kvfree(prog->aux->jited_linfo);
2310 kvfree(prog->aux->linfo);
2311 kfree(prog->aux->kfunc_tab);
2312 if (prog->aux->attach_btf)
2313 btf_put(prog->aux->attach_btf);
2316 if (prog->sleepable)
2317 call_rcu_tasks_trace(&prog->aux->rcu, __bpf_prog_put_rcu);
2319 call_rcu(&prog->aux->rcu, __bpf_prog_put_rcu);
2321 __bpf_prog_put_rcu(&prog->aux->rcu);
2325 static void bpf_prog_put_deferred(struct work_struct *work)
2327 struct bpf_prog_aux *aux;
2328 struct bpf_prog *prog;
2330 aux = container_of(work, struct bpf_prog_aux, work);
2332 perf_event_bpf_event(prog, PERF_BPF_EVENT_PROG_UNLOAD, 0);
2333 bpf_audit_prog(prog, BPF_AUDIT_UNLOAD);
2334 bpf_prog_free_id(prog);
2335 __bpf_prog_put_noref(prog, true);
2338 static void __bpf_prog_put(struct bpf_prog *prog)
2340 struct bpf_prog_aux *aux = prog->aux;
2342 if (atomic64_dec_and_test(&aux->refcnt)) {
2343 if (in_irq() || irqs_disabled()) {
2344 INIT_WORK(&aux->work, bpf_prog_put_deferred);
2345 schedule_work(&aux->work);
2347 bpf_prog_put_deferred(&aux->work);
2352 void bpf_prog_put(struct bpf_prog *prog)
2354 __bpf_prog_put(prog);
2356 EXPORT_SYMBOL_GPL(bpf_prog_put);
2358 static int bpf_prog_release(struct inode *inode, struct file *filp)
2360 struct bpf_prog *prog = filp->private_data;
2366 struct bpf_prog_kstats {
2372 void notrace bpf_prog_inc_misses_counter(struct bpf_prog *prog)
2374 struct bpf_prog_stats *stats;
2377 stats = this_cpu_ptr(prog->stats);
2378 flags = u64_stats_update_begin_irqsave(&stats->syncp);
2379 u64_stats_inc(&stats->misses);
2380 u64_stats_update_end_irqrestore(&stats->syncp, flags);
2383 static void bpf_prog_get_stats(const struct bpf_prog *prog,
2384 struct bpf_prog_kstats *stats)
2386 u64 nsecs = 0, cnt = 0, misses = 0;
2389 for_each_possible_cpu(cpu) {
2390 const struct bpf_prog_stats *st;
2392 u64 tnsecs, tcnt, tmisses;
2394 st = per_cpu_ptr(prog->stats, cpu);
2396 start = u64_stats_fetch_begin(&st->syncp);
2397 tnsecs = u64_stats_read(&st->nsecs);
2398 tcnt = u64_stats_read(&st->cnt);
2399 tmisses = u64_stats_read(&st->misses);
2400 } while (u64_stats_fetch_retry(&st->syncp, start));
2405 stats->nsecs = nsecs;
2407 stats->misses = misses;
2410 #ifdef CONFIG_PROC_FS
2411 static void bpf_prog_show_fdinfo(struct seq_file *m, struct file *filp)
2413 const struct bpf_prog *prog = filp->private_data;
2414 char prog_tag[sizeof(prog->tag) * 2 + 1] = { };
2415 struct bpf_prog_kstats stats;
2417 bpf_prog_get_stats(prog, &stats);
2418 bin2hex(prog_tag, prog->tag, sizeof(prog->tag));
2425 "run_time_ns:\t%llu\n"
2427 "recursion_misses:\t%llu\n"
2428 "verified_insns:\t%u\n",
2432 prog->pages * 1ULL << PAGE_SHIFT,
2437 prog->aux->verified_insns);
2441 const struct file_operations bpf_prog_fops = {
2442 #ifdef CONFIG_PROC_FS
2443 .show_fdinfo = bpf_prog_show_fdinfo,
2445 .release = bpf_prog_release,
2446 .read = bpf_dummy_read,
2447 .write = bpf_dummy_write,
2450 int bpf_prog_new_fd(struct bpf_prog *prog)
2454 ret = security_bpf_prog(prog);
2458 return anon_inode_getfd("bpf-prog", &bpf_prog_fops, prog,
2459 O_RDWR | O_CLOEXEC);
2462 void bpf_prog_add(struct bpf_prog *prog, int i)
2464 atomic64_add(i, &prog->aux->refcnt);
2466 EXPORT_SYMBOL_GPL(bpf_prog_add);
2468 void bpf_prog_sub(struct bpf_prog *prog, int i)
2470 /* Only to be used for undoing previous bpf_prog_add() in some
2471 * error path. We still know that another entity in our call
2472 * path holds a reference to the program, thus atomic_sub() can
2473 * be safely used in such cases!
2475 WARN_ON(atomic64_sub_return(i, &prog->aux->refcnt) == 0);
2477 EXPORT_SYMBOL_GPL(bpf_prog_sub);
2479 void bpf_prog_inc(struct bpf_prog *prog)
2481 atomic64_inc(&prog->aux->refcnt);
2483 EXPORT_SYMBOL_GPL(bpf_prog_inc);
2485 /* prog_idr_lock should have been held */
2486 struct bpf_prog *bpf_prog_inc_not_zero(struct bpf_prog *prog)
2490 refold = atomic64_fetch_add_unless(&prog->aux->refcnt, 1, 0);
2493 return ERR_PTR(-ENOENT);
2497 EXPORT_SYMBOL_GPL(bpf_prog_inc_not_zero);
2499 bool bpf_prog_get_ok(struct bpf_prog *prog,
2500 enum bpf_prog_type *attach_type, bool attach_drv)
2502 /* not an attachment, just a refcount inc, always allow */
2506 if (prog->type != *attach_type)
2508 if (bpf_prog_is_offloaded(prog->aux) && !attach_drv)
2514 static struct bpf_prog *__bpf_prog_get(u32 ufd, enum bpf_prog_type *attach_type,
2518 struct bpf_prog *prog;
2521 return ERR_PTR(-EBADF);
2522 if (fd_file(f)->f_op != &bpf_prog_fops)
2523 return ERR_PTR(-EINVAL);
2525 prog = fd_file(f)->private_data;
2526 if (!bpf_prog_get_ok(prog, attach_type, attach_drv))
2527 return ERR_PTR(-EINVAL);
2533 struct bpf_prog *bpf_prog_get(u32 ufd)
2535 return __bpf_prog_get(ufd, NULL, false);
2538 struct bpf_prog *bpf_prog_get_type_dev(u32 ufd, enum bpf_prog_type type,
2541 return __bpf_prog_get(ufd, &type, attach_drv);
2543 EXPORT_SYMBOL_GPL(bpf_prog_get_type_dev);
2545 /* Initially all BPF programs could be loaded w/o specifying
2546 * expected_attach_type. Later for some of them specifying expected_attach_type
2547 * at load time became required so that program could be validated properly.
2548 * Programs of types that are allowed to be loaded both w/ and w/o (for
2549 * backward compatibility) expected_attach_type, should have the default attach
2550 * type assigned to expected_attach_type for the latter case, so that it can be
2551 * validated later at attach time.
2553 * bpf_prog_load_fixup_attach_type() sets expected_attach_type in @attr if
2554 * prog type requires it but has some attach types that have to be backward
2557 static void bpf_prog_load_fixup_attach_type(union bpf_attr *attr)
2559 switch (attr->prog_type) {
2560 case BPF_PROG_TYPE_CGROUP_SOCK:
2561 /* Unfortunately BPF_ATTACH_TYPE_UNSPEC enumeration doesn't
2562 * exist so checking for non-zero is the way to go here.
2564 if (!attr->expected_attach_type)
2565 attr->expected_attach_type =
2566 BPF_CGROUP_INET_SOCK_CREATE;
2568 case BPF_PROG_TYPE_SK_REUSEPORT:
2569 if (!attr->expected_attach_type)
2570 attr->expected_attach_type =
2571 BPF_SK_REUSEPORT_SELECT;
2577 bpf_prog_load_check_attach(enum bpf_prog_type prog_type,
2578 enum bpf_attach_type expected_attach_type,
2579 struct btf *attach_btf, u32 btf_id,
2580 struct bpf_prog *dst_prog)
2583 if (btf_id > BTF_MAX_TYPE)
2586 if (!attach_btf && !dst_prog)
2589 switch (prog_type) {
2590 case BPF_PROG_TYPE_TRACING:
2591 case BPF_PROG_TYPE_LSM:
2592 case BPF_PROG_TYPE_STRUCT_OPS:
2593 case BPF_PROG_TYPE_EXT:
2600 if (attach_btf && (!btf_id || dst_prog))
2603 if (dst_prog && prog_type != BPF_PROG_TYPE_TRACING &&
2604 prog_type != BPF_PROG_TYPE_EXT)
2607 switch (prog_type) {
2608 case BPF_PROG_TYPE_CGROUP_SOCK:
2609 switch (expected_attach_type) {
2610 case BPF_CGROUP_INET_SOCK_CREATE:
2611 case BPF_CGROUP_INET_SOCK_RELEASE:
2612 case BPF_CGROUP_INET4_POST_BIND:
2613 case BPF_CGROUP_INET6_POST_BIND:
2618 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
2619 switch (expected_attach_type) {
2620 case BPF_CGROUP_INET4_BIND:
2621 case BPF_CGROUP_INET6_BIND:
2622 case BPF_CGROUP_INET4_CONNECT:
2623 case BPF_CGROUP_INET6_CONNECT:
2624 case BPF_CGROUP_UNIX_CONNECT:
2625 case BPF_CGROUP_INET4_GETPEERNAME:
2626 case BPF_CGROUP_INET6_GETPEERNAME:
2627 case BPF_CGROUP_UNIX_GETPEERNAME:
2628 case BPF_CGROUP_INET4_GETSOCKNAME:
2629 case BPF_CGROUP_INET6_GETSOCKNAME:
2630 case BPF_CGROUP_UNIX_GETSOCKNAME:
2631 case BPF_CGROUP_UDP4_SENDMSG:
2632 case BPF_CGROUP_UDP6_SENDMSG:
2633 case BPF_CGROUP_UNIX_SENDMSG:
2634 case BPF_CGROUP_UDP4_RECVMSG:
2635 case BPF_CGROUP_UDP6_RECVMSG:
2636 case BPF_CGROUP_UNIX_RECVMSG:
2641 case BPF_PROG_TYPE_CGROUP_SKB:
2642 switch (expected_attach_type) {
2643 case BPF_CGROUP_INET_INGRESS:
2644 case BPF_CGROUP_INET_EGRESS:
2649 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
2650 switch (expected_attach_type) {
2651 case BPF_CGROUP_SETSOCKOPT:
2652 case BPF_CGROUP_GETSOCKOPT:
2657 case BPF_PROG_TYPE_SK_LOOKUP:
2658 if (expected_attach_type == BPF_SK_LOOKUP)
2661 case BPF_PROG_TYPE_SK_REUSEPORT:
2662 switch (expected_attach_type) {
2663 case BPF_SK_REUSEPORT_SELECT:
2664 case BPF_SK_REUSEPORT_SELECT_OR_MIGRATE:
2669 case BPF_PROG_TYPE_NETFILTER:
2670 if (expected_attach_type == BPF_NETFILTER)
2673 case BPF_PROG_TYPE_SYSCALL:
2674 case BPF_PROG_TYPE_EXT:
2675 if (expected_attach_type)
2683 static bool is_net_admin_prog_type(enum bpf_prog_type prog_type)
2685 switch (prog_type) {
2686 case BPF_PROG_TYPE_SCHED_CLS:
2687 case BPF_PROG_TYPE_SCHED_ACT:
2688 case BPF_PROG_TYPE_XDP:
2689 case BPF_PROG_TYPE_LWT_IN:
2690 case BPF_PROG_TYPE_LWT_OUT:
2691 case BPF_PROG_TYPE_LWT_XMIT:
2692 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
2693 case BPF_PROG_TYPE_SK_SKB:
2694 case BPF_PROG_TYPE_SK_MSG:
2695 case BPF_PROG_TYPE_FLOW_DISSECTOR:
2696 case BPF_PROG_TYPE_CGROUP_DEVICE:
2697 case BPF_PROG_TYPE_CGROUP_SOCK:
2698 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
2699 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
2700 case BPF_PROG_TYPE_CGROUP_SYSCTL:
2701 case BPF_PROG_TYPE_SOCK_OPS:
2702 case BPF_PROG_TYPE_EXT: /* extends any prog */
2703 case BPF_PROG_TYPE_NETFILTER:
2705 case BPF_PROG_TYPE_CGROUP_SKB:
2707 case BPF_PROG_TYPE_SK_REUSEPORT:
2708 /* equivalent to SOCKET_FILTER. need CAP_BPF only */
2714 static bool is_perfmon_prog_type(enum bpf_prog_type prog_type)
2716 switch (prog_type) {
2717 case BPF_PROG_TYPE_KPROBE:
2718 case BPF_PROG_TYPE_TRACEPOINT:
2719 case BPF_PROG_TYPE_PERF_EVENT:
2720 case BPF_PROG_TYPE_RAW_TRACEPOINT:
2721 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
2722 case BPF_PROG_TYPE_TRACING:
2723 case BPF_PROG_TYPE_LSM:
2724 case BPF_PROG_TYPE_STRUCT_OPS: /* has access to struct sock */
2725 case BPF_PROG_TYPE_EXT: /* extends any prog */
2732 /* last field in 'union bpf_attr' used by this command */
2733 #define BPF_PROG_LOAD_LAST_FIELD prog_token_fd
2735 static int bpf_prog_load(union bpf_attr *attr, bpfptr_t uattr, u32 uattr_size)
2737 enum bpf_prog_type type = attr->prog_type;
2738 struct bpf_prog *prog, *dst_prog = NULL;
2739 struct btf *attach_btf = NULL;
2740 struct bpf_token *token = NULL;
2745 if (CHECK_ATTR(BPF_PROG_LOAD))
2748 if (attr->prog_flags & ~(BPF_F_STRICT_ALIGNMENT |
2749 BPF_F_ANY_ALIGNMENT |
2750 BPF_F_TEST_STATE_FREQ |
2752 BPF_F_TEST_RND_HI32 |
2753 BPF_F_XDP_HAS_FRAGS |
2754 BPF_F_XDP_DEV_BOUND_ONLY |
2755 BPF_F_TEST_REG_INVARIANTS |
2759 bpf_prog_load_fixup_attach_type(attr);
2761 if (attr->prog_flags & BPF_F_TOKEN_FD) {
2762 token = bpf_token_get_from_fd(attr->prog_token_fd);
2764 return PTR_ERR(token);
2765 /* if current token doesn't grant prog loading permissions,
2766 * then we can't use this token, so ignore it and rely on
2767 * system-wide capabilities checks
2769 if (!bpf_token_allow_cmd(token, BPF_PROG_LOAD) ||
2770 !bpf_token_allow_prog_type(token, attr->prog_type,
2771 attr->expected_attach_type)) {
2772 bpf_token_put(token);
2777 bpf_cap = bpf_token_capable(token, CAP_BPF);
2780 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS) &&
2781 (attr->prog_flags & BPF_F_ANY_ALIGNMENT) &&
2785 /* Intent here is for unprivileged_bpf_disabled to block BPF program
2786 * creation for unprivileged users; other actions depend
2787 * on fd availability and access to bpffs, so are dependent on
2788 * object creation success. Even with unprivileged BPF disabled,
2789 * capability checks are still carried out for these
2790 * and other operations.
2792 if (sysctl_unprivileged_bpf_disabled && !bpf_cap)
2795 if (attr->insn_cnt == 0 ||
2796 attr->insn_cnt > (bpf_cap ? BPF_COMPLEXITY_LIMIT_INSNS : BPF_MAXINSNS)) {
2800 if (type != BPF_PROG_TYPE_SOCKET_FILTER &&
2801 type != BPF_PROG_TYPE_CGROUP_SKB &&
2805 if (is_net_admin_prog_type(type) && !bpf_token_capable(token, CAP_NET_ADMIN))
2807 if (is_perfmon_prog_type(type) && !bpf_token_capable(token, CAP_PERFMON))
2810 /* attach_prog_fd/attach_btf_obj_fd can specify fd of either bpf_prog
2811 * or btf, we need to check which one it is
2813 if (attr->attach_prog_fd) {
2814 dst_prog = bpf_prog_get(attr->attach_prog_fd);
2815 if (IS_ERR(dst_prog)) {
2817 attach_btf = btf_get_by_fd(attr->attach_btf_obj_fd);
2818 if (IS_ERR(attach_btf)) {
2822 if (!btf_is_kernel(attach_btf)) {
2823 /* attaching through specifying bpf_prog's BTF
2824 * objects directly might be supported eventually
2826 btf_put(attach_btf);
2831 } else if (attr->attach_btf_id) {
2832 /* fall back to vmlinux BTF, if BTF type ID is specified */
2833 attach_btf = bpf_get_btf_vmlinux();
2834 if (IS_ERR(attach_btf)) {
2835 err = PTR_ERR(attach_btf);
2842 btf_get(attach_btf);
2845 if (bpf_prog_load_check_attach(type, attr->expected_attach_type,
2846 attach_btf, attr->attach_btf_id,
2849 bpf_prog_put(dst_prog);
2851 btf_put(attach_btf);
2856 /* plain bpf_prog allocation */
2857 prog = bpf_prog_alloc(bpf_prog_size(attr->insn_cnt), GFP_USER);
2860 bpf_prog_put(dst_prog);
2862 btf_put(attach_btf);
2867 prog->expected_attach_type = attr->expected_attach_type;
2868 prog->sleepable = !!(attr->prog_flags & BPF_F_SLEEPABLE);
2869 prog->aux->attach_btf = attach_btf;
2870 prog->aux->attach_btf_id = attr->attach_btf_id;
2871 prog->aux->dst_prog = dst_prog;
2872 prog->aux->dev_bound = !!attr->prog_ifindex;
2873 prog->aux->xdp_has_frags = attr->prog_flags & BPF_F_XDP_HAS_FRAGS;
2875 /* move token into prog->aux, reuse taken refcnt */
2876 prog->aux->token = token;
2879 prog->aux->user = get_current_user();
2880 prog->len = attr->insn_cnt;
2883 if (copy_from_bpfptr(prog->insns,
2884 make_bpfptr(attr->insns, uattr.is_kernel),
2885 bpf_prog_insn_size(prog)) != 0)
2887 /* copy eBPF program license from user space */
2888 if (strncpy_from_bpfptr(license,
2889 make_bpfptr(attr->license, uattr.is_kernel),
2890 sizeof(license) - 1) < 0)
2892 license[sizeof(license) - 1] = 0;
2894 /* eBPF programs must be GPL compatible to use GPL-ed functions */
2895 prog->gpl_compatible = license_is_gpl_compatible(license) ? 1 : 0;
2897 prog->orig_prog = NULL;
2900 atomic64_set(&prog->aux->refcnt, 1);
2902 if (bpf_prog_is_dev_bound(prog->aux)) {
2903 err = bpf_prog_dev_bound_init(prog, attr);
2908 if (type == BPF_PROG_TYPE_EXT && dst_prog &&
2909 bpf_prog_is_dev_bound(dst_prog->aux)) {
2910 err = bpf_prog_dev_bound_inherit(prog, dst_prog);
2916 * Bookkeeping for managing the program attachment chain.
2918 * It might be tempting to set attach_tracing_prog flag at the attachment
2919 * time, but this will not prevent from loading bunch of tracing prog
2920 * first, then attach them one to another.
2922 * The flag attach_tracing_prog is set for the whole program lifecycle, and
2923 * doesn't have to be cleared in bpf_tracing_link_release, since tracing
2924 * programs cannot change attachment target.
2926 if (type == BPF_PROG_TYPE_TRACING && dst_prog &&
2927 dst_prog->type == BPF_PROG_TYPE_TRACING) {
2928 prog->aux->attach_tracing_prog = true;
2931 /* find program type: socket_filter vs tracing_filter */
2932 err = find_prog_type(type, prog);
2936 prog->aux->load_time = ktime_get_boottime_ns();
2937 err = bpf_obj_name_cpy(prog->aux->name, attr->prog_name,
2938 sizeof(attr->prog_name));
2942 err = security_bpf_prog_load(prog, attr, token);
2946 /* run eBPF verifier */
2947 err = bpf_check(&prog, attr, uattr, uattr_size);
2949 goto free_used_maps;
2951 prog = bpf_prog_select_runtime(prog, &err);
2953 goto free_used_maps;
2955 err = bpf_prog_alloc_id(prog);
2957 goto free_used_maps;
2959 /* Upon success of bpf_prog_alloc_id(), the BPF prog is
2960 * effectively publicly exposed. However, retrieving via
2961 * bpf_prog_get_fd_by_id() will take another reference,
2962 * therefore it cannot be gone underneath us.
2964 * Only for the time /after/ successful bpf_prog_new_fd()
2965 * and before returning to userspace, we might just hold
2966 * one reference and any parallel close on that fd could
2967 * rip everything out. Hence, below notifications must
2968 * happen before bpf_prog_new_fd().
2970 * Also, any failure handling from this point onwards must
2971 * be using bpf_prog_put() given the program is exposed.
2973 bpf_prog_kallsyms_add(prog);
2974 perf_event_bpf_event(prog, PERF_BPF_EVENT_PROG_LOAD, 0);
2975 bpf_audit_prog(prog, BPF_AUDIT_LOAD);
2977 err = bpf_prog_new_fd(prog);
2983 /* In case we have subprogs, we need to wait for a grace
2984 * period before we can tear down JIT memory since symbols
2985 * are already exposed under kallsyms.
2987 __bpf_prog_put_noref(prog, prog->aux->real_func_cnt);
2991 security_bpf_prog_free(prog);
2993 free_uid(prog->aux->user);
2994 if (prog->aux->attach_btf)
2995 btf_put(prog->aux->attach_btf);
2996 bpf_prog_free(prog);
2998 bpf_token_put(token);
3002 #define BPF_OBJ_LAST_FIELD path_fd
3004 static int bpf_obj_pin(const union bpf_attr *attr)
3008 if (CHECK_ATTR(BPF_OBJ) || attr->file_flags & ~BPF_F_PATH_FD)
3011 /* path_fd has to be accompanied by BPF_F_PATH_FD flag */
3012 if (!(attr->file_flags & BPF_F_PATH_FD) && attr->path_fd)
3015 path_fd = attr->file_flags & BPF_F_PATH_FD ? attr->path_fd : AT_FDCWD;
3016 return bpf_obj_pin_user(attr->bpf_fd, path_fd,
3017 u64_to_user_ptr(attr->pathname));
3020 static int bpf_obj_get(const union bpf_attr *attr)
3024 if (CHECK_ATTR(BPF_OBJ) || attr->bpf_fd != 0 ||
3025 attr->file_flags & ~(BPF_OBJ_FLAG_MASK | BPF_F_PATH_FD))
3028 /* path_fd has to be accompanied by BPF_F_PATH_FD flag */
3029 if (!(attr->file_flags & BPF_F_PATH_FD) && attr->path_fd)
3032 path_fd = attr->file_flags & BPF_F_PATH_FD ? attr->path_fd : AT_FDCWD;
3033 return bpf_obj_get_user(path_fd, u64_to_user_ptr(attr->pathname),
3037 /* bpf_link_init_sleepable() allows to specify whether BPF link itself has
3038 * "sleepable" semantics, which normally would mean that BPF link's attach
3039 * hook can dereference link or link's underlying program for some time after
3040 * detachment due to RCU Tasks Trace-based lifetime protection scheme.
3041 * BPF program itself can be non-sleepable, yet, because it's transitively
3042 * reachable through BPF link, its freeing has to be delayed until after RCU
3045 void bpf_link_init_sleepable(struct bpf_link *link, enum bpf_link_type type,
3046 const struct bpf_link_ops *ops, struct bpf_prog *prog,
3049 WARN_ON(ops->dealloc && ops->dealloc_deferred);
3050 atomic64_set(&link->refcnt, 1);
3052 link->sleepable = sleepable;
3058 void bpf_link_init(struct bpf_link *link, enum bpf_link_type type,
3059 const struct bpf_link_ops *ops, struct bpf_prog *prog)
3061 bpf_link_init_sleepable(link, type, ops, prog, false);
3064 static void bpf_link_free_id(int id)
3069 spin_lock_bh(&link_idr_lock);
3070 idr_remove(&link_idr, id);
3071 spin_unlock_bh(&link_idr_lock);
3074 /* Clean up bpf_link and corresponding anon_inode file and FD. After
3075 * anon_inode is created, bpf_link can't be just kfree()'d due to deferred
3076 * anon_inode's release() call. This helper marks bpf_link as
3077 * defunct, releases anon_inode file and puts reserved FD. bpf_prog's refcnt
3078 * is not decremented, it's the responsibility of a calling code that failed
3079 * to complete bpf_link initialization.
3080 * This helper eventually calls link's dealloc callback, but does not call
3081 * link's release callback.
3083 void bpf_link_cleanup(struct bpf_link_primer *primer)
3085 primer->link->prog = NULL;
3086 bpf_link_free_id(primer->id);
3088 put_unused_fd(primer->fd);
3091 void bpf_link_inc(struct bpf_link *link)
3093 atomic64_inc(&link->refcnt);
3096 static void bpf_link_dealloc(struct bpf_link *link)
3098 /* now that we know that bpf_link itself can't be reached, put underlying BPF program */
3100 bpf_prog_put(link->prog);
3102 /* free bpf_link and its containing memory */
3103 if (link->ops->dealloc_deferred)
3104 link->ops->dealloc_deferred(link);
3106 link->ops->dealloc(link);
3109 static void bpf_link_defer_dealloc_rcu_gp(struct rcu_head *rcu)
3111 struct bpf_link *link = container_of(rcu, struct bpf_link, rcu);
3113 bpf_link_dealloc(link);
3116 static void bpf_link_defer_dealloc_mult_rcu_gp(struct rcu_head *rcu)
3118 if (rcu_trace_implies_rcu_gp())
3119 bpf_link_defer_dealloc_rcu_gp(rcu);
3121 call_rcu(rcu, bpf_link_defer_dealloc_rcu_gp);
3124 /* bpf_link_free is guaranteed to be called from process context */
3125 static void bpf_link_free(struct bpf_link *link)
3127 const struct bpf_link_ops *ops = link->ops;
3129 bpf_link_free_id(link->id);
3130 /* detach BPF program, clean up used resources */
3133 if (ops->dealloc_deferred) {
3134 /* Schedule BPF link deallocation, which will only then
3135 * trigger putting BPF program refcount.
3136 * If underlying BPF program is sleepable or BPF link's target
3137 * attach hookpoint is sleepable or otherwise requires RCU GPs
3138 * to ensure link and its underlying BPF program is not
3139 * reachable anymore, we need to first wait for RCU tasks
3140 * trace sync, and then go through "classic" RCU grace period
3142 if (link->sleepable || (link->prog && link->prog->sleepable))
3143 call_rcu_tasks_trace(&link->rcu, bpf_link_defer_dealloc_mult_rcu_gp);
3145 call_rcu(&link->rcu, bpf_link_defer_dealloc_rcu_gp);
3146 } else if (ops->dealloc) {
3147 bpf_link_dealloc(link);
3151 static void bpf_link_put_deferred(struct work_struct *work)
3153 struct bpf_link *link = container_of(work, struct bpf_link, work);
3155 bpf_link_free(link);
3158 /* bpf_link_put might be called from atomic context. It needs to be called
3159 * from sleepable context in order to acquire sleeping locks during the process.
3161 void bpf_link_put(struct bpf_link *link)
3163 if (!atomic64_dec_and_test(&link->refcnt))
3166 INIT_WORK(&link->work, bpf_link_put_deferred);
3167 schedule_work(&link->work);
3169 EXPORT_SYMBOL(bpf_link_put);
3171 static void bpf_link_put_direct(struct bpf_link *link)
3173 if (!atomic64_dec_and_test(&link->refcnt))
3175 bpf_link_free(link);
3178 static int bpf_link_release(struct inode *inode, struct file *filp)
3180 struct bpf_link *link = filp->private_data;
3182 bpf_link_put_direct(link);
3186 #ifdef CONFIG_PROC_FS
3187 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type)
3188 #define BPF_MAP_TYPE(_id, _ops)
3189 #define BPF_LINK_TYPE(_id, _name) [_id] = #_name,
3190 static const char *bpf_link_type_strs[] = {
3191 [BPF_LINK_TYPE_UNSPEC] = "<invalid>",
3192 #include <linux/bpf_types.h>
3194 #undef BPF_PROG_TYPE
3196 #undef BPF_LINK_TYPE
3198 static void bpf_link_show_fdinfo(struct seq_file *m, struct file *filp)
3200 const struct bpf_link *link = filp->private_data;
3201 const struct bpf_prog *prog = link->prog;
3202 enum bpf_link_type type = link->type;
3203 char prog_tag[sizeof(prog->tag) * 2 + 1] = { };
3205 if (type < ARRAY_SIZE(bpf_link_type_strs) && bpf_link_type_strs[type]) {
3206 seq_printf(m, "link_type:\t%s\n", bpf_link_type_strs[type]);
3208 WARN_ONCE(1, "missing BPF_LINK_TYPE(...) for link type %u\n", type);
3209 seq_printf(m, "link_type:\t<%u>\n", type);
3211 seq_printf(m, "link_id:\t%u\n", link->id);
3214 bin2hex(prog_tag, prog->tag, sizeof(prog->tag));
3221 if (link->ops->show_fdinfo)
3222 link->ops->show_fdinfo(link, m);
3226 static __poll_t bpf_link_poll(struct file *file, struct poll_table_struct *pts)
3228 struct bpf_link *link = file->private_data;
3230 return link->ops->poll(file, pts);
3233 static const struct file_operations bpf_link_fops = {
3234 #ifdef CONFIG_PROC_FS
3235 .show_fdinfo = bpf_link_show_fdinfo,
3237 .release = bpf_link_release,
3238 .read = bpf_dummy_read,
3239 .write = bpf_dummy_write,
3242 static const struct file_operations bpf_link_fops_poll = {
3243 #ifdef CONFIG_PROC_FS
3244 .show_fdinfo = bpf_link_show_fdinfo,
3246 .release = bpf_link_release,
3247 .read = bpf_dummy_read,
3248 .write = bpf_dummy_write,
3249 .poll = bpf_link_poll,
3252 static int bpf_link_alloc_id(struct bpf_link *link)
3256 idr_preload(GFP_KERNEL);
3257 spin_lock_bh(&link_idr_lock);
3258 id = idr_alloc_cyclic(&link_idr, link, 1, INT_MAX, GFP_ATOMIC);
3259 spin_unlock_bh(&link_idr_lock);
3265 /* Prepare bpf_link to be exposed to user-space by allocating anon_inode file,
3266 * reserving unused FD and allocating ID from link_idr. This is to be paired
3267 * with bpf_link_settle() to install FD and ID and expose bpf_link to
3268 * user-space, if bpf_link is successfully attached. If not, bpf_link and
3269 * pre-allocated resources are to be freed with bpf_cleanup() call. All the
3270 * transient state is passed around in struct bpf_link_primer.
3271 * This is preferred way to create and initialize bpf_link, especially when
3272 * there are complicated and expensive operations in between creating bpf_link
3273 * itself and attaching it to BPF hook. By using bpf_link_prime() and
3274 * bpf_link_settle() kernel code using bpf_link doesn't have to perform
3275 * expensive (and potentially failing) roll back operations in a rare case
3276 * that file, FD, or ID can't be allocated.
3278 int bpf_link_prime(struct bpf_link *link, struct bpf_link_primer *primer)
3283 fd = get_unused_fd_flags(O_CLOEXEC);
3288 id = bpf_link_alloc_id(link);
3294 file = anon_inode_getfile("bpf_link",
3295 link->ops->poll ? &bpf_link_fops_poll : &bpf_link_fops,
3298 bpf_link_free_id(id);
3300 return PTR_ERR(file);
3303 primer->link = link;
3304 primer->file = file;
3310 int bpf_link_settle(struct bpf_link_primer *primer)
3312 /* make bpf_link fetchable by ID */
3313 spin_lock_bh(&link_idr_lock);
3314 primer->link->id = primer->id;
3315 spin_unlock_bh(&link_idr_lock);
3316 /* make bpf_link fetchable by FD */
3317 fd_install(primer->fd, primer->file);
3318 /* pass through installed FD */
3322 int bpf_link_new_fd(struct bpf_link *link)
3324 return anon_inode_getfd("bpf-link",
3325 link->ops->poll ? &bpf_link_fops_poll : &bpf_link_fops,
3329 struct bpf_link *bpf_link_get_from_fd(u32 ufd)
3332 struct bpf_link *link;
3335 return ERR_PTR(-EBADF);
3336 if (fd_file(f)->f_op != &bpf_link_fops && fd_file(f)->f_op != &bpf_link_fops_poll)
3337 return ERR_PTR(-EINVAL);
3339 link = fd_file(f)->private_data;
3343 EXPORT_SYMBOL(bpf_link_get_from_fd);
3345 static void bpf_tracing_link_release(struct bpf_link *link)
3347 struct bpf_tracing_link *tr_link =
3348 container_of(link, struct bpf_tracing_link, link.link);
3350 WARN_ON_ONCE(bpf_trampoline_unlink_prog(&tr_link->link,
3351 tr_link->trampoline,
3352 tr_link->tgt_prog));
3354 bpf_trampoline_put(tr_link->trampoline);
3356 /* tgt_prog is NULL if target is a kernel function */
3357 if (tr_link->tgt_prog)
3358 bpf_prog_put(tr_link->tgt_prog);
3361 static void bpf_tracing_link_dealloc(struct bpf_link *link)
3363 struct bpf_tracing_link *tr_link =
3364 container_of(link, struct bpf_tracing_link, link.link);
3369 static void bpf_tracing_link_show_fdinfo(const struct bpf_link *link,
3370 struct seq_file *seq)
3372 struct bpf_tracing_link *tr_link =
3373 container_of(link, struct bpf_tracing_link, link.link);
3374 u32 target_btf_id, target_obj_id;
3376 bpf_trampoline_unpack_key(tr_link->trampoline->key,
3377 &target_obj_id, &target_btf_id);
3379 "attach_type:\t%d\n"
3380 "target_obj_id:\t%u\n"
3381 "target_btf_id:\t%u\n",
3382 tr_link->attach_type,
3387 static int bpf_tracing_link_fill_link_info(const struct bpf_link *link,
3388 struct bpf_link_info *info)
3390 struct bpf_tracing_link *tr_link =
3391 container_of(link, struct bpf_tracing_link, link.link);
3393 info->tracing.attach_type = tr_link->attach_type;
3394 bpf_trampoline_unpack_key(tr_link->trampoline->key,
3395 &info->tracing.target_obj_id,
3396 &info->tracing.target_btf_id);
3401 static const struct bpf_link_ops bpf_tracing_link_lops = {
3402 .release = bpf_tracing_link_release,
3403 .dealloc = bpf_tracing_link_dealloc,
3404 .show_fdinfo = bpf_tracing_link_show_fdinfo,
3405 .fill_link_info = bpf_tracing_link_fill_link_info,
3408 static int bpf_tracing_prog_attach(struct bpf_prog *prog,
3413 struct bpf_link_primer link_primer;
3414 struct bpf_prog *tgt_prog = NULL;
3415 struct bpf_trampoline *tr = NULL;
3416 struct bpf_tracing_link *link;
3420 switch (prog->type) {
3421 case BPF_PROG_TYPE_TRACING:
3422 if (prog->expected_attach_type != BPF_TRACE_FENTRY &&
3423 prog->expected_attach_type != BPF_TRACE_FEXIT &&
3424 prog->expected_attach_type != BPF_MODIFY_RETURN) {
3429 case BPF_PROG_TYPE_EXT:
3430 if (prog->expected_attach_type != 0) {
3435 case BPF_PROG_TYPE_LSM:
3436 if (prog->expected_attach_type != BPF_LSM_MAC) {
3446 if (!!tgt_prog_fd != !!btf_id) {
3453 * For now we only allow new targets for BPF_PROG_TYPE_EXT. If this
3454 * part would be changed to implement the same for
3455 * BPF_PROG_TYPE_TRACING, do not forget to update the way how
3456 * attach_tracing_prog flag is set.
3458 if (prog->type != BPF_PROG_TYPE_EXT) {
3463 tgt_prog = bpf_prog_get(tgt_prog_fd);
3464 if (IS_ERR(tgt_prog)) {
3465 err = PTR_ERR(tgt_prog);
3470 key = bpf_trampoline_compute_key(tgt_prog, NULL, btf_id);
3473 link = kzalloc(sizeof(*link), GFP_USER);
3478 bpf_link_init(&link->link.link, BPF_LINK_TYPE_TRACING,
3479 &bpf_tracing_link_lops, prog);
3480 link->attach_type = prog->expected_attach_type;
3481 link->link.cookie = bpf_cookie;
3483 mutex_lock(&prog->aux->dst_mutex);
3485 /* There are a few possible cases here:
3487 * - if prog->aux->dst_trampoline is set, the program was just loaded
3488 * and not yet attached to anything, so we can use the values stored
3491 * - if prog->aux->dst_trampoline is NULL, the program has already been
3492 * attached to a target and its initial target was cleared (below)
3494 * - if tgt_prog != NULL, the caller specified tgt_prog_fd +
3495 * target_btf_id using the link_create API.
3497 * - if tgt_prog == NULL when this function was called using the old
3498 * raw_tracepoint_open API, and we need a target from prog->aux
3500 * - if prog->aux->dst_trampoline and tgt_prog is NULL, the program
3501 * was detached and is going for re-attachment.
3503 * - if prog->aux->dst_trampoline is NULL and tgt_prog and prog->aux->attach_btf
3504 * are NULL, then program was already attached and user did not provide
3505 * tgt_prog_fd so we have no way to find out or create trampoline
3507 if (!prog->aux->dst_trampoline && !tgt_prog) {
3509 * Allow re-attach for TRACING and LSM programs. If it's
3510 * currently linked, bpf_trampoline_link_prog will fail.
3511 * EXT programs need to specify tgt_prog_fd, so they
3512 * re-attach in separate code path.
3514 if (prog->type != BPF_PROG_TYPE_TRACING &&
3515 prog->type != BPF_PROG_TYPE_LSM) {
3519 /* We can allow re-attach only if we have valid attach_btf. */
3520 if (!prog->aux->attach_btf) {
3524 btf_id = prog->aux->attach_btf_id;
3525 key = bpf_trampoline_compute_key(NULL, prog->aux->attach_btf, btf_id);
3528 if (!prog->aux->dst_trampoline ||
3529 (key && key != prog->aux->dst_trampoline->key)) {
3530 /* If there is no saved target, or the specified target is
3531 * different from the destination specified at load time, we
3532 * need a new trampoline and a check for compatibility
3534 struct bpf_attach_target_info tgt_info = {};
3536 err = bpf_check_attach_target(NULL, prog, tgt_prog, btf_id,
3541 if (tgt_info.tgt_mod) {
3542 module_put(prog->aux->mod);
3543 prog->aux->mod = tgt_info.tgt_mod;
3546 tr = bpf_trampoline_get(key, &tgt_info);
3552 /* The caller didn't specify a target, or the target was the
3553 * same as the destination supplied during program load. This
3554 * means we can reuse the trampoline and reference from program
3555 * load time, and there is no need to allocate a new one. This
3556 * can only happen once for any program, as the saved values in
3557 * prog->aux are cleared below.
3559 tr = prog->aux->dst_trampoline;
3560 tgt_prog = prog->aux->dst_prog;
3563 err = bpf_link_prime(&link->link.link, &link_primer);
3567 err = bpf_trampoline_link_prog(&link->link, tr, tgt_prog);
3569 bpf_link_cleanup(&link_primer);
3574 link->tgt_prog = tgt_prog;
3575 link->trampoline = tr;
3577 /* Always clear the trampoline and target prog from prog->aux to make
3578 * sure the original attach destination is not kept alive after a
3579 * program is (re-)attached to another target.
3581 if (prog->aux->dst_prog &&
3582 (tgt_prog_fd || tr != prog->aux->dst_trampoline))
3583 /* got extra prog ref from syscall, or attaching to different prog */
3584 bpf_prog_put(prog->aux->dst_prog);
3585 if (prog->aux->dst_trampoline && tr != prog->aux->dst_trampoline)
3586 /* we allocated a new trampoline, so free the old one */
3587 bpf_trampoline_put(prog->aux->dst_trampoline);
3589 prog->aux->dst_prog = NULL;
3590 prog->aux->dst_trampoline = NULL;
3591 mutex_unlock(&prog->aux->dst_mutex);
3593 return bpf_link_settle(&link_primer);
3595 if (tr && tr != prog->aux->dst_trampoline)
3596 bpf_trampoline_put(tr);
3597 mutex_unlock(&prog->aux->dst_mutex);
3600 if (tgt_prog_fd && tgt_prog)
3601 bpf_prog_put(tgt_prog);
3605 static void bpf_raw_tp_link_release(struct bpf_link *link)
3607 struct bpf_raw_tp_link *raw_tp =
3608 container_of(link, struct bpf_raw_tp_link, link);
3610 bpf_probe_unregister(raw_tp->btp, raw_tp);
3611 bpf_put_raw_tracepoint(raw_tp->btp);
3614 static void bpf_raw_tp_link_dealloc(struct bpf_link *link)
3616 struct bpf_raw_tp_link *raw_tp =
3617 container_of(link, struct bpf_raw_tp_link, link);
3622 static void bpf_raw_tp_link_show_fdinfo(const struct bpf_link *link,
3623 struct seq_file *seq)
3625 struct bpf_raw_tp_link *raw_tp_link =
3626 container_of(link, struct bpf_raw_tp_link, link);
3630 raw_tp_link->btp->tp->name);
3633 static int bpf_copy_to_user(char __user *ubuf, const char *buf, u32 ulen,
3636 if (ulen >= len + 1) {
3637 if (copy_to_user(ubuf, buf, len + 1))
3642 if (copy_to_user(ubuf, buf, ulen - 1))
3644 if (put_user(zero, ubuf + ulen - 1))
3652 static int bpf_raw_tp_link_fill_link_info(const struct bpf_link *link,
3653 struct bpf_link_info *info)
3655 struct bpf_raw_tp_link *raw_tp_link =
3656 container_of(link, struct bpf_raw_tp_link, link);
3657 char __user *ubuf = u64_to_user_ptr(info->raw_tracepoint.tp_name);
3658 const char *tp_name = raw_tp_link->btp->tp->name;
3659 u32 ulen = info->raw_tracepoint.tp_name_len;
3660 size_t tp_len = strlen(tp_name);
3665 info->raw_tracepoint.tp_name_len = tp_len + 1;
3670 return bpf_copy_to_user(ubuf, tp_name, ulen, tp_len);
3673 static const struct bpf_link_ops bpf_raw_tp_link_lops = {
3674 .release = bpf_raw_tp_link_release,
3675 .dealloc_deferred = bpf_raw_tp_link_dealloc,
3676 .show_fdinfo = bpf_raw_tp_link_show_fdinfo,
3677 .fill_link_info = bpf_raw_tp_link_fill_link_info,
3680 #ifdef CONFIG_PERF_EVENTS
3681 struct bpf_perf_link {
3682 struct bpf_link link;
3683 struct file *perf_file;
3686 static void bpf_perf_link_release(struct bpf_link *link)
3688 struct bpf_perf_link *perf_link = container_of(link, struct bpf_perf_link, link);
3689 struct perf_event *event = perf_link->perf_file->private_data;
3691 perf_event_free_bpf_prog(event);
3692 fput(perf_link->perf_file);
3695 static void bpf_perf_link_dealloc(struct bpf_link *link)
3697 struct bpf_perf_link *perf_link = container_of(link, struct bpf_perf_link, link);
3702 static int bpf_perf_link_fill_common(const struct perf_event *event,
3703 char __user *uname, u32 *ulenp,
3704 u64 *probe_offset, u64 *probe_addr,
3705 u32 *fd_type, unsigned long *missed)
3716 err = bpf_get_perf_event_info(event, &prog_id, fd_type, &buf,
3717 probe_offset, probe_addr, missed);
3731 err = bpf_copy_to_user(uname, buf, ulen, len);
3737 if (put_user(zero, uname))
3743 #ifdef CONFIG_KPROBE_EVENTS
3744 static int bpf_perf_link_fill_kprobe(const struct perf_event *event,
3745 struct bpf_link_info *info)
3747 unsigned long missed;
3753 uname = u64_to_user_ptr(info->perf_event.kprobe.func_name);
3754 ulen = info->perf_event.kprobe.name_len;
3755 err = bpf_perf_link_fill_common(event, uname, &ulen, &offset, &addr,
3759 if (type == BPF_FD_TYPE_KRETPROBE)
3760 info->perf_event.type = BPF_PERF_EVENT_KRETPROBE;
3762 info->perf_event.type = BPF_PERF_EVENT_KPROBE;
3763 info->perf_event.kprobe.name_len = ulen;
3764 info->perf_event.kprobe.offset = offset;
3765 info->perf_event.kprobe.missed = missed;
3766 if (!kallsyms_show_value(current_cred()))
3768 info->perf_event.kprobe.addr = addr;
3769 info->perf_event.kprobe.cookie = event->bpf_cookie;
3774 #ifdef CONFIG_UPROBE_EVENTS
3775 static int bpf_perf_link_fill_uprobe(const struct perf_event *event,
3776 struct bpf_link_info *info)
3783 uname = u64_to_user_ptr(info->perf_event.uprobe.file_name);
3784 ulen = info->perf_event.uprobe.name_len;
3785 err = bpf_perf_link_fill_common(event, uname, &ulen, &offset, &addr,
3790 if (type == BPF_FD_TYPE_URETPROBE)
3791 info->perf_event.type = BPF_PERF_EVENT_URETPROBE;
3793 info->perf_event.type = BPF_PERF_EVENT_UPROBE;
3794 info->perf_event.uprobe.name_len = ulen;
3795 info->perf_event.uprobe.offset = offset;
3796 info->perf_event.uprobe.cookie = event->bpf_cookie;
3801 static int bpf_perf_link_fill_probe(const struct perf_event *event,
3802 struct bpf_link_info *info)
3804 #ifdef CONFIG_KPROBE_EVENTS
3805 if (event->tp_event->flags & TRACE_EVENT_FL_KPROBE)
3806 return bpf_perf_link_fill_kprobe(event, info);
3808 #ifdef CONFIG_UPROBE_EVENTS
3809 if (event->tp_event->flags & TRACE_EVENT_FL_UPROBE)
3810 return bpf_perf_link_fill_uprobe(event, info);
3815 static int bpf_perf_link_fill_tracepoint(const struct perf_event *event,
3816 struct bpf_link_info *info)
3822 uname = u64_to_user_ptr(info->perf_event.tracepoint.tp_name);
3823 ulen = info->perf_event.tracepoint.name_len;
3824 err = bpf_perf_link_fill_common(event, uname, &ulen, NULL, NULL, NULL, NULL);
3828 info->perf_event.type = BPF_PERF_EVENT_TRACEPOINT;
3829 info->perf_event.tracepoint.name_len = ulen;
3830 info->perf_event.tracepoint.cookie = event->bpf_cookie;
3834 static int bpf_perf_link_fill_perf_event(const struct perf_event *event,
3835 struct bpf_link_info *info)
3837 info->perf_event.event.type = event->attr.type;
3838 info->perf_event.event.config = event->attr.config;
3839 info->perf_event.event.cookie = event->bpf_cookie;
3840 info->perf_event.type = BPF_PERF_EVENT_EVENT;
3844 static int bpf_perf_link_fill_link_info(const struct bpf_link *link,
3845 struct bpf_link_info *info)
3847 struct bpf_perf_link *perf_link;
3848 const struct perf_event *event;
3850 perf_link = container_of(link, struct bpf_perf_link, link);
3851 event = perf_get_event(perf_link->perf_file);
3853 return PTR_ERR(event);
3855 switch (event->prog->type) {
3856 case BPF_PROG_TYPE_PERF_EVENT:
3857 return bpf_perf_link_fill_perf_event(event, info);
3858 case BPF_PROG_TYPE_TRACEPOINT:
3859 return bpf_perf_link_fill_tracepoint(event, info);
3860 case BPF_PROG_TYPE_KPROBE:
3861 return bpf_perf_link_fill_probe(event, info);
3867 static const struct bpf_link_ops bpf_perf_link_lops = {
3868 .release = bpf_perf_link_release,
3869 .dealloc = bpf_perf_link_dealloc,
3870 .fill_link_info = bpf_perf_link_fill_link_info,
3873 static int bpf_perf_link_attach(const union bpf_attr *attr, struct bpf_prog *prog)
3875 struct bpf_link_primer link_primer;
3876 struct bpf_perf_link *link;
3877 struct perf_event *event;
3878 struct file *perf_file;
3881 if (attr->link_create.flags)
3884 perf_file = perf_event_get(attr->link_create.target_fd);
3885 if (IS_ERR(perf_file))
3886 return PTR_ERR(perf_file);
3888 link = kzalloc(sizeof(*link), GFP_USER);
3893 bpf_link_init(&link->link, BPF_LINK_TYPE_PERF_EVENT, &bpf_perf_link_lops, prog);
3894 link->perf_file = perf_file;
3896 err = bpf_link_prime(&link->link, &link_primer);
3902 event = perf_file->private_data;
3903 err = perf_event_set_bpf_prog(event, prog, attr->link_create.perf_event.bpf_cookie);
3905 bpf_link_cleanup(&link_primer);
3908 /* perf_event_set_bpf_prog() doesn't take its own refcnt on prog */
3911 return bpf_link_settle(&link_primer);
3918 static int bpf_perf_link_attach(const union bpf_attr *attr, struct bpf_prog *prog)
3922 #endif /* CONFIG_PERF_EVENTS */
3924 static int bpf_raw_tp_link_attach(struct bpf_prog *prog,
3925 const char __user *user_tp_name, u64 cookie)
3927 struct bpf_link_primer link_primer;
3928 struct bpf_raw_tp_link *link;
3929 struct bpf_raw_event_map *btp;
3930 const char *tp_name;
3934 switch (prog->type) {
3935 case BPF_PROG_TYPE_TRACING:
3936 case BPF_PROG_TYPE_EXT:
3937 case BPF_PROG_TYPE_LSM:
3939 /* The attach point for this category of programs
3940 * should be specified via btf_id during program load.
3943 if (prog->type == BPF_PROG_TYPE_TRACING &&
3944 prog->expected_attach_type == BPF_TRACE_RAW_TP) {
3945 tp_name = prog->aux->attach_func_name;
3948 return bpf_tracing_prog_attach(prog, 0, 0, 0);
3949 case BPF_PROG_TYPE_RAW_TRACEPOINT:
3950 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
3951 if (strncpy_from_user(buf, user_tp_name, sizeof(buf) - 1) < 0)
3953 buf[sizeof(buf) - 1] = 0;
3960 btp = bpf_get_raw_tracepoint(tp_name);
3964 link = kzalloc(sizeof(*link), GFP_USER);
3969 bpf_link_init_sleepable(&link->link, BPF_LINK_TYPE_RAW_TRACEPOINT,
3970 &bpf_raw_tp_link_lops, prog,
3971 tracepoint_is_faultable(btp->tp));
3973 link->cookie = cookie;
3975 err = bpf_link_prime(&link->link, &link_primer);
3981 err = bpf_probe_register(link->btp, link);
3983 bpf_link_cleanup(&link_primer);
3987 return bpf_link_settle(&link_primer);
3990 bpf_put_raw_tracepoint(btp);
3994 #define BPF_RAW_TRACEPOINT_OPEN_LAST_FIELD raw_tracepoint.cookie
3996 static int bpf_raw_tracepoint_open(const union bpf_attr *attr)
3998 struct bpf_prog *prog;
3999 void __user *tp_name;
4003 if (CHECK_ATTR(BPF_RAW_TRACEPOINT_OPEN))
4006 prog = bpf_prog_get(attr->raw_tracepoint.prog_fd);
4008 return PTR_ERR(prog);
4010 tp_name = u64_to_user_ptr(attr->raw_tracepoint.name);
4011 cookie = attr->raw_tracepoint.cookie;
4012 fd = bpf_raw_tp_link_attach(prog, tp_name, cookie);
4018 static enum bpf_prog_type
4019 attach_type_to_prog_type(enum bpf_attach_type attach_type)
4021 switch (attach_type) {
4022 case BPF_CGROUP_INET_INGRESS:
4023 case BPF_CGROUP_INET_EGRESS:
4024 return BPF_PROG_TYPE_CGROUP_SKB;
4025 case BPF_CGROUP_INET_SOCK_CREATE:
4026 case BPF_CGROUP_INET_SOCK_RELEASE:
4027 case BPF_CGROUP_INET4_POST_BIND:
4028 case BPF_CGROUP_INET6_POST_BIND:
4029 return BPF_PROG_TYPE_CGROUP_SOCK;
4030 case BPF_CGROUP_INET4_BIND:
4031 case BPF_CGROUP_INET6_BIND:
4032 case BPF_CGROUP_INET4_CONNECT:
4033 case BPF_CGROUP_INET6_CONNECT:
4034 case BPF_CGROUP_UNIX_CONNECT:
4035 case BPF_CGROUP_INET4_GETPEERNAME:
4036 case BPF_CGROUP_INET6_GETPEERNAME:
4037 case BPF_CGROUP_UNIX_GETPEERNAME:
4038 case BPF_CGROUP_INET4_GETSOCKNAME:
4039 case BPF_CGROUP_INET6_GETSOCKNAME:
4040 case BPF_CGROUP_UNIX_GETSOCKNAME:
4041 case BPF_CGROUP_UDP4_SENDMSG:
4042 case BPF_CGROUP_UDP6_SENDMSG:
4043 case BPF_CGROUP_UNIX_SENDMSG:
4044 case BPF_CGROUP_UDP4_RECVMSG:
4045 case BPF_CGROUP_UDP6_RECVMSG:
4046 case BPF_CGROUP_UNIX_RECVMSG:
4047 return BPF_PROG_TYPE_CGROUP_SOCK_ADDR;
4048 case BPF_CGROUP_SOCK_OPS:
4049 return BPF_PROG_TYPE_SOCK_OPS;
4050 case BPF_CGROUP_DEVICE:
4051 return BPF_PROG_TYPE_CGROUP_DEVICE;
4052 case BPF_SK_MSG_VERDICT:
4053 return BPF_PROG_TYPE_SK_MSG;
4054 case BPF_SK_SKB_STREAM_PARSER:
4055 case BPF_SK_SKB_STREAM_VERDICT:
4056 case BPF_SK_SKB_VERDICT:
4057 return BPF_PROG_TYPE_SK_SKB;
4058 case BPF_LIRC_MODE2:
4059 return BPF_PROG_TYPE_LIRC_MODE2;
4060 case BPF_FLOW_DISSECTOR:
4061 return BPF_PROG_TYPE_FLOW_DISSECTOR;
4062 case BPF_CGROUP_SYSCTL:
4063 return BPF_PROG_TYPE_CGROUP_SYSCTL;
4064 case BPF_CGROUP_GETSOCKOPT:
4065 case BPF_CGROUP_SETSOCKOPT:
4066 return BPF_PROG_TYPE_CGROUP_SOCKOPT;
4067 case BPF_TRACE_ITER:
4068 case BPF_TRACE_RAW_TP:
4069 case BPF_TRACE_FENTRY:
4070 case BPF_TRACE_FEXIT:
4071 case BPF_MODIFY_RETURN:
4072 return BPF_PROG_TYPE_TRACING;
4074 return BPF_PROG_TYPE_LSM;
4076 return BPF_PROG_TYPE_SK_LOOKUP;
4078 return BPF_PROG_TYPE_XDP;
4079 case BPF_LSM_CGROUP:
4080 return BPF_PROG_TYPE_LSM;
4081 case BPF_TCX_INGRESS:
4082 case BPF_TCX_EGRESS:
4083 case BPF_NETKIT_PRIMARY:
4084 case BPF_NETKIT_PEER:
4085 return BPF_PROG_TYPE_SCHED_CLS;
4087 return BPF_PROG_TYPE_UNSPEC;
4091 static int bpf_prog_attach_check_attach_type(const struct bpf_prog *prog,
4092 enum bpf_attach_type attach_type)
4094 enum bpf_prog_type ptype;
4096 switch (prog->type) {
4097 case BPF_PROG_TYPE_CGROUP_SOCK:
4098 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
4099 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
4100 case BPF_PROG_TYPE_SK_LOOKUP:
4101 return attach_type == prog->expected_attach_type ? 0 : -EINVAL;
4102 case BPF_PROG_TYPE_CGROUP_SKB:
4103 if (!bpf_token_capable(prog->aux->token, CAP_NET_ADMIN))
4104 /* cg-skb progs can be loaded by unpriv user.
4105 * check permissions at attach time.
4109 ptype = attach_type_to_prog_type(attach_type);
4110 if (prog->type != ptype)
4113 return prog->enforce_expected_attach_type &&
4114 prog->expected_attach_type != attach_type ?
4116 case BPF_PROG_TYPE_EXT:
4118 case BPF_PROG_TYPE_NETFILTER:
4119 if (attach_type != BPF_NETFILTER)
4122 case BPF_PROG_TYPE_PERF_EVENT:
4123 case BPF_PROG_TYPE_TRACEPOINT:
4124 if (attach_type != BPF_PERF_EVENT)
4127 case BPF_PROG_TYPE_KPROBE:
4128 if (prog->expected_attach_type == BPF_TRACE_KPROBE_MULTI &&
4129 attach_type != BPF_TRACE_KPROBE_MULTI)
4131 if (prog->expected_attach_type == BPF_TRACE_KPROBE_SESSION &&
4132 attach_type != BPF_TRACE_KPROBE_SESSION)
4134 if (prog->expected_attach_type == BPF_TRACE_UPROBE_MULTI &&
4135 attach_type != BPF_TRACE_UPROBE_MULTI)
4137 if (prog->expected_attach_type == BPF_TRACE_UPROBE_SESSION &&
4138 attach_type != BPF_TRACE_UPROBE_SESSION)
4140 if (attach_type != BPF_PERF_EVENT &&
4141 attach_type != BPF_TRACE_KPROBE_MULTI &&
4142 attach_type != BPF_TRACE_KPROBE_SESSION &&
4143 attach_type != BPF_TRACE_UPROBE_MULTI &&
4144 attach_type != BPF_TRACE_UPROBE_SESSION)
4147 case BPF_PROG_TYPE_SCHED_CLS:
4148 if (attach_type != BPF_TCX_INGRESS &&
4149 attach_type != BPF_TCX_EGRESS &&
4150 attach_type != BPF_NETKIT_PRIMARY &&
4151 attach_type != BPF_NETKIT_PEER)
4155 ptype = attach_type_to_prog_type(attach_type);
4156 if (ptype == BPF_PROG_TYPE_UNSPEC || ptype != prog->type)
4162 #define BPF_PROG_ATTACH_LAST_FIELD expected_revision
4164 #define BPF_F_ATTACH_MASK_BASE \
4165 (BPF_F_ALLOW_OVERRIDE | \
4166 BPF_F_ALLOW_MULTI | \
4169 #define BPF_F_ATTACH_MASK_MPROG \
4176 static int bpf_prog_attach(const union bpf_attr *attr)
4178 enum bpf_prog_type ptype;
4179 struct bpf_prog *prog;
4182 if (CHECK_ATTR(BPF_PROG_ATTACH))
4185 ptype = attach_type_to_prog_type(attr->attach_type);
4186 if (ptype == BPF_PROG_TYPE_UNSPEC)
4188 if (bpf_mprog_supported(ptype)) {
4189 if (attr->attach_flags & ~BPF_F_ATTACH_MASK_MPROG)
4192 if (attr->attach_flags & ~BPF_F_ATTACH_MASK_BASE)
4194 if (attr->relative_fd ||
4195 attr->expected_revision)
4199 prog = bpf_prog_get_type(attr->attach_bpf_fd, ptype);
4201 return PTR_ERR(prog);
4203 if (bpf_prog_attach_check_attach_type(prog, attr->attach_type)) {
4209 case BPF_PROG_TYPE_SK_SKB:
4210 case BPF_PROG_TYPE_SK_MSG:
4211 ret = sock_map_get_from_fd(attr, prog);
4213 case BPF_PROG_TYPE_LIRC_MODE2:
4214 ret = lirc_prog_attach(attr, prog);
4216 case BPF_PROG_TYPE_FLOW_DISSECTOR:
4217 ret = netns_bpf_prog_attach(attr, prog);
4219 case BPF_PROG_TYPE_CGROUP_DEVICE:
4220 case BPF_PROG_TYPE_CGROUP_SKB:
4221 case BPF_PROG_TYPE_CGROUP_SOCK:
4222 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
4223 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
4224 case BPF_PROG_TYPE_CGROUP_SYSCTL:
4225 case BPF_PROG_TYPE_SOCK_OPS:
4226 case BPF_PROG_TYPE_LSM:
4227 if (ptype == BPF_PROG_TYPE_LSM &&
4228 prog->expected_attach_type != BPF_LSM_CGROUP)
4231 ret = cgroup_bpf_prog_attach(attr, ptype, prog);
4233 case BPF_PROG_TYPE_SCHED_CLS:
4234 if (attr->attach_type == BPF_TCX_INGRESS ||
4235 attr->attach_type == BPF_TCX_EGRESS)
4236 ret = tcx_prog_attach(attr, prog);
4238 ret = netkit_prog_attach(attr, prog);
4249 #define BPF_PROG_DETACH_LAST_FIELD expected_revision
4251 static int bpf_prog_detach(const union bpf_attr *attr)
4253 struct bpf_prog *prog = NULL;
4254 enum bpf_prog_type ptype;
4257 if (CHECK_ATTR(BPF_PROG_DETACH))
4260 ptype = attach_type_to_prog_type(attr->attach_type);
4261 if (bpf_mprog_supported(ptype)) {
4262 if (ptype == BPF_PROG_TYPE_UNSPEC)
4264 if (attr->attach_flags & ~BPF_F_ATTACH_MASK_MPROG)
4266 if (attr->attach_bpf_fd) {
4267 prog = bpf_prog_get_type(attr->attach_bpf_fd, ptype);
4269 return PTR_ERR(prog);
4271 } else if (attr->attach_flags ||
4272 attr->relative_fd ||
4273 attr->expected_revision) {
4278 case BPF_PROG_TYPE_SK_MSG:
4279 case BPF_PROG_TYPE_SK_SKB:
4280 ret = sock_map_prog_detach(attr, ptype);
4282 case BPF_PROG_TYPE_LIRC_MODE2:
4283 ret = lirc_prog_detach(attr);
4285 case BPF_PROG_TYPE_FLOW_DISSECTOR:
4286 ret = netns_bpf_prog_detach(attr, ptype);
4288 case BPF_PROG_TYPE_CGROUP_DEVICE:
4289 case BPF_PROG_TYPE_CGROUP_SKB:
4290 case BPF_PROG_TYPE_CGROUP_SOCK:
4291 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
4292 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
4293 case BPF_PROG_TYPE_CGROUP_SYSCTL:
4294 case BPF_PROG_TYPE_SOCK_OPS:
4295 case BPF_PROG_TYPE_LSM:
4296 ret = cgroup_bpf_prog_detach(attr, ptype);
4298 case BPF_PROG_TYPE_SCHED_CLS:
4299 if (attr->attach_type == BPF_TCX_INGRESS ||
4300 attr->attach_type == BPF_TCX_EGRESS)
4301 ret = tcx_prog_detach(attr, prog);
4303 ret = netkit_prog_detach(attr, prog);
4314 #define BPF_PROG_QUERY_LAST_FIELD query.revision
4316 static int bpf_prog_query(const union bpf_attr *attr,
4317 union bpf_attr __user *uattr)
4319 if (!bpf_net_capable())
4321 if (CHECK_ATTR(BPF_PROG_QUERY))
4323 if (attr->query.query_flags & ~BPF_F_QUERY_EFFECTIVE)
4326 switch (attr->query.attach_type) {
4327 case BPF_CGROUP_INET_INGRESS:
4328 case BPF_CGROUP_INET_EGRESS:
4329 case BPF_CGROUP_INET_SOCK_CREATE:
4330 case BPF_CGROUP_INET_SOCK_RELEASE:
4331 case BPF_CGROUP_INET4_BIND:
4332 case BPF_CGROUP_INET6_BIND:
4333 case BPF_CGROUP_INET4_POST_BIND:
4334 case BPF_CGROUP_INET6_POST_BIND:
4335 case BPF_CGROUP_INET4_CONNECT:
4336 case BPF_CGROUP_INET6_CONNECT:
4337 case BPF_CGROUP_UNIX_CONNECT:
4338 case BPF_CGROUP_INET4_GETPEERNAME:
4339 case BPF_CGROUP_INET6_GETPEERNAME:
4340 case BPF_CGROUP_UNIX_GETPEERNAME:
4341 case BPF_CGROUP_INET4_GETSOCKNAME:
4342 case BPF_CGROUP_INET6_GETSOCKNAME:
4343 case BPF_CGROUP_UNIX_GETSOCKNAME:
4344 case BPF_CGROUP_UDP4_SENDMSG:
4345 case BPF_CGROUP_UDP6_SENDMSG:
4346 case BPF_CGROUP_UNIX_SENDMSG:
4347 case BPF_CGROUP_UDP4_RECVMSG:
4348 case BPF_CGROUP_UDP6_RECVMSG:
4349 case BPF_CGROUP_UNIX_RECVMSG:
4350 case BPF_CGROUP_SOCK_OPS:
4351 case BPF_CGROUP_DEVICE:
4352 case BPF_CGROUP_SYSCTL:
4353 case BPF_CGROUP_GETSOCKOPT:
4354 case BPF_CGROUP_SETSOCKOPT:
4355 case BPF_LSM_CGROUP:
4356 return cgroup_bpf_prog_query(attr, uattr);
4357 case BPF_LIRC_MODE2:
4358 return lirc_prog_query(attr, uattr);
4359 case BPF_FLOW_DISSECTOR:
4361 return netns_bpf_prog_query(attr, uattr);
4362 case BPF_SK_SKB_STREAM_PARSER:
4363 case BPF_SK_SKB_STREAM_VERDICT:
4364 case BPF_SK_MSG_VERDICT:
4365 case BPF_SK_SKB_VERDICT:
4366 return sock_map_bpf_prog_query(attr, uattr);
4367 case BPF_TCX_INGRESS:
4368 case BPF_TCX_EGRESS:
4369 return tcx_prog_query(attr, uattr);
4370 case BPF_NETKIT_PRIMARY:
4371 case BPF_NETKIT_PEER:
4372 return netkit_prog_query(attr, uattr);
4378 #define BPF_PROG_TEST_RUN_LAST_FIELD test.batch_size
4380 static int bpf_prog_test_run(const union bpf_attr *attr,
4381 union bpf_attr __user *uattr)
4383 struct bpf_prog *prog;
4384 int ret = -ENOTSUPP;
4386 if (CHECK_ATTR(BPF_PROG_TEST_RUN))
4389 if ((attr->test.ctx_size_in && !attr->test.ctx_in) ||
4390 (!attr->test.ctx_size_in && attr->test.ctx_in))
4393 if ((attr->test.ctx_size_out && !attr->test.ctx_out) ||
4394 (!attr->test.ctx_size_out && attr->test.ctx_out))
4397 prog = bpf_prog_get(attr->test.prog_fd);
4399 return PTR_ERR(prog);
4401 if (prog->aux->ops->test_run)
4402 ret = prog->aux->ops->test_run(prog, attr, uattr);
4408 #define BPF_OBJ_GET_NEXT_ID_LAST_FIELD next_id
4410 static int bpf_obj_get_next_id(const union bpf_attr *attr,
4411 union bpf_attr __user *uattr,
4415 u32 next_id = attr->start_id;
4418 if (CHECK_ATTR(BPF_OBJ_GET_NEXT_ID) || next_id >= INT_MAX)
4421 if (!capable(CAP_SYS_ADMIN))
4426 if (!idr_get_next(idr, &next_id))
4428 spin_unlock_bh(lock);
4431 err = put_user(next_id, &uattr->next_id);
4436 struct bpf_map *bpf_map_get_curr_or_next(u32 *id)
4438 struct bpf_map *map;
4440 spin_lock_bh(&map_idr_lock);
4442 map = idr_get_next(&map_idr, id);
4444 map = __bpf_map_inc_not_zero(map, false);
4450 spin_unlock_bh(&map_idr_lock);
4455 struct bpf_prog *bpf_prog_get_curr_or_next(u32 *id)
4457 struct bpf_prog *prog;
4459 spin_lock_bh(&prog_idr_lock);
4461 prog = idr_get_next(&prog_idr, id);
4463 prog = bpf_prog_inc_not_zero(prog);
4469 spin_unlock_bh(&prog_idr_lock);
4474 #define BPF_PROG_GET_FD_BY_ID_LAST_FIELD prog_id
4476 struct bpf_prog *bpf_prog_by_id(u32 id)
4478 struct bpf_prog *prog;
4481 return ERR_PTR(-ENOENT);
4483 spin_lock_bh(&prog_idr_lock);
4484 prog = idr_find(&prog_idr, id);
4486 prog = bpf_prog_inc_not_zero(prog);
4488 prog = ERR_PTR(-ENOENT);
4489 spin_unlock_bh(&prog_idr_lock);
4493 static int bpf_prog_get_fd_by_id(const union bpf_attr *attr)
4495 struct bpf_prog *prog;
4496 u32 id = attr->prog_id;
4499 if (CHECK_ATTR(BPF_PROG_GET_FD_BY_ID))
4502 if (!capable(CAP_SYS_ADMIN))
4505 prog = bpf_prog_by_id(id);
4507 return PTR_ERR(prog);
4509 fd = bpf_prog_new_fd(prog);
4516 #define BPF_MAP_GET_FD_BY_ID_LAST_FIELD open_flags
4518 static int bpf_map_get_fd_by_id(const union bpf_attr *attr)
4520 struct bpf_map *map;
4521 u32 id = attr->map_id;
4525 if (CHECK_ATTR(BPF_MAP_GET_FD_BY_ID) ||
4526 attr->open_flags & ~BPF_OBJ_FLAG_MASK)
4529 if (!capable(CAP_SYS_ADMIN))
4532 f_flags = bpf_get_file_flag(attr->open_flags);
4536 spin_lock_bh(&map_idr_lock);
4537 map = idr_find(&map_idr, id);
4539 map = __bpf_map_inc_not_zero(map, true);
4541 map = ERR_PTR(-ENOENT);
4542 spin_unlock_bh(&map_idr_lock);
4545 return PTR_ERR(map);
4547 fd = bpf_map_new_fd(map, f_flags);
4549 bpf_map_put_with_uref(map);
4554 static const struct bpf_map *bpf_map_from_imm(const struct bpf_prog *prog,
4555 unsigned long addr, u32 *off,
4558 const struct bpf_map *map;
4561 mutex_lock(&prog->aux->used_maps_mutex);
4562 for (i = 0, *off = 0; i < prog->aux->used_map_cnt; i++) {
4563 map = prog->aux->used_maps[i];
4564 if (map == (void *)addr) {
4565 *type = BPF_PSEUDO_MAP_FD;
4568 if (!map->ops->map_direct_value_meta)
4570 if (!map->ops->map_direct_value_meta(map, addr, off)) {
4571 *type = BPF_PSEUDO_MAP_VALUE;
4578 mutex_unlock(&prog->aux->used_maps_mutex);
4582 static struct bpf_insn *bpf_insn_prepare_dump(const struct bpf_prog *prog,
4583 const struct cred *f_cred)
4585 const struct bpf_map *map;
4586 struct bpf_insn *insns;
4592 insns = kmemdup(prog->insnsi, bpf_prog_insn_size(prog),
4597 for (i = 0; i < prog->len; i++) {
4598 code = insns[i].code;
4600 if (code == (BPF_JMP | BPF_TAIL_CALL)) {
4601 insns[i].code = BPF_JMP | BPF_CALL;
4602 insns[i].imm = BPF_FUNC_tail_call;
4605 if (code == (BPF_JMP | BPF_CALL) ||
4606 code == (BPF_JMP | BPF_CALL_ARGS)) {
4607 if (code == (BPF_JMP | BPF_CALL_ARGS))
4608 insns[i].code = BPF_JMP | BPF_CALL;
4609 if (!bpf_dump_raw_ok(f_cred))
4613 if (BPF_CLASS(code) == BPF_LDX && BPF_MODE(code) == BPF_PROBE_MEM) {
4614 insns[i].code = BPF_LDX | BPF_SIZE(code) | BPF_MEM;
4618 if ((BPF_CLASS(code) == BPF_LDX || BPF_CLASS(code) == BPF_STX ||
4619 BPF_CLASS(code) == BPF_ST) && BPF_MODE(code) == BPF_PROBE_MEM32) {
4620 insns[i].code = BPF_CLASS(code) | BPF_SIZE(code) | BPF_MEM;
4624 if (code != (BPF_LD | BPF_IMM | BPF_DW))
4627 imm = ((u64)insns[i + 1].imm << 32) | (u32)insns[i].imm;
4628 map = bpf_map_from_imm(prog, imm, &off, &type);
4630 insns[i].src_reg = type;
4631 insns[i].imm = map->id;
4632 insns[i + 1].imm = off;
4640 static int set_info_rec_size(struct bpf_prog_info *info)
4643 * Ensure info.*_rec_size is the same as kernel expected size
4647 * Only allow zero *_rec_size if both _rec_size and _cnt are
4648 * zero. In this case, the kernel will set the expected
4649 * _rec_size back to the info.
4652 if ((info->nr_func_info || info->func_info_rec_size) &&
4653 info->func_info_rec_size != sizeof(struct bpf_func_info))
4656 if ((info->nr_line_info || info->line_info_rec_size) &&
4657 info->line_info_rec_size != sizeof(struct bpf_line_info))
4660 if ((info->nr_jited_line_info || info->jited_line_info_rec_size) &&
4661 info->jited_line_info_rec_size != sizeof(__u64))
4664 info->func_info_rec_size = sizeof(struct bpf_func_info);
4665 info->line_info_rec_size = sizeof(struct bpf_line_info);
4666 info->jited_line_info_rec_size = sizeof(__u64);
4671 static int bpf_prog_get_info_by_fd(struct file *file,
4672 struct bpf_prog *prog,
4673 const union bpf_attr *attr,
4674 union bpf_attr __user *uattr)
4676 struct bpf_prog_info __user *uinfo = u64_to_user_ptr(attr->info.info);
4677 struct btf *attach_btf = bpf_prog_get_target_btf(prog);
4678 struct bpf_prog_info info;
4679 u32 info_len = attr->info.info_len;
4680 struct bpf_prog_kstats stats;
4681 char __user *uinsns;
4685 err = bpf_check_uarg_tail_zero(USER_BPFPTR(uinfo), sizeof(info), info_len);
4688 info_len = min_t(u32, sizeof(info), info_len);
4690 memset(&info, 0, sizeof(info));
4691 if (copy_from_user(&info, uinfo, info_len))
4694 info.type = prog->type;
4695 info.id = prog->aux->id;
4696 info.load_time = prog->aux->load_time;
4697 info.created_by_uid = from_kuid_munged(current_user_ns(),
4698 prog->aux->user->uid);
4699 info.gpl_compatible = prog->gpl_compatible;
4701 memcpy(info.tag, prog->tag, sizeof(prog->tag));
4702 memcpy(info.name, prog->aux->name, sizeof(prog->aux->name));
4704 mutex_lock(&prog->aux->used_maps_mutex);
4705 ulen = info.nr_map_ids;
4706 info.nr_map_ids = prog->aux->used_map_cnt;
4707 ulen = min_t(u32, info.nr_map_ids, ulen);
4709 u32 __user *user_map_ids = u64_to_user_ptr(info.map_ids);
4712 for (i = 0; i < ulen; i++)
4713 if (put_user(prog->aux->used_maps[i]->id,
4714 &user_map_ids[i])) {
4715 mutex_unlock(&prog->aux->used_maps_mutex);
4719 mutex_unlock(&prog->aux->used_maps_mutex);
4721 err = set_info_rec_size(&info);
4725 bpf_prog_get_stats(prog, &stats);
4726 info.run_time_ns = stats.nsecs;
4727 info.run_cnt = stats.cnt;
4728 info.recursion_misses = stats.misses;
4730 info.verified_insns = prog->aux->verified_insns;
4732 if (!bpf_capable()) {
4733 info.jited_prog_len = 0;
4734 info.xlated_prog_len = 0;
4735 info.nr_jited_ksyms = 0;
4736 info.nr_jited_func_lens = 0;
4737 info.nr_func_info = 0;
4738 info.nr_line_info = 0;
4739 info.nr_jited_line_info = 0;
4743 ulen = info.xlated_prog_len;
4744 info.xlated_prog_len = bpf_prog_insn_size(prog);
4745 if (info.xlated_prog_len && ulen) {
4746 struct bpf_insn *insns_sanitized;
4749 if (prog->blinded && !bpf_dump_raw_ok(file->f_cred)) {
4750 info.xlated_prog_insns = 0;
4753 insns_sanitized = bpf_insn_prepare_dump(prog, file->f_cred);
4754 if (!insns_sanitized)
4756 uinsns = u64_to_user_ptr(info.xlated_prog_insns);
4757 ulen = min_t(u32, info.xlated_prog_len, ulen);
4758 fault = copy_to_user(uinsns, insns_sanitized, ulen);
4759 kfree(insns_sanitized);
4764 if (bpf_prog_is_offloaded(prog->aux)) {
4765 err = bpf_prog_offload_info_fill(&info, prog);
4771 /* NOTE: the following code is supposed to be skipped for offload.
4772 * bpf_prog_offload_info_fill() is the place to fill similar fields
4775 ulen = info.jited_prog_len;
4776 if (prog->aux->func_cnt) {
4779 info.jited_prog_len = 0;
4780 for (i = 0; i < prog->aux->func_cnt; i++)
4781 info.jited_prog_len += prog->aux->func[i]->jited_len;
4783 info.jited_prog_len = prog->jited_len;
4786 if (info.jited_prog_len && ulen) {
4787 if (bpf_dump_raw_ok(file->f_cred)) {
4788 uinsns = u64_to_user_ptr(info.jited_prog_insns);
4789 ulen = min_t(u32, info.jited_prog_len, ulen);
4791 /* for multi-function programs, copy the JITed
4792 * instructions for all the functions
4794 if (prog->aux->func_cnt) {
4799 for (i = 0; i < prog->aux->func_cnt; i++) {
4800 len = prog->aux->func[i]->jited_len;
4801 len = min_t(u32, len, free);
4802 img = (u8 *) prog->aux->func[i]->bpf_func;
4803 if (copy_to_user(uinsns, img, len))
4811 if (copy_to_user(uinsns, prog->bpf_func, ulen))
4815 info.jited_prog_insns = 0;
4819 ulen = info.nr_jited_ksyms;
4820 info.nr_jited_ksyms = prog->aux->func_cnt ? : 1;
4822 if (bpf_dump_raw_ok(file->f_cred)) {
4823 unsigned long ksym_addr;
4824 u64 __user *user_ksyms;
4827 /* copy the address of the kernel symbol
4828 * corresponding to each function
4830 ulen = min_t(u32, info.nr_jited_ksyms, ulen);
4831 user_ksyms = u64_to_user_ptr(info.jited_ksyms);
4832 if (prog->aux->func_cnt) {
4833 for (i = 0; i < ulen; i++) {
4834 ksym_addr = (unsigned long)
4835 prog->aux->func[i]->bpf_func;
4836 if (put_user((u64) ksym_addr,
4841 ksym_addr = (unsigned long) prog->bpf_func;
4842 if (put_user((u64) ksym_addr, &user_ksyms[0]))
4846 info.jited_ksyms = 0;
4850 ulen = info.nr_jited_func_lens;
4851 info.nr_jited_func_lens = prog->aux->func_cnt ? : 1;
4853 if (bpf_dump_raw_ok(file->f_cred)) {
4854 u32 __user *user_lens;
4857 /* copy the JITed image lengths for each function */
4858 ulen = min_t(u32, info.nr_jited_func_lens, ulen);
4859 user_lens = u64_to_user_ptr(info.jited_func_lens);
4860 if (prog->aux->func_cnt) {
4861 for (i = 0; i < ulen; i++) {
4863 prog->aux->func[i]->jited_len;
4864 if (put_user(func_len, &user_lens[i]))
4868 func_len = prog->jited_len;
4869 if (put_user(func_len, &user_lens[0]))
4873 info.jited_func_lens = 0;
4878 info.btf_id = btf_obj_id(prog->aux->btf);
4879 info.attach_btf_id = prog->aux->attach_btf_id;
4881 info.attach_btf_obj_id = btf_obj_id(attach_btf);
4883 ulen = info.nr_func_info;
4884 info.nr_func_info = prog->aux->func_info_cnt;
4885 if (info.nr_func_info && ulen) {
4886 char __user *user_finfo;
4888 user_finfo = u64_to_user_ptr(info.func_info);
4889 ulen = min_t(u32, info.nr_func_info, ulen);
4890 if (copy_to_user(user_finfo, prog->aux->func_info,
4891 info.func_info_rec_size * ulen))
4895 ulen = info.nr_line_info;
4896 info.nr_line_info = prog->aux->nr_linfo;
4897 if (info.nr_line_info && ulen) {
4898 __u8 __user *user_linfo;
4900 user_linfo = u64_to_user_ptr(info.line_info);
4901 ulen = min_t(u32, info.nr_line_info, ulen);
4902 if (copy_to_user(user_linfo, prog->aux->linfo,
4903 info.line_info_rec_size * ulen))
4907 ulen = info.nr_jited_line_info;
4908 if (prog->aux->jited_linfo)
4909 info.nr_jited_line_info = prog->aux->nr_linfo;
4911 info.nr_jited_line_info = 0;
4912 if (info.nr_jited_line_info && ulen) {
4913 if (bpf_dump_raw_ok(file->f_cred)) {
4914 unsigned long line_addr;
4915 __u64 __user *user_linfo;
4918 user_linfo = u64_to_user_ptr(info.jited_line_info);
4919 ulen = min_t(u32, info.nr_jited_line_info, ulen);
4920 for (i = 0; i < ulen; i++) {
4921 line_addr = (unsigned long)prog->aux->jited_linfo[i];
4922 if (put_user((__u64)line_addr, &user_linfo[i]))
4926 info.jited_line_info = 0;
4930 ulen = info.nr_prog_tags;
4931 info.nr_prog_tags = prog->aux->func_cnt ? : 1;
4933 __u8 __user (*user_prog_tags)[BPF_TAG_SIZE];
4936 user_prog_tags = u64_to_user_ptr(info.prog_tags);
4937 ulen = min_t(u32, info.nr_prog_tags, ulen);
4938 if (prog->aux->func_cnt) {
4939 for (i = 0; i < ulen; i++) {
4940 if (copy_to_user(user_prog_tags[i],
4941 prog->aux->func[i]->tag,
4946 if (copy_to_user(user_prog_tags[0],
4947 prog->tag, BPF_TAG_SIZE))
4953 if (copy_to_user(uinfo, &info, info_len) ||
4954 put_user(info_len, &uattr->info.info_len))
4960 static int bpf_map_get_info_by_fd(struct file *file,
4961 struct bpf_map *map,
4962 const union bpf_attr *attr,
4963 union bpf_attr __user *uattr)
4965 struct bpf_map_info __user *uinfo = u64_to_user_ptr(attr->info.info);
4966 struct bpf_map_info info;
4967 u32 info_len = attr->info.info_len;
4970 err = bpf_check_uarg_tail_zero(USER_BPFPTR(uinfo), sizeof(info), info_len);
4973 info_len = min_t(u32, sizeof(info), info_len);
4975 memset(&info, 0, sizeof(info));
4976 info.type = map->map_type;
4978 info.key_size = map->key_size;
4979 info.value_size = map->value_size;
4980 info.max_entries = map->max_entries;
4981 info.map_flags = map->map_flags;
4982 info.map_extra = map->map_extra;
4983 memcpy(info.name, map->name, sizeof(map->name));
4986 info.btf_id = btf_obj_id(map->btf);
4987 info.btf_key_type_id = map->btf_key_type_id;
4988 info.btf_value_type_id = map->btf_value_type_id;
4990 info.btf_vmlinux_value_type_id = map->btf_vmlinux_value_type_id;
4991 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS)
4992 bpf_map_struct_ops_info_fill(&info, map);
4994 if (bpf_map_is_offloaded(map)) {
4995 err = bpf_map_offload_info_fill(&info, map);
5000 if (copy_to_user(uinfo, &info, info_len) ||
5001 put_user(info_len, &uattr->info.info_len))
5007 static int bpf_btf_get_info_by_fd(struct file *file,
5009 const union bpf_attr *attr,
5010 union bpf_attr __user *uattr)
5012 struct bpf_btf_info __user *uinfo = u64_to_user_ptr(attr->info.info);
5013 u32 info_len = attr->info.info_len;
5016 err = bpf_check_uarg_tail_zero(USER_BPFPTR(uinfo), sizeof(*uinfo), info_len);
5020 return btf_get_info_by_fd(btf, attr, uattr);
5023 static int bpf_link_get_info_by_fd(struct file *file,
5024 struct bpf_link *link,
5025 const union bpf_attr *attr,
5026 union bpf_attr __user *uattr)
5028 struct bpf_link_info __user *uinfo = u64_to_user_ptr(attr->info.info);
5029 struct bpf_link_info info;
5030 u32 info_len = attr->info.info_len;
5033 err = bpf_check_uarg_tail_zero(USER_BPFPTR(uinfo), sizeof(info), info_len);
5036 info_len = min_t(u32, sizeof(info), info_len);
5038 memset(&info, 0, sizeof(info));
5039 if (copy_from_user(&info, uinfo, info_len))
5042 info.type = link->type;
5045 info.prog_id = link->prog->aux->id;
5047 if (link->ops->fill_link_info) {
5048 err = link->ops->fill_link_info(link, &info);
5053 if (copy_to_user(uinfo, &info, info_len) ||
5054 put_user(info_len, &uattr->info.info_len))
5061 #define BPF_OBJ_GET_INFO_BY_FD_LAST_FIELD info.info
5063 static int bpf_obj_get_info_by_fd(const union bpf_attr *attr,
5064 union bpf_attr __user *uattr)
5066 if (CHECK_ATTR(BPF_OBJ_GET_INFO_BY_FD))
5069 CLASS(fd, f)(attr->info.bpf_fd);
5073 if (fd_file(f)->f_op == &bpf_prog_fops)
5074 return bpf_prog_get_info_by_fd(fd_file(f), fd_file(f)->private_data, attr,
5076 else if (fd_file(f)->f_op == &bpf_map_fops)
5077 return bpf_map_get_info_by_fd(fd_file(f), fd_file(f)->private_data, attr,
5079 else if (fd_file(f)->f_op == &btf_fops)
5080 return bpf_btf_get_info_by_fd(fd_file(f), fd_file(f)->private_data, attr, uattr);
5081 else if (fd_file(f)->f_op == &bpf_link_fops || fd_file(f)->f_op == &bpf_link_fops_poll)
5082 return bpf_link_get_info_by_fd(fd_file(f), fd_file(f)->private_data,
5087 #define BPF_BTF_LOAD_LAST_FIELD btf_token_fd
5089 static int bpf_btf_load(const union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size)
5091 struct bpf_token *token = NULL;
5093 if (CHECK_ATTR(BPF_BTF_LOAD))
5096 if (attr->btf_flags & ~BPF_F_TOKEN_FD)
5099 if (attr->btf_flags & BPF_F_TOKEN_FD) {
5100 token = bpf_token_get_from_fd(attr->btf_token_fd);
5102 return PTR_ERR(token);
5103 if (!bpf_token_allow_cmd(token, BPF_BTF_LOAD)) {
5104 bpf_token_put(token);
5109 if (!bpf_token_capable(token, CAP_BPF)) {
5110 bpf_token_put(token);
5114 bpf_token_put(token);
5116 return btf_new_fd(attr, uattr, uattr_size);
5119 #define BPF_BTF_GET_FD_BY_ID_LAST_FIELD btf_id
5121 static int bpf_btf_get_fd_by_id(const union bpf_attr *attr)
5123 if (CHECK_ATTR(BPF_BTF_GET_FD_BY_ID))
5126 if (!capable(CAP_SYS_ADMIN))
5129 return btf_get_fd_by_id(attr->btf_id);
5132 static int bpf_task_fd_query_copy(const union bpf_attr *attr,
5133 union bpf_attr __user *uattr,
5134 u32 prog_id, u32 fd_type,
5135 const char *buf, u64 probe_offset,
5138 char __user *ubuf = u64_to_user_ptr(attr->task_fd_query.buf);
5139 u32 len = buf ? strlen(buf) : 0, input_len;
5142 if (put_user(len, &uattr->task_fd_query.buf_len))
5144 input_len = attr->task_fd_query.buf_len;
5145 if (input_len && ubuf) {
5147 /* nothing to copy, just make ubuf NULL terminated */
5150 if (put_user(zero, ubuf))
5152 } else if (input_len >= len + 1) {
5153 /* ubuf can hold the string with NULL terminator */
5154 if (copy_to_user(ubuf, buf, len + 1))
5157 /* ubuf cannot hold the string with NULL terminator,
5158 * do a partial copy with NULL terminator.
5163 if (copy_to_user(ubuf, buf, input_len - 1))
5165 if (put_user(zero, ubuf + input_len - 1))
5170 if (put_user(prog_id, &uattr->task_fd_query.prog_id) ||
5171 put_user(fd_type, &uattr->task_fd_query.fd_type) ||
5172 put_user(probe_offset, &uattr->task_fd_query.probe_offset) ||
5173 put_user(probe_addr, &uattr->task_fd_query.probe_addr))
5179 #define BPF_TASK_FD_QUERY_LAST_FIELD task_fd_query.probe_addr
5181 static int bpf_task_fd_query(const union bpf_attr *attr,
5182 union bpf_attr __user *uattr)
5184 pid_t pid = attr->task_fd_query.pid;
5185 u32 fd = attr->task_fd_query.fd;
5186 const struct perf_event *event;
5187 struct task_struct *task;
5191 if (CHECK_ATTR(BPF_TASK_FD_QUERY))
5194 if (!capable(CAP_SYS_ADMIN))
5197 if (attr->task_fd_query.flags != 0)
5201 task = get_pid_task(find_vpid(pid), PIDTYPE_PID);
5207 file = fget_task(task, fd);
5208 put_task_struct(task);
5212 if (file->f_op == &bpf_link_fops || file->f_op == &bpf_link_fops_poll) {
5213 struct bpf_link *link = file->private_data;
5215 if (link->ops == &bpf_raw_tp_link_lops) {
5216 struct bpf_raw_tp_link *raw_tp =
5217 container_of(link, struct bpf_raw_tp_link, link);
5218 struct bpf_raw_event_map *btp = raw_tp->btp;
5220 err = bpf_task_fd_query_copy(attr, uattr,
5221 raw_tp->link.prog->aux->id,
5222 BPF_FD_TYPE_RAW_TRACEPOINT,
5223 btp->tp->name, 0, 0);
5229 event = perf_get_event(file);
5230 if (!IS_ERR(event)) {
5231 u64 probe_offset, probe_addr;
5232 u32 prog_id, fd_type;
5235 err = bpf_get_perf_event_info(event, &prog_id, &fd_type,
5236 &buf, &probe_offset,
5239 err = bpf_task_fd_query_copy(attr, uattr, prog_id,
5253 #define BPF_MAP_BATCH_LAST_FIELD batch.flags
5255 #define BPF_DO_BATCH(fn, ...) \
5261 err = fn(__VA_ARGS__); \
5264 static int bpf_map_do_batch(const union bpf_attr *attr,
5265 union bpf_attr __user *uattr,
5268 bool has_read = cmd == BPF_MAP_LOOKUP_BATCH ||
5269 cmd == BPF_MAP_LOOKUP_AND_DELETE_BATCH;
5270 bool has_write = cmd != BPF_MAP_LOOKUP_BATCH;
5271 struct bpf_map *map;
5274 if (CHECK_ATTR(BPF_MAP_BATCH))
5277 CLASS(fd, f)(attr->batch.map_fd);
5279 map = __bpf_map_get(f);
5281 return PTR_ERR(map);
5283 bpf_map_write_active_inc(map);
5284 if (has_read && !(map_get_sys_perms(map, f) & FMODE_CAN_READ)) {
5288 if (has_write && !(map_get_sys_perms(map, f) & FMODE_CAN_WRITE)) {
5293 if (cmd == BPF_MAP_LOOKUP_BATCH)
5294 BPF_DO_BATCH(map->ops->map_lookup_batch, map, attr, uattr);
5295 else if (cmd == BPF_MAP_LOOKUP_AND_DELETE_BATCH)
5296 BPF_DO_BATCH(map->ops->map_lookup_and_delete_batch, map, attr, uattr);
5297 else if (cmd == BPF_MAP_UPDATE_BATCH)
5298 BPF_DO_BATCH(map->ops->map_update_batch, map, fd_file(f), attr, uattr);
5300 BPF_DO_BATCH(map->ops->map_delete_batch, map, attr, uattr);
5303 maybe_wait_bpf_programs(map);
5304 bpf_map_write_active_dec(map);
5309 #define BPF_LINK_CREATE_LAST_FIELD link_create.uprobe_multi.pid
5310 static int link_create(union bpf_attr *attr, bpfptr_t uattr)
5312 struct bpf_prog *prog;
5315 if (CHECK_ATTR(BPF_LINK_CREATE))
5318 if (attr->link_create.attach_type == BPF_STRUCT_OPS)
5319 return bpf_struct_ops_link_create(attr);
5321 prog = bpf_prog_get(attr->link_create.prog_fd);
5323 return PTR_ERR(prog);
5325 ret = bpf_prog_attach_check_attach_type(prog,
5326 attr->link_create.attach_type);
5330 switch (prog->type) {
5331 case BPF_PROG_TYPE_CGROUP_SKB:
5332 case BPF_PROG_TYPE_CGROUP_SOCK:
5333 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
5334 case BPF_PROG_TYPE_SOCK_OPS:
5335 case BPF_PROG_TYPE_CGROUP_DEVICE:
5336 case BPF_PROG_TYPE_CGROUP_SYSCTL:
5337 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
5338 ret = cgroup_bpf_link_attach(attr, prog);
5340 case BPF_PROG_TYPE_EXT:
5341 ret = bpf_tracing_prog_attach(prog,
5342 attr->link_create.target_fd,
5343 attr->link_create.target_btf_id,
5344 attr->link_create.tracing.cookie);
5346 case BPF_PROG_TYPE_LSM:
5347 case BPF_PROG_TYPE_TRACING:
5348 if (attr->link_create.attach_type != prog->expected_attach_type) {
5352 if (prog->expected_attach_type == BPF_TRACE_RAW_TP)
5353 ret = bpf_raw_tp_link_attach(prog, NULL, attr->link_create.tracing.cookie);
5354 else if (prog->expected_attach_type == BPF_TRACE_ITER)
5355 ret = bpf_iter_link_attach(attr, uattr, prog);
5356 else if (prog->expected_attach_type == BPF_LSM_CGROUP)
5357 ret = cgroup_bpf_link_attach(attr, prog);
5359 ret = bpf_tracing_prog_attach(prog,
5360 attr->link_create.target_fd,
5361 attr->link_create.target_btf_id,
5362 attr->link_create.tracing.cookie);
5364 case BPF_PROG_TYPE_FLOW_DISSECTOR:
5365 case BPF_PROG_TYPE_SK_LOOKUP:
5366 ret = netns_bpf_link_create(attr, prog);
5368 case BPF_PROG_TYPE_SK_MSG:
5369 case BPF_PROG_TYPE_SK_SKB:
5370 ret = sock_map_link_create(attr, prog);
5373 case BPF_PROG_TYPE_XDP:
5374 ret = bpf_xdp_link_attach(attr, prog);
5376 case BPF_PROG_TYPE_SCHED_CLS:
5377 if (attr->link_create.attach_type == BPF_TCX_INGRESS ||
5378 attr->link_create.attach_type == BPF_TCX_EGRESS)
5379 ret = tcx_link_attach(attr, prog);
5381 ret = netkit_link_attach(attr, prog);
5383 case BPF_PROG_TYPE_NETFILTER:
5384 ret = bpf_nf_link_attach(attr, prog);
5387 case BPF_PROG_TYPE_PERF_EVENT:
5388 case BPF_PROG_TYPE_TRACEPOINT:
5389 ret = bpf_perf_link_attach(attr, prog);
5391 case BPF_PROG_TYPE_KPROBE:
5392 if (attr->link_create.attach_type == BPF_PERF_EVENT)
5393 ret = bpf_perf_link_attach(attr, prog);
5394 else if (attr->link_create.attach_type == BPF_TRACE_KPROBE_MULTI ||
5395 attr->link_create.attach_type == BPF_TRACE_KPROBE_SESSION)
5396 ret = bpf_kprobe_multi_link_attach(attr, prog);
5397 else if (attr->link_create.attach_type == BPF_TRACE_UPROBE_MULTI ||
5398 attr->link_create.attach_type == BPF_TRACE_UPROBE_SESSION)
5399 ret = bpf_uprobe_multi_link_attach(attr, prog);
5411 static int link_update_map(struct bpf_link *link, union bpf_attr *attr)
5413 struct bpf_map *new_map, *old_map = NULL;
5416 new_map = bpf_map_get(attr->link_update.new_map_fd);
5417 if (IS_ERR(new_map))
5418 return PTR_ERR(new_map);
5420 if (attr->link_update.flags & BPF_F_REPLACE) {
5421 old_map = bpf_map_get(attr->link_update.old_map_fd);
5422 if (IS_ERR(old_map)) {
5423 ret = PTR_ERR(old_map);
5426 } else if (attr->link_update.old_map_fd) {
5431 ret = link->ops->update_map(link, new_map, old_map);
5434 bpf_map_put(old_map);
5436 bpf_map_put(new_map);
5440 #define BPF_LINK_UPDATE_LAST_FIELD link_update.old_prog_fd
5442 static int link_update(union bpf_attr *attr)
5444 struct bpf_prog *old_prog = NULL, *new_prog;
5445 struct bpf_link *link;
5449 if (CHECK_ATTR(BPF_LINK_UPDATE))
5452 flags = attr->link_update.flags;
5453 if (flags & ~BPF_F_REPLACE)
5456 link = bpf_link_get_from_fd(attr->link_update.link_fd);
5458 return PTR_ERR(link);
5460 if (link->ops->update_map) {
5461 ret = link_update_map(link, attr);
5465 new_prog = bpf_prog_get(attr->link_update.new_prog_fd);
5466 if (IS_ERR(new_prog)) {
5467 ret = PTR_ERR(new_prog);
5471 if (flags & BPF_F_REPLACE) {
5472 old_prog = bpf_prog_get(attr->link_update.old_prog_fd);
5473 if (IS_ERR(old_prog)) {
5474 ret = PTR_ERR(old_prog);
5478 } else if (attr->link_update.old_prog_fd) {
5483 if (link->ops->update_prog)
5484 ret = link->ops->update_prog(link, new_prog, old_prog);
5490 bpf_prog_put(old_prog);
5492 bpf_prog_put(new_prog);
5494 bpf_link_put_direct(link);
5498 #define BPF_LINK_DETACH_LAST_FIELD link_detach.link_fd
5500 static int link_detach(union bpf_attr *attr)
5502 struct bpf_link *link;
5505 if (CHECK_ATTR(BPF_LINK_DETACH))
5508 link = bpf_link_get_from_fd(attr->link_detach.link_fd);
5510 return PTR_ERR(link);
5512 if (link->ops->detach)
5513 ret = link->ops->detach(link);
5517 bpf_link_put_direct(link);
5521 struct bpf_link *bpf_link_inc_not_zero(struct bpf_link *link)
5523 return atomic64_fetch_add_unless(&link->refcnt, 1, 0) ? link : ERR_PTR(-ENOENT);
5525 EXPORT_SYMBOL(bpf_link_inc_not_zero);
5527 struct bpf_link *bpf_link_by_id(u32 id)
5529 struct bpf_link *link;
5532 return ERR_PTR(-ENOENT);
5534 spin_lock_bh(&link_idr_lock);
5535 /* before link is "settled", ID is 0, pretend it doesn't exist yet */
5536 link = idr_find(&link_idr, id);
5539 link = bpf_link_inc_not_zero(link);
5541 link = ERR_PTR(-EAGAIN);
5543 link = ERR_PTR(-ENOENT);
5545 spin_unlock_bh(&link_idr_lock);
5549 struct bpf_link *bpf_link_get_curr_or_next(u32 *id)
5551 struct bpf_link *link;
5553 spin_lock_bh(&link_idr_lock);
5555 link = idr_get_next(&link_idr, id);
5557 link = bpf_link_inc_not_zero(link);
5563 spin_unlock_bh(&link_idr_lock);
5568 #define BPF_LINK_GET_FD_BY_ID_LAST_FIELD link_id
5570 static int bpf_link_get_fd_by_id(const union bpf_attr *attr)
5572 struct bpf_link *link;
5573 u32 id = attr->link_id;
5576 if (CHECK_ATTR(BPF_LINK_GET_FD_BY_ID))
5579 if (!capable(CAP_SYS_ADMIN))
5582 link = bpf_link_by_id(id);
5584 return PTR_ERR(link);
5586 fd = bpf_link_new_fd(link);
5588 bpf_link_put_direct(link);
5593 DEFINE_MUTEX(bpf_stats_enabled_mutex);
5595 static int bpf_stats_release(struct inode *inode, struct file *file)
5597 mutex_lock(&bpf_stats_enabled_mutex);
5598 static_key_slow_dec(&bpf_stats_enabled_key.key);
5599 mutex_unlock(&bpf_stats_enabled_mutex);
5603 static const struct file_operations bpf_stats_fops = {
5604 .release = bpf_stats_release,
5607 static int bpf_enable_runtime_stats(void)
5611 mutex_lock(&bpf_stats_enabled_mutex);
5613 /* Set a very high limit to avoid overflow */
5614 if (static_key_count(&bpf_stats_enabled_key.key) > INT_MAX / 2) {
5615 mutex_unlock(&bpf_stats_enabled_mutex);
5619 fd = anon_inode_getfd("bpf-stats", &bpf_stats_fops, NULL, O_CLOEXEC);
5621 static_key_slow_inc(&bpf_stats_enabled_key.key);
5623 mutex_unlock(&bpf_stats_enabled_mutex);
5627 #define BPF_ENABLE_STATS_LAST_FIELD enable_stats.type
5629 static int bpf_enable_stats(union bpf_attr *attr)
5632 if (CHECK_ATTR(BPF_ENABLE_STATS))
5635 if (!capable(CAP_SYS_ADMIN))
5638 switch (attr->enable_stats.type) {
5639 case BPF_STATS_RUN_TIME:
5640 return bpf_enable_runtime_stats();
5647 #define BPF_ITER_CREATE_LAST_FIELD iter_create.flags
5649 static int bpf_iter_create(union bpf_attr *attr)
5651 struct bpf_link *link;
5654 if (CHECK_ATTR(BPF_ITER_CREATE))
5657 if (attr->iter_create.flags)
5660 link = bpf_link_get_from_fd(attr->iter_create.link_fd);
5662 return PTR_ERR(link);
5664 err = bpf_iter_new_fd(link);
5665 bpf_link_put_direct(link);
5670 #define BPF_PROG_BIND_MAP_LAST_FIELD prog_bind_map.flags
5672 static int bpf_prog_bind_map(union bpf_attr *attr)
5674 struct bpf_prog *prog;
5675 struct bpf_map *map;
5676 struct bpf_map **used_maps_old, **used_maps_new;
5679 if (CHECK_ATTR(BPF_PROG_BIND_MAP))
5682 if (attr->prog_bind_map.flags)
5685 prog = bpf_prog_get(attr->prog_bind_map.prog_fd);
5687 return PTR_ERR(prog);
5689 map = bpf_map_get(attr->prog_bind_map.map_fd);
5695 mutex_lock(&prog->aux->used_maps_mutex);
5697 used_maps_old = prog->aux->used_maps;
5699 for (i = 0; i < prog->aux->used_map_cnt; i++)
5700 if (used_maps_old[i] == map) {
5705 used_maps_new = kmalloc_array(prog->aux->used_map_cnt + 1,
5706 sizeof(used_maps_new[0]),
5708 if (!used_maps_new) {
5713 /* The bpf program will not access the bpf map, but for the sake of
5714 * simplicity, increase sleepable_refcnt for sleepable program as well.
5716 if (prog->sleepable)
5717 atomic64_inc(&map->sleepable_refcnt);
5718 memcpy(used_maps_new, used_maps_old,
5719 sizeof(used_maps_old[0]) * prog->aux->used_map_cnt);
5720 used_maps_new[prog->aux->used_map_cnt] = map;
5722 prog->aux->used_map_cnt++;
5723 prog->aux->used_maps = used_maps_new;
5725 kfree(used_maps_old);
5728 mutex_unlock(&prog->aux->used_maps_mutex);
5737 #define BPF_TOKEN_CREATE_LAST_FIELD token_create.bpffs_fd
5739 static int token_create(union bpf_attr *attr)
5741 if (CHECK_ATTR(BPF_TOKEN_CREATE))
5744 /* no flags are supported yet */
5745 if (attr->token_create.flags)
5748 return bpf_token_create(attr);
5751 static int __sys_bpf(enum bpf_cmd cmd, bpfptr_t uattr, unsigned int size)
5753 union bpf_attr attr;
5756 err = bpf_check_uarg_tail_zero(uattr, sizeof(attr), size);
5759 size = min_t(u32, size, sizeof(attr));
5761 /* copy attributes from user space, may be less than sizeof(bpf_attr) */
5762 memset(&attr, 0, sizeof(attr));
5763 if (copy_from_bpfptr(&attr, uattr, size) != 0)
5766 err = security_bpf(cmd, &attr, size);
5771 case BPF_MAP_CREATE:
5772 err = map_create(&attr);
5774 case BPF_MAP_LOOKUP_ELEM:
5775 err = map_lookup_elem(&attr);
5777 case BPF_MAP_UPDATE_ELEM:
5778 err = map_update_elem(&attr, uattr);
5780 case BPF_MAP_DELETE_ELEM:
5781 err = map_delete_elem(&attr, uattr);
5783 case BPF_MAP_GET_NEXT_KEY:
5784 err = map_get_next_key(&attr);
5786 case BPF_MAP_FREEZE:
5787 err = map_freeze(&attr);
5790 err = bpf_prog_load(&attr, uattr, size);
5793 err = bpf_obj_pin(&attr);
5796 err = bpf_obj_get(&attr);
5798 case BPF_PROG_ATTACH:
5799 err = bpf_prog_attach(&attr);
5801 case BPF_PROG_DETACH:
5802 err = bpf_prog_detach(&attr);
5804 case BPF_PROG_QUERY:
5805 err = bpf_prog_query(&attr, uattr.user);
5807 case BPF_PROG_TEST_RUN:
5808 err = bpf_prog_test_run(&attr, uattr.user);
5810 case BPF_PROG_GET_NEXT_ID:
5811 err = bpf_obj_get_next_id(&attr, uattr.user,
5812 &prog_idr, &prog_idr_lock);
5814 case BPF_MAP_GET_NEXT_ID:
5815 err = bpf_obj_get_next_id(&attr, uattr.user,
5816 &map_idr, &map_idr_lock);
5818 case BPF_BTF_GET_NEXT_ID:
5819 err = bpf_obj_get_next_id(&attr, uattr.user,
5820 &btf_idr, &btf_idr_lock);
5822 case BPF_PROG_GET_FD_BY_ID:
5823 err = bpf_prog_get_fd_by_id(&attr);
5825 case BPF_MAP_GET_FD_BY_ID:
5826 err = bpf_map_get_fd_by_id(&attr);
5828 case BPF_OBJ_GET_INFO_BY_FD:
5829 err = bpf_obj_get_info_by_fd(&attr, uattr.user);
5831 case BPF_RAW_TRACEPOINT_OPEN:
5832 err = bpf_raw_tracepoint_open(&attr);
5835 err = bpf_btf_load(&attr, uattr, size);
5837 case BPF_BTF_GET_FD_BY_ID:
5838 err = bpf_btf_get_fd_by_id(&attr);
5840 case BPF_TASK_FD_QUERY:
5841 err = bpf_task_fd_query(&attr, uattr.user);
5843 case BPF_MAP_LOOKUP_AND_DELETE_ELEM:
5844 err = map_lookup_and_delete_elem(&attr);
5846 case BPF_MAP_LOOKUP_BATCH:
5847 err = bpf_map_do_batch(&attr, uattr.user, BPF_MAP_LOOKUP_BATCH);
5849 case BPF_MAP_LOOKUP_AND_DELETE_BATCH:
5850 err = bpf_map_do_batch(&attr, uattr.user,
5851 BPF_MAP_LOOKUP_AND_DELETE_BATCH);
5853 case BPF_MAP_UPDATE_BATCH:
5854 err = bpf_map_do_batch(&attr, uattr.user, BPF_MAP_UPDATE_BATCH);
5856 case BPF_MAP_DELETE_BATCH:
5857 err = bpf_map_do_batch(&attr, uattr.user, BPF_MAP_DELETE_BATCH);
5859 case BPF_LINK_CREATE:
5860 err = link_create(&attr, uattr);
5862 case BPF_LINK_UPDATE:
5863 err = link_update(&attr);
5865 case BPF_LINK_GET_FD_BY_ID:
5866 err = bpf_link_get_fd_by_id(&attr);
5868 case BPF_LINK_GET_NEXT_ID:
5869 err = bpf_obj_get_next_id(&attr, uattr.user,
5870 &link_idr, &link_idr_lock);
5872 case BPF_ENABLE_STATS:
5873 err = bpf_enable_stats(&attr);
5875 case BPF_ITER_CREATE:
5876 err = bpf_iter_create(&attr);
5878 case BPF_LINK_DETACH:
5879 err = link_detach(&attr);
5881 case BPF_PROG_BIND_MAP:
5882 err = bpf_prog_bind_map(&attr);
5884 case BPF_TOKEN_CREATE:
5885 err = token_create(&attr);
5895 SYSCALL_DEFINE3(bpf, int, cmd, union bpf_attr __user *, uattr, unsigned int, size)
5897 return __sys_bpf(cmd, USER_BPFPTR(uattr), size);
5900 static bool syscall_prog_is_valid_access(int off, int size,
5901 enum bpf_access_type type,
5902 const struct bpf_prog *prog,
5903 struct bpf_insn_access_aux *info)
5905 if (off < 0 || off >= U16_MAX)
5907 if (off % size != 0)
5912 BPF_CALL_3(bpf_sys_bpf, int, cmd, union bpf_attr *, attr, u32, attr_size)
5915 case BPF_MAP_CREATE:
5916 case BPF_MAP_DELETE_ELEM:
5917 case BPF_MAP_UPDATE_ELEM:
5918 case BPF_MAP_FREEZE:
5919 case BPF_MAP_GET_FD_BY_ID:
5922 case BPF_LINK_CREATE:
5923 case BPF_RAW_TRACEPOINT_OPEN:
5928 return __sys_bpf(cmd, KERNEL_BPFPTR(attr), attr_size);
5932 /* To shut up -Wmissing-prototypes.
5933 * This function is used by the kernel light skeleton
5934 * to load bpf programs when modules are loaded or during kernel boot.
5935 * See tools/lib/bpf/skel_internal.h
5937 int kern_sys_bpf(int cmd, union bpf_attr *attr, unsigned int size);
5939 int kern_sys_bpf(int cmd, union bpf_attr *attr, unsigned int size)
5941 struct bpf_prog * __maybe_unused prog;
5942 struct bpf_tramp_run_ctx __maybe_unused run_ctx;
5945 #ifdef CONFIG_BPF_JIT /* __bpf_prog_enter_sleepable used by trampoline and JIT */
5946 case BPF_PROG_TEST_RUN:
5947 if (attr->test.data_in || attr->test.data_out ||
5948 attr->test.ctx_out || attr->test.duration ||
5949 attr->test.repeat || attr->test.flags)
5952 prog = bpf_prog_get_type(attr->test.prog_fd, BPF_PROG_TYPE_SYSCALL);
5954 return PTR_ERR(prog);
5956 if (attr->test.ctx_size_in < prog->aux->max_ctx_offset ||
5957 attr->test.ctx_size_in > U16_MAX) {
5962 run_ctx.bpf_cookie = 0;
5963 if (!__bpf_prog_enter_sleepable_recur(prog, &run_ctx)) {
5964 /* recursion detected */
5965 __bpf_prog_exit_sleepable_recur(prog, 0, &run_ctx);
5969 attr->test.retval = bpf_prog_run(prog, (void *) (long) attr->test.ctx_in);
5970 __bpf_prog_exit_sleepable_recur(prog, 0 /* bpf_prog_run does runtime stats */,
5976 return ____bpf_sys_bpf(cmd, attr, size);
5979 EXPORT_SYMBOL(kern_sys_bpf);
5981 static const struct bpf_func_proto bpf_sys_bpf_proto = {
5982 .func = bpf_sys_bpf,
5984 .ret_type = RET_INTEGER,
5985 .arg1_type = ARG_ANYTHING,
5986 .arg2_type = ARG_PTR_TO_MEM | MEM_RDONLY,
5987 .arg3_type = ARG_CONST_SIZE,
5990 const struct bpf_func_proto * __weak
5991 tracing_prog_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
5993 return bpf_base_func_proto(func_id, prog);
5996 BPF_CALL_1(bpf_sys_close, u32, fd)
5998 /* When bpf program calls this helper there should not be
5999 * an fdget() without matching completed fdput().
6000 * This helper is allowed in the following callchain only:
6001 * sys_bpf->prog_test_run->bpf_prog->bpf_sys_close
6003 return close_fd(fd);
6006 static const struct bpf_func_proto bpf_sys_close_proto = {
6007 .func = bpf_sys_close,
6009 .ret_type = RET_INTEGER,
6010 .arg1_type = ARG_ANYTHING,
6013 BPF_CALL_4(bpf_kallsyms_lookup_name, const char *, name, int, name_sz, int, flags, u64 *, res)
6019 if (name_sz <= 1 || name[name_sz - 1])
6022 if (!bpf_dump_raw_ok(current_cred()))
6025 *res = kallsyms_lookup_name(name);
6026 return *res ? 0 : -ENOENT;
6029 static const struct bpf_func_proto bpf_kallsyms_lookup_name_proto = {
6030 .func = bpf_kallsyms_lookup_name,
6032 .ret_type = RET_INTEGER,
6033 .arg1_type = ARG_PTR_TO_MEM,
6034 .arg2_type = ARG_CONST_SIZE_OR_ZERO,
6035 .arg3_type = ARG_ANYTHING,
6036 .arg4_type = ARG_PTR_TO_FIXED_SIZE_MEM | MEM_UNINIT | MEM_WRITE | MEM_ALIGNED,
6037 .arg4_size = sizeof(u64),
6040 static const struct bpf_func_proto *
6041 syscall_prog_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
6044 case BPF_FUNC_sys_bpf:
6045 return !bpf_token_capable(prog->aux->token, CAP_PERFMON)
6046 ? NULL : &bpf_sys_bpf_proto;
6047 case BPF_FUNC_btf_find_by_name_kind:
6048 return &bpf_btf_find_by_name_kind_proto;
6049 case BPF_FUNC_sys_close:
6050 return &bpf_sys_close_proto;
6051 case BPF_FUNC_kallsyms_lookup_name:
6052 return &bpf_kallsyms_lookup_name_proto;
6054 return tracing_prog_func_proto(func_id, prog);
6058 const struct bpf_verifier_ops bpf_syscall_verifier_ops = {
6059 .get_func_proto = syscall_prog_func_proto,
6060 .is_valid_access = syscall_prog_is_valid_access,
6063 const struct bpf_prog_ops bpf_syscall_prog_ops = {
6064 .test_run = bpf_prog_test_run_syscall,
6067 #ifdef CONFIG_SYSCTL
6068 static int bpf_stats_handler(const struct ctl_table *table, int write,
6069 void *buffer, size_t *lenp, loff_t *ppos)
6071 struct static_key *key = (struct static_key *)table->data;
6072 static int saved_val;
6074 struct ctl_table tmp = {
6076 .maxlen = sizeof(val),
6077 .mode = table->mode,
6078 .extra1 = SYSCTL_ZERO,
6079 .extra2 = SYSCTL_ONE,
6082 if (write && !capable(CAP_SYS_ADMIN))
6085 mutex_lock(&bpf_stats_enabled_mutex);
6087 ret = proc_dointvec_minmax(&tmp, write, buffer, lenp, ppos);
6088 if (write && !ret && val != saved_val) {
6090 static_key_slow_inc(key);
6092 static_key_slow_dec(key);
6095 mutex_unlock(&bpf_stats_enabled_mutex);
6099 void __weak unpriv_ebpf_notify(int new_state)
6103 static int bpf_unpriv_handler(const struct ctl_table *table, int write,
6104 void *buffer, size_t *lenp, loff_t *ppos)
6106 int ret, unpriv_enable = *(int *)table->data;
6107 bool locked_state = unpriv_enable == 1;
6108 struct ctl_table tmp = *table;
6110 if (write && !capable(CAP_SYS_ADMIN))
6113 tmp.data = &unpriv_enable;
6114 ret = proc_dointvec_minmax(&tmp, write, buffer, lenp, ppos);
6115 if (write && !ret) {
6116 if (locked_state && unpriv_enable != 1)
6118 *(int *)table->data = unpriv_enable;
6122 unpriv_ebpf_notify(unpriv_enable);
6127 static struct ctl_table bpf_syscall_table[] = {
6129 .procname = "unprivileged_bpf_disabled",
6130 .data = &sysctl_unprivileged_bpf_disabled,
6131 .maxlen = sizeof(sysctl_unprivileged_bpf_disabled),
6133 .proc_handler = bpf_unpriv_handler,
6134 .extra1 = SYSCTL_ZERO,
6135 .extra2 = SYSCTL_TWO,
6138 .procname = "bpf_stats_enabled",
6139 .data = &bpf_stats_enabled_key.key,
6141 .proc_handler = bpf_stats_handler,
6145 static int __init bpf_syscall_sysctl_init(void)
6147 register_sysctl_init("kernel", bpf_syscall_table);
6150 late_initcall(bpf_syscall_sysctl_init);
6151 #endif /* CONFIG_SYSCTL */