Linux Audio

Check our new training course

Loading...
v6.8
   1// SPDX-License-Identifier: GPL-2.0-only
   2/* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
   3 */
   4#include <linux/bpf.h>
   5#include <linux/btf.h>
   6#include <linux/bpf-cgroup.h>
   7#include <linux/cgroup.h>
   8#include <linux/rcupdate.h>
   9#include <linux/random.h>
  10#include <linux/smp.h>
  11#include <linux/topology.h>
  12#include <linux/ktime.h>
  13#include <linux/sched.h>
  14#include <linux/uidgid.h>
  15#include <linux/filter.h>
  16#include <linux/ctype.h>
  17#include <linux/jiffies.h>
  18#include <linux/pid_namespace.h>
  19#include <linux/poison.h>
  20#include <linux/proc_ns.h>
  21#include <linux/sched/task.h>
  22#include <linux/security.h>
  23#include <linux/btf_ids.h>
  24#include <linux/bpf_mem_alloc.h>
  25#include <linux/kasan.h>
  26
  27#include "../../lib/kstrtox.h"
  28
  29/* If kernel subsystem is allowing eBPF programs to call this function,
  30 * inside its own verifier_ops->get_func_proto() callback it should return
  31 * bpf_map_lookup_elem_proto, so that verifier can properly check the arguments
  32 *
  33 * Different map implementations will rely on rcu in map methods
  34 * lookup/update/delete, therefore eBPF programs must run under rcu lock
  35 * if program is allowed to access maps, so check rcu_read_lock_held() or
  36 * rcu_read_lock_trace_held() in all three functions.
  37 */
  38BPF_CALL_2(bpf_map_lookup_elem, struct bpf_map *, map, void *, key)
  39{
  40	WARN_ON_ONCE(!rcu_read_lock_held() && !rcu_read_lock_trace_held() &&
  41		     !rcu_read_lock_bh_held());
  42	return (unsigned long) map->ops->map_lookup_elem(map, key);
  43}
  44
  45const struct bpf_func_proto bpf_map_lookup_elem_proto = {
  46	.func		= bpf_map_lookup_elem,
  47	.gpl_only	= false,
  48	.pkt_access	= true,
  49	.ret_type	= RET_PTR_TO_MAP_VALUE_OR_NULL,
  50	.arg1_type	= ARG_CONST_MAP_PTR,
  51	.arg2_type	= ARG_PTR_TO_MAP_KEY,
  52};
  53
  54BPF_CALL_4(bpf_map_update_elem, struct bpf_map *, map, void *, key,
  55	   void *, value, u64, flags)
  56{
  57	WARN_ON_ONCE(!rcu_read_lock_held() && !rcu_read_lock_trace_held() &&
  58		     !rcu_read_lock_bh_held());
  59	return map->ops->map_update_elem(map, key, value, flags);
  60}
  61
  62const struct bpf_func_proto bpf_map_update_elem_proto = {
  63	.func		= bpf_map_update_elem,
  64	.gpl_only	= false,
  65	.pkt_access	= true,
  66	.ret_type	= RET_INTEGER,
  67	.arg1_type	= ARG_CONST_MAP_PTR,
  68	.arg2_type	= ARG_PTR_TO_MAP_KEY,
  69	.arg3_type	= ARG_PTR_TO_MAP_VALUE,
  70	.arg4_type	= ARG_ANYTHING,
  71};
  72
  73BPF_CALL_2(bpf_map_delete_elem, struct bpf_map *, map, void *, key)
  74{
  75	WARN_ON_ONCE(!rcu_read_lock_held() && !rcu_read_lock_trace_held() &&
  76		     !rcu_read_lock_bh_held());
  77	return map->ops->map_delete_elem(map, key);
  78}
  79
  80const struct bpf_func_proto bpf_map_delete_elem_proto = {
  81	.func		= bpf_map_delete_elem,
  82	.gpl_only	= false,
  83	.pkt_access	= true,
  84	.ret_type	= RET_INTEGER,
  85	.arg1_type	= ARG_CONST_MAP_PTR,
  86	.arg2_type	= ARG_PTR_TO_MAP_KEY,
  87};
  88
  89BPF_CALL_3(bpf_map_push_elem, struct bpf_map *, map, void *, value, u64, flags)
  90{
  91	return map->ops->map_push_elem(map, value, flags);
  92}
  93
  94const struct bpf_func_proto bpf_map_push_elem_proto = {
  95	.func		= bpf_map_push_elem,
  96	.gpl_only	= false,
  97	.pkt_access	= true,
  98	.ret_type	= RET_INTEGER,
  99	.arg1_type	= ARG_CONST_MAP_PTR,
 100	.arg2_type	= ARG_PTR_TO_MAP_VALUE,
 101	.arg3_type	= ARG_ANYTHING,
 102};
 103
 104BPF_CALL_2(bpf_map_pop_elem, struct bpf_map *, map, void *, value)
 105{
 106	return map->ops->map_pop_elem(map, value);
 107}
 108
 109const struct bpf_func_proto bpf_map_pop_elem_proto = {
 110	.func		= bpf_map_pop_elem,
 111	.gpl_only	= false,
 112	.ret_type	= RET_INTEGER,
 113	.arg1_type	= ARG_CONST_MAP_PTR,
 114	.arg2_type	= ARG_PTR_TO_MAP_VALUE | MEM_UNINIT,
 115};
 116
 117BPF_CALL_2(bpf_map_peek_elem, struct bpf_map *, map, void *, value)
 118{
 119	return map->ops->map_peek_elem(map, value);
 120}
 121
 122const struct bpf_func_proto bpf_map_peek_elem_proto = {
 123	.func		= bpf_map_peek_elem,
 124	.gpl_only	= false,
 125	.ret_type	= RET_INTEGER,
 126	.arg1_type	= ARG_CONST_MAP_PTR,
 127	.arg2_type	= ARG_PTR_TO_MAP_VALUE | MEM_UNINIT,
 128};
 129
 130BPF_CALL_3(bpf_map_lookup_percpu_elem, struct bpf_map *, map, void *, key, u32, cpu)
 131{
 132	WARN_ON_ONCE(!rcu_read_lock_held() && !rcu_read_lock_bh_held());
 133	return (unsigned long) map->ops->map_lookup_percpu_elem(map, key, cpu);
 134}
 135
 136const struct bpf_func_proto bpf_map_lookup_percpu_elem_proto = {
 137	.func		= bpf_map_lookup_percpu_elem,
 138	.gpl_only	= false,
 139	.pkt_access	= true,
 140	.ret_type	= RET_PTR_TO_MAP_VALUE_OR_NULL,
 141	.arg1_type	= ARG_CONST_MAP_PTR,
 142	.arg2_type	= ARG_PTR_TO_MAP_KEY,
 143	.arg3_type	= ARG_ANYTHING,
 144};
 145
 146const struct bpf_func_proto bpf_get_prandom_u32_proto = {
 147	.func		= bpf_user_rnd_u32,
 148	.gpl_only	= false,
 149	.ret_type	= RET_INTEGER,
 150};
 151
 152BPF_CALL_0(bpf_get_smp_processor_id)
 153{
 154	return smp_processor_id();
 155}
 156
 157const struct bpf_func_proto bpf_get_smp_processor_id_proto = {
 158	.func		= bpf_get_smp_processor_id,
 159	.gpl_only	= false,
 160	.ret_type	= RET_INTEGER,
 
 161};
 162
 163BPF_CALL_0(bpf_get_numa_node_id)
 164{
 165	return numa_node_id();
 166}
 167
 168const struct bpf_func_proto bpf_get_numa_node_id_proto = {
 169	.func		= bpf_get_numa_node_id,
 170	.gpl_only	= false,
 171	.ret_type	= RET_INTEGER,
 172};
 173
 174BPF_CALL_0(bpf_ktime_get_ns)
 175{
 176	/* NMI safe access to clock monotonic */
 177	return ktime_get_mono_fast_ns();
 178}
 179
 180const struct bpf_func_proto bpf_ktime_get_ns_proto = {
 181	.func		= bpf_ktime_get_ns,
 182	.gpl_only	= false,
 183	.ret_type	= RET_INTEGER,
 184};
 185
 186BPF_CALL_0(bpf_ktime_get_boot_ns)
 187{
 188	/* NMI safe access to clock boottime */
 189	return ktime_get_boot_fast_ns();
 190}
 191
 192const struct bpf_func_proto bpf_ktime_get_boot_ns_proto = {
 193	.func		= bpf_ktime_get_boot_ns,
 194	.gpl_only	= false,
 195	.ret_type	= RET_INTEGER,
 196};
 197
 198BPF_CALL_0(bpf_ktime_get_coarse_ns)
 199{
 200	return ktime_get_coarse_ns();
 201}
 202
 203const struct bpf_func_proto bpf_ktime_get_coarse_ns_proto = {
 204	.func		= bpf_ktime_get_coarse_ns,
 205	.gpl_only	= false,
 206	.ret_type	= RET_INTEGER,
 207};
 208
 209BPF_CALL_0(bpf_ktime_get_tai_ns)
 210{
 211	/* NMI safe access to clock tai */
 212	return ktime_get_tai_fast_ns();
 213}
 214
 215const struct bpf_func_proto bpf_ktime_get_tai_ns_proto = {
 216	.func		= bpf_ktime_get_tai_ns,
 217	.gpl_only	= false,
 218	.ret_type	= RET_INTEGER,
 219};
 220
 221BPF_CALL_0(bpf_get_current_pid_tgid)
 222{
 223	struct task_struct *task = current;
 224
 225	if (unlikely(!task))
 226		return -EINVAL;
 227
 228	return (u64) task->tgid << 32 | task->pid;
 229}
 230
 231const struct bpf_func_proto bpf_get_current_pid_tgid_proto = {
 232	.func		= bpf_get_current_pid_tgid,
 233	.gpl_only	= false,
 234	.ret_type	= RET_INTEGER,
 235};
 236
 237BPF_CALL_0(bpf_get_current_uid_gid)
 238{
 239	struct task_struct *task = current;
 240	kuid_t uid;
 241	kgid_t gid;
 242
 243	if (unlikely(!task))
 244		return -EINVAL;
 245
 246	current_uid_gid(&uid, &gid);
 247	return (u64) from_kgid(&init_user_ns, gid) << 32 |
 248		     from_kuid(&init_user_ns, uid);
 249}
 250
 251const struct bpf_func_proto bpf_get_current_uid_gid_proto = {
 252	.func		= bpf_get_current_uid_gid,
 253	.gpl_only	= false,
 254	.ret_type	= RET_INTEGER,
 255};
 256
 257BPF_CALL_2(bpf_get_current_comm, char *, buf, u32, size)
 258{
 259	struct task_struct *task = current;
 260
 261	if (unlikely(!task))
 262		goto err_clear;
 263
 264	/* Verifier guarantees that size > 0 */
 265	strscpy_pad(buf, task->comm, size);
 266	return 0;
 267err_clear:
 268	memset(buf, 0, size);
 269	return -EINVAL;
 270}
 271
 272const struct bpf_func_proto bpf_get_current_comm_proto = {
 273	.func		= bpf_get_current_comm,
 274	.gpl_only	= false,
 275	.ret_type	= RET_INTEGER,
 276	.arg1_type	= ARG_PTR_TO_UNINIT_MEM,
 277	.arg2_type	= ARG_CONST_SIZE,
 278};
 279
 280#if defined(CONFIG_QUEUED_SPINLOCKS) || defined(CONFIG_BPF_ARCH_SPINLOCK)
 281
 282static inline void __bpf_spin_lock(struct bpf_spin_lock *lock)
 283{
 284	arch_spinlock_t *l = (void *)lock;
 285	union {
 286		__u32 val;
 287		arch_spinlock_t lock;
 288	} u = { .lock = __ARCH_SPIN_LOCK_UNLOCKED };
 289
 290	compiletime_assert(u.val == 0, "__ARCH_SPIN_LOCK_UNLOCKED not 0");
 291	BUILD_BUG_ON(sizeof(*l) != sizeof(__u32));
 292	BUILD_BUG_ON(sizeof(*lock) != sizeof(__u32));
 293	preempt_disable();
 294	arch_spin_lock(l);
 295}
 296
 297static inline void __bpf_spin_unlock(struct bpf_spin_lock *lock)
 298{
 299	arch_spinlock_t *l = (void *)lock;
 300
 301	arch_spin_unlock(l);
 302	preempt_enable();
 303}
 304
 305#else
 306
 307static inline void __bpf_spin_lock(struct bpf_spin_lock *lock)
 308{
 309	atomic_t *l = (void *)lock;
 310
 311	BUILD_BUG_ON(sizeof(*l) != sizeof(*lock));
 312	do {
 313		atomic_cond_read_relaxed(l, !VAL);
 314	} while (atomic_xchg(l, 1));
 315}
 316
 317static inline void __bpf_spin_unlock(struct bpf_spin_lock *lock)
 318{
 319	atomic_t *l = (void *)lock;
 320
 321	atomic_set_release(l, 0);
 322}
 323
 324#endif
 325
 326static DEFINE_PER_CPU(unsigned long, irqsave_flags);
 327
 328static inline void __bpf_spin_lock_irqsave(struct bpf_spin_lock *lock)
 329{
 330	unsigned long flags;
 331
 332	local_irq_save(flags);
 333	__bpf_spin_lock(lock);
 334	__this_cpu_write(irqsave_flags, flags);
 335}
 336
 337notrace BPF_CALL_1(bpf_spin_lock, struct bpf_spin_lock *, lock)
 338{
 339	__bpf_spin_lock_irqsave(lock);
 340	return 0;
 341}
 342
 343const struct bpf_func_proto bpf_spin_lock_proto = {
 344	.func		= bpf_spin_lock,
 345	.gpl_only	= false,
 346	.ret_type	= RET_VOID,
 347	.arg1_type	= ARG_PTR_TO_SPIN_LOCK,
 348	.arg1_btf_id    = BPF_PTR_POISON,
 349};
 350
 351static inline void __bpf_spin_unlock_irqrestore(struct bpf_spin_lock *lock)
 352{
 353	unsigned long flags;
 354
 355	flags = __this_cpu_read(irqsave_flags);
 356	__bpf_spin_unlock(lock);
 357	local_irq_restore(flags);
 358}
 359
 360notrace BPF_CALL_1(bpf_spin_unlock, struct bpf_spin_lock *, lock)
 361{
 362	__bpf_spin_unlock_irqrestore(lock);
 363	return 0;
 364}
 365
 366const struct bpf_func_proto bpf_spin_unlock_proto = {
 367	.func		= bpf_spin_unlock,
 368	.gpl_only	= false,
 369	.ret_type	= RET_VOID,
 370	.arg1_type	= ARG_PTR_TO_SPIN_LOCK,
 371	.arg1_btf_id    = BPF_PTR_POISON,
 372};
 373
 374void copy_map_value_locked(struct bpf_map *map, void *dst, void *src,
 375			   bool lock_src)
 376{
 377	struct bpf_spin_lock *lock;
 378
 379	if (lock_src)
 380		lock = src + map->record->spin_lock_off;
 381	else
 382		lock = dst + map->record->spin_lock_off;
 383	preempt_disable();
 384	__bpf_spin_lock_irqsave(lock);
 385	copy_map_value(map, dst, src);
 386	__bpf_spin_unlock_irqrestore(lock);
 387	preempt_enable();
 388}
 389
 390BPF_CALL_0(bpf_jiffies64)
 391{
 392	return get_jiffies_64();
 393}
 394
 395const struct bpf_func_proto bpf_jiffies64_proto = {
 396	.func		= bpf_jiffies64,
 397	.gpl_only	= false,
 398	.ret_type	= RET_INTEGER,
 399};
 400
 401#ifdef CONFIG_CGROUPS
 402BPF_CALL_0(bpf_get_current_cgroup_id)
 403{
 404	struct cgroup *cgrp;
 405	u64 cgrp_id;
 406
 407	rcu_read_lock();
 408	cgrp = task_dfl_cgroup(current);
 409	cgrp_id = cgroup_id(cgrp);
 410	rcu_read_unlock();
 411
 412	return cgrp_id;
 413}
 414
 415const struct bpf_func_proto bpf_get_current_cgroup_id_proto = {
 416	.func		= bpf_get_current_cgroup_id,
 417	.gpl_only	= false,
 418	.ret_type	= RET_INTEGER,
 419};
 420
 421BPF_CALL_1(bpf_get_current_ancestor_cgroup_id, int, ancestor_level)
 422{
 423	struct cgroup *cgrp;
 424	struct cgroup *ancestor;
 425	u64 cgrp_id;
 426
 427	rcu_read_lock();
 428	cgrp = task_dfl_cgroup(current);
 429	ancestor = cgroup_ancestor(cgrp, ancestor_level);
 430	cgrp_id = ancestor ? cgroup_id(ancestor) : 0;
 431	rcu_read_unlock();
 432
 433	return cgrp_id;
 434}
 435
 436const struct bpf_func_proto bpf_get_current_ancestor_cgroup_id_proto = {
 437	.func		= bpf_get_current_ancestor_cgroup_id,
 438	.gpl_only	= false,
 439	.ret_type	= RET_INTEGER,
 440	.arg1_type	= ARG_ANYTHING,
 441};
 442#endif /* CONFIG_CGROUPS */
 443
 444#define BPF_STRTOX_BASE_MASK 0x1F
 445
 446static int __bpf_strtoull(const char *buf, size_t buf_len, u64 flags,
 447			  unsigned long long *res, bool *is_negative)
 448{
 449	unsigned int base = flags & BPF_STRTOX_BASE_MASK;
 450	const char *cur_buf = buf;
 451	size_t cur_len = buf_len;
 452	unsigned int consumed;
 453	size_t val_len;
 454	char str[64];
 455
 456	if (!buf || !buf_len || !res || !is_negative)
 457		return -EINVAL;
 458
 459	if (base != 0 && base != 8 && base != 10 && base != 16)
 460		return -EINVAL;
 461
 462	if (flags & ~BPF_STRTOX_BASE_MASK)
 463		return -EINVAL;
 464
 465	while (cur_buf < buf + buf_len && isspace(*cur_buf))
 466		++cur_buf;
 467
 468	*is_negative = (cur_buf < buf + buf_len && *cur_buf == '-');
 469	if (*is_negative)
 470		++cur_buf;
 471
 472	consumed = cur_buf - buf;
 473	cur_len -= consumed;
 474	if (!cur_len)
 475		return -EINVAL;
 476
 477	cur_len = min(cur_len, sizeof(str) - 1);
 478	memcpy(str, cur_buf, cur_len);
 479	str[cur_len] = '\0';
 480	cur_buf = str;
 481
 482	cur_buf = _parse_integer_fixup_radix(cur_buf, &base);
 483	val_len = _parse_integer(cur_buf, base, res);
 484
 485	if (val_len & KSTRTOX_OVERFLOW)
 486		return -ERANGE;
 487
 488	if (val_len == 0)
 489		return -EINVAL;
 490
 491	cur_buf += val_len;
 492	consumed += cur_buf - str;
 493
 494	return consumed;
 495}
 496
 497static int __bpf_strtoll(const char *buf, size_t buf_len, u64 flags,
 498			 long long *res)
 499{
 500	unsigned long long _res;
 501	bool is_negative;
 502	int err;
 503
 504	err = __bpf_strtoull(buf, buf_len, flags, &_res, &is_negative);
 505	if (err < 0)
 506		return err;
 507	if (is_negative) {
 508		if ((long long)-_res > 0)
 509			return -ERANGE;
 510		*res = -_res;
 511	} else {
 512		if ((long long)_res < 0)
 513			return -ERANGE;
 514		*res = _res;
 515	}
 516	return err;
 517}
 518
 519BPF_CALL_4(bpf_strtol, const char *, buf, size_t, buf_len, u64, flags,
 520	   long *, res)
 521{
 522	long long _res;
 523	int err;
 524
 
 525	err = __bpf_strtoll(buf, buf_len, flags, &_res);
 526	if (err < 0)
 527		return err;
 528	if (_res != (long)_res)
 529		return -ERANGE;
 530	*res = _res;
 531	return err;
 532}
 533
 534const struct bpf_func_proto bpf_strtol_proto = {
 535	.func		= bpf_strtol,
 536	.gpl_only	= false,
 537	.ret_type	= RET_INTEGER,
 538	.arg1_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
 539	.arg2_type	= ARG_CONST_SIZE,
 540	.arg3_type	= ARG_ANYTHING,
 541	.arg4_type	= ARG_PTR_TO_LONG,
 
 542};
 543
 544BPF_CALL_4(bpf_strtoul, const char *, buf, size_t, buf_len, u64, flags,
 545	   unsigned long *, res)
 546{
 547	unsigned long long _res;
 548	bool is_negative;
 549	int err;
 550
 
 551	err = __bpf_strtoull(buf, buf_len, flags, &_res, &is_negative);
 552	if (err < 0)
 553		return err;
 554	if (is_negative)
 555		return -EINVAL;
 556	if (_res != (unsigned long)_res)
 557		return -ERANGE;
 558	*res = _res;
 559	return err;
 560}
 561
 562const struct bpf_func_proto bpf_strtoul_proto = {
 563	.func		= bpf_strtoul,
 564	.gpl_only	= false,
 565	.ret_type	= RET_INTEGER,
 566	.arg1_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
 567	.arg2_type	= ARG_CONST_SIZE,
 568	.arg3_type	= ARG_ANYTHING,
 569	.arg4_type	= ARG_PTR_TO_LONG,
 
 570};
 571
 572BPF_CALL_3(bpf_strncmp, const char *, s1, u32, s1_sz, const char *, s2)
 573{
 574	return strncmp(s1, s2, s1_sz);
 575}
 576
 577static const struct bpf_func_proto bpf_strncmp_proto = {
 578	.func		= bpf_strncmp,
 579	.gpl_only	= false,
 580	.ret_type	= RET_INTEGER,
 581	.arg1_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
 582	.arg2_type	= ARG_CONST_SIZE,
 583	.arg3_type	= ARG_PTR_TO_CONST_STR,
 584};
 585
 586BPF_CALL_4(bpf_get_ns_current_pid_tgid, u64, dev, u64, ino,
 587	   struct bpf_pidns_info *, nsdata, u32, size)
 588{
 589	struct task_struct *task = current;
 590	struct pid_namespace *pidns;
 591	int err = -EINVAL;
 592
 593	if (unlikely(size != sizeof(struct bpf_pidns_info)))
 594		goto clear;
 595
 596	if (unlikely((u64)(dev_t)dev != dev))
 597		goto clear;
 598
 599	if (unlikely(!task))
 600		goto clear;
 601
 602	pidns = task_active_pid_ns(task);
 603	if (unlikely(!pidns)) {
 604		err = -ENOENT;
 605		goto clear;
 606	}
 607
 608	if (!ns_match(&pidns->ns, (dev_t)dev, ino))
 609		goto clear;
 610
 611	nsdata->pid = task_pid_nr_ns(task, pidns);
 612	nsdata->tgid = task_tgid_nr_ns(task, pidns);
 613	return 0;
 614clear:
 615	memset((void *)nsdata, 0, (size_t) size);
 616	return err;
 617}
 618
 619const struct bpf_func_proto bpf_get_ns_current_pid_tgid_proto = {
 620	.func		= bpf_get_ns_current_pid_tgid,
 621	.gpl_only	= false,
 622	.ret_type	= RET_INTEGER,
 623	.arg1_type	= ARG_ANYTHING,
 624	.arg2_type	= ARG_ANYTHING,
 625	.arg3_type      = ARG_PTR_TO_UNINIT_MEM,
 626	.arg4_type      = ARG_CONST_SIZE,
 627};
 628
 629static const struct bpf_func_proto bpf_get_raw_smp_processor_id_proto = {
 630	.func		= bpf_get_raw_cpu_id,
 631	.gpl_only	= false,
 632	.ret_type	= RET_INTEGER,
 633};
 634
 635BPF_CALL_5(bpf_event_output_data, void *, ctx, struct bpf_map *, map,
 636	   u64, flags, void *, data, u64, size)
 637{
 638	if (unlikely(flags & ~(BPF_F_INDEX_MASK)))
 639		return -EINVAL;
 640
 641	return bpf_event_output(map, flags, data, size, NULL, 0, NULL);
 642}
 643
 644const struct bpf_func_proto bpf_event_output_data_proto =  {
 645	.func		= bpf_event_output_data,
 646	.gpl_only       = true,
 647	.ret_type       = RET_INTEGER,
 648	.arg1_type      = ARG_PTR_TO_CTX,
 649	.arg2_type      = ARG_CONST_MAP_PTR,
 650	.arg3_type      = ARG_ANYTHING,
 651	.arg4_type      = ARG_PTR_TO_MEM | MEM_RDONLY,
 652	.arg5_type      = ARG_CONST_SIZE_OR_ZERO,
 653};
 654
 655BPF_CALL_3(bpf_copy_from_user, void *, dst, u32, size,
 656	   const void __user *, user_ptr)
 657{
 658	int ret = copy_from_user(dst, user_ptr, size);
 659
 660	if (unlikely(ret)) {
 661		memset(dst, 0, size);
 662		ret = -EFAULT;
 663	}
 664
 665	return ret;
 666}
 667
 668const struct bpf_func_proto bpf_copy_from_user_proto = {
 669	.func		= bpf_copy_from_user,
 670	.gpl_only	= false,
 671	.might_sleep	= true,
 672	.ret_type	= RET_INTEGER,
 673	.arg1_type	= ARG_PTR_TO_UNINIT_MEM,
 674	.arg2_type	= ARG_CONST_SIZE_OR_ZERO,
 675	.arg3_type	= ARG_ANYTHING,
 676};
 677
 678BPF_CALL_5(bpf_copy_from_user_task, void *, dst, u32, size,
 679	   const void __user *, user_ptr, struct task_struct *, tsk, u64, flags)
 680{
 681	int ret;
 682
 683	/* flags is not used yet */
 684	if (unlikely(flags))
 685		return -EINVAL;
 686
 687	if (unlikely(!size))
 688		return 0;
 689
 690	ret = access_process_vm(tsk, (unsigned long)user_ptr, dst, size, 0);
 691	if (ret == size)
 692		return 0;
 693
 694	memset(dst, 0, size);
 695	/* Return -EFAULT for partial read */
 696	return ret < 0 ? ret : -EFAULT;
 697}
 698
 699const struct bpf_func_proto bpf_copy_from_user_task_proto = {
 700	.func		= bpf_copy_from_user_task,
 701	.gpl_only	= true,
 702	.might_sleep	= true,
 703	.ret_type	= RET_INTEGER,
 704	.arg1_type	= ARG_PTR_TO_UNINIT_MEM,
 705	.arg2_type	= ARG_CONST_SIZE_OR_ZERO,
 706	.arg3_type	= ARG_ANYTHING,
 707	.arg4_type	= ARG_PTR_TO_BTF_ID,
 708	.arg4_btf_id	= &btf_tracing_ids[BTF_TRACING_TYPE_TASK],
 709	.arg5_type	= ARG_ANYTHING
 710};
 711
 712BPF_CALL_2(bpf_per_cpu_ptr, const void *, ptr, u32, cpu)
 713{
 714	if (cpu >= nr_cpu_ids)
 715		return (unsigned long)NULL;
 716
 717	return (unsigned long)per_cpu_ptr((const void __percpu *)ptr, cpu);
 718}
 719
 720const struct bpf_func_proto bpf_per_cpu_ptr_proto = {
 721	.func		= bpf_per_cpu_ptr,
 722	.gpl_only	= false,
 723	.ret_type	= RET_PTR_TO_MEM_OR_BTF_ID | PTR_MAYBE_NULL | MEM_RDONLY,
 724	.arg1_type	= ARG_PTR_TO_PERCPU_BTF_ID,
 725	.arg2_type	= ARG_ANYTHING,
 726};
 727
 728BPF_CALL_1(bpf_this_cpu_ptr, const void *, percpu_ptr)
 729{
 730	return (unsigned long)this_cpu_ptr((const void __percpu *)percpu_ptr);
 731}
 732
 733const struct bpf_func_proto bpf_this_cpu_ptr_proto = {
 734	.func		= bpf_this_cpu_ptr,
 735	.gpl_only	= false,
 736	.ret_type	= RET_PTR_TO_MEM_OR_BTF_ID | MEM_RDONLY,
 737	.arg1_type	= ARG_PTR_TO_PERCPU_BTF_ID,
 738};
 739
 740static int bpf_trace_copy_string(char *buf, void *unsafe_ptr, char fmt_ptype,
 741		size_t bufsz)
 742{
 743	void __user *user_ptr = (__force void __user *)unsafe_ptr;
 744
 745	buf[0] = 0;
 746
 747	switch (fmt_ptype) {
 748	case 's':
 749#ifdef CONFIG_ARCH_HAS_NON_OVERLAPPING_ADDRESS_SPACE
 750		if ((unsigned long)unsafe_ptr < TASK_SIZE)
 751			return strncpy_from_user_nofault(buf, user_ptr, bufsz);
 752		fallthrough;
 753#endif
 754	case 'k':
 755		return strncpy_from_kernel_nofault(buf, unsafe_ptr, bufsz);
 756	case 'u':
 757		return strncpy_from_user_nofault(buf, user_ptr, bufsz);
 758	}
 759
 760	return -EINVAL;
 761}
 762
 763/* Per-cpu temp buffers used by printf-like helpers to store the bprintf binary
 764 * arguments representation.
 765 */
 766#define MAX_BPRINTF_BIN_ARGS	512
 767
 768/* Support executing three nested bprintf helper calls on a given CPU */
 769#define MAX_BPRINTF_NEST_LEVEL	3
 770struct bpf_bprintf_buffers {
 771	char bin_args[MAX_BPRINTF_BIN_ARGS];
 772	char buf[MAX_BPRINTF_BUF];
 773};
 774
 775static DEFINE_PER_CPU(struct bpf_bprintf_buffers[MAX_BPRINTF_NEST_LEVEL], bpf_bprintf_bufs);
 776static DEFINE_PER_CPU(int, bpf_bprintf_nest_level);
 777
 778static int try_get_buffers(struct bpf_bprintf_buffers **bufs)
 779{
 780	int nest_level;
 781
 782	preempt_disable();
 783	nest_level = this_cpu_inc_return(bpf_bprintf_nest_level);
 784	if (WARN_ON_ONCE(nest_level > MAX_BPRINTF_NEST_LEVEL)) {
 785		this_cpu_dec(bpf_bprintf_nest_level);
 786		preempt_enable();
 787		return -EBUSY;
 788	}
 789	*bufs = this_cpu_ptr(&bpf_bprintf_bufs[nest_level - 1]);
 790
 791	return 0;
 792}
 793
 794void bpf_bprintf_cleanup(struct bpf_bprintf_data *data)
 795{
 796	if (!data->bin_args && !data->buf)
 797		return;
 798	if (WARN_ON_ONCE(this_cpu_read(bpf_bprintf_nest_level) == 0))
 799		return;
 800	this_cpu_dec(bpf_bprintf_nest_level);
 801	preempt_enable();
 802}
 803
 804/*
 805 * bpf_bprintf_prepare - Generic pass on format strings for bprintf-like helpers
 806 *
 807 * Returns a negative value if fmt is an invalid format string or 0 otherwise.
 808 *
 809 * This can be used in two ways:
 810 * - Format string verification only: when data->get_bin_args is false
 811 * - Arguments preparation: in addition to the above verification, it writes in
 812 *   data->bin_args a binary representation of arguments usable by bstr_printf
 813 *   where pointers from BPF have been sanitized.
 814 *
 815 * In argument preparation mode, if 0 is returned, safe temporary buffers are
 816 * allocated and bpf_bprintf_cleanup should be called to free them after use.
 817 */
 818int bpf_bprintf_prepare(char *fmt, u32 fmt_size, const u64 *raw_args,
 819			u32 num_args, struct bpf_bprintf_data *data)
 820{
 821	bool get_buffers = (data->get_bin_args && num_args) || data->get_buf;
 822	char *unsafe_ptr = NULL, *tmp_buf = NULL, *tmp_buf_end, *fmt_end;
 823	struct bpf_bprintf_buffers *buffers = NULL;
 824	size_t sizeof_cur_arg, sizeof_cur_ip;
 825	int err, i, num_spec = 0;
 826	u64 cur_arg;
 827	char fmt_ptype, cur_ip[16], ip_spec[] = "%pXX";
 828
 829	fmt_end = strnchr(fmt, fmt_size, 0);
 830	if (!fmt_end)
 831		return -EINVAL;
 832	fmt_size = fmt_end - fmt;
 833
 834	if (get_buffers && try_get_buffers(&buffers))
 835		return -EBUSY;
 836
 837	if (data->get_bin_args) {
 838		if (num_args)
 839			tmp_buf = buffers->bin_args;
 840		tmp_buf_end = tmp_buf + MAX_BPRINTF_BIN_ARGS;
 841		data->bin_args = (u32 *)tmp_buf;
 842	}
 843
 844	if (data->get_buf)
 845		data->buf = buffers->buf;
 846
 847	for (i = 0; i < fmt_size; i++) {
 848		if ((!isprint(fmt[i]) && !isspace(fmt[i])) || !isascii(fmt[i])) {
 849			err = -EINVAL;
 850			goto out;
 851		}
 852
 853		if (fmt[i] != '%')
 854			continue;
 855
 856		if (fmt[i + 1] == '%') {
 857			i++;
 858			continue;
 859		}
 860
 861		if (num_spec >= num_args) {
 862			err = -EINVAL;
 863			goto out;
 864		}
 865
 866		/* The string is zero-terminated so if fmt[i] != 0, we can
 867		 * always access fmt[i + 1], in the worst case it will be a 0
 868		 */
 869		i++;
 870
 871		/* skip optional "[0 +-][num]" width formatting field */
 872		while (fmt[i] == '0' || fmt[i] == '+'  || fmt[i] == '-' ||
 873		       fmt[i] == ' ')
 874			i++;
 875		if (fmt[i] >= '1' && fmt[i] <= '9') {
 876			i++;
 877			while (fmt[i] >= '0' && fmt[i] <= '9')
 878				i++;
 879		}
 880
 881		if (fmt[i] == 'p') {
 882			sizeof_cur_arg = sizeof(long);
 883
 884			if ((fmt[i + 1] == 'k' || fmt[i + 1] == 'u') &&
 885			    fmt[i + 2] == 's') {
 886				fmt_ptype = fmt[i + 1];
 887				i += 2;
 888				goto fmt_str;
 889			}
 890
 891			if (fmt[i + 1] == 0 || isspace(fmt[i + 1]) ||
 892			    ispunct(fmt[i + 1]) || fmt[i + 1] == 'K' ||
 893			    fmt[i + 1] == 'x' || fmt[i + 1] == 's' ||
 894			    fmt[i + 1] == 'S') {
 895				/* just kernel pointers */
 896				if (tmp_buf)
 897					cur_arg = raw_args[num_spec];
 898				i++;
 899				goto nocopy_fmt;
 900			}
 901
 902			if (fmt[i + 1] == 'B') {
 903				if (tmp_buf)  {
 904					err = snprintf(tmp_buf,
 905						       (tmp_buf_end - tmp_buf),
 906						       "%pB",
 907						       (void *)(long)raw_args[num_spec]);
 908					tmp_buf += (err + 1);
 909				}
 910
 911				i++;
 912				num_spec++;
 913				continue;
 914			}
 915
 916			/* only support "%pI4", "%pi4", "%pI6" and "%pi6". */
 917			if ((fmt[i + 1] != 'i' && fmt[i + 1] != 'I') ||
 918			    (fmt[i + 2] != '4' && fmt[i + 2] != '6')) {
 919				err = -EINVAL;
 920				goto out;
 921			}
 922
 923			i += 2;
 924			if (!tmp_buf)
 925				goto nocopy_fmt;
 926
 927			sizeof_cur_ip = (fmt[i] == '4') ? 4 : 16;
 928			if (tmp_buf_end - tmp_buf < sizeof_cur_ip) {
 929				err = -ENOSPC;
 930				goto out;
 931			}
 932
 933			unsafe_ptr = (char *)(long)raw_args[num_spec];
 934			err = copy_from_kernel_nofault(cur_ip, unsafe_ptr,
 935						       sizeof_cur_ip);
 936			if (err < 0)
 937				memset(cur_ip, 0, sizeof_cur_ip);
 938
 939			/* hack: bstr_printf expects IP addresses to be
 940			 * pre-formatted as strings, ironically, the easiest way
 941			 * to do that is to call snprintf.
 942			 */
 943			ip_spec[2] = fmt[i - 1];
 944			ip_spec[3] = fmt[i];
 945			err = snprintf(tmp_buf, tmp_buf_end - tmp_buf,
 946				       ip_spec, &cur_ip);
 947
 948			tmp_buf += err + 1;
 949			num_spec++;
 950
 951			continue;
 952		} else if (fmt[i] == 's') {
 953			fmt_ptype = fmt[i];
 954fmt_str:
 955			if (fmt[i + 1] != 0 &&
 956			    !isspace(fmt[i + 1]) &&
 957			    !ispunct(fmt[i + 1])) {
 958				err = -EINVAL;
 959				goto out;
 960			}
 961
 962			if (!tmp_buf)
 963				goto nocopy_fmt;
 964
 965			if (tmp_buf_end == tmp_buf) {
 966				err = -ENOSPC;
 967				goto out;
 968			}
 969
 970			unsafe_ptr = (char *)(long)raw_args[num_spec];
 971			err = bpf_trace_copy_string(tmp_buf, unsafe_ptr,
 972						    fmt_ptype,
 973						    tmp_buf_end - tmp_buf);
 974			if (err < 0) {
 975				tmp_buf[0] = '\0';
 976				err = 1;
 977			}
 978
 979			tmp_buf += err;
 980			num_spec++;
 981
 982			continue;
 983		} else if (fmt[i] == 'c') {
 984			if (!tmp_buf)
 985				goto nocopy_fmt;
 986
 987			if (tmp_buf_end == tmp_buf) {
 988				err = -ENOSPC;
 989				goto out;
 990			}
 991
 992			*tmp_buf = raw_args[num_spec];
 993			tmp_buf++;
 994			num_spec++;
 995
 996			continue;
 997		}
 998
 999		sizeof_cur_arg = sizeof(int);
1000
1001		if (fmt[i] == 'l') {
1002			sizeof_cur_arg = sizeof(long);
1003			i++;
1004		}
1005		if (fmt[i] == 'l') {
1006			sizeof_cur_arg = sizeof(long long);
1007			i++;
1008		}
1009
1010		if (fmt[i] != 'i' && fmt[i] != 'd' && fmt[i] != 'u' &&
1011		    fmt[i] != 'x' && fmt[i] != 'X') {
1012			err = -EINVAL;
1013			goto out;
1014		}
1015
1016		if (tmp_buf)
1017			cur_arg = raw_args[num_spec];
1018nocopy_fmt:
1019		if (tmp_buf) {
1020			tmp_buf = PTR_ALIGN(tmp_buf, sizeof(u32));
1021			if (tmp_buf_end - tmp_buf < sizeof_cur_arg) {
1022				err = -ENOSPC;
1023				goto out;
1024			}
1025
1026			if (sizeof_cur_arg == 8) {
1027				*(u32 *)tmp_buf = *(u32 *)&cur_arg;
1028				*(u32 *)(tmp_buf + 4) = *((u32 *)&cur_arg + 1);
1029			} else {
1030				*(u32 *)tmp_buf = (u32)(long)cur_arg;
1031			}
1032			tmp_buf += sizeof_cur_arg;
1033		}
1034		num_spec++;
1035	}
1036
1037	err = 0;
1038out:
1039	if (err)
1040		bpf_bprintf_cleanup(data);
1041	return err;
1042}
1043
1044BPF_CALL_5(bpf_snprintf, char *, str, u32, str_size, char *, fmt,
1045	   const void *, args, u32, data_len)
1046{
1047	struct bpf_bprintf_data data = {
1048		.get_bin_args	= true,
1049	};
1050	int err, num_args;
1051
1052	if (data_len % 8 || data_len > MAX_BPRINTF_VARARGS * 8 ||
1053	    (data_len && !args))
1054		return -EINVAL;
1055	num_args = data_len / 8;
1056
1057	/* ARG_PTR_TO_CONST_STR guarantees that fmt is zero-terminated so we
1058	 * can safely give an unbounded size.
1059	 */
1060	err = bpf_bprintf_prepare(fmt, UINT_MAX, args, num_args, &data);
1061	if (err < 0)
1062		return err;
1063
1064	err = bstr_printf(str, str_size, fmt, data.bin_args);
1065
1066	bpf_bprintf_cleanup(&data);
1067
1068	return err + 1;
1069}
1070
1071const struct bpf_func_proto bpf_snprintf_proto = {
1072	.func		= bpf_snprintf,
1073	.gpl_only	= true,
1074	.ret_type	= RET_INTEGER,
1075	.arg1_type	= ARG_PTR_TO_MEM_OR_NULL,
1076	.arg2_type	= ARG_CONST_SIZE_OR_ZERO,
1077	.arg3_type	= ARG_PTR_TO_CONST_STR,
1078	.arg4_type	= ARG_PTR_TO_MEM | PTR_MAYBE_NULL | MEM_RDONLY,
1079	.arg5_type	= ARG_CONST_SIZE_OR_ZERO,
1080};
1081
 
 
 
 
 
 
 
 
 
 
 
 
1082/* BPF map elements can contain 'struct bpf_timer'.
1083 * Such map owns all of its BPF timers.
1084 * 'struct bpf_timer' is allocated as part of map element allocation
1085 * and it's zero initialized.
1086 * That space is used to keep 'struct bpf_timer_kern'.
1087 * bpf_timer_init() allocates 'struct bpf_hrtimer', inits hrtimer, and
1088 * remembers 'struct bpf_map *' pointer it's part of.
1089 * bpf_timer_set_callback() increments prog refcnt and assign bpf callback_fn.
1090 * bpf_timer_start() arms the timer.
1091 * If user space reference to a map goes to zero at this point
1092 * ops->map_release_uref callback is responsible for cancelling the timers,
1093 * freeing their memory, and decrementing prog's refcnts.
1094 * bpf_timer_cancel() cancels the timer and decrements prog's refcnt.
1095 * Inner maps can contain bpf timers as well. ops->map_release_uref is
1096 * freeing the timers when inner map is replaced or deleted by user space.
1097 */
1098struct bpf_hrtimer {
 
1099	struct hrtimer timer;
1100	struct bpf_map *map;
1101	struct bpf_prog *prog;
1102	void __rcu *callback_fn;
1103	void *value;
1104	struct rcu_head rcu;
1105};
1106
1107/* the actual struct hidden inside uapi struct bpf_timer */
1108struct bpf_timer_kern {
1109	struct bpf_hrtimer *timer;
 
 
 
 
 
 
 
 
 
 
1110	/* bpf_spin_lock is used here instead of spinlock_t to make
1111	 * sure that it always fits into space reserved by struct bpf_timer
1112	 * regardless of LOCKDEP and spinlock debug flags.
1113	 */
1114	struct bpf_spin_lock lock;
1115} __attribute__((aligned(8)));
1116
 
 
 
 
 
