---
title: Critical sections and atomicity
heading: When an interrupt lands in the middle of an update
eyebrow: C8 · Lesson 28 · Critical sections and atomicity
xp: 40
---

::: hook
A main loop adds 1 to a counter in memory, and a timer interrupt adds 100 to the same counter. Both pieces of code are correct on their own. Run them together and the counter comes out thousands short, by a different amount if the timing changes slightly. Nothing is broken in either piece; the trouble is that "add 1 to a variable" is three instructions, and an interrupt can arrive between any two of them.
:::

::: play
- The main loop runs 200 times, each time reading `count`, adding 1 and writing it back. Every 23 instructions or so a timer interrupt adds 100 to `count`.
- At the end, a0 is what `count` should hold: 200 plus 100 for every tick (s0 counts them). a1 is what it holds. a2 is the difference.
- Run it. 62 ticks happened, so `count` should be 6400, but it holds 4000: the updates from 24 ticks vanished.
:::

```sim cpu
.data
count: .word 0
.text
    la s2, count
    la t0, handler
    csrw mtvec, t0
    li t0, 0x20000
    li t1, 30
    sw t1, 12(t0)        # first tick
    li t1, 0x80
    csrw mie, t1
    csrsi mstatus, 8
    li t4, 200
main:
    lw t3, 0(s2)         # read count
    addi t3, t3, 1       # add 1
    sw t3, 0(s2)         # write it back
    addi s1, s1, 1       # iterations done
    blt s1, t4, main
    csrci mstatus, 8     # no more ticks
    li t5, 100
    mul a0, s0, t5
    add a0, a0, s1       # what count should hold
    lw a1, 0(s2)         # what it holds
    sub a2, a0, a1       # lost
    ebreak

handler:
    addi sp, sp, -16
    sw t0, 12(sp)
    sw t1, 8(sp)
    lw t1, 0(s2)         # count += 100
    addi t1, t1, 100
    sw t1, 0(s2)
    addi s0, s0, 1       # ticks
    li t0, 0x20000
    lw t1, 8(t0)
    addi t1, t1, 23
    sw t1, 12(t0)        # next tick
    lw t1, 8(sp)
    lw t0, 12(sp)
    addi sp, sp, 16
    mret
show: s0, s1, a0, a1, a2
csrs: mstatus
memory: 0x1000..0x1004
speed: 200
```

::: predict
## The main loop is five instructions: `lw`, `addi`, `sw`, `addi`, `blt`. A tick can arrive just before any one of them. In what fraction of ticks is the handler's update lost?

- [ ] 1/5
- [x] 2/5
- [ ] 3/5
- [ ] None: each instruction finishes before the interrupt is taken

::: reveal
2/5. If the tick arrives just before the `addi` or the `sw`, the main loop has already read the old count. The handler adds 100 and stores it, then the main loop resumes and stores its stale value plus 1, wiping out the 100. The run lost 24 of 62 ticks, 39%.
:::
:::

::: nameit
## Race conditions

A **race condition** is a bug whose outcome depends on timing. The classic one is a **read-modify-write**: load a value, change it in a register, store it back. If something else changes the value between the load and the store, that change is overwritten, a **lost update**. Each instruction is indivisible, but the sequence isn't.

## Critical sections

A **critical section** is a stretch of code that must run without anything else touching the same data. On a single-core microcontroller the only other code is interrupt handlers, so the usual protection is to turn interrupts off for the section:

```asm
    csrci mstatus, 8    # MIE = 0: interrupts wait
    lw t3, 0(s2)
    addi t3, t3, 1
    sw t3, 0(s2)
    csrsi mstatus, 8    # MIE = 1: a waiting interrupt is taken now
```

An interrupt that arrives meanwhile stays pending and is taken as soon as interrupts come back on, so nothing is lost, only delayed. The delay is the cost: the **worst-case interrupt latency** grows by the longest critical section, so sections should be a few instructions long. Code that might be called with interrupts already off saves the old state and restores it (`csrrci t0, mstatus, 8` … `csrs mstatus, t0`) instead of turning them on unconditionally.

## Things that don't fix it

`volatile` makes the compiler do every load and store, but they're still separate instructions, so the race remains. Doing the increment "quickly" only makes the bug rarer and harder to find.

## Atomic instructions and multiple cores

With two cores, turning off interrupts on one does nothing to the other. Processors provide **atomic** instructions that read, modify and write as one indivisible operation on the bus. RISC-V's A extension has `amoadd.w` (add to memory atomically), `amoswap.w` (the basis of a lock) and the pair `lr.w`/`sc.w`: load-reserved, then a store-conditional that fails, and is retried, if anyone touched the word in between.

## Designs that need no lock

Some structures avoid the problem by giving every variable a single writer. In a **ring buffer** filled by an interrupt and emptied by the main loop, only the handler writes the head index and only the main loop writes the tail. Each side writes its data before moving its own index, and an aligned word store is atomic, so neither ever sees a half-finished update.

## Torn reads

