Pasan lahiru dissanayake

Sep 6, 2021

11 min read

Build your own operating system-part07

Virtual Memory and Paging

Virtual Memory Through Segmentation?

Paging

Why Paging?

Paging in x86 :

Identity Paging

Enabling Paging :

; eax has the address of the page directory
mov cr3, eax

mov ebx, cr4 ; read current cr4
or ebx, 0x00000010 ; set PSE
mov cr4, ebx ; update cr4

mov ebx, cr0 ; read current cr0
or ebx, 0x80000000 ; set PG
mov cr0, ebx ; update cr0

; now paging is enabled

A Few Details :

; invalidate any TLB references to virtual address 0
invlpg [0]

Paging and the Kernel :

Reasons to Not Identity Map the Kernel -

The Virtual Address for the Kernel -

Placing the Kernel at 0xC0000000 -

Higher-half Linker Script -

ENTRY(loader)           /* the name of the entry symbol */

. = 0xC0100000 /* the code should be relocated to 3GB + 1MB */

/* align at 4 KB and load at 1 MB */
.text ALIGN (0x1000) : AT(ADDR(.text)-0xC0000000)
{
*(.text) /* all text sections from all files */
}

/* align at 4 KB and load at 1 MB + . */
.rodata ALIGN (0x1000) : AT(ADDR(.text)-0xC0000000)
{
*(.rodata*) /* all read-only data sections from all files */
}

/* align at 4 KB and load at 1 MB + . */
.data ALIGN (0x1000) : AT(ADDR(.text)-0xC0000000)
{
*(.data) /* all data sections from all files */
}

/* align at 4 KB and load at 1 MB + . */
.bss ALIGN (0x1000) : AT(ADDR(.text)-0xC0000000)
{
*(COMMON) /* all COMMON sections from all files */
*(.bss) /* all bss sections from all files */
}

Entering the Higher Half -

  • Set up a page table.
  • Add identity mapping for the first 4 MB of the virtual address space.
  • Add an entry for 0xC0100000 that maps to 0x0010000
; assembly code executing at around 0x00100000
; enable paging for both actual location of kernel
; and its higher-half virtual location

lea ebx, [higher_half] ; load the address of the label in ebx
jmp ebx ; jump to the label

higher_half:
; code here executes in the higher half kernel
; eip is larger than 0xC0000000
; can continue kernel initialisation, calling C code, etc.

Running in the Higher Half -

Virtual Memory Through Paging :