</>EmbeddedInterview

What is cache coherency?

MediumARM Architecture

Short answer: Hardware keeps coherent copies of a cache line consistent across cores. A writer typically obtains ownership and invalidates other copies; a later coherent reader obtains the updated value. DRAM need not be updated immediately.

Core 0a = 20Coherency fabricInvalidateCore 1Reload = 20
/* Use proper synchronization for shared data. */
smp_store_release(&flag, 1);
/* Other CPU: smp_load_acquire(&flag) */

1. Without coherency: Core 0 and Core 1 both cache a = 10. Core 0 writes 20; without coordination, Core 1 could keep reading stale 10.

2. With coherency: Core 0 requests write ownership, other copies are invalidated, and a later coherent read obtains 20 from the appropriate cache or memory. This works at cache-line granularity.

MESI state Meaning
M Modified, dirty and exclusive
E Exclusive and clean
S Shared and clean
I Invalid

MESI is an illustrative protocol; real Arm implementations vary.

3. CPU vs DMA: Non-coherent DMA may require cleaning before a device reads CPU-written buffers and invalidating stale CPU copies before reading device-written data. Linux DMA APIs manage these transitions.

4. Limitation: Coherency does not make a++ atomic or enforce ordering between different addresses.

Interview takeaway: Coherency keeps cached copies consistent; synchronization and memory barriers solve separate ordering and atomicity problems.

Cache-line ownership: practical multicore example

Assume an illustrative 64-byte cache line contains two variables. Initially both cores cache the line in shared state. Core 0 writes one variable; the coherency protocol obtains exclusive write ownership and invalidates other copies. Core 1's next read of a variable on that line requests a valid copy. The line may be supplied directly by another cache even while DRAM still contains the old value.

If the cores continuously update different variables in the same cache line, ownership can repeatedly move between cores: this is false sharing. Separating hot per-core variables into different cache lines can improve throughput, at the cost of extra memory. Verify actual line size and measure the effect.

Coherence of a location does not impose every desired ordering relationship across locations. Publishing a flag and associated data still requires release/acquire or another synchronization protocol. A C data race remains undefined even on coherent hardware. Non-coherent devices require a separate DMA ownership/cache-maintenance strategy.