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] == 'k' || fmt[i + 1] == 'u') &&
889 fmt[i + 2] == 's') {
890 fmt_ptype = fmt[i + 1];
891 i += 2;
892 goto fmt_str;
893 }
894
895 if (fmt[i + 1] == 0 || isspace(fmt[i + 1]) ||
896 ispunct(fmt[i + 1]) || fmt[i + 1] == 'K' ||
897 fmt[i + 1] == 'x' || fmt[i + 1] == 's' ||
898 fmt[i + 1] == 'S') {
899 /* just kernel pointers */
900 if (tmp_buf)
901 cur_arg = raw_args[num_spec];
902 i++;
903 goto nocopy_fmt;
904 }
905
906 if (fmt[i + 1] == 'B') {
907 if (tmp_buf) {
908 err = snprintf(tmp_buf,
909 (tmp_buf_end - tmp_buf),
910 "%pB",
911 (void *)(long)raw_args[num_spec]);
912 tmp_buf += (err + 1);
913 }
914
915 i++;
916 num_spec++;
917 continue;
918 }
919
920 /* only support "%pI4", "%pi4", "%pI6" and "%pi6". */
921 if ((fmt[i + 1] != 'i' && fmt[i + 1] != 'I') ||
922 (fmt[i + 2] != '4' && fmt[i + 2] != '6')) {
923 err = -EINVAL;
924 goto out;
925 }
926
927 i += 2;
928 if (!tmp_buf)
929 goto nocopy_fmt;
930
931 sizeof_cur_ip = (fmt[i] == '4') ? 4 : 16;
932 if (tmp_buf_end - tmp_buf < sizeof_cur_ip) {
933 err = -ENOSPC;
934 goto out;
935 }
936
937 unsafe_ptr = (char *)(long)raw_args[num_spec];
938 err = copy_from_kernel_nofault(cur_ip, unsafe_ptr,
939 sizeof_cur_ip);
940 if (err < 0)
941 memset(cur_ip, 0, sizeof_cur_ip);
942
943 /* hack: bstr_printf expects IP addresses to be
944 * pre-formatted as strings, ironically, the easiest way
945 * to do that is to call snprintf.
946 */
947 ip_spec[2] = fmt[i - 1];
948 ip_spec[3] = fmt[i];
949 err = snprintf(tmp_buf, tmp_buf_end - tmp_buf,
950 ip_spec, &cur_ip);
951
952 tmp_buf += err + 1;
953 num_spec++;
954
955 continue;
956 } else if (fmt[i] == 's') {
957 fmt_ptype = fmt[i];
958 fmt_str:
959 if (fmt[i + 1] != 0 &&
960 !isspace(fmt[i + 1]) &&
961 !ispunct(fmt[i + 1])) {
962 err = -EINVAL;
963 goto out;
964 }
965
966 if (!tmp_buf)
967 goto nocopy_fmt;
968
969 if (tmp_buf_end == tmp_buf) {
970 err = -ENOSPC;
971 goto out;
972 }
973
974 unsafe_ptr = (char *)(long)raw_args[num_spec];
975 err = bpf_trace_copy_string(tmp_buf, unsafe_ptr,
976 fmt_ptype,
977 tmp_buf_end - tmp_buf);
978 if (err < 0) {
979 tmp_buf[0] = '\0';
980 err = 1;
981 }
982
983 tmp_buf += err;
984 num_spec++;
985
986 continue;
987 } else if (fmt[i] == 'c') {
988 if (!tmp_buf)
989 goto nocopy_fmt;
990
991 if (tmp_buf_end == tmp_buf) {
992 err = -ENOSPC;
993 goto out;
994 }
995
996 *tmp_buf = raw_args[num_spec];
997 tmp_buf++;
998 num_spec++;
999
1000 continue;
1001 }
1002
1003 sizeof_cur_arg = sizeof(int);
1004
1005 if (fmt[i] == 'l') {
1006 sizeof_cur_arg = sizeof(long);
1007 i++;
1008 }
1009 if (fmt[i] == 'l') {
1010 sizeof_cur_arg = sizeof(long long);
1011 i++;
1012 }
1013
1014 if (fmt[i] != 'i' && fmt[i] != 'd' && fmt[i] != 'u' &&
1015 fmt[i] != 'x' && fmt[i] != 'X') {
1016 err = -EINVAL;
1017 goto out;
1018 }
1019
1020 if (tmp_buf)
1021 cur_arg = raw_args[num_spec];
1022 nocopy_fmt:
1023 if (tmp_buf) {
1024 tmp_buf = PTR_ALIGN(tmp_buf, sizeof(u32));
1025 if (tmp_buf_end - tmp_buf < sizeof_cur_arg) {
1026 err = -ENOSPC;
1027 goto out;
1028 }
1029
1030 if (sizeof_cur_arg == 8) {
1031 *(u32 *)tmp_buf = *(u32 *)&cur_arg;
1032 *(u32 *)(tmp_buf + 4) = *((u32 *)&cur_arg + 1);
1033 } else {
1034 *(u32 *)tmp_buf = (u32)(long)cur_arg;
1035 }
1036 tmp_buf += sizeof_cur_arg;
1037 }
1038 num_spec++;
1039 }
1040
1041 err = 0;
1042 out:
1043 if (err)
1044 bpf_bprintf_cleanup(data);
1045 return err;
1046 }
1047
BPF_CALL_5(bpf_snprintf,char *,str,u32,str_size,char *,fmt,const void *,args,u32,data_len)1048 BPF_CALL_5(bpf_snprintf, char *, str, u32, str_size, char *, fmt,
1049 const void *, args, u32, data_len)
1050 {
1051 struct bpf_bprintf_data data = {
1052 .get_bin_args = true,
1053 };
1054 int err, num_args;
1055
1056 if (data_len % 8 || data_len > MAX_BPRINTF_VARARGS * 8 ||
1057 (data_len && !args))
1058 return -EINVAL;
1059 num_args = data_len / 8;
1060
1061 /* ARG_PTR_TO_CONST_STR guarantees that fmt is zero-terminated so we
1062 * can safely give an unbounded size.
1063 */
1064 err = bpf_bprintf_prepare(fmt, UINT_MAX, args, num_args, &data);
1065 if (err < 0)
1066 return err;
1067
1068 err = bstr_printf(str, str_size, fmt, data.bin_args);
1069
1070 bpf_bprintf_cleanup(&data);
1071
1072 return err + 1;
1073 }
1074
1075 const struct bpf_func_proto bpf_snprintf_proto = {
1076 .func = bpf_snprintf,
1077 .gpl_only = true,
1078 .ret_type = RET_INTEGER,
1079 .arg1_type = ARG_PTR_TO_MEM_OR_NULL,
1080 .arg2_type = ARG_CONST_SIZE_OR_ZERO,
1081 .arg3_type = ARG_PTR_TO_CONST_STR,
1082 .arg4_type = ARG_PTR_TO_MEM | PTR_MAYBE_NULL | MEM_RDONLY,
1083 .arg5_type = ARG_CONST_SIZE_OR_ZERO,
1084 };
1085
1086 struct bpf_async_cb {
1087 struct bpf_map *map;
1088 struct bpf_prog *prog;
1089 void __rcu *callback_fn;
1090 void *value;
1091 struct rcu_head rcu;
1092 u64 flags;
1093 };
1094
1095 /* BPF map elements can contain 'struct bpf_timer'.
1096 * Such map owns all of its BPF timers.
1097 * 'struct bpf_timer' is allocated as part of map element allocation
1098 * and it's zero initialized.
1099 * That space is used to keep 'struct bpf_async_kern'.
1100 * bpf_timer_init() allocates 'struct bpf_hrtimer', inits hrtimer, and
1101 * remembers 'struct bpf_map *' pointer it's part of.
1102 * bpf_timer_set_callback() increments prog refcnt and assign bpf callback_fn.
1103 * bpf_timer_start() arms the timer.
1104 * If user space reference to a map goes to zero at this point
1105 * ops->map_release_uref callback is responsible for cancelling the timers,
1106 * freeing their memory, and decrementing prog's refcnts.
1107 * bpf_timer_cancel() cancels the timer and decrements prog's refcnt.
1108 * Inner maps can contain bpf timers as well. ops->map_release_uref is
1109 * freeing the timers when inner map is replaced or deleted by user space.
1110 */
1111 struct bpf_hrtimer {
1112 struct bpf_async_cb cb;
1113 struct hrtimer timer;
1114 atomic_t cancelling;
1115 };
1116
1117 /* the actual struct hidden inside uapi struct bpf_timer */
1118 struct bpf_async_kern {
1119 union {
1120 struct bpf_async_cb *cb;
1121 struct bpf_hrtimer *timer;
1122 };
1123 /* bpf_spin_lock is used here instead of spinlock_t to make
1124 * sure that it always fits into space reserved by struct bpf_timer
1125 * regardless of LOCKDEP and spinlock debug flags.
1126 */
1127 struct bpf_spin_lock lock;
1128 } __attribute__((aligned(8)));
1129
1130 enum bpf_async_type {
1131 BPF_ASYNC_TYPE_TIMER = 0,
1132 };
1133
1134 static DEFINE_PER_CPU(struct bpf_hrtimer *, hrtimer_running);
1135
bpf_timer_cb(struct hrtimer * hrtimer)1136 static enum hrtimer_restart bpf_timer_cb(struct hrtimer *hrtimer)
1137 {
1138 struct bpf_hrtimer *t = container_of(hrtimer, struct bpf_hrtimer, timer);
1139 struct bpf_map *map = t->cb.map;
1140 void *value = t->cb.value;
1141 bpf_callback_t callback_fn;
1142 void *key;
1143 u32 idx;
1144
1145 BTF_TYPE_EMIT(struct bpf_timer);
1146 callback_fn = rcu_dereference_check(t->cb.callback_fn, rcu_read_lock_bh_held());
1147 if (!callback_fn)
1148 goto out;
1149
1150 /* bpf_timer_cb() runs in hrtimer_run_softirq. It doesn't migrate and
1151 * cannot be preempted by another bpf_timer_cb() on the same cpu.
1152 * Remember the timer this callback is servicing to prevent
1153 * deadlock if callback_fn() calls bpf_timer_cancel() or
1154 * bpf_map_delete_elem() on the same timer.
1155 */
1156 this_cpu_write(hrtimer_running, t);
1157 if (map->map_type == BPF_MAP_TYPE_ARRAY) {
1158 struct bpf_array *array = container_of(map, struct bpf_array, map);
1159
1160 /* compute the key */
1161 idx = ((char *)value - array->value) / array->elem_size;
1162 key = &idx;
1163 } else { /* hash or lru */
1164 key = value - round_up(map->key_size, 8);
1165 }
1166
1167 callback_fn((u64)(long)map, (u64)(long)key, (u64)(long)value, 0, 0);
1168 /* The verifier checked that return value is zero. */
1169
1170 this_cpu_write(hrtimer_running, NULL);
1171 out:
1172 return HRTIMER_NORESTART;
1173 }
1174
__bpf_async_init(struct bpf_async_kern * async,struct bpf_map * map,u64 flags,enum bpf_async_type type)1175 static int __bpf_async_init(struct bpf_async_kern *async, struct bpf_map *map, u64 flags,
1176 enum bpf_async_type type)
1177 {
1178 struct bpf_async_cb *cb;
1179 struct bpf_hrtimer *t;
1180 clockid_t clockid;
1181 size_t size;
1182 int ret = 0;
1183
1184 if (in_nmi())
1185 return -EOPNOTSUPP;
1186
1187 switch (type) {
1188 case BPF_ASYNC_TYPE_TIMER:
1189 size = sizeof(struct bpf_hrtimer);
1190 break;
1191 default:
1192 return -EINVAL;
1193 }
1194
1195 __bpf_spin_lock_irqsave(&async->lock);
1196 t = async->timer;
1197 if (t) {
1198 ret = -EBUSY;
1199 goto out;
1200 }
1201
1202 /* allocate hrtimer via map_kmalloc to use memcg accounting */
1203 cb = bpf_map_kmalloc_node(map, size, GFP_ATOMIC, map->numa_node);
1204 if (!cb) {
1205 ret = -ENOMEM;
1206 goto out;
1207 }
1208
1209 if (type == BPF_ASYNC_TYPE_TIMER) {
1210 clockid = flags & (MAX_CLOCKS - 1);
1211 t = (struct bpf_hrtimer *)cb;
1212
1213 atomic_set(&t->cancelling, 0);
1214 hrtimer_init(&t->timer, clockid, HRTIMER_MODE_REL_SOFT);
1215 t->timer.function = bpf_timer_cb;
1216 cb->value = (void *)async - map->record->timer_off;
1217 }
1218 cb->map = map;
1219 cb->prog = NULL;
1220 cb->flags = flags;
1221 rcu_assign_pointer(cb->callback_fn, NULL);
1222
1223 WRITE_ONCE(async->cb, cb);
1224 /* Guarantee the order between async->cb and map->usercnt. So
1225 * when there are concurrent uref release and bpf timer init, either
1226 * bpf_timer_cancel_and_free() called by uref release reads a no-NULL
1227 * timer or atomic64_read() below returns a zero usercnt.
1228 */
1229 smp_mb();
1230 if (!atomic64_read(&map->usercnt)) {
1231 /* maps with timers must be either held by user space
1232 * or pinned in bpffs.
1233 */
1234 WRITE_ONCE(async->cb, NULL);
1235 kfree(cb);
1236 ret = -EPERM;
1237 }
1238 out:
1239 __bpf_spin_unlock_irqrestore(&async->lock);
1240 return ret;
1241 }
1242
BPF_CALL_3(bpf_timer_init,struct bpf_async_kern *,timer,struct bpf_map *,map,u64,flags)1243 BPF_CALL_3(bpf_timer_init, struct bpf_async_kern *, timer, struct bpf_map *, map,
1244 u64, flags)
1245 {
1246 clock_t clockid = flags & (MAX_CLOCKS - 1);
1247
1248 BUILD_BUG_ON(MAX_CLOCKS != 16);
1249 BUILD_BUG_ON(sizeof(struct bpf_async_kern) > sizeof(struct bpf_timer));
1250 BUILD_BUG_ON(__alignof__(struct bpf_async_kern) != __alignof__(struct bpf_timer));
1251
1252 if (flags >= MAX_CLOCKS ||
1253 /* similar to timerfd except _ALARM variants are not supported */
1254 (clockid != CLOCK_MONOTONIC &&
1255 clockid != CLOCK_REALTIME &&
1256 clockid != CLOCK_BOOTTIME))
1257 return -EINVAL;
1258
1259 return __bpf_async_init(timer, map, flags, BPF_ASYNC_TYPE_TIMER);
1260 }
1261
1262 static const struct bpf_func_proto bpf_timer_init_proto = {
1263 .func = bpf_timer_init,
1264 .gpl_only = true,
1265 .ret_type = RET_INTEGER,
1266 .arg1_type = ARG_PTR_TO_TIMER,
1267 .arg2_type = ARG_CONST_MAP_PTR,
1268 .arg3_type = ARG_ANYTHING,
1269 };
1270
BPF_CALL_3(bpf_timer_set_callback,struct bpf_async_kern *,timer,void *,callback_fn,struct bpf_prog_aux *,aux)1271 BPF_CALL_3(bpf_timer_set_callback, struct bpf_async_kern *, timer, void *, callback_fn,
1272 struct bpf_prog_aux *, aux)
1273 {
1274 struct bpf_prog *prev, *prog = aux->prog;
1275 struct bpf_hrtimer *t;
1276 int ret = 0;
1277
1278 if (in_nmi())
1279 return -EOPNOTSUPP;
1280 __bpf_spin_lock_irqsave(&timer->lock);
1281 t = timer->timer;
1282 if (!t) {
1283 ret = -EINVAL;
1284 goto out;
1285 }
1286 if (!atomic64_read(&t->cb.map->usercnt)) {
1287 /* maps with timers must be either held by user space
1288 * or pinned in bpffs. Otherwise timer might still be
1289 * running even when bpf prog is detached and user space
1290 * is gone, since map_release_uref won't ever be called.
1291 */
1292 ret = -EPERM;
1293 goto out;
1294 }
1295 prev = t->cb.prog;
1296 if (prev != prog) {
1297 /* Bump prog refcnt once. Every bpf_timer_set_callback()
1298 * can pick different callback_fn-s within the same prog.
1299 */
1300 prog = bpf_prog_inc_not_zero(prog);
1301 if (IS_ERR(prog)) {
1302 ret = PTR_ERR(prog);
1303 goto out;
1304 }
1305 if (prev)
1306 /* Drop prev prog refcnt when swapping with new prog */
1307 bpf_prog_put(prev);
1308 t->cb.prog = prog;
1309 }
1310 rcu_assign_pointer(t->cb.callback_fn, callback_fn);
1311 out:
1312 __bpf_spin_unlock_irqrestore(&timer->lock);
1313 return ret;
1314 }
1315
1316 static const struct bpf_func_proto bpf_timer_set_callback_proto = {
1317 .func = bpf_timer_set_callback,
1318 .gpl_only = true,
1319 .ret_type = RET_INTEGER,
1320 .arg1_type = ARG_PTR_TO_TIMER,
1321 .arg2_type = ARG_PTR_TO_FUNC,
1322 };
1323
BPF_CALL_3(bpf_timer_start,struct bpf_async_kern *,timer,u64,nsecs,u64,flags)1324 BPF_CALL_3(bpf_timer_start, struct bpf_async_kern *, timer, u64, nsecs, u64, flags)
1325 {
1326 struct bpf_hrtimer *t;
1327 int ret = 0;
1328 enum hrtimer_mode mode;
1329
1330 if (in_nmi())
1331 return -EOPNOTSUPP;
1332 if (flags > BPF_F_TIMER_ABS)
1333 return -EINVAL;
1334 __bpf_spin_lock_irqsave(&timer->lock);
1335 t = timer->timer;
1336 if (!t || !t->cb.prog) {
1337 ret = -EINVAL;
1338 goto out;
1339 }
1340
1341 if (flags & BPF_F_TIMER_ABS)
1342 mode = HRTIMER_MODE_ABS_SOFT;
1343 else
1344 mode = HRTIMER_MODE_REL_SOFT;
1345
1346 hrtimer_start(&t->timer, ns_to_ktime(nsecs), mode);
1347 out:
1348 __bpf_spin_unlock_irqrestore(&timer->lock);
1349 return ret;
1350 }
1351
1352 static const struct bpf_func_proto bpf_timer_start_proto = {
1353 .func = bpf_timer_start,
1354 .gpl_only = true,
1355 .ret_type = RET_INTEGER,
1356 .arg1_type = ARG_PTR_TO_TIMER,
1357 .arg2_type = ARG_ANYTHING,
1358 .arg3_type = ARG_ANYTHING,
1359 };
1360
drop_prog_refcnt(struct bpf_async_cb * async)1361 static void drop_prog_refcnt(struct bpf_async_cb *async)
1362 {
1363 struct bpf_prog *prog = async->prog;
1364
1365 if (prog) {
1366 bpf_prog_put(prog);
1367 async->prog = NULL;
1368 rcu_assign_pointer(async->callback_fn, NULL);
1369 }
1370 }
1371
BPF_CALL_1(bpf_timer_cancel,struct bpf_async_kern *,timer)1372 BPF_CALL_1(bpf_timer_cancel, struct bpf_async_kern *, timer)
1373 {
1374 struct bpf_hrtimer *t, *cur_t;
1375 bool inc = false;
1376 int ret = 0;
1377
1378 if (in_nmi())
1379 return -EOPNOTSUPP;
1380 rcu_read_lock();
1381 __bpf_spin_lock_irqsave(&timer->lock);
1382 t = timer->timer;
1383 if (!t) {
1384 ret = -EINVAL;
1385 goto out;
1386 }
1387
1388 cur_t = this_cpu_read(hrtimer_running);
1389 if (cur_t == t) {
1390 /* If bpf callback_fn is trying to bpf_timer_cancel()
1391 * its own timer the hrtimer_cancel() will deadlock
1392 * since it waits for callback_fn to finish.
1393 */
1394 ret = -EDEADLK;
1395 goto out;
1396 }
1397
1398 /* Only account in-flight cancellations when invoked from a timer
1399 * callback, since we want to avoid waiting only if other _callbacks_
1400 * are waiting on us, to avoid introducing lockups. Non-callback paths
1401 * are ok, since nobody would synchronously wait for their completion.
1402 */
1403 if (!cur_t)
1404 goto drop;
1405 atomic_inc(&t->cancelling);
1406 /* Need full barrier after relaxed atomic_inc */
1407 smp_mb__after_atomic();
1408 inc = true;
1409 if (atomic_read(&cur_t->cancelling)) {
1410 /* We're cancelling timer t, while some other timer callback is
1411 * attempting to cancel us. In such a case, it might be possible
1412 * that timer t belongs to the other callback, or some other
1413 * callback waiting upon it (creating transitive dependencies
1414 * upon us), and we will enter a deadlock if we continue
1415 * cancelling and waiting for it synchronously, since it might
1416 * do the same. Bail!
1417 */
1418 ret = -EDEADLK;
1419 goto out;
1420 }
1421 drop:
1422 drop_prog_refcnt(&t->cb);
1423 out:
1424 __bpf_spin_unlock_irqrestore(&timer->lock);
1425 /* Cancel the timer and wait for associated callback to finish
1426 * if it was running.
1427 */
1428 ret = ret ?: hrtimer_cancel(&t->timer);
1429 if (inc)
1430 atomic_dec(&t->cancelling);
1431 rcu_read_unlock();
1432 return ret;
1433 }
1434
1435 static const struct bpf_func_proto bpf_timer_cancel_proto = {
1436 .func = bpf_timer_cancel,
1437 .gpl_only = true,
1438 .ret_type = RET_INTEGER,
1439 .arg1_type = ARG_PTR_TO_TIMER,
1440 };
1441
1442 /* This function is called by map_delete/update_elem for individual element and
1443 * by ops->map_release_uref when the user space reference to a map reaches zero.
1444 */
bpf_timer_cancel_and_free(void * val)1445 void bpf_timer_cancel_and_free(void *val)
1446 {
1447 struct bpf_async_kern *timer = val;
1448 struct bpf_hrtimer *t;
1449
1450 /* Performance optimization: read timer->timer without lock first. */
1451 if (!READ_ONCE(timer->timer))
1452 return;
1453
1454 __bpf_spin_lock_irqsave(&timer->lock);
1455 /* re-read it under lock */
1456 t = timer->timer;
1457 if (!t)
1458 goto out;
1459 drop_prog_refcnt(&t->cb);
1460 /* The subsequent bpf_timer_start/cancel() helpers won't be able to use
1461 * this timer, since it won't be initialized.
1462 */
1463 WRITE_ONCE(timer->timer, NULL);
1464 out:
1465 __bpf_spin_unlock_irqrestore(&timer->lock);
1466 if (!t)
1467 return;
1468 /* Cancel the timer and wait for callback to complete if it was running.
1469 * If hrtimer_cancel() can be safely called it's safe to call kfree(t)
1470 * right after for both preallocated and non-preallocated maps.
1471 * The timer->timer = NULL was already done and no code path can
1472 * see address 't' anymore.
1473 *
1474 * Check that bpf_map_delete/update_elem() wasn't called from timer
1475 * callback_fn. In such case don't call hrtimer_cancel() (since it will
1476 * deadlock) and don't call hrtimer_try_to_cancel() (since it will just
1477 * return -1). Though callback_fn is still running on this cpu it's
1478 * safe to do kfree(t) because bpf_timer_cb() read everything it needed
1479 * from 't'. The bpf subprog callback_fn won't be able to access 't',
1480 * since timer->timer = NULL was already done. The timer will be
1481 * effectively cancelled because bpf_timer_cb() will return
1482 * HRTIMER_NORESTART.
1483 */
1484 if (this_cpu_read(hrtimer_running) != t)
1485 hrtimer_cancel(&t->timer);
1486 kfree_rcu(t, cb.rcu);
1487 }
1488
BPF_CALL_2(bpf_kptr_xchg,void *,map_value,void *,ptr)1489 BPF_CALL_2(bpf_kptr_xchg, void *, map_value, void *, ptr)
1490 {
1491 unsigned long *kptr = map_value;
1492
1493 return xchg(kptr, (unsigned long)ptr);
1494 }
1495
1496 /* Unlike other PTR_TO_BTF_ID helpers the btf_id in bpf_kptr_xchg()
1497 * helper is determined dynamically by the verifier. Use BPF_PTR_POISON to
1498 * denote type that verifier will determine.
1499 */
1500 static const struct bpf_func_proto bpf_kptr_xchg_proto = {
1501 .func = bpf_kptr_xchg,
1502 .gpl_only = false,
1503 .ret_type = RET_PTR_TO_BTF_ID_OR_NULL,
1504 .ret_btf_id = BPF_PTR_POISON,
1505 .arg1_type = ARG_PTR_TO_KPTR,
1506 .arg2_type = ARG_PTR_TO_BTF_ID_OR_NULL | OBJ_RELEASE,
1507 .arg2_btf_id = BPF_PTR_POISON,
1508 };
1509
1510 /* Since the upper 8 bits of dynptr->size is reserved, the
1511 * maximum supported size is 2^24 - 1.
1512 */
1513 #define DYNPTR_MAX_SIZE ((1UL << 24) - 1)
1514 #define DYNPTR_TYPE_SHIFT 28
1515 #define DYNPTR_SIZE_MASK 0xFFFFFF
1516 #define DYNPTR_RDONLY_BIT BIT(31)
1517
__bpf_dynptr_is_rdonly(const struct bpf_dynptr_kern * ptr)1518 static bool __bpf_dynptr_is_rdonly(const struct bpf_dynptr_kern *ptr)
1519 {
1520 return ptr->size & DYNPTR_RDONLY_BIT;
1521 }
1522
bpf_dynptr_set_rdonly(struct bpf_dynptr_kern * ptr)1523 void bpf_dynptr_set_rdonly(struct bpf_dynptr_kern *ptr)
1524 {
1525 ptr->size |= DYNPTR_RDONLY_BIT;
1526 }
1527
bpf_dynptr_set_type(struct bpf_dynptr_kern * ptr,enum bpf_dynptr_type type)1528 static void bpf_dynptr_set_type(struct bpf_dynptr_kern *ptr, enum bpf_dynptr_type type)
1529 {
1530 ptr->size |= type << DYNPTR_TYPE_SHIFT;
1531 }
1532
bpf_dynptr_get_type(const struct bpf_dynptr_kern * ptr)1533 static enum bpf_dynptr_type bpf_dynptr_get_type(const struct bpf_dynptr_kern *ptr)
1534 {
1535 return (ptr->size & ~(DYNPTR_RDONLY_BIT)) >> DYNPTR_TYPE_SHIFT;
1536 }
1537
__bpf_dynptr_size(const struct bpf_dynptr_kern * ptr)1538 u32 __bpf_dynptr_size(const struct bpf_dynptr_kern *ptr)
1539 {
1540 return ptr->size & DYNPTR_SIZE_MASK;
1541 }
1542
bpf_dynptr_set_size(struct bpf_dynptr_kern * ptr,u32 new_size)1543 static void bpf_dynptr_set_size(struct bpf_dynptr_kern *ptr, u32 new_size)
1544 {
1545 u32 metadata = ptr->size & ~DYNPTR_SIZE_MASK;
1546
1547 ptr->size = new_size | metadata;
1548 }
1549
bpf_dynptr_check_size(u32 size)1550 int bpf_dynptr_check_size(u32 size)
1551 {
1552 return size > DYNPTR_MAX_SIZE ? -E2BIG : 0;
1553 }
1554
bpf_dynptr_init(struct bpf_dynptr_kern * ptr,void * data,enum bpf_dynptr_type type,u32 offset,u32 size)1555 void bpf_dynptr_init(struct bpf_dynptr_kern *ptr, void *data,
1556 enum bpf_dynptr_type type, u32 offset, u32 size)
1557 {
1558 ptr->data = data;
1559 ptr->offset = offset;
1560 ptr->size = size;
1561 bpf_dynptr_set_type(ptr, type);
1562 }
1563
bpf_dynptr_set_null(struct bpf_dynptr_kern * ptr)1564 void bpf_dynptr_set_null(struct bpf_dynptr_kern *ptr)
1565 {
1566 memset(ptr, 0, sizeof(*ptr));
1567 }
1568
bpf_dynptr_check_off_len(const struct bpf_dynptr_kern * ptr,u32 offset,u32 len)1569 static int bpf_dynptr_check_off_len(const struct bpf_dynptr_kern *ptr, u32 offset, u32 len)
1570 {
1571 u32 size = __bpf_dynptr_size(ptr);
1572
1573 if (len > size || offset > size - len)
1574 return -E2BIG;
1575
1576 return 0;
1577 }
1578
BPF_CALL_4(bpf_dynptr_from_mem,void *,data,u32,size,u64,flags,struct bpf_dynptr_kern *,ptr)1579 BPF_CALL_4(bpf_dynptr_from_mem, void *, data, u32, size, u64, flags, struct bpf_dynptr_kern *, ptr)
1580 {
1581 int err;
1582
1583 BTF_TYPE_EMIT(struct bpf_dynptr);
1584
1585 err = bpf_dynptr_check_size(size);
1586 if (err)
1587 goto error;
1588
1589 /* flags is currently unsupported */
1590 if (flags) {
1591 err = -EINVAL;
1592 goto error;
1593 }
1594
1595 bpf_dynptr_init(ptr, data, BPF_DYNPTR_TYPE_LOCAL, 0, size);
1596
1597 return 0;
1598
1599 error:
1600 bpf_dynptr_set_null(ptr);
1601 return err;
1602 }
1603
1604 static const struct bpf_func_proto bpf_dynptr_from_mem_proto = {
1605 .func = bpf_dynptr_from_mem,
1606 .gpl_only = false,
1607 .ret_type = RET_INTEGER,
1608 .arg1_type = ARG_PTR_TO_UNINIT_MEM,
1609 .arg2_type = ARG_CONST_SIZE_OR_ZERO,
1610 .arg3_type = ARG_ANYTHING,
1611 .arg4_type = ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_LOCAL | MEM_UNINIT | MEM_WRITE,
1612 };
1613
BPF_CALL_5(bpf_dynptr_read,void *,dst,u32,len,const struct bpf_dynptr_kern *,src,u32,offset,u64,flags)1614 BPF_CALL_5(bpf_dynptr_read, void *, dst, u32, len, const struct bpf_dynptr_kern *, src,
1615 u32, offset, u64, flags)
1616 {
1617 enum bpf_dynptr_type type;
1618 int err;
1619
1620 if (!src->data || flags)
1621 return -EINVAL;
1622
1623 err = bpf_dynptr_check_off_len(src, offset, len);
1624 if (err)
1625 return err;
1626
1627 type = bpf_dynptr_get_type(src);
1628
1629 switch (type) {
1630 case BPF_DYNPTR_TYPE_LOCAL:
1631 case BPF_DYNPTR_TYPE_RINGBUF:
1632 /* Source and destination may possibly overlap, hence use memmove to
1633 * copy the data. E.g. bpf_dynptr_from_mem may create two dynptr
1634 * pointing to overlapping PTR_TO_MAP_VALUE regions.
1635 */
1636 memmove(dst, src->data + src->offset + offset, len);
1637 return 0;
1638 case BPF_DYNPTR_TYPE_SKB:
1639 return __bpf_skb_load_bytes(src->data, src->offset + offset, dst, len);
1640 case BPF_DYNPTR_TYPE_XDP:
1641 return __bpf_xdp_load_bytes(src->data, src->offset + offset, dst, len);
1642 default:
1643 WARN_ONCE(true, "bpf_dynptr_read: unknown dynptr type %d\n", type);
1644 return -EFAULT;
1645 }
1646 }
1647
1648 static const struct bpf_func_proto bpf_dynptr_read_proto = {
1649 .func = bpf_dynptr_read,
1650 .gpl_only = false,
1651 .ret_type = RET_INTEGER,
1652 .arg1_type = ARG_PTR_TO_UNINIT_MEM,
1653 .arg2_type = ARG_CONST_SIZE_OR_ZERO,
1654 .arg3_type = ARG_PTR_TO_DYNPTR | MEM_RDONLY,
1655 .arg4_type = ARG_ANYTHING,
1656 .arg5_type = ARG_ANYTHING,
1657 };
1658
BPF_CALL_5(bpf_dynptr_write,const struct bpf_dynptr_kern *,dst,u32,offset,void *,src,u32,len,u64,flags)1659 BPF_CALL_5(bpf_dynptr_write, const struct bpf_dynptr_kern *, dst, u32, offset, void *, src,
1660 u32, len, u64, flags)
1661 {
1662 enum bpf_dynptr_type type;
1663 int err;
1664
1665 if (!dst->data || __bpf_dynptr_is_rdonly(dst))
1666 return -EINVAL;
1667
1668 err = bpf_dynptr_check_off_len(dst, offset, len);
1669 if (err)
1670 return err;
1671
1672 type = bpf_dynptr_get_type(dst);
1673
1674 switch (type) {
1675 case BPF_DYNPTR_TYPE_LOCAL:
1676 case BPF_DYNPTR_TYPE_RINGBUF:
1677 if (flags)
1678 return -EINVAL;
1679 /* Source and destination may possibly overlap, hence use memmove to
1680 * copy the data. E.g. bpf_dynptr_from_mem may create two dynptr
1681 * pointing to overlapping PTR_TO_MAP_VALUE regions.
1682 */
1683 memmove(dst->data + dst->offset + offset, src, len);
1684 return 0;
1685 case BPF_DYNPTR_TYPE_SKB:
1686 return __bpf_skb_store_bytes(dst->data, dst->offset + offset, src, len,
1687 flags);
1688 case BPF_DYNPTR_TYPE_XDP:
1689 if (flags)
1690 return -EINVAL;
1691 return __bpf_xdp_store_bytes(dst->data, dst->offset + offset, src, len);
1692 default:
1693 WARN_ONCE(true, "bpf_dynptr_write: unknown dynptr type %d\n", type);
1694 return -EFAULT;
1695 }
1696 }
1697
1698 static const struct bpf_func_proto bpf_dynptr_write_proto = {
1699 .func = bpf_dynptr_write,
1700 .gpl_only = false,
1701 .ret_type = RET_INTEGER,
1702 .arg1_type = ARG_PTR_TO_DYNPTR | MEM_RDONLY,
1703 .arg2_type = ARG_ANYTHING,
1704 .arg3_type = ARG_PTR_TO_MEM | MEM_RDONLY,
1705 .arg4_type = ARG_CONST_SIZE_OR_ZERO,
1706 .arg5_type = ARG_ANYTHING,
1707 };
1708
BPF_CALL_3(bpf_dynptr_data,const struct bpf_dynptr_kern *,ptr,u32,offset,u32,len)1709 BPF_CALL_3(bpf_dynptr_data, const struct bpf_dynptr_kern *, ptr, u32, offset, u32, len)
1710 {
1711 enum bpf_dynptr_type type;
1712 int err;
1713
1714 if (!ptr->data)
1715 return 0;
1716
1717 err = bpf_dynptr_check_off_len(ptr, offset, len);
1718 if (err)
1719 return 0;
1720
1721 if (__bpf_dynptr_is_rdonly(ptr))
1722 return 0;
1723
1724 type = bpf_dynptr_get_type(ptr);
1725
1726 switch (type) {
1727 case BPF_DYNPTR_TYPE_LOCAL:
1728 case BPF_DYNPTR_TYPE_RINGBUF:
1729 return (unsigned long)(ptr->data + ptr->offset + offset);
1730 case BPF_DYNPTR_TYPE_SKB:
1731 case BPF_DYNPTR_TYPE_XDP:
1732 /* skb and xdp dynptrs should use bpf_dynptr_slice / bpf_dynptr_slice_rdwr */
1733 return 0;
1734 default:
1735 WARN_ONCE(true, "bpf_dynptr_data: unknown dynptr type %d\n", type);
1736 return 0;
1737 }
1738 }
1739
1740 static const struct bpf_func_proto bpf_dynptr_data_proto = {
1741 .func = bpf_dynptr_data,
1742 .gpl_only = false,
1743 .ret_type = RET_PTR_TO_DYNPTR_MEM_OR_NULL,
1744 .arg1_type = ARG_PTR_TO_DYNPTR | MEM_RDONLY,
1745 .arg2_type = ARG_ANYTHING,
1746 .arg3_type = ARG_CONST_ALLOC_SIZE_OR_ZERO,
1747 };
1748
1749 const struct bpf_func_proto bpf_get_current_task_proto __weak;
1750 const struct bpf_func_proto bpf_get_current_task_btf_proto __weak;
1751 const struct bpf_func_proto bpf_probe_read_user_proto __weak;
1752 const struct bpf_func_proto bpf_probe_read_user_str_proto __weak;
1753 const struct bpf_func_proto bpf_probe_read_kernel_proto __weak;
1754 const struct bpf_func_proto bpf_probe_read_kernel_str_proto __weak;
1755 const struct bpf_func_proto bpf_task_pt_regs_proto __weak;
1756
1757 const struct bpf_func_proto *
bpf_base_func_proto(enum bpf_func_id func_id)1758 bpf_base_func_proto(enum bpf_func_id func_id)
1759 {
1760 switch (func_id) {
1761 case BPF_FUNC_map_lookup_elem:
1762 return &bpf_map_lookup_elem_proto;
1763 case BPF_FUNC_map_update_elem:
1764 return &bpf_map_update_elem_proto;
1765 case BPF_FUNC_map_delete_elem:
1766 return &bpf_map_delete_elem_proto;
1767 case BPF_FUNC_map_push_elem:
1768 return &bpf_map_push_elem_proto;
1769 case BPF_FUNC_map_pop_elem:
1770 return &bpf_map_pop_elem_proto;
1771 case BPF_FUNC_map_peek_elem:
1772 return &bpf_map_peek_elem_proto;
1773 case BPF_FUNC_map_lookup_percpu_elem:
1774 return &bpf_map_lookup_percpu_elem_proto;
1775 case BPF_FUNC_get_prandom_u32:
1776 return &bpf_get_prandom_u32_proto;
1777 case BPF_FUNC_get_smp_processor_id:
1778 return &bpf_get_raw_smp_processor_id_proto;
1779 case BPF_FUNC_get_numa_node_id:
1780 return &bpf_get_numa_node_id_proto;
1781 case BPF_FUNC_tail_call:
1782 return &bpf_tail_call_proto;
1783 case BPF_FUNC_ktime_get_ns:
1784 return &bpf_ktime_get_ns_proto;
1785 case BPF_FUNC_ktime_get_boot_ns:
1786 return &bpf_ktime_get_boot_ns_proto;
1787 case BPF_FUNC_ktime_get_tai_ns:
1788 return &bpf_ktime_get_tai_ns_proto;
1789 case BPF_FUNC_ringbuf_output:
1790 return &bpf_ringbuf_output_proto;
1791 case BPF_FUNC_ringbuf_reserve:
1792 return &bpf_ringbuf_reserve_proto;
1793 case BPF_FUNC_ringbuf_submit:
1794 return &bpf_ringbuf_submit_proto;
1795 case BPF_FUNC_ringbuf_discard:
1796 return &bpf_ringbuf_discard_proto;
1797 case BPF_FUNC_ringbuf_query:
1798 return &bpf_ringbuf_query_proto;
1799 case BPF_FUNC_strncmp:
1800 return &bpf_strncmp_proto;
1801 case BPF_FUNC_strtol:
1802 return &bpf_strtol_proto;
1803 case BPF_FUNC_strtoul:
1804 return &bpf_strtoul_proto;
1805 default:
1806 break;
1807 }
1808
1809 if (!bpf_capable())
1810 return NULL;
1811
1812 switch (func_id) {
1813 case BPF_FUNC_spin_lock:
1814 return &bpf_spin_lock_proto;
1815 case BPF_FUNC_spin_unlock:
1816 return &bpf_spin_unlock_proto;
1817 case BPF_FUNC_jiffies64:
1818 return &bpf_jiffies64_proto;
1819 case BPF_FUNC_per_cpu_ptr:
1820 return &bpf_per_cpu_ptr_proto;
1821 case BPF_FUNC_this_cpu_ptr:
1822 return &bpf_this_cpu_ptr_proto;
1823 case BPF_FUNC_timer_init:
1824 return &bpf_timer_init_proto;
1825 case BPF_FUNC_timer_set_callback:
1826 return &bpf_timer_set_callback_proto;
1827 case BPF_FUNC_timer_start:
1828 return &bpf_timer_start_proto;
1829 case BPF_FUNC_timer_cancel:
1830 return &bpf_timer_cancel_proto;
1831 case BPF_FUNC_kptr_xchg:
1832 return &bpf_kptr_xchg_proto;
1833 case BPF_FUNC_for_each_map_elem:
1834 return &bpf_for_each_map_elem_proto;
1835 case BPF_FUNC_loop:
1836 return &bpf_loop_proto;
1837 case BPF_FUNC_user_ringbuf_drain:
1838 return &bpf_user_ringbuf_drain_proto;
1839 case BPF_FUNC_ringbuf_reserve_dynptr:
1840 return &bpf_ringbuf_reserve_dynptr_proto;
1841 case BPF_FUNC_ringbuf_submit_dynptr:
1842 return &bpf_ringbuf_submit_dynptr_proto;
1843 case BPF_FUNC_ringbuf_discard_dynptr:
1844 return &bpf_ringbuf_discard_dynptr_proto;
1845 case BPF_FUNC_dynptr_from_mem:
1846 return &bpf_dynptr_from_mem_proto;
1847 case BPF_FUNC_dynptr_read:
1848 return &bpf_dynptr_read_proto;
1849 case BPF_FUNC_dynptr_write:
1850 return &bpf_dynptr_write_proto;
1851 case BPF_FUNC_dynptr_data:
1852 return &bpf_dynptr_data_proto;
1853 #ifdef CONFIG_CGROUPS
1854 case BPF_FUNC_cgrp_storage_get:
1855 return &bpf_cgrp_storage_get_proto;
1856 case BPF_FUNC_cgrp_storage_delete:
1857 return &bpf_cgrp_storage_delete_proto;
1858 case BPF_FUNC_get_current_cgroup_id:
1859 return &bpf_get_current_cgroup_id_proto;
1860 case BPF_FUNC_get_current_ancestor_cgroup_id:
1861 return &bpf_get_current_ancestor_cgroup_id_proto;
1862 #endif
1863 default:
1864 break;
1865 }
1866
1867 if (!perfmon_capable())
1868 return NULL;
1869
1870 switch (func_id) {
1871 case BPF_FUNC_trace_printk:
1872 return bpf_get_trace_printk_proto();
1873 case BPF_FUNC_get_current_task:
1874 return &bpf_get_current_task_proto;
1875 case BPF_FUNC_get_current_task_btf:
1876 return &bpf_get_current_task_btf_proto;
1877 case BPF_FUNC_probe_read_user:
1878 return &bpf_probe_read_user_proto;
1879 case BPF_FUNC_probe_read_kernel:
1880 return security_locked_down(LOCKDOWN_BPF_READ_KERNEL) < 0 ?
1881 NULL : &bpf_probe_read_kernel_proto;
1882 case BPF_FUNC_probe_read_user_str:
1883 return &bpf_probe_read_user_str_proto;
1884 case BPF_FUNC_probe_read_kernel_str:
1885 return security_locked_down(LOCKDOWN_BPF_READ_KERNEL) < 0 ?
1886 NULL : &bpf_probe_read_kernel_str_proto;
1887 case BPF_FUNC_snprintf_btf:
1888 return &bpf_snprintf_btf_proto;
1889 case BPF_FUNC_snprintf:
1890 return &bpf_snprintf_proto;
1891 case BPF_FUNC_task_pt_regs:
1892 return &bpf_task_pt_regs_proto;
1893 case BPF_FUNC_trace_vprintk:
1894 return bpf_get_trace_vprintk_proto();
1895 default:
1896 return NULL;
1897 }
1898 }
1899
1900 void __bpf_obj_drop_impl(void *p, const struct btf_record *rec);
1901
bpf_list_head_free(const struct btf_field * field,void * list_head,struct bpf_spin_lock * spin_lock)1902 void bpf_list_head_free(const struct btf_field *field, void *list_head,
1903 struct bpf_spin_lock *spin_lock)
1904 {
1905 struct list_head *head = list_head, *orig_head = list_head;
1906
1907 BUILD_BUG_ON(sizeof(struct list_head) > sizeof(struct bpf_list_head));
1908 BUILD_BUG_ON(__alignof__(struct list_head) > __alignof__(struct bpf_list_head));
1909
1910 /* Do the actual list draining outside the lock to not hold the lock for
1911 * too long, and also prevent deadlocks if tracing programs end up
1912 * executing on entry/exit of functions called inside the critical
1913 * section, and end up doing map ops that call bpf_list_head_free for
1914 * the same map value again.
1915 */
1916 __bpf_spin_lock_irqsave(spin_lock);
1917 if (!head->next || list_empty(head))
1918 goto unlock;
1919 head = head->next;
1920 unlock:
1921 INIT_LIST_HEAD(orig_head);
1922 __bpf_spin_unlock_irqrestore(spin_lock);
1923
1924 while (head != orig_head) {
1925 void *obj = head;
1926
1927 obj -= field->graph_root.node_offset;
1928 head = head->next;
1929 /* The contained type can also have resources, including a
1930 * bpf_list_head which needs to be freed.
1931 */
1932 migrate_disable();
1933 __bpf_obj_drop_impl(obj, field->graph_root.value_rec);
1934 migrate_enable();
1935 }
1936 }
1937
1938 /* Like rbtree_postorder_for_each_entry_safe, but 'pos' and 'n' are
1939 * 'rb_node *', so field name of rb_node within containing struct is not
1940 * needed.
1941 *
1942 * Since bpf_rb_tree's node type has a corresponding struct btf_field with
1943 * graph_root.node_offset, it's not necessary to know field name
1944 * or type of node struct
1945 */
1946 #define bpf_rbtree_postorder_for_each_entry_safe(pos, n, root) \
1947 for (pos = rb_first_postorder(root); \
1948 pos && ({ n = rb_next_postorder(pos); 1; }); \
1949 pos = n)
1950
bpf_rb_root_free(const struct btf_field * field,void * rb_root,struct bpf_spin_lock * spin_lock)1951 void bpf_rb_root_free(const struct btf_field *field, void *rb_root,
1952 struct bpf_spin_lock *spin_lock)
1953 {
1954 struct rb_root_cached orig_root, *root = rb_root;
1955 struct rb_node *pos, *n;
1956 void *obj;
1957
1958 BUILD_BUG_ON(sizeof(struct rb_root_cached) > sizeof(struct bpf_rb_root));
1959 BUILD_BUG_ON(__alignof__(struct rb_root_cached) > __alignof__(struct bpf_rb_root));
1960
1961 __bpf_spin_lock_irqsave(spin_lock);
1962 orig_root = *root;
1963 *root = RB_ROOT_CACHED;
1964 __bpf_spin_unlock_irqrestore(spin_lock);
1965
1966 bpf_rbtree_postorder_for_each_entry_safe(pos, n, &orig_root.rb_root) {
1967 obj = pos;
1968 obj -= field->graph_root.node_offset;
1969
1970
1971 migrate_disable();
1972 __bpf_obj_drop_impl(obj, field->graph_root.value_rec);
1973 migrate_enable();
1974 }
1975 }
1976
1977 __diag_push();
1978 __diag_ignore_all("-Wmissing-prototypes",
1979 "Global functions as their definitions will be in vmlinux BTF");
1980
bpf_obj_new_impl(u64 local_type_id__k,void * meta__ign)1981 __bpf_kfunc void *bpf_obj_new_impl(u64 local_type_id__k, void *meta__ign)
1982 {
1983 struct btf_struct_meta *meta = meta__ign;
1984 u64 size = local_type_id__k;
1985 void *p;
1986
1987 p = bpf_mem_alloc(&bpf_global_ma, size);
1988 if (!p)
1989 return NULL;
1990 if (meta)
1991 bpf_obj_init(meta->record, p);
1992 return p;
1993 }
1994
1995 /* Must be called under migrate_disable(), as required by bpf_mem_free */
__bpf_obj_drop_impl(void * p,const struct btf_record * rec)1996 void __bpf_obj_drop_impl(void *p, const struct btf_record *rec)
1997 {
1998 if (rec && rec->refcount_off >= 0 &&
1999 !refcount_dec_and_test((refcount_t *)(p + rec->refcount_off))) {
2000 /* Object is refcounted and refcount_dec didn't result in 0
2001 * refcount. Return without freeing the object
2002 */
2003 return;
2004 }
2005
2006 if (rec)
2007 bpf_obj_free_fields(rec, p);
2008
2009 if (rec && rec->refcount_off >= 0)
2010 bpf_mem_free_rcu(&bpf_global_ma, p);
2011 else
2012 bpf_mem_free(&bpf_global_ma, p);
2013 }
2014
bpf_obj_drop_impl(void * p__alloc,void * meta__ign)2015 __bpf_kfunc void bpf_obj_drop_impl(void *p__alloc, void *meta__ign)
2016 {
2017 struct btf_struct_meta *meta = meta__ign;
2018 void *p = p__alloc;
2019
2020 __bpf_obj_drop_impl(p, meta ? meta->record : NULL);
2021 }
2022
bpf_refcount_acquire_impl(void * p__refcounted_kptr,void * meta__ign)2023 __bpf_kfunc void *bpf_refcount_acquire_impl(void *p__refcounted_kptr, void *meta__ign)
2024 {
2025 struct btf_struct_meta *meta = meta__ign;
2026 struct bpf_refcount *ref;
2027
2028 /* Could just cast directly to refcount_t *, but need some code using
2029 * bpf_refcount type so that it is emitted in vmlinux BTF
2030 */
2031 ref = (struct bpf_refcount *)(p__refcounted_kptr + meta->record->refcount_off);
2032 if (!refcount_inc_not_zero((refcount_t *)ref))
2033 return NULL;
2034
2035 /* Verifier strips KF_RET_NULL if input is owned ref, see is_kfunc_ret_null
2036 * in verifier.c
2037 */
2038 return (void *)p__refcounted_kptr;
2039 }
2040
__bpf_list_add(struct bpf_list_node_kern * node,struct bpf_list_head * head,bool tail,struct btf_record * rec,u64 off)2041 static int __bpf_list_add(struct bpf_list_node_kern *node,
2042 struct bpf_list_head *head,
2043 bool tail, struct btf_record *rec, u64 off)
2044 {
2045 struct list_head *n = &node->list_head, *h = (void *)head;
2046
2047 /* If list_head was 0-initialized by map, bpf_obj_init_field wasn't
2048 * called on its fields, so init here
2049 */
2050 if (unlikely(!h->next))
2051 INIT_LIST_HEAD(h);
2052
2053 /* node->owner != NULL implies !list_empty(n), no need to separately
2054 * check the latter
2055 */
2056 if (cmpxchg(&node->owner, NULL, BPF_PTR_POISON)) {
2057 /* Only called from BPF prog, no need to migrate_disable */
2058 __bpf_obj_drop_impl((void *)n - off, rec);
2059 return -EINVAL;
2060 }
2061
2062 tail ? list_add_tail(n, h) : list_add(n, h);
2063 WRITE_ONCE(node->owner, head);
2064
2065 return 0;
2066 }
2067
bpf_list_push_front_impl(struct bpf_list_head * head,struct bpf_list_node * node,void * meta__ign,u64 off)2068 __bpf_kfunc int bpf_list_push_front_impl(struct bpf_list_head *head,
2069 struct bpf_list_node *node,
2070 void *meta__ign, u64 off)
2071 {
2072 struct bpf_list_node_kern *n = (void *)node;
2073 struct btf_struct_meta *meta = meta__ign;
2074
2075 return __bpf_list_add(n, head, false, meta ? meta->record : NULL, off);
2076 }
2077
bpf_list_push_back_impl(struct bpf_list_head * head,struct bpf_list_node * node,void * meta__ign,u64 off)2078 __bpf_kfunc int bpf_list_push_back_impl(struct bpf_list_head *head,
2079 struct bpf_list_node *node,
2080 void *meta__ign, u64 off)
2081 {
2082 struct bpf_list_node_kern *n = (void *)node;
2083 struct btf_struct_meta *meta = meta__ign;
2084
2085 return __bpf_list_add(n, head, true, meta ? meta->record : NULL, off);
2086 }
2087
__bpf_list_del(struct bpf_list_head * head,bool tail)2088 static struct bpf_list_node *__bpf_list_del(struct bpf_list_head *head, bool tail)
2089 {
2090 struct list_head *n, *h = (void *)head;
2091 struct bpf_list_node_kern *node;
2092
2093 /* If list_head was 0-initialized by map, bpf_obj_init_field wasn't
2094 * called on its fields, so init here
2095 */
2096 if (unlikely(!h->next))
2097 INIT_LIST_HEAD(h);
2098 if (list_empty(h))
2099 return NULL;
2100
2101 n = tail ? h->prev : h->next;
2102 node = container_of(n, struct bpf_list_node_kern, list_head);
2103 if (WARN_ON_ONCE(READ_ONCE(node->owner) != head))
2104 return NULL;
2105
2106 list_del_init(n);
2107 WRITE_ONCE(node->owner, NULL);
2108 return (struct bpf_list_node *)n;
2109 }
2110
bpf_list_pop_front(struct bpf_list_head * head)2111 __bpf_kfunc struct bpf_list_node *bpf_list_pop_front(struct bpf_list_head *head)
2112 {
2113 return __bpf_list_del(head, false);
2114 }
2115
bpf_list_pop_back(struct bpf_list_head * head)2116 __bpf_kfunc struct bpf_list_node *bpf_list_pop_back(struct bpf_list_head *head)
2117 {
2118 return __bpf_list_del(head, true);
2119 }
2120
bpf_rbtree_remove(struct bpf_rb_root * root,struct bpf_rb_node * node)2121 __bpf_kfunc struct bpf_rb_node *bpf_rbtree_remove(struct bpf_rb_root *root,
2122 struct bpf_rb_node *node)
2123 {
2124 struct bpf_rb_node_kern *node_internal = (struct bpf_rb_node_kern *)node;
2125 struct rb_root_cached *r = (struct rb_root_cached *)root;
2126 struct rb_node *n = &node_internal->rb_node;
2127
2128 /* node_internal->owner != root implies either RB_EMPTY_NODE(n) or
2129 * n is owned by some other tree. No need to check RB_EMPTY_NODE(n)
2130 */
2131 if (READ_ONCE(node_internal->owner) != root)
2132 return NULL;
2133
2134 rb_erase_cached(n, r);
2135 RB_CLEAR_NODE(n);
2136 WRITE_ONCE(node_internal->owner, NULL);
2137 return (struct bpf_rb_node *)n;
2138 }
2139
2140 /* Need to copy rbtree_add_cached's logic here because our 'less' is a BPF
2141 * program
2142 */
__bpf_rbtree_add(struct bpf_rb_root * root,struct bpf_rb_node_kern * node,void * less,struct btf_record * rec,u64 off)2143 static int __bpf_rbtree_add(struct bpf_rb_root *root,
2144 struct bpf_rb_node_kern *node,
2145 void *less, struct btf_record *rec, u64 off)
2146 {
2147 struct rb_node **link = &((struct rb_root_cached *)root)->rb_root.rb_node;
2148 struct rb_node *parent = NULL, *n = &node->rb_node;
2149 bpf_callback_t cb = (bpf_callback_t)less;
2150 bool leftmost = true;
2151
2152 /* node->owner != NULL implies !RB_EMPTY_NODE(n), no need to separately
2153 * check the latter
2154 */
2155 if (cmpxchg(&node->owner, NULL, BPF_PTR_POISON)) {
2156 /* Only called from BPF prog, no need to migrate_disable */
2157 __bpf_obj_drop_impl((void *)n - off, rec);
2158 return -EINVAL;
2159 }
2160
2161 while (*link) {
2162 parent = *link;
2163 if (cb((uintptr_t)node, (uintptr_t)parent, 0, 0, 0)) {
2164 link = &parent->rb_left;
2165 } else {
2166 link = &parent->rb_right;
2167 leftmost = false;
2168 }
2169 }
2170
2171 rb_link_node(n, parent, link);
2172 rb_insert_color_cached(n, (struct rb_root_cached *)root, leftmost);
2173 WRITE_ONCE(node->owner, root);
2174 return 0;
2175 }
2176
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)2177 __bpf_kfunc int bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node,
2178 bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b),
2179 void *meta__ign, u64 off)
2180 {
2181 struct btf_struct_meta *meta = meta__ign;
2182 struct bpf_rb_node_kern *n = (void *)node;
2183
2184 return __bpf_rbtree_add(root, n, (void *)less, meta ? meta->record : NULL, off);
2185 }
2186
bpf_rbtree_first(struct bpf_rb_root * root)2187 __bpf_kfunc struct bpf_rb_node *bpf_rbtree_first(struct bpf_rb_root *root)
2188 {
2189 struct rb_root_cached *r = (struct rb_root_cached *)root;
2190
2191 return (struct bpf_rb_node *)rb_first_cached(r);
2192 }
2193
2194 /**
2195 * bpf_task_acquire - Acquire a reference to a task. A task acquired by this
2196 * kfunc which is not stored in a map as a kptr, must be released by calling
2197 * bpf_task_release().
2198 * @p: The task on which a reference is being acquired.
2199 */
bpf_task_acquire(struct task_struct * p)2200 __bpf_kfunc struct task_struct *bpf_task_acquire(struct task_struct *p)
2201 {
2202 if (refcount_inc_not_zero(&p->rcu_users))
2203 return p;
2204 return NULL;
2205 }
2206
2207 /**
2208 * bpf_task_release - Release the reference acquired on a task.
2209 * @p: The task on which a reference is being released.
2210 */
bpf_task_release(struct task_struct * p)2211 __bpf_kfunc void bpf_task_release(struct task_struct *p)
2212 {
2213 put_task_struct_rcu_user(p);
2214 }
2215
2216 #ifdef CONFIG_CGROUPS
2217 /**
2218 * bpf_cgroup_acquire - Acquire a reference to a cgroup. A cgroup acquired by
2219 * this kfunc which is not stored in a map as a kptr, must be released by
2220 * calling bpf_cgroup_release().
2221 * @cgrp: The cgroup on which a reference is being acquired.
2222 */
bpf_cgroup_acquire(struct cgroup * cgrp)2223 __bpf_kfunc struct cgroup *bpf_cgroup_acquire(struct cgroup *cgrp)
2224 {
2225 return cgroup_tryget(cgrp) ? cgrp : NULL;
2226 }
2227
2228 /**
2229 * bpf_cgroup_release - Release the reference acquired on a cgroup.
2230 * If this kfunc is invoked in an RCU read region, the cgroup is guaranteed to
2231 * not be freed until the current grace period has ended, even if its refcount
2232 * drops to 0.
2233 * @cgrp: The cgroup on which a reference is being released.
2234 */
bpf_cgroup_release(struct cgroup * cgrp)2235 __bpf_kfunc void bpf_cgroup_release(struct cgroup *cgrp)
2236 {
2237 cgroup_put(cgrp);
2238 }
2239
2240 /**
2241 * bpf_cgroup_ancestor - Perform a lookup on an entry in a cgroup's ancestor
2242 * array. A cgroup returned by this kfunc which is not subsequently stored in a
2243 * map, must be released by calling bpf_cgroup_release().
2244 * @cgrp: The cgroup for which we're performing a lookup.
2245 * @level: The level of ancestor to look up.
2246 */
bpf_cgroup_ancestor(struct cgroup * cgrp,int level)2247 __bpf_kfunc struct cgroup *bpf_cgroup_ancestor(struct cgroup *cgrp, int level)
2248 {
2249 struct cgroup *ancestor;
2250
2251 if (level > cgrp->level || level < 0)
2252 return NULL;
2253
2254 /* cgrp's refcnt could be 0 here, but ancestors can still be accessed */
2255 ancestor = cgrp->ancestors[level];
2256 if (!cgroup_tryget(ancestor))
2257 return NULL;
2258 return ancestor;
2259 }
2260
2261 /**
2262 * bpf_cgroup_from_id - Find a cgroup from its ID. A cgroup returned by this
2263 * kfunc which is not subsequently stored in a map, must be released by calling
2264 * bpf_cgroup_release().
2265 * @cgid: cgroup id.
2266 */
bpf_cgroup_from_id(u64 cgid)2267 __bpf_kfunc struct cgroup *bpf_cgroup_from_id(u64 cgid)
2268 {
2269 struct cgroup *cgrp;
2270
2271 cgrp = cgroup_get_from_id(cgid);
2272 if (IS_ERR(cgrp))
2273 return NULL;
2274 return cgrp;
2275 }
2276
2277 /**
2278 * bpf_task_under_cgroup - wrap task_under_cgroup_hierarchy() as a kfunc, test
2279 * task's membership of cgroup ancestry.
2280 * @task: the task to be tested
2281 * @ancestor: possible ancestor of @task's cgroup
2282 *
2283 * Tests whether @task's default cgroup hierarchy is a descendant of @ancestor.
2284 * It follows all the same rules as cgroup_is_descendant, and only applies
2285 * to the default hierarchy.
2286 */
bpf_task_under_cgroup(struct task_struct * task,struct cgroup * ancestor)2287 __bpf_kfunc long bpf_task_under_cgroup(struct task_struct *task,
2288 struct cgroup *ancestor)
2289 {
2290 long ret;
2291
2292 rcu_read_lock();
2293 ret = task_under_cgroup_hierarchy(task, ancestor);
2294 rcu_read_unlock();
2295 return ret;
2296 }
2297 #endif /* CONFIG_CGROUPS */
2298
2299 /**
2300 * bpf_task_from_pid - Find a struct task_struct from its pid by looking it up
2301 * in the root pid namespace idr. If a task is returned, it must either be
2302 * stored in a map, or released with bpf_task_release().
2303 * @pid: The pid of the task being looked up.
2304 */
bpf_task_from_pid(s32 pid)2305 __bpf_kfunc struct task_struct *bpf_task_from_pid(s32 pid)
2306 {
2307 struct task_struct *p;
2308
2309 rcu_read_lock();
2310 p = find_task_by_pid_ns(pid, &init_pid_ns);
2311 if (p)
2312 p = bpf_task_acquire(p);
2313 rcu_read_unlock();
2314
2315 return p;
2316 }
2317
2318 /**
2319 * bpf_dynptr_slice() - Obtain a read-only pointer to the dynptr data.
2320 * @ptr: The dynptr whose data slice to retrieve
2321 * @offset: Offset into the dynptr
2322 * @buffer__opt: User-provided buffer to copy contents into. May be NULL
2323 * @buffer__szk: Size (in bytes) of the buffer if present. This is the
2324 * length of the requested slice. This must be a constant.
2325 *
2326 * For non-skb and non-xdp type dynptrs, there is no difference between
2327 * bpf_dynptr_slice and bpf_dynptr_data.
2328 *
2329 * If buffer__opt is NULL, the call will fail if buffer_opt was needed.
2330 *
2331 * If the intention is to write to the data slice, please use
2332 * bpf_dynptr_slice_rdwr.
2333 *
2334 * The user must check that the returned pointer is not null before using it.
2335 *
2336 * Please note that in the case of skb and xdp dynptrs, bpf_dynptr_slice
2337 * does not change the underlying packet data pointers, so a call to
2338 * bpf_dynptr_slice will not invalidate any ctx->data/data_end pointers in
2339 * the bpf program.
2340 *
2341 * Return: NULL if the call failed (eg invalid dynptr), pointer to a read-only
2342 * data slice (can be either direct pointer to the data or a pointer to the user
2343 * provided buffer, with its contents containing the data, if unable to obtain
2344 * direct pointer)
2345 */
bpf_dynptr_slice(const struct bpf_dynptr_kern * ptr,u32 offset,void * buffer__opt,u32 buffer__szk)2346 __bpf_kfunc void *bpf_dynptr_slice(const struct bpf_dynptr_kern *ptr, u32 offset,
2347 void *buffer__opt, u32 buffer__szk)
2348 {
2349 enum bpf_dynptr_type type;
2350 u32 len = buffer__szk;
2351 int err;
2352
2353 if (!ptr->data)
2354 return NULL;
2355
2356 err = bpf_dynptr_check_off_len(ptr, offset, len);
2357 if (err)
2358 return NULL;
2359
2360 type = bpf_dynptr_get_type(ptr);
2361
2362 switch (type) {
2363 case BPF_DYNPTR_TYPE_LOCAL:
2364 case BPF_DYNPTR_TYPE_RINGBUF:
2365 return ptr->data + ptr->offset + offset;
2366 case BPF_DYNPTR_TYPE_SKB:
2367 if (buffer__opt)
2368 return skb_header_pointer(ptr->data, ptr->offset + offset, len, buffer__opt);
2369 else
2370 return skb_pointer_if_linear(ptr->data, ptr->offset + offset, len);
2371 case BPF_DYNPTR_TYPE_XDP:
2372 {
2373 void *xdp_ptr = bpf_xdp_pointer(ptr->data, ptr->offset + offset, len);
2374 if (!IS_ERR_OR_NULL(xdp_ptr))
2375 return xdp_ptr;
2376
2377 if (!buffer__opt)
2378 return NULL;
2379 bpf_xdp_copy_buf(ptr->data, ptr->offset + offset, buffer__opt, len, false);
2380 return buffer__opt;
2381 }
2382 default:
2383 WARN_ONCE(true, "unknown dynptr type %d\n", type);
2384 return NULL;
2385 }
2386 }
2387
2388 /**
2389 * bpf_dynptr_slice_rdwr() - Obtain a writable pointer to the dynptr data.
2390 * @ptr: The dynptr whose data slice to retrieve
2391 * @offset: Offset into the dynptr
2392 * @buffer__opt: User-provided buffer to copy contents into. May be NULL
2393 * @buffer__szk: Size (in bytes) of the buffer if present. This is the
2394 * length of the requested slice. This must be a constant.
2395 *
2396 * For non-skb and non-xdp type dynptrs, there is no difference between
2397 * bpf_dynptr_slice and bpf_dynptr_data.
2398 *
2399 * If buffer__opt is NULL, the call will fail if buffer_opt was needed.
2400 *
2401 * The returned pointer is writable and may point to either directly the dynptr
2402 * data at the requested offset or to the buffer if unable to obtain a direct
2403 * data pointer to (example: the requested slice is to the paged area of an skb
2404 * packet). In the case where the returned pointer is to the buffer, the user
2405 * is responsible for persisting writes through calling bpf_dynptr_write(). This
2406 * usually looks something like this pattern:
2407 *
2408 * struct eth_hdr *eth = bpf_dynptr_slice_rdwr(&dynptr, 0, buffer, sizeof(buffer));
2409 * if (!eth)
2410 * return TC_ACT_SHOT;
2411 *
2412 * // mutate eth header //
2413 *
2414 * if (eth == buffer)
2415 * bpf_dynptr_write(&ptr, 0, buffer, sizeof(buffer), 0);
2416 *
2417 * Please note that, as in the example above, the user must check that the
2418 * returned pointer is not null before using it.
2419 *
2420 * Please also note that in the case of skb and xdp dynptrs, bpf_dynptr_slice_rdwr
2421 * does not change the underlying packet data pointers, so a call to
2422 * bpf_dynptr_slice_rdwr will not invalidate any ctx->data/data_end pointers in
2423 * the bpf program.
2424 *
2425 * Return: NULL if the call failed (eg invalid dynptr), pointer to a
2426 * data slice (can be either direct pointer to the data or a pointer to the user
2427 * provided buffer, with its contents containing the data, if unable to obtain
2428 * direct pointer)
2429 */
bpf_dynptr_slice_rdwr(const struct bpf_dynptr_kern * ptr,u32 offset,void * buffer__opt,u32 buffer__szk)2430 __bpf_kfunc void *bpf_dynptr_slice_rdwr(const struct bpf_dynptr_kern *ptr, u32 offset,
2431 void *buffer__opt, u32 buffer__szk)
2432 {
2433 if (!ptr->data || __bpf_dynptr_is_rdonly(ptr))
2434 return NULL;
2435
2436 /* bpf_dynptr_slice_rdwr is the same logic as bpf_dynptr_slice.
2437 *
2438 * For skb-type dynptrs, it is safe to write into the returned pointer
2439 * if the bpf program allows skb data writes. There are two possiblities
2440 * that may occur when calling bpf_dynptr_slice_rdwr:
2441 *
2442 * 1) The requested slice is in the head of the skb. In this case, the
2443 * returned pointer is directly to skb data, and if the skb is cloned, the
2444 * verifier will have uncloned it (see bpf_unclone_prologue()) already.
2445 * The pointer can be directly written into.
2446 *
2447 * 2) Some portion of the requested slice is in the paged buffer area.
2448 * In this case, the requested data will be copied out into the buffer
2449 * and the returned pointer will be a pointer to the buffer. The skb
2450 * will not be pulled. To persist the write, the user will need to call
2451 * bpf_dynptr_write(), which will pull the skb and commit the write.
2452 *
2453 * Similarly for xdp programs, if the requested slice is not across xdp
2454 * fragments, then a direct pointer will be returned, otherwise the data
2455 * will be copied out into the buffer and the user will need to call
2456 * bpf_dynptr_write() to commit changes.
2457 */
2458 return bpf_dynptr_slice(ptr, offset, buffer__opt, buffer__szk);
2459 }
2460
bpf_dynptr_adjust(struct bpf_dynptr_kern * ptr,u32 start,u32 end)2461 __bpf_kfunc int bpf_dynptr_adjust(struct bpf_dynptr_kern *ptr, u32 start, u32 end)
2462 {
2463 u32 size;
2464
2465 if (!ptr->data || start > end)
2466 return -EINVAL;
2467
2468 size = __bpf_dynptr_size(ptr);
2469
2470 if (start > size || end > size)
2471 return -ERANGE;
2472
2473 ptr->offset += start;
2474 bpf_dynptr_set_size(ptr, end - start);
2475
2476 return 0;
2477 }
2478
bpf_dynptr_is_null(struct bpf_dynptr_kern * ptr)2479 __bpf_kfunc bool bpf_dynptr_is_null(struct bpf_dynptr_kern *ptr)
2480 {
2481 return !ptr->data;
2482 }
2483
bpf_dynptr_is_rdonly(struct bpf_dynptr_kern * ptr)2484 __bpf_kfunc bool bpf_dynptr_is_rdonly(struct bpf_dynptr_kern *ptr)
2485 {
2486 if (!ptr->data)
2487 return false;
2488
2489 return __bpf_dynptr_is_rdonly(ptr);
2490 }
2491
bpf_dynptr_size(const struct bpf_dynptr_kern * ptr)2492 __bpf_kfunc __u32 bpf_dynptr_size(const struct bpf_dynptr_kern *ptr)
2493 {
2494 if (!ptr->data)
2495 return -EINVAL;
2496
2497 return __bpf_dynptr_size(ptr);
2498 }
2499
bpf_dynptr_clone(struct bpf_dynptr_kern * ptr,struct bpf_dynptr_kern * clone__uninit)2500 __bpf_kfunc int bpf_dynptr_clone(struct bpf_dynptr_kern *ptr,
2501 struct bpf_dynptr_kern *clone__uninit)
2502 {
2503 if (!ptr->data) {
2504 bpf_dynptr_set_null(clone__uninit);
2505 return -EINVAL;
2506 }
2507
2508 *clone__uninit = *ptr;
2509
2510 return 0;
2511 }
2512
bpf_cast_to_kern_ctx(void * obj)2513 __bpf_kfunc void *bpf_cast_to_kern_ctx(void *obj)
2514 {
2515 return obj;
2516 }
2517
bpf_rdonly_cast(void * obj__ign,u32 btf_id__k)2518 __bpf_kfunc void *bpf_rdonly_cast(void *obj__ign, u32 btf_id__k)
2519 {
2520 return obj__ign;
2521 }
2522
bpf_rcu_read_lock(void)2523 __bpf_kfunc void bpf_rcu_read_lock(void)
2524 {
2525 rcu_read_lock();
2526 }
2527
bpf_rcu_read_unlock(void)2528 __bpf_kfunc void bpf_rcu_read_unlock(void)
2529 {
2530 rcu_read_unlock();
2531 }
2532
2533 __diag_pop();
2534
2535 BTF_SET8_START(generic_btf_ids)
2536 #ifdef CONFIG_KEXEC_CORE
2537 BTF_ID_FLAGS(func, crash_kexec, KF_DESTRUCTIVE)
2538 #endif
2539 BTF_ID_FLAGS(func, bpf_obj_new_impl, KF_ACQUIRE | KF_RET_NULL)
2540 BTF_ID_FLAGS(func, bpf_obj_drop_impl, KF_RELEASE)
2541 BTF_ID_FLAGS(func, bpf_refcount_acquire_impl, KF_ACQUIRE | KF_RET_NULL)
2542 BTF_ID_FLAGS(func, bpf_list_push_front_impl)
2543 BTF_ID_FLAGS(func, bpf_list_push_back_impl)
2544 BTF_ID_FLAGS(func, bpf_list_pop_front, KF_ACQUIRE | KF_RET_NULL)
2545 BTF_ID_FLAGS(func, bpf_list_pop_back, KF_ACQUIRE | KF_RET_NULL)
2546 BTF_ID_FLAGS(func, bpf_task_acquire, KF_ACQUIRE | KF_RCU | KF_RET_NULL)
2547 BTF_ID_FLAGS(func, bpf_task_release, KF_RELEASE)
2548 BTF_ID_FLAGS(func, bpf_rbtree_remove, KF_ACQUIRE | KF_RET_NULL)
2549 BTF_ID_FLAGS(func, bpf_rbtree_add_impl)
2550 BTF_ID_FLAGS(func, bpf_rbtree_first, KF_RET_NULL)
2551
2552 #ifdef CONFIG_CGROUPS
2553 BTF_ID_FLAGS(func, bpf_cgroup_acquire, KF_ACQUIRE | KF_RCU | KF_RET_NULL)
2554 BTF_ID_FLAGS(func, bpf_cgroup_release, KF_RELEASE)
2555 BTF_ID_FLAGS(func, bpf_cgroup_ancestor, KF_ACQUIRE | KF_RCU | KF_RET_NULL)
2556 BTF_ID_FLAGS(func, bpf_cgroup_from_id, KF_ACQUIRE | KF_RET_NULL)
2557 BTF_ID_FLAGS(func, bpf_task_under_cgroup, KF_RCU)
2558 #endif
2559 BTF_ID_FLAGS(func, bpf_task_from_pid, KF_ACQUIRE | KF_RET_NULL)
2560 BTF_SET8_END(generic_btf_ids)
2561
2562 static const struct btf_kfunc_id_set generic_kfunc_set = {
2563 .owner = THIS_MODULE,
2564 .set = &generic_btf_ids,
2565 };
2566
2567
2568 BTF_ID_LIST(generic_dtor_ids)
2569 BTF_ID(struct, task_struct)
2570 BTF_ID(func, bpf_task_release)
2571 #ifdef CONFIG_CGROUPS
2572 BTF_ID(struct, cgroup)
2573 BTF_ID(func, bpf_cgroup_release)
2574 #endif
2575
2576 BTF_SET8_START(common_btf_ids)
2577 BTF_ID_FLAGS(func, bpf_cast_to_kern_ctx)
2578 BTF_ID_FLAGS(func, bpf_rdonly_cast)
2579 BTF_ID_FLAGS(func, bpf_rcu_read_lock)
2580 BTF_ID_FLAGS(func, bpf_rcu_read_unlock)
2581 BTF_ID_FLAGS(func, bpf_dynptr_slice, KF_RET_NULL)
2582 BTF_ID_FLAGS(func, bpf_dynptr_slice_rdwr, KF_RET_NULL)
2583 BTF_ID_FLAGS(func, bpf_iter_num_new, KF_ITER_NEW)
2584 BTF_ID_FLAGS(func, bpf_iter_num_next, KF_ITER_NEXT | KF_RET_NULL)
2585 BTF_ID_FLAGS(func, bpf_iter_num_destroy, KF_ITER_DESTROY)
2586 BTF_ID_FLAGS(func, bpf_dynptr_adjust)
2587 BTF_ID_FLAGS(func, bpf_dynptr_is_null)
2588 BTF_ID_FLAGS(func, bpf_dynptr_is_rdonly)
2589 BTF_ID_FLAGS(func, bpf_dynptr_size)
2590 BTF_ID_FLAGS(func, bpf_dynptr_clone)
2591 BTF_SET8_END(common_btf_ids)
2592
2593 static const struct btf_kfunc_id_set common_kfunc_set = {
2594 .owner = THIS_MODULE,
2595 .set = &common_btf_ids,
2596 };
2597
kfunc_init(void)2598 static int __init kfunc_init(void)
2599 {
2600 int ret;
2601 const struct btf_id_dtor_kfunc generic_dtors[] = {
2602 {
2603 .btf_id = generic_dtor_ids[0],
2604 .kfunc_btf_id = generic_dtor_ids[1]
2605 },
2606 #ifdef CONFIG_CGROUPS
2607 {
2608 .btf_id = generic_dtor_ids[2],
2609 .kfunc_btf_id = generic_dtor_ids[3]
2610 },
2611 #endif
2612 };
2613
2614 ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_TRACING, &generic_kfunc_set);
2615 ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_SCHED_CLS, &generic_kfunc_set);
2616 ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS, &generic_kfunc_set);
2617 ret = ret ?: register_btf_id_dtor_kfuncs(generic_dtors,
2618 ARRAY_SIZE(generic_dtors),
2619 THIS_MODULE);
2620 return ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_UNSPEC, &common_kfunc_set);
2621 }
2622
2623 late_initcall(kfunc_init);
2624