# NuttX ESP32-C3 build, flash, and setup

This guide is the reproducible procedure for the ESP32-C3 DevKitM-1 from the FreeBSD
`esp32freebsd` Bastille jail. The source checkout is `/opt/nuttx-work/nuttx`, apps are
`/opt/nuttx-work/apps`, and deliverables are in `/root/nuttx`.

## How NuttX differs from a Unix distribution

NuttX is a real-time operating system and shell environment, not a desktop or server
Linux distribution. There is no package manager and normally no `/bin`, `/usr/bin`, or
shared userland to install after boot. Applications and NSH commands such as `ls`,
`grep`, `reboot`, Dropbear, and thttpd are selected at build time and linked into the
firmware image. Adding a command therefore means enabling or adding its application in
the source tree and rebuilding/flashing the image.

The `/data` filesystem is persistent storage for runtime state and files; it does not
contain the firmware's executables. Configuration such as WiFi credentials, SSH accounts
and keys, and web content belongs there. Most other filesystem paths are supplied by
NuttX's in-memory pseudo-filesystems and disappear on reboot unless explicitly stored
under `/data`.

## Host and jail

Start the jail on the FreeBSD host:

```sh
doas bastille start esp32freebsd
doas jexec esp32freebsd /bin/sh
```

The board's native USB Serial/JTAG device is normally `/dev/cuaU0` (`ugen0.3`). A CH340
adapter may appear as `/dev/cuaU1`; it is UART0 and is not the console for this image.

## Install build tools (inside the jail)

```sh
pkg install -y git gmake bash gperf gsed gawk wget unzip flock \
  python312 py312-pip py312-esptool
mkdir -p /opt/nuttx-work
cd /opt/nuttx-work
python3.12 -m venv --system-site-packages venv
. /opt/nuttx-work/venv/bin/activate
python -m pip install kconfiglib
export PATH="/usr/local/riscv32-esp-elf-idf60/bin:$PATH"
riscv32-esp-elf-gcc --version
```

`flock` is needed by the apps archive step. The packaged compiler is
`/usr/local/riscv32-esp-elf-idf60/bin/riscv32-esp-elf-gcc`.

For a new checkout:

```sh
cd /opt/nuttx-work
git clone --depth 1 --branch nuttx-13.0.1 https://github.com/apache/nuttx.git nuttx
git clone --depth 1 --branch nuttx-13.0.1 https://github.com/apache/nuttx-apps.git apps
```

## Configure and build

Use the WiFi board configuration, then reapply the project settings whenever
`configure.sh` is run because it resets `.config`:

```sh
cd /opt/nuttx-work/nuttx
bash tools/configure.sh -B esp32c3-devkit:wifi
```

Set these options in `.config` (or with menuconfig), then normalize it:

```text
CONFIG_ESPRESSIF_USBSERIAL=y
# CONFIG_UART0_SERIAL_CONSOLE is not set
CONFIG_NET_ROUTE=y
CONFIG_NETINIT_DHCPC=y
CONFIG_NETUTILS_DROPBEAR=y
CONFIG_NSH_DROPBEAR=y
CONFIG_NETUTILS_THTTPD=y
CONFIG_THTTPD_PATH="/data/var/www"
CONFIG_ESPRESSIF_SPIFLASH_LITTLEFS=y
CONFIG_ESPRESSIF_SPIFLASH_SPIFFS=n
CONFIG_ESPRESSIF_STORAGE_MTD_OFFSET=0x380000
CONFIG_ESPRESSIF_STORAGE_MTD_SIZE=0x80000
CONFIG_BOARDCTL_RESET=y
CONFIG_RAMLOG=y
CONFIG_RAMLOG_SYSLOG=y
CONFIG_RAMLOG_BUFSIZE=8192
CONFIG_SYSLOG_MAX_CHANNELS=2
CONFIG_SYSLOG_DEVPATH="/dev/kmsg"
CONFIG_SYSTEM_GREP=y
```

