title: Returning from kernel mode to user mode
body: <p>I'm a bit confused about the understanding of a mode switch in Unix kernel. I give my understanding here and open it for discussion/correction.</p>
  
  <p>While transitioning from user mode to kernel mode, the processor makes a switch between the per-process-user-stack and the per-process-kernel-stack. Then the user-per-process stack segment selector and stack pointer is stored in the kernel stack and then the <code>eip</code> instruction pointer (return address at user mode) and other hardware registers are pushed on to the kernel stack</p>
  
  <p>When the kernel has to return to user mode, the <code>trapret</code> code pops all values stored in the kernel stack back to the hardware registers.</p>
  
  <p><img src="https://i.stack.imgur.com/vnRlp.png" alt="trapret popping the values off the kernel stack"></p>
  
  <p>But when <code>iret</code> pops eip from the kernel stack, the next instruction that should get executed is the return address in user mode.</p>
  
  <p>This happens without completely popping the other values of the kernel stack. </p>
  
  <p>How do the rest of the values (<code>%cs, %eflags, %esp, %ss</code>) get restored ?</p>
  
  <p>How is the user-stack-pointer present in kernel stack popped back to %esp ?</p>
  
  <p><img src="https://i.stack.imgur.com/wDALp.png" alt="Trap Frame during a transition from user mode to kernel mode "></p>