By the end of this chapter you'll be able to…

  • 1Explain why a memory hierarchy exists and what it tries to achieve
  • 2Distinguish temporal from spatial locality and match each to a design decision
  • 3Split an address into tag, index and offset fields
  • 4Verify a field split by checking the widths sum to the address width
  • 5Compare direct, fully associative and set associative mapping
  • 6Explain why the three mapping schemes are points on one scale
  • 7State when a replacement policy is needed at all
  • 8Compare LRU, FIFO, random and optimal replacement
  • 9Explain Belady's anomaly and why stack algorithms avoid it
  • 10Compare write-through and write-back policies
  • 11Match write-allocate and no-write-allocate to their natural partners
  • 12Classify a miss as compulsory, capacity or conflict
  • 13Choose the design change that addresses each miss type
  • 14Compute average memory access time for one and two levels
  • 15Distinguish local from global miss rate
  • 16Explain why block size has an optimum
  • 17Compare virtually and physically indexed caches
  • 18Explain the page-offset indexing compromise
  • 19Compare DRAM and SRAM and explain where each is used
  • 20Explain row and column addressing in DRAM
  • 21Compute the bandwidth gain from memory interleaving
  • 22Distinguish low-order from high-order interleaving and their use cases
💡
Why this chapter matters in GATE
Memory technology forces an unavoidable trade: fast memory is expensive and therefore small, while large memory is cheap and therefore slow. No single technology gives both, so several levels are stacked and the goal is to make the whole stack behave as though it had the capacity of the largest level and the speed of the smallest. That goal is achievable only because programs do not access memory randomly. Locality of reference is what makes the entire hierarchy work: temporal locality means a location accessed once will likely be accessed again soon, and spatial locality means its neighbours will be. Every design decision in a cache is a bet on one of these two — block size bets on spatial locality, replacement policy on temporal locality, and associativity on how many competing addresses map to the same place. So the way to reason about any cache question is to ask which locality the design exploits and where the address bits go.

Before you start — revise these

🔗
Machine Instructions & Addressing Modes
Byte versus word addressing, alignment and address widths all feed directly into cache field calculations.
🔗
Instruction Pipelining & Hazards
A cache miss is the largest source of pipeline stalls, and the split instruction and data caches exist to remove a structural hazard.
🔗
Memory Management & Virtual Memory
Address translation determines whether a cache can be virtually indexed, and page replacement uses the same policies as cache replacement.

Memory Hierarchy: Cache & Main Memory

Memory technology forces an unavoidable trade: fast memory is expensive and therefore small, and large memory is cheap and therefore slow. No single technology gives capacity and speed together.

The hierarchy is the response. Several levels are stacked, each larger and slower than the one above, and the goal is to make the whole stack behave as though it had the capacity of the largest level and the speed of the smallest.

That goal is achievable only because programs do not access memory randomly. Locality of reference is what makes the entire hierarchy work, and without it a cache would be useless.

Temporal locality means a location accessed once is likely to be accessed again soon — loop variables, a stack top, a frequently called function.

Spatial locality means a location near one just accessed is likely to be accessed soon — array traversal, sequential instruction fetch, fields of a structure.

Every design decision in a cache is a bet on one of these two. Block size bets on spatial locality. Replacement policy bets on temporal locality. Associativity bets on how many competing addresses map to the same place.

So the way to reason about any cache question is to ask which locality the design is exploiting and where the address bits go.

1. The Address Split

A cache holds blocks copied from main memory. An address is divided into fields that answer three questions: which set, which block within it, and which byte within the block.

The offset field is determined by the block size: a block of bytes needs offset bits.

The index field is determined by the number of sets: sets need index bits.

The tag is whatever remains, and it must be stored alongside each cached block so that a hit can be confirmed.

Getting these three widths right is the foundation of every cache calculation, and the number of sets depends on the mapping scheme.

2. Mapping Schemes

SchemeWhere a block may goNumber of sets
Direct mappedExactly one lineNumber of lines
Fully associativeAny line1
-way set associativeAny of lines in one setLines divided by

Direct mapping is fastest to check — one comparison — and suffers most from conflict misses, because two heavily used addresses mapping to the same line evict each other repeatedly.

Fully associative mapping has no conflict misses at all, since a block may go anywhere, but checking requires comparing the tag against every line simultaneously. That comparator array is what limits it to small caches.

Set associative mapping is the compromise that real caches use. A block maps to one set and may occupy any line within it, so comparators suffice and conflicts require competing addresses rather than 2.

Note that direct mapping is 1-way set associative and fully associative mapping is -way for a cache of lines, so the three are points on one scale rather than three separate ideas.

3. Replacement Policies

