1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
6 #include <linux/bpf-cgroup.h>
7 #include <linux/cgroup.h>
8 #include <linux/rcupdate.h>
9 #include <linux/random.h>
10 #include <linux/smp.h>
11 #include <linux/topology.h>
12 #include <linux/ktime.h>
13 #include <linux/sched.h>
14 #include <linux/uidgid.h>
15 #include <linux/filter.h>
16 #include <linux/ctype.h>
17 #include <linux/jiffies.h>
18 #include <linux/pid_namespace.h>
19 #include <linux/poison.h>
20 #include <linux/proc_ns.h>
21 #include <linux/security.h>
22 #include <linux/btf_ids.h>
23 #include <linux/bpf_mem_alloc.h>
25 #include "../../lib/kstrtox.h"
27 /* If kernel subsystem is allowing eBPF programs to call this function,
28 * inside its own verifier_ops->get_func_proto() callback it should return
29 * bpf_map_lookup_elem_proto, so that verifier can properly check the arguments
31 * Different map implementations will rely on rcu in map methods
32 * lookup/update/delete, therefore eBPF programs must run under rcu lock
33 * if program is allowed to access maps, so check rcu_read_lock_held in
34 * all three functions.
36 BPF_CALL_2(bpf_map_lookup_elem, struct bpf_map *, map, void *, key)
38 WARN_ON_ONCE(!rcu_read_lock_held() && !rcu_read_lock_bh_held());
39 return (unsigned long) map->ops->map_lookup_elem(map, key);
42 const struct bpf_func_proto bpf_map_lookup_elem_proto = {
43 .func = bpf_map_lookup_elem,
46 .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
47 .arg1_type = ARG_CONST_MAP_PTR,
48 .arg2_type = ARG_PTR_TO_MAP_KEY,
51 BPF_CALL_4(bpf_map_update_elem, struct bpf_map *, map, void *, key,
52 void *, value, u64, flags)
54 WARN_ON_ONCE(!rcu_read_lock_held() && !rcu_read_lock_bh_held());
55 return map->ops->map_update_elem(map, key, value, flags);
58 const struct bpf_func_proto bpf_map_update_elem_proto = {
59 .func = bpf_map_update_elem,
62 .ret_type = RET_INTEGER,
63 .arg1_type = ARG_CONST_MAP_PTR,
64 .arg2_type = ARG_PTR_TO_MAP_KEY,
65 .arg3_type = ARG_PTR_TO_MAP_VALUE,
66 .arg4_type = ARG_ANYTHING,
69 BPF_CALL_2(bpf_map_delete_elem, struct bpf_map *, map, void *, key)
71 WARN_ON_ONCE(!rcu_read_lock_held() && !rcu_read_lock_bh_held());
72 return map->ops->map_delete_elem(map, key);
75 const struct bpf_func_proto bpf_map_delete_elem_proto = {
76 .func = bpf_map_delete_elem,
79 .ret_type = RET_INTEGER,
80 .arg1_type = ARG_CONST_MAP_PTR,
81 .arg2_type = ARG_PTR_TO_MAP_KEY,
84 BPF_CALL_3(bpf_map_push_elem, struct bpf_map *, map, void *, value, u64, flags)
86 return map->ops->map_push_elem(map, value, flags);
89 const struct bpf_func_proto bpf_map_push_elem_proto = {
90 .func = bpf_map_push_elem,
93 .ret_type = RET_INTEGER,
94 .arg1_type = ARG_CONST_MAP_PTR,
95 .arg2_type = ARG_PTR_TO_MAP_VALUE,
96 .arg3_type = ARG_ANYTHING,
99 BPF_CALL_2(bpf_map_pop_elem, struct bpf_map *, map, void *, value)
101 return map->ops->map_pop_elem(map, value);
104 const struct bpf_func_proto bpf_map_pop_elem_proto = {
105 .func = bpf_map_pop_elem,
107 .ret_type = RET_INTEGER,
108 .arg1_type = ARG_CONST_MAP_PTR,
109 .arg2_type = ARG_PTR_TO_MAP_VALUE | MEM_UNINIT,
112 BPF_CALL_2(bpf_map_peek_elem, struct bpf_map *, map, void *, value)
114 return map->ops->map_peek_elem(map, value);
117 const struct bpf_func_proto bpf_map_peek_elem_proto = {
118 .func = bpf_map_peek_elem,
120 .ret_type = RET_INTEGER,
121 .arg1_type = ARG_CONST_MAP_PTR,
122 .arg2_type = ARG_PTR_TO_MAP_VALUE | MEM_UNINIT,
125 BPF_CALL_3(bpf_map_lookup_percpu_elem, struct bpf_map *, map, void *, key, u32, cpu)
127 WARN_ON_ONCE(!rcu_read_lock_held() && !rcu_read_lock_bh_held());
128 return (unsigned long) map->ops->map_lookup_percpu_elem(map, key, cpu);
131 const struct bpf_func_proto bpf_map_lookup_percpu_elem_proto = {
132 .func = bpf_map_lookup_percpu_elem,
135 .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
136 .arg1_type = ARG_CONST_MAP_PTR,
137 .arg2_type = ARG_PTR_TO_MAP_KEY,
138 .arg3_type = ARG_ANYTHING,
141 const struct bpf_func_proto bpf_get_prandom_u32_proto = {
142 .func = bpf_user_rnd_u32,
144 .ret_type = RET_INTEGER,
147 BPF_CALL_0(bpf_get_smp_processor_id)
149 return smp_processor_id();
152 const struct bpf_func_proto bpf_get_smp_processor_id_proto = {
153 .func = bpf_get_smp_processor_id,
155 .ret_type = RET_INTEGER,
158 BPF_CALL_0(bpf_get_numa_node_id)
160 return numa_node_id();
163 const struct bpf_func_proto bpf_get_numa_node_id_proto = {
164 .func = bpf_get_numa_node_id,
166 .ret_type = RET_INTEGER,
169 BPF_CALL_0(bpf_ktime_get_ns)
171 /* NMI safe access to clock monotonic */
172 return ktime_get_mono_fast_ns();
175 const struct bpf_func_proto bpf_ktime_get_ns_proto = {
176 .func = bpf_ktime_get_ns,
178 .ret_type = RET_INTEGER,
181 BPF_CALL_0(bpf_ktime_get_boot_ns)
183 /* NMI safe access to clock boottime */
184 return ktime_get_boot_fast_ns();
187 const struct bpf_func_proto bpf_ktime_get_boot_ns_proto = {
188 .func = bpf_ktime_get_boot_ns,
190 .ret_type = RET_INTEGER,
193 BPF_CALL_0(bpf_ktime_get_coarse_ns)
195 return ktime_get_coarse_ns();
198 const struct bpf_func_proto bpf_ktime_get_coarse_ns_proto = {
199 .func = bpf_ktime_get_coarse_ns,
201 .ret_type = RET_INTEGER,
204 BPF_CALL_0(bpf_ktime_get_tai_ns)
206 /* NMI safe access to clock tai */
207 return ktime_get_tai_fast_ns();
210 const struct bpf_func_proto bpf_ktime_get_tai_ns_proto = {
211 .func = bpf_ktime_get_tai_ns,
213 .ret_type = RET_INTEGER,
216 BPF_CALL_0(bpf_get_current_pid_tgid)
218 struct task_struct *task = current;
223 return (u64) task->tgid << 32 | task->pid;
226 const struct bpf_func_proto bpf_get_current_pid_tgid_proto = {
227 .func = bpf_get_current_pid_tgid,
229 .ret_type = RET_INTEGER,
232 BPF_CALL_0(bpf_get_current_uid_gid)
234 struct task_struct *task = current;
241 current_uid_gid(&uid, &gid);
242 return (u64) from_kgid(&init_user_ns, gid) << 32 |
243 from_kuid(&init_user_ns, uid);
246 const struct bpf_func_proto bpf_get_current_uid_gid_proto = {
247 .func = bpf_get_current_uid_gid,
249 .ret_type = RET_INTEGER,
252 BPF_CALL_2(bpf_get_current_comm, char *, buf, u32, size)
254 struct task_struct *task = current;
259 /* Verifier guarantees that size > 0 */
260 strscpy(buf, task->comm, size);
263 memset(buf, 0, size);
267 const struct bpf_func_proto bpf_get_current_comm_proto = {
268 .func = bpf_get_current_comm,
270 .ret_type = RET_INTEGER,
271 .arg1_type = ARG_PTR_TO_UNINIT_MEM,
272 .arg2_type = ARG_CONST_SIZE,
275 #if defined(CONFIG_QUEUED_SPINLOCKS) || defined(CONFIG_BPF_ARCH_SPINLOCK)
277 static inline void __bpf_spin_lock(struct bpf_spin_lock *lock)
279 arch_spinlock_t *l = (void *)lock;
282 arch_spinlock_t lock;
283 } u = { .lock = __ARCH_SPIN_LOCK_UNLOCKED };
285 compiletime_assert(u.val == 0, "__ARCH_SPIN_LOCK_UNLOCKED not 0");
286 BUILD_BUG_ON(sizeof(*l) != sizeof(__u32));
287 BUILD_BUG_ON(sizeof(*lock) != sizeof(__u32));
291 static inline void __bpf_spin_unlock(struct bpf_spin_lock *lock)
293 arch_spinlock_t *l = (void *)lock;
300 static inline void __bpf_spin_lock(struct bpf_spin_lock *lock)
302 atomic_t *l = (void *)lock;
304 BUILD_BUG_ON(sizeof(*l) != sizeof(*lock));
306 atomic_cond_read_relaxed(l, !VAL);
307 } while (atomic_xchg(l, 1));
310 static inline void __bpf_spin_unlock(struct bpf_spin_lock *lock)
312 atomic_t *l = (void *)lock;
314 atomic_set_release(l, 0);
319 static DEFINE_PER_CPU(unsigned long, irqsave_flags);
321 static inline void __bpf_spin_lock_irqsave(struct bpf_spin_lock *lock)
325 local_irq_save(flags);
326 __bpf_spin_lock(lock);
327 __this_cpu_write(irqsave_flags, flags);
330 notrace BPF_CALL_1(bpf_spin_lock, struct bpf_spin_lock *, lock)
332 __bpf_spin_lock_irqsave(lock);
336 const struct bpf_func_proto bpf_spin_lock_proto = {
337 .func = bpf_spin_lock,
339 .ret_type = RET_VOID,
340 .arg1_type = ARG_PTR_TO_SPIN_LOCK,
341 .arg1_btf_id = BPF_PTR_POISON,
344 static inline void __bpf_spin_unlock_irqrestore(struct bpf_spin_lock *lock)
348 flags = __this_cpu_read(irqsave_flags);
349 __bpf_spin_unlock(lock);
350 local_irq_restore(flags);
353 notrace BPF_CALL_1(bpf_spin_unlock, struct bpf_spin_lock *, lock)
355 __bpf_spin_unlock_irqrestore(lock);
359 const struct bpf_func_proto bpf_spin_unlock_proto = {
360 .func = bpf_spin_unlock,
362 .ret_type = RET_VOID,
363 .arg1_type = ARG_PTR_TO_SPIN_LOCK,
364 .arg1_btf_id = BPF_PTR_POISON,
367 void copy_map_value_locked(struct bpf_map *map, void *dst, void *src,
370 struct bpf_spin_lock *lock;
373 lock = src + map->record->spin_lock_off;
375 lock = dst + map->record->spin_lock_off;
377 __bpf_spin_lock_irqsave(lock);
378 copy_map_value(map, dst, src);
379 __bpf_spin_unlock_irqrestore(lock);
383 BPF_CALL_0(bpf_jiffies64)
385 return get_jiffies_64();
388 const struct bpf_func_proto bpf_jiffies64_proto = {
389 .func = bpf_jiffies64,
391 .ret_type = RET_INTEGER,
394 #ifdef CONFIG_CGROUPS
395 BPF_CALL_0(bpf_get_current_cgroup_id)
401 cgrp = task_dfl_cgroup(current);
402 cgrp_id = cgroup_id(cgrp);
408 const struct bpf_func_proto bpf_get_current_cgroup_id_proto = {
409 .func = bpf_get_current_cgroup_id,
411 .ret_type = RET_INTEGER,
414 BPF_CALL_1(bpf_get_current_ancestor_cgroup_id, int, ancestor_level)
417 struct cgroup *ancestor;
421 cgrp = task_dfl_cgroup(current);
422 ancestor = cgroup_ancestor(cgrp, ancestor_level);
423 cgrp_id = ancestor ? cgroup_id(ancestor) : 0;
429 const struct bpf_func_proto bpf_get_current_ancestor_cgroup_id_proto = {
430 .func = bpf_get_current_ancestor_cgroup_id,
432 .ret_type = RET_INTEGER,
433 .arg1_type = ARG_ANYTHING,
435 #endif /* CONFIG_CGROUPS */
437 #define BPF_STRTOX_BASE_MASK 0x1F
439 static int __bpf_strtoull(const char *buf, size_t buf_len, u64 flags,
440 unsigned long long *res, bool *is_negative)
442 unsigned int base = flags & BPF_STRTOX_BASE_MASK;
443 const char *cur_buf = buf;
444 size_t cur_len = buf_len;
445 unsigned int consumed;
449 if (!buf || !buf_len || !res || !is_negative)
452 if (base != 0 && base != 8 && base != 10 && base != 16)
455 if (flags & ~BPF_STRTOX_BASE_MASK)
458 while (cur_buf < buf + buf_len && isspace(*cur_buf))
461 *is_negative = (cur_buf < buf + buf_len && *cur_buf == '-');
465 consumed = cur_buf - buf;
470 cur_len = min(cur_len, sizeof(str) - 1);
471 memcpy(str, cur_buf, cur_len);
475 cur_buf = _parse_integer_fixup_radix(cur_buf, &base);
476 val_len = _parse_integer(cur_buf, base, res);
478 if (val_len & KSTRTOX_OVERFLOW)
485 consumed += cur_buf - str;
490 static int __bpf_strtoll(const char *buf, size_t buf_len, u64 flags,
493 unsigned long long _res;
497 err = __bpf_strtoull(buf, buf_len, flags, &_res, &is_negative);
501 if ((long long)-_res > 0)
505 if ((long long)_res < 0)
512 BPF_CALL_4(bpf_strtol, const char *, buf, size_t, buf_len, u64, flags,
518 err = __bpf_strtoll(buf, buf_len, flags, &_res);
521 if (_res != (long)_res)
527 const struct bpf_func_proto bpf_strtol_proto = {
530 .ret_type = RET_INTEGER,
531 .arg1_type = ARG_PTR_TO_MEM | MEM_RDONLY,
532 .arg2_type = ARG_CONST_SIZE,
533 .arg3_type = ARG_ANYTHING,
534 .arg4_type = ARG_PTR_TO_LONG,
537 BPF_CALL_4(bpf_strtoul, const char *, buf, size_t, buf_len, u64, flags,
538 unsigned long *, res)
540 unsigned long long _res;
544 err = __bpf_strtoull(buf, buf_len, flags, &_res, &is_negative);
549 if (_res != (unsigned long)_res)
555 const struct bpf_func_proto bpf_strtoul_proto = {
558 .ret_type = RET_INTEGER,
559 .arg1_type = ARG_PTR_TO_MEM | MEM_RDONLY,
560 .arg2_type = ARG_CONST_SIZE,
561 .arg3_type = ARG_ANYTHING,
562 .arg4_type = ARG_PTR_TO_LONG,
565 BPF_CALL_3(bpf_strncmp, const char *, s1, u32, s1_sz, const char *, s2)
567 return strncmp(s1, s2, s1_sz);
570 static const struct bpf_func_proto bpf_strncmp_proto = {
573 .ret_type = RET_INTEGER,
574 .arg1_type = ARG_PTR_TO_MEM,
575 .arg2_type = ARG_CONST_SIZE,
576 .arg3_type = ARG_PTR_TO_CONST_STR,
579 BPF_CALL_4(bpf_get_ns_current_pid_tgid, u64, dev, u64, ino,
580 struct bpf_pidns_info *, nsdata, u32, size)
582 struct task_struct *task = current;
583 struct pid_namespace *pidns;
586 if (unlikely(size != sizeof(struct bpf_pidns_info)))
589 if (unlikely((u64)(dev_t)dev != dev))
595 pidns = task_active_pid_ns(task);
596 if (unlikely(!pidns)) {
601 if (!ns_match(&pidns->ns, (dev_t)dev, ino))
604 nsdata->pid = task_pid_nr_ns(task, pidns);
605 nsdata->tgid = task_tgid_nr_ns(task, pidns);
608 memset((void *)nsdata, 0, (size_t) size);
612 const struct bpf_func_proto bpf_get_ns_current_pid_tgid_proto = {
613 .func = bpf_get_ns_current_pid_tgid,
615 .ret_type = RET_INTEGER,
616 .arg1_type = ARG_ANYTHING,
617 .arg2_type = ARG_ANYTHING,
618 .arg3_type = ARG_PTR_TO_UNINIT_MEM,
619 .arg4_type = ARG_CONST_SIZE,
622 static const struct bpf_func_proto bpf_get_raw_smp_processor_id_proto = {
623 .func = bpf_get_raw_cpu_id,
625 .ret_type = RET_INTEGER,
628 BPF_CALL_5(bpf_event_output_data, void *, ctx, struct bpf_map *, map,
629 u64, flags, void *, data, u64, size)
631 if (unlikely(flags & ~(BPF_F_INDEX_MASK)))
634 return bpf_event_output(map, flags, data, size, NULL, 0, NULL);
637 const struct bpf_func_proto bpf_event_output_data_proto = {
638 .func = bpf_event_output_data,
640 .ret_type = RET_INTEGER,
641 .arg1_type = ARG_PTR_TO_CTX,
642 .arg2_type = ARG_CONST_MAP_PTR,
643 .arg3_type = ARG_ANYTHING,
644 .arg4_type = ARG_PTR_TO_MEM | MEM_RDONLY,
645 .arg5_type = ARG_CONST_SIZE_OR_ZERO,
648 BPF_CALL_3(bpf_copy_from_user, void *, dst, u32, size,
649 const void __user *, user_ptr)
651 int ret = copy_from_user(dst, user_ptr, size);
654 memset(dst, 0, size);
661 const struct bpf_func_proto bpf_copy_from_user_proto = {
662 .func = bpf_copy_from_user,
665 .ret_type = RET_INTEGER,
666 .arg1_type = ARG_PTR_TO_UNINIT_MEM,
667 .arg2_type = ARG_CONST_SIZE_OR_ZERO,
668 .arg3_type = ARG_ANYTHING,
671 BPF_CALL_5(bpf_copy_from_user_task, void *, dst, u32, size,
672 const void __user *, user_ptr, struct task_struct *, tsk, u64, flags)
676 /* flags is not used yet */
683 ret = access_process_vm(tsk, (unsigned long)user_ptr, dst, size, 0);
687 memset(dst, 0, size);
688 /* Return -EFAULT for partial read */
689 return ret < 0 ? ret : -EFAULT;
692 const struct bpf_func_proto bpf_copy_from_user_task_proto = {
693 .func = bpf_copy_from_user_task,
696 .ret_type = RET_INTEGER,
697 .arg1_type = ARG_PTR_TO_UNINIT_MEM,
698 .arg2_type = ARG_CONST_SIZE_OR_ZERO,
699 .arg3_type = ARG_ANYTHING,
700 .arg4_type = ARG_PTR_TO_BTF_ID,
701 .arg4_btf_id = &btf_tracing_ids[BTF_TRACING_TYPE_TASK],
702 .arg5_type = ARG_ANYTHING
705 BPF_CALL_2(bpf_per_cpu_ptr, const void *, ptr, u32, cpu)
707 if (cpu >= nr_cpu_ids)
708 return (unsigned long)NULL;
710 return (unsigned long)per_cpu_ptr((const void __percpu *)ptr, cpu);
713 const struct bpf_func_proto bpf_per_cpu_ptr_proto = {
714 .func = bpf_per_cpu_ptr,
716 .ret_type = RET_PTR_TO_MEM_OR_BTF_ID | PTR_MAYBE_NULL | MEM_RDONLY,
717 .arg1_type = ARG_PTR_TO_PERCPU_BTF_ID,
718 .arg2_type = ARG_ANYTHING,
721 BPF_CALL_1(bpf_this_cpu_ptr, const void *, percpu_ptr)
723 return (unsigned long)this_cpu_ptr((const void __percpu *)percpu_ptr);
726 const struct bpf_func_proto bpf_this_cpu_ptr_proto = {
727 .func = bpf_this_cpu_ptr,
729 .ret_type = RET_PTR_TO_MEM_OR_BTF_ID | MEM_RDONLY,
730 .arg1_type = ARG_PTR_TO_PERCPU_BTF_ID,
733 static int bpf_trace_copy_string(char *buf, void *unsafe_ptr, char fmt_ptype,
736 void __user *user_ptr = (__force void __user *)unsafe_ptr;
742 #ifdef CONFIG_ARCH_HAS_NON_OVERLAPPING_ADDRESS_SPACE
743 if ((unsigned long)unsafe_ptr < TASK_SIZE)
744 return strncpy_from_user_nofault(buf, user_ptr, bufsz);
748 return strncpy_from_kernel_nofault(buf, unsafe_ptr, bufsz);
750 return strncpy_from_user_nofault(buf, user_ptr, bufsz);
756 /* Per-cpu temp buffers used by printf-like helpers to store the bprintf binary
757 * arguments representation.
759 #define MAX_BPRINTF_BIN_ARGS 512
761 /* Support executing three nested bprintf helper calls on a given CPU */
762 #define MAX_BPRINTF_NEST_LEVEL 3
763 struct bpf_bprintf_buffers {
764 char bin_args[MAX_BPRINTF_BIN_ARGS];
765 char buf[MAX_BPRINTF_BUF];
768 static DEFINE_PER_CPU(struct bpf_bprintf_buffers[MAX_BPRINTF_NEST_LEVEL], bpf_bprintf_bufs);
769 static DEFINE_PER_CPU(int, bpf_bprintf_nest_level);
771 static int try_get_buffers(struct bpf_bprintf_buffers **bufs)
776 nest_level = this_cpu_inc_return(bpf_bprintf_nest_level);
777 if (WARN_ON_ONCE(nest_level > MAX_BPRINTF_NEST_LEVEL)) {
778 this_cpu_dec(bpf_bprintf_nest_level);
782 *bufs = this_cpu_ptr(&bpf_bprintf_bufs[nest_level - 1]);
787 void bpf_bprintf_cleanup(struct bpf_bprintf_data *data)
789 if (!data->bin_args && !data->buf)
791 if (WARN_ON_ONCE(this_cpu_read(bpf_bprintf_nest_level) == 0))
793 this_cpu_dec(bpf_bprintf_nest_level);
798 * bpf_bprintf_prepare - Generic pass on format strings for bprintf-like helpers
800 * Returns a negative value if fmt is an invalid format string or 0 otherwise.
802 * This can be used in two ways:
803 * - Format string verification only: when data->get_bin_args is false
804 * - Arguments preparation: in addition to the above verification, it writes in
805 * data->bin_args a binary representation of arguments usable by bstr_printf
806 * where pointers from BPF have been sanitized.
808 * In argument preparation mode, if 0 is returned, safe temporary buffers are
809 * allocated and bpf_bprintf_cleanup should be called to free them after use.
811 int bpf_bprintf_prepare(char *fmt, u32 fmt_size, const u64 *raw_args,
812 u32 num_args, struct bpf_bprintf_data *data)
814 bool get_buffers = (data->get_bin_args && num_args) || data->get_buf;
815 char *unsafe_ptr = NULL, *tmp_buf = NULL, *tmp_buf_end, *fmt_end;
816 struct bpf_bprintf_buffers *buffers = NULL;
817 size_t sizeof_cur_arg, sizeof_cur_ip;
818 int err, i, num_spec = 0;
820 char fmt_ptype, cur_ip[16], ip_spec[] = "%pXX";
822 fmt_end = strnchr(fmt, fmt_size, 0);
825 fmt_size = fmt_end - fmt;
827 if (get_buffers && try_get_buffers(&buffers))
830 if (data->get_bin_args) {
832 tmp_buf = buffers->bin_args;
833 tmp_buf_end = tmp_buf + MAX_BPRINTF_BIN_ARGS;
834 data->bin_args = (u32 *)tmp_buf;
838 data->buf = buffers->buf;
840 for (i = 0; i < fmt_size; i++) {
841 if ((!isprint(fmt[i]) && !isspace(fmt[i])) || !isascii(fmt[i])) {
849 if (fmt[i + 1] == '%') {
854 if (num_spec >= num_args) {
859 /* The string is zero-terminated so if fmt[i] != 0, we can
860 * always access fmt[i + 1], in the worst case it will be a 0
864 /* skip optional "[0 +-][num]" width formatting field */
865 while (fmt[i] == '0' || fmt[i] == '+' || fmt[i] == '-' ||
868 if (fmt[i] >= '1' && fmt[i] <= '9') {
870 while (fmt[i] >= '0' && fmt[i] <= '9')
875 sizeof_cur_arg = sizeof(long);
877 if ((fmt[i + 1] == 'k' || fmt[i + 1] == 'u') &&
879 fmt_ptype = fmt[i + 1];
884 if (fmt[i + 1] == 0 || isspace(fmt[i + 1]) ||
885 ispunct(fmt[i + 1]) || fmt[i + 1] == 'K' ||
886 fmt[i + 1] == 'x' || fmt[i + 1] == 's' ||
888 /* just kernel pointers */
890 cur_arg = raw_args[num_spec];
895 if (fmt[i + 1] == 'B') {
897 err = snprintf(tmp_buf,
898 (tmp_buf_end - tmp_buf),
900 (void *)(long)raw_args[num_spec]);
901 tmp_buf += (err + 1);
909 /* only support "%pI4", "%pi4", "%pI6" and "%pi6". */
910 if ((fmt[i + 1] != 'i' && fmt[i + 1] != 'I') ||
911 (fmt[i + 2] != '4' && fmt[i + 2] != '6')) {
920 sizeof_cur_ip = (fmt[i] == '4') ? 4 : 16;
921 if (tmp_buf_end - tmp_buf < sizeof_cur_ip) {
926 unsafe_ptr = (char *)(long)raw_args[num_spec];
927 err = copy_from_kernel_nofault(cur_ip, unsafe_ptr,
930 memset(cur_ip, 0, sizeof_cur_ip);
932 /* hack: bstr_printf expects IP addresses to be
933 * pre-formatted as strings, ironically, the easiest way
934 * to do that is to call snprintf.
936 ip_spec[2] = fmt[i - 1];
938 err = snprintf(tmp_buf, tmp_buf_end - tmp_buf,
945 } else if (fmt[i] == 's') {
948 if (fmt[i + 1] != 0 &&
949 !isspace(fmt[i + 1]) &&
950 !ispunct(fmt[i + 1])) {
958 if (tmp_buf_end == tmp_buf) {
963 unsafe_ptr = (char *)(long)raw_args[num_spec];
964 err = bpf_trace_copy_string(tmp_buf, unsafe_ptr,
966 tmp_buf_end - tmp_buf);
976 } else if (fmt[i] == 'c') {
980 if (tmp_buf_end == tmp_buf) {
985 *tmp_buf = raw_args[num_spec];
992 sizeof_cur_arg = sizeof(int);
995 sizeof_cur_arg = sizeof(long);
999 sizeof_cur_arg = sizeof(long long);
1003 if (fmt[i] != 'i' && fmt[i] != 'd' && fmt[i] != 'u' &&
1004 fmt[i] != 'x' && fmt[i] != 'X') {
1010 cur_arg = raw_args[num_spec];
1013 tmp_buf = PTR_ALIGN(tmp_buf, sizeof(u32));
1014 if (tmp_buf_end - tmp_buf < sizeof_cur_arg) {
1019 if (sizeof_cur_arg == 8) {
1020 *(u32 *)tmp_buf = *(u32 *)&cur_arg;
1021 *(u32 *)(tmp_buf + 4) = *((u32 *)&cur_arg + 1);
1023 *(u32 *)tmp_buf = (u32)(long)cur_arg;
1025 tmp_buf += sizeof_cur_arg;
1033 bpf_bprintf_cleanup(data);
1037 BPF_CALL_5(bpf_snprintf, char *, str, u32, str_size, char *, fmt,
1038 const void *, args, u32, data_len)
1040 struct bpf_bprintf_data data = {
1041 .get_bin_args = true,
1045 if (data_len % 8 || data_len > MAX_BPRINTF_VARARGS * 8 ||
1046 (data_len && !args))
1048 num_args = data_len / 8;
1050 /* ARG_PTR_TO_CONST_STR guarantees that fmt is zero-terminated so we
1051 * can safely give an unbounded size.
1053 err = bpf_bprintf_prepare(fmt, UINT_MAX, args, num_args, &data);
1057 err = bstr_printf(str, str_size, fmt, data.bin_args);
1059 bpf_bprintf_cleanup(&data);
1064 const struct bpf_func_proto bpf_snprintf_proto = {
1065 .func = bpf_snprintf,
1067 .ret_type = RET_INTEGER,
1068 .arg1_type = ARG_PTR_TO_MEM_OR_NULL,
1069 .arg2_type = ARG_CONST_SIZE_OR_ZERO,
1070 .arg3_type = ARG_PTR_TO_CONST_STR,
1071 .arg4_type = ARG_PTR_TO_MEM | PTR_MAYBE_NULL | MEM_RDONLY,
1072 .arg5_type = ARG_CONST_SIZE_OR_ZERO,
1075 /* BPF map elements can contain 'struct bpf_timer'.
1076 * Such map owns all of its BPF timers.
1077 * 'struct bpf_timer' is allocated as part of map element allocation
1078 * and it's zero initialized.
1079 * That space is used to keep 'struct bpf_timer_kern'.
1080 * bpf_timer_init() allocates 'struct bpf_hrtimer', inits hrtimer, and
1081 * remembers 'struct bpf_map *' pointer it's part of.
1082 * bpf_timer_set_callback() increments prog refcnt and assign bpf callback_fn.
1083 * bpf_timer_start() arms the timer.
1084 * If user space reference to a map goes to zero at this point
1085 * ops->map_release_uref callback is responsible for cancelling the timers,
1086 * freeing their memory, and decrementing prog's refcnts.
1087 * bpf_timer_cancel() cancels the timer and decrements prog's refcnt.
1088 * Inner maps can contain bpf timers as well. ops->map_release_uref is
1089 * freeing the timers when inner map is replaced or deleted by user space.
1091 struct bpf_hrtimer {
1092 struct hrtimer timer;
1093 struct bpf_map *map;
1094 struct bpf_prog *prog;
1095 void __rcu *callback_fn;
1099 /* the actual struct hidden inside uapi struct bpf_timer */
1100 struct bpf_timer_kern {
1101 struct bpf_hrtimer *timer;
1102 /* bpf_spin_lock is used here instead of spinlock_t to make
1103 * sure that it always fits into space reserved by struct bpf_timer
1104 * regardless of LOCKDEP and spinlock debug flags.
1106 struct bpf_spin_lock lock;
1107 } __attribute__((aligned(8)));
1109 static DEFINE_PER_CPU(struct bpf_hrtimer *, hrtimer_running);
1111 static enum hrtimer_restart bpf_timer_cb(struct hrtimer *hrtimer)
1113 struct bpf_hrtimer *t = container_of(hrtimer, struct bpf_hrtimer, timer);
1114 struct bpf_map *map = t->map;
1115 void *value = t->value;
1116 bpf_callback_t callback_fn;
1120 BTF_TYPE_EMIT(struct bpf_timer);
1121 callback_fn = rcu_dereference_check(t->callback_fn, rcu_read_lock_bh_held());
1125 /* bpf_timer_cb() runs in hrtimer_run_softirq. It doesn't migrate and
1126 * cannot be preempted by another bpf_timer_cb() on the same cpu.
1127 * Remember the timer this callback is servicing to prevent
1128 * deadlock if callback_fn() calls bpf_timer_cancel() or
1129 * bpf_map_delete_elem() on the same timer.
1131 this_cpu_write(hrtimer_running, t);
1132 if (map->map_type == BPF_MAP_TYPE_ARRAY) {
1133 struct bpf_array *array = container_of(map, struct bpf_array, map);
1135 /* compute the key */
1136 idx = ((char *)value - array->value) / array->elem_size;
1138 } else { /* hash or lru */
1139 key = value - round_up(map->key_size, 8);
1142 callback_fn((u64)(long)map, (u64)(long)key, (u64)(long)value, 0, 0);
1143 /* The verifier checked that return value is zero. */
1145 this_cpu_write(hrtimer_running, NULL);
1147 return HRTIMER_NORESTART;
1150 BPF_CALL_3(bpf_timer_init, struct bpf_timer_kern *, timer, struct bpf_map *, map,
1153 clockid_t clockid = flags & (MAX_CLOCKS - 1);
1154 struct bpf_hrtimer *t;
1157 BUILD_BUG_ON(MAX_CLOCKS != 16);
1158 BUILD_BUG_ON(sizeof(struct bpf_timer_kern) > sizeof(struct bpf_timer));
1159 BUILD_BUG_ON(__alignof__(struct bpf_timer_kern) != __alignof__(struct bpf_timer));
1164 if (flags >= MAX_CLOCKS ||
1165 /* similar to timerfd except _ALARM variants are not supported */
1166 (clockid != CLOCK_MONOTONIC &&
1167 clockid != CLOCK_REALTIME &&
1168 clockid != CLOCK_BOOTTIME))
1170 __bpf_spin_lock_irqsave(&timer->lock);
1176 if (!atomic64_read(&map->usercnt)) {
1177 /* maps with timers must be either held by user space
1178 * or pinned in bpffs.
1183 /* allocate hrtimer via map_kmalloc to use memcg accounting */
1184 t = bpf_map_kmalloc_node(map, sizeof(*t), GFP_ATOMIC, map->numa_node);
1189 t->value = (void *)timer - map->record->timer_off;
1192 rcu_assign_pointer(t->callback_fn, NULL);
1193 hrtimer_init(&t->timer, clockid, HRTIMER_MODE_REL_SOFT);
1194 t->timer.function = bpf_timer_cb;
1197 __bpf_spin_unlock_irqrestore(&timer->lock);
1201 static const struct bpf_func_proto bpf_timer_init_proto = {
1202 .func = bpf_timer_init,
1204 .ret_type = RET_INTEGER,
1205 .arg1_type = ARG_PTR_TO_TIMER,
1206 .arg2_type = ARG_CONST_MAP_PTR,
1207 .arg3_type = ARG_ANYTHING,
1210 BPF_CALL_3(bpf_timer_set_callback, struct bpf_timer_kern *, timer, void *, callback_fn,
1211 struct bpf_prog_aux *, aux)
1213 struct bpf_prog *prev, *prog = aux->prog;
1214 struct bpf_hrtimer *t;
1219 __bpf_spin_lock_irqsave(&timer->lock);
1225 if (!atomic64_read(&t->map->usercnt)) {
1226 /* maps with timers must be either held by user space
1227 * or pinned in bpffs. Otherwise timer might still be
1228 * running even when bpf prog is detached and user space
1229 * is gone, since map_release_uref won't ever be called.
1236 /* Bump prog refcnt once. Every bpf_timer_set_callback()
1237 * can pick different callback_fn-s within the same prog.
1239 prog = bpf_prog_inc_not_zero(prog);
1241 ret = PTR_ERR(prog);
1245 /* Drop prev prog refcnt when swapping with new prog */
1249 rcu_assign_pointer(t->callback_fn, callback_fn);
1251 __bpf_spin_unlock_irqrestore(&timer->lock);
1255 static const struct bpf_func_proto bpf_timer_set_callback_proto = {
1256 .func = bpf_timer_set_callback,
1258 .ret_type = RET_INTEGER,
1259 .arg1_type = ARG_PTR_TO_TIMER,
1260 .arg2_type = ARG_PTR_TO_FUNC,
1263 BPF_CALL_3(bpf_timer_start, struct bpf_timer_kern *, timer, u64, nsecs, u64, flags)
1265 struct bpf_hrtimer *t;
1272 __bpf_spin_lock_irqsave(&timer->lock);
1274 if (!t || !t->prog) {
1278 hrtimer_start(&t->timer, ns_to_ktime(nsecs), HRTIMER_MODE_REL_SOFT);
1280 __bpf_spin_unlock_irqrestore(&timer->lock);
1284 static const struct bpf_func_proto bpf_timer_start_proto = {
1285 .func = bpf_timer_start,
1287 .ret_type = RET_INTEGER,
1288 .arg1_type = ARG_PTR_TO_TIMER,
1289 .arg2_type = ARG_ANYTHING,
1290 .arg3_type = ARG_ANYTHING,
1293 static void drop_prog_refcnt(struct bpf_hrtimer *t)
1295 struct bpf_prog *prog = t->prog;
1300 rcu_assign_pointer(t->callback_fn, NULL);
1304 BPF_CALL_1(bpf_timer_cancel, struct bpf_timer_kern *, timer)
1306 struct bpf_hrtimer *t;
1311 __bpf_spin_lock_irqsave(&timer->lock);
1317 if (this_cpu_read(hrtimer_running) == t) {
1318 /* If bpf callback_fn is trying to bpf_timer_cancel()
1319 * its own timer the hrtimer_cancel() will deadlock
1320 * since it waits for callback_fn to finish
1325 drop_prog_refcnt(t);
1327 __bpf_spin_unlock_irqrestore(&timer->lock);
1328 /* Cancel the timer and wait for associated callback to finish
1329 * if it was running.
1331 ret = ret ?: hrtimer_cancel(&t->timer);
1335 static const struct bpf_func_proto bpf_timer_cancel_proto = {
1336 .func = bpf_timer_cancel,
1338 .ret_type = RET_INTEGER,
1339 .arg1_type = ARG_PTR_TO_TIMER,
1342 /* This function is called by map_delete/update_elem for individual element and
1343 * by ops->map_release_uref when the user space reference to a map reaches zero.
1345 void bpf_timer_cancel_and_free(void *val)
1347 struct bpf_timer_kern *timer = val;
1348 struct bpf_hrtimer *t;
1350 /* Performance optimization: read timer->timer without lock first. */
1351 if (!READ_ONCE(timer->timer))
1354 __bpf_spin_lock_irqsave(&timer->lock);
1355 /* re-read it under lock */
1359 drop_prog_refcnt(t);
1360 /* The subsequent bpf_timer_start/cancel() helpers won't be able to use
1361 * this timer, since it won't be initialized.
1363 timer->timer = NULL;
1365 __bpf_spin_unlock_irqrestore(&timer->lock);
1368 /* Cancel the timer and wait for callback to complete if it was running.
1369 * If hrtimer_cancel() can be safely called it's safe to call kfree(t)
1370 * right after for both preallocated and non-preallocated maps.
1371 * The timer->timer = NULL was already done and no code path can
1372 * see address 't' anymore.
1374 * Check that bpf_map_delete/update_elem() wasn't called from timer
1375 * callback_fn. In such case don't call hrtimer_cancel() (since it will
1376 * deadlock) and don't call hrtimer_try_to_cancel() (since it will just
1377 * return -1). Though callback_fn is still running on this cpu it's
1378 * safe to do kfree(t) because bpf_timer_cb() read everything it needed
1379 * from 't'. The bpf subprog callback_fn won't be able to access 't',
1380 * since timer->timer = NULL was already done. The timer will be
1381 * effectively cancelled because bpf_timer_cb() will return
1382 * HRTIMER_NORESTART.
1384 if (this_cpu_read(hrtimer_running) != t)
1385 hrtimer_cancel(&t->timer);
1389 BPF_CALL_2(bpf_kptr_xchg, void *, map_value, void *, ptr)
1391 unsigned long *kptr = map_value;
1393 return xchg(kptr, (unsigned long)ptr);
1396 /* Unlike other PTR_TO_BTF_ID helpers the btf_id in bpf_kptr_xchg()
1397 * helper is determined dynamically by the verifier. Use BPF_PTR_POISON to
1398 * denote type that verifier will determine.
1400 static const struct bpf_func_proto bpf_kptr_xchg_proto = {
1401 .func = bpf_kptr_xchg,
1403 .ret_type = RET_PTR_TO_BTF_ID_OR_NULL,
1404 .ret_btf_id = BPF_PTR_POISON,
1405 .arg1_type = ARG_PTR_TO_KPTR,
1406 .arg2_type = ARG_PTR_TO_BTF_ID_OR_NULL | OBJ_RELEASE,
1407 .arg2_btf_id = BPF_PTR_POISON,
1410 /* Since the upper 8 bits of dynptr->size is reserved, the
1411 * maximum supported size is 2^24 - 1.
1413 #define DYNPTR_MAX_SIZE ((1UL << 24) - 1)
1414 #define DYNPTR_TYPE_SHIFT 28
1415 #define DYNPTR_SIZE_MASK 0xFFFFFF
1416 #define DYNPTR_RDONLY_BIT BIT(31)
1418 static bool bpf_dynptr_is_rdonly(const struct bpf_dynptr_kern *ptr)
1420 return ptr->size & DYNPTR_RDONLY_BIT;
1423 static void bpf_dynptr_set_type(struct bpf_dynptr_kern *ptr, enum bpf_dynptr_type type)
1425 ptr->size |= type << DYNPTR_TYPE_SHIFT;
1428 u32 bpf_dynptr_get_size(const struct bpf_dynptr_kern *ptr)
1430 return ptr->size & DYNPTR_SIZE_MASK;
1433 int bpf_dynptr_check_size(u32 size)
1435 return size > DYNPTR_MAX_SIZE ? -E2BIG : 0;
1438 void bpf_dynptr_init(struct bpf_dynptr_kern *ptr, void *data,
1439 enum bpf_dynptr_type type, u32 offset, u32 size)
1442 ptr->offset = offset;
1444 bpf_dynptr_set_type(ptr, type);
1447 void bpf_dynptr_set_null(struct bpf_dynptr_kern *ptr)
1449 memset(ptr, 0, sizeof(*ptr));
1452 static int bpf_dynptr_check_off_len(const struct bpf_dynptr_kern *ptr, u32 offset, u32 len)
1454 u32 size = bpf_dynptr_get_size(ptr);
1456 if (len > size || offset > size - len)
1462 BPF_CALL_4(bpf_dynptr_from_mem, void *, data, u32, size, u64, flags, struct bpf_dynptr_kern *, ptr)
1466 BTF_TYPE_EMIT(struct bpf_dynptr);
1468 err = bpf_dynptr_check_size(size);
1472 /* flags is currently unsupported */
1478 bpf_dynptr_init(ptr, data, BPF_DYNPTR_TYPE_LOCAL, 0, size);
1483 bpf_dynptr_set_null(ptr);
1487 static const struct bpf_func_proto bpf_dynptr_from_mem_proto = {
1488 .func = bpf_dynptr_from_mem,
1490 .ret_type = RET_INTEGER,
1491 .arg1_type = ARG_PTR_TO_UNINIT_MEM,
1492 .arg2_type = ARG_CONST_SIZE_OR_ZERO,
1493 .arg3_type = ARG_ANYTHING,
1494 .arg4_type = ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_LOCAL | MEM_UNINIT,
1497 BPF_CALL_5(bpf_dynptr_read, void *, dst, u32, len, const struct bpf_dynptr_kern *, src,
1498 u32, offset, u64, flags)
1502 if (!src->data || flags)
1505 err = bpf_dynptr_check_off_len(src, offset, len);
1509 /* Source and destination may possibly overlap, hence use memmove to
1510 * copy the data. E.g. bpf_dynptr_from_mem may create two dynptr
1511 * pointing to overlapping PTR_TO_MAP_VALUE regions.
1513 memmove(dst, src->data + src->offset + offset, len);
1518 static const struct bpf_func_proto bpf_dynptr_read_proto = {
1519 .func = bpf_dynptr_read,
1521 .ret_type = RET_INTEGER,
1522 .arg1_type = ARG_PTR_TO_UNINIT_MEM,
1523 .arg2_type = ARG_CONST_SIZE_OR_ZERO,
1524 .arg3_type = ARG_PTR_TO_DYNPTR | MEM_RDONLY,
1525 .arg4_type = ARG_ANYTHING,
1526 .arg5_type = ARG_ANYTHING,
1529 BPF_CALL_5(bpf_dynptr_write, const struct bpf_dynptr_kern *, dst, u32, offset, void *, src,
1530 u32, len, u64, flags)
1534 if (!dst->data || flags || bpf_dynptr_is_rdonly(dst))
1537 err = bpf_dynptr_check_off_len(dst, offset, len);
1541 /* Source and destination may possibly overlap, hence use memmove to
1542 * copy the data. E.g. bpf_dynptr_from_mem may create two dynptr
1543 * pointing to overlapping PTR_TO_MAP_VALUE regions.
1545 memmove(dst->data + dst->offset + offset, src, len);
1550 static const struct bpf_func_proto bpf_dynptr_write_proto = {
1551 .func = bpf_dynptr_write,
1553 .ret_type = RET_INTEGER,
1554 .arg1_type = ARG_PTR_TO_DYNPTR | MEM_RDONLY,
1555 .arg2_type = ARG_ANYTHING,
1556 .arg3_type = ARG_PTR_TO_MEM | MEM_RDONLY,
1557 .arg4_type = ARG_CONST_SIZE_OR_ZERO,
1558 .arg5_type = ARG_ANYTHING,
1561 BPF_CALL_3(bpf_dynptr_data, const struct bpf_dynptr_kern *, ptr, u32, offset, u32, len)
1568 err = bpf_dynptr_check_off_len(ptr, offset, len);
1572 if (bpf_dynptr_is_rdonly(ptr))
1575 return (unsigned long)(ptr->data + ptr->offset + offset);
1578 static const struct bpf_func_proto bpf_dynptr_data_proto = {
1579 .func = bpf_dynptr_data,
1581 .ret_type = RET_PTR_TO_DYNPTR_MEM_OR_NULL,
1582 .arg1_type = ARG_PTR_TO_DYNPTR | MEM_RDONLY,
1583 .arg2_type = ARG_ANYTHING,
1584 .arg3_type = ARG_CONST_ALLOC_SIZE_OR_ZERO,
1587 const struct bpf_func_proto bpf_get_current_task_proto __weak;
1588 const struct bpf_func_proto bpf_get_current_task_btf_proto __weak;
1589 const struct bpf_func_proto bpf_probe_read_user_proto __weak;
1590 const struct bpf_func_proto bpf_probe_read_user_str_proto __weak;
1591 const struct bpf_func_proto bpf_probe_read_kernel_proto __weak;
1592 const struct bpf_func_proto bpf_probe_read_kernel_str_proto __weak;
1593 const struct bpf_func_proto bpf_task_pt_regs_proto __weak;
1595 const struct bpf_func_proto *
1596 bpf_base_func_proto(enum bpf_func_id func_id)
1599 case BPF_FUNC_map_lookup_elem:
1600 return &bpf_map_lookup_elem_proto;
1601 case BPF_FUNC_map_update_elem:
1602 return &bpf_map_update_elem_proto;
1603 case BPF_FUNC_map_delete_elem:
1604 return &bpf_map_delete_elem_proto;
1605 case BPF_FUNC_map_push_elem:
1606 return &bpf_map_push_elem_proto;
1607 case BPF_FUNC_map_pop_elem:
1608 return &bpf_map_pop_elem_proto;
1609 case BPF_FUNC_map_peek_elem:
1610 return &bpf_map_peek_elem_proto;
1611 case BPF_FUNC_map_lookup_percpu_elem:
1612 return &bpf_map_lookup_percpu_elem_proto;
1613 case BPF_FUNC_get_prandom_u32:
1614 return &bpf_get_prandom_u32_proto;
1615 case BPF_FUNC_get_smp_processor_id:
1616 return &bpf_get_raw_smp_processor_id_proto;
1617 case BPF_FUNC_get_numa_node_id:
1618 return &bpf_get_numa_node_id_proto;
1619 case BPF_FUNC_tail_call:
1620 return &bpf_tail_call_proto;
1621 case BPF_FUNC_ktime_get_ns:
1622 return &bpf_ktime_get_ns_proto;
1623 case BPF_FUNC_ktime_get_boot_ns:
1624 return &bpf_ktime_get_boot_ns_proto;
1625 case BPF_FUNC_ktime_get_tai_ns:
1626 return &bpf_ktime_get_tai_ns_proto;
1627 case BPF_FUNC_ringbuf_output:
1628 return &bpf_ringbuf_output_proto;
1629 case BPF_FUNC_ringbuf_reserve:
1630 return &bpf_ringbuf_reserve_proto;
1631 case BPF_FUNC_ringbuf_submit:
1632 return &bpf_ringbuf_submit_proto;
1633 case BPF_FUNC_ringbuf_discard:
1634 return &bpf_ringbuf_discard_proto;
1635 case BPF_FUNC_ringbuf_query:
1636 return &bpf_ringbuf_query_proto;
1637 case BPF_FUNC_strncmp:
1638 return &bpf_strncmp_proto;
1639 case BPF_FUNC_strtol:
1640 return &bpf_strtol_proto;
1641 case BPF_FUNC_strtoul:
1642 return &bpf_strtoul_proto;
1651 case BPF_FUNC_spin_lock:
1652 return &bpf_spin_lock_proto;
1653 case BPF_FUNC_spin_unlock:
1654 return &bpf_spin_unlock_proto;
1655 case BPF_FUNC_jiffies64:
1656 return &bpf_jiffies64_proto;
1657 case BPF_FUNC_per_cpu_ptr:
1658 return &bpf_per_cpu_ptr_proto;
1659 case BPF_FUNC_this_cpu_ptr:
1660 return &bpf_this_cpu_ptr_proto;
1661 case BPF_FUNC_timer_init:
1662 return &bpf_timer_init_proto;
1663 case BPF_FUNC_timer_set_callback:
1664 return &bpf_timer_set_callback_proto;
1665 case BPF_FUNC_timer_start:
1666 return &bpf_timer_start_proto;
1667 case BPF_FUNC_timer_cancel:
1668 return &bpf_timer_cancel_proto;
1669 case BPF_FUNC_kptr_xchg:
1670 return &bpf_kptr_xchg_proto;
1671 case BPF_FUNC_for_each_map_elem:
1672 return &bpf_for_each_map_elem_proto;
1674 return &bpf_loop_proto;
1675 case BPF_FUNC_user_ringbuf_drain:
1676 return &bpf_user_ringbuf_drain_proto;
1677 case BPF_FUNC_ringbuf_reserve_dynptr:
1678 return &bpf_ringbuf_reserve_dynptr_proto;
1679 case BPF_FUNC_ringbuf_submit_dynptr:
1680 return &bpf_ringbuf_submit_dynptr_proto;
1681 case BPF_FUNC_ringbuf_discard_dynptr:
1682 return &bpf_ringbuf_discard_dynptr_proto;
1683 case BPF_FUNC_dynptr_from_mem:
1684 return &bpf_dynptr_from_mem_proto;
1685 case BPF_FUNC_dynptr_read:
1686 return &bpf_dynptr_read_proto;
1687 case BPF_FUNC_dynptr_write:
1688 return &bpf_dynptr_write_proto;
1689 case BPF_FUNC_dynptr_data:
1690 return &bpf_dynptr_data_proto;
1691 #ifdef CONFIG_CGROUPS
1692 case BPF_FUNC_cgrp_storage_get:
1693 return &bpf_cgrp_storage_get_proto;
1694 case BPF_FUNC_cgrp_storage_delete:
1695 return &bpf_cgrp_storage_delete_proto;
1701 if (!perfmon_capable())
1705 case BPF_FUNC_trace_printk:
1706 return bpf_get_trace_printk_proto();
1707 case BPF_FUNC_get_current_task:
1708 return &bpf_get_current_task_proto;
1709 case BPF_FUNC_get_current_task_btf:
1710 return &bpf_get_current_task_btf_proto;
1711 case BPF_FUNC_probe_read_user:
1712 return &bpf_probe_read_user_proto;
1713 case BPF_FUNC_probe_read_kernel:
1714 return security_locked_down(LOCKDOWN_BPF_READ_KERNEL) < 0 ?
1715 NULL : &bpf_probe_read_kernel_proto;
1716 case BPF_FUNC_probe_read_user_str:
1717 return &bpf_probe_read_user_str_proto;
1718 case BPF_FUNC_probe_read_kernel_str:
1719 return security_locked_down(LOCKDOWN_BPF_READ_KERNEL) < 0 ?
1720 NULL : &bpf_probe_read_kernel_str_proto;
1721 case BPF_FUNC_snprintf_btf:
1722 return &bpf_snprintf_btf_proto;
1723 case BPF_FUNC_snprintf:
1724 return &bpf_snprintf_proto;
1725 case BPF_FUNC_task_pt_regs:
1726 return &bpf_task_pt_regs_proto;
1727 case BPF_FUNC_trace_vprintk:
1728 return bpf_get_trace_vprintk_proto();
1734 void bpf_list_head_free(const struct btf_field *field, void *list_head,
1735 struct bpf_spin_lock *spin_lock)
1737 struct list_head *head = list_head, *orig_head = list_head;
1739 BUILD_BUG_ON(sizeof(struct list_head) > sizeof(struct bpf_list_head));
1740 BUILD_BUG_ON(__alignof__(struct list_head) > __alignof__(struct bpf_list_head));
1742 /* Do the actual list draining outside the lock to not hold the lock for
1743 * too long, and also prevent deadlocks if tracing programs end up
1744 * executing on entry/exit of functions called inside the critical
1745 * section, and end up doing map ops that call bpf_list_head_free for
1746 * the same map value again.
1748 __bpf_spin_lock_irqsave(spin_lock);
1749 if (!head->next || list_empty(head))
1753 INIT_LIST_HEAD(orig_head);
1754 __bpf_spin_unlock_irqrestore(spin_lock);
1756 while (head != orig_head) {
1759 obj -= field->graph_root.node_offset;
1761 /* The contained type can also have resources, including a
1762 * bpf_list_head which needs to be freed.
1764 bpf_obj_free_fields(field->graph_root.value_rec, obj);
1765 /* bpf_mem_free requires migrate_disable(), since we can be
1766 * called from map free path as well apart from BPF program (as
1767 * part of map ops doing bpf_obj_free_fields).
1770 bpf_mem_free(&bpf_global_ma, obj);
1776 __diag_ignore_all("-Wmissing-prototypes",
1777 "Global functions as their definitions will be in vmlinux BTF");
1779 void *bpf_obj_new_impl(u64 local_type_id__k, void *meta__ign)
1781 struct btf_struct_meta *meta = meta__ign;
1782 u64 size = local_type_id__k;
1785 p = bpf_mem_alloc(&bpf_global_ma, size);
1789 bpf_obj_init(meta->field_offs, p);
1793 void bpf_obj_drop_impl(void *p__alloc, void *meta__ign)
1795 struct btf_struct_meta *meta = meta__ign;
1799 bpf_obj_free_fields(meta->record, p);
1800 bpf_mem_free(&bpf_global_ma, p);
1803 static void __bpf_list_add(struct bpf_list_node *node, struct bpf_list_head *head, bool tail)
1805 struct list_head *n = (void *)node, *h = (void *)head;
1807 if (unlikely(!h->next))
1809 if (unlikely(!n->next))
1811 tail ? list_add_tail(n, h) : list_add(n, h);
1814 void bpf_list_push_front(struct bpf_list_head *head, struct bpf_list_node *node)
1816 return __bpf_list_add(node, head, false);
1819 void bpf_list_push_back(struct bpf_list_head *head, struct bpf_list_node *node)
1821 return __bpf_list_add(node, head, true);
1824 static struct bpf_list_node *__bpf_list_del(struct bpf_list_head *head, bool tail)
1826 struct list_head *n, *h = (void *)head;
1828 if (unlikely(!h->next))
1832 n = tail ? h->prev : h->next;
1834 return (struct bpf_list_node *)n;
1837 struct bpf_list_node *bpf_list_pop_front(struct bpf_list_head *head)
1839 return __bpf_list_del(head, false);
1842 struct bpf_list_node *bpf_list_pop_back(struct bpf_list_head *head)
1844 return __bpf_list_del(head, true);
1848 * bpf_task_acquire - Acquire a reference to a task. A task acquired by this
1849 * kfunc which is not stored in a map as a kptr, must be released by calling
1850 * bpf_task_release().
1851 * @p: The task on which a reference is being acquired.
1853 struct task_struct *bpf_task_acquire(struct task_struct *p)
1855 return get_task_struct(p);
1859 * bpf_task_acquire_not_zero - Acquire a reference to a rcu task object. A task
1860 * acquired by this kfunc which is not stored in a map as a kptr, must be
1861 * released by calling bpf_task_release().
1862 * @p: The task on which a reference is being acquired.
1864 struct task_struct *bpf_task_acquire_not_zero(struct task_struct *p)
1866 /* For the time being this function returns NULL, as it's not currently
1867 * possible to safely acquire a reference to a task with RCU protection
1868 * using get_task_struct() and put_task_struct(). This is due to the
1869 * slightly odd mechanics of p->rcu_users, and how task RCU protection
1872 * A struct task_struct is refcounted by two different refcount_t
1875 * 1. p->usage: The "true" refcount field which tracks a task's
1876 * lifetime. The task is freed as soon as this
1877 * refcount drops to 0.
1879 * 2. p->rcu_users: An "RCU users" refcount field which is statically
1880 * initialized to 2, and is co-located in a union with
1881 * a struct rcu_head field (p->rcu). p->rcu_users
1882 * essentially encapsulates a single p->usage
1883 * refcount, and when p->rcu_users goes to 0, an RCU
1884 * callback is scheduled on the struct rcu_head which
1885 * decrements the p->usage refcount.
1887 * There are two important implications to this task refcounting logic
1888 * described above. The first is that
1889 * refcount_inc_not_zero(&p->rcu_users) cannot be used anywhere, as
1890 * after the refcount goes to 0, the RCU callback being scheduled will
1891 * cause the memory backing the refcount to again be nonzero due to the
1892 * fields sharing a union. The other is that we can't rely on RCU to
1893 * guarantee that a task is valid in a BPF program. This is because a
1894 * task could have already transitioned to being in the TASK_DEAD
1895 * state, had its rcu_users refcount go to 0, and its rcu callback
1896 * invoked in which it drops its single p->usage reference. At this
1897 * point the task will be freed as soon as the last p->usage reference
1898 * goes to 0, without waiting for another RCU gp to elapse. The only
1899 * way that a BPF program can guarantee that a task is valid is in this
1900 * scenario is to hold a p->usage refcount itself.
1902 * Until we're able to resolve this issue, either by pulling
1903 * p->rcu_users and p->rcu out of the union, or by getting rid of
1904 * p->usage and just using p->rcu_users for refcounting, we'll just
1911 * bpf_task_kptr_get - Acquire a reference on a struct task_struct kptr. A task
1912 * kptr acquired by this kfunc which is not subsequently stored in a map, must
1913 * be released by calling bpf_task_release().
1914 * @pp: A pointer to a task kptr on which a reference is being acquired.
1916 struct task_struct *bpf_task_kptr_get(struct task_struct **pp)
1918 /* We must return NULL here until we have clarity on how to properly
1919 * leverage RCU for ensuring a task's lifetime. See the comment above
1920 * in bpf_task_acquire_not_zero() for more details.
1926 * bpf_task_release - Release the reference acquired on a task.
1927 * @p: The task on which a reference is being released.
1929 void bpf_task_release(struct task_struct *p)
1937 #ifdef CONFIG_CGROUPS
1939 * bpf_cgroup_acquire - Acquire a reference to a cgroup. A cgroup acquired by
1940 * this kfunc which is not stored in a map as a kptr, must be released by
1941 * calling bpf_cgroup_release().
1942 * @cgrp: The cgroup on which a reference is being acquired.
1944 struct cgroup *bpf_cgroup_acquire(struct cgroup *cgrp)
1951 * bpf_cgroup_kptr_get - Acquire a reference on a struct cgroup kptr. A cgroup
1952 * kptr acquired by this kfunc which is not subsequently stored in a map, must
1953 * be released by calling bpf_cgroup_release().
1954 * @cgrpp: A pointer to a cgroup kptr on which a reference is being acquired.
1956 struct cgroup *bpf_cgroup_kptr_get(struct cgroup **cgrpp)
1958 struct cgroup *cgrp;
1961 /* Another context could remove the cgroup from the map and release it
1962 * at any time, including after we've done the lookup above. This is
1963 * safe because we're in an RCU read region, so the cgroup is
1964 * guaranteed to remain valid until at least the rcu_read_unlock()
1967 cgrp = READ_ONCE(*cgrpp);
1969 if (cgrp && !cgroup_tryget(cgrp))
1970 /* If the cgroup had been removed from the map and freed as
1971 * described above, cgroup_tryget() will return false. The
1972 * cgroup will be freed at some point after the current RCU gp
1973 * has ended, so just return NULL to the user.
1982 * bpf_cgroup_release - Release the reference acquired on a cgroup.
1983 * If this kfunc is invoked in an RCU read region, the cgroup is guaranteed to
1984 * not be freed until the current grace period has ended, even if its refcount
1986 * @cgrp: The cgroup on which a reference is being released.
1988 void bpf_cgroup_release(struct cgroup *cgrp)
1997 * bpf_cgroup_ancestor - Perform a lookup on an entry in a cgroup's ancestor
1998 * array. A cgroup returned by this kfunc which is not subsequently stored in a
1999 * map, must be released by calling bpf_cgroup_release().
2000 * @cgrp: The cgroup for which we're performing a lookup.
2001 * @level: The level of ancestor to look up.
2003 struct cgroup *bpf_cgroup_ancestor(struct cgroup *cgrp, int level)
2005 struct cgroup *ancestor;
2007 if (level > cgrp->level || level < 0)
2010 ancestor = cgrp->ancestors[level];
2011 cgroup_get(ancestor);
2014 #endif /* CONFIG_CGROUPS */
2017 * bpf_task_from_pid - Find a struct task_struct from its pid by looking it up
2018 * in the root pid namespace idr. If a task is returned, it must either be
2019 * stored in a map, or released with bpf_task_release().
2020 * @pid: The pid of the task being looked up.
2022 struct task_struct *bpf_task_from_pid(s32 pid)
2024 struct task_struct *p;
2027 p = find_task_by_pid_ns(pid, &init_pid_ns);
2029 bpf_task_acquire(p);
2035 void *bpf_cast_to_kern_ctx(void *obj)
2040 void *bpf_rdonly_cast(void *obj__ign, u32 btf_id__k)
2045 void bpf_rcu_read_lock(void)
2050 void bpf_rcu_read_unlock(void)
2057 BTF_SET8_START(generic_btf_ids)
2058 #ifdef CONFIG_KEXEC_CORE
2059 BTF_ID_FLAGS(func, crash_kexec, KF_DESTRUCTIVE)
2061 BTF_ID_FLAGS(func, bpf_obj_new_impl, KF_ACQUIRE | KF_RET_NULL)
2062 BTF_ID_FLAGS(func, bpf_obj_drop_impl, KF_RELEASE)
2063 BTF_ID_FLAGS(func, bpf_list_push_front)
2064 BTF_ID_FLAGS(func, bpf_list_push_back)
2065 BTF_ID_FLAGS(func, bpf_list_pop_front, KF_ACQUIRE | KF_RET_NULL)
2066 BTF_ID_FLAGS(func, bpf_list_pop_back, KF_ACQUIRE | KF_RET_NULL)
2067 BTF_ID_FLAGS(func, bpf_task_acquire, KF_ACQUIRE | KF_TRUSTED_ARGS)
2068 BTF_ID_FLAGS(func, bpf_task_acquire_not_zero, KF_ACQUIRE | KF_RCU | KF_RET_NULL)
2069 BTF_ID_FLAGS(func, bpf_task_kptr_get, KF_ACQUIRE | KF_KPTR_GET | KF_RET_NULL)
2070 BTF_ID_FLAGS(func, bpf_task_release, KF_RELEASE)
2071 #ifdef CONFIG_CGROUPS
2072 BTF_ID_FLAGS(func, bpf_cgroup_acquire, KF_ACQUIRE | KF_TRUSTED_ARGS)
2073 BTF_ID_FLAGS(func, bpf_cgroup_kptr_get, KF_ACQUIRE | KF_KPTR_GET | KF_RET_NULL)
2074 BTF_ID_FLAGS(func, bpf_cgroup_release, KF_RELEASE)
2075 BTF_ID_FLAGS(func, bpf_cgroup_ancestor, KF_ACQUIRE | KF_TRUSTED_ARGS | KF_RET_NULL)
2077 BTF_ID_FLAGS(func, bpf_task_from_pid, KF_ACQUIRE | KF_RET_NULL)
2078 BTF_SET8_END(generic_btf_ids)
2080 static const struct btf_kfunc_id_set generic_kfunc_set = {
2081 .owner = THIS_MODULE,
2082 .set = &generic_btf_ids,
2086 BTF_ID_LIST(generic_dtor_ids)
2087 BTF_ID(struct, task_struct)
2088 BTF_ID(func, bpf_task_release)
2089 #ifdef CONFIG_CGROUPS
2090 BTF_ID(struct, cgroup)
2091 BTF_ID(func, bpf_cgroup_release)
2094 BTF_SET8_START(common_btf_ids)
2095 BTF_ID_FLAGS(func, bpf_cast_to_kern_ctx)
2096 BTF_ID_FLAGS(func, bpf_rdonly_cast)
2097 BTF_ID_FLAGS(func, bpf_rcu_read_lock)
2098 BTF_ID_FLAGS(func, bpf_rcu_read_unlock)
2099 BTF_SET8_END(common_btf_ids)
2101 static const struct btf_kfunc_id_set common_kfunc_set = {
2102 .owner = THIS_MODULE,
2103 .set = &common_btf_ids,
2106 static int __init kfunc_init(void)
2109 const struct btf_id_dtor_kfunc generic_dtors[] = {
2111 .btf_id = generic_dtor_ids[0],
2112 .kfunc_btf_id = generic_dtor_ids[1]
2114 #ifdef CONFIG_CGROUPS
2116 .btf_id = generic_dtor_ids[2],
2117 .kfunc_btf_id = generic_dtor_ids[3]
2122 ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_TRACING, &generic_kfunc_set);
2123 ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_SCHED_CLS, &generic_kfunc_set);
2124 ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS, &generic_kfunc_set);
2125 ret = ret ?: register_btf_id_dtor_kfuncs(generic_dtors,
2126 ARRAY_SIZE(generic_dtors),
2128 return ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_UNSPEC, &common_kfunc_set);
2131 late_initcall(kfunc_init);