# Running Cells for NetBSD on bhyve

## What is Cells?

Cells for NetBSD is a kernel-enforced, jail-like isolation stack built natively for NetBSD. It sits between chroot (too weak) and Xen (too heavy), providing lightweight workload isolation with declarative, Lua-based desired-state management.

Core components:
- **secmodel_cell** - kernel security model enforcing cell boundaries
- **cellman** - declarative control plane (desired state, apply, backup/restore)
- **cellui** - interactive curses TUI frontend
- **cellctl** - low-level runtime primitive layer (create/destroy/exec/stats)
- **libcellman** - shared library for core logic

Project links:
- Cells documentation: https://netbsd-cells.petermann-digital.de/
- NeoBSD integration builds: https://neobsd.com/
- Source tree: https://github.com/MatthiasPetermann/netbsd-src/tree/netbsd-11-cells-dev-2
- Build system: https://github.com/MatthiasPetermann/neobsd

## Prerequisites

- A running NetBSD 11 VM on bhyve with SSH access (see [BLOG_NETBSD_VM.md](BLOG_NETBSD_VM.md))
- NeoBSD 11 image (kernel + sets from https://neobsd.com/downloads.php)

## Step 1: Install NeoBSD (Cells-enabled) components

Cells requires a patched kernel and userspace from NeoBSD. The standard NetBSD 11 does not include Cells.

### 1a: Download the NeoBSD kernel and sets

```sh
cd /tmp
export PATH=/sbin:/usr/sbin:$PATH

# Download NeoBSD kernel (with secmodel_cell compiled in)
ftp https://neobsd.com/downloads.php?d=neobsd-11/26.12/amd64-x86_64/amd64/binary/kernel/netbsd-GENERIC.gz

# Download base set (contains cellman, cellui, cellctl, libcellman)
ftp https://neobsd.com/downloads.php?d=neobsd-11/26.12/amd64-x86_64/amd64/binary/sets/base.tar.xz

# Download modules set (contains secmodel_cell.kmod)
ftp https://neobsd.com/downloads.php?d=neobsd-11/26.12/amd64-x86_64/amd64/binary/sets/modules.tar.xz
```

### 1b: Install the NeoBSD kernel

```sh
gunzip netbsd-GENERIC.gz
cp netbsd-GENERIC /netbsd
```

### 1c: Install the base and modules sets

```sh
tar xJpf base.tar.xz -C /
tar xJpf modules.tar.xz -C /
```

### 1d: Reboot

```sh
shutdown -r now
```

After reboot, verify the kernel:
```sh
uname -a
# Should show: GENERIC.neobsd-26.12 or similar
```

## Step 2: Bootstrap Cells

```sh
export PATH=/sbin:/usr/sbin:$PATH
cellman system bootstrap
```

### Fixing the bootstrap 404 error

The bootstrap may fail with a 404 error. This happens because:

1. `cellman` uses the `ftp(1)` command to download NetBSD release sets
2. The VM's `ftp` client tries IPv6 addresses first, which don't work in bhyve
3. The resulting error manifests as a misleading "404 Not Found"

**Solution:** Replace the `ftp` binary with a curl-based shim that forces IPv4:

```sh
export PATH=/sbin:/usr/sbin:$PATH

# Save original
cp /usr/bin/ftp /usr/bin/ftp.orig

# Create shim
cat > /usr/local/bin/ftp << 'EOF'
#!/bin/sh
output=""
url=""
while [ $# -gt 0 ]; do
    case "$1" in
        -o) shift; output="$1" ;;
        -[46AadefginpRtVv]) ;;
        -b|-H|-N|-P|-q|-r|-s|-T|-x) shift ;;
        http*|https*) url="$1" ;;
    esac
    shift
done
if [ -n "$url" ] && [ -n "$output" ]; then
    curl -4 -sSL -o "$output" "$url"
elif [ -n "$url" ]; then
    curl -4 -sSL "$url"
else
    echo "ftp-shim: no URL provided" >&2
    exit 1
fi
EOF
chmod +x /usr/local/bin/ftp

# Make sure /usr/local/bin is in PATH
echo 'export PATH=/usr/local/bin:$PATH' >> /etc/profile
```

### Fixing the release version mismatch

`cellman` derives the release version from `uname -r` (e.g., `11.0_RC4`), but the NetBSD CDN only has sets under `NetBSD-11.0`. Download the sets manually and symlink:

```sh
export PATH=/sbin:/usr/sbin:$PATH

# Create directory for the detected release
mkdir -p /var/cellman/releases/11.0_RC4/amd64

# Download sets to the 11.0 path
mkdir -p /var/cellman/releases/11.0/amd64
cd /var/cellman/releases/11.0/amd64
curl -4 -sSL -O https://cdn.netbsd.org/pub/NetBSD/NetBSD-11.0/amd64/binary/sets/base.tar.xz
curl -4 -sSL -O https://cdn.netbsd.org/pub/NetBSD/NetBSD-11.0/amd64/binary/sets/etc.tar.xz

# Symlink to the RC4 path
ln -sf /var/cellman/releases/11.0/amd64/base.tar.xz /var/cellman/releases/11.0_RC4/amd64/base.tar.xz
ln -sf /var/cellman/releases/11.0/amd64/etc.tar.xz /var/cellman/releases/11.0_RC4/amd64/etc.tar.xz
```

Now retry:
```sh
cellman system bootstrap
```

Expected output:
```
ok bootstrap release=11.0_RC4 arch=amd64 xbase=NO
```

### Verify the installation

```sh
# Check kernel module is loaded
modstat secmodel_cell

# Check cellman works
cellman cell list
cellman volume list

# Check config
cat /etc/cellman.conf
cat /etc/modules.conf    # should contain "secmodel_cell"
grep cell /etc/rc.conf   # should contain "cellman=YES"
```

## Step 3: Install Caddy via pkgsrc

Cells run inside a minimal base layer that doesn't include pkgsrc. We need to install Caddy on the host first, then copy the binary into the cell's overlay.

```sh
export PATH=/sbin:/usr/sbin:/usr/bin:/usr/pkg/bin:$PATH

# Install Caddy from pkgsrc
pkg_add caddy
# Installs to /usr/pkg/bin/caddy
```

## Step 4: Create a ZFS-backed data pool for cell storage

Since the VM has only one disk, create a file-backed ZFS pool:

```sh
export PATH=/sbin:/usr/sbin:/usr/bin:/usr/pkg/bin:$PATH

# Create a 5GB file for the ZFS pool
dd if=/dev/zero of=/var/cellman/cells-pool.img bs=1m count=5120

# Create the ZFS pool
zpool create cellspool /var/cellman/cells-pool.img

# Create datasets for cell data and root
zfs create cellspool/caddy-data
zfs create cellspool/caddy-root
```

Create the web content on the ZFS dataset:

```sh
printf ':8080 {\n  root * /etc/caddy\n  file_server\n}\n' > /cellspool/caddy-data/Caddyfile
printf 'Hello from Cells on ZFS!\n' > /cellspool/caddy-data/index.html
```

Create the cellman volume manifest:

```sh
cat > /etc/cellman/00-volume-caddy-data.lua << 'EOF'
volume("caddy-data", {
  mode = "0755",
})
EOF
```

## Step 5: Create the cell manifest

Create `/etc/cellman/01-cell-caddy.lua`:

```lua
cell("caddy", {
  autostart = true,
  create = {
    profile = "medium",
    reserved_ports = "8080",
    root = "/cellspool/caddy-root",
  },
  supervise = {
    cmd = "/.overlay/usr/pkg/bin/caddy run --config /.overlay/etc/caddy/Caddyfile --adapter caddyfile",
  },
  healthcheck = "test -f /.overlay/etc/caddy/index.html",
})
```

### Understanding the overlay architecture

NetBSD cells use a layered filesystem approach:

1. **Base layer** (`/var/cellman/base/`) - read-only null mount of the NetBSD base set
2. **Overlay** (`/.overlay/`) - writable layer mounted on top at `/.overlay`

The base layer's `/usr/pkg` is a symlink to `../.overlay/usr/pkg`, which means it resolves to `/.overlay/usr/pkg` inside the cell. This is why the supervise command references `/.overlay/usr/pkg/bin/caddy` - it leverages this symlink resolution.

The base layer's `/etc`, `/var`, `/tmp`, `/home`, `/root` are all symlinks pointing into `/.overlay/`. This means **all writable paths are redirected into the overlay**. There is no way to disable this - the overlay is architecturally mandatory.

Files placed in the cell's overlay directory **before** cell creation are visible inside the cell at `/.overlay/`. Mounts done on the host **after** cell creation do NOT propagate into the cell's mount namespace.

#### Why the overlay is mandatory

The `ensure_base_writable_links()` function in cellman creates these symlinks in the base layer at cell creation time:

```sh
# Simplified from cellman source
rm -rf "${BASE_LAYER}/etc" "${BASE_LAYER}/var" "${BASE_LAYER}/tmp" \
    "${BASE_LAYER}/home" "${BASE_LAYER}/root" "${BASE_LAYER}/usr/pkg"

ln -s ".overlay/etc" "${BASE_LAYER}/etc"
ln -s ".overlay/var" "${BASE_LAYER}/var"
ln -s ".overlay/tmp" "${BASE_LAYER}/tmp"
ln -s ".overlay/home" "${BASE_LAYER}/home"
ln -s ".overlay/root" "${BASE_LAYER}/root"
ln -s "../.overlay/usr/pkg" "${BASE_LAYER}/usr/pkg"
```

This means inside the cell:
- `/etc` → `/.overlay/etc` (writable per-cell copy)
- `/var` → `/.overlay/var` (writable per-cell copy)
- `/usr/pkg` → `/.overlay/usr/pkg` (writable per-cell copy)
- Everything else → read-only from base layer

**You cannot specify a custom rootfs that bypasses the overlay.** The `root` parameter in the manifest only controls where the read-only base layer is mounted; the overlay is always created and symlinks are always created.

## Step 6: Populate the overlay and apply

Before applying, populate the overlay with the caddy binary and web content:

```sh
export PATH=/sbin:/usr/sbin:/usr/bin:/usr/pkg/bin:$PATH

# Destroy any existing cell
cellctl destroy caddy 2>/dev/null
rm -rf /var/cellman/cells/caddy

# Create overlay directories
mkdir -p /var/cellman/cells/caddy/root
mkdir -p /var/cellman/cells/caddy/overlay/etc/caddy
mkdir -p /var/cellman/cells/caddy/overlay/usr/pkg/bin

# Copy the caddy binary into the overlay
cp /usr/pkg/bin/caddy /var/cellman/cells/caddy/overlay/usr/pkg/bin/caddy

# Write web content directly (printf avoids NUL byte issues with cp from ZFS)
printf ':8080 {\n  root * /etc/caddy\n  file_server\n}\n' > /var/cellman/cells/caddy/overlay/etc/caddy/Caddyfile
printf 'Hello from Cells on ZFS!\n' > /var/cellman/cells/caddy/overlay/etc/caddy/index.html

# Verify the files are correct (no NUL bytes!)
od -c /var/cellman/cells/caddy/overlay/etc/caddy/Caddyfile
file /var/cellman/cells/caddy/overlay/usr/pkg/bin/caddy
```

Now apply:

```sh
cellman apply --all
```

Verify it's running:

```sh
cellman cell list --view merged
# Should show: caddy, managed, RUNNING=YES, PROCS=1

curl http://127.0.0.1:8080/
# Should show: Hello from Cells on ZFS!
```

### How it works

The cell creation process:
1. `cellman apply` creates the cell with `cellctl create`
2. The base layer is null-mounted as read-only at the cell root
3. The overlay directory is null-mounted at `/.overlay`
4. Inside the cell, `/usr/pkg` (symlink in base) resolves to `/.overlay/usr/pkg` (where we put caddy)
5. The healthcheck verifies `/.overlay/etc/caddy/index.html` exists
6. The supervise command starts caddy listening on port 8080

## Networking in Cells: Limitations and Workarounds

### The limitation: No network isolation

Cells share the host's network stack entirely. There is no network namespace isolation. When you run `ifconfig` inside a cell, you see the same interfaces and IPs as the host:

```sh
cellctl exec caddy /sbin/ifconfig
# Shows vioif0 with 192.168.3.225, lo0 with 127.0.0.1
```

There are no manifest fields for IP addresses, VLANs, bridges, or network namespaces. The kernel `secmodel_cell` has no network-related code.

### Workaround: IP aliases + application-level binding

While the network stack is shared, you can achieve **application-level isolation** by:

1. **Adding IP aliases to the host interface**:
   ```sh
   # On the host
   ifconfig vioif0 alias 192.168.3.200/24
   ifconfig vioif0 alias 192.168.3.201/24
   ```

2. **Configuring services to bind to specific IPs** (example with Caddy):
   ```sh
   # In the cell's Caddyfile
   http://192.168.3.200:8080 {
     root * /etc/caddy
     file_server
   }
   
   http://192.168.3.201:8080 {
     root * /var/www/other
     file_server
   }
   ```

   When caddy binds to `192.168.3.200:8080`, it **only** responds to requests on that IP. Requests to `192.168.3.225:8080` or `127.0.0.1:8080` get no response.

3. **Persisting aliases in rc.local**:
   ```sh
   # In /etc/rc.local
   ifconfig vioif0 alias 192.168.3.200/24
   ifconfig vioif0 alias 192.168.3.201/24
   ```

### Alternative: Loopback aliases for cell-to-cell communication

For services that only need to communicate between cells on the same host:

```sh
# On the host
ifconfig lo0 alias 192.168.3.200/32
ifconfig lo0 alias 192.168.3.201/32
```

Cells can then use these IPs for internal communication while being unreachable from the network.

### What doesn't work (yet)

- **Virtual Ethernet (vether) interfaces**: Not available as kernel modules on this build
- **Bridge interfaces**: Not available as kernel modules
- **Automatic IP assignment**: No cellman/cellctl support
- **Network namespace isolation**: Not implemented in `secmodel_cell`

### Summary table

| Approach | Isolation Level | Persistence | Use Case |
|----------|----------------|-------------|----------|
| Host IP alias + bind | Application-level | Manual/rc.local | Exposing services on different IPs |
| Loopback alias | Application-level (localhost only) | Manual/rc.local | Cell-to-cell on same host |
| Port reservation (`reserved_ports`) | Port-level | cellman manifest | Preventing port conflicts |

For production deployments requiring true network isolation, consider running each workload in a separate VM with its own bhyve instance and network interface.

The ZFS pool, null mounts, and cell need to survive reboots. Add to `/etc/rc.local`:

```sh
# ZFS pool import (file-backed)
zpool import cellspool 2>/dev/null

# Restore cell overlay content if missing
if [ ! -f /var/cellman/cells/caddy/overlay/usr/pkg/bin/caddy ]; then
    mkdir -p /var/cellman/cells/caddy/root
    mkdir -p /var/cellman/cells/caddy/overlay/etc/caddy
    mkdir -p /var/cellman/cells/caddy/overlay/usr/pkg/bin
    cp /usr/pkg/bin/caddy /var/cellman/cells/caddy/overlay/usr/pkg/bin/caddy
    printf ':8080 {\n  root * /etc/caddy\n  file_server\n}\n' > /var/cellman/cells/caddy/overlay/etc/caddy/Caddyfile
    printf 'Hello from Cells on ZFS!\n' > /var/cellman/cells/caddy/overlay/etc/caddy/index.html
fi

# Null mount ZFS data into cell volume path
mkdir -p /var/cellman/volumes/caddy-data
mount -t null /cellspool/caddy-data /var/cellman/volumes/caddy-data 2>/dev/null

# Apply cellman configuration (creates cell + starts supervision)
export PATH=/sbin:/usr/sbin:/usr/bin:/usr/pkg/bin:$PATH
cellman apply --all
```

### Reboot test

```sh
shutdown -r now

# After reboot:
ssh netbsd11
curl http://127.0.0.1:8080/
# Should show: Hello from Cells on ZFS!

cellman cell list --view merged
# Should show caddy with RUNNING=YES
```

## Debugging: What went wrong with Cells bootstrap

### Problem 1: `cellman: command not found`

After installing the NeoBSD base set, running `cellman system bootstrap` returned `sh: cellman: not found`.

**Diagnosis:** The cellman binary is installed at `/usr/sbin/cellman`, but `/usr/sbin` is not in the default user PATH on NetBSD. The default PATH is:

```
/usr/bin:/bin:/usr/pkg/bin:/usr/local/bin
```

**Fix:** Run with the full path or add `/sbin` and `/usr/sbin` to PATH:

```sh
export PATH=/sbin:/usr/sbin:$PATH
```

### Problem 2: `cellman: missing required tool: modstat/modload`

After fixing PATH, bootstrap failed with:

```
/usr/sbin/cellman: missing required tool: modstat/modload
```

**Diagnosis:** `cellman` checks for `modstat` and `modload` in PATH. These tools are at `/sbin/modstat` and `/sbin/modload`. Even though `/sbin` was in PATH for the parent shell, `cellman` might invoke subshells that don't inherit it.

**Fix:** Ensure both `/sbin` and `/usr/sbin` are in PATH when calling cellman:

```sh
export PATH=/sbin:/usr/sbin:/usr/bin:/usr/pkg/bin:$PATH
```

### Problem 3: `modload: secmodel_cell: Exec format error`

The first attempt to load the kernel module:

```
modload: /stand/amd64/11.0/modules/secmodel_cell/secmodel_cell.kmod: Exec format error
```

**Diagnosis:** Running `modstat -a | grep cell` revealed that `secmodel_cell` was already loaded from the `filesys` source - meaning it was **compiled into the kernel**, not a loadable module. The NeoBSD GENERIC kernel bakes `secmodel_cell` directly into the kernel image.

When the bootstrap then tried `modload` again, it failed with "linker error: global symbol `secmodel_cell_*' redefined" because the symbols already existed in the running kernel.

**Fix:** None needed. The module is already active. This can be confirmed with:

```sh
modstat secmodel_cell
# NAME              CLASS    SOURCE   FLAG  REFS    SIZE REQUIRES
# secmodel_cell     secmodel filesys  -        0    8059 -
```

The `source=filesys` means built-in. If it were a loadable module, it would show the `.kmod` file path.

### Problem 4: `ftp: Error retrieving file '404 Not Found'`

The most confusing error. Running `cellman system bootstrap` produced:

```
ftp: Error retrieving file `404 Not Found'
cellman: command failed: ftp
```

**Diagnosis - three separate issues combined:**

#### 4a: IPv6 broken in bhyve

The VM has IPv6 link-local addresses on its network interface, but bhyve doesn't route IPv6 traffic. The NetBSD `ftp(1)` client resolves `cdn.netbsd.org` to both IPv4 and IPv6 addresses and tries IPv6 first:

```
Trying [2a04:4e42::262]:443 ...
ftp: Can't connect to `2a04:4e42::262:443': No route to host
Trying [2a04:4e42:200::262]:443 ...
ftp: Can't connect to `2a04:4e42:200::262:443': No route to host
```

After the IPv6 attempts fail, `ftp` falls through with a garbled error that manifests as "404 Not Found". The `ftp` command supports `-4` to force IPv4, but `cellman` calls `ftp` without this flag.

**Verification:** `curl` works fine because it falls back to IPv4 automatically:

```sh
curl -4 -I https://cdn.netbsd.org/pub/NetBSD/NetBSD-11.0/amd64/binary/sets/etc.tar.xz
# HTTP/1.1 200 OK
```

But `ftp` hangs or errors out:

```sh
ftp -o /dev/null https://cdn.netbsd.org/pub/NetBSD/NetBSD-11.0/amd64/binary/sets/etc.tar.xz
# hangs forever
```

**Fix:** Replace `ftp` with a curl-based shim that forces `-4`. See Step 2 in the setup guide.

#### 4b: Release version mismatch

After fixing the `ftp` issue, bootstrap still failed:

```
/usr/sbin/cellman: missing /var/cellman/releases/11.0_RC4/amd64/base.tar.xz
```

**Diagnosis:** `cellman` derives the release version from `uname -r`, which returns `11.0_RC4`. It then constructs the download URL:

```
https://cdn.netbsd.org/pub/NetBSD/NetBSD-11.0_RC4/amd64/binary/sets
```

But the NetBSD CDN doesn't have `NetBSD-11.0_RC4` - only `NetBSD-11.0`. The CDN returns 404 for the entire directory listing, which `ftp` interprets as the error.

**Verification:**

```sh
# This works:
curl -I https://cdn.netbsd.org/pub/NetBSD/NetBSD-11.0/amd64/binary/sets/base.tar.xz

# This 404s:
curl -I https://cdn.netbsd.org/pub/NetBSD/NetBSD-11.0_RC4/amd64/binary/sets/base.tar.xz
```

**Fix:** Download the sets manually from the correct URL and symlink them to the path cellman expects:

```sh
mkdir -p /var/cellman/releases/11.0/amd64
cd /var/cellman/releases/11.0/amd64
curl -4 -sSL -O https://cdn.netbsd.org/pub/NetBSD/NetBSD-11.0/amd64/binary/sets/base.tar.xz
curl -4 -sSL -O https://cdn.netbsd.org/pub/NetBSD/NetBSD-11.0/amd64/binary/sets/etc.tar.xz

mkdir -p /var/cellman/releases/11.0_RC4/amd64
ln -sf /var/cellman/releases/11.0/amd64/base.tar.xz /var/cellman/releases/11.0_RC4/amd64/base.tar.xz
ln -sf /var/cellman/releases/11.0/amd64/etc.tar.xz /var/cellman/releases/11.0_RC4/amd64/etc.tar.xz
```

#### 4c: cellman.conf RELEASE field overridden by uname

Even after editing `/etc/cellman.conf` to set `RELEASE=11.0`, cellman continued using `11.0_RC4`. The `RELEASE` field in `cellman.conf` is only used as a template variable in comments; `cellman` ignores it at runtime and uses `uname -r` directly.

**Fix:** The symlink approach above works because it maps the `uname -r` value to the actual CDN paths.

### Problem 5: `cellman system bootstrap` curl version banner

After replacing `ftp` with a curl shim, bootstrap output included curl's verbose version banner:

```
curl 8.21.0 (x86_64--netbsd) libcurl/8.21.0 ...
```

**Diagnosis:** The initial shim was too simplistic - it called `curl` without `-s` (silent mode), so curl printed its version info and protocol list to stderr.

**Fix:** Add `-s` (silent) to the curl invocation in the shim. Also, the shim was called with arguments like `ftp -o /path/file https://url` which needed proper parsing of ftp's argument format.

### Problem 6: Cell can't find pkgsrc binaries

After creating a cell with `cellctl create`, running `cellctl exec caddy /usr/pkg/bin/caddy` returned "No such file or directory", even though caddy was installed on the host.

**Diagnosis:** The cell's base layer doesn't include pkgsrc. The base layer's `/usr/pkg` is a symlink to `../.overlay/usr/pkg`, which resolves to `/.overlay/usr/pkg` inside the cell. The cell's mount namespace doesn't see host-side mounts done after cell creation.

**Fix:** Copy the caddy binary into the overlay directory BEFORE cell creation. The overlay is visible at `/.overlay/` inside the cell, and the base layer's `/usr/pkg` symlink resolves to the binary there.

```sh
# This must be done before cellman apply / cellctl create
mkdir -p /var/cellman/cells/caddy/overlay/usr/pkg/bin
cp /usr/pkg/bin/caddy /var/cellman/cells/caddy/overlay/usr/pkg/bin/
```

### Problem 7: `mkdir /var/cellman/cells/caddy/root/data failed: Read-only file system`

When using a cell with a ZFS-backed root and volume mounts, cellman failed with a read-only filesystem error when trying to create mount points inside the cell root.

**Diagnosis:** The cell root is a read-only null mount of the base layer. Cellman cannot create directories inside it.

**Fix:** Use the overlay directory for writable content. Place files at `overlay/etc/caddy/` and reference them as `/.overlay/etc/caddy/` inside the cell.

### Problem 8: Files in overlay not visible inside cell

After copying files to the overlay directory on the host, they weren't visible inside the cell when checked with `cellctl exec`.

**Diagnosis:** The overlay null mount was established before the files were created. The mount captures the directory state at mount time, and new files may not be visible without remounting.

**Fix:** Either:
1. Populate the overlay BEFORE `cellman apply` / `cellctl create` (preferred)
2. Or remount the overlay: `umount /var/cellman/cells/caddy/root/.overlay && mount -t null /var/cellman/cells/caddy/overlay /var/cellman/cells/caddy/root/.overlay`

### Problem 9: Caddyfile contains NUL bytes after `cp` from ZFS

After `cp /cellspool/caddy-data/Caddyfile /var/cellman/cells/caddy/overlay/etc/caddy/`, the Caddyfile was filled with NUL bytes (`\0`), making caddy fail to parse it.

**Diagnosis:** `cp` from a ZFS null-mounted dataset can produce corrupted files with NUL bytes. The `od -c` command reveals the corruption.

**Fix:** Use `printf` to write text files directly instead of `cp` from ZFS:

```sh
printf ':8080 {\n  root * /etc/caddy\n  file_server\n}\n' > /var/cellman/cells/caddy/overlay/etc/caddy/Caddyfile
printf 'Hello from Cells on ZFS!\n' > /var/cellman/cells/caddy/overlay/etc/caddy/index.html
```

Always verify with `od -c` after writing:
```sh
od -c /var/cellman/cells/caddy/overlay/etc/caddy/Caddyfile
# Should show readable text, not \0 characters
```

### Problem 10: Cell supervisor respawns endlessly after config changes

Changing the cell manifest (e.g., disabling autostart) didn't stop the already-running cell. The supervisor kept respawning caddy.

**Diagnosis:** `cellman apply` with `autostart=false` doesn't destroy an already-running cell. The cellctl process continues supervising.

**Fix:** Force-stop the cell first:
```sh
cellctl destroy caddy 2>/dev/null
# Then remove stale overlay data if needed
rm -rf /var/cellman/cells/caddy
# Rebuild overlay and re-apply
```

### Summary of all issues

| # | Error message | Root cause | Fix |
|---|---|---|---|
| 1 | `cellman: command not found` | `/usr/sbin` not in PATH | `export PATH=/sbin:/usr/sbin:$PATH` |
| 2 | `missing required tool: modstat/modload` | `/sbin` not in PATH | Add `/sbin` to PATH |
| 3 | `modload: Exec format error` | Module already built into kernel | Ignore; `modstat` confirms it's loaded |
| 4 | `ftp: 404 Not Found` | IPv6 broken + release version mismatch | curl shim + symlink sets |
| 5 | curl version banner in output | Shim missing `-s` flag | Add `-s` to curl invocation |
| 6 | Cell can't find pkgsrc binaries | pkgsrc not in cell base layer | Copy binary into overlay before cell creation |
| 7 | `mkdir: Read-only file system` | Cell root is read-only null mount | Use overlay paths instead |
| 8 | Files in overlay not visible inside cell | Mount captures state at creation time | Populate overlay before `cellctl create` |
| 9 | Caddyfile contains NUL bytes after `cp` | `cp` from ZFS null mount corrupts files | Use `printf` instead of `cp` for text files |
| 10 | Supervisor respawns endlessly | `cellman apply` doesn't stop running cells | `cellctl destroy` before re-applying |

## Troubleshooting

### `cellman system bootstrap` fails with 404

The `ftp` client tries IPv6 addresses that bhyve doesn't route. Replace `ftp` with a curl-based shim. See Step 2.

### `cellman system bootstrap` fails with "missing release sets"

`cellman` derives the release version from `uname -r`, which may not match the NetBSD CDN path. Download and symlink sets manually. See Step 2.

### `modload secmodel_cell` fails with "Exec format error"

If using the NeoBSD GENERIC kernel, `secmodel_cell` is compiled into the kernel (not a loadable module). The `modload` error is harmless - `modstat secmodel_cell` will show it as loaded from `filesys` source.

## Summary of the full setup sequence

1. Install NeoBSD kernel (`netbsd-GENERIC.gz` -> `/netbsd`), base set, and modules set
2. Replace `ftp` with curl shim to work around IPv6 routing issue in bhyve
3. Symlink sets for release version mismatch
4. Run `cellman system bootstrap`
5. Install Caddy via pkgsrc
6. Create ZFS pool (`cellspool`) with datasets for cell data
7. Populate cell overlay with caddy binary and web content
8. Create cell and volume manifests
9. Apply with `cellman apply --all`
10. Add persistence to `/etc/rc.local`
