Section 6.38

Device driver

Definition

A device driver is the software that operates one kind of hardware device, such as a serial port, a sensor or a radio, for the rest of the system. The driver knows the device’s registers, the memory addresses through which the processor reads the device’s status and gives it commands, and it hides them behind functions that other code calls. A driver sets the device up, turns each request into register writes, handles the device’s interrupts §6.11, and reports when a request has finished or failed.

The idea

An application wants to send 64 bytes over a UART §6.23 (universal asynchronous receiver-transmitter), the serial port found on almost every microcontroller §6.1. Without a driver, the application itself would have to know the address of the UART’s data register, which status bit says that the transmitter can take another byte, how to set the speed, and which interrupt fires when a byte has gone. Another chip puts all of these at different addresses with different bit layouts, so every application would need one version per chip. A driver collects that knowledge in one place and offers one request instead: send these 64 bytes.

The device works in parallel with the processor, and that makes the driver’s most important promise a promise about time. A send function can return long before the bytes have left the chip, because the hardware keeps working after the call returns. So “the function returned”, “the hardware has finished reading my buffer”, “the last bit has left the pin” and “the receiver has the data” are four different moments. The driver’s completion contract states which of these moments it reports as done.

A post office counter is a fair picture: a clerk who says “accepted” has not delivered the letter. The picture stops at one point. The post office keeps the letter, but a driver often only borrows the caller’s memory: the bytes stay where the caller put them, and the hardware reads them from there later. The caller must therefore leave them unchanged until the driver says it has finished with them.

How it works

The parts a driver works with:

An asynchronous interface lets the caller submit a request without waiting for the transfer. A typical transfer proceeds as follows.

  1. Initialization, once at start-up: the driver switches on the device’s clock, connects the device to its pins, writes the speed and format registers, and enables the device’s interrupt.

  2. Submission: the caller passes a buffer and a length. The driver checks the arguments and refuses the request if another transfer is still running. It then either copies the bytes into memory of its own, or records the caller’s buffer address and borrows the buffer.

  3. Start: the driver programs the DMA unit with the buffer address and the length, or writes the first byte into the data register, and returns to the caller. The return value means accepted, not finished.

  4. Hardware work: the DMA unit reads the bytes one by one, and the UART shifts each byte out bit by bit.

  5. Interrupt: the device signals an event, such as the DMA unit having read the last byte, the transmitter having become idle, or an error. The ISR reads the status register, clears the event and updates the driver state.

  6. Completion: the driver tells the caller that the request has ended, and how: success, error, or the number of bytes sent before an abort. It does so by calling a function that the caller registered earlier, called a callback §14.22, by releasing a semaphore §9.6, a kernel counter that the caller’s thread waits on, or by setting a status flag. From then on the driver no longer touches the caller’s buffer.

Zephyr §6.33, an operating system for microcontrollers, shows the common forms side by side. Each device is a struct device that points to the device’s constant settings, its changing state, and a table of the driver’s functions; a generic call such as uart_tx() goes through that table to the driver for the chip. Zephyr’s UART interface offers three styles.

Worked example

A caller sends 64 bytes over a UART at 115200 baud, meaning 115200 bits per second on the wire. Each byte travels as a frame of 10 bits: a start bit, 8 data bits and a stop bit. One frame takes 10/115200s≈86.8μs10 / 115200\ \text{s} \approx 86.8\ \mu\text{s}, so 64 frames take 640/115200s≈5556μs640 / 115200\ \text{s} \approx 5556\ \mu\text{s}, about 5.56 ms. The driver borrows the buffer and uses DMA. The UART in this example has a holding register, which keeps one waiting byte, in front of its shift register, which sends the bits of one byte one at a time; the DMA unit refills the holding register whenever it becomes empty. Time 0 is the moment of the call.

A completion report at 5.38 ms correctly answers the question “may I reuse the buffer?”. The same report is wrong for “may I switch off the UART?”: switching it off at 5.38 ms cuts off the last two bytes. A report at 5.56 ms answers both questions, but neither report says that the receiver has the data. A driver that copies the 64 bytes into its own memory lets the caller reuse the buffer as soon as the call returns. The copy costs 64 bytes of memory and the time to copy them, and the bytes still leave the pin at 5.56 ms.

