Search code examples
assemblyoperating-systemcontext-switch

How can a CPU save its register state in a context switch?


I've been taking a course on operating systems, and in a lecture on context switching, it was mentioned that when a context switch occurs, the OS saves the state of all of the registers to a PCB block, so that the exact state of this process can be resumed when the OS chooses to revisit it.

In assembly, how would someone write the code to save all of this information? As far as I understand, if you want to write any information to memory, you need to have the memory location stored in one of your registers. So, in the process of writing your registers to memory, at least one of your registers has to be overwritten to a location in the PCB block, and the information stored in that register would be lost.

Is there hardware support that makes this task possible?


Solution

  • Here is an example of how it can be done:
    1. Save one register to the stack.
    2. Load that register with the address of the PCB.
    3. Save all the state in the PCB, including retrieving the register value saved on the stack.