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