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