The image also uses Dropbear on TCP port 22, thttpd on TCP port 80, and the persistent
LittleFS mount `/data`. Keep the local Dropbear, thttpd, and grep source changes in the
apps tree; they are part of this workspace's working tree even though the upstream
checkout's status may not show generated/config files.

After a fresh HAL clone, apply the C23 fix in
`arch/risc-v/src/esp32c3/esp-hal-3rdparty/components/esp_hw_support/esp_gpio_reserve.c`:
replace `ATOMIC_VAR_INIT(~(SOC_GPIO_VALID_GPIO_MASK))` with
`~(SOC_GPIO_VALID_GPIO_MASK)`.

Build incrementally (there is no routine clean step):

```sh
gmake olddefconfig CROSSDEV=riscv32-esp-elf-
gmake -j10 CROSSDEV=riscv32-esp-elf- > ../build-cli.log 2>&1
tail -40 ../build-cli.log
cp nuttx.bin /root/nuttx/nuttx-microunix-ssh22-web-2.5mb-scpfix-tar-r1.bin
sha256 /root/nuttx/nuttx-microunix-ssh22-web-2.5mb-scpfix-tar-r1.bin
```

`nuttx` is the ELF; `nuttx.bin` is the flash image. Simple Boot uses flash offset `0x0`.
The `kconfig-tweak` warning from `configure.sh` is harmless on this FreeBSD setup.

## Back up and flash

Close `console.sh` before using the serial port. From `/root/nuttx` inside the jail:

```sh
./flash-esp.sh nuttx-microunix-ssh22-web-2.5mb-scpfix-tar-r1.bin
```

The helper requires the image, selects the only connected Espressif USB device, backs up
all 4 MiB, writes the image at `0x0`, verifies it, and records the backup in
`.last_backup_dir`. If more than one Espressif device is present, pass its device as the
second argument. The manual equivalent is:

```sh
esptool --chip esp32c3 --port /dev/cuaU0 --baud 115200 flash-id
esptool --chip esp32c3 --port /dev/cuaU0 --baud 115200 \
  write-flash 0x0 nuttx-microunix-ssh22-web-2.5mb-scpfix-tar-r1.bin
esptool --chip esp32c3 --port /dev/cuaU0 --baud 115200 verify-flash 0x0 \
  nuttx-microunix-ssh22-web-2.5mb-scpfix-tar-r1.bin
```

To erase `/data` and initialize the 2.5 MiB partition at `0x180000..0x3fffff`:

```sh
esptool --chip esp32c3 --port /dev/cuaU0 erase-region 0x180000 0x280000
```

This erases saved WiFi credentials, SSH accounts and keys, and web files.

## USB console and recovery

Run from `/root/nuttx`:

```sh
./console.sh                 # Ctrl-] quits the console
minicom -o -D /dev/cuaU0 -b 115200
cu -l /dev/cuaU0 -s 115200
```

For `cu`, type `~.` (tilde then period) or `~Ctrl-D` at the start of a new line
to disconnect; these local escape sequences do not send `exit` to NSH. `console.sh`
releases DTR and pulses RTS so opening it does not leave the ESP32 in ROM download mode. If the board is stuck at `waiting for download`, run
`esptool --chip esp32c3 --port /dev/cuaU0 run` or reflash. `reboot` is the NSH reboot
command; it is now enabled. If a console `exit` closes the shell, reconnect and use
`reboot` (or press RESET).

The image includes `grep [-n] PATTERN [FILE...]`, and `dmesg` backed by an 8 KiB volatile
RAM log at `/dev/kmsg`. The RAM log is lost on reboot. `dmesg` reports “No such file” if
an older image without the RAMLOG configuration is running.

## First boot and persistent setup

The LittleFS region is mounted at `/data`. It is separate from the application image and
normally survives flashing at `0x0`.

### WiFi and DHCP

If `/data/wapi.conf` already exists, `netinit` automatically brings up `wlan0`, associates,
and runs DHCP at boot. For a fresh filesystem, use the console:

```text
wapi psk wlan0 YOUR_WIFI_PASSWORD 3
wapi essid wlan0 YOUR_WIFI_SSID 1
renew wlan0
ifconfig wlan0
wapi save_config wlan0
reboot
```

`CONFIG_NET_ROUTE=y` is required for the DHCP default route. Verify the address with
`ifconfig wlan0`; it may change after reboot.

### Dropbear SSH

Create the persistent directories and an account once on a fresh filesystem:

```text
mkdir -p /data/etc/dropbear
useradd USERNAME PASSWORD
reboot
```

Dropbear then generates its host key under `/data/etc/dropbear` and listens on port 22.
Connect from the jail with `ssh USERNAME@BOARD_IP`. If `/data/etc/passwd` is missing,
repeat the account setup. A known NuttX Dropbear limitation is that remote NSH commands
can print correct output while the SSH client exits 255 because no command exit status is
returned. If starting `dropbear &` causes a Store/AMO access fault in `mm_delayfree`, do
not repeatedly relaunch it; check the directories/account, reboot, and capture the fault
if it recurs.

### Dropbear SCP memory setting

The SCP receiver is enabled with `CONFIG_NETUTILS_DROPBEAR_SCP=y`; use legacy SCP
protocol from a modern OpenSSH client: `scp -O FILE USER@BOARD_IP:/data/var/www/`.

An SCP session originally exhausted RAM. It could report
`xmalloc: out of memory (allocating 4096 bytes)`, reset the connection after a `C0644`
file header, or appear to fail at a different file on another board. This was not a board
hardware fault. The shared ESP32-C3 heap holds task stacks, Dropbear's SSH buffers,
the SCP task, WiFi, thttpd, LittleFS state, and application allocations.

The build makes all of these changes:

```text
CONFIG_NETUTILS_DROPBEAR_SCP_STACKSIZE=16384
apps/netutils/dropbear/port/localoptions.h:
  DEFAULT_RECV_WINDOW=4096
  TRANS_MAX_PAYLOAD_LEN=4096
```

The old SCP task stack reservation was 32 KiB. Reducing it to 16 KiB returns 16 KiB to
the shared heap. The Dropbear channel receive window was 24 KiB and its transmit payload
buffer was 16 KiB; limiting each to 4 KiB removes a further large per-session allocation.
Leave `RECV_MAX_PAYLOAD_LEN` at its interoperable 32 KiB default. Dropbear's NuttX log
function now writes to RAM syslog, so `dmesg` can identify allocation failures without
blocking the USB console.

After changing `localoptions.h`, clean and rebuild the apps tree: the ordinary incremental
build can retain stale Dropbear objects that do not track this generated-header dependency.

```sh
gmake -C /opt/nuttx-work/apps TOPDIR=/opt/nuttx-work/nuttx \
  APPDIR=/opt/nuttx-work/apps CROSSDEV=riscv32-esp-elf- clean
gmake -C /opt/nuttx-work/nuttx -j10 CROSSDEV=riscv32-esp-elf-
```

The fixed `nuttx-scpfix-test2.bin` was flashed to both boards. A recursive transfer to
board 2 passed the earlier large-file failure point and ended only when LittleFS returned
`No space left on device`; `dmesg` showed the normal SSH disconnect rather than
`m_realloc failed` or a reset. The tested `public/` tree has 110 files totaling
1,878,748 bytes, which does not fit a 2 MiB LittleFS volume after filesystem and directory
overhead. Increase `/data` or deploy a smaller site before expecting the complete tree to fit.

### Web server

thttpd starts at boot on port 80 and serves `/data/var/www`. Create the persistent index:

```text
mkdir -p /data/var/www
echo 'hello from ESP32-C3' > /data/var/www/index.html
```

Test from a host with `curl http://BOARD_IP/`.

## `/data` size

