W8 - Memory Management
Layered Memory
Today we will focus on the management of the main memory (RAM)

Why Does Memory Need Management?
Protection
- Prevent one process from corrupting another
Sharing
- Allow multiple programs to coexist in memory
Abstraction
- Decouple program addresses from physical RAM
A Historical Perspective: Early Computers
Very limited memory and lacked the sophisticated memory protection and
address translation used in modern general-purpose systems.
No Memory Abstraction
- Programmes directly “see” the physical memory
MOV REG1, 1000corresponds to physical address 100
What Could Go Wrong Without Isolation?
- Bugs in user programmes can crash the OS
- Not possible to have two running processes in memory (at least fundamentally)
- No security
- Still common in embedded systems and smart cards
Notes:
- It wasn't possible, at least fundamentally, to have processes running at the same time in memory
- It adds a lot of complexity
- Programmers used to have a lot of flexibility back in the day
Memory Protection Keys
- Running multiple programmes without abstraction
- We split memory into blocks
- Each block associated with a memory protection key
- User programmes also get a key
- Can access memory when key matches
- Problem?
- Programmes still reference absolute physical addresses
- We need static relocation: add start address to all instructions that reference memory
Notes:
- Here the idea is that we are still considering no structure for our memory, but essentially we split it into specific blocks and we assign a key to each blog. Only the user that has that specific key, can access to this block.
- But quite easy to get some sort of unauthorized access
- We still have our programs that are performing operations in memory, what about a
JMPinstruction? - We could raise some exception to reach unauthorized memory access
- We still have our programs that are performing operations in memory, what about a
- So it enables to possibility to run multiple programs in parallel (you will run each in its own block), but still the protection side is not good.
Memory Abstraction: Address Space
- Programmes do not directly ”see” the physical memory
- Instead, they “see” only their address space
- Address Space
- The set of addresses a process can use
MOV REG1, 1000corresponds to address 1000 within the address space
Notes:
- We are still far, but it is the first step on top of physical memory
Can Two Processes Use the Same Address?
Same Address. Different Memory?
- Process A
- Virtual Address
- 0x1000
- Value: 50
- Process B
- Virtual Address
- 0x1000
- Value: 99
Can both processes use the same address (0x1000)?
- Since they are both virtual addresses, yes, but they cannot map to the same physical address of course.
Process Creation - fork() example
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(void) {
int *A = malloc(sizeof(int));
*A = 50;
pid_t pid = fork();
*A = *A + 1;
printf("PID=%d, address=%p, A=%d\n", getpid(), (void *)A, *A);
return 0;
}
Output:
PID=43913, address=0x105581a00, A=51
PID=43914, address=0x105581a00, A=51
- Example taken from W5 - Processes, Threads, and Scheduling
Dynamic Relocation
- Base and Limit registers
- Every time a process references a memory address, the CPU adds the base value to the address before talking to the RAM
- For protection, it checks if address is less than the limit value
- Disadvantage: Extra addition and comparison with every memory reference

Notes:
- Introduce two different registers:
- Base register (offset required to access specific part of the memory)
- Limit register (serves as top bound of our address space)
Address Translation
Example:
- Base register: 12000
- Limit Register: 4000
What happens when the process accesses logical address is 2500?
- Take the Base register, add this offset and if we didn't reach the limit address then it is a valid address?
What happens when the process accesses logical address is 4500?
- Trying to access a logical address that go beyond the limit register address
- In this case you end up having some sort of unauthorized memory access
Memory Overload
-
What if there is not enough RAM to keep all running processes in memory?
-
Swapping: Store the address space of processes on the disk

