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 |
2577 BPF_F_TEST_REG_INVARIANTS))
2580 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS) &&
2581 (attr->prog_flags & BPF_F_ANY_ALIGNMENT) &&
2585 /* Intent here is for unprivileged_bpf_disabled to block BPF program
2586 * creation for unprivileged users; other actions depend
2587 * on fd availability and access to bpffs, so are dependent on
2588 * object creation success. Even with unprivileged BPF disabled,
2589 * capability checks are still carried out for these
2590 * and other operations.
2592 if (sysctl_unprivileged_bpf_disabled && !bpf_capable())
2595 if (attr->insn_cnt == 0 ||
2596 attr->insn_cnt > (bpf_capable() ? BPF_COMPLEXITY_LIMIT_INSNS : BPF_MAXINSNS))
2598 if (type != BPF_PROG_TYPE_SOCKET_FILTER &&
2599 type != BPF_PROG_TYPE_CGROUP_SKB &&
2603 if (is_net_admin_prog_type(type) && !capable(CAP_NET_ADMIN) && !capable(CAP_SYS_ADMIN))
2605 if (is_perfmon_prog_type(type) && !perfmon_capable())
2608 /* attach_prog_fd/attach_btf_obj_fd can specify fd of either bpf_prog
2609 * or btf, we need to check which one it is
2611 if (attr->attach_prog_fd) {
2612 dst_prog = bpf_prog_get(attr->attach_prog_fd);
2613 if (IS_ERR(dst_prog)) {
2615 attach_btf = btf_get_by_fd(attr->attach_btf_obj_fd);
2616 if (IS_ERR(attach_btf))
2618 if (!btf_is_kernel(attach_btf)) {
2619 /* attaching through specifying bpf_prog's BTF
2620 * objects directly might be supported eventually
2622 btf_put(attach_btf);
2626 } else if (attr->attach_btf_id) {
2627 /* fall back to vmlinux BTF, if BTF type ID is specified */
2628 attach_btf = bpf_get_btf_vmlinux();
2629 if (IS_ERR(attach_btf))
2630 return PTR_ERR(attach_btf);
2633 btf_get(attach_btf);
2636 bpf_prog_load_fixup_attach_type(attr);
2637 if (bpf_prog_load_check_attach(type, attr->expected_attach_type,
2638 attach_btf, attr->attach_btf_id,
2641 bpf_prog_put(dst_prog);
2643 btf_put(attach_btf);
2647 /* plain bpf_prog allocation */
2648 prog = bpf_prog_alloc(bpf_prog_size(attr->insn_cnt), GFP_USER);
2651 bpf_prog_put(dst_prog);
2653 btf_put(attach_btf);
2657 prog->expected_attach_type = attr->expected_attach_type;
2658 prog->aux->attach_btf = attach_btf;
2659 prog->aux->attach_btf_id = attr->attach_btf_id;
2660 prog->aux->dst_prog = dst_prog;
2661 prog->aux->dev_bound = !!attr->prog_ifindex;
2662 prog->aux->sleepable = attr->prog_flags & BPF_F_SLEEPABLE;
2663 prog->aux->xdp_has_frags = attr->prog_flags & BPF_F_XDP_HAS_FRAGS;
2665 err = security_bpf_prog_alloc(prog->aux);
2669 prog->aux->user = get_current_user();
2670 prog->len = attr->insn_cnt;
2673 if (copy_from_bpfptr(prog->insns,
2674 make_bpfptr(attr->insns, uattr.is_kernel),
2675 bpf_prog_insn_size(prog)) != 0)
2677 /* copy eBPF program license from user space */
2678 if (strncpy_from_bpfptr(license,
2679 make_bpfptr(attr->license, uattr.is_kernel),
2680 sizeof(license) - 1) < 0)
2682 license[sizeof(license) - 1] = 0;
2684 /* eBPF programs must be GPL compatible to use GPL-ed functions */
2685 prog->gpl_compatible = license_is_gpl_compatible(license) ? 1 : 0;
2687 prog->orig_prog = NULL;
2690 atomic64_set(&prog->aux->refcnt, 1);
2692 if (bpf_prog_is_dev_bound(prog->aux)) {
2693 err = bpf_prog_dev_bound_init(prog, attr);
2698 if (type == BPF_PROG_TYPE_EXT && dst_prog &&
2699 bpf_prog_is_dev_bound(dst_prog->aux)) {
2700 err = bpf_prog_dev_bound_inherit(prog, dst_prog);
2705 /* find program type: socket_filter vs tracing_filter */
2706 err = find_prog_type(type, prog);
2710 prog->aux->load_time = ktime_get_boottime_ns();
2711 err = bpf_obj_name_cpy(prog->aux->name, attr->prog_name,
2712 sizeof(attr->prog_name));
2716 /* run eBPF verifier */
2717 err = bpf_check(&prog, attr, uattr, uattr_size);
2719 goto free_used_maps;
2721 prog = bpf_prog_select_runtime(prog, &err);
2723 goto free_used_maps;
2725 err = bpf_prog_alloc_id(prog);
2727 goto free_used_maps;
2729 /* Upon success of bpf_prog_alloc_id(), the BPF prog is
2730 * effectively publicly exposed. However, retrieving via
2731 * bpf_prog_get_fd_by_id() will take another reference,
2732 * therefore it cannot be gone underneath us.
2734 * Only for the time /after/ successful bpf_prog_new_fd()
2735 * and before returning to userspace, we might just hold
2736 * one reference and any parallel close on that fd could
2737 * rip everything out. Hence, below notifications must
2738 * happen before bpf_prog_new_fd().
2740 * Also, any failure handling from this point onwards must
2741 * be using bpf_prog_put() given the program is exposed.
2743 bpf_prog_kallsyms_add(prog);
2744 perf_event_bpf_event(prog, PERF_BPF_EVENT_PROG_LOAD, 0);
2745 bpf_audit_prog(prog, BPF_AUDIT_LOAD);
2747 err = bpf_prog_new_fd(prog);
2753 /* In case we have subprogs, we need to wait for a grace
2754 * period before we can tear down JIT memory since symbols
2755 * are already exposed under kallsyms.
2757 __bpf_prog_put_noref(prog, prog->aux->real_func_cnt);
2760 free_uid(prog->aux->user);
2761 security_bpf_prog_free(prog->aux);
2763 if (prog->aux->attach_btf)
2764 btf_put(prog->aux->attach_btf);
2765 bpf_prog_free(prog);
2769 #define BPF_OBJ_LAST_FIELD path_fd
2771 static int bpf_obj_pin(const union bpf_attr *attr)
2775 if (CHECK_ATTR(BPF_OBJ) || attr->file_flags & ~BPF_F_PATH_FD)
2778 /* path_fd has to be accompanied by BPF_F_PATH_FD flag */
2779 if (!(attr->file_flags & BPF_F_PATH_FD) && attr->path_fd)
2782 path_fd = attr->file_flags & BPF_F_PATH_FD ? attr->path_fd : AT_FDCWD;
2783 return bpf_obj_pin_user(attr->bpf_fd, path_fd,
2784 u64_to_user_ptr(attr->pathname));
2787 static int bpf_obj_get(const union bpf_attr *attr)
2791 if (CHECK_ATTR(BPF_OBJ) || attr->bpf_fd != 0 ||
2792 attr->file_flags & ~(BPF_OBJ_FLAG_MASK | BPF_F_PATH_FD))
2795 /* path_fd has to be accompanied by BPF_F_PATH_FD flag */
2796 if (!(attr->file_flags & BPF_F_PATH_FD) && attr->path_fd)
2799 path_fd = attr->file_flags & BPF_F_PATH_FD ? attr->path_fd : AT_FDCWD;
2800 return bpf_obj_get_user(path_fd, u64_to_user_ptr(attr->pathname),
2804 void bpf_link_init(struct bpf_link *link, enum bpf_link_type type,
2805 const struct bpf_link_ops *ops, struct bpf_prog *prog)
2807 atomic64_set(&link->refcnt, 1);
2814 static void bpf_link_free_id(int id)
2819 spin_lock_bh(&link_idr_lock);
2820 idr_remove(&link_idr, id);
2821 spin_unlock_bh(&link_idr_lock);
2824 /* Clean up bpf_link and corresponding anon_inode file and FD. After
2825 * anon_inode is created, bpf_link can't be just kfree()'d due to deferred
2826 * anon_inode's release() call. This helper marks bpf_link as
2827 * defunct, releases anon_inode file and puts reserved FD. bpf_prog's refcnt
2828 * is not decremented, it's the responsibility of a calling code that failed
2829 * to complete bpf_link initialization.
2830 * This helper eventually calls link's dealloc callback, but does not call
2831 * link's release callback.
2833 void bpf_link_cleanup(struct bpf_link_primer *primer)
2835 primer->link->prog = NULL;
2836 bpf_link_free_id(primer->id);
2838 put_unused_fd(primer->fd);
2841 void bpf_link_inc(struct bpf_link *link)
2843 atomic64_inc(&link->refcnt);
2846 /* bpf_link_free is guaranteed to be called from process context */
2847 static void bpf_link_free(struct bpf_link *link)
2849 bpf_link_free_id(link->id);
2851 /* detach BPF program, clean up used resources */
2852 link->ops->release(link);
2853 bpf_prog_put(link->prog);
2855 /* free bpf_link and its containing memory */
2856 link->ops->dealloc(link);
2859 static void bpf_link_put_deferred(struct work_struct *work)
2861 struct bpf_link *link = container_of(work, struct bpf_link, work);
2863 bpf_link_free(link);
2866 /* bpf_link_put might be called from atomic context. It needs to be called
2867 * from sleepable context in order to acquire sleeping locks during the process.
2869 void bpf_link_put(struct bpf_link *link)
2871 if (!atomic64_dec_and_test(&link->refcnt))
2874 INIT_WORK(&link->work, bpf_link_put_deferred);
2875 schedule_work(&link->work);
2877 EXPORT_SYMBOL(bpf_link_put);
2879 static void bpf_link_put_direct(struct bpf_link *link)
2881 if (!atomic64_dec_and_test(&link->refcnt))
2883 bpf_link_free(link);
2886 static int bpf_link_release(struct inode *inode, struct file *filp)
2888 struct bpf_link *link = filp->private_data;
2890 bpf_link_put_direct(link);
2894 #ifdef CONFIG_PROC_FS
2895 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type)
2896 #define BPF_MAP_TYPE(_id, _ops)
2897 #define BPF_LINK_TYPE(_id, _name) [_id] = #_name,
2898 static const char *bpf_link_type_strs[] = {
2899 [BPF_LINK_TYPE_UNSPEC] = "<invalid>",
2900 #include <linux/bpf_types.h>
2902 #undef BPF_PROG_TYPE
2904 #undef BPF_LINK_TYPE
2906 static void bpf_link_show_fdinfo(struct seq_file *m, struct file *filp)
2908 const struct bpf_link *link = filp->private_data;
2909 const struct bpf_prog *prog = link->prog;
2910 char prog_tag[sizeof(prog->tag) * 2 + 1] = { };
2915 bpf_link_type_strs[link->type],
2918 bin2hex(prog_tag, prog->tag, sizeof(prog->tag));
2925 if (link->ops->show_fdinfo)
2926 link->ops->show_fdinfo(link, m);
2930 static const struct file_operations bpf_link_fops = {
2931 #ifdef CONFIG_PROC_FS
2932 .show_fdinfo = bpf_link_show_fdinfo,
2934 .release = bpf_link_release,
2935 .read = bpf_dummy_read,
2936 .write = bpf_dummy_write,
2939 static int bpf_link_alloc_id(struct bpf_link *link)
2943 idr_preload(GFP_KERNEL);
2944 spin_lock_bh(&link_idr_lock);
2945 id = idr_alloc_cyclic(&link_idr, link, 1, INT_MAX, GFP_ATOMIC);
2946 spin_unlock_bh(&link_idr_lock);
2952 /* Prepare bpf_link to be exposed to user-space by allocating anon_inode file,
2953 * reserving unused FD and allocating ID from link_idr. This is to be paired
2954 * with bpf_link_settle() to install FD and ID and expose bpf_link to
2955 * user-space, if bpf_link is successfully attached. If not, bpf_link and
2956 * pre-allocated resources are to be freed with bpf_cleanup() call. All the
2957 * transient state is passed around in struct bpf_link_primer.
2958 * This is preferred way to create and initialize bpf_link, especially when
2959 * there are complicated and expensive operations in between creating bpf_link
2960 * itself and attaching it to BPF hook. By using bpf_link_prime() and
2961 * bpf_link_settle() kernel code using bpf_link doesn't have to perform
2962 * expensive (and potentially failing) roll back operations in a rare case
2963 * that file, FD, or ID can't be allocated.
2965 int bpf_link_prime(struct bpf_link *link, struct bpf_link_primer *primer)
2970 fd = get_unused_fd_flags(O_CLOEXEC);
2975 id = bpf_link_alloc_id(link);
2981 file = anon_inode_getfile("bpf_link", &bpf_link_fops, link, O_CLOEXEC);
2983 bpf_link_free_id(id);
2985 return PTR_ERR(file);
2988 primer->link = link;
2989 primer->file = file;
2995 int bpf_link_settle(struct bpf_link_primer *primer)
2997 /* make bpf_link fetchable by ID */
2998 spin_lock_bh(&link_idr_lock);
2999 primer->link->id = primer->id;
3000 spin_unlock_bh(&link_idr_lock);
3001 /* make bpf_link fetchable by FD */
3002 fd_install(primer->fd, primer->file);
3003 /* pass through installed FD */
3007 int bpf_link_new_fd(struct bpf_link *link)
3009 return anon_inode_getfd("bpf-link", &bpf_link_fops, link, O_CLOEXEC);
3012 struct bpf_link *bpf_link_get_from_fd(u32 ufd)
3014 struct fd f = fdget(ufd);
3015 struct bpf_link *link;
3018 return ERR_PTR(-EBADF);
3019 if (f.file->f_op != &bpf_link_fops) {
3021 return ERR_PTR(-EINVAL);
3024 link = f.file->private_data;
3030 EXPORT_SYMBOL(bpf_link_get_from_fd);
3032 static void bpf_tracing_link_release(struct bpf_link *link)
3034 struct bpf_tracing_link *tr_link =
3035 container_of(link, struct bpf_tracing_link, link.link);
3037 WARN_ON_ONCE(bpf_trampoline_unlink_prog(&tr_link->link,
3038 tr_link->trampoline));
3040 bpf_trampoline_put(tr_link->trampoline);
3042 /* tgt_prog is NULL if target is a kernel function */
3043 if (tr_link->tgt_prog)
3044 bpf_prog_put(tr_link->tgt_prog);
3047 static void bpf_tracing_link_dealloc(struct bpf_link *link)
3049 struct bpf_tracing_link *tr_link =
3050 container_of(link, struct bpf_tracing_link, link.link);
3055 static void bpf_tracing_link_show_fdinfo(const struct bpf_link *link,
3056 struct seq_file *seq)
3058 struct bpf_tracing_link *tr_link =
3059 container_of(link, struct bpf_tracing_link, link.link);
3060 u32 target_btf_id, target_obj_id;
3062 bpf_trampoline_unpack_key(tr_link->trampoline->key,
3063 &target_obj_id, &target_btf_id);
3065 "attach_type:\t%d\n"
3066 "target_obj_id:\t%u\n"
3067 "target_btf_id:\t%u\n",
3068 tr_link->attach_type,
3073 static int bpf_tracing_link_fill_link_info(const struct bpf_link *link,
3074 struct bpf_link_info *info)
3076 struct bpf_tracing_link *tr_link =
3077 container_of(link, struct bpf_tracing_link, link.link);
3079 info->tracing.attach_type = tr_link->attach_type;
3080 bpf_trampoline_unpack_key(tr_link->trampoline->key,
3081 &info->tracing.target_obj_id,
3082 &info->tracing.target_btf_id);
3087 static const struct bpf_link_ops bpf_tracing_link_lops = {
3088 .release = bpf_tracing_link_release,
3089 .dealloc = bpf_tracing_link_dealloc,
3090 .show_fdinfo = bpf_tracing_link_show_fdinfo,
3091 .fill_link_info = bpf_tracing_link_fill_link_info,
3094 static int bpf_tracing_prog_attach(struct bpf_prog *prog,
3099 struct bpf_link_primer link_primer;
3100 struct bpf_prog *tgt_prog = NULL;
3101 struct bpf_trampoline *tr = NULL;
3102 struct bpf_tracing_link *link;
3106 switch (prog->type) {
3107 case BPF_PROG_TYPE_TRACING:
3108 if (prog->expected_attach_type != BPF_TRACE_FENTRY &&
3109 prog->expected_attach_type != BPF_TRACE_FEXIT &&
3110 prog->expected_attach_type != BPF_MODIFY_RETURN) {
3115 case BPF_PROG_TYPE_EXT:
3116 if (prog->expected_attach_type != 0) {
3121 case BPF_PROG_TYPE_LSM:
3122 if (prog->expected_attach_type != BPF_LSM_MAC) {
3132 if (!!tgt_prog_fd != !!btf_id) {
3138 /* For now we only allow new targets for BPF_PROG_TYPE_EXT */
3139 if (prog->type != BPF_PROG_TYPE_EXT) {
3144 tgt_prog = bpf_prog_get(tgt_prog_fd);
3145 if (IS_ERR(tgt_prog)) {
3146 err = PTR_ERR(tgt_prog);
3151 key = bpf_trampoline_compute_key(tgt_prog, NULL, btf_id);
3154 link = kzalloc(sizeof(*link), GFP_USER);
3159 bpf_link_init(&link->link.link, BPF_LINK_TYPE_TRACING,
3160 &bpf_tracing_link_lops, prog);
3161 link->attach_type = prog->expected_attach_type;
3162 link->link.cookie = bpf_cookie;
3164 mutex_lock(&prog->aux->dst_mutex);
3166 /* There are a few possible cases here:
3168 * - if prog->aux->dst_trampoline is set, the program was just loaded
3169 * and not yet attached to anything, so we can use the values stored
3172 * - if prog->aux->dst_trampoline is NULL, the program has already been
3173 * attached to a target and its initial target was cleared (below)
3175 * - if tgt_prog != NULL, the caller specified tgt_prog_fd +
3176 * target_btf_id using the link_create API.
3178 * - if tgt_prog == NULL when this function was called using the old
3179 * raw_tracepoint_open API, and we need a target from prog->aux
3181 * - if prog->aux->dst_trampoline and tgt_prog is NULL, the program
3182 * was detached and is going for re-attachment.
3184 if (!prog->aux->dst_trampoline && !tgt_prog) {
3186 * Allow re-attach for TRACING and LSM programs. If it's
3187 * currently linked, bpf_trampoline_link_prog will fail.
3188 * EXT programs need to specify tgt_prog_fd, so they
3189 * re-attach in separate code path.
3191 if (prog->type != BPF_PROG_TYPE_TRACING &&
3192 prog->type != BPF_PROG_TYPE_LSM) {
3196 btf_id = prog->aux->attach_btf_id;
3197 key = bpf_trampoline_compute_key(NULL, prog->aux->attach_btf, btf_id);
3200 if (!prog->aux->dst_trampoline ||
3201 (key && key != prog->aux->dst_trampoline->key)) {
3202 /* If there is no saved target, or the specified target is
3203 * different from the destination specified at load time, we
3204 * need a new trampoline and a check for compatibility
3206 struct bpf_attach_target_info tgt_info = {};
3208 err = bpf_check_attach_target(NULL, prog, tgt_prog, btf_id,
3213 if (tgt_info.tgt_mod) {
3214 module_put(prog->aux->mod);
3215 prog->aux->mod = tgt_info.tgt_mod;
3218 tr = bpf_trampoline_get(key, &tgt_info);
3224 /* The caller didn't specify a target, or the target was the
3225 * same as the destination supplied during program load. This
3226 * means we can reuse the trampoline and reference from program
3227 * load time, and there is no need to allocate a new one. This
3228 * can only happen once for any program, as the saved values in
3229 * prog->aux are cleared below.
3231 tr = prog->aux->dst_trampoline;
3232 tgt_prog = prog->aux->dst_prog;
3235 err = bpf_link_prime(&link->link.link, &link_primer);
3239 err = bpf_trampoline_link_prog(&link->link, tr);
3241 bpf_link_cleanup(&link_primer);
3246 link->tgt_prog = tgt_prog;
3247 link->trampoline = tr;
3249 /* Always clear the trampoline and target prog from prog->aux to make
3250 * sure the original attach destination is not kept alive after a
3251 * program is (re-)attached to another target.
3253 if (prog->aux->dst_prog &&
3254 (tgt_prog_fd || tr != prog->aux->dst_trampoline))
3255 /* got extra prog ref from syscall, or attaching to different prog */
3256 bpf_prog_put(prog->aux->dst_prog);
3257 if (prog->aux->dst_trampoline && tr != prog->aux->dst_trampoline)
3258 /* we allocated a new trampoline, so free the old one */
3259 bpf_trampoline_put(prog->aux->dst_trampoline);
3261 prog->aux->dst_prog = NULL;
3262 prog->aux->dst_trampoline = NULL;
3263 mutex_unlock(&prog->aux->dst_mutex);
3265 return bpf_link_settle(&link_primer);
3267 if (tr && tr != prog->aux->dst_trampoline)
3268 bpf_trampoline_put(tr);
3269 mutex_unlock(&prog->aux->dst_mutex);
3272 if (tgt_prog_fd && tgt_prog)
3273 bpf_prog_put(tgt_prog);
3277 struct bpf_raw_tp_link {
3278 struct bpf_link link;
3279 struct bpf_raw_event_map *btp;
3282 static void bpf_raw_tp_link_release(struct bpf_link *link)
3284 struct bpf_raw_tp_link *raw_tp =
3285 container_of(link, struct bpf_raw_tp_link, link);
3287 bpf_probe_unregister(raw_tp->btp, raw_tp->link.prog);
3288 bpf_put_raw_tracepoint(raw_tp->btp);
3291 static void bpf_raw_tp_link_dealloc(struct bpf_link *link)
3293 struct bpf_raw_tp_link *raw_tp =
3294 container_of(link, struct bpf_raw_tp_link, link);
3299 static void bpf_raw_tp_link_show_fdinfo(const struct bpf_link *link,
3300 struct seq_file *seq)
3302 struct bpf_raw_tp_link *raw_tp_link =
3303 container_of(link, struct bpf_raw_tp_link, link);
3307 raw_tp_link->btp->tp->name);
3310 static int bpf_copy_to_user(char __user *ubuf, const char *buf, u32 ulen,
3313 if (ulen >= len + 1) {
3314 if (copy_to_user(ubuf, buf, len + 1))
3319 if (copy_to_user(ubuf, buf, ulen - 1))
3321 if (put_user(zero, ubuf + ulen - 1))
3329 static int bpf_raw_tp_link_fill_link_info(const struct bpf_link *link,
3330 struct bpf_link_info *info)
3332 struct bpf_raw_tp_link *raw_tp_link =
3333 container_of(link, struct bpf_raw_tp_link, link);
3334 char __user *ubuf = u64_to_user_ptr(info->raw_tracepoint.tp_name);
3335 const char *tp_name = raw_tp_link->btp->tp->name;
3336 u32 ulen = info->raw_tracepoint.tp_name_len;
3337 size_t tp_len = strlen(tp_name);
3342 info->raw_tracepoint.tp_name_len = tp_len + 1;
3347 return bpf_copy_to_user(ubuf, tp_name, ulen, tp_len);
3350 static const struct bpf_link_ops bpf_raw_tp_link_lops = {
3351 .release = bpf_raw_tp_link_release,
3352 .dealloc = bpf_raw_tp_link_dealloc,
3353 .show_fdinfo = bpf_raw_tp_link_show_fdinfo,
3354 .fill_link_info = bpf_raw_tp_link_fill_link_info,
3357 #ifdef CONFIG_PERF_EVENTS
3358 struct bpf_perf_link {
3359 struct bpf_link link;
3360 struct file *perf_file;
3363 static void bpf_perf_link_release(struct bpf_link *link)
3365 struct bpf_perf_link *perf_link = container_of(link, struct bpf_perf_link, link);
3366 struct perf_event *event = perf_link->perf_file->private_data;
3368 perf_event_free_bpf_prog(event);
3369 fput(perf_link->perf_file);
3372 static void bpf_perf_link_dealloc(struct bpf_link *link)
3374 struct bpf_perf_link *perf_link = container_of(link, struct bpf_perf_link, link);
3379 static int bpf_perf_link_fill_common(const struct perf_event *event,
3380 char __user *uname, u32 ulen,
3381 u64 *probe_offset, u64 *probe_addr,
3382 u32 *fd_type, unsigned long *missed)
3392 err = bpf_get_perf_event_info(event, &prog_id, fd_type, &buf,
3393 probe_offset, probe_addr, missed);
3400 err = bpf_copy_to_user(uname, buf, ulen, len);
3406 if (put_user(zero, uname))
3412 #ifdef CONFIG_KPROBE_EVENTS
3413 static int bpf_perf_link_fill_kprobe(const struct perf_event *event,
3414 struct bpf_link_info *info)
3416 unsigned long missed;
3422 uname = u64_to_user_ptr(info->perf_event.kprobe.func_name);
3423 ulen = info->perf_event.kprobe.name_len;
3424 err = bpf_perf_link_fill_common(event, uname, ulen, &offset, &addr,
3428 if (type == BPF_FD_TYPE_KRETPROBE)
3429 info->perf_event.type = BPF_PERF_EVENT_KRETPROBE;
3431 info->perf_event.type = BPF_PERF_EVENT_KPROBE;
3433 info->perf_event.kprobe.offset = offset;
3434 info->perf_event.kprobe.missed = missed;
3435 if (!kallsyms_show_value(current_cred()))
3437 info->perf_event.kprobe.addr = addr;
3442 #ifdef CONFIG_UPROBE_EVENTS
3443 static int bpf_perf_link_fill_uprobe(const struct perf_event *event,
3444 struct bpf_link_info *info)
3451 uname = u64_to_user_ptr(info->perf_event.uprobe.file_name);
3452 ulen = info->perf_event.uprobe.name_len;
3453 err = bpf_perf_link_fill_common(event, uname, ulen, &offset, &addr,
3458 if (type == BPF_FD_TYPE_URETPROBE)
3459 info->perf_event.type = BPF_PERF_EVENT_URETPROBE;
3461 info->perf_event.type = BPF_PERF_EVENT_UPROBE;
3462 info->perf_event.uprobe.offset = offset;
3467 static int bpf_perf_link_fill_probe(const struct perf_event *event,
3468 struct bpf_link_info *info)
3470 #ifdef CONFIG_KPROBE_EVENTS
3471 if (event->tp_event->flags & TRACE_EVENT_FL_KPROBE)
3472 return bpf_perf_link_fill_kprobe(event, info);
3474 #ifdef CONFIG_UPROBE_EVENTS
3475 if (event->tp_event->flags & TRACE_EVENT_FL_UPROBE)
3476 return bpf_perf_link_fill_uprobe(event, info);
3481 static int bpf_perf_link_fill_tracepoint(const struct perf_event *event,
3482 struct bpf_link_info *info)
3487 uname = u64_to_user_ptr(info->perf_event.tracepoint.tp_name);
3488 ulen = info->perf_event.tracepoint.name_len;
3489 info->perf_event.type = BPF_PERF_EVENT_TRACEPOINT;
3490 return bpf_perf_link_fill_common(event, uname, ulen, NULL, NULL, NULL, NULL);
3493 static int bpf_perf_link_fill_perf_event(const struct perf_event *event,
3494 struct bpf_link_info *info)
3496 info->perf_event.event.type = event->attr.type;
3497 info->perf_event.event.config = event->attr.config;
3498 info->perf_event.type = BPF_PERF_EVENT_EVENT;
3502 static int bpf_perf_link_fill_link_info(const struct bpf_link *link,
3503 struct bpf_link_info *info)
3505 struct bpf_perf_link *perf_link;
3506 const struct perf_event *event;
3508 perf_link = container_of(link, struct bpf_perf_link, link);
3509 event = perf_get_event(perf_link->perf_file);
3511 return PTR_ERR(event);
3513 switch (event->prog->type) {
3514 case BPF_PROG_TYPE_PERF_EVENT:
3515 return bpf_perf_link_fill_perf_event(event, info);
3516 case BPF_PROG_TYPE_TRACEPOINT:
3517 return bpf_perf_link_fill_tracepoint(event, info);
3518 case BPF_PROG_TYPE_KPROBE:
3519 return bpf_perf_link_fill_probe(event, info);
3525 static const struct bpf_link_ops bpf_perf_link_lops = {
3526 .release = bpf_perf_link_release,
3527 .dealloc = bpf_perf_link_dealloc,
3528 .fill_link_info = bpf_perf_link_fill_link_info,
3531 static int bpf_perf_link_attach(const union bpf_attr *attr, struct bpf_prog *prog)
3533 struct bpf_link_primer link_primer;
3534 struct bpf_perf_link *link;
3535 struct perf_event *event;
3536 struct file *perf_file;
3539 if (attr->link_create.flags)
3542 perf_file = perf_event_get(attr->link_create.target_fd);
3543 if (IS_ERR(perf_file))
3544 return PTR_ERR(perf_file);
3546 link = kzalloc(sizeof(*link), GFP_USER);
3551 bpf_link_init(&link->link, BPF_LINK_TYPE_PERF_EVENT, &bpf_perf_link_lops, prog);
3552 link->perf_file = perf_file;
3554 err = bpf_link_prime(&link->link, &link_primer);
3560 event = perf_file->private_data;
3561 err = perf_event_set_bpf_prog(event, prog, attr->link_create.perf_event.bpf_cookie);
3563 bpf_link_cleanup(&link_primer);
3566 /* perf_event_set_bpf_prog() doesn't take its own refcnt on prog */
3569 return bpf_link_settle(&link_primer);
3576 static int bpf_perf_link_attach(const union bpf_attr *attr, struct bpf_prog *prog)
3580 #endif /* CONFIG_PERF_EVENTS */
3582 static int bpf_raw_tp_link_attach(struct bpf_prog *prog,
3583 const char __user *user_tp_name)
3585 struct bpf_link_primer link_primer;
3586 struct bpf_raw_tp_link *link;
3587 struct bpf_raw_event_map *btp;
3588 const char *tp_name;
3592 switch (prog->type) {
3593 case BPF_PROG_TYPE_TRACING:
3594 case BPF_PROG_TYPE_EXT:
3595 case BPF_PROG_TYPE_LSM:
3597 /* The attach point for this category of programs
3598 * should be specified via btf_id during program load.
3601 if (prog->type == BPF_PROG_TYPE_TRACING &&
3602 prog->expected_attach_type == BPF_TRACE_RAW_TP) {
3603 tp_name = prog->aux->attach_func_name;
3606 return bpf_tracing_prog_attach(prog, 0, 0, 0);
3607 case BPF_PROG_TYPE_RAW_TRACEPOINT:
3608 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
3609 if (strncpy_from_user(buf, user_tp_name, sizeof(buf) - 1) < 0)
3611 buf[sizeof(buf) - 1] = 0;
3618 btp = bpf_get_raw_tracepoint(tp_name);
3622 link = kzalloc(sizeof(*link), GFP_USER);
3627 bpf_link_init(&link->link, BPF_LINK_TYPE_RAW_TRACEPOINT,
3628 &bpf_raw_tp_link_lops, prog);
3631 err = bpf_link_prime(&link->link, &link_primer);
3637 err = bpf_probe_register(link->btp, prog);
3639 bpf_link_cleanup(&link_primer);
3643 return bpf_link_settle(&link_primer);
3646 bpf_put_raw_tracepoint(btp);
3650 #define BPF_RAW_TRACEPOINT_OPEN_LAST_FIELD raw_tracepoint.prog_fd
3652 static int bpf_raw_tracepoint_open(const union bpf_attr *attr)
3654 struct bpf_prog *prog;
3657 if (CHECK_ATTR(BPF_RAW_TRACEPOINT_OPEN))
3660 prog = bpf_prog_get(attr->raw_tracepoint.prog_fd);
3662 return PTR_ERR(prog);
3664 fd = bpf_raw_tp_link_attach(prog, u64_to_user_ptr(attr->raw_tracepoint.name));
3670 static enum bpf_prog_type
3671 attach_type_to_prog_type(enum bpf_attach_type attach_type)
3673 switch (attach_type) {
3674 case BPF_CGROUP_INET_INGRESS:
3675 case BPF_CGROUP_INET_EGRESS:
3676 return BPF_PROG_TYPE_CGROUP_SKB;
3677 case BPF_CGROUP_INET_SOCK_CREATE:
3678 case BPF_CGROUP_INET_SOCK_RELEASE:
3679 case BPF_CGROUP_INET4_POST_BIND:
3680 case BPF_CGROUP_INET6_POST_BIND:
3681 return BPF_PROG_TYPE_CGROUP_SOCK;
3682 case BPF_CGROUP_INET4_BIND:
3683 case BPF_CGROUP_INET6_BIND:
3684 case BPF_CGROUP_INET4_CONNECT:
3685 case BPF_CGROUP_INET6_CONNECT:
3686 case BPF_CGROUP_UNIX_CONNECT:
3687 case BPF_CGROUP_INET4_GETPEERNAME:
3688 case BPF_CGROUP_INET6_GETPEERNAME:
3689 case BPF_CGROUP_UNIX_GETPEERNAME:
3690 case BPF_CGROUP_INET4_GETSOCKNAME:
3691 case BPF_CGROUP_INET6_GETSOCKNAME:
3692 case BPF_CGROUP_UNIX_GETSOCKNAME:
3693 case BPF_CGROUP_UDP4_SENDMSG:
3694 case BPF_CGROUP_UDP6_SENDMSG:
3695 case BPF_CGROUP_UNIX_SENDMSG:
3696 case BPF_CGROUP_UDP4_RECVMSG:
3697 case BPF_CGROUP_UDP6_RECVMSG:
3698 case BPF_CGROUP_UNIX_RECVMSG:
3699 return BPF_PROG_TYPE_CGROUP_SOCK_ADDR;
3700 case BPF_CGROUP_SOCK_OPS:
3701 return BPF_PROG_TYPE_SOCK_OPS;
3702 case BPF_CGROUP_DEVICE:
3703 return BPF_PROG_TYPE_CGROUP_DEVICE;
3704 case BPF_SK_MSG_VERDICT:
3705 return BPF_PROG_TYPE_SK_MSG;
3706 case BPF_SK_SKB_STREAM_PARSER:
3707 case BPF_SK_SKB_STREAM_VERDICT:
3708 case BPF_SK_SKB_VERDICT:
3709 return BPF_PROG_TYPE_SK_SKB;
3710 case BPF_LIRC_MODE2:
3711 return BPF_PROG_TYPE_LIRC_MODE2;
3712 case BPF_FLOW_DISSECTOR:
3713 return BPF_PROG_TYPE_FLOW_DISSECTOR;
3714 case BPF_CGROUP_SYSCTL:
3715 return BPF_PROG_TYPE_CGROUP_SYSCTL;
3716 case BPF_CGROUP_GETSOCKOPT:
3717 case BPF_CGROUP_SETSOCKOPT:
3718 return BPF_PROG_TYPE_CGROUP_SOCKOPT;
3719 case BPF_TRACE_ITER:
3720 case BPF_TRACE_RAW_TP:
3721 case BPF_TRACE_FENTRY:
3722 case BPF_TRACE_FEXIT:
3723 case BPF_MODIFY_RETURN:
3724 return BPF_PROG_TYPE_TRACING;
3726 return BPF_PROG_TYPE_LSM;
3728 return BPF_PROG_TYPE_SK_LOOKUP;
3730 return BPF_PROG_TYPE_XDP;
3731 case BPF_LSM_CGROUP:
3732 return BPF_PROG_TYPE_LSM;
3733 case BPF_TCX_INGRESS:
3734 case BPF_TCX_EGRESS:
3735 case BPF_NETKIT_PRIMARY:
3736 case BPF_NETKIT_PEER:
3737 return BPF_PROG_TYPE_SCHED_CLS;
3739 return BPF_PROG_TYPE_UNSPEC;
3743 static int bpf_prog_attach_check_attach_type(const struct bpf_prog *prog,
3744 enum bpf_attach_type attach_type)
3746 enum bpf_prog_type ptype;
3748 switch (prog->type) {
3749 case BPF_PROG_TYPE_CGROUP_SOCK:
3750 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
3751 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3752 case BPF_PROG_TYPE_SK_LOOKUP:
3753 return attach_type == prog->expected_attach_type ? 0 : -EINVAL;
3754 case BPF_PROG_TYPE_CGROUP_SKB:
3755 if (!capable(CAP_NET_ADMIN))
3756 /* cg-skb progs can be loaded by unpriv user.
3757 * check permissions at attach time.
3760 return prog->enforce_expected_attach_type &&
3761 prog->expected_attach_type != attach_type ?
3763 case BPF_PROG_TYPE_EXT:
3765 case BPF_PROG_TYPE_NETFILTER:
3766 if (attach_type != BPF_NETFILTER)
3769 case BPF_PROG_TYPE_PERF_EVENT:
3770 case BPF_PROG_TYPE_TRACEPOINT:
3771 if (attach_type != BPF_PERF_EVENT)
3774 case BPF_PROG_TYPE_KPROBE:
3775 if (prog->expected_attach_type == BPF_TRACE_KPROBE_MULTI &&
3776 attach_type != BPF_TRACE_KPROBE_MULTI)
3778 if (prog->expected_attach_type == BPF_TRACE_UPROBE_MULTI &&
3779 attach_type != BPF_TRACE_UPROBE_MULTI)
3781 if (attach_type != BPF_PERF_EVENT &&
3782 attach_type != BPF_TRACE_KPROBE_MULTI &&
3783 attach_type != BPF_TRACE_UPROBE_MULTI)
3786 case BPF_PROG_TYPE_SCHED_CLS:
3787 if (attach_type != BPF_TCX_INGRESS &&
3788 attach_type != BPF_TCX_EGRESS &&
3789 attach_type != BPF_NETKIT_PRIMARY &&
3790 attach_type != BPF_NETKIT_PEER)
3794 ptype = attach_type_to_prog_type(attach_type);
3795 if (ptype == BPF_PROG_TYPE_UNSPEC || ptype != prog->type)
3801 #define BPF_PROG_ATTACH_LAST_FIELD expected_revision
3803 #define BPF_F_ATTACH_MASK_BASE \
3804 (BPF_F_ALLOW_OVERRIDE | \
3805 BPF_F_ALLOW_MULTI | \
3808 #define BPF_F_ATTACH_MASK_MPROG \
3815 static int bpf_prog_attach(const union bpf_attr *attr)
3817 enum bpf_prog_type ptype;
3818 struct bpf_prog *prog;
3821 if (CHECK_ATTR(BPF_PROG_ATTACH))
3824 ptype = attach_type_to_prog_type(attr->attach_type);
3825 if (ptype == BPF_PROG_TYPE_UNSPEC)
3827 if (bpf_mprog_supported(ptype)) {
3828 if (attr->attach_flags & ~BPF_F_ATTACH_MASK_MPROG)
3831 if (attr->attach_flags & ~BPF_F_ATTACH_MASK_BASE)
3833 if (attr->relative_fd ||
3834 attr->expected_revision)
3838 prog = bpf_prog_get_type(attr->attach_bpf_fd, ptype);
3840 return PTR_ERR(prog);
3842 if (bpf_prog_attach_check_attach_type(prog, attr->attach_type)) {
3848 case BPF_PROG_TYPE_SK_SKB:
3849 case BPF_PROG_TYPE_SK_MSG:
3850 ret = sock_map_get_from_fd(attr, prog);
3852 case BPF_PROG_TYPE_LIRC_MODE2:
3853 ret = lirc_prog_attach(attr, prog);
3855 case BPF_PROG_TYPE_FLOW_DISSECTOR:
3856 ret = netns_bpf_prog_attach(attr, prog);
3858 case BPF_PROG_TYPE_CGROUP_DEVICE:
3859 case BPF_PROG_TYPE_CGROUP_SKB:
3860 case BPF_PROG_TYPE_CGROUP_SOCK:
3861 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
3862 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3863 case BPF_PROG_TYPE_CGROUP_SYSCTL:
3864 case BPF_PROG_TYPE_SOCK_OPS:
3865 case BPF_PROG_TYPE_LSM:
3866 if (ptype == BPF_PROG_TYPE_LSM &&
3867 prog->expected_attach_type != BPF_LSM_CGROUP)
3870 ret = cgroup_bpf_prog_attach(attr, ptype, prog);
3872 case BPF_PROG_TYPE_SCHED_CLS:
3873 if (attr->attach_type == BPF_TCX_INGRESS ||
3874 attr->attach_type == BPF_TCX_EGRESS)
3875 ret = tcx_prog_attach(attr, prog);
3877 ret = netkit_prog_attach(attr, prog);
3888 #define BPF_PROG_DETACH_LAST_FIELD expected_revision
3890 static int bpf_prog_detach(const union bpf_attr *attr)
3892 struct bpf_prog *prog = NULL;
3893 enum bpf_prog_type ptype;
3896 if (CHECK_ATTR(BPF_PROG_DETACH))
3899 ptype = attach_type_to_prog_type(attr->attach_type);
3900 if (bpf_mprog_supported(ptype)) {
3901 if (ptype == BPF_PROG_TYPE_UNSPEC)
3903 if (attr->attach_flags & ~BPF_F_ATTACH_MASK_MPROG)
3905 if (attr->attach_bpf_fd) {
3906 prog = bpf_prog_get_type(attr->attach_bpf_fd, ptype);
3908 return PTR_ERR(prog);
3910 } else if (attr->attach_flags ||
3911 attr->relative_fd ||
3912 attr->expected_revision) {
3917 case BPF_PROG_TYPE_SK_MSG:
3918 case BPF_PROG_TYPE_SK_SKB:
3919 ret = sock_map_prog_detach(attr, ptype);
3921 case BPF_PROG_TYPE_LIRC_MODE2:
3922 ret = lirc_prog_detach(attr);
3924 case BPF_PROG_TYPE_FLOW_DISSECTOR:
3925 ret = netns_bpf_prog_detach(attr, ptype);
3927 case BPF_PROG_TYPE_CGROUP_DEVICE:
3928 case BPF_PROG_TYPE_CGROUP_SKB:
3929 case BPF_PROG_TYPE_CGROUP_SOCK:
3930 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
3931 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3932 case BPF_PROG_TYPE_CGROUP_SYSCTL:
3933 case BPF_PROG_TYPE_SOCK_OPS:
3934 case BPF_PROG_TYPE_LSM:
3935 ret = cgroup_bpf_prog_detach(attr, ptype);
3937 case BPF_PROG_TYPE_SCHED_CLS:
3938 if (attr->attach_type == BPF_TCX_INGRESS ||
3939 attr->attach_type == BPF_TCX_EGRESS)
3940 ret = tcx_prog_detach(attr, prog);
3942 ret = netkit_prog_detach(attr, prog);
3953 #define BPF_PROG_QUERY_LAST_FIELD query.revision
3955 static int bpf_prog_query(const union bpf_attr *attr,
3956 union bpf_attr __user *uattr)
3958 if (!capable(CAP_NET_ADMIN))
3960 if (CHECK_ATTR(BPF_PROG_QUERY))
3962 if (attr->query.query_flags & ~BPF_F_QUERY_EFFECTIVE)
3965 switch (attr->query.attach_type) {
3966 case BPF_CGROUP_INET_INGRESS:
3967 case BPF_CGROUP_INET_EGRESS:
3968 case BPF_CGROUP_INET_SOCK_CREATE:
3969 case BPF_CGROUP_INET_SOCK_RELEASE:
3970 case BPF_CGROUP_INET4_BIND:
3971 case BPF_CGROUP_INET6_BIND:
3972 case BPF_CGROUP_INET4_POST_BIND:
3973 case BPF_CGROUP_INET6_POST_BIND:
3974 case BPF_CGROUP_INET4_CONNECT:
3975 case BPF_CGROUP_INET6_CONNECT:
3976 case BPF_CGROUP_UNIX_CONNECT:
3977 case BPF_CGROUP_INET4_GETPEERNAME:
3978 case BPF_CGROUP_INET6_GETPEERNAME:
3979 case BPF_CGROUP_UNIX_GETPEERNAME:
3980 case BPF_CGROUP_INET4_GETSOCKNAME:
3981 case BPF_CGROUP_INET6_GETSOCKNAME:
3982 case BPF_CGROUP_UNIX_GETSOCKNAME:
3983 case BPF_CGROUP_UDP4_SENDMSG:
3984 case BPF_CGROUP_UDP6_SENDMSG:
3985 case BPF_CGROUP_UNIX_SENDMSG:
3986 case BPF_CGROUP_UDP4_RECVMSG:
3987 case BPF_CGROUP_UDP6_RECVMSG:
3988 case BPF_CGROUP_UNIX_RECVMSG:
3989 case BPF_CGROUP_SOCK_OPS:
3990 case BPF_CGROUP_DEVICE:
3991 case BPF_CGROUP_SYSCTL:
3992 case BPF_CGROUP_GETSOCKOPT:
3993 case BPF_CGROUP_SETSOCKOPT:
3994 case BPF_LSM_CGROUP:
3995 return cgroup_bpf_prog_query(attr, uattr);
3996 case BPF_LIRC_MODE2:
3997 return lirc_prog_query(attr, uattr);
3998 case BPF_FLOW_DISSECTOR:
4000 return netns_bpf_prog_query(attr, uattr);
4001 case BPF_SK_SKB_STREAM_PARSER:
4002 case BPF_SK_SKB_STREAM_VERDICT:
4003 case BPF_SK_MSG_VERDICT:
4004 case BPF_SK_SKB_VERDICT:
4005 return sock_map_bpf_prog_query(attr, uattr);
4006 case BPF_TCX_INGRESS:
4007 case BPF_TCX_EGRESS:
4008 return tcx_prog_query(attr, uattr);
4009 case BPF_NETKIT_PRIMARY:
4010 case BPF_NETKIT_PEER:
4011 return netkit_prog_query(attr, uattr);
4017 #define BPF_PROG_TEST_RUN_LAST_FIELD test.batch_size
4019 static int bpf_prog_test_run(const union bpf_attr *attr,
4020 union bpf_attr __user *uattr)
4022 struct bpf_prog *prog;
4023 int ret = -ENOTSUPP;
4025 if (CHECK_ATTR(BPF_PROG_TEST_RUN))
4028 if ((attr->test.ctx_size_in && !attr->test.ctx_in) ||
4029 (!attr->test.ctx_size_in && attr->test.ctx_in))
4032 if ((attr->test.ctx_size_out && !attr->test.ctx_out) ||
4033 (!attr->test.ctx_size_out && attr->test.ctx_out))
4036 prog = bpf_prog_get(attr->test.prog_fd);
4038 return PTR_ERR(prog);
4040 if (prog->aux->ops->test_run)
4041 ret = prog->aux->ops->test_run(prog, attr, uattr);
4047 #define BPF_OBJ_GET_NEXT_ID_LAST_FIELD next_id
4049 static int bpf_obj_get_next_id(const union bpf_attr *attr,
4050 union bpf_attr __user *uattr,
4054 u32 next_id = attr->start_id;
4057 if (CHECK_ATTR(BPF_OBJ_GET_NEXT_ID) || next_id >= INT_MAX)
4060 if (!capable(CAP_SYS_ADMIN))
4065 if (!idr_get_next(idr, &next_id))
4067 spin_unlock_bh(lock);
4070 err = put_user(next_id, &uattr->next_id);
4075 struct bpf_map *bpf_map_get_curr_or_next(u32 *id)
4077 struct bpf_map *map;
4079 spin_lock_bh(&map_idr_lock);
4081 map = idr_get_next(&map_idr, id);
4083 map = __bpf_map_inc_not_zero(map, false);
4089 spin_unlock_bh(&map_idr_lock);
4094 struct bpf_prog *bpf_prog_get_curr_or_next(u32 *id)
4096 struct bpf_prog *prog;
4098 spin_lock_bh(&prog_idr_lock);
4100 prog = idr_get_next(&prog_idr, id);
4102 prog = bpf_prog_inc_not_zero(prog);
4108 spin_unlock_bh(&prog_idr_lock);
4113 #define BPF_PROG_GET_FD_BY_ID_LAST_FIELD prog_id
4115 struct bpf_prog *bpf_prog_by_id(u32 id)
4117 struct bpf_prog *prog;
4120 return ERR_PTR(-ENOENT);
4122 spin_lock_bh(&prog_idr_lock);
4123 prog = idr_find(&prog_idr, id);
4125 prog = bpf_prog_inc_not_zero(prog);
4127 prog = ERR_PTR(-ENOENT);
4128 spin_unlock_bh(&prog_idr_lock);
4132 static int bpf_prog_get_fd_by_id(const union bpf_attr *attr)
4134 struct bpf_prog *prog;
4135 u32 id = attr->prog_id;
4138 if (CHECK_ATTR(BPF_PROG_GET_FD_BY_ID))
4141 if (!capable(CAP_SYS_ADMIN))
4144 prog = bpf_prog_by_id(id);
4146 return PTR_ERR(prog);
4148 fd = bpf_prog_new_fd(prog);
4155 #define BPF_MAP_GET_FD_BY_ID_LAST_FIELD open_flags
4157 static int bpf_map_get_fd_by_id(const union bpf_attr *attr)
4159 struct bpf_map *map;
4160 u32 id = attr->map_id;
4164 if (CHECK_ATTR(BPF_MAP_GET_FD_BY_ID) ||
4165 attr->open_flags & ~BPF_OBJ_FLAG_MASK)
4168 if (!capable(CAP_SYS_ADMIN))
4171 f_flags = bpf_get_file_flag(attr->open_flags);
4175 spin_lock_bh(&map_idr_lock);
4176 map = idr_find(&map_idr, id);
4178 map = __bpf_map_inc_not_zero(map, true);
4180 map = ERR_PTR(-ENOENT);
4181 spin_unlock_bh(&map_idr_lock);
4184 return PTR_ERR(map);
4186 fd = bpf_map_new_fd(map, f_flags);
4188 bpf_map_put_with_uref(map);
4193 static const struct bpf_map *bpf_map_from_imm(const struct bpf_prog *prog,
4194 unsigned long addr, u32 *off,
4197 const struct bpf_map *map;
4200 mutex_lock(&prog->aux->used_maps_mutex);
4201 for (i = 0, *off = 0; i < prog->aux->used_map_cnt; i++) {
4202 map = prog->aux->used_maps[i];
4203 if (map == (void *)addr) {
4204 *type = BPF_PSEUDO_MAP_FD;
4207 if (!map->ops->map_direct_value_meta)
4209 if (!map->ops->map_direct_value_meta(map, addr, off)) {
4210 *type = BPF_PSEUDO_MAP_VALUE;
4217 mutex_unlock(&prog->aux->used_maps_mutex);
4221 static struct bpf_insn *bpf_insn_prepare_dump(const struct bpf_prog *prog,
4222 const struct cred *f_cred)
4224 const struct bpf_map *map;
4225 struct bpf_insn *insns;
4231 insns = kmemdup(prog->insnsi, bpf_prog_insn_size(prog),
4236 for (i = 0; i < prog->len; i++) {
4237 code = insns[i].code;
4239 if (code == (BPF_JMP | BPF_TAIL_CALL)) {
4240 insns[i].code = BPF_JMP | BPF_CALL;
4241 insns[i].imm = BPF_FUNC_tail_call;
4244 if (code == (BPF_JMP | BPF_CALL) ||
4245 code == (BPF_JMP | BPF_CALL_ARGS)) {
4246 if (code == (BPF_JMP | BPF_CALL_ARGS))
4247 insns[i].code = BPF_JMP | BPF_CALL;
4248 if (!bpf_dump_raw_ok(f_cred))
4252 if (BPF_CLASS(code) == BPF_LDX && BPF_MODE(code) == BPF_PROBE_MEM) {
4253 insns[i].code = BPF_LDX | BPF_SIZE(code) | BPF_MEM;
4257 if (code != (BPF_LD | BPF_IMM | BPF_DW))
4260 imm = ((u64)insns[i + 1].imm << 32) | (u32)insns[i].imm;
4261 map = bpf_map_from_imm(prog, imm, &off, &type);
4263 insns[i].src_reg = type;
4264 insns[i].imm = map->id;
4265 insns[i + 1].imm = off;
4273 static int set_info_rec_size(struct bpf_prog_info *info)
4276 * Ensure info.*_rec_size is the same as kernel expected size
4280 * Only allow zero *_rec_size if both _rec_size and _cnt are
4281 * zero. In this case, the kernel will set the expected
4282 * _rec_size back to the info.
4285 if ((info->nr_func_info || info->func_info_rec_size) &&
4286 info->func_info_rec_size != sizeof(struct bpf_func_info))
4289 if ((info->nr_line_info || info->line_info_rec_size) &&
4290 info->line_info_rec_size != sizeof(struct bpf_line_info))
4293 if ((info->nr_jited_line_info || info->jited_line_info_rec_size) &&
4294 info->jited_line_info_rec_size != sizeof(__u64))
4297 info->func_info_rec_size = sizeof(struct bpf_func_info);
4298 info->line_info_rec_size = sizeof(struct bpf_line_info);
4299 info->jited_line_info_rec_size = sizeof(__u64);
4304 static int bpf_prog_get_info_by_fd(struct file *file,
4305 struct bpf_prog *prog,
4306 const union bpf_attr *attr,
4307 union bpf_attr __user *uattr)
4309 struct bpf_prog_info __user *uinfo = u64_to_user_ptr(attr->info.info);
4310 struct btf *attach_btf = bpf_prog_get_target_btf(prog);
4311 struct bpf_prog_info info;
4312 u32 info_len = attr->info.info_len;
4313 struct bpf_prog_kstats stats;
4314 char __user *uinsns;
4318 err = bpf_check_uarg_tail_zero(USER_BPFPTR(uinfo), sizeof(info), info_len);
4321 info_len = min_t(u32, sizeof(info), info_len);
4323 memset(&info, 0, sizeof(info));
4324 if (copy_from_user(&info, uinfo, info_len))
4327 info.type = prog->type;
4328 info.id = prog->aux->id;
4329 info.load_time = prog->aux->load_time;
4330 info.created_by_uid = from_kuid_munged(current_user_ns(),
4331 prog->aux->user->uid);
4332 info.gpl_compatible = prog->gpl_compatible;
4334 memcpy(info.tag, prog->tag, sizeof(prog->tag));
4335 memcpy(info.name, prog->aux->name, sizeof(prog->aux->name));
4337 mutex_lock(&prog->aux->used_maps_mutex);
4338 ulen = info.nr_map_ids;
4339 info.nr_map_ids = prog->aux->used_map_cnt;
4340 ulen = min_t(u32, info.nr_map_ids, ulen);
4342 u32 __user *user_map_ids = u64_to_user_ptr(info.map_ids);
4345 for (i = 0; i < ulen; i++)
4346 if (put_user(prog->aux->used_maps[i]->id,
4347 &user_map_ids[i])) {
4348 mutex_unlock(&prog->aux->used_maps_mutex);
4352 mutex_unlock(&prog->aux->used_maps_mutex);
4354 err = set_info_rec_size(&info);
4358 bpf_prog_get_stats(prog, &stats);
4359 info.run_time_ns = stats.nsecs;
4360 info.run_cnt = stats.cnt;
4361 info.recursion_misses = stats.misses;
4363 info.verified_insns = prog->aux->verified_insns;
4365 if (!bpf_capable()) {
4366 info.jited_prog_len = 0;
4367 info.xlated_prog_len = 0;
4368 info.nr_jited_ksyms = 0;
4369 info.nr_jited_func_lens = 0;
4370 info.nr_func_info = 0;
4371 info.nr_line_info = 0;
4372 info.nr_jited_line_info = 0;
4376 ulen = info.xlated_prog_len;
4377 info.xlated_prog_len = bpf_prog_insn_size(prog);
4378 if (info.xlated_prog_len && ulen) {
4379 struct bpf_insn *insns_sanitized;
4382 if (prog->blinded && !bpf_dump_raw_ok(file->f_cred)) {
4383 info.xlated_prog_insns = 0;
4386 insns_sanitized = bpf_insn_prepare_dump(prog, file->f_cred);
4387 if (!insns_sanitized)
4389 uinsns = u64_to_user_ptr(info.xlated_prog_insns);
4390 ulen = min_t(u32, info.xlated_prog_len, ulen);
4391 fault = copy_to_user(uinsns, insns_sanitized, ulen);
4392 kfree(insns_sanitized);
4397 if (bpf_prog_is_offloaded(prog->aux)) {
4398 err = bpf_prog_offload_info_fill(&info, prog);
4404 /* NOTE: the following code is supposed to be skipped for offload.
4405 * bpf_prog_offload_info_fill() is the place to fill similar fields
4408 ulen = info.jited_prog_len;
4409 if (prog->aux->func_cnt) {
4412 info.jited_prog_len = 0;
4413 for (i = 0; i < prog->aux->func_cnt; i++)
4414 info.jited_prog_len += prog->aux->func[i]->jited_len;
4416 info.jited_prog_len = prog->jited_len;
4419 if (info.jited_prog_len && ulen) {
4420 if (bpf_dump_raw_ok(file->f_cred)) {
4421 uinsns = u64_to_user_ptr(info.jited_prog_insns);
4422 ulen = min_t(u32, info.jited_prog_len, ulen);
4424 /* for multi-function programs, copy the JITed
4425 * instructions for all the functions
4427 if (prog->aux->func_cnt) {
4432 for (i = 0; i < prog->aux->func_cnt; i++) {
4433 len = prog->aux->func[i]->jited_len;
4434 len = min_t(u32, len, free);
4435 img = (u8 *) prog->aux->func[i]->bpf_func;
4436 if (copy_to_user(uinsns, img, len))
4444 if (copy_to_user(uinsns, prog->bpf_func, ulen))
4448 info.jited_prog_insns = 0;
4452 ulen = info.nr_jited_ksyms;
4453 info.nr_jited_ksyms = prog->aux->func_cnt ? : 1;
4455 if (bpf_dump_raw_ok(file->f_cred)) {
4456 unsigned long ksym_addr;
4457 u64 __user *user_ksyms;
4460 /* copy the address of the kernel symbol
4461 * corresponding to each function
4463 ulen = min_t(u32, info.nr_jited_ksyms, ulen);
4464 user_ksyms = u64_to_user_ptr(info.jited_ksyms);
4465 if (prog->aux->func_cnt) {
4466 for (i = 0; i < ulen; i++) {
4467 ksym_addr = (unsigned long)
4468 prog->aux->func[i]->bpf_func;
4469 if (put_user((u64) ksym_addr,
4474 ksym_addr = (unsigned long) prog->bpf_func;
4475 if (put_user((u64) ksym_addr, &user_ksyms[0]))
4479 info.jited_ksyms = 0;
4483 ulen = info.nr_jited_func_lens;
4484 info.nr_jited_func_lens = prog->aux->func_cnt ? : 1;
4486 if (bpf_dump_raw_ok(file->f_cred)) {
4487 u32 __user *user_lens;
4490 /* copy the JITed image lengths for each function */
4491 ulen = min_t(u32, info.nr_jited_func_lens, ulen);
4492 user_lens = u64_to_user_ptr(info.jited_func_lens);
4493 if (prog->aux->func_cnt) {
4494 for (i = 0; i < ulen; i++) {
4496 prog->aux->func[i]->jited_len;
4497 if (put_user(func_len, &user_lens[i]))
4501 func_len = prog->jited_len;
4502 if (put_user(func_len, &user_lens[0]))
4506 info.jited_func_lens = 0;
4511 info.btf_id = btf_obj_id(prog->aux->btf);
4512 info.attach_btf_id = prog->aux->attach_btf_id;
4514 info.attach_btf_obj_id = btf_obj_id(attach_btf);
4516 ulen = info.nr_func_info;
4517 info.nr_func_info = prog->aux->func_info_cnt;
4518 if (info.nr_func_info && ulen) {
4519 char __user *user_finfo;
4521 user_finfo = u64_to_user_ptr(info.func_info);
4522 ulen = min_t(u32, info.nr_func_info, ulen);
4523 if (copy_to_user(user_finfo, prog->aux->func_info,
4524 info.func_info_rec_size * ulen))
4528 ulen = info.nr_line_info;
4529 info.nr_line_info = prog->aux->nr_linfo;
4530 if (info.nr_line_info && ulen) {
4531 __u8 __user *user_linfo;
4533 user_linfo = u64_to_user_ptr(info.line_info);
4534 ulen = min_t(u32, info.nr_line_info, ulen);
4535 if (copy_to_user(user_linfo, prog->aux->linfo,
4536 info.line_info_rec_size * ulen))
4540 ulen = info.nr_jited_line_info;
4541 if (prog->aux->jited_linfo)
4542 info.nr_jited_line_info = prog->aux->nr_linfo;
4544 info.nr_jited_line_info = 0;
4545 if (info.nr_jited_line_info && ulen) {
4546 if (bpf_dump_raw_ok(file->f_cred)) {
4547 unsigned long line_addr;
4548 __u64 __user *user_linfo;
4551 user_linfo = u64_to_user_ptr(info.jited_line_info);
4552 ulen = min_t(u32, info.nr_jited_line_info, ulen);
4553 for (i = 0; i < ulen; i++) {
4554 line_addr = (unsigned long)prog->aux->jited_linfo[i];
4555 if (put_user((__u64)line_addr, &user_linfo[i]))
4559 info.jited_line_info = 0;
4563 ulen = info.nr_prog_tags;
4564 info.nr_prog_tags = prog->aux->func_cnt ? : 1;
4566 __u8 __user (*user_prog_tags)[BPF_TAG_SIZE];
4569 user_prog_tags = u64_to_user_ptr(info.prog_tags);
4570 ulen = min_t(u32, info.nr_prog_tags, ulen);
4571 if (prog->aux->func_cnt) {
4572 for (i = 0; i < ulen; i++) {
4573 if (copy_to_user(user_prog_tags[i],
4574 prog->aux->func[i]->tag,
4579 if (copy_to_user(user_prog_tags[0],
4580 prog->tag, BPF_TAG_SIZE))
4586 if (copy_to_user(uinfo, &info, info_len) ||
4587 put_user(info_len, &uattr->info.info_len))
4593 static int bpf_map_get_info_by_fd(struct file *file,
4594 struct bpf_map *map,
4595 const union bpf_attr *attr,
4596 union bpf_attr __user *uattr)
4598 struct bpf_map_info __user *uinfo = u64_to_user_ptr(attr->info.info);
4599 struct bpf_map_info info;
4600 u32 info_len = attr->info.info_len;
4603 err = bpf_check_uarg_tail_zero(USER_BPFPTR(uinfo), sizeof(info), info_len);
4606 info_len = min_t(u32, sizeof(info), info_len);
4608 memset(&info, 0, sizeof(info));
4609 info.type = map->map_type;
4611 info.key_size = map->key_size;
4612 info.value_size = map->value_size;
4613 info.max_entries = map->max_entries;
4614 info.map_flags = map->map_flags;
4615 info.map_extra = map->map_extra;
4616 memcpy(info.name, map->name, sizeof(map->name));
4619 info.btf_id = btf_obj_id(map->btf);
4620 info.btf_key_type_id = map->btf_key_type_id;
4621 info.btf_value_type_id = map->btf_value_type_id;
4623 info.btf_vmlinux_value_type_id = map->btf_vmlinux_value_type_id;
4625 if (bpf_map_is_offloaded(map)) {
4626 err = bpf_map_offload_info_fill(&info, map);
4631 if (copy_to_user(uinfo, &info, info_len) ||
4632 put_user(info_len, &uattr->info.info_len))
4638 static int bpf_btf_get_info_by_fd(struct file *file,
4640 const union bpf_attr *attr,
4641 union bpf_attr __user *uattr)
4643 struct bpf_btf_info __user *uinfo = u64_to_user_ptr(attr->info.info);
4644 u32 info_len = attr->info.info_len;
4647 err = bpf_check_uarg_tail_zero(USER_BPFPTR(uinfo), sizeof(*uinfo), info_len);
4651 return btf_get_info_by_fd(btf, attr, uattr);
4654 static int bpf_link_get_info_by_fd(struct file *file,
4655 struct bpf_link *link,
4656 const union bpf_attr *attr,
4657 union bpf_attr __user *uattr)
4659 struct bpf_link_info __user *uinfo = u64_to_user_ptr(attr->info.info);
4660 struct bpf_link_info info;
4661 u32 info_len = attr->info.info_len;
4664 err = bpf_check_uarg_tail_zero(USER_BPFPTR(uinfo), sizeof(info), info_len);
4667 info_len = min_t(u32, sizeof(info), info_len);
4669 memset(&info, 0, sizeof(info));
4670 if (copy_from_user(&info, uinfo, info_len))
4673 info.type = link->type;
4676 info.prog_id = link->prog->aux->id;
4678 if (link->ops->fill_link_info) {
4679 err = link->ops->fill_link_info(link, &info);
4684 if (copy_to_user(uinfo, &info, info_len) ||
4685 put_user(info_len, &uattr->info.info_len))
4692 #define BPF_OBJ_GET_INFO_BY_FD_LAST_FIELD info.info
4694 static int bpf_obj_get_info_by_fd(const union bpf_attr *attr,
4695 union bpf_attr __user *uattr)
4697 int ufd = attr->info.bpf_fd;
4701 if (CHECK_ATTR(BPF_OBJ_GET_INFO_BY_FD))
4708 if (f.file->f_op == &bpf_prog_fops)
4709 err = bpf_prog_get_info_by_fd(f.file, f.file->private_data, attr,
4711 else if (f.file->f_op == &bpf_map_fops)
4712 err = bpf_map_get_info_by_fd(f.file, f.file->private_data, attr,
4714 else if (f.file->f_op == &btf_fops)
4715 err = bpf_btf_get_info_by_fd(f.file, f.file->private_data, attr, uattr);
4716 else if (f.file->f_op == &bpf_link_fops)
4717 err = bpf_link_get_info_by_fd(f.file, f.file->private_data,
4726 #define BPF_BTF_LOAD_LAST_FIELD btf_log_true_size
4728 static int bpf_btf_load(const union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size)
4730 if (CHECK_ATTR(BPF_BTF_LOAD))
4736 return btf_new_fd(attr, uattr, uattr_size);
4739 #define BPF_BTF_GET_FD_BY_ID_LAST_FIELD btf_id
4741 static int bpf_btf_get_fd_by_id(const union bpf_attr *attr)
4743 if (CHECK_ATTR(BPF_BTF_GET_FD_BY_ID))
4746 if (!capable(CAP_SYS_ADMIN))
4749 return btf_get_fd_by_id(attr->btf_id);
4752 static int bpf_task_fd_query_copy(const union bpf_attr *attr,
4753 union bpf_attr __user *uattr,
4754 u32 prog_id, u32 fd_type,
4755 const char *buf, u64 probe_offset,
4758 char __user *ubuf = u64_to_user_ptr(attr->task_fd_query.buf);
4759 u32 len = buf ? strlen(buf) : 0, input_len;
4762 if (put_user(len, &uattr->task_fd_query.buf_len))
4764 input_len = attr->task_fd_query.buf_len;
4765 if (input_len && ubuf) {
4767 /* nothing to copy, just make ubuf NULL terminated */
4770 if (put_user(zero, ubuf))
4772 } else if (input_len >= len + 1) {
4773 /* ubuf can hold the string with NULL terminator */
4774 if (copy_to_user(ubuf, buf, len + 1))
4777 /* ubuf cannot hold the string with NULL terminator,
4778 * do a partial copy with NULL terminator.
4783 if (copy_to_user(ubuf, buf, input_len - 1))
4785 if (put_user(zero, ubuf + input_len - 1))
4790 if (put_user(prog_id, &uattr->task_fd_query.prog_id) ||
4791 put_user(fd_type, &uattr->task_fd_query.fd_type) ||
4792 put_user(probe_offset, &uattr->task_fd_query.probe_offset) ||
4793 put_user(probe_addr, &uattr->task_fd_query.probe_addr))
4799 #define BPF_TASK_FD_QUERY_LAST_FIELD task_fd_query.probe_addr
4801 static int bpf_task_fd_query(const union bpf_attr *attr,
4802 union bpf_attr __user *uattr)
4804 pid_t pid = attr->task_fd_query.pid;
4805 u32 fd = attr->task_fd_query.fd;
4806 const struct perf_event *event;
4807 struct task_struct *task;
4811 if (CHECK_ATTR(BPF_TASK_FD_QUERY))
4814 if (!capable(CAP_SYS_ADMIN))
4817 if (attr->task_fd_query.flags != 0)
4821 task = get_pid_task(find_vpid(pid), PIDTYPE_PID);
4827 file = fget_task(task, fd);
4828 put_task_struct(task);
4832 if (file->f_op == &bpf_link_fops) {
4833 struct bpf_link *link = file->private_data;
4835 if (link->ops == &bpf_raw_tp_link_lops) {
4836 struct bpf_raw_tp_link *raw_tp =
4837 container_of(link, struct bpf_raw_tp_link, link);
4838 struct bpf_raw_event_map *btp = raw_tp->btp;
4840 err = bpf_task_fd_query_copy(attr, uattr,
4841 raw_tp->link.prog->aux->id,
4842 BPF_FD_TYPE_RAW_TRACEPOINT,
4843 btp->tp->name, 0, 0);
4849 event = perf_get_event(file);
4850 if (!IS_ERR(event)) {
4851 u64 probe_offset, probe_addr;
4852 u32 prog_id, fd_type;
4855 err = bpf_get_perf_event_info(event, &prog_id, &fd_type,
4856 &buf, &probe_offset,
4859 err = bpf_task_fd_query_copy(attr, uattr, prog_id,
4873 #define BPF_MAP_BATCH_LAST_FIELD batch.flags
4875 #define BPF_DO_BATCH(fn, ...) \
4881 err = fn(__VA_ARGS__); \
4884 static int bpf_map_do_batch(const union bpf_attr *attr,
4885 union bpf_attr __user *uattr,
4888 bool has_read = cmd == BPF_MAP_LOOKUP_BATCH ||
4889 cmd == BPF_MAP_LOOKUP_AND_DELETE_BATCH;
4890 bool has_write = cmd != BPF_MAP_LOOKUP_BATCH;
4891 struct bpf_map *map;
4895 if (CHECK_ATTR(BPF_MAP_BATCH))
4898 ufd = attr->batch.map_fd;
4900 map = __bpf_map_get(f);
4902 return PTR_ERR(map);
4904 bpf_map_write_active_inc(map);
4905 if (has_read && !(map_get_sys_perms(map, f) & FMODE_CAN_READ)) {
4909 if (has_write && !(map_get_sys_perms(map, f) & FMODE_CAN_WRITE)) {
4914 if (cmd == BPF_MAP_LOOKUP_BATCH)
4915 BPF_DO_BATCH(map->ops->map_lookup_batch, map, attr, uattr);
4916 else if (cmd == BPF_MAP_LOOKUP_AND_DELETE_BATCH)
4917 BPF_DO_BATCH(map->ops->map_lookup_and_delete_batch, map, attr, uattr);
4918 else if (cmd == BPF_MAP_UPDATE_BATCH)
4919 BPF_DO_BATCH(map->ops->map_update_batch, map, f.file, attr, uattr);
4921 BPF_DO_BATCH(map->ops->map_delete_batch, map, attr, uattr);
4924 bpf_map_write_active_dec(map);
4929 #define BPF_LINK_CREATE_LAST_FIELD link_create.uprobe_multi.pid
4930 static int link_create(union bpf_attr *attr, bpfptr_t uattr)
4932 struct bpf_prog *prog;
4935 if (CHECK_ATTR(BPF_LINK_CREATE))
4938 if (attr->link_create.attach_type == BPF_STRUCT_OPS)
4939 return bpf_struct_ops_link_create(attr);
4941 prog = bpf_prog_get(attr->link_create.prog_fd);
4943 return PTR_ERR(prog);
4945 ret = bpf_prog_attach_check_attach_type(prog,
4946 attr->link_create.attach_type);
4950 switch (prog->type) {
4951 case BPF_PROG_TYPE_CGROUP_SKB:
4952 case BPF_PROG_TYPE_CGROUP_SOCK:
4953 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
4954 case BPF_PROG_TYPE_SOCK_OPS:
4955 case BPF_PROG_TYPE_CGROUP_DEVICE:
4956 case BPF_PROG_TYPE_CGROUP_SYSCTL:
4957 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
4958 ret = cgroup_bpf_link_attach(attr, prog);
4960 case BPF_PROG_TYPE_EXT:
4961 ret = bpf_tracing_prog_attach(prog,
4962 attr->link_create.target_fd,
4963 attr->link_create.target_btf_id,
4964 attr->link_create.tracing.cookie);
4966 case BPF_PROG_TYPE_LSM:
4967 case BPF_PROG_TYPE_TRACING:
4968 if (attr->link_create.attach_type != prog->expected_attach_type) {
4972 if (prog->expected_attach_type == BPF_TRACE_RAW_TP)
4973 ret = bpf_raw_tp_link_attach(prog, NULL);
4974 else if (prog->expected_attach_type == BPF_TRACE_ITER)
4975 ret = bpf_iter_link_attach(attr, uattr, prog);
4976 else if (prog->expected_attach_type == BPF_LSM_CGROUP)
4977 ret = cgroup_bpf_link_attach(attr, prog);
4979 ret = bpf_tracing_prog_attach(prog,
4980 attr->link_create.target_fd,
4981 attr->link_create.target_btf_id,
4982 attr->link_create.tracing.cookie);
4984 case BPF_PROG_TYPE_FLOW_DISSECTOR:
4985 case BPF_PROG_TYPE_SK_LOOKUP:
4986 ret = netns_bpf_link_create(attr, prog);
4989 case BPF_PROG_TYPE_XDP:
4990 ret = bpf_xdp_link_attach(attr, prog);
4992 case BPF_PROG_TYPE_SCHED_CLS:
4993 if (attr->link_create.attach_type == BPF_TCX_INGRESS ||
4994 attr->link_create.attach_type == BPF_TCX_EGRESS)
4995 ret = tcx_link_attach(attr, prog);
4997 ret = netkit_link_attach(attr, prog);
4999 case BPF_PROG_TYPE_NETFILTER:
5000 ret = bpf_nf_link_attach(attr, prog);
5003 case BPF_PROG_TYPE_PERF_EVENT:
5004 case BPF_PROG_TYPE_TRACEPOINT:
5005 ret = bpf_perf_link_attach(attr, prog);
5007 case BPF_PROG_TYPE_KPROBE:
5008 if (attr->link_create.attach_type == BPF_PERF_EVENT)
5009 ret = bpf_perf_link_attach(attr, prog);
5010 else if (attr->link_create.attach_type == BPF_TRACE_KPROBE_MULTI)
5011 ret = bpf_kprobe_multi_link_attach(attr, prog);
5012 else if (attr->link_create.attach_type == BPF_TRACE_UPROBE_MULTI)
5013 ret = bpf_uprobe_multi_link_attach(attr, prog);
5025 static int link_update_map(struct bpf_link *link, union bpf_attr *attr)
5027 struct bpf_map *new_map, *old_map = NULL;
5030 new_map = bpf_map_get(attr->link_update.new_map_fd);
5031 if (IS_ERR(new_map))
5032 return PTR_ERR(new_map);
5034 if (attr->link_update.flags & BPF_F_REPLACE) {
5035 old_map = bpf_map_get(attr->link_update.old_map_fd);
5036 if (IS_ERR(old_map)) {
5037 ret = PTR_ERR(old_map);
5040 } else if (attr->link_update.old_map_fd) {
5045 ret = link->ops->update_map(link, new_map, old_map);
5048 bpf_map_put(old_map);
5050 bpf_map_put(new_map);
5054 #define BPF_LINK_UPDATE_LAST_FIELD link_update.old_prog_fd
5056 static int link_update(union bpf_attr *attr)
5058 struct bpf_prog *old_prog = NULL, *new_prog;
5059 struct bpf_link *link;
5063 if (CHECK_ATTR(BPF_LINK_UPDATE))
5066 flags = attr->link_update.flags;
5067 if (flags & ~BPF_F_REPLACE)
5070 link = bpf_link_get_from_fd(attr->link_update.link_fd);
5072 return PTR_ERR(link);
5074 if (link->ops->update_map) {
5075 ret = link_update_map(link, attr);
5079 new_prog = bpf_prog_get(attr->link_update.new_prog_fd);
5080 if (IS_ERR(new_prog)) {
5081 ret = PTR_ERR(new_prog);
5085 if (flags & BPF_F_REPLACE) {
5086 old_prog = bpf_prog_get(attr->link_update.old_prog_fd);
5087 if (IS_ERR(old_prog)) {
5088 ret = PTR_ERR(old_prog);
5092 } else if (attr->link_update.old_prog_fd) {
5097 if (link->ops->update_prog)
5098 ret = link->ops->update_prog(link, new_prog, old_prog);
5104 bpf_prog_put(old_prog);
5106 bpf_prog_put(new_prog);
5108 bpf_link_put_direct(link);
5112 #define BPF_LINK_DETACH_LAST_FIELD link_detach.link_fd
5114 static int link_detach(union bpf_attr *attr)
5116 struct bpf_link *link;
5119 if (CHECK_ATTR(BPF_LINK_DETACH))
5122 link = bpf_link_get_from_fd(attr->link_detach.link_fd);
5124 return PTR_ERR(link);
5126 if (link->ops->detach)
5127 ret = link->ops->detach(link);
5131 bpf_link_put_direct(link);
5135 static struct bpf_link *bpf_link_inc_not_zero(struct bpf_link *link)
5137 return atomic64_fetch_add_unless(&link->refcnt, 1, 0) ? link : ERR_PTR(-ENOENT);
5140 struct bpf_link *bpf_link_by_id(u32 id)
5142 struct bpf_link *link;
5145 return ERR_PTR(-ENOENT);
5147 spin_lock_bh(&link_idr_lock);
5148 /* before link is "settled", ID is 0, pretend it doesn't exist yet */
5149 link = idr_find(&link_idr, id);
5152 link = bpf_link_inc_not_zero(link);
5154 link = ERR_PTR(-EAGAIN);
5156 link = ERR_PTR(-ENOENT);
5158 spin_unlock_bh(&link_idr_lock);
5162 struct bpf_link *bpf_link_get_curr_or_next(u32 *id)
5164 struct bpf_link *link;
5166 spin_lock_bh(&link_idr_lock);
5168 link = idr_get_next(&link_idr, id);
5170 link = bpf_link_inc_not_zero(link);
5176 spin_unlock_bh(&link_idr_lock);
5181 #define BPF_LINK_GET_FD_BY_ID_LAST_FIELD link_id
5183 static int bpf_link_get_fd_by_id(const union bpf_attr *attr)
5185 struct bpf_link *link;
5186 u32 id = attr->link_id;
5189 if (CHECK_ATTR(BPF_LINK_GET_FD_BY_ID))
5192 if (!capable(CAP_SYS_ADMIN))
5195 link = bpf_link_by_id(id);
5197 return PTR_ERR(link);
5199 fd = bpf_link_new_fd(link);
5201 bpf_link_put_direct(link);
5206 DEFINE_MUTEX(bpf_stats_enabled_mutex);
5208 static int bpf_stats_release(struct inode *inode, struct file *file)
5210 mutex_lock(&bpf_stats_enabled_mutex);
5211 static_key_slow_dec(&bpf_stats_enabled_key.key);
5212 mutex_unlock(&bpf_stats_enabled_mutex);
5216 static const struct file_operations bpf_stats_fops = {
5217 .release = bpf_stats_release,
5220 static int bpf_enable_runtime_stats(void)
5224 mutex_lock(&bpf_stats_enabled_mutex);
5226 /* Set a very high limit to avoid overflow */
5227 if (static_key_count(&bpf_stats_enabled_key.key) > INT_MAX / 2) {
5228 mutex_unlock(&bpf_stats_enabled_mutex);
5232 fd = anon_inode_getfd("bpf-stats", &bpf_stats_fops, NULL, O_CLOEXEC);
5234 static_key_slow_inc(&bpf_stats_enabled_key.key);
5236 mutex_unlock(&bpf_stats_enabled_mutex);
5240 #define BPF_ENABLE_STATS_LAST_FIELD enable_stats.type
5242 static int bpf_enable_stats(union bpf_attr *attr)
5245 if (CHECK_ATTR(BPF_ENABLE_STATS))
5248 if (!capable(CAP_SYS_ADMIN))
5251 switch (attr->enable_stats.type) {
5252 case BPF_STATS_RUN_TIME:
5253 return bpf_enable_runtime_stats();
5260 #define BPF_ITER_CREATE_LAST_FIELD iter_create.flags
5262 static int bpf_iter_create(union bpf_attr *attr)
5264 struct bpf_link *link;
5267 if (CHECK_ATTR(BPF_ITER_CREATE))
5270 if (attr->iter_create.flags)
5273 link = bpf_link_get_from_fd(attr->iter_create.link_fd);
5275 return PTR_ERR(link);
5277 err = bpf_iter_new_fd(link);
5278 bpf_link_put_direct(link);
5283 #define BPF_PROG_BIND_MAP_LAST_FIELD prog_bind_map.flags
5285 static int bpf_prog_bind_map(union bpf_attr *attr)
5287 struct bpf_prog *prog;
5288 struct bpf_map *map;
5289 struct bpf_map **used_maps_old, **used_maps_new;
5292 if (CHECK_ATTR(BPF_PROG_BIND_MAP))
5295 if (attr->prog_bind_map.flags)
5298 prog = bpf_prog_get(attr->prog_bind_map.prog_fd);
5300 return PTR_ERR(prog);
5302 map = bpf_map_get(attr->prog_bind_map.map_fd);
5308 mutex_lock(&prog->aux->used_maps_mutex);
5310 used_maps_old = prog->aux->used_maps;
5312 for (i = 0; i < prog->aux->used_map_cnt; i++)
5313 if (used_maps_old[i] == map) {
5318 used_maps_new = kmalloc_array(prog->aux->used_map_cnt + 1,
5319 sizeof(used_maps_new[0]),
5321 if (!used_maps_new) {
5326 memcpy(used_maps_new, used_maps_old,
5327 sizeof(used_maps_old[0]) * prog->aux->used_map_cnt);
5328 used_maps_new[prog->aux->used_map_cnt] = map;
5330 prog->aux->used_map_cnt++;
5331 prog->aux->used_maps = used_maps_new;
5333 kfree(used_maps_old);
5336 mutex_unlock(&prog->aux->used_maps_mutex);
5345 static int __sys_bpf(int cmd, bpfptr_t uattr, unsigned int size)
5347 union bpf_attr attr;
5350 err = bpf_check_uarg_tail_zero(uattr, sizeof(attr), size);
5353 size = min_t(u32, size, sizeof(attr));
5355 /* copy attributes from user space, may be less than sizeof(bpf_attr) */
5356 memset(&attr, 0, sizeof(attr));
5357 if (copy_from_bpfptr(&attr, uattr, size) != 0)
5360 err = security_bpf(cmd, &attr, size);
5365 case BPF_MAP_CREATE:
5366 err = map_create(&attr);
5368 case BPF_MAP_LOOKUP_ELEM:
5369 err = map_lookup_elem(&attr);
5371 case BPF_MAP_UPDATE_ELEM:
5372 err = map_update_elem(&attr, uattr);
5374 case BPF_MAP_DELETE_ELEM:
5375 err = map_delete_elem(&attr, uattr);
5377 case BPF_MAP_GET_NEXT_KEY:
5378 err = map_get_next_key(&attr);
5380 case BPF_MAP_FREEZE:
5381 err = map_freeze(&attr);
5384 err = bpf_prog_load(&attr, uattr, size);
5387 err = bpf_obj_pin(&attr);
5390 err = bpf_obj_get(&attr);
5392 case BPF_PROG_ATTACH:
5393 err = bpf_prog_attach(&attr);
5395 case BPF_PROG_DETACH:
5396 err = bpf_prog_detach(&attr);
5398 case BPF_PROG_QUERY:
5399 err = bpf_prog_query(&attr, uattr.user);
5401 case BPF_PROG_TEST_RUN:
5402 err = bpf_prog_test_run(&attr, uattr.user);
5404 case BPF_PROG_GET_NEXT_ID:
5405 err = bpf_obj_get_next_id(&attr, uattr.user,
5406 &prog_idr, &prog_idr_lock);
5408 case BPF_MAP_GET_NEXT_ID:
5409 err = bpf_obj_get_next_id(&attr, uattr.user,
5410 &map_idr, &map_idr_lock);
5412 case BPF_BTF_GET_NEXT_ID:
5413 err = bpf_obj_get_next_id(&attr, uattr.user,
5414 &btf_idr, &btf_idr_lock);
5416 case BPF_PROG_GET_FD_BY_ID:
5417 err = bpf_prog_get_fd_by_id(&attr);
5419 case BPF_MAP_GET_FD_BY_ID:
5420 err = bpf_map_get_fd_by_id(&attr);
5422 case BPF_OBJ_GET_INFO_BY_FD:
5423 err = bpf_obj_get_info_by_fd(&attr, uattr.user);
5425 case BPF_RAW_TRACEPOINT_OPEN:
5426 err = bpf_raw_tracepoint_open(&attr);
5429 err = bpf_btf_load(&attr, uattr, size);
5431 case BPF_BTF_GET_FD_BY_ID:
5432 err = bpf_btf_get_fd_by_id(&attr);
5434 case BPF_TASK_FD_QUERY:
5435 err = bpf_task_fd_query(&attr, uattr.user);
5437 case BPF_MAP_LOOKUP_AND_DELETE_ELEM:
5438 err = map_lookup_and_delete_elem(&attr);
5440 case BPF_MAP_LOOKUP_BATCH:
5441 err = bpf_map_do_batch(&attr, uattr.user, BPF_MAP_LOOKUP_BATCH);
5443 case BPF_MAP_LOOKUP_AND_DELETE_BATCH:
5444 err = bpf_map_do_batch(&attr, uattr.user,
5445 BPF_MAP_LOOKUP_AND_DELETE_BATCH);
5447 case BPF_MAP_UPDATE_BATCH:
5448 err = bpf_map_do_batch(&attr, uattr.user, BPF_MAP_UPDATE_BATCH);
5450 case BPF_MAP_DELETE_BATCH:
5451 err = bpf_map_do_batch(&attr, uattr.user, BPF_MAP_DELETE_BATCH);
5453 case BPF_LINK_CREATE:
5454 err = link_create(&attr, uattr);
5456 case BPF_LINK_UPDATE:
5457 err = link_update(&attr);
5459 case BPF_LINK_GET_FD_BY_ID:
5460 err = bpf_link_get_fd_by_id(&attr);
5462 case BPF_LINK_GET_NEXT_ID:
5463 err = bpf_obj_get_next_id(&attr, uattr.user,
5464 &link_idr, &link_idr_lock);
5466 case BPF_ENABLE_STATS:
5467 err = bpf_enable_stats(&attr);
5469 case BPF_ITER_CREATE:
5470 err = bpf_iter_create(&attr);
5472 case BPF_LINK_DETACH:
5473 err = link_detach(&attr);
5475 case BPF_PROG_BIND_MAP:
5476 err = bpf_prog_bind_map(&attr);
5486 SYSCALL_DEFINE3(bpf, int, cmd, union bpf_attr __user *, uattr, unsigned int, size)
5488 return __sys_bpf(cmd, USER_BPFPTR(uattr), size);
5491 static bool syscall_prog_is_valid_access(int off, int size,
5492 enum bpf_access_type type,
5493 const struct bpf_prog *prog,
5494 struct bpf_insn_access_aux *info)
5496 if (off < 0 || off >= U16_MAX)
5498 if (off % size != 0)
5503 BPF_CALL_3(bpf_sys_bpf, int, cmd, union bpf_attr *, attr, u32, attr_size)
5506 case BPF_MAP_CREATE:
5507 case BPF_MAP_DELETE_ELEM:
5508 case BPF_MAP_UPDATE_ELEM:
5509 case BPF_MAP_FREEZE:
5510 case BPF_MAP_GET_FD_BY_ID:
5513 case BPF_LINK_CREATE:
5514 case BPF_RAW_TRACEPOINT_OPEN:
5519 return __sys_bpf(cmd, KERNEL_BPFPTR(attr), attr_size);
5523 /* To shut up -Wmissing-prototypes.
5524 * This function is used by the kernel light skeleton
5525 * to load bpf programs when modules are loaded or during kernel boot.
5526 * See tools/lib/bpf/skel_internal.h
5528 int kern_sys_bpf(int cmd, union bpf_attr *attr, unsigned int size);
5530 int kern_sys_bpf(int cmd, union bpf_attr *attr, unsigned int size)
5532 struct bpf_prog * __maybe_unused prog;
5533 struct bpf_tramp_run_ctx __maybe_unused run_ctx;
5536 #ifdef CONFIG_BPF_JIT /* __bpf_prog_enter_sleepable used by trampoline and JIT */
5537 case BPF_PROG_TEST_RUN:
5538 if (attr->test.data_in || attr->test.data_out ||
5539 attr->test.ctx_out || attr->test.duration ||
5540 attr->test.repeat || attr->test.flags)
5543 prog = bpf_prog_get_type(attr->test.prog_fd, BPF_PROG_TYPE_SYSCALL);
5545 return PTR_ERR(prog);
5547 if (attr->test.ctx_size_in < prog->aux->max_ctx_offset ||
5548 attr->test.ctx_size_in > U16_MAX) {
5553 run_ctx.bpf_cookie = 0;
5554 if (!__bpf_prog_enter_sleepable_recur(prog, &run_ctx)) {
5555 /* recursion detected */
5556 __bpf_prog_exit_sleepable_recur(prog, 0, &run_ctx);
5560 attr->test.retval = bpf_prog_run(prog, (void *) (long) attr->test.ctx_in);
5561 __bpf_prog_exit_sleepable_recur(prog, 0 /* bpf_prog_run does runtime stats */,
5567 return ____bpf_sys_bpf(cmd, attr, size);
5570 EXPORT_SYMBOL(kern_sys_bpf);
5572 static const struct bpf_func_proto bpf_sys_bpf_proto = {
5573 .func = bpf_sys_bpf,
5575 .ret_type = RET_INTEGER,
5576 .arg1_type = ARG_ANYTHING,
5577 .arg2_type = ARG_PTR_TO_MEM | MEM_RDONLY,
5578 .arg3_type = ARG_CONST_SIZE,
5581 const struct bpf_func_proto * __weak
5582 tracing_prog_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
5584 return bpf_base_func_proto(func_id);
5587 BPF_CALL_1(bpf_sys_close, u32, fd)
5589 /* When bpf program calls this helper there should not be
5590 * an fdget() without matching completed fdput().
5591 * This helper is allowed in the following callchain only:
5592 * sys_bpf->prog_test_run->bpf_prog->bpf_sys_close
5594 return close_fd(fd);
5597 static const struct bpf_func_proto bpf_sys_close_proto = {
5598 .func = bpf_sys_close,
5600 .ret_type = RET_INTEGER,
5601 .arg1_type = ARG_ANYTHING,
5604 BPF_CALL_4(bpf_kallsyms_lookup_name, const char *, name, int, name_sz, int, flags, u64 *, res)
5609 if (name_sz <= 1 || name[name_sz - 1])
5612 if (!bpf_dump_raw_ok(current_cred()))
5615 *res = kallsyms_lookup_name(name);
5616 return *res ? 0 : -ENOENT;
5619 static const struct bpf_func_proto bpf_kallsyms_lookup_name_proto = {
5620 .func = bpf_kallsyms_lookup_name,
5622 .ret_type = RET_INTEGER,
5623 .arg1_type = ARG_PTR_TO_MEM,
5624 .arg2_type = ARG_CONST_SIZE_OR_ZERO,
5625 .arg3_type = ARG_ANYTHING,
5626 .arg4_type = ARG_PTR_TO_LONG,
5629 static const struct bpf_func_proto *
5630 syscall_prog_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
5633 case BPF_FUNC_sys_bpf:
5634 return !perfmon_capable() ? NULL : &bpf_sys_bpf_proto;
5635 case BPF_FUNC_btf_find_by_name_kind:
5636 return &bpf_btf_find_by_name_kind_proto;
5637 case BPF_FUNC_sys_close:
5638 return &bpf_sys_close_proto;
5639 case BPF_FUNC_kallsyms_lookup_name:
5640 return &bpf_kallsyms_lookup_name_proto;
5642 return tracing_prog_func_proto(func_id, prog);
5646 const struct bpf_verifier_ops bpf_syscall_verifier_ops = {
5647 .get_func_proto = syscall_prog_func_proto,
5648 .is_valid_access = syscall_prog_is_valid_access,
5651 const struct bpf_prog_ops bpf_syscall_prog_ops = {
5652 .test_run = bpf_prog_test_run_syscall,
5655 #ifdef CONFIG_SYSCTL
5656 static int bpf_stats_handler(struct ctl_table *table, int write,
5657 void *buffer, size_t *lenp, loff_t *ppos)
5659 struct static_key *key = (struct static_key *)table->data;
5660 static int saved_val;
5662 struct ctl_table tmp = {
5664 .maxlen = sizeof(val),
5665 .mode = table->mode,
5666 .extra1 = SYSCTL_ZERO,
5667 .extra2 = SYSCTL_ONE,
5670 if (write && !capable(CAP_SYS_ADMIN))
5673 mutex_lock(&bpf_stats_enabled_mutex);
5675 ret = proc_dointvec_minmax(&tmp, write, buffer, lenp, ppos);
5676 if (write && !ret && val != saved_val) {
5678 static_key_slow_inc(key);
5680 static_key_slow_dec(key);
5683 mutex_unlock(&bpf_stats_enabled_mutex);
5687 void __weak unpriv_ebpf_notify(int new_state)
5691 static int bpf_unpriv_handler(struct ctl_table *table, int write,
5692 void *buffer, size_t *lenp, loff_t *ppos)
5694 int ret, unpriv_enable = *(int *)table->data;
5695 bool locked_state = unpriv_enable == 1;
5696 struct ctl_table tmp = *table;
5698 if (write && !capable(CAP_SYS_ADMIN))
5701 tmp.data = &unpriv_enable;
5702 ret = proc_dointvec_minmax(&tmp, write, buffer, lenp, ppos);
5703 if (write && !ret) {
5704 if (locked_state && unpriv_enable != 1)
5706 *(int *)table->data = unpriv_enable;
5710 unpriv_ebpf_notify(unpriv_enable);
5715 static struct ctl_table bpf_syscall_table[] = {
5717 .procname = "unprivileged_bpf_disabled",
5718 .data = &sysctl_unprivileged_bpf_disabled,
5719 .maxlen = sizeof(sysctl_unprivileged_bpf_disabled),
5721 .proc_handler = bpf_unpriv_handler,
5722 .extra1 = SYSCTL_ZERO,
5723 .extra2 = SYSCTL_TWO,
5726 .procname = "bpf_stats_enabled",
5727 .data = &bpf_stats_enabled_key.key,
5729 .proc_handler = bpf_stats_handler,
5734 static int __init bpf_syscall_sysctl_init(void)
5736 register_sysctl_init("kernel", bpf_syscall_table);
5739 late_initcall(bpf_syscall_sysctl_init);
5740 #endif /* CONFIG_SYSCTL */