ADVERTISEMENT
Responsive Ad Unit • Systems Architecture & Low-Level Engineering

Module 8 — Cache Memory (L1, L2, L3)

Learning Objectives

After completing this module, you should be able to answer:

  • Why do we need cache?
  • Why is RAM slow?
  • What is cache memory?
  • What are L1, L2, and L3 caches?
  • What is cache locality?
  • What is a cache line?
  • How does the CPU search the cache?
  • What is a cache hit?
  • What is a cache miss?
  • What are direct-mapped, set-associative, and fully associative caches?
  • What are write-through and write-back caches?
  • What is cache coherence?
  • Why is cache important in embedded systems?

1. Why Do We Need Cache?

Imagine a CPU running at 3 GHz.
That means:
3 Billion cycles/second

Now imagine RAM takes about 60–100 nanoseconds to return data (actual values vary by system).
At 3 GHz:
1 clock cycle ≈ 0.33 ns

If RAM access takes 90 ns:
90 / 0.33 ≈ 270 CPU cycles

The CPU may have to wait hundreds of cycles for a RAM access.
Without cache:

CPU
↓
Wait
↓
Wait
↓
Wait
↓
RAM Returns Data

Most of the CPU would be idle.

Real-Life Analogy

Imagine you are cooking.

  • Warehouse = SSD
  • Kitchen Cabinet = RAM
  • Kitchen Table = Cache
  • Your Hands = Registers

Would you go to the warehouse for every spoon?
No.
You keep frequently used items on the table.
That's exactly what cache does.

Memory Hierarchy

Fastest
Registers
↓
L1 Cache
↓
L2 Cache
↓
L3 Cache
↓
RAM
↓
SSD
↓
HDD
Slowest

The closer the memory is to the CPU, the faster—and usually smaller—it is.

2. What is Cache?

Cache is small, very fast memory located on or very close to the CPU.
Purpose:
Store recently or frequently used data.

Instead of

CPU
↓
RAM

we have

CPU
↓
L1 Cache
↓
L2 Cache
↓
L3 Cache
↓
RAM

If the data is found in a cache, the CPU avoids a slower RAM access.

3. L1 Cache

The fastest cache.

Characteristics:

  • Smallest
  • Fastest
  • Private to each CPU core

Example:

CPU Core
↓
L1 Cache
↓
Registers

Typical size (varies by processor):

  • 32 KB Instruction Cache
  • 32 KB Data Cache

Often split into:

  • L1I (Instruction Cache)
  • L1D (Data Cache)

4. L2 Cache

Larger than L1.
Slightly slower.
Often private to each core (architecture-dependent).

Example:

CPU
↓
L1
↓
L2
↓
RAM

Typical size:

  • 256 KB
  • 512 KB
  • 1 MB

(varies widely)

5. L3 Cache

Largest on-chip cache.
Usually shared by multiple cores.

Example

Core1
↓
L1
↓
L2
Core2
↓
L1
↓
L2
↓
L3

Typical size:

  • 8 MB
  • 16 MB
  • 32 MB
  • or more.

Complete Cache Hierarchy

CPU
Registers
|
L1
|
L2
|
L3
|
RAM

6. How Cache Works

Suppose CPU wants

a = array[100];

Step 1
CPU checks
L1
If found
Done.

If not
↓
Check
L2

If not
↓
Check
L3

If not
↓
RAM

This sequence is automatic and managed by hardware.

7. Cache Hit

Suppose
CPU wants
Variable X

Already present
L1 Cache

Result

CPU
↓
L1
↓
Data Found

This is a cache hit.
Fast.

8. Cache Miss

Suppose
Data is not in L1.

CPU
↓
L1
×
↓
L2
×
↓
L3
×
↓
RAM
↓
Return

This is a cache miss.
Slow.

The fetched data is then typically copied into one or more cache levels for future accesses.

Cache Hit vs Miss

Cache Hit Cache Miss
Fast Slow
No RAM access RAM access required (eventually)
Better performance Higher latency

9. Why Does Cache Work?

Programs usually access memory with predictable patterns.
Two important principles explain this.

Temporal Locality

"If you used data recently, you'll probably use it again."

Example

sum += x;
sum += y;
sum += z;

Variable
sum
is reused repeatedly.
Keep it in cache.

Spatial Locality

"If you accessed one memory location, you'll probably access nearby locations."

Example

array[0]
array[1]
array[2]
array[3]