A replacement policy is needed only when a block may go in more than one place, so direct-mapped caches need none.

PolicyRuleCost
LRUEvict the least recently usedNeeds recency tracking per set
FIFOEvict the oldest loadedOne counter per set
RandomEvict an arbitrary lineAlmost free
OptimalEvict the one used furthest in the futureUnimplementable

LRU is a bet on temporal locality and performs well because recent use predicts near-future use in real programs.

The optimal policy is not implementable, since it requires knowing the future, but it is used as a benchmark: no online policy can beat it, so it bounds how much a better policy could possibly gain.

FIFO suffers from Belady's anomaly, in which increasing the number of lines can increase the number of misses. LRU and optimal are stack algorithms and cannot exhibit it, which is a standard examination point.

4. Write Policies

Reads and writes are handled differently because a write creates an inconsistency between cache and memory.

Write-through updates both cache and memory on every write. Memory is always current, so a cache line may be discarded without further action, but write traffic to memory is heavy.

Write-back updates only the cache and marks the line dirty, writing it to memory only when it is evicted. Traffic falls dramatically, since a line written many times is transferred once, at the cost of a dirty bit per line and a more complex eviction path.

A write buffer sits between a write-through cache and memory to absorb bursts, letting the processor continue while the write drains.

On a write miss, two further choices exist.

Write-allocate fetches the block into the cache and then writes it, betting that more accesses to the block will follow. It pairs naturally with write-back.

No-write-allocate writes straight to memory without loading the block, which pairs naturally with write-through, since the cache would gain nothing from holding a block it is not going to read.

5. The Three Kinds of Miss

Classifying misses tells you which design change would help.

Compulsory misses occur on the first reference to a block, and no cache organisation avoids them. Larger blocks reduce them by prefetching neighbours, which is a bet on spatial locality.

Capacity misses occur because the cache cannot hold the program's working set. Only a larger cache helps.

Conflict misses occur because too many blocks map to the same set, even though the cache has room elsewhere. Higher associativity reduces them, and a fully associative cache has none by definition.

The classification is diagnostic. A cache with many conflict misses should be made more associative; one with many capacity misses should be made larger; one dominated by compulsory misses should use larger blocks or prefetching.

6. Performance

Average memory access time combines the hit case and the miss case:

where is the miss rate and is the extra time a miss costs.

The miss penalty is usually so large that a small change in miss rate outweighs a large change in hit time. A hit time of 1 cycle with a 5 per cent miss rate and a 100-cycle penalty gives an AMAT of 6 cycles, so the misses account for five-sixths of the time.

For a multi-level hierarchy the formula nests: the miss penalty of level 1 is the average access time of level 2.

Two miss rates must be distinguished. The local miss rate of a level is misses at that level divided by accesses to that level. The global miss rate is misses at that level divided by all processor accesses.

Since only level-1 misses reach level 2, the level-2 local miss rate is typically high while its global miss rate is low, and confusing the two is a standard error.

Block size has an optimum. Increasing it exploits spatial locality and reduces compulsory misses, but beyond some point it reduces the number of blocks, raising conflict and capacity misses, and it lengthens the miss penalty because more bytes must be transferred.

A related question is whether the cache is indexed by virtual or physical addresses, and it decides what happens on a context switch.

A virtually indexed cache can begin its lookup before address translation completes, which removes the translation from the critical path. The cost is that the same virtual address in two processes refers to different data, so the cache must either be flushed on a context switch or tagged with a process identifier.

A physically indexed cache has no such ambiguity but must wait for translation. The standard compromise indexes with the page-offset bits, which translation leaves unchanged, and compares physical tags — giving the speed of virtual indexing with the correctness of physical tagging.

7. Main Memory Organisation

Main memory is built from DRAM, which stores a bit as charge on a capacitor and therefore must be refreshed periodically. SRAM stores a bit in a latch, needs no refresh, and is faster and larger per bit — which is why caches are SRAM and main memory is DRAM.

DRAM is organised as a two-dimensional array addressed in two phases, sending a row address and then a column address on the same pins. This halves the pin count at the cost of an extra timing step, and it is why the row access strobe and column access strobe signals exist.

Once a row is open, successive accesses within it are fast, which is what burst transfers exploit — and it is another instance of spatial locality being converted into speed.

Interleaving increases bandwidth by spreading consecutive addresses across independent banks. With banks, accesses can proceed concurrently, so a sequential read stream achieves close to times the bandwidth of a single bank.

The addressing detail matters: low-order interleaving puts consecutive addresses in different banks, which suits sequential access, while high-order interleaving puts consecutive addresses in the same bank, which suits independent processes using separate regions.

8. Worked Examples

