3
votes

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?

2
The answer to this question strongly depends on the architecture you are programming for. Some architectures like x86 have hardware support, others like SPARC do not. Also, the implementation differs between operating systems, so please narrow down the question at least to a single CPU.fuz
Ok, thanks. I was really just curious about this question as I was going through my course, and I wanted to know how something like this could be possible. I'm not developing anything that needs to be able to do this at the moment, and the only architecture I'm familiar with is MIPS, but I haven't worked with it in depthuser129137

2 Answers

3
votes

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.

-1
votes

In general, a processor defines a Process Context Block (PCB). This is a data structure in which the processor stores into and loads from the registers. For the most part the operating system does not really need to know the internal structure of the PCB, only the size.

Processors generally have a Load Process Context and Save Process Context instruction. For simplicity, assume you have process context blocks with the labels PROCESS_1 and PROCESS_2 where the former is the current running process, to switch processes you do something like:

 SVPCTX  PROCESS_1
 LDPCTX  PROCESS_2 ; As soon as this instruction execute the context switch is complete.

This can be more complex on some systems that have multiple register sets (say "Hi" Intel) but what I have described is how it generally works on most processors.