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