Skip to content
Academia.
ELEmbedded LinuxT550077101 · Fall 2026
CourseFall 2026

Friday · 12:00–16:00 · Odense U174

Implementation, Debugging, and Deployment

Lecture 11: This module focuses on turning embedded Linux prototypes into field-ready systems through disciplined implementation, evidence-led debugging, and controlled deployment. Students learn to validate configuration, handle errors, use structured logging and health indicators, diagnose failures across hardware, kernel, process, storage, network, protocol, and application layers, and distinguish symptoms from root causes. The module also covers reproducible release artifacts, staged deployment, health checks, rollback procedures, resource constraints, performance measurement, and recovery verification.

Learning objectives

✓After completing this module, students should be able to:
✓• implement project components with explicit error handling, structured logging, configuration validation, and health reporting;
✓• debug embedded Linux systems systematically across hardware, kernel, process, storage, network, protocol, and application layers;
✓• collect evidence using Linux inspection, logging, tracing, network-capture, and profiling tools;
✓• distinguish symptoms, hypotheses, experiments, root causes, contributing factors, and corrective actions;
✓• build identifiable and reproducible release artifacts from controlled inputs;
✓• deploy through staged procedures with smoke tests, health observation, rollback triggers, and compatible data migration;
✓• diagnose memory, CPU, storage I/O, network, energy, and thermal constraints;
✓• measure latency distributions, throughput, loss, resource use, and long-duration stability;
✓• verify recovery from process, dependency, network, sensor, storage, configuration, and power failures; and
✓• present an attributable debugging and release narrative suitable for the final portfolio and a technical interview.
Block 112:00–12:50content

Block 1 · 12:00–12:50 · Field-Ready Implementation

EMBEDDED LINUX Fall 2026
CHAPTER 11

Implementation, Debugging, and
Deployment

Learning objectives
After completing this module, students should be able to:
  • implement project components with explicit error handling, structured logging, configuration validation, and health reporting;
  • debug embedded Linux systems systematically across hardware, kernel, process, storage, network, protocol, and application layers;
  • collect evidence using Linux inspection, logging, tracing, network-capture, and profiling tools;
  • distinguish symptoms, hypotheses, experiments, root causes, contributing factors, and corrective actions;
  • build identifiable and reproducible release artifacts from controlled inputs;
  • deploy through staged procedures with smoke tests, health observation, rollback triggers, and compatible data migration;
  • diagnose memory, CPU, storage, I/O, network, energy, and thermal constraints;
  • measure latency distributions, throughput, loss, resource use, and long-duration stability;
  • verify recovery from process, dependency, network, sensor, storage, configuration, and power failures; and
  • present an attributable debugging and release narrative suitable for the final portfolio and a technical interview.
Debugging is controlled uncertainty reduction
Debugging is not trying commands until the symptom disappears. It is the disciplined process of collecting evidence that distinguishes competing explanations. A workaround that hides a symptom is not a root-cause correction unless the failure mechanism is understood and recurrence is prevented.

11.1  Implementation Is More Than Writing the Main Algorithm

An application that works once on a developer’s laptop is not yet an embedded service. A field-ready implementation also needs:

  • validated configuration and explicit defaults;
  • bounded memory, files, queues, retries, and execution time;
  • input validation at every interface;
  • meaningful exit codes and error categories;





EMBEDDED LINUX Fall 2026
  • structured logs, metrics, and health indicators;
  • clean startup, shutdown, and restart behavior;
  • least-privilege device and network access;
  • a defined safe state for physical outputs;
  • version and build identification; and
  • deployment, update, recovery, and rollback procedures.

The non-functional behavior is often what determines whether a prototype survives outside the laboratory.

11.2  Evidence-Led Debugging

Start by writing the symptom in observable language. “MQTT is broken” is vague. “At 14:03:12 UTC, gateway node 07 completed TCP connection to the broker but received an authorization failure when publishing topic eml/v1/node-07/state” is useful.



254.11.2.
Figure 11.1.
Evidence-led debugging: define the symptom, preserve evidence, test a hypothesis, correct the cause, and verify with regression tests. Unresolved or recurring symptoms require another evidence-based iteration.
EMBEDDED LINUX Fall 2026

The practical loop is:

  1. preserve evidence before restarting or changing the system;
  2. reproduce the fault under controlled conditions;
  3. identify the earliest layer at which expected behavior diverges;
  4. list several plausible hypotheses;
  5. predict what observation each hypothesis implies;
  6. run the smallest safe experiment that separates them;
  7. correct the mechanism rather than only the visible symptom;
  8. add a regression test and monitoring; and
  9. remove temporary privileges, debug ports, bypasses, and verbose secret-bearing logs.

11.3  Symptom and Root Cause

A symptom is observed abnormal behavior. A proximate cause directly produces it. A root cause is a correctable underlying condition whose removal prevents recurrence in the relevant scope. A contributing factor increases probability or impact without being sufficient alone.

Example:

  • Symptom: the sensor service restarts every few minutes.
  • Proximate cause: the kernel terminal after memory exhaustion.
  • Root cause: an unbounded queue retains measurements during broker outage.
  • Contributing factors: no resource limit, no queue metric, and a restart policy without backoff.
  • Corrective action: bound the queue, define discard/persistence policy, expose depth, add an outage test, and rate-limit restart.

“Human error” is rarely a sufficient root cause. Ask why the interface, review, test, permission, or procedure allowed one mistake to create the failure.

11.4  Make the Failure Reproducible

