Skip to content

50k · File descriptors

Released Tue Dec 1, in class: posted here early

This is the README OSlings will give every student for 50k_file_descriptors (oslings lesson shows it) when the exercise is released on Tue Dec 1. The starter code is not published here: it reaches you through OSlings, in class on the class network. Back to All Exercises.

Learn -> Understand -> Implement. In exercise 48k a user program could only write to the console; in 49k it could take arguments. But it still could not touch a file. This exercise gives user programs the last piece: open, read, write, and close, all through small integer handles called file descriptors. Most of the machinery is given; you write the two pieces that make a descriptor a descriptor - the table that hands them out, and the read that remembers its place. After this, a user-mode cat reads a real file through system calls, the way cat does on real Unix.

Learn

What a file descriptor is

When a program wants to work with a file, it does not carry the file around. Instead it asks the kernel to open the file, and the kernel hands back a small integer: a file descriptor (fd). From then on the program says "read from fd 3" or "write to fd 3", and the kernel looks up what fd 3 refers to. close gives the descriptor back.

Why a plain integer? Because it is the simplest possible handle: cheap to pass in a register, cheap for the kernel to look up (it is just an array index), and it hides what is behind it. Behind an fd can be a file on disk, the console, or (later) a pipe or a socket - and the program reads and writes all of them the same way. "Everything is a file" is one of Unix's oldest and best ideas, and the file descriptor is what makes it work.

Every process starts with three descriptors already open, by convention:

fd name usually
0 standard input (stdin) the keyboard
1 standard output (stdout) the screen
2 standard error (stderr) the screen

That is why write(1, ...) printed to the console in exercises 48k and 49k: fd 1 was the console all along. In allocproc (proc.rs), rv6 now sets those three up for every process.

The per-process file table

Each process owns an array of open files, ofile in Proc (proc.rs). The fd is the index into that array: fd 3 is ofile[3]. Each entry is a File (file.rs):

pub struct File {
    pub kind: FileKind,   // None (free), Console, or Inode
    pub inum: usize,      // which inode, when kind == Inode
    pub off: usize,       // the read/write cursor  <-- the interesting part
    pub readable: bool,
    pub writable: bool,
}

Because the table is per-process, fd 3 in one program has nothing to do with fd 3 in another - descriptors are private, like the address space. Handing out a slot in this table is fdalloc, the first thing you write: find the lowest free entry, store the File there, and its index is the fd.

The offset: what makes a descriptor stateful

Back in exercise 47k the shell's cat read a whole file in one call: read(inum, buf) always started at the beginning. A file descriptor is different: it remembers where you are. Each File carries an offset off, the byte position the next read or write starts at. Every read returns the next chunk and then advances off by however many bytes it returned:

file:  [ h e l l o   f i l e s . . . ]
         ^
read(fd, buf, 64)  -> returns "hello files...", off jumps to 64
read(fd, buf, 64)  -> returns the NEXT 64 bytes, off jumps to 128
read(fd, buf, 64)  -> returns 0  (nothing left: end of file)

That returned 0 is how a reader knows it has hit the end. A program like cat just loops "read a chunk, write it out" until read returns 0. If you forget to advance the offset, every read returns the same first chunk forever and the loop never ends - the test catches it as a timeout. This is the second thing you write: the inode arm of sys_read.

open is given - read it as the spec

open(path, flags) is where a name becomes a descriptor. sys_open (syscall.rs) is given in full; its doc comment lays out the five steps it takes, and that is the spec. Three things to notice as you read it:

  • flags is a bitmask from file.rs (O_RDONLY, O_WRONLY, O_RDWR, O_CREATE, O_TRUNC) combined with |: O_CREATE | O_WRONLY means "make the file if needed, open it for writing." Every path is resolved in the root directory (a per-process current directory comes with the userland shell).
  • The path is a NUL-terminated string in user memory, with no length the kernel knows in advance - so instead of copyin, open uses the given vm::copyinstr, a copyin that stops at the zero byte.
  • The name lookup is exercise-47k filesystem work (dirlookup, dircreate, truncate). The only new step is the last: wrap the inode in a File with off: 0 and hand it to your fdalloc. Until fdalloc works, every open fails.

The uniform read/write path

The neat part of the design: read and write do not care whether the fd is the console or a file. They look at file.kind and branch - console bytes go to/from the UART, inode bytes to/from the filesystem - but the program calling read(fd, ...) is identical either way. You will see this in sys_write (given) and finish the matching sys_read: its lookup, Console arm, and None arm are given; the Inode arm - the one with the offset - is yours.

Understand

Read these, in order - about 560 lines, most of them doc comments and given code you read once:

  1. rv6/src/file.rs (all of it, ~90 lines): the File struct, FileKind, NOFILE, and the open flags.
  2. rv6/src/proc.rs (~45 lines): only the ofile field of Proc, allocproc (opens fds 0/1/2 on the console), and freeproc.
  3. rv6/src/fs.rs (~60 lines): only the offset-based primitives at the bottom of impl FileSystem - size, read_at, write_at, truncate. The fd layer sits on these.
  4. rv6/src/syscall.rs (~250 lines): the SYS_* constants, fdalloc (yours), getfile, sys_open (given - its doc comment is the spec), sys_read (the Inode arm is yours), sys_write (your model), and sys_close. Skip dispatch, emit, and the capture module.
  5. rv6/src/exec.rs (~40 lines): only the cat program in the assembly block; its comments narrate open, the read/write loop, and close from the user side. The rest of the file is exercise 49k's.
  6. rv6/src/main.rs (~80 lines): fd_self_check, the three steps the harness runs and what it prints when one fails.

Control flow of run cat notes.txt:

cat: open("notes.txt", O_RDONLY)
   -> sys_open: copyinstr the name, dirlookup, fdalloc -> fd     (given, but fdalloc is YOU)
cat: loop { read(fd, buf, 64); write(1, buf, n) } until read == 0
   -> sys_read: read_at(off) -> copyout -> off += n -> return n  <- YOU (the Inode arm)
   -> sys_write: copyin -> emit to console                       (given)
cat: close(fd); exit(0)

Implement

Two pieces, both in rv6/src/syscall.rs:

  1. fdalloc: scan the current process's ofile table for a free slot (FileKind::None), store the given File there, and return the slot index as the fd. Return -1 if the table is full. The given sys_open calls it as its last step.
  2. sys_read, the FileKind::Inode arm: the mirror of the inode arm of the given sys_write (read that first). read_at the file's current offset into the kernel buffer, copyout the bytes to the user, advance the stored offset by n, and return n. The // IMPLEMENT comment has it step by step.

Check your work:

oslings run 50k_file_descriptors
# or
oslings watch

The harness seeds a file, then runs the cat and create programs and checks what they read and wrote (read a file, create+write a file, open a missing file).

Then the payoff:

cd rv6 && cargo run        # boots to the rv6$ prompt

Try:

run create notes.txt        (a user program creates and writes the file)
run cat notes.txt           (a user program reads it back, through syscalls)

Both are unprivileged user programs doing real file I/O through the system-call wall - not the kernel touching the filesystem directly. (The shell's built-in cat, given since 47k, is still there for comparison; run cat launches the user-mode one.) Exit QEMU with Ctrl-A then X.

Stuck? oslings hint.