Since they are contiguous, fetching one often brings nearby elements into the cache.

10. Cache Line

The CPU does not fetch one byte at a time.
It fetches a cache line.

Typical cache line size:
64 Bytes

Suppose you need
Address 1000

CPU loads
1000, 1001, 1002, ..., 1063
All 64 bytes.
This exploits spatial locality.

Visualization

Cache Line
--------------------------------
1000
1001
1002
...
1063
--------------------------------

11. Cache Mapping

The cache cannot hold all of RAM.
The CPU must decide where to place each memory block.
Three common approaches:

Direct-Mapped Cache

Each memory block has exactly one possible cache location.

Example

Memory Block 1
→
Cache Slot 1
Memory Block 17
→
Cache Slot 1

Simple.
Fast.
Can suffer from frequent conflicts.

Fully Associative Cache

Any memory block can go into any cache slot.

Example

Block1
→
Anywhere
Block2
→
Anywhere

Most flexible.
Most expensive hardware.

Set-Associative Cache

A practical compromise.

Example

Set 0
Way0
Way1
Way2
Way3

A memory block maps to one set but can occupy any way within that set.

Common choices:

  • 2-way
  • 4-way
  • 8-way
  • 16-way

Most modern CPUs use set-associative caches.

12. Cache Replacement Policy

What happens when the cache is full?
One line must be evicted.

Common policies:

  • Least Recently Used (LRU): Remove the line not used for the longest time.
  • FIFO: Remove the oldest line.
  • Random: Choose a random line.

Modern CPUs often use approximations to LRU for efficiency.

13. Write Policies

Write-Through

CPU
↓
Cache
↓
RAM

Every write updates both cache and RAM.

Advantages:

  • RAM always contains the latest data.

Disadvantages:

  • More memory traffic.

Write-Back

CPU
↓
Cache
↓
Later
↓
RAM

RAM is updated only when the modified cache line is evicted.

Advantages:

  • Faster writes.
  • Lower memory bandwidth usage.

Disadvantages:

  • More complex.
  • Requires tracking modified ("dirty") cache lines.

14. Cache Coherence (Multicore)

Suppose
Core 1
Counter = 10

Core 2
also has
Counter = 10

Core 1 updates
Counter =20

Core 2 still has
10

Wrong.
The hardware must keep caches synchronized.
This is called cache coherence.

Modern processors commonly use protocols such as MESI (Modified, Exclusive, Shared, Invalid).

15. DMA and Cache (Very Important for Embedded)

This is highly relevant to your ADAS work.

Camera
↓
DMA
↓
DDR Memory

CPU
↓
Reads Image

Problem:
CPU may still have an old copy of the image in its cache.
DMA updated RAM directly.
CPU cache wasn't updated.

Result:
Old image processed.
Wrong ADAS output.

Solution:
Typical embedded software performs cache maintenance operations:

Invalidate Cache
↓
Read New Data

Or, before DMA reads data written by the CPU:

Clean (Flush) Cache
↓
DMA Reads Updated RAM

The exact operations depend on the CPU architecture and DMA direction.

ADAS Example

Camera
↓
DMA
↓
DDR
↓
CPU Cache
↓
ISP Algorithm
↓
Object Detection
↓
Display

If cache maintenance is forgotten:

  • Stale image data
  • Corrupted frames
  • Flickering
  • Incorrect detections

This is a common source of embedded bugs.

Why Cache Matters for Operating Systems

The OS:

  • Manages memory mappings.
  • Coordinates DMA with device drivers.
  • Schedules tasks across CPU cores.
  • Relies on hardware cache coherence mechanisms.
  • Uses cache-aware data structures for performance.

Interview Questions

Beginner

  • Why do we need cache?
  • Difference between cache and RAM?
  • What are L1, L2, and L3 caches?
  • What is a cache hit?
  • What is a cache miss?

Intermediate

  • Explain temporal locality.
  • Explain spatial locality.
  • What is a cache line?
  • Difference between write-through and write-back.
  • What is cache coherence?

Senior

  • Explain DMA cache coherency problems.
  • Why are cache maintenance operations required in embedded systems?
  • Direct-mapped vs set-associative cache.
  • Explain MESI at a high level.
  • Why does cache improve CPU performance?
  • How can poor data layout reduce cache efficiency?