Record at least:

  • hardware revision, wiring, power source, and connected peripherals;
  • operating-system, kernel, firmware, application, and configuration versions;
  • exact command, input, workload, and sequence of preceding events;
  • time and time-synchronization state;
  • network topology, addresses, radio settings, and signal metadata;
  • expected and actual behavior;
  • occurrence rate and whether restart changes it; and
  • logs, metrics, captures, core dumps, or photographs required to preserve the state.

Intermittent faults often correlate with temperature, vibration, load, power, network quality, buffer size, or elapsed time. Maintain a table of occurrences rather than relying on memory.

11.5  Debug from the Physical Layer Upward

For embedded systems, begin with the lowest credible layer:

EMBEDDED LINUX Fall 2026
Layer Questions Evidence and tools
Physical/power Correct voltage, polarity, ground, current, connectors, antenna, thermal state? Multimeter, oscilloscope, supply log, visual inspection, thermal measurement
Kernel/device Was hardware enumerated and bound to the expected driver? dmesg, lsusb, lspci, lsblk, /sys, /dev
Permission Which identity owns the process and device? id, ls -l, groups, udev rules, service sandbox settings
Process/service Did it start, exit, hang, or restart? systemctl, journalctl, ps, exit status, coredump
Resource CPU, memory, disk, I/O, temperature, file descriptors? top, free, df, du, vmstat, iostat, lsof
Network Link, address, route, DNS, listener, firewall? ip, ping, dig, ss, tcpdump, curl
Protocol Correct framing, topic, schema, QoS, timing, authentication? Protocol logs, capture, broker log, known-good client, recorded frames
Application Correct state, algorithm, units, calibration, and policy? Structured logs, metrics, debugger, tests, profiler, domain reference

Do not begin by rewriting application code if the input voltage collapses when a motor starts.

11.6  Linux Inspection Commands

Run commands with the least privilege necessary. Capture relevant output with timestamps and explain what each command proves and does not prove.

Listing 11.1. System identity and recent boot evidence
1
2
3
4
5
6
7
8
date --iso-8601=seconds uname -a cat /etc/os-release uptime systemd-analyze systemd-analyze blame | head -20 journalctl --list-boots journalctl -b -p warning dmesg --level=err,warn

dmesg reports kernel messages but may require elevated permission. A driver message proves that the kernel observed an event; it does not prove that the application received valid data.

Listing 11.2. Process and service diagnosis
1
2
3
4
5
6
7
systemctl status eml-acquire.service --no-pager systemctl show eml-acquire.service \ -p ActiveState -p SubState -p Result -p NRestarts journalctl -u eml-acquire.service -b --since "10 minutes ago" ps -eo pid,ppid,user,state,etimes,%cpu,%mem,cmd --sort=-%cpu | head pgrep -a acquire cat /proc/PID/status ls -l /proc/PID/fd | head

A process in active (running) state may be deadlocked or producing stale data. Health must include useful progress.

Block 213:00–13:50content

Block 2 · 13:00–13:50 · Evidence-Led Debugging

EMBEDDED LINUX Fall 2026

11.7  Logs That Support Diagnosis

Useful logs are structured events rather than prose dumps. Include:

  • synchronized timestamp and component identity;
  • severity and stable event name;
  • release/configuration version;
  • device, operation, sequence, or correlation identifier;
  • relevant state and bounded diagnostic context; and
  • outcome and recoverability.
Listing 11.3.  Illustrative structured log event
1 {"timestamp":"2026-10-30T09:17:04.221Z",
2 "severity":"warning",
3 "event":"mqtt_publish_timeout",
4 "service":"eml-gateway",
5 "version":"1.6.0",
6 "device_id":"node-07",
7 "sequence":8142,
8 "attempt":3,
9 "queue_depth":127,
10 "next_retry_ms":8000}

Never log passwords, tokens, private keys, full authorization headers, or unnecessary personal data. Debug logging can change timing and fill storage; enable it deliberately and remove it after investigation.

11.8  systemd and Journal Diagnosis

Listing 11.4.  Focused journal queries
1# Current boot, one service, newest entries first
2journalctl -b -u eml-gateway.service -r -n 100
3 
4# Time interval and warning-or-more-severe events
5journalctl --since "2026-10-30 09:00" \
6 --until "2026-10-30 09:30" -p warning
7 
8# Follow new entries with precise timestamps
9journalctl -u eml-gateway.service -f -o short-iso-precise
10 
11# Previous boot
12journalctl -b -1 -u eml-gateway.service
13 
14# Journal storage use and integrity check
15journalctl --disk-usage
16journalctl --verify

Inspect service configuration with systemctl cat and the combined effective properties with systemctl show. After editing a unit, use systemctl daemon-reload. Restarting without reload may continue using the earlier unit definition. A single -p warning includes warning and every more severe priority, including emergency. Previous-boot queries require retained journal data.[13]

EMBEDDED LINUX Fall 2026

11.9  Tracing System Calls

strace observes system calls and signals. It is useful when a program fails to open a file, connect a socket, access a device, or waits unexpectedly.

Listing 11.5.  Targeted strace examples
1# Run a program and capture file/network/process-related system calls
2strace -f -tt -T -e trace=%file,%network,%process \
3 -o /tmp/acquire.strace /opt/eml/bin/acquire --check
4 
5# Attach briefly to an existing process when permitted
6sudo strace -f -tt -T -p PID -o /tmp/live.strace

Tracing changes timing, can produce sensitive output, and may be prohibited on production systems. Filter the call classes and capture for a bounded period. ENOENT means a path was not found; EACCES indicates permission failure; repeated poll or futex calls may reveal waiting but require context.

