xref: /linux/arch/loongarch/kernel/stacktrace.c (revision ef5b28372c565128bdce7a59bc78402a8ce68e1b)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Stack trace management functions
4  *
5  * Copyright (C) 2022 Loongson Technology Corporation Limited
6  */
7 #include <linux/sched.h>
8 #include <linux/stacktrace.h>
9 #include <linux/uaccess.h>
10 
11 #include <asm/stacktrace.h>
12 #include <asm/unwind.h>
13 
14 void arch_stack_walk(stack_trace_consume_fn consume_entry, void *cookie,
15 		     struct task_struct *task, struct pt_regs *regs)
16 {
17 	unsigned long addr;
18 	struct pt_regs dummyregs;
19 	struct unwind_state state;
20 
21 	if (!regs) {
22 		regs = &dummyregs;
23 
24 		if (task == current) {
25 			regs->regs[3] = (unsigned long)__builtin_frame_address(0);
26 			regs->csr_era = (unsigned long)__builtin_return_address(0);
27 		} else {
28 			regs->regs[3] = thread_saved_fp(task);
29 			regs->csr_era = thread_saved_ra(task);
30 		}
31 		regs->regs[1] = 0;
32 	}
33 
34 	for (unwind_start(&state, task, regs);
35 	     !unwind_done(&state); unwind_next_frame(&state)) {
36 		addr = unwind_get_return_address(&state);
37 		if (!addr || !consume_entry(cookie, addr))
38 			break;
39 	}
40 }
41 
42 static int
43 copy_stack_frame(unsigned long fp, struct stack_frame *frame)
44 {
45 	int ret = 1;
46 	unsigned long err;
47 	unsigned long __user *user_frame_tail;
48 
49 	user_frame_tail = (unsigned long *)(fp - sizeof(struct stack_frame));
50 	if (!access_ok(user_frame_tail, sizeof(*frame)))
51 		return 0;
52 
53 	pagefault_disable();
54 	err = (__copy_from_user_inatomic(frame, user_frame_tail, sizeof(*frame)));
55 	if (err || (unsigned long)user_frame_tail >= frame->fp)
56 		ret = 0;
57 	pagefault_enable();
58 
59 	return ret;
60 }
61 
62 void arch_stack_walk_user(stack_trace_consume_fn consume_entry, void *cookie,
63 			  const struct pt_regs *regs)
64 {
65 	unsigned long fp = regs->regs[22];
66 
67 	while (fp && !((unsigned long)fp & 0xf)) {
68 		struct stack_frame frame;
69 
70 		frame.fp = 0;
71 		frame.ra = 0;
72 		if (!copy_stack_frame(fp, &frame))
73 			break;
74 		if (!frame.ra)
75 			break;
76 		if (!consume_entry(cookie, frame.ra))
77 			break;
78 		fp = frame.fp;
79 	}
80 }
81