switch.S 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. /*
  2. * Context-switch PIT IRQ stub.
  3. *
  4. * On entry the CPU has already pushed EFLAGS, CS, EIP onto the
  5. * current process's stack. We save the rest, bump the tick counter,
  6. * and -- when the timeslice expires -- call schedule() and swap ESP
  7. * to the next process.
  8. *
  9. * Shadow buffer flush: every ~33 ticks (30Hz), set pending flag.
  10. * Main loop checks dirty rows and copies only what changed.
  11. *
  12. * Serial poll: every tick, check UART for received data and push
  13. * to ring buffer so no bytes are lost during preemption.
  14. */
  15. .code32
  16. .text
  17. .extern ticks
  18. .extern current_pid
  19. .extern procs
  20. .extern schedule
  21. .extern vga_shadow_flush_pending
  22. .extern serial_poll
  23. .extern tss
  24. /* struct process offsets (must match process.h / process.c) */
  25. .equ PCB_ESP, 0
  26. .equ PCB_CR3, 32
  27. .equ PCB_KSTACK_TOP, 36
  28. .equ PCB_SIZE, 40 /* sizeof(struct process): 4+4+4+12+4+4+4+4 = 40 */
  29. .equ TIMESLICE, 20
  30. .equ FLUSH_INTERVAL, 33 /* 1000Hz PIT / 30Hz flush ≈ 33 ticks */
  31. .globl pit_irq_stub
  32. pit_irq_stub:
  33. pusha
  34. /* ticks++ and send EOI -- always, even when we don't switch. */
  35. incl ticks
  36. movb $0x20, %al
  37. outb %al, $0x20
  38. /* Poll UART for received serial data (prevents FIFO overflow). */
  39. call serial_poll
  40. /* Shadow buffer flush at 30Hz: set pending flag, main loop does the copy. */
  41. decl flush_counter
  42. jnz .no_flush
  43. movl $FLUSH_INTERVAL, flush_counter
  44. movl $1, vga_shadow_flush_pending
  45. .no_flush:
  46. /* Decrement timeslice counter; switch only when it reaches 0. */
  47. decl slice_counter
  48. jnz .no_switch
  49. /* Reset counter for next timeslice. */
  50. movl $TIMESLICE, slice_counter
  51. /* Save current ESP into procs[current_pid].esp (procs is a pointer). */
  52. movl current_pid, %eax
  53. imull $PCB_SIZE, %eax
  54. addl procs, %eax
  55. movl %esp, PCB_ESP(%eax)
  56. /* Let the C scheduler pick the next process. */
  57. call schedule
  58. /* Load new ESP, CR3, and TSS esp0 from procs[current_pid]. */
  59. movl current_pid, %eax
  60. imull $PCB_SIZE, %eax
  61. addl procs, %eax
  62. movl PCB_ESP(%eax), %esp
  63. movl PCB_CR3(%eax), %ebx
  64. movl %ebx, %cr3
  65. movl PCB_KSTACK_TOP(%eax), %ebx
  66. movl %ebx, tss+4 /* TSS.esp0 = this process's ring-0 stack top */
  67. .no_switch:
  68. popa
  69. iret
  70. .data
  71. .align 4
  72. slice_counter:
  73. .long TIMESLICE
  74. flush_counter:
  75. .long FLUSH_INTERVAL