xref: /linux/kernel/bpf/helpers.c (revision 9b8107553424fd87955fed257a807672c2097297)
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/rcupdate.h>
8 #include <linux/random.h>
9 #include <linux/smp.h>
10 #include <linux/topology.h>
11 #include <linux/ktime.h>
12 #include <linux/sched.h>
13 #include <linux/uidgid.h>
14 #include <linux/filter.h>
15 #include <linux/ctype.h>
16 #include <linux/jiffies.h>
17 #include <linux/pid_namespace.h>
18 #include <linux/poison.h>
19 #include <linux/proc_ns.h>
20 #include <linux/security.h>
21 #include <linux/btf_ids.h>
22 #include <linux/bpf_mem_alloc.h>
23 
24 #include "../../lib/kstrtox.h"
25 
26 /* If kernel subsystem is allowing eBPF programs to call this function,
27  * inside its own verifier_ops->get_func_proto() callback it should return
28  * bpf_map_lookup_elem_proto, so that verifier can properly check the arguments
29  *
30  * Different map implementations will rely on rcu in map methods
31  * lookup/update/delete, therefore eBPF programs must run under rcu lock
32  * if program is allowed to access maps, so check rcu_read_lock_held in
33  * all three functions.
34  */
35 BPF_CALL_2(bpf_map_lookup_elem, struct bpf_map *, map, void *, key)
36 {
37 	WARN_ON_ONCE(!rcu_read_lock_held() && !rcu_read_lock_bh_held());
38 	return (unsigned long) map->ops->map_lookup_elem(map, key);
39 }
40 
41 const struct bpf_func_proto bpf_map_lookup_elem_proto = {
42 	.func		= bpf_map_lookup_elem,
43 	.gpl_only	= false,
44 	.pkt_access	= true,
45 	.ret_type	= RET_PTR_TO_MAP_VALUE_OR_NULL,
46 	.arg1_type	= ARG_CONST_MAP_PTR,
47 	.arg2_type	= ARG_PTR_TO_MAP_KEY,
48 };
49 
50 BPF_CALL_4(bpf_map_update_elem, struct bpf_map *, map, void *, key,
51 	   void *, value, u64, flags)
52 {
53 	WARN_ON_ONCE(!rcu_read_lock_held() && !rcu_read_lock_bh_held());
54 	return map->ops->map_update_elem(map, key, value, flags);
55 }
56 
57 const struct bpf_func_proto bpf_map_update_elem_proto = {
58 	.func		= bpf_map_update_elem,
59 	.gpl_only	= false,
60 	.pkt_access	= true,
61 	.ret_type	= RET_INTEGER,
62 	.arg1_type	= ARG_CONST_MAP_PTR,
63 	.arg2_type	= ARG_PTR_TO_MAP_KEY,
64 	.arg3_type	= ARG_PTR_TO_MAP_VALUE,
65 	.arg4_type	= ARG_ANYTHING,
66 };
67 
68 BPF_CALL_2(bpf_map_delete_elem, struct bpf_map *, map, void *, key)
69 {
70 	WARN_ON_ONCE(!rcu_read_lock_held() && !rcu_read_lock_bh_held());
71 	return map->ops->map_delete_elem(map, key);
72 }
73 
74 const struct bpf_func_proto bpf_map_delete_elem_proto = {
75 	.func		= bpf_map_delete_elem,
76 	.gpl_only	= false,
77 	.pkt_access	= true,
78 	.ret_type	= RET_INTEGER,
79 	.arg1_type	= ARG_CONST_MAP_PTR,
80 	.arg2_type	= ARG_PTR_TO_MAP_KEY,
81 };
82 
83 BPF_CALL_3(bpf_map_push_elem, struct bpf_map *, map, void *, value, u64, flags)
84 {
85 	return map->ops->map_push_elem(map, value, flags);
86 }
87 
88 const struct bpf_func_proto bpf_map_push_elem_proto = {
89 	.func		= bpf_map_push_elem,
90 	.gpl_only	= false,
91 	.pkt_access	= true,
92 	.ret_type	= RET_INTEGER,
93 	.arg1_type	= ARG_CONST_MAP_PTR,
94 	.arg2_type	= ARG_PTR_TO_MAP_VALUE,
95 	.arg3_type	= ARG_ANYTHING,
96 };
97 
98 BPF_CALL_2(bpf_map_pop_elem, struct bpf_map *, map, void *, value)
99 {
100 	return map->ops->map_pop_elem(map, value);
101 }
102 
103 const struct bpf_func_proto bpf_map_pop_elem_proto = {
104 	.func		= bpf_map_pop_elem,
105 	.gpl_only	= false,
106 	.ret_type	= RET_INTEGER,
107 	.arg1_type	= ARG_CONST_MAP_PTR,
108 	.arg2_type	= ARG_PTR_TO_MAP_VALUE | MEM_UNINIT,
109 };
110 
111 BPF_CALL_2(bpf_map_peek_elem, struct bpf_map *, map, void *, value)
112 {
113 	return map->ops->map_peek_elem(map, value);
114 }
115 
116 const struct bpf_func_proto bpf_map_peek_elem_proto = {
117 	.func		= bpf_map_peek_elem,
118 	.gpl_only	= false,
119 	.ret_type	= RET_INTEGER,
120 	.arg1_type	= ARG_CONST_MAP_PTR,
121 	.arg2_type	= ARG_PTR_TO_MAP_VALUE | MEM_UNINIT,
122 };
123 
124 BPF_CALL_3(bpf_map_lookup_percpu_elem, struct bpf_map *, map, void *, key, u32, cpu)
125 {
126 	WARN_ON_ONCE(!rcu_read_lock_held() && !rcu_read_lock_bh_held());
127 	return (unsigned long) map->ops->map_lookup_percpu_elem(map, key, cpu);
128 }
129 
130 const struct bpf_func_proto bpf_map_lookup_percpu_elem_proto = {
131 	.func		= bpf_map_lookup_percpu_elem,
132 	.gpl_only	= false,
133 	.pkt_access	= true,
134 	.ret_type	= RET_PTR_TO_MAP_VALUE_OR_NULL,
135 	.arg1_type	= ARG_CONST_MAP_PTR,
136 	.arg2_type	= ARG_PTR_TO_MAP_KEY,
137 	.arg3_type	= ARG_ANYTHING,
138 };
139 
140 const struct bpf_func_proto bpf_get_prandom_u32_proto = {
141 	.func		= bpf_user_rnd_u32,
142 	.gpl_only	= false,
143 	.ret_type	= RET_INTEGER,
144 };
145 
146 BPF_CALL_0(bpf_get_smp_processor_id)
147 {
148 	return smp_processor_id();
149 }
150 
151 const struct bpf_func_proto bpf_get_smp_processor_id_proto = {
152 	.func		= bpf_get_smp_processor_id,
153 	.gpl_only	= false,
154 	.ret_type	= RET_INTEGER,
155 };
156 
157 BPF_CALL_0(bpf_get_numa_node_id)
158 {
159 	return numa_node_id();
160 }
161 
162 const struct bpf_func_proto bpf_get_numa_node_id_proto = {
163 	.func		= bpf_get_numa_node_id,
164 	.gpl_only	= false,
165 	.ret_type	= RET_INTEGER,
166 };
167 
168 BPF_CALL_0(bpf_ktime_get_ns)
169 {
170 	/* NMI safe access to clock monotonic */
171 	return ktime_get_mono_fast_ns();
172 }
173 
174 const struct bpf_func_proto bpf_ktime_get_ns_proto = {
175 	.func		= bpf_ktime_get_ns,
176 	.gpl_only	= false,
177 	.ret_type	= RET_INTEGER,
178 };
179 
180 BPF_CALL_0(bpf_ktime_get_boot_ns)
181 {
182 	/* NMI safe access to clock boottime */
183 	return ktime_get_boot_fast_ns();
184 }
185 
186 const struct bpf_func_proto bpf_ktime_get_boot_ns_proto = {
187 	.func		= bpf_ktime_get_boot_ns,
188 	.gpl_only	= false,
189 	.ret_type	= RET_INTEGER,
190 };
191 
192 BPF_CALL_0(bpf_ktime_get_coarse_ns)
193 {
194 	return ktime_get_coarse_ns();
195 }
196 
197 const struct bpf_func_proto bpf_ktime_get_coarse_ns_proto = {
198 	.func		= bpf_ktime_get_coarse_ns,
199 	.gpl_only	= false,
200 	.ret_type	= RET_INTEGER,
201 };
202 
203 BPF_CALL_0(bpf_ktime_get_tai_ns)
204 {
205 	/* NMI safe access to clock tai */
206 	return ktime_get_tai_fast_ns();
207 }
208 
209 const struct bpf_func_proto bpf_ktime_get_tai_ns_proto = {
210 	.func		= bpf_ktime_get_tai_ns,
211 	.gpl_only	= false,
212 	.ret_type	= RET_INTEGER,
213 };
214 
215 BPF_CALL_0(bpf_get_current_pid_tgid)
216 {
217 	struct task_struct *task = current;
218 
219 	if (unlikely(!task))
220 		return -EINVAL;
221 
222 	return (u64) task->tgid << 32 | task->pid;
223 }
224 
225 const struct bpf_func_proto bpf_get_current_pid_tgid_proto = {
226 	.func		= bpf_get_current_pid_tgid,
227 	.gpl_only	= false,
228 	.ret_type	= RET_INTEGER,
229 };
230 
231 BPF_CALL_0(bpf_get_current_uid_gid)
232 {
233 	struct task_struct *task = current;
234 	kuid_t uid;
235 	kgid_t gid;
236 
237 	if (unlikely(!task))
238 		return -EINVAL;
239 
240 	current_uid_gid(&uid, &gid);
241 	return (u64) from_kgid(&init_user_ns, gid) << 32 |
242 		     from_kuid(&init_user_ns, uid);
243 }
244 
245 const struct bpf_func_proto bpf_get_current_uid_gid_proto = {
246 	.func		= bpf_get_current_uid_gid,
247 	.gpl_only	= false,
248 	.ret_type	= RET_INTEGER,
249 };
250 
251 BPF_CALL_2(bpf_get_current_comm, char *, buf, u32, size)
252 {
253 	struct task_struct *task = current;
254 
255 	if (unlikely(!task))
256 		goto err_clear;
257 
258 	/* Verifier guarantees that size > 0 */
259 	strscpy(buf, task->comm, size);
260 	return 0;
261 err_clear:
262 	memset(buf, 0, size);
263 	return -EINVAL;
264 }
265 
266 const struct bpf_func_proto bpf_get_current_comm_proto = {
267 	.func		= bpf_get_current_comm,
268 	.gpl_only	= false,
269 	.ret_type	= RET_INTEGER,
270 	.arg1_type	= ARG_PTR_TO_UNINIT_MEM,
271 	.arg2_type	= ARG_CONST_SIZE,
272 };
273 
274 #if defined(CONFIG_QUEUED_SPINLOCKS) || defined(CONFIG_BPF_ARCH_SPINLOCK)
275 
276 static inline void __bpf_spin_lock(struct bpf_spin_lock *lock)
277 {
278 	arch_spinlock_t *l = (void *)lock;
279 	union {
280 		__u32 val;
281 		arch_spinlock_t lock;
282 	} u = { .lock = __ARCH_SPIN_LOCK_UNLOCKED };
283 
284 	compiletime_assert(u.val == 0, "__ARCH_SPIN_LOCK_UNLOCKED not 0");
285 	BUILD_BUG_ON(sizeof(*l) != sizeof(__u32));
286 	BUILD_BUG_ON(sizeof(*lock) != sizeof(__u32));
287 	arch_spin_lock(l);
288 }
289 
290 static inline void __bpf_spin_unlock(struct bpf_spin_lock *lock)
291 {
292 	arch_spinlock_t *l = (void *)lock;
293 
294 	arch_spin_unlock(l);
295 }
296 
297 #else
298 
299 static inline void __bpf_spin_lock(struct bpf_spin_lock *lock)
300 {
301 	atomic_t *l = (void *)lock;
302 
303 	BUILD_BUG_ON(sizeof(*l) != sizeof(*lock));
304 	do {
305 		atomic_cond_read_relaxed(l, !VAL);
306 	} while (atomic_xchg(l, 1));
307 }
308 
309 static inline void __bpf_spin_unlock(struct bpf_spin_lock *lock)
310 {
311 	atomic_t *l = (void *)lock;
312 
313 	atomic_set_release(l, 0);
314 }
315 
316 #endif
317 
318 static DEFINE_PER_CPU(unsigned long, irqsave_flags);
319 
320 static inline void __bpf_spin_lock_irqsave(struct bpf_spin_lock *lock)
321 {
322 	unsigned long flags;
323 
324 	local_irq_save(flags);
325 	__bpf_spin_lock(lock);
326 	__this_cpu_write(irqsave_flags, flags);
327 }
328 
329 notrace BPF_CALL_1(bpf_spin_lock, struct bpf_spin_lock *, lock)
330 {
331 	__bpf_spin_lock_irqsave(lock);
332 	return 0;
333 }
334 
335 const struct bpf_func_proto bpf_spin_lock_proto = {
336 	.func		= bpf_spin_lock,
337 	.gpl_only	= false,
338 	.ret_type	= RET_VOID,
339 	.arg1_type	= ARG_PTR_TO_SPIN_LOCK,
340 	.arg1_btf_id    = BPF_PTR_POISON,
341 };
342 
343 static inline void __bpf_spin_unlock_irqrestore(struct bpf_spin_lock *lock)
344 {
345 	unsigned long flags;
346 
347 	flags = __this_cpu_read(irqsave_flags);
348 	__bpf_spin_unlock(lock);
349 	local_irq_restore(flags);
350 }
351 
352 notrace BPF_CALL_1(bpf_spin_unlock, struct bpf_spin_lock *, lock)
353 {
354 	__bpf_spin_unlock_irqrestore(lock);
355 	return 0;
356 }
357 
358 const struct bpf_func_proto bpf_spin_unlock_proto = {
359 	.func		= bpf_spin_unlock,
360 	.gpl_only	= false,
361 	.ret_type	= RET_VOID,
362 	.arg1_type	= ARG_PTR_TO_SPIN_LOCK,
363 	.arg1_btf_id    = BPF_PTR_POISON,
364 };
365 
366 void copy_map_value_locked(struct bpf_map *map, void *dst, void *src,
367 			   bool lock_src)
368 {
369 	struct bpf_spin_lock *lock;
370 
371 	if (lock_src)
372 		lock = src + map->record->spin_lock_off;
373 	else
374 		lock = dst + map->record->spin_lock_off;
375 	preempt_disable();
376 	__bpf_spin_lock_irqsave(lock);
377 	copy_map_value(map, dst, src);
378 	__bpf_spin_unlock_irqrestore(lock);
379 	preempt_enable();
380 }
381 
382 BPF_CALL_0(bpf_jiffies64)
383 {
384 	return get_jiffies_64();
385 }
386 
387 const struct bpf_func_proto bpf_jiffies64_proto = {
388 	.func		= bpf_jiffies64,
389 	.gpl_only	= false,
390 	.ret_type	= RET_INTEGER,
391 };
392 
393 #ifdef CONFIG_CGROUPS
394 BPF_CALL_0(bpf_get_current_cgroup_id)
395 {
396 	struct cgroup *cgrp;
397 	u64 cgrp_id;
398 
399 	rcu_read_lock();
400 	cgrp = task_dfl_cgroup(current);
401 	cgrp_id = cgroup_id(cgrp);
402 	rcu_read_unlock();
403 
404 	return cgrp_id;
405 }
406 
407 const struct bpf_func_proto bpf_get_current_cgroup_id_proto = {
408 	.func		= bpf_get_current_cgroup_id,
409 	.gpl_only	= false,
410 	.ret_type	= RET_INTEGER,
411 };
412 
413 BPF_CALL_1(bpf_get_current_ancestor_cgroup_id, int, ancestor_level)
414 {
415 	struct cgroup *cgrp;
416 	struct cgroup *ancestor;
417 	u64 cgrp_id;
418 
419 	rcu_read_lock();
420 	cgrp = task_dfl_cgroup(current);
421 	ancestor = cgroup_ancestor(cgrp, ancestor_level);
422 	cgrp_id = ancestor ? cgroup_id(ancestor) : 0;
423 	rcu_read_unlock();
424 
425 	return cgrp_id;
426 }
427 
428 const struct bpf_func_proto bpf_get_current_ancestor_cgroup_id_proto = {
429 	.func		= bpf_get_current_ancestor_cgroup_id,
430 	.gpl_only	= false,
431 	.ret_type	= RET_INTEGER,
432 	.arg1_type	= ARG_ANYTHING,
433 };
434 #endif /* CONFIG_CGROUPS */
435 
436 #define BPF_STRTOX_BASE_MASK 0x1F
437 
438 static int __bpf_strtoull(const char *buf, size_t buf_len, u64 flags,
439 			  unsigned long long *res, bool *is_negative)
440 {
441 	unsigned int base = flags & BPF_STRTOX_BASE_MASK;
442 	const char *cur_buf = buf;
443 	size_t cur_len = buf_len;
444 	unsigned int consumed;
445 	size_t val_len;
446 	char str[64];
447 
448 	if (!buf || !buf_len || !res || !is_negative)
449 		return -EINVAL;
450 
451 	if (base != 0 && base != 8 && base != 10 && base != 16)
452 		return -EINVAL;
453 
454 	if (flags & ~BPF_STRTOX_BASE_MASK)
455 		return -EINVAL;
456 
457 	while (cur_buf < buf + buf_len && isspace(*cur_buf))
458 		++cur_buf;
459 
460 	*is_negative = (cur_buf < buf + buf_len && *cur_buf == '-');
461 	if (*is_negative)
462 		++cur_buf;
463 
464 	consumed = cur_buf - buf;
465 	cur_len -= consumed;
466 	if (!cur_len)
467 		return -EINVAL;
468 
469 	cur_len = min(cur_len, sizeof(str) - 1);
470 	memcpy(str, cur_buf, cur_len);
471 	str[cur_len] = '\0';
472 	cur_buf = str;
473 
474 	cur_buf = _parse_integer_fixup_radix(cur_buf, &base);
475 	val_len = _parse_integer(cur_buf, base, res);
476 
477 	if (val_len & KSTRTOX_OVERFLOW)
478 		return -ERANGE;
479 
480 	if (val_len == 0)
481 		return -EINVAL;
482 
483 	cur_buf += val_len;
484 	consumed += cur_buf - str;
485 
486 	return consumed;
487 }
488 
489 static int __bpf_strtoll(const char *buf, size_t buf_len, u64 flags,
490 			 long long *res)
491 {
492 	unsigned long long _res;
493 	bool is_negative;
494 	int err;
495 
496 	err = __bpf_strtoull(buf, buf_len, flags, &_res, &is_negative);
497 	if (err < 0)
498 		return err;
499 	if (is_negative) {
500 		if ((long long)-_res > 0)
501 			return -ERANGE;
502 		*res = -_res;
503 	} else {
504 		if ((long long)_res < 0)
505 			return -ERANGE;
506 		*res = _res;
507 	}
508 	return err;
509 }
510 
511 BPF_CALL_4(bpf_strtol, const char *, buf, size_t, buf_len, u64, flags,
512 	   long *, res)
513 {
514 	long long _res;
515 	int err;
516 
517 	err = __bpf_strtoll(buf, buf_len, flags, &_res);
518 	if (err < 0)
519 		return err;
520 	if (_res != (long)_res)
521 		return -ERANGE;
522 	*res = _res;
523 	return err;
524 }
525 
526 const struct bpf_func_proto bpf_strtol_proto = {
527 	.func		= bpf_strtol,
528 	.gpl_only	= false,
529 	.ret_type	= RET_INTEGER,
530 	.arg1_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
531 	.arg2_type	= ARG_CONST_SIZE,
532 	.arg3_type	= ARG_ANYTHING,
533 	.arg4_type	= ARG_PTR_TO_LONG,
534 };
535 
536 BPF_CALL_4(bpf_strtoul, const char *, buf, size_t, buf_len, u64, flags,
537 	   unsigned long *, res)
538 {
539 	unsigned long long _res;
540 	bool is_negative;
541 	int err;
542 
543 	err = __bpf_strtoull(buf, buf_len, flags, &_res, &is_negative);
544 	if (err < 0)
545 		return err;
546 	if (is_negative)
547 		return -EINVAL;
548 	if (_res != (unsigned long)_res)
549 		return -ERANGE;
550 	*res = _res;
551 	return err;
552 }
553 
554 const struct bpf_func_proto bpf_strtoul_proto = {
555 	.func		= bpf_strtoul,
556 	.gpl_only	= false,
557 	.ret_type	= RET_INTEGER,
558 	.arg1_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
559 	.arg2_type	= ARG_CONST_SIZE,
560 	.arg3_type	= ARG_ANYTHING,
561 	.arg4_type	= ARG_PTR_TO_LONG,
562 };
563 
564 BPF_CALL_3(bpf_strncmp, const char *, s1, u32, s1_sz, const char *, s2)
565 {
566 	return strncmp(s1, s2, s1_sz);
567 }
568 
569 static const struct bpf_func_proto bpf_strncmp_proto = {
570 	.func		= bpf_strncmp,
571 	.gpl_only	= false,
572 	.ret_type	= RET_INTEGER,
573 	.arg1_type	= ARG_PTR_TO_MEM,
574 	.arg2_type	= ARG_CONST_SIZE,
575 	.arg3_type	= ARG_PTR_TO_CONST_STR,
576 };
577 
578 BPF_CALL_4(bpf_get_ns_current_pid_tgid, u64, dev, u64, ino,
579 	   struct bpf_pidns_info *, nsdata, u32, size)
580 {
581 	struct task_struct *task = current;
582 	struct pid_namespace *pidns;
583 	int err = -EINVAL;
584 
585 	if (unlikely(size != sizeof(struct bpf_pidns_info)))
586 		goto clear;
587 
588 	if (unlikely((u64)(dev_t)dev != dev))
589 		goto clear;
590 
591 	if (unlikely(!task))
592 		goto clear;
593 
594 	pidns = task_active_pid_ns(task);
595 	if (unlikely(!pidns)) {
596 		err = -ENOENT;
597 		goto clear;
598 	}
599 
600 	if (!ns_match(&pidns->ns, (dev_t)dev, ino))
601 		goto clear;
602 
603 	nsdata->pid = task_pid_nr_ns(task, pidns);
604 	nsdata->tgid = task_tgid_nr_ns(task, pidns);
605 	return 0;
606 clear:
607 	memset((void *)nsdata, 0, (size_t) size);
608 	return err;
609 }
610 
611 const struct bpf_func_proto bpf_get_ns_current_pid_tgid_proto = {
612 	.func		= bpf_get_ns_current_pid_tgid,
613 	.gpl_only	= false,
614 	.ret_type	= RET_INTEGER,
615 	.arg1_type	= ARG_ANYTHING,
616 	.arg2_type	= ARG_ANYTHING,
617 	.arg3_type      = ARG_PTR_TO_UNINIT_MEM,
618 	.arg4_type      = ARG_CONST_SIZE,
619 };
620 
621 static const struct bpf_func_proto bpf_get_raw_smp_processor_id_proto = {
622 	.func		= bpf_get_raw_cpu_id,
623 	.gpl_only	= false,
624 	.ret_type	= RET_INTEGER,
625 };
626 
627 BPF_CALL_5(bpf_event_output_data, void *, ctx, struct bpf_map *, map,
628 	   u64, flags, void *, data, u64, size)
629 {
630 	if (unlikely(flags & ~(BPF_F_INDEX_MASK)))
631 		return -EINVAL;
632 
633 	return bpf_event_output(map, flags, data, size, NULL, 0, NULL);
634 }
635 
636 const struct bpf_func_proto bpf_event_output_data_proto =  {
637 	.func		= bpf_event_output_data,
638 	.gpl_only       = true,
639 	.ret_type       = RET_INTEGER,
640 	.arg1_type      = ARG_PTR_TO_CTX,
641 	.arg2_type      = ARG_CONST_MAP_PTR,
642 	.arg3_type      = ARG_ANYTHING,
643 	.arg4_type      = ARG_PTR_TO_MEM | MEM_RDONLY,
644 	.arg5_type      = ARG_CONST_SIZE_OR_ZERO,
645 };
646 
647 BPF_CALL_3(bpf_copy_from_user, void *, dst, u32, size,
648 	   const void __user *, user_ptr)
649 {
650 	int ret = copy_from_user(dst, user_ptr, size);
651 
652 	if (unlikely(ret)) {
653 		memset(dst, 0, size);
654 		ret = -EFAULT;
655 	}
656 
657 	return ret;
658 }
659 
660 const struct bpf_func_proto bpf_copy_from_user_proto = {
661 	.func		= bpf_copy_from_user,
662 	.gpl_only	= false,
663 	.ret_type	= RET_INTEGER,
664 	.arg1_type	= ARG_PTR_TO_UNINIT_MEM,
665 	.arg2_type	= ARG_CONST_SIZE_OR_ZERO,
666 	.arg3_type	= ARG_ANYTHING,
667 };
668 
669 BPF_CALL_5(bpf_copy_from_user_task, void *, dst, u32, size,
670 	   const void __user *, user_ptr, struct task_struct *, tsk, u64, flags)
671 {
672 	int ret;
673 
674 	/* flags is not used yet */
675 	if (unlikely(flags))
676 		return -EINVAL;
677 
678 	if (unlikely(!size))
679 		return 0;
680 
681 	ret = access_process_vm(tsk, (unsigned long)user_ptr, dst, size, 0);
682 	if (ret == size)
683 		return 0;
684 
685 	memset(dst, 0, size);
686 	/* Return -EFAULT for partial read */
687 	return ret < 0 ? ret : -EFAULT;
688 }
689 
690 const struct bpf_func_proto bpf_copy_from_user_task_proto = {
691 	.func		= bpf_copy_from_user_task,
692 	.gpl_only	= true,
693 	.ret_type	= RET_INTEGER,
694 	.arg1_type	= ARG_PTR_TO_UNINIT_MEM,
695 	.arg2_type	= ARG_CONST_SIZE_OR_ZERO,
696 	.arg3_type	= ARG_ANYTHING,
697 	.arg4_type	= ARG_PTR_TO_BTF_ID,
698 	.arg4_btf_id	= &btf_tracing_ids[BTF_TRACING_TYPE_TASK],
699 	.arg5_type	= ARG_ANYTHING
700 };
701 
702 BPF_CALL_2(bpf_per_cpu_ptr, const void *, ptr, u32, cpu)
703 {
704 	if (cpu >= nr_cpu_ids)
705 		return (unsigned long)NULL;
706 
707 	return (unsigned long)per_cpu_ptr((const void __percpu *)ptr, cpu);
708 }
709 
710 const struct bpf_func_proto bpf_per_cpu_ptr_proto = {
711 	.func		= bpf_per_cpu_ptr,
712 	.gpl_only	= false,
713 	.ret_type	= RET_PTR_TO_MEM_OR_BTF_ID | PTR_MAYBE_NULL | MEM_RDONLY,
714 	.arg1_type	= ARG_PTR_TO_PERCPU_BTF_ID,
715 	.arg2_type	= ARG_ANYTHING,
716 };
717 
718 BPF_CALL_1(bpf_this_cpu_ptr, const void *, percpu_ptr)
719 {
720 	return (unsigned long)this_cpu_ptr((const void __percpu *)percpu_ptr);
721 }
722 
723 const struct bpf_func_proto bpf_this_cpu_ptr_proto = {
724 	.func		= bpf_this_cpu_ptr,
725 	.gpl_only	= false,
726 	.ret_type	= RET_PTR_TO_MEM_OR_BTF_ID | MEM_RDONLY,
727 	.arg1_type	= ARG_PTR_TO_PERCPU_BTF_ID,
728 };
729 
730 static int bpf_trace_copy_string(char *buf, void *unsafe_ptr, char fmt_ptype,
731 		size_t bufsz)
732 {
733 	void __user *user_ptr = (__force void __user *)unsafe_ptr;
734 
735 	buf[0] = 0;
736 
737 	switch (fmt_ptype) {
738 	case 's':
739 #ifdef CONFIG_ARCH_HAS_NON_OVERLAPPING_ADDRESS_SPACE
740 		if ((unsigned long)unsafe_ptr < TASK_SIZE)
741 			return strncpy_from_user_nofault(buf, user_ptr, bufsz);
742 		fallthrough;
743 #endif
744 	case 'k':
745 		return strncpy_from_kernel_nofault(buf, unsafe_ptr, bufsz);
746 	case 'u':
747 		return strncpy_from_user_nofault(buf, user_ptr, bufsz);
748 	}
749 
750 	return -EINVAL;
751 }
752 
753 /* Per-cpu temp buffers used by printf-like helpers to store the bprintf binary
754  * arguments representation.
755  */
756 #define MAX_BPRINTF_BUF_LEN	512
757 
758 /* Support executing three nested bprintf helper calls on a given CPU */
759 #define MAX_BPRINTF_NEST_LEVEL	3
760 struct bpf_bprintf_buffers {
761 	char tmp_bufs[MAX_BPRINTF_NEST_LEVEL][MAX_BPRINTF_BUF_LEN];
762 };
763 static DEFINE_PER_CPU(struct bpf_bprintf_buffers, bpf_bprintf_bufs);
764 static DEFINE_PER_CPU(int, bpf_bprintf_nest_level);
765 
766 static int try_get_fmt_tmp_buf(char **tmp_buf)
767 {
768 	struct bpf_bprintf_buffers *bufs;
769 	int nest_level;
770 
771 	preempt_disable();
772 	nest_level = this_cpu_inc_return(bpf_bprintf_nest_level);
773 	if (WARN_ON_ONCE(nest_level > MAX_BPRINTF_NEST_LEVEL)) {
774 		this_cpu_dec(bpf_bprintf_nest_level);
775 		preempt_enable();
776 		return -EBUSY;
777 	}
778 	bufs = this_cpu_ptr(&bpf_bprintf_bufs);
779 	*tmp_buf = bufs->tmp_bufs[nest_level - 1];
780 
781 	return 0;
782 }
783 
784 void bpf_bprintf_cleanup(void)
785 {
786 	if (this_cpu_read(bpf_bprintf_nest_level)) {
787 		this_cpu_dec(bpf_bprintf_nest_level);
788 		preempt_enable();
789 	}
790 }
791 
792 /*
793  * bpf_bprintf_prepare - Generic pass on format strings for bprintf-like helpers
794  *
795  * Returns a negative value if fmt is an invalid format string or 0 otherwise.
796  *
797  * This can be used in two ways:
798  * - Format string verification only: when bin_args is NULL
799  * - Arguments preparation: in addition to the above verification, it writes in
800  *   bin_args a binary representation of arguments usable by bstr_printf where
801  *   pointers from BPF have been sanitized.
802  *
803  * In argument preparation mode, if 0 is returned, safe temporary buffers are
804  * allocated and bpf_bprintf_cleanup should be called to free them after use.
805  */
806 int bpf_bprintf_prepare(char *fmt, u32 fmt_size, const u64 *raw_args,
807 			u32 **bin_args, u32 num_args)
808 {
809 	char *unsafe_ptr = NULL, *tmp_buf = NULL, *tmp_buf_end, *fmt_end;
810 	size_t sizeof_cur_arg, sizeof_cur_ip;
811 	int err, i, num_spec = 0;
812 	u64 cur_arg;
813 	char fmt_ptype, cur_ip[16], ip_spec[] = "%pXX";
814 
815 	fmt_end = strnchr(fmt, fmt_size, 0);
816 	if (!fmt_end)
817 		return -EINVAL;
818 	fmt_size = fmt_end - fmt;
819 
820 	if (bin_args) {
821 		if (num_args && try_get_fmt_tmp_buf(&tmp_buf))
822 			return -EBUSY;
823 
824 		tmp_buf_end = tmp_buf + MAX_BPRINTF_BUF_LEN;
825 		*bin_args = (u32 *)tmp_buf;
826 	}
827 
828 	for (i = 0; i < fmt_size; i++) {
829 		if ((!isprint(fmt[i]) && !isspace(fmt[i])) || !isascii(fmt[i])) {
830 			err = -EINVAL;
831 			goto out;
832 		}
833 
834 		if (fmt[i] != '%')
835 			continue;
836 
837 		if (fmt[i + 1] == '%') {
838 			i++;
839 			continue;
840 		}
841 
842 		if (num_spec >= num_args) {
843 			err = -EINVAL;
844 			goto out;
845 		}
846 
847 		/* The string is zero-terminated so if fmt[i] != 0, we can
848 		 * always access fmt[i + 1], in the worst case it will be a 0
849 		 */
850 		i++;
851 
852 		/* skip optional "[0 +-][num]" width formatting field */
853 		while (fmt[i] == '0' || fmt[i] == '+'  || fmt[i] == '-' ||
854 		       fmt[i] == ' ')
855 			i++;
856 		if (fmt[i] >= '1' && fmt[i] <= '9') {
857 			i++;
858 			while (fmt[i] >= '0' && fmt[i] <= '9')
859 				i++;
860 		}
861 
862 		if (fmt[i] == 'p') {
863 			sizeof_cur_arg = sizeof(long);
864 
865 			if ((fmt[i + 1] == 'k' || fmt[i + 1] == 'u') &&
866 			    fmt[i + 2] == 's') {
867 				fmt_ptype = fmt[i + 1];
868 				i += 2;
869 				goto fmt_str;
870 			}
871 
872 			if (fmt[i + 1] == 0 || isspace(fmt[i + 1]) ||
873 			    ispunct(fmt[i + 1]) || fmt[i + 1] == 'K' ||
874 			    fmt[i + 1] == 'x' || fmt[i + 1] == 's' ||
875 			    fmt[i + 1] == 'S') {
876 				/* just kernel pointers */
877 				if (tmp_buf)
878 					cur_arg = raw_args[num_spec];
879 				i++;
880 				goto nocopy_fmt;
881 			}
882 
883 			if (fmt[i + 1] == 'B') {
884 				if (tmp_buf)  {
885 					err = snprintf(tmp_buf,
886 						       (tmp_buf_end - tmp_buf),
887 						       "%pB",
888 						       (void *)(long)raw_args[num_spec]);
889 					tmp_buf += (err + 1);
890 				}
891 
892 				i++;
893 				num_spec++;
894 				continue;
895 			}
896 
897 			/* only support "%pI4", "%pi4", "%pI6" and "%pi6". */
898 			if ((fmt[i + 1] != 'i' && fmt[i + 1] != 'I') ||
899 			    (fmt[i + 2] != '4' && fmt[i + 2] != '6')) {
900 				err = -EINVAL;
901 				goto out;
902 			}
903 
904 			i += 2;
905 			if (!tmp_buf)
906 				goto nocopy_fmt;
907 
908 			sizeof_cur_ip = (fmt[i] == '4') ? 4 : 16;
909 			if (tmp_buf_end - tmp_buf < sizeof_cur_ip) {
910 				err = -ENOSPC;
911 				goto out;
912 			}
913 
914 			unsafe_ptr = (char *)(long)raw_args[num_spec];
915 			err = copy_from_kernel_nofault(cur_ip, unsafe_ptr,
916 						       sizeof_cur_ip);
917 			if (err < 0)
918 				memset(cur_ip, 0, sizeof_cur_ip);
919 
920 			/* hack: bstr_printf expects IP addresses to be
921 			 * pre-formatted as strings, ironically, the easiest way
922 			 * to do that is to call snprintf.
923 			 */
924 			ip_spec[2] = fmt[i - 1];
925 			ip_spec[3] = fmt[i];
926 			err = snprintf(tmp_buf, tmp_buf_end - tmp_buf,
927 				       ip_spec, &cur_ip);
928 
929 			tmp_buf += err + 1;
930 			num_spec++;
931 
932 			continue;
933 		} else if (fmt[i] == 's') {
934 			fmt_ptype = fmt[i];
935 fmt_str:
936 			if (fmt[i + 1] != 0 &&
937 			    !isspace(fmt[i + 1]) &&
938 			    !ispunct(fmt[i + 1])) {
939 				err = -EINVAL;
940 				goto out;
941 			}
942 
943 			if (!tmp_buf)
944 				goto nocopy_fmt;
945 
946 			if (tmp_buf_end == tmp_buf) {
947 				err = -ENOSPC;
948 				goto out;
949 			}
950 
951 			unsafe_ptr = (char *)(long)raw_args[num_spec];
952 			err = bpf_trace_copy_string(tmp_buf, unsafe_ptr,
953 						    fmt_ptype,
954 						    tmp_buf_end - tmp_buf);
955 			if (err < 0) {
956 				tmp_buf[0] = '\0';
957 				err = 1;
958 			}
959 
960 			tmp_buf += err;
961 			num_spec++;
962 
963 			continue;
964 		} else if (fmt[i] == 'c') {
965 			if (!tmp_buf)
966 				goto nocopy_fmt;
967 
968 			if (tmp_buf_end == tmp_buf) {
969 				err = -ENOSPC;
970 				goto out;
971 			}
972 
973 			*tmp_buf = raw_args[num_spec];
974 			tmp_buf++;
975 			num_spec++;
976 
977 			continue;
978 		}
979 
980 		sizeof_cur_arg = sizeof(int);
981 
982 		if (fmt[i] == 'l') {
983 			sizeof_cur_arg = sizeof(long);
984 			i++;
985 		}
986 		if (fmt[i] == 'l') {
987 			sizeof_cur_arg = sizeof(long long);
988 			i++;
989 		}
990 
991 		if (fmt[i] != 'i' && fmt[i] != 'd' && fmt[i] != 'u' &&
992 		    fmt[i] != 'x' && fmt[i] != 'X') {
993 			err = -EINVAL;
994 			goto out;
995 		}
996 
997 		if (tmp_buf)
998 			cur_arg = raw_args[num_spec];
999 nocopy_fmt:
1000 		if (tmp_buf) {
1001 			tmp_buf = PTR_ALIGN(tmp_buf, sizeof(u32));
1002 			if (tmp_buf_end - tmp_buf < sizeof_cur_arg) {
1003 				err = -ENOSPC;
1004 				goto out;
1005 			}
1006 
1007 			if (sizeof_cur_arg == 8) {
1008 				*(u32 *)tmp_buf = *(u32 *)&cur_arg;
1009 				*(u32 *)(tmp_buf + 4) = *((u32 *)&cur_arg + 1);
1010 			} else {
1011 				*(u32 *)tmp_buf = (u32)(long)cur_arg;
1012 			}
1013 			tmp_buf += sizeof_cur_arg;
1014 		}
1015 		num_spec++;
1016 	}
1017 
1018 	err = 0;
1019 out:
1020 	if (err)
1021 		bpf_bprintf_cleanup();
1022 	return err;
1023 }
1024 
1025 BPF_CALL_5(bpf_snprintf, char *, str, u32, str_size, char *, fmt,
1026 	   const void *, data, u32, data_len)
1027 {
1028 	int err, num_args;
1029 	u32 *bin_args;
1030 
1031 	if (data_len % 8 || data_len > MAX_BPRINTF_VARARGS * 8 ||
1032 	    (data_len && !data))
1033 		return -EINVAL;
1034 	num_args = data_len / 8;
1035 
1036 	/* ARG_PTR_TO_CONST_STR guarantees that fmt is zero-terminated so we
1037 	 * can safely give an unbounded size.
1038 	 */
1039 	err = bpf_bprintf_prepare(fmt, UINT_MAX, data, &bin_args, num_args);
1040 	if (err < 0)
1041 		return err;
1042 
1043 	err = bstr_printf(str, str_size, fmt, bin_args);
1044 
1045 	bpf_bprintf_cleanup();
1046 
1047 	return err + 1;
1048 }
1049 
1050 const struct bpf_func_proto bpf_snprintf_proto = {
1051 	.func		= bpf_snprintf,
1052 	.gpl_only	= true,
1053 	.ret_type	= RET_INTEGER,
1054 	.arg1_type	= ARG_PTR_TO_MEM_OR_NULL,
1055 	.arg2_type	= ARG_CONST_SIZE_OR_ZERO,
1056 	.arg3_type	= ARG_PTR_TO_CONST_STR,
1057 	.arg4_type	= ARG_PTR_TO_MEM | PTR_MAYBE_NULL | MEM_RDONLY,
1058 	.arg5_type	= ARG_CONST_SIZE_OR_ZERO,
1059 };
1060 
1061 /* BPF map elements can contain 'struct bpf_timer'.
1062  * Such map owns all of its BPF timers.
1063  * 'struct bpf_timer' is allocated as part of map element allocation
1064  * and it's zero initialized.
1065  * That space is used to keep 'struct bpf_timer_kern'.
1066  * bpf_timer_init() allocates 'struct bpf_hrtimer', inits hrtimer, and
1067  * remembers 'struct bpf_map *' pointer it's part of.
1068  * bpf_timer_set_callback() increments prog refcnt and assign bpf callback_fn.
1069  * bpf_timer_start() arms the timer.
1070  * If user space reference to a map goes to zero at this point
1071  * ops->map_release_uref callback is responsible for cancelling the timers,
1072  * freeing their memory, and decrementing prog's refcnts.
1073  * bpf_timer_cancel() cancels the timer and decrements prog's refcnt.
1074  * Inner maps can contain bpf timers as well. ops->map_release_uref is
1075  * freeing the timers when inner map is replaced or deleted by user space.
1076  */
1077 struct bpf_hrtimer {
1078 	struct hrtimer timer;
1079 	struct bpf_map *map;
1080 	struct bpf_prog *prog;
1081 	void __rcu *callback_fn;
1082 	void *value;
1083 };
1084 
1085 /* the actual struct hidden inside uapi struct bpf_timer */
1086 struct bpf_timer_kern {
1087 	struct bpf_hrtimer *timer;
1088 	/* bpf_spin_lock is used here instead of spinlock_t to make
1089 	 * sure that it always fits into space reserved by struct bpf_timer
1090 	 * regardless of LOCKDEP and spinlock debug flags.
1091 	 */
1092 	struct bpf_spin_lock lock;
1093 } __attribute__((aligned(8)));
1094 
1095 static DEFINE_PER_CPU(struct bpf_hrtimer *, hrtimer_running);
1096 
1097 static enum hrtimer_restart bpf_timer_cb(struct hrtimer *hrtimer)
1098 {
1099 	struct bpf_hrtimer *t = container_of(hrtimer, struct bpf_hrtimer, timer);
1100 	struct bpf_map *map = t->map;
1101 	void *value = t->value;
1102 	bpf_callback_t callback_fn;
1103 	void *key;
1104 	u32 idx;
1105 
1106 	BTF_TYPE_EMIT(struct bpf_timer);
1107 	callback_fn = rcu_dereference_check(t->callback_fn, rcu_read_lock_bh_held());
1108 	if (!callback_fn)
1109 		goto out;
1110 
1111 	/* bpf_timer_cb() runs in hrtimer_run_softirq. It doesn't migrate and
1112 	 * cannot be preempted by another bpf_timer_cb() on the same cpu.
1113 	 * Remember the timer this callback is servicing to prevent
1114 	 * deadlock if callback_fn() calls bpf_timer_cancel() or
1115 	 * bpf_map_delete_elem() on the same timer.
1116 	 */
1117 	this_cpu_write(hrtimer_running, t);
1118 	if (map->map_type == BPF_MAP_TYPE_ARRAY) {
1119 		struct bpf_array *array = container_of(map, struct bpf_array, map);
1120 
1121 		/* compute the key */
1122 		idx = ((char *)value - array->value) / array->elem_size;
1123 		key = &idx;
1124 	} else { /* hash or lru */
1125 		key = value - round_up(map->key_size, 8);
1126 	}
1127 
1128 	callback_fn((u64)(long)map, (u64)(long)key, (u64)(long)value, 0, 0);
1129 	/* The verifier checked that return value is zero. */
1130 
1131 	this_cpu_write(hrtimer_running, NULL);
1132 out:
1133 	return HRTIMER_NORESTART;
1134 }
1135 
1136 BPF_CALL_3(bpf_timer_init, struct bpf_timer_kern *, timer, struct bpf_map *, map,
1137 	   u64, flags)
1138 {
1139 	clockid_t clockid = flags & (MAX_CLOCKS - 1);
1140 	struct bpf_hrtimer *t;
1141 	int ret = 0;
1142 
1143 	BUILD_BUG_ON(MAX_CLOCKS != 16);
1144 	BUILD_BUG_ON(sizeof(struct bpf_timer_kern) > sizeof(struct bpf_timer));
1145 	BUILD_BUG_ON(__alignof__(struct bpf_timer_kern) != __alignof__(struct bpf_timer));
1146 
1147 	if (in_nmi())
1148 		return -EOPNOTSUPP;
1149 
1150 	if (flags >= MAX_CLOCKS ||
1151 	    /* similar to timerfd except _ALARM variants are not supported */
1152 	    (clockid != CLOCK_MONOTONIC &&
1153 	     clockid != CLOCK_REALTIME &&
1154 	     clockid != CLOCK_BOOTTIME))
1155 		return -EINVAL;
1156 	__bpf_spin_lock_irqsave(&timer->lock);
1157 	t = timer->timer;
1158 	if (t) {
1159 		ret = -EBUSY;
1160 		goto out;
1161 	}
1162 	if (!atomic64_read(&map->usercnt)) {
1163 		/* maps with timers must be either held by user space
1164 		 * or pinned in bpffs.
1165 		 */
1166 		ret = -EPERM;
1167 		goto out;
1168 	}
1169 	/* allocate hrtimer via map_kmalloc to use memcg accounting */
1170 	t = bpf_map_kmalloc_node(map, sizeof(*t), GFP_ATOMIC, map->numa_node);
1171 	if (!t) {
1172 		ret = -ENOMEM;
1173 		goto out;
1174 	}
1175 	t->value = (void *)timer - map->record->timer_off;
1176 	t->map = map;
1177 	t->prog = NULL;
1178 	rcu_assign_pointer(t->callback_fn, NULL);
1179 	hrtimer_init(&t->timer, clockid, HRTIMER_MODE_REL_SOFT);
1180 	t->timer.function = bpf_timer_cb;
1181 	timer->timer = t;
1182 out:
1183 	__bpf_spin_unlock_irqrestore(&timer->lock);
1184 	return ret;
1185 }
1186 
1187 static const struct bpf_func_proto bpf_timer_init_proto = {
1188 	.func		= bpf_timer_init,
1189 	.gpl_only	= true,
1190 	.ret_type	= RET_INTEGER,
1191 	.arg1_type	= ARG_PTR_TO_TIMER,
1192 	.arg2_type	= ARG_CONST_MAP_PTR,
1193 	.arg3_type	= ARG_ANYTHING,
1194 };
1195 
1196 BPF_CALL_3(bpf_timer_set_callback, struct bpf_timer_kern *, timer, void *, callback_fn,
1197 	   struct bpf_prog_aux *, aux)
1198 {
1199 	struct bpf_prog *prev, *prog = aux->prog;
1200 	struct bpf_hrtimer *t;
1201 	int ret = 0;
1202 
1203 	if (in_nmi())
1204 		return -EOPNOTSUPP;
1205 	__bpf_spin_lock_irqsave(&timer->lock);
1206 	t = timer->timer;
1207 	if (!t) {
1208 		ret = -EINVAL;
1209 		goto out;
1210 	}
1211 	if (!atomic64_read(&t->map->usercnt)) {
1212 		/* maps with timers must be either held by user space
1213 		 * or pinned in bpffs. Otherwise timer might still be
1214 		 * running even when bpf prog is detached and user space
1215 		 * is gone, since map_release_uref won't ever be called.
1216 		 */
1217 		ret = -EPERM;
1218 		goto out;
1219 	}
1220 	prev = t->prog;
1221 	if (prev != prog) {
1222 		/* Bump prog refcnt once. Every bpf_timer_set_callback()
1223 		 * can pick different callback_fn-s within the same prog.
1224 		 */
1225 		prog = bpf_prog_inc_not_zero(prog);
1226 		if (IS_ERR(prog)) {
1227 			ret = PTR_ERR(prog);
1228 			goto out;
1229 		}
1230 		if (prev)
1231 			/* Drop prev prog refcnt when swapping with new prog */
1232 			bpf_prog_put(prev);
1233 		t->prog = prog;
1234 	}
1235 	rcu_assign_pointer(t->callback_fn, callback_fn);
1236 out:
1237 	__bpf_spin_unlock_irqrestore(&timer->lock);
1238 	return ret;
1239 }
1240 
1241 static const struct bpf_func_proto bpf_timer_set_callback_proto = {
1242 	.func		= bpf_timer_set_callback,
1243 	.gpl_only	= true,
1244 	.ret_type	= RET_INTEGER,
1245 	.arg1_type	= ARG_PTR_TO_TIMER,
1246 	.arg2_type	= ARG_PTR_TO_FUNC,
1247 };
1248 
1249 BPF_CALL_3(bpf_timer_start, struct bpf_timer_kern *, timer, u64, nsecs, u64, flags)
1250 {
1251 	struct bpf_hrtimer *t;
1252 	int ret = 0;
1253 
1254 	if (in_nmi())
1255 		return -EOPNOTSUPP;
1256 	if (flags)
1257 		return -EINVAL;
1258 	__bpf_spin_lock_irqsave(&timer->lock);
1259 	t = timer->timer;
1260 	if (!t || !t->prog) {
1261 		ret = -EINVAL;
1262 		goto out;
1263 	}
1264 	hrtimer_start(&t->timer, ns_to_ktime(nsecs), HRTIMER_MODE_REL_SOFT);
1265 out:
1266 	__bpf_spin_unlock_irqrestore(&timer->lock);
1267 	return ret;
1268 }
1269 
1270 static const struct bpf_func_proto bpf_timer_start_proto = {
1271 	.func		= bpf_timer_start,
1272 	.gpl_only	= true,
1273 	.ret_type	= RET_INTEGER,
1274 	.arg1_type	= ARG_PTR_TO_TIMER,
1275 	.arg2_type	= ARG_ANYTHING,
1276 	.arg3_type	= ARG_ANYTHING,
1277 };
1278 
1279 static void drop_prog_refcnt(struct bpf_hrtimer *t)
1280 {
1281 	struct bpf_prog *prog = t->prog;
1282 
1283 	if (prog) {
1284 		bpf_prog_put(prog);
1285 		t->prog = NULL;
1286 		rcu_assign_pointer(t->callback_fn, NULL);
1287 	}
1288 }
1289 
1290 BPF_CALL_1(bpf_timer_cancel, struct bpf_timer_kern *, timer)
1291 {
1292 	struct bpf_hrtimer *t;
1293 	int ret = 0;
1294 
1295 	if (in_nmi())
1296 		return -EOPNOTSUPP;
1297 	__bpf_spin_lock_irqsave(&timer->lock);
1298 	t = timer->timer;
1299 	if (!t) {
1300 		ret = -EINVAL;
1301 		goto out;
1302 	}
1303 	if (this_cpu_read(hrtimer_running) == t) {
1304 		/* If bpf callback_fn is trying to bpf_timer_cancel()
1305 		 * its own timer the hrtimer_cancel() will deadlock
1306 		 * since it waits for callback_fn to finish
1307 		 */
1308 		ret = -EDEADLK;
1309 		goto out;
1310 	}
1311 	drop_prog_refcnt(t);
1312 out:
1313 	__bpf_spin_unlock_irqrestore(&timer->lock);
1314 	/* Cancel the timer and wait for associated callback to finish
1315 	 * if it was running.
1316 	 */
1317 	ret = ret ?: hrtimer_cancel(&t->timer);
1318 	return ret;
1319 }
1320 
1321 static const struct bpf_func_proto bpf_timer_cancel_proto = {
1322 	.func		= bpf_timer_cancel,
1323 	.gpl_only	= true,
1324 	.ret_type	= RET_INTEGER,
1325 	.arg1_type	= ARG_PTR_TO_TIMER,
1326 };
1327 
1328 /* This function is called by map_delete/update_elem for individual element and
1329  * by ops->map_release_uref when the user space reference to a map reaches zero.
1330  */
1331 void bpf_timer_cancel_and_free(void *val)
1332 {
1333 	struct bpf_timer_kern *timer = val;
1334 	struct bpf_hrtimer *t;
1335 
1336 	/* Performance optimization: read timer->timer without lock first. */
1337 	if (!READ_ONCE(timer->timer))
1338 		return;
1339 
1340 	__bpf_spin_lock_irqsave(&timer->lock);
1341 	/* re-read it under lock */
1342 	t = timer->timer;
1343 	if (!t)
1344 		goto out;
1345 	drop_prog_refcnt(t);
1346 	/* The subsequent bpf_timer_start/cancel() helpers won't be able to use
1347 	 * this timer, since it won't be initialized.
1348 	 */
1349 	timer->timer = NULL;
1350 out:
1351 	__bpf_spin_unlock_irqrestore(&timer->lock);
1352 	if (!t)
1353 		return;
1354 	/* Cancel the timer and wait for callback to complete if it was running.
1355 	 * If hrtimer_cancel() can be safely called it's safe to call kfree(t)
1356 	 * right after for both preallocated and non-preallocated maps.
1357 	 * The timer->timer = NULL was already done and no code path can
1358 	 * see address 't' anymore.
1359 	 *
1360 	 * Check that bpf_map_delete/update_elem() wasn't called from timer
1361 	 * callback_fn. In such case don't call hrtimer_cancel() (since it will
1362 	 * deadlock) and don't call hrtimer_try_to_cancel() (since it will just
1363 	 * return -1). Though callback_fn is still running on this cpu it's
1364 	 * safe to do kfree(t) because bpf_timer_cb() read everything it needed
1365 	 * from 't'. The bpf subprog callback_fn won't be able to access 't',
1366 	 * since timer->timer = NULL was already done. The timer will be
1367 	 * effectively cancelled because bpf_timer_cb() will return
1368 	 * HRTIMER_NORESTART.
1369 	 */
1370 	if (this_cpu_read(hrtimer_running) != t)
1371 		hrtimer_cancel(&t->timer);
1372 	kfree(t);
1373 }
1374 
1375 BPF_CALL_2(bpf_kptr_xchg, void *, map_value, void *, ptr)
1376 {
1377 	unsigned long *kptr = map_value;
1378 
1379 	return xchg(kptr, (unsigned long)ptr);
1380 }
1381 
1382 /* Unlike other PTR_TO_BTF_ID helpers the btf_id in bpf_kptr_xchg()
1383  * helper is determined dynamically by the verifier. Use BPF_PTR_POISON to
1384  * denote type that verifier will determine.
1385  */
1386 static const struct bpf_func_proto bpf_kptr_xchg_proto = {
1387 	.func         = bpf_kptr_xchg,
1388 	.gpl_only     = false,
1389 	.ret_type     = RET_PTR_TO_BTF_ID_OR_NULL,
1390 	.ret_btf_id   = BPF_PTR_POISON,
1391 	.arg1_type    = ARG_PTR_TO_KPTR,
1392 	.arg2_type    = ARG_PTR_TO_BTF_ID_OR_NULL | OBJ_RELEASE,
1393 	.arg2_btf_id  = BPF_PTR_POISON,
1394 };
1395 
1396 /* Since the upper 8 bits of dynptr->size is reserved, the
1397  * maximum supported size is 2^24 - 1.
1398  */
1399 #define DYNPTR_MAX_SIZE	((1UL << 24) - 1)
1400 #define DYNPTR_TYPE_SHIFT	28
1401 #define DYNPTR_SIZE_MASK	0xFFFFFF
1402 #define DYNPTR_RDONLY_BIT	BIT(31)
1403 
1404 static bool bpf_dynptr_is_rdonly(struct bpf_dynptr_kern *ptr)
1405 {
1406 	return ptr->size & DYNPTR_RDONLY_BIT;
1407 }
1408 
1409 static void bpf_dynptr_set_type(struct bpf_dynptr_kern *ptr, enum bpf_dynptr_type type)
1410 {
1411 	ptr->size |= type << DYNPTR_TYPE_SHIFT;
1412 }
1413 
1414 u32 bpf_dynptr_get_size(struct bpf_dynptr_kern *ptr)
1415 {
1416 	return ptr->size & DYNPTR_SIZE_MASK;
1417 }
1418 
1419 int bpf_dynptr_check_size(u32 size)
1420 {
1421 	return size > DYNPTR_MAX_SIZE ? -E2BIG : 0;
1422 }
1423 
1424 void bpf_dynptr_init(struct bpf_dynptr_kern *ptr, void *data,
1425 		     enum bpf_dynptr_type type, u32 offset, u32 size)
1426 {
1427 	ptr->data = data;
1428 	ptr->offset = offset;
1429 	ptr->size = size;
1430 	bpf_dynptr_set_type(ptr, type);
1431 }
1432 
1433 void bpf_dynptr_set_null(struct bpf_dynptr_kern *ptr)
1434 {
1435 	memset(ptr, 0, sizeof(*ptr));
1436 }
1437 
1438 static int bpf_dynptr_check_off_len(struct bpf_dynptr_kern *ptr, u32 offset, u32 len)
1439 {
1440 	u32 size = bpf_dynptr_get_size(ptr);
1441 
1442 	if (len > size || offset > size - len)
1443 		return -E2BIG;
1444 
1445 	return 0;
1446 }
1447 
1448 BPF_CALL_4(bpf_dynptr_from_mem, void *, data, u32, size, u64, flags, struct bpf_dynptr_kern *, ptr)
1449 {
1450 	int err;
1451 
1452 	BTF_TYPE_EMIT(struct bpf_dynptr);
1453 
1454 	err = bpf_dynptr_check_size(size);
1455 	if (err)
1456 		goto error;
1457 
1458 	/* flags is currently unsupported */
1459 	if (flags) {
1460 		err = -EINVAL;
1461 		goto error;
1462 	}
1463 
1464 	bpf_dynptr_init(ptr, data, BPF_DYNPTR_TYPE_LOCAL, 0, size);
1465 
1466 	return 0;
1467 
1468 error:
1469 	bpf_dynptr_set_null(ptr);
1470 	return err;
1471 }
1472 
1473 static const struct bpf_func_proto bpf_dynptr_from_mem_proto = {
1474 	.func		= bpf_dynptr_from_mem,
1475 	.gpl_only	= false,
1476 	.ret_type	= RET_INTEGER,
1477 	.arg1_type	= ARG_PTR_TO_UNINIT_MEM,
1478 	.arg2_type	= ARG_CONST_SIZE_OR_ZERO,
1479 	.arg3_type	= ARG_ANYTHING,
1480 	.arg4_type	= ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_LOCAL | MEM_UNINIT,
1481 };
1482 
1483 BPF_CALL_5(bpf_dynptr_read, void *, dst, u32, len, struct bpf_dynptr_kern *, src,
1484 	   u32, offset, u64, flags)
1485 {
1486 	int err;
1487 
1488 	if (!src->data || flags)
1489 		return -EINVAL;
1490 
1491 	err = bpf_dynptr_check_off_len(src, offset, len);
1492 	if (err)
1493 		return err;
1494 
1495 	memcpy(dst, src->data + src->offset + offset, len);
1496 
1497 	return 0;
1498 }
1499 
1500 static const struct bpf_func_proto bpf_dynptr_read_proto = {
1501 	.func		= bpf_dynptr_read,
1502 	.gpl_only	= false,
1503 	.ret_type	= RET_INTEGER,
1504 	.arg1_type	= ARG_PTR_TO_UNINIT_MEM,
1505 	.arg2_type	= ARG_CONST_SIZE_OR_ZERO,
1506 	.arg3_type	= ARG_PTR_TO_DYNPTR,
1507 	.arg4_type	= ARG_ANYTHING,
1508 	.arg5_type	= ARG_ANYTHING,
1509 };
1510 
1511 BPF_CALL_5(bpf_dynptr_write, struct bpf_dynptr_kern *, dst, u32, offset, void *, src,
1512 	   u32, len, u64, flags)
1513 {
1514 	int err;
1515 
1516 	if (!dst->data || flags || bpf_dynptr_is_rdonly(dst))
1517 		return -EINVAL;
1518 
1519 	err = bpf_dynptr_check_off_len(dst, offset, len);
1520 	if (err)
1521 		return err;
1522 
1523 	memcpy(dst->data + dst->offset + offset, src, len);
1524 
1525 	return 0;
1526 }
1527 
1528 static const struct bpf_func_proto bpf_dynptr_write_proto = {
1529 	.func		= bpf_dynptr_write,
1530 	.gpl_only	= false,
1531 	.ret_type	= RET_INTEGER,
1532 	.arg1_type	= ARG_PTR_TO_DYNPTR,
1533 	.arg2_type	= ARG_ANYTHING,
1534 	.arg3_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
1535 	.arg4_type	= ARG_CONST_SIZE_OR_ZERO,
1536 	.arg5_type	= ARG_ANYTHING,
1537 };
1538 
1539 BPF_CALL_3(bpf_dynptr_data, struct bpf_dynptr_kern *, ptr, u32, offset, u32, len)
1540 {
1541 	int err;
1542 
1543 	if (!ptr->data)
1544 		return 0;
1545 
1546 	err = bpf_dynptr_check_off_len(ptr, offset, len);
1547 	if (err)
1548 		return 0;
1549 
1550 	if (bpf_dynptr_is_rdonly(ptr))
1551 		return 0;
1552 
1553 	return (unsigned long)(ptr->data + ptr->offset + offset);
1554 }
1555 
1556 static const struct bpf_func_proto bpf_dynptr_data_proto = {
1557 	.func		= bpf_dynptr_data,
1558 	.gpl_only	= false,
1559 	.ret_type	= RET_PTR_TO_DYNPTR_MEM_OR_NULL,
1560 	.arg1_type	= ARG_PTR_TO_DYNPTR,
1561 	.arg2_type	= ARG_ANYTHING,
1562 	.arg3_type	= ARG_CONST_ALLOC_SIZE_OR_ZERO,
1563 };
1564 
1565 const struct bpf_func_proto bpf_get_current_task_proto __weak;
1566 const struct bpf_func_proto bpf_get_current_task_btf_proto __weak;
1567 const struct bpf_func_proto bpf_probe_read_user_proto __weak;
1568 const struct bpf_func_proto bpf_probe_read_user_str_proto __weak;
1569 const struct bpf_func_proto bpf_probe_read_kernel_proto __weak;
1570 const struct bpf_func_proto bpf_probe_read_kernel_str_proto __weak;
1571 const struct bpf_func_proto bpf_task_pt_regs_proto __weak;
1572 
1573 const struct bpf_func_proto *
1574 bpf_base_func_proto(enum bpf_func_id func_id)
1575 {
1576 	switch (func_id) {
1577 	case BPF_FUNC_map_lookup_elem:
1578 		return &bpf_map_lookup_elem_proto;
1579 	case BPF_FUNC_map_update_elem:
1580 		return &bpf_map_update_elem_proto;
1581 	case BPF_FUNC_map_delete_elem:
1582 		return &bpf_map_delete_elem_proto;
1583 	case BPF_FUNC_map_push_elem:
1584 		return &bpf_map_push_elem_proto;
1585 	case BPF_FUNC_map_pop_elem:
1586 		return &bpf_map_pop_elem_proto;
1587 	case BPF_FUNC_map_peek_elem:
1588 		return &bpf_map_peek_elem_proto;
1589 	case BPF_FUNC_map_lookup_percpu_elem:
1590 		return &bpf_map_lookup_percpu_elem_proto;
1591 	case BPF_FUNC_get_prandom_u32:
1592 		return &bpf_get_prandom_u32_proto;
1593 	case BPF_FUNC_get_smp_processor_id:
1594 		return &bpf_get_raw_smp_processor_id_proto;
1595 	case BPF_FUNC_get_numa_node_id:
1596 		return &bpf_get_numa_node_id_proto;
1597 	case BPF_FUNC_tail_call:
1598 		return &bpf_tail_call_proto;
1599 	case BPF_FUNC_ktime_get_ns:
1600 		return &bpf_ktime_get_ns_proto;
1601 	case BPF_FUNC_ktime_get_boot_ns:
1602 		return &bpf_ktime_get_boot_ns_proto;
1603 	case BPF_FUNC_ktime_get_tai_ns:
1604 		return &bpf_ktime_get_tai_ns_proto;
1605 	case BPF_FUNC_ringbuf_output:
1606 		return &bpf_ringbuf_output_proto;
1607 	case BPF_FUNC_ringbuf_reserve:
1608 		return &bpf_ringbuf_reserve_proto;
1609 	case BPF_FUNC_ringbuf_submit:
1610 		return &bpf_ringbuf_submit_proto;
1611 	case BPF_FUNC_ringbuf_discard:
1612 		return &bpf_ringbuf_discard_proto;
1613 	case BPF_FUNC_ringbuf_query:
1614 		return &bpf_ringbuf_query_proto;
1615 	case BPF_FUNC_strncmp:
1616 		return &bpf_strncmp_proto;
1617 	case BPF_FUNC_strtol:
1618 		return &bpf_strtol_proto;
1619 	case BPF_FUNC_strtoul:
1620 		return &bpf_strtoul_proto;
1621 	default:
1622 		break;
1623 	}
1624 
1625 	if (!bpf_capable())
1626 		return NULL;
1627 
1628 	switch (func_id) {
1629 	case BPF_FUNC_spin_lock:
1630 		return &bpf_spin_lock_proto;
1631 	case BPF_FUNC_spin_unlock:
1632 		return &bpf_spin_unlock_proto;
1633 	case BPF_FUNC_jiffies64:
1634 		return &bpf_jiffies64_proto;
1635 	case BPF_FUNC_per_cpu_ptr:
1636 		return &bpf_per_cpu_ptr_proto;
1637 	case BPF_FUNC_this_cpu_ptr:
1638 		return &bpf_this_cpu_ptr_proto;
1639 	case BPF_FUNC_timer_init:
1640 		return &bpf_timer_init_proto;
1641 	case BPF_FUNC_timer_set_callback:
1642 		return &bpf_timer_set_callback_proto;
1643 	case BPF_FUNC_timer_start:
1644 		return &bpf_timer_start_proto;
1645 	case BPF_FUNC_timer_cancel:
1646 		return &bpf_timer_cancel_proto;
1647 	case BPF_FUNC_kptr_xchg:
1648 		return &bpf_kptr_xchg_proto;
1649 	case BPF_FUNC_for_each_map_elem:
1650 		return &bpf_for_each_map_elem_proto;
1651 	case BPF_FUNC_loop:
1652 		return &bpf_loop_proto;
1653 	case BPF_FUNC_user_ringbuf_drain:
1654 		return &bpf_user_ringbuf_drain_proto;
1655 	case BPF_FUNC_ringbuf_reserve_dynptr:
1656 		return &bpf_ringbuf_reserve_dynptr_proto;
1657 	case BPF_FUNC_ringbuf_submit_dynptr:
1658 		return &bpf_ringbuf_submit_dynptr_proto;
1659 	case BPF_FUNC_ringbuf_discard_dynptr:
1660 		return &bpf_ringbuf_discard_dynptr_proto;
1661 	case BPF_FUNC_dynptr_from_mem:
1662 		return &bpf_dynptr_from_mem_proto;
1663 	case BPF_FUNC_dynptr_read:
1664 		return &bpf_dynptr_read_proto;
1665 	case BPF_FUNC_dynptr_write:
1666 		return &bpf_dynptr_write_proto;
1667 	case BPF_FUNC_dynptr_data:
1668 		return &bpf_dynptr_data_proto;
1669 #ifdef CONFIG_CGROUPS
1670 	case BPF_FUNC_cgrp_storage_get:
1671 		return &bpf_cgrp_storage_get_proto;
1672 	case BPF_FUNC_cgrp_storage_delete:
1673 		return &bpf_cgrp_storage_delete_proto;
1674 #endif
1675 	default:
1676 		break;
1677 	}
1678 
1679 	if (!perfmon_capable())
1680 		return NULL;
1681 
1682 	switch (func_id) {
1683 	case BPF_FUNC_trace_printk:
1684 		return bpf_get_trace_printk_proto();
1685 	case BPF_FUNC_get_current_task:
1686 		return &bpf_get_current_task_proto;
1687 	case BPF_FUNC_get_current_task_btf:
1688 		return &bpf_get_current_task_btf_proto;
1689 	case BPF_FUNC_probe_read_user:
1690 		return &bpf_probe_read_user_proto;
1691 	case BPF_FUNC_probe_read_kernel:
1692 		return security_locked_down(LOCKDOWN_BPF_READ_KERNEL) < 0 ?
1693 		       NULL : &bpf_probe_read_kernel_proto;
1694 	case BPF_FUNC_probe_read_user_str:
1695 		return &bpf_probe_read_user_str_proto;
1696 	case BPF_FUNC_probe_read_kernel_str:
1697 		return security_locked_down(LOCKDOWN_BPF_READ_KERNEL) < 0 ?
1698 		       NULL : &bpf_probe_read_kernel_str_proto;
1699 	case BPF_FUNC_snprintf_btf:
1700 		return &bpf_snprintf_btf_proto;
1701 	case BPF_FUNC_snprintf:
1702 		return &bpf_snprintf_proto;
1703 	case BPF_FUNC_task_pt_regs:
1704 		return &bpf_task_pt_regs_proto;
1705 	case BPF_FUNC_trace_vprintk:
1706 		return bpf_get_trace_vprintk_proto();
1707 	default:
1708 		return NULL;
1709 	}
1710 }
1711 
1712 void bpf_list_head_free(const struct btf_field *field, void *list_head,
1713 			struct bpf_spin_lock *spin_lock)
1714 {
1715 	struct list_head *head = list_head, *orig_head = list_head;
1716 
1717 	BUILD_BUG_ON(sizeof(struct list_head) > sizeof(struct bpf_list_head));
1718 	BUILD_BUG_ON(__alignof__(struct list_head) > __alignof__(struct bpf_list_head));
1719 
1720 	/* Do the actual list draining outside the lock to not hold the lock for
1721 	 * too long, and also prevent deadlocks if tracing programs end up
1722 	 * executing on entry/exit of functions called inside the critical
1723 	 * section, and end up doing map ops that call bpf_list_head_free for
1724 	 * the same map value again.
1725 	 */
1726 	__bpf_spin_lock_irqsave(spin_lock);
1727 	if (!head->next || list_empty(head))
1728 		goto unlock;
1729 	head = head->next;
1730 unlock:
1731 	INIT_LIST_HEAD(orig_head);
1732 	__bpf_spin_unlock_irqrestore(spin_lock);
1733 
1734 	while (head != orig_head) {
1735 		void *obj = head;
1736 
1737 		obj -= field->list_head.node_offset;
1738 		head = head->next;
1739 		/* The contained type can also have resources, including a
1740 		 * bpf_list_head which needs to be freed.
1741 		 */
1742 		bpf_obj_free_fields(field->list_head.value_rec, obj);
1743 		/* bpf_mem_free requires migrate_disable(), since we can be
1744 		 * called from map free path as well apart from BPF program (as
1745 		 * part of map ops doing bpf_obj_free_fields).
1746 		 */
1747 		migrate_disable();
1748 		bpf_mem_free(&bpf_global_ma, obj);
1749 		migrate_enable();
1750 	}
1751 }
1752 
1753 __diag_push();
1754 __diag_ignore_all("-Wmissing-prototypes",
1755 		  "Global functions as their definitions will be in vmlinux BTF");
1756 
1757 void *bpf_obj_new_impl(u64 local_type_id__k, void *meta__ign)
1758 {
1759 	struct btf_struct_meta *meta = meta__ign;
1760 	u64 size = local_type_id__k;
1761 	void *p;
1762 
1763 	p = bpf_mem_alloc(&bpf_global_ma, size);
1764 	if (!p)
1765 		return NULL;
1766 	if (meta)
1767 		bpf_obj_init(meta->field_offs, p);
1768 	return p;
1769 }
1770 
1771 void bpf_obj_drop_impl(void *p__alloc, void *meta__ign)
1772 {
1773 	struct btf_struct_meta *meta = meta__ign;
1774 	void *p = p__alloc;
1775 
1776 	if (meta)
1777 		bpf_obj_free_fields(meta->record, p);
1778 	bpf_mem_free(&bpf_global_ma, p);
1779 }
1780 
1781 static void __bpf_list_add(struct bpf_list_node *node, struct bpf_list_head *head, bool tail)
1782 {
1783 	struct list_head *n = (void *)node, *h = (void *)head;
1784 
1785 	if (unlikely(!h->next))
1786 		INIT_LIST_HEAD(h);
1787 	if (unlikely(!n->next))
1788 		INIT_LIST_HEAD(n);
1789 	tail ? list_add_tail(n, h) : list_add(n, h);
1790 }
1791 
1792 void bpf_list_push_front(struct bpf_list_head *head, struct bpf_list_node *node)
1793 {
1794 	return __bpf_list_add(node, head, false);
1795 }
1796 
1797 void bpf_list_push_back(struct bpf_list_head *head, struct bpf_list_node *node)
1798 {
1799 	return __bpf_list_add(node, head, true);
1800 }
1801 
1802 static struct bpf_list_node *__bpf_list_del(struct bpf_list_head *head, bool tail)
1803 {
1804 	struct list_head *n, *h = (void *)head;
1805 
1806 	if (unlikely(!h->next))
1807 		INIT_LIST_HEAD(h);
1808 	if (list_empty(h))
1809 		return NULL;
1810 	n = tail ? h->prev : h->next;
1811 	list_del_init(n);
1812 	return (struct bpf_list_node *)n;
1813 }
1814 
1815 struct bpf_list_node *bpf_list_pop_front(struct bpf_list_head *head)
1816 {
1817 	return __bpf_list_del(head, false);
1818 }
1819 
1820 struct bpf_list_node *bpf_list_pop_back(struct bpf_list_head *head)
1821 {
1822 	return __bpf_list_del(head, true);
1823 }
1824 
1825 /**
1826  * bpf_task_acquire - Acquire a reference to a task. A task acquired by this
1827  * kfunc which is not stored in a map as a kptr, must be released by calling
1828  * bpf_task_release().
1829  * @p: The task on which a reference is being acquired.
1830  */
1831 struct task_struct *bpf_task_acquire(struct task_struct *p)
1832 {
1833 	refcount_inc(&p->rcu_users);
1834 	return p;
1835 }
1836 
1837 /**
1838  * bpf_task_kptr_get - Acquire a reference on a struct task_struct kptr. A task
1839  * kptr acquired by this kfunc which is not subsequently stored in a map, must
1840  * be released by calling bpf_task_release().
1841  * @pp: A pointer to a task kptr on which a reference is being acquired.
1842  */
1843 struct task_struct *bpf_task_kptr_get(struct task_struct **pp)
1844 {
1845 	struct task_struct *p;
1846 
1847 	rcu_read_lock();
1848 	p = READ_ONCE(*pp);
1849 
1850 	/* Another context could remove the task from the map and release it at
1851 	 * any time, including after we've done the lookup above. This is safe
1852 	 * because we're in an RCU read region, so the task is guaranteed to
1853 	 * remain valid until at least the rcu_read_unlock() below.
1854 	 */
1855 	if (p && !refcount_inc_not_zero(&p->rcu_users))
1856 		/* If the task had been removed from the map and freed as
1857 		 * described above, refcount_inc_not_zero() will return false.
1858 		 * The task will be freed at some point after the current RCU
1859 		 * gp has ended, so just return NULL to the user.
1860 		 */
1861 		p = NULL;
1862 	rcu_read_unlock();
1863 
1864 	return p;
1865 }
1866 
1867 /**
1868  * bpf_task_release - Release the reference acquired on a struct task_struct *.
1869  * If this kfunc is invoked in an RCU read region, the task_struct is
1870  * guaranteed to not be freed until the current grace period has ended, even if
1871  * its refcount drops to 0.
1872  * @p: The task on which a reference is being released.
1873  */
1874 void bpf_task_release(struct task_struct *p)
1875 {
1876 	if (!p)
1877 		return;
1878 
1879 	put_task_struct_rcu_user(p);
1880 }
1881 
1882 void *bpf_cast_to_kern_ctx(void *obj)
1883 {
1884 	return obj;
1885 }
1886 
1887 void *bpf_rdonly_cast(void *obj__ign, u32 btf_id__k)
1888 {
1889 	return obj__ign;
1890 }
1891 
1892 __diag_pop();
1893 
1894 BTF_SET8_START(generic_btf_ids)
1895 #ifdef CONFIG_KEXEC_CORE
1896 BTF_ID_FLAGS(func, crash_kexec, KF_DESTRUCTIVE)
1897 #endif
1898 BTF_ID_FLAGS(func, bpf_obj_new_impl, KF_ACQUIRE | KF_RET_NULL)
1899 BTF_ID_FLAGS(func, bpf_obj_drop_impl, KF_RELEASE)
1900 BTF_ID_FLAGS(func, bpf_list_push_front)
1901 BTF_ID_FLAGS(func, bpf_list_push_back)
1902 BTF_ID_FLAGS(func, bpf_list_pop_front, KF_ACQUIRE | KF_RET_NULL)
1903 BTF_ID_FLAGS(func, bpf_list_pop_back, KF_ACQUIRE | KF_RET_NULL)
1904 BTF_ID_FLAGS(func, bpf_task_acquire, KF_ACQUIRE | KF_TRUSTED_ARGS)
1905 BTF_ID_FLAGS(func, bpf_task_kptr_get, KF_ACQUIRE | KF_KPTR_GET | KF_RET_NULL)
1906 BTF_ID_FLAGS(func, bpf_task_release, KF_RELEASE)
1907 BTF_SET8_END(generic_btf_ids)
1908 
1909 static const struct btf_kfunc_id_set generic_kfunc_set = {
1910 	.owner = THIS_MODULE,
1911 	.set   = &generic_btf_ids,
1912 };
1913 
1914 
1915 BTF_ID_LIST(generic_dtor_ids)
1916 BTF_ID(struct, task_struct)
1917 BTF_ID(func, bpf_task_release)
1918 
1919 BTF_SET8_START(common_btf_ids)
1920 BTF_ID_FLAGS(func, bpf_cast_to_kern_ctx)
1921 BTF_ID_FLAGS(func, bpf_rdonly_cast)
1922 BTF_SET8_END(common_btf_ids)
1923 
1924 static const struct btf_kfunc_id_set common_kfunc_set = {
1925 	.owner = THIS_MODULE,
1926 	.set   = &common_btf_ids,
1927 };
1928 
1929 static int __init kfunc_init(void)
1930 {
1931 	int ret;
1932 	const struct btf_id_dtor_kfunc generic_dtors[] = {
1933 		{
1934 			.btf_id       = generic_dtor_ids[0],
1935 			.kfunc_btf_id = generic_dtor_ids[1]
1936 		},
1937 	};
1938 
1939 	ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_TRACING, &generic_kfunc_set);
1940 	ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_SCHED_CLS, &generic_kfunc_set);
1941 	ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS, &generic_kfunc_set);
1942 	ret = ret ?: register_btf_id_dtor_kfuncs(generic_dtors,
1943 						  ARRAY_SIZE(generic_dtors),
1944 						  THIS_MODULE);
1945 	return ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_UNSPEC, &common_kfunc_set);
1946 }
1947 
1948 late_initcall(kfunc_init);
1949