11.10  Network Debugging by Layers

Use a consistent sequence:

  1. verify physical link or radio association;
  2. inspect address and link state;
  3. inspect routes and selected path;
  4. test name resolution separately from reachability;
  5. confirm that the expected service is listening;
  6. test transport connection;
  7. test application protocol and authentication; and
  8. inspect return traffic, firewall, and server logs.
Listing 11.6.  Layered network investigation
1ip -brief link
2ip -brief address
3ip route
4ip route get 192.0.2.10
5resolvectl status
6getent hosts broker.example.net
7ss -lntup
8ping -c 4 192.0.2.10
9curl --connect-timeout 3 --max-time 8 -v http://192.0.2.10:8080/health
10sudo tcpdump -ni any host 192.0.2.10 and port 1883

The documentation address 192.0.2.10, example host, service names, and PID tokens must be replaced with values for the test system. resolvectl is relevant only where systemd-resolved is in use. A successful ping does not prove that an application port, TLS handshake, credentials, topic permission, or payload is correct. A failed ping does not prove the host is unavailable because ICMP may be filtered.

Engineering caution
Packet captures can contain credentials, tokens, identifiers, locations, and personal data. Capture only the required interface, hosts, ports, and duration; protect and delete files
EMBEDDED LINUX Fall 2026
according to project policy. Never disable TLS merely to make diagnosis convenient on an exposed network.

11.11  Hardware and Serial Debugging

For UART, I2C, SPI, CAN, GPIO, and USB, verify electrical compatibility before software. Typical causes include wrong voltage, missing common reference, swapped lines, absent pull-ups, incorrect termination, floating pins, inadequate power, long cables, EMI, connector intermittency, and incorrect bus parameters.

Listing 11.7.  Examples of device investigation
1ls -l /dev/ttyUSB* /dev/ttyACM* 2>/dev/null
2udevadm info --query=all --name=/dev/ttyUSB0
3stty -F /dev/ttyUSB0 -a
4i2cdetect -y 1      # only when safe for the attached bus
5lsusb -t
6ip -details link show can0
7dmesg --follow

Bus scanners can disturb certain devices. Never probe an unknown live industrial or safety-relevant bus without understanding the consequences. Use an oscilloscope or logic analyzer to confirm voltage, timing, framing, and noise when software evidence is insufficient.

11.12  Intermittent and Timing Faults

Intermittent bugs often disappear under a debugger. Add lightweight sequence numbers, state transitions, monotonic timestamps, queue depth, and deadline metrics. Compare clocks carefully: wall-clock time can jump during synchronization, while a monotonic clock is better for durations.

Race conditions require stress, repeated execution, and tools appropriate to the language. Do not “fix” a race by adding arbitrary sleep. A sleep may alter probability without establishing synchronization.

11.13  Minimal Reproduction and Binary Search

Reduce the system until the failure disappears, then restore one element. Examples:

  • replace a sensor with recorded input;
  • replace the cloud with a local known-good broker;
  • bypass DNS by testing the resolved address separately;
  • run the process outside a container, then restore constraints;
  • use git bisect to test selected revisions between a known-good and known-bad commit; or
  • compare a known-good hardware node with the failing node while changing one item at a time.

A minimal reproduction should retain the failing mechanism while removing unrelated complexity. Document every removed assumption.

EMBEDDED LINUX Fall 2026

11.14  Reproducible Releases

A release is an identified, tested set of artifacts and metadata intended for deployment. A release is not an unnamed directory copied from a laptop.

Record:

  • semantic or project version and source commit;
  • build time and controlled build environment;
  • target architecture and operating-system baseline;
  • dependency lock files or package manifest;
  • firmware, bootloader, and hardware compatibility;
  • configuration schema and migration requirements;
  • database or stored-data schema;
  • container image digest or artifact checksum;
  • known limitations; and
  • verification results and approval.
Listing 11.8.  Identifying source and release artifacts
1git status --short
2git rev-parse --verify HEAD
3git describe --tags --always --dirty
4git tag -a v1.6.0 -m "EML release candidate 1.6.0"
5sha256sum eml-gateway-1.6.0.tar.gz > eml-gateway-1.6.0.sha256
6sha256sum -c eml-gateway-1.6.0.sha256

A checksum detects accidental or malicious modification only if the expected checksum is obtained through a trustworthy channel. A digital signature additionally authenticates the signer when keys are managed correctly.

11.15  Reproducibility Has Levels

Repeatable: The same team can obtain the result using the same setup.
Reproducible: Another qualified person can rebuild or repeat it from documented inputs.
Hermetic build: The build depends only on declared inputs and controlled tooling rather than
    hidden host state or network downloads.
Deterministic build: Identical declared inputs produce byte-identical outputs, where the
    toolchain supports it.

Containers improve environment control but do not automatically make builds deterministic. Unpinned base images, package mirrors, timestamps, architecture differences, and external downloads remain sources of variation.

Block 314:00–14:50content

Block 3 · 14:00–14:50 · Systematic Fault Isolation

EMBEDDED LINUXFall 2026

11.16  Configuration and Secrets

Validate configuration before starting useful work. Fail with a precise error rather than silently inventing a dangerous default.