A value wider than a word, such as a 64-bit tick counter, takes two loads to read. If the handler carries from the low word into the high word between them, the reader gets the old low word with the new high word, an error of nearly $2^{32}$ ticks. The fix is to read high, low, then high again, and repeat if the two highs differ.
:::

The same loop with the read-modify-write inside a critical section: interrupts are off for three instructions at a time, and the count comes out exact.

```sim cpu
.data
count: .word 0
.text
    la s2, count
    la t0, handler
    csrw mtvec, t0
    li t0, 0x20000
    li t1, 30
    sw t1, 12(t0)        # first tick
    li t1, 0x80
    csrw mie, t1
    csrsi mstatus, 8
    li t4, 200
main:
    csrci mstatus, 8     # interrupts off
    lw t3, 0(s2)         # read count
    addi t3, t3, 1       # add 1
    sw t3, 0(s2)         # write it back
    csrsi mstatus, 8     # interrupts on
    addi s1, s1, 1       # iterations done
    blt s1, t4, main
    csrci mstatus, 8     # no more ticks
    li t5, 100
    mul a0, s0, t5
    add a0, a0, s1       # what count should hold
    lw a1, 0(s2)         # what it holds
    sub a2, a0, a1       # lost
    ebreak

handler:
    addi sp, sp, -16
    sw t0, 12(sp)
    sw t1, 8(sp)
    lw t1, 0(s2)         # count += 100
    addi t1, t1, 100
    sw t1, 0(s2)
    addi s0, s0, 1       # ticks
    li t0, 0x20000
    lw t1, 8(t0)
    addi t1, t1, 23
    sw t1, 12(t0)        # next tick
    lw t1, 8(sp)
    lw t0, 12(sp)
    addi sp, sp, 16
    mret
show: s0, s1, a0, a1, a2
csrs: mstatus
memory: 0x1000..0x1004
speed: 200
```

::: example
## A 16 MHz microcontroller takes 12 cycles to enter an interrupt handler. Its longest critical section is 20 cycles. What's the worst-case latency, and how long could a critical section be if a sensor must be answered within 3 µs?

::: solution
1. **The worst case.** The interrupt arrives just as the critical section starts, waits 20 cycles, then takes 12 to enter:
   $$20 + 12 = 32\ \text{cycles}$$
   which is 2 µs.
2. **Cycles in 3 µs.** There are 48.
3. **The budget.** Less the 12 for entry:
   $$48 - 12 = 36\ \text{cycles}$$
4. **Who shares it.** That budget is shared by every critical section in the program, which is why they're kept to a few instructions.

**Answer:** the worst-case latency is 32 cycles, 2 µs, and critical sections may be up to 36 cycles.
:::
:::

::: example
## A 64-bit tick counter is split across two words. The handler has just carried: the count went from 0x5_FFFFFFFF to 0x6_00000000. The main loop read the low word just before the tick and the high word just after. What value did it see?

::: solution
1. **What the loop read.** The low word was 0xFFFFFFFF (old) and the high word 6 (new): 0x6_FFFFFFFF.
2. **The error.** That's $2^{32} - 1$ ticks, about 4.3 billion, too high.
3. **The fix.** Reading high, low and high again catches it: the first high was 5 and the second 6, so the loop reads all three words again and this time gets 0x6_00000000 with matching highs.

**Answer:** it saw 0x6_FFFFFFFF, about 4.3 billion ticks too high.
:::
:::

::: example
## A 16-entry ring buffer has head = 5 (where the handler writes next) and tail = 2 (where the main loop reads next). How many entries are waiting, and when is it full?

::: solution
1. **Entries waiting.** head − tail = 3, counting modulo 16, so a head that has wrapped to 1 with tail 14 also gives 3.
2. **When it's full.** The buffer is full when advancing head would make it equal tail, at 15 waiting entries: one slot always stays empty so that "full" and "empty" (head = tail) look different.
3. **Who moves what.** The handler writes the entry, then advances head; the main loop reads the entry, then advances tail. Neither needs interrupts off.

**Answer:** 3 entries are waiting, and the buffer is full at 15.
:::
:::

::: check
kind: parts
given: L = 4 | 6 | 8; w = 2 | 3; T = 100 | 1000

## A main loop of {L} instructions does a read-modify-write, and a tick arriving before any of {w} of them loses the handler's update. {T} ticks arrive at random points.

::: part
answer: w/L*100
unit: %
tolerance: 0.5%

### What fraction of the handler's updates are lost?

::: misses
- [any] The window of {w} instructions out of {L}.
:::
:::

::: part
answer: T*w/L
tolerance: 0.5%

### About how many updates are lost?

::: misses
- [any] Ticks × the fraction.
:::
:::
:::

::: check
kind: parts
given: f = 8 | 16 | 48; e = 6 | 12; c = 10 | 40 | 100

## A {f} MHz core takes {e} cycles to enter a handler, and its longest critical section is {c} cycles.

::: part
answer: (e + c)/f
unit: µs
tolerance: 0.5%

### What's the worst-case interrupt latency?

