Chapter 32 of 39

Programmed I/O & Interrupts

In I/O Organization & Interfaces we saw that every device sits behind an interface with data, status and control registers. Now comes the central question of I/O: how does the CPU know when the device is ready?

There are two answers. The CPU can keep asking ("are you ready? are you ready?"), which is programmed I/O with polling. Or the device can tap the CPU on the shoulder when it is ready, which is an interrupt. Think of waiting for a courier: you can stand at the door checking every minute, or you can get on with your work and let the doorbell ring.

This chapter covers both methods, the hardware interrupt cycle, vectored and non-vectored interrupts, priority schemes (polling, daisy chaining and parallel priority with an encoder), nested interrupts, the difference between interrupts, exceptions and traps, and the GATE-style numerical problems that compare their CPU cost.


Programmed I/O

Programmed I/O: the CPU executes a program that directly controls every step of the transfer. It checks the device's status register, and when the device is ready, moves each byte or word between the device's data register and a CPU register (and then memory) by itself.

An input operation looks like this:

        +-------------------------------+
        | issue READ command to device  |
        +---------------+---------------+
                        v
        +-------------------------------+
  +---->| read status register          |
  |     +---------------+---------------+
  |                     v
  |       ready flag = 1 ?  --- no ---+    (busy waiting / polling loop)
  |                     | yes         |
  +---------------------|-------------+
                        v
        +-------------------------------+
        | read data register into CPU   |
        | store word in memory          |
        +---------------+---------------+
                        v
               more data?  -- yes --> back to "read status register"
                        | no
                        v
                      done

In C-like driver code (with memory-mapped registers):

volatile unsigned char *status = (unsigned char *)0xFFFF0000;
volatile unsigned char *data   = (unsigned char *)0xFFFF0004;

for (int i = 0; i < n; i++) {
    while ((*status & 0x01) == 0)   /* poll: wait for READY bit */
        ;                            /* CPU does nothing useful here */
    buf[i] = *data;                  /* CPU moves the byte itself */
}

The volatile keyword tells the compiler that the value can change on its own (the device changes it), so it must actually read the register every time round the loop.

The Problem With Polling

The CPU is enormously faster than most devices. While it spins in the loop, it executes thousands or millions of useless status reads. The CPU is tied up for the entire duration of the transfer, even though the useful work (copying a byte) takes a tiny fraction of that time.

But polling is not always bad. It has no setup cost, it is simple, and it is predictable. If the device will be ready within a few hundred nanoseconds, polling is cheaper than the overhead of taking an interrupt. Simple microcontrollers and some very high-speed devices deliberately poll.


Interrupt-Driven I/O

Interrupt: a hardware signal from a device (or other source) that makes the CPU suspend the current program after the current instruction, run a special routine called the interrupt service routine (ISR) or interrupt handler, and then resume the suspended program exactly where it stopped.

With interrupts, the CPU issues the command and goes back to other work. The device interface raises its interrupt request (IRQ) line when data is ready; the ISR then transfers the data. The CPU no longer wastes time waiting, but it still moves every word itself, inside the ISR.

The Interrupt Cycle: What the Hardware Does

The CPU checks for interrupts at one well-defined point: after finishing the current instruction and before fetching the next. If an interrupt is pending and interrupts are enabled, it enters an interrupt cycle instead of a normal fetch:

   +--------+     +---------+     +-----------------------------+
   | Fetch  | --> | Execute | --> | Interrupt pending AND        |
   +--------+     +---------+     | interrupts enabled (IEN=1)? |
       ^                          +--------------+--------------+
       |  no                                     | yes
       +-----------------------------------------+
       |                                         v
       |                     INTERRUPT CYCLE:
       |                     1. save PC (and status flags), usually on the stack
       |                     2. disable further interrupts (IEN = 0)
       |                     3. load PC with the ISR address (vector)
       +----------------------------------------- then fetch from the ISR

The ISR (software) then does the rest:

  1. Save any other registers it will use.

  2. Identify the source if necessary, and service the device (read or write the data register). Reading the data or writing a command also clears the device's request.

  3. Restore the registers.

  4. Re-enable interrupts and execute the return-from-interrupt instruction (for example IRET on x86, RETI on 8051), which restores the PC and flags.

Why only at an instruction boundary? Because then the saved PC describes a clean, consistent state: every earlier instruction is complete and no later instruction has started. Resuming is simply "continue from the saved PC". Interrupting halfway through an instruction would require saving hidden internal state.

