Section 6.11

Interrupt

Definition

An interrupt is a signal, usually from a hardware device, that makes the processor suspend the code it is running, run a routine called an interrupt handler §6.12, and then resume the suspended code exactly where it stopped. A device uses an interrupt to report an event, such as a received byte or an expired timer, soon after it happens. Software then does not need polling, which means checking the device again and again. Interrupts are asynchronous: one can arrive between almost any two instructions of the suspended code.

The idea

A serial port of the kind called a UART §6.23 (universal asynchronous receiver-transmitter) receives text at 115200 bits per second. Each byte takes 10 bit times on the wire, 8 data bits plus a start bit and a stop bit, so a new byte arrives every 10/11520010 / 115200 seconds, about 86.8 microseconds. Suppose the port holds one received byte. Software that polls must look at the port at least every 86.8 microseconds, whatever else it is doing, or bytes are overwritten and lost, and most of those looks find nothing. With an interrupt, the port itself tells the processor when a byte is there, and the processor spends no time looking in between.

A doorbell is a fair picture: nobody needs to walk to the door every minute, because the bell calls them when a visitor comes. The picture stops at one important point. A person decides when to answer the bell; the processor does not. Unless the running code has blocked the interrupt, the processor stops that code between two instructions and runs the handler at once. So even a processor with one core runs two flows of control that interleave at points neither chose, which is a form of concurrency §9.1. Any data that both the handler and the interrupted code use can be seen half-updated.

How it works

This sequence follows Arm Cortex-M processors, whose interrupt controller is the NVIC §6.13 (Nested Vectored Interrupt Controller). Other processors differ in detail, not in principle.

  1. Request. The device sets a status flag in one of its registers and raises its interrupt request (IRQ) signal. The interrupt controller records the request as pending.

  2. Decision. The controller lets the request through when the interrupt is enabled, is not masked (blocked for the moment, see below) and has a higher priority than the code now running. Otherwise the request stays pending.

  3. Entry. The processor finishes the current instruction; a long instruction that loads or stores many registers can instead be abandoned and restarted, or paused and continued, afterwards. The hardware saves eight registers, 32 bytes, onto the current stack, the memory area that holds a routine’s saved values: R0 to R3, R12, the link register §4.45 LR, the program counter §2.9 PC and the status register xPSR. It saves more if the interrupted code was using floating-point registers. It reads the handler’s address from the vector table §6.14, the table of handler addresses, at the entry for this interrupt. On a Cortex-M4 §6.3 whose memory adds no wait cycles, the handler’s first instruction starts 12 clock cycles after the request, if nothing else delays it.

  4. Handler. The interrupt service routine (ISR) runs. It finds out what happened, clears the device’s flag, and does or arranges the necessary work.

  5. Return. The handler returns. The hardware restores the saved registers, and the interrupted code continues without noticing anything except the lost time. If another interrupt is pending, the processor goes straight into its handler, which Arm calls tail-chaining.

Three controls decide when an interrupt may run.

A pending request is a single bit, not a counter. If a device requests the same interrupt three times before the handler runs, the handler runs once, so a handler that must count events reads a count kept by the device, not the number of times it ran. A device that keeps its request signal active until software clears its flag makes the interrupt pending again as soon as the handler returns, if the handler did not clear the flag. Arm uses the word exception for every event of this kind, including faults and the supervisor call instruction; an interrupt is an exception requested from outside the processor core.

A thread is an independent sequence of instructions that the scheduler of an operating system starts, stops and resumes. A mutex §9.5 is a lock that threads take in turn: a thread that finds the mutex held waits until the holder releases it. The interrupt controller knows nothing about mutexes, so a thread that holds a mutex is interrupted like any other code. Nor can a handler wait for the mutex: the holder is the very thread that the handler interrupted, and on a single core that thread cannot run again until the handler returns. A handler that waited would wait forever, a deadlock §9.14. Kernels such as the Zephyr RTOS §6.33 (real-time operating system) and FreeRTOS, another widely used real-time operating system, therefore do not allow a handler to take a mutex. Data shared between a thread and a handler needs one of two other protections, both shown in the worked example: the thread masks the interrupt while it changes the data, or the data is changed so that every state the handler can see is valid.

Worked example

A thread and a receive handler share a record with two fields: buf, the address of a byte array §14.5, and len, the number of bytes that array holds. The handler copies len received bytes into buf. At first buf points to array A of 4 bytes and len is 4. The thread wants to switch to array B of 8 bytes. It takes a mutex, runs two lines, and releases the mutex:

  1. len = 8;

  2. buf = B;

The receive interrupt arrives after line 1 and before line 2. The handler reads buf equal to A and len equal to 8, a pair that was never meant to exist. It writes 8 bytes into the 4-byte array A, so 8−4=48 - 4 = 4 bytes land beyond its end, on whatever variable follows A in memory: a buffer overflow §4.4. The mutex changed nothing, because the handler never asks for it. Swapping the two lines does not repair the design. The handler could then see B with length 4, which is harmless here, but the same code switching back from B to A would expose A with length 8 again. The compiler may also reorder two ordinary stores, so the order of the lines in the source is not a guarantee.

