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 29 #include "../../lib/kstrtox.h" 30 31 /* If kernel subsystem is allowing eBPF programs to call this function, 32 * inside its own verifier_ops->get_func_proto() callback it should return 33 * bpf_map_lookup_elem_proto, so that verifier can properly check the arguments 34 * 35 * Different map implementations will rely on rcu in map methods 36 * lookup/update/delete, therefore eBPF programs must run under rcu lock 37 * if program is allowed to access maps, so check rcu_read_lock_held() or 38 * rcu_read_lock_trace_held() in all three functions. 39 */ 40 BPF_CALL_2(bpf_map_lookup_elem, struct bpf_map *, map, void *, key) 41 { 42 WARN_ON_ONCE(!rcu_read_lock_held() && !rcu_read_lock_trace_held() && 43 !rcu_read_lock_bh_held()); 44 return (unsigned long) map->ops->map_lookup_elem(map, key); 45 } 46 47 const struct bpf_func_proto bpf_map_lookup_elem_proto = { 48 .func = bpf_map_lookup_elem, 49 .gpl_only = false, 50 .pkt_access = true, 51 .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL, 52 .arg1_type = ARG_CONST_MAP_PTR, 53 .arg2_type = ARG_PTR_TO_MAP_KEY, 54 }; 55 56 BPF_CALL_4(bpf_map_update_elem, struct bpf_map *, map, void *, key, 57 void *, value, u64, flags) 58 { 59 WARN_ON_ONCE(!rcu_read_lock_held() && !rcu_read_lock_trace_held() && 60 !rcu_read_lock_bh_held()); 61 return map->ops->map_update_elem(map, key, value, flags); 62 } 63 64 const struct bpf_func_proto bpf_map_update_elem_proto = { 65 .func = bpf_map_update_elem, 66 .gpl_only = false, 67 .pkt_access = true, 68 .ret_type = RET_INTEGER, 69 .arg1_type = ARG_CONST_MAP_PTR, 70 .arg2_type = ARG_PTR_TO_MAP_KEY, 71 .arg3_type = ARG_PTR_TO_MAP_VALUE, 72 .arg4_type = ARG_ANYTHING, 73 }; 74 75 BPF_CALL_2(bpf_map_delete_elem, struct bpf_map *, map, void *, key) 76 { 77 WARN_ON_ONCE(!rcu_read_lock_held() && !rcu_read_lock_trace_held() && 78 !rcu_read_lock_bh_held()); 79 return map->ops->map_delete_elem(map, key); 80 } 81 82 const struct bpf_func_proto bpf_map_delete_elem_proto = { 83 .func = bpf_map_delete_elem, 84 .gpl_only = false, 85 .pkt_access = true, 86 .ret_type = RET_INTEGER, 87 .arg1_type = ARG_CONST_MAP_PTR, 88 .arg2_type = ARG_PTR_TO_MAP_KEY, 89 }; 90 91 BPF_CALL_3(bpf_map_push_elem, struct bpf_map *, map, void *, value, u64, flags) 92 { 93 return map->ops->map_push_elem(map, value, flags); 94 } 95 96 const struct bpf_func_proto bpf_map_push_elem_proto = { 97 .func = bpf_map_push_elem, 98 .gpl_only = false, 99 .pkt_access = true, 100 .ret_type = RET_INTEGER, 101 .arg1_type = ARG_CONST_MAP_PTR, 102 .arg2_type = ARG_PTR_TO_MAP_VALUE, 103 .arg3_type = ARG_ANYTHING, 104 }; 105 106 BPF_CALL_2(bpf_map_pop_elem, struct bpf_map *, map, void *, value) 107 { 108 return map->ops->map_pop_elem(map, value); 109 } 110 111 const struct bpf_func_proto bpf_map_pop_elem_proto = { 112 .func = bpf_map_pop_elem, 113 .gpl_only = false, 114 .ret_type = RET_INTEGER, 115 .arg1_type = ARG_CONST_MAP_PTR, 116 .arg2_type = ARG_PTR_TO_MAP_VALUE | MEM_UNINIT | MEM_WRITE, 117 }; 118 119 BPF_CALL_2(bpf_map_peek_elem, struct bpf_map *, map, void *, value) 120 { 121 return map->ops->map_peek_elem(map, value); 122 } 123 124 const struct bpf_func_proto bpf_map_peek_elem_proto = { 125 .func = bpf_map_peek_elem, 126 .gpl_only = false, 127 .ret_type = RET_INTEGER, 128 .arg1_type = ARG_CONST_MAP_PTR, 129 .arg2_type = ARG_PTR_TO_MAP_VALUE | MEM_UNINIT | MEM_WRITE, 130 }; 131 132 BPF_CALL_3(bpf_map_lookup_percpu_elem, struct bpf_map *, map, void *, key, u32, cpu) 133 { 134 WARN_ON_ONCE(!rcu_read_lock_held() && !rcu_read_lock_trace_held() && 135 !rcu_read_lock_bh_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_CONST_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_CONST_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_CONST_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_CONST_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_CONST_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_CONST_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_CONST_SIZE_OR_ZERO, 679 .arg3_type = ARG_ANYTHING, 680 }; 681 682 BPF_CALL_5(bpf_copy_from_user_task, void *, dst, u32, size, 683 const void __user *, user_ptr, struct task_struct *, tsk, u64, flags) 684 { 685 int ret; 686 687 /* flags is not used yet */ 688 if (unlikely(flags)) 689 return -EINVAL; 690 691 if (unlikely(!size)) 692 return 0; 693 694 ret = access_process_vm(tsk, (unsigned long)user_ptr, dst, size, 0); 695 if (ret == size) 696 return 0; 697 698 memset(dst, 0, size); 699 /* Return -EFAULT for partial read */ 700 return ret < 0 ? ret : -EFAULT; 701 } 702 703 const struct bpf_func_proto bpf_copy_from_user_task_proto = { 704 .func = bpf_copy_from_user_task, 705 .gpl_only = true, 706 .might_sleep = true, 707 .ret_type = RET_INTEGER, 708 .arg1_type = ARG_PTR_TO_UNINIT_MEM, 709 .arg2_type = ARG_CONST_SIZE_OR_ZERO, 710 .arg3_type = ARG_ANYTHING, 711 .arg4_type = ARG_PTR_TO_BTF_ID, 712 .arg4_btf_id = &btf_tracing_ids[BTF_TRACING_TYPE_TASK], 713 .arg5_type = ARG_ANYTHING 714 }; 715 716 BPF_CALL_2(bpf_per_cpu_ptr, const void *, ptr, u32, cpu) 717 { 718 if (cpu >= nr_cpu_ids) 719 return (unsigned long)NULL; 720 721 return (unsigned long)per_cpu_ptr((const void __percpu *)(const uintptr_t)ptr, cpu); 722 } 723 724 const struct bpf_func_proto bpf_per_cpu_ptr_proto = { 725 .func = bpf_per_cpu_ptr, 726 .gpl_only = false, 727 .ret_type = RET_PTR_TO_MEM_OR_BTF_ID | PTR_MAYBE_NULL | MEM_RDONLY, 728 .arg1_type = ARG_PTR_TO_PERCPU_BTF_ID, 729 .arg2_type = ARG_ANYTHING, 730 }; 731 732 BPF_CALL_1(bpf_this_cpu_ptr, const void *, percpu_ptr) 733 { 734 return (unsigned long)this_cpu_ptr((const void __percpu *)(const uintptr_t)percpu_ptr); 735 } 736 737 const struct bpf_func_proto bpf_this_cpu_ptr_proto = { 738 .func = bpf_this_cpu_ptr, 739 .gpl_only = false, 740 .ret_type = RET_PTR_TO_MEM_OR_BTF_ID | MEM_RDONLY, 741 .arg1_type = ARG_PTR_TO_PERCPU_BTF_ID, 742 }; 743 744 static int bpf_trace_copy_string(char *buf, void *unsafe_ptr, char fmt_ptype, 745 size_t bufsz) 746 { 747 void __user *user_ptr = (__force void __user *)unsafe_ptr; 748 749 buf[0] = 0; 750 751 switch (fmt_ptype) { 752 case 's': 753 #ifdef CONFIG_ARCH_HAS_NON_OVERLAPPING_ADDRESS_SPACE 754 if ((unsigned long)unsafe_ptr < TASK_SIZE) 755 return strncpy_from_user_nofault(buf, user_ptr, bufsz); 756 fallthrough; 757 #endif 758 case 'k': 759 return strncpy_from_kernel_nofault(buf, unsafe_ptr, bufsz); 760 case 'u': 761 return strncpy_from_user_nofault(buf, user_ptr, bufsz); 762 } 763 764 return -EINVAL; 765 } 766 767 /* Support executing three nested bprintf helper calls on a given CPU */ 768 #define MAX_BPRINTF_NEST_LEVEL 3 769 770 static DEFINE_PER_CPU(struct bpf_bprintf_buffers[MAX_BPRINTF_NEST_LEVEL], bpf_bprintf_bufs); 771 static DEFINE_PER_CPU(int, bpf_bprintf_nest_level); 772 773 int bpf_try_get_buffers(struct bpf_bprintf_buffers **bufs) 774 { 775 int nest_level; 776 777 nest_level = this_cpu_inc_return(bpf_bprintf_nest_level); 778 if (WARN_ON_ONCE(nest_level > MAX_BPRINTF_NEST_LEVEL)) { 779 this_cpu_dec(bpf_bprintf_nest_level); 780 return -EBUSY; 781 } 782 *bufs = this_cpu_ptr(&bpf_bprintf_bufs[nest_level - 1]); 783 784 return 0; 785 } 786 787 void bpf_put_buffers(void) 788 { 789 if (WARN_ON_ONCE(this_cpu_read(bpf_bprintf_nest_level) == 0)) 790 return; 791 this_cpu_dec(bpf_bprintf_nest_level); 792 } 793 794 void bpf_bprintf_cleanup(struct bpf_bprintf_data *data) 795 { 796 if (!data->bin_args && !data->buf) 797 return; 798 bpf_put_buffers(); 799 } 800 801 /* 802 * bpf_bprintf_prepare - Generic pass on format strings for bprintf-like helpers 803 * 804 * Returns a negative value if fmt is an invalid format string or 0 otherwise. 805 * 806 * This can be used in two ways: 807 * - Format string verification only: when data->get_bin_args is false 808 * - Arguments preparation: in addition to the above verification, it writes in 809 * data->bin_args a binary representation of arguments usable by bstr_printf 810 * where pointers from BPF have been sanitized. 811 * 812 * In argument preparation mode, if 0 is returned, safe temporary buffers are 813 * allocated and bpf_bprintf_cleanup should be called to free them after use. 814 */ 815 int bpf_bprintf_prepare(const char *fmt, u32 fmt_size, const u64 *raw_args, 816 u32 num_args, struct bpf_bprintf_data *data) 817 { 818 bool get_buffers = (data->get_bin_args && num_args) || data->get_buf; 819 char *unsafe_ptr = NULL, *tmp_buf = NULL, *tmp_buf_end, *fmt_end; 820 struct bpf_bprintf_buffers *buffers = NULL; 821 size_t sizeof_cur_arg, sizeof_cur_ip; 822 int err, i, num_spec = 0; 823 u64 cur_arg; 824 char fmt_ptype, cur_ip[16], ip_spec[] = "%pXX"; 825 826 fmt_end = strnchr(fmt, fmt_size, 0); 827 if (!fmt_end) 828 return -EINVAL; 829 fmt_size = fmt_end - fmt; 830 831 if (get_buffers && bpf_try_get_buffers(&buffers)) 832 return -EBUSY; 833 834 if (data->get_bin_args) { 835 if (num_args) 836 tmp_buf = buffers->bin_args; 837 tmp_buf_end = tmp_buf + MAX_BPRINTF_BIN_ARGS; 838 data->bin_args = (u32 *)tmp_buf; 839 } 840 841 if (data->get_buf) 842 data->buf = buffers->buf; 843 844 for (i = 0; i < fmt_size; i++) { 845 if ((!isprint(fmt[i]) && !isspace(fmt[i])) || !isascii(fmt[i])) { 846 err = -EINVAL; 847 goto out; 848 } 849 850 if (fmt[i] != '%') 851 continue; 852 853 if (fmt[i + 1] == '%') { 854 i++; 855 continue; 856 } 857 858 if (num_spec >= num_args) { 859 err = -EINVAL; 860 goto out; 861 } 862 863 /* The string is zero-terminated so if fmt[i] != 0, we can 864 * always access fmt[i + 1], in the worst case it will be a 0 865 */ 866 i++; 867 868 /* skip optional "[0 +-][num]" width formatting field */ 869 while (fmt[i] == '0' || fmt[i] == '+' || fmt[i] == '-' || 870 fmt[i] == ' ') 871 i++; 872 if (fmt[i] >= '1' && fmt[i] <= '9') { 873 i++; 874 while (fmt[i] >= '0' && fmt[i] <= '9') 875 i++; 876 } 877 878 if (fmt[i] == 'p') { 879 sizeof_cur_arg = sizeof(long); 880 881 if (fmt[i + 1] == 0 || isspace(fmt[i + 1]) || 882 ispunct(fmt[i + 1])) { 883 if (tmp_buf) 884 cur_arg = raw_args[num_spec]; 885 goto nocopy_fmt; 886 } 887 888 if ((fmt[i + 1] == 'k' || fmt[i + 1] == 'u') && 889 fmt[i + 2] == 's') { 890 fmt_ptype = fmt[i + 1]; 891 i += 2; 892 goto fmt_str; 893 } 894 895 if (fmt[i + 1] == 'K' || 896 fmt[i + 1] == 'x' || fmt[i + 1] == 's' || 897 fmt[i + 1] == 'S') { 898 if (tmp_buf) 899 cur_arg = raw_args[num_spec]; 900 i++; 901 goto nocopy_fmt; 902 } 903 904 if (fmt[i + 1] == 'B') { 905 if (tmp_buf) { 906 err = snprintf(tmp_buf, 907 (tmp_buf_end - tmp_buf), 908 "%pB", 909 (void *)(long)raw_args[num_spec]); 910 tmp_buf += (err + 1); 911 } 912 913 i++; 914 num_spec++; 915 continue; 916 } 917 918 /* only support "%pI4", "%pi4", "%pI6" and "%pi6". */ 919 if ((fmt[i + 1] != 'i' && fmt[i + 1] != 'I') || 920 (fmt[i + 2] != '4' && fmt[i + 2] != '6')) { 921 err = -EINVAL; 922 goto out; 923 } 924 925 i += 2; 926 if (!tmp_buf) 927 goto nocopy_fmt; 928 929 sizeof_cur_ip = (fmt[i] == '4') ? 4 : 16; 930 if (tmp_buf_end - tmp_buf < sizeof_cur_ip) { 931 err = -ENOSPC; 932 goto out; 933 } 934 935 unsafe_ptr = (char *)(long)raw_args[num_spec]; 936 err = copy_from_kernel_nofault(cur_ip, unsafe_ptr, 937 sizeof_cur_ip); 938 if (err < 0) 939 memset(cur_ip, 0, sizeof_cur_ip); 940 941 /* hack: bstr_printf expects IP addresses to be 942 * pre-formatted as strings, ironically, the easiest way 943 * to do that is to call snprintf. 944 */ 945 ip_spec[2] = fmt[i - 1]; 946 ip_spec[3] = fmt[i]; 947 err = snprintf(tmp_buf, tmp_buf_end - tmp_buf, 948 ip_spec, &cur_ip); 949 950 tmp_buf += err + 1; 951 num_spec++; 952 953 continue; 954 } else if (fmt[i] == 's') { 955 fmt_ptype = fmt[i]; 956 fmt_str: 957 if (fmt[i + 1] != 0 && 958 !isspace(fmt[i + 1]) && 959 !ispunct(fmt[i + 1])) { 960 err = -EINVAL; 961 goto out; 962 } 963 964 if (!tmp_buf) 965 goto nocopy_fmt; 966 967 if (tmp_buf_end == tmp_buf) { 968 err = -ENOSPC; 969 goto out; 970 } 971 972 unsafe_ptr = (char *)(long)raw_args[num_spec]; 973 err = bpf_trace_copy_string(tmp_buf, unsafe_ptr, 974 fmt_ptype, 975 tmp_buf_end - tmp_buf); 976 if (err < 0) { 977 tmp_buf[0] = '\0'; 978 err = 1; 979 } 980 981 tmp_buf += err; 982 num_spec++; 983 984 continue; 985 } else if (fmt[i] == 'c') { 986 if (!tmp_buf) 987 goto nocopy_fmt; 988 989 if (tmp_buf_end == tmp_buf) { 990 err = -ENOSPC; 991 goto out; 992 } 993 994 *tmp_buf = raw_args[num_spec]; 995 tmp_buf++; 996 num_spec++; 997 998 continue; 999 } 1000 1001 sizeof_cur_arg = sizeof(int); 1002 1003 if (fmt[i] == 'l') { 1004 sizeof_cur_arg = sizeof(long); 1005 i++; 1006 } 1007 if (fmt[i] == 'l') { 1008 sizeof_cur_arg = sizeof(long long); 1009 i++; 1010 } 1011 1012 if (fmt[i] != 'i' && fmt[i] != 'd' && fmt[i] != 'u' && 1013 fmt[i] != 'x' && fmt[i] != 'X') { 1014 err = -EINVAL; 1015 goto out; 1016 } 1017 1018 if (tmp_buf) 1019 cur_arg = raw_args[num_spec]; 1020 nocopy_fmt: 1021 if (tmp_buf) { 1022 tmp_buf = PTR_ALIGN(tmp_buf, sizeof(u32)); 1023 if (tmp_buf_end - tmp_buf < sizeof_cur_arg) { 1024 err = -ENOSPC; 1025 goto out; 1026 } 1027 1028 if (sizeof_cur_arg == 8) { 1029 *(u32 *)tmp_buf = *(u32 *)&cur_arg; 1030 *(u32 *)(tmp_buf + 4) = *((u32 *)&cur_arg + 1); 1031 } else { 1032 *(u32 *)tmp_buf = (u32)(long)cur_arg; 1033 } 1034 tmp_buf += sizeof_cur_arg; 1035 } 1036 num_spec++; 1037 } 1038 1039 err = 0; 1040 out: 1041 if (err) 1042 bpf_bprintf_cleanup(data); 1043 return err; 1044 } 1045 1046 BPF_CALL_5(bpf_snprintf, char *, str, u32, str_size, char *, fmt, 1047 const void *, args, u32, data_len) 1048 { 1049 struct bpf_bprintf_data data = { 1050 .get_bin_args = true, 1051 }; 1052 int err, num_args; 1053 1054 if (data_len % 8 || data_len > MAX_BPRINTF_VARARGS * 8 || 1055 (data_len && !args)) 1056 return -EINVAL; 1057 num_args = data_len / 8; 1058 1059 /* ARG_PTR_TO_CONST_STR guarantees that fmt is zero-terminated so we 1060 * can safely give an unbounded size. 1061 */ 1062 err = bpf_bprintf_prepare(fmt, UINT_MAX, args, num_args, &data); 1063 if (err < 0) 1064 return err; 1065 1066 err = bstr_printf(str, str_size, fmt, data.bin_args); 1067 1068 bpf_bprintf_cleanup(&data); 1069 1070 return err + 1; 1071 } 1072 1073 const struct bpf_func_proto bpf_snprintf_proto = { 1074 .func = bpf_snprintf, 1075 .gpl_only = true, 1076 .ret_type = RET_INTEGER, 1077 .arg1_type = ARG_PTR_TO_MEM_OR_NULL, 1078 .arg2_type = ARG_CONST_SIZE_OR_ZERO, 1079 .arg3_type = ARG_PTR_TO_CONST_STR, 1080 .arg4_type = ARG_PTR_TO_MEM | PTR_MAYBE_NULL | MEM_RDONLY, 1081 .arg5_type = ARG_CONST_SIZE_OR_ZERO, 1082 }; 1083 1084 struct bpf_async_cb { 1085 struct bpf_map *map; 1086 struct bpf_prog *prog; 1087 void __rcu *callback_fn; 1088 void *value; 1089 union { 1090 struct rcu_head rcu; 1091 struct work_struct delete_work; 1092 }; 1093 u64 flags; 1094 }; 1095 1096 /* BPF map elements can contain 'struct bpf_timer'. 1097 * Such map owns all of its BPF timers. 1098 * 'struct bpf_timer' is allocated as part of map element allocation 1099 * and it's zero initialized. 1100 * That space is used to keep 'struct bpf_async_kern'. 1101 * bpf_timer_init() allocates 'struct bpf_hrtimer', inits hrtimer, and 1102 * remembers 'struct bpf_map *' pointer it's part of. 1103 * bpf_timer_set_callback() increments prog refcnt and assign bpf callback_fn. 1104 * bpf_timer_start() arms the timer. 1105 * If user space reference to a map goes to zero at this point 1106 * ops->map_release_uref callback is responsible for cancelling the timers, 1107 * freeing their memory, and decrementing prog's refcnts. 1108 * bpf_timer_cancel() cancels the timer and decrements prog's refcnt. 1109 * Inner maps can contain bpf timers as well. ops->map_release_uref is 1110 * freeing the timers when inner map is replaced or deleted by user space. 1111 */ 1112 struct bpf_hrtimer { 1113 struct bpf_async_cb cb; 1114 struct hrtimer timer; 1115 atomic_t cancelling; 1116 }; 1117 1118 struct bpf_work { 1119 struct bpf_async_cb cb; 1120 struct work_struct work; 1121 struct work_struct delete_work; 1122 }; 1123 1124 /* the actual struct hidden inside uapi struct bpf_timer and bpf_wq */ 1125 struct bpf_async_kern { 1126 union { 1127 struct bpf_async_cb *cb; 1128 struct bpf_hrtimer *timer; 1129 struct bpf_work *work; 1130 }; 1131 /* bpf_spin_lock is used here instead of spinlock_t to make 1132 * sure that it always fits into space reserved by struct bpf_timer 1133 * regardless of LOCKDEP and spinlock debug flags. 1134 */ 1135 struct bpf_spin_lock lock; 1136 } __attribute__((aligned(8))); 1137 1138 enum bpf_async_type { 1139 BPF_ASYNC_TYPE_TIMER = 0, 1140 BPF_ASYNC_TYPE_WQ, 1141 }; 1142 1143 static DEFINE_PER_CPU(struct bpf_hrtimer *, hrtimer_running); 1144 1145 static enum hrtimer_restart bpf_timer_cb(struct hrtimer *hrtimer) 1146 { 1147 struct bpf_hrtimer *t = container_of(hrtimer, struct bpf_hrtimer, timer); 1148 struct bpf_map *map = t->cb.map; 1149 void *value = t->cb.value; 1150 bpf_callback_t callback_fn; 1151 void *key; 1152 u32 idx; 1153 1154 BTF_TYPE_EMIT(struct bpf_timer); 1155 callback_fn = rcu_dereference_check(t->cb.callback_fn, rcu_read_lock_bh_held()); 1156 if (!callback_fn) 1157 goto out; 1158 1159 /* bpf_timer_cb() runs in hrtimer_run_softirq. It doesn't migrate and 1160 * cannot be preempted by another bpf_timer_cb() on the same cpu. 1161 * Remember the timer this callback is servicing to prevent 1162 * deadlock if callback_fn() calls bpf_timer_cancel() or 1163 * bpf_map_delete_elem() on the same timer. 1164 */ 1165 this_cpu_write(hrtimer_running, t); 1166 if (map->map_type == BPF_MAP_TYPE_ARRAY) { 1167 struct bpf_array *array = container_of(map, struct bpf_array, map); 1168 1169 /* compute the key */ 1170 idx = ((char *)value - array->value) / array->elem_size; 1171 key = &idx; 1172 } else { /* hash or lru */ 1173 key = value - round_up(map->key_size, 8); 1174 } 1175 1176 callback_fn((u64)(long)map, (u64)(long)key, (u64)(long)value, 0, 0); 1177 /* The verifier checked that return value is zero. */ 1178 1179 this_cpu_write(hrtimer_running, NULL); 1180 out: 1181 return HRTIMER_NORESTART; 1182 } 1183 1184 static void bpf_wq_work(struct work_struct *work) 1185 { 1186 struct bpf_work *w = container_of(work, struct bpf_work, work); 1187 struct bpf_async_cb *cb = &w->cb; 1188 struct bpf_map *map = cb->map; 1189 bpf_callback_t callback_fn; 1190 void *value = cb->value; 1191 void *key; 1192 u32 idx; 1193 1194 BTF_TYPE_EMIT(struct bpf_wq); 1195 1196 callback_fn = READ_ONCE(cb->callback_fn); 1197 if (!callback_fn) 1198 return; 1199 1200 if (map->map_type == BPF_MAP_TYPE_ARRAY) { 1201 struct bpf_array *array = container_of(map, struct bpf_array, map); 1202 1203 /* compute the key */ 1204 idx = ((char *)value - array->value) / array->elem_size; 1205 key = &idx; 1206 } else { /* hash or lru */ 1207 key = value - round_up(map->key_size, 8); 1208 } 1209 1210 rcu_read_lock_trace(); 1211 migrate_disable(); 1212 1213 callback_fn((u64)(long)map, (u64)(long)key, (u64)(long)value, 0, 0); 1214 1215 migrate_enable(); 1216 rcu_read_unlock_trace(); 1217 } 1218 1219 static void bpf_wq_delete_work(struct work_struct *work) 1220 { 1221 struct bpf_work *w = container_of(work, struct bpf_work, delete_work); 1222 1223 cancel_work_sync(&w->work); 1224 1225 kfree_rcu(w, cb.rcu); 1226 } 1227 1228 static void bpf_timer_delete_work(struct work_struct *work) 1229 { 1230 struct bpf_hrtimer *t = container_of(work, struct bpf_hrtimer, cb.delete_work); 1231 1232 /* Cancel the timer and wait for callback to complete if it was running. 1233 * If hrtimer_cancel() can be safely called it's safe to call 1234 * kfree_rcu(t) right after for both preallocated and non-preallocated 1235 * maps. The async->cb = NULL was already done and no code path can see 1236 * address 't' anymore. Timer if armed for existing bpf_hrtimer before 1237 * bpf_timer_cancel_and_free will have been cancelled. 1238 */ 1239 hrtimer_cancel(&t->timer); 1240 kfree_rcu(t, cb.rcu); 1241 } 1242 1243 static int __bpf_async_init(struct bpf_async_kern *async, struct bpf_map *map, u64 flags, 1244 enum bpf_async_type type) 1245 { 1246 struct bpf_async_cb *cb; 1247 struct bpf_hrtimer *t; 1248 struct bpf_work *w; 1249 clockid_t clockid; 1250 size_t size; 1251 int ret = 0; 1252 1253 if (in_nmi()) 1254 return -EOPNOTSUPP; 1255 1256 switch (type) { 1257 case BPF_ASYNC_TYPE_TIMER: 1258 size = sizeof(struct bpf_hrtimer); 1259 break; 1260 case BPF_ASYNC_TYPE_WQ: 1261 size = sizeof(struct bpf_work); 1262 break; 1263 default: 1264 return -EINVAL; 1265 } 1266 1267 __bpf_spin_lock_irqsave(&async->lock); 1268 t = async->timer; 1269 if (t) { 1270 ret = -EBUSY; 1271 goto out; 1272 } 1273 1274 /* Allocate via bpf_map_kmalloc_node() for memcg accounting. Until 1275 * kmalloc_nolock() is available, avoid locking issues by using 1276 * __GFP_HIGH (GFP_ATOMIC & ~__GFP_RECLAIM). 1277 */ 1278 cb = bpf_map_kmalloc_node(map, size, __GFP_HIGH, map->numa_node); 1279 if (!cb) { 1280 ret = -ENOMEM; 1281 goto out; 1282 } 1283 1284 switch (type) { 1285 case BPF_ASYNC_TYPE_TIMER: 1286 clockid = flags & (MAX_CLOCKS - 1); 1287 t = (struct bpf_hrtimer *)cb; 1288 1289 atomic_set(&t->cancelling, 0); 1290 INIT_WORK(&t->cb.delete_work, bpf_timer_delete_work); 1291 hrtimer_setup(&t->timer, bpf_timer_cb, clockid, HRTIMER_MODE_REL_SOFT); 1292 cb->value = (void *)async - map->record->timer_off; 1293 break; 1294 case BPF_ASYNC_TYPE_WQ: 1295 w = (struct bpf_work *)cb; 1296 1297 INIT_WORK(&w->work, bpf_wq_work); 1298 INIT_WORK(&w->delete_work, bpf_wq_delete_work); 1299 cb->value = (void *)async - map->record->wq_off; 1300 break; 1301 } 1302 cb->map = map; 1303 cb->prog = NULL; 1304 cb->flags = flags; 1305 rcu_assign_pointer(cb->callback_fn, NULL); 1306 1307 WRITE_ONCE(async->cb, cb); 1308 /* Guarantee the order between async->cb and map->usercnt. So 1309 * when there are concurrent uref release and bpf timer init, either 1310 * bpf_timer_cancel_and_free() called by uref release reads a no-NULL 1311 * timer or atomic64_read() below returns a zero usercnt. 1312 */ 1313 smp_mb(); 1314 if (!atomic64_read(&map->usercnt)) { 1315 /* maps with timers must be either held by user space 1316 * or pinned in bpffs. 1317 */ 1318 WRITE_ONCE(async->cb, NULL); 1319 kfree(cb); 1320 ret = -EPERM; 1321 } 1322 out: 1323 __bpf_spin_unlock_irqrestore(&async->lock); 1324 return ret; 1325 } 1326 1327 BPF_CALL_3(bpf_timer_init, struct bpf_async_kern *, timer, struct bpf_map *, map, 1328 u64, flags) 1329 { 1330 clock_t clockid = flags & (MAX_CLOCKS - 1); 1331 1332 BUILD_BUG_ON(MAX_CLOCKS != 16); 1333 BUILD_BUG_ON(sizeof(struct bpf_async_kern) > sizeof(struct bpf_timer)); 1334 BUILD_BUG_ON(__alignof__(struct bpf_async_kern) != __alignof__(struct bpf_timer)); 1335 1336 if (flags >= MAX_CLOCKS || 1337 /* similar to timerfd except _ALARM variants are not supported */ 1338 (clockid != CLOCK_MONOTONIC && 1339 clockid != CLOCK_REALTIME && 1340 clockid != CLOCK_BOOTTIME)) 1341 return -EINVAL; 1342 1343 return __bpf_async_init(timer, map, flags, BPF_ASYNC_TYPE_TIMER); 1344 } 1345 1346 static const struct bpf_func_proto bpf_timer_init_proto = { 1347 .func = bpf_timer_init, 1348 .gpl_only = true, 1349 .ret_type = RET_INTEGER, 1350 .arg1_type = ARG_PTR_TO_TIMER, 1351 .arg2_type = ARG_CONST_MAP_PTR, 1352 .arg3_type = ARG_ANYTHING, 1353 }; 1354 1355 static int __bpf_async_set_callback(struct bpf_async_kern *async, void *callback_fn, 1356 struct bpf_prog_aux *aux, unsigned int flags, 1357 enum bpf_async_type type) 1358 { 1359 struct bpf_prog *prev, *prog = aux->prog; 1360 struct bpf_async_cb *cb; 1361 int ret = 0; 1362 1363 if (in_nmi()) 1364 return -EOPNOTSUPP; 1365 __bpf_spin_lock_irqsave(&async->lock); 1366 cb = async->cb; 1367 if (!cb) { 1368 ret = -EINVAL; 1369 goto out; 1370 } 1371 if (!atomic64_read(&cb->map->usercnt)) { 1372 /* maps with timers must be either held by user space 1373 * or pinned in bpffs. Otherwise timer might still be 1374 * running even when bpf prog is detached and user space 1375 * is gone, since map_release_uref won't ever be called. 1376 */ 1377 ret = -EPERM; 1378 goto out; 1379 } 1380 prev = cb->prog; 1381 if (prev != prog) { 1382 /* Bump prog refcnt once. Every bpf_timer_set_callback() 1383 * can pick different callback_fn-s within the same prog. 1384 */ 1385 prog = bpf_prog_inc_not_zero(prog); 1386 if (IS_ERR(prog)) { 1387 ret = PTR_ERR(prog); 1388 goto out; 1389 } 1390 if (prev) 1391 /* Drop prev prog refcnt when swapping with new prog */ 1392 bpf_prog_put(prev); 1393 cb->prog = prog; 1394 } 1395 rcu_assign_pointer(cb->callback_fn, callback_fn); 1396 out: 1397 __bpf_spin_unlock_irqrestore(&async->lock); 1398 return ret; 1399 } 1400 1401 BPF_CALL_3(bpf_timer_set_callback, struct bpf_async_kern *, timer, void *, callback_fn, 1402 struct bpf_prog_aux *, aux) 1403 { 1404 return __bpf_async_set_callback(timer, callback_fn, aux, 0, BPF_ASYNC_TYPE_TIMER); 1405 } 1406 1407 static const struct bpf_func_proto bpf_timer_set_callback_proto = { 1408 .func = bpf_timer_set_callback, 1409 .gpl_only = true, 1410 .ret_type = RET_INTEGER, 1411 .arg1_type = ARG_PTR_TO_TIMER, 1412 .arg2_type = ARG_PTR_TO_FUNC, 1413 }; 1414 1415 BPF_CALL_3(bpf_timer_start, struct bpf_async_kern *, timer, u64, nsecs, u64, flags) 1416 { 1417 struct bpf_hrtimer *t; 1418 int ret = 0; 1419 enum hrtimer_mode mode; 1420 1421 if (in_nmi()) 1422 return -EOPNOTSUPP; 1423 if (flags & ~(BPF_F_TIMER_ABS | BPF_F_TIMER_CPU_PIN)) 1424 return -EINVAL; 1425 __bpf_spin_lock_irqsave(&timer->lock); 1426 t = timer->timer; 1427 if (!t || !t->cb.prog) { 1428 ret = -EINVAL; 1429 goto out; 1430 } 1431 1432 if (flags & BPF_F_TIMER_ABS) 1433 mode = HRTIMER_MODE_ABS_SOFT; 1434 else 1435 mode = HRTIMER_MODE_REL_SOFT; 1436 1437 if (flags & BPF_F_TIMER_CPU_PIN) 1438 mode |= HRTIMER_MODE_PINNED; 1439 1440 hrtimer_start(&t->timer, ns_to_ktime(nsecs), mode); 1441 out: 1442 __bpf_spin_unlock_irqrestore(&timer->lock); 1443 return ret; 1444 } 1445 1446 static const struct bpf_func_proto bpf_timer_start_proto = { 1447 .func = bpf_timer_start, 1448 .gpl_only = true, 1449 .ret_type = RET_INTEGER, 1450 .arg1_type = ARG_PTR_TO_TIMER, 1451 .arg2_type = ARG_ANYTHING, 1452 .arg3_type = ARG_ANYTHING, 1453 }; 1454 1455 static void drop_prog_refcnt(struct bpf_async_cb *async) 1456 { 1457 struct bpf_prog *prog = async->prog; 1458 1459 if (prog) { 1460 bpf_prog_put(prog); 1461 async->prog = NULL; 1462 rcu_assign_pointer(async->callback_fn, NULL); 1463 } 1464 } 1465 1466 BPF_CALL_1(bpf_timer_cancel, struct bpf_async_kern *, timer) 1467 { 1468 struct bpf_hrtimer *t, *cur_t; 1469 bool inc = false; 1470 int ret = 0; 1471 1472 if (in_nmi()) 1473 return -EOPNOTSUPP; 1474 rcu_read_lock(); 1475 __bpf_spin_lock_irqsave(&timer->lock); 1476 t = timer->timer; 1477 if (!t) { 1478 ret = -EINVAL; 1479 goto out; 1480 } 1481 1482 cur_t = this_cpu_read(hrtimer_running); 1483 if (cur_t == t) { 1484 /* If bpf callback_fn is trying to bpf_timer_cancel() 1485 * its own timer the hrtimer_cancel() will deadlock 1486 * since it waits for callback_fn to finish. 1487 */ 1488 ret = -EDEADLK; 1489 goto out; 1490 } 1491 1492 /* Only account in-flight cancellations when invoked from a timer 1493 * callback, since we want to avoid waiting only if other _callbacks_ 1494 * are waiting on us, to avoid introducing lockups. Non-callback paths 1495 * are ok, since nobody would synchronously wait for their completion. 1496 */ 1497 if (!cur_t) 1498 goto drop; 1499 atomic_inc(&t->cancelling); 1500 /* Need full barrier after relaxed atomic_inc */ 1501 smp_mb__after_atomic(); 1502 inc = true; 1503 if (atomic_read(&cur_t->cancelling)) { 1504 /* We're cancelling timer t, while some other timer callback is 1505 * attempting to cancel us. In such a case, it might be possible 1506 * that timer t belongs to the other callback, or some other 1507 * callback waiting upon it (creating transitive dependencies 1508 * upon us), and we will enter a deadlock if we continue 1509 * cancelling and waiting for it synchronously, since it might 1510 * do the same. Bail! 1511 */ 1512 ret = -EDEADLK; 1513 goto out; 1514 } 1515 drop: 1516 drop_prog_refcnt(&t->cb); 1517 out: 1518 __bpf_spin_unlock_irqrestore(&timer->lock); 1519 /* Cancel the timer and wait for associated callback to finish 1520 * if it was running. 1521 */ 1522 ret = ret ?: hrtimer_cancel(&t->timer); 1523 if (inc) 1524 atomic_dec(&t->cancelling); 1525 rcu_read_unlock(); 1526 return ret; 1527 } 1528 1529 static const struct bpf_func_proto bpf_timer_cancel_proto = { 1530 .func = bpf_timer_cancel, 1531 .gpl_only = true, 1532 .ret_type = RET_INTEGER, 1533 .arg1_type = ARG_PTR_TO_TIMER, 1534 }; 1535 1536 static struct bpf_async_cb *__bpf_async_cancel_and_free(struct bpf_async_kern *async) 1537 { 1538 struct bpf_async_cb *cb; 1539 1540 /* Performance optimization: read async->cb without lock first. */ 1541 if (!READ_ONCE(async->cb)) 1542 return NULL; 1543 1544 __bpf_spin_lock_irqsave(&async->lock); 1545 /* re-read it under lock */ 1546 cb = async->cb; 1547 if (!cb) 1548 goto out; 1549 drop_prog_refcnt(cb); 1550 /* The subsequent bpf_timer_start/cancel() helpers won't be able to use 1551 * this timer, since it won't be initialized. 1552 */ 1553 WRITE_ONCE(async->cb, NULL); 1554 out: 1555 __bpf_spin_unlock_irqrestore(&async->lock); 1556 return cb; 1557 } 1558 1559 /* This function is called by map_delete/update_elem for individual element and 1560 * by ops->map_release_uref when the user space reference to a map reaches zero. 1561 */ 1562 void bpf_timer_cancel_and_free(void *val) 1563 { 1564 struct bpf_hrtimer *t; 1565 1566 t = (struct bpf_hrtimer *)__bpf_async_cancel_and_free(val); 1567 1568 if (!t) 1569 return; 1570 /* We check that bpf_map_delete/update_elem() was called from timer 1571 * callback_fn. In such case we don't call hrtimer_cancel() (since it 1572 * will deadlock) and don't call hrtimer_try_to_cancel() (since it will 1573 * just return -1). Though callback_fn is still running on this cpu it's 1574 * safe to do kfree(t) because bpf_timer_cb() read everything it needed 1575 * from 't'. The bpf subprog callback_fn won't be able to access 't', 1576 * since async->cb = NULL was already done. The timer will be 1577 * effectively cancelled because bpf_timer_cb() will return 1578 * HRTIMER_NORESTART. 1579 * 1580 * However, it is possible the timer callback_fn calling us armed the 1581 * timer _before_ calling us, such that failing to cancel it here will 1582 * cause it to possibly use struct hrtimer after freeing bpf_hrtimer. 1583 * Therefore, we _need_ to cancel any outstanding timers before we do 1584 * kfree_rcu, even though no more timers can be armed. 1585 * 1586 * Moreover, we need to schedule work even if timer does not belong to 1587 * the calling callback_fn, as on two different CPUs, we can end up in a 1588 * situation where both sides run in parallel, try to cancel one 1589 * another, and we end up waiting on both sides in hrtimer_cancel 1590 * without making forward progress, since timer1 depends on time2 1591 * callback to finish, and vice versa. 1592 * 1593 * CPU 1 (timer1_cb) CPU 2 (timer2_cb) 1594 * bpf_timer_cancel_and_free(timer2) bpf_timer_cancel_and_free(timer1) 1595 * 1596 * To avoid these issues, punt to workqueue context when we are in a 1597 * timer callback. 1598 */ 1599 if (this_cpu_read(hrtimer_running)) { 1600 queue_work(system_dfl_wq, &t->cb.delete_work); 1601 return; 1602 } 1603 1604 if (IS_ENABLED(CONFIG_PREEMPT_RT)) { 1605 /* If the timer is running on other CPU, also use a kworker to 1606 * wait for the completion of the timer instead of trying to 1607 * acquire a sleepable lock in hrtimer_cancel() to wait for its 1608 * completion. 1609 */ 1610 if (hrtimer_try_to_cancel(&t->timer) >= 0) 1611 kfree_rcu(t, cb.rcu); 1612 else 1613 queue_work(system_dfl_wq, &t->cb.delete_work); 1614 } else { 1615 bpf_timer_delete_work(&t->cb.delete_work); 1616 } 1617 } 1618 1619 /* This function is called by map_delete/update_elem for individual element and 1620 * by ops->map_release_uref when the user space reference to a map reaches zero. 1621 */ 1622 void bpf_wq_cancel_and_free(void *val) 1623 { 1624 struct bpf_work *work; 1625 1626 BTF_TYPE_EMIT(struct bpf_wq); 1627 1628 work = (struct bpf_work *)__bpf_async_cancel_and_free(val); 1629 if (!work) 1630 return; 1631 /* Trigger cancel of the sleepable work, but *do not* wait for 1632 * it to finish if it was running as we might not be in a 1633 * sleepable context. 1634 * kfree will be called once the work has finished. 1635 */ 1636 schedule_work(&work->delete_work); 1637 } 1638 1639 BPF_CALL_2(bpf_kptr_xchg, void *, dst, void *, ptr) 1640 { 1641 unsigned long *kptr = dst; 1642 1643 /* This helper may be inlined by verifier. */ 1644 return xchg(kptr, (unsigned long)ptr); 1645 } 1646 1647 /* Unlike other PTR_TO_BTF_ID helpers the btf_id in bpf_kptr_xchg() 1648 * helper is determined dynamically by the verifier. Use BPF_PTR_POISON to 1649 * denote type that verifier will determine. 1650 */ 1651 static const struct bpf_func_proto bpf_kptr_xchg_proto = { 1652 .func = bpf_kptr_xchg, 1653 .gpl_only = false, 1654 .ret_type = RET_PTR_TO_BTF_ID_OR_NULL, 1655 .ret_btf_id = BPF_PTR_POISON, 1656 .arg1_type = ARG_KPTR_XCHG_DEST, 1657 .arg2_type = ARG_PTR_TO_BTF_ID_OR_NULL | OBJ_RELEASE, 1658 .arg2_btf_id = BPF_PTR_POISON, 1659 }; 1660 1661 /* Since the upper 8 bits of dynptr->size is reserved, the 1662 * maximum supported size is 2^24 - 1. 1663 */ 1664 #define DYNPTR_MAX_SIZE ((1UL << 24) - 1) 1665 #define DYNPTR_TYPE_SHIFT 28 1666 #define DYNPTR_SIZE_MASK 0xFFFFFF 1667 #define DYNPTR_RDONLY_BIT BIT(31) 1668 1669 bool __bpf_dynptr_is_rdonly(const struct bpf_dynptr_kern *ptr) 1670 { 1671 return ptr->size & DYNPTR_RDONLY_BIT; 1672 } 1673 1674 void bpf_dynptr_set_rdonly(struct bpf_dynptr_kern *ptr) 1675 { 1676 ptr->size |= DYNPTR_RDONLY_BIT; 1677 } 1678 1679 static void bpf_dynptr_set_type(struct bpf_dynptr_kern *ptr, enum bpf_dynptr_type type) 1680 { 1681 ptr->size |= type << DYNPTR_TYPE_SHIFT; 1682 } 1683 1684 static enum bpf_dynptr_type bpf_dynptr_get_type(const struct bpf_dynptr_kern *ptr) 1685 { 1686 return (ptr->size & ~(DYNPTR_RDONLY_BIT)) >> DYNPTR_TYPE_SHIFT; 1687 } 1688 1689 u32 __bpf_dynptr_size(const struct bpf_dynptr_kern *ptr) 1690 { 1691 return ptr->size & DYNPTR_SIZE_MASK; 1692 } 1693 1694 static void bpf_dynptr_set_size(struct bpf_dynptr_kern *ptr, u32 new_size) 1695 { 1696 u32 metadata = ptr->size & ~DYNPTR_SIZE_MASK; 1697 1698 ptr->size = new_size | metadata; 1699 } 1700 1701 int bpf_dynptr_check_size(u32 size) 1702 { 1703 return size > DYNPTR_MAX_SIZE ? -E2BIG : 0; 1704 } 1705 1706 void bpf_dynptr_init(struct bpf_dynptr_kern *ptr, void *data, 1707 enum bpf_dynptr_type type, u32 offset, u32 size) 1708 { 1709 ptr->data = data; 1710 ptr->offset = offset; 1711 ptr->size = size; 1712 bpf_dynptr_set_type(ptr, type); 1713 } 1714 1715 void bpf_dynptr_set_null(struct bpf_dynptr_kern *ptr) 1716 { 1717 memset(ptr, 0, sizeof(*ptr)); 1718 } 1719 1720 BPF_CALL_4(bpf_dynptr_from_mem, void *, data, u32, size, u64, flags, struct bpf_dynptr_kern *, ptr) 1721 { 1722 int err; 1723 1724 BTF_TYPE_EMIT(struct bpf_dynptr); 1725 1726 err = bpf_dynptr_check_size(size); 1727 if (err) 1728 goto error; 1729 1730 /* flags is currently unsupported */ 1731 if (flags) { 1732 err = -EINVAL; 1733 goto error; 1734 } 1735 1736 bpf_dynptr_init(ptr, data, BPF_DYNPTR_TYPE_LOCAL, 0, size); 1737 1738 return 0; 1739 1740 error: 1741 bpf_dynptr_set_null(ptr); 1742 return err; 1743 } 1744 1745 static const struct bpf_func_proto bpf_dynptr_from_mem_proto = { 1746 .func = bpf_dynptr_from_mem, 1747 .gpl_only = false, 1748 .ret_type = RET_INTEGER, 1749 .arg1_type = ARG_PTR_TO_UNINIT_MEM, 1750 .arg2_type = ARG_CONST_SIZE_OR_ZERO, 1751 .arg3_type = ARG_ANYTHING, 1752 .arg4_type = ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_LOCAL | MEM_UNINIT | MEM_WRITE, 1753 }; 1754 1755 static int __bpf_dynptr_read(void *dst, u32 len, const struct bpf_dynptr_kern *src, 1756 u32 offset, u64 flags) 1757 { 1758 enum bpf_dynptr_type type; 1759 int err; 1760 1761 if (!src->data || flags) 1762 return -EINVAL; 1763 1764 err = bpf_dynptr_check_off_len(src, offset, len); 1765 if (err) 1766 return err; 1767 1768 type = bpf_dynptr_get_type(src); 1769 1770 switch (type) { 1771 case BPF_DYNPTR_TYPE_LOCAL: 1772 case BPF_DYNPTR_TYPE_RINGBUF: 1773 /* Source and destination may possibly overlap, hence use memmove to 1774 * copy the data. E.g. bpf_dynptr_from_mem may create two dynptr 1775 * pointing to overlapping PTR_TO_MAP_VALUE regions. 1776 */ 1777 memmove(dst, src->data + src->offset + offset, len); 1778 return 0; 1779 case BPF_DYNPTR_TYPE_SKB: 1780 return __bpf_skb_load_bytes(src->data, src->offset + offset, dst, len); 1781 case BPF_DYNPTR_TYPE_XDP: 1782 return __bpf_xdp_load_bytes(src->data, src->offset + offset, dst, len); 1783 case BPF_DYNPTR_TYPE_SKB_META: 1784 memmove(dst, bpf_skb_meta_pointer(src->data, src->offset + offset), len); 1785 return 0; 1786 default: 1787 WARN_ONCE(true, "bpf_dynptr_read: unknown dynptr type %d\n", type); 1788 return -EFAULT; 1789 } 1790 } 1791 1792 BPF_CALL_5(bpf_dynptr_read, void *, dst, u32, len, const struct bpf_dynptr_kern *, src, 1793 u32, offset, u64, flags) 1794 { 1795 return __bpf_dynptr_read(dst, len, src, offset, flags); 1796 } 1797 1798 static const struct bpf_func_proto bpf_dynptr_read_proto = { 1799 .func = bpf_dynptr_read, 1800 .gpl_only = false, 1801 .ret_type = RET_INTEGER, 1802 .arg1_type = ARG_PTR_TO_UNINIT_MEM, 1803 .arg2_type = ARG_CONST_SIZE_OR_ZERO, 1804 .arg3_type = ARG_PTR_TO_DYNPTR | MEM_RDONLY, 1805 .arg4_type = ARG_ANYTHING, 1806 .arg5_type = ARG_ANYTHING, 1807 }; 1808 1809 int __bpf_dynptr_write(const struct bpf_dynptr_kern *dst, u32 offset, void *src, 1810 u32 len, u64 flags) 1811 { 1812 enum bpf_dynptr_type type; 1813 int err; 1814 1815 if (!dst->data || __bpf_dynptr_is_rdonly(dst)) 1816 return -EINVAL; 1817 1818 err = bpf_dynptr_check_off_len(dst, offset, len); 1819 if (err) 1820 return err; 1821 1822 type = bpf_dynptr_get_type(dst); 1823 1824 switch (type) { 1825 case BPF_DYNPTR_TYPE_LOCAL: 1826 case BPF_DYNPTR_TYPE_RINGBUF: 1827 if (flags) 1828 return -EINVAL; 1829 /* Source and destination may possibly overlap, hence use memmove to 1830 * copy the data. E.g. bpf_dynptr_from_mem may create two dynptr 1831 * pointing to overlapping PTR_TO_MAP_VALUE regions. 1832 */ 1833 memmove(dst->data + dst->offset + offset, src, len); 1834 return 0; 1835 case BPF_DYNPTR_TYPE_SKB: 1836 return __bpf_skb_store_bytes(dst->data, dst->offset + offset, src, len, 1837 flags); 1838 case BPF_DYNPTR_TYPE_XDP: 1839 if (flags) 1840 return -EINVAL; 1841 return __bpf_xdp_store_bytes(dst->data, dst->offset + offset, src, len); 1842 case BPF_DYNPTR_TYPE_SKB_META: 1843 if (flags) 1844 return -EINVAL; 1845 memmove(bpf_skb_meta_pointer(dst->data, dst->offset + offset), src, len); 1846 return 0; 1847 default: 1848 WARN_ONCE(true, "bpf_dynptr_write: unknown dynptr type %d\n", type); 1849 return -EFAULT; 1850 } 1851 } 1852 1853 BPF_CALL_5(bpf_dynptr_write, const struct bpf_dynptr_kern *, dst, u32, offset, void *, src, 1854 u32, len, u64, flags) 1855 { 1856 return __bpf_dynptr_write(dst, offset, src, len, flags); 1857 } 1858 1859 static const struct bpf_func_proto bpf_dynptr_write_proto = { 1860 .func = bpf_dynptr_write, 1861 .gpl_only = false, 1862 .ret_type = RET_INTEGER, 1863 .arg1_type = ARG_PTR_TO_DYNPTR | MEM_RDONLY, 1864 .arg2_type = ARG_ANYTHING, 1865 .arg3_type = ARG_PTR_TO_MEM | MEM_RDONLY, 1866 .arg4_type = ARG_CONST_SIZE_OR_ZERO, 1867 .arg5_type = ARG_ANYTHING, 1868 }; 1869 1870 BPF_CALL_3(bpf_dynptr_data, const struct bpf_dynptr_kern *, ptr, u32, offset, u32, len) 1871 { 1872 enum bpf_dynptr_type type; 1873 int err; 1874 1875 if (!ptr->data) 1876 return 0; 1877 1878 err = bpf_dynptr_check_off_len(ptr, offset, len); 1879 if (err) 1880 return 0; 1881 1882 if (__bpf_dynptr_is_rdonly(ptr)) 1883 return 0; 1884 1885 type = bpf_dynptr_get_type(ptr); 1886 1887 switch (type) { 1888 case BPF_DYNPTR_TYPE_LOCAL: 1889 case BPF_DYNPTR_TYPE_RINGBUF: 1890 return (unsigned long)(ptr->data + ptr->offset + offset); 1891 case BPF_DYNPTR_TYPE_SKB: 1892 case BPF_DYNPTR_TYPE_XDP: 1893 case BPF_DYNPTR_TYPE_SKB_META: 1894 /* skb and xdp dynptrs should use bpf_dynptr_slice / bpf_dynptr_slice_rdwr */ 1895 return 0; 1896 default: 1897 WARN_ONCE(true, "bpf_dynptr_data: unknown dynptr type %d\n", type); 1898 return 0; 1899 } 1900 } 1901 1902 static const struct bpf_func_proto bpf_dynptr_data_proto = { 1903 .func = bpf_dynptr_data, 1904 .gpl_only = false, 1905 .ret_type = RET_PTR_TO_DYNPTR_MEM_OR_NULL, 1906 .arg1_type = ARG_PTR_TO_DYNPTR | MEM_RDONLY, 1907 .arg2_type = ARG_ANYTHING, 1908 .arg3_type = ARG_CONST_ALLOC_SIZE_OR_ZERO, 1909 }; 1910 1911 const struct bpf_func_proto bpf_get_current_task_proto __weak; 1912 const struct bpf_func_proto bpf_get_current_task_btf_proto __weak; 1913 const struct bpf_func_proto bpf_probe_read_user_proto __weak; 1914 const struct bpf_func_proto bpf_probe_read_user_str_proto __weak; 1915 const struct bpf_func_proto bpf_probe_read_kernel_proto __weak; 1916 const struct bpf_func_proto bpf_probe_read_kernel_str_proto __weak; 1917 const struct bpf_func_proto bpf_task_pt_regs_proto __weak; 1918 const struct bpf_func_proto bpf_perf_event_read_proto __weak; 1919 const struct bpf_func_proto bpf_send_signal_proto __weak; 1920 const struct bpf_func_proto bpf_send_signal_thread_proto __weak; 1921 const struct bpf_func_proto bpf_get_task_stack_sleepable_proto __weak; 1922 const struct bpf_func_proto bpf_get_task_stack_proto __weak; 1923 const struct bpf_func_proto bpf_get_branch_snapshot_proto __weak; 1924 1925 const struct bpf_func_proto * 1926 bpf_base_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog) 1927 { 1928 switch (func_id) { 1929 case BPF_FUNC_map_lookup_elem: 1930 return &bpf_map_lookup_elem_proto; 1931 case BPF_FUNC_map_update_elem: 1932 return &bpf_map_update_elem_proto; 1933 case BPF_FUNC_map_delete_elem: 1934 return &bpf_map_delete_elem_proto; 1935 case BPF_FUNC_map_push_elem: 1936 return &bpf_map_push_elem_proto; 1937 case BPF_FUNC_map_pop_elem: 1938 return &bpf_map_pop_elem_proto; 1939 case BPF_FUNC_map_peek_elem: 1940 return &bpf_map_peek_elem_proto; 1941 case BPF_FUNC_map_lookup_percpu_elem: 1942 return &bpf_map_lookup_percpu_elem_proto; 1943 case BPF_FUNC_get_prandom_u32: 1944 return &bpf_get_prandom_u32_proto; 1945 case BPF_FUNC_get_smp_processor_id: 1946 return &bpf_get_raw_smp_processor_id_proto; 1947 case BPF_FUNC_get_numa_node_id: 1948 return &bpf_get_numa_node_id_proto; 1949 case BPF_FUNC_tail_call: 1950 return &bpf_tail_call_proto; 1951 case BPF_FUNC_ktime_get_ns: 1952 return &bpf_ktime_get_ns_proto; 1953 case BPF_FUNC_ktime_get_boot_ns: 1954 return &bpf_ktime_get_boot_ns_proto; 1955 case BPF_FUNC_ktime_get_tai_ns: 1956 return &bpf_ktime_get_tai_ns_proto; 1957 case BPF_FUNC_ringbuf_output: 1958 return &bpf_ringbuf_output_proto; 1959 case BPF_FUNC_ringbuf_reserve: 1960 return &bpf_ringbuf_reserve_proto; 1961 case BPF_FUNC_ringbuf_submit: 1962 return &bpf_ringbuf_submit_proto; 1963 case BPF_FUNC_ringbuf_discard: 1964 return &bpf_ringbuf_discard_proto; 1965 case BPF_FUNC_ringbuf_query: 1966 return &bpf_ringbuf_query_proto; 1967 case BPF_FUNC_strncmp: 1968 return &bpf_strncmp_proto; 1969 case BPF_FUNC_strtol: 1970 return &bpf_strtol_proto; 1971 case BPF_FUNC_strtoul: 1972 return &bpf_strtoul_proto; 1973 case BPF_FUNC_get_current_pid_tgid: 1974 return &bpf_get_current_pid_tgid_proto; 1975 case BPF_FUNC_get_ns_current_pid_tgid: 1976 return &bpf_get_ns_current_pid_tgid_proto; 1977 case BPF_FUNC_get_current_uid_gid: 1978 return &bpf_get_current_uid_gid_proto; 1979 default: 1980 break; 1981 } 1982 1983 if (!bpf_token_capable(prog->aux->token, CAP_BPF)) 1984 return NULL; 1985 1986 switch (func_id) { 1987 case BPF_FUNC_spin_lock: 1988 return &bpf_spin_lock_proto; 1989 case BPF_FUNC_spin_unlock: 1990 return &bpf_spin_unlock_proto; 1991 case BPF_FUNC_jiffies64: 1992 return &bpf_jiffies64_proto; 1993 case BPF_FUNC_per_cpu_ptr: 1994 return &bpf_per_cpu_ptr_proto; 1995 case BPF_FUNC_this_cpu_ptr: 1996 return &bpf_this_cpu_ptr_proto; 1997 case BPF_FUNC_timer_init: 1998 return &bpf_timer_init_proto; 1999 case BPF_FUNC_timer_set_callback: 2000 return &bpf_timer_set_callback_proto; 2001 case BPF_FUNC_timer_start: 2002 return &bpf_timer_start_proto; 2003 case BPF_FUNC_timer_cancel: 2004 return &bpf_timer_cancel_proto; 2005 case BPF_FUNC_kptr_xchg: 2006 return &bpf_kptr_xchg_proto; 2007 case BPF_FUNC_for_each_map_elem: 2008 return &bpf_for_each_map_elem_proto; 2009 case BPF_FUNC_loop: 2010 return &bpf_loop_proto; 2011 case BPF_FUNC_user_ringbuf_drain: 2012 return &bpf_user_ringbuf_drain_proto; 2013 case BPF_FUNC_ringbuf_reserve_dynptr: 2014 return &bpf_ringbuf_reserve_dynptr_proto; 2015 case BPF_FUNC_ringbuf_submit_dynptr: 2016 return &bpf_ringbuf_submit_dynptr_proto; 2017 case BPF_FUNC_ringbuf_discard_dynptr: 2018 return &bpf_ringbuf_discard_dynptr_proto; 2019 case BPF_FUNC_dynptr_from_mem: 2020 return &bpf_dynptr_from_mem_proto; 2021 case BPF_FUNC_dynptr_read: 2022 return &bpf_dynptr_read_proto; 2023 case BPF_FUNC_dynptr_write: 2024 return &bpf_dynptr_write_proto; 2025 case BPF_FUNC_dynptr_data: 2026 return &bpf_dynptr_data_proto; 2027 #ifdef CONFIG_CGROUPS 2028 case BPF_FUNC_cgrp_storage_get: 2029 return &bpf_cgrp_storage_get_proto; 2030 case BPF_FUNC_cgrp_storage_delete: 2031 return &bpf_cgrp_storage_delete_proto; 2032 case BPF_FUNC_get_current_cgroup_id: 2033 return &bpf_get_current_cgroup_id_proto; 2034 case BPF_FUNC_get_current_ancestor_cgroup_id: 2035 return &bpf_get_current_ancestor_cgroup_id_proto; 2036 case BPF_FUNC_current_task_under_cgroup: 2037 return &bpf_current_task_under_cgroup_proto; 2038 #endif 2039 #ifdef CONFIG_CGROUP_NET_CLASSID 2040 case BPF_FUNC_get_cgroup_classid: 2041 return &bpf_get_cgroup_classid_curr_proto; 2042 #endif 2043 case BPF_FUNC_task_storage_get: 2044 if (bpf_prog_check_recur(prog)) 2045 return &bpf_task_storage_get_recur_proto; 2046 return &bpf_task_storage_get_proto; 2047 case BPF_FUNC_task_storage_delete: 2048 if (bpf_prog_check_recur(prog)) 2049 return &bpf_task_storage_delete_recur_proto; 2050 return &bpf_task_storage_delete_proto; 2051 default: 2052 break; 2053 } 2054 2055 if (!bpf_token_capable(prog->aux->token, CAP_PERFMON)) 2056 return NULL; 2057 2058 switch (func_id) { 2059 case BPF_FUNC_trace_printk: 2060 return bpf_get_trace_printk_proto(); 2061 case BPF_FUNC_get_current_task: 2062 return &bpf_get_current_task_proto; 2063 case BPF_FUNC_get_current_task_btf: 2064 return &bpf_get_current_task_btf_proto; 2065 case BPF_FUNC_get_current_comm: 2066 return &bpf_get_current_comm_proto; 2067 case BPF_FUNC_probe_read_user: 2068 return &bpf_probe_read_user_proto; 2069 case BPF_FUNC_probe_read_kernel: 2070 return security_locked_down(LOCKDOWN_BPF_READ_KERNEL) < 0 ? 2071 NULL : &bpf_probe_read_kernel_proto; 2072 case BPF_FUNC_probe_read_user_str: 2073 return &bpf_probe_read_user_str_proto; 2074 case BPF_FUNC_probe_read_kernel_str: 2075 return security_locked_down(LOCKDOWN_BPF_READ_KERNEL) < 0 ? 2076 NULL : &bpf_probe_read_kernel_str_proto; 2077 case BPF_FUNC_copy_from_user: 2078 return &bpf_copy_from_user_proto; 2079 case BPF_FUNC_copy_from_user_task: 2080 return &bpf_copy_from_user_task_proto; 2081 case BPF_FUNC_snprintf_btf: 2082 return &bpf_snprintf_btf_proto; 2083 case BPF_FUNC_snprintf: 2084 return &bpf_snprintf_proto; 2085 case BPF_FUNC_task_pt_regs: 2086 return &bpf_task_pt_regs_proto; 2087 case BPF_FUNC_trace_vprintk: 2088 return bpf_get_trace_vprintk_proto(); 2089 case BPF_FUNC_perf_event_read_value: 2090 return bpf_get_perf_event_read_value_proto(); 2091 case BPF_FUNC_perf_event_read: 2092 return &bpf_perf_event_read_proto; 2093 case BPF_FUNC_send_signal: 2094 return &bpf_send_signal_proto; 2095 case BPF_FUNC_send_signal_thread: 2096 return &bpf_send_signal_thread_proto; 2097 case BPF_FUNC_get_task_stack: 2098 return prog->sleepable ? &bpf_get_task_stack_sleepable_proto 2099 : &bpf_get_task_stack_proto; 2100 case BPF_FUNC_get_branch_snapshot: 2101 return &bpf_get_branch_snapshot_proto; 2102 case BPF_FUNC_find_vma: 2103 return &bpf_find_vma_proto; 2104 default: 2105 return NULL; 2106 } 2107 } 2108 EXPORT_SYMBOL_GPL(bpf_base_func_proto); 2109 2110 void bpf_list_head_free(const struct btf_field *field, void *list_head, 2111 struct bpf_spin_lock *spin_lock) 2112 { 2113 struct list_head *head = list_head, *orig_head = list_head; 2114 2115 BUILD_BUG_ON(sizeof(struct list_head) > sizeof(struct bpf_list_head)); 2116 BUILD_BUG_ON(__alignof__(struct list_head) > __alignof__(struct bpf_list_head)); 2117 2118 /* Do the actual list draining outside the lock to not hold the lock for 2119 * too long, and also prevent deadlocks if tracing programs end up 2120 * executing on entry/exit of functions called inside the critical 2121 * section, and end up doing map ops that call bpf_list_head_free for 2122 * the same map value again. 2123 */ 2124 __bpf_spin_lock_irqsave(spin_lock); 2125 if (!head->next || list_empty(head)) 2126 goto unlock; 2127 head = head->next; 2128 unlock: 2129 INIT_LIST_HEAD(orig_head); 2130 __bpf_spin_unlock_irqrestore(spin_lock); 2131 2132 while (head != orig_head) { 2133 void *obj = head; 2134 2135 obj -= field->graph_root.node_offset; 2136 head = head->next; 2137 /* The contained type can also have resources, including a 2138 * bpf_list_head which needs to be freed. 2139 */ 2140 __bpf_obj_drop_impl(obj, field->graph_root.value_rec, false); 2141 } 2142 } 2143 2144 /* Like rbtree_postorder_for_each_entry_safe, but 'pos' and 'n' are 2145 * 'rb_node *', so field name of rb_node within containing struct is not 2146 * needed. 2147 * 2148 * Since bpf_rb_tree's node type has a corresponding struct btf_field with 2149 * graph_root.node_offset, it's not necessary to know field name 2150 * or type of node struct 2151 */ 2152 #define bpf_rbtree_postorder_for_each_entry_safe(pos, n, root) \ 2153 for (pos = rb_first_postorder(root); \ 2154 pos && ({ n = rb_next_postorder(pos); 1; }); \ 2155 pos = n) 2156 2157 void bpf_rb_root_free(const struct btf_field *field, void *rb_root, 2158 struct bpf_spin_lock *spin_lock) 2159 { 2160 struct rb_root_cached orig_root, *root = rb_root; 2161 struct rb_node *pos, *n; 2162 void *obj; 2163 2164 BUILD_BUG_ON(sizeof(struct rb_root_cached) > sizeof(struct bpf_rb_root)); 2165 BUILD_BUG_ON(__alignof__(struct rb_root_cached) > __alignof__(struct bpf_rb_root)); 2166 2167 __bpf_spin_lock_irqsave(spin_lock); 2168 orig_root = *root; 2169 *root = RB_ROOT_CACHED; 2170 __bpf_spin_unlock_irqrestore(spin_lock); 2171 2172 bpf_rbtree_postorder_for_each_entry_safe(pos, n, &orig_root.rb_root) { 2173 obj = pos; 2174 obj -= field->graph_root.node_offset; 2175 2176 2177 __bpf_obj_drop_impl(obj, field->graph_root.value_rec, false); 2178 } 2179 } 2180 2181 __bpf_kfunc_start_defs(); 2182 2183 __bpf_kfunc void *bpf_obj_new_impl(u64 local_type_id__k, void *meta__ign) 2184 { 2185 struct btf_struct_meta *meta = meta__ign; 2186 u64 size = local_type_id__k; 2187 void *p; 2188 2189 p = bpf_mem_alloc(&bpf_global_ma, size); 2190 if (!p) 2191 return NULL; 2192 if (meta) 2193 bpf_obj_init(meta->record, p); 2194 return p; 2195 } 2196 2197 __bpf_kfunc void *bpf_percpu_obj_new_impl(u64 local_type_id__k, void *meta__ign) 2198 { 2199 u64 size = local_type_id__k; 2200 2201 /* The verifier has ensured that meta__ign must be NULL */ 2202 return bpf_mem_alloc(&bpf_global_percpu_ma, size); 2203 } 2204 2205 /* Must be called under migrate_disable(), as required by bpf_mem_free */ 2206 void __bpf_obj_drop_impl(void *p, const struct btf_record *rec, bool percpu) 2207 { 2208 struct bpf_mem_alloc *ma; 2209 2210 if (rec && rec->refcount_off >= 0 && 2211 !refcount_dec_and_test((refcount_t *)(p + rec->refcount_off))) { 2212 /* Object is refcounted and refcount_dec didn't result in 0 2213 * refcount. Return without freeing the object 2214 */ 2215 return; 2216 } 2217 2218 if (rec) 2219 bpf_obj_free_fields(rec, p); 2220 2221 if (percpu) 2222 ma = &bpf_global_percpu_ma; 2223 else 2224 ma = &bpf_global_ma; 2225 bpf_mem_free_rcu(ma, p); 2226 } 2227 2228 __bpf_kfunc void bpf_obj_drop_impl(void *p__alloc, void *meta__ign) 2229 { 2230 struct btf_struct_meta *meta = meta__ign; 2231 void *p = p__alloc; 2232 2233 __bpf_obj_drop_impl(p, meta ? meta->record : NULL, false); 2234 } 2235 2236 __bpf_kfunc void bpf_percpu_obj_drop_impl(void *p__alloc, void *meta__ign) 2237 { 2238 /* The verifier has ensured that meta__ign must be NULL */ 2239 bpf_mem_free_rcu(&bpf_global_percpu_ma, p__alloc); 2240 } 2241 2242 __bpf_kfunc void *bpf_refcount_acquire_impl(void *p__refcounted_kptr, void *meta__ign) 2243 { 2244 struct btf_struct_meta *meta = meta__ign; 2245 struct bpf_refcount *ref; 2246 2247 /* Could just cast directly to refcount_t *, but need some code using 2248 * bpf_refcount type so that it is emitted in vmlinux BTF 2249 */ 2250 ref = (struct bpf_refcount *)(p__refcounted_kptr + meta->record->refcount_off); 2251 if (!refcount_inc_not_zero((refcount_t *)ref)) 2252 return NULL; 2253 2254 /* Verifier strips KF_RET_NULL if input is owned ref, see is_kfunc_ret_null 2255 * in verifier.c 2256 */ 2257 return (void *)p__refcounted_kptr; 2258 } 2259 2260 static int __bpf_list_add(struct bpf_list_node_kern *node, 2261 struct bpf_list_head *head, 2262 bool tail, struct btf_record *rec, u64 off) 2263 { 2264 struct list_head *n = &node->list_head, *h = (void *)head; 2265 2266 /* If list_head was 0-initialized by map, bpf_obj_init_field wasn't 2267 * called on its fields, so init here 2268 */ 2269 if (unlikely(!h->next)) 2270 INIT_LIST_HEAD(h); 2271 2272 /* node->owner != NULL implies !list_empty(n), no need to separately 2273 * check the latter 2274 */ 2275 if (cmpxchg(&node->owner, NULL, BPF_PTR_POISON)) { 2276 /* Only called from BPF prog, no need to migrate_disable */ 2277 __bpf_obj_drop_impl((void *)n - off, rec, false); 2278 return -EINVAL; 2279 } 2280 2281 tail ? list_add_tail(n, h) : list_add(n, h); 2282 WRITE_ONCE(node->owner, head); 2283 2284 return 0; 2285 } 2286 2287 __bpf_kfunc int bpf_list_push_front_impl(struct bpf_list_head *head, 2288 struct bpf_list_node *node, 2289 void *meta__ign, u64 off) 2290 { 2291 struct bpf_list_node_kern *n = (void *)node; 2292 struct btf_struct_meta *meta = meta__ign; 2293 2294 return __bpf_list_add(n, head, false, meta ? meta->record : NULL, off); 2295 } 2296 2297 __bpf_kfunc int bpf_list_push_back_impl(struct bpf_list_head *head, 2298 struct bpf_list_node *node, 2299 void *meta__ign, u64 off) 2300 { 2301 struct bpf_list_node_kern *n = (void *)node; 2302 struct btf_struct_meta *meta = meta__ign; 2303 2304 return __bpf_list_add(n, head, true, meta ? meta->record : NULL, off); 2305 } 2306 2307 static struct bpf_list_node *__bpf_list_del(struct bpf_list_head *head, bool tail) 2308 { 2309 struct list_head *n, *h = (void *)head; 2310 struct bpf_list_node_kern *node; 2311 2312 /* If list_head was 0-initialized by map, bpf_obj_init_field wasn't 2313 * called on its fields, so init here 2314 */ 2315 if (unlikely(!h->next)) 2316 INIT_LIST_HEAD(h); 2317 if (list_empty(h)) 2318 return NULL; 2319 2320 n = tail ? h->prev : h->next; 2321 node = container_of(n, struct bpf_list_node_kern, list_head); 2322 if (WARN_ON_ONCE(READ_ONCE(node->owner) != head)) 2323 return NULL; 2324 2325 list_del_init(n); 2326 WRITE_ONCE(node->owner, NULL); 2327 return (struct bpf_list_node *)n; 2328 } 2329 2330 __bpf_kfunc struct bpf_list_node *bpf_list_pop_front(struct bpf_list_head *head) 2331 { 2332 return __bpf_list_del(head, false); 2333 } 2334 2335 __bpf_kfunc struct bpf_list_node *bpf_list_pop_back(struct bpf_list_head *head) 2336 { 2337 return __bpf_list_del(head, true); 2338 } 2339 2340 __bpf_kfunc struct bpf_list_node *bpf_list_front(struct bpf_list_head *head) 2341 { 2342 struct list_head *h = (struct list_head *)head; 2343 2344 if (list_empty(h) || unlikely(!h->next)) 2345 return NULL; 2346 2347 return (struct bpf_list_node *)h->next; 2348 } 2349 2350 __bpf_kfunc struct bpf_list_node *bpf_list_back(struct bpf_list_head *head) 2351 { 2352 struct list_head *h = (struct list_head *)head; 2353 2354 if (list_empty(h) || unlikely(!h->next)) 2355 return NULL; 2356 2357 return (struct bpf_list_node *)h->prev; 2358 } 2359 2360 __bpf_kfunc struct bpf_rb_node *bpf_rbtree_remove(struct bpf_rb_root *root, 2361 struct bpf_rb_node *node) 2362 { 2363 struct bpf_rb_node_kern *node_internal = (struct bpf_rb_node_kern *)node; 2364 struct rb_root_cached *r = (struct rb_root_cached *)root; 2365 struct rb_node *n = &node_internal->rb_node; 2366 2367 /* node_internal->owner != root implies either RB_EMPTY_NODE(n) or 2368 * n is owned by some other tree. No need to check RB_EMPTY_NODE(n) 2369 */ 2370 if (READ_ONCE(node_internal->owner) != root) 2371 return NULL; 2372 2373 rb_erase_cached(n, r); 2374 RB_CLEAR_NODE(n); 2375 WRITE_ONCE(node_internal->owner, NULL); 2376 return (struct bpf_rb_node *)n; 2377 } 2378 2379 /* Need to copy rbtree_add_cached's logic here because our 'less' is a BPF 2380 * program 2381 */ 2382 static int __bpf_rbtree_add(struct bpf_rb_root *root, 2383 struct bpf_rb_node_kern *node, 2384 void *less, struct btf_record *rec, u64 off) 2385 { 2386 struct rb_node **link = &((struct rb_root_cached *)root)->rb_root.rb_node; 2387 struct rb_node *parent = NULL, *n = &node->rb_node; 2388 bpf_callback_t cb = (bpf_callback_t)less; 2389 bool leftmost = true; 2390 2391 /* node->owner != NULL implies !RB_EMPTY_NODE(n), no need to separately 2392 * check the latter 2393 */ 2394 if (cmpxchg(&node->owner, NULL, BPF_PTR_POISON)) { 2395 /* Only called from BPF prog, no need to migrate_disable */ 2396 __bpf_obj_drop_impl((void *)n - off, rec, false); 2397 return -EINVAL; 2398 } 2399 2400 while (*link) { 2401 parent = *link; 2402 if (cb((uintptr_t)node, (uintptr_t)parent, 0, 0, 0)) { 2403 link = &parent->rb_left; 2404 } else { 2405 link = &parent->rb_right; 2406 leftmost = false; 2407 } 2408 } 2409 2410 rb_link_node(n, parent, link); 2411 rb_insert_color_cached(n, (struct rb_root_cached *)root, leftmost); 2412 WRITE_ONCE(node->owner, root); 2413 return 0; 2414 } 2415 2416 __bpf_kfunc int bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node, 2417 bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b), 2418 void *meta__ign, u64 off) 2419 { 2420 struct btf_struct_meta *meta = meta__ign; 2421 struct bpf_rb_node_kern *n = (void *)node; 2422 2423 return __bpf_rbtree_add(root, n, (void *)less, meta ? meta->record : NULL, off); 2424 } 2425 2426 __bpf_kfunc struct bpf_rb_node *bpf_rbtree_first(struct bpf_rb_root *root) 2427 { 2428 struct rb_root_cached *r = (struct rb_root_cached *)root; 2429 2430 return (struct bpf_rb_node *)rb_first_cached(r); 2431 } 2432 2433 __bpf_kfunc struct bpf_rb_node *bpf_rbtree_root(struct bpf_rb_root *root) 2434 { 2435 struct rb_root_cached *r = (struct rb_root_cached *)root; 2436 2437 return (struct bpf_rb_node *)r->rb_root.rb_node; 2438 } 2439 2440 __bpf_kfunc struct bpf_rb_node *bpf_rbtree_left(struct bpf_rb_root *root, struct bpf_rb_node *node) 2441 { 2442 struct bpf_rb_node_kern *node_internal = (struct bpf_rb_node_kern *)node; 2443 2444 if (READ_ONCE(node_internal->owner) != root) 2445 return NULL; 2446 2447 return (struct bpf_rb_node *)node_internal->rb_node.rb_left; 2448 } 2449 2450 __bpf_kfunc struct bpf_rb_node *bpf_rbtree_right(struct bpf_rb_root *root, struct bpf_rb_node *node) 2451 { 2452 struct bpf_rb_node_kern *node_internal = (struct bpf_rb_node_kern *)node; 2453 2454 if (READ_ONCE(node_internal->owner) != root) 2455 return NULL; 2456 2457 return (struct bpf_rb_node *)node_internal->rb_node.rb_right; 2458 } 2459 2460 /** 2461 * bpf_task_acquire - Acquire a reference to a task. A task acquired by this 2462 * kfunc which is not stored in a map as a kptr, must be released by calling 2463 * bpf_task_release(). 2464 * @p: The task on which a reference is being acquired. 2465 */ 2466 __bpf_kfunc struct task_struct *bpf_task_acquire(struct task_struct *p) 2467 { 2468 if (refcount_inc_not_zero(&p->rcu_users)) 2469 return p; 2470 return NULL; 2471 } 2472 2473 /** 2474 * bpf_task_release - Release the reference acquired on a task. 2475 * @p: The task on which a reference is being released. 2476 */ 2477 __bpf_kfunc void bpf_task_release(struct task_struct *p) 2478 { 2479 put_task_struct_rcu_user(p); 2480 } 2481 2482 __bpf_kfunc void bpf_task_release_dtor(void *p) 2483 { 2484 put_task_struct_rcu_user(p); 2485 } 2486 CFI_NOSEAL(bpf_task_release_dtor); 2487 2488 #ifdef CONFIG_CGROUPS 2489 /** 2490 * bpf_cgroup_acquire - Acquire a reference to a cgroup. A cgroup acquired by 2491 * this kfunc which is not stored in a map as a kptr, must be released by 2492 * calling bpf_cgroup_release(). 2493 * @cgrp: The cgroup on which a reference is being acquired. 2494 */ 2495 __bpf_kfunc struct cgroup *bpf_cgroup_acquire(struct cgroup *cgrp) 2496 { 2497 return cgroup_tryget(cgrp) ? cgrp : NULL; 2498 } 2499 2500 /** 2501 * bpf_cgroup_release - Release the reference acquired on a cgroup. 2502 * If this kfunc is invoked in an RCU read region, the cgroup is guaranteed to 2503 * not be freed until the current grace period has ended, even if its refcount 2504 * drops to 0. 2505 * @cgrp: The cgroup on which a reference is being released. 2506 */ 2507 __bpf_kfunc void bpf_cgroup_release(struct cgroup *cgrp) 2508 { 2509 cgroup_put(cgrp); 2510 } 2511 2512 __bpf_kfunc void bpf_cgroup_release_dtor(void *cgrp) 2513 { 2514 cgroup_put(cgrp); 2515 } 2516 CFI_NOSEAL(bpf_cgroup_release_dtor); 2517 2518 /** 2519 * bpf_cgroup_ancestor - Perform a lookup on an entry in a cgroup's ancestor 2520 * array. A cgroup returned by this kfunc which is not subsequently stored in a 2521 * map, must be released by calling bpf_cgroup_release(). 2522 * @cgrp: The cgroup for which we're performing a lookup. 2523 * @level: The level of ancestor to look up. 2524 */ 2525 __bpf_kfunc struct cgroup *bpf_cgroup_ancestor(struct cgroup *cgrp, int level) 2526 { 2527 struct cgroup *ancestor; 2528 2529 if (level > cgrp->level || level < 0) 2530 return NULL; 2531 2532 /* cgrp's refcnt could be 0 here, but ancestors can still be accessed */ 2533 ancestor = cgrp->ancestors[level]; 2534 if (!cgroup_tryget(ancestor)) 2535 return NULL; 2536 return ancestor; 2537 } 2538 2539 /** 2540 * bpf_cgroup_from_id - Find a cgroup from its ID. A cgroup returned by this 2541 * kfunc which is not subsequently stored in a map, must be released by calling 2542 * bpf_cgroup_release(). 2543 * @cgid: cgroup id. 2544 */ 2545 __bpf_kfunc struct cgroup *bpf_cgroup_from_id(u64 cgid) 2546 { 2547 struct cgroup *cgrp; 2548 2549 cgrp = cgroup_get_from_id(cgid); 2550 if (IS_ERR(cgrp)) 2551 return NULL; 2552 return cgrp; 2553 } 2554 2555 /** 2556 * bpf_task_under_cgroup - wrap task_under_cgroup_hierarchy() as a kfunc, test 2557 * task's membership of cgroup ancestry. 2558 * @task: the task to be tested 2559 * @ancestor: possible ancestor of @task's cgroup 2560 * 2561 * Tests whether @task's default cgroup hierarchy is a descendant of @ancestor. 2562 * It follows all the same rules as cgroup_is_descendant, and only applies 2563 * to the default hierarchy. 2564 */ 2565 __bpf_kfunc long bpf_task_under_cgroup(struct task_struct *task, 2566 struct cgroup *ancestor) 2567 { 2568 long ret; 2569 2570 rcu_read_lock(); 2571 ret = task_under_cgroup_hierarchy(task, ancestor); 2572 rcu_read_unlock(); 2573 return ret; 2574 } 2575 2576 BPF_CALL_2(bpf_current_task_under_cgroup, struct bpf_map *, map, u32, idx) 2577 { 2578 struct bpf_array *array = container_of(map, struct bpf_array, map); 2579 struct cgroup *cgrp; 2580 2581 if (unlikely(idx >= array->map.max_entries)) 2582 return -E2BIG; 2583 2584 cgrp = READ_ONCE(array->ptrs[idx]); 2585 if (unlikely(!cgrp)) 2586 return -EAGAIN; 2587 2588 return task_under_cgroup_hierarchy(current, cgrp); 2589 } 2590 2591 const struct bpf_func_proto bpf_current_task_under_cgroup_proto = { 2592 .func = bpf_current_task_under_cgroup, 2593 .gpl_only = false, 2594 .ret_type = RET_INTEGER, 2595 .arg1_type = ARG_CONST_MAP_PTR, 2596 .arg2_type = ARG_ANYTHING, 2597 }; 2598 2599 /** 2600 * bpf_task_get_cgroup1 - Acquires the associated cgroup of a task within a 2601 * specific cgroup1 hierarchy. The cgroup1 hierarchy is identified by its 2602 * hierarchy ID. 2603 * @task: The target task 2604 * @hierarchy_id: The ID of a cgroup1 hierarchy 2605 * 2606 * On success, the cgroup is returen. On failure, NULL is returned. 2607 */ 2608 __bpf_kfunc struct cgroup * 2609 bpf_task_get_cgroup1(struct task_struct *task, int hierarchy_id) 2610 { 2611 struct cgroup *cgrp = task_get_cgroup1(task, hierarchy_id); 2612 2613 if (IS_ERR(cgrp)) 2614 return NULL; 2615 return cgrp; 2616 } 2617 #endif /* CONFIG_CGROUPS */ 2618 2619 /** 2620 * bpf_task_from_pid - Find a struct task_struct from its pid by looking it up 2621 * in the root pid namespace idr. If a task is returned, it must either be 2622 * stored in a map, or released with bpf_task_release(). 2623 * @pid: The pid of the task being looked up. 2624 */ 2625 __bpf_kfunc struct task_struct *bpf_task_from_pid(s32 pid) 2626 { 2627 struct task_struct *p; 2628 2629 rcu_read_lock(); 2630 p = find_task_by_pid_ns(pid, &init_pid_ns); 2631 if (p) 2632 p = bpf_task_acquire(p); 2633 rcu_read_unlock(); 2634 2635 return p; 2636 } 2637 2638 /** 2639 * bpf_task_from_vpid - Find a struct task_struct from its vpid by looking it up 2640 * in the pid namespace of the current task. If a task is returned, it must 2641 * either be stored in a map, or released with bpf_task_release(). 2642 * @vpid: The vpid of the task being looked up. 2643 */ 2644 __bpf_kfunc struct task_struct *bpf_task_from_vpid(s32 vpid) 2645 { 2646 struct task_struct *p; 2647 2648 rcu_read_lock(); 2649 p = find_task_by_vpid(vpid); 2650 if (p) 2651 p = bpf_task_acquire(p); 2652 rcu_read_unlock(); 2653 2654 return p; 2655 } 2656 2657 /** 2658 * bpf_dynptr_slice() - Obtain a read-only pointer to the dynptr data. 2659 * @p: The dynptr whose data slice to retrieve 2660 * @offset: Offset into the dynptr 2661 * @buffer__opt: User-provided buffer to copy contents into. May be NULL 2662 * @buffer__szk: Size (in bytes) of the buffer if present. This is the 2663 * length of the requested slice. This must be a constant. 2664 * 2665 * For non-skb and non-xdp type dynptrs, there is no difference between 2666 * bpf_dynptr_slice and bpf_dynptr_data. 2667 * 2668 * If buffer__opt is NULL, the call will fail if buffer_opt was needed. 2669 * 2670 * If the intention is to write to the data slice, please use 2671 * bpf_dynptr_slice_rdwr. 2672 * 2673 * The user must check that the returned pointer is not null before using it. 2674 * 2675 * Please note that in the case of skb and xdp dynptrs, bpf_dynptr_slice 2676 * does not change the underlying packet data pointers, so a call to 2677 * bpf_dynptr_slice will not invalidate any ctx->data/data_end pointers in 2678 * the bpf program. 2679 * 2680 * Return: NULL if the call failed (eg invalid dynptr), pointer to a read-only 2681 * data slice (can be either direct pointer to the data or a pointer to the user 2682 * provided buffer, with its contents containing the data, if unable to obtain 2683 * direct pointer) 2684 */ 2685 __bpf_kfunc void *bpf_dynptr_slice(const struct bpf_dynptr *p, u32 offset, 2686 void *buffer__opt, u32 buffer__szk) 2687 { 2688 const struct bpf_dynptr_kern *ptr = (struct bpf_dynptr_kern *)p; 2689 enum bpf_dynptr_type type; 2690 u32 len = buffer__szk; 2691 int err; 2692 2693 if (!ptr->data) 2694 return NULL; 2695 2696 err = bpf_dynptr_check_off_len(ptr, offset, len); 2697 if (err) 2698 return NULL; 2699 2700 type = bpf_dynptr_get_type(ptr); 2701 2702 switch (type) { 2703 case BPF_DYNPTR_TYPE_LOCAL: 2704 case BPF_DYNPTR_TYPE_RINGBUF: 2705 return ptr->data + ptr->offset + offset; 2706 case BPF_DYNPTR_TYPE_SKB: 2707 if (buffer__opt) 2708 return skb_header_pointer(ptr->data, ptr->offset + offset, len, buffer__opt); 2709 else 2710 return skb_pointer_if_linear(ptr->data, ptr->offset + offset, len); 2711 case BPF_DYNPTR_TYPE_XDP: 2712 { 2713 void *xdp_ptr = bpf_xdp_pointer(ptr->data, ptr->offset + offset, len); 2714 if (!IS_ERR_OR_NULL(xdp_ptr)) 2715 return xdp_ptr; 2716 2717 if (!buffer__opt) 2718 return NULL; 2719 bpf_xdp_copy_buf(ptr->data, ptr->offset + offset, buffer__opt, len, false); 2720 return buffer__opt; 2721 } 2722 case BPF_DYNPTR_TYPE_SKB_META: 2723 return bpf_skb_meta_pointer(ptr->data, ptr->offset + offset); 2724 default: 2725 WARN_ONCE(true, "unknown dynptr type %d\n", type); 2726 return NULL; 2727 } 2728 } 2729 2730 /** 2731 * bpf_dynptr_slice_rdwr() - Obtain a writable pointer to the dynptr data. 2732 * @p: The dynptr whose data slice to retrieve 2733 * @offset: Offset into the dynptr 2734 * @buffer__opt: User-provided buffer to copy contents into. May be NULL 2735 * @buffer__szk: Size (in bytes) of the buffer if present. This is the 2736 * length of the requested slice. This must be a constant. 2737 * 2738 * For non-skb and non-xdp type dynptrs, there is no difference between 2739 * bpf_dynptr_slice and bpf_dynptr_data. 2740 * 2741 * If buffer__opt is NULL, the call will fail if buffer_opt was needed. 2742 * 2743 * The returned pointer is writable and may point to either directly the dynptr 2744 * data at the requested offset or to the buffer if unable to obtain a direct 2745 * data pointer to (example: the requested slice is to the paged area of an skb 2746 * packet). In the case where the returned pointer is to the buffer, the user 2747 * is responsible for persisting writes through calling bpf_dynptr_write(). This 2748 * usually looks something like this pattern: 2749 * 2750 * struct eth_hdr *eth = bpf_dynptr_slice_rdwr(&dynptr, 0, buffer, sizeof(buffer)); 2751 * if (!eth) 2752 * return TC_ACT_SHOT; 2753 * 2754 * // mutate eth header // 2755 * 2756 * if (eth == buffer) 2757 * bpf_dynptr_write(&ptr, 0, buffer, sizeof(buffer), 0); 2758 * 2759 * Please note that, as in the example above, the user must check that the 2760 * returned pointer is not null before using it. 2761 * 2762 * Please also note that in the case of skb and xdp dynptrs, bpf_dynptr_slice_rdwr 2763 * does not change the underlying packet data pointers, so a call to 2764 * bpf_dynptr_slice_rdwr will not invalidate any ctx->data/data_end pointers in 2765 * the bpf program. 2766 * 2767 * Return: NULL if the call failed (eg invalid dynptr), pointer to a 2768 * data slice (can be either direct pointer to the data or a pointer to the user 2769 * provided buffer, with its contents containing the data, if unable to obtain 2770 * direct pointer) 2771 */ 2772 __bpf_kfunc void *bpf_dynptr_slice_rdwr(const struct bpf_dynptr *p, u32 offset, 2773 void *buffer__opt, u32 buffer__szk) 2774 { 2775 const struct bpf_dynptr_kern *ptr = (struct bpf_dynptr_kern *)p; 2776 2777 if (!ptr->data || __bpf_dynptr_is_rdonly(ptr)) 2778 return NULL; 2779 2780 /* bpf_dynptr_slice_rdwr is the same logic as bpf_dynptr_slice. 2781 * 2782 * For skb-type dynptrs, it is safe to write into the returned pointer 2783 * if the bpf program allows skb data writes. There are two possibilities 2784 * that may occur when calling bpf_dynptr_slice_rdwr: 2785 * 2786 * 1) The requested slice is in the head of the skb. In this case, the 2787 * returned pointer is directly to skb data, and if the skb is cloned, the 2788 * verifier will have uncloned it (see bpf_unclone_prologue()) already. 2789 * The pointer can be directly written into. 2790 * 2791 * 2) Some portion of the requested slice is in the paged buffer area. 2792 * In this case, the requested data will be copied out into the buffer 2793 * and the returned pointer will be a pointer to the buffer. The skb 2794 * will not be pulled. To persist the write, the user will need to call 2795 * bpf_dynptr_write(), which will pull the skb and commit the write. 2796 * 2797 * Similarly for xdp programs, if the requested slice is not across xdp 2798 * fragments, then a direct pointer will be returned, otherwise the data 2799 * will be copied out into the buffer and the user will need to call 2800 * bpf_dynptr_write() to commit changes. 2801 */ 2802 return bpf_dynptr_slice(p, offset, buffer__opt, buffer__szk); 2803 } 2804 2805 __bpf_kfunc int bpf_dynptr_adjust(const struct bpf_dynptr *p, u32 start, u32 end) 2806 { 2807 struct bpf_dynptr_kern *ptr = (struct bpf_dynptr_kern *)p; 2808 u32 size; 2809 2810 if (!ptr->data || start > end) 2811 return -EINVAL; 2812 2813 size = __bpf_dynptr_size(ptr); 2814 2815 if (start > size || end > size) 2816 return -ERANGE; 2817 2818 ptr->offset += start; 2819 bpf_dynptr_set_size(ptr, end - start); 2820 2821 return 0; 2822 } 2823 2824 __bpf_kfunc bool bpf_dynptr_is_null(const struct bpf_dynptr *p) 2825 { 2826 struct bpf_dynptr_kern *ptr = (struct bpf_dynptr_kern *)p; 2827 2828 return !ptr->data; 2829 } 2830 2831 __bpf_kfunc bool bpf_dynptr_is_rdonly(const struct bpf_dynptr *p) 2832 { 2833 struct bpf_dynptr_kern *ptr = (struct bpf_dynptr_kern *)p; 2834 2835 if (!ptr->data) 2836 return false; 2837 2838 return __bpf_dynptr_is_rdonly(ptr); 2839 } 2840 2841 __bpf_kfunc __u32 bpf_dynptr_size(const struct bpf_dynptr *p) 2842 { 2843 struct bpf_dynptr_kern *ptr = (struct bpf_dynptr_kern *)p; 2844 2845 if (!ptr->data) 2846 return -EINVAL; 2847 2848 return __bpf_dynptr_size(ptr); 2849 } 2850 2851 __bpf_kfunc int bpf_dynptr_clone(const struct bpf_dynptr *p, 2852 struct bpf_dynptr *clone__uninit) 2853 { 2854 struct bpf_dynptr_kern *clone = (struct bpf_dynptr_kern *)clone__uninit; 2855 struct bpf_dynptr_kern *ptr = (struct bpf_dynptr_kern *)p; 2856 2857 if (!ptr->data) { 2858 bpf_dynptr_set_null(clone); 2859 return -EINVAL; 2860 } 2861 2862 *clone = *ptr; 2863 2864 return 0; 2865 } 2866 2867 /** 2868 * bpf_dynptr_copy() - Copy data from one dynptr to another. 2869 * @dst_ptr: Destination dynptr - where data should be copied to 2870 * @dst_off: Offset into the destination dynptr 2871 * @src_ptr: Source dynptr - where data should be copied from 2872 * @src_off: Offset into the source dynptr 2873 * @size: Length of the data to copy from source to destination 2874 * 2875 * Copies data from source dynptr to destination dynptr. 2876 * Returns 0 on success; negative error, otherwise. 2877 */ 2878 __bpf_kfunc int bpf_dynptr_copy(struct bpf_dynptr *dst_ptr, u32 dst_off, 2879 struct bpf_dynptr *src_ptr, u32 src_off, u32 size) 2880 { 2881 struct bpf_dynptr_kern *dst = (struct bpf_dynptr_kern *)dst_ptr; 2882 struct bpf_dynptr_kern *src = (struct bpf_dynptr_kern *)src_ptr; 2883 void *src_slice, *dst_slice; 2884 char buf[256]; 2885 u32 off; 2886 2887 src_slice = bpf_dynptr_slice(src_ptr, src_off, NULL, size); 2888 dst_slice = bpf_dynptr_slice_rdwr(dst_ptr, dst_off, NULL, size); 2889 2890 if (src_slice && dst_slice) { 2891 memmove(dst_slice, src_slice, size); 2892 return 0; 2893 } 2894 2895 if (src_slice) 2896 return __bpf_dynptr_write(dst, dst_off, src_slice, size, 0); 2897 2898 if (dst_slice) 2899 return __bpf_dynptr_read(dst_slice, size, src, src_off, 0); 2900 2901 if (bpf_dynptr_check_off_len(dst, dst_off, size) || 2902 bpf_dynptr_check_off_len(src, src_off, size)) 2903 return -E2BIG; 2904 2905 off = 0; 2906 while (off < size) { 2907 u32 chunk_sz = min_t(u32, sizeof(buf), size - off); 2908 int err; 2909 2910 err = __bpf_dynptr_read(buf, chunk_sz, src, src_off + off, 0); 2911 if (err) 2912 return err; 2913 err = __bpf_dynptr_write(dst, dst_off + off, buf, chunk_sz, 0); 2914 if (err) 2915 return err; 2916 2917 off += chunk_sz; 2918 } 2919 return 0; 2920 } 2921 2922 /** 2923 * bpf_dynptr_memset() - Fill dynptr memory with a constant byte. 2924 * @p: Destination dynptr - where data will be filled 2925 * @offset: Offset into the dynptr to start filling from 2926 * @size: Number of bytes to fill 2927 * @val: Constant byte to fill the memory with 2928 * 2929 * Fills the @size bytes of the memory area pointed to by @p 2930 * at @offset with the constant byte @val. 2931 * Returns 0 on success; negative error, otherwise. 2932 */ 2933 __bpf_kfunc int bpf_dynptr_memset(struct bpf_dynptr *p, u32 offset, u32 size, u8 val) 2934 { 2935 struct bpf_dynptr_kern *ptr = (struct bpf_dynptr_kern *)p; 2936 u32 chunk_sz, write_off; 2937 char buf[256]; 2938 void* slice; 2939 int err; 2940 2941 slice = bpf_dynptr_slice_rdwr(p, offset, NULL, size); 2942 if (likely(slice)) { 2943 memset(slice, val, size); 2944 return 0; 2945 } 2946 2947 if (__bpf_dynptr_is_rdonly(ptr)) 2948 return -EINVAL; 2949 2950 err = bpf_dynptr_check_off_len(ptr, offset, size); 2951 if (err) 2952 return err; 2953 2954 /* Non-linear data under the dynptr, write from a local buffer */ 2955 chunk_sz = min_t(u32, sizeof(buf), size); 2956 memset(buf, val, chunk_sz); 2957 2958 for (write_off = 0; write_off < size; write_off += chunk_sz) { 2959 chunk_sz = min_t(u32, sizeof(buf), size - write_off); 2960 err = __bpf_dynptr_write(ptr, offset + write_off, buf, chunk_sz, 0); 2961 if (err) 2962 return err; 2963 } 2964 2965 return 0; 2966 } 2967 2968 __bpf_kfunc void *bpf_cast_to_kern_ctx(void *obj) 2969 { 2970 return obj; 2971 } 2972 2973 __bpf_kfunc void *bpf_rdonly_cast(const void *obj__ign, u32 btf_id__k) 2974 { 2975 return (void *)obj__ign; 2976 } 2977 2978 __bpf_kfunc void bpf_rcu_read_lock(void) 2979 { 2980 rcu_read_lock(); 2981 } 2982 2983 __bpf_kfunc void bpf_rcu_read_unlock(void) 2984 { 2985 rcu_read_unlock(); 2986 } 2987 2988 struct bpf_throw_ctx { 2989 struct bpf_prog_aux *aux; 2990 u64 sp; 2991 u64 bp; 2992 int cnt; 2993 }; 2994 2995 static bool bpf_stack_walker(void *cookie, u64 ip, u64 sp, u64 bp) 2996 { 2997 struct bpf_throw_ctx *ctx = cookie; 2998 struct bpf_prog *prog; 2999 3000 /* 3001 * The RCU read lock is held to safely traverse the latch tree, but we 3002 * don't need its protection when accessing the prog, since it has an 3003 * active stack frame on the current stack trace, and won't disappear. 3004 */ 3005 rcu_read_lock(); 3006 prog = bpf_prog_ksym_find(ip); 3007 rcu_read_unlock(); 3008 if (!prog) 3009 return !ctx->cnt; 3010 ctx->cnt++; 3011 if (bpf_is_subprog(prog)) 3012 return true; 3013 ctx->aux = prog->aux; 3014 ctx->sp = sp; 3015 ctx->bp = bp; 3016 return false; 3017 } 3018 3019 __bpf_kfunc void bpf_throw(u64 cookie) 3020 { 3021 struct bpf_throw_ctx ctx = {}; 3022 3023 arch_bpf_stack_walk(bpf_stack_walker, &ctx); 3024 WARN_ON_ONCE(!ctx.aux); 3025 if (ctx.aux) 3026 WARN_ON_ONCE(!ctx.aux->exception_boundary); 3027 WARN_ON_ONCE(!ctx.bp); 3028 WARN_ON_ONCE(!ctx.cnt); 3029 /* Prevent KASAN false positives for CONFIG_KASAN_STACK by unpoisoning 3030 * deeper stack depths than ctx.sp as we do not return from bpf_throw, 3031 * which skips compiler generated instrumentation to do the same. 3032 */ 3033 kasan_unpoison_task_stack_below((void *)(long)ctx.sp); 3034 ctx.aux->bpf_exception_cb(cookie, ctx.sp, ctx.bp, 0, 0); 3035 WARN(1, "A call to BPF exception callback should never return\n"); 3036 } 3037 3038 __bpf_kfunc int bpf_wq_init(struct bpf_wq *wq, void *p__map, unsigned int flags) 3039 { 3040 struct bpf_async_kern *async = (struct bpf_async_kern *)wq; 3041 struct bpf_map *map = p__map; 3042 3043 BUILD_BUG_ON(sizeof(struct bpf_async_kern) > sizeof(struct bpf_wq)); 3044 BUILD_BUG_ON(__alignof__(struct bpf_async_kern) != __alignof__(struct bpf_wq)); 3045 3046 if (flags) 3047 return -EINVAL; 3048 3049 return __bpf_async_init(async, map, flags, BPF_ASYNC_TYPE_WQ); 3050 } 3051 3052 __bpf_kfunc int bpf_wq_start(struct bpf_wq *wq, unsigned int flags) 3053 { 3054 struct bpf_async_kern *async = (struct bpf_async_kern *)wq; 3055 struct bpf_work *w; 3056 3057 if (in_nmi()) 3058 return -EOPNOTSUPP; 3059 if (flags) 3060 return -EINVAL; 3061 w = READ_ONCE(async->work); 3062 if (!w || !READ_ONCE(w->cb.prog)) 3063 return -EINVAL; 3064 3065 schedule_work(&w->work); 3066 return 0; 3067 } 3068 3069 __bpf_kfunc int bpf_wq_set_callback_impl(struct bpf_wq *wq, 3070 int (callback_fn)(void *map, int *key, void *value), 3071 unsigned int flags, 3072 void *aux__prog) 3073 { 3074 struct bpf_prog_aux *aux = (struct bpf_prog_aux *)aux__prog; 3075 struct bpf_async_kern *async = (struct bpf_async_kern *)wq; 3076 3077 if (flags) 3078 return -EINVAL; 3079 3080 return __bpf_async_set_callback(async, callback_fn, aux, flags, BPF_ASYNC_TYPE_WQ); 3081 } 3082 3083 __bpf_kfunc void bpf_preempt_disable(void) 3084 { 3085 preempt_disable(); 3086 } 3087 3088 __bpf_kfunc void bpf_preempt_enable(void) 3089 { 3090 preempt_enable(); 3091 } 3092 3093 struct bpf_iter_bits { 3094 __u64 __opaque[2]; 3095 } __aligned(8); 3096 3097 #define BITS_ITER_NR_WORDS_MAX 511 3098 3099 struct bpf_iter_bits_kern { 3100 union { 3101 __u64 *bits; 3102 __u64 bits_copy; 3103 }; 3104 int nr_bits; 3105 int bit; 3106 } __aligned(8); 3107 3108 /* On 64-bit hosts, unsigned long and u64 have the same size, so passing 3109 * a u64 pointer and an unsigned long pointer to find_next_bit() will 3110 * return the same result, as both point to the same 8-byte area. 3111 * 3112 * For 32-bit little-endian hosts, using a u64 pointer or unsigned long 3113 * pointer also makes no difference. This is because the first iterated 3114 * unsigned long is composed of bits 0-31 of the u64 and the second unsigned 3115 * long is composed of bits 32-63 of the u64. 3116 * 3117 * However, for 32-bit big-endian hosts, this is not the case. The first 3118 * iterated unsigned long will be bits 32-63 of the u64, so swap these two 3119 * ulong values within the u64. 3120 */ 3121 static void swap_ulong_in_u64(u64 *bits, unsigned int nr) 3122 { 3123 #if (BITS_PER_LONG == 32) && defined(__BIG_ENDIAN) 3124 unsigned int i; 3125 3126 for (i = 0; i < nr; i++) 3127 bits[i] = (bits[i] >> 32) | ((u64)(u32)bits[i] << 32); 3128 #endif 3129 } 3130 3131 /** 3132 * bpf_iter_bits_new() - Initialize a new bits iterator for a given memory area 3133 * @it: The new bpf_iter_bits to be created 3134 * @unsafe_ptr__ign: A pointer pointing to a memory area to be iterated over 3135 * @nr_words: The size of the specified memory area, measured in 8-byte units. 3136 * The maximum value of @nr_words is @BITS_ITER_NR_WORDS_MAX. This limit may be 3137 * further reduced by the BPF memory allocator implementation. 3138 * 3139 * This function initializes a new bpf_iter_bits structure for iterating over 3140 * a memory area which is specified by the @unsafe_ptr__ign and @nr_words. It 3141 * copies the data of the memory area to the newly created bpf_iter_bits @it for 3142 * subsequent iteration operations. 3143 * 3144 * On success, 0 is returned. On failure, ERR is returned. 3145 */ 3146 __bpf_kfunc int 3147 bpf_iter_bits_new(struct bpf_iter_bits *it, const u64 *unsafe_ptr__ign, u32 nr_words) 3148 { 3149 struct bpf_iter_bits_kern *kit = (void *)it; 3150 u32 nr_bytes = nr_words * sizeof(u64); 3151 u32 nr_bits = BYTES_TO_BITS(nr_bytes); 3152 int err; 3153 3154 BUILD_BUG_ON(sizeof(struct bpf_iter_bits_kern) != sizeof(struct bpf_iter_bits)); 3155 BUILD_BUG_ON(__alignof__(struct bpf_iter_bits_kern) != 3156 __alignof__(struct bpf_iter_bits)); 3157 3158 kit->nr_bits = 0; 3159 kit->bits_copy = 0; 3160 kit->bit = -1; 3161 3162 if (!unsafe_ptr__ign || !nr_words) 3163 return -EINVAL; 3164 if (nr_words > BITS_ITER_NR_WORDS_MAX) 3165 return -E2BIG; 3166 3167 /* Optimization for u64 mask */ 3168 if (nr_bits == 64) { 3169 err = bpf_probe_read_kernel_common(&kit->bits_copy, nr_bytes, unsafe_ptr__ign); 3170 if (err) 3171 return -EFAULT; 3172 3173 swap_ulong_in_u64(&kit->bits_copy, nr_words); 3174 3175 kit->nr_bits = nr_bits; 3176 return 0; 3177 } 3178 3179 if (bpf_mem_alloc_check_size(false, nr_bytes)) 3180 return -E2BIG; 3181 3182 /* Fallback to memalloc */ 3183 kit->bits = bpf_mem_alloc(&bpf_global_ma, nr_bytes); 3184 if (!kit->bits) 3185 return -ENOMEM; 3186 3187 err = bpf_probe_read_kernel_common(kit->bits, nr_bytes, unsafe_ptr__ign); 3188 if (err) { 3189 bpf_mem_free(&bpf_global_ma, kit->bits); 3190 return err; 3191 } 3192 3193 swap_ulong_in_u64(kit->bits, nr_words); 3194 3195 kit->nr_bits = nr_bits; 3196 return 0; 3197 } 3198 3199 /** 3200 * bpf_iter_bits_next() - Get the next bit in a bpf_iter_bits 3201 * @it: The bpf_iter_bits to be checked 3202 * 3203 * This function returns a pointer to a number representing the value of the 3204 * next bit in the bits. 3205 * 3206 * If there are no further bits available, it returns NULL. 3207 */ 3208 __bpf_kfunc int *bpf_iter_bits_next(struct bpf_iter_bits *it) 3209 { 3210 struct bpf_iter_bits_kern *kit = (void *)it; 3211 int bit = kit->bit, nr_bits = kit->nr_bits; 3212 const void *bits; 3213 3214 if (!nr_bits || bit >= nr_bits) 3215 return NULL; 3216 3217 bits = nr_bits == 64 ? &kit->bits_copy : kit->bits; 3218 bit = find_next_bit(bits, nr_bits, bit + 1); 3219 if (bit >= nr_bits) { 3220 kit->bit = bit; 3221 return NULL; 3222 } 3223 3224 kit->bit = bit; 3225 return &kit->bit; 3226 } 3227 3228 /** 3229 * bpf_iter_bits_destroy() - Destroy a bpf_iter_bits 3230 * @it: The bpf_iter_bits to be destroyed 3231 * 3232 * Destroy the resource associated with the bpf_iter_bits. 3233 */ 3234 __bpf_kfunc void bpf_iter_bits_destroy(struct bpf_iter_bits *it) 3235 { 3236 struct bpf_iter_bits_kern *kit = (void *)it; 3237 3238 if (kit->nr_bits <= 64) 3239 return; 3240 bpf_mem_free(&bpf_global_ma, kit->bits); 3241 } 3242 3243 /** 3244 * bpf_copy_from_user_str() - Copy a string from an unsafe user address 3245 * @dst: Destination address, in kernel space. This buffer must be 3246 * at least @dst__sz bytes long. 3247 * @dst__sz: Maximum number of bytes to copy, includes the trailing NUL. 3248 * @unsafe_ptr__ign: Source address, in user space. 3249 * @flags: The only supported flag is BPF_F_PAD_ZEROS 3250 * 3251 * Copies a NUL-terminated string from userspace to BPF space. If user string is 3252 * too long this will still ensure zero termination in the dst buffer unless 3253 * buffer size is 0. 3254 * 3255 * If BPF_F_PAD_ZEROS flag is set, memset the tail of @dst to 0 on success and 3256 * memset all of @dst on failure. 3257 */ 3258 __bpf_kfunc int bpf_copy_from_user_str(void *dst, u32 dst__sz, const void __user *unsafe_ptr__ign, u64 flags) 3259 { 3260 int ret; 3261 3262 if (unlikely(flags & ~BPF_F_PAD_ZEROS)) 3263 return -EINVAL; 3264 3265 if (unlikely(!dst__sz)) 3266 return 0; 3267 3268 ret = strncpy_from_user(dst, unsafe_ptr__ign, dst__sz - 1); 3269 if (ret < 0) { 3270 if (flags & BPF_F_PAD_ZEROS) 3271 memset((char *)dst, 0, dst__sz); 3272 3273 return ret; 3274 } 3275 3276 if (flags & BPF_F_PAD_ZEROS) 3277 memset((char *)dst + ret, 0, dst__sz - ret); 3278 else 3279 ((char *)dst)[ret] = '\0'; 3280 3281 return ret + 1; 3282 } 3283 3284 /** 3285 * bpf_copy_from_user_task_str() - Copy a string from an task's address space 3286 * @dst: Destination address, in kernel space. This buffer must be 3287 * at least @dst__sz bytes long. 3288 * @dst__sz: Maximum number of bytes to copy, includes the trailing NUL. 3289 * @unsafe_ptr__ign: Source address in the task's address space. 3290 * @tsk: The task whose address space will be used 3291 * @flags: The only supported flag is BPF_F_PAD_ZEROS 3292 * 3293 * Copies a NUL terminated string from a task's address space to @dst__sz 3294 * buffer. If user string is too long this will still ensure zero termination 3295 * in the @dst__sz buffer unless buffer size is 0. 3296 * 3297 * If BPF_F_PAD_ZEROS flag is set, memset the tail of @dst__sz to 0 on success 3298 * and memset all of @dst__sz on failure. 3299 * 3300 * Return: The number of copied bytes on success including the NUL terminator. 3301 * A negative error code on failure. 3302 */ 3303 __bpf_kfunc int bpf_copy_from_user_task_str(void *dst, u32 dst__sz, 3304 const void __user *unsafe_ptr__ign, 3305 struct task_struct *tsk, u64 flags) 3306 { 3307 int ret; 3308 3309 if (unlikely(flags & ~BPF_F_PAD_ZEROS)) 3310 return -EINVAL; 3311 3312 if (unlikely(dst__sz == 0)) 3313 return 0; 3314 3315 ret = copy_remote_vm_str(tsk, (unsigned long)unsafe_ptr__ign, dst, dst__sz, 0); 3316 if (ret < 0) { 3317 if (flags & BPF_F_PAD_ZEROS) 3318 memset(dst, 0, dst__sz); 3319 return ret; 3320 } 3321 3322 if (flags & BPF_F_PAD_ZEROS) 3323 memset(dst + ret, 0, dst__sz - ret); 3324 3325 return ret + 1; 3326 } 3327 3328 /* Keep unsinged long in prototype so that kfunc is usable when emitted to 3329 * vmlinux.h in BPF programs directly, but note that while in BPF prog, the 3330 * unsigned long always points to 8-byte region on stack, the kernel may only 3331 * read and write the 4-bytes on 32-bit. 3332 */ 3333 __bpf_kfunc void bpf_local_irq_save(unsigned long *flags__irq_flag) 3334 { 3335 local_irq_save(*flags__irq_flag); 3336 } 3337 3338 __bpf_kfunc void bpf_local_irq_restore(unsigned long *flags__irq_flag) 3339 { 3340 local_irq_restore(*flags__irq_flag); 3341 } 3342 3343 __bpf_kfunc void __bpf_trap(void) 3344 { 3345 } 3346 3347 /* 3348 * Kfuncs for string operations. 3349 * 3350 * Since strings are not necessarily %NUL-terminated, we cannot directly call 3351 * in-kernel implementations. Instead, we open-code the implementations using 3352 * __get_kernel_nofault instead of plain dereference to make them safe. 3353 */ 3354 3355 static int __bpf_strcasecmp(const char *s1, const char *s2, bool ignore_case) 3356 { 3357 char c1, c2; 3358 int i; 3359 3360 if (!copy_from_kernel_nofault_allowed(s1, 1) || 3361 !copy_from_kernel_nofault_allowed(s2, 1)) { 3362 return -ERANGE; 3363 } 3364 3365 guard(pagefault)(); 3366 for (i = 0; i < XATTR_SIZE_MAX; i++) { 3367 __get_kernel_nofault(&c1, s1, char, err_out); 3368 __get_kernel_nofault(&c2, s2, char, err_out); 3369 if (ignore_case) { 3370 c1 = tolower(c1); 3371 c2 = tolower(c2); 3372 } 3373 if (c1 != c2) 3374 return c1 < c2 ? -1 : 1; 3375 if (c1 == '\0') 3376 return 0; 3377 s1++; 3378 s2++; 3379 } 3380 return -E2BIG; 3381 err_out: 3382 return -EFAULT; 3383 } 3384 3385 /** 3386 * bpf_strcmp - Compare two strings 3387 * @s1__ign: One string 3388 * @s2__ign: Another string 3389 * 3390 * Return: 3391 * * %0 - Strings are equal 3392 * * %-1 - @s1__ign is smaller 3393 * * %1 - @s2__ign is smaller 3394 * * %-EFAULT - Cannot read one of the strings 3395 * * %-E2BIG - One of strings is too large 3396 * * %-ERANGE - One of strings is outside of kernel address space 3397 */ 3398 __bpf_kfunc int bpf_strcmp(const char *s1__ign, const char *s2__ign) 3399 { 3400 return __bpf_strcasecmp(s1__ign, s2__ign, false); 3401 } 3402 3403 /** 3404 * bpf_strcasecmp - Compare two strings, ignoring the case of the characters 3405 * @s1__ign: One string 3406 * @s2__ign: Another string 3407 * 3408 * Return: 3409 * * %0 - Strings are equal 3410 * * %-1 - @s1__ign is smaller 3411 * * %1 - @s2__ign is smaller 3412 * * %-EFAULT - Cannot read one of the strings 3413 * * %-E2BIG - One of strings is too large 3414 * * %-ERANGE - One of strings is outside of kernel address space 3415 */ 3416 __bpf_kfunc int bpf_strcasecmp(const char *s1__ign, const char *s2__ign) 3417 { 3418 return __bpf_strcasecmp(s1__ign, s2__ign, true); 3419 } 3420 3421 /** 3422 * bpf_strnchr - Find a character in a length limited string 3423 * @s__ign: The string to be searched 3424 * @count: The number of characters to be searched 3425 * @c: The character to search for 3426 * 3427 * Note that the %NUL-terminator is considered part of the string, and can 3428 * be searched for. 3429 * 3430 * Return: 3431 * * >=0 - Index of the first occurrence of @c within @s__ign 3432 * * %-ENOENT - @c not found in the first @count characters of @s__ign 3433 * * %-EFAULT - Cannot read @s__ign 3434 * * %-E2BIG - @s__ign is too large 3435 * * %-ERANGE - @s__ign is outside of kernel address space 3436 */ 3437 __bpf_kfunc int bpf_strnchr(const char *s__ign, size_t count, char c) 3438 { 3439 char sc; 3440 int i; 3441 3442 if (!copy_from_kernel_nofault_allowed(s__ign, 1)) 3443 return -ERANGE; 3444 3445 guard(pagefault)(); 3446 for (i = 0; i < count && i < XATTR_SIZE_MAX; i++) { 3447 __get_kernel_nofault(&sc, s__ign, char, err_out); 3448 if (sc == c) 3449 return i; 3450 if (sc == '\0') 3451 return -ENOENT; 3452 s__ign++; 3453 } 3454 return i == XATTR_SIZE_MAX ? -E2BIG : -ENOENT; 3455 err_out: 3456 return -EFAULT; 3457 } 3458 3459 /** 3460 * bpf_strchr - Find the first occurrence of a character in a string 3461 * @s__ign: The string to be searched 3462 * @c: The character to search for 3463 * 3464 * Note that the %NUL-terminator is considered part of the string, and can 3465 * be searched for. 3466 * 3467 * Return: 3468 * * >=0 - The index of the first occurrence of @c within @s__ign 3469 * * %-ENOENT - @c not found in @s__ign 3470 * * %-EFAULT - Cannot read @s__ign 3471 * * %-E2BIG - @s__ign is too large 3472 * * %-ERANGE - @s__ign is outside of kernel address space 3473 */ 3474 __bpf_kfunc int bpf_strchr(const char *s__ign, char c) 3475 { 3476 return bpf_strnchr(s__ign, XATTR_SIZE_MAX, c); 3477 } 3478 3479 /** 3480 * bpf_strchrnul - Find and return a character in a string, or end of string 3481 * @s__ign: The string to be searched 3482 * @c: The character to search for 3483 * 3484 * Return: 3485 * * >=0 - Index of the first occurrence of @c within @s__ign or index of 3486 * the null byte at the end of @s__ign when @c is not found 3487 * * %-EFAULT - Cannot read @s__ign 3488 * * %-E2BIG - @s__ign is too large 3489 * * %-ERANGE - @s__ign is outside of kernel address space 3490 */ 3491 __bpf_kfunc int bpf_strchrnul(const char *s__ign, char c) 3492 { 3493 char sc; 3494 int i; 3495 3496 if (!copy_from_kernel_nofault_allowed(s__ign, 1)) 3497 return -ERANGE; 3498 3499 guard(pagefault)(); 3500 for (i = 0; i < XATTR_SIZE_MAX; i++) { 3501 __get_kernel_nofault(&sc, s__ign, char, err_out); 3502 if (sc == '\0' || sc == c) 3503 return i; 3504 s__ign++; 3505 } 3506 return -E2BIG; 3507 err_out: 3508 return -EFAULT; 3509 } 3510 3511 /** 3512 * bpf_strrchr - Find the last occurrence of a character in a string 3513 * @s__ign: The string to be searched 3514 * @c: The character to search for 3515 * 3516 * Return: 3517 * * >=0 - Index of the last occurrence of @c within @s__ign 3518 * * %-ENOENT - @c not found in @s__ign 3519 * * %-EFAULT - Cannot read @s__ign 3520 * * %-E2BIG - @s__ign is too large 3521 * * %-ERANGE - @s__ign is outside of kernel address space 3522 */ 3523 __bpf_kfunc int bpf_strrchr(const char *s__ign, int c) 3524 { 3525 char sc; 3526 int i, last = -ENOENT; 3527 3528 if (!copy_from_kernel_nofault_allowed(s__ign, 1)) 3529 return -ERANGE; 3530 3531 guard(pagefault)(); 3532 for (i = 0; i < XATTR_SIZE_MAX; i++) { 3533 __get_kernel_nofault(&sc, s__ign, char, err_out); 3534 if (sc == c) 3535 last = i; 3536 if (sc == '\0') 3537 return last; 3538 s__ign++; 3539 } 3540 return -E2BIG; 3541 err_out: 3542 return -EFAULT; 3543 } 3544 3545 /** 3546 * bpf_strnlen - Calculate the length of a length-limited string 3547 * @s__ign: The string 3548 * @count: The maximum number of characters to count 3549 * 3550 * Return: 3551 * * >=0 - The length of @s__ign 3552 * * %-EFAULT - Cannot read @s__ign 3553 * * %-E2BIG - @s__ign is too large 3554 * * %-ERANGE - @s__ign is outside of kernel address space 3555 */ 3556 __bpf_kfunc int bpf_strnlen(const char *s__ign, size_t count) 3557 { 3558 char c; 3559 int i; 3560 3561 if (!copy_from_kernel_nofault_allowed(s__ign, 1)) 3562 return -ERANGE; 3563 3564 guard(pagefault)(); 3565 for (i = 0; i < count && i < XATTR_SIZE_MAX; i++) { 3566 __get_kernel_nofault(&c, s__ign, char, err_out); 3567 if (c == '\0') 3568 return i; 3569 s__ign++; 3570 } 3571 return i == XATTR_SIZE_MAX ? -E2BIG : i; 3572 err_out: 3573 return -EFAULT; 3574 } 3575 3576 /** 3577 * bpf_strlen - Calculate the length of a string 3578 * @s__ign: The string 3579 * 3580 * Return: 3581 * * >=0 - The length of @s__ign 3582 * * %-EFAULT - Cannot read @s__ign 3583 * * %-E2BIG - @s__ign is too large 3584 * * %-ERANGE - @s__ign is outside of kernel address space 3585 */ 3586 __bpf_kfunc int bpf_strlen(const char *s__ign) 3587 { 3588 return bpf_strnlen(s__ign, XATTR_SIZE_MAX); 3589 } 3590 3591 /** 3592 * bpf_strspn - Calculate the length of the initial substring of @s__ign which 3593 * only contains letters in @accept__ign 3594 * @s__ign: The string to be searched 3595 * @accept__ign: The string to search for 3596 * 3597 * Return: 3598 * * >=0 - The length of the initial substring of @s__ign which only 3599 * contains letters from @accept__ign 3600 * * %-EFAULT - Cannot read one of the strings 3601 * * %-E2BIG - One of the strings is too large 3602 * * %-ERANGE - One of the strings is outside of kernel address space 3603 */ 3604 __bpf_kfunc int bpf_strspn(const char *s__ign, const char *accept__ign) 3605 { 3606 char cs, ca; 3607 int i, j; 3608 3609 if (!copy_from_kernel_nofault_allowed(s__ign, 1) || 3610 !copy_from_kernel_nofault_allowed(accept__ign, 1)) { 3611 return -ERANGE; 3612 } 3613 3614 guard(pagefault)(); 3615 for (i = 0; i < XATTR_SIZE_MAX; i++) { 3616 __get_kernel_nofault(&cs, s__ign, char, err_out); 3617 if (cs == '\0') 3618 return i; 3619 for (j = 0; j < XATTR_SIZE_MAX; j++) { 3620 __get_kernel_nofault(&ca, accept__ign + j, char, err_out); 3621 if (cs == ca || ca == '\0') 3622 break; 3623 } 3624 if (j == XATTR_SIZE_MAX) 3625 return -E2BIG; 3626 if (ca == '\0') 3627 return i; 3628 s__ign++; 3629 } 3630 return -E2BIG; 3631 err_out: 3632 return -EFAULT; 3633 } 3634 3635 /** 3636 * bpf_strcspn - Calculate the length of the initial substring of @s__ign which 3637 * does not contain letters in @reject__ign 3638 * @s__ign: The string to be searched 3639 * @reject__ign: The string to search for 3640 * 3641 * Return: 3642 * * >=0 - The length of the initial substring of @s__ign which does not 3643 * contain letters from @reject__ign 3644 * * %-EFAULT - Cannot read one of the strings 3645 * * %-E2BIG - One of the strings is too large 3646 * * %-ERANGE - One of the strings is outside of kernel address space 3647 */ 3648 __bpf_kfunc int bpf_strcspn(const char *s__ign, const char *reject__ign) 3649 { 3650 char cs, cr; 3651 int i, j; 3652 3653 if (!copy_from_kernel_nofault_allowed(s__ign, 1) || 3654 !copy_from_kernel_nofault_allowed(reject__ign, 1)) { 3655 return -ERANGE; 3656 } 3657 3658 guard(pagefault)(); 3659 for (i = 0; i < XATTR_SIZE_MAX; i++) { 3660 __get_kernel_nofault(&cs, s__ign, char, err_out); 3661 if (cs == '\0') 3662 return i; 3663 for (j = 0; j < XATTR_SIZE_MAX; j++) { 3664 __get_kernel_nofault(&cr, reject__ign + j, char, err_out); 3665 if (cs == cr || cr == '\0') 3666 break; 3667 } 3668 if (j == XATTR_SIZE_MAX) 3669 return -E2BIG; 3670 if (cr != '\0') 3671 return i; 3672 s__ign++; 3673 } 3674 return -E2BIG; 3675 err_out: 3676 return -EFAULT; 3677 } 3678 3679 /** 3680 * bpf_strnstr - Find the first substring in a length-limited string 3681 * @s1__ign: The string to be searched 3682 * @s2__ign: The string to search for 3683 * @len: the maximum number of characters to search 3684 * 3685 * Return: 3686 * * >=0 - Index of the first character of the first occurrence of @s2__ign 3687 * within the first @len characters of @s1__ign 3688 * * %-ENOENT - @s2__ign not found in the first @len characters of @s1__ign 3689 * * %-EFAULT - Cannot read one of the strings 3690 * * %-E2BIG - One of the strings is too large 3691 * * %-ERANGE - One of the strings is outside of kernel address space 3692 */ 3693 __bpf_kfunc int bpf_strnstr(const char *s1__ign, const char *s2__ign, size_t len) 3694 { 3695 char c1, c2; 3696 int i, j; 3697 3698 if (!copy_from_kernel_nofault_allowed(s1__ign, 1) || 3699 !copy_from_kernel_nofault_allowed(s2__ign, 1)) { 3700 return -ERANGE; 3701 } 3702 3703 guard(pagefault)(); 3704 for (i = 0; i < XATTR_SIZE_MAX; i++) { 3705 for (j = 0; i + j <= len && j < XATTR_SIZE_MAX; j++) { 3706 __get_kernel_nofault(&c2, s2__ign + j, char, err_out); 3707 if (c2 == '\0') 3708 return i; 3709 /* 3710 * We allow reading an extra byte from s2 (note the 3711 * `i + j <= len` above) to cover the case when s2 is 3712 * a suffix of the first len chars of s1. 3713 */ 3714 if (i + j == len) 3715 break; 3716 __get_kernel_nofault(&c1, s1__ign + j, char, err_out); 3717 if (c1 == '\0') 3718 return -ENOENT; 3719 if (c1 != c2) 3720 break; 3721 } 3722 if (j == XATTR_SIZE_MAX) 3723 return -E2BIG; 3724 if (i + j == len) 3725 return -ENOENT; 3726 s1__ign++; 3727 } 3728 return -E2BIG; 3729 err_out: 3730 return -EFAULT; 3731 } 3732 3733 /** 3734 * bpf_strstr - Find the first substring in a string 3735 * @s1__ign: The string to be searched 3736 * @s2__ign: The string to search for 3737 * 3738 * Return: 3739 * * >=0 - Index of the first character of the first occurrence of @s2__ign 3740 * within @s1__ign 3741 * * %-ENOENT - @s2__ign is not a substring of @s1__ign 3742 * * %-EFAULT - Cannot read one of the strings 3743 * * %-E2BIG - One of the strings is too large 3744 * * %-ERANGE - One of the strings is outside of kernel address space 3745 */ 3746 __bpf_kfunc int bpf_strstr(const char *s1__ign, const char *s2__ign) 3747 { 3748 return bpf_strnstr(s1__ign, s2__ign, XATTR_SIZE_MAX); 3749 } 3750 3751 __bpf_kfunc_end_defs(); 3752 3753 BTF_KFUNCS_START(generic_btf_ids) 3754 #ifdef CONFIG_CRASH_DUMP 3755 BTF_ID_FLAGS(func, crash_kexec, KF_DESTRUCTIVE) 3756 #endif 3757 BTF_ID_FLAGS(func, bpf_obj_new_impl, KF_ACQUIRE | KF_RET_NULL) 3758 BTF_ID_FLAGS(func, bpf_percpu_obj_new_impl, KF_ACQUIRE | KF_RET_NULL) 3759 BTF_ID_FLAGS(func, bpf_obj_drop_impl, KF_RELEASE) 3760 BTF_ID_FLAGS(func, bpf_percpu_obj_drop_impl, KF_RELEASE) 3761 BTF_ID_FLAGS(func, bpf_refcount_acquire_impl, KF_ACQUIRE | KF_RET_NULL | KF_RCU) 3762 BTF_ID_FLAGS(func, bpf_list_push_front_impl) 3763 BTF_ID_FLAGS(func, bpf_list_push_back_impl) 3764 BTF_ID_FLAGS(func, bpf_list_pop_front, KF_ACQUIRE | KF_RET_NULL) 3765 BTF_ID_FLAGS(func, bpf_list_pop_back, KF_ACQUIRE | KF_RET_NULL) 3766 BTF_ID_FLAGS(func, bpf_list_front, KF_RET_NULL) 3767 BTF_ID_FLAGS(func, bpf_list_back, KF_RET_NULL) 3768 BTF_ID_FLAGS(func, bpf_task_acquire, KF_ACQUIRE | KF_RCU | KF_RET_NULL) 3769 BTF_ID_FLAGS(func, bpf_task_release, KF_RELEASE) 3770 BTF_ID_FLAGS(func, bpf_rbtree_remove, KF_ACQUIRE | KF_RET_NULL) 3771 BTF_ID_FLAGS(func, bpf_rbtree_add_impl) 3772 BTF_ID_FLAGS(func, bpf_rbtree_first, KF_RET_NULL) 3773 BTF_ID_FLAGS(func, bpf_rbtree_root, KF_RET_NULL) 3774 BTF_ID_FLAGS(func, bpf_rbtree_left, KF_RET_NULL) 3775 BTF_ID_FLAGS(func, bpf_rbtree_right, KF_RET_NULL) 3776 3777 #ifdef CONFIG_CGROUPS 3778 BTF_ID_FLAGS(func, bpf_cgroup_acquire, KF_ACQUIRE | KF_RCU | KF_RET_NULL) 3779 BTF_ID_FLAGS(func, bpf_cgroup_release, KF_RELEASE) 3780 BTF_ID_FLAGS(func, bpf_cgroup_ancestor, KF_ACQUIRE | KF_RCU | KF_RET_NULL) 3781 BTF_ID_FLAGS(func, bpf_cgroup_from_id, KF_ACQUIRE | KF_RET_NULL) 3782 BTF_ID_FLAGS(func, bpf_task_under_cgroup, KF_RCU) 3783 BTF_ID_FLAGS(func, bpf_task_get_cgroup1, KF_ACQUIRE | KF_RCU | KF_RET_NULL) 3784 #endif 3785 BTF_ID_FLAGS(func, bpf_task_from_pid, KF_ACQUIRE | KF_RET_NULL) 3786 BTF_ID_FLAGS(func, bpf_task_from_vpid, KF_ACQUIRE | KF_RET_NULL) 3787 BTF_ID_FLAGS(func, bpf_throw) 3788 #ifdef CONFIG_BPF_EVENTS 3789 BTF_ID_FLAGS(func, bpf_send_signal_task, KF_TRUSTED_ARGS) 3790 #endif 3791 BTF_KFUNCS_END(generic_btf_ids) 3792 3793 static const struct btf_kfunc_id_set generic_kfunc_set = { 3794 .owner = THIS_MODULE, 3795 .set = &generic_btf_ids, 3796 }; 3797 3798 3799 BTF_ID_LIST(generic_dtor_ids) 3800 BTF_ID(struct, task_struct) 3801 BTF_ID(func, bpf_task_release_dtor) 3802 #ifdef CONFIG_CGROUPS 3803 BTF_ID(struct, cgroup) 3804 BTF_ID(func, bpf_cgroup_release_dtor) 3805 #endif 3806 3807 BTF_KFUNCS_START(common_btf_ids) 3808 BTF_ID_FLAGS(func, bpf_cast_to_kern_ctx, KF_FASTCALL) 3809 BTF_ID_FLAGS(func, bpf_rdonly_cast, KF_FASTCALL) 3810 BTF_ID_FLAGS(func, bpf_rcu_read_lock) 3811 BTF_ID_FLAGS(func, bpf_rcu_read_unlock) 3812 BTF_ID_FLAGS(func, bpf_dynptr_slice, KF_RET_NULL) 3813 BTF_ID_FLAGS(func, bpf_dynptr_slice_rdwr, KF_RET_NULL) 3814 BTF_ID_FLAGS(func, bpf_iter_num_new, KF_ITER_NEW) 3815 BTF_ID_FLAGS(func, bpf_iter_num_next, KF_ITER_NEXT | KF_RET_NULL) 3816 BTF_ID_FLAGS(func, bpf_iter_num_destroy, KF_ITER_DESTROY) 3817 BTF_ID_FLAGS(func, bpf_iter_task_vma_new, KF_ITER_NEW | KF_RCU) 3818 BTF_ID_FLAGS(func, bpf_iter_task_vma_next, KF_ITER_NEXT | KF_RET_NULL) 3819 BTF_ID_FLAGS(func, bpf_iter_task_vma_destroy, KF_ITER_DESTROY) 3820 #ifdef CONFIG_CGROUPS 3821 BTF_ID_FLAGS(func, bpf_iter_css_task_new, KF_ITER_NEW | KF_TRUSTED_ARGS) 3822 BTF_ID_FLAGS(func, bpf_iter_css_task_next, KF_ITER_NEXT | KF_RET_NULL) 3823 BTF_ID_FLAGS(func, bpf_iter_css_task_destroy, KF_ITER_DESTROY) 3824 BTF_ID_FLAGS(func, bpf_iter_css_new, KF_ITER_NEW | KF_TRUSTED_ARGS | KF_RCU_PROTECTED) 3825 BTF_ID_FLAGS(func, bpf_iter_css_next, KF_ITER_NEXT | KF_RET_NULL) 3826 BTF_ID_FLAGS(func, bpf_iter_css_destroy, KF_ITER_DESTROY) 3827 #endif 3828 BTF_ID_FLAGS(func, bpf_iter_task_new, KF_ITER_NEW | KF_TRUSTED_ARGS | KF_RCU_PROTECTED) 3829 BTF_ID_FLAGS(func, bpf_iter_task_next, KF_ITER_NEXT | KF_RET_NULL) 3830 BTF_ID_FLAGS(func, bpf_iter_task_destroy, KF_ITER_DESTROY) 3831 BTF_ID_FLAGS(func, bpf_dynptr_adjust) 3832 BTF_ID_FLAGS(func, bpf_dynptr_is_null) 3833 BTF_ID_FLAGS(func, bpf_dynptr_is_rdonly) 3834 BTF_ID_FLAGS(func, bpf_dynptr_size) 3835 BTF_ID_FLAGS(func, bpf_dynptr_clone) 3836 BTF_ID_FLAGS(func, bpf_dynptr_copy) 3837 BTF_ID_FLAGS(func, bpf_dynptr_memset) 3838 #ifdef CONFIG_NET 3839 BTF_ID_FLAGS(func, bpf_modify_return_test_tp) 3840 #endif 3841 BTF_ID_FLAGS(func, bpf_wq_init) 3842 BTF_ID_FLAGS(func, bpf_wq_set_callback_impl) 3843 BTF_ID_FLAGS(func, bpf_wq_start) 3844 BTF_ID_FLAGS(func, bpf_preempt_disable) 3845 BTF_ID_FLAGS(func, bpf_preempt_enable) 3846 BTF_ID_FLAGS(func, bpf_iter_bits_new, KF_ITER_NEW) 3847 BTF_ID_FLAGS(func, bpf_iter_bits_next, KF_ITER_NEXT | KF_RET_NULL) 3848 BTF_ID_FLAGS(func, bpf_iter_bits_destroy, KF_ITER_DESTROY) 3849 BTF_ID_FLAGS(func, bpf_copy_from_user_str, KF_SLEEPABLE) 3850 BTF_ID_FLAGS(func, bpf_copy_from_user_task_str, KF_SLEEPABLE) 3851 BTF_ID_FLAGS(func, bpf_get_kmem_cache) 3852 BTF_ID_FLAGS(func, bpf_iter_kmem_cache_new, KF_ITER_NEW | KF_SLEEPABLE) 3853 BTF_ID_FLAGS(func, bpf_iter_kmem_cache_next, KF_ITER_NEXT | KF_RET_NULL | KF_SLEEPABLE) 3854 BTF_ID_FLAGS(func, bpf_iter_kmem_cache_destroy, KF_ITER_DESTROY | KF_SLEEPABLE) 3855 BTF_ID_FLAGS(func, bpf_local_irq_save) 3856 BTF_ID_FLAGS(func, bpf_local_irq_restore) 3857 BTF_ID_FLAGS(func, bpf_probe_read_user_dynptr) 3858 BTF_ID_FLAGS(func, bpf_probe_read_kernel_dynptr) 3859 BTF_ID_FLAGS(func, bpf_probe_read_user_str_dynptr) 3860 BTF_ID_FLAGS(func, bpf_probe_read_kernel_str_dynptr) 3861 BTF_ID_FLAGS(func, bpf_copy_from_user_dynptr, KF_SLEEPABLE) 3862 BTF_ID_FLAGS(func, bpf_copy_from_user_str_dynptr, KF_SLEEPABLE) 3863 BTF_ID_FLAGS(func, bpf_copy_from_user_task_dynptr, KF_SLEEPABLE | KF_TRUSTED_ARGS) 3864 BTF_ID_FLAGS(func, bpf_copy_from_user_task_str_dynptr, KF_SLEEPABLE | KF_TRUSTED_ARGS) 3865 #ifdef CONFIG_DMA_SHARED_BUFFER 3866 BTF_ID_FLAGS(func, bpf_iter_dmabuf_new, KF_ITER_NEW | KF_SLEEPABLE) 3867 BTF_ID_FLAGS(func, bpf_iter_dmabuf_next, KF_ITER_NEXT | KF_RET_NULL | KF_SLEEPABLE) 3868 BTF_ID_FLAGS(func, bpf_iter_dmabuf_destroy, KF_ITER_DESTROY | KF_SLEEPABLE) 3869 #endif 3870 BTF_ID_FLAGS(func, __bpf_trap) 3871 BTF_ID_FLAGS(func, bpf_strcmp); 3872 BTF_ID_FLAGS(func, bpf_strcasecmp); 3873 BTF_ID_FLAGS(func, bpf_strchr); 3874 BTF_ID_FLAGS(func, bpf_strchrnul); 3875 BTF_ID_FLAGS(func, bpf_strnchr); 3876 BTF_ID_FLAGS(func, bpf_strrchr); 3877 BTF_ID_FLAGS(func, bpf_strlen); 3878 BTF_ID_FLAGS(func, bpf_strnlen); 3879 BTF_ID_FLAGS(func, bpf_strspn); 3880 BTF_ID_FLAGS(func, bpf_strcspn); 3881 BTF_ID_FLAGS(func, bpf_strstr); 3882 BTF_ID_FLAGS(func, bpf_strnstr); 3883 #if defined(CONFIG_BPF_LSM) && defined(CONFIG_CGROUPS) 3884 BTF_ID_FLAGS(func, bpf_cgroup_read_xattr, KF_RCU) 3885 #endif 3886 BTF_ID_FLAGS(func, bpf_stream_vprintk, KF_TRUSTED_ARGS) 3887 BTF_KFUNCS_END(common_btf_ids) 3888 3889 static const struct btf_kfunc_id_set common_kfunc_set = { 3890 .owner = THIS_MODULE, 3891 .set = &common_btf_ids, 3892 }; 3893 3894 static int __init kfunc_init(void) 3895 { 3896 int ret; 3897 const struct btf_id_dtor_kfunc generic_dtors[] = { 3898 { 3899 .btf_id = generic_dtor_ids[0], 3900 .kfunc_btf_id = generic_dtor_ids[1] 3901 }, 3902 #ifdef CONFIG_CGROUPS 3903 { 3904 .btf_id = generic_dtor_ids[2], 3905 .kfunc_btf_id = generic_dtor_ids[3] 3906 }, 3907 #endif 3908 }; 3909 3910 ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_TRACING, &generic_kfunc_set); 3911 ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_SCHED_CLS, &generic_kfunc_set); 3912 ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_XDP, &generic_kfunc_set); 3913 ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS, &generic_kfunc_set); 3914 ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_SYSCALL, &generic_kfunc_set); 3915 ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_CGROUP_SKB, &generic_kfunc_set); 3916 ret = ret ?: register_btf_id_dtor_kfuncs(generic_dtors, 3917 ARRAY_SIZE(generic_dtors), 3918 THIS_MODULE); 3919 return ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_UNSPEC, &common_kfunc_set); 3920 } 3921 3922 late_initcall(kfunc_init); 3923 3924 /* Get a pointer to dynptr data up to len bytes for read only access. If 3925 * the dynptr doesn't have continuous data up to len bytes, return NULL. 3926 */ 3927 const void *__bpf_dynptr_data(const struct bpf_dynptr_kern *ptr, u32 len) 3928 { 3929 const struct bpf_dynptr *p = (struct bpf_dynptr *)ptr; 3930 3931 return bpf_dynptr_slice(p, 0, NULL, len); 3932 } 3933 3934 /* Get a pointer to dynptr data up to len bytes for read write access. If 3935 * the dynptr doesn't have continuous data up to len bytes, or the dynptr 3936 * is read only, return NULL. 3937 */ 3938 void *__bpf_dynptr_data_rw(const struct bpf_dynptr_kern *ptr, u32 len) 3939 { 3940 if (__bpf_dynptr_is_rdonly(ptr)) 3941 return NULL; 3942 return (void *)__bpf_dynptr_data(ptr, len); 3943 } 3944