Section 6.12

Interrupt service routine (ISR)

Definition

An interrupt service routine (ISR), also called an interrupt handler, is the routine that the processor runs when a particular interrupt §6.11 is taken. It runs in interrupt context: not as a thread, a sequence of instructions that the scheduler starts and stops, but on top of the code the interrupt suspended, which cannot continue until the ISR returns. An ISR serves the device that raised the interrupt: it clears the request, saves data that would otherwise be lost, and hands longer work to thread code.

The idea

While an ISR runs, everything below it waits. Every thread waits, even the most urgent one, because threads run only when no ISR is running. Every interrupt of the same or lower priority waits, because the interrupt controller holds it pending. And an ISR cannot wait for anything itself. It is not a thread, so the scheduler cannot set it aside and run something else meanwhile. If an ISR waited for a thread to release a lock or to finish a write, that thread could not run, and the system would stop.

So the work is split. The ISR does the part that cannot wait: it reads the data that the next event would overwrite and quiets the device. A thread does the rest later: parsing, computing, writing to flash memory §6.6, sending replies. A shop counter works this way. The clerk takes the order and the payment in a minute and passes a slip to the kitchen, instead of cooking each meal while the queue at the counter grows. The picture stops at one point. The kitchen is a thread that the scheduler runs by priority, so an order may wait behind more urgent work, and the slip must carry everything the cook needs, because the counter is cleared for the next customer. Linux calls the two parts the top half and the bottom half.

How it works

  1. Find the cause. Read the device’s status register to learn which event happened; one interrupt often reports several kinds of event.

  2. Acknowledge. Clear the device’s interrupt flag in the way the device’s manual prescribes; some flags clear when written, others when a data register is read. If the flag stays set, the request stays active and the ISR runs again as soon as it returns.

  3. Capture. Copy the data that the next event would overwrite, such as a received byte or a status word, into storage that outlives the ISR. Common choices are a ring buffer §14.15, a fixed-size array §14.5 used in a circle, into which the ISR writes and from which a thread reads; a message queue that copies each message into its own storage; and the fields of a work item §6.36.

  4. Signal. Tell the deferred code that there is work, using only kernel calls that never wait. In the Zephyr RTOS §6.33 (real-time operating system), such calls include k_sem_give(), which releases a semaphore §9.6, a counter on which a thread can wait; k_msgq_put() with the timeout §9.34 K_NO_WAIT; and k_work_submit(), which hands a work item to the thread of a Zephyr workqueue.

  5. Return. If the signal made ready a thread that is more urgent than the interrupted thread, the kernel switches to that thread when the ISR returns, not during it. Cortex-M kernels commonly perform this switch in the exception PendSV, set to the least urgent priority, so that the switch runs only after every pending ISR has finished.

  6. Deferred work. The worker thread runs when the scheduler chooses it. It may take locks, wait for a flash write, allocate memory and take as long as it needs, because anything more urgent can still interrupt or preempt it.

Code in an ISR follows rules that thread code does not.

Worked example

A radio interrupt reports a received packet, and handling the packet takes 500 microseconds of parsing. A UART §6.23 (universal asynchronous receiver-transmitter), a serial port, receives a byte every 86.8 microseconds (10 bits at 115200 bits per second) and holds one unread byte; a byte that arrives before the previous one was read is lost. The UART’s ISR has the same priority as the radio’s ISR, so neither can interrupt the other. When the radio’s request arrives, no ISR is running and interrupts are not masked, so the radio ISR starts at once.

Design A: all work in the ISR. The radio ISR copies the packet in 4 microseconds and parses it for 500, so it occupies the processor for 4+500=5044 + 500 = 504 microseconds, and the UART’s ISR waits that long. During 504 microseconds at least ⌊504/86.8⌋=5\lfloor 504 / 86.8 \rfloor = 5 bytes arrive, where ⌊x⌋\lfloor x \rfloor means xx rounded down, since 5×86.8=4345 \times 86.8 = 434 and 6×86.8=520.86 \times 86.8 = 520.8. If the UART was empty when the wait began, it holds the first of these bytes and at least 4 are lost.

Design B: defer the parsing. The radio ISR copies the packet into a work item in 4 microseconds, submits the work item in 2 microseconds and returns. It occupies the processor for 4+2=64 + 2 = 6 microseconds, less than one byte time of 86.8 microseconds, so the UART loses nothing. The worker thread waits 90 microseconds behind a more urgent thread and then parses for 500 microseconds. Ignoring the few cycles of interrupt entry and exit, the packet is fully handled 6+90+500=5966 + 90 + 500 = 596 microseconds after the request, which is 596−504=92596 - 504 = 92 microseconds later than in design A. Deferral did not make the packet faster. It cut the time during which the radio ISR blocks everything else from 504 to 6 microseconds.

