|
| 1 | +#include <config.h> |
| 2 | +#include <stdint.h> |
| 3 | +#include <mem/paging.h> |
| 4 | +#include <console.h> |
| 5 | +#include <interrupt/irq.h> |
| 6 | + |
| 7 | +static uint32_t page_directory[1024] __attribute__((aligned(4096))); |
| 8 | +static uint32_t first_table[1024] __attribute__((aligned(4096))); |
| 9 | + |
| 10 | +/** |
| 11 | + * @fn paging_init_identity |
| 12 | + * @brief 指定されたMB数分のメモリを同一マッピングで初期化する |
| 13 | + * @param map_mb マッピングするメモリ容量(MB単位) |
| 14 | + */ |
| 15 | +void paging_init_identity(uint32_t map_mb) { |
| 16 | + uint32_t pages = ((map_mb * 1024u * 1024u) + 0xFFF) / 0x1000; |
| 17 | + |
| 18 | + // 最初のテーブル: 最初の4MBを同一マッピング(1024エントリ) |
| 19 | + for (uint32_t i = 0; i < 1024; ++i) { |
| 20 | + first_table[i] = (i * 0x1000) | 3u; // present + rw |
| 21 | + } |
| 22 | + |
| 23 | + // ディレクトリエントリ0はfirst_tableを指す |
| 24 | + page_directory[0] = ((uint32_t)first_table) | 3u; |
| 25 | + |
| 26 | + // 残りのPDEをnot presentにする |
| 27 | + for (uint32_t i = 1; i < 1024; ++i) page_directory[i] = 0x00000000; |
| 28 | + |
| 29 | + printk("paging: identity map initialized for %u MB (pages=%u)\n", (unsigned)map_mb, (unsigned)pages); |
| 30 | +} |
| 31 | + |
| 32 | +/** |
| 33 | + * @fn paging_enable |
| 34 | + * @brief ページング機能を有効化する |
| 35 | + */ |
| 36 | +void paging_enable(void) { |
| 37 | + // CR3をロード |
| 38 | + asm volatile("mov %%eax, %%cr3" :: "a"((uint32_t)page_directory)); |
| 39 | + // CR0のPGビットを有効化 |
| 40 | + uint32_t cr0; |
| 41 | + asm volatile("mov %%cr0, %%eax" : "=a" (cr0)); |
| 42 | + cr0 |= 0x80000000u; // PGビットをセット |
| 43 | + asm volatile("mov %%eax, %%cr0" :: "a" (cr0)); |
| 44 | +} |
| 45 | + |
| 46 | +/** |
| 47 | + * @fn page_fault_handler |
| 48 | + * @brief ページフォルト発生時のハンドラ |
| 49 | + * @param vec 割り込みベクタ番号 |
| 50 | + */ |
| 51 | +void page_fault_handler(uint32_t vec) { |
| 52 | + (void)vec; |
| 53 | + uint32_t fault_addr; |
| 54 | + asm volatile ("mov %%cr2, %0" : "=r" (fault_addr)); |
| 55 | + printk("PAGE FAULT at 0x%x\n", (unsigned)fault_addr); |
| 56 | + while (1) {} |
| 57 | +} |
0 commit comments