CTXSW(9)

NAME
mi_switch, cpu_switch, cpu_switchto - switch to another light weight process

SYNOPSIS
int
mi_switch(struct lwp *cur, struct lwp *newl);
int
cpu_switch(struct lwp *cur, struct lwp *newl);
int
cpu_switchto(struct lwp *cur, struct lwp *newl);

DESCRIPTION
The mi_switch() function implements the machine-independent prelude to an LWP context switch. It is called from only a few distinguished places in the kernel code as a result of the principle of non-preemptable kernel mode execution. The three major uses of mi_switch() can be enumerated as follows:

1.  From within tsleep(9) when the current LWP voluntarily relinquishes the CPU to wait for some resource to become available.

2.  From within preempt(9) when the current LWP voluntarily relinquishes the CPU or when the kernel prepares a return to user-mode execution.

3.  In the signal handling code if a signal is delivered that causes an LWP to stop (see issignal(9)).

mi_switch() records the amount of time the current LWP has been running in the LWP structure and checks this value against the CPU time limits allocated to the LWP (see getrlimit(2)). Exceeding the soft limit results in a SIGXCPU signal to be posted to the LWP, while exceeding the hard limit will cause a SIGKILL. If newl is NULL, mi_switch() will hand over control to the machine-dependent function cpu_switch() to select a new LWP from the system run queue. If a new LWP is specified, mi_switch() will hand over control to the machine-dependent function cpu_switchto() to switch to the new LWP. If the new LWP is the same as the current LWP, then control is returned immediately to the LWP, avoiding any unnecessary overhead associated with switching in a new LWP.

The cpu_switch() and cpu_switchto() functions switch the new LWP onto the CPU. This procedure is performed by saving the LWP context of the current LWP in its process control block (PCB) and restoring the LWP context of the new LWP. The address space of the new LWP is activated using pmap_activate() (see pmap(9)). Finally, the new LWP is checked to see if it was previously preempted while inside a restartable atomic sequence (see ras(9)).

These functions must be called with the scheduler lock held (see SCHED_LOCK(9)) and at the splsched(9) interrupt protection level. Both functions return with the scheduler lock released.

RETURN VALUES
These functions return 1 if a context switch was performed to a different LWP, 0 otherwise.

SEE ALSO
SCHED_LOCK(9), pmap(9), ras(9), splsched(9), tsleep(9), wakeup(9)