Thread context switching – Comtrol eCos User Manual
Page 283
Chapter 9. HAL Interfaces
arg
A value that is passed as the first argument to the entry point function.
entry
The address of an entry point function. This will be called according the C calling conventions, and the value
of
arg
will be passed as the first argument. This function should have the following type signature
void
entry(CYG_ADDRWORD arg)
.
id
A thread id value. This is only used for debugging purposes, it is ORed into the initialization pattern for
unused registers and may be used to help identify the thread from its register dump. The least significant 16
bits of this value should be zero to allow space for a register identifier.
Thread Context Switching
HAL_THREAD_LOAD_CONTEXT( to )
HAL_THREAD_SWITCH_CONTEXT( from, to )
These macros implement the thread switch code. The arguments are:
from
A pointer to a location where the stack pointer of the current thread will be stored.
to
A pointer to a location from where the stack pointer of the next thread will be read.
For
HAL_THREAD_LOAD_CONTEXT()
the current CPU state is discarded and the state of the destination thread is
loaded. This is only used once, to load the first thread when the scheduler is started.
For
HAL_THREAD_SWITCH_CONTEXT()
the state of the current thread is saved onto its stack, using the current value
of the stack pointer, and the address of the saved state placed in
*from
. The value in
*to
is then read and the
state of the new thread is loaded from it.
While these two operations may be implemented with inline assembler, they are normally implemented as calls
to assembly code functions in the HAL. There are two advantages to doing it this way. First, the return link of
the call provides a convenient PC value to be used in the saved context. Second, the calling conventions mean
that the compiler will have already saved the caller-saved registers before the call, so the HAL need only save the
callee-saved registers.
The implementation of
HAL_THREAD_SWITCH_CONTEXT()
saves the current CPU state on the stack, including the
current interrupt state (or at least the register that contains it). For debugging purposes it is useful to save the entire
register set, but for performance only the ABI-defined callee-saved registers need be saved. If it is implemented,
the option
CYGDBG_HAL_COMMON_CONTEXT_SAVE_MINIMUM
controls how many registers are saved.
The implementation of
HAL_THREAD_LOAD_CONTEXT()
loads a thread context, destroying the current context.
With a little care this can be implemented by sharing code with
HAL_THREAD_SWITCH_CONTEXT()
. To load a
thread context simply requires the saved registers to be restored from the stack and a jump or return made back to
the saved PC.
179