paging.c 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /* Paging: identity-map RAM + the VESA LFB, enable CR0.PG (4 MB pages).
  2. *
  3. * This is the "paging on but flat" stage: every physical address is mapped
  4. * 1:1, so all existing code (kernel, stacks, DMA, UHCI, VGA shadow) keeps
  5. * working unchanged. Per-process page directories come later (Phase 3b/4).
  6. *
  7. * Uses 4 MB pages via CR4.PSE (supported since the original Pentium), so the
  8. * whole map is a single 4 KB page directory.
  9. */
  10. #include "paging.h"
  11. #include "mm.h"
  12. #include "serial.h"
  13. #include "vga.h"
  14. /* Page-directory entry flags (4 MB page). */
  15. #define PDE_PRESENT 0x001
  16. #define PDE_WRITABLE 0x002
  17. #define PDE_PWT 0x008
  18. #define PDE_PCD 0x010
  19. #define PDE_PS 0x080 /* 4 MB page */
  20. /* How much of the LFB to map. 16 MB covers any mode up to 1280x1024x32
  21. * (~5 MB) with margin, and is independent of the BIOS's VRAM report. */
  22. #define LFB_MAP_SIZE 0x1000000
  23. static unsigned int page_dir[1024] __attribute__((aligned(4096)));
  24. void paging_init(void)
  25. {
  26. unsigned int i;
  27. const volatile struct vga_boot_fb_info *fb = VGA_BOOT_FB;
  28. /* Opaque asm hides the fixed 0x600 pointer from -Warray-bounds. */
  29. __asm__ volatile ("" : "+r"(fb));
  30. /* Identity-map RAM [0, MM_MAX_PHYS) with 4 MB pages (write-back). */
  31. for (i = 0; i < MM_MAX_PHYS / 0x400000; i++)
  32. page_dir[i] = (i << 22) | PDE_PS | PDE_WRITABLE | PDE_PRESENT;
  33. /* Identity-map the framebuffer (MMIO, uncacheable) so the screen works. */
  34. if (fb->valid && fb->lfb_base) {
  35. unsigned int base = fb->lfb_base;
  36. unsigned int p0 = base >> 22;
  37. unsigned int p1 = (base + LFB_MAP_SIZE) >> 22;
  38. for (i = p0; i < p1 && i < 1024; i++)
  39. page_dir[i] = (i << 22) | PDE_PS | PDE_PCD |
  40. PDE_WRITABLE | PDE_PRESENT;
  41. }
  42. /* Load CR3, enable PSE, then PG + WP. The jump flushes the prefetch
  43. * queue after the paging flip. */
  44. __asm__ volatile (
  45. "movl %0, %%cr3\n\t"
  46. "movl %%cr4, %%eax\n\t"
  47. "orl $0x10, %%eax\n\t" /* CR4.PSE */
  48. "movl %%eax, %%cr4\n\t"
  49. "movl %%cr0, %%eax\n\t"
  50. "orl $0x80010000, %%eax\n\t" /* CR0.PG | CR0.WP */
  51. "movl %%eax, %%cr0\n\t"
  52. "jmp 1f\n\t"
  53. "1:\n\t"
  54. :
  55. : "r"((unsigned int)&page_dir[0])
  56. : "eax", "memory");
  57. serial_puts(SERIAL_COM1, "paging: enabled (identity map)\n");
  58. }