Microprocessor Architecture

Chapter 7
Input/Output, Buses, Interrupts, and DMA

Bachelors Program in Electronics and Communication
Microprocessor Architecture   •   Bachelor

Input/Output, Buses, Interrupts, and DMA

Introduction

A microprocessor is useful only when it can exchange information with the physical and digital world. Input/output (I/O) systems connect the processor to sensors, displays, storage devices, communication links, timers, and actuators. This chapter examines the organization of I/O, the buses that transport addresses and data, mechanisms for requesting processor attention, and direct memory access (DMA), in which peripherals transfer data without continuous processor intervention.

The central design challenge is coordination. A processor operates according to its clock and instruction sequence, whereas an external device may be slower, faster, asynchronous, burst-oriented, or subject to electrical and protocol constraints. Effective I/O architecture therefore requires addressing, synchronization, arbitration, buffering, error detection, and carefully defined software interfaces.

Learning Objectives

After studying this chapter, the reader should be able to:

  • distinguish memory-mapped and isolated I/O;
  • explain the roles of address, data, and control buses;
  • compare programmed I/O, polling, interrupts, and DMA;
  • describe interrupt sources, priorities, nesting, and exception handling;
  • explain bus arbitration and timing considerations;
  • outline UART, SPI, I²C, USB, PCIe, and AMBA operation;
  • select an appropriate I/O method for a practical embedded system;
  • analyze throughput, latency, buffering, and design limitations.

1. I/O Addressing and Interface Organization

An I/O interface generally contains data registers, status registers, and control registers. A data register holds information being transferred. A status register reports conditions such as receive-ready, transmit-empty, overrun, error, or DMA completion. A control register enables functions and configures parameters such as baud rate, interrupt masks, operating mode, or transfer size.

A typical interface performs four tasks:

  1. decode an address and determine whether it is selected;
  2. synchronize or handshake with the peripheral;
  3. hold data temporarily in registers or buffers;
  4. report completion and error conditions.

Memory-mapped I/O

In memory-mapped I/O, peripheral registers occupy ordinary processor address locations. The same load and store instructions used for memory access are used for I/O. For example, a store to address 0x40001000 might write to a timer-control register, while a load from 0x40001004 might read its status.

Advantages include a uniform programming model, access to the full instruction set, and straightforward integration with compilers and operating systems. Disadvantages include consumption of address space and the possibility that speculative, cached, or reordered memory operations could incorrectly affect device registers. Device regions must therefore usually be marked as uncached and have carefully defined ordering rules.

Isolated (port-mapped) I/O

In isolated I/O, peripheral registers occupy a separate I/O address space. Special instructions, such as IN and OUT in some processor families, distinguish device transfers from memory transfers. Memory address space is preserved, and the hardware can clearly distinguish I/O cycles. However, the instruction set and programming model are less uniform, and port addressing may be more limited.

FeatureMemory-mapped I/OIsolated I/O
Address spaceShared with memorySeparate I/O space
InstructionsOrdinary loads and storesSpecial I/O instructions
Programming modelUniformDistinct
Address-space costUses memory addressesDoes not consume memory addresses
Main concernOrdering, caching, side effectsLimited instructions and address range

Register semantics

A read-only status register cannot safely be treated like ordinary RAM. Some registers are read-to-clear: reading them removes a pending condition. Others are write-one-to-clear: writing a 1 clears the corresponding flag. A register may also contain reserved bits that must be written as zero or preserved. These semantics belong in the hardware specification and device-driver documentation.

A robust driver should use volatile or equivalent device-access declarations where necessary, avoid unintended read-modify-write operations, and observe required ordering barriers. A compiler must not remove or combine accesses whose side effects are observable by hardware.

2. Buses and Transfer Timing

A bus is a shared or point-to-point communication structure. A conventional parallel system bus contains:

  • an address path identifying a source, destination, or register;
  • a data path carrying values;
  • control signals defining direction, validity, read/write operation, byte enables, acknowledgement, reset, and errors.

