1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
5 #include <linux/bpf-cgroup.h>
6 #include <linux/bpf_trace.h>
7 #include <linux/bpf_lirc.h>
8 #include <linux/bpf_verifier.h>
9 #include <linux/bsearch.h>
10 #include <linux/btf.h>
11 #include <linux/syscalls.h>
12 #include <linux/slab.h>
13 #include <linux/sched/signal.h>
14 #include <linux/vmalloc.h>
15 #include <linux/mmzone.h>
16 #include <linux/anon_inodes.h>
17 #include <linux/fdtable.h>
18 #include <linux/file.h>
20 #include <linux/license.h>
21 #include <linux/filter.h>
22 #include <linux/kernel.h>
23 #include <linux/idr.h>
24 #include <linux/cred.h>
25 #include <linux/timekeeping.h>
26 #include <linux/ctype.h>
27 #include <linux/nospec.h>
28 #include <linux/audit.h>
29 #include <uapi/linux/btf.h>
30 #include <linux/pgtable.h>
31 #include <linux/bpf_lsm.h>
32 #include <linux/poll.h>
33 #include <linux/sort.h>
34 #include <linux/bpf-netns.h>
35 #include <linux/rcupdate_trace.h>
36 #include <linux/memcontrol.h>
37 #include <linux/trace_events.h>
38 #include <net/netfilter/nf_bpf_link.h>
42 #define IS_FD_ARRAY(map) ((map)->map_type == BPF_MAP_TYPE_PERF_EVENT_ARRAY || \
43 (map)->map_type == BPF_MAP_TYPE_CGROUP_ARRAY || \
44 (map)->map_type == BPF_MAP_TYPE_ARRAY_OF_MAPS)
45 #define IS_FD_PROG_ARRAY(map) ((map)->map_type == BPF_MAP_TYPE_PROG_ARRAY)
46 #define IS_FD_HASH(map) ((map)->map_type == BPF_MAP_TYPE_HASH_OF_MAPS)
47 #define IS_FD_MAP(map) (IS_FD_ARRAY(map) || IS_FD_PROG_ARRAY(map) || \
50 #define BPF_OBJ_FLAG_MASK (BPF_F_RDONLY | BPF_F_WRONLY)
52 DEFINE_PER_CPU(int, bpf_prog_active);
53 static DEFINE_IDR(prog_idr);
54 static DEFINE_SPINLOCK(prog_idr_lock);
55 static DEFINE_IDR(map_idr);
56 static DEFINE_SPINLOCK(map_idr_lock);
57 static DEFINE_IDR(link_idr);
58 static DEFINE_SPINLOCK(link_idr_lock);
60 int sysctl_unprivileged_bpf_disabled __read_mostly =
61 IS_BUILTIN(CONFIG_BPF_UNPRIV_DEFAULT_OFF) ? 2 : 0;
63 static const struct bpf_map_ops * const bpf_map_types[] = {
64 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type)
65 #define BPF_MAP_TYPE(_id, _ops) \
67 #define BPF_LINK_TYPE(_id, _name)
68 #include <linux/bpf_types.h>
75 * If we're handed a bigger struct than we know of, ensure all the unknown bits
76 * are 0 - i.e. new user-space does not rely on any kernel feature extensions
77 * we don't know about yet.
79 * There is a ToCToU between this function call and the following
80 * copy_from_user() call. However, this is not a concern since this function is
81 * meant to be a future-proofing of bits.
83 int bpf_check_uarg_tail_zero(bpfptr_t uaddr,
89 if (unlikely(actual_size > PAGE_SIZE)) /* silly large */
92 if (actual_size <= expected_size)
96 res = memchr_inv(uaddr.kernel + expected_size, 0,
97 actual_size - expected_size) == NULL;
99 res = check_zeroed_user(uaddr.user + expected_size,
100 actual_size - expected_size);
103 return res ? 0 : -E2BIG;
106 const struct bpf_map_ops bpf_map_offload_ops = {
107 .map_meta_equal = bpf_map_meta_equal,
108 .map_alloc = bpf_map_offload_map_alloc,
109 .map_free = bpf_map_offload_map_free,
110 .map_check_btf = map_check_no_btf,
111 .map_mem_usage = bpf_map_offload_map_mem_usage,
114 static void bpf_map_write_active_inc(struct bpf_map *map)
116 atomic64_inc(&map->writecnt);
119 static void bpf_map_write_active_dec(struct bpf_map *map)
121 atomic64_dec(&map->writecnt);
124 bool bpf_map_write_active(const struct bpf_map *map)
126 return atomic64_read(&map->writecnt) != 0;
129 static u32 bpf_map_value_size(const struct bpf_map *map)
131 if (map->map_type == BPF_MAP_TYPE_PERCPU_HASH ||
132 map->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH ||
133 map->map_type == BPF_MAP_TYPE_PERCPU_ARRAY ||
134 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
135 return round_up(map->value_size, 8) * num_possible_cpus();
136 else if (IS_FD_MAP(map))
139 return map->value_size;
142 static void maybe_wait_bpf_programs(struct bpf_map *map)
144 /* Wait for any running BPF programs to complete so that
145 * userspace, when we return to it, knows that all programs
146 * that could be running use the new map value.
148 if (map->map_type == BPF_MAP_TYPE_HASH_OF_MAPS ||
149 map->map_type == BPF_MAP_TYPE_ARRAY_OF_MAPS)
153 static int bpf_map_update_value(struct bpf_map *map, struct file *map_file,
154 void *key, void *value, __u64 flags)
158 /* Need to create a kthread, thus must support schedule */
159 if (bpf_map_is_offloaded(map)) {
160 return bpf_map_offload_update_elem(map, key, value, flags);
161 } else if (map->map_type == BPF_MAP_TYPE_CPUMAP ||
162 map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
163 return map->ops->map_update_elem(map, key, value, flags);
164 } else if (map->map_type == BPF_MAP_TYPE_SOCKHASH ||
165 map->map_type == BPF_MAP_TYPE_SOCKMAP) {
166 return sock_map_update_elem_sys(map, key, value, flags);
167 } else if (IS_FD_PROG_ARRAY(map)) {
168 return bpf_fd_array_map_update_elem(map, map_file, key, value,
172 bpf_disable_instrumentation();
173 if (map->map_type == BPF_MAP_TYPE_PERCPU_HASH ||
174 map->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH) {
175 err = bpf_percpu_hash_update(map, key, value, flags);
176 } else if (map->map_type == BPF_MAP_TYPE_PERCPU_ARRAY) {
177 err = bpf_percpu_array_update(map, key, value, flags);
178 } else if (map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE) {
179 err = bpf_percpu_cgroup_storage_update(map, key, value,
181 } else if (IS_FD_ARRAY(map)) {
183 err = bpf_fd_array_map_update_elem(map, map_file, key, value,
186 } else if (map->map_type == BPF_MAP_TYPE_HASH_OF_MAPS) {
188 err = bpf_fd_htab_map_update_elem(map, map_file, key, value,
191 } else if (map->map_type == BPF_MAP_TYPE_REUSEPORT_SOCKARRAY) {
192 /* rcu_read_lock() is not needed */
193 err = bpf_fd_reuseport_array_update_elem(map, key, value,
195 } else if (map->map_type == BPF_MAP_TYPE_QUEUE ||
196 map->map_type == BPF_MAP_TYPE_STACK ||
197 map->map_type == BPF_MAP_TYPE_BLOOM_FILTER) {
198 err = map->ops->map_push_elem(map, value, flags);
201 err = map->ops->map_update_elem(map, key, value, flags);
204 bpf_enable_instrumentation();
205 maybe_wait_bpf_programs(map);
210 static int bpf_map_copy_value(struct bpf_map *map, void *key, void *value,
216 if (bpf_map_is_offloaded(map))
217 return bpf_map_offload_lookup_elem(map, key, value);
219 bpf_disable_instrumentation();
220 if (map->map_type == BPF_MAP_TYPE_PERCPU_HASH ||
221 map->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH) {
222 err = bpf_percpu_hash_copy(map, key, value);
223 } else if (map->map_type == BPF_MAP_TYPE_PERCPU_ARRAY) {
224 err = bpf_percpu_array_copy(map, key, value);
225 } else if (map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE) {
226 err = bpf_percpu_cgroup_storage_copy(map, key, value);
227 } else if (map->map_type == BPF_MAP_TYPE_STACK_TRACE) {
228 err = bpf_stackmap_copy(map, key, value);
229 } else if (IS_FD_ARRAY(map) || IS_FD_PROG_ARRAY(map)) {
230 err = bpf_fd_array_map_lookup_elem(map, key, value);
231 } else if (IS_FD_HASH(map)) {
232 err = bpf_fd_htab_map_lookup_elem(map, key, value);
233 } else if (map->map_type == BPF_MAP_TYPE_REUSEPORT_SOCKARRAY) {
234 err = bpf_fd_reuseport_array_lookup_elem(map, key, value);
235 } else if (map->map_type == BPF_MAP_TYPE_QUEUE ||
236 map->map_type == BPF_MAP_TYPE_STACK ||
237 map->map_type == BPF_MAP_TYPE_BLOOM_FILTER) {
238 err = map->ops->map_peek_elem(map, value);
239 } else if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
240 /* struct_ops map requires directly updating "value" */
241 err = bpf_struct_ops_map_sys_lookup_elem(map, key, value);
244 if (map->ops->map_lookup_elem_sys_only)
245 ptr = map->ops->map_lookup_elem_sys_only(map, key);
247 ptr = map->ops->map_lookup_elem(map, key);
254 if (flags & BPF_F_LOCK)
255 /* lock 'ptr' and copy everything but lock */
256 copy_map_value_locked(map, value, ptr, true);
258 copy_map_value(map, value, ptr);
259 /* mask lock and timer, since value wasn't zero inited */
260 check_and_init_map_value(map, value);
265 bpf_enable_instrumentation();
266 maybe_wait_bpf_programs(map);
271 /* Please, do not use this function outside from the map creation path
272 * (e.g. in map update path) without taking care of setting the active
273 * memory cgroup (see at bpf_map_kmalloc_node() for example).
275 static void *__bpf_map_area_alloc(u64 size, int numa_node, bool mmapable)
277 /* We really just want to fail instead of triggering OOM killer
278 * under memory pressure, therefore we set __GFP_NORETRY to kmalloc,
279 * which is used for lower order allocation requests.
281 * It has been observed that higher order allocation requests done by
282 * vmalloc with __GFP_NORETRY being set might fail due to not trying
283 * to reclaim memory from the page cache, thus we set
284 * __GFP_RETRY_MAYFAIL to avoid such situations.
287 gfp_t gfp = bpf_memcg_flags(__GFP_NOWARN | __GFP_ZERO);
288 unsigned int flags = 0;
289 unsigned long align = 1;
292 if (size >= SIZE_MAX)
295 /* kmalloc()'ed memory can't be mmap()'ed */
297 BUG_ON(!PAGE_ALIGNED(size));
300 } else if (size <= (PAGE_SIZE << PAGE_ALLOC_COSTLY_ORDER)) {
301 area = kmalloc_node(size, gfp | GFP_USER | __GFP_NORETRY,
307 return __vmalloc_node_range(size, align, VMALLOC_START, VMALLOC_END,
308 gfp | GFP_KERNEL | __GFP_RETRY_MAYFAIL, PAGE_KERNEL,
309 flags, numa_node, __builtin_return_address(0));
312 void *bpf_map_area_alloc(u64 size, int numa_node)
314 return __bpf_map_area_alloc(size, numa_node, false);
317 void *bpf_map_area_mmapable_alloc(u64 size, int numa_node)
319 return __bpf_map_area_alloc(size, numa_node, true);
322 void bpf_map_area_free(void *area)
327 static u32 bpf_map_flags_retain_permanent(u32 flags)
329 /* Some map creation flags are not tied to the map object but
330 * rather to the map fd instead, so they have no meaning upon
331 * map object inspection since multiple file descriptors with
332 * different (access) properties can exist here. Thus, given
333 * this has zero meaning for the map itself, lets clear these
336 return flags & ~(BPF_F_RDONLY | BPF_F_WRONLY);
339 void bpf_map_init_from_attr(struct bpf_map *map, union bpf_attr *attr)
341 map->map_type = attr->map_type;
342 map->key_size = attr->key_size;
343 map->value_size = attr->value_size;
344 map->max_entries = attr->max_entries;
345 map->map_flags = bpf_map_flags_retain_permanent(attr->map_flags);
346 map->numa_node = bpf_map_attr_numa_node(attr);
347 map->map_extra = attr->map_extra;
350 static int bpf_map_alloc_id(struct bpf_map *map)
354 idr_preload(GFP_KERNEL);
355 spin_lock_bh(&map_idr_lock);
356 id = idr_alloc_cyclic(&map_idr, map, 1, INT_MAX, GFP_ATOMIC);
359 spin_unlock_bh(&map_idr_lock);
362 if (WARN_ON_ONCE(!id))
365 return id > 0 ? 0 : id;
368 void bpf_map_free_id(struct bpf_map *map)
372 /* Offloaded maps are removed from the IDR store when their device
373 * disappears - even if someone holds an fd to them they are unusable,
374 * the memory is gone, all ops will fail; they are simply waiting for
375 * refcnt to drop to be freed.
380 spin_lock_irqsave(&map_idr_lock, flags);
382 idr_remove(&map_idr, map->id);
385 spin_unlock_irqrestore(&map_idr_lock, flags);
388 #ifdef CONFIG_MEMCG_KMEM
389 static void bpf_map_save_memcg(struct bpf_map *map)
391 /* Currently if a map is created by a process belonging to the root
392 * memory cgroup, get_obj_cgroup_from_current() will return NULL.
393 * So we have to check map->objcg for being NULL each time it's
396 if (memcg_bpf_enabled())
397 map->objcg = get_obj_cgroup_from_current();
400 static void bpf_map_release_memcg(struct bpf_map *map)
403 obj_cgroup_put(map->objcg);
406 static struct mem_cgroup *bpf_map_get_memcg(const struct bpf_map *map)
409 return get_mem_cgroup_from_objcg(map->objcg);
411 return root_mem_cgroup;
414 void *bpf_map_kmalloc_node(const struct bpf_map *map, size_t size, gfp_t flags,
417 struct mem_cgroup *memcg, *old_memcg;
420 memcg = bpf_map_get_memcg(map);
421 old_memcg = set_active_memcg(memcg);
422 ptr = kmalloc_node(size, flags | __GFP_ACCOUNT, node);
423 set_active_memcg(old_memcg);
424 mem_cgroup_put(memcg);
429 void *bpf_map_kzalloc(const struct bpf_map *map, size_t size, gfp_t flags)
431 struct mem_cgroup *memcg, *old_memcg;
434 memcg = bpf_map_get_memcg(map);
435 old_memcg = set_active_memcg(memcg);
436 ptr = kzalloc(size, flags | __GFP_ACCOUNT);
437 set_active_memcg(old_memcg);
438 mem_cgroup_put(memcg);
443 void *bpf_map_kvcalloc(struct bpf_map *map, size_t n, size_t size,
446 struct mem_cgroup *memcg, *old_memcg;
449 memcg = bpf_map_get_memcg(map);
450 old_memcg = set_active_memcg(memcg);
451 ptr = kvcalloc(n, size, flags | __GFP_ACCOUNT);
452 set_active_memcg(old_memcg);
453 mem_cgroup_put(memcg);
458 void __percpu *bpf_map_alloc_percpu(const struct bpf_map *map, size_t size,
459 size_t align, gfp_t flags)
461 struct mem_cgroup *memcg, *old_memcg;
464 memcg = bpf_map_get_memcg(map);
465 old_memcg = set_active_memcg(memcg);
466 ptr = __alloc_percpu_gfp(size, align, flags | __GFP_ACCOUNT);
467 set_active_memcg(old_memcg);
468 mem_cgroup_put(memcg);
474 static void bpf_map_save_memcg(struct bpf_map *map)
478 static void bpf_map_release_memcg(struct bpf_map *map)
483 static int btf_field_cmp(const void *a, const void *b)
485 const struct btf_field *f1 = a, *f2 = b;
487 if (f1->offset < f2->offset)
489 else if (f1->offset > f2->offset)
494 struct btf_field *btf_record_find(const struct btf_record *rec, u32 offset,
497 struct btf_field *field;
499 if (IS_ERR_OR_NULL(rec) || !(rec->field_mask & field_mask))
501 field = bsearch(&offset, rec->fields, rec->cnt, sizeof(rec->fields[0]), btf_field_cmp);
502 if (!field || !(field->type & field_mask))
507 void btf_record_free(struct btf_record *rec)
511 if (IS_ERR_OR_NULL(rec))
513 for (i = 0; i < rec->cnt; i++) {
514 switch (rec->fields[i].type) {
517 case BPF_KPTR_PERCPU:
518 if (rec->fields[i].kptr.module)
519 module_put(rec->fields[i].kptr.module);
520 btf_put(rec->fields[i].kptr.btf);
529 /* Nothing to release */
539 void bpf_map_free_record(struct bpf_map *map)
541 btf_record_free(map->record);
545 struct btf_record *btf_record_dup(const struct btf_record *rec)
547 const struct btf_field *fields;
548 struct btf_record *new_rec;
551 if (IS_ERR_OR_NULL(rec))
553 size = offsetof(struct btf_record, fields[rec->cnt]);
554 new_rec = kmemdup(rec, size, GFP_KERNEL | __GFP_NOWARN);
556 return ERR_PTR(-ENOMEM);
557 /* Do a deep copy of the btf_record */
558 fields = rec->fields;
560 for (i = 0; i < rec->cnt; i++) {
561 switch (fields[i].type) {
564 case BPF_KPTR_PERCPU:
565 btf_get(fields[i].kptr.btf);
566 if (fields[i].kptr.module && !try_module_get(fields[i].kptr.module)) {
578 /* Nothing to acquire */
589 btf_record_free(new_rec);
593 bool btf_record_equal(const struct btf_record *rec_a, const struct btf_record *rec_b)
595 bool a_has_fields = !IS_ERR_OR_NULL(rec_a), b_has_fields = !IS_ERR_OR_NULL(rec_b);
598 if (!a_has_fields && !b_has_fields)
600 if (a_has_fields != b_has_fields)
602 if (rec_a->cnt != rec_b->cnt)
604 size = offsetof(struct btf_record, fields[rec_a->cnt]);
605 /* btf_parse_fields uses kzalloc to allocate a btf_record, so unused
606 * members are zeroed out. So memcmp is safe to do without worrying
607 * about padding/unused fields.
609 * While spin_lock, timer, and kptr have no relation to map BTF,
610 * list_head metadata is specific to map BTF, the btf and value_rec
611 * members in particular. btf is the map BTF, while value_rec points to
612 * btf_record in that map BTF.
614 * So while by default, we don't rely on the map BTF (which the records
615 * were parsed from) matching for both records, which is not backwards
616 * compatible, in case list_head is part of it, we implicitly rely on
617 * that by way of depending on memcmp succeeding for it.
619 return !memcmp(rec_a, rec_b, size);
622 void bpf_obj_free_timer(const struct btf_record *rec, void *obj)
624 if (WARN_ON_ONCE(!btf_record_has_field(rec, BPF_TIMER)))
626 bpf_timer_cancel_and_free(obj + rec->timer_off);
629 extern void __bpf_obj_drop_impl(void *p, const struct btf_record *rec);
631 void bpf_obj_free_fields(const struct btf_record *rec, void *obj)
633 const struct btf_field *fields;
636 if (IS_ERR_OR_NULL(rec))
638 fields = rec->fields;
639 for (i = 0; i < rec->cnt; i++) {
640 struct btf_struct_meta *pointee_struct_meta;
641 const struct btf_field *field = &fields[i];
642 void *field_ptr = obj + field->offset;
645 switch (fields[i].type) {
649 bpf_timer_cancel_and_free(field_ptr);
652 WRITE_ONCE(*(u64 *)field_ptr, 0);
655 case BPF_KPTR_PERCPU:
656 xchgd_field = (void *)xchg((unsigned long *)field_ptr, 0);
660 if (!btf_is_kernel(field->kptr.btf)) {
661 pointee_struct_meta = btf_find_struct_meta(field->kptr.btf,
664 __bpf_obj_drop_impl(xchgd_field, pointee_struct_meta ?
665 pointee_struct_meta->record :
669 field->kptr.dtor(xchgd_field);
673 if (WARN_ON_ONCE(rec->spin_lock_off < 0))
675 bpf_list_head_free(field, field_ptr, obj + rec->spin_lock_off);
678 if (WARN_ON_ONCE(rec->spin_lock_off < 0))
680 bpf_rb_root_free(field, field_ptr, obj + rec->spin_lock_off);
693 /* called from workqueue */
694 static void bpf_map_free_deferred(struct work_struct *work)
696 struct bpf_map *map = container_of(work, struct bpf_map, work);
697 struct btf_record *rec = map->record;
699 security_bpf_map_free(map);
700 bpf_map_release_memcg(map);
701 /* implementation dependent freeing */
702 map->ops->map_free(map);
703 /* Delay freeing of btf_record for maps, as map_free
704 * callback usually needs access to them. It is better to do it here
705 * than require each callback to do the free itself manually.
707 * Note that the btf_record stashed in map->inner_map_meta->record was
708 * already freed using the map_free callback for map in map case which
709 * eventually calls bpf_map_free_meta, since inner_map_meta is only a
710 * template bpf_map struct used during verification.
712 btf_record_free(rec);
715 static void bpf_map_put_uref(struct bpf_map *map)
717 if (atomic64_dec_and_test(&map->usercnt)) {
718 if (map->ops->map_release_uref)
719 map->ops->map_release_uref(map);
723 /* decrement map refcnt and schedule it for freeing via workqueue
724 * (underlying map implementation ops->map_free() might sleep)
726 void bpf_map_put(struct bpf_map *map)
728 if (atomic64_dec_and_test(&map->refcnt)) {
729 /* bpf_map_free_id() must be called first */
730 bpf_map_free_id(map);
732 INIT_WORK(&map->work, bpf_map_free_deferred);
733 /* Avoid spawning kworkers, since they all might contend
734 * for the same mutex like slab_mutex.
736 queue_work(system_unbound_wq, &map->work);
739 EXPORT_SYMBOL_GPL(bpf_map_put);
741 void bpf_map_put_with_uref(struct bpf_map *map)
743 bpf_map_put_uref(map);
747 static int bpf_map_release(struct inode *inode, struct file *filp)
749 struct bpf_map *map = filp->private_data;
751 if (map->ops->map_release)
752 map->ops->map_release(map, filp);
754 bpf_map_put_with_uref(map);
758 static fmode_t map_get_sys_perms(struct bpf_map *map, struct fd f)
760 fmode_t mode = f.file->f_mode;
762 /* Our file permissions may have been overridden by global
763 * map permissions facing syscall side.
765 if (READ_ONCE(map->frozen))
766 mode &= ~FMODE_CAN_WRITE;
770 #ifdef CONFIG_PROC_FS
771 /* Show the memory usage of a bpf map */
772 static u64 bpf_map_memory_usage(const struct bpf_map *map)
774 return map->ops->map_mem_usage(map);
777 static void bpf_map_show_fdinfo(struct seq_file *m, struct file *filp)
779 struct bpf_map *map = filp->private_data;
780 u32 type = 0, jited = 0;
782 if (map_type_contains_progs(map)) {
783 spin_lock(&map->owner.lock);
784 type = map->owner.type;
785 jited = map->owner.jited;
786 spin_unlock(&map->owner.lock);
795 "map_extra:\t%#llx\n"
804 (unsigned long long)map->map_extra,
805 bpf_map_memory_usage(map),
807 READ_ONCE(map->frozen));
809 seq_printf(m, "owner_prog_type:\t%u\n", type);
810 seq_printf(m, "owner_jited:\t%u\n", jited);
815 static ssize_t bpf_dummy_read(struct file *filp, char __user *buf, size_t siz,
818 /* We need this handler such that alloc_file() enables
819 * f_mode with FMODE_CAN_READ.
824 static ssize_t bpf_dummy_write(struct file *filp, const char __user *buf,
825 size_t siz, loff_t *ppos)
827 /* We need this handler such that alloc_file() enables
828 * f_mode with FMODE_CAN_WRITE.
833 /* called for any extra memory-mapped regions (except initial) */
834 static void bpf_map_mmap_open(struct vm_area_struct *vma)
836 struct bpf_map *map = vma->vm_file->private_data;
838 if (vma->vm_flags & VM_MAYWRITE)
839 bpf_map_write_active_inc(map);
842 /* called for all unmapped memory region (including initial) */
843 static void bpf_map_mmap_close(struct vm_area_struct *vma)
845 struct bpf_map *map = vma->vm_file->private_data;
847 if (vma->vm_flags & VM_MAYWRITE)
848 bpf_map_write_active_dec(map);
851 static const struct vm_operations_struct bpf_map_default_vmops = {
852 .open = bpf_map_mmap_open,
853 .close = bpf_map_mmap_close,
856 static int bpf_map_mmap(struct file *filp, struct vm_area_struct *vma)
858 struct bpf_map *map = filp->private_data;
861 if (!map->ops->map_mmap || !IS_ERR_OR_NULL(map->record))
864 if (!(vma->vm_flags & VM_SHARED))
867 mutex_lock(&map->freeze_mutex);
869 if (vma->vm_flags & VM_WRITE) {
874 /* map is meant to be read-only, so do not allow mapping as
875 * writable, because it's possible to leak a writable page
876 * reference and allows user-space to still modify it after
877 * freezing, while verifier will assume contents do not change
879 if (map->map_flags & BPF_F_RDONLY_PROG) {
885 /* set default open/close callbacks */
886 vma->vm_ops = &bpf_map_default_vmops;
887 vma->vm_private_data = map;
888 vm_flags_clear(vma, VM_MAYEXEC);
889 if (!(vma->vm_flags & VM_WRITE))
890 /* disallow re-mapping with PROT_WRITE */
891 vm_flags_clear(vma, VM_MAYWRITE);
893 err = map->ops->map_mmap(map, vma);
897 if (vma->vm_flags & VM_MAYWRITE)
898 bpf_map_write_active_inc(map);
900 mutex_unlock(&map->freeze_mutex);
904 static __poll_t bpf_map_poll(struct file *filp, struct poll_table_struct *pts)
906 struct bpf_map *map = filp->private_data;
908 if (map->ops->map_poll)
909 return map->ops->map_poll(map, filp, pts);
914 const struct file_operations bpf_map_fops = {
915 #ifdef CONFIG_PROC_FS
916 .show_fdinfo = bpf_map_show_fdinfo,
918 .release = bpf_map_release,
919 .read = bpf_dummy_read,
920 .write = bpf_dummy_write,
921 .mmap = bpf_map_mmap,
922 .poll = bpf_map_poll,
925 int bpf_map_new_fd(struct bpf_map *map, int flags)
929 ret = security_bpf_map(map, OPEN_FMODE(flags));
933 return anon_inode_getfd("bpf-map", &bpf_map_fops, map,
937 int bpf_get_file_flag(int flags)
939 if ((flags & BPF_F_RDONLY) && (flags & BPF_F_WRONLY))
941 if (flags & BPF_F_RDONLY)
943 if (flags & BPF_F_WRONLY)
948 /* helper macro to check that unused fields 'union bpf_attr' are zero */
949 #define CHECK_ATTR(CMD) \
950 memchr_inv((void *) &attr->CMD##_LAST_FIELD + \
951 sizeof(attr->CMD##_LAST_FIELD), 0, \
953 offsetof(union bpf_attr, CMD##_LAST_FIELD) - \
954 sizeof(attr->CMD##_LAST_FIELD)) != NULL
956 /* dst and src must have at least "size" number of bytes.
957 * Return strlen on success and < 0 on error.
959 int bpf_obj_name_cpy(char *dst, const char *src, unsigned int size)
961 const char *end = src + size;
962 const char *orig_src = src;
964 memset(dst, 0, size);
965 /* Copy all isalnum(), '_' and '.' chars. */
966 while (src < end && *src) {
967 if (!isalnum(*src) &&
968 *src != '_' && *src != '.')
973 /* No '\0' found in "size" number of bytes */
977 return src - orig_src;
980 int map_check_no_btf(const struct bpf_map *map,
981 const struct btf *btf,
982 const struct btf_type *key_type,
983 const struct btf_type *value_type)
988 static int map_check_btf(struct bpf_map *map, const struct btf *btf,
989 u32 btf_key_id, u32 btf_value_id)
991 const struct btf_type *key_type, *value_type;
992 u32 key_size, value_size;
995 /* Some maps allow key to be unspecified. */
997 key_type = btf_type_id_size(btf, &btf_key_id, &key_size);
998 if (!key_type || key_size != map->key_size)
1001 key_type = btf_type_by_id(btf, 0);
1002 if (!map->ops->map_check_btf)
1006 value_type = btf_type_id_size(btf, &btf_value_id, &value_size);
1007 if (!value_type || value_size != map->value_size)
1010 map->record = btf_parse_fields(btf, value_type,
1011 BPF_SPIN_LOCK | BPF_TIMER | BPF_KPTR | BPF_LIST_HEAD |
1012 BPF_RB_ROOT | BPF_REFCOUNT,
1014 if (!IS_ERR_OR_NULL(map->record)) {
1017 if (!bpf_capable()) {
1021 if (map->map_flags & (BPF_F_RDONLY_PROG | BPF_F_WRONLY_PROG)) {
1025 for (i = 0; i < sizeof(map->record->field_mask) * 8; i++) {
1026 switch (map->record->field_mask & (1 << i)) {
1030 if (map->map_type != BPF_MAP_TYPE_HASH &&
1031 map->map_type != BPF_MAP_TYPE_ARRAY &&
1032 map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
1033 map->map_type != BPF_MAP_TYPE_SK_STORAGE &&
1034 map->map_type != BPF_MAP_TYPE_INODE_STORAGE &&
1035 map->map_type != BPF_MAP_TYPE_TASK_STORAGE &&
1036 map->map_type != BPF_MAP_TYPE_CGRP_STORAGE) {
1042 if (map->map_type != BPF_MAP_TYPE_HASH &&
1043 map->map_type != BPF_MAP_TYPE_LRU_HASH &&
1044 map->map_type != BPF_MAP_TYPE_ARRAY) {
1049 case BPF_KPTR_UNREF:
1051 case BPF_KPTR_PERCPU:
1053 if (map->map_type != BPF_MAP_TYPE_HASH &&
1054 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
1055 map->map_type != BPF_MAP_TYPE_LRU_HASH &&
1056 map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH &&
1057 map->map_type != BPF_MAP_TYPE_ARRAY &&
1058 map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
1059 map->map_type != BPF_MAP_TYPE_SK_STORAGE &&
1060 map->map_type != BPF_MAP_TYPE_INODE_STORAGE &&
1061 map->map_type != BPF_MAP_TYPE_TASK_STORAGE &&
1062 map->map_type != BPF_MAP_TYPE_CGRP_STORAGE) {
1069 if (map->map_type != BPF_MAP_TYPE_HASH &&
1070 map->map_type != BPF_MAP_TYPE_LRU_HASH &&
1071 map->map_type != BPF_MAP_TYPE_ARRAY) {
1077 /* Fail if map_type checks are missing for a field type */
1084 ret = btf_check_and_fixup_fields(btf, map->record);
1088 if (map->ops->map_check_btf) {
1089 ret = map->ops->map_check_btf(map, btf, key_type, value_type);
1096 bpf_map_free_record(map);
1100 #define BPF_MAP_CREATE_LAST_FIELD map_extra
1101 /* called via syscall */
1102 static int map_create(union bpf_attr *attr)
1104 const struct bpf_map_ops *ops;
1105 int numa_node = bpf_map_attr_numa_node(attr);
1106 u32 map_type = attr->map_type;
1107 struct bpf_map *map;
1111 err = CHECK_ATTR(BPF_MAP_CREATE);
1115 if (attr->btf_vmlinux_value_type_id) {
1116 if (attr->map_type != BPF_MAP_TYPE_STRUCT_OPS ||
1117 attr->btf_key_type_id || attr->btf_value_type_id)
1119 } else if (attr->btf_key_type_id && !attr->btf_value_type_id) {
1123 if (attr->map_type != BPF_MAP_TYPE_BLOOM_FILTER &&
1124 attr->map_extra != 0)
1127 f_flags = bpf_get_file_flag(attr->map_flags);
1131 if (numa_node != NUMA_NO_NODE &&
1132 ((unsigned int)numa_node >= nr_node_ids ||
1133 !node_online(numa_node)))
1136 /* find map type and init map: hashtable vs rbtree vs bloom vs ... */
1137 map_type = attr->map_type;
1138 if (map_type >= ARRAY_SIZE(bpf_map_types))
1140 map_type = array_index_nospec(map_type, ARRAY_SIZE(bpf_map_types));
1141 ops = bpf_map_types[map_type];
1145 if (ops->map_alloc_check) {
1146 err = ops->map_alloc_check(attr);
1150 if (attr->map_ifindex)
1151 ops = &bpf_map_offload_ops;
1152 if (!ops->map_mem_usage)
1155 /* Intent here is for unprivileged_bpf_disabled to block BPF map
1156 * creation for unprivileged users; other actions depend
1157 * on fd availability and access to bpffs, so are dependent on
1158 * object creation success. Even with unprivileged BPF disabled,
1159 * capability checks are still carried out.
1161 if (sysctl_unprivileged_bpf_disabled && !bpf_capable())
1164 /* check privileged map type permissions */
1166 case BPF_MAP_TYPE_ARRAY:
1167 case BPF_MAP_TYPE_PERCPU_ARRAY:
1168 case BPF_MAP_TYPE_PROG_ARRAY:
1169 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
1170 case BPF_MAP_TYPE_CGROUP_ARRAY:
1171 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
1172 case BPF_MAP_TYPE_HASH:
1173 case BPF_MAP_TYPE_PERCPU_HASH:
1174 case BPF_MAP_TYPE_HASH_OF_MAPS:
1175 case BPF_MAP_TYPE_RINGBUF:
1176 case BPF_MAP_TYPE_USER_RINGBUF:
1177 case BPF_MAP_TYPE_CGROUP_STORAGE:
1178 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
1181 case BPF_MAP_TYPE_SK_STORAGE:
1182 case BPF_MAP_TYPE_INODE_STORAGE:
1183 case BPF_MAP_TYPE_TASK_STORAGE:
1184 case BPF_MAP_TYPE_CGRP_STORAGE:
1185 case BPF_MAP_TYPE_BLOOM_FILTER:
1186 case BPF_MAP_TYPE_LPM_TRIE:
1187 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
1188 case BPF_MAP_TYPE_STACK_TRACE:
1189 case BPF_MAP_TYPE_QUEUE:
1190 case BPF_MAP_TYPE_STACK:
1191 case BPF_MAP_TYPE_LRU_HASH:
1192 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
1193 case BPF_MAP_TYPE_STRUCT_OPS:
1194 case BPF_MAP_TYPE_CPUMAP:
1198 case BPF_MAP_TYPE_SOCKMAP:
1199 case BPF_MAP_TYPE_SOCKHASH:
1200 case BPF_MAP_TYPE_DEVMAP:
1201 case BPF_MAP_TYPE_DEVMAP_HASH:
1202 case BPF_MAP_TYPE_XSKMAP:
1203 if (!capable(CAP_NET_ADMIN))
1207 WARN(1, "unsupported map type %d", map_type);
1211 map = ops->map_alloc(attr);
1213 return PTR_ERR(map);
1215 map->map_type = map_type;
1217 err = bpf_obj_name_cpy(map->name, attr->map_name,
1218 sizeof(attr->map_name));
1222 atomic64_set(&map->refcnt, 1);
1223 atomic64_set(&map->usercnt, 1);
1224 mutex_init(&map->freeze_mutex);
1225 spin_lock_init(&map->owner.lock);
1227 if (attr->btf_key_type_id || attr->btf_value_type_id ||
1228 /* Even the map's value is a kernel's struct,
1229 * the bpf_prog.o must have BTF to begin with
1230 * to figure out the corresponding kernel's
1231 * counter part. Thus, attr->btf_fd has
1234 attr->btf_vmlinux_value_type_id) {
1237 btf = btf_get_by_fd(attr->btf_fd);
1242 if (btf_is_kernel(btf)) {
1249 if (attr->btf_value_type_id) {
1250 err = map_check_btf(map, btf, attr->btf_key_type_id,
1251 attr->btf_value_type_id);
1256 map->btf_key_type_id = attr->btf_key_type_id;
1257 map->btf_value_type_id = attr->btf_value_type_id;
1258 map->btf_vmlinux_value_type_id =
1259 attr->btf_vmlinux_value_type_id;
1262 err = security_bpf_map_alloc(map);
1266 err = bpf_map_alloc_id(map);
1270 bpf_map_save_memcg(map);
1272 err = bpf_map_new_fd(map, f_flags);
1274 /* failed to allocate fd.
1275 * bpf_map_put_with_uref() is needed because the above
1276 * bpf_map_alloc_id() has published the map
1277 * to the userspace and the userspace may
1278 * have refcnt-ed it through BPF_MAP_GET_FD_BY_ID.
1280 bpf_map_put_with_uref(map);
1287 security_bpf_map_free(map);
1290 map->ops->map_free(map);
1294 /* if error is returned, fd is released.
1295 * On success caller should complete fd access with matching fdput()
1297 struct bpf_map *__bpf_map_get(struct fd f)
1300 return ERR_PTR(-EBADF);
1301 if (f.file->f_op != &bpf_map_fops) {
1303 return ERR_PTR(-EINVAL);
1306 return f.file->private_data;
1309 void bpf_map_inc(struct bpf_map *map)
1311 atomic64_inc(&map->refcnt);
1313 EXPORT_SYMBOL_GPL(bpf_map_inc);
1315 void bpf_map_inc_with_uref(struct bpf_map *map)
1317 atomic64_inc(&map->refcnt);
1318 atomic64_inc(&map->usercnt);
1320 EXPORT_SYMBOL_GPL(bpf_map_inc_with_uref);
1322 struct bpf_map *bpf_map_get(u32 ufd)
1324 struct fd f = fdget(ufd);
1325 struct bpf_map *map;
1327 map = __bpf_map_get(f);
1336 EXPORT_SYMBOL(bpf_map_get);
1338 struct bpf_map *bpf_map_get_with_uref(u32 ufd)
1340 struct fd f = fdget(ufd);
1341 struct bpf_map *map;
1343 map = __bpf_map_get(f);
1347 bpf_map_inc_with_uref(map);
1353 /* map_idr_lock should have been held or the map should have been
1354 * protected by rcu read lock.
1356 struct bpf_map *__bpf_map_inc_not_zero(struct bpf_map *map, bool uref)
1360 refold = atomic64_fetch_add_unless(&map->refcnt, 1, 0);
1362 return ERR_PTR(-ENOENT);
1364 atomic64_inc(&map->usercnt);
1369 struct bpf_map *bpf_map_inc_not_zero(struct bpf_map *map)
1371 spin_lock_bh(&map_idr_lock);
1372 map = __bpf_map_inc_not_zero(map, false);
1373 spin_unlock_bh(&map_idr_lock);
1377 EXPORT_SYMBOL_GPL(bpf_map_inc_not_zero);
1379 int __weak bpf_stackmap_copy(struct bpf_map *map, void *key, void *value)
1384 static void *__bpf_copy_key(void __user *ukey, u64 key_size)
1387 return vmemdup_user(ukey, key_size);
1390 return ERR_PTR(-EINVAL);
1395 static void *___bpf_copy_key(bpfptr_t ukey, u64 key_size)
1398 return kvmemdup_bpfptr(ukey, key_size);
1400 if (!bpfptr_is_null(ukey))
1401 return ERR_PTR(-EINVAL);
1406 /* last field in 'union bpf_attr' used by this command */
1407 #define BPF_MAP_LOOKUP_ELEM_LAST_FIELD flags
1409 static int map_lookup_elem(union bpf_attr *attr)
1411 void __user *ukey = u64_to_user_ptr(attr->key);
1412 void __user *uvalue = u64_to_user_ptr(attr->value);
1413 int ufd = attr->map_fd;
1414 struct bpf_map *map;
1420 if (CHECK_ATTR(BPF_MAP_LOOKUP_ELEM))
1423 if (attr->flags & ~BPF_F_LOCK)
1427 map = __bpf_map_get(f);
1429 return PTR_ERR(map);
1430 if (!(map_get_sys_perms(map, f) & FMODE_CAN_READ)) {
1435 if ((attr->flags & BPF_F_LOCK) &&
1436 !btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
1441 key = __bpf_copy_key(ukey, map->key_size);
1447 value_size = bpf_map_value_size(map);
1450 value = kvmalloc(value_size, GFP_USER | __GFP_NOWARN);
1454 if (map->map_type == BPF_MAP_TYPE_BLOOM_FILTER) {
1455 if (copy_from_user(value, uvalue, value_size))
1458 err = bpf_map_copy_value(map, key, value, attr->flags);
1462 err = bpf_map_copy_value(map, key, value, attr->flags);
1467 if (copy_to_user(uvalue, value, value_size) != 0)
1482 #define BPF_MAP_UPDATE_ELEM_LAST_FIELD flags
1484 static int map_update_elem(union bpf_attr *attr, bpfptr_t uattr)
1486 bpfptr_t ukey = make_bpfptr(attr->key, uattr.is_kernel);
1487 bpfptr_t uvalue = make_bpfptr(attr->value, uattr.is_kernel);
1488 int ufd = attr->map_fd;
1489 struct bpf_map *map;
1495 if (CHECK_ATTR(BPF_MAP_UPDATE_ELEM))
1499 map = __bpf_map_get(f);
1501 return PTR_ERR(map);
1502 bpf_map_write_active_inc(map);
1503 if (!(map_get_sys_perms(map, f) & FMODE_CAN_WRITE)) {
1508 if ((attr->flags & BPF_F_LOCK) &&
1509 !btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
1514 key = ___bpf_copy_key(ukey, map->key_size);
1520 value_size = bpf_map_value_size(map);
1521 value = kvmemdup_bpfptr(uvalue, value_size);
1522 if (IS_ERR(value)) {
1523 err = PTR_ERR(value);
1527 err = bpf_map_update_value(map, f.file, key, value, attr->flags);
1533 bpf_map_write_active_dec(map);
1538 #define BPF_MAP_DELETE_ELEM_LAST_FIELD key
1540 static int map_delete_elem(union bpf_attr *attr, bpfptr_t uattr)
1542 bpfptr_t ukey = make_bpfptr(attr->key, uattr.is_kernel);
1543 int ufd = attr->map_fd;
1544 struct bpf_map *map;
1549 if (CHECK_ATTR(BPF_MAP_DELETE_ELEM))
1553 map = __bpf_map_get(f);
1555 return PTR_ERR(map);
1556 bpf_map_write_active_inc(map);
1557 if (!(map_get_sys_perms(map, f) & FMODE_CAN_WRITE)) {
1562 key = ___bpf_copy_key(ukey, map->key_size);
1568 if (bpf_map_is_offloaded(map)) {
1569 err = bpf_map_offload_delete_elem(map, key);
1571 } else if (IS_FD_PROG_ARRAY(map) ||
1572 map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
1573 /* These maps require sleepable context */
1574 err = map->ops->map_delete_elem(map, key);
1578 bpf_disable_instrumentation();
1580 err = map->ops->map_delete_elem(map, key);
1582 bpf_enable_instrumentation();
1583 maybe_wait_bpf_programs(map);
1587 bpf_map_write_active_dec(map);
1592 /* last field in 'union bpf_attr' used by this command */
1593 #define BPF_MAP_GET_NEXT_KEY_LAST_FIELD next_key
1595 static int map_get_next_key(union bpf_attr *attr)
1597 void __user *ukey = u64_to_user_ptr(attr->key);
1598 void __user *unext_key = u64_to_user_ptr(attr->next_key);
1599 int ufd = attr->map_fd;
1600 struct bpf_map *map;
1601 void *key, *next_key;
1605 if (CHECK_ATTR(BPF_MAP_GET_NEXT_KEY))
1609 map = __bpf_map_get(f);
1611 return PTR_ERR(map);
1612 if (!(map_get_sys_perms(map, f) & FMODE_CAN_READ)) {
1618 key = __bpf_copy_key(ukey, map->key_size);
1628 next_key = kvmalloc(map->key_size, GFP_USER);
1632 if (bpf_map_is_offloaded(map)) {
1633 err = bpf_map_offload_get_next_key(map, key, next_key);
1638 err = map->ops->map_get_next_key(map, key, next_key);
1645 if (copy_to_user(unext_key, next_key, map->key_size) != 0)
1659 int generic_map_delete_batch(struct bpf_map *map,
1660 const union bpf_attr *attr,
1661 union bpf_attr __user *uattr)
1663 void __user *keys = u64_to_user_ptr(attr->batch.keys);
1668 if (attr->batch.elem_flags & ~BPF_F_LOCK)
1671 if ((attr->batch.elem_flags & BPF_F_LOCK) &&
1672 !btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
1676 max_count = attr->batch.count;
1680 key = kvmalloc(map->key_size, GFP_USER | __GFP_NOWARN);
1684 for (cp = 0; cp < max_count; cp++) {
1686 if (copy_from_user(key, keys + cp * map->key_size,
1690 if (bpf_map_is_offloaded(map)) {
1691 err = bpf_map_offload_delete_elem(map, key);
1695 bpf_disable_instrumentation();
1697 err = map->ops->map_delete_elem(map, key);
1699 bpf_enable_instrumentation();
1704 if (copy_to_user(&uattr->batch.count, &cp, sizeof(cp)))
1709 maybe_wait_bpf_programs(map);
1713 int generic_map_update_batch(struct bpf_map *map, struct file *map_file,
1714 const union bpf_attr *attr,
1715 union bpf_attr __user *uattr)
1717 void __user *values = u64_to_user_ptr(attr->batch.values);
1718 void __user *keys = u64_to_user_ptr(attr->batch.keys);
1719 u32 value_size, cp, max_count;
1723 if (attr->batch.elem_flags & ~BPF_F_LOCK)
1726 if ((attr->batch.elem_flags & BPF_F_LOCK) &&
1727 !btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
1731 value_size = bpf_map_value_size(map);
1733 max_count = attr->batch.count;
1737 key = kvmalloc(map->key_size, GFP_USER | __GFP_NOWARN);
1741 value = kvmalloc(value_size, GFP_USER | __GFP_NOWARN);
1747 for (cp = 0; cp < max_count; cp++) {
1749 if (copy_from_user(key, keys + cp * map->key_size,
1751 copy_from_user(value, values + cp * value_size, value_size))
1754 err = bpf_map_update_value(map, map_file, key, value,
1755 attr->batch.elem_flags);
1762 if (copy_to_user(&uattr->batch.count, &cp, sizeof(cp)))
1770 #define MAP_LOOKUP_RETRIES 3
1772 int generic_map_lookup_batch(struct bpf_map *map,
1773 const union bpf_attr *attr,
1774 union bpf_attr __user *uattr)
1776 void __user *uobatch = u64_to_user_ptr(attr->batch.out_batch);
1777 void __user *ubatch = u64_to_user_ptr(attr->batch.in_batch);
1778 void __user *values = u64_to_user_ptr(attr->batch.values);
1779 void __user *keys = u64_to_user_ptr(attr->batch.keys);
1780 void *buf, *buf_prevkey, *prev_key, *key, *value;
1781 int err, retry = MAP_LOOKUP_RETRIES;
1782 u32 value_size, cp, max_count;
1784 if (attr->batch.elem_flags & ~BPF_F_LOCK)
1787 if ((attr->batch.elem_flags & BPF_F_LOCK) &&
1788 !btf_record_has_field(map->record, BPF_SPIN_LOCK))
1791 value_size = bpf_map_value_size(map);
1793 max_count = attr->batch.count;
1797 if (put_user(0, &uattr->batch.count))
1800 buf_prevkey = kvmalloc(map->key_size, GFP_USER | __GFP_NOWARN);
1804 buf = kvmalloc(map->key_size + value_size, GFP_USER | __GFP_NOWARN);
1806 kvfree(buf_prevkey);
1812 if (ubatch && copy_from_user(buf_prevkey, ubatch, map->key_size))
1815 value = key + map->key_size;
1817 prev_key = buf_prevkey;
1819 for (cp = 0; cp < max_count;) {
1821 err = map->ops->map_get_next_key(map, prev_key, key);
1825 err = bpf_map_copy_value(map, key, value,
1826 attr->batch.elem_flags);
1828 if (err == -ENOENT) {
1840 if (copy_to_user(keys + cp * map->key_size, key,
1845 if (copy_to_user(values + cp * value_size, value, value_size)) {
1851 prev_key = buf_prevkey;
1853 swap(prev_key, key);
1854 retry = MAP_LOOKUP_RETRIES;
1862 if ((copy_to_user(&uattr->batch.count, &cp, sizeof(cp)) ||
1863 (cp && copy_to_user(uobatch, prev_key, map->key_size))))
1867 kvfree(buf_prevkey);
1872 #define BPF_MAP_LOOKUP_AND_DELETE_ELEM_LAST_FIELD flags
1874 static int map_lookup_and_delete_elem(union bpf_attr *attr)
1876 void __user *ukey = u64_to_user_ptr(attr->key);
1877 void __user *uvalue = u64_to_user_ptr(attr->value);
1878 int ufd = attr->map_fd;
1879 struct bpf_map *map;
1885 if (CHECK_ATTR(BPF_MAP_LOOKUP_AND_DELETE_ELEM))
1888 if (attr->flags & ~BPF_F_LOCK)
1892 map = __bpf_map_get(f);
1894 return PTR_ERR(map);
1895 bpf_map_write_active_inc(map);
1896 if (!(map_get_sys_perms(map, f) & FMODE_CAN_READ) ||
1897 !(map_get_sys_perms(map, f) & FMODE_CAN_WRITE)) {
1903 (map->map_type == BPF_MAP_TYPE_QUEUE ||
1904 map->map_type == BPF_MAP_TYPE_STACK)) {
1909 if ((attr->flags & BPF_F_LOCK) &&
1910 !btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
1915 key = __bpf_copy_key(ukey, map->key_size);
1921 value_size = bpf_map_value_size(map);
1924 value = kvmalloc(value_size, GFP_USER | __GFP_NOWARN);
1929 if (map->map_type == BPF_MAP_TYPE_QUEUE ||
1930 map->map_type == BPF_MAP_TYPE_STACK) {
1931 err = map->ops->map_pop_elem(map, value);
1932 } else if (map->map_type == BPF_MAP_TYPE_HASH ||
1933 map->map_type == BPF_MAP_TYPE_PERCPU_HASH ||
1934 map->map_type == BPF_MAP_TYPE_LRU_HASH ||
1935 map->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH) {
1936 if (!bpf_map_is_offloaded(map)) {
1937 bpf_disable_instrumentation();
1939 err = map->ops->map_lookup_and_delete_elem(map, key, value, attr->flags);
1941 bpf_enable_instrumentation();
1948 if (copy_to_user(uvalue, value, value_size) != 0) {
1960 bpf_map_write_active_dec(map);
1965 #define BPF_MAP_FREEZE_LAST_FIELD map_fd
1967 static int map_freeze(const union bpf_attr *attr)
1969 int err = 0, ufd = attr->map_fd;
1970 struct bpf_map *map;
1973 if (CHECK_ATTR(BPF_MAP_FREEZE))
1977 map = __bpf_map_get(f);
1979 return PTR_ERR(map);
1981 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS || !IS_ERR_OR_NULL(map->record)) {
1986 if (!(map_get_sys_perms(map, f) & FMODE_CAN_WRITE)) {
1991 mutex_lock(&map->freeze_mutex);
1992 if (bpf_map_write_active(map)) {
1996 if (READ_ONCE(map->frozen)) {
2001 WRITE_ONCE(map->frozen, true);
2003 mutex_unlock(&map->freeze_mutex);
2008 static const struct bpf_prog_ops * const bpf_prog_types[] = {
2009 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
2010 [_id] = & _name ## _prog_ops,
2011 #define BPF_MAP_TYPE(_id, _ops)
2012 #define BPF_LINK_TYPE(_id, _name)
2013 #include <linux/bpf_types.h>
2014 #undef BPF_PROG_TYPE
2016 #undef BPF_LINK_TYPE
2019 static int find_prog_type(enum bpf_prog_type type, struct bpf_prog *prog)
2021 const struct bpf_prog_ops *ops;
2023 if (type >= ARRAY_SIZE(bpf_prog_types))
2025 type = array_index_nospec(type, ARRAY_SIZE(bpf_prog_types));
2026 ops = bpf_prog_types[type];
2030 if (!bpf_prog_is_offloaded(prog->aux))
2031 prog->aux->ops = ops;
2033 prog->aux->ops = &bpf_offload_prog_ops;
2044 static const char * const bpf_audit_str[BPF_AUDIT_MAX] = {
2045 [BPF_AUDIT_LOAD] = "LOAD",
2046 [BPF_AUDIT_UNLOAD] = "UNLOAD",
2049 static void bpf_audit_prog(const struct bpf_prog *prog, unsigned int op)
2051 struct audit_context *ctx = NULL;
2052 struct audit_buffer *ab;
2054 if (WARN_ON_ONCE(op >= BPF_AUDIT_MAX))
2056 if (audit_enabled == AUDIT_OFF)
2058 if (!in_irq() && !irqs_disabled())
2059 ctx = audit_context();
2060 ab = audit_log_start(ctx, GFP_ATOMIC, AUDIT_BPF);
2063 audit_log_format(ab, "prog-id=%u op=%s",
2064 prog->aux->id, bpf_audit_str[op]);
2068 static int bpf_prog_alloc_id(struct bpf_prog *prog)
2072 idr_preload(GFP_KERNEL);
2073 spin_lock_bh(&prog_idr_lock);
2074 id = idr_alloc_cyclic(&prog_idr, prog, 1, INT_MAX, GFP_ATOMIC);
2077 spin_unlock_bh(&prog_idr_lock);
2080 /* id is in [1, INT_MAX) */
2081 if (WARN_ON_ONCE(!id))
2084 return id > 0 ? 0 : id;
2087 void bpf_prog_free_id(struct bpf_prog *prog)
2089 unsigned long flags;
2091 /* cBPF to eBPF migrations are currently not in the idr store.
2092 * Offloaded programs are removed from the store when their device
2093 * disappears - even if someone grabs an fd to them they are unusable,
2094 * simply waiting for refcnt to drop to be freed.
2099 spin_lock_irqsave(&prog_idr_lock, flags);
2100 idr_remove(&prog_idr, prog->aux->id);
2102 spin_unlock_irqrestore(&prog_idr_lock, flags);
2105 static void __bpf_prog_put_rcu(struct rcu_head *rcu)
2107 struct bpf_prog_aux *aux = container_of(rcu, struct bpf_prog_aux, rcu);
2109 kvfree(aux->func_info);
2110 kfree(aux->func_info_aux);
2111 free_uid(aux->user);
2112 security_bpf_prog_free(aux);
2113 bpf_prog_free(aux->prog);
2116 static void __bpf_prog_put_noref(struct bpf_prog *prog, bool deferred)
2118 bpf_prog_kallsyms_del_all(prog);
2119 btf_put(prog->aux->btf);
2120 module_put(prog->aux->mod);
2121 kvfree(prog->aux->jited_linfo);
2122 kvfree(prog->aux->linfo);
2123 kfree(prog->aux->kfunc_tab);
2124 if (prog->aux->attach_btf)
2125 btf_put(prog->aux->attach_btf);
2128 if (prog->aux->sleepable)
2129 call_rcu_tasks_trace(&prog->aux->rcu, __bpf_prog_put_rcu);
2131 call_rcu(&prog->aux->rcu, __bpf_prog_put_rcu);
2133 __bpf_prog_put_rcu(&prog->aux->rcu);
2137 static void bpf_prog_put_deferred(struct work_struct *work)
2139 struct bpf_prog_aux *aux;
2140 struct bpf_prog *prog;
2142 aux = container_of(work, struct bpf_prog_aux, work);
2144 perf_event_bpf_event(prog, PERF_BPF_EVENT_PROG_UNLOAD, 0);
2145 bpf_audit_prog(prog, BPF_AUDIT_UNLOAD);
2146 bpf_prog_free_id(prog);
2147 __bpf_prog_put_noref(prog, true);
2150 static void __bpf_prog_put(struct bpf_prog *prog)
2152 struct bpf_prog_aux *aux = prog->aux;
2154 if (atomic64_dec_and_test(&aux->refcnt)) {
2155 if (in_irq() || irqs_disabled()) {
2156 INIT_WORK(&aux->work, bpf_prog_put_deferred);
2157 schedule_work(&aux->work);
2159 bpf_prog_put_deferred(&aux->work);
2164 void bpf_prog_put(struct bpf_prog *prog)
2166 __bpf_prog_put(prog);
2168 EXPORT_SYMBOL_GPL(bpf_prog_put);
2170 static int bpf_prog_release(struct inode *inode, struct file *filp)
2172 struct bpf_prog *prog = filp->private_data;
2178 struct bpf_prog_kstats {
2184 void notrace bpf_prog_inc_misses_counter(struct bpf_prog *prog)
2186 struct bpf_prog_stats *stats;
2189 stats = this_cpu_ptr(prog->stats);
2190 flags = u64_stats_update_begin_irqsave(&stats->syncp);
2191 u64_stats_inc(&stats->misses);
2192 u64_stats_update_end_irqrestore(&stats->syncp, flags);
2195 static void bpf_prog_get_stats(const struct bpf_prog *prog,
2196 struct bpf_prog_kstats *stats)
2198 u64 nsecs = 0, cnt = 0, misses = 0;
2201 for_each_possible_cpu(cpu) {
2202 const struct bpf_prog_stats *st;
2204 u64 tnsecs, tcnt, tmisses;
2206 st = per_cpu_ptr(prog->stats, cpu);
2208 start = u64_stats_fetch_begin(&st->syncp);
2209 tnsecs = u64_stats_read(&st->nsecs);
2210 tcnt = u64_stats_read(&st->cnt);
2211 tmisses = u64_stats_read(&st->misses);
2212 } while (u64_stats_fetch_retry(&st->syncp, start));
2217 stats->nsecs = nsecs;
2219 stats->misses = misses;
2222 #ifdef CONFIG_PROC_FS
2223 static void bpf_prog_show_fdinfo(struct seq_file *m, struct file *filp)
2225 const struct bpf_prog *prog = filp->private_data;
2226 char prog_tag[sizeof(prog->tag) * 2 + 1] = { };
2227 struct bpf_prog_kstats stats;
2229 bpf_prog_get_stats(prog, &stats);
2230 bin2hex(prog_tag, prog->tag, sizeof(prog->tag));
2237 "run_time_ns:\t%llu\n"
2239 "recursion_misses:\t%llu\n"
2240 "verified_insns:\t%u\n",
2244 prog->pages * 1ULL << PAGE_SHIFT,
2249 prog->aux->verified_insns);
2253 const struct file_operations bpf_prog_fops = {
2254 #ifdef CONFIG_PROC_FS
2255 .show_fdinfo = bpf_prog_show_fdinfo,
2257 .release = bpf_prog_release,
2258 .read = bpf_dummy_read,
2259 .write = bpf_dummy_write,
2262 int bpf_prog_new_fd(struct bpf_prog *prog)
2266 ret = security_bpf_prog(prog);
2270 return anon_inode_getfd("bpf-prog", &bpf_prog_fops, prog,
2271 O_RDWR | O_CLOEXEC);
2274 static struct bpf_prog *____bpf_prog_get(struct fd f)
2277 return ERR_PTR(-EBADF);
2278 if (f.file->f_op != &bpf_prog_fops) {
2280 return ERR_PTR(-EINVAL);
2283 return f.file->private_data;
2286 void bpf_prog_add(struct bpf_prog *prog, int i)
2288 atomic64_add(i, &prog->aux->refcnt);
2290 EXPORT_SYMBOL_GPL(bpf_prog_add);
2292 void bpf_prog_sub(struct bpf_prog *prog, int i)
2294 /* Only to be used for undoing previous bpf_prog_add() in some
2295 * error path. We still know that another entity in our call
2296 * path holds a reference to the program, thus atomic_sub() can
2297 * be safely used in such cases!
2299 WARN_ON(atomic64_sub_return(i, &prog->aux->refcnt) == 0);
2301 EXPORT_SYMBOL_GPL(bpf_prog_sub);
2303 void bpf_prog_inc(struct bpf_prog *prog)
2305 atomic64_inc(&prog->aux->refcnt);
2307 EXPORT_SYMBOL_GPL(bpf_prog_inc);
2309 /* prog_idr_lock should have been held */
2310 struct bpf_prog *bpf_prog_inc_not_zero(struct bpf_prog *prog)
2314 refold = atomic64_fetch_add_unless(&prog->aux->refcnt, 1, 0);
2317 return ERR_PTR(-ENOENT);
2321 EXPORT_SYMBOL_GPL(bpf_prog_inc_not_zero);
2323 bool bpf_prog_get_ok(struct bpf_prog *prog,
2324 enum bpf_prog_type *attach_type, bool attach_drv)
2326 /* not an attachment, just a refcount inc, always allow */
2330 if (prog->type != *attach_type)
2332 if (bpf_prog_is_offloaded(prog->aux) && !attach_drv)
2338 static struct bpf_prog *__bpf_prog_get(u32 ufd, enum bpf_prog_type *attach_type,
2341 struct fd f = fdget(ufd);
2342 struct bpf_prog *prog;
2344 prog = ____bpf_prog_get(f);
2347 if (!bpf_prog_get_ok(prog, attach_type, attach_drv)) {
2348 prog = ERR_PTR(-EINVAL);
2358 struct bpf_prog *bpf_prog_get(u32 ufd)
2360 return __bpf_prog_get(ufd, NULL, false);
2363 struct bpf_prog *bpf_prog_get_type_dev(u32 ufd, enum bpf_prog_type type,
2366 return __bpf_prog_get(ufd, &type, attach_drv);
2368 EXPORT_SYMBOL_GPL(bpf_prog_get_type_dev);
2370 /* Initially all BPF programs could be loaded w/o specifying
2371 * expected_attach_type. Later for some of them specifying expected_attach_type
2372 * at load time became required so that program could be validated properly.
2373 * Programs of types that are allowed to be loaded both w/ and w/o (for
2374 * backward compatibility) expected_attach_type, should have the default attach
2375 * type assigned to expected_attach_type for the latter case, so that it can be
2376 * validated later at attach time.
2378 * bpf_prog_load_fixup_attach_type() sets expected_attach_type in @attr if
2379 * prog type requires it but has some attach types that have to be backward
2382 static void bpf_prog_load_fixup_attach_type(union bpf_attr *attr)
2384 switch (attr->prog_type) {
2385 case BPF_PROG_TYPE_CGROUP_SOCK:
2386 /* Unfortunately BPF_ATTACH_TYPE_UNSPEC enumeration doesn't
2387 * exist so checking for non-zero is the way to go here.
2389 if (!attr->expected_attach_type)
2390 attr->expected_attach_type =
2391 BPF_CGROUP_INET_SOCK_CREATE;
2393 case BPF_PROG_TYPE_SK_REUSEPORT:
2394 if (!attr->expected_attach_type)
2395 attr->expected_attach_type =
2396 BPF_SK_REUSEPORT_SELECT;
2402 bpf_prog_load_check_attach(enum bpf_prog_type prog_type,
2403 enum bpf_attach_type expected_attach_type,
2404 struct btf *attach_btf, u32 btf_id,
2405 struct bpf_prog *dst_prog)
2408 if (btf_id > BTF_MAX_TYPE)
2411 if (!attach_btf && !dst_prog)
2414 switch (prog_type) {
2415 case BPF_PROG_TYPE_TRACING:
2416 case BPF_PROG_TYPE_LSM:
2417 case BPF_PROG_TYPE_STRUCT_OPS:
2418 case BPF_PROG_TYPE_EXT:
2425 if (attach_btf && (!btf_id || dst_prog))
2428 if (dst_prog && prog_type != BPF_PROG_TYPE_TRACING &&
2429 prog_type != BPF_PROG_TYPE_EXT)
2432 switch (prog_type) {
2433 case BPF_PROG_TYPE_CGROUP_SOCK:
2434 switch (expected_attach_type) {
2435 case BPF_CGROUP_INET_SOCK_CREATE:
2436 case BPF_CGROUP_INET_SOCK_RELEASE:
2437 case BPF_CGROUP_INET4_POST_BIND:
2438 case BPF_CGROUP_INET6_POST_BIND:
2443 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
2444 switch (expected_attach_type) {
2445 case BPF_CGROUP_INET4_BIND:
2446 case BPF_CGROUP_INET6_BIND:
2447 case BPF_CGROUP_INET4_CONNECT:
2448 case BPF_CGROUP_INET6_CONNECT:
2449 case BPF_CGROUP_UNIX_CONNECT:
2450 case BPF_CGROUP_INET4_GETPEERNAME:
2451 case BPF_CGROUP_INET6_GETPEERNAME:
2452 case BPF_CGROUP_UNIX_GETPEERNAME:
2453 case BPF_CGROUP_INET4_GETSOCKNAME:
2454 case BPF_CGROUP_INET6_GETSOCKNAME:
2455 case BPF_CGROUP_UNIX_GETSOCKNAME:
2456 case BPF_CGROUP_UDP4_SENDMSG:
2457 case BPF_CGROUP_UDP6_SENDMSG:
2458 case BPF_CGROUP_UNIX_SENDMSG:
2459 case BPF_CGROUP_UDP4_RECVMSG:
2460 case BPF_CGROUP_UDP6_RECVMSG:
2461 case BPF_CGROUP_UNIX_RECVMSG:
2466 case BPF_PROG_TYPE_CGROUP_SKB:
2467 switch (expected_attach_type) {
2468 case BPF_CGROUP_INET_INGRESS:
2469 case BPF_CGROUP_INET_EGRESS:
2474 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
2475 switch (expected_attach_type) {
2476 case BPF_CGROUP_SETSOCKOPT:
2477 case BPF_CGROUP_GETSOCKOPT:
2482 case BPF_PROG_TYPE_SK_LOOKUP:
2483 if (expected_attach_type == BPF_SK_LOOKUP)
2486 case BPF_PROG_TYPE_SK_REUSEPORT:
2487 switch (expected_attach_type) {
2488 case BPF_SK_REUSEPORT_SELECT:
2489 case BPF_SK_REUSEPORT_SELECT_OR_MIGRATE:
2494 case BPF_PROG_TYPE_NETFILTER:
2495 if (expected_attach_type == BPF_NETFILTER)
2498 case BPF_PROG_TYPE_SYSCALL:
2499 case BPF_PROG_TYPE_EXT:
2500 if (expected_attach_type)
2508 static bool is_net_admin_prog_type(enum bpf_prog_type prog_type)
2510 switch (prog_type) {
2511 case BPF_PROG_TYPE_SCHED_CLS:
2512 case BPF_PROG_TYPE_SCHED_ACT:
2513 case BPF_PROG_TYPE_XDP:
2514 case BPF_PROG_TYPE_LWT_IN:
2515 case BPF_PROG_TYPE_LWT_OUT:
2516 case BPF_PROG_TYPE_LWT_XMIT:
2517 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
2518 case BPF_PROG_TYPE_SK_SKB:
2519 case BPF_PROG_TYPE_SK_MSG:
2520 case BPF_PROG_TYPE_FLOW_DISSECTOR:
2521 case BPF_PROG_TYPE_CGROUP_DEVICE:
2522 case BPF_PROG_TYPE_CGROUP_SOCK:
2523 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
2524 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
2525 case BPF_PROG_TYPE_CGROUP_SYSCTL:
2526 case BPF_PROG_TYPE_SOCK_OPS:
2527 case BPF_PROG_TYPE_EXT: /* extends any prog */
2528 case BPF_PROG_TYPE_NETFILTER:
2530 case BPF_PROG_TYPE_CGROUP_SKB:
2532 case BPF_PROG_TYPE_SK_REUSEPORT:
2533 /* equivalent to SOCKET_FILTER. need CAP_BPF only */
2539 static bool is_perfmon_prog_type(enum bpf_prog_type prog_type)
2541 switch (prog_type) {
2542 case BPF_PROG_TYPE_KPROBE:
2543 case BPF_PROG_TYPE_TRACEPOINT:
2544 case BPF_PROG_TYPE_PERF_EVENT:
2545 case BPF_PROG_TYPE_RAW_TRACEPOINT:
2546 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
2547 case BPF_PROG_TYPE_TRACING:
2548 case BPF_PROG_TYPE_LSM:
2549 case BPF_PROG_TYPE_STRUCT_OPS: /* has access to struct sock */
2550 case BPF_PROG_TYPE_EXT: /* extends any prog */
2557 /* last field in 'union bpf_attr' used by this command */
2558 #define BPF_PROG_LOAD_LAST_FIELD log_true_size
2560 static int bpf_prog_load(union bpf_attr *attr, bpfptr_t uattr, u32 uattr_size)
2562 enum bpf_prog_type type = attr->prog_type;
2563 struct bpf_prog *prog, *dst_prog = NULL;
2564 struct btf *attach_btf = NULL;
2568 if (CHECK_ATTR(BPF_PROG_LOAD))
2571 if (attr->prog_flags & ~(BPF_F_STRICT_ALIGNMENT |
2572 BPF_F_ANY_ALIGNMENT |
2573 BPF_F_TEST_STATE_FREQ |
2575 BPF_F_TEST_RND_HI32 |
2576 BPF_F_XDP_HAS_FRAGS |
2577 BPF_F_XDP_DEV_BOUND_ONLY))
2580 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS) &&
2581 (attr->prog_flags & BPF_F_ANY_ALIGNMENT) &&
2585 /* Intent here is for unprivileged_bpf_disabled to block BPF program
2586 * creation for unprivileged users; other actions depend
2587 * on fd availability and access to bpffs, so are dependent on
2588 * object creation success. Even with unprivileged BPF disabled,
2589 * capability checks are still carried out for these
2590 * and other operations.
2592 if (sysctl_unprivileged_bpf_disabled && !bpf_capable())
2595 if (attr->insn_cnt == 0 ||
2596 attr->insn_cnt > (bpf_capable() ? BPF_COMPLEXITY_LIMIT_INSNS : BPF_MAXINSNS))
2598 if (type != BPF_PROG_TYPE_SOCKET_FILTER &&
2599 type != BPF_PROG_TYPE_CGROUP_SKB &&
2603 if (is_net_admin_prog_type(type) && !capable(CAP_NET_ADMIN) && !capable(CAP_SYS_ADMIN))
2605 if (is_perfmon_prog_type(type) && !perfmon_capable())
2608 /* attach_prog_fd/attach_btf_obj_fd can specify fd of either bpf_prog
2609 * or btf, we need to check which one it is
2611 if (attr->attach_prog_fd) {
2612 dst_prog = bpf_prog_get(attr->attach_prog_fd);
2613 if (IS_ERR(dst_prog)) {
2615 attach_btf = btf_get_by_fd(attr->attach_btf_obj_fd);
2616 if (IS_ERR(attach_btf))
2618 if (!btf_is_kernel(attach_btf)) {
2619 /* attaching through specifying bpf_prog's BTF
2620 * objects directly might be supported eventually
2622 btf_put(attach_btf);
2626 } else if (attr->attach_btf_id) {
2627 /* fall back to vmlinux BTF, if BTF type ID is specified */
2628 attach_btf = bpf_get_btf_vmlinux();
2629 if (IS_ERR(attach_btf))
2630 return PTR_ERR(attach_btf);
2633 btf_get(attach_btf);
2636 bpf_prog_load_fixup_attach_type(attr);
2637 if (bpf_prog_load_check_attach(type, attr->expected_attach_type,
2638 attach_btf, attr->attach_btf_id,
2641 bpf_prog_put(dst_prog);
2643 btf_put(attach_btf);
2647 /* plain bpf_prog allocation */
2648 prog = bpf_prog_alloc(bpf_prog_size(attr->insn_cnt), GFP_USER);
2651 bpf_prog_put(dst_prog);
2653 btf_put(attach_btf);
2657 prog->expected_attach_type = attr->expected_attach_type;
2658 prog->aux->attach_btf = attach_btf;
2659 prog->aux->attach_btf_id = attr->attach_btf_id;
2660 prog->aux->dst_prog = dst_prog;
2661 prog->aux->dev_bound = !!attr->prog_ifindex;
2662 prog->aux->sleepable = attr->prog_flags & BPF_F_SLEEPABLE;
2663 prog->aux->xdp_has_frags = attr->prog_flags & BPF_F_XDP_HAS_FRAGS;
2665 err = security_bpf_prog_alloc(prog->aux);
2669 prog->aux->user = get_current_user();
2670 prog->len = attr->insn_cnt;
2673 if (copy_from_bpfptr(prog->insns,
2674 make_bpfptr(attr->insns, uattr.is_kernel),
2675 bpf_prog_insn_size(prog)) != 0)
2677 /* copy eBPF program license from user space */
2678 if (strncpy_from_bpfptr(license,
2679 make_bpfptr(attr->license, uattr.is_kernel),
2680 sizeof(license) - 1) < 0)
2682 license[sizeof(license) - 1] = 0;
2684 /* eBPF programs must be GPL compatible to use GPL-ed functions */
2685 prog->gpl_compatible = license_is_gpl_compatible(license) ? 1 : 0;
2687 prog->orig_prog = NULL;
2690 atomic64_set(&prog->aux->refcnt, 1);
2692 if (bpf_prog_is_dev_bound(prog->aux)) {
2693 err = bpf_prog_dev_bound_init(prog, attr);
2698 if (type == BPF_PROG_TYPE_EXT && dst_prog &&
2699 bpf_prog_is_dev_bound(dst_prog->aux)) {
2700 err = bpf_prog_dev_bound_inherit(prog, dst_prog);
2705 /* find program type: socket_filter vs tracing_filter */
2706 err = find_prog_type(type, prog);
2710 prog->aux->load_time = ktime_get_boottime_ns();
2711 err = bpf_obj_name_cpy(prog->aux->name, attr->prog_name,
2712 sizeof(attr->prog_name));
2716 /* run eBPF verifier */
2717 err = bpf_check(&prog, attr, uattr, uattr_size);
2719 goto free_used_maps;
2721 prog = bpf_prog_select_runtime(prog, &err);
2723 goto free_used_maps;
2725 err = bpf_prog_alloc_id(prog);
2727 goto free_used_maps;
2729 /* Upon success of bpf_prog_alloc_id(), the BPF prog is
2730 * effectively publicly exposed. However, retrieving via
2731 * bpf_prog_get_fd_by_id() will take another reference,
2732 * therefore it cannot be gone underneath us.
2734 * Only for the time /after/ successful bpf_prog_new_fd()
2735 * and before returning to userspace, we might just hold
2736 * one reference and any parallel close on that fd could
2737 * rip everything out. Hence, below notifications must
2738 * happen before bpf_prog_new_fd().
2740 * Also, any failure handling from this point onwards must
2741 * be using bpf_prog_put() given the program is exposed.
2743 bpf_prog_kallsyms_add(prog);
2744 perf_event_bpf_event(prog, PERF_BPF_EVENT_PROG_LOAD, 0);
2745 bpf_audit_prog(prog, BPF_AUDIT_LOAD);
2747 err = bpf_prog_new_fd(prog);
2753 /* In case we have subprogs, we need to wait for a grace
2754 * period before we can tear down JIT memory since symbols
2755 * are already exposed under kallsyms.
2757 __bpf_prog_put_noref(prog, prog->aux->real_func_cnt);
2760 free_uid(prog->aux->user);
2761 security_bpf_prog_free(prog->aux);
2763 if (prog->aux->attach_btf)
2764 btf_put(prog->aux->attach_btf);
2765 bpf_prog_free(prog);
2769 #define BPF_OBJ_LAST_FIELD path_fd
2771 static int bpf_obj_pin(const union bpf_attr *attr)
2775 if (CHECK_ATTR(BPF_OBJ) || attr->file_flags & ~BPF_F_PATH_FD)
2778 /* path_fd has to be accompanied by BPF_F_PATH_FD flag */
2779 if (!(attr->file_flags & BPF_F_PATH_FD) && attr->path_fd)
2782 path_fd = attr->file_flags & BPF_F_PATH_FD ? attr->path_fd : AT_FDCWD;
2783 return bpf_obj_pin_user(attr->bpf_fd, path_fd,
2784 u64_to_user_ptr(attr->pathname));
2787 static int bpf_obj_get(const union bpf_attr *attr)
2791 if (CHECK_ATTR(BPF_OBJ) || attr->bpf_fd != 0 ||
2792 attr->file_flags & ~(BPF_OBJ_FLAG_MASK | BPF_F_PATH_FD))
2795 /* path_fd has to be accompanied by BPF_F_PATH_FD flag */
2796 if (!(attr->file_flags & BPF_F_PATH_FD) && attr->path_fd)
2799 path_fd = attr->file_flags & BPF_F_PATH_FD ? attr->path_fd : AT_FDCWD;
2800 return bpf_obj_get_user(path_fd, u64_to_user_ptr(attr->pathname),
2804 void bpf_link_init(struct bpf_link *link, enum bpf_link_type type,
2805 const struct bpf_link_ops *ops, struct bpf_prog *prog)
2807 atomic64_set(&link->refcnt, 1);
2814 static void bpf_link_free_id(int id)
2819 spin_lock_bh(&link_idr_lock);
2820 idr_remove(&link_idr, id);
2821 spin_unlock_bh(&link_idr_lock);
2824 /* Clean up bpf_link and corresponding anon_inode file and FD. After
2825 * anon_inode is created, bpf_link can't be just kfree()'d due to deferred
2826 * anon_inode's release() call. This helper marks bpf_link as
2827 * defunct, releases anon_inode file and puts reserved FD. bpf_prog's refcnt
2828 * is not decremented, it's the responsibility of a calling code that failed
2829 * to complete bpf_link initialization.
2830 * This helper eventually calls link's dealloc callback, but does not call
2831 * link's release callback.
2833 void bpf_link_cleanup(struct bpf_link_primer *primer)
2835 primer->link->prog = NULL;
2836 bpf_link_free_id(primer->id);
2838 put_unused_fd(primer->fd);
2841 void bpf_link_inc(struct bpf_link *link)
2843 atomic64_inc(&link->refcnt);
2846 /* bpf_link_free is guaranteed to be called from process context */
2847 static void bpf_link_free(struct bpf_link *link)
2849 bpf_link_free_id(link->id);
2851 /* detach BPF program, clean up used resources */
2852 link->ops->release(link);
2853 bpf_prog_put(link->prog);
2855 /* free bpf_link and its containing memory */
2856 link->ops->dealloc(link);
2859 static void bpf_link_put_deferred(struct work_struct *work)
2861 struct bpf_link *link = container_of(work, struct bpf_link, work);
2863 bpf_link_free(link);
2866 /* bpf_link_put might be called from atomic context. It needs to be called
2867 * from sleepable context in order to acquire sleeping locks during the process.
2869 void bpf_link_put(struct bpf_link *link)
2871 if (!atomic64_dec_and_test(&link->refcnt))
2874 INIT_WORK(&link->work, bpf_link_put_deferred);
2875 schedule_work(&link->work);
2877 EXPORT_SYMBOL(bpf_link_put);
2879 static void bpf_link_put_direct(struct bpf_link *link)
2881 if (!atomic64_dec_and_test(&link->refcnt))
2883 bpf_link_free(link);
2886 static int bpf_link_release(struct inode *inode, struct file *filp)
2888 struct bpf_link *link = filp->private_data;
2890 bpf_link_put_direct(link);
2894 #ifdef CONFIG_PROC_FS
2895 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type)
2896 #define BPF_MAP_TYPE(_id, _ops)
2897 #define BPF_LINK_TYPE(_id, _name) [_id] = #_name,
2898 static const char *bpf_link_type_strs[] = {
2899 [BPF_LINK_TYPE_UNSPEC] = "<invalid>",
2900 #include <linux/bpf_types.h>
2902 #undef BPF_PROG_TYPE
2904 #undef BPF_LINK_TYPE
2906 static void bpf_link_show_fdinfo(struct seq_file *m, struct file *filp)
2908 const struct bpf_link *link = filp->private_data;
2909 const struct bpf_prog *prog = link->prog;
2910 char prog_tag[sizeof(prog->tag) * 2 + 1] = { };
2915 bpf_link_type_strs[link->type],
2918 bin2hex(prog_tag, prog->tag, sizeof(prog->tag));
2925 if (link->ops->show_fdinfo)
2926 link->ops->show_fdinfo(link, m);
2930 static const struct file_operations bpf_link_fops = {
2931 #ifdef CONFIG_PROC_FS
2932 .show_fdinfo = bpf_link_show_fdinfo,
2934 .release = bpf_link_release,
2935 .read = bpf_dummy_read,
2936 .write = bpf_dummy_write,
2939 static int bpf_link_alloc_id(struct bpf_link *link)
2943 idr_preload(GFP_KERNEL);
2944 spin_lock_bh(&link_idr_lock);
2945 id = idr_alloc_cyclic(&link_idr, link, 1, INT_MAX, GFP_ATOMIC);
2946 spin_unlock_bh(&link_idr_lock);
2952 /* Prepare bpf_link to be exposed to user-space by allocating anon_inode file,
2953 * reserving unused FD and allocating ID from link_idr. This is to be paired
2954 * with bpf_link_settle() to install FD and ID and expose bpf_link to
2955 * user-space, if bpf_link is successfully attached. If not, bpf_link and
2956 * pre-allocated resources are to be freed with bpf_cleanup() call. All the
2957 * transient state is passed around in struct bpf_link_primer.
2958 * This is preferred way to create and initialize bpf_link, especially when
2959 * there are complicated and expensive operations in between creating bpf_link
2960 * itself and attaching it to BPF hook. By using bpf_link_prime() and
2961 * bpf_link_settle() kernel code using bpf_link doesn't have to perform
2962 * expensive (and potentially failing) roll back operations in a rare case
2963 * that file, FD, or ID can't be allocated.
2965 int bpf_link_prime(struct bpf_link *link, struct bpf_link_primer *primer)
2970 fd = get_unused_fd_flags(O_CLOEXEC);
2975 id = bpf_link_alloc_id(link);
2981 file = anon_inode_getfile("bpf_link", &bpf_link_fops, link, O_CLOEXEC);
2983 bpf_link_free_id(id);
2985 return PTR_ERR(file);
2988 primer->link = link;
2989 primer->file = file;
2995 int bpf_link_settle(struct bpf_link_primer *primer)
2997 /* make bpf_link fetchable by ID */
2998 spin_lock_bh(&link_idr_lock);
2999 primer->link->id = primer->id;
3000 spin_unlock_bh(&link_idr_lock);
3001 /* make bpf_link fetchable by FD */
3002 fd_install(primer->fd, primer->file);
3003 /* pass through installed FD */
3007 int bpf_link_new_fd(struct bpf_link *link)
3009 return anon_inode_getfd("bpf-link", &bpf_link_fops, link, O_CLOEXEC);
3012 struct bpf_link *bpf_link_get_from_fd(u32 ufd)
3014 struct fd f = fdget(ufd);
3015 struct bpf_link *link;
3018 return ERR_PTR(-EBADF);
3019 if (f.file->f_op != &bpf_link_fops) {
3021 return ERR_PTR(-EINVAL);
3024 link = f.file->private_data;
3030 EXPORT_SYMBOL(bpf_link_get_from_fd);
3032 static void bpf_tracing_link_release(struct bpf_link *link)
3034 struct bpf_tracing_link *tr_link =
3035 container_of(link, struct bpf_tracing_link, link.link);
3037 WARN_ON_ONCE(bpf_trampoline_unlink_prog(&tr_link->link,
3038 tr_link->trampoline));
3040 bpf_trampoline_put(tr_link->trampoline);
3042 /* tgt_prog is NULL if target is a kernel function */
3043 if (tr_link->tgt_prog)
3044 bpf_prog_put(tr_link->tgt_prog);
3047 static void bpf_tracing_link_dealloc(struct bpf_link *link)
3049 struct bpf_tracing_link *tr_link =
3050 container_of(link, struct bpf_tracing_link, link.link);
3055 static void bpf_tracing_link_show_fdinfo(const struct bpf_link *link,
3056 struct seq_file *seq)
3058 struct bpf_tracing_link *tr_link =
3059 container_of(link, struct bpf_tracing_link, link.link);
3060 u32 target_btf_id, target_obj_id;
3062 bpf_trampoline_unpack_key(tr_link->trampoline->key,
3063 &target_obj_id, &target_btf_id);
3065 "attach_type:\t%d\n"
3066 "target_obj_id:\t%u\n"
3067 "target_btf_id:\t%u\n",
3068 tr_link->attach_type,
3073 static int bpf_tracing_link_fill_link_info(const struct bpf_link *link,
3074 struct bpf_link_info *info)
3076 struct bpf_tracing_link *tr_link =
3077 container_of(link, struct bpf_tracing_link, link.link);
3079 info->tracing.attach_type = tr_link->attach_type;
3080 bpf_trampoline_unpack_key(tr_link->trampoline->key,
3081 &info->tracing.target_obj_id,
3082 &info->tracing.target_btf_id);
3087 static const struct bpf_link_ops bpf_tracing_link_lops = {
3088 .release = bpf_tracing_link_release,
3089 .dealloc = bpf_tracing_link_dealloc,
3090 .show_fdinfo = bpf_tracing_link_show_fdinfo,
3091 .fill_link_info = bpf_tracing_link_fill_link_info,
3094 static int bpf_tracing_prog_attach(struct bpf_prog *prog,
3099 struct bpf_link_primer link_primer;
3100 struct bpf_prog *tgt_prog = NULL;
3101 struct bpf_trampoline *tr = NULL;
3102 struct bpf_tracing_link *link;
3106 switch (prog->type) {
3107 case BPF_PROG_TYPE_TRACING:
3108 if (prog->expected_attach_type != BPF_TRACE_FENTRY &&
3109 prog->expected_attach_type != BPF_TRACE_FEXIT &&
3110 prog->expected_attach_type != BPF_MODIFY_RETURN) {
3115 case BPF_PROG_TYPE_EXT:
3116 if (prog->expected_attach_type != 0) {
3121 case BPF_PROG_TYPE_LSM:
3122 if (prog->expected_attach_type != BPF_LSM_MAC) {
3132 if (!!tgt_prog_fd != !!btf_id) {
3138 /* For now we only allow new targets for BPF_PROG_TYPE_EXT */
3139 if (prog->type != BPF_PROG_TYPE_EXT) {
3144 tgt_prog = bpf_prog_get(tgt_prog_fd);
3145 if (IS_ERR(tgt_prog)) {
3146 err = PTR_ERR(tgt_prog);
3151 key = bpf_trampoline_compute_key(tgt_prog, NULL, btf_id);
3154 link = kzalloc(sizeof(*link), GFP_USER);
3159 bpf_link_init(&link->link.link, BPF_LINK_TYPE_TRACING,
3160 &bpf_tracing_link_lops, prog);
3161 link->attach_type = prog->expected_attach_type;
3162 link->link.cookie = bpf_cookie;
3164 mutex_lock(&prog->aux->dst_mutex);
3166 /* There are a few possible cases here:
3168 * - if prog->aux->dst_trampoline is set, the program was just loaded
3169 * and not yet attached to anything, so we can use the values stored
3172 * - if prog->aux->dst_trampoline is NULL, the program has already been
3173 * attached to a target and its initial target was cleared (below)
3175 * - if tgt_prog != NULL, the caller specified tgt_prog_fd +
3176 * target_btf_id using the link_create API.
3178 * - if tgt_prog == NULL when this function was called using the old
3179 * raw_tracepoint_open API, and we need a target from prog->aux
3181 * - if prog->aux->dst_trampoline and tgt_prog is NULL, the program
3182 * was detached and is going for re-attachment.
3184 if (!prog->aux->dst_trampoline && !tgt_prog) {
3186 * Allow re-attach for TRACING and LSM programs. If it's
3187 * currently linked, bpf_trampoline_link_prog will fail.
3188 * EXT programs need to specify tgt_prog_fd, so they
3189 * re-attach in separate code path.
3191 if (prog->type != BPF_PROG_TYPE_TRACING &&
3192 prog->type != BPF_PROG_TYPE_LSM) {
3196 btf_id = prog->aux->attach_btf_id;
3197 key = bpf_trampoline_compute_key(NULL, prog->aux->attach_btf, btf_id);
3200 if (!prog->aux->dst_trampoline ||
3201 (key && key != prog->aux->dst_trampoline->key)) {
3202 /* If there is no saved target, or the specified target is
3203 * different from the destination specified at load time, we
3204 * need a new trampoline and a check for compatibility
3206 struct bpf_attach_target_info tgt_info = {};
3208 err = bpf_check_attach_target(NULL, prog, tgt_prog, btf_id,
3213 if (tgt_info.tgt_mod) {
3214 module_put(prog->aux->mod);
3215 prog->aux->mod = tgt_info.tgt_mod;
3218 tr = bpf_trampoline_get(key, &tgt_info);
3224 /* The caller didn't specify a target, or the target was the
3225 * same as the destination supplied during program load. This
3226 * means we can reuse the trampoline and reference from program
3227 * load time, and there is no need to allocate a new one. This
3228 * can only happen once for any program, as the saved values in
3229 * prog->aux are cleared below.
3231 tr = prog->aux->dst_trampoline;
3232 tgt_prog = prog->aux->dst_prog;
3235 err = bpf_link_prime(&link->link.link, &link_primer);
3239 err = bpf_trampoline_link_prog(&link->link, tr);
3241 bpf_link_cleanup(&link_primer);
3246 link->tgt_prog = tgt_prog;
3247 link->trampoline = tr;
3249 /* Always clear the trampoline and target prog from prog->aux to make
3250 * sure the original attach destination is not kept alive after a
3251 * program is (re-)attached to another target.
3253 if (prog->aux->dst_prog &&
3254 (tgt_prog_fd || tr != prog->aux->dst_trampoline))
3255 /* got extra prog ref from syscall, or attaching to different prog */
3256 bpf_prog_put(prog->aux->dst_prog);
3257 if (prog->aux->dst_trampoline && tr != prog->aux->dst_trampoline)
3258 /* we allocated a new trampoline, so free the old one */
3259 bpf_trampoline_put(prog->aux->dst_trampoline);
3261 prog->aux->dst_prog = NULL;
3262 prog->aux->dst_trampoline = NULL;
3263 mutex_unlock(&prog->aux->dst_mutex);
3265 return bpf_link_settle(&link_primer);
3267 if (tr && tr != prog->aux->dst_trampoline)
3268 bpf_trampoline_put(tr);
3269 mutex_unlock(&prog->aux->dst_mutex);
3272 if (tgt_prog_fd && tgt_prog)
3273 bpf_prog_put(tgt_prog);
3277 struct bpf_raw_tp_link {
3278 struct bpf_link link;
3279 struct bpf_raw_event_map *btp;
3282 static void bpf_raw_tp_link_release(struct bpf_link *link)
3284 struct bpf_raw_tp_link *raw_tp =
3285 container_of(link, struct bpf_raw_tp_link, link);
3287 bpf_probe_unregister(raw_tp->btp, raw_tp->link.prog);
3288 bpf_put_raw_tracepoint(raw_tp->btp);
3291 static void bpf_raw_tp_link_dealloc(struct bpf_link *link)
3293 struct bpf_raw_tp_link *raw_tp =
3294 container_of(link, struct bpf_raw_tp_link, link);
3299 static void bpf_raw_tp_link_show_fdinfo(const struct bpf_link *link,
3300 struct seq_file *seq)
3302 struct bpf_raw_tp_link *raw_tp_link =
3303 container_of(link, struct bpf_raw_tp_link, link);
3307 raw_tp_link->btp->tp->name);
3310 static int bpf_copy_to_user(char __user *ubuf, const char *buf, u32 ulen,
3313 if (ulen >= len + 1) {
3314 if (copy_to_user(ubuf, buf, len + 1))
3319 if (copy_to_user(ubuf, buf, ulen - 1))
3321 if (put_user(zero, ubuf + ulen - 1))
3329 static int bpf_raw_tp_link_fill_link_info(const struct bpf_link *link,
3330 struct bpf_link_info *info)
3332 struct bpf_raw_tp_link *raw_tp_link =
3333 container_of(link, struct bpf_raw_tp_link, link);
3334 char __user *ubuf = u64_to_user_ptr(info->raw_tracepoint.tp_name);
3335 const char *tp_name = raw_tp_link->btp->tp->name;
3336 u32 ulen = info->raw_tracepoint.tp_name_len;
3337 size_t tp_len = strlen(tp_name);
3342 info->raw_tracepoint.tp_name_len = tp_len + 1;
3347 return bpf_copy_to_user(ubuf, tp_name, ulen, tp_len);
3350 static const struct bpf_link_ops bpf_raw_tp_link_lops = {
3351 .release = bpf_raw_tp_link_release,
3352 .dealloc = bpf_raw_tp_link_dealloc,
3353 .show_fdinfo = bpf_raw_tp_link_show_fdinfo,
3354 .fill_link_info = bpf_raw_tp_link_fill_link_info,
3357 #ifdef CONFIG_PERF_EVENTS
3358 struct bpf_perf_link {
3359 struct bpf_link link;
3360 struct file *perf_file;
3363 static void bpf_perf_link_release(struct bpf_link *link)
3365 struct bpf_perf_link *perf_link = container_of(link, struct bpf_perf_link, link);
3366 struct perf_event *event = perf_link->perf_file->private_data;
3368 perf_event_free_bpf_prog(event);
3369 fput(perf_link->perf_file);
3372 static void bpf_perf_link_dealloc(struct bpf_link *link)
3374 struct bpf_perf_link *perf_link = container_of(link, struct bpf_perf_link, link);
3379 static int bpf_perf_link_fill_common(const struct perf_event *event,
3380 char __user *uname, u32 ulen,
3381 u64 *probe_offset, u64 *probe_addr,
3382 u32 *fd_type, unsigned long *missed)
3392 err = bpf_get_perf_event_info(event, &prog_id, fd_type, &buf,
3393 probe_offset, probe_addr, missed);
3400 err = bpf_copy_to_user(uname, buf, ulen, len);
3406 if (put_user(zero, uname))
3412 #ifdef CONFIG_KPROBE_EVENTS
3413 static int bpf_perf_link_fill_kprobe(const struct perf_event *event,
3414 struct bpf_link_info *info)
3416 unsigned long missed;
3422 uname = u64_to_user_ptr(info->perf_event.kprobe.func_name);
3423 ulen = info->perf_event.kprobe.name_len;
3424 err = bpf_perf_link_fill_common(event, uname, ulen, &offset, &addr,
3428 if (type == BPF_FD_TYPE_KRETPROBE)
3429 info->perf_event.type = BPF_PERF_EVENT_KRETPROBE;
3431 info->perf_event.type = BPF_PERF_EVENT_KPROBE;
3433 info->perf_event.kprobe.offset = offset;
3434 info->perf_event.kprobe.missed = missed;
3435 if (!kallsyms_show_value(current_cred()))
3437 info->perf_event.kprobe.addr = addr;
3442 #ifdef CONFIG_UPROBE_EVENTS
3443 static int bpf_perf_link_fill_uprobe(const struct perf_event *event,
3444 struct bpf_link_info *info)
3451 uname = u64_to_user_ptr(info->perf_event.uprobe.file_name);
3452 ulen = info->perf_event.uprobe.name_len;
3453 err = bpf_perf_link_fill_common(event, uname, ulen, &offset, &addr,
3458 if (type == BPF_FD_TYPE_URETPROBE)
3459 info->perf_event.type = BPF_PERF_EVENT_URETPROBE;
3461 info->perf_event.type = BPF_PERF_EVENT_UPROBE;
3462 info->perf_event.uprobe.offset = offset;
3467 static int bpf_perf_link_fill_probe(const struct perf_event *event,
3468 struct bpf_link_info *info)
3470 #ifdef CONFIG_KPROBE_EVENTS
3471 if (event->tp_event->flags & TRACE_EVENT_FL_KPROBE)
3472 return bpf_perf_link_fill_kprobe(event, info);
3474 #ifdef CONFIG_UPROBE_EVENTS
3475 if (event->tp_event->flags & TRACE_EVENT_FL_UPROBE)
3476 return bpf_perf_link_fill_uprobe(event, info);
3481 static int bpf_perf_link_fill_tracepoint(const struct perf_event *event,
3482 struct bpf_link_info *info)
3487 uname = u64_to_user_ptr(info->perf_event.tracepoint.tp_name);
3488 ulen = info->perf_event.tracepoint.name_len;
3489 info->perf_event.type = BPF_PERF_EVENT_TRACEPOINT;
3490 return bpf_perf_link_fill_common(event, uname, ulen, NULL, NULL, NULL, NULL);
3493 static int bpf_perf_link_fill_perf_event(const struct perf_event *event,
3494 struct bpf_link_info *info)
3496 info->perf_event.event.type = event->attr.type;
3497 info->perf_event.event.config = event->attr.config;
3498 info->perf_event.type = BPF_PERF_EVENT_EVENT;
3502 static int bpf_perf_link_fill_link_info(const struct bpf_link *link,
3503 struct bpf_link_info *info)
3505 struct bpf_perf_link *perf_link;
3506 const struct perf_event *event;
3508 perf_link = container_of(link, struct bpf_perf_link, link);
3509 event = perf_get_event(perf_link->perf_file);
3511 return PTR_ERR(event);
3513 switch (event->prog->type) {
3514 case BPF_PROG_TYPE_PERF_EVENT:
3515 return bpf_perf_link_fill_perf_event(event, info);
3516 case BPF_PROG_TYPE_TRACEPOINT:
3517 return bpf_perf_link_fill_tracepoint(event, info);
3518 case BPF_PROG_TYPE_KPROBE:
3519 return bpf_perf_link_fill_probe(event, info);
3525 static const struct bpf_link_ops bpf_perf_link_lops = {
3526 .release = bpf_perf_link_release,
3527 .dealloc = bpf_perf_link_dealloc,
3528 .fill_link_info = bpf_perf_link_fill_link_info,
3531 static int bpf_perf_link_attach(const union bpf_attr *attr, struct bpf_prog *prog)
3533 struct bpf_link_primer link_primer;
3534 struct bpf_perf_link *link;
3535 struct perf_event *event;
3536 struct file *perf_file;
3539 if (attr->link_create.flags)
3542 perf_file = perf_event_get(attr->link_create.target_fd);
3543 if (IS_ERR(perf_file))
3544 return PTR_ERR(perf_file);
3546 link = kzalloc(sizeof(*link), GFP_USER);
3551 bpf_link_init(&link->link, BPF_LINK_TYPE_PERF_EVENT, &bpf_perf_link_lops, prog);
3552 link->perf_file = perf_file;
3554 err = bpf_link_prime(&link->link, &link_primer);
3560 event = perf_file->private_data;
3561 err = perf_event_set_bpf_prog(event, prog, attr->link_create.perf_event.bpf_cookie);
3563 bpf_link_cleanup(&link_primer);
3566 /* perf_event_set_bpf_prog() doesn't take its own refcnt on prog */
3569 return bpf_link_settle(&link_primer);
3576 static int bpf_perf_link_attach(const union bpf_attr *attr, struct bpf_prog *prog)
3580 #endif /* CONFIG_PERF_EVENTS */
3582 static int bpf_raw_tp_link_attach(struct bpf_prog *prog,
3583 const char __user *user_tp_name)
3585 struct bpf_link_primer link_primer;
3586 struct bpf_raw_tp_link *link;
3587 struct bpf_raw_event_map *btp;
3588 const char *tp_name;
3592 switch (prog->type) {
3593 case BPF_PROG_TYPE_TRACING:
3594 case BPF_PROG_TYPE_EXT:
3595 case BPF_PROG_TYPE_LSM:
3597 /* The attach point for this category of programs
3598 * should be specified via btf_id during program load.
3601 if (prog->type == BPF_PROG_TYPE_TRACING &&
3602 prog->expected_attach_type == BPF_TRACE_RAW_TP) {
3603 tp_name = prog->aux->attach_func_name;
3606 return bpf_tracing_prog_attach(prog, 0, 0, 0);
3607 case BPF_PROG_TYPE_RAW_TRACEPOINT:
3608 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
3609 if (strncpy_from_user(buf, user_tp_name, sizeof(buf) - 1) < 0)
3611 buf[sizeof(buf) - 1] = 0;
3618 btp = bpf_get_raw_tracepoint(tp_name);
3622 link = kzalloc(sizeof(*link), GFP_USER);
3627 bpf_link_init(&link->link, BPF_LINK_TYPE_RAW_TRACEPOINT,
3628 &bpf_raw_tp_link_lops, prog);
3631 err = bpf_link_prime(&link->link, &link_primer);
3637 err = bpf_probe_register(link->btp, prog);
3639 bpf_link_cleanup(&link_primer);
3643 return bpf_link_settle(&link_primer);
3646 bpf_put_raw_tracepoint(btp);
3650 #define BPF_RAW_TRACEPOINT_OPEN_LAST_FIELD raw_tracepoint.prog_fd
3652 static int bpf_raw_tracepoint_open(const union bpf_attr *attr)
3654 struct bpf_prog *prog;
3657 if (CHECK_ATTR(BPF_RAW_TRACEPOINT_OPEN))
3660 prog = bpf_prog_get(attr->raw_tracepoint.prog_fd);
3662 return PTR_ERR(prog);
3664 fd = bpf_raw_tp_link_attach(prog, u64_to_user_ptr(attr->raw_tracepoint.name));
3670 static enum bpf_prog_type
3671 attach_type_to_prog_type(enum bpf_attach_type attach_type)
3673 switch (attach_type) {
3674 case BPF_CGROUP_INET_INGRESS:
3675 case BPF_CGROUP_INET_EGRESS:
3676 return BPF_PROG_TYPE_CGROUP_SKB;
3677 case BPF_CGROUP_INET_SOCK_CREATE:
3678 case BPF_CGROUP_INET_SOCK_RELEASE:
3679 case BPF_CGROUP_INET4_POST_BIND:
3680 case BPF_CGROUP_INET6_POST_BIND:
3681 return BPF_PROG_TYPE_CGROUP_SOCK;
3682 case BPF_CGROUP_INET4_BIND:
3683 case BPF_CGROUP_INET6_BIND:
3684 case BPF_CGROUP_INET4_CONNECT:
3685 case BPF_CGROUP_INET6_CONNECT:
3686 case BPF_CGROUP_UNIX_CONNECT:
3687 case BPF_CGROUP_INET4_GETPEERNAME:
3688 case BPF_CGROUP_INET6_GETPEERNAME:
3689 case BPF_CGROUP_UNIX_GETPEERNAME:
3690 case BPF_CGROUP_INET4_GETSOCKNAME:
3691 case BPF_CGROUP_INET6_GETSOCKNAME:
3692 case BPF_CGROUP_UNIX_GETSOCKNAME:
3693 case BPF_CGROUP_UDP4_SENDMSG:
3694 case BPF_CGROUP_UDP6_SENDMSG:
3695 case BPF_CGROUP_UNIX_SENDMSG:
3696 case BPF_CGROUP_UDP4_RECVMSG:
3697 case BPF_CGROUP_UDP6_RECVMSG:
3698 case BPF_CGROUP_UNIX_RECVMSG:
3699 return BPF_PROG_TYPE_CGROUP_SOCK_ADDR;
3700 case BPF_CGROUP_SOCK_OPS:
3701 return BPF_PROG_TYPE_SOCK_OPS;
3702 case BPF_CGROUP_DEVICE:
3703 return BPF_PROG_TYPE_CGROUP_DEVICE;
3704 case BPF_SK_MSG_VERDICT:
3705 return BPF_PROG_TYPE_SK_MSG;
3706 case BPF_SK_SKB_STREAM_PARSER:
3707 case BPF_SK_SKB_STREAM_VERDICT:
3708 case BPF_SK_SKB_VERDICT:
3709 return BPF_PROG_TYPE_SK_SKB;
3710 case BPF_LIRC_MODE2:
3711 return BPF_PROG_TYPE_LIRC_MODE2;
3712 case BPF_FLOW_DISSECTOR:
3713 return BPF_PROG_TYPE_FLOW_DISSECTOR;
3714 case BPF_CGROUP_SYSCTL:
3715 return BPF_PROG_TYPE_CGROUP_SYSCTL;
3716 case BPF_CGROUP_GETSOCKOPT:
3717 case BPF_CGROUP_SETSOCKOPT:
3718 return BPF_PROG_TYPE_CGROUP_SOCKOPT;
3719 case BPF_TRACE_ITER:
3720 case BPF_TRACE_RAW_TP:
3721 case BPF_TRACE_FENTRY:
3722 case BPF_TRACE_FEXIT:
3723 case BPF_MODIFY_RETURN:
3724 return BPF_PROG_TYPE_TRACING;
3726 return BPF_PROG_TYPE_LSM;
3728 return BPF_PROG_TYPE_SK_LOOKUP;
3730 return BPF_PROG_TYPE_XDP;
3731 case BPF_LSM_CGROUP:
3732 return BPF_PROG_TYPE_LSM;
3733 case BPF_TCX_INGRESS:
3734 case BPF_TCX_EGRESS:
3735 return BPF_PROG_TYPE_SCHED_CLS;
3737 return BPF_PROG_TYPE_UNSPEC;
3741 static int bpf_prog_attach_check_attach_type(const struct bpf_prog *prog,
3742 enum bpf_attach_type attach_type)
3744 enum bpf_prog_type ptype;
3746 switch (prog->type) {
3747 case BPF_PROG_TYPE_CGROUP_SOCK:
3748 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
3749 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3750 case BPF_PROG_TYPE_SK_LOOKUP:
3751 return attach_type == prog->expected_attach_type ? 0 : -EINVAL;
3752 case BPF_PROG_TYPE_CGROUP_SKB:
3753 if (!capable(CAP_NET_ADMIN))
3754 /* cg-skb progs can be loaded by unpriv user.
3755 * check permissions at attach time.
3758 return prog->enforce_expected_attach_type &&
3759 prog->expected_attach_type != attach_type ?
3761 case BPF_PROG_TYPE_EXT:
3763 case BPF_PROG_TYPE_NETFILTER:
3764 if (attach_type != BPF_NETFILTER)
3767 case BPF_PROG_TYPE_PERF_EVENT:
3768 case BPF_PROG_TYPE_TRACEPOINT:
3769 if (attach_type != BPF_PERF_EVENT)
3772 case BPF_PROG_TYPE_KPROBE:
3773 if (prog->expected_attach_type == BPF_TRACE_KPROBE_MULTI &&
3774 attach_type != BPF_TRACE_KPROBE_MULTI)
3776 if (prog->expected_attach_type == BPF_TRACE_UPROBE_MULTI &&
3777 attach_type != BPF_TRACE_UPROBE_MULTI)
3779 if (attach_type != BPF_PERF_EVENT &&
3780 attach_type != BPF_TRACE_KPROBE_MULTI &&
3781 attach_type != BPF_TRACE_UPROBE_MULTI)
3784 case BPF_PROG_TYPE_SCHED_CLS:
3785 if (attach_type != BPF_TCX_INGRESS &&
3786 attach_type != BPF_TCX_EGRESS)
3790 ptype = attach_type_to_prog_type(attach_type);
3791 if (ptype == BPF_PROG_TYPE_UNSPEC || ptype != prog->type)
3797 #define BPF_PROG_ATTACH_LAST_FIELD expected_revision
3799 #define BPF_F_ATTACH_MASK_BASE \
3800 (BPF_F_ALLOW_OVERRIDE | \
3801 BPF_F_ALLOW_MULTI | \
3804 #define BPF_F_ATTACH_MASK_MPROG \
3811 static int bpf_prog_attach(const union bpf_attr *attr)
3813 enum bpf_prog_type ptype;
3814 struct bpf_prog *prog;
3817 if (CHECK_ATTR(BPF_PROG_ATTACH))
3820 ptype = attach_type_to_prog_type(attr->attach_type);
3821 if (ptype == BPF_PROG_TYPE_UNSPEC)
3823 if (bpf_mprog_supported(ptype)) {
3824 if (attr->attach_flags & ~BPF_F_ATTACH_MASK_MPROG)
3827 if (attr->attach_flags & ~BPF_F_ATTACH_MASK_BASE)
3829 if (attr->relative_fd ||
3830 attr->expected_revision)
3834 prog = bpf_prog_get_type(attr->attach_bpf_fd, ptype);
3836 return PTR_ERR(prog);
3838 if (bpf_prog_attach_check_attach_type(prog, attr->attach_type)) {
3844 case BPF_PROG_TYPE_SK_SKB:
3845 case BPF_PROG_TYPE_SK_MSG:
3846 ret = sock_map_get_from_fd(attr, prog);
3848 case BPF_PROG_TYPE_LIRC_MODE2:
3849 ret = lirc_prog_attach(attr, prog);
3851 case BPF_PROG_TYPE_FLOW_DISSECTOR:
3852 ret = netns_bpf_prog_attach(attr, prog);
3854 case BPF_PROG_TYPE_CGROUP_DEVICE:
3855 case BPF_PROG_TYPE_CGROUP_SKB:
3856 case BPF_PROG_TYPE_CGROUP_SOCK:
3857 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
3858 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3859 case BPF_PROG_TYPE_CGROUP_SYSCTL:
3860 case BPF_PROG_TYPE_SOCK_OPS:
3861 case BPF_PROG_TYPE_LSM:
3862 if (ptype == BPF_PROG_TYPE_LSM &&
3863 prog->expected_attach_type != BPF_LSM_CGROUP)
3866 ret = cgroup_bpf_prog_attach(attr, ptype, prog);
3868 case BPF_PROG_TYPE_SCHED_CLS:
3869 ret = tcx_prog_attach(attr, prog);
3880 #define BPF_PROG_DETACH_LAST_FIELD expected_revision
3882 static int bpf_prog_detach(const union bpf_attr *attr)
3884 struct bpf_prog *prog = NULL;
3885 enum bpf_prog_type ptype;
3888 if (CHECK_ATTR(BPF_PROG_DETACH))
3891 ptype = attach_type_to_prog_type(attr->attach_type);
3892 if (bpf_mprog_supported(ptype)) {
3893 if (ptype == BPF_PROG_TYPE_UNSPEC)
3895 if (attr->attach_flags & ~BPF_F_ATTACH_MASK_MPROG)
3897 if (attr->attach_bpf_fd) {
3898 prog = bpf_prog_get_type(attr->attach_bpf_fd, ptype);
3900 return PTR_ERR(prog);
3902 } else if (attr->attach_flags ||
3903 attr->relative_fd ||
3904 attr->expected_revision) {
3909 case BPF_PROG_TYPE_SK_MSG:
3910 case BPF_PROG_TYPE_SK_SKB:
3911 ret = sock_map_prog_detach(attr, ptype);
3913 case BPF_PROG_TYPE_LIRC_MODE2:
3914 ret = lirc_prog_detach(attr);
3916 case BPF_PROG_TYPE_FLOW_DISSECTOR:
3917 ret = netns_bpf_prog_detach(attr, ptype);
3919 case BPF_PROG_TYPE_CGROUP_DEVICE:
3920 case BPF_PROG_TYPE_CGROUP_SKB:
3921 case BPF_PROG_TYPE_CGROUP_SOCK:
3922 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
3923 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3924 case BPF_PROG_TYPE_CGROUP_SYSCTL:
3925 case BPF_PROG_TYPE_SOCK_OPS:
3926 case BPF_PROG_TYPE_LSM:
3927 ret = cgroup_bpf_prog_detach(attr, ptype);
3929 case BPF_PROG_TYPE_SCHED_CLS:
3930 ret = tcx_prog_detach(attr, prog);
3941 #define BPF_PROG_QUERY_LAST_FIELD query.revision
3943 static int bpf_prog_query(const union bpf_attr *attr,
3944 union bpf_attr __user *uattr)
3946 if (!capable(CAP_NET_ADMIN))
3948 if (CHECK_ATTR(BPF_PROG_QUERY))
3950 if (attr->query.query_flags & ~BPF_F_QUERY_EFFECTIVE)
3953 switch (attr->query.attach_type) {
3954 case BPF_CGROUP_INET_INGRESS:
3955 case BPF_CGROUP_INET_EGRESS:
3956 case BPF_CGROUP_INET_SOCK_CREATE:
3957 case BPF_CGROUP_INET_SOCK_RELEASE:
3958 case BPF_CGROUP_INET4_BIND:
3959 case BPF_CGROUP_INET6_BIND:
3960 case BPF_CGROUP_INET4_POST_BIND:
3961 case BPF_CGROUP_INET6_POST_BIND:
3962 case BPF_CGROUP_INET4_CONNECT:
3963 case BPF_CGROUP_INET6_CONNECT:
3964 case BPF_CGROUP_UNIX_CONNECT:
3965 case BPF_CGROUP_INET4_GETPEERNAME:
3966 case BPF_CGROUP_INET6_GETPEERNAME:
3967 case BPF_CGROUP_UNIX_GETPEERNAME:
3968 case BPF_CGROUP_INET4_GETSOCKNAME:
3969 case BPF_CGROUP_INET6_GETSOCKNAME:
3970 case BPF_CGROUP_UNIX_GETSOCKNAME:
3971 case BPF_CGROUP_UDP4_SENDMSG:
3972 case BPF_CGROUP_UDP6_SENDMSG:
3973 case BPF_CGROUP_UNIX_SENDMSG:
3974 case BPF_CGROUP_UDP4_RECVMSG:
3975 case BPF_CGROUP_UDP6_RECVMSG:
3976 case BPF_CGROUP_UNIX_RECVMSG:
3977 case BPF_CGROUP_SOCK_OPS:
3978 case BPF_CGROUP_DEVICE:
3979 case BPF_CGROUP_SYSCTL:
3980 case BPF_CGROUP_GETSOCKOPT:
3981 case BPF_CGROUP_SETSOCKOPT:
3982 case BPF_LSM_CGROUP:
3983 return cgroup_bpf_prog_query(attr, uattr);
3984 case BPF_LIRC_MODE2:
3985 return lirc_prog_query(attr, uattr);
3986 case BPF_FLOW_DISSECTOR:
3988 return netns_bpf_prog_query(attr, uattr);
3989 case BPF_SK_SKB_STREAM_PARSER:
3990 case BPF_SK_SKB_STREAM_VERDICT:
3991 case BPF_SK_MSG_VERDICT:
3992 case BPF_SK_SKB_VERDICT:
3993 return sock_map_bpf_prog_query(attr, uattr);
3994 case BPF_TCX_INGRESS:
3995 case BPF_TCX_EGRESS:
3996 return tcx_prog_query(attr, uattr);
4002 #define BPF_PROG_TEST_RUN_LAST_FIELD test.batch_size
4004 static int bpf_prog_test_run(const union bpf_attr *attr,
4005 union bpf_attr __user *uattr)
4007 struct bpf_prog *prog;
4008 int ret = -ENOTSUPP;
4010 if (CHECK_ATTR(BPF_PROG_TEST_RUN))
4013 if ((attr->test.ctx_size_in && !attr->test.ctx_in) ||
4014 (!attr->test.ctx_size_in && attr->test.ctx_in))
4017 if ((attr->test.ctx_size_out && !attr->test.ctx_out) ||
4018 (!attr->test.ctx_size_out && attr->test.ctx_out))
4021 prog = bpf_prog_get(attr->test.prog_fd);
4023 return PTR_ERR(prog);
4025 if (prog->aux->ops->test_run)
4026 ret = prog->aux->ops->test_run(prog, attr, uattr);
4032 #define BPF_OBJ_GET_NEXT_ID_LAST_FIELD next_id
4034 static int bpf_obj_get_next_id(const union bpf_attr *attr,
4035 union bpf_attr __user *uattr,
4039 u32 next_id = attr->start_id;
4042 if (CHECK_ATTR(BPF_OBJ_GET_NEXT_ID) || next_id >= INT_MAX)
4045 if (!capable(CAP_SYS_ADMIN))
4050 if (!idr_get_next(idr, &next_id))
4052 spin_unlock_bh(lock);
4055 err = put_user(next_id, &uattr->next_id);
4060 struct bpf_map *bpf_map_get_curr_or_next(u32 *id)
4062 struct bpf_map *map;
4064 spin_lock_bh(&map_idr_lock);
4066 map = idr_get_next(&map_idr, id);
4068 map = __bpf_map_inc_not_zero(map, false);
4074 spin_unlock_bh(&map_idr_lock);
4079 struct bpf_prog *bpf_prog_get_curr_or_next(u32 *id)
4081 struct bpf_prog *prog;
4083 spin_lock_bh(&prog_idr_lock);
4085 prog = idr_get_next(&prog_idr, id);
4087 prog = bpf_prog_inc_not_zero(prog);
4093 spin_unlock_bh(&prog_idr_lock);
4098 #define BPF_PROG_GET_FD_BY_ID_LAST_FIELD prog_id
4100 struct bpf_prog *bpf_prog_by_id(u32 id)
4102 struct bpf_prog *prog;
4105 return ERR_PTR(-ENOENT);
4107 spin_lock_bh(&prog_idr_lock);
4108 prog = idr_find(&prog_idr, id);
4110 prog = bpf_prog_inc_not_zero(prog);
4112 prog = ERR_PTR(-ENOENT);
4113 spin_unlock_bh(&prog_idr_lock);
4117 static int bpf_prog_get_fd_by_id(const union bpf_attr *attr)
4119 struct bpf_prog *prog;
4120 u32 id = attr->prog_id;
4123 if (CHECK_ATTR(BPF_PROG_GET_FD_BY_ID))
4126 if (!capable(CAP_SYS_ADMIN))
4129 prog = bpf_prog_by_id(id);
4131 return PTR_ERR(prog);
4133 fd = bpf_prog_new_fd(prog);
4140 #define BPF_MAP_GET_FD_BY_ID_LAST_FIELD open_flags
4142 static int bpf_map_get_fd_by_id(const union bpf_attr *attr)
4144 struct bpf_map *map;
4145 u32 id = attr->map_id;
4149 if (CHECK_ATTR(BPF_MAP_GET_FD_BY_ID) ||
4150 attr->open_flags & ~BPF_OBJ_FLAG_MASK)
4153 if (!capable(CAP_SYS_ADMIN))
4156 f_flags = bpf_get_file_flag(attr->open_flags);
4160 spin_lock_bh(&map_idr_lock);
4161 map = idr_find(&map_idr, id);
4163 map = __bpf_map_inc_not_zero(map, true);
4165 map = ERR_PTR(-ENOENT);
4166 spin_unlock_bh(&map_idr_lock);
4169 return PTR_ERR(map);
4171 fd = bpf_map_new_fd(map, f_flags);
4173 bpf_map_put_with_uref(map);
4178 static const struct bpf_map *bpf_map_from_imm(const struct bpf_prog *prog,
4179 unsigned long addr, u32 *off,
4182 const struct bpf_map *map;
4185 mutex_lock(&prog->aux->used_maps_mutex);
4186 for (i = 0, *off = 0; i < prog->aux->used_map_cnt; i++) {
4187 map = prog->aux->used_maps[i];
4188 if (map == (void *)addr) {
4189 *type = BPF_PSEUDO_MAP_FD;
4192 if (!map->ops->map_direct_value_meta)
4194 if (!map->ops->map_direct_value_meta(map, addr, off)) {
4195 *type = BPF_PSEUDO_MAP_VALUE;
4202 mutex_unlock(&prog->aux->used_maps_mutex);
4206 static struct bpf_insn *bpf_insn_prepare_dump(const struct bpf_prog *prog,
4207 const struct cred *f_cred)
4209 const struct bpf_map *map;
4210 struct bpf_insn *insns;
4216 insns = kmemdup(prog->insnsi, bpf_prog_insn_size(prog),
4221 for (i = 0; i < prog->len; i++) {
4222 code = insns[i].code;
4224 if (code == (BPF_JMP | BPF_TAIL_CALL)) {
4225 insns[i].code = BPF_JMP | BPF_CALL;
4226 insns[i].imm = BPF_FUNC_tail_call;
4229 if (code == (BPF_JMP | BPF_CALL) ||
4230 code == (BPF_JMP | BPF_CALL_ARGS)) {
4231 if (code == (BPF_JMP | BPF_CALL_ARGS))
4232 insns[i].code = BPF_JMP | BPF_CALL;
4233 if (!bpf_dump_raw_ok(f_cred))
4237 if (BPF_CLASS(code) == BPF_LDX && BPF_MODE(code) == BPF_PROBE_MEM) {
4238 insns[i].code = BPF_LDX | BPF_SIZE(code) | BPF_MEM;
4242 if (code != (BPF_LD | BPF_IMM | BPF_DW))
4245 imm = ((u64)insns[i + 1].imm << 32) | (u32)insns[i].imm;
4246 map = bpf_map_from_imm(prog, imm, &off, &type);
4248 insns[i].src_reg = type;
4249 insns[i].imm = map->id;
4250 insns[i + 1].imm = off;
4258 static int set_info_rec_size(struct bpf_prog_info *info)
4261 * Ensure info.*_rec_size is the same as kernel expected size
4265 * Only allow zero *_rec_size if both _rec_size and _cnt are
4266 * zero. In this case, the kernel will set the expected
4267 * _rec_size back to the info.
4270 if ((info->nr_func_info || info->func_info_rec_size) &&
4271 info->func_info_rec_size != sizeof(struct bpf_func_info))
4274 if ((info->nr_line_info || info->line_info_rec_size) &&
4275 info->line_info_rec_size != sizeof(struct bpf_line_info))
4278 if ((info->nr_jited_line_info || info->jited_line_info_rec_size) &&
4279 info->jited_line_info_rec_size != sizeof(__u64))
4282 info->func_info_rec_size = sizeof(struct bpf_func_info);
4283 info->line_info_rec_size = sizeof(struct bpf_line_info);
4284 info->jited_line_info_rec_size = sizeof(__u64);
4289 static int bpf_prog_get_info_by_fd(struct file *file,
4290 struct bpf_prog *prog,
4291 const union bpf_attr *attr,
4292 union bpf_attr __user *uattr)
4294 struct bpf_prog_info __user *uinfo = u64_to_user_ptr(attr->info.info);
4295 struct btf *attach_btf = bpf_prog_get_target_btf(prog);
4296 struct bpf_prog_info info;
4297 u32 info_len = attr->info.info_len;
4298 struct bpf_prog_kstats stats;
4299 char __user *uinsns;
4303 err = bpf_check_uarg_tail_zero(USER_BPFPTR(uinfo), sizeof(info), info_len);
4306 info_len = min_t(u32, sizeof(info), info_len);
4308 memset(&info, 0, sizeof(info));
4309 if (copy_from_user(&info, uinfo, info_len))
4312 info.type = prog->type;
4313 info.id = prog->aux->id;
4314 info.load_time = prog->aux->load_time;
4315 info.created_by_uid = from_kuid_munged(current_user_ns(),
4316 prog->aux->user->uid);
4317 info.gpl_compatible = prog->gpl_compatible;
4319 memcpy(info.tag, prog->tag, sizeof(prog->tag));
4320 memcpy(info.name, prog->aux->name, sizeof(prog->aux->name));
4322 mutex_lock(&prog->aux->used_maps_mutex);
4323 ulen = info.nr_map_ids;
4324 info.nr_map_ids = prog->aux->used_map_cnt;
4325 ulen = min_t(u32, info.nr_map_ids, ulen);
4327 u32 __user *user_map_ids = u64_to_user_ptr(info.map_ids);
4330 for (i = 0; i < ulen; i++)
4331 if (put_user(prog->aux->used_maps[i]->id,
4332 &user_map_ids[i])) {
4333 mutex_unlock(&prog->aux->used_maps_mutex);
4337 mutex_unlock(&prog->aux->used_maps_mutex);
4339 err = set_info_rec_size(&info);
4343 bpf_prog_get_stats(prog, &stats);
4344 info.run_time_ns = stats.nsecs;
4345 info.run_cnt = stats.cnt;
4346 info.recursion_misses = stats.misses;
4348 info.verified_insns = prog->aux->verified_insns;
4350 if (!bpf_capable()) {
4351 info.jited_prog_len = 0;
4352 info.xlated_prog_len = 0;
4353 info.nr_jited_ksyms = 0;
4354 info.nr_jited_func_lens = 0;
4355 info.nr_func_info = 0;
4356 info.nr_line_info = 0;
4357 info.nr_jited_line_info = 0;
4361 ulen = info.xlated_prog_len;
4362 info.xlated_prog_len = bpf_prog_insn_size(prog);
4363 if (info.xlated_prog_len && ulen) {
4364 struct bpf_insn *insns_sanitized;
4367 if (prog->blinded && !bpf_dump_raw_ok(file->f_cred)) {
4368 info.xlated_prog_insns = 0;
4371 insns_sanitized = bpf_insn_prepare_dump(prog, file->f_cred);
4372 if (!insns_sanitized)
4374 uinsns = u64_to_user_ptr(info.xlated_prog_insns);
4375 ulen = min_t(u32, info.xlated_prog_len, ulen);
4376 fault = copy_to_user(uinsns, insns_sanitized, ulen);
4377 kfree(insns_sanitized);
4382 if (bpf_prog_is_offloaded(prog->aux)) {
4383 err = bpf_prog_offload_info_fill(&info, prog);
4389 /* NOTE: the following code is supposed to be skipped for offload.
4390 * bpf_prog_offload_info_fill() is the place to fill similar fields
4393 ulen = info.jited_prog_len;
4394 if (prog->aux->func_cnt) {
4397 info.jited_prog_len = 0;
4398 for (i = 0; i < prog->aux->func_cnt; i++)
4399 info.jited_prog_len += prog->aux->func[i]->jited_len;
4401 info.jited_prog_len = prog->jited_len;
4404 if (info.jited_prog_len && ulen) {
4405 if (bpf_dump_raw_ok(file->f_cred)) {
4406 uinsns = u64_to_user_ptr(info.jited_prog_insns);
4407 ulen = min_t(u32, info.jited_prog_len, ulen);
4409 /* for multi-function programs, copy the JITed
4410 * instructions for all the functions
4412 if (prog->aux->func_cnt) {
4417 for (i = 0; i < prog->aux->func_cnt; i++) {
4418 len = prog->aux->func[i]->jited_len;
4419 len = min_t(u32, len, free);
4420 img = (u8 *) prog->aux->func[i]->bpf_func;
4421 if (copy_to_user(uinsns, img, len))
4429 if (copy_to_user(uinsns, prog->bpf_func, ulen))
4433 info.jited_prog_insns = 0;
4437 ulen = info.nr_jited_ksyms;
4438 info.nr_jited_ksyms = prog->aux->func_cnt ? : 1;
4440 if (bpf_dump_raw_ok(file->f_cred)) {
4441 unsigned long ksym_addr;
4442 u64 __user *user_ksyms;
4445 /* copy the address of the kernel symbol
4446 * corresponding to each function
4448 ulen = min_t(u32, info.nr_jited_ksyms, ulen);
4449 user_ksyms = u64_to_user_ptr(info.jited_ksyms);
4450 if (prog->aux->func_cnt) {
4451 for (i = 0; i < ulen; i++) {
4452 ksym_addr = (unsigned long)
4453 prog->aux->func[i]->bpf_func;
4454 if (put_user((u64) ksym_addr,
4459 ksym_addr = (unsigned long) prog->bpf_func;
4460 if (put_user((u64) ksym_addr, &user_ksyms[0]))
4464 info.jited_ksyms = 0;
4468 ulen = info.nr_jited_func_lens;
4469 info.nr_jited_func_lens = prog->aux->func_cnt ? : 1;
4471 if (bpf_dump_raw_ok(file->f_cred)) {
4472 u32 __user *user_lens;
4475 /* copy the JITed image lengths for each function */
4476 ulen = min_t(u32, info.nr_jited_func_lens, ulen);
4477 user_lens = u64_to_user_ptr(info.jited_func_lens);
4478 if (prog->aux->func_cnt) {
4479 for (i = 0; i < ulen; i++) {
4481 prog->aux->func[i]->jited_len;
4482 if (put_user(func_len, &user_lens[i]))
4486 func_len = prog->jited_len;
4487 if (put_user(func_len, &user_lens[0]))
4491 info.jited_func_lens = 0;
4496 info.btf_id = btf_obj_id(prog->aux->btf);
4497 info.attach_btf_id = prog->aux->attach_btf_id;
4499 info.attach_btf_obj_id = btf_obj_id(attach_btf);
4501 ulen = info.nr_func_info;
4502 info.nr_func_info = prog->aux->func_info_cnt;
4503 if (info.nr_func_info && ulen) {
4504 char __user *user_finfo;
4506 user_finfo = u64_to_user_ptr(info.func_info);
4507 ulen = min_t(u32, info.nr_func_info, ulen);
4508 if (copy_to_user(user_finfo, prog->aux->func_info,
4509 info.func_info_rec_size * ulen))
4513 ulen = info.nr_line_info;
4514 info.nr_line_info = prog->aux->nr_linfo;
4515 if (info.nr_line_info && ulen) {
4516 __u8 __user *user_linfo;
4518 user_linfo = u64_to_user_ptr(info.line_info);
4519 ulen = min_t(u32, info.nr_line_info, ulen);
4520 if (copy_to_user(user_linfo, prog->aux->linfo,
4521 info.line_info_rec_size * ulen))
4525 ulen = info.nr_jited_line_info;
4526 if (prog->aux->jited_linfo)
4527 info.nr_jited_line_info = prog->aux->nr_linfo;
4529 info.nr_jited_line_info = 0;
4530 if (info.nr_jited_line_info && ulen) {
4531 if (bpf_dump_raw_ok(file->f_cred)) {
4532 unsigned long line_addr;
4533 __u64 __user *user_linfo;
4536 user_linfo = u64_to_user_ptr(info.jited_line_info);
4537 ulen = min_t(u32, info.nr_jited_line_info, ulen);
4538 for (i = 0; i < ulen; i++) {
4539 line_addr = (unsigned long)prog->aux->jited_linfo[i];
4540 if (put_user((__u64)line_addr, &user_linfo[i]))
4544 info.jited_line_info = 0;
4548 ulen = info.nr_prog_tags;
4549 info.nr_prog_tags = prog->aux->func_cnt ? : 1;
4551 __u8 __user (*user_prog_tags)[BPF_TAG_SIZE];
4554 user_prog_tags = u64_to_user_ptr(info.prog_tags);
4555 ulen = min_t(u32, info.nr_prog_tags, ulen);
4556 if (prog->aux->func_cnt) {
4557 for (i = 0; i < ulen; i++) {
4558 if (copy_to_user(user_prog_tags[i],
4559 prog->aux->func[i]->tag,
4564 if (copy_to_user(user_prog_tags[0],
4565 prog->tag, BPF_TAG_SIZE))
4571 if (copy_to_user(uinfo, &info, info_len) ||
4572 put_user(info_len, &uattr->info.info_len))
4578 static int bpf_map_get_info_by_fd(struct file *file,
4579 struct bpf_map *map,
4580 const union bpf_attr *attr,
4581 union bpf_attr __user *uattr)
4583 struct bpf_map_info __user *uinfo = u64_to_user_ptr(attr->info.info);
4584 struct bpf_map_info info;
4585 u32 info_len = attr->info.info_len;
4588 err = bpf_check_uarg_tail_zero(USER_BPFPTR(uinfo), sizeof(info), info_len);
4591 info_len = min_t(u32, sizeof(info), info_len);
4593 memset(&info, 0, sizeof(info));
4594 info.type = map->map_type;
4596 info.key_size = map->key_size;
4597 info.value_size = map->value_size;
4598 info.max_entries = map->max_entries;
4599 info.map_flags = map->map_flags;
4600 info.map_extra = map->map_extra;
4601 memcpy(info.name, map->name, sizeof(map->name));
4604 info.btf_id = btf_obj_id(map->btf);
4605 info.btf_key_type_id = map->btf_key_type_id;
4606 info.btf_value_type_id = map->btf_value_type_id;
4608 info.btf_vmlinux_value_type_id = map->btf_vmlinux_value_type_id;
4610 if (bpf_map_is_offloaded(map)) {
4611 err = bpf_map_offload_info_fill(&info, map);
4616 if (copy_to_user(uinfo, &info, info_len) ||
4617 put_user(info_len, &uattr->info.info_len))
4623 static int bpf_btf_get_info_by_fd(struct file *file,
4625 const union bpf_attr *attr,
4626 union bpf_attr __user *uattr)
4628 struct bpf_btf_info __user *uinfo = u64_to_user_ptr(attr->info.info);
4629 u32 info_len = attr->info.info_len;
4632 err = bpf_check_uarg_tail_zero(USER_BPFPTR(uinfo), sizeof(*uinfo), info_len);
4636 return btf_get_info_by_fd(btf, attr, uattr);
4639 static int bpf_link_get_info_by_fd(struct file *file,
4640 struct bpf_link *link,
4641 const union bpf_attr *attr,
4642 union bpf_attr __user *uattr)
4644 struct bpf_link_info __user *uinfo = u64_to_user_ptr(attr->info.info);
4645 struct bpf_link_info info;
4646 u32 info_len = attr->info.info_len;
4649 err = bpf_check_uarg_tail_zero(USER_BPFPTR(uinfo), sizeof(info), info_len);
4652 info_len = min_t(u32, sizeof(info), info_len);
4654 memset(&info, 0, sizeof(info));
4655 if (copy_from_user(&info, uinfo, info_len))
4658 info.type = link->type;
4661 info.prog_id = link->prog->aux->id;
4663 if (link->ops->fill_link_info) {
4664 err = link->ops->fill_link_info(link, &info);
4669 if (copy_to_user(uinfo, &info, info_len) ||
4670 put_user(info_len, &uattr->info.info_len))
4677 #define BPF_OBJ_GET_INFO_BY_FD_LAST_FIELD info.info
4679 static int bpf_obj_get_info_by_fd(const union bpf_attr *attr,
4680 union bpf_attr __user *uattr)
4682 int ufd = attr->info.bpf_fd;
4686 if (CHECK_ATTR(BPF_OBJ_GET_INFO_BY_FD))
4693 if (f.file->f_op == &bpf_prog_fops)
4694 err = bpf_prog_get_info_by_fd(f.file, f.file->private_data, attr,
4696 else if (f.file->f_op == &bpf_map_fops)
4697 err = bpf_map_get_info_by_fd(f.file, f.file->private_data, attr,
4699 else if (f.file->f_op == &btf_fops)
4700 err = bpf_btf_get_info_by_fd(f.file, f.file->private_data, attr, uattr);
4701 else if (f.file->f_op == &bpf_link_fops)
4702 err = bpf_link_get_info_by_fd(f.file, f.file->private_data,
4711 #define BPF_BTF_LOAD_LAST_FIELD btf_log_true_size
4713 static int bpf_btf_load(const union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size)
4715 if (CHECK_ATTR(BPF_BTF_LOAD))
4721 return btf_new_fd(attr, uattr, uattr_size);
4724 #define BPF_BTF_GET_FD_BY_ID_LAST_FIELD btf_id
4726 static int bpf_btf_get_fd_by_id(const union bpf_attr *attr)
4728 if (CHECK_ATTR(BPF_BTF_GET_FD_BY_ID))
4731 if (!capable(CAP_SYS_ADMIN))
4734 return btf_get_fd_by_id(attr->btf_id);
4737 static int bpf_task_fd_query_copy(const union bpf_attr *attr,
4738 union bpf_attr __user *uattr,
4739 u32 prog_id, u32 fd_type,
4740 const char *buf, u64 probe_offset,
4743 char __user *ubuf = u64_to_user_ptr(attr->task_fd_query.buf);
4744 u32 len = buf ? strlen(buf) : 0, input_len;
4747 if (put_user(len, &uattr->task_fd_query.buf_len))
4749 input_len = attr->task_fd_query.buf_len;
4750 if (input_len && ubuf) {
4752 /* nothing to copy, just make ubuf NULL terminated */
4755 if (put_user(zero, ubuf))
4757 } else if (input_len >= len + 1) {
4758 /* ubuf can hold the string with NULL terminator */
4759 if (copy_to_user(ubuf, buf, len + 1))
4762 /* ubuf cannot hold the string with NULL terminator,
4763 * do a partial copy with NULL terminator.
4768 if (copy_to_user(ubuf, buf, input_len - 1))
4770 if (put_user(zero, ubuf + input_len - 1))
4775 if (put_user(prog_id, &uattr->task_fd_query.prog_id) ||
4776 put_user(fd_type, &uattr->task_fd_query.fd_type) ||
4777 put_user(probe_offset, &uattr->task_fd_query.probe_offset) ||
4778 put_user(probe_addr, &uattr->task_fd_query.probe_addr))
4784 #define BPF_TASK_FD_QUERY_LAST_FIELD task_fd_query.probe_addr
4786 static int bpf_task_fd_query(const union bpf_attr *attr,
4787 union bpf_attr __user *uattr)
4789 pid_t pid = attr->task_fd_query.pid;
4790 u32 fd = attr->task_fd_query.fd;
4791 const struct perf_event *event;
4792 struct task_struct *task;
4796 if (CHECK_ATTR(BPF_TASK_FD_QUERY))
4799 if (!capable(CAP_SYS_ADMIN))
4802 if (attr->task_fd_query.flags != 0)
4806 task = get_pid_task(find_vpid(pid), PIDTYPE_PID);
4812 file = fget_task(task, fd);
4813 put_task_struct(task);
4817 if (file->f_op == &bpf_link_fops) {
4818 struct bpf_link *link = file->private_data;
4820 if (link->ops == &bpf_raw_tp_link_lops) {
4821 struct bpf_raw_tp_link *raw_tp =
4822 container_of(link, struct bpf_raw_tp_link, link);
4823 struct bpf_raw_event_map *btp = raw_tp->btp;
4825 err = bpf_task_fd_query_copy(attr, uattr,
4826 raw_tp->link.prog->aux->id,
4827 BPF_FD_TYPE_RAW_TRACEPOINT,
4828 btp->tp->name, 0, 0);
4834 event = perf_get_event(file);
4835 if (!IS_ERR(event)) {
4836 u64 probe_offset, probe_addr;
4837 u32 prog_id, fd_type;
4840 err = bpf_get_perf_event_info(event, &prog_id, &fd_type,
4841 &buf, &probe_offset,
4844 err = bpf_task_fd_query_copy(attr, uattr, prog_id,
4858 #define BPF_MAP_BATCH_LAST_FIELD batch.flags
4860 #define BPF_DO_BATCH(fn, ...) \
4866 err = fn(__VA_ARGS__); \
4869 static int bpf_map_do_batch(const union bpf_attr *attr,
4870 union bpf_attr __user *uattr,
4873 bool has_read = cmd == BPF_MAP_LOOKUP_BATCH ||
4874 cmd == BPF_MAP_LOOKUP_AND_DELETE_BATCH;
4875 bool has_write = cmd != BPF_MAP_LOOKUP_BATCH;
4876 struct bpf_map *map;
4880 if (CHECK_ATTR(BPF_MAP_BATCH))
4883 ufd = attr->batch.map_fd;
4885 map = __bpf_map_get(f);
4887 return PTR_ERR(map);
4889 bpf_map_write_active_inc(map);
4890 if (has_read && !(map_get_sys_perms(map, f) & FMODE_CAN_READ)) {
4894 if (has_write && !(map_get_sys_perms(map, f) & FMODE_CAN_WRITE)) {
4899 if (cmd == BPF_MAP_LOOKUP_BATCH)
4900 BPF_DO_BATCH(map->ops->map_lookup_batch, map, attr, uattr);
4901 else if (cmd == BPF_MAP_LOOKUP_AND_DELETE_BATCH)
4902 BPF_DO_BATCH(map->ops->map_lookup_and_delete_batch, map, attr, uattr);
4903 else if (cmd == BPF_MAP_UPDATE_BATCH)
4904 BPF_DO_BATCH(map->ops->map_update_batch, map, f.file, attr, uattr);
4906 BPF_DO_BATCH(map->ops->map_delete_batch, map, attr, uattr);
4909 bpf_map_write_active_dec(map);
4914 #define BPF_LINK_CREATE_LAST_FIELD link_create.uprobe_multi.pid
4915 static int link_create(union bpf_attr *attr, bpfptr_t uattr)
4917 struct bpf_prog *prog;
4920 if (CHECK_ATTR(BPF_LINK_CREATE))
4923 if (attr->link_create.attach_type == BPF_STRUCT_OPS)
4924 return bpf_struct_ops_link_create(attr);
4926 prog = bpf_prog_get(attr->link_create.prog_fd);
4928 return PTR_ERR(prog);
4930 ret = bpf_prog_attach_check_attach_type(prog,
4931 attr->link_create.attach_type);
4935 switch (prog->type) {
4936 case BPF_PROG_TYPE_CGROUP_SKB:
4937 case BPF_PROG_TYPE_CGROUP_SOCK:
4938 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
4939 case BPF_PROG_TYPE_SOCK_OPS:
4940 case BPF_PROG_TYPE_CGROUP_DEVICE:
4941 case BPF_PROG_TYPE_CGROUP_SYSCTL:
4942 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
4943 ret = cgroup_bpf_link_attach(attr, prog);
4945 case BPF_PROG_TYPE_EXT:
4946 ret = bpf_tracing_prog_attach(prog,
4947 attr->link_create.target_fd,
4948 attr->link_create.target_btf_id,
4949 attr->link_create.tracing.cookie);
4951 case BPF_PROG_TYPE_LSM:
4952 case BPF_PROG_TYPE_TRACING:
4953 if (attr->link_create.attach_type != prog->expected_attach_type) {
4957 if (prog->expected_attach_type == BPF_TRACE_RAW_TP)
4958 ret = bpf_raw_tp_link_attach(prog, NULL);
4959 else if (prog->expected_attach_type == BPF_TRACE_ITER)
4960 ret = bpf_iter_link_attach(attr, uattr, prog);
4961 else if (prog->expected_attach_type == BPF_LSM_CGROUP)
4962 ret = cgroup_bpf_link_attach(attr, prog);
4964 ret = bpf_tracing_prog_attach(prog,
4965 attr->link_create.target_fd,
4966 attr->link_create.target_btf_id,
4967 attr->link_create.tracing.cookie);
4969 case BPF_PROG_TYPE_FLOW_DISSECTOR:
4970 case BPF_PROG_TYPE_SK_LOOKUP:
4971 ret = netns_bpf_link_create(attr, prog);
4974 case BPF_PROG_TYPE_XDP:
4975 ret = bpf_xdp_link_attach(attr, prog);
4977 case BPF_PROG_TYPE_SCHED_CLS:
4978 ret = tcx_link_attach(attr, prog);
4980 case BPF_PROG_TYPE_NETFILTER:
4981 ret = bpf_nf_link_attach(attr, prog);
4984 case BPF_PROG_TYPE_PERF_EVENT:
4985 case BPF_PROG_TYPE_TRACEPOINT:
4986 ret = bpf_perf_link_attach(attr, prog);
4988 case BPF_PROG_TYPE_KPROBE:
4989 if (attr->link_create.attach_type == BPF_PERF_EVENT)
4990 ret = bpf_perf_link_attach(attr, prog);
4991 else if (attr->link_create.attach_type == BPF_TRACE_KPROBE_MULTI)
4992 ret = bpf_kprobe_multi_link_attach(attr, prog);
4993 else if (attr->link_create.attach_type == BPF_TRACE_UPROBE_MULTI)
4994 ret = bpf_uprobe_multi_link_attach(attr, prog);
5006 static int link_update_map(struct bpf_link *link, union bpf_attr *attr)
5008 struct bpf_map *new_map, *old_map = NULL;
5011 new_map = bpf_map_get(attr->link_update.new_map_fd);
5012 if (IS_ERR(new_map))
5013 return PTR_ERR(new_map);
5015 if (attr->link_update.flags & BPF_F_REPLACE) {
5016 old_map = bpf_map_get(attr->link_update.old_map_fd);
5017 if (IS_ERR(old_map)) {
5018 ret = PTR_ERR(old_map);
5021 } else if (attr->link_update.old_map_fd) {
5026 ret = link->ops->update_map(link, new_map, old_map);
5029 bpf_map_put(old_map);
5031 bpf_map_put(new_map);
5035 #define BPF_LINK_UPDATE_LAST_FIELD link_update.old_prog_fd
5037 static int link_update(union bpf_attr *attr)
5039 struct bpf_prog *old_prog = NULL, *new_prog;
5040 struct bpf_link *link;
5044 if (CHECK_ATTR(BPF_LINK_UPDATE))
5047 flags = attr->link_update.flags;
5048 if (flags & ~BPF_F_REPLACE)
5051 link = bpf_link_get_from_fd(attr->link_update.link_fd);
5053 return PTR_ERR(link);
5055 if (link->ops->update_map) {
5056 ret = link_update_map(link, attr);
5060 new_prog = bpf_prog_get(attr->link_update.new_prog_fd);
5061 if (IS_ERR(new_prog)) {
5062 ret = PTR_ERR(new_prog);
5066 if (flags & BPF_F_REPLACE) {
5067 old_prog = bpf_prog_get(attr->link_update.old_prog_fd);
5068 if (IS_ERR(old_prog)) {
5069 ret = PTR_ERR(old_prog);
5073 } else if (attr->link_update.old_prog_fd) {
5078 if (link->ops->update_prog)
5079 ret = link->ops->update_prog(link, new_prog, old_prog);
5085 bpf_prog_put(old_prog);
5087 bpf_prog_put(new_prog);
5089 bpf_link_put_direct(link);
5093 #define BPF_LINK_DETACH_LAST_FIELD link_detach.link_fd
5095 static int link_detach(union bpf_attr *attr)
5097 struct bpf_link *link;
5100 if (CHECK_ATTR(BPF_LINK_DETACH))
5103 link = bpf_link_get_from_fd(attr->link_detach.link_fd);
5105 return PTR_ERR(link);
5107 if (link->ops->detach)
5108 ret = link->ops->detach(link);
5112 bpf_link_put_direct(link);
5116 static struct bpf_link *bpf_link_inc_not_zero(struct bpf_link *link)
5118 return atomic64_fetch_add_unless(&link->refcnt, 1, 0) ? link : ERR_PTR(-ENOENT);
5121 struct bpf_link *bpf_link_by_id(u32 id)
5123 struct bpf_link *link;
5126 return ERR_PTR(-ENOENT);
5128 spin_lock_bh(&link_idr_lock);
5129 /* before link is "settled", ID is 0, pretend it doesn't exist yet */
5130 link = idr_find(&link_idr, id);
5133 link = bpf_link_inc_not_zero(link);
5135 link = ERR_PTR(-EAGAIN);
5137 link = ERR_PTR(-ENOENT);
5139 spin_unlock_bh(&link_idr_lock);
5143 struct bpf_link *bpf_link_get_curr_or_next(u32 *id)
5145 struct bpf_link *link;
5147 spin_lock_bh(&link_idr_lock);
5149 link = idr_get_next(&link_idr, id);
5151 link = bpf_link_inc_not_zero(link);
5157 spin_unlock_bh(&link_idr_lock);
5162 #define BPF_LINK_GET_FD_BY_ID_LAST_FIELD link_id
5164 static int bpf_link_get_fd_by_id(const union bpf_attr *attr)
5166 struct bpf_link *link;
5167 u32 id = attr->link_id;
5170 if (CHECK_ATTR(BPF_LINK_GET_FD_BY_ID))
5173 if (!capable(CAP_SYS_ADMIN))
5176 link = bpf_link_by_id(id);
5178 return PTR_ERR(link);
5180 fd = bpf_link_new_fd(link);
5182 bpf_link_put_direct(link);
5187 DEFINE_MUTEX(bpf_stats_enabled_mutex);
5189 static int bpf_stats_release(struct inode *inode, struct file *file)
5191 mutex_lock(&bpf_stats_enabled_mutex);
5192 static_key_slow_dec(&bpf_stats_enabled_key.key);
5193 mutex_unlock(&bpf_stats_enabled_mutex);
5197 static const struct file_operations bpf_stats_fops = {
5198 .release = bpf_stats_release,
5201 static int bpf_enable_runtime_stats(void)
5205 mutex_lock(&bpf_stats_enabled_mutex);
5207 /* Set a very high limit to avoid overflow */
5208 if (static_key_count(&bpf_stats_enabled_key.key) > INT_MAX / 2) {
5209 mutex_unlock(&bpf_stats_enabled_mutex);
5213 fd = anon_inode_getfd("bpf-stats", &bpf_stats_fops, NULL, O_CLOEXEC);
5215 static_key_slow_inc(&bpf_stats_enabled_key.key);
5217 mutex_unlock(&bpf_stats_enabled_mutex);
5221 #define BPF_ENABLE_STATS_LAST_FIELD enable_stats.type
5223 static int bpf_enable_stats(union bpf_attr *attr)
5226 if (CHECK_ATTR(BPF_ENABLE_STATS))
5229 if (!capable(CAP_SYS_ADMIN))
5232 switch (attr->enable_stats.type) {
5233 case BPF_STATS_RUN_TIME:
5234 return bpf_enable_runtime_stats();
5241 #define BPF_ITER_CREATE_LAST_FIELD iter_create.flags
5243 static int bpf_iter_create(union bpf_attr *attr)
5245 struct bpf_link *link;
5248 if (CHECK_ATTR(BPF_ITER_CREATE))
5251 if (attr->iter_create.flags)
5254 link = bpf_link_get_from_fd(attr->iter_create.link_fd);
5256 return PTR_ERR(link);
5258 err = bpf_iter_new_fd(link);
5259 bpf_link_put_direct(link);
5264 #define BPF_PROG_BIND_MAP_LAST_FIELD prog_bind_map.flags
5266 static int bpf_prog_bind_map(union bpf_attr *attr)
5268 struct bpf_prog *prog;
5269 struct bpf_map *map;
5270 struct bpf_map **used_maps_old, **used_maps_new;
5273 if (CHECK_ATTR(BPF_PROG_BIND_MAP))
5276 if (attr->prog_bind_map.flags)
5279 prog = bpf_prog_get(attr->prog_bind_map.prog_fd);
5281 return PTR_ERR(prog);
5283 map = bpf_map_get(attr->prog_bind_map.map_fd);
5289 mutex_lock(&prog->aux->used_maps_mutex);
5291 used_maps_old = prog->aux->used_maps;
5293 for (i = 0; i < prog->aux->used_map_cnt; i++)
5294 if (used_maps_old[i] == map) {
5299 used_maps_new = kmalloc_array(prog->aux->used_map_cnt + 1,
5300 sizeof(used_maps_new[0]),
5302 if (!used_maps_new) {
5307 memcpy(used_maps_new, used_maps_old,
5308 sizeof(used_maps_old[0]) * prog->aux->used_map_cnt);
5309 used_maps_new[prog->aux->used_map_cnt] = map;
5311 prog->aux->used_map_cnt++;
5312 prog->aux->used_maps = used_maps_new;
5314 kfree(used_maps_old);
5317 mutex_unlock(&prog->aux->used_maps_mutex);
5326 static int __sys_bpf(int cmd, bpfptr_t uattr, unsigned int size)
5328 union bpf_attr attr;
5331 err = bpf_check_uarg_tail_zero(uattr, sizeof(attr), size);
5334 size = min_t(u32, size, sizeof(attr));
5336 /* copy attributes from user space, may be less than sizeof(bpf_attr) */
5337 memset(&attr, 0, sizeof(attr));
5338 if (copy_from_bpfptr(&attr, uattr, size) != 0)
5341 err = security_bpf(cmd, &attr, size);
5346 case BPF_MAP_CREATE:
5347 err = map_create(&attr);
5349 case BPF_MAP_LOOKUP_ELEM:
5350 err = map_lookup_elem(&attr);
5352 case BPF_MAP_UPDATE_ELEM:
5353 err = map_update_elem(&attr, uattr);
5355 case BPF_MAP_DELETE_ELEM:
5356 err = map_delete_elem(&attr, uattr);
5358 case BPF_MAP_GET_NEXT_KEY:
5359 err = map_get_next_key(&attr);
5361 case BPF_MAP_FREEZE:
5362 err = map_freeze(&attr);
5365 err = bpf_prog_load(&attr, uattr, size);
5368 err = bpf_obj_pin(&attr);
5371 err = bpf_obj_get(&attr);
5373 case BPF_PROG_ATTACH:
5374 err = bpf_prog_attach(&attr);
5376 case BPF_PROG_DETACH:
5377 err = bpf_prog_detach(&attr);
5379 case BPF_PROG_QUERY:
5380 err = bpf_prog_query(&attr, uattr.user);
5382 case BPF_PROG_TEST_RUN:
5383 err = bpf_prog_test_run(&attr, uattr.user);
5385 case BPF_PROG_GET_NEXT_ID:
5386 err = bpf_obj_get_next_id(&attr, uattr.user,
5387 &prog_idr, &prog_idr_lock);
5389 case BPF_MAP_GET_NEXT_ID:
5390 err = bpf_obj_get_next_id(&attr, uattr.user,
5391 &map_idr, &map_idr_lock);
5393 case BPF_BTF_GET_NEXT_ID:
5394 err = bpf_obj_get_next_id(&attr, uattr.user,
5395 &btf_idr, &btf_idr_lock);
5397 case BPF_PROG_GET_FD_BY_ID:
5398 err = bpf_prog_get_fd_by_id(&attr);
5400 case BPF_MAP_GET_FD_BY_ID:
5401 err = bpf_map_get_fd_by_id(&attr);
5403 case BPF_OBJ_GET_INFO_BY_FD:
5404 err = bpf_obj_get_info_by_fd(&attr, uattr.user);
5406 case BPF_RAW_TRACEPOINT_OPEN:
5407 err = bpf_raw_tracepoint_open(&attr);
5410 err = bpf_btf_load(&attr, uattr, size);
5412 case BPF_BTF_GET_FD_BY_ID:
5413 err = bpf_btf_get_fd_by_id(&attr);
5415 case BPF_TASK_FD_QUERY:
5416 err = bpf_task_fd_query(&attr, uattr.user);
5418 case BPF_MAP_LOOKUP_AND_DELETE_ELEM:
5419 err = map_lookup_and_delete_elem(&attr);
5421 case BPF_MAP_LOOKUP_BATCH:
5422 err = bpf_map_do_batch(&attr, uattr.user, BPF_MAP_LOOKUP_BATCH);
5424 case BPF_MAP_LOOKUP_AND_DELETE_BATCH:
5425 err = bpf_map_do_batch(&attr, uattr.user,
5426 BPF_MAP_LOOKUP_AND_DELETE_BATCH);
5428 case BPF_MAP_UPDATE_BATCH:
5429 err = bpf_map_do_batch(&attr, uattr.user, BPF_MAP_UPDATE_BATCH);
5431 case BPF_MAP_DELETE_BATCH:
5432 err = bpf_map_do_batch(&attr, uattr.user, BPF_MAP_DELETE_BATCH);
5434 case BPF_LINK_CREATE:
5435 err = link_create(&attr, uattr);
5437 case BPF_LINK_UPDATE:
5438 err = link_update(&attr);
5440 case BPF_LINK_GET_FD_BY_ID:
5441 err = bpf_link_get_fd_by_id(&attr);
5443 case BPF_LINK_GET_NEXT_ID:
5444 err = bpf_obj_get_next_id(&attr, uattr.user,
5445 &link_idr, &link_idr_lock);
5447 case BPF_ENABLE_STATS:
5448 err = bpf_enable_stats(&attr);
5450 case BPF_ITER_CREATE:
5451 err = bpf_iter_create(&attr);
5453 case BPF_LINK_DETACH:
5454 err = link_detach(&attr);
5456 case BPF_PROG_BIND_MAP:
5457 err = bpf_prog_bind_map(&attr);
5467 SYSCALL_DEFINE3(bpf, int, cmd, union bpf_attr __user *, uattr, unsigned int, size)
5469 return __sys_bpf(cmd, USER_BPFPTR(uattr), size);
5472 static bool syscall_prog_is_valid_access(int off, int size,
5473 enum bpf_access_type type,
5474 const struct bpf_prog *prog,
5475 struct bpf_insn_access_aux *info)
5477 if (off < 0 || off >= U16_MAX)
5479 if (off % size != 0)
5484 BPF_CALL_3(bpf_sys_bpf, int, cmd, union bpf_attr *, attr, u32, attr_size)
5487 case BPF_MAP_CREATE:
5488 case BPF_MAP_DELETE_ELEM:
5489 case BPF_MAP_UPDATE_ELEM:
5490 case BPF_MAP_FREEZE:
5491 case BPF_MAP_GET_FD_BY_ID:
5494 case BPF_LINK_CREATE:
5495 case BPF_RAW_TRACEPOINT_OPEN:
5500 return __sys_bpf(cmd, KERNEL_BPFPTR(attr), attr_size);
5504 /* To shut up -Wmissing-prototypes.
5505 * This function is used by the kernel light skeleton
5506 * to load bpf programs when modules are loaded or during kernel boot.
5507 * See tools/lib/bpf/skel_internal.h
5509 int kern_sys_bpf(int cmd, union bpf_attr *attr, unsigned int size);
5511 int kern_sys_bpf(int cmd, union bpf_attr *attr, unsigned int size)
5513 struct bpf_prog * __maybe_unused prog;
5514 struct bpf_tramp_run_ctx __maybe_unused run_ctx;
5517 #ifdef CONFIG_BPF_JIT /* __bpf_prog_enter_sleepable used by trampoline and JIT */
5518 case BPF_PROG_TEST_RUN:
5519 if (attr->test.data_in || attr->test.data_out ||
5520 attr->test.ctx_out || attr->test.duration ||
5521 attr->test.repeat || attr->test.flags)
5524 prog = bpf_prog_get_type(attr->test.prog_fd, BPF_PROG_TYPE_SYSCALL);
5526 return PTR_ERR(prog);
5528 if (attr->test.ctx_size_in < prog->aux->max_ctx_offset ||
5529 attr->test.ctx_size_in > U16_MAX) {
5534 run_ctx.bpf_cookie = 0;
5535 if (!__bpf_prog_enter_sleepable_recur(prog, &run_ctx)) {
5536 /* recursion detected */
5537 __bpf_prog_exit_sleepable_recur(prog, 0, &run_ctx);
5541 attr->test.retval = bpf_prog_run(prog, (void *) (long) attr->test.ctx_in);
5542 __bpf_prog_exit_sleepable_recur(prog, 0 /* bpf_prog_run does runtime stats */,
5548 return ____bpf_sys_bpf(cmd, attr, size);
5551 EXPORT_SYMBOL(kern_sys_bpf);
5553 static const struct bpf_func_proto bpf_sys_bpf_proto = {
5554 .func = bpf_sys_bpf,
5556 .ret_type = RET_INTEGER,
5557 .arg1_type = ARG_ANYTHING,
5558 .arg2_type = ARG_PTR_TO_MEM | MEM_RDONLY,
5559 .arg3_type = ARG_CONST_SIZE,
5562 const struct bpf_func_proto * __weak
5563 tracing_prog_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
5565 return bpf_base_func_proto(func_id);
5568 BPF_CALL_1(bpf_sys_close, u32, fd)
5570 /* When bpf program calls this helper there should not be
5571 * an fdget() without matching completed fdput().
5572 * This helper is allowed in the following callchain only:
5573 * sys_bpf->prog_test_run->bpf_prog->bpf_sys_close
5575 return close_fd(fd);
5578 static const struct bpf_func_proto bpf_sys_close_proto = {
5579 .func = bpf_sys_close,
5581 .ret_type = RET_INTEGER,
5582 .arg1_type = ARG_ANYTHING,
5585 BPF_CALL_4(bpf_kallsyms_lookup_name, const char *, name, int, name_sz, int, flags, u64 *, res)
5590 if (name_sz <= 1 || name[name_sz - 1])
5593 if (!bpf_dump_raw_ok(current_cred()))
5596 *res = kallsyms_lookup_name(name);
5597 return *res ? 0 : -ENOENT;
5600 static const struct bpf_func_proto bpf_kallsyms_lookup_name_proto = {
5601 .func = bpf_kallsyms_lookup_name,
5603 .ret_type = RET_INTEGER,
5604 .arg1_type = ARG_PTR_TO_MEM,
5605 .arg2_type = ARG_CONST_SIZE_OR_ZERO,
5606 .arg3_type = ARG_ANYTHING,
5607 .arg4_type = ARG_PTR_TO_LONG,
5610 static const struct bpf_func_proto *
5611 syscall_prog_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
5614 case BPF_FUNC_sys_bpf:
5615 return !perfmon_capable() ? NULL : &bpf_sys_bpf_proto;
5616 case BPF_FUNC_btf_find_by_name_kind:
5617 return &bpf_btf_find_by_name_kind_proto;
5618 case BPF_FUNC_sys_close:
5619 return &bpf_sys_close_proto;
5620 case BPF_FUNC_kallsyms_lookup_name:
5621 return &bpf_kallsyms_lookup_name_proto;
5623 return tracing_prog_func_proto(func_id, prog);
5627 const struct bpf_verifier_ops bpf_syscall_verifier_ops = {
5628 .get_func_proto = syscall_prog_func_proto,
5629 .is_valid_access = syscall_prog_is_valid_access,
5632 const struct bpf_prog_ops bpf_syscall_prog_ops = {
5633 .test_run = bpf_prog_test_run_syscall,
5636 #ifdef CONFIG_SYSCTL
5637 static int bpf_stats_handler(struct ctl_table *table, int write,
5638 void *buffer, size_t *lenp, loff_t *ppos)
5640 struct static_key *key = (struct static_key *)table->data;
5641 static int saved_val;
5643 struct ctl_table tmp = {
5645 .maxlen = sizeof(val),
5646 .mode = table->mode,
5647 .extra1 = SYSCTL_ZERO,
5648 .extra2 = SYSCTL_ONE,
5651 if (write && !capable(CAP_SYS_ADMIN))
5654 mutex_lock(&bpf_stats_enabled_mutex);
5656 ret = proc_dointvec_minmax(&tmp, write, buffer, lenp, ppos);
5657 if (write && !ret && val != saved_val) {
5659 static_key_slow_inc(key);
5661 static_key_slow_dec(key);
5664 mutex_unlock(&bpf_stats_enabled_mutex);
5668 void __weak unpriv_ebpf_notify(int new_state)
5672 static int bpf_unpriv_handler(struct ctl_table *table, int write,
5673 void *buffer, size_t *lenp, loff_t *ppos)
5675 int ret, unpriv_enable = *(int *)table->data;
5676 bool locked_state = unpriv_enable == 1;
5677 struct ctl_table tmp = *table;
5679 if (write && !capable(CAP_SYS_ADMIN))
5682 tmp.data = &unpriv_enable;
5683 ret = proc_dointvec_minmax(&tmp, write, buffer, lenp, ppos);
5684 if (write && !ret) {
5685 if (locked_state && unpriv_enable != 1)
5687 *(int *)table->data = unpriv_enable;
5691 unpriv_ebpf_notify(unpriv_enable);
5696 static struct ctl_table bpf_syscall_table[] = {
5698 .procname = "unprivileged_bpf_disabled",
5699 .data = &sysctl_unprivileged_bpf_disabled,
5700 .maxlen = sizeof(sysctl_unprivileged_bpf_disabled),
5702 .proc_handler = bpf_unpriv_handler,
5703 .extra1 = SYSCTL_ZERO,
5704 .extra2 = SYSCTL_TWO,
5707 .procname = "bpf_stats_enabled",
5708 .data = &bpf_stats_enabled_key.key,
5710 .proc_handler = bpf_stats_handler,
5715 static int __init bpf_syscall_sysctl_init(void)
5717 register_sysctl_init("kernel", bpf_syscall_table);
5720 late_initcall(bpf_syscall_sysctl_init);
5721 #endif /* CONFIG_SYSCTL */