freeRTOS: Why so much memory as StackDepth (for xTaskCreate) is needed?

1.2k views Asked by At

xTaskCreate has 3rd argument const uint16_t usStackDepth. It is the number of words to allocate for use as the task's stack.

In my case configMINIMAL_STACK_SIZE is 1024 words, and it is lots of memory. Nevertheless it is minimum: it isn't enough to start a task and allocate anything inside; it looks like the main reason for using as little tasks as its possible.

Why so much memory is needed? What is it used for? Can I reduce it?

2

There are 2 answers

1
Clifford On

In FreeRTOS configMINIMAL_STACK_SIZE is the stack size used by the idle task and the recommended minimum size for any task. This recommended size is architecture dependent. In addition to the thread-context storage, which is dependent on the number of registers on the processor, potentially including FPU registers is an FPU is present.

On some architectures the interrupt context shares the stack of the interrupted thread, so necessarily every thread must allow allow for the interrupt stack requirement. If interrupts are nestable, that will be the worst-case for all ISRs, not just the single worst ISR. Architectures with a dedicated interrupt stack do not need to include ISR usage on every task.

STM32 which is an ARM Cortex-M device does have a dedicated ISR stack; in which case I would suggest that 1024 words (4kbytes) is excessively large for the minimum stack. I believe that in the standard demonstration port for STM32 it is set to 128. The FAQ suggests that the minimum user stack size should be the same as the value of configMINIMAL_STACK_SIZE set in the demoonstration port for the particular target; it does not say that it should be configMINIMAL_STACK_SIZE whose value may have been changed for example to accommodate user hooks to the idle task.

1
Richard On

You provide so little information in your question that it is not really possible to answer as it depends on the port you are using, where you got the code from, who set configMINIMAL_STACK_SIZE to 1024 and why, etc. etc.

The ONLY place configMINIMAL_STACK_SIZE is used by FreeRTOS itself is to dimension the stack used by the Idle task. It is used by some demo application code too, to make sure the demos are portable across architectures, by they are nothing to do with FreeRTOS itself, just usage examples.

Unless you are using an Idle hook function, and that idle hook function is doing something that requires a lot of stack, then it would be normal to set configMINIMAL_STACK_SIZE to somewhere between 70 and 90 on a Cortex-M microcontroller such as an STM32.