title: How does schedule()+switch_to() functions from linux kernel actually work?
body: <p>I'm trying to understand how the schedule process in linux kernel actually works. My question is not about the scheduling algorithm. Its about how the functions <code>schedule()</code> and <code>switch_to()</code> work.</p>
  
  <p>I'll try to explain. I saw that: </p>
  
  <p>When a process runs out of time-slice, the flag <code>need_resched</code> is set by <code>scheduler_tick()</code>. The kernel checks the flag, sees that it is set, and calls <code>schedule()</code> (pertinent to question 1) to switch to a new process. This flag is a message that schedule should be invoked as soon as possible because another process deserves to run. 
  Upon returning to user-space or returning from an interrupt, the <code>need_resched</code> flag is checked. If it is set, the kernel invokes the scheduler before continuing.</p>
  
  <p>Looking into the kernel source (linux-2.6.10 - version that the book "Linux Kernel Development, second edition" is based on), I also saw that some codes can call the <code>schedule()</code> function voluntarily, giving another process the right to run.
  I saw that the function <code>switch_to()</code> is the one that actually does the context switch. I looked into some architecture dependent codes, trying to understand what <code>switch_to()</code> was actually doing.</p>
  
  <p>That behavior raised some questions that I could not find the answers for :</p>
  
  <ol>
  <li><p>When <code>switch_to()</code> finishes, what is the current running process? The process that called <code>schedule()</code>? Or the next process, the one that was picked to run?</p></li>
  <li><p>When <code>schedule()</code> gets called by an interrupt, the selected process to run starts to run when the interrupt handling finishes (after some kind of RTE) ? Or before that?</p></li>
  <li><p>If the <code>schedule()</code> function can not be called from an interrupt, when is the flag- <code>need_resched</code> set?</p></li>
  <li><p>When the timer interrupt handler is working, what stack is being used?</p></li>
  </ol>
  
  <p>I don't know if I could make myself clear. If I couldn't, I hope I can do this after some answers (or questions).
  I already looked at several sources trying to understand that process. I have the book "Linux Kernel Development, sec ed", and I'm using it too.
  I know a bit about MIPs and H8300 architecture, if that help to explain.</p>