Example 1. A byte-addressable machine has a 32-bit address, a 64 KB cache with 32-byte blocks, 4-way set associative. Find the tag, index and offset widths.

Start with the offset, determined by the block size.

Block size is 32 bytes, so the offset is bits.

Next the number of lines: cache size divided by block size is lines.

Next the number of sets: lines divided by associativity is sets.

So the index is bits.

The tag is whatever remains: bits.

Check the total: , which confirms the arithmetic. Performing this check catches almost every slip in cache field questions.

Example 2. For the cache above, how much storage is used for tags and valid bits, as a fraction of the data storage?

Each line needs its 18-bit tag plus 1 valid bit, so 19 bits of overhead per line.

With 2048 lines, the overhead is bits, which is 4,864 bytes.

The data storage is 64 KB, which is 65,536 bytes.

The overhead is per cent.

A dirty bit would add one more bit per line if the cache were write-back, taking the overhead to 20 bits per line and about 7.8 per cent.

Note how the overhead scales: halving the block size doubles the number of lines and roughly doubles the overhead, which is one of the practical arguments against very small blocks.

Example 3. A processor has a 1-cycle hit time, a 4 per cent miss rate and a 120-cycle miss penalty. Compute the AMAT, and the AMAT if a second-level cache with a 12-cycle access time and a 25 per cent local miss rate is added.

Without the second level:

With the second level, the level-1 miss penalty becomes the level-2 access time plus the level-2 miss rate times the memory time.

The second-level cache reduces the AMAT from 5.8 to 2.68 cycles, a speedup of about 2.16.

Note the two miss rates. The 25 per cent figure is the local miss rate of level 2, meaning a quarter of the accesses that reach it also miss. The global miss rate of level 2 is per cent, meaning only one per cent of all processor accesses reach main memory.

Using the global rate in place of the local one in the formula would understate the level-2 contribution by a factor of 25.

Example 4. A direct-mapped cache with 4 lines receives the block reference string 0, 4, 0, 4, 0, 4. How many misses occur, and what happens with 2-way set associativity?

With 4 lines and direct mapping, block maps to line .

Block 0 maps to line 0, and block 4 also maps to line 0 since .

The two blocks therefore evict each other on every access.

Reference 0: miss, load into line 0. Reference 4: miss, evict 0, load 4. Reference 0: miss, evict 4, load 0.

And so on. All 6 references miss.

Now make the cache 2-way set associative with the same total of 4 lines, giving 2 sets of 2 lines each. Block maps to set .

Block 0 maps to set 0 and block 4 also maps to set 0, since . But set 0 has two lines, so both blocks fit simultaneously.

Reference 0: miss, load. Reference 4: miss, load into the other line of the set. All four subsequent references hit.

Only 2 misses, both compulsory.

This is exactly the conflict-miss phenomenon, and it shows why associativity is the right fix for it: the cache had room all along, and only the mapping restriction prevented its use.

Example 5. Show that FIFO exhibits Belady's anomaly on the reference string 1, 2, 3, 4, 1, 2, 5, 1, 2, 3, 4, 5 with 3 and 4 frames.

With 3 frames under FIFO:

1 miss, 2 miss, 3 miss (frames 1,2,3). 4 miss evicting 1 (2,3,4). 1 miss evicting 2 (3,4,1). 2 miss evicting 3 (4,1,2). 5 miss evicting 4 (1,2,5). 1 hit. 2 hit. 3 miss evicting 1 (2,5,3). 4 miss evicting 2 (5,3,4). 5 hit.

Counting: 9 misses.

With 4 frames under FIFO:

1 miss, 2 miss, 3 miss, 4 miss (1,2,3,4). 1 hit. 2 hit. 5 miss evicting 1 (2,3,4,5). 1 miss evicting 2 (3,4,5,1). 2 miss evicting 3 (4,5,1,2). 3 miss evicting 4 (5,1,2,3). 4 miss evicting 5 (1,2,3,4). 5 miss evicting 1 (2,3,4,5).

Counting: 10 misses.

More frames produced more misses, which is Belady's anomaly. It arises because FIFO's eviction choice ignores usage, so a larger set of frames can change the eviction order in a way that discards a block just before it is needed.

LRU cannot do this because it is a stack algorithm: the contents with frames are always a subset of the contents with frames, so any hit with frames is also a hit with .

Example 6. A main memory has 8 banks with low-order interleaving and a bank cycle time of 80 ns. What is the peak bandwidth for sequential 4-byte accesses, and what changes with high-order interleaving?

Low-order interleaving places consecutive addresses in different banks, so a sequential stream touches bank 0, then bank 1, and so on.

With 8 banks, 8 accesses can be in flight simultaneously, and once the pipeline is full one access completes every ns.

