switch.S 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. /*
  2. * Context-switch PIT IRQ stub.
  3. *
  4. * On entry the CPU has already pushed EFLAGS, CS, EIP onto the current
  5. * process's stack. We save the rest, bump the tick counter, and -- when
  6. * sched_tick_bsp() says the timeslice expired -- call schedule() and swap
  7. * ESP to the next process.
  8. *
  9. * The only process facts this file knows are:
  10. * - %gs:0 is struct cpu.current
  11. * - offset 0 of struct process is esp (saved/restored here)
  12. * CR3 and TSS.esp0 are switched by schedule() in C.
  13. *
  14. * Serial poll: every tick, check UART for received data and push to the ring
  15. * buffer so no bytes are lost during preemption.
  16. */
  17. .code32
  18. .text
  19. .extern ticks
  20. .extern schedule
  21. .extern sched_tick_bsp
  22. .extern serial_poll
  23. .include "irqret.inc"
  24. .globl pit_irq_stub
  25. pit_irq_stub:
  26. pusha
  27. /* Load the kernel selectors. The PIT can fire while a ring-3 process
  28. * is running; DS would then be null after the IRET that entered ring 3,
  29. * and the accesses below would #GP. GS is the per-CPU data selector. */
  30. movw $0x10, %ax
  31. movw %ax, %ds
  32. movw %ax, %es
  33. movw %ax, %fs
  34. movw $0x28, %ax
  35. movw %ax, %gs
  36. /* ticks++ and send EOI -- always, even when we don't switch. */
  37. incl ticks
  38. movb $0x20, %al
  39. outb %al, $0x20
  40. /* Poll UART for received serial data (prevents FIFO overflow). */
  41. call serial_poll
  42. /* Account the tick and decide whether the timeslice expired. */
  43. call sched_tick_bsp
  44. testl %eax, %eax
  45. jz .no_switch
  46. /* Save the interrupted ESP into current->esp. */
  47. movl %gs:0, %eax
  48. movl %esp, (%eax)
  49. /* Let the C scheduler pick the next process and switch CR3/TSS. */
  50. call schedule
  51. /* Load the new process's ESP. */
  52. movl %gs:0, %eax
  53. movl (%eax), %esp
  54. .no_switch:
  55. /* Both paths must leave a usable data selector for the context being
  56. * resumed; ring-3 needs 0x23, ring-0 uses 0x10 + GS 0x28. */
  57. IRQ_RETURN_DS 36
  58. popa
  59. iret
  60. /*
  61. * Voluntary reschedule gate: int 0x81. Entered from ring 0 only, with the
  62. * CPU having pushed EFLAGS/CS/EIP exactly like the PIT path. No EOI and no
  63. * tick accounting; just save ESP, pick a new process and restore its frame.
  64. */
  65. .globl resched_stub
  66. resched_stub:
  67. pusha
  68. movw $0x10, %ax
  69. movw %ax, %ds
  70. movw %ax, %es
  71. movw %ax, %fs
  72. movw $0x28, %ax
  73. movw %ax, %gs
  74. movl %gs:0, %eax
  75. movl %esp, (%eax)
  76. call schedule
  77. movl %gs:0, %eax
  78. movl (%eax), %esp
  79. IRQ_RETURN_DS 36
  80. popa
  81. iret