The idea: urgent work cuts in, the stack remembers where to go back

A microcontroller has several things that can interrupt it: a timer, a button on a pin, a byte arriving on the serial port. Each one has an interrupt service routine (ISR) and a priority level. On this page level 0 is the most urgent and main runs below every level. When a request comes in, the CPU asks one question at the end of each instruction: is this more urgent than what I am doing now? If yes, it saves where it was and jumps to the ISR, even if it is already inside another ISR. That is nesting. If no, the request stays pending until the CPU drops to a lower level. The page counts every cycle, so you can see what each step costs. How a PC's interrupt controller and iret work is on interrupt-driven I/O; how a MIPS CPU saves EPC and Cause is on MIPS exceptions; why to use interrupts instead of polling is on embedded I/O.

The vector table at address 0x0000 with four entries: 0x0000 Reset to main at 0x0100, 0x0002 TIMER to TIMER_ISR at 0x0200 with priority 1, 0x0004 BUTTON to BUTTON_ISR at 0x0240 with priority 2, 0x0006 UART to UART_ISR at 0x0280 with priority 0. On the right a ladder of levels: 0 UART most urgent at the top, then 1 TIMER, 2 BUTTON, and main at the bottom. A request preempts only if it sits higher on the ladder than the level the CPU runs at
The vector table says where each handler is; the priority ladder says who may cut in on whom.

The vector table

At address 0x0000 the chip keeps the vector table, one entry per source. Entry 0x0000 is reset: after power-on the CPU starts there, and it leads to main. The page's other entries are TIMER at 0x0002, BUTTON at 0x0004 and UART at 0x0006. Each holds the address of that source's ISR. On the 8051 and on AVR chips each entry is a short jump instruction. On ARM Cortex-M each entry is a plain address, and the very first word is the initial stack pointer, loaded before the reset handler runs (see Cortex-M exceptions).

What taking an interrupt costs

The source sets its pending flag. The CPU only looks at the flags between instructions, so it first finishes the current one. Then the hardware does the entry: it pushes the return address PC and the status register SR (with the global enable bit I and the current level L) on the stack, reads the vector and jumps. Here that is 6 cycles. The ISR's first instructions (its prologue) save the registers it will use; here PUSH R0. At the end, POP R0 and RETI undo it all: RETI pops SR and PC in 4 cycles. The interrupt latency is the time from the request to the ISR's first instruction.

Demo: one interrupt, step by step: the button rises at cycle 5, in the middle of a 2-cycle JMP. The CPU sees it at cycle 6, the entry takes cycles 6–11 and BUTTON_ISR starts at cycle 12. Latency = 12 − 5 = 7 cycles (1 to finish the JMP + 6 for the entry). The whole round trip, entry to RETI, is 19 cycles, of which only 5 do the work (presses++).

Priority: preempt or wait

The rule is one comparison. A pending source is taken only if its priority is strictly more urgent than the level the CPU runs at. Three cases follow:

request vs running levelwhat happensdemo, latency
more urgentpreempts at the next instruction boundary: a second frame on the stacka more urgent interrupt nests: UART (0) cuts into TIMER (1), 7 cycles
less urgentpending until the running ISR returnsa less urgent one waits: BUTTON (2) waits for TIMER, 21 cycles
equalpending too: equal priority never preemptsequal priority, same cycle: UART set to 1, 30 cycles

When two pending sources have the same priority, the chip needs a tie-break. Here, as on most chips, the lower vector address wins. In Demo: equal priority, same cycle TIMER and UART both ask at cycle 4 with priority 1. TIMER (0x0002) goes first, its entry starts at cycle 4, so its latency is 6. UART waits for the whole TIMER round trip (24 cycles) plus its own entry: 30 cycles. Priority is how you choose which source pays for the others.

Nesting and the stack