1117static DEFINE_PER_CPU(struct bpf_hrtimer *, hrtimer_running);
1118
1119static enum hrtimer_restart bpf_timer_cb(struct hrtimer *hrtimer)
1120{
1121	struct bpf_hrtimer *t = container_of(hrtimer, struct bpf_hrtimer, timer);
1122	struct bpf_map *map = t->map;
1123	void *value = t->value;
1124	bpf_callback_t callback_fn;
1125	void *key;
1126	u32 idx;
1127
1128	BTF_TYPE_EMIT(struct bpf_timer);
1129	callback_fn = rcu_dereference_check(t->callback_fn, rcu_read_lock_bh_held());
1130	if (!callback_fn)
1131		goto out;
1132
1133	/* bpf_timer_cb() runs in hrtimer_run_softirq. It doesn't migrate and
1134	 * cannot be preempted by another bpf_timer_cb() on the same cpu.
1135	 * Remember the timer this callback is servicing to prevent
1136	 * deadlock if callback_fn() calls bpf_timer_cancel() or
1137	 * bpf_map_delete_elem() on the same timer.
1138	 */
1139	this_cpu_write(hrtimer_running, t);
1140	if (map->map_type == BPF_MAP_TYPE_ARRAY) {
1141		struct bpf_array *array = container_of(map, struct bpf_array, map);
1142
1143		/* compute the key */
1144		idx = ((char *)value - array->value) / array->elem_size;
1145		key = &idx;
1146	} else { /* hash or lru */
1147		key = value - round_up(map->key_size, 8);
1148	}
1149
1150	callback_fn((u64)(long)map, (u64)(long)key, (u64)(long)value, 0, 0);
1151	/* The verifier checked that return value is zero. */
1152
1153	this_cpu_write(hrtimer_running, NULL);
1154out:
1155	return HRTIMER_NORESTART;
1156}
1157
1158BPF_CALL_3(bpf_timer_init, struct bpf_timer_kern *, timer, struct bpf_map *, map,
1159	   u64, flags)
1160{
1161	clockid_t clockid = flags & (MAX_CLOCKS - 1);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1162	struct bpf_hrtimer *t;
 
 
 
1163	int ret = 0;
1164
1165	BUILD_BUG_ON(MAX_CLOCKS != 16);
1166	BUILD_BUG_ON(sizeof(struct bpf_timer_kern) > sizeof(struct bpf_timer));
1167	BUILD_BUG_ON(__alignof__(struct bpf_timer_kern) != __alignof__(struct bpf_timer));
1168
1169	if (in_nmi())
1170		return -EOPNOTSUPP;
1171
1172	if (flags >= MAX_CLOCKS ||
1173	    /* similar to timerfd except _ALARM variants are not supported */
1174	    (clockid != CLOCK_MONOTONIC &&
1175	     clockid != CLOCK_REALTIME &&
1176	     clockid != CLOCK_BOOTTIME))
 
 
 
1177		return -EINVAL;
1178	__bpf_spin_lock_irqsave(&timer->lock);
1179	t = timer->timer;
 
 
1180	if (t) {
1181		ret = -EBUSY;
1182		goto out;
1183	}
 
1184	/* allocate hrtimer via map_kmalloc to use memcg accounting */
1185	t = bpf_map_kmalloc_node(map, sizeof(*t), GFP_ATOMIC, map->numa_node);
1186	if (!t) {
1187		ret = -ENOMEM;
1188		goto out;
1189	}
1190	t->value = (void *)timer - map->record->timer_off;
1191	t->map = map;
1192	t->prog = NULL;
1193	rcu_assign_pointer(t->callback_fn, NULL);
1194	hrtimer_init(&t->timer, clockid, HRTIMER_MODE_REL_SOFT);
1195	t->timer.function = bpf_timer_cb;
1196	WRITE_ONCE(timer->timer, t);
1197	/* Guarantee the order between timer->timer and map->usercnt. So
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1198	 * when there are concurrent uref release and bpf timer init, either
1199	 * bpf_timer_cancel_and_free() called by uref release reads a no-NULL
1200	 * timer or atomic64_read() below returns a zero usercnt.
1201	 */
1202	smp_mb();
1203	if (!atomic64_read(&map->usercnt)) {
1204		/* maps with timers must be either held by user space
1205		 * or pinned in bpffs.
1206		 */
1207		WRITE_ONCE(timer->timer, NULL);
1208		kfree(t);
1209		ret = -EPERM;
1210	}
1211out:
1212	__bpf_spin_unlock_irqrestore(&timer->lock);
1213	return ret;
1214}
1215
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1216static const struct bpf_func_proto bpf_timer_init_proto = {
1217	.func		= bpf_timer_init,
1218	.gpl_only	= true,
1219	.ret_type	= RET_INTEGER,
1220	.arg1_type	= ARG_PTR_TO_TIMER,
1221	.arg2_type	= ARG_CONST_MAP_PTR,
1222	.arg3_type	= ARG_ANYTHING,
1223};
1224
1225BPF_CALL_3(bpf_timer_set_callback, struct bpf_timer_kern *, timer, void *, callback_fn,
1226	   struct bpf_prog_aux *, aux)
 
1227{
1228	struct bpf_prog *prev, *prog = aux->prog;
1229	struct bpf_hrtimer *t;
1230	int ret = 0;
1231
1232	if (in_nmi())
1233		return -EOPNOTSUPP;
1234	__bpf_spin_lock_irqsave(&timer->lock);
1235	t = timer->timer;
1236	if (!t) {
1237		ret = -EINVAL;
1238		goto out;
1239	}
1240	if (!atomic64_read(&t->map->usercnt)) {
1241		/* maps with timers must be either held by user space
1242		 * or pinned in bpffs. Otherwise timer might still be
1243		 * running even when bpf prog is detached and user space
1244		 * is gone, since map_release_uref won't ever be called.
1245		 */
1246		ret = -EPERM;
1247		goto out;
1248	}
1249	prev = t->prog;
1250	if (prev != prog) {
1251		/* Bump prog refcnt once. Every bpf_timer_set_callback()
1252		 * can pick different callback_fn-s within the same prog.
1253		 */
1254		prog = bpf_prog_inc_not_zero(prog);
1255		if (IS_ERR(prog)) {
1256			ret = PTR_ERR(prog);
1257			goto out;
1258		}
1259		if (prev)
1260			/* Drop prev prog refcnt when swapping with new prog */
1261			bpf_prog_put(prev);
1262		t->prog = prog;
1263	}
1264	rcu_assign_pointer(t->callback_fn, callback_fn);
1265out:
1266	__bpf_spin_unlock_irqrestore(&timer->lock);
1267	return ret;
1268}
1269
 
 
 
 
 
 
1270static const struct bpf_func_proto bpf_timer_set_callback_proto = {
1271	.func		= bpf_timer_set_callback,
1272	.gpl_only	= true,
1273	.ret_type	= RET_INTEGER,
1274	.arg1_type	= ARG_PTR_TO_TIMER,
1275	.arg2_type	= ARG_PTR_TO_FUNC,
1276};
1277
1278BPF_CALL_3(bpf_timer_start, struct bpf_timer_kern *, timer, u64, nsecs, u64, flags)
1279{
1280	struct bpf_hrtimer *t;
1281	int ret = 0;
1282	enum hrtimer_mode mode;
1283
1284	if (in_nmi())
1285		return -EOPNOTSUPP;
1286	if (flags & ~(BPF_F_TIMER_ABS | BPF_F_TIMER_CPU_PIN))
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
1295	if (flags & BPF_F_TIMER_ABS)
1296		mode = HRTIMER_MODE_ABS_SOFT;
1297	else
1298		mode = HRTIMER_MODE_REL_SOFT;
1299
1300	if (flags & BPF_F_TIMER_CPU_PIN)
1301		mode |= HRTIMER_MODE_PINNED;
1302
1303	hrtimer_start(&t->timer, ns_to_ktime(nsecs), mode);
1304out:
1305	__bpf_spin_unlock_irqrestore(&timer->lock);
1306	return ret;
1307}
1308
1309static const struct bpf_func_proto bpf_timer_start_proto = {
1310	.func		= bpf_timer_start,
1311	.gpl_only	= true,
1312	.ret_type	= RET_INTEGER,
1313	.arg1_type	= ARG_PTR_TO_TIMER,
1314	.arg2_type	= ARG_ANYTHING,
1315	.arg3_type	= ARG_ANYTHING,
1316};
1317
1318static void drop_prog_refcnt(struct bpf_hrtimer *t)
1319{
1320	struct bpf_prog *prog = t->prog;
1321
1322	if (prog) {
1323		bpf_prog_put(prog);
1324		t->prog = NULL;
1325		rcu_assign_pointer(t->callback_fn, NULL);
1326	}
1327}
1328
1329BPF_CALL_1(bpf_timer_cancel, struct bpf_timer_kern *, timer)
1330{
1331	struct bpf_hrtimer *t;
 
1332	int ret = 0;
1333
1334	if (in_nmi())
1335		return -EOPNOTSUPP;
1336	rcu_read_lock();
1337	__bpf_spin_lock_irqsave(&timer->lock);
1338	t = timer->timer;
1339	if (!t) {
1340		ret = -EINVAL;
1341		goto out;
1342	}
1343	if (this_cpu_read(hrtimer_running) == t) {
 
 
1344		/* If bpf callback_fn is trying to bpf_timer_cancel()
1345		 * its own timer the hrtimer_cancel() will deadlock
1346		 * since it waits for callback_fn to finish
1347		 */
1348		ret = -EDEADLK;
1349		goto out;
1350	}
1351	drop_prog_refcnt(t);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1352out:
1353	__bpf_spin_unlock_irqrestore(&timer->lock);
1354	/* Cancel the timer and wait for associated callback to finish
1355	 * if it was running.
1356	 */
1357	ret = ret ?: hrtimer_cancel(&t->timer);
 
 
1358	rcu_read_unlock();
1359	return ret;
1360}
1361
1362static const struct bpf_func_proto bpf_timer_cancel_proto = {
1363	.func		= bpf_timer_cancel,
1364	.gpl_only	= true,
1365	.ret_type	= RET_INTEGER,
1366	.arg1_type	= ARG_PTR_TO_TIMER,
1367};
1368
1369/* This function is called by map_delete/update_elem for individual element and
1370 * by ops->map_release_uref when the user space reference to a map reaches zero.
1371 */
1372void bpf_timer_cancel_and_free(void *val)
1373{
1374	struct bpf_timer_kern *timer = val;
1375	struct bpf_hrtimer *t;
1376
1377	/* Performance optimization: read timer->timer without lock first. */
1378	if (!READ_ONCE(timer->timer))
1379		return;
1380
1381	__bpf_spin_lock_irqsave(&timer->lock);
1382	/* re-read it under lock */
1383	t = timer->timer;
1384	if (!t)
1385		goto out;
1386	drop_prog_refcnt(t);
1387	/* The subsequent bpf_timer_start/cancel() helpers won't be able to use
1388	 * this timer, since it won't be initialized.
1389	 */
1390	WRITE_ONCE(timer->timer, NULL);
1391out:
1392	__bpf_spin_unlock_irqrestore(&timer->lock);
 
 
 
 
 
 
 
 
 
 
 
 
1393	if (!t)
1394		return;
1395	/* Cancel the timer and wait for callback to complete if it was running.
1396	 * If hrtimer_cancel() can be safely called it's safe to call kfree(t)
1397	 * right after for both preallocated and non-preallocated maps.
1398	 * The timer->timer = NULL was already done and no code path can
1399	 * see address 't' anymore.
1400	 *
1401	 * Check that bpf_map_delete/update_elem() wasn't called from timer
1402	 * callback_fn. In such case don't call hrtimer_cancel() (since it will
1403	 * deadlock) and don't call hrtimer_try_to_cancel() (since it will just
1404	 * return -1). Though callback_fn is still running on this cpu it's
1405	 * safe to do kfree(t) because bpf_timer_cb() read everything it needed
1406	 * from 't'. The bpf subprog callback_fn won't be able to access 't',
1407	 * since timer->timer = NULL was already done. The timer will be
1408	 * effectively cancelled because bpf_timer_cb() will return
1409	 * HRTIMER_NORESTART.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1410	 */
1411	if (this_cpu_read(hrtimer_running) != t)
1412		hrtimer_cancel(&t->timer);
1413	kfree_rcu(t, rcu);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1414}
1415
1416BPF_CALL_2(bpf_kptr_xchg, void *, map_value, void *, ptr)
 
 
 