::: misses
- [e/f] The interrupt may have to wait out a whole critical section first.
- [any] Wait for the section, then enter.
:::
:::

::: part
answer: e/f
unit: µs
tolerance: 0.5%

### And with no critical sections?

::: misses
- [any] Entry alone.
:::
:::
:::

::: check
kind: asm
given: H = 0..7 int; v = 1..1000 int
setup: a1 = v
expect: mem[4100 + 4*H] = v; mem[4096] = H + 1 - 8*floor((H + 1)/8)

## `head` (at 0x1000) indexes an 8-word ring buffer `buf` (from 0x1004). Store a1 at buf[head], then advance head, wrapping from 7 to 0.

```asm starter
.data
head: .word H
buf: .space 32
.text
    ebreak
```

```asm solution
.data
head: .word H
buf: .space 32
.text
    la t0, head
    lw t1, 0(t0)
    la t2, buf
    slli t3, t1, 2
    add t3, t2, t3
    sw a1, 0(t3)
    addi t1, t1, 1
    andi t1, t1, 7
    sw t1, 0(t0)
    ebreak
```

::: right
Right. The data goes in first, then head moves, so the reader never takes a slot before it's filled.
:::
:::

::: check
kind: parts
given: N = 8 | 16 | 64; h = 1 | 2 | 3; t = 5 | 6 | 7

## A ring buffer of {N} slots has head = {h} and tail = {t}: the head has wrapped around.

::: part
answer: h - t + N*step(t - h - 0.5)
tolerance: 0

### How many entries are waiting?

::: misses
- [h - t] Count modulo {N}: the head may have wrapped.
- [any] $(h - t) \bmod N$.
:::
:::

::: part
answer: N - 1 - (h - t + N*step(t - h - 0.5))
tolerance: 0

### How many more can the handler add before it's full?

::: misses
- [N - (h - t + N*step(t - h - 0.5))] One slot always stays empty.
- [any] $N - 1$ less those waiting.
:::
:::
:::

::: check
kind: choice

## A dual-core chip runs the main loop on core 0 and the interrupt handler on core 1, and both update one counter. Core 0 turns interrupts off around its update. Why isn't that enough?

- [ ] Turning interrupts off takes too long
- [x] It only stops interrupts on core 0; core 1 can still change the counter between core 0's load and store
- [ ] The counter needs to be declared volatile
- [ ] Cores can't share memory

::: misses
- [1] It's one instruction. The problem is what it doesn't stop.
- [3] volatile keeps the loads and stores, but they're still separate instructions.
- [4] They do share it; that's the trouble.
:::
:::

::: check
kind: derivation
vars: D = 0.000001..0.001, e = 1..100, f = 1000000..500000000

## An interrupt must be answered within D seconds on a clock of f, and entering the handler takes e cycles.

::: step
answer: D*f

### How many cycles are there in D?
:::

::: step
answer: D*f - e

### How long may the longest critical section be, in cycles?
:::

::: right
Right. Every critical section in the program has to fit in what's left after the entry.
:::
:::

::: check
kind: choice

## An interrupt handler increments a 64-bit tick count stored as two words. Which way of reading it in the main loop always gets a consistent value without turning interrupts off?

- [ ] Read the low word, then the high word
- [ ] Read the high word, then the low word
- [x] Read high, low, then high again, and start over if the two highs differ
- [ ] Read the low word twice and keep the larger

::: misses
- [1] A carry between the two loads pairs the old low word with the new high word.
- [2] The same carry can still fall between them, the other way round.
- [4] The low word alone can't tell you whether the high word moved.
:::
:::

::: explain
## Why does turning interrupts off around a read-modify-write fix a lost update on a single-core microcontroller, and what does it cost?

::: model
The update goes wrong only when the handler runs between the load and the store, because then the store writes back a value computed from stale data. With interrupts off, a tick that arrives in that window isn't taken; it stays pending, and the processor takes it as soon as interrupts come back on, after the store. So the handler's change is applied to the updated value and nothing is lost. The cost is latency: any interrupt may now wait for the longest critical section before its handler starts, which is why the sections are kept to a few instructions, and why on a multicore chip, where another core can still interfere, atomic instructions are needed instead.
:::
:::

::: practice
::: check
given: L = 5 | 7 | 10; w = 2 | 3
answer: w/L*100
unit: %
tolerance: 0.5%

## A {w}-instruction window in a {L}-instruction loop. What share of ticks lose their update?

::: misses
- [any] $w/L$.
:::
:::

::: check
given: f = 16 | 72; e = 12 | 20; c = 24 | 60
answer: (e + c)/f
unit: µs
tolerance: 0.5%

## {f} MHz, {e}-cycle entry, {c}-cycle critical section. Worst-case latency?

::: misses
- [any] $(e + c)/f$.
:::
:::

::: check
given: N = 16 | 32; h = 2 | 9; t = 4 | 12
answer: h - t + N*step(t - h - 0.5)
tolerance: 0

## Ring buffer of {N}, head {h}, tail {t}. Entries waiting?

::: misses
- [any] $(h - t) \bmod N$.
:::
:::
:::
