Switching stacks in C requires inline assembly inside a naked function
and even then, the compiler is free to keep using the old stack pointer.

Let's add call_with_stack() instead, which takes the new stack top, a
function and two arguments for it. Everything is passed in registers, so
it's safe to call before a stack has been set up, as the upcoming PBL
stage dispatch will do.

The prototype goes into asm-generic/registers.h, as other architectures
will implement the same helper.

Assisted-by: Claude:fable-5
Signed-off-by: Ahmad Fatoum <[email protected]>
---
 arch/riscv/lib/Makefile          |  1 +
 arch/riscv/lib/call_with_stack.S | 12 ++++++++++++
 include/asm-generic/registers.h  | 10 ++++++++++
 3 files changed, 23 insertions(+)
 create mode 100644 arch/riscv/lib/call_with_stack.S

diff --git a/arch/riscv/lib/Makefile b/arch/riscv/lib/Makefile
index 693248080070..13c7c34a487c 100644
--- a/arch/riscv/lib/Makefile
+++ b/arch/riscv/lib/Makefile
@@ -4,6 +4,7 @@ extra-y += barebox.lds
 
 obj-y += dtb.o
 obj-pbl-y += sections.o setupc.o reloc.o sections.o runtime-offset.o
+obj-pbl-y += call_with_stack.o
 obj-$(CONFIG_ARCH_HAS_SJLJ) += setjmp.o longjmp.o
 obj-$(CONFIG_RISCV_OPTIMZED_STRING_FUNCTIONS) += memcpy.o memset.o memmove.o
 obj-$(CONFIG_RISCV_SBI) += sbi.o
diff --git a/arch/riscv/lib/call_with_stack.S b/arch/riscv/lib/call_with_stack.S
new file mode 100644
index 000000000000..f3093d062a59
--- /dev/null
+++ b/arch/riscv/lib/call_with_stack.S
@@ -0,0 +1,12 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+
+#include <linux/linkage.h>
+
+.section .text.call_with_stack
+ENTRY(call_with_stack)
+       mv      t1, a1
+       mv      sp, a0
+       mv      a0, a2
+       mv      a1, a3
+       jr      t1
+ENDPROC(call_with_stack)
diff --git a/include/asm-generic/registers.h b/include/asm-generic/registers.h
index 8ce28f74e1db..ec85476019c7 100644
--- a/include/asm-generic/registers.h
+++ b/include/asm-generic/registers.h
@@ -20,4 +20,14 @@ static __always_inline bool pc_inside(unsigned long start, 
unsigned long size)
        return pc - start < size;
 }
 
+/*
+ * call_with_stack - switch to the stack ending at stack_top and call fn
+ *
+ * stack_top must be aligned as the architecture requires and fn must not
+ * return. No memory is accessed, so there needn't be a stack yet.
+ */
+void __noreturn call_with_stack(unsigned long stack_top,
+                               void (*fn)(unsigned long, unsigned long),
+                               unsigned long arg0, unsigned long arg1);
+
 #endif
-- 
2.47.3


Reply via email to