> For the complete documentation index, see [llms.txt](https://davidjosearaujo.gitbook.io/notes-miect/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://davidjosearaujo.gitbook.io/notes-miect/sistemas-de-operacao/processes/context-switching.md).

# Context switching

Current processors have two functioning modes:

* **supervisor mode** – all instruction set can be executed.
  * is a privileged mode.
* **user mode** – only part of the instruction set can be executed.
  * input/output instructions are excluded as well as those that modify control registers.
  * it is the normal mode of operation.

Switching from user mode to supervisor mode is only possible through an **exception** (for security reasons).

An exception can be caused by:

* I/O interrupt.
  * external to the execution of the current instruction.
* Illegal instruction (division by zero, bus error).
  * associated with the execution of the current instruction, but not intended.
* Trap instruction (software interruption)
  * associated with the execution of the current instruction, and intended.

The operating system should function in supervisor mode.

* in order to have access to all the functionalities of the processor.

Thus kernel functions (including system calls) must be fired by:

* hardware (interrupt).
* trap (software interruption).

This establishes a uniform operating environment: **exception handling**.

**Context switching** is the process of storing the state of a process and restoring the state of another process.

Context switching occurs necessarily in the context of an exception, with a small difference on how it is handled.

## Processing a (normal) exception

<figure><img src="https://933056030-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FmDWmJ4LyRblScRPGY3di%2Fuploads%2Fl1tf2UF7HL7SK7ZEvvIF%2Funknown.png?alt=media&amp;token=9d7f3e34-35ca-4afc-a71c-6abc8b4ef554" alt=""><figcaption></figcaption></figure>
