1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
5 #include <linux/bpf-cgroup.h>
6 #include <linux/bpf_trace.h>
7 #include <linux/bpf_lirc.h>
8 #include <linux/bpf_verifier.h>
9 #include <linux/bsearch.h>
10 #include <linux/btf.h>
11 #include <linux/syscalls.h>
12 #include <linux/slab.h>
13 #include <linux/sched/signal.h>
14 #include <linux/vmalloc.h>
15 #include <linux/mmzone.h>
16 #include <linux/anon_inodes.h>
17 #include <linux/fdtable.h>
18 #include <linux/file.h>
20 #include <linux/license.h>
21 #include <linux/filter.h>
22 #include <linux/kernel.h>
23 #include <linux/idr.h>
24 #include <linux/cred.h>
25 #include <linux/timekeeping.h>
26 #include <linux/ctype.h>
27 #include <linux/nospec.h>
28 #include <linux/audit.h>
29 #include <uapi/linux/btf.h>
30 #include <linux/pgtable.h>
31 #include <linux/bpf_lsm.h>
32 #include <linux/poll.h>
33 #include <linux/sort.h>
34 #include <linux/bpf-netns.h>
35 #include <linux/rcupdate_trace.h>
36 #include <linux/memcontrol.h>
37 #include <linux/trace_events.h>
39 #include <net/netfilter/nf_bpf_link.h>
40 #include <net/netkit.h>
43 #define IS_FD_ARRAY(map) ((map)->map_type == BPF_MAP_TYPE_PERF_EVENT_ARRAY || \
44 (map)->map_type == BPF_MAP_TYPE_CGROUP_ARRAY || \
45 (map)->map_type == BPF_MAP_TYPE_ARRAY_OF_MAPS)
46 #define IS_FD_PROG_ARRAY(map) ((map)->map_type == BPF_MAP_TYPE_PROG_ARRAY)
47 #define IS_FD_HASH(map) ((map)->map_type == BPF_MAP_TYPE_HASH_OF_MAPS)
48 #define IS_FD_MAP(map) (IS_FD_ARRAY(map) || IS_FD_PROG_ARRAY(map) || \
51 #define BPF_OBJ_FLAG_MASK (BPF_F_RDONLY | BPF_F_WRONLY)
53 DEFINE_PER_CPU(int, bpf_prog_active);
54 static DEFINE_IDR(prog_idr);
55 static DEFINE_SPINLOCK(prog_idr_lock);
56 static DEFINE_IDR(map_idr);
57 static DEFINE_SPINLOCK(map_idr_lock);
58 static DEFINE_IDR(link_idr);
59 static DEFINE_SPINLOCK(link_idr_lock);
61 int sysctl_unprivileged_bpf_disabled __read_mostly =
62 IS_BUILTIN(CONFIG_BPF_UNPRIV_DEFAULT_OFF) ? 2 : 0;
64 static const struct bpf_map_ops * const bpf_map_types[] = {
65 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type)
66 #define BPF_MAP_TYPE(_id, _ops) \
68 #define BPF_LINK_TYPE(_id, _name)
69 #include <linux/bpf_types.h>
76 * If we're handed a bigger struct than we know of, ensure all the unknown bits
77 * are 0 - i.e. new user-space does not rely on any kernel feature extensions
78 * we don't know about yet.
80 * There is a ToCToU between this function call and the following
81 * copy_from_user() call. However, this is not a concern since this function is
82 * meant to be a future-proofing of bits.
84 int bpf_check_uarg_tail_zero(bpfptr_t uaddr,
90 if (unlikely(actual_size > PAGE_SIZE)) /* silly large */
93 if (actual_size <= expected_size)
97 res = memchr_inv(uaddr.kernel + expected_size, 0,
98 actual_size - expected_size) == NULL;
100 res = check_zeroed_user(uaddr.user + expected_size,
101 actual_size - expected_size);
104 return res ? 0 : -E2BIG;
107 const struct bpf_map_ops bpf_map_offload_ops = {
108 .map_meta_equal = bpf_map_meta_equal,
109 .map_alloc = bpf_map_offload_map_alloc,
110 .map_free = bpf_map_offload_map_free,
111 .map_check_btf = map_check_no_btf,
112 .map_mem_usage = bpf_map_offload_map_mem_usage,
115 static void bpf_map_write_active_inc(struct bpf_map *map)
117 atomic64_inc(&map->writecnt);
120 static void bpf_map_write_active_dec(struct bpf_map *map)
122 atomic64_dec(&map->writecnt);
125 bool bpf_map_write_active(const struct bpf_map *map)
127 return atomic64_read(&map->writecnt) != 0;
130 static u32 bpf_map_value_size(const struct bpf_map *map)
132 if (map->map_type == BPF_MAP_TYPE_PERCPU_HASH ||
133 map->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH ||
134 map->map_type == BPF_MAP_TYPE_PERCPU_ARRAY ||
135 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
136 return round_up(map->value_size, 8) * num_possible_cpus();
137 else if (IS_FD_MAP(map))
140 return map->value_size;
143 static void maybe_wait_bpf_programs(struct bpf_map *map)
145 /* Wait for any running non-sleepable BPF programs to complete so that
146 * userspace, when we return to it, knows that all non-sleepable
147 * programs that could be running use the new map value. For sleepable
148 * BPF programs, synchronize_rcu_tasks_trace() should be used to wait
149 * for the completions of these programs, but considering the waiting
150 * time can be very long and userspace may think it will hang forever,
151 * so don't handle sleepable BPF programs now.
153 if (map->map_type == BPF_MAP_TYPE_HASH_OF_MAPS ||
154 map->map_type == BPF_MAP_TYPE_ARRAY_OF_MAPS)
158 static int bpf_map_update_value(struct bpf_map *map, struct file *map_file,
159 void *key, void *value, __u64 flags)
163 /* Need to create a kthread, thus must support schedule */
164 if (bpf_map_is_offloaded(map)) {
165 return bpf_map_offload_update_elem(map, key, value, flags);
166 } else if (map->map_type == BPF_MAP_TYPE_CPUMAP ||
167 map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
168 return map->ops->map_update_elem(map, key, value, flags);
169 } else if (map->map_type == BPF_MAP_TYPE_SOCKHASH ||
170 map->map_type == BPF_MAP_TYPE_SOCKMAP) {
171 return sock_map_update_elem_sys(map, key, value, flags);
172 } else if (IS_FD_PROG_ARRAY(map)) {
173 return bpf_fd_array_map_update_elem(map, map_file, key, value,
177 bpf_disable_instrumentation();
178 if (map->map_type == BPF_MAP_TYPE_PERCPU_HASH ||
179 map->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH) {
180 err = bpf_percpu_hash_update(map, key, value, flags);
181 } else if (map->map_type == BPF_MAP_TYPE_PERCPU_ARRAY) {
182 err = bpf_percpu_array_update(map, key, value, flags);
183 } else if (map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE) {
184 err = bpf_percpu_cgroup_storage_update(map, key, value,
186 } else if (IS_FD_ARRAY(map)) {
187 err = bpf_fd_array_map_update_elem(map, map_file, key, value,
189 } else if (map->map_type == BPF_MAP_TYPE_HASH_OF_MAPS) {
190 err = bpf_fd_htab_map_update_elem(map, map_file, key, value,
192 } else if (map->map_type == BPF_MAP_TYPE_REUSEPORT_SOCKARRAY) {
193 /* rcu_read_lock() is not needed */
194 err = bpf_fd_reuseport_array_update_elem(map, key, value,
196 } else if (map->map_type == BPF_MAP_TYPE_QUEUE ||
197 map->map_type == BPF_MAP_TYPE_STACK ||
198 map->map_type == BPF_MAP_TYPE_BLOOM_FILTER) {
199 err = map->ops->map_push_elem(map, value, flags);
202 err = map->ops->map_update_elem(map, key, value, flags);
205 bpf_enable_instrumentation();
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();
270 /* Please, do not use this function outside from the map creation path
271 * (e.g. in map update path) without taking care of setting the active
272 * memory cgroup (see at bpf_map_kmalloc_node() for example).
274 static void *__bpf_map_area_alloc(u64 size, int numa_node, bool mmapable)
276 /* We really just want to fail instead of triggering OOM killer
277 * under memory pressure, therefore we set __GFP_NORETRY to kmalloc,
278 * which is used for lower order allocation requests.
280 * It has been observed that higher order allocation requests done by
281 * vmalloc with __GFP_NORETRY being set might fail due to not trying
282 * to reclaim memory from the page cache, thus we set
283 * __GFP_RETRY_MAYFAIL to avoid such situations.
286 gfp_t gfp = bpf_memcg_flags(__GFP_NOWARN | __GFP_ZERO);
287 unsigned int flags = 0;
288 unsigned long align = 1;
291 if (size >= SIZE_MAX)
294 /* kmalloc()'ed memory can't be mmap()'ed */
296 BUG_ON(!PAGE_ALIGNED(size));
299 } else if (size <= (PAGE_SIZE << PAGE_ALLOC_COSTLY_ORDER)) {
300 area = kmalloc_node(size, gfp | GFP_USER | __GFP_NORETRY,
306 return __vmalloc_node_range(size, align, VMALLOC_START, VMALLOC_END,
307 gfp | GFP_KERNEL | __GFP_RETRY_MAYFAIL, PAGE_KERNEL,
308 flags, numa_node, __builtin_return_address(0));
311 void *bpf_map_area_alloc(u64 size, int numa_node)
313 return __bpf_map_area_alloc(size, numa_node, false);
316 void *bpf_map_area_mmapable_alloc(u64 size, int numa_node)
318 return __bpf_map_area_alloc(size, numa_node, true);
321 void bpf_map_area_free(void *area)
326 static u32 bpf_map_flags_retain_permanent(u32 flags)
328 /* Some map creation flags are not tied to the map object but
329 * rather to the map fd instead, so they have no meaning upon
330 * map object inspection since multiple file descriptors with
331 * different (access) properties can exist here. Thus, given
332 * this has zero meaning for the map itself, lets clear these
335 return flags & ~(BPF_F_RDONLY | BPF_F_WRONLY);
338 void bpf_map_init_from_attr(struct bpf_map *map, union bpf_attr *attr)
340 map->map_type = attr->map_type;
341 map->key_size = attr->key_size;
342 map->value_size = attr->value_size;
343 map->max_entries = attr->max_entries;
344 map->map_flags = bpf_map_flags_retain_permanent(attr->map_flags);
345 map->numa_node = bpf_map_attr_numa_node(attr);
346 map->map_extra = attr->map_extra;
349 static int bpf_map_alloc_id(struct bpf_map *map)
353 idr_preload(GFP_KERNEL);
354 spin_lock_bh(&map_idr_lock);
355 id = idr_alloc_cyclic(&map_idr, map, 1, INT_MAX, GFP_ATOMIC);
358 spin_unlock_bh(&map_idr_lock);
361 if (WARN_ON_ONCE(!id))
364 return id > 0 ? 0 : id;
367 void bpf_map_free_id(struct bpf_map *map)
371 /* Offloaded maps are removed from the IDR store when their device
372 * disappears - even if someone holds an fd to them they are unusable,
373 * the memory is gone, all ops will fail; they are simply waiting for
374 * refcnt to drop to be freed.
379 spin_lock_irqsave(&map_idr_lock, flags);
381 idr_remove(&map_idr, map->id);
384 spin_unlock_irqrestore(&map_idr_lock, flags);
387 #ifdef CONFIG_MEMCG_KMEM
388 static void bpf_map_save_memcg(struct bpf_map *map)
390 /* Currently if a map is created by a process belonging to the root
391 * memory cgroup, get_obj_cgroup_from_current() will return NULL.
392 * So we have to check map->objcg for being NULL each time it's
395 if (memcg_bpf_enabled())
396 map->objcg = get_obj_cgroup_from_current();
399 static void bpf_map_release_memcg(struct bpf_map *map)
402 obj_cgroup_put(map->objcg);
405 static struct mem_cgroup *bpf_map_get_memcg(const struct bpf_map *map)
408 return get_mem_cgroup_from_objcg(map->objcg);
410 return root_mem_cgroup;
413 void *bpf_map_kmalloc_node(const struct bpf_map *map, size_t size, gfp_t flags,
416 struct mem_cgroup *memcg, *old_memcg;
419 memcg = bpf_map_get_memcg(map);
420 old_memcg = set_active_memcg(memcg);
421 ptr = kmalloc_node(size, flags | __GFP_ACCOUNT, node);
422 set_active_memcg(old_memcg);
423 mem_cgroup_put(memcg);
428 void *bpf_map_kzalloc(const struct bpf_map *map, size_t size, gfp_t flags)
430 struct mem_cgroup *memcg, *old_memcg;
433 memcg = bpf_map_get_memcg(map);
434 old_memcg = set_active_memcg(memcg);
435 ptr = kzalloc(size, flags | __GFP_ACCOUNT);
436 set_active_memcg(old_memcg);
437 mem_cgroup_put(memcg);
442 void *bpf_map_kvcalloc(struct bpf_map *map, size_t n, size_t size,
445 struct mem_cgroup *memcg, *old_memcg;
448 memcg = bpf_map_get_memcg(map);
449 old_memcg = set_active_memcg(memcg);
450 ptr = kvcalloc(n, size, flags | __GFP_ACCOUNT);
451 set_active_memcg(old_memcg);
452 mem_cgroup_put(memcg);
457 void __percpu *bpf_map_alloc_percpu(const struct bpf_map *map, size_t size,
458 size_t align, gfp_t flags)
460 struct mem_cgroup *memcg, *old_memcg;
463 memcg = bpf_map_get_memcg(map);
464 old_memcg = set_active_memcg(memcg);
465 ptr = __alloc_percpu_gfp(size, align, flags | __GFP_ACCOUNT);
466 set_active_memcg(old_memcg);
467 mem_cgroup_put(memcg);
473 static void bpf_map_save_memcg(struct bpf_map *map)
477 static void bpf_map_release_memcg(struct bpf_map *map)
482 static int btf_field_cmp(const void *a, const void *b)
484 const struct btf_field *f1 = a, *f2 = b;
486 if (f1->offset < f2->offset)
488 else if (f1->offset > f2->offset)
493 struct btf_field *btf_record_find(const struct btf_record *rec, u32 offset,
496 struct btf_field *field;
498 if (IS_ERR_OR_NULL(rec) || !(rec->field_mask & field_mask))
500 field = bsearch(&offset, rec->fields, rec->cnt, sizeof(rec->fields[0]), btf_field_cmp);
501 if (!field || !(field->type & field_mask))
506 void btf_record_free(struct btf_record *rec)
510 if (IS_ERR_OR_NULL(rec))
512 for (i = 0; i < rec->cnt; i++) {
513 switch (rec->fields[i].type) {
516 case BPF_KPTR_PERCPU:
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 case BPF_KPTR_PERCPU:
564 btf_get(fields[i].kptr.btf);
565 if (fields[i].kptr.module && !try_module_get(fields[i].kptr.module)) {
577 /* Nothing to acquire */
588 btf_record_free(new_rec);
592 bool btf_record_equal(const struct btf_record *rec_a, const struct btf_record *rec_b)
594 bool a_has_fields = !IS_ERR_OR_NULL(rec_a), b_has_fields = !IS_ERR_OR_NULL(rec_b);
597 if (!a_has_fields && !b_has_fields)
599 if (a_has_fields != b_has_fields)
601 if (rec_a->cnt != rec_b->cnt)
603 size = offsetof(struct btf_record, fields[rec_a->cnt]);
604 /* btf_parse_fields uses kzalloc to allocate a btf_record, so unused
605 * members are zeroed out. So memcmp is safe to do without worrying
606 * about padding/unused fields.
608 * While spin_lock, timer, and kptr have no relation to map BTF,
609 * list_head metadata is specific to map BTF, the btf and value_rec
610 * members in particular. btf is the map BTF, while value_rec points to
611 * btf_record in that map BTF.
613 * So while by default, we don't rely on the map BTF (which the records
614 * were parsed from) matching for both records, which is not backwards
615 * compatible, in case list_head is part of it, we implicitly rely on
616 * that by way of depending on memcmp succeeding for it.
618 return !memcmp(rec_a, rec_b, size);
621 void bpf_obj_free_timer(const struct btf_record *rec, void *obj)
623 if (WARN_ON_ONCE(!btf_record_has_field(rec, BPF_TIMER)))
625 bpf_timer_cancel_and_free(obj + rec->timer_off);
628 void bpf_obj_free_fields(const struct btf_record *rec, void *obj)
630 const struct btf_field *fields;
633 if (IS_ERR_OR_NULL(rec))
635 fields = rec->fields;
636 for (i = 0; i < rec->cnt; i++) {
637 struct btf_struct_meta *pointee_struct_meta;
638 const struct btf_field *field = &fields[i];
639 void *field_ptr = obj + field->offset;
642 switch (fields[i].type) {
646 bpf_timer_cancel_and_free(field_ptr);
649 WRITE_ONCE(*(u64 *)field_ptr, 0);
652 case BPF_KPTR_PERCPU:
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 : NULL,
663 fields[i].type == BPF_KPTR_PERCPU);
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;
695 struct btf *btf = map->btf;
697 security_bpf_map_free(map);
698 bpf_map_release_memcg(map);
699 /* implementation dependent freeing */
700 map->ops->map_free(map);
701 /* Delay freeing of btf_record for maps, as map_free
702 * callback usually needs access to them. It is better to do it here
703 * than require each callback to do the free itself manually.
705 * Note that the btf_record stashed in map->inner_map_meta->record was
706 * already freed using the map_free callback for map in map case which
707 * eventually calls bpf_map_free_meta, since inner_map_meta is only a
708 * template bpf_map struct used during verification.
710 btf_record_free(rec);
711 /* Delay freeing of btf for maps, as map_free callback may need
712 * struct_meta info which will be freed with btf_put().
717 static void bpf_map_put_uref(struct bpf_map *map)
719 if (atomic64_dec_and_test(&map->usercnt)) {
720 if (map->ops->map_release_uref)
721 map->ops->map_release_uref(map);
725 static void bpf_map_free_in_work(struct bpf_map *map)
727 INIT_WORK(&map->work, bpf_map_free_deferred);
728 /* Avoid spawning kworkers, since they all might contend
729 * for the same mutex like slab_mutex.
731 queue_work(system_unbound_wq, &map->work);
734 static void bpf_map_free_rcu_gp(struct rcu_head *rcu)
736 bpf_map_free_in_work(container_of(rcu, struct bpf_map, rcu));
739 static void bpf_map_free_mult_rcu_gp(struct rcu_head *rcu)
741 if (rcu_trace_implies_rcu_gp())
742 bpf_map_free_rcu_gp(rcu);
744 call_rcu(rcu, bpf_map_free_rcu_gp);
747 /* decrement map refcnt and schedule it for freeing via workqueue
748 * (underlying map implementation ops->map_free() might sleep)
750 void bpf_map_put(struct bpf_map *map)
752 if (atomic64_dec_and_test(&map->refcnt)) {
753 /* bpf_map_free_id() must be called first */
754 bpf_map_free_id(map);
756 WARN_ON_ONCE(atomic64_read(&map->sleepable_refcnt));
757 if (READ_ONCE(map->free_after_mult_rcu_gp))
758 call_rcu_tasks_trace(&map->rcu, bpf_map_free_mult_rcu_gp);
759 else if (READ_ONCE(map->free_after_rcu_gp))
760 call_rcu(&map->rcu, bpf_map_free_rcu_gp);
762 bpf_map_free_in_work(map);
765 EXPORT_SYMBOL_GPL(bpf_map_put);
767 void bpf_map_put_with_uref(struct bpf_map *map)
769 bpf_map_put_uref(map);
773 static int bpf_map_release(struct inode *inode, struct file *filp)
775 struct bpf_map *map = filp->private_data;
777 if (map->ops->map_release)
778 map->ops->map_release(map, filp);
780 bpf_map_put_with_uref(map);
784 static fmode_t map_get_sys_perms(struct bpf_map *map, struct fd f)
786 fmode_t mode = f.file->f_mode;
788 /* Our file permissions may have been overridden by global
789 * map permissions facing syscall side.
791 if (READ_ONCE(map->frozen))
792 mode &= ~FMODE_CAN_WRITE;
796 #ifdef CONFIG_PROC_FS
797 /* Show the memory usage of a bpf map */
798 static u64 bpf_map_memory_usage(const struct bpf_map *map)
800 return map->ops->map_mem_usage(map);
803 static void bpf_map_show_fdinfo(struct seq_file *m, struct file *filp)
805 struct bpf_map *map = filp->private_data;
806 u32 type = 0, jited = 0;
808 if (map_type_contains_progs(map)) {
809 spin_lock(&map->owner.lock);
810 type = map->owner.type;
811 jited = map->owner.jited;
812 spin_unlock(&map->owner.lock);
821 "map_extra:\t%#llx\n"
830 (unsigned long long)map->map_extra,
831 bpf_map_memory_usage(map),
833 READ_ONCE(map->frozen));
835 seq_printf(m, "owner_prog_type:\t%u\n", type);
836 seq_printf(m, "owner_jited:\t%u\n", jited);
841 static ssize_t bpf_dummy_read(struct file *filp, char __user *buf, size_t siz,
844 /* We need this handler such that alloc_file() enables
845 * f_mode with FMODE_CAN_READ.
850 static ssize_t bpf_dummy_write(struct file *filp, const char __user *buf,
851 size_t siz, loff_t *ppos)
853 /* We need this handler such that alloc_file() enables
854 * f_mode with FMODE_CAN_WRITE.
859 /* called for any extra memory-mapped regions (except initial) */
860 static void bpf_map_mmap_open(struct vm_area_struct *vma)
862 struct bpf_map *map = vma->vm_file->private_data;
864 if (vma->vm_flags & VM_MAYWRITE)
865 bpf_map_write_active_inc(map);
868 /* called for all unmapped memory region (including initial) */
869 static void bpf_map_mmap_close(struct vm_area_struct *vma)
871 struct bpf_map *map = vma->vm_file->private_data;
873 if (vma->vm_flags & VM_MAYWRITE)
874 bpf_map_write_active_dec(map);
877 static const struct vm_operations_struct bpf_map_default_vmops = {
878 .open = bpf_map_mmap_open,
879 .close = bpf_map_mmap_close,
882 static int bpf_map_mmap(struct file *filp, struct vm_area_struct *vma)
884 struct bpf_map *map = filp->private_data;
887 if (!map->ops->map_mmap || !IS_ERR_OR_NULL(map->record))
890 if (!(vma->vm_flags & VM_SHARED))
893 mutex_lock(&map->freeze_mutex);
895 if (vma->vm_flags & VM_WRITE) {
900 /* map is meant to be read-only, so do not allow mapping as
901 * writable, because it's possible to leak a writable page
902 * reference and allows user-space to still modify it after
903 * freezing, while verifier will assume contents do not change
905 if (map->map_flags & BPF_F_RDONLY_PROG) {
911 /* set default open/close callbacks */
912 vma->vm_ops = &bpf_map_default_vmops;
913 vma->vm_private_data = map;
914 vm_flags_clear(vma, VM_MAYEXEC);
915 if (!(vma->vm_flags & VM_WRITE))
916 /* disallow re-mapping with PROT_WRITE */
917 vm_flags_clear(vma, VM_MAYWRITE);
919 err = map->ops->map_mmap(map, vma);
923 if (vma->vm_flags & VM_MAYWRITE)
924 bpf_map_write_active_inc(map);
926 mutex_unlock(&map->freeze_mutex);
930 static __poll_t bpf_map_poll(struct file *filp, struct poll_table_struct *pts)
932 struct bpf_map *map = filp->private_data;
934 if (map->ops->map_poll)
935 return map->ops->map_poll(map, filp, pts);
940 const struct file_operations bpf_map_fops = {
941 #ifdef CONFIG_PROC_FS
942 .show_fdinfo = bpf_map_show_fdinfo,
944 .release = bpf_map_release,
945 .read = bpf_dummy_read,
946 .write = bpf_dummy_write,
947 .mmap = bpf_map_mmap,
948 .poll = bpf_map_poll,
951 int bpf_map_new_fd(struct bpf_map *map, int flags)
955 ret = security_bpf_map(map, OPEN_FMODE(flags));
959 return anon_inode_getfd("bpf-map", &bpf_map_fops, map,
963 int bpf_get_file_flag(int flags)
965 if ((flags & BPF_F_RDONLY) && (flags & BPF_F_WRONLY))
967 if (flags & BPF_F_RDONLY)
969 if (flags & BPF_F_WRONLY)
974 /* helper macro to check that unused fields 'union bpf_attr' are zero */
975 #define CHECK_ATTR(CMD) \
976 memchr_inv((void *) &attr->CMD##_LAST_FIELD + \
977 sizeof(attr->CMD##_LAST_FIELD), 0, \
979 offsetof(union bpf_attr, CMD##_LAST_FIELD) - \
980 sizeof(attr->CMD##_LAST_FIELD)) != NULL
982 /* dst and src must have at least "size" number of bytes.
983 * Return strlen on success and < 0 on error.
985 int bpf_obj_name_cpy(char *dst, const char *src, unsigned int size)
987 const char *end = src + size;
988 const char *orig_src = src;
990 memset(dst, 0, size);
991 /* Copy all isalnum(), '_' and '.' chars. */
992 while (src < end && *src) {
993 if (!isalnum(*src) &&
994 *src != '_' && *src != '.')
999 /* No '\0' found in "size" number of bytes */
1003 return src - orig_src;
1006 int map_check_no_btf(const struct bpf_map *map,
1007 const struct btf *btf,
1008 const struct btf_type *key_type,
1009 const struct btf_type *value_type)
1014 static int map_check_btf(struct bpf_map *map, const struct btf *btf,
1015 u32 btf_key_id, u32 btf_value_id)
1017 const struct btf_type *key_type, *value_type;
1018 u32 key_size, value_size;
1021 /* Some maps allow key to be unspecified. */
1023 key_type = btf_type_id_size(btf, &btf_key_id, &key_size);
1024 if (!key_type || key_size != map->key_size)
1027 key_type = btf_type_by_id(btf, 0);
1028 if (!map->ops->map_check_btf)
1032 value_type = btf_type_id_size(btf, &btf_value_id, &value_size);
1033 if (!value_type || value_size != map->value_size)
1036 map->record = btf_parse_fields(btf, value_type,
1037 BPF_SPIN_LOCK | BPF_TIMER | BPF_KPTR | BPF_LIST_HEAD |
1038 BPF_RB_ROOT | BPF_REFCOUNT,
1040 if (!IS_ERR_OR_NULL(map->record)) {
1043 if (!bpf_capable()) {
1047 if (map->map_flags & (BPF_F_RDONLY_PROG | BPF_F_WRONLY_PROG)) {
1051 for (i = 0; i < sizeof(map->record->field_mask) * 8; i++) {
1052 switch (map->record->field_mask & (1 << i)) {
1056 if (map->map_type != BPF_MAP_TYPE_HASH &&
1057 map->map_type != BPF_MAP_TYPE_ARRAY &&
1058 map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
1059 map->map_type != BPF_MAP_TYPE_SK_STORAGE &&
1060 map->map_type != BPF_MAP_TYPE_INODE_STORAGE &&
1061 map->map_type != BPF_MAP_TYPE_TASK_STORAGE &&
1062 map->map_type != BPF_MAP_TYPE_CGRP_STORAGE) {
1068 if (map->map_type != BPF_MAP_TYPE_HASH &&
1069 map->map_type != BPF_MAP_TYPE_LRU_HASH &&
1070 map->map_type != BPF_MAP_TYPE_ARRAY) {
1075 case BPF_KPTR_UNREF:
1077 case BPF_KPTR_PERCPU:
1079 if (map->map_type != BPF_MAP_TYPE_HASH &&
1080 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
1081 map->map_type != BPF_MAP_TYPE_LRU_HASH &&
1082 map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH &&
1083 map->map_type != BPF_MAP_TYPE_ARRAY &&
1084 map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
1085 map->map_type != BPF_MAP_TYPE_SK_STORAGE &&
1086 map->map_type != BPF_MAP_TYPE_INODE_STORAGE &&
1087 map->map_type != BPF_MAP_TYPE_TASK_STORAGE &&
1088 map->map_type != BPF_MAP_TYPE_CGRP_STORAGE) {
1095 if (map->map_type != BPF_MAP_TYPE_HASH &&
1096 map->map_type != BPF_MAP_TYPE_LRU_HASH &&
1097 map->map_type != BPF_MAP_TYPE_ARRAY) {
1103 /* Fail if map_type checks are missing for a field type */
1110 ret = btf_check_and_fixup_fields(btf, map->record);
1114 if (map->ops->map_check_btf) {
1115 ret = map->ops->map_check_btf(map, btf, key_type, value_type);
1122 bpf_map_free_record(map);
1126 #define BPF_MAP_CREATE_LAST_FIELD map_extra
1127 /* called via syscall */
1128 static int map_create(union bpf_attr *attr)
1130 const struct bpf_map_ops *ops;
1131 int numa_node = bpf_map_attr_numa_node(attr);
1132 u32 map_type = attr->map_type;
1133 struct bpf_map *map;
1137 err = CHECK_ATTR(BPF_MAP_CREATE);
1141 if (attr->btf_vmlinux_value_type_id) {
1142 if (attr->map_type != BPF_MAP_TYPE_STRUCT_OPS ||
1143 attr->btf_key_type_id || attr->btf_value_type_id)
1145 } else if (attr->btf_key_type_id && !attr->btf_value_type_id) {
1149 if (attr->map_type != BPF_MAP_TYPE_BLOOM_FILTER &&
1150 attr->map_extra != 0)
1153 f_flags = bpf_get_file_flag(attr->map_flags);
1157 if (numa_node != NUMA_NO_NODE &&
1158 ((unsigned int)numa_node >= nr_node_ids ||
1159 !node_online(numa_node)))
1162 /* find map type and init map: hashtable vs rbtree vs bloom vs ... */
1163 map_type = attr->map_type;
1164 if (map_type >= ARRAY_SIZE(bpf_map_types))
1166 map_type = array_index_nospec(map_type, ARRAY_SIZE(bpf_map_types));
1167 ops = bpf_map_types[map_type];
1171 if (ops->map_alloc_check) {
1172 err = ops->map_alloc_check(attr);
1176 if (attr->map_ifindex)
1177 ops = &bpf_map_offload_ops;
1178 if (!ops->map_mem_usage)
1181 /* Intent here is for unprivileged_bpf_disabled to block BPF map
1182 * creation for unprivileged users; other actions depend
1183 * on fd availability and access to bpffs, so are dependent on
1184 * object creation success. Even with unprivileged BPF disabled,
1185 * capability checks are still carried out.
1187 if (sysctl_unprivileged_bpf_disabled && !bpf_capable())
1190 /* check privileged map type permissions */
1192 case BPF_MAP_TYPE_ARRAY:
1193 case BPF_MAP_TYPE_PERCPU_ARRAY:
1194 case BPF_MAP_TYPE_PROG_ARRAY:
1195 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
1196 case BPF_MAP_TYPE_CGROUP_ARRAY:
1197 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
1198 case BPF_MAP_TYPE_HASH:
1199 case BPF_MAP_TYPE_PERCPU_HASH:
1200 case BPF_MAP_TYPE_HASH_OF_MAPS:
1201 case BPF_MAP_TYPE_RINGBUF:
1202 case BPF_MAP_TYPE_USER_RINGBUF:
1203 case BPF_MAP_TYPE_CGROUP_STORAGE:
1204 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
1207 case BPF_MAP_TYPE_SK_STORAGE:
1208 case BPF_MAP_TYPE_INODE_STORAGE:
1209 case BPF_MAP_TYPE_TASK_STORAGE:
1210 case BPF_MAP_TYPE_CGRP_STORAGE:
1211 case BPF_MAP_TYPE_BLOOM_FILTER:
1212 case BPF_MAP_TYPE_LPM_TRIE:
1213 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
1214 case BPF_MAP_TYPE_STACK_TRACE:
1215 case BPF_MAP_TYPE_QUEUE:
1216 case BPF_MAP_TYPE_STACK:
1217 case BPF_MAP_TYPE_LRU_HASH:
1218 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
1219 case BPF_MAP_TYPE_STRUCT_OPS:
1220 case BPF_MAP_TYPE_CPUMAP:
1224 case BPF_MAP_TYPE_SOCKMAP:
1225 case BPF_MAP_TYPE_SOCKHASH:
1226 case BPF_MAP_TYPE_DEVMAP:
1227 case BPF_MAP_TYPE_DEVMAP_HASH:
1228 case BPF_MAP_TYPE_XSKMAP:
1229 if (!capable(CAP_NET_ADMIN))
1233 WARN(1, "unsupported map type %d", map_type);
1237 map = ops->map_alloc(attr);
1239 return PTR_ERR(map);
1241 map->map_type = map_type;
1243 err = bpf_obj_name_cpy(map->name, attr->map_name,
1244 sizeof(attr->map_name));
1248 atomic64_set(&map->refcnt, 1);
1249 atomic64_set(&map->usercnt, 1);
1250 mutex_init(&map->freeze_mutex);
1251 spin_lock_init(&map->owner.lock);
1253 if (attr->btf_key_type_id || attr->btf_value_type_id ||
1254 /* Even the map's value is a kernel's struct,
1255 * the bpf_prog.o must have BTF to begin with
1256 * to figure out the corresponding kernel's
1257 * counter part. Thus, attr->btf_fd has
1260 attr->btf_vmlinux_value_type_id) {
1263 btf = btf_get_by_fd(attr->btf_fd);
1268 if (btf_is_kernel(btf)) {
1275 if (attr->btf_value_type_id) {
1276 err = map_check_btf(map, btf, attr->btf_key_type_id,
1277 attr->btf_value_type_id);
1282 map->btf_key_type_id = attr->btf_key_type_id;
1283 map->btf_value_type_id = attr->btf_value_type_id;
1284 map->btf_vmlinux_value_type_id =
1285 attr->btf_vmlinux_value_type_id;
1288 err = security_bpf_map_alloc(map);
1292 err = bpf_map_alloc_id(map);
1296 bpf_map_save_memcg(map);
1298 err = bpf_map_new_fd(map, f_flags);
1300 /* failed to allocate fd.
1301 * bpf_map_put_with_uref() is needed because the above
1302 * bpf_map_alloc_id() has published the map
1303 * to the userspace and the userspace may
1304 * have refcnt-ed it through BPF_MAP_GET_FD_BY_ID.
1306 bpf_map_put_with_uref(map);
1313 security_bpf_map_free(map);
1316 map->ops->map_free(map);
1320 /* if error is returned, fd is released.
1321 * On success caller should complete fd access with matching fdput()
1323 struct bpf_map *__bpf_map_get(struct fd f)
1326 return ERR_PTR(-EBADF);
1327 if (f.file->f_op != &bpf_map_fops) {
1329 return ERR_PTR(-EINVAL);
1332 return f.file->private_data;
1335 void bpf_map_inc(struct bpf_map *map)
1337 atomic64_inc(&map->refcnt);
1339 EXPORT_SYMBOL_GPL(bpf_map_inc);
1341 void bpf_map_inc_with_uref(struct bpf_map *map)
1343 atomic64_inc(&map->refcnt);
1344 atomic64_inc(&map->usercnt);
1346 EXPORT_SYMBOL_GPL(bpf_map_inc_with_uref);
1348 struct bpf_map *bpf_map_get(u32 ufd)
1350 struct fd f = fdget(ufd);
1351 struct bpf_map *map;
1353 map = __bpf_map_get(f);
1362 EXPORT_SYMBOL(bpf_map_get);
1364 struct bpf_map *bpf_map_get_with_uref(u32 ufd)
1366 struct fd f = fdget(ufd);
1367 struct bpf_map *map;
1369 map = __bpf_map_get(f);
1373 bpf_map_inc_with_uref(map);
1379 /* map_idr_lock should have been held or the map should have been
1380 * protected by rcu read lock.
1382 struct bpf_map *__bpf_map_inc_not_zero(struct bpf_map *map, bool uref)
1386 refold = atomic64_fetch_add_unless(&map->refcnt, 1, 0);
1388 return ERR_PTR(-ENOENT);
1390 atomic64_inc(&map->usercnt);
1395 struct bpf_map *bpf_map_inc_not_zero(struct bpf_map *map)
1397 spin_lock_bh(&map_idr_lock);
1398 map = __bpf_map_inc_not_zero(map, false);
1399 spin_unlock_bh(&map_idr_lock);
1403 EXPORT_SYMBOL_GPL(bpf_map_inc_not_zero);
1405 int __weak bpf_stackmap_copy(struct bpf_map *map, void *key, void *value)
1410 static void *__bpf_copy_key(void __user *ukey, u64 key_size)
1413 return vmemdup_user(ukey, key_size);
1416 return ERR_PTR(-EINVAL);
1421 static void *___bpf_copy_key(bpfptr_t ukey, u64 key_size)
1424 return kvmemdup_bpfptr(ukey, key_size);
1426 if (!bpfptr_is_null(ukey))
1427 return ERR_PTR(-EINVAL);
1432 /* last field in 'union bpf_attr' used by this command */
1433 #define BPF_MAP_LOOKUP_ELEM_LAST_FIELD flags
1435 static int map_lookup_elem(union bpf_attr *attr)
1437 void __user *ukey = u64_to_user_ptr(attr->key);
1438 void __user *uvalue = u64_to_user_ptr(attr->value);
1439 int ufd = attr->map_fd;
1440 struct bpf_map *map;
1446 if (CHECK_ATTR(BPF_MAP_LOOKUP_ELEM))
1449 if (attr->flags & ~BPF_F_LOCK)
1453 map = __bpf_map_get(f);
1455 return PTR_ERR(map);
1456 if (!(map_get_sys_perms(map, f) & FMODE_CAN_READ)) {
1461 if ((attr->flags & BPF_F_LOCK) &&
1462 !btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
1467 key = __bpf_copy_key(ukey, map->key_size);
1473 value_size = bpf_map_value_size(map);
1476 value = kvmalloc(value_size, GFP_USER | __GFP_NOWARN);
1480 if (map->map_type == BPF_MAP_TYPE_BLOOM_FILTER) {
1481 if (copy_from_user(value, uvalue, value_size))
1484 err = bpf_map_copy_value(map, key, value, attr->flags);
1488 err = bpf_map_copy_value(map, key, value, attr->flags);
1493 if (copy_to_user(uvalue, value, value_size) != 0)
1508 #define BPF_MAP_UPDATE_ELEM_LAST_FIELD flags
1510 static int map_update_elem(union bpf_attr *attr, bpfptr_t uattr)
1512 bpfptr_t ukey = make_bpfptr(attr->key, uattr.is_kernel);
1513 bpfptr_t uvalue = make_bpfptr(attr->value, uattr.is_kernel);
1514 int ufd = attr->map_fd;
1515 struct bpf_map *map;
1521 if (CHECK_ATTR(BPF_MAP_UPDATE_ELEM))
1525 map = __bpf_map_get(f);
1527 return PTR_ERR(map);
1528 bpf_map_write_active_inc(map);
1529 if (!(map_get_sys_perms(map, f) & FMODE_CAN_WRITE)) {
1534 if ((attr->flags & BPF_F_LOCK) &&
1535 !btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
1540 key = ___bpf_copy_key(ukey, map->key_size);
1546 value_size = bpf_map_value_size(map);
1547 value = kvmemdup_bpfptr(uvalue, value_size);
1548 if (IS_ERR(value)) {
1549 err = PTR_ERR(value);
1553 err = bpf_map_update_value(map, f.file, key, value, attr->flags);
1555 maybe_wait_bpf_programs(map);
1561 bpf_map_write_active_dec(map);
1566 #define BPF_MAP_DELETE_ELEM_LAST_FIELD key
1568 static int map_delete_elem(union bpf_attr *attr, bpfptr_t uattr)
1570 bpfptr_t ukey = make_bpfptr(attr->key, uattr.is_kernel);
1571 int ufd = attr->map_fd;
1572 struct bpf_map *map;
1577 if (CHECK_ATTR(BPF_MAP_DELETE_ELEM))
1581 map = __bpf_map_get(f);
1583 return PTR_ERR(map);
1584 bpf_map_write_active_inc(map);
1585 if (!(map_get_sys_perms(map, f) & FMODE_CAN_WRITE)) {
1590 key = ___bpf_copy_key(ukey, map->key_size);
1596 if (bpf_map_is_offloaded(map)) {
1597 err = bpf_map_offload_delete_elem(map, key);
1599 } else if (IS_FD_PROG_ARRAY(map) ||
1600 map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
1601 /* These maps require sleepable context */
1602 err = map->ops->map_delete_elem(map, key);
1606 bpf_disable_instrumentation();
1608 err = map->ops->map_delete_elem(map, key);
1610 bpf_enable_instrumentation();
1612 maybe_wait_bpf_programs(map);
1616 bpf_map_write_active_dec(map);
1621 /* last field in 'union bpf_attr' used by this command */
1622 #define BPF_MAP_GET_NEXT_KEY_LAST_FIELD next_key
1624 static int map_get_next_key(union bpf_attr *attr)
1626 void __user *ukey = u64_to_user_ptr(attr->key);
1627 void __user *unext_key = u64_to_user_ptr(attr->next_key);
1628 int ufd = attr->map_fd;
1629 struct bpf_map *map;
1630 void *key, *next_key;
1634 if (CHECK_ATTR(BPF_MAP_GET_NEXT_KEY))
1638 map = __bpf_map_get(f);
1640 return PTR_ERR(map);
1641 if (!(map_get_sys_perms(map, f) & FMODE_CAN_READ)) {
1647 key = __bpf_copy_key(ukey, map->key_size);
1657 next_key = kvmalloc(map->key_size, GFP_USER);
1661 if (bpf_map_is_offloaded(map)) {
1662 err = bpf_map_offload_get_next_key(map, key, next_key);
1667 err = map->ops->map_get_next_key(map, key, next_key);
1674 if (copy_to_user(unext_key, next_key, map->key_size) != 0)
1688 int generic_map_delete_batch(struct bpf_map *map,
1689 const union bpf_attr *attr,
1690 union bpf_attr __user *uattr)
1692 void __user *keys = u64_to_user_ptr(attr->batch.keys);
1697 if (attr->batch.elem_flags & ~BPF_F_LOCK)
1700 if ((attr->batch.elem_flags & BPF_F_LOCK) &&
1701 !btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
1705 max_count = attr->batch.count;
1709 if (put_user(0, &uattr->batch.count))
1712 key = kvmalloc(map->key_size, GFP_USER | __GFP_NOWARN);
1716 for (cp = 0; cp < max_count; cp++) {
1718 if (copy_from_user(key, keys + cp * map->key_size,
1722 if (bpf_map_is_offloaded(map)) {
1723 err = bpf_map_offload_delete_elem(map, key);
1727 bpf_disable_instrumentation();
1729 err = map->ops->map_delete_elem(map, key);
1731 bpf_enable_instrumentation();
1736 if (copy_to_user(&uattr->batch.count, &cp, sizeof(cp)))
1744 int generic_map_update_batch(struct bpf_map *map, struct file *map_file,
1745 const union bpf_attr *attr,
1746 union bpf_attr __user *uattr)
1748 void __user *values = u64_to_user_ptr(attr->batch.values);
1749 void __user *keys = u64_to_user_ptr(attr->batch.keys);
1750 u32 value_size, cp, max_count;
1754 if (attr->batch.elem_flags & ~BPF_F_LOCK)
1757 if ((attr->batch.elem_flags & BPF_F_LOCK) &&
1758 !btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
1762 value_size = bpf_map_value_size(map);
1764 max_count = attr->batch.count;
1768 if (put_user(0, &uattr->batch.count))
1771 key = kvmalloc(map->key_size, GFP_USER | __GFP_NOWARN);
1775 value = kvmalloc(value_size, GFP_USER | __GFP_NOWARN);
1781 for (cp = 0; cp < max_count; cp++) {
1783 if (copy_from_user(key, keys + cp * map->key_size,
1785 copy_from_user(value, values + cp * value_size, value_size))
1788 err = bpf_map_update_value(map, map_file, key, value,
1789 attr->batch.elem_flags);
1796 if (copy_to_user(&uattr->batch.count, &cp, sizeof(cp)))
1805 #define MAP_LOOKUP_RETRIES 3
1807 int generic_map_lookup_batch(struct bpf_map *map,
1808 const union bpf_attr *attr,
1809 union bpf_attr __user *uattr)
1811 void __user *uobatch = u64_to_user_ptr(attr->batch.out_batch);
1812 void __user *ubatch = u64_to_user_ptr(attr->batch.in_batch);
1813 void __user *values = u64_to_user_ptr(attr->batch.values);
1814 void __user *keys = u64_to_user_ptr(attr->batch.keys);
1815 void *buf, *buf_prevkey, *prev_key, *key, *value;
1816 int err, retry = MAP_LOOKUP_RETRIES;
1817 u32 value_size, cp, max_count;
1819 if (attr->batch.elem_flags & ~BPF_F_LOCK)
1822 if ((attr->batch.elem_flags & BPF_F_LOCK) &&
1823 !btf_record_has_field(map->record, BPF_SPIN_LOCK))
1826 value_size = bpf_map_value_size(map);
1828 max_count = attr->batch.count;
1832 if (put_user(0, &uattr->batch.count))
1835 buf_prevkey = kvmalloc(map->key_size, GFP_USER | __GFP_NOWARN);
1839 buf = kvmalloc(map->key_size + value_size, GFP_USER | __GFP_NOWARN);
1841 kvfree(buf_prevkey);
1847 if (ubatch && copy_from_user(buf_prevkey, ubatch, map->key_size))
1850 value = key + map->key_size;
1852 prev_key = buf_prevkey;
1854 for (cp = 0; cp < max_count;) {
1856 err = map->ops->map_get_next_key(map, prev_key, key);
1860 err = bpf_map_copy_value(map, key, value,
1861 attr->batch.elem_flags);
1863 if (err == -ENOENT) {
1875 if (copy_to_user(keys + cp * map->key_size, key,
1880 if (copy_to_user(values + cp * value_size, value, value_size)) {
1886 prev_key = buf_prevkey;
1888 swap(prev_key, key);
1889 retry = MAP_LOOKUP_RETRIES;
1897 if ((copy_to_user(&uattr->batch.count, &cp, sizeof(cp)) ||
1898 (cp && copy_to_user(uobatch, prev_key, map->key_size))))
1902 kvfree(buf_prevkey);
1907 #define BPF_MAP_LOOKUP_AND_DELETE_ELEM_LAST_FIELD flags
1909 static int map_lookup_and_delete_elem(union bpf_attr *attr)
1911 void __user *ukey = u64_to_user_ptr(attr->key);
1912 void __user *uvalue = u64_to_user_ptr(attr->value);
1913 int ufd = attr->map_fd;
1914 struct bpf_map *map;
1920 if (CHECK_ATTR(BPF_MAP_LOOKUP_AND_DELETE_ELEM))
1923 if (attr->flags & ~BPF_F_LOCK)
1927 map = __bpf_map_get(f);
1929 return PTR_ERR(map);
1930 bpf_map_write_active_inc(map);
1931 if (!(map_get_sys_perms(map, f) & FMODE_CAN_READ) ||
1932 !(map_get_sys_perms(map, f) & FMODE_CAN_WRITE)) {
1938 (map->map_type == BPF_MAP_TYPE_QUEUE ||
1939 map->map_type == BPF_MAP_TYPE_STACK)) {
1944 if ((attr->flags & BPF_F_LOCK) &&
1945 !btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
1950 key = __bpf_copy_key(ukey, map->key_size);
1956 value_size = bpf_map_value_size(map);
1959 value = kvmalloc(value_size, GFP_USER | __GFP_NOWARN);
1964 if (map->map_type == BPF_MAP_TYPE_QUEUE ||
1965 map->map_type == BPF_MAP_TYPE_STACK) {
1966 err = map->ops->map_pop_elem(map, value);
1967 } else if (map->map_type == BPF_MAP_TYPE_HASH ||
1968 map->map_type == BPF_MAP_TYPE_PERCPU_HASH ||
1969 map->map_type == BPF_MAP_TYPE_LRU_HASH ||
1970 map->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH) {
1971 if (!bpf_map_is_offloaded(map)) {
1972 bpf_disable_instrumentation();
1974 err = map->ops->map_lookup_and_delete_elem(map, key, value, attr->flags);
1976 bpf_enable_instrumentation();
1983 if (copy_to_user(uvalue, value, value_size) != 0) {
1995 bpf_map_write_active_dec(map);
2000 #define BPF_MAP_FREEZE_LAST_FIELD map_fd
2002 static int map_freeze(const union bpf_attr *attr)
2004 int err = 0, ufd = attr->map_fd;
2005 struct bpf_map *map;
2008 if (CHECK_ATTR(BPF_MAP_FREEZE))
2012 map = __bpf_map_get(f);
2014 return PTR_ERR(map);
2016 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS || !IS_ERR_OR_NULL(map->record)) {
2021 if (!(map_get_sys_perms(map, f) & FMODE_CAN_WRITE)) {
2026 mutex_lock(&map->freeze_mutex);
2027 if (bpf_map_write_active(map)) {
2031 if (READ_ONCE(map->frozen)) {
2036 WRITE_ONCE(map->frozen, true);
2038 mutex_unlock(&map->freeze_mutex);
2043 static const struct bpf_prog_ops * const bpf_prog_types[] = {
2044 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
2045 [_id] = & _name ## _prog_ops,
2046 #define BPF_MAP_TYPE(_id, _ops)
2047 #define BPF_LINK_TYPE(_id, _name)
2048 #include <linux/bpf_types.h>
2049 #undef BPF_PROG_TYPE
2051 #undef BPF_LINK_TYPE
2054 static int find_prog_type(enum bpf_prog_type type, struct bpf_prog *prog)
2056 const struct bpf_prog_ops *ops;
2058 if (type >= ARRAY_SIZE(bpf_prog_types))
2060 type = array_index_nospec(type, ARRAY_SIZE(bpf_prog_types));
2061 ops = bpf_prog_types[type];
2065 if (!bpf_prog_is_offloaded(prog->aux))
2066 prog->aux->ops = ops;
2068 prog->aux->ops = &bpf_offload_prog_ops;
2079 static const char * const bpf_audit_str[BPF_AUDIT_MAX] = {
2080 [BPF_AUDIT_LOAD] = "LOAD",
2081 [BPF_AUDIT_UNLOAD] = "UNLOAD",
2084 static void bpf_audit_prog(const struct bpf_prog *prog, unsigned int op)
2086 struct audit_context *ctx = NULL;
2087 struct audit_buffer *ab;
2089 if (WARN_ON_ONCE(op >= BPF_AUDIT_MAX))
2091 if (audit_enabled == AUDIT_OFF)
2093 if (!in_irq() && !irqs_disabled())
2094 ctx = audit_context();
2095 ab = audit_log_start(ctx, GFP_ATOMIC, AUDIT_BPF);
2098 audit_log_format(ab, "prog-id=%u op=%s",
2099 prog->aux->id, bpf_audit_str[op]);
2103 static int bpf_prog_alloc_id(struct bpf_prog *prog)
2107 idr_preload(GFP_KERNEL);
2108 spin_lock_bh(&prog_idr_lock);
2109 id = idr_alloc_cyclic(&prog_idr, prog, 1, INT_MAX, GFP_ATOMIC);
2112 spin_unlock_bh(&prog_idr_lock);
2115 /* id is in [1, INT_MAX) */
2116 if (WARN_ON_ONCE(!id))
2119 return id > 0 ? 0 : id;
2122 void bpf_prog_free_id(struct bpf_prog *prog)
2124 unsigned long flags;
2126 /* cBPF to eBPF migrations are currently not in the idr store.
2127 * Offloaded programs are removed from the store when their device
2128 * disappears - even if someone grabs an fd to them they are unusable,
2129 * simply waiting for refcnt to drop to be freed.
2134 spin_lock_irqsave(&prog_idr_lock, flags);
2135 idr_remove(&prog_idr, prog->aux->id);
2137 spin_unlock_irqrestore(&prog_idr_lock, flags);
2140 static void __bpf_prog_put_rcu(struct rcu_head *rcu)
2142 struct bpf_prog_aux *aux = container_of(rcu, struct bpf_prog_aux, rcu);
2144 kvfree(aux->func_info);
2145 kfree(aux->func_info_aux);
2146 free_uid(aux->user);
2147 security_bpf_prog_free(aux);
2148 bpf_prog_free(aux->prog);
2151 static void __bpf_prog_put_noref(struct bpf_prog *prog, bool deferred)
2153 bpf_prog_kallsyms_del_all(prog);
2154 btf_put(prog->aux->btf);
2155 module_put(prog->aux->mod);
2156 kvfree(prog->aux->jited_linfo);
2157 kvfree(prog->aux->linfo);
2158 kfree(prog->aux->kfunc_tab);
2159 if (prog->aux->attach_btf)
2160 btf_put(prog->aux->attach_btf);
2163 if (prog->aux->sleepable)
2164 call_rcu_tasks_trace(&prog->aux->rcu, __bpf_prog_put_rcu);
2166 call_rcu(&prog->aux->rcu, __bpf_prog_put_rcu);
2168 __bpf_prog_put_rcu(&prog->aux->rcu);
2172 static void bpf_prog_put_deferred(struct work_struct *work)
2174 struct bpf_prog_aux *aux;
2175 struct bpf_prog *prog;
2177 aux = container_of(work, struct bpf_prog_aux, work);
2179 perf_event_bpf_event(prog, PERF_BPF_EVENT_PROG_UNLOAD, 0);
2180 bpf_audit_prog(prog, BPF_AUDIT_UNLOAD);
2181 bpf_prog_free_id(prog);
2182 __bpf_prog_put_noref(prog, true);
2185 static void __bpf_prog_put(struct bpf_prog *prog)
2187 struct bpf_prog_aux *aux = prog->aux;
2189 if (atomic64_dec_and_test(&aux->refcnt)) {
2190 if (in_irq() || irqs_disabled()) {
2191 INIT_WORK(&aux->work, bpf_prog_put_deferred);
2192 schedule_work(&aux->work);
2194 bpf_prog_put_deferred(&aux->work);
2199 void bpf_prog_put(struct bpf_prog *prog)
2201 __bpf_prog_put(prog);
2203 EXPORT_SYMBOL_GPL(bpf_prog_put);
2205 static int bpf_prog_release(struct inode *inode, struct file *filp)
2207 struct bpf_prog *prog = filp->private_data;
2213 struct bpf_prog_kstats {
2219 void notrace bpf_prog_inc_misses_counter(struct bpf_prog *prog)
2221 struct bpf_prog_stats *stats;
2224 stats = this_cpu_ptr(prog->stats);
2225 flags = u64_stats_update_begin_irqsave(&stats->syncp);
2226 u64_stats_inc(&stats->misses);
2227 u64_stats_update_end_irqrestore(&stats->syncp, flags);
2230 static void bpf_prog_get_stats(const struct bpf_prog *prog,
2231 struct bpf_prog_kstats *stats)
2233 u64 nsecs = 0, cnt = 0, misses = 0;
2236 for_each_possible_cpu(cpu) {
2237 const struct bpf_prog_stats *st;
2239 u64 tnsecs, tcnt, tmisses;
2241 st = per_cpu_ptr(prog->stats, cpu);
2243 start = u64_stats_fetch_begin(&st->syncp);
2244 tnsecs = u64_stats_read(&st->nsecs);
2245 tcnt = u64_stats_read(&st->cnt);
2246 tmisses = u64_stats_read(&st->misses);
2247 } while (u64_stats_fetch_retry(&st->syncp, start));
2252 stats->nsecs = nsecs;
2254 stats->misses = misses;
2257 #ifdef CONFIG_PROC_FS
2258 static void bpf_prog_show_fdinfo(struct seq_file *m, struct file *filp)
2260 const struct bpf_prog *prog = filp->private_data;
2261 char prog_tag[sizeof(prog->tag) * 2 + 1] = { };
2262 struct bpf_prog_kstats stats;
2264 bpf_prog_get_stats(prog, &stats);
2265 bin2hex(prog_tag, prog->tag, sizeof(prog->tag));
2272 "run_time_ns:\t%llu\n"
2274 "recursion_misses:\t%llu\n"
2275 "verified_insns:\t%u\n",
2279 prog->pages * 1ULL << PAGE_SHIFT,
2284 prog->aux->verified_insns);
2288 const struct file_operations bpf_prog_fops = {
2289 #ifdef CONFIG_PROC_FS
2290 .show_fdinfo = bpf_prog_show_fdinfo,
2292 .release = bpf_prog_release,
2293 .read = bpf_dummy_read,
2294 .write = bpf_dummy_write,
2297 int bpf_prog_new_fd(struct bpf_prog *prog)
2301 ret = security_bpf_prog(prog);
2305 return anon_inode_getfd("bpf-prog", &bpf_prog_fops, prog,
2306 O_RDWR | O_CLOEXEC);
2309 static struct bpf_prog *____bpf_prog_get(struct fd f)
2312 return ERR_PTR(-EBADF);
2313 if (f.file->f_op != &bpf_prog_fops) {
2315 return ERR_PTR(-EINVAL);
2318 return f.file->private_data;
2321 void bpf_prog_add(struct bpf_prog *prog, int i)
2323 atomic64_add(i, &prog->aux->refcnt);
2325 EXPORT_SYMBOL_GPL(bpf_prog_add);
2327 void bpf_prog_sub(struct bpf_prog *prog, int i)
2329 /* Only to be used for undoing previous bpf_prog_add() in some
2330 * error path. We still know that another entity in our call
2331 * path holds a reference to the program, thus atomic_sub() can
2332 * be safely used in such cases!
2334 WARN_ON(atomic64_sub_return(i, &prog->aux->refcnt) == 0);
2336 EXPORT_SYMBOL_GPL(bpf_prog_sub);
2338 void bpf_prog_inc(struct bpf_prog *prog)
2340 atomic64_inc(&prog->aux->refcnt);
2342 EXPORT_SYMBOL_GPL(bpf_prog_inc);
2344 /* prog_idr_lock should have been held */
2345 struct bpf_prog *bpf_prog_inc_not_zero(struct bpf_prog *prog)
2349 refold = atomic64_fetch_add_unless(&prog->aux->refcnt, 1, 0);
2352 return ERR_PTR(-ENOENT);
2356 EXPORT_SYMBOL_GPL(bpf_prog_inc_not_zero);
2358 bool bpf_prog_get_ok(struct bpf_prog *prog,
2359 enum bpf_prog_type *attach_type, bool attach_drv)
2361 /* not an attachment, just a refcount inc, always allow */
2365 if (prog->type != *attach_type)
2367 if (bpf_prog_is_offloaded(prog->aux) && !attach_drv)
2373 static struct bpf_prog *__bpf_prog_get(u32 ufd, enum bpf_prog_type *attach_type,
2376 struct fd f = fdget(ufd);
2377 struct bpf_prog *prog;
2379 prog = ____bpf_prog_get(f);
2382 if (!bpf_prog_get_ok(prog, attach_type, attach_drv)) {
2383 prog = ERR_PTR(-EINVAL);
2393 struct bpf_prog *bpf_prog_get(u32 ufd)
2395 return __bpf_prog_get(ufd, NULL, false);
2398 struct bpf_prog *bpf_prog_get_type_dev(u32 ufd, enum bpf_prog_type type,
2401 return __bpf_prog_get(ufd, &type, attach_drv);
2403 EXPORT_SYMBOL_GPL(bpf_prog_get_type_dev);
2405 /* Initially all BPF programs could be loaded w/o specifying
2406 * expected_attach_type. Later for some of them specifying expected_attach_type
2407 * at load time became required so that program could be validated properly.
2408 * Programs of types that are allowed to be loaded both w/ and w/o (for
2409 * backward compatibility) expected_attach_type, should have the default attach
2410 * type assigned to expected_attach_type for the latter case, so that it can be
2411 * validated later at attach time.
2413 * bpf_prog_load_fixup_attach_type() sets expected_attach_type in @attr if
2414 * prog type requires it but has some attach types that have to be backward
2417 static void bpf_prog_load_fixup_attach_type(union bpf_attr *attr)
2419 switch (attr->prog_type) {
2420 case BPF_PROG_TYPE_CGROUP_SOCK:
2421 /* Unfortunately BPF_ATTACH_TYPE_UNSPEC enumeration doesn't
2422 * exist so checking for non-zero is the way to go here.
2424 if (!attr->expected_attach_type)
2425 attr->expected_attach_type =
2426 BPF_CGROUP_INET_SOCK_CREATE;
2428 case BPF_PROG_TYPE_SK_REUSEPORT:
2429 if (!attr->expected_attach_type)
2430 attr->expected_attach_type =
2431 BPF_SK_REUSEPORT_SELECT;
2437 bpf_prog_load_check_attach(enum bpf_prog_type prog_type,
2438 enum bpf_attach_type expected_attach_type,
2439 struct btf *attach_btf, u32 btf_id,
2440 struct bpf_prog *dst_prog)
2443 if (btf_id > BTF_MAX_TYPE)
2446 if (!attach_btf && !dst_prog)
2449 switch (prog_type) {
2450 case BPF_PROG_TYPE_TRACING:
2451 case BPF_PROG_TYPE_LSM:
2452 case BPF_PROG_TYPE_STRUCT_OPS:
2453 case BPF_PROG_TYPE_EXT:
2460 if (attach_btf && (!btf_id || dst_prog))
2463 if (dst_prog && prog_type != BPF_PROG_TYPE_TRACING &&
2464 prog_type != BPF_PROG_TYPE_EXT)
2467 switch (prog_type) {
2468 case BPF_PROG_TYPE_CGROUP_SOCK:
2469 switch (expected_attach_type) {
2470 case BPF_CGROUP_INET_SOCK_CREATE:
2471 case BPF_CGROUP_INET_SOCK_RELEASE:
2472 case BPF_CGROUP_INET4_POST_BIND:
2473 case BPF_CGROUP_INET6_POST_BIND:
2478 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
2479 switch (expected_attach_type) {
2480 case BPF_CGROUP_INET4_BIND:
2481 case BPF_CGROUP_INET6_BIND:
2482 case BPF_CGROUP_INET4_CONNECT:
2483 case BPF_CGROUP_INET6_CONNECT:
2484 case BPF_CGROUP_UNIX_CONNECT:
2485 case BPF_CGROUP_INET4_GETPEERNAME:
2486 case BPF_CGROUP_INET6_GETPEERNAME:
2487 case BPF_CGROUP_UNIX_GETPEERNAME:
2488 case BPF_CGROUP_INET4_GETSOCKNAME:
2489 case BPF_CGROUP_INET6_GETSOCKNAME:
2490 case BPF_CGROUP_UNIX_GETSOCKNAME:
2491 case BPF_CGROUP_UDP4_SENDMSG:
2492 case BPF_CGROUP_UDP6_SENDMSG:
2493 case BPF_CGROUP_UNIX_SENDMSG:
2494 case BPF_CGROUP_UDP4_RECVMSG:
2495 case BPF_CGROUP_UDP6_RECVMSG:
2496 case BPF_CGROUP_UNIX_RECVMSG:
2501 case BPF_PROG_TYPE_CGROUP_SKB:
2502 switch (expected_attach_type) {
2503 case BPF_CGROUP_INET_INGRESS:
2504 case BPF_CGROUP_INET_EGRESS:
2509 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
2510 switch (expected_attach_type) {
2511 case BPF_CGROUP_SETSOCKOPT:
2512 case BPF_CGROUP_GETSOCKOPT:
2517 case BPF_PROG_TYPE_SK_LOOKUP:
2518 if (expected_attach_type == BPF_SK_LOOKUP)
2521 case BPF_PROG_TYPE_SK_REUSEPORT:
2522 switch (expected_attach_type) {
2523 case BPF_SK_REUSEPORT_SELECT:
2524 case BPF_SK_REUSEPORT_SELECT_OR_MIGRATE:
2529 case BPF_PROG_TYPE_NETFILTER:
2530 if (expected_attach_type == BPF_NETFILTER)
2533 case BPF_PROG_TYPE_SYSCALL:
2534 case BPF_PROG_TYPE_EXT:
2535 if (expected_attach_type)
2543 static bool is_net_admin_prog_type(enum bpf_prog_type prog_type)
2545 switch (prog_type) {
2546 case BPF_PROG_TYPE_SCHED_CLS:
2547 case BPF_PROG_TYPE_SCHED_ACT:
2548 case BPF_PROG_TYPE_XDP:
2549 case BPF_PROG_TYPE_LWT_IN:
2550 case BPF_PROG_TYPE_LWT_OUT:
2551 case BPF_PROG_TYPE_LWT_XMIT:
2552 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
2553 case BPF_PROG_TYPE_SK_SKB:
2554 case BPF_PROG_TYPE_SK_MSG:
2555 case BPF_PROG_TYPE_FLOW_DISSECTOR:
2556 case BPF_PROG_TYPE_CGROUP_DEVICE:
2557 case BPF_PROG_TYPE_CGROUP_SOCK:
2558 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
2559 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
2560 case BPF_PROG_TYPE_CGROUP_SYSCTL:
2561 case BPF_PROG_TYPE_SOCK_OPS:
2562 case BPF_PROG_TYPE_EXT: /* extends any prog */
2563 case BPF_PROG_TYPE_NETFILTER:
2565 case BPF_PROG_TYPE_CGROUP_SKB:
2567 case BPF_PROG_TYPE_SK_REUSEPORT:
2568 /* equivalent to SOCKET_FILTER. need CAP_BPF only */
2574 static bool is_perfmon_prog_type(enum bpf_prog_type prog_type)
2576 switch (prog_type) {
2577 case BPF_PROG_TYPE_KPROBE:
2578 case BPF_PROG_TYPE_TRACEPOINT:
2579 case BPF_PROG_TYPE_PERF_EVENT:
2580 case BPF_PROG_TYPE_RAW_TRACEPOINT:
2581 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
2582 case BPF_PROG_TYPE_TRACING:
2583 case BPF_PROG_TYPE_LSM:
2584 case BPF_PROG_TYPE_STRUCT_OPS: /* has access to struct sock */
2585 case BPF_PROG_TYPE_EXT: /* extends any prog */
2592 /* last field in 'union bpf_attr' used by this command */
2593 #define BPF_PROG_LOAD_LAST_FIELD log_true_size
2595 static int bpf_prog_load(union bpf_attr *attr, bpfptr_t uattr, u32 uattr_size)
2597 enum bpf_prog_type type = attr->prog_type;
2598 struct bpf_prog *prog, *dst_prog = NULL;
2599 struct btf *attach_btf = NULL;
2603 if (CHECK_ATTR(BPF_PROG_LOAD))
2606 if (attr->prog_flags & ~(BPF_F_STRICT_ALIGNMENT |
2607 BPF_F_ANY_ALIGNMENT |
2608 BPF_F_TEST_STATE_FREQ |
2610 BPF_F_TEST_RND_HI32 |
2611 BPF_F_XDP_HAS_FRAGS |
2612 BPF_F_XDP_DEV_BOUND_ONLY |
2613 BPF_F_TEST_REG_INVARIANTS))
2616 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS) &&
2617 (attr->prog_flags & BPF_F_ANY_ALIGNMENT) &&
2621 /* Intent here is for unprivileged_bpf_disabled to block BPF program
2622 * creation for unprivileged users; other actions depend
2623 * on fd availability and access to bpffs, so are dependent on
2624 * object creation success. Even with unprivileged BPF disabled,
2625 * capability checks are still carried out for these
2626 * and other operations.
2628 if (sysctl_unprivileged_bpf_disabled && !bpf_capable())
2631 if (attr->insn_cnt == 0 ||
2632 attr->insn_cnt > (bpf_capable() ? BPF_COMPLEXITY_LIMIT_INSNS : BPF_MAXINSNS))
2634 if (type != BPF_PROG_TYPE_SOCKET_FILTER &&
2635 type != BPF_PROG_TYPE_CGROUP_SKB &&
2639 if (is_net_admin_prog_type(type) && !capable(CAP_NET_ADMIN) && !capable(CAP_SYS_ADMIN))
2641 if (is_perfmon_prog_type(type) && !perfmon_capable())
2644 /* attach_prog_fd/attach_btf_obj_fd can specify fd of either bpf_prog
2645 * or btf, we need to check which one it is
2647 if (attr->attach_prog_fd) {
2648 dst_prog = bpf_prog_get(attr->attach_prog_fd);
2649 if (IS_ERR(dst_prog)) {
2651 attach_btf = btf_get_by_fd(attr->attach_btf_obj_fd);
2652 if (IS_ERR(attach_btf))
2654 if (!btf_is_kernel(attach_btf)) {
2655 /* attaching through specifying bpf_prog's BTF
2656 * objects directly might be supported eventually
2658 btf_put(attach_btf);
2662 } else if (attr->attach_btf_id) {
2663 /* fall back to vmlinux BTF, if BTF type ID is specified */
2664 attach_btf = bpf_get_btf_vmlinux();
2665 if (IS_ERR(attach_btf))
2666 return PTR_ERR(attach_btf);
2669 btf_get(attach_btf);
2672 bpf_prog_load_fixup_attach_type(attr);
2673 if (bpf_prog_load_check_attach(type, attr->expected_attach_type,
2674 attach_btf, attr->attach_btf_id,
2677 bpf_prog_put(dst_prog);
2679 btf_put(attach_btf);
2683 /* plain bpf_prog allocation */
2684 prog = bpf_prog_alloc(bpf_prog_size(attr->insn_cnt), GFP_USER);
2687 bpf_prog_put(dst_prog);
2689 btf_put(attach_btf);
2693 prog->expected_attach_type = attr->expected_attach_type;
2694 prog->aux->attach_btf = attach_btf;
2695 prog->aux->attach_btf_id = attr->attach_btf_id;
2696 prog->aux->dst_prog = dst_prog;
2697 prog->aux->dev_bound = !!attr->prog_ifindex;
2698 prog->aux->sleepable = attr->prog_flags & BPF_F_SLEEPABLE;
2699 prog->aux->xdp_has_frags = attr->prog_flags & BPF_F_XDP_HAS_FRAGS;
2701 err = security_bpf_prog_alloc(prog->aux);
2705 prog->aux->user = get_current_user();
2706 prog->len = attr->insn_cnt;
2709 if (copy_from_bpfptr(prog->insns,
2710 make_bpfptr(attr->insns, uattr.is_kernel),
2711 bpf_prog_insn_size(prog)) != 0)
2713 /* copy eBPF program license from user space */
2714 if (strncpy_from_bpfptr(license,
2715 make_bpfptr(attr->license, uattr.is_kernel),
2716 sizeof(license) - 1) < 0)
2718 license[sizeof(license) - 1] = 0;
2720 /* eBPF programs must be GPL compatible to use GPL-ed functions */
2721 prog->gpl_compatible = license_is_gpl_compatible(license) ? 1 : 0;
2723 prog->orig_prog = NULL;
2726 atomic64_set(&prog->aux->refcnt, 1);
2728 if (bpf_prog_is_dev_bound(prog->aux)) {
2729 err = bpf_prog_dev_bound_init(prog, attr);
2734 if (type == BPF_PROG_TYPE_EXT && dst_prog &&
2735 bpf_prog_is_dev_bound(dst_prog->aux)) {
2736 err = bpf_prog_dev_bound_inherit(prog, dst_prog);
2742 * Bookkeeping for managing the program attachment chain.
2744 * It might be tempting to set attach_tracing_prog flag at the attachment
2745 * time, but this will not prevent from loading bunch of tracing prog
2746 * first, then attach them one to another.
2748 * The flag attach_tracing_prog is set for the whole program lifecycle, and
2749 * doesn't have to be cleared in bpf_tracing_link_release, since tracing
2750 * programs cannot change attachment target.
2752 if (type == BPF_PROG_TYPE_TRACING && dst_prog &&
2753 dst_prog->type == BPF_PROG_TYPE_TRACING) {
2754 prog->aux->attach_tracing_prog = true;
2757 /* find program type: socket_filter vs tracing_filter */
2758 err = find_prog_type(type, prog);
2762 prog->aux->load_time = ktime_get_boottime_ns();
2763 err = bpf_obj_name_cpy(prog->aux->name, attr->prog_name,
2764 sizeof(attr->prog_name));
2768 /* run eBPF verifier */
2769 err = bpf_check(&prog, attr, uattr, uattr_size);
2771 goto free_used_maps;
2773 prog = bpf_prog_select_runtime(prog, &err);
2775 goto free_used_maps;
2777 err = bpf_prog_alloc_id(prog);
2779 goto free_used_maps;
2781 /* Upon success of bpf_prog_alloc_id(), the BPF prog is
2782 * effectively publicly exposed. However, retrieving via
2783 * bpf_prog_get_fd_by_id() will take another reference,
2784 * therefore it cannot be gone underneath us.
2786 * Only for the time /after/ successful bpf_prog_new_fd()
2787 * and before returning to userspace, we might just hold
2788 * one reference and any parallel close on that fd could
2789 * rip everything out. Hence, below notifications must
2790 * happen before bpf_prog_new_fd().
2792 * Also, any failure handling from this point onwards must
2793 * be using bpf_prog_put() given the program is exposed.
2795 bpf_prog_kallsyms_add(prog);
2796 perf_event_bpf_event(prog, PERF_BPF_EVENT_PROG_LOAD, 0);
2797 bpf_audit_prog(prog, BPF_AUDIT_LOAD);
2799 err = bpf_prog_new_fd(prog);
2805 /* In case we have subprogs, we need to wait for a grace
2806 * period before we can tear down JIT memory since symbols
2807 * are already exposed under kallsyms.
2809 __bpf_prog_put_noref(prog, prog->aux->real_func_cnt);
2812 free_uid(prog->aux->user);
2813 security_bpf_prog_free(prog->aux);
2815 if (prog->aux->attach_btf)
2816 btf_put(prog->aux->attach_btf);
2817 bpf_prog_free(prog);
2821 #define BPF_OBJ_LAST_FIELD path_fd
2823 static int bpf_obj_pin(const union bpf_attr *attr)
2827 if (CHECK_ATTR(BPF_OBJ) || attr->file_flags & ~BPF_F_PATH_FD)
2830 /* path_fd has to be accompanied by BPF_F_PATH_FD flag */
2831 if (!(attr->file_flags & BPF_F_PATH_FD) && attr->path_fd)
2834 path_fd = attr->file_flags & BPF_F_PATH_FD ? attr->path_fd : AT_FDCWD;
2835 return bpf_obj_pin_user(attr->bpf_fd, path_fd,
2836 u64_to_user_ptr(attr->pathname));
2839 static int bpf_obj_get(const union bpf_attr *attr)
2843 if (CHECK_ATTR(BPF_OBJ) || attr->bpf_fd != 0 ||
2844 attr->file_flags & ~(BPF_OBJ_FLAG_MASK | BPF_F_PATH_FD))
2847 /* path_fd has to be accompanied by BPF_F_PATH_FD flag */
2848 if (!(attr->file_flags & BPF_F_PATH_FD) && attr->path_fd)
2851 path_fd = attr->file_flags & BPF_F_PATH_FD ? attr->path_fd : AT_FDCWD;
2852 return bpf_obj_get_user(path_fd, u64_to_user_ptr(attr->pathname),
2856 void bpf_link_init(struct bpf_link *link, enum bpf_link_type type,
2857 const struct bpf_link_ops *ops, struct bpf_prog *prog)
2859 atomic64_set(&link->refcnt, 1);
2866 static void bpf_link_free_id(int id)
2871 spin_lock_bh(&link_idr_lock);
2872 idr_remove(&link_idr, id);
2873 spin_unlock_bh(&link_idr_lock);
2876 /* Clean up bpf_link and corresponding anon_inode file and FD. After
2877 * anon_inode is created, bpf_link can't be just kfree()'d due to deferred
2878 * anon_inode's release() call. This helper marks bpf_link as
2879 * defunct, releases anon_inode file and puts reserved FD. bpf_prog's refcnt
2880 * is not decremented, it's the responsibility of a calling code that failed
2881 * to complete bpf_link initialization.
2882 * This helper eventually calls link's dealloc callback, but does not call
2883 * link's release callback.
2885 void bpf_link_cleanup(struct bpf_link_primer *primer)
2887 primer->link->prog = NULL;
2888 bpf_link_free_id(primer->id);
2890 put_unused_fd(primer->fd);
2893 void bpf_link_inc(struct bpf_link *link)
2895 atomic64_inc(&link->refcnt);
2898 /* bpf_link_free is guaranteed to be called from process context */
2899 static void bpf_link_free(struct bpf_link *link)
2901 bpf_link_free_id(link->id);
2903 /* detach BPF program, clean up used resources */
2904 link->ops->release(link);
2905 bpf_prog_put(link->prog);
2907 /* free bpf_link and its containing memory */
2908 link->ops->dealloc(link);
2911 static void bpf_link_put_deferred(struct work_struct *work)
2913 struct bpf_link *link = container_of(work, struct bpf_link, work);
2915 bpf_link_free(link);
2918 /* bpf_link_put might be called from atomic context. It needs to be called
2919 * from sleepable context in order to acquire sleeping locks during the process.
2921 void bpf_link_put(struct bpf_link *link)
2923 if (!atomic64_dec_and_test(&link->refcnt))
2926 INIT_WORK(&link->work, bpf_link_put_deferred);
2927 schedule_work(&link->work);
2929 EXPORT_SYMBOL(bpf_link_put);
2931 static void bpf_link_put_direct(struct bpf_link *link)
2933 if (!atomic64_dec_and_test(&link->refcnt))
2935 bpf_link_free(link);
2938 static int bpf_link_release(struct inode *inode, struct file *filp)
2940 struct bpf_link *link = filp->private_data;
2942 bpf_link_put_direct(link);
2946 #ifdef CONFIG_PROC_FS
2947 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type)
2948 #define BPF_MAP_TYPE(_id, _ops)
2949 #define BPF_LINK_TYPE(_id, _name) [_id] = #_name,
2950 static const char *bpf_link_type_strs[] = {
2951 [BPF_LINK_TYPE_UNSPEC] = "<invalid>",
2952 #include <linux/bpf_types.h>
2954 #undef BPF_PROG_TYPE
2956 #undef BPF_LINK_TYPE
2958 static void bpf_link_show_fdinfo(struct seq_file *m, struct file *filp)
2960 const struct bpf_link *link = filp->private_data;
2961 const struct bpf_prog *prog = link->prog;
2962 char prog_tag[sizeof(prog->tag) * 2 + 1] = { };
2967 bpf_link_type_strs[link->type],
2970 bin2hex(prog_tag, prog->tag, sizeof(prog->tag));
2977 if (link->ops->show_fdinfo)
2978 link->ops->show_fdinfo(link, m);
2982 static const struct file_operations bpf_link_fops = {
2983 #ifdef CONFIG_PROC_FS
2984 .show_fdinfo = bpf_link_show_fdinfo,
2986 .release = bpf_link_release,
2987 .read = bpf_dummy_read,
2988 .write = bpf_dummy_write,
2991 static int bpf_link_alloc_id(struct bpf_link *link)
2995 idr_preload(GFP_KERNEL);
2996 spin_lock_bh(&link_idr_lock);
2997 id = idr_alloc_cyclic(&link_idr, link, 1, INT_MAX, GFP_ATOMIC);
2998 spin_unlock_bh(&link_idr_lock);
3004 /* Prepare bpf_link to be exposed to user-space by allocating anon_inode file,
3005 * reserving unused FD and allocating ID from link_idr. This is to be paired
3006 * with bpf_link_settle() to install FD and ID and expose bpf_link to
3007 * user-space, if bpf_link is successfully attached. If not, bpf_link and
3008 * pre-allocated resources are to be freed with bpf_cleanup() call. All the
3009 * transient state is passed around in struct bpf_link_primer.
3010 * This is preferred way to create and initialize bpf_link, especially when
3011 * there are complicated and expensive operations in between creating bpf_link
3012 * itself and attaching it to BPF hook. By using bpf_link_prime() and
3013 * bpf_link_settle() kernel code using bpf_link doesn't have to perform
3014 * expensive (and potentially failing) roll back operations in a rare case
3015 * that file, FD, or ID can't be allocated.
3017 int bpf_link_prime(struct bpf_link *link, struct bpf_link_primer *primer)
3022 fd = get_unused_fd_flags(O_CLOEXEC);
3027 id = bpf_link_alloc_id(link);
3033 file = anon_inode_getfile("bpf_link", &bpf_link_fops, link, O_CLOEXEC);
3035 bpf_link_free_id(id);
3037 return PTR_ERR(file);
3040 primer->link = link;
3041 primer->file = file;
3047 int bpf_link_settle(struct bpf_link_primer *primer)
3049 /* make bpf_link fetchable by ID */
3050 spin_lock_bh(&link_idr_lock);
3051 primer->link->id = primer->id;
3052 spin_unlock_bh(&link_idr_lock);
3053 /* make bpf_link fetchable by FD */
3054 fd_install(primer->fd, primer->file);
3055 /* pass through installed FD */
3059 int bpf_link_new_fd(struct bpf_link *link)
3061 return anon_inode_getfd("bpf-link", &bpf_link_fops, link, O_CLOEXEC);
3064 struct bpf_link *bpf_link_get_from_fd(u32 ufd)
3066 struct fd f = fdget(ufd);
3067 struct bpf_link *link;
3070 return ERR_PTR(-EBADF);
3071 if (f.file->f_op != &bpf_link_fops) {
3073 return ERR_PTR(-EINVAL);
3076 link = f.file->private_data;
3082 EXPORT_SYMBOL(bpf_link_get_from_fd);
3084 static void bpf_tracing_link_release(struct bpf_link *link)
3086 struct bpf_tracing_link *tr_link =
3087 container_of(link, struct bpf_tracing_link, link.link);
3089 WARN_ON_ONCE(bpf_trampoline_unlink_prog(&tr_link->link,
3090 tr_link->trampoline));
3092 bpf_trampoline_put(tr_link->trampoline);
3094 /* tgt_prog is NULL if target is a kernel function */
3095 if (tr_link->tgt_prog)
3096 bpf_prog_put(tr_link->tgt_prog);
3099 static void bpf_tracing_link_dealloc(struct bpf_link *link)
3101 struct bpf_tracing_link *tr_link =
3102 container_of(link, struct bpf_tracing_link, link.link);
3107 static void bpf_tracing_link_show_fdinfo(const struct bpf_link *link,
3108 struct seq_file *seq)
3110 struct bpf_tracing_link *tr_link =
3111 container_of(link, struct bpf_tracing_link, link.link);
3112 u32 target_btf_id, target_obj_id;
3114 bpf_trampoline_unpack_key(tr_link->trampoline->key,
3115 &target_obj_id, &target_btf_id);
3117 "attach_type:\t%d\n"
3118 "target_obj_id:\t%u\n"
3119 "target_btf_id:\t%u\n",
3120 tr_link->attach_type,
3125 static int bpf_tracing_link_fill_link_info(const struct bpf_link *link,
3126 struct bpf_link_info *info)
3128 struct bpf_tracing_link *tr_link =
3129 container_of(link, struct bpf_tracing_link, link.link);
3131 info->tracing.attach_type = tr_link->attach_type;
3132 bpf_trampoline_unpack_key(tr_link->trampoline->key,
3133 &info->tracing.target_obj_id,
3134 &info->tracing.target_btf_id);
3139 static const struct bpf_link_ops bpf_tracing_link_lops = {
3140 .release = bpf_tracing_link_release,
3141 .dealloc = bpf_tracing_link_dealloc,
3142 .show_fdinfo = bpf_tracing_link_show_fdinfo,
3143 .fill_link_info = bpf_tracing_link_fill_link_info,
3146 static int bpf_tracing_prog_attach(struct bpf_prog *prog,
3151 struct bpf_link_primer link_primer;
3152 struct bpf_prog *tgt_prog = NULL;
3153 struct bpf_trampoline *tr = NULL;
3154 struct bpf_tracing_link *link;
3158 switch (prog->type) {
3159 case BPF_PROG_TYPE_TRACING:
3160 if (prog->expected_attach_type != BPF_TRACE_FENTRY &&
3161 prog->expected_attach_type != BPF_TRACE_FEXIT &&
3162 prog->expected_attach_type != BPF_MODIFY_RETURN) {
3167 case BPF_PROG_TYPE_EXT:
3168 if (prog->expected_attach_type != 0) {
3173 case BPF_PROG_TYPE_LSM:
3174 if (prog->expected_attach_type != BPF_LSM_MAC) {
3184 if (!!tgt_prog_fd != !!btf_id) {
3191 * For now we only allow new targets for BPF_PROG_TYPE_EXT. If this
3192 * part would be changed to implement the same for
3193 * BPF_PROG_TYPE_TRACING, do not forget to update the way how
3194 * attach_tracing_prog flag is set.
3196 if (prog->type != BPF_PROG_TYPE_EXT) {
3201 tgt_prog = bpf_prog_get(tgt_prog_fd);
3202 if (IS_ERR(tgt_prog)) {
3203 err = PTR_ERR(tgt_prog);
3208 key = bpf_trampoline_compute_key(tgt_prog, NULL, btf_id);
3211 link = kzalloc(sizeof(*link), GFP_USER);
3216 bpf_link_init(&link->link.link, BPF_LINK_TYPE_TRACING,
3217 &bpf_tracing_link_lops, prog);
3218 link->attach_type = prog->expected_attach_type;
3219 link->link.cookie = bpf_cookie;
3221 mutex_lock(&prog->aux->dst_mutex);
3223 /* There are a few possible cases here:
3225 * - if prog->aux->dst_trampoline is set, the program was just loaded
3226 * and not yet attached to anything, so we can use the values stored
3229 * - if prog->aux->dst_trampoline is NULL, the program has already been
3230 * attached to a target and its initial target was cleared (below)
3232 * - if tgt_prog != NULL, the caller specified tgt_prog_fd +
3233 * target_btf_id using the link_create API.
3235 * - if tgt_prog == NULL when this function was called using the old
3236 * raw_tracepoint_open API, and we need a target from prog->aux
3238 * - if prog->aux->dst_trampoline and tgt_prog is NULL, the program
3239 * was detached and is going for re-attachment.
3241 * - if prog->aux->dst_trampoline is NULL and tgt_prog and prog->aux->attach_btf
3242 * are NULL, then program was already attached and user did not provide
3243 * tgt_prog_fd so we have no way to find out or create trampoline
3245 if (!prog->aux->dst_trampoline && !tgt_prog) {
3247 * Allow re-attach for TRACING and LSM programs. If it's
3248 * currently linked, bpf_trampoline_link_prog will fail.
3249 * EXT programs need to specify tgt_prog_fd, so they
3250 * re-attach in separate code path.
3252 if (prog->type != BPF_PROG_TYPE_TRACING &&
3253 prog->type != BPF_PROG_TYPE_LSM) {
3257 /* We can allow re-attach only if we have valid attach_btf. */
3258 if (!prog->aux->attach_btf) {
3262 btf_id = prog->aux->attach_btf_id;
3263 key = bpf_trampoline_compute_key(NULL, prog->aux->attach_btf, btf_id);
3266 if (!prog->aux->dst_trampoline ||
3267 (key && key != prog->aux->dst_trampoline->key)) {
3268 /* If there is no saved target, or the specified target is
3269 * different from the destination specified at load time, we
3270 * need a new trampoline and a check for compatibility
3272 struct bpf_attach_target_info tgt_info = {};
3274 err = bpf_check_attach_target(NULL, prog, tgt_prog, btf_id,
3279 if (tgt_info.tgt_mod) {
3280 module_put(prog->aux->mod);
3281 prog->aux->mod = tgt_info.tgt_mod;
3284 tr = bpf_trampoline_get(key, &tgt_info);
3290 /* The caller didn't specify a target, or the target was the
3291 * same as the destination supplied during program load. This
3292 * means we can reuse the trampoline and reference from program
3293 * load time, and there is no need to allocate a new one. This
3294 * can only happen once for any program, as the saved values in
3295 * prog->aux are cleared below.
3297 tr = prog->aux->dst_trampoline;
3298 tgt_prog = prog->aux->dst_prog;
3301 err = bpf_link_prime(&link->link.link, &link_primer);
3305 err = bpf_trampoline_link_prog(&link->link, tr);
3307 bpf_link_cleanup(&link_primer);
3312 link->tgt_prog = tgt_prog;
3313 link->trampoline = tr;
3315 /* Always clear the trampoline and target prog from prog->aux to make
3316 * sure the original attach destination is not kept alive after a
3317 * program is (re-)attached to another target.
3319 if (prog->aux->dst_prog &&
3320 (tgt_prog_fd || tr != prog->aux->dst_trampoline))
3321 /* got extra prog ref from syscall, or attaching to different prog */
3322 bpf_prog_put(prog->aux->dst_prog);
3323 if (prog->aux->dst_trampoline && tr != prog->aux->dst_trampoline)
3324 /* we allocated a new trampoline, so free the old one */
3325 bpf_trampoline_put(prog->aux->dst_trampoline);
3327 prog->aux->dst_prog = NULL;
3328 prog->aux->dst_trampoline = NULL;
3329 mutex_unlock(&prog->aux->dst_mutex);
3331 return bpf_link_settle(&link_primer);
3333 if (tr && tr != prog->aux->dst_trampoline)
3334 bpf_trampoline_put(tr);
3335 mutex_unlock(&prog->aux->dst_mutex);
3338 if (tgt_prog_fd && tgt_prog)
3339 bpf_prog_put(tgt_prog);
3343 struct bpf_raw_tp_link {
3344 struct bpf_link link;
3345 struct bpf_raw_event_map *btp;
3348 static void bpf_raw_tp_link_release(struct bpf_link *link)
3350 struct bpf_raw_tp_link *raw_tp =
3351 container_of(link, struct bpf_raw_tp_link, link);
3353 bpf_probe_unregister(raw_tp->btp, raw_tp->link.prog);
3354 bpf_put_raw_tracepoint(raw_tp->btp);
3357 static void bpf_raw_tp_link_dealloc(struct bpf_link *link)
3359 struct bpf_raw_tp_link *raw_tp =
3360 container_of(link, struct bpf_raw_tp_link, link);
3365 static void bpf_raw_tp_link_show_fdinfo(const struct bpf_link *link,
3366 struct seq_file *seq)
3368 struct bpf_raw_tp_link *raw_tp_link =
3369 container_of(link, struct bpf_raw_tp_link, link);
3373 raw_tp_link->btp->tp->name);
3376 static int bpf_copy_to_user(char __user *ubuf, const char *buf, u32 ulen,
3379 if (ulen >= len + 1) {
3380 if (copy_to_user(ubuf, buf, len + 1))
3385 if (copy_to_user(ubuf, buf, ulen - 1))
3387 if (put_user(zero, ubuf + ulen - 1))
3395 static int bpf_raw_tp_link_fill_link_info(const struct bpf_link *link,
3396 struct bpf_link_info *info)
3398 struct bpf_raw_tp_link *raw_tp_link =
3399 container_of(link, struct bpf_raw_tp_link, link);
3400 char __user *ubuf = u64_to_user_ptr(info->raw_tracepoint.tp_name);
3401 const char *tp_name = raw_tp_link->btp->tp->name;
3402 u32 ulen = info->raw_tracepoint.tp_name_len;
3403 size_t tp_len = strlen(tp_name);
3408 info->raw_tracepoint.tp_name_len = tp_len + 1;
3413 return bpf_copy_to_user(ubuf, tp_name, ulen, tp_len);
3416 static const struct bpf_link_ops bpf_raw_tp_link_lops = {
3417 .release = bpf_raw_tp_link_release,
3418 .dealloc = bpf_raw_tp_link_dealloc,
3419 .show_fdinfo = bpf_raw_tp_link_show_fdinfo,
3420 .fill_link_info = bpf_raw_tp_link_fill_link_info,
3423 #ifdef CONFIG_PERF_EVENTS
3424 struct bpf_perf_link {
3425 struct bpf_link link;
3426 struct file *perf_file;
3429 static void bpf_perf_link_release(struct bpf_link *link)
3431 struct bpf_perf_link *perf_link = container_of(link, struct bpf_perf_link, link);
3432 struct perf_event *event = perf_link->perf_file->private_data;
3434 perf_event_free_bpf_prog(event);
3435 fput(perf_link->perf_file);
3438 static void bpf_perf_link_dealloc(struct bpf_link *link)
3440 struct bpf_perf_link *perf_link = container_of(link, struct bpf_perf_link, link);
3445 static int bpf_perf_link_fill_common(const struct perf_event *event,
3446 char __user *uname, u32 ulen,
3447 u64 *probe_offset, u64 *probe_addr,
3448 u32 *fd_type, unsigned long *missed)
3458 err = bpf_get_perf_event_info(event, &prog_id, fd_type, &buf,
3459 probe_offset, probe_addr, missed);
3466 err = bpf_copy_to_user(uname, buf, ulen, len);
3472 if (put_user(zero, uname))
3478 #ifdef CONFIG_KPROBE_EVENTS
3479 static int bpf_perf_link_fill_kprobe(const struct perf_event *event,
3480 struct bpf_link_info *info)
3482 unsigned long missed;
3488 uname = u64_to_user_ptr(info->perf_event.kprobe.func_name);
3489 ulen = info->perf_event.kprobe.name_len;
3490 err = bpf_perf_link_fill_common(event, uname, ulen, &offset, &addr,
3494 if (type == BPF_FD_TYPE_KRETPROBE)
3495 info->perf_event.type = BPF_PERF_EVENT_KRETPROBE;
3497 info->perf_event.type = BPF_PERF_EVENT_KPROBE;
3499 info->perf_event.kprobe.offset = offset;
3500 info->perf_event.kprobe.missed = missed;
3501 if (!kallsyms_show_value(current_cred()))
3503 info->perf_event.kprobe.addr = addr;
3508 #ifdef CONFIG_UPROBE_EVENTS
3509 static int bpf_perf_link_fill_uprobe(const struct perf_event *event,
3510 struct bpf_link_info *info)
3517 uname = u64_to_user_ptr(info->perf_event.uprobe.file_name);
3518 ulen = info->perf_event.uprobe.name_len;
3519 err = bpf_perf_link_fill_common(event, uname, ulen, &offset, &addr,
3524 if (type == BPF_FD_TYPE_URETPROBE)
3525 info->perf_event.type = BPF_PERF_EVENT_URETPROBE;
3527 info->perf_event.type = BPF_PERF_EVENT_UPROBE;
3528 info->perf_event.uprobe.offset = offset;
3533 static int bpf_perf_link_fill_probe(const struct perf_event *event,
3534 struct bpf_link_info *info)
3536 #ifdef CONFIG_KPROBE_EVENTS
3537 if (event->tp_event->flags & TRACE_EVENT_FL_KPROBE)
3538 return bpf_perf_link_fill_kprobe(event, info);
3540 #ifdef CONFIG_UPROBE_EVENTS
3541 if (event->tp_event->flags & TRACE_EVENT_FL_UPROBE)
3542 return bpf_perf_link_fill_uprobe(event, info);
3547 static int bpf_perf_link_fill_tracepoint(const struct perf_event *event,
3548 struct bpf_link_info *info)
3553 uname = u64_to_user_ptr(info->perf_event.tracepoint.tp_name);
3554 ulen = info->perf_event.tracepoint.name_len;
3555 info->perf_event.type = BPF_PERF_EVENT_TRACEPOINT;
3556 return bpf_perf_link_fill_common(event, uname, ulen, NULL, NULL, NULL, NULL);
3559 static int bpf_perf_link_fill_perf_event(const struct perf_event *event,
3560 struct bpf_link_info *info)
3562 info->perf_event.event.type = event->attr.type;
3563 info->perf_event.event.config = event->attr.config;
3564 info->perf_event.type = BPF_PERF_EVENT_EVENT;
3568 static int bpf_perf_link_fill_link_info(const struct bpf_link *link,
3569 struct bpf_link_info *info)
3571 struct bpf_perf_link *perf_link;
3572 const struct perf_event *event;
3574 perf_link = container_of(link, struct bpf_perf_link, link);
3575 event = perf_get_event(perf_link->perf_file);
3577 return PTR_ERR(event);
3579 switch (event->prog->type) {
3580 case BPF_PROG_TYPE_PERF_EVENT:
3581 return bpf_perf_link_fill_perf_event(event, info);
3582 case BPF_PROG_TYPE_TRACEPOINT:
3583 return bpf_perf_link_fill_tracepoint(event, info);
3584 case BPF_PROG_TYPE_KPROBE:
3585 return bpf_perf_link_fill_probe(event, info);
3591 static const struct bpf_link_ops bpf_perf_link_lops = {
3592 .release = bpf_perf_link_release,
3593 .dealloc = bpf_perf_link_dealloc,
3594 .fill_link_info = bpf_perf_link_fill_link_info,
3597 static int bpf_perf_link_attach(const union bpf_attr *attr, struct bpf_prog *prog)
3599 struct bpf_link_primer link_primer;
3600 struct bpf_perf_link *link;
3601 struct perf_event *event;
3602 struct file *perf_file;
3605 if (attr->link_create.flags)
3608 perf_file = perf_event_get(attr->link_create.target_fd);
3609 if (IS_ERR(perf_file))
3610 return PTR_ERR(perf_file);
3612 link = kzalloc(sizeof(*link), GFP_USER);
3617 bpf_link_init(&link->link, BPF_LINK_TYPE_PERF_EVENT, &bpf_perf_link_lops, prog);
3618 link->perf_file = perf_file;
3620 err = bpf_link_prime(&link->link, &link_primer);
3626 event = perf_file->private_data;
3627 err = perf_event_set_bpf_prog(event, prog, attr->link_create.perf_event.bpf_cookie);
3629 bpf_link_cleanup(&link_primer);
3632 /* perf_event_set_bpf_prog() doesn't take its own refcnt on prog */
3635 return bpf_link_settle(&link_primer);
3642 static int bpf_perf_link_attach(const union bpf_attr *attr, struct bpf_prog *prog)
3646 #endif /* CONFIG_PERF_EVENTS */
3648 static int bpf_raw_tp_link_attach(struct bpf_prog *prog,
3649 const char __user *user_tp_name)
3651 struct bpf_link_primer link_primer;
3652 struct bpf_raw_tp_link *link;
3653 struct bpf_raw_event_map *btp;
3654 const char *tp_name;
3658 switch (prog->type) {
3659 case BPF_PROG_TYPE_TRACING:
3660 case BPF_PROG_TYPE_EXT:
3661 case BPF_PROG_TYPE_LSM:
3663 /* The attach point for this category of programs
3664 * should be specified via btf_id during program load.
3667 if (prog->type == BPF_PROG_TYPE_TRACING &&
3668 prog->expected_attach_type == BPF_TRACE_RAW_TP) {
3669 tp_name = prog->aux->attach_func_name;
3672 return bpf_tracing_prog_attach(prog, 0, 0, 0);
3673 case BPF_PROG_TYPE_RAW_TRACEPOINT:
3674 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
3675 if (strncpy_from_user(buf, user_tp_name, sizeof(buf) - 1) < 0)
3677 buf[sizeof(buf) - 1] = 0;
3684 btp = bpf_get_raw_tracepoint(tp_name);
3688 link = kzalloc(sizeof(*link), GFP_USER);
3693 bpf_link_init(&link->link, BPF_LINK_TYPE_RAW_TRACEPOINT,
3694 &bpf_raw_tp_link_lops, prog);
3697 err = bpf_link_prime(&link->link, &link_primer);
3703 err = bpf_probe_register(link->btp, prog);
3705 bpf_link_cleanup(&link_primer);
3709 return bpf_link_settle(&link_primer);
3712 bpf_put_raw_tracepoint(btp);
3716 #define BPF_RAW_TRACEPOINT_OPEN_LAST_FIELD raw_tracepoint.prog_fd
3718 static int bpf_raw_tracepoint_open(const union bpf_attr *attr)
3720 struct bpf_prog *prog;
3723 if (CHECK_ATTR(BPF_RAW_TRACEPOINT_OPEN))
3726 prog = bpf_prog_get(attr->raw_tracepoint.prog_fd);
3728 return PTR_ERR(prog);
3730 fd = bpf_raw_tp_link_attach(prog, u64_to_user_ptr(attr->raw_tracepoint.name));
3736 static enum bpf_prog_type
3737 attach_type_to_prog_type(enum bpf_attach_type attach_type)
3739 switch (attach_type) {
3740 case BPF_CGROUP_INET_INGRESS:
3741 case BPF_CGROUP_INET_EGRESS:
3742 return BPF_PROG_TYPE_CGROUP_SKB;
3743 case BPF_CGROUP_INET_SOCK_CREATE:
3744 case BPF_CGROUP_INET_SOCK_RELEASE:
3745 case BPF_CGROUP_INET4_POST_BIND:
3746 case BPF_CGROUP_INET6_POST_BIND:
3747 return BPF_PROG_TYPE_CGROUP_SOCK;
3748 case BPF_CGROUP_INET4_BIND:
3749 case BPF_CGROUP_INET6_BIND:
3750 case BPF_CGROUP_INET4_CONNECT:
3751 case BPF_CGROUP_INET6_CONNECT:
3752 case BPF_CGROUP_UNIX_CONNECT:
3753 case BPF_CGROUP_INET4_GETPEERNAME:
3754 case BPF_CGROUP_INET6_GETPEERNAME:
3755 case BPF_CGROUP_UNIX_GETPEERNAME:
3756 case BPF_CGROUP_INET4_GETSOCKNAME:
3757 case BPF_CGROUP_INET6_GETSOCKNAME:
3758 case BPF_CGROUP_UNIX_GETSOCKNAME:
3759 case BPF_CGROUP_UDP4_SENDMSG:
3760 case BPF_CGROUP_UDP6_SENDMSG:
3761 case BPF_CGROUP_UNIX_SENDMSG:
3762 case BPF_CGROUP_UDP4_RECVMSG:
3763 case BPF_CGROUP_UDP6_RECVMSG:
3764 case BPF_CGROUP_UNIX_RECVMSG:
3765 return BPF_PROG_TYPE_CGROUP_SOCK_ADDR;
3766 case BPF_CGROUP_SOCK_OPS:
3767 return BPF_PROG_TYPE_SOCK_OPS;
3768 case BPF_CGROUP_DEVICE:
3769 return BPF_PROG_TYPE_CGROUP_DEVICE;
3770 case BPF_SK_MSG_VERDICT:
3771 return BPF_PROG_TYPE_SK_MSG;
3772 case BPF_SK_SKB_STREAM_PARSER:
3773 case BPF_SK_SKB_STREAM_VERDICT:
3774 case BPF_SK_SKB_VERDICT:
3775 return BPF_PROG_TYPE_SK_SKB;
3776 case BPF_LIRC_MODE2:
3777 return BPF_PROG_TYPE_LIRC_MODE2;
3778 case BPF_FLOW_DISSECTOR:
3779 return BPF_PROG_TYPE_FLOW_DISSECTOR;
3780 case BPF_CGROUP_SYSCTL:
3781 return BPF_PROG_TYPE_CGROUP_SYSCTL;
3782 case BPF_CGROUP_GETSOCKOPT:
3783 case BPF_CGROUP_SETSOCKOPT:
3784 return BPF_PROG_TYPE_CGROUP_SOCKOPT;
3785 case BPF_TRACE_ITER:
3786 case BPF_TRACE_RAW_TP:
3787 case BPF_TRACE_FENTRY:
3788 case BPF_TRACE_FEXIT:
3789 case BPF_MODIFY_RETURN:
3790 return BPF_PROG_TYPE_TRACING;
3792 return BPF_PROG_TYPE_LSM;
3794 return BPF_PROG_TYPE_SK_LOOKUP;
3796 return BPF_PROG_TYPE_XDP;
3797 case BPF_LSM_CGROUP:
3798 return BPF_PROG_TYPE_LSM;
3799 case BPF_TCX_INGRESS:
3800 case BPF_TCX_EGRESS:
3801 case BPF_NETKIT_PRIMARY:
3802 case BPF_NETKIT_PEER:
3803 return BPF_PROG_TYPE_SCHED_CLS;
3805 return BPF_PROG_TYPE_UNSPEC;
3809 static int bpf_prog_attach_check_attach_type(const struct bpf_prog *prog,
3810 enum bpf_attach_type attach_type)
3812 enum bpf_prog_type ptype;
3814 switch (prog->type) {
3815 case BPF_PROG_TYPE_CGROUP_SOCK:
3816 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
3817 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3818 case BPF_PROG_TYPE_SK_LOOKUP:
3819 return attach_type == prog->expected_attach_type ? 0 : -EINVAL;
3820 case BPF_PROG_TYPE_CGROUP_SKB:
3821 if (!capable(CAP_NET_ADMIN))
3822 /* cg-skb progs can be loaded by unpriv user.
3823 * check permissions at attach time.
3826 return prog->enforce_expected_attach_type &&
3827 prog->expected_attach_type != attach_type ?
3829 case BPF_PROG_TYPE_EXT:
3831 case BPF_PROG_TYPE_NETFILTER:
3832 if (attach_type != BPF_NETFILTER)
3835 case BPF_PROG_TYPE_PERF_EVENT:
3836 case BPF_PROG_TYPE_TRACEPOINT:
3837 if (attach_type != BPF_PERF_EVENT)
3840 case BPF_PROG_TYPE_KPROBE:
3841 if (prog->expected_attach_type == BPF_TRACE_KPROBE_MULTI &&
3842 attach_type != BPF_TRACE_KPROBE_MULTI)
3844 if (prog->expected_attach_type == BPF_TRACE_UPROBE_MULTI &&
3845 attach_type != BPF_TRACE_UPROBE_MULTI)
3847 if (attach_type != BPF_PERF_EVENT &&
3848 attach_type != BPF_TRACE_KPROBE_MULTI &&
3849 attach_type != BPF_TRACE_UPROBE_MULTI)
3852 case BPF_PROG_TYPE_SCHED_CLS:
3853 if (attach_type != BPF_TCX_INGRESS &&
3854 attach_type != BPF_TCX_EGRESS &&
3855 attach_type != BPF_NETKIT_PRIMARY &&
3856 attach_type != BPF_NETKIT_PEER)
3860 ptype = attach_type_to_prog_type(attach_type);
3861 if (ptype == BPF_PROG_TYPE_UNSPEC || ptype != prog->type)
3867 #define BPF_PROG_ATTACH_LAST_FIELD expected_revision
3869 #define BPF_F_ATTACH_MASK_BASE \
3870 (BPF_F_ALLOW_OVERRIDE | \
3871 BPF_F_ALLOW_MULTI | \
3874 #define BPF_F_ATTACH_MASK_MPROG \
3881 static int bpf_prog_attach(const union bpf_attr *attr)
3883 enum bpf_prog_type ptype;
3884 struct bpf_prog *prog;
3887 if (CHECK_ATTR(BPF_PROG_ATTACH))
3890 ptype = attach_type_to_prog_type(attr->attach_type);
3891 if (ptype == BPF_PROG_TYPE_UNSPEC)
3893 if (bpf_mprog_supported(ptype)) {
3894 if (attr->attach_flags & ~BPF_F_ATTACH_MASK_MPROG)
3897 if (attr->attach_flags & ~BPF_F_ATTACH_MASK_BASE)
3899 if (attr->relative_fd ||
3900 attr->expected_revision)
3904 prog = bpf_prog_get_type(attr->attach_bpf_fd, ptype);
3906 return PTR_ERR(prog);
3908 if (bpf_prog_attach_check_attach_type(prog, attr->attach_type)) {
3914 case BPF_PROG_TYPE_SK_SKB:
3915 case BPF_PROG_TYPE_SK_MSG:
3916 ret = sock_map_get_from_fd(attr, prog);
3918 case BPF_PROG_TYPE_LIRC_MODE2:
3919 ret = lirc_prog_attach(attr, prog);
3921 case BPF_PROG_TYPE_FLOW_DISSECTOR:
3922 ret = netns_bpf_prog_attach(attr, prog);
3924 case BPF_PROG_TYPE_CGROUP_DEVICE:
3925 case BPF_PROG_TYPE_CGROUP_SKB:
3926 case BPF_PROG_TYPE_CGROUP_SOCK:
3927 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
3928 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3929 case BPF_PROG_TYPE_CGROUP_SYSCTL:
3930 case BPF_PROG_TYPE_SOCK_OPS:
3931 case BPF_PROG_TYPE_LSM:
3932 if (ptype == BPF_PROG_TYPE_LSM &&
3933 prog->expected_attach_type != BPF_LSM_CGROUP)
3936 ret = cgroup_bpf_prog_attach(attr, ptype, prog);
3938 case BPF_PROG_TYPE_SCHED_CLS:
3939 if (attr->attach_type == BPF_TCX_INGRESS ||
3940 attr->attach_type == BPF_TCX_EGRESS)
3941 ret = tcx_prog_attach(attr, prog);
3943 ret = netkit_prog_attach(attr, prog);
3954 #define BPF_PROG_DETACH_LAST_FIELD expected_revision
3956 static int bpf_prog_detach(const union bpf_attr *attr)
3958 struct bpf_prog *prog = NULL;
3959 enum bpf_prog_type ptype;
3962 if (CHECK_ATTR(BPF_PROG_DETACH))
3965 ptype = attach_type_to_prog_type(attr->attach_type);
3966 if (bpf_mprog_supported(ptype)) {
3967 if (ptype == BPF_PROG_TYPE_UNSPEC)
3969 if (attr->attach_flags & ~BPF_F_ATTACH_MASK_MPROG)
3971 if (attr->attach_bpf_fd) {
3972 prog = bpf_prog_get_type(attr->attach_bpf_fd, ptype);
3974 return PTR_ERR(prog);
3976 } else if (attr->attach_flags ||
3977 attr->relative_fd ||
3978 attr->expected_revision) {
3983 case BPF_PROG_TYPE_SK_MSG:
3984 case BPF_PROG_TYPE_SK_SKB:
3985 ret = sock_map_prog_detach(attr, ptype);
3987 case BPF_PROG_TYPE_LIRC_MODE2:
3988 ret = lirc_prog_detach(attr);
3990 case BPF_PROG_TYPE_FLOW_DISSECTOR:
3991 ret = netns_bpf_prog_detach(attr, ptype);
3993 case BPF_PROG_TYPE_CGROUP_DEVICE:
3994 case BPF_PROG_TYPE_CGROUP_SKB:
3995 case BPF_PROG_TYPE_CGROUP_SOCK:
3996 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
3997 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3998 case BPF_PROG_TYPE_CGROUP_SYSCTL:
3999 case BPF_PROG_TYPE_SOCK_OPS:
4000 case BPF_PROG_TYPE_LSM:
4001 ret = cgroup_bpf_prog_detach(attr, ptype);
4003 case BPF_PROG_TYPE_SCHED_CLS:
4004 if (attr->attach_type == BPF_TCX_INGRESS ||
4005 attr->attach_type == BPF_TCX_EGRESS)
4006 ret = tcx_prog_detach(attr, prog);
4008 ret = netkit_prog_detach(attr, prog);
4019 #define BPF_PROG_QUERY_LAST_FIELD query.revision
4021 static int bpf_prog_query(const union bpf_attr *attr,
4022 union bpf_attr __user *uattr)
4024 if (!capable(CAP_NET_ADMIN))
4026 if (CHECK_ATTR(BPF_PROG_QUERY))
4028 if (attr->query.query_flags & ~BPF_F_QUERY_EFFECTIVE)
4031 switch (attr->query.attach_type) {
4032 case BPF_CGROUP_INET_INGRESS:
4033 case BPF_CGROUP_INET_EGRESS:
4034 case BPF_CGROUP_INET_SOCK_CREATE:
4035 case BPF_CGROUP_INET_SOCK_RELEASE:
4036 case BPF_CGROUP_INET4_BIND:
4037 case BPF_CGROUP_INET6_BIND:
4038 case BPF_CGROUP_INET4_POST_BIND:
4039 case BPF_CGROUP_INET6_POST_BIND:
4040 case BPF_CGROUP_INET4_CONNECT:
4041 case BPF_CGROUP_INET6_CONNECT:
4042 case BPF_CGROUP_UNIX_CONNECT:
4043 case BPF_CGROUP_INET4_GETPEERNAME:
4044 case BPF_CGROUP_INET6_GETPEERNAME:
4045 case BPF_CGROUP_UNIX_GETPEERNAME:
4046 case BPF_CGROUP_INET4_GETSOCKNAME:
4047 case BPF_CGROUP_INET6_GETSOCKNAME:
4048 case BPF_CGROUP_UNIX_GETSOCKNAME:
4049 case BPF_CGROUP_UDP4_SENDMSG:
4050 case BPF_CGROUP_UDP6_SENDMSG:
4051 case BPF_CGROUP_UNIX_SENDMSG:
4052 case BPF_CGROUP_UDP4_RECVMSG:
4053 case BPF_CGROUP_UDP6_RECVMSG:
4054 case BPF_CGROUP_UNIX_RECVMSG:
4055 case BPF_CGROUP_SOCK_OPS:
4056 case BPF_CGROUP_DEVICE:
4057 case BPF_CGROUP_SYSCTL:
4058 case BPF_CGROUP_GETSOCKOPT:
4059 case BPF_CGROUP_SETSOCKOPT:
4060 case BPF_LSM_CGROUP:
4061 return cgroup_bpf_prog_query(attr, uattr);
4062 case BPF_LIRC_MODE2:
4063 return lirc_prog_query(attr, uattr);
4064 case BPF_FLOW_DISSECTOR:
4066 return netns_bpf_prog_query(attr, uattr);
4067 case BPF_SK_SKB_STREAM_PARSER:
4068 case BPF_SK_SKB_STREAM_VERDICT:
4069 case BPF_SK_MSG_VERDICT:
4070 case BPF_SK_SKB_VERDICT:
4071 return sock_map_bpf_prog_query(attr, uattr);
4072 case BPF_TCX_INGRESS:
4073 case BPF_TCX_EGRESS:
4074 return tcx_prog_query(attr, uattr);
4075 case BPF_NETKIT_PRIMARY:
4076 case BPF_NETKIT_PEER:
4077 return netkit_prog_query(attr, uattr);
4083 #define BPF_PROG_TEST_RUN_LAST_FIELD test.batch_size
4085 static int bpf_prog_test_run(const union bpf_attr *attr,
4086 union bpf_attr __user *uattr)
4088 struct bpf_prog *prog;
4089 int ret = -ENOTSUPP;
4091 if (CHECK_ATTR(BPF_PROG_TEST_RUN))
4094 if ((attr->test.ctx_size_in && !attr->test.ctx_in) ||
4095 (!attr->test.ctx_size_in && attr->test.ctx_in))
4098 if ((attr->test.ctx_size_out && !attr->test.ctx_out) ||
4099 (!attr->test.ctx_size_out && attr->test.ctx_out))
4102 prog = bpf_prog_get(attr->test.prog_fd);
4104 return PTR_ERR(prog);
4106 if (prog->aux->ops->test_run)
4107 ret = prog->aux->ops->test_run(prog, attr, uattr);
4113 #define BPF_OBJ_GET_NEXT_ID_LAST_FIELD next_id
4115 static int bpf_obj_get_next_id(const union bpf_attr *attr,
4116 union bpf_attr __user *uattr,
4120 u32 next_id = attr->start_id;
4123 if (CHECK_ATTR(BPF_OBJ_GET_NEXT_ID) || next_id >= INT_MAX)
4126 if (!capable(CAP_SYS_ADMIN))
4131 if (!idr_get_next(idr, &next_id))
4133 spin_unlock_bh(lock);
4136 err = put_user(next_id, &uattr->next_id);
4141 struct bpf_map *bpf_map_get_curr_or_next(u32 *id)
4143 struct bpf_map *map;
4145 spin_lock_bh(&map_idr_lock);
4147 map = idr_get_next(&map_idr, id);
4149 map = __bpf_map_inc_not_zero(map, false);
4155 spin_unlock_bh(&map_idr_lock);
4160 struct bpf_prog *bpf_prog_get_curr_or_next(u32 *id)
4162 struct bpf_prog *prog;
4164 spin_lock_bh(&prog_idr_lock);
4166 prog = idr_get_next(&prog_idr, id);
4168 prog = bpf_prog_inc_not_zero(prog);
4174 spin_unlock_bh(&prog_idr_lock);
4179 #define BPF_PROG_GET_FD_BY_ID_LAST_FIELD prog_id
4181 struct bpf_prog *bpf_prog_by_id(u32 id)
4183 struct bpf_prog *prog;
4186 return ERR_PTR(-ENOENT);
4188 spin_lock_bh(&prog_idr_lock);
4189 prog = idr_find(&prog_idr, id);
4191 prog = bpf_prog_inc_not_zero(prog);
4193 prog = ERR_PTR(-ENOENT);
4194 spin_unlock_bh(&prog_idr_lock);
4198 static int bpf_prog_get_fd_by_id(const union bpf_attr *attr)
4200 struct bpf_prog *prog;
4201 u32 id = attr->prog_id;
4204 if (CHECK_ATTR(BPF_PROG_GET_FD_BY_ID))
4207 if (!capable(CAP_SYS_ADMIN))
4210 prog = bpf_prog_by_id(id);
4212 return PTR_ERR(prog);
4214 fd = bpf_prog_new_fd(prog);
4221 #define BPF_MAP_GET_FD_BY_ID_LAST_FIELD open_flags
4223 static int bpf_map_get_fd_by_id(const union bpf_attr *attr)
4225 struct bpf_map *map;
4226 u32 id = attr->map_id;
4230 if (CHECK_ATTR(BPF_MAP_GET_FD_BY_ID) ||
4231 attr->open_flags & ~BPF_OBJ_FLAG_MASK)
4234 if (!capable(CAP_SYS_ADMIN))
4237 f_flags = bpf_get_file_flag(attr->open_flags);
4241 spin_lock_bh(&map_idr_lock);
4242 map = idr_find(&map_idr, id);
4244 map = __bpf_map_inc_not_zero(map, true);
4246 map = ERR_PTR(-ENOENT);
4247 spin_unlock_bh(&map_idr_lock);
4250 return PTR_ERR(map);
4252 fd = bpf_map_new_fd(map, f_flags);
4254 bpf_map_put_with_uref(map);
4259 static const struct bpf_map *bpf_map_from_imm(const struct bpf_prog *prog,
4260 unsigned long addr, u32 *off,
4263 const struct bpf_map *map;
4266 mutex_lock(&prog->aux->used_maps_mutex);
4267 for (i = 0, *off = 0; i < prog->aux->used_map_cnt; i++) {
4268 map = prog->aux->used_maps[i];
4269 if (map == (void *)addr) {
4270 *type = BPF_PSEUDO_MAP_FD;
4273 if (!map->ops->map_direct_value_meta)
4275 if (!map->ops->map_direct_value_meta(map, addr, off)) {
4276 *type = BPF_PSEUDO_MAP_VALUE;
4283 mutex_unlock(&prog->aux->used_maps_mutex);
4287 static struct bpf_insn *bpf_insn_prepare_dump(const struct bpf_prog *prog,
4288 const struct cred *f_cred)
4290 const struct bpf_map *map;
4291 struct bpf_insn *insns;
4297 insns = kmemdup(prog->insnsi, bpf_prog_insn_size(prog),
4302 for (i = 0; i < prog->len; i++) {
4303 code = insns[i].code;
4305 if (code == (BPF_JMP | BPF_TAIL_CALL)) {
4306 insns[i].code = BPF_JMP | BPF_CALL;
4307 insns[i].imm = BPF_FUNC_tail_call;
4310 if (code == (BPF_JMP | BPF_CALL) ||
4311 code == (BPF_JMP | BPF_CALL_ARGS)) {
4312 if (code == (BPF_JMP | BPF_CALL_ARGS))
4313 insns[i].code = BPF_JMP | BPF_CALL;
4314 if (!bpf_dump_raw_ok(f_cred))
4318 if (BPF_CLASS(code) == BPF_LDX && BPF_MODE(code) == BPF_PROBE_MEM) {
4319 insns[i].code = BPF_LDX | BPF_SIZE(code) | BPF_MEM;
4323 if (code != (BPF_LD | BPF_IMM | BPF_DW))
4326 imm = ((u64)insns[i + 1].imm << 32) | (u32)insns[i].imm;
4327 map = bpf_map_from_imm(prog, imm, &off, &type);
4329 insns[i].src_reg = type;
4330 insns[i].imm = map->id;
4331 insns[i + 1].imm = off;
4339 static int set_info_rec_size(struct bpf_prog_info *info)
4342 * Ensure info.*_rec_size is the same as kernel expected size
4346 * Only allow zero *_rec_size if both _rec_size and _cnt are
4347 * zero. In this case, the kernel will set the expected
4348 * _rec_size back to the info.
4351 if ((info->nr_func_info || info->func_info_rec_size) &&
4352 info->func_info_rec_size != sizeof(struct bpf_func_info))
4355 if ((info->nr_line_info || info->line_info_rec_size) &&
4356 info->line_info_rec_size != sizeof(struct bpf_line_info))
4359 if ((info->nr_jited_line_info || info->jited_line_info_rec_size) &&
4360 info->jited_line_info_rec_size != sizeof(__u64))
4363 info->func_info_rec_size = sizeof(struct bpf_func_info);
4364 info->line_info_rec_size = sizeof(struct bpf_line_info);
4365 info->jited_line_info_rec_size = sizeof(__u64);
4370 static int bpf_prog_get_info_by_fd(struct file *file,
4371 struct bpf_prog *prog,
4372 const union bpf_attr *attr,
4373 union bpf_attr __user *uattr)
4375 struct bpf_prog_info __user *uinfo = u64_to_user_ptr(attr->info.info);
4376 struct btf *attach_btf = bpf_prog_get_target_btf(prog);
4377 struct bpf_prog_info info;
4378 u32 info_len = attr->info.info_len;
4379 struct bpf_prog_kstats stats;
4380 char __user *uinsns;
4384 err = bpf_check_uarg_tail_zero(USER_BPFPTR(uinfo), sizeof(info), info_len);
4387 info_len = min_t(u32, sizeof(info), info_len);
4389 memset(&info, 0, sizeof(info));
4390 if (copy_from_user(&info, uinfo, info_len))
4393 info.type = prog->type;
4394 info.id = prog->aux->id;
4395 info.load_time = prog->aux->load_time;
4396 info.created_by_uid = from_kuid_munged(current_user_ns(),
4397 prog->aux->user->uid);
4398 info.gpl_compatible = prog->gpl_compatible;
4400 memcpy(info.tag, prog->tag, sizeof(prog->tag));
4401 memcpy(info.name, prog->aux->name, sizeof(prog->aux->name));
4403 mutex_lock(&prog->aux->used_maps_mutex);
4404 ulen = info.nr_map_ids;
4405 info.nr_map_ids = prog->aux->used_map_cnt;
4406 ulen = min_t(u32, info.nr_map_ids, ulen);
4408 u32 __user *user_map_ids = u64_to_user_ptr(info.map_ids);
4411 for (i = 0; i < ulen; i++)
4412 if (put_user(prog->aux->used_maps[i]->id,
4413 &user_map_ids[i])) {
4414 mutex_unlock(&prog->aux->used_maps_mutex);
4418 mutex_unlock(&prog->aux->used_maps_mutex);
4420 err = set_info_rec_size(&info);
4424 bpf_prog_get_stats(prog, &stats);
4425 info.run_time_ns = stats.nsecs;
4426 info.run_cnt = stats.cnt;
4427 info.recursion_misses = stats.misses;
4429 info.verified_insns = prog->aux->verified_insns;
4431 if (!bpf_capable()) {
4432 info.jited_prog_len = 0;
4433 info.xlated_prog_len = 0;
4434 info.nr_jited_ksyms = 0;
4435 info.nr_jited_func_lens = 0;
4436 info.nr_func_info = 0;
4437 info.nr_line_info = 0;
4438 info.nr_jited_line_info = 0;
4442 ulen = info.xlated_prog_len;
4443 info.xlated_prog_len = bpf_prog_insn_size(prog);
4444 if (info.xlated_prog_len && ulen) {
4445 struct bpf_insn *insns_sanitized;
4448 if (prog->blinded && !bpf_dump_raw_ok(file->f_cred)) {
4449 info.xlated_prog_insns = 0;
4452 insns_sanitized = bpf_insn_prepare_dump(prog, file->f_cred);
4453 if (!insns_sanitized)
4455 uinsns = u64_to_user_ptr(info.xlated_prog_insns);
4456 ulen = min_t(u32, info.xlated_prog_len, ulen);
4457 fault = copy_to_user(uinsns, insns_sanitized, ulen);
4458 kfree(insns_sanitized);
4463 if (bpf_prog_is_offloaded(prog->aux)) {
4464 err = bpf_prog_offload_info_fill(&info, prog);
4470 /* NOTE: the following code is supposed to be skipped for offload.
4471 * bpf_prog_offload_info_fill() is the place to fill similar fields
4474 ulen = info.jited_prog_len;
4475 if (prog->aux->func_cnt) {
4478 info.jited_prog_len = 0;
4479 for (i = 0; i < prog->aux->func_cnt; i++)
4480 info.jited_prog_len += prog->aux->func[i]->jited_len;
4482 info.jited_prog_len = prog->jited_len;
4485 if (info.jited_prog_len && ulen) {
4486 if (bpf_dump_raw_ok(file->f_cred)) {
4487 uinsns = u64_to_user_ptr(info.jited_prog_insns);
4488 ulen = min_t(u32, info.jited_prog_len, ulen);
4490 /* for multi-function programs, copy the JITed
4491 * instructions for all the functions
4493 if (prog->aux->func_cnt) {
4498 for (i = 0; i < prog->aux->func_cnt; i++) {
4499 len = prog->aux->func[i]->jited_len;
4500 len = min_t(u32, len, free);
4501 img = (u8 *) prog->aux->func[i]->bpf_func;
4502 if (copy_to_user(uinsns, img, len))
4510 if (copy_to_user(uinsns, prog->bpf_func, ulen))
4514 info.jited_prog_insns = 0;
4518 ulen = info.nr_jited_ksyms;
4519 info.nr_jited_ksyms = prog->aux->func_cnt ? : 1;
4521 if (bpf_dump_raw_ok(file->f_cred)) {
4522 unsigned long ksym_addr;
4523 u64 __user *user_ksyms;
4526 /* copy the address of the kernel symbol
4527 * corresponding to each function
4529 ulen = min_t(u32, info.nr_jited_ksyms, ulen);
4530 user_ksyms = u64_to_user_ptr(info.jited_ksyms);
4531 if (prog->aux->func_cnt) {
4532 for (i = 0; i < ulen; i++) {
4533 ksym_addr = (unsigned long)
4534 prog->aux->func[i]->bpf_func;
4535 if (put_user((u64) ksym_addr,
4540 ksym_addr = (unsigned long) prog->bpf_func;
4541 if (put_user((u64) ksym_addr, &user_ksyms[0]))
4545 info.jited_ksyms = 0;
4549 ulen = info.nr_jited_func_lens;
4550 info.nr_jited_func_lens = prog->aux->func_cnt ? : 1;
4552 if (bpf_dump_raw_ok(file->f_cred)) {
4553 u32 __user *user_lens;
4556 /* copy the JITed image lengths for each function */
4557 ulen = min_t(u32, info.nr_jited_func_lens, ulen);
4558 user_lens = u64_to_user_ptr(info.jited_func_lens);
4559 if (prog->aux->func_cnt) {
4560 for (i = 0; i < ulen; i++) {
4562 prog->aux->func[i]->jited_len;
4563 if (put_user(func_len, &user_lens[i]))
4567 func_len = prog->jited_len;
4568 if (put_user(func_len, &user_lens[0]))
4572 info.jited_func_lens = 0;
4577 info.btf_id = btf_obj_id(prog->aux->btf);
4578 info.attach_btf_id = prog->aux->attach_btf_id;
4580 info.attach_btf_obj_id = btf_obj_id(attach_btf);
4582 ulen = info.nr_func_info;
4583 info.nr_func_info = prog->aux->func_info_cnt;
4584 if (info.nr_func_info && ulen) {
4585 char __user *user_finfo;
4587 user_finfo = u64_to_user_ptr(info.func_info);
4588 ulen = min_t(u32, info.nr_func_info, ulen);
4589 if (copy_to_user(user_finfo, prog->aux->func_info,
4590 info.func_info_rec_size * ulen))
4594 ulen = info.nr_line_info;
4595 info.nr_line_info = prog->aux->nr_linfo;
4596 if (info.nr_line_info && ulen) {
4597 __u8 __user *user_linfo;
4599 user_linfo = u64_to_user_ptr(info.line_info);
4600 ulen = min_t(u32, info.nr_line_info, ulen);
4601 if (copy_to_user(user_linfo, prog->aux->linfo,
4602 info.line_info_rec_size * ulen))
4606 ulen = info.nr_jited_line_info;
4607 if (prog->aux->jited_linfo)
4608 info.nr_jited_line_info = prog->aux->nr_linfo;
4610 info.nr_jited_line_info = 0;
4611 if (info.nr_jited_line_info && ulen) {
4612 if (bpf_dump_raw_ok(file->f_cred)) {
4613 unsigned long line_addr;
4614 __u64 __user *user_linfo;
4617 user_linfo = u64_to_user_ptr(info.jited_line_info);
4618 ulen = min_t(u32, info.nr_jited_line_info, ulen);
4619 for (i = 0; i < ulen; i++) {
4620 line_addr = (unsigned long)prog->aux->jited_linfo[i];
4621 if (put_user((__u64)line_addr, &user_linfo[i]))
4625 info.jited_line_info = 0;
4629 ulen = info.nr_prog_tags;
4630 info.nr_prog_tags = prog->aux->func_cnt ? : 1;
4632 __u8 __user (*user_prog_tags)[BPF_TAG_SIZE];
4635 user_prog_tags = u64_to_user_ptr(info.prog_tags);
4636 ulen = min_t(u32, info.nr_prog_tags, ulen);
4637 if (prog->aux->func_cnt) {
4638 for (i = 0; i < ulen; i++) {
4639 if (copy_to_user(user_prog_tags[i],
4640 prog->aux->func[i]->tag,
4645 if (copy_to_user(user_prog_tags[0],
4646 prog->tag, BPF_TAG_SIZE))
4652 if (copy_to_user(uinfo, &info, info_len) ||
4653 put_user(info_len, &uattr->info.info_len))
4659 static int bpf_map_get_info_by_fd(struct file *file,
4660 struct bpf_map *map,
4661 const union bpf_attr *attr,
4662 union bpf_attr __user *uattr)
4664 struct bpf_map_info __user *uinfo = u64_to_user_ptr(attr->info.info);
4665 struct bpf_map_info info;
4666 u32 info_len = attr->info.info_len;
4669 err = bpf_check_uarg_tail_zero(USER_BPFPTR(uinfo), sizeof(info), info_len);
4672 info_len = min_t(u32, sizeof(info), info_len);
4674 memset(&info, 0, sizeof(info));
4675 info.type = map->map_type;
4677 info.key_size = map->key_size;
4678 info.value_size = map->value_size;
4679 info.max_entries = map->max_entries;
4680 info.map_flags = map->map_flags;
4681 info.map_extra = map->map_extra;
4682 memcpy(info.name, map->name, sizeof(map->name));
4685 info.btf_id = btf_obj_id(map->btf);
4686 info.btf_key_type_id = map->btf_key_type_id;
4687 info.btf_value_type_id = map->btf_value_type_id;
4689 info.btf_vmlinux_value_type_id = map->btf_vmlinux_value_type_id;
4691 if (bpf_map_is_offloaded(map)) {
4692 err = bpf_map_offload_info_fill(&info, map);
4697 if (copy_to_user(uinfo, &info, info_len) ||
4698 put_user(info_len, &uattr->info.info_len))
4704 static int bpf_btf_get_info_by_fd(struct file *file,
4706 const union bpf_attr *attr,
4707 union bpf_attr __user *uattr)
4709 struct bpf_btf_info __user *uinfo = u64_to_user_ptr(attr->info.info);
4710 u32 info_len = attr->info.info_len;
4713 err = bpf_check_uarg_tail_zero(USER_BPFPTR(uinfo), sizeof(*uinfo), info_len);
4717 return btf_get_info_by_fd(btf, attr, uattr);
4720 static int bpf_link_get_info_by_fd(struct file *file,
4721 struct bpf_link *link,
4722 const union bpf_attr *attr,
4723 union bpf_attr __user *uattr)
4725 struct bpf_link_info __user *uinfo = u64_to_user_ptr(attr->info.info);
4726 struct bpf_link_info info;
4727 u32 info_len = attr->info.info_len;
4730 err = bpf_check_uarg_tail_zero(USER_BPFPTR(uinfo), sizeof(info), info_len);
4733 info_len = min_t(u32, sizeof(info), info_len);
4735 memset(&info, 0, sizeof(info));
4736 if (copy_from_user(&info, uinfo, info_len))
4739 info.type = link->type;
4742 info.prog_id = link->prog->aux->id;
4744 if (link->ops->fill_link_info) {
4745 err = link->ops->fill_link_info(link, &info);
4750 if (copy_to_user(uinfo, &info, info_len) ||
4751 put_user(info_len, &uattr->info.info_len))
4758 #define BPF_OBJ_GET_INFO_BY_FD_LAST_FIELD info.info
4760 static int bpf_obj_get_info_by_fd(const union bpf_attr *attr,
4761 union bpf_attr __user *uattr)
4763 int ufd = attr->info.bpf_fd;
4767 if (CHECK_ATTR(BPF_OBJ_GET_INFO_BY_FD))
4774 if (f.file->f_op == &bpf_prog_fops)
4775 err = bpf_prog_get_info_by_fd(f.file, f.file->private_data, attr,
4777 else if (f.file->f_op == &bpf_map_fops)
4778 err = bpf_map_get_info_by_fd(f.file, f.file->private_data, attr,
4780 else if (f.file->f_op == &btf_fops)
4781 err = bpf_btf_get_info_by_fd(f.file, f.file->private_data, attr, uattr);
4782 else if (f.file->f_op == &bpf_link_fops)
4783 err = bpf_link_get_info_by_fd(f.file, f.file->private_data,
4792 #define BPF_BTF_LOAD_LAST_FIELD btf_log_true_size
4794 static int bpf_btf_load(const union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size)
4796 if (CHECK_ATTR(BPF_BTF_LOAD))
4802 return btf_new_fd(attr, uattr, uattr_size);
4805 #define BPF_BTF_GET_FD_BY_ID_LAST_FIELD btf_id
4807 static int bpf_btf_get_fd_by_id(const union bpf_attr *attr)
4809 if (CHECK_ATTR(BPF_BTF_GET_FD_BY_ID))
4812 if (!capable(CAP_SYS_ADMIN))
4815 return btf_get_fd_by_id(attr->btf_id);
4818 static int bpf_task_fd_query_copy(const union bpf_attr *attr,
4819 union bpf_attr __user *uattr,
4820 u32 prog_id, u32 fd_type,
4821 const char *buf, u64 probe_offset,
4824 char __user *ubuf = u64_to_user_ptr(attr->task_fd_query.buf);
4825 u32 len = buf ? strlen(buf) : 0, input_len;
4828 if (put_user(len, &uattr->task_fd_query.buf_len))
4830 input_len = attr->task_fd_query.buf_len;
4831 if (input_len && ubuf) {
4833 /* nothing to copy, just make ubuf NULL terminated */
4836 if (put_user(zero, ubuf))
4838 } else if (input_len >= len + 1) {
4839 /* ubuf can hold the string with NULL terminator */
4840 if (copy_to_user(ubuf, buf, len + 1))
4843 /* ubuf cannot hold the string with NULL terminator,
4844 * do a partial copy with NULL terminator.
4849 if (copy_to_user(ubuf, buf, input_len - 1))
4851 if (put_user(zero, ubuf + input_len - 1))
4856 if (put_user(prog_id, &uattr->task_fd_query.prog_id) ||
4857 put_user(fd_type, &uattr->task_fd_query.fd_type) ||
4858 put_user(probe_offset, &uattr->task_fd_query.probe_offset) ||
4859 put_user(probe_addr, &uattr->task_fd_query.probe_addr))
4865 #define BPF_TASK_FD_QUERY_LAST_FIELD task_fd_query.probe_addr
4867 static int bpf_task_fd_query(const union bpf_attr *attr,
4868 union bpf_attr __user *uattr)
4870 pid_t pid = attr->task_fd_query.pid;
4871 u32 fd = attr->task_fd_query.fd;
4872 const struct perf_event *event;
4873 struct task_struct *task;
4877 if (CHECK_ATTR(BPF_TASK_FD_QUERY))
4880 if (!capable(CAP_SYS_ADMIN))
4883 if (attr->task_fd_query.flags != 0)
4887 task = get_pid_task(find_vpid(pid), PIDTYPE_PID);
4893 file = fget_task(task, fd);
4894 put_task_struct(task);
4898 if (file->f_op == &bpf_link_fops) {
4899 struct bpf_link *link = file->private_data;
4901 if (link->ops == &bpf_raw_tp_link_lops) {
4902 struct bpf_raw_tp_link *raw_tp =
4903 container_of(link, struct bpf_raw_tp_link, link);
4904 struct bpf_raw_event_map *btp = raw_tp->btp;
4906 err = bpf_task_fd_query_copy(attr, uattr,
4907 raw_tp->link.prog->aux->id,
4908 BPF_FD_TYPE_RAW_TRACEPOINT,
4909 btp->tp->name, 0, 0);
4915 event = perf_get_event(file);
4916 if (!IS_ERR(event)) {
4917 u64 probe_offset, probe_addr;
4918 u32 prog_id, fd_type;
4921 err = bpf_get_perf_event_info(event, &prog_id, &fd_type,
4922 &buf, &probe_offset,
4925 err = bpf_task_fd_query_copy(attr, uattr, prog_id,
4939 #define BPF_MAP_BATCH_LAST_FIELD batch.flags
4941 #define BPF_DO_BATCH(fn, ...) \
4947 err = fn(__VA_ARGS__); \
4950 static int bpf_map_do_batch(const union bpf_attr *attr,
4951 union bpf_attr __user *uattr,
4954 bool has_read = cmd == BPF_MAP_LOOKUP_BATCH ||
4955 cmd == BPF_MAP_LOOKUP_AND_DELETE_BATCH;
4956 bool has_write = cmd != BPF_MAP_LOOKUP_BATCH;
4957 struct bpf_map *map;
4961 if (CHECK_ATTR(BPF_MAP_BATCH))
4964 ufd = attr->batch.map_fd;
4966 map = __bpf_map_get(f);
4968 return PTR_ERR(map);
4970 bpf_map_write_active_inc(map);
4971 if (has_read && !(map_get_sys_perms(map, f) & FMODE_CAN_READ)) {
4975 if (has_write && !(map_get_sys_perms(map, f) & FMODE_CAN_WRITE)) {
4980 if (cmd == BPF_MAP_LOOKUP_BATCH)
4981 BPF_DO_BATCH(map->ops->map_lookup_batch, map, attr, uattr);
4982 else if (cmd == BPF_MAP_LOOKUP_AND_DELETE_BATCH)
4983 BPF_DO_BATCH(map->ops->map_lookup_and_delete_batch, map, attr, uattr);
4984 else if (cmd == BPF_MAP_UPDATE_BATCH)
4985 BPF_DO_BATCH(map->ops->map_update_batch, map, f.file, attr, uattr);
4987 BPF_DO_BATCH(map->ops->map_delete_batch, map, attr, uattr);
4990 maybe_wait_bpf_programs(map);
4991 bpf_map_write_active_dec(map);
4997 #define BPF_LINK_CREATE_LAST_FIELD link_create.uprobe_multi.pid
4998 static int link_create(union bpf_attr *attr, bpfptr_t uattr)
5000 struct bpf_prog *prog;
5003 if (CHECK_ATTR(BPF_LINK_CREATE))
5006 if (attr->link_create.attach_type == BPF_STRUCT_OPS)
5007 return bpf_struct_ops_link_create(attr);
5009 prog = bpf_prog_get(attr->link_create.prog_fd);
5011 return PTR_ERR(prog);
5013 ret = bpf_prog_attach_check_attach_type(prog,
5014 attr->link_create.attach_type);
5018 switch (prog->type) {
5019 case BPF_PROG_TYPE_CGROUP_SKB:
5020 case BPF_PROG_TYPE_CGROUP_SOCK:
5021 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
5022 case BPF_PROG_TYPE_SOCK_OPS:
5023 case BPF_PROG_TYPE_CGROUP_DEVICE:
5024 case BPF_PROG_TYPE_CGROUP_SYSCTL:
5025 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
5026 ret = cgroup_bpf_link_attach(attr, prog);
5028 case BPF_PROG_TYPE_EXT:
5029 ret = bpf_tracing_prog_attach(prog,
5030 attr->link_create.target_fd,
5031 attr->link_create.target_btf_id,
5032 attr->link_create.tracing.cookie);
5034 case BPF_PROG_TYPE_LSM:
5035 case BPF_PROG_TYPE_TRACING:
5036 if (attr->link_create.attach_type != prog->expected_attach_type) {
5040 if (prog->expected_attach_type == BPF_TRACE_RAW_TP)
5041 ret = bpf_raw_tp_link_attach(prog, NULL);
5042 else if (prog->expected_attach_type == BPF_TRACE_ITER)
5043 ret = bpf_iter_link_attach(attr, uattr, prog);
5044 else if (prog->expected_attach_type == BPF_LSM_CGROUP)
5045 ret = cgroup_bpf_link_attach(attr, prog);
5047 ret = bpf_tracing_prog_attach(prog,
5048 attr->link_create.target_fd,
5049 attr->link_create.target_btf_id,
5050 attr->link_create.tracing.cookie);
5052 case BPF_PROG_TYPE_FLOW_DISSECTOR:
5053 case BPF_PROG_TYPE_SK_LOOKUP:
5054 ret = netns_bpf_link_create(attr, prog);
5057 case BPF_PROG_TYPE_XDP:
5058 ret = bpf_xdp_link_attach(attr, prog);
5060 case BPF_PROG_TYPE_SCHED_CLS:
5061 if (attr->link_create.attach_type == BPF_TCX_INGRESS ||
5062 attr->link_create.attach_type == BPF_TCX_EGRESS)
5063 ret = tcx_link_attach(attr, prog);
5065 ret = netkit_link_attach(attr, prog);
5067 case BPF_PROG_TYPE_NETFILTER:
5068 ret = bpf_nf_link_attach(attr, prog);
5071 case BPF_PROG_TYPE_PERF_EVENT:
5072 case BPF_PROG_TYPE_TRACEPOINT:
5073 ret = bpf_perf_link_attach(attr, prog);
5075 case BPF_PROG_TYPE_KPROBE:
5076 if (attr->link_create.attach_type == BPF_PERF_EVENT)
5077 ret = bpf_perf_link_attach(attr, prog);
5078 else if (attr->link_create.attach_type == BPF_TRACE_KPROBE_MULTI)
5079 ret = bpf_kprobe_multi_link_attach(attr, prog);
5080 else if (attr->link_create.attach_type == BPF_TRACE_UPROBE_MULTI)
5081 ret = bpf_uprobe_multi_link_attach(attr, prog);
5093 static int link_update_map(struct bpf_link *link, union bpf_attr *attr)
5095 struct bpf_map *new_map, *old_map = NULL;
5098 new_map = bpf_map_get(attr->link_update.new_map_fd);
5099 if (IS_ERR(new_map))
5100 return PTR_ERR(new_map);
5102 if (attr->link_update.flags & BPF_F_REPLACE) {
5103 old_map = bpf_map_get(attr->link_update.old_map_fd);
5104 if (IS_ERR(old_map)) {
5105 ret = PTR_ERR(old_map);
5108 } else if (attr->link_update.old_map_fd) {
5113 ret = link->ops->update_map(link, new_map, old_map);
5116 bpf_map_put(old_map);
5118 bpf_map_put(new_map);
5122 #define BPF_LINK_UPDATE_LAST_FIELD link_update.old_prog_fd
5124 static int link_update(union bpf_attr *attr)
5126 struct bpf_prog *old_prog = NULL, *new_prog;
5127 struct bpf_link *link;
5131 if (CHECK_ATTR(BPF_LINK_UPDATE))
5134 flags = attr->link_update.flags;
5135 if (flags & ~BPF_F_REPLACE)
5138 link = bpf_link_get_from_fd(attr->link_update.link_fd);
5140 return PTR_ERR(link);
5142 if (link->ops->update_map) {
5143 ret = link_update_map(link, attr);
5147 new_prog = bpf_prog_get(attr->link_update.new_prog_fd);
5148 if (IS_ERR(new_prog)) {
5149 ret = PTR_ERR(new_prog);
5153 if (flags & BPF_F_REPLACE) {
5154 old_prog = bpf_prog_get(attr->link_update.old_prog_fd);
5155 if (IS_ERR(old_prog)) {
5156 ret = PTR_ERR(old_prog);
5160 } else if (attr->link_update.old_prog_fd) {
5165 if (link->ops->update_prog)
5166 ret = link->ops->update_prog(link, new_prog, old_prog);
5172 bpf_prog_put(old_prog);
5174 bpf_prog_put(new_prog);
5176 bpf_link_put_direct(link);
5180 #define BPF_LINK_DETACH_LAST_FIELD link_detach.link_fd
5182 static int link_detach(union bpf_attr *attr)
5184 struct bpf_link *link;
5187 if (CHECK_ATTR(BPF_LINK_DETACH))
5190 link = bpf_link_get_from_fd(attr->link_detach.link_fd);
5192 return PTR_ERR(link);
5194 if (link->ops->detach)
5195 ret = link->ops->detach(link);
5199 bpf_link_put_direct(link);
5203 static struct bpf_link *bpf_link_inc_not_zero(struct bpf_link *link)
5205 return atomic64_fetch_add_unless(&link->refcnt, 1, 0) ? link : ERR_PTR(-ENOENT);
5208 struct bpf_link *bpf_link_by_id(u32 id)
5210 struct bpf_link *link;
5213 return ERR_PTR(-ENOENT);
5215 spin_lock_bh(&link_idr_lock);
5216 /* before link is "settled", ID is 0, pretend it doesn't exist yet */
5217 link = idr_find(&link_idr, id);
5220 link = bpf_link_inc_not_zero(link);
5222 link = ERR_PTR(-EAGAIN);
5224 link = ERR_PTR(-ENOENT);
5226 spin_unlock_bh(&link_idr_lock);
5230 struct bpf_link *bpf_link_get_curr_or_next(u32 *id)
5232 struct bpf_link *link;
5234 spin_lock_bh(&link_idr_lock);
5236 link = idr_get_next(&link_idr, id);
5238 link = bpf_link_inc_not_zero(link);
5244 spin_unlock_bh(&link_idr_lock);
5249 #define BPF_LINK_GET_FD_BY_ID_LAST_FIELD link_id
5251 static int bpf_link_get_fd_by_id(const union bpf_attr *attr)
5253 struct bpf_link *link;
5254 u32 id = attr->link_id;
5257 if (CHECK_ATTR(BPF_LINK_GET_FD_BY_ID))
5260 if (!capable(CAP_SYS_ADMIN))
5263 link = bpf_link_by_id(id);
5265 return PTR_ERR(link);
5267 fd = bpf_link_new_fd(link);
5269 bpf_link_put_direct(link);
5274 DEFINE_MUTEX(bpf_stats_enabled_mutex);
5276 static int bpf_stats_release(struct inode *inode, struct file *file)
5278 mutex_lock(&bpf_stats_enabled_mutex);
5279 static_key_slow_dec(&bpf_stats_enabled_key.key);
5280 mutex_unlock(&bpf_stats_enabled_mutex);
5284 static const struct file_operations bpf_stats_fops = {
5285 .release = bpf_stats_release,
5288 static int bpf_enable_runtime_stats(void)
5292 mutex_lock(&bpf_stats_enabled_mutex);
5294 /* Set a very high limit to avoid overflow */
5295 if (static_key_count(&bpf_stats_enabled_key.key) > INT_MAX / 2) {
5296 mutex_unlock(&bpf_stats_enabled_mutex);
5300 fd = anon_inode_getfd("bpf-stats", &bpf_stats_fops, NULL, O_CLOEXEC);
5302 static_key_slow_inc(&bpf_stats_enabled_key.key);
5304 mutex_unlock(&bpf_stats_enabled_mutex);
5308 #define BPF_ENABLE_STATS_LAST_FIELD enable_stats.type
5310 static int bpf_enable_stats(union bpf_attr *attr)
5313 if (CHECK_ATTR(BPF_ENABLE_STATS))
5316 if (!capable(CAP_SYS_ADMIN))
5319 switch (attr->enable_stats.type) {
5320 case BPF_STATS_RUN_TIME:
5321 return bpf_enable_runtime_stats();
5328 #define BPF_ITER_CREATE_LAST_FIELD iter_create.flags
5330 static int bpf_iter_create(union bpf_attr *attr)
5332 struct bpf_link *link;
5335 if (CHECK_ATTR(BPF_ITER_CREATE))
5338 if (attr->iter_create.flags)
5341 link = bpf_link_get_from_fd(attr->iter_create.link_fd);
5343 return PTR_ERR(link);
5345 err = bpf_iter_new_fd(link);
5346 bpf_link_put_direct(link);
5351 #define BPF_PROG_BIND_MAP_LAST_FIELD prog_bind_map.flags
5353 static int bpf_prog_bind_map(union bpf_attr *attr)
5355 struct bpf_prog *prog;
5356 struct bpf_map *map;
5357 struct bpf_map **used_maps_old, **used_maps_new;
5360 if (CHECK_ATTR(BPF_PROG_BIND_MAP))
5363 if (attr->prog_bind_map.flags)
5366 prog = bpf_prog_get(attr->prog_bind_map.prog_fd);
5368 return PTR_ERR(prog);
5370 map = bpf_map_get(attr->prog_bind_map.map_fd);
5376 mutex_lock(&prog->aux->used_maps_mutex);
5378 used_maps_old = prog->aux->used_maps;
5380 for (i = 0; i < prog->aux->used_map_cnt; i++)
5381 if (used_maps_old[i] == map) {
5386 used_maps_new = kmalloc_array(prog->aux->used_map_cnt + 1,
5387 sizeof(used_maps_new[0]),
5389 if (!used_maps_new) {
5394 /* The bpf program will not access the bpf map, but for the sake of
5395 * simplicity, increase sleepable_refcnt for sleepable program as well.
5397 if (prog->aux->sleepable)
5398 atomic64_inc(&map->sleepable_refcnt);
5399 memcpy(used_maps_new, used_maps_old,
5400 sizeof(used_maps_old[0]) * prog->aux->used_map_cnt);
5401 used_maps_new[prog->aux->used_map_cnt] = map;
5403 prog->aux->used_map_cnt++;
5404 prog->aux->used_maps = used_maps_new;
5406 kfree(used_maps_old);
5409 mutex_unlock(&prog->aux->used_maps_mutex);
5418 static int __sys_bpf(int cmd, bpfptr_t uattr, unsigned int size)
5420 union bpf_attr attr;
5423 err = bpf_check_uarg_tail_zero(uattr, sizeof(attr), size);
5426 size = min_t(u32, size, sizeof(attr));
5428 /* copy attributes from user space, may be less than sizeof(bpf_attr) */
5429 memset(&attr, 0, sizeof(attr));
5430 if (copy_from_bpfptr(&attr, uattr, size) != 0)
5433 err = security_bpf(cmd, &attr, size);
5438 case BPF_MAP_CREATE:
5439 err = map_create(&attr);
5441 case BPF_MAP_LOOKUP_ELEM:
5442 err = map_lookup_elem(&attr);
5444 case BPF_MAP_UPDATE_ELEM:
5445 err = map_update_elem(&attr, uattr);
5447 case BPF_MAP_DELETE_ELEM:
5448 err = map_delete_elem(&attr, uattr);
5450 case BPF_MAP_GET_NEXT_KEY:
5451 err = map_get_next_key(&attr);
5453 case BPF_MAP_FREEZE:
5454 err = map_freeze(&attr);
5457 err = bpf_prog_load(&attr, uattr, size);
5460 err = bpf_obj_pin(&attr);
5463 err = bpf_obj_get(&attr);
5465 case BPF_PROG_ATTACH:
5466 err = bpf_prog_attach(&attr);
5468 case BPF_PROG_DETACH:
5469 err = bpf_prog_detach(&attr);
5471 case BPF_PROG_QUERY:
5472 err = bpf_prog_query(&attr, uattr.user);
5474 case BPF_PROG_TEST_RUN:
5475 err = bpf_prog_test_run(&attr, uattr.user);
5477 case BPF_PROG_GET_NEXT_ID:
5478 err = bpf_obj_get_next_id(&attr, uattr.user,
5479 &prog_idr, &prog_idr_lock);
5481 case BPF_MAP_GET_NEXT_ID:
5482 err = bpf_obj_get_next_id(&attr, uattr.user,
5483 &map_idr, &map_idr_lock);
5485 case BPF_BTF_GET_NEXT_ID:
5486 err = bpf_obj_get_next_id(&attr, uattr.user,
5487 &btf_idr, &btf_idr_lock);
5489 case BPF_PROG_GET_FD_BY_ID:
5490 err = bpf_prog_get_fd_by_id(&attr);
5492 case BPF_MAP_GET_FD_BY_ID:
5493 err = bpf_map_get_fd_by_id(&attr);
5495 case BPF_OBJ_GET_INFO_BY_FD:
5496 err = bpf_obj_get_info_by_fd(&attr, uattr.user);
5498 case BPF_RAW_TRACEPOINT_OPEN:
5499 err = bpf_raw_tracepoint_open(&attr);
5502 err = bpf_btf_load(&attr, uattr, size);
5504 case BPF_BTF_GET_FD_BY_ID:
5505 err = bpf_btf_get_fd_by_id(&attr);
5507 case BPF_TASK_FD_QUERY:
5508 err = bpf_task_fd_query(&attr, uattr.user);
5510 case BPF_MAP_LOOKUP_AND_DELETE_ELEM:
5511 err = map_lookup_and_delete_elem(&attr);
5513 case BPF_MAP_LOOKUP_BATCH:
5514 err = bpf_map_do_batch(&attr, uattr.user, BPF_MAP_LOOKUP_BATCH);
5516 case BPF_MAP_LOOKUP_AND_DELETE_BATCH:
5517 err = bpf_map_do_batch(&attr, uattr.user,
5518 BPF_MAP_LOOKUP_AND_DELETE_BATCH);
5520 case BPF_MAP_UPDATE_BATCH:
5521 err = bpf_map_do_batch(&attr, uattr.user, BPF_MAP_UPDATE_BATCH);
5523 case BPF_MAP_DELETE_BATCH:
5524 err = bpf_map_do_batch(&attr, uattr.user, BPF_MAP_DELETE_BATCH);
5526 case BPF_LINK_CREATE:
5527 err = link_create(&attr, uattr);
5529 case BPF_LINK_UPDATE:
5530 err = link_update(&attr);
5532 case BPF_LINK_GET_FD_BY_ID:
5533 err = bpf_link_get_fd_by_id(&attr);
5535 case BPF_LINK_GET_NEXT_ID:
5536 err = bpf_obj_get_next_id(&attr, uattr.user,
5537 &link_idr, &link_idr_lock);
5539 case BPF_ENABLE_STATS:
5540 err = bpf_enable_stats(&attr);
5542 case BPF_ITER_CREATE:
5543 err = bpf_iter_create(&attr);
5545 case BPF_LINK_DETACH:
5546 err = link_detach(&attr);
5548 case BPF_PROG_BIND_MAP:
5549 err = bpf_prog_bind_map(&attr);
5559 SYSCALL_DEFINE3(bpf, int, cmd, union bpf_attr __user *, uattr, unsigned int, size)
5561 return __sys_bpf(cmd, USER_BPFPTR(uattr), size);
5564 static bool syscall_prog_is_valid_access(int off, int size,
5565 enum bpf_access_type type,
5566 const struct bpf_prog *prog,
5567 struct bpf_insn_access_aux *info)
5569 if (off < 0 || off >= U16_MAX)
5571 if (off % size != 0)
5576 BPF_CALL_3(bpf_sys_bpf, int, cmd, union bpf_attr *, attr, u32, attr_size)
5579 case BPF_MAP_CREATE:
5580 case BPF_MAP_DELETE_ELEM:
5581 case BPF_MAP_UPDATE_ELEM:
5582 case BPF_MAP_FREEZE:
5583 case BPF_MAP_GET_FD_BY_ID:
5586 case BPF_LINK_CREATE:
5587 case BPF_RAW_TRACEPOINT_OPEN:
5592 return __sys_bpf(cmd, KERNEL_BPFPTR(attr), attr_size);
5596 /* To shut up -Wmissing-prototypes.
5597 * This function is used by the kernel light skeleton
5598 * to load bpf programs when modules are loaded or during kernel boot.
5599 * See tools/lib/bpf/skel_internal.h
5601 int kern_sys_bpf(int cmd, union bpf_attr *attr, unsigned int size);
5603 int kern_sys_bpf(int cmd, union bpf_attr *attr, unsigned int size)
5605 struct bpf_prog * __maybe_unused prog;
5606 struct bpf_tramp_run_ctx __maybe_unused run_ctx;
5609 #ifdef CONFIG_BPF_JIT /* __bpf_prog_enter_sleepable used by trampoline and JIT */
5610 case BPF_PROG_TEST_RUN:
5611 if (attr->test.data_in || attr->test.data_out ||
5612 attr->test.ctx_out || attr->test.duration ||
5613 attr->test.repeat || attr->test.flags)
5616 prog = bpf_prog_get_type(attr->test.prog_fd, BPF_PROG_TYPE_SYSCALL);
5618 return PTR_ERR(prog);
5620 if (attr->test.ctx_size_in < prog->aux->max_ctx_offset ||
5621 attr->test.ctx_size_in > U16_MAX) {
5626 run_ctx.bpf_cookie = 0;
5627 if (!__bpf_prog_enter_sleepable_recur(prog, &run_ctx)) {
5628 /* recursion detected */
5629 __bpf_prog_exit_sleepable_recur(prog, 0, &run_ctx);
5633 attr->test.retval = bpf_prog_run(prog, (void *) (long) attr->test.ctx_in);
5634 __bpf_prog_exit_sleepable_recur(prog, 0 /* bpf_prog_run does runtime stats */,
5640 return ____bpf_sys_bpf(cmd, attr, size);
5643 EXPORT_SYMBOL(kern_sys_bpf);
5645 static const struct bpf_func_proto bpf_sys_bpf_proto = {
5646 .func = bpf_sys_bpf,
5648 .ret_type = RET_INTEGER,
5649 .arg1_type = ARG_ANYTHING,
5650 .arg2_type = ARG_PTR_TO_MEM | MEM_RDONLY,
5651 .arg3_type = ARG_CONST_SIZE,
5654 const struct bpf_func_proto * __weak
5655 tracing_prog_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
5657 return bpf_base_func_proto(func_id);
5660 BPF_CALL_1(bpf_sys_close, u32, fd)
5662 /* When bpf program calls this helper there should not be
5663 * an fdget() without matching completed fdput().
5664 * This helper is allowed in the following callchain only:
5665 * sys_bpf->prog_test_run->bpf_prog->bpf_sys_close
5667 return close_fd(fd);
5670 static const struct bpf_func_proto bpf_sys_close_proto = {
5671 .func = bpf_sys_close,
5673 .ret_type = RET_INTEGER,
5674 .arg1_type = ARG_ANYTHING,
5677 BPF_CALL_4(bpf_kallsyms_lookup_name, const char *, name, int, name_sz, int, flags, u64 *, res)
5682 if (name_sz <= 1 || name[name_sz - 1])
5685 if (!bpf_dump_raw_ok(current_cred()))
5688 *res = kallsyms_lookup_name(name);
5689 return *res ? 0 : -ENOENT;
5692 static const struct bpf_func_proto bpf_kallsyms_lookup_name_proto = {
5693 .func = bpf_kallsyms_lookup_name,
5695 .ret_type = RET_INTEGER,
5696 .arg1_type = ARG_PTR_TO_MEM,
5697 .arg2_type = ARG_CONST_SIZE_OR_ZERO,
5698 .arg3_type = ARG_ANYTHING,
5699 .arg4_type = ARG_PTR_TO_LONG,
5702 static const struct bpf_func_proto *
5703 syscall_prog_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
5706 case BPF_FUNC_sys_bpf:
5707 return !perfmon_capable() ? NULL : &bpf_sys_bpf_proto;
5708 case BPF_FUNC_btf_find_by_name_kind:
5709 return &bpf_btf_find_by_name_kind_proto;
5710 case BPF_FUNC_sys_close:
5711 return &bpf_sys_close_proto;
5712 case BPF_FUNC_kallsyms_lookup_name:
5713 return &bpf_kallsyms_lookup_name_proto;
5715 return tracing_prog_func_proto(func_id, prog);
5719 const struct bpf_verifier_ops bpf_syscall_verifier_ops = {
5720 .get_func_proto = syscall_prog_func_proto,
5721 .is_valid_access = syscall_prog_is_valid_access,
5724 const struct bpf_prog_ops bpf_syscall_prog_ops = {
5725 .test_run = bpf_prog_test_run_syscall,
5728 #ifdef CONFIG_SYSCTL
5729 static int bpf_stats_handler(struct ctl_table *table, int write,
5730 void *buffer, size_t *lenp, loff_t *ppos)
5732 struct static_key *key = (struct static_key *)table->data;
5733 static int saved_val;
5735 struct ctl_table tmp = {
5737 .maxlen = sizeof(val),
5738 .mode = table->mode,
5739 .extra1 = SYSCTL_ZERO,
5740 .extra2 = SYSCTL_ONE,
5743 if (write && !capable(CAP_SYS_ADMIN))
5746 mutex_lock(&bpf_stats_enabled_mutex);
5748 ret = proc_dointvec_minmax(&tmp, write, buffer, lenp, ppos);
5749 if (write && !ret && val != saved_val) {
5751 static_key_slow_inc(key);
5753 static_key_slow_dec(key);
5756 mutex_unlock(&bpf_stats_enabled_mutex);
5760 void __weak unpriv_ebpf_notify(int new_state)
5764 static int bpf_unpriv_handler(struct ctl_table *table, int write,
5765 void *buffer, size_t *lenp, loff_t *ppos)
5767 int ret, unpriv_enable = *(int *)table->data;
5768 bool locked_state = unpriv_enable == 1;
5769 struct ctl_table tmp = *table;
5771 if (write && !capable(CAP_SYS_ADMIN))
5774 tmp.data = &unpriv_enable;
5775 ret = proc_dointvec_minmax(&tmp, write, buffer, lenp, ppos);
5776 if (write && !ret) {
5777 if (locked_state && unpriv_enable != 1)
5779 *(int *)table->data = unpriv_enable;
5783 unpriv_ebpf_notify(unpriv_enable);
5788 static struct ctl_table bpf_syscall_table[] = {
5790 .procname = "unprivileged_bpf_disabled",
5791 .data = &sysctl_unprivileged_bpf_disabled,
5792 .maxlen = sizeof(sysctl_unprivileged_bpf_disabled),
5794 .proc_handler = bpf_unpriv_handler,
5795 .extra1 = SYSCTL_ZERO,
5796 .extra2 = SYSCTL_TWO,
5799 .procname = "bpf_stats_enabled",
5800 .data = &bpf_stats_enabled_key.key,
5802 .proc_handler = bpf_stats_handler,
5807 static int __init bpf_syscall_sysctl_init(void)
5809 register_sysctl_init("kernel", bpf_syscall_table);
5812 late_initcall(bpf_syscall_sysctl_init);
5813 #endif /* CONFIG_SYSCTL */