1 // SPDX-License-Identifier: GPL-2.0-only 2 /* Copyright (c) 2016 Facebook 3 */ 4 #include <linux/bpf.h> 5 #include <linux/jhash.h> 6 #include <linux/filter.h> 7 #include <linux/kernel.h> 8 #include <linux/stacktrace.h> 9 #include <linux/perf_event.h> 10 #include <linux/btf_ids.h> 11 #include <linux/buildid.h> 12 #include <linux/mmap_lock.h> 13 #include "percpu_freelist.h" 14 #include "mmap_unlock_work.h" 15 16 #define STACK_CREATE_FLAG_MASK \ 17 (BPF_F_NUMA_NODE | BPF_F_RDONLY | BPF_F_WRONLY | \ 18 BPF_F_STACK_BUILD_ID) 19 20 struct stack_map_bucket { 21 struct pcpu_freelist_node fnode; 22 u32 hash; 23 u32 nr; 24 u64 data[]; 25 }; 26 27 struct bpf_stack_map { 28 struct bpf_map map; 29 void *elems; 30 struct pcpu_freelist freelist; 31 u32 n_buckets; 32 struct stack_map_bucket *buckets[] __counted_by(n_buckets); 33 }; 34 35 static inline bool stack_map_use_build_id(struct bpf_map *map) 36 { 37 return (map->map_flags & BPF_F_STACK_BUILD_ID); 38 } 39 40 static inline int stack_map_data_size(struct bpf_map *map) 41 { 42 return stack_map_use_build_id(map) ? 43 sizeof(struct bpf_stack_build_id) : sizeof(u64); 44 } 45 46 /** 47 * stack_map_calculate_max_depth - Calculate maximum allowed stack trace depth 48 * @size: Size of the buffer/map value in bytes 49 * @elem_size: Size of each stack trace element 50 * @flags: BPF stack trace flags (BPF_F_USER_STACK, BPF_F_USER_BUILD_ID, ...) 51 * 52 * Return: Maximum number of stack trace entries that can be safely stored 53 */ 54 static u32 stack_map_calculate_max_depth(u32 size, u32 elem_size, u64 flags) 55 { 56 u32 skip = flags & BPF_F_SKIP_FIELD_MASK; 57 u32 max_depth; 58 u32 curr_sysctl_max_stack = READ_ONCE(sysctl_perf_event_max_stack); 59 60 max_depth = size / elem_size; 61 max_depth += skip; 62 if (max_depth > curr_sysctl_max_stack) 63 return curr_sysctl_max_stack; 64 65 return max_depth; 66 } 67 68 static int prealloc_elems_and_freelist(struct bpf_stack_map *smap) 69 { 70 u64 elem_size = sizeof(struct stack_map_bucket) + 71 (u64)smap->map.value_size; 72 int err; 73 74 smap->elems = bpf_map_area_alloc(elem_size * smap->map.max_entries, 75 smap->map.numa_node); 76 if (!smap->elems) 77 return -ENOMEM; 78 79 err = pcpu_freelist_init(&smap->freelist); 80 if (err) 81 goto free_elems; 82 83 pcpu_freelist_populate(&smap->freelist, smap->elems, elem_size, 84 smap->map.max_entries); 85 return 0; 86 87 free_elems: 88 bpf_map_area_free(smap->elems); 89 return err; 90 } 91 92 /* Called from syscall */ 93 static struct bpf_map *stack_map_alloc(union bpf_attr *attr) 94 { 95 u32 value_size = attr->value_size; 96 struct bpf_stack_map *smap; 97 u64 cost, n_buckets; 98 int err; 99 100 if (attr->map_flags & ~STACK_CREATE_FLAG_MASK) 101 return ERR_PTR(-EINVAL); 102 103 /* check sanity of attributes */ 104 if (attr->max_entries == 0 || attr->key_size != 4 || 105 value_size < 8 || value_size % 8) 106 return ERR_PTR(-EINVAL); 107 108 BUILD_BUG_ON(sizeof(struct bpf_stack_build_id) % sizeof(u64)); 109 if (attr->map_flags & BPF_F_STACK_BUILD_ID) { 110 if (value_size % sizeof(struct bpf_stack_build_id) || 111 value_size / sizeof(struct bpf_stack_build_id) 112 > sysctl_perf_event_max_stack) 113 return ERR_PTR(-EINVAL); 114 } else if (value_size / 8 > sysctl_perf_event_max_stack) 115 return ERR_PTR(-EINVAL); 116 117 /* hash table size must be power of 2; roundup_pow_of_two() can overflow 118 * into UB on 32-bit arches, so check that first 119 */ 120 if (attr->max_entries > 1UL << 31) 121 return ERR_PTR(-E2BIG); 122 123 n_buckets = roundup_pow_of_two(attr->max_entries); 124 125 cost = n_buckets * sizeof(struct stack_map_bucket *) + sizeof(*smap); 126 smap = bpf_map_area_alloc(cost, bpf_map_attr_numa_node(attr)); 127 if (!smap) 128 return ERR_PTR(-ENOMEM); 129 130 bpf_map_init_from_attr(&smap->map, attr); 131 smap->n_buckets = n_buckets; 132 133 err = get_callchain_buffers(sysctl_perf_event_max_stack); 134 if (err) 135 goto free_smap; 136 137 err = prealloc_elems_and_freelist(smap); 138 if (err) 139 goto put_buffers; 140 141 return &smap->map; 142 143 put_buffers: 144 put_callchain_buffers(); 145 free_smap: 146 bpf_map_area_free(smap); 147 return ERR_PTR(err); 148 } 149 150 static int fetch_build_id(struct vm_area_struct *vma, unsigned char *build_id, bool may_fault) 151 { 152 return may_fault ? build_id_parse(vma, build_id, NULL) 153 : build_id_parse_nofault(vma, build_id, NULL); 154 } 155 156 static inline void stack_map_build_id_set_ip(struct bpf_stack_build_id *id) 157 { 158 id->status = BPF_STACK_BUILD_ID_IP; 159 memset(id->build_id, 0, BUILD_ID_SIZE_MAX); 160 } 161 162 static inline u64 stack_map_build_id_offset(unsigned long vm_pgoff, 163 unsigned long vm_start, u64 ip) 164 { 165 return (vm_pgoff << PAGE_SHIFT) + ip - vm_start; 166 } 167 168 static inline void stack_map_build_id_set_valid(struct bpf_stack_build_id *id, 169 u64 offset, 170 const unsigned char *build_id) 171 { 172 id->status = BPF_STACK_BUILD_ID_VALID; 173 id->offset = offset; 174 if (id->build_id != build_id) 175 memcpy(id->build_id, build_id, BUILD_ID_SIZE_MAX); 176 } 177 178 /* 179 * A cached VMA lookup result. The range [vm_start, vm_end) is always set. 180 * vm_pgoff, file, build_id are set only when the build ID was resolved. 181 * Zero vm_end marks the slot empty. build_id aliases the id_offs[] entry. 182 */ 183 struct stack_map_cached_vma { 184 unsigned long vm_start; 185 unsigned long vm_end; 186 unsigned long vm_pgoff; 187 struct file *file; /* pinned in the sleepable path; NULL otherwise */ 188 const unsigned char *build_id; 189 }; 190 191 /* 192 * Per stack_map_get_build_id_offset() call cache of the last VMA with a build ID 193 * resolved and the last VMA with no usable build ID. Adjacent stack frames tend 194 * to land in the same VMA or the same backing file, so caching the last result 195 * of each kind lets us skip unnecessary VMA lookups and build ID parse calls. 196 * Keeping the two slots independent means a build-ID-less VMA doesn't evict the 197 * last resolved build ID. 198 */ 199 struct stack_map_build_id_cache { 200 struct stack_map_cached_vma resolved; 201 struct stack_map_cached_vma unresolved; 202 }; 203 204 /* 205 * Fill @id from a cached range covering @ip. On a hit this writes @id (resolved 206 * range -> build ID + offset, unresolved range -> raw ip) and returns 0; on a 207 * miss it leaves @id untouched and returns -ENOENT. 208 */ 209 static int stack_map_build_id_set_from_cache(struct stack_map_build_id_cache *cache, 210 struct bpf_stack_build_id *id, u64 ip) 211 { 212 unsigned long vm_start, vm_end, vm_pgoff; 213 u64 offset; 214 215 vm_start = cache->resolved.vm_start; 216 vm_end = cache->resolved.vm_end; 217 if (vm_end && ip >= vm_start && ip < vm_end) { 218 vm_pgoff = cache->resolved.vm_pgoff; 219 offset = stack_map_build_id_offset(vm_pgoff, vm_start, ip); 220 stack_map_build_id_set_valid(id, offset, cache->resolved.build_id); 221 return 0; 222 } 223 224 vm_start = cache->unresolved.vm_start; 225 vm_end = cache->unresolved.vm_end; 226 if (vm_end && ip >= vm_start && ip < vm_end) { 227 stack_map_build_id_set_ip(id); 228 return 0; 229 } 230 231 return -ENOENT; 232 } 233 234 /* 235 * Record @vma's build ID as the last resolved one. @file is the pinned backing 236 * file in the sleepable path (released when evicted), or NULL otherwise. 237 */ 238 static void stack_map_build_id_cache_set_resolved(struct stack_map_build_id_cache *cache, 239 struct file *file, 240 const unsigned char *build_id, 241 unsigned long vm_start, 242 unsigned long vm_end, 243 unsigned long vm_pgoff) 244 { 245 if (cache->resolved.file) 246 fput(cache->resolved.file); 247 cache->resolved = (struct stack_map_cached_vma){ 248 .vm_start = vm_start, 249 .vm_end = vm_end, 250 .vm_pgoff = vm_pgoff, 251 .file = file, 252 .build_id = build_id, 253 }; 254 } 255 256 /* Record [vm_start, vm_end) as a range with no usable build ID. */ 257 static void stack_map_build_id_cache_set_unresolved(struct stack_map_build_id_cache *cache, 258 unsigned long vm_start, 259 unsigned long vm_end) 260 { 261 cache->unresolved = (struct stack_map_cached_vma){ 262 .vm_start = vm_start, 263 .vm_end = vm_end, 264 }; 265 } 266 267 struct stack_map_vma_lock { 268 struct vm_area_struct *vma; 269 struct mm_struct *mm; 270 }; 271 272 /* 273 * Acquire a stable read-side reference on the VMA covering @ip. 274 * 275 * With CONFIG_PER_VMA_LOCK=y this returns a VMA with its per-VMA read 276 * lock held and mmap_lock dropped, so the caller may sleep. 277 * 278 * With CONFIG_PER_VMA_LOCK=n it returns a VMA with mmap_lock still 279 * held; the caller must snapshot any fields it needs and pin vm_file 280 * with get_file() before stack_map_unlock_vma() drops mmap_lock, as 281 * the VMA may be split, merged, or freed after that. 282 * 283 * Returns NULL on failure, in which case no lock is held. 284 */ 285 static struct vm_area_struct * 286 stack_map_lock_vma(struct stack_map_vma_lock *lock, unsigned long ip) 287 { 288 struct mm_struct *mm = lock->mm; 289 struct vm_area_struct *vma; 290 291 /* noop under !CONFIG_PER_VMA_LOCK */ 292 vma = lock_vma_under_rcu(mm, ip); 293 if (vma) { 294 lock->vma = vma; 295 return vma; 296 } 297 298 /* 299 * Taking mmap_read_lock() is unsafe here, because the caller BPF 300 * program might already hold it, causing a deadlock. 301 */ 302 if (!mmap_read_trylock(mm)) 303 return NULL; 304 305 vma = vma_lookup(mm, ip); 306 if (!vma) { 307 mmap_read_unlock(mm); 308 return NULL; 309 } 310 311 #ifdef CONFIG_PER_VMA_LOCK 312 if (!vma_start_read_locked(vma)) { 313 mmap_read_unlock(mm); 314 return NULL; 315 } 316 mmap_read_unlock(mm); 317 #endif 318 319 lock->vma = vma; 320 return vma; 321 } 322 323 static void stack_map_unlock_vma(struct stack_map_vma_lock *lock) 324 { 325 #ifdef CONFIG_PER_VMA_LOCK 326 vma_end_read(lock->vma); 327 #else 328 mmap_read_unlock(lock->mm); 329 #endif 330 lock->vma = NULL; 331 } 332 333 static void stack_map_get_build_id_offset_sleepable(struct bpf_stack_build_id *id_offs, 334 u32 trace_nr) 335 { 336 struct stack_map_vma_lock lock = { .mm = current->mm }; 337 struct stack_map_build_id_cache cache = {}; 338 struct stack_map_cached_vma *res = &cache.resolved; 339 unsigned long vm_pgoff, vm_start, vm_end; 340 struct vm_area_struct *vma; 341 struct file *file; 342 u64 offset; 343 u64 ip; 344 345 for (u32 i = 0; i < trace_nr; i++) { 346 ip = READ_ONCE(id_offs[i].ip); 347 348 if (!stack_map_build_id_set_from_cache(&cache, &id_offs[i], ip)) 349 continue; 350 351 vma = stack_map_lock_vma(&lock, ip); 352 if (!vma) { 353 stack_map_build_id_set_ip(&id_offs[i]); 354 continue; 355 } 356 357 vm_pgoff = vma->vm_pgoff; 358 vm_start = vma->vm_start; 359 vm_end = vma->vm_end; 360 361 if (vma_is_anonymous(vma) || !vma->vm_file) { 362 stack_map_unlock_vma(&lock); 363 stack_map_build_id_set_ip(&id_offs[i]); 364 stack_map_build_id_cache_set_unresolved(&cache, vm_start, vm_end); 365 continue; 366 } 367 368 file = vma->vm_file; 369 offset = stack_map_build_id_offset(vm_pgoff, vm_start, ip); 370 371 /* 372 * Same backing file as the last resolved VMA (another mapping 373 * of the same ELF binary): reuse its build_id without re-parsing. 374 */ 375 if (file == res->file) { 376 stack_map_unlock_vma(&lock); 377 stack_map_build_id_set_valid(&id_offs[i], offset, res->build_id); 378 res->vm_start = vm_start; 379 res->vm_end = vm_end; 380 res->vm_pgoff = vm_pgoff; 381 continue; 382 } 383 384 file = get_file(file); 385 stack_map_unlock_vma(&lock); 386 387 /* build_id_parse_file() may block on filesystem reads */ 388 if (build_id_parse_file(file, id_offs[i].build_id, NULL)) { 389 stack_map_build_id_set_ip(&id_offs[i]); 390 fput(file); 391 stack_map_build_id_cache_set_unresolved(&cache, vm_start, vm_end); 392 continue; 393 } 394 395 stack_map_build_id_set_valid(&id_offs[i], offset, id_offs[i].build_id); 396 stack_map_build_id_cache_set_resolved(&cache, file, id_offs[i].build_id, 397 vm_start, vm_end, vm_pgoff); 398 } 399 400 if (res->file) 401 fput(res->file); 402 } 403 404 /* 405 * Expects all id_offs[i].ip values to be set to correct initial IPs. 406 * They will be subsequently: 407 * - either adjusted in place to a file offset, if build ID fetching 408 * succeeds; in this case id_offs[i].build_id is set to correct build ID, 409 * and id_offs[i].status is set to BPF_STACK_BUILD_ID_VALID; 410 * - or IP will be kept intact, if build ID fetching failed; in this case 411 * id_offs[i].build_id is zeroed out and id_offs[i].status is set to 412 * BPF_STACK_BUILD_ID_IP. 413 */ 414 static void stack_map_get_build_id_offset(struct bpf_stack_build_id *id_offs, 415 u32 trace_nr, bool user, bool may_fault) 416 { 417 struct mmap_unlock_irq_work *work; 418 bool has_user_ctx = user && current && current->mm; 419 struct stack_map_build_id_cache cache = {}; 420 struct vm_area_struct *vma; 421 int i; 422 423 if (may_fault && has_user_ctx) { 424 stack_map_get_build_id_offset_sleepable(id_offs, trace_nr); 425 return; 426 } 427 428 if (!has_user_ctx) 429 goto fallback; 430 431 work = bpf_mmap_unlock_guard_get(); 432 if (IS_ERR(work)) 433 goto fallback; 434 435 if (!mmap_read_trylock(current->mm)) { 436 bpf_mmap_unlock_guard_put(work); 437 goto fallback; 438 } 439 440 for (i = 0; i < trace_nr; i++) { 441 u64 ip = READ_ONCE(id_offs[i].ip); 442 443 if (!stack_map_build_id_set_from_cache(&cache, &id_offs[i], ip)) 444 continue; 445 446 vma = find_vma(current->mm, ip); 447 if (!vma || vma_is_anonymous(vma) || 448 fetch_build_id(vma, id_offs[i].build_id, may_fault)) { 449 /* per entry fall back to ips; cache build-ID-less range */ 450 stack_map_build_id_set_ip(&id_offs[i]); 451 if (vma) 452 stack_map_build_id_cache_set_unresolved(&cache, 453 vma->vm_start, vma->vm_end); 454 continue; 455 } 456 /* 457 * mmap_lock is held for the whole loop, so the cached VMA 458 * fields stay valid; no file pinning is needed here. 459 */ 460 stack_map_build_id_set_valid(&id_offs[i], 461 stack_map_build_id_offset(vma->vm_pgoff, vma->vm_start, ip), 462 id_offs[i].build_id); 463 stack_map_build_id_cache_set_resolved(&cache, NULL, id_offs[i].build_id, 464 vma->vm_start, vma->vm_end, 465 vma->vm_pgoff); 466 } 467 bpf_mmap_unlock_mm(work, current->mm); 468 return; 469 470 fallback: 471 /* cannot access current->mm, fall back to ips */ 472 for (i = 0; i < trace_nr; i++) 473 stack_map_build_id_set_ip(&id_offs[i]); 474 } 475 476 static struct perf_callchain_entry * 477 get_callchain_entry_for_task(struct task_struct *task, u32 max_depth) 478 { 479 #ifdef CONFIG_STACKTRACE 480 struct perf_callchain_entry *entry; 481 int rctx; 482 483 entry = get_callchain_entry(&rctx); 484 485 if (!entry) 486 return NULL; 487 488 entry->nr = stack_trace_save_tsk(task, (unsigned long *)entry->ip, 489 max_depth, 0); 490 491 /* stack_trace_save_tsk() works on unsigned long array, while 492 * perf_callchain_entry uses u64 array. For 32-bit systems, it is 493 * necessary to fix this mismatch. 494 */ 495 if (__BITS_PER_LONG != 64) { 496 unsigned long *from = (unsigned long *) entry->ip; 497 u64 *to = entry->ip; 498 int i; 499 500 /* copy data from the end to avoid using extra buffer */ 501 for (i = entry->nr - 1; i >= 0; i--) 502 to[i] = (u64)(from[i]); 503 } 504 505 put_callchain_entry(rctx); 506 507 return entry; 508 #else /* CONFIG_STACKTRACE */ 509 return NULL; 510 #endif 511 } 512 513 struct stackid { 514 struct stack_map_bucket *bucket; 515 const u64 *ips; 516 u32 nr; 517 u32 len; 518 u32 hash; 519 u32 id; 520 bool hash_matches; 521 }; 522 523 static int stackid_init(struct stackid *stackid, struct bpf_map *map, 524 const struct perf_callchain_entry *trace, u32 trace_nr, u64 flags) 525 { 526 struct bpf_stack_map *smap = container_of(map, struct bpf_stack_map, map); 527 u32 skip = flags & BPF_F_SKIP_FIELD_MASK; 528 u32 max_depth; 529 530 if (trace_nr <= skip) 531 /* skipping more than usable stack trace */ 532 return -EFAULT; 533 534 max_depth = stack_map_calculate_max_depth(map->value_size, stack_map_data_size(map), flags); 535 stackid->nr = min_t(u32, trace_nr - skip, max_depth - skip); 536 stackid->len = stackid->nr * sizeof(u64); 537 stackid->ips = trace->ip + skip; 538 stackid->hash = jhash2((const u32 *)stackid->ips, stackid->len / sizeof(u32), 0); 539 stackid->id = stackid->hash & (smap->n_buckets - 1); 540 stackid->bucket = READ_ONCE(smap->buckets[stackid->id]); 541 stackid->hash_matches = stackid->bucket && stackid->bucket->hash == stackid->hash; 542 return 0; 543 } 544 545 static int stackid_fastpath(struct stackid *stackid, struct bpf_map *map, 546 const struct perf_callchain_entry *trace, u32 trace_nr, 547 u64 flags) 548 { 549 int err; 550 551 err = stackid_init(stackid, map, trace, trace_nr, flags); 552 if (err) 553 return err; 554 555 /* fast cmp */ 556 if (stackid->hash_matches && flags & BPF_F_FAST_STACK_CMP) 557 return stackid->id; 558 559 if (stack_map_use_build_id(map)) 560 return -ENOENT; 561 if (stackid->hash_matches && stackid->bucket->nr == stackid->nr && 562 memcmp(stackid->bucket->data, stackid->ips, stackid->len) == 0) 563 return stackid->id; 564 if (stackid->bucket && !(flags & BPF_F_REUSE_STACKID)) 565 return -EEXIST; 566 return -ENOENT; 567 } 568 569 static struct stack_map_bucket * 570 stackid_new_bucket(struct stackid *stackid, struct bpf_map *map) 571 { 572 struct bpf_stack_map *smap = container_of(map, struct bpf_stack_map, map); 573 struct bpf_stack_build_id *id_offs; 574 struct stack_map_bucket *bucket; 575 u32 i; 576 577 bucket = (struct stack_map_bucket *) pcpu_freelist_pop(&smap->freelist); 578 if (unlikely(!bucket)) 579 return NULL; 580 581 if (stack_map_use_build_id(map)) { 582 id_offs = (struct bpf_stack_build_id *)bucket->data; 583 for (i = 0; i < stackid->nr; i++) 584 id_offs[i].ip = stackid->ips[i]; 585 } else { 586 memcpy(bucket->data, stackid->ips, stackid->len); 587 } 588 589 bucket->hash = stackid->hash; 590 bucket->nr = stackid->nr; 591 return bucket; 592 } 593 594 static long stackid_install(struct stackid *stackid, struct bpf_map *map, 595 struct stack_map_bucket *new_bucket, u64 flags) 596 { 597 struct bpf_stack_map *smap = container_of(map, struct bpf_stack_map, map); 598 bool user = flags & BPF_F_USER_STACK; 599 struct stack_map_bucket *old_bucket; 600 u32 trace_len; 601 602 if (stack_map_use_build_id(map)) { 603 struct bpf_stack_build_id *id_offs; 604 605 id_offs = (struct bpf_stack_build_id *)new_bucket->data; 606 stack_map_get_build_id_offset(id_offs, stackid->nr, user, false /* !may_fault */); 607 trace_len = stackid->nr * sizeof(struct bpf_stack_build_id); 608 if (stackid->hash_matches && stackid->bucket->nr == stackid->nr && 609 memcmp(stackid->bucket->data, new_bucket->data, trace_len) == 0) { 610 pcpu_freelist_push(&smap->freelist, &new_bucket->fnode); 611 return stackid->id; 612 } 613 if (stackid->bucket && !(flags & BPF_F_REUSE_STACKID)) { 614 pcpu_freelist_push(&smap->freelist, &new_bucket->fnode); 615 return -EEXIST; 616 } 617 } 618 619 old_bucket = xchg(&smap->buckets[stackid->id], new_bucket); 620 if (old_bucket) 621 pcpu_freelist_push(&smap->freelist, &old_bucket->fnode); 622 return stackid->id; 623 } 624 625 BPF_CALL_3(bpf_get_stackid, struct pt_regs *, regs, struct bpf_map *, map, 626 u64, flags) 627 { 628 u32 elem_size = stack_map_data_size(map); 629 bool user = flags & BPF_F_USER_STACK; 630 struct stack_map_bucket *new_bucket; 631 struct perf_callchain_entry *trace; 632 struct stackid stackid; 633 bool kernel = !user; 634 u32 max_depth; 635 int err; 636 637 if (unlikely(flags & ~(BPF_F_SKIP_FIELD_MASK | BPF_F_USER_STACK | 638 BPF_F_FAST_STACK_CMP | BPF_F_REUSE_STACKID))) 639 return -EINVAL; 640 641 max_depth = stack_map_calculate_max_depth(map->value_size, elem_size, flags); 642 643 scoped_guard(preempt) { 644 trace = get_perf_callchain(regs, kernel, user, max_depth, 645 false, false, 0); 646 if (unlikely(!trace)) 647 /* couldn't fetch the stack trace */ 648 return -EFAULT; 649 650 err = stackid_fastpath(&stackid, map, trace, trace->nr, flags); 651 if (err != -ENOENT) 652 return err; 653 654 new_bucket = stackid_new_bucket(&stackid, map); 655 if (!new_bucket) 656 return -ENOMEM; 657 } 658 659 return stackid_install(&stackid, map, new_bucket, flags); 660 } 661 662 const struct bpf_func_proto bpf_get_stackid_proto = { 663 .func = bpf_get_stackid, 664 .gpl_only = true, 665 .ret_type = RET_INTEGER, 666 .arg1_type = ARG_PTR_TO_CTX, 667 .arg2_type = ARG_CONST_MAP_PTR, 668 .arg3_type = ARG_ANYTHING, 669 }; 670 671 static __u64 count_kernel_ip(const struct perf_callchain_entry *trace) 672 { 673 __u64 nr_kernel = 0; 674 675 while (nr_kernel < trace->nr) { 676 if (trace->ip[nr_kernel] == PERF_CONTEXT_USER) 677 break; 678 nr_kernel++; 679 } 680 return nr_kernel; 681 } 682 683 BPF_CALL_3(bpf_get_stackid_pe, struct bpf_perf_event_data_kern *, ctx, 684 struct bpf_map *, map, u64, flags) 685 { 686 const struct perf_callchain_entry *trace; 687 struct perf_event *event = ctx->event; 688 struct stack_map_bucket *new_bucket; 689 struct stackid stackid; 690 bool kernel, user; 691 __u64 nr_kernel; 692 u32 trace_nr; 693 int ret; 694 695 /* perf_sample_data doesn't have callchain, use bpf_get_stackid */ 696 if (!(event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)) 697 return bpf_get_stackid((unsigned long)(ctx->regs), 698 (unsigned long) map, flags, 0, 0); 699 700 if (unlikely(flags & ~(BPF_F_SKIP_FIELD_MASK | BPF_F_USER_STACK | 701 BPF_F_FAST_STACK_CMP | BPF_F_REUSE_STACKID))) 702 return -EINVAL; 703 704 user = flags & BPF_F_USER_STACK; 705 kernel = !user; 706 707 trace = ctx->data->callchain; 708 if (unlikely(!trace)) 709 return -EFAULT; 710 711 nr_kernel = count_kernel_ip(trace); 712 713 if (kernel) { 714 trace_nr = nr_kernel; 715 } else { /* user */ 716 u64 skip = flags & BPF_F_SKIP_FIELD_MASK; 717 718 trace_nr = trace->nr; 719 skip += nr_kernel; 720 if (skip > BPF_F_SKIP_FIELD_MASK) 721 return -EFAULT; 722 723 flags = (flags & ~BPF_F_SKIP_FIELD_MASK) | skip; 724 } 725 726 ret = stackid_fastpath(&stackid, map, trace, trace_nr, flags); 727 if (ret != -ENOENT) 728 return ret; 729 730 new_bucket = stackid_new_bucket(&stackid, map); 731 if (new_bucket) 732 return stackid_install(&stackid, map, new_bucket, flags); 733 return -ENOMEM; 734 } 735 736 const struct bpf_func_proto bpf_get_stackid_proto_pe = { 737 .func = bpf_get_stackid_pe, 738 .gpl_only = false, 739 .ret_type = RET_INTEGER, 740 .arg1_type = ARG_PTR_TO_CTX, 741 .arg2_type = ARG_CONST_MAP_PTR, 742 .arg3_type = ARG_ANYTHING, 743 }; 744 745 static u32 callchain_store(const struct perf_callchain_entry *trace, u32 trace_nr, 746 void *buf, u32 elem_size, u64 flags) 747 { 748 bool user_build_id = flags & BPF_F_USER_BUILD_ID; 749 u32 skip = flags & BPF_F_SKIP_FIELD_MASK; 750 const u64 *ips; 751 u32 copy_len; 752 753 trace_nr = trace_nr - skip; 754 copy_len = trace_nr * elem_size; 755 756 ips = trace->ip + skip; 757 if (user_build_id) { 758 struct bpf_stack_build_id *id_offs = buf; 759 760 for (u32 i = 0; i < trace_nr; i++) 761 id_offs[i].ip = ips[i]; 762 } else { 763 memcpy(buf, ips, copy_len); 764 } 765 return trace_nr; 766 } 767 768 static long callchain_finalize(void *buf, u32 size, u32 trace_nr, u32 elem_size, 769 u64 flags, bool may_fault) 770 { 771 bool user_build_id = flags & BPF_F_USER_BUILD_ID; 772 bool user = flags & BPF_F_USER_STACK; 773 u32 copy_len = trace_nr * elem_size; 774 775 if (user_build_id) 776 stack_map_get_build_id_offset(buf, trace_nr, user, may_fault); 777 778 if (size > copy_len) 779 memset(buf + copy_len, 0, size - copy_len); 780 return copy_len; 781 } 782 783 static long __bpf_get_stack(struct pt_regs *regs, struct task_struct *task, 784 void *buf, u32 size, u64 flags, bool may_fault) 785 { 786 bool user_build_id = flags & BPF_F_USER_BUILD_ID; 787 bool crosstask = task && task != current; 788 u32 skip = flags & BPF_F_SKIP_FIELD_MASK; 789 bool user = flags & BPF_F_USER_STACK; 790 struct perf_callchain_entry *trace; 791 u32 trace_nr, elem_size, max_depth; 792 bool kernel = !user; 793 int err = -EINVAL; 794 795 if (unlikely(flags & ~(BPF_F_SKIP_FIELD_MASK | BPF_F_USER_STACK | 796 BPF_F_USER_BUILD_ID))) 797 goto clear; 798 if (kernel && user_build_id) 799 goto clear; 800 801 elem_size = user_build_id ? sizeof(struct bpf_stack_build_id) : sizeof(u64); 802 if (unlikely(size % elem_size)) 803 goto clear; 804 805 /* cannot get valid user stack for task without user_mode regs */ 806 if (task && user && !user_mode(regs)) 807 goto err_fault; 808 809 /* get_perf_callchain does not support crosstask user stack walking 810 * but returns an empty stack instead of NULL. 811 */ 812 if (crosstask && user) { 813 err = -EOPNOTSUPP; 814 goto clear; 815 } 816 817 max_depth = stack_map_calculate_max_depth(size, elem_size, flags); 818 819 preempt_disable(); 820 if (may_fault) 821 rcu_read_lock(); /* need RCU for perf's callchain below */ 822 823 if (kernel && task) { 824 trace = get_callchain_entry_for_task(task, max_depth); 825 } else { 826 trace = get_perf_callchain(regs, kernel, user, max_depth, 827 crosstask, false, 0); 828 } 829 830 if (unlikely(!trace) || trace->nr < skip) { 831 if (may_fault) 832 rcu_read_unlock(); 833 preempt_enable(); 834 goto err_fault; 835 } 836 837 trace_nr = callchain_store(trace, trace->nr, buf, elem_size, flags); 838 839 /* trace should not be dereferenced after this point */ 840 if (may_fault) 841 rcu_read_unlock(); 842 preempt_enable(); 843 844 return callchain_finalize(buf, size, trace_nr, elem_size, flags, may_fault); 845 846 err_fault: 847 err = -EFAULT; 848 clear: 849 memset(buf, 0, size); 850 return err; 851 } 852 853 BPF_CALL_4(bpf_get_stack, struct pt_regs *, regs, void *, buf, u32, size, 854 u64, flags) 855 { 856 return __bpf_get_stack(regs, NULL, buf, size, flags, false /* !may_fault */); 857 } 858 859 const struct bpf_func_proto bpf_get_stack_proto = { 860 .func = bpf_get_stack, 861 .gpl_only = true, 862 .ret_type = RET_INTEGER, 863 .arg1_type = ARG_PTR_TO_CTX, 864 .arg2_type = ARG_PTR_TO_UNINIT_MEM, 865 .arg3_type = ARG_MEM_SIZE_OR_ZERO, 866 .arg4_type = ARG_ANYTHING, 867 }; 868 869 BPF_CALL_4(bpf_get_stack_sleepable, struct pt_regs *, regs, void *, buf, u32, size, 870 u64, flags) 871 { 872 return __bpf_get_stack(regs, NULL, buf, size, flags, true /* may_fault */); 873 } 874 875 const struct bpf_func_proto bpf_get_stack_sleepable_proto = { 876 .func = bpf_get_stack_sleepable, 877 .gpl_only = true, 878 .ret_type = RET_INTEGER, 879 .arg1_type = ARG_PTR_TO_CTX, 880 .arg2_type = ARG_PTR_TO_UNINIT_MEM, 881 .arg3_type = ARG_MEM_SIZE_OR_ZERO, 882 .arg4_type = ARG_ANYTHING, 883 }; 884 885 static long __bpf_get_task_stack(struct task_struct *task, void *buf, u32 size, 886 u64 flags, bool may_fault) 887 { 888 struct pt_regs *regs; 889 long res = -EINVAL; 890 891 if (!try_get_task_stack(task)) { 892 memset(buf, 0, size); 893 return -EFAULT; 894 } 895 896 regs = task_pt_regs(task); 897 if (regs) 898 res = __bpf_get_stack(regs, task, buf, size, flags, may_fault); 899 else 900 memset(buf, 0, size); 901 put_task_stack(task); 902 return res; 903 } 904 905 BPF_CALL_4(bpf_get_task_stack, struct task_struct *, task, void *, buf, 906 u32, size, u64, flags) 907 { 908 return __bpf_get_task_stack(task, buf, size, flags, false /* !may_fault */); 909 } 910 911 const struct bpf_func_proto bpf_get_task_stack_proto = { 912 .func = bpf_get_task_stack, 913 .gpl_only = false, 914 .ret_type = RET_INTEGER, 915 .arg1_type = ARG_PTR_TO_BTF_ID, 916 .arg1_btf_id = &btf_tracing_ids[BTF_TRACING_TYPE_TASK], 917 .arg2_type = ARG_PTR_TO_UNINIT_MEM, 918 .arg3_type = ARG_MEM_SIZE_OR_ZERO, 919 .arg4_type = ARG_ANYTHING, 920 }; 921 922 BPF_CALL_4(bpf_get_task_stack_sleepable, struct task_struct *, task, void *, buf, 923 u32, size, u64, flags) 924 { 925 return __bpf_get_task_stack(task, buf, size, flags, true /* !may_fault */); 926 } 927 928 const struct bpf_func_proto bpf_get_task_stack_sleepable_proto = { 929 .func = bpf_get_task_stack_sleepable, 930 .gpl_only = false, 931 .ret_type = RET_INTEGER, 932 .arg1_type = ARG_PTR_TO_BTF_ID, 933 .arg1_btf_id = &btf_tracing_ids[BTF_TRACING_TYPE_TASK], 934 .arg2_type = ARG_PTR_TO_UNINIT_MEM, 935 .arg3_type = ARG_MEM_SIZE_OR_ZERO, 936 .arg4_type = ARG_ANYTHING, 937 }; 938 939 static int __bpf_get_stack_pe(const struct perf_callchain_entry *trace, u32 trace_nr, 940 void *buf, u32 size, u64 flags) 941 { 942 bool user_build_id = flags & BPF_F_USER_BUILD_ID; 943 u64 skip = flags & BPF_F_SKIP_FIELD_MASK; 944 bool user = flags & BPF_F_USER_STACK; 945 u32 elem_size, max_depth, nr_trace; 946 bool kernel = !user; 947 948 if (kernel && user_build_id) 949 return -EINVAL; 950 951 elem_size = user_build_id ? sizeof(struct bpf_stack_build_id) : sizeof(u64); 952 if (unlikely(size % elem_size)) 953 return -EINVAL; 954 955 max_depth = stack_map_calculate_max_depth(size, elem_size, flags); 956 trace_nr = min_t(u32, trace_nr, max_depth); 957 958 if (trace_nr < skip) 959 return -EFAULT; 960 961 nr_trace = callchain_store(trace, trace_nr, buf, elem_size, flags); 962 return callchain_finalize(buf, size, nr_trace, elem_size, flags, false /* !may_fault */); 963 } 964 965 BPF_CALL_4(bpf_get_stack_pe, struct bpf_perf_event_data_kern *, ctx, 966 void *, buf, u32, size, u64, flags) 967 { 968 struct pt_regs *regs = (struct pt_regs *)(ctx->regs); 969 const struct perf_callchain_entry *trace; 970 struct perf_event *event = ctx->event; 971 bool kernel, user; 972 int err = -EINVAL; 973 __u64 nr_kernel; 974 975 if (!(event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)) 976 return __bpf_get_stack(regs, NULL, buf, size, flags, false /* !may_fault */); 977 978 if (unlikely(flags & ~(BPF_F_SKIP_FIELD_MASK | BPF_F_USER_STACK | 979 BPF_F_USER_BUILD_ID))) 980 goto clear; 981 982 user = flags & BPF_F_USER_STACK; 983 kernel = !user; 984 985 err = -EFAULT; 986 trace = ctx->data->callchain; 987 if (unlikely(!trace)) 988 goto clear; 989 990 nr_kernel = count_kernel_ip(trace); 991 992 if (kernel) { 993 err = __bpf_get_stack_pe(trace, nr_kernel, buf, size, flags); 994 } else { /* user */ 995 u64 skip = flags & BPF_F_SKIP_FIELD_MASK; 996 997 skip += nr_kernel; 998 if (skip > BPF_F_SKIP_FIELD_MASK) 999 goto clear; 1000 flags = (flags & ~BPF_F_SKIP_FIELD_MASK) | skip; 1001 err = __bpf_get_stack_pe(trace, trace->nr, buf, size, flags); 1002 } 1003 1004 clear: 1005 if (err < 0) 1006 memset(buf, 0, size); 1007 return err; 1008 1009 } 1010 1011 const struct bpf_func_proto bpf_get_stack_proto_pe = { 1012 .func = bpf_get_stack_pe, 1013 .gpl_only = true, 1014 .ret_type = RET_INTEGER, 1015 .arg1_type = ARG_PTR_TO_CTX, 1016 .arg2_type = ARG_PTR_TO_UNINIT_MEM, 1017 .arg3_type = ARG_MEM_SIZE_OR_ZERO, 1018 .arg4_type = ARG_ANYTHING, 1019 }; 1020 1021 /* Called from eBPF program */ 1022 static void *stack_map_lookup_elem(struct bpf_map *map, void *key) 1023 { 1024 return ERR_PTR(-EOPNOTSUPP); 1025 } 1026 1027 /* Called from syscall */ 1028 static int stack_map_lookup_and_delete_elem(struct bpf_map *map, void *key, 1029 void *value, u64 flags) 1030 { 1031 return bpf_stackmap_extract(map, key, value, true); 1032 } 1033 1034 /* Called from syscall */ 1035 int bpf_stackmap_extract(struct bpf_map *map, void *key, void *value, 1036 bool delete) 1037 { 1038 struct bpf_stack_map *smap = container_of(map, struct bpf_stack_map, map); 1039 struct stack_map_bucket *bucket, *old_bucket; 1040 u32 id = *(u32 *)key, trace_len; 1041 1042 if (unlikely(id >= smap->n_buckets)) 1043 return -ENOENT; 1044 1045 bucket = xchg(&smap->buckets[id], NULL); 1046 if (!bucket) 1047 return -ENOENT; 1048 1049 trace_len = bucket->nr * stack_map_data_size(map); 1050 memcpy(value, bucket->data, trace_len); 1051 memset(value + trace_len, 0, map->value_size - trace_len); 1052 1053 if (delete) 1054 old_bucket = bucket; 1055 else 1056 old_bucket = xchg(&smap->buckets[id], bucket); 1057 if (old_bucket) 1058 pcpu_freelist_push(&smap->freelist, &old_bucket->fnode); 1059 return 0; 1060 } 1061 1062 static int stack_map_get_next_key(struct bpf_map *map, void *key, 1063 void *next_key) 1064 { 1065 struct bpf_stack_map *smap = container_of(map, 1066 struct bpf_stack_map, map); 1067 u32 id; 1068 1069 WARN_ON_ONCE(!rcu_read_lock_held()); 1070 1071 if (!key) { 1072 id = 0; 1073 } else { 1074 id = *(u32 *)key; 1075 if (id >= smap->n_buckets || !smap->buckets[id]) 1076 id = 0; 1077 else 1078 id++; 1079 } 1080 1081 while (id < smap->n_buckets && !smap->buckets[id]) 1082 id++; 1083 1084 if (id >= smap->n_buckets) 1085 return -ENOENT; 1086 1087 *(u32 *)next_key = id; 1088 return 0; 1089 } 1090 1091 static long stack_map_update_elem(struct bpf_map *map, void *key, void *value, 1092 u64 map_flags) 1093 { 1094 return -EINVAL; 1095 } 1096 1097 /* Called from syscall or from eBPF program */ 1098 static long stack_map_delete_elem(struct bpf_map *map, void *key) 1099 { 1100 struct bpf_stack_map *smap = container_of(map, struct bpf_stack_map, map); 1101 struct stack_map_bucket *old_bucket; 1102 u32 id = *(u32 *)key; 1103 1104 if (unlikely(id >= smap->n_buckets)) 1105 return -E2BIG; 1106 1107 old_bucket = xchg(&smap->buckets[id], NULL); 1108 if (old_bucket) { 1109 pcpu_freelist_push(&smap->freelist, &old_bucket->fnode); 1110 return 0; 1111 } else { 1112 return -ENOENT; 1113 } 1114 } 1115 1116 /* Called when map->refcnt goes to zero, either from workqueue or from syscall */ 1117 static void stack_map_free(struct bpf_map *map) 1118 { 1119 struct bpf_stack_map *smap = container_of(map, struct bpf_stack_map, map); 1120 1121 bpf_map_area_free(smap->elems); 1122 pcpu_freelist_destroy(&smap->freelist); 1123 bpf_map_area_free(smap); 1124 put_callchain_buffers(); 1125 } 1126 1127 static u64 stack_map_mem_usage(const struct bpf_map *map) 1128 { 1129 struct bpf_stack_map *smap = container_of(map, struct bpf_stack_map, map); 1130 u64 value_size = map->value_size; 1131 u64 n_buckets = smap->n_buckets; 1132 u64 enties = map->max_entries; 1133 u64 usage = sizeof(*smap); 1134 1135 usage += n_buckets * sizeof(struct stack_map_bucket *); 1136 usage += enties * (sizeof(struct stack_map_bucket) + value_size); 1137 return usage; 1138 } 1139 1140 BTF_ID_LIST_SINGLE(stack_trace_map_btf_ids, struct, bpf_stack_map) 1141 const struct bpf_map_ops stack_trace_map_ops = { 1142 .map_meta_equal = bpf_map_meta_equal, 1143 .map_alloc = stack_map_alloc, 1144 .map_free = stack_map_free, 1145 .map_get_next_key = stack_map_get_next_key, 1146 .map_lookup_elem = stack_map_lookup_elem, 1147 .map_lookup_and_delete_elem = stack_map_lookup_and_delete_elem, 1148 .map_update_elem = stack_map_update_elem, 1149 .map_delete_elem = stack_map_delete_elem, 1150 .map_check_btf = map_check_no_btf, 1151 .map_mem_usage = stack_map_mem_usage, 1152 .map_btf_id = &stack_trace_map_btf_ids[0], 1153 }; 1154