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