1417{
1418	unsigned long *kptr = map_value;
 
 
1419
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1420	return xchg(kptr, (unsigned long)ptr);
1421}
1422
1423/* Unlike other PTR_TO_BTF_ID helpers the btf_id in bpf_kptr_xchg()
1424 * helper is determined dynamically by the verifier. Use BPF_PTR_POISON to
1425 * denote type that verifier will determine.
1426 */
1427static const struct bpf_func_proto bpf_kptr_xchg_proto = {
1428	.func         = bpf_kptr_xchg,
1429	.gpl_only     = false,
1430	.ret_type     = RET_PTR_TO_BTF_ID_OR_NULL,
1431	.ret_btf_id   = BPF_PTR_POISON,
1432	.arg1_type    = ARG_PTR_TO_KPTR,
1433	.arg2_type    = ARG_PTR_TO_BTF_ID_OR_NULL | OBJ_RELEASE,
1434	.arg2_btf_id  = BPF_PTR_POISON,
1435};
1436
1437/* Since the upper 8 bits of dynptr->size is reserved, the
1438 * maximum supported size is 2^24 - 1.
1439 */
1440#define DYNPTR_MAX_SIZE	((1UL << 24) - 1)
1441#define DYNPTR_TYPE_SHIFT	28
1442#define DYNPTR_SIZE_MASK	0xFFFFFF
1443#define DYNPTR_RDONLY_BIT	BIT(31)
1444
1445static bool __bpf_dynptr_is_rdonly(const struct bpf_dynptr_kern *ptr)
1446{
1447	return ptr->size & DYNPTR_RDONLY_BIT;
1448}
1449
1450void bpf_dynptr_set_rdonly(struct bpf_dynptr_kern *ptr)
1451{
1452	ptr->size |= DYNPTR_RDONLY_BIT;
1453}
1454
1455static void bpf_dynptr_set_type(struct bpf_dynptr_kern *ptr, enum bpf_dynptr_type type)
1456{
1457	ptr->size |= type << DYNPTR_TYPE_SHIFT;
1458}
1459
1460static enum bpf_dynptr_type bpf_dynptr_get_type(const struct bpf_dynptr_kern *ptr)
1461{
1462	return (ptr->size & ~(DYNPTR_RDONLY_BIT)) >> DYNPTR_TYPE_SHIFT;
1463}
1464
1465u32 __bpf_dynptr_size(const struct bpf_dynptr_kern *ptr)
1466{
1467	return ptr->size & DYNPTR_SIZE_MASK;
1468}
1469
1470static void bpf_dynptr_set_size(struct bpf_dynptr_kern *ptr, u32 new_size)
1471{
1472	u32 metadata = ptr->size & ~DYNPTR_SIZE_MASK;
1473
1474	ptr->size = new_size | metadata;
1475}
1476
1477int bpf_dynptr_check_size(u32 size)
1478{
1479	return size > DYNPTR_MAX_SIZE ? -E2BIG : 0;
1480}
1481
1482void bpf_dynptr_init(struct bpf_dynptr_kern *ptr, void *data,
1483		     enum bpf_dynptr_type type, u32 offset, u32 size)
1484{
1485	ptr->data = data;
1486	ptr->offset = offset;
1487	ptr->size = size;
1488	bpf_dynptr_set_type(ptr, type);
1489}
1490
1491void bpf_dynptr_set_null(struct bpf_dynptr_kern *ptr)
1492{
1493	memset(ptr, 0, sizeof(*ptr));
1494}
1495
1496static int bpf_dynptr_check_off_len(const struct bpf_dynptr_kern *ptr, u32 offset, u32 len)
1497{
1498	u32 size = __bpf_dynptr_size(ptr);
1499
1500	if (len > size || offset > size - len)
1501		return -E2BIG;
1502
1503	return 0;
1504}
1505
1506BPF_CALL_4(bpf_dynptr_from_mem, void *, data, u32, size, u64, flags, struct bpf_dynptr_kern *, ptr)
1507{
1508	int err;
1509
1510	BTF_TYPE_EMIT(struct bpf_dynptr);
1511
1512	err = bpf_dynptr_check_size(size);
1513	if (err)
1514		goto error;
1515
1516	/* flags is currently unsupported */
1517	if (flags) {
1518		err = -EINVAL;
1519		goto error;
1520	}
1521
1522	bpf_dynptr_init(ptr, data, BPF_DYNPTR_TYPE_LOCAL, 0, size);
1523
1524	return 0;
1525
1526error:
1527	bpf_dynptr_set_null(ptr);
1528	return err;
1529}
1530
1531static const struct bpf_func_proto bpf_dynptr_from_mem_proto = {
1532	.func		= bpf_dynptr_from_mem,
1533	.gpl_only	= false,
1534	.ret_type	= RET_INTEGER,
1535	.arg1_type	= ARG_PTR_TO_UNINIT_MEM,
1536	.arg2_type	= ARG_CONST_SIZE_OR_ZERO,
1537	.arg3_type	= ARG_ANYTHING,
1538	.arg4_type	= ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_LOCAL | MEM_UNINIT,
1539};
1540
1541BPF_CALL_5(bpf_dynptr_read, void *, dst, u32, len, const struct bpf_dynptr_kern *, src,
1542	   u32, offset, u64, flags)
1543{
1544	enum bpf_dynptr_type type;
1545	int err;
1546
1547	if (!src->data || flags)
1548		return -EINVAL;
1549
1550	err = bpf_dynptr_check_off_len(src, offset, len);
1551	if (err)
1552		return err;
1553
1554	type = bpf_dynptr_get_type(src);
1555
1556	switch (type) {
1557	case BPF_DYNPTR_TYPE_LOCAL:
1558	case BPF_DYNPTR_TYPE_RINGBUF:
1559		/* Source and destination may possibly overlap, hence use memmove to
1560		 * copy the data. E.g. bpf_dynptr_from_mem may create two dynptr
1561		 * pointing to overlapping PTR_TO_MAP_VALUE regions.
1562		 */
1563		memmove(dst, src->data + src->offset + offset, len);
1564		return 0;
1565	case BPF_DYNPTR_TYPE_SKB:
1566		return __bpf_skb_load_bytes(src->data, src->offset + offset, dst, len);
1567	case BPF_DYNPTR_TYPE_XDP:
1568		return __bpf_xdp_load_bytes(src->data, src->offset + offset, dst, len);
1569	default:
1570		WARN_ONCE(true, "bpf_dynptr_read: unknown dynptr type %d\n", type);
1571		return -EFAULT;
1572	}
1573}
1574
1575static const struct bpf_func_proto bpf_dynptr_read_proto = {
1576	.func		= bpf_dynptr_read,
1577	.gpl_only	= false,
1578	.ret_type	= RET_INTEGER,
1579	.arg1_type	= ARG_PTR_TO_UNINIT_MEM,
1580	.arg2_type	= ARG_CONST_SIZE_OR_ZERO,
1581	.arg3_type	= ARG_PTR_TO_DYNPTR | MEM_RDONLY,
1582	.arg4_type	= ARG_ANYTHING,
1583	.arg5_type	= ARG_ANYTHING,
1584};
1585
1586BPF_CALL_5(bpf_dynptr_write, const struct bpf_dynptr_kern *, dst, u32, offset, void *, src,
1587	   u32, len, u64, flags)
1588{
1589	enum bpf_dynptr_type type;
1590	int err;
1591
1592	if (!dst->data || __bpf_dynptr_is_rdonly(dst))
1593		return -EINVAL;
1594
1595	err = bpf_dynptr_check_off_len(dst, offset, len);
1596	if (err)
1597		return err;
1598
1599	type = bpf_dynptr_get_type(dst);
1600
1601	switch (type) {
1602	case BPF_DYNPTR_TYPE_LOCAL:
1603	case BPF_DYNPTR_TYPE_RINGBUF:
1604		if (flags)
1605			return -EINVAL;
1606		/* Source and destination may possibly overlap, hence use memmove to
1607		 * copy the data. E.g. bpf_dynptr_from_mem may create two dynptr
1608		 * pointing to overlapping PTR_TO_MAP_VALUE regions.
1609		 */
1610		memmove(dst->data + dst->offset + offset, src, len);
1611		return 0;
1612	case BPF_DYNPTR_TYPE_SKB:
1613		return __bpf_skb_store_bytes(dst->data, dst->offset + offset, src, len,
1614					     flags);
1615	case BPF_DYNPTR_TYPE_XDP:
1616		if (flags)
1617			return -EINVAL;
1618		return __bpf_xdp_store_bytes(dst->data, dst->offset + offset, src, len);
1619	default:
1620		WARN_ONCE(true, "bpf_dynptr_write: unknown dynptr type %d\n", type);
1621		return -EFAULT;
1622	}
1623}
1624
1625static const struct bpf_func_proto bpf_dynptr_write_proto = {
1626	.func		= bpf_dynptr_write,
1627	.gpl_only	= false,
1628	.ret_type	= RET_INTEGER,
1629	.arg1_type	= ARG_PTR_TO_DYNPTR | MEM_RDONLY,
1630	.arg2_type	= ARG_ANYTHING,
1631	.arg3_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
1632	.arg4_type	= ARG_CONST_SIZE_OR_ZERO,
1633	.arg5_type	= ARG_ANYTHING,
1634};
1635
1636BPF_CALL_3(bpf_dynptr_data, const struct bpf_dynptr_kern *, ptr, u32, offset, u32, len)
1637{
1638	enum bpf_dynptr_type type;
1639	int err;
1640
1641	if (!ptr->data)
1642		return 0;
1643
1644	err = bpf_dynptr_check_off_len(ptr, offset, len);
1645	if (err)
1646		return 0;
1647
1648	if (__bpf_dynptr_is_rdonly(ptr))
1649		return 0;
1650
1651	type = bpf_dynptr_get_type(ptr);
1652
1653	switch (type) {
1654	case BPF_DYNPTR_TYPE_LOCAL:
1655	case BPF_DYNPTR_TYPE_RINGBUF:
1656		return (unsigned long)(ptr->data + ptr->offset + offset);
1657	case BPF_DYNPTR_TYPE_SKB:
1658	case BPF_DYNPTR_TYPE_XDP:
1659		/* skb and xdp dynptrs should use bpf_dynptr_slice / bpf_dynptr_slice_rdwr */
1660		return 0;
1661	default:
1662		WARN_ONCE(true, "bpf_dynptr_data: unknown dynptr type %d\n", type);
1663		return 0;
1664	}
1665}
1666
1667static const struct bpf_func_proto bpf_dynptr_data_proto = {
1668	.func		= bpf_dynptr_data,
1669	.gpl_only	= false,
1670	.ret_type	= RET_PTR_TO_DYNPTR_MEM_OR_NULL,
1671	.arg1_type	= ARG_PTR_TO_DYNPTR | MEM_RDONLY,
1672	.arg2_type	= ARG_ANYTHING,
1673	.arg3_type	= ARG_CONST_ALLOC_SIZE_OR_ZERO,
1674};
1675
1676const struct bpf_func_proto bpf_get_current_task_proto __weak;
1677const struct bpf_func_proto bpf_get_current_task_btf_proto __weak;
1678const struct bpf_func_proto bpf_probe_read_user_proto __weak;
1679const struct bpf_func_proto bpf_probe_read_user_str_proto __weak;
1680const struct bpf_func_proto bpf_probe_read_kernel_proto __weak;
1681const struct bpf_func_proto bpf_probe_read_kernel_str_proto __weak;
1682const struct bpf_func_proto bpf_task_pt_regs_proto __weak;
1683
1684const struct bpf_func_proto *
1685bpf_base_func_proto(enum bpf_func_id func_id)
1686{
1687	switch (func_id) {
1688	case BPF_FUNC_map_lookup_elem:
1689		return &bpf_map_lookup_elem_proto;
1690	case BPF_FUNC_map_update_elem:
1691		return &bpf_map_update_elem_proto;
1692	case BPF_FUNC_map_delete_elem:
1693		return &bpf_map_delete_elem_proto;
1694	case BPF_FUNC_map_push_elem:
1695		return &bpf_map_push_elem_proto;
1696	case BPF_FUNC_map_pop_elem:
1697		return &bpf_map_pop_elem_proto;
1698	case BPF_FUNC_map_peek_elem:
1699		return &bpf_map_peek_elem_proto;
1700	case BPF_FUNC_map_lookup_percpu_elem:
1701		return &bpf_map_lookup_percpu_elem_proto;
1702	case BPF_FUNC_get_prandom_u32:
1703		return &bpf_get_prandom_u32_proto;
1704	case BPF_FUNC_get_smp_processor_id:
1705		return &bpf_get_raw_smp_processor_id_proto;
1706	case BPF_FUNC_get_numa_node_id:
1707		return &bpf_get_numa_node_id_proto;
1708	case BPF_FUNC_tail_call:
1709		return &bpf_tail_call_proto;
1710	case BPF_FUNC_ktime_get_ns:
1711		return &bpf_ktime_get_ns_proto;
1712	case BPF_FUNC_ktime_get_boot_ns:
1713		return &bpf_ktime_get_boot_ns_proto;
1714	case BPF_FUNC_ktime_get_tai_ns:
1715		return &bpf_ktime_get_tai_ns_proto;
1716	case BPF_FUNC_ringbuf_output:
1717		return &bpf_ringbuf_output_proto;
1718	case BPF_FUNC_ringbuf_reserve:
1719		return &bpf_ringbuf_reserve_proto;
1720	case BPF_FUNC_ringbuf_submit:
1721		return &bpf_ringbuf_submit_proto;
1722	case BPF_FUNC_ringbuf_discard:
1723		return &bpf_ringbuf_discard_proto;
1724	case BPF_FUNC_ringbuf_query:
1725		return &bpf_ringbuf_query_proto;
1726	case BPF_FUNC_strncmp:
1727		return &bpf_strncmp_proto;
1728	case BPF_FUNC_strtol:
1729		return &bpf_strtol_proto;
1730	case BPF_FUNC_strtoul:
1731		return &bpf_strtoul_proto;
 
 
 
 
1732	default:
1733		break;
1734	}
1735
1736	if (!bpf_capable())
1737		return NULL;
1738
1739	switch (func_id) {
1740	case BPF_FUNC_spin_lock:
1741		return &bpf_spin_lock_proto;
1742	case BPF_FUNC_spin_unlock:
1743		return &bpf_spin_unlock_proto;
1744	case BPF_FUNC_jiffies64:
1745		return &bpf_jiffies64_proto;
1746	case BPF_FUNC_per_cpu_ptr:
1747		return &bpf_per_cpu_ptr_proto;
1748	case BPF_FUNC_this_cpu_ptr:
1749		return &bpf_this_cpu_ptr_proto;
1750	case BPF_FUNC_timer_init:
1751		return &bpf_timer_init_proto;
1752	case BPF_FUNC_timer_set_callback:
1753		return &bpf_timer_set_callback_proto;
1754	case BPF_FUNC_timer_start:
1755		return &bpf_timer_start_proto;
1756	case BPF_FUNC_timer_cancel:
1757		return &bpf_timer_cancel_proto;
1758	case BPF_FUNC_kptr_xchg:
1759		return &bpf_kptr_xchg_proto;
1760	case BPF_FUNC_for_each_map_elem:
1761		return &bpf_for_each_map_elem_proto;
1762	case BPF_FUNC_loop:
1763		return &bpf_loop_proto;
1764	case BPF_FUNC_user_ringbuf_drain:
1765		return &bpf_user_ringbuf_drain_proto;
1766	case BPF_FUNC_ringbuf_reserve_dynptr:
1767		return &bpf_ringbuf_reserve_dynptr_proto;
1768	case BPF_FUNC_ringbuf_submit_dynptr:
1769		return &bpf_ringbuf_submit_dynptr_proto;
1770	case BPF_FUNC_ringbuf_discard_dynptr:
1771		return &bpf_ringbuf_discard_dynptr_proto;
1772	case BPF_FUNC_dynptr_from_mem:
1773		return &bpf_dynptr_from_mem_proto;
1774	case BPF_FUNC_dynptr_read:
1775		return &bpf_dynptr_read_proto;
1776	case BPF_FUNC_dynptr_write:
1777		return &bpf_dynptr_write_proto;
1778	case BPF_FUNC_dynptr_data:
1779		return &bpf_dynptr_data_proto;
1780#ifdef CONFIG_CGROUPS
1781	case BPF_FUNC_cgrp_storage_get:
1782		return &bpf_cgrp_storage_get_proto;
1783	case BPF_FUNC_cgrp_storage_delete:
1784		return &bpf_cgrp_storage_delete_proto;
1785	case BPF_FUNC_get_current_cgroup_id:
1786		return &bpf_get_current_cgroup_id_proto;
1787	case BPF_FUNC_get_current_ancestor_cgroup_id:
1788		return &bpf_get_current_ancestor_cgroup_id_proto;
1789#endif
1790	default:
1791		break;
1792	}
1793
1794	if (!perfmon_capable())
1795		return NULL;
1796
1797	switch (func_id) {
1798	case BPF_FUNC_trace_printk:
1799		return bpf_get_trace_printk_proto();
1800	case BPF_FUNC_get_current_task:
1801		return &bpf_get_current_task_proto;
1802	case BPF_FUNC_get_current_task_btf:
1803		return &bpf_get_current_task_btf_proto;
1804	case BPF_FUNC_probe_read_user:
1805		return &bpf_probe_read_user_proto;
1806	case BPF_FUNC_probe_read_kernel:
1807		return security_locked_down(LOCKDOWN_BPF_READ_KERNEL) < 0 ?
1808		       NULL : &bpf_probe_read_kernel_proto;
1809	case BPF_FUNC_probe_read_user_str:
1810		return &bpf_probe_read_user_str_proto;
1811	case BPF_FUNC_probe_read_kernel_str:
1812		return security_locked_down(LOCKDOWN_BPF_READ_KERNEL) < 0 ?
1813		       NULL : &bpf_probe_read_kernel_str_proto;
1814	case BPF_FUNC_snprintf_btf:
1815		return &bpf_snprintf_btf_proto;
1816	case BPF_FUNC_snprintf:
1817		return &bpf_snprintf_proto;
1818	case BPF_FUNC_task_pt_regs:
1819		return &bpf_task_pt_regs_proto;
1820	case BPF_FUNC_trace_vprintk:
1821		return bpf_get_trace_vprintk_proto();
1822	default:
1823		return NULL;
1824	}
1825}
 
1826
1827void bpf_list_head_free(const struct btf_field *field, void *list_head,
1828			struct bpf_spin_lock *spin_lock)
1829{
1830	struct list_head *head = list_head, *orig_head = list_head;
1831
1832	BUILD_BUG_ON(sizeof(struct list_head) > sizeof(struct bpf_list_head));
1833	BUILD_BUG_ON(__alignof__(struct list_head) > __alignof__(struct bpf_list_head));
1834
1835	/* Do the actual list draining outside the lock to not hold the lock for
1836	 * too long, and also prevent deadlocks if tracing programs end up
1837	 * executing on entry/exit of functions called inside the critical
1838	 * section, and end up doing map ops that call bpf_list_head_free for
1839	 * the same map value again.
1840	 */
1841	__bpf_spin_lock_irqsave(spin_lock);
1842	if (!head->next || list_empty(head))
1843		goto unlock;
1844	head = head->next;
1845unlock:
1846	INIT_LIST_HEAD(orig_head);
1847	__bpf_spin_unlock_irqrestore(spin_lock);
1848
1849	while (head != orig_head) {
1850		void *obj = head;
1851
1852		obj -= field->graph_root.node_offset;
1853		head = head->next;
1854		/* The contained type can also have resources, including a
1855		 * bpf_list_head which needs to be freed.
1856		 */
1857		migrate_disable();
1858		__bpf_obj_drop_impl(obj, field->graph_root.value_rec, false);
1859		migrate_enable();
1860	}
1861}
1862
1863/* Like rbtree_postorder_for_each_entry_safe, but 'pos' and 'n' are
1864 * 'rb_node *', so field name of rb_node within containing struct is not
1865 * needed.
1866 *
1867 * Since bpf_rb_tree's node type has a corresponding struct btf_field with
1868 * graph_root.node_offset, it's not necessary to know field name
1869 * or type of node struct
1870 */
1871#define bpf_rbtree_postorder_for_each_entry_safe(pos, n, root) \
1872	for (pos = rb_first_postorder(root); \
1873	    pos && ({ n = rb_next_postorder(pos); 1; }); \
1874	    pos = n)
1875
1876void bpf_rb_root_free(const struct btf_field *field, void *rb_root,
1877		      struct bpf_spin_lock *spin_lock)
1878{
1879	struct rb_root_cached orig_root, *root = rb_root;
1880	struct rb_node *pos, *n;
1881	void *obj;
1882
1883	BUILD_BUG_ON(sizeof(struct rb_root_cached) > sizeof(struct bpf_rb_root));
1884	BUILD_BUG_ON(__alignof__(struct rb_root_cached) > __alignof__(struct bpf_rb_root));
1885
1886	__bpf_spin_lock_irqsave(spin_lock);
1887	orig_root = *root;
1888	*root = RB_ROOT_CACHED;
1889	__bpf_spin_unlock_irqrestore(spin_lock);
1890
1891	bpf_rbtree_postorder_for_each_entry_safe(pos, n, &orig_root.rb_root) {
1892		obj = pos;
1893		obj -= field->graph_root.node_offset;
1894
1895
1896		migrate_disable();
1897		__bpf_obj_drop_impl(obj, field->graph_root.value_rec, false);
1898		migrate_enable();
1899	}
1900}
1901
1902__bpf_kfunc_start_defs();
1903
1904__bpf_kfunc void *bpf_obj_new_impl(u64 local_type_id__k, void *meta__ign)
1905{
1906	struct btf_struct_meta *meta = meta__ign;
1907	u64 size = local_type_id__k;
1908	void *p;
1909
1910	p = bpf_mem_alloc(&bpf_global_ma, size);
1911	if (!p)
1912		return NULL;
1913	if (meta)
1914		bpf_obj_init(meta->record, p);
1915	return p;
1916}
1917
1918__bpf_kfunc void *bpf_percpu_obj_new_impl(u64 local_type_id__k, void *meta__ign)
1919{
1920	u64 size = local_type_id__k;
1921
1922	/* The verifier has ensured that meta__ign must be NULL */
1923	return bpf_mem_alloc(&bpf_global_percpu_ma, size);
1924}
1925
1926/* Must be called under migrate_disable(), as required by bpf_mem_free */
1927void __bpf_obj_drop_impl(void *p, const struct btf_record *rec, bool percpu)
1928{
1929	struct bpf_mem_alloc *ma;
1930
1931	if (rec && rec->refcount_off >= 0 &&
1932	    !refcount_dec_and_test((refcount_t *)(p + rec->refcount_off))) {
1933		/* Object is refcounted and refcount_dec didn't result in 0
1934		 * refcount. Return without freeing the object
1935		 */
1936		return;
1937	}
1938
1939	if (rec)
1940		bpf_obj_free_fields(rec, p);
1941
1942	if (percpu)
1943		ma = &bpf_global_percpu_ma;
1944	else
1945		ma = &bpf_global_ma;
1946	bpf_mem_free_rcu(ma, p);
1947}
1948
1949__bpf_kfunc void bpf_obj_drop_impl(void *p__alloc, void *meta__ign)
1950{
1951	struct btf_struct_meta *meta = meta__ign;
1952	void *p = p__alloc;
1953
1954	__bpf_obj_drop_impl(p, meta ? meta->record : NULL, false);
1955}
1956
1957__bpf_kfunc void bpf_percpu_obj_drop_impl(void *p__alloc, void *meta__ign)
1958{
1959	/* The verifier has ensured that meta__ign must be NULL */
1960	bpf_mem_free_rcu(&bpf_global_percpu_ma, p__alloc);
1961}
1962
1963__bpf_kfunc void *bpf_refcount_acquire_impl(void *p__refcounted_kptr, void *meta__ign)
1964{
1965	struct btf_struct_meta *meta = meta__ign;
1966	struct bpf_refcount *ref;
1967
1968	/* Could just cast directly to refcount_t *, but need some code using
1969	 * bpf_refcount type so that it is emitted in vmlinux BTF
1970	 */
1971	ref = (struct bpf_refcount *)(p__refcounted_kptr + meta->record->refcount_off);
1972	if (!refcount_inc_not_zero((refcount_t *)ref))
1973		return NULL;
1974
1975	/* Verifier strips KF_RET_NULL if input is owned ref, see is_kfunc_ret_null
1976	 * in verifier.c
1977	 */
1978	return (void *)p__refcounted_kptr;
1979}
1980
1981static int __bpf_list_add(struct bpf_list_node_kern *node,
1982			  struct bpf_list_head *head,
1983			  bool tail, struct btf_record *rec, u64 off)
1984{
1985	struct list_head *n = &node->list_head, *h = (void *)head;
1986
1987	/* If list_head was 0-initialized by map, bpf_obj_init_field wasn't
1988	 * called on its fields, so init here
1989	 */
1990	if (unlikely(!h->next))
1991		INIT_LIST_HEAD(h);
1992
1993	/* node->owner != NULL implies !list_empty(n), no need to separately
1994	 * check the latter
1995	 */
1996	if (cmpxchg(&node->owner, NULL, BPF_PTR_POISON)) {
1997		/* Only called from BPF prog, no need to migrate_disable */
1998		__bpf_obj_drop_impl((void *)n - off, rec, false);
1999		return -EINVAL;
2000	}
2001
2002	tail ? list_add_tail(n, h) : list_add(n, h);
2003	WRITE_ONCE(node->owner, head);
2004
2005	return 0;
2006}
2007
2008__bpf_kfunc int bpf_list_push_front_impl(struct bpf_list_head *head,
2009					 struct bpf_list_node *node,
2010					 void *meta__ign, u64 off)
2011{
2012	struct bpf_list_node_kern *n = (void *)node;
2013	struct btf_struct_meta *meta = meta__ign;
2014
2015	return __bpf_list_add(n, head, false, meta ? meta->record : NULL, off);
2016}
2017
2018__bpf_kfunc int bpf_list_push_back_impl(struct bpf_list_head *head,
2019					struct bpf_list_node *node,
2020					void *meta__ign, u64 off)
2021{
2022	struct bpf_list_node_kern *n = (void *)node;
2023	struct btf_struct_meta *meta = meta__ign;
2024
2025	return __bpf_list_add(n, head, true, meta ? meta->record : NULL, off);
2026}
2027
2028static struct bpf_list_node *__bpf_list_del(struct bpf_list_head *head, bool tail)
2029{
2030	struct list_head *n, *h = (void *)head;
2031	struct bpf_list_node_kern *node;
2032
2033	/* If list_head was 0-initialized by map, bpf_obj_init_field wasn't
2034	 * called on its fields, so init here
2035	 */
2036	if (unlikely(!h->next))
2037		INIT_LIST_HEAD(h);
2038	if (list_empty(h))
2039		return NULL;
2040
2041	n = tail ? h->prev : h->next;
2042	node = container_of(n, struct bpf_list_node_kern, list_head);
2043	if (WARN_ON_ONCE(READ_ONCE(node->owner) != head))
2044		return NULL;
2045
2046	list_del_init(n);
2047	WRITE_ONCE(node->owner, NULL);
2048	return (struct bpf_list_node *)n;
2049}
2050
2051__bpf_kfunc struct bpf_list_node *bpf_list_pop_front(struct bpf_list_head *head)
2052{
2053	return __bpf_list_del(head, false);
2054}
2055
2056__bpf_kfunc struct bpf_list_node *bpf_list_pop_back(struct bpf_list_head *head)
2057{
2058	return __bpf_list_del(head, true);
2059}
2060
2061__bpf_kfunc struct bpf_rb_node *bpf_rbtree_remove(struct bpf_rb_root *root,
2062						  struct bpf_rb_node *node)
2063{
2064	struct bpf_rb_node_kern *node_internal = (struct bpf_rb_node_kern *)node;
2065	struct rb_root_cached *r = (struct rb_root_cached *)root;
2066	struct rb_node *n = &node_internal->rb_node;
2067
2068	/* node_internal->owner != root implies either RB_EMPTY_NODE(n) or
2069	 * n is owned by some other tree. No need to check RB_EMPTY_NODE(n)
2070	 */
2071	if (READ_ONCE(node_internal->owner) != root)
2072		return NULL;
2073
2074	rb_erase_cached(n, r);
2075	RB_CLEAR_NODE(n);
2076	WRITE_ONCE(node_internal->owner, NULL);
2077	return (struct bpf_rb_node *)n;
2078}
2079
2080/* Need to copy rbtree_add_cached's logic here because our 'less' is a BPF
2081 * program
2082 */
2083static int __bpf_rbtree_add(struct bpf_rb_root *root,
2084			    struct bpf_rb_node_kern *node,
2085			    void *less, struct btf_record *rec, u64 off)
2086{
2087	struct rb_node **link = &((struct rb_root_cached *)root)->rb_root.rb_node;
2088	struct rb_node *parent = NULL, *n = &node->rb_node;
2089	bpf_callback_t cb = (bpf_callback_t)less;
2090	bool leftmost = true;
2091
2092	/* node->owner != NULL implies !RB_EMPTY_NODE(n), no need to separately
2093	 * check the latter
2094	 */
2095	if (cmpxchg(&node->owner, NULL, BPF_PTR_POISON)) {
2096		/* Only called from BPF prog, no need to migrate_disable */
2097		__bpf_obj_drop_impl((void *)n - off, rec, false);
2098		return -EINVAL;
2099	}
2100
2101	while (*link) {
2102		parent = *link;
2103		if (cb((uintptr_t)node, (uintptr_t)parent, 0, 0, 0)) {
2104			link = &parent->rb_left;
2105		} else {
2106			link = &parent->rb_right;
2107			leftmost = false;
2108		}
2109	}
2110
2111	rb_link_node(n, parent, link);
2112	rb_insert_color_cached(n, (struct rb_root_cached *)root, leftmost);
2113	WRITE_ONCE(node->owner, root);
2114	return 0;
2115}
2116
2117__bpf_kfunc int bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node,
2118				    bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b),
2119				    void *meta__ign, u64 off)
2120{
2121	struct btf_struct_meta *meta = meta__ign;
2122	struct bpf_rb_node_kern *n = (void *)node;
2123
2124	return __bpf_rbtree_add(root, n, (void *)less, meta ? meta->record : NULL, off);
2125}
2126
2127__bpf_kfunc struct bpf_rb_node *bpf_rbtree_first(struct bpf_rb_root *root)
2128{
2129	struct rb_root_cached *r = (struct rb_root_cached *)root;
2130
2131	return (struct bpf_rb_node *)rb_first_cached(r);
2132}
2133
2134/**
2135 * bpf_task_acquire - Acquire a reference to a task. A task acquired by this
2136 * kfunc which is not stored in a map as a kptr, must be released by calling
2137 * bpf_task_release().
2138 * @p: The task on which a reference is being acquired.
2139 */
2140__bpf_kfunc struct task_struct *bpf_task_acquire(struct task_struct *p)
2141{
2142	if (refcount_inc_not_zero(&p->rcu_users))
2143		return p;
2144	return NULL;
2145}
2146
2147/**
2148 * bpf_task_release - Release the reference acquired on a task.
2149 * @p: The task on which a reference is being released.
2150 */
2151__bpf_kfunc void bpf_task_release(struct task_struct *p)
2152{
2153	put_task_struct_rcu_user(p);
2154}
2155
2156__bpf_kfunc void bpf_task_release_dtor(void *p)
2157{
2158	put_task_struct_rcu_user(p);
2159}
2160CFI_NOSEAL(bpf_task_release_dtor);
2161
2162#ifdef CONFIG_CGROUPS
2163/**
2164 * bpf_cgroup_acquire - Acquire a reference to a cgroup. A cgroup acquired by
2165 * this kfunc which is not stored in a map as a kptr, must be released by
2166 * calling bpf_cgroup_release().
2167 * @cgrp: The cgroup on which a reference is being acquired.
2168 */
2169__bpf_kfunc struct cgroup *bpf_cgroup_acquire(struct cgroup *cgrp)
2170{
2171	return cgroup_tryget(cgrp) ? cgrp : NULL;
2172}
2173
2174/**
2175 * bpf_cgroup_release - Release the reference acquired on a cgroup.
2176 * If this kfunc is invoked in an RCU read region, the cgroup is guaranteed to
2177 * not be freed until the current grace period has ended, even if its refcount
2178 * drops to 0.
2179 * @cgrp: The cgroup on which a reference is being released.
2180 */
2181__bpf_kfunc void bpf_cgroup_release(struct cgroup *cgrp)
2182{
2183	cgroup_put(cgrp);
2184}
2185
2186__bpf_kfunc void bpf_cgroup_release_dtor(void *cgrp)
2187{
2188	cgroup_put(cgrp);
2189}
2190CFI_NOSEAL(bpf_cgroup_release_dtor);
2191
2192/**
2193 * bpf_cgroup_ancestor - Perform a lookup on an entry in a cgroup's ancestor
2194 * array. A cgroup returned by this kfunc which is not subsequently stored in a
2195 * map, must be released by calling bpf_cgroup_release().
2196 * @cgrp: The cgroup for which we're performing a lookup.
2197 * @level: The level of ancestor to look up.
2198 */
2199__bpf_kfunc struct cgroup *bpf_cgroup_ancestor(struct cgroup *cgrp, int level)
2200{
2201	struct cgroup *ancestor;
2202
2203	if (level > cgrp->level || level < 0)
2204		return NULL;
2205
2206	/* cgrp's refcnt could be 0 here, but ancestors can still be accessed */
2207	ancestor = cgrp->ancestors[level];
2208	if (!cgroup_tryget(ancestor))
2209		return NULL;
2210	return ancestor;
2211}
2212
2213/**
2214 * bpf_cgroup_from_id - Find a cgroup from its ID. A cgroup returned by this
2215 * kfunc which is not subsequently stored in a map, must be released by calling
2216 * bpf_cgroup_release().
2217 * @cgid: cgroup id.
2218 */
2219__bpf_kfunc struct cgroup *bpf_cgroup_from_id(u64 cgid)
2220{
2221	struct cgroup *cgrp;
2222
2223	cgrp = cgroup_get_from_id(cgid);
2224	if (IS_ERR(cgrp))
2225		return NULL;
2226	return cgrp;
2227}
2228
2229/**
2230 * bpf_task_under_cgroup - wrap task_under_cgroup_hierarchy() as a kfunc, test
2231 * task's membership of cgroup ancestry.
2232 * @task: the task to be tested
2233 * @ancestor: possible ancestor of @task's cgroup
2234 *
2235 * Tests whether @task's default cgroup hierarchy is a descendant of @ancestor.
2236 * It follows all the same rules as cgroup_is_descendant, and only applies
2237 * to the default hierarchy.
2238 */
2239__bpf_kfunc long bpf_task_under_cgroup(struct task_struct *task,
2240				       struct cgroup *ancestor)
2241{
2242	long ret;
2243
2244	rcu_read_lock();
2245	ret = task_under_cgroup_hierarchy(task, ancestor);
2246	rcu_read_unlock();
2247	return ret;
2248}
2249
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2250/**
2251 * bpf_task_get_cgroup1 - Acquires the associated cgroup of a task within a
2252 * specific cgroup1 hierarchy. The cgroup1 hierarchy is identified by its
2253 * hierarchy ID.
2254 * @task: The target task
2255 * @hierarchy_id: The ID of a cgroup1 hierarchy
2256 *
2257 * On success, the cgroup is returen. On failure, NULL is returned.
2258 */
2259__bpf_kfunc struct cgroup *
2260bpf_task_get_cgroup1(struct task_struct *task, int hierarchy_id)
2261{
2262	struct cgroup *cgrp = task_get_cgroup1(task, hierarchy_id);
2263
2264	if (IS_ERR(cgrp))
2265		return NULL;
2266	return cgrp;
2267}
2268#endif /* CONFIG_CGROUPS */
2269
2270/**
2271 * bpf_task_from_pid - Find a struct task_struct from its pid by looking it up
2272 * in the root pid namespace idr. If a task is returned, it must either be
2273 * stored in a map, or released with bpf_task_release().
2274 * @pid: The pid of the task being looked up.
2275 */
2276__bpf_kfunc struct task_struct *bpf_task_from_pid(s32 pid)
2277{
2278	struct task_struct *p;
2279
2280	rcu_read_lock();
2281	p = find_task_by_pid_ns(pid, &init_pid_ns);
2282	if (p)
2283		p = bpf_task_acquire(p);
2284	rcu_read_unlock();
2285
2286	return p;
2287}
2288
2289/**
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2290 * bpf_dynptr_slice() - Obtain a read-only pointer to the dynptr data.
2291 * @ptr: The dynptr whose data slice to retrieve
2292 * @offset: Offset into the dynptr
2293 * @buffer__opt: User-provided buffer to copy contents into.  May be NULL
2294 * @buffer__szk: Size (in bytes) of the buffer if present. This is the
2295 *               length of the requested slice. This must be a constant.
2296 *
2297 * For non-skb and non-xdp type dynptrs, there is no difference between
2298 * bpf_dynptr_slice and bpf_dynptr_data.
2299 *
2300 *  If buffer__opt is NULL, the call will fail if buffer_opt was needed.
2301 *
2302 * If the intention is to write to the data slice, please use
2303 * bpf_dynptr_slice_rdwr.
2304 *
2305 * The user must check that the returned pointer is not null before using it.
2306 *
2307 * Please note that in the case of skb and xdp dynptrs, bpf_dynptr_slice
2308 * does not change the underlying packet data pointers, so a call to
2309 * bpf_dynptr_slice will not invalidate any ctx->data/data_end pointers in
2310 * the bpf program.
2311 *
2312 * Return: NULL if the call failed (eg invalid dynptr), pointer to a read-only
2313 * data slice (can be either direct pointer to the data or a pointer to the user
2314 * provided buffer, with its contents containing the data, if unable to obtain
2315 * direct pointer)
2316 */
2317__bpf_kfunc void *bpf_dynptr_slice(const struct bpf_dynptr_kern *ptr, u32 offset,
2318				   void *buffer__opt, u32 buffer__szk)
2319{
 
2320	enum bpf_dynptr_type type;
2321	u32 len = buffer__szk;
2322	int err;
2323
2324	if (!ptr->data)
2325		return NULL;
2326
2327	err = bpf_dynptr_check_off_len(ptr, offset, len);
2328	if (err)
2329		return NULL;
2330
2331	type = bpf_dynptr_get_type(ptr);
2332
2333	switch (type) {
2334	case BPF_DYNPTR_TYPE_LOCAL:
2335	case BPF_DYNPTR_TYPE_RINGBUF:
2336		return ptr->data + ptr->offset + offset;
2337	case BPF_DYNPTR_TYPE_SKB:
2338		if (buffer__opt)
2339			return skb_header_pointer(ptr->data, ptr->offset + offset, len, buffer__opt);
2340		else
2341			return skb_pointer_if_linear(ptr->data, ptr->offset + offset, len);
2342	case BPF_DYNPTR_TYPE_XDP:
2343	{
2344		void *xdp_ptr = bpf_xdp_pointer(ptr->data, ptr->offset + offset, len);
2345		if (!IS_ERR_OR_NULL(xdp_ptr))
2346			return xdp_ptr;
2347
2348		if (!buffer__opt)
2349			return NULL;
2350		bpf_xdp_copy_buf(ptr->data, ptr->offset + offset, buffer__opt, len, false);
2351		return buffer__opt;
2352	}
2353	default:
2354		WARN_ONCE(true, "unknown dynptr type %d\n", type);
2355		return NULL;
2356	}
2357}
2358
2359/**
2360 * bpf_dynptr_slice_rdwr() - Obtain a writable pointer to the dynptr data.
2361 * @ptr: The dynptr whose data slice to retrieve
2362 * @offset: Offset into the dynptr
2363 * @buffer__opt: User-provided buffer to copy contents into. May be NULL
2364 * @buffer__szk: Size (in bytes) of the buffer if present. This is the
2365 *               length of the requested slice. This must be a constant.
2366 *
2367 * For non-skb and non-xdp type dynptrs, there is no difference between
2368 * bpf_dynptr_slice and bpf_dynptr_data.
2369 *
2370 * If buffer__opt is NULL, the call will fail if buffer_opt was needed.
2371 *
2372 * The returned pointer is writable and may point to either directly the dynptr
2373 * data at the requested offset or to the buffer if unable to obtain a direct
2374 * data pointer to (example: the requested slice is to the paged area of an skb
2375 * packet). In the case where the returned pointer is to the buffer, the user
2376 * is responsible for persisting writes through calling bpf_dynptr_write(). This
2377 * usually looks something like this pattern:
2378 *
2379 * struct eth_hdr *eth = bpf_dynptr_slice_rdwr(&dynptr, 0, buffer, sizeof(buffer));
2380 * if (!eth)
2381 *	return TC_ACT_SHOT;
2382 *
2383 * // mutate eth header //
2384 *
2385 * if (eth == buffer)
2386 *	bpf_dynptr_write(&ptr, 0, buffer, sizeof(buffer), 0);
2387 *
2388 * Please note that, as in the example above, the user must check that the
2389 * returned pointer is not null before using it.
2390 *
2391 * Please also note that in the case of skb and xdp dynptrs, bpf_dynptr_slice_rdwr
2392 * does not change the underlying packet data pointers, so a call to
2393 * bpf_dynptr_slice_rdwr will not invalidate any ctx->data/data_end pointers in
2394 * the bpf program.
2395 *
2396 * Return: NULL if the call failed (eg invalid dynptr), pointer to a
2397 * data slice (can be either direct pointer to the data or a pointer to the user
2398 * provided buffer, with its contents containing the data, if unable to obtain
2399 * direct pointer)
2400 */
2401__bpf_kfunc void *bpf_dynptr_slice_rdwr(const struct bpf_dynptr_kern *ptr, u32 offset,
2402					void *buffer__opt, u32 buffer__szk)
2403{
 
 
2404	if (!ptr->data || __bpf_dynptr_is_rdonly(ptr))
2405		return NULL;
2406
2407	/* bpf_dynptr_slice_rdwr is the same logic as bpf_dynptr_slice.
2408	 *
2409	 * For skb-type dynptrs, it is safe to write into the returned pointer
2410	 * if the bpf program allows skb data writes. There are two possiblities
2411	 * that may occur when calling bpf_dynptr_slice_rdwr:
2412	 *
2413	 * 1) The requested slice is in the head of the skb. In this case, the
2414	 * returned pointer is directly to skb data, and if the skb is cloned, the
2415	 * verifier will have uncloned it (see bpf_unclone_prologue()) already.
2416	 * The pointer can be directly written into.
2417	 *
2418	 * 2) Some portion of the requested slice is in the paged buffer area.
2419	 * In this case, the requested data will be copied out into the buffer
2420	 * and the returned pointer will be a pointer to the buffer. The skb
2421	 * will not be pulled. To persist the write, the user will need to call
2422	 * bpf_dynptr_write(), which will pull the skb and commit the write.
2423	 *
2424	 * Similarly for xdp programs, if the requested slice is not across xdp
2425	 * fragments, then a direct pointer will be returned, otherwise the data
2426	 * will be copied out into the buffer and the user will need to call
2427	 * bpf_dynptr_write() to commit changes.
2428	 */
2429	return bpf_dynptr_slice(ptr, offset, buffer__opt, buffer__szk);
2430}
2431
2432__bpf_kfunc int bpf_dynptr_adjust(struct bpf_dynptr_kern *ptr, u32 start, u32 end)
2433{
 
2434	u32 size;
2435
2436	if (!ptr->data || start > end)
2437		return -EINVAL;
2438
2439	size = __bpf_dynptr_size(ptr);
2440
2441	if (start > size || end > size)
2442		return -ERANGE;
2443
2444	ptr->offset += start;
2445	bpf_dynptr_set_size(ptr, end - start);
2446
2447	return 0;
2448}
2449
2450__bpf_kfunc bool bpf_dynptr_is_null(struct bpf_dynptr_kern *ptr)
2451{
 
 
2452	return !ptr->data;
2453}
2454
2455__bpf_kfunc bool bpf_dynptr_is_rdonly(struct bpf_dynptr_kern *ptr)
2456{
 
 
2457	if (!ptr->data)
2458		return false;
2459
2460	return __bpf_dynptr_is_rdonly(ptr);
2461}
2462
2463__bpf_kfunc __u32 bpf_dynptr_size(const struct bpf_dynptr_kern *ptr)
2464{
 
 
2465	if (!ptr->data)
2466		return -EINVAL;
2467
2468	return __bpf_dynptr_size(ptr);
2469}
2470
2471__bpf_kfunc int bpf_dynptr_clone(struct bpf_dynptr_kern *ptr,
2472				 struct bpf_dynptr_kern *clone__uninit)
2473{
 
 
 
2474	if (!ptr->data) {
2475		bpf_dynptr_set_null(clone__uninit);
2476		return -EINVAL;
2477	}
2478
2479	*clone__uninit = *ptr;
2480
2481	return 0;
2482}
2483
2484__bpf_kfunc void *bpf_cast_to_kern_ctx(void *obj)
2485{
2486	return obj;
2487}
2488
2489__bpf_kfunc void *bpf_rdonly_cast(void *obj__ign, u32 btf_id__k)
2490{
2491	return obj__ign;
2492}
2493
2494__bpf_kfunc void bpf_rcu_read_lock(void)
2495{
2496	rcu_read_lock();
2497}
2498
2499__bpf_kfunc void bpf_rcu_read_unlock(void)
2500{
2501	rcu_read_unlock();
2502}
2503
2504struct bpf_throw_ctx {
2505	struct bpf_prog_aux *aux;
2506	u64 sp;
2507	u64 bp;
2508	int cnt;
2509};
2510
2511static bool bpf_stack_walker(void *cookie, u64 ip, u64 sp, u64 bp)
2512{
2513	struct bpf_throw_ctx *ctx = cookie;
2514	struct bpf_prog *prog;
2515
2516	if (!is_bpf_text_address(ip))
2517		return !ctx->cnt;
2518	prog = bpf_prog_ksym_find(ip);
2519	ctx->cnt++;
2520	if (bpf_is_subprog(prog))
2521		return true;
2522	ctx->aux = prog->aux;
2523	ctx->sp = sp;
2524	ctx->bp = bp;
2525	return false;
2526}
2527
2528__bpf_kfunc void bpf_throw(u64 cookie)
2529{
2530	struct bpf_throw_ctx ctx = {};
2531
2532	arch_bpf_stack_walk(bpf_stack_walker, &ctx);
2533	WARN_ON_ONCE(!ctx.aux);
2534	if (ctx.aux)
2535		WARN_ON_ONCE(!ctx.aux->exception_boundary);
2536	WARN_ON_ONCE(!ctx.bp);
2537	WARN_ON_ONCE(!ctx.cnt);
2538	/* Prevent KASAN false positives for CONFIG_KASAN_STACK by unpoisoning
2539	 * deeper stack depths than ctx.sp as we do not return from bpf_throw,
2540	 * which skips compiler generated instrumentation to do the same.
2541	 */
2542	kasan_unpoison_task_stack_below((void *)(long)ctx.sp);
2543	ctx.aux->bpf_exception_cb(cookie, ctx.sp, ctx.bp, 0, 0);
2544	WARN(1, "A call to BPF exception callback should never return\n");
2545}
2546
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2547__bpf_kfunc_end_defs();
2548
2549BTF_SET8_START(generic_btf_ids)
2550#ifdef CONFIG_KEXEC_CORE
2551BTF_ID_FLAGS(func, crash_kexec, KF_DESTRUCTIVE)
2552#endif
2553BTF_ID_FLAGS(func, bpf_obj_new_impl, KF_ACQUIRE | KF_RET_NULL)
2554BTF_ID_FLAGS(func, bpf_percpu_obj_new_impl, KF_ACQUIRE | KF_RET_NULL)
2555BTF_ID_FLAGS(func, bpf_obj_drop_impl, KF_RELEASE)
2556BTF_ID_FLAGS(func, bpf_percpu_obj_drop_impl, KF_RELEASE)
2557BTF_ID_FLAGS(func, bpf_refcount_acquire_impl, KF_ACQUIRE | KF_RET_NULL | KF_RCU)
2558BTF_ID_FLAGS(func, bpf_list_push_front_impl)
2559BTF_ID_FLAGS(func, bpf_list_push_back_impl)
2560BTF_ID_FLAGS(func, bpf_list_pop_front, KF_ACQUIRE | KF_RET_NULL)
2561BTF_ID_FLAGS(func, bpf_list_pop_back, KF_ACQUIRE | KF_RET_NULL)
2562BTF_ID_FLAGS(func, bpf_task_acquire, KF_ACQUIRE | KF_RCU | KF_RET_NULL)
2563BTF_ID_FLAGS(func, bpf_task_release, KF_RELEASE)
2564BTF_ID_FLAGS(func, bpf_rbtree_remove, KF_ACQUIRE | KF_RET_NULL)
2565BTF_ID_FLAGS(func, bpf_rbtree_add_impl)
2566BTF_ID_FLAGS(func, bpf_rbtree_first, KF_RET_NULL)
2567
2568#ifdef CONFIG_CGROUPS
2569BTF_ID_FLAGS(func, bpf_cgroup_acquire, KF_ACQUIRE | KF_RCU | KF_RET_NULL)
2570BTF_ID_FLAGS(func, bpf_cgroup_release, KF_RELEASE)
2571BTF_ID_FLAGS(func, bpf_cgroup_ancestor, KF_ACQUIRE | KF_RCU | KF_RET_NULL)
2572BTF_ID_FLAGS(func, bpf_cgroup_from_id, KF_ACQUIRE | KF_RET_NULL)
2573BTF_ID_FLAGS(func, bpf_task_under_cgroup, KF_RCU)
2574BTF_ID_FLAGS(func, bpf_task_get_cgroup1, KF_ACQUIRE | KF_RCU | KF_RET_NULL)
2575#endif
2576BTF_ID_FLAGS(func, bpf_task_from_pid, KF_ACQUIRE | KF_RET_NULL)
 
