@@ -31,9 +31,14 @@ void *alloc_page_table(void) {
3131 (unsigned )phys );
3232 return NULL ;
3333 }
34- uint32_t * tbl = (uint32_t * )(uintptr_t )virt ;
34+ printk ("alloc_page_table: clearing table at virt=0x%x (phys=0x%x)\n" , (unsigned )virt , (unsigned )phys );
35+ // ページングが有効化されていない場合、virtはphysと同じ(アイデンティティ)
36+ // しかし、physが1MBを超える場合、アクセスできない可能性がある
37+ // 安全のため、物理アドレスで直接アクセス
38+ uint32_t * tbl_phys = (uint32_t * )(uintptr_t )phys ;
3539 for (size_t i = 0 ; i < 1024 ; ++ i )
36- tbl [i ] = 0 ;
40+ tbl_phys [i ] = 0 ;
41+ printk ("alloc_page_table: table cleared\n" );
3742 // return the virtual pointer for convenience to callers
3843 return (void * )(uintptr_t )virt ;
3944}
@@ -58,8 +63,10 @@ int map_page(uint32_t phys, uint32_t virt, uint32_t flags) {
5863 (unsigned )pd_idx );
5964 return -1 ;
6065 }
66+ printk ("map_page: new_pt_virt=0x%x, converting to phys\n" , (unsigned )(uintptr_t )new_pt_virt );
6167 uint32_t new_pt_phys =
6268 vmem_virt_to_phys ((uint32_t )(uintptr_t )new_pt_virt );
69+ printk ("map_page: new_pt_phys=0x%x\n" , (unsigned )new_pt_phys );
6370 if (new_pt_phys == 0 ) {
6471 printk ("map_page: vmem_virt_to_phys returned 0 for new_pt_virt=0x%x\n" ,
6572 (unsigned )(uintptr_t )new_pt_virt );
@@ -195,24 +202,22 @@ void page_fault_handler_ex(uint32_t vec, uint32_t error_code, uint32_t eip) {
195202 * @brief ページングを有効化
196203 */
197204void paging_enable (void ) {
198- // CR3をロード
199- uint32_t pd_phys =
200- vmem_virt_to_phys ((uint32_t )(uintptr_t )page_directory );
201- if (pd_phys == 0 ) {
202- printk ("paging_enable: vmem_virt_to_phys returned 0 for page_directory! skipping paging enable\n" );
203- return ;
204- }
205- if (pd_phys & 0xFFF ) {
206- printk ("paging_enable: pd_phys 0x%x not 4KB aligned! skipping\n" ,
207- (unsigned )pd_phys );
208- return ;
209- }
210- asm volatile ("mov %0, %%cr3" ::"r" ((uint64_t )pd_phys ));
211- // CR0のPGビットを有効化
212- uint64_t cr0 ;
205+ // 現在のページング状態を確認
206+ uint64_t cr0 , cr3 , cr4 ;
213207 asm volatile ("mov %%cr0, %0" : "=r" (cr0 ));
214- cr0 |= 0x80000000u ; // PGビットをセット
215- asm volatile ("mov %0, %%cr0" ::"r" (cr0 ));
208+ asm volatile ("mov %%cr3, %0" : "=r" (cr3 ));
209+ asm volatile ("mov %%cr4, %0" : "=r" (cr4 ));
210+ printk ("paging_enable: Current CR0=0x%lx CR3=0x%lx CR4=0x%lx\n" ,
211+ (unsigned long )cr0 , (unsigned long )cr3 , (unsigned long )cr4 );
212+ printk ("paging_enable: PG bit=%d, PAE bit=%d\n" ,
213+ (int )((cr0 >> 31 ) & 1 ), (int )((cr4 >> 5 ) & 1 ));
214+
215+ // 注意: x86-64ロングモードでは、UEFIがすでに64ビットページングを設定しています。
216+ // 現在の32ビットページング構造(2レベル: PD→PT)は互換性がありません。
217+ // 64ビットモードでは4レベル(PML4→PDPT→PD→PT)構造が必要です。
218+ // そのため、UEFIが設定したページテーブルをそのまま使用します。
219+ printk ("paging_enable: Skipping custom paging setup (using UEFI page tables)\n" );
220+ printk ("paging_enable: WARNING - 32-bit paging structures are incompatible with x86-64 long mode\n" );
216221}
217222
218223void page_fault_handler (uint32_t vec ) {
0 commit comments