Try Embedded

Linux userspace basics

Root filesystem, flash filesystems, init systems and BusyBox.

What lives above the kernel

Once the kernel mounts the root filesystem and starts init, everything else is user space: the C library, shell utilities, daemons, your application and its configuration. On an embedded device you decide exactly what goes in, which keeps the image small, the attack surface narrow and the boot fast.

The root filesystem layout

Linux systems follow the Filesystem Hierarchy Standard:

DirectoryContents
/bin, /sbin, /usr/bin, /usr/sbinPrograms (often merged into /usr today)
/lib, /usr/libShared libraries, kernel modules (/lib/modules/<version>)
/etcConfiguration
/devDevice nodes (populated by devtmpfs and udev/mdev)
/proc, /sysKernel interfaces: processes, hardware, tunables (virtual filesystems)
/tmp, /runTemporary and runtime files (tmpfs in RAM)
/varVariable data: logs, caches, spool
/home, /rootUser homes (often empty on devices)
/optAdd-on applications

A minimal embedded root filesystem can be a few megabytes: a C library, BusyBox, init scripts and the application.

C libraries

LibrarySizeNotes
glibcLargeFull-featured; desktop distributions; best compatibility
muslSmallClean, standards-focused, static linking friendly; Alpine, OpenWrt
uClibc-ngSmallConfigurable; older embedded systems

BusyBox

BusyBox combines hundreds of common Unix tools (sh, ls, cp, grep, vi, ifconfig, udhcpc, mount, init...) into one small binary. Each tool is a symbolic link to it; BusyBox looks at argv[0] to decide which tool to act as.

$ ls -l /bin/ls /bin/grep
lrwxrwxrwx 1 root root 7 /bin/ls -> busybox
lrwxrwxrwx 1 root root 7 /bin/grep -> busybox
$ busybox --list | wc -l
312
#include <stdio.h>
#include <string.h>

/* The multi-call idea: one program, behaviour chosen by the name it was run as. */
static int cmd_echo(const char *arg) { printf("%s\n", arg); return 0; }
static int cmd_true(const char *arg) { (void)arg; return 0; }
static int cmd_rev(const char *arg)  { for (int i = (int)strlen(arg) - 1; i >= 0; i--) putchar(arg[i]); putchar('\n'); return 0; }

static const struct { const char *name; int (*fn)(const char *); } applets[] = {
  { "echo", cmd_echo }, { "true", cmd_true }, { "rev", cmd_rev },
};

static int run_as(const char *argv0, const char *arg) {
  const char *name = strrchr(argv0, '/') ? strrchr(argv0, '/') + 1 : argv0;   /* basename */
  for (unsigned i = 0; i < sizeof applets / sizeof applets[0]; i++)
    if (strcmp(applets[i].name, name) == 0) return applets[i].fn(arg);
  printf("%s: applet not found\n", name);
  return 127;
}

int main(void) {
  run_as("/bin/echo", "hello from echo");
  run_as("/usr/bin/rev", "busybox");
  run_as("/bin/vim", "");
  return 0;
}

Init systems

PID 1 starts and supervises everything else.

BusyBox initsystemd
Configuration/etc/inittab plus scripts in /etc/init.d/Unit files (.service, .socket, .timer, .mount)
Start orderScript orderDependency graph, in parallel
SupervisionRespawn entries in inittabRestart=on-failure, watchdog integration, resource limits
Loggingsyslog to filesjournald
SizeTinyLarger, more features

A systemd service for an application:

# /etc/systemd/system/sensord.service
[Unit]
Description=Sensor daemon
After=network-online.target
Wants=network-online.target

[Service]
ExecStart=/usr/bin/sensord --config /etc/sensord.conf
Restart=on-failure
RestartSec=2
WatchdogSec=30
User=sensord
ProtectSystem=strict
ReadWritePaths=/var/lib/sensord

[Install]
WantedBy=multi-user.target

WatchdogSec makes systemd restart the service if it stops calling sd_notify("WATCHDOG=1"), and systemd itself can feed the hardware watchdog (RuntimeWatchdogSec in system.conf). The Protect* and User= options sandbox the service cheaply.

Filesystems for flash

Storage on embedded devices is flash, which wears out and must handle sudden power loss.

StorageFilesystem choices
Raw NAND (no controller)UBI + UBIFS: wear levelling, bad-block handling, power-cut safe
Raw NOR (SPI flash)JFFS2 (small), UBIFS, or read-only squashfs
Managed flash: eMMC, SD, UFSext4, F2FS (flash-friendly); the controller handles wear levelling
Read-only system imagesquashfs (compressed, read-only), EROFS
RAMtmpfs for /tmp, /run and volatile logs

A common robust layout:

  • the root filesystem read-only (squashfs or ext4 mounted ro), so it cannot be corrupted at run time and can be verified (dm-verity)
  • a small read-write data partition for configuration and persistent data
  • tmpfs for temporary files, and an overlayfs if parts of /etc must appear writable
  • two root partitions (A/B) for safe updates

