1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
5 #include <linux/bpf-cgroup.h>
6 #include <linux/bpf_trace.h>
7 #include <linux/bpf_lirc.h>
8 #include <linux/bpf_verifier.h>
9 #include <linux/bsearch.h>
10 #include <linux/btf.h>
11 #include <linux/syscalls.h>
12 #include <linux/slab.h>
13 #include <linux/sched/signal.h>
14 #include <linux/vmalloc.h>
15 #include <linux/mmzone.h>
16 #include <linux/anon_inodes.h>
17 #include <linux/fdtable.h>
18 #include <linux/file.h>
20 #include <linux/license.h>
21 #include <linux/filter.h>
22 #include <linux/kernel.h>
23 #include <linux/idr.h>
24 #include <linux/cred.h>
25 #include <linux/timekeeping.h>
26 #include <linux/ctype.h>
27 #include <linux/nospec.h>
28 #include <linux/audit.h>
29 #include <uapi/linux/btf.h>
30 #include <linux/pgtable.h>
31 #include <linux/bpf_lsm.h>
32 #include <linux/poll.h>
33 #include <linux/sort.h>
34 #include <linux/bpf-netns.h>
35 #include <linux/rcupdate_trace.h>
36 #include <linux/memcontrol.h>
37 #include <linux/trace_events.h>
39 #include <net/netfilter/nf_bpf_link.h>
40 #include <net/netkit.h>
43 #define IS_FD_ARRAY(map) ((map)->map_type == BPF_MAP_TYPE_PERF_EVENT_ARRAY || \
44 (map)->map_type == BPF_MAP_TYPE_CGROUP_ARRAY || \
45 (map)->map_type == BPF_MAP_TYPE_ARRAY_OF_MAPS)
46 #define IS_FD_PROG_ARRAY(map) ((map)->map_type == BPF_MAP_TYPE_PROG_ARRAY)
47 #define IS_FD_HASH(map) ((map)->map_type == BPF_MAP_TYPE_HASH_OF_MAPS)
48 #define IS_FD_MAP(map) (IS_FD_ARRAY(map) || IS_FD_PROG_ARRAY(map) || \
51 #define BPF_OBJ_FLAG_MASK (BPF_F_RDONLY | BPF_F_WRONLY)
53 DEFINE_PER_CPU(int, bpf_prog_active);
54 static DEFINE_IDR(prog_idr);
55 static DEFINE_SPINLOCK(prog_idr_lock);
56 static DEFINE_IDR(map_idr);
57 static DEFINE_SPINLOCK(map_idr_lock);
58 static DEFINE_IDR(link_idr);
59 static DEFINE_SPINLOCK(link_idr_lock);
61 int sysctl_unprivileged_bpf_disabled __read_mostly =
62 IS_BUILTIN(CONFIG_BPF_UNPRIV_DEFAULT_OFF) ? 2 : 0;
64 static const struct bpf_map_ops * const bpf_map_types[] = {
65 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type)
66 #define BPF_MAP_TYPE(_id, _ops) \
68 #define BPF_LINK_TYPE(_id, _name)
69 #include <linux/bpf_types.h>
76 * If we're handed a bigger struct than we know of, ensure all the unknown bits
77 * are 0 - i.e. new user-space does not rely on any kernel feature extensions
78 * we don't know about yet.
80 * There is a ToCToU between this function call and the following
81 * copy_from_user() call. However, this is not a concern since this function is
82 * meant to be a future-proofing of bits.
84 int bpf_check_uarg_tail_zero(bpfptr_t uaddr,
90 if (unlikely(actual_size > PAGE_SIZE)) /* silly large */
93 if (actual_size <= expected_size)
97 res = memchr_inv(uaddr.kernel + expected_size, 0,
98 actual_size - expected_size) == NULL;
100 res = check_zeroed_user(uaddr.user + expected_size,
101 actual_size - expected_size);
104 return res ? 0 : -E2BIG;
107 const struct bpf_map_ops bpf_map_offload_ops = {
108 .map_meta_equal = bpf_map_meta_equal,
109 .map_alloc = bpf_map_offload_map_alloc,
110 .map_free = bpf_map_offload_map_free,
111 .map_check_btf = map_check_no_btf,
112 .map_mem_usage = bpf_map_offload_map_mem_usage,
115 static void bpf_map_write_active_inc(struct bpf_map *map)
117 atomic64_inc(&map->writecnt);
120 static void bpf_map_write_active_dec(struct bpf_map *map)
122 atomic64_dec(&map->writecnt);
125 bool bpf_map_write_active(const struct bpf_map *map)
127 return atomic64_read(&map->writecnt) != 0;
130 static u32 bpf_map_value_size(const struct bpf_map *map)
132 if (map->map_type == BPF_MAP_TYPE_PERCPU_HASH ||
133 map->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH ||
134 map->map_type == BPF_MAP_TYPE_PERCPU_ARRAY ||
135 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
136 return round_up(map->value_size, 8) * num_possible_cpus();
137 else if (IS_FD_MAP(map))
140 return map->value_size;
143 static void maybe_wait_bpf_programs(struct bpf_map *map)
145 /* Wait for any running BPF programs to complete so that
146 * userspace, when we return to it, knows that all programs
147 * that could be running use the new map value.
149 if (map->map_type == BPF_MAP_TYPE_HASH_OF_MAPS ||
150 map->map_type == BPF_MAP_TYPE_ARRAY_OF_MAPS)
154 static int bpf_map_update_value(struct bpf_map *map, struct file *map_file,
155 void *key, void *value, __u64 flags)
159 /* Need to create a kthread, thus must support schedule */
160 if (bpf_map_is_offloaded(map)) {
161 return bpf_map_offload_update_elem(map, key, value, flags);
162 } else if (map->map_type == BPF_MAP_TYPE_CPUMAP ||
163 map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
164 return map->ops->map_update_elem(map, key, value, flags);
165 } else if (map->map_type == BPF_MAP_TYPE_SOCKHASH ||
166 map->map_type == BPF_MAP_TYPE_SOCKMAP) {
167 return sock_map_update_elem_sys(map, key, value, flags);
168 } else if (IS_FD_PROG_ARRAY(map)) {
169 return bpf_fd_array_map_update_elem(map, map_file, key, value,
173 bpf_disable_instrumentation();
174 if (map->map_type == BPF_MAP_TYPE_PERCPU_HASH ||
175 map->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH) {
176 err = bpf_percpu_hash_update(map, key, value, flags);
177 } else if (map->map_type == BPF_MAP_TYPE_PERCPU_ARRAY) {
178 err = bpf_percpu_array_update(map, key, value, flags);
179 } else if (map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE) {
180 err = bpf_percpu_cgroup_storage_update(map, key, value,
182 } else if (IS_FD_ARRAY(map)) {
184 err = bpf_fd_array_map_update_elem(map, map_file, key, value,
187 } else if (map->map_type == BPF_MAP_TYPE_HASH_OF_MAPS) {
189 err = bpf_fd_htab_map_update_elem(map, map_file, key, value,
192 } else if (map->map_type == BPF_MAP_TYPE_REUSEPORT_SOCKARRAY) {
193 /* rcu_read_lock() is not needed */
194 err = bpf_fd_reuseport_array_update_elem(map, key, value,
196 } else if (map->map_type == BPF_MAP_TYPE_QUEUE ||
197 map->map_type == BPF_MAP_TYPE_STACK ||
198 map->map_type == BPF_MAP_TYPE_BLOOM_FILTER) {
199 err = map->ops->map_push_elem(map, value, flags);
202 err = map->ops->map_update_elem(map, key, value, flags);
205 bpf_enable_instrumentation();
206 maybe_wait_bpf_programs(map);
211 static int bpf_map_copy_value(struct bpf_map *map, void *key, void *value,
217 if (bpf_map_is_offloaded(map))
218 return bpf_map_offload_lookup_elem(map, key, value);
220 bpf_disable_instrumentation();
221 if (map->map_type == BPF_MAP_TYPE_PERCPU_HASH ||
222 map->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH) {
223 err = bpf_percpu_hash_copy(map, key, value);
224 } else if (map->map_type == BPF_MAP_TYPE_PERCPU_ARRAY) {
225 err = bpf_percpu_array_copy(map, key, value);
226 } else if (map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE) {
227 err = bpf_percpu_cgroup_storage_copy(map, key, value);
228 } else if (map->map_type == BPF_MAP_TYPE_STACK_TRACE) {
229 err = bpf_stackmap_copy(map, key, value);
230 } else if (IS_FD_ARRAY(map) || IS_FD_PROG_ARRAY(map)) {
231 err = bpf_fd_array_map_lookup_elem(map, key, value);
232 } else if (IS_FD_HASH(map)) {
233 err = bpf_fd_htab_map_lookup_elem(map, key, value);
234 } else if (map->map_type == BPF_MAP_TYPE_REUSEPORT_SOCKARRAY) {
235 err = bpf_fd_reuseport_array_lookup_elem(map, key, value);
236 } else if (map->map_type == BPF_MAP_TYPE_QUEUE ||
237 map->map_type == BPF_MAP_TYPE_STACK ||
238 map->map_type == BPF_MAP_TYPE_BLOOM_FILTER) {
239 err = map->ops->map_peek_elem(map, value);
240 } else if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
241 /* struct_ops map requires directly updating "value" */
242 err = bpf_struct_ops_map_sys_lookup_elem(map, key, value);
245 if (map->ops->map_lookup_elem_sys_only)
246 ptr = map->ops->map_lookup_elem_sys_only(map, key);
248 ptr = map->ops->map_lookup_elem(map, key);
255 if (flags & BPF_F_LOCK)
256 /* lock 'ptr' and copy everything but lock */
257 copy_map_value_locked(map, value, ptr, true);
259 copy_map_value(map, value, ptr);
260 /* mask lock and timer, since value wasn't zero inited */
261 check_and_init_map_value(map, value);
266 bpf_enable_instrumentation();
267 maybe_wait_bpf_programs(map);
272 /* Please, do not use this function outside from the map creation path
273 * (e.g. in map update path) without taking care of setting the active
274 * memory cgroup (see at bpf_map_kmalloc_node() for example).
276 static void *__bpf_map_area_alloc(u64 size, int numa_node, bool mmapable)
278 /* We really just want to fail instead of triggering OOM killer
279 * under memory pressure, therefore we set __GFP_NORETRY to kmalloc,
280 * which is used for lower order allocation requests.
282 * It has been observed that higher order allocation requests done by
283 * vmalloc with __GFP_NORETRY being set might fail due to not trying
284 * to reclaim memory from the page cache, thus we set
285 * __GFP_RETRY_MAYFAIL to avoid such situations.
288 gfp_t gfp = bpf_memcg_flags(__GFP_NOWARN | __GFP_ZERO);
289 unsigned int flags = 0;
290 unsigned long align = 1;
293 if (size >= SIZE_MAX)
296 /* kmalloc()'ed memory can't be mmap()'ed */
298 BUG_ON(!PAGE_ALIGNED(size));
301 } else if (size <= (PAGE_SIZE << PAGE_ALLOC_COSTLY_ORDER)) {
302 area = kmalloc_node(size, gfp | GFP_USER | __GFP_NORETRY,
308 return __vmalloc_node_range(size, align, VMALLOC_START, VMALLOC_END,
309 gfp | GFP_KERNEL | __GFP_RETRY_MAYFAIL, PAGE_KERNEL,
310 flags, numa_node, __builtin_return_address(0));
313 void *bpf_map_area_alloc(u64 size, int numa_node)
315 return __bpf_map_area_alloc(size, numa_node, false);
318 void *bpf_map_area_mmapable_alloc(u64 size, int numa_node)
320 return __bpf_map_area_alloc(size, numa_node, true);
323 void bpf_map_area_free(void *area)
328 static u32 bpf_map_flags_retain_permanent(u32 flags)
330 /* Some map creation flags are not tied to the map object but
331 * rather to the map fd instead, so they have no meaning upon
332 * map object inspection since multiple file descriptors with
333 * different (access) properties can exist here. Thus, given
334 * this has zero meaning for the map itself, lets clear these
337 return flags & ~(BPF_F_RDONLY | BPF_F_WRONLY);
340 void bpf_map_init_from_attr(struct bpf_map *map, union bpf_attr *attr)
342 map->map_type = attr->map_type;
343 map->key_size = attr->key_size;
344 map->value_size = attr->value_size;
345 map->max_entries = attr->max_entries;
346 map->map_flags = bpf_map_flags_retain_permanent(attr->map_flags);
347 map->numa_node = bpf_map_attr_numa_node(attr);
348 map->map_extra = attr->map_extra;
351 static int bpf_map_alloc_id(struct bpf_map *map)
355 idr_preload(GFP_KERNEL);
356 spin_lock_bh(&map_idr_lock);
357 id = idr_alloc_cyclic(&map_idr, map, 1, INT_MAX, GFP_ATOMIC);
360 spin_unlock_bh(&map_idr_lock);
363 if (WARN_ON_ONCE(!id))
366 return id > 0 ? 0 : id;
369 void bpf_map_free_id(struct bpf_map *map)
373 /* Offloaded maps are removed from the IDR store when their device
374 * disappears - even if someone holds an fd to them they are unusable,
375 * the memory is gone, all ops will fail; they are simply waiting for
376 * refcnt to drop to be freed.
381 spin_lock_irqsave(&map_idr_lock, flags);
383 idr_remove(&map_idr, map->id);
386 spin_unlock_irqrestore(&map_idr_lock, flags);
389 #ifdef CONFIG_MEMCG_KMEM
390 static void bpf_map_save_memcg(struct bpf_map *map)
392 /* Currently if a map is created by a process belonging to the root
393 * memory cgroup, get_obj_cgroup_from_current() will return NULL.
394 * So we have to check map->objcg for being NULL each time it's
397 if (memcg_bpf_enabled())
398 map->objcg = get_obj_cgroup_from_current();
401 static void bpf_map_release_memcg(struct bpf_map *map)
404 obj_cgroup_put(map->objcg);
407 static struct mem_cgroup *bpf_map_get_memcg(const struct bpf_map *map)
410 return get_mem_cgroup_from_objcg(map->objcg);
412 return root_mem_cgroup;
415 void *bpf_map_kmalloc_node(const struct bpf_map *map, size_t size, gfp_t flags,
418 struct mem_cgroup *memcg, *old_memcg;
421 memcg = bpf_map_get_memcg(map);
422 old_memcg = set_active_memcg(memcg);
423 ptr = kmalloc_node(size, flags | __GFP_ACCOUNT, node);
424 set_active_memcg(old_memcg);
425 mem_cgroup_put(memcg);
430 void *bpf_map_kzalloc(const struct bpf_map *map, size_t size, gfp_t flags)
432 struct mem_cgroup *memcg, *old_memcg;
435 memcg = bpf_map_get_memcg(map);
436 old_memcg = set_active_memcg(memcg);
437 ptr = kzalloc(size, flags | __GFP_ACCOUNT);
438 set_active_memcg(old_memcg);
439 mem_cgroup_put(memcg);
444 void *bpf_map_kvcalloc(struct bpf_map *map, size_t n, size_t size,
447 struct mem_cgroup *memcg, *old_memcg;
450 memcg = bpf_map_get_memcg(map);
451 old_memcg = set_active_memcg(memcg);
452 ptr = kvcalloc(n, size, flags | __GFP_ACCOUNT);
453 set_active_memcg(old_memcg);
454 mem_cgroup_put(memcg);
459 void __percpu *bpf_map_alloc_percpu(const struct bpf_map *map, size_t size,
460 size_t align, gfp_t flags)
462 struct mem_cgroup *memcg, *old_memcg;
465 memcg = bpf_map_get_memcg(map);
466 old_memcg = set_active_memcg(memcg);
467 ptr = __alloc_percpu_gfp(size, align, flags | __GFP_ACCOUNT);
468 set_active_memcg(old_memcg);
469 mem_cgroup_put(memcg);
475 static void bpf_map_save_memcg(struct bpf_map *map)
479 static void bpf_map_release_memcg(struct bpf_map *map)
484 static int btf_field_cmp(const void *a, const void *b)
486 const struct btf_field *f1 = a, *f2 = b;
488 if (f1->offset < f2->offset)
490 else if (f1->offset > f2->offset)
495 struct btf_field *btf_record_find(const struct btf_record *rec, u32 offset,
498 struct btf_field *field;
500 if (IS_ERR_OR_NULL(rec) || !(rec->field_mask & field_mask))
502 field = bsearch(&offset, rec->fields, rec->cnt, sizeof(rec->fields[0]), btf_field_cmp);
503 if (!field || !(field->type & field_mask))
508 void btf_record_free(struct btf_record *rec)
512 if (IS_ERR_OR_NULL(rec))
514 for (i = 0; i < rec->cnt; i++) {
515 switch (rec->fields[i].type) {
518 case BPF_KPTR_PERCPU:
519 if (rec->fields[i].kptr.module)
520 module_put(rec->fields[i].kptr.module);
521 btf_put(rec->fields[i].kptr.btf);
530 /* Nothing to release */
540 void bpf_map_free_record(struct bpf_map *map)
542 btf_record_free(map->record);
546 struct btf_record *btf_record_dup(const struct btf_record *rec)
548 const struct btf_field *fields;
549 struct btf_record *new_rec;
552 if (IS_ERR_OR_NULL(rec))
554 size = offsetof(struct btf_record, fields[rec->cnt]);
555 new_rec = kmemdup(rec, size, GFP_KERNEL | __GFP_NOWARN);
557 return ERR_PTR(-ENOMEM);
558 /* Do a deep copy of the btf_record */
559 fields = rec->fields;
561 for (i = 0; i < rec->cnt; i++) {
562 switch (fields[i].type) {
565 case BPF_KPTR_PERCPU:
566 btf_get(fields[i].kptr.btf);
567 if (fields[i].kptr.module && !try_module_get(fields[i].kptr.module)) {
579 /* Nothing to acquire */
590 btf_record_free(new_rec);
594 bool btf_record_equal(const struct btf_record *rec_a, const struct btf_record *rec_b)
596 bool a_has_fields = !IS_ERR_OR_NULL(rec_a), b_has_fields = !IS_ERR_OR_NULL(rec_b);
599 if (!a_has_fields && !b_has_fields)
601 if (a_has_fields != b_has_fields)
603 if (rec_a->cnt != rec_b->cnt)
605 size = offsetof(struct btf_record, fields[rec_a->cnt]);
606 /* btf_parse_fields uses kzalloc to allocate a btf_record, so unused
607 * members are zeroed out. So memcmp is safe to do without worrying
608 * about padding/unused fields.
610 * While spin_lock, timer, and kptr have no relation to map BTF,
611 * list_head metadata is specific to map BTF, the btf and value_rec
612 * members in particular. btf is the map BTF, while value_rec points to
613 * btf_record in that map BTF.
615 * So while by default, we don't rely on the map BTF (which the records
616 * were parsed from) matching for both records, which is not backwards
617 * compatible, in case list_head is part of it, we implicitly rely on
618 * that by way of depending on memcmp succeeding for it.
620 return !memcmp(rec_a, rec_b, size);
623 void bpf_obj_free_timer(const struct btf_record *rec, void *obj)
625 if (WARN_ON_ONCE(!btf_record_has_field(rec, BPF_TIMER)))
627 bpf_timer_cancel_and_free(obj + rec->timer_off);
630 void bpf_obj_free_fields(const struct btf_record *rec, void *obj)
632 const struct btf_field *fields;
635 if (IS_ERR_OR_NULL(rec))
637 fields = rec->fields;
638 for (i = 0; i < rec->cnt; i++) {
639 struct btf_struct_meta *pointee_struct_meta;
640 const struct btf_field *field = &fields[i];
641 void *field_ptr = obj + field->offset;
644 switch (fields[i].type) {
648 bpf_timer_cancel_and_free(field_ptr);
651 WRITE_ONCE(*(u64 *)field_ptr, 0);
654 case BPF_KPTR_PERCPU:
655 xchgd_field = (void *)xchg((unsigned long *)field_ptr, 0);
659 if (!btf_is_kernel(field->kptr.btf)) {
660 pointee_struct_meta = btf_find_struct_meta(field->kptr.btf,
663 __bpf_obj_drop_impl(xchgd_field, pointee_struct_meta ?
664 pointee_struct_meta->record : NULL,
665 fields[i].type == BPF_KPTR_PERCPU);
668 field->kptr.dtor(xchgd_field);
672 if (WARN_ON_ONCE(rec->spin_lock_off < 0))
674 bpf_list_head_free(field, field_ptr, obj + rec->spin_lock_off);
677 if (WARN_ON_ONCE(rec->spin_lock_off < 0))
679 bpf_rb_root_free(field, field_ptr, obj + rec->spin_lock_off);
692 /* called from workqueue */
693 static void bpf_map_free_deferred(struct work_struct *work)
695 struct bpf_map *map = container_of(work, struct bpf_map, work);
696 struct btf_record *rec = map->record;
698 security_bpf_map_free(map);
699 bpf_map_release_memcg(map);
700 /* implementation dependent freeing */
701 map->ops->map_free(map);
702 /* Delay freeing of btf_record for maps, as map_free
703 * callback usually needs access to them. It is better to do it here
704 * than require each callback to do the free itself manually.
706 * Note that the btf_record stashed in map->inner_map_meta->record was
707 * already freed using the map_free callback for map in map case which
708 * eventually calls bpf_map_free_meta, since inner_map_meta is only a
709 * template bpf_map struct used during verification.
711 btf_record_free(rec);
714 static void bpf_map_put_uref(struct bpf_map *map)
716 if (atomic64_dec_and_test(&map->usercnt)) {
717 if (map->ops->map_release_uref)
718 map->ops->map_release_uref(map);
722 /* decrement map refcnt and schedule it for freeing via workqueue
723 * (underlying map implementation ops->map_free() might sleep)
725 void bpf_map_put(struct bpf_map *map)
727 if (atomic64_dec_and_test(&map->refcnt)) {
728 /* bpf_map_free_id() must be called first */
729 bpf_map_free_id(map);
731 INIT_WORK(&map->work, bpf_map_free_deferred);
732 /* Avoid spawning kworkers, since they all might contend
733 * for the same mutex like slab_mutex.
735 queue_work(system_unbound_wq, &map->work);
738 EXPORT_SYMBOL_GPL(bpf_map_put);
740 void bpf_map_put_with_uref(struct bpf_map *map)
742 bpf_map_put_uref(map);
746 static int bpf_map_release(struct inode *inode, struct file *filp)
748 struct bpf_map *map = filp->private_data;
750 if (map->ops->map_release)
751 map->ops->map_release(map, filp);
753 bpf_map_put_with_uref(map);
757 static fmode_t map_get_sys_perms(struct bpf_map *map, struct fd f)
759 fmode_t mode = f.file->f_mode;
761 /* Our file permissions may have been overridden by global
762 * map permissions facing syscall side.
764 if (READ_ONCE(map->frozen))
765 mode &= ~FMODE_CAN_WRITE;
769 #ifdef CONFIG_PROC_FS
770 /* Show the memory usage of a bpf map */
771 static u64 bpf_map_memory_usage(const struct bpf_map *map)
773 return map->ops->map_mem_usage(map);
776 static void bpf_map_show_fdinfo(struct seq_file *m, struct file *filp)
778 struct bpf_map *map = filp->private_data;
779 u32 type = 0, jited = 0;
781 if (map_type_contains_progs(map)) {
782 spin_lock(&map->owner.lock);
783 type = map->owner.type;
784 jited = map->owner.jited;
785 spin_unlock(&map->owner.lock);
794 "map_extra:\t%#llx\n"
803 (unsigned long long)map->map_extra,
804 bpf_map_memory_usage(map),
806 READ_ONCE(map->frozen));
808 seq_printf(m, "owner_prog_type:\t%u\n", type);
809 seq_printf(m, "owner_jited:\t%u\n", jited);
814 static ssize_t bpf_dummy_read(struct file *filp, char __user *buf, size_t siz,
817 /* We need this handler such that alloc_file() enables
818 * f_mode with FMODE_CAN_READ.
823 static ssize_t bpf_dummy_write(struct file *filp, const char __user *buf,
824 size_t siz, loff_t *ppos)
826 /* We need this handler such that alloc_file() enables
827 * f_mode with FMODE_CAN_WRITE.
832 /* called for any extra memory-mapped regions (except initial) */
833 static void bpf_map_mmap_open(struct vm_area_struct *vma)
835 struct bpf_map *map = vma->vm_file->private_data;
837 if (vma->vm_flags & VM_MAYWRITE)
838 bpf_map_write_active_inc(map);
841 /* called for all unmapped memory region (including initial) */
842 static void bpf_map_mmap_close(struct vm_area_struct *vma)
844 struct bpf_map *map = vma->vm_file->private_data;
846 if (vma->vm_flags & VM_MAYWRITE)
847 bpf_map_write_active_dec(map);
850 static const struct vm_operations_struct bpf_map_default_vmops = {
851 .open = bpf_map_mmap_open,
852 .close = bpf_map_mmap_close,
855 static int bpf_map_mmap(struct file *filp, struct vm_area_struct *vma)
857 struct bpf_map *map = filp->private_data;
860 if (!map->ops->map_mmap || !IS_ERR_OR_NULL(map->record))
863 if (!(vma->vm_flags & VM_SHARED))
866 mutex_lock(&map->freeze_mutex);
868 if (vma->vm_flags & VM_WRITE) {
873 /* map is meant to be read-only, so do not allow mapping as
874 * writable, because it's possible to leak a writable page
875 * reference and allows user-space to still modify it after
876 * freezing, while verifier will assume contents do not change
878 if (map->map_flags & BPF_F_RDONLY_PROG) {
884 /* set default open/close callbacks */
885 vma->vm_ops = &bpf_map_default_vmops;
886 vma->vm_private_data = map;
887 vm_flags_clear(vma, VM_MAYEXEC);
888 if (!(vma->vm_flags & VM_WRITE))
889 /* disallow re-mapping with PROT_WRITE */
890 vm_flags_clear(vma, VM_MAYWRITE);
892 err = map->ops->map_mmap(map, vma);
896 if (vma->vm_flags & VM_MAYWRITE)
897 bpf_map_write_active_inc(map);
899 mutex_unlock(&map->freeze_mutex);
903 static __poll_t bpf_map_poll(struct file *filp, struct poll_table_struct *pts)
905 struct bpf_map *map = filp->private_data;
907 if (map->ops->map_poll)
908 return map->ops->map_poll(map, filp, pts);
913 const struct file_operations bpf_map_fops = {
914 #ifdef CONFIG_PROC_FS
915 .show_fdinfo = bpf_map_show_fdinfo,
917 .release = bpf_map_release,
918 .read = bpf_dummy_read,
919 .write = bpf_dummy_write,
920 .mmap = bpf_map_mmap,
921 .poll = bpf_map_poll,
924 int bpf_map_new_fd(struct bpf_map *map, int flags)
928 ret = security_bpf_map(map, OPEN_FMODE(flags));
932 return anon_inode_getfd("bpf-map", &bpf_map_fops, map,
936 int bpf_get_file_flag(int flags)
938 if ((flags & BPF_F_RDONLY) && (flags & BPF_F_WRONLY))
940 if (flags & BPF_F_RDONLY)
942 if (flags & BPF_F_WRONLY)
947 /* helper macro to check that unused fields 'union bpf_attr' are zero */
948 #define CHECK_ATTR(CMD) \
949 memchr_inv((void *) &attr->CMD##_LAST_FIELD + \
950 sizeof(attr->CMD##_LAST_FIELD), 0, \
952 offsetof(union bpf_attr, CMD##_LAST_FIELD) - \
953 sizeof(attr->CMD##_LAST_FIELD)) != NULL
955 /* dst and src must have at least "size" number of bytes.
956 * Return strlen on success and < 0 on error.
958 int bpf_obj_name_cpy(char *dst, const char *src, unsigned int size)
960 const char *end = src + size;
961 const char *orig_src = src;
963 memset(dst, 0, size);
964 /* Copy all isalnum(), '_' and '.' chars. */
965 while (src < end && *src) {
966 if (!isalnum(*src) &&
967 *src != '_' && *src != '.')
972 /* No '\0' found in "size" number of bytes */
976 return src - orig_src;
979 int map_check_no_btf(const struct bpf_map *map,
980 const struct btf *btf,
981 const struct btf_type *key_type,
982 const struct btf_type *value_type)
987 static int map_check_btf(struct bpf_map *map, const struct btf *btf,
988 u32 btf_key_id, u32 btf_value_id)
990 const struct btf_type *key_type, *value_type;
991 u32 key_size, value_size;
994 /* Some maps allow key to be unspecified. */
996 key_type = btf_type_id_size(btf, &btf_key_id, &key_size);
997 if (!key_type || key_size != map->key_size)
1000 key_type = btf_type_by_id(btf, 0);
1001 if (!map->ops->map_check_btf)
1005 value_type = btf_type_id_size(btf, &btf_value_id, &value_size);
1006 if (!value_type || value_size != map->value_size)
1009 map->record = btf_parse_fields(btf, value_type,
1010 BPF_SPIN_LOCK | BPF_TIMER | BPF_KPTR | BPF_LIST_HEAD |
1011 BPF_RB_ROOT | BPF_REFCOUNT,
1013 if (!IS_ERR_OR_NULL(map->record)) {
1016 if (!bpf_capable()) {
1020 if (map->map_flags & (BPF_F_RDONLY_PROG | BPF_F_WRONLY_PROG)) {
1024 for (i = 0; i < sizeof(map->record->field_mask) * 8; i++) {
1025 switch (map->record->field_mask & (1 << i)) {
1029 if (map->map_type != BPF_MAP_TYPE_HASH &&
1030 map->map_type != BPF_MAP_TYPE_ARRAY &&
1031 map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
1032 map->map_type != BPF_MAP_TYPE_SK_STORAGE &&
1033 map->map_type != BPF_MAP_TYPE_INODE_STORAGE &&
1034 map->map_type != BPF_MAP_TYPE_TASK_STORAGE &&
1035 map->map_type != BPF_MAP_TYPE_CGRP_STORAGE) {
1041 if (map->map_type != BPF_MAP_TYPE_HASH &&
1042 map->map_type != BPF_MAP_TYPE_LRU_HASH &&
1043 map->map_type != BPF_MAP_TYPE_ARRAY) {
1048 case BPF_KPTR_UNREF:
1050 case BPF_KPTR_PERCPU:
1052 if (map->map_type != BPF_MAP_TYPE_HASH &&
1053 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
1054 map->map_type != BPF_MAP_TYPE_LRU_HASH &&
1055 map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH &&
1056 map->map_type != BPF_MAP_TYPE_ARRAY &&
1057 map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
1058 map->map_type != BPF_MAP_TYPE_SK_STORAGE &&
1059 map->map_type != BPF_MAP_TYPE_INODE_STORAGE &&
1060 map->map_type != BPF_MAP_TYPE_TASK_STORAGE &&
1061 map->map_type != BPF_MAP_TYPE_CGRP_STORAGE) {
1068 if (map->map_type != BPF_MAP_TYPE_HASH &&
1069 map->map_type != BPF_MAP_TYPE_LRU_HASH &&
1070 map->map_type != BPF_MAP_TYPE_ARRAY) {
1076 /* Fail if map_type checks are missing for a field type */
1083 ret = btf_check_and_fixup_fields(btf, map->record);
1087 if (map->ops->map_check_btf) {
1088 ret = map->ops->map_check_btf(map, btf, key_type, value_type);
1095 bpf_map_free_record(map);
1099 #define BPF_MAP_CREATE_LAST_FIELD map_extra
1100 /* called via syscall */
1101 static int map_create(union bpf_attr *attr)
1103 const struct bpf_map_ops *ops;
1104 int numa_node = bpf_map_attr_numa_node(attr);
1105 u32 map_type = attr->map_type;
1106 struct bpf_map *map;
1110 err = CHECK_ATTR(BPF_MAP_CREATE);
1114 if (attr->btf_vmlinux_value_type_id) {
1115 if (attr->map_type != BPF_MAP_TYPE_STRUCT_OPS ||
1116 attr->btf_key_type_id || attr->btf_value_type_id)
1118 } else if (attr->btf_key_type_id && !attr->btf_value_type_id) {
1122 if (attr->map_type != BPF_MAP_TYPE_BLOOM_FILTER &&
1123 attr->map_extra != 0)
1126 f_flags = bpf_get_file_flag(attr->map_flags);
1130 if (numa_node != NUMA_NO_NODE &&
1131 ((unsigned int)numa_node >= nr_node_ids ||
1132 !node_online(numa_node)))
1135 /* find map type and init map: hashtable vs rbtree vs bloom vs ... */
1136 map_type = attr->map_type;
1137 if (map_type >= ARRAY_SIZE(bpf_map_types))
1139 map_type = array_index_nospec(map_type, ARRAY_SIZE(bpf_map_types));
1140 ops = bpf_map_types[map_type];
1144 if (ops->map_alloc_check) {
1145 err = ops->map_alloc_check(attr);
1149 if (attr->map_ifindex)
1150 ops = &bpf_map_offload_ops;
1151 if (!ops->map_mem_usage)
1154 /* Intent here is for unprivileged_bpf_disabled to block BPF map
1155 * creation for unprivileged users; other actions depend
1156 * on fd availability and access to bpffs, so are dependent on
1157 * object creation success. Even with unprivileged BPF disabled,
1158 * capability checks are still carried out.
1160 if (sysctl_unprivileged_bpf_disabled && !bpf_capable())
1163 /* check privileged map type permissions */
1165 case BPF_MAP_TYPE_ARRAY:
1166 case BPF_MAP_TYPE_PERCPU_ARRAY:
1167 case BPF_MAP_TYPE_PROG_ARRAY:
1168 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
1169 case BPF_MAP_TYPE_CGROUP_ARRAY:
1170 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
1171 case BPF_MAP_TYPE_HASH:
1172 case BPF_MAP_TYPE_PERCPU_HASH:
1173 case BPF_MAP_TYPE_HASH_OF_MAPS:
1174 case BPF_MAP_TYPE_RINGBUF:
1175 case BPF_MAP_TYPE_USER_RINGBUF:
1176 case BPF_MAP_TYPE_CGROUP_STORAGE:
1177 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
1180 case BPF_MAP_TYPE_SK_STORAGE:
1181 case BPF_MAP_TYPE_INODE_STORAGE:
1182 case BPF_MAP_TYPE_TASK_STORAGE:
1183 case BPF_MAP_TYPE_CGRP_STORAGE:
1184 case BPF_MAP_TYPE_BLOOM_FILTER:
1185 case BPF_MAP_TYPE_LPM_TRIE:
1186 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
1187 case BPF_MAP_TYPE_STACK_TRACE:
1188 case BPF_MAP_TYPE_QUEUE:
1189 case BPF_MAP_TYPE_STACK:
1190 case BPF_MAP_TYPE_LRU_HASH:
1191 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
1192 case BPF_MAP_TYPE_STRUCT_OPS:
1193 case BPF_MAP_TYPE_CPUMAP:
1197 case BPF_MAP_TYPE_SOCKMAP:
1198 case BPF_MAP_TYPE_SOCKHASH:
1199 case BPF_MAP_TYPE_DEVMAP:
1200 case BPF_MAP_TYPE_DEVMAP_HASH:
1201 case BPF_MAP_TYPE_XSKMAP:
1202 if (!capable(CAP_NET_ADMIN))
1206 WARN(1, "unsupported map type %d", map_type);
1210 map = ops->map_alloc(attr);
1212 return PTR_ERR(map);
1214 map->map_type = map_type;
1216 err = bpf_obj_name_cpy(map->name, attr->map_name,
1217 sizeof(attr->map_name));
1221 atomic64_set(&map->refcnt, 1);
1222 atomic64_set(&map->usercnt, 1);
1223 mutex_init(&map->freeze_mutex);
1224 spin_lock_init(&map->owner.lock);
1226 if (attr->btf_key_type_id || attr->btf_value_type_id ||
1227 /* Even the map's value is a kernel's struct,
1228 * the bpf_prog.o must have BTF to begin with
1229 * to figure out the corresponding kernel's
1230 * counter part. Thus, attr->btf_fd has
1233 attr->btf_vmlinux_value_type_id) {
1236 btf = btf_get_by_fd(attr->btf_fd);
1241 if (btf_is_kernel(btf)) {
1248 if (attr->btf_value_type_id) {
1249 err = map_check_btf(map, btf, attr->btf_key_type_id,
1250 attr->btf_value_type_id);
1255 map->btf_key_type_id = attr->btf_key_type_id;
1256 map->btf_value_type_id = attr->btf_value_type_id;
1257 map->btf_vmlinux_value_type_id =
1258 attr->btf_vmlinux_value_type_id;
1261 err = security_bpf_map_alloc(map);
1265 err = bpf_map_alloc_id(map);
1269 bpf_map_save_memcg(map);
1271 err = bpf_map_new_fd(map, f_flags);
1273 /* failed to allocate fd.
1274 * bpf_map_put_with_uref() is needed because the above
1275 * bpf_map_alloc_id() has published the map
1276 * to the userspace and the userspace may
1277 * have refcnt-ed it through BPF_MAP_GET_FD_BY_ID.
1279 bpf_map_put_with_uref(map);
1286 security_bpf_map_free(map);
1289 map->ops->map_free(map);
1293 /* if error is returned, fd is released.
1294 * On success caller should complete fd access with matching fdput()
1296 struct bpf_map *__bpf_map_get(struct fd f)
1299 return ERR_PTR(-EBADF);
1300 if (f.file->f_op != &bpf_map_fops) {
1302 return ERR_PTR(-EINVAL);
1305 return f.file->private_data;
1308 void bpf_map_inc(struct bpf_map *map)
1310 atomic64_inc(&map->refcnt);
1312 EXPORT_SYMBOL_GPL(bpf_map_inc);
1314 void bpf_map_inc_with_uref(struct bpf_map *map)
1316 atomic64_inc(&map->refcnt);
1317 atomic64_inc(&map->usercnt);
1319 EXPORT_SYMBOL_GPL(bpf_map_inc_with_uref);
1321 struct bpf_map *bpf_map_get(u32 ufd)
1323 struct fd f = fdget(ufd);
1324 struct bpf_map *map;
1326 map = __bpf_map_get(f);
1335 EXPORT_SYMBOL(bpf_map_get);
1337 struct bpf_map *bpf_map_get_with_uref(u32 ufd)
1339 struct fd f = fdget(ufd);
1340 struct bpf_map *map;
1342 map = __bpf_map_get(f);
1346 bpf_map_inc_with_uref(map);
1352 /* map_idr_lock should have been held or the map should have been
1353 * protected by rcu read lock.
1355 struct bpf_map *__bpf_map_inc_not_zero(struct bpf_map *map, bool uref)
1359 refold = atomic64_fetch_add_unless(&map->refcnt, 1, 0);
1361 return ERR_PTR(-ENOENT);
1363 atomic64_inc(&map->usercnt);
1368 struct bpf_map *bpf_map_inc_not_zero(struct bpf_map *map)
1370 spin_lock_bh(&map_idr_lock);
1371 map = __bpf_map_inc_not_zero(map, false);
1372 spin_unlock_bh(&map_idr_lock);
1376 EXPORT_SYMBOL_GPL(bpf_map_inc_not_zero);
1378 int __weak bpf_stackmap_copy(struct bpf_map *map, void *key, void *value)
1383 static void *__bpf_copy_key(void __user *ukey, u64 key_size)
1386 return vmemdup_user(ukey, key_size);
1389 return ERR_PTR(-EINVAL);
1394 static void *___bpf_copy_key(bpfptr_t ukey, u64 key_size)
1397 return kvmemdup_bpfptr(ukey, key_size);
1399 if (!bpfptr_is_null(ukey))
1400 return ERR_PTR(-EINVAL);
1405 /* last field in 'union bpf_attr' used by this command */
1406 #define BPF_MAP_LOOKUP_ELEM_LAST_FIELD flags
1408 static int map_lookup_elem(union bpf_attr *attr)
1410 void __user *ukey = u64_to_user_ptr(attr->key);
1411 void __user *uvalue = u64_to_user_ptr(attr->value);
1412 int ufd = attr->map_fd;
1413 struct bpf_map *map;
1419 if (CHECK_ATTR(BPF_MAP_LOOKUP_ELEM))
1422 if (attr->flags & ~BPF_F_LOCK)
1426 map = __bpf_map_get(f);
1428 return PTR_ERR(map);
1429 if (!(map_get_sys_perms(map, f) & FMODE_CAN_READ)) {
1434 if ((attr->flags & BPF_F_LOCK) &&
1435 !btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
1440 key = __bpf_copy_key(ukey, map->key_size);
1446 value_size = bpf_map_value_size(map);
1449 value = kvmalloc(value_size, GFP_USER | __GFP_NOWARN);
1453 if (map->map_type == BPF_MAP_TYPE_BLOOM_FILTER) {
1454 if (copy_from_user(value, uvalue, value_size))
1457 err = bpf_map_copy_value(map, key, value, attr->flags);
1461 err = bpf_map_copy_value(map, key, value, attr->flags);
1466 if (copy_to_user(uvalue, value, value_size) != 0)
1481 #define BPF_MAP_UPDATE_ELEM_LAST_FIELD flags
1483 static int map_update_elem(union bpf_attr *attr, bpfptr_t uattr)
1485 bpfptr_t ukey = make_bpfptr(attr->key, uattr.is_kernel);
1486 bpfptr_t uvalue = make_bpfptr(attr->value, uattr.is_kernel);
1487 int ufd = attr->map_fd;
1488 struct bpf_map *map;
1494 if (CHECK_ATTR(BPF_MAP_UPDATE_ELEM))
1498 map = __bpf_map_get(f);
1500 return PTR_ERR(map);
1501 bpf_map_write_active_inc(map);
1502 if (!(map_get_sys_perms(map, f) & FMODE_CAN_WRITE)) {
1507 if ((attr->flags & BPF_F_LOCK) &&
1508 !btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
1513 key = ___bpf_copy_key(ukey, map->key_size);
1519 value_size = bpf_map_value_size(map);
1520 value = kvmemdup_bpfptr(uvalue, value_size);
1521 if (IS_ERR(value)) {
1522 err = PTR_ERR(value);
1526 err = bpf_map_update_value(map, f.file, key, value, attr->flags);
1532 bpf_map_write_active_dec(map);
1537 #define BPF_MAP_DELETE_ELEM_LAST_FIELD key
1539 static int map_delete_elem(union bpf_attr *attr, bpfptr_t uattr)
1541 bpfptr_t ukey = make_bpfptr(attr->key, uattr.is_kernel);
1542 int ufd = attr->map_fd;
1543 struct bpf_map *map;
1548 if (CHECK_ATTR(BPF_MAP_DELETE_ELEM))
1552 map = __bpf_map_get(f);
1554 return PTR_ERR(map);
1555 bpf_map_write_active_inc(map);
1556 if (!(map_get_sys_perms(map, f) & FMODE_CAN_WRITE)) {
1561 key = ___bpf_copy_key(ukey, map->key_size);
1567 if (bpf_map_is_offloaded(map)) {
1568 err = bpf_map_offload_delete_elem(map, key);
1570 } else if (IS_FD_PROG_ARRAY(map) ||
1571 map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
1572 /* These maps require sleepable context */
1573 err = map->ops->map_delete_elem(map, key);
1577 bpf_disable_instrumentation();
1579 err = map->ops->map_delete_elem(map, key);
1581 bpf_enable_instrumentation();
1582 maybe_wait_bpf_programs(map);
1586 bpf_map_write_active_dec(map);
1591 /* last field in 'union bpf_attr' used by this command */
1592 #define BPF_MAP_GET_NEXT_KEY_LAST_FIELD next_key
1594 static int map_get_next_key(union bpf_attr *attr)
1596 void __user *ukey = u64_to_user_ptr(attr->key);
1597 void __user *unext_key = u64_to_user_ptr(attr->next_key);
1598 int ufd = attr->map_fd;
1599 struct bpf_map *map;
1600 void *key, *next_key;
1604 if (CHECK_ATTR(BPF_MAP_GET_NEXT_KEY))
1608 map = __bpf_map_get(f);
1610 return PTR_ERR(map);
1611 if (!(map_get_sys_perms(map, f) & FMODE_CAN_READ)) {
1617 key = __bpf_copy_key(ukey, map->key_size);
1627 next_key = kvmalloc(map->key_size, GFP_USER);
1631 if (bpf_map_is_offloaded(map)) {
1632 err = bpf_map_offload_get_next_key(map, key, next_key);
1637 err = map->ops->map_get_next_key(map, key, next_key);
1644 if (copy_to_user(unext_key, next_key, map->key_size) != 0)
1658 int generic_map_delete_batch(struct bpf_map *map,
1659 const union bpf_attr *attr,
1660 union bpf_attr __user *uattr)
1662 void __user *keys = u64_to_user_ptr(attr->batch.keys);
1667 if (attr->batch.elem_flags & ~BPF_F_LOCK)
1670 if ((attr->batch.elem_flags & BPF_F_LOCK) &&
1671 !btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
1675 max_count = attr->batch.count;
1679 key = kvmalloc(map->key_size, GFP_USER | __GFP_NOWARN);
1683 for (cp = 0; cp < max_count; cp++) {
1685 if (copy_from_user(key, keys + cp * map->key_size,
1689 if (bpf_map_is_offloaded(map)) {
1690 err = bpf_map_offload_delete_elem(map, key);
1694 bpf_disable_instrumentation();
1696 err = map->ops->map_delete_elem(map, key);
1698 bpf_enable_instrumentation();
1703 if (copy_to_user(&uattr->batch.count, &cp, sizeof(cp)))
1708 maybe_wait_bpf_programs(map);
1712 int generic_map_update_batch(struct bpf_map *map, struct file *map_file,
1713 const union bpf_attr *attr,
1714 union bpf_attr __user *uattr)
1716 void __user *values = u64_to_user_ptr(attr->batch.values);
1717 void __user *keys = u64_to_user_ptr(attr->batch.keys);
1718 u32 value_size, cp, max_count;
1722 if (attr->batch.elem_flags & ~BPF_F_LOCK)
1725 if ((attr->batch.elem_flags & BPF_F_LOCK) &&
1726 !btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
1730 value_size = bpf_map_value_size(map);
1732 max_count = attr->batch.count;
1736 key = kvmalloc(map->key_size, GFP_USER | __GFP_NOWARN);
1740 value = kvmalloc(value_size, GFP_USER | __GFP_NOWARN);
1746 for (cp = 0; cp < max_count; cp++) {
1748 if (copy_from_user(key, keys + cp * map->key_size,
1750 copy_from_user(value, values + cp * value_size, value_size))
1753 err = bpf_map_update_value(map, map_file, key, value,
1754 attr->batch.elem_flags);
1761 if (copy_to_user(&uattr->batch.count, &cp, sizeof(cp)))
1769 #define MAP_LOOKUP_RETRIES 3
1771 int generic_map_lookup_batch(struct bpf_map *map,
1772 const union bpf_attr *attr,
1773 union bpf_attr __user *uattr)
1775 void __user *uobatch = u64_to_user_ptr(attr->batch.out_batch);
1776 void __user *ubatch = u64_to_user_ptr(attr->batch.in_batch);
1777 void __user *values = u64_to_user_ptr(attr->batch.values);
1778 void __user *keys = u64_to_user_ptr(attr->batch.keys);
1779 void *buf, *buf_prevkey, *prev_key, *key, *value;
1780 int err, retry = MAP_LOOKUP_RETRIES;
1781 u32 value_size, cp, max_count;
1783 if (attr->batch.elem_flags & ~BPF_F_LOCK)
1786 if ((attr->batch.elem_flags & BPF_F_LOCK) &&
1787 !btf_record_has_field(map->record, BPF_SPIN_LOCK))
1790 value_size = bpf_map_value_size(map);
1792 max_count = attr->batch.count;
1796 if (put_user(0, &uattr->batch.count))
1799 buf_prevkey = kvmalloc(map->key_size, GFP_USER | __GFP_NOWARN);
1803 buf = kvmalloc(map->key_size + value_size, GFP_USER | __GFP_NOWARN);
1805 kvfree(buf_prevkey);
1811 if (ubatch && copy_from_user(buf_prevkey, ubatch, map->key_size))
1814 value = key + map->key_size;
1816 prev_key = buf_prevkey;
1818 for (cp = 0; cp < max_count;) {
1820 err = map->ops->map_get_next_key(map, prev_key, key);
1824 err = bpf_map_copy_value(map, key, value,
1825 attr->batch.elem_flags);
1827 if (err == -ENOENT) {
1839 if (copy_to_user(keys + cp * map->key_size, key,
1844 if (copy_to_user(values + cp * value_size, value, value_size)) {
1850 prev_key = buf_prevkey;
1852 swap(prev_key, key);
1853 retry = MAP_LOOKUP_RETRIES;
1861 if ((copy_to_user(&uattr->batch.count, &cp, sizeof(cp)) ||
1862 (cp && copy_to_user(uobatch, prev_key, map->key_size))))
1866 kvfree(buf_prevkey);
1871 #define BPF_MAP_LOOKUP_AND_DELETE_ELEM_LAST_FIELD flags
1873 static int map_lookup_and_delete_elem(union bpf_attr *attr)
1875 void __user *ukey = u64_to_user_ptr(attr->key);
1876 void __user *uvalue = u64_to_user_ptr(attr->value);
1877 int ufd = attr->map_fd;
1878 struct bpf_map *map;
1884 if (CHECK_ATTR(BPF_MAP_LOOKUP_AND_DELETE_ELEM))
1887 if (attr->flags & ~BPF_F_LOCK)
1891 map = __bpf_map_get(f);
1893 return PTR_ERR(map);
1894 bpf_map_write_active_inc(map);
1895 if (!(map_get_sys_perms(map, f) & FMODE_CAN_READ) ||
1896 !(map_get_sys_perms(map, f) & FMODE_CAN_WRITE)) {
1902 (map->map_type == BPF_MAP_TYPE_QUEUE ||
1903 map->map_type == BPF_MAP_TYPE_STACK)) {
1908 if ((attr->flags & BPF_F_LOCK) &&
1909 !btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
1914 key = __bpf_copy_key(ukey, map->key_size);
1920 value_size = bpf_map_value_size(map);
1923 value = kvmalloc(value_size, GFP_USER | __GFP_NOWARN);
1928 if (map->map_type == BPF_MAP_TYPE_QUEUE ||
1929 map->map_type == BPF_MAP_TYPE_STACK) {
1930 err = map->ops->map_pop_elem(map, value);
1931 } else if (map->map_type == BPF_MAP_TYPE_HASH ||
1932 map->map_type == BPF_MAP_TYPE_PERCPU_HASH ||
1933 map->map_type == BPF_MAP_TYPE_LRU_HASH ||
1934 map->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH) {
1935 if (!bpf_map_is_offloaded(map)) {
1936 bpf_disable_instrumentation();
1938 err = map->ops->map_lookup_and_delete_elem(map, key, value, attr->flags);
1940 bpf_enable_instrumentation();
1947 if (copy_to_user(uvalue, value, value_size) != 0) {
1959 bpf_map_write_active_dec(map);
1964 #define BPF_MAP_FREEZE_LAST_FIELD map_fd
1966 static int map_freeze(const union bpf_attr *attr)
1968 int err = 0, ufd = attr->map_fd;
1969 struct bpf_map *map;
1972 if (CHECK_ATTR(BPF_MAP_FREEZE))
1976 map = __bpf_map_get(f);
1978 return PTR_ERR(map);
1980 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS || !IS_ERR_OR_NULL(map->record)) {
1985 if (!(map_get_sys_perms(map, f) & FMODE_CAN_WRITE)) {
1990 mutex_lock(&map->freeze_mutex);
1991 if (bpf_map_write_active(map)) {
1995 if (READ_ONCE(map->frozen)) {
2000 WRITE_ONCE(map->frozen, true);
2002 mutex_unlock(&map->freeze_mutex);
2007 static const struct bpf_prog_ops * const bpf_prog_types[] = {
2008 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
2009 [_id] = & _name ## _prog_ops,
2010 #define BPF_MAP_TYPE(_id, _ops)
2011 #define BPF_LINK_TYPE(_id, _name)
2012 #include <linux/bpf_types.h>
2013 #undef BPF_PROG_TYPE
2015 #undef BPF_LINK_TYPE
2018 static int find_prog_type(enum bpf_prog_type type, struct bpf_prog *prog)
2020 const struct bpf_prog_ops *ops;
2022 if (type >= ARRAY_SIZE(bpf_prog_types))
2024 type = array_index_nospec(type, ARRAY_SIZE(bpf_prog_types));
2025 ops = bpf_prog_types[type];
2029 if (!bpf_prog_is_offloaded(prog->aux))
2030 prog->aux->ops = ops;
2032 prog->aux->ops = &bpf_offload_prog_ops;
2043 static const char * const bpf_audit_str[BPF_AUDIT_MAX] = {
2044 [BPF_AUDIT_LOAD] = "LOAD",
2045 [BPF_AUDIT_UNLOAD] = "UNLOAD",
2048 static void bpf_audit_prog(const struct bpf_prog *prog, unsigned int op)
2050 struct audit_context *ctx = NULL;
2051 struct audit_buffer *ab;
2053 if (WARN_ON_ONCE(op >= BPF_AUDIT_MAX))
2055 if (audit_enabled == AUDIT_OFF)
2057 if (!in_irq() && !irqs_disabled())
2058 ctx = audit_context();
2059 ab = audit_log_start(ctx, GFP_ATOMIC, AUDIT_BPF);
2062 audit_log_format(ab, "prog-id=%u op=%s",
2063 prog->aux->id, bpf_audit_str[op]);
2067 static int bpf_prog_alloc_id(struct bpf_prog *prog)
2071 idr_preload(GFP_KERNEL);
2072 spin_lock_bh(&prog_idr_lock);
2073 id = idr_alloc_cyclic(&prog_idr, prog, 1, INT_MAX, GFP_ATOMIC);
2076 spin_unlock_bh(&prog_idr_lock);
2079 /* id is in [1, INT_MAX) */
2080 if (WARN_ON_ONCE(!id))
2083 return id > 0 ? 0 : id;
2086 void bpf_prog_free_id(struct bpf_prog *prog)
2088 unsigned long flags;
2090 /* cBPF to eBPF migrations are currently not in the idr store.
2091 * Offloaded programs are removed from the store when their device
2092 * disappears - even if someone grabs an fd to them they are unusable,
2093 * simply waiting for refcnt to drop to be freed.
2098 spin_lock_irqsave(&prog_idr_lock, flags);
2099 idr_remove(&prog_idr, prog->aux->id);
2101 spin_unlock_irqrestore(&prog_idr_lock, flags);
2104 static void __bpf_prog_put_rcu(struct rcu_head *rcu)
2106 struct bpf_prog_aux *aux = container_of(rcu, struct bpf_prog_aux, rcu);
2108 kvfree(aux->func_info);
2109 kfree(aux->func_info_aux);
2110 free_uid(aux->user);
2111 security_bpf_prog_free(aux);
2112 bpf_prog_free(aux->prog);
2115 static void __bpf_prog_put_noref(struct bpf_prog *prog, bool deferred)
2117 bpf_prog_kallsyms_del_all(prog);
2118 btf_put(prog->aux->btf);
2119 module_put(prog->aux->mod);
2120 kvfree(prog->aux->jited_linfo);
2121 kvfree(prog->aux->linfo);
2122 kfree(prog->aux->kfunc_tab);
2123 if (prog->aux->attach_btf)
2124 btf_put(prog->aux->attach_btf);
2127 if (prog->aux->sleepable)
2128 call_rcu_tasks_trace(&prog->aux->rcu, __bpf_prog_put_rcu);
2130 call_rcu(&prog->aux->rcu, __bpf_prog_put_rcu);
2132 __bpf_prog_put_rcu(&prog->aux->rcu);
2136 static void bpf_prog_put_deferred(struct work_struct *work)
2138 struct bpf_prog_aux *aux;
2139 struct bpf_prog *prog;
2141 aux = container_of(work, struct bpf_prog_aux, work);
2143 perf_event_bpf_event(prog, PERF_BPF_EVENT_PROG_UNLOAD, 0);
2144 bpf_audit_prog(prog, BPF_AUDIT_UNLOAD);
2145 bpf_prog_free_id(prog);
2146 __bpf_prog_put_noref(prog, true);
2149 static void __bpf_prog_put(struct bpf_prog *prog)
2151 struct bpf_prog_aux *aux = prog->aux;
2153 if (atomic64_dec_and_test(&aux->refcnt)) {
2154 if (in_irq() || irqs_disabled()) {
2155 INIT_WORK(&aux->work, bpf_prog_put_deferred);
2156 schedule_work(&aux->work);
2158 bpf_prog_put_deferred(&aux->work);
2163 void bpf_prog_put(struct bpf_prog *prog)
2165 __bpf_prog_put(prog);
2167 EXPORT_SYMBOL_GPL(bpf_prog_put);
2169 static int bpf_prog_release(struct inode *inode, struct file *filp)
2171 struct bpf_prog *prog = filp->private_data;
2177 struct bpf_prog_kstats {
2183 void notrace bpf_prog_inc_misses_counter(struct bpf_prog *prog)
2185 struct bpf_prog_stats *stats;
2188 stats = this_cpu_ptr(prog->stats);
2189 flags = u64_stats_update_begin_irqsave(&stats->syncp);
2190 u64_stats_inc(&stats->misses);
2191 u64_stats_update_end_irqrestore(&stats->syncp, flags);
2194 static void bpf_prog_get_stats(const struct bpf_prog *prog,
2195 struct bpf_prog_kstats *stats)
2197 u64 nsecs = 0, cnt = 0, misses = 0;
2200 for_each_possible_cpu(cpu) {
2201 const struct bpf_prog_stats *st;
2203 u64 tnsecs, tcnt, tmisses;
2205 st = per_cpu_ptr(prog->stats, cpu);
2207 start = u64_stats_fetch_begin(&st->syncp);
2208 tnsecs = u64_stats_read(&st->nsecs);
2209 tcnt = u64_stats_read(&st->cnt);
2210 tmisses = u64_stats_read(&st->misses);
2211 } while (u64_stats_fetch_retry(&st->syncp, start));
2216 stats->nsecs = nsecs;
2218 stats->misses = misses;
2221 #ifdef CONFIG_PROC_FS
2222 static void bpf_prog_show_fdinfo(struct seq_file *m, struct file *filp)
2224 const struct bpf_prog *prog = filp->private_data;
2225 char prog_tag[sizeof(prog->tag) * 2 + 1] = { };
2226 struct bpf_prog_kstats stats;
2228 bpf_prog_get_stats(prog, &stats);
2229 bin2hex(prog_tag, prog->tag, sizeof(prog->tag));
2236 "run_time_ns:\t%llu\n"
2238 "recursion_misses:\t%llu\n"
2239 "verified_insns:\t%u\n",
2243 prog->pages * 1ULL << PAGE_SHIFT,
2248 prog->aux->verified_insns);
2252 const struct file_operations bpf_prog_fops = {
2253 #ifdef CONFIG_PROC_FS
2254 .show_fdinfo = bpf_prog_show_fdinfo,
2256 .release = bpf_prog_release,
2257 .read = bpf_dummy_read,
2258 .write = bpf_dummy_write,
2261 int bpf_prog_new_fd(struct bpf_prog *prog)
2265 ret = security_bpf_prog(prog);
2269 return anon_inode_getfd("bpf-prog", &bpf_prog_fops, prog,
2270 O_RDWR | O_CLOEXEC);
2273 static struct bpf_prog *____bpf_prog_get(struct fd f)
2276 return ERR_PTR(-EBADF);
2277 if (f.file->f_op != &bpf_prog_fops) {
2279 return ERR_PTR(-EINVAL);
2282 return f.file->private_data;
2285 void bpf_prog_add(struct bpf_prog *prog, int i)
2287 atomic64_add(i, &prog->aux->refcnt);
2289 EXPORT_SYMBOL_GPL(bpf_prog_add);
2291 void bpf_prog_sub(struct bpf_prog *prog, int i)
2293 /* Only to be used for undoing previous bpf_prog_add() in some
2294 * error path. We still know that another entity in our call
2295 * path holds a reference to the program, thus atomic_sub() can
2296 * be safely used in such cases!
2298 WARN_ON(atomic64_sub_return(i, &prog->aux->refcnt) == 0);
2300 EXPORT_SYMBOL_GPL(bpf_prog_sub);
2302 void bpf_prog_inc(struct bpf_prog *prog)
2304 atomic64_inc(&prog->aux->refcnt);
2306 EXPORT_SYMBOL_GPL(bpf_prog_inc);
2308 /* prog_idr_lock should have been held */
2309 struct bpf_prog *bpf_prog_inc_not_zero(struct bpf_prog *prog)
2313 refold = atomic64_fetch_add_unless(&prog->aux->refcnt, 1, 0);
2316 return ERR_PTR(-ENOENT);
2320 EXPORT_SYMBOL_GPL(bpf_prog_inc_not_zero);
2322 bool bpf_prog_get_ok(struct bpf_prog *prog,
2323 enum bpf_prog_type *attach_type, bool attach_drv)
2325 /* not an attachment, just a refcount inc, always allow */
2329 if (prog->type != *attach_type)
2331 if (bpf_prog_is_offloaded(prog->aux) && !attach_drv)
2337 static struct bpf_prog *__bpf_prog_get(u32 ufd, enum bpf_prog_type *attach_type,
2340 struct fd f = fdget(ufd);
2341 struct bpf_prog *prog;
2343 prog = ____bpf_prog_get(f);
2346 if (!bpf_prog_get_ok(prog, attach_type, attach_drv)) {
2347 prog = ERR_PTR(-EINVAL);
2357 struct bpf_prog *bpf_prog_get(u32 ufd)
2359 return __bpf_prog_get(ufd, NULL, false);
2362 struct bpf_prog *bpf_prog_get_type_dev(u32 ufd, enum bpf_prog_type type,
2365 return __bpf_prog_get(ufd, &type, attach_drv);
2367 EXPORT_SYMBOL_GPL(bpf_prog_get_type_dev);
2369 /* Initially all BPF programs could be loaded w/o specifying
2370 * expected_attach_type. Later for some of them specifying expected_attach_type
2371 * at load time became required so that program could be validated properly.
2372 * Programs of types that are allowed to be loaded both w/ and w/o (for
2373 * backward compatibility) expected_attach_type, should have the default attach
2374 * type assigned to expected_attach_type for the latter case, so that it can be
2375 * validated later at attach time.
2377 * bpf_prog_load_fixup_attach_type() sets expected_attach_type in @attr if
2378 * prog type requires it but has some attach types that have to be backward
2381 static void bpf_prog_load_fixup_attach_type(union bpf_attr *attr)
2383 switch (attr->prog_type) {
2384 case BPF_PROG_TYPE_CGROUP_SOCK:
2385 /* Unfortunately BPF_ATTACH_TYPE_UNSPEC enumeration doesn't
2386 * exist so checking for non-zero is the way to go here.
2388 if (!attr->expected_attach_type)
2389 attr->expected_attach_type =
2390 BPF_CGROUP_INET_SOCK_CREATE;
2392 case BPF_PROG_TYPE_SK_REUSEPORT:
2393 if (!attr->expected_attach_type)
2394 attr->expected_attach_type =
2395 BPF_SK_REUSEPORT_SELECT;
2401 bpf_prog_load_check_attach(enum bpf_prog_type prog_type,
2402 enum bpf_attach_type expected_attach_type,
2403 struct btf *attach_btf, u32 btf_id,
2404 struct bpf_prog *dst_prog)
2407 if (btf_id > BTF_MAX_TYPE)
2410 if (!attach_btf && !dst_prog)
2413 switch (prog_type) {
2414 case BPF_PROG_TYPE_TRACING:
2415 case BPF_PROG_TYPE_LSM:
2416 case BPF_PROG_TYPE_STRUCT_OPS:
2417 case BPF_PROG_TYPE_EXT:
2424 if (attach_btf && (!btf_id || dst_prog))
2427 if (dst_prog && prog_type != BPF_PROG_TYPE_TRACING &&
2428 prog_type != BPF_PROG_TYPE_EXT)
2431 switch (prog_type) {
2432 case BPF_PROG_TYPE_CGROUP_SOCK:
2433 switch (expected_attach_type) {
2434 case BPF_CGROUP_INET_SOCK_CREATE:
2435 case BPF_CGROUP_INET_SOCK_RELEASE:
2436 case BPF_CGROUP_INET4_POST_BIND:
2437 case BPF_CGROUP_INET6_POST_BIND:
2442 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
2443 switch (expected_attach_type) {
2444 case BPF_CGROUP_INET4_BIND:
2445 case BPF_CGROUP_INET6_BIND:
2446 case BPF_CGROUP_INET4_CONNECT:
2447 case BPF_CGROUP_INET6_CONNECT:
2448 case BPF_CGROUP_UNIX_CONNECT:
2449 case BPF_CGROUP_INET4_GETPEERNAME:
2450 case BPF_CGROUP_INET6_GETPEERNAME:
2451 case BPF_CGROUP_UNIX_GETPEERNAME:
2452 case BPF_CGROUP_INET4_GETSOCKNAME:
2453 case BPF_CGROUP_INET6_GETSOCKNAME:
2454 case BPF_CGROUP_UNIX_GETSOCKNAME:
2455 case BPF_CGROUP_UDP4_SENDMSG:
2456 case BPF_CGROUP_UDP6_SENDMSG:
2457 case BPF_CGROUP_UNIX_SENDMSG:
2458 case BPF_CGROUP_UDP4_RECVMSG:
2459 case BPF_CGROUP_UDP6_RECVMSG:
2460 case BPF_CGROUP_UNIX_RECVMSG:
2465 case BPF_PROG_TYPE_CGROUP_SKB:
2466 switch (expected_attach_type) {
2467 case BPF_CGROUP_INET_INGRESS:
2468 case BPF_CGROUP_INET_EGRESS:
2473 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
2474 switch (expected_attach_type) {
2475 case BPF_CGROUP_SETSOCKOPT:
2476 case BPF_CGROUP_GETSOCKOPT:
2481 case BPF_PROG_TYPE_SK_LOOKUP:
2482 if (expected_attach_type == BPF_SK_LOOKUP)
2485 case BPF_PROG_TYPE_SK_REUSEPORT:
2486 switch (expected_attach_type) {
2487 case BPF_SK_REUSEPORT_SELECT:
2488 case BPF_SK_REUSEPORT_SELECT_OR_MIGRATE:
2493 case BPF_PROG_TYPE_NETFILTER:
2494 if (expected_attach_type == BPF_NETFILTER)
2497 case BPF_PROG_TYPE_SYSCALL:
2498 case BPF_PROG_TYPE_EXT:
2499 if (expected_attach_type)
2507 static bool is_net_admin_prog_type(enum bpf_prog_type prog_type)
2509 switch (prog_type) {
2510 case BPF_PROG_TYPE_SCHED_CLS:
2511 case BPF_PROG_TYPE_SCHED_ACT:
2512 case BPF_PROG_TYPE_XDP:
2513 case BPF_PROG_TYPE_LWT_IN:
2514 case BPF_PROG_TYPE_LWT_OUT:
2515 case BPF_PROG_TYPE_LWT_XMIT:
2516 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
2517 case BPF_PROG_TYPE_SK_SKB:
2518 case BPF_PROG_TYPE_SK_MSG:
2519 case BPF_PROG_TYPE_FLOW_DISSECTOR:
2520 case BPF_PROG_TYPE_CGROUP_DEVICE:
2521 case BPF_PROG_TYPE_CGROUP_SOCK:
2522 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
2523 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
2524 case BPF_PROG_TYPE_CGROUP_SYSCTL:
2525 case BPF_PROG_TYPE_SOCK_OPS:
2526 case BPF_PROG_TYPE_EXT: /* extends any prog */
2527 case BPF_PROG_TYPE_NETFILTER:
2529 case BPF_PROG_TYPE_CGROUP_SKB:
2531 case BPF_PROG_TYPE_SK_REUSEPORT:
2532 /* equivalent to SOCKET_FILTER. need CAP_BPF only */
2538 static bool is_perfmon_prog_type(enum bpf_prog_type prog_type)
2540 switch (prog_type) {
2541 case BPF_PROG_TYPE_KPROBE:
2542 case BPF_PROG_TYPE_TRACEPOINT:
2543 case BPF_PROG_TYPE_PERF_EVENT:
2544 case BPF_PROG_TYPE_RAW_TRACEPOINT:
2545 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
2546 case BPF_PROG_TYPE_TRACING:
2547 case BPF_PROG_TYPE_LSM:
2548 case BPF_PROG_TYPE_STRUCT_OPS: /* has access to struct sock */
2549 case BPF_PROG_TYPE_EXT: /* extends any prog */
2556 /* last field in 'union bpf_attr' used by this command */
2557 #define BPF_PROG_LOAD_LAST_FIELD log_true_size
2559 static int bpf_prog_load(union bpf_attr *attr, bpfptr_t uattr, u32 uattr_size)
2561 enum bpf_prog_type type = attr->prog_type;
2562 struct bpf_prog *prog, *dst_prog = NULL;
2563 struct btf *attach_btf = NULL;
2567 if (CHECK_ATTR(BPF_PROG_LOAD))
2570 if (attr->prog_flags & ~(BPF_F_STRICT_ALIGNMENT |
2571 BPF_F_ANY_ALIGNMENT |
2572 BPF_F_TEST_STATE_FREQ |
2574 BPF_F_TEST_RND_HI32 |
2575 BPF_F_XDP_HAS_FRAGS |
2576 BPF_F_XDP_DEV_BOUND_ONLY))
2579 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS) &&
2580 (attr->prog_flags & BPF_F_ANY_ALIGNMENT) &&
2584 /* Intent here is for unprivileged_bpf_disabled to block BPF program
2585 * creation for unprivileged users; other actions depend
2586 * on fd availability and access to bpffs, so are dependent on
2587 * object creation success. Even with unprivileged BPF disabled,
2588 * capability checks are still carried out for these
2589 * and other operations.
2591 if (sysctl_unprivileged_bpf_disabled && !bpf_capable())
2594 if (attr->insn_cnt == 0 ||
2595 attr->insn_cnt > (bpf_capable() ? BPF_COMPLEXITY_LIMIT_INSNS : BPF_MAXINSNS))
2597 if (type != BPF_PROG_TYPE_SOCKET_FILTER &&
2598 type != BPF_PROG_TYPE_CGROUP_SKB &&
2602 if (is_net_admin_prog_type(type) && !capable(CAP_NET_ADMIN) && !capable(CAP_SYS_ADMIN))
2604 if (is_perfmon_prog_type(type) && !perfmon_capable())
2607 /* attach_prog_fd/attach_btf_obj_fd can specify fd of either bpf_prog
2608 * or btf, we need to check which one it is
2610 if (attr->attach_prog_fd) {
2611 dst_prog = bpf_prog_get(attr->attach_prog_fd);
2612 if (IS_ERR(dst_prog)) {
2614 attach_btf = btf_get_by_fd(attr->attach_btf_obj_fd);
2615 if (IS_ERR(attach_btf))
2617 if (!btf_is_kernel(attach_btf)) {
2618 /* attaching through specifying bpf_prog's BTF
2619 * objects directly might be supported eventually
2621 btf_put(attach_btf);
2625 } else if (attr->attach_btf_id) {
2626 /* fall back to vmlinux BTF, if BTF type ID is specified */
2627 attach_btf = bpf_get_btf_vmlinux();
2628 if (IS_ERR(attach_btf))
2629 return PTR_ERR(attach_btf);
2632 btf_get(attach_btf);
2635 bpf_prog_load_fixup_attach_type(attr);
2636 if (bpf_prog_load_check_attach(type, attr->expected_attach_type,
2637 attach_btf, attr->attach_btf_id,
2640 bpf_prog_put(dst_prog);
2642 btf_put(attach_btf);
2646 /* plain bpf_prog allocation */
2647 prog = bpf_prog_alloc(bpf_prog_size(attr->insn_cnt), GFP_USER);
2650 bpf_prog_put(dst_prog);
2652 btf_put(attach_btf);
2656 prog->expected_attach_type = attr->expected_attach_type;
2657 prog->aux->attach_btf = attach_btf;
2658 prog->aux->attach_btf_id = attr->attach_btf_id;
2659 prog->aux->dst_prog = dst_prog;
2660 prog->aux->dev_bound = !!attr->prog_ifindex;
2661 prog->aux->sleepable = attr->prog_flags & BPF_F_SLEEPABLE;
2662 prog->aux->xdp_has_frags = attr->prog_flags & BPF_F_XDP_HAS_FRAGS;
2664 err = security_bpf_prog_alloc(prog->aux);
2668 prog->aux->user = get_current_user();
2669 prog->len = attr->insn_cnt;
2672 if (copy_from_bpfptr(prog->insns,
2673 make_bpfptr(attr->insns, uattr.is_kernel),
2674 bpf_prog_insn_size(prog)) != 0)
2676 /* copy eBPF program license from user space */
2677 if (strncpy_from_bpfptr(license,
2678 make_bpfptr(attr->license, uattr.is_kernel),
2679 sizeof(license) - 1) < 0)
2681 license[sizeof(license) - 1] = 0;
2683 /* eBPF programs must be GPL compatible to use GPL-ed functions */
2684 prog->gpl_compatible = license_is_gpl_compatible(license) ? 1 : 0;
2686 prog->orig_prog = NULL;
2689 atomic64_set(&prog->aux->refcnt, 1);
2691 if (bpf_prog_is_dev_bound(prog->aux)) {
2692 err = bpf_prog_dev_bound_init(prog, attr);
2697 if (type == BPF_PROG_TYPE_EXT && dst_prog &&
2698 bpf_prog_is_dev_bound(dst_prog->aux)) {
2699 err = bpf_prog_dev_bound_inherit(prog, dst_prog);
2704 /* find program type: socket_filter vs tracing_filter */
2705 err = find_prog_type(type, prog);
2709 prog->aux->load_time = ktime_get_boottime_ns();
2710 err = bpf_obj_name_cpy(prog->aux->name, attr->prog_name,
2711 sizeof(attr->prog_name));
2715 /* run eBPF verifier */
2716 err = bpf_check(&prog, attr, uattr, uattr_size);
2718 goto free_used_maps;
2720 prog = bpf_prog_select_runtime(prog, &err);
2722 goto free_used_maps;
2724 err = bpf_prog_alloc_id(prog);
2726 goto free_used_maps;
2728 /* Upon success of bpf_prog_alloc_id(), the BPF prog is
2729 * effectively publicly exposed. However, retrieving via
2730 * bpf_prog_get_fd_by_id() will take another reference,
2731 * therefore it cannot be gone underneath us.
2733 * Only for the time /after/ successful bpf_prog_new_fd()
2734 * and before returning to userspace, we might just hold
2735 * one reference and any parallel close on that fd could
2736 * rip everything out. Hence, below notifications must
2737 * happen before bpf_prog_new_fd().
2739 * Also, any failure handling from this point onwards must
2740 * be using bpf_prog_put() given the program is exposed.
2742 bpf_prog_kallsyms_add(prog);
2743 perf_event_bpf_event(prog, PERF_BPF_EVENT_PROG_LOAD, 0);
2744 bpf_audit_prog(prog, BPF_AUDIT_LOAD);
2746 err = bpf_prog_new_fd(prog);
2752 /* In case we have subprogs, we need to wait for a grace
2753 * period before we can tear down JIT memory since symbols
2754 * are already exposed under kallsyms.
2756 __bpf_prog_put_noref(prog, prog->aux->real_func_cnt);
2759 free_uid(prog->aux->user);
2760 security_bpf_prog_free(prog->aux);
2762 if (prog->aux->attach_btf)
2763 btf_put(prog->aux->attach_btf);
2764 bpf_prog_free(prog);
2768 #define BPF_OBJ_LAST_FIELD path_fd
2770 static int bpf_obj_pin(const union bpf_attr *attr)
2774 if (CHECK_ATTR(BPF_OBJ) || attr->file_flags & ~BPF_F_PATH_FD)
2777 /* path_fd has to be accompanied by BPF_F_PATH_FD flag */
2778 if (!(attr->file_flags & BPF_F_PATH_FD) && attr->path_fd)
2781 path_fd = attr->file_flags & BPF_F_PATH_FD ? attr->path_fd : AT_FDCWD;
2782 return bpf_obj_pin_user(attr->bpf_fd, path_fd,
2783 u64_to_user_ptr(attr->pathname));
2786 static int bpf_obj_get(const union bpf_attr *attr)
2790 if (CHECK_ATTR(BPF_OBJ) || attr->bpf_fd != 0 ||
2791 attr->file_flags & ~(BPF_OBJ_FLAG_MASK | BPF_F_PATH_FD))
2794 /* path_fd has to be accompanied by BPF_F_PATH_FD flag */
2795 if (!(attr->file_flags & BPF_F_PATH_FD) && attr->path_fd)
2798 path_fd = attr->file_flags & BPF_F_PATH_FD ? attr->path_fd : AT_FDCWD;
2799 return bpf_obj_get_user(path_fd, u64_to_user_ptr(attr->pathname),
2803 void bpf_link_init(struct bpf_link *link, enum bpf_link_type type,
2804 const struct bpf_link_ops *ops, struct bpf_prog *prog)
2806 atomic64_set(&link->refcnt, 1);
2813 static void bpf_link_free_id(int id)
2818 spin_lock_bh(&link_idr_lock);
2819 idr_remove(&link_idr, id);
2820 spin_unlock_bh(&link_idr_lock);
2823 /* Clean up bpf_link and corresponding anon_inode file and FD. After
2824 * anon_inode is created, bpf_link can't be just kfree()'d due to deferred
2825 * anon_inode's release() call. This helper marks bpf_link as
2826 * defunct, releases anon_inode file and puts reserved FD. bpf_prog's refcnt
2827 * is not decremented, it's the responsibility of a calling code that failed
2828 * to complete bpf_link initialization.
2829 * This helper eventually calls link's dealloc callback, but does not call
2830 * link's release callback.
2832 void bpf_link_cleanup(struct bpf_link_primer *primer)
2834 primer->link->prog = NULL;
2835 bpf_link_free_id(primer->id);
2837 put_unused_fd(primer->fd);
2840 void bpf_link_inc(struct bpf_link *link)
2842 atomic64_inc(&link->refcnt);
2845 /* bpf_link_free is guaranteed to be called from process context */
2846 static void bpf_link_free(struct bpf_link *link)
2848 bpf_link_free_id(link->id);
2850 /* detach BPF program, clean up used resources */
2851 link->ops->release(link);
2852 bpf_prog_put(link->prog);
2854 /* free bpf_link and its containing memory */
2855 link->ops->dealloc(link);
2858 static void bpf_link_put_deferred(struct work_struct *work)
2860 struct bpf_link *link = container_of(work, struct bpf_link, work);
2862 bpf_link_free(link);
2865 /* bpf_link_put might be called from atomic context. It needs to be called
2866 * from sleepable context in order to acquire sleeping locks during the process.
2868 void bpf_link_put(struct bpf_link *link)
2870 if (!atomic64_dec_and_test(&link->refcnt))
2873 INIT_WORK(&link->work, bpf_link_put_deferred);
2874 schedule_work(&link->work);
2876 EXPORT_SYMBOL(bpf_link_put);
2878 static void bpf_link_put_direct(struct bpf_link *link)
2880 if (!atomic64_dec_and_test(&link->refcnt))
2882 bpf_link_free(link);
2885 static int bpf_link_release(struct inode *inode, struct file *filp)
2887 struct bpf_link *link = filp->private_data;
2889 bpf_link_put_direct(link);
2893 #ifdef CONFIG_PROC_FS
2894 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type)
2895 #define BPF_MAP_TYPE(_id, _ops)
2896 #define BPF_LINK_TYPE(_id, _name) [_id] = #_name,
2897 static const char *bpf_link_type_strs[] = {
2898 [BPF_LINK_TYPE_UNSPEC] = "<invalid>",
2899 #include <linux/bpf_types.h>
2901 #undef BPF_PROG_TYPE
2903 #undef BPF_LINK_TYPE
2905 static void bpf_link_show_fdinfo(struct seq_file *m, struct file *filp)
2907 const struct bpf_link *link = filp->private_data;
2908 const struct bpf_prog *prog = link->prog;
2909 char prog_tag[sizeof(prog->tag) * 2 + 1] = { };
2914 bpf_link_type_strs[link->type],
2917 bin2hex(prog_tag, prog->tag, sizeof(prog->tag));
2924 if (link->ops->show_fdinfo)
2925 link->ops->show_fdinfo(link, m);
2929 static const struct file_operations bpf_link_fops = {
2930 #ifdef CONFIG_PROC_FS
2931 .show_fdinfo = bpf_link_show_fdinfo,
2933 .release = bpf_link_release,
2934 .read = bpf_dummy_read,
2935 .write = bpf_dummy_write,
2938 static int bpf_link_alloc_id(struct bpf_link *link)
2942 idr_preload(GFP_KERNEL);
2943 spin_lock_bh(&link_idr_lock);
2944 id = idr_alloc_cyclic(&link_idr, link, 1, INT_MAX, GFP_ATOMIC);
2945 spin_unlock_bh(&link_idr_lock);
2951 /* Prepare bpf_link to be exposed to user-space by allocating anon_inode file,
2952 * reserving unused FD and allocating ID from link_idr. This is to be paired
2953 * with bpf_link_settle() to install FD and ID and expose bpf_link to
2954 * user-space, if bpf_link is successfully attached. If not, bpf_link and
2955 * pre-allocated resources are to be freed with bpf_cleanup() call. All the
2956 * transient state is passed around in struct bpf_link_primer.
2957 * This is preferred way to create and initialize bpf_link, especially when
2958 * there are complicated and expensive operations in between creating bpf_link
2959 * itself and attaching it to BPF hook. By using bpf_link_prime() and
2960 * bpf_link_settle() kernel code using bpf_link doesn't have to perform
2961 * expensive (and potentially failing) roll back operations in a rare case
2962 * that file, FD, or ID can't be allocated.
2964 int bpf_link_prime(struct bpf_link *link, struct bpf_link_primer *primer)
2969 fd = get_unused_fd_flags(O_CLOEXEC);
2974 id = bpf_link_alloc_id(link);
2980 file = anon_inode_getfile("bpf_link", &bpf_link_fops, link, O_CLOEXEC);
2982 bpf_link_free_id(id);
2984 return PTR_ERR(file);
2987 primer->link = link;
2988 primer->file = file;
2994 int bpf_link_settle(struct bpf_link_primer *primer)
2996 /* make bpf_link fetchable by ID */
2997 spin_lock_bh(&link_idr_lock);
2998 primer->link->id = primer->id;
2999 spin_unlock_bh(&link_idr_lock);
3000 /* make bpf_link fetchable by FD */
3001 fd_install(primer->fd, primer->file);
3002 /* pass through installed FD */
3006 int bpf_link_new_fd(struct bpf_link *link)
3008 return anon_inode_getfd("bpf-link", &bpf_link_fops, link, O_CLOEXEC);
3011 struct bpf_link *bpf_link_get_from_fd(u32 ufd)
3013 struct fd f = fdget(ufd);
3014 struct bpf_link *link;
3017 return ERR_PTR(-EBADF);
3018 if (f.file->f_op != &bpf_link_fops) {
3020 return ERR_PTR(-EINVAL);
3023 link = f.file->private_data;
3029 EXPORT_SYMBOL(bpf_link_get_from_fd);
3031 static void bpf_tracing_link_release(struct bpf_link *link)
3033 struct bpf_tracing_link *tr_link =
3034 container_of(link, struct bpf_tracing_link, link.link);
3036 WARN_ON_ONCE(bpf_trampoline_unlink_prog(&tr_link->link,
3037 tr_link->trampoline));
3039 bpf_trampoline_put(tr_link->trampoline);
3041 /* tgt_prog is NULL if target is a kernel function */
3042 if (tr_link->tgt_prog)
3043 bpf_prog_put(tr_link->tgt_prog);
3046 static void bpf_tracing_link_dealloc(struct bpf_link *link)
3048 struct bpf_tracing_link *tr_link =
3049 container_of(link, struct bpf_tracing_link, link.link);
3054 static void bpf_tracing_link_show_fdinfo(const struct bpf_link *link,
3055 struct seq_file *seq)
3057 struct bpf_tracing_link *tr_link =
3058 container_of(link, struct bpf_tracing_link, link.link);
3059 u32 target_btf_id, target_obj_id;
3061 bpf_trampoline_unpack_key(tr_link->trampoline->key,
3062 &target_obj_id, &target_btf_id);
3064 "attach_type:\t%d\n"
3065 "target_obj_id:\t%u\n"
3066 "target_btf_id:\t%u\n",
3067 tr_link->attach_type,
3072 static int bpf_tracing_link_fill_link_info(const struct bpf_link *link,
3073 struct bpf_link_info *info)
3075 struct bpf_tracing_link *tr_link =
3076 container_of(link, struct bpf_tracing_link, link.link);
3078 info->tracing.attach_type = tr_link->attach_type;
3079 bpf_trampoline_unpack_key(tr_link->trampoline->key,
3080 &info->tracing.target_obj_id,
3081 &info->tracing.target_btf_id);
3086 static const struct bpf_link_ops bpf_tracing_link_lops = {
3087 .release = bpf_tracing_link_release,
3088 .dealloc = bpf_tracing_link_dealloc,
3089 .show_fdinfo = bpf_tracing_link_show_fdinfo,
3090 .fill_link_info = bpf_tracing_link_fill_link_info,
3093 static int bpf_tracing_prog_attach(struct bpf_prog *prog,
3098 struct bpf_link_primer link_primer;
3099 struct bpf_prog *tgt_prog = NULL;
3100 struct bpf_trampoline *tr = NULL;
3101 struct bpf_tracing_link *link;
3105 switch (prog->type) {
3106 case BPF_PROG_TYPE_TRACING:
3107 if (prog->expected_attach_type != BPF_TRACE_FENTRY &&
3108 prog->expected_attach_type != BPF_TRACE_FEXIT &&
3109 prog->expected_attach_type != BPF_MODIFY_RETURN) {
3114 case BPF_PROG_TYPE_EXT:
3115 if (prog->expected_attach_type != 0) {
3120 case BPF_PROG_TYPE_LSM:
3121 if (prog->expected_attach_type != BPF_LSM_MAC) {
3131 if (!!tgt_prog_fd != !!btf_id) {
3137 /* For now we only allow new targets for BPF_PROG_TYPE_EXT */
3138 if (prog->type != BPF_PROG_TYPE_EXT) {
3143 tgt_prog = bpf_prog_get(tgt_prog_fd);
3144 if (IS_ERR(tgt_prog)) {
3145 err = PTR_ERR(tgt_prog);
3150 key = bpf_trampoline_compute_key(tgt_prog, NULL, btf_id);
3153 link = kzalloc(sizeof(*link), GFP_USER);
3158 bpf_link_init(&link->link.link, BPF_LINK_TYPE_TRACING,
3159 &bpf_tracing_link_lops, prog);
3160 link->attach_type = prog->expected_attach_type;
3161 link->link.cookie = bpf_cookie;
3163 mutex_lock(&prog->aux->dst_mutex);
3165 /* There are a few possible cases here:
3167 * - if prog->aux->dst_trampoline is set, the program was just loaded
3168 * and not yet attached to anything, so we can use the values stored
3171 * - if prog->aux->dst_trampoline is NULL, the program has already been
3172 * attached to a target and its initial target was cleared (below)
3174 * - if tgt_prog != NULL, the caller specified tgt_prog_fd +
3175 * target_btf_id using the link_create API.
3177 * - if tgt_prog == NULL when this function was called using the old
3178 * raw_tracepoint_open API, and we need a target from prog->aux
3180 * - if prog->aux->dst_trampoline and tgt_prog is NULL, the program
3181 * was detached and is going for re-attachment.
3183 if (!prog->aux->dst_trampoline && !tgt_prog) {
3185 * Allow re-attach for TRACING and LSM programs. If it's
3186 * currently linked, bpf_trampoline_link_prog will fail.
3187 * EXT programs need to specify tgt_prog_fd, so they
3188 * re-attach in separate code path.
3190 if (prog->type != BPF_PROG_TYPE_TRACING &&
3191 prog->type != BPF_PROG_TYPE_LSM) {
3195 btf_id = prog->aux->attach_btf_id;
3196 key = bpf_trampoline_compute_key(NULL, prog->aux->attach_btf, btf_id);
3199 if (!prog->aux->dst_trampoline ||
3200 (key && key != prog->aux->dst_trampoline->key)) {
3201 /* If there is no saved target, or the specified target is
3202 * different from the destination specified at load time, we
3203 * need a new trampoline and a check for compatibility
3205 struct bpf_attach_target_info tgt_info = {};
3207 err = bpf_check_attach_target(NULL, prog, tgt_prog, btf_id,
3212 if (tgt_info.tgt_mod) {
3213 module_put(prog->aux->mod);
3214 prog->aux->mod = tgt_info.tgt_mod;
3217 tr = bpf_trampoline_get(key, &tgt_info);
3223 /* The caller didn't specify a target, or the target was the
3224 * same as the destination supplied during program load. This
3225 * means we can reuse the trampoline and reference from program
3226 * load time, and there is no need to allocate a new one. This
3227 * can only happen once for any program, as the saved values in
3228 * prog->aux are cleared below.
3230 tr = prog->aux->dst_trampoline;
3231 tgt_prog = prog->aux->dst_prog;
3234 err = bpf_link_prime(&link->link.link, &link_primer);
3238 err = bpf_trampoline_link_prog(&link->link, tr);
3240 bpf_link_cleanup(&link_primer);
3245 link->tgt_prog = tgt_prog;
3246 link->trampoline = tr;
3248 /* Always clear the trampoline and target prog from prog->aux to make
3249 * sure the original attach destination is not kept alive after a
3250 * program is (re-)attached to another target.
3252 if (prog->aux->dst_prog &&
3253 (tgt_prog_fd || tr != prog->aux->dst_trampoline))
3254 /* got extra prog ref from syscall, or attaching to different prog */
3255 bpf_prog_put(prog->aux->dst_prog);
3256 if (prog->aux->dst_trampoline && tr != prog->aux->dst_trampoline)
3257 /* we allocated a new trampoline, so free the old one */
3258 bpf_trampoline_put(prog->aux->dst_trampoline);
3260 prog->aux->dst_prog = NULL;
3261 prog->aux->dst_trampoline = NULL;
3262 mutex_unlock(&prog->aux->dst_mutex);
3264 return bpf_link_settle(&link_primer);
3266 if (tr && tr != prog->aux->dst_trampoline)
3267 bpf_trampoline_put(tr);
3268 mutex_unlock(&prog->aux->dst_mutex);
3271 if (tgt_prog_fd && tgt_prog)
3272 bpf_prog_put(tgt_prog);
3276 struct bpf_raw_tp_link {
3277 struct bpf_link link;
3278 struct bpf_raw_event_map *btp;
3281 static void bpf_raw_tp_link_release(struct bpf_link *link)
3283 struct bpf_raw_tp_link *raw_tp =
3284 container_of(link, struct bpf_raw_tp_link, link);
3286 bpf_probe_unregister(raw_tp->btp, raw_tp->link.prog);
3287 bpf_put_raw_tracepoint(raw_tp->btp);
3290 static void bpf_raw_tp_link_dealloc(struct bpf_link *link)
3292 struct bpf_raw_tp_link *raw_tp =
3293 container_of(link, struct bpf_raw_tp_link, link);
3298 static void bpf_raw_tp_link_show_fdinfo(const struct bpf_link *link,
3299 struct seq_file *seq)
3301 struct bpf_raw_tp_link *raw_tp_link =
3302 container_of(link, struct bpf_raw_tp_link, link);
3306 raw_tp_link->btp->tp->name);
3309 static int bpf_copy_to_user(char __user *ubuf, const char *buf, u32 ulen,
3312 if (ulen >= len + 1) {
3313 if (copy_to_user(ubuf, buf, len + 1))
3318 if (copy_to_user(ubuf, buf, ulen - 1))
3320 if (put_user(zero, ubuf + ulen - 1))
3328 static int bpf_raw_tp_link_fill_link_info(const struct bpf_link *link,
3329 struct bpf_link_info *info)
3331 struct bpf_raw_tp_link *raw_tp_link =
3332 container_of(link, struct bpf_raw_tp_link, link);
3333 char __user *ubuf = u64_to_user_ptr(info->raw_tracepoint.tp_name);
3334 const char *tp_name = raw_tp_link->btp->tp->name;
3335 u32 ulen = info->raw_tracepoint.tp_name_len;
3336 size_t tp_len = strlen(tp_name);
3341 info->raw_tracepoint.tp_name_len = tp_len + 1;
3346 return bpf_copy_to_user(ubuf, tp_name, ulen, tp_len);
3349 static const struct bpf_link_ops bpf_raw_tp_link_lops = {
3350 .release = bpf_raw_tp_link_release,
3351 .dealloc = bpf_raw_tp_link_dealloc,
3352 .show_fdinfo = bpf_raw_tp_link_show_fdinfo,
3353 .fill_link_info = bpf_raw_tp_link_fill_link_info,
3356 #ifdef CONFIG_PERF_EVENTS
3357 struct bpf_perf_link {
3358 struct bpf_link link;
3359 struct file *perf_file;
3362 static void bpf_perf_link_release(struct bpf_link *link)
3364 struct bpf_perf_link *perf_link = container_of(link, struct bpf_perf_link, link);
3365 struct perf_event *event = perf_link->perf_file->private_data;
3367 perf_event_free_bpf_prog(event);
3368 fput(perf_link->perf_file);
3371 static void bpf_perf_link_dealloc(struct bpf_link *link)
3373 struct bpf_perf_link *perf_link = container_of(link, struct bpf_perf_link, link);
3378 static int bpf_perf_link_fill_common(const struct perf_event *event,
3379 char __user *uname, u32 ulen,
3380 u64 *probe_offset, u64 *probe_addr,
3381 u32 *fd_type, unsigned long *missed)
3391 err = bpf_get_perf_event_info(event, &prog_id, fd_type, &buf,
3392 probe_offset, probe_addr, missed);
3399 err = bpf_copy_to_user(uname, buf, ulen, len);
3405 if (put_user(zero, uname))
3411 #ifdef CONFIG_KPROBE_EVENTS
3412 static int bpf_perf_link_fill_kprobe(const struct perf_event *event,
3413 struct bpf_link_info *info)
3415 unsigned long missed;
3421 uname = u64_to_user_ptr(info->perf_event.kprobe.func_name);
3422 ulen = info->perf_event.kprobe.name_len;
3423 err = bpf_perf_link_fill_common(event, uname, ulen, &offset, &addr,
3427 if (type == BPF_FD_TYPE_KRETPROBE)
3428 info->perf_event.type = BPF_PERF_EVENT_KRETPROBE;
3430 info->perf_event.type = BPF_PERF_EVENT_KPROBE;
3432 info->perf_event.kprobe.offset = offset;
3433 info->perf_event.kprobe.missed = missed;
3434 if (!kallsyms_show_value(current_cred()))
3436 info->perf_event.kprobe.addr = addr;
3441 #ifdef CONFIG_UPROBE_EVENTS
3442 static int bpf_perf_link_fill_uprobe(const struct perf_event *event,
3443 struct bpf_link_info *info)
3450 uname = u64_to_user_ptr(info->perf_event.uprobe.file_name);
3451 ulen = info->perf_event.uprobe.name_len;
3452 err = bpf_perf_link_fill_common(event, uname, ulen, &offset, &addr,
3457 if (type == BPF_FD_TYPE_URETPROBE)
3458 info->perf_event.type = BPF_PERF_EVENT_URETPROBE;
3460 info->perf_event.type = BPF_PERF_EVENT_UPROBE;
3461 info->perf_event.uprobe.offset = offset;
3466 static int bpf_perf_link_fill_probe(const struct perf_event *event,
3467 struct bpf_link_info *info)
3469 #ifdef CONFIG_KPROBE_EVENTS
3470 if (event->tp_event->flags & TRACE_EVENT_FL_KPROBE)
3471 return bpf_perf_link_fill_kprobe(event, info);
3473 #ifdef CONFIG_UPROBE_EVENTS
3474 if (event->tp_event->flags & TRACE_EVENT_FL_UPROBE)
3475 return bpf_perf_link_fill_uprobe(event, info);
3480 static int bpf_perf_link_fill_tracepoint(const struct perf_event *event,
3481 struct bpf_link_info *info)
3486 uname = u64_to_user_ptr(info->perf_event.tracepoint.tp_name);
3487 ulen = info->perf_event.tracepoint.name_len;
3488 info->perf_event.type = BPF_PERF_EVENT_TRACEPOINT;
3489 return bpf_perf_link_fill_common(event, uname, ulen, NULL, NULL, NULL, NULL);
3492 static int bpf_perf_link_fill_perf_event(const struct perf_event *event,
3493 struct bpf_link_info *info)
3495 info->perf_event.event.type = event->attr.type;
3496 info->perf_event.event.config = event->attr.config;
3497 info->perf_event.type = BPF_PERF_EVENT_EVENT;
3501 static int bpf_perf_link_fill_link_info(const struct bpf_link *link,
3502 struct bpf_link_info *info)
3504 struct bpf_perf_link *perf_link;
3505 const struct perf_event *event;
3507 perf_link = container_of(link, struct bpf_perf_link, link);
3508 event = perf_get_event(perf_link->perf_file);
3510 return PTR_ERR(event);
3512 switch (event->prog->type) {
3513 case BPF_PROG_TYPE_PERF_EVENT:
3514 return bpf_perf_link_fill_perf_event(event, info);
3515 case BPF_PROG_TYPE_TRACEPOINT:
3516 return bpf_perf_link_fill_tracepoint(event, info);
3517 case BPF_PROG_TYPE_KPROBE:
3518 return bpf_perf_link_fill_probe(event, info);
3524 static const struct bpf_link_ops bpf_perf_link_lops = {
3525 .release = bpf_perf_link_release,
3526 .dealloc = bpf_perf_link_dealloc,
3527 .fill_link_info = bpf_perf_link_fill_link_info,
3530 static int bpf_perf_link_attach(const union bpf_attr *attr, struct bpf_prog *prog)
3532 struct bpf_link_primer link_primer;
3533 struct bpf_perf_link *link;
3534 struct perf_event *event;
3535 struct file *perf_file;
3538 if (attr->link_create.flags)
3541 perf_file = perf_event_get(attr->link_create.target_fd);
3542 if (IS_ERR(perf_file))
3543 return PTR_ERR(perf_file);
3545 link = kzalloc(sizeof(*link), GFP_USER);
3550 bpf_link_init(&link->link, BPF_LINK_TYPE_PERF_EVENT, &bpf_perf_link_lops, prog);
3551 link->perf_file = perf_file;
3553 err = bpf_link_prime(&link->link, &link_primer);
3559 event = perf_file->private_data;
3560 err = perf_event_set_bpf_prog(event, prog, attr->link_create.perf_event.bpf_cookie);
3562 bpf_link_cleanup(&link_primer);
3565 /* perf_event_set_bpf_prog() doesn't take its own refcnt on prog */
3568 return bpf_link_settle(&link_primer);
3575 static int bpf_perf_link_attach(const union bpf_attr *attr, struct bpf_prog *prog)
3579 #endif /* CONFIG_PERF_EVENTS */
3581 static int bpf_raw_tp_link_attach(struct bpf_prog *prog,
3582 const char __user *user_tp_name)
3584 struct bpf_link_primer link_primer;
3585 struct bpf_raw_tp_link *link;
3586 struct bpf_raw_event_map *btp;
3587 const char *tp_name;
3591 switch (prog->type) {
3592 case BPF_PROG_TYPE_TRACING:
3593 case BPF_PROG_TYPE_EXT:
3594 case BPF_PROG_TYPE_LSM:
3596 /* The attach point for this category of programs
3597 * should be specified via btf_id during program load.
3600 if (prog->type == BPF_PROG_TYPE_TRACING &&
3601 prog->expected_attach_type == BPF_TRACE_RAW_TP) {
3602 tp_name = prog->aux->attach_func_name;
3605 return bpf_tracing_prog_attach(prog, 0, 0, 0);
3606 case BPF_PROG_TYPE_RAW_TRACEPOINT:
3607 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
3608 if (strncpy_from_user(buf, user_tp_name, sizeof(buf) - 1) < 0)
3610 buf[sizeof(buf) - 1] = 0;
3617 btp = bpf_get_raw_tracepoint(tp_name);
3621 link = kzalloc(sizeof(*link), GFP_USER);
3626 bpf_link_init(&link->link, BPF_LINK_TYPE_RAW_TRACEPOINT,
3627 &bpf_raw_tp_link_lops, prog);
3630 err = bpf_link_prime(&link->link, &link_primer);
3636 err = bpf_probe_register(link->btp, prog);
3638 bpf_link_cleanup(&link_primer);
3642 return bpf_link_settle(&link_primer);
3645 bpf_put_raw_tracepoint(btp);
3649 #define BPF_RAW_TRACEPOINT_OPEN_LAST_FIELD raw_tracepoint.prog_fd
3651 static int bpf_raw_tracepoint_open(const union bpf_attr *attr)
3653 struct bpf_prog *prog;
3656 if (CHECK_ATTR(BPF_RAW_TRACEPOINT_OPEN))
3659 prog = bpf_prog_get(attr->raw_tracepoint.prog_fd);
3661 return PTR_ERR(prog);
3663 fd = bpf_raw_tp_link_attach(prog, u64_to_user_ptr(attr->raw_tracepoint.name));
3669 static enum bpf_prog_type
3670 attach_type_to_prog_type(enum bpf_attach_type attach_type)
3672 switch (attach_type) {
3673 case BPF_CGROUP_INET_INGRESS:
3674 case BPF_CGROUP_INET_EGRESS:
3675 return BPF_PROG_TYPE_CGROUP_SKB;
3676 case BPF_CGROUP_INET_SOCK_CREATE:
3677 case BPF_CGROUP_INET_SOCK_RELEASE:
3678 case BPF_CGROUP_INET4_POST_BIND:
3679 case BPF_CGROUP_INET6_POST_BIND:
3680 return BPF_PROG_TYPE_CGROUP_SOCK;
3681 case BPF_CGROUP_INET4_BIND:
3682 case BPF_CGROUP_INET6_BIND:
3683 case BPF_CGROUP_INET4_CONNECT:
3684 case BPF_CGROUP_INET6_CONNECT:
3685 case BPF_CGROUP_UNIX_CONNECT:
3686 case BPF_CGROUP_INET4_GETPEERNAME:
3687 case BPF_CGROUP_INET6_GETPEERNAME:
3688 case BPF_CGROUP_UNIX_GETPEERNAME:
3689 case BPF_CGROUP_INET4_GETSOCKNAME:
3690 case BPF_CGROUP_INET6_GETSOCKNAME:
3691 case BPF_CGROUP_UNIX_GETSOCKNAME:
3692 case BPF_CGROUP_UDP4_SENDMSG:
3693 case BPF_CGROUP_UDP6_SENDMSG:
3694 case BPF_CGROUP_UNIX_SENDMSG:
3695 case BPF_CGROUP_UDP4_RECVMSG:
3696 case BPF_CGROUP_UDP6_RECVMSG:
3697 case BPF_CGROUP_UNIX_RECVMSG:
3698 return BPF_PROG_TYPE_CGROUP_SOCK_ADDR;
3699 case BPF_CGROUP_SOCK_OPS:
3700 return BPF_PROG_TYPE_SOCK_OPS;
3701 case BPF_CGROUP_DEVICE:
3702 return BPF_PROG_TYPE_CGROUP_DEVICE;
3703 case BPF_SK_MSG_VERDICT:
3704 return BPF_PROG_TYPE_SK_MSG;
3705 case BPF_SK_SKB_STREAM_PARSER:
3706 case BPF_SK_SKB_STREAM_VERDICT:
3707 case BPF_SK_SKB_VERDICT:
3708 return BPF_PROG_TYPE_SK_SKB;
3709 case BPF_LIRC_MODE2:
3710 return BPF_PROG_TYPE_LIRC_MODE2;
3711 case BPF_FLOW_DISSECTOR:
3712 return BPF_PROG_TYPE_FLOW_DISSECTOR;
3713 case BPF_CGROUP_SYSCTL:
3714 return BPF_PROG_TYPE_CGROUP_SYSCTL;
3715 case BPF_CGROUP_GETSOCKOPT:
3716 case BPF_CGROUP_SETSOCKOPT:
3717 return BPF_PROG_TYPE_CGROUP_SOCKOPT;
3718 case BPF_TRACE_ITER:
3719 case BPF_TRACE_RAW_TP:
3720 case BPF_TRACE_FENTRY:
3721 case BPF_TRACE_FEXIT:
3722 case BPF_MODIFY_RETURN:
3723 return BPF_PROG_TYPE_TRACING;
3725 return BPF_PROG_TYPE_LSM;
3727 return BPF_PROG_TYPE_SK_LOOKUP;
3729 return BPF_PROG_TYPE_XDP;
3730 case BPF_LSM_CGROUP:
3731 return BPF_PROG_TYPE_LSM;
3732 case BPF_TCX_INGRESS:
3733 case BPF_TCX_EGRESS:
3734 case BPF_NETKIT_PRIMARY:
3735 case BPF_NETKIT_PEER:
3736 return BPF_PROG_TYPE_SCHED_CLS;
3738 return BPF_PROG_TYPE_UNSPEC;
3742 static int bpf_prog_attach_check_attach_type(const struct bpf_prog *prog,
3743 enum bpf_attach_type attach_type)
3745 enum bpf_prog_type ptype;
3747 switch (prog->type) {
3748 case BPF_PROG_TYPE_CGROUP_SOCK:
3749 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
3750 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3751 case BPF_PROG_TYPE_SK_LOOKUP:
3752 return attach_type == prog->expected_attach_type ? 0 : -EINVAL;
3753 case BPF_PROG_TYPE_CGROUP_SKB:
3754 if (!capable(CAP_NET_ADMIN))
3755 /* cg-skb progs can be loaded by unpriv user.
3756 * check permissions at attach time.
3759 return prog->enforce_expected_attach_type &&
3760 prog->expected_attach_type != attach_type ?
3762 case BPF_PROG_TYPE_EXT:
3764 case BPF_PROG_TYPE_NETFILTER:
3765 if (attach_type != BPF_NETFILTER)
3768 case BPF_PROG_TYPE_PERF_EVENT:
3769 case BPF_PROG_TYPE_TRACEPOINT:
3770 if (attach_type != BPF_PERF_EVENT)
3773 case BPF_PROG_TYPE_KPROBE:
3774 if (prog->expected_attach_type == BPF_TRACE_KPROBE_MULTI &&
3775 attach_type != BPF_TRACE_KPROBE_MULTI)
3777 if (prog->expected_attach_type == BPF_TRACE_UPROBE_MULTI &&
3778 attach_type != BPF_TRACE_UPROBE_MULTI)
3780 if (attach_type != BPF_PERF_EVENT &&
3781 attach_type != BPF_TRACE_KPROBE_MULTI &&
3782 attach_type != BPF_TRACE_UPROBE_MULTI)
3785 case BPF_PROG_TYPE_SCHED_CLS:
3786 if (attach_type != BPF_TCX_INGRESS &&
3787 attach_type != BPF_TCX_EGRESS &&
3788 attach_type != BPF_NETKIT_PRIMARY &&
3789 attach_type != BPF_NETKIT_PEER)
3793 ptype = attach_type_to_prog_type(attach_type);
3794 if (ptype == BPF_PROG_TYPE_UNSPEC || ptype != prog->type)
3800 #define BPF_PROG_ATTACH_LAST_FIELD expected_revision
3802 #define BPF_F_ATTACH_MASK_BASE \
3803 (BPF_F_ALLOW_OVERRIDE | \
3804 BPF_F_ALLOW_MULTI | \
3807 #define BPF_F_ATTACH_MASK_MPROG \
3814 static int bpf_prog_attach(const union bpf_attr *attr)
3816 enum bpf_prog_type ptype;
3817 struct bpf_prog *prog;
3820 if (CHECK_ATTR(BPF_PROG_ATTACH))
3823 ptype = attach_type_to_prog_type(attr->attach_type);
3824 if (ptype == BPF_PROG_TYPE_UNSPEC)
3826 if (bpf_mprog_supported(ptype)) {
3827 if (attr->attach_flags & ~BPF_F_ATTACH_MASK_MPROG)
3830 if (attr->attach_flags & ~BPF_F_ATTACH_MASK_BASE)
3832 if (attr->relative_fd ||
3833 attr->expected_revision)
3837 prog = bpf_prog_get_type(attr->attach_bpf_fd, ptype);
3839 return PTR_ERR(prog);
3841 if (bpf_prog_attach_check_attach_type(prog, attr->attach_type)) {
3847 case BPF_PROG_TYPE_SK_SKB:
3848 case BPF_PROG_TYPE_SK_MSG:
3849 ret = sock_map_get_from_fd(attr, prog);
3851 case BPF_PROG_TYPE_LIRC_MODE2:
3852 ret = lirc_prog_attach(attr, prog);
3854 case BPF_PROG_TYPE_FLOW_DISSECTOR:
3855 ret = netns_bpf_prog_attach(attr, prog);
3857 case BPF_PROG_TYPE_CGROUP_DEVICE:
3858 case BPF_PROG_TYPE_CGROUP_SKB:
3859 case BPF_PROG_TYPE_CGROUP_SOCK:
3860 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
3861 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3862 case BPF_PROG_TYPE_CGROUP_SYSCTL:
3863 case BPF_PROG_TYPE_SOCK_OPS:
3864 case BPF_PROG_TYPE_LSM:
3865 if (ptype == BPF_PROG_TYPE_LSM &&
3866 prog->expected_attach_type != BPF_LSM_CGROUP)
3869 ret = cgroup_bpf_prog_attach(attr, ptype, prog);
3871 case BPF_PROG_TYPE_SCHED_CLS:
3872 if (attr->attach_type == BPF_TCX_INGRESS ||
3873 attr->attach_type == BPF_TCX_EGRESS)
3874 ret = tcx_prog_attach(attr, prog);
3876 ret = netkit_prog_attach(attr, prog);
3887 #define BPF_PROG_DETACH_LAST_FIELD expected_revision
3889 static int bpf_prog_detach(const union bpf_attr *attr)
3891 struct bpf_prog *prog = NULL;
3892 enum bpf_prog_type ptype;
3895 if (CHECK_ATTR(BPF_PROG_DETACH))
3898 ptype = attach_type_to_prog_type(attr->attach_type);
3899 if (bpf_mprog_supported(ptype)) {
3900 if (ptype == BPF_PROG_TYPE_UNSPEC)
3902 if (attr->attach_flags & ~BPF_F_ATTACH_MASK_MPROG)
3904 if (attr->attach_bpf_fd) {
3905 prog = bpf_prog_get_type(attr->attach_bpf_fd, ptype);
3907 return PTR_ERR(prog);
3909 } else if (attr->attach_flags ||
3910 attr->relative_fd ||
3911 attr->expected_revision) {
3916 case BPF_PROG_TYPE_SK_MSG:
3917 case BPF_PROG_TYPE_SK_SKB:
3918 ret = sock_map_prog_detach(attr, ptype);
3920 case BPF_PROG_TYPE_LIRC_MODE2:
3921 ret = lirc_prog_detach(attr);
3923 case BPF_PROG_TYPE_FLOW_DISSECTOR:
3924 ret = netns_bpf_prog_detach(attr, ptype);
3926 case BPF_PROG_TYPE_CGROUP_DEVICE:
3927 case BPF_PROG_TYPE_CGROUP_SKB:
3928 case BPF_PROG_TYPE_CGROUP_SOCK:
3929 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
3930 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3931 case BPF_PROG_TYPE_CGROUP_SYSCTL:
3932 case BPF_PROG_TYPE_SOCK_OPS:
3933 case BPF_PROG_TYPE_LSM:
3934 ret = cgroup_bpf_prog_detach(attr, ptype);
3936 case BPF_PROG_TYPE_SCHED_CLS:
3937 if (attr->attach_type == BPF_TCX_INGRESS ||
3938 attr->attach_type == BPF_TCX_EGRESS)
3939 ret = tcx_prog_detach(attr, prog);
3941 ret = netkit_prog_detach(attr, prog);
3952 #define BPF_PROG_QUERY_LAST_FIELD query.revision
3954 static int bpf_prog_query(const union bpf_attr *attr,
3955 union bpf_attr __user *uattr)
3957 if (!capable(CAP_NET_ADMIN))
3959 if (CHECK_ATTR(BPF_PROG_QUERY))
3961 if (attr->query.query_flags & ~BPF_F_QUERY_EFFECTIVE)
3964 switch (attr->query.attach_type) {
3965 case BPF_CGROUP_INET_INGRESS:
3966 case BPF_CGROUP_INET_EGRESS:
3967 case BPF_CGROUP_INET_SOCK_CREATE:
3968 case BPF_CGROUP_INET_SOCK_RELEASE:
3969 case BPF_CGROUP_INET4_BIND:
3970 case BPF_CGROUP_INET6_BIND:
3971 case BPF_CGROUP_INET4_POST_BIND:
3972 case BPF_CGROUP_INET6_POST_BIND:
3973 case BPF_CGROUP_INET4_CONNECT:
3974 case BPF_CGROUP_INET6_CONNECT:
3975 case BPF_CGROUP_UNIX_CONNECT:
3976 case BPF_CGROUP_INET4_GETPEERNAME:
3977 case BPF_CGROUP_INET6_GETPEERNAME:
3978 case BPF_CGROUP_UNIX_GETPEERNAME:
3979 case BPF_CGROUP_INET4_GETSOCKNAME:
3980 case BPF_CGROUP_INET6_GETSOCKNAME:
3981 case BPF_CGROUP_UNIX_GETSOCKNAME:
3982 case BPF_CGROUP_UDP4_SENDMSG:
3983 case BPF_CGROUP_UDP6_SENDMSG:
3984 case BPF_CGROUP_UNIX_SENDMSG:
3985 case BPF_CGROUP_UDP4_RECVMSG:
3986 case BPF_CGROUP_UDP6_RECVMSG:
3987 case BPF_CGROUP_UNIX_RECVMSG:
3988 case BPF_CGROUP_SOCK_OPS:
3989 case BPF_CGROUP_DEVICE:
3990 case BPF_CGROUP_SYSCTL:
3991 case BPF_CGROUP_GETSOCKOPT:
3992 case BPF_CGROUP_SETSOCKOPT:
3993 case BPF_LSM_CGROUP:
3994 return cgroup_bpf_prog_query(attr, uattr);
3995 case BPF_LIRC_MODE2:
3996 return lirc_prog_query(attr, uattr);
3997 case BPF_FLOW_DISSECTOR:
3999 return netns_bpf_prog_query(attr, uattr);
4000 case BPF_SK_SKB_STREAM_PARSER:
4001 case BPF_SK_SKB_STREAM_VERDICT:
4002 case BPF_SK_MSG_VERDICT:
4003 case BPF_SK_SKB_VERDICT:
4004 return sock_map_bpf_prog_query(attr, uattr);
4005 case BPF_TCX_INGRESS:
4006 case BPF_TCX_EGRESS:
4007 return tcx_prog_query(attr, uattr);
4008 case BPF_NETKIT_PRIMARY:
4009 case BPF_NETKIT_PEER:
4010 return netkit_prog_query(attr, uattr);
4016 #define BPF_PROG_TEST_RUN_LAST_FIELD test.batch_size
4018 static int bpf_prog_test_run(const union bpf_attr *attr,
4019 union bpf_attr __user *uattr)
4021 struct bpf_prog *prog;
4022 int ret = -ENOTSUPP;
4024 if (CHECK_ATTR(BPF_PROG_TEST_RUN))
4027 if ((attr->test.ctx_size_in && !attr->test.ctx_in) ||
4028 (!attr->test.ctx_size_in && attr->test.ctx_in))
4031 if ((attr->test.ctx_size_out && !attr->test.ctx_out) ||
4032 (!attr->test.ctx_size_out && attr->test.ctx_out))
4035 prog = bpf_prog_get(attr->test.prog_fd);
4037 return PTR_ERR(prog);
4039 if (prog->aux->ops->test_run)
4040 ret = prog->aux->ops->test_run(prog, attr, uattr);
4046 #define BPF_OBJ_GET_NEXT_ID_LAST_FIELD next_id
4048 static int bpf_obj_get_next_id(const union bpf_attr *attr,
4049 union bpf_attr __user *uattr,
4053 u32 next_id = attr->start_id;
4056 if (CHECK_ATTR(BPF_OBJ_GET_NEXT_ID) || next_id >= INT_MAX)
4059 if (!capable(CAP_SYS_ADMIN))
4064 if (!idr_get_next(idr, &next_id))
4066 spin_unlock_bh(lock);
4069 err = put_user(next_id, &uattr->next_id);
4074 struct bpf_map *bpf_map_get_curr_or_next(u32 *id)
4076 struct bpf_map *map;
4078 spin_lock_bh(&map_idr_lock);
4080 map = idr_get_next(&map_idr, id);
4082 map = __bpf_map_inc_not_zero(map, false);
4088 spin_unlock_bh(&map_idr_lock);
4093 struct bpf_prog *bpf_prog_get_curr_or_next(u32 *id)
4095 struct bpf_prog *prog;
4097 spin_lock_bh(&prog_idr_lock);
4099 prog = idr_get_next(&prog_idr, id);
4101 prog = bpf_prog_inc_not_zero(prog);
4107 spin_unlock_bh(&prog_idr_lock);
4112 #define BPF_PROG_GET_FD_BY_ID_LAST_FIELD prog_id
4114 struct bpf_prog *bpf_prog_by_id(u32 id)
4116 struct bpf_prog *prog;
4119 return ERR_PTR(-ENOENT);
4121 spin_lock_bh(&prog_idr_lock);
4122 prog = idr_find(&prog_idr, id);
4124 prog = bpf_prog_inc_not_zero(prog);
4126 prog = ERR_PTR(-ENOENT);
4127 spin_unlock_bh(&prog_idr_lock);
4131 static int bpf_prog_get_fd_by_id(const union bpf_attr *attr)
4133 struct bpf_prog *prog;
4134 u32 id = attr->prog_id;
4137 if (CHECK_ATTR(BPF_PROG_GET_FD_BY_ID))
4140 if (!capable(CAP_SYS_ADMIN))
4143 prog = bpf_prog_by_id(id);
4145 return PTR_ERR(prog);
4147 fd = bpf_prog_new_fd(prog);
4154 #define BPF_MAP_GET_FD_BY_ID_LAST_FIELD open_flags
4156 static int bpf_map_get_fd_by_id(const union bpf_attr *attr)
4158 struct bpf_map *map;
4159 u32 id = attr->map_id;
4163 if (CHECK_ATTR(BPF_MAP_GET_FD_BY_ID) ||
4164 attr->open_flags & ~BPF_OBJ_FLAG_MASK)
4167 if (!capable(CAP_SYS_ADMIN))
4170 f_flags = bpf_get_file_flag(attr->open_flags);
4174 spin_lock_bh(&map_idr_lock);
4175 map = idr_find(&map_idr, id);
4177 map = __bpf_map_inc_not_zero(map, true);
4179 map = ERR_PTR(-ENOENT);
4180 spin_unlock_bh(&map_idr_lock);
4183 return PTR_ERR(map);
4185 fd = bpf_map_new_fd(map, f_flags);
4187 bpf_map_put_with_uref(map);
4192 static const struct bpf_map *bpf_map_from_imm(const struct bpf_prog *prog,
4193 unsigned long addr, u32 *off,
4196 const struct bpf_map *map;
4199 mutex_lock(&prog->aux->used_maps_mutex);
4200 for (i = 0, *off = 0; i < prog->aux->used_map_cnt; i++) {
4201 map = prog->aux->used_maps[i];
4202 if (map == (void *)addr) {
4203 *type = BPF_PSEUDO_MAP_FD;
4206 if (!map->ops->map_direct_value_meta)
4208 if (!map->ops->map_direct_value_meta(map, addr, off)) {
4209 *type = BPF_PSEUDO_MAP_VALUE;
4216 mutex_unlock(&prog->aux->used_maps_mutex);
4220 static struct bpf_insn *bpf_insn_prepare_dump(const struct bpf_prog *prog,
4221 const struct cred *f_cred)
4223 const struct bpf_map *map;
4224 struct bpf_insn *insns;
4230 insns = kmemdup(prog->insnsi, bpf_prog_insn_size(prog),
4235 for (i = 0; i < prog->len; i++) {
4236 code = insns[i].code;
4238 if (code == (BPF_JMP | BPF_TAIL_CALL)) {
4239 insns[i].code = BPF_JMP | BPF_CALL;
4240 insns[i].imm = BPF_FUNC_tail_call;
4243 if (code == (BPF_JMP | BPF_CALL) ||
4244 code == (BPF_JMP | BPF_CALL_ARGS)) {
4245 if (code == (BPF_JMP | BPF_CALL_ARGS))
4246 insns[i].code = BPF_JMP | BPF_CALL;
4247 if (!bpf_dump_raw_ok(f_cred))
4251 if (BPF_CLASS(code) == BPF_LDX && BPF_MODE(code) == BPF_PROBE_MEM) {
4252 insns[i].code = BPF_LDX | BPF_SIZE(code) | BPF_MEM;
4256 if (code != (BPF_LD | BPF_IMM | BPF_DW))
4259 imm = ((u64)insns[i + 1].imm << 32) | (u32)insns[i].imm;
4260 map = bpf_map_from_imm(prog, imm, &off, &type);
4262 insns[i].src_reg = type;
4263 insns[i].imm = map->id;
4264 insns[i + 1].imm = off;
4272 static int set_info_rec_size(struct bpf_prog_info *info)
4275 * Ensure info.*_rec_size is the same as kernel expected size
4279 * Only allow zero *_rec_size if both _rec_size and _cnt are
4280 * zero. In this case, the kernel will set the expected
4281 * _rec_size back to the info.
4284 if ((info->nr_func_info || info->func_info_rec_size) &&
4285 info->func_info_rec_size != sizeof(struct bpf_func_info))
4288 if ((info->nr_line_info || info->line_info_rec_size) &&
4289 info->line_info_rec_size != sizeof(struct bpf_line_info))
4292 if ((info->nr_jited_line_info || info->jited_line_info_rec_size) &&
4293 info->jited_line_info_rec_size != sizeof(__u64))
4296 info->func_info_rec_size = sizeof(struct bpf_func_info);
4297 info->line_info_rec_size = sizeof(struct bpf_line_info);
4298 info->jited_line_info_rec_size = sizeof(__u64);
4303 static int bpf_prog_get_info_by_fd(struct file *file,
4304 struct bpf_prog *prog,
4305 const union bpf_attr *attr,
4306 union bpf_attr __user *uattr)
4308 struct bpf_prog_info __user *uinfo = u64_to_user_ptr(attr->info.info);
4309 struct btf *attach_btf = bpf_prog_get_target_btf(prog);
4310 struct bpf_prog_info info;
4311 u32 info_len = attr->info.info_len;
4312 struct bpf_prog_kstats stats;
4313 char __user *uinsns;
4317 err = bpf_check_uarg_tail_zero(USER_BPFPTR(uinfo), sizeof(info), info_len);
4320 info_len = min_t(u32, sizeof(info), info_len);
4322 memset(&info, 0, sizeof(info));
4323 if (copy_from_user(&info, uinfo, info_len))
4326 info.type = prog->type;
4327 info.id = prog->aux->id;
4328 info.load_time = prog->aux->load_time;
4329 info.created_by_uid = from_kuid_munged(current_user_ns(),
4330 prog->aux->user->uid);
4331 info.gpl_compatible = prog->gpl_compatible;
4333 memcpy(info.tag, prog->tag, sizeof(prog->tag));
4334 memcpy(info.name, prog->aux->name, sizeof(prog->aux->name));
4336 mutex_lock(&prog->aux->used_maps_mutex);
4337 ulen = info.nr_map_ids;
4338 info.nr_map_ids = prog->aux->used_map_cnt;
4339 ulen = min_t(u32, info.nr_map_ids, ulen);
4341 u32 __user *user_map_ids = u64_to_user_ptr(info.map_ids);
4344 for (i = 0; i < ulen; i++)
4345 if (put_user(prog->aux->used_maps[i]->id,
4346 &user_map_ids[i])) {
4347 mutex_unlock(&prog->aux->used_maps_mutex);
4351 mutex_unlock(&prog->aux->used_maps_mutex);
4353 err = set_info_rec_size(&info);
4357 bpf_prog_get_stats(prog, &stats);
4358 info.run_time_ns = stats.nsecs;
4359 info.run_cnt = stats.cnt;
4360 info.recursion_misses = stats.misses;
4362 info.verified_insns = prog->aux->verified_insns;
4364 if (!bpf_capable()) {
4365 info.jited_prog_len = 0;
4366 info.xlated_prog_len = 0;
4367 info.nr_jited_ksyms = 0;
4368 info.nr_jited_func_lens = 0;
4369 info.nr_func_info = 0;
4370 info.nr_line_info = 0;
4371 info.nr_jited_line_info = 0;
4375 ulen = info.xlated_prog_len;
4376 info.xlated_prog_len = bpf_prog_insn_size(prog);
4377 if (info.xlated_prog_len && ulen) {
4378 struct bpf_insn *insns_sanitized;
4381 if (prog->blinded && !bpf_dump_raw_ok(file->f_cred)) {
4382 info.xlated_prog_insns = 0;
4385 insns_sanitized = bpf_insn_prepare_dump(prog, file->f_cred);
4386 if (!insns_sanitized)
4388 uinsns = u64_to_user_ptr(info.xlated_prog_insns);
4389 ulen = min_t(u32, info.xlated_prog_len, ulen);
4390 fault = copy_to_user(uinsns, insns_sanitized, ulen);
4391 kfree(insns_sanitized);
4396 if (bpf_prog_is_offloaded(prog->aux)) {
4397 err = bpf_prog_offload_info_fill(&info, prog);
4403 /* NOTE: the following code is supposed to be skipped for offload.
4404 * bpf_prog_offload_info_fill() is the place to fill similar fields
4407 ulen = info.jited_prog_len;
4408 if (prog->aux->func_cnt) {
4411 info.jited_prog_len = 0;
4412 for (i = 0; i < prog->aux->func_cnt; i++)
4413 info.jited_prog_len += prog->aux->func[i]->jited_len;
4415 info.jited_prog_len = prog->jited_len;
4418 if (info.jited_prog_len && ulen) {
4419 if (bpf_dump_raw_ok(file->f_cred)) {
4420 uinsns = u64_to_user_ptr(info.jited_prog_insns);
4421 ulen = min_t(u32, info.jited_prog_len, ulen);
4423 /* for multi-function programs, copy the JITed
4424 * instructions for all the functions
4426 if (prog->aux->func_cnt) {
4431 for (i = 0; i < prog->aux->func_cnt; i++) {
4432 len = prog->aux->func[i]->jited_len;
4433 len = min_t(u32, len, free);
4434 img = (u8 *) prog->aux->func[i]->bpf_func;
4435 if (copy_to_user(uinsns, img, len))
4443 if (copy_to_user(uinsns, prog->bpf_func, ulen))
4447 info.jited_prog_insns = 0;
4451 ulen = info.nr_jited_ksyms;
4452 info.nr_jited_ksyms = prog->aux->func_cnt ? : 1;
4454 if (bpf_dump_raw_ok(file->f_cred)) {
4455 unsigned long ksym_addr;
4456 u64 __user *user_ksyms;
4459 /* copy the address of the kernel symbol
4460 * corresponding to each function
4462 ulen = min_t(u32, info.nr_jited_ksyms, ulen);
4463 user_ksyms = u64_to_user_ptr(info.jited_ksyms);
4464 if (prog->aux->func_cnt) {
4465 for (i = 0; i < ulen; i++) {
4466 ksym_addr = (unsigned long)
4467 prog->aux->func[i]->bpf_func;
4468 if (put_user((u64) ksym_addr,
4473 ksym_addr = (unsigned long) prog->bpf_func;
4474 if (put_user((u64) ksym_addr, &user_ksyms[0]))
4478 info.jited_ksyms = 0;
4482 ulen = info.nr_jited_func_lens;
4483 info.nr_jited_func_lens = prog->aux->func_cnt ? : 1;
4485 if (bpf_dump_raw_ok(file->f_cred)) {
4486 u32 __user *user_lens;
4489 /* copy the JITed image lengths for each function */
4490 ulen = min_t(u32, info.nr_jited_func_lens, ulen);
4491 user_lens = u64_to_user_ptr(info.jited_func_lens);
4492 if (prog->aux->func_cnt) {
4493 for (i = 0; i < ulen; i++) {
4495 prog->aux->func[i]->jited_len;
4496 if (put_user(func_len, &user_lens[i]))
4500 func_len = prog->jited_len;
4501 if (put_user(func_len, &user_lens[0]))
4505 info.jited_func_lens = 0;
4510 info.btf_id = btf_obj_id(prog->aux->btf);
4511 info.attach_btf_id = prog->aux->attach_btf_id;
4513 info.attach_btf_obj_id = btf_obj_id(attach_btf);
4515 ulen = info.nr_func_info;
4516 info.nr_func_info = prog->aux->func_info_cnt;
4517 if (info.nr_func_info && ulen) {
4518 char __user *user_finfo;
4520 user_finfo = u64_to_user_ptr(info.func_info);
4521 ulen = min_t(u32, info.nr_func_info, ulen);
4522 if (copy_to_user(user_finfo, prog->aux->func_info,
4523 info.func_info_rec_size * ulen))
4527 ulen = info.nr_line_info;
4528 info.nr_line_info = prog->aux->nr_linfo;
4529 if (info.nr_line_info && ulen) {
4530 __u8 __user *user_linfo;
4532 user_linfo = u64_to_user_ptr(info.line_info);
4533 ulen = min_t(u32, info.nr_line_info, ulen);
4534 if (copy_to_user(user_linfo, prog->aux->linfo,
4535 info.line_info_rec_size * ulen))
4539 ulen = info.nr_jited_line_info;
4540 if (prog->aux->jited_linfo)
4541 info.nr_jited_line_info = prog->aux->nr_linfo;
4543 info.nr_jited_line_info = 0;
4544 if (info.nr_jited_line_info && ulen) {
4545 if (bpf_dump_raw_ok(file->f_cred)) {
4546 unsigned long line_addr;
4547 __u64 __user *user_linfo;
4550 user_linfo = u64_to_user_ptr(info.jited_line_info);
4551 ulen = min_t(u32, info.nr_jited_line_info, ulen);
4552 for (i = 0; i < ulen; i++) {
4553 line_addr = (unsigned long)prog->aux->jited_linfo[i];
4554 if (put_user((__u64)line_addr, &user_linfo[i]))
4558 info.jited_line_info = 0;
4562 ulen = info.nr_prog_tags;
4563 info.nr_prog_tags = prog->aux->func_cnt ? : 1;
4565 __u8 __user (*user_prog_tags)[BPF_TAG_SIZE];
4568 user_prog_tags = u64_to_user_ptr(info.prog_tags);
4569 ulen = min_t(u32, info.nr_prog_tags, ulen);
4570 if (prog->aux->func_cnt) {
4571 for (i = 0; i < ulen; i++) {
4572 if (copy_to_user(user_prog_tags[i],
4573 prog->aux->func[i]->tag,
4578 if (copy_to_user(user_prog_tags[0],
4579 prog->tag, BPF_TAG_SIZE))
4585 if (copy_to_user(uinfo, &info, info_len) ||
4586 put_user(info_len, &uattr->info.info_len))
4592 static int bpf_map_get_info_by_fd(struct file *file,
4593 struct bpf_map *map,
4594 const union bpf_attr *attr,
4595 union bpf_attr __user *uattr)
4597 struct bpf_map_info __user *uinfo = u64_to_user_ptr(attr->info.info);
4598 struct bpf_map_info info;
4599 u32 info_len = attr->info.info_len;
4602 err = bpf_check_uarg_tail_zero(USER_BPFPTR(uinfo), sizeof(info), info_len);
4605 info_len = min_t(u32, sizeof(info), info_len);
4607 memset(&info, 0, sizeof(info));
4608 info.type = map->map_type;
4610 info.key_size = map->key_size;
4611 info.value_size = map->value_size;
4612 info.max_entries = map->max_entries;
4613 info.map_flags = map->map_flags;
4614 info.map_extra = map->map_extra;
4615 memcpy(info.name, map->name, sizeof(map->name));
4618 info.btf_id = btf_obj_id(map->btf);
4619 info.btf_key_type_id = map->btf_key_type_id;
4620 info.btf_value_type_id = map->btf_value_type_id;
4622 info.btf_vmlinux_value_type_id = map->btf_vmlinux_value_type_id;
4624 if (bpf_map_is_offloaded(map)) {
4625 err = bpf_map_offload_info_fill(&info, map);
4630 if (copy_to_user(uinfo, &info, info_len) ||
4631 put_user(info_len, &uattr->info.info_len))
4637 static int bpf_btf_get_info_by_fd(struct file *file,
4639 const union bpf_attr *attr,
4640 union bpf_attr __user *uattr)
4642 struct bpf_btf_info __user *uinfo = u64_to_user_ptr(attr->info.info);
4643 u32 info_len = attr->info.info_len;
4646 err = bpf_check_uarg_tail_zero(USER_BPFPTR(uinfo), sizeof(*uinfo), info_len);
4650 return btf_get_info_by_fd(btf, attr, uattr);
4653 static int bpf_link_get_info_by_fd(struct file *file,
4654 struct bpf_link *link,
4655 const union bpf_attr *attr,
4656 union bpf_attr __user *uattr)
4658 struct bpf_link_info __user *uinfo = u64_to_user_ptr(attr->info.info);
4659 struct bpf_link_info info;
4660 u32 info_len = attr->info.info_len;
4663 err = bpf_check_uarg_tail_zero(USER_BPFPTR(uinfo), sizeof(info), info_len);
4666 info_len = min_t(u32, sizeof(info), info_len);
4668 memset(&info, 0, sizeof(info));
4669 if (copy_from_user(&info, uinfo, info_len))
4672 info.type = link->type;
4675 info.prog_id = link->prog->aux->id;
4677 if (link->ops->fill_link_info) {
4678 err = link->ops->fill_link_info(link, &info);
4683 if (copy_to_user(uinfo, &info, info_len) ||
4684 put_user(info_len, &uattr->info.info_len))
4691 #define BPF_OBJ_GET_INFO_BY_FD_LAST_FIELD info.info
4693 static int bpf_obj_get_info_by_fd(const union bpf_attr *attr,
4694 union bpf_attr __user *uattr)
4696 int ufd = attr->info.bpf_fd;
4700 if (CHECK_ATTR(BPF_OBJ_GET_INFO_BY_FD))
4707 if (f.file->f_op == &bpf_prog_fops)
4708 err = bpf_prog_get_info_by_fd(f.file, f.file->private_data, attr,
4710 else if (f.file->f_op == &bpf_map_fops)
4711 err = bpf_map_get_info_by_fd(f.file, f.file->private_data, attr,
4713 else if (f.file->f_op == &btf_fops)
4714 err = bpf_btf_get_info_by_fd(f.file, f.file->private_data, attr, uattr);
4715 else if (f.file->f_op == &bpf_link_fops)
4716 err = bpf_link_get_info_by_fd(f.file, f.file->private_data,
4725 #define BPF_BTF_LOAD_LAST_FIELD btf_log_true_size
4727 static int bpf_btf_load(const union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size)
4729 if (CHECK_ATTR(BPF_BTF_LOAD))
4735 return btf_new_fd(attr, uattr, uattr_size);
4738 #define BPF_BTF_GET_FD_BY_ID_LAST_FIELD btf_id
4740 static int bpf_btf_get_fd_by_id(const union bpf_attr *attr)
4742 if (CHECK_ATTR(BPF_BTF_GET_FD_BY_ID))
4745 if (!capable(CAP_SYS_ADMIN))
4748 return btf_get_fd_by_id(attr->btf_id);
4751 static int bpf_task_fd_query_copy(const union bpf_attr *attr,
4752 union bpf_attr __user *uattr,
4753 u32 prog_id, u32 fd_type,
4754 const char *buf, u64 probe_offset,
4757 char __user *ubuf = u64_to_user_ptr(attr->task_fd_query.buf);
4758 u32 len = buf ? strlen(buf) : 0, input_len;
4761 if (put_user(len, &uattr->task_fd_query.buf_len))
4763 input_len = attr->task_fd_query.buf_len;
4764 if (input_len && ubuf) {
4766 /* nothing to copy, just make ubuf NULL terminated */
4769 if (put_user(zero, ubuf))
4771 } else if (input_len >= len + 1) {
4772 /* ubuf can hold the string with NULL terminator */
4773 if (copy_to_user(ubuf, buf, len + 1))
4776 /* ubuf cannot hold the string with NULL terminator,
4777 * do a partial copy with NULL terminator.
4782 if (copy_to_user(ubuf, buf, input_len - 1))
4784 if (put_user(zero, ubuf + input_len - 1))
4789 if (put_user(prog_id, &uattr->task_fd_query.prog_id) ||
4790 put_user(fd_type, &uattr->task_fd_query.fd_type) ||
4791 put_user(probe_offset, &uattr->task_fd_query.probe_offset) ||
4792 put_user(probe_addr, &uattr->task_fd_query.probe_addr))
4798 #define BPF_TASK_FD_QUERY_LAST_FIELD task_fd_query.probe_addr
4800 static int bpf_task_fd_query(const union bpf_attr *attr,
4801 union bpf_attr __user *uattr)
4803 pid_t pid = attr->task_fd_query.pid;
4804 u32 fd = attr->task_fd_query.fd;
4805 const struct perf_event *event;
4806 struct task_struct *task;
4810 if (CHECK_ATTR(BPF_TASK_FD_QUERY))
4813 if (!capable(CAP_SYS_ADMIN))
4816 if (attr->task_fd_query.flags != 0)
4820 task = get_pid_task(find_vpid(pid), PIDTYPE_PID);
4826 file = fget_task(task, fd);
4827 put_task_struct(task);
4831 if (file->f_op == &bpf_link_fops) {
4832 struct bpf_link *link = file->private_data;
4834 if (link->ops == &bpf_raw_tp_link_lops) {
4835 struct bpf_raw_tp_link *raw_tp =
4836 container_of(link, struct bpf_raw_tp_link, link);
4837 struct bpf_raw_event_map *btp = raw_tp->btp;
4839 err = bpf_task_fd_query_copy(attr, uattr,
4840 raw_tp->link.prog->aux->id,
4841 BPF_FD_TYPE_RAW_TRACEPOINT,
4842 btp->tp->name, 0, 0);
4848 event = perf_get_event(file);
4849 if (!IS_ERR(event)) {
4850 u64 probe_offset, probe_addr;
4851 u32 prog_id, fd_type;
4854 err = bpf_get_perf_event_info(event, &prog_id, &fd_type,
4855 &buf, &probe_offset,
4858 err = bpf_task_fd_query_copy(attr, uattr, prog_id,
4872 #define BPF_MAP_BATCH_LAST_FIELD batch.flags
4874 #define BPF_DO_BATCH(fn, ...) \
4880 err = fn(__VA_ARGS__); \
4883 static int bpf_map_do_batch(const union bpf_attr *attr,
4884 union bpf_attr __user *uattr,
4887 bool has_read = cmd == BPF_MAP_LOOKUP_BATCH ||
4888 cmd == BPF_MAP_LOOKUP_AND_DELETE_BATCH;
4889 bool has_write = cmd != BPF_MAP_LOOKUP_BATCH;
4890 struct bpf_map *map;
4894 if (CHECK_ATTR(BPF_MAP_BATCH))
4897 ufd = attr->batch.map_fd;
4899 map = __bpf_map_get(f);
4901 return PTR_ERR(map);
4903 bpf_map_write_active_inc(map);
4904 if (has_read && !(map_get_sys_perms(map, f) & FMODE_CAN_READ)) {
4908 if (has_write && !(map_get_sys_perms(map, f) & FMODE_CAN_WRITE)) {
4913 if (cmd == BPF_MAP_LOOKUP_BATCH)
4914 BPF_DO_BATCH(map->ops->map_lookup_batch, map, attr, uattr);
4915 else if (cmd == BPF_MAP_LOOKUP_AND_DELETE_BATCH)
4916 BPF_DO_BATCH(map->ops->map_lookup_and_delete_batch, map, attr, uattr);
4917 else if (cmd == BPF_MAP_UPDATE_BATCH)
4918 BPF_DO_BATCH(map->ops->map_update_batch, map, f.file, attr, uattr);
4920 BPF_DO_BATCH(map->ops->map_delete_batch, map, attr, uattr);
4923 bpf_map_write_active_dec(map);
4928 #define BPF_LINK_CREATE_LAST_FIELD link_create.uprobe_multi.pid
4929 static int link_create(union bpf_attr *attr, bpfptr_t uattr)
4931 struct bpf_prog *prog;
4934 if (CHECK_ATTR(BPF_LINK_CREATE))
4937 if (attr->link_create.attach_type == BPF_STRUCT_OPS)
4938 return bpf_struct_ops_link_create(attr);
4940 prog = bpf_prog_get(attr->link_create.prog_fd);
4942 return PTR_ERR(prog);
4944 ret = bpf_prog_attach_check_attach_type(prog,
4945 attr->link_create.attach_type);
4949 switch (prog->type) {
4950 case BPF_PROG_TYPE_CGROUP_SKB:
4951 case BPF_PROG_TYPE_CGROUP_SOCK:
4952 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
4953 case BPF_PROG_TYPE_SOCK_OPS:
4954 case BPF_PROG_TYPE_CGROUP_DEVICE:
4955 case BPF_PROG_TYPE_CGROUP_SYSCTL:
4956 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
4957 ret = cgroup_bpf_link_attach(attr, prog);
4959 case BPF_PROG_TYPE_EXT:
4960 ret = bpf_tracing_prog_attach(prog,
4961 attr->link_create.target_fd,
4962 attr->link_create.target_btf_id,
4963 attr->link_create.tracing.cookie);
4965 case BPF_PROG_TYPE_LSM:
4966 case BPF_PROG_TYPE_TRACING:
4967 if (attr->link_create.attach_type != prog->expected_attach_type) {
4971 if (prog->expected_attach_type == BPF_TRACE_RAW_TP)
4972 ret = bpf_raw_tp_link_attach(prog, NULL);
4973 else if (prog->expected_attach_type == BPF_TRACE_ITER)
4974 ret = bpf_iter_link_attach(attr, uattr, prog);
4975 else if (prog->expected_attach_type == BPF_LSM_CGROUP)
4976 ret = cgroup_bpf_link_attach(attr, prog);
4978 ret = bpf_tracing_prog_attach(prog,
4979 attr->link_create.target_fd,
4980 attr->link_create.target_btf_id,
4981 attr->link_create.tracing.cookie);
4983 case BPF_PROG_TYPE_FLOW_DISSECTOR:
4984 case BPF_PROG_TYPE_SK_LOOKUP:
4985 ret = netns_bpf_link_create(attr, prog);
4988 case BPF_PROG_TYPE_XDP:
4989 ret = bpf_xdp_link_attach(attr, prog);
4991 case BPF_PROG_TYPE_SCHED_CLS:
4992 if (attr->link_create.attach_type == BPF_TCX_INGRESS ||
4993 attr->link_create.attach_type == BPF_TCX_EGRESS)
4994 ret = tcx_link_attach(attr, prog);
4996 ret = netkit_link_attach(attr, prog);
4998 case BPF_PROG_TYPE_NETFILTER:
4999 ret = bpf_nf_link_attach(attr, prog);
5002 case BPF_PROG_TYPE_PERF_EVENT:
5003 case BPF_PROG_TYPE_TRACEPOINT:
5004 ret = bpf_perf_link_attach(attr, prog);
5006 case BPF_PROG_TYPE_KPROBE:
5007 if (attr->link_create.attach_type == BPF_PERF_EVENT)
5008 ret = bpf_perf_link_attach(attr, prog);
5009 else if (attr->link_create.attach_type == BPF_TRACE_KPROBE_MULTI)
5010 ret = bpf_kprobe_multi_link_attach(attr, prog);
5011 else if (attr->link_create.attach_type == BPF_TRACE_UPROBE_MULTI)
5012 ret = bpf_uprobe_multi_link_attach(attr, prog);
5024 static int link_update_map(struct bpf_link *link, union bpf_attr *attr)
5026 struct bpf_map *new_map, *old_map = NULL;
5029 new_map = bpf_map_get(attr->link_update.new_map_fd);
5030 if (IS_ERR(new_map))
5031 return PTR_ERR(new_map);
5033 if (attr->link_update.flags & BPF_F_REPLACE) {
5034 old_map = bpf_map_get(attr->link_update.old_map_fd);
5035 if (IS_ERR(old_map)) {
5036 ret = PTR_ERR(old_map);
5039 } else if (attr->link_update.old_map_fd) {
5044 ret = link->ops->update_map(link, new_map, old_map);
5047 bpf_map_put(old_map);
5049 bpf_map_put(new_map);
5053 #define BPF_LINK_UPDATE_LAST_FIELD link_update.old_prog_fd
5055 static int link_update(union bpf_attr *attr)
5057 struct bpf_prog *old_prog = NULL, *new_prog;
5058 struct bpf_link *link;
5062 if (CHECK_ATTR(BPF_LINK_UPDATE))
5065 flags = attr->link_update.flags;
5066 if (flags & ~BPF_F_REPLACE)
5069 link = bpf_link_get_from_fd(attr->link_update.link_fd);
5071 return PTR_ERR(link);
5073 if (link->ops->update_map) {
5074 ret = link_update_map(link, attr);
5078 new_prog = bpf_prog_get(attr->link_update.new_prog_fd);
5079 if (IS_ERR(new_prog)) {
5080 ret = PTR_ERR(new_prog);
5084 if (flags & BPF_F_REPLACE) {
5085 old_prog = bpf_prog_get(attr->link_update.old_prog_fd);
5086 if (IS_ERR(old_prog)) {
5087 ret = PTR_ERR(old_prog);
5091 } else if (attr->link_update.old_prog_fd) {
5096 if (link->ops->update_prog)
5097 ret = link->ops->update_prog(link, new_prog, old_prog);
5103 bpf_prog_put(old_prog);
5105 bpf_prog_put(new_prog);
5107 bpf_link_put_direct(link);
5111 #define BPF_LINK_DETACH_LAST_FIELD link_detach.link_fd
5113 static int link_detach(union bpf_attr *attr)
5115 struct bpf_link *link;
5118 if (CHECK_ATTR(BPF_LINK_DETACH))
5121 link = bpf_link_get_from_fd(attr->link_detach.link_fd);
5123 return PTR_ERR(link);
5125 if (link->ops->detach)
5126 ret = link->ops->detach(link);
5130 bpf_link_put_direct(link);
5134 static struct bpf_link *bpf_link_inc_not_zero(struct bpf_link *link)
5136 return atomic64_fetch_add_unless(&link->refcnt, 1, 0) ? link : ERR_PTR(-ENOENT);
5139 struct bpf_link *bpf_link_by_id(u32 id)
5141 struct bpf_link *link;
5144 return ERR_PTR(-ENOENT);
5146 spin_lock_bh(&link_idr_lock);
5147 /* before link is "settled", ID is 0, pretend it doesn't exist yet */
5148 link = idr_find(&link_idr, id);
5151 link = bpf_link_inc_not_zero(link);
5153 link = ERR_PTR(-EAGAIN);
5155 link = ERR_PTR(-ENOENT);
5157 spin_unlock_bh(&link_idr_lock);
5161 struct bpf_link *bpf_link_get_curr_or_next(u32 *id)
5163 struct bpf_link *link;
5165 spin_lock_bh(&link_idr_lock);
5167 link = idr_get_next(&link_idr, id);
5169 link = bpf_link_inc_not_zero(link);
5175 spin_unlock_bh(&link_idr_lock);
5180 #define BPF_LINK_GET_FD_BY_ID_LAST_FIELD link_id
5182 static int bpf_link_get_fd_by_id(const union bpf_attr *attr)
5184 struct bpf_link *link;
5185 u32 id = attr->link_id;
5188 if (CHECK_ATTR(BPF_LINK_GET_FD_BY_ID))
5191 if (!capable(CAP_SYS_ADMIN))
5194 link = bpf_link_by_id(id);
5196 return PTR_ERR(link);
5198 fd = bpf_link_new_fd(link);
5200 bpf_link_put_direct(link);
5205 DEFINE_MUTEX(bpf_stats_enabled_mutex);
5207 static int bpf_stats_release(struct inode *inode, struct file *file)
5209 mutex_lock(&bpf_stats_enabled_mutex);
5210 static_key_slow_dec(&bpf_stats_enabled_key.key);
5211 mutex_unlock(&bpf_stats_enabled_mutex);
5215 static const struct file_operations bpf_stats_fops = {
5216 .release = bpf_stats_release,
5219 static int bpf_enable_runtime_stats(void)
5223 mutex_lock(&bpf_stats_enabled_mutex);
5225 /* Set a very high limit to avoid overflow */
5226 if (static_key_count(&bpf_stats_enabled_key.key) > INT_MAX / 2) {
5227 mutex_unlock(&bpf_stats_enabled_mutex);
5231 fd = anon_inode_getfd("bpf-stats", &bpf_stats_fops, NULL, O_CLOEXEC);
5233 static_key_slow_inc(&bpf_stats_enabled_key.key);
5235 mutex_unlock(&bpf_stats_enabled_mutex);
5239 #define BPF_ENABLE_STATS_LAST_FIELD enable_stats.type
5241 static int bpf_enable_stats(union bpf_attr *attr)
5244 if (CHECK_ATTR(BPF_ENABLE_STATS))
5247 if (!capable(CAP_SYS_ADMIN))
5250 switch (attr->enable_stats.type) {
5251 case BPF_STATS_RUN_TIME:
5252 return bpf_enable_runtime_stats();
5259 #define BPF_ITER_CREATE_LAST_FIELD iter_create.flags
5261 static int bpf_iter_create(union bpf_attr *attr)
5263 struct bpf_link *link;
5266 if (CHECK_ATTR(BPF_ITER_CREATE))
5269 if (attr->iter_create.flags)
5272 link = bpf_link_get_from_fd(attr->iter_create.link_fd);
5274 return PTR_ERR(link);
5276 err = bpf_iter_new_fd(link);
5277 bpf_link_put_direct(link);
5282 #define BPF_PROG_BIND_MAP_LAST_FIELD prog_bind_map.flags
5284 static int bpf_prog_bind_map(union bpf_attr *attr)
5286 struct bpf_prog *prog;
5287 struct bpf_map *map;
5288 struct bpf_map **used_maps_old, **used_maps_new;
5291 if (CHECK_ATTR(BPF_PROG_BIND_MAP))
5294 if (attr->prog_bind_map.flags)
5297 prog = bpf_prog_get(attr->prog_bind_map.prog_fd);
5299 return PTR_ERR(prog);
5301 map = bpf_map_get(attr->prog_bind_map.map_fd);
5307 mutex_lock(&prog->aux->used_maps_mutex);
5309 used_maps_old = prog->aux->used_maps;
5311 for (i = 0; i < prog->aux->used_map_cnt; i++)
5312 if (used_maps_old[i] == map) {
5317 used_maps_new = kmalloc_array(prog->aux->used_map_cnt + 1,
5318 sizeof(used_maps_new[0]),
5320 if (!used_maps_new) {
5325 memcpy(used_maps_new, used_maps_old,
5326 sizeof(used_maps_old[0]) * prog->aux->used_map_cnt);
5327 used_maps_new[prog->aux->used_map_cnt] = map;
5329 prog->aux->used_map_cnt++;
5330 prog->aux->used_maps = used_maps_new;
5332 kfree(used_maps_old);
5335 mutex_unlock(&prog->aux->used_maps_mutex);
5344 static int __sys_bpf(int cmd, bpfptr_t uattr, unsigned int size)
5346 union bpf_attr attr;
5349 err = bpf_check_uarg_tail_zero(uattr, sizeof(attr), size);
5352 size = min_t(u32, size, sizeof(attr));
5354 /* copy attributes from user space, may be less than sizeof(bpf_attr) */
5355 memset(&attr, 0, sizeof(attr));
5356 if (copy_from_bpfptr(&attr, uattr, size) != 0)
5359 err = security_bpf(cmd, &attr, size);
5364 case BPF_MAP_CREATE:
5365 err = map_create(&attr);
5367 case BPF_MAP_LOOKUP_ELEM:
5368 err = map_lookup_elem(&attr);
5370 case BPF_MAP_UPDATE_ELEM:
5371 err = map_update_elem(&attr, uattr);
5373 case BPF_MAP_DELETE_ELEM:
5374 err = map_delete_elem(&attr, uattr);
5376 case BPF_MAP_GET_NEXT_KEY:
5377 err = map_get_next_key(&attr);
5379 case BPF_MAP_FREEZE:
5380 err = map_freeze(&attr);
5383 err = bpf_prog_load(&attr, uattr, size);
5386 err = bpf_obj_pin(&attr);
5389 err = bpf_obj_get(&attr);
5391 case BPF_PROG_ATTACH:
5392 err = bpf_prog_attach(&attr);
5394 case BPF_PROG_DETACH:
5395 err = bpf_prog_detach(&attr);
5397 case BPF_PROG_QUERY:
5398 err = bpf_prog_query(&attr, uattr.user);
5400 case BPF_PROG_TEST_RUN:
5401 err = bpf_prog_test_run(&attr, uattr.user);
5403 case BPF_PROG_GET_NEXT_ID:
5404 err = bpf_obj_get_next_id(&attr, uattr.user,
5405 &prog_idr, &prog_idr_lock);
5407 case BPF_MAP_GET_NEXT_ID:
5408 err = bpf_obj_get_next_id(&attr, uattr.user,
5409 &map_idr, &map_idr_lock);
5411 case BPF_BTF_GET_NEXT_ID:
5412 err = bpf_obj_get_next_id(&attr, uattr.user,
5413 &btf_idr, &btf_idr_lock);
5415 case BPF_PROG_GET_FD_BY_ID:
5416 err = bpf_prog_get_fd_by_id(&attr);
5418 case BPF_MAP_GET_FD_BY_ID:
5419 err = bpf_map_get_fd_by_id(&attr);
5421 case BPF_OBJ_GET_INFO_BY_FD:
5422 err = bpf_obj_get_info_by_fd(&attr, uattr.user);
5424 case BPF_RAW_TRACEPOINT_OPEN:
5425 err = bpf_raw_tracepoint_open(&attr);
5428 err = bpf_btf_load(&attr, uattr, size);
5430 case BPF_BTF_GET_FD_BY_ID:
5431 err = bpf_btf_get_fd_by_id(&attr);
5433 case BPF_TASK_FD_QUERY:
5434 err = bpf_task_fd_query(&attr, uattr.user);
5436 case BPF_MAP_LOOKUP_AND_DELETE_ELEM:
5437 err = map_lookup_and_delete_elem(&attr);
5439 case BPF_MAP_LOOKUP_BATCH:
5440 err = bpf_map_do_batch(&attr, uattr.user, BPF_MAP_LOOKUP_BATCH);
5442 case BPF_MAP_LOOKUP_AND_DELETE_BATCH:
5443 err = bpf_map_do_batch(&attr, uattr.user,
5444 BPF_MAP_LOOKUP_AND_DELETE_BATCH);
5446 case BPF_MAP_UPDATE_BATCH:
5447 err = bpf_map_do_batch(&attr, uattr.user, BPF_MAP_UPDATE_BATCH);
5449 case BPF_MAP_DELETE_BATCH:
5450 err = bpf_map_do_batch(&attr, uattr.user, BPF_MAP_DELETE_BATCH);
5452 case BPF_LINK_CREATE:
5453 err = link_create(&attr, uattr);
5455 case BPF_LINK_UPDATE:
5456 err = link_update(&attr);
5458 case BPF_LINK_GET_FD_BY_ID:
5459 err = bpf_link_get_fd_by_id(&attr);
5461 case BPF_LINK_GET_NEXT_ID:
5462 err = bpf_obj_get_next_id(&attr, uattr.user,
5463 &link_idr, &link_idr_lock);
5465 case BPF_ENABLE_STATS:
5466 err = bpf_enable_stats(&attr);
5468 case BPF_ITER_CREATE:
5469 err = bpf_iter_create(&attr);
5471 case BPF_LINK_DETACH:
5472 err = link_detach(&attr);
5474 case BPF_PROG_BIND_MAP:
5475 err = bpf_prog_bind_map(&attr);
5485 SYSCALL_DEFINE3(bpf, int, cmd, union bpf_attr __user *, uattr, unsigned int, size)
5487 return __sys_bpf(cmd, USER_BPFPTR(uattr), size);
5490 static bool syscall_prog_is_valid_access(int off, int size,
5491 enum bpf_access_type type,
5492 const struct bpf_prog *prog,
5493 struct bpf_insn_access_aux *info)
5495 if (off < 0 || off >= U16_MAX)
5497 if (off % size != 0)
5502 BPF_CALL_3(bpf_sys_bpf, int, cmd, union bpf_attr *, attr, u32, attr_size)
5505 case BPF_MAP_CREATE:
5506 case BPF_MAP_DELETE_ELEM:
5507 case BPF_MAP_UPDATE_ELEM:
5508 case BPF_MAP_FREEZE:
5509 case BPF_MAP_GET_FD_BY_ID:
5512 case BPF_LINK_CREATE:
5513 case BPF_RAW_TRACEPOINT_OPEN:
5518 return __sys_bpf(cmd, KERNEL_BPFPTR(attr), attr_size);
5522 /* To shut up -Wmissing-prototypes.
5523 * This function is used by the kernel light skeleton
5524 * to load bpf programs when modules are loaded or during kernel boot.
5525 * See tools/lib/bpf/skel_internal.h
5527 int kern_sys_bpf(int cmd, union bpf_attr *attr, unsigned int size);
5529 int kern_sys_bpf(int cmd, union bpf_attr *attr, unsigned int size)
5531 struct bpf_prog * __maybe_unused prog;
5532 struct bpf_tramp_run_ctx __maybe_unused run_ctx;
5535 #ifdef CONFIG_BPF_JIT /* __bpf_prog_enter_sleepable used by trampoline and JIT */
5536 case BPF_PROG_TEST_RUN:
5537 if (attr->test.data_in || attr->test.data_out ||
5538 attr->test.ctx_out || attr->test.duration ||
5539 attr->test.repeat || attr->test.flags)
5542 prog = bpf_prog_get_type(attr->test.prog_fd, BPF_PROG_TYPE_SYSCALL);
5544 return PTR_ERR(prog);
5546 if (attr->test.ctx_size_in < prog->aux->max_ctx_offset ||
5547 attr->test.ctx_size_in > U16_MAX) {
5552 run_ctx.bpf_cookie = 0;
5553 if (!__bpf_prog_enter_sleepable_recur(prog, &run_ctx)) {
5554 /* recursion detected */
5555 __bpf_prog_exit_sleepable_recur(prog, 0, &run_ctx);
5559 attr->test.retval = bpf_prog_run(prog, (void *) (long) attr->test.ctx_in);
5560 __bpf_prog_exit_sleepable_recur(prog, 0 /* bpf_prog_run does runtime stats */,
5566 return ____bpf_sys_bpf(cmd, attr, size);
5569 EXPORT_SYMBOL(kern_sys_bpf);
5571 static const struct bpf_func_proto bpf_sys_bpf_proto = {
5572 .func = bpf_sys_bpf,
5574 .ret_type = RET_INTEGER,
5575 .arg1_type = ARG_ANYTHING,
5576 .arg2_type = ARG_PTR_TO_MEM | MEM_RDONLY,
5577 .arg3_type = ARG_CONST_SIZE,
5580 const struct bpf_func_proto * __weak
5581 tracing_prog_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
5583 return bpf_base_func_proto(func_id);
5586 BPF_CALL_1(bpf_sys_close, u32, fd)
5588 /* When bpf program calls this helper there should not be
5589 * an fdget() without matching completed fdput().
5590 * This helper is allowed in the following callchain only:
5591 * sys_bpf->prog_test_run->bpf_prog->bpf_sys_close
5593 return close_fd(fd);
5596 static const struct bpf_func_proto bpf_sys_close_proto = {
5597 .func = bpf_sys_close,
5599 .ret_type = RET_INTEGER,
5600 .arg1_type = ARG_ANYTHING,
5603 BPF_CALL_4(bpf_kallsyms_lookup_name, const char *, name, int, name_sz, int, flags, u64 *, res)
5608 if (name_sz <= 1 || name[name_sz - 1])
5611 if (!bpf_dump_raw_ok(current_cred()))
5614 *res = kallsyms_lookup_name(name);
5615 return *res ? 0 : -ENOENT;
5618 static const struct bpf_func_proto bpf_kallsyms_lookup_name_proto = {
5619 .func = bpf_kallsyms_lookup_name,
5621 .ret_type = RET_INTEGER,
5622 .arg1_type = ARG_PTR_TO_MEM,
5623 .arg2_type = ARG_CONST_SIZE_OR_ZERO,
5624 .arg3_type = ARG_ANYTHING,
5625 .arg4_type = ARG_PTR_TO_LONG,
5628 static const struct bpf_func_proto *
5629 syscall_prog_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
5632 case BPF_FUNC_sys_bpf:
5633 return !perfmon_capable() ? NULL : &bpf_sys_bpf_proto;
5634 case BPF_FUNC_btf_find_by_name_kind:
5635 return &bpf_btf_find_by_name_kind_proto;
5636 case BPF_FUNC_sys_close:
5637 return &bpf_sys_close_proto;
5638 case BPF_FUNC_kallsyms_lookup_name:
5639 return &bpf_kallsyms_lookup_name_proto;
5641 return tracing_prog_func_proto(func_id, prog);
5645 const struct bpf_verifier_ops bpf_syscall_verifier_ops = {
5646 .get_func_proto = syscall_prog_func_proto,
5647 .is_valid_access = syscall_prog_is_valid_access,
5650 const struct bpf_prog_ops bpf_syscall_prog_ops = {
5651 .test_run = bpf_prog_test_run_syscall,
5654 #ifdef CONFIG_SYSCTL
5655 static int bpf_stats_handler(struct ctl_table *table, int write,
5656 void *buffer, size_t *lenp, loff_t *ppos)
5658 struct static_key *key = (struct static_key *)table->data;
5659 static int saved_val;
5661 struct ctl_table tmp = {
5663 .maxlen = sizeof(val),
5664 .mode = table->mode,
5665 .extra1 = SYSCTL_ZERO,
5666 .extra2 = SYSCTL_ONE,
5669 if (write && !capable(CAP_SYS_ADMIN))
5672 mutex_lock(&bpf_stats_enabled_mutex);
5674 ret = proc_dointvec_minmax(&tmp, write, buffer, lenp, ppos);
5675 if (write && !ret && val != saved_val) {
5677 static_key_slow_inc(key);
5679 static_key_slow_dec(key);
5682 mutex_unlock(&bpf_stats_enabled_mutex);
5686 void __weak unpriv_ebpf_notify(int new_state)
5690 static int bpf_unpriv_handler(struct ctl_table *table, int write,
5691 void *buffer, size_t *lenp, loff_t *ppos)
5693 int ret, unpriv_enable = *(int *)table->data;
5694 bool locked_state = unpriv_enable == 1;
5695 struct ctl_table tmp = *table;
5697 if (write && !capable(CAP_SYS_ADMIN))
5700 tmp.data = &unpriv_enable;
5701 ret = proc_dointvec_minmax(&tmp, write, buffer, lenp, ppos);
5702 if (write && !ret) {
5703 if (locked_state && unpriv_enable != 1)
5705 *(int *)table->data = unpriv_enable;
5709 unpriv_ebpf_notify(unpriv_enable);
5714 static struct ctl_table bpf_syscall_table[] = {
5716 .procname = "unprivileged_bpf_disabled",
5717 .data = &sysctl_unprivileged_bpf_disabled,
5718 .maxlen = sizeof(sysctl_unprivileged_bpf_disabled),
5720 .proc_handler = bpf_unpriv_handler,
5721 .extra1 = SYSCTL_ZERO,
5722 .extra2 = SYSCTL_TWO,
5725 .procname = "bpf_stats_enabled",
5726 .data = &bpf_stats_enabled_key.key,
5728 .proc_handler = bpf_stats_handler,
5733 static int __init bpf_syscall_sysctl_init(void)
5735 register_sysctl_init("kernel", bpf_syscall_table);
5738 late_initcall(bpf_syscall_sysctl_init);
5739 #endif /* CONFIG_SYSCTL */