A bus transaction normally consists of an initiator placing an address and command, a target recognizing the request, a data phase, and a completion response. Some buses separate address and data phases; others multiplex them on the same wires.

Synchronous and asynchronous transfers

A synchronous bus uses a common clock. A transfer is sampled at a defined clock edge, which simplifies timing analysis but constrains devices to the clocking scheme. An asynchronous bus uses request and acknowledge signals. It can accommodate devices with different speeds, but handshake design and metastability control become important.

If a synchronous transfer requires n clock cycles and the clock frequency is fclk, the ideal transfer time is:

ttransfer = n / fclk

Here, ttransfer is in seconds, n is dimensionless, and fclk is in hertz. This relation assumes no wait states, arbitration delay, refresh interruption, or bus turnaround. If w wait cycles are inserted, the model becomes:

ttransfer = (n + w) / fclk

For a transfer of [[MATH{B}]] bytes completed in time [[MATH{t}]], the average payload throughput is:

R = B / t

where R is bytes per second. Protocol overhead, idle time, retries, and arbitration reduce useful throughput below the physical signaling rate.

Bus width and bandwidth

If a bus transfers [[MATH{W}]] bits per transfer at [[MATH{f}]] transfers per second, its theoretical raw bandwidth is:

BWraw = (W × f) / 8

The factor 8 converts bits to bytes. This is a maximum physical rate, not a guaranteed application rate. For example, a 32-bit bus operating at 50 million transfers per second has a raw bandwidth of 200 MB/s, before protocol and waiting losses.

Arbitration

When several potential initiators—such as a processor, DMA controller, or bus master—request a shared bus, arbitration determines who may proceed. Common strategies are:

  • Centralized priority arbitration: a controller grants access according to fixed or programmable priority.
  • Round-robin arbitration: requests are served cyclically, improving fairness.
  • Daisy-chain arbitration: a grant propagates through devices; the first requesting device captures it.
  • Distributed arbitration: devices collectively determine ownership, often using wired priority or collision-resolution rules.

Fixed priority gives rapid service to urgent devices but can starve low-priority requesters. Round-robin improves bounded fairness but may increase latency for critical traffic. A real-time design should specify maximum waiting time, not merely average throughput.

Bus turnaround and electrical integrity

A bidirectional bus requires a turnaround interval when control changes from transmitter to receiver. Without sufficient turnaround, two drivers may contend electrically. At high speed, trace impedance, termination, skew, setup time, hold time, crosstalk, and signal integrity constrain the design. Protocol correctness therefore depends on both logical timing and physical-layer engineering.

3. Programmed I/O and Polling

In programmed I/O, software explicitly transfers each value. The processor reads a status register, determines whether the peripheral is ready, and then accesses the data register. Polling is simple and deterministic for slow systems, but it consumes processor cycles while waiting.

A polling loop can be represented conceptually as:

repeat
    status ← read STATUS
until status indicates ready
data ← read or write DATA

Polling is appropriate when events occur frequently, waiting time is short, the software must maintain a simple control flow, or the processor has no interrupt facility. It is inefficient when events are rare or device response time is unpredictable.

Suppose a processor polls every [[MATH{T_p}]] seconds and an event can occur uniformly at any time between polls. The average detection delay is approximately:

Tavg ≈ Tp / 2

This approximation assumes negligible service time and uniformly distributed event arrival. The worst-case delay is approximately [[MATH{T_p}]], so polling frequency must be selected with both latency and processor-utilization requirements in mind.

4. Interrupts and Exceptions

An interrupt is a request for processor service caused by hardware or software. Unlike polling, it allows the processor to perform other work until service is required. A typical sequence is:

  1. a device asserts an interrupt request;
  2. the processor completes an instruction or reaches an architecturally defined boundary;
  3. processor state is saved, either automatically or by a handler;
  4. the processor identifies the interrupt vector or source;
  5. an interrupt-service routine (ISR) services the device;
  6. the source is acknowledged or cleared;
  7. saved state is restored and interrupted execution resumes.

An interrupt vector is an address or index identifying the handler. In a vectored system, each source has a distinct vector. In a non-vectored system, a common handler reads an interrupt-pending register and determines the source.

