Write a 16550 UART Driver for QEMU's RISC-V virt Machine
Drive the NS16550A UART at 0x10000000 on QEMU's RISC-V virt machine with volatile MMIO in C: initialize it, send and poll bytes, then add receive interrupts.

The first thing a new kernel needs is a way to talk to you, and on QEMU's RISC-V virt machine that is a serial port. It is a standard 16550 UART mapped into physical memory at 0x10000000, and the driver for it is about thirty lines of C. The same chip, or a clone of it, sits on thousands of boards, and the register model is more than forty years old, so what you learn here reads real hardware too. This post builds the driver from nothing: what memory-mapped I/O is, what each register does, how to send a byte, how to receive one by polling, and how to switch to interrupt-driven receive.
You can start from a kernel that already boots, as in the bare-metal kernel post of this series, and replace the firmware console with this driver. The device description comes from the NS16550A datasheet, and the board layout from QEMU's virt machine documentation.
What memory-mapped I/O means
A device on a RISC-V system has no special instruction. Its registers appear at fixed physical addresses, and a load or a store to one of those addresses talks to the device instead of memory. The UART's registers are at 0x10000000 upward, one byte each. Writing a byte to the transmit register sends that byte down the wire, and reading the receive register takes a byte off it.
Two properties of this arrangement need handling in C. First, the compiler does not know these addresses are special, and it may remove, reorder or merge accesses it believes are redundant. Marking the pointer volatile forbids that: every access in the source is performed, in order. Second, the UART's registers are one byte wide, so access them as uint8_t, not as words, or you will read and write the neighboring registers too.
#include <stdint.h>
#define UART0 0x10000000UL
#define UART_RBR 0 // receive buffer, read
#define UART_THR 0 // transmit holding, write
#define UART_IER 1 // interrupt enable
#define UART_IIR 2 // interrupt identification, read
#define UART_FCR 2 // FIFO control, write
#define UART_LCR 3 // line control
#define UART_MCR 4 // modem control
#define UART_LSR 5 // line status
#define UART_DLL 0 // divisor latch low, when LCR bit 7 is set
#define UART_DLM 1 // divisor latch high, when LCR bit 7 is set
#define LSR_DATA_READY 0x01
#define LSR_THR_EMPTY 0x20
static inline uint8_t uart_read(int reg)
{
return *(volatile uint8_t *)(UART0 + reg);
}
static inline void uart_write(int reg, uint8_t v)
{
*(volatile uint8_t *)(UART0 + reg) = v;
}Notice that some registers share an offset: reading offset 0 gives received data and writing it sends data, and offset 2 is the interrupt identification register when read and the FIFO control register when written. The chip tells them apart by the direction of the access. When the Divisor Latch Access bit, bit 7 of the line control register, is set, offsets 0 and 1 switch to the baud rate divisor registers instead.
Initialize the port
A freshly reset 16550 works at defaults in QEMU, which ignores baud rates and treats the port as a byte pipe, but a driver that also runs on hardware must set the line parameters. The standard sequence has four steps: disable interrupts, set the baud rate divisor, set the data format, and enable and clear the FIFOs.
void uart_init(void)
{
uart_write(UART_IER, 0x00); // 1. mask all UART interrupts
uart_write(UART_LCR, 0x80); // 2. set DLAB to reach the divisor registers
uart_write(UART_DLL, 0x02); // divisor 2: 3.6864 MHz / 16 / 2 = 115200 baud
uart_write(UART_DLM, 0x00);
uart_write(UART_LCR, 0x03); // 3. 8 data bits, no parity, 1 stop bit; DLAB off
uart_write(UART_FCR, 0x07); // 4. enable FIFOs and reset both of them
}The divisor comes from the input clock. The virt machine's device tree declares the UART clock as 3,686,400 Hz, and a 16550 divides the clock by 16 times the divisor to get the baud rate, so a divisor of 2 gives 3,686,400 / 32 = 115,200 baud. On a board with a different clock, read the clock-frequency property from its device tree and compute the divisor from it.
The line control value 0x03 selects word length bits 1:0 equal to 3, meaning 8 data bits, with parity and the second stop bit off, the format virtually every serial terminal expects. The FIFO control value 0x07 sets bit 0 to enable the 16-byte FIFOs and bits 1 and 2 to clear the receive and transmit FIFOs.
Send a byte
The transmit holding register accepts a byte only when the previous one has left it. The line status register's bit 5, "transmit holding register empty", says so. The driver waits for it and then writes:
void uart_putc(char c)
{
while (!(uart_read(UART_LSR) & LSR_THR_EMPTY))
; // spin until the register can take a byte
uart_write(UART_THR, (uint8_t)c);
}
void uart_puts(const char *s)
{
while (*s) {
if (*s == '\n')
uart_putc('\r'); // terminals expect CR before LF
uart_putc(*s++);
}
}The carriage return in uart_puts fixes a classic annoyance. A serial terminal treats line feed as "move down" and carriage return as "move to column zero", so a bare newline produces a staircase of text. Sending a carriage return followed by a newline gives a normal line break.
Call these from the kernel entry:
void kmain(void)
{
uart_init();
uart_puts("hello from the uart driver\n");
}On make run with QEMU's -nographic, the serial port is wired to your terminal, and the line appears:
hello from the uart driverReceive a byte by polling
Receiving mirrors sending: bit 0 of the line status register, "data ready", says a byte is waiting in the receive buffer. Reading RBR takes it and clears the bit.
int uart_getc_nonblock(void)
{
if (uart_read(UART_LSR) & LSR_DATA_READY)
return uart_read(UART_RBR);
return -1; // nothing waiting
}
int uart_getc(void)
{
int c;
while ((c = uart_getc_nonblock()) < 0)
; // busy wait for a key
return c;
}With these two functions, a minimal echo loop proves both directions. Type into the terminal and each character comes back:
for (;;) {
int c = uart_getc();
uart_putc((char)c);
}helloTyping hello and pressing keys echoes hello, because each uart_getc returns as soon as a key arrives. QEMU's terminal sends a carriage return for the Enter key, so the loop needs to translate it to a newline if you want line editing.
Polling works and is wasteful. The CPU sits in a loop doing nothing useful, and no other work can happen while it waits. The remedy is an interrupt.
Receive with an interrupt
The 16550 raises an interrupt line when data arrives, if you enable it in the interrupt enable register. That line is wired on virt to the PLIC, the platform interrupt controller, as source number 10. So receive-by-interrupt needs three pieces: the UART's own enable bit, the PLIC configuration, and a handler.
Enable the UART side by setting bit 0 of IER, "received data available":
void uart_enable_rx_interrupt(void)
{
uart_write(UART_IER, 0x01);
}Configure the PLIC with a priority for source 10, an enable bit for your hart's supervisor context and a zero threshold, then set sie.SEIE. The CLINT and PLIC post covers these registers in full. Then the handler claims the interrupt and drains the UART:
#define RX_BUF 128
static volatile char rx_ring[RX_BUF];
static volatile unsigned rx_head, rx_tail;
void uart_irq(void)
{
while (uart_read(UART_LSR) & LSR_DATA_READY) {
char c = (char)uart_read(UART_RBR);
unsigned next = (rx_head + 1) % RX_BUF;
if (next != rx_tail) { // drop input if the ring is full
rx_ring[rx_head] = c;
rx_head = next;
}
}
}
int uart_read_buffered(void)
{
if (rx_tail == rx_head)
return -1;
char c = rx_ring[rx_tail];
rx_tail = (rx_tail + 1) % RX_BUF;
return (unsigned char)c;
}The handler loops while data is ready, because the FIFO may hold several bytes by the time the interrupt is serviced, and a handler that reads only one leaves the interrupt line asserted and loses throughput. The head and tail indexes make a single-producer, single-consumer ring: the interrupt handler writes rx_head, and the reading code writes rx_tail, so on one hart the two never conflict, as long as each index is read and written as a whole.
A shell that uses uart_read_buffered in a loop, sleeping when it returns -1, no longer wastes cycles. That is the design the guide and the shell post build on.
What the code gets wrong on real hardware
The driver is correct for QEMU and for the common case, and two assumptions are worth naming. It assumes the 16550's registers are byte-wide at consecutive byte addresses. Some boards put a 16550-compatible UART behind a bus that spaces the registers 4 bytes apart (reg-shift = 2 in the device tree) or accesses them as 32-bit words. The SiFive and other vendor UARTs are an entirely different design that merely shares a use. Read the device tree node's compatible string, which for virt is ns16550a, before assuming the layout. The second assumption is that the transmit loop never gives up. A UART with flow control asserted by a disconnected peer can block uart_putc forever, so a kernel that must not hang adds a timeout or drops output.