2577BTF_ID_FLAGS(func, bpf_throw)
2578BTF_SET8_END(generic_btf_ids)
 
2579
2580static const struct btf_kfunc_id_set generic_kfunc_set = {
2581	.owner = THIS_MODULE,
2582	.set   = &generic_btf_ids,
2583};
2584
2585
2586BTF_ID_LIST(generic_dtor_ids)
2587BTF_ID(struct, task_struct)
2588BTF_ID(func, bpf_task_release_dtor)
2589#ifdef CONFIG_CGROUPS
2590BTF_ID(struct, cgroup)
2591BTF_ID(func, bpf_cgroup_release_dtor)
2592#endif
2593
2594BTF_SET8_START(common_btf_ids)
2595BTF_ID_FLAGS(func, bpf_cast_to_kern_ctx)
2596BTF_ID_FLAGS(func, bpf_rdonly_cast)
2597BTF_ID_FLAGS(func, bpf_rcu_read_lock)
2598BTF_ID_FLAGS(func, bpf_rcu_read_unlock)
2599BTF_ID_FLAGS(func, bpf_dynptr_slice, KF_RET_NULL)
2600BTF_ID_FLAGS(func, bpf_dynptr_slice_rdwr, KF_RET_NULL)
2601BTF_ID_FLAGS(func, bpf_iter_num_new, KF_ITER_NEW)
2602BTF_ID_FLAGS(func, bpf_iter_num_next, KF_ITER_NEXT | KF_RET_NULL)
2603BTF_ID_FLAGS(func, bpf_iter_num_destroy, KF_ITER_DESTROY)
2604BTF_ID_FLAGS(func, bpf_iter_task_vma_new, KF_ITER_NEW | KF_RCU)
2605BTF_ID_FLAGS(func, bpf_iter_task_vma_next, KF_ITER_NEXT | KF_RET_NULL)
2606BTF_ID_FLAGS(func, bpf_iter_task_vma_destroy, KF_ITER_DESTROY)
2607#ifdef CONFIG_CGROUPS
2608BTF_ID_FLAGS(func, bpf_iter_css_task_new, KF_ITER_NEW | KF_TRUSTED_ARGS)
2609BTF_ID_FLAGS(func, bpf_iter_css_task_next, KF_ITER_NEXT | KF_RET_NULL)
2610BTF_ID_FLAGS(func, bpf_iter_css_task_destroy, KF_ITER_DESTROY)
2611BTF_ID_FLAGS(func, bpf_iter_css_new, KF_ITER_NEW | KF_TRUSTED_ARGS | KF_RCU_PROTECTED)
2612BTF_ID_FLAGS(func, bpf_iter_css_next, KF_ITER_NEXT | KF_RET_NULL)
2613BTF_ID_FLAGS(func, bpf_iter_css_destroy, KF_ITER_DESTROY)
2614#endif
2615BTF_ID_FLAGS(func, bpf_iter_task_new, KF_ITER_NEW | KF_TRUSTED_ARGS | KF_RCU_PROTECTED)
2616BTF_ID_FLAGS(func, bpf_iter_task_next, KF_ITER_NEXT | KF_RET_NULL)
2617BTF_ID_FLAGS(func, bpf_iter_task_destroy, KF_ITER_DESTROY)
2618BTF_ID_FLAGS(func, bpf_dynptr_adjust)
2619BTF_ID_FLAGS(func, bpf_dynptr_is_null)
2620BTF_ID_FLAGS(func, bpf_dynptr_is_rdonly)
2621BTF_ID_FLAGS(func, bpf_dynptr_size)
2622BTF_ID_FLAGS(func, bpf_dynptr_clone)
2623BTF_SET8_END(common_btf_ids)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2624
2625static const struct btf_kfunc_id_set common_kfunc_set = {
2626	.owner = THIS_MODULE,
2627	.set   = &common_btf_ids,
2628};
2629
2630static int __init kfunc_init(void)
2631{
2632	int ret;
2633	const struct btf_id_dtor_kfunc generic_dtors[] = {
2634		{
2635			.btf_id       = generic_dtor_ids[0],
2636			.kfunc_btf_id = generic_dtor_ids[1]
2637		},
2638#ifdef CONFIG_CGROUPS
2639		{
2640			.btf_id       = generic_dtor_ids[2],
2641			.kfunc_btf_id = generic_dtor_ids[3]
2642		},
2643#endif
2644	};
2645
2646	ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_TRACING, &generic_kfunc_set);
2647	ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_SCHED_CLS, &generic_kfunc_set);
2648	ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_XDP, &generic_kfunc_set);
2649	ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS, &generic_kfunc_set);
 
 
2650	ret = ret ?: register_btf_id_dtor_kfuncs(generic_dtors,
2651						  ARRAY_SIZE(generic_dtors),
2652						  THIS_MODULE);
2653	return ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_UNSPEC, &common_kfunc_set);
2654}
2655
2656late_initcall(kfunc_init);
2657
2658/* Get a pointer to dynptr data up to len bytes for read only access. If
2659 * the dynptr doesn't have continuous data up to len bytes, return NULL.
2660 */
2661const void *__bpf_dynptr_data(const struct bpf_dynptr_kern *ptr, u32 len)
2662{
2663	return bpf_dynptr_slice(ptr, 0, NULL, len);
 
 
2664}
2665
2666/* Get a pointer to dynptr data up to len bytes for read write access. If
2667 * the dynptr doesn't have continuous data up to len bytes, or the dynptr
2668 * is read only, return NULL.
2669 */
2670void *__bpf_dynptr_data_rw(const struct bpf_dynptr_kern *ptr, u32 len)
2671{
2672	if (__bpf_dynptr_is_rdonly(ptr))
2673		return NULL;
2674	return (void *)__bpf_dynptr_data(ptr, len);
2675}
v6.13.7
   1// SPDX-License-Identifier: GPL-2.0-only
   2/* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
   3 */
   4#include <linux/bpf.h>
   5#include <linux/btf.h>
   6#include <linux/bpf-cgroup.h>
   7#include <linux/cgroup.h>
   8#include <linux/rcupdate.h>
   9#include <linux/random.h>
  10#include <linux/smp.h>
  11#include <linux/topology.h>
  12#include <linux/ktime.h>
  13#include <linux/sched.h>
  14#include <linux/uidgid.h>
  15#include <linux/filter.h>
  16#include <linux/ctype.h>
  17#include <linux/jiffies.h>
  18#include <linux/pid_namespace.h>
  19#include <linux/poison.h>
  20#include <linux/proc_ns.h>
  21#include <linux/sched/task.h>
  22#include <linux/security.h>
  23#include <linux/btf_ids.h>
  24#include <linux/bpf_mem_alloc.h>
  25#include <linux/kasan.h>
  26
  27#include "../../lib/kstrtox.h"
  28
  29/* If kernel subsystem is allowing eBPF programs to call this function,
  30 * inside its own verifier_ops->get_func_proto() callback it should return
  31 * bpf_map_lookup_elem_proto, so that verifier can properly check the arguments
  32 *
  33 * Different map implementations will rely on rcu in map methods
  34 * lookup/update/delete, therefore eBPF programs must run under rcu lock
  35 * if program is allowed to access maps, so check rcu_read_lock_held() or
  36 * rcu_read_lock_trace_held() in all three functions.
  37 */
  38BPF_CALL_2(bpf_map_lookup_elem, struct bpf_map *, map, void *, key)
  39{
  40	WARN_ON_ONCE(!rcu_read_lock_held() && !rcu_read_lock_trace_held() &&
  41		     !rcu_read_lock_bh_held());
  42	return (unsigned long) map->ops->map_lookup_elem(map, key);
  43}
  44
  45const struct bpf_func_proto bpf_map_lookup_elem_proto = {
  46	.func		= bpf_map_lookup_elem,
  47	.gpl_only	= false,
  48	.pkt_access	= true,
  49	.ret_type	= RET_PTR_TO_MAP_VALUE_OR_NULL,
  50	.arg1_type	= ARG_CONST_MAP_PTR,
  51	.arg2_type	= ARG_PTR_TO_MAP_KEY,
  52};
  53
  54BPF_CALL_4(bpf_map_update_elem, struct bpf_map *, map, void *, key,
  55	   void *, value, u64, flags)
  56{
  57	WARN_ON_ONCE(!rcu_read_lock_held() && !rcu_read_lock_trace_held() &&
  58		     !rcu_read_lock_bh_held());
  59	return map->ops->map_update_elem(map, key, value, flags);
  60}
  61
  62const struct bpf_func_proto bpf_map_update_elem_proto = {
  63	.func		= bpf_map_update_elem,
  64	.gpl_only	= false,
  65	.pkt_access	= true,
  66	.ret_type	= RET_INTEGER,
  67	.arg1_type	= ARG_CONST_MAP_PTR,
  68	.arg2_type	= ARG_PTR_TO_MAP_KEY,
  69	.arg3_type	= ARG_PTR_TO_MAP_VALUE,
  70	.arg4_type	= ARG_ANYTHING,
  71};
  72
  73BPF_CALL_2(bpf_map_delete_elem, struct bpf_map *, map, void *, key)
  74{
  75	WARN_ON_ONCE(!rcu_read_lock_held() && !rcu_read_lock_trace_held() &&
  76		     !rcu_read_lock_bh_held());
  77	return map->ops->map_delete_elem(map, key);
  78}
  79
  80const struct bpf_func_proto bpf_map_delete_elem_proto = {
  81	.func		= bpf_map_delete_elem,
  82	.gpl_only	= false,
  83	.pkt_access	= true,
  84	.ret_type	= RET_INTEGER,
  85	.arg1_type	= ARG_CONST_MAP_PTR,
  86	.arg2_type	= ARG_PTR_TO_MAP_KEY,
  87};
  88
  89BPF_CALL_3(bpf_map_push_elem, struct bpf_map *, map, void *, value, u64, flags)
  90{
  91	return map->ops->map_push_elem(map, value, flags);
  92}
  93
  94const struct bpf_func_proto bpf_map_push_elem_proto = {
  95	.func		= bpf_map_push_elem,
  96	.gpl_only	= false,
  97	.pkt_access	= true,
  98	.ret_type	= RET_INTEGER,
  99	.arg1_type	= ARG_CONST_MAP_PTR,
 100	.arg2_type	= ARG_PTR_TO_MAP_VALUE,
 101	.arg3_type	= ARG_ANYTHING,
 102};
 103
 104BPF_CALL_2(bpf_map_pop_elem, struct bpf_map *, map, void *, value)
 105{
 106	return map->ops->map_pop_elem(map, value);
 107}
 108
 109const struct bpf_func_proto bpf_map_pop_elem_proto = {
 110	.func		= bpf_map_pop_elem,
 111	.gpl_only	= false,
 112	.ret_type	= RET_INTEGER,
 113	.arg1_type	= ARG_CONST_MAP_PTR,
 114	.arg2_type	= ARG_PTR_TO_MAP_VALUE | MEM_UNINIT | MEM_WRITE,
 115};
 116
 117BPF_CALL_2(bpf_map_peek_elem, struct bpf_map *, map, void *, value)
 118{
 119	return map->ops->map_peek_elem(map, value);
 120}
 121
 122const struct bpf_func_proto bpf_map_peek_elem_proto = {
 123	.func		= bpf_map_peek_elem,
 124	.gpl_only	= false,
 125	.ret_type	= RET_INTEGER,
 126	.arg1_type	= ARG_CONST_MAP_PTR,
 127	.arg2_type	= ARG_PTR_TO_MAP_VALUE | MEM_UNINIT | MEM_WRITE,
 128};
 129
 130BPF_CALL_3(bpf_map_lookup_percpu_elem, struct bpf_map *, map, void *, key, u32, cpu)
 131{
 132	WARN_ON_ONCE(!rcu_read_lock_held() && !rcu_read_lock_bh_held());
 133	return (unsigned long) map->ops->map_lookup_percpu_elem(map, key, cpu);
 134}
 135
 136const struct bpf_func_proto bpf_map_lookup_percpu_elem_proto = {
 137	.func		= bpf_map_lookup_percpu_elem,
 138	.gpl_only	= false,
 139	.pkt_access	= true,
 140	.ret_type	= RET_PTR_TO_MAP_VALUE_OR_NULL,
 141	.arg1_type	= ARG_CONST_MAP_PTR,
 142	.arg2_type	= ARG_PTR_TO_MAP_KEY,
 143	.arg3_type	= ARG_ANYTHING,
 144};
 145
 146const struct bpf_func_proto bpf_get_prandom_u32_proto = {
 147	.func		= bpf_user_rnd_u32,
 148	.gpl_only	= false,
 149	.ret_type	= RET_INTEGER,
 150};
 151
 152BPF_CALL_0(bpf_get_smp_processor_id)
 153{
 154	return smp_processor_id();
 155}
 156
 157const struct bpf_func_proto bpf_get_smp_processor_id_proto = {
 158	.func		= bpf_get_smp_processor_id,
 159	.gpl_only	= false,
 160	.ret_type	= RET_INTEGER,
 161	.allow_fastcall	= true,
 162};
 163
 164BPF_CALL_0(bpf_get_numa_node_id)
 165{
 166	return numa_node_id();
 167}
 168
 169const struct bpf_func_proto bpf_get_numa_node_id_proto = {
 170	.func		= bpf_get_numa_node_id,
 171	.gpl_only	= false,
 172	.ret_type	= RET_INTEGER,
 173};
 174
 175BPF_CALL_0(bpf_ktime_get_ns)
 176{
 177	/* NMI safe access to clock monotonic */
 178	return ktime_get_mono_fast_ns();
 179}
 180
 181const struct bpf_func_proto bpf_ktime_get_ns_proto = {
 182	.func		= bpf_ktime_get_ns,
 183	.gpl_only	= false,
 184	.ret_type	= RET_INTEGER,
 185};
 186
 187BPF_CALL_0(bpf_ktime_get_boot_ns)
 188{
 189	/* NMI safe access to clock boottime */
 190	return ktime_get_boot_fast_ns();
 191}
 192
 193const struct bpf_func_proto bpf_ktime_get_boot_ns_proto = {
 194	.func		= bpf_ktime_get_boot_ns,
 195	.gpl_only	= false,
 196	.ret_type	= RET_INTEGER,
 197};
 198
 199BPF_CALL_0(bpf_ktime_get_coarse_ns)
 200{
 201	return ktime_get_coarse_ns();
 202}
 203
 204const struct bpf_func_proto bpf_ktime_get_coarse_ns_proto = {
 205	.func		= bpf_ktime_get_coarse_ns,
 206	.gpl_only	= false,
 207	.ret_type	= RET_INTEGER,
 208};
 209
 210BPF_CALL_0(bpf_ktime_get_tai_ns)
 211{
 212	/* NMI safe access to clock tai */
 213	return ktime_get_tai_fast_ns();
 214}
 215
 216const struct bpf_func_proto bpf_ktime_get_tai_ns_proto = {
 217	.func		= bpf_ktime_get_tai_ns,
 218	.gpl_only	= false,
 219	.ret_type	= RET_INTEGER,
 220};
 221
 222BPF_CALL_0(bpf_get_current_pid_tgid)
 223{
 224	struct task_struct *task = current;
 225
 226	if (unlikely(!task))
 227		return -EINVAL;
 228
 229	return (u64) task->tgid << 32 | task->pid;
 230}
 231
 232const struct bpf_func_proto bpf_get_current_pid_tgid_proto = {
 233	.func		= bpf_get_current_pid_tgid,
 234	.gpl_only	= false,
 235	.ret_type	= RET_INTEGER,
 236};
 237
 238BPF_CALL_0(bpf_get_current_uid_gid)
 239{
 240	struct task_struct *task = current;
 241	kuid_t uid;
 242	kgid_t gid;
 243
 244	if (unlikely(!task))
 245		return -EINVAL;
 246
 247	current_uid_gid(&uid, &gid);
 248	return (u64) from_kgid(&init_user_ns, gid) << 32 |
 249		     from_kuid(&init_user_ns, uid);
 250}
 251
 252const struct bpf_func_proto bpf_get_current_uid_gid_proto = {
 253	.func		= bpf_get_current_uid_gid,
 254	.gpl_only	= false,
 255	.ret_type	= RET_INTEGER,
 256};
 257
 258BPF_CALL_2(bpf_get_current_comm, char *, buf, u32, size)
 259{
 260	struct task_struct *task = current;
 261
 262	if (unlikely(!task))
 263		goto err_clear;
 264
 265	/* Verifier guarantees that size > 0 */
 266	strscpy_pad(buf, task->comm, size);
 267	return 0;
 268err_clear:
 269	memset(buf, 0, size);
 270	return -EINVAL;
 271}
 272
 273const struct bpf_func_proto bpf_get_current_comm_proto = {
 274	.func		= bpf_get_current_comm,
 275	.gpl_only	= false,
 276	.ret_type	= RET_INTEGER,
 277	.arg1_type	= ARG_PTR_TO_UNINIT_MEM,
 278	.arg2_type	= ARG_CONST_SIZE,
 279};
 280
 281#if defined(CONFIG_QUEUED_SPINLOCKS) || defined(CONFIG_BPF_ARCH_SPINLOCK)
 282
 283static inline void __bpf_spin_lock(struct bpf_spin_lock *lock)
 284{
 285	arch_spinlock_t *l = (void *)lock;
 286	union {
 287		__u32 val;
 288		arch_spinlock_t lock;
 289	} u = { .lock = __ARCH_SPIN_LOCK_UNLOCKED };
 290
 291	compiletime_assert(u.val == 0, "__ARCH_SPIN_LOCK_UNLOCKED not 0");
 292	BUILD_BUG_ON(sizeof(*l) != sizeof(__u32));
 293	BUILD_BUG_ON(sizeof(*lock) != sizeof(__u32));
 294	preempt_disable();
 295	arch_spin_lock(l);
 296}
 297
 298static inline void __bpf_spin_unlock(struct bpf_spin_lock *lock)
 299{
 300	arch_spinlock_t *l = (void *)lock;
 301
 302	arch_spin_unlock(l);
 303	preempt_enable();
 304}
 305
 306#else
 307
 308static inline void __bpf_spin_lock(struct bpf_spin_lock *lock)
 309{
 310	atomic_t *l = (void *)lock;
 311
 312	BUILD_BUG_ON(sizeof(*l) != sizeof(*lock));
 313	do {
 314		atomic_cond_read_relaxed(l, !VAL);
 315	} while (atomic_xchg(l, 1));
 316}
 317
 318static inline void __bpf_spin_unlock(struct bpf_spin_lock *lock)
 319{
 320	atomic_t *l = (void *)lock;
 321
 322	atomic_set_release(l, 0);
 323}
 324
 325#endif
 326
 327static DEFINE_PER_CPU(unsigned long, irqsave_flags);
 328
 329static inline void __bpf_spin_lock_irqsave(struct bpf_spin_lock *lock)
 330{
 331	unsigned long flags;
 332
 333	local_irq_save(flags);
 334	__bpf_spin_lock(lock);
 335	__this_cpu_write(irqsave_flags, flags);
 336}
 337
 338NOTRACE_BPF_CALL_1(bpf_spin_lock, struct bpf_spin_lock *, lock)
 339{
 340	__bpf_spin_lock_irqsave(lock);
 341	return 0;
 342}
 343
 344const struct bpf_func_proto bpf_spin_lock_proto = {
 345	.func		= bpf_spin_lock,
 346	.gpl_only	= false,
 347	.ret_type	= RET_VOID,
 348	.arg1_type	= ARG_PTR_TO_SPIN_LOCK,
 349	.arg1_btf_id    = BPF_PTR_POISON,
 350};
 351
 352static inline void __bpf_spin_unlock_irqrestore(struct bpf_spin_lock *lock)
 353{
 354	unsigned long flags;
 355
 356	flags = __this_cpu_read(irqsave_flags);
 357	__bpf_spin_unlock(lock);
 358	local_irq_restore(flags);
 359}
 360
 361NOTRACE_BPF_CALL_1(bpf_spin_unlock, struct bpf_spin_lock *, lock)
 362{
 363	__bpf_spin_unlock_irqrestore(lock);
 364	return 0;
 365}
 366
 367const struct bpf_func_proto bpf_spin_unlock_proto = {
 368	.func		= bpf_spin_unlock,
 369	.gpl_only	= false,
 370	.ret_type	= RET_VOID,
 371	.arg1_type	= ARG_PTR_TO_SPIN_LOCK,
 372	.arg1_btf_id    = BPF_PTR_POISON,
 373};
 374
 375void copy_map_value_locked(struct bpf_map *map, void *dst, void *src,
 376			   bool lock_src)
 377{
 378	struct bpf_spin_lock *lock;
 379
 380	if (lock_src)
 381		lock = src + map->record->spin_lock_off;
 382	else
 383		lock = dst + map->record->spin_lock_off;
 384	preempt_disable();
 385	__bpf_spin_lock_irqsave(lock);
 386	copy_map_value(map, dst, src);
 387	__bpf_spin_unlock_irqrestore(lock);
 388	preempt_enable();
 389}
 390
 391BPF_CALL_0(bpf_jiffies64)
 392{
 393	return get_jiffies_64();
 394}
 395
 396const struct bpf_func_proto bpf_jiffies64_proto = {
 397	.func		= bpf_jiffies64,
 398	.gpl_only	= false,
 399	.ret_type	= RET_INTEGER,
 400};
 401
 402#ifdef CONFIG_CGROUPS
 403BPF_CALL_0(bpf_get_current_cgroup_id)
 404{
 405	struct cgroup *cgrp;
 406	u64 cgrp_id;
 407
 408	rcu_read_lock();
 409	cgrp = task_dfl_cgroup(current);
 410	cgrp_id = cgroup_id(cgrp);
 411	rcu_read_unlock();
 412
 413	return cgrp_id;
 414}
 415
 416const struct bpf_func_proto bpf_get_current_cgroup_id_proto = {
 417	.func		= bpf_get_current_cgroup_id,
 418	.gpl_only	= false,
 419	.ret_type	= RET_INTEGER,
 420};
 421
 422BPF_CALL_1(bpf_get_current_ancestor_cgroup_id, int, ancestor_level)
 423{
 424	struct cgroup *cgrp;
 425	struct cgroup *ancestor;
 426	u64 cgrp_id;
 427
 428	rcu_read_lock();
 429	cgrp = task_dfl_cgroup(current);
 430	ancestor = cgroup_ancestor(cgrp, ancestor_level);
 431	cgrp_id = ancestor ? cgroup_id(ancestor) : 0;
 432	rcu_read_unlock();
 433
 434	return cgrp_id;
 435}
 436
 437const struct bpf_func_proto bpf_get_current_ancestor_cgroup_id_proto = {
 438	.func		= bpf_get_current_ancestor_cgroup_id,
 439	.gpl_only	= false,
 440	.ret_type	= RET_INTEGER,
 441	.arg1_type	= ARG_ANYTHING,
 442};
 443#endif /* CONFIG_CGROUPS */
 444
 445#define BPF_STRTOX_BASE_MASK 0x1F
 446
 447static int __bpf_strtoull(const char *buf, size_t buf_len, u64 flags,
 448			  unsigned long long *res, bool *is_negative)
 449{
 450	unsigned int base = flags & BPF_STRTOX_BASE_MASK;
 451	const char *cur_buf = buf;
 452	size_t cur_len = buf_len;
 453	unsigned int consumed;
 454	size_t val_len;
 455	char str[64];
 456
 457	if (!buf || !buf_len || !res || !is_negative)
 458		return -EINVAL;
 459
 460	if (base != 0 && base != 8 && base != 10 && base != 16)
 461		return -EINVAL;
 462
 463	if (flags & ~BPF_STRTOX_BASE_MASK)
 464		return -EINVAL;
 465
 466	while (cur_buf < buf + buf_len && isspace(*cur_buf))
 467		++cur_buf;
 468
 469	*is_negative = (cur_buf < buf + buf_len && *cur_buf == '-');
 470	if (*is_negative)
 471		++cur_buf;
 472
 473	consumed = cur_buf - buf;
 474	cur_len -= consumed;
 475	if (!cur_len)
 476		return -EINVAL;
 477
 478	cur_len = min(cur_len, sizeof(str) - 1);
 479	memcpy(str, cur_buf, cur_len);
 480	str[cur_len] = '\0';
 481	cur_buf = str;
 482
 483	cur_buf = _parse_integer_fixup_radix(cur_buf, &base);
 484	val_len = _parse_integer(cur_buf, base, res);
 485
 486	if (val_len & KSTRTOX_OVERFLOW)
 487		return -ERANGE;
 488
 489	if (val_len == 0)
 490		return -EINVAL;
 491
 492	cur_buf += val_len;
 493	consumed += cur_buf - str;
 494
 495	return consumed;
 496}
 497
 498static int __bpf_strtoll(const char *buf, size_t buf_len, u64 flags,
 499			 long long *res)
 500{
 501	unsigned long long _res;
 502	bool is_negative;
 503	int err;
 504
 505	err = __bpf_strtoull(buf, buf_len, flags, &_res, &is_negative);
 506	if (err < 0)
 507		return err;
 508	if (is_negative) {
 509		if ((long long)-_res > 0)
 510			return -ERANGE;
 511		*res = -_res;
 512	} else {
 513		if ((long long)_res < 0)
 514			return -ERANGE;
 515		*res = _res;
 516	}
 517	return err;
 518}
 519
 520BPF_CALL_4(bpf_strtol, const char *, buf, size_t, buf_len, u64, flags,
 521	   s64 *, res)
 522{
 523	long long _res;
 524	int err;
 525
 526	*res = 0;
 527	err = __bpf_strtoll(buf, buf_len, flags, &_res);
 528	if (err < 0)
 529		return err;
 
 
 530	*res = _res;
 531	return err;
 532}
 533
 534const struct bpf_func_proto bpf_strtol_proto = {
 535	.func		= bpf_strtol,
 536	.gpl_only	= false,
 537	.ret_type	= RET_INTEGER,
 538	.arg1_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
 539	.arg2_type	= ARG_CONST_SIZE,
 540	.arg3_type	= ARG_ANYTHING,
 541	.arg4_type	= ARG_PTR_TO_FIXED_SIZE_MEM | MEM_UNINIT | MEM_WRITE | MEM_ALIGNED,
 542	.arg4_size	= sizeof(s64),
 543};
 544
 545BPF_CALL_4(bpf_strtoul, const char *, buf, size_t, buf_len, u64, flags,
 546	   u64 *, res)
 547{
 548	unsigned long long _res;
 549	bool is_negative;
 550	int err;
 551
 552	*res = 0;
 553	err = __bpf_strtoull(buf, buf_len, flags, &_res, &is_negative);
 554	if (err < 0)
 555		return err;
 556	if (is_negative)
 557		return -EINVAL;
 
 
 558	*res = _res;
 559	return err;
 560}
 561
 562const struct bpf_func_proto bpf_strtoul_proto = {
 563	.func		= bpf_strtoul,
 564	.gpl_only	= false,
 565	.ret_type	= RET_INTEGER,
 566	.arg1_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
 567	.arg2_type	= ARG_CONST_SIZE,
 568	.arg3_type	= ARG_ANYTHING,
 569	.arg4_type	= ARG_PTR_TO_FIXED_SIZE_MEM | MEM_UNINIT | MEM_WRITE | MEM_ALIGNED,
 570	.arg4_size	= sizeof(u64),
 571};
 572
 573BPF_CALL_3(bpf_strncmp, const char *, s1, u32, s1_sz, const char *, s2)
 574{
 575	return strncmp(s1, s2, s1_sz);
 576}
 577
 578static const struct bpf_func_proto bpf_strncmp_proto = {
 579	.func		= bpf_strncmp,
 580	.gpl_only	= false,
 581	.ret_type	= RET_INTEGER,
 582	.arg1_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
 583	.arg2_type	= ARG_CONST_SIZE,
 584	.arg3_type	= ARG_PTR_TO_CONST_STR,
 585};
 586
 587BPF_CALL_4(bpf_get_ns_current_pid_tgid, u64, dev, u64, ino,
 588	   struct bpf_pidns_info *, nsdata, u32, size)
 589{
 590	struct task_struct *task = current;
 591	struct pid_namespace *pidns;
 592	int err = -EINVAL;
 593
 594	if (unlikely(size != sizeof(struct bpf_pidns_info)))
 595		goto clear;
 596
 597	if (unlikely((u64)(dev_t)dev != dev))
 598		goto clear;
 599
 600	if (unlikely(!task))
 601		goto clear;
 602
 603	pidns = task_active_pid_ns(task);
 604	if (unlikely(!pidns)) {
 605		err = -ENOENT;
 606		goto clear;
 607	}
 608
 609	if (!ns_match(&pidns->ns, (dev_t)dev, ino))
 610		goto clear;
 611
 612	nsdata->pid = task_pid_nr_ns(task, pidns);
 613	nsdata->tgid = task_tgid_nr_ns(task, pidns);
 614	return 0;
 615clear:
 616	memset((void *)nsdata, 0, (size_t) size);
 617	return err;
 618}
 619
 620const struct bpf_func_proto bpf_get_ns_current_pid_tgid_proto = {
 621	.func		= bpf_get_ns_current_pid_tgid,
 622	.gpl_only	= false,
 623	.ret_type	= RET_INTEGER,
 624	.arg1_type	= ARG_ANYTHING,
 625	.arg2_type	= ARG_ANYTHING,
 626	.arg3_type      = ARG_PTR_TO_UNINIT_MEM,
 627	.arg4_type      = ARG_CONST_SIZE,
 628};
 629
 630static const struct bpf_func_proto bpf_get_raw_smp_processor_id_proto = {
 631	.func		= bpf_get_raw_cpu_id,
 632	.gpl_only	= false,
 633	.ret_type	= RET_INTEGER,
 634};
 635
 636BPF_CALL_5(bpf_event_output_data, void *, ctx, struct bpf_map *, map,
 637	   u64, flags, void *, data, u64, size)
 638{
 639	if (unlikely(flags & ~(BPF_F_INDEX_MASK)))
 640		return -EINVAL;
 641
 642	return bpf_event_output(map, flags, data, size, NULL, 0, NULL);
 643}
 644
 645const struct bpf_func_proto bpf_event_output_data_proto =  {
 646	.func		= bpf_event_output_data,
 647	.gpl_only       = true,
 648	.ret_type       = RET_INTEGER,
 649	.arg1_type      = ARG_PTR_TO_CTX,
 650	.arg2_type      = ARG_CONST_MAP_PTR,
 651	.arg3_type      = ARG_ANYTHING,
 652	.arg4_type      = ARG_PTR_TO_MEM | MEM_RDONLY,
 653	.arg5_type      = ARG_CONST_SIZE_OR_ZERO,
 654};
 655
 656BPF_CALL_3(bpf_copy_from_user, void *, dst, u32, size,
 657	   const void __user *, user_ptr)
 658{
 659	int ret = copy_from_user(dst, user_ptr, size);
 660
 661	if (unlikely(ret)) {
 662		memset(dst, 0, size);
 663		ret = -EFAULT;
 664	}
 665
 666	return ret;
 667}
 668
 669const struct bpf_func_proto bpf_copy_from_user_proto = {
 670	.func		= bpf_copy_from_user,
 671	.gpl_only	= false,
 672	.might_sleep	= true,
 673	.ret_type	= RET_INTEGER,
 674	.arg1_type	= ARG_PTR_TO_UNINIT_MEM,
 675	.arg2_type	= ARG_CONST_SIZE_OR_ZERO,
 676	.arg3_type	= ARG_ANYTHING,
 677};
 678
 679BPF_CALL_5(bpf_copy_from_user_task, void *, dst, u32, size,
 680	   const void __user *, user_ptr, struct task_struct *, tsk, u64, flags)
 681{
 682	int ret;
 683
 684	/* flags is not used yet */
 685	if (unlikely(flags))
 686		return -EINVAL;
 687
 688	if (unlikely(!size))
 689		return 0;
 690
 691	ret = access_process_vm(tsk, (unsigned long)user_ptr, dst, size, 0);
 692	if (ret == size)
 693		return 0;
 694
 695	memset(dst, 0, size);
 696	/* Return -EFAULT for partial read */
 697	return ret < 0 ? ret : -EFAULT;
 698}
 699
 700const struct bpf_func_proto bpf_copy_from_user_task_proto = {
 701	.func		= bpf_copy_from_user_task,
 702	.gpl_only	= true,
 703	.might_sleep	= true,
 704	.ret_type	= RET_INTEGER,
 705	.arg1_type	= ARG_PTR_TO_UNINIT_MEM,
 706	.arg2_type	= ARG_CONST_SIZE_OR_ZERO,
 707	.arg3_type	= ARG_ANYTHING,
 708	.arg4_type	= ARG_PTR_TO_BTF_ID,
 709	.arg4_btf_id	= &btf_tracing_ids[BTF_TRACING_TYPE_TASK],
 710	.arg5_type	= ARG_ANYTHING
 711};
 712
 713BPF_CALL_2(bpf_per_cpu_ptr, const void *, ptr, u32, cpu)
 714{
 715	if (cpu >= nr_cpu_ids)
 716		return (unsigned long)NULL;
 717
 718	return (unsigned long)per_cpu_ptr((const void __percpu *)(const uintptr_t)ptr, cpu);
 719}
 720
 721const struct bpf_func_proto bpf_per_cpu_ptr_proto = {
 722	.func		= bpf_per_cpu_ptr,
 723	.gpl_only	= false,
 724	.ret_type	= RET_PTR_TO_MEM_OR_BTF_ID | PTR_MAYBE_NULL | MEM_RDONLY,
 725	.arg1_type	= ARG_PTR_TO_PERCPU_BTF_ID,
 726	.arg2_type	= ARG_ANYTHING,
 727};
 728
 729BPF_CALL_1(bpf_this_cpu_ptr, const void *, percpu_ptr)
 730{
 731	return (unsigned long)this_cpu_ptr((const void __percpu *)(const uintptr_t)percpu_ptr);
 732}
 733
 734const struct bpf_func_proto bpf_this_cpu_ptr_proto = {
 735	.func		= bpf_this_cpu_ptr,
 736	.gpl_only	= false,
 737	.ret_type	= RET_PTR_TO_MEM_OR_BTF_ID | MEM_RDONLY,
 738	.arg1_type	= ARG_PTR_TO_PERCPU_BTF_ID,
 739};
 740
 741static int bpf_trace_copy_string(char *buf, void *unsafe_ptr, char fmt_ptype,
 742		size_t bufsz)
 743{
 744	void __user *user_ptr = (__force void __user *)unsafe_ptr;
 745
 746	buf[0] = 0;
 747
 748	switch (fmt_ptype) {
 749	case 's':
 750#ifdef CONFIG_ARCH_HAS_NON_OVERLAPPING_ADDRESS_SPACE
 751		if ((unsigned long)unsafe_ptr < TASK_SIZE)
 752			return strncpy_from_user_nofault(buf, user_ptr, bufsz);
 753		fallthrough;
 754#endif
 755	case 'k':
 756		return strncpy_from_kernel_nofault(buf, unsafe_ptr, bufsz);
 757	case 'u':
 758		return strncpy_from_user_nofault(buf, user_ptr, bufsz);
 759	}
 760
 761	return -EINVAL;
 762}
 763
 764/* Per-cpu temp buffers used by printf-like helpers to store the bprintf binary
 765 * arguments representation.
 766 */
 767#define MAX_BPRINTF_BIN_ARGS	512
 768
 769/* Support executing three nested bprintf helper calls on a given CPU */
 770#define MAX_BPRINTF_NEST_LEVEL	3
 771struct bpf_bprintf_buffers {
 772	char bin_args[MAX_BPRINTF_BIN_ARGS];
 773	char buf[MAX_BPRINTF_BUF];
 774};
 775
 776static DEFINE_PER_CPU(struct bpf_bprintf_buffers[MAX_BPRINTF_NEST_LEVEL], bpf_bprintf_bufs);
 777static DEFINE_PER_CPU(int, bpf_bprintf_nest_level);
 778
 779static int try_get_buffers(struct bpf_bprintf_buffers **bufs)
 780{
 781	int nest_level;
 782
 783	preempt_disable();
 784	nest_level = this_cpu_inc_return(bpf_bprintf_nest_level);
 785	if (WARN_ON_ONCE(nest_level > MAX_BPRINTF_NEST_LEVEL)) {
 786		this_cpu_dec(bpf_bprintf_nest_level);
 787		preempt_enable();
 788		return -EBUSY;
 789	}
 790	*bufs = this_cpu_ptr(&bpf_bprintf_bufs[nest_level - 1]);
 791
 792	return 0;
 793}
 794
 795void bpf_bprintf_cleanup(struct bpf_bprintf_data *data)
 796{
 797	if (!data->bin_args && !data->buf)
 798		return;
 799	if (WARN_ON_ONCE(this_cpu_read(bpf_bprintf_nest_level) == 0))
 800		return;
 801	this_cpu_dec(bpf_bprintf_nest_level);
 802	preempt_enable();
 803}
 804
 805/*
 806 * bpf_bprintf_prepare - Generic pass on format strings for bprintf-like helpers
 807 *
 808 * Returns a negative value if fmt is an invalid format string or 0 otherwise.
 809 *
 810 * This can be used in two ways:
 811 * - Format string verification only: when data->get_bin_args is false
 812 * - Arguments preparation: in addition to the above verification, it writes in
 813 *   data->bin_args a binary representation of arguments usable by bstr_printf
 814 *   where pointers from BPF have been sanitized.
 815 *
 816 * In argument preparation mode, if 0 is returned, safe temporary buffers are
 817 * allocated and bpf_bprintf_cleanup should be called to free them after use.
 818 */
 819int bpf_bprintf_prepare(char *fmt, u32 fmt_size, const u64 *raw_args,
 820			u32 num_args, struct bpf_bprintf_data *data)
 821{
 822	bool get_buffers = (data->get_bin_args && num_args) || data->get_buf;
 823	char *unsafe_ptr = NULL, *tmp_buf = NULL, *tmp_buf_end, *fmt_end;
 824	struct bpf_bprintf_buffers *buffers = NULL;
 825	size_t sizeof_cur_arg, sizeof_cur_ip;
 826	int err, i, num_spec = 0;
 827	u64 cur_arg;
 828	char fmt_ptype, cur_ip[16], ip_spec[] = "%pXX";
 829
 830	fmt_end = strnchr(fmt, fmt_size, 0);
 831	if (!fmt_end)
 832		return -EINVAL;
 833	fmt_size = fmt_end - fmt;
 834
 835	if (get_buffers && try_get_buffers(&buffers))
 836		return -EBUSY;
 837
 838	if (data->get_bin_args) {
 839		if (num_args)
 840			tmp_buf = buffers->bin_args;
 841		tmp_buf_end = tmp_buf + MAX_BPRINTF_BIN_ARGS;
 842		data->bin_args = (u32 *)tmp_buf;
 843	}
 844
 845	if (data->get_buf)
 846		data->buf = buffers->buf;
 847
 848	for (i = 0; i < fmt_size; i++) {
 849		if ((!isprint(fmt[i]) && !isspace(fmt[i])) || !isascii(fmt[i])) {
 850			err = -EINVAL;
 851			goto out;
 852		}
 853
 854		if (fmt[i] != '%')
 855			continue;
 856
 857		if (fmt[i + 1] == '%') {
 858			i++;
 859			continue;
 860		}
 861
 862		if (num_spec >= num_args) {
 863			err = -EINVAL;
 864			goto out;
 865		}
 866
 867		/* The string is zero-terminated so if fmt[i] != 0, we can
 868		 * always access fmt[i + 1], in the worst case it will be a 0
 869		 */
 870		i++;
 871
 872		/* skip optional "[0 +-][num]" width formatting field */
 873		while (fmt[i] == '0' || fmt[i] == '+'  || fmt[i] == '-' ||
 874		       fmt[i] == ' ')
 875			i++;
 876		if (fmt[i] >= '1' && fmt[i] <= '9') {
 877			i++;
 878			while (fmt[i] >= '0' && fmt[i] <= '9')
 879				i++;
 880		}
 881
 882		if (fmt[i] == 'p') {
 883			sizeof_cur_arg = sizeof(long);
 884
 885			if ((fmt[i + 1] == 'k' || fmt[i + 1] == 'u') &&
 886			    fmt[i + 2] == 's') {
 887				fmt_ptype = fmt[i + 1];
 888				i += 2;
 889				goto fmt_str;
 890			}
 891
 892			if (fmt[i + 1] == 0 || isspace(fmt[i + 1]) ||
 893			    ispunct(fmt[i + 1]) || fmt[i + 1] == 'K' ||
 894			    fmt[i + 1] == 'x' || fmt[i + 1] == 's' ||
 895			    fmt[i + 1] == 'S') {
 896				/* just kernel pointers */
 897				if (tmp_buf)
 898					cur_arg = raw_args[num_spec];
 899				i++;
 900				goto nocopy_fmt;
 901			}
 902
 903			if (fmt[i + 1] == 'B') {
 904				if (tmp_buf)  {
 905					err = snprintf(tmp_buf,
 906						       (tmp_buf_end - tmp_buf),
 907						       "%pB",
 908						       (void *)(long)raw_args[num_spec]);
 909					tmp_buf += (err + 1);
 910				}
 911
 912				i++;
 913				num_spec++;
 914				continue;
 915			}
 916
 917			/* only support "%pI4", "%pi4", "%pI6" and "%pi6". */
 918			if ((fmt[i + 1] != 'i' && fmt[i + 1] != 'I') ||
 919			    (fmt[i + 2] != '4' && fmt[i + 2] != '6')) {
 920				err = -EINVAL;
 921				goto out;
 922			}
 923
 924			i += 2;
 925			if (!tmp_buf)
 926				goto nocopy_fmt;
 927
 928			sizeof_cur_ip = (fmt[i] == '4') ? 4 : 16;
 929			if (tmp_buf_end - tmp_buf < sizeof_cur_ip) {
 930				err = -ENOSPC;
 931				goto out;
 932			}
 933
 934			unsafe_ptr = (char *)(long)raw_args[num_spec];
 935			err = copy_from_kernel_nofault(cur_ip, unsafe_ptr,
 936						       sizeof_cur_ip);
 937			if (err < 0)
 938				memset(cur_ip, 0, sizeof_cur_ip);
 939
 940			/* hack: bstr_printf expects IP addresses to be
 941			 * pre-formatted as strings, ironically, the easiest way
 942			 * to do that is to call snprintf.
 943			 */
 944			ip_spec[2] = fmt[i - 1];
 945			ip_spec[3] = fmt[i];
 946			err = snprintf(tmp_buf, tmp_buf_end - tmp_buf,
 947				       ip_spec, &cur_ip);
 948
 949			tmp_buf += err + 1;
 950			num_spec++;
 951
 952			continue;
 953		} else if (fmt[i] == 's') {
 954			fmt_ptype = fmt[i];
 955fmt_str:
 956			if (fmt[i + 1] != 0 &&
 957			    !isspace(fmt[i + 1]) &&
 958			    !ispunct(fmt[i + 1])) {
 959				err = -EINVAL;
 960				goto out;
 961			}
 962
 963			if (!tmp_buf)
 964				goto nocopy_fmt;
 965
 966			if (tmp_buf_end == tmp_buf) {
 967				err = -ENOSPC;
 968				goto out;
 969			}
 970
 971			unsafe_ptr = (char *)(long)raw_args[num_spec];
 972			err = bpf_trace_copy_string(tmp_buf, unsafe_ptr,
 973						    fmt_ptype,
 974						    tmp_buf_end - tmp_buf);
 975			if (err < 0) {
 976				tmp_buf[0] = '\0';
 977				err = 1;
 978			}
 979
 980			tmp_buf += err;
 981			num_spec++;
 982
 983			continue;
 984		} else if (fmt[i] == 'c') {
 985			if (!tmp_buf)
 986				goto nocopy_fmt;
 987
 988			if (tmp_buf_end == tmp_buf) {
 989				err = -ENOSPC;
 990				goto out;
 991			}
 992
 993			*tmp_buf = raw_args[num_spec];
 994			tmp_buf++;
 995			num_spec++;
 996
 997			continue;
 998		}
 999
1000		sizeof_cur_arg = sizeof(int);
1001
1002		if (fmt[i] == 'l') {
1003			sizeof_cur_arg = sizeof(long);
1004			i++;
1005		}
1006		if (fmt[i] == 'l') {
1007			sizeof_cur_arg = sizeof(long long);
1008			i++;
1009		}
1010
1011		if (fmt[i] != 'i' && fmt[i] != 'd' && fmt[i] != 'u' &&
1012		    fmt[i] != 'x' && fmt[i] != 'X') {
1013			err = -EINVAL;
1014			goto out;
1015		}
1016
1017		if (tmp_buf)
1018			cur_arg = raw_args[num_spec];
1019nocopy_fmt:
1020		if (tmp_buf) {
1021			tmp_buf = PTR_ALIGN(tmp_buf, sizeof(u32));
1022			if (tmp_buf_end - tmp_buf < sizeof_cur_arg) {
1023				err = -ENOSPC;
1024				goto out;
1025			}
1026
1027			if (sizeof_cur_arg == 8) {
1028				*(u32 *)tmp_buf = *(u32 *)&cur_arg;
1029				*(u32 *)(tmp_buf + 4) = *((u32 *)&cur_arg + 1);
1030			} else {
1031				*(u32 *)tmp_buf = (u32)(long)cur_arg;
1032			}
1033			tmp_buf += sizeof_cur_arg;
1034		}
1035		num_spec++;
1036	}
1037
1038	err = 0;
1039out:
1040	if (err)
1041		bpf_bprintf_cleanup(data);
1042	return err;
1043}
1044
1045BPF_CALL_5(bpf_snprintf, char *, str, u32, str_size, char *, fmt,
1046	   const void *, args, u32, data_len)
1047{
1048	struct bpf_bprintf_data data = {
1049		.get_bin_args	= true,
1050	};
1051	int err, num_args;
1052
1053	if (data_len % 8 || data_len > MAX_BPRINTF_VARARGS * 8 ||
1054	    (data_len && !args))
1055		return -EINVAL;
1056	num_args = data_len / 8;
1057
1058	/* ARG_PTR_TO_CONST_STR guarantees that fmt is zero-terminated so we
1059	 * can safely give an unbounded size.
1060	 */
1061	err = bpf_bprintf_prepare(fmt, UINT_MAX, args, num_args, &data);
1062	if (err < 0)
1063		return err;
1064
1065	err = bstr_printf(str, str_size, fmt, data.bin_args);
1066
1067	bpf_bprintf_cleanup(&data);
1068
1069	return err + 1;
1070}
1071
1072const struct bpf_func_proto bpf_snprintf_proto = {
1073	.func		= bpf_snprintf,
1074	.gpl_only	= true,
1075	.ret_type	= RET_INTEGER,
1076	.arg1_type	= ARG_PTR_TO_MEM_OR_NULL,
1077	.arg2_type	= ARG_CONST_SIZE_OR_ZERO,
1078	.arg3_type	= ARG_PTR_TO_CONST_STR,
1079	.arg4_type	= ARG_PTR_TO_MEM | PTR_MAYBE_NULL | MEM_RDONLY,
1080	.arg5_type	= ARG_CONST_SIZE_OR_ZERO,
1081};
1082
1083struct bpf_async_cb {
1084	struct bpf_map *map;
1085	struct bpf_prog *prog;
1086	void __rcu *callback_fn;
1087	void *value;
1088	union {
1089		struct rcu_head rcu;
1090		struct work_struct delete_work;
1091	};
1092	u64 flags;
1093};
1094
1095/* BPF map elements can contain 'struct bpf_timer'.
1096 * Such map owns all of its BPF timers.
1097 * 'struct bpf_timer' is allocated as part of map element allocation
1098 * and it's zero initialized.
1099 * That space is used to keep 'struct bpf_async_kern'.
1100 * bpf_timer_init() allocates 'struct bpf_hrtimer', inits hrtimer, and
1101 * remembers 'struct bpf_map *' pointer it's part of.
1102 * bpf_timer_set_callback() increments prog refcnt and assign bpf callback_fn.
1103 * bpf_timer_start() arms the timer.
1104 * If user space reference to a map goes to zero at this point
1105 * ops->map_release_uref callback is responsible for cancelling the timers,
1106 * freeing their memory, and decrementing prog's refcnts.
1107 * bpf_timer_cancel() cancels the timer and decrements prog's refcnt.
1108 * Inner maps can contain bpf timers as well. ops->map_release_uref is
1109 * freeing the timers when inner map is replaced or deleted by user space.
1110 */
1111struct bpf_hrtimer {
1112	struct bpf_async_cb cb;
1113	struct hrtimer timer;
1114	atomic_t cancelling;
 
 
 
 
1115};
1116
1117struct bpf_work {
1118	struct bpf_async_cb cb;
1119	struct work_struct work;
1120	struct work_struct delete_work;
1121};
1122
1123/* the actual struct hidden inside uapi struct bpf_timer and bpf_wq */
1124struct bpf_async_kern {
1125	union {
1126		struct bpf_async_cb *cb;
1127		struct bpf_hrtimer *timer;
1128		struct bpf_work *work;
1129	};
1130	/* bpf_spin_lock is used here instead of spinlock_t to make
1131	 * sure that it always fits into space reserved by struct bpf_timer
1132	 * regardless of LOCKDEP and spinlock debug flags.
1133	 */
1134	struct bpf_spin_lock lock;
1135} __attribute__((aligned(8)));
1136
1137enum bpf_async_type {
1138	BPF_ASYNC_TYPE_TIMER = 0,
1139	BPF_ASYNC_TYPE_WQ,
1140};
1141
1142static DEFINE_PER_CPU(struct bpf_hrtimer *, hrtimer_running);
1143
1144static enum hrtimer_restart bpf_timer_cb(struct hrtimer *hrtimer)
1145{
1146	struct bpf_hrtimer *t = container_of(hrtimer, struct bpf_hrtimer, timer);
1147	struct bpf_map *map = t->cb.map;
1148	void *value = t->cb.value;
1149	bpf_callback_t callback_fn;
1150	void *key;
1151	u32 idx;
1152
1153	BTF_TYPE_EMIT(struct bpf_timer);
1154	callback_fn = rcu_dereference_check(t->cb.callback_fn, rcu_read_lock_bh_held());
1155	if (!callback_fn)
1156		goto out;
1157
1158	/* bpf_timer_cb() runs in hrtimer_run_softirq. It doesn't migrate and
1159	 * cannot be preempted by another bpf_timer_cb() on the same cpu.
1160	 * Remember the timer this callback is servicing to prevent
1161	 * deadlock if callback_fn() calls bpf_timer_cancel() or
1162	 * bpf_map_delete_elem() on the same timer.
1163	 */
1164	this_cpu_write(hrtimer_running, t);
1165	if (map->map_type == BPF_MAP_TYPE_ARRAY) {
1166		struct bpf_array *array = container_of(map, struct bpf_array, map);
1167
1168		/* compute the key */
1169		idx = ((char *)value - array->value) / array->elem_size;
1170		key = &idx;
1171	} else { /* hash or lru */
1172		key = value - round_up(map->key_size, 8);
1173	}
1174
1175	callback_fn((u64)(long)map, (u64)(long)key, (u64)(long)value, 0, 0);
1176	/* The verifier checked that return value is zero. */
1177
1178	this_cpu_write(hrtimer_running, NULL);
1179out:
1180	return HRTIMER_NORESTART;
1181}
1182
1183static void bpf_wq_work(struct work_struct *work)
 