Every level that is cut into leaves one frame on the stack: PC, SR and R0, 3 words here. In Demo: three levels deep the button comes at cycle 2, the timer at 10 and the UART at 22. Each one is more urgent than the one running, so each cuts in. At the deepest point the stack holds 9 words (18 bytes) and SP has gone from 0x0800 down to 0x07EE. The handlers start BUTTON → TIMER → UART and finish in the opposite order, UART → TIMER → BUTTON, each one picking up exactly where it was cut. Look at the TIMER frame: its saved R0 is 1, the half-done ticks + 1 that TIMER_ISR had computed but not yet stored. The latencies are 7, 7 and 6 cycles: nesting keeps the urgent source fast.

The stack at the deepest point of the three-levels demo, from 0x07FE down to 0x07EE: main's frame PC 0x0100, SR I=1 L=–, R0 0, pushed when BUTTON came in; BUTTON's frame PC 0x0242, SR I=1 L=2, R0 0, pushed when TIMER came in; TIMER's frame PC 0x0206, SR I=1 L=1, R0 1, pushed when UART came in. SP points at 0x07EE. On the right the timeline: BUTTON from cycle 3, TIMER from 11, UART from 22, then UART returns at cycle 41, TIMER at 54, BUTTON at 65
Three nested interrupts leave three frames; the stack must have room for the worst case of all levels at once.

So the worst-case stack need is the sum of one frame per priority level, plus what each ISR's own code uses. Fewer levels means less stack. An ISR of the same level can never nest in itself, which is why the page's three sources with three different levels give at most 3 frames.

Back-to-back interrupts

In Demo: a less urgent one waits BUTTON is still pending when TIMER_ISR ends at cycle 27. The CPU pops PC and SR (4 cycles), finds that the button now beats main, and pushes the very same PC and SR again (6 cycles). Those 10 cycles do nothing useful. ARM Cortex-M chips skip that pair with tail-chaining (Cortex-M exceptions). Many small chips also run at least one instruction of the interrupted code before taking the next interrupt.

A variable shared with an ISR

The stack saves registers, not memory. If main and an ISR both change the same variable, the ISR can run between main's read and main's write. count-- compiles to three instructions: LD R0,[count], SUB R0,#1, ST [count],R0. In Demo: shared counter, a lost update count starts at 3. main loads 3 into R0, the UART comes in at cycle 1, UART_ISR saves R0, adds 1 and stores count = 4, then restores R0 = 3 and returns. main subtracts and stores 2. The answer should be 3 − 1 + 1 = 3: the UART's byte is lost. This is the race condition of threads, on a single core and with no OS at all.

Two columns, time going down. Left, the race: main LD R0 = 3, then UART_ISR runs and writes count = 4, then main SUB R0 = 2 and ST count = 2, marked wrong. Right, the fix: main cli, LD R0 = 3, SUB, ST count = 2, sei; the UART request at cycle 2 waits pending; after sei UART_ISR writes count = 3, marked right, with latency 11 cycles instead of 7
Turning interrupts off around the read-modify-write makes it one step for the ISR; the price is latency.

Two things are needed to fix it:

  • volatile uint8_t count; tells the compiler that the variable can change behind its back. It must load it from memory every time and store it every time. Without it, an optimizing compiler may keep count in a register across a loop, and main would never see the ISR's updates, for example in while (count == 0) { }. But volatile does not make count-- one step: the demo's count is volatile and still loses the update.
  • A critical section: turn interrupts off around the read-modify-write, cli(); count--; sei(); on AVR. In Demo: fix with volatile + cli/sei the UART asks at cycle 2, while I = 0. Its flag stays set, the request is not lost. It is taken right after sei at cycle 7, and count ends at 3 ✓. The latency grows from 7 to 11 cycles, the length of the protected code. Keep critical sections a few instructions long.

Other fixes: disable only that one source (its enable bit) instead of all of them, raise the CPU level to the ISR's level for a moment, use an instruction that changes memory in one step if the chip has one, or let only one side write (the ISR writes a head index, main writes a tail index, as in a ring buffer).

On real chips

