10. Pipes and a console
Why this layer exists
Two processes exist since chapter 8, and they cannot say anything to each other. They share a page table, which is a hole, not a channel: either could scribble on the other’s pages if it guessed an address, and nothing would tell the victim. What a kernel owes its processes is the opposite of that — a way to pass bytes that shares nothing: no page, no pointer, no lock, no address either side could name. This chapter builds one. A pipe is a kernel page neither process maps, and the two copies that move bytes in and out of it are the isolation boundary made into a data path.
A console is the same thing with the machine on one end. Until now ember talked; from here it listens, and a program that reads a line the reader typed is the first program on this hart that waits for the outside world. Waiting is the second object this chapter adds, and it is a scheduler state, not a loop.
The contrast is worth naming once. A unikernel (Part VI) deletes this boundary on purpose: one address space, the “pipe” is a function call, the copy is gone, and with it every property the copy enforced. That deletion is a choice with a price, and this chapter is where the price is stated so that Part VI can be read as choosing.
Mechanism
A small integer
A process names what it can read or write by a file descriptor: an index into its own table of pointers into one kernel-wide table of open files. The kernel table has sixteen slots and each process eight; the object in a slot has a kind, a reference count, and permission bits. Two kinds exist this chapter — the console and a pipe end — and chapter 12 adds a file on disk as the third behind the same three syscalls.
struct file *file_alloc(void)
{
int i;
for (i = 0; i < NFILE; i++)
if (ftab[i].ref == 0) {
ftab[i].ref = 1;
ftab[i].type = FD_NONE;
ftab[i].readable = ftab[i].writable = 0;
ftab[i].pipe = 0;
return &ftab[i];
}
return 0;
}
void file_close(struct file *f)
{
if (--f->ref > 0)
return; /* another descriptor still names it */
if (f->type == FD_PIPE)
pipe_close(f->pipe, f->writable);
#if HP_CH >= 12
if (f->type == FD_FILE)
fs_close(f->ino); /* the cache reaches the disk here */
#endif
f->type = FD_NONE;
}
long file_read(struct file *f, unsigned long uva, long n)
{
if (!f->readable)
return -1;
switch (f->type) {
case FD_CONSOLE:
return console_read(uva, n);
case FD_PIPE:
return pipe_read(f->pipe, uva, n);
#if HP_CH >= 12
case FD_FILE:
return fs_fread(f, uva, n);
#endif
default:
return -1;
}
}
long file_write(struct file *f, unsigned long uva, long n)
{
if (!f->writable)
return -1;
switch (f->type) {
case FD_CONSOLE:
return console_write(uva, n);
case FD_PIPE:
return pipe_write(f->pipe, uva, n);
#if HP_CH >= 12
case FD_FILE:
return fs_fwrite(f, uva, n);
#endif
default:
return -1;
}
}
/* The lowest free slot: 0, 1, 2 for the console, 3 for the first pipe
* end — the POSIX shape, by construction rather than by rule. */
int fd_install(struct proc *p, struct file *f)
{
int fd;
for (fd = 0; fd < NOFILE; fd++)
if (!p->ofile[fd]) {
p->ofile[fd] = f;
return fd;
}
return -1;
}
struct file *fd_get(struct proc *p, long fd)
{
if (fd < 0 || fd >= NOFILE)
return 0;
return p->ofile[fd];
}
/* On exit: every open end is closed, which is how a reader learns its
* writer is gone. */
void fd_close_all(struct proc *p)
{
int fd;
for (fd = 0; fd < NOFILE; fd++)
if (p->ofile[fd]) {
file_close(p->ofile[fd]);
p->ofile[fd] = 0;
}
}
Nothing in that file touches user memory; it routes. read(fd, …) and write(fd, …) find the file and dispatch on its kind, close(fd) drops a reference and, at zero, tells the underlying object. The lowest free slot is handed out first, so the console lands at 0, 1, 2 and a pipe end at 3 — the POSIX layout by construction, not by rule. On exit every descriptor is closed, which is not tidiness: it is how a reader learns its writer is gone.
/* read is the first syscall that can wait: a pipe with nothing in it
* or a console with no line yet puts the caller to sleep inside
* file_read, and the return happens on a later switch. */
static long sys_read(long fd, long buf, long n)
{
struct file *f = fd_get(curproc, fd);
if (!f || n < 0)
return -1;
return file_read(f, (unsigned long)buf, n);
}
static long sys_close(long fd)
{
struct file *f = fd_get(curproc, fd);
if (!f)
return -1;
file_close(f);
curproc->ofile[fd] = 0;
return 0;
}
write existed in chapter 7 as “fd 1 is the UART.” It now goes through the table; fd 1 is still the console, it is just no longer the only thing a process can write to.
The pipe
A pipe is one page from chapter 9’s allocator, used as a ring, with two cursors that only ever increase and a count of open ends on each side. The cursors are taken modulo the page size when they index the ring; their difference is the number of bytes waiting, and the ring is full when that difference is the page. Neither process maps the page. The writer’s bytes cross into the kernel through copy_in_user — the walk-to-PA copy chapter 7 built — and the reader’s leave through copy_out_user, its mirror, called here for the first time:
int copy_in_user(struct proc *p, unsigned long uva, void *kbuf,
unsigned long n)
{
unsigned char *dst = kbuf;
unsigned long done = 0;
(void)p; /* one table; the walk is the authority */
while (done < n) {
unsigned long va = uva + done;
unsigned long pa = user_pa(va);
unsigned long off = va & (PAGE_SIZE - 1);
unsigned long chunk = PAGE_SIZE - off;
const unsigned char *src;
unsigned long i;
if (!pa || chunk > n - done)
chunk = n - done;
if (!pa)
return -1; /* unmapped or not a U page: the boundary */
src = (const unsigned char *)(pa | off);
for (i = 0; i < chunk; i++)
dst[done + i] = src[i];
done += chunk;
}
return 0;
}
long pipe_write(struct pipe *pi, unsigned long uva, long n)
{
char kbuf[128];
long done = 0;
while (done < n) {
long chunk = n - done, i;
/* Full: wake any reader, then wait for room. A pipe with no
* reader left can never drain — refuse rather than sleep. */
while (pi->nwrite == pi->nread + PIPE_SIZE) {
if (pi->readers == 0)
return -1;
wakeup(&pi->nread);
sleep_on(&pi->nwrite, "pipe (full)");
}
if (chunk > (long)sizeof(kbuf))
chunk = sizeof(kbuf);
if (chunk > (long)(pi->nread + PIPE_SIZE - pi->nwrite))
chunk = (long)(pi->nread + PIPE_SIZE - pi->nwrite);
if (copy_in_user(curproc, uva + (unsigned long)done, kbuf,
(unsigned long)chunk) < 0)
return -1;
for (i = 0; i < chunk; i++)
pi->data[pi->nwrite++ % PIPE_SIZE] = kbuf[i];
done += chunk;
}
wakeup(&pi->nread);
return done;
}
long pipe_read(struct pipe *pi, unsigned long uva, long n)
{
char kbuf[128];
long chunk, i;
/* Empty with a writer still open: block. Empty with none: EOF. */
while (pi->nread == pi->nwrite && pi->writers > 0)
sleep_on(&pi->nread, "pipe");
chunk = (long)(pi->nwrite - pi->nread);
if (chunk == 0)
return 0;
if (chunk > n)
chunk = n;
if (chunk > (long)sizeof(kbuf))
chunk = sizeof(kbuf);
for (i = 0; i < chunk; i++)
kbuf[i] = pi->data[pi->nread++ % PIPE_SIZE];
if (copy_out_user(curproc, uva, kbuf, (unsigned long)chunk) < 0)
return -1;
wakeup(&pi->nwrite); /* room for a writer blocked on full */
return chunk;
}
The two copies are the design. Setting sstatus.SUM and letting the kernel dereference user pointers would save a walk per chunk, and it would cost exactly what chapter 7 said it costs: a wrong pointer becomes a silent read instead of a fault. This kernel keeps the walk, and the pipe inherits the refusal — a user buffer that is not a mapped U page is a -1, never a kernel read.
Three facts about the ring follow from the cursors. A read returns whatever is waiting, up to the caller’s count: a pipe has no message boundaries, and exercise (a) shows a read that returns the writer’s line and the start of its next write in one call. A write larger than the ring’s free space fills what it can and blocks for the rest — the writer sleeps until a reader makes room, and wakes any reader before it sleeps so the two cannot wait for each other. And EOF is a fact about the ends: a read on an empty pipe blocks while a write end is open and returns 0 once none is, which is why exit closing every descriptor matters.
Blocking is a state
A reader with nothing to read does not spin. It records what it is waiting for, marks itself WAITING, and switches to the scheduler — chapter 8’s sched(), from inside a syscall, on its own kernel stack, exactly as yield did. The loop skips WAITING slots. Whoever makes the awaited thing true calls wakeup on the same channel, and the sleeper is RUNNABLE again; when the loop next picks it, sleep_on returns into the loop that called it, which re-checks its condition and either proceeds or sleeps again.
void sleep_on(void *chan, const char *what)
{
curproc->chan = chan;
curproc->state = WAITING;
uart_puts("S: proc ");
uart_putc((char)('0' + curproc->pid));
uart_puts(" blocks on ");
uart_puts(what);
uart_puts("\r\n");
sched(); /* returns when the loop picks this proc again */
curproc->chan = 0;
}
void wakeup(void *chan)
{
int i;
for (i = 0; i < NPROC; i++) {
struct proc *p = &proc_tab[i];
if (p->state == WAITING && p->chan == chan) {
p->state = RUNNABLE;
uart_puts("S: wake proc ");
uart_putc((char)('0' + p->pid));
uart_puts("\r\n");
}
}
}
The channel is just an address both sides agree on — a pipe’s read cursor for readers, its write cursor for writers, the console’s line count for a console reader — and wakeup wakes everyone on it. That is why every sleep sits inside a while, never an if: a wakeup means “look again,” not “it is true,” and a second reader may have taken the bytes first. The kernel says both events aloud, S: proc N blocks on … and S: wake proc N, so the lab’s transcript pins that the block happened and in what order the world moved.
This scheduler is cooperative — chapter 9 said so — and the lab is honest about what that means. A process that blocks gives up the hart; a process that is runnable keeps it until it blocks, yields, or exits. The writer, once woken, runs to its exit before the reader gets a turn, and the transcript’s order is fixed by that. Add chapter 8’s tick and the order would depend on where the tick landed; the mechanism would be the same, the transcript would not.
No fork, so the kernel wires it
POSIX gives a pipe to a process with pipe(2) and to a second process with fork: the child inherits the descriptors. ember has no fork (chapter 13 says why, and what spawn does instead), so a pipe syscall would hand both ends to one process with no way to give either away. The kernel does the wiring: the boot stage creates the pipe and installs the read end in the reader’s table and the write end in the writer’s. Chapter 13’s spawn attaches only the console to a child; installing a caller’s descriptor in the child is what posix_spawn’s file actions add, and what a sh | cat would need. The thing POSIX has that this kernel lacks is the inheritance, not the pipe.
The console
Input comes in on chapter 5’s path, untouched: the UART raises PLIC source 10, the S-mode handler claims it, handle_uart drains the receive register — echoing each byte, as a terminal in cooked mode does — and now hands each byte to console_rx. The console keeps a 128-byte ring of its own and a count of complete lines in it; a newline bumps the count and wakes anyone sleeping on it.
void console_rx(int c)
{
if (cw - cr >= CONS_SIZE)
return; /* full: the byte is dropped, as a tty would */
cbuf[cw++ % CONS_SIZE] = (char)c;
if (c == '\n') {
lines++;
wakeup((void *)&lines);
}
}
long console_read(unsigned long uva, long n)
{
char kbuf[CONS_SIZE];
long i = 0;
while (lines == 0)
sleep_on((void *)&lines, "console");
while (i < n && i < CONS_SIZE && cr != cw) {
char c = cbuf[cr++ % CONS_SIZE];
kbuf[i++] = c;
if (c == '\n') {
lines--;
break; /* one line per read */
}
}
if (copy_out_user(curproc, uva, kbuf, (unsigned long)i) < 0)
return -1;
return i;
}
console_read is line-disciplined: it waits for a whole line and returns at most one, newline included. That is the first read on this hart whose data comes from outside the machine, and the wait is the same sleep_on a pipe reader uses — the console is a pipe whose writer is the interrupt handler. Output is symmetric and simpler: console_write copies chunks in through the walk and puts them on the UART.
One thing in the boot stage is there for the lab, and the chapter says so rather than hiding it. QEMU feeds input.txt to the UART from its main loop, in a split between chapter 5’s boot-time drain and later interrupts that the host’s timing decides. A process that read the console before the newline had arrived would block, and S: proc 2 blocks on console would appear on some runs and not others. So console_wait_line idles in wfi until the interrupt path has delivered one complete line, before any process exists; the transcript is then fixed. (The boot stage runs with sstatus.SIE set from uart_irq_on on — interrupts are how the line arrives — until the first process traps in and chapter 8’s rule takes over.) A console with a human at it would not do this — the process’s own read would wait, through the same sleep_on — and nothing in console_read is different for that case.
Chapter 5’s 128-byte guard on the drain loop is retired from this chapter on: the console ring bounds the loop, and a full ring drops bytes, which is what a terminal does.
mem_init();
trap_init();
/* No csrr mhartid here: that proof is chapter 5's, and the sepc it
* reports depends on the compiler's prologue for this function, and
* captures pin behavior, not layout. Chapter 5's line names the
* probe instead of printing an address. */
uart_puts("S: kernel up\r\n");
kalloc_init();
uart_irq_on(); /* chapter 5's path: PLIC, IER, drain, unmask */
console_wait_line(1); /* the lab's line is on stdin; see console.c */
{
struct proc *reader = launch(user4_blob_start,
(unsigned long)(user4_blob_end -
user4_blob_start),
USER_BASE, 0);
struct proc *writer = launch(user5_blob_start,
(unsigned long)(user5_blob_end -
user5_blob_start),
USER_BASE + 0x10000UL, 0);
console_attach(reader);
console_attach(writer);
pipe_wire(reader, writer); /* read end → reader, write end → writer */
}
scheduler();
{
/* Nothing runnable is not the same as nothing left: a process
* asleep on a channel nobody will ever signal is a deadlock,
* and PASS over one would be a lie. */
int i;
for (i = 0; i < NPROC; i++)
if (proc_tab[i].state == WAITING) {
uart_puts("S: deadlock: proc ");
uart_putc((char)('0' + proc_tab[i].pid));
uart_puts(" still waiting\r\n");
halt(1);
}
}
uart_puts("PASS\r\n");
halt(0);
The reader is launched first so that its first read finds the pipe empty and blocks — that is the sentence the lab is built to print — and the check after scheduler() is not decoration. “Nothing runnable” and “nothing left” are different: a process asleep on a channel nobody will ever signal is WAITING, not RUNNABLE, and the loop returns over it. PASS on top of a sleeping process would be a lie; the stage looks, and says deadlock instead.
The programs
int main(void);
int main(void)
{
char line[64];
long n;
n = syscall3(5, 3, (long)line, sizeof(line)); /* read(3, …): blocks */
tag();
puts(" pipe: ");
syscall3(2, 1, (long)line, n); /* the line, newline included */
n = syscall3(5, 3, (long)line, sizeof(line)); /* the writer is gone: 0 */
if (n == 0) {
tag();
puts(" eof\r\n");
}
syscall3(1, 0, 0, 0);
return 0;
}
int main(void);
int main(void)
{
char line[64];
long n;
n = syscall3(5, 0, (long)line, sizeof(line)); /* read(0, …): the console */
tag();
puts(" console: ");
syscall3(2, 1, (long)line, n);
syscall3(2, 3, (long)line, n); /* write(3, …): into the pipe */
syscall3(1, 0, 0, 0); /* exit closes fd 3 */
return 0;
}
The reader reads fd 3 until it returns 0. The writer reads a line from fd 0, says what it got, writes it into fd 3, and exits; the exit closes fd 3, the pipe’s last write end, and the reader’s second read returns 0. Each program prints U: and its pid, which the kernel handed it in a1 at launch, the same register-at-entry trick chapter 8’s programs used for a0.
Walkthrough
ch10-main (the boot stage: drain, wait for the line, two launches, the console attached to each, the pipe wired, the loop, the deadlock check), ch10-fd (the tables and the dispatch), ch10-read-close (the two new syscalls), ch07-copy-in re-shown beside its mirror’s first use, ch10-pipe-write and ch10-pipe-read (the ring, full and empty, EOF), ch10-sleep-wake (blocking as a state), ch10-console-read (the interrupt-fed ring and the line discipline), ch10-reader and ch10-writer.
Exercises
(a) Have the writer, after its line, write 64 bytes seventy times into the pipe with no yield, and have the reader drain until EOF. Predict where the writer sleeps and who wakes it, then run it.
Answer
The writer’s first write wakes the reader (S: wake proc 1) but does not yield to it: cooperative, it keeps the hart and keeps writing. After exactly 64 writes the ring holds 4096 bytes and the 65th finds it full — S: proc 2 blocks on pipe (full), on the write-cursor channel, having first woken any reader on the read-cursor channel (already awake). The loop picks the reader, whose first read returns 64 bytes: the 8-byte line and 56 bytes of the writer’s pattern — one read, two writes, no boundary between them. Its copy_out_user done, pipe_read calls wakeup on the write cursor: S: wake proc 2. The reader, also cooperative, drains the ring to empty before it blocks again (S: proc 1 blocks on pipe); the writer resumes, finishes its seventy, exits, and the reader’s next read is the EOF. Observed, in that order. Each side wakes the other before it sleeps, which is why neither can wait forever on a pipe the other still holds.
(b) Close the write end while the reader is blocked. Derive the reader’s return value and the path it takes.
Answer
The reader sleeps inside pipe_read’s while (empty && writers > 0). Closing the last write end — by close(3) or, as in the lab, by exit — runs pipe_close: writers becomes 0 and wakeup fires on the read cursor. The reader is picked, sleep_on returns, the loop re-checks: still empty, but writers == 0, so it falls through with zero bytes available and returns 0. That 0 is EOF, and it is a statement about the ends, not the bytes: the same empty ring with a writer still open would have put the reader back to sleep. The lab’s U:1 eof line is this path, taken through the writer’s exit.
(c) Map the pipe’s page into both processes with U=1 and let them read and write it directly. What did the design just give away?
Answer
Everything the copy enforced. The reader can see bytes the writer has not finished writing and the writer can see what the reader has still to read; either can move the cursors, so “full” and “empty” are advisory; a write is no longer bounded by the ring, because a process that ignores the cursor can write anywhere on the page; and a bad pointer on either side is a silent corruption of shared state, not a -1. There is no longer anything for the kernel to refuse, because nothing crosses it. On this kernel the argument has an extra twist: the processes already share a page table, so they could already reach each other’s U pages by guessing. The pipe’s value is precisely that its page is U=0 — the one page in the exchange that neither side can touch — and giving that up leaves shared memory by accident, which is what the chapter set out not to build.
(d) Make the pipe unbounded — a writer never blocks, the kernel allocates another page whenever the ring is full. Compute the failure.
Answer
A writer with a slow or absent reader grows the pipe by 4 KiB per page until chapter 9’s freelist is empty: 31741 pages, about 124 MiB, then kalloc_page returns 0 and the writer gets -1 — from the allocator, not from the pipe, and after taking every page any other process or the kernel itself would have needed. The bound is what makes backpressure exist: a full ring is the kernel telling the writer that the reader is behind, and blocking is the only message the writer cannot ignore. Without it the reader’s slowness becomes everyone’s exhaustion. This is the same argument chapter 11’s block device will make with a fixed ring of descriptors, and chapter 22’s backend with the other side of it.
(e) Suppose the console were read with the external interrupt masked — sie.SEIE clear after the boot drain. Derive what happens to a process that asks for a second line.
Answer
The bytes arrive at the UART and the PLIC raises the line, but the hart never takes the trap: handle_uart never runs, console_rx never sees a newline, lines stays 0. The process’s console_read sleeps on the line count, and nothing in the kernel can ever call wakeup on it — the only caller is the interrupt handler that has been masked off. That is not a livelock, in which something runs and nothing progresses; it is a process that will never be runnable again. Watch what the rest of the kernel does with it: the scheduler finds nothing runnable and returns, and a boot stage that printed PASS on an empty run would have reported success over a process asleep forever. This chapter’s stage checks the table for WAITING first and prints S: deadlock: proc N still waiting instead. A blocking read is only correct if its wakeup path stays alive; masking the interrupt cuts the path and leaves the sleep.
(f) Name what POSIX pipes provide that this pipe omits.
Answer
Named, not built: pipe(2) as a syscall a process calls for itself, and fork to inherit the ends; the PIPE_BUF guarantee that a write of at most that many bytes is atomic with respect to other writers (this pipe has one writer and chunks at 128 bytes, so the question does not arise); O_NONBLOCK, a read or write that returns EAGAIN instead of sleeping; SIGPIPE/EPIPE when writing to a pipe with no reader (this pipe returns -1, and there is no signal to deliver); readiness — select, poll — over several descriptors at once; and named pipes in the file system. Every one of them is a refinement of the same three facts: a bounded ring, two ends, a copy in and a copy out.
Lab
make lab CH=10
make lab CH=10 IMPL=mine
input.txt is one line, pipe me. After the boot lines: pipe me echoed by the drain, exactly as it arrived (a bare newline — the UART echoes what it got); S: console line ready; S: proc 1 blocks on pipe, the reader’s first read; U:2 console: pipe me, the writer showing the line it read from fd 0; S: wake proc 1, the writer’s write into the pipe; S: proc 2 exited, which closes the write end; U:1 pipe: pipe me, the reader’s read returning; U:1 eof, the second read returning 0; S: proc 1 exited; PASS. The order is fixed by the cooperative scheduler and by the boot stage waiting for the line before launching. Nothing in the transcript is an address or a clock. The chapter 5 proof line (S: trap sepc=probe …) is absent from chapter 7 on: the boot stage no longer runs the csrr mhartid probe it belongs to, and the line’s old form, a hex sepc, was a link-time address that moved with each stage’s prologue. Captures pin behavior, not layout.
IMPL=mine copies exactly the objects chapter 10 links and stubs pipe_write to print MINE: pipe_write stub and halt. The lab boots, the reader blocks, the writer reads its line and reaches the stub — and fails loudly before any wake.
Further reading
- pipe(2) — Linux manual page (man-pages project) — the POSIX contract this chapter’s pipe is measured against:
PIPE_BUF,O_NONBLOCK,EPIPE, and the inheritance throughforkthatemberreplaces with wiring. - The RISC-V Instruction Set Manual, Volume II: Privileged Architecture (RISC-V International, v20260120, January 2026) —
wfiand the interrupt-taking rule behindconsole_wait_line, and theU/SUMrules the copies rest on. - xv6-riscv (MIT PDOS) —
kernel/pipe.cis the same ring with the same two cursors;kernel/proc.c’ssleep/wakeupis the same channel idea with the lock this single-hart, non-preemptible kernel does not need.