Peak bandwidth is 4 bytes per 10 ns, which is 400 MB per second — eight times the 50 MB per second a single bank would deliver.

With high-order interleaving, consecutive addresses fall in the same bank, since the bank is selected by the high-order address bits.

A sequential stream then hits one bank repeatedly and achieves only single-bank bandwidth, 50 MB per second, with the other seven banks idle.

High-order interleaving is not simply worse; it suits a different pattern. Several independent processes working in separate memory regions land in different banks and proceed concurrently, and a failed bank takes out one contiguous region rather than every eighth word of the whole address space.

Summary

The hierarchy exists because fast memory is small and large memory is slow, and it works only because programs exhibit temporal and spatial locality.

An address splits into tag, index and offset. The offset comes from block size, the index from the number of sets, and the tag is the remainder — always check that the three sum to the address width.

Direct mapping is one comparison and many conflict misses; fully associative has no conflicts but needs a comparator per line; set associative is the practical compromise, and the three are points on one scale.

Replacement policies matter only when a block may go in more than one place. LRU bets on temporal locality, optimal bounds what any policy could achieve, and FIFO can exhibit Belady's anomaly while stack algorithms cannot.

Write-through keeps memory current at the cost of traffic; write-back marks lines dirty and writes once on eviction. Write-allocate pairs with write-back, no-write-allocate with write-through.

Misses are compulsory, capacity or conflict, and the classification tells you whether to enlarge blocks, enlarge the cache or raise associativity.

AMAT is hit time plus miss rate times penalty, and it nests for multiple levels. Local and global miss rates differ, and only level-1 misses reach level 2.

DRAM needs refresh and is addressed in row and column phases; SRAM does not and is used for caches. Low-order interleaving accelerates sequential access, while high-order interleaving suits independent regions.

Key formulas & results

Everything to memorise for the exam hall, in one card. Screenshot this for revision.