Common Mistakes

  • ❌ Thinking cache is software-managed in general-purpose CPUs. It is primarily managed by hardware (with software involvement for special cases like DMA).
  • ❌ Assuming L3 exists on every processor. Many microcontrollers have only L1 or no cache at all.
  • ❌ Believing cache stores only instructions. Modern CPUs often have separate instruction and data caches.
  • ❌ Thinking DMA automatically updates CPU caches. It updates RAM, not cached copies.

Summary

Cache memory bridges the performance gap between the CPU and RAM. It exploits temporal and spatial locality to keep frequently used data close to the processor. Modern systems use a hierarchy of L1, L2, and L3 caches, along with sophisticated mapping, replacement, write policies, and coherence protocols. For embedded systems—especially ADAS camera pipelines—understanding cache behavior is essential for both correctness and performance.

Mini Quiz

  1. Why is cache needed?
  2. Why is RAM slower than cache?
  3. What is the difference between L1, L2, and L3 caches?
  4. What is a cache hit?
  5. What is temporal locality?
  6. What is spatial locality?
  7. Why are cache lines used instead of fetching a single byte?
  8. What is the difference between write-through and write-back?
  9. Why is cache coherence necessary in multicore systems?
  10. Why can DMA create cache coherency issues?
Knowledge Check

Concept Mastery Assessment — Module 08

Verify your conceptual understanding with 12 targeted technical assessment questions. Instant feedback and explanations are provided for every choice.

Question 1 of 12
What fundamental principle explains why CPU caching is effective despite caches being tiny fractions of main memory capacity?
Explanation
Programs exhibit temporal locality (recently accessed data is accessed again soon) and spatial locality (nearby memory locations are accessed together).
Question 2 of 12
What is the standard unit of data transfer between main memory and CPU cache?
Explanation
Caches transfer data in fixed-size blocks called cache lines (or cache blocks), typically 64 bytes wide on modern x86-64 and ARM64 systems.
Question 3 of 12
What is a 'Cold' (or Compulsory) cache miss?
Explanation
Compulsory (cold) misses occur on the first reference to a memory block, as it must be brought into the cache from lower memory tiers initially.
Question 4 of 12
In an N-way set-associative cache, how is a memory address partitioned into fields?
Explanation
Cache addresses are partitioned into: Offset (which byte within the 64-byte line), Set Index (which cache set), and Tag (to verify exact address match).
Question 5 of 12
What is the difference between Write-Through and Write-Back cache write policies?
Explanation
Write-through updates both cache and main memory synchronously. Write-back updates only the cache line and defers writing to RAM until the line is evicted.
Question 6 of 12
What is the MESI cache coherence protocol, and what do its four states stand for?
Explanation
MESI maintains multi-core cache coherence using four line states: Modified (dirty), Exclusive (clean, single-core), Shared (clean, multi-core), and Invalid.
Question 7 of 12
What performance pathology occurs when multiple CPU cores modify distinct variables that happen to reside on the same 64-byte cache line?
Explanation
False sharing occurs when independent variables share a cache line; writes by one core invalidate the line on other cores, causing performance degradation.
Question 8 of 12
What is the role of an inclusive vs exclusive multi-level cache hierarchy?
Explanation
Inclusive hierarchy ensures L3 contains all lines held in L1 and L2, simplifying snoop coherence. Exclusive hierarchy avoids duplicate data storage.
Question 9 of 12
Which cache replacement policy evicts the line that has not been accessed for the longest duration of time?
Explanation
LRU tracks usage recency and replaces the line that has gone the longest without being referenced, aligning with temporal locality.
Question 10 of 12
What is a 'hardware prefetcher' in modern processor architectures?
Explanation
Hardware stream and stride prefetchers monitor memory requests and fetch subsequent cache lines into L1/L2 cache ahead of execution to mask RAM latency.
Question 11 of 12
What typical access latencies distinguish L1 cache, L3 cache, and main DDR DRAM on modern processors?
Explanation
L1 cache is ultra-fast (~1-4 cycles / 1ns), L3 cache is intermediate (~30-50 cycles / 12ns), and main DRAM requires ~150-250 cycles (60-90ns).
Question 12 of 12
Why does traversing a large two-dimensional array row-by-row execute substantially faster in C than traversing it column-by-column?
Explanation
C arrays use row-major order. Row-wise traversal reads consecutive memory addresses, ensuring each 64-byte cache line is fully utilized before eviction.
0 / 12 (0%)
Great job! Review the concepts above and proceed when ready.
ADVERTISEMENT
Responsive Ad Unit • Technical Courses & Certifications