792 lines · 20.9 KB · C
RawDownload
// SPDX-License-Identifier: GPL-2.0-only/* Copyright (c) 2016 Facebook */#include <linux/bpf.h>#include <linux/jhash.h>#include <linux/filter.h>#include <linux/kernel.h>#include <linux/stacktrace.h>#include <linux/perf_event.h>#include <linux/btf_ids.h>#include <linux/buildid.h>#include "percpu_freelist.h"#include "mmap_unlock_work.h" #define STACK_CREATE_FLAG_MASK					\	(BPF_F_NUMA_NODE | BPF_F_RDONLY | BPF_F_WRONLY |	\	 BPF_F_STACK_BUILD_ID) struct stack_map_bucket {	struct pcpu_freelist_node fnode;	u32 hash;	u32 nr;	u64 data[];}; struct bpf_stack_map {	struct bpf_map map;	void *elems;	struct pcpu_freelist freelist;	u32 n_buckets;	struct stack_map_bucket *buckets[] __counted_by(n_buckets);}; static inline bool stack_map_use_build_id(struct bpf_map *map){	return (map->map_flags & BPF_F_STACK_BUILD_ID);} static inline int stack_map_data_size(struct bpf_map *map){	return stack_map_use_build_id(map) ?		sizeof(struct bpf_stack_build_id) : sizeof(u64);} /** * stack_map_calculate_max_depth - Calculate maximum allowed stack trace depth * @size:  Size of the buffer/map value in bytes * @elem_size:  Size of each stack trace element * @flags:  BPF stack trace flags (BPF_F_USER_STACK, BPF_F_USER_BUILD_ID, ...) * * Return: Maximum number of stack trace entries that can be safely stored */static u32 stack_map_calculate_max_depth(u32 size, u32 elem_size, u64 flags){	u32 skip = flags & BPF_F_SKIP_FIELD_MASK;	u32 max_depth;	u32 curr_sysctl_max_stack = READ_ONCE(sysctl_perf_event_max_stack); 	max_depth = size / elem_size;	max_depth += skip;	if (max_depth > curr_sysctl_max_stack)		return curr_sysctl_max_stack; 	return max_depth;} static int prealloc_elems_and_freelist(struct bpf_stack_map *smap){	u64 elem_size = sizeof(struct stack_map_bucket) +			(u64)smap->map.value_size;	int err; 	smap->elems = bpf_map_area_alloc(elem_size * smap->map.max_entries,					 smap->map.numa_node);	if (!smap->elems)		return -ENOMEM; 	err = pcpu_freelist_init(&smap->freelist);	if (err)		goto free_elems; 	pcpu_freelist_populate(&smap->freelist, smap->elems, elem_size,			       smap->map.max_entries);	return 0; free_elems:	bpf_map_area_free(smap->elems);	return err;} /* Called from syscall */static struct bpf_map *stack_map_alloc(union bpf_attr *attr){	u32 value_size = attr->value_size;	struct bpf_stack_map *smap;	u64 cost, n_buckets;	int err; 	if (attr->map_flags & ~STACK_CREATE_FLAG_MASK)		return ERR_PTR(-EINVAL); 	/* check sanity of attributes */	if (attr->max_entries == 0 || attr->key_size != 4 ||	    value_size < 8 || value_size % 8)		return ERR_PTR(-EINVAL); 	BUILD_BUG_ON(sizeof(struct bpf_stack_build_id) % sizeof(u64));	if (attr->map_flags & BPF_F_STACK_BUILD_ID) {		if (value_size % sizeof(struct bpf_stack_build_id) ||		    value_size / sizeof(struct bpf_stack_build_id)		    > sysctl_perf_event_max_stack)			return ERR_PTR(-EINVAL);	} else if (value_size / 8 > sysctl_perf_event_max_stack)		return ERR_PTR(-EINVAL); 	/* hash table size must be power of 2; roundup_pow_of_two() can overflow	 * into UB on 32-bit arches, so check that first	 */	if (attr->max_entries > 1UL << 31)		return ERR_PTR(-E2BIG); 	n_buckets = roundup_pow_of_two(attr->max_entries); 	cost = n_buckets * sizeof(struct stack_map_bucket *) + sizeof(*smap);	smap = bpf_map_area_alloc(cost, bpf_map_attr_numa_node(attr));	if (!smap)		return ERR_PTR(-ENOMEM); 	bpf_map_init_from_attr(&smap->map, attr);	smap->n_buckets = n_buckets; 	err = get_callchain_buffers(sysctl_perf_event_max_stack);	if (err)		goto free_smap; 	err = prealloc_elems_and_freelist(smap);	if (err)		goto put_buffers; 	return &smap->map; put_buffers:	put_callchain_buffers();free_smap:	bpf_map_area_free(smap);	return ERR_PTR(err);} static int fetch_build_id(struct vm_area_struct *vma, unsigned char *build_id, bool may_fault){	return may_fault ? build_id_parse(vma, build_id, NULL)			 : build_id_parse_nofault(vma, build_id, NULL);} /* * Expects all id_offs[i].ip values to be set to correct initial IPs. * They will be subsequently: *   - either adjusted in place to a file offset, if build ID fetching *     succeeds; in this case id_offs[i].build_id is set to correct build ID, *     and id_offs[i].status is set to BPF_STACK_BUILD_ID_VALID; *   - or IP will be kept intact, if build ID fetching failed; in this case *     id_offs[i].build_id is zeroed out and id_offs[i].status is set to *     BPF_STACK_BUILD_ID_IP. */static void stack_map_get_build_id_offset(struct bpf_stack_build_id *id_offs,					  u32 trace_nr, bool user, bool may_fault){	int i;	struct mmap_unlock_irq_work *work = NULL;	bool irq_work_busy = bpf_mmap_unlock_get_irq_work(&work);	struct vm_area_struct *vma, *prev_vma = NULL;	const char *prev_build_id; 	/* If the irq_work is in use, fall back to report ips. Same	 * fallback is used for kernel stack (!user) on a stackmap with	 * build_id.	 */	if (!user || !current || !current->mm || irq_work_busy ||	    !mmap_read_trylock(current->mm)) {		/* cannot access current->mm, fall back to ips */		for (i = 0; i < trace_nr; i++) {			id_offs[i].status = BPF_STACK_BUILD_ID_IP;			memset(id_offs[i].build_id, 0, BUILD_ID_SIZE_MAX);		}		return;	} 	for (i = 0; i < trace_nr; i++) {		u64 ip = READ_ONCE(id_offs[i].ip); 		if (range_in_vma(prev_vma, ip, ip)) {			vma = prev_vma;			memcpy(id_offs[i].build_id, prev_build_id, BUILD_ID_SIZE_MAX);			goto build_id_valid;		}		vma = find_vma(current->mm, ip);		if (!vma || fetch_build_id(vma, id_offs[i].build_id, may_fault)) {			/* per entry fall back to ips */			id_offs[i].status = BPF_STACK_BUILD_ID_IP;			memset(id_offs[i].build_id, 0, BUILD_ID_SIZE_MAX);			continue;		}build_id_valid:		id_offs[i].offset = (vma->vm_pgoff << PAGE_SHIFT) + ip - vma->vm_start;		id_offs[i].status = BPF_STACK_BUILD_ID_VALID;		prev_vma = vma;		prev_build_id = id_offs[i].build_id;	}	bpf_mmap_unlock_mm(work, current->mm);} static struct perf_callchain_entry *get_callchain_entry_for_task(struct task_struct *task, u32 max_depth){#ifdef CONFIG_STACKTRACE	struct perf_callchain_entry *entry;	int rctx; 	entry = get_callchain_entry(&rctx); 	if (!entry)		return NULL; 	entry->nr = stack_trace_save_tsk(task, (unsigned long *)entry->ip,					 max_depth, 0); 	/* stack_trace_save_tsk() works on unsigned long array, while	 * perf_callchain_entry uses u64 array. For 32-bit systems, it is	 * necessary to fix this mismatch.	 */	if (__BITS_PER_LONG != 64) {		unsigned long *from = (unsigned long *) entry->ip;		u64 *to = entry->ip;		int i; 		/* copy data from the end to avoid using extra buffer */		for (i = entry->nr - 1; i >= 0; i--)			to[i] = (u64)(from[i]);	} 	put_callchain_entry(rctx); 	return entry;#else /* CONFIG_STACKTRACE */	return NULL;#endif} static long __bpf_get_stackid(struct bpf_map *map,			      struct perf_callchain_entry *trace, u64 flags){	struct bpf_stack_map *smap = container_of(map, struct bpf_stack_map, map);	struct stack_map_bucket *bucket, *new_bucket, *old_bucket;	u32 hash, id, trace_nr, trace_len, i, max_depth;	u32 skip = flags & BPF_F_SKIP_FIELD_MASK;	bool user = flags & BPF_F_USER_STACK;	u64 *ips;	bool hash_matches; 	if (trace->nr <= skip)		/* skipping more than usable stack trace */		return -EFAULT; 	max_depth = stack_map_calculate_max_depth(map->value_size, stack_map_data_size(map), flags);	trace_nr = min_t(u32, trace->nr - skip, max_depth - skip);	trace_len = trace_nr * sizeof(u64);	ips = trace->ip + skip;	hash = jhash2((u32 *)ips, trace_len / sizeof(u32), 0);	id = hash & (smap->n_buckets - 1);	bucket = READ_ONCE(smap->buckets[id]); 	hash_matches = bucket && bucket->hash == hash;	/* fast cmp */	if (hash_matches && flags & BPF_F_FAST_STACK_CMP)		return id; 	if (stack_map_use_build_id(map)) {		struct bpf_stack_build_id *id_offs; 		/* for build_id+offset, pop a bucket before slow cmp */		new_bucket = (struct stack_map_bucket *)			pcpu_freelist_pop(&smap->freelist);		if (unlikely(!new_bucket))			return -ENOMEM;		new_bucket->nr = trace_nr;		id_offs = (struct bpf_stack_build_id *)new_bucket->data;		for (i = 0; i < trace_nr; i++)			id_offs[i].ip = ips[i];		stack_map_get_build_id_offset(id_offs, trace_nr, user, false /* !may_fault */);		trace_len = trace_nr * sizeof(struct bpf_stack_build_id);		if (hash_matches && bucket->nr == trace_nr &&		    memcmp(bucket->data, new_bucket->data, trace_len) == 0) {			pcpu_freelist_push(&smap->freelist, &new_bucket->fnode);			return id;		}		if (bucket && !(flags & BPF_F_REUSE_STACKID)) {			pcpu_freelist_push(&smap->freelist, &new_bucket->fnode);			return -EEXIST;		}	} else {		if (hash_matches && bucket->nr == trace_nr &&		    memcmp(bucket->data, ips, trace_len) == 0)			return id;		if (bucket && !(flags & BPF_F_REUSE_STACKID))			return -EEXIST; 		new_bucket = (struct stack_map_bucket *)			pcpu_freelist_pop(&smap->freelist);		if (unlikely(!new_bucket))			return -ENOMEM;		memcpy(new_bucket->data, ips, trace_len);	} 	new_bucket->hash = hash;	new_bucket->nr = trace_nr; 	old_bucket = xchg(&smap->buckets[id], new_bucket);	if (old_bucket)		pcpu_freelist_push(&smap->freelist, &old_bucket->fnode);	return id;} BPF_CALL_3(bpf_get_stackid, struct pt_regs *, regs, struct bpf_map *, map,	   u64, flags){	u32 elem_size = stack_map_data_size(map);	bool user = flags & BPF_F_USER_STACK;	struct perf_callchain_entry *trace;	bool kernel = !user;	u32 max_depth; 	if (unlikely(flags & ~(BPF_F_SKIP_FIELD_MASK | BPF_F_USER_STACK |			       BPF_F_FAST_STACK_CMP | BPF_F_REUSE_STACKID)))		return -EINVAL; 	max_depth = stack_map_calculate_max_depth(map->value_size, elem_size, flags);	trace = get_perf_callchain(regs, kernel, user, max_depth,				   false, false, 0); 	if (unlikely(!trace))		/* couldn't fetch the stack trace */		return -EFAULT; 	return __bpf_get_stackid(map, trace, flags);} const struct bpf_func_proto bpf_get_stackid_proto = {	.func		= bpf_get_stackid,	.gpl_only	= true,	.ret_type	= RET_INTEGER,	.arg1_type	= ARG_PTR_TO_CTX,	.arg2_type	= ARG_CONST_MAP_PTR,	.arg3_type	= ARG_ANYTHING,}; static __u64 count_kernel_ip(struct perf_callchain_entry *trace){	__u64 nr_kernel = 0; 	while (nr_kernel < trace->nr) {		if (trace->ip[nr_kernel] == PERF_CONTEXT_USER)			break;		nr_kernel++;	}	return nr_kernel;} BPF_CALL_3(bpf_get_stackid_pe, struct bpf_perf_event_data_kern *, ctx,	   struct bpf_map *, map, u64, flags){	struct perf_event *event = ctx->event;	struct perf_callchain_entry *trace;	bool kernel, user;	__u64 nr_kernel;	int ret; 	/* perf_sample_data doesn't have callchain, use bpf_get_stackid */	if (!(event->attr.sample_type & PERF_SAMPLE_CALLCHAIN))		return bpf_get_stackid((unsigned long)(ctx->regs),				       (unsigned long) map, flags, 0, 0); 	if (unlikely(flags & ~(BPF_F_SKIP_FIELD_MASK | BPF_F_USER_STACK |			       BPF_F_FAST_STACK_CMP | BPF_F_REUSE_STACKID)))		return -EINVAL; 	user = flags & BPF_F_USER_STACK;	kernel = !user; 	trace = ctx->data->callchain;	if (unlikely(!trace))		return -EFAULT; 	nr_kernel = count_kernel_ip(trace);	__u64 nr = trace->nr; /* save original */ 	if (kernel) {		trace->nr = nr_kernel;		ret = __bpf_get_stackid(map, trace, flags);	} else { /* user */		u64 skip = flags & BPF_F_SKIP_FIELD_MASK; 		skip += nr_kernel;		if (skip > BPF_F_SKIP_FIELD_MASK)			return -EFAULT; 		flags = (flags & ~BPF_F_SKIP_FIELD_MASK) | skip;		ret = __bpf_get_stackid(map, trace, flags);	} 	/* restore nr */	trace->nr = nr; 	return ret;} const struct bpf_func_proto bpf_get_stackid_proto_pe = {	.func		= bpf_get_stackid_pe,	.gpl_only	= false,	.ret_type	= RET_INTEGER,	.arg1_type	= ARG_PTR_TO_CTX,	.arg2_type	= ARG_CONST_MAP_PTR,	.arg3_type	= ARG_ANYTHING,}; static long __bpf_get_stack(struct pt_regs *regs, struct task_struct *task,			    struct perf_callchain_entry *trace_in,			    void *buf, u32 size, u64 flags, bool may_fault){	u32 trace_nr, copy_len, elem_size, max_depth;	bool user_build_id = flags & BPF_F_USER_BUILD_ID;	bool crosstask = task && task != current;	u32 skip = flags & BPF_F_SKIP_FIELD_MASK;	bool user = flags & BPF_F_USER_STACK;	struct perf_callchain_entry *trace;	bool kernel = !user;	int err = -EINVAL;	u64 *ips; 	if (unlikely(flags & ~(BPF_F_SKIP_FIELD_MASK | BPF_F_USER_STACK |			       BPF_F_USER_BUILD_ID)))		goto clear;	if (kernel && user_build_id)		goto clear; 	elem_size = user_build_id ? sizeof(struct bpf_stack_build_id) : sizeof(u64);	if (unlikely(size % elem_size))		goto clear; 	/* cannot get valid user stack for task without user_mode regs */	if (task && user && !user_mode(regs))		goto err_fault; 	/* get_perf_callchain does not support crosstask user stack walking	 * but returns an empty stack instead of NULL.	 */	if (crosstask && user) {		err = -EOPNOTSUPP;		goto clear;	} 	max_depth = stack_map_calculate_max_depth(size, elem_size, flags); 	if (may_fault)		rcu_read_lock(); /* need RCU for perf's callchain below */ 	if (trace_in) {		trace = trace_in;		trace->nr = min_t(u32, trace->nr, max_depth);	} else if (kernel && task) {		trace = get_callchain_entry_for_task(task, max_depth);	} else {		trace = get_perf_callchain(regs, kernel, user, max_depth,					   crosstask, false, 0);	} 	if (unlikely(!trace) || trace->nr < skip) {		if (may_fault)			rcu_read_unlock();		goto err_fault;	} 	trace_nr = trace->nr - skip;	copy_len = trace_nr * elem_size; 	ips = trace->ip + skip;	if (user_build_id) {		struct bpf_stack_build_id *id_offs = buf;		u32 i; 		for (i = 0; i < trace_nr; i++)			id_offs[i].ip = ips[i];	} else {		memcpy(buf, ips, copy_len);	} 	/* trace/ips should not be dereferenced after this point */	if (may_fault)		rcu_read_unlock(); 	if (user_build_id)

Lines 1–500 of 792.