boot.S 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /* Minimal x86 boot sector: load kernel from sector 2 to 0x7E00,
  2. * switch to protected mode, jump to kernel (C code at 0x7E00). */
  3. .code16
  4. .section .text
  5. .globl _start
  6. _start:
  7. /* Segment and stack for real mode */
  8. xorw %ax, %ax
  9. movw %ax, %ds
  10. movw %ax, %ss
  11. movw $0x7c00, %sp
  12. /* Save boot drive (BIOS puts it in DL) */
  13. movb %dl, boot_drive
  14. /* Set VGA mode 0x03 (80x25 color text) so 0xB8000 is the visible framebuffer */
  15. movw $0x0003, %ax
  16. int $0x10
  17. /* Load kernel: 5 sectors from sector 2 into 0x7E00 (ES:BX = 0x07E0:0) */
  18. movw $0x07e0, %ax
  19. movw %ax, %es
  20. xorw %bx, %bx
  21. movb $0x02, %ah /* int 0x13 read */
  22. movb $5, %al /* 5 sectors (kernel can be > 2K) */
  23. xorw %cx, %cx
  24. movb $2, %cl /* sector 2 (1-based) */
  25. xorw %dx, %dx /* head 0, drive in DL */
  26. movb boot_drive, %dl
  27. int $0x13
  28. jc halt /* on error just halt */
  29. /* Protected mode: load GDT, set CR0.PE, far jump to 32-bit code */
  30. cli
  31. lgdt gdtr
  32. movl %cr0, %eax
  33. orl $1, %eax
  34. movl %eax, %cr0
  35. .byte 0x66, 0xea
  36. .long pm_start
  37. .word 0x08
  38. .align 4
  39. boot_drive:
  40. .byte 0
  41. /* GDT (flat 4GB code and data) */
  42. .align 8
  43. gdt:
  44. .quad 0x0000000000000000
  45. /* 0x08: 32-bit code, DPL=0, base=0, limit=0xfffff (4GB) */
  46. .word 0xffff, 0x0000
  47. .byte 0x00, 0x9a, 0xcf, 0x00
  48. /* 0x10: 32-bit data */
  49. .word 0xffff, 0x0000
  50. .byte 0x00, 0x92, 0xcf, 0x00
  51. gdt_end:
  52. gdtr:
  53. .word gdt_end - gdt - 1
  54. .long gdt /* linear address (linker uses 0x7C00 base) */
  55. halt:
  56. cli
  57. 1: hlt
  58. jmp 1b
  59. /* --- 32-bit protected mode --- */
  60. .code32
  61. pm_start:
  62. movw $0x10, %ax
  63. movw %ax, %ds
  64. movw %ax, %es
  65. movw %ax, %fs
  66. movw %ax, %gs
  67. movw %ax, %ss
  68. movl $0x9000, %esp /* stack above kernel (0x7E00+2K); was 0x8000 and overwrote kernel */
  69. /* Jump to kernel at 0x7E00 (direct; *0x7e00 would be indirect = wrong) */
  70. movl $0x7e00, %eax
  71. jmp *%eax
  72. 1: cli
  73. hlt
  74. jmp 1b
  75. /* Boot signature at offset 510 (linker places it) */
  76. .section .bootsig
  77. .byte 0x55, 0xaa