Minimise writes: excessive logging to flash is a common cause of devices wearing out in the field. Send logs to RAM with limited persistence, or to the network.

Debugging tools worth having

ToolUse
dmesg, journalctlKernel and service logs
top/htop, ps, free, vmstatCPU and memory
straceSystem calls a process makes: why it fails to open a file, what it is waiting on
ltraceLibrary calls
gdbserver + cross gdbDebug an application from the development PC
perfCPU profiling
valgrind (where it runs), AddressSanitizerMemory errors
tcpdump, ss, ipNetworking
i2cdetect, i2cget, gpioinfo, gpiogetPoke hardware from user space
evtestInput devices

Remote debugging is the norm: build with debug symbols on the PC, run gdbserver :2345 ./app on the target, and connect with gdb-multiarch using the sysroot from the SDK.

Pitfall: Pulling power while an ext4 filesystem is being written can corrupt files, and default ext4 settings plus application code that does not fsync lose recent data. Write configuration atomically: write a temporary file, fsync it, rename over the old one, then fsync the directory.

Interview question: How would you lay out the filesystems on an embedded Linux product to survive power loss and allow updates?

Answer: Keep the root filesystem read-only (squashfs, EROFS or ext4 mounted ro, ideally verified with dm-verity) in two A/B partitions for atomic updates with rollback. Put persistent configuration and data on a separate small read-write partition using a power-cut-safe filesystem (UBIFS on raw NAND, ext4 or F2FS on eMMC), write files atomically with fsync and rename, and keep temporary files and most logs in tmpfs to reduce flash wear. Use overlayfs only where parts of the root must appear writable.

Interview question: A daemon on your device fails to start but works when run by hand. How do you debug it?

Answer: Read its logs with journalctl -u name or the syslog, check the exit status with systemctl status, and compare the environment: systemd services run as a different user, with a minimal PATH, no terminal, a different working directory and sandboxing options such as ProtectSystem that make paths read-only. Run it under strace (ExecStart with strace -f -o) to see which file, permission or socket fails. Check ordering dependencies: it may start before the network, a mount or a device node exists.

Build it: restart a crashed daemon, but not forever

This is step 6, the last of the module project. The smart-home gateway's daemons will crash in the field: a malformed Zigbee frame, a memory leak that takes three weeks to bite. The init system restarts them, with a policy like systemd's Restart=on-failure with StartLimitBurst= and StartLimitIntervalSec=. The gateway's minimal image has no systemd, so its small supervisor process does the same job, and the policy is yours to write.

Lab: The supervisor's restart policy

svc_exited(s, now_s, code, sig) is called when a daemon has exited, with its exit code or, if a signal killed it, the signal number (sig is 0 otherwise). It returns:

  • SVC_STOPPED for a clean stop, which is not restarted: exit code 0, or killed by SIGHUP, SIGINT, SIGTERM or SIGPIPE (the signals used to stop a daemon on purpose).
  • SVC_RESTART for a failure (any other exit code or signal), after recording now_s as a restart.
  • SVC_FAILED when restarting now would make more than BURST restarts within INTERVAL_S seconds: the daemon is crash-looping, and restarting it again only hides the problem and wears the flash with logs. Once failed, it stays failed (every later call returns SVC_FAILED) until svc_reset is called, which is what a technician's "restart service" does.

Keep the times of the last BURST restarts in s->times. A new restart is allowed unless BURST restarts are already recorded and the oldest of them is less than INTERVAL_S seconds before now_s.

Going deeper

Interview question: How would you keep a network video recorder's recording service running for months?

Answer: Run it under systemd with automatic restart and a watchdog, give it its own unprivileged user, log to the journal with rotation so the disk never fills, and monitor resources (memory, file descriptors, disk) with alerts. Make the service resume recording cleanly after a restart, and test by killing it.

Interview question: What is overlayfs and why is it used on embedded systems?

Answer: Overlayfs combines a read-only lower filesystem with a writable upper layer, presenting a merged view: reads come from the upper layer if a file was changed, otherwise from the lower; writes go to the upper. It lets a read-only, verifiable root filesystem appear writable in selected places (such as /etc) while keeping the base image intact, and a factory reset is simply clearing the upper layer.

Interview question: How do you debug an application on an embedded Linux target from a PC?

Answer: Build it with debug symbols using the SDK's cross toolchain, run gdbserver on the target (gdbserver :2345 ./app or attach to a PID), and connect from the PC with the matching cross gdb, pointing it at the SDK sysroot so it finds libraries and symbols. IDEs wrap this. strace, perf and core dumps analysed on the PC complement it.

Explain it: In your own words, explain why many embedded Linux products keep the root filesystem read-only.

Answer: A read-only root cannot be corrupted by a power cut in the middle of a write or by a misbehaving process, so the system always boots into a known state, and it never needs a slow filesystem check. It can be compressed and cryptographically verified to detect tampering, and it makes updates clean: a whole new image is written to the other partition instead of changing files in place. Data that must change, such as configuration and logs, lives on a separate small writable partition or in RAM.