Interrupt Latency

The time from the device raising the request to the first instruction of the ISR is the interrupt latency. It includes waiting for the current instruction to finish, waiting while interrupts are disabled (for example during another ISR) and the interrupt cycle itself. Real-time systems care a great deal about the worst-case latency, which is why ISRs should be short and interrupts should be disabled for as little time as possible.


Worked Example 1: Interrupt Mode vs Programmed Mode (GATE-style)

Problem. A device with data transfer rate 10 KB/s is connected to a CPU. Data is transferred byte-wise. The interrupt overhead is 4 µs. The byte transfer time between the device interface register and the CPU or memory is negligible. What is the minimum performance gain of operating the device in interrupt mode over operating it in program-controlled (polling) mode?

Solution. Take 1 KB = 1000 bytes as such questions intend.

Time between bytes = 1 / (10 x 1000) s = 100 µs

Program-controlled mode: the CPU waits for the whole gap
    CPU time per byte = 100 µs

Interrupt mode: the CPU spends only the overhead per byte
    CPU time per byte = 4 µs

Gain = 100 / 4 = 25

In interrupt mode the CPU is busy only 4/100 = 4% of the time with this device; the other 96% is available for other programs.


Worked Example 2: When Polling Is Cheaper

A 2 GHz processor takes 200 clock cycles for one poll (call the routine, read status, return) and 400 cycles to take and service one interrupt.

(a) Mouse. A mouse must be polled 30 times per second so no movement is missed.

Cycles per second = 30 x 200 = 6,000
Fraction of CPU   = 6,000 / (2 x 10^9) = 0.0003%

Negligible. Polling a slow device occasionally is fine.

(b) Fast device. A device transfers 4-byte words at 4 MB/s (106 bytes per MB). The CPU must poll often enough not to miss a word, so once per word, and it has to do this all the time because it cannot know when a transfer starts.

Words per second = 4 x 10^6 / 4 = 10^6
Polling cost     = 10^6 x 200 = 2 x 10^8 cycles/s
Fraction of CPU  = 2 x 10^8 / 2 x 10^9 = 10%   (always, even when idle)

(c) Same device with interrupts. It is actually transferring only 20% of the time.

While transferring: 10^6 interrupts/s x 400 = 4 x 10^8 cycles/s = 20% of CPU
Average over time : 20% x 0.20 = 4%

Interesting: while the device is busy, interrupts (20%) cost more than polling (10%) because each interrupt is more expensive than a poll. Interrupts win on average (4% vs 10%) only because they cost nothing when the device is idle. This is why real systems switch to polling under very heavy load and back to interrupts when traffic is light. For really fast bulk devices, the answer is neither: use DMA (next chapter) so there is one interrupt per block instead of per word.


Identifying the Source: Vectored vs Non-Vectored Interrupts

When several devices can interrupt, the CPU must find out who interrupted, so it can run the right ISR.

Non-vectored interrupt

Vectored interrupt

The ISR starts at a fixed address, the same for all devices on that line

The interrupting device (or interrupt controller) supplies a vector: an address, or a number used to index an interrupt vector table