1184{
1185	struct bpf_work *w = container_of(work, struct bpf_work, work);
1186	struct bpf_async_cb *cb = &w->cb;
1187	struct bpf_map *map = cb->map;
1188	bpf_callback_t callback_fn;
1189	void *value = cb->value;
1190	void *key;
1191	u32 idx;
1192
1193	BTF_TYPE_EMIT(struct bpf_wq);
1194
1195	callback_fn = READ_ONCE(cb->callback_fn);
1196	if (!callback_fn)
1197		return;
1198
1199	if (map->map_type == BPF_MAP_TYPE_ARRAY) {
1200		struct bpf_array *array = container_of(map, struct bpf_array, map);
1201
1202		/* compute the key */
1203		idx = ((char *)value - array->value) / array->elem_size;
1204		key = &idx;
1205	} else { /* hash or lru */
1206		key = value - round_up(map->key_size, 8);
1207	}
1208
1209        rcu_read_lock_trace();
1210        migrate_disable();
1211
1212	callback_fn((u64)(long)map, (u64)(long)key, (u64)(long)value, 0, 0);
1213
1214	migrate_enable();
1215	rcu_read_unlock_trace();
1216}
1217
1218static void bpf_wq_delete_work(struct work_struct *work)
1219{
1220	struct bpf_work *w = container_of(work, struct bpf_work, delete_work);
1221
1222	cancel_work_sync(&w->work);
1223
1224	kfree_rcu(w, cb.rcu);
1225}
1226
1227static void bpf_timer_delete_work(struct work_struct *work)
1228{
1229	struct bpf_hrtimer *t = container_of(work, struct bpf_hrtimer, cb.delete_work);
1230
1231	/* Cancel the timer and wait for callback to complete if it was running.
1232	 * If hrtimer_cancel() can be safely called it's safe to call
1233	 * kfree_rcu(t) right after for both preallocated and non-preallocated
1234	 * maps.  The async->cb = NULL was already done and no code path can see
1235	 * address 't' anymore. Timer if armed for existing bpf_hrtimer before
1236	 * bpf_timer_cancel_and_free will have been cancelled.
1237	 */
1238	hrtimer_cancel(&t->timer);
1239	kfree_rcu(t, cb.rcu);
1240}
1241
1242static int __bpf_async_init(struct bpf_async_kern *async, struct bpf_map *map, u64 flags,
1243			    enum bpf_async_type type)
1244{
1245	struct bpf_async_cb *cb;
1246	struct bpf_hrtimer *t;
1247	struct bpf_work *w;
1248	clockid_t clockid;
1249	size_t size;
1250	int ret = 0;
1251
 
 
 
 
1252	if (in_nmi())
1253		return -EOPNOTSUPP;
1254
1255	switch (type) {
1256	case BPF_ASYNC_TYPE_TIMER:
1257		size = sizeof(struct bpf_hrtimer);
1258		break;
1259	case BPF_ASYNC_TYPE_WQ:
1260		size = sizeof(struct bpf_work);
1261		break;
1262	default:
1263		return -EINVAL;
1264	}
1265
1266	__bpf_spin_lock_irqsave(&async->lock);
1267	t = async->timer;
1268	if (t) {
1269		ret = -EBUSY;
1270		goto out;
1271	}
1272
1273	/* allocate hrtimer via map_kmalloc to use memcg accounting */
1274	cb = bpf_map_kmalloc_node(map, size, GFP_ATOMIC, map->numa_node);
1275	if (!cb) {
1276		ret = -ENOMEM;
1277		goto out;
1278	}
1279
1280	switch (type) {
1281	case BPF_ASYNC_TYPE_TIMER:
1282		clockid = flags & (MAX_CLOCKS - 1);
1283		t = (struct bpf_hrtimer *)cb;
1284
1285		atomic_set(&t->cancelling, 0);
1286		INIT_WORK(&t->cb.delete_work, bpf_timer_delete_work);
1287		hrtimer_init(&t->timer, clockid, HRTIMER_MODE_REL_SOFT);
1288		t->timer.function = bpf_timer_cb;
1289		cb->value = (void *)async - map->record->timer_off;
1290		break;
1291	case BPF_ASYNC_TYPE_WQ:
1292		w = (struct bpf_work *)cb;
1293
1294		INIT_WORK(&w->work, bpf_wq_work);
1295		INIT_WORK(&w->delete_work, bpf_wq_delete_work);
1296		cb->value = (void *)async - map->record->wq_off;
1297		break;
1298	}
1299	cb->map = map;
1300	cb->prog = NULL;
1301	cb->flags = flags;
1302	rcu_assign_pointer(cb->callback_fn, NULL);
1303
1304	WRITE_ONCE(async->cb, cb);
1305	/* Guarantee the order between async->cb and map->usercnt. So
1306	 * when there are concurrent uref release and bpf timer init, either
1307	 * bpf_timer_cancel_and_free() called by uref release reads a no-NULL
1308	 * timer or atomic64_read() below returns a zero usercnt.
1309	 */
1310	smp_mb();
1311	if (!atomic64_read(&map->usercnt)) {
1312		/* maps with timers must be either held by user space
1313		 * or pinned in bpffs.
1314		 */
1315		WRITE_ONCE(async->cb, NULL);
1316		kfree(cb);
1317		ret = -EPERM;
1318	}
1319out:
1320	__bpf_spin_unlock_irqrestore(&async->lock);
1321	return ret;
1322}
1323
1324BPF_CALL_3(bpf_timer_init, struct bpf_async_kern *, timer, struct bpf_map *, map,
1325	   u64, flags)
1326{
1327	clock_t clockid = flags & (MAX_CLOCKS - 1);
1328
1329	BUILD_BUG_ON(MAX_CLOCKS != 16);
1330	BUILD_BUG_ON(sizeof(struct bpf_async_kern) > sizeof(struct bpf_timer));
1331	BUILD_BUG_ON(__alignof__(struct bpf_async_kern) != __alignof__(struct bpf_timer));
1332
1333	if (flags >= MAX_CLOCKS ||
1334	    /* similar to timerfd except _ALARM variants are not supported */
1335	    (clockid != CLOCK_MONOTONIC &&
1336	     clockid != CLOCK_REALTIME &&
1337	     clockid != CLOCK_BOOTTIME))
1338		return -EINVAL;
1339
1340	return __bpf_async_init(timer, map, flags, BPF_ASYNC_TYPE_TIMER);
1341}
1342
1343static const struct bpf_func_proto bpf_timer_init_proto = {
1344	.func		= bpf_timer_init,
1345	.gpl_only	= true,
1346	.ret_type	= RET_INTEGER,
1347	.arg1_type	= ARG_PTR_TO_TIMER,
1348	.arg2_type	= ARG_CONST_MAP_PTR,
1349	.arg3_type	= ARG_ANYTHING,
1350};
1351
1352static int __bpf_async_set_callback(struct bpf_async_kern *async, void *callback_fn,
1353				    struct bpf_prog_aux *aux, unsigned int flags,
1354				    enum bpf_async_type type)
1355{
1356	struct bpf_prog *prev, *prog = aux->prog;
1357	struct bpf_async_cb *cb;
1358	int ret = 0;
1359
1360	if (in_nmi())
1361		return -EOPNOTSUPP;
1362	__bpf_spin_lock_irqsave(&async->lock);
1363	cb = async->cb;
1364	if (!cb) {
1365		ret = -EINVAL;
1366		goto out;
1367	}
1368	if (!atomic64_read(&cb->map->usercnt)) {
1369		/* maps with timers must be either held by user space
1370		 * or pinned in bpffs. Otherwise timer might still be
1371		 * running even when bpf prog is detached and user space
1372		 * is gone, since map_release_uref won't ever be called.
1373		 */
1374		ret = -EPERM;
1375		goto out;
1376	}
1377	prev = cb->prog;
1378	if (prev != prog) {
1379		/* Bump prog refcnt once. Every bpf_timer_set_callback()
1380		 * can pick different callback_fn-s within the same prog.
1381		 */
1382		prog = bpf_prog_inc_not_zero(prog);
1383		if (IS_ERR(prog)) {
1384			ret = PTR_ERR(prog);
1385			goto out;
1386		}
1387		if (prev)
1388			/* Drop prev prog refcnt when swapping with new prog */
1389			bpf_prog_put(prev);
1390		cb->prog = prog;
1391	}
1392	rcu_assign_pointer(cb->callback_fn, callback_fn);
1393out:
1394	__bpf_spin_unlock_irqrestore(&async->lock);
1395	return ret;
1396}
1397
1398BPF_CALL_3(bpf_timer_set_callback, struct bpf_async_kern *, timer, void *, callback_fn,
1399	   struct bpf_prog_aux *, aux)
1400{
1401	return __bpf_async_set_callback(timer, callback_fn, aux, 0, BPF_ASYNC_TYPE_TIMER);
1402}
1403
1404static const struct bpf_func_proto bpf_timer_set_callback_proto = {
1405	.func		= bpf_timer_set_callback,
1406	.gpl_only	= true,
1407	.ret_type	= RET_INTEGER,
1408	.arg1_type	= ARG_PTR_TO_TIMER,
1409	.arg2_type	= ARG_PTR_TO_FUNC,
1410};
1411
1412BPF_CALL_3(bpf_timer_start, struct bpf_async_kern *, timer, u64, nsecs, u64, flags)
1413{
1414	struct bpf_hrtimer *t;
1415	int ret = 0;
1416	enum hrtimer_mode mode;
1417
1418	if (in_nmi())
1419		return -EOPNOTSUPP;
1420	if (flags & ~(BPF_F_TIMER_ABS | BPF_F_TIMER_CPU_PIN))
1421		return -EINVAL;
1422	__bpf_spin_lock_irqsave(&timer->lock);
1423	t = timer->timer;
1424	if (!t || !t->cb.prog) {
1425		ret = -EINVAL;
1426		goto out;
1427	}
1428
1429	if (flags & BPF_F_TIMER_ABS)
1430		mode = HRTIMER_MODE_ABS_SOFT;
1431	else
1432		mode = HRTIMER_MODE_REL_SOFT;
1433
1434	if (flags & BPF_F_TIMER_CPU_PIN)
1435		mode |= HRTIMER_MODE_PINNED;
1436
1437	hrtimer_start(&t->timer, ns_to_ktime(nsecs), mode);
1438out:
1439	__bpf_spin_unlock_irqrestore(&timer->lock);
1440	return ret;
1441}
1442
1443static const struct bpf_func_proto bpf_timer_start_proto = {
1444	.func		= bpf_timer_start,
1445	.gpl_only	= true,
1446	.ret_type	= RET_INTEGER,
1447	.arg1_type	= ARG_PTR_TO_TIMER,
1448	.arg2_type	= ARG_ANYTHING,
1449	.arg3_type	= ARG_ANYTHING,
1450};
1451
1452static void drop_prog_refcnt(struct bpf_async_cb *async)
1453{
1454	struct bpf_prog *prog = async->prog;
1455
1456	if (prog) {
1457		bpf_prog_put(prog);
1458		async->prog = NULL;
1459		rcu_assign_pointer(async->callback_fn, NULL);
1460	}
1461}
1462
1463BPF_CALL_1(bpf_timer_cancel, struct bpf_async_kern *, timer)
1464{
1465	struct bpf_hrtimer *t, *cur_t;
1466	bool inc = false;
1467	int ret = 0;
1468
1469	if (in_nmi())
1470		return -EOPNOTSUPP;
1471	rcu_read_lock();
1472	__bpf_spin_lock_irqsave(&timer->lock);
1473	t = timer->timer;
1474	if (!t) {
1475		ret = -EINVAL;
1476		goto out;
1477	}
1478
1479	cur_t = this_cpu_read(hrtimer_running);
1480	if (cur_t == t) {
1481		/* If bpf callback_fn is trying to bpf_timer_cancel()
1482		 * its own timer the hrtimer_cancel() will deadlock
1483		 * since it waits for callback_fn to finish.
1484		 */
1485		ret = -EDEADLK;
1486		goto out;
1487	}
1488
1489	/* Only account in-flight cancellations when invoked from a timer
1490	 * callback, since we want to avoid waiting only if other _callbacks_
1491	 * are waiting on us, to avoid introducing lockups. Non-callback paths
1492	 * are ok, since nobody would synchronously wait for their completion.
1493	 */
1494	if (!cur_t)
1495		goto drop;
1496	atomic_inc(&t->cancelling);
1497	/* Need full barrier after relaxed atomic_inc */
1498	smp_mb__after_atomic();
1499	inc = true;
1500	if (atomic_read(&cur_t->cancelling)) {
1501		/* We're cancelling timer t, while some other timer callback is
1502		 * attempting to cancel us. In such a case, it might be possible
1503		 * that timer t belongs to the other callback, or some other
1504		 * callback waiting upon it (creating transitive dependencies
1505		 * upon us), and we will enter a deadlock if we continue
1506		 * cancelling and waiting for it synchronously, since it might
1507		 * do the same. Bail!
1508		 */
1509		ret = -EDEADLK;
1510		goto out;
1511	}
1512drop:
1513	drop_prog_refcnt(&t->cb);
1514out:
1515	__bpf_spin_unlock_irqrestore(&timer->lock);
1516	/* Cancel the timer and wait for associated callback to finish
1517	 * if it was running.
1518	 */
1519	ret = ret ?: hrtimer_cancel(&t->timer);
1520	if (inc)
1521		atomic_dec(&t->cancelling);
1522	rcu_read_unlock();
1523	return ret;
1524}
1525
1526static const struct bpf_func_proto bpf_timer_cancel_proto = {
1527	.func		= bpf_timer_cancel,
1528	.gpl_only	= true,
1529	.ret_type	= RET_INTEGER,
1530	.arg1_type	= ARG_PTR_TO_TIMER,
1531};
1532
1533static struct bpf_async_cb *__bpf_async_cancel_and_free(struct bpf_async_kern *async)
 
 
 