Stated precisely

Let trett_{\mathrm{ret}} be the time at which the submitting call returns, tbuft_{\mathrm{buf}} the time of the last access to the caller’s buffer by the driver or the hardware, twiret_{\mathrm{wire}} the time at which the last bit leaves the device, and tackt_{\mathrm{ack}} the time at which the receiver’s answer arrives, if the protocol has one. For the example in which the transmitter borrows the buffer and makes its last read before the final bit leaves, tbuf≤twire≤tackt_{\mathrm{buf}} \le t_{\mathrm{wire}} \le t_{\mathrm{ack}}, because the hardware must read a byte before it can send it and the receiver can answer only after the bytes have arrived. For a driver that copies, tbuf≤trett_{\mathrm{buf}} \le t_{\mathrm{ret}}.

A driver’s completion contract names one event EE, such as the moment tbuft_{\mathrm{buf}} or the moment twiret_{\mathrm{wire}}, and promises two things.

  1. The completion report happens at or after EE.

  2. After the report, neither the driver nor the hardware reads or writes the caller’s buffer, so for a borrowed buffer the report comes at or after tbuft_{\mathrm{buf}}.

The caller may rely on exactly the facts that hold at EE and on nothing that happens later. In return, the caller keeps a borrowed buffer valid and unchanged from submission until the report, and does not read a report of tbuft_{\mathrm{buf}} as a report of twiret_{\mathrm{wire}} or of tackt_{\mathrm{ack}}. On a processor with a data cache, a small fast copy of recently used memory, the second promise also needs the cache and memory to agree: the driver writes cached data back to memory before a DMA read, and discards stale cached copies before the processor reads data that DMA wrote.

Limits and common mistakes

A return value of 0 from an asynchronous call means that the request was accepted. It does not mean that any byte has left the chip.

The same function name can stand for different completion events on different chips. Zephyr’s description of UART_TX_DONE does not say whether the last stop bit has already left the pin. Zephyr’s interrupt-driven interface has a separate test, uart_irq_tx_complete(), which reports that everything has been sent and the transmitter is idle, the condition its documentation gives for switching the UART off.

A transfer can end half done. An error or an abort can come after some bytes have been sent, so the report must say how many; Zephyr’s abort event carries that information.

Cancellation §9.29 races with completion: a request to cancel can arrive just after the hardware has finished. A correct driver reports exactly one outcome for each request.

The callback often runs inside the ISR. It must then be short and must not wait for anything, such as a mutex §9.5, a lock held by another thread, because an interrupt handler is not allowed to wait.

Some DMA units can read only RAM. A driver that borrows a buffer stored in flash memory §6.6, such as a constant string, must copy it to RAM first or refuse it.

A driver is trusted code. Its DMA unit writes wherever it is told to, and the memory protection unit §6.8 of a Cortex-M processor checks only the processor’s own accesses, not DMA, so a driver bug can corrupt any memory that the DMA unit can reach.

Questions answered

When does a driver report an asynchronous transfer complete?

A driver reports completion when the event specified by its interface has occurred. Submission may return first, or a fast operation may invoke the completion callback before submission returns. Initialize the state that the callback will use before submitting the request. For most drivers, completion means that the hardware has finished with the caller’s buffer: the last byte to be sent has been read from it, or the last received byte has been written into it. From then on the caller may reuse or free the buffer. The driver reports completion by calling a callback function, by releasing a semaphore that the caller waits on, or by setting a status flag, usually from its interrupt service routine (ISR), the function that runs when the device signals an event.

Being finished with the buffer is not the same as having finished sending. In a UART (universal asynchronous receiver-transmitter) at 115200 bits per second, the hardware finishes reading a 64-byte buffer about 0.17 ms, two byte times, before the last bit leaves the pin; switching the device off at the earlier moment loses the last two bytes. No driver completion means that the receiver has the data; only an answer from the receiver shows that. So check, for each driver, which event its completion stands for, whether it covers partial transfers and errors, and in which context the report runs.

Related entries: Direct memory access (DMA) (§4.36), Asynchronous completion (§9.28), Hardware abstraction layer (HAL) (§6.42), UART (§6.23), Interrupt service routine (ISR) (§6.12), Borrowed pointer (§4.3).