Skip to main content
@shmVirus

Memory Hierarchy

Organize RAM and ROM, map cache lines, calculate effective access time, translate virtual addresses, and compare replacement and write policies.

Updated

Learning objectives

  • Explain why locality makes a memory hierarchy effective
  • Construct memory modules and address maps from RAM and ROM chips
  • Derive direct, associative, and set-associative cache fields
  • Calculate hit ratio, average access time, speed ratio, and efficiency
  • Trace virtual-address translation, page faults, and replacement policies

Prerequisites

  • Computer Organization
  • Digital Components

A useful memory system must appear large, fast, and inexpensive, but no single technology maximizes all three. A hierarchy keeps the current working set in small fast levels and the rest in progressively larger, slower levels.

TermDefinition
LatencyTime from a request until its requested item becomes usable.
BandwidthAmount of information transferred per unit time.
Cache lineFixed-size block moved between a cache and the next memory level.
PageFixed-size virtual-memory block mapped to a physical frame.
HitThe requested item is present in the level being checked.
Miss penaltyExtra time needed to obtain the item from a lower level.
Memory hierarchy pyramid from CPU registers through cache, main memory, solid-state storage, disk, and archival storage
Moving downward increases capacity and access time while reducing cost per bit. Data moves between adjacent levels in blocks.
LevelTypical roleVolatile?Unit transferred
CPU registersImmediate operands and stateYesWord
L1/L2/L3 cacheRecently used instructions and dataYesCache line
Main memoryActive processesYesCache line or page
SSD/diskFiles and virtual-memory backingNoPage/block
ArchiveLong-term backupNoLarge blocks

Why the Hierarchy Works

Programs show temporal locality—recently used items tend to be reused—and spatial locality—nearby addresses tend to be used soon. Loops, stacks, arrays, instructions in a basic block, subroutines, and symbol tables all exhibit locality. Moving an entire block on a miss anticipates nearby references.

The terms hit and miss are relative to a level. Hit ratio hh is the fraction found there; miss rate is 1h1-h. Miss penalty includes the time to fetch from the next level and make the requested word available.

Main Memory Technologies

RAM

Random-access memory takes approximately the same time to access any addressed word.

TypeCellRefreshDensity/costCommon use
SRAMBistable latch, commonly six transistorsNoLower density, expensiveCache
DRAMCapacitor plus access transistorRequiredHigh density, inexpensiveMain memory

DRAM reads are destructive and must restore the cell. Its address may be multiplexed into row and column portions to reduce package pins. SRAM is faster and simpler to interface but consumes more area per bit.

ROM family

TypeHow contents change
Mask ROMFixed during manufacture
PROMProgrammed once
EPROMErased with ultraviolet light and reprogrammed
EEPROM/flashElectrically erased and reprogrammed

ROM stores firmware and fixed lookup data. Modern flash is nonvolatile and rewritable, but writes are slower and organized in erase blocks.

Building and Addressing a Memory Module

An m×nm\times n chip stores mm words of nn bits. It needs log2m\log_2m address inputs and nn data connections. Capacity expansion has two independent directions:

  • Put chips in parallel to widen each word.
  • Decode additional high-order address bits to select one bank and increase the number of words.

For example, build 2KiB×82\,\text{KiB}\times8 from 512×8512\times8 chips. Each chip uses nine address bits because 512=29512=2^9. Four chips provide depth; A8A0A_8\dots A_0 go to every chip and a 2-to-4 decoder driven by A10A9A_{10}A_9 selects one chip.

RAM and ROM chips connected to common low address and data buses with high address bits decoded into chip select lines and a matching address map
Low address bits select a word inside every chip; decoded high bits ensure that only the chip assigned to that address range responds.

If four 512-byte regions start at address 0x000, their inclusive ranges are:

SelectBinary high bitsAddress range
CS0000x000–0x1FF
CS1010x200–0x3FF
CS2100x400–0x5FF
CS3110x600–0x7FF

The same decoder can select a mixture of RAM and ROM, creating a memory map. Read/write control must be disabled for ROM.

Cache Organization

A cache line contains a valid bit, a tag, a data block, and often dirty/replacement metadata. The CPU address separates into:

tagwhich memory block set/indexwhere to look word/byte offsetwhich item in the block.\underbrace{\text{tag}}_{\text{which memory block}} \ \underbrace{\text{set/index}}_{\text{where to look}} \ \underbrace{\text{word/byte offset}}_{\text{which item in the block}}.
Direct, fully associative, and two-way set-associative mappings from main-memory blocks to cache lines
Associativity controls placement freedom: exactly one line, any line, or any way inside one indexed set.

Direct mapping

Main-memory block jj maps to cache line i=jmodLi=j\bmod L, where LL is the number of cache lines. The index selects one line and its stored tag confirms whether that line contains the requested block. Hardware is small and fast, but two active blocks with the same index repeatedly evict each other.

Source example: a 32K×1232\text{K}\times12 main memory has 2152^{15} words and a 512×12512\times12 one-word-line cache has 292^9 lines. Its 15-bit address splits into a 6-bit tag and a 9-bit line index. If each line instead contains eight words and the cache still holds 512 words, it has 64=2664=2^6 lines, so the split is 6 tag bits, 6 line bits, and 3 word bits.

Fully associative mapping

Any memory block may occupy any line. Every stored tag is compared in parallel, eliminating conflict based solely on index. The parallel comparison and replacement search cost more hardware.

Set-associative mapping

The cache is divided into SS sets with WW ways per set. Block jj maps to set jmodSj\bmod S and may occupy any of its WW ways. It balances direct mapping’s fast indexing with associative placement inside a small set.

For a 32 KiB, 4-way cache with 64-byte lines and 32-bit byte addresses:

lines=32768/64=512,sets=512/4=128.\text{lines}=32768/64=512,\qquad \text{sets}=512/4=128.

Offset bits =log264=6=\log_2 64=6, set bits =log2128=7=\log_2 128=7, and tag bits =3276=19=32-7-6=19.

Cache Lookup, Replacement, and Writes

CPU address split into tag index and offset, indexed cache lookup, parallel tag comparison, hit selection, and main-memory refill path
On a hit, the offset selects the requested item. On a miss, the next level supplies a complete block, a victim line is chosen, and the request is retried or forwarded.

Common victim policies are:

  • FIFO: replace the line resident longest; simple, but not sensitive to actual use.
  • LRU: replace the least recently referenced line; good locality behavior, but exact tracking becomes costly at high associativity.
  • Random/pseudo-LRU: inexpensive approximations often used in hardware.
  • Optimal: replace the item whose next use is farthest in the future; unattainable online, but a useful lower bound.

On a write, write-through updates cache and main memory immediately; a write buffer can hide some delay. Write-back updates only the cache, marks the line dirty, and writes it to memory when evicted. A write miss also needs an allocation choice: write-allocate fetches the line, whereas no-write-allocate writes around the cache.

Average Access Time

If a hit costs tct_c and a miss first checks cache and then accesses main memory in tmt_m, the source model is

T=htc+(1h)(tm+tc).T=h\,t_c+(1-h)(t_m+t_c).

With tc=160t_c=160 ns, tm=960t_m=960 ns, and h=0.90h=0.90:

T=0.9(160)+0.1(960+160)=256 ns.T=0.9(160)+0.1(960+160)=256\text{ ns}.

The main-memory/cache speed ratio is γ=tm/tc=6\gamma=t_m/t_c=6. Efficiency relative to ideal cache time is

λ=tcT=11+γ(1h)=11+6(0.1)=0.625.\lambda=\frac{t_c}{T}=\frac1{1+\gamma(1-h)} =\frac1{1+6(0.1)}=0.625.

Always state the timing convention. Some systems overlap cache lookup with the lower-level access and use T=tc+(1h)tmT=t_c+(1-h)t_m; the numerical result happens to be the same algebraically here.

For multiple levels, let FiF_i be the fraction of all requests that reach level ii, and tit_i its access time:

T=iFiti.T=\sum_i F_it_i.

Using the lecture example’s stated reach fractions and latencies—F=(1,0.4,0.2,0.1)F=(1,0.4,0.2,0.1) and t=(100 ns,1μs,50 ms,1 s)t=(100\text{ ns},1\,\mu\text{s},50\text{ ms},1\text{ s})

T=0.0001+0.0004+10+100=110.0005 ms.T=0.0001+0.0004+10+100=110.0005\text{ ms}.

This calculation treats FiF_i as unconditional fractions of all references. If hit probabilities are conditional on reaching a level, multiply the preceding miss probabilities to derive FiF_i instead.

Virtual Memory

Virtual memory gives each process a private address space larger and more regular than available physical RAM. It divides virtual space into fixed-size pages and physical memory into equal-size frames.

Virtual page number and offset translated through a TLB and page table to a physical frame and offset, with a page-fault path to secondary storage
The page offset is unchanged. Only the virtual page number is translated to a physical frame number.

For virtual address width vv, physical address width pp, and page size 2d2^d bytes:

FieldWidth
Page offsetdd bits
Virtual page numbervdv-d bits
Physical frame numberpdp-d bits

A page-table entry records the frame plus valid/present, protection, referenced, and dirty information. A translation lookaside buffer (TLB) caches recent page-table entries.

For a 32-bit byte address and a 4 KiB page, the offset has log24096=12\log_2 4096=12 bits and the virtual page number has 3212=2032-12=20 bits. If physical memory is 1 GiB, physical addresses have 30 bits, so a frame number needs 3012=1830-12=18 bits. Translation changes the 20-bit virtual page number into an 18-bit frame number; it copies the 12-bit offset unchanged.

On a TLB miss, hardware or software consults the page table. If the page is present, translation is inserted into the TLB. If absent, a page fault transfers control to the operating system, which selects a frame, writes a dirty victim if needed, reads the required page from storage, updates the page table/TLB, and restarts the instruction.

Page Replacement

FIFO, LRU, and Optimal also illustrate virtual-memory replacement:

PolicyDecision basisImportant property
FIFOOldest loaded pageCan show Belady’s anomaly: more frames can cause more faults
LRUOldest last useStack property; no Belady anomaly
OptimalFarthest future useMinimum possible faults; requires future knowledge

For reference string 7 0 1 2 0 3 0 4 and three empty frames, FIFO evolves:

7--  70-  701  201  201  231  230  430
 F    F    F    F    H    F    F    F

There are seven faults and one hit. LRU differs at the request for 3: because 1 is least recently used, it evicts 1 rather than FIFO’s 0. Optimal is useful for comparing algorithms, not implementing a real system.

Check Your Understanding

  1. Why is a complete block fetched on a cache miss rather than only one word?
  2. Split a 24-bit byte address for a direct-mapped 4 KiB cache with 16-byte lines.
  3. What is the average time for tc=5t_c=5 ns, tm=80t_m=80 ns, and h=0.95h=0.95 under the sequential-lookup model?
  4. Which virtual-address field passes through translation unchanged?
Answers
  1. Spatial locality makes nearby words likely to be referenced soon.
  2. 16=2416=2^4, so 4 offset bits; 4096/16=256=284096/16=256=2^8 lines, so 8 index bits and 2484=1224-8-4=12 tag bits.
  3. 0.95(5)+0.05(80+5)=90.95(5)+0.05(80+5)=9 ns.
  4. The page offset.