Maskable and non-maskable interrupts

Maskable interrupts can be disabled temporarily, for example while protecting a short critical section. Non-maskable interrupts are reserved for urgent conditions such as catastrophic hardware failure, watchdog expiration, or power-fail warning. Excessive use of non-maskable mechanisms undermines system control and should be avoided.

Priorities and nesting

When several requests arrive together, a priority mechanism selects the order of service. Priority may be fixed, programmable, or dynamically assigned. Interrupt nesting allows a higher-priority interrupt to pre-empt a lower-priority ISR. Nesting improves responsiveness but increases stack use and complicates shared-data protection.

A sound ISR should be short: capture essential state, acknowledge the hardware, move data to a buffer, and defer lengthy processing to a task or bottom-half mechanism. It should not perform blocking I/O or hold a lock while waiting for an event.

Exceptions and faults

An exception is a processor-detected event associated with instruction execution. Examples include invalid opcode, privilege violation, page fault, arithmetic fault, and system call. Some exceptions are synchronous: they can be associated with a particular instruction. Hardware interrupts are generally asynchronous. The distinction matters because a synchronous fault may be restartable, whereas an asynchronous interrupt normally is not tied to one instruction.

Exception handling must preserve sufficient context for diagnosis or recovery. Operating systems often separate user mode from privileged mode, validate addresses, and prevent an application from directly configuring arbitrary devices. These mechanisms are essential for reliability and security.

5. Direct Memory Access

DMA transfers blocks of data between a peripheral and memory with limited processor involvement. The processor programs the DMA controller with source and destination addresses, transfer length, direction, transfer width, and control options. The DMA controller then requests bus ownership, performs transfers, and generates an interrupt on completion or error.

Common DMA modes include:

  • Burst mode: transfers many words after acquiring the bus; high efficiency but potentially long processor blocking.
  • Cycle stealing: transfers one or a few words at a time between processor bus cycles; better processor responsiveness but greater overhead.
  • Scatter-gather: follows a list of descriptors to transfer non-contiguous buffers.
  • Circular mode: repeatedly fills or drains a ring buffer, useful for audio and continuous data acquisition.

For a stream producing [[MATH{r}]] bytes/s and a DMA buffer of [[MATH{B}]] bytes, the nominal time before the buffer fills is:

tfill = B / r

This assumes a constant production rate and no consumed data. Software must process or recycle the buffer before it is overwritten. In a double-buffer system, one buffer can be processed while the other is being filled.

DMA correctness and cache coherence

DMA introduces ownership questions. If a processor cache contains a modified copy of a buffer, a peripheral may read stale memory. Conversely, the processor may read stale cache data after a peripheral writes memory. Systems solve this using coherent caches, cache flush and invalidate operations, non-cacheable buffers, or an I/O memory-management unit (IOMMU).

A DMA descriptor should specify length, address, ownership, status, and error fields. Software must establish descriptor contents before transferring ownership to hardware, and hardware must return ownership before software reuses the buffer. Memory barriers are required where the architecture permits reordering.

DMA improves throughput and reduces processor overhead, but it can increase latency for other bus masters, complicate debugging, and create security risks. An unrestricted peripheral DMA engine could overwrite kernel memory or another process’s data. IOMMUs and strict buffer validation limit this danger.

6. Timers, Counters, and Watchdogs

Timers are I/O peripherals that count clock events. A timer can generate periodic interrupts, measure intervals, produce pulse-width modulation (PWM), or trigger DMA. A counter may count external events such as encoder pulses.

For a timer clocked at frequency [[MATH{f_t}]] with a reload value producing [[MATH{N}]] clock intervals, the ideal period is:

T = N / ft

The actual period may include prescaler quantization, interrupt latency, clock tolerance, and synchronization delay. A watchdog timer resets or interrupts the system if software fails to refresh it within a specified interval. Watchdogs improve fault recovery but should be designed so that a genuine software fault cannot continuously and silently refresh them.

7. Serial and Parallel Protocols

