<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Madhav Saraswat  on Medium]]></title>
        <description><![CDATA[Stories by Madhav Saraswat  on Medium]]></description>
        <link>https://medium.com/@madhavsaraswat28?source=rss-14b2893c3dbc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*0PJrs87L8uAtc098q-STWw.jpeg</url>
            <title>Stories by Madhav Saraswat  on Medium</title>
            <link>https://medium.com/@madhavsaraswat28?source=rss-14b2893c3dbc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 21:13:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@madhavsaraswat28/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How an RTOS cheats the CPU !!]]></title>
            <link>https://medium.com/@madhavsaraswat28/how-an-rtos-cheats-the-cpu-c082b7c8e12e?source=rss-14b2893c3dbc------2</link>
            <guid isPermaLink="false">https://medium.com/p/c082b7c8e12e</guid>
            <category><![CDATA[embedded-systems]]></category>
            <category><![CDATA[tor]]></category>
            <category><![CDATA[context-switching]]></category>
            <category><![CDATA[operating-systems]]></category>
            <category><![CDATA[freertos]]></category>
            <dc:creator><![CDATA[Madhav Saraswat ]]></dc:creator>
            <pubDate>Mon, 29 Jun 2026 21:02:22 GMT</pubDate>
            <atom:updated>2026-06-29T21:02:22.012Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mgLHsqG4ZwBlabRxRN7ZnA.png" /></figure><p>When I first started reading RTOS code, one thing kept bothering me. I understood how tasks switch between each other. A task runs, an interrupt happens, the CPU saves its state, the scheduler picks another task, and execution continues.</p><p>That all made sense. But then I had a simple question : <strong>How does the very first task start?</strong></p><p>There is no previous task … there is no context to restore.Nobody has ever called the task function.</p><p>So how does the CPU suddenly start executing:</p><pre>worker_task();</pre><p>without anyone ever directly calling :</p><pre>worker_task();</pre><p>The answer is both clever and slightly evil:</p><p><strong>We cheat the CPU.</strong></p><h3>The Problem</h3><p>Suppose we create a task:</p><pre>void worker_task(void *arg)<br>{<br>    while (1)<br>    {<br>        // do work<br>    }<br>}</pre><p>At some point, the scheduler decides:</p><blockquote><em>“Okay, this task should run now.”</em></blockquote><p>But how?</p><p>The CPU can’t magically jump into the middle of nowhere. Normally, a function starts because someone calls it:</p><pre>worker_task();</pre><p>But an RTOS doesn’t do that. Instead, it <strong>tricks </strong>the processor into believing:</p><blockquote><em>“This task was running before and got interrupted.”</em></blockquote><p>Even though it never existed.</p><h3>How Cortex-M Restores a Task</h3><p>Whenever an exception happens on Cortex-M (SysTick, PendSV, SVC, etc.), the CPU automatically saves:</p><p><em>R0</em></p><p><em>R1</em></p><p><em>R2</em></p><p><em>R3</em></p><p><em>R12</em></p><p><em>LR</em></p><p><em>PC</em></p><p><em>xPSR</em></p><p>onto the current stack.</p><p>This is called the <strong>hardware exception frame</strong>. Later, when the exception returns, the CPU restores these registers automatically. This means the processor already knows how to do one thing extremely well:</p><blockquote><em>Restore a task that was interrupted.</em></blockquote><p>So the RTOS asks:</p><blockquote><em>Why not pretend that our brand-new task was interrupted earlier?</em></blockquote><h3>Building a Fake Context</h3><p>Before the scheduler ever runs a task, it manually creates this on the task’s stack:</p><pre>xPSR<br>PC   = worker_task<br>LR<br>R12<br>R3<br>R2<br>R1<br>R0   = task argument</pre><p>Then it also places:</p><pre>R11<br>R10<br>R9<br>R8<br>R7<br>R6<br>R5<br>R4</pre><p>below it.</p><p>The entire stack now looks exactly like a task that was interrupted in the past. Except it wasn’t.</p><p>We completely made it up.</p><h3>Enter SVC</h3><p>Inside SVC_Handler, we do something very interesting:</p><pre>LDR     r3, =os_current<br>LDR     r1, [r3]<br>LDR     r0, [r1, #0]<br>LDMIA   r0!, {r4-r11}<br>MSR     psp, r0<br>MOV     r0, #2<br>MSR     control, r0<br>MVN     lr, #2<br>BX      lr</pre><p>At first glance this looks scary.</p><p>But in reality it’s just:</p><ol><li><em>Find the current task.</em></li><li><em>Get its saved stack pointer.</em></li><li><em>Restore R4-R11.</em></li><li><em>Point PSP at the fake hardware frame.</em></li><li><em>Tell the CPU to use PSP.</em></li><li><em>Perform an exception return.</em></li></ol><p>The magic happens here:</p><pre>BX lr</pre><p>with:</p><pre>lr = 0xFFFFFFFD</pre><p>This special value means:</p><blockquote><em>Return from exception using PSP.</em></blockquote><p>The CPU then automatically restores:</p><pre>R0<br>R1<br>R2<br>R3<br>R12<br>LR<br>PC<br>xPSR</pre><p>from the stack.</p><p>And here’s the trick:</p><p>The value we placed in the fake PC slot was:</p><pre>PC = worker_task</pre><p>So the CPU happily restores it and jumps into:</p><pre>worker_task();</pre><p>completely believing that it’s resuming an old task.</p><h3>The CPU Has Been Fooled</h3><p>From the processor’s perspective:</p><pre>Task was running<br>↓<br>Exception happened<br>↓<br>Now resume it</pre><p>Reality:</p><pre>Task never existed<br>↓<br>RTOS built a fake stack frame<br>↓<br>CPU was tricked into restoring it</pre><p>The task starts executing, completely unaware that it never actually existed before.</p><h3>Why This Is So Beautiful</h3><p>I think this is one of the most elegant ideas in embedded systems.</p><p>The processor already had all the machinery necessary to restore an interrupted task.</p><p>The RTOS simply reuses that machinery.</p><p>Instead of inventing a special way to start tasks, it :</p><p><em>“Just creates a fake interrupted task and let the CPU do what it already knows.”</em></p><p>No special startup mechanism , no complicated boot sequence. Just a carefully crafted lie.</p><h3>The Best Part</h3><p>After this first task starts, every future context switch works exactly the same way.</p><p>The only difference is:</p><ul><li>Later context switches restore a <strong>real</strong> saved context.</li><li>The first task restores a <strong>fake</strong> saved context.</li></ul><p>The CPU doesn’t know the difference.</p><p>And honestly… that’s kind of beautiful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c082b7c8e12e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>