The organising tool
EVERY CACHE DESIGN DECISION IS A BET ON LOCALITY. BLOCK SIZE BETS ON SPATIAL LOCALITY, REPLACEMENT POLICY ON TEMPORAL LOCALITY, ASSOCIATIVITY ON HOW MANY ADDRESSES COMPETE FOR ONE PLACE.
ASK WHICH LOCALITY THE DESIGN EXPLOITS AND WHERE THE ADDRESS BITS GO. WITHOUT LOCALITY A CACHE WOULD BE USELESS.
The address split
AN ADDRESS DIVIDES INTO TAG, INDEX AND OFFSET. THE OFFSET IS log2 OF THE BLOCK SIZE, THE INDEX IS log2 OF THE NUMBER OF SETS, AND THE TAG IS WHATEVER REMAINS.
ALWAYS CHECK THAT THE THREE WIDTHS SUM TO THE ADDRESS WIDTH. THAT SINGLE CHECK CATCHES ALMOST EVERY SLIP IN CACHE FIELD QUESTIONS.
Counting sets
LINES EQUALS CACHE SIZE DIVIDED BY BLOCK SIZE. SETS EQUALS LINES DIVIDED BY ASSOCIATIVITY.
DIRECT MAPPED HAS AS MANY SETS AS LINES; FULLY ASSOCIATIVE HAS ONE SET; k-WAY HAS LINES DIVIDED BY k.
Mapping schemes
DIRECT MAPPING ALLOWS ONE LINE AND ONE COMPARISON. FULLY ASSOCIATIVE ALLOWS ANY LINE AND NEEDS A COMPARATOR PER LINE. k-WAY SET ASSOCIATIVE ALLOWS ANY OF k LINES IN ONE SET.
DIRECT MAPPING IS 1-WAY AND FULLY ASSOCIATIVE IS N-WAY FOR N LINES, SO THE THREE ARE POINTS ON ONE SCALE RATHER THAN THREE SEPARATE IDEAS.
Tag overhead
EACH LINE STORES ITS TAG PLUS A VALID BIT, AND A DIRTY BIT TOO IF THE CACHE IS WRITE-BACK.
HALVING THE BLOCK SIZE DOUBLES THE LINE COUNT AND ROUGHLY DOUBLES THE OVERHEAD, WHICH IS A PRACTICAL ARGUMENT AGAINST VERY SMALL BLOCKS.
Replacement policies
LRU EVICTS THE LEAST RECENTLY USED. FIFO EVICTS THE OLDEST LOADED. RANDOM EVICTS ARBITRARILY. OPTIMAL EVICTS THE ONE USED FURTHEST IN THE FUTURE AND IS UNIMPLEMENTABLE.
A REPLACEMENT POLICY IS NEEDED ONLY WHEN A BLOCK MAY GO IN MORE THAN ONE PLACE, SO DIRECT-MAPPED CACHES NEED NONE.
Belady's anomaly
UNDER FIFO, INCREASING THE NUMBER OF FRAMES CAN INCREASE THE NUMBER OF MISSES.
LRU AND OPTIMAL ARE STACK ALGORITHMS: THE CONTENTS WITH n FRAMES ARE ALWAYS A SUBSET OF THE CONTENTS WITH n PLUS 1, SO THEY CANNOT EXHIBIT IT.
Write policies
WRITE-THROUGH UPDATES CACHE AND MEMORY ON EVERY WRITE. WRITE-BACK UPDATES ONLY THE CACHE, MARKS THE LINE DIRTY, AND WRITES ON EVICTION.
WRITE-BACK CUTS TRAFFIC DRAMATICALLY BECAUSE A LINE WRITTEN MANY TIMES IS TRANSFERRED ONCE. A WRITE BUFFER ABSORBS BURSTS FOR A WRITE-THROUGH CACHE.
Write miss policies
WRITE-ALLOCATE FETCHES THE BLOCK THEN WRITES IT. NO-WRITE-ALLOCATE WRITES STRAIGHT TO MEMORY WITHOUT LOADING THE BLOCK.
WRITE-ALLOCATE PAIRS NATURALLY WITH WRITE-BACK, AND NO-WRITE-ALLOCATE WITH WRITE-THROUGH, SINCE THE CACHE GAINS NOTHING FROM A BLOCK IT WILL NOT READ.
The three miss types
COMPULSORY MISSES OCCUR ON FIRST REFERENCE. CAPACITY MISSES OCCUR BECAUSE THE WORKING SET EXCEEDS THE CACHE. CONFLICT MISSES OCCUR BECAUSE TOO MANY BLOCKS MAP TO ONE SET.
THE CLASSIFICATION IS DIAGNOSTIC: LARGER BLOCKS FOR COMPULSORY, A LARGER CACHE FOR CAPACITY, HIGHER ASSOCIATIVITY FOR CONFLICT.
Average memory access time
AMAT = T_hit PLUS MISS RATE TIMES MISS PENALTY.
THE PENALTY IS USUALLY SO LARGE THAT A SMALL CHANGE IN MISS RATE OUTWEIGHS A LARGE CHANGE IN HIT TIME. A 1-CYCLE HIT WITH 5 PER CENT MISSES AT 100 CYCLES GIVES AMAT 6.
Multi-level AMAT
AMAT = T_L1 PLUS m_L1 TIMES (T_L2 PLUS m_L2 TIMES T_mem). THE MISS PENALTY OF ONE LEVEL IS THE AVERAGE ACCESS TIME OF THE NEXT.
THE FORMULA NESTS FOR ANY NUMBER OF LEVELS, EACH LEVEL'S PENALTY BEING THE NEXT LEVEL'S AVERAGE ACCESS TIME.
Local versus global miss rate
LOCAL MISS RATE IS MISSES AT A LEVEL DIVIDED BY ACCESSES TO THAT LEVEL. GLOBAL MISS RATE IS MISSES AT THAT LEVEL DIVIDED BY ALL PROCESSOR ACCESSES.
ONLY LEVEL-1 MISSES REACH LEVEL 2, SO ITS LOCAL RATE IS TYPICALLY HIGH WHILE ITS GLOBAL RATE IS LOW. CONFUSING THE TWO IS A STANDARD ERROR.
Optimal block size
LARGER BLOCKS EXPLOIT SPATIAL LOCALITY AND REDUCE COMPULSORY MISSES, BUT REDUCE THE BLOCK COUNT AND LENGTHEN THE MISS PENALTY.
BEYOND SOME POINT THE RISING CONFLICT AND CAPACITY MISSES AND THE LONGER TRANSFER OUTWEIGH THE PREFETCH BENEFIT.
Virtual versus physical indexing
A VIRTUALLY INDEXED CACHE STARTS ITS LOOKUP BEFORE TRANSLATION COMPLETES BUT MUST BE FLUSHED OR PROCESS-TAGGED ON A CONTEXT SWITCH. A PHYSICALLY INDEXED CACHE WAITS FOR TRANSLATION.
THE STANDARD COMPROMISE INDEXES WITH THE PAGE-OFFSET BITS, WHICH TRANSLATION LEAVES UNCHANGED, AND COMPARES PHYSICAL TAGS.
DRAM versus SRAM
DRAM STORES A BIT AS CHARGE ON A CAPACITOR AND MUST BE REFRESHED. SRAM STORES A BIT IN A LATCH, NEEDS NO REFRESH, AND IS FASTER AND LARGER PER BIT.
THIS IS WHY CACHES ARE SRAM AND MAIN MEMORY IS DRAM: THE HIERARCHY IS A DIRECT CONSEQUENCE OF THE TWO TECHNOLOGIES' TRADE-OFFS.
DRAM addressing
DRAM IS A TWO-DIMENSIONAL ARRAY ADDRESSED IN TWO PHASES, SENDING A ROW ADDRESS THEN A COLUMN ADDRESS ON THE SAME PINS.
THIS HALVES THE PIN COUNT AT THE COST OF AN EXTRA TIMING STEP. ONCE A ROW IS OPEN, SUCCESSIVE ACCESSES WITHIN IT ARE FAST, WHICH IS WHAT BURST TRANSFERS EXPLOIT.
Interleaving
WITH n BANKS, n ACCESSES CAN PROCEED CONCURRENTLY, SO A SEQUENTIAL STREAM ACHIEVES CLOSE TO n TIMES SINGLE-BANK BANDWIDTH.
LOW-ORDER INTERLEAVING PUTS CONSECUTIVE ADDRESSES IN DIFFERENT BANKS AND SUITS SEQUENTIAL ACCESS. HIGH-ORDER PUTS THEM IN THE SAME BANK AND SUITS INDEPENDENT REGIONS.
⚠️

