C828 of 55
0 XP
  1. Hook
  2. Play
  3. Predict
  4. Name it
  5. Check
  6. Explain

C8 · Lesson 28 · Critical sections and atomicity

When an interrupt lands in the middle of an update

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.

  • 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.

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?

Name it

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:

    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 232 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.

Worked 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?

Show the solution
  1. The worst case. The interrupt arrives just as the critical section starts, waits 20 cycles, then takes 12 to enter: 20+12=32cycles which is 2 µs.
  2. Cycles in 3 µs. There are 48.
  3. The budget. Less the 12 for entry: 48−12=36cycles
  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.

Worked 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?

Show the 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 232−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.

Worked 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?

Show the 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

A main loop of 6 instructions does a read-modify-write, and a tick arriving before any of 2 of them loses the handler's update. 1000 ticks arrive at random points.

(a)

What fraction of the handler's updates are lost?

(b)

About how many updates are lost?

Check

A 16 MHz core takes 6 cycles to enter a handler, and its longest critical section is 100 cycles.

(a)

What's the worst-case interrupt latency?

Write units the way you normally would: 1.5 µs, 1500 ns and 0.0015 ms are the same answer.

(b)

And with no critical sections?

Check

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.

RISC-V RV32IM (base integer plus multiply and divide). End your program with ebreak. Tab indents; press Esc and then Tab to move on.

Check

A ring buffer of 16 slots has head = 1 and tail = 7: the head has wrapped around.

(a)

How many entries are waiting?

(b)

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

Check

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?

Check

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

Step 1

How many cycles are there in D?

Type it the way you would write it, like 3sin(2πft) or 3*sin(2*pi*f*t). Angles can be in radians or carry a degree sign, like 45°.

Check

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?

Explain why

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

Practice

Keep practicing

7 kinds of problem on this topic, dealt one at a time with new numbers every time, for as long as you like.