Listing 11.9.  Simple configuration validation pattern
1from dataclasses import dataclass
2 
3@dataclass(frozen=True)
4class Config:
5 sample_period_s: float
6 queue_capacity: int
7 broker_host: str
8 
9def validate(c: Config) -> None:
10 if type(c.sample_period_s) not in (int, float):
11 raise ValueError("sample_period_s must be numeric")
12 if not 0.1 <= c.sample_period_s <= 3600:
13 raise ValueError("sample_period_s outside supported range")
14 if type(c.queue_capacity) is not int:
15 raise ValueError("queue_capacity must be an integer")
16 if not 1 <= c.queue_capacity <= 100_000:
17 raise ValueError("queue_capacity outside supported range")
18 if not isinstance(c.broker_host, str) or not c.broker_host.strip():
19 raise ValueError("broker_host is required")

Do not include secrets in container images, Git, command-line arguments, or general environment dumps. Separate public configuration from protected credentials. Document provisioning, rotation, revocation, and recovery without revealing the secret value.

11.17  Release and Deployment Strategies

Strategy Advantage Limitation or use
In-place updateSimple and low storageFailure can leave mixed state; requires strong backup and recovery
A/B imageKnown-good inactive slot supports rollbackNeeds storage, boot selection, compatibility design
Blue/green serviceOld and new versions coexist for switchingRequires duplicated capacity and compatible data interfaces
CanaryNew release reaches a small subset firstNeeds fleet observability and safe cohort selection
Rolling updateLimits simultaneous downtimeMixed versions must interoperate
Immutable imageReduces configuration driftPersistent data and device identity must be externalized carefully

For a student system, a versioned directory plus a stable symbolic link can provide simple atomic switching, provided service state and configuration remain compatible.

Listing 11.10.  Illustrative versioned deployment layout
1# Directory layout (these lines are not shell commands):
2# /opt/eml/releases/1.5.2/
3# /opt/eml/releases/1.6.0/
4# /opt/eml/current -> /opt/eml/releases/1.6.0/
5# /etc/eml/gateway.yaml
6# /var/lib/eml/
7 
8# Inspect, validate, switch, restart, and verify deliberately.
9# Stop on a failed command. Run with exclusive deployment ownership.
EMBEDDED LINUXFall 2026
10set -e
11readlink -f /opt/eml/current
12/opt/eml/releases/1.6.0/bin/gateway --check-config /etc/eml/gateway.yaml
13sudo ln -s /opt/eml/releases/1.6.0 /opt/eml/current.next
14sudo mv -Tf /opt/eml/current.next /opt/eml/current
15sudo systemctl restart eml-gateway.service
16systemctl is-active eml-gateway.service
17curl --fail --max-time 3 http://127.0.0.1:8080/ready

The temporary link must not already exist, the deployment directory must be writable only by the authorized deployer, and concurrent deployments must be excluded. On this GNU/Linux layout, the same-filesystem rename replaces the link atomically; ln -sfn alone does not provide the same guarantee. This changes a pathname, not the running process, database, or configuration as one transaction. If restart or readiness fails, use the recorded prior target and the rollback procedure. The exact procedure must also handle power-loss durability, ownership, partial failure, and authorization.

11.18  Deployment Checklist

Phase Required checks Evidence
PrepareApproved artifact, checksum, compatibility,
change record, owner, maintenance window
Release manifest
ProtectBackup data/configuration, confirm rollback
artifact and access
Restore/rollback test
ValidateConfiguration schema, storage margin, time,
credentials, dependencies
Preflight output
DeployApply controlled steps with captured result and
no secret leakage
Deployment log
Smoke testProcess, readiness, one acquisition, one
communication path, safe outputs
Test record
ObserveErrors, restarts, latency, queues, disk, memory,
temperature
Dashboard/log
snapshot
Accept or roll
back
Compare against explicit trigger and approval
criterion
Decision record

11.19  Smoke Checks and Health Semantics

A smoke test quickly checks the most important release paths. It does not replace full verification. Distinguish:

  • startup: required initialization has completed;
  • liveness: the component is making enough progress that restart is not justified;
  • readiness: it can currently accept useful work;
  • health: richer diagnostic state for operators; and
  • functional result: the actual end-to-end requirement is satisfied.

A web process returning HTTP 200 from /health can still publish incorrect units. Health checks should be cheap, bounded, and unable to amplify dependency outages.

EMBEDDED LINUXFall 2026

11.20  Rollback and Data Migration

Define rollback triggers before deployment: repeated crash, failed readiness, unacceptable latency, lost data, incompatible interface, resource growth, or safety-related anomaly. Rollback should be a rehearsed operation rather than improvisation.

Data migration complicates rollback. If version 2 irreversibly transforms the database, version 1 may no longer read it. Prefer additive, backward-compatible changes:

  1. deploy code that understands old and new forms;
  2. add new schema fields without removing old ones;
  3. migrate data while both versions remain compatible;
  4. stop writing the old form after observation; and
  5. remove obsolete fields only in a later release.

Backups are not proven until restoration is tested. Record recovery-point objective (acceptable data loss) and recovery-time objective (acceptable restoration time) when the project needs them.

11.21  Resource Management

Embedded resources are finite. Observe both current utilization and pressure over time.