1534{
1535	struct bpf_async_cb *cb;
 
1536
1537	/* Performance optimization: read async->cb without lock first. */
1538	if (!READ_ONCE(async->cb))
1539		return NULL;
1540
1541	__bpf_spin_lock_irqsave(&async->lock);
1542	/* re-read it under lock */
1543	cb = async->cb;
1544	if (!cb)
1545		goto out;
1546	drop_prog_refcnt(cb);
1547	/* The subsequent bpf_timer_start/cancel() helpers won't be able to use
1548	 * this timer, since it won't be initialized.
1549	 */
1550	WRITE_ONCE(async->cb, NULL);
1551out:
1552	__bpf_spin_unlock_irqrestore(&async->lock);
1553	return cb;
1554}
1555
1556/* This function is called by map_delete/update_elem for individual element and
1557 * by ops->map_release_uref when the user space reference to a map reaches zero.
1558 */
1559void bpf_timer_cancel_and_free(void *val)
1560{
1561	struct bpf_hrtimer *t;
1562
1563	t = (struct bpf_hrtimer *)__bpf_async_cancel_and_free(val);
1564
1565	if (!t)
1566		return;
1567	/* We check that bpf_map_delete/update_elem() was called from timer
1568	 * callback_fn. In such case we don't call hrtimer_cancel() (since it
1569	 * will deadlock) and don't call hrtimer_try_to_cancel() (since it will
1570	 * just return -1). Though callback_fn is still running on this cpu it's
 
 
 
 
 
 
1571	 * safe to do kfree(t) because bpf_timer_cb() read everything it needed
1572	 * from 't'. The bpf subprog callback_fn won't be able to access 't',
1573	 * since async->cb = NULL was already done. The timer will be
1574	 * effectively cancelled because bpf_timer_cb() will return
1575	 * HRTIMER_NORESTART.
1576	 *
1577	 * However, it is possible the timer callback_fn calling us armed the
1578	 * timer _before_ calling us, such that failing to cancel it here will
1579	 * cause it to possibly use struct hrtimer after freeing bpf_hrtimer.
1580	 * Therefore, we _need_ to cancel any outstanding timers before we do
1581	 * kfree_rcu, even though no more timers can be armed.
1582	 *
1583	 * Moreover, we need to schedule work even if timer does not belong to
1584	 * the calling callback_fn, as on two different CPUs, we can end up in a
1585	 * situation where both sides run in parallel, try to cancel one
1586	 * another, and we end up waiting on both sides in hrtimer_cancel
1587	 * without making forward progress, since timer1 depends on time2
1588	 * callback to finish, and vice versa.
1589	 *
1590	 *  CPU 1 (timer1_cb)			CPU 2 (timer2_cb)
1591	 *  bpf_timer_cancel_and_free(timer2)	bpf_timer_cancel_and_free(timer1)
1592	 *
1593	 * To avoid these issues, punt to workqueue context when we are in a
1594	 * timer callback.
1595	 */
1596	if (this_cpu_read(hrtimer_running)) {
1597		queue_work(system_unbound_wq, &t->cb.delete_work);
1598		return;
1599	}
1600
1601	if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
1602		/* If the timer is running on other CPU, also use a kworker to
1603		 * wait for the completion of the timer instead of trying to
1604		 * acquire a sleepable lock in hrtimer_cancel() to wait for its
1605		 * completion.
1606		 */
1607		if (hrtimer_try_to_cancel(&t->timer) >= 0)
1608			kfree_rcu(t, cb.rcu);
1609		else
1610			queue_work(system_unbound_wq, &t->cb.delete_work);
1611	} else {
1612		bpf_timer_delete_work(&t->cb.delete_work);
1613	}
1614}
1615
1616/* This function is called by map_delete/update_elem for individual element and
1617 * by ops->map_release_uref when the user space reference to a map reaches zero.
1618 */
1619void bpf_wq_cancel_and_free(void *val)
1620{
1621	struct bpf_work *work;
1622
1623	BTF_TYPE_EMIT(struct bpf_wq);
1624
1625	work = (struct bpf_work *)__bpf_async_cancel_and_free(val);
1626	if (!work)
1627		return;
1628	/* Trigger cancel of the sleepable work, but *do not* wait for
1629	 * it to finish if it was running as we might not be in a
1630	 * sleepable context.
1631	 * kfree will be called once the work has finished.
1632	 */
1633	schedule_work(&work->delete_work);
1634}
1635
1636BPF_CALL_2(bpf_kptr_xchg, void *, dst, void *, ptr)
1637{
1638	unsigned long *kptr = dst;
1639
1640	/* This helper may be inlined by verifier. */
1641	return xchg(kptr, (unsigned long)ptr);
1642}
1643
1644/* Unlike other PTR_TO_BTF_ID helpers the btf_id in bpf_kptr_xchg()
1645 * helper is determined dynamically by the verifier. Use BPF_PTR_POISON to
1646 * denote type that verifier will determine.
1647 */
1648static const struct bpf_func_proto bpf_kptr_xchg_proto = {
1649	.func         = bpf_kptr_xchg,
1650	.gpl_only     = false,
1651	.ret_type     = RET_PTR_TO_BTF_ID_OR_NULL,
1652	.ret_btf_id   = BPF_PTR_POISON,
1653	.arg1_type    = ARG_KPTR_XCHG_DEST,
1654	.arg2_type    = ARG_PTR_TO_BTF_ID_OR_NULL | OBJ_RELEASE,
1655	.arg2_btf_id  = BPF_PTR_POISON,
1656};
1657
1658/* Since the upper 8 bits of dynptr->size is reserved, the
1659 * maximum supported size is 2^24 - 1.
1660 */
1661#define DYNPTR_MAX_SIZE	((1UL << 24) - 1)
1662#define DYNPTR_TYPE_SHIFT	28
1663#define DYNPTR_SIZE_MASK	0xFFFFFF
1664#define DYNPTR_RDONLY_BIT	BIT(31)
1665
1666bool __bpf_dynptr_is_rdonly(const struct bpf_dynptr_kern *ptr)
1667{
1668	return ptr->size & DYNPTR_RDONLY_BIT;
1669}
1670
1671void bpf_dynptr_set_rdonly(struct bpf_dynptr_kern *ptr)
1672{
1673	ptr->size |= DYNPTR_RDONLY_BIT;
1674}
1675
1676static void bpf_dynptr_set_type(struct bpf_dynptr_kern *ptr, enum bpf_dynptr_type type)
1677{
1678	ptr->size |= type << DYNPTR_TYPE_SHIFT;
1679}
1680
1681static enum bpf_dynptr_type bpf_dynptr_get_type(const struct bpf_dynptr_kern *ptr)
1682{
1683	return (ptr->size & ~(DYNPTR_RDONLY_BIT)) >> DYNPTR_TYPE_SHIFT;
1684}
1685
1686u32 __bpf_dynptr_size(const struct bpf_dynptr_kern *ptr)
1687{
1688	return ptr->size & DYNPTR_SIZE_MASK;
1689}
1690
1691static void bpf_dynptr_set_size(struct bpf_dynptr_kern *ptr, u32 new_size)
1692{
1693	u32 metadata = ptr->size & ~DYNPTR_SIZE_MASK;
1694
1695	ptr->size = new_size | metadata;
1696}
1697
1698int bpf_dynptr_check_size(u32 size)
1699{
1700	return size > DYNPTR_MAX_SIZE ? -E2BIG : 0;
1701}
1702
1703void bpf_dynptr_init(struct bpf_dynptr_kern *ptr, void *data,
1704		     enum bpf_dynptr_type type, u32 offset, u32 size)
1705{
1706	ptr->data = data;
1707	ptr->offset = offset;
1708	ptr->size = size;
1709	bpf_dynptr_set_type(ptr, type);
1710}
1711
1712void bpf_dynptr_set_null(struct bpf_dynptr_kern *ptr)
1713{
1714	memset(ptr, 0, sizeof(*ptr));
1715}
1716
1717static int bpf_dynptr_check_off_len(const struct bpf_dynptr_kern *ptr, u32 offset, u32 len)
1718{
1719	u32 size = __bpf_dynptr_size(ptr);
1720
1721	if (len > size || offset > size - len)
1722		return -E2BIG;
1723
1724	return 0;
1725}
1726
1727BPF_CALL_4(bpf_dynptr_from_mem, void *, data, u32, size, u64, flags, struct bpf_dynptr_kern *, ptr)
1728{
1729	int err;
1730
1731	BTF_TYPE_EMIT(struct bpf_dynptr);
1732
1733	err = bpf_dynptr_check_size(size);
1734	if (err)
1735		goto error;
1736
1737	/* flags is currently unsupported */
1738	if (flags) {
1739		err = -EINVAL;
1740		goto error;
1741	}
1742
1743	bpf_dynptr_init(ptr, data, BPF_DYNPTR_TYPE_LOCAL, 0, size);
1744
1745	return 0;
1746
1747error:
1748	bpf_dynptr_set_null(ptr);
1749	return err;
1750}
1751
1752static const struct bpf_func_proto bpf_dynptr_from_mem_proto = {
1753	.func		= bpf_dynptr_from_mem,
1754	.gpl_only	= false,
1755	.ret_type	= RET_INTEGER,
1756	.arg1_type	= ARG_PTR_TO_UNINIT_MEM,
1757	.arg2_type	= ARG_CONST_SIZE_OR_ZERO,
1758	.arg3_type	= ARG_ANYTHING,
1759	.arg4_type	= ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_LOCAL | MEM_UNINIT | MEM_WRITE,
1760};
1761
1762BPF_CALL_5(bpf_dynptr_read, void *, dst, u32, len, const struct bpf_dynptr_kern *, src,
1763	   u32, offset, u64, flags)
1764{
1765	enum bpf_dynptr_type type;
1766	int err;
1767
1768	if (!src->data || flags)
1769		return -EINVAL;
1770
1771	err = bpf_dynptr_check_off_len(src, offset, len);
1772	if (err)
1773		return err;
1774
1775	type = bpf_dynptr_get_type(src);
1776
1777	switch (type) {
1778	case BPF_DYNPTR_TYPE_LOCAL:
1779	case BPF_DYNPTR_TYPE_RINGBUF:
1780		/* Source and destination may possibly overlap, hence use memmove to
1781		 * copy the data. E.g. bpf_dynptr_from_mem may create two dynptr
1782		 * pointing to overlapping PTR_TO_MAP_VALUE regions.
1783		 */
1784		memmove(dst, src->data + src->offset + offset, len);
1785		return 0;
1786	case BPF_DYNPTR_TYPE_SKB:
1787		return __bpf_skb_load_bytes(src->data, src->offset + offset, dst, len);
1788	case BPF_DYNPTR_TYPE_XDP:
1789		return __bpf_xdp_load_bytes(src->data, src->offset + offset, dst, len);
1790	default:
1791		WARN_ONCE(true, "bpf_dynptr_read: unknown dynptr type %d\n", type);
1792		return -EFAULT;
1793	}
1794}
1795
1796static const struct bpf_func_proto bpf_dynptr_read_proto = {
1797	.func		= bpf_dynptr_read,
1798	.gpl_only	= false,
1799	.ret_type	= RET_INTEGER,
1800	.arg1_type	= ARG_PTR_TO_UNINIT_MEM,
1801	.arg2_type	= ARG_CONST_SIZE_OR_ZERO,
1802	.arg3_type	= ARG_PTR_TO_DYNPTR | MEM_RDONLY,
1803	.arg4_type	= ARG_ANYTHING,
1804	.arg5_type	= ARG_ANYTHING,
1805};
1806
1807BPF_CALL_5(bpf_dynptr_write, const struct bpf_dynptr_kern *, dst, u32, offset, void *, src,
1808	   u32, len, u64, flags)
1809{
1810	enum bpf_dynptr_type type;
1811	int err;
1812
1813	if (!dst->data || __bpf_dynptr_is_rdonly(dst))
1814		return -EINVAL;
1815
1816	err = bpf_dynptr_check_off_len(dst, offset, len);
1817	if (err)
1818		return err;
1819
1820	type = bpf_dynptr_get_type(dst);
1821
1822	switch (type) {
1823	case BPF_DYNPTR_TYPE_LOCAL:
1824	case BPF_DYNPTR_TYPE_RINGBUF:
1825		if (flags)
1826			return -EINVAL;
1827		/* Source and destination may possibly overlap, hence use memmove to
1828		 * copy the data. E.g. bpf_dynptr_from_mem may create two dynptr
1829		 * pointing to overlapping PTR_TO_MAP_VALUE regions.
1830		 */
1831		memmove(dst->data + dst->offset + offset, src, len);
1832		return 0;
1833	case BPF_DYNPTR_TYPE_SKB:
1834		return __bpf_skb_store_bytes(dst->data, dst->offset + offset, src, len,
1835					     flags);
1836	case BPF_DYNPTR_TYPE_XDP:
1837		if (flags)
1838			return -EINVAL;
1839		return __bpf_xdp_store_bytes(dst->data, dst->offset + offset, src, len);
1840	default:
1841		WARN_ONCE(true, "bpf_dynptr_write: unknown dynptr type %d\n", type);
1842		return -EFAULT;
1843	}
1844}
1845
1846static const struct bpf_func_proto bpf_dynptr_write_proto = {
1847	.func		= bpf_dynptr_write,
1848	.gpl_only	= false,
1849	.ret_type	= RET_INTEGER,
1850	.arg1_type	= ARG_PTR_TO_DYNPTR | MEM_RDONLY,
1851	.arg2_type	= ARG_ANYTHING,
1852	.arg3_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
1853	.arg4_type	= ARG_CONST_SIZE_OR_ZERO,
1854	.arg5_type	= ARG_ANYTHING,
1855};
1856
1857BPF_CALL_3(bpf_dynptr_data, const struct bpf_dynptr_kern *, ptr, u32, offset, u32, len)
1858{
1859	enum bpf_dynptr_type type;
1860	int err;
1861
1862	if (!ptr->data)
1863		return 0;
1864
1865	err = bpf_dynptr_check_off_len(ptr, offset, len);
1866	if (err)
1867		return 0;
1868
1869	if (__bpf_dynptr_is_rdonly(ptr))
1870		return 0;
1871
1872	type = bpf_dynptr_get_type(ptr);
1873
1874	switch (type) {
1875	case BPF_DYNPTR_TYPE_LOCAL:
1876	case BPF_DYNPTR_TYPE_RINGBUF:
1877		return (unsigned long)(ptr->data + ptr->offset + offset);
1878	case BPF_DYNPTR_TYPE_SKB:
1879	case BPF_DYNPTR_TYPE_XDP:
1880		/* skb and xdp dynptrs should use bpf_dynptr_slice / bpf_dynptr_slice_rdwr */
1881		return 0;
1882	default:
1883		WARN_ONCE(true, "bpf_dynptr_data: unknown dynptr type %d\n", type);
1884		return 0;
1885	}
1886}
1887
1888static const struct bpf_func_proto bpf_dynptr_data_proto = {
1889	.func		= bpf_dynptr_data,
1890	.gpl_only	= false,
1891	.ret_type	= RET_PTR_TO_DYNPTR_MEM_OR_NULL,
1892	.arg1_type	= ARG_PTR_TO_DYNPTR | MEM_RDONLY,
1893	.arg2_type	= ARG_ANYTHING,
1894	.arg3_type	= ARG_CONST_ALLOC_SIZE_OR_ZERO,
1895};
1896
1897const struct bpf_func_proto bpf_get_current_task_proto __weak;
1898const struct bpf_func_proto bpf_get_current_task_btf_proto __weak;
1899const struct bpf_func_proto bpf_probe_read_user_proto __weak;
1900const struct bpf_func_proto bpf_probe_read_user_str_proto __weak;
1901const struct bpf_func_proto bpf_probe_read_kernel_proto __weak;
1902const struct bpf_func_proto bpf_probe_read_kernel_str_proto __weak;
1903const struct bpf_func_proto bpf_task_pt_regs_proto __weak;
1904
1905const struct bpf_func_proto *
1906bpf_base_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
1907{
1908	switch (func_id) {
1909	case BPF_FUNC_map_lookup_elem:
1910		return &bpf_map_lookup_elem_proto;
1911	case BPF_FUNC_map_update_elem:
1912		return &bpf_map_update_elem_proto;
1913	case BPF_FUNC_map_delete_elem:
1914		return &bpf_map_delete_elem_proto;
1915	case BPF_FUNC_map_push_elem:
1916		return &bpf_map_push_elem_proto;
1917	case BPF_FUNC_map_pop_elem:
1918		return &bpf_map_pop_elem_proto;
1919	case BPF_FUNC_map_peek_elem:
1920		return &bpf_map_peek_elem_proto;
1921	case BPF_FUNC_map_lookup_percpu_elem:
1922		return &bpf_map_lookup_percpu_elem_proto;
1923	case BPF_FUNC_get_prandom_u32:
1924		return &bpf_get_prandom_u32_proto;
1925	case BPF_FUNC_get_smp_processor_id:
1926		return &bpf_get_raw_smp_processor_id_proto;
1927	case BPF_FUNC_get_numa_node_id:
1928		return &bpf_get_numa_node_id_proto;
1929	case BPF_FUNC_tail_call:
1930		return &bpf_tail_call_proto;
1931	case BPF_FUNC_ktime_get_ns:
1932		return &bpf_ktime_get_ns_proto;
1933	case BPF_FUNC_ktime_get_boot_ns:
1934		return &bpf_ktime_get_boot_ns_proto;
1935	case BPF_FUNC_ktime_get_tai_ns:
1936		return &bpf_ktime_get_tai_ns_proto;
1937	case BPF_FUNC_ringbuf_output:
1938		return &bpf_ringbuf_output_proto;
1939	case BPF_FUNC_ringbuf_reserve:
1940		return &bpf_ringbuf_reserve_proto;
1941	case BPF_FUNC_ringbuf_submit:
1942		return &bpf_ringbuf_submit_proto;
1943	case BPF_FUNC_ringbuf_discard:
1944		return &bpf_ringbuf_discard_proto;
1945	case BPF_FUNC_ringbuf_query:
1946		return &bpf_ringbuf_query_proto;
1947	case BPF_FUNC_strncmp:
1948		return &bpf_strncmp_proto;
1949	case BPF_FUNC_strtol:
1950		return &bpf_strtol_proto;
1951	case BPF_FUNC_strtoul:
1952		return &bpf_strtoul_proto;
1953	case BPF_FUNC_get_current_pid_tgid:
1954		return &bpf_get_current_pid_tgid_proto;
1955	case BPF_FUNC_get_ns_current_pid_tgid:
1956		return &bpf_get_ns_current_pid_tgid_proto;
1957	default:
1958		break;
1959	}
1960
1961	if (!bpf_token_capable(prog->aux->token, CAP_BPF))
1962		return NULL;
1963
1964	switch (func_id) {
1965	case BPF_FUNC_spin_lock:
1966		return &bpf_spin_lock_proto;
1967	case BPF_FUNC_spin_unlock:
1968		return &bpf_spin_unlock_proto;
1969	case BPF_FUNC_jiffies64:
1970		return &bpf_jiffies64_proto;
1971	case BPF_FUNC_per_cpu_ptr:
1972		return &bpf_per_cpu_ptr_proto;
1973	case BPF_FUNC_this_cpu_ptr:
1974		return &bpf_this_cpu_ptr_proto;
1975	case BPF_FUNC_timer_init:
1976		return &bpf_timer_init_proto;
1977	case BPF_FUNC_timer_set_callback:
1978		return &bpf_timer_set_callback_proto;
1979	case BPF_FUNC_timer_start:
1980		return &bpf_timer_start_proto;
1981	case BPF_FUNC_timer_cancel:
1982		return &bpf_timer_cancel_proto;
1983	case BPF_FUNC_kptr_xchg:
1984		return &bpf_kptr_xchg_proto;
1985	case BPF_FUNC_for_each_map_elem:
1986		return &bpf_for_each_map_elem_proto;
1987	case BPF_FUNC_loop:
1988		return &bpf_loop_proto;
1989	case BPF_FUNC_user_ringbuf_drain:
1990		return &bpf_user_ringbuf_drain_proto;
1991	case BPF_FUNC_ringbuf_reserve_dynptr:
1992		return &bpf_ringbuf_reserve_dynptr_proto;
1993	case BPF_FUNC_ringbuf_submit_dynptr:
1994		return &bpf_ringbuf_submit_dynptr_proto;
1995	case BPF_FUNC_ringbuf_discard_dynptr:
1996		return &bpf_ringbuf_discard_dynptr_proto;
1997	case BPF_FUNC_dynptr_from_mem:
1998		return &bpf_dynptr_from_mem_proto;
1999	case BPF_FUNC_dynptr_read:
2000		return &bpf_dynptr_read_proto;
2001	case BPF_FUNC_dynptr_write:
2002		return &bpf_dynptr_write_proto;
2003	case BPF_FUNC_dynptr_data:
2004		return &bpf_dynptr_data_proto;
2005#ifdef CONFIG_CGROUPS
2006	case BPF_FUNC_cgrp_storage_get:
2007		return &bpf_cgrp_storage_get_proto;
2008	case BPF_FUNC_cgrp_storage_delete:
2009		return &bpf_cgrp_storage_delete_proto;
2010	case BPF_FUNC_get_current_cgroup_id:
2011		return &bpf_get_current_cgroup_id_proto;
2012	case BPF_FUNC_get_current_ancestor_cgroup_id:
2013		return &bpf_get_current_ancestor_cgroup_id_proto;
2014#endif
2015	default:
2016		break;
2017	}
2018
2019	if (!bpf_token_capable(prog->aux->token, CAP_PERFMON))
2020		return NULL;
2021
2022	switch (func_id) {
2023	case BPF_FUNC_trace_printk:
2024		return bpf_get_trace_printk_proto();
2025	case BPF_FUNC_get_current_task:
2026		return &bpf_get_current_task_proto;
2027	case BPF_FUNC_get_current_task_btf:
2028		return &bpf_get_current_task_btf_proto;
2029	case BPF_FUNC_probe_read_user:
2030		return &bpf_probe_read_user_proto;
2031	case BPF_FUNC_probe_read_kernel:
2032		return security_locked_down(LOCKDOWN_BPF_READ_KERNEL) < 0 ?
2033		       NULL : &bpf_probe_read_kernel_proto;
2034	case BPF_FUNC_probe_read_user_str:
2035		return &bpf_probe_read_user_str_proto;
2036	case BPF_FUNC_probe_read_kernel_str:
2037		return security_locked_down(LOCKDOWN_BPF_READ_KERNEL) < 0 ?
2038		       NULL : &bpf_probe_read_kernel_str_proto;
2039	case BPF_FUNC_snprintf_btf:
2040		return &bpf_snprintf_btf_proto;
2041	case BPF_FUNC_snprintf:
2042		return &bpf_snprintf_proto;
2043	case BPF_FUNC_task_pt_regs:
2044		return &bpf_task_pt_regs_proto;
2045	case BPF_FUNC_trace_vprintk:
2046		return bpf_get_trace_vprintk_proto();
2047	default:
2048		return NULL;
2049	}
2050}
2051EXPORT_SYMBOL_GPL(bpf_base_func_proto);
2052
2053void bpf_list_head_free(const struct btf_field *field, void *list_head,
2054			struct bpf_spin_lock *spin_lock)
2055{
2056	struct list_head *head = list_head, *orig_head = list_head;
2057
2058	BUILD_BUG_ON(sizeof(struct list_head) > sizeof(struct bpf_list_head));
2059	BUILD_BUG_ON(__alignof__(struct list_head) > __alignof__(struct bpf_list_head));
2060
2061	/* Do the actual list draining outside the lock to not hold the lock for
2062	 * too long, and also prevent deadlocks if tracing programs end up
2063	 * executing on entry/exit of functions called inside the critical
2064	 * section, and end up doing map ops that call bpf_list_head_free for
2065	 * the same map value again.
2066	 */
2067	__bpf_spin_lock_irqsave(spin_lock);
2068	if (!head->next || list_empty(head))
2069		goto unlock;
2070	head = head->next;
2071unlock:
2072	INIT_LIST_HEAD(orig_head);
2073	__bpf_spin_unlock_irqrestore(spin_lock);
2074
2075	while (head != orig_head) {
2076		void *obj = head;
2077
2078		obj -= field->graph_root.node_offset;
2079		head = head->next;
2080		/* The contained type can also have resources, including a
2081		 * bpf_list_head which needs to be freed.
2082		 */
2083		migrate_disable();
2084		__bpf_obj_drop_impl(obj, field->graph_root.value_rec, false);
2085		migrate_enable();
2086	}
2087}
2088
2089/* Like rbtree_postorder_for_each_entry_safe, but 'pos' and 'n' are
2090 * 'rb_node *', so field name of rb_node within containing struct is not
2091 * needed.
2092 *
2093 * Since bpf_rb_tree's node type has a corresponding struct btf_field with
2094 * graph_root.node_offset, it's not necessary to know field name
2095 * or type of node struct
2096 */
2097#define bpf_rbtree_postorder_for_each_entry_safe(pos, n, root) \
2098	for (pos = rb_first_postorder(root); \
2099	    pos && ({ n = rb_next_postorder(pos); 1; }); \
2100	    pos = n)
2101
2102void bpf_rb_root_free(const struct btf_field *field, void *rb_root,
2103		      struct bpf_spin_lock *spin_lock)
2104{
2105	struct rb_root_cached orig_root, *root = rb_root;
2106	struct rb_node *pos, *n;
2107	void *obj;
2108
2109	BUILD_BUG_ON(sizeof(struct rb_root_cached) > sizeof(struct bpf_rb_root));
2110	BUILD_BUG_ON(__alignof__(struct rb_root_cached) > __alignof__(struct bpf_rb_root));
2111
2112	__bpf_spin_lock_irqsave(spin_lock);
2113	orig_root = *root;
2114	*root = RB_ROOT_CACHED;
2115	__bpf_spin_unlock_irqrestore(spin_lock);
2116
2117	bpf_rbtree_postorder_for_each_entry_safe(pos, n, &orig_root.rb_root) {
2118		obj = pos;
2119		obj -= field->graph_root.node_offset;
2120
2121
2122		migrate_disable();
2123		__bpf_obj_drop_impl(obj, field->graph_root.value_rec, false);
2124		migrate_enable();
2125	}
2126}
2127
2128__bpf_kfunc_start_defs();
2129
2130__bpf_kfunc void *bpf_obj_new_impl(u64 local_type_id__k, void *meta__ign)
2131{
2132	struct btf_struct_meta *meta = meta__ign;
2133	u64 size = local_type_id__k;
2134	void *p;
2135
2136	p = bpf_mem_alloc(&bpf_global_ma, size);
2137	if (!p)
2138		return NULL;
2139	if (meta)
2140		bpf_obj_init(meta->record, p);
2141	return p;
2142}
2143
2144__bpf_kfunc void *bpf_percpu_obj_new_impl(u64 local_type_id__k, void *meta__ign)
2145{
2146	u64 size = local_type_id__k;
2147
2148	/* The verifier has ensured that meta__ign must be NULL */
2149	return bpf_mem_alloc(&bpf_global_percpu_ma, size);
2150}
2151
2152/* Must be called under migrate_disable(), as required by bpf_mem_free */
2153void __bpf_obj_drop_impl(void *p, const struct btf_record *rec, bool percpu)
2154{
2155	struct bpf_mem_alloc *ma;
2156
2157	if (rec && rec->refcount_off >= 0 &&
2158	    !refcount_dec_and_test((refcount_t *)(p + rec->refcount_off))) {
2159		/* Object is refcounted and refcount_dec didn't result in 0
2160		 * refcount. Return without freeing the object
2161		 */
2162		return;
2163	}
2164
2165	if (rec)
2166		bpf_obj_free_fields(rec, p);
2167
2168	if (percpu)
2169		ma = &bpf_global_percpu_ma;
2170	else
2171		ma = &bpf_global_ma;
2172	bpf_mem_free_rcu(ma, p);
2173}
2174
2175__bpf_kfunc void bpf_obj_drop_impl(void *p__alloc, void *meta__ign)
2176{
2177	struct btf_struct_meta *meta = meta__ign;
2178	void *p = p__alloc;
2179
2180	__bpf_obj_drop_impl(p, meta ? meta->record : NULL, false);
2181}
2182
2183__bpf_kfunc void bpf_percpu_obj_drop_impl(void *p__alloc, void *meta__ign)
2184{
2185	/* The verifier has ensured that meta__ign must be NULL */
2186	bpf_mem_free_rcu(&bpf_global_percpu_ma, p__alloc);
2187}
2188
2189__bpf_kfunc void *bpf_refcount_acquire_impl(void *p__refcounted_kptr, void *meta__ign)
2190{
2191	struct btf_struct_meta *meta = meta__ign;
2192	struct bpf_refcount *ref;
2193
2194	/* Could just cast directly to refcount_t *, but need some code using
2195	 * bpf_refcount type so that it is emitted in vmlinux BTF
2196	 */
2197	ref = (struct bpf_refcount *)(p__refcounted_kptr + meta->record->refcount_off);
2198	if (!refcount_inc_not_zero((refcount_t *)ref))
2199		return NULL;
2200
2201	/* Verifier strips KF_RET_NULL if input is owned ref, see is_kfunc_ret_null
2202	 * in verifier.c
2203	 */
2204	return (void *)p__refcounted_kptr;
2205}
2206
2207static int __bpf_list_add(struct bpf_list_node_kern *node,
2208			  struct bpf_list_head *head,
2209			  bool tail, struct btf_record *rec, u64 off)
2210{
2211	struct list_head *n = &node->list_head, *h = (void *)head;
2212
2213	/* If list_head was 0-initialized by map, bpf_obj_init_field wasn't
2214	 * called on its fields, so init here
2215	 */
2216	if (unlikely(!h->next))
2217		INIT_LIST_HEAD(h);
2218
2219	/* node->owner != NULL implies !list_empty(n), no need to separately
2220	 * check the latter
2221	 */
2222	if (cmpxchg(&node->owner, NULL, BPF_PTR_POISON)) {
2223		/* Only called from BPF prog, no need to migrate_disable */
2224		__bpf_obj_drop_impl((void *)n - off, rec, false);
2225		return -EINVAL;
2226	}
2227
2228	tail ? list_add_tail(n, h) : list_add(n, h);
2229	WRITE_ONCE(node->owner, head);
2230
2231	return 0;
2232}
2233
2234__bpf_kfunc int bpf_list_push_front_impl(struct bpf_list_head *head,
2235					 struct bpf_list_node *node,
2236					 void *meta__ign, u64 off)
2237{
2238	struct bpf_list_node_kern *n = (void *)node;
2239	struct btf_struct_meta *meta = meta__ign;
2240
2241	return __bpf_list_add(n, head, false, meta ? meta->record : NULL, off);
2242}
2243
2244__bpf_kfunc int bpf_list_push_back_impl(struct bpf_list_head *head,
2245					struct bpf_list_node *node,
2246					void *meta__ign, u64 off)
2247{
2248	struct bpf_list_node_kern *n = (void *)node;
2249	struct btf_struct_meta *meta = meta__ign;
2250
2251	return __bpf_list_add(n, head, true, meta ? meta->record : NULL, off);
2252}
2253
2254static struct bpf_list_node *__bpf_list_del(struct bpf_list_head *head, bool tail)
2255{
2256	struct list_head *n, *h = (void *)head;
2257	struct bpf_list_node_kern *node;
2258
2259	/* If list_head was 0-initialized by map, bpf_obj_init_field wasn't
2260	 * called on its fields, so init here
2261	 */
2262	if (unlikely(!h->next))
2263		INIT_LIST_HEAD(h);
2264	if (list_empty(h))
2265		return NULL;
2266
2267	n = tail ? h->prev : h->next;
2268	node = container_of(n, struct bpf_list_node_kern, list_head);
2269	if (WARN_ON_ONCE(READ_ONCE(node->owner) != head))
2270		return NULL;
2271
2272	list_del_init(n);
2273	WRITE_ONCE(node->owner, NULL);
2274	return (struct bpf_list_node *)n;
2275}
2276
2277__bpf_kfunc struct bpf_list_node *bpf_list_pop_front(struct bpf_list_head *head)
2278{
2279	return __bpf_list_del(head, false);
2280}
2281
2282__bpf_kfunc struct bpf_list_node *bpf_list_pop_back(struct bpf_list_head *head)
2283{
2284	return __bpf_list_del(head, true);
2285}
2286
2287__bpf_kfunc struct bpf_rb_node *bpf_rbtree_remove(struct bpf_rb_root *root,
2288						  struct bpf_rb_node *node)
2289{
2290	struct bpf_rb_node_kern *node_internal = (struct bpf_rb_node_kern *)node;
2291	struct rb_root_cached *r = (struct rb_root_cached *)root;
2292	struct rb_node *n = &node_internal->rb_node;
2293
2294	/* node_internal->owner != root implies either RB_EMPTY_NODE(n) or
2295	 * n is owned by some other tree. No need to check RB_EMPTY_NODE(n)
2296	 */
2297	if (READ_ONCE(node_internal->owner) != root)
2298		return NULL;
2299
2300	rb_erase_cached(n, r);
2301	RB_CLEAR_NODE(n);
2302	WRITE_ONCE(node_internal->owner, NULL);
2303	return (struct bpf_rb_node *)n;
2304}
2305
2306/* Need to copy rbtree_add_cached's logic here because our 'less' is a BPF
2307 * program
2308 */
2309static int __bpf_rbtree_add(struct bpf_rb_root *root,
2310			    struct bpf_rb_node_kern *node,
2311			    void *less, struct btf_record *rec, u64 off)
2312{
2313	struct rb_node **link = &((struct rb_root_cached *)root)->rb_root.rb_node;
2314	struct rb_node *parent = NULL, *n = &node->rb_node;
2315	bpf_callback_t cb = (bpf_callback_t)less;
2316	bool leftmost = true;
2317
2318	/* node->owner != NULL implies !RB_EMPTY_NODE(n), no need to separately
2319	 * check the latter
2320	 */
2321	if (cmpxchg(&node->owner, NULL, BPF_PTR_POISON)) {
2322		/* Only called from BPF prog, no need to migrate_disable */
2323		__bpf_obj_drop_impl((void *)n - off, rec, false);
2324		return -EINVAL;
2325	}
2326
2327	while (*link) {
2328		parent = *link;
2329		if (cb((uintptr_t)node, (uintptr_t)parent, 0, 0, 0)) {
2330			link = &parent->rb_left;
2331		} else {
2332			link = &parent->rb_right;
2333			leftmost = false;
2334		}
2335	}
2336
2337	rb_link_node(n, parent, link);
2338	rb_insert_color_cached(n, (struct rb_root_cached *)root, leftmost);
2339	WRITE_ONCE(node->owner, root);
2340	return 0;
2341}
2342
2343__bpf_kfunc int bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node,
2344				    bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b),
2345				    void *meta__ign, u64 off)
2346{
2347	struct btf_struct_meta *meta = meta__ign;
2348	struct bpf_rb_node_kern *n = (void *)node;
2349
2350	return __bpf_rbtree_add(root, n, (void *)less, meta ? meta->record : NULL, off);
2351}
2352
2353__bpf_kfunc struct bpf_rb_node *bpf_rbtree_first(struct bpf_rb_root *root)
2354{
2355	struct rb_root_cached *r = (struct rb_root_cached *)root;
2356
2357	return (struct bpf_rb_node *)rb_first_cached(r);
2358}
2359
2360/**
2361 * bpf_task_acquire - Acquire a reference to a task. A task acquired by this
2362 * kfunc which is not stored in a map as a kptr, must be released by calling
2363 * bpf_task_release().
2364 * @p: The task on which a reference is being acquired.
2365 */
2366__bpf_kfunc struct task_struct *bpf_task_acquire(struct task_struct *p)
2367{
2368	if (refcount_inc_not_zero(&p->rcu_users))
2369		return p;
2370	return NULL;
2371}
2372
2373/**
2374 * bpf_task_release - Release the reference acquired on a task.
2375 * @p: The task on which a reference is being released.
2376 */
2377__bpf_kfunc void bpf_task_release(struct task_struct *p)
2378{
2379	put_task_struct_rcu_user(p);
2380}
2381
2382__bpf_kfunc void bpf_task_release_dtor(void *p)
2383{
2384	put_task_struct_rcu_user(p);
2385}
2386CFI_NOSEAL(bpf_task_release_dtor);
2387
2388#ifdef CONFIG_CGROUPS
2389/**
2390 * bpf_cgroup_acquire - Acquire a reference to a cgroup. A cgroup acquired by
2391 * this kfunc which is not stored in a map as a kptr, must be released by
2392 * calling bpf_cgroup_release().
2393 * @cgrp: The cgroup on which a reference is being acquired.
2394 */
2395__bpf_kfunc struct cgroup *bpf_cgroup_acquire(struct cgroup *cgrp)
2396{
2397	return cgroup_tryget(cgrp) ? cgrp : NULL;
2398}
2399
2400/**
2401 * bpf_cgroup_release - Release the reference acquired on a cgroup.
2402 * If this kfunc is invoked in an RCU read region, the cgroup is guaranteed to
2403 * not be freed until the current grace period has ended, even if its refcount
2404 * drops to 0.
2405 * @cgrp: The cgroup on which a reference is being released.
2406 */
2407__bpf_kfunc void bpf_cgroup_release(struct cgroup *cgrp)
2408{
2409	cgroup_put(cgrp);
2410}
2411
2412__bpf_kfunc void bpf_cgroup_release_dtor(void *cgrp)
2413{
2414	cgroup_put(cgrp);
2415}
2416CFI_NOSEAL(bpf_cgroup_release_dtor);
2417
2418/**
2419 * bpf_cgroup_ancestor - Perform a lookup on an entry in a cgroup's ancestor
2420 * array. A cgroup returned by this kfunc which is not subsequently stored in a
2421 * map, must be released by calling bpf_cgroup_release().
2422 * @cgrp: The cgroup for which we're performing a lookup.
2423 * @level: The level of ancestor to look up.
2424 */
2425__bpf_kfunc struct cgroup *bpf_cgroup_ancestor(struct cgroup *cgrp, int level)
2426{
2427	struct cgroup *ancestor;
2428
2429	if (level > cgrp->level || level < 0)
2430		return NULL;
2431
2432	/* cgrp's refcnt could be 0 here, but ancestors can still be accessed */
2433	ancestor = cgrp->ancestors[level];
2434	if (!cgroup_tryget(ancestor))
2435		return NULL;
2436	return ancestor;
2437}
2438
2439/**
2440 * bpf_cgroup_from_id - Find a cgroup from its ID. A cgroup returned by this
2441 * kfunc which is not subsequently stored in a map, must be released by calling
2442 * bpf_cgroup_release().
2443 * @cgid: cgroup id.
2444 */
2445__bpf_kfunc struct cgroup *bpf_cgroup_from_id(u64 cgid)
2446{
2447	struct cgroup *cgrp;
2448
2449	cgrp = cgroup_get_from_id(cgid);
2450	if (IS_ERR(cgrp))
2451		return NULL;
2452	return cgrp;
2453}
2454
2455/**
2456 * bpf_task_under_cgroup - wrap task_under_cgroup_hierarchy() as a kfunc, test
2457 * task's membership of cgroup ancestry.
2458 * @task: the task to be tested
2459 * @ancestor: possible ancestor of @task's cgroup
2460 *
2461 * Tests whether @task's default cgroup hierarchy is a descendant of @ancestor.
2462 * It follows all the same rules as cgroup_is_descendant, and only applies
2463 * to the default hierarchy.
2464 */
2465__bpf_kfunc long bpf_task_under_cgroup(struct task_struct *task,
2466				       struct cgroup *ancestor)
2467{
2468	long ret;
2469
2470	rcu_read_lock();
2471	ret = task_under_cgroup_hierarchy(task, ancestor);
2472	rcu_read_unlock();
2473	return ret;
2474}
2475
2476BPF_CALL_2(bpf_current_task_under_cgroup, struct bpf_map *, map, u32, idx)
2477{
2478	struct bpf_array *array = container_of(map, struct bpf_array, map);
2479	struct cgroup *cgrp;
2480
2481	if (unlikely(idx >= array->map.max_entries))
2482		return -E2BIG;
2483
2484	cgrp = READ_ONCE(array->ptrs[idx]);
2485	if (unlikely(!cgrp))
2486		return -EAGAIN;
2487
2488	return task_under_cgroup_hierarchy(current, cgrp);
2489}
2490
2491const struct bpf_func_proto bpf_current_task_under_cgroup_proto = {
2492	.func           = bpf_current_task_under_cgroup,
2493	.gpl_only       = false,
2494	.ret_type       = RET_INTEGER,
2495	.arg1_type      = ARG_CONST_MAP_PTR,
2496	.arg2_type      = ARG_ANYTHING,
2497};
2498
2499/**
2500 * bpf_task_get_cgroup1 - Acquires the associated cgroup of a task within a
2501 * specific cgroup1 hierarchy. The cgroup1 hierarchy is identified by its
2502 * hierarchy ID.
2503 * @task: The target task
2504 * @hierarchy_id: The ID of a cgroup1 hierarchy
2505 *
2506 * On success, the cgroup is returen. On failure, NULL is returned.
2507 */
2508__bpf_kfunc struct cgroup *
2509bpf_task_get_cgroup1(struct task_struct *task, int hierarchy_id)
2510{
2511	struct cgroup *cgrp = task_get_cgroup1(task, hierarchy_id);
2512
2513	if (IS_ERR(cgrp))
2514		return NULL;
2515	return cgrp;
2516}
2517#endif /* CONFIG_CGROUPS */
2518
2519/**
2520 * bpf_task_from_pid - Find a struct task_struct from its pid by looking it up
2521 * in the root pid namespace idr. If a task is returned, it must either be
2522 * stored in a map, or released with bpf_task_release().
2523 * @pid: The pid of the task being looked up.
2524 */
2525__bpf_kfunc struct task_struct *bpf_task_from_pid(s32 pid)
2526{
2527	struct task_struct *p;
2528
2529	rcu_read_lock();
2530	p = find_task_by_pid_ns(pid, &init_pid_ns);
2531	if (p)
2532		p = bpf_task_acquire(p);
2533	rcu_read_unlock();
2534
2535	return p;
2536}
2537
2538/**
2539 * bpf_task_from_vpid - Find a struct task_struct from its vpid by looking it up
2540 * in the pid namespace of the current task. If a task is returned, it must
2541 * either be stored in a map, or released with bpf_task_release().
2542 * @vpid: The vpid of the task being looked up.
2543 */
2544__bpf_kfunc struct task_struct *bpf_task_from_vpid(s32 vpid)
2545{
2546	struct task_struct *p;
2547
2548	rcu_read_lock();
2549	p = find_task_by_vpid(vpid);
2550	if (p)
2551		p = bpf_task_acquire(p);
2552	rcu_read_unlock();
2553
2554	return p;
2555}
2556
2557/**
2558 * bpf_dynptr_slice() - Obtain a read-only pointer to the dynptr data.
2559 * @p: The dynptr whose data slice to retrieve
2560 * @offset: Offset into the dynptr
2561 * @buffer__opt: User-provided buffer to copy contents into.  May be NULL
2562 * @buffer__szk: Size (in bytes) of the buffer if present. This is the
2563 *               length of the requested slice. This must be a constant.
2564 *
2565 * For non-skb and non-xdp type dynptrs, there is no difference between
2566 * bpf_dynptr_slice and bpf_dynptr_data.
2567 *
2568 *  If buffer__opt is NULL, the call will fail if buffer_opt was needed.
2569 *
2570 * If the intention is to write to the data slice, please use
2571 * bpf_dynptr_slice_rdwr.
2572 *
2573 * The user must check that the returned pointer is not null before using it.
2574 *
2575 * Please note that in the case of skb and xdp dynptrs, bpf_dynptr_slice
2576 * does not change the underlying packet data pointers, so a call to
2577 * bpf_dynptr_slice will not invalidate any ctx->data/data_end pointers in
2578 * the bpf program.
2579 *
2580 * Return: NULL if the call failed (eg invalid dynptr), pointer to a read-only
2581 * data slice (can be either direct pointer to the data or a pointer to the user
2582 * provided buffer, with its contents containing the data, if unable to obtain
2583 * direct pointer)
2584 */
2585__bpf_kfunc void *bpf_dynptr_slice(const struct bpf_dynptr *p, u32 offset,
2586				   void *buffer__opt, u32 buffer__szk)
2587{
2588	const struct bpf_dynptr_kern *ptr = (struct bpf_dynptr_kern *)p;
2589	enum bpf_dynptr_type type;
2590	u32 len = buffer__szk;
2591	int err;
2592
2593	if (!ptr->data)
2594		return NULL;
2595
2596	err = bpf_dynptr_check_off_len(ptr, offset, len);
2597	if (err)
2598		return NULL;
2599
2600	type = bpf_dynptr_get_type(ptr);
2601
2602	switch (type) {
2603	case BPF_DYNPTR_TYPE_LOCAL:
2604	case BPF_DYNPTR_TYPE_RINGBUF:
2605		return ptr->data + ptr->offset + offset;
2606	case BPF_DYNPTR_TYPE_SKB:
2607		if (buffer__opt)
2608			return skb_header_pointer(ptr->data, ptr->offset + offset, len, buffer__opt);
2609		else
2610			return skb_pointer_if_linear(ptr->data, ptr->offset + offset, len);
2611	case BPF_DYNPTR_TYPE_XDP:
2612	{
2613		void *xdp_ptr = bpf_xdp_pointer(ptr->data, ptr->offset + offset, len);
2614		if (!IS_ERR_OR_NULL(xdp_ptr))
2615			return xdp_ptr;
2616
2617		if (!buffer__opt)
2618			return NULL;
2619		bpf_xdp_copy_buf(ptr->data, ptr->offset + offset, buffer__opt, len, false);
2620		return buffer__opt;
2621	}
2622	default:
2623		WARN_ONCE(true, "unknown dynptr type %d\n", type);
2624		return NULL;
2625	}
2626}
2627
2628/**
2629 * bpf_dynptr_slice_rdwr() - Obtain a writable pointer to the dynptr data.
2630 * @p: The dynptr whose data slice to retrieve
2631 * @offset: Offset into the dynptr
2632 * @buffer__opt: User-provided buffer to copy contents into. May be NULL
2633 * @buffer__szk: Size (in bytes) of the buffer if present. This is the
2634 *               length of the requested slice. This must be a constant.
2635 *
2636 * For non-skb and non-xdp type dynptrs, there is no difference between
2637 * bpf_dynptr_slice and bpf_dynptr_data.
2638 *
2639 * If buffer__opt is NULL, the call will fail if buffer_opt was needed.
2640 *
2641 * The returned pointer is writable and may point to either directly the dynptr
2642 * data at the requested offset or to the buffer if unable to obtain a direct
2643 * data pointer to (example: the requested slice is to the paged area of an skb
2644 * packet). In the case where the returned pointer is to the buffer, the user
2645 * is responsible for persisting writes through calling bpf_dynptr_write(). This
2646 * usually looks something like this pattern:
2647 *
2648 * struct eth_hdr *eth = bpf_dynptr_slice_rdwr(&dynptr, 0, buffer, sizeof(buffer));
2649 * if (!eth)
2650 *	return TC_ACT_SHOT;
2651 *
2652 * // mutate eth header //
2653 *
2654 * if (eth == buffer)
2655 *	bpf_dynptr_write(&ptr, 0, buffer, sizeof(buffer), 0);
2656 *
2657 * Please note that, as in the example above, the user must check that the
2658 * returned pointer is not null before using it.
2659 *
2660 * Please also note that in the case of skb and xdp dynptrs, bpf_dynptr_slice_rdwr
2661 * does not change the underlying packet data pointers, so a call to
2662 * bpf_dynptr_slice_rdwr will not invalidate any ctx->data/data_end pointers in
2663 * the bpf program.
2664 *
2665 * Return: NULL if the call failed (eg invalid dynptr), pointer to a
2666 * data slice (can be either direct pointer to the data or a pointer to the user
2667 * provided buffer, with its contents containing the data, if unable to obtain
2668 * direct pointer)
2669 */
2670__bpf_kfunc void *bpf_dynptr_slice_rdwr(const struct bpf_dynptr *p, u32 offset,
2671					void *buffer__opt, u32 buffer__szk)
2672{
2673	const struct bpf_dynptr_kern *ptr = (struct bpf_dynptr_kern *)p;
2674
2675	if (!ptr->data || __bpf_dynptr_is_rdonly(ptr))
2676		return NULL;
2677
2678	/* bpf_dynptr_slice_rdwr is the same logic as bpf_dynptr_slice.
2679	 *
2680	 * For skb-type dynptrs, it is safe to write into the returned pointer
2681	 * if the bpf program allows skb data writes. There are two possibilities
2682	 * that may occur when calling bpf_dynptr_slice_rdwr:
2683	 *
2684	 * 1) The requested slice is in the head of the skb. In this case, the
2685	 * returned pointer is directly to skb data, and if the skb is cloned, the
2686	 * verifier will have uncloned it (see bpf_unclone_prologue()) already.
2687	 * The pointer can be directly written into.
2688	 *
2689	 * 2) Some portion of the requested slice is in the paged buffer area.
2690	 * In this case, the requested data will be copied out into the buffer
2691	 * and the returned pointer will be a pointer to the buffer. The skb
2692	 * will not be pulled. To persist the write, the user will need to call
2693	 * bpf_dynptr_write(), which will pull the skb and commit the write.
2694	 *
2695	 * Similarly for xdp programs, if the requested slice is not across xdp
2696	 * fragments, then a direct pointer will be returned, otherwise the data
2697	 * will be copied out into the buffer and the user will need to call
2698	 * bpf_dynptr_write() to commit changes.
2699	 */
2700	return bpf_dynptr_slice(p, offset, buffer__opt, buffer__szk);
2701}
2702
2703__bpf_kfunc int bpf_dynptr_adjust(const struct bpf_dynptr *p, u32 start, u32 end)
2704{
2705	struct bpf_dynptr_kern *ptr = (struct bpf_dynptr_kern *)p;
2706	u32 size;
2707
2708	if (!ptr->data || start > end)
2709		return -EINVAL;
2710
2711	size = __bpf_dynptr_size(ptr);
2712
2713	if (start > size || end > size)
2714		return -ERANGE;
2715
2716	ptr->offset += start;
2717	bpf_dynptr_set_size(ptr, end - start);
2718
2719	return 0;
2720}
2721
2722__bpf_kfunc bool bpf_dynptr_is_null(const struct bpf_dynptr *p)
2723{
2724	struct bpf_dynptr_kern *ptr = (struct bpf_dynptr_kern *)p;
2725
2726	return !ptr->data;
2727}
2728
2729__bpf_kfunc bool bpf_dynptr_is_rdonly(const struct bpf_dynptr *p)
2730{
2731	struct bpf_dynptr_kern *ptr = (struct bpf_dynptr_kern *)p;
2732
2733	if (!ptr->data)
2734		return false;
2735
2736	return __bpf_dynptr_is_rdonly(ptr);
2737}
2738
2739__bpf_kfunc __u32 bpf_dynptr_size(const struct bpf_dynptr *p)
2740{
2741	struct bpf_dynptr_kern *ptr = (struct bpf_dynptr_kern *)p;
2742
2743	if (!ptr->data)
2744		return -EINVAL;
2745
2746	return __bpf_dynptr_size(ptr);
2747}
2748
2749__bpf_kfunc int bpf_dynptr_clone(const struct bpf_dynptr *p,
2750				 struct bpf_dynptr *clone__uninit)
2751{
2752	struct bpf_dynptr_kern *clone = (struct bpf_dynptr_kern *)clone__uninit;
2753	struct bpf_dynptr_kern *ptr = (struct bpf_dynptr_kern *)p;
2754
2755	if (!ptr->data) {
2756		bpf_dynptr_set_null(clone);
2757		return -EINVAL;
2758	}
2759
2760	*clone = *ptr;
2761
2762	return 0;
2763}
2764
2765__bpf_kfunc void *bpf_cast_to_kern_ctx(void *obj)
2766{
2767	return obj;
2768}
2769
2770__bpf_kfunc void *bpf_rdonly_cast(const void *obj__ign, u32 btf_id__k)
2771{
2772	return (void *)obj__ign;
2773}
2774
2775__bpf_kfunc void bpf_rcu_read_lock(void)
2776{
2777	rcu_read_lock();
2778}
2779
2780__bpf_kfunc void bpf_rcu_read_unlock(void)
2781{
2782	rcu_read_unlock();
2783}
2784
2785struct bpf_throw_ctx {
2786	struct bpf_prog_aux *aux;
2787	u64 sp;
2788	u64 bp;
2789	int cnt;
2790};
2791
2792static bool bpf_stack_walker(void *cookie, u64 ip, u64 sp, u64 bp)
2793{
2794	struct bpf_throw_ctx *ctx = cookie;
2795	struct bpf_prog *prog;
2796
2797	if (!is_bpf_text_address(ip))
2798		return !ctx->cnt;
2799	prog = bpf_prog_ksym_find(ip);
2800	ctx->cnt++;
2801	if (bpf_is_subprog(prog))
2802		return true;
2803	ctx->aux = prog->aux;
2804	ctx->sp = sp;
2805	ctx->bp = bp;
2806	return false;
2807}
2808
2809__bpf_kfunc void bpf_throw(u64 cookie)
2810{
2811	struct bpf_throw_ctx ctx = {};
2812
2813	arch_bpf_stack_walk(bpf_stack_walker, &ctx);
2814	WARN_ON_ONCE(!ctx.aux);
2815	if (ctx.aux)
2816		WARN_ON_ONCE(!ctx.aux->exception_boundary);
2817	WARN_ON_ONCE(!ctx.bp);
2818	WARN_ON_ONCE(!ctx.cnt);
2819	/* Prevent KASAN false positives for CONFIG_KASAN_STACK by unpoisoning
2820	 * deeper stack depths than ctx.sp as we do not return from bpf_throw,
2821	 * which skips compiler generated instrumentation to do the same.
2822	 */
2823	kasan_unpoison_task_stack_below((void *)(long)ctx.sp);
2824	ctx.aux->bpf_exception_cb(cookie, ctx.sp, ctx.bp, 0, 0);
2825	WARN(1, "A call to BPF exception callback should never return\n");
2826}
2827
2828__bpf_kfunc int bpf_wq_init(struct bpf_wq *wq, void *p__map, unsigned int flags)
2829{
2830	struct bpf_async_kern *async = (struct bpf_async_kern *)wq;
2831	struct bpf_map *map = p__map;
2832
2833	BUILD_BUG_ON(sizeof(struct bpf_async_kern) > sizeof(struct bpf_wq));
2834	BUILD_BUG_ON(__alignof__(struct bpf_async_kern) != __alignof__(struct bpf_wq));
2835
2836	if (flags)
2837		return -EINVAL;
2838
2839	return __bpf_async_init(async, map, flags, BPF_ASYNC_TYPE_WQ);
2840}
2841
2842__bpf_kfunc int bpf_wq_start(struct bpf_wq *wq, unsigned int flags)
2843{
2844	struct bpf_async_kern *async = (struct bpf_async_kern *)wq;
2845	struct bpf_work *w;
2846
2847	if (in_nmi())
2848		return -EOPNOTSUPP;
2849	if (flags)
2850		return -EINVAL;
2851	w = READ_ONCE(async->work);
2852	if (!w || !READ_ONCE(w->cb.prog))
2853		return -EINVAL;
2854
2855	schedule_work(&w->work);
2856	return 0;
2857}
2858
2859__bpf_kfunc int bpf_wq_set_callback_impl(struct bpf_wq *wq,
2860					 int (callback_fn)(void *map, int *key, void *value),
2861					 unsigned int flags,
2862					 void *aux__ign)
2863{
2864	struct bpf_prog_aux *aux = (struct bpf_prog_aux *)aux__ign;
2865	struct bpf_async_kern *async = (struct bpf_async_kern *)wq;
2866
2867	if (flags)
2868		return -EINVAL;
2869
2870	return __bpf_async_set_callback(async, callback_fn, aux, flags, BPF_ASYNC_TYPE_WQ);
2871}
2872
2873__bpf_kfunc void bpf_preempt_disable(void)
2874{
2875	preempt_disable();
2876}
2877
2878__bpf_kfunc void bpf_preempt_enable(void)
2879{
2880	preempt_enable();
2881}
2882
2883struct bpf_iter_bits {
2884	__u64 __opaque[2];
2885} __aligned(8);
2886
2887#define BITS_ITER_NR_WORDS_MAX 511
2888
2889struct bpf_iter_bits_kern {
2890	union {
2891		__u64 *bits;
2892		__u64 bits_copy;
2893	};
2894	int nr_bits;
2895	int bit;
2896} __aligned(8);
2897
2898/* On 64-bit hosts, unsigned long and u64 have the same size, so passing
2899 * a u64 pointer and an unsigned long pointer to find_next_bit() will
2900 * return the same result, as both point to the same 8-byte area.
2901 *
2902 * For 32-bit little-endian hosts, using a u64 pointer or unsigned long
2903 * pointer also makes no difference. This is because the first iterated
2904 * unsigned long is composed of bits 0-31 of the u64 and the second unsigned
2905 * long is composed of bits 32-63 of the u64.
2906 *
2907 * However, for 32-bit big-endian hosts, this is not the case. The first
2908 * iterated unsigned long will be bits 32-63 of the u64, so swap these two
2909 * ulong values within the u64.
2910 */
2911static void swap_ulong_in_u64(u64 *bits, unsigned int nr)
2912{
2913#if (BITS_PER_LONG == 32) && defined(__BIG_ENDIAN)
2914	unsigned int i;
2915
2916	for (i = 0; i < nr; i++)
2917		bits[i] = (bits[i] >> 32) | ((u64)(u32)bits[i] << 32);
2918#endif
2919}
2920
2921/**
2922 * bpf_iter_bits_new() - Initialize a new bits iterator for a given memory area
2923 * @it: The new bpf_iter_bits to be created
2924 * @unsafe_ptr__ign: A pointer pointing to a memory area to be iterated over
2925 * @nr_words: The size of the specified memory area, measured in 8-byte units.
2926 * The maximum value of @nr_words is @BITS_ITER_NR_WORDS_MAX. This limit may be
2927 * further reduced by the BPF memory allocator implementation.
2928 *
2929 * This function initializes a new bpf_iter_bits structure for iterating over
2930 * a memory area which is specified by the @unsafe_ptr__ign and @nr_words. It
2931 * copies the data of the memory area to the newly created bpf_iter_bits @it for
2932 * subsequent iteration operations.
2933 *
2934 * On success, 0 is returned. On failure, ERR is returned.
2935 */
2936__bpf_kfunc int
2937bpf_iter_bits_new(struct bpf_iter_bits *it, const u64 *unsafe_ptr__ign, u32 nr_words)
2938{
2939	struct bpf_iter_bits_kern *kit = (void *)it;
2940	u32 nr_bytes = nr_words * sizeof(u64);
2941	u32 nr_bits = BYTES_TO_BITS(nr_bytes);
2942	int err;
2943
2944	BUILD_BUG_ON(sizeof(struct bpf_iter_bits_kern) != sizeof(struct bpf_iter_bits));
2945	BUILD_BUG_ON(__alignof__(struct bpf_iter_bits_kern) !=
2946		     __alignof__(struct bpf_iter_bits));
2947
2948	kit->nr_bits = 0;
2949	kit->bits_copy = 0;
2950	kit->bit = -1;
2951
2952	if (!unsafe_ptr__ign || !nr_words)
2953		return -EINVAL;
2954	if (nr_words > BITS_ITER_NR_WORDS_MAX)
2955		return -E2BIG;
2956
2957	/* Optimization for u64 mask */
2958	if (nr_bits == 64) {
2959		err = bpf_probe_read_kernel_common(&kit->bits_copy, nr_bytes, unsafe_ptr__ign);
2960		if (err)
2961			return -EFAULT;
2962
2963		swap_ulong_in_u64(&kit->bits_copy, nr_words);
2964
2965		kit->nr_bits = nr_bits;
2966		return 0;
2967	}
2968
2969	if (bpf_mem_alloc_check_size(false, nr_bytes))
2970		return -E2BIG;
2971
2972	/* Fallback to memalloc */
2973	kit->bits = bpf_mem_alloc(&bpf_global_ma, nr_bytes);
2974	if (!kit->bits)
2975		return -ENOMEM;
2976
2977	err = bpf_probe_read_kernel_common(kit->bits, nr_bytes, unsafe_ptr__ign);
2978	if (err) {
2979		bpf_mem_free(&bpf_global_ma, kit->bits);
2980		return err;
2981	}
2982
2983	swap_ulong_in_u64(kit->bits, nr_words);
2984
2985	kit->nr_bits = nr_bits;
2986	return 0;
2987}
2988
2989/**
2990 * bpf_iter_bits_next() - Get the next bit in a bpf_iter_bits
2991 * @it: The bpf_iter_bits to be checked
2992 *
2993 * This function returns a pointer to a number representing the value of the
2994 * next bit in the bits.
2995 *
2996 * If there are no further bits available, it returns NULL.
2997 */
2998__bpf_kfunc int *bpf_iter_bits_next(struct bpf_iter_bits *it)
2999{
3000	struct bpf_iter_bits_kern *kit = (void *)it;
3001	int bit = kit->bit, nr_bits = kit->nr_bits;
3002	const void *bits;
3003
3004	if (!nr_bits || bit >= nr_bits)
3005		return NULL;
3006
3007	bits = nr_bits == 64 ? &kit->bits_copy : kit->bits;
3008	bit = find_next_bit(bits, nr_bits, bit + 1);
3009	if (bit >= nr_bits) {
3010		kit->bit = bit;
3011		return NULL;
3012	}
3013
3014	kit->bit = bit;
3015	return &kit->bit;
3016}
3017
3018/**
3019 * bpf_iter_bits_destroy() - Destroy a bpf_iter_bits
3020 * @it: The bpf_iter_bits to be destroyed
3021 *
3022 * Destroy the resource associated with the bpf_iter_bits.
3023 */
3024__bpf_kfunc void bpf_iter_bits_destroy(struct bpf_iter_bits *it)
3025{
3026	struct bpf_iter_bits_kern *kit = (void *)it;
3027
3028	if (kit->nr_bits <= 64)
3029		return;
3030	bpf_mem_free(&bpf_global_ma, kit->bits);
3031}
3032
3033/**
3034 * bpf_copy_from_user_str() - Copy a string from an unsafe user address
3035 * @dst:             Destination address, in kernel space.  This buffer must be
3036 *                   at least @dst__sz bytes long.
3037 * @dst__sz:         Maximum number of bytes to copy, includes the trailing NUL.
3038 * @unsafe_ptr__ign: Source address, in user space.
3039 * @flags:           The only supported flag is BPF_F_PAD_ZEROS
3040 *
3041 * Copies a NUL-terminated string from userspace to BPF space. If user string is
3042 * too long this will still ensure zero termination in the dst buffer unless
3043 * buffer size is 0.
3044 *
3045 * If BPF_F_PAD_ZEROS flag is set, memset the tail of @dst to 0 on success and
3046 * memset all of @dst on failure.
3047 */
3048__bpf_kfunc int bpf_copy_from_user_str(void *dst, u32 dst__sz, const void __user *unsafe_ptr__ign, u64 flags)
3049{
3050	int ret;
3051
3052	if (unlikely(flags & ~BPF_F_PAD_ZEROS))
3053		return -EINVAL;
3054
3055	if (unlikely(!dst__sz))
3056		return 0;
3057
3058	ret = strncpy_from_user(dst, unsafe_ptr__ign, dst__sz - 1);
3059	if (ret < 0) {
3060		if (flags & BPF_F_PAD_ZEROS)
3061			memset((char *)dst, 0, dst__sz);
3062
3063		return ret;
3064	}
3065
3066	if (flags & BPF_F_PAD_ZEROS)
3067		memset((char *)dst + ret, 0, dst__sz - ret);
3068	else
3069		((char *)dst)[ret] = '\0';
3070
3071	return ret + 1;
3072}
3073
3074__bpf_kfunc_end_defs();
3075
3076BTF_KFUNCS_START(generic_btf_ids)
3077#ifdef CONFIG_CRASH_DUMP
3078BTF_ID_FLAGS(func, crash_kexec, KF_DESTRUCTIVE)
3079#endif
3080BTF_ID_FLAGS(func, bpf_obj_new_impl, KF_ACQUIRE | KF_RET_NULL)
3081BTF_ID_FLAGS(func, bpf_percpu_obj_new_impl, KF_ACQUIRE | KF_RET_NULL)
3082BTF_ID_FLAGS(func, bpf_obj_drop_impl, KF_RELEASE)
3083BTF_ID_FLAGS(func, bpf_percpu_obj_drop_impl, KF_RELEASE)
3084BTF_ID_FLAGS(func, bpf_refcount_acquire_impl, KF_ACQUIRE | KF_RET_NULL | KF_RCU)
3085BTF_ID_FLAGS(func, bpf_list_push_front_impl)
3086BTF_ID_FLAGS(func, bpf_list_push_back_impl)
3087BTF_ID_FLAGS(func, bpf_list_pop_front, KF_ACQUIRE | KF_RET_NULL)
3088BTF_ID_FLAGS(func, bpf_list_pop_back, KF_ACQUIRE | KF_RET_NULL)
3089BTF_ID_FLAGS(func, bpf_task_acquire, KF_ACQUIRE | KF_RCU | KF_RET_NULL)
3090BTF_ID_FLAGS(func, bpf_task_release, KF_RELEASE)
3091BTF_ID_FLAGS(func, bpf_rbtree_remove, KF_ACQUIRE | KF_RET_NULL)
3092BTF_ID_FLAGS(func, bpf_rbtree_add_impl)
3093BTF_ID_FLAGS(func, bpf_rbtree_first, KF_RET_NULL)
3094
3095#ifdef CONFIG_CGROUPS
3096BTF_ID_FLAGS(func, bpf_cgroup_acquire, KF_ACQUIRE | KF_RCU | KF_RET_NULL)
3097BTF_ID_FLAGS(func, bpf_cgroup_release, KF_RELEASE)
3098BTF_ID_FLAGS(func, bpf_cgroup_ancestor, KF_ACQUIRE | KF_RCU | KF_RET_NULL)
3099BTF_ID_FLAGS(func, bpf_cgroup_from_id, KF_ACQUIRE | KF_RET_NULL)
3100BTF_ID_FLAGS(func, bpf_task_under_cgroup, KF_RCU)
3101BTF_ID_FLAGS(func, bpf_task_get_cgroup1, KF_ACQUIRE | KF_RCU | KF_RET_NULL)
3102#endif
3103BTF_ID_FLAGS(func, bpf_task_from_pid, KF_ACQUIRE | KF_RET_NULL)
3104BTF_ID_FLAGS(func, bpf_task_from_vpid, KF_ACQUIRE | KF_RET_NULL)
3105BTF_ID_FLAGS(func, bpf_throw)
3106BTF_ID_FLAGS(func, bpf_send_signal_task, KF_TRUSTED_ARGS)
3107BTF_KFUNCS_END(generic_btf_ids)
3108
3109static const struct btf_kfunc_id_set generic_kfunc_set = {
3110	.owner = THIS_MODULE,
3111	.set   = &generic_btf_ids,
3112};
3113
3114
3115BTF_ID_LIST(generic_dtor_ids)
3116BTF_ID(struct, task_struct)
3117BTF_ID(func, bpf_task_release_dtor)
3118#ifdef CONFIG_CGROUPS
3119BTF_ID(struct, cgroup)
3120BTF_ID(func, bpf_cgroup_release_dtor)
3121#endif
3122
3123BTF_KFUNCS_START(common_btf_ids)
3124BTF_ID_FLAGS(func, bpf_cast_to_kern_ctx, KF_FASTCALL)
3125BTF_ID_FLAGS(func, bpf_rdonly_cast, KF_FASTCALL)
3126BTF_ID_FLAGS(func, bpf_rcu_read_lock)
3127BTF_ID_FLAGS(func, bpf_rcu_read_unlock)
3128BTF_ID_FLAGS(func, bpf_dynptr_slice, KF_RET_NULL)
3129BTF_ID_FLAGS(func, bpf_dynptr_slice_rdwr, KF_RET_NULL)
3130BTF_ID_FLAGS(func, bpf_iter_num_new, KF_ITER_NEW)
3131BTF_ID_FLAGS(func, bpf_iter_num_next, KF_ITER_NEXT | KF_RET_NULL)
3132BTF_ID_FLAGS(func, bpf_iter_num_destroy, KF_ITER_DESTROY)
3133BTF_ID_FLAGS(func, bpf_iter_task_vma_new, KF_ITER_NEW | KF_RCU)
3134BTF_ID_FLAGS(func, bpf_iter_task_vma_next, KF_ITER_NEXT | KF_RET_NULL)
3135BTF_ID_FLAGS(func, bpf_iter_task_vma_destroy, KF_ITER_DESTROY)
3136#ifdef CONFIG_CGROUPS
3137BTF_ID_FLAGS(func, bpf_iter_css_task_new, KF_ITER_NEW | KF_TRUSTED_ARGS)
3138BTF_ID_FLAGS(func, bpf_iter_css_task_next, KF_ITER_NEXT | KF_RET_NULL)
3139BTF_ID_FLAGS(func, bpf_iter_css_task_destroy, KF_ITER_DESTROY)
3140BTF_ID_FLAGS(func, bpf_iter_css_new, KF_ITER_NEW | KF_TRUSTED_ARGS | KF_RCU_PROTECTED)
3141BTF_ID_FLAGS(func, bpf_iter_css_next, KF_ITER_NEXT | KF_RET_NULL)
3142BTF_ID_FLAGS(func, bpf_iter_css_destroy, KF_ITER_DESTROY)
3143#endif
3144BTF_ID_FLAGS(func, bpf_iter_task_new, KF_ITER_NEW | KF_TRUSTED_ARGS | KF_RCU_PROTECTED)
3145BTF_ID_FLAGS(func, bpf_iter_task_next, KF_ITER_NEXT | KF_RET_NULL)
3146BTF_ID_FLAGS(func, bpf_iter_task_destroy, KF_ITER_DESTROY)
3147BTF_ID_FLAGS(func, bpf_dynptr_adjust)
3148BTF_ID_FLAGS(func, bpf_dynptr_is_null)
3149BTF_ID_FLAGS(func, bpf_dynptr_is_rdonly)
3150BTF_ID_FLAGS(func, bpf_dynptr_size)
3151BTF_ID_FLAGS(func, bpf_dynptr_clone)
3152BTF_ID_FLAGS(func, bpf_modify_return_test_tp)
3153BTF_ID_FLAGS(func, bpf_wq_init)
3154BTF_ID_FLAGS(func, bpf_wq_set_callback_impl)
3155BTF_ID_FLAGS(func, bpf_wq_start)
3156BTF_ID_FLAGS(func, bpf_preempt_disable)
3157BTF_ID_FLAGS(func, bpf_preempt_enable)
3158BTF_ID_FLAGS(func, bpf_iter_bits_new, KF_ITER_NEW)
3159BTF_ID_FLAGS(func, bpf_iter_bits_next, KF_ITER_NEXT | KF_RET_NULL)
3160BTF_ID_FLAGS(func, bpf_iter_bits_destroy, KF_ITER_DESTROY)
3161BTF_ID_FLAGS(func, bpf_copy_from_user_str, KF_SLEEPABLE)
3162BTF_ID_FLAGS(func, bpf_get_kmem_cache)
3163BTF_ID_FLAGS(func, bpf_iter_kmem_cache_new, KF_ITER_NEW | KF_SLEEPABLE)
3164BTF_ID_FLAGS(func, bpf_iter_kmem_cache_next, KF_ITER_NEXT | KF_RET_NULL | KF_SLEEPABLE)
3165BTF_ID_FLAGS(func, bpf_iter_kmem_cache_destroy, KF_ITER_DESTROY | KF_SLEEPABLE)
3166BTF_KFUNCS_END(common_btf_ids)
3167
3168static const struct btf_kfunc_id_set common_kfunc_set = {
3169	.owner = THIS_MODULE,
3170	.set   = &common_btf_ids,
3171};
3172
3173static int __init kfunc_init(void)
3174{
3175	int ret;
3176	const struct btf_id_dtor_kfunc generic_dtors[] = {
3177		{
3178			.btf_id       = generic_dtor_ids[0],
3179			.kfunc_btf_id = generic_dtor_ids[1]
3180		},
3181#ifdef CONFIG_CGROUPS
3182		{
3183			.btf_id       = generic_dtor_ids[2],
3184			.kfunc_btf_id = generic_dtor_ids[3]
3185		},
3186#endif
3187	};
3188
3189	ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_TRACING, &generic_kfunc_set);
3190	ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_SCHED_CLS, &generic_kfunc_set);
3191	ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_XDP, &generic_kfunc_set);
3192	ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS, &generic_kfunc_set);
3193	ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_SYSCALL, &generic_kfunc_set);
3194	ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_CGROUP_SKB, &generic_kfunc_set);
3195	ret = ret ?: register_btf_id_dtor_kfuncs(generic_dtors,
3196						  ARRAY_SIZE(generic_dtors),
3197						  THIS_MODULE);
3198	return ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_UNSPEC, &common_kfunc_set);
3199}
3200
3201late_initcall(kfunc_init);
3202
3203/* Get a pointer to dynptr data up to len bytes for read only access. If
3204 * the dynptr doesn't have continuous data up to len bytes, return NULL.
3205 */
3206const void *__bpf_dynptr_data(const struct bpf_dynptr_kern *ptr, u32 len)
3207{
3208	const struct bpf_dynptr *p = (struct bpf_dynptr *)ptr;
3209
3210	return bpf_dynptr_slice(p, 0, NULL, len);
3211}
3212
3213/* Get a pointer to dynptr data up to len bytes for read write access. If
3214 * the dynptr doesn't have continuous data up to len bytes, or the dynptr
3215 * is read only, return NULL.
3216 */
3217void *__bpf_dynptr_data_rw(const struct bpf_dynptr_kern *ptr, u32 len)
3218{
3219	if (__bpf_dynptr_is_rdonly(ptr))
3220		return NULL;
3221	return (void *)__bpf_dynptr_data(ptr, len);
3222}