Stack reuse in GD32VF103 multi-tasking applications[Copy link]
When developing applications using FreeRTOS, after the multi-task scheduler is started, since each task has its own stack space, the C startup stack is no longer used, reducing the amount of RAM available in embedded applications.
How to reuse this RAM space?
Reuse of stack space requires taking advantage of processor and IDE features.
GD32VF103 is a general-purpose MCU based on the Bumblebee RISC-V core. The RISC-V core provides a temporary register mscratch, which can be used by programs running in machine mode to temporarily save data. The mscratch register provides a save and restore mechanism. For example, after entering the interrupt handler, the value of the user stack pointer SP is temporarily stored in the register mscratch; before exiting the exception handler, the value in the mscratch register is restored to the user stack pointer register.
The RISC-V kernel also provides the mscratchcswl register, which is used to exchange the value of the destination register with mscratch when switching between multiple interrupt levels to speed up interrupt processing and separate the interrupt handler from the stack space of the application task.
For SEGGER's Embedded Studio for RISC-V toolchain (SES), the initial stack storage space is stack. The size of the stack can be configured through the project options as shown below:
The default stack size is 1KB, which is sufficient for typical startup code. If your startup code requires more (or less) stack space, you can simply change its value to suit your application needs.
FreeRTOS does not provide an independent ISR stack. We can use the hardware features of GD32 to use the stack as an independent interrupt stack, isolate the task stack and interrupt stack, reduce the stack space configuration of each task, and avoid wasting RAM resources.
The specific implementation process is as follows:
In the FreeRTOS porting file portasm.S, when starting the first task of the system, the address of the stack is written to the mscratch register and used as the interrupt stack.
After entering the interrupt handler, adding a mscratchcswl at the interrupt program entry can switch the stack from the task stack to the independent interrupt stack space.
csrrw sp, CSR_MSCRATCHCSWL, sp
Add an mscratchcswl instruction at the exit of the interrupt program to switch the stack to the task stack space.
csrrw sp, CSR_MSCRATCHCSWL, sp
Through RISC-V's special CSR register, we can separate the stack space of the interrupt handler and the application, improve the robustness of the code, and avoid wasting RAM space.