UART

A universal asynchronous receiver/transmitter (UART) sends frames without a shared clock. A common frame contains a start bit, 5–9 data bits, optional parity, and one or more stop bits. Both ends must use sufficiently similar baud rates. UART is simple and inexpensive, but generally provides point-to-point communication and limited distance or speed without additional transceivers.

SPI

Serial Peripheral Interface (SPI) normally uses a controller clock, serial data output, serial data input, and one chip-select signal per selected peripheral. It supports full-duplex transfers and high speed with little protocol overhead. Its disadvantages include additional chip-select wiring and the absence of a universal addressing or error-detection format.

I²C

I²C uses two open-drain lines: serial data (SDA) and serial clock (SCL). Pull-up resistors return the lines high, and devices pull them low. Addressing, acknowledgement, arbitration, clock stretching, and multiple controllers are built into the protocol. Because a low level is dominant, a controller can detect that another controller has won arbitration. Rise time depends on pull-up resistance and bus capacitance; thus electrical design limits speed and node count.

USB

Universal Serial Bus (USB) is a host-controlled, hierarchical serial system. Devices are enumerated and assigned addresses; transfers use defined endpoints and transaction types. USB provides standardized connectors, power negotiation in many versions, error detection, and broad operating-system support. Its complexity is much greater than that of UART, SPI, or I²C.

PCI Express

PCIe is a high-speed, packet-based, point-to-point interconnect. It uses differential serial lanes, link training, transaction-layer packets, flow control, and error detection. Multiple lanes may be bonded to increase bandwidth. PCIe differs fundamentally from a simple shared parallel bus: switches create scalable topologies, and packets carry address, data, and control information.

AMBA

The Advanced Microcontroller Bus Architecture (AMBA) is a family of on-chip interconnect specifications widely used in system-on-chip designs. AXI supports high-performance, independent read and write channels and burst transfers. AHB provides pipelined transfers for many systems, while APB is a simpler, low-power peripheral bus used for registers such as timers and UARTs. A bridge commonly connects a high-speed AXI or AHB fabric to an APB peripheral region.

InterfaceTypical organizationStrengthTypical limitation
UARTAsynchronous point-to-pointSimple, low pin countBaud-rate matching; modest throughput
SPISynchronous controller-peripheralFast, full duplexChip-select wiring; no universal framing
I²CAddressed multi-device busTwo wires, arbitrationPull-up rise time and lower speed
USBHost-controlled hierarchyStandardized ecosystemProtocol and software complexity
PCIePacketized point-to-pointHigh bandwidth and scalabilitySignificant hardware complexity
AMBAOn-chip interconnect familySoC integration and separation of speedsSpecification and verification complexity

8. Case Study: Sensor Gateway with DMA and Interrupts

Background

Consider an illustrative industrial sensor gateway containing a microcontroller, a temperature sensor on I²C, a high-rate vibration sensor connected through SPI, a UART maintenance port, and Ethernet connected through a system bus. Vibration samples arrive at 2 MB/s and must be processed continuously.

Problem

A polling implementation reads the SPI status register for every sample. At 2 MB/s, the processor spends most of its time waiting and risks missing samples when Ethernet traffic occurs. Occasional I²C faults also require recovery without stopping vibration acquisition.

Analysis

The vibration path is a continuous stream with predictable block structure, so DMA is appropriate. If a 16 KiB buffer is used, the nominal fill time is:

tfill = 16,384 / 2,000,000 ≈ 0.008192 s = 8.192 ms

The processor must therefore process or recycle each buffer within approximately 8.192 ms, allowing additional margin for scheduling and bus contention. A double-buffer arrangement permits DMA to fill one buffer while software processes the other.

Approach and solution

The SPI controller is configured to generate DMA requests. Two memory buffers are allocated in a DMA-safe region. The DMA completion interrupt is configured at half-buffer and full-buffer boundaries. The ISR acknowledges the interrupt, records which buffer is ready, and signals a processing task. It does not perform spectral analysis itself.