Resource Failure symptoms Useful evidence and mitigation
CPUDeadlines missed, load average risesPer-thread CPU, scheduler pressure; reduce work, prioritize, bound rates
MemorySwap/thrashing, OOM terminationRSS, heap profile, kernel log; bound queues, fix leaks, set limits
Storage capacityWrites and databases faildf, journal size, inode use; rotation, quotas, reserved margin
Storage enduranceCorruption or early media failureWrite rate, power events; batching, durable media, controlled shutdown
File descriptorsNew files/sockets faillsof, /proc/PID/limits; close leaks, bound connections
NetworkLoss, latency, reconnect stormsBytes, packets, retransmits, queue depth; backoff, compression, capacity plan
Thermal/powerThrottling, resets, corruptionTemperature, frequency, supply measurement; cooling, power budget
Listing 11.11.  Resource inspection on a Linux target
1uptime
2top -b -n 1 | head -30
3free -h
4vmstat 1 5
5df -hT
6df -ih
7du -xhd1 /var 2>/dev/null | sort -h
8cat /proc/pressure/cpu
9cat /proc/pressure/memory
10cat /proc/pressure/io
11systemctl show eml-gateway.service \
12 -p MemoryCurrent -p MemoryPeak -p CPUUsageNSec -p TasksCurrent
EMBEDDED LINUXFall 2026

Pressure Stall Information reports time during which tasks stall because CPU, memory, or I/O resources are contended. It complements utilization: a CPU can appear busy without harmful delay, while memory or I/O pressure may block critical work.

11.22  Memory Exhaustion and the OOM Killer

When memory cannot be reclaimed, Linux may invoke the out-of-memory mechanism and terminate a selected process. Diagnose with kernel logs rather than assuming an application crash:

Listing 11.12.  Looking for memory exhaustion evidence
1journalctl -k -b | grep -Ei 'out of memory|oom|killed process'
2systemctl show eml-gateway.service -p OOMPolicy -p MemoryMax
3cat /proc/meminfo

Restarting an unbounded process can create a cycle. Bound memory at the design level, configure meaningful service/container limits, expose queue size, and test outage duration beyond expected operation.

11.23  Storage Capacity and Endurance

Storage can be full by bytes or by inodes. Deleted files may continue consuming space while a process holds them open. Investigate with df -h, df -i, du, and lsof +L1. Rotate and retain logs according to an explicit policy.

Flash media also has finite write endurance and is vulnerable to abrupt power interruption. Measure write amplification, batch updates when acceptable, use atomic replacement and suitable filesystems, separate transient from durable data, and choose media appropriate to expected writes and environment.

11.24  Performance Engineering

Begin with a question: “Can the gateway validate and store 50 measurements per second while keeping 95th-percentile end-to-end latency below 500 ms?” Define workload, boundaries, clock, warm-up, duration, hardware, software, and acceptance threshold.

For latencies t1, …, tn with n ≥ 2, the sample mean and sample standard deviation are

t = 1 n n ∑ i=1 t i , s = 1 n−1 n ∑ i=1 (t i −t 2 ) .

The p95 latency is a value at or below which approximately 95% of observations fall under the chosen sample definition. State the percentile method and sample count when precision matters. Tail latency often determines missed deadlines and operator experience.

11.24.1   Coordinated omission

A load generator that waits for each slow response before issuing the next request may fail to measure delays that would have occurred under the intended arrival rate. This is coordinated omission. Generate workload according to the real arrival model and record rejected or unserved requests.

EMBEDDED LINUXFall 2026

11.25  Profiling Before Optimization

Optimization should follow measurement:

  1. define the metric and target;
  2. establish a repeatable baseline;
  3. profile to locate the bottleneck;
  4. change one justified mechanism;
  5. repeat under identical conditions;
  6. evaluate side effects; and
  7. retain the simpler design if improvement is not meaningful.

Useful tools include language profilers, perf, timing instrumentation, flame graphs, database query plans, network capture, and power measurement. Optimize the end-to-end path, not merely a convenient function.

Listing 11.13.  Illustrative CPU profiling workflow
1perf stat -r 5 /opt/eml/bin/decoder --input recorded.bin
2sudo perf record -F 99 -g -- /opt/eml/bin/decoder --input recorded.bin
3sudo perf report

Profiling requires suitable permission and can add overhead. Never expose unrestricted profiling access on an operational system.

11.26  Common Optimization Trade-offs

Optimization Possible benefit Possible cost
BatchingFewer network/storage operationsGreater latency and loss per failed batch
CachingLower computation or network useStale data, memory growth, invalidation complexity
CompressionLower bandwidth/storageCPU, latency, memory, corruption sensitivity
Higher concurrencyBetter throughputRaces, memory, contention, tail latency
Reduced loggingLower storage and CPUWeaker diagnosis and audit evidence
Lower numerical precisionFaster AI inferenceAccuracy degradation or unequal class impact
In-memory queueLow latencyData lost on process or power failure
Persistent queueOutage resilienceStorage writes, latency, schema migration

Every portfolio optimization should report its cost, not only its improvement.


Block 415:00–15:50content

Block 4 · 15:00–15:50 · Debugging Investigation Laboratory

EMBEDDED LINUXFall 2026

11.27  Resilience and Fault-Injection Testing

Test failures systematically:

  • kill, terminate, pause, or deadlock a process safely;
  • restart services in unexpected order;
  • disconnect and restore networking;
  • reject authentication or rotate credentials;
  • disconnect a sensor or send malformed, stale, duplicate, and reordered data;
  • fill a test queue and approach a controlled storage limit;
  • supply missing and invalid configuration;
  • interrupt an update in a safe test environment;
  • reboot and power-cycle the target; and
  • run a long soak test with representative workload.

For each fault, verify detection time, state transition, safe physical behavior, data loss/duplication, diagnostic clarity, automatic recovery, operator action, and recovery time.

11.28  Power-Cycle Testing