Traps GATE sets — and how to dodge them

These are the exact option-traps and misreads that cost marks under negative marking.

WATCH OUT
Computing the index from the number of lines in a set-associative cache
The index selects a set, not a line. Divide the line count by the associativity first, then take the base-two logarithm. Using the line count directly overstates the index and understates the tag.
WATCH OUT
Forgetting to check that the three field widths sum to the address width
Tag plus index plus offset must equal the full address width. This one check catches almost every arithmetic slip in cache questions and takes a few seconds.
WATCH OUT
Treating direct-mapped and set-associative as unrelated schemes
Direct mapping is 1-way set associative and fully associative is N-way for N lines. Seeing them as one scale makes the trade-off between comparator count and conflict misses obvious.
WATCH OUT
Assigning a replacement policy to a direct-mapped cache
A block has exactly one possible location, so there is no choice to make. Replacement policies matter only when associativity exceeds one.
WATCH OUT
Assuming more frames always means fewer misses
Under FIFO, more frames can mean more misses, which is Belady's anomaly. Only stack algorithms such as LRU and optimal are guaranteed monotonic.
WATCH OUT
Pairing write-through with write-allocate
Write-allocate loads a block so future accesses hit, which only pays if the cache retains the written data. With write-through the data goes to memory anyway, so no-write-allocate is the natural partner.
WATCH OUT
Using the global miss rate where the local one belongs
In the nested AMAT formula, each level's miss rate is local to that level, since it applies only to the accesses that reach it. Substituting a global rate understates the deeper level's contribution badly.
WATCH OUT
Assuming a larger block always reduces the miss rate
Beyond an optimum, larger blocks reduce the number of blocks, raising conflict and capacity misses, and they lengthen the miss penalty. The curve turns upward, which is why block sizes are typically 32 to 128 bytes.
WATCH OUT
Trying to fix conflict misses with a larger cache
Conflict misses occur even when the cache has free space elsewhere, because the mapping restricted where the block could go. Higher associativity is the correct fix; more capacity may not help at all.
WATCH OUT
Trying to fix compulsory misses with associativity
A first reference misses whatever the organisation. Only larger blocks or prefetching help, by bringing in neighbouring data before it is requested.
WATCH OUT
Ignoring the context-switch cost of a virtually indexed cache
The same virtual address means different data in different processes, so the cache must be flushed or tagged with a process identifier. The page-offset indexing compromise avoids both costs.
WATCH OUT
Assuming high-order interleaving is simply worse
It suits independent processes in separate regions, which then land in different banks, and it localises a bank failure to one contiguous region rather than every nth word of the address space.

Exam-pattern practice

PYQ-style questions with full solutions. Work through them as a readiness check — mark yourself honestly and get your gap report at the end.

Readiness check

Are you exam-ready for Memory Hierarchy: Cache & Main Memory?

9 problems from this chapter. Try each one, reveal the worked solution, mark yourself honestly — get your gap report at the end.

9 questions~6 min

5-minute revision

