Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Asynchronous vs. Synchronous Context Switches

Two Types of Context Switches

There are really two different kinds of context switches. I refer to them as synchronous and asynchronous context switches (but there might be better names):

...

  • A synchronous context switch in my terminology occurs when a task explicitly suspends itself by calling some OS interface that causes the task to block, such as usleep().

Synchronous Context Switches

There are two ways to implement a synchronous context switch:

up_savecontext() and up_fullcontextrestore()

You can implement the moral equivalent of setjmp() and longjmp() on steroids. Some architectures have a function called up_savecontext() that is the moral equivalent of setjmp(); it saves the current state of the task (and like setjmp() returns 0 or 1 to indicate if the context is being restored. Another function up_fullcontextrestore() is like longjmp(); it restores the context saved by either the interrupt handler during a previous asynchronous context switch or by up_savecontext().

...

The are a couple of downsides to the this approach: First, the up_savecontext() and up_fullcontextrestore() functions are tricky to write. And second, they have limited usage. They can be used only in the FLAT build mode where all tasks are running with the same privileges. If you were to try to do up_fullcontextrestore() to get from an unprivileged task to a privileged task, you would get an
access violation exception of some sort.

System Calls

In order to the limitations of up_savecontext() and
up_fullcontextrestore(), you have to do something a little differently. One way is to use a system call (a software interrupt, a trap in x86 or an SVCALL in ARM land). This generates a software interrupt and uses the mechanization of the asynchronous context switch: The software interrupt
saves the context of the old task on entry (replacing the functionality of up_savecontext()) and restores the new task context on return (replacing the functionality of up_fullcontextrestore()). The tiny software interrupt handler just sets up the context switch.

...