1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
5 #include <linux/bpf-cgroup.h>
6 #include <linux/bpf_trace.h>
7 #include <linux/bpf_lirc.h>
8 #include <linux/bpf_verifier.h>
9 #include <linux/bsearch.h>
10 #include <linux/btf.h>
11 #include <linux/syscalls.h>
12 #include <linux/slab.h>
13 #include <linux/sched/signal.h>
14 #include <linux/vmalloc.h>
15 #include <linux/mmzone.h>
16 #include <linux/anon_inodes.h>
17 #include <linux/fdtable.h>
18 #include <linux/file.h>
20 #include <linux/license.h>
21 #include <linux/filter.h>
22 #include <linux/kernel.h>
23 #include <linux/idr.h>
24 #include <linux/cred.h>
25 #include <linux/timekeeping.h>
26 #include <linux/ctype.h>
27 #include <linux/nospec.h>
28 #include <linux/audit.h>
29 #include <uapi/linux/btf.h>
30 #include <linux/pgtable.h>
31 #include <linux/bpf_lsm.h>
32 #include <linux/poll.h>
33 #include <linux/sort.h>
34 #include <linux/bpf-netns.h>
35 #include <linux/rcupdate_trace.h>
36 #include <linux/memcontrol.h>
37 #include <linux/trace_events.h>
38 #include <net/netfilter/nf_bpf_link.h>
42 #define IS_FD_ARRAY(map) ((map)->map_type == BPF_MAP_TYPE_PERF_EVENT_ARRAY || \
43 (map)->map_type == BPF_MAP_TYPE_CGROUP_ARRAY || \
44 (map)->map_type == BPF_MAP_TYPE_ARRAY_OF_MAPS)
45 #define IS_FD_PROG_ARRAY(map) ((map)->map_type == BPF_MAP_TYPE_PROG_ARRAY)
46 #define IS_FD_HASH(map) ((map)->map_type == BPF_MAP_TYPE_HASH_OF_MAPS)
47 #define IS_FD_MAP(map) (IS_FD_ARRAY(map) || IS_FD_PROG_ARRAY(map) || \
50 #define BPF_OBJ_FLAG_MASK (BPF_F_RDONLY | BPF_F_WRONLY)
52 DEFINE_PER_CPU(int, bpf_prog_active);
53 static DEFINE_IDR(prog_idr);
54 static DEFINE_SPINLOCK(prog_idr_lock);
55 static DEFINE_IDR(map_idr);
56 static DEFINE_SPINLOCK(map_idr_lock);
57 static DEFINE_IDR(link_idr);
58 static DEFINE_SPINLOCK(link_idr_lock);
60 int sysctl_unprivileged_bpf_disabled __read_mostly =
61 IS_BUILTIN(CONFIG_BPF_UNPRIV_DEFAULT_OFF) ? 2 : 0;
63 static const struct bpf_map_ops * const bpf_map_types[] = {
64 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type)
65 #define BPF_MAP_TYPE(_id, _ops) \
67 #define BPF_LINK_TYPE(_id, _name)
68 #include <linux/bpf_types.h>
75 * If we're handed a bigger struct than we know of, ensure all the unknown bits
76 * are 0 - i.e. new user-space does not rely on any kernel feature extensions
77 * we don't know about yet.
79 * There is a ToCToU between this function call and the following
80 * copy_from_user() call. However, this is not a concern since this function is
81 * meant to be a future-proofing of bits.
83 int bpf_check_uarg_tail_zero(bpfptr_t uaddr,
89 if (unlikely(actual_size > PAGE_SIZE)) /* silly large */
92 if (actual_size <= expected_size)
96 res = memchr_inv(uaddr.kernel + expected_size, 0,
97 actual_size - expected_size) == NULL;
99 res = check_zeroed_user(uaddr.user + expected_size,
100 actual_size - expected_size);
103 return res ? 0 : -E2BIG;
106 const struct bpf_map_ops bpf_map_offload_ops = {
107 .map_meta_equal = bpf_map_meta_equal,
108 .map_alloc = bpf_map_offload_map_alloc,
109 .map_free = bpf_map_offload_map_free,
110 .map_check_btf = map_check_no_btf,
111 .map_mem_usage = bpf_map_offload_map_mem_usage,
114 static void bpf_map_write_active_inc(struct bpf_map *map)
116 atomic64_inc(&map->writecnt);
119 static void bpf_map_write_active_dec(struct bpf_map *map)
121 atomic64_dec(&map->writecnt);
124 bool bpf_map_write_active(const struct bpf_map *map)
126 return atomic64_read(&map->writecnt) != 0;
129 static u32 bpf_map_value_size(const struct bpf_map *map)
131 if (map->map_type == BPF_MAP_TYPE_PERCPU_HASH ||
132 map->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH ||
133 map->map_type == BPF_MAP_TYPE_PERCPU_ARRAY ||
134 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
135 return round_up(map->value_size, 8) * num_possible_cpus();
136 else if (IS_FD_MAP(map))
139 return map->value_size;
142 static void maybe_wait_bpf_programs(struct bpf_map *map)
144 /* Wait for any running BPF programs to complete so that
145 * userspace, when we return to it, knows that all programs
146 * that could be running use the new map value.
148 if (map->map_type == BPF_MAP_TYPE_HASH_OF_MAPS ||
149 map->map_type == BPF_MAP_TYPE_ARRAY_OF_MAPS)
153 static int bpf_map_update_value(struct bpf_map *map, struct file *map_file,
154 void *key, void *value, __u64 flags)
158 /* Need to create a kthread, thus must support schedule */
159 if (bpf_map_is_offloaded(map)) {
160 return bpf_map_offload_update_elem(map, key, value, flags);
161 } else if (map->map_type == BPF_MAP_TYPE_CPUMAP ||
162 map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
163 return map->ops->map_update_elem(map, key, value, flags);
164 } else if (map->map_type == BPF_MAP_TYPE_SOCKHASH ||
165 map->map_type == BPF_MAP_TYPE_SOCKMAP) {
166 return sock_map_update_elem_sys(map, key, value, flags);
167 } else if (IS_FD_PROG_ARRAY(map)) {
168 return bpf_fd_array_map_update_elem(map, map_file, key, value,
172 bpf_disable_instrumentation();
173 if (map->map_type == BPF_MAP_TYPE_PERCPU_HASH ||
174 map->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH) {
175 err = bpf_percpu_hash_update(map, key, value, flags);
176 } else if (map->map_type == BPF_MAP_TYPE_PERCPU_ARRAY) {
177 err = bpf_percpu_array_update(map, key, value, flags);
178 } else if (map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE) {
179 err = bpf_percpu_cgroup_storage_update(map, key, value,
181 } else if (IS_FD_ARRAY(map)) {
183 err = bpf_fd_array_map_update_elem(map, map_file, key, value,
186 } else if (map->map_type == BPF_MAP_TYPE_HASH_OF_MAPS) {
188 err = bpf_fd_htab_map_update_elem(map, map_file, key, value,
191 } else if (map->map_type == BPF_MAP_TYPE_REUSEPORT_SOCKARRAY) {
192 /* rcu_read_lock() is not needed */
193 err = bpf_fd_reuseport_array_update_elem(map, key, value,
195 } else if (map->map_type == BPF_MAP_TYPE_QUEUE ||
196 map->map_type == BPF_MAP_TYPE_STACK ||
197 map->map_type == BPF_MAP_TYPE_BLOOM_FILTER) {
198 err = map->ops->map_push_elem(map, value, flags);
201 err = map->ops->map_update_elem(map, key, value, flags);
204 bpf_enable_instrumentation();
205 maybe_wait_bpf_programs(map);
210 static int bpf_map_copy_value(struct bpf_map *map, void *key, void *value,
216 if (bpf_map_is_offloaded(map))
217 return bpf_map_offload_lookup_elem(map, key, value);
219 bpf_disable_instrumentation();
220 if (map->map_type == BPF_MAP_TYPE_PERCPU_HASH ||
221 map->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH) {
222 err = bpf_percpu_hash_copy(map, key, value);
223 } else if (map->map_type == BPF_MAP_TYPE_PERCPU_ARRAY) {
224 err = bpf_percpu_array_copy(map, key, value);
225 } else if (map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE) {
226 err = bpf_percpu_cgroup_storage_copy(map, key, value);
227 } else if (map->map_type == BPF_MAP_TYPE_STACK_TRACE) {
228 err = bpf_stackmap_copy(map, key, value);
229 } else if (IS_FD_ARRAY(map) || IS_FD_PROG_ARRAY(map)) {
230 err = bpf_fd_array_map_lookup_elem(map, key, value);
231 } else if (IS_FD_HASH(map)) {
232 err = bpf_fd_htab_map_lookup_elem(map, key, value);
233 } else if (map->map_type == BPF_MAP_TYPE_REUSEPORT_SOCKARRAY) {
234 err = bpf_fd_reuseport_array_lookup_elem(map, key, value);
235 } else if (map->map_type == BPF_MAP_TYPE_QUEUE ||
236 map->map_type == BPF_MAP_TYPE_STACK ||
237 map->map_type == BPF_MAP_TYPE_BLOOM_FILTER) {
238 err = map->ops->map_peek_elem(map, value);
239 } else if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
240 /* struct_ops map requires directly updating "value" */
241 err = bpf_struct_ops_map_sys_lookup_elem(map, key, value);
244 if (map->ops->map_lookup_elem_sys_only)
245 ptr = map->ops->map_lookup_elem_sys_only(map, key);
247 ptr = map->ops->map_lookup_elem(map, key);
254 if (flags & BPF_F_LOCK)
255 /* lock 'ptr' and copy everything but lock */
256 copy_map_value_locked(map, value, ptr, true);
258 copy_map_value(map, value, ptr);
259 /* mask lock and timer, since value wasn't zero inited */
260 check_and_init_map_value(map, value);
265 bpf_enable_instrumentation();
266 maybe_wait_bpf_programs(map);
271 /* Please, do not use this function outside from the map creation path
272 * (e.g. in map update path) without taking care of setting the active
273 * memory cgroup (see at bpf_map_kmalloc_node() for example).
275 static void *__bpf_map_area_alloc(u64 size, int numa_node, bool mmapable)
277 /* We really just want to fail instead of triggering OOM killer
278 * under memory pressure, therefore we set __GFP_NORETRY to kmalloc,
279 * which is used for lower order allocation requests.
281 * It has been observed that higher order allocation requests done by
282 * vmalloc with __GFP_NORETRY being set might fail due to not trying
283 * to reclaim memory from the page cache, thus we set
284 * __GFP_RETRY_MAYFAIL to avoid such situations.
287 gfp_t gfp = bpf_memcg_flags(__GFP_NOWARN | __GFP_ZERO);
288 unsigned int flags = 0;
289 unsigned long align = 1;
292 if (size >= SIZE_MAX)
295 /* kmalloc()'ed memory can't be mmap()'ed */
297 BUG_ON(!PAGE_ALIGNED(size));
300 } else if (size <= (PAGE_SIZE << PAGE_ALLOC_COSTLY_ORDER)) {
301 area = kmalloc_node(size, gfp | GFP_USER | __GFP_NORETRY,
307 return __vmalloc_node_range(size, align, VMALLOC_START, VMALLOC_END,
308 gfp | GFP_KERNEL | __GFP_RETRY_MAYFAIL, PAGE_KERNEL,
309 flags, numa_node, __builtin_return_address(0));
312 void *bpf_map_area_alloc(u64 size, int numa_node)
314 return __bpf_map_area_alloc(size, numa_node, false);
317 void *bpf_map_area_mmapable_alloc(u64 size, int numa_node)
319 return __bpf_map_area_alloc(size, numa_node, true);
322 void bpf_map_area_free(void *area)
327 static u32 bpf_map_flags_retain_permanent(u32 flags)
329 /* Some map creation flags are not tied to the map object but
330 * rather to the map fd instead, so they have no meaning upon
331 * map object inspection since multiple file descriptors with
332 * different (access) properties can exist here. Thus, given
333 * this has zero meaning for the map itself, lets clear these
336 return flags & ~(BPF_F_RDONLY | BPF_F_WRONLY);
339 void bpf_map_init_from_attr(struct bpf_map *map, union bpf_attr *attr)
341 map->map_type = attr->map_type;
342 map->key_size = attr->key_size;
343 map->value_size = attr->value_size;
344 map->max_entries = attr->max_entries;
345 map->map_flags = bpf_map_flags_retain_permanent(attr->map_flags);
346 map->numa_node = bpf_map_attr_numa_node(attr);
347 map->map_extra = attr->map_extra;
350 static int bpf_map_alloc_id(struct bpf_map *map)
354 idr_preload(GFP_KERNEL);
355 spin_lock_bh(&map_idr_lock);
356 id = idr_alloc_cyclic(&map_idr, map, 1, INT_MAX, GFP_ATOMIC);
359 spin_unlock_bh(&map_idr_lock);
362 if (WARN_ON_ONCE(!id))
365 return id > 0 ? 0 : id;
368 void bpf_map_free_id(struct bpf_map *map)
372 /* Offloaded maps are removed from the IDR store when their device
373 * disappears - even if someone holds an fd to them they are unusable,
374 * the memory is gone, all ops will fail; they are simply waiting for
375 * refcnt to drop to be freed.
380 spin_lock_irqsave(&map_idr_lock, flags);
382 idr_remove(&map_idr, map->id);
385 spin_unlock_irqrestore(&map_idr_lock, flags);
388 #ifdef CONFIG_MEMCG_KMEM
389 static void bpf_map_save_memcg(struct bpf_map *map)
391 /* Currently if a map is created by a process belonging to the root
392 * memory cgroup, get_obj_cgroup_from_current() will return NULL.
393 * So we have to check map->objcg for being NULL each time it's
396 if (memcg_bpf_enabled())
397 map->objcg = get_obj_cgroup_from_current();
400 static void bpf_map_release_memcg(struct bpf_map *map)
403 obj_cgroup_put(map->objcg);
406 static struct mem_cgroup *bpf_map_get_memcg(const struct bpf_map *map)
409 return get_mem_cgroup_from_objcg(map->objcg);
411 return root_mem_cgroup;
414 void *bpf_map_kmalloc_node(const struct bpf_map *map, size_t size, gfp_t flags,
417 struct mem_cgroup *memcg, *old_memcg;
420 memcg = bpf_map_get_memcg(map);
421 old_memcg = set_active_memcg(memcg);
422 ptr = kmalloc_node(size, flags | __GFP_ACCOUNT, node);
423 set_active_memcg(old_memcg);
424 mem_cgroup_put(memcg);
429 void *bpf_map_kzalloc(const struct bpf_map *map, size_t size, gfp_t flags)
431 struct mem_cgroup *memcg, *old_memcg;
434 memcg = bpf_map_get_memcg(map);
435 old_memcg = set_active_memcg(memcg);
436 ptr = kzalloc(size, flags | __GFP_ACCOUNT);
437 set_active_memcg(old_memcg);
438 mem_cgroup_put(memcg);
443 void *bpf_map_kvcalloc(struct bpf_map *map, size_t n, size_t size,
446 struct mem_cgroup *memcg, *old_memcg;
449 memcg = bpf_map_get_memcg(map);
450 old_memcg = set_active_memcg(memcg);
451 ptr = kvcalloc(n, size, flags | __GFP_ACCOUNT);
452 set_active_memcg(old_memcg);
453 mem_cgroup_put(memcg);
458 void __percpu *bpf_map_alloc_percpu(const struct bpf_map *map, size_t size,
459 size_t align, gfp_t flags)
461 struct mem_cgroup *memcg, *old_memcg;
464 memcg = bpf_map_get_memcg(map);
465 old_memcg = set_active_memcg(memcg);
466 ptr = __alloc_percpu_gfp(size, align, flags | __GFP_ACCOUNT);
467 set_active_memcg(old_memcg);
468 mem_cgroup_put(memcg);
474 static void bpf_map_save_memcg(struct bpf_map *map)
478 static void bpf_map_release_memcg(struct bpf_map *map)
483 static int btf_field_cmp(const void *a, const void *b)
485 const struct btf_field *f1 = a, *f2 = b;
487 if (f1->offset < f2->offset)
489 else if (f1->offset > f2->offset)
494 struct btf_field *btf_record_find(const struct btf_record *rec, u32 offset,
497 struct btf_field *field;
499 if (IS_ERR_OR_NULL(rec) || !(rec->field_mask & field_mask))
501 field = bsearch(&offset, rec->fields, rec->cnt, sizeof(rec->fields[0]), btf_field_cmp);
502 if (!field || !(field->type & field_mask))
507 void btf_record_free(struct btf_record *rec)
511 if (IS_ERR_OR_NULL(rec))
513 for (i = 0; i < rec->cnt; i++) {
514 switch (rec->fields[i].type) {
517 if (rec->fields[i].kptr.module)
518 module_put(rec->fields[i].kptr.module);
519 btf_put(rec->fields[i].kptr.btf);
528 /* Nothing to release */
538 void bpf_map_free_record(struct bpf_map *map)
540 btf_record_free(map->record);
544 struct btf_record *btf_record_dup(const struct btf_record *rec)
546 const struct btf_field *fields;
547 struct btf_record *new_rec;
550 if (IS_ERR_OR_NULL(rec))
552 size = offsetof(struct btf_record, fields[rec->cnt]);
553 new_rec = kmemdup(rec, size, GFP_KERNEL | __GFP_NOWARN);
555 return ERR_PTR(-ENOMEM);
556 /* Do a deep copy of the btf_record */
557 fields = rec->fields;
559 for (i = 0; i < rec->cnt; i++) {
560 switch (fields[i].type) {
563 btf_get(fields[i].kptr.btf);
564 if (fields[i].kptr.module && !try_module_get(fields[i].kptr.module)) {
576 /* Nothing to acquire */
587 btf_record_free(new_rec);
591 bool btf_record_equal(const struct btf_record *rec_a, const struct btf_record *rec_b)
593 bool a_has_fields = !IS_ERR_OR_NULL(rec_a), b_has_fields = !IS_ERR_OR_NULL(rec_b);
596 if (!a_has_fields && !b_has_fields)
598 if (a_has_fields != b_has_fields)
600 if (rec_a->cnt != rec_b->cnt)
602 size = offsetof(struct btf_record, fields[rec_a->cnt]);
603 /* btf_parse_fields uses kzalloc to allocate a btf_record, so unused
604 * members are zeroed out. So memcmp is safe to do without worrying
605 * about padding/unused fields.
607 * While spin_lock, timer, and kptr have no relation to map BTF,
608 * list_head metadata is specific to map BTF, the btf and value_rec
609 * members in particular. btf is the map BTF, while value_rec points to
610 * btf_record in that map BTF.
612 * So while by default, we don't rely on the map BTF (which the records
613 * were parsed from) matching for both records, which is not backwards
614 * compatible, in case list_head is part of it, we implicitly rely on
615 * that by way of depending on memcmp succeeding for it.
617 return !memcmp(rec_a, rec_b, size);
620 void bpf_obj_free_timer(const struct btf_record *rec, void *obj)
622 if (WARN_ON_ONCE(!btf_record_has_field(rec, BPF_TIMER)))
624 bpf_timer_cancel_and_free(obj + rec->timer_off);
627 extern void __bpf_obj_drop_impl(void *p, const struct btf_record *rec);
629 void bpf_obj_free_fields(const struct btf_record *rec, void *obj)
631 const struct btf_field *fields;
634 if (IS_ERR_OR_NULL(rec))
636 fields = rec->fields;
637 for (i = 0; i < rec->cnt; i++) {
638 struct btf_struct_meta *pointee_struct_meta;
639 const struct btf_field *field = &fields[i];
640 void *field_ptr = obj + field->offset;
643 switch (fields[i].type) {
647 bpf_timer_cancel_and_free(field_ptr);
650 WRITE_ONCE(*(u64 *)field_ptr, 0);
653 xchgd_field = (void *)xchg((unsigned long *)field_ptr, 0);
657 if (!btf_is_kernel(field->kptr.btf)) {
658 pointee_struct_meta = btf_find_struct_meta(field->kptr.btf,
661 __bpf_obj_drop_impl(xchgd_field, pointee_struct_meta ?
662 pointee_struct_meta->record :
666 field->kptr.dtor(xchgd_field);
670 if (WARN_ON_ONCE(rec->spin_lock_off < 0))
672 bpf_list_head_free(field, field_ptr, obj + rec->spin_lock_off);
675 if (WARN_ON_ONCE(rec->spin_lock_off < 0))
677 bpf_rb_root_free(field, field_ptr, obj + rec->spin_lock_off);
690 /* called from workqueue */
691 static void bpf_map_free_deferred(struct work_struct *work)
693 struct bpf_map *map = container_of(work, struct bpf_map, work);
694 struct btf_record *rec = map->record;
696 security_bpf_map_free(map);
697 bpf_map_release_memcg(map);
698 /* implementation dependent freeing */
699 map->ops->map_free(map);
700 /* Delay freeing of btf_record for maps, as map_free
701 * callback usually needs access to them. It is better to do it here
702 * than require each callback to do the free itself manually.
704 * Note that the btf_record stashed in map->inner_map_meta->record was
705 * already freed using the map_free callback for map in map case which
706 * eventually calls bpf_map_free_meta, since inner_map_meta is only a
707 * template bpf_map struct used during verification.
709 btf_record_free(rec);
712 static void bpf_map_put_uref(struct bpf_map *map)
714 if (atomic64_dec_and_test(&map->usercnt)) {
715 if (map->ops->map_release_uref)
716 map->ops->map_release_uref(map);
720 static void bpf_map_free_in_work(struct bpf_map *map)
722 INIT_WORK(&map->work, bpf_map_free_deferred);
723 /* Avoid spawning kworkers, since they all might contend
724 * for the same mutex like slab_mutex.
726 queue_work(system_unbound_wq, &map->work);
729 static void bpf_map_free_rcu_gp(struct rcu_head *rcu)
731 bpf_map_free_in_work(container_of(rcu, struct bpf_map, rcu));
734 static void bpf_map_free_mult_rcu_gp(struct rcu_head *rcu)
736 if (rcu_trace_implies_rcu_gp())
737 bpf_map_free_rcu_gp(rcu);
739 call_rcu(rcu, bpf_map_free_rcu_gp);
742 /* decrement map refcnt and schedule it for freeing via workqueue
743 * (underlying map implementation ops->map_free() might sleep)
745 void bpf_map_put(struct bpf_map *map)
747 if (atomic64_dec_and_test(&map->refcnt)) {
748 /* bpf_map_free_id() must be called first */
749 bpf_map_free_id(map);
752 if (READ_ONCE(map->free_after_mult_rcu_gp))
753 call_rcu_tasks_trace(&map->rcu, bpf_map_free_mult_rcu_gp);
755 bpf_map_free_in_work(map);
758 EXPORT_SYMBOL_GPL(bpf_map_put);
760 void bpf_map_put_with_uref(struct bpf_map *map)
762 bpf_map_put_uref(map);
766 static int bpf_map_release(struct inode *inode, struct file *filp)
768 struct bpf_map *map = filp->private_data;
770 if (map->ops->map_release)
771 map->ops->map_release(map, filp);
773 bpf_map_put_with_uref(map);
777 static fmode_t map_get_sys_perms(struct bpf_map *map, struct fd f)
779 fmode_t mode = f.file->f_mode;
781 /* Our file permissions may have been overridden by global
782 * map permissions facing syscall side.
784 if (READ_ONCE(map->frozen))
785 mode &= ~FMODE_CAN_WRITE;
789 #ifdef CONFIG_PROC_FS
790 /* Show the memory usage of a bpf map */
791 static u64 bpf_map_memory_usage(const struct bpf_map *map)
793 return map->ops->map_mem_usage(map);
796 static void bpf_map_show_fdinfo(struct seq_file *m, struct file *filp)
798 struct bpf_map *map = filp->private_data;
799 u32 type = 0, jited = 0;
801 if (map_type_contains_progs(map)) {
802 spin_lock(&map->owner.lock);
803 type = map->owner.type;
804 jited = map->owner.jited;
805 spin_unlock(&map->owner.lock);
814 "map_extra:\t%#llx\n"
823 (unsigned long long)map->map_extra,
824 bpf_map_memory_usage(map),
826 READ_ONCE(map->frozen));
828 seq_printf(m, "owner_prog_type:\t%u\n", type);
829 seq_printf(m, "owner_jited:\t%u\n", jited);
834 static ssize_t bpf_dummy_read(struct file *filp, char __user *buf, size_t siz,
837 /* We need this handler such that alloc_file() enables
838 * f_mode with FMODE_CAN_READ.
843 static ssize_t bpf_dummy_write(struct file *filp, const char __user *buf,
844 size_t siz, loff_t *ppos)
846 /* We need this handler such that alloc_file() enables
847 * f_mode with FMODE_CAN_WRITE.
852 /* called for any extra memory-mapped regions (except initial) */
853 static void bpf_map_mmap_open(struct vm_area_struct *vma)
855 struct bpf_map *map = vma->vm_file->private_data;
857 if (vma->vm_flags & VM_MAYWRITE)
858 bpf_map_write_active_inc(map);
861 /* called for all unmapped memory region (including initial) */
862 static void bpf_map_mmap_close(struct vm_area_struct *vma)
864 struct bpf_map *map = vma->vm_file->private_data;
866 if (vma->vm_flags & VM_MAYWRITE)
867 bpf_map_write_active_dec(map);
870 static const struct vm_operations_struct bpf_map_default_vmops = {
871 .open = bpf_map_mmap_open,
872 .close = bpf_map_mmap_close,
875 static int bpf_map_mmap(struct file *filp, struct vm_area_struct *vma)
877 struct bpf_map *map = filp->private_data;
880 if (!map->ops->map_mmap || !IS_ERR_OR_NULL(map->record))
883 if (!(vma->vm_flags & VM_SHARED))
886 mutex_lock(&map->freeze_mutex);
888 if (vma->vm_flags & VM_WRITE) {
893 /* map is meant to be read-only, so do not allow mapping as
894 * writable, because it's possible to leak a writable page
895 * reference and allows user-space to still modify it after
896 * freezing, while verifier will assume contents do not change
898 if (map->map_flags & BPF_F_RDONLY_PROG) {
904 /* set default open/close callbacks */
905 vma->vm_ops = &bpf_map_default_vmops;
906 vma->vm_private_data = map;
907 vm_flags_clear(vma, VM_MAYEXEC);
908 if (!(vma->vm_flags & VM_WRITE))
909 /* disallow re-mapping with PROT_WRITE */
910 vm_flags_clear(vma, VM_MAYWRITE);
912 err = map->ops->map_mmap(map, vma);
916 if (vma->vm_flags & VM_MAYWRITE)
917 bpf_map_write_active_inc(map);
919 mutex_unlock(&map->freeze_mutex);
923 static __poll_t bpf_map_poll(struct file *filp, struct poll_table_struct *pts)
925 struct bpf_map *map = filp->private_data;
927 if (map->ops->map_poll)
928 return map->ops->map_poll(map, filp, pts);
933 const struct file_operations bpf_map_fops = {
934 #ifdef CONFIG_PROC_FS
935 .show_fdinfo = bpf_map_show_fdinfo,
937 .release = bpf_map_release,
938 .read = bpf_dummy_read,
939 .write = bpf_dummy_write,
940 .mmap = bpf_map_mmap,
941 .poll = bpf_map_poll,
944 int bpf_map_new_fd(struct bpf_map *map, int flags)
948 ret = security_bpf_map(map, OPEN_FMODE(flags));
952 return anon_inode_getfd("bpf-map", &bpf_map_fops, map,
956 int bpf_get_file_flag(int flags)
958 if ((flags & BPF_F_RDONLY) && (flags & BPF_F_WRONLY))
960 if (flags & BPF_F_RDONLY)
962 if (flags & BPF_F_WRONLY)
967 /* helper macro to check that unused fields 'union bpf_attr' are zero */
968 #define CHECK_ATTR(CMD) \
969 memchr_inv((void *) &attr->CMD##_LAST_FIELD + \
970 sizeof(attr->CMD##_LAST_FIELD), 0, \
972 offsetof(union bpf_attr, CMD##_LAST_FIELD) - \
973 sizeof(attr->CMD##_LAST_FIELD)) != NULL
975 /* dst and src must have at least "size" number of bytes.
976 * Return strlen on success and < 0 on error.
978 int bpf_obj_name_cpy(char *dst, const char *src, unsigned int size)
980 const char *end = src + size;
981 const char *orig_src = src;
983 memset(dst, 0, size);
984 /* Copy all isalnum(), '_' and '.' chars. */
985 while (src < end && *src) {
986 if (!isalnum(*src) &&
987 *src != '_' && *src != '.')
992 /* No '\0' found in "size" number of bytes */
996 return src - orig_src;
999 int map_check_no_btf(const struct bpf_map *map,
1000 const struct btf *btf,
1001 const struct btf_type *key_type,
1002 const struct btf_type *value_type)
1007 static int map_check_btf(struct bpf_map *map, const struct btf *btf,
1008 u32 btf_key_id, u32 btf_value_id)
1010 const struct btf_type *key_type, *value_type;
1011 u32 key_size, value_size;
1014 /* Some maps allow key to be unspecified. */
1016 key_type = btf_type_id_size(btf, &btf_key_id, &key_size);
1017 if (!key_type || key_size != map->key_size)
1020 key_type = btf_type_by_id(btf, 0);
1021 if (!map->ops->map_check_btf)
1025 value_type = btf_type_id_size(btf, &btf_value_id, &value_size);
1026 if (!value_type || value_size != map->value_size)
1029 map->record = btf_parse_fields(btf, value_type,
1030 BPF_SPIN_LOCK | BPF_TIMER | BPF_KPTR | BPF_LIST_HEAD |
1031 BPF_RB_ROOT | BPF_REFCOUNT,
1033 if (!IS_ERR_OR_NULL(map->record)) {
1036 if (!bpf_capable()) {
1040 if (map->map_flags & (BPF_F_RDONLY_PROG | BPF_F_WRONLY_PROG)) {
1044 for (i = 0; i < sizeof(map->record->field_mask) * 8; i++) {
1045 switch (map->record->field_mask & (1 << i)) {
1049 if (map->map_type != BPF_MAP_TYPE_HASH &&
1050 map->map_type != BPF_MAP_TYPE_ARRAY &&
1051 map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
1052 map->map_type != BPF_MAP_TYPE_SK_STORAGE &&
1053 map->map_type != BPF_MAP_TYPE_INODE_STORAGE &&
1054 map->map_type != BPF_MAP_TYPE_TASK_STORAGE &&
1055 map->map_type != BPF_MAP_TYPE_CGRP_STORAGE) {
1061 if (map->map_type != BPF_MAP_TYPE_HASH &&
1062 map->map_type != BPF_MAP_TYPE_LRU_HASH &&
1063 map->map_type != BPF_MAP_TYPE_ARRAY) {
1068 case BPF_KPTR_UNREF:
1071 if (map->map_type != BPF_MAP_TYPE_HASH &&
1072 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
1073 map->map_type != BPF_MAP_TYPE_LRU_HASH &&
1074 map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH &&
1075 map->map_type != BPF_MAP_TYPE_ARRAY &&
1076 map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
1077 map->map_type != BPF_MAP_TYPE_SK_STORAGE &&
1078 map->map_type != BPF_MAP_TYPE_INODE_STORAGE &&
1079 map->map_type != BPF_MAP_TYPE_TASK_STORAGE &&
1080 map->map_type != BPF_MAP_TYPE_CGRP_STORAGE) {
1087 if (map->map_type != BPF_MAP_TYPE_HASH &&
1088 map->map_type != BPF_MAP_TYPE_LRU_HASH &&
1089 map->map_type != BPF_MAP_TYPE_ARRAY) {
1095 /* Fail if map_type checks are missing for a field type */
1102 ret = btf_check_and_fixup_fields(btf, map->record);
1106 if (map->ops->map_check_btf) {
1107 ret = map->ops->map_check_btf(map, btf, key_type, value_type);
1114 bpf_map_free_record(map);
1118 #define BPF_MAP_CREATE_LAST_FIELD map_extra
1119 /* called via syscall */
1120 static int map_create(union bpf_attr *attr)
1122 const struct bpf_map_ops *ops;
1123 int numa_node = bpf_map_attr_numa_node(attr);
1124 u32 map_type = attr->map_type;
1125 struct bpf_map *map;
1129 err = CHECK_ATTR(BPF_MAP_CREATE);
1133 if (attr->btf_vmlinux_value_type_id) {
1134 if (attr->map_type != BPF_MAP_TYPE_STRUCT_OPS ||
1135 attr->btf_key_type_id || attr->btf_value_type_id)
1137 } else if (attr->btf_key_type_id && !attr->btf_value_type_id) {
1141 if (attr->map_type != BPF_MAP_TYPE_BLOOM_FILTER &&
1142 attr->map_extra != 0)
1145 f_flags = bpf_get_file_flag(attr->map_flags);
1149 if (numa_node != NUMA_NO_NODE &&
1150 ((unsigned int)numa_node >= nr_node_ids ||
1151 !node_online(numa_node)))
1154 /* find map type and init map: hashtable vs rbtree vs bloom vs ... */
1155 map_type = attr->map_type;
1156 if (map_type >= ARRAY_SIZE(bpf_map_types))
1158 map_type = array_index_nospec(map_type, ARRAY_SIZE(bpf_map_types));
1159 ops = bpf_map_types[map_type];
1163 if (ops->map_alloc_check) {
1164 err = ops->map_alloc_check(attr);
1168 if (attr->map_ifindex)
1169 ops = &bpf_map_offload_ops;
1170 if (!ops->map_mem_usage)
1173 /* Intent here is for unprivileged_bpf_disabled to block BPF map
1174 * creation for unprivileged users; other actions depend
1175 * on fd availability and access to bpffs, so are dependent on
1176 * object creation success. Even with unprivileged BPF disabled,
1177 * capability checks are still carried out.
1179 if (sysctl_unprivileged_bpf_disabled && !bpf_capable())
1182 /* check privileged map type permissions */
1184 case BPF_MAP_TYPE_ARRAY:
1185 case BPF_MAP_TYPE_PERCPU_ARRAY:
1186 case BPF_MAP_TYPE_PROG_ARRAY:
1187 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
1188 case BPF_MAP_TYPE_CGROUP_ARRAY:
1189 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
1190 case BPF_MAP_TYPE_HASH:
1191 case BPF_MAP_TYPE_PERCPU_HASH:
1192 case BPF_MAP_TYPE_HASH_OF_MAPS:
1193 case BPF_MAP_TYPE_RINGBUF:
1194 case BPF_MAP_TYPE_USER_RINGBUF:
1195 case BPF_MAP_TYPE_CGROUP_STORAGE:
1196 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
1199 case BPF_MAP_TYPE_SK_STORAGE:
1200 case BPF_MAP_TYPE_INODE_STORAGE:
1201 case BPF_MAP_TYPE_TASK_STORAGE:
1202 case BPF_MAP_TYPE_CGRP_STORAGE:
1203 case BPF_MAP_TYPE_BLOOM_FILTER:
1204 case BPF_MAP_TYPE_LPM_TRIE:
1205 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
1206 case BPF_MAP_TYPE_STACK_TRACE:
1207 case BPF_MAP_TYPE_QUEUE:
1208 case BPF_MAP_TYPE_STACK:
1209 case BPF_MAP_TYPE_LRU_HASH:
1210 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
1211 case BPF_MAP_TYPE_STRUCT_OPS:
1212 case BPF_MAP_TYPE_CPUMAP:
1216 case BPF_MAP_TYPE_SOCKMAP:
1217 case BPF_MAP_TYPE_SOCKHASH:
1218 case BPF_MAP_TYPE_DEVMAP:
1219 case BPF_MAP_TYPE_DEVMAP_HASH:
1220 case BPF_MAP_TYPE_XSKMAP:
1221 if (!capable(CAP_NET_ADMIN))
1225 WARN(1, "unsupported map type %d", map_type);
1229 map = ops->map_alloc(attr);
1231 return PTR_ERR(map);
1233 map->map_type = map_type;
1235 err = bpf_obj_name_cpy(map->name, attr->map_name,
1236 sizeof(attr->map_name));
1240 atomic64_set(&map->refcnt, 1);
1241 atomic64_set(&map->usercnt, 1);
1242 mutex_init(&map->freeze_mutex);
1243 spin_lock_init(&map->owner.lock);
1245 if (attr->btf_key_type_id || attr->btf_value_type_id ||
1246 /* Even the map's value is a kernel's struct,
1247 * the bpf_prog.o must have BTF to begin with
1248 * to figure out the corresponding kernel's
1249 * counter part. Thus, attr->btf_fd has
1252 attr->btf_vmlinux_value_type_id) {
1255 btf = btf_get_by_fd(attr->btf_fd);
1260 if (btf_is_kernel(btf)) {
1267 if (attr->btf_value_type_id) {
1268 err = map_check_btf(map, btf, attr->btf_key_type_id,
1269 attr->btf_value_type_id);
1274 map->btf_key_type_id = attr->btf_key_type_id;
1275 map->btf_value_type_id = attr->btf_value_type_id;
1276 map->btf_vmlinux_value_type_id =
1277 attr->btf_vmlinux_value_type_id;
1280 err = security_bpf_map_alloc(map);
1284 err = bpf_map_alloc_id(map);
1288 bpf_map_save_memcg(map);
1290 err = bpf_map_new_fd(map, f_flags);
1292 /* failed to allocate fd.
1293 * bpf_map_put_with_uref() is needed because the above
1294 * bpf_map_alloc_id() has published the map
1295 * to the userspace and the userspace may
1296 * have refcnt-ed it through BPF_MAP_GET_FD_BY_ID.
1298 bpf_map_put_with_uref(map);
1305 security_bpf_map_free(map);
1308 map->ops->map_free(map);
1312 /* if error is returned, fd is released.
1313 * On success caller should complete fd access with matching fdput()
1315 struct bpf_map *__bpf_map_get(struct fd f)
1318 return ERR_PTR(-EBADF);
1319 if (f.file->f_op != &bpf_map_fops) {
1321 return ERR_PTR(-EINVAL);
1324 return f.file->private_data;
1327 void bpf_map_inc(struct bpf_map *map)
1329 atomic64_inc(&map->refcnt);
1331 EXPORT_SYMBOL_GPL(bpf_map_inc);
1333 void bpf_map_inc_with_uref(struct bpf_map *map)
1335 atomic64_inc(&map->refcnt);
1336 atomic64_inc(&map->usercnt);
1338 EXPORT_SYMBOL_GPL(bpf_map_inc_with_uref);
1340 struct bpf_map *bpf_map_get(u32 ufd)
1342 struct fd f = fdget(ufd);
1343 struct bpf_map *map;
1345 map = __bpf_map_get(f);
1354 EXPORT_SYMBOL(bpf_map_get);
1356 struct bpf_map *bpf_map_get_with_uref(u32 ufd)
1358 struct fd f = fdget(ufd);
1359 struct bpf_map *map;
1361 map = __bpf_map_get(f);
1365 bpf_map_inc_with_uref(map);
1371 /* map_idr_lock should have been held or the map should have been
1372 * protected by rcu read lock.
1374 struct bpf_map *__bpf_map_inc_not_zero(struct bpf_map *map, bool uref)
1378 refold = atomic64_fetch_add_unless(&map->refcnt, 1, 0);
1380 return ERR_PTR(-ENOENT);
1382 atomic64_inc(&map->usercnt);
1387 struct bpf_map *bpf_map_inc_not_zero(struct bpf_map *map)
1389 spin_lock_bh(&map_idr_lock);
1390 map = __bpf_map_inc_not_zero(map, false);
1391 spin_unlock_bh(&map_idr_lock);
1395 EXPORT_SYMBOL_GPL(bpf_map_inc_not_zero);
1397 int __weak bpf_stackmap_copy(struct bpf_map *map, void *key, void *value)
1402 static void *__bpf_copy_key(void __user *ukey, u64 key_size)
1405 return vmemdup_user(ukey, key_size);
1408 return ERR_PTR(-EINVAL);
1413 static void *___bpf_copy_key(bpfptr_t ukey, u64 key_size)
1416 return kvmemdup_bpfptr(ukey, key_size);
1418 if (!bpfptr_is_null(ukey))
1419 return ERR_PTR(-EINVAL);
1424 /* last field in 'union bpf_attr' used by this command */
1425 #define BPF_MAP_LOOKUP_ELEM_LAST_FIELD flags
1427 static int map_lookup_elem(union bpf_attr *attr)
1429 void __user *ukey = u64_to_user_ptr(attr->key);
1430 void __user *uvalue = u64_to_user_ptr(attr->value);
1431 int ufd = attr->map_fd;
1432 struct bpf_map *map;
1438 if (CHECK_ATTR(BPF_MAP_LOOKUP_ELEM))
1441 if (attr->flags & ~BPF_F_LOCK)
1445 map = __bpf_map_get(f);
1447 return PTR_ERR(map);
1448 if (!(map_get_sys_perms(map, f) & FMODE_CAN_READ)) {
1453 if ((attr->flags & BPF_F_LOCK) &&
1454 !btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
1459 key = __bpf_copy_key(ukey, map->key_size);
1465 value_size = bpf_map_value_size(map);
1468 value = kvmalloc(value_size, GFP_USER | __GFP_NOWARN);
1472 if (map->map_type == BPF_MAP_TYPE_BLOOM_FILTER) {
1473 if (copy_from_user(value, uvalue, value_size))
1476 err = bpf_map_copy_value(map, key, value, attr->flags);
1480 err = bpf_map_copy_value(map, key, value, attr->flags);
1485 if (copy_to_user(uvalue, value, value_size) != 0)
1500 #define BPF_MAP_UPDATE_ELEM_LAST_FIELD flags
1502 static int map_update_elem(union bpf_attr *attr, bpfptr_t uattr)
1504 bpfptr_t ukey = make_bpfptr(attr->key, uattr.is_kernel);
1505 bpfptr_t uvalue = make_bpfptr(attr->value, uattr.is_kernel);
1506 int ufd = attr->map_fd;
1507 struct bpf_map *map;
1513 if (CHECK_ATTR(BPF_MAP_UPDATE_ELEM))
1517 map = __bpf_map_get(f);
1519 return PTR_ERR(map);
1520 bpf_map_write_active_inc(map);
1521 if (!(map_get_sys_perms(map, f) & FMODE_CAN_WRITE)) {
1526 if ((attr->flags & BPF_F_LOCK) &&
1527 !btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
1532 key = ___bpf_copy_key(ukey, map->key_size);
1538 value_size = bpf_map_value_size(map);
1539 value = kvmemdup_bpfptr(uvalue, value_size);
1540 if (IS_ERR(value)) {
1541 err = PTR_ERR(value);
1545 err = bpf_map_update_value(map, f.file, key, value, attr->flags);
1551 bpf_map_write_active_dec(map);
1556 #define BPF_MAP_DELETE_ELEM_LAST_FIELD key
1558 static int map_delete_elem(union bpf_attr *attr, bpfptr_t uattr)
1560 bpfptr_t ukey = make_bpfptr(attr->key, uattr.is_kernel);
1561 int ufd = attr->map_fd;
1562 struct bpf_map *map;
1567 if (CHECK_ATTR(BPF_MAP_DELETE_ELEM))
1571 map = __bpf_map_get(f);
1573 return PTR_ERR(map);
1574 bpf_map_write_active_inc(map);
1575 if (!(map_get_sys_perms(map, f) & FMODE_CAN_WRITE)) {
1580 key = ___bpf_copy_key(ukey, map->key_size);
1586 if (bpf_map_is_offloaded(map)) {
1587 err = bpf_map_offload_delete_elem(map, key);
1589 } else if (IS_FD_PROG_ARRAY(map) ||
1590 map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
1591 /* These maps require sleepable context */
1592 err = map->ops->map_delete_elem(map, key);
1596 bpf_disable_instrumentation();
1598 err = map->ops->map_delete_elem(map, key);
1600 bpf_enable_instrumentation();
1601 maybe_wait_bpf_programs(map);
1605 bpf_map_write_active_dec(map);
1610 /* last field in 'union bpf_attr' used by this command */
1611 #define BPF_MAP_GET_NEXT_KEY_LAST_FIELD next_key
1613 static int map_get_next_key(union bpf_attr *attr)
1615 void __user *ukey = u64_to_user_ptr(attr->key);
1616 void __user *unext_key = u64_to_user_ptr(attr->next_key);
1617 int ufd = attr->map_fd;
1618 struct bpf_map *map;
1619 void *key, *next_key;
1623 if (CHECK_ATTR(BPF_MAP_GET_NEXT_KEY))
1627 map = __bpf_map_get(f);
1629 return PTR_ERR(map);
1630 if (!(map_get_sys_perms(map, f) & FMODE_CAN_READ)) {
1636 key = __bpf_copy_key(ukey, map->key_size);
1646 next_key = kvmalloc(map->key_size, GFP_USER);
1650 if (bpf_map_is_offloaded(map)) {
1651 err = bpf_map_offload_get_next_key(map, key, next_key);
1656 err = map->ops->map_get_next_key(map, key, next_key);
1663 if (copy_to_user(unext_key, next_key, map->key_size) != 0)
1677 int generic_map_delete_batch(struct bpf_map *map,
1678 const union bpf_attr *attr,
1679 union bpf_attr __user *uattr)
1681 void __user *keys = u64_to_user_ptr(attr->batch.keys);
1686 if (attr->batch.elem_flags & ~BPF_F_LOCK)
1689 if ((attr->batch.elem_flags & BPF_F_LOCK) &&
1690 !btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
1694 max_count = attr->batch.count;
1698 key = kvmalloc(map->key_size, GFP_USER | __GFP_NOWARN);
1702 for (cp = 0; cp < max_count; cp++) {
1704 if (copy_from_user(key, keys + cp * map->key_size,
1708 if (bpf_map_is_offloaded(map)) {
1709 err = bpf_map_offload_delete_elem(map, key);
1713 bpf_disable_instrumentation();
1715 err = map->ops->map_delete_elem(map, key);
1717 bpf_enable_instrumentation();
1722 if (copy_to_user(&uattr->batch.count, &cp, sizeof(cp)))
1727 maybe_wait_bpf_programs(map);
1731 int generic_map_update_batch(struct bpf_map *map, struct file *map_file,
1732 const union bpf_attr *attr,
1733 union bpf_attr __user *uattr)
1735 void __user *values = u64_to_user_ptr(attr->batch.values);
1736 void __user *keys = u64_to_user_ptr(attr->batch.keys);
1737 u32 value_size, cp, max_count;
1741 if (attr->batch.elem_flags & ~BPF_F_LOCK)
1744 if ((attr->batch.elem_flags & BPF_F_LOCK) &&
1745 !btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
1749 value_size = bpf_map_value_size(map);
1751 max_count = attr->batch.count;
1755 key = kvmalloc(map->key_size, GFP_USER | __GFP_NOWARN);
1759 value = kvmalloc(value_size, GFP_USER | __GFP_NOWARN);
1765 for (cp = 0; cp < max_count; cp++) {
1767 if (copy_from_user(key, keys + cp * map->key_size,
1769 copy_from_user(value, values + cp * value_size, value_size))
1772 err = bpf_map_update_value(map, map_file, key, value,
1773 attr->batch.elem_flags);
1780 if (copy_to_user(&uattr->batch.count, &cp, sizeof(cp)))
1788 #define MAP_LOOKUP_RETRIES 3
1790 int generic_map_lookup_batch(struct bpf_map *map,
1791 const union bpf_attr *attr,
1792 union bpf_attr __user *uattr)
1794 void __user *uobatch = u64_to_user_ptr(attr->batch.out_batch);
1795 void __user *ubatch = u64_to_user_ptr(attr->batch.in_batch);
1796 void __user *values = u64_to_user_ptr(attr->batch.values);
1797 void __user *keys = u64_to_user_ptr(attr->batch.keys);
1798 void *buf, *buf_prevkey, *prev_key, *key, *value;
1799 int err, retry = MAP_LOOKUP_RETRIES;
1800 u32 value_size, cp, max_count;
1802 if (attr->batch.elem_flags & ~BPF_F_LOCK)
1805 if ((attr->batch.elem_flags & BPF_F_LOCK) &&
1806 !btf_record_has_field(map->record, BPF_SPIN_LOCK))
1809 value_size = bpf_map_value_size(map);
1811 max_count = attr->batch.count;
1815 if (put_user(0, &uattr->batch.count))
1818 buf_prevkey = kvmalloc(map->key_size, GFP_USER | __GFP_NOWARN);
1822 buf = kvmalloc(map->key_size + value_size, GFP_USER | __GFP_NOWARN);
1824 kvfree(buf_prevkey);
1830 if (ubatch && copy_from_user(buf_prevkey, ubatch, map->key_size))
1833 value = key + map->key_size;
1835 prev_key = buf_prevkey;
1837 for (cp = 0; cp < max_count;) {
1839 err = map->ops->map_get_next_key(map, prev_key, key);
1843 err = bpf_map_copy_value(map, key, value,
1844 attr->batch.elem_flags);
1846 if (err == -ENOENT) {
1858 if (copy_to_user(keys + cp * map->key_size, key,
1863 if (copy_to_user(values + cp * value_size, value, value_size)) {
1869 prev_key = buf_prevkey;
1871 swap(prev_key, key);
1872 retry = MAP_LOOKUP_RETRIES;
1880 if ((copy_to_user(&uattr->batch.count, &cp, sizeof(cp)) ||
1881 (cp && copy_to_user(uobatch, prev_key, map->key_size))))
1885 kvfree(buf_prevkey);
1890 #define BPF_MAP_LOOKUP_AND_DELETE_ELEM_LAST_FIELD flags
1892 static int map_lookup_and_delete_elem(union bpf_attr *attr)
1894 void __user *ukey = u64_to_user_ptr(attr->key);
1895 void __user *uvalue = u64_to_user_ptr(attr->value);
1896 int ufd = attr->map_fd;
1897 struct bpf_map *map;
1903 if (CHECK_ATTR(BPF_MAP_LOOKUP_AND_DELETE_ELEM))
1906 if (attr->flags & ~BPF_F_LOCK)
1910 map = __bpf_map_get(f);
1912 return PTR_ERR(map);
1913 bpf_map_write_active_inc(map);
1914 if (!(map_get_sys_perms(map, f) & FMODE_CAN_READ) ||
1915 !(map_get_sys_perms(map, f) & FMODE_CAN_WRITE)) {
1921 (map->map_type == BPF_MAP_TYPE_QUEUE ||
1922 map->map_type == BPF_MAP_TYPE_STACK)) {
1927 if ((attr->flags & BPF_F_LOCK) &&
1928 !btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
1933 key = __bpf_copy_key(ukey, map->key_size);
1939 value_size = bpf_map_value_size(map);
1942 value = kvmalloc(value_size, GFP_USER | __GFP_NOWARN);
1947 if (map->map_type == BPF_MAP_TYPE_QUEUE ||
1948 map->map_type == BPF_MAP_TYPE_STACK) {
1949 err = map->ops->map_pop_elem(map, value);
1950 } else if (map->map_type == BPF_MAP_TYPE_HASH ||
1951 map->map_type == BPF_MAP_TYPE_PERCPU_HASH ||
1952 map->map_type == BPF_MAP_TYPE_LRU_HASH ||
1953 map->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH) {
1954 if (!bpf_map_is_offloaded(map)) {
1955 bpf_disable_instrumentation();
1957 err = map->ops->map_lookup_and_delete_elem(map, key, value, attr->flags);
1959 bpf_enable_instrumentation();
1966 if (copy_to_user(uvalue, value, value_size) != 0) {
1978 bpf_map_write_active_dec(map);
1983 #define BPF_MAP_FREEZE_LAST_FIELD map_fd
1985 static int map_freeze(const union bpf_attr *attr)
1987 int err = 0, ufd = attr->map_fd;
1988 struct bpf_map *map;
1991 if (CHECK_ATTR(BPF_MAP_FREEZE))
1995 map = __bpf_map_get(f);
1997 return PTR_ERR(map);
1999 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS || !IS_ERR_OR_NULL(map->record)) {
2004 if (!(map_get_sys_perms(map, f) & FMODE_CAN_WRITE)) {
2009 mutex_lock(&map->freeze_mutex);
2010 if (bpf_map_write_active(map)) {
2014 if (READ_ONCE(map->frozen)) {
2019 WRITE_ONCE(map->frozen, true);
2021 mutex_unlock(&map->freeze_mutex);
2026 static const struct bpf_prog_ops * const bpf_prog_types[] = {
2027 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
2028 [_id] = & _name ## _prog_ops,
2029 #define BPF_MAP_TYPE(_id, _ops)
2030 #define BPF_LINK_TYPE(_id, _name)
2031 #include <linux/bpf_types.h>
2032 #undef BPF_PROG_TYPE
2034 #undef BPF_LINK_TYPE
2037 static int find_prog_type(enum bpf_prog_type type, struct bpf_prog *prog)
2039 const struct bpf_prog_ops *ops;
2041 if (type >= ARRAY_SIZE(bpf_prog_types))
2043 type = array_index_nospec(type, ARRAY_SIZE(bpf_prog_types));
2044 ops = bpf_prog_types[type];
2048 if (!bpf_prog_is_offloaded(prog->aux))
2049 prog->aux->ops = ops;
2051 prog->aux->ops = &bpf_offload_prog_ops;
2062 static const char * const bpf_audit_str[BPF_AUDIT_MAX] = {
2063 [BPF_AUDIT_LOAD] = "LOAD",
2064 [BPF_AUDIT_UNLOAD] = "UNLOAD",
2067 static void bpf_audit_prog(const struct bpf_prog *prog, unsigned int op)
2069 struct audit_context *ctx = NULL;
2070 struct audit_buffer *ab;
2072 if (WARN_ON_ONCE(op >= BPF_AUDIT_MAX))
2074 if (audit_enabled == AUDIT_OFF)
2076 if (!in_irq() && !irqs_disabled())
2077 ctx = audit_context();
2078 ab = audit_log_start(ctx, GFP_ATOMIC, AUDIT_BPF);
2081 audit_log_format(ab, "prog-id=%u op=%s",
2082 prog->aux->id, bpf_audit_str[op]);
2086 static int bpf_prog_alloc_id(struct bpf_prog *prog)
2090 idr_preload(GFP_KERNEL);
2091 spin_lock_bh(&prog_idr_lock);
2092 id = idr_alloc_cyclic(&prog_idr, prog, 1, INT_MAX, GFP_ATOMIC);
2095 spin_unlock_bh(&prog_idr_lock);
2098 /* id is in [1, INT_MAX) */
2099 if (WARN_ON_ONCE(!id))
2102 return id > 0 ? 0 : id;
2105 void bpf_prog_free_id(struct bpf_prog *prog)
2107 unsigned long flags;
2109 /* cBPF to eBPF migrations are currently not in the idr store.
2110 * Offloaded programs are removed from the store when their device
2111 * disappears - even if someone grabs an fd to them they are unusable,
2112 * simply waiting for refcnt to drop to be freed.
2117 spin_lock_irqsave(&prog_idr_lock, flags);
2118 idr_remove(&prog_idr, prog->aux->id);
2120 spin_unlock_irqrestore(&prog_idr_lock, flags);
2123 static void __bpf_prog_put_rcu(struct rcu_head *rcu)
2125 struct bpf_prog_aux *aux = container_of(rcu, struct bpf_prog_aux, rcu);
2127 kvfree(aux->func_info);
2128 kfree(aux->func_info_aux);
2129 free_uid(aux->user);
2130 security_bpf_prog_free(aux);
2131 bpf_prog_free(aux->prog);
2134 static void __bpf_prog_put_noref(struct bpf_prog *prog, bool deferred)
2136 bpf_prog_kallsyms_del_all(prog);
2137 btf_put(prog->aux->btf);
2138 module_put(prog->aux->mod);
2139 kvfree(prog->aux->jited_linfo);
2140 kvfree(prog->aux->linfo);
2141 kfree(prog->aux->kfunc_tab);
2142 if (prog->aux->attach_btf)
2143 btf_put(prog->aux->attach_btf);
2146 if (prog->aux->sleepable)
2147 call_rcu_tasks_trace(&prog->aux->rcu, __bpf_prog_put_rcu);
2149 call_rcu(&prog->aux->rcu, __bpf_prog_put_rcu);
2151 __bpf_prog_put_rcu(&prog->aux->rcu);
2155 static void bpf_prog_put_deferred(struct work_struct *work)
2157 struct bpf_prog_aux *aux;
2158 struct bpf_prog *prog;
2160 aux = container_of(work, struct bpf_prog_aux, work);
2162 perf_event_bpf_event(prog, PERF_BPF_EVENT_PROG_UNLOAD, 0);
2163 bpf_audit_prog(prog, BPF_AUDIT_UNLOAD);
2164 bpf_prog_free_id(prog);
2165 __bpf_prog_put_noref(prog, true);
2168 static void __bpf_prog_put(struct bpf_prog *prog)
2170 struct bpf_prog_aux *aux = prog->aux;
2172 if (atomic64_dec_and_test(&aux->refcnt)) {
2173 if (in_irq() || irqs_disabled()) {
2174 INIT_WORK(&aux->work, bpf_prog_put_deferred);
2175 schedule_work(&aux->work);
2177 bpf_prog_put_deferred(&aux->work);
2182 void bpf_prog_put(struct bpf_prog *prog)
2184 __bpf_prog_put(prog);
2186 EXPORT_SYMBOL_GPL(bpf_prog_put);
2188 static int bpf_prog_release(struct inode *inode, struct file *filp)
2190 struct bpf_prog *prog = filp->private_data;
2196 struct bpf_prog_kstats {
2202 void notrace bpf_prog_inc_misses_counter(struct bpf_prog *prog)
2204 struct bpf_prog_stats *stats;
2207 stats = this_cpu_ptr(prog->stats);
2208 flags = u64_stats_update_begin_irqsave(&stats->syncp);
2209 u64_stats_inc(&stats->misses);
2210 u64_stats_update_end_irqrestore(&stats->syncp, flags);
2213 static void bpf_prog_get_stats(const struct bpf_prog *prog,
2214 struct bpf_prog_kstats *stats)
2216 u64 nsecs = 0, cnt = 0, misses = 0;
2219 for_each_possible_cpu(cpu) {
2220 const struct bpf_prog_stats *st;
2222 u64 tnsecs, tcnt, tmisses;
2224 st = per_cpu_ptr(prog->stats, cpu);
2226 start = u64_stats_fetch_begin(&st->syncp);
2227 tnsecs = u64_stats_read(&st->nsecs);
2228 tcnt = u64_stats_read(&st->cnt);
2229 tmisses = u64_stats_read(&st->misses);
2230 } while (u64_stats_fetch_retry(&st->syncp, start));
2235 stats->nsecs = nsecs;
2237 stats->misses = misses;
2240 #ifdef CONFIG_PROC_FS
2241 static void bpf_prog_show_fdinfo(struct seq_file *m, struct file *filp)
2243 const struct bpf_prog *prog = filp->private_data;
2244 char prog_tag[sizeof(prog->tag) * 2 + 1] = { };
2245 struct bpf_prog_kstats stats;
2247 bpf_prog_get_stats(prog, &stats);
2248 bin2hex(prog_tag, prog->tag, sizeof(prog->tag));
2255 "run_time_ns:\t%llu\n"
2257 "recursion_misses:\t%llu\n"
2258 "verified_insns:\t%u\n",
2262 prog->pages * 1ULL << PAGE_SHIFT,
2267 prog->aux->verified_insns);
2271 const struct file_operations bpf_prog_fops = {
2272 #ifdef CONFIG_PROC_FS
2273 .show_fdinfo = bpf_prog_show_fdinfo,
2275 .release = bpf_prog_release,
2276 .read = bpf_dummy_read,
2277 .write = bpf_dummy_write,
2280 int bpf_prog_new_fd(struct bpf_prog *prog)
2284 ret = security_bpf_prog(prog);
2288 return anon_inode_getfd("bpf-prog", &bpf_prog_fops, prog,
2289 O_RDWR | O_CLOEXEC);
2292 static struct bpf_prog *____bpf_prog_get(struct fd f)
2295 return ERR_PTR(-EBADF);
2296 if (f.file->f_op != &bpf_prog_fops) {
2298 return ERR_PTR(-EINVAL);
2301 return f.file->private_data;
2304 void bpf_prog_add(struct bpf_prog *prog, int i)
2306 atomic64_add(i, &prog->aux->refcnt);
2308 EXPORT_SYMBOL_GPL(bpf_prog_add);
2310 void bpf_prog_sub(struct bpf_prog *prog, int i)
2312 /* Only to be used for undoing previous bpf_prog_add() in some
2313 * error path. We still know that another entity in our call
2314 * path holds a reference to the program, thus atomic_sub() can
2315 * be safely used in such cases!
2317 WARN_ON(atomic64_sub_return(i, &prog->aux->refcnt) == 0);
2319 EXPORT_SYMBOL_GPL(bpf_prog_sub);
2321 void bpf_prog_inc(struct bpf_prog *prog)
2323 atomic64_inc(&prog->aux->refcnt);
2325 EXPORT_SYMBOL_GPL(bpf_prog_inc);
2327 /* prog_idr_lock should have been held */
2328 struct bpf_prog *bpf_prog_inc_not_zero(struct bpf_prog *prog)
2332 refold = atomic64_fetch_add_unless(&prog->aux->refcnt, 1, 0);
2335 return ERR_PTR(-ENOENT);
2339 EXPORT_SYMBOL_GPL(bpf_prog_inc_not_zero);
2341 bool bpf_prog_get_ok(struct bpf_prog *prog,
2342 enum bpf_prog_type *attach_type, bool attach_drv)
2344 /* not an attachment, just a refcount inc, always allow */
2348 if (prog->type != *attach_type)
2350 if (bpf_prog_is_offloaded(prog->aux) && !attach_drv)
2356 static struct bpf_prog *__bpf_prog_get(u32 ufd, enum bpf_prog_type *attach_type,
2359 struct fd f = fdget(ufd);
2360 struct bpf_prog *prog;
2362 prog = ____bpf_prog_get(f);
2365 if (!bpf_prog_get_ok(prog, attach_type, attach_drv)) {
2366 prog = ERR_PTR(-EINVAL);
2376 struct bpf_prog *bpf_prog_get(u32 ufd)
2378 return __bpf_prog_get(ufd, NULL, false);
2381 struct bpf_prog *bpf_prog_get_type_dev(u32 ufd, enum bpf_prog_type type,
2384 return __bpf_prog_get(ufd, &type, attach_drv);
2386 EXPORT_SYMBOL_GPL(bpf_prog_get_type_dev);
2388 /* Initially all BPF programs could be loaded w/o specifying
2389 * expected_attach_type. Later for some of them specifying expected_attach_type
2390 * at load time became required so that program could be validated properly.
2391 * Programs of types that are allowed to be loaded both w/ and w/o (for
2392 * backward compatibility) expected_attach_type, should have the default attach
2393 * type assigned to expected_attach_type for the latter case, so that it can be
2394 * validated later at attach time.
2396 * bpf_prog_load_fixup_attach_type() sets expected_attach_type in @attr if
2397 * prog type requires it but has some attach types that have to be backward
2400 static void bpf_prog_load_fixup_attach_type(union bpf_attr *attr)
2402 switch (attr->prog_type) {
2403 case BPF_PROG_TYPE_CGROUP_SOCK:
2404 /* Unfortunately BPF_ATTACH_TYPE_UNSPEC enumeration doesn't
2405 * exist so checking for non-zero is the way to go here.
2407 if (!attr->expected_attach_type)
2408 attr->expected_attach_type =
2409 BPF_CGROUP_INET_SOCK_CREATE;
2411 case BPF_PROG_TYPE_SK_REUSEPORT:
2412 if (!attr->expected_attach_type)
2413 attr->expected_attach_type =
2414 BPF_SK_REUSEPORT_SELECT;
2420 bpf_prog_load_check_attach(enum bpf_prog_type prog_type,
2421 enum bpf_attach_type expected_attach_type,
2422 struct btf *attach_btf, u32 btf_id,
2423 struct bpf_prog *dst_prog)
2426 if (btf_id > BTF_MAX_TYPE)
2429 if (!attach_btf && !dst_prog)
2432 switch (prog_type) {
2433 case BPF_PROG_TYPE_TRACING:
2434 case BPF_PROG_TYPE_LSM:
2435 case BPF_PROG_TYPE_STRUCT_OPS:
2436 case BPF_PROG_TYPE_EXT:
2443 if (attach_btf && (!btf_id || dst_prog))
2446 if (dst_prog && prog_type != BPF_PROG_TYPE_TRACING &&
2447 prog_type != BPF_PROG_TYPE_EXT)
2450 switch (prog_type) {
2451 case BPF_PROG_TYPE_CGROUP_SOCK:
2452 switch (expected_attach_type) {
2453 case BPF_CGROUP_INET_SOCK_CREATE:
2454 case BPF_CGROUP_INET_SOCK_RELEASE:
2455 case BPF_CGROUP_INET4_POST_BIND:
2456 case BPF_CGROUP_INET6_POST_BIND:
2461 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
2462 switch (expected_attach_type) {
2463 case BPF_CGROUP_INET4_BIND:
2464 case BPF_CGROUP_INET6_BIND:
2465 case BPF_CGROUP_INET4_CONNECT:
2466 case BPF_CGROUP_INET6_CONNECT:
2467 case BPF_CGROUP_INET4_GETPEERNAME:
2468 case BPF_CGROUP_INET6_GETPEERNAME:
2469 case BPF_CGROUP_INET4_GETSOCKNAME:
2470 case BPF_CGROUP_INET6_GETSOCKNAME:
2471 case BPF_CGROUP_UDP4_SENDMSG:
2472 case BPF_CGROUP_UDP6_SENDMSG:
2473 case BPF_CGROUP_UDP4_RECVMSG:
2474 case BPF_CGROUP_UDP6_RECVMSG:
2479 case BPF_PROG_TYPE_CGROUP_SKB:
2480 switch (expected_attach_type) {
2481 case BPF_CGROUP_INET_INGRESS:
2482 case BPF_CGROUP_INET_EGRESS:
2487 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
2488 switch (expected_attach_type) {
2489 case BPF_CGROUP_SETSOCKOPT:
2490 case BPF_CGROUP_GETSOCKOPT:
2495 case BPF_PROG_TYPE_SK_LOOKUP:
2496 if (expected_attach_type == BPF_SK_LOOKUP)
2499 case BPF_PROG_TYPE_SK_REUSEPORT:
2500 switch (expected_attach_type) {
2501 case BPF_SK_REUSEPORT_SELECT:
2502 case BPF_SK_REUSEPORT_SELECT_OR_MIGRATE:
2507 case BPF_PROG_TYPE_NETFILTER:
2508 if (expected_attach_type == BPF_NETFILTER)
2511 case BPF_PROG_TYPE_SYSCALL:
2512 case BPF_PROG_TYPE_EXT:
2513 if (expected_attach_type)
2521 static bool is_net_admin_prog_type(enum bpf_prog_type prog_type)
2523 switch (prog_type) {
2524 case BPF_PROG_TYPE_SCHED_CLS:
2525 case BPF_PROG_TYPE_SCHED_ACT:
2526 case BPF_PROG_TYPE_XDP:
2527 case BPF_PROG_TYPE_LWT_IN:
2528 case BPF_PROG_TYPE_LWT_OUT:
2529 case BPF_PROG_TYPE_LWT_XMIT:
2530 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
2531 case BPF_PROG_TYPE_SK_SKB:
2532 case BPF_PROG_TYPE_SK_MSG:
2533 case BPF_PROG_TYPE_FLOW_DISSECTOR:
2534 case BPF_PROG_TYPE_CGROUP_DEVICE:
2535 case BPF_PROG_TYPE_CGROUP_SOCK:
2536 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
2537 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
2538 case BPF_PROG_TYPE_CGROUP_SYSCTL:
2539 case BPF_PROG_TYPE_SOCK_OPS:
2540 case BPF_PROG_TYPE_EXT: /* extends any prog */
2541 case BPF_PROG_TYPE_NETFILTER:
2543 case BPF_PROG_TYPE_CGROUP_SKB:
2545 case BPF_PROG_TYPE_SK_REUSEPORT:
2546 /* equivalent to SOCKET_FILTER. need CAP_BPF only */
2552 static bool is_perfmon_prog_type(enum bpf_prog_type prog_type)
2554 switch (prog_type) {
2555 case BPF_PROG_TYPE_KPROBE:
2556 case BPF_PROG_TYPE_TRACEPOINT:
2557 case BPF_PROG_TYPE_PERF_EVENT:
2558 case BPF_PROG_TYPE_RAW_TRACEPOINT:
2559 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
2560 case BPF_PROG_TYPE_TRACING:
2561 case BPF_PROG_TYPE_LSM:
2562 case BPF_PROG_TYPE_STRUCT_OPS: /* has access to struct sock */
2563 case BPF_PROG_TYPE_EXT: /* extends any prog */
2570 /* last field in 'union bpf_attr' used by this command */
2571 #define BPF_PROG_LOAD_LAST_FIELD log_true_size
2573 static int bpf_prog_load(union bpf_attr *attr, bpfptr_t uattr, u32 uattr_size)
2575 enum bpf_prog_type type = attr->prog_type;
2576 struct bpf_prog *prog, *dst_prog = NULL;
2577 struct btf *attach_btf = NULL;
2581 if (CHECK_ATTR(BPF_PROG_LOAD))
2584 if (attr->prog_flags & ~(BPF_F_STRICT_ALIGNMENT |
2585 BPF_F_ANY_ALIGNMENT |
2586 BPF_F_TEST_STATE_FREQ |
2588 BPF_F_TEST_RND_HI32 |
2589 BPF_F_XDP_HAS_FRAGS |
2590 BPF_F_XDP_DEV_BOUND_ONLY))
2593 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS) &&
2594 (attr->prog_flags & BPF_F_ANY_ALIGNMENT) &&
2598 /* Intent here is for unprivileged_bpf_disabled to block BPF program
2599 * creation for unprivileged users; other actions depend
2600 * on fd availability and access to bpffs, so are dependent on
2601 * object creation success. Even with unprivileged BPF disabled,
2602 * capability checks are still carried out for these
2603 * and other operations.
2605 if (sysctl_unprivileged_bpf_disabled && !bpf_capable())
2608 if (attr->insn_cnt == 0 ||
2609 attr->insn_cnt > (bpf_capable() ? BPF_COMPLEXITY_LIMIT_INSNS : BPF_MAXINSNS))
2611 if (type != BPF_PROG_TYPE_SOCKET_FILTER &&
2612 type != BPF_PROG_TYPE_CGROUP_SKB &&
2616 if (is_net_admin_prog_type(type) && !capable(CAP_NET_ADMIN) && !capable(CAP_SYS_ADMIN))
2618 if (is_perfmon_prog_type(type) && !perfmon_capable())
2621 /* attach_prog_fd/attach_btf_obj_fd can specify fd of either bpf_prog
2622 * or btf, we need to check which one it is
2624 if (attr->attach_prog_fd) {
2625 dst_prog = bpf_prog_get(attr->attach_prog_fd);
2626 if (IS_ERR(dst_prog)) {
2628 attach_btf = btf_get_by_fd(attr->attach_btf_obj_fd);
2629 if (IS_ERR(attach_btf))
2631 if (!btf_is_kernel(attach_btf)) {
2632 /* attaching through specifying bpf_prog's BTF
2633 * objects directly might be supported eventually
2635 btf_put(attach_btf);
2639 } else if (attr->attach_btf_id) {
2640 /* fall back to vmlinux BTF, if BTF type ID is specified */
2641 attach_btf = bpf_get_btf_vmlinux();
2642 if (IS_ERR(attach_btf))
2643 return PTR_ERR(attach_btf);
2646 btf_get(attach_btf);
2649 bpf_prog_load_fixup_attach_type(attr);
2650 if (bpf_prog_load_check_attach(type, attr->expected_attach_type,
2651 attach_btf, attr->attach_btf_id,
2654 bpf_prog_put(dst_prog);
2656 btf_put(attach_btf);
2660 /* plain bpf_prog allocation */
2661 prog = bpf_prog_alloc(bpf_prog_size(attr->insn_cnt), GFP_USER);
2664 bpf_prog_put(dst_prog);
2666 btf_put(attach_btf);
2670 prog->expected_attach_type = attr->expected_attach_type;
2671 prog->aux->attach_btf = attach_btf;
2672 prog->aux->attach_btf_id = attr->attach_btf_id;
2673 prog->aux->dst_prog = dst_prog;
2674 prog->aux->dev_bound = !!attr->prog_ifindex;
2675 prog->aux->sleepable = attr->prog_flags & BPF_F_SLEEPABLE;
2676 prog->aux->xdp_has_frags = attr->prog_flags & BPF_F_XDP_HAS_FRAGS;
2678 err = security_bpf_prog_alloc(prog->aux);
2682 prog->aux->user = get_current_user();
2683 prog->len = attr->insn_cnt;
2686 if (copy_from_bpfptr(prog->insns,
2687 make_bpfptr(attr->insns, uattr.is_kernel),
2688 bpf_prog_insn_size(prog)) != 0)
2690 /* copy eBPF program license from user space */
2691 if (strncpy_from_bpfptr(license,
2692 make_bpfptr(attr->license, uattr.is_kernel),
2693 sizeof(license) - 1) < 0)
2695 license[sizeof(license) - 1] = 0;
2697 /* eBPF programs must be GPL compatible to use GPL-ed functions */
2698 prog->gpl_compatible = license_is_gpl_compatible(license) ? 1 : 0;
2700 prog->orig_prog = NULL;
2703 atomic64_set(&prog->aux->refcnt, 1);
2705 if (bpf_prog_is_dev_bound(prog->aux)) {
2706 err = bpf_prog_dev_bound_init(prog, attr);
2711 if (type == BPF_PROG_TYPE_EXT && dst_prog &&
2712 bpf_prog_is_dev_bound(dst_prog->aux)) {
2713 err = bpf_prog_dev_bound_inherit(prog, dst_prog);
2718 /* find program type: socket_filter vs tracing_filter */
2719 err = find_prog_type(type, prog);
2723 prog->aux->load_time = ktime_get_boottime_ns();
2724 err = bpf_obj_name_cpy(prog->aux->name, attr->prog_name,
2725 sizeof(attr->prog_name));
2729 /* run eBPF verifier */
2730 err = bpf_check(&prog, attr, uattr, uattr_size);
2732 goto free_used_maps;
2734 prog = bpf_prog_select_runtime(prog, &err);
2736 goto free_used_maps;
2738 err = bpf_prog_alloc_id(prog);
2740 goto free_used_maps;
2742 /* Upon success of bpf_prog_alloc_id(), the BPF prog is
2743 * effectively publicly exposed. However, retrieving via
2744 * bpf_prog_get_fd_by_id() will take another reference,
2745 * therefore it cannot be gone underneath us.
2747 * Only for the time /after/ successful bpf_prog_new_fd()
2748 * and before returning to userspace, we might just hold
2749 * one reference and any parallel close on that fd could
2750 * rip everything out. Hence, below notifications must
2751 * happen before bpf_prog_new_fd().
2753 * Also, any failure handling from this point onwards must
2754 * be using bpf_prog_put() given the program is exposed.
2756 bpf_prog_kallsyms_add(prog);
2757 perf_event_bpf_event(prog, PERF_BPF_EVENT_PROG_LOAD, 0);
2758 bpf_audit_prog(prog, BPF_AUDIT_LOAD);
2760 err = bpf_prog_new_fd(prog);
2766 /* In case we have subprogs, we need to wait for a grace
2767 * period before we can tear down JIT memory since symbols
2768 * are already exposed under kallsyms.
2770 __bpf_prog_put_noref(prog, prog->aux->func_cnt);
2773 free_uid(prog->aux->user);
2774 security_bpf_prog_free(prog->aux);
2776 if (prog->aux->attach_btf)
2777 btf_put(prog->aux->attach_btf);
2778 bpf_prog_free(prog);
2782 #define BPF_OBJ_LAST_FIELD path_fd
2784 static int bpf_obj_pin(const union bpf_attr *attr)
2788 if (CHECK_ATTR(BPF_OBJ) || attr->file_flags & ~BPF_F_PATH_FD)
2791 /* path_fd has to be accompanied by BPF_F_PATH_FD flag */
2792 if (!(attr->file_flags & BPF_F_PATH_FD) && attr->path_fd)
2795 path_fd = attr->file_flags & BPF_F_PATH_FD ? attr->path_fd : AT_FDCWD;
2796 return bpf_obj_pin_user(attr->bpf_fd, path_fd,
2797 u64_to_user_ptr(attr->pathname));
2800 static int bpf_obj_get(const union bpf_attr *attr)
2804 if (CHECK_ATTR(BPF_OBJ) || attr->bpf_fd != 0 ||
2805 attr->file_flags & ~(BPF_OBJ_FLAG_MASK | BPF_F_PATH_FD))
2808 /* path_fd has to be accompanied by BPF_F_PATH_FD flag */
2809 if (!(attr->file_flags & BPF_F_PATH_FD) && attr->path_fd)
2812 path_fd = attr->file_flags & BPF_F_PATH_FD ? attr->path_fd : AT_FDCWD;
2813 return bpf_obj_get_user(path_fd, u64_to_user_ptr(attr->pathname),
2817 void bpf_link_init(struct bpf_link *link, enum bpf_link_type type,
2818 const struct bpf_link_ops *ops, struct bpf_prog *prog)
2820 atomic64_set(&link->refcnt, 1);
2827 static void bpf_link_free_id(int id)
2832 spin_lock_bh(&link_idr_lock);
2833 idr_remove(&link_idr, id);
2834 spin_unlock_bh(&link_idr_lock);
2837 /* Clean up bpf_link and corresponding anon_inode file and FD. After
2838 * anon_inode is created, bpf_link can't be just kfree()'d due to deferred
2839 * anon_inode's release() call. This helper marks bpf_link as
2840 * defunct, releases anon_inode file and puts reserved FD. bpf_prog's refcnt
2841 * is not decremented, it's the responsibility of a calling code that failed
2842 * to complete bpf_link initialization.
2843 * This helper eventually calls link's dealloc callback, but does not call
2844 * link's release callback.
2846 void bpf_link_cleanup(struct bpf_link_primer *primer)
2848 primer->link->prog = NULL;
2849 bpf_link_free_id(primer->id);
2851 put_unused_fd(primer->fd);
2854 void bpf_link_inc(struct bpf_link *link)
2856 atomic64_inc(&link->refcnt);
2859 /* bpf_link_free is guaranteed to be called from process context */
2860 static void bpf_link_free(struct bpf_link *link)
2862 bpf_link_free_id(link->id);
2864 /* detach BPF program, clean up used resources */
2865 link->ops->release(link);
2866 bpf_prog_put(link->prog);
2868 /* free bpf_link and its containing memory */
2869 link->ops->dealloc(link);
2872 static void bpf_link_put_deferred(struct work_struct *work)
2874 struct bpf_link *link = container_of(work, struct bpf_link, work);
2876 bpf_link_free(link);
2879 /* bpf_link_put might be called from atomic context. It needs to be called
2880 * from sleepable context in order to acquire sleeping locks during the process.
2882 void bpf_link_put(struct bpf_link *link)
2884 if (!atomic64_dec_and_test(&link->refcnt))
2887 INIT_WORK(&link->work, bpf_link_put_deferred);
2888 schedule_work(&link->work);
2890 EXPORT_SYMBOL(bpf_link_put);
2892 static void bpf_link_put_direct(struct bpf_link *link)
2894 if (!atomic64_dec_and_test(&link->refcnt))
2896 bpf_link_free(link);
2899 static int bpf_link_release(struct inode *inode, struct file *filp)
2901 struct bpf_link *link = filp->private_data;
2903 bpf_link_put_direct(link);
2907 #ifdef CONFIG_PROC_FS
2908 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type)
2909 #define BPF_MAP_TYPE(_id, _ops)
2910 #define BPF_LINK_TYPE(_id, _name) [_id] = #_name,
2911 static const char *bpf_link_type_strs[] = {
2912 [BPF_LINK_TYPE_UNSPEC] = "<invalid>",
2913 #include <linux/bpf_types.h>
2915 #undef BPF_PROG_TYPE
2917 #undef BPF_LINK_TYPE
2919 static void bpf_link_show_fdinfo(struct seq_file *m, struct file *filp)
2921 const struct bpf_link *link = filp->private_data;
2922 const struct bpf_prog *prog = link->prog;
2923 char prog_tag[sizeof(prog->tag) * 2 + 1] = { };
2928 bpf_link_type_strs[link->type],
2931 bin2hex(prog_tag, prog->tag, sizeof(prog->tag));
2938 if (link->ops->show_fdinfo)
2939 link->ops->show_fdinfo(link, m);
2943 static const struct file_operations bpf_link_fops = {
2944 #ifdef CONFIG_PROC_FS
2945 .show_fdinfo = bpf_link_show_fdinfo,
2947 .release = bpf_link_release,
2948 .read = bpf_dummy_read,
2949 .write = bpf_dummy_write,
2952 static int bpf_link_alloc_id(struct bpf_link *link)
2956 idr_preload(GFP_KERNEL);
2957 spin_lock_bh(&link_idr_lock);
2958 id = idr_alloc_cyclic(&link_idr, link, 1, INT_MAX, GFP_ATOMIC);
2959 spin_unlock_bh(&link_idr_lock);
2965 /* Prepare bpf_link to be exposed to user-space by allocating anon_inode file,
2966 * reserving unused FD and allocating ID from link_idr. This is to be paired
2967 * with bpf_link_settle() to install FD and ID and expose bpf_link to
2968 * user-space, if bpf_link is successfully attached. If not, bpf_link and
2969 * pre-allocated resources are to be freed with bpf_cleanup() call. All the
2970 * transient state is passed around in struct bpf_link_primer.
2971 * This is preferred way to create and initialize bpf_link, especially when
2972 * there are complicated and expensive operations in between creating bpf_link
2973 * itself and attaching it to BPF hook. By using bpf_link_prime() and
2974 * bpf_link_settle() kernel code using bpf_link doesn't have to perform
2975 * expensive (and potentially failing) roll back operations in a rare case
2976 * that file, FD, or ID can't be allocated.
2978 int bpf_link_prime(struct bpf_link *link, struct bpf_link_primer *primer)
2983 fd = get_unused_fd_flags(O_CLOEXEC);
2988 id = bpf_link_alloc_id(link);
2994 file = anon_inode_getfile("bpf_link", &bpf_link_fops, link, O_CLOEXEC);
2996 bpf_link_free_id(id);
2998 return PTR_ERR(file);
3001 primer->link = link;
3002 primer->file = file;
3008 int bpf_link_settle(struct bpf_link_primer *primer)
3010 /* make bpf_link fetchable by ID */
3011 spin_lock_bh(&link_idr_lock);
3012 primer->link->id = primer->id;
3013 spin_unlock_bh(&link_idr_lock);
3014 /* make bpf_link fetchable by FD */
3015 fd_install(primer->fd, primer->file);
3016 /* pass through installed FD */
3020 int bpf_link_new_fd(struct bpf_link *link)
3022 return anon_inode_getfd("bpf-link", &bpf_link_fops, link, O_CLOEXEC);
3025 struct bpf_link *bpf_link_get_from_fd(u32 ufd)
3027 struct fd f = fdget(ufd);
3028 struct bpf_link *link;
3031 return ERR_PTR(-EBADF);
3032 if (f.file->f_op != &bpf_link_fops) {
3034 return ERR_PTR(-EINVAL);
3037 link = f.file->private_data;
3043 EXPORT_SYMBOL(bpf_link_get_from_fd);
3045 static void bpf_tracing_link_release(struct bpf_link *link)
3047 struct bpf_tracing_link *tr_link =
3048 container_of(link, struct bpf_tracing_link, link.link);
3050 WARN_ON_ONCE(bpf_trampoline_unlink_prog(&tr_link->link,
3051 tr_link->trampoline));
3053 bpf_trampoline_put(tr_link->trampoline);
3055 /* tgt_prog is NULL if target is a kernel function */
3056 if (tr_link->tgt_prog)
3057 bpf_prog_put(tr_link->tgt_prog);
3060 static void bpf_tracing_link_dealloc(struct bpf_link *link)
3062 struct bpf_tracing_link *tr_link =
3063 container_of(link, struct bpf_tracing_link, link.link);
3068 static void bpf_tracing_link_show_fdinfo(const struct bpf_link *link,
3069 struct seq_file *seq)
3071 struct bpf_tracing_link *tr_link =
3072 container_of(link, struct bpf_tracing_link, link.link);
3073 u32 target_btf_id, target_obj_id;
3075 bpf_trampoline_unpack_key(tr_link->trampoline->key,
3076 &target_obj_id, &target_btf_id);
3078 "attach_type:\t%d\n"
3079 "target_obj_id:\t%u\n"
3080 "target_btf_id:\t%u\n",
3081 tr_link->attach_type,
3086 static int bpf_tracing_link_fill_link_info(const struct bpf_link *link,
3087 struct bpf_link_info *info)
3089 struct bpf_tracing_link *tr_link =
3090 container_of(link, struct bpf_tracing_link, link.link);
3092 info->tracing.attach_type = tr_link->attach_type;
3093 bpf_trampoline_unpack_key(tr_link->trampoline->key,
3094 &info->tracing.target_obj_id,
3095 &info->tracing.target_btf_id);
3100 static const struct bpf_link_ops bpf_tracing_link_lops = {
3101 .release = bpf_tracing_link_release,
3102 .dealloc = bpf_tracing_link_dealloc,
3103 .show_fdinfo = bpf_tracing_link_show_fdinfo,
3104 .fill_link_info = bpf_tracing_link_fill_link_info,
3107 static int bpf_tracing_prog_attach(struct bpf_prog *prog,
3112 struct bpf_link_primer link_primer;
3113 struct bpf_prog *tgt_prog = NULL;
3114 struct bpf_trampoline *tr = NULL;
3115 struct bpf_tracing_link *link;
3119 switch (prog->type) {
3120 case BPF_PROG_TYPE_TRACING:
3121 if (prog->expected_attach_type != BPF_TRACE_FENTRY &&
3122 prog->expected_attach_type != BPF_TRACE_FEXIT &&
3123 prog->expected_attach_type != BPF_MODIFY_RETURN) {
3128 case BPF_PROG_TYPE_EXT:
3129 if (prog->expected_attach_type != 0) {
3134 case BPF_PROG_TYPE_LSM:
3135 if (prog->expected_attach_type != BPF_LSM_MAC) {
3145 if (!!tgt_prog_fd != !!btf_id) {
3151 /* For now we only allow new targets for BPF_PROG_TYPE_EXT */
3152 if (prog->type != BPF_PROG_TYPE_EXT) {
3157 tgt_prog = bpf_prog_get(tgt_prog_fd);
3158 if (IS_ERR(tgt_prog)) {
3159 err = PTR_ERR(tgt_prog);
3164 key = bpf_trampoline_compute_key(tgt_prog, NULL, btf_id);
3167 link = kzalloc(sizeof(*link), GFP_USER);
3172 bpf_link_init(&link->link.link, BPF_LINK_TYPE_TRACING,
3173 &bpf_tracing_link_lops, prog);
3174 link->attach_type = prog->expected_attach_type;
3175 link->link.cookie = bpf_cookie;
3177 mutex_lock(&prog->aux->dst_mutex);
3179 /* There are a few possible cases here:
3181 * - if prog->aux->dst_trampoline is set, the program was just loaded
3182 * and not yet attached to anything, so we can use the values stored
3185 * - if prog->aux->dst_trampoline is NULL, the program has already been
3186 * attached to a target and its initial target was cleared (below)
3188 * - if tgt_prog != NULL, the caller specified tgt_prog_fd +
3189 * target_btf_id using the link_create API.
3191 * - if tgt_prog == NULL when this function was called using the old
3192 * raw_tracepoint_open API, and we need a target from prog->aux
3194 * - if prog->aux->dst_trampoline and tgt_prog is NULL, the program
3195 * was detached and is going for re-attachment.
3197 if (!prog->aux->dst_trampoline && !tgt_prog) {
3199 * Allow re-attach for TRACING and LSM programs. If it's
3200 * currently linked, bpf_trampoline_link_prog will fail.
3201 * EXT programs need to specify tgt_prog_fd, so they
3202 * re-attach in separate code path.
3204 if (prog->type != BPF_PROG_TYPE_TRACING &&
3205 prog->type != BPF_PROG_TYPE_LSM) {
3209 btf_id = prog->aux->attach_btf_id;
3210 key = bpf_trampoline_compute_key(NULL, prog->aux->attach_btf, btf_id);
3213 if (!prog->aux->dst_trampoline ||
3214 (key && key != prog->aux->dst_trampoline->key)) {
3215 /* If there is no saved target, or the specified target is
3216 * different from the destination specified at load time, we
3217 * need a new trampoline and a check for compatibility
3219 struct bpf_attach_target_info tgt_info = {};
3221 err = bpf_check_attach_target(NULL, prog, tgt_prog, btf_id,
3226 if (tgt_info.tgt_mod) {
3227 module_put(prog->aux->mod);
3228 prog->aux->mod = tgt_info.tgt_mod;
3231 tr = bpf_trampoline_get(key, &tgt_info);
3237 /* The caller didn't specify a target, or the target was the
3238 * same as the destination supplied during program load. This
3239 * means we can reuse the trampoline and reference from program
3240 * load time, and there is no need to allocate a new one. This
3241 * can only happen once for any program, as the saved values in
3242 * prog->aux are cleared below.
3244 tr = prog->aux->dst_trampoline;
3245 tgt_prog = prog->aux->dst_prog;
3248 err = bpf_link_prime(&link->link.link, &link_primer);
3252 err = bpf_trampoline_link_prog(&link->link, tr);
3254 bpf_link_cleanup(&link_primer);
3259 link->tgt_prog = tgt_prog;
3260 link->trampoline = tr;
3262 /* Always clear the trampoline and target prog from prog->aux to make
3263 * sure the original attach destination is not kept alive after a
3264 * program is (re-)attached to another target.
3266 if (prog->aux->dst_prog &&
3267 (tgt_prog_fd || tr != prog->aux->dst_trampoline))
3268 /* got extra prog ref from syscall, or attaching to different prog */
3269 bpf_prog_put(prog->aux->dst_prog);
3270 if (prog->aux->dst_trampoline && tr != prog->aux->dst_trampoline)
3271 /* we allocated a new trampoline, so free the old one */
3272 bpf_trampoline_put(prog->aux->dst_trampoline);
3274 prog->aux->dst_prog = NULL;
3275 prog->aux->dst_trampoline = NULL;
3276 mutex_unlock(&prog->aux->dst_mutex);
3278 return bpf_link_settle(&link_primer);
3280 if (tr && tr != prog->aux->dst_trampoline)
3281 bpf_trampoline_put(tr);
3282 mutex_unlock(&prog->aux->dst_mutex);
3285 if (tgt_prog_fd && tgt_prog)
3286 bpf_prog_put(tgt_prog);
3290 struct bpf_raw_tp_link {
3291 struct bpf_link link;
3292 struct bpf_raw_event_map *btp;
3295 static void bpf_raw_tp_link_release(struct bpf_link *link)
3297 struct bpf_raw_tp_link *raw_tp =
3298 container_of(link, struct bpf_raw_tp_link, link);
3300 bpf_probe_unregister(raw_tp->btp, raw_tp->link.prog);
3301 bpf_put_raw_tracepoint(raw_tp->btp);
3304 static void bpf_raw_tp_link_dealloc(struct bpf_link *link)
3306 struct bpf_raw_tp_link *raw_tp =
3307 container_of(link, struct bpf_raw_tp_link, link);
3312 static void bpf_raw_tp_link_show_fdinfo(const struct bpf_link *link,
3313 struct seq_file *seq)
3315 struct bpf_raw_tp_link *raw_tp_link =
3316 container_of(link, struct bpf_raw_tp_link, link);
3320 raw_tp_link->btp->tp->name);
3323 static int bpf_copy_to_user(char __user *ubuf, const char *buf, u32 ulen,
3326 if (ulen >= len + 1) {
3327 if (copy_to_user(ubuf, buf, len + 1))
3332 if (copy_to_user(ubuf, buf, ulen - 1))
3334 if (put_user(zero, ubuf + ulen - 1))
3342 static int bpf_raw_tp_link_fill_link_info(const struct bpf_link *link,
3343 struct bpf_link_info *info)
3345 struct bpf_raw_tp_link *raw_tp_link =
3346 container_of(link, struct bpf_raw_tp_link, link);
3347 char __user *ubuf = u64_to_user_ptr(info->raw_tracepoint.tp_name);
3348 const char *tp_name = raw_tp_link->btp->tp->name;
3349 u32 ulen = info->raw_tracepoint.tp_name_len;
3350 size_t tp_len = strlen(tp_name);
3355 info->raw_tracepoint.tp_name_len = tp_len + 1;
3360 return bpf_copy_to_user(ubuf, tp_name, ulen, tp_len);
3363 static const struct bpf_link_ops bpf_raw_tp_link_lops = {
3364 .release = bpf_raw_tp_link_release,
3365 .dealloc = bpf_raw_tp_link_dealloc,
3366 .show_fdinfo = bpf_raw_tp_link_show_fdinfo,
3367 .fill_link_info = bpf_raw_tp_link_fill_link_info,
3370 #ifdef CONFIG_PERF_EVENTS
3371 struct bpf_perf_link {
3372 struct bpf_link link;
3373 struct file *perf_file;
3376 static void bpf_perf_link_release(struct bpf_link *link)
3378 struct bpf_perf_link *perf_link = container_of(link, struct bpf_perf_link, link);
3379 struct perf_event *event = perf_link->perf_file->private_data;
3381 perf_event_free_bpf_prog(event);
3382 fput(perf_link->perf_file);
3385 static void bpf_perf_link_dealloc(struct bpf_link *link)
3387 struct bpf_perf_link *perf_link = container_of(link, struct bpf_perf_link, link);
3392 static int bpf_perf_link_fill_common(const struct perf_event *event,
3393 char __user *uname, u32 ulen,
3394 u64 *probe_offset, u64 *probe_addr,
3405 err = bpf_get_perf_event_info(event, &prog_id, fd_type, &buf,
3406 probe_offset, probe_addr);
3413 err = bpf_copy_to_user(uname, buf, ulen, len);
3419 if (put_user(zero, uname))
3425 #ifdef CONFIG_KPROBE_EVENTS
3426 static int bpf_perf_link_fill_kprobe(const struct perf_event *event,
3427 struct bpf_link_info *info)
3434 uname = u64_to_user_ptr(info->perf_event.kprobe.func_name);
3435 ulen = info->perf_event.kprobe.name_len;
3436 err = bpf_perf_link_fill_common(event, uname, ulen, &offset, &addr,
3440 if (type == BPF_FD_TYPE_KRETPROBE)
3441 info->perf_event.type = BPF_PERF_EVENT_KRETPROBE;
3443 info->perf_event.type = BPF_PERF_EVENT_KPROBE;
3445 info->perf_event.kprobe.offset = offset;
3446 if (!kallsyms_show_value(current_cred()))
3448 info->perf_event.kprobe.addr = addr;
3453 #ifdef CONFIG_UPROBE_EVENTS
3454 static int bpf_perf_link_fill_uprobe(const struct perf_event *event,
3455 struct bpf_link_info *info)
3462 uname = u64_to_user_ptr(info->perf_event.uprobe.file_name);
3463 ulen = info->perf_event.uprobe.name_len;
3464 err = bpf_perf_link_fill_common(event, uname, ulen, &offset, &addr,
3469 if (type == BPF_FD_TYPE_URETPROBE)
3470 info->perf_event.type = BPF_PERF_EVENT_URETPROBE;
3472 info->perf_event.type = BPF_PERF_EVENT_UPROBE;
3473 info->perf_event.uprobe.offset = offset;
3478 static int bpf_perf_link_fill_probe(const struct perf_event *event,
3479 struct bpf_link_info *info)
3481 #ifdef CONFIG_KPROBE_EVENTS
3482 if (event->tp_event->flags & TRACE_EVENT_FL_KPROBE)
3483 return bpf_perf_link_fill_kprobe(event, info);
3485 #ifdef CONFIG_UPROBE_EVENTS
3486 if (event->tp_event->flags & TRACE_EVENT_FL_UPROBE)
3487 return bpf_perf_link_fill_uprobe(event, info);
3492 static int bpf_perf_link_fill_tracepoint(const struct perf_event *event,
3493 struct bpf_link_info *info)
3498 uname = u64_to_user_ptr(info->perf_event.tracepoint.tp_name);
3499 ulen = info->perf_event.tracepoint.name_len;
3500 info->perf_event.type = BPF_PERF_EVENT_TRACEPOINT;
3501 return bpf_perf_link_fill_common(event, uname, ulen, NULL, NULL, NULL);
3504 static int bpf_perf_link_fill_perf_event(const struct perf_event *event,
3505 struct bpf_link_info *info)
3507 info->perf_event.event.type = event->attr.type;
3508 info->perf_event.event.config = event->attr.config;
3509 info->perf_event.type = BPF_PERF_EVENT_EVENT;
3513 static int bpf_perf_link_fill_link_info(const struct bpf_link *link,
3514 struct bpf_link_info *info)
3516 struct bpf_perf_link *perf_link;
3517 const struct perf_event *event;
3519 perf_link = container_of(link, struct bpf_perf_link, link);
3520 event = perf_get_event(perf_link->perf_file);
3522 return PTR_ERR(event);
3524 switch (event->prog->type) {
3525 case BPF_PROG_TYPE_PERF_EVENT:
3526 return bpf_perf_link_fill_perf_event(event, info);
3527 case BPF_PROG_TYPE_TRACEPOINT:
3528 return bpf_perf_link_fill_tracepoint(event, info);
3529 case BPF_PROG_TYPE_KPROBE:
3530 return bpf_perf_link_fill_probe(event, info);
3536 static const struct bpf_link_ops bpf_perf_link_lops = {
3537 .release = bpf_perf_link_release,
3538 .dealloc = bpf_perf_link_dealloc,
3539 .fill_link_info = bpf_perf_link_fill_link_info,
3542 static int bpf_perf_link_attach(const union bpf_attr *attr, struct bpf_prog *prog)
3544 struct bpf_link_primer link_primer;
3545 struct bpf_perf_link *link;
3546 struct perf_event *event;
3547 struct file *perf_file;
3550 if (attr->link_create.flags)
3553 perf_file = perf_event_get(attr->link_create.target_fd);
3554 if (IS_ERR(perf_file))
3555 return PTR_ERR(perf_file);
3557 link = kzalloc(sizeof(*link), GFP_USER);
3562 bpf_link_init(&link->link, BPF_LINK_TYPE_PERF_EVENT, &bpf_perf_link_lops, prog);
3563 link->perf_file = perf_file;
3565 err = bpf_link_prime(&link->link, &link_primer);
3571 event = perf_file->private_data;
3572 err = perf_event_set_bpf_prog(event, prog, attr->link_create.perf_event.bpf_cookie);
3574 bpf_link_cleanup(&link_primer);
3577 /* perf_event_set_bpf_prog() doesn't take its own refcnt on prog */
3580 return bpf_link_settle(&link_primer);
3587 static int bpf_perf_link_attach(const union bpf_attr *attr, struct bpf_prog *prog)
3591 #endif /* CONFIG_PERF_EVENTS */
3593 static int bpf_raw_tp_link_attach(struct bpf_prog *prog,
3594 const char __user *user_tp_name)
3596 struct bpf_link_primer link_primer;
3597 struct bpf_raw_tp_link *link;
3598 struct bpf_raw_event_map *btp;
3599 const char *tp_name;
3603 switch (prog->type) {
3604 case BPF_PROG_TYPE_TRACING:
3605 case BPF_PROG_TYPE_EXT:
3606 case BPF_PROG_TYPE_LSM:
3608 /* The attach point for this category of programs
3609 * should be specified via btf_id during program load.
3612 if (prog->type == BPF_PROG_TYPE_TRACING &&
3613 prog->expected_attach_type == BPF_TRACE_RAW_TP) {
3614 tp_name = prog->aux->attach_func_name;
3617 return bpf_tracing_prog_attach(prog, 0, 0, 0);
3618 case BPF_PROG_TYPE_RAW_TRACEPOINT:
3619 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
3620 if (strncpy_from_user(buf, user_tp_name, sizeof(buf) - 1) < 0)
3622 buf[sizeof(buf) - 1] = 0;
3629 btp = bpf_get_raw_tracepoint(tp_name);
3633 link = kzalloc(sizeof(*link), GFP_USER);
3638 bpf_link_init(&link->link, BPF_LINK_TYPE_RAW_TRACEPOINT,
3639 &bpf_raw_tp_link_lops, prog);
3642 err = bpf_link_prime(&link->link, &link_primer);
3648 err = bpf_probe_register(link->btp, prog);
3650 bpf_link_cleanup(&link_primer);
3654 return bpf_link_settle(&link_primer);
3657 bpf_put_raw_tracepoint(btp);
3661 #define BPF_RAW_TRACEPOINT_OPEN_LAST_FIELD raw_tracepoint.prog_fd
3663 static int bpf_raw_tracepoint_open(const union bpf_attr *attr)
3665 struct bpf_prog *prog;
3668 if (CHECK_ATTR(BPF_RAW_TRACEPOINT_OPEN))
3671 prog = bpf_prog_get(attr->raw_tracepoint.prog_fd);
3673 return PTR_ERR(prog);
3675 fd = bpf_raw_tp_link_attach(prog, u64_to_user_ptr(attr->raw_tracepoint.name));
3681 static enum bpf_prog_type
3682 attach_type_to_prog_type(enum bpf_attach_type attach_type)
3684 switch (attach_type) {
3685 case BPF_CGROUP_INET_INGRESS:
3686 case BPF_CGROUP_INET_EGRESS:
3687 return BPF_PROG_TYPE_CGROUP_SKB;
3688 case BPF_CGROUP_INET_SOCK_CREATE:
3689 case BPF_CGROUP_INET_SOCK_RELEASE:
3690 case BPF_CGROUP_INET4_POST_BIND:
3691 case BPF_CGROUP_INET6_POST_BIND:
3692 return BPF_PROG_TYPE_CGROUP_SOCK;
3693 case BPF_CGROUP_INET4_BIND:
3694 case BPF_CGROUP_INET6_BIND:
3695 case BPF_CGROUP_INET4_CONNECT:
3696 case BPF_CGROUP_INET6_CONNECT:
3697 case BPF_CGROUP_INET4_GETPEERNAME:
3698 case BPF_CGROUP_INET6_GETPEERNAME:
3699 case BPF_CGROUP_INET4_GETSOCKNAME:
3700 case BPF_CGROUP_INET6_GETSOCKNAME:
3701 case BPF_CGROUP_UDP4_SENDMSG:
3702 case BPF_CGROUP_UDP6_SENDMSG:
3703 case BPF_CGROUP_UDP4_RECVMSG:
3704 case BPF_CGROUP_UDP6_RECVMSG:
3705 return BPF_PROG_TYPE_CGROUP_SOCK_ADDR;
3706 case BPF_CGROUP_SOCK_OPS:
3707 return BPF_PROG_TYPE_SOCK_OPS;
3708 case BPF_CGROUP_DEVICE:
3709 return BPF_PROG_TYPE_CGROUP_DEVICE;
3710 case BPF_SK_MSG_VERDICT:
3711 return BPF_PROG_TYPE_SK_MSG;
3712 case BPF_SK_SKB_STREAM_PARSER:
3713 case BPF_SK_SKB_STREAM_VERDICT:
3714 case BPF_SK_SKB_VERDICT:
3715 return BPF_PROG_TYPE_SK_SKB;
3716 case BPF_LIRC_MODE2:
3717 return BPF_PROG_TYPE_LIRC_MODE2;
3718 case BPF_FLOW_DISSECTOR:
3719 return BPF_PROG_TYPE_FLOW_DISSECTOR;
3720 case BPF_CGROUP_SYSCTL:
3721 return BPF_PROG_TYPE_CGROUP_SYSCTL;
3722 case BPF_CGROUP_GETSOCKOPT:
3723 case BPF_CGROUP_SETSOCKOPT:
3724 return BPF_PROG_TYPE_CGROUP_SOCKOPT;
3725 case BPF_TRACE_ITER:
3726 case BPF_TRACE_RAW_TP:
3727 case BPF_TRACE_FENTRY:
3728 case BPF_TRACE_FEXIT:
3729 case BPF_MODIFY_RETURN:
3730 return BPF_PROG_TYPE_TRACING;
3732 return BPF_PROG_TYPE_LSM;
3734 return BPF_PROG_TYPE_SK_LOOKUP;
3736 return BPF_PROG_TYPE_XDP;
3737 case BPF_LSM_CGROUP:
3738 return BPF_PROG_TYPE_LSM;
3739 case BPF_TCX_INGRESS:
3740 case BPF_TCX_EGRESS:
3741 return BPF_PROG_TYPE_SCHED_CLS;
3743 return BPF_PROG_TYPE_UNSPEC;
3747 static int bpf_prog_attach_check_attach_type(const struct bpf_prog *prog,
3748 enum bpf_attach_type attach_type)
3750 enum bpf_prog_type ptype;
3752 switch (prog->type) {
3753 case BPF_PROG_TYPE_CGROUP_SOCK:
3754 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
3755 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3756 case BPF_PROG_TYPE_SK_LOOKUP:
3757 return attach_type == prog->expected_attach_type ? 0 : -EINVAL;
3758 case BPF_PROG_TYPE_CGROUP_SKB:
3759 if (!capable(CAP_NET_ADMIN))
3760 /* cg-skb progs can be loaded by unpriv user.
3761 * check permissions at attach time.
3764 return prog->enforce_expected_attach_type &&
3765 prog->expected_attach_type != attach_type ?
3767 case BPF_PROG_TYPE_EXT:
3769 case BPF_PROG_TYPE_NETFILTER:
3770 if (attach_type != BPF_NETFILTER)
3773 case BPF_PROG_TYPE_PERF_EVENT:
3774 case BPF_PROG_TYPE_TRACEPOINT:
3775 if (attach_type != BPF_PERF_EVENT)
3778 case BPF_PROG_TYPE_KPROBE:
3779 if (prog->expected_attach_type == BPF_TRACE_KPROBE_MULTI &&
3780 attach_type != BPF_TRACE_KPROBE_MULTI)
3782 if (prog->expected_attach_type == BPF_TRACE_UPROBE_MULTI &&
3783 attach_type != BPF_TRACE_UPROBE_MULTI)
3785 if (attach_type != BPF_PERF_EVENT &&
3786 attach_type != BPF_TRACE_KPROBE_MULTI &&
3787 attach_type != BPF_TRACE_UPROBE_MULTI)
3790 case BPF_PROG_TYPE_SCHED_CLS:
3791 if (attach_type != BPF_TCX_INGRESS &&
3792 attach_type != BPF_TCX_EGRESS)
3796 ptype = attach_type_to_prog_type(attach_type);
3797 if (ptype == BPF_PROG_TYPE_UNSPEC || ptype != prog->type)
3803 #define BPF_PROG_ATTACH_LAST_FIELD expected_revision
3805 #define BPF_F_ATTACH_MASK_BASE \
3806 (BPF_F_ALLOW_OVERRIDE | \
3807 BPF_F_ALLOW_MULTI | \
3810 #define BPF_F_ATTACH_MASK_MPROG \
3817 static int bpf_prog_attach(const union bpf_attr *attr)
3819 enum bpf_prog_type ptype;
3820 struct bpf_prog *prog;
3823 if (CHECK_ATTR(BPF_PROG_ATTACH))
3826 ptype = attach_type_to_prog_type(attr->attach_type);
3827 if (ptype == BPF_PROG_TYPE_UNSPEC)
3829 if (bpf_mprog_supported(ptype)) {
3830 if (attr->attach_flags & ~BPF_F_ATTACH_MASK_MPROG)
3833 if (attr->attach_flags & ~BPF_F_ATTACH_MASK_BASE)
3835 if (attr->relative_fd ||
3836 attr->expected_revision)
3840 prog = bpf_prog_get_type(attr->attach_bpf_fd, ptype);
3842 return PTR_ERR(prog);
3844 if (bpf_prog_attach_check_attach_type(prog, attr->attach_type)) {
3850 case BPF_PROG_TYPE_SK_SKB:
3851 case BPF_PROG_TYPE_SK_MSG:
3852 ret = sock_map_get_from_fd(attr, prog);
3854 case BPF_PROG_TYPE_LIRC_MODE2:
3855 ret = lirc_prog_attach(attr, prog);
3857 case BPF_PROG_TYPE_FLOW_DISSECTOR:
3858 ret = netns_bpf_prog_attach(attr, prog);
3860 case BPF_PROG_TYPE_CGROUP_DEVICE:
3861 case BPF_PROG_TYPE_CGROUP_SKB:
3862 case BPF_PROG_TYPE_CGROUP_SOCK:
3863 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
3864 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3865 case BPF_PROG_TYPE_CGROUP_SYSCTL:
3866 case BPF_PROG_TYPE_SOCK_OPS:
3867 case BPF_PROG_TYPE_LSM:
3868 if (ptype == BPF_PROG_TYPE_LSM &&
3869 prog->expected_attach_type != BPF_LSM_CGROUP)
3872 ret = cgroup_bpf_prog_attach(attr, ptype, prog);
3874 case BPF_PROG_TYPE_SCHED_CLS:
3875 ret = tcx_prog_attach(attr, prog);
3886 #define BPF_PROG_DETACH_LAST_FIELD expected_revision
3888 static int bpf_prog_detach(const union bpf_attr *attr)
3890 struct bpf_prog *prog = NULL;
3891 enum bpf_prog_type ptype;
3894 if (CHECK_ATTR(BPF_PROG_DETACH))
3897 ptype = attach_type_to_prog_type(attr->attach_type);
3898 if (bpf_mprog_supported(ptype)) {
3899 if (ptype == BPF_PROG_TYPE_UNSPEC)
3901 if (attr->attach_flags & ~BPF_F_ATTACH_MASK_MPROG)
3903 if (attr->attach_bpf_fd) {
3904 prog = bpf_prog_get_type(attr->attach_bpf_fd, ptype);
3906 return PTR_ERR(prog);
3908 } else if (attr->attach_flags ||
3909 attr->relative_fd ||
3910 attr->expected_revision) {
3915 case BPF_PROG_TYPE_SK_MSG:
3916 case BPF_PROG_TYPE_SK_SKB:
3917 ret = sock_map_prog_detach(attr, ptype);
3919 case BPF_PROG_TYPE_LIRC_MODE2:
3920 ret = lirc_prog_detach(attr);
3922 case BPF_PROG_TYPE_FLOW_DISSECTOR:
3923 ret = netns_bpf_prog_detach(attr, ptype);
3925 case BPF_PROG_TYPE_CGROUP_DEVICE:
3926 case BPF_PROG_TYPE_CGROUP_SKB:
3927 case BPF_PROG_TYPE_CGROUP_SOCK:
3928 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
3929 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3930 case BPF_PROG_TYPE_CGROUP_SYSCTL:
3931 case BPF_PROG_TYPE_SOCK_OPS:
3932 case BPF_PROG_TYPE_LSM:
3933 ret = cgroup_bpf_prog_detach(attr, ptype);
3935 case BPF_PROG_TYPE_SCHED_CLS:
3936 ret = tcx_prog_detach(attr, prog);
3947 #define BPF_PROG_QUERY_LAST_FIELD query.revision
3949 static int bpf_prog_query(const union bpf_attr *attr,
3950 union bpf_attr __user *uattr)
3952 if (!capable(CAP_NET_ADMIN))
3954 if (CHECK_ATTR(BPF_PROG_QUERY))
3956 if (attr->query.query_flags & ~BPF_F_QUERY_EFFECTIVE)
3959 switch (attr->query.attach_type) {
3960 case BPF_CGROUP_INET_INGRESS:
3961 case BPF_CGROUP_INET_EGRESS:
3962 case BPF_CGROUP_INET_SOCK_CREATE:
3963 case BPF_CGROUP_INET_SOCK_RELEASE:
3964 case BPF_CGROUP_INET4_BIND:
3965 case BPF_CGROUP_INET6_BIND:
3966 case BPF_CGROUP_INET4_POST_BIND:
3967 case BPF_CGROUP_INET6_POST_BIND:
3968 case BPF_CGROUP_INET4_CONNECT:
3969 case BPF_CGROUP_INET6_CONNECT:
3970 case BPF_CGROUP_INET4_GETPEERNAME:
3971 case BPF_CGROUP_INET6_GETPEERNAME:
3972 case BPF_CGROUP_INET4_GETSOCKNAME:
3973 case BPF_CGROUP_INET6_GETSOCKNAME:
3974 case BPF_CGROUP_UDP4_SENDMSG:
3975 case BPF_CGROUP_UDP6_SENDMSG:
3976 case BPF_CGROUP_UDP4_RECVMSG:
3977 case BPF_CGROUP_UDP6_RECVMSG:
3978 case BPF_CGROUP_SOCK_OPS:
3979 case BPF_CGROUP_DEVICE:
3980 case BPF_CGROUP_SYSCTL:
3981 case BPF_CGROUP_GETSOCKOPT:
3982 case BPF_CGROUP_SETSOCKOPT:
3983 case BPF_LSM_CGROUP:
3984 return cgroup_bpf_prog_query(attr, uattr);
3985 case BPF_LIRC_MODE2:
3986 return lirc_prog_query(attr, uattr);
3987 case BPF_FLOW_DISSECTOR:
3989 return netns_bpf_prog_query(attr, uattr);
3990 case BPF_SK_SKB_STREAM_PARSER:
3991 case BPF_SK_SKB_STREAM_VERDICT:
3992 case BPF_SK_MSG_VERDICT:
3993 case BPF_SK_SKB_VERDICT:
3994 return sock_map_bpf_prog_query(attr, uattr);
3995 case BPF_TCX_INGRESS:
3996 case BPF_TCX_EGRESS:
3997 return tcx_prog_query(attr, uattr);
4003 #define BPF_PROG_TEST_RUN_LAST_FIELD test.batch_size
4005 static int bpf_prog_test_run(const union bpf_attr *attr,
4006 union bpf_attr __user *uattr)
4008 struct bpf_prog *prog;
4009 int ret = -ENOTSUPP;
4011 if (CHECK_ATTR(BPF_PROG_TEST_RUN))
4014 if ((attr->test.ctx_size_in && !attr->test.ctx_in) ||
4015 (!attr->test.ctx_size_in && attr->test.ctx_in))
4018 if ((attr->test.ctx_size_out && !attr->test.ctx_out) ||
4019 (!attr->test.ctx_size_out && attr->test.ctx_out))
4022 prog = bpf_prog_get(attr->test.prog_fd);
4024 return PTR_ERR(prog);
4026 if (prog->aux->ops->test_run)
4027 ret = prog->aux->ops->test_run(prog, attr, uattr);
4033 #define BPF_OBJ_GET_NEXT_ID_LAST_FIELD next_id
4035 static int bpf_obj_get_next_id(const union bpf_attr *attr,
4036 union bpf_attr __user *uattr,
4040 u32 next_id = attr->start_id;
4043 if (CHECK_ATTR(BPF_OBJ_GET_NEXT_ID) || next_id >= INT_MAX)
4046 if (!capable(CAP_SYS_ADMIN))
4051 if (!idr_get_next(idr, &next_id))
4053 spin_unlock_bh(lock);
4056 err = put_user(next_id, &uattr->next_id);
4061 struct bpf_map *bpf_map_get_curr_or_next(u32 *id)
4063 struct bpf_map *map;
4065 spin_lock_bh(&map_idr_lock);
4067 map = idr_get_next(&map_idr, id);
4069 map = __bpf_map_inc_not_zero(map, false);
4075 spin_unlock_bh(&map_idr_lock);
4080 struct bpf_prog *bpf_prog_get_curr_or_next(u32 *id)
4082 struct bpf_prog *prog;
4084 spin_lock_bh(&prog_idr_lock);
4086 prog = idr_get_next(&prog_idr, id);
4088 prog = bpf_prog_inc_not_zero(prog);
4094 spin_unlock_bh(&prog_idr_lock);
4099 #define BPF_PROG_GET_FD_BY_ID_LAST_FIELD prog_id
4101 struct bpf_prog *bpf_prog_by_id(u32 id)
4103 struct bpf_prog *prog;
4106 return ERR_PTR(-ENOENT);
4108 spin_lock_bh(&prog_idr_lock);
4109 prog = idr_find(&prog_idr, id);
4111 prog = bpf_prog_inc_not_zero(prog);
4113 prog = ERR_PTR(-ENOENT);
4114 spin_unlock_bh(&prog_idr_lock);
4118 static int bpf_prog_get_fd_by_id(const union bpf_attr *attr)
4120 struct bpf_prog *prog;
4121 u32 id = attr->prog_id;
4124 if (CHECK_ATTR(BPF_PROG_GET_FD_BY_ID))
4127 if (!capable(CAP_SYS_ADMIN))
4130 prog = bpf_prog_by_id(id);
4132 return PTR_ERR(prog);
4134 fd = bpf_prog_new_fd(prog);
4141 #define BPF_MAP_GET_FD_BY_ID_LAST_FIELD open_flags
4143 static int bpf_map_get_fd_by_id(const union bpf_attr *attr)
4145 struct bpf_map *map;
4146 u32 id = attr->map_id;
4150 if (CHECK_ATTR(BPF_MAP_GET_FD_BY_ID) ||
4151 attr->open_flags & ~BPF_OBJ_FLAG_MASK)
4154 if (!capable(CAP_SYS_ADMIN))
4157 f_flags = bpf_get_file_flag(attr->open_flags);
4161 spin_lock_bh(&map_idr_lock);
4162 map = idr_find(&map_idr, id);
4164 map = __bpf_map_inc_not_zero(map, true);
4166 map = ERR_PTR(-ENOENT);
4167 spin_unlock_bh(&map_idr_lock);
4170 return PTR_ERR(map);
4172 fd = bpf_map_new_fd(map, f_flags);
4174 bpf_map_put_with_uref(map);
4179 static const struct bpf_map *bpf_map_from_imm(const struct bpf_prog *prog,
4180 unsigned long addr, u32 *off,
4183 const struct bpf_map *map;
4186 mutex_lock(&prog->aux->used_maps_mutex);
4187 for (i = 0, *off = 0; i < prog->aux->used_map_cnt; i++) {
4188 map = prog->aux->used_maps[i];
4189 if (map == (void *)addr) {
4190 *type = BPF_PSEUDO_MAP_FD;
4193 if (!map->ops->map_direct_value_meta)
4195 if (!map->ops->map_direct_value_meta(map, addr, off)) {
4196 *type = BPF_PSEUDO_MAP_VALUE;
4203 mutex_unlock(&prog->aux->used_maps_mutex);
4207 static struct bpf_insn *bpf_insn_prepare_dump(const struct bpf_prog *prog,
4208 const struct cred *f_cred)
4210 const struct bpf_map *map;
4211 struct bpf_insn *insns;
4217 insns = kmemdup(prog->insnsi, bpf_prog_insn_size(prog),
4222 for (i = 0; i < prog->len; i++) {
4223 code = insns[i].code;
4225 if (code == (BPF_JMP | BPF_TAIL_CALL)) {
4226 insns[i].code = BPF_JMP | BPF_CALL;
4227 insns[i].imm = BPF_FUNC_tail_call;
4230 if (code == (BPF_JMP | BPF_CALL) ||
4231 code == (BPF_JMP | BPF_CALL_ARGS)) {
4232 if (code == (BPF_JMP | BPF_CALL_ARGS))
4233 insns[i].code = BPF_JMP | BPF_CALL;
4234 if (!bpf_dump_raw_ok(f_cred))
4238 if (BPF_CLASS(code) == BPF_LDX && BPF_MODE(code) == BPF_PROBE_MEM) {
4239 insns[i].code = BPF_LDX | BPF_SIZE(code) | BPF_MEM;
4243 if (code != (BPF_LD | BPF_IMM | BPF_DW))
4246 imm = ((u64)insns[i + 1].imm << 32) | (u32)insns[i].imm;
4247 map = bpf_map_from_imm(prog, imm, &off, &type);
4249 insns[i].src_reg = type;
4250 insns[i].imm = map->id;
4251 insns[i + 1].imm = off;
4259 static int set_info_rec_size(struct bpf_prog_info *info)
4262 * Ensure info.*_rec_size is the same as kernel expected size
4266 * Only allow zero *_rec_size if both _rec_size and _cnt are
4267 * zero. In this case, the kernel will set the expected
4268 * _rec_size back to the info.
4271 if ((info->nr_func_info || info->func_info_rec_size) &&
4272 info->func_info_rec_size != sizeof(struct bpf_func_info))
4275 if ((info->nr_line_info || info->line_info_rec_size) &&
4276 info->line_info_rec_size != sizeof(struct bpf_line_info))
4279 if ((info->nr_jited_line_info || info->jited_line_info_rec_size) &&
4280 info->jited_line_info_rec_size != sizeof(__u64))
4283 info->func_info_rec_size = sizeof(struct bpf_func_info);
4284 info->line_info_rec_size = sizeof(struct bpf_line_info);
4285 info->jited_line_info_rec_size = sizeof(__u64);
4290 static int bpf_prog_get_info_by_fd(struct file *file,
4291 struct bpf_prog *prog,
4292 const union bpf_attr *attr,
4293 union bpf_attr __user *uattr)
4295 struct bpf_prog_info __user *uinfo = u64_to_user_ptr(attr->info.info);
4296 struct btf *attach_btf = bpf_prog_get_target_btf(prog);
4297 struct bpf_prog_info info;
4298 u32 info_len = attr->info.info_len;
4299 struct bpf_prog_kstats stats;
4300 char __user *uinsns;
4304 err = bpf_check_uarg_tail_zero(USER_BPFPTR(uinfo), sizeof(info), info_len);
4307 info_len = min_t(u32, sizeof(info), info_len);
4309 memset(&info, 0, sizeof(info));
4310 if (copy_from_user(&info, uinfo, info_len))
4313 info.type = prog->type;
4314 info.id = prog->aux->id;
4315 info.load_time = prog->aux->load_time;
4316 info.created_by_uid = from_kuid_munged(current_user_ns(),
4317 prog->aux->user->uid);
4318 info.gpl_compatible = prog->gpl_compatible;
4320 memcpy(info.tag, prog->tag, sizeof(prog->tag));
4321 memcpy(info.name, prog->aux->name, sizeof(prog->aux->name));
4323 mutex_lock(&prog->aux->used_maps_mutex);
4324 ulen = info.nr_map_ids;
4325 info.nr_map_ids = prog->aux->used_map_cnt;
4326 ulen = min_t(u32, info.nr_map_ids, ulen);
4328 u32 __user *user_map_ids = u64_to_user_ptr(info.map_ids);
4331 for (i = 0; i < ulen; i++)
4332 if (put_user(prog->aux->used_maps[i]->id,
4333 &user_map_ids[i])) {
4334 mutex_unlock(&prog->aux->used_maps_mutex);
4338 mutex_unlock(&prog->aux->used_maps_mutex);
4340 err = set_info_rec_size(&info);
4344 bpf_prog_get_stats(prog, &stats);
4345 info.run_time_ns = stats.nsecs;
4346 info.run_cnt = stats.cnt;
4347 info.recursion_misses = stats.misses;
4349 info.verified_insns = prog->aux->verified_insns;
4351 if (!bpf_capable()) {
4352 info.jited_prog_len = 0;
4353 info.xlated_prog_len = 0;
4354 info.nr_jited_ksyms = 0;
4355 info.nr_jited_func_lens = 0;
4356 info.nr_func_info = 0;
4357 info.nr_line_info = 0;
4358 info.nr_jited_line_info = 0;
4362 ulen = info.xlated_prog_len;
4363 info.xlated_prog_len = bpf_prog_insn_size(prog);
4364 if (info.xlated_prog_len && ulen) {
4365 struct bpf_insn *insns_sanitized;
4368 if (prog->blinded && !bpf_dump_raw_ok(file->f_cred)) {
4369 info.xlated_prog_insns = 0;
4372 insns_sanitized = bpf_insn_prepare_dump(prog, file->f_cred);
4373 if (!insns_sanitized)
4375 uinsns = u64_to_user_ptr(info.xlated_prog_insns);
4376 ulen = min_t(u32, info.xlated_prog_len, ulen);
4377 fault = copy_to_user(uinsns, insns_sanitized, ulen);
4378 kfree(insns_sanitized);
4383 if (bpf_prog_is_offloaded(prog->aux)) {
4384 err = bpf_prog_offload_info_fill(&info, prog);
4390 /* NOTE: the following code is supposed to be skipped for offload.
4391 * bpf_prog_offload_info_fill() is the place to fill similar fields
4394 ulen = info.jited_prog_len;
4395 if (prog->aux->func_cnt) {
4398 info.jited_prog_len = 0;
4399 for (i = 0; i < prog->aux->func_cnt; i++)
4400 info.jited_prog_len += prog->aux->func[i]->jited_len;
4402 info.jited_prog_len = prog->jited_len;
4405 if (info.jited_prog_len && ulen) {
4406 if (bpf_dump_raw_ok(file->f_cred)) {
4407 uinsns = u64_to_user_ptr(info.jited_prog_insns);
4408 ulen = min_t(u32, info.jited_prog_len, ulen);
4410 /* for multi-function programs, copy the JITed
4411 * instructions for all the functions
4413 if (prog->aux->func_cnt) {
4418 for (i = 0; i < prog->aux->func_cnt; i++) {
4419 len = prog->aux->func[i]->jited_len;
4420 len = min_t(u32, len, free);
4421 img = (u8 *) prog->aux->func[i]->bpf_func;
4422 if (copy_to_user(uinsns, img, len))
4430 if (copy_to_user(uinsns, prog->bpf_func, ulen))
4434 info.jited_prog_insns = 0;
4438 ulen = info.nr_jited_ksyms;
4439 info.nr_jited_ksyms = prog->aux->func_cnt ? : 1;
4441 if (bpf_dump_raw_ok(file->f_cred)) {
4442 unsigned long ksym_addr;
4443 u64 __user *user_ksyms;
4446 /* copy the address of the kernel symbol
4447 * corresponding to each function
4449 ulen = min_t(u32, info.nr_jited_ksyms, ulen);
4450 user_ksyms = u64_to_user_ptr(info.jited_ksyms);
4451 if (prog->aux->func_cnt) {
4452 for (i = 0; i < ulen; i++) {
4453 ksym_addr = (unsigned long)
4454 prog->aux->func[i]->bpf_func;
4455 if (put_user((u64) ksym_addr,
4460 ksym_addr = (unsigned long) prog->bpf_func;
4461 if (put_user((u64) ksym_addr, &user_ksyms[0]))
4465 info.jited_ksyms = 0;
4469 ulen = info.nr_jited_func_lens;
4470 info.nr_jited_func_lens = prog->aux->func_cnt ? : 1;
4472 if (bpf_dump_raw_ok(file->f_cred)) {
4473 u32 __user *user_lens;
4476 /* copy the JITed image lengths for each function */
4477 ulen = min_t(u32, info.nr_jited_func_lens, ulen);
4478 user_lens = u64_to_user_ptr(info.jited_func_lens);
4479 if (prog->aux->func_cnt) {
4480 for (i = 0; i < ulen; i++) {
4482 prog->aux->func[i]->jited_len;
4483 if (put_user(func_len, &user_lens[i]))
4487 func_len = prog->jited_len;
4488 if (put_user(func_len, &user_lens[0]))
4492 info.jited_func_lens = 0;
4497 info.btf_id = btf_obj_id(prog->aux->btf);
4498 info.attach_btf_id = prog->aux->attach_btf_id;
4500 info.attach_btf_obj_id = btf_obj_id(attach_btf);
4502 ulen = info.nr_func_info;
4503 info.nr_func_info = prog->aux->func_info_cnt;
4504 if (info.nr_func_info && ulen) {
4505 char __user *user_finfo;
4507 user_finfo = u64_to_user_ptr(info.func_info);
4508 ulen = min_t(u32, info.nr_func_info, ulen);
4509 if (copy_to_user(user_finfo, prog->aux->func_info,
4510 info.func_info_rec_size * ulen))
4514 ulen = info.nr_line_info;
4515 info.nr_line_info = prog->aux->nr_linfo;
4516 if (info.nr_line_info && ulen) {
4517 __u8 __user *user_linfo;
4519 user_linfo = u64_to_user_ptr(info.line_info);
4520 ulen = min_t(u32, info.nr_line_info, ulen);
4521 if (copy_to_user(user_linfo, prog->aux->linfo,
4522 info.line_info_rec_size * ulen))
4526 ulen = info.nr_jited_line_info;
4527 if (prog->aux->jited_linfo)
4528 info.nr_jited_line_info = prog->aux->nr_linfo;
4530 info.nr_jited_line_info = 0;
4531 if (info.nr_jited_line_info && ulen) {
4532 if (bpf_dump_raw_ok(file->f_cred)) {
4533 unsigned long line_addr;
4534 __u64 __user *user_linfo;
4537 user_linfo = u64_to_user_ptr(info.jited_line_info);
4538 ulen = min_t(u32, info.nr_jited_line_info, ulen);
4539 for (i = 0; i < ulen; i++) {
4540 line_addr = (unsigned long)prog->aux->jited_linfo[i];
4541 if (put_user((__u64)line_addr, &user_linfo[i]))
4545 info.jited_line_info = 0;
4549 ulen = info.nr_prog_tags;
4550 info.nr_prog_tags = prog->aux->func_cnt ? : 1;
4552 __u8 __user (*user_prog_tags)[BPF_TAG_SIZE];
4555 user_prog_tags = u64_to_user_ptr(info.prog_tags);
4556 ulen = min_t(u32, info.nr_prog_tags, ulen);
4557 if (prog->aux->func_cnt) {
4558 for (i = 0; i < ulen; i++) {
4559 if (copy_to_user(user_prog_tags[i],
4560 prog->aux->func[i]->tag,
4565 if (copy_to_user(user_prog_tags[0],
4566 prog->tag, BPF_TAG_SIZE))
4572 if (copy_to_user(uinfo, &info, info_len) ||
4573 put_user(info_len, &uattr->info.info_len))
4579 static int bpf_map_get_info_by_fd(struct file *file,
4580 struct bpf_map *map,
4581 const union bpf_attr *attr,
4582 union bpf_attr __user *uattr)
4584 struct bpf_map_info __user *uinfo = u64_to_user_ptr(attr->info.info);
4585 struct bpf_map_info info;
4586 u32 info_len = attr->info.info_len;
4589 err = bpf_check_uarg_tail_zero(USER_BPFPTR(uinfo), sizeof(info), info_len);
4592 info_len = min_t(u32, sizeof(info), info_len);
4594 memset(&info, 0, sizeof(info));
4595 info.type = map->map_type;
4597 info.key_size = map->key_size;
4598 info.value_size = map->value_size;
4599 info.max_entries = map->max_entries;
4600 info.map_flags = map->map_flags;
4601 info.map_extra = map->map_extra;
4602 memcpy(info.name, map->name, sizeof(map->name));
4605 info.btf_id = btf_obj_id(map->btf);
4606 info.btf_key_type_id = map->btf_key_type_id;
4607 info.btf_value_type_id = map->btf_value_type_id;
4609 info.btf_vmlinux_value_type_id = map->btf_vmlinux_value_type_id;
4611 if (bpf_map_is_offloaded(map)) {
4612 err = bpf_map_offload_info_fill(&info, map);
4617 if (copy_to_user(uinfo, &info, info_len) ||
4618 put_user(info_len, &uattr->info.info_len))
4624 static int bpf_btf_get_info_by_fd(struct file *file,
4626 const union bpf_attr *attr,
4627 union bpf_attr __user *uattr)
4629 struct bpf_btf_info __user *uinfo = u64_to_user_ptr(attr->info.info);
4630 u32 info_len = attr->info.info_len;
4633 err = bpf_check_uarg_tail_zero(USER_BPFPTR(uinfo), sizeof(*uinfo), info_len);
4637 return btf_get_info_by_fd(btf, attr, uattr);
4640 static int bpf_link_get_info_by_fd(struct file *file,
4641 struct bpf_link *link,
4642 const union bpf_attr *attr,
4643 union bpf_attr __user *uattr)
4645 struct bpf_link_info __user *uinfo = u64_to_user_ptr(attr->info.info);
4646 struct bpf_link_info info;
4647 u32 info_len = attr->info.info_len;
4650 err = bpf_check_uarg_tail_zero(USER_BPFPTR(uinfo), sizeof(info), info_len);
4653 info_len = min_t(u32, sizeof(info), info_len);
4655 memset(&info, 0, sizeof(info));
4656 if (copy_from_user(&info, uinfo, info_len))
4659 info.type = link->type;
4662 info.prog_id = link->prog->aux->id;
4664 if (link->ops->fill_link_info) {
4665 err = link->ops->fill_link_info(link, &info);
4670 if (copy_to_user(uinfo, &info, info_len) ||
4671 put_user(info_len, &uattr->info.info_len))
4678 #define BPF_OBJ_GET_INFO_BY_FD_LAST_FIELD info.info
4680 static int bpf_obj_get_info_by_fd(const union bpf_attr *attr,
4681 union bpf_attr __user *uattr)
4683 int ufd = attr->info.bpf_fd;
4687 if (CHECK_ATTR(BPF_OBJ_GET_INFO_BY_FD))
4694 if (f.file->f_op == &bpf_prog_fops)
4695 err = bpf_prog_get_info_by_fd(f.file, f.file->private_data, attr,
4697 else if (f.file->f_op == &bpf_map_fops)
4698 err = bpf_map_get_info_by_fd(f.file, f.file->private_data, attr,
4700 else if (f.file->f_op == &btf_fops)
4701 err = bpf_btf_get_info_by_fd(f.file, f.file->private_data, attr, uattr);
4702 else if (f.file->f_op == &bpf_link_fops)
4703 err = bpf_link_get_info_by_fd(f.file, f.file->private_data,
4712 #define BPF_BTF_LOAD_LAST_FIELD btf_log_true_size
4714 static int bpf_btf_load(const union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size)
4716 if (CHECK_ATTR(BPF_BTF_LOAD))
4722 return btf_new_fd(attr, uattr, uattr_size);
4725 #define BPF_BTF_GET_FD_BY_ID_LAST_FIELD btf_id
4727 static int bpf_btf_get_fd_by_id(const union bpf_attr *attr)
4729 if (CHECK_ATTR(BPF_BTF_GET_FD_BY_ID))
4732 if (!capable(CAP_SYS_ADMIN))
4735 return btf_get_fd_by_id(attr->btf_id);
4738 static int bpf_task_fd_query_copy(const union bpf_attr *attr,
4739 union bpf_attr __user *uattr,
4740 u32 prog_id, u32 fd_type,
4741 const char *buf, u64 probe_offset,
4744 char __user *ubuf = u64_to_user_ptr(attr->task_fd_query.buf);
4745 u32 len = buf ? strlen(buf) : 0, input_len;
4748 if (put_user(len, &uattr->task_fd_query.buf_len))
4750 input_len = attr->task_fd_query.buf_len;
4751 if (input_len && ubuf) {
4753 /* nothing to copy, just make ubuf NULL terminated */
4756 if (put_user(zero, ubuf))
4758 } else if (input_len >= len + 1) {
4759 /* ubuf can hold the string with NULL terminator */
4760 if (copy_to_user(ubuf, buf, len + 1))
4763 /* ubuf cannot hold the string with NULL terminator,
4764 * do a partial copy with NULL terminator.
4769 if (copy_to_user(ubuf, buf, input_len - 1))
4771 if (put_user(zero, ubuf + input_len - 1))
4776 if (put_user(prog_id, &uattr->task_fd_query.prog_id) ||
4777 put_user(fd_type, &uattr->task_fd_query.fd_type) ||
4778 put_user(probe_offset, &uattr->task_fd_query.probe_offset) ||
4779 put_user(probe_addr, &uattr->task_fd_query.probe_addr))
4785 #define BPF_TASK_FD_QUERY_LAST_FIELD task_fd_query.probe_addr
4787 static int bpf_task_fd_query(const union bpf_attr *attr,
4788 union bpf_attr __user *uattr)
4790 pid_t pid = attr->task_fd_query.pid;
4791 u32 fd = attr->task_fd_query.fd;
4792 const struct perf_event *event;
4793 struct task_struct *task;
4797 if (CHECK_ATTR(BPF_TASK_FD_QUERY))
4800 if (!capable(CAP_SYS_ADMIN))
4803 if (attr->task_fd_query.flags != 0)
4807 task = get_pid_task(find_vpid(pid), PIDTYPE_PID);
4813 file = fget_task(task, fd);
4814 put_task_struct(task);
4818 if (file->f_op == &bpf_link_fops) {
4819 struct bpf_link *link = file->private_data;
4821 if (link->ops == &bpf_raw_tp_link_lops) {
4822 struct bpf_raw_tp_link *raw_tp =
4823 container_of(link, struct bpf_raw_tp_link, link);
4824 struct bpf_raw_event_map *btp = raw_tp->btp;
4826 err = bpf_task_fd_query_copy(attr, uattr,
4827 raw_tp->link.prog->aux->id,
4828 BPF_FD_TYPE_RAW_TRACEPOINT,
4829 btp->tp->name, 0, 0);
4835 event = perf_get_event(file);
4836 if (!IS_ERR(event)) {
4837 u64 probe_offset, probe_addr;
4838 u32 prog_id, fd_type;
4841 err = bpf_get_perf_event_info(event, &prog_id, &fd_type,
4842 &buf, &probe_offset,
4845 err = bpf_task_fd_query_copy(attr, uattr, prog_id,
4859 #define BPF_MAP_BATCH_LAST_FIELD batch.flags
4861 #define BPF_DO_BATCH(fn, ...) \
4867 err = fn(__VA_ARGS__); \
4870 static int bpf_map_do_batch(const union bpf_attr *attr,
4871 union bpf_attr __user *uattr,
4874 bool has_read = cmd == BPF_MAP_LOOKUP_BATCH ||
4875 cmd == BPF_MAP_LOOKUP_AND_DELETE_BATCH;
4876 bool has_write = cmd != BPF_MAP_LOOKUP_BATCH;
4877 struct bpf_map *map;
4881 if (CHECK_ATTR(BPF_MAP_BATCH))
4884 ufd = attr->batch.map_fd;
4886 map = __bpf_map_get(f);
4888 return PTR_ERR(map);
4890 bpf_map_write_active_inc(map);
4891 if (has_read && !(map_get_sys_perms(map, f) & FMODE_CAN_READ)) {
4895 if (has_write && !(map_get_sys_perms(map, f) & FMODE_CAN_WRITE)) {
4900 if (cmd == BPF_MAP_LOOKUP_BATCH)
4901 BPF_DO_BATCH(map->ops->map_lookup_batch, map, attr, uattr);
4902 else if (cmd == BPF_MAP_LOOKUP_AND_DELETE_BATCH)
4903 BPF_DO_BATCH(map->ops->map_lookup_and_delete_batch, map, attr, uattr);
4904 else if (cmd == BPF_MAP_UPDATE_BATCH)
4905 BPF_DO_BATCH(map->ops->map_update_batch, map, f.file, attr, uattr);
4907 BPF_DO_BATCH(map->ops->map_delete_batch, map, attr, uattr);
4910 bpf_map_write_active_dec(map);
4915 #define BPF_LINK_CREATE_LAST_FIELD link_create.uprobe_multi.pid
4916 static int link_create(union bpf_attr *attr, bpfptr_t uattr)
4918 struct bpf_prog *prog;
4921 if (CHECK_ATTR(BPF_LINK_CREATE))
4924 if (attr->link_create.attach_type == BPF_STRUCT_OPS)
4925 return bpf_struct_ops_link_create(attr);
4927 prog = bpf_prog_get(attr->link_create.prog_fd);
4929 return PTR_ERR(prog);
4931 ret = bpf_prog_attach_check_attach_type(prog,
4932 attr->link_create.attach_type);
4936 switch (prog->type) {
4937 case BPF_PROG_TYPE_CGROUP_SKB:
4938 case BPF_PROG_TYPE_CGROUP_SOCK:
4939 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
4940 case BPF_PROG_TYPE_SOCK_OPS:
4941 case BPF_PROG_TYPE_CGROUP_DEVICE:
4942 case BPF_PROG_TYPE_CGROUP_SYSCTL:
4943 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
4944 ret = cgroup_bpf_link_attach(attr, prog);
4946 case BPF_PROG_TYPE_EXT:
4947 ret = bpf_tracing_prog_attach(prog,
4948 attr->link_create.target_fd,
4949 attr->link_create.target_btf_id,
4950 attr->link_create.tracing.cookie);
4952 case BPF_PROG_TYPE_LSM:
4953 case BPF_PROG_TYPE_TRACING:
4954 if (attr->link_create.attach_type != prog->expected_attach_type) {
4958 if (prog->expected_attach_type == BPF_TRACE_RAW_TP)
4959 ret = bpf_raw_tp_link_attach(prog, NULL);
4960 else if (prog->expected_attach_type == BPF_TRACE_ITER)
4961 ret = bpf_iter_link_attach(attr, uattr, prog);
4962 else if (prog->expected_attach_type == BPF_LSM_CGROUP)
4963 ret = cgroup_bpf_link_attach(attr, prog);
4965 ret = bpf_tracing_prog_attach(prog,
4966 attr->link_create.target_fd,
4967 attr->link_create.target_btf_id,
4968 attr->link_create.tracing.cookie);
4970 case BPF_PROG_TYPE_FLOW_DISSECTOR:
4971 case BPF_PROG_TYPE_SK_LOOKUP:
4972 ret = netns_bpf_link_create(attr, prog);
4975 case BPF_PROG_TYPE_XDP:
4976 ret = bpf_xdp_link_attach(attr, prog);
4978 case BPF_PROG_TYPE_SCHED_CLS:
4979 ret = tcx_link_attach(attr, prog);
4981 case BPF_PROG_TYPE_NETFILTER:
4982 ret = bpf_nf_link_attach(attr, prog);
4985 case BPF_PROG_TYPE_PERF_EVENT:
4986 case BPF_PROG_TYPE_TRACEPOINT:
4987 ret = bpf_perf_link_attach(attr, prog);
4989 case BPF_PROG_TYPE_KPROBE:
4990 if (attr->link_create.attach_type == BPF_PERF_EVENT)
4991 ret = bpf_perf_link_attach(attr, prog);
4992 else if (attr->link_create.attach_type == BPF_TRACE_KPROBE_MULTI)
4993 ret = bpf_kprobe_multi_link_attach(attr, prog);
4994 else if (attr->link_create.attach_type == BPF_TRACE_UPROBE_MULTI)
4995 ret = bpf_uprobe_multi_link_attach(attr, prog);
5007 static int link_update_map(struct bpf_link *link, union bpf_attr *attr)
5009 struct bpf_map *new_map, *old_map = NULL;
5012 new_map = bpf_map_get(attr->link_update.new_map_fd);
5013 if (IS_ERR(new_map))
5014 return PTR_ERR(new_map);
5016 if (attr->link_update.flags & BPF_F_REPLACE) {
5017 old_map = bpf_map_get(attr->link_update.old_map_fd);
5018 if (IS_ERR(old_map)) {
5019 ret = PTR_ERR(old_map);
5022 } else if (attr->link_update.old_map_fd) {
5027 ret = link->ops->update_map(link, new_map, old_map);
5030 bpf_map_put(old_map);
5032 bpf_map_put(new_map);
5036 #define BPF_LINK_UPDATE_LAST_FIELD link_update.old_prog_fd
5038 static int link_update(union bpf_attr *attr)
5040 struct bpf_prog *old_prog = NULL, *new_prog;
5041 struct bpf_link *link;
5045 if (CHECK_ATTR(BPF_LINK_UPDATE))
5048 flags = attr->link_update.flags;
5049 if (flags & ~BPF_F_REPLACE)
5052 link = bpf_link_get_from_fd(attr->link_update.link_fd);
5054 return PTR_ERR(link);
5056 if (link->ops->update_map) {
5057 ret = link_update_map(link, attr);
5061 new_prog = bpf_prog_get(attr->link_update.new_prog_fd);
5062 if (IS_ERR(new_prog)) {
5063 ret = PTR_ERR(new_prog);
5067 if (flags & BPF_F_REPLACE) {
5068 old_prog = bpf_prog_get(attr->link_update.old_prog_fd);
5069 if (IS_ERR(old_prog)) {
5070 ret = PTR_ERR(old_prog);
5074 } else if (attr->link_update.old_prog_fd) {
5079 if (link->ops->update_prog)
5080 ret = link->ops->update_prog(link, new_prog, old_prog);
5086 bpf_prog_put(old_prog);
5088 bpf_prog_put(new_prog);
5090 bpf_link_put_direct(link);
5094 #define BPF_LINK_DETACH_LAST_FIELD link_detach.link_fd
5096 static int link_detach(union bpf_attr *attr)
5098 struct bpf_link *link;
5101 if (CHECK_ATTR(BPF_LINK_DETACH))
5104 link = bpf_link_get_from_fd(attr->link_detach.link_fd);
5106 return PTR_ERR(link);
5108 if (link->ops->detach)
5109 ret = link->ops->detach(link);
5113 bpf_link_put_direct(link);
5117 static struct bpf_link *bpf_link_inc_not_zero(struct bpf_link *link)
5119 return atomic64_fetch_add_unless(&link->refcnt, 1, 0) ? link : ERR_PTR(-ENOENT);
5122 struct bpf_link *bpf_link_by_id(u32 id)
5124 struct bpf_link *link;
5127 return ERR_PTR(-ENOENT);
5129 spin_lock_bh(&link_idr_lock);
5130 /* before link is "settled", ID is 0, pretend it doesn't exist yet */
5131 link = idr_find(&link_idr, id);
5134 link = bpf_link_inc_not_zero(link);
5136 link = ERR_PTR(-EAGAIN);
5138 link = ERR_PTR(-ENOENT);
5140 spin_unlock_bh(&link_idr_lock);
5144 struct bpf_link *bpf_link_get_curr_or_next(u32 *id)
5146 struct bpf_link *link;
5148 spin_lock_bh(&link_idr_lock);
5150 link = idr_get_next(&link_idr, id);
5152 link = bpf_link_inc_not_zero(link);
5158 spin_unlock_bh(&link_idr_lock);
5163 #define BPF_LINK_GET_FD_BY_ID_LAST_FIELD link_id
5165 static int bpf_link_get_fd_by_id(const union bpf_attr *attr)
5167 struct bpf_link *link;
5168 u32 id = attr->link_id;
5171 if (CHECK_ATTR(BPF_LINK_GET_FD_BY_ID))
5174 if (!capable(CAP_SYS_ADMIN))
5177 link = bpf_link_by_id(id);
5179 return PTR_ERR(link);
5181 fd = bpf_link_new_fd(link);
5183 bpf_link_put_direct(link);
5188 DEFINE_MUTEX(bpf_stats_enabled_mutex);
5190 static int bpf_stats_release(struct inode *inode, struct file *file)
5192 mutex_lock(&bpf_stats_enabled_mutex);
5193 static_key_slow_dec(&bpf_stats_enabled_key.key);
5194 mutex_unlock(&bpf_stats_enabled_mutex);
5198 static const struct file_operations bpf_stats_fops = {
5199 .release = bpf_stats_release,
5202 static int bpf_enable_runtime_stats(void)
5206 mutex_lock(&bpf_stats_enabled_mutex);
5208 /* Set a very high limit to avoid overflow */
5209 if (static_key_count(&bpf_stats_enabled_key.key) > INT_MAX / 2) {
5210 mutex_unlock(&bpf_stats_enabled_mutex);
5214 fd = anon_inode_getfd("bpf-stats", &bpf_stats_fops, NULL, O_CLOEXEC);
5216 static_key_slow_inc(&bpf_stats_enabled_key.key);
5218 mutex_unlock(&bpf_stats_enabled_mutex);
5222 #define BPF_ENABLE_STATS_LAST_FIELD enable_stats.type
5224 static int bpf_enable_stats(union bpf_attr *attr)
5227 if (CHECK_ATTR(BPF_ENABLE_STATS))
5230 if (!capable(CAP_SYS_ADMIN))
5233 switch (attr->enable_stats.type) {
5234 case BPF_STATS_RUN_TIME:
5235 return bpf_enable_runtime_stats();
5242 #define BPF_ITER_CREATE_LAST_FIELD iter_create.flags
5244 static int bpf_iter_create(union bpf_attr *attr)
5246 struct bpf_link *link;
5249 if (CHECK_ATTR(BPF_ITER_CREATE))
5252 if (attr->iter_create.flags)
5255 link = bpf_link_get_from_fd(attr->iter_create.link_fd);
5257 return PTR_ERR(link);
5259 err = bpf_iter_new_fd(link);
5260 bpf_link_put_direct(link);
5265 #define BPF_PROG_BIND_MAP_LAST_FIELD prog_bind_map.flags
5267 static int bpf_prog_bind_map(union bpf_attr *attr)
5269 struct bpf_prog *prog;
5270 struct bpf_map *map;
5271 struct bpf_map **used_maps_old, **used_maps_new;
5274 if (CHECK_ATTR(BPF_PROG_BIND_MAP))
5277 if (attr->prog_bind_map.flags)
5280 prog = bpf_prog_get(attr->prog_bind_map.prog_fd);
5282 return PTR_ERR(prog);
5284 map = bpf_map_get(attr->prog_bind_map.map_fd);
5290 mutex_lock(&prog->aux->used_maps_mutex);
5292 used_maps_old = prog->aux->used_maps;
5294 for (i = 0; i < prog->aux->used_map_cnt; i++)
5295 if (used_maps_old[i] == map) {
5300 used_maps_new = kmalloc_array(prog->aux->used_map_cnt + 1,
5301 sizeof(used_maps_new[0]),
5303 if (!used_maps_new) {
5308 memcpy(used_maps_new, used_maps_old,
5309 sizeof(used_maps_old[0]) * prog->aux->used_map_cnt);
5310 used_maps_new[prog->aux->used_map_cnt] = map;
5312 prog->aux->used_map_cnt++;
5313 prog->aux->used_maps = used_maps_new;
5315 kfree(used_maps_old);
5318 mutex_unlock(&prog->aux->used_maps_mutex);
5327 static int __sys_bpf(int cmd, bpfptr_t uattr, unsigned int size)
5329 union bpf_attr attr;
5332 err = bpf_check_uarg_tail_zero(uattr, sizeof(attr), size);
5335 size = min_t(u32, size, sizeof(attr));
5337 /* copy attributes from user space, may be less than sizeof(bpf_attr) */
5338 memset(&attr, 0, sizeof(attr));
5339 if (copy_from_bpfptr(&attr, uattr, size) != 0)
5342 err = security_bpf(cmd, &attr, size);
5347 case BPF_MAP_CREATE:
5348 err = map_create(&attr);
5350 case BPF_MAP_LOOKUP_ELEM:
5351 err = map_lookup_elem(&attr);
5353 case BPF_MAP_UPDATE_ELEM:
5354 err = map_update_elem(&attr, uattr);
5356 case BPF_MAP_DELETE_ELEM:
5357 err = map_delete_elem(&attr, uattr);
5359 case BPF_MAP_GET_NEXT_KEY:
5360 err = map_get_next_key(&attr);
5362 case BPF_MAP_FREEZE:
5363 err = map_freeze(&attr);
5366 err = bpf_prog_load(&attr, uattr, size);
5369 err = bpf_obj_pin(&attr);
5372 err = bpf_obj_get(&attr);
5374 case BPF_PROG_ATTACH:
5375 err = bpf_prog_attach(&attr);
5377 case BPF_PROG_DETACH:
5378 err = bpf_prog_detach(&attr);
5380 case BPF_PROG_QUERY:
5381 err = bpf_prog_query(&attr, uattr.user);
5383 case BPF_PROG_TEST_RUN:
5384 err = bpf_prog_test_run(&attr, uattr.user);
5386 case BPF_PROG_GET_NEXT_ID:
5387 err = bpf_obj_get_next_id(&attr, uattr.user,
5388 &prog_idr, &prog_idr_lock);
5390 case BPF_MAP_GET_NEXT_ID:
5391 err = bpf_obj_get_next_id(&attr, uattr.user,
5392 &map_idr, &map_idr_lock);
5394 case BPF_BTF_GET_NEXT_ID:
5395 err = bpf_obj_get_next_id(&attr, uattr.user,
5396 &btf_idr, &btf_idr_lock);
5398 case BPF_PROG_GET_FD_BY_ID:
5399 err = bpf_prog_get_fd_by_id(&attr);
5401 case BPF_MAP_GET_FD_BY_ID:
5402 err = bpf_map_get_fd_by_id(&attr);
5404 case BPF_OBJ_GET_INFO_BY_FD:
5405 err = bpf_obj_get_info_by_fd(&attr, uattr.user);
5407 case BPF_RAW_TRACEPOINT_OPEN:
5408 err = bpf_raw_tracepoint_open(&attr);
5411 err = bpf_btf_load(&attr, uattr, size);
5413 case BPF_BTF_GET_FD_BY_ID:
5414 err = bpf_btf_get_fd_by_id(&attr);
5416 case BPF_TASK_FD_QUERY:
5417 err = bpf_task_fd_query(&attr, uattr.user);
5419 case BPF_MAP_LOOKUP_AND_DELETE_ELEM:
5420 err = map_lookup_and_delete_elem(&attr);
5422 case BPF_MAP_LOOKUP_BATCH:
5423 err = bpf_map_do_batch(&attr, uattr.user, BPF_MAP_LOOKUP_BATCH);
5425 case BPF_MAP_LOOKUP_AND_DELETE_BATCH:
5426 err = bpf_map_do_batch(&attr, uattr.user,
5427 BPF_MAP_LOOKUP_AND_DELETE_BATCH);
5429 case BPF_MAP_UPDATE_BATCH:
5430 err = bpf_map_do_batch(&attr, uattr.user, BPF_MAP_UPDATE_BATCH);
5432 case BPF_MAP_DELETE_BATCH:
5433 err = bpf_map_do_batch(&attr, uattr.user, BPF_MAP_DELETE_BATCH);
5435 case BPF_LINK_CREATE:
5436 err = link_create(&attr, uattr);
5438 case BPF_LINK_UPDATE:
5439 err = link_update(&attr);
5441 case BPF_LINK_GET_FD_BY_ID:
5442 err = bpf_link_get_fd_by_id(&attr);
5444 case BPF_LINK_GET_NEXT_ID:
5445 err = bpf_obj_get_next_id(&attr, uattr.user,
5446 &link_idr, &link_idr_lock);
5448 case BPF_ENABLE_STATS:
5449 err = bpf_enable_stats(&attr);
5451 case BPF_ITER_CREATE:
5452 err = bpf_iter_create(&attr);
5454 case BPF_LINK_DETACH:
5455 err = link_detach(&attr);
5457 case BPF_PROG_BIND_MAP:
5458 err = bpf_prog_bind_map(&attr);
5468 SYSCALL_DEFINE3(bpf, int, cmd, union bpf_attr __user *, uattr, unsigned int, size)
5470 return __sys_bpf(cmd, USER_BPFPTR(uattr), size);
5473 static bool syscall_prog_is_valid_access(int off, int size,
5474 enum bpf_access_type type,
5475 const struct bpf_prog *prog,
5476 struct bpf_insn_access_aux *info)
5478 if (off < 0 || off >= U16_MAX)
5480 if (off % size != 0)
5485 BPF_CALL_3(bpf_sys_bpf, int, cmd, union bpf_attr *, attr, u32, attr_size)
5488 case BPF_MAP_CREATE:
5489 case BPF_MAP_DELETE_ELEM:
5490 case BPF_MAP_UPDATE_ELEM:
5491 case BPF_MAP_FREEZE:
5492 case BPF_MAP_GET_FD_BY_ID:
5495 case BPF_LINK_CREATE:
5496 case BPF_RAW_TRACEPOINT_OPEN:
5501 return __sys_bpf(cmd, KERNEL_BPFPTR(attr), attr_size);
5505 /* To shut up -Wmissing-prototypes.
5506 * This function is used by the kernel light skeleton
5507 * to load bpf programs when modules are loaded or during kernel boot.
5508 * See tools/lib/bpf/skel_internal.h
5510 int kern_sys_bpf(int cmd, union bpf_attr *attr, unsigned int size);
5512 int kern_sys_bpf(int cmd, union bpf_attr *attr, unsigned int size)
5514 struct bpf_prog * __maybe_unused prog;
5515 struct bpf_tramp_run_ctx __maybe_unused run_ctx;
5518 #ifdef CONFIG_BPF_JIT /* __bpf_prog_enter_sleepable used by trampoline and JIT */
5519 case BPF_PROG_TEST_RUN:
5520 if (attr->test.data_in || attr->test.data_out ||
5521 attr->test.ctx_out || attr->test.duration ||
5522 attr->test.repeat || attr->test.flags)
5525 prog = bpf_prog_get_type(attr->test.prog_fd, BPF_PROG_TYPE_SYSCALL);
5527 return PTR_ERR(prog);
5529 if (attr->test.ctx_size_in < prog->aux->max_ctx_offset ||
5530 attr->test.ctx_size_in > U16_MAX) {
5535 run_ctx.bpf_cookie = 0;
5536 if (!__bpf_prog_enter_sleepable_recur(prog, &run_ctx)) {
5537 /* recursion detected */
5538 __bpf_prog_exit_sleepable_recur(prog, 0, &run_ctx);
5542 attr->test.retval = bpf_prog_run(prog, (void *) (long) attr->test.ctx_in);
5543 __bpf_prog_exit_sleepable_recur(prog, 0 /* bpf_prog_run does runtime stats */,
5549 return ____bpf_sys_bpf(cmd, attr, size);
5552 EXPORT_SYMBOL(kern_sys_bpf);
5554 static const struct bpf_func_proto bpf_sys_bpf_proto = {
5555 .func = bpf_sys_bpf,
5557 .ret_type = RET_INTEGER,
5558 .arg1_type = ARG_ANYTHING,
5559 .arg2_type = ARG_PTR_TO_MEM | MEM_RDONLY,
5560 .arg3_type = ARG_CONST_SIZE,
5563 const struct bpf_func_proto * __weak
5564 tracing_prog_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
5566 return bpf_base_func_proto(func_id);
5569 BPF_CALL_1(bpf_sys_close, u32, fd)
5571 /* When bpf program calls this helper there should not be
5572 * an fdget() without matching completed fdput().
5573 * This helper is allowed in the following callchain only:
5574 * sys_bpf->prog_test_run->bpf_prog->bpf_sys_close
5576 return close_fd(fd);
5579 static const struct bpf_func_proto bpf_sys_close_proto = {
5580 .func = bpf_sys_close,
5582 .ret_type = RET_INTEGER,
5583 .arg1_type = ARG_ANYTHING,
5586 BPF_CALL_4(bpf_kallsyms_lookup_name, const char *, name, int, name_sz, int, flags, u64 *, res)
5591 if (name_sz <= 1 || name[name_sz - 1])
5594 if (!bpf_dump_raw_ok(current_cred()))
5597 *res = kallsyms_lookup_name(name);
5598 return *res ? 0 : -ENOENT;
5601 static const struct bpf_func_proto bpf_kallsyms_lookup_name_proto = {
5602 .func = bpf_kallsyms_lookup_name,
5604 .ret_type = RET_INTEGER,
5605 .arg1_type = ARG_PTR_TO_MEM,
5606 .arg2_type = ARG_CONST_SIZE_OR_ZERO,
5607 .arg3_type = ARG_ANYTHING,
5608 .arg4_type = ARG_PTR_TO_LONG,
5611 static const struct bpf_func_proto *
5612 syscall_prog_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
5615 case BPF_FUNC_sys_bpf:
5616 return !perfmon_capable() ? NULL : &bpf_sys_bpf_proto;
5617 case BPF_FUNC_btf_find_by_name_kind:
5618 return &bpf_btf_find_by_name_kind_proto;
5619 case BPF_FUNC_sys_close:
5620 return &bpf_sys_close_proto;
5621 case BPF_FUNC_kallsyms_lookup_name:
5622 return &bpf_kallsyms_lookup_name_proto;
5624 return tracing_prog_func_proto(func_id, prog);
5628 const struct bpf_verifier_ops bpf_syscall_verifier_ops = {
5629 .get_func_proto = syscall_prog_func_proto,
5630 .is_valid_access = syscall_prog_is_valid_access,
5633 const struct bpf_prog_ops bpf_syscall_prog_ops = {
5634 .test_run = bpf_prog_test_run_syscall,
5637 #ifdef CONFIG_SYSCTL
5638 static int bpf_stats_handler(struct ctl_table *table, int write,
5639 void *buffer, size_t *lenp, loff_t *ppos)
5641 struct static_key *key = (struct static_key *)table->data;
5642 static int saved_val;
5644 struct ctl_table tmp = {
5646 .maxlen = sizeof(val),
5647 .mode = table->mode,
5648 .extra1 = SYSCTL_ZERO,
5649 .extra2 = SYSCTL_ONE,
5652 if (write && !capable(CAP_SYS_ADMIN))
5655 mutex_lock(&bpf_stats_enabled_mutex);
5657 ret = proc_dointvec_minmax(&tmp, write, buffer, lenp, ppos);
5658 if (write && !ret && val != saved_val) {
5660 static_key_slow_inc(key);
5662 static_key_slow_dec(key);
5665 mutex_unlock(&bpf_stats_enabled_mutex);
5669 void __weak unpriv_ebpf_notify(int new_state)
5673 static int bpf_unpriv_handler(struct ctl_table *table, int write,
5674 void *buffer, size_t *lenp, loff_t *ppos)
5676 int ret, unpriv_enable = *(int *)table->data;
5677 bool locked_state = unpriv_enable == 1;
5678 struct ctl_table tmp = *table;
5680 if (write && !capable(CAP_SYS_ADMIN))
5683 tmp.data = &unpriv_enable;
5684 ret = proc_dointvec_minmax(&tmp, write, buffer, lenp, ppos);
5685 if (write && !ret) {
5686 if (locked_state && unpriv_enable != 1)
5688 *(int *)table->data = unpriv_enable;
5692 unpriv_ebpf_notify(unpriv_enable);
5697 static struct ctl_table bpf_syscall_table[] = {
5699 .procname = "unprivileged_bpf_disabled",
5700 .data = &sysctl_unprivileged_bpf_disabled,
5701 .maxlen = sizeof(sysctl_unprivileged_bpf_disabled),
5703 .proc_handler = bpf_unpriv_handler,
5704 .extra1 = SYSCTL_ZERO,
5705 .extra2 = SYSCTL_TWO,
5708 .procname = "bpf_stats_enabled",
5709 .data = &bpf_stats_enabled_key.key,
5711 .proc_handler = bpf_stats_handler,
5716 static int __init bpf_syscall_sysctl_init(void)
5718 register_sysctl_init("kernel", bpf_syscall_table);
5721 late_initcall(bpf_syscall_sysctl_init);
5722 #endif /* CONFIG_SYSCTL */