bpf: Allow bpf_spin_{lock,unlock} in sleepable progs
[linux-block.git] / kernel / bpf / helpers.c
CommitLineData
5b497af4 1// SPDX-License-Identifier: GPL-2.0-only
d0003ec0 2/* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
d0003ec0
AS
3 */
4#include <linux/bpf.h>
3bd916ee 5#include <linux/btf.h>
aef2feda 6#include <linux/bpf-cgroup.h>
fda01efc 7#include <linux/cgroup.h>
d0003ec0 8#include <linux/rcupdate.h>
03e69b50 9#include <linux/random.h>
c04167ce 10#include <linux/smp.h>
2d0e30c3 11#include <linux/topology.h>
17ca8cbf 12#include <linux/ktime.h>
ffeedafb
AS
13#include <linux/sched.h>
14#include <linux/uidgid.h>
f3694e00 15#include <linux/filter.h>
d7a4cb9b 16#include <linux/ctype.h>
5576b991 17#include <linux/jiffies.h>
b4490c5c 18#include <linux/pid_namespace.h>
47e34cb7 19#include <linux/poison.h>
b4490c5c 20#include <linux/proc_ns.h>
d02c48fa 21#include <linux/sched/task.h>
ff40e510 22#include <linux/security.h>
376040e4 23#include <linux/btf_ids.h>
958cf2e2 24#include <linux/bpf_mem_alloc.h>
d7a4cb9b
AI
25
26#include "../../lib/kstrtox.h"
d0003ec0
AS
27
28/* If kernel subsystem is allowing eBPF programs to call this function,
29 * inside its own verifier_ops->get_func_proto() callback it should return
30 * bpf_map_lookup_elem_proto, so that verifier can properly check the arguments
31 *
32 * Different map implementations will rely on rcu in map methods
33 * lookup/update/delete, therefore eBPF programs must run under rcu lock
34 * if program is allowed to access maps, so check rcu_read_lock_held in
35 * all three functions.
36 */
f3694e00 37BPF_CALL_2(bpf_map_lookup_elem, struct bpf_map *, map, void *, key)
d0003ec0 38{
694cea39 39 WARN_ON_ONCE(!rcu_read_lock_held() && !rcu_read_lock_bh_held());
f3694e00 40 return (unsigned long) map->ops->map_lookup_elem(map, key);
d0003ec0
AS
41}
42
a2c83fff 43const struct bpf_func_proto bpf_map_lookup_elem_proto = {
3324b584
DB
44 .func = bpf_map_lookup_elem,
45 .gpl_only = false,
36bbef52 46 .pkt_access = true,
3324b584
DB
47 .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
48 .arg1_type = ARG_CONST_MAP_PTR,
49 .arg2_type = ARG_PTR_TO_MAP_KEY,
d0003ec0
AS
50};
51
f3694e00
DB
52BPF_CALL_4(bpf_map_update_elem, struct bpf_map *, map, void *, key,
53 void *, value, u64, flags)
d0003ec0 54{
694cea39 55 WARN_ON_ONCE(!rcu_read_lock_held() && !rcu_read_lock_bh_held());
f3694e00 56 return map->ops->map_update_elem(map, key, value, flags);
d0003ec0
AS
57}
58
a2c83fff 59const struct bpf_func_proto bpf_map_update_elem_proto = {
3324b584
DB
60 .func = bpf_map_update_elem,
61 .gpl_only = false,
36bbef52 62 .pkt_access = true,
3324b584
DB
63 .ret_type = RET_INTEGER,
64 .arg1_type = ARG_CONST_MAP_PTR,
65 .arg2_type = ARG_PTR_TO_MAP_KEY,
66 .arg3_type = ARG_PTR_TO_MAP_VALUE,
67 .arg4_type = ARG_ANYTHING,
d0003ec0
AS
68};
69
f3694e00 70BPF_CALL_2(bpf_map_delete_elem, struct bpf_map *, map, void *, key)
d0003ec0 71{
694cea39 72 WARN_ON_ONCE(!rcu_read_lock_held() && !rcu_read_lock_bh_held());
d0003ec0
AS
73 return map->ops->map_delete_elem(map, key);
74}
75
a2c83fff 76const struct bpf_func_proto bpf_map_delete_elem_proto = {
3324b584
DB
77 .func = bpf_map_delete_elem,
78 .gpl_only = false,
36bbef52 79 .pkt_access = true,
3324b584
DB
80 .ret_type = RET_INTEGER,
81 .arg1_type = ARG_CONST_MAP_PTR,
82 .arg2_type = ARG_PTR_TO_MAP_KEY,
d0003ec0 83};
03e69b50 84
f1a2e44a
MV
85BPF_CALL_3(bpf_map_push_elem, struct bpf_map *, map, void *, value, u64, flags)
86{
87 return map->ops->map_push_elem(map, value, flags);
88}
89
90const struct bpf_func_proto bpf_map_push_elem_proto = {
91 .func = bpf_map_push_elem,
92 .gpl_only = false,
93 .pkt_access = true,
94 .ret_type = RET_INTEGER,
95 .arg1_type = ARG_CONST_MAP_PTR,
96 .arg2_type = ARG_PTR_TO_MAP_VALUE,
97 .arg3_type = ARG_ANYTHING,
98};
99
100BPF_CALL_2(bpf_map_pop_elem, struct bpf_map *, map, void *, value)
101{
102 return map->ops->map_pop_elem(map, value);
103}
104
105const struct bpf_func_proto bpf_map_pop_elem_proto = {
106 .func = bpf_map_pop_elem,
107 .gpl_only = false,
f1a2e44a
MV
108 .ret_type = RET_INTEGER,
109 .arg1_type = ARG_CONST_MAP_PTR,
16d1e00c 110 .arg2_type = ARG_PTR_TO_MAP_VALUE | MEM_UNINIT,
f1a2e44a
MV
111};
112
113BPF_CALL_2(bpf_map_peek_elem, struct bpf_map *, map, void *, value)
114{
115 return map->ops->map_peek_elem(map, value);
116}
117
118const struct bpf_func_proto bpf_map_peek_elem_proto = {
301a33d5 119 .func = bpf_map_peek_elem,
f1a2e44a 120 .gpl_only = false,
f1a2e44a
MV
121 .ret_type = RET_INTEGER,
122 .arg1_type = ARG_CONST_MAP_PTR,
16d1e00c 123 .arg2_type = ARG_PTR_TO_MAP_VALUE | MEM_UNINIT,
f1a2e44a
MV
124};
125
07343110
FZ
126BPF_CALL_3(bpf_map_lookup_percpu_elem, struct bpf_map *, map, void *, key, u32, cpu)
127{
128 WARN_ON_ONCE(!rcu_read_lock_held() && !rcu_read_lock_bh_held());
129 return (unsigned long) map->ops->map_lookup_percpu_elem(map, key, cpu);
130}
131
132const struct bpf_func_proto bpf_map_lookup_percpu_elem_proto = {
133 .func = bpf_map_lookup_percpu_elem,
134 .gpl_only = false,
135 .pkt_access = true,
136 .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
137 .arg1_type = ARG_CONST_MAP_PTR,
138 .arg2_type = ARG_PTR_TO_MAP_KEY,
139 .arg3_type = ARG_ANYTHING,
140};
141
03e69b50 142const struct bpf_func_proto bpf_get_prandom_u32_proto = {
3ad00405 143 .func = bpf_user_rnd_u32,
03e69b50
DB
144 .gpl_only = false,
145 .ret_type = RET_INTEGER,
146};
c04167ce 147
f3694e00 148BPF_CALL_0(bpf_get_smp_processor_id)
c04167ce 149{
80b48c44 150 return smp_processor_id();
c04167ce
DB
151}
152
153const struct bpf_func_proto bpf_get_smp_processor_id_proto = {
154 .func = bpf_get_smp_processor_id,
155 .gpl_only = false,
156 .ret_type = RET_INTEGER,
157};
17ca8cbf 158
2d0e30c3
DB
159BPF_CALL_0(bpf_get_numa_node_id)
160{
161 return numa_node_id();
162}
163
164const struct bpf_func_proto bpf_get_numa_node_id_proto = {
165 .func = bpf_get_numa_node_id,
166 .gpl_only = false,
167 .ret_type = RET_INTEGER,
168};
169
f3694e00 170BPF_CALL_0(bpf_ktime_get_ns)
17ca8cbf
DB
171{
172 /* NMI safe access to clock monotonic */
173 return ktime_get_mono_fast_ns();
174}
175
176const struct bpf_func_proto bpf_ktime_get_ns_proto = {
177 .func = bpf_ktime_get_ns,
082b57e3 178 .gpl_only = false,
17ca8cbf
DB
179 .ret_type = RET_INTEGER,
180};
ffeedafb 181
71d19214
182BPF_CALL_0(bpf_ktime_get_boot_ns)
183{
184 /* NMI safe access to clock boottime */
185 return ktime_get_boot_fast_ns();
186}
187
188const struct bpf_func_proto bpf_ktime_get_boot_ns_proto = {
189 .func = bpf_ktime_get_boot_ns,
190 .gpl_only = false,
191 .ret_type = RET_INTEGER,
192};
193
d0551261
DB
194BPF_CALL_0(bpf_ktime_get_coarse_ns)
195{
196 return ktime_get_coarse_ns();
197}
198
199const struct bpf_func_proto bpf_ktime_get_coarse_ns_proto = {
200 .func = bpf_ktime_get_coarse_ns,
201 .gpl_only = false,
202 .ret_type = RET_INTEGER,
203};
204
c8996c98
JDB
205BPF_CALL_0(bpf_ktime_get_tai_ns)
206{
207 /* NMI safe access to clock tai */
208 return ktime_get_tai_fast_ns();
209}
210
211const struct bpf_func_proto bpf_ktime_get_tai_ns_proto = {
212 .func = bpf_ktime_get_tai_ns,
213 .gpl_only = false,
214 .ret_type = RET_INTEGER,
215};
216
f3694e00 217BPF_CALL_0(bpf_get_current_pid_tgid)
ffeedafb
AS
218{
219 struct task_struct *task = current;
220
6088b582 221 if (unlikely(!task))
ffeedafb
AS
222 return -EINVAL;
223
224 return (u64) task->tgid << 32 | task->pid;
225}
226
227const struct bpf_func_proto bpf_get_current_pid_tgid_proto = {
228 .func = bpf_get_current_pid_tgid,
229 .gpl_only = false,
230 .ret_type = RET_INTEGER,
231};
232
f3694e00 233BPF_CALL_0(bpf_get_current_uid_gid)
ffeedafb
AS
234{
235 struct task_struct *task = current;
236 kuid_t uid;
237 kgid_t gid;
238
6088b582 239 if (unlikely(!task))
ffeedafb
AS
240 return -EINVAL;
241
242 current_uid_gid(&uid, &gid);
243 return (u64) from_kgid(&init_user_ns, gid) << 32 |
6088b582 244 from_kuid(&init_user_ns, uid);
ffeedafb
AS
245}
246
247const struct bpf_func_proto bpf_get_current_uid_gid_proto = {
248 .func = bpf_get_current_uid_gid,
249 .gpl_only = false,
250 .ret_type = RET_INTEGER,
251};
252
f3694e00 253BPF_CALL_2(bpf_get_current_comm, char *, buf, u32, size)
ffeedafb
AS
254{
255 struct task_struct *task = current;
ffeedafb 256
074f528e
DB
257 if (unlikely(!task))
258 goto err_clear;
ffeedafb 259
03b9c7fa 260 /* Verifier guarantees that size > 0 */
f3f21349 261 strscpy_pad(buf, task->comm, size);
ffeedafb 262 return 0;
074f528e
DB
263err_clear:
264 memset(buf, 0, size);
265 return -EINVAL;
ffeedafb
AS
266}
267
268const struct bpf_func_proto bpf_get_current_comm_proto = {
269 .func = bpf_get_current_comm,
270 .gpl_only = false,
271 .ret_type = RET_INTEGER,
39f19ebb
AS
272 .arg1_type = ARG_PTR_TO_UNINIT_MEM,
273 .arg2_type = ARG_CONST_SIZE,
ffeedafb 274};
bf6fa2c8 275
d83525ca
AS
276#if defined(CONFIG_QUEUED_SPINLOCKS) || defined(CONFIG_BPF_ARCH_SPINLOCK)
277
278static inline void __bpf_spin_lock(struct bpf_spin_lock *lock)
279{
280 arch_spinlock_t *l = (void *)lock;
281 union {
282 __u32 val;
283 arch_spinlock_t lock;
284 } u = { .lock = __ARCH_SPIN_LOCK_UNLOCKED };
285
286 compiletime_assert(u.val == 0, "__ARCH_SPIN_LOCK_UNLOCKED not 0");
287 BUILD_BUG_ON(sizeof(*l) != sizeof(__u32));
288 BUILD_BUG_ON(sizeof(*lock) != sizeof(__u32));
5861d1e8 289 preempt_disable();
d83525ca
AS
290 arch_spin_lock(l);
291}
292
293static inline void __bpf_spin_unlock(struct bpf_spin_lock *lock)
294{
295 arch_spinlock_t *l = (void *)lock;
296
297 arch_spin_unlock(l);
5861d1e8 298 preempt_enable();
d83525ca
AS
299}
300
301#else
302
303static inline void __bpf_spin_lock(struct bpf_spin_lock *lock)
304{
305 atomic_t *l = (void *)lock;
306
307 BUILD_BUG_ON(sizeof(*l) != sizeof(*lock));
308 do {
309 atomic_cond_read_relaxed(l, !VAL);
310 } while (atomic_xchg(l, 1));
311}
312
313static inline void __bpf_spin_unlock(struct bpf_spin_lock *lock)
314{
315 atomic_t *l = (void *)lock;
316
317 atomic_set_release(l, 0);
318}
319
320#endif
321
322static DEFINE_PER_CPU(unsigned long, irqsave_flags);
323
c1b3fed3 324static inline void __bpf_spin_lock_irqsave(struct bpf_spin_lock *lock)
d83525ca
AS
325{
326 unsigned long flags;
327
328 local_irq_save(flags);
329 __bpf_spin_lock(lock);
330 __this_cpu_write(irqsave_flags, flags);
c1b3fed3
AS
331}
332
333notrace BPF_CALL_1(bpf_spin_lock, struct bpf_spin_lock *, lock)
334{
335 __bpf_spin_lock_irqsave(lock);
d83525ca
AS
336 return 0;
337}
338
339const struct bpf_func_proto bpf_spin_lock_proto = {
340 .func = bpf_spin_lock,
341 .gpl_only = false,
342 .ret_type = RET_VOID,
343 .arg1_type = ARG_PTR_TO_SPIN_LOCK,
4e814da0 344 .arg1_btf_id = BPF_PTR_POISON,
d83525ca
AS
345};
346
c1b3fed3 347static inline void __bpf_spin_unlock_irqrestore(struct bpf_spin_lock *lock)
d83525ca
AS
348{
349 unsigned long flags;
350
351 flags = __this_cpu_read(irqsave_flags);
352 __bpf_spin_unlock(lock);
353 local_irq_restore(flags);
c1b3fed3
AS
354}
355
356notrace BPF_CALL_1(bpf_spin_unlock, struct bpf_spin_lock *, lock)
357{
358 __bpf_spin_unlock_irqrestore(lock);
d83525ca
AS
359 return 0;
360}
361
362const struct bpf_func_proto bpf_spin_unlock_proto = {
363 .func = bpf_spin_unlock,
364 .gpl_only = false,
365 .ret_type = RET_VOID,
366 .arg1_type = ARG_PTR_TO_SPIN_LOCK,
4e814da0 367 .arg1_btf_id = BPF_PTR_POISON,
d83525ca
AS
368};
369
96049f3a
AS
370void copy_map_value_locked(struct bpf_map *map, void *dst, void *src,
371 bool lock_src)
372{
373 struct bpf_spin_lock *lock;
374
375 if (lock_src)
db559117 376 lock = src + map->record->spin_lock_off;
96049f3a 377 else
db559117 378 lock = dst + map->record->spin_lock_off;
96049f3a 379 preempt_disable();
c1b3fed3 380 __bpf_spin_lock_irqsave(lock);
96049f3a 381 copy_map_value(map, dst, src);
c1b3fed3 382 __bpf_spin_unlock_irqrestore(lock);
96049f3a
AS
383 preempt_enable();
384}
385
5576b991
MKL
386BPF_CALL_0(bpf_jiffies64)
387{
388 return get_jiffies_64();
389}
390
391const struct bpf_func_proto bpf_jiffies64_proto = {
392 .func = bpf_jiffies64,
393 .gpl_only = false,
394 .ret_type = RET_INTEGER,
395};
396
bf6fa2c8
YS
397#ifdef CONFIG_CGROUPS
398BPF_CALL_0(bpf_get_current_cgroup_id)
399{
2d3a1e36
YS
400 struct cgroup *cgrp;
401 u64 cgrp_id;
bf6fa2c8 402
2d3a1e36
YS
403 rcu_read_lock();
404 cgrp = task_dfl_cgroup(current);
405 cgrp_id = cgroup_id(cgrp);
406 rcu_read_unlock();
407
408 return cgrp_id;
bf6fa2c8
YS
409}
410
411const struct bpf_func_proto bpf_get_current_cgroup_id_proto = {
412 .func = bpf_get_current_cgroup_id,
413 .gpl_only = false,
414 .ret_type = RET_INTEGER,
415};
cd339431 416
0f09abd1
DB
417BPF_CALL_1(bpf_get_current_ancestor_cgroup_id, int, ancestor_level)
418{
2d3a1e36 419 struct cgroup *cgrp;
0f09abd1 420 struct cgroup *ancestor;
2d3a1e36 421 u64 cgrp_id;
0f09abd1 422
2d3a1e36
YS
423 rcu_read_lock();
424 cgrp = task_dfl_cgroup(current);
0f09abd1 425 ancestor = cgroup_ancestor(cgrp, ancestor_level);
2d3a1e36
YS
426 cgrp_id = ancestor ? cgroup_id(ancestor) : 0;
427 rcu_read_unlock();
428
429 return cgrp_id;
0f09abd1
DB
430}
431
432const struct bpf_func_proto bpf_get_current_ancestor_cgroup_id_proto = {
433 .func = bpf_get_current_ancestor_cgroup_id,
434 .gpl_only = false,
435 .ret_type = RET_INTEGER,
436 .arg1_type = ARG_ANYTHING,
437};
8a67f2de 438#endif /* CONFIG_CGROUPS */
0f09abd1 439
d7a4cb9b
AI
440#define BPF_STRTOX_BASE_MASK 0x1F
441
442static int __bpf_strtoull(const char *buf, size_t buf_len, u64 flags,
443 unsigned long long *res, bool *is_negative)
444{
445 unsigned int base = flags & BPF_STRTOX_BASE_MASK;
446 const char *cur_buf = buf;
447 size_t cur_len = buf_len;
448 unsigned int consumed;
449 size_t val_len;
450 char str[64];
451
452 if (!buf || !buf_len || !res || !is_negative)
453 return -EINVAL;
454
455 if (base != 0 && base != 8 && base != 10 && base != 16)
456 return -EINVAL;
457
458 if (flags & ~BPF_STRTOX_BASE_MASK)
459 return -EINVAL;
460
461 while (cur_buf < buf + buf_len && isspace(*cur_buf))
462 ++cur_buf;
463
464 *is_negative = (cur_buf < buf + buf_len && *cur_buf == '-');
465 if (*is_negative)
466 ++cur_buf;
467
468 consumed = cur_buf - buf;
469 cur_len -= consumed;
470 if (!cur_len)
471 return -EINVAL;
472
473 cur_len = min(cur_len, sizeof(str) - 1);
474 memcpy(str, cur_buf, cur_len);
475 str[cur_len] = '\0';
476 cur_buf = str;
477
478 cur_buf = _parse_integer_fixup_radix(cur_buf, &base);
479 val_len = _parse_integer(cur_buf, base, res);
480
481 if (val_len & KSTRTOX_OVERFLOW)
482 return -ERANGE;
483
484 if (val_len == 0)
485 return -EINVAL;
486
487 cur_buf += val_len;
488 consumed += cur_buf - str;
489
490 return consumed;
491}
492
493static int __bpf_strtoll(const char *buf, size_t buf_len, u64 flags,
494 long long *res)
495{
496 unsigned long long _res;
497 bool is_negative;
498 int err;
499
500 err = __bpf_strtoull(buf, buf_len, flags, &_res, &is_negative);
501 if (err < 0)
502 return err;
503 if (is_negative) {
504 if ((long long)-_res > 0)
505 return -ERANGE;
506 *res = -_res;
507 } else {
508 if ((long long)_res < 0)
509 return -ERANGE;
510 *res = _res;
511 }
512 return err;
513}
514
515BPF_CALL_4(bpf_strtol, const char *, buf, size_t, buf_len, u64, flags,
516 long *, res)
517{
518 long long _res;
519 int err;
520
521 err = __bpf_strtoll(buf, buf_len, flags, &_res);
522 if (err < 0)
523 return err;
524 if (_res != (long)_res)
525 return -ERANGE;
526 *res = _res;
527 return err;
528}
529
530const struct bpf_func_proto bpf_strtol_proto = {
531 .func = bpf_strtol,
532 .gpl_only = false,
533 .ret_type = RET_INTEGER,
216e3cd2 534 .arg1_type = ARG_PTR_TO_MEM | MEM_RDONLY,
d7a4cb9b
AI
535 .arg2_type = ARG_CONST_SIZE,
536 .arg3_type = ARG_ANYTHING,
537 .arg4_type = ARG_PTR_TO_LONG,
538};
539
540BPF_CALL_4(bpf_strtoul, const char *, buf, size_t, buf_len, u64, flags,
541 unsigned long *, res)
542{
543 unsigned long long _res;
544 bool is_negative;
545 int err;
546
547 err = __bpf_strtoull(buf, buf_len, flags, &_res, &is_negative);
548 if (err < 0)
549 return err;
550 if (is_negative)
551 return -EINVAL;
552 if (_res != (unsigned long)_res)
553 return -ERANGE;
554 *res = _res;
555 return err;
556}
557
558const struct bpf_func_proto bpf_strtoul_proto = {
559 .func = bpf_strtoul,
560 .gpl_only = false,
561 .ret_type = RET_INTEGER,
216e3cd2 562 .arg1_type = ARG_PTR_TO_MEM | MEM_RDONLY,
d7a4cb9b
AI
563 .arg2_type = ARG_CONST_SIZE,
564 .arg3_type = ARG_ANYTHING,
565 .arg4_type = ARG_PTR_TO_LONG,
566};
b4490c5c 567
c5fb1993
HT
568BPF_CALL_3(bpf_strncmp, const char *, s1, u32, s1_sz, const char *, s2)
569{
570 return strncmp(s1, s2, s1_sz);
571}
572
dc368e1c 573static const struct bpf_func_proto bpf_strncmp_proto = {
c5fb1993
HT
574 .func = bpf_strncmp,
575 .gpl_only = false,
576 .ret_type = RET_INTEGER,
c9267aa8 577 .arg1_type = ARG_PTR_TO_MEM | MEM_RDONLY,
c5fb1993
HT
578 .arg2_type = ARG_CONST_SIZE,
579 .arg3_type = ARG_PTR_TO_CONST_STR,
580};
581
b4490c5c
CN
582BPF_CALL_4(bpf_get_ns_current_pid_tgid, u64, dev, u64, ino,
583 struct bpf_pidns_info *, nsdata, u32, size)
584{
585 struct task_struct *task = current;
586 struct pid_namespace *pidns;
587 int err = -EINVAL;
588
589 if (unlikely(size != sizeof(struct bpf_pidns_info)))
590 goto clear;
591
592 if (unlikely((u64)(dev_t)dev != dev))
593 goto clear;
594
595 if (unlikely(!task))
596 goto clear;
597
598 pidns = task_active_pid_ns(task);
599 if (unlikely(!pidns)) {
600 err = -ENOENT;
601 goto clear;
602 }
603
604 if (!ns_match(&pidns->ns, (dev_t)dev, ino))
605 goto clear;
606
607 nsdata->pid = task_pid_nr_ns(task, pidns);
608 nsdata->tgid = task_tgid_nr_ns(task, pidns);
609 return 0;
610clear:
611 memset((void *)nsdata, 0, (size_t) size);
612 return err;
613}
614
615const struct bpf_func_proto bpf_get_ns_current_pid_tgid_proto = {
616 .func = bpf_get_ns_current_pid_tgid,
617 .gpl_only = false,
618 .ret_type = RET_INTEGER,
619 .arg1_type = ARG_ANYTHING,
620 .arg2_type = ARG_ANYTHING,
621 .arg3_type = ARG_PTR_TO_UNINIT_MEM,
622 .arg4_type = ARG_CONST_SIZE,
623};
6890896b
SF
624
625static const struct bpf_func_proto bpf_get_raw_smp_processor_id_proto = {
626 .func = bpf_get_raw_cpu_id,
627 .gpl_only = false,
628 .ret_type = RET_INTEGER,
629};
630
631BPF_CALL_5(bpf_event_output_data, void *, ctx, struct bpf_map *, map,
632 u64, flags, void *, data, u64, size)
633{
634 if (unlikely(flags & ~(BPF_F_INDEX_MASK)))
635 return -EINVAL;
636
637 return bpf_event_output(map, flags, data, size, NULL, 0, NULL);
638}
639
640const struct bpf_func_proto bpf_event_output_data_proto = {
641 .func = bpf_event_output_data,
642 .gpl_only = true,
643 .ret_type = RET_INTEGER,
644 .arg1_type = ARG_PTR_TO_CTX,
645 .arg2_type = ARG_CONST_MAP_PTR,
646 .arg3_type = ARG_ANYTHING,
216e3cd2 647 .arg4_type = ARG_PTR_TO_MEM | MEM_RDONLY,
6890896b
SF
648 .arg5_type = ARG_CONST_SIZE_OR_ZERO,
649};
650
07be4c4a
AS
651BPF_CALL_3(bpf_copy_from_user, void *, dst, u32, size,
652 const void __user *, user_ptr)
653{
654 int ret = copy_from_user(dst, user_ptr, size);
655
656 if (unlikely(ret)) {
657 memset(dst, 0, size);
658 ret = -EFAULT;
659 }
660
661 return ret;
662}
663
664const struct bpf_func_proto bpf_copy_from_user_proto = {
665 .func = bpf_copy_from_user,
666 .gpl_only = false,
01685c5b 667 .might_sleep = true,
07be4c4a
AS
668 .ret_type = RET_INTEGER,
669 .arg1_type = ARG_PTR_TO_UNINIT_MEM,
670 .arg2_type = ARG_CONST_SIZE_OR_ZERO,
671 .arg3_type = ARG_ANYTHING,
672};
673
376040e4
KY
674BPF_CALL_5(bpf_copy_from_user_task, void *, dst, u32, size,
675 const void __user *, user_ptr, struct task_struct *, tsk, u64, flags)
676{
677 int ret;
678
679 /* flags is not used yet */
680 if (unlikely(flags))
681 return -EINVAL;
682
683 if (unlikely(!size))
684 return 0;
685
686 ret = access_process_vm(tsk, (unsigned long)user_ptr, dst, size, 0);
687 if (ret == size)
688 return 0;
689
690 memset(dst, 0, size);
691 /* Return -EFAULT for partial read */
692 return ret < 0 ? ret : -EFAULT;
693}
694
695const struct bpf_func_proto bpf_copy_from_user_task_proto = {
696 .func = bpf_copy_from_user_task,
0407a65f 697 .gpl_only = true,
01685c5b 698 .might_sleep = true,
376040e4
KY
699 .ret_type = RET_INTEGER,
700 .arg1_type = ARG_PTR_TO_UNINIT_MEM,
701 .arg2_type = ARG_CONST_SIZE_OR_ZERO,
702 .arg3_type = ARG_ANYTHING,
703 .arg4_type = ARG_PTR_TO_BTF_ID,
704 .arg4_btf_id = &btf_tracing_ids[BTF_TRACING_TYPE_TASK],
705 .arg5_type = ARG_ANYTHING
706};
707
eaa6bcb7
HL
708BPF_CALL_2(bpf_per_cpu_ptr, const void *, ptr, u32, cpu)
709{
710 if (cpu >= nr_cpu_ids)
711 return (unsigned long)NULL;
712
713 return (unsigned long)per_cpu_ptr((const void __percpu *)ptr, cpu);
714}
715
716const struct bpf_func_proto bpf_per_cpu_ptr_proto = {
717 .func = bpf_per_cpu_ptr,
718 .gpl_only = false,
34d3a78c 719 .ret_type = RET_PTR_TO_MEM_OR_BTF_ID | PTR_MAYBE_NULL | MEM_RDONLY,
eaa6bcb7
HL
720 .arg1_type = ARG_PTR_TO_PERCPU_BTF_ID,
721 .arg2_type = ARG_ANYTHING,
722};
723
63d9b80d
HL
724BPF_CALL_1(bpf_this_cpu_ptr, const void *, percpu_ptr)
725{
726 return (unsigned long)this_cpu_ptr((const void __percpu *)percpu_ptr);
727}
728
729const struct bpf_func_proto bpf_this_cpu_ptr_proto = {
730 .func = bpf_this_cpu_ptr,
731 .gpl_only = false,
34d3a78c 732 .ret_type = RET_PTR_TO_MEM_OR_BTF_ID | MEM_RDONLY,
63d9b80d
HL
733 .arg1_type = ARG_PTR_TO_PERCPU_BTF_ID,
734};
735
d9c9e4db
FR
736static int bpf_trace_copy_string(char *buf, void *unsafe_ptr, char fmt_ptype,
737 size_t bufsz)
738{
739 void __user *user_ptr = (__force void __user *)unsafe_ptr;
740
741 buf[0] = 0;
742
743 switch (fmt_ptype) {
744 case 's':
745#ifdef CONFIG_ARCH_HAS_NON_OVERLAPPING_ADDRESS_SPACE
746 if ((unsigned long)unsafe_ptr < TASK_SIZE)
747 return strncpy_from_user_nofault(buf, user_ptr, bufsz);
748 fallthrough;
749#endif
750 case 'k':
751 return strncpy_from_kernel_nofault(buf, unsafe_ptr, bufsz);
752 case 'u':
753 return strncpy_from_user_nofault(buf, user_ptr, bufsz);
754 }
755
756 return -EINVAL;
757}
758
8afcc19f
FR
759/* Per-cpu temp buffers used by printf-like helpers to store the bprintf binary
760 * arguments representation.
d9c9e4db 761 */
e2bb9e01 762#define MAX_BPRINTF_BIN_ARGS 512
d9c9e4db 763
e2d5b2bb 764/* Support executing three nested bprintf helper calls on a given CPU */
0af02eb2 765#define MAX_BPRINTF_NEST_LEVEL 3
e2d5b2bb 766struct bpf_bprintf_buffers {
e2bb9e01
JO
767 char bin_args[MAX_BPRINTF_BIN_ARGS];
768 char buf[MAX_BPRINTF_BUF];
d9c9e4db 769};
e2bb9e01
JO
770
771static DEFINE_PER_CPU(struct bpf_bprintf_buffers[MAX_BPRINTF_NEST_LEVEL], bpf_bprintf_bufs);
e2d5b2bb 772static DEFINE_PER_CPU(int, bpf_bprintf_nest_level);
d9c9e4db 773
e2bb9e01 774static int try_get_buffers(struct bpf_bprintf_buffers **bufs)
d9c9e4db 775{
e2d5b2bb 776 int nest_level;
d9c9e4db 777
d9c9e4db 778 preempt_disable();
e2d5b2bb 779 nest_level = this_cpu_inc_return(bpf_bprintf_nest_level);
0af02eb2 780 if (WARN_ON_ONCE(nest_level > MAX_BPRINTF_NEST_LEVEL)) {
e2d5b2bb 781 this_cpu_dec(bpf_bprintf_nest_level);
d9c9e4db
FR
782 preempt_enable();
783 return -EBUSY;
784 }
e2bb9e01 785 *bufs = this_cpu_ptr(&bpf_bprintf_bufs[nest_level - 1]);
d9c9e4db
FR
786
787 return 0;
788}
789
f19a4050 790void bpf_bprintf_cleanup(struct bpf_bprintf_data *data)
d9c9e4db 791{
e2bb9e01 792 if (!data->bin_args && !data->buf)
f19a4050
JO
793 return;
794 if (WARN_ON_ONCE(this_cpu_read(bpf_bprintf_nest_level) == 0))
795 return;
796 this_cpu_dec(bpf_bprintf_nest_level);
797 preempt_enable();
d9c9e4db
FR
798}
799
800/*
48cac3f4 801 * bpf_bprintf_prepare - Generic pass on format strings for bprintf-like helpers
d9c9e4db
FR
802 *
803 * Returns a negative value if fmt is an invalid format string or 0 otherwise.
804 *
805 * This can be used in two ways:
78aa1cc9 806 * - Format string verification only: when data->get_bin_args is false
d9c9e4db 807 * - Arguments preparation: in addition to the above verification, it writes in
78aa1cc9
JO
808 * data->bin_args a binary representation of arguments usable by bstr_printf
809 * where pointers from BPF have been sanitized.
d9c9e4db
FR
810 *
811 * In argument preparation mode, if 0 is returned, safe temporary buffers are
48cac3f4 812 * allocated and bpf_bprintf_cleanup should be called to free them after use.
d9c9e4db 813 */
48cac3f4 814int bpf_bprintf_prepare(char *fmt, u32 fmt_size, const u64 *raw_args,
78aa1cc9 815 u32 num_args, struct bpf_bprintf_data *data)
48cac3f4 816{
e2bb9e01 817 bool get_buffers = (data->get_bin_args && num_args) || data->get_buf;
48cac3f4 818 char *unsafe_ptr = NULL, *tmp_buf = NULL, *tmp_buf_end, *fmt_end;
e2bb9e01 819 struct bpf_bprintf_buffers *buffers = NULL;
48cac3f4
FR
820 size_t sizeof_cur_arg, sizeof_cur_ip;
821 int err, i, num_spec = 0;
d9c9e4db 822 u64 cur_arg;
48cac3f4 823 char fmt_ptype, cur_ip[16], ip_spec[] = "%pXX";
d9c9e4db
FR
824
825 fmt_end = strnchr(fmt, fmt_size, 0);
826 if (!fmt_end)
827 return -EINVAL;
828 fmt_size = fmt_end - fmt;
829
e2bb9e01
JO
830 if (get_buffers && try_get_buffers(&buffers))
831 return -EBUSY;
48cac3f4 832
e2bb9e01
JO
833 if (data->get_bin_args) {
834 if (num_args)
835 tmp_buf = buffers->bin_args;
836 tmp_buf_end = tmp_buf + MAX_BPRINTF_BIN_ARGS;
78aa1cc9 837 data->bin_args = (u32 *)tmp_buf;
48cac3f4
FR
838 }
839
e2bb9e01
JO
840 if (data->get_buf)
841 data->buf = buffers->buf;
842
d9c9e4db
FR
843 for (i = 0; i < fmt_size; i++) {
844 if ((!isprint(fmt[i]) && !isspace(fmt[i])) || !isascii(fmt[i])) {
845 err = -EINVAL;
48cac3f4 846 goto out;
d9c9e4db
FR
847 }
848
849 if (fmt[i] != '%')
850 continue;
851
852 if (fmt[i + 1] == '%') {
853 i++;
854 continue;
855 }
856
857 if (num_spec >= num_args) {
858 err = -EINVAL;
48cac3f4 859 goto out;
d9c9e4db
FR
860 }
861
862 /* The string is zero-terminated so if fmt[i] != 0, we can
863 * always access fmt[i + 1], in the worst case it will be a 0
864 */
865 i++;
866
867 /* skip optional "[0 +-][num]" width formatting field */
868 while (fmt[i] == '0' || fmt[i] == '+' || fmt[i] == '-' ||
869 fmt[i] == ' ')
870 i++;
871 if (fmt[i] >= '1' && fmt[i] <= '9') {
872 i++;
873 while (fmt[i] >= '0' && fmt[i] <= '9')
874 i++;
875 }
876
877 if (fmt[i] == 'p') {
48cac3f4 878 sizeof_cur_arg = sizeof(long);
d9c9e4db
FR
879
880 if ((fmt[i + 1] == 'k' || fmt[i + 1] == 'u') &&
881 fmt[i + 2] == 's') {
882 fmt_ptype = fmt[i + 1];
883 i += 2;
884 goto fmt_str;
885 }
886
887 if (fmt[i + 1] == 0 || isspace(fmt[i + 1]) ||
888 ispunct(fmt[i + 1]) || fmt[i + 1] == 'K' ||
48cac3f4
FR
889 fmt[i + 1] == 'x' || fmt[i + 1] == 's' ||
890 fmt[i + 1] == 'S') {
d9c9e4db 891 /* just kernel pointers */
48cac3f4 892 if (tmp_buf)
d9c9e4db 893 cur_arg = raw_args[num_spec];
48cac3f4
FR
894 i++;
895 goto nocopy_fmt;
896 }
897
898 if (fmt[i + 1] == 'B') {
899 if (tmp_buf) {
900 err = snprintf(tmp_buf,
901 (tmp_buf_end - tmp_buf),
902 "%pB",
903 (void *)(long)raw_args[num_spec]);
904 tmp_buf += (err + 1);
905 }
906
907 i++;
908 num_spec++;
909 continue;
d9c9e4db
FR
910 }
911
912 /* only support "%pI4", "%pi4", "%pI6" and "%pi6". */
913 if ((fmt[i + 1] != 'i' && fmt[i + 1] != 'I') ||
914 (fmt[i + 2] != '4' && fmt[i + 2] != '6')) {
915 err = -EINVAL;
48cac3f4 916 goto out;
d9c9e4db
FR
917 }
918
919 i += 2;
48cac3f4
FR
920 if (!tmp_buf)
921 goto nocopy_fmt;
d9c9e4db 922
48cac3f4
FR
923 sizeof_cur_ip = (fmt[i] == '4') ? 4 : 16;
924 if (tmp_buf_end - tmp_buf < sizeof_cur_ip) {
d9c9e4db 925 err = -ENOSPC;
48cac3f4 926 goto out;
d9c9e4db
FR
927 }
928
929 unsafe_ptr = (char *)(long)raw_args[num_spec];
48cac3f4
FR
930 err = copy_from_kernel_nofault(cur_ip, unsafe_ptr,
931 sizeof_cur_ip);
d9c9e4db 932 if (err < 0)
48cac3f4 933 memset(cur_ip, 0, sizeof_cur_ip);
d9c9e4db 934
48cac3f4
FR
935 /* hack: bstr_printf expects IP addresses to be
936 * pre-formatted as strings, ironically, the easiest way
937 * to do that is to call snprintf.
938 */
939 ip_spec[2] = fmt[i - 1];
940 ip_spec[3] = fmt[i];
941 err = snprintf(tmp_buf, tmp_buf_end - tmp_buf,
942 ip_spec, &cur_ip);
943
944 tmp_buf += err + 1;
945 num_spec++;
946
947 continue;
d9c9e4db 948 } else if (fmt[i] == 's') {
d9c9e4db
FR
949 fmt_ptype = fmt[i];
950fmt_str:
951 if (fmt[i + 1] != 0 &&
952 !isspace(fmt[i + 1]) &&
953 !ispunct(fmt[i + 1])) {
954 err = -EINVAL;
d9c9e4db
FR
955 goto out;
956 }
957
48cac3f4
FR
958 if (!tmp_buf)
959 goto nocopy_fmt;
960
961 if (tmp_buf_end == tmp_buf) {
d9c9e4db 962 err = -ENOSPC;
48cac3f4 963 goto out;
d9c9e4db
FR
964 }
965
966 unsafe_ptr = (char *)(long)raw_args[num_spec];
967 err = bpf_trace_copy_string(tmp_buf, unsafe_ptr,
48cac3f4
FR
968 fmt_ptype,
969 tmp_buf_end - tmp_buf);
d9c9e4db
FR
970 if (err < 0) {
971 tmp_buf[0] = '\0';
972 err = 1;
973 }
974
d9c9e4db 975 tmp_buf += err;
48cac3f4 976 num_spec++;
d9c9e4db 977
3478cfcf
KI
978 continue;
979 } else if (fmt[i] == 'c') {
980 if (!tmp_buf)
981 goto nocopy_fmt;
982
983 if (tmp_buf_end == tmp_buf) {
984 err = -ENOSPC;
985 goto out;
986 }
987
988 *tmp_buf = raw_args[num_spec];
989 tmp_buf++;
990 num_spec++;
991
48cac3f4 992 continue;
d9c9e4db
FR
993 }
994
48cac3f4 995 sizeof_cur_arg = sizeof(int);
d9c9e4db
FR
996
997 if (fmt[i] == 'l') {
48cac3f4 998 sizeof_cur_arg = sizeof(long);
d9c9e4db
FR
999 i++;
1000 }
1001 if (fmt[i] == 'l') {
48cac3f4 1002 sizeof_cur_arg = sizeof(long long);
d9c9e4db
FR
1003 i++;
1004 }
1005
1006 if (fmt[i] != 'i' && fmt[i] != 'd' && fmt[i] != 'u' &&
1007 fmt[i] != 'x' && fmt[i] != 'X') {
1008 err = -EINVAL;
48cac3f4 1009 goto out;
d9c9e4db
FR
1010 }
1011
48cac3f4 1012 if (tmp_buf)
d9c9e4db 1013 cur_arg = raw_args[num_spec];
48cac3f4
FR
1014nocopy_fmt:
1015 if (tmp_buf) {
1016 tmp_buf = PTR_ALIGN(tmp_buf, sizeof(u32));
1017 if (tmp_buf_end - tmp_buf < sizeof_cur_arg) {
1018 err = -ENOSPC;
1019 goto out;
1020 }
1021
1022 if (sizeof_cur_arg == 8) {
1023 *(u32 *)tmp_buf = *(u32 *)&cur_arg;
1024 *(u32 *)(tmp_buf + 4) = *((u32 *)&cur_arg + 1);
1025 } else {
1026 *(u32 *)tmp_buf = (u32)(long)cur_arg;
1027 }
1028 tmp_buf += sizeof_cur_arg;
d9c9e4db
FR
1029 }
1030 num_spec++;
1031 }
1032
1033 err = 0;
d9c9e4db 1034out:
48cac3f4 1035 if (err)
f19a4050 1036 bpf_bprintf_cleanup(data);
d9c9e4db
FR
1037 return err;
1038}
1039
7b15523a 1040BPF_CALL_5(bpf_snprintf, char *, str, u32, str_size, char *, fmt,
78aa1cc9 1041 const void *, args, u32, data_len)
7b15523a 1042{
78aa1cc9
JO
1043 struct bpf_bprintf_data data = {
1044 .get_bin_args = true,
1045 };
7b15523a
FR
1046 int err, num_args;
1047
335ff499 1048 if (data_len % 8 || data_len > MAX_BPRINTF_VARARGS * 8 ||
78aa1cc9 1049 (data_len && !args))
7b15523a
FR
1050 return -EINVAL;
1051 num_args = data_len / 8;
1052
1053 /* ARG_PTR_TO_CONST_STR guarantees that fmt is zero-terminated so we
1054 * can safely give an unbounded size.
1055 */
78aa1cc9 1056 err = bpf_bprintf_prepare(fmt, UINT_MAX, args, num_args, &data);
7b15523a
FR
1057 if (err < 0)
1058 return err;
1059
78aa1cc9 1060 err = bstr_printf(str, str_size, fmt, data.bin_args);
48cac3f4 1061
f19a4050 1062 bpf_bprintf_cleanup(&data);
7b15523a
FR
1063
1064 return err + 1;
1065}
1066
1067const struct bpf_func_proto bpf_snprintf_proto = {
1068 .func = bpf_snprintf,
1069 .gpl_only = true,
1070 .ret_type = RET_INTEGER,
1071 .arg1_type = ARG_PTR_TO_MEM_OR_NULL,
1072 .arg2_type = ARG_CONST_SIZE_OR_ZERO,
1073 .arg3_type = ARG_PTR_TO_CONST_STR,
216e3cd2 1074 .arg4_type = ARG_PTR_TO_MEM | PTR_MAYBE_NULL | MEM_RDONLY,
7b15523a
FR
1075 .arg5_type = ARG_CONST_SIZE_OR_ZERO,
1076};
1077
b00628b1
AS
1078/* BPF map elements can contain 'struct bpf_timer'.
1079 * Such map owns all of its BPF timers.
1080 * 'struct bpf_timer' is allocated as part of map element allocation
1081 * and it's zero initialized.
1082 * That space is used to keep 'struct bpf_timer_kern'.
1083 * bpf_timer_init() allocates 'struct bpf_hrtimer', inits hrtimer, and
1084 * remembers 'struct bpf_map *' pointer it's part of.
1085 * bpf_timer_set_callback() increments prog refcnt and assign bpf callback_fn.
1086 * bpf_timer_start() arms the timer.
1087 * If user space reference to a map goes to zero at this point
1088 * ops->map_release_uref callback is responsible for cancelling the timers,
1089 * freeing their memory, and decrementing prog's refcnts.
1090 * bpf_timer_cancel() cancels the timer and decrements prog's refcnt.
1091 * Inner maps can contain bpf timers as well. ops->map_release_uref is
1092 * freeing the timers when inner map is replaced or deleted by user space.
1093 */
1094struct bpf_hrtimer {
1095 struct hrtimer timer;
1096 struct bpf_map *map;
1097 struct bpf_prog *prog;
1098 void __rcu *callback_fn;
1099 void *value;
1100};
1101
1102/* the actual struct hidden inside uapi struct bpf_timer */
1103struct bpf_timer_kern {
1104 struct bpf_hrtimer *timer;
1105 /* bpf_spin_lock is used here instead of spinlock_t to make
c561d110 1106 * sure that it always fits into space reserved by struct bpf_timer
b00628b1
AS
1107 * regardless of LOCKDEP and spinlock debug flags.
1108 */
1109 struct bpf_spin_lock lock;
1110} __attribute__((aligned(8)));
1111
1112static DEFINE_PER_CPU(struct bpf_hrtimer *, hrtimer_running);
1113
1114static enum hrtimer_restart bpf_timer_cb(struct hrtimer *hrtimer)
1115{
1116 struct bpf_hrtimer *t = container_of(hrtimer, struct bpf_hrtimer, timer);
1117 struct bpf_map *map = t->map;
1118 void *value = t->value;
102acbac 1119 bpf_callback_t callback_fn;
b00628b1
AS
1120 void *key;
1121 u32 idx;
b00628b1 1122
3bd916ee 1123 BTF_TYPE_EMIT(struct bpf_timer);
b00628b1
AS
1124 callback_fn = rcu_dereference_check(t->callback_fn, rcu_read_lock_bh_held());
1125 if (!callback_fn)
1126 goto out;
1127
1128 /* bpf_timer_cb() runs in hrtimer_run_softirq. It doesn't migrate and
1129 * cannot be preempted by another bpf_timer_cb() on the same cpu.
1130 * Remember the timer this callback is servicing to prevent
1131 * deadlock if callback_fn() calls bpf_timer_cancel() or
1132 * bpf_map_delete_elem() on the same timer.
1133 */
1134 this_cpu_write(hrtimer_running, t);
1135 if (map->map_type == BPF_MAP_TYPE_ARRAY) {
1136 struct bpf_array *array = container_of(map, struct bpf_array, map);
1137
1138 /* compute the key */
1139 idx = ((char *)value - array->value) / array->elem_size;
1140 key = &idx;
1141 } else { /* hash or lru */
1142 key = value - round_up(map->key_size, 8);
1143 }
1144
102acbac 1145 callback_fn((u64)(long)map, (u64)(long)key, (u64)(long)value, 0, 0);
bfc6bb74 1146 /* The verifier checked that return value is zero. */
b00628b1
AS
1147
1148 this_cpu_write(hrtimer_running, NULL);
1149out:
1150 return HRTIMER_NORESTART;
1151}
1152
1153BPF_CALL_3(bpf_timer_init, struct bpf_timer_kern *, timer, struct bpf_map *, map,
1154 u64, flags)
1155{
1156 clockid_t clockid = flags & (MAX_CLOCKS - 1);
1157 struct bpf_hrtimer *t;
1158 int ret = 0;
1159
1160 BUILD_BUG_ON(MAX_CLOCKS != 16);
1161 BUILD_BUG_ON(sizeof(struct bpf_timer_kern) > sizeof(struct bpf_timer));
1162 BUILD_BUG_ON(__alignof__(struct bpf_timer_kern) != __alignof__(struct bpf_timer));
1163
1164 if (in_nmi())
1165 return -EOPNOTSUPP;
1166
1167 if (flags >= MAX_CLOCKS ||
1168 /* similar to timerfd except _ALARM variants are not supported */
1169 (clockid != CLOCK_MONOTONIC &&
1170 clockid != CLOCK_REALTIME &&
1171 clockid != CLOCK_BOOTTIME))
1172 return -EINVAL;
1173 __bpf_spin_lock_irqsave(&timer->lock);
1174 t = timer->timer;
1175 if (t) {
1176 ret = -EBUSY;
1177 goto out;
1178 }
1179 if (!atomic64_read(&map->usercnt)) {
1180 /* maps with timers must be either held by user space
1181 * or pinned in bpffs.
1182 */
1183 ret = -EPERM;
1184 goto out;
1185 }
1186 /* allocate hrtimer via map_kmalloc to use memcg accounting */
1187 t = bpf_map_kmalloc_node(map, sizeof(*t), GFP_ATOMIC, map->numa_node);
1188 if (!t) {
1189 ret = -ENOMEM;
1190 goto out;
1191 }
db559117 1192 t->value = (void *)timer - map->record->timer_off;
b00628b1
AS
1193 t->map = map;
1194 t->prog = NULL;
1195 rcu_assign_pointer(t->callback_fn, NULL);
1196 hrtimer_init(&t->timer, clockid, HRTIMER_MODE_REL_SOFT);
1197 t->timer.function = bpf_timer_cb;
1198 timer->timer = t;
1199out:
1200 __bpf_spin_unlock_irqrestore(&timer->lock);
1201 return ret;
1202}
1203
1204static const struct bpf_func_proto bpf_timer_init_proto = {
1205 .func = bpf_timer_init,
1206 .gpl_only = true,
1207 .ret_type = RET_INTEGER,
1208 .arg1_type = ARG_PTR_TO_TIMER,
1209 .arg2_type = ARG_CONST_MAP_PTR,
1210 .arg3_type = ARG_ANYTHING,
1211};
1212
1213BPF_CALL_3(bpf_timer_set_callback, struct bpf_timer_kern *, timer, void *, callback_fn,
1214 struct bpf_prog_aux *, aux)
1215{
1216 struct bpf_prog *prev, *prog = aux->prog;
1217 struct bpf_hrtimer *t;
1218 int ret = 0;
1219
1220 if (in_nmi())
1221 return -EOPNOTSUPP;
1222 __bpf_spin_lock_irqsave(&timer->lock);
1223 t = timer->timer;
1224 if (!t) {
1225 ret = -EINVAL;
1226 goto out;
1227 }
1228 if (!atomic64_read(&t->map->usercnt)) {
1229 /* maps with timers must be either held by user space
1230 * or pinned in bpffs. Otherwise timer might still be
1231 * running even when bpf prog is detached and user space
1232 * is gone, since map_release_uref won't ever be called.
1233 */
1234 ret = -EPERM;
1235 goto out;
1236 }
1237 prev = t->prog;
1238 if (prev != prog) {
1239 /* Bump prog refcnt once. Every bpf_timer_set_callback()
1240 * can pick different callback_fn-s within the same prog.
1241 */
1242 prog = bpf_prog_inc_not_zero(prog);
1243 if (IS_ERR(prog)) {
1244 ret = PTR_ERR(prog);
1245 goto out;
1246 }
1247 if (prev)
1248 /* Drop prev prog refcnt when swapping with new prog */
1249 bpf_prog_put(prev);
1250 t->prog = prog;
1251 }
1252 rcu_assign_pointer(t->callback_fn, callback_fn);
1253out:
1254 __bpf_spin_unlock_irqrestore(&timer->lock);
1255 return ret;
1256}
1257
1258static const struct bpf_func_proto bpf_timer_set_callback_proto = {
1259 .func = bpf_timer_set_callback,
1260 .gpl_only = true,
1261 .ret_type = RET_INTEGER,
1262 .arg1_type = ARG_PTR_TO_TIMER,
1263 .arg2_type = ARG_PTR_TO_FUNC,
1264};
1265
1266BPF_CALL_3(bpf_timer_start, struct bpf_timer_kern *, timer, u64, nsecs, u64, flags)
1267{
1268 struct bpf_hrtimer *t;
1269 int ret = 0;
f71f8530 1270 enum hrtimer_mode mode;
b00628b1
AS
1271
1272 if (in_nmi())
1273 return -EOPNOTSUPP;
f71f8530 1274 if (flags > BPF_F_TIMER_ABS)
b00628b1
AS
1275 return -EINVAL;
1276 __bpf_spin_lock_irqsave(&timer->lock);
1277 t = timer->timer;
1278 if (!t || !t->prog) {
1279 ret = -EINVAL;
1280 goto out;
1281 }
f71f8530
TK
1282
1283 if (flags & BPF_F_TIMER_ABS)
1284 mode = HRTIMER_MODE_ABS_SOFT;
1285 else
1286 mode = HRTIMER_MODE_REL_SOFT;
1287
1288 hrtimer_start(&t->timer, ns_to_ktime(nsecs), mode);
b00628b1
AS
1289out:
1290 __bpf_spin_unlock_irqrestore(&timer->lock);
1291 return ret;
1292}
1293
1294static const struct bpf_func_proto bpf_timer_start_proto = {
1295 .func = bpf_timer_start,
1296 .gpl_only = true,
1297 .ret_type = RET_INTEGER,
1298 .arg1_type = ARG_PTR_TO_TIMER,
1299 .arg2_type = ARG_ANYTHING,
1300 .arg3_type = ARG_ANYTHING,
1301};
1302
1303static void drop_prog_refcnt(struct bpf_hrtimer *t)
1304{
1305 struct bpf_prog *prog = t->prog;
1306
1307 if (prog) {
1308 bpf_prog_put(prog);
1309 t->prog = NULL;
1310 rcu_assign_pointer(t->callback_fn, NULL);
1311 }
1312}
1313
1314BPF_CALL_1(bpf_timer_cancel, struct bpf_timer_kern *, timer)
1315{
1316 struct bpf_hrtimer *t;
1317 int ret = 0;
1318
1319 if (in_nmi())
1320 return -EOPNOTSUPP;
1321 __bpf_spin_lock_irqsave(&timer->lock);
1322 t = timer->timer;
1323 if (!t) {
1324 ret = -EINVAL;
1325 goto out;
1326 }
1327 if (this_cpu_read(hrtimer_running) == t) {
1328 /* If bpf callback_fn is trying to bpf_timer_cancel()
1329 * its own timer the hrtimer_cancel() will deadlock
1330 * since it waits for callback_fn to finish
1331 */
1332 ret = -EDEADLK;
1333 goto out;
1334 }
1335 drop_prog_refcnt(t);
1336out:
1337 __bpf_spin_unlock_irqrestore(&timer->lock);
1338 /* Cancel the timer and wait for associated callback to finish
1339 * if it was running.
1340 */
1341 ret = ret ?: hrtimer_cancel(&t->timer);
1342 return ret;
1343}
1344
1345static const struct bpf_func_proto bpf_timer_cancel_proto = {
1346 .func = bpf_timer_cancel,
1347 .gpl_only = true,
1348 .ret_type = RET_INTEGER,
1349 .arg1_type = ARG_PTR_TO_TIMER,
1350};
1351
1352/* This function is called by map_delete/update_elem for individual element and
1353 * by ops->map_release_uref when the user space reference to a map reaches zero.
1354 */
1355void bpf_timer_cancel_and_free(void *val)
1356{
1357 struct bpf_timer_kern *timer = val;
1358 struct bpf_hrtimer *t;
1359
1360 /* Performance optimization: read timer->timer without lock first. */
1361 if (!READ_ONCE(timer->timer))
1362 return;
1363
1364 __bpf_spin_lock_irqsave(&timer->lock);
1365 /* re-read it under lock */
1366 t = timer->timer;
1367 if (!t)
1368 goto out;
1369 drop_prog_refcnt(t);
1370 /* The subsequent bpf_timer_start/cancel() helpers won't be able to use
1371 * this timer, since it won't be initialized.
1372 */
1373 timer->timer = NULL;
1374out:
1375 __bpf_spin_unlock_irqrestore(&timer->lock);
1376 if (!t)
1377 return;
1378 /* Cancel the timer and wait for callback to complete if it was running.
1379 * If hrtimer_cancel() can be safely called it's safe to call kfree(t)
1380 * right after for both preallocated and non-preallocated maps.
1381 * The timer->timer = NULL was already done and no code path can
1382 * see address 't' anymore.
1383 *
1384 * Check that bpf_map_delete/update_elem() wasn't called from timer
1385 * callback_fn. In such case don't call hrtimer_cancel() (since it will
1386 * deadlock) and don't call hrtimer_try_to_cancel() (since it will just
1387 * return -1). Though callback_fn is still running on this cpu it's
1388 * safe to do kfree(t) because bpf_timer_cb() read everything it needed
1389 * from 't'. The bpf subprog callback_fn won't be able to access 't',
1390 * since timer->timer = NULL was already done. The timer will be
1391 * effectively cancelled because bpf_timer_cb() will return
1392 * HRTIMER_NORESTART.
1393 */
1394 if (this_cpu_read(hrtimer_running) != t)
1395 hrtimer_cancel(&t->timer);
1396 kfree(t);
1397}
1398
c0a5a21c
KKD
1399BPF_CALL_2(bpf_kptr_xchg, void *, map_value, void *, ptr)
1400{
1401 unsigned long *kptr = map_value;
1402
1403 return xchg(kptr, (unsigned long)ptr);
1404}
1405
1406/* Unlike other PTR_TO_BTF_ID helpers the btf_id in bpf_kptr_xchg()
47e34cb7
DM
1407 * helper is determined dynamically by the verifier. Use BPF_PTR_POISON to
1408 * denote type that verifier will determine.
c0a5a21c 1409 */
dc368e1c 1410static const struct bpf_func_proto bpf_kptr_xchg_proto = {
c0a5a21c
KKD
1411 .func = bpf_kptr_xchg,
1412 .gpl_only = false,
1413 .ret_type = RET_PTR_TO_BTF_ID_OR_NULL,
1414 .ret_btf_id = BPF_PTR_POISON,
1415 .arg1_type = ARG_PTR_TO_KPTR,
1416 .arg2_type = ARG_PTR_TO_BTF_ID_OR_NULL | OBJ_RELEASE,
1417 .arg2_btf_id = BPF_PTR_POISON,
1418};
1419
263ae152
JK
1420/* Since the upper 8 bits of dynptr->size is reserved, the
1421 * maximum supported size is 2^24 - 1.
1422 */
1423#define DYNPTR_MAX_SIZE ((1UL << 24) - 1)
1424#define DYNPTR_TYPE_SHIFT 28
13bbbfbe
JK
1425#define DYNPTR_SIZE_MASK 0xFFFFFF
1426#define DYNPTR_RDONLY_BIT BIT(31)
1427
540ccf96 1428static bool __bpf_dynptr_is_rdonly(const struct bpf_dynptr_kern *ptr)
13bbbfbe
JK
1429{
1430 return ptr->size & DYNPTR_RDONLY_BIT;
1431}
263ae152 1432
b5964b96
JK
1433void bpf_dynptr_set_rdonly(struct bpf_dynptr_kern *ptr)
1434{
1435 ptr->size |= DYNPTR_RDONLY_BIT;
1436}
1437
263ae152
JK
1438static void bpf_dynptr_set_type(struct bpf_dynptr_kern *ptr, enum bpf_dynptr_type type)
1439{
1440 ptr->size |= type << DYNPTR_TYPE_SHIFT;
1441}
1442
b5964b96
JK
1443static enum bpf_dynptr_type bpf_dynptr_get_type(const struct bpf_dynptr_kern *ptr)
1444{
1445 return (ptr->size & ~(DYNPTR_RDONLY_BIT)) >> DYNPTR_TYPE_SHIFT;
1446}
1447
26662d73 1448u32 __bpf_dynptr_size(const struct bpf_dynptr_kern *ptr)
13bbbfbe
JK
1449{
1450 return ptr->size & DYNPTR_SIZE_MASK;
1451}
1452
987d0242
JK
1453static void bpf_dynptr_set_size(struct bpf_dynptr_kern *ptr, u32 new_size)
1454{
1455 u32 metadata = ptr->size & ~DYNPTR_SIZE_MASK;
1456
1457 ptr->size = new_size | metadata;
1458}
1459
bc34dee6 1460int bpf_dynptr_check_size(u32 size)
263ae152
JK
1461{
1462 return size > DYNPTR_MAX_SIZE ? -E2BIG : 0;
1463}
1464
bc34dee6
JK
1465void bpf_dynptr_init(struct bpf_dynptr_kern *ptr, void *data,
1466 enum bpf_dynptr_type type, u32 offset, u32 size)
263ae152
JK
1467{
1468 ptr->data = data;
1469 ptr->offset = offset;
1470 ptr->size = size;
1471 bpf_dynptr_set_type(ptr, type);
1472}
1473
bc34dee6 1474void bpf_dynptr_set_null(struct bpf_dynptr_kern *ptr)
263ae152
JK
1475{
1476 memset(ptr, 0, sizeof(*ptr));
1477}
1478
27060531 1479static int bpf_dynptr_check_off_len(const struct bpf_dynptr_kern *ptr, u32 offset, u32 len)
13bbbfbe 1480{
26662d73 1481 u32 size = __bpf_dynptr_size(ptr);
13bbbfbe
JK
1482
1483 if (len > size || offset > size - len)
1484 return -E2BIG;
1485
1486 return 0;
1487}
1488
263ae152
JK
1489BPF_CALL_4(bpf_dynptr_from_mem, void *, data, u32, size, u64, flags, struct bpf_dynptr_kern *, ptr)
1490{
1491 int err;
1492
00f14641
RS
1493 BTF_TYPE_EMIT(struct bpf_dynptr);
1494
263ae152
JK
1495 err = bpf_dynptr_check_size(size);
1496 if (err)
1497 goto error;
1498
1499 /* flags is currently unsupported */
1500 if (flags) {
1501 err = -EINVAL;
1502 goto error;
1503 }
1504
1505 bpf_dynptr_init(ptr, data, BPF_DYNPTR_TYPE_LOCAL, 0, size);
1506
1507 return 0;
1508
1509error:
1510 bpf_dynptr_set_null(ptr);
1511 return err;
1512}
1513
dc368e1c 1514static const struct bpf_func_proto bpf_dynptr_from_mem_proto = {
263ae152
JK
1515 .func = bpf_dynptr_from_mem,
1516 .gpl_only = false,
1517 .ret_type = RET_INTEGER,
1518 .arg1_type = ARG_PTR_TO_UNINIT_MEM,
1519 .arg2_type = ARG_CONST_SIZE_OR_ZERO,
1520 .arg3_type = ARG_ANYTHING,
1521 .arg4_type = ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_LOCAL | MEM_UNINIT,
1522};
1523
27060531 1524BPF_CALL_5(bpf_dynptr_read, void *, dst, u32, len, const struct bpf_dynptr_kern *, src,
f8d3da4e 1525 u32, offset, u64, flags)
13bbbfbe 1526{
b5964b96 1527 enum bpf_dynptr_type type;
13bbbfbe
JK
1528 int err;
1529
f8d3da4e 1530 if (!src->data || flags)
13bbbfbe
JK
1531 return -EINVAL;
1532
1533 err = bpf_dynptr_check_off_len(src, offset, len);
1534 if (err)
1535 return err;
1536
b5964b96 1537 type = bpf_dynptr_get_type(src);
13bbbfbe 1538
b5964b96
JK
1539 switch (type) {
1540 case BPF_DYNPTR_TYPE_LOCAL:
1541 case BPF_DYNPTR_TYPE_RINGBUF:
1542 /* Source and destination may possibly overlap, hence use memmove to
1543 * copy the data. E.g. bpf_dynptr_from_mem may create two dynptr
1544 * pointing to overlapping PTR_TO_MAP_VALUE regions.
1545 */
1546 memmove(dst, src->data + src->offset + offset, len);
1547 return 0;
1548 case BPF_DYNPTR_TYPE_SKB:
1549 return __bpf_skb_load_bytes(src->data, src->offset + offset, dst, len);
05421aec
JK
1550 case BPF_DYNPTR_TYPE_XDP:
1551 return __bpf_xdp_load_bytes(src->data, src->offset + offset, dst, len);
b5964b96
JK
1552 default:
1553 WARN_ONCE(true, "bpf_dynptr_read: unknown dynptr type %d\n", type);
1554 return -EFAULT;
1555 }
13bbbfbe
JK
1556}
1557
dc368e1c 1558static const struct bpf_func_proto bpf_dynptr_read_proto = {
13bbbfbe
JK
1559 .func = bpf_dynptr_read,
1560 .gpl_only = false,
1561 .ret_type = RET_INTEGER,
1562 .arg1_type = ARG_PTR_TO_UNINIT_MEM,
1563 .arg2_type = ARG_CONST_SIZE_OR_ZERO,
27060531 1564 .arg3_type = ARG_PTR_TO_DYNPTR | MEM_RDONLY,
13bbbfbe 1565 .arg4_type = ARG_ANYTHING,
f8d3da4e 1566 .arg5_type = ARG_ANYTHING,
13bbbfbe
JK
1567};
1568
27060531 1569BPF_CALL_5(bpf_dynptr_write, const struct bpf_dynptr_kern *, dst, u32, offset, void *, src,
f8d3da4e 1570 u32, len, u64, flags)
13bbbfbe 1571{
b5964b96 1572 enum bpf_dynptr_type type;
13bbbfbe
JK
1573 int err;
1574
540ccf96 1575 if (!dst->data || __bpf_dynptr_is_rdonly(dst))
13bbbfbe
JK
1576 return -EINVAL;
1577
1578 err = bpf_dynptr_check_off_len(dst, offset, len);
1579 if (err)
1580 return err;
1581
b5964b96 1582 type = bpf_dynptr_get_type(dst);
13bbbfbe 1583
b5964b96
JK
1584 switch (type) {
1585 case BPF_DYNPTR_TYPE_LOCAL:
1586 case BPF_DYNPTR_TYPE_RINGBUF:
1587 if (flags)
1588 return -EINVAL;
1589 /* Source and destination may possibly overlap, hence use memmove to
1590 * copy the data. E.g. bpf_dynptr_from_mem may create two dynptr
1591 * pointing to overlapping PTR_TO_MAP_VALUE regions.
1592 */
1593 memmove(dst->data + dst->offset + offset, src, len);
1594 return 0;
1595 case BPF_DYNPTR_TYPE_SKB:
1596 return __bpf_skb_store_bytes(dst->data, dst->offset + offset, src, len,
1597 flags);
05421aec
JK
1598 case BPF_DYNPTR_TYPE_XDP:
1599 if (flags)
1600 return -EINVAL;
1601 return __bpf_xdp_store_bytes(dst->data, dst->offset + offset, src, len);
b5964b96
JK
1602 default:
1603 WARN_ONCE(true, "bpf_dynptr_write: unknown dynptr type %d\n", type);
1604 return -EFAULT;
1605 }
13bbbfbe
JK
1606}
1607
dc368e1c 1608static const struct bpf_func_proto bpf_dynptr_write_proto = {
13bbbfbe
JK
1609 .func = bpf_dynptr_write,
1610 .gpl_only = false,
1611 .ret_type = RET_INTEGER,
27060531 1612 .arg1_type = ARG_PTR_TO_DYNPTR | MEM_RDONLY,
13bbbfbe
JK
1613 .arg2_type = ARG_ANYTHING,
1614 .arg3_type = ARG_PTR_TO_MEM | MEM_RDONLY,
1615 .arg4_type = ARG_CONST_SIZE_OR_ZERO,
f8d3da4e 1616 .arg5_type = ARG_ANYTHING,
13bbbfbe
JK
1617};
1618
27060531 1619BPF_CALL_3(bpf_dynptr_data, const struct bpf_dynptr_kern *, ptr, u32, offset, u32, len)
34d4ef57 1620{
b5964b96 1621 enum bpf_dynptr_type type;
34d4ef57
JK
1622 int err;
1623
1624 if (!ptr->data)
1625 return 0;
1626
1627 err = bpf_dynptr_check_off_len(ptr, offset, len);
1628 if (err)
1629 return 0;
1630
540ccf96 1631 if (__bpf_dynptr_is_rdonly(ptr))
34d4ef57
JK
1632 return 0;
1633
b5964b96
JK
1634 type = bpf_dynptr_get_type(ptr);
1635
1636 switch (type) {
1637 case BPF_DYNPTR_TYPE_LOCAL:
1638 case BPF_DYNPTR_TYPE_RINGBUF:
1639 return (unsigned long)(ptr->data + ptr->offset + offset);
1640 case BPF_DYNPTR_TYPE_SKB:
05421aec
JK
1641 case BPF_DYNPTR_TYPE_XDP:
1642 /* skb and xdp dynptrs should use bpf_dynptr_slice / bpf_dynptr_slice_rdwr */
b5964b96
JK
1643 return 0;
1644 default:
1645 WARN_ONCE(true, "bpf_dynptr_data: unknown dynptr type %d\n", type);
1646 return 0;
1647 }
34d4ef57
JK
1648}
1649
dc368e1c 1650static const struct bpf_func_proto bpf_dynptr_data_proto = {
34d4ef57
JK
1651 .func = bpf_dynptr_data,
1652 .gpl_only = false,
1653 .ret_type = RET_PTR_TO_DYNPTR_MEM_OR_NULL,
27060531 1654 .arg1_type = ARG_PTR_TO_DYNPTR | MEM_RDONLY,
34d4ef57
JK
1655 .arg2_type = ARG_ANYTHING,
1656 .arg3_type = ARG_CONST_ALLOC_SIZE_OR_ZERO,
1657};
1658
f470378c 1659const struct bpf_func_proto bpf_get_current_task_proto __weak;
a396eda5 1660const struct bpf_func_proto bpf_get_current_task_btf_proto __weak;
f470378c
JF
1661const struct bpf_func_proto bpf_probe_read_user_proto __weak;
1662const struct bpf_func_proto bpf_probe_read_user_str_proto __weak;
1663const struct bpf_func_proto bpf_probe_read_kernel_proto __weak;
1664const struct bpf_func_proto bpf_probe_read_kernel_str_proto __weak;
dd6e10fb 1665const struct bpf_func_proto bpf_task_pt_regs_proto __weak;
f470378c 1666
6890896b
SF
1667const struct bpf_func_proto *
1668bpf_base_func_proto(enum bpf_func_id func_id)
1669{
1670 switch (func_id) {
1671 case BPF_FUNC_map_lookup_elem:
1672 return &bpf_map_lookup_elem_proto;
1673 case BPF_FUNC_map_update_elem:
1674 return &bpf_map_update_elem_proto;
1675 case BPF_FUNC_map_delete_elem:
1676 return &bpf_map_delete_elem_proto;
1677 case BPF_FUNC_map_push_elem:
1678 return &bpf_map_push_elem_proto;
1679 case BPF_FUNC_map_pop_elem:
1680 return &bpf_map_pop_elem_proto;
1681 case BPF_FUNC_map_peek_elem:
1682 return &bpf_map_peek_elem_proto;
07343110
FZ
1683 case BPF_FUNC_map_lookup_percpu_elem:
1684 return &bpf_map_lookup_percpu_elem_proto;
6890896b
SF
1685 case BPF_FUNC_get_prandom_u32:
1686 return &bpf_get_prandom_u32_proto;
1687 case BPF_FUNC_get_smp_processor_id:
1688 return &bpf_get_raw_smp_processor_id_proto;
1689 case BPF_FUNC_get_numa_node_id:
1690 return &bpf_get_numa_node_id_proto;
1691 case BPF_FUNC_tail_call:
1692 return &bpf_tail_call_proto;
1693 case BPF_FUNC_ktime_get_ns:
1694 return &bpf_ktime_get_ns_proto;
71d19214
1695 case BPF_FUNC_ktime_get_boot_ns:
1696 return &bpf_ktime_get_boot_ns_proto;
c8996c98
JDB
1697 case BPF_FUNC_ktime_get_tai_ns:
1698 return &bpf_ktime_get_tai_ns_proto;
457f4436
AN
1699 case BPF_FUNC_ringbuf_output:
1700 return &bpf_ringbuf_output_proto;
1701 case BPF_FUNC_ringbuf_reserve:
1702 return &bpf_ringbuf_reserve_proto;
1703 case BPF_FUNC_ringbuf_submit:
1704 return &bpf_ringbuf_submit_proto;
1705 case BPF_FUNC_ringbuf_discard:
1706 return &bpf_ringbuf_discard_proto;
1707 case BPF_FUNC_ringbuf_query:
1708 return &bpf_ringbuf_query_proto;
c5fb1993
HT
1709 case BPF_FUNC_strncmp:
1710 return &bpf_strncmp_proto;
8a67f2de
SF
1711 case BPF_FUNC_strtol:
1712 return &bpf_strtol_proto;
1713 case BPF_FUNC_strtoul:
1714 return &bpf_strtoul_proto;
6890896b
SF
1715 default:
1716 break;
1717 }
1718
2c78ee89 1719 if (!bpf_capable())
6890896b
SF
1720 return NULL;
1721
1722 switch (func_id) {
1723 case BPF_FUNC_spin_lock:
1724 return &bpf_spin_lock_proto;
1725 case BPF_FUNC_spin_unlock:
1726 return &bpf_spin_unlock_proto;
6890896b
SF
1727 case BPF_FUNC_jiffies64:
1728 return &bpf_jiffies64_proto;
b7906b70 1729 case BPF_FUNC_per_cpu_ptr:
eaa6bcb7 1730 return &bpf_per_cpu_ptr_proto;
b7906b70 1731 case BPF_FUNC_this_cpu_ptr:
63d9b80d 1732 return &bpf_this_cpu_ptr_proto;
b00628b1
AS
1733 case BPF_FUNC_timer_init:
1734 return &bpf_timer_init_proto;
1735 case BPF_FUNC_timer_set_callback:
1736 return &bpf_timer_set_callback_proto;
1737 case BPF_FUNC_timer_start:
1738 return &bpf_timer_start_proto;
1739 case BPF_FUNC_timer_cancel:
1740 return &bpf_timer_cancel_proto;
c0a5a21c
KKD
1741 case BPF_FUNC_kptr_xchg:
1742 return &bpf_kptr_xchg_proto;
5679ff2f
KKD
1743 case BPF_FUNC_for_each_map_elem:
1744 return &bpf_for_each_map_elem_proto;
1745 case BPF_FUNC_loop:
1746 return &bpf_loop_proto;
20571567
DV
1747 case BPF_FUNC_user_ringbuf_drain:
1748 return &bpf_user_ringbuf_drain_proto;
8addbfc7
KKD
1749 case BPF_FUNC_ringbuf_reserve_dynptr:
1750 return &bpf_ringbuf_reserve_dynptr_proto;
1751 case BPF_FUNC_ringbuf_submit_dynptr:
1752 return &bpf_ringbuf_submit_dynptr_proto;
1753 case BPF_FUNC_ringbuf_discard_dynptr:
1754 return &bpf_ringbuf_discard_dynptr_proto;
1755 case BPF_FUNC_dynptr_from_mem:
1756 return &bpf_dynptr_from_mem_proto;
1757 case BPF_FUNC_dynptr_read:
1758 return &bpf_dynptr_read_proto;
1759 case BPF_FUNC_dynptr_write:
1760 return &bpf_dynptr_write_proto;
1761 case BPF_FUNC_dynptr_data:
1762 return &bpf_dynptr_data_proto;
c4bcfb38
YS
1763#ifdef CONFIG_CGROUPS
1764 case BPF_FUNC_cgrp_storage_get:
1765 return &bpf_cgrp_storage_get_proto;
1766 case BPF_FUNC_cgrp_storage_delete:
1767 return &bpf_cgrp_storage_delete_proto;
c501bf55
TH
1768 case BPF_FUNC_get_current_cgroup_id:
1769 return &bpf_get_current_cgroup_id_proto;
1770 case BPF_FUNC_get_current_ancestor_cgroup_id:
1771 return &bpf_get_current_ancestor_cgroup_id_proto;
c4bcfb38 1772#endif
f470378c
JF
1773 default:
1774 break;
1775 }
1776
1777 if (!perfmon_capable())
1778 return NULL;
1779
1780 switch (func_id) {
61ca36c8
TK
1781 case BPF_FUNC_trace_printk:
1782 return bpf_get_trace_printk_proto();
f470378c
JF
1783 case BPF_FUNC_get_current_task:
1784 return &bpf_get_current_task_proto;
a396eda5
DX
1785 case BPF_FUNC_get_current_task_btf:
1786 return &bpf_get_current_task_btf_proto;
f470378c
JF
1787 case BPF_FUNC_probe_read_user:
1788 return &bpf_probe_read_user_proto;
1789 case BPF_FUNC_probe_read_kernel:
71330842 1790 return security_locked_down(LOCKDOWN_BPF_READ_KERNEL) < 0 ?
ff40e510 1791 NULL : &bpf_probe_read_kernel_proto;
f470378c
JF
1792 case BPF_FUNC_probe_read_user_str:
1793 return &bpf_probe_read_user_str_proto;
1794 case BPF_FUNC_probe_read_kernel_str:
71330842 1795 return security_locked_down(LOCKDOWN_BPF_READ_KERNEL) < 0 ?
ff40e510 1796 NULL : &bpf_probe_read_kernel_str_proto;
61ca36c8
TK
1797 case BPF_FUNC_snprintf_btf:
1798 return &bpf_snprintf_btf_proto;
7b15523a
FR
1799 case BPF_FUNC_snprintf:
1800 return &bpf_snprintf_proto;
dd6e10fb
DX
1801 case BPF_FUNC_task_pt_regs:
1802 return &bpf_task_pt_regs_proto;
10aceb62
DM
1803 case BPF_FUNC_trace_vprintk:
1804 return bpf_get_trace_vprintk_proto();
6890896b
SF
1805 default:
1806 return NULL;
1807 }
1808}
13379059 1809
1512217c
DM
1810void __bpf_obj_drop_impl(void *p, const struct btf_record *rec);
1811
f0c5941f
KKD
1812void bpf_list_head_free(const struct btf_field *field, void *list_head,
1813 struct bpf_spin_lock *spin_lock)
1814{
1815 struct list_head *head = list_head, *orig_head = list_head;
1816
1817 BUILD_BUG_ON(sizeof(struct list_head) > sizeof(struct bpf_list_head));
1818 BUILD_BUG_ON(__alignof__(struct list_head) > __alignof__(struct bpf_list_head));
1819
1820 /* Do the actual list draining outside the lock to not hold the lock for
1821 * too long, and also prevent deadlocks if tracing programs end up
1822 * executing on entry/exit of functions called inside the critical
1823 * section, and end up doing map ops that call bpf_list_head_free for
1824 * the same map value again.
1825 */
1826 __bpf_spin_lock_irqsave(spin_lock);
1827 if (!head->next || list_empty(head))
1828 goto unlock;
1829 head = head->next;
1830unlock:
1831 INIT_LIST_HEAD(orig_head);
1832 __bpf_spin_unlock_irqrestore(spin_lock);
1833
1834 while (head != orig_head) {
1835 void *obj = head;
1836
30465003 1837 obj -= field->graph_root.node_offset;
f0c5941f 1838 head = head->next;
958cf2e2
KKD
1839 /* The contained type can also have resources, including a
1840 * bpf_list_head which needs to be freed.
1841 */
958cf2e2 1842 migrate_disable();
1512217c 1843 __bpf_obj_drop_impl(obj, field->graph_root.value_rec);
958cf2e2 1844 migrate_enable();
f0c5941f
KKD
1845 }
1846}
1847
9c395c1b
DM
1848/* Like rbtree_postorder_for_each_entry_safe, but 'pos' and 'n' are
1849 * 'rb_node *', so field name of rb_node within containing struct is not
1850 * needed.
1851 *
1852 * Since bpf_rb_tree's node type has a corresponding struct btf_field with
1853 * graph_root.node_offset, it's not necessary to know field name
1854 * or type of node struct
1855 */
1856#define bpf_rbtree_postorder_for_each_entry_safe(pos, n, root) \
1857 for (pos = rb_first_postorder(root); \
1858 pos && ({ n = rb_next_postorder(pos); 1; }); \
1859 pos = n)
1860
1861void bpf_rb_root_free(const struct btf_field *field, void *rb_root,
1862 struct bpf_spin_lock *spin_lock)
1863{
1864 struct rb_root_cached orig_root, *root = rb_root;
1865 struct rb_node *pos, *n;
1866 void *obj;
1867
1868 BUILD_BUG_ON(sizeof(struct rb_root_cached) > sizeof(struct bpf_rb_root));
1869 BUILD_BUG_ON(__alignof__(struct rb_root_cached) > __alignof__(struct bpf_rb_root));
1870
1871 __bpf_spin_lock_irqsave(spin_lock);
1872 orig_root = *root;
1873 *root = RB_ROOT_CACHED;
1874 __bpf_spin_unlock_irqrestore(spin_lock);
1875
1876 bpf_rbtree_postorder_for_each_entry_safe(pos, n, &orig_root.rb_root) {
1877 obj = pos;
1878 obj -= field->graph_root.node_offset;
1879
9c395c1b
DM
1880
1881 migrate_disable();
1512217c 1882 __bpf_obj_drop_impl(obj, field->graph_root.value_rec);
9c395c1b
DM
1883 migrate_enable();
1884 }
1885}
1886
958cf2e2
KKD
1887__diag_push();
1888__diag_ignore_all("-Wmissing-prototypes",
1889 "Global functions as their definitions will be in vmlinux BTF");
1890
400031e0 1891__bpf_kfunc void *bpf_obj_new_impl(u64 local_type_id__k, void *meta__ign)
958cf2e2
KKD
1892{
1893 struct btf_struct_meta *meta = meta__ign;
1894 u64 size = local_type_id__k;
1895 void *p;
1896
958cf2e2
KKD
1897 p = bpf_mem_alloc(&bpf_global_ma, size);
1898 if (!p)
1899 return NULL;
1900 if (meta)
cd2a8079 1901 bpf_obj_init(meta->record, p);
958cf2e2
KKD
1902 return p;
1903}
1904
1512217c 1905/* Must be called under migrate_disable(), as required by bpf_mem_free */
c8e18754
DM
1906void __bpf_obj_drop_impl(void *p, const struct btf_record *rec)
1907{
1512217c
DM
1908 if (rec && rec->refcount_off >= 0 &&
1909 !refcount_dec_and_test((refcount_t *)(p + rec->refcount_off))) {
1910 /* Object is refcounted and refcount_dec didn't result in 0
1911 * refcount. Return without freeing the object
1912 */
1913 return;
1914 }
1915
c8e18754
DM
1916 if (rec)
1917 bpf_obj_free_fields(rec, p);
7e26cd12
DM
1918
1919 if (rec && rec->refcount_off >= 0)
1920 bpf_mem_free_rcu(&bpf_global_ma, p);
1921 else
1922 bpf_mem_free(&bpf_global_ma, p);
c8e18754
DM
1923}
1924
400031e0 1925__bpf_kfunc void bpf_obj_drop_impl(void *p__alloc, void *meta__ign)
ac9f0605
KKD
1926{
1927 struct btf_struct_meta *meta = meta__ign;
1928 void *p = p__alloc;
1929
c8e18754 1930 __bpf_obj_drop_impl(p, meta ? meta->record : NULL);
ac9f0605
KKD
1931}
1932
7c50b1cb
DM
1933__bpf_kfunc void *bpf_refcount_acquire_impl(void *p__refcounted_kptr, void *meta__ign)
1934{
1935 struct btf_struct_meta *meta = meta__ign;
1936 struct bpf_refcount *ref;
1937
1938 /* Could just cast directly to refcount_t *, but need some code using
1939 * bpf_refcount type so that it is emitted in vmlinux BTF
1940 */
4ab07209 1941 ref = (struct bpf_refcount *)(p__refcounted_kptr + meta->record->refcount_off);
7793fc3b
DM
1942 if (!refcount_inc_not_zero((refcount_t *)ref))
1943 return NULL;
7c50b1cb 1944
7793fc3b
DM
1945 /* Verifier strips KF_RET_NULL if input is owned ref, see is_kfunc_ret_null
1946 * in verifier.c
1947 */
7c50b1cb
DM
1948 return (void *)p__refcounted_kptr;
1949}
1950
0a1f7bfe
DM
1951static int __bpf_list_add(struct bpf_list_node_kern *node,
1952 struct bpf_list_head *head,
d2dcc67d 1953 bool tail, struct btf_record *rec, u64 off)
8cab76ec 1954{
0a1f7bfe 1955 struct list_head *n = &node->list_head, *h = (void *)head;
8cab76ec 1956
3e81740a
DM
1957 /* If list_head was 0-initialized by map, bpf_obj_init_field wasn't
1958 * called on its fields, so init here
1959 */
8cab76ec
KKD
1960 if (unlikely(!h->next))
1961 INIT_LIST_HEAD(h);
c3c510ce
DM
1962
1963 /* node->owner != NULL implies !list_empty(n), no need to separately
1964 * check the latter
1965 */
1966 if (cmpxchg(&node->owner, NULL, BPF_PTR_POISON)) {
d2dcc67d 1967 /* Only called from BPF prog, no need to migrate_disable */
cc0d76ca 1968 __bpf_obj_drop_impl((void *)n - off, rec);
d2dcc67d
DM
1969 return -EINVAL;
1970 }
1971
8cab76ec 1972 tail ? list_add_tail(n, h) : list_add(n, h);
c3c510ce 1973 WRITE_ONCE(node->owner, head);
d2dcc67d
DM
1974
1975 return 0;
8cab76ec
KKD
1976}
1977
d2dcc67d
DM
1978__bpf_kfunc int bpf_list_push_front_impl(struct bpf_list_head *head,
1979 struct bpf_list_node *node,
1980 void *meta__ign, u64 off)
8cab76ec 1981{
0a1f7bfe 1982 struct bpf_list_node_kern *n = (void *)node;
d2dcc67d
DM
1983 struct btf_struct_meta *meta = meta__ign;
1984
0a1f7bfe 1985 return __bpf_list_add(n, head, false, meta ? meta->record : NULL, off);
8cab76ec
KKD
1986}
1987
d2dcc67d
DM
1988__bpf_kfunc int bpf_list_push_back_impl(struct bpf_list_head *head,
1989 struct bpf_list_node *node,
1990 void *meta__ign, u64 off)
8cab76ec 1991{
0a1f7bfe 1992 struct bpf_list_node_kern *n = (void *)node;
d2dcc67d
DM
1993 struct btf_struct_meta *meta = meta__ign;
1994
0a1f7bfe 1995 return __bpf_list_add(n, head, true, meta ? meta->record : NULL, off);
8cab76ec
KKD
1996}
1997
1998static struct bpf_list_node *__bpf_list_del(struct bpf_list_head *head, bool tail)
1999{
2000 struct list_head *n, *h = (void *)head;
c3c510ce 2001 struct bpf_list_node_kern *node;
8cab76ec 2002
3e81740a
DM
2003 /* If list_head was 0-initialized by map, bpf_obj_init_field wasn't
2004 * called on its fields, so init here
2005 */
8cab76ec
KKD
2006 if (unlikely(!h->next))
2007 INIT_LIST_HEAD(h);
2008 if (list_empty(h))
2009 return NULL;
c3c510ce 2010
8cab76ec 2011 n = tail ? h->prev : h->next;
c3c510ce
DM
2012 node = container_of(n, struct bpf_list_node_kern, list_head);
2013 if (WARN_ON_ONCE(READ_ONCE(node->owner) != head))
2014 return NULL;
2015
8cab76ec 2016 list_del_init(n);
c3c510ce 2017 WRITE_ONCE(node->owner, NULL);
8cab76ec
KKD
2018 return (struct bpf_list_node *)n;
2019}
2020
400031e0 2021__bpf_kfunc struct bpf_list_node *bpf_list_pop_front(struct bpf_list_head *head)
8cab76ec
KKD
2022{
2023 return __bpf_list_del(head, false);
2024}
2025
400031e0 2026__bpf_kfunc struct bpf_list_node *bpf_list_pop_back(struct bpf_list_head *head)
8cab76ec
KKD
2027{
2028 return __bpf_list_del(head, true);
2029}
2030
bd1279ae
DM
2031__bpf_kfunc struct bpf_rb_node *bpf_rbtree_remove(struct bpf_rb_root *root,
2032 struct bpf_rb_node *node)
2033{
c3c510ce 2034 struct bpf_rb_node_kern *node_internal = (struct bpf_rb_node_kern *)node;
bd1279ae 2035 struct rb_root_cached *r = (struct rb_root_cached *)root;
c3c510ce 2036 struct rb_node *n = &node_internal->rb_node;
bd1279ae 2037
c3c510ce
DM
2038 /* node_internal->owner != root implies either RB_EMPTY_NODE(n) or
2039 * n is owned by some other tree. No need to check RB_EMPTY_NODE(n)
2040 */
2041 if (READ_ONCE(node_internal->owner) != root)
404ad75a
DM
2042 return NULL;
2043
bd1279ae
DM
2044 rb_erase_cached(n, r);
2045 RB_CLEAR_NODE(n);
c3c510ce 2046 WRITE_ONCE(node_internal->owner, NULL);
bd1279ae
DM
2047 return (struct bpf_rb_node *)n;
2048}
2049
2050/* Need to copy rbtree_add_cached's logic here because our 'less' is a BPF
2051 * program
2052 */
0a1f7bfe
DM
2053static int __bpf_rbtree_add(struct bpf_rb_root *root,
2054 struct bpf_rb_node_kern *node,
d2dcc67d 2055 void *less, struct btf_record *rec, u64 off)
bd1279ae
DM
2056{
2057 struct rb_node **link = &((struct rb_root_cached *)root)->rb_root.rb_node;
0a1f7bfe 2058 struct rb_node *parent = NULL, *n = &node->rb_node;
bd1279ae 2059 bpf_callback_t cb = (bpf_callback_t)less;
bd1279ae
DM
2060 bool leftmost = true;
2061
c3c510ce
DM
2062 /* node->owner != NULL implies !RB_EMPTY_NODE(n), no need to separately
2063 * check the latter
2064 */
2065 if (cmpxchg(&node->owner, NULL, BPF_PTR_POISON)) {
d2dcc67d 2066 /* Only called from BPF prog, no need to migrate_disable */
cc0d76ca 2067 __bpf_obj_drop_impl((void *)n - off, rec);
d2dcc67d
DM
2068 return -EINVAL;
2069 }
2070
bd1279ae
DM
2071 while (*link) {
2072 parent = *link;
2073 if (cb((uintptr_t)node, (uintptr_t)parent, 0, 0, 0)) {
2074 link = &parent->rb_left;
2075 } else {
2076 link = &parent->rb_right;
2077 leftmost = false;
2078 }
2079 }
2080
d2dcc67d
DM
2081 rb_link_node(n, parent, link);
2082 rb_insert_color_cached(n, (struct rb_root_cached *)root, leftmost);
c3c510ce 2083 WRITE_ONCE(node->owner, root);
d2dcc67d 2084 return 0;
bd1279ae
DM
2085}
2086
d2dcc67d
DM
2087__bpf_kfunc int bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node,
2088 bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b),
2089 void *meta__ign, u64 off)
bd1279ae 2090{
d2dcc67d 2091 struct btf_struct_meta *meta = meta__ign;
0a1f7bfe 2092 struct bpf_rb_node_kern *n = (void *)node;
d2dcc67d 2093
0a1f7bfe 2094 return __bpf_rbtree_add(root, n, (void *)less, meta ? meta->record : NULL, off);
bd1279ae
DM
2095}
2096
2097__bpf_kfunc struct bpf_rb_node *bpf_rbtree_first(struct bpf_rb_root *root)
2098{
2099 struct rb_root_cached *r = (struct rb_root_cached *)root;
2100
2101 return (struct bpf_rb_node *)rb_first_cached(r);
2102}
2103
90660309
DV
2104/**
2105 * bpf_task_acquire - Acquire a reference to a task. A task acquired by this
2106 * kfunc which is not stored in a map as a kptr, must be released by calling
2107 * bpf_task_release().
2108 * @p: The task on which a reference is being acquired.
2109 */
400031e0 2110__bpf_kfunc struct task_struct *bpf_task_acquire(struct task_struct *p)
90660309 2111{
d02c48fa
DV
2112 if (refcount_inc_not_zero(&p->rcu_users))
2113 return p;
2114 return NULL;
90660309
DV
2115}
2116
90660309 2117/**
25c5e92d 2118 * bpf_task_release - Release the reference acquired on a task.
90660309
DV
2119 * @p: The task on which a reference is being released.
2120 */
400031e0 2121__bpf_kfunc void bpf_task_release(struct task_struct *p)
90660309 2122{
d02c48fa 2123 put_task_struct_rcu_user(p);
90660309
DV
2124}
2125
fda01efc
DV
2126#ifdef CONFIG_CGROUPS
2127/**
2128 * bpf_cgroup_acquire - Acquire a reference to a cgroup. A cgroup acquired by
2129 * this kfunc which is not stored in a map as a kptr, must be released by
2130 * calling bpf_cgroup_release().
2131 * @cgrp: The cgroup on which a reference is being acquired.
2132 */
400031e0 2133__bpf_kfunc struct cgroup *bpf_cgroup_acquire(struct cgroup *cgrp)
fda01efc 2134{
1d712839 2135 return cgroup_tryget(cgrp) ? cgrp : NULL;
fda01efc
DV
2136}
2137
fda01efc 2138/**
36aa10ff 2139 * bpf_cgroup_release - Release the reference acquired on a cgroup.
fda01efc
DV
2140 * If this kfunc is invoked in an RCU read region, the cgroup is guaranteed to
2141 * not be freed until the current grace period has ended, even if its refcount
2142 * drops to 0.
2143 * @cgrp: The cgroup on which a reference is being released.
2144 */
400031e0 2145__bpf_kfunc void bpf_cgroup_release(struct cgroup *cgrp)
fda01efc 2146{
fda01efc
DV
2147 cgroup_put(cgrp);
2148}
5ca78670
DV
2149
2150/**
2151 * bpf_cgroup_ancestor - Perform a lookup on an entry in a cgroup's ancestor
2152 * array. A cgroup returned by this kfunc which is not subsequently stored in a
2153 * map, must be released by calling bpf_cgroup_release().
2154 * @cgrp: The cgroup for which we're performing a lookup.
2155 * @level: The level of ancestor to look up.
2156 */
400031e0 2157__bpf_kfunc struct cgroup *bpf_cgroup_ancestor(struct cgroup *cgrp, int level)
5ca78670
DV
2158{
2159 struct cgroup *ancestor;
2160
2161 if (level > cgrp->level || level < 0)
2162 return NULL;
2163
20c09d92 2164 /* cgrp's refcnt could be 0 here, but ancestors can still be accessed */
5ca78670 2165 ancestor = cgrp->ancestors[level];
20c09d92
AS
2166 if (!cgroup_tryget(ancestor))
2167 return NULL;
5ca78670
DV
2168 return ancestor;
2169}
332ea1f6
TH
2170
2171/**
2172 * bpf_cgroup_from_id - Find a cgroup from its ID. A cgroup returned by this
2173 * kfunc which is not subsequently stored in a map, must be released by calling
2174 * bpf_cgroup_release().
30a2d832 2175 * @cgid: cgroup id.
332ea1f6
TH
2176 */
2177__bpf_kfunc struct cgroup *bpf_cgroup_from_id(u64 cgid)
2178{
2179 struct cgroup *cgrp;
2180
2181 cgrp = cgroup_get_from_id(cgid);
2182 if (IS_ERR(cgrp))
2183 return NULL;
2184 return cgrp;
2185}
b5ad4cdc
FZ
2186
2187/**
2188 * bpf_task_under_cgroup - wrap task_under_cgroup_hierarchy() as a kfunc, test
2189 * task's membership of cgroup ancestry.
2190 * @task: the task to be tested
2191 * @ancestor: possible ancestor of @task's cgroup
2192 *
2193 * Tests whether @task's default cgroup hierarchy is a descendant of @ancestor.
2194 * It follows all the same rules as cgroup_is_descendant, and only applies
2195 * to the default hierarchy.
2196 */
2197__bpf_kfunc long bpf_task_under_cgroup(struct task_struct *task,
2198 struct cgroup *ancestor)
2199{
2200 return task_under_cgroup_hierarchy(task, ancestor);
2201}
fda01efc
DV
2202#endif /* CONFIG_CGROUPS */
2203
3f0e6f2b
DV
2204/**
2205 * bpf_task_from_pid - Find a struct task_struct from its pid by looking it up
2206 * in the root pid namespace idr. If a task is returned, it must either be
2207 * stored in a map, or released with bpf_task_release().
2208 * @pid: The pid of the task being looked up.
2209 */
400031e0 2210__bpf_kfunc struct task_struct *bpf_task_from_pid(s32 pid)
3f0e6f2b
DV
2211{
2212 struct task_struct *p;
2213
2214 rcu_read_lock();
2215 p = find_task_by_pid_ns(pid, &init_pid_ns);
2216 if (p)
d02c48fa 2217 p = bpf_task_acquire(p);
3f0e6f2b
DV
2218 rcu_read_unlock();
2219
2220 return p;
2221}
2222
66e3a13e 2223/**
7ce60b11
DV
2224 * bpf_dynptr_slice() - Obtain a read-only pointer to the dynptr data.
2225 * @ptr: The dynptr whose data slice to retrieve
2226 * @offset: Offset into the dynptr
3bda08b6
DR
2227 * @buffer__opt: User-provided buffer to copy contents into. May be NULL
2228 * @buffer__szk: Size (in bytes) of the buffer if present. This is the
2229 * length of the requested slice. This must be a constant.
66e3a13e
JK
2230 *
2231 * For non-skb and non-xdp type dynptrs, there is no difference between
2232 * bpf_dynptr_slice and bpf_dynptr_data.
2233 *
3bda08b6
DR
2234 * If buffer__opt is NULL, the call will fail if buffer_opt was needed.
2235 *
66e3a13e
JK
2236 * If the intention is to write to the data slice, please use
2237 * bpf_dynptr_slice_rdwr.
2238 *
2239 * The user must check that the returned pointer is not null before using it.
2240 *
2241 * Please note that in the case of skb and xdp dynptrs, bpf_dynptr_slice
2242 * does not change the underlying packet data pointers, so a call to
2243 * bpf_dynptr_slice will not invalidate any ctx->data/data_end pointers in
2244 * the bpf program.
2245 *
7ce60b11 2246 * Return: NULL if the call failed (eg invalid dynptr), pointer to a read-only
66e3a13e
JK
2247 * data slice (can be either direct pointer to the data or a pointer to the user
2248 * provided buffer, with its contents containing the data, if unable to obtain
2249 * direct pointer)
2250 */
2251__bpf_kfunc void *bpf_dynptr_slice(const struct bpf_dynptr_kern *ptr, u32 offset,
3bda08b6 2252 void *buffer__opt, u32 buffer__szk)
66e3a13e
JK
2253{
2254 enum bpf_dynptr_type type;
2255 u32 len = buffer__szk;
2256 int err;
2257
2258 if (!ptr->data)
c45eac53 2259 return NULL;
66e3a13e
JK
2260
2261 err = bpf_dynptr_check_off_len(ptr, offset, len);
2262 if (err)
c45eac53 2263 return NULL;
66e3a13e
JK
2264
2265 type = bpf_dynptr_get_type(ptr);
2266
2267 switch (type) {
2268 case BPF_DYNPTR_TYPE_LOCAL:
2269 case BPF_DYNPTR_TYPE_RINGBUF:
2270 return ptr->data + ptr->offset + offset;
2271 case BPF_DYNPTR_TYPE_SKB:
6f5a630d
AS
2272 if (buffer__opt)
2273 return skb_header_pointer(ptr->data, ptr->offset + offset, len, buffer__opt);
2274 else
2275 return skb_pointer_if_linear(ptr->data, ptr->offset + offset, len);
66e3a13e
JK
2276 case BPF_DYNPTR_TYPE_XDP:
2277 {
2278 void *xdp_ptr = bpf_xdp_pointer(ptr->data, ptr->offset + offset, len);
5426700e 2279 if (!IS_ERR_OR_NULL(xdp_ptr))
66e3a13e
JK
2280 return xdp_ptr;
2281
3bda08b6
DR
2282 if (!buffer__opt)
2283 return NULL;
2284 bpf_xdp_copy_buf(ptr->data, ptr->offset + offset, buffer__opt, len, false);
2285 return buffer__opt;
66e3a13e
JK
2286 }
2287 default:
2288 WARN_ONCE(true, "unknown dynptr type %d\n", type);
c45eac53 2289 return NULL;
66e3a13e
JK
2290 }
2291}
2292
2293/**
7ce60b11
DV
2294 * bpf_dynptr_slice_rdwr() - Obtain a writable pointer to the dynptr data.
2295 * @ptr: The dynptr whose data slice to retrieve
2296 * @offset: Offset into the dynptr
3bda08b6
DR
2297 * @buffer__opt: User-provided buffer to copy contents into. May be NULL
2298 * @buffer__szk: Size (in bytes) of the buffer if present. This is the
2299 * length of the requested slice. This must be a constant.
66e3a13e
JK
2300 *
2301 * For non-skb and non-xdp type dynptrs, there is no difference between
2302 * bpf_dynptr_slice and bpf_dynptr_data.
2303 *
3bda08b6
DR
2304 * If buffer__opt is NULL, the call will fail if buffer_opt was needed.
2305 *
66e3a13e
JK
2306 * The returned pointer is writable and may point to either directly the dynptr
2307 * data at the requested offset or to the buffer if unable to obtain a direct
2308 * data pointer to (example: the requested slice is to the paged area of an skb
2309 * packet). In the case where the returned pointer is to the buffer, the user
2310 * is responsible for persisting writes through calling bpf_dynptr_write(). This
2311 * usually looks something like this pattern:
2312 *
2313 * struct eth_hdr *eth = bpf_dynptr_slice_rdwr(&dynptr, 0, buffer, sizeof(buffer));
2314 * if (!eth)
2315 * return TC_ACT_SHOT;
2316 *
2317 * // mutate eth header //
2318 *
2319 * if (eth == buffer)
2320 * bpf_dynptr_write(&ptr, 0, buffer, sizeof(buffer), 0);
2321 *
2322 * Please note that, as in the example above, the user must check that the
2323 * returned pointer is not null before using it.
2324 *
2325 * Please also note that in the case of skb and xdp dynptrs, bpf_dynptr_slice_rdwr
2326 * does not change the underlying packet data pointers, so a call to
2327 * bpf_dynptr_slice_rdwr will not invalidate any ctx->data/data_end pointers in
2328 * the bpf program.
2329 *
7ce60b11 2330 * Return: NULL if the call failed (eg invalid dynptr), pointer to a
66e3a13e
JK
2331 * data slice (can be either direct pointer to the data or a pointer to the user
2332 * provided buffer, with its contents containing the data, if unable to obtain
2333 * direct pointer)
2334 */
2335__bpf_kfunc void *bpf_dynptr_slice_rdwr(const struct bpf_dynptr_kern *ptr, u32 offset,
3bda08b6 2336 void *buffer__opt, u32 buffer__szk)
66e3a13e 2337{
540ccf96 2338 if (!ptr->data || __bpf_dynptr_is_rdonly(ptr))
c45eac53 2339 return NULL;
66e3a13e
JK
2340
2341 /* bpf_dynptr_slice_rdwr is the same logic as bpf_dynptr_slice.
2342 *
2343 * For skb-type dynptrs, it is safe to write into the returned pointer
2344 * if the bpf program allows skb data writes. There are two possiblities
2345 * that may occur when calling bpf_dynptr_slice_rdwr:
2346 *
2347 * 1) The requested slice is in the head of the skb. In this case, the
2348 * returned pointer is directly to skb data, and if the skb is cloned, the
2349 * verifier will have uncloned it (see bpf_unclone_prologue()) already.
2350 * The pointer can be directly written into.
2351 *
2352 * 2) Some portion of the requested slice is in the paged buffer area.
2353 * In this case, the requested data will be copied out into the buffer
2354 * and the returned pointer will be a pointer to the buffer. The skb
2355 * will not be pulled. To persist the write, the user will need to call
2356 * bpf_dynptr_write(), which will pull the skb and commit the write.
2357 *
2358 * Similarly for xdp programs, if the requested slice is not across xdp
2359 * fragments, then a direct pointer will be returned, otherwise the data
2360 * will be copied out into the buffer and the user will need to call
2361 * bpf_dynptr_write() to commit changes.
2362 */
3bda08b6 2363 return bpf_dynptr_slice(ptr, offset, buffer__opt, buffer__szk);
66e3a13e
JK
2364}
2365
987d0242
JK
2366__bpf_kfunc int bpf_dynptr_adjust(struct bpf_dynptr_kern *ptr, u32 start, u32 end)
2367{
2368 u32 size;
2369
2370 if (!ptr->data || start > end)
2371 return -EINVAL;
2372
26662d73 2373 size = __bpf_dynptr_size(ptr);
987d0242
JK
2374
2375 if (start > size || end > size)
2376 return -ERANGE;
2377
2378 ptr->offset += start;
2379 bpf_dynptr_set_size(ptr, end - start);
2380
2381 return 0;
2382}
2383
540ccf96
JK
2384__bpf_kfunc bool bpf_dynptr_is_null(struct bpf_dynptr_kern *ptr)
2385{
2386 return !ptr->data;
2387}
2388
2389__bpf_kfunc bool bpf_dynptr_is_rdonly(struct bpf_dynptr_kern *ptr)
2390{
2391 if (!ptr->data)
2392 return false;
2393
2394 return __bpf_dynptr_is_rdonly(ptr);
2395}
2396
26662d73
JK
2397__bpf_kfunc __u32 bpf_dynptr_size(const struct bpf_dynptr_kern *ptr)
2398{
2399 if (!ptr->data)
2400 return -EINVAL;
2401
2402 return __bpf_dynptr_size(ptr);
2403}
2404
361f129f
JK
2405__bpf_kfunc int bpf_dynptr_clone(struct bpf_dynptr_kern *ptr,
2406 struct bpf_dynptr_kern *clone__uninit)
2407{
2408 if (!ptr->data) {
2409 bpf_dynptr_set_null(clone__uninit);
2410 return -EINVAL;
2411 }
2412
2413 *clone__uninit = *ptr;
2414
2415 return 0;
2416}
2417
400031e0 2418__bpf_kfunc void *bpf_cast_to_kern_ctx(void *obj)
fd264ca0
YS
2419{
2420 return obj;
2421}
2422
400031e0 2423__bpf_kfunc void *bpf_rdonly_cast(void *obj__ign, u32 btf_id__k)
a35b9af4
YS
2424{
2425 return obj__ign;
2426}
2427
400031e0 2428__bpf_kfunc void bpf_rcu_read_lock(void)
9bb00b28
YS
2429{
2430 rcu_read_lock();
2431}
2432
400031e0 2433__bpf_kfunc void bpf_rcu_read_unlock(void)
9bb00b28
YS
2434{
2435 rcu_read_unlock();
2436}
2437
958cf2e2
KKD
2438__diag_pop();
2439
2440BTF_SET8_START(generic_btf_ids)
13379059
AS
2441#ifdef CONFIG_KEXEC_CORE
2442BTF_ID_FLAGS(func, crash_kexec, KF_DESTRUCTIVE)
2443#endif
958cf2e2 2444BTF_ID_FLAGS(func, bpf_obj_new_impl, KF_ACQUIRE | KF_RET_NULL)
ac9f0605 2445BTF_ID_FLAGS(func, bpf_obj_drop_impl, KF_RELEASE)
7793fc3b 2446BTF_ID_FLAGS(func, bpf_refcount_acquire_impl, KF_ACQUIRE | KF_RET_NULL)
d2dcc67d
DM
2447BTF_ID_FLAGS(func, bpf_list_push_front_impl)
2448BTF_ID_FLAGS(func, bpf_list_push_back_impl)
8cab76ec
KKD
2449BTF_ID_FLAGS(func, bpf_list_pop_front, KF_ACQUIRE | KF_RET_NULL)
2450BTF_ID_FLAGS(func, bpf_list_pop_back, KF_ACQUIRE | KF_RET_NULL)
d02c48fa 2451BTF_ID_FLAGS(func, bpf_task_acquire, KF_ACQUIRE | KF_RCU | KF_RET_NULL)
90660309 2452BTF_ID_FLAGS(func, bpf_task_release, KF_RELEASE)
404ad75a 2453BTF_ID_FLAGS(func, bpf_rbtree_remove, KF_ACQUIRE | KF_RET_NULL)
d2dcc67d 2454BTF_ID_FLAGS(func, bpf_rbtree_add_impl)
bd1279ae
DM
2455BTF_ID_FLAGS(func, bpf_rbtree_first, KF_RET_NULL)
2456
fda01efc 2457#ifdef CONFIG_CGROUPS
1d712839 2458BTF_ID_FLAGS(func, bpf_cgroup_acquire, KF_ACQUIRE | KF_RCU | KF_RET_NULL)
fda01efc 2459BTF_ID_FLAGS(func, bpf_cgroup_release, KF_RELEASE)
20c09d92 2460BTF_ID_FLAGS(func, bpf_cgroup_ancestor, KF_ACQUIRE | KF_RCU | KF_RET_NULL)
332ea1f6 2461BTF_ID_FLAGS(func, bpf_cgroup_from_id, KF_ACQUIRE | KF_RET_NULL)
b5ad4cdc 2462BTF_ID_FLAGS(func, bpf_task_under_cgroup, KF_RCU)
fda01efc 2463#endif
3f0e6f2b 2464BTF_ID_FLAGS(func, bpf_task_from_pid, KF_ACQUIRE | KF_RET_NULL)
958cf2e2 2465BTF_SET8_END(generic_btf_ids)
13379059 2466
958cf2e2 2467static const struct btf_kfunc_id_set generic_kfunc_set = {
13379059 2468 .owner = THIS_MODULE,
958cf2e2 2469 .set = &generic_btf_ids,
13379059
AS
2470};
2471
cfe14564 2472
90660309
DV
2473BTF_ID_LIST(generic_dtor_ids)
2474BTF_ID(struct, task_struct)
2475BTF_ID(func, bpf_task_release)
fda01efc
DV
2476#ifdef CONFIG_CGROUPS
2477BTF_ID(struct, cgroup)
2478BTF_ID(func, bpf_cgroup_release)
2479#endif
90660309 2480
cfe14564 2481BTF_SET8_START(common_btf_ids)
fd264ca0 2482BTF_ID_FLAGS(func, bpf_cast_to_kern_ctx)
a35b9af4 2483BTF_ID_FLAGS(func, bpf_rdonly_cast)
9bb00b28
YS
2484BTF_ID_FLAGS(func, bpf_rcu_read_lock)
2485BTF_ID_FLAGS(func, bpf_rcu_read_unlock)
66e3a13e
JK
2486BTF_ID_FLAGS(func, bpf_dynptr_slice, KF_RET_NULL)
2487BTF_ID_FLAGS(func, bpf_dynptr_slice_rdwr, KF_RET_NULL)
6018e1f4
AN
2488BTF_ID_FLAGS(func, bpf_iter_num_new, KF_ITER_NEW)
2489BTF_ID_FLAGS(func, bpf_iter_num_next, KF_ITER_NEXT | KF_RET_NULL)
2490BTF_ID_FLAGS(func, bpf_iter_num_destroy, KF_ITER_DESTROY)
987d0242 2491BTF_ID_FLAGS(func, bpf_dynptr_adjust)
540ccf96
JK
2492BTF_ID_FLAGS(func, bpf_dynptr_is_null)
2493BTF_ID_FLAGS(func, bpf_dynptr_is_rdonly)
26662d73 2494BTF_ID_FLAGS(func, bpf_dynptr_size)
361f129f 2495BTF_ID_FLAGS(func, bpf_dynptr_clone)
cfe14564
YS
2496BTF_SET8_END(common_btf_ids)
2497
2498static const struct btf_kfunc_id_set common_kfunc_set = {
2499 .owner = THIS_MODULE,
2500 .set = &common_btf_ids,
2501};
2502
13379059
AS
2503static int __init kfunc_init(void)
2504{
2fcc6081 2505 int ret;
90660309
DV
2506 const struct btf_id_dtor_kfunc generic_dtors[] = {
2507 {
2fcc6081
DV
2508 .btf_id = generic_dtor_ids[0],
2509 .kfunc_btf_id = generic_dtor_ids[1]
90660309 2510 },
fda01efc
DV
2511#ifdef CONFIG_CGROUPS
2512 {
2fcc6081
DV
2513 .btf_id = generic_dtor_ids[2],
2514 .kfunc_btf_id = generic_dtor_ids[3]
fda01efc
DV
2515 },
2516#endif
90660309 2517 };
8cab76ec
KKD
2518
2519 ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_TRACING, &generic_kfunc_set);
90660309
DV
2520 ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_SCHED_CLS, &generic_kfunc_set);
2521 ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS, &generic_kfunc_set);
cfe14564 2522 ret = ret ?: register_btf_id_dtor_kfuncs(generic_dtors,
90660309
DV
2523 ARRAY_SIZE(generic_dtors),
2524 THIS_MODULE);
cfe14564 2525 return ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_UNSPEC, &common_kfunc_set);
13379059
AS
2526}
2527
2528late_initcall(kfunc_init);