A lifetime mistake. A first version of design B kept a 16-byte packet summary in a local variable of the ISR, which lives on the stack, and put only the variable’s address in the work item. The ISR returned, the next interrupt reused the same stack bytes, and the worker read whatever lay there by then: a dangling pointer §4.1, an address whose object no longer exists. The repair copies the 16 bytes into the work item, or into a message queue slot, which stays valid until the worker has finished with it.

A capacity check. Deferral needs the worker to keep up on average. If packets arrive every 400 microseconds and each needs 500 microseconds of work, then in every 2000 microseconds 2000/400=52000 / 400 = 5 packets arrive and only 2000/500=42000 / 500 = 4 are processed. The backlog grows by one packet every 2 milliseconds, so a queue of 16 entries is full after about 16×2=3216 \times 2 = 32 milliseconds, and from then on the ISR must drop packets.

Stated precisely

Split the time from the interrupt request to the end of the deferred work into four parts. Let LL be the interrupt latency: the time from the request to the ISR’s first instruction. The latency LL includes the time the request stays pending while the interrupt is disabled or masked, the time it waits while ISRs of equal or higher priority run, and the few cycles of interrupt entry. Let CisrC_{\mathrm{isr}} be the ISR’s occupancy: the time from the ISR’s first instruction to its return, during which every thread and every interrupt of equal or lower priority waits. Let QQ be the total time, between the ISR’s return and the end of the deferred work, during which that work waits instead of running: in the queue, behind more urgent threads and behind ISRs. Let CwC_{\mathrm{w}} be the worker’s own processing time. The response time §9.32 of the event, from the interrupt request to the end of the deferred work, is R=L+Cisr+Q+Cw.R = L + C_{\mathrm{isr}} + Q + C_{\mathrm{w}}. Deferral lowers CisrC_{\mathrm{isr}}, the delay that the ISR imposes on everything else. It does not lower RR, and it usually raises RR by QQ plus the cost of the signal.

An ISR design is correct when four conditions hold.

  1. Every call the ISR makes is one that its kernel documents as safe in an ISR, and none of them waits.

  2. Every piece of data the ISR hands to deferred work stays valid until the worker has finished with it.

  3. The deferred work keeps up: over the long run, events arrive more slowly than the worker completes them, and the queue holds the longest burst that can occur.

  4. If the event must be handled by a deadline, bounds on LL, CisrC_{\mathrm{isr}}, QQ and CwC_{\mathrm{w}} are known, and their sum stays within the deadline. The bound on LL depends on the longest stretch with the interrupt disabled or masked and on every ISR of equal or higher priority; the bound on QQ depends on the queue, on every more urgent thread and on every ISR.

Limits and common mistakes

Deferral moves work; it does not remove it. The total processor time stays the same, plus the cost of signaling and switching threads.

A shared worker causes head-of-line blocking §9.19: one long work item delays every item behind it in the same queue, including urgent ones. Zephyr’s system workqueue serves many parts of the system at once, so time-critical work may need a workqueue thread of its own.

A full queue needs a policy: drop the new event, drop the oldest, or count the losses. A signaling call that fails because the queue is full returns an error, and the ISR must check it.

Getting the acknowledgment wrong either loses events or makes the ISR run in an endless loop. The correct way to clear a flag is set by each device’s manual.

Not every ISR should defer. Work of a few microseconds costs less in the ISR than the signal and the thread switch.

Printing or logging inside an ISR is a common way to make an ISR long, because formatting text can take far longer than the rest of the ISR.

Questions answered

Why defer expensive work from an ISR to a thread?

Expensive work is deferred from an interrupt service routine (ISR) to a thread because, while an ISR runs, every thread and every interrupt of equal or lower priority must wait, and an ISR is not allowed to wait for anything itself. A long ISR therefore delays other interrupts until their devices lose data, delays even the most urgent thread, and cannot use blocking operations such as taking a mutex, sleeping or waiting for a flash write. A thread can do all of these, and the scheduler can preempt it when something more urgent arrives.

The ISR keeps the part that cannot wait: reading the data that the next event would overwrite and clearing the device’s request. It copies what the thread will need into storage that outlives the ISR and signals the thread with a call that never waits. Deferral does not make the event itself finish sooner, because the deferred work now also waits in a queue and behind more urgent threads. Its response time must therefore be checked against any deadline, the queue must be large enough for bursts, and the worker must be fast enough to keep up on average.

Related entries: Asynchronous completion (§9.28), Head-of-line blocking (§9.19), Response time versus execution time (§9.32), Borrowed pointer (§4.3), Interrupt (§6.11), Zephyr workqueue (§6.36), Ring buffer (§14.15), Object lifetime (§4.1). Further reading: [15, 176].