RTOS on ARM: Ports, System Ticks, and Context Switching
What You'll Learn
- 1Explain the Cortex-M context switch sequence
- 2Map RTOS task priorities onto NVIC priorities
- 3Implement critical sections with the priority mask
- 4Diagnose stack overflow and scheduling faults
Real time operating system ports for Cortex-M lean almost entirely on the architecture exception model, which is why they are compact and portable. SysTick provides the time slice, PendSV provides a deferred, lowest priority context switch, and the priority mask register provides the critical section. Tasks are just stacks with a saved register context at the top, and switching means letting the exception entry and exit machinery restore the next task. Understanding this machinery removes most of the mystery from RTOS debugging.
PendSV and the Switch Sequence
PendSV is a pendable exception that is almost always configured at the lowest priority so it runs only when nothing else needs the core. When a switch is required, software pends it, and on entry the handler saves the callee saved registers and the link register onto the current task stack, records the stack pointer in the task control block, then loads the next task stack pointer and restores its registers. Returning from the handler restores the next task as if it had been interrupted.
The special exception return value carried in the link register tells the hardware which stack to use and whether floating point state is present. Because the switch happens inside exception exit, no task ever directly manipulates another task context, which keeps the design small and hard to get wrong.
SysTick and Time Slicing
The RTOS ticks SysTick at a fixed rate, typically one hundred or one thousand hertz, and the handler increments a tick count, decrements the time slice of the running task, and pends PendSV when the slice expires. The tick also drives timeouts, software timers, and delayed reads. Tickless idle stops the periodic interrupt during long sleeps and reprograms the timer for the next deadline, which is how an RTOS stays usable on battery.
The tick rate is a trade-off: a higher rate gives finer timeouts and faster response but raises the background interrupt load, since the handler runs at every tick regardless of what the system is doing.
Priorities, Masking, and Faults
RTOS task priorities are software constructs and are completely separate from NVIC hardware priorities, but the two interact through the priority mask. Raising the mask above the highest interrupt priority creates a critical section that both task switching and interrupt handlers respect, and masking only up to a chosen level lets high rate control interrupts keep running while a kernel structure is touched. SysTick and PendSV are kept below all application interrupts for exactly this reason.
The most common failures are stack overflow and a critical section held too long. Stack canaries and a margin check at the tick catch the first, and cycle counting around kernel calls catches the second. When a fault occurs, the stacked registers and the fault status registers name the task and the instruction that failed.
RTOS Port Building Blocks
| Element | ARM Mechanism | Role |
|---|---|---|
| Time base | SysTick | Ticks, timeouts, and time slices |
| Context switch | PendSV at lowest priority | Deferred task restore and save |
| Critical section | Priority mask register | Blocks interrupts up to a level |
| Task stack | Process stack pointer | Holds saved registers and locals |
| Kernel service call | Supervisor call exception | Traps into privileged kernel code |
| Fault handling | Hard and memory management faults | Names the failing task and instruction |
Real-World Examples
- Trace a context switch â The tick handler pends PendSV, the handler saves r4 to r11 and the link register, then swaps stack pointers and returns into the next task.
- Build a mask based critical section â Raise the priority mask above kernel priorities, touch the list, then restore the previous mask value atomically.
- Keep control interrupts free â Map PendSV and SysTick to the lowest priority so the current control interrupt always preempts them.
- Find a stack overflow â Enable the stack limit check or a canary pattern and inspect the task stack high water mark from the tick.
đTask Priorities Are Not Interrupt Priorities
Common Mistakes
Doing critical sections by disabling interrupts globally
Fix: Use the priority mask so high rate control interrupts can still run while kernel data is protected.
Calling kernel functions from an interrupt at the wrong priority
Fix: Kernel calls from interrupts require the interrupt priority to be compatible with the masking scheme.
Ignoring stack overflow checks
Fix: Overflow corrupts the adjacent task silently and shows up as unrelated data corruption much later.
Key Takeaways
- PendSV performs the switch during exception exit for portability and safety.
- SysTick drives time slices, timeouts, and tickless idle.
- The priority mask builds critical sections that cooperate with the NVIC.
- Task priorities and interrupt priorities are separate domains that must be mapped deliberately.
Frequently Asked Questions
Why is PendSV used instead of switching in SysTick?
Deferring the switch to the lowest priority lets any pending interrupt complete first and keeps the switch out of the tick handler.
Does an RTOS make hard real time guarantees?
It gives bounded, analyzable latency only when priorities and masking are configured with worst case analysis in mind.
How much RAM does a task cost?
Each task needs its own stack, typically from a few hundred bytes to a few kilobytes, plus a small task control block.
Interview Questions
Q1: Walk through a Cortex-M RTOS context switch.
The tick pends PendSV, the handler pushes r4 to r11 and the link register on the current stack, saves the stack pointer in the task control block, loads the next task stack pointer, pops its registers, and returns using the exception return value.
Q2: How do you protect kernel data structures?
Raise the priority mask to a level above kernel work but below critical application interrupts, modify the structure, then restore the mask in one step.
Extended Learning: Beyond the Basics
Key Concepts Summary
This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.
Prerequisite Knowledge
Before studying this topic in depth, ensure you understand:
- Basic definitions and terminology
- Core formulas and their derivations
- Common applications in real-world scenarios
- Typical pitfalls and misconceptions
Step-by-Step Walkthrough
Let us work through a complete example to solidify understanding:
Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.
Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.
Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.
Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.
Common Mistakes to Avoid
- Misidentifying the problem type â Always start by categorizing the problem
- Incorrect formula application â Verify the formula applies to your specific case
- Unit errors â Always check units are consistent throughout
- Sign errors â Pay careful attention to positive and negative values
- Rounding too early â Keep full precision until the final answer
- Forgetting constraints â Check that solutions satisfy all given conditions
Real-World Applications
Understanding this concept is essential for:
- Advanced problem solving in examinations
- Building intuition for more complex topics
- Developing analytical thinking skills
- Applying mathematical reasoning to practical situations
Practice Exercises
- Basic: Solve 5 problems of increasing difficulty using the core concept.
- Intermediate: Apply the concept to word problems with multiple steps.
- Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
- Challenge: Create your own problem that requires this concept plus additional knowledge.
Interview and Exam Tips
- Common question patterns: Identify which exam or interview formats test this topic
- Time management: Practice completing problems within time constraints
- Common traps: Know the typical mistakes examiners set as distractors
- Verification strategy: Develop a quick method to check your answer
Related Topics
- Previous Topic â Build on the foundation laid here
- Next Topic â See how this concept extends to more advanced material
- Practice Problems â Additional exercises with solutions
- Video Explanation â Visual walkthrough of key concepts
Quick Reference Card
| Concept | Formula/Rule | Key Insight | Common Use |
|---|---|---|---|
| Core Definition | See main text | Understand the intuition | Foundation for all applications |
| Key Formula | See main text | Memorize the derivation | Direct problem solving |
| Special Case | See main text | Recognize when it applies | Simplifies complex problems |
| Edge Case | See main text | Know the limitations | Avoids errors |
Further Reading
For students who want to go deeper:
- Standard textbooks on the subject
- Research papers applying this concept
- Online courses with video explanations
- Practice problem collections with detailed solutions