I. Why Do Computers Need I/O Management?
A computer not only needs the CPU to execute instructions and memory to store data, but also needs to exchange information with external devices.
Common input/output devices include:
| Device type | Typical devices | Main function |
|---|---|---|
| Input devices | Keyboard, mouse, camera | Input data into the computer |
| Output devices | Monitor, printer, speaker | Output data externally |
| Storage devices | SSD, HDD, USB drive | Store data persistently |
| Network devices | Network card, wireless network card | Send and receive network data |
| Communication devices | USB controller, serial device | Exchange data with other hardware |
These devices differ significantly:
- Different speeds: The CPU can execute a large number of instructions in an extremely short time, while the response speeds of disks, network devices, and keyboards are usually much slower.
- Different working modes: Some devices actively generate events, while others require the CPU to initiate requests.
- Different data formats: A keyboard generates key events, a network card generates network packets, and a disk handles block data.
- Different control methods: Different devices have different registers, commands, and status management mechanisms.
- Different concurrency requirements: Multiple devices may generate requests at the same time, requiring the operating system to coordinate their handling.
If the CPU had to personally control every detail of every data transfer for every device, not only would programs become complex, but a large amount of computing resources would also be wasted.
Therefore, the operating system needs a unified I/O management mechanism.
1. What Problems Does I/O Management Solve?
I/O management mainly solves five types of problems:
- Device abstraction: Uniformly abstract different hardware devices into objects that the operating system can manage.
- Device control: Control hardware operation through device drivers.
- Event notification: Use interrupts to notify the CPU of device state changes.
- Data transfer: Transfer data through mechanisms such as programmed I/O, interrupt-driven I/O, and DMA.
- Resource coordination: Manage device access permissions, request queues, buffers, and concurrent operations.
2. Overall Architecture of the I/O System
Operating systems usually manage input/output devices through a multi-layer structure.
flowchart TD
A["Application"] --> B["System call interface"]
B --> C["Kernel I/O subsystem"]
C --> D["Device driver"]
D --> E["Device controller"]
E --> F["Physical device"]
F --> G["Device status and data"]
G --> E
E --> D
D --> C
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style C fill:#E9E2F8,stroke:#B7A5D8,color:#514078
style D fill:#FFF1D6,stroke:#E7C77E,color:#76551C
style E fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style F fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style G fill:#F1F3F5,stroke:#C8CDD3,color:#475569
Responsibilities of each layer:
| Layer | Core responsibility |
|---|---|
| Application | Initiate file read/write, network communication, device access, and other requests |
| System call interface | Provide a unified entry point for kernel access |
| Kernel I/O subsystem | Manage requests, buffering, queues, permissions, and error handling |
| Device driver | Convert generic operations into device-specific commands |
| Device controller | Directly control hardware and perform data transfer |
| Physical device | Actually perform input, output, or storage operations |
Note: A device driver does not necessarily communicate directly with the physical device; between them there are usually a device controller, bus, and platform-related hardware interfaces.
II. What Is a Device Driver?
A device driver is a software bridge between the operating system and hardware devices.
Different hardware devices are controlled in different ways.
For example:
- Keyboard drivers need to handle key scan codes and input events.
- Disk drivers need to handle block device requests and read/write commands.
- Network card drivers need to manage packet send/receive queues.
- Graphics card drivers need to manage graphics devices and hardware execution resources.
If every application needed to understand these hardware details, software would be very difficult to develop and maintain.
A device driver encapsulates hardware operations and provides the operating system with a unified way to access them.
1. Core Responsibilities of a Device Driver
Device initialization
When the system starts or a device is connected, the driver is responsible for identifying the device, initializing the hardware, and configuring operating parameters.
Device control
The driver is responsible for sending commands to the device, such as starting a transfer, setting a mode, and querying status.
Data transfer
The driver coordinates data exchange among the CPU, memory, and device controllers.
Interrupt Handling
When a device completes an operation or an exception occurs, the driver is responsible for handling the interrupt event.
Error Handling
When a device times out, a transfer fails, or a hardware exception occurs, the driver needs to perform error recovery or report the error.
Resource Management
The driver needs to manage device registers, DMA buffers, interrupt resources, device queues, etc.
2. How Does a Device Driver Work?
Take reading disk data as an example.
An application calls read(), the operating system receives the request, the file system converts the request into a block device operation, and the block device layer submits the request to the disk driver.
The driver constructs hardware commands according to the device type, submits them to the controller, and waits for the device to complete the data transfer.
flowchart TD
A["Application calls read"] --> B["Kernel receives read request"]
B --> C["File system parses file location"]
C --> D["Block device layer generates I/O request"]
D --> E["Disk driver handles the request"]
E --> F["Device controller performs the read"]
F --> G["Device completes data transfer"]
G --> H["Interrupt notifies CPU"]
H --> I["Driver completes the request"]
I --> J["Kernel returns read result"]
J --> K["Application obtains data"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style C fill:#E9E2F8,stroke:#B7A5D8,color:#514078
style D fill:#FFF1D6,stroke:#E7C77E,color:#76551C
style E fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style F fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style G fill:#E9E2F8,stroke:#B7A5D8,color:#514078
style H fill:#FFF1D6,stroke:#E7C77E,color:#76551C
style I fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style J fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style K fill:#E9E2F8,stroke:#B7A5D8,color:#514078
There is an important distinction to understand here:
read()is the system call interface used by applications.- The file system is responsible for parsing files and organizing storage requests.
- The block device layer is responsible for organizing block device requests.
- The driver is responsible for device-specific control operations.
- The device controller is responsible for actually controlling the hardware.
Applications usually do not need to directly know the register and command formats of the disk controller.
3. Where Do Device Drivers Run?
Common device drivers can be divided into two categories.
| Type | Where It Runs | Characteristics |
|---|---|---|
| Kernel-mode driver | OS kernel space | Can directly use kernel interfaces and hardware resources, with stronger performance and control capabilities |
| User-mode driver | User space | Accesses devices through controlled interfaces, with better isolation |
In Linux, a large number of device drivers run in kernel mode.
User-mode drivers also have use cases, such as certain USB device access frameworks, user-mode network processing, and dedicated hardware runtimes.
Kernel-mode drivers have relatively high privileges; if an out-of-bounds memory access, null pointer, or incorrect concurrent access occurs, the stability of the entire system may be affected.
User-mode drivers can reduce the impact of some failures through process isolation, but the kernel still needs to provide secure device access interfaces.
3. Device Controllers and Device Registers
A device driver needs to control a device through a hardware interface.
One of the most important hardware components is the device controller.
1. What Is a Device Controller?
A device controller, called Device Controller in English, is a hardware module responsible for controlling the operation of a specific hardware device.
It can be integrated inside the device or serve as a standalone chip or part of a host controller.
For example:
- SATA controllers manage communication with SATA storage devices.
- NVMe controllers manage NVMe SSD command queues.
- USB host controllers manage USB bus transfers.
- Network interface controllers are responsible for sending and receiving Ethernet frames.
The CPU usually does not directly control every circuit operation inside the device; instead, it submits commands, exchanges data, and reads status through the controller.
2. Device Registers
A device controller usually provides a set of registers for receiving commands, returning status, and exchanging data.
Common registers include:
| Register | Function |
|---|---|
| Data register | Stores data to be transferred |
| Status register | Indicates whether the device is busy, has completed, or has encountered an error |
| Control register | Sets the device operating mode and control commands |
| Command register | Receives commands for the device to execute |
| Interrupt status register | Records interrupt events and their status |
For example, a simple device controller may have the following states:
#define DEVICE_STATUS_BUSY 0x01
#define DEVICE_STATUS_DONE 0x02
#define DEVICE_STATUS_ERROR 0x04
After the driver reads the status register, it can determine what state the device is currently in.
The code here only illustrates the concept of register states; it does not represent a unified register definition for real hardware.
3. Memory-Mapped I/O and Port-Mapped I/O
The CPU needs to access device registers through a certain addressing mechanism.
There are two common approaches.
Memory-Mapped I/O, MMIO
Memory-Mapped I/O maps device registers into the processor's physical address space.
The CPU uses instructions similar to memory accesses to read from and write to device registers.
For example:
#include <stdint.h>
volatile uint32_t *status =
(volatile uint32_t *)0xF0000000;
uint32_t value = *status;
Here, 0xF0000000 is assumed to be the mapped address of a device register.
In practice, this address cannot be accessed arbitrarily; the operating system must handle mapping and permission management.
volatile can restrict certain compiler optimizations for the relevant accesses, but it cannot replace memory barriers, nor can it guarantee all requirements for multithreaded synchronization or device access ordering.
Port-Mapped I/O, PIO
Port-Mapped I/O uses a separate I/O address space to access device registers.
On traditional x86 architectures, dedicated in and out instructions can be used.
Illustrative code:
static inline unsigned char inb(unsigned short port)
{
unsigned char value;
__asm__ volatile (
"inb %1, %0"
: "=a"(value)
: "Nd"(port)
);
return value;
}
This example shows how x86 port I/O is accessed; actual drivers need to use it within the permission and interface constraints provided by the operating system.
4. Differences Between MMIO and PIO
| Comparison Dimension | MMIO | PIO |
|---|---|---|
| Address space | Mapped into the physical memory address space | Separate I/O address space |
| Access method | Ordinary load and store instructions | Dedicated I/O instructions |
| Common scenarios | PCIe devices, modern hardware controllers | Legacy x86 devices |
| Caching attributes | Device memory attributes need to be set correctly | Not cached as ordinary memory |
| Architecture support | Widely used across multiple processor architectures | Mainly found in specific architectures |
Special attention is required: MMIO is not equivalent to ordinary RAM. Device register accesses have special semantics and must not be arbitrarily cached, merged, or reordered.
IV. How Does the CPU Know the Device Has Completed an Operation?
An event notification mechanism is needed between the CPU and devices.
Suppose an application requests to read disk data; the disk may take several milliseconds or even longer to complete the operation.
If the CPU waits continuously for the disk to finish, processor resources are wasted.
Operating systems mainly use three I/O control methods:
- Programmed I/O, also called polling.
- Interrupt-driven I/O.
- DMA, or Direct Memory Access.
They solve different problems, and real systems often use them in combination.
V. Programmed I/O: Polling Mechanism
Polling refers to the CPU actively and repeatedly querying device status to determine whether the device has completed an operation.
1. Basic Principle of Polling
Suppose the CPU sends a read command to a device.
After the device starts working, the CPU continuously reads the status register.
When the device completes the operation, the status register changes, and the CPU continues execution after detecting the completion status.
flowchart TD
A["CPU initiates device request"] --> B["Device starts working"]
B --> C["CPU reads status register"]
C --> D{"Has the device completed?"}
D -->|No| E["Continue polling"]
E --> C
D -->|Yes| F{"Has an error occurred?"}
F -->|Yes| G["Handle device error"]
F -->|No| H["Read or process data"]
G --> I["End this operation"]
H --> I
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style C fill:#E9E2F8,stroke:#B7A5D8,color:#514078
style D fill:#FFF1D6,stroke:#E7C77E,color:#76551C
style E fill:#F1F3F5,stroke:#C8CDD3,color:#475569
style F fill:#FFF1D6,stroke:#E7C77E,color:#76551C
style G fill:#F1F3F5,stroke:#C8CDD3,color:#475569
style H fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style I fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
2. Polling Code Example
#define STATUS_BUSY 0x01
#define STATUS_ERROR 0x02
int wait_device_ready(volatile unsigned int *status)
{
while (*status & STATUS_BUSY) {
// Device is still working, continue checking
}
if (*status & STATUS_ERROR) {
return -1;
}
return 0;
}
This is a simplified illustrative program. A real driver usually also needs to consider timeouts, memory access ordering, device error recovery, and CPU usage.
3. Advantages and Disadvantages of Polling
Advantages:
- Simple to implement.
- Clear control flow.
- Does not require complex interrupt-handling logic.
- For devices with extremely short response times, it can avoid interrupt-handling overhead.
Disadvantages:
- The CPU may continuously perform useless queries.
- When device response is slow, CPU resource waste is significant.
- When multiple devices are polled simultaneously, management overhead increases.
4. What Scenarios Is Polling Suitable For?
Polling is not an outdated technology.
Polling may still be used in the following scenarios:
- Device operation time is very short.
- There are strict requirements on response latency.
- Device request frequency is high.
- Polling overhead is lower than interrupt-handling overhead.
- The system needs to avoid unpredictable delays caused by interrupts.
For example, high-performance network processing can use polling mode to reduce interrupt frequency and context-switching costs.
VI. Interrupt-Driven I/O: Devices Actively Notify the CPU
An interrupt is one of the core mechanisms by which computer hardware and operating systems work together.
Unlike polling, interrupt-driven I/O does not require the CPU to continuously query device status.
When a device needs the CPU to handle something, it actively sends an interrupt request to the processor.
1. What Is an Interrupt?
An interrupt is a mechanism by which the processor responds to external or internal events.
For example:
- A keyboard generates key input.
- A network card receives a data packet.
- A disk completes a transfer.
- A timer expires.
- A hardware device reports an exception.
After a device generates an interrupt request, the CPU determines whether it needs to respond according to the interrupt control mechanism.
If the response conditions are met, the CPU suspends the current execution flow and switches to the corresponding interrupt-handling routine.
2. Basic Flow of Interrupt Handling
Take a network card receiving a data packet as an example:
- The network card receives network data.
- The network card places the data into a receive buffer or DMA buffer.
- The network card generates an interrupt request.
- The interrupt controller submits the interrupt to the CPU.
- The CPU saves the necessary execution context.
- The CPU uses the interrupt vector to find the corresponding handler entry point.
- The kernel executes the interrupt handler.
- The driver confirms the interrupt source and handles the device status.
- The kernel completes the interrupt return and restores the original execution flow.
flowchart TD
A["Device generates an event"] --> B["Device sends an interrupt request"]
B --> C["Interrupt controller receives the request"]
C --> D{"Can the CPU respond?"}
D -->|No| E["Wait until the interrupt conditions are met"]
E --> D
D -->|Yes| F["CPU saves the necessary execution context"]
F --> G["Enter the handler entry point based on the interrupt vector"]
G --> H["Execute the interrupt handler"]
H --> I["Driver confirms the interrupt source"]
I --> J{"Is there pending work?"}
J -->|Yes| K["Schedule follow-up processing"]
J -->|No| L["Finish interrupt handling"]
K --> L
L --> M["Restore the execution context"]
M --> N["Continue the original execution flow"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style C fill:#E9E2F8,stroke:#B7A5D8,color:#514078
style D fill:#FFF1D6,stroke:#E7C77E,color:#76551C
style E fill:#F1F3F5,stroke:#C8CDD3,color:#475569
style F fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style G fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style H fill:#E9E2F8,stroke:#B7A5D8,color:#514078
style I fill:#FFF1D6,stroke:#E7C77E,color:#76551C
style J fill:#FFF1D6,stroke:#E7C77E,color:#76551C
style K fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style L fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style M fill:#F1F3F5,stroke:#C8CDD3,color:#475569
style N fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
The execution context here usually includes the processor state needed to resume execution, such as the program counter, the status register, and the necessary general-purpose registers.
Exactly which registers are saved is determined by the processor architecture and by how the operating system implements the interrupt entry.
3. Interrupt Vector Table
How does the CPU know which interrupt handler it should execute?
The answer is the interrupt vector mechanism.
An interrupt vector is a number or index used to identify an interrupt type or handler entry point.
Through data structures such as the interrupt descriptor table, the operating system and the processor establish the association between an interrupt source and the entry point of its handler.
On the x86 architecture, the operating system uses the IDT, that is, the Interrupt Descriptor Table.
Its main responsibilities include:
- Storing the entry point information for interrupt or exception handling.
- Describing the attributes and privileges of the corresponding entry.
- Providing the CPU with the entry address for interrupt or exception handling.
Conceptual structure:
flowchart TD
A["An interrupt or exception occurs"] --> B["CPU obtains the vector number"]
B --> C["Look up the IDT"]
C --> D["Read the handler entry descriptor"]
D --> E["Enter the corresponding handler"]
E --> F["Execute the handling logic"]
F --> G["Return from the interrupt or exception"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style C fill:#E9E2F8,stroke:#B7A5D8,color:#514078
style D fill:#FFF1D6,stroke:#E7C77E,color:#76551C
style E fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style F fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style G fill:#F1F3F5,stroke:#C8CDD3,color:#475569
Note that the IDT is a concrete mechanism of the x86 architecture; different processor architectures have their own ways of managing interrupt entry points and vectors.
4. Interrupt Controller
When multiple devices generate interrupt requests at the same time, the CPU needs to know:
- Which device raised the request?
- Which interrupt has the higher priority?
- Which interrupts can be deferred?
- After the current interrupt handling is complete, are there any other requests?
The interrupt controller is responsible for coordinating these requests.
Common interrupt controllers include:
| Type | Main Purpose |
|---|---|
| 8259 PIC | Programmable interrupt controller on traditional x86 platforms |
| Local APIC | Local interrupt management in x86 multiprocessor systems |
| I/O APIC | Interrupt routing for external devices on x86 platforms |
| GIC | Common generic interrupt controller on ARM platforms |
On modern x86 platforms, the APIC architecture handles interrupt management among multiple processor cores and routing of external interrupts.
ARM platforms commonly use the GIC architecture.
5. Classification of Interrupts
Interrupts can be classified from different perspectives.
By event source
| Type | Description | Example |
|---|---|---|
| External interrupt | Hardware event originating outside the processor | Network card, keyboard, timer |
| Internal exception | Exceptional condition detected while the CPU is executing an instruction | Division by zero, page fault |
| Software interrupt | Event actively triggered through a software mechanism | System call entry in some architectures |
Note that exceptions and external hardware interrupts are not exactly the same concept.
Exceptions are usually directly related to the currently executing instruction, whereas external interrupts usually come from independent hardware events.
In modern operating systems, system calls also often enter the kernel through dedicated processor instructions and do not necessarily use software interrupt instructions in the traditional sense.
By handling timing
| Type | Description |
|---|---|
| Maskable interrupt | Can be delayed depending on processor or interrupt controller state |
| Non-maskable interrupt | Has special priority and is usually used for important hardware events |
| Synchronous exception | Directly related to execution of the current instruction |
| Asynchronous interrupt | Has no direct causal relationship with the current instruction stream |
6. Differences Between Interrupts and Exceptions
| Comparison Dimension | Interrupt | Exception |
|---|---|---|
| Trigger source | Usually from external hardware events | Usually caused by execution of the current instruction |
| Timing relationship | Asynchronous | Synchronous |
| Typical examples | Network card, timer, keyboard | Division by zero, page fault |
| Depends on the current instruction | Usually no | Usually yes |
| Handling goal | Respond to external events | Handle exceptional conditions during execution |
For example, when a network card receives a packet, it generates an external interrupt, whereas when a program accesses a valid virtual address that has not yet been mapped, it may trigger a page fault exception.
7. Why Should Interrupt Handlers Be as Short as Possible?
Interrupt handlers usually run in a special kernel execution context.
If too many time-consuming operations are performed during interrupt handling, the response to other interrupts may be affected.
Therefore, operating systems usually divide interrupt handling into two parts:
- Top half: Acknowledge the interrupt as quickly as possible, read the necessary status, clear the interrupt cause, and schedule follow-up work.
- Bottom half: Complete relatively time-consuming processing tasks in an appropriate execution context.
Common bottom-half mechanisms in Linux include:
| Mechanism | Characteristics |
|---|---|
| Softirq | Software interrupt mechanism, suitable for high-frequency, relatively low-level deferred processing |
| Tasklet | A simpler deferred-processing mechanism based on softirqs; it is an older mechanism, and new code usually tends to use other mechanisms |
| Workqueue | Hands tasks to kernel worker threads for execution and can perform operations such as sleeping |
| Threaded IRQ | Places part of the interrupt handling logic in a kernel thread for execution |
For example, when a network card receives a packet, the interrupt handler can first acknowledge the interrupt and schedule network data processing work.
Subsequent protocol stack processing then does not all have to be squeezed into the hardware interrupt handling context.
Special attention is needed: hard interrupt context cannot sleep at will, nor can it call interfaces that can only be used in sleepable contexts.
VII. DMA: How Do Devices Access Memory Directly?
Interrupts solve the problem of how devices notify the CPU.
However, if the amount of data is large, relying solely on the CPU to move data still incurs significant overhead.
For example:
- Reading several MB of data from a disk.
- A network card receiving a large number of network packets.
- An audio device continuously transmitting audio data.
- A high-speed acquisition card continuously acquiring data.
If the CPU had to move data byte by byte or word by word, it would waste a large amount of computing resources.
DMA is designed to solve this problem.
1. What Is DMA?
DMA stands for Direct Memory Access.
It allows devices with DMA capability or a DMA controller, after obtaining the necessary access permissions and transfer configuration, to transfer data directly between the device and memory without the CPU moving each data unit one by one.
The CPU is mainly responsible for:
- Allocating or preparing DMA buffers.
- Establishing DMA mappings.
- Configuring the transfer address, length, and direction.
- Starting the device transfer.
- Waiting for device completion notification.
- Processing the transfer result.
During data transfer, the CPU can perform other tasks.
2. How DMA Works
Take a network card receiving data as an example:
flowchart TD
A["CPU prepares receive buffer"] --> B["Driver sets up DMA mapping"]
B --> C["Configure device DMA descriptors"]
C --> D["NIC receives network data"]
D --> E["NIC writes to memory via DMA"]
E --> F["Device updates transfer status"]
F --> G["Device raises an interrupt"]
G --> H["CPU enters driver interrupt handling"]
H --> I{"Was the transfer successful?"}
I -->|No| J["Perform error recovery"]
I -->|Yes| K["Driver processes the received data"]
K --> L["Submit to the network protocol stack"]
J --> M["End this round of processing"]
L --> M
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style C fill:#E9E2F8,stroke:#B7A5D8,color:#514078
style D fill:#FFF1D6,stroke:#E7C77E,color:#76551C
style E fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style F fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style G fill:#E9E2F8,stroke:#B7A5D8,color:#514078
style H fill:#FFF1D6,stroke:#E7C77E,color:#76551C
style I fill:#FFF1D6,stroke:#E7C77E,color:#76551C
style J fill:#F1F3F5,stroke:#C8CDD3,color:#475569
style K fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style L fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style M fill:#F1F3F5,stroke:#C8CDD3,color:#475569
3. Why Does DMA Improve Performance?
Suppose a device needs to transfer 100 MB of data.
With the traditional programmed I/O approach, the CPU may have to take part in a large number of data read and write operations.
With DMA, the CPU is mainly responsible for configuring the transfer task, while the data movement is carried out by the DMA hardware.
This reduces the amount of work the CPU has to do in copying data.
However, DMA does not mean there is no CPU overhead at all.
The CPU still has to handle:
- Buffer allocation.
- DMA address mapping.
- Descriptor configuration.
- Starting the device.
- Interrupt handling.
- Data coherency management.
- Processing the data after the transfer completes.
4. Common DMA Modes
| Type | Description |
|---|---|
| Device to memory | The device writes data to memory, for example a network card receiving |
| Memory to device | Memory supplies data to the device, for example a network card transmitting |
| Memory to memory | Some DMA controllers support transfers between memory regions |
5. DMA and Cache Coherency
DMA also involves an important issue: data coherency between the CPU cache and main memory.
Suppose the CPU modifies data in a buffer, but the data still exists only in the CPU cache.
At this point, if the device reads main memory via DMA, it may not see the CPU's latest modifications.
Conversely, after the device writes data to memory via DMA, the CPU may also read stale contents from an old cache line.
This is the DMA cache coherency problem.
Common solutions include:
- Hardware cache coherency mechanisms.
- DMA cache synchronization operations.
- Cache Clean.
- Cache Invalidate.
- The DMA mapping and synchronization interfaces provided by the operating system.
In Linux drivers, you should generally use the DMA API rather than treating an ordinary virtual address directly as a device DMA address.
For example:
dma_addr_t dma_handle;
void *buffer;
buffer = dma_alloc_coherent(
dev,
size,
&dma_handle,
GFP_KERNEL
);
if (!buffer) {
return -ENOMEM;
}
Here, dma_alloc_coherent() is used to allocate a buffer suitable for coherent DMA use.
Once it is no longer needed, the resources should be released through the corresponding DMA API.
Note that:
- A CPU virtual address is not necessarily equal to the physical address.
- The physical address is also not necessarily equal to the DMA address seen by the device.
- An IOMMU may be involved in DMA address translation.
- Cache coherency strategies may differ across platforms.
Therefore, drivers should follow the DMA API provided by the operating system.
VIII. How Do Interrupts, DMA, and Polling Work Together?
Polling, interrupts, and DMA are not three mutually exclusive technologies.
They address problems at different levels:
| Mechanism | Main problem addressed |
|---|---|
| Polling | How the CPU determines device status |
| Interrupts | How devices proactively notify the CPU |
| DMA | How to reduce CPU involvement in data movement |
Actual hardware usually uses them in combination.
For example, when a network card receives data:
- The driver prepares receive buffers in advance.
- The driver configures DMA descriptors.
- The network card receives network data.
- The network card uses DMA to write to memory.
- The network card generates an interrupt to notify the CPU.
- The driver processes the data and replenishes new receive buffers.
This combination balances data transfer efficiency and event responsiveness.
1. Relationship Between Interrupts and DMA
It can be understood as follows:
- DMA handles moving data.
- Interrupts handle notifying the CPU.
- The driver coordinates the two.
- The kernel I/O subsystem manages requests and results.
DMA does not necessarily need to generate an interrupt for every transfer.
For high-performance devices, techniques such as batch completion notifications, polling completion queues, or interrupt coalescing may be used.
2. Interrupt Coalescing
If the network card generates an interrupt every time it receives a packet, then under high-traffic scenarios, the number of interrupts may be very large.
Interrupt Coalescing means that a device combines multiple events before notifying the CPU.
For example, a network card can generate an interrupt after receiving a certain number of packets, or it can notify the CPU after waiting for a period of time.
Advantages:
- Reduces the number of interrupts.
- Lowers CPU interrupt handling overhead.
- Improves batch processing efficiency.
Disadvantages:
- Data notification may be delayed to some extent.
- Latency-sensitive applications may be affected.
Therefore, interrupt coalescing requires a trade-off between throughput and latency.
3. NAPI: Linux Network Receive Mechanism
The Linux network subsystem uses NAPI, short for New API, to handle high-performance network receive processing.
It combines interrupt notification with polling-based processing:
- When data arrives at a network device, the CPU is first notified through an interrupt.
- The driver disables or suppresses the relevant receive interrupts and schedules NAPI processing.
- The kernel processes received packets in batches by polling.
- If there is still data to be processed, polling continues.
- If processing is complete, receive interrupts are re-enabled.
flowchart TD
A["NIC receives packets"] --> B["NIC triggers receive interrupt"]
B --> C["Driver acknowledges interrupt"]
C --> D["Schedule NAPI processing"]
D --> E["Temporarily suppress receive interrupts"]
E --> F["NAPI polls packets in batches"]
F --> G{"Is there still pending data?"}
G -->|Yes| H["Continue batch processing"]
H --> F
G -->|No| I["Complete this round of NAPI processing"]
I --> J["Re-enable receive interrupts"]
J --> K["Wait for the next batch of data"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style C fill:#E9E2F8,stroke:#B7A5D8,color:#514078
style D fill:#FFF1D6,stroke:#E7C77E,color:#76551C
style E fill:#F1F3F5,stroke:#C8CDD3,color:#475569
style F fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style G fill:#FFF1D6,stroke:#E7C77E,color:#76551C
style H fill:#E9E2F8,stroke:#B7A5D8,color:#514078
style I fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style J fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style K fill:#F1F3F5,stroke:#C8CDD3,color:#475569
The core idea of NAPI is: use interrupts to reduce useless polling under low load, and use batch polling to reduce interrupt overhead under high load.
9. I/O Buffering: Why Do We Need Buffers?
There is a clear speed difference between the CPU, memory, and external devices.
If the rate at which a device produces data differs from the rate at which the CPU consumes it, a buffering mechanism is needed to coordinate the two.
1. What Is I/O Buffering?
I/O Buffering means setting up a temporary storage area between the data producer and the consumer.
For example:
- Keyboard input first enters the kernel input buffer.
- File reads may use the page cache.
- A network card stores packets in receive buffers.
- Audio devices exchange data continuously through ring buffers.
Buffers mainly solve three problems:
- Balance the speed difference between devices and the CPU.
- Reduce frequent small-scale I/O operations.
- Temporarily store data that has not yet been processed or transmitted.
2. Basic Working Method of Buffering
Suppose a device continuously produces data, and the CPU is responsible for processing the data.
The device puts data into the buffer, and the CPU takes data out of the buffer for processing.
flowchart TD
A["Device generates data"] --> B["Data enters I/O buffer"]
B --> C["Buffer holds pending data"]
C --> D{"Is the CPU able to process it?"}
D -->|No| E["Data is temporarily stored in the buffer"]
E --> D
D -->|Yes| F["CPU reads data"]
F --> G["CPU processes data"]
G --> H["Release processed space"]
H --> I["Continue receiving new data"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style C fill:#E9E2F8,stroke:#B7A5D8,color:#514078
style D fill:#FFF1D6,stroke:#E7C77E,color:#76551C
style E fill:#F1F3F5,stroke:#C8CDD3,color:#475569
style F fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style G fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style H fill:#E9E2F8,stroke:#B7A5D8,color:#514078
style I fill:#FFF1D6,stroke:#E7C77E,color:#76551C
3. Common Buffering Approaches
Single buffering
The system uses one buffer to hold data.
The advantage is its simple structure; the disadvantage is that data production and consumption may wait on each other.
Double buffering
The system uses two buffers.
One buffer receives data while the other is used to process data, thereby increasing the degree of parallelism between producer and consumer.
Ring buffer
A Ring Buffer uses a fixed-size storage space and reuses it cyclically through read and write pointers.
It is widely used in NIC queues, serial port drivers, audio devices, and high-performance data processing.
The logical structure of a ring buffer:
Read pointer
|
v
+------+------+------+------+------+
| Data | Data | Free | Free | Data |
+------+------+------+------+------+
^
|
Write pointer
The above shows a structural illustration; it does not mean that the read and write pointers in a specific implementation must be arranged this way.
4. Key Issues of Ring Buffers
When implementing a ring buffer, you need to consider:
- How the read and write pointers are updated.
- How to handle a full buffer.
- How to determine when the buffer is empty.
- Whether multiple producers and multiple consumers require locks.
- Whether atomic operations are used.
- Whether memory barriers are needed.
- Whether data is allowed to overwrite old data.
For example, a single-producer single-consumer ring buffer can achieve lock-free operation through atomic variables and appropriate memory ordering.