Loading W Code...
Deep Dive into Paging, TLB, Page Replacement Algorithms & Thrashing
Virtual Memory provides process isolation by mapping contiguous Virtual Addresses used by software to non-contiguous Physical RAM Frames via the hardware Memory Management Unit (MMU).
(Page Number, Offset) into physical address tuple (Frame Number, Offset).Read, Write, Execute, User/Kernel Mode).# Linux mmap Virtual Memory Allocation Example
#include <sys/mman.h>
#include <stdio.h>
int main() {
// Requesting 4KB virtual page allocation from kernel
void *ptr = mmap(NULL, 4096, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
printf("Allocated Virtual Address: %p\n", ptr);
munmap(ptr, 4096);
return 0;
}Paging splits virtual address spaces into fixed-size blocks (typically 4 KB).
PML4 \to PDPT \to PD \to PT), saving physical memory.// Effective Memory Access Time (EMAT) Calculation
// EMAT = (TLB_Hit_Rate * TLB_Access_Time) + (TLB_Miss_Rate * (TLB_Access_Time + Memory_Access_Time * Page_Table_Levels))
double compute_emat(double hit_rate, double tlb_time, double mem_time, int levels) {
return (hit_rate * tlb_time) + ((1.0 - hit_rate) * (tlb_time + (levels + 1) * mem_time));
}Variable allocation strategies allocate contiguous memory segments to requesting processes:
External fragmentation is resolved by shifting active processes in physical RAM to coalesce contiguous free memory space into a single block.
// C Buddy Allocator Concept
void* buddy_malloc(size_t size) {
// Splits power-of-two memory blocks recursively
return NULL;
}When physical RAM is full during a Page Fault, the OS page replacement algorithm selects a victim page to evict to swap disk:
# LRU Cache Page Replacement Simulation in Python
class LRUCache:
def __init__(self, capacity: int):
self.cap = capacity
self.cache = {} # OrderedDict for O(1) eviction
def get(self, page_id: int) -> int:
if page_id not in self.cache:
return -1
val = self.cache.pop(page_id)
self.cache[page_id] = val
return valThrashing occurs when a system spends more time servicing page faults than executing instructions.
# Checking Linux Swap & Memory Pressure Signals
free -h
vmstat 1 5
cat /proc/sys/vm/swappiness