Вся документация
Как это устроено
Загружаемые модули
docs/modules.mdОткрыть на GitHubЭта страница пока есть только на английском: документация собирается прямо из каталога docs/ репозитория и поэтому всегда совпадает с кодом. На русском у нас есть руководства.
A kernel service can be built on its own, as a module, and put into a running kernel -- and taken out again -- without rebuilding or rebooting it:
$ wget http://10.0.2.2:8000/hello.ko /hello.ko
$ insmod /hello.ko
module: hello loaded at 0xFFFF8000...
$ hello nos
hello, nos -- call 1 since the module was loaded
$ lsmod
hello 24 KiB at 0xFFFF8000..., 7 kernel imports
$ rmmod hello
module: hello unloaded
Modules are written in Rust, and only in Rust. A module is a crate that runs
in the kernel and reaches it through exactly the API the drivers built into
the kernel use -- the extern "C" functions the ffi crate declares, wrapped
safely by kcore -- and through nothing else: the loader binds a module
against that API and refuses anything it does not recognise.
Writing one
A module lives in src/crates/modules/<area>/<name>/, its area what it is
for: cluster/, hypervisor/, mgmt/, net/, storage/, tools/, test/.
hello (modules/test/hello) is the smallest one worth reading:
#![no_std]
extern crate alloc;
use alloc::boxed::Box;
use core::fmt::Write;
use kcore::cmd::Command;
struct Hello {
_cmd: Command,
}
impl kmod::Module for Hello {}
fn init() -> kcore::error::Result<Box<dyn kmod::Module>> {
let cmd = Command::register("hello", "hello [name] - ...", |args, out| {
let _ = writeln!(out, "hello, {}", args);
})?;
Ok(Box::new(Hello { _cmd: cmd }))
}
kmod::module!(name: "hello", init: init);
kmod::module! names the module -- what lsmod shows and rmmod takes, at
most 31 printable characters -- and says which function insmod runs. That
function builds the module's state and hands it back as a Box<dyn kmod::Module>; an error instead fails the insmod. The kernel keeps the box
while the module is loaded, and rmmod drops it: there is no exit function to
write, because the module's Drop is its exit. Whatever the state holds --
the commands it registered, the tasks it started, the timers and interrupts
it took -- is released by the drops of the kcore handles in it, and must be,
because the module's code is freed right after. The state has to be Send:
the task that runs rmmod drops what the task that ran insmod built.
Dropping a handle is enough because every unregister the kernel offers waits
out a callback still running on another CPU before it returns: a command
(kernel_cmd_unregister), a timer, a legacy or MSI-X interrupt, a task
(TaskHandle joins it). And the drop never runs beside a call of the
module's own commands or bus providers: the loader takes those back first
(Unloading), so whatever the drop stops -- its tasks above all
-- stays stopped, whatever order its fields go in. One registration has no unregister at all: a softirq
handler (kcore::softirq::register_for) is the kernel's to call for as long
as it runs. A module that imports it is permanent: the loader sees the
import, lsmod says so, and rmmod refuses it -- the way Linux keeps a
module that has no exit function. (A disk's or a NIC's driver cannot be a
module at all: it registers with the block or the net layer as a Rust trait
object, from inside the kernel image, and there is no C name for that. A
module uses disks and NICs -- kcore::block::Disk, kcore::net::Nic -- it
does not provide them.)
The kmod crate supplies the rest of what every module needs once: the
global allocator (the kernel heap, through kernel_alloc), the panic handler
(a module that panics panics the kernel, as the in-kernel Rust does) and the
header the loader looks for. kcore::cmd is how a module puts a command in
front of whoever runs the shell, on the console or over the UDP
shell; the handler gets the rest of the command line and an
Output that is core::fmt::Write.
To add a module:
src/crates/modules/<area>/<name>/Cargo.toml, astaticlibwhose library is namedmod_<name>, depending onkmodandkcore(copyhello's: at the same depth its paths to them are right as they are);- add
modules/<area>/<name>to the workspacemembersinsrc/crates/Cargo.toml-- not todefault-members, which is what the kernel's own build compiles; - add
<name>toMODULESin theMakefile.
Parameters
What insmod is given after the path is the module's: insmod /hv.ko vms=/data/vms hands vms=/data/vms to hv's init. A module that takes
parameters is declared with init_with_params, and its init is lent them --
and insmod's output, to say what it makes of them:
fn init(params: &kmod::Params, out: &mut kcore::cmd::Output)
-> kcore::error::Result<Box<dyn kmod::Module>> {
for (key, value) in params.words() {
match (key, value) {
("vms", Some(path)) => { /* ... */ }
_ => {
let _ = writeln!(out, "hv: \"{}\" is not a parameter of hv's -- vms=<folder> is", key);
return Err(kcore::error::Error::InvalidValue);
}
}
}
// ...
}
kmod::module!(name: "hv", init_with_params: init);
Params::words splits them at blanks, each key=value or a word alone, so
a value has no blank in it; text is all of them as typed. They are lent
for the init's call: what a module keeps of them, it copies. A parameter a
module has not got should fail the load, said on out, as hv's and
modtest's do -- a word meant for it dropped without a sound is a setting
the machine goes on without, and nobody told. A module declared with
init takes none, and refuses any:
$ insmod /sshd.ko port=2222
sshd: takes no parameters, and was given "port=2222"
module: sshd: init failed
insmod: /sshd.ko failed, error 502
They are at most 255 bytes (ModuleTable::PARAMS_MAX). The module's header
is at layout version 3 -- 2 when its init came to take them, 3 with its
stop -- and a module built before is refused with header version 2, this kernel reads 3: rebuild it.
Building
make modules # out/x86_64/modules/<name>.ko
make modules ARCH=aarch64 # out/aarch64/modules/<name>.ko
make and make nocheck build them too. Each module is compiled on its own,
with its own copy of core, alloc, kcore and kmod, into a target
directory of its own (src/crates/target/modules), because it is compiled with
flags the kernel's Rust is not:
-Crelocation-model=pic, since nobody knows where it will be loaded;- on x86,
-Ccode-model=small: the kernel is built with the large code model so it can be linked in the top half of the address space, and a module has no need of that -- everything a PIC module addresses of its own isrip-relative, and everything of the kernel's goes through the GOT; - compiler-builtins' own
memcpy,memsetand friends, so that a module imports nothing but the kernel's API.
The staticlib is then linked into an ELF shared object:
-Bsymbolic, so every reference the module makes to itself is bound at link time and what is left for the loader isRELATIVErelocations and the kernel's functions;-z separate-loadable-segments -z max-page-size=4096: every segment starts on a page of its own, since page permissions are per page and each segment gets its own;- a version script that exports
nos_module_infoand nothing else; -z now,-z norelro: every import is bound at load time, and there is no lazy binding and no dynamic linker to protect anything from.
Last, llvm-nm -n -C lists the module's functions, demangled, and
llvm-objcopy adds the list to the .ko as a .nos_syms section -- what
backtraces name a module's frames with (below). Rust's v0 names would need a
demangler in the kernel otherwise.
hello.ko comes out around 25 KiB.
Releases
A tagged release (.github/workflows/release.yml) carries every module the
Makefile builds, next to the kernels it was built with, as <name>-x86_64.ko
and <name>-arm64.ko -- so a running nos can fetch one over HTTPS and load
it:
$ wget https://github.com/irqlevel/nos/releases/download/<tag>/blkload-x86_64.ko /blkload.ko
$ insmod /blkload.ko
The release's system image, nos-x86_64.squashfs, carries them all too, in
/lib/modules next to the kernel they were built with, and that is where a
server set up from it loads them from (Install).
Take it from the release the running kernel came from (version names it):
the kernel from another release may have another kernel interface, and then
refuses the module (What a module may call). The
release's SHA256SUMS covers the modules too, for sha256 to check.
Loading
insmod <path> [params] reads a .ko off any mounted filesystem -- put it on the root
filesystem with wget from a web server on the build host, or build it into
a fresh root image with scripts/mkrootfs.sh <image> <MiB> <dir>. The loader
(kernel/module.cpp) then:
-
checks the file: ELF64, little-endian, a shared object for this CPU, headers inside the file. No thread-local or interpreter segment. Every loadable segment page-aligned, inside the file, clear of the others and never both writable and executable.
-
binds its imports, before mapping anything. Each undefined symbol in
.dynsymis looked up by name in the kernel's export table; a module the kernel cannot satisfy is refused with the list of everything it lacks. A weak import may go unresolved and binds to 0. -
maps the image: pages of its own, which need not be physically contiguous, mapped writable into one run of kernel virtual addresses -- from a window of 16 MiB blocks set aside for runs the page allocator's own blocks, 512 KiB at most, cannot hold (
mm::map_large_pages). The segments are copied in; the zeroed tail of the last is.bss. The function names from.nos_symsgo into the same pages, past the segments, indexed by offset. -
relocates it: every
RELAsection the loader is meant to see (.rela.dyn,.rela.plt). Three kinds of relocation reach it, and the architecture says which is which (hal::classify_module_reloc):Meaning x86-64 arm64 nothing NONENONEload base + addend RELATIVERELATIVEsymbol + addend 64,GLOB_DAT,JUMP_SLOTABS64,GLOB_DAT,JUMP_SLOTAnything else is refused. In practice x86 modules carry
RELATIVEandGLOB_DATrelocations and arm64 onesRELATIVEandJUMP_SLOT-- calls through the PLT, whose slots are bound now rather than lazily. -
checks the header,
nos_module_info, now that its pointers are real: the magic, the layout version, the name, init, stop and exit pointing into the module's own code -- and the kernel interface the module was built against (below). -
protects it: each segment gets the permissions its program header asks for -- read-only, read-execute or read-write -- every CPU's TLB is shot down, and on arm64 the new code is cleaned from the data cache and invalidated in every CPU's instruction cache (
hal::sync_instruction_cache), which x86 does not need. -
runs its init, lending it the parameters and
insmod's output (Parameters). A second module by the same name is refused before this, and an init that fails leaves nothing behind: what it left registered is taken back as an unload's is, below, before its pages go.
Unloading
A shell command and a bus provider each run the module's code on the
caller's task -- the console's, an SSH session's, a job's -- whenever a call
comes, so a call can be running in a module at the moment it is told to go.
Were the module's state dropped under it, a call could start a task after the
drop had stopped the module's tasks -- a cluster init still running when
rmmod cluster came could, as a read of the code found -- and that task
would run on in code about to be freed. So
rmmod <name>, the halt and an init that failed all take a module down in
one order (ModuleTable::take_down), whatever module it is:
- its commands and providers are closed -- those whose handler is in
its image: no call of them starts from here on, their jobs are told to
stop, and none of the kind can be registered while the module goes
(
ModuleTable::unloading_at); - its stop runs (
kmod::Module::stop, nothing unless the module says otherwise): what a call still running may be blocked on that only the module's going would end is told to end. sshd and api tell their servers to stop, so that a call whose output a client is not taking gives up; hv stops its guests, so that anhv boot,hv waitorhv execreturns; - the calls still running are waited out, for as long as they take --
one still running is in the module's code. A wait past ten seconds is
said in the log, as a join's is (
Task::wait), again each time it has doubled: which commands and providers, how many calls, and on which task (bt <pid>shows where it is); - the module is dropped, with no call of its commands or providers running or able to start;
- what the drop left registered is taken off, each said in the log as
the module's leaving it behind, and the mailboxes it left open are closed;
so are a UDP listener and a virtual NIC's sink whose code is in its image
(
rust_net_close_range), a timer it left running and an interrupt handler -- a line's or an MSI-X entry's -- it left registered: the bridge's slots whose code is in its image (sweep_module_slots). Each would otherwise call into pages about to be freed. A task it left running is asked to stop and waited for (sweep_module_tasks); and then what it opened through the C ABI and left open is closed, said the same way: a TCP listener or connection and NAT (rust_net_close_range), a device queue and a device's claim (rust_block_module_gone), an image and a file (rust_fs_module_gone), an event (rust_events_module_gone). Each table keeps whose every entry is -- the module, by the name the loader knows it by, from an address in its code that the open passes (kcore::owner); an accepted connection is its listener's owner's. Left open, a device stayed claimed by a name nothing answered to, an image unwritable, a mount held by a file, a port taken and NAT busy for the uptime, and the module's next load refused the lot;
and only then are its pages unmapped and freed. rmmod must not be run from
the module's own command, which would wait for itself.
Loads and unloads run in task context: a module's init and exit may sleep,
and an exit that waits out a command still running may take as long as that
command does. So nothing is held across an init or an exit. The table's lock
covers looking a module up and moving it from one phase to the next --
loading, live, unloading -- and nothing else: a load or unload that takes its
time holds up no other, and lsmod never waits. A module is on the list
while its init runs, so a second insmod of it is refused, as is an rmmod
of one still loading or already unloading.
insmod and rmmod each hand the work to a task of their own and wait for it
at most five seconds (ModuleTable::SHELL_WAIT_MS). What the loader says is
printed when it is done by then. When it is not -- an unload waiting on a
command, say -- the shell says so and gets its prompt back; lsmod shows the
module as unloading meanwhile, and the kernel log says how it ended:
$ rmmod slowexit
rmmod: slowexit is taking its time and goes on in the background -- lsmod shows where it is, the kernel log will say how it ended
$ lsmod
slowexit 12 KiB at 0xFFFF8000..., 5 kernel imports, unloading
$ dmesg 5 module:
... module: rmmod slowexit, done in the background, error 0: module: slowexit unloaded
poweroff and reboot unload every module that can be unloaded, newest
first, before the filesystems are unmounted and the soft IRQs stop -- so a
module's exit still has the kernel services it may need, and nothing of the
module is left running while they go. The shells are stopped after the
modules, not before: a shell may be inside a module's command that returns
only when its module is told to stop -- an hv boot on the console as
poweroff comes over SSH -- and the order above is what gets it out. From the
moment the halt begins no module is loaded (insmod says the machine is going
down); a load another task is in the middle of is waited for, ten seconds at
most, and unloaded with the rest.
What a module may call
The export table is generated by the build, like the symbol
table: from pass1.elf, the kernel's first link, the Makefile
takes every function named in an extern "C" block of the ffi crate that the
kernel defines, and writes their names and addresses into
out/<arch>/module_exports.S, which the second link and the final one take in.
Every such function the Rust staticlib defines is taken into each link by
-u, whether or not anything in the image calls it, and the build fails if a
module it makes imports a function the table lacks
(Building). So what a module
can call is what an in-kernel Rust driver can call; adding a kernel service
for modules is the same three steps as adding one for the drivers (see
Rust in the kernel), and the table picks
it up.
A module compiled against one version of those declarations and loaded into
a kernel built from another would call functions with arguments they no
longer take. The build hashes the ffi crate's sources -- and the
tracepoints' payloads kcore declares (base/kcore/src/trace/events.rs), bytes a
module's sites hand the kernel's emit() (tracing)
-- into a digest that goes into every module's header and into the kernel,
and the loader refuses a module whose digest is not the kernel's:
module: built against another kernel interface (ffi 3fa81c..., this kernel 9b02e7...) -- rebuild it from this tree
A module built outside the Makefile carries unset and is refused, and so is
one whose word is no digest at all -- an empty one, from a build with no
sha256sum, once matched every module built the same way. The Makefile and
kmod refuse to build with such a digest, and the loader to load one.
A module cannot call another module. What it offers others -- the host API
above all -- it offers on the management bus: kcore::mgmt:: Provider::register(name, methods, descriptor, handler) registers it, and the
Provider kept in the module's state unregisters it when the module is
dropped. The loader has closed it before that and waited out its calls and
jobs (Unloading), as the unregister would, so an unload never
leaves a call in code that is gone. modtest has one, which the boot's
test_module_bus calls and unloads under a running job.
blkload
blkload (src/crates/modules/storage/blkload) runs a short load test against a block
device -- a disk, or one of its partitions, by the name disks gives it --
and reports IOPS, bandwidth and latency. Under QEMU, against its emulated
NVMe disk:
$ insmod /blkload.ko
$ blkload nvme0 randread qd=8 secs=2
blkload nvme0: randread, bs 4 KiB, qd 8, 2 s over 64 MiB
51965 ios in 2.06 s: 25223 IOPS, 98.5 MiB/s
latency us: min 56.0, avg 297.6, p50 270.3, p90 434.1, p99 770.0, p99.9 1146.8, max 9557.0
blkload <dev> [randread|randwrite|read|write] [bs=4k] [qd=1] [secs=5] [aio] [force]
randread, the default, andrandwritepick blocks at random over the whole device;readandwritego through it in order, the tasks taking consecutive blocks.qdtasks, up to 64, each keep one I/O in flight: the queue depth asked of the driver, which passes on as many as it has room for -- 8 at a time for virtio-blk, 63 for NVMe, 31 for a SATA disk with NCQ. A burst past that waits for a command to complete rather than failing.aio: one task keeps theqdrequests in flight instead, through the device's queue (kcore::block::DiskQueue) -- each started, the driver kicked, the ends reaped as they come -- which is the path a VM's disk, NBS's chunk server andnetblktake. A device with no asynchronous path does each as it is started, one at a time. The queue claims the device for a read test too, so a mounted filesystem's device is refused.bsis a whole number of sectors, up to 512 KiB -- and no more than the driver takes in one I/O, which today is a page for virtio-blk (one descriptor per request) and two for NVMe (two PRP entries, no PRP lists). Past that the first I/O fails, and blkload says the largest size that does go through.secs, 1 to 60: the command holds its shell that long. Over the UDP shell the reply comes whole once the command is done, andudpsh.pygives up on one after 30 s unless its third argument says otherwise -- so give a longer run a longer wait:udpsh.py <host> 9000 90.- Latency is timed per I/O on the kernel's clock, to the nanosecond; the
percentiles come off a histogram with sixteen buckets to each power of two,
so they are within 1/16. It runs from submission to the task running
again: the kernel's waits yield rather than sleep, so with more tasks than
CPUs it includes waiting for one, and the test keeps the CPUs busy. With
aio, from the start to the reap that finds it done.
Reads are always allowed. A write test destroys what is on the device, so it
has to be asked for by name, and it claims the device first
(kernel_blockdev_claim_as, which mounts and the disk log take too, and the
shell's diskwrite while it writes). The claim is refused
while a mounted filesystem, the disk log or another writer holds the device
-- or the disk it is a partition of, or one of its partitions -- whatever
else is said; once taken, it holds all of those off until the test is done,
so nothing can be mounted under it midway. Unless force is given the test
is also refused on a disk with partitions, and on a device that starts with
a superblock of the ext family or of a nanofs an older kernel made, a
partition table, a boot sector or a prepared
disk log area. A write test ends with a flush, timed.
To try a spare partition on a machine's NVMe disk, find it with disks --
a partition is named after its disk and numbered: nvme01, nvme02 -- fetch
the module from the release the machine's kernel came from
(Releases), and start with reads:
wget https://github.com/irqlevel/nos/releases/download/<tag>/blkload-x86_64.ko /blkload.ko
insmod /blkload.ko
blkload nvme02 randread qd=32 secs=10
blkload nvme02 randwrite qd=32 secs=10
blkload nvme02 write bs=8k qd=16
The module and the machine's kernel have to share a kernel interface -- see What a module may call -- so take both from one release, or build both from one tree.
netload
netload (src/crates/modules/net/netload) is a UDP load test from either end of
the wire, so that profile has something to look at other
than an idle machine: an idle twenty-CPU box spends about 0.06% of a core on
anything at all, and the paths worth seeing -- the frame pool, the driver
rings, soft IRQ dispatch -- only appear when packets are moving. Two
machines running it, one each way, move them with nothing else in the
picture. Under QEMU, the source against a host that sends back what it gets:
$ insmod /netload.ko
$ netload send 10.0.2.2 7777 size=200 pps=500 count=300 tasks=2
netload: sending to 10.0.2.2:7777 from port 9998, 200 byte datagrams, 2 task(s), 500 a second, 300 of them
$ netload
netload: sending to 10.0.2.2:7777 from port 9998, 200 byte datagrams, 2 task(s), 500 a second, 300 of them -- done in 0.613 s
sent 300 packets, 72600 bytes, 0 failed
echoes 300 packets, 72600 bytes, 0 from elsewhere
rate 0 tx-pps, 0 rx-pps, 0 tx-bytes/s
per cpu tx: 0:150 1:150
and the target, on another machine, is netload start -- then
netload send <its address> 9999 from the first.
netload start [port] [sink] [nic=ethN]
netload send <ip> <port> [size=64] [pps=0] [secs=0] [count=0] [tasks=1] [sport=9998] [nic=ethN]
netload what either has counted
netload stop both
netload reset the counters
The target (start, port 9999 unless told) answers every datagram, which
exercises receive and transmit together; sink drops them, which isolates
the receive half. The reply is the frame that arrived with its addresses
swapped where they lie -- no copy, no allocation -- built in the receive
callback itself, because a load target that woke a task per packet would be
measuring the wakeup; and the replies of one receive batch go to the NIC
together when the batch ends, one transmit lock and one doorbell for the
lot. It can be driven from any host as well: scripts/netload.py (--pps
to hold a rate, --threads to raise the ceiling).
The source (send) has tasks sender tasks, up to 16, each building its
datagrams straight into frames off the pool -- one copy of a template made
once, and a sequence number -- and handing them to the NIC a batch at a
time.
sizeis the payload, 16 to 1472 bytes.ppsis a rate over all the senders, and 0 is as fast as the NIC takes them.nic=ethNselects the interface for a source or target; without it both useeth0. The run ends whencountdatagrams are sent, whensecshave passed, or atnetload stop; a finished run stays to be asked about until the nextsend.- The destination's Ethernet address is asked of ARP once, before the first frame -- the gateway's, for an address off the subnet. If nothing answers, nothing is sent: a load test does not fall back to broadcast.
- A sender asks the NIC's transmit queue how much room it has before it
builds a batch, so that it loses nothing of its own to a full queue, and
leaves a quarter of the queue alone. A source that took every slot the
moment one opened would keep the queue full for as long as it ran, and
everybody else's frames would find no room: the shell's answers, the
netconsole's lines. On a machine whose only console is the network, the
load test would silence the one channel that says how it is going.
failedcounts what found no room anyway -- with several senders the room one was told of may be another's by the time it has built its batch. - What comes back to
sportis counted asechoeswhen it is from where the run is sending, and asfrom elsewherewhen it is not -- and never answered, so two sources pointed at each other do not bounce one datagram for good. Pointed at a target of this same module, a source therefore sees how much of what it sent made the round trip. - A datagram says which one it is:
NLD1, the sender's number (four bytes, big-endian), a sequence number (eight), then filler whose every byte is its own offset. Whatever receives them can tell what was lost, what came twice and what was damaged; a sequence number is spent whether or not its frame found room, so what the far end misses is what this end counted failed, plus what the wire lost.
Both write a line a second to the kernel log while they run -- packets, failures, the frame pool's misses and what is out of it, how often the tick had to find the frames an interrupt should have announced. The point is not the numbers: it is that the line keeps arriving. A machine goes deaf under load -- the shell stops answering and so does ping -- and every channel that could say why is a network channel. The netconsole only sends, so if these lines continue after the machine has stopped receiving, the machine is alive and the receive path is what died; if they stop with it, the kernel itself is wedged.
It is the one module that lives on the receive path, and the reason a
module's UDP listener is what it is: kcore::net::Nic::listen takes a
handler the listener owns, lends it each frame as a Lent, tells it when a
receive batch ends, and lends both calls the RxContext that reaches what
only the receive path touches (RxOwned) with no lock -- here, the TxBatch
the replies gather in. The module has no unsafe in it; the frame formats
are the netwire crate's, which the network layer is built on too.
tests/netload-test.py is its test (Tests and gates).
netblk
netblk (src/crates/modules/storage/netblk) serves an NVMe disk, or a partition of
one, over UDP, zero-copy both ways: netblk start nvme0 7000, then
scripts/netblk.py <host> 7000 ... from anywhere else. Its own page is
netblk. It takes its requests through the same listener netload
does, and takes them apart with netwire. It is the module that stops cleanly with the most in
flight -- a receive callback on one CPU, the disk's interrupt handler on
another, a worker task, frames the NIC still holds -- and its Drop is the
order that takes: the listener, the worker, then kcore::cpu::synchronize for
an interrupt handler still on its way out of the module's code.
sshd
sshd (src/crates/modules/net/sshd) is an SSH server: sshd allow <key>, sshd start, and an OpenSSH client logs in to the kernel's shell -- or copies files
in and out over SFTP, sftp and scp. The protocol is a
crate of its own, src/crates/common/net/ssh, which knows nothing of the kernel, and
SFTP's another, src/crates/common/net/sftp; the
module is the kernel's side -- a listener task, a task for each connection,
the files it keeps under /etc/ssh, and the files a client copies through
kcore::fs. Its page is sshd. Nothing loads
a module at boot by itself, so a machine that is to be reached only through
it gets two lines in /etc/rc, which the shell runs once the network is up:
insmod /sshd.ko and sshd start.
It needed the kernel to export more than the drivers ever had: TCP's passive
side (kcore::tcp::TcpListener, TcpStream), running a shell command with
its output handed back (kcore::cmd::dispatch), files (kcore::fs) and the
calling task's identity (kcore::task::current_id). And it carries its own
copy of the cryptography the TLS client uses: modules share nothing with the
kernel but the exported functions.
api
api (src/crates/modules/mgmt/api) is the host API: the management bus served
over HTTP/1.1 and a WebSocket, TLS 1.3 with a client's certificate required,
to the programs that manage the machine -- the panel, nosctl, other hosts'
panels. api client add <name> <role> <fingerprint>, api start. Its page is
The host API.
It is the bus's first caller from a module: kcore::mgmt::call, kind,
providers, describe and the jobs, over the bus's C ABI (kernel_mgmt_call
and the rest), as well as a provider of its own (api.status). And it links
the TLS server -- tls with its pinned feature, which the kernel's own build
leaves off -- the web crate's HTTP and WebSocket, and conf for api.toml.
edit
edit (src/crates/modules/tools/edit) is a text editor, for a person at an SSH
session with a terminal: edit /etc/rc, from the shell ssh <host> gives,
or ssh -t <host> edit /etc/rc. The image's /etc/rc loads it after sshd;
on a machine whose /etc/rc came before that, insmod /lib/modules/edit.ko
does, and a line saying so in /etc/rc keeps it -- an edit, now, of /etc/rc
itself. The editor is a crate with no kernel in it, src/crates/common/text/edit, which
tests/edit-test.py runs on the host; the module is its seat in the
kernel: the command, the file read and written, and the session's terminal
-- the keys typed (Output::read_input) and its size, which the session
tells the command it runs (Output::terminal, sshd).
The console and the UDP shell have no terminal to lend, and edit says so
there rather than draw on nothing.
The keys are a Mac's habits on Control -- a terminal keeps Command for itself, and sends Option as characters unless told otherwise -- and nothing needs a key a Mac keyboard lacks:
| Keys | |
|---|---|
^S (^O) / ^Q |
save / quit, asked first when there are changes: y saves and leaves, n leaves without, Esc goes back |
^F |
find: the match found as it is typed, Enter or ↓ the next, ↑ the one before, Esc leaves it selected; a term with no capital letter matches either case |
^G |
go to a line |
^Z / ^Y |
undo / redo; a run of typing, of deletes or a paste is one step |
^X (^K) / ^C / ^V |
cut / copy / paste the selection -- or, with none, the cursor's line, pasted back above the cursor's; cuts one after another collect their lines |
| Shift with any move | selects |
^A / ^E |
the line's first character that is not blank, then its start / its end -- ⌘← / ⌘→ under iTerm2's Natural Text Editing |
⌥← / ⌥→ |
a word back / on |
^W / ^U |
delete the word before / everything before on the line -- ⌥⌫ / ⌘⌫ under Natural Text Editing |
fn-⌫, ^D |
delete forward |
PgUp / PgDn, ⌥↑ / ⌥↓ |
a page up / down, where the terminal passes them on (Terminal.app with Shift); the trackpad scrolls as arrows |
Esc |
the selection gone; ^L draws the screen again |
⌘C and ⌘V are the terminal's: a selection made with the mouse copies out
of the editor, and a paste comes in bracketed, whole, as text -- a ^S or an
ESC in it is not a key, and a pasted y answers no question.
A file is its bytes, and comes back out as it went in: a file saved
untouched is the same file -- CR LF line ends, no newline at the end, NUL
bytes, invalid UTF-8 all kept. What is not text is shown for what it is,
in reverse: a control character as ^X, a byte that is no UTF-8 in hex, a
direction or zero-width mark as ?. A save is kcore::fs::write, which
writes the new content whole and syncs it before it takes the old one's
place, so a full disk or a crash leaves the old file and not half of the
new one; a file that changed on disk since it was read is asked about before
it is written over; and a session that ends under changes not saved -- the
connection gone -- leaves them in <file>.save, or the first .save.1 to
.save.9 not taken, never over a file that is there, and the kernel log
says where. A file is held whole in kernel memory, and over 16 MiB is not
opened; an edit that cannot have the memory it needs is not made, and says
so, rather than panic the kernel.
hv
hv (src/crates/modules/hypervisor/hv) is the hypervisor, the
beginning of stage 3. It is two crates --
hvarch, the CPU's virtualization extension and all of the hypervisor's
unsafe, and hv, everything above it, which has three sites -- plus this
module, which is their lifetime, their shell command and the guests it
starts. Neither crate is a
default member of the workspace, so a kernel built without the module has no
hypervisor in it at all.
It is the module that makes the clearest case for the shape. The one piece
of state it takes is not the module's: EFER.SVME and MSR_VM_HSAVE_PA on
AMD, CR4.VMXE and VMX root operation on Intel belong to the CPU, and an
rmmod that forgot them would leave the CPU saving host state into a page
that has been freed and given to somebody else, with the code that would
have turned it off unmapped. So the module turns the extension off in its
own Drop -- after the command is unregistered, so nothing can ask it
anything -- reads back what every CPU has, and says so if anything is left.
tests/hv-test.py is that round trip: load, turn on, unload without
turning off, load again and ask the CPUs.
Before any of that, its guests stop. A guest hv started runs on a vCPU task
of its own until it is stopped, and an hv boot may be minutes into its
time; the module's stop stops both -- which is also what lets an hv exec or
hv wait still waiting on one return, since the loader waits for every call
of the command still running before it drops the module -- and the Drop
then unregisters the command, and only then turns the extension off. An hv start still reading its files when the
unload begins finds the module going when it comes to add its guest, and
stops that guest itself before it returns. tests/hv-linux-test.py unloads with a
guest running and checks the order in the log
(Guests that stay up).
The rest of it is what a module does with CPUs. A page per CPU (CpuPage)
is allocated in task context, because the IPI handler that hands it to the
CPU runs with interrupts off and may not allocate; kcore::cpu::run_on_with
carries it over as a borrowed value rather than a word to cast back, which
is sound because run_on does not return until the handler has run.
numabench
numabench (src/crates/modules/test/numabench) measures what each NUMA
node's memory costs the CPUs of each node (NUMA). A task bound to
a CPU of each node takes mib= of the heap there, in blocks of its largest
size (512 KiB) -- its node's, as an allocation is the node of its CPU first
-- and threads a random cycle through their cache lines in place (Sattolo's
shuffle); then a task on a CPU of each node follows that cycle loads=
lines, each load waiting for the one before, and reads every word in order
for a second -- a line's latency as a task meets it, TLB misses among it,
and one CPU's bandwidth: a line a pair of nodes, with the share of the
memory's pages that were its node's as their physical addresses say. Every
node's memory is taken before any is read, and given back after the last
read: a block freed is kept by the heap for its next taker, whichever node
that one is on.
numabench [mib=256] [loads=4000000]
heapbench
heapbench (src/crates/modules/test/heapbench) times the kernel heap as Rust code
reaches it -- Box, Vec, String go through the global allocator to
kernel_alloc, and so does everything it allocates. Each workload runs on
one CPU and then on N at once, a task bound to each CPU, and reports the
time an operation took as the workers saw it, and the operations a second of
all of them together. Under QEMU on an M-series Mac (arm64, HVF, four CPUs):
$ insmod /heapbench.ko
$ heapbench
heapbench: 200 ms a run, on 1 CPU and on 4
workload ns/op 1cpu ns/op 4cpu Mops/s 4cpu
pair 16 170.1 165.1 24.2
pair 1536 161.7 171.8 23.2
pair 4096 139.6 1868.1 2.1
pair 262144 160.7 1425.9 2.8
batch 64 209.0 325.2 12.2
grow 64k 5427.5 8239.6 0.4
pass 256 481.7 583.1 6.8
heapbench [cpus=N] [ms=200] [pass [roam]]
pair S: an allocation of S bytes and its free. The sizes are the ones the heap treats differently: its pools' classes (16 to 1024), the largest class, whose block has a page to itself (1536, 2032), and the page allocator's runs (4096 and up).batch S: 64 allocations, then their frees -- what a pool's page refill and give-back cost.grow 64k: a vector grown to 64 KiB in 512-byte pieces and dropped, every reallocation an allocation, a copy and a free.pass Schecks as much as it measures: each worker makes a batch of blocks, every word of each its block's id -- the worker's slot and a number -- mixed with the word's index, hands it to the next worker and checks and frees the batch handed to it: every block freed on another CPU than the one that took it. A block that comes back changed ends the run withCORRUPT, the size, the maker, the word that was wrong and what it held -- which block's, by the id it carries.passalone runs only these, a stress rather than a measure (heapbench pass ms=10000).roam(it impliespass) takes the workers off their CPUs: two a CPU, bound to none, each pausing after a round -- a yield, or a sleep of up to 300 µs. A task moves only when it is displaced while it can run and its queue is busier than another by two (Load balancing), so workers that never sleep leave every queue even and nobody moves; sleeping, they leave their CPUs short, and each wakeup displaces whoever runs there, at any point of a round -- a free among them. A free moved between its CPU's TLB flush and its list of the CPUs still to flush once left the CPU it moved to with the freed block's translation, and the next block at that address was read and written through it (TLB shootdown): on x86 under KVM, four CPUs, the tree before the fix panicked inroam's first round, a kept block found written after its free.- Nothing panics on a refusal: an allocation the heap refuses ends the run and says so.
tlsbench
tlsbench (src/crates/modules/net/tlsbench) times TLS 1.3 on this machine's
CPUs: both pinned ends of tls::pinned -- a server and a client, each with
a key made for the run -- in one kernel, over a pipe in memory, so that
nothing is measured but the handshake, the crypto and the sessions' own
work. ipcnet's links between hosts are such sessions; ChaCha20-Poly1305 runs
on the crypto crate's assembly in the kernel's SIMD sections, and the command
shows which suite is cheapest on this machine.
$ insmod /tlsbench.ko
$ tlsbench mb=64
tlsbench: 2 CPUs, both pinned ends over memory
aes128-gcm handshake 2.4 ms; 64 MB client->server 92.2 MB/s, server->client 93.5 MB/s
aes256-gcm handshake 2.4 ms; 64 MB client->server 83.1 MB/s, server->client 80.8 MB/s
chacha20-poly1305 handshake 1.2 ms; 64 MB client->server 204.6 MB/s, server->client 201.7 MB/s
tlsbench [mb=16] [suite=aes128|aes256|chacha]
Each way, the sender encrypts in one task and the receiver decrypts in
another, as two hosts would -- on two CPUs where there are two. The suite
the two agreed on is checked to be the one asked for (Session::suite).
tests/tlsbench.py [--arch ...] [--mb N] [--cpus N] boots nos with it and
prints what it said; the numbers above are the AX41's, under KVM
(docs/tls.md, "What it costs").
Two hosts can also be measured over TCP, with and without TLS. Start the
server first, then the client; ipcnet id prints the fingerprint each side
pins the other by:
server$ tlsbench listen mb=64 peer=<client fingerprint>
client$ tlsbench connect=10.77.0.95 mb=64 peer=<server fingerprint>
server$ tlsbench raw listen mb=64
client$ tlsbench raw connect=10.77.0.95 mb=64
The default NIC is eth3, the port 39241; nic= and port= change them.
TLS reads /etc/ipc/tls/identity.pem unless id= names another PEM holding a
private key and a certificate. Both ends use bulk TCP buffers and the same
20-ms RTO floor as ipcnet; rto=20..200 changes that floor for a diagnostic
run. The client sends the requested amount, the server
sends it back, and each side checks every received byte and prints its own
send and receive rates. raw measures exactly the same stream without a TLS
session around it, separating TCP from the pinned session and from ipcnet's
message framing.
ipcnet
ipcnet (src/crates/modules/cluster/ipcnet) is the message channel between hosts
(docs/ipc.md, "Between hosts: ipcnet"): the channel's router, which makes a
mailbox on another host of the cluster an address here and name@host a
name. Its folder is /etc/ipc (insmod /lib/modules/ipcnet.ko conf= names
another): hosts.toml -- this host's name, the cluster's id, its peers, each
pinned by its key -- and tls/identity.pem, its key and certificate in one
file, made at the first start (tls/key.pem and tls/cert.pem, as openssl
makes them, are read where there is none), and tls/next.pem while a key
is staged for a rekey.
$ insmod /ipcnet.ko
$ ipcnet init a # this host, in a new cluster -- or cluster=<32 hex>
$ ipcnet id # its key, which every peer pins
$ ipcnet add b 10.9.0.2 9c1e... # a peer, by its key
$ ipcnet start
$ ipcnet
ipcnet: a in cluster 0123..., on eth0 port 39240, key 5f3a... -- serving 12 s
b 10.9.0.2 dials -- up 10 s as host 65; sent 200 got 200, ...
$ ipc ping kernel.echo@b count=100
ipcnet [start | stop | id | init <name> [cluster=<hex>] | add <name> <ip> <key> [<key>] | remove <name>]
add and remove change a running server too: a peer taken off is lost
and its connections closed; one whose address changed is lost and dialed
again; one whose keys changed keeps its connections -- each made with a key
it had -- and the next is made with a key it has now (to cut a key's
connections at once, remove the peer). tests/ipc-test.py runs three of them on a LAN of
tests/hub.py's.
A host of a cluster has its peers from the cluster's registry instead
(below): ipcnet's control mailbox, ipcnet.ctl (ipcwire::control, a Host
name, so that nothing from another host reaches it), says who this host is
and takes the list of peers it is to have, which it writes into hosts.toml
as add and remove do -- one writer of the file.
cluster
cluster (src/crates/modules/cluster/cluster) is the cluster's registry
(docs/cluster.md): every host of the cluster, its key and its address,
kept through Raft by a member on each host, which gives ipcnet its peers.
It needs ipcnet loaded first. Its folder is /etc/cluster (insmod /lib/modules/cluster.ko conf= names another): member, the log in
raft/, and begun, the mark that keeps a member whose log is gone from
starting as the one it was (docs/cluster.md). What it does with its member
-- starts it, stops it, recovers the last one standing -- is raftmember's,
as every group's module has it.
$ insmod /cluster.ko
$ cluster init test # the first host
$ cluster invite b 10.9.0.2 dcbe3e82... # on a member: b's key, from `ipcnet id` on b
cluster: b invited from 10.9.0.2 for 15 minutes -- on it: cluster join nos1-...
$ cluster join nos1-... # on b
$ cluster hosts
$ cluster remove b
cluster [init <name> | invite <host> <ip> <key> | join <token> | hosts | remove <host> | revoke <host>
| maintenance <host> on|off | address <host> <ipc|underlay|public> <ip|none> | rekey
| recover [<cluster>]]
It is on the management bus as the cluster provider too, whose
descriptor the panel builds the cluster's page of.
tests/cluster-test.py makes a cluster of three on tests/hub.py's
LAN.
vnet
vnet (src/crates/modules/net/vnet) is the cluster's networks for VMs
(plans/vnet.md): a raft group of its own -- vnet.raft on every member,
raftmember's offered group, as nbs-mds's is -- of the networks, their ports,
the public addresses and the cluster's firewalls (common/net/vnetmeta).
It needs ipcnet and cluster loaded first: its members are hosts of the
registry, a port's host the registry's node, and what no network or public
address may cover the registry's hosts' own addresses, which it asks the
cluster provider for. Its folder is /etc/vnet (dir= names another);
compact= is its snapshot's floor, as nbs-mds's.
$ insmod /vnet.ko
$ vnet init lab # the first host
$ vnet host add b # a host of the registry, offered the vnet
$ vnet create lan 10.10.0.0/24 # .1 the gateway on every host
$ vnet port create lan <uuid> # as hv makes a VM's port (V2)
$ vnet fw create edge && vnet fw edge add allow in tcp 22
It is on the management bus as the vnet provider too, whose descriptor
the panel builds its page of networks, ports, public addresses and
firewalls of. hv takes its ports and its table from the member on its host
from V2 on; tests/vnet-test.py --phase v1b makes a vnet of three on
tests/hub.py's LAN.
nbs-mds and nbs-cs
NBS, the replicated block storage (docs/nbs.md), is two modules on every
host of the cluster registry. nbs-mds (src/crates/modules/storage/nbs-mds)
is its metadata service: a member on each host, through Raft over ipc --
raftmember's, as cluster.ko's is -- of the NBS cluster's members, each host's
chunk server and its devices, and the volumes. Its folder is /nbs/mds
(dir= names another). Its offers, the listener of a host in no NBS
cluster and the members' commands are raftmember's offered, which vnet's
module will run too; nbs recover makes the last member standing the one
voter. nbs-cs (src/crates/modules/storage/nbs-cs) is the
host's chunk server: it asks the host's mds which devices are its, takes them
in with queues of its own, and serves the chunks on them. It takes no
parameters, and is loaded after nbs-mds.
$ insmod /nbs-mds.ko
$ insmod /nbs-cs.ko
$ nbs init store # the first host
$ nbs host add b # on a member: b, a host of the registry
$ nbs devices add part:4f7661ab-... # on each host: a device for its cs
$ nbs volume create disk1 64
$ nbs io write disk1 0 65536 0x5a # a volume's bytes, through the cs's
$ nbscs # the cs: its devices, what it served
tests/nbs-test.py runs both on three hosts of tests/hub.py's LAN.
Backtraces
A frame in a module's code is named like the kernel's own, with the module
after it -- in the panic report, in bt and in the profiler's call chains:
Backtrace:
[0] 0xFFFF800012DA1C40 mod_hello::init::{closure#0}+0x3c [hello]
[1] 0xFFFF80000104A2F1 kernel::Cmd::dispatch_dynamic+0xd1
...
Modules: hello 0xFFFF800012DA0000+0x5000
SymbolTable::describe asks the kernel's table first -- which now answers
only for an address in the kernel's text, rather than naming whatever lies
past its last function after that function -- and then the module table,
whose names come from each module's .nos_syms. The name is copied out under
the table's lock, since the module may be unloaded right after; the lock is
only tried, never waited on, so a panic can ask too. The panic report ends
with where each module sits (Modules:), which places any frame the list
could not name.
Testing
The boot self-test loads a module on both architectures. modtest
(src/crates/modules/test/modtest) is built with the kernel and embedded in its
image (out/<arch>/modtest_blob.S); test_modules in kernel/test.cpp loads
it, and its init checks what a loader can get wrong -- initialised data,
.bss (a megabyte of it, past the 512 KiB images were once held to), a
table of function pointers, a trait object's vtable, allocations from the
kernel heap, a kernel object created and destroyed through the export table
-- and fails the load if anything comes out wrong. The test then runs the
command the module registered through the shell's dispatcher, has the
symbolizer name the function whose address the command prints, checks a
second copy is refused, unloads it and checks the command went with it,
twice -- the second time given answer=7, which the command must answer
with, so what insmod was given has reached the init whole; then has a
parameter modtest has not got refused by its init, and parameters longer
than 255 bytes by the loader; and last feeds the loader damaged copies -- truncated, another
machine's, an import the kernel lacks, no header, a bad magic, another kernel
interface -- each of which it must refuse.
test_module_unload, once there are tasks, holds the unload to its order
(Unloading): it starts modtest hold on a task of its own, a
call that returns only once the module's stop has run, and unloads modtest
under it. The stop must find modtest's command and provider closed already
-- a call of the one says "not found", of the other no_provider -- the
call says so as it returns, and modtest's drop panics if a call of its
command is still running. Before the unload modtest leaves a timer running
(modtest timer) and a UDP listener registered on eth0 (modtest listen), as a module's bug would: the timer's next tick after the unload
would fault in the freed image, and a second load's modtest listen must
find the port free again -- the sweep took the first listener off.
test_module_tcp_left, run once TCP is up, does the same for what a module
opens: modtest leaves a TCP listener with its handle forgotten (modtest tcp), and after the unload a second load's modtest tcp must take the port
again -- the sweep closed the first by its owner. With the sweep taken out,
the smoke boot fails it.
slowexit (src/crates/modules/test/slowexit) is never loaded by the kernel itself:
its exit takes eight seconds, for testing an rmmod that outlasts the
shell's wait by hand or from a script.
Limits
- A module's image, function names included, is at most 16 MiB
(
PageTable::MAX_LARGE_MAP_PAGESpages), and so is the.kofile. The window they are mapped from holds 63 such runs at a time. - A module that registers a softirq handler (
kernel_softirq_register, the one namePERMANENT_IMPORTSholds) cannot be unloaded (above). A block or a net device it cannot register at all; a virtual NIC it opens stays when it goes, for its next load to find, and does not make it permanent. - An unload waits for a running call of the module's commands and providers for as long as it runs -- in a task of its own, so it holds up nothing else, and saying so in the log every so often; but a call that never returns, and that the module's stop does not end, leaves its module unloading for good.
- Modules cannot call each other; each carries its own
kcore, so they share no statics either. - Only the functions
ffideclares are exported -- not C++ classes, not arbitrary kernel symbols. - No signatures: whoever can run
insmodcan run code in the kernel. On nos that is whoever can reach the shell, which already could.