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