The I²C driver uses interrupts for transaction completion and a timeout watchdog for a stuck bus. If SDA remains low beyond the allowed interval, the driver disables the controller, generates controlled clock pulses if supported, and reinitializes the bus. The UART uses a small receive ring buffer and interrupt-driven reception. Ethernet DMA descriptors are placed in coherent or explicitly managed memory.

Outcome

The processor is freed from per-sample polling. Buffer-level interrupts reduce interrupt frequency, while DMA maintains sustained throughput. Error handling is localized: an I²C recovery event does not disrupt the SPI acquisition path. The design still requires worst-case scheduling analysis, cache-coherency controls, and protection against buffer overrun.

Learning points

The best I/O mechanism depends on traffic pattern. Polling suits simple, low-rate events; interrupts suit sporadic events requiring prompt service; DMA suits sustained block transfers. Combining mechanisms is often superior to choosing one universally.

9. Design Challenges, Security, and Best Practices

Important practical limitations include interrupt storms, priority inversion, buffer overrun, lost acknowledgements, bus deadlock, clock-domain crossing errors, metastability, and incorrect reset sequencing. Every interface should define behavior for timeout, malformed input, parity or CRC failure, power loss, and device removal.

Security is an architectural concern. Device registers and DMA engines must be protected by privilege levels, access-control policies, IOMMU mappings, and validation of lengths and addresses. External inputs should be treated as untrusted. Firmware updates and diagnostic interfaces must be authenticated where systems affect safety, infrastructure, or personal data.

Best practices include:

  • specify maximum latency and minimum throughput, not only nominal values;
  • use status and error flags deliberately and document side effects;
  • keep ISRs short and defer complex work;
  • use bounded buffers and explicit overflow policy;
  • verify cache coherency and memory ordering;
  • apply timeouts to every potentially blocking transaction;
  • test arbitration under worst-case simultaneous requests;
  • use logic analyzers and bus traces to validate timing;
  • separate hardware abstraction, driver, and application layers;
  • design reset and recovery behavior before normal operation.

Chapter Summary

I/O architecture connects a processor to peripherals through addressing, registers, buses, synchronization, and software drivers. Memory-mapped I/O provides a uniform load/store model, whereas isolated I/O uses a separate address space and special instructions. Buses carry addresses, data, and control information; their performance depends on width, frequency, protocol overhead, arbitration, and wait states.

Polling is simple but consumes processor time. Interrupts provide event-driven service and require vectors, priorities, acknowledgement, and carefully designed handlers. Exceptions are processor-related events that may be synchronous and restartable. DMA transfers blocks between memory and devices with low processor overhead, but it introduces ownership, cache-coherency, security, and arbitration concerns. Timers provide scheduling, measurement, PWM, and watchdog functions.

UART, SPI, and I²C are common low- and medium-complexity serial interfaces; USB provides a standardized host-controlled ecosystem; PCIe provides scalable packetized high-speed connectivity; and AMBA integrates processors and peripherals within system-on-chip devices. Effective designs select mechanisms according to rate, latency, buffering, complexity, safety, and security requirements.

Key Terms

Memory-mapped I/O: I/O registers located in the processor’s ordinary memory address space.

Isolated I/O: I/O registers located in a separate address space accessed by special instructions.

Bus: A communication structure carrying address, data, and control information.

Initiator: A device that begins a bus transaction.

Target: A device that responds to a bus transaction.

Arbitration: Selection of one requester to control a shared bus.

Polling: Repeated software examination of a device status condition.

Interrupt: A request that causes processor service outside the normal instruction sequence.

ISR: Interrupt-service routine that responds to an interrupt.

Interrupt vector: Address or identifier of an interrupt handler.

Exception: A processor-detected event associated with instruction execution.

DMA: Direct memory access performed by a controller with limited processor intervention.

Descriptor: A memory record containing DMA transfer information.

Cache coherency: Agreement between cached processor data and main-memory data.

UART: Asynchronous serial communication peripheral.

SPI: Synchronous serial peripheral interface.

I²C: Two-wire addressed serial bus using open-drain signaling.

