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 * On NOMMU configurations, returns with the mmap_lock held. If the MMU 276 * is enabled, the per-VMA lock will be held instead. The lock 277 * should be released with stack_map_unlock_vma() which will release the 278 * appropriate lock. Once the lock is released, the VMA may be freed. 279 * 280 * Returns NULL on failure, in which case no lock is held. 281 */ 282 static struct vm_area_struct * 283 stack_map_lock_vma(struct stack_map_vma_lock *lock, unsigned long ip) 284 { 285 struct mm_struct *mm = lock->mm; 286 struct vm_area_struct *vma; 287 288 vma = lock_vma_under_rcu(mm, ip); 289 if (vma) { 290 lock->vma = vma; 291 return vma; 292 } 293 294 /* 295 * Taking mmap_read_lock() is unsafe here, because the caller BPF 296 * program might already hold it, causing a deadlock. 297 */ 298 if (!mmap_read_trylock(mm)) 299 return NULL; 300 301 vma = vma_lookup(mm, ip); 302 if (!vma) { 303 mmap_read_unlock(mm); 304 return NULL; 305 } 306 307 #ifdef CONFIG_MMU 308 if (!vma_start_read_locked(vma)) { 309 mmap_read_unlock(mm); 310 return NULL; 311 } 312 mmap_read_unlock(mm); 313 #endif 314 lock->vma = vma; 315 return vma; 316 } 317 318 static void stack_map_unlock_vma(struct stack_map_vma_lock *lock) 319 { 320 #ifdef CONFIG_MMU 321 vma_end_read(lock->vma); 322 #else 323 mmap_read_unlock(lock->mm); 324 #endif 325 lock->vma = NULL; 326 } 327 328 static void stack_map_get_build_id_offset_sleepable(struct bpf_stack_build_id *id_offs, 329 u32 trace_nr) 330 { 331 struct stack_map_vma_lock lock = { .mm = current->mm }; 332 struct stack_map_build_id_cache cache = {}; 333 struct stack_map_cached_vma *res = &cache.resolved; 334 unsigned long vm_pgoff, vm_start, vm_end; 335 struct vm_area_struct *vma; 336 struct file *file; 337 u64 offset; 338 u64 ip; 339 340 for (u32 i = 0; i < trace_nr; i++) { 341 ip = READ_ONCE(id_offs[i].ip); 342 343 if (!stack_map_build_id_set_from_cache(&cache, &id_offs[i], ip)) 344 continue; 345 346 vma = stack_map_lock_vma(&lock, ip); 347 if (!vma) { 348 stack_map_build_id_set_ip(&id_offs[i]); 349 continue; 350 } 351 352 vm_pgoff = vma->vm_pgoff; 353 vm_start = vma->vm_start; 354 vm_end = vma->vm_end; 355 356 if (vma_is_anonymous(vma) || !vma->vm_file) { 357 stack_map_unlock_vma(&lock); 358 stack_map_build_id_set_ip(&id_offs[i]); 359 stack_map_build_id_cache_set_unresolved(&cache, vm_start, vm_end); 360 continue; 361 } 362 363 file = vma->vm_file; 364 offset = stack_map_build_id_offset(vm_pgoff, vm_start, ip); 365 366 /* 367 * Same backing file as the last resolved VMA (another mapping 368 * of the same ELF binary): reuse its build_id without re-parsing. 369 */ 370 if (file == res->file) { 371 stack_map_unlock_vma(&lock); 372 stack_map_build_id_set_valid(&id_offs[i], offset, res->build_id); 373 res->vm_start = vm_start; 374 res->vm_end = vm_end; 375 res->vm_pgoff = vm_pgoff; 376 continue; 377 } 378 379 file = get_file(file); 380 stack_map_unlock_vma(&lock); 381 382 /* build_id_parse_file() may block on filesystem reads */ 383 if (build_id_parse_file(file, id_offs[i].build_id, NULL)) { 384 stack_map_build_id_set_ip(&id_offs[i]); 385 fput(file); 386 stack_map_build_id_cache_set_unresolved(&cache, vm_start, vm_end); 387 continue; 388 } 389 390 stack_map_build_id_set_valid(&id_offs[i], offset, id_offs[i].build_id); 391 stack_map_build_id_cache_set_resolved(&cache, file, id_offs[i].build_id, 392 vm_start, vm_end, vm_pgoff); 393 } 394 395 if (res->file) 396 fput(res->file); 397 } 398 399 /* 400 * Expects all id_offs[i].ip values to be set to correct initial IPs. 401 * They will be subsequently: 402 * - either adjusted in place to a file offset, if build ID fetching 403 * succeeds; in this case id_offs[i].build_id is set to correct build ID, 404 * and id_offs[i].status is set to BPF_STACK_BUILD_ID_VALID; 405 * - or IP will be kept intact, if build ID fetching failed; in this case 406 * id_offs[i].build_id is zeroed out and id_offs[i].status is set to 407 * BPF_STACK_BUILD_ID_IP. 408 */ 409 static void stack_map_get_build_id_offset(struct bpf_stack_build_id *id_offs, 410 u32 trace_nr, bool user, bool may_fault) 411 { 412 struct mmap_unlock_irq_work *work; 413 bool has_user_ctx = user && current && current->mm; 414 struct stack_map_build_id_cache cache = {}; 415 struct vm_area_struct *vma; 416 int i; 417 418 if (may_fault && has_user_ctx) { 419 stack_map_get_build_id_offset_sleepable(id_offs, trace_nr); 420 return; 421 } 422 423 if (!has_user_ctx) 424 goto fallback; 425 426 work = bpf_mmap_unlock_guard_get(); 427 if (IS_ERR(work)) 428 goto fallback; 429 430 if (!mmap_read_trylock(current->mm)) { 431 bpf_mmap_unlock_guard_put(work); 432 goto fallback; 433 } 434 435 for (i = 0; i < trace_nr; i++) { 436 u64 ip = READ_ONCE(id_offs[i].ip); 437 438 if (!stack_map_build_id_set_from_cache(&cache, &id_offs[i], ip)) 439 continue; 440 441 vma = find_vma(current->mm, ip); 442 if (!vma || vma_is_anonymous(vma) || 443 fetch_build_id(vma, id_offs[i].build_id, may_fault)) { 444 /* per entry fall back to ips; cache build-ID-less range */ 445 stack_map_build_id_set_ip(&id_offs[i]); 446 if (vma) 447 stack_map_build_id_cache_set_unresolved(&cache, 448 vma->vm_start, vma->vm_end); 449 continue; 450 } 451 /* 452 * mmap_lock is held for the whole loop, so the cached VMA 453 * fields stay valid; no file pinning is needed here. 454 */ 455 stack_map_build_id_set_valid(&id_offs[i], 456 stack_map_build_id_offset(vma->vm_pgoff, vma->vm_start, ip), 457 id_offs[i].build_id); 458 stack_map_build_id_cache_set_resolved(&cache, NULL, id_offs[i].build_id, 459 vma->vm_start, vma->vm_end, 460 vma->vm_pgoff); 461 } 462 bpf_mmap_unlock_mm(work, current->mm); 463 return; 464 465 fallback: 466 /* cannot access current->mm, fall back to ips */ 467 for (i = 0; i < trace_nr; i++) 468 stack_map_build_id_set_ip(&id_offs[i]); 469 } 470 471 static struct perf_callchain_entry * 472 get_callchain_entry_for_task(struct task_struct *task, u32 max_depth) 473 { 474 #ifdef CONFIG_STACKTRACE 475 struct perf_callchain_entry *entry; 476 int rctx; 477 478 entry = get_callchain_entry(&rctx); 479 480 if (!entry) 481 return NULL; 482 483 entry->nr = stack_trace_save_tsk(task, (unsigned long *)entry->ip, 484 max_depth, 0); 485 486 /* stack_trace_save_tsk() works on unsigned long array, while 487 * perf_callchain_entry uses u64 array. For 32-bit systems, it is 488 * necessary to fix this mismatch. 489 */ 490 if (__BITS_PER_LONG != 64) { 491 unsigned long *from = (unsigned long *) entry->ip; 492 u64 *to = entry->ip; 493 int i; 494 495 /* copy data from the end to avoid using extra buffer */ 496 for (i = entry->nr - 1; i >= 0; i--) 497 to[i] = (u64)(from[i]); 498 } 499 500 put_callchain_entry(rctx); 501 502 return entry; 503 #else /* CONFIG_STACKTRACE */ 504 return NULL; 505 #endif 506 } 507 508 struct stackid { 509 struct stack_map_bucket *bucket; 510 const u64 *ips; 511 u32 nr; 512 u32 len; 513 u32 hash; 514 u32 id; 515 bool hash_matches; 516 }; 517 518 static int stackid_init(struct stackid *stackid, struct bpf_map *map, 519 const struct perf_callchain_entry *trace, u32 trace_nr, u64 flags) 520 { 521 struct bpf_stack_map *smap = container_of(map, struct bpf_stack_map, map); 522 u32 skip = flags & BPF_F_SKIP_FIELD_MASK; 523 u32 max_depth; 524 525 if (trace_nr <= skip) 526 /* skipping more than usable stack trace */ 527 return -EFAULT; 528 529 max_depth = stack_map_calculate_max_depth(map->value_size, stack_map_data_size(map), flags); 530 stackid->nr = min_t(u32, trace_nr - skip, max_depth - skip); 531 stackid->len = stackid->nr * sizeof(u64); 532 stackid->ips = trace->ip + skip; 533 stackid->hash = jhash2((const u32 *)stackid->ips, stackid->len / sizeof(u32), 0); 534 stackid->id = stackid->hash & (smap->n_buckets - 1); 535 stackid->bucket = READ_ONCE(smap->buckets[stackid->id]); 536 stackid->hash_matches = stackid->bucket && stackid->bucket->hash == stackid->hash; 537 return 0; 538 } 539 540 static int stackid_fastpath(struct stackid *stackid, struct bpf_map *map, 541 const struct perf_callchain_entry *trace, u32 trace_nr, 542 u64 flags) 543 { 544 int err; 545 546 err = stackid_init(stackid, map, trace, trace_nr, flags); 547 if (err) 548 return err; 549 550 /* fast cmp */ 551 if (stackid->hash_matches && flags & BPF_F_FAST_STACK_CMP) 552 return stackid->id; 553 554 if (stack_map_use_build_id(map)) 555 return -ENOENT; 556 if (stackid->hash_matches && stackid->bucket->nr == stackid->nr && 557 memcmp(stackid->bucket->data, stackid->ips, stackid->len) == 0) 558 return stackid->id; 559 if (stackid->bucket && !(flags & BPF_F_REUSE_STACKID)) 560 return -EEXIST; 561 return -ENOENT; 562 } 563 564 static struct stack_map_bucket * 565 stackid_new_bucket(struct stackid *stackid, struct bpf_map *map) 566 { 567 struct bpf_stack_map *smap = container_of(map, struct bpf_stack_map, map); 568 struct bpf_stack_build_id *id_offs; 569 struct stack_map_bucket *bucket; 570 u32 i; 571 572 bucket = (struct stack_map_bucket *) pcpu_freelist_pop(&smap->freelist); 573 if (unlikely(!bucket)) 574 return NULL; 575 576 if (stack_map_use_build_id(map)) { 577 id_offs = (struct bpf_stack_build_id *)bucket->data; 578 for (i = 0; i < stackid->nr; i++) 579 id_offs[i].ip = stackid->ips[i]; 580 } else { 581 memcpy(bucket->data, stackid->ips, stackid->len); 582 } 583 584 bucket->hash = stackid->hash; 585 bucket->nr = stackid->nr; 586 return bucket; 587 } 588 589 static long stackid_install(struct stackid *stackid, struct bpf_map *map, 590 struct stack_map_bucket *new_bucket, u64 flags) 591 { 592 struct bpf_stack_map *smap = container_of(map, struct bpf_stack_map, map); 593 bool user = flags & BPF_F_USER_STACK; 594 struct stack_map_bucket *old_bucket; 595 u32 trace_len; 596 597 if (stack_map_use_build_id(map)) { 598 struct bpf_stack_build_id *id_offs; 599 600 id_offs = (struct bpf_stack_build_id *)new_bucket->data; 601 stack_map_get_build_id_offset(id_offs, stackid->nr, user, false /* !may_fault */); 602 trace_len = stackid->nr * sizeof(struct bpf_stack_build_id); 603 if (stackid->hash_matches && stackid->bucket->nr == stackid->nr && 604 memcmp(stackid->bucket->data, new_bucket->data, trace_len) == 0) { 605 pcpu_freelist_push(&smap->freelist, &new_bucket->fnode); 606 return stackid->id; 607 } 608 if (stackid->bucket && !(flags & BPF_F_REUSE_STACKID)) { 609 pcpu_freelist_push(&smap->freelist, &new_bucket->fnode); 610 return -EEXIST; 611 } 612 } 613 614 old_bucket = xchg(&smap->buckets[stackid->id], new_bucket); 615 if (old_bucket) 616 pcpu_freelist_push(&smap->freelist, &old_bucket->fnode); 617 return stackid->id; 618 } 619 620 BPF_CALL_3(bpf_get_stackid, struct pt_regs *, regs, struct bpf_map *, map, 621 u64, flags) 622 { 623 u32 elem_size = stack_map_data_size(map); 624 bool user = flags & BPF_F_USER_STACK; 625 struct stack_map_bucket *new_bucket; 626 struct perf_callchain_entry *trace; 627 struct stackid stackid; 628 bool kernel = !user; 629 u32 max_depth; 630 int err; 631 632 if (unlikely(flags & ~(BPF_F_SKIP_FIELD_MASK | BPF_F_USER_STACK | 633 BPF_F_FAST_STACK_CMP | BPF_F_REUSE_STACKID))) 634 return -EINVAL; 635 636 max_depth = stack_map_calculate_max_depth(map->value_size, elem_size, flags); 637 638 scoped_guard(preempt) { 639 trace = get_perf_callchain(regs, kernel, user, max_depth, 640 false, false, 0); 641 if (unlikely(!trace)) 642 /* couldn't fetch the stack trace */ 643 return -EFAULT; 644 645 err = stackid_fastpath(&stackid, map, trace, trace->nr, flags); 646 if (err != -ENOENT) 647 return err; 648 649 new_bucket = stackid_new_bucket(&stackid, map); 650 if (!new_bucket) 651 return -ENOMEM; 652 } 653 654 return stackid_install(&stackid, map, new_bucket, flags); 655 } 656 657 const struct bpf_func_proto bpf_get_stackid_proto = { 658 .func = bpf_get_stackid, 659 .gpl_only = true, 660 .ret_type = RET_INTEGER, 661 .arg1_type = ARG_PTR_TO_CTX, 662 .arg2_type = ARG_CONST_MAP_PTR, 663 .arg3_type = ARG_ANYTHING, 664 }; 665 666 static __u64 count_kernel_ip(const struct perf_callchain_entry *trace) 667 { 668 __u64 nr_kernel = 0; 669 670 while (nr_kernel < trace->nr) { 671 if (trace->ip[nr_kernel] == PERF_CONTEXT_USER) 672 break; 673 nr_kernel++; 674 } 675 return nr_kernel; 676 } 677 678 BPF_CALL_3(bpf_get_stackid_pe, struct bpf_perf_event_data_kern *, ctx, 679 struct bpf_map *, map, u64, flags) 680 { 681 const struct perf_callchain_entry *trace; 682 struct perf_event *event = ctx->event; 683 struct stack_map_bucket *new_bucket; 684 struct stackid stackid; 685 bool kernel, user; 686 __u64 nr_kernel; 687 u32 trace_nr; 688 int ret; 689 690 /* perf_sample_data doesn't have callchain, use bpf_get_stackid */ 691 if (!(event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)) 692 return bpf_get_stackid((unsigned long)(ctx->regs), 693 (unsigned long) map, flags, 0, 0); 694 695 if (unlikely(flags & ~(BPF_F_SKIP_FIELD_MASK | BPF_F_USER_STACK | 696 BPF_F_FAST_STACK_CMP | BPF_F_REUSE_STACKID))) 697 return -EINVAL; 698 699 user = flags & BPF_F_USER_STACK; 700 kernel = !user; 701 702 trace = ctx->data->callchain; 703 if (unlikely(!trace)) 704 return -EFAULT; 705 706 nr_kernel = count_kernel_ip(trace); 707 708 if (kernel) { 709 trace_nr = nr_kernel; 710 } else { /* user */ 711 u64 skip = flags & BPF_F_SKIP_FIELD_MASK; 712 713 trace_nr = trace->nr; 714 skip += nr_kernel; 715 if (skip > BPF_F_SKIP_FIELD_MASK) 716 return -EFAULT; 717 718 flags = (flags & ~BPF_F_SKIP_FIELD_MASK) | skip; 719 } 720 721 ret = stackid_fastpath(&stackid, map, trace, trace_nr, flags); 722 if (ret != -ENOENT) 723 return ret; 724 725 new_bucket = stackid_new_bucket(&stackid, map); 726 if (new_bucket) 727 return stackid_install(&stackid, map, new_bucket, flags); 728 return -ENOMEM; 729 } 730 731 const struct bpf_func_proto bpf_get_stackid_proto_pe = { 732 .func = bpf_get_stackid_pe, 733 .gpl_only = false, 734 .ret_type = RET_INTEGER, 735 .arg1_type = ARG_PTR_TO_CTX, 736 .arg2_type = ARG_CONST_MAP_PTR, 737 .arg3_type = ARG_ANYTHING, 738 }; 739 740 static u32 callchain_store(const struct perf_callchain_entry *trace, u32 trace_nr, 741 void *buf, u32 elem_size, u64 flags) 742 { 743 bool user_build_id = flags & BPF_F_USER_BUILD_ID; 744 u32 skip = flags & BPF_F_SKIP_FIELD_MASK; 745 const u64 *ips; 746 u32 copy_len; 747 748 trace_nr = trace_nr - skip; 749 copy_len = trace_nr * elem_size; 750 751 ips = trace->ip + skip; 752 if (user_build_id) { 753 struct bpf_stack_build_id *id_offs = buf; 754 755 for (u32 i = 0; i < trace_nr; i++) 756 id_offs[i].ip = ips[i]; 757 } else { 758 memcpy(buf, ips, copy_len); 759 } 760 return trace_nr; 761 } 762 763 static long callchain_finalize(void *buf, u32 size, u32 trace_nr, u32 elem_size, 764 u64 flags, bool may_fault) 765 { 766 bool user_build_id = flags & BPF_F_USER_BUILD_ID; 767 bool user = flags & BPF_F_USER_STACK; 768 u32 copy_len = trace_nr * elem_size; 769 770 if (user_build_id) 771 stack_map_get_build_id_offset(buf, trace_nr, user, may_fault); 772 773 if (size > copy_len) 774 memset(buf + copy_len, 0, size - copy_len); 775 return copy_len; 776 } 777 778 static long __bpf_get_stack(struct pt_regs *regs, struct task_struct *task, 779 void *buf, u32 size, u64 flags, bool may_fault) 780 { 781 bool user_build_id = flags & BPF_F_USER_BUILD_ID; 782 bool crosstask = task && task != current; 783 u32 skip = flags & BPF_F_SKIP_FIELD_MASK; 784 bool user = flags & BPF_F_USER_STACK; 785 struct perf_callchain_entry *trace; 786 u32 trace_nr, elem_size, max_depth; 787 bool kernel = !user; 788 int err = -EINVAL; 789 790 if (unlikely(flags & ~(BPF_F_SKIP_FIELD_MASK | BPF_F_USER_STACK | 791 BPF_F_USER_BUILD_ID))) 792 goto clear; 793 if (kernel && user_build_id) 794 goto clear; 795 796 elem_size = user_build_id ? sizeof(struct bpf_stack_build_id) : sizeof(u64); 797 if (unlikely(size % elem_size)) 798 goto clear; 799 800 /* cannot get valid user stack for task without user_mode regs */ 801 if (task && user && !user_mode(regs)) 802 goto err_fault; 803 804 /* get_perf_callchain does not support crosstask user stack walking 805 * but returns an empty stack instead of NULL. 806 */ 807 if (crosstask && user) { 808 err = -EOPNOTSUPP; 809 goto clear; 810 } 811 812 max_depth = stack_map_calculate_max_depth(size, elem_size, flags); 813 814 preempt_disable(); 815 if (may_fault) 816 rcu_read_lock(); /* need RCU for perf's callchain below */ 817 818 if (kernel && task) { 819 trace = get_callchain_entry_for_task(task, max_depth); 820 } else { 821 trace = get_perf_callchain(regs, kernel, user, max_depth, 822 crosstask, false, 0); 823 } 824 825 if (unlikely(!trace) || trace->nr < skip) { 826 if (may_fault) 827 rcu_read_unlock(); 828 preempt_enable(); 829 goto err_fault; 830 } 831 832 trace_nr = callchain_store(trace, trace->nr, buf, elem_size, flags); 833 834 /* trace should not be dereferenced after this point */ 835 if (may_fault) 836 rcu_read_unlock(); 837 preempt_enable(); 838 839 return callchain_finalize(buf, size, trace_nr, elem_size, flags, may_fault); 840 841 err_fault: 842 err = -EFAULT; 843 clear: 844 memset(buf, 0, size); 845 return err; 846 } 847 848 BPF_CALL_4(bpf_get_stack, struct pt_regs *, regs, void *, buf, u32, size, 849 u64, flags) 850 { 851 return __bpf_get_stack(regs, NULL, buf, size, flags, false /* !may_fault */); 852 } 853 854 const struct bpf_func_proto bpf_get_stack_proto = { 855 .func = bpf_get_stack, 856 .gpl_only = true, 857 .ret_type = RET_INTEGER, 858 .arg1_type = ARG_PTR_TO_CTX, 859 .arg2_type = ARG_PTR_TO_UNINIT_MEM, 860 .arg3_type = ARG_MEM_SIZE_OR_ZERO, 861 .arg4_type = ARG_ANYTHING, 862 }; 863 864 BPF_CALL_4(bpf_get_stack_sleepable, struct pt_regs *, regs, void *, buf, u32, size, 865 u64, flags) 866 { 867 return __bpf_get_stack(regs, NULL, buf, size, flags, true /* may_fault */); 868 } 869 870 const struct bpf_func_proto bpf_get_stack_sleepable_proto = { 871 .func = bpf_get_stack_sleepable, 872 .gpl_only = true, 873 .might_sleep = true, 874 .ret_type = RET_INTEGER, 875 .arg1_type = ARG_PTR_TO_CTX, 876 .arg2_type = ARG_PTR_TO_UNINIT_MEM, 877 .arg3_type = ARG_MEM_SIZE_OR_ZERO, 878 .arg4_type = ARG_ANYTHING, 879 }; 880 881 static long __bpf_get_task_stack(struct task_struct *task, void *buf, u32 size, 882 u64 flags, bool may_fault) 883 { 884 struct pt_regs *regs; 885 long res = -EINVAL; 886 887 if (!try_get_task_stack(task)) { 888 memset(buf, 0, size); 889 return -EFAULT; 890 } 891 892 regs = task_pt_regs(task); 893 if (regs) 894 res = __bpf_get_stack(regs, task, buf, size, flags, may_fault); 895 else 896 memset(buf, 0, size); 897 put_task_stack(task); 898 return res; 899 } 900 901 BPF_CALL_4(bpf_get_task_stack, struct task_struct *, task, void *, buf, 902 u32, size, u64, flags) 903 { 904 return __bpf_get_task_stack(task, buf, size, flags, false /* !may_fault */); 905 } 906 907 const struct bpf_func_proto bpf_get_task_stack_proto = { 908 .func = bpf_get_task_stack, 909 .gpl_only = false, 910 .ret_type = RET_INTEGER, 911 .arg1_type = ARG_PTR_TO_BTF_ID, 912 .arg1_btf_id = &btf_tracing_ids[BTF_TRACING_TYPE_TASK], 913 .arg2_type = ARG_PTR_TO_UNINIT_MEM, 914 .arg3_type = ARG_MEM_SIZE_OR_ZERO, 915 .arg4_type = ARG_ANYTHING, 916 }; 917 918 BPF_CALL_4(bpf_get_task_stack_sleepable, struct task_struct *, task, void *, buf, 919 u32, size, u64, flags) 920 { 921 return __bpf_get_task_stack(task, buf, size, flags, true /* !may_fault */); 922 } 923 924 const struct bpf_func_proto bpf_get_task_stack_sleepable_proto = { 925 .func = bpf_get_task_stack_sleepable, 926 .gpl_only = false, 927 .might_sleep = true, 928 .ret_type = RET_INTEGER, 929 .arg1_type = ARG_PTR_TO_BTF_ID, 930 .arg1_btf_id = &btf_tracing_ids[BTF_TRACING_TYPE_TASK], 931 .arg2_type = ARG_PTR_TO_UNINIT_MEM, 932 .arg3_type = ARG_MEM_SIZE_OR_ZERO, 933 .arg4_type = ARG_ANYTHING, 934 }; 935 936 static int __bpf_get_stack_pe(const struct perf_callchain_entry *trace, u32 trace_nr, 937 void *buf, u32 size, u64 flags) 938 { 939 bool user_build_id = flags & BPF_F_USER_BUILD_ID; 940 u64 skip = flags & BPF_F_SKIP_FIELD_MASK; 941 bool user = flags & BPF_F_USER_STACK; 942 u32 elem_size, max_depth, nr_trace; 943 bool kernel = !user; 944 945 if (kernel && user_build_id) 946 return -EINVAL; 947 948 elem_size = user_build_id ? sizeof(struct bpf_stack_build_id) : sizeof(u64); 949 if (unlikely(size % elem_size)) 950 return -EINVAL; 951 952 max_depth = stack_map_calculate_max_depth(size, elem_size, flags); 953 trace_nr = min_t(u32, trace_nr, max_depth); 954 955 if (trace_nr < skip) 956 return -EFAULT; 957 958 nr_trace = callchain_store(trace, trace_nr, buf, elem_size, flags); 959 return callchain_finalize(buf, size, nr_trace, elem_size, flags, false /* !may_fault */); 960 } 961 962 BPF_CALL_4(bpf_get_stack_pe, struct bpf_perf_event_data_kern *, ctx, 963 void *, buf, u32, size, u64, flags) 964 { 965 struct pt_regs *regs = (struct pt_regs *)(ctx->regs); 966 const struct perf_callchain_entry *trace; 967 struct perf_event *event = ctx->event; 968 bool kernel, user; 969 int err = -EINVAL; 970 __u64 nr_kernel; 971 972 if (!(event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)) 973 return __bpf_get_stack(regs, NULL, buf, size, flags, false /* !may_fault */); 974 975 if (unlikely(flags & ~(BPF_F_SKIP_FIELD_MASK | BPF_F_USER_STACK | 976 BPF_F_USER_BUILD_ID))) 977 goto clear; 978 979 user = flags & BPF_F_USER_STACK; 980 kernel = !user; 981 982 err = -EFAULT; 983 trace = ctx->data->callchain; 984 if (unlikely(!trace)) 985 goto clear; 986 987 nr_kernel = count_kernel_ip(trace); 988 989 if (kernel) { 990 err = __bpf_get_stack_pe(trace, nr_kernel, buf, size, flags); 991 } else { /* user */ 992 u64 skip = flags & BPF_F_SKIP_FIELD_MASK; 993 994 skip += nr_kernel; 995 if (skip > BPF_F_SKIP_FIELD_MASK) 996 goto clear; 997 flags = (flags & ~BPF_F_SKIP_FIELD_MASK) | skip; 998 err = __bpf_get_stack_pe(trace, trace->nr, buf, size, flags); 999 } 1000 1001 clear: 1002 if (err < 0) 1003 memset(buf, 0, size); 1004 return err; 1005 1006 } 1007 1008 const struct bpf_func_proto bpf_get_stack_proto_pe = { 1009 .func = bpf_get_stack_pe, 1010 .gpl_only = true, 1011 .ret_type = RET_INTEGER, 1012 .arg1_type = ARG_PTR_TO_CTX, 1013 .arg2_type = ARG_PTR_TO_UNINIT_MEM, 1014 .arg3_type = ARG_MEM_SIZE_OR_ZERO, 1015 .arg4_type = ARG_ANYTHING, 1016 }; 1017 1018 /* Called from eBPF program */ 1019 static void *stack_map_lookup_elem(struct bpf_map *map, void *key) 1020 { 1021 return ERR_PTR(-EOPNOTSUPP); 1022 } 1023 1024 /* Called from syscall */ 1025 static int stack_map_lookup_and_delete_elem(struct bpf_map *map, void *key, 1026 void *value, u64 flags) 1027 { 1028 return bpf_stackmap_extract(map, key, value, true); 1029 } 1030 1031 /* Called from syscall */ 1032 int bpf_stackmap_extract(struct bpf_map *map, void *key, void *value, 1033 bool delete) 1034 { 1035 struct bpf_stack_map *smap = container_of(map, struct bpf_stack_map, map); 1036 struct stack_map_bucket *bucket, *old_bucket; 1037 u32 id = *(u32 *)key, trace_len; 1038 1039 if (unlikely(id >= smap->n_buckets)) 1040 return -ENOENT; 1041 1042 bucket = xchg(&smap->buckets[id], NULL); 1043 if (!bucket) 1044 return -ENOENT; 1045 1046 trace_len = bucket->nr * stack_map_data_size(map); 1047 memcpy(value, bucket->data, trace_len); 1048 memset(value + trace_len, 0, map->value_size - trace_len); 1049 1050 if (delete) 1051 old_bucket = bucket; 1052 else 1053 old_bucket = xchg(&smap->buckets[id], bucket); 1054 if (old_bucket) 1055 pcpu_freelist_push(&smap->freelist, &old_bucket->fnode); 1056 return 0; 1057 } 1058 1059 static int stack_map_get_next_key(struct bpf_map *map, void *key, 1060 void *next_key) 1061 { 1062 struct bpf_stack_map *smap = container_of(map, 1063 struct bpf_stack_map, map); 1064 u32 id; 1065 1066 WARN_ON_ONCE(!rcu_read_lock_held()); 1067 1068 if (!key) { 1069 id = 0; 1070 } else { 1071 id = *(u32 *)key; 1072 if (id >= smap->n_buckets || !smap->buckets[id]) 1073 id = 0; 1074 else 1075 id++; 1076 } 1077 1078 while (id < smap->n_buckets && !smap->buckets[id]) 1079 id++; 1080 1081 if (id >= smap->n_buckets) 1082 return -ENOENT; 1083 1084 *(u32 *)next_key = id; 1085 return 0; 1086 } 1087 1088 static long stack_map_update_elem(struct bpf_map *map, void *key, void *value, 1089 u64 map_flags) 1090 { 1091 return -EINVAL; 1092 } 1093 1094 /* Called from syscall or from eBPF program */ 1095 static long stack_map_delete_elem(struct bpf_map *map, void *key) 1096 { 1097 struct bpf_stack_map *smap = container_of(map, struct bpf_stack_map, map); 1098 struct stack_map_bucket *old_bucket; 1099 u32 id = *(u32 *)key; 1100 1101 if (unlikely(id >= smap->n_buckets)) 1102 return -E2BIG; 1103 1104 old_bucket = xchg(&smap->buckets[id], NULL); 1105 if (old_bucket) { 1106 pcpu_freelist_push(&smap->freelist, &old_bucket->fnode); 1107 return 0; 1108 } else { 1109 return -ENOENT; 1110 } 1111 } 1112 1113 /* Called when map->refcnt goes to zero, either from workqueue or from syscall */ 1114 static void stack_map_free(struct bpf_map *map) 1115 { 1116 struct bpf_stack_map *smap = container_of(map, struct bpf_stack_map, map); 1117 1118 bpf_map_area_free(smap->elems); 1119 pcpu_freelist_destroy(&smap->freelist); 1120 bpf_map_area_free(smap); 1121 put_callchain_buffers(); 1122 } 1123 1124 static u64 stack_map_mem_usage(const struct bpf_map *map) 1125 { 1126 struct bpf_stack_map *smap = container_of(map, struct bpf_stack_map, map); 1127 u64 value_size = map->value_size; 1128 u64 n_buckets = smap->n_buckets; 1129 u64 enties = map->max_entries; 1130 u64 usage = sizeof(*smap); 1131 1132 usage += n_buckets * sizeof(struct stack_map_bucket *); 1133 usage += enties * (sizeof(struct stack_map_bucket) + value_size); 1134 return usage; 1135 } 1136 1137 BTF_ID_LIST_SINGLE(stack_trace_map_btf_ids, struct, bpf_stack_map) 1138 const struct bpf_map_ops stack_trace_map_ops = { 1139 .map_meta_equal = bpf_map_meta_equal, 1140 .map_alloc = stack_map_alloc, 1141 .map_free = stack_map_free, 1142 .map_get_next_key = stack_map_get_next_key, 1143 .map_lookup_elem = stack_map_lookup_elem, 1144 .map_lookup_and_delete_elem = stack_map_lookup_and_delete_elem, 1145 .map_update_elem = stack_map_update_elem, 1146 .map_delete_elem = stack_map_delete_elem, 1147 .map_check_btf = map_check_no_btf, 1148 .map_mem_usage = stack_map_mem_usage, 1149 .map_btf_id = &stack_trace_map_btf_ids[0], 1150 }; 1151