,

Contents ยท Memory Management (Paging, Segmentation, TLBs)


Address Spaces and Translation

  • Virtual memory: each process has its own virtual address space; translations map to physical frames.
  • Protection: per-page permissions (R/W/X, user/supervisor), isolation between processes.
  • MMU: hardware that performs page-table walks on TLB misses.

Segmentation

  • Logical partitions (code, data, stack) with base+limit; supports growth and protection per segment.
  • x86 legacy segmentation mostly disabled in 64-bit mode; still used for FS/GS base (TLS).
  • Modern systems favor paging; segmentation can help partitioning in microcontrollers.

Paging and Page Tables

  • Fixed-size pages (e.g., 4 KiB); virtual page number (VPN) + page offset.
  • Multi-level page tables: reduce memory footprint by allocating levels on demand (e.g., x86-64 4/5 levels).
  • PTE fields: PFN, valid, R/W/X, U/S, dirty, accessed; OS manages swapping via backing store.
  • Copy-on-write: fork() optimization by sharing pages read-only until written.
  • Demand paging: page faults bring pages lazily; working set and replacement policies matter.
// Tiny N-level page table walk (conceptual)
function walk(vaddr, levels, pageBits=12, idxBits=9) {
  let addr = vaddr >>> pageBits;
  const idxs = [];
  for (let i=0;i<levels;i++) { idxs.unshift(addr & ((1<<idxBits)-1)); addr >>= idxBits; }
  return idxs; // indices per level for vaddr
}

TLBs and Caching Translations

  • TLB: small associative cache of recent translations; miss triggers page-table walk.
  • ASIDs/PCIDs: avoid flushing on context switch by tagging TLB entries per process.
  • Shootdowns: on multiprocessors, invalidations broadcast to other cores when PTEs change.
  • Page coloring/NUMA: align allocations to reduce cache conflicts and remote memory access.
// Estimate effective memory access time (EMAT)
function emat(hitRate, tlbHit, walkCost) {
  return hitRate * tlbHit + (1-hitRate) * (tlbHit + walkCost);
}

Large Pages and HugeTLB

  • Use 2 MiB (x86-64) or 1 GiB huge pages for large contiguous regions to reduce TLB pressure.
  • Trade-offs: internal fragmentation, longer allocation time, potential security implications.

Security: NX, ASLR, Isolation

  • NX (no-execute): write XOR execute policy reduces code injection risks.
  • ASLR: randomize code/stack/heap bases to hinder ROP/JOP; effectiveness depends on entropy and info leaks.
  • Kernel isolation: KPTI separates user/kernel mappings to mitigate Meltdown-like attacks.

Exercises

  1. Write a simulator that walks 4-level page tables and counts memory references per translation.
  2. Measure TLB miss rates for random vs. sequential access patterns; test huge pages impact.
  3. Implement copy-on-write for a toy OS simulator with fork and demand paging.
Paging enables isolation and flexibility; TLB behavior often dominates real performance.