- Written
- Published
- Updated
Lab: networking
UART
UART = Universal Asynchronous Receiver/Transmitter.
UART’s job is only:
- Take a byte from the CPU → serialize it (add start/stop bits) → send it out on the TX line.
- Take serial bits from the RX line → reassemble them into a byte → give it to the CPU.
Think of UART as a mailman, It is only responsible for sending or receive data to or from the external device!!! These devices do real work like draw pixels on screen, reads/writes blocks on disk, etc.
UART overall process
1. What is the UART here?
xv6 runs on a RISC‑V platform that exposes a 16550a‑compatible UART (Universal Asynchronous Receiver/Transmitter) at a fixed physical MMIO base address UART0 (defined in memlayout.h). The UART is a tiny piece of hardware that converts between:
- Parallel CPU loads/stores (to its memory-mapped registers)
- A serial bitstream on TX/RX pins (e.g., to your host terminal via QEMU)
You interact with it by reading/writing a handful of byte-sized registers:
- RHR (Receive Holding Register, read) – holds one received byte (if any)
- THR (Transmit Holding Register, write) – write a byte to send
- IER (Interrupt Enable Register) – enable RX/TX interrupts
- FCR (FIFO Control Register) – enable/clear FIFOs
- LCR (Line Control Register) – sets word length, parity, and enables baud latch mode
- LSR (Line Status Register) – indicates RX ready, TX idle, etc.
- ISR (Interrupt Status Register) – reading can acknowledge interrupt source (in this driver it's just read-and-discard to quench)
The code hides these with Reg(reg), ReadReg, and WriteReg.
2. Initialization (uartinit())
Steps:
- Disable interrupts:
IER = 0. - Enter baud latch mode: set
LCR_BAUD_LATCH. - Program divisor (LSB at register 0, MSB at 1) for 38.4K baud.
- Leave latch mode and set 8N1 framing:
LCR = LCR_EIGHT_BITS. - Enable and clear FIFOs:
FCR = FIFO_ENABLE | FIFO_CLEAR. - Enable TX and RX interrupts:
IER = IER_TX_ENABLE | IER_RX_ENABLE. - Initialize a spinlock guarding the transmit ring buffer.
After this, the UART can:
- Raise an interrupt when a byte arrives
- Raise an interrupt when it’s ready to accept another transmit byte (THR empty)
3. Transmit Path (kernel -> UART -> terminal)
There are two ways the kernel outputs characters:
3.1 Slow but synchronous: uartputc_sync()
Used by printf() early or in panic contexts:
- Disables interrupts on the local CPU (
push_off()). - Polls
LSR_TX_IDLEuntil THR is free. - Writes the byte directly to
THR. - Re-enables interrupts (
pop_off()). Pros: Simple, no dependence on interrupts. Cons: Busy-waits; blocks CPU.
3.2 Buffered + interrupt-driven: uartputc()
Used by normal console writes: Flow:
-
Acquire
uart_tx_lock. -
If panicked, spin forever (avoid returning into a broken kernel).
-
If transmit ring buffer is full (
uart_tx_w == uart_tx_r + UART_TX_BUF_SIZE), sleep:
sleep(&uart_tx_r, &uart_tx_lock);atomically releases the lock and parks the process.- It will be woken when space opens (see
uartstart()).
-
Place the character into
uart_tx_buf[uart_tx_w % SIZE], incrementuart_tx_w. -
Call
uartstart()to push bytes into hardware if possible. -
Release lock.
3.3 Actually handing bytes to hardware: uartstart()
Called:
-
From
uartputc()(top half) -
From
uartintr()(bottom half, after TX interrupt) Algorithm: -
While there are unsent bytes (w != r) and hardware indicates THR empty (
LSR_TX_IDLE):
- Take next byte from ring buffer
- Advance
uart_tx_r wakeup(&uart_tx_r)to unblock any sleepers inuartputc()- Write byte to
THR
-
If buffer empty, read
ISR(ack/clear) and return. It stops when hardware is full or ring buffer is empty.
3.4 Interrupt cycle for transmit
- Hardware finishes shifting out a character.
- Sets LSR_TX_IDLE and raises a TX interrupt (because IER_TX_ENABLE set).
- Trap handler ->
devintr()->uartintr(). uartintr()acquires the lock, callsuartstart()to feed more bytes, releases lock.- Sleeping writers get woken as the ring drains.
4. Receive Path (terminal -> UART -> kernel -> user process)
Data entry path:
- A character arrives electrically; UART shifts bits and assembles a byte in RHR, sets
LSR_RX_READY, raises RX interrupt (IER_RX_ENABLE). - Trap ->
devintr()->uartintr(). - In
uartintr(), first loop callsuartgetc()repeatedly:uartgetc()checksLSR_RX_READYand returns the byte or -1 if none.
- For each received byte
c,uartintr()callsconsoleintr(c).
consoleintr() (in console.c) does line discipline:
- Handles backspace/delete editing
- Implements special control chars (e.g., Ctrl-P, Ctrl-U, newline)
- Stores characters into a circular input buffer
- Wakes processes sleeping in
consoleread()(which services userread()on stdin)
Ultimately:
- User process calls
read(fd=0, buf, n) - System call
sys_read->fileread-> device switch entry for console ->consoleread - If no complete line (or no data, depending on policy), process sleeps on input buffer
- When characters (or a newline) arrive,
consolereadcopies them to user buffer and returns.
DMA
Refer to xv6 book 5.5 Real world for DMA method.
PCI
PCI/PCI-X/PCIe are bus standards.
- Devices (NICs, GPUs, etc.) sit on this bus.
- The CPU can access them through:
- I/O ports (legacy) or
- Memory-mapped I/O (MMIO, the usual way today).
So interacting with PCI = reading/writing special registers on the bus.
PCI Configuration Space
Every PCI device exposes a configuration space (256 or 4096 bytes).
The OS can read/write this to:
- Discover what devices exist.
- Get their Vendor ID (Intel, Broadcom, etc.) and Device ID (82540EM, etc.).
- Learn the device’s capabilities.
- Find the BARs (Base Address Registers), which tell the OS where the device’s MMIO registers live in physical memory.
So at boot, the OS:
- Scans the PCI bus (through config space).
- For each device, checks Vendor/Device ID.
- If it finds a supported device (like Intel 82540EM), it loads the corresponding driver.
See pic_init() in pic.c.
void
pci_init()
{
// we'll place the e1000 registers at this address.
// vm.c maps this range.
uint64 e1000_regs = 0x40000000L;
// qemu -machine virt puts PCIe config space here.
// vm.c maps this range.
uint32 *ecam = (uint32 *) 0x30000000L;
// look at each possible PCI device on bus 0.
for(int dev = 0; dev < 32; dev++){
int bus = 0;
int func = 0;
int offset = 0;
uint32 off = (bus << 16) | (dev << 11) | (func << 8) | (offset);
volatile uint32 *base = ecam + off;
uint32 id = base[0];
// 100e:8086 is an e1000
if(id == 0x100e8086){
// command and status register.
// bit 0 : I/O access enable
// bit 1 : memory access enable
// bit 2 : enable mastering
base[1] = 7;
__sync_synchronize();
for(int i = 0; i < 6; i++){
uint32 old = base[4+i];
// writing all 1's to the BAR causes it to be
// replaced with its size.
base[4+i] = 0xffffffff;
__sync_synchronize();
base[4+i] = old;
}
// tell the e1000 to reveal its registers at
// physical address 0x40000000.
base[4+0] = e1000_regs;
e1000_init((uint32*)e1000_regs);
}
}
}
E1000
Receive
E1000 maintain a circular queue for receiving Ethenet packet.
Each element of queue is a structure which called descriptor.
struct rx_desc
{
uint64 addr; /* Address of the descriptor's data buffer */
uint16 length; /* Length of data DMAed into data buffer */
uint16 csum; /* Packet checksum */
uint8 status; /* Descriptor status [E1000 3.2.3.1] */
uint8 errors; /* Descriptor Errors [E1000 3.2.3.2] */
uint16 special; /* Descriptor special [E1000 3.2.3.3] */
};
And we can access the received data according addr field in descriptor.
The max length of data buffer of one descriptor is set by e1000_init
regs[E1000_RCTL] = E1000_RCTL_EN | // enable receiver
E1000_RCTL_BAM | // enable broadcast
E1000_RCTL_SZ_2048 | // 2048-byte rx buffers
E1000_RCTL_SECRC; // strip CRC
Now it is 2048 byte.
For receive circular queue, it have head and tail registers regs[E1000_RDT] and regs[E1000_RDH].
Hardware behavior:
Every time, when hardware try to write receive packets into main memory at receive circular queue,
it will write to the queue head, and place data to addr field in head descriptor. Then move head to next one (head plus one). Now this descriptor referred before is ready to process by OS and its descriptor->status & bit will be set 1.
All space from head to tail belongs to hardware to write.
OS behavior:
All space from tail + 1 to head belongs to OS to read (continuous).
Every time, begin to read tail + 1 descriptor and check its E1000_RXD_STAT_DD bit. Handle it and plus tail, then keep doing until E1000_RXD_STAT_DD == 0 .
Transmit
Transmit is similar as receive. There is a transmit circular queue and corresponding transmit descriptor.
But head and tail are different.
Every time we write data into descriptor begin to tail not tail + 1.
This because queue initialization. When transmitting, head = tail = 0, but in receiving, head = 0, tail = queue_size - 1.
NOTE:
We don't usehead > tail or tail > head or something like this to check when to stop reading or writing. Instead we use status bit E1000_RXD_STAT_DD to check if it is ready for OS to handle. So we only need to know where to begin since the E1000_RXD_STAT_DD will be continuous the same! (One continuous part will be 0 and remained continuous part is 1)
Lab: Locks
In xv6 when one CPU hold at least one lock, it will not be allowed interruptions.
See Locks and interrupt handlers for more details in xv6 book.
__sync_synchronize()
Modern CPUs and compilers reorder instructions to optimize performance.
__sync_synchronize() is a memory barrier (or memory fence).
It tells both the CPU and the compiler:
“Don’t reorder any memory operations (reads/writes) across this point.”
In other words, all loads and stores before it are completed before anything after it begins.
Sleep locks
See 6.8 Sleep locks in xv6 book.
Because sleep-locks leave interrupts enabled, they cannot be used in interrupt handlers. Because acquiresleep may yield the CPU, sleep-locks cannot be used inside spinlock critical sections (though spinlocks can be used inside sleep-lock critical sections).
Comments
No approved comments yet.
Your display name and plain-text comment become public only after owner approval. No account or email is required.