The whole chapter, distilled. Read this the night before the exam.

  • Fast memory is small; large memory is slow.
  • Locality is what makes the hierarchy work.
  • Temporal locality justifies replacement policies.
  • Spatial locality justifies block size.
  • Offset width is log base 2 of block size.
  • Index width is log base 2 of the number of sets.
  • Tag is whatever remains.
  • Check that the three widths sum to the address width.
  • Lines equal cache size over block size.
  • Sets equal lines over associativity.
  • Direct mapping is one comparison, many conflicts.
  • Fully associative has no conflict misses.
  • Set associative is the practical compromise.
  • Direct mapped needs no replacement policy.
  • LRU bets on temporal locality.
  • Optimal is a benchmark, not implementable.
  • FIFO can exhibit Belady's anomaly.
  • Stack algorithms cannot exhibit it.
  • Write-through keeps memory current.
  • Write-back marks lines dirty and writes on eviction.
  • Write-allocate pairs with write-back.
  • No-write-allocate pairs with write-through.
  • Compulsory misses need larger blocks or prefetch.
  • Capacity misses need a larger cache.
  • Conflict misses need higher associativity.
  • AMAT is hit time plus miss rate times penalty.
  • The formula nests for multiple levels.
  • Local and global miss rates differ.
  • Only L1 misses reach L2.
  • Block size has an optimum.
  • Virtual indexing removes translation from the critical path.
  • Virtual indexing needs flushing or process tags.
  • Page-offset indexing is the standard compromise.
  • DRAM needs refresh; SRAM does not.
  • DRAM is addressed in row and column phases.
  • Open-row access is fast, which bursts exploit.
  • n banks give up to n times the bandwidth.
  • Low-order interleaving suits sequential access.
  • High-order interleaving suits independent regions.

GATE question blueprint

How this topic is asked, tier by tier — so you can prep to the pattern.

Typical weightage: Computer Organization contributes roughly 7-9 of the 72 core-CS marks; the memory hierarchy supplies 2-3 of those across 1-2 questions

Question styleMarks eachTypical countWhat it tests
Address split1~1Computing tag, index and offset widths and verifying the total
Cache organisation2~1Set counts, tag storage overhead and the effect of block size
AMAT1~1Single-level average access time and the balance between hit time and miss rate
Multi-level AMAT2~1Nesting the formula and distinguishing local from global miss rates
Conflict misses2~1Tracing a reference string and comparing mapping schemes
Miss classification1~1Identifying the miss type and the design change that addresses it
Write policies2~1Traffic comparison and when write-through is preferable
Interleaving2~1Bandwidth computation and stride sensitivity
Belady's anomaly2~1Demonstrating it under FIFO and explaining why stack algorithms are immune

Exam-hall strategy

Battle-tested tips from mentors and toppers for this topic under the sectional clock.

  1. Compute the offset from block size first, then lines, then sets, then index, then tag.
  2. Always verify that the three field widths sum to the address width.
  3. Divide lines by associativity before taking the index logarithm.
  4. In nested AMAT, use local miss rates at every level.
  5. Classify a miss before proposing a fix; associativity does not cure capacity misses.
  6. Check whether the machine is byte- or word-addressable before computing the offset.
  7. Cache field widths and AMAT are commonly set as NAT, which carries no negative marking, so never leave one blank.
  8. For 1-mark and 2-mark MCQs, negative marking is -1/3 and -2/3, so guess only after eliminating an option.
  9. GATE gives a single freely-navigable 180-minute window, so flag a long reference-string trace and return to it.

Beyond the exam

Where this skill shows up in the job you're competing for — and in life.

Choosing an array traversal order

Row-major versus column-major traversal changes both cache line utilisation and bank distribution, which is why the same loop nest can differ in speed by a large factor.

Sizing a working set to fit in cache

Blocking or tiling a matrix computation is the direct application of converting capacity misses into hits by keeping the active data smaller than the cache.

Padding a structure to avoid conflicts

Adding a field or an array dimension to break an unfortunate power-of-two stride is a standard fix for conflict misses in performance-sensitive code.

Reading a processor's cache specification

Size, associativity, block size and the write policy together determine the address split and the overhead, all of which follow from this chapter's arithmetic.

Where else this topic is tested

Prepare once, score in every exam that asks it.

GATE DALow overlap — memory hierarchy is not a major component of that paper
UGC NET Computer ScienceHigh overlap — cache mapping, replacement policies and hit ratio calculations are examined as direct recall and short computation
ISRO / BARC / DRDO computer science papersVery high overlap — address splits, AMAT, Belady's anomaly and interleaving are recurring MCQ and numerical topics

Questions aspirants ask

Pulled from the Q&A community and mentor sessions.

