xref: /openbmc/linux/kernel/bpf/stackmap.c (revision 887069f4)
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/irq_work.h>
11 #include <linux/btf_ids.h>
12 #include <linux/buildid.h>
13 #include "percpu_freelist.h"
14 
15 #define STACK_CREATE_FLAG_MASK					\
16 	(BPF_F_NUMA_NODE | BPF_F_RDONLY | BPF_F_WRONLY |	\
17 	 BPF_F_STACK_BUILD_ID)
18 
19 struct stack_map_bucket {
20 	struct pcpu_freelist_node fnode;
21 	u32 hash;
22 	u32 nr;
23 	u64 data[];
24 };
25 
26 struct bpf_stack_map {
27 	struct bpf_map map;
28 	void *elems;
29 	struct pcpu_freelist freelist;
30 	u32 n_buckets;
31 	struct stack_map_bucket *buckets[];
32 };
33 
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;
37 	struct mm_struct *mm;
38 };
39 
40 static void do_up_read(struct irq_work *entry)
41 {
42 	struct stack_map_irq_work *work;
43 
44 	if (WARN_ON_ONCE(IS_ENABLED(CONFIG_PREEMPT_RT)))
45 		return;
46 
47 	work = container_of(entry, struct stack_map_irq_work, irq_work);
48 	mmap_read_unlock_non_owner(work->mm);
49 }
50 
51 static DEFINE_PER_CPU(struct stack_map_irq_work, up_read_work);
52 
53 static inline bool stack_map_use_build_id(struct bpf_map *map)
54 {
55 	return (map->map_flags & BPF_F_STACK_BUILD_ID);
56 }
57 
58 static inline int stack_map_data_size(struct bpf_map *map)
59 {
60 	return stack_map_use_build_id(map) ?
61 		sizeof(struct bpf_stack_build_id) : sizeof(u64);
62 }
63 
64 static int prealloc_elems_and_freelist(struct bpf_stack_map *smap)
65 {
66 	u32 elem_size = sizeof(struct stack_map_bucket) + smap->map.value_size;
67 	int err;
68 
69 	smap->elems = bpf_map_area_alloc(elem_size * smap->map.max_entries,
70 					 smap->map.numa_node);
71 	if (!smap->elems)
72 		return -ENOMEM;
73 
74 	err = pcpu_freelist_init(&smap->freelist);
75 	if (err)
76 		goto free_elems;
77 
78 	pcpu_freelist_populate(&smap->freelist, smap->elems, elem_size,
79 			       smap->map.max_entries);
80 	return 0;
81 
82 free_elems:
83 	bpf_map_area_free(smap->elems);
84 	return err;
85 }
86 
87 /* Called from syscall */
88 static struct bpf_map *stack_map_alloc(union bpf_attr *attr)
89 {
90 	u32 value_size = attr->value_size;
91 	struct bpf_stack_map *smap;
92 	u64 cost, n_buckets;
93 	int err;
94 
95 	if (!bpf_capable())
96 		return ERR_PTR(-EPERM);
97 
98 	if (attr->map_flags & ~STACK_CREATE_FLAG_MASK)
99 		return ERR_PTR(-EINVAL);
100 
101 	/* check sanity of attributes */
102 	if (attr->max_entries == 0 || attr->key_size != 4 ||
103 	    value_size < 8 || value_size % 8)
104 		return ERR_PTR(-EINVAL);
105 
106 	BUILD_BUG_ON(sizeof(struct bpf_stack_build_id) % sizeof(u64));
107 	if (attr->map_flags & BPF_F_STACK_BUILD_ID) {
108 		if (value_size % sizeof(struct bpf_stack_build_id) ||
109 		    value_size / sizeof(struct bpf_stack_build_id)
110 		    > sysctl_perf_event_max_stack)
111 			return ERR_PTR(-EINVAL);
112 	} else if (value_size / 8 > sysctl_perf_event_max_stack)
113 		return ERR_PTR(-EINVAL);
114 
115 	/* hash table size must be power of 2 */
116 	n_buckets = roundup_pow_of_two(attr->max_entries);
117 	if (!n_buckets)
118 		return ERR_PTR(-E2BIG);
119 
120 	cost = n_buckets * sizeof(struct stack_map_bucket *) + sizeof(*smap);
121 	cost += n_buckets * (value_size + sizeof(struct stack_map_bucket));
122 	smap = bpf_map_area_alloc(cost, bpf_map_attr_numa_node(attr));
123 	if (!smap)
124 		return ERR_PTR(-ENOMEM);
125 
126 	bpf_map_init_from_attr(&smap->map, attr);
127 	smap->map.value_size = value_size;
128 	smap->n_buckets = n_buckets;
129 
130 	err = get_callchain_buffers(sysctl_perf_event_max_stack);
131 	if (err)
132 		goto free_smap;
133 
134 	err = prealloc_elems_and_freelist(smap);
135 	if (err)
136 		goto put_buffers;
137 
138 	return &smap->map;
139 
140 put_buffers:
141 	put_callchain_buffers();
142 free_smap:
143 	bpf_map_area_free(smap);
144 	return ERR_PTR(err);
145 }
146 
147 static void stack_map_get_build_id_offset(struct bpf_stack_build_id *id_offs,
148 					  u64 *ips, u32 trace_nr, bool user)
149 {
150 	int i;
151 	struct vm_area_struct *vma;
152 	bool irq_work_busy = false;
153 	struct stack_map_irq_work *work = NULL;
154 
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;
161 			}
162 		} else {
163 			/*
164 			 * PREEMPT_RT does not allow to trylock mmap sem in
165 			 * interrupt disabled context. Force the fallback code.
166 			 */
167 			irq_work_busy = true;
168 		}
169 	}
170 
171 	/*
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.
177 	 *
178 	 * Same fallback is used for kernel stack (!user) on a stackmap
179 	 * with build_id.
180 	 */
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);
188 		}
189 		return;
190 	}
191 
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);
199 			continue;
200 		}
201 		id_offs[i].offset = (vma->vm_pgoff << PAGE_SHIFT) + ips[i]
202 			- vma->vm_start;
203 		id_offs[i].status = BPF_STACK_BUILD_ID_VALID;
204 	}
205 
206 	if (!work) {
207 		mmap_read_unlock(current->mm);
208 	} else {
209 		work->mm = current->mm;
210 
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.
214 		 */
215 		rwsem_release(&current->mm->mmap_lock.dep_map, _RET_IP_);
216 		irq_work_queue(&work->irq_work);
217 	}
218 }
219 
220 static struct perf_callchain_entry *
221 get_callchain_entry_for_task(struct task_struct *task, u32 init_nr)
222 {
223 #ifdef CONFIG_STACKTRACE
224 	struct perf_callchain_entry *entry;
225 	int rctx;
226 
227 	entry = get_callchain_entry(&rctx);
228 
229 	if (!entry)
230 		return NULL;
231 
232 	entry->nr = init_nr +
233 		stack_trace_save_tsk(task, (unsigned long *)(entry->ip + init_nr),
234 				     sysctl_perf_event_max_stack - init_nr, 0);
235 
236 	/* stack_trace_save_tsk() works on unsigned long array, while
237 	 * perf_callchain_entry uses u64 array. For 32-bit systems, it is
238 	 * necessary to fix this mismatch.
239 	 */
240 	if (__BITS_PER_LONG != 64) {
241 		unsigned long *from = (unsigned long *) entry->ip;
242 		u64 *to = entry->ip;
243 		int i;
244 
245 		/* copy data from the end to avoid using extra buffer */
246 		for (i = entry->nr - 1; i >= (int)init_nr; i--)
247 			to[i] = (u64)(from[i]);
248 	}
249 
250 	put_callchain_entry(rctx);
251 
252 	return entry;
253 #else /* CONFIG_STACKTRACE */
254 	return NULL;
255 #endif
256 }
257 
258 static long __bpf_get_stackid(struct bpf_map *map,
259 			      struct perf_callchain_entry *trace, u64 flags)
260 {
261 	struct bpf_stack_map *smap = container_of(map, struct bpf_stack_map, map);
262 	struct stack_map_bucket *bucket, *new_bucket, *old_bucket;
263 	u32 max_depth = map->value_size / stack_map_data_size(map);
264 	/* stack_map_alloc() checks that max_depth <= sysctl_perf_event_max_stack */
265 	u32 init_nr = sysctl_perf_event_max_stack - max_depth;
266 	u32 skip = flags & BPF_F_SKIP_FIELD_MASK;
267 	u32 hash, id, trace_nr, trace_len;
268 	bool user = flags & BPF_F_USER_STACK;
269 	u64 *ips;
270 	bool hash_matches;
271 
272 	/* get_perf_callchain() guarantees that trace->nr >= init_nr
273 	 * and trace-nr <= sysctl_perf_event_max_stack, so trace_nr <= max_depth
274 	 */
275 	trace_nr = trace->nr - init_nr;
276 
277 	if (trace_nr <= skip)
278 		/* skipping more than usable stack trace */
279 		return -EFAULT;
280 
281 	trace_nr -= skip;
282 	trace_len = trace_nr * sizeof(u64);
283 	ips = trace->ip + skip + init_nr;
284 	hash = jhash2((u32 *)ips, trace_len / sizeof(u32), 0);
285 	id = hash & (smap->n_buckets - 1);
286 	bucket = READ_ONCE(smap->buckets[id]);
287 
288 	hash_matches = bucket && bucket->hash == hash;
289 	/* fast cmp */
290 	if (hash_matches && flags & BPF_F_FAST_STACK_CMP)
291 		return id;
292 
293 	if (stack_map_use_build_id(map)) {
294 		/* for build_id+offset, pop a bucket before slow cmp */
295 		new_bucket = (struct stack_map_bucket *)
296 			pcpu_freelist_pop(&smap->freelist);
297 		if (unlikely(!new_bucket))
298 			return -ENOMEM;
299 		new_bucket->nr = trace_nr;
300 		stack_map_get_build_id_offset(
301 			(struct bpf_stack_build_id *)new_bucket->data,
302 			ips, trace_nr, user);
303 		trace_len = trace_nr * sizeof(struct bpf_stack_build_id);
304 		if (hash_matches && bucket->nr == trace_nr &&
305 		    memcmp(bucket->data, new_bucket->data, trace_len) == 0) {
306 			pcpu_freelist_push(&smap->freelist, &new_bucket->fnode);
307 			return id;
308 		}
309 		if (bucket && !(flags & BPF_F_REUSE_STACKID)) {
310 			pcpu_freelist_push(&smap->freelist, &new_bucket->fnode);
311 			return -EEXIST;
312 		}
313 	} else {
314 		if (hash_matches && bucket->nr == trace_nr &&
315 		    memcmp(bucket->data, ips, trace_len) == 0)
316 			return id;
317 		if (bucket && !(flags & BPF_F_REUSE_STACKID))
318 			return -EEXIST;
319 
320 		new_bucket = (struct stack_map_bucket *)
321 			pcpu_freelist_pop(&smap->freelist);
322 		if (unlikely(!new_bucket))
323 			return -ENOMEM;
324 		memcpy(new_bucket->data, ips, trace_len);
325 	}
326 
327 	new_bucket->hash = hash;
328 	new_bucket->nr = trace_nr;
329 
330 	old_bucket = xchg(&smap->buckets[id], new_bucket);
331 	if (old_bucket)
332 		pcpu_freelist_push(&smap->freelist, &old_bucket->fnode);
333 	return id;
334 }
335 
336 BPF_CALL_3(bpf_get_stackid, struct pt_regs *, regs, struct bpf_map *, map,
337 	   u64, flags)
338 {
339 	u32 max_depth = map->value_size / stack_map_data_size(map);
340 	/* stack_map_alloc() checks that max_depth <= sysctl_perf_event_max_stack */
341 	u32 init_nr = sysctl_perf_event_max_stack - max_depth;
342 	bool user = flags & BPF_F_USER_STACK;
343 	struct perf_callchain_entry *trace;
344 	bool kernel = !user;
345 
346 	if (unlikely(flags & ~(BPF_F_SKIP_FIELD_MASK | BPF_F_USER_STACK |
347 			       BPF_F_FAST_STACK_CMP | BPF_F_REUSE_STACKID)))
348 		return -EINVAL;
349 
350 	trace = get_perf_callchain(regs, init_nr, kernel, user,
351 				   sysctl_perf_event_max_stack, false, false);
352 
353 	if (unlikely(!trace))
354 		/* couldn't fetch the stack trace */
355 		return -EFAULT;
356 
357 	return __bpf_get_stackid(map, trace, flags);
358 }
359 
360 const struct bpf_func_proto bpf_get_stackid_proto = {
361 	.func		= bpf_get_stackid,
362 	.gpl_only	= true,
363 	.ret_type	= RET_INTEGER,
364 	.arg1_type	= ARG_PTR_TO_CTX,
365 	.arg2_type	= ARG_CONST_MAP_PTR,
366 	.arg3_type	= ARG_ANYTHING,
367 };
368 
369 static __u64 count_kernel_ip(struct perf_callchain_entry *trace)
370 {
371 	__u64 nr_kernel = 0;
372 
373 	while (nr_kernel < trace->nr) {
374 		if (trace->ip[nr_kernel] == PERF_CONTEXT_USER)
375 			break;
376 		nr_kernel++;
377 	}
378 	return nr_kernel;
379 }
380 
381 BPF_CALL_3(bpf_get_stackid_pe, struct bpf_perf_event_data_kern *, ctx,
382 	   struct bpf_map *, map, u64, flags)
383 {
384 	struct perf_event *event = ctx->event;
385 	struct perf_callchain_entry *trace;
386 	bool kernel, user;
387 	__u64 nr_kernel;
388 	int ret;
389 
390 	/* perf_sample_data doesn't have callchain, use bpf_get_stackid */
391 	if (!(event->attr.sample_type & __PERF_SAMPLE_CALLCHAIN_EARLY))
392 		return bpf_get_stackid((unsigned long)(ctx->regs),
393 				       (unsigned long) map, flags, 0, 0);
394 
395 	if (unlikely(flags & ~(BPF_F_SKIP_FIELD_MASK | BPF_F_USER_STACK |
396 			       BPF_F_FAST_STACK_CMP | BPF_F_REUSE_STACKID)))
397 		return -EINVAL;
398 
399 	user = flags & BPF_F_USER_STACK;
400 	kernel = !user;
401 
402 	trace = ctx->data->callchain;
403 	if (unlikely(!trace))
404 		return -EFAULT;
405 
406 	nr_kernel = count_kernel_ip(trace);
407 
408 	if (kernel) {
409 		__u64 nr = trace->nr;
410 
411 		trace->nr = nr_kernel;
412 		ret = __bpf_get_stackid(map, trace, flags);
413 
414 		/* restore nr */
415 		trace->nr = nr;
416 	} else { /* user */
417 		u64 skip = flags & BPF_F_SKIP_FIELD_MASK;
418 
419 		skip += nr_kernel;
420 		if (skip > BPF_F_SKIP_FIELD_MASK)
421 			return -EFAULT;
422 
423 		flags = (flags & ~BPF_F_SKIP_FIELD_MASK) | skip;
424 		ret = __bpf_get_stackid(map, trace, flags);
425 	}
426 	return ret;
427 }
428 
429 const struct bpf_func_proto bpf_get_stackid_proto_pe = {
430 	.func		= bpf_get_stackid_pe,
431 	.gpl_only	= false,
432 	.ret_type	= RET_INTEGER,
433 	.arg1_type	= ARG_PTR_TO_CTX,
434 	.arg2_type	= ARG_CONST_MAP_PTR,
435 	.arg3_type	= ARG_ANYTHING,
436 };
437 
438 static long __bpf_get_stack(struct pt_regs *regs, struct task_struct *task,
439 			    struct perf_callchain_entry *trace_in,
440 			    void *buf, u32 size, u64 flags)
441 {
442 	u32 init_nr, trace_nr, copy_len, elem_size, num_elem;
443 	bool user_build_id = flags & BPF_F_USER_BUILD_ID;
444 	u32 skip = flags & BPF_F_SKIP_FIELD_MASK;
445 	bool user = flags & BPF_F_USER_STACK;
446 	struct perf_callchain_entry *trace;
447 	bool kernel = !user;
448 	int err = -EINVAL;
449 	u64 *ips;
450 
451 	if (unlikely(flags & ~(BPF_F_SKIP_FIELD_MASK | BPF_F_USER_STACK |
452 			       BPF_F_USER_BUILD_ID)))
453 		goto clear;
454 	if (kernel && user_build_id)
455 		goto clear;
456 
457 	elem_size = (user && user_build_id) ? sizeof(struct bpf_stack_build_id)
458 					    : sizeof(u64);
459 	if (unlikely(size % elem_size))
460 		goto clear;
461 
462 	/* cannot get valid user stack for task without user_mode regs */
463 	if (task && user && !user_mode(regs))
464 		goto err_fault;
465 
466 	num_elem = size / elem_size;
467 	if (sysctl_perf_event_max_stack < num_elem)
468 		init_nr = 0;
469 	else
470 		init_nr = sysctl_perf_event_max_stack - num_elem;
471 
472 	if (trace_in)
473 		trace = trace_in;
474 	else if (kernel && task)
475 		trace = get_callchain_entry_for_task(task, init_nr);
476 	else
477 		trace = get_perf_callchain(regs, init_nr, kernel, user,
478 					   sysctl_perf_event_max_stack,
479 					   false, false);
480 	if (unlikely(!trace))
481 		goto err_fault;
482 
483 	trace_nr = trace->nr - init_nr;
484 	if (trace_nr < skip)
485 		goto err_fault;
486 
487 	trace_nr -= skip;
488 	trace_nr = (trace_nr <= num_elem) ? trace_nr : num_elem;
489 	copy_len = trace_nr * elem_size;
490 	ips = trace->ip + skip + init_nr;
491 	if (user && user_build_id)
492 		stack_map_get_build_id_offset(buf, ips, trace_nr, user);
493 	else
494 		memcpy(buf, ips, copy_len);
495 
496 	if (size > copy_len)
497 		memset(buf + copy_len, 0, size - copy_len);
498 	return copy_len;
499 
500 err_fault:
501 	err = -EFAULT;
502 clear:
503 	memset(buf, 0, size);
504 	return err;
505 }
506 
507 BPF_CALL_4(bpf_get_stack, struct pt_regs *, regs, void *, buf, u32, size,
508 	   u64, flags)
509 {
510 	return __bpf_get_stack(regs, NULL, NULL, buf, size, flags);
511 }
512 
513 const struct bpf_func_proto bpf_get_stack_proto = {
514 	.func		= bpf_get_stack,
515 	.gpl_only	= true,
516 	.ret_type	= RET_INTEGER,
517 	.arg1_type	= ARG_PTR_TO_CTX,
518 	.arg2_type	= ARG_PTR_TO_UNINIT_MEM,
519 	.arg3_type	= ARG_CONST_SIZE_OR_ZERO,
520 	.arg4_type	= ARG_ANYTHING,
521 };
522 
523 BPF_CALL_4(bpf_get_task_stack, struct task_struct *, task, void *, buf,
524 	   u32, size, u64, flags)
525 {
526 	struct pt_regs *regs;
527 	long res;
528 
529 	if (!try_get_task_stack(task))
530 		return -EFAULT;
531 
532 	regs = task_pt_regs(task);
533 	res = __bpf_get_stack(regs, task, NULL, buf, size, flags);
534 	put_task_stack(task);
535 
536 	return res;
537 }
538 
539 const struct bpf_func_proto bpf_get_task_stack_proto = {
540 	.func		= bpf_get_task_stack,
541 	.gpl_only	= false,
542 	.ret_type	= RET_INTEGER,
543 	.arg1_type	= ARG_PTR_TO_BTF_ID,
544 	.arg1_btf_id	= &btf_task_struct_ids[0],
545 	.arg2_type	= ARG_PTR_TO_UNINIT_MEM,
546 	.arg3_type	= ARG_CONST_SIZE_OR_ZERO,
547 	.arg4_type	= ARG_ANYTHING,
548 };
549 
550 BPF_CALL_4(bpf_get_stack_pe, struct bpf_perf_event_data_kern *, ctx,
551 	   void *, buf, u32, size, u64, flags)
552 {
553 	struct pt_regs *regs = (struct pt_regs *)(ctx->regs);
554 	struct perf_event *event = ctx->event;
555 	struct perf_callchain_entry *trace;
556 	bool kernel, user;
557 	int err = -EINVAL;
558 	__u64 nr_kernel;
559 
560 	if (!(event->attr.sample_type & __PERF_SAMPLE_CALLCHAIN_EARLY))
561 		return __bpf_get_stack(regs, NULL, NULL, buf, size, flags);
562 
563 	if (unlikely(flags & ~(BPF_F_SKIP_FIELD_MASK | BPF_F_USER_STACK |
564 			       BPF_F_USER_BUILD_ID)))
565 		goto clear;
566 
567 	user = flags & BPF_F_USER_STACK;
568 	kernel = !user;
569 
570 	err = -EFAULT;
571 	trace = ctx->data->callchain;
572 	if (unlikely(!trace))
573 		goto clear;
574 
575 	nr_kernel = count_kernel_ip(trace);
576 
577 	if (kernel) {
578 		__u64 nr = trace->nr;
579 
580 		trace->nr = nr_kernel;
581 		err = __bpf_get_stack(regs, NULL, trace, buf, size, flags);
582 
583 		/* restore nr */
584 		trace->nr = nr;
585 	} else { /* user */
586 		u64 skip = flags & BPF_F_SKIP_FIELD_MASK;
587 
588 		skip += nr_kernel;
589 		if (skip > BPF_F_SKIP_FIELD_MASK)
590 			goto clear;
591 
592 		flags = (flags & ~BPF_F_SKIP_FIELD_MASK) | skip;
593 		err = __bpf_get_stack(regs, NULL, trace, buf, size, flags);
594 	}
595 	return err;
596 
597 clear:
598 	memset(buf, 0, size);
599 	return err;
600 
601 }
602 
603 const struct bpf_func_proto bpf_get_stack_proto_pe = {
604 	.func		= bpf_get_stack_pe,
605 	.gpl_only	= true,
606 	.ret_type	= RET_INTEGER,
607 	.arg1_type	= ARG_PTR_TO_CTX,
608 	.arg2_type	= ARG_PTR_TO_UNINIT_MEM,
609 	.arg3_type	= ARG_CONST_SIZE_OR_ZERO,
610 	.arg4_type	= ARG_ANYTHING,
611 };
612 
613 /* Called from eBPF program */
614 static void *stack_map_lookup_elem(struct bpf_map *map, void *key)
615 {
616 	return ERR_PTR(-EOPNOTSUPP);
617 }
618 
619 /* Called from syscall */
620 int bpf_stackmap_copy(struct bpf_map *map, void *key, void *value)
621 {
622 	struct bpf_stack_map *smap = container_of(map, struct bpf_stack_map, map);
623 	struct stack_map_bucket *bucket, *old_bucket;
624 	u32 id = *(u32 *)key, trace_len;
625 
626 	if (unlikely(id >= smap->n_buckets))
627 		return -ENOENT;
628 
629 	bucket = xchg(&smap->buckets[id], NULL);
630 	if (!bucket)
631 		return -ENOENT;
632 
633 	trace_len = bucket->nr * stack_map_data_size(map);
634 	memcpy(value, bucket->data, trace_len);
635 	memset(value + trace_len, 0, map->value_size - trace_len);
636 
637 	old_bucket = xchg(&smap->buckets[id], bucket);
638 	if (old_bucket)
639 		pcpu_freelist_push(&smap->freelist, &old_bucket->fnode);
640 	return 0;
641 }
642 
643 static int stack_map_get_next_key(struct bpf_map *map, void *key,
644 				  void *next_key)
645 {
646 	struct bpf_stack_map *smap = container_of(map,
647 						  struct bpf_stack_map, map);
648 	u32 id;
649 
650 	WARN_ON_ONCE(!rcu_read_lock_held());
651 
652 	if (!key) {
653 		id = 0;
654 	} else {
655 		id = *(u32 *)key;
656 		if (id >= smap->n_buckets || !smap->buckets[id])
657 			id = 0;
658 		else
659 			id++;
660 	}
661 
662 	while (id < smap->n_buckets && !smap->buckets[id])
663 		id++;
664 
665 	if (id >= smap->n_buckets)
666 		return -ENOENT;
667 
668 	*(u32 *)next_key = id;
669 	return 0;
670 }
671 
672 static int stack_map_update_elem(struct bpf_map *map, void *key, void *value,
673 				 u64 map_flags)
674 {
675 	return -EINVAL;
676 }
677 
678 /* Called from syscall or from eBPF program */
679 static int stack_map_delete_elem(struct bpf_map *map, void *key)
680 {
681 	struct bpf_stack_map *smap = container_of(map, struct bpf_stack_map, map);
682 	struct stack_map_bucket *old_bucket;
683 	u32 id = *(u32 *)key;
684 
685 	if (unlikely(id >= smap->n_buckets))
686 		return -E2BIG;
687 
688 	old_bucket = xchg(&smap->buckets[id], NULL);
689 	if (old_bucket) {
690 		pcpu_freelist_push(&smap->freelist, &old_bucket->fnode);
691 		return 0;
692 	} else {
693 		return -ENOENT;
694 	}
695 }
696 
697 /* Called when map->refcnt goes to zero, either from workqueue or from syscall */
698 static void stack_map_free(struct bpf_map *map)
699 {
700 	struct bpf_stack_map *smap = container_of(map, struct bpf_stack_map, map);
701 
702 	bpf_map_area_free(smap->elems);
703 	pcpu_freelist_destroy(&smap->freelist);
704 	bpf_map_area_free(smap);
705 	put_callchain_buffers();
706 }
707 
708 static int stack_trace_map_btf_id;
709 const struct bpf_map_ops stack_trace_map_ops = {
710 	.map_meta_equal = bpf_map_meta_equal,
711 	.map_alloc = stack_map_alloc,
712 	.map_free = stack_map_free,
713 	.map_get_next_key = stack_map_get_next_key,
714 	.map_lookup_elem = stack_map_lookup_elem,
715 	.map_update_elem = stack_map_update_elem,
716 	.map_delete_elem = stack_map_delete_elem,
717 	.map_check_btf = map_check_no_btf,
718 	.map_btf_name = "bpf_stack_map",
719 	.map_btf_id = &stack_trace_map_btf_id,
720 };
721 
722 static int __init stack_map_init(void)
723 {
724 	int cpu;
725 	struct stack_map_irq_work *work;
726 
727 	for_each_possible_cpu(cpu) {
728 		work = per_cpu_ptr(&up_read_work, cpu);
729 		init_irq_work(&work->irq_work, do_up_read);
730 	}
731 	return 0;
732 }
733 subsys_initcall(stack_map_init);
734