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