Building a Deterministic Deadline Watchdog & Jitter Observatory on QNX 8.0
Learn how to build TickWarden from scratch using native QNX Neutrino microkernel primitives:
a resource manager at /dev/tickwarden, zero-copy synchronous _IO_MSG heartbeats with priority inheritance,
TIMER_PRECISE control-loop releases, kernel-authorized safe-state pulses via MsgRegisterEvent / MsgDeliverEvent,
and instantaneous crash detection via io_close_ocb() — with zero heartbeat polling delay.
Prerequisites & QNX SDP 8.0 Toolchain Setup
Everything in this codelab runs on the free QNX Everywhere non-commercial license using a local QEMU x86_64 target — no physical board is required (the exact same Makefile also cross-compiles for Raspberry Pi 5 via make ARCH=aarch64le).
Verified Host & Target Matrix
- QNX Version: QNX Software Development Platform (SDP) 8.0 installed via QNX Software Center (
~/qnx800/qnxsdp-env.sh). - Toolchain:
qcc -Vgcc_ntox86_64(GCC 12) for QEMU x86_64, orqcc -Vgcc_ntoaarch64lefor ARM64 targets. - Target Image Builder:
mkqnximage0.6 bundled with SDP 8.0. - Host Environment: Ubuntu 24.04 on WSL2 (Windows 11) or native Linux with
qemu-system-x86_648.2 (KVM optional; automatic fallback to TCG) and Python 3.8+ (stdlib only) for the host dashboard.
# 1. Source your QNX SDP 8.0 environment
source ~/qnx800/qnxsdp-env.sh
# 2. Verify compiler, image builder, and QEMU
qcc -V
which mkqnximage qemu-system-x86_64
test -w /dev/kvm && echo "KVM acceleration available" || echo "Falling back to TCG"
# 3. Clone TickWarden (MIT licensed, verified at commit 607830b)
git clone https://github.com/quietstack-labs/tickwarden.git
cd tickwarden
SIGALRM loop only tells you whether a process is alive after a coarse timeout (hundreds of milliseconds). On QNX 8.0, a control loop can remain alive while silently missing its 800 µs deadline due to a misconfigured higher-priority thread. By using QNX's microkernel IPC and resource manager lifecycle directly, TickWarden tracks cycle-by-cycle jitter, pushes a safe-state pulse on the exact cycle a deadline breaks, and learns of crashes directly from procnto.
Designing a Native QNX Resource Manager (/dev/tickwarden)
In QNX, user-space servers expose POSIX pathnames through the resource manager framework (resmgr_attach + iofunc_*). TickWarden attaches a character device at /dev/tickwarden where one open() file descriptor equals one supervised periodic task. That single design decision unlocks three microkernel superpowers at once:
- Zero-dependency observability:
cat /dev/tickwardentriggersio_read()and returns a live JSON snapshot of every supervised task and its 16-bucket latency histogram. - Per-connection ownership: Each client gets an Open Control Block (
iofunc_ocb_t *ocb) mapped 1-to-1 to a watchdog slot ing_slot[TW_MAX_TASKS]. - Automatic priority inheritance: When a priority-63 controller calls
MsgSend()intotickwardend, the kernel temporarily boosts the server thread to match the caller's priority — eliminating priority inversion inside the watchdog itself.
In src/tickwardend.c, server bootstrap takes fewer than 40 lines. Notice how we bind four callbacks (read, msg, devctl, close_ocb), attach an internal 500 µs timer pulse straight into the same dispatch_t loop, and elevate the server thread to SCHED_FIFO:
dispatch_t *dpp = dispatch_create();
if (!dpp) { perror("dispatch_create"); return 1; }
iofunc_func_init(_RESMGR_CONNECT_NFUNCS, &g_connect_funcs,
_RESMGR_IO_NFUNCS, &g_io_funcs);
g_io_funcs.read = io_read;
g_io_funcs.msg = io_msg;
g_io_funcs.devctl = io_devctl;
g_io_funcs.close_ocb = io_close_ocb;
iofunc_attr_init(&g_attr, S_IFCHR | 0666, NULL, NULL);
resmgr_attr_t rattr;
memset(&rattr, 0, sizeof rattr);
rattr.nparts_max = 1;
rattr.msg_max_size = sizeof(tw_stats_reply_t) + 64;
if (resmgr_attach(dpp, &rattr, TW_DEVICE, _FTYPE_ANY, 0,
&g_connect_funcs, &g_io_funcs, &g_attr) == -1) {
perror("resmgr_attach " TW_DEVICE);
return 1;
}
/* Periodic 500 us watchdog scan pulse into our own dispatch loop. */
int code = pulse_attach(dpp, MSG_FLAG_ALLOC_PULSE, 0, on_scan_pulse, NULL);
int coid = message_connect(dpp, MSG_FLAG_SIDE_CHANNEL);
struct sigevent ev;
SIGEV_PULSE_INIT(&ev, coid, scan_prio, code, 0);
timer_t tid;
timer_create(CLOCK_MONOTONIC, &ev, &tid);
struct itimerspec its = {
.it_value = { 0, scan_us * 1000 },
.it_interval = { 0, scan_us * 1000 },
};
timer_settime(tid, 0, &its, NULL);
struct sched_param sp = { .sched_priority = scan_prio };
pthread_setschedparam(pthread_self(), SCHED_FIFO, &sp);
dispatch_context_t *ctp = dispatch_context_alloc(dpp);
for (;;) {
if ((ctp = dispatch_block(ctp)) == NULL) {
if (errno == EINTR) continue;
break;
}
dispatch_handler(ctp);
}
Synchronous _IO_MSG Wire Protocol & Latency Accounting
Instead of serializing text over pipes or sockets on every 1 kHz control cycle, TickWarden defines fixed-size C structs prefixed with QNX's standard struct _io_msg header (include/tickwarden.h). Every cycle sends one tw_beat_t packet via MsgSend() and receives a 8-byte tw_beat_reply_t via MsgReply().
#define TW_DEVICE "/dev/tickwarden"
#define TW_MGRID (_IOMGR_PRIVATE_BASE + 0x0D1)
#define TW_HIST_BUCKETS 16 /* log2 microsecond buckets: <1us,<2us,<4us ... */
#define TW_PULSE_MISS (_PULSE_CODE_MINAVAIL + 7)
enum tw_op {
TW_OP_REGISTER = 1, /* bind this fd to a periodic task */
TW_OP_BEAT = 2, /* one cycle completed */
TW_OP_STATS = 3, /* fetch binary stats for all tasks */
TW_OP_RESET = 4, /* clear counters (all tasks) */
};
typedef struct {
struct _io_msg hdr;
uint64_t seq;
uint64_t release_ns; /* CLOCK_MONOTONIC when the cycle woke */
uint64_t done_ns; /* CLOCK_MONOTONIC when work finished */
uint64_t nominal_ns; /* scheduled release (0 = auto-anchor) */
} tw_beat_t;
Preventing Drift Accumulation in Release-Latency Accounting
A subtle pitfall in real-time monitors is anchoring every beat against t0 + k * period when the underlying virtualized clock ticks slightly slow: a 0.05% drift would falsely look like unbounded lateness after 10 seconds. In io_msg(), when nominal_ns == 0, TickWarden anchors each cycle to prev_release_ns + period and clamps early wake-ups to 0 lateness. Release latency is then bucketed in O(log₂ µs) with a branch-free bitshift loop:
static unsigned hist_bucket(uint64_t ns)
{
uint64_t us = ns / 1000;
unsigned b = 0;
while (us && b < TW_HIST_BUCKETS - 1) { us >>= 1; b++; }
return b;
}
/* Inside io_msg(), case TW_OP_BEAT: */
uint64_t nominal = b.nominal_ns;
if (nominal == 0)
nominal = t->prev_release_ns ? t->prev_release_ns + per : b.release_ns;
if (b.release_ns < nominal)
nominal = b.release_ns; /* early wake-up: no lateness */
uint64_t lat = b.release_ns > nominal ? b.release_ns - nominal : 0;
uint64_t resp = b.done_ns > nominal ? b.done_ns - nominal : 0;
t->s.beats++;
t->s.resp_last_ns = resp;
if (resp > t->s.resp_max_ns) t->s.resp_max_ns = resp;
if (t->s.beats > 1) {
t->s.jitter_last_ns = lat;
t->s.jitter_sum_ns += lat;
if (lat > t->s.jitter_max_ns) t->s.jitter_max_ns = lat;
t->s.hist[hist_bucket(lat)]++;
}
t->prev_release_ns = b.release_ns;
t->expected_by_ns = nominal + g_overrun_periods * per + t->s.deadline_ns;
if (resp > t->s.deadline_ns) {
t->s.misses++;
t->s.state = TW_STATE_LATE;
notify_miss(t);
} else {
t->s.state = TW_STATE_OK;
}
tw_beat_reply_t rep = { .id = t->s.slot, .state = t->s.state };
MsgReply(ctp->rcvid, EOK, &rep, sizeof rep);
return _RESMGR_NOREPLY;
TIMER_PRECISE Pulse Loops & Secure Safe-State Delivery
QNX 8.0 enforces strict event security: a server cannot arbitrarily inject a pulse into a client's channel unless the client explicitly registers that struct sigevent with the kernel for that specific connection using MsgRegisterEvent(). In src/libtw.c, tw_open() registers TW_PULSE_MISS on the client's private side-channel:
if (chid > 0) {
/* Miss notifications arrive as a pulse on the caller's channel. The
* event is registered with the kernel against this connection so
* the server can only deliver exactly this event back to us. */
c->chid = chid;
c->coid = ConnectAttach(0, 0, chid, _NTO_SIDE_CHANNEL, 0);
if (c->coid == -1) goto fail;
SIGEV_PULSE_INIT(&c->ev, c->coid, priority, TW_PULSE_MISS, 0);
if (MsgRegisterEvent(&c->ev, c->fd) == -1) goto fail;
r.notify = 1;
r.ev = c->ev;
}
Inside the supervised controller (src/ctrl_loop.c), both the periodic release timer (PULSE_TICK, armed with TIMER_PRECISE so QNX does not coalesce the wakeup for power saving) and the watchdog safe-state alarm (TW_PULSE_MISS) converge on a single deterministic MsgReceivePulse() loop:
/* Arm periodic timer without kernel timer coalescing (TIMER_PRECISE) */
if (timer_settime(tid, TIMER_PRECISE, &its, NULL) == -1 &&
timer_settime(tid, 0, &its, NULL) == -1) {
perror("timer_settime");
return 1;
}
while (!g_stop) {
struct _pulse p;
if (MsgReceivePulse(chid, &p, sizeof p, NULL) == -1) {
if (errno == EINTR) continue;
break;
}
if (p.code == TW_PULSE_MISS) {
misses_seen++;
safe = 1; /* force actuator output to 0.0 on next control step */
continue;
}
if (p.code != PULSE_TICK) continue;
uint64_t release = tw_now_ns();
setpoint = sin((double)cycles * dt * 0.5);
double u = safe ? 0.0 : pid_step(&pid, setpoint - pos, dt);
vel += (u - 0.8 * vel) * dt;
pos += vel * dt;
if (work_us > 0)
spin_until(release + (uint64_t)work_us * 1000);
uint64_t done = tw_now_ns();
tw_beat_reply_t r;
if (tw_beat(&tw, 0, release, done, &r) == TW_STATE_OK && safe)
safe = 0; /* back on time: resume normal control */
cycles++;
}
TIMER_PRECISE matters on QNX 8.0: Modern QNX kernels apply default timer tolerance (coalescing) to save power on battery/automotive SoCs. Passing TIMER_PRECISE to timer_settime() tells the microkernel that this control loop's wakeup must not be grouped with nearby timers.
Zero-Timeout Crash Detection via Kernel io_close_ocb()
Traditional watchdogs cannot distinguish between a stalled thread and a dead process until a multi-period timeout expires. On QNX, when a supervised process segfaults (SIGSEGV) or is killed with slay -f, the process manager (procnto) immediately closes every open connection owned by that PID and delivers an _IO_CLOSE message to tickwardend, triggering io_close_ocb() within microseconds.
To distinguish an intentional graceful shutdown from a crash, tw_close() issues a private devctl() (TW_DCMD_CLEAN_CLOSE) before calling close(). If io_close_ocb() runs without that handshake, TickWarden marks the slot TW_STATE_DEAD immediately:
static int io_close_ocb(resmgr_context_t *ctp, void *reserved, iofunc_ocb_t *ocb)
{
tw_slot_t *t = slot_for_ocb(ocb);
if (t) {
int clean = (t->s.state == TW_STATE_DONE);
t->s.state = clean ? TW_STATE_DONE : TW_STATE_DEAD;
t->s.died_ns = tw_now_ns();
t->ocb = NULL;
t->rcvid = 0;
if (g_verbose || !clean)
printf("tickwardend: %s %s pid=%d after %llu beats\n",
clean ? "-" : "!! DEAD", t->s.name, t->s.pid,
(unsigned long long)t->s.beats);
fflush(stdout);
}
return iofunc_close_ocb_default(ctp, reserved, ocb);
}
/* 500 us timer pulse inside tickwardend catches starved/hung tasks */
static int on_scan_pulse(message_context_t *ctp, int code, unsigned flags, void *handle)
{
(void)ctp; (void)code; (void)flags; (void)handle;
uint64_t now = tw_now_ns();
for (int i = 0; i < TW_MAX_TASKS; i++) {
tw_slot_t *t = &g_slot[i];
if (t->ocb == NULL || (t->s.state != TW_STATE_OK && t->s.state != TW_STATE_LATE))
continue;
if (now > t->expected_by_ns) {
t->s.overruns++;
t->s.state = TW_STATE_LATE;
t->expected_by_ns = now + t->s.period_ns;
notify_miss(t);
}
}
return 0;
}
Compiling, Packaging with mkqnximage & Booting QEMU
Now compile all five QNX binaries (tickwardend, ctrl_loop, cpu_hog, twtop, twbridge), inject them into a bootable QNX 8.0 QEMU image via mkqnximage snippets, and auto-start the watchdog at boot using QNX's waitfor /dev/tickwarden 5 synchronization primitive.
# Appended to the mkqnximage post-startup script (local/snippets/post_start.custom)
echo "Starting TickWarden watchdog"
tickwardend -p 200 -v &
waitfor /dev/tickwarden 5
twbridge -P 7777 -i 100 &
# 1. Cross-compile all 5 QNX 8.0 x86_64 binaries -> build/x86_64/
# (For Raspberry Pi 5 / ARM64, run: make ARCH=aarch64le)
source ~/qnx800/qnxsdp-env.sh
make
# 2. Generate the QNX 8.0 QEMU image in ~/tickwarden-vm
target/build-image.sh
# 3. Boot QEMU x86_64 (4 vCPUs, 1G RAM, TCP 7777 forwarded to host)
target/run-qemu.sh --console
Once the QNX 8.0 shell prompt (#) appears, inspect the device directly with cat /dev/tickwarden, start the optional Python host dashboard in a second terminal, and run the scripted 4-stage benchmark:
# On the QNX 8.0 target console:
cat /dev/tickwarden # verifies /dev/tickwarden resource manager JSON
STAGE_S=12 twdemo # runs all 4 stages (~55 seconds total)
# In a second host terminal (Python 3.8+, stdlib only):
python3 host/dashboard.py --target 127.0.0.1:7777
# Open http://127.0.0.1:8080 in your browser
Captured QNX 8.0 Micro-Benchmarks & Interactive Histogram Explorer
Below is the exact, unedited telemetry captured from STAGE_S=12 twdemo on QNX 8.0.0 (x86pc, QEMU 8.2 KVM, 4 vCPUs, 1 GB RAM, recorded verbatim in docs/twdemo-output.txt). Select each stage to inspect the live task table, 16-bucket log2 release-latency histogram, and computed P50/P95/P99 bounds.
Live Host Dashboard Captures (Calm vs. Priority-70 Interference)
joint_ctrl (prio 63) and infusion_pump (prio 50) stay green with tight <64 µs release-latency distributions.
Interactive QNX SCHED_FIFO Deadline & WCRT Lab
Before deploying a control loop to QNX 8.0, verify its Worst-Case Response Time (WCRT) under fixed-priority preemptive scheduling (Rk+1 = Ci + ⌈Rk / Thog⌉ · Chog) including TickWarden's ~12 µs MsgSend IPC budget. Load any twdemo preset or tune your own parameters to generate the exact QNX 8.0 reproduction commands.
Common QNX 8.0 Troubleshooting Checkpoints
| Symptom | Root Cause on QNX 8.0 | Fix |
|---|---|---|
tw_open /dev/tickwarden: No such file |
Client started before tickwardend attached its pathname. |
Add waitfor /dev/tickwarden 5 in post_start.custom or start tickwardend -p 200 -v & first. |
warning: could not set SCHED_FIFO |
Unprivileged user lacks PROCMGR_AID_PRIORITY ability. |
Run as root on the QEMU target or grant the ability via procmgr_ability(). |
| Coarse 1 ms timer quantization | Default QNX tick period is 1 ms; TIMER_PRECISE still aligns to clock resolution unless adjusted. |
Pass -c 100 to tickwardend to call ClockPeriod(CLOCK_MONOTONIC, 100us). |
Interleaved console output during twdemo |
tickwardend -v and twtop -1 share the serial TTY asynchronously. |
Normal on serial console; read structured JSON via cat /dev/tickwarden or host/dashboard.py. |