xref: /linux/kernel/bpf/helpers.c (revision ec274bb4665c2f0e42316d0f9e4ac9f63cda9c1d)
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 #include <linux/kasan.h>
26 #include <linux/bpf_verifier.h>
27 #include <linux/uaccess.h>
28 #include <linux/verification.h>
29 #include <linux/task_work.h>
30 #include <linux/irq_work.h>
31 #include <linux/buildid.h>
32 
33 #include "../../lib/kstrtox.h"
34 
35 /* If kernel subsystem is allowing eBPF programs to call this function,
36  * inside its own verifier_ops->get_func_proto() callback it should return
37  * bpf_map_lookup_elem_proto, so that verifier can properly check the arguments
38  *
39  * Different map implementations will rely on rcu in map methods
40  * lookup/update/delete, therefore eBPF programs must run under rcu lock
41  * if program is allowed to access maps, so check rcu_read_lock_held() or
42  * rcu_read_lock_trace_held() in all three functions.
43  */
44 BPF_CALL_2(bpf_map_lookup_elem, struct bpf_map *, map, void *, key)
45 {
46 	WARN_ON_ONCE(!bpf_rcu_lock_held());
47 	return (unsigned long) map->ops->map_lookup_elem(map, key);
48 }
49 
50 const struct bpf_func_proto bpf_map_lookup_elem_proto = {
51 	.func		= bpf_map_lookup_elem,
52 	.gpl_only	= false,
53 	.pkt_access	= true,
54 	.ret_type	= RET_PTR_TO_MAP_VALUE_OR_NULL,
55 	.arg1_type	= ARG_CONST_MAP_PTR,
56 	.arg2_type	= ARG_PTR_TO_MAP_KEY,
57 };
58 
59 BPF_CALL_4(bpf_map_update_elem, struct bpf_map *, map, void *, key,
60 	   void *, value, u64, flags)
61 {
62 	WARN_ON_ONCE(!bpf_rcu_lock_held());
63 	return map->ops->map_update_elem(map, key, value, flags);
64 }
65 
66 const struct bpf_func_proto bpf_map_update_elem_proto = {
67 	.func		= bpf_map_update_elem,
68 	.gpl_only	= false,
69 	.pkt_access	= true,
70 	.ret_type	= RET_INTEGER,
71 	.arg1_type	= ARG_CONST_MAP_PTR,
72 	.arg2_type	= ARG_PTR_TO_MAP_KEY,
73 	.arg3_type	= ARG_PTR_TO_MAP_VALUE,
74 	.arg4_type	= ARG_ANYTHING,
75 };
76 
77 BPF_CALL_2(bpf_map_delete_elem, struct bpf_map *, map, void *, key)
78 {
79 	WARN_ON_ONCE(!bpf_rcu_lock_held());
80 	return map->ops->map_delete_elem(map, key);
81 }
82 
83 const struct bpf_func_proto bpf_map_delete_elem_proto = {
84 	.func		= bpf_map_delete_elem,
85 	.gpl_only	= false,
86 	.pkt_access	= true,
87 	.ret_type	= RET_INTEGER,
88 	.arg1_type	= ARG_CONST_MAP_PTR,
89 	.arg2_type	= ARG_PTR_TO_MAP_KEY,
90 };
91 
92 BPF_CALL_3(bpf_map_push_elem, struct bpf_map *, map, void *, value, u64, flags)
93 {
94 	return map->ops->map_push_elem(map, value, flags);
95 }
96 
97 const struct bpf_func_proto bpf_map_push_elem_proto = {
98 	.func		= bpf_map_push_elem,
99 	.gpl_only	= false,
100 	.pkt_access	= true,
101 	.ret_type	= RET_INTEGER,
102 	.arg1_type	= ARG_CONST_MAP_PTR,
103 	.arg2_type	= ARG_PTR_TO_MAP_VALUE,
104 	.arg3_type	= ARG_ANYTHING,
105 };
106 
107 BPF_CALL_2(bpf_map_pop_elem, struct bpf_map *, map, void *, value)
108 {
109 	return map->ops->map_pop_elem(map, value);
110 }
111 
112 const struct bpf_func_proto bpf_map_pop_elem_proto = {
113 	.func		= bpf_map_pop_elem,
114 	.gpl_only	= false,
115 	.ret_type	= RET_INTEGER,
116 	.arg1_type	= ARG_CONST_MAP_PTR,
117 	.arg2_type	= ARG_PTR_TO_MAP_VALUE | MEM_UNINIT | MEM_WRITE,
118 };
119 
120 BPF_CALL_2(bpf_map_peek_elem, struct bpf_map *, map, void *, value)
121 {
122 	return map->ops->map_peek_elem(map, value);
123 }
124 
125 const struct bpf_func_proto bpf_map_peek_elem_proto = {
126 	.func		= bpf_map_peek_elem,
127 	.gpl_only	= false,
128 	.ret_type	= RET_INTEGER,
129 	.arg1_type	= ARG_CONST_MAP_PTR,
130 	.arg2_type	= ARG_PTR_TO_MAP_VALUE | MEM_UNINIT | MEM_WRITE,
131 };
132 
133 BPF_CALL_3(bpf_map_lookup_percpu_elem, struct bpf_map *, map, void *, key, u32, cpu)
134 {
135 	WARN_ON_ONCE(!bpf_rcu_lock_held());
136 	return (unsigned long) map->ops->map_lookup_percpu_elem(map, key, cpu);
137 }
138 
139 const struct bpf_func_proto bpf_map_lookup_percpu_elem_proto = {
140 	.func		= bpf_map_lookup_percpu_elem,
141 	.gpl_only	= false,
142 	.pkt_access	= true,
143 	.ret_type	= RET_PTR_TO_MAP_VALUE_OR_NULL,
144 	.arg1_type	= ARG_CONST_MAP_PTR,
145 	.arg2_type	= ARG_PTR_TO_MAP_KEY,
146 	.arg3_type	= ARG_ANYTHING,
147 };
148 
149 const struct bpf_func_proto bpf_get_prandom_u32_proto = {
150 	.func		= bpf_user_rnd_u32,
151 	.gpl_only	= false,
152 	.ret_type	= RET_INTEGER,
153 };
154 
155 BPF_CALL_0(bpf_get_smp_processor_id)
156 {
157 	return smp_processor_id();
158 }
159 
160 const struct bpf_func_proto bpf_get_smp_processor_id_proto = {
161 	.func		= bpf_get_smp_processor_id,
162 	.gpl_only	= false,
163 	.ret_type	= RET_INTEGER,
164 	.allow_fastcall	= true,
165 };
166 
167 BPF_CALL_0(bpf_get_numa_node_id)
168 {
169 	return numa_node_id();
170 }
171 
172 const struct bpf_func_proto bpf_get_numa_node_id_proto = {
173 	.func		= bpf_get_numa_node_id,
174 	.gpl_only	= false,
175 	.ret_type	= RET_INTEGER,
176 };
177 
178 BPF_CALL_0(bpf_ktime_get_ns)
179 {
180 	/* NMI safe access to clock monotonic */
181 	return ktime_get_mono_fast_ns();
182 }
183 
184 const struct bpf_func_proto bpf_ktime_get_ns_proto = {
185 	.func		= bpf_ktime_get_ns,
186 	.gpl_only	= false,
187 	.ret_type	= RET_INTEGER,
188 };
189 
190 BPF_CALL_0(bpf_ktime_get_boot_ns)
191 {
192 	/* NMI safe access to clock boottime */
193 	return ktime_get_boot_fast_ns();
194 }
195 
196 const struct bpf_func_proto bpf_ktime_get_boot_ns_proto = {
197 	.func		= bpf_ktime_get_boot_ns,
198 	.gpl_only	= false,
199 	.ret_type	= RET_INTEGER,
200 };
201 
202 BPF_CALL_0(bpf_ktime_get_coarse_ns)
203 {
204 	return ktime_get_coarse_ns();
205 }
206 
207 const struct bpf_func_proto bpf_ktime_get_coarse_ns_proto = {
208 	.func		= bpf_ktime_get_coarse_ns,
209 	.gpl_only	= false,
210 	.ret_type	= RET_INTEGER,
211 };
212 
213 BPF_CALL_0(bpf_ktime_get_tai_ns)
214 {
215 	/* NMI safe access to clock tai */
216 	return ktime_get_tai_fast_ns();
217 }
218 
219 const struct bpf_func_proto bpf_ktime_get_tai_ns_proto = {
220 	.func		= bpf_ktime_get_tai_ns,
221 	.gpl_only	= false,
222 	.ret_type	= RET_INTEGER,
223 };
224 
225 BPF_CALL_0(bpf_get_current_pid_tgid)
226 {
227 	struct task_struct *task = current;
228 
229 	if (unlikely(!task))
230 		return -EINVAL;
231 
232 	return (u64) task->tgid << 32 | task->pid;
233 }
234 
235 const struct bpf_func_proto bpf_get_current_pid_tgid_proto = {
236 	.func		= bpf_get_current_pid_tgid,
237 	.gpl_only	= false,
238 	.ret_type	= RET_INTEGER,
239 };
240 
241 BPF_CALL_0(bpf_get_current_uid_gid)
242 {
243 	struct task_struct *task = current;
244 	kuid_t uid;
245 	kgid_t gid;
246 
247 	if (unlikely(!task))
248 		return -EINVAL;
249 
250 	current_uid_gid(&uid, &gid);
251 	return (u64) from_kgid(&init_user_ns, gid) << 32 |
252 		     from_kuid(&init_user_ns, uid);
253 }
254 
255 const struct bpf_func_proto bpf_get_current_uid_gid_proto = {
256 	.func		= bpf_get_current_uid_gid,
257 	.gpl_only	= false,
258 	.ret_type	= RET_INTEGER,
259 };
260 
261 BPF_CALL_2(bpf_get_current_comm, char *, buf, u32, size)
262 {
263 	struct task_struct *task = current;
264 
265 	if (unlikely(!task))
266 		goto err_clear;
267 
268 	/* Verifier guarantees that size > 0 */
269 	strscpy_pad(buf, task->comm, size);
270 	return 0;
271 err_clear:
272 	memset(buf, 0, size);
273 	return -EINVAL;
274 }
275 
276 const struct bpf_func_proto bpf_get_current_comm_proto = {
277 	.func		= bpf_get_current_comm,
278 	.gpl_only	= false,
279 	.ret_type	= RET_INTEGER,
280 	.arg1_type	= ARG_PTR_TO_UNINIT_MEM,
281 	.arg2_type	= ARG_MEM_SIZE,
282 };
283 
284 #if defined(CONFIG_QUEUED_SPINLOCKS) || defined(CONFIG_BPF_ARCH_SPINLOCK)
285 
286 static inline void __bpf_spin_lock(struct bpf_spin_lock *lock)
287 {
288 	arch_spinlock_t *l = (void *)lock;
289 	union {
290 		__u32 val;
291 		arch_spinlock_t lock;
292 	} u = { .lock = __ARCH_SPIN_LOCK_UNLOCKED };
293 
294 	compiletime_assert(u.val == 0, "__ARCH_SPIN_LOCK_UNLOCKED not 0");
295 	BUILD_BUG_ON(sizeof(*l) != sizeof(__u32));
296 	BUILD_BUG_ON(sizeof(*lock) != sizeof(__u32));
297 	preempt_disable();
298 	arch_spin_lock(l);
299 }
300 
301 static inline void __bpf_spin_unlock(struct bpf_spin_lock *lock)
302 {
303 	arch_spinlock_t *l = (void *)lock;
304 
305 	arch_spin_unlock(l);
306 	preempt_enable();
307 }
308 
309 #else
310 
311 static inline void __bpf_spin_lock(struct bpf_spin_lock *lock)
312 {
313 	atomic_t *l = (void *)lock;
314 
315 	BUILD_BUG_ON(sizeof(*l) != sizeof(*lock));
316 	do {
317 		atomic_cond_read_relaxed(l, !VAL);
318 	} while (atomic_xchg(l, 1));
319 }
320 
321 static inline void __bpf_spin_unlock(struct bpf_spin_lock *lock)
322 {
323 	atomic_t *l = (void *)lock;
324 
325 	atomic_set_release(l, 0);
326 }
327 
328 #endif
329 
330 static DEFINE_PER_CPU(unsigned long, irqsave_flags);
331 
332 static inline void __bpf_spin_lock_irqsave(struct bpf_spin_lock *lock)
333 {
334 	unsigned long flags;
335 
336 	local_irq_save(flags);
337 	__bpf_spin_lock(lock);
338 	__this_cpu_write(irqsave_flags, flags);
339 }
340 
341 NOTRACE_BPF_CALL_1(bpf_spin_lock, struct bpf_spin_lock *, lock)
342 {
343 	__bpf_spin_lock_irqsave(lock);
344 	return 0;
345 }
346 
347 const struct bpf_func_proto bpf_spin_lock_proto = {
348 	.func		= bpf_spin_lock,
349 	.gpl_only	= false,
350 	.ret_type	= RET_VOID,
351 	.arg1_type	= ARG_PTR_TO_SPIN_LOCK,
352 	.arg1_btf_id    = BPF_PTR_POISON,
353 };
354 
355 static inline void __bpf_spin_unlock_irqrestore(struct bpf_spin_lock *lock)
356 {
357 	unsigned long flags;
358 
359 	flags = __this_cpu_read(irqsave_flags);
360 	__bpf_spin_unlock(lock);
361 	local_irq_restore(flags);
362 }
363 
364 NOTRACE_BPF_CALL_1(bpf_spin_unlock, struct bpf_spin_lock *, lock)
365 {
366 	__bpf_spin_unlock_irqrestore(lock);
367 	return 0;
368 }
369 
370 const struct bpf_func_proto bpf_spin_unlock_proto = {
371 	.func		= bpf_spin_unlock,
372 	.gpl_only	= false,
373 	.ret_type	= RET_VOID,
374 	.arg1_type	= ARG_PTR_TO_SPIN_LOCK,
375 	.arg1_btf_id    = BPF_PTR_POISON,
376 };
377 
378 void copy_map_value_locked(struct bpf_map *map, void *dst, void *src,
379 			   bool lock_src)
380 {
381 	struct bpf_spin_lock *lock;
382 
383 	if (lock_src)
384 		lock = src + map->record->spin_lock_off;
385 	else
386 		lock = dst + map->record->spin_lock_off;
387 	preempt_disable();
388 	__bpf_spin_lock_irqsave(lock);
389 	copy_map_value(map, dst, src);
390 	__bpf_spin_unlock_irqrestore(lock);
391 	preempt_enable();
392 }
393 
394 BPF_CALL_0(bpf_jiffies64)
395 {
396 	return get_jiffies_64();
397 }
398 
399 const struct bpf_func_proto bpf_jiffies64_proto = {
400 	.func		= bpf_jiffies64,
401 	.gpl_only	= false,
402 	.ret_type	= RET_INTEGER,
403 };
404 
405 #ifdef CONFIG_CGROUPS
406 BPF_CALL_0(bpf_get_current_cgroup_id)
407 {
408 	struct cgroup *cgrp;
409 	u64 cgrp_id;
410 
411 	rcu_read_lock();
412 	cgrp = task_dfl_cgroup(current);
413 	cgrp_id = cgroup_id(cgrp);
414 	rcu_read_unlock();
415 
416 	return cgrp_id;
417 }
418 
419 const struct bpf_func_proto bpf_get_current_cgroup_id_proto = {
420 	.func		= bpf_get_current_cgroup_id,
421 	.gpl_only	= false,
422 	.ret_type	= RET_INTEGER,
423 };
424 
425 BPF_CALL_1(bpf_get_current_ancestor_cgroup_id, int, ancestor_level)
426 {
427 	struct cgroup *cgrp;
428 	struct cgroup *ancestor;
429 	u64 cgrp_id;
430 
431 	rcu_read_lock();
432 	cgrp = task_dfl_cgroup(current);
433 	ancestor = cgroup_ancestor(cgrp, ancestor_level);
434 	cgrp_id = ancestor ? cgroup_id(ancestor) : 0;
435 	rcu_read_unlock();
436 
437 	return cgrp_id;
438 }
439 
440 const struct bpf_func_proto bpf_get_current_ancestor_cgroup_id_proto = {
441 	.func		= bpf_get_current_ancestor_cgroup_id,
442 	.gpl_only	= false,
443 	.ret_type	= RET_INTEGER,
444 	.arg1_type	= ARG_ANYTHING,
445 };
446 #endif /* CONFIG_CGROUPS */
447 
448 #define BPF_STRTOX_BASE_MASK 0x1F
449 
450 static int __bpf_strtoull(const char *buf, size_t buf_len, u64 flags,
451 			  unsigned long long *res, bool *is_negative)
452 {
453 	unsigned int base = flags & BPF_STRTOX_BASE_MASK;
454 	const char *cur_buf = buf;
455 	size_t cur_len = buf_len;
456 	unsigned int consumed;
457 	size_t val_len;
458 	char str[64];
459 
460 	if (!buf || !buf_len || !res || !is_negative)
461 		return -EINVAL;
462 
463 	if (base != 0 && base != 8 && base != 10 && base != 16)
464 		return -EINVAL;
465 
466 	if (flags & ~BPF_STRTOX_BASE_MASK)
467 		return -EINVAL;
468 
469 	while (cur_buf < buf + buf_len && isspace(*cur_buf))
470 		++cur_buf;
471 
472 	*is_negative = (cur_buf < buf + buf_len && *cur_buf == '-');
473 	if (*is_negative)
474 		++cur_buf;
475 
476 	consumed = cur_buf - buf;
477 	cur_len -= consumed;
478 	if (!cur_len)
479 		return -EINVAL;
480 
481 	cur_len = min(cur_len, sizeof(str) - 1);
482 	memcpy(str, cur_buf, cur_len);
483 	str[cur_len] = '\0';
484 	cur_buf = str;
485 
486 	cur_buf = _parse_integer_fixup_radix(cur_buf, &base);
487 	val_len = _parse_integer(cur_buf, base, res);
488 
489 	if (val_len & KSTRTOX_OVERFLOW)
490 		return -ERANGE;
491 
492 	if (val_len == 0)
493 		return -EINVAL;
494 
495 	cur_buf += val_len;
496 	consumed += cur_buf - str;
497 
498 	return consumed;
499 }
500 
501 static int __bpf_strtoll(const char *buf, size_t buf_len, u64 flags,
502 			 long long *res)
503 {
504 	unsigned long long _res;
505 	bool is_negative;
506 	int err;
507 
508 	err = __bpf_strtoull(buf, buf_len, flags, &_res, &is_negative);
509 	if (err < 0)
510 		return err;
511 	if (is_negative) {
512 		if ((long long)-_res > 0)
513 			return -ERANGE;
514 		*res = -_res;
515 	} else {
516 		if ((long long)_res < 0)
517 			return -ERANGE;
518 		*res = _res;
519 	}
520 	return err;
521 }
522 
523 BPF_CALL_4(bpf_strtol, const char *, buf, size_t, buf_len, u64, flags,
524 	   s64 *, res)
525 {
526 	long long _res;
527 	int err;
528 
529 	*res = 0;
530 	err = __bpf_strtoll(buf, buf_len, flags, &_res);
531 	if (err < 0)
532 		return err;
533 	*res = _res;
534 	return err;
535 }
536 
537 const struct bpf_func_proto bpf_strtol_proto = {
538 	.func		= bpf_strtol,
539 	.gpl_only	= false,
540 	.ret_type	= RET_INTEGER,
541 	.arg1_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
542 	.arg2_type	= ARG_MEM_SIZE,
543 	.arg3_type	= ARG_ANYTHING,
544 	.arg4_type	= ARG_PTR_TO_FIXED_SIZE_MEM | MEM_UNINIT | MEM_WRITE | MEM_ALIGNED,
545 	.arg4_size	= sizeof(s64),
546 };
547 
548 BPF_CALL_4(bpf_strtoul, const char *, buf, size_t, buf_len, u64, flags,
549 	   u64 *, res)
550 {
551 	unsigned long long _res;
552 	bool is_negative;
553 	int err;
554 
555 	*res = 0;
556 	err = __bpf_strtoull(buf, buf_len, flags, &_res, &is_negative);
557 	if (err < 0)
558 		return err;
559 	if (is_negative)
560 		return -EINVAL;
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_MEM_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 
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_MEM_SIZE,
587 	.arg3_type	= ARG_PTR_TO_CONST_STR,
588 };
589 
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_MEM_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 
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_MEM_SIZE_OR_ZERO,
657 };
658 
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_MEM_SIZE_OR_ZERO,
679 	.arg3_type	= ARG_ANYTHING,
680 };
681 
682 static int __bpf_copy_from_user_mm(void *dst, u32 size,
683 				   const void __user *user_ptr,
684 				   struct mm_struct *mm)
685 {
686 	int ret;
687 
688 	ret = access_remote_vm(mm, (unsigned long)user_ptr, dst, size, 0);
689 	if (ret == size)
690 		return 0;
691 
692 	memset(dst, 0, size);
693 	/* Return -EFAULT for partial read */
694 	return ret < 0 ? ret : -EFAULT;
695 }
696 
697 static int __bpf_copy_from_user_mm_str(void *dst, u32 size,
698 				       const void __user *user_ptr,
699 				       struct mm_struct *mm, u64 flags)
700 {
701 	int ret;
702 
703 	ret = copy_remote_mm_str(mm, (unsigned long)user_ptr, dst, size, 0);
704 	if (ret < 0) {
705 		if (flags & BPF_F_PAD_ZEROS)
706 			memset(dst, 0, size);
707 		return ret;
708 	}
709 
710 	if (flags & BPF_F_PAD_ZEROS)
711 		memset(dst + ret, 0, size - ret);
712 
713 	return ret + 1;
714 }
715 
716 BPF_CALL_5(bpf_copy_from_user_task, void *, dst, u32, size,
717 	   const void __user *, user_ptr, struct task_struct *, tsk, u64, flags)
718 {
719 	struct mm_struct *mm;
720 	int ret;
721 
722 	/* flags is not used yet */
723 	if (unlikely(flags))
724 		return -EINVAL;
725 
726 	if (unlikely(!size))
727 		return 0;
728 
729 	mm = get_task_mm(tsk);
730 	if (!mm) {
731 		memset(dst, 0, size);
732 		return -EFAULT;
733 	}
734 
735 	ret = __bpf_copy_from_user_mm(dst, size, user_ptr, mm);
736 	mmput(mm);
737 
738 	return ret;
739 }
740 
741 const struct bpf_func_proto bpf_copy_from_user_task_proto = {
742 	.func		= bpf_copy_from_user_task,
743 	.gpl_only	= true,
744 	.might_sleep	= true,
745 	.ret_type	= RET_INTEGER,
746 	.arg1_type	= ARG_PTR_TO_UNINIT_MEM,
747 	.arg2_type	= ARG_MEM_SIZE_OR_ZERO,
748 	.arg3_type	= ARG_ANYTHING,
749 	.arg4_type	= ARG_PTR_TO_BTF_ID,
750 	.arg4_btf_id	= &btf_tracing_ids[BTF_TRACING_TYPE_TASK],
751 	.arg5_type	= ARG_ANYTHING
752 };
753 
754 BPF_CALL_2(bpf_per_cpu_ptr, const void *, ptr, u32, cpu)
755 {
756 	if (cpu >= nr_cpu_ids)
757 		return (unsigned long)NULL;
758 
759 	return (unsigned long)per_cpu_ptr((const void __percpu *)(const uintptr_t)ptr, cpu);
760 }
761 
762 const struct bpf_func_proto bpf_per_cpu_ptr_proto = {
763 	.func		= bpf_per_cpu_ptr,
764 	.gpl_only	= false,
765 	.ret_type	= RET_PTR_TO_MEM_OR_BTF_ID | PTR_MAYBE_NULL | MEM_RDONLY,
766 	.arg1_type	= ARG_PTR_TO_PERCPU_BTF_ID,
767 	.arg2_type	= ARG_ANYTHING,
768 };
769 
770 BPF_CALL_1(bpf_this_cpu_ptr, const void *, percpu_ptr)
771 {
772 	return (unsigned long)this_cpu_ptr((const void __percpu *)(const uintptr_t)percpu_ptr);
773 }
774 
775 const struct bpf_func_proto bpf_this_cpu_ptr_proto = {
776 	.func		= bpf_this_cpu_ptr,
777 	.gpl_only	= false,
778 	.ret_type	= RET_PTR_TO_MEM_OR_BTF_ID | MEM_RDONLY,
779 	.arg1_type	= ARG_PTR_TO_PERCPU_BTF_ID,
780 };
781 
782 static int bpf_trace_copy_string(char *buf, void *unsafe_ptr, char fmt_ptype,
783 		size_t bufsz)
784 {
785 	void __user *user_ptr = (__force void __user *)unsafe_ptr;
786 
787 	buf[0] = 0;
788 
789 	switch (fmt_ptype) {
790 	case 's':
791 #ifdef CONFIG_ARCH_HAS_NON_OVERLAPPING_ADDRESS_SPACE
792 		if ((unsigned long)unsafe_ptr < TASK_SIZE)
793 			return strncpy_from_user_nofault(buf, user_ptr, bufsz);
794 		fallthrough;
795 #endif
796 	case 'k':
797 		return strncpy_from_kernel_nofault(buf, unsafe_ptr, bufsz);
798 	case 'u':
799 		return strncpy_from_user_nofault(buf, user_ptr, bufsz);
800 	}
801 
802 	return -EINVAL;
803 }
804 
805 /* Support executing three nested bprintf helper calls on a given CPU */
806 #define MAX_BPRINTF_NEST_LEVEL	3
807 
808 static DEFINE_PER_CPU(struct bpf_bprintf_buffers[MAX_BPRINTF_NEST_LEVEL], bpf_bprintf_bufs);
809 static DEFINE_PER_CPU(int, bpf_bprintf_nest_level);
810 
811 int bpf_try_get_buffers(struct bpf_bprintf_buffers **bufs)
812 {
813 	int nest_level;
814 
815 	preempt_disable();
816 	nest_level = this_cpu_inc_return(bpf_bprintf_nest_level);
817 	if (WARN_ON_ONCE(nest_level > MAX_BPRINTF_NEST_LEVEL)) {
818 		this_cpu_dec(bpf_bprintf_nest_level);
819 		preempt_enable();
820 		return -EBUSY;
821 	}
822 	*bufs = this_cpu_ptr(&bpf_bprintf_bufs[nest_level - 1]);
823 
824 	return 0;
825 }
826 
827 void bpf_put_buffers(void)
828 {
829 	if (WARN_ON_ONCE(this_cpu_read(bpf_bprintf_nest_level) == 0))
830 		return;
831 	this_cpu_dec(bpf_bprintf_nest_level);
832 	preempt_enable();
833 }
834 
835 void bpf_bprintf_cleanup(struct bpf_bprintf_data *data)
836 {
837 	if (!data->bin_args && !data->buf)
838 		return;
839 	bpf_put_buffers();
840 }
841 
842 /*
843  * bpf_bprintf_prepare - Generic pass on format strings for bprintf-like helpers
844  *
845  * Returns a negative value if fmt is an invalid format string or 0 otherwise.
846  *
847  * This can be used in two ways:
848  * - Format string verification only: when data->get_bin_args is false
849  * - Arguments preparation: in addition to the above verification, it writes in
850  *   data->bin_args a binary representation of arguments usable by bstr_printf
851  *   where pointers from BPF have been sanitized.
852  *
853  * In argument preparation mode, if 0 is returned, safe temporary buffers are
854  * allocated and bpf_bprintf_cleanup should be called to free them after use.
855  */
856 int bpf_bprintf_prepare(const char *fmt, u32 fmt_size, const u64 *raw_args,
857 			u32 num_args, struct bpf_bprintf_data *data)
858 {
859 	bool get_buffers = (data->get_bin_args && num_args) || data->get_buf;
860 	char *unsafe_ptr = NULL, *tmp_buf = NULL, *tmp_buf_end, *fmt_end;
861 	struct bpf_bprintf_buffers *buffers = NULL;
862 	size_t sizeof_cur_arg, sizeof_cur_ip;
863 	int err, i, num_spec = 0;
864 	u64 cur_arg;
865 	char fmt_ptype, cur_ip[16], ip_spec[] = "%pXX";
866 
867 	fmt_end = strnchr(fmt, fmt_size, 0);
868 	if (!fmt_end)
869 		return -EINVAL;
870 	fmt_size = fmt_end - fmt;
871 
872 	if (get_buffers && bpf_try_get_buffers(&buffers))
873 		return -EBUSY;
874 
875 	if (data->get_bin_args) {
876 		if (num_args)
877 			tmp_buf = buffers->bin_args;
878 		tmp_buf_end = tmp_buf + MAX_BPRINTF_BIN_ARGS;
879 		data->bin_args = (u32 *)tmp_buf;
880 	}
881 
882 	if (data->get_buf)
883 		data->buf = buffers->buf;
884 
885 	for (i = 0; i < fmt_size; i++) {
886 		unsigned char c = fmt[i];
887 
888 		/*
889 		 * Permit bytes >= 0x80 in plain text so UTF-8 literals can pass
890 		 * through unchanged, while still rejecting ASCII control bytes.
891 		 */
892 		if (isascii(c) && !isprint(c) && !isspace(c)) {
893 			err = -EINVAL;
894 			goto out;
895 		}
896 
897 		if (fmt[i] != '%')
898 			continue;
899 
900 		if (fmt[i + 1] == '%') {
901 			i++;
902 			continue;
903 		}
904 
905 		if (num_spec >= num_args) {
906 			err = -EINVAL;
907 			goto out;
908 		}
909 
910 		/* The string is zero-terminated so if fmt[i] != 0, we can
911 		 * always access fmt[i + 1], in the worst case it will be a 0
912 		 */
913 		i++;
914 		c = fmt[i];
915 		/*
916 		 * The format parser below only understands ASCII conversion
917 		 * specifiers and modifiers, so reject non-ASCII after '%'.
918 		 */
919 		if (!isascii(c)) {
920 			err = -EINVAL;
921 			goto out;
922 		}
923 
924 		/* skip optional "[0 +-][num]" width formatting field */
925 		while (fmt[i] == '0' || fmt[i] == '+'  || fmt[i] == '-' ||
926 		       fmt[i] == ' ')
927 			i++;
928 		if (fmt[i] >= '1' && fmt[i] <= '9') {
929 			i++;
930 			while (fmt[i] >= '0' && fmt[i] <= '9')
931 				i++;
932 		}
933 
934 		if (fmt[i] == 'p') {
935 			sizeof_cur_arg = sizeof(long);
936 
937 			if (fmt[i + 1] == 0 || isspace(fmt[i + 1]) ||
938 			    ispunct(fmt[i + 1])) {
939 				if (tmp_buf)
940 					cur_arg = raw_args[num_spec];
941 				goto nocopy_fmt;
942 			}
943 
944 			if ((fmt[i + 1] == 'k' || fmt[i + 1] == 'u') &&
945 			    fmt[i + 2] == 's') {
946 				fmt_ptype = fmt[i + 1];
947 				i += 2;
948 				goto fmt_str;
949 			}
950 
951 			if (fmt[i + 1] == 'K' ||
952 			    fmt[i + 1] == 'x' || fmt[i + 1] == 's' ||
953 			    fmt[i + 1] == 'S') {
954 				if (tmp_buf)
955 					cur_arg = raw_args[num_spec];
956 				i++;
957 				goto nocopy_fmt;
958 			}
959 
960 			if (fmt[i + 1] == 'B') {
961 				if (tmp_buf)  {
962 					err = snprintf(tmp_buf,
963 						       (tmp_buf_end - tmp_buf),
964 						       "%pB",
965 						       (void *)(long)raw_args[num_spec]);
966 					tmp_buf += (err + 1);
967 				}
968 
969 				i++;
970 				num_spec++;
971 				continue;
972 			}
973 
974 			/* only support "%pI4", "%pi4", "%pI6" and "%pi6". */
975 			if ((fmt[i + 1] != 'i' && fmt[i + 1] != 'I') ||
976 			    (fmt[i + 2] != '4' && fmt[i + 2] != '6')) {
977 				err = -EINVAL;
978 				goto out;
979 			}
980 
981 			i += 2;
982 			if (!tmp_buf)
983 				goto nocopy_fmt;
984 
985 			sizeof_cur_ip = (fmt[i] == '4') ? 4 : 16;
986 			if (tmp_buf_end - tmp_buf < sizeof_cur_ip) {
987 				err = -ENOSPC;
988 				goto out;
989 			}
990 
991 			unsafe_ptr = (char *)(long)raw_args[num_spec];
992 			err = copy_from_kernel_nofault(cur_ip, unsafe_ptr,
993 						       sizeof_cur_ip);
994 			if (err < 0)
995 				memset(cur_ip, 0, sizeof_cur_ip);
996 
997 			/* hack: bstr_printf expects IP addresses to be
998 			 * pre-formatted as strings, ironically, the easiest way
999 			 * to do that is to call snprintf.
1000 			 */
1001 			ip_spec[2] = fmt[i - 1];
1002 			ip_spec[3] = fmt[i];
1003 			err = snprintf(tmp_buf, tmp_buf_end - tmp_buf,
1004 				       ip_spec, &cur_ip);
1005 
1006 			tmp_buf += err + 1;
1007 			num_spec++;
1008 
1009 			continue;
1010 		} else if (fmt[i] == 's') {
1011 			fmt_ptype = fmt[i];
1012 fmt_str:
1013 			if (fmt[i + 1] != 0 &&
1014 			    !isspace(fmt[i + 1]) &&
1015 			    !ispunct(fmt[i + 1])) {
1016 				err = -EINVAL;
1017 				goto out;
1018 			}
1019 
1020 			if (!tmp_buf)
1021 				goto nocopy_fmt;
1022 
1023 			if (tmp_buf_end == tmp_buf) {
1024 				err = -ENOSPC;
1025 				goto out;
1026 			}
1027 
1028 			unsafe_ptr = (char *)(long)raw_args[num_spec];
1029 			err = bpf_trace_copy_string(tmp_buf, unsafe_ptr,
1030 						    fmt_ptype,
1031 						    tmp_buf_end - tmp_buf);
1032 			if (err < 0) {
1033 				tmp_buf[0] = '\0';
1034 				err = 1;
1035 			}
1036 
1037 			tmp_buf += err;
1038 			num_spec++;
1039 
1040 			continue;
1041 		} else if (fmt[i] == 'c') {
1042 			if (!tmp_buf)
1043 				goto nocopy_fmt;
1044 
1045 			if (tmp_buf_end == tmp_buf) {
1046 				err = -ENOSPC;
1047 				goto out;
1048 			}
1049 
1050 			*tmp_buf = raw_args[num_spec];
1051 			tmp_buf++;
1052 			num_spec++;
1053 
1054 			continue;
1055 		}
1056 
1057 		sizeof_cur_arg = sizeof(int);
1058 
1059 		if (fmt[i] == 'l') {
1060 			sizeof_cur_arg = sizeof(long);
1061 			i++;
1062 		}
1063 		if (fmt[i] == 'l') {
1064 			sizeof_cur_arg = sizeof(long long);
1065 			i++;
1066 		}
1067 
1068 		if (fmt[i] != 'i' && fmt[i] != 'd' && fmt[i] != 'u' &&
1069 		    fmt[i] != 'x' && fmt[i] != 'X') {
1070 			err = -EINVAL;
1071 			goto out;
1072 		}
1073 
1074 		if (tmp_buf)
1075 			cur_arg = raw_args[num_spec];
1076 nocopy_fmt:
1077 		if (tmp_buf) {
1078 			tmp_buf = PTR_ALIGN(tmp_buf, sizeof(u32));
1079 			if (tmp_buf_end - tmp_buf < sizeof_cur_arg) {
1080 				err = -ENOSPC;
1081 				goto out;
1082 			}
1083 
1084 			if (sizeof_cur_arg == 8) {
1085 				*(u32 *)tmp_buf = *(u32 *)&cur_arg;
1086 				*(u32 *)(tmp_buf + 4) = *((u32 *)&cur_arg + 1);
1087 			} else {
1088 				*(u32 *)tmp_buf = (u32)(long)cur_arg;
1089 			}
1090 			tmp_buf += sizeof_cur_arg;
1091 		}
1092 		num_spec++;
1093 	}
1094 
1095 	err = 0;
1096 out:
1097 	if (err)
1098 		bpf_bprintf_cleanup(data);
1099 	return err;
1100 }
1101 
1102 BPF_CALL_5(bpf_snprintf, char *, str, u32, str_size, char *, fmt,
1103 	   const void *, args, u32, data_len)
1104 {
1105 	struct bpf_bprintf_data data = {
1106 		.get_bin_args	= true,
1107 	};
1108 	int err, num_args;
1109 
1110 	if (data_len % 8 || data_len > MAX_BPRINTF_VARARGS * 8 ||
1111 	    (data_len && !args))
1112 		return -EINVAL;
1113 	num_args = data_len / 8;
1114 
1115 	/* ARG_PTR_TO_CONST_STR guarantees that fmt is zero-terminated so we
1116 	 * can safely give an unbounded size.
1117 	 */
1118 	err = bpf_bprintf_prepare(fmt, UINT_MAX, args, num_args, &data);
1119 	if (err < 0)
1120 		return err;
1121 
1122 	err = bstr_printf(str, str_size, fmt, data.bin_args);
1123 
1124 	bpf_bprintf_cleanup(&data);
1125 
1126 	return err + 1;
1127 }
1128 
1129 const struct bpf_func_proto bpf_snprintf_proto = {
1130 	.func		= bpf_snprintf,
1131 	.gpl_only	= true,
1132 	.ret_type	= RET_INTEGER,
1133 	.arg1_type	= ARG_PTR_TO_MEM_OR_NULL | MEM_UNINIT | MEM_WRITE,
1134 	.arg2_type	= ARG_MEM_SIZE_OR_ZERO,
1135 	.arg3_type	= ARG_PTR_TO_CONST_STR,
1136 	.arg4_type	= ARG_PTR_TO_MEM | PTR_MAYBE_NULL | MEM_RDONLY,
1137 	.arg5_type	= ARG_MEM_SIZE_OR_ZERO,
1138 };
1139 
1140 static void *map_key_from_value(struct bpf_map *map, void *value, u32 *arr_idx)
1141 {
1142 	if (map->map_type == BPF_MAP_TYPE_ARRAY) {
1143 		struct bpf_array *array = container_of(map, struct bpf_array, map);
1144 
1145 		*arr_idx = ((char *)value - array->value) / array->elem_size;
1146 		return arr_idx;
1147 	}
1148 	return (void *)value - round_up(map->key_size, 8);
1149 }
1150 
1151 enum bpf_async_type {
1152 	BPF_ASYNC_TYPE_TIMER = 0,
1153 	BPF_ASYNC_TYPE_WQ,
1154 };
1155 
1156 enum bpf_async_op {
1157 	BPF_ASYNC_START,
1158 	BPF_ASYNC_CANCEL
1159 };
1160 
1161 struct bpf_async_cmd {
1162 	struct llist_node node;
1163 	u64 nsec;
1164 	u32 mode;
1165 	enum bpf_async_op op;
1166 };
1167 
1168 struct bpf_async_cb {
1169 	struct bpf_map *map;
1170 	struct bpf_prog *prog;
1171 	void __rcu *callback_fn;
1172 	void *value;
1173 	struct rcu_head rcu;
1174 	u64 flags;
1175 	struct irq_work worker;
1176 	refcount_t refcnt;
1177 	enum bpf_async_type type;
1178 	struct llist_head async_cmds;
1179 };
1180 
1181 /* BPF map elements can contain 'struct bpf_timer'.
1182  * Such map owns all of its BPF timers.
1183  * 'struct bpf_timer' is allocated as part of map element allocation
1184  * and it's zero initialized.
1185  * That space is used to keep 'struct bpf_async_kern'.
1186  * bpf_timer_init() allocates 'struct bpf_hrtimer', inits hrtimer, and
1187  * remembers 'struct bpf_map *' pointer it's part of.
1188  * bpf_timer_set_callback() increments prog refcnt and assign bpf callback_fn.
1189  * bpf_timer_start() arms the timer.
1190  * If user space reference to a map goes to zero at this point
1191  * ops->map_release_uref callback is responsible for cancelling the timers,
1192  * freeing their memory, and decrementing prog's refcnts.
1193  * bpf_timer_cancel() cancels the timer and decrements prog's refcnt.
1194  * Inner maps can contain bpf timers as well. ops->map_release_uref is
1195  * freeing the timers when inner map is replaced or deleted by user space.
1196  */
1197 struct bpf_hrtimer {
1198 	struct bpf_async_cb cb;
1199 	struct hrtimer timer;
1200 	atomic_t cancelling;
1201 };
1202 
1203 struct bpf_work {
1204 	struct bpf_async_cb cb;
1205 	struct work_struct work;
1206 };
1207 
1208 /* the actual struct hidden inside uapi struct bpf_timer and bpf_wq */
1209 struct bpf_async_kern {
1210 	union {
1211 		struct bpf_async_cb *cb;
1212 		struct bpf_hrtimer *timer;
1213 		struct bpf_work *work;
1214 	};
1215 } __attribute__((aligned(8)));
1216 
1217 static DEFINE_PER_CPU(struct bpf_hrtimer *, hrtimer_running);
1218 
1219 static void bpf_async_refcount_put(struct bpf_async_cb *cb);
1220 
1221 static enum hrtimer_restart bpf_timer_cb(struct hrtimer *hrtimer)
1222 {
1223 	struct bpf_hrtimer *t = container_of(hrtimer, struct bpf_hrtimer, timer);
1224 	struct bpf_map *map = READ_ONCE(t->cb.map);
1225 	struct bpf_prog *prog = READ_ONCE(t->cb.prog);
1226 	struct bpf_timed_may_goto saved;
1227 	void *value = t->cb.value;
1228 	bpf_callback_t callback_fn;
1229 	void *key;
1230 	u32 idx;
1231 
1232 	BTF_TYPE_EMIT(struct bpf_timer);
1233 	callback_fn = rcu_dereference_check(t->cb.callback_fn, rcu_read_lock_bh_held());
1234 	if (!callback_fn || !map || !prog)
1235 		goto out;
1236 
1237 	/* bpf_timer_cb() runs in hrtimer_run_softirq. It doesn't migrate and
1238 	 * cannot be preempted by another bpf_timer_cb() on the same cpu.
1239 	 * Remember the timer this callback is servicing to prevent
1240 	 * deadlock if callback_fn() calls bpf_timer_cancel() or
1241 	 * bpf_map_delete_elem() on the same timer.
1242 	 */
1243 	this_cpu_write(hrtimer_running, t);
1244 
1245 	key = map_key_from_value(map, value, &idx);
1246 
1247 	bpf_timed_may_goto_save(prog, &saved);
1248 	callback_fn((u64)(long)map, (u64)(long)key, (u64)(long)value, 0, 0);
1249 	/* The verifier checked that return value is zero. */
1250 	bpf_timed_may_goto_restore(prog, &saved);
1251 
1252 	this_cpu_write(hrtimer_running, NULL);
1253 out:
1254 	return HRTIMER_NORESTART;
1255 }
1256 
1257 static void bpf_wq_work(struct work_struct *work)
1258 {
1259 	struct bpf_work *w = container_of(work, struct bpf_work, work);
1260 	struct bpf_async_cb *cb = &w->cb;
1261 	struct bpf_timed_may_goto saved;
1262 	struct bpf_prog *prog;
1263 	struct bpf_map *map;
1264 	bpf_callback_t callback_fn;
1265 	void *value = cb->value;
1266 	void *key;
1267 	u32 idx;
1268 
1269 	BTF_TYPE_EMIT(struct bpf_wq);
1270 
1271 	/* keeps the program that callback_fn belongs to */
1272 	rcu_read_lock_trace();
1273 
1274 	map = READ_ONCE(cb->map);
1275 	callback_fn = READ_ONCE(cb->callback_fn);
1276 	prog = READ_ONCE(cb->prog);
1277 	if (!callback_fn || !map || !prog)
1278 		goto out;
1279 
1280 	key = map_key_from_value(map, value, &idx);
1281 
1282 	migrate_disable();
1283 
1284 	bpf_timed_may_goto_save(prog, &saved);
1285 	callback_fn((u64)(long)map, (u64)(long)key, (u64)(long)value, 0, 0);
1286 	bpf_timed_may_goto_restore(prog, &saved);
1287 
1288 	migrate_enable();
1289 out:
1290 	rcu_read_unlock_trace();
1291 }
1292 
1293 static void bpf_async_cb_rcu_free(struct rcu_head *rcu)
1294 {
1295 	struct bpf_async_cb *cb = container_of(rcu, struct bpf_async_cb, rcu);
1296 
1297 	/*
1298 	 * Drop the last reference to prog only after RCU GP, as set_callback()
1299 	 * may race with cancel_and_free()
1300 	 */
1301 	if (cb->prog)
1302 		bpf_prog_put(cb->prog);
1303 
1304 	kfree_nolock(cb);
1305 }
1306 
1307 /* Callback from call_rcu_tasks_trace, chains to call_rcu for final free */
1308 static void bpf_async_cb_rcu_tasks_trace_free(struct rcu_head *rcu)
1309 {
1310 	struct bpf_async_cb *cb = container_of(rcu, struct bpf_async_cb, rcu);
1311 	struct bpf_hrtimer *t = container_of(cb, struct bpf_hrtimer, cb);
1312 	struct bpf_work *w = container_of(cb, struct bpf_work, cb);
1313 	bool retry = false;
1314 
1315 	/*
1316 	 * bpf_async_cancel_and_free() tried to cancel timer/wq, but it
1317 	 * could have raced with timer/wq_start. Now refcnt is zero and
1318 	 * srcu/rcu GP completed. Cancel timer/wq again.
1319 	 */
1320 	switch (cb->type) {
1321 	case BPF_ASYNC_TYPE_TIMER:
1322 		if (hrtimer_try_to_cancel(&t->timer) < 0)
1323 			retry = true;
1324 		break;
1325 	case BPF_ASYNC_TYPE_WQ:
1326 		if (!cancel_work(&w->work) && work_busy(&w->work))
1327 			retry = true;
1328 		break;
1329 	}
1330 	if (retry) {
1331 		/*
1332 		 * hrtimer or wq callback may still be running. It must be
1333 		 * in rcu_tasks_trace or rcu CS, so wait for GP again.
1334 		 * It won't retry forever, since refcnt zero prevents all
1335 		 * operations on timer/wq.
1336 		 */
1337 		call_rcu_tasks_trace(&cb->rcu, bpf_async_cb_rcu_tasks_trace_free);
1338 		return;
1339 	}
1340 
1341 	/* RCU Tasks Trace grace period implies RCU grace period. */
1342 	bpf_async_cb_rcu_free(rcu);
1343 }
1344 
1345 static void worker_for_call_rcu(struct irq_work *work)
1346 {
1347 	struct bpf_async_cb *cb = container_of(work, struct bpf_async_cb, worker);
1348 
1349 	call_rcu_tasks_trace(&cb->rcu, bpf_async_cb_rcu_tasks_trace_free);
1350 }
1351 
1352 static void bpf_async_refcount_put(struct bpf_async_cb *cb)
1353 {
1354 	if (!refcount_dec_and_test(&cb->refcnt))
1355 		return;
1356 
1357 	if (irqs_disabled()) {
1358 		cb->worker = IRQ_WORK_INIT(worker_for_call_rcu);
1359 		irq_work_queue(&cb->worker);
1360 	} else {
1361 		call_rcu_tasks_trace(&cb->rcu, bpf_async_cb_rcu_tasks_trace_free);
1362 	}
1363 }
1364 
1365 static void bpf_async_cancel_and_free(struct bpf_async_kern *async);
1366 static void bpf_async_irq_worker(struct irq_work *work);
1367 
1368 static int __bpf_async_init(struct bpf_async_kern *async, struct bpf_map *map, u64 flags,
1369 			    enum bpf_async_type type)
1370 {
1371 	struct bpf_async_cb *cb, *old_cb;
1372 	struct bpf_hrtimer *t;
1373 	struct bpf_work *w;
1374 	clockid_t clockid;
1375 	size_t size;
1376 
1377 	switch (type) {
1378 	case BPF_ASYNC_TYPE_TIMER:
1379 		size = sizeof(struct bpf_hrtimer);
1380 		break;
1381 	case BPF_ASYNC_TYPE_WQ:
1382 		size = sizeof(struct bpf_work);
1383 		break;
1384 	default:
1385 		return -EINVAL;
1386 	}
1387 
1388 	old_cb = READ_ONCE(async->cb);
1389 	if (old_cb)
1390 		return -EBUSY;
1391 
1392 	cb = bpf_map_kmalloc_nolock(map, size, 0, map->numa_node);
1393 	if (!cb)
1394 		return -ENOMEM;
1395 
1396 	switch (type) {
1397 	case BPF_ASYNC_TYPE_TIMER:
1398 		clockid = flags & (MAX_CLOCKS - 1);
1399 		t = (struct bpf_hrtimer *)cb;
1400 
1401 		atomic_set(&t->cancelling, 0);
1402 		hrtimer_setup(&t->timer, bpf_timer_cb, clockid, HRTIMER_MODE_REL_SOFT);
1403 		cb->value = (void *)async - map->record->timer_off;
1404 		break;
1405 	case BPF_ASYNC_TYPE_WQ:
1406 		w = (struct bpf_work *)cb;
1407 
1408 		INIT_WORK(&w->work, bpf_wq_work);
1409 		cb->value = (void *)async - map->record->wq_off;
1410 		break;
1411 	}
1412 	cb->map = map;
1413 	cb->prog = NULL;
1414 	cb->flags = flags;
1415 	cb->worker = IRQ_WORK_INIT(bpf_async_irq_worker);
1416 	init_llist_head(&cb->async_cmds);
1417 	refcount_set(&cb->refcnt, 1); /* map's reference */
1418 	cb->type = type;
1419 	rcu_assign_pointer(cb->callback_fn, NULL);
1420 
1421 	old_cb = cmpxchg(&async->cb, NULL, cb);
1422 	if (old_cb) {
1423 		/* Lost the race to initialize this bpf_async_kern, drop the allocated object */
1424 		kfree_nolock(cb);
1425 		return -EBUSY;
1426 	}
1427 	/* Guarantee the order between async->cb and map->usercnt. So
1428 	 * when there are concurrent uref release and bpf timer init, either
1429 	 * bpf_timer_cancel_and_free() called by uref release reads a no-NULL
1430 	 * timer or atomic64_read() below returns a zero usercnt.
1431 	 */
1432 	smp_mb();
1433 	if (!atomic64_read(&map->usercnt)) {
1434 		/* maps with timers must be either held by user space
1435 		 * or pinned in bpffs.
1436 		 */
1437 		bpf_async_cancel_and_free(async);
1438 		return -EPERM;
1439 	}
1440 
1441 	return 0;
1442 }
1443 
1444 BPF_CALL_3(bpf_timer_init, struct bpf_async_kern *, timer, struct bpf_map *, map,
1445 	   u64, flags)
1446 {
1447 	clock_t clockid = flags & (MAX_CLOCKS - 1);
1448 
1449 	BUILD_BUG_ON(MAX_CLOCKS != 16);
1450 	BUILD_BUG_ON(sizeof(struct bpf_async_kern) > sizeof(struct bpf_timer));
1451 	BUILD_BUG_ON(__alignof__(struct bpf_async_kern) != __alignof__(struct bpf_timer));
1452 
1453 	if (flags >= MAX_CLOCKS ||
1454 	    /* similar to timerfd except _ALARM variants are not supported */
1455 	    (clockid != CLOCK_MONOTONIC &&
1456 	     clockid != CLOCK_REALTIME &&
1457 	     clockid != CLOCK_BOOTTIME))
1458 		return -EINVAL;
1459 
1460 	return __bpf_async_init(timer, map, flags, BPF_ASYNC_TYPE_TIMER);
1461 }
1462 
1463 static const struct bpf_func_proto bpf_timer_init_proto = {
1464 	.func		= bpf_timer_init,
1465 	.gpl_only	= true,
1466 	.ret_type	= RET_INTEGER,
1467 	.arg1_type	= ARG_PTR_TO_TIMER,
1468 	.arg2_type	= ARG_CONST_MAP_PTR,
1469 	.arg3_type	= ARG_ANYTHING,
1470 };
1471 
1472 static int bpf_async_update_prog_callback(struct bpf_async_cb *cb,
1473 					  struct bpf_prog *prog,
1474 					  void *callback_fn)
1475 {
1476 	struct bpf_prog *prev;
1477 
1478 	/* Acquire a guard reference on prog to prevent it from being freed during the loop */
1479 	if (prog) {
1480 		prog = bpf_prog_inc_not_zero(prog);
1481 		if (IS_ERR(prog))
1482 			return PTR_ERR(prog);
1483 	}
1484 
1485 	do {
1486 		if (prog)
1487 			prog = bpf_prog_inc_not_zero(prog);
1488 		prev = xchg(&cb->prog, prog);
1489 		rcu_assign_pointer(cb->callback_fn, callback_fn);
1490 
1491 		/*
1492 		 * Release previous prog, make sure that if other CPU is contending,
1493 		 * to set bpf_prog, references are not leaked as each iteration acquires and
1494 		 * releases one reference.
1495 		 */
1496 		if (prev)
1497 			bpf_prog_put(prev);
1498 
1499 	} while (READ_ONCE(cb->prog) != prog ||
1500 		 (void __force *)READ_ONCE(cb->callback_fn) != callback_fn);
1501 
1502 	if (prog)
1503 		bpf_prog_put(prog);
1504 
1505 	return 0;
1506 }
1507 
1508 static DEFINE_PER_CPU(struct bpf_async_cb *, async_cb_running);
1509 
1510 static int bpf_async_schedule_op(struct bpf_async_cb *cb, enum bpf_async_op op,
1511 				 u64 nsec, u32 timer_mode)
1512 {
1513 	/*
1514 	 * Do not schedule another operation on this cpu if it's in irq_work
1515 	 * callback that is processing async_cmds queue. Otherwise the following
1516 	 * loop is possible:
1517 	 * bpf_timer_start() -> bpf_async_schedule_op() -> irq_work_queue().
1518 	 * irqrestore -> bpf_async_irq_worker() -> tracepoint -> bpf_timer_start().
1519 	 */
1520 	if (this_cpu_read(async_cb_running) == cb) {
1521 		bpf_async_refcount_put(cb);
1522 		return -EDEADLK;
1523 	}
1524 
1525 	struct bpf_async_cmd *cmd = kmalloc_nolock(sizeof(*cmd), 0, NUMA_NO_NODE);
1526 
1527 	if (!cmd) {
1528 		bpf_async_refcount_put(cb);
1529 		return -ENOMEM;
1530 	}
1531 	init_llist_node(&cmd->node);
1532 	cmd->nsec = nsec;
1533 	cmd->mode = timer_mode;
1534 	cmd->op = op;
1535 	if (llist_add(&cmd->node, &cb->async_cmds))
1536 		irq_work_queue(&cb->worker);
1537 	return 0;
1538 }
1539 
1540 static int __bpf_async_set_callback(struct bpf_async_kern *async, void *callback_fn,
1541 				    struct bpf_prog *prog)
1542 {
1543 	struct bpf_async_cb *cb;
1544 
1545 	cb = READ_ONCE(async->cb);
1546 	if (!cb)
1547 		return -EINVAL;
1548 
1549 	return bpf_async_update_prog_callback(cb, prog, callback_fn);
1550 }
1551 
1552 BPF_CALL_3(bpf_timer_set_callback, struct bpf_async_kern *, timer, void *, callback_fn,
1553 	   struct bpf_prog_aux *, aux)
1554 {
1555 	return __bpf_async_set_callback(timer, callback_fn, aux->prog);
1556 }
1557 
1558 static const struct bpf_func_proto bpf_timer_set_callback_proto = {
1559 	.func		= bpf_timer_set_callback,
1560 	.gpl_only	= true,
1561 	.ret_type	= RET_INTEGER,
1562 	.arg1_type	= ARG_PTR_TO_TIMER,
1563 	.arg2_type	= ARG_PTR_TO_FUNC,
1564 	.arg3_type	= ARG_PTR_TO_PROG_AUX,
1565 };
1566 
1567 static bool defer_timer_wq_op(void)
1568 {
1569 	return in_hardirq() || irqs_disabled();
1570 }
1571 
1572 BPF_CALL_3(bpf_timer_start, struct bpf_async_kern *, async, u64, nsecs, u64, flags)
1573 {
1574 	struct bpf_hrtimer *t;
1575 	u32 mode;
1576 
1577 	if (flags & ~(BPF_F_TIMER_ABS | BPF_F_TIMER_CPU_PIN))
1578 		return -EINVAL;
1579 
1580 	t = READ_ONCE(async->timer);
1581 	if (!t || !READ_ONCE(t->cb.prog))
1582 		return -EINVAL;
1583 
1584 	if (flags & BPF_F_TIMER_ABS)
1585 		mode = HRTIMER_MODE_ABS_SOFT;
1586 	else
1587 		mode = HRTIMER_MODE_REL_SOFT;
1588 
1589 	if (flags & BPF_F_TIMER_CPU_PIN)
1590 		mode |= HRTIMER_MODE_PINNED;
1591 
1592 	/*
1593 	 * bpf_async_cancel_and_free() could have dropped refcnt to zero. In
1594 	 * such case BPF progs are not allowed to arm the timer to prevent UAF.
1595 	 */
1596 	if (!refcount_inc_not_zero(&t->cb.refcnt))
1597 		return -ENOENT;
1598 
1599 	if (!defer_timer_wq_op()) {
1600 		hrtimer_start(&t->timer, ns_to_ktime(nsecs), mode);
1601 		bpf_async_refcount_put(&t->cb);
1602 		return 0;
1603 	} else {
1604 		return bpf_async_schedule_op(&t->cb, BPF_ASYNC_START, nsecs, mode);
1605 	}
1606 }
1607 
1608 static const struct bpf_func_proto bpf_timer_start_proto = {
1609 	.func		= bpf_timer_start,
1610 	.gpl_only	= true,
1611 	.ret_type	= RET_INTEGER,
1612 	.arg1_type	= ARG_PTR_TO_TIMER,
1613 	.arg2_type	= ARG_ANYTHING,
1614 	.arg3_type	= ARG_ANYTHING,
1615 };
1616 
1617 BPF_CALL_1(bpf_timer_cancel, struct bpf_async_kern *, async)
1618 {
1619 	struct bpf_hrtimer *t, *cur_t;
1620 	bool inc = false;
1621 	int ret = 0;
1622 
1623 	if (defer_timer_wq_op())
1624 		return -EOPNOTSUPP;
1625 
1626 	t = READ_ONCE(async->timer);
1627 	if (!t)
1628 		return -EINVAL;
1629 
1630 	cur_t = this_cpu_read(hrtimer_running);
1631 	if (cur_t == t) {
1632 		/* If bpf callback_fn is trying to bpf_timer_cancel()
1633 		 * its own timer the hrtimer_cancel() will deadlock
1634 		 * since it waits for callback_fn to finish.
1635 		 */
1636 		return -EDEADLK;
1637 	}
1638 
1639 	/* Only account in-flight cancellations when invoked from a timer
1640 	 * callback, since we want to avoid waiting only if other _callbacks_
1641 	 * are waiting on us, to avoid introducing lockups. Non-callback paths
1642 	 * are ok, since nobody would synchronously wait for their completion.
1643 	 */
1644 	if (!cur_t)
1645 		goto drop;
1646 	atomic_inc(&t->cancelling);
1647 	/* Need full barrier after relaxed atomic_inc */
1648 	smp_mb__after_atomic();
1649 	inc = true;
1650 	if (atomic_read(&cur_t->cancelling)) {
1651 		/* We're cancelling timer t, while some other timer callback is
1652 		 * attempting to cancel us. In such a case, it might be possible
1653 		 * that timer t belongs to the other callback, or some other
1654 		 * callback waiting upon it (creating transitive dependencies
1655 		 * upon us), and we will enter a deadlock if we continue
1656 		 * cancelling and waiting for it synchronously, since it might
1657 		 * do the same. Bail!
1658 		 */
1659 		atomic_dec(&t->cancelling);
1660 		return -EDEADLK;
1661 	}
1662 drop:
1663 	bpf_async_update_prog_callback(&t->cb, NULL, NULL);
1664 	/* Cancel the timer and wait for associated callback to finish
1665 	 * if it was running.
1666 	 */
1667 	ret = hrtimer_cancel(&t->timer);
1668 	if (inc)
1669 		atomic_dec(&t->cancelling);
1670 	return ret;
1671 }
1672 
1673 static const struct bpf_func_proto bpf_timer_cancel_proto = {
1674 	.func		= bpf_timer_cancel,
1675 	.gpl_only	= true,
1676 	.ret_type	= RET_INTEGER,
1677 	.arg1_type	= ARG_PTR_TO_TIMER,
1678 };
1679 
1680 static void bpf_async_process_op(struct bpf_async_cb *cb, u32 op,
1681 				 u64 timer_nsec, u32 timer_mode)
1682 {
1683 	switch (cb->type) {
1684 	case BPF_ASYNC_TYPE_TIMER: {
1685 		struct bpf_hrtimer *t = container_of(cb, struct bpf_hrtimer, cb);
1686 
1687 		switch (op) {
1688 		case BPF_ASYNC_START:
1689 			hrtimer_start(&t->timer, ns_to_ktime(timer_nsec), timer_mode);
1690 			break;
1691 		case BPF_ASYNC_CANCEL:
1692 			hrtimer_try_to_cancel(&t->timer);
1693 			break;
1694 		}
1695 		break;
1696 	}
1697 	case BPF_ASYNC_TYPE_WQ: {
1698 		struct bpf_work *w = container_of(cb, struct bpf_work, cb);
1699 
1700 		switch (op) {
1701 		case BPF_ASYNC_START:
1702 			schedule_work(&w->work);
1703 			break;
1704 		case BPF_ASYNC_CANCEL:
1705 			cancel_work(&w->work);
1706 			break;
1707 		}
1708 		break;
1709 	}
1710 	}
1711 	bpf_async_refcount_put(cb);
1712 }
1713 
1714 static void bpf_async_irq_worker(struct irq_work *work)
1715 {
1716 	struct bpf_async_cb *cb = container_of(work, struct bpf_async_cb, worker);
1717 	struct llist_node *pos, *n, *list;
1718 
1719 	list = llist_del_all(&cb->async_cmds);
1720 	if (!list)
1721 		return;
1722 
1723 	list = llist_reverse_order(list);
1724 	this_cpu_write(async_cb_running, cb);
1725 	llist_for_each_safe(pos, n, list) {
1726 		struct bpf_async_cmd *cmd;
1727 
1728 		cmd = container_of(pos, struct bpf_async_cmd, node);
1729 		bpf_async_process_op(cb, cmd->op, cmd->nsec, cmd->mode);
1730 		kfree_nolock(cmd);
1731 	}
1732 	this_cpu_write(async_cb_running, NULL);
1733 }
1734 
1735 static void bpf_async_cancel_and_free(struct bpf_async_kern *async)
1736 {
1737 	struct bpf_async_cb *cb;
1738 
1739 	if (!READ_ONCE(async->cb))
1740 		return;
1741 
1742 	cb = xchg(&async->cb, NULL);
1743 	if (!cb)
1744 		return;
1745 
1746 	/* Callbacks that run after this see NULL and return. */
1747 	WRITE_ONCE(cb->map, NULL);
1748 	bpf_async_update_prog_callback(cb, NULL, NULL);
1749 	/*
1750 	 * No refcount_inc_not_zero(&cb->refcnt) here. Dropping the last
1751 	 * refcnt. Either synchronously or asynchronously in irq_work.
1752 	 */
1753 
1754 	if (!defer_timer_wq_op()) {
1755 		bpf_async_process_op(cb, BPF_ASYNC_CANCEL, 0, 0);
1756 	} else {
1757 		(void)bpf_async_schedule_op(cb, BPF_ASYNC_CANCEL, 0, 0);
1758 		/*
1759 		 * bpf_async_schedule_op() either enqueues allocated cmd into llist
1760 		 * or fails with ENOMEM and drop the last refcnt.
1761 		 * This is unlikely, but safe, since bpf_async_cb_rcu_tasks_trace_free()
1762 		 * callback will do additional timer/wq_cancel due to races anyway.
1763 		 */
1764 	}
1765 }
1766 
1767 /*
1768  * This function is called by map_delete/update_elem for individual element and
1769  * by ops->map_release_uref when the user space reference to a map reaches zero.
1770  */
1771 void bpf_timer_cancel_and_free(void *val)
1772 {
1773 	bpf_async_cancel_and_free(val);
1774 }
1775 
1776 /*
1777  * This function is called by map_delete/update_elem for individual element and
1778  * by ops->map_release_uref when the user space reference to a map reaches zero.
1779  */
1780 void bpf_wq_cancel_and_free(void *val)
1781 {
1782 	bpf_async_cancel_and_free(val);
1783 }
1784 
1785 BPF_CALL_2(bpf_kptr_xchg, void *, dst, void *, ptr)
1786 {
1787 	unsigned long *kptr = dst;
1788 
1789 	/* This helper may be inlined by verifier. */
1790 	return xchg(kptr, (unsigned long)ptr);
1791 }
1792 
1793 /* Unlike other PTR_TO_BTF_ID helpers the btf_id in bpf_kptr_xchg()
1794  * helper is determined dynamically by the verifier. Use BPF_PTR_POISON to
1795  * denote type that verifier will determine.
1796  */
1797 static const struct bpf_func_proto bpf_kptr_xchg_proto = {
1798 	.func         = bpf_kptr_xchg,
1799 	.gpl_only     = false,
1800 	.ret_type     = RET_PTR_TO_BTF_ID_OR_NULL,
1801 	.ret_btf_id   = BPF_PTR_POISON,
1802 	.arg1_type    = ARG_KPTR_XCHG_DEST,
1803 	.arg2_type    = ARG_PTR_TO_BTF_ID_OR_NULL | OBJ_RELEASE,
1804 	.arg2_btf_id  = BPF_PTR_POISON,
1805 };
1806 
1807 struct bpf_dynptr_file_impl {
1808 	struct freader freader;
1809 	/* 64 bit offset and size overriding 32 bit ones in bpf_dynptr_kern */
1810 	u64 offset;
1811 	u64 size;
1812 };
1813 
1814 /* Since the upper 8 bits of dynptr->size is reserved, the
1815  * maximum supported size is 2^24 - 1.
1816  */
1817 #define DYNPTR_MAX_SIZE	((1UL << 24) - 1)
1818 #define DYNPTR_TYPE_SHIFT	28
1819 #define DYNPTR_SIZE_MASK	0xFFFFFF
1820 #define DYNPTR_RDONLY_BIT	BIT(31)
1821 
1822 bool __bpf_dynptr_is_rdonly(const struct bpf_dynptr_kern *ptr)
1823 {
1824 	return ptr->size & DYNPTR_RDONLY_BIT;
1825 }
1826 
1827 void bpf_dynptr_set_rdonly(struct bpf_dynptr_kern *ptr)
1828 {
1829 	ptr->size |= DYNPTR_RDONLY_BIT;
1830 }
1831 
1832 static void bpf_dynptr_set_type(struct bpf_dynptr_kern *ptr, enum bpf_dynptr_type type)
1833 {
1834 	ptr->size |= type << DYNPTR_TYPE_SHIFT;
1835 }
1836 
1837 static enum bpf_dynptr_type bpf_dynptr_get_type(const struct bpf_dynptr_kern *ptr)
1838 {
1839 	return (ptr->size & ~(DYNPTR_RDONLY_BIT)) >> DYNPTR_TYPE_SHIFT;
1840 }
1841 
1842 u64 __bpf_dynptr_size(const struct bpf_dynptr_kern *ptr)
1843 {
1844 	if (bpf_dynptr_get_type(ptr) == BPF_DYNPTR_TYPE_FILE) {
1845 		struct bpf_dynptr_file_impl *df = ptr->data;
1846 
1847 		return df->size;
1848 	}
1849 
1850 	return ptr->size & DYNPTR_SIZE_MASK;
1851 }
1852 
1853 static void bpf_dynptr_advance_offset(struct bpf_dynptr_kern *ptr, u64 off)
1854 {
1855 	if (bpf_dynptr_get_type(ptr) == BPF_DYNPTR_TYPE_FILE) {
1856 		struct bpf_dynptr_file_impl *df = ptr->data;
1857 
1858 		df->offset += off;
1859 		return;
1860 	}
1861 	ptr->offset += off;
1862 }
1863 
1864 static void bpf_dynptr_set_size(struct bpf_dynptr_kern *ptr, u64 new_size)
1865 {
1866 	u32 metadata = ptr->size & ~DYNPTR_SIZE_MASK;
1867 
1868 	if (bpf_dynptr_get_type(ptr) == BPF_DYNPTR_TYPE_FILE) {
1869 		struct bpf_dynptr_file_impl *df = ptr->data;
1870 
1871 		df->size = new_size;
1872 		return;
1873 	}
1874 	ptr->size = (u32)new_size | metadata;
1875 }
1876 
1877 int bpf_dynptr_check_size(u64 size)
1878 {
1879 	return size > DYNPTR_MAX_SIZE ? -E2BIG : 0;
1880 }
1881 
1882 static int bpf_file_fetch_bytes(struct bpf_dynptr_file_impl *df, u64 offset, void *buf, u64 len)
1883 {
1884 	const void *ptr;
1885 
1886 	if (!buf)
1887 		return -EINVAL;
1888 
1889 	df->freader.buf = buf;
1890 	df->freader.buf_sz = len;
1891 	ptr = freader_fetch(&df->freader, offset + df->offset, len);
1892 	if (!ptr)
1893 		return df->freader.err;
1894 
1895 	if (ptr != buf) /* Force copying into the buffer */
1896 		memcpy(buf, ptr, len);
1897 
1898 	return 0;
1899 }
1900 
1901 void bpf_dynptr_init(struct bpf_dynptr_kern *ptr, void *data,
1902 		     enum bpf_dynptr_type type, u32 offset, u32 size)
1903 {
1904 	ptr->data = data;
1905 	ptr->offset = offset;
1906 	ptr->size = size;
1907 	bpf_dynptr_set_type(ptr, type);
1908 }
1909 
1910 void bpf_dynptr_set_null(struct bpf_dynptr_kern *ptr)
1911 {
1912 	memset(ptr, 0, sizeof(*ptr));
1913 }
1914 
1915 BPF_CALL_4(bpf_dynptr_from_mem, void *, data, u64, size, u64, flags, struct bpf_dynptr_kern *, ptr)
1916 {
1917 	int err;
1918 
1919 	BTF_TYPE_EMIT(struct bpf_dynptr);
1920 
1921 	err = bpf_dynptr_check_size(size);
1922 	if (err)
1923 		goto error;
1924 
1925 	/* flags is currently unsupported */
1926 	if (flags) {
1927 		err = -EINVAL;
1928 		goto error;
1929 	}
1930 
1931 	bpf_dynptr_init(ptr, data, BPF_DYNPTR_TYPE_LOCAL, 0, size);
1932 
1933 	return 0;
1934 
1935 error:
1936 	bpf_dynptr_set_null(ptr);
1937 	return err;
1938 }
1939 
1940 static const struct bpf_func_proto bpf_dynptr_from_mem_proto = {
1941 	.func		= bpf_dynptr_from_mem,
1942 	.gpl_only	= false,
1943 	.ret_type	= RET_INTEGER,
1944 	.arg1_type	= ARG_PTR_TO_UNINIT_MEM,
1945 	.arg2_type	= ARG_MEM_SIZE_OR_ZERO,
1946 	.arg3_type	= ARG_ANYTHING,
1947 	.arg4_type	= ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_LOCAL | MEM_UNINIT | MEM_WRITE,
1948 };
1949 
1950 static int __bpf_dynptr_read(void *dst, u64 len, const struct bpf_dynptr_kern *src,
1951 			     u64 offset, u64 flags)
1952 {
1953 	enum bpf_dynptr_type type;
1954 	int err;
1955 
1956 	if (!src->data || flags)
1957 		return -EINVAL;
1958 
1959 	err = bpf_dynptr_check_off_len(src, offset, len);
1960 	if (err)
1961 		return err;
1962 
1963 	type = bpf_dynptr_get_type(src);
1964 
1965 	switch (type) {
1966 	case BPF_DYNPTR_TYPE_LOCAL:
1967 	case BPF_DYNPTR_TYPE_RINGBUF:
1968 		/* Source and destination may possibly overlap, hence use memmove to
1969 		 * copy the data. E.g. bpf_dynptr_from_mem may create two dynptr
1970 		 * pointing to overlapping PTR_TO_MAP_VALUE regions.
1971 		 */
1972 		memmove(dst, src->data + src->offset + offset, len);
1973 		return 0;
1974 	case BPF_DYNPTR_TYPE_SKB:
1975 		return __bpf_skb_load_bytes(src->data, src->offset + offset, dst, len);
1976 	case BPF_DYNPTR_TYPE_XDP:
1977 		return __bpf_xdp_load_bytes(src->data, src->offset + offset, dst, len);
1978 	case BPF_DYNPTR_TYPE_SKB_META:
1979 		memmove(dst, bpf_skb_meta_pointer(src->data, src->offset + offset), len);
1980 		return 0;
1981 	case BPF_DYNPTR_TYPE_FILE:
1982 		return bpf_file_fetch_bytes(src->data, offset, dst, len);
1983 	default:
1984 		WARN_ONCE(true, "bpf_dynptr_read: unknown dynptr type %d\n", type);
1985 		return -EFAULT;
1986 	}
1987 }
1988 
1989 BPF_CALL_5(bpf_dynptr_read, void *, dst, u64, len, const struct bpf_dynptr_kern *, src,
1990 	   u64, offset, u64, flags)
1991 {
1992 	return __bpf_dynptr_read(dst, len, src, offset, flags);
1993 }
1994 
1995 static const struct bpf_func_proto bpf_dynptr_read_proto = {
1996 	.func		= bpf_dynptr_read,
1997 	.gpl_only	= false,
1998 	.ret_type	= RET_INTEGER,
1999 	.arg1_type	= ARG_PTR_TO_UNINIT_MEM,
2000 	.arg2_type	= ARG_MEM_SIZE_OR_ZERO,
2001 	.arg3_type	= ARG_PTR_TO_DYNPTR,
2002 	.arg4_type	= ARG_ANYTHING,
2003 	.arg5_type	= ARG_ANYTHING,
2004 };
2005 
2006 int __bpf_dynptr_write(const struct bpf_dynptr_kern *dst, u64 offset, void *src,
2007 		       u64 len, u64 flags)
2008 {
2009 	enum bpf_dynptr_type type;
2010 	int err;
2011 
2012 	if (!dst->data || __bpf_dynptr_is_rdonly(dst))
2013 		return -EINVAL;
2014 
2015 	err = bpf_dynptr_check_off_len(dst, offset, len);
2016 	if (err)
2017 		return err;
2018 
2019 	type = bpf_dynptr_get_type(dst);
2020 
2021 	switch (type) {
2022 	case BPF_DYNPTR_TYPE_LOCAL:
2023 	case BPF_DYNPTR_TYPE_RINGBUF:
2024 		if (flags)
2025 			return -EINVAL;
2026 		/* Source and destination may possibly overlap, hence use memmove to
2027 		 * copy the data. E.g. bpf_dynptr_from_mem may create two dynptr
2028 		 * pointing to overlapping PTR_TO_MAP_VALUE regions.
2029 		 */
2030 		memmove(dst->data + dst->offset + offset, src, len);
2031 		return 0;
2032 	case BPF_DYNPTR_TYPE_SKB:
2033 		return __bpf_skb_store_bytes(dst->data, dst->offset + offset, src, len,
2034 					     flags);
2035 	case BPF_DYNPTR_TYPE_XDP:
2036 		if (flags)
2037 			return -EINVAL;
2038 		return __bpf_xdp_store_bytes(dst->data, dst->offset + offset, src, len);
2039 	case BPF_DYNPTR_TYPE_SKB_META:
2040 		return __bpf_skb_meta_store_bytes(dst->data, dst->offset + offset, src,
2041 						  len, flags);
2042 	default:
2043 		WARN_ONCE(true, "bpf_dynptr_write: unknown dynptr type %d\n", type);
2044 		return -EFAULT;
2045 	}
2046 }
2047 
2048 BPF_CALL_5(bpf_dynptr_write, const struct bpf_dynptr_kern *, dst, u64, offset, void *, src,
2049 	   u64, len, u64, flags)
2050 {
2051 	return __bpf_dynptr_write(dst, offset, src, len, flags);
2052 }
2053 
2054 static const struct bpf_func_proto bpf_dynptr_write_proto = {
2055 	.func		= bpf_dynptr_write,
2056 	.gpl_only	= false,
2057 	.ret_type	= RET_INTEGER,
2058 	.arg1_type	= ARG_PTR_TO_DYNPTR,
2059 	.arg2_type	= ARG_ANYTHING,
2060 	.arg3_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
2061 	.arg4_type	= ARG_MEM_SIZE_OR_ZERO,
2062 	.arg5_type	= ARG_ANYTHING,
2063 };
2064 
2065 BPF_CALL_3(bpf_dynptr_data, const struct bpf_dynptr_kern *, ptr, u64, offset, u64, len)
2066 {
2067 	enum bpf_dynptr_type type;
2068 	int err;
2069 
2070 	if (!ptr->data)
2071 		return 0;
2072 
2073 	err = bpf_dynptr_check_off_len(ptr, offset, len);
2074 	if (err)
2075 		return 0;
2076 
2077 	if (__bpf_dynptr_is_rdonly(ptr))
2078 		return 0;
2079 
2080 	type = bpf_dynptr_get_type(ptr);
2081 
2082 	switch (type) {
2083 	case BPF_DYNPTR_TYPE_LOCAL:
2084 	case BPF_DYNPTR_TYPE_RINGBUF:
2085 		return (unsigned long)(ptr->data + ptr->offset + offset);
2086 	case BPF_DYNPTR_TYPE_SKB:
2087 	case BPF_DYNPTR_TYPE_XDP:
2088 	case BPF_DYNPTR_TYPE_SKB_META:
2089 		/* skb and xdp dynptrs should use bpf_dynptr_slice / bpf_dynptr_slice_rdwr */
2090 		return 0;
2091 	default:
2092 		WARN_ONCE(true, "bpf_dynptr_data: unknown dynptr type %d\n", type);
2093 		return 0;
2094 	}
2095 }
2096 
2097 static const struct bpf_func_proto bpf_dynptr_data_proto = {
2098 	.func		= bpf_dynptr_data,
2099 	.gpl_only	= false,
2100 	.ret_type	= RET_PTR_TO_DYNPTR_MEM_OR_NULL,
2101 	.arg1_type	= ARG_PTR_TO_DYNPTR,
2102 	.arg2_type	= ARG_ANYTHING,
2103 	.arg3_type	= ARG_CONST_ALLOC_SIZE_OR_ZERO,
2104 };
2105 
2106 const struct bpf_func_proto bpf_get_current_task_proto __weak;
2107 const struct bpf_func_proto bpf_get_current_task_btf_proto __weak;
2108 const struct bpf_func_proto bpf_probe_read_user_proto __weak;
2109 const struct bpf_func_proto bpf_probe_read_user_str_proto __weak;
2110 const struct bpf_func_proto bpf_probe_read_kernel_proto __weak;
2111 const struct bpf_func_proto bpf_probe_read_kernel_str_proto __weak;
2112 const struct bpf_func_proto bpf_task_pt_regs_proto __weak;
2113 const struct bpf_func_proto bpf_perf_event_read_proto __weak;
2114 const struct bpf_func_proto bpf_send_signal_proto __weak;
2115 const struct bpf_func_proto bpf_send_signal_thread_proto __weak;
2116 const struct bpf_func_proto bpf_get_task_stack_sleepable_proto __weak;
2117 const struct bpf_func_proto bpf_get_task_stack_proto __weak;
2118 const struct bpf_func_proto bpf_get_branch_snapshot_proto __weak;
2119 
2120 const struct bpf_func_proto *
2121 bpf_base_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
2122 {
2123 	switch (func_id) {
2124 	case BPF_FUNC_map_lookup_elem:
2125 		return &bpf_map_lookup_elem_proto;
2126 	case BPF_FUNC_map_update_elem:
2127 		return &bpf_map_update_elem_proto;
2128 	case BPF_FUNC_map_delete_elem:
2129 		return &bpf_map_delete_elem_proto;
2130 	case BPF_FUNC_map_push_elem:
2131 		return &bpf_map_push_elem_proto;
2132 	case BPF_FUNC_map_pop_elem:
2133 		return &bpf_map_pop_elem_proto;
2134 	case BPF_FUNC_map_peek_elem:
2135 		return &bpf_map_peek_elem_proto;
2136 	case BPF_FUNC_map_lookup_percpu_elem:
2137 		return &bpf_map_lookup_percpu_elem_proto;
2138 	case BPF_FUNC_get_prandom_u32:
2139 		return &bpf_get_prandom_u32_proto;
2140 	case BPF_FUNC_get_smp_processor_id:
2141 		return &bpf_get_raw_smp_processor_id_proto;
2142 	case BPF_FUNC_get_numa_node_id:
2143 		return &bpf_get_numa_node_id_proto;
2144 	case BPF_FUNC_tail_call:
2145 		return &bpf_tail_call_proto;
2146 	case BPF_FUNC_ktime_get_ns:
2147 		return &bpf_ktime_get_ns_proto;
2148 	case BPF_FUNC_ktime_get_boot_ns:
2149 		return &bpf_ktime_get_boot_ns_proto;
2150 	case BPF_FUNC_ktime_get_tai_ns:
2151 		return &bpf_ktime_get_tai_ns_proto;
2152 	case BPF_FUNC_ringbuf_output:
2153 		return &bpf_ringbuf_output_proto;
2154 	case BPF_FUNC_ringbuf_reserve:
2155 		return &bpf_ringbuf_reserve_proto;
2156 	case BPF_FUNC_ringbuf_submit:
2157 		return &bpf_ringbuf_submit_proto;
2158 	case BPF_FUNC_ringbuf_discard:
2159 		return &bpf_ringbuf_discard_proto;
2160 	case BPF_FUNC_ringbuf_query:
2161 		return &bpf_ringbuf_query_proto;
2162 	case BPF_FUNC_strncmp:
2163 		return &bpf_strncmp_proto;
2164 	case BPF_FUNC_strtol:
2165 		return &bpf_strtol_proto;
2166 	case BPF_FUNC_strtoul:
2167 		return &bpf_strtoul_proto;
2168 	case BPF_FUNC_get_current_pid_tgid:
2169 		return &bpf_get_current_pid_tgid_proto;
2170 	case BPF_FUNC_get_ns_current_pid_tgid:
2171 		return &bpf_get_ns_current_pid_tgid_proto;
2172 	case BPF_FUNC_get_current_uid_gid:
2173 		return &bpf_get_current_uid_gid_proto;
2174 	default:
2175 		break;
2176 	}
2177 
2178 	if (!bpf_token_capable(prog->aux->token, CAP_BPF))
2179 		return NULL;
2180 
2181 	switch (func_id) {
2182 	case BPF_FUNC_spin_lock:
2183 		return &bpf_spin_lock_proto;
2184 	case BPF_FUNC_spin_unlock:
2185 		return &bpf_spin_unlock_proto;
2186 	case BPF_FUNC_jiffies64:
2187 		return &bpf_jiffies64_proto;
2188 	case BPF_FUNC_per_cpu_ptr:
2189 		return &bpf_per_cpu_ptr_proto;
2190 	case BPF_FUNC_this_cpu_ptr:
2191 		return &bpf_this_cpu_ptr_proto;
2192 	case BPF_FUNC_timer_init:
2193 		return &bpf_timer_init_proto;
2194 	case BPF_FUNC_timer_set_callback:
2195 		return &bpf_timer_set_callback_proto;
2196 	case BPF_FUNC_timer_start:
2197 		return &bpf_timer_start_proto;
2198 	case BPF_FUNC_timer_cancel:
2199 		return &bpf_timer_cancel_proto;
2200 	case BPF_FUNC_kptr_xchg:
2201 		return &bpf_kptr_xchg_proto;
2202 	case BPF_FUNC_for_each_map_elem:
2203 		return &bpf_for_each_map_elem_proto;
2204 	case BPF_FUNC_loop:
2205 		return &bpf_loop_proto;
2206 	case BPF_FUNC_user_ringbuf_drain:
2207 		return &bpf_user_ringbuf_drain_proto;
2208 	case BPF_FUNC_ringbuf_reserve_dynptr:
2209 		return &bpf_ringbuf_reserve_dynptr_proto;
2210 	case BPF_FUNC_ringbuf_submit_dynptr:
2211 		return &bpf_ringbuf_submit_dynptr_proto;
2212 	case BPF_FUNC_ringbuf_discard_dynptr:
2213 		return &bpf_ringbuf_discard_dynptr_proto;
2214 	case BPF_FUNC_dynptr_from_mem:
2215 		return &bpf_dynptr_from_mem_proto;
2216 	case BPF_FUNC_dynptr_read:
2217 		return &bpf_dynptr_read_proto;
2218 	case BPF_FUNC_dynptr_write:
2219 		return &bpf_dynptr_write_proto;
2220 	case BPF_FUNC_dynptr_data:
2221 		return &bpf_dynptr_data_proto;
2222 #ifdef CONFIG_CGROUPS
2223 	case BPF_FUNC_cgrp_storage_get:
2224 		return &bpf_cgrp_storage_get_proto;
2225 	case BPF_FUNC_cgrp_storage_delete:
2226 		return &bpf_cgrp_storage_delete_proto;
2227 	case BPF_FUNC_get_current_cgroup_id:
2228 		return &bpf_get_current_cgroup_id_proto;
2229 	case BPF_FUNC_get_current_ancestor_cgroup_id:
2230 		return &bpf_get_current_ancestor_cgroup_id_proto;
2231 	case BPF_FUNC_current_task_under_cgroup:
2232 		return &bpf_current_task_under_cgroup_proto;
2233 #endif
2234 #ifdef CONFIG_CGROUP_NET_CLASSID
2235 	case BPF_FUNC_get_cgroup_classid:
2236 		return &bpf_get_cgroup_classid_curr_proto;
2237 #endif
2238 	case BPF_FUNC_task_storage_get:
2239 		return &bpf_task_storage_get_proto;
2240 	case BPF_FUNC_task_storage_delete:
2241 		return &bpf_task_storage_delete_proto;
2242 	default:
2243 		break;
2244 	}
2245 
2246 	if (!bpf_token_capable(prog->aux->token, CAP_PERFMON))
2247 		return NULL;
2248 
2249 	switch (func_id) {
2250 	case BPF_FUNC_trace_printk:
2251 		return bpf_get_trace_printk_proto();
2252 	case BPF_FUNC_get_current_task:
2253 		return &bpf_get_current_task_proto;
2254 	case BPF_FUNC_get_current_task_btf:
2255 		return &bpf_get_current_task_btf_proto;
2256 	case BPF_FUNC_get_current_comm:
2257 		return &bpf_get_current_comm_proto;
2258 	case BPF_FUNC_probe_read_user:
2259 		return &bpf_probe_read_user_proto;
2260 	case BPF_FUNC_probe_read_kernel:
2261 		return security_locked_down(LOCKDOWN_BPF_READ_KERNEL) < 0 ?
2262 		       NULL : &bpf_probe_read_kernel_proto;
2263 	case BPF_FUNC_probe_read_user_str:
2264 		return &bpf_probe_read_user_str_proto;
2265 	case BPF_FUNC_probe_read_kernel_str:
2266 		return security_locked_down(LOCKDOWN_BPF_READ_KERNEL) < 0 ?
2267 		       NULL : &bpf_probe_read_kernel_str_proto;
2268 	case BPF_FUNC_copy_from_user:
2269 		return &bpf_copy_from_user_proto;
2270 	case BPF_FUNC_copy_from_user_task:
2271 		return &bpf_copy_from_user_task_proto;
2272 	case BPF_FUNC_snprintf_btf:
2273 		return &bpf_snprintf_btf_proto;
2274 	case BPF_FUNC_snprintf:
2275 		return &bpf_snprintf_proto;
2276 	case BPF_FUNC_task_pt_regs:
2277 		return &bpf_task_pt_regs_proto;
2278 	case BPF_FUNC_trace_vprintk:
2279 		return bpf_get_trace_vprintk_proto();
2280 	case BPF_FUNC_perf_event_read_value:
2281 		return bpf_get_perf_event_read_value_proto();
2282 	case BPF_FUNC_perf_event_read:
2283 		return &bpf_perf_event_read_proto;
2284 	case BPF_FUNC_send_signal:
2285 		return &bpf_send_signal_proto;
2286 	case BPF_FUNC_send_signal_thread:
2287 		return &bpf_send_signal_thread_proto;
2288 	case BPF_FUNC_get_task_stack:
2289 		return prog->sleepable ? &bpf_get_task_stack_sleepable_proto
2290 				       : &bpf_get_task_stack_proto;
2291 	case BPF_FUNC_get_branch_snapshot:
2292 		return &bpf_get_branch_snapshot_proto;
2293 	case BPF_FUNC_find_vma:
2294 		return &bpf_find_vma_proto;
2295 	default:
2296 		return NULL;
2297 	}
2298 }
2299 EXPORT_SYMBOL_GPL(bpf_base_func_proto);
2300 
2301 void bpf_list_head_free(const struct btf_field *field, void *list_head,
2302 			struct bpf_spin_lock *spin_lock)
2303 {
2304 	struct list_head *head = list_head, drain, *pos, *n;
2305 
2306 	BUILD_BUG_ON(sizeof(struct list_head) > sizeof(struct bpf_list_head));
2307 	BUILD_BUG_ON(__alignof__(struct list_head) > __alignof__(struct bpf_list_head));
2308 	INIT_LIST_HEAD(&drain);
2309 
2310 	/* Do the actual list draining outside the lock to not hold the lock for
2311 	 * too long, and also prevent deadlocks if tracing programs end up
2312 	 * executing on entry/exit of functions called inside the critical
2313 	 * section, and end up doing map ops that call bpf_list_head_free for
2314 	 * the same map value again.
2315 	 */
2316 	__bpf_spin_lock_irqsave(spin_lock);
2317 	if (!head->next || list_empty(head))
2318 		goto unlock;
2319 	list_for_each_safe(pos, n, head) {
2320 		struct bpf_list_node_kern *node;
2321 
2322 		node = container_of(pos, struct bpf_list_node_kern, list_head);
2323 		WRITE_ONCE(node->owner, BPF_PTR_POISON);
2324 		list_move_tail(pos, &drain);
2325 	}
2326 unlock:
2327 	INIT_LIST_HEAD(head);
2328 	__bpf_spin_unlock_irqrestore(spin_lock);
2329 
2330 	while (!list_empty(&drain)) {
2331 		struct bpf_list_node_kern *node;
2332 
2333 		pos = drain.next;
2334 		node = container_of(pos, struct bpf_list_node_kern, list_head);
2335 		list_del_init(pos);
2336 		/* Ensure __bpf_list_add() sees the node as unlinked. */
2337 		smp_store_release(&node->owner, NULL);
2338 		/* The contained type can also have resources, including a
2339 		 * bpf_list_head which needs to be freed.
2340 		 */
2341 		__bpf_obj_drop_impl((char *)pos - field->graph_root.node_offset,
2342 				    field->graph_root.value_rec, false);
2343 	}
2344 }
2345 
2346 /* Like rbtree_postorder_for_each_entry_safe, but 'pos' and 'n' are
2347  * 'rb_node *', so field name of rb_node within containing struct is not
2348  * needed.
2349  *
2350  * Since bpf_rb_tree's node type has a corresponding struct btf_field with
2351  * graph_root.node_offset, it's not necessary to know field name
2352  * or type of node struct
2353  */
2354 #define bpf_rbtree_postorder_for_each_entry_safe(pos, n, root) \
2355 	for (pos = rb_first_postorder(root); \
2356 	    pos && ({ n = rb_next_postorder(pos); 1; }); \
2357 	    pos = n)
2358 
2359 void bpf_rb_root_free(const struct btf_field *field, void *rb_root,
2360 		      struct bpf_spin_lock *spin_lock)
2361 {
2362 	struct rb_root_cached orig_root, *root = rb_root;
2363 	struct bpf_rb_node_kern *node;
2364 	struct rb_node *pos, *n;
2365 	void *obj;
2366 
2367 	BUILD_BUG_ON(sizeof(struct rb_root_cached) > sizeof(struct bpf_rb_root));
2368 	BUILD_BUG_ON(__alignof__(struct rb_root_cached) > __alignof__(struct bpf_rb_root));
2369 
2370 	__bpf_spin_lock_irqsave(spin_lock);
2371 	orig_root = *root;
2372 	bpf_rbtree_postorder_for_each_entry_safe(pos, n, &orig_root.rb_root) {
2373 		node = rb_entry(pos, struct bpf_rb_node_kern, rb_node);
2374 		WRITE_ONCE(node->owner, BPF_PTR_POISON);
2375 	}
2376 	*root = RB_ROOT_CACHED;
2377 	__bpf_spin_unlock_irqrestore(spin_lock);
2378 
2379 	bpf_rbtree_postorder_for_each_entry_safe(pos, n, &orig_root.rb_root) {
2380 		obj = pos;
2381 		obj -= field->graph_root.node_offset;
2382 		node = rb_entry(pos, struct bpf_rb_node_kern, rb_node);
2383 		RB_CLEAR_NODE(pos);
2384 		/* Ensure __bpf_rbtree_add() sees the node as unlinked. */
2385 		smp_store_release(&node->owner, NULL);
2386 		__bpf_obj_drop_impl(obj, field->graph_root.value_rec, false);
2387 	}
2388 }
2389 
2390 __bpf_kfunc_start_defs();
2391 
2392 /**
2393  * bpf_obj_new() - allocate an object described by program BTF
2394  * @local_type_id__k: type ID in program BTF
2395  * @meta: verifier-supplied struct metadata
2396  *
2397  * Allocate an object of the type identified by @local_type_id__k and
2398  * initialize its special fields. BPF programs can use
2399  * bpf_core_type_id_local() to provide @local_type_id__k. The verifier
2400  * rewrites @meta; BPF programs do not set it.
2401  *
2402  * Return: Pointer to the allocated object, or %NULL on failure.
2403  */
2404 __bpf_kfunc void *bpf_obj_new(u64 local_type_id__k, struct btf_struct_meta *meta)
2405 {
2406 	u64 size = local_type_id__k;
2407 	void *p;
2408 
2409 	p = bpf_mem_alloc(&bpf_global_ma, size);
2410 	if (!p)
2411 		return NULL;
2412 	if (meta)
2413 		bpf_obj_init(meta->record, p);
2414 
2415 	return p;
2416 }
2417 
2418 __bpf_kfunc void *bpf_obj_new_impl(u64 local_type_id__k, void *meta__ign)
2419 {
2420 	return bpf_obj_new(local_type_id__k, meta__ign);
2421 }
2422 
2423 /**
2424  * bpf_percpu_obj_new() - allocate a percpu object described by program BTF
2425  * @local_type_id__k: type ID in program BTF
2426  * @meta: verifier-supplied struct metadata
2427  *
2428  * Allocate a percpu object of the type identified by @local_type_id__k. BPF
2429  * programs can use bpf_core_type_id_local() to provide @local_type_id__k.
2430  * The verifier rewrites @meta; BPF programs do not set it.
2431  *
2432  * Return: Pointer to the allocated percpu object, or %NULL on failure.
2433  */
2434 __bpf_kfunc void *bpf_percpu_obj_new(u64 local_type_id__k, struct btf_struct_meta *meta)
2435 {
2436 	u64 size = local_type_id__k;
2437 
2438 	/* The verifier has ensured that meta must be NULL */
2439 	return bpf_mem_alloc(&bpf_global_percpu_ma, size);
2440 }
2441 
2442 __bpf_kfunc void *bpf_percpu_obj_new_impl(u64 local_type_id__k, void *meta__ign)
2443 {
2444 	return bpf_percpu_obj_new(local_type_id__k, meta__ign);
2445 }
2446 
2447 /* Must be called under migrate_disable(), as required by bpf_mem_free */
2448 void __bpf_obj_drop_impl(void *p, const struct btf_record *rec, bool percpu)
2449 {
2450 	struct bpf_mem_alloc *ma;
2451 
2452 	if (rec && rec->refcount_off >= 0 &&
2453 	    !refcount_dec_and_test((refcount_t *)(p + rec->refcount_off))) {
2454 		/* Object is refcounted and refcount_dec didn't result in 0
2455 		 * refcount. Return without freeing the object
2456 		 */
2457 		return;
2458 	}
2459 
2460 	if (rec)
2461 		bpf_obj_free_fields(rec, p);
2462 
2463 	if (percpu)
2464 		ma = &bpf_global_percpu_ma;
2465 	else
2466 		ma = &bpf_global_ma;
2467 	bpf_mem_free_rcu(ma, p);
2468 }
2469 
2470 /**
2471  * bpf_obj_drop() - drop a previously allocated object
2472  * @p__alloc: object to free
2473  * @meta: verifier-supplied struct metadata
2474  *
2475  * Destroy special fields in @p__alloc as needed and free the object. The
2476  * verifier rewrites @meta; BPF programs do not set it.
2477  */
2478 __bpf_kfunc void bpf_obj_drop(void *p__alloc, struct btf_struct_meta *meta)
2479 {
2480 	void *p = p__alloc;
2481 
2482 	__bpf_obj_drop_impl(p, meta ? meta->record : NULL, false);
2483 }
2484 
2485 __bpf_kfunc void bpf_obj_drop_impl(void *p__alloc, void *meta__ign)
2486 {
2487 	return bpf_obj_drop(p__alloc, meta__ign);
2488 }
2489 
2490 /**
2491  * bpf_percpu_obj_drop() - drop a previously allocated percpu object
2492  * @p__alloc: percpu object to free
2493  * @meta: verifier-supplied struct metadata
2494  *
2495  * Free @p__alloc. The verifier rewrites @meta; BPF programs do not set it.
2496  */
2497 __bpf_kfunc void bpf_percpu_obj_drop(void *p__alloc, struct btf_struct_meta *meta)
2498 {
2499 	/* The verifier has ensured that meta must be NULL */
2500 	bpf_mem_free_rcu(&bpf_global_percpu_ma, p__alloc);
2501 }
2502 
2503 __bpf_kfunc void bpf_percpu_obj_drop_impl(void *p__alloc, void *meta__ign)
2504 {
2505 	bpf_percpu_obj_drop(p__alloc, meta__ign);
2506 }
2507 
2508 /**
2509  * bpf_refcount_acquire() - turn a local kptr into an owning reference
2510  * @p__refcounted_kptr: non-owning local kptr
2511  * @meta: verifier-supplied struct metadata
2512  *
2513  * Increment the refcount for @p__refcounted_kptr. The verifier rewrites
2514  * @meta; BPF programs do not set it.
2515  *
2516  * Return: Owning reference to @p__refcounted_kptr, or %NULL on failure.
2517  */
2518 __bpf_kfunc void *bpf_refcount_acquire(void *p__refcounted_kptr, struct btf_struct_meta *meta)
2519 {
2520 	struct bpf_refcount *ref;
2521 
2522 	/* Could just cast directly to refcount_t *, but need some code using
2523 	 * bpf_refcount type so that it is emitted in vmlinux BTF
2524 	 */
2525 	ref = (struct bpf_refcount *)(p__refcounted_kptr + meta->record->refcount_off);
2526 	if (!refcount_inc_not_zero((refcount_t *)ref))
2527 		return NULL;
2528 
2529 	/* Verifier strips KF_RET_NULL if input is owned ref, see is_kfunc_ret_null
2530 	 * in verifier.c
2531 	 */
2532 	return (void *)p__refcounted_kptr;
2533 }
2534 
2535 __bpf_kfunc void *bpf_refcount_acquire_impl(void *p__refcounted_kptr, void *meta__ign)
2536 {
2537 	return bpf_refcount_acquire(p__refcounted_kptr, meta__ign);
2538 }
2539 
2540 static int __bpf_list_add(struct bpf_list_node_kern *node,
2541 			  struct bpf_list_head *head,
2542 			  struct list_head **prev_ptr,
2543 			  struct btf_record *rec, u64 off)
2544 {
2545 	struct list_head *n = &node->list_head, *h = (void *)head;
2546 	struct list_head *prev;
2547 
2548 	/* If list_head was 0-initialized by map, bpf_obj_init_field wasn't
2549 	 * called on its fields, so init here
2550 	 */
2551 	if (unlikely(!h->next))
2552 		INIT_LIST_HEAD(h);
2553 
2554 	prev = *prev_ptr;
2555 
2556 	/* When prev is not the list head, it must be a node in this list. */
2557 	if (prev != h) {
2558 		struct bpf_list_node_kern *prev_kn =
2559 			container_of(prev, struct bpf_list_node_kern, list_head);
2560 
2561 		if (unlikely(READ_ONCE(prev_kn->owner) != head))
2562 			goto fail;
2563 	}
2564 
2565 	/* node->owner != NULL implies !list_empty(n), no need to separately
2566 	 * check the latter
2567 	 */
2568 	if (cmpxchg(&node->owner, NULL, BPF_PTR_POISON))
2569 		goto fail;
2570 
2571 	list_add(n, prev);
2572 	WRITE_ONCE(node->owner, head);
2573 	return 0;
2574 
2575 fail:
2576 	/* Only called from BPF prog, no need to migrate_disable */
2577 	__bpf_obj_drop_impl((void *)n - off, rec, false);
2578 	return -EINVAL;
2579 }
2580 
2581 /**
2582  * bpf_list_push_front() - add a node to the front of a BPF linked list
2583  * @head: list head
2584  * @node: node to insert
2585  * @meta: verifier-supplied struct metadata
2586  * @off: verifier-supplied offset of @node within the containing object
2587  *
2588  * Insert @node at the front of @head. The verifier rewrites @meta and @off;
2589  * BPF programs do not set them.
2590  *
2591  * Return: 0 on success, or %-EINVAL if @node is already linked.
2592  */
2593 __bpf_kfunc int bpf_list_push_front(struct bpf_list_head *head,
2594 				    struct bpf_list_node *node,
2595 				    struct btf_struct_meta *meta,
2596 				    u64 off)
2597 {
2598 	struct bpf_list_node_kern *n = (void *)node;
2599 	struct list_head *h = (void *)head;
2600 
2601 	return __bpf_list_add(n, head, &h, meta ? meta->record : NULL, off);
2602 }
2603 
2604 __bpf_kfunc int bpf_list_push_front_impl(struct bpf_list_head *head,
2605 					 struct bpf_list_node *node,
2606 					 void *meta__ign, u64 off)
2607 {
2608 	return bpf_list_push_front(head, node, meta__ign, off);
2609 }
2610 
2611 /**
2612  * bpf_list_push_back() - add a node to the back of a BPF linked list
2613  * @head: list head
2614  * @node: node to insert
2615  * @meta: verifier-supplied struct metadata
2616  * @off: verifier-supplied offset of @node within the containing object
2617  *
2618  * Insert @node at the back of @head. The verifier rewrites @meta and @off;
2619  * BPF programs do not set them.
2620  *
2621  * Return: 0 on success, or %-EINVAL if @node is already linked.
2622  */
2623 __bpf_kfunc int bpf_list_push_back(struct bpf_list_head *head,
2624 				   struct bpf_list_node *node,
2625 				   struct btf_struct_meta *meta,
2626 				   u64 off)
2627 {
2628 	struct bpf_list_node_kern *n = (void *)node;
2629 	struct list_head *h = (void *)head;
2630 
2631 	return __bpf_list_add(n, head, &h->prev, meta ? meta->record : NULL, off);
2632 }
2633 
2634 __bpf_kfunc int bpf_list_push_back_impl(struct bpf_list_head *head,
2635 					struct bpf_list_node *node,
2636 					void *meta__ign, u64 off)
2637 {
2638 	return bpf_list_push_back(head, node, meta__ign, off);
2639 }
2640 
2641 __bpf_kfunc int bpf_list_add(struct bpf_list_head *head, struct bpf_list_node *new,
2642 			     struct bpf_list_node *prev__nonown_allowed,
2643 			     struct btf_struct_meta *meta, u64 off)
2644 {
2645 	struct bpf_list_node_kern *n = (void *)new, *p = (void *)prev__nonown_allowed;
2646 	struct list_head *prev_ptr = &p->list_head;
2647 
2648 	return __bpf_list_add(n, head, &prev_ptr, meta ? meta->record : NULL, off);
2649 }
2650 
2651 static struct bpf_list_node *__bpf_list_del(struct bpf_list_head *head,
2652 					    struct list_head *n)
2653 {
2654 	struct list_head *h = (void *)head;
2655 	struct bpf_list_node_kern *node;
2656 
2657 	/* If list_head was 0-initialized by map, bpf_obj_init_field wasn't
2658 	 * called on its fields, so init here
2659 	 */
2660 	if (unlikely(!h->next)) {
2661 		INIT_LIST_HEAD(h);
2662 		return NULL;
2663 	}
2664 	if (list_empty(h))
2665 		return NULL;
2666 
2667 	node = container_of(n, struct bpf_list_node_kern, list_head);
2668 	if (unlikely(READ_ONCE(node->owner) != head))
2669 		return NULL;
2670 
2671 	list_del_init(n);
2672 	/* Ensure __bpf_list_add() sees the node as unlinked. */
2673 	smp_store_release(&node->owner, NULL);
2674 	return (struct bpf_list_node *)n;
2675 }
2676 
2677 __bpf_kfunc struct bpf_list_node *bpf_list_pop_front(struct bpf_list_head *head)
2678 {
2679 	struct list_head *h = (void *)head;
2680 
2681 	return __bpf_list_del(head, h->next);
2682 }
2683 
2684 __bpf_kfunc struct bpf_list_node *bpf_list_pop_back(struct bpf_list_head *head)
2685 {
2686 	struct list_head *h = (void *)head;
2687 
2688 	return __bpf_list_del(head, h->prev);
2689 }
2690 
2691 __bpf_kfunc struct bpf_list_node *bpf_list_del(struct bpf_list_head *head,
2692 					       struct bpf_list_node *node__nonown_allowed)
2693 {
2694 	struct bpf_list_node_kern *kn = (void *)node__nonown_allowed;
2695 
2696 	/* verifier guarantees node is a list node rather than list head */
2697 	return __bpf_list_del(head, &kn->list_head);
2698 }
2699 
2700 __bpf_kfunc struct bpf_list_node *bpf_list_front(struct bpf_list_head *head)
2701 {
2702 	struct list_head *h = (struct list_head *)head;
2703 
2704 	if (list_empty(h) || unlikely(!h->next))
2705 		return NULL;
2706 
2707 	return (struct bpf_list_node *)h->next;
2708 }
2709 
2710 __bpf_kfunc struct bpf_list_node *bpf_list_back(struct bpf_list_head *head)
2711 {
2712 	struct list_head *h = (struct list_head *)head;
2713 
2714 	if (list_empty(h) || unlikely(!h->next))
2715 		return NULL;
2716 
2717 	return (struct bpf_list_node *)h->prev;
2718 }
2719 
2720 __bpf_kfunc bool bpf_list_is_first(struct bpf_list_head *head,
2721 				   struct bpf_list_node *node__nonown_allowed)
2722 {
2723 	struct list_head *h = (struct list_head *)head;
2724 	struct bpf_list_node_kern *kn = (struct bpf_list_node_kern *)node__nonown_allowed;
2725 
2726 	if (READ_ONCE(kn->owner) != head)
2727 		return false;
2728 
2729 	return list_is_first(&kn->list_head, h);
2730 }
2731 
2732 __bpf_kfunc bool bpf_list_is_last(struct bpf_list_head *head,
2733 				  struct bpf_list_node *node__nonown_allowed)
2734 {
2735 	struct list_head *h = (struct list_head *)head;
2736 	struct bpf_list_node_kern *kn = (struct bpf_list_node_kern *)node__nonown_allowed;
2737 
2738 	if (READ_ONCE(kn->owner) != head)
2739 		return false;
2740 
2741 	return list_is_last(&kn->list_head, h);
2742 }
2743 
2744 __bpf_kfunc bool bpf_list_empty(struct bpf_list_head *head)
2745 {
2746 	struct list_head *h = (struct list_head *)head;
2747 
2748 	/* If list_head was 0-initialized by map, bpf_obj_init_field wasn't
2749 	 * called on its fields, so init here
2750 	 */
2751 	if (unlikely(!h->next))
2752 		INIT_LIST_HEAD(h);
2753 
2754 	return list_empty(h);
2755 }
2756 
2757 __bpf_kfunc struct bpf_rb_node *bpf_rbtree_remove(struct bpf_rb_root *root,
2758 						  struct bpf_rb_node *node)
2759 {
2760 	struct bpf_rb_node_kern *node_internal = (struct bpf_rb_node_kern *)node;
2761 	struct rb_root_cached *r = (struct rb_root_cached *)root;
2762 	struct rb_node *n = &node_internal->rb_node;
2763 
2764 	/* node_internal->owner != root implies either RB_EMPTY_NODE(n) or
2765 	 * n is owned by some other tree. No need to check RB_EMPTY_NODE(n)
2766 	 */
2767 	if (READ_ONCE(node_internal->owner) != root)
2768 		return NULL;
2769 
2770 	rb_erase_cached(n, r);
2771 	RB_CLEAR_NODE(n);
2772 	WRITE_ONCE(node_internal->owner, NULL);
2773 	return (struct bpf_rb_node *)n;
2774 }
2775 
2776 /* Need to copy rbtree_add_cached's logic here because our 'less' is a BPF
2777  * program
2778  */
2779 static int __bpf_rbtree_add(struct bpf_rb_root *root,
2780 			    struct bpf_rb_node_kern *node,
2781 			    void *less, struct btf_record *rec, u64 off)
2782 {
2783 	struct rb_node **link = &((struct rb_root_cached *)root)->rb_root.rb_node;
2784 	struct rb_node *parent = NULL, *n = &node->rb_node;
2785 	bpf_callback_t cb = (bpf_callback_t)less;
2786 	bool leftmost = true;
2787 
2788 	/* node->owner != NULL implies !RB_EMPTY_NODE(n), no need to separately
2789 	 * check the latter
2790 	 */
2791 	if (cmpxchg(&node->owner, NULL, BPF_PTR_POISON)) {
2792 		/* Only called from BPF prog, no need to migrate_disable */
2793 		__bpf_obj_drop_impl((void *)n - off, rec, false);
2794 		return -EINVAL;
2795 	}
2796 
2797 	while (*link) {
2798 		parent = *link;
2799 		if (cb((uintptr_t)node, (uintptr_t)parent, 0, 0, 0)) {
2800 			link = &parent->rb_left;
2801 		} else {
2802 			link = &parent->rb_right;
2803 			leftmost = false;
2804 		}
2805 	}
2806 
2807 	rb_link_node(n, parent, link);
2808 	rb_insert_color_cached(n, (struct rb_root_cached *)root, leftmost);
2809 	WRITE_ONCE(node->owner, root);
2810 	return 0;
2811 }
2812 
2813 /**
2814  * bpf_rbtree_add() - add a node to a BPF rbtree
2815  * @root: tree root
2816  * @node: node to insert
2817  * @less: comparator used to order nodes
2818  * @meta: verifier-supplied struct metadata
2819  * @off: verifier-supplied offset of @node within the containing object
2820  *
2821  * Insert @node into @root using @less. The verifier rewrites @meta and @off;
2822  * BPF programs do not set them.
2823  *
2824  * Return: 0 on success, or %-EINVAL if @node is already linked in a tree.
2825  */
2826 __bpf_kfunc int bpf_rbtree_add(struct bpf_rb_root *root,
2827 			       struct bpf_rb_node *node,
2828 			       bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b),
2829 			       struct btf_struct_meta *meta,
2830 			       u64 off)
2831 {
2832 	struct bpf_rb_node_kern *n = (void *)node;
2833 
2834 	return __bpf_rbtree_add(root, n, (void *)less, meta ? meta->record : NULL, off);
2835 }
2836 
2837 __bpf_kfunc int bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node,
2838 				    bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b),
2839 				    void *meta__ign, u64 off)
2840 {
2841 	return bpf_rbtree_add(root, node, less, meta__ign, off);
2842 }
2843 
2844 __bpf_kfunc struct bpf_rb_node *bpf_rbtree_first(struct bpf_rb_root *root)
2845 {
2846 	struct rb_root_cached *r = (struct rb_root_cached *)root;
2847 
2848 	return (struct bpf_rb_node *)rb_first_cached(r);
2849 }
2850 
2851 __bpf_kfunc struct bpf_rb_node *bpf_rbtree_root(struct bpf_rb_root *root)
2852 {
2853 	struct rb_root_cached *r = (struct rb_root_cached *)root;
2854 
2855 	return (struct bpf_rb_node *)r->rb_root.rb_node;
2856 }
2857 
2858 __bpf_kfunc struct bpf_rb_node *bpf_rbtree_left(struct bpf_rb_root *root, struct bpf_rb_node *node)
2859 {
2860 	struct bpf_rb_node_kern *node_internal = (struct bpf_rb_node_kern *)node;
2861 
2862 	if (READ_ONCE(node_internal->owner) != root)
2863 		return NULL;
2864 
2865 	return (struct bpf_rb_node *)node_internal->rb_node.rb_left;
2866 }
2867 
2868 __bpf_kfunc struct bpf_rb_node *bpf_rbtree_right(struct bpf_rb_root *root, struct bpf_rb_node *node)
2869 {
2870 	struct bpf_rb_node_kern *node_internal = (struct bpf_rb_node_kern *)node;
2871 
2872 	if (READ_ONCE(node_internal->owner) != root)
2873 		return NULL;
2874 
2875 	return (struct bpf_rb_node *)node_internal->rb_node.rb_right;
2876 }
2877 
2878 /**
2879  * bpf_task_acquire - Acquire a reference to a task. A task acquired by this
2880  * kfunc which is not stored in a map as a kptr, must be released by calling
2881  * bpf_task_release().
2882  * @p: The task on which a reference is being acquired.
2883  */
2884 __bpf_kfunc struct task_struct *bpf_task_acquire(struct task_struct *p)
2885 {
2886 	if (refcount_inc_not_zero(&p->rcu_users))
2887 		return p;
2888 	return NULL;
2889 }
2890 
2891 /**
2892  * bpf_task_release - Release the reference acquired on a task.
2893  * @p: The task on which a reference is being released.
2894  */
2895 __bpf_kfunc void bpf_task_release(struct task_struct *p)
2896 {
2897 	put_task_struct_rcu_user(p);
2898 }
2899 
2900 __bpf_kfunc void bpf_task_release_dtor(void *p)
2901 {
2902 	put_task_struct_rcu_user(p);
2903 }
2904 CFI_NOSEAL(bpf_task_release_dtor);
2905 
2906 #ifdef CONFIG_CGROUPS
2907 /**
2908  * bpf_cgroup_acquire - Acquire a reference to a cgroup. A cgroup acquired by
2909  * this kfunc which is not stored in a map as a kptr, must be released by
2910  * calling bpf_cgroup_release().
2911  * @cgrp: The cgroup on which a reference is being acquired.
2912  */
2913 __bpf_kfunc struct cgroup *bpf_cgroup_acquire(struct cgroup *cgrp)
2914 {
2915 	return cgroup_tryget(cgrp) ? cgrp : NULL;
2916 }
2917 
2918 /**
2919  * bpf_cgroup_release - Release the reference acquired on a cgroup.
2920  * If this kfunc is invoked in an RCU read region, the cgroup is guaranteed to
2921  * not be freed until the current grace period has ended, even if its refcount
2922  * drops to 0.
2923  * @cgrp: The cgroup on which a reference is being released.
2924  */
2925 __bpf_kfunc void bpf_cgroup_release(struct cgroup *cgrp)
2926 {
2927 	cgroup_put(cgrp);
2928 }
2929 
2930 __bpf_kfunc void bpf_cgroup_release_dtor(void *cgrp)
2931 {
2932 	cgroup_put(cgrp);
2933 }
2934 CFI_NOSEAL(bpf_cgroup_release_dtor);
2935 
2936 /**
2937  * bpf_cgroup_ancestor - Perform a lookup on an entry in a cgroup's ancestor
2938  * array. A cgroup returned by this kfunc which is not subsequently stored in a
2939  * map, must be released by calling bpf_cgroup_release().
2940  * @cgrp: The cgroup for which we're performing a lookup.
2941  * @level: The level of ancestor to look up.
2942  */
2943 __bpf_kfunc struct cgroup *bpf_cgroup_ancestor(struct cgroup *cgrp, int level)
2944 {
2945 	struct cgroup *ancestor;
2946 
2947 	if (level > cgrp->level || level < 0)
2948 		return NULL;
2949 
2950 	/* cgrp's refcnt could be 0 here, but ancestors can still be accessed */
2951 	ancestor = cgrp->ancestors[level];
2952 	if (!cgroup_tryget(ancestor))
2953 		return NULL;
2954 	return ancestor;
2955 }
2956 
2957 /**
2958  * bpf_cgroup_from_id - Find a cgroup from its ID. A cgroup returned by this
2959  * kfunc which is not subsequently stored in a map, must be released by calling
2960  * bpf_cgroup_release().
2961  * @cgid: cgroup id.
2962  */
2963 __bpf_kfunc struct cgroup *bpf_cgroup_from_id(u64 cgid)
2964 {
2965 	struct cgroup *cgrp;
2966 
2967 	cgrp = __cgroup_get_from_id(cgid);
2968 	if (IS_ERR(cgrp))
2969 		return NULL;
2970 	return cgrp;
2971 }
2972 
2973 /**
2974  * bpf_task_under_cgroup - wrap task_under_cgroup_hierarchy() as a kfunc, test
2975  * task's membership of cgroup ancestry.
2976  * @task: the task to be tested
2977  * @ancestor: possible ancestor of @task's cgroup
2978  *
2979  * Tests whether @task's default cgroup hierarchy is a descendant of @ancestor.
2980  * It follows all the same rules as cgroup_is_descendant, and only applies
2981  * to the default hierarchy.
2982  */
2983 __bpf_kfunc long bpf_task_under_cgroup(struct task_struct *task,
2984 				       struct cgroup *ancestor)
2985 {
2986 	long ret;
2987 
2988 	rcu_read_lock();
2989 	ret = task_under_cgroup_hierarchy(task, ancestor);
2990 	rcu_read_unlock();
2991 	return ret;
2992 }
2993 
2994 BPF_CALL_2(bpf_current_task_under_cgroup, struct bpf_map *, map, u32, idx)
2995 {
2996 	struct bpf_array *array = container_of(map, struct bpf_array, map);
2997 	struct cgroup *cgrp;
2998 
2999 	if (unlikely(idx >= array->map.max_entries))
3000 		return -E2BIG;
3001 
3002 	cgrp = READ_ONCE(array->ptrs[idx]);
3003 	if (unlikely(!cgrp))
3004 		return -EAGAIN;
3005 
3006 	return task_under_cgroup_hierarchy(current, cgrp);
3007 }
3008 
3009 const struct bpf_func_proto bpf_current_task_under_cgroup_proto = {
3010 	.func           = bpf_current_task_under_cgroup,
3011 	.gpl_only       = false,
3012 	.ret_type       = RET_INTEGER,
3013 	.arg1_type      = ARG_CONST_MAP_PTR,
3014 	.arg2_type      = ARG_ANYTHING,
3015 };
3016 
3017 /**
3018  * bpf_task_get_cgroup1 - Acquires the associated cgroup of a task within a
3019  * specific cgroup1 hierarchy. The cgroup1 hierarchy is identified by its
3020  * hierarchy ID.
3021  * @task: The target task
3022  * @hierarchy_id: The ID of a cgroup1 hierarchy
3023  *
3024  * On success, the cgroup is returen. On failure, NULL is returned.
3025  */
3026 __bpf_kfunc struct cgroup *
3027 bpf_task_get_cgroup1(struct task_struct *task, int hierarchy_id)
3028 {
3029 	struct cgroup *cgrp = task_get_cgroup1(task, hierarchy_id);
3030 
3031 	if (IS_ERR(cgrp))
3032 		return NULL;
3033 	return cgrp;
3034 }
3035 #endif /* CONFIG_CGROUPS */
3036 
3037 /**
3038  * bpf_task_from_pid - Find a struct task_struct from its pid by looking it up
3039  * in the root pid namespace idr. If a task is returned, it must either be
3040  * stored in a map, or released with bpf_task_release().
3041  * @pid: The pid of the task being looked up.
3042  */
3043 __bpf_kfunc struct task_struct *bpf_task_from_pid(s32 pid)
3044 {
3045 	struct task_struct *p;
3046 
3047 	rcu_read_lock();
3048 	p = find_task_by_pid_ns(pid, &init_pid_ns);
3049 	if (p)
3050 		p = bpf_task_acquire(p);
3051 	rcu_read_unlock();
3052 
3053 	return p;
3054 }
3055 
3056 /**
3057  * bpf_task_from_vpid - Find a struct task_struct from its vpid by looking it up
3058  * in the pid namespace of the current task. If a task is returned, it must
3059  * either be stored in a map, or released with bpf_task_release().
3060  * @vpid: The vpid of the task being looked up.
3061  */
3062 __bpf_kfunc struct task_struct *bpf_task_from_vpid(s32 vpid)
3063 {
3064 	struct task_struct *p;
3065 
3066 	guard(rcu)();
3067 	if (!task_active_pid_ns(current))
3068 		return NULL;
3069 
3070 	p = find_task_by_vpid(vpid);
3071 	if (p)
3072 		p = bpf_task_acquire(p);
3073 
3074 	return p;
3075 }
3076 
3077 /**
3078  * bpf_dynptr_slice() - Obtain a read-only pointer to the dynptr data.
3079  * @p: The dynptr whose data slice to retrieve
3080  * @offset: Offset into the dynptr
3081  * @buffer__nullable: User-provided buffer to copy contents into.  May be NULL
3082  * @buffer__szk: Size (in bytes) of the buffer if present. This is the
3083  *               length of the requested slice. This must be a constant.
3084  *
3085  * For non-skb and non-xdp type dynptrs, there is no difference between
3086  * bpf_dynptr_slice and bpf_dynptr_data.
3087  *
3088  *  If buffer__nullable is NULL, the call will fail if buffer_opt was needed.
3089  *
3090  * If the intention is to write to the data slice, please use
3091  * bpf_dynptr_slice_rdwr.
3092  *
3093  * The user must check that the returned pointer is not null before using it.
3094  *
3095  * Please note that in the case of skb and xdp dynptrs, bpf_dynptr_slice
3096  * does not change the underlying packet data pointers, so a call to
3097  * bpf_dynptr_slice will not invalidate any ctx->data/data_end pointers in
3098  * the bpf program.
3099  *
3100  * Please also note that when the buffer is on the stack, the verifier invalidates
3101  * the returned pointer when the program stores to the buffer (helpers and kfuncs
3102  * may fill it), or returns from the function that has it.
3103  *
3104  * Return: NULL if the call failed (eg invalid dynptr), pointer to a read-only
3105  * data slice (can be either direct pointer to the data or a pointer to the user
3106  * provided buffer, with its contents containing the data, if unable to obtain
3107  * direct pointer)
3108  */
3109 __bpf_kfunc void *bpf_dynptr_slice(const struct bpf_dynptr *p, u64 offset,
3110 				   void *buffer__nullable, u64 buffer__szk)
3111 {
3112 	const struct bpf_dynptr_kern *ptr = (struct bpf_dynptr_kern *)p;
3113 	enum bpf_dynptr_type type;
3114 	u64 len = buffer__szk;
3115 	int err;
3116 
3117 	if (!ptr->data)
3118 		return NULL;
3119 
3120 	err = bpf_dynptr_check_off_len(ptr, offset, len);
3121 	if (err)
3122 		return NULL;
3123 
3124 	type = bpf_dynptr_get_type(ptr);
3125 
3126 	switch (type) {
3127 	case BPF_DYNPTR_TYPE_LOCAL:
3128 	case BPF_DYNPTR_TYPE_RINGBUF:
3129 		return ptr->data + ptr->offset + offset;
3130 	case BPF_DYNPTR_TYPE_SKB:
3131 		if (buffer__nullable)
3132 			return skb_header_pointer(ptr->data, ptr->offset + offset, len, buffer__nullable);
3133 		else
3134 			return skb_pointer_if_linear(ptr->data, ptr->offset + offset, len);
3135 	case BPF_DYNPTR_TYPE_XDP:
3136 	{
3137 		void *xdp_ptr = bpf_xdp_pointer(ptr->data, ptr->offset + offset, len);
3138 		if (!IS_ERR_OR_NULL(xdp_ptr))
3139 			return xdp_ptr;
3140 
3141 		if (!buffer__nullable)
3142 			return NULL;
3143 		bpf_xdp_copy_buf(ptr->data, ptr->offset + offset, buffer__nullable, len, false);
3144 		return buffer__nullable;
3145 	}
3146 	case BPF_DYNPTR_TYPE_SKB_META:
3147 		return bpf_skb_meta_pointer(ptr->data, ptr->offset + offset);
3148 	case BPF_DYNPTR_TYPE_FILE:
3149 		err = bpf_file_fetch_bytes(ptr->data, offset, buffer__nullable, buffer__szk);
3150 		return err ? NULL : buffer__nullable;
3151 	default:
3152 		WARN_ONCE(true, "unknown dynptr type %d\n", type);
3153 		return NULL;
3154 	}
3155 }
3156 
3157 /**
3158  * bpf_dynptr_slice_rdwr() - Obtain a writable pointer to the dynptr data.
3159  * @p: The dynptr whose data slice to retrieve
3160  * @offset: Offset into the dynptr
3161  * @buffer__nullable: User-provided buffer to copy contents into. May be NULL
3162  * @buffer__szk: Size (in bytes) of the buffer if present. This is the
3163  *               length of the requested slice. This must be a constant.
3164  *
3165  * For non-skb and non-xdp type dynptrs, there is no difference between
3166  * bpf_dynptr_slice and bpf_dynptr_data.
3167  *
3168  * If buffer__nullable is NULL, the call will fail if buffer_opt was needed.
3169  *
3170  * The returned pointer is writable and may point to either directly the dynptr
3171  * data at the requested offset or to the buffer if unable to obtain a direct
3172  * data pointer to (example: the requested slice is to the paged area of an skb
3173  * packet). In the case where the returned pointer is to the buffer, the user
3174  * is responsible for persisting writes through calling bpf_dynptr_write(). This
3175  * usually looks something like this pattern:
3176  *
3177  * struct eth_hdr *eth = bpf_dynptr_slice_rdwr(&dynptr, 0, buffer, sizeof(buffer));
3178  * if (!eth)
3179  *	return TC_ACT_SHOT;
3180  *
3181  * // mutate eth header //
3182  *
3183  * if (eth == buffer)
3184  *	bpf_dynptr_write(&ptr, 0, buffer, sizeof(buffer), 0);
3185  *
3186  * Please note that, as in the example above, the user must check that the
3187  * returned pointer is not null before using it.
3188  *
3189  * Please also note that when the buffer is on the stack, the verifier invalidates
3190  * the returned pointer when the program stores to the buffer (helpers and kfuncs
3191  * may fill it), or returns from the function that has it. Change the data through
3192  * the returned pointer, and before the comparison with the buffer, as in the
3193  * example above: after it the compiler may use one pointer in place of the other.
3194  *
3195  * Please also note that in the case of skb and xdp dynptrs, bpf_dynptr_slice_rdwr
3196  * does not change the underlying packet data pointers, so a call to
3197  * bpf_dynptr_slice_rdwr will not invalidate any ctx->data/data_end pointers in
3198  * the bpf program.
3199  *
3200  * Return: NULL if the call failed (eg invalid dynptr), pointer to a
3201  * data slice (can be either direct pointer to the data or a pointer to the user
3202  * provided buffer, with its contents containing the data, if unable to obtain
3203  * direct pointer)
3204  */
3205 __bpf_kfunc void *bpf_dynptr_slice_rdwr(const struct bpf_dynptr *p, u64 offset,
3206 					void *buffer__nullable, u64 buffer__szk)
3207 {
3208 	const struct bpf_dynptr_kern *ptr = (struct bpf_dynptr_kern *)p;
3209 
3210 	if (!ptr->data || __bpf_dynptr_is_rdonly(ptr))
3211 		return NULL;
3212 
3213 	/* bpf_dynptr_slice_rdwr is the same logic as bpf_dynptr_slice.
3214 	 *
3215 	 * For skb-type dynptrs, it is safe to write into the returned pointer
3216 	 * if the bpf program allows skb data writes. There are two possibilities
3217 	 * that may occur when calling bpf_dynptr_slice_rdwr:
3218 	 *
3219 	 * 1) The requested slice is in the head of the skb. In this case, the
3220 	 * returned pointer is directly to skb data, and if the skb is cloned, the
3221 	 * verifier will have uncloned it (see bpf_unclone_prologue()) already.
3222 	 * The pointer can be directly written into.
3223 	 *
3224 	 * 2) Some portion of the requested slice is in the paged buffer area.
3225 	 * In this case, the requested data will be copied out into the buffer
3226 	 * and the returned pointer will be a pointer to the buffer. The skb
3227 	 * will not be pulled. To persist the write, the user will need to call
3228 	 * bpf_dynptr_write(), which will pull the skb and commit the write.
3229 	 *
3230 	 * Similarly for xdp programs, if the requested slice is not across xdp
3231 	 * fragments, then a direct pointer will be returned, otherwise the data
3232 	 * will be copied out into the buffer and the user will need to call
3233 	 * bpf_dynptr_write() to commit changes.
3234 	 */
3235 	return bpf_dynptr_slice(p, offset, buffer__nullable, buffer__szk);
3236 }
3237 
3238 __bpf_kfunc int bpf_dynptr_adjust(struct bpf_dynptr *p, u64 start, u64 end)
3239 {
3240 	struct bpf_dynptr_kern *ptr = (struct bpf_dynptr_kern *)p;
3241 	u64 size;
3242 
3243 	if (!ptr->data || start > end)
3244 		return -EINVAL;
3245 
3246 	size = __bpf_dynptr_size(ptr);
3247 
3248 	if (start > size || end > size)
3249 		return -ERANGE;
3250 
3251 	bpf_dynptr_advance_offset(ptr, start);
3252 	bpf_dynptr_set_size(ptr, end - start);
3253 
3254 	return 0;
3255 }
3256 
3257 __bpf_kfunc bool bpf_dynptr_is_null(const struct bpf_dynptr *p)
3258 {
3259 	const struct bpf_dynptr_kern *ptr = (struct bpf_dynptr_kern *)p;
3260 
3261 	return !ptr->data;
3262 }
3263 
3264 __bpf_kfunc bool bpf_dynptr_is_rdonly(const struct bpf_dynptr *p)
3265 {
3266 	const struct bpf_dynptr_kern *ptr = (struct bpf_dynptr_kern *)p;
3267 
3268 	if (!ptr->data)
3269 		return false;
3270 
3271 	return __bpf_dynptr_is_rdonly(ptr);
3272 }
3273 
3274 __bpf_kfunc u64 bpf_dynptr_size(const struct bpf_dynptr *p)
3275 {
3276 	const struct bpf_dynptr_kern *ptr = (struct bpf_dynptr_kern *)p;
3277 
3278 	if (!ptr->data)
3279 		return -EINVAL;
3280 
3281 	return __bpf_dynptr_size(ptr);
3282 }
3283 
3284 __bpf_kfunc int bpf_dynptr_clone(const struct bpf_dynptr *p,
3285 				 struct bpf_dynptr *clone__uninit)
3286 {
3287 	struct bpf_dynptr_kern *clone = (struct bpf_dynptr_kern *)clone__uninit;
3288 	const struct bpf_dynptr_kern *ptr = (struct bpf_dynptr_kern *)p;
3289 
3290 	if (!ptr->data) {
3291 		bpf_dynptr_set_null(clone);
3292 		return -EINVAL;
3293 	}
3294 
3295 	*clone = *ptr;
3296 
3297 	return 0;
3298 }
3299 
3300 /**
3301  * bpf_dynptr_copy() - Copy data from one dynptr to another.
3302  * @dst_ptr: Destination dynptr - where data should be copied to
3303  * @dst_off: Offset into the destination dynptr
3304  * @src_ptr: Source dynptr - where data should be copied from
3305  * @src_off: Offset into the source dynptr
3306  * @size: Length of the data to copy from source to destination
3307  *
3308  * Copies data from source dynptr to destination dynptr.
3309  * Returns 0 on success; negative error, otherwise.
3310  */
3311 __bpf_kfunc int bpf_dynptr_copy(const struct bpf_dynptr *dst_ptr, u64 dst_off,
3312 				const struct bpf_dynptr *src_ptr, u64 src_off, u64 size)
3313 {
3314 	const struct bpf_dynptr_kern *dst = (struct bpf_dynptr_kern *)dst_ptr;
3315 	const struct bpf_dynptr_kern *src = (struct bpf_dynptr_kern *)src_ptr;
3316 	bool same = src->data == dst->data;
3317 	void *src_slice, *dst_slice;
3318 	char buf[256];
3319 	bool rev;
3320 	u64 off;
3321 
3322 	src_slice = bpf_dynptr_slice(src_ptr, src_off, NULL, size);
3323 	dst_slice = bpf_dynptr_slice_rdwr(dst_ptr, dst_off, NULL, size);
3324 
3325 	if (src_slice && dst_slice) {
3326 		memmove(dst_slice, src_slice, size);
3327 		return 0;
3328 	}
3329 
3330 	/* The other range is copied piece by piece. A slice of the same packet
3331 	 * may overlap with it, so it cannot be the buffer for that.
3332 	 */
3333 	if (src_slice && !same)
3334 		return __bpf_dynptr_write(dst, dst_off, src_slice, size, 0);
3335 
3336 	if (dst_slice && !same)
3337 		return __bpf_dynptr_read(dst_slice, size, src, src_off, 0);
3338 
3339 	if (bpf_dynptr_check_off_len(dst, dst_off, size) ||
3340 	    bpf_dynptr_check_off_len(src, src_off, size))
3341 		return -E2BIG;
3342 
3343 	/* like memmove(): from the end if the destination is above the source */
3344 	rev = same && dst->offset + dst_off > src->offset + src_off;
3345 	off = 0;
3346 	while (off < size) {
3347 		u64 chunk_sz = min_t(u64, sizeof(buf), size - off);
3348 		u64 pos = rev ? size - off - chunk_sz : off;
3349 		int err;
3350 
3351 		err = __bpf_dynptr_read(buf, chunk_sz, src, src_off + pos, 0);
3352 		if (err)
3353 			return err;
3354 		err = __bpf_dynptr_write(dst, dst_off + pos, buf, chunk_sz, 0);
3355 		if (err)
3356 			return err;
3357 
3358 		off += chunk_sz;
3359 	}
3360 	return 0;
3361 }
3362 
3363 /**
3364  * bpf_dynptr_memset() - Fill dynptr memory with a constant byte.
3365  * @p: Destination dynptr - where data will be filled
3366  * @offset: Offset into the dynptr to start filling from
3367  * @size: Number of bytes to fill
3368  * @val: Constant byte to fill the memory with
3369  *
3370  * Fills the @size bytes of the memory area pointed to by @p
3371  * at @offset with the constant byte @val.
3372  * Returns 0 on success; negative error, otherwise.
3373  */
3374 __bpf_kfunc int bpf_dynptr_memset(const struct bpf_dynptr *p, u64 offset, u64 size, u8 val)
3375 {
3376 	const struct bpf_dynptr_kern *ptr = (struct bpf_dynptr_kern *)p;
3377 	u64 chunk_sz, write_off;
3378 	char buf[256];
3379 	void* slice;
3380 	int err;
3381 
3382 	slice = bpf_dynptr_slice_rdwr(p, offset, NULL, size);
3383 	if (likely(slice)) {
3384 		memset(slice, val, size);
3385 		return 0;
3386 	}
3387 
3388 	if (__bpf_dynptr_is_rdonly(ptr))
3389 		return -EINVAL;
3390 
3391 	err = bpf_dynptr_check_off_len(ptr, offset, size);
3392 	if (err)
3393 		return err;
3394 
3395 	/* Non-linear data under the dynptr, write from a local buffer */
3396 	chunk_sz = min_t(u64, sizeof(buf), size);
3397 	memset(buf, val, chunk_sz);
3398 
3399 	for (write_off = 0; write_off < size; write_off += chunk_sz) {
3400 		chunk_sz = min_t(u64, sizeof(buf), size - write_off);
3401 		err = __bpf_dynptr_write(ptr, offset + write_off, buf, chunk_sz, 0);
3402 		if (err)
3403 			return err;
3404 	}
3405 
3406 	return 0;
3407 }
3408 
3409 __bpf_kfunc void *bpf_cast_to_kern_ctx(void *obj)
3410 {
3411 	return obj;
3412 }
3413 
3414 __bpf_kfunc void *bpf_rdonly_cast(const void *obj__ign, u32 btf_id__k)
3415 {
3416 	return (void *)obj__ign;
3417 }
3418 
3419 __bpf_kfunc void bpf_rcu_read_lock(void)
3420 {
3421 	rcu_read_lock();
3422 }
3423 
3424 __bpf_kfunc void bpf_rcu_read_unlock(void)
3425 {
3426 	rcu_read_unlock();
3427 }
3428 
3429 struct bpf_throw_ctx {
3430 	struct bpf_prog_aux *aux;
3431 	u64 sp;
3432 	u64 bp;
3433 	int cnt;
3434 };
3435 
3436 static bool bpf_stack_walker(void *cookie, u64 ip, u64 sp, u64 bp)
3437 {
3438 	struct bpf_throw_ctx *ctx = cookie;
3439 	struct bpf_prog *prog;
3440 
3441 	/*
3442 	 * The RCU read lock is held to safely traverse the latch tree, but we
3443 	 * don't need its protection when accessing the prog, since it has an
3444 	 * active stack frame on the current stack trace, and won't disappear.
3445 	 */
3446 	rcu_read_lock();
3447 	prog = bpf_prog_ksym_find(ip);
3448 	rcu_read_unlock();
3449 	if (!prog)
3450 		return !ctx->cnt;
3451 	ctx->cnt++;
3452 	if (bpf_is_subprog(prog))
3453 		return true;
3454 	ctx->aux = prog->aux;
3455 	ctx->sp = sp;
3456 	ctx->bp = bp;
3457 	return false;
3458 }
3459 
3460 __bpf_kfunc void bpf_throw(u64 cookie)
3461 {
3462 	struct bpf_throw_ctx ctx = {};
3463 
3464 	arch_bpf_stack_walk(bpf_stack_walker, &ctx);
3465 	WARN_ON_ONCE(!ctx.aux);
3466 	if (ctx.aux)
3467 		WARN_ON_ONCE(!ctx.aux->exception_boundary);
3468 	WARN_ON_ONCE(!ctx.bp);
3469 	WARN_ON_ONCE(!ctx.cnt);
3470 	/*
3471 	 * Prevent KASAN false positives for CONFIG_KASAN_STACK by unpoisoning
3472 	 * deeper stack depths than ctx.sp as we do not return from bpf_throw,
3473 	 * which skips compiler generated instrumentation to do the same. Some
3474 	 * architectures cannot recover sp while unwinding, so fall back to bp.
3475 	 */
3476 	kasan_unpoison_task_stack_below((void *)(long)(ctx.sp ?: ctx.bp));
3477 	ctx.aux->bpf_exception_cb(cookie, ctx.sp + ctx.aux->stack_arg_sp_adjust, ctx.bp, 0, 0);
3478 	WARN(1, "A call to BPF exception callback should never return\n");
3479 }
3480 
3481 __bpf_kfunc int bpf_wq_init(struct bpf_wq *wq, void *p__const_map, unsigned int flags)
3482 {
3483 	struct bpf_async_kern *async = (struct bpf_async_kern *)wq;
3484 	struct bpf_map *map = p__const_map;
3485 
3486 	BUILD_BUG_ON(sizeof(struct bpf_async_kern) > sizeof(struct bpf_wq));
3487 	BUILD_BUG_ON(__alignof__(struct bpf_async_kern) != __alignof__(struct bpf_wq));
3488 
3489 	if (flags)
3490 		return -EINVAL;
3491 
3492 	return __bpf_async_init(async, map, flags, BPF_ASYNC_TYPE_WQ);
3493 }
3494 
3495 __bpf_kfunc int bpf_wq_start(struct bpf_wq *wq, unsigned int flags)
3496 {
3497 	struct bpf_async_kern *async = (struct bpf_async_kern *)wq;
3498 	struct bpf_work *w;
3499 
3500 	if (flags)
3501 		return -EINVAL;
3502 
3503 	w = READ_ONCE(async->work);
3504 	if (!w || !READ_ONCE(w->cb.prog))
3505 		return -EINVAL;
3506 
3507 	if (!refcount_inc_not_zero(&w->cb.refcnt))
3508 		return -ENOENT;
3509 
3510 	if (!defer_timer_wq_op()) {
3511 		schedule_work(&w->work);
3512 		bpf_async_refcount_put(&w->cb);
3513 		return 0;
3514 	} else {
3515 		return bpf_async_schedule_op(&w->cb, BPF_ASYNC_START, 0, 0);
3516 	}
3517 }
3518 
3519 __bpf_kfunc int bpf_wq_set_callback(struct bpf_wq *wq,
3520 				    int (callback_fn)(void *map, int *key, void *value),
3521 				    unsigned int flags,
3522 				    struct bpf_prog_aux *aux)
3523 {
3524 	struct bpf_async_kern *async = (struct bpf_async_kern *)wq;
3525 
3526 	if (flags)
3527 		return -EINVAL;
3528 
3529 	return __bpf_async_set_callback(async, callback_fn, aux->prog);
3530 }
3531 
3532 __bpf_kfunc void bpf_preempt_disable(void)
3533 {
3534 	preempt_disable();
3535 }
3536 
3537 __bpf_kfunc void bpf_preempt_enable(void)
3538 {
3539 	preempt_enable();
3540 }
3541 
3542 struct bpf_iter_bits {
3543 	__u64 __opaque[2];
3544 } __aligned(8);
3545 
3546 #define BITS_ITER_NR_WORDS_MAX 511
3547 
3548 struct bpf_iter_bits_kern {
3549 	union {
3550 		__u64 *bits;
3551 		__u64 bits_copy;
3552 	};
3553 	int nr_bits;
3554 	int bit;
3555 } __aligned(8);
3556 
3557 /* On 64-bit hosts, unsigned long and u64 have the same size, so passing
3558  * a u64 pointer and an unsigned long pointer to find_next_bit() will
3559  * return the same result, as both point to the same 8-byte area.
3560  *
3561  * For 32-bit little-endian hosts, using a u64 pointer or unsigned long
3562  * pointer also makes no difference. This is because the first iterated
3563  * unsigned long is composed of bits 0-31 of the u64 and the second unsigned
3564  * long is composed of bits 32-63 of the u64.
3565  *
3566  * However, for 32-bit big-endian hosts, this is not the case. The first
3567  * iterated unsigned long will be bits 32-63 of the u64, so swap these two
3568  * ulong values within the u64.
3569  */
3570 static void swap_ulong_in_u64(u64 *bits, unsigned int nr)
3571 {
3572 #if (BITS_PER_LONG == 32) && defined(__BIG_ENDIAN)
3573 	unsigned int i;
3574 
3575 	for (i = 0; i < nr; i++)
3576 		bits[i] = (bits[i] >> 32) | ((u64)(u32)bits[i] << 32);
3577 #endif
3578 }
3579 
3580 /**
3581  * bpf_iter_bits_new() - Initialize a new bits iterator for a given memory area
3582  * @it: The new bpf_iter_bits to be created
3583  * @unsafe_ptr__ign: A pointer pointing to a memory area to be iterated over
3584  * @nr_words: The size of the specified memory area, measured in 8-byte units.
3585  * The maximum value of @nr_words is @BITS_ITER_NR_WORDS_MAX. This limit may be
3586  * further reduced by the BPF memory allocator implementation.
3587  *
3588  * This function initializes a new bpf_iter_bits structure for iterating over
3589  * a memory area which is specified by the @unsafe_ptr__ign and @nr_words. It
3590  * copies the data of the memory area to the newly created bpf_iter_bits @it for
3591  * subsequent iteration operations.
3592  *
3593  * On success, 0 is returned. On failure, ERR is returned.
3594  */
3595 __bpf_kfunc int
3596 bpf_iter_bits_new(struct bpf_iter_bits *it, const u64 *unsafe_ptr__ign, u32 nr_words)
3597 {
3598 	struct bpf_iter_bits_kern *kit = (void *)it;
3599 	u32 nr_bytes = nr_words * sizeof(u64);
3600 	u32 nr_bits = BYTES_TO_BITS(nr_bytes);
3601 	int err;
3602 
3603 	BUILD_BUG_ON(sizeof(struct bpf_iter_bits_kern) != sizeof(struct bpf_iter_bits));
3604 	BUILD_BUG_ON(__alignof__(struct bpf_iter_bits_kern) !=
3605 		     __alignof__(struct bpf_iter_bits));
3606 
3607 	kit->nr_bits = 0;
3608 	kit->bits_copy = 0;
3609 	kit->bit = -1;
3610 
3611 	if (!unsafe_ptr__ign || !nr_words)
3612 		return -EINVAL;
3613 	if (nr_words > BITS_ITER_NR_WORDS_MAX)
3614 		return -E2BIG;
3615 
3616 	/* Optimization for u64 mask */
3617 	if (nr_bits == 64) {
3618 		err = bpf_probe_read_kernel_common(&kit->bits_copy, nr_bytes, unsafe_ptr__ign);
3619 		if (err)
3620 			return -EFAULT;
3621 
3622 		swap_ulong_in_u64(&kit->bits_copy, nr_words);
3623 
3624 		kit->nr_bits = nr_bits;
3625 		return 0;
3626 	}
3627 
3628 	if (bpf_mem_alloc_check_size(false, nr_bytes))
3629 		return -E2BIG;
3630 
3631 	/* Fallback to memalloc */
3632 	kit->bits = bpf_mem_alloc(&bpf_global_ma, nr_bytes);
3633 	if (!kit->bits)
3634 		return -ENOMEM;
3635 
3636 	err = bpf_probe_read_kernel_common(kit->bits, nr_bytes, unsafe_ptr__ign);
3637 	if (err) {
3638 		bpf_mem_free(&bpf_global_ma, kit->bits);
3639 		return err;
3640 	}
3641 
3642 	swap_ulong_in_u64(kit->bits, nr_words);
3643 
3644 	kit->nr_bits = nr_bits;
3645 	return 0;
3646 }
3647 
3648 /**
3649  * bpf_iter_bits_next() - Get the next bit in a bpf_iter_bits
3650  * @it: The bpf_iter_bits to be checked
3651  *
3652  * This function returns a pointer to a number representing the value of the
3653  * next bit in the bits.
3654  *
3655  * If there are no further bits available, it returns NULL.
3656  */
3657 __bpf_kfunc int *bpf_iter_bits_next(struct bpf_iter_bits *it)
3658 {
3659 	struct bpf_iter_bits_kern *kit = (void *)it;
3660 	int bit = kit->bit, nr_bits = kit->nr_bits;
3661 	const void *bits;
3662 
3663 	if (!nr_bits || bit >= nr_bits)
3664 		return NULL;
3665 
3666 	bits = nr_bits == 64 ? &kit->bits_copy : kit->bits;
3667 	bit = find_next_bit(bits, nr_bits, bit + 1);
3668 	if (bit >= nr_bits) {
3669 		kit->bit = bit;
3670 		return NULL;
3671 	}
3672 
3673 	kit->bit = bit;
3674 	return &kit->bit;
3675 }
3676 
3677 /**
3678  * bpf_iter_bits_destroy() - Destroy a bpf_iter_bits
3679  * @it: The bpf_iter_bits to be destroyed
3680  *
3681  * Destroy the resource associated with the bpf_iter_bits.
3682  */
3683 __bpf_kfunc void bpf_iter_bits_destroy(struct bpf_iter_bits *it)
3684 {
3685 	struct bpf_iter_bits_kern *kit = (void *)it;
3686 
3687 	if (kit->nr_bits <= 64)
3688 		return;
3689 	bpf_mem_free(&bpf_global_ma, kit->bits);
3690 }
3691 
3692 /**
3693  * bpf_copy_from_user_str() - Copy a string from an unsafe user address
3694  * @dst:             Destination address, in kernel space.  This buffer must be
3695  *                   at least @dst__sz bytes long.
3696  * @dst__sz:         Maximum number of bytes to copy, includes the trailing NUL.
3697  * @unsafe_ptr__ign: Source address, in user space.
3698  * @flags:           The only supported flag is BPF_F_PAD_ZEROS
3699  *
3700  * Copies a NUL-terminated string from userspace to BPF space. If user string is
3701  * too long this will still ensure zero termination in the dst buffer unless
3702  * buffer size is 0.
3703  *
3704  * If BPF_F_PAD_ZEROS flag is set, memset the tail of @dst to 0 on success and
3705  * memset all of @dst on failure.
3706  */
3707 __bpf_kfunc int bpf_copy_from_user_str(void *dst, u32 dst__sz, const void __user *unsafe_ptr__ign, u64 flags)
3708 {
3709 	int ret;
3710 
3711 	if (unlikely(flags & ~BPF_F_PAD_ZEROS))
3712 		return -EINVAL;
3713 
3714 	if (unlikely(!dst__sz))
3715 		return 0;
3716 
3717 	ret = strncpy_from_user(dst, unsafe_ptr__ign, dst__sz - 1);
3718 	if (ret < 0) {
3719 		if (flags & BPF_F_PAD_ZEROS)
3720 			memset((char *)dst, 0, dst__sz);
3721 
3722 		return ret;
3723 	}
3724 
3725 	if (flags & BPF_F_PAD_ZEROS)
3726 		memset((char *)dst + ret, 0, dst__sz - ret);
3727 	else
3728 		((char *)dst)[ret] = '\0';
3729 
3730 	return ret + 1;
3731 }
3732 
3733 /**
3734  * bpf_copy_from_user_mm() - Copy data from an address space
3735  * @dst:             Destination address, in kernel space
3736  * @dst__sz:         Number of bytes to copy
3737  * @unsafe_ptr__ign: Source address in the address space
3738  * @mm:              Address space to copy from
3739  * @flags:           Reserved for future use; must be zero
3740  *
3741  * Copies data from the user address space associated with @mm. The destination
3742  * is zeroed if an attempted copy cannot be completed in full. Unsupported
3743  * flags return -EINVAL without modifying @dst.
3744  *
3745  * Return: 0 on success, -EINVAL if @flags is non-zero, or -EFAULT if @mm is no
3746  * longer active or the copy fails or is partial.
3747  */
3748 __bpf_kfunc int bpf_copy_from_user_mm(void *dst, u32 dst__sz,
3749 				      const void __user *unsafe_ptr__ign,
3750 				      struct mm_struct *mm, u64 flags)
3751 {
3752 	int ret;
3753 
3754 	if (unlikely(flags))
3755 		return -EINVAL;
3756 
3757 	if (unlikely(!dst__sz))
3758 		return 0;
3759 
3760 	if (unlikely(!mmget_not_zero(mm))) {
3761 		memset(dst, 0, dst__sz);
3762 		return -EFAULT;
3763 	}
3764 
3765 	ret = __bpf_copy_from_user_mm(dst, dst__sz, unsafe_ptr__ign, mm);
3766 	mmput(mm);
3767 
3768 	return ret;
3769 }
3770 
3771 /**
3772  * bpf_copy_from_user_mm_str() - Copy a string from an address space
3773  * @dst:             Destination address, in kernel space. This buffer must be
3774  *                   at least @dst__sz bytes long
3775  * @dst__sz:         Maximum number of bytes to copy, including the trailing NUL
3776  * @unsafe_ptr__ign: Source address in the address space
3777  * @mm:              Address space to copy from
3778  * @flags:           The only supported flag is BPF_F_PAD_ZEROS
3779  *
3780  * Copies a NUL-terminated string from the user address space associated with
3781  * @mm. If the string is too long, @dst is still NUL-terminated unless @dst__sz
3782  * is zero.
3783  *
3784  * If the flags are valid and BPF_F_PAD_ZEROS is set, the unused portion of
3785  * @dst is cleared on success and all of @dst is cleared on a copy failure.
3786  * Unsupported flags return -EINVAL without modifying @dst.
3787  *
3788  * Return: The number of copied bytes including the NUL terminator on success,
3789  * -EINVAL if @flags is invalid, or -EFAULT if @mm is no longer active or the
3790  * copy fails.
3791  */
3792 __bpf_kfunc int bpf_copy_from_user_mm_str(void *dst, u32 dst__sz,
3793 					  const void __user *unsafe_ptr__ign,
3794 					  struct mm_struct *mm, u64 flags)
3795 {
3796 	int ret;
3797 
3798 	if (unlikely(flags & ~BPF_F_PAD_ZEROS))
3799 		return -EINVAL;
3800 
3801 	if (unlikely(dst__sz == 0))
3802 		return 0;
3803 
3804 	if (unlikely(!mmget_not_zero(mm))) {
3805 		if (flags & BPF_F_PAD_ZEROS)
3806 			memset(dst, 0, dst__sz);
3807 		else
3808 			*(char *)dst = '\0';
3809 		return -EFAULT;
3810 	}
3811 
3812 	ret = __bpf_copy_from_user_mm_str(dst, dst__sz, unsafe_ptr__ign,
3813 					  mm, flags);
3814 	mmput(mm);
3815 
3816 	return ret;
3817 }
3818 
3819 /**
3820  * bpf_copy_from_user_task_str() - Copy a string from an task's address space
3821  * @dst:             Destination address, in kernel space.  This buffer must be
3822  *                   at least @dst__sz bytes long.
3823  * @dst__sz:         Maximum number of bytes to copy, includes the trailing NUL.
3824  * @unsafe_ptr__ign: Source address in the task's address space.
3825  * @tsk:             The task whose address space will be used
3826  * @flags:           The only supported flag is BPF_F_PAD_ZEROS
3827  *
3828  * Copies a NUL terminated string from a task's address space to @dst__sz
3829  * buffer. If user string is too long this will still ensure zero termination
3830  * in the @dst__sz buffer unless buffer size is 0.
3831  *
3832  * If BPF_F_PAD_ZEROS flag is set, memset the tail of @dst__sz to 0 on success
3833  * and memset all of @dst__sz on failure.
3834  *
3835  * Return: The number of copied bytes on success including the NUL terminator.
3836  * A negative error code on failure.
3837  */
3838 __bpf_kfunc int bpf_copy_from_user_task_str(void *dst, u32 dst__sz,
3839 					    const void __user *unsafe_ptr__ign,
3840 					    struct task_struct *tsk, u64 flags)
3841 {
3842 	struct mm_struct *mm;
3843 	int ret;
3844 
3845 	if (unlikely(flags & ~BPF_F_PAD_ZEROS))
3846 		return -EINVAL;
3847 
3848 	if (unlikely(dst__sz == 0))
3849 		return 0;
3850 
3851 	mm = get_task_mm(tsk);
3852 	if (!mm) {
3853 		if (flags & BPF_F_PAD_ZEROS)
3854 			memset(dst, 0, dst__sz);
3855 		else
3856 			*(char *)dst = '\0';
3857 		return -EFAULT;
3858 	}
3859 
3860 	ret = __bpf_copy_from_user_mm_str(dst, dst__sz, unsafe_ptr__ign,
3861 					  mm, flags);
3862 	mmput(mm);
3863 
3864 	return ret;
3865 }
3866 
3867 /* Keep unsigned long in prototype so that kfunc is usable when emitted to
3868  * vmlinux.h in BPF programs directly, but note that while in BPF prog, the
3869  * unsigned long always points to 8-byte region on stack, the kernel may only
3870  * read and write the 4-bytes on 32-bit.
3871  */
3872 __bpf_kfunc void bpf_local_irq_save(unsigned long *flags__irq_flag)
3873 {
3874 	local_irq_save(*flags__irq_flag);
3875 }
3876 
3877 __bpf_kfunc void bpf_local_irq_restore(unsigned long *flags__irq_flag)
3878 {
3879 	local_irq_restore(*flags__irq_flag);
3880 }
3881 
3882 __bpf_kfunc void __bpf_trap(void)
3883 {
3884 }
3885 
3886 /*
3887  * Kfuncs for string operations.
3888  *
3889  * Since strings are not necessarily %NUL-terminated, we cannot directly call
3890  * in-kernel implementations. Instead, we open-code the implementations using
3891  * __get_kernel_nofault instead of plain dereference to make them safe.
3892  */
3893 
3894 static int __bpf_strncasecmp(const char *s1, const char *s2, bool ignore_case, size_t len)
3895 {
3896 	char c1, c2;
3897 	int i;
3898 
3899 	if (!copy_from_kernel_nofault_allowed(s1, 1) ||
3900 	    !copy_from_kernel_nofault_allowed(s2, 1)) {
3901 		return -ERANGE;
3902 	}
3903 
3904 	guard(pagefault)();
3905 	for (i = 0; i < len && i < XATTR_SIZE_MAX; i++) {
3906 		__get_kernel_nofault(&c1, s1, char, err_out);
3907 		__get_kernel_nofault(&c2, s2, char, err_out);
3908 		if (ignore_case) {
3909 			c1 = tolower(c1);
3910 			c2 = tolower(c2);
3911 		}
3912 		if (c1 != c2)
3913 			return c1 < c2 ? -1 : 1;
3914 		if (c1 == '\0')
3915 			return 0;
3916 		s1++;
3917 		s2++;
3918 	}
3919 	return i == XATTR_SIZE_MAX ? -E2BIG : 0;
3920 err_out:
3921 	return -EFAULT;
3922 }
3923 
3924 /**
3925  * bpf_strcmp - Compare two strings
3926  * @s1__ign: One string
3927  * @s2__ign: Another string
3928  *
3929  * Return:
3930  * * %0       - Strings are equal
3931  * * %-1      - @s1__ign is smaller
3932  * * %1       - @s2__ign is smaller
3933  * * %-EFAULT - Cannot read one of the strings
3934  * * %-E2BIG  - One of strings is too large
3935  * * %-ERANGE - One of strings is outside of kernel address space
3936  */
3937 __bpf_kfunc int bpf_strcmp(const char *s1__ign, const char *s2__ign)
3938 {
3939 	return __bpf_strncasecmp(s1__ign, s2__ign, false, XATTR_SIZE_MAX);
3940 }
3941 
3942 /**
3943  * bpf_strcasecmp - Compare two strings, ignoring the case of the characters
3944  * @s1__ign: One string
3945  * @s2__ign: Another string
3946  *
3947  * Return:
3948  * * %0       - Strings are equal
3949  * * %-1      - @s1__ign is smaller
3950  * * %1       - @s2__ign is smaller
3951  * * %-EFAULT - Cannot read one of the strings
3952  * * %-E2BIG  - One of strings is too large
3953  * * %-ERANGE - One of strings is outside of kernel address space
3954  */
3955 __bpf_kfunc int bpf_strcasecmp(const char *s1__ign, const char *s2__ign)
3956 {
3957 	return __bpf_strncasecmp(s1__ign, s2__ign, true, XATTR_SIZE_MAX);
3958 }
3959 
3960 /*
3961  * bpf_strncasecmp - Compare two length-limited strings, ignoring case
3962  * @s1__ign: One string
3963  * @s2__ign: Another string
3964  * @len: The maximum number of characters to compare
3965  *
3966  * Return:
3967  * * %0       - Strings are equal
3968  * * %-1      - @s1__ign is smaller
3969  * * %1       - @s2__ign is smaller
3970  * * %-EFAULT - Cannot read one of the strings
3971  * * %-E2BIG  - One of strings is too large
3972  * * %-ERANGE - One of strings is outside of kernel address space
3973  */
3974 __bpf_kfunc int bpf_strncasecmp(const char *s1__ign, const char *s2__ign, size_t len)
3975 {
3976 	return __bpf_strncasecmp(s1__ign, s2__ign, true, len);
3977 }
3978 
3979 /**
3980  * bpf_strnchr - Find a character in a length limited string
3981  * @s__ign: The string to be searched
3982  * @count: The number of characters to be searched
3983  * @c: The character to search for
3984  *
3985  * Note that the %NUL-terminator is considered part of the string, and can
3986  * be searched for.
3987  *
3988  * Return:
3989  * * >=0      - Index of the first occurrence of @c within @s__ign
3990  * * %-ENOENT - @c not found in the first @count characters of @s__ign
3991  * * %-EFAULT - Cannot read @s__ign
3992  * * %-E2BIG  - @s__ign is too large
3993  * * %-ERANGE - @s__ign is outside of kernel address space
3994  */
3995 __bpf_kfunc int bpf_strnchr(const char *s__ign, size_t count, char c)
3996 {
3997 	char sc;
3998 	int i;
3999 
4000 	if (!copy_from_kernel_nofault_allowed(s__ign, 1))
4001 		return -ERANGE;
4002 
4003 	guard(pagefault)();
4004 	for (i = 0; i < count && i < XATTR_SIZE_MAX; i++) {
4005 		__get_kernel_nofault(&sc, s__ign, char, err_out);
4006 		if (sc == c)
4007 			return i;
4008 		if (sc == '\0')
4009 			return -ENOENT;
4010 		s__ign++;
4011 	}
4012 	return i == XATTR_SIZE_MAX ? -E2BIG : -ENOENT;
4013 err_out:
4014 	return -EFAULT;
4015 }
4016 
4017 /**
4018  * bpf_strchr - Find the first occurrence of a character in a string
4019  * @s__ign: The string to be searched
4020  * @c: The character to search for
4021  *
4022  * Note that the %NUL-terminator is considered part of the string, and can
4023  * be searched for.
4024  *
4025  * Return:
4026  * * >=0      - The index of the first occurrence of @c within @s__ign
4027  * * %-ENOENT - @c not found in @s__ign
4028  * * %-EFAULT - Cannot read @s__ign
4029  * * %-E2BIG  - @s__ign is too large
4030  * * %-ERANGE - @s__ign is outside of kernel address space
4031  */
4032 __bpf_kfunc int bpf_strchr(const char *s__ign, char c)
4033 {
4034 	return bpf_strnchr(s__ign, XATTR_SIZE_MAX, c);
4035 }
4036 
4037 /**
4038  * bpf_strchrnul - Find and return a character in a string, or end of string
4039  * @s__ign: The string to be searched
4040  * @c: The character to search for
4041  *
4042  * Return:
4043  * * >=0      - Index of the first occurrence of @c within @s__ign or index of
4044  *              the null byte at the end of @s__ign when @c is not found
4045  * * %-EFAULT - Cannot read @s__ign
4046  * * %-E2BIG  - @s__ign is too large
4047  * * %-ERANGE - @s__ign is outside of kernel address space
4048  */
4049 __bpf_kfunc int bpf_strchrnul(const char *s__ign, char c)
4050 {
4051 	char sc;
4052 	int i;
4053 
4054 	if (!copy_from_kernel_nofault_allowed(s__ign, 1))
4055 		return -ERANGE;
4056 
4057 	guard(pagefault)();
4058 	for (i = 0; i < XATTR_SIZE_MAX; i++) {
4059 		__get_kernel_nofault(&sc, s__ign, char, err_out);
4060 		if (sc == '\0' || sc == c)
4061 			return i;
4062 		s__ign++;
4063 	}
4064 	return -E2BIG;
4065 err_out:
4066 	return -EFAULT;
4067 }
4068 
4069 /**
4070  * bpf_strrchr - Find the last occurrence of a character in a string
4071  * @s__ign: The string to be searched
4072  * @c: The character to search for
4073  *
4074  * Return:
4075  * * >=0      - Index of the last occurrence of @c within @s__ign
4076  * * %-ENOENT - @c not found in @s__ign
4077  * * %-EFAULT - Cannot read @s__ign
4078  * * %-E2BIG  - @s__ign is too large
4079  * * %-ERANGE - @s__ign is outside of kernel address space
4080  */
4081 __bpf_kfunc int bpf_strrchr(const char *s__ign, int c)
4082 {
4083 	char sc;
4084 	int i, last = -ENOENT;
4085 
4086 	if (!copy_from_kernel_nofault_allowed(s__ign, 1))
4087 		return -ERANGE;
4088 
4089 	guard(pagefault)();
4090 	for (i = 0; i < XATTR_SIZE_MAX; i++) {
4091 		__get_kernel_nofault(&sc, s__ign, char, err_out);
4092 		if (sc == c)
4093 			last = i;
4094 		if (sc == '\0')
4095 			return last;
4096 		s__ign++;
4097 	}
4098 	return -E2BIG;
4099 err_out:
4100 	return -EFAULT;
4101 }
4102 
4103 /**
4104  * bpf_strnlen - Calculate the length of a length-limited string
4105  * @s__ign: The string
4106  * @count: The maximum number of characters to count
4107  *
4108  * Return:
4109  * * >=0      - The length of @s__ign
4110  * * %-EFAULT - Cannot read @s__ign
4111  * * %-E2BIG  - @s__ign is too large
4112  * * %-ERANGE - @s__ign is outside of kernel address space
4113  */
4114 __bpf_kfunc int bpf_strnlen(const char *s__ign, size_t count)
4115 {
4116 	char c;
4117 	int i;
4118 
4119 	if (!copy_from_kernel_nofault_allowed(s__ign, 1))
4120 		return -ERANGE;
4121 
4122 	guard(pagefault)();
4123 	for (i = 0; i < count && i < XATTR_SIZE_MAX; i++) {
4124 		__get_kernel_nofault(&c, s__ign, char, err_out);
4125 		if (c == '\0')
4126 			return i;
4127 		s__ign++;
4128 	}
4129 	return i == XATTR_SIZE_MAX ? -E2BIG : i;
4130 err_out:
4131 	return -EFAULT;
4132 }
4133 
4134 /**
4135  * bpf_strlen - Calculate the length of a string
4136  * @s__ign: The string
4137  *
4138  * Return:
4139  * * >=0      - The length of @s__ign
4140  * * %-EFAULT - Cannot read @s__ign
4141  * * %-E2BIG  - @s__ign is too large
4142  * * %-ERANGE - @s__ign is outside of kernel address space
4143  */
4144 __bpf_kfunc int bpf_strlen(const char *s__ign)
4145 {
4146 	return bpf_strnlen(s__ign, XATTR_SIZE_MAX);
4147 }
4148 
4149 /**
4150  * bpf_strspn - Calculate the length of the initial substring of @s__ign which
4151  *              only contains letters in @accept__ign
4152  * @s__ign: The string to be searched
4153  * @accept__ign: The string to search for
4154  *
4155  * Return:
4156  * * >=0      - The length of the initial substring of @s__ign which only
4157  *              contains letters from @accept__ign
4158  * * %-EFAULT - Cannot read one of the strings
4159  * * %-E2BIG  - One of the strings is too large
4160  * * %-ERANGE - One of the strings is outside of kernel address space
4161  */
4162 __bpf_kfunc int bpf_strspn(const char *s__ign, const char *accept__ign)
4163 {
4164 	char cs, ca;
4165 	int i, j;
4166 
4167 	if (!copy_from_kernel_nofault_allowed(s__ign, 1) ||
4168 	    !copy_from_kernel_nofault_allowed(accept__ign, 1)) {
4169 		return -ERANGE;
4170 	}
4171 
4172 	guard(pagefault)();
4173 	for (i = 0; i < XATTR_SIZE_MAX; i++) {
4174 		__get_kernel_nofault(&cs, s__ign, char, err_out);
4175 		if (cs == '\0')
4176 			return i;
4177 		for (j = 0; j < XATTR_SIZE_MAX; j++) {
4178 			__get_kernel_nofault(&ca, accept__ign + j, char, err_out);
4179 			if (cs == ca || ca == '\0')
4180 				break;
4181 		}
4182 		if (j == XATTR_SIZE_MAX)
4183 			return -E2BIG;
4184 		if (ca == '\0')
4185 			return i;
4186 		s__ign++;
4187 	}
4188 	return -E2BIG;
4189 err_out:
4190 	return -EFAULT;
4191 }
4192 
4193 /**
4194  * bpf_strcspn - Calculate the length of the initial substring of @s__ign which
4195  *               does not contain letters in @reject__ign
4196  * @s__ign: The string to be searched
4197  * @reject__ign: The string to search for
4198  *
4199  * Return:
4200  * * >=0      - The length of the initial substring of @s__ign which does not
4201  *              contain letters from @reject__ign
4202  * * %-EFAULT - Cannot read one of the strings
4203  * * %-E2BIG  - One of the strings is too large
4204  * * %-ERANGE - One of the strings is outside of kernel address space
4205  */
4206 __bpf_kfunc int bpf_strcspn(const char *s__ign, const char *reject__ign)
4207 {
4208 	char cs, cr;
4209 	int i, j;
4210 
4211 	if (!copy_from_kernel_nofault_allowed(s__ign, 1) ||
4212 	    !copy_from_kernel_nofault_allowed(reject__ign, 1)) {
4213 		return -ERANGE;
4214 	}
4215 
4216 	guard(pagefault)();
4217 	for (i = 0; i < XATTR_SIZE_MAX; i++) {
4218 		__get_kernel_nofault(&cs, s__ign, char, err_out);
4219 		if (cs == '\0')
4220 			return i;
4221 		for (j = 0; j < XATTR_SIZE_MAX; j++) {
4222 			__get_kernel_nofault(&cr, reject__ign + j, char, err_out);
4223 			if (cs == cr || cr == '\0')
4224 				break;
4225 		}
4226 		if (j == XATTR_SIZE_MAX)
4227 			return -E2BIG;
4228 		if (cr != '\0')
4229 			return i;
4230 		s__ign++;
4231 	}
4232 	return -E2BIG;
4233 err_out:
4234 	return -EFAULT;
4235 }
4236 
4237 static int __bpf_strnstr(const char *s1, const char *s2, size_t len,
4238 			 bool ignore_case)
4239 {
4240 	char c1, c2;
4241 	int i, j;
4242 
4243 	if (!copy_from_kernel_nofault_allowed(s1, 1) ||
4244 	    !copy_from_kernel_nofault_allowed(s2, 1)) {
4245 		return -ERANGE;
4246 	}
4247 
4248 	guard(pagefault)();
4249 	for (i = 0; i < XATTR_SIZE_MAX; i++) {
4250 		for (j = 0; i + j <= len && j < XATTR_SIZE_MAX; j++) {
4251 			__get_kernel_nofault(&c2, s2 + j, char, err_out);
4252 			if (c2 == '\0')
4253 				return i;
4254 			/*
4255 			 * We allow reading an extra byte from s2 (note the
4256 			 * `i + j <= len` above) to cover the case when s2 is
4257 			 * a suffix of the first len chars of s1.
4258 			 */
4259 			if (i + j == len)
4260 				break;
4261 			__get_kernel_nofault(&c1, s1 + j, char, err_out);
4262 
4263 			if (ignore_case) {
4264 				c1 = tolower(c1);
4265 				c2 = tolower(c2);
4266 			}
4267 
4268 			if (c1 == '\0')
4269 				return -ENOENT;
4270 			if (c1 != c2)
4271 				break;
4272 		}
4273 		if (j == XATTR_SIZE_MAX)
4274 			return -E2BIG;
4275 		if (i + j == len)
4276 			return -ENOENT;
4277 		s1++;
4278 	}
4279 	return -E2BIG;
4280 err_out:
4281 	return -EFAULT;
4282 }
4283 
4284 /**
4285  * bpf_strstr - Find the first substring in a string
4286  * @s1__ign: The string to be searched
4287  * @s2__ign: The string to search for
4288  *
4289  * Return:
4290  * * >=0      - Index of the first character of the first occurrence of @s2__ign
4291  *              within @s1__ign
4292  * * %-ENOENT - @s2__ign is not a substring of @s1__ign
4293  * * %-EFAULT - Cannot read one of the strings
4294  * * %-E2BIG  - One of the strings is too large
4295  * * %-ERANGE - One of the strings is outside of kernel address space
4296  */
4297 __bpf_kfunc int bpf_strstr(const char *s1__ign, const char *s2__ign)
4298 {
4299 	return __bpf_strnstr(s1__ign, s2__ign, XATTR_SIZE_MAX, false);
4300 }
4301 
4302 /**
4303  * bpf_strcasestr - Find the first substring in a string, ignoring the case of
4304  *                  the characters
4305  * @s1__ign: The string to be searched
4306  * @s2__ign: The string to search for
4307  *
4308  * Return:
4309  * * >=0      - Index of the first character of the first occurrence of @s2__ign
4310  *              within @s1__ign
4311  * * %-ENOENT - @s2__ign is not a substring of @s1__ign
4312  * * %-EFAULT - Cannot read one of the strings
4313  * * %-E2BIG  - One of the strings is too large
4314  * * %-ERANGE - One of the strings is outside of kernel address space
4315  */
4316 __bpf_kfunc int bpf_strcasestr(const char *s1__ign, const char *s2__ign)
4317 {
4318 	return __bpf_strnstr(s1__ign, s2__ign, XATTR_SIZE_MAX, true);
4319 }
4320 
4321 /**
4322  * bpf_strnstr - Find the first substring in a length-limited string
4323  * @s1__ign: The string to be searched
4324  * @s2__ign: The string to search for
4325  * @len: the maximum number of characters to search
4326  *
4327  * Return:
4328  * * >=0      - Index of the first character of the first occurrence of @s2__ign
4329  *              within the first @len characters of @s1__ign
4330  * * %-ENOENT - @s2__ign not found in the first @len characters of @s1__ign
4331  * * %-EFAULT - Cannot read one of the strings
4332  * * %-E2BIG  - One of the strings is too large
4333  * * %-ERANGE - One of the strings is outside of kernel address space
4334  */
4335 __bpf_kfunc int bpf_strnstr(const char *s1__ign, const char *s2__ign,
4336 			    size_t len)
4337 {
4338 	return __bpf_strnstr(s1__ign, s2__ign, len, false);
4339 }
4340 
4341 /**
4342  * bpf_strncasestr - Find the first substring in a length-limited string,
4343  *                   ignoring the case of the characters
4344  * @s1__ign: The string to be searched
4345  * @s2__ign: The string to search for
4346  * @len: the maximum number of characters to search
4347  *
4348  * Return:
4349  * * >=0      - Index of the first character of the first occurrence of @s2__ign
4350  *              within the first @len characters of @s1__ign
4351  * * %-ENOENT - @s2__ign not found in the first @len characters of @s1__ign
4352  * * %-EFAULT - Cannot read one of the strings
4353  * * %-E2BIG  - One of the strings is too large
4354  * * %-ERANGE - One of the strings is outside of kernel address space
4355  */
4356 __bpf_kfunc int bpf_strncasestr(const char *s1__ign, const char *s2__ign,
4357 				size_t len)
4358 {
4359 	return __bpf_strnstr(s1__ign, s2__ign, len, true);
4360 }
4361 
4362 #ifdef CONFIG_KEYS
4363 /**
4364  * bpf_lookup_user_key - lookup a key by its serial
4365  * @serial: key handle serial number
4366  * @flags: lookup-specific flags
4367  *
4368  * Search a key with a given *serial* and the provided *flags*.
4369  * If found, increment the reference count of the key by one, and
4370  * return it in the bpf_key structure.
4371  *
4372  * The bpf_key structure must be passed to bpf_key_put() when done
4373  * with it, so that the key reference count is decremented and the
4374  * bpf_key structure is freed.
4375  *
4376  * Permission checks are deferred to the time the key is used by
4377  * one of the available key-specific kfuncs.
4378  *
4379  * Set *flags* with KEY_LOOKUP_CREATE, to attempt creating a requested
4380  * special keyring (e.g. session keyring), if it doesn't yet exist.
4381  * Set *flags* with KEY_LOOKUP_PARTIAL, to lookup a key without waiting
4382  * for the key construction, and to retrieve uninstantiated keys (keys
4383  * without data attached to them).
4384  *
4385  * Return: a bpf_key pointer with a valid key pointer if the key is found, a
4386  *         NULL pointer otherwise.
4387  */
4388 __bpf_kfunc struct bpf_key *bpf_lookup_user_key(s32 serial, u64 flags)
4389 {
4390 	key_ref_t key_ref;
4391 	struct bpf_key *bkey;
4392 
4393 	if (flags & ~KEY_LOOKUP_ALL)
4394 		return NULL;
4395 
4396 	/*
4397 	 * Permission check is deferred until the key is used, as the
4398 	 * intent of the caller is unknown here.
4399 	 */
4400 	key_ref = lookup_user_key(serial, flags, KEY_DEFER_PERM_CHECK);
4401 	if (IS_ERR(key_ref))
4402 		return NULL;
4403 
4404 	bkey = kmalloc_obj(*bkey);
4405 	if (!bkey) {
4406 		key_put(key_ref_to_ptr(key_ref));
4407 		return NULL;
4408 	}
4409 
4410 	bkey->key = key_ref_to_ptr(key_ref);
4411 	bkey->has_ref = true;
4412 
4413 	return bkey;
4414 }
4415 
4416 /**
4417  * bpf_lookup_system_key - lookup a key by a system-defined ID
4418  * @id: key ID
4419  *
4420  * Obtain a bpf_key structure with a key pointer set to the passed key ID.
4421  * The key pointer is marked as invalid, to prevent bpf_key_put() from
4422  * attempting to decrement the key reference count on that pointer. The key
4423  * pointer set in such way is currently understood only by
4424  * verify_pkcs7_signature().
4425  *
4426  * Set *id* to one of the values defined in include/linux/verification.h:
4427  * 0 for the primary keyring (immutable keyring of system keys);
4428  * VERIFY_USE_SECONDARY_KEYRING for both the primary and secondary keyring
4429  * (where keys can be added only if they are vouched for by existing keys
4430  * in those keyrings); VERIFY_USE_PLATFORM_KEYRING for the platform
4431  * keyring (primarily used by the integrity subsystem to verify a kexec'ed
4432  * kerned image and, possibly, the initramfs signature).
4433  *
4434  * Return: a bpf_key pointer with an invalid key pointer set from the
4435  *         pre-determined ID on success, a NULL pointer otherwise
4436  */
4437 __bpf_kfunc struct bpf_key *bpf_lookup_system_key(u64 id)
4438 {
4439 	struct bpf_key *bkey;
4440 
4441 	if (system_keyring_id_check(id) < 0)
4442 		return NULL;
4443 
4444 	bkey = kmalloc_obj(*bkey, GFP_ATOMIC);
4445 	if (!bkey)
4446 		return NULL;
4447 
4448 	bkey->key = (struct key *)(unsigned long)id;
4449 	bkey->has_ref = false;
4450 
4451 	return bkey;
4452 }
4453 
4454 /**
4455  * bpf_key_put - decrement key reference count if key is valid and free bpf_key
4456  * @bkey: bpf_key structure
4457  *
4458  * Decrement the reference count of the key inside *bkey*, if the pointer
4459  * is valid, and free *bkey*.
4460  */
4461 __bpf_kfunc void bpf_key_put(struct bpf_key *bkey)
4462 {
4463 	if (bkey->has_ref)
4464 		key_put(bkey->key);
4465 
4466 	kfree(bkey);
4467 }
4468 
4469 /**
4470  * bpf_verify_pkcs7_signature - verify a PKCS#7 signature
4471  * @data_p: data to verify
4472  * @sig_p: signature of the data
4473  * @trusted_keyring: keyring with keys trusted for signature verification
4474  *
4475  * Verify the PKCS#7 signature *sig_ptr* against the supplied *data_ptr*
4476  * with keys in a keyring referenced by *trusted_keyring*.
4477  *
4478  * Return: 0 on success, a negative value on error.
4479  */
4480 __bpf_kfunc int bpf_verify_pkcs7_signature(const struct bpf_dynptr *data_p,
4481 			       const struct bpf_dynptr *sig_p,
4482 			       struct bpf_key *trusted_keyring)
4483 {
4484 #ifdef CONFIG_SYSTEM_DATA_VERIFICATION
4485 	const struct bpf_dynptr_kern *data_ptr = (struct bpf_dynptr_kern *)data_p;
4486 	const struct bpf_dynptr_kern *sig_ptr = (struct bpf_dynptr_kern *)sig_p;
4487 	const void *data, *sig;
4488 	u32 data_len, sig_len;
4489 	int ret;
4490 
4491 	if (trusted_keyring->has_ref) {
4492 		/*
4493 		 * Do the permission check deferred in bpf_lookup_user_key().
4494 		 * See bpf_lookup_user_key() for more details.
4495 		 *
4496 		 * A call to key_task_permission() here would be redundant, as
4497 		 * it is already done by keyring_search() called by
4498 		 * find_asymmetric_key().
4499 		 */
4500 		ret = key_validate(trusted_keyring->key);
4501 		if (ret < 0)
4502 			return ret;
4503 	}
4504 
4505 	data_len = __bpf_dynptr_size(data_ptr);
4506 	data = __bpf_dynptr_data(data_ptr, data_len);
4507 	if (!data)
4508 		return -EINVAL;
4509 
4510 	sig_len = __bpf_dynptr_size(sig_ptr);
4511 	sig = __bpf_dynptr_data(sig_ptr, sig_len);
4512 	if (!sig)
4513 		return -EINVAL;
4514 
4515 	return verify_pkcs7_signature(data, data_len, sig, sig_len,
4516 				      trusted_keyring->key,
4517 				      VERIFYING_BPF_SIGNATURE, NULL,
4518 				      NULL);
4519 #else
4520 	return -EOPNOTSUPP;
4521 #endif /* CONFIG_SYSTEM_DATA_VERIFICATION */
4522 }
4523 #endif /* CONFIG_KEYS */
4524 
4525 typedef int (*bpf_task_work_callback_t)(struct bpf_map *map, void *key, void *value);
4526 
4527 enum bpf_task_work_state {
4528 	/* bpf_task_work is ready to be used */
4529 	BPF_TW_STANDBY = 0,
4530 	/* irq work scheduling in progress */
4531 	BPF_TW_PENDING,
4532 	/* task work scheduling in progress */
4533 	BPF_TW_SCHEDULING,
4534 	/* task work is scheduled successfully */
4535 	BPF_TW_SCHEDULED,
4536 	/* callback is running */
4537 	BPF_TW_RUNNING,
4538 	/* associated BPF map value is deleted */
4539 	BPF_TW_FREED,
4540 };
4541 
4542 struct bpf_task_work_ctx {
4543 	enum bpf_task_work_state state;
4544 	refcount_t refcnt;
4545 	struct callback_head work;
4546 	struct irq_work irq_work;
4547 	/* bpf_prog that schedules task work */
4548 	struct bpf_prog *prog;
4549 	/* task for which callback is scheduled */
4550 	struct task_struct *task;
4551 	/* the map and map value associated with this context */
4552 	struct bpf_map *map;
4553 	void *map_val;
4554 	enum task_work_notify_mode mode;
4555 	bpf_callback_t callback_fn;
4556 	struct rcu_head rcu;
4557 } __aligned(8);
4558 
4559 /* Actual type for struct bpf_task_work */
4560 struct bpf_task_work_kern {
4561 	struct bpf_task_work_ctx *ctx;
4562 };
4563 
4564 static void bpf_task_work_ctx_reset(struct bpf_task_work_ctx *ctx)
4565 {
4566 	if (ctx->prog) {
4567 		bpf_prog_put(ctx->prog);
4568 		ctx->prog = NULL;
4569 	}
4570 	if (ctx->task) {
4571 		bpf_task_release(ctx->task);
4572 		ctx->task = NULL;
4573 	}
4574 }
4575 
4576 static bool bpf_task_work_ctx_tryget(struct bpf_task_work_ctx *ctx)
4577 {
4578 	return refcount_inc_not_zero(&ctx->refcnt);
4579 }
4580 
4581 static void bpf_task_work_destroy(struct irq_work *irq_work)
4582 {
4583 	struct bpf_task_work_ctx *ctx = container_of(irq_work, struct bpf_task_work_ctx, irq_work);
4584 
4585 	bpf_task_work_ctx_reset(ctx);
4586 	kfree_rcu(ctx, rcu);
4587 }
4588 
4589 static void bpf_task_work_ctx_put(struct bpf_task_work_ctx *ctx)
4590 {
4591 	if (!refcount_dec_and_test(&ctx->refcnt))
4592 		return;
4593 
4594 	if (irqs_disabled()) {
4595 		ctx->irq_work = IRQ_WORK_INIT(bpf_task_work_destroy);
4596 		irq_work_queue(&ctx->irq_work);
4597 	} else {
4598 		bpf_task_work_destroy(&ctx->irq_work);
4599 	}
4600 }
4601 
4602 static void bpf_task_work_cancel(struct bpf_task_work_ctx *ctx,
4603 				 struct task_struct *task)
4604 {
4605 	/*
4606 	 * Scheduled task_work callback holds ctx ref, so if we successfully
4607 	 * cancelled, we put that ref on callback's behalf. If we couldn't
4608 	 * cancel, callback will inevitably run or has already completed
4609 	 * running, and it would have taken care of its ctx ref itself.
4610 	 *
4611 	 * The caller passes the task explicitly: the scheduling handler must
4612 	 * not read ctx->task after the work is published (the callback may
4613 	 * have reset it), while in the asynchronous cancellation path
4614 	 * ctx->task is stable, see bpf_task_work_cancel_scheduled().
4615 	 */
4616 	if (task_work_cancel(task, &ctx->work))
4617 		bpf_task_work_ctx_put(ctx);
4618 }
4619 
4620 static void bpf_task_work_callback(struct callback_head *cb)
4621 {
4622 	struct bpf_task_work_ctx *ctx = container_of(cb, struct bpf_task_work_ctx, work);
4623 	struct bpf_timed_may_goto saved;
4624 	enum bpf_task_work_state state;
4625 	u32 idx;
4626 	void *key;
4627 
4628 	/* Read lock is needed to protect ctx and map key/value access */
4629 	guard(rcu_tasks_trace)();
4630 	/*
4631 	 * This callback may start running before bpf_task_work_irq() switched to
4632 	 * SCHEDULED state, so handle both transition variants SCHEDULING|SCHEDULED -> RUNNING.
4633 	 */
4634 	state = cmpxchg(&ctx->state, BPF_TW_SCHEDULING, BPF_TW_RUNNING);
4635 	if (state == BPF_TW_SCHEDULED)
4636 		state = cmpxchg(&ctx->state, BPF_TW_SCHEDULED, BPF_TW_RUNNING);
4637 	if (state == BPF_TW_FREED) {
4638 		bpf_task_work_ctx_put(ctx);
4639 		return;
4640 	}
4641 
4642 	key = (void *)map_key_from_value(ctx->map, ctx->map_val, &idx);
4643 
4644 	migrate_disable();
4645 	bpf_timed_may_goto_save(ctx->prog, &saved);
4646 	ctx->callback_fn((u64)(long)ctx->map, (u64)(long)key,
4647 			 (u64)(long)ctx->map_val, 0, 0);
4648 	bpf_timed_may_goto_restore(ctx->prog, &saved);
4649 	migrate_enable();
4650 
4651 	bpf_task_work_ctx_reset(ctx);
4652 	(void)cmpxchg(&ctx->state, BPF_TW_RUNNING, BPF_TW_STANDBY);
4653 
4654 	bpf_task_work_ctx_put(ctx);
4655 }
4656 
4657 static void bpf_task_work_irq(struct irq_work *irq_work)
4658 {
4659 	struct bpf_task_work_ctx *ctx = container_of(irq_work, struct bpf_task_work_ctx, irq_work);
4660 	struct task_struct *task;
4661 	enum bpf_task_work_state state;
4662 	int err;
4663 
4664 	guard(rcu)();
4665 
4666 	if (cmpxchg(&ctx->state, BPF_TW_PENDING, BPF_TW_SCHEDULING) != BPF_TW_PENDING) {
4667 		bpf_task_work_ctx_put(ctx);
4668 		return;
4669 	}
4670 
4671 	/*
4672 	 * Capture the task pointer before the work is published: once the
4673 	 * callback runs, it may reset ctx->task. The capture happens while
4674 	 * this round's task reference is held, and every path that can
4675 	 * release it runs after this handler entered its rcu read-side
4676 	 * section. bpf_task_release() is put_task_struct_rcu_user(), so the
4677 	 * task_struct itself cannot be freed before this section ends.
4678 	 */
4679 	task = ctx->task;
4680 	err = task_work_add(task, &ctx->work, ctx->mode);
4681 	if (err) {
4682 		bpf_task_work_ctx_reset(ctx);
4683 		/*
4684 		 * try to switch back to STANDBY for another task_work reuse, but we might have
4685 		 * gone to FREED already, which is fine as we already cleaned up after ourselves
4686 		 */
4687 		(void)cmpxchg(&ctx->state, BPF_TW_SCHEDULING, BPF_TW_STANDBY);
4688 		bpf_task_work_ctx_put(ctx);
4689 		return;
4690 	}
4691 
4692 	/*
4693 	 * It's technically possible for just scheduled task_work callback to
4694 	 * complete running by now, going SCHEDULING -> RUNNING, resetting
4695 	 * ctx->task and dropping its ctx refcount. The rcu read-side section
4696 	 * above keeps both the ctx memory and the captured task pointer
4697 	 * valid until this handler returns.
4698 	 */
4699 	state = cmpxchg(&ctx->state, BPF_TW_SCHEDULING, BPF_TW_SCHEDULED);
4700 	if (state == BPF_TW_FREED)
4701 		bpf_task_work_cancel(ctx, task); /* clean up if we switched into FREED state */
4702 }
4703 
4704 static struct bpf_task_work_ctx *bpf_task_work_fetch_ctx(struct bpf_task_work *tw,
4705 							 struct bpf_map *map)
4706 {
4707 	struct bpf_task_work_kern *twk = (void *)tw;
4708 	struct bpf_task_work_ctx *ctx, *old_ctx;
4709 
4710 	ctx = READ_ONCE(twk->ctx);
4711 	if (ctx)
4712 		return ctx;
4713 
4714 	ctx = bpf_map_kmalloc_nolock(map, sizeof(*ctx), 0, NUMA_NO_NODE);
4715 	if (!ctx)
4716 		return ERR_PTR(-ENOMEM);
4717 
4718 	memset(ctx, 0, sizeof(*ctx));
4719 	refcount_set(&ctx->refcnt, 1); /* map's own ref */
4720 	ctx->state = BPF_TW_STANDBY;
4721 	init_irq_work(&ctx->irq_work, bpf_task_work_irq);
4722 
4723 	old_ctx = cmpxchg(&twk->ctx, NULL, ctx);
4724 	if (old_ctx) {
4725 		/*
4726 		 * tw->ctx is set by concurrent BPF program, release allocated
4727 		 * memory and try to reuse already set context.
4728 		 */
4729 		kfree_nolock(ctx);
4730 		return old_ctx;
4731 	}
4732 
4733 	return ctx; /* Success */
4734 }
4735 
4736 static struct bpf_task_work_ctx *bpf_task_work_acquire_ctx(struct bpf_task_work *tw,
4737 							   struct bpf_map *map)
4738 {
4739 	struct bpf_task_work_ctx *ctx;
4740 
4741 	/*
4742 	 * Sleepable BPF programs hold rcu_read_lock_trace but not
4743 	 * regular rcu_read_lock. Since kfree_rcu waits for regular
4744 	 * RCU GP, the ctx can be freed while we're between reading
4745 	 * the pointer and incrementing the refcount. Take regular
4746 	 * rcu_read_lock to prevent kfree_rcu from freeing the ctx
4747 	 * before we can tryget it.
4748 	 */
4749 	scoped_guard(rcu) {
4750 		ctx = bpf_task_work_fetch_ctx(tw, map);
4751 		if (IS_ERR(ctx))
4752 			return ctx;
4753 
4754 		/* try to get ref for task_work callback to hold */
4755 		if (!bpf_task_work_ctx_tryget(ctx))
4756 			return ERR_PTR(-EBUSY);
4757 	}
4758 
4759 	if (cmpxchg(&ctx->state, BPF_TW_STANDBY, BPF_TW_PENDING) != BPF_TW_STANDBY) {
4760 		/* lost acquiring race or map_release_uref() stole it from us, put ref and bail */
4761 		bpf_task_work_ctx_put(ctx);
4762 		return ERR_PTR(-EBUSY);
4763 	}
4764 	/*
4765 	 * STANDBY can be published before the previous scheduling irq_work
4766 	 * returns. Claim PENDING before checking BUSY to order the check after
4767 	 * that publication. No irq_work has been queued for this attempt yet,
4768 	 * so reject reuse and roll back to STANDBY while BUSY is set. Preserve
4769 	 * FREED if deletion wins the rollback race.
4770 	 */
4771 	if (unlikely(irq_work_is_busy(&ctx->irq_work))) {
4772 		(void)cmpxchg(&ctx->state, BPF_TW_PENDING, BPF_TW_STANDBY);
4773 		bpf_task_work_ctx_put(ctx);
4774 		return ERR_PTR(-EBUSY);
4775 	}
4776 
4777 	/*
4778 	 * If no process or bpffs is holding a reference to the map, no new callbacks should be
4779 	 * scheduled. This does not address any race or correctness issue, but rather is a policy
4780 	 * choice: dropping user references should stop everything.
4781 	 */
4782 	if (!atomic64_read(&map->usercnt)) {
4783 		/* drop ref we just got for task_work callback itself */
4784 		bpf_task_work_ctx_put(ctx);
4785 		/* transfer map's ref into cancel_and_free() */
4786 		bpf_task_work_cancel_and_free(tw);
4787 		return ERR_PTR(-EBUSY);
4788 	}
4789 
4790 	return ctx;
4791 }
4792 
4793 static int bpf_task_work_schedule(struct task_struct *task, struct bpf_task_work *tw,
4794 				  struct bpf_map *map, void *callback_fn,
4795 				  struct bpf_prog_aux *aux, enum task_work_notify_mode mode)
4796 {
4797 	struct bpf_prog *prog;
4798 	struct bpf_task_work_ctx *ctx;
4799 	int err;
4800 
4801 	BTF_TYPE_EMIT(struct bpf_task_work);
4802 
4803 	prog = bpf_prog_inc_not_zero(aux->prog);
4804 	if (IS_ERR(prog))
4805 		return -EBADF;
4806 	task = bpf_task_acquire(task);
4807 	if (!task) {
4808 		err = -EBADF;
4809 		goto release_prog;
4810 	}
4811 
4812 	ctx = bpf_task_work_acquire_ctx(tw, map);
4813 	if (IS_ERR(ctx)) {
4814 		err = PTR_ERR(ctx);
4815 		goto release_all;
4816 	}
4817 
4818 	ctx->task = task;
4819 	ctx->callback_fn = (bpf_callback_t)callback_fn;
4820 	ctx->prog = prog;
4821 	ctx->mode = mode;
4822 	ctx->map = map;
4823 	ctx->map_val = (void *)tw - map->record->task_work_off;
4824 	init_task_work(&ctx->work, bpf_task_work_callback);
4825 
4826 	irq_work_queue(&ctx->irq_work);
4827 	return 0;
4828 
4829 release_all:
4830 	bpf_task_release(task);
4831 release_prog:
4832 	bpf_prog_put(prog);
4833 	return err;
4834 }
4835 
4836 /**
4837  * bpf_task_work_schedule_signal - Schedule BPF callback using task_work_add with TWA_SIGNAL
4838  * mode
4839  * @task: Task struct for which callback should be scheduled
4840  * @tw: Pointer to struct bpf_task_work in BPF map value for internal bookkeeping
4841  * @map__const_map: bpf_map that embeds struct bpf_task_work in the values
4842  * @callback: pointer to BPF subprogram to call
4843  * @aux: pointer to bpf_prog_aux of the caller BPF program, implicitly set by the verifier
4844  *
4845  * Return: 0 if task work has been scheduled successfully, negative error code otherwise
4846  */
4847 __bpf_kfunc int bpf_task_work_schedule_signal(struct task_struct *task, struct bpf_task_work *tw,
4848 					      void *map__const_map, bpf_task_work_callback_t callback,
4849 					      struct bpf_prog_aux *aux)
4850 {
4851 	return bpf_task_work_schedule(task, tw, map__const_map, callback, aux, TWA_SIGNAL);
4852 }
4853 
4854 /**
4855  * bpf_task_work_schedule_resume - Schedule BPF callback using task_work_add with TWA_RESUME
4856  * mode
4857  * @task: Task struct for which callback should be scheduled
4858  * @tw: Pointer to struct bpf_task_work in BPF map value for internal bookkeeping
4859  * @map__const_map: bpf_map that embeds struct bpf_task_work in the values
4860  * @callback: pointer to BPF subprogram to call
4861  * @aux: pointer to bpf_prog_aux of the caller BPF program, implicitly set by the verifier
4862  *
4863  * Return: 0 if task work has been scheduled successfully, negative error code otherwise
4864  */
4865 __bpf_kfunc int bpf_task_work_schedule_resume(struct task_struct *task, struct bpf_task_work *tw,
4866 					      void *map__const_map, bpf_task_work_callback_t callback,
4867 					      struct bpf_prog_aux *aux)
4868 {
4869 	return bpf_task_work_schedule(task, tw, map__const_map, callback, aux, TWA_RESUME);
4870 }
4871 
4872 typedef int (*bpf_rcu_callback_t)(struct bpf_map *map, void *key, void *value);
4873 
4874 /* Actual type for struct bpf_rcu_head */
4875 struct bpf_rcu_head_kern {
4876 	struct rcu_head rcu;
4877 	bpf_callback_t callback_fn;
4878 	struct bpf_map *map;
4879 	struct bpf_prog *prog;
4880 	u32 armed;
4881 } __aligned(8);
4882 
4883 static void bpf_rcu_run_callback(struct rcu_head *rcu)
4884 {
4885 	struct bpf_rcu_head_kern *rh = container_of(rcu, struct bpf_rcu_head_kern, rcu);
4886 	bpf_callback_t callback_fn = rh->callback_fn;
4887 	struct bpf_prog *prog = rh->prog;
4888 	struct bpf_timed_may_goto saved;
4889 	struct bpf_map *map = rh->map;
4890 	void *value, *key;
4891 	u32 idx;
4892 
4893 	value = (void *)rh - map->record->rcu_head_off;
4894 	key = map_key_from_value(map, value, &idx);
4895 
4896 	/* Pairs with the arming cmpxchg(): rh may be re-armed as soon as this store lands. */
4897 	smp_store_release(&rh->armed, 0);
4898 
4899 	rcu_read_lock_dont_migrate();
4900 	bpf_timed_may_goto_save(prog, &saved);
4901 	callback_fn((u64)(long)map, (u64)(long)key, (u64)(long)value, 0, 0);
4902 	bpf_timed_may_goto_restore(prog, &saved);
4903 	rcu_read_unlock_migrate();
4904 
4905 	bpf_prog_put(prog);
4906 }
4907 
4908 static int __bpf_call_rcu(struct bpf_rcu_head *rh, struct bpf_map *map, void *callback,
4909 			  struct bpf_prog_aux *aux, bool trace)
4910 {
4911 	struct bpf_rcu_head_kern *rhk = (void *)rh;
4912 	struct bpf_prog *prog;
4913 
4914 	BUILD_BUG_ON(sizeof(struct bpf_rcu_head_kern) > sizeof(struct bpf_rcu_head));
4915 	BUILD_BUG_ON(__alignof__(struct bpf_rcu_head_kern) != __alignof__(struct bpf_rcu_head));
4916 	BTF_TYPE_EMIT(struct bpf_rcu_head);
4917 
4918 	/* A queued callback cannot be cancelled, so a self-rearming one would pin prog and map. */
4919 	if (!atomic64_read(&map->usercnt))
4920 		return -EPERM;
4921 
4922 	if (cmpxchg(&rhk->armed, 0, 1))
4923 		return -EBUSY;
4924 
4925 	prog = bpf_prog_inc_not_zero(aux->prog);
4926 	if (IS_ERR(prog)) {
4927 		WRITE_ONCE(rhk->armed, 0);
4928 		return -EBADF;
4929 	}
4930 
4931 	rhk->callback_fn = (bpf_callback_t)callback;
4932 	rhk->map = map;
4933 	rhk->prog = prog;
4934 	if (trace)
4935 		call_rcu_tasks_trace(&rhk->rcu, bpf_rcu_run_callback);
4936 	else
4937 		call_rcu(&rhk->rcu, bpf_rcu_run_callback);
4938 	return 0;
4939 }
4940 
4941 /**
4942  * bpf_call_rcu - Invoke a BPF callback after an RCU grace period
4943  * @rh: struct bpf_rcu_head in a BPF map value
4944  * @map__const_map: bpf_map that embeds struct bpf_rcu_head in the values
4945  * @callback: BPF subprogram, invoked as callback(map, key, value) for the value holding @rh
4946  * @aux: bpf_prog_aux of the caller, implicitly set by the verifier
4947  *
4948  * Return: 0, -EBUSY if @rh is already queued, -EPERM if @map is held by neither a process
4949  * nor bpffs, or -EBADF if the calling program is going away.
4950  */
4951 __bpf_kfunc int bpf_call_rcu(struct bpf_rcu_head *rh, void *map__const_map,
4952 			     bpf_rcu_callback_t callback, struct bpf_prog_aux *aux)
4953 {
4954 	return __bpf_call_rcu(rh, map__const_map, callback, aux, false);
4955 }
4956 
4957 /**
4958  * bpf_call_rcu_tasks_trace - Invoke a BPF callback after an RCU tasks trace grace period
4959  * @rh: struct bpf_rcu_head in a BPF map value
4960  * @map__const_map: bpf_map that embeds struct bpf_rcu_head in the values
4961  * @callback: BPF subprogram, invoked as callback(map, key, value) for the value holding @rh
4962  * @aux: bpf_prog_aux of the caller, implicitly set by the verifier
4963  *
4964  * Waits for sleepable BPF programs too.  The callback itself is not sleepable either way.
4965  *
4966  * Return: 0, -EBUSY if @rh is already queued, -EPERM if @map is held by neither a process
4967  * nor bpffs, or -EBADF if the calling program is going away.
4968  */
4969 __bpf_kfunc int bpf_call_rcu_tasks_trace(struct bpf_rcu_head *rh, void *map__const_map,
4970 					 bpf_rcu_callback_t callback, struct bpf_prog_aux *aux)
4971 {
4972 	return __bpf_call_rcu(rh, map__const_map, callback, aux, true);
4973 }
4974 
4975 static int make_file_dynptr(struct file *file, u32 flags, bool may_sleep,
4976 			    struct bpf_dynptr_kern *ptr)
4977 {
4978 	struct bpf_dynptr_file_impl *state;
4979 
4980 	/* flags is currently unsupported */
4981 	if (flags) {
4982 		bpf_dynptr_set_null(ptr);
4983 		return -EINVAL;
4984 	}
4985 
4986 	state = kmalloc_nolock(sizeof(*state), 0, NUMA_NO_NODE);
4987 	if (!state) {
4988 		bpf_dynptr_set_null(ptr);
4989 		return -ENOMEM;
4990 	}
4991 	state->offset = 0;
4992 	state->size = U64_MAX; /* Don't restrict size, as file may change anyways */
4993 	freader_init_from_file(&state->freader, NULL, 0, file, may_sleep);
4994 	bpf_dynptr_init(ptr, state, BPF_DYNPTR_TYPE_FILE, 0, 0);
4995 	bpf_dynptr_set_rdonly(ptr);
4996 	return 0;
4997 }
4998 
4999 __bpf_kfunc int bpf_dynptr_from_file(struct file *file, u32 flags, struct bpf_dynptr *ptr__uninit)
5000 {
5001 	return make_file_dynptr(file, flags, false, (struct bpf_dynptr_kern *)ptr__uninit);
5002 }
5003 
5004 int bpf_dynptr_from_file_sleepable(struct file *file, u32 flags, struct bpf_dynptr *ptr__uninit)
5005 {
5006 	return make_file_dynptr(file, flags, true, (struct bpf_dynptr_kern *)ptr__uninit);
5007 }
5008 
5009 __bpf_kfunc int bpf_dynptr_file_discard(struct bpf_dynptr *dynptr)
5010 {
5011 	struct bpf_dynptr_kern *ptr = (struct bpf_dynptr_kern *)dynptr;
5012 	struct bpf_dynptr_file_impl *df = ptr->data;
5013 
5014 	if (!df)
5015 		return 0;
5016 
5017 	freader_cleanup(&df->freader);
5018 	kfree_nolock(df);
5019 	bpf_dynptr_set_null(ptr);
5020 	return 0;
5021 }
5022 
5023 /**
5024  * bpf_timer_cancel_async - try to deactivate a timer
5025  * @timer:	bpf_timer to stop
5026  *
5027  * Returns:
5028  *
5029  *  *  0 when the timer was not active
5030  *  *  1 when the timer was active
5031  *  * -1 when the timer is currently executing the callback function and
5032  *       cannot be stopped
5033  *  * -ECANCELED when the timer will be cancelled asynchronously
5034  *  * -ENOMEM when out of memory
5035  *  * -EINVAL when the timer was not initialized
5036  *  * -ENOENT when this kfunc is racing with timer deletion
5037  */
5038 __bpf_kfunc int bpf_timer_cancel_async(struct bpf_timer *timer)
5039 {
5040 	struct bpf_async_kern *async = (void *)timer;
5041 	struct bpf_async_cb *cb;
5042 	int ret;
5043 
5044 	cb = READ_ONCE(async->cb);
5045 	if (!cb)
5046 		return -EINVAL;
5047 
5048 	/*
5049 	 * Unlike hrtimer_start() it's ok to synchronously call
5050 	 * hrtimer_try_to_cancel() when refcnt reached zero, but deferring to
5051 	 * irq_work is not, since irq callback may execute after RCU GP and
5052 	 * cb could be freed at that time. Check for refcnt zero for
5053 	 * consistency.
5054 	 */
5055 	if (!refcount_inc_not_zero(&cb->refcnt))
5056 		return -ENOENT;
5057 
5058 	if (!defer_timer_wq_op()) {
5059 		struct bpf_hrtimer *t = container_of(cb, struct bpf_hrtimer, cb);
5060 
5061 		ret = hrtimer_try_to_cancel(&t->timer);
5062 		bpf_async_refcount_put(cb);
5063 		return ret;
5064 	} else {
5065 		ret = bpf_async_schedule_op(cb, BPF_ASYNC_CANCEL, 0, 0);
5066 		return ret ? ret : -ECANCELED;
5067 	}
5068 }
5069 
5070 __bpf_kfunc_end_defs();
5071 
5072 static void bpf_task_work_cancel_scheduled(struct irq_work *irq_work)
5073 {
5074 	struct bpf_task_work_ctx *ctx = container_of(irq_work, struct bpf_task_work_ctx, irq_work);
5075 
5076 	/*
5077 	 * Deletion observed SCHEDULED and won against the callback's
5078 	 * transition to RUNNING. The callback takes its FREED exit without
5079 	 * resetting ctx->task, and the transferred map reference prevents
5080 	 * destruction until cancellation completes.
5081 	 */
5082 	bpf_task_work_cancel(ctx, ctx->task); /* this might put task_work callback's ref */
5083 	bpf_task_work_ctx_put(ctx); /* and here we put map's own ref that was transferred to us */
5084 }
5085 
5086 void bpf_task_work_cancel_and_free(void *val)
5087 {
5088 	struct bpf_task_work_kern *twk = val;
5089 	struct bpf_task_work_ctx *ctx;
5090 	enum bpf_task_work_state state;
5091 
5092 	ctx = xchg(&twk->ctx, NULL);
5093 	if (!ctx)
5094 		return;
5095 
5096 	state = xchg(&ctx->state, BPF_TW_FREED);
5097 	if (state == BPF_TW_SCHEDULED) {
5098 		/* run in irq_work to avoid locks in NMI */
5099 		init_irq_work(&ctx->irq_work, bpf_task_work_cancel_scheduled);
5100 		irq_work_queue(&ctx->irq_work);
5101 		return;
5102 	}
5103 
5104 	bpf_task_work_ctx_put(ctx); /* put bpf map's ref */
5105 }
5106 
5107 BTF_KFUNCS_START(generic_btf_ids)
5108 #ifdef CONFIG_CRASH_DUMP
5109 BTF_ID_FLAGS(func, crash_kexec, KF_DESTRUCTIVE)
5110 #endif
5111 BTF_ID_FLAGS(func, bpf_obj_new, KF_ACQUIRE | KF_RET_NULL | KF_IMPLICIT_ARGS)
5112 BTF_ID_FLAGS(func, bpf_obj_new_impl, KF_ACQUIRE | KF_RET_NULL)
5113 BTF_ID_FLAGS(func, bpf_percpu_obj_new, KF_ACQUIRE | KF_RET_NULL | KF_IMPLICIT_ARGS)
5114 BTF_ID_FLAGS(func, bpf_percpu_obj_new_impl, KF_ACQUIRE | KF_RET_NULL)
5115 BTF_ID_FLAGS(func, bpf_obj_drop, KF_RELEASE | KF_IMPLICIT_ARGS)
5116 BTF_ID_FLAGS(func, bpf_obj_drop_impl, KF_RELEASE)
5117 BTF_ID_FLAGS(func, bpf_percpu_obj_drop, KF_RELEASE | KF_IMPLICIT_ARGS)
5118 BTF_ID_FLAGS(func, bpf_percpu_obj_drop_impl, KF_RELEASE)
5119 BTF_ID_FLAGS(func, bpf_refcount_acquire,
5120 	     KF_ACQUIRE | KF_RET_NULL | KF_RCU | KF_IMPLICIT_ARGS | KF_SPINLOCK_SAFE)
5121 BTF_ID_FLAGS(func, bpf_refcount_acquire_impl,
5122 	     KF_ACQUIRE | KF_RET_NULL | KF_RCU | KF_SPINLOCK_SAFE)
5123 BTF_ID_FLAGS(func, bpf_list_push_front, KF_IMPLICIT_ARGS | KF_SPINLOCK_SAFE)
5124 BTF_ID_FLAGS(func, bpf_list_push_front_impl, KF_SPINLOCK_SAFE)
5125 BTF_ID_FLAGS(func, bpf_list_push_back, KF_IMPLICIT_ARGS | KF_SPINLOCK_SAFE)
5126 BTF_ID_FLAGS(func, bpf_list_push_back_impl, KF_SPINLOCK_SAFE)
5127 BTF_ID_FLAGS(func, bpf_list_add, KF_IMPLICIT_ARGS | KF_SPINLOCK_SAFE)
5128 BTF_ID_FLAGS(func, bpf_list_pop_front, KF_ACQUIRE | KF_RET_NULL | KF_SPINLOCK_SAFE)
5129 BTF_ID_FLAGS(func, bpf_list_pop_back, KF_ACQUIRE | KF_RET_NULL | KF_SPINLOCK_SAFE)
5130 BTF_ID_FLAGS(func, bpf_list_del, KF_ACQUIRE | KF_RET_NULL | KF_SPINLOCK_SAFE)
5131 BTF_ID_FLAGS(func, bpf_list_front, KF_RET_NULL | KF_SPINLOCK_SAFE)
5132 BTF_ID_FLAGS(func, bpf_list_back, KF_RET_NULL | KF_SPINLOCK_SAFE)
5133 BTF_ID_FLAGS(func, bpf_list_is_first, KF_SPINLOCK_SAFE)
5134 BTF_ID_FLAGS(func, bpf_list_is_last, KF_SPINLOCK_SAFE)
5135 BTF_ID_FLAGS(func, bpf_list_empty, KF_SPINLOCK_SAFE)
5136 BTF_ID_FLAGS(func, bpf_task_acquire, KF_ACQUIRE | KF_RCU | KF_RET_NULL)
5137 BTF_ID_FLAGS(func, bpf_task_release, KF_RELEASE)
5138 BTF_ID_FLAGS(func, bpf_rbtree_remove, KF_ACQUIRE | KF_RET_NULL | KF_SPINLOCK_SAFE)
5139 BTF_ID_FLAGS(func, bpf_rbtree_add, KF_IMPLICIT_ARGS | KF_SPINLOCK_SAFE)
5140 BTF_ID_FLAGS(func, bpf_rbtree_add_impl, KF_SPINLOCK_SAFE)
5141 BTF_ID_FLAGS(func, bpf_rbtree_first, KF_RET_NULL | KF_SPINLOCK_SAFE)
5142 BTF_ID_FLAGS(func, bpf_rbtree_root, KF_RET_NULL | KF_SPINLOCK_SAFE)
5143 BTF_ID_FLAGS(func, bpf_rbtree_left, KF_RET_NULL | KF_SPINLOCK_SAFE)
5144 BTF_ID_FLAGS(func, bpf_rbtree_right, KF_RET_NULL | KF_SPINLOCK_SAFE)
5145 
5146 #ifdef CONFIG_CGROUPS
5147 BTF_ID_FLAGS(func, bpf_cgroup_acquire, KF_ACQUIRE | KF_RCU | KF_RET_NULL)
5148 BTF_ID_FLAGS(func, bpf_cgroup_release, KF_RELEASE)
5149 BTF_ID_FLAGS(func, bpf_cgroup_ancestor, KF_ACQUIRE | KF_RCU | KF_RET_NULL)
5150 BTF_ID_FLAGS(func, bpf_cgroup_from_id, KF_ACQUIRE | KF_RET_NULL)
5151 BTF_ID_FLAGS(func, bpf_task_under_cgroup, KF_RCU)
5152 BTF_ID_FLAGS(func, bpf_task_get_cgroup1, KF_ACQUIRE | KF_RCU | KF_RET_NULL)
5153 #endif
5154 BTF_ID_FLAGS(func, bpf_task_from_pid, KF_ACQUIRE | KF_RET_NULL)
5155 BTF_ID_FLAGS(func, bpf_task_from_vpid, KF_ACQUIRE | KF_RET_NULL)
5156 BTF_ID_FLAGS(func, bpf_throw)
5157 #ifdef CONFIG_BPF_EVENTS
5158 BTF_ID_FLAGS(func, bpf_send_signal_task)
5159 #endif
5160 #ifdef CONFIG_KEYS
5161 BTF_ID_FLAGS(func, bpf_lookup_user_key, KF_ACQUIRE | KF_RET_NULL | KF_SLEEPABLE)
5162 BTF_ID_FLAGS(func, bpf_lookup_system_key, KF_ACQUIRE | KF_RET_NULL)
5163 BTF_ID_FLAGS(func, bpf_key_put, KF_RELEASE)
5164 #ifdef CONFIG_SYSTEM_DATA_VERIFICATION
5165 BTF_ID_FLAGS(func, bpf_verify_pkcs7_signature, KF_SLEEPABLE)
5166 #endif
5167 #endif
5168 #ifdef CONFIG_S390
5169 BTF_ID_FLAGS(func, bpf_get_lowcore)
5170 #endif
5171 BTF_KFUNCS_END(generic_btf_ids)
5172 
5173 static const struct btf_kfunc_id_set generic_kfunc_set = {
5174 	.owner = THIS_MODULE,
5175 	.set   = &generic_btf_ids,
5176 };
5177 
5178 BTF_ID_LIST(generic_dtor_ids)
5179 BTF_ID(struct, task_struct)
5180 BTF_ID(func, bpf_task_release_dtor)
5181 #ifdef CONFIG_CGROUPS
5182 BTF_ID(struct, cgroup)
5183 BTF_ID(func, bpf_cgroup_release_dtor)
5184 #endif
5185 
5186 BTF_KFUNCS_START(common_btf_ids)
5187 BTF_ID_FLAGS(func, bpf_cast_to_kern_ctx, KF_FASTCALL)
5188 BTF_ID_FLAGS(func, bpf_rdonly_cast, KF_FASTCALL | KF_PERFMON)
5189 BTF_ID_FLAGS(func, bpf_rcu_read_lock)
5190 BTF_ID_FLAGS(func, bpf_rcu_read_unlock)
5191 BTF_ID_FLAGS(func, bpf_dynptr_slice, KF_RET_NULL)
5192 BTF_ID_FLAGS(func, bpf_dynptr_slice_rdwr, KF_RET_NULL)
5193 BTF_ID_FLAGS(func, bpf_iter_num_new, KF_ITER_NEW | KF_SPINLOCK_SAFE)
5194 BTF_ID_FLAGS(func, bpf_iter_num_next, KF_ITER_NEXT | KF_RET_NULL | KF_SPINLOCK_SAFE)
5195 BTF_ID_FLAGS(func, bpf_iter_num_destroy, KF_ITER_DESTROY | KF_SPINLOCK_SAFE)
5196 BTF_ID_FLAGS(func, bpf_iter_task_vma_new, KF_ITER_NEW | KF_RCU)
5197 BTF_ID_FLAGS(func, bpf_iter_task_vma_next, KF_ITER_NEXT | KF_RET_NULL)
5198 BTF_ID_FLAGS(func, bpf_iter_task_vma_destroy, KF_ITER_DESTROY)
5199 #ifdef CONFIG_CGROUPS
5200 BTF_ID_FLAGS(func, bpf_iter_css_task_new, KF_ITER_NEW)
5201 BTF_ID_FLAGS(func, bpf_iter_css_task_next, KF_ITER_NEXT | KF_RET_NULL)
5202 BTF_ID_FLAGS(func, bpf_iter_css_task_destroy, KF_ITER_DESTROY)
5203 BTF_ID_FLAGS(func, bpf_iter_css_new, KF_ITER_NEW | KF_RCU_PROTECTED)
5204 BTF_ID_FLAGS(func, bpf_iter_css_next, KF_ITER_NEXT | KF_RET_NULL)
5205 BTF_ID_FLAGS(func, bpf_iter_css_destroy, KF_ITER_DESTROY)
5206 #endif
5207 BTF_ID_FLAGS(func, bpf_iter_task_new, KF_ITER_NEW | KF_RCU_PROTECTED)
5208 BTF_ID_FLAGS(func, bpf_iter_task_next, KF_ITER_NEXT | KF_RET_NULL)
5209 BTF_ID_FLAGS(func, bpf_iter_task_destroy, KF_ITER_DESTROY)
5210 BTF_ID_FLAGS(func, bpf_dynptr_adjust)
5211 BTF_ID_FLAGS(func, bpf_dynptr_is_null)
5212 BTF_ID_FLAGS(func, bpf_dynptr_is_rdonly)
5213 BTF_ID_FLAGS(func, bpf_dynptr_size)
5214 BTF_ID_FLAGS(func, bpf_dynptr_clone)
5215 BTF_ID_FLAGS(func, bpf_dynptr_copy)
5216 BTF_ID_FLAGS(func, bpf_dynptr_memset)
5217 #ifdef CONFIG_NET
5218 BTF_ID_FLAGS(func, bpf_modify_return_test_tp)
5219 #endif
5220 BTF_ID_FLAGS(func, bpf_wq_init)
5221 BTF_ID_FLAGS(func, bpf_wq_set_callback, KF_IMPLICIT_ARGS)
5222 BTF_ID_FLAGS(func, bpf_wq_start)
5223 BTF_ID_FLAGS(func, bpf_preempt_disable)
5224 BTF_ID_FLAGS(func, bpf_preempt_enable)
5225 BTF_ID_FLAGS(func, bpf_iter_bits_new, KF_ITER_NEW | KF_PERFMON)
5226 BTF_ID_FLAGS(func, bpf_iter_bits_next, KF_ITER_NEXT | KF_RET_NULL)
5227 BTF_ID_FLAGS(func, bpf_iter_bits_destroy, KF_ITER_DESTROY)
5228 BTF_ID_FLAGS(func, bpf_copy_from_user_str, KF_SLEEPABLE | KF_PERFMON)
5229 BTF_ID_FLAGS(func, bpf_copy_from_user_mm, KF_SLEEPABLE | KF_PERFMON)
5230 BTF_ID_FLAGS(func, bpf_copy_from_user_mm_str, KF_SLEEPABLE | KF_PERFMON)
5231 BTF_ID_FLAGS(func, bpf_copy_from_user_task_str, KF_SLEEPABLE | KF_PERFMON)
5232 BTF_ID_FLAGS(func, bpf_get_kmem_cache, KF_PERFMON)
5233 BTF_ID_FLAGS(func, bpf_iter_kmem_cache_new, KF_ITER_NEW | KF_SLEEPABLE)
5234 BTF_ID_FLAGS(func, bpf_iter_kmem_cache_next, KF_ITER_NEXT | KF_RET_NULL | KF_SLEEPABLE)
5235 BTF_ID_FLAGS(func, bpf_iter_kmem_cache_destroy, KF_ITER_DESTROY | KF_SLEEPABLE)
5236 BTF_ID_FLAGS(func, bpf_local_irq_save)
5237 BTF_ID_FLAGS(func, bpf_local_irq_restore)
5238 #ifdef CONFIG_BPF_EVENTS
5239 BTF_ID_FLAGS(func, bpf_probe_read_user_dynptr, KF_PERFMON)
5240 BTF_ID_FLAGS(func, bpf_probe_read_kernel_dynptr, KF_PERFMON)
5241 BTF_ID_FLAGS(func, bpf_probe_read_user_str_dynptr, KF_PERFMON)
5242 BTF_ID_FLAGS(func, bpf_probe_read_kernel_str_dynptr, KF_PERFMON)
5243 BTF_ID_FLAGS(func, bpf_copy_from_user_dynptr, KF_SLEEPABLE | KF_PERFMON)
5244 BTF_ID_FLAGS(func, bpf_copy_from_user_str_dynptr, KF_SLEEPABLE | KF_PERFMON)
5245 BTF_ID_FLAGS(func, bpf_copy_from_user_task_dynptr, KF_SLEEPABLE | KF_PERFMON)
5246 BTF_ID_FLAGS(func, bpf_copy_from_user_task_str_dynptr, KF_SLEEPABLE | KF_PERFMON)
5247 #endif
5248 #ifdef CONFIG_DMA_SHARED_BUFFER
5249 BTF_ID_FLAGS(func, bpf_iter_dmabuf_new, KF_ITER_NEW | KF_SLEEPABLE)
5250 BTF_ID_FLAGS(func, bpf_iter_dmabuf_next, KF_ITER_NEXT | KF_RET_NULL | KF_SLEEPABLE)
5251 BTF_ID_FLAGS(func, bpf_iter_dmabuf_destroy, KF_ITER_DESTROY | KF_SLEEPABLE)
5252 #endif
5253 BTF_ID_FLAGS(func, __bpf_trap)
5254 BTF_ID_FLAGS(func, bpf_strcmp, KF_PERFMON);
5255 BTF_ID_FLAGS(func, bpf_strcasecmp, KF_PERFMON);
5256 BTF_ID_FLAGS(func, bpf_strncasecmp, KF_PERFMON);
5257 BTF_ID_FLAGS(func, bpf_strchr, KF_PERFMON);
5258 BTF_ID_FLAGS(func, bpf_strchrnul, KF_PERFMON);
5259 BTF_ID_FLAGS(func, bpf_strnchr, KF_PERFMON);
5260 BTF_ID_FLAGS(func, bpf_strrchr, KF_PERFMON);
5261 BTF_ID_FLAGS(func, bpf_strlen, KF_PERFMON);
5262 BTF_ID_FLAGS(func, bpf_strnlen, KF_PERFMON);
5263 BTF_ID_FLAGS(func, bpf_strspn, KF_PERFMON);
5264 BTF_ID_FLAGS(func, bpf_strcspn, KF_PERFMON);
5265 BTF_ID_FLAGS(func, bpf_strstr, KF_PERFMON);
5266 BTF_ID_FLAGS(func, bpf_strcasestr, KF_PERFMON);
5267 BTF_ID_FLAGS(func, bpf_strnstr, KF_PERFMON);
5268 BTF_ID_FLAGS(func, bpf_strncasestr, KF_PERFMON);
5269 #if defined(CONFIG_BPF_LSM) && defined(CONFIG_CGROUPS)
5270 BTF_ID_FLAGS(func, bpf_cgroup_read_xattr, KF_RCU)
5271 #endif
5272 BTF_ID_FLAGS(func, bpf_stream_vprintk, KF_IMPLICIT_ARGS | KF_SPINLOCK_SAFE | KF_PERFMON)
5273 BTF_ID_FLAGS(func, bpf_stream_print_stack, KF_IMPLICIT_ARGS | KF_SPINLOCK_SAFE | KF_PERFMON)
5274 BTF_ID_FLAGS(func, bpf_task_work_schedule_signal, KF_IMPLICIT_ARGS)
5275 BTF_ID_FLAGS(func, bpf_task_work_schedule_resume, KF_IMPLICIT_ARGS)
5276 BTF_ID_FLAGS(func, bpf_call_rcu, KF_IMPLICIT_ARGS)
5277 BTF_ID_FLAGS(func, bpf_call_rcu_tasks_trace, KF_IMPLICIT_ARGS)
5278 BTF_ID_FLAGS(func, bpf_dynptr_from_file)
5279 BTF_ID_FLAGS(func, bpf_dynptr_file_discard, KF_RELEASE)
5280 BTF_ID_FLAGS(func, bpf_timer_cancel_async)
5281 BTF_KFUNCS_END(common_btf_ids)
5282 
5283 static const struct btf_kfunc_id_set common_kfunc_set = {
5284 	.owner = THIS_MODULE,
5285 	.set   = &common_btf_ids,
5286 };
5287 
5288 static int __init kfunc_init(void)
5289 {
5290 	int ret;
5291 	const struct btf_id_dtor_kfunc generic_dtors[] = {
5292 		{
5293 			.btf_id       = generic_dtor_ids[0],
5294 			.kfunc_btf_id = generic_dtor_ids[1]
5295 		},
5296 #ifdef CONFIG_CGROUPS
5297 		{
5298 			.btf_id       = generic_dtor_ids[2],
5299 			.kfunc_btf_id = generic_dtor_ids[3]
5300 		},
5301 #endif
5302 	};
5303 
5304 	ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_TRACING, &generic_kfunc_set);
5305 	ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_SCHED_CLS, &generic_kfunc_set);
5306 	ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_XDP, &generic_kfunc_set);
5307 	ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS, &generic_kfunc_set);
5308 	ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_SYSCALL, &generic_kfunc_set);
5309 	ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_CGROUP_SKB, &generic_kfunc_set);
5310 	ret = ret ?: register_btf_id_dtor_kfuncs(generic_dtors,
5311 						  ARRAY_SIZE(generic_dtors),
5312 						  THIS_MODULE);
5313 	return ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_UNSPEC, &common_kfunc_set);
5314 }
5315 
5316 late_initcall(kfunc_init);
5317 
5318 /* Get a pointer to dynptr data up to len bytes for read only access. If
5319  * the dynptr doesn't have continuous data up to len bytes, return NULL.
5320  */
5321 const void *__bpf_dynptr_data(const struct bpf_dynptr_kern *ptr, u64 len)
5322 {
5323 	const struct bpf_dynptr *p = (struct bpf_dynptr *)ptr;
5324 
5325 	return bpf_dynptr_slice(p, 0, NULL, len);
5326 }
5327 
5328 /* Get a pointer to dynptr data up to len bytes for read write access. If
5329  * the dynptr doesn't have continuous data up to len bytes, or the dynptr
5330  * is read only, return NULL.
5331  */
5332 void *__bpf_dynptr_data_rw(const struct bpf_dynptr_kern *ptr, u64 len)
5333 {
5334 	if (__bpf_dynptr_is_rdonly(ptr))
5335 		return NULL;
5336 	return (void *)__bpf_dynptr_data(ptr, len);
5337 }
5338 
5339 void bpf_map_free_internal_structs(struct bpf_map *map, void *val)
5340 {
5341 	if (btf_record_has_field(map->record, BPF_TIMER))
5342 		bpf_obj_free_timer(map->record, val);
5343 	if (btf_record_has_field(map->record, BPF_WORKQUEUE))
5344 		bpf_obj_free_workqueue(map->record, val);
5345 	if (btf_record_has_field(map->record, BPF_TASK_WORK))
5346 		bpf_obj_free_task_work(map->record, val);
5347 }
5348