A software restart does not reproduce abrupt power loss. Power-cycle testing reveals boot ordering, storage durability, peripheral initialization, clock behavior, retained commands, and safe output state. Use low-risk equipment and a controlled switching method. After power restoration verify:

  • outputs remain safe during boot;
  • file systems and databases are consistent;
  • services wait for actual dependencies rather than arbitrary sleep;
  • time uncertainty is represented until synchronization;
  • queues and sequence identifiers recover correctly; and
  • the device returns to a known operational or diagnosable state.

11.29  Soak and Endurance Testing

A soak test operates the system under representative load for an extended period. Track memory, file descriptors, queue depth, storage, CPU, latency percentiles, temperature, reconnects, errors, and output correctness. Plot values over time; a slow leak may be invisible in a short benchmark.

Include environmental and workload cycles. A 24-hour test at constant room conditions does not establish outdoor seasonal reliability, but it can reveal resource leaks and repeated scheduled failures.

11.30  Incident Narrative and Learning

A useful debugging record contains:

  1. impact and observable symptom;
  2. detection source and timeline;
  3. affected versions and scope;
  4. evidence preserved;
  5. hypotheses and experiments;
  6. root cause and contributing factors;
  7. immediate containment;
  8. permanent corrective action;
  9. regression test and monitoring added; and
  10. remaining uncertainty and follow-up.
EMBEDDED LINUXFall 2026

282.11.1.
Figure 11.2. A controlled release preserves build identity, validation evidence, package integrity, and deployment health criteria. Hashes detect changes relative to a trusted reference; signature verification authenticates the signed artifact under the configured trust policy. Health monitoring determines acceptance or rollback after deployment.


Blameless does not mean accountability-free. It means analyzing system conditions and decisions so recurrence becomes less likely, while clearly assigning corrective actions.

EMBEDDED LINUXFall 2026

11.31  Guided Laboratory

Guided laboratory: release candidate and evidence-led debugging

Part A—controlled release

  1. Select a release candidate and record Git revision, tag, target image, dependency, firmware, hardware, schema, and configuration versions.
  2. Build or package it from a clean checkout and calculate a checksum.
  3. Validate configuration and execute unit, contract, integration, and smoke tests.
  4. Deploy using a written checklist and observe readiness, restarts, queue depth, memory, storage, and temperature.

Part B—fault diagnosis

  1. The instructor or another team introduces one safe fault without revealing it.
  2. Record the symptom, competing hypotheses, predicted observations, commands, and results.
  3. Identify root cause, implement a correction, and add a regression test.
  4. Remove any temporary diagnostic privilege or workaround.

Part C—resilience and performance

  1. Test process crash, target reboot or controlled power cycle, dependency outage, invalid input, and unavailable sensor.
  2. Measure one justified baseline including median, p95, throughput, and relevant resources.
  3. Profile one bottleneck, apply one change, and repeat the identical test.
  4. Report improvement and trade-offs.
  5. Demonstrate rollback to the known-good release and verify data/configuration compatibility.
Portfolio evidence
Include the reproducible failure description, hypothesis table, diagnostic evidence, root-cause narrative, correction and regression test; release manifest and checksum; configuration validation; deployment and smoke-test records; resource and soak results; fault-recovery evidence; baseline and post-change performance distributions; optimization trade-off; rollback procedure and successful rollback evidence; and the student’s attributable contribution.

11.32  Self-Assessment and Job-Interview Questions

These questions assess the course material and prepare students for embedded Linux, robotics, IoT, DevOps, test, and integration interviews.

  1. What distinguishes evidence-led debugging from trial and error?
  2. Distinguish a symptom, proximate cause, root cause, and contributing factor.
  3. Why should evidence be preserved before restarting a failed system?
  4. Why is changing several variables at once poor debugging practice?
  5. A service is active but measurements are stale. What should you inspect?
  6. What do systemctl status and journalctl -u contribute?
EMBEDDED LINUXFall 2026
  1. When is strace useful, and what are its limitations?
  2. Give a layered plan for diagnosing a failed HTTPS or MQTT connection.
  3. Why can arbitrary sleep appear to fix a race condition?
  4. What is a minimal reproduction?
  5. What information uniquely identifies a reproducible release?
  6. Compare a checksum and a digital signature.
  7. Why does a container not guarantee a reproducible build?
  8. Distinguish liveness, readiness, and functional correctness.
  9. What is a smoke test?
  10. Compare in-place, A/B, blue/green, canary, and rolling deployment.
  11. What makes rollback difficult after a data migration?
  12. How would you diagnose Linux OOM termination?
  13. Why must both bytes and inodes be checked for storage exhaustion?
  14. What does Pressure Stall Information add to utilization metrics?
  15. Why is mean latency insufficient?
  16. What is coordinated omission?
  17. Describe a defensible optimization experiment.
  18. Why can batching improve throughput but worsen reliability or latency?
  19. What should a network-outage resilience test measure?
  20. Why is a controlled power cycle different from restarting a service?
  21. What does a soak test reveal?
  22. What makes a debugging narrative strong portfolio evidence?