chip familylevelswhat the hardware savesnesting
80512 (IP register), 4 on newer onesPC only; the ISR pushes PSW and registersa high-level source can cut into a low-level ISR
AVR (ATmega)fixed order by vector numberPC only; I is cleared on entry, the ISR saves SREGnone unless the ISR runs sei itself
ARM Cortex-Mup to 256 (NVIC)R0–R3, R12, LR, PC, xPSR, 12 cyclesby priority, with tail-chaining

The page's chip is a mix: 8051-style levels, with the hardware saving PC and SR. When the ISRs are periodic jobs, the same numbers feed a schedulability check; see rate-monotonic analysis and, for a design with only one interrupt, a time-triggered scheduler.

See also the button debounce state machine, a short 10 ms task that replaces an edge interrupt on a bouncing pin.

See also embedded software architectures, where ISRs set flags, fill queues or wake RTOS tasks, and the response of the task code depends on which design is used.

See also a FIR filter accelerator, where the CPU sleeps in WFI until the accelerator's done interrupt and the handler clears DONE.

See also MCU startup from power-on to main() for what a microcontroller does before main runs and its interrupts are enabled.

See also the watchdog timer, where a timer interrupt that keeps running while the main loop is stuck hides the hang from the watchdog.

What the page leaves out

One register and one RAM bank; real ISRs save more registers, and compilers decide which. Instruction times are fixed; real latency also depends on wait states, flash fetch, caches and the longest instruction (a multiply or a block copy). No peripheral timing: the flag is set at the given cycle. Level-triggered lines that stay asserted, clearing a flag in software, priority grouping and sub-priorities, the NMI and fault handlers, and Cortex-M's late arrival are not shown. Interrupts on a multi-core chip or under an RTOS are a separate topic.

On the mind map

Open the Operating Systems mind mapOperatingSystemsBoot and program start: from power on to main()Boot and program startProcesses and the kernel: how user code talks to the kernelProcesses and the kernelInterrupts and devices: hardware interrupts the CPUInterrupts and devicesScheduling and deadlock: who runs next, who gets whatScheduling and deadlockVirtual memory: every address is translatedVirtual memoryPhysical memory: who gets which bytes of RAMPhysical memoryFiles and storage: from open() down to the diskFiles and storageDisks and RAID: blocks down to platter or flashDisks and RAIDIsolation and security: limit what a process can doIsolation and securityInterrupt-driven I/OInterrupt-driven I/OIRQ, IDT, handler, then iretInterrupt priority nestingOnly a more urgent level cuts inWatchdog timerWatchdog timerKick only after real work, never from an ISRCortex-M exceptionsCortex-M exceptionsHardware stacks 8 words; tail-chain in 6Kinds of interruptsKinds of interruptsIRQ, timer, NMI, fault, syscall: one IDTDMADMAdevice writes RAM itself, then one IRQHW/SW co-design acceleratorHW/SW co-design acceleratorAmdahl: 2,226 → 478 cycles, capped at 12.5×Packet receive pathPacket receive pathone IRQ, then NAPI polls in a softirqOpen the Operating Systems mind mapOperating Systemshardware interrupts the CPUInterrupts and devicesInterrupt-driven I/OInterrupt-driven I/OIRQ, IDT, handler, then iretInterrupt priority nestingOnly a more urgent level cuts inWatchdog timerWatchdog timerKick only after real work, never from an ISRCortex-M exceptionsCortex-M exceptionsHardware stacks 8 words; tail-chain in 6Kinds of interruptsKinds of interruptsIRQ, timer, NMI, fault, syscall: one IDTDMADMAdevice writes RAM itself, then one IRQHW/SW co-design acceleratorHW/SW co-design acceleratorAmdahl: 2,226 → 478 cycles, capped at 12.5×Packet receive pathPacket receive pathone IRQ, then NAPI polls in a softirq
This page on the Operating Systems mind map · 78 pages in 9 branches · open it to see the whole map and test yourself in recall mode.