westfw,
Here is an example that shows why the ARM CM3 architecture is very RTOS friendly. The example is a bit long. I will use the internals of ChibiOS to illustrate.
The context for the ARM Cortex M3 is divided into two parts. ChibiOS refers to the first part as the Interrupt saved context. This part of stack frame is eight 32-bit words and is saved by the NVIC, Nested Vectored Interrupt Controller, when an interrupt occurs.
Here is the structure in ChibiOS:
struct extctx {
regarm_t r0;
regarm_t r1;
regarm_t r2;
regarm_t r3;
regarm_t r12;
regarm_t lr_thd;
regarm_t pc;
regarm_t xpsr;
};
The remainder of the context can be saved by a single instruction if a context switch is required. Here is the structure for that part of the stack frame in ChibiOS:
struct intctx {
regarm_t r4;
regarm_t r5;
regarm_t r6;
regarm_t r7;
regarm_t r8;
regarm_t r9;
regarm_t r10;
regarm_t r11;
regarm_t lr;
};
Here is the context switch function that is called by ChibiOS at the ISR level if a context switch is required.
#define PUSH_CONTEXT() { \
asm volatile ("push {r4, r5, r6, r7, r8, r9, r10, r11, lr}" \
: : : "memory"); \
}
#define POP_CONTEXT() { \
asm volatile ("pop {r4, r5, r6, r7, r8, r9, r10, r11, pc}" \
: : : "memory"); \
}
__attribute__((naked))
void port_switch(Thread *ntp, Thread *otp) {
PUSH_CONTEXT();
asm volatile ("str sp, [%1, #12] \n\t"
"ldr sp, [%0, #12]" : : "r" (ntp), "r" (otp));
POP_CONTEXT();
}
When you write an ISR you decide if an event has happened that requires a task to be triggered. In a USART handler this could be an end of message character. If you have not received this character there is no overhead.
If you receive the end of message character, you call a ChibiOS routine and it checks if a context switch is required and does the above stack switch if necessary. When you return from interrupt the rest of the context switch will occur in the NVIC.
On a 72 MHz STM32 the overhead for this call with a context switch is about 2 microseconds. Most of this time is in determining which task should run, not the context switch.
I have made this as simple as possible so I am sure you will have a "but what if?".