11.33  Answers and Discussion

  1. Evidence-led debugging states the symptom precisely, forms competing hypotheses, predicts observations, and runs discriminating tests. Trial and error changes things without preserving causal knowledge.
  2. The symptom is observed behavior; the proximate cause directly creates it; the root cause is an underlying correctable condition whose removal prevents recurrence in scope; a contributing factor increases probability or impact.
  3. Restarting destroys volatile state, timing, process information, queues, and sometimes logs. Preserve the evidence required to reconstruct what happened, unless immediate safety requires shutdown.
  4. If the result changes, the responsible variable is unknown and interactions are hidden. Change one relevant factor or use a designed experiment when interactions are the question.
  5. Check source observation timestamps and sequence progress, acquisition health, queues, threads, resource pressure, device input, dependency status, logs, and readiness semantics. Process existence proves little.
  6. systemctl status summarizes current unit state and recent messages; journalctl -u provides filterable service history across a defined boot/time interval. Effective unit properties and kernel logs may also be useful.
  7. strace reveals system calls, errors, signals, file access, sockets, and waits. It adds overhead, changes timing, may expose sensitive data, needs permission, and does not directly explain application-level intent.
  8. Verify link, address, route, DNS, listening endpoint, transport connection, TLS identity/time, protocol response, authentication, authorization, payload/schema, return traffic, and server logs. Each step answers a narrower question.
  9. Sleep changes scheduling probability and may hide a missing synchronization mechanism. It is workload-dependent and does not establish ordering, mutual exclusion, or readiness.
EMBEDDED LINUXFall 2026
  1. A minimal reproduction retains the failing mechanism with the fewest relevant components and explicit steps. It speeds experiments and makes hidden assumptions visible.
  2. Record source commit/tag, dirty state, artifact checksum/digest, build environment, target architecture/OS, dependencies, firmware/hardware compatibility, configuration and data schemas, migrations, and verification result.
  3. A checksum detects different bytes when the expected value is trusted. A digital signature links an artifact to a private signing key and can authenticate origin when key trust and protection are valid.
  4. Base tags can move; packages and downloads change; host kernel/architecture remain external; timestamps and build tools vary; secrets/configuration may be injected. All inputs must be declared and controlled.
  5. Liveness asks whether restart is justified, readiness whether useful work can currently be accepted, and functional correctness whether the required output is actually correct under stated conditions.
  6. A smoke test is a fast post-build or post-deployment check of critical paths. It detects gross release failure but does not replace complete verification.
  7. In-place modifies the active installation; A/B switches between system slots; blue/green keeps complete old/new service environments; canary exposes a small cohort first; rolling replaces instances gradually. Compatibility and rollback needs differ.
  8. Old code may not understand a new schema, and the migration may discard or transform data irreversibly. Use staged backward-compatible migrations and test restoration and rollback.
  9. Inspect kernel/journal messages for OOM and killed-process records, service results, memory/cgroup limits, RSS and trends, swap/pressure, queues, and allocation profiles. Correct leaks or unbounded behavior rather than only raising limits.
  10. A filesystem can have free bytes but no available inodes, preventing new files. Conversely, large files can exhaust capacity while inodes remain. Open deleted files can consume space invisibly to ordinary du.
  11. PSI measures time tasks are stalled by CPU, memory, or I/O contention. It helps distinguish harmless utilization from resource pressure that delays useful work.
  12. The mean hides variability and rare delays. Report sample count, distribution, median, high percentiles, maximum, missed deadlines, workload, and end-to-end measurement boundaries.
  13. Coordinated omission occurs when the measurement workload slows with the system and fails to generate requests that should have arrived during long responses, understating user-visible delay.
  14. Define target and conditions, establish a repeatable baseline, profile the bottleneck, change one mechanism, rerun the same workload, quantify uncertainty and tail behavior, and report costs and regressions.
  15. Batching amortizes overhead but waits for a batch to fill and places more data at risk in one failed operation. It may increase memory and recovery complexity.
  16. Measure detection, queue growth and bounds, local behavior, data accepted/lost/discarded, reconnect backoff, replay time, duplicates/order, service readiness, alerting, and complete recovery.
  17. Service restart retains kernel, device, filesystem, clock, and much system state. Power cycling tests boot ordering, safe outputs, durable storage, peripheral initialization, retained data, and time synchronization.
  18. A soak test reveals slow memory/file-descriptor leaks, queue accumulation, storage growth, thermal throttling, periodic faults, reconnect patterns, and long-tail performance under representative load.
  19. It links a precise symptom and version to preserved evidence, competing hypotheses, discriminating tests, root cause, correction, regression prevention, remaining uncertainty, and the student’s own contribution.
EMBEDDED LINUXFall 2026

11.34  Authoritative References and Verification Links

Tool behavior and platform capabilities evolve. Verify commands and configuration against primary documentation:

  • systemctl manual
  • journalctl manual
  • systemd service-unit documentation
  • strace manual page
  • tcpdump manual
  • Linux kernel control-group v2 documentation
  • Linux Pressure Stall Information documentation
  • Linux perf documentation
  • Docker container resource constraints
  • Dockerfile health-check reference
  • Git tag documentation
  • Git bisect documentation
Chapter summary
Reliable implementation requires bounded behavior, validated configuration, useful observability, safe state, and explicit recovery. Debugging begins with a precise symptom and preserved evidence, then narrows the failing layer through competing hypotheses and discriminating tests. Releases must be identifiable and reproducible; deployments require preflight validation, smoke tests, monitoring, compatible migration, and rehearsed rollback. Embedded resources and thermal behavior must be measured over time, while performance work must target a profiled bottleneck and report tail behavior and trade-offs. Resilience is demonstrated by controlled fault injection, power-cycle, outage, and soak testing. The strongest portfolio evidence is not a perfect screenshot but a traceable narrative showing how a student found, understood, corrected, and prevented a real failure.

Summary

