1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2016 Facebook
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/irq_work.h>
11 #include <linux/btf_ids.h>
12 #include <linux/buildid.h>
13 #include "percpu_freelist.h"
15 #define STACK_CREATE_FLAG_MASK \
16 (BPF_F_NUMA_NODE | BPF_F_RDONLY | BPF_F_WRONLY | \
19 struct stack_map_bucket {
20 struct pcpu_freelist_node fnode;
26 struct bpf_stack_map {
29 struct pcpu_freelist freelist;
31 struct stack_map_bucket *buckets[];
34 /* irq_work to run up_read() for build_id lookup in nmi context */
35 struct stack_map_irq_work {
36 struct irq_work irq_work;
40 static void do_up_read(struct irq_work *entry)
42 struct stack_map_irq_work *work;
44 if (WARN_ON_ONCE(IS_ENABLED(CONFIG_PREEMPT_RT)))
47 work = container_of(entry, struct stack_map_irq_work, irq_work);
48 mmap_read_unlock_non_owner(work->mm);
51 static DEFINE_PER_CPU(struct stack_map_irq_work, up_read_work);
53 static inline bool stack_map_use_build_id(struct bpf_map *map)
55 return (map->map_flags & BPF_F_STACK_BUILD_ID);
58 static inline int stack_map_data_size(struct bpf_map *map)
60 return stack_map_use_build_id(map) ?
61 sizeof(struct bpf_stack_build_id) : sizeof(u64);
64 static int prealloc_elems_and_freelist(struct bpf_stack_map *smap)
66 u64 elem_size = sizeof(struct stack_map_bucket) +
67 (u64)smap->map.value_size;
70 smap->elems = bpf_map_area_alloc(elem_size * smap->map.max_entries,
75 err = pcpu_freelist_init(&smap->freelist);
79 pcpu_freelist_populate(&smap->freelist, smap->elems, elem_size,
80 smap->map.max_entries);
84 bpf_map_area_free(smap->elems);
88 /* Called from syscall */
89 static struct bpf_map *stack_map_alloc(union bpf_attr *attr)
91 u32 value_size = attr->value_size;
92 struct bpf_stack_map *smap;
97 return ERR_PTR(-EPERM);
99 if (attr->map_flags & ~STACK_CREATE_FLAG_MASK)
100 return ERR_PTR(-EINVAL);
102 /* check sanity of attributes */
103 if (attr->max_entries == 0 || attr->key_size != 4 ||
104 value_size < 8 || value_size % 8)
105 return ERR_PTR(-EINVAL);
107 BUILD_BUG_ON(sizeof(struct bpf_stack_build_id) % sizeof(u64));
108 if (attr->map_flags & BPF_F_STACK_BUILD_ID) {
109 if (value_size % sizeof(struct bpf_stack_build_id) ||
110 value_size / sizeof(struct bpf_stack_build_id)
111 > sysctl_perf_event_max_stack)
112 return ERR_PTR(-EINVAL);
113 } else if (value_size / 8 > sysctl_perf_event_max_stack)
114 return ERR_PTR(-EINVAL);
116 /* hash table size must be power of 2 */
117 n_buckets = roundup_pow_of_two(attr->max_entries);
119 return ERR_PTR(-E2BIG);
121 cost = n_buckets * sizeof(struct stack_map_bucket *) + sizeof(*smap);
122 smap = bpf_map_area_alloc(cost, bpf_map_attr_numa_node(attr));
124 return ERR_PTR(-ENOMEM);
126 bpf_map_init_from_attr(&smap->map, attr);
127 smap->map.value_size = value_size;
128 smap->n_buckets = n_buckets;
130 err = get_callchain_buffers(sysctl_perf_event_max_stack);
134 err = prealloc_elems_and_freelist(smap);
141 put_callchain_buffers();
143 bpf_map_area_free(smap);
147 static void stack_map_get_build_id_offset(struct bpf_stack_build_id *id_offs,
148 u64 *ips, u32 trace_nr, bool user)
151 struct vm_area_struct *vma;
152 bool irq_work_busy = false;
153 struct stack_map_irq_work *work = NULL;
155 if (irqs_disabled()) {
156 if (!IS_ENABLED(CONFIG_PREEMPT_RT)) {
157 work = this_cpu_ptr(&up_read_work);
158 if (irq_work_is_busy(&work->irq_work)) {
159 /* cannot queue more up_read, fallback */
160 irq_work_busy = true;
164 * PREEMPT_RT does not allow to trylock mmap sem in
165 * interrupt disabled context. Force the fallback code.
167 irq_work_busy = true;
172 * We cannot do up_read() when the irq is disabled, because of
173 * risk to deadlock with rq_lock. To do build_id lookup when the
174 * irqs are disabled, we need to run up_read() in irq_work. We use
175 * a percpu variable to do the irq_work. If the irq_work is
176 * already used by another lookup, we fall back to report ips.
178 * Same fallback is used for kernel stack (!user) on a stackmap
181 if (!user || !current || !current->mm || irq_work_busy ||
182 !mmap_read_trylock(current->mm)) {
183 /* cannot access current->mm, fall back to ips */
184 for (i = 0; i < trace_nr; i++) {
185 id_offs[i].status = BPF_STACK_BUILD_ID_IP;
186 id_offs[i].ip = ips[i];
187 memset(id_offs[i].build_id, 0, BUILD_ID_SIZE_MAX);
192 for (i = 0; i < trace_nr; i++) {
193 vma = find_vma(current->mm, ips[i]);
194 if (!vma || build_id_parse(vma, id_offs[i].build_id, NULL)) {
195 /* per entry fall back to ips */
196 id_offs[i].status = BPF_STACK_BUILD_ID_IP;
197 id_offs[i].ip = ips[i];
198 memset(id_offs[i].build_id, 0, BUILD_ID_SIZE_MAX);
201 id_offs[i].offset = (vma->vm_pgoff << PAGE_SHIFT) + ips[i]
203 id_offs[i].status = BPF_STACK_BUILD_ID_VALID;
207 mmap_read_unlock(current->mm);
209 work->mm = current->mm;
211 /* The lock will be released once we're out of interrupt
212 * context. Tell lockdep that we've released it now so
213 * it doesn't complain that we forgot to release it.
215 rwsem_release(¤t->mm->mmap_lock.dep_map, _RET_IP_);
216 irq_work_queue(&work->irq_work);
220 static struct perf_callchain_entry *
221 get_callchain_entry_for_task(struct task_struct *task, u32 max_depth)
223 #ifdef CONFIG_STACKTRACE
224 struct perf_callchain_entry *entry;
227 entry = get_callchain_entry(&rctx);
232 entry->nr = stack_trace_save_tsk(task, (unsigned long *)entry->ip,
235 /* stack_trace_save_tsk() works on unsigned long array, while
236 * perf_callchain_entry uses u64 array. For 32-bit systems, it is
237 * necessary to fix this mismatch.
239 if (__BITS_PER_LONG != 64) {
240 unsigned long *from = (unsigned long *) entry->ip;
244 /* copy data from the end to avoid using extra buffer */
245 for (i = entry->nr - 1; i >= 0; i--)
246 to[i] = (u64)(from[i]);
249 put_callchain_entry(rctx);
252 #else /* CONFIG_STACKTRACE */
257 static long __bpf_get_stackid(struct bpf_map *map,
258 struct perf_callchain_entry *trace, u64 flags)
260 struct bpf_stack_map *smap = container_of(map, struct bpf_stack_map, map);
261 struct stack_map_bucket *bucket, *new_bucket, *old_bucket;
262 u32 skip = flags & BPF_F_SKIP_FIELD_MASK;
263 u32 hash, id, trace_nr, trace_len;
264 bool user = flags & BPF_F_USER_STACK;
268 if (trace->nr <= skip)
269 /* skipping more than usable stack trace */
272 trace_nr = trace->nr - skip;
273 trace_len = trace_nr * sizeof(u64);
274 ips = trace->ip + skip;
275 hash = jhash2((u32 *)ips, trace_len / sizeof(u32), 0);
276 id = hash & (smap->n_buckets - 1);
277 bucket = READ_ONCE(smap->buckets[id]);
279 hash_matches = bucket && bucket->hash == hash;
281 if (hash_matches && flags & BPF_F_FAST_STACK_CMP)
284 if (stack_map_use_build_id(map)) {
285 /* for build_id+offset, pop a bucket before slow cmp */
286 new_bucket = (struct stack_map_bucket *)
287 pcpu_freelist_pop(&smap->freelist);
288 if (unlikely(!new_bucket))
290 new_bucket->nr = trace_nr;
291 stack_map_get_build_id_offset(
292 (struct bpf_stack_build_id *)new_bucket->data,
293 ips, trace_nr, user);
294 trace_len = trace_nr * sizeof(struct bpf_stack_build_id);
295 if (hash_matches && bucket->nr == trace_nr &&
296 memcmp(bucket->data, new_bucket->data, trace_len) == 0) {
297 pcpu_freelist_push(&smap->freelist, &new_bucket->fnode);
300 if (bucket && !(flags & BPF_F_REUSE_STACKID)) {
301 pcpu_freelist_push(&smap->freelist, &new_bucket->fnode);
305 if (hash_matches && bucket->nr == trace_nr &&
306 memcmp(bucket->data, ips, trace_len) == 0)
308 if (bucket && !(flags & BPF_F_REUSE_STACKID))
311 new_bucket = (struct stack_map_bucket *)
312 pcpu_freelist_pop(&smap->freelist);
313 if (unlikely(!new_bucket))
315 memcpy(new_bucket->data, ips, trace_len);
318 new_bucket->hash = hash;
319 new_bucket->nr = trace_nr;
321 old_bucket = xchg(&smap->buckets[id], new_bucket);
323 pcpu_freelist_push(&smap->freelist, &old_bucket->fnode);
327 BPF_CALL_3(bpf_get_stackid, struct pt_regs *, regs, struct bpf_map *, map,
330 u32 max_depth = map->value_size / stack_map_data_size(map);
331 u32 skip = flags & BPF_F_SKIP_FIELD_MASK;
332 bool user = flags & BPF_F_USER_STACK;
333 struct perf_callchain_entry *trace;
336 if (unlikely(flags & ~(BPF_F_SKIP_FIELD_MASK | BPF_F_USER_STACK |
337 BPF_F_FAST_STACK_CMP | BPF_F_REUSE_STACKID)))
341 if (max_depth > sysctl_perf_event_max_stack)
342 max_depth = sysctl_perf_event_max_stack;
344 trace = get_perf_callchain(regs, 0, kernel, user, max_depth,
347 if (unlikely(!trace))
348 /* couldn't fetch the stack trace */
351 return __bpf_get_stackid(map, trace, flags);
354 const struct bpf_func_proto bpf_get_stackid_proto = {
355 .func = bpf_get_stackid,
357 .ret_type = RET_INTEGER,
358 .arg1_type = ARG_PTR_TO_CTX,
359 .arg2_type = ARG_CONST_MAP_PTR,
360 .arg3_type = ARG_ANYTHING,
363 static __u64 count_kernel_ip(struct perf_callchain_entry *trace)
367 while (nr_kernel < trace->nr) {
368 if (trace->ip[nr_kernel] == PERF_CONTEXT_USER)
375 BPF_CALL_3(bpf_get_stackid_pe, struct bpf_perf_event_data_kern *, ctx,
376 struct bpf_map *, map, u64, flags)
378 struct perf_event *event = ctx->event;
379 struct perf_callchain_entry *trace;
384 /* perf_sample_data doesn't have callchain, use bpf_get_stackid */
385 if (!(event->attr.sample_type & __PERF_SAMPLE_CALLCHAIN_EARLY))
386 return bpf_get_stackid((unsigned long)(ctx->regs),
387 (unsigned long) map, flags, 0, 0);
389 if (unlikely(flags & ~(BPF_F_SKIP_FIELD_MASK | BPF_F_USER_STACK |
390 BPF_F_FAST_STACK_CMP | BPF_F_REUSE_STACKID)))
393 user = flags & BPF_F_USER_STACK;
396 trace = ctx->data->callchain;
397 if (unlikely(!trace))
400 nr_kernel = count_kernel_ip(trace);
403 __u64 nr = trace->nr;
405 trace->nr = nr_kernel;
406 ret = __bpf_get_stackid(map, trace, flags);
411 u64 skip = flags & BPF_F_SKIP_FIELD_MASK;
414 if (skip > BPF_F_SKIP_FIELD_MASK)
417 flags = (flags & ~BPF_F_SKIP_FIELD_MASK) | skip;
418 ret = __bpf_get_stackid(map, trace, flags);
423 const struct bpf_func_proto bpf_get_stackid_proto_pe = {
424 .func = bpf_get_stackid_pe,
426 .ret_type = RET_INTEGER,
427 .arg1_type = ARG_PTR_TO_CTX,
428 .arg2_type = ARG_CONST_MAP_PTR,
429 .arg3_type = ARG_ANYTHING,
432 static long __bpf_get_stack(struct pt_regs *regs, struct task_struct *task,
433 struct perf_callchain_entry *trace_in,
434 void *buf, u32 size, u64 flags)
436 u32 trace_nr, copy_len, elem_size, num_elem, max_depth;
437 bool user_build_id = flags & BPF_F_USER_BUILD_ID;
438 u32 skip = flags & BPF_F_SKIP_FIELD_MASK;
439 bool user = flags & BPF_F_USER_STACK;
440 struct perf_callchain_entry *trace;
445 if (unlikely(flags & ~(BPF_F_SKIP_FIELD_MASK | BPF_F_USER_STACK |
446 BPF_F_USER_BUILD_ID)))
448 if (kernel && user_build_id)
451 elem_size = (user && user_build_id) ? sizeof(struct bpf_stack_build_id)
453 if (unlikely(size % elem_size))
456 /* cannot get valid user stack for task without user_mode regs */
457 if (task && user && !user_mode(regs))
460 num_elem = size / elem_size;
461 max_depth = num_elem + skip;
462 if (sysctl_perf_event_max_stack < max_depth)
463 max_depth = sysctl_perf_event_max_stack;
467 else if (kernel && task)
468 trace = get_callchain_entry_for_task(task, max_depth);
470 trace = get_perf_callchain(regs, 0, kernel, user, max_depth,
472 if (unlikely(!trace))
475 if (trace->nr < skip)
478 trace_nr = trace->nr - skip;
479 trace_nr = (trace_nr <= num_elem) ? trace_nr : num_elem;
480 copy_len = trace_nr * elem_size;
482 ips = trace->ip + skip;
483 if (user && user_build_id)
484 stack_map_get_build_id_offset(buf, ips, trace_nr, user);
486 memcpy(buf, ips, copy_len);
489 memset(buf + copy_len, 0, size - copy_len);
495 memset(buf, 0, size);
499 BPF_CALL_4(bpf_get_stack, struct pt_regs *, regs, void *, buf, u32, size,
502 return __bpf_get_stack(regs, NULL, NULL, buf, size, flags);
505 const struct bpf_func_proto bpf_get_stack_proto = {
506 .func = bpf_get_stack,
508 .ret_type = RET_INTEGER,
509 .arg1_type = ARG_PTR_TO_CTX,
510 .arg2_type = ARG_PTR_TO_UNINIT_MEM,
511 .arg3_type = ARG_CONST_SIZE_OR_ZERO,
512 .arg4_type = ARG_ANYTHING,
515 BPF_CALL_4(bpf_get_task_stack, struct task_struct *, task, void *, buf,
516 u32, size, u64, flags)
518 struct pt_regs *regs;
521 if (!try_get_task_stack(task))
524 regs = task_pt_regs(task);
526 res = __bpf_get_stack(regs, task, NULL, buf, size, flags);
527 put_task_stack(task);
532 const struct bpf_func_proto bpf_get_task_stack_proto = {
533 .func = bpf_get_task_stack,
535 .ret_type = RET_INTEGER,
536 .arg1_type = ARG_PTR_TO_BTF_ID,
537 .arg1_btf_id = &btf_task_struct_ids[0],
538 .arg2_type = ARG_PTR_TO_UNINIT_MEM,
539 .arg3_type = ARG_CONST_SIZE_OR_ZERO,
540 .arg4_type = ARG_ANYTHING,
543 BPF_CALL_4(bpf_get_stack_pe, struct bpf_perf_event_data_kern *, ctx,
544 void *, buf, u32, size, u64, flags)
546 struct pt_regs *regs = (struct pt_regs *)(ctx->regs);
547 struct perf_event *event = ctx->event;
548 struct perf_callchain_entry *trace;
553 if (!(event->attr.sample_type & __PERF_SAMPLE_CALLCHAIN_EARLY))
554 return __bpf_get_stack(regs, NULL, NULL, buf, size, flags);
556 if (unlikely(flags & ~(BPF_F_SKIP_FIELD_MASK | BPF_F_USER_STACK |
557 BPF_F_USER_BUILD_ID)))
560 user = flags & BPF_F_USER_STACK;
564 trace = ctx->data->callchain;
565 if (unlikely(!trace))
568 nr_kernel = count_kernel_ip(trace);
571 __u64 nr = trace->nr;
573 trace->nr = nr_kernel;
574 err = __bpf_get_stack(regs, NULL, trace, buf, size, flags);
579 u64 skip = flags & BPF_F_SKIP_FIELD_MASK;
582 if (skip > BPF_F_SKIP_FIELD_MASK)
585 flags = (flags & ~BPF_F_SKIP_FIELD_MASK) | skip;
586 err = __bpf_get_stack(regs, NULL, trace, buf, size, flags);
591 memset(buf, 0, size);
596 const struct bpf_func_proto bpf_get_stack_proto_pe = {
597 .func = bpf_get_stack_pe,
599 .ret_type = RET_INTEGER,
600 .arg1_type = ARG_PTR_TO_CTX,
601 .arg2_type = ARG_PTR_TO_UNINIT_MEM,
602 .arg3_type = ARG_CONST_SIZE_OR_ZERO,
603 .arg4_type = ARG_ANYTHING,
606 /* Called from eBPF program */
607 static void *stack_map_lookup_elem(struct bpf_map *map, void *key)
609 return ERR_PTR(-EOPNOTSUPP);
612 /* Called from syscall */
613 int bpf_stackmap_copy(struct bpf_map *map, void *key, void *value)
615 struct bpf_stack_map *smap = container_of(map, struct bpf_stack_map, map);
616 struct stack_map_bucket *bucket, *old_bucket;
617 u32 id = *(u32 *)key, trace_len;
619 if (unlikely(id >= smap->n_buckets))
622 bucket = xchg(&smap->buckets[id], NULL);
626 trace_len = bucket->nr * stack_map_data_size(map);
627 memcpy(value, bucket->data, trace_len);
628 memset(value + trace_len, 0, map->value_size - trace_len);
630 old_bucket = xchg(&smap->buckets[id], bucket);
632 pcpu_freelist_push(&smap->freelist, &old_bucket->fnode);
636 static int stack_map_get_next_key(struct bpf_map *map, void *key,
639 struct bpf_stack_map *smap = container_of(map,
640 struct bpf_stack_map, map);
643 WARN_ON_ONCE(!rcu_read_lock_held());
649 if (id >= smap->n_buckets || !smap->buckets[id])
655 while (id < smap->n_buckets && !smap->buckets[id])
658 if (id >= smap->n_buckets)
661 *(u32 *)next_key = id;
665 static int stack_map_update_elem(struct bpf_map *map, void *key, void *value,
671 /* Called from syscall or from eBPF program */
672 static int stack_map_delete_elem(struct bpf_map *map, void *key)
674 struct bpf_stack_map *smap = container_of(map, struct bpf_stack_map, map);
675 struct stack_map_bucket *old_bucket;
676 u32 id = *(u32 *)key;
678 if (unlikely(id >= smap->n_buckets))
681 old_bucket = xchg(&smap->buckets[id], NULL);
683 pcpu_freelist_push(&smap->freelist, &old_bucket->fnode);
690 /* Called when map->refcnt goes to zero, either from workqueue or from syscall */
691 static void stack_map_free(struct bpf_map *map)
693 struct bpf_stack_map *smap = container_of(map, struct bpf_stack_map, map);
695 bpf_map_area_free(smap->elems);
696 pcpu_freelist_destroy(&smap->freelist);
697 bpf_map_area_free(smap);
698 put_callchain_buffers();
701 static int stack_trace_map_btf_id;
702 const struct bpf_map_ops stack_trace_map_ops = {
703 .map_meta_equal = bpf_map_meta_equal,
704 .map_alloc = stack_map_alloc,
705 .map_free = stack_map_free,
706 .map_get_next_key = stack_map_get_next_key,
707 .map_lookup_elem = stack_map_lookup_elem,
708 .map_update_elem = stack_map_update_elem,
709 .map_delete_elem = stack_map_delete_elem,
710 .map_check_btf = map_check_no_btf,
711 .map_btf_name = "bpf_stack_map",
712 .map_btf_id = &stack_trace_map_btf_id,
715 static int __init stack_map_init(void)
718 struct stack_map_irq_work *work;
720 for_each_possible_cpu(cpu) {
721 work = per_cpu_ptr(&up_read_work, cpu);
722 init_irq_work(&work->irq_work, do_up_read);
726 subsys_initcall(stack_map_init);