Building your own Operating System (Week 07)

Virtual Memory

Virtual memory is an abstraction of physical memory. The goal of virtual memory is to make application development easier and to allow processes to access more memory than is physically available on the computer. Due to security concerns, we don’t want apps tampering with the kernel or other applications’ memory.


Paging is a function of memory management where a computer will store and retrieve data from a device’s secondary storage to the primary storage. Segmentation translates a logical address into a linear address. Paging translates these linear addresses onto the physical address space and determines access rights and how the memory should be cached.

Enabling Paging

Paging is enabled by first writing the address of a page directory to “cr3” and then setting bit 31 of “cr0” to “1”. To use 4 MB pages, set the PSE bit of “cr4”. We can enable paging using this assembly code.

The Virtual Address for the Kernel

The kernel should ideally be put at a very high virtual memory address, such as 0xC0000000 (3 GB). The user-mode process is unlikely to be 3 GB in size, which is the only way it may now cause a kernel conflict. A higher-half kernel is one that uses virtual addresses in the range of 3 GB and up. The location 0xC0000000 is only used as an example, the kernel may be put at any address greater than 0 to get the same results. The proper address is determined by the amount of virtual memory available for the kernel and the amount of virtual memory available for the process.

Virtual Memory Through Paging

Paging allows for two benefits in virtual memory. To begin with, it enables fine-grained memory access control. Pages can be marked as read-only, read-write, or exclusively for PL0, among other options. Second, it gives the impression of a single, continuous memory. The memory may be accessed as if it were contiguous by user-mode programs and the kernel, and the contiguous memory can be expanded without moving data around in memory. We can also provide user-mode applications access to any memory under 3 GB, but we don’t need to allocate page frames to the pages unless they actually utilize it. This enables processes to contain code around 0x00000000 and a stack slightly below 0xC0000000 while still requiring only two threads.

sudo apt-get install gcc-multilib



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store