The SmartFS build uses a 2.5 MiB partition occupying `0x180000..0x3fffff` on the 4 MiB flash:

```text
CONFIG_ESPRESSIF_STORAGE_MTD_OFFSET=0x180000
CONFIG_ESPRESSIF_STORAGE_MTD_SIZE=0x280000
CONFIG_ESPRESSIF_SPIFLASH_SMARTFS=y
CONFIG_ESPRESSIF_SPIFLASH_FS_MOUNT_PT="/data"
CONFIG_FSUTILS_MKSMARTFS=y
```

The authoritative editable values are in `/opt/nuttx-work/nuttx/.config`; the build generates
`include/nuttx/config.h` from them. During boot,
`boards/risc-v/esp32c3/common/src/esp_board_spiflash.c` creates the MTD partition,
initializes SmartFS, and mounts it at `/data`. The mount-point setting comes from
`boards/risc-v/esp32c3/common/Kconfig`.

`CONFIG_ESPRESSIF_SPIFLASH_MTD_BLKSIZE=64` is the MTD driver's 64-byte read/write block
size in this firmware. Despite the older Kconfig help text calling it “kB”, the ESP32-C3
driver assigns the value directly to `MTD_BLK_SIZE`; it is 64 bytes, not 64 KiB.
SmartFS uses this as its logical sector size, while the physical flash erase sector remains
4 KiB. SmartFS supports nested directories and avoids LittleFS's 4 KiB minimum allocation
block for every non-inline file. SPIFFS is not a replacement because it has a flat namespace
and does not implement real directories.

Formatting erases the partition. After flashing the SmartFS image, erase the region:

```sh
esptool --chip esp32c3 --port /dev/cuaU0 erase-region 0x180000 0x280000
```

At NSH, create the SmartFS format and reboot:

```text
mksmartfs /dev/smart0
reboot
```

`df -h` should then report approximately `2.5M` for `/data`. A `2M` result means the
board is still running an earlier image with the old `0x200000` offset and size.
Changing the offset or size changes the SmartFS geometry; back up or recreate `/data`
(WiFi credentials, passwd, host key, and web files) after changing it.

## Useful source and logs

- Source: `/opt/nuttx-work/nuttx`, `/opt/nuttx-work/apps`
- Virtual environment: `/opt/nuttx-work/venv`
- Build logs: `/opt/nuttx-work/build-cli.log` and `/opt/nuttx-work/build-wifi.log`
- Flash backup: path recorded by `/root/nuttx/.last_backup_dir`
- Deliverables and scripts: `/root/nuttx`

## Transfer a directory as a tar archive

The `nuttx-microunix-ssh22-web-2mb-scp16-tar.bin` build adds a small `tar`
extractor. It supports uncompressed USTAR archives, regular files and directories,
listing (`-tf`), extraction (`-xf`), stdin (`-`), and destination selection (`-C`).
It does not create archives, decompress gzip, restore ownership/modes/timestamps,
or extract links/PAX/GNU extended headers. Existing regular files are overwritten.
A failed extraction can leave partial files.

On the host, create a compatible archive and upload it:

```sh
tar --format=ustar -cf site.tar -C public .
scp -O site.tar USERNAME@BOARD_IP:/data/site.tar
```

After SCP finishes, extract from the USB console to reduce simultaneous RAM use:

```text
tar -tf /data/site.tar
tar -xf /data/site.tar -C /data/var/www
rm /data/site.tar
```

The destination directory must exist. Keep room in `/data` for both the archive
and the extracted files. Alternatively, stdin support permits streaming:

```sh
tar --format=ustar -cf - -C public . |
  ssh USERNAME@BOARD_IP 'tar -xf - -C /data/var/www'
```

Streaming needs SSH and extraction memory simultaneously. The extractor's host
tests pass; this firmware and SSH streaming still require testing on the board.
The utility uses a 512-byte transfer buffer and an 8 KiB task stack. Reducing
the flash `/data` partition does not provide comparable RAM savings.
