recategorized
1,075 views
0 votes
0 votes

Consider the context switch of a CPU from the context of process $P1$ to that of process $P2$. Consider the following two events in the chronological order of the events during the context switch.
(P) The Stack Pointer (SP) shifts from pointing to the kernel stack of $P1$ to the kernel stack of $P2$.
(Q) The Program Counter (PC) shifts from pointing to an address in the memory allocated to $P1$ to an address in the memory allocated in $P2$

Which of the following statements is true regarding the relative ordering of actions $P$ and $Q$?

  1. $P$ occurs before $Q$
  2. $Q$ occurs before $P$
  3. Both occur simultaneously via an atomic hardware instruction
  4. The relative ordering of $P$ and $Q$ varies from one context switch to the other
recategorized

1 Answer

2 votes
2 votes

A context switch from a process to another process is done in kernel mode. So, there would be a switch needed from user mode of P1 to kernel mode of P1, then a switch from kernel mode of P1 to kernel mode of P2, and then from kernel mode of P2 to user mode of P2.

Detailed steps: 1)-  Initially P1 is running in user mode. Let say a timer interrupt occurs, a switch from user mode of P1 to kernel mode of P1 happens, CPU saves registers and PC value into the kernel stack of P1, lookup the interrupt table and jump to the timer interrupt handler code.

2)- Now, control is in the hands of OS, and trap handler will execute. Before returning from trap, OS scheduler code is invoked, and scheduler  decides whether to switch to another process or not.

3)- If it decides to switch, then a context switch() routine is executed:: I) - context ( PC and registers)of P1 would be saved on the per process kernel stack of P1( PCB).

ii) stack pointer would be changed and will start pointing to per process kernel stack of P2.

iii) And context of P2(PC and registers) would be restored in CPU from the kernel stack of P2.

4)- Now, the CPU is running in the kernel mode of P2. Return from Trap instruction is executed which will restore the registers of P2 from kernel stack of P2, do switching from kernel to user mode, and jumps to P2's PC value.

5) Now, the CPU is running in user mode of P2.

Hence, according to the context switch routine, P occurs before Q.

edited by
Answer:

Related questions

4 votes
4 votes
1 answer
2