Repair 1: mask the interrupt. The thread blocks the receive interrupt, or all interrupts, around the two stores and unblocks it afterwards; in Zephyr, irq_lock() and irq_unlock() do this for all interrupts. The handler then sees either the old pair or the new pair. The price is latency: a request that arrives during the masked stretch waits until it ends. If the stretch takes 20 clock cycles on a processor running at 64 MHz (megahertz, millions of cycles per second), the extra delay is at most 20/(64×106)20 / (64 \times 10^{6}) seconds, about 0.31 microseconds. A masked stretch of 2 milliseconds would be a different matter: the UART above would receive 2000/86.8≈23.02000 / 86.8 \approx 23.0 bytes meanwhile, and could lose all but one of them.

Repair 2: publish a complete record. Keep two records, each with a buf and a len, and one shared variable cur that holds the address of the record in force. The thread fills in the record that is not in force, then stores its address into cur with a single store. On Cortex-M a store of one aligned 32-bit word cannot be split by an interrupt, so the handler, which reads cur once and then uses only that record, sees the old record or the new one, never a mixture. In the program the store must be an atomic operation §9.8 as well, for example atomic_store from C11, the 2011 edition of the C language standard [78], so that the compiler neither splits it nor moves the field stores after it. On a single core, once the thread has executed the store, any handler that read the old address has already returned, because a handler runs to completion before the interrupted thread continues. The thread may therefore reuse the old record at the next update, provided the handler never keeps the address after it returns.

Stated precisely

Take one processor core and one thread TT that shares an object with the handler HH of interrupt II. Suppose II is enabled, not masked, and of a priority high enough to be taken while TT runs. Then HH may run between any two instructions of TT, and HH runs to completion before TT executes its next instruction, apart from handlers of still higher priority that interrupt HH and also complete first. A mutex taken only by threads places no condition on when II is taken.

The sharing is safe when every state of the object that HH can observe is a state that HH handles correctly. Two conditions each give this.

  1. Masking. II is masked from the first to the last instruction of each update by TT, and every masked stretch is short enough that the added delay still lets HH meet its deadline.

  2. Single publication. TT changes the object only by preparing a complete new version that HH cannot yet reach and then making it reachable with one atomic store, with compiler ordering that keeps the preparation before the store; HH reads the published address once.

With more than one core, neither condition suffices on its own. Masking acts only on the core that masks, so code on another core needs a spinlock §9.7 or another cross-core protocol as well, and the publication needs a memory barrier §4.37 so that the other core sees the record’s fields before the new address.

Limits and common mistakes

Masking delays every masked interrupt by up to the length of the masked stretch. Long stretches miss deadlines and lose data, so a masked stretch should cover a few instructions, never a loop of unknown length or a call that waits.

Masking stops the processor from taking interrupts. It does not stop a direct memory access §4.36 (DMA) controller, which copies data without the processor, nor code on another core, nor the non-maskable interrupt.

Disabling one interrupt protects only against that interrupt’s handler. Another handler that touches the same data still runs.

Requests merge while pending, so the number of handler runs is not the number of events.

A handler that does not clear its device’s flag runs again immediately after it returns, again and again, and the threads never run. This is called an interrupt storm.

Declaring a shared variable volatile in C makes the compiler read and write it in memory on every use, but it does not make an update of two fields atomic.

Interrupts add variable delay to every thread. The timing analysis of a real-time system §6.34 must include the worst-case execution time §9.33 of every handler that can run.

Questions answered

Can an interrupt access an object while an update holds a thread mutex?

Yes. A mutex used only by threads does not stop an interrupt: the interrupt controller does not know that the mutex exists, so the interrupt handler can run while a thread holds the mutex, in the middle of the thread’s update, and see the object half-changed. The handler cannot take the mutex either. On a single core, the thread that holds the mutex cannot run again until the handler returns, so a handler that waited for it would wait forever; kernels such as Zephyr forbid it.

To protect an object shared with an interrupt handler, use a protection that acts on the interrupt. Either the thread masks that interrupt, or all interrupts, for the few instructions of the update, or the thread prepares a complete new version of the object and publishes it with one atomic store, so that the handler sees either the old or the new version. Check separately for agents that an interrupt mask does not stop: a direct memory access controller, another processor core, and the non-maskable interrupt.

Related entries: Concurrency versus parallelism (§9.1), Critical section (§9.4), Direct memory access (DMA) (§4.36), Interrupt service routine (ISR) (§6.12), NVIC (§6.13), Mutex (§9.5), Atomic operation (§9.8), Buffer overflow (§4.4). Further reading: [78, 81, 83, 176].