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 <net/xdp.h> 17 #include <linux/ctype.h> 18 #include <linux/jiffies.h> 19 #include <linux/pid_namespace.h> 20 #include <linux/poison.h> 21 #include <linux/proc_ns.h> 22 #include <linux/sched/task.h> 23 #include <linux/security.h> 24 #include <linux/btf_ids.h> 25 #include <linux/bpf_mem_alloc.h> 26 #include <linux/kprobes.h> 27 #include <linux/bpf_verifier.h> 28 #include <linux/uaccess.h> 29 #include <linux/verification.h> 30 #include <linux/task_work.h> 31 #include <linux/irq_work.h> 32 #include <linux/buildid.h> 33 34 #include "../../lib/kstrtox.h" 35 36 /* If kernel subsystem is allowing eBPF programs to call this function, 37 * inside its own verifier_ops->get_func_proto() callback it should return 38 * bpf_map_lookup_elem_proto, so that verifier can properly check the arguments 39 * 40 * Different map implementations will rely on rcu in map methods 41 * lookup/update/delete, therefore eBPF programs must run under rcu lock 42 * if program is allowed to access maps, so check rcu_read_lock_held() or 43 * rcu_read_lock_trace_held() in all three functions. 44 */ 45 BPF_CALL_2(bpf_map_lookup_elem, struct bpf_map *, map, void *, key) 46 { 47 WARN_ON_ONCE(!bpf_rcu_lock_held()); 48 return (unsigned long) map->ops->map_lookup_elem(map, key); 49 } 50 51 const struct bpf_func_proto bpf_map_lookup_elem_proto = { 52 .func = bpf_map_lookup_elem, 53 .gpl_only = false, 54 .pkt_access = true, 55 .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL, 56 .arg1_type = ARG_CONST_MAP_PTR, 57 .arg2_type = ARG_PTR_TO_MAP_KEY, 58 }; 59 60 BPF_CALL_4(bpf_map_update_elem, struct bpf_map *, map, void *, key, 61 void *, value, u64, flags) 62 { 63 WARN_ON_ONCE(!bpf_rcu_lock_held()); 64 return map->ops->map_update_elem(map, key, value, flags); 65 } 66 67 const struct bpf_func_proto bpf_map_update_elem_proto = { 68 .func = bpf_map_update_elem, 69 .gpl_only = false, 70 .pkt_access = true, 71 .ret_type = RET_INTEGER, 72 .arg1_type = ARG_CONST_MAP_PTR, 73 .arg2_type = ARG_PTR_TO_MAP_KEY, 74 .arg3_type = ARG_PTR_TO_MAP_VALUE, 75 .arg4_type = ARG_ANYTHING, 76 }; 77 78 BPF_CALL_2(bpf_map_delete_elem, struct bpf_map *, map, void *, key) 79 { 80 WARN_ON_ONCE(!bpf_rcu_lock_held()); 81 return map->ops->map_delete_elem(map, key); 82 } 83 84 const struct bpf_func_proto bpf_map_delete_elem_proto = { 85 .func = bpf_map_delete_elem, 86 .gpl_only = false, 87 .pkt_access = true, 88 .ret_type = RET_INTEGER, 89 .arg1_type = ARG_CONST_MAP_PTR, 90 .arg2_type = ARG_PTR_TO_MAP_KEY, 91 }; 92 93 BPF_CALL_3(bpf_map_push_elem, struct bpf_map *, map, void *, value, u64, flags) 94 { 95 return map->ops->map_push_elem(map, value, flags); 96 } 97 98 const struct bpf_func_proto bpf_map_push_elem_proto = { 99 .func = bpf_map_push_elem, 100 .gpl_only = false, 101 .pkt_access = true, 102 .ret_type = RET_INTEGER, 103 .arg1_type = ARG_CONST_MAP_PTR, 104 .arg2_type = ARG_PTR_TO_MAP_VALUE, 105 .arg3_type = ARG_ANYTHING, 106 }; 107 108 BPF_CALL_2(bpf_map_pop_elem, struct bpf_map *, map, void *, value) 109 { 110 return map->ops->map_pop_elem(map, value); 111 } 112 113 const struct bpf_func_proto bpf_map_pop_elem_proto = { 114 .func = bpf_map_pop_elem, 115 .gpl_only = false, 116 .ret_type = RET_INTEGER, 117 .arg1_type = ARG_CONST_MAP_PTR, 118 .arg2_type = ARG_PTR_TO_MAP_VALUE | MEM_UNINIT | MEM_WRITE, 119 }; 120 121 BPF_CALL_2(bpf_map_peek_elem, struct bpf_map *, map, void *, value) 122 { 123 return map->ops->map_peek_elem(map, value); 124 } 125 126 const struct bpf_func_proto bpf_map_peek_elem_proto = { 127 .func = bpf_map_peek_elem, 128 .gpl_only = false, 129 .ret_type = RET_INTEGER, 130 .arg1_type = ARG_CONST_MAP_PTR, 131 .arg2_type = ARG_PTR_TO_MAP_VALUE | MEM_UNINIT | MEM_WRITE, 132 }; 133 134 BPF_CALL_3(bpf_map_lookup_percpu_elem, struct bpf_map *, map, void *, key, u32, cpu) 135 { 136 WARN_ON_ONCE(!bpf_rcu_lock_held()); 137 return (unsigned long) map->ops->map_lookup_percpu_elem(map, key, cpu); 138 } 139 140 const struct bpf_func_proto bpf_map_lookup_percpu_elem_proto = { 141 .func = bpf_map_lookup_percpu_elem, 142 .gpl_only = false, 143 .pkt_access = true, 144 .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL, 145 .arg1_type = ARG_CONST_MAP_PTR, 146 .arg2_type = ARG_PTR_TO_MAP_KEY, 147 .arg3_type = ARG_ANYTHING, 148 }; 149 150 const struct bpf_func_proto bpf_get_prandom_u32_proto = { 151 .func = bpf_user_rnd_u32, 152 .gpl_only = false, 153 .ret_type = RET_INTEGER, 154 }; 155 156 BPF_CALL_0(bpf_get_smp_processor_id) 157 { 158 return smp_processor_id(); 159 } 160 161 const struct bpf_func_proto bpf_get_smp_processor_id_proto = { 162 .func = bpf_get_smp_processor_id, 163 .gpl_only = false, 164 .ret_type = RET_INTEGER, 165 .allow_fastcall = true, 166 }; 167 168 BPF_CALL_0(bpf_get_numa_node_id) 169 { 170 return numa_node_id(); 171 } 172 173 const struct bpf_func_proto bpf_get_numa_node_id_proto = { 174 .func = bpf_get_numa_node_id, 175 .gpl_only = false, 176 .ret_type = RET_INTEGER, 177 }; 178 179 BPF_CALL_0(bpf_ktime_get_ns) 180 { 181 /* NMI safe access to clock monotonic */ 182 return ktime_get_mono_fast_ns(); 183 } 184 185 const struct bpf_func_proto bpf_ktime_get_ns_proto = { 186 .func = bpf_ktime_get_ns, 187 .gpl_only = false, 188 .ret_type = RET_INTEGER, 189 }; 190 191 BPF_CALL_0(bpf_ktime_get_boot_ns) 192 { 193 /* NMI safe access to clock boottime */ 194 return ktime_get_boot_fast_ns(); 195 } 196 197 const struct bpf_func_proto bpf_ktime_get_boot_ns_proto = { 198 .func = bpf_ktime_get_boot_ns, 199 .gpl_only = false, 200 .ret_type = RET_INTEGER, 201 }; 202 203 BPF_CALL_0(bpf_ktime_get_coarse_ns) 204 { 205 return ktime_get_coarse_ns(); 206 } 207 208 const struct bpf_func_proto bpf_ktime_get_coarse_ns_proto = { 209 .func = bpf_ktime_get_coarse_ns, 210 .gpl_only = false, 211 .ret_type = RET_INTEGER, 212 }; 213 214 BPF_CALL_0(bpf_ktime_get_tai_ns) 215 { 216 /* NMI safe access to clock tai */ 217 return ktime_get_tai_fast_ns(); 218 } 219 220 const struct bpf_func_proto bpf_ktime_get_tai_ns_proto = { 221 .func = bpf_ktime_get_tai_ns, 222 .gpl_only = false, 223 .ret_type = RET_INTEGER, 224 }; 225 226 BPF_CALL_0(bpf_get_current_pid_tgid) 227 { 228 struct task_struct *task = current; 229 230 if (unlikely(!task)) 231 return -EINVAL; 232 233 return (u64) task->tgid << 32 | task->pid; 234 } 235 236 const struct bpf_func_proto bpf_get_current_pid_tgid_proto = { 237 .func = bpf_get_current_pid_tgid, 238 .gpl_only = false, 239 .ret_type = RET_INTEGER, 240 }; 241 242 BPF_CALL_0(bpf_get_current_uid_gid) 243 { 244 struct task_struct *task = current; 245 kuid_t uid; 246 kgid_t gid; 247 248 if (unlikely(!task)) 249 return -EINVAL; 250 251 current_uid_gid(&uid, &gid); 252 return (u64) from_kgid(&init_user_ns, gid) << 32 | 253 from_kuid(&init_user_ns, uid); 254 } 255 256 const struct bpf_func_proto bpf_get_current_uid_gid_proto = { 257 .func = bpf_get_current_uid_gid, 258 .gpl_only = false, 259 .ret_type = RET_INTEGER, 260 }; 261 262 BPF_CALL_2(bpf_get_current_comm, char *, buf, u32, size) 263 { 264 struct task_struct *task = current; 265 266 if (unlikely(!task)) 267 goto err_clear; 268 269 /* Verifier guarantees that size > 0 */ 270 strscpy_pad(buf, task->comm, size); 271 return 0; 272 err_clear: 273 memset(buf, 0, size); 274 return -EINVAL; 275 } 276 277 const struct bpf_func_proto bpf_get_current_comm_proto = { 278 .func = bpf_get_current_comm, 279 .gpl_only = false, 280 .ret_type = RET_INTEGER, 281 .arg1_type = ARG_PTR_TO_UNINIT_MEM, 282 .arg2_type = ARG_MEM_SIZE, 283 }; 284 285 #if defined(CONFIG_QUEUED_SPINLOCKS) || defined(CONFIG_BPF_ARCH_SPINLOCK) 286 287 static inline void __bpf_spin_lock(struct bpf_spin_lock *lock) 288 { 289 arch_spinlock_t *l = (void *)lock; 290 union { 291 __u32 val; 292 arch_spinlock_t lock; 293 } u = { .lock = __ARCH_SPIN_LOCK_UNLOCKED }; 294 295 compiletime_assert(u.val == 0, "__ARCH_SPIN_LOCK_UNLOCKED not 0"); 296 BUILD_BUG_ON(sizeof(*l) != sizeof(__u32)); 297 BUILD_BUG_ON(sizeof(*lock) != sizeof(__u32)); 298 preempt_disable(); 299 arch_spin_lock(l); 300 } 301 302 static inline void __bpf_spin_unlock(struct bpf_spin_lock *lock) 303 { 304 arch_spinlock_t *l = (void *)lock; 305 306 arch_spin_unlock(l); 307 preempt_enable(); 308 } 309 310 #else 311 312 static inline void __bpf_spin_lock(struct bpf_spin_lock *lock) 313 { 314 atomic_t *l = (void *)lock; 315 316 BUILD_BUG_ON(sizeof(*l) != sizeof(*lock)); 317 do { 318 atomic_cond_read_relaxed(l, !VAL); 319 } while (atomic_xchg(l, 1)); 320 } 321 322 static inline void __bpf_spin_unlock(struct bpf_spin_lock *lock) 323 { 324 atomic_t *l = (void *)lock; 325 326 atomic_set_release(l, 0); 327 } 328 329 #endif 330 331 static DEFINE_PER_CPU(unsigned long, irqsave_flags); 332 333 static inline void __bpf_spin_lock_irqsave(struct bpf_spin_lock *lock) 334 { 335 unsigned long flags; 336 337 local_irq_save(flags); 338 __bpf_spin_lock(lock); 339 __this_cpu_write(irqsave_flags, flags); 340 } 341 342 NOTRACE_BPF_CALL_1(bpf_spin_lock, struct bpf_spin_lock *, lock) 343 { 344 __bpf_spin_lock_irqsave(lock); 345 return 0; 346 } 347 348 const struct bpf_func_proto bpf_spin_lock_proto = { 349 .func = bpf_spin_lock, 350 .gpl_only = false, 351 .ret_type = RET_VOID, 352 .arg1_type = ARG_PTR_TO_SPIN_LOCK, 353 .arg1_btf_id = BPF_PTR_POISON, 354 }; 355 356 static inline void __bpf_spin_unlock_irqrestore(struct bpf_spin_lock *lock) 357 { 358 unsigned long flags; 359 360 flags = __this_cpu_read(irqsave_flags); 361 __bpf_spin_unlock(lock); 362 local_irq_restore(flags); 363 } 364 365 NOTRACE_BPF_CALL_1(bpf_spin_unlock, struct bpf_spin_lock *, lock) 366 { 367 __bpf_spin_unlock_irqrestore(lock); 368 return 0; 369 } 370 371 const struct bpf_func_proto bpf_spin_unlock_proto = { 372 .func = bpf_spin_unlock, 373 .gpl_only = false, 374 .ret_type = RET_VOID, 375 .arg1_type = ARG_PTR_TO_SPIN_LOCK, 376 .arg1_btf_id = BPF_PTR_POISON, 377 }; 378 379 void copy_map_value_locked(struct bpf_map *map, void *dst, void *src, 380 bool lock_src) 381 { 382 struct bpf_spin_lock *lock; 383 384 if (lock_src) 385 lock = src + map->record->spin_lock_off; 386 else 387 lock = dst + map->record->spin_lock_off; 388 preempt_disable(); 389 __bpf_spin_lock_irqsave(lock); 390 copy_map_value(map, dst, src); 391 __bpf_spin_unlock_irqrestore(lock); 392 preempt_enable(); 393 } 394 395 BPF_CALL_0(bpf_jiffies64) 396 { 397 return get_jiffies_64(); 398 } 399 400 const struct bpf_func_proto bpf_jiffies64_proto = { 401 .func = bpf_jiffies64, 402 .gpl_only = false, 403 .ret_type = RET_INTEGER, 404 }; 405 406 #ifdef CONFIG_CGROUPS 407 BPF_CALL_0(bpf_get_current_cgroup_id) 408 { 409 struct cgroup *cgrp; 410 u64 cgrp_id; 411 412 rcu_read_lock(); 413 cgrp = task_dfl_cgroup(current); 414 cgrp_id = cgroup_id(cgrp); 415 rcu_read_unlock(); 416 417 return cgrp_id; 418 } 419 420 const struct bpf_func_proto bpf_get_current_cgroup_id_proto = { 421 .func = bpf_get_current_cgroup_id, 422 .gpl_only = false, 423 .ret_type = RET_INTEGER, 424 }; 425 426 BPF_CALL_1(bpf_get_current_ancestor_cgroup_id, int, ancestor_level) 427 { 428 struct cgroup *cgrp; 429 struct cgroup *ancestor; 430 u64 cgrp_id; 431 432 rcu_read_lock(); 433 cgrp = task_dfl_cgroup(current); 434 ancestor = cgroup_ancestor(cgrp, ancestor_level); 435 cgrp_id = ancestor ? cgroup_id(ancestor) : 0; 436 rcu_read_unlock(); 437 438 return cgrp_id; 439 } 440 441 const struct bpf_func_proto bpf_get_current_ancestor_cgroup_id_proto = { 442 .func = bpf_get_current_ancestor_cgroup_id, 443 .gpl_only = false, 444 .ret_type = RET_INTEGER, 445 .arg1_type = ARG_ANYTHING, 446 }; 447 #endif /* CONFIG_CGROUPS */ 448 449 #define BPF_STRTOX_BASE_MASK 0x1F 450 451 static int __bpf_strtoull(const char *buf, size_t buf_len, u64 flags, 452 unsigned long long *res, bool *is_negative) 453 { 454 unsigned int base = flags & BPF_STRTOX_BASE_MASK; 455 const char *cur_buf = buf; 456 size_t cur_len = buf_len; 457 unsigned int consumed; 458 size_t val_len; 459 char str[64]; 460 461 if (!buf || !buf_len || !res || !is_negative) 462 return -EINVAL; 463 464 if (base != 0 && base != 8 && base != 10 && base != 16) 465 return -EINVAL; 466 467 if (flags & ~BPF_STRTOX_BASE_MASK) 468 return -EINVAL; 469 470 while (cur_buf < buf + buf_len && isspace(*cur_buf)) 471 ++cur_buf; 472 473 *is_negative = (cur_buf < buf + buf_len && *cur_buf == '-'); 474 if (*is_negative) 475 ++cur_buf; 476 477 consumed = cur_buf - buf; 478 cur_len -= consumed; 479 if (!cur_len) 480 return -EINVAL; 481 482 cur_len = min(cur_len, sizeof(str) - 1); 483 memcpy(str, cur_buf, cur_len); 484 str[cur_len] = '\0'; 485 cur_buf = str; 486 487 cur_buf = _parse_integer_fixup_radix(cur_buf, &base); 488 val_len = _parse_integer(cur_buf, base, res); 489 490 if (val_len & KSTRTOX_OVERFLOW) 491 return -ERANGE; 492 493 if (val_len == 0) 494 return -EINVAL; 495 496 cur_buf += val_len; 497 consumed += cur_buf - str; 498 499 return consumed; 500 } 501 502 static int __bpf_strtoll(const char *buf, size_t buf_len, u64 flags, 503 long long *res) 504 { 505 unsigned long long _res; 506 bool is_negative; 507 int err; 508 509 err = __bpf_strtoull(buf, buf_len, flags, &_res, &is_negative); 510 if (err < 0) 511 return err; 512 if (is_negative) { 513 if ((long long)-_res > 0) 514 return -ERANGE; 515 *res = -_res; 516 } else { 517 if ((long long)_res < 0) 518 return -ERANGE; 519 *res = _res; 520 } 521 return err; 522 } 523 524 BPF_CALL_4(bpf_strtol, const char *, buf, size_t, buf_len, u64, flags, 525 s64 *, res) 526 { 527 long long _res; 528 int err; 529 530 *res = 0; 531 err = __bpf_strtoll(buf, buf_len, flags, &_res); 532 if (err < 0) 533 return err; 534 *res = _res; 535 return err; 536 } 537 538 const struct bpf_func_proto bpf_strtol_proto = { 539 .func = bpf_strtol, 540 .gpl_only = false, 541 .ret_type = RET_INTEGER, 542 .arg1_type = ARG_PTR_TO_MEM | MEM_RDONLY, 543 .arg2_type = ARG_MEM_SIZE, 544 .arg3_type = ARG_ANYTHING, 545 .arg4_type = ARG_PTR_TO_FIXED_SIZE_MEM | MEM_UNINIT | MEM_WRITE | MEM_ALIGNED, 546 .arg4_size = sizeof(s64), 547 }; 548 549 BPF_CALL_4(bpf_strtoul, const char *, buf, size_t, buf_len, u64, flags, 550 u64 *, res) 551 { 552 unsigned long long _res; 553 bool is_negative; 554 int err; 555 556 *res = 0; 557 err = __bpf_strtoull(buf, buf_len, flags, &_res, &is_negative); 558 if (err < 0) 559 return err; 560 if (is_negative) 561 return -EINVAL; 562 *res = _res; 563 return err; 564 } 565 566 const struct bpf_func_proto bpf_strtoul_proto = { 567 .func = bpf_strtoul, 568 .gpl_only = false, 569 .ret_type = RET_INTEGER, 570 .arg1_type = ARG_PTR_TO_MEM | MEM_RDONLY, 571 .arg2_type = ARG_MEM_SIZE, 572 .arg3_type = ARG_ANYTHING, 573 .arg4_type = ARG_PTR_TO_FIXED_SIZE_MEM | MEM_UNINIT | MEM_WRITE | MEM_ALIGNED, 574 .arg4_size = sizeof(u64), 575 }; 576 577 BPF_CALL_3(bpf_strncmp, const char *, s1, u32, s1_sz, const char *, s2) 578 { 579 return strncmp(s1, s2, s1_sz); 580 } 581 582 static const struct bpf_func_proto bpf_strncmp_proto = { 583 .func = bpf_strncmp, 584 .gpl_only = false, 585 .ret_type = RET_INTEGER, 586 .arg1_type = ARG_PTR_TO_MEM | MEM_RDONLY, 587 .arg2_type = ARG_MEM_SIZE, 588 .arg3_type = ARG_PTR_TO_CONST_STR, 589 }; 590 591 BPF_CALL_4(bpf_get_ns_current_pid_tgid, u64, dev, u64, ino, 592 struct bpf_pidns_info *, nsdata, u32, size) 593 { 594 struct task_struct *task = current; 595 struct pid_namespace *pidns; 596 int err = -EINVAL; 597 598 if (unlikely(size != sizeof(struct bpf_pidns_info))) 599 goto clear; 600 601 if (unlikely((u64)(dev_t)dev != dev)) 602 goto clear; 603 604 if (unlikely(!task)) 605 goto clear; 606 607 pidns = task_active_pid_ns(task); 608 if (unlikely(!pidns)) { 609 err = -ENOENT; 610 goto clear; 611 } 612 613 if (!ns_match(&pidns->ns, (dev_t)dev, ino)) 614 goto clear; 615 616 nsdata->pid = task_pid_nr_ns(task, pidns); 617 nsdata->tgid = task_tgid_nr_ns(task, pidns); 618 return 0; 619 clear: 620 memset((void *)nsdata, 0, (size_t) size); 621 return err; 622 } 623 624 const struct bpf_func_proto bpf_get_ns_current_pid_tgid_proto = { 625 .func = bpf_get_ns_current_pid_tgid, 626 .gpl_only = false, 627 .ret_type = RET_INTEGER, 628 .arg1_type = ARG_ANYTHING, 629 .arg2_type = ARG_ANYTHING, 630 .arg3_type = ARG_PTR_TO_UNINIT_MEM, 631 .arg4_type = ARG_MEM_SIZE, 632 }; 633 634 static const struct bpf_func_proto bpf_get_raw_smp_processor_id_proto = { 635 .func = bpf_get_raw_cpu_id, 636 .gpl_only = false, 637 .ret_type = RET_INTEGER, 638 }; 639 640 BPF_CALL_5(bpf_event_output_data, void *, ctx, struct bpf_map *, map, 641 u64, flags, void *, data, u64, size) 642 { 643 if (unlikely(flags & ~(BPF_F_INDEX_MASK))) 644 return -EINVAL; 645 646 return bpf_event_output(map, flags, data, size, NULL, 0, NULL); 647 } 648 649 const struct bpf_func_proto bpf_event_output_data_proto = { 650 .func = bpf_event_output_data, 651 .gpl_only = true, 652 .ret_type = RET_INTEGER, 653 .arg1_type = ARG_PTR_TO_CTX, 654 .arg2_type = ARG_CONST_MAP_PTR, 655 .arg3_type = ARG_ANYTHING, 656 .arg4_type = ARG_PTR_TO_MEM | MEM_RDONLY, 657 .arg5_type = ARG_MEM_SIZE_OR_ZERO, 658 }; 659 660 BPF_CALL_3(bpf_copy_from_user, void *, dst, u32, size, 661 const void __user *, user_ptr) 662 { 663 int ret = copy_from_user(dst, user_ptr, size); 664 665 if (unlikely(ret)) { 666 memset(dst, 0, size); 667 ret = -EFAULT; 668 } 669 670 return ret; 671 } 672 673 const struct bpf_func_proto bpf_copy_from_user_proto = { 674 .func = bpf_copy_from_user, 675 .gpl_only = false, 676 .might_sleep = true, 677 .ret_type = RET_INTEGER, 678 .arg1_type = ARG_PTR_TO_UNINIT_MEM, 679 .arg2_type = ARG_MEM_SIZE_OR_ZERO, 680 .arg3_type = ARG_ANYTHING, 681 }; 682 683 static int __bpf_copy_from_user_mm(void *dst, u32 size, 684 const void __user *user_ptr, 685 struct mm_struct *mm) 686 { 687 int ret; 688 689 ret = access_remote_vm(mm, (unsigned long)user_ptr, dst, size, 0); 690 if (ret == size) 691 return 0; 692 693 memset(dst, 0, size); 694 /* Return -EFAULT for partial read */ 695 return ret < 0 ? ret : -EFAULT; 696 } 697 698 static int __bpf_copy_from_user_mm_str(void *dst, u32 size, 699 const void __user *user_ptr, 700 struct mm_struct *mm, u64 flags) 701 { 702 int ret; 703 704 ret = copy_remote_mm_str(mm, (unsigned long)user_ptr, dst, size, 0); 705 if (ret < 0) { 706 if (flags & BPF_F_PAD_ZEROS) 707 memset(dst, 0, size); 708 return ret; 709 } 710 711 if (flags & BPF_F_PAD_ZEROS) 712 memset(dst + ret, 0, size - ret); 713 714 return ret + 1; 715 } 716 717 BPF_CALL_5(bpf_copy_from_user_task, void *, dst, u32, size, 718 const void __user *, user_ptr, struct task_struct *, tsk, u64, flags) 719 { 720 struct mm_struct *mm; 721 int ret; 722 723 /* flags is not used yet */ 724 if (unlikely(flags)) 725 return -EINVAL; 726 727 if (unlikely(!size)) 728 return 0; 729 730 mm = tsk ? get_task_mm(tsk) : NULL; 731 if (!mm) { 732 memset(dst, 0, size); 733 return -EFAULT; 734 } 735 736 ret = __bpf_copy_from_user_mm(dst, size, user_ptr, mm); 737 mmput(mm); 738 739 return ret; 740 } 741 742 const struct bpf_func_proto bpf_copy_from_user_task_proto = { 743 .func = bpf_copy_from_user_task, 744 .gpl_only = true, 745 .might_sleep = true, 746 .ret_type = RET_INTEGER, 747 .arg1_type = ARG_PTR_TO_UNINIT_MEM, 748 .arg2_type = ARG_MEM_SIZE_OR_ZERO, 749 .arg3_type = ARG_ANYTHING, 750 .arg4_type = ARG_PTR_TO_BTF_ID, 751 .arg4_btf_id = &btf_tracing_ids[BTF_TRACING_TYPE_TASK], 752 .arg5_type = ARG_ANYTHING 753 }; 754 755 BPF_CALL_2(bpf_per_cpu_ptr, const void *, ptr, u32, cpu) 756 { 757 if (cpu >= nr_cpu_ids) 758 return (unsigned long)NULL; 759 760 return (unsigned long)per_cpu_ptr((const void __percpu *)(const uintptr_t)ptr, cpu); 761 } 762 763 const struct bpf_func_proto bpf_per_cpu_ptr_proto = { 764 .func = bpf_per_cpu_ptr, 765 .gpl_only = false, 766 .ret_type = RET_PTR_TO_MEM_OR_BTF_ID | PTR_MAYBE_NULL | MEM_RDONLY, 767 .arg1_type = ARG_PTR_TO_PERCPU_BTF_ID, 768 .arg2_type = ARG_ANYTHING, 769 }; 770 771 BPF_CALL_1(bpf_this_cpu_ptr, const void *, percpu_ptr) 772 { 773 return (unsigned long)this_cpu_ptr((const void __percpu *)(const uintptr_t)percpu_ptr); 774 } 775 776 const struct bpf_func_proto bpf_this_cpu_ptr_proto = { 777 .func = bpf_this_cpu_ptr, 778 .gpl_only = false, 779 .ret_type = RET_PTR_TO_MEM_OR_BTF_ID | MEM_RDONLY, 780 .arg1_type = ARG_PTR_TO_PERCPU_BTF_ID, 781 }; 782 783 static int bpf_trace_copy_string(char *buf, void *unsafe_ptr, char fmt_ptype, 784 size_t bufsz) 785 { 786 void __user *user_ptr = (__force void __user *)unsafe_ptr; 787 788 buf[0] = 0; 789 790 switch (fmt_ptype) { 791 case 's': 792 #ifdef CONFIG_ARCH_HAS_NON_OVERLAPPING_ADDRESS_SPACE 793 if ((unsigned long)unsafe_ptr < TASK_SIZE) 794 return strncpy_from_user_nofault(buf, user_ptr, bufsz); 795 fallthrough; 796 #endif 797 case 'k': 798 return strncpy_from_kernel_nofault(buf, unsafe_ptr, bufsz); 799 case 'u': 800 return strncpy_from_user_nofault(buf, user_ptr, bufsz); 801 } 802 803 return -EINVAL; 804 } 805 806 /* Support executing three nested bprintf helper calls on a given CPU */ 807 #define MAX_BPRINTF_NEST_LEVEL 3 808 809 static DEFINE_PER_CPU(struct bpf_bprintf_buffers[MAX_BPRINTF_NEST_LEVEL], bpf_bprintf_bufs); 810 static DEFINE_PER_CPU(int, bpf_bprintf_nest_level); 811 812 int bpf_try_get_buffers(struct bpf_bprintf_buffers **bufs) 813 { 814 int nest_level; 815 816 preempt_disable(); 817 nest_level = this_cpu_inc_return(bpf_bprintf_nest_level); 818 if (WARN_ON_ONCE(nest_level > MAX_BPRINTF_NEST_LEVEL)) { 819 this_cpu_dec(bpf_bprintf_nest_level); 820 preempt_enable(); 821 return -EBUSY; 822 } 823 *bufs = this_cpu_ptr(&bpf_bprintf_bufs[nest_level - 1]); 824 825 return 0; 826 } 827 828 void bpf_put_buffers(void) 829 { 830 if (WARN_ON_ONCE(this_cpu_read(bpf_bprintf_nest_level) == 0)) 831 return; 832 this_cpu_dec(bpf_bprintf_nest_level); 833 preempt_enable(); 834 } 835 836 void bpf_bprintf_cleanup(struct bpf_bprintf_data *data) 837 { 838 if (!data->bin_args && !data->buf) 839 return; 840 bpf_put_buffers(); 841 } 842 843 /* 844 * bpf_bprintf_prepare - Generic pass on format strings for bprintf-like helpers 845 * 846 * Returns a negative value if fmt is an invalid format string or 0 otherwise. 847 * 848 * This can be used in two ways: 849 * - Format string verification only: when data->get_bin_args is false 850 * - Arguments preparation: in addition to the above verification, it writes in 851 * data->bin_args a binary representation of arguments usable by bstr_printf 852 * where pointers from BPF have been sanitized. 853 * 854 * In argument preparation mode, if 0 is returned, safe temporary buffers are 855 * allocated and bpf_bprintf_cleanup should be called to free them after use. 856 */ 857 int bpf_bprintf_prepare(const char *fmt, u32 fmt_size, const u64 *raw_args, 858 u32 num_args, struct bpf_bprintf_data *data) 859 { 860 bool get_buffers = (data->get_bin_args && num_args) || data->get_buf; 861 char *unsafe_ptr = NULL, *tmp_buf = NULL, *tmp_buf_end, *fmt_end; 862 struct bpf_bprintf_buffers *buffers = NULL; 863 size_t sizeof_cur_arg, sizeof_cur_ip; 864 int err, i, num_spec = 0; 865 u64 cur_arg; 866 char fmt_ptype, cur_ip[16], ip_spec[] = "%pXX"; 867 868 fmt_end = strnchr(fmt, fmt_size, 0); 869 if (!fmt_end) 870 return -EINVAL; 871 fmt_size = fmt_end - fmt; 872 873 if (get_buffers && bpf_try_get_buffers(&buffers)) 874 return -EBUSY; 875 876 if (data->get_bin_args) { 877 if (num_args) 878 tmp_buf = buffers->bin_args; 879 tmp_buf_end = tmp_buf + MAX_BPRINTF_BIN_ARGS; 880 data->bin_args = (u32 *)tmp_buf; 881 } 882 883 if (data->get_buf) 884 data->buf = buffers->buf; 885 886 for (i = 0; i < fmt_size; i++) { 887 unsigned char c = fmt[i]; 888 889 /* 890 * Permit bytes >= 0x80 in plain text so UTF-8 literals can pass 891 * through unchanged, while still rejecting ASCII control bytes. 892 */ 893 if (isascii(c) && !isprint(c) && !isspace(c)) { 894 err = -EINVAL; 895 goto out; 896 } 897 898 if (fmt[i] != '%') 899 continue; 900 901 if (fmt[i + 1] == '%') { 902 i++; 903 continue; 904 } 905 906 if (num_spec >= num_args) { 907 err = -EINVAL; 908 goto out; 909 } 910 911 /* The string is zero-terminated so if fmt[i] != 0, we can 912 * always access fmt[i + 1], in the worst case it will be a 0 913 */ 914 i++; 915 c = fmt[i]; 916 /* 917 * The format parser below only understands ASCII conversion 918 * specifiers and modifiers, so reject non-ASCII after '%'. 919 */ 920 if (!isascii(c)) { 921 err = -EINVAL; 922 goto out; 923 } 924 925 /* skip optional "[0 +-][num]" width formatting field */ 926 while (fmt[i] == '0' || fmt[i] == '+' || fmt[i] == '-' || 927 fmt[i] == ' ') 928 i++; 929 if (fmt[i] >= '1' && fmt[i] <= '9') { 930 i++; 931 while (fmt[i] >= '0' && fmt[i] <= '9') 932 i++; 933 } 934 935 if (fmt[i] == 'p') { 936 sizeof_cur_arg = sizeof(long); 937 938 if (fmt[i + 1] == 0 || isspace(fmt[i + 1]) || 939 ispunct(fmt[i + 1])) { 940 if (tmp_buf) 941 cur_arg = raw_args[num_spec]; 942 goto nocopy_fmt; 943 } 944 945 if ((fmt[i + 1] == 'k' || fmt[i + 1] == 'u') && 946 fmt[i + 2] == 's') { 947 fmt_ptype = fmt[i + 1]; 948 i += 2; 949 goto fmt_str; 950 } 951 952 if (fmt[i + 1] == 'K' || 953 fmt[i + 1] == 'x' || fmt[i + 1] == 's' || 954 fmt[i + 1] == 'S') { 955 if (tmp_buf) 956 cur_arg = raw_args[num_spec]; 957 i++; 958 goto nocopy_fmt; 959 } 960 961 if (fmt[i + 1] == 'B') { 962 if (tmp_buf) { 963 err = snprintf(tmp_buf, 964 (tmp_buf_end - tmp_buf), 965 "%pB", 966 (void *)(long)raw_args[num_spec]); 967 tmp_buf += (err + 1); 968 } 969 970 i++; 971 num_spec++; 972 continue; 973 } 974 975 /* only support "%pI4", "%pi4", "%pI6" and "%pi6". */ 976 if ((fmt[i + 1] != 'i' && fmt[i + 1] != 'I') || 977 (fmt[i + 2] != '4' && fmt[i + 2] != '6')) { 978 err = -EINVAL; 979 goto out; 980 } 981 982 i += 2; 983 if (!tmp_buf) 984 goto nocopy_fmt; 985 986 sizeof_cur_ip = (fmt[i] == '4') ? 4 : 16; 987 if (tmp_buf_end - tmp_buf < sizeof_cur_ip) { 988 err = -ENOSPC; 989 goto out; 990 } 991 992 unsafe_ptr = (char *)(long)raw_args[num_spec]; 993 err = copy_from_kernel_nofault(cur_ip, unsafe_ptr, 994 sizeof_cur_ip); 995 if (err < 0) 996 memset(cur_ip, 0, sizeof_cur_ip); 997 998 /* hack: bstr_printf expects IP addresses to be 999 * pre-formatted as strings, ironically, the easiest way 1000 * to do that is to call snprintf. 1001 */ 1002 ip_spec[2] = fmt[i - 1]; 1003 ip_spec[3] = fmt[i]; 1004 err = snprintf(tmp_buf, tmp_buf_end - tmp_buf, 1005 ip_spec, &cur_ip); 1006 1007 tmp_buf += err + 1; 1008 num_spec++; 1009 1010 continue; 1011 } else if (fmt[i] == 's') { 1012 fmt_ptype = fmt[i]; 1013 fmt_str: 1014 if (fmt[i + 1] != 0 && 1015 !isspace(fmt[i + 1]) && 1016 !ispunct(fmt[i + 1])) { 1017 err = -EINVAL; 1018 goto out; 1019 } 1020 1021 if (!tmp_buf) 1022 goto nocopy_fmt; 1023 1024 if (tmp_buf_end == tmp_buf) { 1025 err = -ENOSPC; 1026 goto out; 1027 } 1028 1029 unsafe_ptr = (char *)(long)raw_args[num_spec]; 1030 err = bpf_trace_copy_string(tmp_buf, unsafe_ptr, 1031 fmt_ptype, 1032 tmp_buf_end - tmp_buf); 1033 if (err < 0) { 1034 tmp_buf[0] = '\0'; 1035 err = 1; 1036 } 1037 1038 tmp_buf += err; 1039 num_spec++; 1040 1041 continue; 1042 } else if (fmt[i] == 'c') { 1043 if (!tmp_buf) 1044 goto nocopy_fmt; 1045 1046 if (tmp_buf_end == tmp_buf) { 1047 err = -ENOSPC; 1048 goto out; 1049 } 1050 1051 *tmp_buf = raw_args[num_spec]; 1052 tmp_buf++; 1053 num_spec++; 1054 1055 continue; 1056 } 1057 1058 sizeof_cur_arg = sizeof(int); 1059 1060 if (fmt[i] == 'l') { 1061 sizeof_cur_arg = sizeof(long); 1062 i++; 1063 } 1064 if (fmt[i] == 'l') { 1065 sizeof_cur_arg = sizeof(long long); 1066 i++; 1067 } 1068 1069 if (fmt[i] != 'i' && fmt[i] != 'd' && fmt[i] != 'u' && 1070 fmt[i] != 'x' && fmt[i] != 'X') { 1071 err = -EINVAL; 1072 goto out; 1073 } 1074 1075 if (tmp_buf) 1076 cur_arg = raw_args[num_spec]; 1077 nocopy_fmt: 1078 if (tmp_buf) { 1079 tmp_buf = PTR_ALIGN(tmp_buf, sizeof(u32)); 1080 if (tmp_buf_end - tmp_buf < sizeof_cur_arg) { 1081 err = -ENOSPC; 1082 goto out; 1083 } 1084 1085 if (sizeof_cur_arg == 8) { 1086 *(u32 *)tmp_buf = *(u32 *)&cur_arg; 1087 *(u32 *)(tmp_buf + 4) = *((u32 *)&cur_arg + 1); 1088 } else { 1089 *(u32 *)tmp_buf = (u32)(long)cur_arg; 1090 } 1091 tmp_buf += sizeof_cur_arg; 1092 } 1093 num_spec++; 1094 } 1095 1096 err = 0; 1097 out: 1098 if (err) 1099 bpf_bprintf_cleanup(data); 1100 return err; 1101 } 1102 1103 BPF_CALL_5(bpf_snprintf, char *, str, u32, str_size, char *, fmt, 1104 const void *, args, u32, data_len) 1105 { 1106 struct bpf_bprintf_data data = { 1107 .get_bin_args = true, 1108 }; 1109 int err, num_args; 1110 1111 if (data_len % 8 || data_len > MAX_BPRINTF_VARARGS * 8 || 1112 (data_len && !args)) 1113 return -EINVAL; 1114 num_args = data_len / 8; 1115 1116 /* ARG_PTR_TO_CONST_STR guarantees that fmt is zero-terminated so we 1117 * can safely give an unbounded size. 1118 */ 1119 err = bpf_bprintf_prepare(fmt, UINT_MAX, args, num_args, &data); 1120 if (err < 0) 1121 return err; 1122 1123 err = bstr_printf(str, str_size, fmt, data.bin_args); 1124 1125 bpf_bprintf_cleanup(&data); 1126 1127 return err + 1; 1128 } 1129 1130 const struct bpf_func_proto bpf_snprintf_proto = { 1131 .func = bpf_snprintf, 1132 .gpl_only = true, 1133 .ret_type = RET_INTEGER, 1134 .arg1_type = ARG_PTR_TO_MEM_OR_NULL | MEM_UNINIT | MEM_WRITE, 1135 .arg2_type = ARG_MEM_SIZE_OR_ZERO, 1136 .arg3_type = ARG_PTR_TO_CONST_STR, 1137 .arg4_type = ARG_PTR_TO_MEM | PTR_MAYBE_NULL | MEM_RDONLY, 1138 .arg5_type = ARG_MEM_SIZE_OR_ZERO, 1139 }; 1140 1141 static void *map_key_from_value(struct bpf_map *map, void *value, u32 *arr_idx) 1142 { 1143 if (map->map_type == BPF_MAP_TYPE_ARRAY) { 1144 struct bpf_array *array = container_of(map, struct bpf_array, map); 1145 1146 *arr_idx = ((char *)value - array->value) / array->elem_size; 1147 return arr_idx; 1148 } 1149 return (void *)value - round_up(map->key_size, 8); 1150 } 1151 1152 enum bpf_async_type { 1153 BPF_ASYNC_TYPE_TIMER = 0, 1154 BPF_ASYNC_TYPE_WQ, 1155 }; 1156 1157 enum bpf_async_op { 1158 BPF_ASYNC_START, 1159 BPF_ASYNC_CANCEL 1160 }; 1161 1162 struct bpf_async_cmd { 1163 struct llist_node node; 1164 u64 nsec; 1165 u32 mode; 1166 enum bpf_async_op op; 1167 }; 1168 1169 struct bpf_async_cb { 1170 struct bpf_map *map; 1171 struct bpf_prog *prog; 1172 void __rcu *callback_fn; 1173 void *value; 1174 struct rcu_head rcu; 1175 u64 flags; 1176 struct irq_work worker; 1177 refcount_t refcnt; 1178 enum bpf_async_type type; 1179 struct llist_head async_cmds; 1180 }; 1181 1182 /* BPF map elements can contain 'struct bpf_timer'. 1183 * Such map owns all of its BPF timers. 1184 * 'struct bpf_timer' is allocated as part of map element allocation 1185 * and it's zero initialized. 1186 * That space is used to keep 'struct bpf_async_kern'. 1187 * bpf_timer_init() allocates 'struct bpf_hrtimer', inits hrtimer, and 1188 * remembers 'struct bpf_map *' pointer it's part of. 1189 * bpf_timer_set_callback() increments prog refcnt and assign bpf callback_fn. 1190 * bpf_timer_start() arms the timer. 1191 * If user space reference to a map goes to zero at this point 1192 * ops->map_release_uref callback is responsible for cancelling the timers, 1193 * freeing their memory, and decrementing prog's refcnts. 1194 * bpf_timer_cancel() cancels the timer and decrements prog's refcnt. 1195 * Inner maps can contain bpf timers as well. ops->map_release_uref is 1196 * freeing the timers when inner map is replaced or deleted by user space. 1197 */ 1198 struct bpf_hrtimer { 1199 struct bpf_async_cb cb; 1200 struct hrtimer timer; 1201 atomic_t cancelling; 1202 }; 1203 1204 struct bpf_work { 1205 struct bpf_async_cb cb; 1206 struct work_struct work; 1207 }; 1208 1209 /* the actual struct hidden inside uapi struct bpf_timer and bpf_wq */ 1210 struct bpf_async_kern { 1211 union { 1212 struct bpf_async_cb *cb; 1213 struct bpf_hrtimer *timer; 1214 struct bpf_work *work; 1215 }; 1216 } __attribute__((aligned(8))); 1217 1218 static DEFINE_PER_CPU(struct bpf_hrtimer *, hrtimer_running); 1219 1220 static void bpf_async_refcount_put(struct bpf_async_cb *cb); 1221 1222 struct bpf_run_ctx bpf_async_run_ctx; 1223 1224 static void bpf_run_async_cb(struct bpf_prog *prog, bpf_callback_t callback_fn, 1225 struct bpf_map *map, void *key, void *value) 1226 { 1227 struct bpf_run_ctx *old_ctx = bpf_set_run_ctx(&bpf_async_run_ctx); 1228 struct bpf_timed_may_goto saved; 1229 1230 bpf_timed_may_goto_save(prog, &saved); 1231 callback_fn((u64)(long)map, (u64)(long)key, (u64)(long)value, 0, 0); 1232 bpf_timed_may_goto_restore(prog, &saved); 1233 bpf_reset_run_ctx(old_ctx); 1234 } 1235 1236 static enum hrtimer_restart bpf_timer_cb(struct hrtimer *hrtimer) 1237 { 1238 struct bpf_hrtimer *t = container_of(hrtimer, struct bpf_hrtimer, timer); 1239 struct bpf_map *map = READ_ONCE(t->cb.map); 1240 struct bpf_prog *prog = READ_ONCE(t->cb.prog); 1241 void *value = t->cb.value; 1242 bpf_callback_t callback_fn; 1243 void *key; 1244 u32 idx; 1245 1246 BTF_TYPE_EMIT(struct bpf_timer); 1247 callback_fn = rcu_dereference_check(t->cb.callback_fn, rcu_read_lock_bh_held()); 1248 if (!callback_fn || !map || !prog) 1249 goto out; 1250 1251 /* bpf_timer_cb() runs in hrtimer_run_softirq. It doesn't migrate and 1252 * cannot be preempted by another bpf_timer_cb() on the same cpu. 1253 * Remember the timer this callback is servicing to prevent 1254 * deadlock if callback_fn() calls bpf_timer_cancel() or 1255 * bpf_map_delete_elem() on the same timer. 1256 */ 1257 this_cpu_write(hrtimer_running, t); 1258 1259 key = map_key_from_value(map, value, &idx); 1260 1261 /* The verifier checked that return value is zero. */ 1262 bpf_run_async_cb(prog, callback_fn, map, key, value); 1263 1264 this_cpu_write(hrtimer_running, NULL); 1265 out: 1266 return HRTIMER_NORESTART; 1267 } 1268 1269 static void bpf_wq_work(struct work_struct *work) 1270 { 1271 struct bpf_work *w = container_of(work, struct bpf_work, work); 1272 struct bpf_async_cb *cb = &w->cb; 1273 struct bpf_prog *prog; 1274 struct bpf_map *map; 1275 bpf_callback_t callback_fn; 1276 void *value = cb->value; 1277 void *key; 1278 u32 idx; 1279 1280 BTF_TYPE_EMIT(struct bpf_wq); 1281 1282 /* keeps the program that callback_fn belongs to */ 1283 rcu_read_lock_trace(); 1284 1285 map = READ_ONCE(cb->map); 1286 callback_fn = READ_ONCE(cb->callback_fn); 1287 prog = READ_ONCE(cb->prog); 1288 if (!callback_fn || !map || !prog) 1289 goto out; 1290 1291 key = map_key_from_value(map, value, &idx); 1292 1293 migrate_disable(); 1294 1295 bpf_run_async_cb(prog, callback_fn, map, key, value); 1296 1297 migrate_enable(); 1298 out: 1299 rcu_read_unlock_trace(); 1300 } 1301 1302 static void bpf_async_cb_rcu_free(struct rcu_head *rcu) 1303 { 1304 struct bpf_async_cb *cb = container_of(rcu, struct bpf_async_cb, rcu); 1305 1306 /* 1307 * Drop the last reference to prog only after RCU GP, as set_callback() 1308 * may race with cancel_and_free() 1309 */ 1310 if (cb->prog) 1311 bpf_prog_put(cb->prog); 1312 1313 kfree_nolock(cb); 1314 } 1315 1316 /* Callback from call_rcu_tasks_trace, chains to call_rcu for final free */ 1317 static void bpf_async_cb_rcu_tasks_trace_free(struct rcu_head *rcu) 1318 { 1319 struct bpf_async_cb *cb = container_of(rcu, struct bpf_async_cb, rcu); 1320 struct bpf_hrtimer *t = container_of(cb, struct bpf_hrtimer, cb); 1321 struct bpf_work *w = container_of(cb, struct bpf_work, cb); 1322 bool retry = false; 1323 1324 /* 1325 * bpf_async_cancel_and_free() tried to cancel timer/wq, but it 1326 * could have raced with timer/wq_start. Now refcnt is zero and 1327 * srcu/rcu GP completed. Cancel timer/wq again. 1328 */ 1329 switch (cb->type) { 1330 case BPF_ASYNC_TYPE_TIMER: 1331 if (hrtimer_try_to_cancel(&t->timer) < 0) 1332 retry = true; 1333 break; 1334 case BPF_ASYNC_TYPE_WQ: 1335 if (!cancel_work(&w->work) && work_busy(&w->work)) 1336 retry = true; 1337 break; 1338 } 1339 if (retry) { 1340 /* 1341 * hrtimer or wq callback may still be running. It must be 1342 * in rcu_tasks_trace or rcu CS, so wait for GP again. 1343 * It won't retry forever, since refcnt zero prevents all 1344 * operations on timer/wq. 1345 */ 1346 call_rcu_tasks_trace(&cb->rcu, bpf_async_cb_rcu_tasks_trace_free); 1347 return; 1348 } 1349 1350 /* RCU Tasks Trace grace period implies RCU grace period. */ 1351 bpf_async_cb_rcu_free(rcu); 1352 } 1353 1354 static void worker_for_call_rcu(struct irq_work *work) 1355 { 1356 struct bpf_async_cb *cb = container_of(work, struct bpf_async_cb, worker); 1357 1358 call_rcu_tasks_trace(&cb->rcu, bpf_async_cb_rcu_tasks_trace_free); 1359 } 1360 1361 static void bpf_async_refcount_put(struct bpf_async_cb *cb) 1362 { 1363 if (!refcount_dec_and_test(&cb->refcnt)) 1364 return; 1365 1366 if (irqs_disabled()) { 1367 cb->worker = IRQ_WORK_INIT(worker_for_call_rcu); 1368 irq_work_queue(&cb->worker); 1369 } else { 1370 call_rcu_tasks_trace(&cb->rcu, bpf_async_cb_rcu_tasks_trace_free); 1371 } 1372 } 1373 1374 static void bpf_async_cancel_and_free(struct bpf_async_kern *async); 1375 static void bpf_async_irq_worker(struct irq_work *work); 1376 1377 static int __bpf_async_init(struct bpf_async_kern *async, struct bpf_map *map, u64 flags, 1378 enum bpf_async_type type) 1379 { 1380 struct bpf_async_cb *cb, *old_cb; 1381 struct bpf_hrtimer *t; 1382 struct bpf_work *w; 1383 clockid_t clockid; 1384 size_t size; 1385 1386 switch (type) { 1387 case BPF_ASYNC_TYPE_TIMER: 1388 size = sizeof(struct bpf_hrtimer); 1389 break; 1390 case BPF_ASYNC_TYPE_WQ: 1391 size = sizeof(struct bpf_work); 1392 break; 1393 default: 1394 return -EINVAL; 1395 } 1396 1397 old_cb = READ_ONCE(async->cb); 1398 if (old_cb) 1399 return -EBUSY; 1400 1401 cb = bpf_map_kmalloc_nolock(map, size, 0, map->numa_node); 1402 if (!cb) 1403 return -ENOMEM; 1404 1405 switch (type) { 1406 case BPF_ASYNC_TYPE_TIMER: 1407 clockid = flags & (MAX_CLOCKS - 1); 1408 t = (struct bpf_hrtimer *)cb; 1409 1410 atomic_set(&t->cancelling, 0); 1411 hrtimer_setup(&t->timer, bpf_timer_cb, clockid, HRTIMER_MODE_REL_SOFT); 1412 cb->value = (void *)async - map->record->timer_off; 1413 break; 1414 case BPF_ASYNC_TYPE_WQ: 1415 w = (struct bpf_work *)cb; 1416 1417 INIT_WORK(&w->work, bpf_wq_work); 1418 cb->value = (void *)async - map->record->wq_off; 1419 break; 1420 } 1421 cb->map = map; 1422 cb->prog = NULL; 1423 cb->flags = flags; 1424 cb->worker = IRQ_WORK_INIT(bpf_async_irq_worker); 1425 init_llist_head(&cb->async_cmds); 1426 refcount_set(&cb->refcnt, 1); /* map's reference */ 1427 cb->type = type; 1428 rcu_assign_pointer(cb->callback_fn, NULL); 1429 1430 old_cb = cmpxchg(&async->cb, NULL, cb); 1431 if (old_cb) { 1432 /* Lost the race to initialize this bpf_async_kern, drop the allocated object */ 1433 kfree_nolock(cb); 1434 return -EBUSY; 1435 } 1436 /* Guarantee the order between async->cb and map->usercnt. So 1437 * when there are concurrent uref release and bpf timer init, either 1438 * bpf_timer_cancel_and_free() called by uref release reads a no-NULL 1439 * timer or atomic64_read() below returns a zero usercnt. 1440 */ 1441 smp_mb(); 1442 if (!atomic64_read(&map->usercnt)) { 1443 /* maps with timers must be either held by user space 1444 * or pinned in bpffs. 1445 */ 1446 bpf_async_cancel_and_free(async); 1447 return -EPERM; 1448 } 1449 1450 return 0; 1451 } 1452 1453 BPF_CALL_3(bpf_timer_init, struct bpf_async_kern *, timer, struct bpf_map *, map, 1454 u64, flags) 1455 { 1456 clock_t clockid = flags & (MAX_CLOCKS - 1); 1457 1458 BUILD_BUG_ON(MAX_CLOCKS != 16); 1459 BUILD_BUG_ON(sizeof(struct bpf_async_kern) > sizeof(struct bpf_timer)); 1460 BUILD_BUG_ON(__alignof__(struct bpf_async_kern) != __alignof__(struct bpf_timer)); 1461 1462 if (flags >= MAX_CLOCKS || 1463 /* similar to timerfd except _ALARM variants are not supported */ 1464 (clockid != CLOCK_MONOTONIC && 1465 clockid != CLOCK_REALTIME && 1466 clockid != CLOCK_BOOTTIME)) 1467 return -EINVAL; 1468 1469 return __bpf_async_init(timer, map, flags, BPF_ASYNC_TYPE_TIMER); 1470 } 1471 1472 static const struct bpf_func_proto bpf_timer_init_proto = { 1473 .func = bpf_timer_init, 1474 .gpl_only = true, 1475 .ret_type = RET_INTEGER, 1476 .arg1_type = ARG_PTR_TO_TIMER, 1477 .arg2_type = ARG_CONST_MAP_PTR, 1478 .arg3_type = ARG_ANYTHING, 1479 }; 1480 1481 static int bpf_async_update_prog_callback(struct bpf_async_cb *cb, 1482 struct bpf_prog *prog, 1483 void *callback_fn) 1484 { 1485 struct bpf_prog *prev; 1486 1487 /* Acquire a guard reference on prog to prevent it from being freed during the loop */ 1488 if (prog) { 1489 prog = bpf_prog_inc_not_zero(prog); 1490 if (IS_ERR(prog)) 1491 return PTR_ERR(prog); 1492 } 1493 1494 do { 1495 if (prog) 1496 prog = bpf_prog_inc_not_zero(prog); 1497 prev = xchg(&cb->prog, prog); 1498 rcu_assign_pointer(cb->callback_fn, callback_fn); 1499 1500 /* 1501 * Release previous prog, make sure that if other CPU is contending, 1502 * to set bpf_prog, references are not leaked as each iteration acquires and 1503 * releases one reference. 1504 */ 1505 if (prev) 1506 bpf_prog_put(prev); 1507 1508 } while (READ_ONCE(cb->prog) != prog || 1509 (void __force *)READ_ONCE(cb->callback_fn) != callback_fn); 1510 1511 if (prog) 1512 bpf_prog_put(prog); 1513 1514 return 0; 1515 } 1516 1517 static DEFINE_PER_CPU(struct bpf_async_cb *, async_cb_running); 1518 1519 static int bpf_async_schedule_op(struct bpf_async_cb *cb, enum bpf_async_op op, 1520 u64 nsec, u32 timer_mode) 1521 { 1522 /* 1523 * Do not schedule another operation on this cpu if it's in irq_work 1524 * callback that is processing async_cmds queue. Otherwise the following 1525 * loop is possible: 1526 * bpf_timer_start() -> bpf_async_schedule_op() -> irq_work_queue(). 1527 * irqrestore -> bpf_async_irq_worker() -> tracepoint -> bpf_timer_start(). 1528 */ 1529 if (this_cpu_read(async_cb_running) == cb) { 1530 bpf_async_refcount_put(cb); 1531 return -EDEADLK; 1532 } 1533 1534 struct bpf_async_cmd *cmd = kmalloc_nolock(sizeof(*cmd), 0, NUMA_NO_NODE); 1535 1536 if (!cmd) { 1537 bpf_async_refcount_put(cb); 1538 return -ENOMEM; 1539 } 1540 init_llist_node(&cmd->node); 1541 cmd->nsec = nsec; 1542 cmd->mode = timer_mode; 1543 cmd->op = op; 1544 if (llist_add(&cmd->node, &cb->async_cmds)) 1545 irq_work_queue(&cb->worker); 1546 return 0; 1547 } 1548 1549 static int __bpf_async_set_callback(struct bpf_async_kern *async, void *callback_fn, 1550 struct bpf_prog *prog) 1551 { 1552 struct bpf_async_cb *cb; 1553 1554 cb = READ_ONCE(async->cb); 1555 if (!cb) 1556 return -EINVAL; 1557 1558 return bpf_async_update_prog_callback(cb, prog, callback_fn); 1559 } 1560 1561 BPF_CALL_3(bpf_timer_set_callback, struct bpf_async_kern *, timer, void *, callback_fn, 1562 struct bpf_prog_aux *, aux) 1563 { 1564 return __bpf_async_set_callback(timer, callback_fn, aux->prog); 1565 } 1566 1567 static const struct bpf_func_proto bpf_timer_set_callback_proto = { 1568 .func = bpf_timer_set_callback, 1569 .gpl_only = true, 1570 .ret_type = RET_INTEGER, 1571 .arg1_type = ARG_PTR_TO_TIMER, 1572 .arg2_type = ARG_PTR_TO_FUNC, 1573 .arg3_type = ARG_PTR_TO_PROG_AUX, 1574 }; 1575 1576 static bool defer_timer_wq_op(void) 1577 { 1578 return in_hardirq() || irqs_disabled(); 1579 } 1580 1581 BPF_CALL_3(bpf_timer_start, struct bpf_async_kern *, async, u64, nsecs, u64, flags) 1582 { 1583 struct bpf_hrtimer *t; 1584 u32 mode; 1585 1586 if (flags & ~(BPF_F_TIMER_ABS | BPF_F_TIMER_CPU_PIN)) 1587 return -EINVAL; 1588 1589 t = READ_ONCE(async->timer); 1590 if (!t || !READ_ONCE(t->cb.prog)) 1591 return -EINVAL; 1592 1593 if (flags & BPF_F_TIMER_ABS) 1594 mode = HRTIMER_MODE_ABS_SOFT; 1595 else 1596 mode = HRTIMER_MODE_REL_SOFT; 1597 1598 if (flags & BPF_F_TIMER_CPU_PIN) 1599 mode |= HRTIMER_MODE_PINNED; 1600 1601 /* 1602 * bpf_async_cancel_and_free() could have dropped refcnt to zero. In 1603 * such case BPF progs are not allowed to arm the timer to prevent UAF. 1604 */ 1605 if (!refcount_inc_not_zero(&t->cb.refcnt)) 1606 return -ENOENT; 1607 1608 if (!defer_timer_wq_op()) { 1609 hrtimer_start(&t->timer, ns_to_ktime(nsecs), mode); 1610 bpf_async_refcount_put(&t->cb); 1611 return 0; 1612 } else { 1613 return bpf_async_schedule_op(&t->cb, BPF_ASYNC_START, nsecs, mode); 1614 } 1615 } 1616 1617 static const struct bpf_func_proto bpf_timer_start_proto = { 1618 .func = bpf_timer_start, 1619 .gpl_only = true, 1620 .ret_type = RET_INTEGER, 1621 .arg1_type = ARG_PTR_TO_TIMER, 1622 .arg2_type = ARG_ANYTHING, 1623 .arg3_type = ARG_ANYTHING, 1624 }; 1625 1626 BPF_CALL_1(bpf_timer_cancel, struct bpf_async_kern *, async) 1627 { 1628 struct bpf_hrtimer *t, *cur_t; 1629 bool inc = false; 1630 int ret = 0; 1631 1632 if (defer_timer_wq_op()) 1633 return -EOPNOTSUPP; 1634 1635 t = READ_ONCE(async->timer); 1636 if (!t) 1637 return -EINVAL; 1638 1639 cur_t = this_cpu_read(hrtimer_running); 1640 if (cur_t == t) { 1641 /* If bpf callback_fn is trying to bpf_timer_cancel() 1642 * its own timer the hrtimer_cancel() will deadlock 1643 * since it waits for callback_fn to finish. 1644 */ 1645 return -EDEADLK; 1646 } 1647 1648 /* Only account in-flight cancellations when invoked from a timer 1649 * callback, since we want to avoid waiting only if other _callbacks_ 1650 * are waiting on us, to avoid introducing lockups. Non-callback paths 1651 * are ok, since nobody would synchronously wait for their completion. 1652 */ 1653 if (!cur_t) 1654 goto drop; 1655 atomic_inc(&t->cancelling); 1656 /* Need full barrier after relaxed atomic_inc */ 1657 smp_mb__after_atomic(); 1658 inc = true; 1659 if (atomic_read(&cur_t->cancelling)) { 1660 /* We're cancelling timer t, while some other timer callback is 1661 * attempting to cancel us. In such a case, it might be possible 1662 * that timer t belongs to the other callback, or some other 1663 * callback waiting upon it (creating transitive dependencies 1664 * upon us), and we will enter a deadlock if we continue 1665 * cancelling and waiting for it synchronously, since it might 1666 * do the same. Bail! 1667 */ 1668 atomic_dec(&t->cancelling); 1669 return -EDEADLK; 1670 } 1671 drop: 1672 bpf_async_update_prog_callback(&t->cb, NULL, NULL); 1673 /* Cancel the timer and wait for associated callback to finish 1674 * if it was running. 1675 */ 1676 ret = hrtimer_cancel(&t->timer); 1677 if (inc) 1678 atomic_dec(&t->cancelling); 1679 return ret; 1680 } 1681 1682 static const struct bpf_func_proto bpf_timer_cancel_proto = { 1683 .func = bpf_timer_cancel, 1684 .gpl_only = true, 1685 .ret_type = RET_INTEGER, 1686 .arg1_type = ARG_PTR_TO_TIMER, 1687 }; 1688 1689 static void bpf_async_process_op(struct bpf_async_cb *cb, u32 op, 1690 u64 timer_nsec, u32 timer_mode) 1691 { 1692 switch (cb->type) { 1693 case BPF_ASYNC_TYPE_TIMER: { 1694 struct bpf_hrtimer *t = container_of(cb, struct bpf_hrtimer, cb); 1695 1696 switch (op) { 1697 case BPF_ASYNC_START: 1698 hrtimer_start(&t->timer, ns_to_ktime(timer_nsec), timer_mode); 1699 break; 1700 case BPF_ASYNC_CANCEL: 1701 hrtimer_try_to_cancel(&t->timer); 1702 break; 1703 } 1704 break; 1705 } 1706 case BPF_ASYNC_TYPE_WQ: { 1707 struct bpf_work *w = container_of(cb, struct bpf_work, cb); 1708 1709 switch (op) { 1710 case BPF_ASYNC_START: 1711 schedule_work(&w->work); 1712 break; 1713 case BPF_ASYNC_CANCEL: 1714 cancel_work(&w->work); 1715 break; 1716 } 1717 break; 1718 } 1719 } 1720 bpf_async_refcount_put(cb); 1721 } 1722 1723 static void bpf_async_irq_worker(struct irq_work *work) 1724 { 1725 struct bpf_async_cb *cb = container_of(work, struct bpf_async_cb, worker); 1726 struct llist_node *pos, *n, *list; 1727 1728 list = llist_del_all(&cb->async_cmds); 1729 if (!list) 1730 return; 1731 1732 list = llist_reverse_order(list); 1733 this_cpu_write(async_cb_running, cb); 1734 llist_for_each_safe(pos, n, list) { 1735 struct bpf_async_cmd *cmd; 1736 1737 cmd = container_of(pos, struct bpf_async_cmd, node); 1738 bpf_async_process_op(cb, cmd->op, cmd->nsec, cmd->mode); 1739 kfree_nolock(cmd); 1740 } 1741 this_cpu_write(async_cb_running, NULL); 1742 } 1743 1744 static void bpf_async_cancel_and_free(struct bpf_async_kern *async) 1745 { 1746 struct bpf_async_cb *cb; 1747 1748 if (!READ_ONCE(async->cb)) 1749 return; 1750 1751 cb = xchg(&async->cb, NULL); 1752 if (!cb) 1753 return; 1754 1755 /* Callbacks that run after this see NULL and return. */ 1756 WRITE_ONCE(cb->map, NULL); 1757 bpf_async_update_prog_callback(cb, NULL, NULL); 1758 /* 1759 * No refcount_inc_not_zero(&cb->refcnt) here. Dropping the last 1760 * refcnt. Either synchronously or asynchronously in irq_work. 1761 */ 1762 1763 if (!defer_timer_wq_op()) { 1764 bpf_async_process_op(cb, BPF_ASYNC_CANCEL, 0, 0); 1765 } else { 1766 (void)bpf_async_schedule_op(cb, BPF_ASYNC_CANCEL, 0, 0); 1767 /* 1768 * bpf_async_schedule_op() either enqueues allocated cmd into llist 1769 * or fails with ENOMEM and drop the last refcnt. 1770 * This is unlikely, but safe, since bpf_async_cb_rcu_tasks_trace_free() 1771 * callback will do additional timer/wq_cancel due to races anyway. 1772 */ 1773 } 1774 } 1775 1776 /* 1777 * This function is called by map_delete/update_elem for individual element and 1778 * by ops->map_release_uref when the user space reference to a map reaches zero. 1779 */ 1780 void bpf_timer_cancel_and_free(void *val) 1781 { 1782 bpf_async_cancel_and_free(val); 1783 } 1784 1785 /* 1786 * This function is called by map_delete/update_elem for individual element and 1787 * by ops->map_release_uref when the user space reference to a map reaches zero. 1788 */ 1789 void bpf_wq_cancel_and_free(void *val) 1790 { 1791 bpf_async_cancel_and_free(val); 1792 } 1793 1794 BPF_CALL_2(bpf_kptr_xchg, void *, dst, void *, ptr) 1795 { 1796 unsigned long *kptr = dst; 1797 1798 /* This helper may be inlined by verifier. */ 1799 return xchg(kptr, (unsigned long)ptr); 1800 } 1801 1802 /* Unlike other PTR_TO_BTF_ID helpers the btf_id in bpf_kptr_xchg() 1803 * helper is determined dynamically by the verifier. Use BPF_PTR_POISON to 1804 * denote type that verifier will determine. 1805 */ 1806 static const struct bpf_func_proto bpf_kptr_xchg_proto = { 1807 .func = bpf_kptr_xchg, 1808 .gpl_only = false, 1809 .ret_type = RET_PTR_TO_BTF_ID_OR_NULL, 1810 .ret_btf_id = BPF_PTR_POISON, 1811 .arg1_type = ARG_KPTR_XCHG_DEST, 1812 .arg2_type = ARG_PTR_TO_BTF_ID_OR_NULL | OBJ_RELEASE, 1813 .arg2_btf_id = BPF_PTR_POISON, 1814 }; 1815 1816 struct bpf_dynptr_file_impl { 1817 struct freader freader; 1818 /* 64 bit offset and size overriding 32 bit ones in bpf_dynptr_kern */ 1819 u64 offset; 1820 u64 size; 1821 }; 1822 1823 /* Since the upper 8 bits of dynptr->size is reserved, the 1824 * maximum supported size is 2^24 - 1. 1825 */ 1826 #define DYNPTR_MAX_SIZE ((1UL << 24) - 1) 1827 #define DYNPTR_TYPE_SHIFT 28 1828 #define DYNPTR_SIZE_MASK 0xFFFFFF 1829 #define DYNPTR_RDONLY_BIT BIT(31) 1830 1831 bool __bpf_dynptr_is_rdonly(const struct bpf_dynptr_kern *ptr) 1832 { 1833 return ptr->size & DYNPTR_RDONLY_BIT; 1834 } 1835 1836 void bpf_dynptr_set_rdonly(struct bpf_dynptr_kern *ptr) 1837 { 1838 ptr->size |= DYNPTR_RDONLY_BIT; 1839 } 1840 1841 static void bpf_dynptr_set_type(struct bpf_dynptr_kern *ptr, enum bpf_dynptr_type type) 1842 { 1843 ptr->size |= type << DYNPTR_TYPE_SHIFT; 1844 } 1845 1846 static enum bpf_dynptr_type bpf_dynptr_get_type(const struct bpf_dynptr_kern *ptr) 1847 { 1848 return (ptr->size & ~(DYNPTR_RDONLY_BIT)) >> DYNPTR_TYPE_SHIFT; 1849 } 1850 1851 u64 __bpf_dynptr_size(const struct bpf_dynptr_kern *ptr) 1852 { 1853 if (bpf_dynptr_get_type(ptr) == BPF_DYNPTR_TYPE_FILE) { 1854 struct bpf_dynptr_file_impl *df = ptr->data; 1855 1856 return df->size; 1857 } 1858 1859 return ptr->size & DYNPTR_SIZE_MASK; 1860 } 1861 1862 static void bpf_dynptr_advance_offset(struct bpf_dynptr_kern *ptr, u64 off) 1863 { 1864 if (bpf_dynptr_get_type(ptr) == BPF_DYNPTR_TYPE_FILE) { 1865 struct bpf_dynptr_file_impl *df = ptr->data; 1866 1867 df->offset += off; 1868 return; 1869 } 1870 ptr->offset += off; 1871 } 1872 1873 static void bpf_dynptr_set_size(struct bpf_dynptr_kern *ptr, u64 new_size) 1874 { 1875 u32 metadata = ptr->size & ~DYNPTR_SIZE_MASK; 1876 1877 if (bpf_dynptr_get_type(ptr) == BPF_DYNPTR_TYPE_FILE) { 1878 struct bpf_dynptr_file_impl *df = ptr->data; 1879 1880 df->size = new_size; 1881 return; 1882 } 1883 ptr->size = (u32)new_size | metadata; 1884 } 1885 1886 int bpf_dynptr_check_size(u64 size) 1887 { 1888 return size > DYNPTR_MAX_SIZE ? -E2BIG : 0; 1889 } 1890 1891 static int bpf_file_fetch_bytes(struct bpf_dynptr_file_impl *df, u64 offset, void *buf, u64 len) 1892 { 1893 const void *ptr; 1894 1895 if (!buf) 1896 return -EINVAL; 1897 1898 df->freader.buf = buf; 1899 df->freader.buf_sz = len; 1900 ptr = freader_fetch(&df->freader, offset + df->offset, len); 1901 if (!ptr) 1902 return df->freader.err; 1903 1904 if (ptr != buf) /* Force copying into the buffer */ 1905 memcpy(buf, ptr, len); 1906 1907 return 0; 1908 } 1909 1910 void bpf_dynptr_init(struct bpf_dynptr_kern *ptr, void *data, 1911 enum bpf_dynptr_type type, u32 offset, u32 size) 1912 { 1913 ptr->data = data; 1914 ptr->offset = offset; 1915 ptr->size = size; 1916 bpf_dynptr_set_type(ptr, type); 1917 } 1918 1919 void bpf_dynptr_set_null(struct bpf_dynptr_kern *ptr) 1920 { 1921 memset(ptr, 0, sizeof(*ptr)); 1922 } 1923 1924 BPF_CALL_4(bpf_dynptr_from_mem, void *, data, u64, size, u64, flags, struct bpf_dynptr_kern *, ptr) 1925 { 1926 int err; 1927 1928 BTF_TYPE_EMIT(struct bpf_dynptr); 1929 1930 err = bpf_dynptr_check_size(size); 1931 if (err) 1932 goto error; 1933 1934 /* flags is currently unsupported */ 1935 if (flags) { 1936 err = -EINVAL; 1937 goto error; 1938 } 1939 1940 bpf_dynptr_init(ptr, data, BPF_DYNPTR_TYPE_LOCAL, 0, size); 1941 1942 return 0; 1943 1944 error: 1945 bpf_dynptr_set_null(ptr); 1946 return err; 1947 } 1948 1949 static const struct bpf_func_proto bpf_dynptr_from_mem_proto = { 1950 .func = bpf_dynptr_from_mem, 1951 .gpl_only = false, 1952 .ret_type = RET_INTEGER, 1953 .arg1_type = ARG_PTR_TO_UNINIT_MEM, 1954 .arg2_type = ARG_MEM_SIZE_OR_ZERO, 1955 .arg3_type = ARG_ANYTHING, 1956 .arg4_type = ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_LOCAL | MEM_UNINIT | MEM_WRITE, 1957 }; 1958 1959 static int __bpf_dynptr_read(void *dst, u64 len, const struct bpf_dynptr_kern *src, 1960 u64 offset, u64 flags) 1961 { 1962 enum bpf_dynptr_type type; 1963 int err; 1964 1965 if (!src->data || flags) 1966 return -EINVAL; 1967 1968 err = bpf_dynptr_check_off_len(src, offset, len); 1969 if (err) 1970 return err; 1971 1972 type = bpf_dynptr_get_type(src); 1973 1974 switch (type) { 1975 case BPF_DYNPTR_TYPE_LOCAL: 1976 case BPF_DYNPTR_TYPE_RINGBUF: 1977 /* Source and destination may possibly overlap, hence use memmove to 1978 * copy the data. E.g. bpf_dynptr_from_mem may create two dynptr 1979 * pointing to overlapping PTR_TO_MAP_VALUE regions. 1980 */ 1981 memmove(dst, src->data + src->offset + offset, len); 1982 return 0; 1983 case BPF_DYNPTR_TYPE_SKB: 1984 return __bpf_skb_load_bytes(src->data, src->offset + offset, dst, len); 1985 case BPF_DYNPTR_TYPE_XDP: 1986 return __bpf_xdp_load_bytes(src->data, src->offset + offset, dst, len); 1987 case BPF_DYNPTR_TYPE_SKB_META: 1988 memmove(dst, bpf_skb_meta_pointer(src->data, src->offset + offset), len); 1989 return 0; 1990 case BPF_DYNPTR_TYPE_FILE: 1991 return bpf_file_fetch_bytes(src->data, offset, dst, len); 1992 default: 1993 WARN_ONCE(true, "bpf_dynptr_read: unknown dynptr type %d\n", type); 1994 return -EFAULT; 1995 } 1996 } 1997 1998 BPF_CALL_5(bpf_dynptr_read, void *, dst, u64, len, const struct bpf_dynptr_kern *, src, 1999 u64, offset, u64, flags) 2000 { 2001 return __bpf_dynptr_read(dst, len, src, offset, flags); 2002 } 2003 2004 static const struct bpf_func_proto bpf_dynptr_read_proto = { 2005 .func = bpf_dynptr_read, 2006 .gpl_only = false, 2007 .ret_type = RET_INTEGER, 2008 .arg1_type = ARG_PTR_TO_UNINIT_MEM, 2009 .arg2_type = ARG_MEM_SIZE_OR_ZERO, 2010 .arg3_type = ARG_PTR_TO_DYNPTR, 2011 .arg4_type = ARG_ANYTHING, 2012 .arg5_type = ARG_ANYTHING, 2013 }; 2014 2015 int __bpf_dynptr_write(const struct bpf_dynptr_kern *dst, u64 offset, void *src, 2016 u64 len, u64 flags) 2017 { 2018 enum bpf_dynptr_type type; 2019 int err; 2020 2021 if (!dst->data || __bpf_dynptr_is_rdonly(dst)) 2022 return -EINVAL; 2023 2024 err = bpf_dynptr_check_off_len(dst, offset, len); 2025 if (err) 2026 return err; 2027 2028 type = bpf_dynptr_get_type(dst); 2029 2030 switch (type) { 2031 case BPF_DYNPTR_TYPE_LOCAL: 2032 case BPF_DYNPTR_TYPE_RINGBUF: 2033 if (flags) 2034 return -EINVAL; 2035 /* Source and destination may possibly overlap, hence use memmove to 2036 * copy the data. E.g. bpf_dynptr_from_mem may create two dynptr 2037 * pointing to overlapping PTR_TO_MAP_VALUE regions. 2038 */ 2039 memmove(dst->data + dst->offset + offset, src, len); 2040 return 0; 2041 case BPF_DYNPTR_TYPE_SKB: 2042 return __bpf_skb_store_bytes(dst->data, dst->offset + offset, src, len, 2043 flags); 2044 case BPF_DYNPTR_TYPE_XDP: 2045 if (flags) 2046 return -EINVAL; 2047 return __bpf_xdp_store_bytes(dst->data, dst->offset + offset, src, len); 2048 case BPF_DYNPTR_TYPE_SKB_META: 2049 return __bpf_skb_meta_store_bytes(dst->data, dst->offset + offset, src, 2050 len, flags); 2051 default: 2052 WARN_ONCE(true, "bpf_dynptr_write: unknown dynptr type %d\n", type); 2053 return -EFAULT; 2054 } 2055 } 2056 2057 BPF_CALL_5(bpf_dynptr_write, const struct bpf_dynptr_kern *, dst, u64, offset, void *, src, 2058 u64, len, u64, flags) 2059 { 2060 return __bpf_dynptr_write(dst, offset, src, len, flags); 2061 } 2062 2063 static const struct bpf_func_proto bpf_dynptr_write_proto = { 2064 .func = bpf_dynptr_write, 2065 .gpl_only = false, 2066 .ret_type = RET_INTEGER, 2067 .arg1_type = ARG_PTR_TO_DYNPTR, 2068 .arg2_type = ARG_ANYTHING, 2069 .arg3_type = ARG_PTR_TO_MEM | MEM_RDONLY, 2070 .arg4_type = ARG_MEM_SIZE_OR_ZERO, 2071 .arg5_type = ARG_ANYTHING, 2072 }; 2073 2074 BPF_CALL_3(bpf_dynptr_data, const struct bpf_dynptr_kern *, ptr, u64, offset, u64, len) 2075 { 2076 enum bpf_dynptr_type type; 2077 int err; 2078 2079 if (!ptr->data) 2080 return 0; 2081 2082 err = bpf_dynptr_check_off_len(ptr, offset, len); 2083 if (err) 2084 return 0; 2085 2086 if (__bpf_dynptr_is_rdonly(ptr)) 2087 return 0; 2088 2089 type = bpf_dynptr_get_type(ptr); 2090 2091 switch (type) { 2092 case BPF_DYNPTR_TYPE_LOCAL: 2093 case BPF_DYNPTR_TYPE_RINGBUF: 2094 return (unsigned long)(ptr->data + ptr->offset + offset); 2095 case BPF_DYNPTR_TYPE_SKB: 2096 case BPF_DYNPTR_TYPE_XDP: 2097 case BPF_DYNPTR_TYPE_SKB_META: 2098 /* skb and xdp dynptrs should use bpf_dynptr_slice / bpf_dynptr_slice_rdwr */ 2099 return 0; 2100 default: 2101 WARN_ONCE(true, "bpf_dynptr_data: unknown dynptr type %d\n", type); 2102 return 0; 2103 } 2104 } 2105 2106 static const struct bpf_func_proto bpf_dynptr_data_proto = { 2107 .func = bpf_dynptr_data, 2108 .gpl_only = false, 2109 .ret_type = RET_PTR_TO_DYNPTR_MEM_OR_NULL, 2110 .arg1_type = ARG_PTR_TO_DYNPTR, 2111 .arg2_type = ARG_ANYTHING, 2112 .arg3_type = ARG_CONST_ALLOC_SIZE_OR_ZERO, 2113 }; 2114 2115 const struct bpf_func_proto bpf_get_current_task_proto __weak; 2116 const struct bpf_func_proto bpf_get_current_task_btf_proto __weak; 2117 const struct bpf_func_proto bpf_probe_read_user_proto __weak; 2118 const struct bpf_func_proto bpf_probe_read_user_str_proto __weak; 2119 const struct bpf_func_proto bpf_probe_read_kernel_proto __weak; 2120 const struct bpf_func_proto bpf_probe_read_kernel_str_proto __weak; 2121 const struct bpf_func_proto bpf_task_pt_regs_proto __weak; 2122 const struct bpf_func_proto bpf_perf_event_read_proto __weak; 2123 const struct bpf_func_proto bpf_send_signal_proto __weak; 2124 const struct bpf_func_proto bpf_send_signal_thread_proto __weak; 2125 const struct bpf_func_proto bpf_get_task_stack_sleepable_proto __weak; 2126 const struct bpf_func_proto bpf_get_task_stack_proto __weak; 2127 const struct bpf_func_proto bpf_get_branch_snapshot_proto __weak; 2128 2129 const struct bpf_func_proto * 2130 bpf_base_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog) 2131 { 2132 switch (func_id) { 2133 case BPF_FUNC_map_lookup_elem: 2134 return &bpf_map_lookup_elem_proto; 2135 case BPF_FUNC_map_update_elem: 2136 return &bpf_map_update_elem_proto; 2137 case BPF_FUNC_map_delete_elem: 2138 return &bpf_map_delete_elem_proto; 2139 case BPF_FUNC_map_push_elem: 2140 return &bpf_map_push_elem_proto; 2141 case BPF_FUNC_map_pop_elem: 2142 return &bpf_map_pop_elem_proto; 2143 case BPF_FUNC_map_peek_elem: 2144 return &bpf_map_peek_elem_proto; 2145 case BPF_FUNC_map_lookup_percpu_elem: 2146 return &bpf_map_lookup_percpu_elem_proto; 2147 case BPF_FUNC_get_prandom_u32: 2148 return &bpf_get_prandom_u32_proto; 2149 case BPF_FUNC_get_smp_processor_id: 2150 return &bpf_get_raw_smp_processor_id_proto; 2151 case BPF_FUNC_get_numa_node_id: 2152 return &bpf_get_numa_node_id_proto; 2153 case BPF_FUNC_tail_call: 2154 return &bpf_tail_call_proto; 2155 case BPF_FUNC_ktime_get_ns: 2156 return &bpf_ktime_get_ns_proto; 2157 case BPF_FUNC_ktime_get_boot_ns: 2158 return &bpf_ktime_get_boot_ns_proto; 2159 case BPF_FUNC_ktime_get_tai_ns: 2160 return &bpf_ktime_get_tai_ns_proto; 2161 case BPF_FUNC_ringbuf_output: 2162 return &bpf_ringbuf_output_proto; 2163 case BPF_FUNC_ringbuf_reserve: 2164 return &bpf_ringbuf_reserve_proto; 2165 case BPF_FUNC_ringbuf_submit: 2166 return &bpf_ringbuf_submit_proto; 2167 case BPF_FUNC_ringbuf_discard: 2168 return &bpf_ringbuf_discard_proto; 2169 case BPF_FUNC_ringbuf_query: 2170 return &bpf_ringbuf_query_proto; 2171 case BPF_FUNC_strncmp: 2172 return &bpf_strncmp_proto; 2173 case BPF_FUNC_strtol: 2174 return &bpf_strtol_proto; 2175 case BPF_FUNC_strtoul: 2176 return &bpf_strtoul_proto; 2177 case BPF_FUNC_get_current_pid_tgid: 2178 return &bpf_get_current_pid_tgid_proto; 2179 case BPF_FUNC_get_ns_current_pid_tgid: 2180 return &bpf_get_ns_current_pid_tgid_proto; 2181 case BPF_FUNC_get_current_uid_gid: 2182 return &bpf_get_current_uid_gid_proto; 2183 default: 2184 break; 2185 } 2186 2187 if (!bpf_token_capable(prog->aux->token, CAP_BPF)) 2188 return NULL; 2189 2190 switch (func_id) { 2191 case BPF_FUNC_spin_lock: 2192 return &bpf_spin_lock_proto; 2193 case BPF_FUNC_spin_unlock: 2194 return &bpf_spin_unlock_proto; 2195 case BPF_FUNC_jiffies64: 2196 return &bpf_jiffies64_proto; 2197 case BPF_FUNC_timer_init: 2198 return &bpf_timer_init_proto; 2199 case BPF_FUNC_timer_set_callback: 2200 return &bpf_timer_set_callback_proto; 2201 case BPF_FUNC_timer_start: 2202 return &bpf_timer_start_proto; 2203 case BPF_FUNC_timer_cancel: 2204 return &bpf_timer_cancel_proto; 2205 case BPF_FUNC_kptr_xchg: 2206 return &bpf_kptr_xchg_proto; 2207 case BPF_FUNC_for_each_map_elem: 2208 return &bpf_for_each_map_elem_proto; 2209 case BPF_FUNC_loop: 2210 return &bpf_loop_proto; 2211 case BPF_FUNC_user_ringbuf_drain: 2212 return &bpf_user_ringbuf_drain_proto; 2213 case BPF_FUNC_ringbuf_reserve_dynptr: 2214 return &bpf_ringbuf_reserve_dynptr_proto; 2215 case BPF_FUNC_ringbuf_submit_dynptr: 2216 return &bpf_ringbuf_submit_dynptr_proto; 2217 case BPF_FUNC_ringbuf_discard_dynptr: 2218 return &bpf_ringbuf_discard_dynptr_proto; 2219 case BPF_FUNC_dynptr_from_mem: 2220 return &bpf_dynptr_from_mem_proto; 2221 case BPF_FUNC_dynptr_read: 2222 return &bpf_dynptr_read_proto; 2223 case BPF_FUNC_dynptr_write: 2224 return &bpf_dynptr_write_proto; 2225 case BPF_FUNC_dynptr_data: 2226 return &bpf_dynptr_data_proto; 2227 #ifdef CONFIG_CGROUPS 2228 case BPF_FUNC_cgrp_storage_get: 2229 return &bpf_cgrp_storage_get_proto; 2230 case BPF_FUNC_cgrp_storage_delete: 2231 return &bpf_cgrp_storage_delete_proto; 2232 case BPF_FUNC_get_current_cgroup_id: 2233 return &bpf_get_current_cgroup_id_proto; 2234 case BPF_FUNC_get_current_ancestor_cgroup_id: 2235 return &bpf_get_current_ancestor_cgroup_id_proto; 2236 case BPF_FUNC_current_task_under_cgroup: 2237 return &bpf_current_task_under_cgroup_proto; 2238 #endif 2239 #ifdef CONFIG_CGROUP_NET_CLASSID 2240 case BPF_FUNC_get_cgroup_classid: 2241 return &bpf_get_cgroup_classid_curr_proto; 2242 #endif 2243 case BPF_FUNC_task_storage_get: 2244 return &bpf_task_storage_get_proto; 2245 case BPF_FUNC_task_storage_delete: 2246 return &bpf_task_storage_delete_proto; 2247 default: 2248 break; 2249 } 2250 2251 if (!bpf_token_capable(prog->aux->token, CAP_PERFMON)) 2252 return NULL; 2253 2254 switch (func_id) { 2255 case BPF_FUNC_trace_printk: 2256 return bpf_get_trace_printk_proto(); 2257 case BPF_FUNC_get_current_task: 2258 return &bpf_get_current_task_proto; 2259 case BPF_FUNC_get_current_task_btf: 2260 return &bpf_get_current_task_btf_proto; 2261 case BPF_FUNC_get_current_comm: 2262 return &bpf_get_current_comm_proto; 2263 case BPF_FUNC_probe_read_user: 2264 return &bpf_probe_read_user_proto; 2265 case BPF_FUNC_probe_read_kernel: 2266 return security_locked_down(LOCKDOWN_BPF_READ_KERNEL) < 0 ? 2267 NULL : &bpf_probe_read_kernel_proto; 2268 case BPF_FUNC_probe_read_user_str: 2269 return &bpf_probe_read_user_str_proto; 2270 case BPF_FUNC_probe_read_kernel_str: 2271 return security_locked_down(LOCKDOWN_BPF_READ_KERNEL) < 0 ? 2272 NULL : &bpf_probe_read_kernel_str_proto; 2273 case BPF_FUNC_copy_from_user: 2274 return &bpf_copy_from_user_proto; 2275 case BPF_FUNC_copy_from_user_task: 2276 return &bpf_copy_from_user_task_proto; 2277 case BPF_FUNC_snprintf_btf: 2278 return &bpf_snprintf_btf_proto; 2279 case BPF_FUNC_snprintf: 2280 return &bpf_snprintf_proto; 2281 case BPF_FUNC_task_pt_regs: 2282 return &bpf_task_pt_regs_proto; 2283 case BPF_FUNC_trace_vprintk: 2284 return bpf_get_trace_vprintk_proto(); 2285 case BPF_FUNC_perf_event_read_value: 2286 return bpf_get_perf_event_read_value_proto(); 2287 case BPF_FUNC_perf_event_read: 2288 return &bpf_perf_event_read_proto; 2289 case BPF_FUNC_send_signal: 2290 return &bpf_send_signal_proto; 2291 case BPF_FUNC_send_signal_thread: 2292 return &bpf_send_signal_thread_proto; 2293 case BPF_FUNC_get_task_stack: 2294 return prog->sleepable ? &bpf_get_task_stack_sleepable_proto 2295 : &bpf_get_task_stack_proto; 2296 case BPF_FUNC_get_branch_snapshot: 2297 return &bpf_get_branch_snapshot_proto; 2298 case BPF_FUNC_find_vma: 2299 return &bpf_find_vma_proto; 2300 case BPF_FUNC_per_cpu_ptr: 2301 return &bpf_per_cpu_ptr_proto; 2302 case BPF_FUNC_this_cpu_ptr: 2303 return &bpf_this_cpu_ptr_proto; 2304 default: 2305 return NULL; 2306 } 2307 } 2308 EXPORT_SYMBOL_GPL(bpf_base_func_proto); 2309 2310 void bpf_list_head_free(const struct btf_field *field, void *list_head, 2311 struct bpf_spin_lock *spin_lock) 2312 { 2313 struct list_head *head = list_head, drain, *pos, *n; 2314 unsigned long flags; 2315 2316 BUILD_BUG_ON(sizeof(struct list_head) > sizeof(struct bpf_list_head)); 2317 BUILD_BUG_ON(__alignof__(struct list_head) > __alignof__(struct bpf_list_head)); 2318 INIT_LIST_HEAD(&drain); 2319 2320 /* Do the actual list draining outside the lock to not hold the lock for 2321 * too long, and also prevent deadlocks if tracing programs end up 2322 * executing on entry/exit of functions called inside the critical 2323 * section, and end up doing map ops that call bpf_list_head_free for 2324 * the same map value again. 2325 */ 2326 local_irq_save(flags); 2327 __bpf_spin_lock(spin_lock); 2328 if (!head->next || list_empty(head)) 2329 goto unlock; 2330 list_for_each_safe(pos, n, head) { 2331 struct bpf_list_node_kern *node; 2332 2333 node = container_of(pos, struct bpf_list_node_kern, list_head); 2334 WRITE_ONCE(node->owner, BPF_PTR_POISON); 2335 list_move_tail(pos, &drain); 2336 } 2337 unlock: 2338 INIT_LIST_HEAD(head); 2339 __bpf_spin_unlock(spin_lock); 2340 local_irq_restore(flags); 2341 2342 while (!list_empty(&drain)) { 2343 struct bpf_list_node_kern *node; 2344 2345 pos = drain.next; 2346 node = container_of(pos, struct bpf_list_node_kern, list_head); 2347 list_del_init(pos); 2348 /* Ensure __bpf_list_add() sees the node as unlinked. */ 2349 smp_store_release(&node->owner, NULL); 2350 /* The contained type can also have resources, including a 2351 * bpf_list_head which needs to be freed. 2352 */ 2353 __bpf_obj_drop_impl((char *)pos - field->graph_root.node_offset, 2354 field->graph_root.value_rec, false); 2355 } 2356 } 2357 2358 /* Like rbtree_postorder_for_each_entry_safe, but 'pos' and 'n' are 2359 * 'rb_node *', so field name of rb_node within containing struct is not 2360 * needed. 2361 * 2362 * Since bpf_rb_tree's node type has a corresponding struct btf_field with 2363 * graph_root.node_offset, it's not necessary to know field name 2364 * or type of node struct 2365 */ 2366 #define bpf_rbtree_postorder_for_each_entry_safe(pos, n, root) \ 2367 for (pos = rb_first_postorder(root); \ 2368 pos && ({ n = rb_next_postorder(pos); 1; }); \ 2369 pos = n) 2370 2371 void bpf_rb_root_free(const struct btf_field *field, void *rb_root, 2372 struct bpf_spin_lock *spin_lock) 2373 { 2374 struct rb_root_cached orig_root, *root = rb_root; 2375 struct bpf_rb_node_kern *node; 2376 struct rb_node *pos, *n; 2377 unsigned long flags; 2378 void *obj; 2379 2380 BUILD_BUG_ON(sizeof(struct rb_root_cached) > sizeof(struct bpf_rb_root)); 2381 BUILD_BUG_ON(__alignof__(struct rb_root_cached) > __alignof__(struct bpf_rb_root)); 2382 2383 local_irq_save(flags); 2384 __bpf_spin_lock(spin_lock); 2385 orig_root = *root; 2386 bpf_rbtree_postorder_for_each_entry_safe(pos, n, &orig_root.rb_root) { 2387 node = rb_entry(pos, struct bpf_rb_node_kern, rb_node); 2388 WRITE_ONCE(node->owner, BPF_PTR_POISON); 2389 } 2390 *root = RB_ROOT_CACHED; 2391 __bpf_spin_unlock(spin_lock); 2392 local_irq_restore(flags); 2393 2394 bpf_rbtree_postorder_for_each_entry_safe(pos, n, &orig_root.rb_root) { 2395 obj = pos; 2396 obj -= field->graph_root.node_offset; 2397 node = rb_entry(pos, struct bpf_rb_node_kern, rb_node); 2398 RB_CLEAR_NODE(pos); 2399 /* Ensure __bpf_rbtree_add() sees the node as unlinked. */ 2400 smp_store_release(&node->owner, NULL); 2401 __bpf_obj_drop_impl(obj, field->graph_root.value_rec, false); 2402 } 2403 } 2404 2405 __bpf_kfunc_start_defs(); 2406 2407 /** 2408 * bpf_obj_new() - allocate an object described by program BTF 2409 * @local_type_id__k: type ID in program BTF 2410 * @meta: verifier-supplied struct metadata 2411 * 2412 * Allocate an object of the type identified by @local_type_id__k and 2413 * initialize its special fields. BPF programs can use 2414 * bpf_core_type_id_local() to provide @local_type_id__k. The verifier 2415 * rewrites @meta; BPF programs do not set it. 2416 * 2417 * Return: Pointer to the allocated object, or %NULL on failure. 2418 */ 2419 __bpf_kfunc void *bpf_obj_new(u64 local_type_id__k, struct btf_struct_meta *meta) 2420 { 2421 u64 size = local_type_id__k; 2422 void *p; 2423 2424 p = bpf_mem_alloc(&bpf_global_ma, size); 2425 if (!p) 2426 return NULL; 2427 if (meta) 2428 bpf_obj_init(meta->record, p); 2429 2430 return p; 2431 } 2432 2433 __bpf_kfunc void *bpf_obj_new_impl(u64 local_type_id__k, void *meta__ign) 2434 { 2435 return bpf_obj_new(local_type_id__k, meta__ign); 2436 } 2437 2438 /** 2439 * bpf_percpu_obj_new() - allocate a percpu object described by program BTF 2440 * @local_type_id__k: type ID in program BTF 2441 * @meta: verifier-supplied struct metadata 2442 * 2443 * Allocate a percpu object of the type identified by @local_type_id__k. BPF 2444 * programs can use bpf_core_type_id_local() to provide @local_type_id__k. 2445 * The verifier rewrites @meta; BPF programs do not set it. 2446 * 2447 * Return: Pointer to the allocated percpu object, or %NULL on failure. 2448 */ 2449 __bpf_kfunc void *bpf_percpu_obj_new(u64 local_type_id__k, struct btf_struct_meta *meta) 2450 { 2451 u64 size = local_type_id__k; 2452 2453 /* The verifier has ensured that meta must be NULL */ 2454 return bpf_mem_alloc(&bpf_global_percpu_ma, size); 2455 } 2456 2457 __bpf_kfunc void *bpf_percpu_obj_new_impl(u64 local_type_id__k, void *meta__ign) 2458 { 2459 return bpf_percpu_obj_new(local_type_id__k, meta__ign); 2460 } 2461 2462 /* Must be called under migrate_disable(), as required by bpf_mem_free */ 2463 void __bpf_obj_drop_impl(void *p, const struct btf_record *rec, bool percpu) 2464 { 2465 struct bpf_mem_alloc *ma; 2466 2467 if (rec && rec->refcount_off >= 0 && 2468 !refcount_dec_and_test((refcount_t *)(p + rec->refcount_off))) { 2469 /* Object is refcounted and refcount_dec didn't result in 0 2470 * refcount. Return without freeing the object 2471 */ 2472 return; 2473 } 2474 2475 if (rec) 2476 bpf_obj_free_fields(rec, p); 2477 2478 if (percpu) 2479 ma = &bpf_global_percpu_ma; 2480 else 2481 ma = &bpf_global_ma; 2482 bpf_mem_free_rcu(ma, p); 2483 } 2484 2485 /** 2486 * bpf_obj_drop() - drop a previously allocated object 2487 * @p__alloc: object to free 2488 * @meta: verifier-supplied struct metadata 2489 * 2490 * Destroy special fields in @p__alloc as needed and free the object. The 2491 * verifier rewrites @meta; BPF programs do not set it. 2492 */ 2493 __bpf_kfunc void bpf_obj_drop(void *p__alloc, struct btf_struct_meta *meta) 2494 { 2495 void *p = p__alloc; 2496 2497 __bpf_obj_drop_impl(p, meta ? meta->record : NULL, false); 2498 } 2499 2500 __bpf_kfunc void bpf_obj_drop_impl(void *p__alloc, void *meta__ign) 2501 { 2502 return bpf_obj_drop(p__alloc, meta__ign); 2503 } 2504 2505 /** 2506 * bpf_percpu_obj_drop() - drop a previously allocated percpu object 2507 * @p__alloc: percpu object to free 2508 * @meta: verifier-supplied struct metadata 2509 * 2510 * Free @p__alloc. The verifier rewrites @meta; BPF programs do not set it. 2511 */ 2512 __bpf_kfunc void bpf_percpu_obj_drop(void *p__alloc, struct btf_struct_meta *meta) 2513 { 2514 /* The verifier has ensured that meta must be NULL */ 2515 bpf_mem_free_rcu(&bpf_global_percpu_ma, p__alloc); 2516 } 2517 2518 __bpf_kfunc void bpf_percpu_obj_drop_impl(void *p__alloc, void *meta__ign) 2519 { 2520 bpf_percpu_obj_drop(p__alloc, meta__ign); 2521 } 2522 2523 /** 2524 * bpf_refcount_acquire() - turn a local kptr into an owning reference 2525 * @p__refcounted_kptr: non-owning local kptr 2526 * @meta: verifier-supplied struct metadata 2527 * 2528 * Increment the refcount for @p__refcounted_kptr. The verifier rewrites 2529 * @meta; BPF programs do not set it. 2530 * 2531 * Return: Owning reference to @p__refcounted_kptr, or %NULL on failure. 2532 */ 2533 __bpf_kfunc void *bpf_refcount_acquire(void *p__refcounted_kptr, struct btf_struct_meta *meta) 2534 { 2535 struct bpf_refcount *ref; 2536 2537 /* Could just cast directly to refcount_t *, but need some code using 2538 * bpf_refcount type so that it is emitted in vmlinux BTF 2539 */ 2540 ref = (struct bpf_refcount *)(p__refcounted_kptr + meta->record->refcount_off); 2541 if (!refcount_inc_not_zero((refcount_t *)ref)) 2542 return NULL; 2543 2544 /* Verifier strips KF_RET_NULL if input is owned ref, see is_kfunc_ret_null 2545 * in verifier.c 2546 */ 2547 return (void *)p__refcounted_kptr; 2548 } 2549 2550 __bpf_kfunc void *bpf_refcount_acquire_impl(void *p__refcounted_kptr, void *meta__ign) 2551 { 2552 return bpf_refcount_acquire(p__refcounted_kptr, meta__ign); 2553 } 2554 2555 static int __bpf_list_add(struct bpf_list_node_kern *node, 2556 struct bpf_list_head *head, 2557 struct list_head **prev_ptr, 2558 struct btf_record *rec, u64 off) 2559 { 2560 struct list_head *n = &node->list_head, *h = (void *)head; 2561 struct list_head *prev; 2562 2563 /* If list_head was 0-initialized by map, bpf_obj_init_field wasn't 2564 * called on its fields, so init here 2565 */ 2566 if (unlikely(!h->next)) 2567 INIT_LIST_HEAD(h); 2568 2569 prev = *prev_ptr; 2570 2571 /* When prev is not the list head, it must be a node in this list. */ 2572 if (prev != h) { 2573 struct bpf_list_node_kern *prev_kn = 2574 container_of(prev, struct bpf_list_node_kern, list_head); 2575 2576 if (unlikely(READ_ONCE(prev_kn->owner) != head)) 2577 goto fail; 2578 } 2579 2580 /* node->owner != NULL implies !list_empty(n), no need to separately 2581 * check the latter 2582 */ 2583 if (cmpxchg(&node->owner, NULL, BPF_PTR_POISON)) 2584 goto fail; 2585 2586 list_add(n, prev); 2587 WRITE_ONCE(node->owner, head); 2588 return 0; 2589 2590 fail: 2591 /* Only called from BPF prog, no need to migrate_disable */ 2592 __bpf_obj_drop_impl((void *)n - off, rec, false); 2593 return -EINVAL; 2594 } 2595 2596 /** 2597 * bpf_list_push_front() - add a node to the front of a BPF linked list 2598 * @head: list head 2599 * @node: node to insert 2600 * @meta: verifier-supplied struct metadata 2601 * @off: verifier-supplied offset of @node within the containing object 2602 * 2603 * Insert @node at the front of @head. The verifier rewrites @meta and @off; 2604 * BPF programs do not set them. 2605 * 2606 * Return: 0 on success, or %-EINVAL if @node is already linked. 2607 */ 2608 __bpf_kfunc int bpf_list_push_front(struct bpf_list_head *head, 2609 struct bpf_list_node *node, 2610 struct btf_struct_meta *meta, 2611 u64 off) 2612 { 2613 struct bpf_list_node_kern *n = (void *)node; 2614 struct list_head *h = (void *)head; 2615 2616 return __bpf_list_add(n, head, &h, meta ? meta->record : NULL, off); 2617 } 2618 2619 __bpf_kfunc int bpf_list_push_front_impl(struct bpf_list_head *head, 2620 struct bpf_list_node *node, 2621 void *meta__ign, u64 off) 2622 { 2623 return bpf_list_push_front(head, node, meta__ign, off); 2624 } 2625 2626 /** 2627 * bpf_list_push_back() - add a node to the back of a BPF linked list 2628 * @head: list head 2629 * @node: node to insert 2630 * @meta: verifier-supplied struct metadata 2631 * @off: verifier-supplied offset of @node within the containing object 2632 * 2633 * Insert @node at the back of @head. The verifier rewrites @meta and @off; 2634 * BPF programs do not set them. 2635 * 2636 * Return: 0 on success, or %-EINVAL if @node is already linked. 2637 */ 2638 __bpf_kfunc int bpf_list_push_back(struct bpf_list_head *head, 2639 struct bpf_list_node *node, 2640 struct btf_struct_meta *meta, 2641 u64 off) 2642 { 2643 struct bpf_list_node_kern *n = (void *)node; 2644 struct list_head *h = (void *)head; 2645 2646 return __bpf_list_add(n, head, &h->prev, meta ? meta->record : NULL, off); 2647 } 2648 2649 __bpf_kfunc int bpf_list_push_back_impl(struct bpf_list_head *head, 2650 struct bpf_list_node *node, 2651 void *meta__ign, u64 off) 2652 { 2653 return bpf_list_push_back(head, node, meta__ign, off); 2654 } 2655 2656 __bpf_kfunc int bpf_list_add(struct bpf_list_head *head, struct bpf_list_node *new, 2657 struct bpf_list_node *prev__nonown_allowed, 2658 struct btf_struct_meta *meta, u64 off) 2659 { 2660 struct bpf_list_node_kern *n = (void *)new, *p = (void *)prev__nonown_allowed; 2661 struct list_head *prev_ptr = &p->list_head; 2662 2663 return __bpf_list_add(n, head, &prev_ptr, meta ? meta->record : NULL, off); 2664 } 2665 2666 static struct bpf_list_node *__bpf_list_del(struct bpf_list_head *head, 2667 struct list_head *n) 2668 { 2669 struct list_head *h = (void *)head; 2670 struct bpf_list_node_kern *node; 2671 2672 /* If list_head was 0-initialized by map, bpf_obj_init_field wasn't 2673 * called on its fields, so init here 2674 */ 2675 if (unlikely(!h->next)) { 2676 INIT_LIST_HEAD(h); 2677 return NULL; 2678 } 2679 if (list_empty(h)) 2680 return NULL; 2681 2682 node = container_of(n, struct bpf_list_node_kern, list_head); 2683 if (unlikely(READ_ONCE(node->owner) != head)) 2684 return NULL; 2685 2686 list_del_init(n); 2687 /* Ensure __bpf_list_add() sees the node as unlinked. */ 2688 smp_store_release(&node->owner, NULL); 2689 return (struct bpf_list_node *)n; 2690 } 2691 2692 __bpf_kfunc struct bpf_list_node *bpf_list_pop_front(struct bpf_list_head *head) 2693 { 2694 struct list_head *h = (void *)head; 2695 2696 return __bpf_list_del(head, h->next); 2697 } 2698 2699 __bpf_kfunc struct bpf_list_node *bpf_list_pop_back(struct bpf_list_head *head) 2700 { 2701 struct list_head *h = (void *)head; 2702 2703 return __bpf_list_del(head, h->prev); 2704 } 2705 2706 __bpf_kfunc struct bpf_list_node *bpf_list_del(struct bpf_list_head *head, 2707 struct bpf_list_node *node__nonown_allowed) 2708 { 2709 struct bpf_list_node_kern *kn = (void *)node__nonown_allowed; 2710 2711 /* verifier guarantees node is a list node rather than list head */ 2712 return __bpf_list_del(head, &kn->list_head); 2713 } 2714 2715 __bpf_kfunc struct bpf_list_node *bpf_list_front(struct bpf_list_head *head) 2716 { 2717 struct list_head *h = (struct list_head *)head; 2718 2719 if (list_empty(h) || unlikely(!h->next)) 2720 return NULL; 2721 2722 return (struct bpf_list_node *)h->next; 2723 } 2724 2725 __bpf_kfunc struct bpf_list_node *bpf_list_back(struct bpf_list_head *head) 2726 { 2727 struct list_head *h = (struct list_head *)head; 2728 2729 if (list_empty(h) || unlikely(!h->next)) 2730 return NULL; 2731 2732 return (struct bpf_list_node *)h->prev; 2733 } 2734 2735 __bpf_kfunc bool bpf_list_is_first(struct bpf_list_head *head, 2736 struct bpf_list_node *node__nonown_allowed) 2737 { 2738 struct list_head *h = (struct list_head *)head; 2739 struct bpf_list_node_kern *kn = (struct bpf_list_node_kern *)node__nonown_allowed; 2740 2741 if (READ_ONCE(kn->owner) != head) 2742 return false; 2743 2744 return list_is_first(&kn->list_head, h); 2745 } 2746 2747 __bpf_kfunc bool bpf_list_is_last(struct bpf_list_head *head, 2748 struct bpf_list_node *node__nonown_allowed) 2749 { 2750 struct list_head *h = (struct list_head *)head; 2751 struct bpf_list_node_kern *kn = (struct bpf_list_node_kern *)node__nonown_allowed; 2752 2753 if (READ_ONCE(kn->owner) != head) 2754 return false; 2755 2756 return list_is_last(&kn->list_head, h); 2757 } 2758 2759 __bpf_kfunc bool bpf_list_empty(struct bpf_list_head *head) 2760 { 2761 struct list_head *h = (struct list_head *)head; 2762 2763 /* If list_head was 0-initialized by map, bpf_obj_init_field wasn't 2764 * called on its fields, so init here 2765 */ 2766 if (unlikely(!h->next)) 2767 INIT_LIST_HEAD(h); 2768 2769 return list_empty(h); 2770 } 2771 2772 __bpf_kfunc struct bpf_rb_node *bpf_rbtree_remove(struct bpf_rb_root *root, 2773 struct bpf_rb_node *node) 2774 { 2775 struct bpf_rb_node_kern *node_internal = (struct bpf_rb_node_kern *)node; 2776 struct rb_root_cached *r = (struct rb_root_cached *)root; 2777 struct rb_node *n = &node_internal->rb_node; 2778 2779 /* node_internal->owner != root implies either RB_EMPTY_NODE(n) or 2780 * n is owned by some other tree. No need to check RB_EMPTY_NODE(n) 2781 */ 2782 if (READ_ONCE(node_internal->owner) != root) 2783 return NULL; 2784 2785 rb_erase_cached(n, r); 2786 RB_CLEAR_NODE(n); 2787 WRITE_ONCE(node_internal->owner, NULL); 2788 return (struct bpf_rb_node *)n; 2789 } 2790 2791 /* Need to copy rbtree_add_cached's logic here because our 'less' is a BPF 2792 * program 2793 */ 2794 static int __bpf_rbtree_add(struct bpf_rb_root *root, 2795 struct bpf_rb_node_kern *node, 2796 void *less, struct btf_record *rec, u64 off) 2797 { 2798 struct rb_node **link = &((struct rb_root_cached *)root)->rb_root.rb_node; 2799 struct rb_node *parent = NULL, *n = &node->rb_node; 2800 bpf_callback_t cb = (bpf_callback_t)less; 2801 bool leftmost = true; 2802 2803 /* node->owner != NULL implies !RB_EMPTY_NODE(n), no need to separately 2804 * check the latter 2805 */ 2806 if (cmpxchg(&node->owner, NULL, BPF_PTR_POISON)) { 2807 /* Only called from BPF prog, no need to migrate_disable */ 2808 __bpf_obj_drop_impl((void *)n - off, rec, false); 2809 return -EINVAL; 2810 } 2811 2812 while (*link) { 2813 parent = *link; 2814 if (cb((uintptr_t)node, (uintptr_t)parent, 0, 0, 0)) { 2815 link = &parent->rb_left; 2816 } else { 2817 link = &parent->rb_right; 2818 leftmost = false; 2819 } 2820 } 2821 2822 rb_link_node(n, parent, link); 2823 rb_insert_color_cached(n, (struct rb_root_cached *)root, leftmost); 2824 WRITE_ONCE(node->owner, root); 2825 return 0; 2826 } 2827 2828 /** 2829 * bpf_rbtree_add() - add a node to a BPF rbtree 2830 * @root: tree root 2831 * @node: node to insert 2832 * @less: comparator used to order nodes 2833 * @meta: verifier-supplied struct metadata 2834 * @off: verifier-supplied offset of @node within the containing object 2835 * 2836 * Insert @node into @root using @less. The verifier rewrites @meta and @off; 2837 * BPF programs do not set them. 2838 * 2839 * Return: 0 on success, or %-EINVAL if @node is already linked in a tree. 2840 */ 2841 __bpf_kfunc int bpf_rbtree_add(struct bpf_rb_root *root, 2842 struct bpf_rb_node *node, 2843 bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b), 2844 struct btf_struct_meta *meta, 2845 u64 off) 2846 { 2847 struct bpf_rb_node_kern *n = (void *)node; 2848 2849 return __bpf_rbtree_add(root, n, (void *)less, meta ? meta->record : NULL, off); 2850 } 2851 2852 __bpf_kfunc int bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node, 2853 bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b), 2854 void *meta__ign, u64 off) 2855 { 2856 return bpf_rbtree_add(root, node, less, meta__ign, off); 2857 } 2858 2859 __bpf_kfunc struct bpf_rb_node *bpf_rbtree_first(struct bpf_rb_root *root) 2860 { 2861 struct rb_root_cached *r = (struct rb_root_cached *)root; 2862 2863 return (struct bpf_rb_node *)rb_first_cached(r); 2864 } 2865 2866 __bpf_kfunc struct bpf_rb_node *bpf_rbtree_root(struct bpf_rb_root *root) 2867 { 2868 struct rb_root_cached *r = (struct rb_root_cached *)root; 2869 2870 return (struct bpf_rb_node *)r->rb_root.rb_node; 2871 } 2872 2873 __bpf_kfunc struct bpf_rb_node *bpf_rbtree_left(struct bpf_rb_root *root, struct bpf_rb_node *node) 2874 { 2875 struct bpf_rb_node_kern *node_internal = (struct bpf_rb_node_kern *)node; 2876 2877 if (READ_ONCE(node_internal->owner) != root) 2878 return NULL; 2879 2880 return (struct bpf_rb_node *)node_internal->rb_node.rb_left; 2881 } 2882 2883 __bpf_kfunc struct bpf_rb_node *bpf_rbtree_right(struct bpf_rb_root *root, struct bpf_rb_node *node) 2884 { 2885 struct bpf_rb_node_kern *node_internal = (struct bpf_rb_node_kern *)node; 2886 2887 if (READ_ONCE(node_internal->owner) != root) 2888 return NULL; 2889 2890 return (struct bpf_rb_node *)node_internal->rb_node.rb_right; 2891 } 2892 2893 /** 2894 * bpf_task_acquire - Acquire a reference to a task. A task acquired by this 2895 * kfunc which is not stored in a map as a kptr, must be released by calling 2896 * bpf_task_release(). 2897 * @p: The task on which a reference is being acquired. 2898 */ 2899 __bpf_kfunc struct task_struct *bpf_task_acquire(struct task_struct *p) 2900 { 2901 if (refcount_inc_not_zero(&p->rcu_users)) 2902 return p; 2903 return NULL; 2904 } 2905 2906 /** 2907 * bpf_task_release - Release the reference acquired on a task. 2908 * @p: The task on which a reference is being released. 2909 */ 2910 __bpf_kfunc void bpf_task_release(struct task_struct *p) 2911 { 2912 put_task_struct_rcu_user(p); 2913 } 2914 2915 __bpf_kfunc void bpf_task_release_dtor(void *p) 2916 { 2917 put_task_struct_rcu_user(p); 2918 } 2919 CFI_NOSEAL(bpf_task_release_dtor); 2920 2921 #ifdef CONFIG_CGROUPS 2922 /** 2923 * bpf_cgroup_acquire - Acquire a reference to a cgroup. A cgroup acquired by 2924 * this kfunc which is not stored in a map as a kptr, must be released by 2925 * calling bpf_cgroup_release(). 2926 * @cgrp: The cgroup on which a reference is being acquired. 2927 */ 2928 __bpf_kfunc struct cgroup *bpf_cgroup_acquire(struct cgroup *cgrp) 2929 { 2930 return cgroup_tryget(cgrp) ? cgrp : NULL; 2931 } 2932 2933 /** 2934 * bpf_cgroup_release - Release the reference acquired on a cgroup. 2935 * If this kfunc is invoked in an RCU read region, the cgroup is guaranteed to 2936 * not be freed until the current grace period has ended, even if its refcount 2937 * drops to 0. 2938 * @cgrp: The cgroup on which a reference is being released. 2939 */ 2940 __bpf_kfunc void bpf_cgroup_release(struct cgroup *cgrp) 2941 { 2942 cgroup_put(cgrp); 2943 } 2944 2945 __bpf_kfunc void bpf_cgroup_release_dtor(void *cgrp) 2946 { 2947 cgroup_put(cgrp); 2948 } 2949 CFI_NOSEAL(bpf_cgroup_release_dtor); 2950 2951 /** 2952 * bpf_cgroup_ancestor - Perform a lookup on an entry in a cgroup's ancestor 2953 * array. A cgroup returned by this kfunc which is not subsequently stored in a 2954 * map, must be released by calling bpf_cgroup_release(). 2955 * @cgrp: The cgroup for which we're performing a lookup. 2956 * @level: The level of ancestor to look up. 2957 */ 2958 __bpf_kfunc struct cgroup *bpf_cgroup_ancestor(struct cgroup *cgrp, int level) 2959 { 2960 struct cgroup *ancestor; 2961 2962 if (level > cgrp->level || level < 0) 2963 return NULL; 2964 2965 /* cgrp's refcnt could be 0 here, but ancestors can still be accessed */ 2966 ancestor = cgrp->ancestors[level]; 2967 if (!cgroup_tryget(ancestor)) 2968 return NULL; 2969 return ancestor; 2970 } 2971 2972 /** 2973 * bpf_cgroup_from_id - Find a cgroup from its ID. A cgroup returned by this 2974 * kfunc which is not subsequently stored in a map, must be released by calling 2975 * bpf_cgroup_release(). 2976 * @cgid: cgroup id. 2977 */ 2978 __bpf_kfunc struct cgroup *bpf_cgroup_from_id(u64 cgid) 2979 { 2980 struct cgroup *cgrp; 2981 2982 cgrp = __cgroup_get_from_id(cgid); 2983 if (IS_ERR(cgrp)) 2984 return NULL; 2985 return cgrp; 2986 } 2987 2988 /** 2989 * bpf_task_under_cgroup - wrap task_under_cgroup_hierarchy() as a kfunc, test 2990 * task's membership of cgroup ancestry. 2991 * @task: the task to be tested 2992 * @ancestor: possible ancestor of @task's cgroup 2993 * 2994 * Tests whether @task's default cgroup hierarchy is a descendant of @ancestor. 2995 * It follows all the same rules as cgroup_is_descendant, and only applies 2996 * to the default hierarchy. 2997 */ 2998 __bpf_kfunc long bpf_task_under_cgroup(struct task_struct *task, 2999 struct cgroup *ancestor) 3000 { 3001 long ret; 3002 3003 rcu_read_lock(); 3004 ret = task_under_cgroup_hierarchy(task, ancestor); 3005 rcu_read_unlock(); 3006 return ret; 3007 } 3008 3009 BPF_CALL_2(bpf_current_task_under_cgroup, struct bpf_map *, map, u32, idx) 3010 { 3011 struct bpf_array *array = container_of(map, struct bpf_array, map); 3012 struct cgroup *cgrp; 3013 3014 if (unlikely(idx >= array->map.max_entries)) 3015 return -E2BIG; 3016 3017 cgrp = READ_ONCE(array->ptrs[idx]); 3018 if (unlikely(!cgrp)) 3019 return -EAGAIN; 3020 3021 return task_under_cgroup_hierarchy(current, cgrp); 3022 } 3023 3024 const struct bpf_func_proto bpf_current_task_under_cgroup_proto = { 3025 .func = bpf_current_task_under_cgroup, 3026 .gpl_only = false, 3027 .ret_type = RET_INTEGER, 3028 .arg1_type = ARG_CONST_MAP_PTR, 3029 .arg2_type = ARG_ANYTHING, 3030 }; 3031 3032 /** 3033 * bpf_task_get_cgroup1 - Acquires the associated cgroup of a task within a 3034 * specific cgroup1 hierarchy. The cgroup1 hierarchy is identified by its 3035 * hierarchy ID. 3036 * @task: The target task 3037 * @hierarchy_id: The ID of a cgroup1 hierarchy 3038 * 3039 * On success, the cgroup is returen. On failure, NULL is returned. 3040 */ 3041 __bpf_kfunc struct cgroup * 3042 bpf_task_get_cgroup1(struct task_struct *task, int hierarchy_id) 3043 { 3044 struct cgroup *cgrp = task_get_cgroup1(task, hierarchy_id); 3045 3046 if (IS_ERR(cgrp)) 3047 return NULL; 3048 return cgrp; 3049 } 3050 #endif /* CONFIG_CGROUPS */ 3051 3052 /** 3053 * bpf_task_from_pid - Find a struct task_struct from its pid by looking it up 3054 * in the root pid namespace idr. If a task is returned, it must either be 3055 * stored in a map, or released with bpf_task_release(). 3056 * @pid: The pid of the task being looked up. 3057 */ 3058 __bpf_kfunc struct task_struct *bpf_task_from_pid(s32 pid) 3059 { 3060 struct task_struct *p; 3061 3062 rcu_read_lock(); 3063 p = find_task_by_pid_ns(pid, &init_pid_ns); 3064 if (p) 3065 p = bpf_task_acquire(p); 3066 rcu_read_unlock(); 3067 3068 return p; 3069 } 3070 3071 /** 3072 * bpf_task_from_vpid - Find a struct task_struct from its vpid by looking it up 3073 * in the pid namespace of the current task. If a task is returned, it must 3074 * either be stored in a map, or released with bpf_task_release(). 3075 * @vpid: The vpid of the task being looked up. 3076 */ 3077 __bpf_kfunc struct task_struct *bpf_task_from_vpid(s32 vpid) 3078 { 3079 struct task_struct *p; 3080 3081 guard(rcu)(); 3082 if (!task_active_pid_ns(current)) 3083 return NULL; 3084 3085 p = find_task_by_vpid(vpid); 3086 if (p) 3087 p = bpf_task_acquire(p); 3088 3089 return p; 3090 } 3091 3092 /** 3093 * bpf_dynptr_slice() - Obtain a read-only pointer to the dynptr data. 3094 * @p: The dynptr whose data slice to retrieve 3095 * @offset: Offset into the dynptr 3096 * @buffer__nullable: User-provided buffer to copy contents into. May be NULL 3097 * @buffer__szk: Size (in bytes) of the buffer if present. This is the 3098 * length of the requested slice. This must be a constant. 3099 * 3100 * For non-skb and non-xdp type dynptrs, there is no difference between 3101 * bpf_dynptr_slice and bpf_dynptr_data. 3102 * 3103 * If buffer__nullable is NULL, the call will fail if buffer_opt was needed. 3104 * 3105 * If the intention is to write to the data slice, please use 3106 * bpf_dynptr_slice_rdwr. 3107 * 3108 * The user must check that the returned pointer is not null before using it. 3109 * 3110 * Please note that in the case of skb and xdp dynptrs, bpf_dynptr_slice 3111 * does not change the underlying packet data pointers, so a call to 3112 * bpf_dynptr_slice will not invalidate any ctx->data/data_end pointers in 3113 * the bpf program. 3114 * 3115 * Please also note that when the buffer is on the stack, the verifier invalidates 3116 * the returned pointer when the program stores to the buffer (helpers and kfuncs 3117 * may fill it), or returns from the function that has it. 3118 * 3119 * Return: NULL if the call failed (eg invalid dynptr), pointer to a read-only 3120 * data slice (can be either direct pointer to the data or a pointer to the user 3121 * provided buffer, with its contents containing the data, if unable to obtain 3122 * direct pointer) 3123 */ 3124 __bpf_kfunc void *bpf_dynptr_slice(const struct bpf_dynptr *p, u64 offset, 3125 void *buffer__nullable, u64 buffer__szk) 3126 { 3127 const struct bpf_dynptr_kern *ptr = (struct bpf_dynptr_kern *)p; 3128 enum bpf_dynptr_type type; 3129 u64 len = buffer__szk; 3130 int err; 3131 3132 if (!ptr->data) 3133 return NULL; 3134 3135 err = bpf_dynptr_check_off_len(ptr, offset, len); 3136 if (err) 3137 return NULL; 3138 3139 type = bpf_dynptr_get_type(ptr); 3140 3141 switch (type) { 3142 case BPF_DYNPTR_TYPE_LOCAL: 3143 case BPF_DYNPTR_TYPE_RINGBUF: 3144 return ptr->data + ptr->offset + offset; 3145 case BPF_DYNPTR_TYPE_SKB: 3146 if (buffer__nullable) 3147 return skb_header_pointer(ptr->data, ptr->offset + offset, len, buffer__nullable); 3148 else 3149 return skb_pointer_if_linear(ptr->data, ptr->offset + offset, len); 3150 case BPF_DYNPTR_TYPE_XDP: 3151 { 3152 void *xdp_ptr = bpf_xdp_pointer(ptr->data, ptr->offset + offset, len); 3153 if (!IS_ERR_OR_NULL(xdp_ptr)) 3154 return xdp_ptr; 3155 3156 /* the packet may be shorter than it was for bpf_dynptr_from_xdp() */ 3157 if (!buffer__nullable || ptr->offset + offset + len > xdp_get_buff_len(ptr->data)) 3158 return NULL; 3159 bpf_xdp_copy_buf(ptr->data, ptr->offset + offset, buffer__nullable, len, false); 3160 return buffer__nullable; 3161 } 3162 case BPF_DYNPTR_TYPE_SKB_META: 3163 return bpf_skb_meta_pointer(ptr->data, ptr->offset + offset); 3164 case BPF_DYNPTR_TYPE_FILE: 3165 err = bpf_file_fetch_bytes(ptr->data, offset, buffer__nullable, buffer__szk); 3166 return err ? NULL : buffer__nullable; 3167 default: 3168 WARN_ONCE(true, "unknown dynptr type %d\n", type); 3169 return NULL; 3170 } 3171 } 3172 3173 /** 3174 * bpf_dynptr_slice_rdwr() - Obtain a writable pointer to the dynptr data. 3175 * @p: The dynptr whose data slice to retrieve 3176 * @offset: Offset into the dynptr 3177 * @buffer__nullable: User-provided buffer to copy contents into. May be NULL 3178 * @buffer__szk: Size (in bytes) of the buffer if present. This is the 3179 * length of the requested slice. This must be a constant. 3180 * 3181 * For non-skb and non-xdp type dynptrs, there is no difference between 3182 * bpf_dynptr_slice and bpf_dynptr_data. 3183 * 3184 * If buffer__nullable is NULL, the call will fail if buffer_opt was needed. 3185 * 3186 * The returned pointer is writable and may point to either directly the dynptr 3187 * data at the requested offset or to the buffer if unable to obtain a direct 3188 * data pointer to (example: the requested slice is to the paged area of an skb 3189 * packet). In the case where the returned pointer is to the buffer, the user 3190 * is responsible for persisting writes through calling bpf_dynptr_write(). This 3191 * usually looks something like this pattern: 3192 * 3193 * struct eth_hdr *eth = bpf_dynptr_slice_rdwr(&dynptr, 0, buffer, sizeof(buffer)); 3194 * if (!eth) 3195 * return TC_ACT_SHOT; 3196 * 3197 * // mutate eth header // 3198 * 3199 * if (eth == buffer) 3200 * bpf_dynptr_write(&ptr, 0, buffer, sizeof(buffer), 0); 3201 * 3202 * Please note that, as in the example above, the user must check that the 3203 * returned pointer is not null before using it. 3204 * 3205 * Please also note that when the buffer is on the stack, the verifier invalidates 3206 * the returned pointer when the program stores to the buffer (helpers and kfuncs 3207 * may fill it), or returns from the function that has it. Change the data through 3208 * the returned pointer, and before the comparison with the buffer, as in the 3209 * example above: after it the compiler may use one pointer in place of the other. 3210 * 3211 * Please also note that in the case of skb and xdp dynptrs, bpf_dynptr_slice_rdwr 3212 * does not change the underlying packet data pointers, so a call to 3213 * bpf_dynptr_slice_rdwr will not invalidate any ctx->data/data_end pointers in 3214 * the bpf program. 3215 * 3216 * Return: NULL if the call failed (eg invalid dynptr), pointer to a 3217 * data slice (can be either direct pointer to the data or a pointer to the user 3218 * provided buffer, with its contents containing the data, if unable to obtain 3219 * direct pointer) 3220 */ 3221 __bpf_kfunc void *bpf_dynptr_slice_rdwr(const struct bpf_dynptr *p, u64 offset, 3222 void *buffer__nullable, u64 buffer__szk) 3223 { 3224 const struct bpf_dynptr_kern *ptr = (struct bpf_dynptr_kern *)p; 3225 3226 if (!ptr->data || __bpf_dynptr_is_rdonly(ptr)) 3227 return NULL; 3228 3229 /* bpf_dynptr_slice_rdwr is the same logic as bpf_dynptr_slice. 3230 * 3231 * For skb-type dynptrs, it is safe to write into the returned pointer 3232 * if the bpf program allows skb data writes. There are two possibilities 3233 * that may occur when calling bpf_dynptr_slice_rdwr: 3234 * 3235 * 1) The requested slice is in the head of the skb. In this case, the 3236 * returned pointer is directly to skb data, and if the skb is cloned, the 3237 * verifier will have uncloned it (see bpf_unclone_prologue()) already. 3238 * The pointer can be directly written into. 3239 * 3240 * 2) Some portion of the requested slice is in the paged buffer area. 3241 * In this case, the requested data will be copied out into the buffer 3242 * and the returned pointer will be a pointer to the buffer. The skb 3243 * will not be pulled. To persist the write, the user will need to call 3244 * bpf_dynptr_write(), which will pull the skb and commit the write. 3245 * 3246 * Similarly for xdp programs, if the requested slice is not across xdp 3247 * fragments, then a direct pointer will be returned, otherwise the data 3248 * will be copied out into the buffer and the user will need to call 3249 * bpf_dynptr_write() to commit changes. 3250 */ 3251 return bpf_dynptr_slice(p, offset, buffer__nullable, buffer__szk); 3252 } 3253 3254 __bpf_kfunc int bpf_dynptr_adjust(struct bpf_dynptr *p, u64 start, u64 end) 3255 { 3256 struct bpf_dynptr_kern *ptr = (struct bpf_dynptr_kern *)p; 3257 u64 size; 3258 3259 if (!ptr->data || start > end) 3260 return -EINVAL; 3261 3262 size = __bpf_dynptr_size(ptr); 3263 3264 if (start > size || end > size) 3265 return -ERANGE; 3266 3267 bpf_dynptr_advance_offset(ptr, start); 3268 bpf_dynptr_set_size(ptr, end - start); 3269 3270 return 0; 3271 } 3272 3273 __bpf_kfunc bool bpf_dynptr_is_null(const struct bpf_dynptr *p) 3274 { 3275 const struct bpf_dynptr_kern *ptr = (struct bpf_dynptr_kern *)p; 3276 3277 return !ptr->data; 3278 } 3279 3280 __bpf_kfunc bool bpf_dynptr_is_rdonly(const struct bpf_dynptr *p) 3281 { 3282 const struct bpf_dynptr_kern *ptr = (struct bpf_dynptr_kern *)p; 3283 3284 if (!ptr->data) 3285 return false; 3286 3287 return __bpf_dynptr_is_rdonly(ptr); 3288 } 3289 3290 __bpf_kfunc u64 bpf_dynptr_size(const struct bpf_dynptr *p) 3291 { 3292 const struct bpf_dynptr_kern *ptr = (struct bpf_dynptr_kern *)p; 3293 3294 if (!ptr->data) 3295 return -EINVAL; 3296 3297 return __bpf_dynptr_size(ptr); 3298 } 3299 3300 __bpf_kfunc int bpf_dynptr_clone(const struct bpf_dynptr *p, 3301 struct bpf_dynptr *clone__uninit) 3302 { 3303 struct bpf_dynptr_kern *clone = (struct bpf_dynptr_kern *)clone__uninit; 3304 const struct bpf_dynptr_kern *ptr = (struct bpf_dynptr_kern *)p; 3305 3306 if (!ptr->data) { 3307 bpf_dynptr_set_null(clone); 3308 return -EINVAL; 3309 } 3310 3311 *clone = *ptr; 3312 3313 return 0; 3314 } 3315 3316 /** 3317 * bpf_dynptr_copy() - Copy data from one dynptr to another. 3318 * @dst_ptr: Destination dynptr - where data should be copied to 3319 * @dst_off: Offset into the destination dynptr 3320 * @src_ptr: Source dynptr - where data should be copied from 3321 * @src_off: Offset into the source dynptr 3322 * @size: Length of the data to copy from source to destination 3323 * 3324 * Copies data from source dynptr to destination dynptr. 3325 * Returns 0 on success; negative error, otherwise. 3326 */ 3327 __bpf_kfunc int bpf_dynptr_copy(const struct bpf_dynptr *dst_ptr, u64 dst_off, 3328 const struct bpf_dynptr *src_ptr, u64 src_off, u64 size) 3329 { 3330 const struct bpf_dynptr_kern *dst = (struct bpf_dynptr_kern *)dst_ptr; 3331 const struct bpf_dynptr_kern *src = (struct bpf_dynptr_kern *)src_ptr; 3332 bool same = src->data == dst->data; 3333 void *src_slice, *dst_slice; 3334 char buf[256]; 3335 bool rev; 3336 u64 off; 3337 3338 src_slice = bpf_dynptr_slice(src_ptr, src_off, NULL, size); 3339 dst_slice = bpf_dynptr_slice_rdwr(dst_ptr, dst_off, NULL, size); 3340 3341 if (src_slice && dst_slice) { 3342 memmove(dst_slice, src_slice, size); 3343 return 0; 3344 } 3345 3346 /* The other range is copied piece by piece. A slice of the same packet 3347 * may overlap with it, so it cannot be the buffer for that. 3348 */ 3349 if (src_slice && !same) 3350 return __bpf_dynptr_write(dst, dst_off, src_slice, size, 0); 3351 3352 if (dst_slice && !same) 3353 return __bpf_dynptr_read(dst_slice, size, src, src_off, 0); 3354 3355 if (bpf_dynptr_check_off_len(dst, dst_off, size) || 3356 bpf_dynptr_check_off_len(src, src_off, size)) 3357 return -E2BIG; 3358 3359 /* like memmove(): from the end if the destination is above the source */ 3360 rev = same && dst->offset + dst_off > src->offset + src_off; 3361 off = 0; 3362 while (off < size) { 3363 u64 chunk_sz = min_t(u64, sizeof(buf), size - off); 3364 u64 pos = rev ? size - off - chunk_sz : off; 3365 int err; 3366 3367 err = __bpf_dynptr_read(buf, chunk_sz, src, src_off + pos, 0); 3368 if (err) 3369 return err; 3370 err = __bpf_dynptr_write(dst, dst_off + pos, buf, chunk_sz, 0); 3371 if (err) 3372 return err; 3373 3374 off += chunk_sz; 3375 } 3376 return 0; 3377 } 3378 3379 /** 3380 * bpf_dynptr_memset() - Fill dynptr memory with a constant byte. 3381 * @p: Destination dynptr - where data will be filled 3382 * @offset: Offset into the dynptr to start filling from 3383 * @size: Number of bytes to fill 3384 * @val: Constant byte to fill the memory with 3385 * 3386 * Fills the @size bytes of the memory area pointed to by @p 3387 * at @offset with the constant byte @val. 3388 * Returns 0 on success; negative error, otherwise. 3389 */ 3390 __bpf_kfunc int bpf_dynptr_memset(const struct bpf_dynptr *p, u64 offset, u64 size, u8 val) 3391 { 3392 const struct bpf_dynptr_kern *ptr = (struct bpf_dynptr_kern *)p; 3393 u64 chunk_sz, write_off; 3394 char buf[256]; 3395 void* slice; 3396 int err; 3397 3398 slice = bpf_dynptr_slice_rdwr(p, offset, NULL, size); 3399 if (likely(slice)) { 3400 memset(slice, val, size); 3401 return 0; 3402 } 3403 3404 if (__bpf_dynptr_is_rdonly(ptr)) 3405 return -EINVAL; 3406 3407 err = bpf_dynptr_check_off_len(ptr, offset, size); 3408 if (err) 3409 return err; 3410 3411 /* Non-linear data under the dynptr, write from a local buffer */ 3412 chunk_sz = min_t(u64, sizeof(buf), size); 3413 memset(buf, val, chunk_sz); 3414 3415 for (write_off = 0; write_off < size; write_off += chunk_sz) { 3416 chunk_sz = min_t(u64, sizeof(buf), size - write_off); 3417 err = __bpf_dynptr_write(ptr, offset + write_off, buf, chunk_sz, 0); 3418 if (err) 3419 return err; 3420 } 3421 3422 return 0; 3423 } 3424 3425 __bpf_kfunc void *bpf_cast_to_kern_ctx(void *obj) 3426 { 3427 return obj; 3428 } 3429 3430 __bpf_kfunc void *bpf_rdonly_cast(const void *obj__ign, u32 btf_id__k) 3431 { 3432 return (void *)obj__ign; 3433 } 3434 3435 __bpf_kfunc void bpf_rcu_read_lock(void) 3436 { 3437 rcu_read_lock(); 3438 } 3439 3440 __bpf_kfunc void bpf_rcu_read_unlock(void) 3441 { 3442 rcu_read_unlock(); 3443 } 3444 3445 struct bpf_throw_ctx { 3446 struct bpf_prog_aux *aux; 3447 u64 sp; 3448 u64 bp; 3449 int cnt; 3450 }; 3451 3452 static bool bpf_stack_walker(void *cookie, u64 ip, u64 sp, u64 bp) 3453 { 3454 struct bpf_throw_ctx *ctx = cookie; 3455 struct bpf_prog *prog; 3456 3457 /* 3458 * The RCU read lock is held to safely traverse the latch tree, but we 3459 * don't need its protection when accessing the prog, since it has an 3460 * active stack frame on the current stack trace, and won't disappear. 3461 */ 3462 rcu_read_lock(); 3463 prog = bpf_prog_ksym_find(ip); 3464 rcu_read_unlock(); 3465 if (!prog) 3466 return !ctx->cnt; 3467 ctx->cnt++; 3468 if (bpf_is_subprog(prog)) 3469 return true; 3470 ctx->aux = prog->aux; 3471 ctx->sp = sp; 3472 ctx->bp = bp; 3473 return false; 3474 } 3475 3476 /* It does not return. What a tracer keeps for the return would stay behind, redzones too. */ 3477 __bpf_kfunc notrace __no_sanitize_address void bpf_throw(u64 cookie) 3478 { 3479 struct bpf_throw_ctx ctx = {}; 3480 3481 arch_bpf_stack_walk(bpf_stack_walker, &ctx); 3482 WARN_ON_ONCE(!ctx.aux); 3483 if (ctx.aux) 3484 WARN_ON_ONCE(!ctx.aux->exception_boundary); 3485 WARN_ON_ONCE(!ctx.bp); 3486 WARN_ON_ONCE(!ctx.cnt); 3487 /* arm64 drops one entry of the shadow call stack, don't move the call to a callee */ 3488 ctx.aux->bpf_exception_cb(cookie, ctx.sp + ctx.aux->stack_arg_sp_adjust, ctx.bp, 0, 0); 3489 WARN(1, "A call to BPF exception callback should never return\n"); 3490 } 3491 NOKPROBE_SYMBOL(bpf_throw); 3492 3493 __bpf_kfunc int bpf_wq_init(struct bpf_wq *wq, void *p__const_map, unsigned int flags) 3494 { 3495 struct bpf_async_kern *async = (struct bpf_async_kern *)wq; 3496 struct bpf_map *map = p__const_map; 3497 3498 BUILD_BUG_ON(sizeof(struct bpf_async_kern) > sizeof(struct bpf_wq)); 3499 BUILD_BUG_ON(__alignof__(struct bpf_async_kern) != __alignof__(struct bpf_wq)); 3500 3501 if (flags) 3502 return -EINVAL; 3503 3504 return __bpf_async_init(async, map, flags, BPF_ASYNC_TYPE_WQ); 3505 } 3506 3507 __bpf_kfunc int bpf_wq_start(struct bpf_wq *wq, unsigned int flags) 3508 { 3509 struct bpf_async_kern *async = (struct bpf_async_kern *)wq; 3510 struct bpf_work *w; 3511 3512 if (flags) 3513 return -EINVAL; 3514 3515 w = READ_ONCE(async->work); 3516 if (!w || !READ_ONCE(w->cb.prog)) 3517 return -EINVAL; 3518 3519 if (!refcount_inc_not_zero(&w->cb.refcnt)) 3520 return -ENOENT; 3521 3522 if (!defer_timer_wq_op()) { 3523 schedule_work(&w->work); 3524 bpf_async_refcount_put(&w->cb); 3525 return 0; 3526 } else { 3527 return bpf_async_schedule_op(&w->cb, BPF_ASYNC_START, 0, 0); 3528 } 3529 } 3530 3531 __bpf_kfunc int bpf_wq_set_callback(struct bpf_wq *wq, 3532 int (callback_fn)(void *map, int *key, void *value), 3533 unsigned int flags, 3534 struct bpf_prog_aux *aux) 3535 { 3536 struct bpf_async_kern *async = (struct bpf_async_kern *)wq; 3537 3538 if (flags) 3539 return -EINVAL; 3540 3541 return __bpf_async_set_callback(async, callback_fn, aux->prog); 3542 } 3543 3544 __bpf_kfunc void bpf_preempt_disable(void) 3545 { 3546 preempt_disable(); 3547 } 3548 3549 __bpf_kfunc void bpf_preempt_enable(void) 3550 { 3551 preempt_enable(); 3552 } 3553 3554 struct bpf_iter_bits { 3555 __u64 __opaque[2]; 3556 } __aligned(8); 3557 3558 #define BITS_ITER_NR_WORDS_MAX 511 3559 3560 struct bpf_iter_bits_kern { 3561 union { 3562 __u64 *bits; 3563 __u64 bits_copy; 3564 }; 3565 int nr_bits; 3566 int bit; 3567 } __aligned(8); 3568 3569 /* On 64-bit hosts, unsigned long and u64 have the same size, so passing 3570 * a u64 pointer and an unsigned long pointer to find_next_bit() will 3571 * return the same result, as both point to the same 8-byte area. 3572 * 3573 * For 32-bit little-endian hosts, using a u64 pointer or unsigned long 3574 * pointer also makes no difference. This is because the first iterated 3575 * unsigned long is composed of bits 0-31 of the u64 and the second unsigned 3576 * long is composed of bits 32-63 of the u64. 3577 * 3578 * However, for 32-bit big-endian hosts, this is not the case. The first 3579 * iterated unsigned long will be bits 32-63 of the u64, so swap these two 3580 * ulong values within the u64. 3581 */ 3582 static void swap_ulong_in_u64(u64 *bits, unsigned int nr) 3583 { 3584 #if (BITS_PER_LONG == 32) && defined(__BIG_ENDIAN) 3585 unsigned int i; 3586 3587 for (i = 0; i < nr; i++) 3588 bits[i] = (bits[i] >> 32) | ((u64)(u32)bits[i] << 32); 3589 #endif 3590 } 3591 3592 /** 3593 * bpf_iter_bits_new() - Initialize a new bits iterator for a given memory area 3594 * @it: The new bpf_iter_bits to be created 3595 * @unsafe_ptr__ign: A pointer pointing to a memory area to be iterated over 3596 * @nr_words: The size of the specified memory area, measured in 8-byte units. 3597 * The maximum value of @nr_words is @BITS_ITER_NR_WORDS_MAX. This limit may be 3598 * further reduced by the BPF memory allocator implementation. 3599 * 3600 * This function initializes a new bpf_iter_bits structure for iterating over 3601 * a memory area which is specified by the @unsafe_ptr__ign and @nr_words. It 3602 * copies the data of the memory area to the newly created bpf_iter_bits @it for 3603 * subsequent iteration operations. 3604 * 3605 * On success, 0 is returned. On failure, ERR is returned. 3606 */ 3607 __bpf_kfunc int 3608 bpf_iter_bits_new(struct bpf_iter_bits *it, const u64 *unsafe_ptr__ign, u32 nr_words) 3609 { 3610 struct bpf_iter_bits_kern *kit = (void *)it; 3611 u32 nr_bytes = nr_words * sizeof(u64); 3612 u32 nr_bits = BYTES_TO_BITS(nr_bytes); 3613 int err; 3614 3615 BUILD_BUG_ON(sizeof(struct bpf_iter_bits_kern) != sizeof(struct bpf_iter_bits)); 3616 BUILD_BUG_ON(__alignof__(struct bpf_iter_bits_kern) != 3617 __alignof__(struct bpf_iter_bits)); 3618 3619 kit->nr_bits = 0; 3620 kit->bits_copy = 0; 3621 kit->bit = -1; 3622 3623 if (!unsafe_ptr__ign || !nr_words) 3624 return -EINVAL; 3625 if (nr_words > BITS_ITER_NR_WORDS_MAX) 3626 return -E2BIG; 3627 3628 /* Optimization for u64 mask */ 3629 if (nr_bits == 64) { 3630 err = bpf_probe_read_kernel_common(&kit->bits_copy, nr_bytes, unsafe_ptr__ign); 3631 if (err) 3632 return -EFAULT; 3633 3634 swap_ulong_in_u64(&kit->bits_copy, nr_words); 3635 3636 kit->nr_bits = nr_bits; 3637 return 0; 3638 } 3639 3640 if (bpf_mem_alloc_check_size(false, nr_bytes)) 3641 return -E2BIG; 3642 3643 /* Fallback to memalloc */ 3644 kit->bits = bpf_mem_alloc(&bpf_global_ma, nr_bytes); 3645 if (!kit->bits) 3646 return -ENOMEM; 3647 3648 err = bpf_probe_read_kernel_common(kit->bits, nr_bytes, unsafe_ptr__ign); 3649 if (err) { 3650 bpf_mem_free(&bpf_global_ma, kit->bits); 3651 return err; 3652 } 3653 3654 swap_ulong_in_u64(kit->bits, nr_words); 3655 3656 kit->nr_bits = nr_bits; 3657 return 0; 3658 } 3659 3660 /** 3661 * bpf_iter_bits_next() - Get the next bit in a bpf_iter_bits 3662 * @it: The bpf_iter_bits to be checked 3663 * 3664 * This function returns a pointer to a number representing the value of the 3665 * next bit in the bits. 3666 * 3667 * If there are no further bits available, it returns NULL. 3668 */ 3669 __bpf_kfunc int *bpf_iter_bits_next(struct bpf_iter_bits *it) 3670 { 3671 struct bpf_iter_bits_kern *kit = (void *)it; 3672 int bit = kit->bit, nr_bits = kit->nr_bits; 3673 const void *bits; 3674 3675 if (!nr_bits || bit >= nr_bits) 3676 return NULL; 3677 3678 bits = nr_bits == 64 ? &kit->bits_copy : kit->bits; 3679 bit = find_next_bit(bits, nr_bits, bit + 1); 3680 if (bit >= nr_bits) { 3681 kit->bit = bit; 3682 return NULL; 3683 } 3684 3685 kit->bit = bit; 3686 return &kit->bit; 3687 } 3688 3689 /** 3690 * bpf_iter_bits_destroy() - Destroy a bpf_iter_bits 3691 * @it: The bpf_iter_bits to be destroyed 3692 * 3693 * Destroy the resource associated with the bpf_iter_bits. 3694 */ 3695 __bpf_kfunc void bpf_iter_bits_destroy(struct bpf_iter_bits *it) 3696 { 3697 struct bpf_iter_bits_kern *kit = (void *)it; 3698 3699 if (kit->nr_bits <= 64) 3700 return; 3701 bpf_mem_free(&bpf_global_ma, kit->bits); 3702 } 3703 3704 /** 3705 * bpf_copy_from_user_str() - Copy a string from an unsafe user address 3706 * @dst: Destination address, in kernel space. This buffer must be 3707 * at least @dst__sz bytes long. 3708 * @dst__sz: Maximum number of bytes to copy, includes the trailing NUL. 3709 * @unsafe_ptr__ign: Source address, in user space. 3710 * @flags: The only supported flag is BPF_F_PAD_ZEROS 3711 * 3712 * Copies a NUL-terminated string from userspace to BPF space. If user string is 3713 * too long this will still ensure zero termination in the dst buffer unless 3714 * buffer size is 0. 3715 * 3716 * If BPF_F_PAD_ZEROS flag is set, memset the tail of @dst to 0 on success and 3717 * memset all of @dst on failure. 3718 */ 3719 __bpf_kfunc int bpf_copy_from_user_str(void *dst, u32 dst__sz, const void __user *unsafe_ptr__ign, u64 flags) 3720 { 3721 int ret; 3722 3723 if (unlikely(flags & ~BPF_F_PAD_ZEROS)) 3724 return -EINVAL; 3725 3726 if (unlikely(!dst__sz)) 3727 return 0; 3728 3729 ret = strncpy_from_user(dst, unsafe_ptr__ign, dst__sz - 1); 3730 if (ret < 0) { 3731 if (flags & BPF_F_PAD_ZEROS) 3732 memset((char *)dst, 0, dst__sz); 3733 3734 return ret; 3735 } 3736 3737 if (flags & BPF_F_PAD_ZEROS) 3738 memset((char *)dst + ret, 0, dst__sz - ret); 3739 else 3740 ((char *)dst)[ret] = '\0'; 3741 3742 return ret + 1; 3743 } 3744 3745 /** 3746 * bpf_copy_from_user_mm() - Copy data from an address space 3747 * @dst: Destination address, in kernel space 3748 * @dst__sz: Number of bytes to copy 3749 * @unsafe_ptr__ign: Source address in the address space 3750 * @mm: Address space to copy from 3751 * @flags: Reserved for future use; must be zero 3752 * 3753 * Copies data from the user address space associated with @mm. The destination 3754 * is zeroed if an attempted copy cannot be completed in full. Unsupported 3755 * flags return -EINVAL without modifying @dst. 3756 * 3757 * Return: 0 on success, -EINVAL if @flags is non-zero, or -EFAULT if @mm is no 3758 * longer active or the copy fails or is partial. 3759 */ 3760 __bpf_kfunc int bpf_copy_from_user_mm(void *dst, u32 dst__sz, 3761 const void __user *unsafe_ptr__ign, 3762 struct mm_struct *mm, u64 flags) 3763 { 3764 int ret; 3765 3766 if (unlikely(flags)) 3767 return -EINVAL; 3768 3769 if (unlikely(!dst__sz)) 3770 return 0; 3771 3772 if (unlikely(!mmget_not_zero(mm))) { 3773 memset(dst, 0, dst__sz); 3774 return -EFAULT; 3775 } 3776 3777 ret = __bpf_copy_from_user_mm(dst, dst__sz, unsafe_ptr__ign, mm); 3778 mmput(mm); 3779 3780 return ret; 3781 } 3782 3783 /** 3784 * bpf_copy_from_user_mm_str() - Copy a string from an address space 3785 * @dst: Destination address, in kernel space. This buffer must be 3786 * at least @dst__sz bytes long 3787 * @dst__sz: Maximum number of bytes to copy, including the trailing NUL 3788 * @unsafe_ptr__ign: Source address in the address space 3789 * @mm: Address space to copy from 3790 * @flags: The only supported flag is BPF_F_PAD_ZEROS 3791 * 3792 * Copies a NUL-terminated string from the user address space associated with 3793 * @mm. If the string is too long, @dst is still NUL-terminated unless @dst__sz 3794 * is zero. 3795 * 3796 * If the flags are valid and BPF_F_PAD_ZEROS is set, the unused portion of 3797 * @dst is cleared on success and all of @dst is cleared on a copy failure. 3798 * Unsupported flags return -EINVAL without modifying @dst. 3799 * 3800 * Return: The number of copied bytes including the NUL terminator on success, 3801 * -EINVAL if @flags is invalid, or -EFAULT if @mm is no longer active or the 3802 * copy fails. 3803 */ 3804 __bpf_kfunc int bpf_copy_from_user_mm_str(void *dst, u32 dst__sz, 3805 const void __user *unsafe_ptr__ign, 3806 struct mm_struct *mm, u64 flags) 3807 { 3808 int ret; 3809 3810 if (unlikely(flags & ~BPF_F_PAD_ZEROS)) 3811 return -EINVAL; 3812 3813 if (unlikely(dst__sz == 0)) 3814 return 0; 3815 3816 if (unlikely(!mmget_not_zero(mm))) { 3817 if (flags & BPF_F_PAD_ZEROS) 3818 memset(dst, 0, dst__sz); 3819 else 3820 *(char *)dst = '\0'; 3821 return -EFAULT; 3822 } 3823 3824 ret = __bpf_copy_from_user_mm_str(dst, dst__sz, unsafe_ptr__ign, 3825 mm, flags); 3826 mmput(mm); 3827 3828 return ret; 3829 } 3830 3831 /** 3832 * bpf_copy_from_user_task_str() - Copy a string from an task's address space 3833 * @dst: Destination address, in kernel space. This buffer must be 3834 * at least @dst__sz bytes long. 3835 * @dst__sz: Maximum number of bytes to copy, includes the trailing NUL. 3836 * @unsafe_ptr__ign: Source address in the task's address space. 3837 * @tsk: The task whose address space will be used 3838 * @flags: The only supported flag is BPF_F_PAD_ZEROS 3839 * 3840 * Copies a NUL terminated string from a task's address space to @dst__sz 3841 * buffer. If user string is too long this will still ensure zero termination 3842 * in the @dst__sz buffer unless buffer size is 0. 3843 * 3844 * If BPF_F_PAD_ZEROS flag is set, memset the tail of @dst__sz to 0 on success 3845 * and memset all of @dst__sz on failure. 3846 * 3847 * Return: The number of copied bytes on success including the NUL terminator. 3848 * A negative error code on failure. 3849 */ 3850 __bpf_kfunc int bpf_copy_from_user_task_str(void *dst, u32 dst__sz, 3851 const void __user *unsafe_ptr__ign, 3852 struct task_struct *tsk, u64 flags) 3853 { 3854 struct mm_struct *mm; 3855 int ret; 3856 3857 if (unlikely(flags & ~BPF_F_PAD_ZEROS)) 3858 return -EINVAL; 3859 3860 if (unlikely(dst__sz == 0)) 3861 return 0; 3862 3863 mm = get_task_mm(tsk); 3864 if (!mm) { 3865 if (flags & BPF_F_PAD_ZEROS) 3866 memset(dst, 0, dst__sz); 3867 else 3868 *(char *)dst = '\0'; 3869 return -EFAULT; 3870 } 3871 3872 ret = __bpf_copy_from_user_mm_str(dst, dst__sz, unsafe_ptr__ign, 3873 mm, flags); 3874 mmput(mm); 3875 3876 return ret; 3877 } 3878 3879 /* Keep unsigned long in prototype so that kfunc is usable when emitted to 3880 * vmlinux.h in BPF programs directly, but note that while in BPF prog, the 3881 * unsigned long always points to 8-byte region on stack, the kernel may only 3882 * read and write the 4-bytes on 32-bit. 3883 */ 3884 __bpf_kfunc void bpf_local_irq_save(unsigned long *flags__irq_flag) 3885 { 3886 local_irq_save(*flags__irq_flag); 3887 } 3888 3889 __bpf_kfunc void bpf_local_irq_restore(unsigned long *flags__irq_flag) 3890 { 3891 local_irq_restore(*flags__irq_flag); 3892 } 3893 3894 __bpf_kfunc void __bpf_trap(void) 3895 { 3896 } 3897 3898 /* 3899 * Kfuncs for string operations. 3900 * 3901 * Since strings are not necessarily %NUL-terminated, we cannot directly call 3902 * in-kernel implementations. Instead, we open-code the implementations using 3903 * __get_kernel_nofault instead of plain dereference to make them safe. 3904 */ 3905 3906 static int __bpf_strncasecmp(const char *s1, const char *s2, bool ignore_case, size_t len) 3907 { 3908 char c1, c2; 3909 int i; 3910 3911 if (!copy_from_kernel_nofault_allowed(s1, 1) || 3912 !copy_from_kernel_nofault_allowed(s2, 1)) { 3913 return -ERANGE; 3914 } 3915 3916 guard(pagefault)(); 3917 for (i = 0; i < len && i < XATTR_SIZE_MAX; i++) { 3918 __get_kernel_nofault(&c1, s1, char, err_out); 3919 __get_kernel_nofault(&c2, s2, char, err_out); 3920 if (ignore_case) { 3921 c1 = tolower(c1); 3922 c2 = tolower(c2); 3923 } 3924 if (c1 != c2) 3925 return c1 < c2 ? -1 : 1; 3926 if (c1 == '\0') 3927 return 0; 3928 s1++; 3929 s2++; 3930 } 3931 return i == XATTR_SIZE_MAX ? -E2BIG : 0; 3932 err_out: 3933 return -EFAULT; 3934 } 3935 3936 /** 3937 * bpf_strcmp - Compare two strings 3938 * @s1__ign: One string 3939 * @s2__ign: Another string 3940 * 3941 * Return: 3942 * * %0 - Strings are equal 3943 * * %-1 - @s1__ign is smaller 3944 * * %1 - @s2__ign is smaller 3945 * * %-EFAULT - Cannot read one of the strings 3946 * * %-E2BIG - One of strings is too large 3947 * * %-ERANGE - One of strings is outside of kernel address space 3948 */ 3949 __bpf_kfunc int bpf_strcmp(const char *s1__ign, const char *s2__ign) 3950 { 3951 return __bpf_strncasecmp(s1__ign, s2__ign, false, XATTR_SIZE_MAX); 3952 } 3953 3954 /** 3955 * bpf_strcasecmp - Compare two strings, ignoring the case of the characters 3956 * @s1__ign: One string 3957 * @s2__ign: Another string 3958 * 3959 * Return: 3960 * * %0 - Strings are equal 3961 * * %-1 - @s1__ign is smaller 3962 * * %1 - @s2__ign is smaller 3963 * * %-EFAULT - Cannot read one of the strings 3964 * * %-E2BIG - One of strings is too large 3965 * * %-ERANGE - One of strings is outside of kernel address space 3966 */ 3967 __bpf_kfunc int bpf_strcasecmp(const char *s1__ign, const char *s2__ign) 3968 { 3969 return __bpf_strncasecmp(s1__ign, s2__ign, true, XATTR_SIZE_MAX); 3970 } 3971 3972 /* 3973 * bpf_strncasecmp - Compare two length-limited strings, ignoring case 3974 * @s1__ign: One string 3975 * @s2__ign: Another string 3976 * @len: The maximum number of characters to compare 3977 * 3978 * Return: 3979 * * %0 - Strings are equal 3980 * * %-1 - @s1__ign is smaller 3981 * * %1 - @s2__ign is smaller 3982 * * %-EFAULT - Cannot read one of the strings 3983 * * %-E2BIG - One of strings is too large 3984 * * %-ERANGE - One of strings is outside of kernel address space 3985 */ 3986 __bpf_kfunc int bpf_strncasecmp(const char *s1__ign, const char *s2__ign, size_t len) 3987 { 3988 return __bpf_strncasecmp(s1__ign, s2__ign, true, len); 3989 } 3990 3991 /** 3992 * bpf_strnchr - Find a character in a length limited string 3993 * @s__ign: The string to be searched 3994 * @count: The number of characters to be searched 3995 * @c: The character to search for 3996 * 3997 * Note that the %NUL-terminator is considered part of the string, and can 3998 * be searched for. 3999 * 4000 * Return: 4001 * * >=0 - Index of the first occurrence of @c within @s__ign 4002 * * %-ENOENT - @c not found in the first @count characters of @s__ign 4003 * * %-EFAULT - Cannot read @s__ign 4004 * * %-E2BIG - @s__ign is too large 4005 * * %-ERANGE - @s__ign is outside of kernel address space 4006 */ 4007 __bpf_kfunc int bpf_strnchr(const char *s__ign, size_t count, char c) 4008 { 4009 char sc; 4010 int i; 4011 4012 if (!copy_from_kernel_nofault_allowed(s__ign, 1)) 4013 return -ERANGE; 4014 4015 guard(pagefault)(); 4016 for (i = 0; i < count && i < XATTR_SIZE_MAX; i++) { 4017 __get_kernel_nofault(&sc, s__ign, char, err_out); 4018 if (sc == c) 4019 return i; 4020 if (sc == '\0') 4021 return -ENOENT; 4022 s__ign++; 4023 } 4024 return i == XATTR_SIZE_MAX ? -E2BIG : -ENOENT; 4025 err_out: 4026 return -EFAULT; 4027 } 4028 4029 /** 4030 * bpf_strchr - Find the first occurrence of a character in a string 4031 * @s__ign: The string to be searched 4032 * @c: The character to search for 4033 * 4034 * Note that the %NUL-terminator is considered part of the string, and can 4035 * be searched for. 4036 * 4037 * Return: 4038 * * >=0 - The index of the first occurrence of @c within @s__ign 4039 * * %-ENOENT - @c not found in @s__ign 4040 * * %-EFAULT - Cannot read @s__ign 4041 * * %-E2BIG - @s__ign is too large 4042 * * %-ERANGE - @s__ign is outside of kernel address space 4043 */ 4044 __bpf_kfunc int bpf_strchr(const char *s__ign, char c) 4045 { 4046 return bpf_strnchr(s__ign, XATTR_SIZE_MAX, c); 4047 } 4048 4049 /** 4050 * bpf_strchrnul - Find and return a character in a string, or end of string 4051 * @s__ign: The string to be searched 4052 * @c: The character to search for 4053 * 4054 * Return: 4055 * * >=0 - Index of the first occurrence of @c within @s__ign or index of 4056 * the null byte at the end of @s__ign when @c is not found 4057 * * %-EFAULT - Cannot read @s__ign 4058 * * %-E2BIG - @s__ign is too large 4059 * * %-ERANGE - @s__ign is outside of kernel address space 4060 */ 4061 __bpf_kfunc int bpf_strchrnul(const char *s__ign, char c) 4062 { 4063 char sc; 4064 int i; 4065 4066 if (!copy_from_kernel_nofault_allowed(s__ign, 1)) 4067 return -ERANGE; 4068 4069 guard(pagefault)(); 4070 for (i = 0; i < XATTR_SIZE_MAX; i++) { 4071 __get_kernel_nofault(&sc, s__ign, char, err_out); 4072 if (sc == '\0' || sc == c) 4073 return i; 4074 s__ign++; 4075 } 4076 return -E2BIG; 4077 err_out: 4078 return -EFAULT; 4079 } 4080 4081 /** 4082 * bpf_strrchr - Find the last occurrence of a character in a string 4083 * @s__ign: The string to be searched 4084 * @c: The character to search for 4085 * 4086 * Return: 4087 * * >=0 - Index of the last occurrence of @c within @s__ign 4088 * * %-ENOENT - @c not found in @s__ign 4089 * * %-EFAULT - Cannot read @s__ign 4090 * * %-E2BIG - @s__ign is too large 4091 * * %-ERANGE - @s__ign is outside of kernel address space 4092 */ 4093 __bpf_kfunc int bpf_strrchr(const char *s__ign, int c) 4094 { 4095 char sc; 4096 int i, last = -ENOENT; 4097 4098 if (!copy_from_kernel_nofault_allowed(s__ign, 1)) 4099 return -ERANGE; 4100 4101 guard(pagefault)(); 4102 for (i = 0; i < XATTR_SIZE_MAX; i++) { 4103 __get_kernel_nofault(&sc, s__ign, char, err_out); 4104 if (sc == c) 4105 last = i; 4106 if (sc == '\0') 4107 return last; 4108 s__ign++; 4109 } 4110 return -E2BIG; 4111 err_out: 4112 return -EFAULT; 4113 } 4114 4115 /** 4116 * bpf_strnlen - Calculate the length of a length-limited string 4117 * @s__ign: The string 4118 * @count: The maximum number of characters to count 4119 * 4120 * Return: 4121 * * >=0 - The length of @s__ign 4122 * * %-EFAULT - Cannot read @s__ign 4123 * * %-E2BIG - @s__ign is too large 4124 * * %-ERANGE - @s__ign is outside of kernel address space 4125 */ 4126 __bpf_kfunc int bpf_strnlen(const char *s__ign, size_t count) 4127 { 4128 char c; 4129 int i; 4130 4131 if (!copy_from_kernel_nofault_allowed(s__ign, 1)) 4132 return -ERANGE; 4133 4134 guard(pagefault)(); 4135 for (i = 0; i < count && i < XATTR_SIZE_MAX; i++) { 4136 __get_kernel_nofault(&c, s__ign, char, err_out); 4137 if (c == '\0') 4138 return i; 4139 s__ign++; 4140 } 4141 return i == XATTR_SIZE_MAX ? -E2BIG : i; 4142 err_out: 4143 return -EFAULT; 4144 } 4145 4146 /** 4147 * bpf_strlen - Calculate the length of a string 4148 * @s__ign: The string 4149 * 4150 * Return: 4151 * * >=0 - The length of @s__ign 4152 * * %-EFAULT - Cannot read @s__ign 4153 * * %-E2BIG - @s__ign is too large 4154 * * %-ERANGE - @s__ign is outside of kernel address space 4155 */ 4156 __bpf_kfunc int bpf_strlen(const char *s__ign) 4157 { 4158 return bpf_strnlen(s__ign, XATTR_SIZE_MAX); 4159 } 4160 4161 /** 4162 * bpf_strspn - Calculate the length of the initial substring of @s__ign which 4163 * only contains letters in @accept__ign 4164 * @s__ign: The string to be searched 4165 * @accept__ign: The string to search for 4166 * 4167 * Return: 4168 * * >=0 - The length of the initial substring of @s__ign which only 4169 * contains letters from @accept__ign 4170 * * %-EFAULT - Cannot read one of the strings 4171 * * %-E2BIG - One of the strings is too large 4172 * * %-ERANGE - One of the strings is outside of kernel address space 4173 */ 4174 __bpf_kfunc int bpf_strspn(const char *s__ign, const char *accept__ign) 4175 { 4176 char cs, ca; 4177 int i, j; 4178 4179 if (!copy_from_kernel_nofault_allowed(s__ign, 1) || 4180 !copy_from_kernel_nofault_allowed(accept__ign, 1)) { 4181 return -ERANGE; 4182 } 4183 4184 guard(pagefault)(); 4185 for (i = 0; i < XATTR_SIZE_MAX; i++) { 4186 __get_kernel_nofault(&cs, s__ign, char, err_out); 4187 if (cs == '\0') 4188 return i; 4189 for (j = 0; j < XATTR_SIZE_MAX; j++) { 4190 __get_kernel_nofault(&ca, accept__ign + j, char, err_out); 4191 if (cs == ca || ca == '\0') 4192 break; 4193 } 4194 if (j == XATTR_SIZE_MAX) 4195 return -E2BIG; 4196 if (ca == '\0') 4197 return i; 4198 s__ign++; 4199 } 4200 return -E2BIG; 4201 err_out: 4202 return -EFAULT; 4203 } 4204 4205 /** 4206 * bpf_strcspn - Calculate the length of the initial substring of @s__ign which 4207 * does not contain letters in @reject__ign 4208 * @s__ign: The string to be searched 4209 * @reject__ign: The string to search for 4210 * 4211 * Return: 4212 * * >=0 - The length of the initial substring of @s__ign which does not 4213 * contain letters from @reject__ign 4214 * * %-EFAULT - Cannot read one of the strings 4215 * * %-E2BIG - One of the strings is too large 4216 * * %-ERANGE - One of the strings is outside of kernel address space 4217 */ 4218 __bpf_kfunc int bpf_strcspn(const char *s__ign, const char *reject__ign) 4219 { 4220 char cs, cr; 4221 int i, j; 4222 4223 if (!copy_from_kernel_nofault_allowed(s__ign, 1) || 4224 !copy_from_kernel_nofault_allowed(reject__ign, 1)) { 4225 return -ERANGE; 4226 } 4227 4228 guard(pagefault)(); 4229 for (i = 0; i < XATTR_SIZE_MAX; i++) { 4230 __get_kernel_nofault(&cs, s__ign, char, err_out); 4231 if (cs == '\0') 4232 return i; 4233 for (j = 0; j < XATTR_SIZE_MAX; j++) { 4234 __get_kernel_nofault(&cr, reject__ign + j, char, err_out); 4235 if (cs == cr || cr == '\0') 4236 break; 4237 } 4238 if (j == XATTR_SIZE_MAX) 4239 return -E2BIG; 4240 if (cr != '\0') 4241 return i; 4242 s__ign++; 4243 } 4244 return -E2BIG; 4245 err_out: 4246 return -EFAULT; 4247 } 4248 4249 static int __bpf_strnstr(const char *s1, const char *s2, size_t len, 4250 bool ignore_case) 4251 { 4252 char c1, c2; 4253 int i, j; 4254 4255 if (!copy_from_kernel_nofault_allowed(s1, 1) || 4256 !copy_from_kernel_nofault_allowed(s2, 1)) { 4257 return -ERANGE; 4258 } 4259 4260 guard(pagefault)(); 4261 for (i = 0; i < XATTR_SIZE_MAX; i++) { 4262 for (j = 0; i + j <= len && j < XATTR_SIZE_MAX; j++) { 4263 __get_kernel_nofault(&c2, s2 + j, char, err_out); 4264 if (c2 == '\0') 4265 return i; 4266 /* 4267 * We allow reading an extra byte from s2 (note the 4268 * `i + j <= len` above) to cover the case when s2 is 4269 * a suffix of the first len chars of s1. 4270 */ 4271 if (i + j == len) 4272 break; 4273 __get_kernel_nofault(&c1, s1 + j, char, err_out); 4274 4275 if (ignore_case) { 4276 c1 = tolower(c1); 4277 c2 = tolower(c2); 4278 } 4279 4280 if (c1 == '\0') 4281 return -ENOENT; 4282 if (c1 != c2) 4283 break; 4284 } 4285 if (j == XATTR_SIZE_MAX) 4286 return -E2BIG; 4287 if (i + j == len) 4288 return -ENOENT; 4289 s1++; 4290 } 4291 return -E2BIG; 4292 err_out: 4293 return -EFAULT; 4294 } 4295 4296 /** 4297 * bpf_strstr - Find the first substring in a string 4298 * @s1__ign: The string to be searched 4299 * @s2__ign: The string to search for 4300 * 4301 * Return: 4302 * * >=0 - Index of the first character of the first occurrence of @s2__ign 4303 * within @s1__ign 4304 * * %-ENOENT - @s2__ign is not a substring of @s1__ign 4305 * * %-EFAULT - Cannot read one of the strings 4306 * * %-E2BIG - One of the strings is too large 4307 * * %-ERANGE - One of the strings is outside of kernel address space 4308 */ 4309 __bpf_kfunc int bpf_strstr(const char *s1__ign, const char *s2__ign) 4310 { 4311 return __bpf_strnstr(s1__ign, s2__ign, XATTR_SIZE_MAX, false); 4312 } 4313 4314 /** 4315 * bpf_strcasestr - Find the first substring in a string, ignoring the case of 4316 * the characters 4317 * @s1__ign: The string to be searched 4318 * @s2__ign: The string to search for 4319 * 4320 * Return: 4321 * * >=0 - Index of the first character of the first occurrence of @s2__ign 4322 * within @s1__ign 4323 * * %-ENOENT - @s2__ign is not a substring of @s1__ign 4324 * * %-EFAULT - Cannot read one of the strings 4325 * * %-E2BIG - One of the strings is too large 4326 * * %-ERANGE - One of the strings is outside of kernel address space 4327 */ 4328 __bpf_kfunc int bpf_strcasestr(const char *s1__ign, const char *s2__ign) 4329 { 4330 return __bpf_strnstr(s1__ign, s2__ign, XATTR_SIZE_MAX, true); 4331 } 4332 4333 /** 4334 * bpf_strnstr - Find the first substring in a length-limited string 4335 * @s1__ign: The string to be searched 4336 * @s2__ign: The string to search for 4337 * @len: the maximum number of characters to search 4338 * 4339 * Return: 4340 * * >=0 - Index of the first character of the first occurrence of @s2__ign 4341 * within the first @len characters of @s1__ign 4342 * * %-ENOENT - @s2__ign not found in the first @len characters of @s1__ign 4343 * * %-EFAULT - Cannot read one of the strings 4344 * * %-E2BIG - One of the strings is too large 4345 * * %-ERANGE - One of the strings is outside of kernel address space 4346 */ 4347 __bpf_kfunc int bpf_strnstr(const char *s1__ign, const char *s2__ign, 4348 size_t len) 4349 { 4350 return __bpf_strnstr(s1__ign, s2__ign, len, false); 4351 } 4352 4353 /** 4354 * bpf_strncasestr - Find the first substring in a length-limited string, 4355 * ignoring the case of the characters 4356 * @s1__ign: The string to be searched 4357 * @s2__ign: The string to search for 4358 * @len: the maximum number of characters to search 4359 * 4360 * Return: 4361 * * >=0 - Index of the first character of the first occurrence of @s2__ign 4362 * within the first @len characters of @s1__ign 4363 * * %-ENOENT - @s2__ign not found in the first @len characters of @s1__ign 4364 * * %-EFAULT - Cannot read one of the strings 4365 * * %-E2BIG - One of the strings is too large 4366 * * %-ERANGE - One of the strings is outside of kernel address space 4367 */ 4368 __bpf_kfunc int bpf_strncasestr(const char *s1__ign, const char *s2__ign, 4369 size_t len) 4370 { 4371 return __bpf_strnstr(s1__ign, s2__ign, len, true); 4372 } 4373 4374 #ifdef CONFIG_KEYS 4375 /** 4376 * bpf_lookup_user_key - lookup a key by its serial 4377 * @serial: key handle serial number 4378 * @flags: lookup-specific flags 4379 * 4380 * Search a key with a given *serial* and the provided *flags*. 4381 * If found, increment the reference count of the key by one, and 4382 * return it in the bpf_key structure. 4383 * 4384 * The bpf_key structure must be passed to bpf_key_put() when done 4385 * with it, so that the key reference count is decremented and the 4386 * bpf_key structure is freed. 4387 * 4388 * Permission checks are deferred to the time the key is used by 4389 * one of the available key-specific kfuncs. 4390 * 4391 * Set *flags* with KEY_LOOKUP_CREATE, to attempt creating a requested 4392 * special keyring (e.g. session keyring), if it doesn't yet exist. 4393 * Set *flags* with KEY_LOOKUP_PARTIAL, to lookup a key without waiting 4394 * for the key construction, and to retrieve uninstantiated keys (keys 4395 * without data attached to them). 4396 * 4397 * Return: a bpf_key pointer with a valid key pointer if the key is found, a 4398 * NULL pointer otherwise. 4399 */ 4400 __bpf_kfunc struct bpf_key *bpf_lookup_user_key(s32 serial, u64 flags) 4401 { 4402 key_ref_t key_ref; 4403 struct bpf_key *bkey; 4404 4405 if (flags & ~KEY_LOOKUP_ALL) 4406 return NULL; 4407 4408 /* 4409 * Permission check is deferred until the key is used, as the 4410 * intent of the caller is unknown here. 4411 */ 4412 key_ref = lookup_user_key(serial, flags, KEY_DEFER_PERM_CHECK); 4413 if (IS_ERR(key_ref)) 4414 return NULL; 4415 4416 bkey = kmalloc_obj(*bkey); 4417 if (!bkey) { 4418 key_put(key_ref_to_ptr(key_ref)); 4419 return NULL; 4420 } 4421 4422 bkey->key = key_ref_to_ptr(key_ref); 4423 bkey->has_ref = true; 4424 4425 return bkey; 4426 } 4427 4428 /** 4429 * bpf_lookup_system_key - lookup a key by a system-defined ID 4430 * @id: key ID 4431 * 4432 * Obtain a bpf_key structure with a key pointer set to the passed key ID. 4433 * The key pointer is marked as invalid, to prevent bpf_key_put() from 4434 * attempting to decrement the key reference count on that pointer. The key 4435 * pointer set in such way is currently understood only by 4436 * verify_pkcs7_signature(). 4437 * 4438 * Set *id* to one of the values defined in include/linux/verification.h: 4439 * 0 for the primary keyring (immutable keyring of system keys); 4440 * VERIFY_USE_SECONDARY_KEYRING for both the primary and secondary keyring 4441 * (where keys can be added only if they are vouched for by existing keys 4442 * in those keyrings); VERIFY_USE_PLATFORM_KEYRING for the platform 4443 * keyring (primarily used by the integrity subsystem to verify a kexec'ed 4444 * kerned image and, possibly, the initramfs signature). 4445 * 4446 * Return: a bpf_key pointer with an invalid key pointer set from the 4447 * pre-determined ID on success, a NULL pointer otherwise 4448 */ 4449 __bpf_kfunc struct bpf_key *bpf_lookup_system_key(u64 id) 4450 { 4451 struct bpf_key *bkey; 4452 4453 if (system_keyring_id_check(id) < 0) 4454 return NULL; 4455 4456 bkey = kmalloc_obj(*bkey, GFP_ATOMIC); 4457 if (!bkey) 4458 return NULL; 4459 4460 bkey->key = (struct key *)(unsigned long)id; 4461 bkey->has_ref = false; 4462 4463 return bkey; 4464 } 4465 4466 /** 4467 * bpf_key_put - decrement key reference count if key is valid and free bpf_key 4468 * @bkey: bpf_key structure 4469 * 4470 * Decrement the reference count of the key inside *bkey*, if the pointer 4471 * is valid, and free *bkey*. 4472 */ 4473 __bpf_kfunc void bpf_key_put(struct bpf_key *bkey) 4474 { 4475 if (bkey->has_ref) 4476 key_put(bkey->key); 4477 4478 kfree(bkey); 4479 } 4480 4481 /** 4482 * bpf_verify_pkcs7_signature - verify a PKCS#7 signature 4483 * @data_p: data to verify 4484 * @sig_p: signature of the data 4485 * @trusted_keyring: keyring with keys trusted for signature verification 4486 * 4487 * Verify the PKCS#7 signature *sig_ptr* against the supplied *data_ptr* 4488 * with keys in a keyring referenced by *trusted_keyring*. 4489 * 4490 * Return: 0 on success, a negative value on error. 4491 */ 4492 __bpf_kfunc int bpf_verify_pkcs7_signature(const struct bpf_dynptr *data_p, 4493 const struct bpf_dynptr *sig_p, 4494 struct bpf_key *trusted_keyring) 4495 { 4496 #ifdef CONFIG_SYSTEM_DATA_VERIFICATION 4497 const struct bpf_dynptr_kern *data_ptr = (struct bpf_dynptr_kern *)data_p; 4498 const struct bpf_dynptr_kern *sig_ptr = (struct bpf_dynptr_kern *)sig_p; 4499 const void *data, *sig; 4500 u32 data_len, sig_len; 4501 int ret; 4502 4503 if (trusted_keyring->has_ref) { 4504 /* 4505 * Do the permission check deferred in bpf_lookup_user_key(). 4506 * See bpf_lookup_user_key() for more details. 4507 * 4508 * A call to key_task_permission() here would be redundant, as 4509 * it is already done by keyring_search() called by 4510 * find_asymmetric_key(). 4511 */ 4512 ret = key_validate(trusted_keyring->key); 4513 if (ret < 0) 4514 return ret; 4515 } 4516 4517 data_len = __bpf_dynptr_size(data_ptr); 4518 data = __bpf_dynptr_data(data_ptr, data_len); 4519 if (!data) 4520 return -EINVAL; 4521 4522 sig_len = __bpf_dynptr_size(sig_ptr); 4523 sig = __bpf_dynptr_data(sig_ptr, sig_len); 4524 if (!sig) 4525 return -EINVAL; 4526 4527 return verify_pkcs7_signature(data, data_len, sig, sig_len, 4528 trusted_keyring->key, 4529 VERIFYING_BPF_SIGNATURE, NULL, 4530 NULL); 4531 #else 4532 return -EOPNOTSUPP; 4533 #endif /* CONFIG_SYSTEM_DATA_VERIFICATION */ 4534 } 4535 #endif /* CONFIG_KEYS */ 4536 4537 typedef int (*bpf_task_work_callback_t)(struct bpf_map *map, void *key, void *value); 4538 4539 enum bpf_task_work_state { 4540 /* bpf_task_work is ready to be used */ 4541 BPF_TW_STANDBY = 0, 4542 /* irq work scheduling in progress */ 4543 BPF_TW_PENDING, 4544 /* task work scheduling in progress */ 4545 BPF_TW_SCHEDULING, 4546 /* task work is scheduled successfully */ 4547 BPF_TW_SCHEDULED, 4548 /* callback is running */ 4549 BPF_TW_RUNNING, 4550 /* associated BPF map value is deleted */ 4551 BPF_TW_FREED, 4552 }; 4553 4554 struct bpf_task_work_ctx { 4555 enum bpf_task_work_state state; 4556 refcount_t refcnt; 4557 struct callback_head work; 4558 struct irq_work irq_work; 4559 /* bpf_prog that schedules task work */ 4560 struct bpf_prog *prog; 4561 /* task for which callback is scheduled */ 4562 struct task_struct *task; 4563 /* the map and map value associated with this context */ 4564 struct bpf_map *map; 4565 void *map_val; 4566 enum task_work_notify_mode mode; 4567 bpf_callback_t callback_fn; 4568 struct rcu_head rcu; 4569 } __aligned(8); 4570 4571 /* Actual type for struct bpf_task_work */ 4572 struct bpf_task_work_kern { 4573 struct bpf_task_work_ctx *ctx; 4574 }; 4575 4576 static void bpf_task_work_ctx_reset(struct bpf_task_work_ctx *ctx) 4577 { 4578 if (ctx->prog) { 4579 bpf_prog_put(ctx->prog); 4580 ctx->prog = NULL; 4581 } 4582 if (ctx->task) { 4583 bpf_task_release(ctx->task); 4584 ctx->task = NULL; 4585 } 4586 } 4587 4588 static bool bpf_task_work_ctx_tryget(struct bpf_task_work_ctx *ctx) 4589 { 4590 return refcount_inc_not_zero(&ctx->refcnt); 4591 } 4592 4593 static void bpf_task_work_destroy(struct irq_work *irq_work) 4594 { 4595 struct bpf_task_work_ctx *ctx = container_of(irq_work, struct bpf_task_work_ctx, irq_work); 4596 4597 bpf_task_work_ctx_reset(ctx); 4598 kfree_rcu(ctx, rcu); 4599 } 4600 4601 static void bpf_task_work_ctx_put(struct bpf_task_work_ctx *ctx) 4602 { 4603 if (!refcount_dec_and_test(&ctx->refcnt)) 4604 return; 4605 4606 if (irqs_disabled()) { 4607 ctx->irq_work = IRQ_WORK_INIT(bpf_task_work_destroy); 4608 irq_work_queue(&ctx->irq_work); 4609 } else { 4610 bpf_task_work_destroy(&ctx->irq_work); 4611 } 4612 } 4613 4614 static void bpf_task_work_cancel(struct bpf_task_work_ctx *ctx, 4615 struct task_struct *task) 4616 { 4617 /* 4618 * Scheduled task_work callback holds ctx ref, so if we successfully 4619 * cancelled, we put that ref on callback's behalf. If we couldn't 4620 * cancel, callback will inevitably run or has already completed 4621 * running, and it would have taken care of its ctx ref itself. 4622 * 4623 * The caller passes the task explicitly: the scheduling handler must 4624 * not read ctx->task after the work is published (the callback may 4625 * have reset it), while in the asynchronous cancellation path 4626 * ctx->task is stable, see bpf_task_work_cancel_scheduled(). 4627 */ 4628 if (task_work_cancel(task, &ctx->work)) 4629 bpf_task_work_ctx_put(ctx); 4630 } 4631 4632 static void bpf_task_work_callback(struct callback_head *cb) 4633 { 4634 struct bpf_task_work_ctx *ctx = container_of(cb, struct bpf_task_work_ctx, work); 4635 enum bpf_task_work_state state; 4636 u32 idx; 4637 void *key; 4638 4639 /* Read lock is needed to protect ctx and map key/value access */ 4640 guard(rcu_tasks_trace)(); 4641 /* 4642 * This callback may start running before bpf_task_work_irq() switched to 4643 * SCHEDULED state, so handle both transition variants SCHEDULING|SCHEDULED -> RUNNING. 4644 */ 4645 state = cmpxchg(&ctx->state, BPF_TW_SCHEDULING, BPF_TW_RUNNING); 4646 if (state == BPF_TW_SCHEDULED) 4647 state = cmpxchg(&ctx->state, BPF_TW_SCHEDULED, BPF_TW_RUNNING); 4648 if (state == BPF_TW_FREED) { 4649 bpf_task_work_ctx_put(ctx); 4650 return; 4651 } 4652 4653 key = (void *)map_key_from_value(ctx->map, ctx->map_val, &idx); 4654 4655 migrate_disable(); 4656 bpf_run_async_cb(ctx->prog, ctx->callback_fn, ctx->map, key, ctx->map_val); 4657 migrate_enable(); 4658 4659 bpf_task_work_ctx_reset(ctx); 4660 (void)cmpxchg(&ctx->state, BPF_TW_RUNNING, BPF_TW_STANDBY); 4661 4662 bpf_task_work_ctx_put(ctx); 4663 } 4664 4665 static void bpf_task_work_irq(struct irq_work *irq_work) 4666 { 4667 struct bpf_task_work_ctx *ctx = container_of(irq_work, struct bpf_task_work_ctx, irq_work); 4668 struct task_struct *task; 4669 enum bpf_task_work_state state; 4670 int err; 4671 4672 guard(rcu)(); 4673 4674 if (cmpxchg(&ctx->state, BPF_TW_PENDING, BPF_TW_SCHEDULING) != BPF_TW_PENDING) { 4675 bpf_task_work_ctx_put(ctx); 4676 return; 4677 } 4678 4679 /* 4680 * Capture the task pointer before the work is published: once the 4681 * callback runs, it may reset ctx->task. The capture happens while 4682 * this round's task reference is held, and every path that can 4683 * release it runs after this handler entered its rcu read-side 4684 * section. bpf_task_release() is put_task_struct_rcu_user(), so the 4685 * task_struct itself cannot be freed before this section ends. 4686 */ 4687 task = ctx->task; 4688 err = task_work_add(task, &ctx->work, ctx->mode); 4689 if (err) { 4690 bpf_task_work_ctx_reset(ctx); 4691 /* 4692 * try to switch back to STANDBY for another task_work reuse, but we might have 4693 * gone to FREED already, which is fine as we already cleaned up after ourselves 4694 */ 4695 (void)cmpxchg(&ctx->state, BPF_TW_SCHEDULING, BPF_TW_STANDBY); 4696 bpf_task_work_ctx_put(ctx); 4697 return; 4698 } 4699 4700 /* 4701 * It's technically possible for just scheduled task_work callback to 4702 * complete running by now, going SCHEDULING -> RUNNING, resetting 4703 * ctx->task and dropping its ctx refcount. The rcu read-side section 4704 * above keeps both the ctx memory and the captured task pointer 4705 * valid until this handler returns. 4706 */ 4707 state = cmpxchg(&ctx->state, BPF_TW_SCHEDULING, BPF_TW_SCHEDULED); 4708 if (state == BPF_TW_FREED) 4709 bpf_task_work_cancel(ctx, task); /* clean up if we switched into FREED state */ 4710 } 4711 4712 static struct bpf_task_work_ctx *bpf_task_work_fetch_ctx(struct bpf_task_work *tw, 4713 struct bpf_map *map) 4714 { 4715 struct bpf_task_work_kern *twk = (void *)tw; 4716 struct bpf_task_work_ctx *ctx, *old_ctx; 4717 4718 ctx = READ_ONCE(twk->ctx); 4719 if (ctx) 4720 return ctx; 4721 4722 ctx = bpf_map_kmalloc_nolock(map, sizeof(*ctx), 0, NUMA_NO_NODE); 4723 if (!ctx) 4724 return ERR_PTR(-ENOMEM); 4725 4726 memset(ctx, 0, sizeof(*ctx)); 4727 refcount_set(&ctx->refcnt, 1); /* map's own ref */ 4728 ctx->state = BPF_TW_STANDBY; 4729 init_irq_work(&ctx->irq_work, bpf_task_work_irq); 4730 4731 old_ctx = cmpxchg(&twk->ctx, NULL, ctx); 4732 if (old_ctx) { 4733 /* 4734 * tw->ctx is set by concurrent BPF program, release allocated 4735 * memory and try to reuse already set context. 4736 */ 4737 kfree_nolock(ctx); 4738 return old_ctx; 4739 } 4740 4741 return ctx; /* Success */ 4742 } 4743 4744 static struct bpf_task_work_ctx *bpf_task_work_acquire_ctx(struct bpf_task_work *tw, 4745 struct bpf_map *map) 4746 { 4747 struct bpf_task_work_ctx *ctx; 4748 4749 /* 4750 * Sleepable BPF programs hold rcu_read_lock_trace but not 4751 * regular rcu_read_lock. Since kfree_rcu waits for regular 4752 * RCU GP, the ctx can be freed while we're between reading 4753 * the pointer and incrementing the refcount. Take regular 4754 * rcu_read_lock to prevent kfree_rcu from freeing the ctx 4755 * before we can tryget it. 4756 */ 4757 scoped_guard(rcu) { 4758 ctx = bpf_task_work_fetch_ctx(tw, map); 4759 if (IS_ERR(ctx)) 4760 return ctx; 4761 4762 /* try to get ref for task_work callback to hold */ 4763 if (!bpf_task_work_ctx_tryget(ctx)) 4764 return ERR_PTR(-EBUSY); 4765 } 4766 4767 if (cmpxchg(&ctx->state, BPF_TW_STANDBY, BPF_TW_PENDING) != BPF_TW_STANDBY) { 4768 /* lost acquiring race or map_release_uref() stole it from us, put ref and bail */ 4769 bpf_task_work_ctx_put(ctx); 4770 return ERR_PTR(-EBUSY); 4771 } 4772 /* 4773 * STANDBY can be published before the previous scheduling irq_work 4774 * returns. Claim PENDING before checking BUSY to order the check after 4775 * that publication. No irq_work has been queued for this attempt yet, 4776 * so reject reuse and roll back to STANDBY while BUSY is set. Preserve 4777 * FREED if deletion wins the rollback race. 4778 */ 4779 if (unlikely(irq_work_is_busy(&ctx->irq_work))) { 4780 (void)cmpxchg(&ctx->state, BPF_TW_PENDING, BPF_TW_STANDBY); 4781 bpf_task_work_ctx_put(ctx); 4782 return ERR_PTR(-EBUSY); 4783 } 4784 4785 /* 4786 * If no process or bpffs is holding a reference to the map, no new callbacks should be 4787 * scheduled. This does not address any race or correctness issue, but rather is a policy 4788 * choice: dropping user references should stop everything. 4789 */ 4790 if (!atomic64_read(&map->usercnt)) { 4791 /* drop ref we just got for task_work callback itself */ 4792 bpf_task_work_ctx_put(ctx); 4793 /* transfer map's ref into cancel_and_free() */ 4794 bpf_task_work_cancel_and_free(tw); 4795 return ERR_PTR(-EBUSY); 4796 } 4797 4798 return ctx; 4799 } 4800 4801 static int bpf_task_work_schedule(struct task_struct *task, struct bpf_task_work *tw, 4802 struct bpf_map *map, void *callback_fn, 4803 struct bpf_prog_aux *aux, enum task_work_notify_mode mode) 4804 { 4805 struct bpf_prog *prog; 4806 struct bpf_task_work_ctx *ctx; 4807 int err; 4808 4809 BTF_TYPE_EMIT(struct bpf_task_work); 4810 4811 if (task->flags & PF_KTHREAD) 4812 return -EPERM; 4813 4814 prog = bpf_prog_inc_not_zero(aux->prog); 4815 if (IS_ERR(prog)) 4816 return -EBADF; 4817 task = bpf_task_acquire(task); 4818 if (!task) { 4819 err = -EBADF; 4820 goto release_prog; 4821 } 4822 4823 ctx = bpf_task_work_acquire_ctx(tw, map); 4824 if (IS_ERR(ctx)) { 4825 err = PTR_ERR(ctx); 4826 goto release_all; 4827 } 4828 4829 ctx->task = task; 4830 ctx->callback_fn = (bpf_callback_t)callback_fn; 4831 ctx->prog = prog; 4832 ctx->mode = mode; 4833 ctx->map = map; 4834 ctx->map_val = (void *)tw - map->record->task_work_off; 4835 init_task_work(&ctx->work, bpf_task_work_callback); 4836 4837 irq_work_queue(&ctx->irq_work); 4838 return 0; 4839 4840 release_all: 4841 bpf_task_release(task); 4842 release_prog: 4843 bpf_prog_put(prog); 4844 return err; 4845 } 4846 4847 /** 4848 * bpf_task_work_schedule_signal - Schedule BPF callback using task_work_add with TWA_SIGNAL 4849 * mode 4850 * @task: Task struct for which callback should be scheduled 4851 * @tw: Pointer to struct bpf_task_work in BPF map value for internal bookkeeping 4852 * @map__const_map: bpf_map that embeds struct bpf_task_work in the values 4853 * @callback: pointer to BPF subprogram to call 4854 * @aux: pointer to bpf_prog_aux of the caller BPF program, implicitly set by the verifier 4855 * 4856 * Return: 0 if task work has been scheduled successfully, negative error code otherwise 4857 */ 4858 __bpf_kfunc int bpf_task_work_schedule_signal(struct task_struct *task, struct bpf_task_work *tw, 4859 void *map__const_map, bpf_task_work_callback_t callback, 4860 struct bpf_prog_aux *aux) 4861 { 4862 return bpf_task_work_schedule(task, tw, map__const_map, callback, aux, TWA_SIGNAL); 4863 } 4864 4865 /** 4866 * bpf_task_work_schedule_resume - Schedule BPF callback using task_work_add with TWA_RESUME 4867 * mode 4868 * @task: Task struct for which callback should be scheduled 4869 * @tw: Pointer to struct bpf_task_work in BPF map value for internal bookkeeping 4870 * @map__const_map: bpf_map that embeds struct bpf_task_work in the values 4871 * @callback: pointer to BPF subprogram to call 4872 * @aux: pointer to bpf_prog_aux of the caller BPF program, implicitly set by the verifier 4873 * 4874 * Return: 0 if task work has been scheduled successfully, negative error code otherwise 4875 */ 4876 __bpf_kfunc int bpf_task_work_schedule_resume(struct task_struct *task, struct bpf_task_work *tw, 4877 void *map__const_map, bpf_task_work_callback_t callback, 4878 struct bpf_prog_aux *aux) 4879 { 4880 return bpf_task_work_schedule(task, tw, map__const_map, callback, aux, TWA_RESUME); 4881 } 4882 4883 typedef int (*bpf_rcu_callback_t)(struct bpf_map *map, void *key, void *value); 4884 4885 /* Actual type for struct bpf_rcu_head */ 4886 struct bpf_rcu_head_kern { 4887 struct rcu_head rcu; 4888 bpf_callback_t callback_fn; 4889 struct bpf_map *map; 4890 struct bpf_prog *prog; 4891 u32 armed; 4892 } __aligned(8); 4893 4894 static void bpf_rcu_run_callback(struct rcu_head *rcu) 4895 { 4896 struct bpf_rcu_head_kern *rh = container_of(rcu, struct bpf_rcu_head_kern, rcu); 4897 bpf_callback_t callback_fn = rh->callback_fn; 4898 struct bpf_prog *prog = rh->prog; 4899 struct bpf_map *map = rh->map; 4900 void *value, *key; 4901 u32 idx; 4902 4903 value = (void *)rh - map->record->rcu_head_off; 4904 key = map_key_from_value(map, value, &idx); 4905 4906 /* Pairs with the arming cmpxchg(): rh may be re-armed as soon as this store lands. */ 4907 smp_store_release(&rh->armed, 0); 4908 4909 rcu_read_lock_dont_migrate(); 4910 bpf_run_async_cb(prog, callback_fn, map, key, value); 4911 rcu_read_unlock_migrate(); 4912 4913 bpf_prog_put(prog); 4914 } 4915 4916 static int __bpf_call_rcu(struct bpf_rcu_head *rh, struct bpf_map *map, void *callback, 4917 struct bpf_prog_aux *aux, bool trace) 4918 { 4919 struct bpf_rcu_head_kern *rhk = (void *)rh; 4920 struct bpf_prog *prog; 4921 4922 BUILD_BUG_ON(sizeof(struct bpf_rcu_head_kern) > sizeof(struct bpf_rcu_head)); 4923 BUILD_BUG_ON(__alignof__(struct bpf_rcu_head_kern) != __alignof__(struct bpf_rcu_head)); 4924 BTF_TYPE_EMIT(struct bpf_rcu_head); 4925 4926 /* A queued callback cannot be cancelled, so a self-rearming one would pin prog and map. */ 4927 if (!atomic64_read(&map->usercnt)) 4928 return -EPERM; 4929 4930 if (cmpxchg(&rhk->armed, 0, 1)) 4931 return -EBUSY; 4932 4933 prog = bpf_prog_inc_not_zero(aux->prog); 4934 if (IS_ERR(prog)) { 4935 WRITE_ONCE(rhk->armed, 0); 4936 return -EBADF; 4937 } 4938 4939 rhk->callback_fn = (bpf_callback_t)callback; 4940 rhk->map = map; 4941 rhk->prog = prog; 4942 if (trace) 4943 call_rcu_tasks_trace(&rhk->rcu, bpf_rcu_run_callback); 4944 else 4945 call_rcu(&rhk->rcu, bpf_rcu_run_callback); 4946 return 0; 4947 } 4948 4949 /** 4950 * bpf_call_rcu - Invoke a BPF callback after an RCU grace period 4951 * @rh: struct bpf_rcu_head in a BPF map value 4952 * @map__const_map: bpf_map that embeds struct bpf_rcu_head in the values 4953 * @callback: BPF subprogram, invoked as callback(map, key, value) for the value holding @rh 4954 * @aux: bpf_prog_aux of the caller, implicitly set by the verifier 4955 * 4956 * Return: 0, -EBUSY if @rh is already queued, -EPERM if @map is held by neither a process 4957 * nor bpffs, or -EBADF if the calling program is going away. 4958 */ 4959 __bpf_kfunc int bpf_call_rcu(struct bpf_rcu_head *rh, void *map__const_map, 4960 bpf_rcu_callback_t callback, struct bpf_prog_aux *aux) 4961 { 4962 return __bpf_call_rcu(rh, map__const_map, callback, aux, false); 4963 } 4964 4965 /** 4966 * bpf_call_rcu_tasks_trace - Invoke a BPF callback after an RCU tasks trace grace period 4967 * @rh: struct bpf_rcu_head in a BPF map value 4968 * @map__const_map: bpf_map that embeds struct bpf_rcu_head in the values 4969 * @callback: BPF subprogram, invoked as callback(map, key, value) for the value holding @rh 4970 * @aux: bpf_prog_aux of the caller, implicitly set by the verifier 4971 * 4972 * Waits for sleepable BPF programs too. The callback itself is not sleepable either way. 4973 * 4974 * Return: 0, -EBUSY if @rh is already queued, -EPERM if @map is held by neither a process 4975 * nor bpffs, or -EBADF if the calling program is going away. 4976 */ 4977 __bpf_kfunc int bpf_call_rcu_tasks_trace(struct bpf_rcu_head *rh, void *map__const_map, 4978 bpf_rcu_callback_t callback, struct bpf_prog_aux *aux) 4979 { 4980 return __bpf_call_rcu(rh, map__const_map, callback, aux, true); 4981 } 4982 4983 static int make_file_dynptr(struct file *file, u32 flags, bool may_sleep, 4984 struct bpf_dynptr_kern *ptr) 4985 { 4986 struct bpf_dynptr_file_impl *state; 4987 4988 /* flags is currently unsupported */ 4989 if (flags) { 4990 bpf_dynptr_set_null(ptr); 4991 return -EINVAL; 4992 } 4993 4994 state = kmalloc_nolock(sizeof(*state), 0, NUMA_NO_NODE); 4995 if (!state) { 4996 bpf_dynptr_set_null(ptr); 4997 return -ENOMEM; 4998 } 4999 state->offset = 0; 5000 state->size = U64_MAX; /* Don't restrict size, as file may change anyways */ 5001 freader_init_from_file(&state->freader, NULL, 0, file, may_sleep); 5002 bpf_dynptr_init(ptr, state, BPF_DYNPTR_TYPE_FILE, 0, 0); 5003 bpf_dynptr_set_rdonly(ptr); 5004 return 0; 5005 } 5006 5007 __bpf_kfunc int bpf_dynptr_from_file(struct file *file, u32 flags, struct bpf_dynptr *ptr__uninit) 5008 { 5009 return make_file_dynptr(file, flags, false, (struct bpf_dynptr_kern *)ptr__uninit); 5010 } 5011 5012 int bpf_dynptr_from_file_sleepable(struct file *file, u32 flags, struct bpf_dynptr *ptr__uninit) 5013 { 5014 return make_file_dynptr(file, flags, true, (struct bpf_dynptr_kern *)ptr__uninit); 5015 } 5016 5017 __bpf_kfunc int bpf_dynptr_file_discard(struct bpf_dynptr *dynptr) 5018 { 5019 struct bpf_dynptr_kern *ptr = (struct bpf_dynptr_kern *)dynptr; 5020 struct bpf_dynptr_file_impl *df = ptr->data; 5021 5022 if (!df) 5023 return 0; 5024 5025 freader_cleanup(&df->freader); 5026 kfree_nolock(df); 5027 bpf_dynptr_set_null(ptr); 5028 return 0; 5029 } 5030 5031 /** 5032 * bpf_timer_cancel_async - try to deactivate a timer 5033 * @timer: bpf_timer to stop 5034 * 5035 * Returns: 5036 * 5037 * * 0 when the timer was not active 5038 * * 1 when the timer was active 5039 * * -1 when the timer is currently executing the callback function and 5040 * cannot be stopped 5041 * * -ECANCELED when the timer will be cancelled asynchronously 5042 * * -ENOMEM when out of memory 5043 * * -EINVAL when the timer was not initialized 5044 * * -ENOENT when this kfunc is racing with timer deletion 5045 */ 5046 __bpf_kfunc int bpf_timer_cancel_async(struct bpf_timer *timer) 5047 { 5048 struct bpf_async_kern *async = (void *)timer; 5049 struct bpf_async_cb *cb; 5050 int ret; 5051 5052 cb = READ_ONCE(async->cb); 5053 if (!cb) 5054 return -EINVAL; 5055 5056 /* 5057 * Unlike hrtimer_start() it's ok to synchronously call 5058 * hrtimer_try_to_cancel() when refcnt reached zero, but deferring to 5059 * irq_work is not, since irq callback may execute after RCU GP and 5060 * cb could be freed at that time. Check for refcnt zero for 5061 * consistency. 5062 */ 5063 if (!refcount_inc_not_zero(&cb->refcnt)) 5064 return -ENOENT; 5065 5066 if (!defer_timer_wq_op()) { 5067 struct bpf_hrtimer *t = container_of(cb, struct bpf_hrtimer, cb); 5068 5069 ret = hrtimer_try_to_cancel(&t->timer); 5070 bpf_async_refcount_put(cb); 5071 return ret; 5072 } else { 5073 ret = bpf_async_schedule_op(cb, BPF_ASYNC_CANCEL, 0, 0); 5074 return ret ? ret : -ECANCELED; 5075 } 5076 } 5077 5078 __bpf_kfunc_end_defs(); 5079 5080 static void bpf_task_work_cancel_scheduled(struct irq_work *irq_work) 5081 { 5082 struct bpf_task_work_ctx *ctx = container_of(irq_work, struct bpf_task_work_ctx, irq_work); 5083 5084 /* 5085 * Deletion observed SCHEDULED and won against the callback's 5086 * transition to RUNNING. The callback takes its FREED exit without 5087 * resetting ctx->task, and the transferred map reference prevents 5088 * destruction until cancellation completes. 5089 */ 5090 bpf_task_work_cancel(ctx, ctx->task); /* this might put task_work callback's ref */ 5091 bpf_task_work_ctx_put(ctx); /* and here we put map's own ref that was transferred to us */ 5092 } 5093 5094 void bpf_task_work_cancel_and_free(void *val) 5095 { 5096 struct bpf_task_work_kern *twk = val; 5097 struct bpf_task_work_ctx *ctx; 5098 enum bpf_task_work_state state; 5099 5100 ctx = xchg(&twk->ctx, NULL); 5101 if (!ctx) 5102 return; 5103 5104 state = xchg(&ctx->state, BPF_TW_FREED); 5105 if (state == BPF_TW_SCHEDULED) { 5106 /* run in irq_work to avoid locks in NMI */ 5107 init_irq_work(&ctx->irq_work, bpf_task_work_cancel_scheduled); 5108 irq_work_queue(&ctx->irq_work); 5109 return; 5110 } 5111 5112 bpf_task_work_ctx_put(ctx); /* put bpf map's ref */ 5113 } 5114 5115 BTF_KFUNCS_START(generic_btf_ids) 5116 #ifdef CONFIG_CRASH_DUMP 5117 BTF_ID_FLAGS(func, crash_kexec, KF_DESTRUCTIVE) 5118 #endif 5119 BTF_ID_FLAGS(func, bpf_obj_new, KF_ACQUIRE | KF_RET_NULL | KF_IMPLICIT_ARGS) 5120 BTF_ID_FLAGS(func, bpf_obj_new_impl, KF_ACQUIRE | KF_RET_NULL) 5121 BTF_ID_FLAGS(func, bpf_percpu_obj_new, KF_ACQUIRE | KF_RET_NULL | KF_IMPLICIT_ARGS) 5122 BTF_ID_FLAGS(func, bpf_percpu_obj_new_impl, KF_ACQUIRE | KF_RET_NULL) 5123 BTF_ID_FLAGS(func, bpf_obj_drop, KF_RELEASE | KF_IMPLICIT_ARGS) 5124 BTF_ID_FLAGS(func, bpf_obj_drop_impl, KF_RELEASE) 5125 BTF_ID_FLAGS(func, bpf_percpu_obj_drop, KF_RELEASE | KF_IMPLICIT_ARGS) 5126 BTF_ID_FLAGS(func, bpf_percpu_obj_drop_impl, KF_RELEASE) 5127 BTF_ID_FLAGS(func, bpf_refcount_acquire, 5128 KF_ACQUIRE | KF_RET_NULL | KF_RCU | KF_IMPLICIT_ARGS | KF_SPINLOCK_SAFE) 5129 BTF_ID_FLAGS(func, bpf_refcount_acquire_impl, 5130 KF_ACQUIRE | KF_RET_NULL | KF_RCU | KF_SPINLOCK_SAFE) 5131 BTF_ID_FLAGS(func, bpf_list_push_front, KF_IMPLICIT_ARGS | KF_SPINLOCK_SAFE) 5132 BTF_ID_FLAGS(func, bpf_list_push_front_impl, KF_SPINLOCK_SAFE) 5133 BTF_ID_FLAGS(func, bpf_list_push_back, KF_IMPLICIT_ARGS | KF_SPINLOCK_SAFE) 5134 BTF_ID_FLAGS(func, bpf_list_push_back_impl, KF_SPINLOCK_SAFE) 5135 BTF_ID_FLAGS(func, bpf_list_add, KF_IMPLICIT_ARGS | KF_SPINLOCK_SAFE) 5136 BTF_ID_FLAGS(func, bpf_list_pop_front, KF_ACQUIRE | KF_RET_NULL | KF_SPINLOCK_SAFE) 5137 BTF_ID_FLAGS(func, bpf_list_pop_back, KF_ACQUIRE | KF_RET_NULL | KF_SPINLOCK_SAFE) 5138 BTF_ID_FLAGS(func, bpf_list_del, KF_ACQUIRE | KF_RET_NULL | KF_SPINLOCK_SAFE) 5139 BTF_ID_FLAGS(func, bpf_list_front, KF_RET_NULL | KF_SPINLOCK_SAFE) 5140 BTF_ID_FLAGS(func, bpf_list_back, KF_RET_NULL | KF_SPINLOCK_SAFE) 5141 BTF_ID_FLAGS(func, bpf_list_is_first, KF_SPINLOCK_SAFE) 5142 BTF_ID_FLAGS(func, bpf_list_is_last, KF_SPINLOCK_SAFE) 5143 BTF_ID_FLAGS(func, bpf_list_empty, KF_SPINLOCK_SAFE) 5144 BTF_ID_FLAGS(func, bpf_task_acquire, KF_ACQUIRE | KF_RCU | KF_RET_NULL) 5145 BTF_ID_FLAGS(func, bpf_task_release, KF_RELEASE) 5146 BTF_ID_FLAGS(func, bpf_rbtree_remove, KF_ACQUIRE | KF_RET_NULL | KF_SPINLOCK_SAFE) 5147 BTF_ID_FLAGS(func, bpf_rbtree_add, KF_IMPLICIT_ARGS | KF_SPINLOCK_SAFE) 5148 BTF_ID_FLAGS(func, bpf_rbtree_add_impl, KF_SPINLOCK_SAFE) 5149 BTF_ID_FLAGS(func, bpf_rbtree_first, KF_RET_NULL | KF_SPINLOCK_SAFE) 5150 BTF_ID_FLAGS(func, bpf_rbtree_root, KF_RET_NULL | KF_SPINLOCK_SAFE) 5151 BTF_ID_FLAGS(func, bpf_rbtree_left, KF_RET_NULL | KF_SPINLOCK_SAFE) 5152 BTF_ID_FLAGS(func, bpf_rbtree_right, KF_RET_NULL | KF_SPINLOCK_SAFE) 5153 5154 #ifdef CONFIG_CGROUPS 5155 BTF_ID_FLAGS(func, bpf_cgroup_acquire, KF_ACQUIRE | KF_RCU | KF_RET_NULL) 5156 BTF_ID_FLAGS(func, bpf_cgroup_release, KF_RELEASE) 5157 BTF_ID_FLAGS(func, bpf_cgroup_ancestor, KF_ACQUIRE | KF_RCU | KF_RET_NULL) 5158 BTF_ID_FLAGS(func, bpf_cgroup_from_id, KF_ACQUIRE | KF_RET_NULL) 5159 BTF_ID_FLAGS(func, bpf_task_under_cgroup, KF_RCU) 5160 BTF_ID_FLAGS(func, bpf_task_get_cgroup1, KF_ACQUIRE | KF_RCU | KF_RET_NULL) 5161 #endif 5162 BTF_ID_FLAGS(func, bpf_task_from_pid, KF_ACQUIRE | KF_RET_NULL) 5163 BTF_ID_FLAGS(func, bpf_task_from_vpid, KF_ACQUIRE | KF_RET_NULL) 5164 BTF_ID_FLAGS(func, bpf_throw) 5165 #ifdef CONFIG_BPF_EVENTS 5166 BTF_ID_FLAGS(func, bpf_send_signal_task, KF_PERFMON) 5167 #endif 5168 #ifdef CONFIG_KEYS 5169 BTF_ID_FLAGS(func, bpf_lookup_user_key, KF_ACQUIRE | KF_RET_NULL | KF_SLEEPABLE) 5170 BTF_ID_FLAGS(func, bpf_lookup_system_key, KF_ACQUIRE | KF_RET_NULL) 5171 BTF_ID_FLAGS(func, bpf_key_put, KF_RELEASE) 5172 #ifdef CONFIG_SYSTEM_DATA_VERIFICATION 5173 BTF_ID_FLAGS(func, bpf_verify_pkcs7_signature, KF_SLEEPABLE) 5174 #endif 5175 #endif 5176 #ifdef CONFIG_S390 5177 BTF_ID_FLAGS(func, bpf_get_lowcore) 5178 #endif 5179 BTF_KFUNCS_END(generic_btf_ids) 5180 5181 static const struct btf_kfunc_id_set generic_kfunc_set = { 5182 .owner = THIS_MODULE, 5183 .set = &generic_btf_ids, 5184 }; 5185 5186 BTF_ID_LIST(generic_dtor_ids) 5187 BTF_ID(struct, task_struct) 5188 BTF_ID(func, bpf_task_release_dtor) 5189 #ifdef CONFIG_CGROUPS 5190 BTF_ID(struct, cgroup) 5191 BTF_ID(func, bpf_cgroup_release_dtor) 5192 #endif 5193 5194 BTF_KFUNCS_START(common_btf_ids) 5195 BTF_ID_FLAGS(func, bpf_cast_to_kern_ctx, KF_FASTCALL) 5196 BTF_ID_FLAGS(func, bpf_rdonly_cast, KF_FASTCALL | KF_PERFMON) 5197 BTF_ID_FLAGS(func, bpf_rcu_read_lock) 5198 BTF_ID_FLAGS(func, bpf_rcu_read_unlock) 5199 BTF_ID_FLAGS(func, bpf_dynptr_slice, KF_RET_NULL) 5200 BTF_ID_FLAGS(func, bpf_dynptr_slice_rdwr, KF_RET_NULL) 5201 BTF_ID_FLAGS(func, bpf_iter_num_new, KF_ITER_NEW | KF_SPINLOCK_SAFE) 5202 BTF_ID_FLAGS(func, bpf_iter_num_next, KF_ITER_NEXT | KF_RET_NULL | KF_SPINLOCK_SAFE) 5203 BTF_ID_FLAGS(func, bpf_iter_num_destroy, KF_ITER_DESTROY | KF_SPINLOCK_SAFE) 5204 BTF_ID_FLAGS(func, bpf_iter_task_vma_new, KF_ITER_NEW | KF_RCU) 5205 BTF_ID_FLAGS(func, bpf_iter_task_vma_next, KF_ITER_NEXT | KF_RET_NULL) 5206 BTF_ID_FLAGS(func, bpf_iter_task_vma_destroy, KF_ITER_DESTROY) 5207 #ifdef CONFIG_CGROUPS 5208 BTF_ID_FLAGS(func, bpf_iter_css_task_new, KF_ITER_NEW) 5209 BTF_ID_FLAGS(func, bpf_iter_css_task_next, KF_ITER_NEXT | KF_RET_NULL) 5210 BTF_ID_FLAGS(func, bpf_iter_css_task_destroy, KF_ITER_DESTROY) 5211 BTF_ID_FLAGS(func, bpf_iter_css_new, KF_ITER_NEW | KF_RCU_PROTECTED) 5212 BTF_ID_FLAGS(func, bpf_iter_css_next, KF_ITER_NEXT | KF_RET_NULL) 5213 BTF_ID_FLAGS(func, bpf_iter_css_destroy, KF_ITER_DESTROY) 5214 #endif 5215 BTF_ID_FLAGS(func, bpf_iter_task_new, KF_ITER_NEW | KF_RCU_PROTECTED) 5216 BTF_ID_FLAGS(func, bpf_iter_task_next, KF_ITER_NEXT | KF_RET_NULL) 5217 BTF_ID_FLAGS(func, bpf_iter_task_destroy, KF_ITER_DESTROY) 5218 BTF_ID_FLAGS(func, bpf_dynptr_adjust) 5219 BTF_ID_FLAGS(func, bpf_dynptr_is_null) 5220 BTF_ID_FLAGS(func, bpf_dynptr_is_rdonly) 5221 BTF_ID_FLAGS(func, bpf_dynptr_size) 5222 BTF_ID_FLAGS(func, bpf_dynptr_clone) 5223 BTF_ID_FLAGS(func, bpf_dynptr_copy) 5224 BTF_ID_FLAGS(func, bpf_dynptr_memset) 5225 #ifdef CONFIG_NET 5226 BTF_ID_FLAGS(func, bpf_modify_return_test_tp) 5227 #endif 5228 BTF_ID_FLAGS(func, bpf_wq_init) 5229 BTF_ID_FLAGS(func, bpf_wq_set_callback, KF_IMPLICIT_ARGS) 5230 BTF_ID_FLAGS(func, bpf_wq_start) 5231 BTF_ID_FLAGS(func, bpf_preempt_disable) 5232 BTF_ID_FLAGS(func, bpf_preempt_enable) 5233 BTF_ID_FLAGS(func, bpf_iter_bits_new, KF_ITER_NEW | KF_PERFMON) 5234 BTF_ID_FLAGS(func, bpf_iter_bits_next, KF_ITER_NEXT | KF_RET_NULL) 5235 BTF_ID_FLAGS(func, bpf_iter_bits_destroy, KF_ITER_DESTROY) 5236 BTF_ID_FLAGS(func, bpf_copy_from_user_str, KF_SLEEPABLE | KF_PERFMON) 5237 BTF_ID_FLAGS(func, bpf_copy_from_user_mm, KF_SLEEPABLE | KF_PERFMON) 5238 BTF_ID_FLAGS(func, bpf_copy_from_user_mm_str, KF_SLEEPABLE | KF_PERFMON) 5239 BTF_ID_FLAGS(func, bpf_copy_from_user_task_str, KF_SLEEPABLE | KF_PERFMON) 5240 BTF_ID_FLAGS(func, bpf_get_kmem_cache, KF_PERFMON) 5241 BTF_ID_FLAGS(func, bpf_iter_kmem_cache_new, KF_ITER_NEW | KF_SLEEPABLE) 5242 BTF_ID_FLAGS(func, bpf_iter_kmem_cache_next, KF_ITER_NEXT | KF_RET_NULL | KF_SLEEPABLE) 5243 BTF_ID_FLAGS(func, bpf_iter_kmem_cache_destroy, KF_ITER_DESTROY | KF_SLEEPABLE) 5244 BTF_ID_FLAGS(func, bpf_local_irq_save) 5245 BTF_ID_FLAGS(func, bpf_local_irq_restore) 5246 #ifdef CONFIG_BPF_EVENTS 5247 BTF_ID_FLAGS(func, bpf_probe_read_user_dynptr, KF_PERFMON) 5248 BTF_ID_FLAGS(func, bpf_probe_read_kernel_dynptr, KF_PERFMON) 5249 BTF_ID_FLAGS(func, bpf_probe_read_user_str_dynptr, KF_PERFMON) 5250 BTF_ID_FLAGS(func, bpf_probe_read_kernel_str_dynptr, KF_PERFMON) 5251 BTF_ID_FLAGS(func, bpf_copy_from_user_dynptr, KF_SLEEPABLE | KF_PERFMON) 5252 BTF_ID_FLAGS(func, bpf_copy_from_user_str_dynptr, KF_SLEEPABLE | KF_PERFMON) 5253 BTF_ID_FLAGS(func, bpf_copy_from_user_task_dynptr, KF_SLEEPABLE | KF_PERFMON) 5254 BTF_ID_FLAGS(func, bpf_copy_from_user_task_str_dynptr, KF_SLEEPABLE | KF_PERFMON) 5255 #endif 5256 #ifdef CONFIG_DMA_SHARED_BUFFER 5257 BTF_ID_FLAGS(func, bpf_iter_dmabuf_new, KF_ITER_NEW | KF_SLEEPABLE) 5258 BTF_ID_FLAGS(func, bpf_iter_dmabuf_next, KF_ITER_NEXT | KF_RET_NULL | KF_SLEEPABLE) 5259 BTF_ID_FLAGS(func, bpf_iter_dmabuf_destroy, KF_ITER_DESTROY | KF_SLEEPABLE) 5260 #endif 5261 BTF_ID_FLAGS(func, __bpf_trap) 5262 BTF_ID_FLAGS(func, bpf_strcmp, KF_PERFMON); 5263 BTF_ID_FLAGS(func, bpf_strcasecmp, KF_PERFMON); 5264 BTF_ID_FLAGS(func, bpf_strncasecmp, KF_PERFMON); 5265 BTF_ID_FLAGS(func, bpf_strchr, KF_PERFMON); 5266 BTF_ID_FLAGS(func, bpf_strchrnul, KF_PERFMON); 5267 BTF_ID_FLAGS(func, bpf_strnchr, KF_PERFMON); 5268 BTF_ID_FLAGS(func, bpf_strrchr, KF_PERFMON); 5269 BTF_ID_FLAGS(func, bpf_strlen, KF_PERFMON); 5270 BTF_ID_FLAGS(func, bpf_strnlen, KF_PERFMON); 5271 BTF_ID_FLAGS(func, bpf_strspn, KF_PERFMON); 5272 BTF_ID_FLAGS(func, bpf_strcspn, KF_PERFMON); 5273 BTF_ID_FLAGS(func, bpf_strstr, KF_PERFMON); 5274 BTF_ID_FLAGS(func, bpf_strcasestr, KF_PERFMON); 5275 BTF_ID_FLAGS(func, bpf_strnstr, KF_PERFMON); 5276 BTF_ID_FLAGS(func, bpf_strncasestr, KF_PERFMON); 5277 #if defined(CONFIG_BPF_LSM) && defined(CONFIG_CGROUPS) 5278 BTF_ID_FLAGS(func, bpf_cgroup_read_xattr, KF_RCU) 5279 #endif 5280 BTF_ID_FLAGS(func, bpf_stream_vprintk, KF_IMPLICIT_ARGS | KF_SPINLOCK_SAFE | KF_PERFMON) 5281 BTF_ID_FLAGS(func, bpf_stream_print_stack, KF_IMPLICIT_ARGS | KF_SPINLOCK_SAFE | KF_PERFMON) 5282 BTF_ID_FLAGS(func, bpf_task_work_schedule_signal, KF_IMPLICIT_ARGS | KF_PERFMON) 5283 BTF_ID_FLAGS(func, bpf_task_work_schedule_resume, KF_IMPLICIT_ARGS | KF_PERFMON) 5284 BTF_ID_FLAGS(func, bpf_call_rcu, KF_IMPLICIT_ARGS) 5285 BTF_ID_FLAGS(func, bpf_call_rcu_tasks_trace, KF_IMPLICIT_ARGS) 5286 BTF_ID_FLAGS(func, bpf_dynptr_from_file) 5287 BTF_ID_FLAGS(func, bpf_dynptr_file_discard, KF_RELEASE) 5288 BTF_ID_FLAGS(func, bpf_timer_cancel_async) 5289 BTF_KFUNCS_END(common_btf_ids) 5290 5291 static const struct btf_kfunc_id_set common_kfunc_set = { 5292 .owner = THIS_MODULE, 5293 .set = &common_btf_ids, 5294 }; 5295 5296 static int __init kfunc_init(void) 5297 { 5298 int ret; 5299 const struct btf_id_dtor_kfunc generic_dtors[] = { 5300 { 5301 .btf_id = generic_dtor_ids[0], 5302 .kfunc_btf_id = generic_dtor_ids[1] 5303 }, 5304 #ifdef CONFIG_CGROUPS 5305 { 5306 .btf_id = generic_dtor_ids[2], 5307 .kfunc_btf_id = generic_dtor_ids[3] 5308 }, 5309 #endif 5310 }; 5311 5312 ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_TRACING, &generic_kfunc_set); 5313 ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_SCHED_CLS, &generic_kfunc_set); 5314 ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_XDP, &generic_kfunc_set); 5315 ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS, &generic_kfunc_set); 5316 ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_SYSCALL, &generic_kfunc_set); 5317 ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_CGROUP_SKB, &generic_kfunc_set); 5318 ret = ret ?: register_btf_id_dtor_kfuncs(generic_dtors, 5319 ARRAY_SIZE(generic_dtors), 5320 THIS_MODULE); 5321 return ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_UNSPEC, &common_kfunc_set); 5322 } 5323 5324 late_initcall(kfunc_init); 5325 5326 /* Get a pointer to dynptr data up to len bytes for read only access. If 5327 * the dynptr doesn't have continuous data up to len bytes, return NULL. 5328 */ 5329 const void *__bpf_dynptr_data(const struct bpf_dynptr_kern *ptr, u64 len) 5330 { 5331 const struct bpf_dynptr *p = (struct bpf_dynptr *)ptr; 5332 5333 return bpf_dynptr_slice(p, 0, NULL, len); 5334 } 5335 5336 /* Get a pointer to dynptr data up to len bytes for read write access. If 5337 * the dynptr doesn't have continuous data up to len bytes, or the dynptr 5338 * is read only, return NULL. 5339 */ 5340 void *__bpf_dynptr_data_rw(const struct bpf_dynptr_kern *ptr, u64 len) 5341 { 5342 if (__bpf_dynptr_is_rdonly(ptr)) 5343 return NULL; 5344 return (void *)__bpf_dynptr_data(ptr, len); 5345 } 5346 5347 void bpf_map_free_internal_structs(struct bpf_map *map, void *val) 5348 { 5349 if (btf_record_has_field(map->record, BPF_TIMER)) 5350 bpf_obj_free_timer(map->record, val); 5351 if (btf_record_has_field(map->record, BPF_WORKQUEUE)) 5352 bpf_obj_free_workqueue(map->record, val); 5353 if (btf_record_has_field(map->record, BPF_TASK_WORK)) 5354 bpf_obj_free_task_work(map->record, val); 5355 } 5356