-
Notice Process A: base/limit registers need to be adjusted to new location
- We allocate A back again in step (g), but then we also have to take into consideration that fact that in the moment we have to re-allocate A, we don't necessarily have the space to allocate A in the same space as it was previously allocated
What Happens When RAM is Full?
vm_statmemory_pressure
Notes:
- If you look at the memory statistics, you will be able to see the number of swapouts, which you will notice is quite huge, this represents how important memory management is
Managing Free Memory: Bitmaps
-
Memory is divided in allocation units
-
A bitmap specifies if an allocation unit is free or occupied
-
Simple and memory-efficient (overhead of 1 bit per allocation unit)
-
To add a k-unit process, we need to search the bitmap for k consecutive 0 bits (slow)
Notes:
- We use 1 and 0 to check if chunks of memory are full or empty
- We would need to add a process that would take 6,7 chunks of memory, and we need to build this bitmap and try to find a spot where this process can fit it.
- Of course is not really efficient, but it is quite straight forward
Managing Free Memory: (Double) Linked List
-
Memory is divided in allocation units
-
OS maintains a linked list of allocated and free segment

-
Quick to search for sufficient space
- Different allocation strategies: first fit, next fit, best fit, worst fit
-
Easy to remove address spaces (i.e. free memory)
Notes:
- It is much more easier to destroy this kind of map, instead of getting rid of a whole bit map
- Also if I have a process that takes 2 chunks of memory, it is intuitive to do here, you just link them together
- It is more efficient than the first case (with bitmaps) but of course the complexity is a little higher
- But it is easier to understand the actual availability of the memory
Challenge
- Memories increase rapidly, but software sizes increase much faster
- How can I run a programme that is too large to fit in memory?
Fragmentation: The Hidden Problem
There are 5 free units. Can we allocate a contiguous block of 3?

There Is Enough Free Memory. Why Can't We Allocate?
Virtual Memory
The Birth of Virtual Memory:
-
Manchester Atlas Computer (one of the first attempts)
-
Approach: we want to make the life of the programmers easier, so that they don't have to think about memory allocation
-
Th OS will be the one that manages the physical memory while we are presented with a "virtual" representation of this memory.
-
Each process has a virtual address space
- We call them virtual addresses
-
The address space is split into chunks that we call pages
- Each page is a continuous range of addresses
-
Not all pages need to be in physical memory for a process to run
- Most of the pages are stored in the hard drive
- Some may be file-backed, and some may be not-yet-materialized zero-filled pages
- Most of the pages are stored in the hard drive
-
If programme accesses an address that is in memory: All good.
-
If programme accesses address that is not in memory: Page Fault.
- OS takes control, fetches the missing piece, instruction is executed again

Memory Management Unit (MMU)
-
CPU contains hardware that maps virtual addresses to physical addresses

-
Transfers between memory and disk are always in while pages
Virtual Memory: Paging Example
-
MMU keeps track of two things:
- Page is present/absent in physical memory
- If present, where exactly it is
-
MOV REG1, 1000- Virtual address 1000 is in virtual page 0 (0K-4K)
- Virtual page 0 is in physical memory in frame 2
1000 mod PAGE_SIZE + 2 * PAGE_SIZE = 9192
-
MOV REG1, 10000- Virtual address 10000 is virtual page 2 (8K-12K)
- Virtual page 2 is in physical memory in frame 6
10000 mod PAGE_SIZE + 6 * PAGE_SIZE = 26384
-
MOV REG1, 25000- Virtual address is virtual page 6 (24K-28K)
- Virtual page 6 is not in physical memory
- Page fault and try again

Let's translate the address (example):
Given virtual address 10000:
If page 2 maps to physical frame 6:
Virtual Memory: Page Tables
-
A virtual address is split into a virtual page number and an offset
- E.g. 4-bit page number, 12-bit offset
-
The virtual page number is used as an index to the page table

-
Protection bit(s): Read/Write/Execute
-
Modified bit: 1 if page in memory is modified
-
Referenced bit: 1 if page has been accessed

Large Page Tables
- Page tables can get very large
- E.g. 32-bit virtual addresses with 4K pages (12-bit) equals to 20-bit page tables
- Solution: Multilevel Page Table
- PT1 (10-bits) index to top-level page table (aka page directory)
- PT2 (10-bits) index to page
- Offset (12-bits) within 4K page
- Advantage: Only page tables that are needed are kept in memory