USB: Standardized host-controlled serial bus.

PCIe: Packet-based, point-to-point high-speed serial interconnect.

AMBA: Family of on-chip bus and interconnect specifications.

Review Questions

Short Answer Questions

  1. What is the principal difference between memory-mapped and isolated I/O?
  2. Why can fixed-priority arbitration cause starvation?
  3. What is the purpose of an interrupt vector?
  4. Name two cache-coherency problems that can occur with DMA.
  5. Why are pull-up resistors used on an I²C bus?

Long Answer Questions

  1. Explain the complete sequence of an interrupt from request assertion to return from the ISR.
  2. Compare polling, interrupts, and DMA in terms of processor utilization, latency, complexity, and suitable applications.
  3. Describe bus arbitration methods and discuss the trade-off between priority and fairness.
  4. Explain UART, SPI, and I²C operation and compare their wiring, synchronization, and application characteristics.
  5. Describe the organization of an AMBA-based SoC containing AXI, AHB, and APB components.

Analytical / Application Questions

  1. A device produces data at 1.5 MB/s and uses two 12 KiB DMA buffers. Calculate the nominal time available to process each buffer and identify practical sources of timing margin.
  2. Design an interrupt and buffering strategy for a gateway that receives sporadic UART commands, continuous SPI samples, and periodic I²C measurements. Justify the mechanism selected for each stream.
  3. A system experiences corrupted data when a DMA peripheral writes to a buffer recently read by the processor. Analyze the likely cache-coherency cause and propose two valid architectural remedies.

Multiple Choice Questions with Answers

Question 1

Which feature is characteristic of memory-mapped I/O?

A. Peripheral registers use ordinary load and store instructions

B. Peripheral registers cannot be assigned addresses

C. Only special IN and OUT instructions access devices

D. Devices are accessed without address decoding

Correct Answer: A. Peripheral registers use ordinary load and store instructions

Question 2

A 32-bit bus performs 50 million transfers per second. What is its ideal raw bandwidth?

A. 50 MB/s

B. 100 MB/s

C. 200 MB/s

D. 400 MB/s

Correct Answer: C. 200 MB/s

Question 3

What is the main purpose of an interrupt-service routine?

A. To replace the system clock

B. To respond to and service an interrupt source

C. To allocate all memory buffers permanently

D. To arbitrate every bus transaction

Correct Answer: B. To respond to and service an interrupt source

Question 4

Which DMA mode repeatedly uses a list of transfer descriptors?

A. Daisy-chain mode

B. Scatter-gather mode

C. Port-mapped mode

D. Half-duplex mode

Correct Answer: B. Scatter-gather mode

Question 5

If a polling interval is 10 ms and event arrival is uniformly distributed, what is the approximate average detection delay?

A. 1 ms

B. 5 ms

C. 10 ms

D. 20 ms

Correct Answer: B. 5 ms

Question 6

Which interface normally uses SDA and SCL lines with open-drain signaling?

A. UART

B. SPI

C. I²C

D. PCIe

Correct Answer: C. I²C

Question 7

What is a major advantage of round-robin bus arbitration?

A. It guarantees the highest priority device always wins

B. It improves fairness among requesters

C. It eliminates the need for bus timing

D. It prevents all wait states

Correct Answer: B. It improves fairness among requesters

Question 8

Why may a DMA buffer require cache maintenance?

A. Caches change the bus voltage

B. The processor cache and memory may contain different versions of data

C. DMA operates only with read-only memory

D. Cache maintenance increases UART baud rate

Correct Answer: B. The processor cache and memory may contain different versions of data

Question 9

Which interface is packet-based and point-to-point rather than a traditional shared parallel bus?

A. PCIe

B. I²C

C. UART

D. APB

Correct Answer: A. PCIe

Question 10

A 16,384-byte buffer receives data at 2,000,000 bytes/s. What is its nominal fill time?

A. 0.8192 ms

B. 8.192 ms

C. 81.92 ms

D. 819.2 ms

Correct Answer: B. 8.192 ms

Microprocessor Architecture
Chapter 7 of 15