Work outward from the block size and finish with a check. The offset field selects a byte within a block, so its width is the base-two logarithm of the block size in bytes. Next compute the number of lines, which is the cache data size divided by the block size. Then compute the number of sets, which is the line count divided by the associativity — this is the step most often skipped, and skipping it makes a set-associative cache look direct-mapped. The index width is the base-two logarithm of the set count. The tag is everything left over. Finally, add the three widths and confirm they equal the full address width. That check takes a few seconds and catches virtually every arithmetic slip, because an error in any one field shows up as a total that does not match. Two refinements matter for real questions. If the machine is word-addressable rather than byte-addressable, the offset counts words rather than bytes, and the block size must be expressed in the same unit. And if the question asks for storage overhead rather than field widths, remember that each line stores its tag plus a valid bit, plus a dirty bit if the cache is write-back, and that halving the block size doubles the line count and therefore roughly doubles the overhead.

It tells you which design change would help, which is the entire point of classifying a miss at all. A compulsory miss is the first reference to a block, and no cache organisation avoids it: the data has never been fetched, so it cannot be present. Only larger blocks or prefetching help, both of which bring in neighbouring data before it is requested, which is a bet on spatial locality. A capacity miss occurs because the program's working set is larger than the cache can hold, so blocks are evicted before being reused even with perfect placement. Only a larger cache helps; associativity does nothing, since there was genuinely no room. A conflict miss occurs when a block is evicted even though the cache had free space elsewhere, because the mapping restricted where it could go. Higher associativity is the fix, and a fully associative cache has none by definition. The diagnostic procedure follows directly. Simulate the reference stream on an infinite cache to count compulsory misses. Simulate on a fully associative cache of the same size to count compulsory plus capacity. The remainder, when simulating the actual organisation, is conflict. In practice a cache dominated by conflict misses is the easiest to fix, since raising associativity from direct-mapped to two-way typically removes most of them at modest cost.

Because they differ by a large factor and substituting one for the other in the AMAT formula produces wildly wrong answers. A local miss rate measures how a level performs on the traffic it actually sees: misses at that level divided by accesses to that level. A global miss rate measures how often a processor access ends up going that deep: misses at that level divided by all processor accesses. For a first-level cache the two coincide, since every access reaches it. For a second-level cache they diverge sharply, because only first-level misses reach it at all. A typical case has an L1 miss rate of 5 per cent and an L2 local miss rate of 30 per cent, giving an L2 global miss rate of 0.05 times 0.30, which is 1.5 per cent. The local rate looks alarming and the global rate looks excellent, and both describe the same system. The reason the L2 local rate is high is that L1 has already absorbed all the easy accesses, so the traffic reaching L2 is precisely the hard traffic. In the nested AMAT formula, each level's rate must be the local one, because it multiplies only the accesses that reach that level. Substituting a global rate there double-counts the filtering that the higher level already performed, and understates the deeper level's contribution by roughly the factor of the higher level's miss rate.

Because FIFO's eviction decision depends on load order rather than usage, and changing the frame count changes which blocks happen to be oldest at each moment. The contents of an n-frame FIFO cache are not necessarily a subset of the contents of an n plus 1 frame cache, so a block present in the smaller cache can be absent from the larger one at exactly the moment it is referenced. LRU and the optimal policy do not have this problem, and the reason is structural rather than accidental. Both are stack algorithms, meaning their contents satisfy the inclusion property: with any number of frames, LRU holds precisely the most recently referenced blocks, so the n-frame contents are the top n of a single recency ordering and the n plus 1 frame contents are the top n plus 1. The first is contained in the second by construction, so any hit with n frames is also a hit with n plus 1, and the miss count can only fall as frames are added. The practical significance is limited but the examinable significance is not. Real systems rarely use pure FIFO, and the reference strings that trigger the anomaly are contrived. But the property is a clean way to test whether a candidate understands why LRU's dependence on usage rather than load order is what makes it well-behaved, and it appears regularly in both the cache and the page-replacement contexts.

Because the bank is selected by a small field of the address, and a stride that is a multiple of the bank count leaves that field unchanged. Under low-order interleaving, the bank index comes from the address bits immediately above the within-access offset, so consecutive accesses walk through the banks in turn and all banks stay busy. That gives close to n times the bandwidth of a single bank with n banks, which is the whole reason interleaving exists. Now suppose a program accesses every fourth word in a system with four banks. Advancing by four words advances the bank index by four, which is zero modulo four, so every access lands in the same bank. The other three sit idle, and the achieved bandwidth collapses to single-bank speed despite identical hardware. Nothing is broken; the addresses simply never leave one bank. This is a real and frequently encountered effect. Traversing a two-dimensional array along the wrong axis produces exactly such a stride, which is one reason row-major and column-major traversal can differ in speed by a large factor even when the cache behaviour is similar. The classic remedy is to pad the array's inner dimension by one element, which makes the stride co-prime with the bank count and restores full distribution. High-order interleaving inverts the picture entirely: consecutive addresses share a bank, so sequential access gains nothing, but several independent processes working in separate regions land in different banks and proceed concurrently.
Header Logo