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