Chapter 11 explains how an embedded Linux project moves from a working prototype to a field-ready implementation. Reliable implementation requires more than a functioning main algorithm: configuration validation, bounded resources, input validation, meaningful errors, structured logs, health indicators, clean lifecycle behavior, least-privilege access, safe physical outputs, version identification, and deployment and rollback procedures are essential. Debugging is presented as controlled uncertainty reduction, where engineers observe and record symptoms, reproduce failures, bound the affected layer, compare competing hypotheses, perform discriminating tests, correct the underlying cause, and verify the correction with regression testing. The module emphasizes evidence-based diagnosis, reproducible releases, staged deployment, recovery, performance measurement, and operational reliability.

Course outline

What we will learn

From Linux foundations to physical interfaces, networking, security and a complete embedded system.

Linux foundationsKernel, users, processes and file systems
Command lineShells, scripting and automation
Embedded hardwareBoot, storage and device drivers
Physical I/OGPIO, sensors and actuators
Device busesUART, I²C and SPI
NetworkingTCP/IP, SSH and remote management
Distributed systemsMessage passing and cooperating nodes
Engineering practiceGit, testing, logging and deployment
SecurityLeast privilege, updates and secrets

Teaching method

Short introductions are followed by laboratory activities. Work is normally completed in teams of three. Each team develops an embedded Linux system; the examination portfolio is individual.

Project ideas

Applications you could build

Each project should begin with one reliable end-to-end function.

Automatic Raspberry Pi-based GPS trackerSample examination report available in PDF format
Environmental monitoring stationValidated sensing, local storage and dashboard
Energy monitoring systemMeasure, log and visualize equipment power use
Greenhouse automationClimate sensing, actuation and remote supervision
Field-robot telemetryLocation, operating state, measurements and faults
LoRaWAN sensor networkField nodes, TTN integration and private cloud
Intelligent irrigationSensing, decisions, valves and safe failure handling
Multi-node IoT gatewayProtocol translation, buffering and secure forwarding
ROS 2 communication systemDistributed nodes, QoS and service integration
Edge-AI monitoring systemLocal inference, measured performance and safe fallback

A complete project should demonstrate

NeedA clear user and purpose
Physical interfaceA sensor, actuator or device
Linux integrationPrograms, scripts or services
CommunicationA justified data-exchange method
ReliabilityLogging and failure handling
EvidenceTests, results and reflection

Contractor and client roles

Project groups

Each group develops a project for one client group and evaluates the project received from another contractor group.

Contractor

Heros

ProjectProject 01
Delivers to
Client not assigned
Receives from
Contractor not assigned

Fridays · four 50-minute slots · Odense

Fall 2026 lecture plan

The SDU timetable remains authoritative for dates, times and rooms.

Project progression

Project ideas and proposals begin in Module 1 and evolve throughout the course. Module 10 is the formal integration, architecture and verification review; Modules 11–12 complete implementation, demonstration and individual portfolio evidence.

Lecture 11 · participation

Student questions

Questions remain hidden until the student is called. Model answers are revealed separately.

Instructor classroom view

The roster, answers, attendance and participation records are available only to the authorized primary owner after sign-in.

Instructor sign in

Definitions

Essential course vocabulary

Plain-language definitions for the technical terms used throughout the course.

TermDefinitionExample
ActuatorA device that produces a physical action.Motor, valve, relay or fan
BootThe sequence that starts the hardware, kernel, services and applications.Starting an embedded computer
CLIA text interface that accepts commands.Windows Terminal or a Linux terminal
CommandAn instruction interpreted by a shell.pwd, ls or Get-Location
Device driverSoftware through which the operating system communicates with hardware.GPIO or camera driver
DirectoryA named container for files and other directories./home/student/eml
DistributionA complete operating system built around the Linux kernel.Ubuntu or Debian
Embedded systemA computer integrated into a larger product for a defined purpose.Greenhouse controller
File systemThe structure used to name, store and retrieve files.ext4
GPIOA configurable digital input or output pin.Reading a switch
I²CA two-signal serial bus for peripherals.Environmental sensor
KernelThe privileged core managing memory, processors, devices and processes.Linux kernel
MQTTA lightweight publish/subscribe messaging protocol.Sending sensor data
ProcessA running instance of a program.A data logger
PWMRapid switching used to control average power or a signal duty cycle.Motor speed
RootThe privileged Linux user or the top directory, depending on context.Administrative access
ScriptA file containing commands that automate work.A backup script
SensorA device that converts a physical quantity into data.Temperature sensor
ServiceA background program providing an ongoing function.SSH server
ShellA program that interprets commands and starts programs.Bash or PowerShell
SPIA synchronous bus commonly used for fast peripherals.Display or converter
SSHEncrypted remote command-line access.Managing a Raspberry Pi
TCP/IPThe principal protocol family used across computer networks.Device-to-server communication
UARTAn asynchronous serial interface.Debug console
User spaceThe environment where ordinary programs run outside the kernel.Application software
Version controlA system that records and manages file changes.Git

Official examination information · EKA T550077102

Individual portfolio examination

Form

Portfolio

Individual presentation portfolio submitted at semester end.

Grade

7-point scale

No second examiner.

Weighting

No split published

No separate written-exam or coursework percentages are stated.

Re-examination

Same form

Same form as the ordinary examination.

Team project and individual assessment

The team project creates practical evidence, but each student is assessed individually through the presentation portfolio. Classroom participation points support engagement and do not form part of the official grade.

Document from the beginning

  • Your own decisions and identifiable contribution
  • Commands, code, configuration and version history
  • Tests, results, failures and improvements
  • Reflection on trade-offs and learning

People and course systems

Contacts and official links