Three things to remember
- Address spaces provide abstraction and isolation between processes.
- The MMU and page tables translate virtual addresses into physical addresses.
- Virtual memory allows execution without keeping every page in RAM
Why do we need a Translation Lookaside Buffer (TLB)?
The Translation Lookaside Buffer (TLB)
- A small, fast hardware cache of recent virtual-to-physical address translations.
- A TLB hit avoids a page-table lookup.
- A TLB miss requires the translation to be found elsewhere, but does not necessarily cause a page fault

TLB Hit vs TLB Miss
What happens when the CPU accesses memory?
- TLB hit: Translation found → access physical memory.
- TLB miss: Translation not cached → consult the page tables.
- Page fault: The required mapping is missing, not resident, or violates access permissions.
- It is something quite common, not really a fatal error.
- It is more a sort of routine

Anatomy of a Page Fault
When a memory access cannot proceed
- The CPU raises a page-fault exception.
- The OS examines the address and the reason for the fault.
- If the access is valid, the OS resolves the fault (possibly loading or allocating a page).
- The instruction is restarted and execution continues

A Page Fault is not Necessarily an Error
- Suppose I allocate 100 MB of memory but haven't accessed it yet.
- Does the operating system necessarily need to allocate 100 MB of physical RAM immediately?
Demand Paging on macOS (example):
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <unistd.h>
int main(void) {
size_t page = (size_t)sysconf(_SC_PAGESIZE);
size_t pages = 16384;
size_t bytes = pages * page;
char *p = mmap(NULL, bytes, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANON, -1, 0);
if (p == MAP_FAILED) {
perror("mmap");
return 1;
}
printf("Page size: %zu bytes\n", page);
printf("Reserved: %zu MiB\n", bytes / 1024 / 1024);
printf("Press Enter to touch every page...\n");
getchar();
for (size_t i = 0; i < pages; i++)
p[i * page] = 1;
printf("All pages touched. Press Enter...\n");
getchar();
munmap(p, bytes);
return 0;
}
Output:
[robertomorabito@Mac W6-Memory Management % ps -o pid,rss,vsz,comm
PID RSS VSZ COMM
59909 1440 435561616 ./demand_paging
[robertomorabito@Mac W6-Memory Management % ps -o pid,rss,vsz,comm
PID RSS VSZ COMM
59909 263584 435561616 ./demand_paging
- The RSS changes (how much has been accessed in terms of virtual memory)
- Reserving virtual address space and physically populating it are different operations.
- The operating system can defer work until pages are actually accessed.
The Replacement Problem
Suppose physical memory has only three frames, currently containing
pages A, B, and C.
A process requests page D. Which page should the OS evict?
Page Replacement Algorithms
- When a page fault occurs, the OS needs to choose which page to remove from memory to make space for the incoming page
- Remember caches: Similar philosophy!
- If removed page is modified, then hard disk copy must be updated
- Otherwise, no rewrite is needed
- Which one shall we remove?
- Goal: Minimise the number of page faults
- Ideally, we want to remove the one that will be referenced last
- Push the next page fault into the future!
- Theoretically optimal
- Not very practical
Not Recently Used (NRU)
- Remember the Referenced/Modified bits?
- Both bits initialised to 0
- "Modified" is set to 1 every time we modify the page in memory
- "Referenced" is set to 1 every time we access the page in memory
- "Referenced" is periodically set to 0 (periodic clock interrupts, e.g. 20ms)
- NRU
- Idea: Remove pages that are not recently used (”Referenced” is 0)
- Implementation: Remove random from lowest-numbered nonempty class
- Class 0: not referenced / not modified
- Class 1: not referenced / modified
- Class 2: referenced / not modified
- Class 3: referenced / modified
Class R M Interpretation
0 0 0 Not recently used, clean
1 0 1 Not recently used, dirty
2 1 0 Recently used, clean
3 1 1 Recently used, dirty
Limitations?
- A page referenced 21ms ago is treated equally to one referenced 1 minute ago!
First-In, First-Out (FIFO)
-
Idea: Remove the page that was loaded in the most distant past

-
Implementation:
- OS keeps a list with all pages in memory
- Most recent arrival at the tail and least recent arrival at the head
- When a page fault occurs, remove the page at the head
-
Limitation?
- Oldest page may still be useful
Belady's Anomaly
Reference sequence
1, 2, 3, 4, 1, 2, 5, 1, 2, 3, 4, 5
Under FIFO:

Notes:
- Because of this specific sequence you will end up in a situation lie this one:
- 3 physical frames: 9 Faults
- 4 physical frames: 10 Faults
Second Chance
-
Idea: Remove the oldest page that has not been referenced recently
-
Implementation:
- Inspect ”Referenced” bit of oldest page
- If referenced recently (
“R”==1)- Put at the end of the queue
- Set “R”=0
- And try with the next oldest
- If not referenced recently (
“R”==0)- Remove and put new page at the end

-
Big improvements from FIFO
- But it constantly moves pages around
Clock
- Same idea, faster implementation
- Pages in memory are organised in a circular list
- Hand points to the oldest page
- When page fault, OS inspects the pointed page
- If referenced recently (
“R”==1)- Set “R”=0
- Advance hand and try again
- If not referenced recently (
“R”==0)- Replace page and advance hand
- If referenced recently (
Notes:
- Basically the same idea but with a small implementation improvement that makes it faster
Least Recently Used (LRU)
-
Idea: Remove the page that has been unused for the longest time
-
Advantages
- Close approximation of the optimal
- Realistic to implement
-
Disadvantages
- Expensive/inefficient to implement
-
Practical implementations:
- Linked list of pages (must be updated on each page reference)
- Hardware timer (needs specialised hardware)
Why isn't exact LRY used everywhere?
- Because we know in modern complex systems, using a static approach like this one is not that good, we rather do some forecast on the activity that is coming.
Not Frequently Used (NFU)
- Idea: Remove the page that is used less frequently
- Approximation of LFU but with software counters
- Implementation
- Keep a counter for each page in memory, initialise to zero
- Periodically, the OS scans the memory and increments of each page that has “
R==1” - Intuition: Counter roughly keeps tracks of use frequency
- When a page fault occurs, remove the page with the lowest counter
- Problem?
- It never forgets!
- Imagine a program that uses some pages a lot during initialisation and never later on
Ageing
- Idea: Keep short memory of page usage
- Implementation:
- Periodically, shift counters right and insert R bit
- On page fault, select smallest counter
- Efficient approximation to LRU

Which Algorithm Would You Choose?
| Scenario | Useful idea |
|---|---|
| Simplest implementation | FIFO |
| Recent references should matter | LRU |
| Approximate recency with low overhead | Clock |
| Track recent access history | Ageing |
The best replacement policy is a trade-off between implementation overhead and replacement effectiveness.
Working Set
-
Working set of a process is defined as the set of pages it has referenced during the past τ seconds of virtual time (execution time)
-
Remove page not in working set
-
Takes advantage of the locality of reference, meaning that during an execution phase, the process tends to reference only a relative small fraction of its pages
-
Somewhat expensive due to remembering smallest time

Notes:
- Essentially kind of split the process in different pages
- These are all different pages
- We can use the Time of last use to scan all the pages and find the smallest time
- Very smart way to think about the complexity of the processes memory management
Thrashing and Why it Happens

Thrashing occurs when insufficient resident memory causes excessive paging activity, leaving little useful progress.
- Decreases the actual work that our software does
WSClock
-
Combination of Clock and Working Set
-
Implementation:
- Examine the page pointed by the hand
- If
“R==1”, set ”R=0” and move hand - If
“R==0”and “age<=τ”, move hand - If
“R==0”and “age>τ”, remove
-
Optimisations to handle modified pages
-
Simple to implement and good performance
-
Widely used in practice

Summary of Page Replacement Algorithms
/CSCE-410-02159/Visual%20Aids/image-13.png)
What does macOS do today?
vm_stat
Three Things to Remember
- Virtual memory separates the addresses a program uses from physical RAM.
- Page replacement is a prediction problem: which pages will be useful again?
- Locality is the reason virtual memory can work efficiently.