The ISR must find the source in software (by polling each device's status register)

The CPU jumps directly to the device's own ISR

Simple hardware, slower response

Faster response, a little more hardware

The Intel 8085, still taught in many Indian universities, has both kinds. TRAP, RST 7.5, RST 6.5 and RST 5.5 are vectored to fixed addresses (8 times the RST number); INTR is non-vectored and the device must place an instruction (such as an RST) on the data bus during the acknowledge (INTA) cycle.

8085 input

Vector address

Maskable?

Priority

TRAP

0024H

No

Highest

RST 7.5

003CH

Yes

2

RST 6.5

0034H

Yes

3

RST 5.5

002CH

Yes

4

INTR

Non-vectored

Yes

Lowest

On x86, the vector is an 8-bit number (0 to 255) used to index the Interrupt Descriptor Table; vectors 0 to 31 are reserved for processor exceptions.


Interrupt Priority

If two devices interrupt at the same time, which is served first? A fast device that would lose data (a disk or network card) should beat a slow one (a keyboard). There are three classic ways to establish priority.

1. Software Polling

One common interrupt line; the ISR checks devices one by one in priority order, and the first one found requesting is served. Priority is simply the order of the checks. Flexible and cheap, but slow if there are many devices.

2. Daisy Chaining (Serial Priority, Hardware)

All devices share one interrupt request line, but the interrupt acknowledge signal from the CPU passes through the devices one after another like a chain.

               INTR (wired-OR: any device can pull it)
     +-------------+--------------+--------------+------- to CPU
     |             |              |              |
CPU INTACK   +-----+----+   +-----+----+   +-----+----+
 --------->  PI Device 1 PO->PI Device 2 PO->PI Device 3 PO --> ...
             |(highest) |   |          |   | (lowest) |
             +----+-----+   +----+-----+   +----+-----+
                  |              |              |
                  +-------- vector address on data bus --------
  • When a device receives the acknowledge on its priority-in (PI) input: if it has a request pending, it places its vector address on the data bus and sets priority-out (PO) = 0, blocking the devices after it.

  • If it has no request, it passes the acknowledge on: PO = PI = 1.

So priority is fixed by physical position: the device nearest the CPU wins. Advantages: very few wires, easy to add devices. Disadvantages: fixed priority, low-priority devices may starve, and a failed device can break the chain.

3. Parallel Priority (Priority Encoder)

Each device has its own request line into an interrupt register. A mask register lets software enable or disable each line, and a priority encoder picks the highest-priority unmasked request and produces its code, which becomes part of the vector address.

A 4-input priority encoder with I0 highest priority (X = don't care):

I0

I1

I2

I3

x

y

IST

Vector address 0000 xy00

1

X

X

X

0

0

1

0

0

1

X

X

0

1

1

4

0

0

1

X

1

0

1

8

0

0

0

1

1

1

1

12

0

0

0

0

X

X

0

none

x   = I0' . I1'
y   = I0' . I1  +  I0' . I2'
IST = I0 + I1 + I2 + I3        (interrupt status: some request is present)

We checked these equations against all 16 input combinations. Placing x and y in bits 3 and 2 of the vector address gives addresses 0, 4, 8 and 12: four memory words per device, enough for a jump to the full ISR. This is the idea behind interrupt controllers such as the Intel 8259A PIC and the modern APIC.

Method

Priority decided by

Speed

Hardware cost

Flexibility

Software polling

Order of checks in the ISR

Slow

Lowest

High (change the program)

Daisy chain

Physical position in the chain

Fast

Low

Fixed

Parallel priority encoder

Encoder input position, plus mask register

Fastest

Highest

Mask bits allow software control


Nested Interrupts: Worked Example 3

Normally the interrupt cycle disables interrupts. If the ISR re-enables interrupts for higher-priority sources early, a more urgent device can interrupt the running ISR: these are nested interrupts.

Problem. Ignoring overheads, three requests arrive while a main program is running (higher number = higher priority):

Device

Priority

Arrives at (µs)

ISR length (µs)

Printer

2

10

30

Disk

4

15

15

Keyboard

1

20

5

Draw the timeline (a) with nesting by priority, (b) without nesting (pending requests served by priority after the current ISR ends).

(a) Nested
 0-10   main
10-15   printer ISR (5 of 30 done)
15-30   disk ISR    (preempts printer; done at 30)
30-55   printer ISR (remaining 25; done at 55)   keyboard waits: lower than printer
55-60   keyboard ISR (done at 60)
60-     main resumes

(b) Not nested
 0-10   main
10-40   printer ISR (runs to completion)
40-55   disk ISR    (highest pending request)
55-60   keyboard ISR
60-     main resumes

The main program resumes at 60 µs either way (the total work is the same), but the disk waits 0 µs with nesting and 25 µs without. Nesting exists to cut the latency of urgent devices. Notice also that the keyboard does not preempt the printer: a request can only interrupt an ISR of lower priority.


Interrupts, Exceptions and Traps

The same mechanism (save state, jump through a vector, return) is used for several kinds of events. Terminology varies between books, but this is the usual classification:

Type

Source

Synchronous with the program?

Examples

Hardware (external) interrupt

I/O devices, timers

No: can arrive at any time

Key pressed, disk transfer done, timer tick

Exception (fault)

The CPU itself, while executing an instruction

Yes: caused by a particular instruction

Divide by zero, page fault, illegal opcode

Trap / software interrupt

A deliberate instruction

Yes

System calls (INT 0x80, SYSCALL, ECALL), breakpoints

One important difference: after a fault such as a page fault, the PC saved points to the faulting instruction, so it is re-executed after the OS fixes the problem. After a trap or external interrupt, execution resumes with the next instruction.

Hardware interrupts are also divided into maskable interrupts, which software can disable, and non-maskable interrupts (NMI), reserved for critical events such as power failure or memory errors.


Programmed I/O vs Interrupt-Driven I/O

Point

Programmed I/O (polling)

Interrupt-driven I/O

How readiness is detected

CPU repeatedly reads the status register

Device raises an interrupt request

CPU while waiting

Busy, wasted

Free for other work

Who moves the data

CPU

CPU (in the ISR)

Overhead per transfer

Small (a status check)

Larger (save/restore state, jump, return)

Hardware needed

Minimal

Interrupt lines, priority logic, vectors

Best for

Simple systems, devices that are almost always ready

Slow or unpredictable devices (keyboard, mouse, serial)

The weakness they share: the CPU still moves every byte. For bulk transfers that is fixed by DMA.


Common Mistakes

  • Thinking interrupts are checked in the middle of an instruction. The CPU tests for (external) interrupts after completing the current instruction.

  • Saying interrupt-driven I/O frees the CPU from moving data. It only frees the CPU from waiting. Each word is still transferred by the ISR.

  • Assuming interrupts are always cheaper than polling. Per event, an interrupt usually costs more than a poll; interrupts win when the device is often idle.

  • Getting daisy-chain priority backwards. The device closest to the CPU on the acknowledge chain has the highest priority.

  • Forgetting to save registers in the ISR, or to re-enable interrupts before returning. Either corrupts the interrupted program or blocks future interrupts.

  • Mixing up the saved PC for faults and traps. Faults re-execute the instruction; traps continue after it.


GATE and Interview Questions

A device transfers data byte-wise at 20 KB/s (1 KB = 1000 bytes). Interrupt overhead is 5 µs. What fraction of CPU time does interrupt-driven I/O use, and what is the gain over polling?

One byte every 1/20,000 s = 50 µs. Interrupt mode costs 5 µs per byte, so 5/50 = 10% of the CPU. Polling costs the whole 50 µs per byte. Gain = 50/5 = 10.

When does the CPU check for a pending interrupt?

At the end of the current instruction cycle (before fetching the next instruction), provided interrupts are enabled.

What does the CPU save during the interrupt cycle, and why are interrupts disabled at that moment?

At least the program counter, and usually the status/flag register. Interrupts are disabled so that another interrupt cannot occur before the ISR has saved the rest of the state; the ISR can re-enable them (for nesting) once that is done.

In a daisy chain, how does a device without a pending request behave?

It passes the acknowledge signal on: its priority-out equals its priority-in. A device with a pending request blocks the signal (PO = 0) and places its vector address on the data bus.

What is the difference between vectored and non-vectored interrupts?

In a vectored interrupt the source supplies (directly or through the interrupt controller) the address or number of its ISR, so the CPU jumps straight to it. In a non-vectored interrupt, the ISR is at a fixed address and must identify the source by polling.

Is a page fault an interrupt? Where does execution resume?

It is an exception (fault): internal and synchronous, caused by the instruction itself. After the OS loads the page, the faulting instruction is restarted, so execution resumes at that same instruction.

A 1 GHz CPU must poll a device 50,000 times per second; each poll costs 100 cycles. What percentage of CPU time goes to polling?

50,000 x 100 = 5 x 106 cycles per second, out of 109: 0.5%.


Summary

  • Programmed I/O: the CPU polls the status register and moves every byte; simple but wastes CPU time while waiting.

  • Interrupt-driven I/O: the device signals readiness; the CPU checks for interrupts after each instruction, saves the PC, disables interrupts and jumps to the ISR.

  • In the GATE-style example, interrupt mode was 25 times better (100 µs vs 4 µs of CPU per byte). But per event, an interrupt costs more than a poll.

  • Vectored interrupts give the ISR address directly; non-vectored ones need software polling to find the source.

  • Priority is decided by software polling, a daisy chain (position) or a parallel priority encoder with a mask register. Nested interrupts cut latency for urgent devices.

  • Interrupts are external and asynchronous; exceptions and traps are caused by instructions.

Next, in Direct Memory Access (DMA), we remove the CPU from the data path completely, so a whole block moves with just one interrupt.