Blog Migrate
Process Migration in Sprite i386 (v0.1.0)
Sprite was designed from the start as a distributed system where processes can move between machines. The i386 port preserves that property: a running process can be transparently relocated from one QEMU guest to another, retaining its PID, file descriptors, open file offsets, signal state, memory mappings, and TTY association. The destination host can even continue using the source's console through a proxy, so the user sees no discontinuity.
This tutorial walks through how migration works, how to build and run it, and how to read the results.
Quick start
make ARCH=i386 PLATFORM=qemu-pc
make test-qemu-migration
That single command builds the kernel, assembles three disk images (one server, two clients), patches both client images with the migration feature flag, boots them under QEMU TCG with multicast networking, and asserts the serial log markers that prove migration completed exactly once. No TAP device or elevated privileges are required.
If every check passes you will see:
qemu: exactly-once client migration and resources passed
What happens under the hood
The migration test scenario runs three QEMU guests on a shared multicast Ethernet segment:
+----------+ +----------+ +-----------+
| Server | OFS | Client 2 | migrate | Client 3 |
| (host 1)|<-------->| (source)|--------->| (dest) |
+----------+ native +----------+ native +-----------+
\ /
\ multicast /
+-------------+
Server (host 1): Boots, mounts its OFS image, and starts the remote block server so both clients can access the shared namespace. It does not participate directly in migration.
Client 2 (source, host 2): After the kernel boots and initsprite starts, it creates a synthetic probe process (PID 55) with known signals, descriptors, file offsets, and a TTY console descriptor. It sends this probe to client 3, verifies the TTY proxy round-trips correctly, then sends the real initsprite process (PID 2) over. After the transfer commits, client 2 enters a TTY proxy server loop, continuing to service console reads and writes on behalf of the migrated process.
Client 3 (destination, host 3): Listens for incoming migration RPCs. When a
probe arrives, it validates the PCB state, tests the TTY proxy, and reports
MIGRATION:RESOURCES_OK. When the real process arrives, it restores the full
address space, descriptors, and signal state, then hands the process to the
scheduler as if it had always been local. The shell starts and the user sees
INIT:START only on the destination.
Guarantee
A migrated process moves exactly once. It either transfers successfully and resumes at the destination, or the transaction rolls back and the source retains the process. It never disappears or executes concurrently at both nodes.
Building migration images
make test-qemu-migration builds the images automatically, but you can
construct them manually to understand each step.
1. Build the kernel
make ARCH=i386 PLATFORM=qemu-pc
This produces build/i386-qemu-pc/sprite.img.
2. Assemble the cluster
make cluster-images
This copies the base image three times and patches client 2 and client 3 with
mknodeconfig:
build/host/mknodeconfig client 2 | dd of=build/client2.img bs=512 seek=1024 conv=notrunc
build/host/mknodeconfig client 3 | dd of=build/client3.img bs=512 seek=1024 conv=notrunc
Each client image gets a 64-byte Platform_NodeConfig sector written at
offset 1024 (sector 2) that identifies the host ID, MAC addresses, root
server, and boot epoch.
3. Patch the migration feature flag
make migration-images
This copies the cluster images, then rewrites the feature word in both client images:
build/host/mknodeconfig client 2 migration | dd of=build/migration-client2.img ...
build/host/mknodeconfig client 3 migration | dd of=build/migration-client3.img ...
The migration argument sets bit 0 of the features field
(PLATFORM_FEATURE_MIGRATION_TEST = 0x00000001). When the kernel boots and
sees this flag, it activates the migration code path instead of the normal
user-entry path.
The node config sector layout:
Offset Field Value (example for client 2)
------ ----- ----------------------------
0 magic 0x434e5053 ("SNPC")
4 version 1
6 size 64
8 role 2 (diskless client)
12 hostId 2
16 rootServerId 1
20 bootEpoch 0x5350524900000002
28 nativeMac 02:53:50:00:02:00
34 ipMac 02:53:51:00:02:00
40 ipv4Address 10.0.2.2
44 ipv4Netmask 255.255.255.0
48 ipv4Gateway 10.0.0.2
52 features 0x00000001 (MIGRATION_TEST)
56 reserved1 0
60 checksum CRC-32
Running the migration
Automated
make test-qemu-migration
From the Sprite shell
The native migrate command is installed in /boot on cluster images. From
a diskless client, move the shell that is currently running the command to
host 3 with:
migrate 3
The process is the default target when no PID is supplied. A successful
self-migration prints migrate: resumed after the process has restored on
the destination; the source continues to provide its TTY as a proxy, so the
same console remains usable.
To migrate another process, use -p and the process ID. In tcsh, put a
normal sleep in the background so the shell remains available to issue the
migration request. tcsh sets $! to the PID of the most recently started
background job:
sleep 15 &
set sleepPid = $!
echo $sleepPid
migrate -p $sleepPid 3
3 is the destination Sprite host ID in the three-node example; substitute
the host ID of the client you want to use. The sleep command prints
SLEEP:START before blocking and SLEEP:DONE when its timer expires. After a
successful request, the sleeping process continues on the destination and
its completion output is still visible through the source-owned TTY proxy.
The command prints migrate: acknowledged for an existing process. Omit the
host argument (migrate -p $sleepPid) to let Sprite select an available peer.
For the deterministic QEMU regression, use the sleeper helper instead. It
forks the sleeping child and prints its PID, which is useful when a test needs
to avoid relying on shell job-control output:
sleeper 15
# SLEEPER:PID=42 # use the PID printed by the guest
migrate -p 42 3
# migrate: pid=42 source=2 destination=3 state=...
# migrate: acknowledged
sleeper prints SLEEP:START before its delay and SLEEP:DONE after it
resumes. The latter confirms the existing sleeping process survived the
transfer. Both forms use the same native migration path; the helper merely
makes the child PID unambiguous for the automated test.
The command rejects unavailable processes, invalid host IDs, and requests with no available destination instead of silently falling back to a local execution.
For the exact three-node interactive regression, run:
make test-qemu-migration-command test-qemu-migration-sleep-command
Manual
Boot the three images in separate QEMU instances connected via multicast socket networking:
NETWORK=239.195.1.1:34500
# Server
qemu-system-i386 -machine pc -cpu 486 -accel tcg -m 128M \
-display none -monitor none -serial file:server.log \
-no-reboot -no-shutdown -snapshot \
-drive file=build/migration-server.img,format=raw,if=ide \
-netdev socket,id=native,mcast=$NETWORK \
-device pcnet,netdev=native,mac=02:53:50:00:01:00 \
-netdev user,id=ip,restrict=on \
-device pcnet,netdev=ip,mac=02:53:51:00:01:00 &
# Client 2 (source)
qemu-system-i386 -machine pc -cpu 486 -accel tcg -m 128M \
-display none -monitor none -serial file:client2.log \
-no-reboot -no-shutdown -snapshot \
-drive file=build/migration-client2.img,format=raw,if=ide \
-netdev socket,id=native,mcast=$NETWORK \
-device pcnet,netdev=native,mac=02:53:50:00:02:00 \
-netdev user,id=ip,restrict=on \
-device pcnet,netdev=ip,mac=02:53:51:00:02:00 &
# Client 3 (destination)
qemu-system-i386 -machine pc -cpu 486 -accel tcg -m 128M \
-display none -monitor none -serial file:client3.log \
-no-reboot -no-shutdown -snapshot \
-drive file=build/migration-client3.img,format=raw,if=ide \
-netdev socket,id=native,mcast=$NETWORK \
-device pcnet,netdev=native,mac=02:53:50:00:03:00 \
-netdev user,id=ip,restrict=on \
-device pcnet,netdev=ip,mac=02:53:51:00:03:00 &
wait
Each instance uses 128 MiB of RAM, TCG software emulation, a serial port redirected to a log file, a write-once snapshot so the disk images are not modified, and dual PCnet NICs: one on the native multicast segment and one on a restricted SLIRP user network (unused in this scenario but reserved for the IP milestone).
Reading the serial logs
Server log (server.log)
The server boots, mounts OFS, and starts the remote block server:
OFS:STATE_COLD
CONSOLE:NAMESPACE_OK
KERNEL:READY
OFS:EXPORT_READY
OFS:EXPORT_READY means the server is accepting remote block requests. Both
clients need this before they can access the shared filesystem.
Source log (client2.log)
The source boots, starts initsprite, then sends the migration:
KERNEL:READY
OFS:REMOTE_OK
USER:ELF_OK
USER:ENTER
USER:PID2_OK
Then the migration kicks in and the process is transferred:
MIGRATION:SOURCE_COMMITTED
The source also validates that the TTY proxy works by confirming exactly one
MIGRATION:TTY_PROXY_OK marker. After committing, the source does not start
initsprite (no INIT:START) because its process was sent to client 3. It
enters the TTY proxy server loop and services console I/O for the migrated
process indefinitely.
Destination log (client3.log)
The destination receives and validates the probe process first:
MIGRATION:RESOURCES_OK
MIGRATION:TTY_ACK_OK
Then it receives the real process and boots into it:
MIGRATION:DESTINATION_READY
USER:ELF_OK
USER:ENTER
VM:CR3_OK
INIT:START
INIT:START appears exactly once and only on the destination. That is the
shell starting.
Assertion checklist
The test script verifies:
| Marker | Where | Meaning |
|---|---|---|
OFS:EXPORT_READY |
server | Server is accepting remote OFS |
MIGRATION:SOURCE_COMMITTED |
client 2 | Source committed the transfer |
MIGRATION:TTY_PROXY_OK (exactly 1) |
client 2 | TTY proxy round-tripped |
INIT:START (absent) |
client 2 | Source did not also start a shell |
MIGRATION:RESOURCES_OK |
client 3 | Probe PCB state validated |
MIGRATION:TTY_ACK_OK |
client 3 | Destination verified TTY proxy |
MIGRATION:DESTINATION_READY |
client 3 | Real process restored |
INIT:START (exactly 1) |
client 3 | Shell started only here |
No PANIC: |
all | No kernel crashes |
The five-layer migration stack
The implementation is split into five modules, each with a clean boundary:
1. Wire format (migration_wire.c/h)
Serializes the process control block into a 3164-byte fixed-width little-endian blob. Every field has explicit bounds: PID is nonzero, ABI is valid, user context has ring-3 segment selectors, heap regions are ordered, all 64 descriptors have recognized types, addresses are within user bounds, and strings are null-terminated within their buffers. The blob is CRC-32 checksummed. Decoding is strict: any corruption or version mismatch is rejected.
Contents of the snapshot:
Process identity: PID, parent, process group, host ID
Execution state: ABI, state, user context (EIP, ESP, segments)
Signals: mask, pending, 32 action entries
Descriptors: 64 slots (OFS files, pipes, console, none)
Credentials: uid, gid, effective IDs
Memory layout: heap base/break/limit
Filesystem: current directory path
Timers: alarm tick, sleep tick, profiling state
Arguments: argc, envc, argv/env pointer addresses
2. Image format (migration_image.c/h)
Wraps the wire snapshot together with the serialized virtual address space
into a single blob with a 32-byte header (magic, version, total size, offsets
to the process and VM sections, CRC). This is the unit that crosses the
network. On the destination, Migration_ProcessRestore allocates a new PCB,
applies the snapshot, and reconstructs the address space via Vm_Deserialize.
3. Transaction protocol (migration_txn.c/h)
A four-phase state machine:
NONE --> PREPARED --> TRANSFERRING --> COMMITTED
(abort) (abort/rollback)
- SourceBegin: Validates the process (must be RUNNABLE or BLOCKED, no existing migration), transitions to MIGRATING, retains the image.
- SourceTransfer / SourceAcknowledge / SourceRollback: Phase transitions with ownership transfer semantics. The source keeps the process until the destination acknowledges.
- DestinationPrepare: Allocates a slot (idempotent: re-prepare returns the existing slot).
- DestinationTransfer: Writes image chunks (idempotent: duplicate chunks are detected and skipped).
- DestinationCommit: Verifies completeness, invokes the user callback to restore the process.
- DestinationAbort: Frees the slot and discards partial data.
The destination table supports up to 8 concurrent inbound migrations.
4. RPC transport (migration_rpc.c/h)
Sends the image blob in 896-byte chunks over native Ethernet RPC (command 200). The client side:
- Calls
SourceBeginandImageEncodeto produce the blob. - Sends a PREPARE message with the transaction key and total size.
- Sends TRANSFER messages for each chunk, with offset and length.
- Sends COMMIT. On failure at any step, sends ABORT and calls
SourceRollback.
The server side dispatches each message to the transaction layer, with
duplicate detection via Rpc_DuplicateCache. A 500-tick deadline and 20-tick
retransmit bound the transfer.
5. TTY proxy (migration_tty.c/h)
After migration, the process's console descriptor still points back to the source host. The TTY proxy lets the migrated process read, write, and control its console through RPC:
- Client side (destination):
Migration_TtyProxyOpspopulates aProc_ConsoleProxyOpsstructure withProxyRead,ProxyWrite,ProxyControl, andProxyReadycallbacks. Each sends an RPC to the source. - Server side (source):
Migration_TtyServerPollreceives requests, services them through the local console, and caches the last 8 results for duplicate replay.
This means tcsh running on client 3 can continue reading from and writing to
the console that physically belongs to client 2.
What gets preserved
| Resource | Preserved? | Notes |
|---|---|---|
| PID | Yes | Same PID on destination |
| Parent PID | Yes | In the snapshot |
| Process group | Yes | |
| Signals | Yes | Mask, pending, all 32 action entries |
| File descriptors | Yes | All 64 slots |
| OFS file handles | Yes | Remote handles reopen against the server |
| File offsets | Yes | Seek positions survive |
| Console/TTY | Yes | Via source-owned RPC proxy |
| Memory mappings | Yes | VM pages serialized and restored |
| Heap state | Yes | Base, break, limit |
| Current directory | Yes | Path preserved |
| Environment/argv | Yes | Pointers and counts |
| Profiling state | Yes | Buffer address, scale, offset |
What can be migrated
Eligibility
Migration_SourceBegin (migration_txn.c:13-22) enforces four preconditions:
- The process must be
inUsewith a non-zeroownerHostId. - The destination host must differ from the source.
- The process state must be
RUNNABLEorBLOCKED. - The process must not already be mid-migration (
migrationState == NONE).
There is no PROC_DONT_MIGRATE check in the i386 port. The original Sprite
had additional restrictions -- a flag preventing certain processes from
migrating, a permission mask gating non-root migration, a check refusing
foreign or dying processes, and a root-only bulk-eviction path. The i386 port
omits all of that. Any process that meets the four criteria above can move.
In practice this means every process that is not currently executing on the CPU
at the instant of migration is eligible. A process blocked waiting for console
input, pipe data, or file I/O is eligible. A process in the run queue waiting
for its time slice is eligible. A process currently mid-syscall on the CPU is
not (it would be in RUNNING state, not RUNNABLE or BLOCKED).
The i386 userland
The port ships exactly four userland binaries, all built from source in
src/user/:
| Binary | Source | Purpose |
|---|---|---|
initsprite |
initsprite.c |
Init process; forks abi-probe, then tcsh |
tcsh |
tcsh/ (upstream) |
C shell with job control |
cat |
cat.c |
File concatenation |
sleep |
sleep.c |
Pause for N seconds (prints serial markers) |
abi-probe |
abi_probe.c |
ABI validation test program |
There is no C compiler, assembler, linker, or any other development tool in
the tree. The entire userland is cross-compiled on the host with LLVM/Clang
targeting i386-unknown-none-elf. The OFS image is assembled by mkofs
(tools/mkofs.c) which copies these five binaries into /boot/ alongside the
kernel bootstrap, initsprite, and tcsh.
All five programs are normal user processes with no migration restrictions.
The test scenario migrates initsprite (PID 2) -- the process that forks
tcsh -- from client 2 to client 3. After migration, tcsh starts on the
destination and the user can run cat, sleep, or any other command in
/boot/. Every one of these processes is eligible for migration the same way.
The TTY proxy system exists specifically so that tcsh (or any shell) can
continue interactive use of the console after migration. Console reads, writes,
ioctl, and select all proxy back to the source host via RPC, so the user sees
no discontinuity.
Creating your own migration scenario
The current implementation triggers migration automatically at boot when the
PLATFORM_FEATURE_MIGRATION_TEST flag is set. To create a custom scenario:
1. Prepare a test image
make ARCH=i386 PLATFORM=qemu-pc
make image
# Patch a client image with the migration flag
build/host/mknodeconfig client 2 migration | \
dd of=my-client2.img bs=512 seek=1024 conv=notrunc
build/host/mknodeconfig client 3 migration | \
dd of=my-client3.img bs=512 seek=1024 conv=notrunc
2. Boot manually
Use the QEMU invocation from the section above, substituting your images. Pass
-serial stdio instead of -serial file: if you want to watch the output
live.
3. Inspect the serial output
# After the QEMU instances finish:
rg 'MIGRATION:' client2.log client3.log
rg 'PANIC:' server.log client2.log client3.log
4. Extend the kernel
The migration entry point is in src/kernel/main.c:738-769. The kernel checks
for PLATFORM_FEATURE_MIGRATION_TEST and hostId to decide whether to act as
source (host 2) or destination (host 3). You can modify MigrationSendProbe
to create different synthetic processes, or replace the probe with a call to
migrate an arbitrary existing process.
The key functions to understand:
MigrationSendProbe(main.c:342) -- creates the test processMigrationSendProcess(main.c:316) -- encodes and transmitsMigrationCommit(main.c:277) -- destination-side restore callbackMigrationReceiveProcesses(main.c:394) -- destination receive loopMigrationServiceProbeProxy(main.c:378) -- TTY proxy verification
Writing a new user program
The i386 userland is intentionally small: initsprite, tcsh, cat, and
sleep. Every program is a freestanding ELF32 binary linked with the same
runtime objects. There is no libc archive; each program pulls in only the object
files it needs from src/user/libc/. The build uses host Clang targeting
i386-unknown-none-elf and links with LLD against src/user/i386/user.ld.
Anatomy of a user program
Every user program follows the same structure:
-
Declare the syscalls you need as
externfunctions. The i386 port has two syscall ABIs: native (Sprite-native, declared insyscalls.S) and Unix (POSIX-compatible, declared inunix_syscalls.S). Most programs use the native ABI forread/write/open/close/lseekand the Unix ABI forfork/exec/wait/kill. -
Write
main(int argc, char **argv). There is no_startin user code; the CRT objectcrt0.ohandles entry and callsmain. -
Link with the standard set of objects.
Example: sleep.c
The sleep program (src/user/sleep.c) demonstrates the pattern:
extern int sprite_sleep(unsigned int seconds);
extern int sprite_write(unsigned int descriptor, const void *buffer,
unsigned int length);
static int
WriteString(const char *string, unsigned int length)
{
return sprite_write(1, string, length) == (int)length ? 0 : -1;
}
static unsigned int
ParseSeconds(const char *string)
{
unsigned int result;
unsigned int index;
result = 0;
for (index = 0; string[index] >= '0' && string[index] <= '9'; index++) {
result = result * 10U + (unsigned int)(string[index] - '0');
}
return result;
}
int
main(int argumentCount, char **arguments)
{
unsigned int seconds;
if (argumentCount != 2 || arguments == 0 || arguments[0] == 0 ||
arguments[1] == 0) {
(void)WriteString("usage: sleep <seconds>\r\n", 23);
return 1;
}
seconds = ParseSeconds(arguments[1]);
if (seconds == 0) {
(void)WriteString("SLEEP:ZERO\r\n", 12);
return 0;
}
if (WriteString("SLEEP:START\r\n", 13) != 0) return 1;
(void)sprite_sleep(seconds);
if (WriteString("SLEEP:DONE\r\n", 12) != 0) return 1;
return 0;
}
The program is intentionally minimal: no headers, no libc, just raw syscall
declarations and serial markers for test verification. sprite_sleep is a
native syscall that blocks the process for the given number of seconds.
sprite_write writes to file descriptor 1 (the console).
Build rules
The Makefile follows a two-step pattern for each user program:
${BUILD}/user/sleep.o: src/user/sleep.c
@mkdir -p ${.TARGET:H}
${CC} ${USER_CFLAGS} -c ${.ALLSRC} -o ${.TARGET}
${BUILD}/sleep.elf: ${BUILD}/user/abi_note.o ${BUILD}/user/crt0.o \
${BUILD}/user/syscalls.o ${BUILD}/user/unix_syscalls.o ${USER_LIBC_O} \
${BUILD}/user/sleep.o src/user/i386/user.ld
${LD} -m elf_i386 -nostdlib -T src/user/i386/user.ld -o ${.TARGET} \
${BUILD}/user/abi_note.o ${BUILD}/user/crt0.o \
${BUILD}/user/syscalls.o ${BUILD}/user/unix_syscalls.o \
${USER_LIBC_O} ${BUILD}/user/sleep.o
The link line always starts with the same five objects (ABI note, CRT, native
syscall stubs, Unix syscall stubs, and the shared libc objects), followed by
your program's object. The linker script places everything at 0x00400000 and
separates text, read-only data, and writable data into distinct pages.
Adding to the OFS image
The image builder (tools/mkofs.c) creates a deterministic OFS filesystem with
hardcoded directory entries and file descriptor allocations. To add a new
binary:
-
Add a
sleepPathparameter toCreateImage()and asleepContents/sleepBytes/sleepKilobytes/sleepFragmentvariable set. -
Calculate the fragment:
sleepFragment = catFragment + ceil(catBytes / 4096) * 4. -
Add a directory entry in the
/boot/directory block (20 bytes per entry, FD number 12 for sleep). -
Allocate a file descriptor (FD 12) with
InitializeDescriptor, set its last-byte offset, fragment pointers, and kilobyte count. -
Mark the allocated fragments in the bitmap.
-
Write the file data with
WriteAt. -
Update
summary.freeFileDescriptors(subtract 1) andsummary.freeKilobytes(subtract sleep kilobytes). -
Update
tools/mkimage.shto pass the new ELF as a 10th argument. -
Update the
imagetarget in the Makefile to listsleep.elf.
Running the new program
Once the image is built, sleep appears in /boot/ on every node. In the
interactive shell:
sprite3# /boot/sleep 5
SLEEP:START
The process blocks for 5 seconds, prints SLEEP:DONE, and returns to the
shell. While blocked in sprite_sleep, the process is in PROC_STATE_BLOCKED
and is eligible for migration.
Migrating a sleeping process
The current migration scenario in main.c is hardcoded to migrate initsprite
(PID 2) at boot. To migrate an arbitrary user process, you would need to:
- Add a
Sys_Migratesyscall handler insrc/kernel/syscall.cthat callsMigrationSendProcesswith the caller's process and a destination host ID. - Add it to the
nativeTableat index 37 and incrementSYS_NATIVE_COUNT. - Add a
SYS_MIGRATE = 37constant insrc/include/user.h. - Write a user-level stub in
src/user/i386/syscalls.S:.globl sprite_migrate sprite_migrate: movl $37, %eax int $0x80 ret - Call
sprite_migrate(destinationHostId)from any user program.
Until that syscall is implemented, migration is limited to the kernel-initiated
test scenario. The sleep program demonstrates the building blocks --
freestanding ELF, serial markers, BLOCKED state -- that a future migration
syscall would operate on.
Troubleshooting
Migration does not complete: Ensure all three QEMU instances are running
and connected to the same multicast address. Check that the server log shows
OFS:EXPORT_READY before the clients try to access the filesystem.
PANIC:migration:receive: The destination timed out waiting for the source
to send. Verify the source image has the migration flag set (check for
PLATFORM_FEATURE_MIGRATION_TEST in the node config sector).
PANIC:migration:send: The source could not complete the transfer. This
typically means the destination was unreachable or the RPC deadline expired.
MIGRATION:TTY_PROXY_OK missing on source: The TTY proxy round-trip
failed. Both native network interfaces must be functional. Check the PCnet
driver initialization in the serial logs.
QEMU instances hang: Each instance has a 35-second hard timeout in the
automated test. When running manually, you can kill them with kill or
Ctrl-C. The -no-shutdown flag prevents QEMU from exiting when the guest
halts; the -snapshot flag ensures disk images are not modified.
Host-side unit tests
Before running the full QEMU scenario, you can validate the migration modules in isolation:
make test
The host tests exercise:
test_migration_wire: encode/decode round-trip, checksum, version, size, and invalid descriptor rejectiontest_migration_image: image encode/decode with VM pages, CRC rejection, allocation failure rollback, same-host rejectiontest_migration_txn: source lifecycle, destination idempotent re-prepare, duplicate transfer detection, commit completenesstest_migration_rpc: message encode/decode, server dispatch, idempotent re-prepare, transfer gaps, commit callback, abort cleanuptest_migration_tty: message encode/decode, version rejection, chunk size overflow
These use fake hardware backends and run in milliseconds on the host, making them useful for rapid iteration during development.