Skip to content

Commit bec9d50

Browse files
committed
Add per-hart stack allocation in RISC-V boot for SMP support
To support SMP, allocate separate stack memory regions for each hart during boot. This patch modifies the assembly entry code in arch/riscv/boot.c to compute the initial stack pointer based on the hart ID, ensuring each hart uses a distinct stack area of fixed size (STACK_SIZE_PER_HART). This enables multiple harts to safely run concurrently without stack collisions during early boot stages.
1 parent bd65251 commit bec9d50

File tree

1 file changed

+9
-1
lines changed

1 file changed

+9
-1
lines changed

arch/riscv/boot.c

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@
1414
extern uint32_t _gp, _stack, _end;
1515
extern uint32_t _sbss, _ebss;
1616

17+
#define STACK_SIZE_PER_HART 524288
18+
1719
/* C entry points */
1820
void main(void);
1921
void do_trap(uint32_t cause, uint32_t epc);
@@ -29,6 +31,12 @@ __attribute__((naked, section(".text.prologue"))) void _entry(void)
2931
/* Initialize Global Pointer (gp) and Stack Pointer (sp). */
3032
"la gp, _gp\n"
3133
"la sp, _stack\n"
34+
/* Set up stack for each hart */
35+
"csrr t0, mhartid\n" /* t0 = hartid */
36+
"la t1, _stack_top\n" /* t1 = base address of full stack region (top) */
37+
"li t2, %2\n" /* t2 = per-hart stack size */
38+
"mul t0, t0, t2\n" /* t0 = hartid * STACK_SIZE_PER_HART */
39+
"sub sp, t1, t0\n" /* sp = _stack_top - hartid * stack_size */
3240

3341
/* Initialize Thread Pointer (tp). The ABI requires tp to point to
3442
* a 64-byte aligned memory region for thread-local storage. Here, we
@@ -89,7 +97,7 @@ __attribute__((naked, section(".text.prologue"))) void _entry(void)
8997
"j .Lpark_hart\n"
9098

9199
: /* no outputs */
92-
: "i"(MSTATUS_MPP_MACH), "i"(MIE_MEIE)
100+
: "i"(MSTATUS_MPP_MACH), "i"(MIE_MEIE), "i"(STACK_SIZE_PER_HART)
93101
: "memory");
94102
}
95103

0 commit comments

Comments
 (0)