Welcome to the first post in our series on virtual memory! In this series, we will be exploring the concepts, benefits, and implementation of virtual memory in computer systems.
In this first post, we will discuss the motivation behind the use of virtual memory, including the limitations of physical memory and the need for efficient memory management. Virtual memory is an essential component of modern computing, allowing for the efficient utilization of resources and the execution of complex applications. So, let’s dive in.
Motivation
Virtual memory arises as a need to solve three problems:
- What happens when systems do not have enough memory? Capacity.
- What occurs with memory space segmentation? Segmentation.
- How can systems keep applications secure? Isolation.
Each problem is discussed in the following sections.
Capacity
To explain this point, we are using a 32-bit CPU with 1 GiB of RAM installed. When we read the technical specs of the processor the following is promised:
Any program can access any byte of the 32-bit address space
So, if a program is executed and tries to access any address over 0x3FFFFFFF, the program will crash because only 1 GiB is installed in the system.
Segmentation
Let’s suppose we have the following scenario:
- RAM address space: 32 bits (
0x00000000–0xFFFFFFFF). - Program 1 size: 1 GiB.
- Program 2 size: 2 GiB.
- Program 3 size: 2 GiB.
With that scenario, we get the following:
- Program 1 is loaded in RAM at address zero (
0x00000000–0x3FFFFFFF). As it is the first program to be loaded, there is enough space in memory. At the end, we now have 3 GiB free. - Program 2 is loaded now, right after program 1 (
0x40000000–0xBFFFFFFF). Before the program is loaded, there were 3 GiB of free space, so the program can be loaded. At the end, the remaining free space is 1 GiB. - Program 1 is terminated, freeing up 1 GiB of space. At this point the amount of free space is 2 GiB ([
0x00000000–0x3FFFFFFF], [0xC0000000–0xFFFFFFFF]). - Even though the current amount of free space is 2 GiB, program 3 cannot be loaded in memory because the free space is segmented.
Isolation
Imagine that in our system, we have two different programs. One of the programs is used to manage bank information and the other is a video game. Both share the following instruction:
mov rcx, [rsp + 0x400]; [rsp] = 0x0
In our system, both programs will access the same address, creating a race-condition-like problem. This could cause critical information to be overwritten.
Summary
Virtual memory, as mentioned, was motivated by the need to solve the exposed problems. In the following posts, we will see how virtual memory works under the hood. Stay tuned!