04r · Structs, Methods, and const fn¶
Released Thu Sep 10, in class
This is the README OSlings gives every student for 04r_structs_impl (oslings
lesson shows it). 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. Almost everything interesting in a kernel is a struct: a process, a saved CPU state, a page table entry. Today you build three of them and give them behavior: a region of physical memory, a real working piece of exercise 33k, and a page that puts itself back when you are done with it.
Learn¶
Up to now you have been passing loose numbers around. A kernel cannot work that way for long. By exercise 34k you will have a table of process records, each one holding a state, a process id, a page table pointer and a name; by exercise 35k you will have a block of saved registers that hand-written assembly reads. Both are structs: one named type bundling several values that travel as a unit.
Defining a struct¶
That declares a type called MemRegion with two fields. pub on the struct
means other files may use the type; pub on a field means other files may read
and write that field. Leave it off and the field is private to this file, which
is how a kernel module stops the rest of the kernel from corrupting its data
behind its back.
You build a value with a struct literal, naming every field, and read the
fields back with a dot — ram.start:
If a local variable already has a field's name you may write it once:
MemRegion { start, end } means MemRegion { start: start, end: end }.
Methods: functions that belong to the type¶
Functions that operate on a MemRegion live in an impl block ("implementation
block") for that type:
impl MemRegion {
pub fn contains(&self, addr: usize) -> bool {
addr >= self.start && addr < self.end
}
}
The first parameter, &self, means "a borrowed reference to the value this was
called on", so inside the body self.start is that region's start. You call it
with a dot: ram.contains(0x8000_1000). Because &self borrows rather than
takes, the caller still owns ram afterwards. A method that had to change its
value would take &mut self; a method on a small copyable type — like the Pte
below — can take plain self by value.
Associated functions: same block, no self¶
A function in an impl block that does not take self is an associated
function. It belongs to the type but to no particular value, which is exactly
right for something whose job is to make a value:
pub fn of_pages(start: usize, pages: usize) -> MemRegion {
MemRegion { start, end: start + pages * PAGE_SIZE }
}
You call it through the type, with :: instead of a dot:
MemRegion::of_pages(0x8000_0000, 3).
Rust has no constructor keyword. An associated function named new is purely
a convention, and it is the one the kernel follows: Proc::new() in exercise 34k,
Context::zero() in exercise 35k, Pte::new(pa, flags) below. Inside an impl
block the type's own name may be written Self, so -> MemRegion and -> Self
mean the same thing there.
Page arithmetic, and where a free list comes from¶
A kernel spends its life rounding addresses to page boundaries. The idiom is one
line of bit work: PAGE_SIZE - 1 is 0xfff, twelve ones — the part of an
address that says where inside the page — so !(PAGE_SIZE - 1) is the mask
that clears it, and ANDing with that mask rounds an address down to a
boundary. Add 0xfff first and the same mask rounds up instead, leaving an
already-aligned address exactly where it is. xv6 calls these PGROUNDDOWN and
PGROUNDUP; you write the second one today, as a const fn.
That is the first half of kinit, the routine that gives exercise 32k's
allocator something to allocate. The kernel is handed one region — everything
between the end of its own code and the top of RAM — and turns it into a list of
free pages by walking from the first boundary inside the region to the last,
PAGE_SIZE at a time. A page earns a place on that list only if it fits
entirely inside the region: a part-page at either end is memory nothing can be
put in, so it is dropped on the floor. Getting that condition wrong by one page
hands out memory that is not there, which is a fault the first time somebody
writes to it and a puzzle for an hour afterwards.
derive: free implementations of the boring traits¶
#[derive(...)] asks the compiler to write mechanical implementations for you.
Debug lets assert_eq! print the value when a test fails; PartialEq and Eq
let you compare two with ==. Copy is the load-bearing one: by default,
assigning a struct value moves it and the original becomes unusable, so
without Copy on Pte, calling entry.pa() and then entry.flags() would be a
compile error — the first call consumed entry. A page table entry is eight
bytes; it should behave like the integer it is.
The newtype pattern¶
A struct with unnamed fields is a tuple struct, and one with exactly a single
field is called a newtype. You reach the wrapped value by position: self.0.
At runtime this buys nothing — a Pte is its u64. What it buys is at compile
time. A page table entry, a physical address, a process id and a byte count are
all "just a 64-bit number", and passing one where another was meant is a bug the
compiler cannot see while they share a type. Give the entry its own type and it
sees every one. #[repr(transparent)] is the promise that the wrapper has the
exact layout of the thing it wraps, which is what makes an array of 512 Pte
values a genuine hardware page table rather than a Rust convenience.
The thing you are actually building¶
A RISC-V Sv39 page table entry is one 64-bit word with two fields packed in:
The physical page number is the address with its bottom 12 bits chopped off
(pa >> 12) — legitimate because a page is 4096 = 2¹² bytes, so a page's address
always ends in twelve zero bits and storing them would be storing zeros. The
freed space holds ten flag bits: Valid, Readable, Writable, eXecutable, and
Usable from user mode.
Four bit operations do all the work. a >> n shifts every bit down n places and
a << n shifts them up. a | b sets every bit set in either operand, which is
how two fields merge into one word. a & b keeps only the bits set in both,
which is how a field is selected back out — the value you AND with is a mask,
and 0x3ff (ten binary ones) is the mask for a ten-bit flag field.
So building an entry is "shift the address into place, then OR in the flags", and
reading the address back is those shifts in reverse. This is the same arithmetic,
on the same bit layout, that you will write in vm.rs in exercise 33k — with the
raw-pointer machinery stripped away.
const fn¶
A function marked const fn may also be evaluated by the compiler, before the
program runs:
pub const fn new(pa: u64, flags: u64) -> Pte { ... }
const ROOT: Pte = Pte::new(0x8000_5000, PTE_V);
ROOT is not computed at start-up; the compiler works it out and bakes the
finished number into the binary. A const fn is still an ordinary function you
may call at runtime — const only adds an ability. That matters in a kernel: a
global like static mut PROCS: [Proc; 64] = [const { Proc::new() }; 64]; must be
known at compile time, because nothing is running yet that could initialize it.
A struct that cleans up after itself¶
In exercise 02r you took a page off a free list and then had to remember to call
give_back. That is C's bargain, and it is the one that produces leaks (you
forgot) and double frees (you did it twice). Rust's third road is to make the
release part of a value's life rather than a call you might not make.
When a value goes out of scope the compiler emits a call to its type's Drop
implementation. You do not write the call, you cannot forget it, and its site is
a closing brace:
impl Drop for PageGuard<'_> {
fn drop(&mut self) {
self.free.push(self.pa); // give_back, with the calling removed
}
}
Two properties earn this its place in a kernel. It is deterministic — it
happens at a specific instruction, so a drop can carry real work: returning a
page, releasing a lock, closing a file, re-enabling interrupts. And it runs
wherever the owner ends, including paths you did not think about: an early
return, a ?, the end of a function the value was passed into. C++ has had
this since the mid-1980s under the name RAII, "resource acquisition is
initialization". What Rust adds is that ownership is checked, so RAII cannot be
defeated by an accidental copy or a second owner.
Which is the other half of the Copy story from earlier in this page. Copy
says "duplicating the bits duplicates the value"; Drop says "the release runs
exactly once". A type cannot promise both, or the release would run once per
duplicate — the double free in a new hat. So Pte derives Copy and has no
Drop, and PageGuard has a Drop and can never be Copy. Try the derive on
it and rustc stops one step earlier, at the field: error[E0204]: the trait
'Copy' cannot be implemented for this type, because free is a &mut, and an
exclusive borrow cannot be copied either. A Drop type whose fields are all
Copy meets the destructor rule itself: error[E0184]: the trait 'Copy' cannot
be implemented for this type; the type has a destructor.
The type you build is a guard: a value whose existence is the held
resource. PageGuard<'a> borrows the free list exclusively — the &mut and the
'a from 03r — so while a page is out, the list cannot be reached by anybody
else at all, and when the guard dies the page goes back. Exercise 02r's
invariant, "a page that has been handed out is no longer free", stops being a
sentence in a comment and becomes a thing the compiler checks. Exercise 37k is
this same type with a spinlock in place of the page, and its Drop is the
unlock; that is why a rv6 kernel cannot leave a lock held.
One last piece, given to you in the file, is worth reading twice:
An empty body. self is taken by value, so calling page.release() moves the
guard in, and it dies at that closing brace — running Drop and returning the
page early. The standard library's drop is this function and nothing more:
pub fn drop<T>(_x: T) { }. Release travels with ownership; handing a value
away hands away the duty to release it.
#[repr(C)], in passing¶
Rust does not promise to lay a struct's fields out in the order you wrote them;
it may reorder or pad to suit the machine. #[repr(C)] gives that freedom up and
uses C's rules: fields in source order. You need it whenever something other than
Rust reads the struct. In exercise 35k hand-written assembly saves the stack
pointer at "the Context's address plus 8" — correct only because sp is the
second 8-byte field and stays there. The Context here is given; read it and
notice why the attribute is not optional.
Understand¶
Open warmup/src/lib.rs. As in every Rust exercise that one file is your whole
workspace, and the #[cfg(test)] mod tests block at the bottom is given — you
never edit it. It is the exact contract your code must satisfy, so read it first.
Given pieces reward study before you write anything. MemRegion::contains is a
complete method. Pte::is_valid is a method calling another method
(self.flags()) on the same value — it starts working the moment your flags
does. PageGuard::free_len reaches the free list through the &mut the guard
stores, which is the only path to that list while the guard is alive. And
PageGuard::release is one line long, does nothing, and gives a page back; read
the comment above it.
One test, the_layout_is_what_the_hardware_expects, passes before you touch
anything; it proves three layout facts the rest of the course leans on.
Implement¶
Fill in the eleven IMPLEMENT markers in warmup/src/lib.rs. Most are one
expression; two are not, and they are marked below.
page_align_up— round an address up to the next page boundary.MemRegion::size— how many bytes the region covers.MemRegion::of_pages— build a region of exactlypagespages.MemRegion::page_list— every whole page in the region, as a free list. (a loop; the longest one here, and the one to slow down for)Pte::new— pack a physical address and flags into one 64-bit word.Pte::pa— recover the physical address from a packed entry.Pte::flags— recover the flag bits.PageGuard::take— take the last page off a free list and hold it. (two statements and a struct literal, and the order matters)PageGuard::region— the one-page region this page covers.PageGuard::entry— the page table entry that maps this page.Drop for PageGuard— give the page back.
Markers 9 and 10 are one call each into code you wrote earlier in the file. That is the point of them: by the end a region hands you a free list, the free list hands you a page, and the page hands you the entry that maps it.
Check your work:
oslings run 04r_structs_impl
# or leave it watching and it re-runs every time you save:
oslings watch
This runs cargo test on your laptop. No QEMU, no kernel — if the tests are
green, you're done.
Stuck? oslings hint.