interplane.Get Omega
Read in your language

aienux

Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.

Brought by drakestapleton

branch main Branches Tags History

aienux / scripts / qemu_ck_slot_loader_test.sh

610 lines · 33238 bytes Raw Blame History
1#!/usr/bin/env bash
2# SPDX-License-Identifier: Apache-2.0
3# Copyright 2026 Drake Stapleton (AIEN / aien-dev)
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
17# qemu_ck_slot_loader_test.sh -- QEMU gate for SLOTLDR.EFI, the AIENOS signed
18# A/B image slot loader (native/boot/slot_loader.c; native v1 plan P11 cut 2a,
19# gate N7; docs/NATIVE_IMAGE_SLOTS.md section 7). QEMU is an emulator: a PASS
20# here qualifies nothing physical (hardware NOT_RUN).
21#
22# Setup: the boot disk is a FAT directory (fat:rw:, as scripts/qemu_ck_boot_test.sh)
23# whose EFI/BOOT/BOOTAA64.EFI is SLOTLDR.EFI built with CK_TEST_SLOT_KEY=1
24# (RFC 8032 TEST 1). A second virtio disk holds a GPT with one slots partition
25# (ck_gpt_image layout "slots"); ck_slot_tool slots-image writes the control
26# record and the two slots into it. The slot payloads are the unchanged core
27# image built twice, with AIENOS_COMMIT slotA-<commit> and slotB-<commit>, so
28# the serial line "aienos_commit: slotX-" names the slot that really ran. The
29# core image prints its report and resets (PSCI); with -no-reboot QEMU exits 0.
30# Every row also asks the host tool (ck_slot_tool select, same slot_select.c)
31# for its decision over the same files and requires the loader to agree.
32#
33# Rows (each check prints PASS or FAIL with the serial line it needed):
34# 1 fresh media, control active=A, A valid, B empty: boots A (active).
35# 2 B staged (tries 3): boots 1-3 boot B (candidate_try) with tries 2, 1, 0
36# committed before the jump and read back from the disk by the tool;
37# boot 4 boots A (candidate_exhausted_active) and writes nothing.
38# 3 B manifest flipped in its signed bytes: "signature does not verify", boots A.
39# 4 B signed by RFC 8032 TEST 2 (not trusted): "signer_id names no trusted key", boots A.
40# 5 B image flipped, manifest intact: "image SHA-512 mismatch", boots A.
41# 6 torn control write (the staging record's body half written, no commit
42# header): the previous record is recovered, boots A (active), B not tried.
43# 7 both slots invalid: "recovery_required (A: ...; B: ...)", the loader returns
44# to the firmware, no kernel runs (QEMU is stopped by the row timeout).
45# 8 B validly signed but below the generation floor: refused, boots A.
46# P11 cut 2b (the service kernel promotes / abandons; svc/slot_service.c), one NVMe
47# disk with the Store and slots partitions, "shutdown" sent once the lifecycle is ready:
48# 9 healthy candidate B: the kernel promotes it (active=B, floor 2); next boot
49# is a steady boot of B, nothing written.
50# 10 candidate that never becomes healthy (Store LOCKED): last try spent, not
51# promoted; next boot falls back to A and the kernel abandons B (flags 0x01).
52# 11 negative control: the service image started without SLOTLDR finds no boot
53# record and writes nothing.
54# P11 cut 3 (the inactive-slot updater, operator verb `update`; native/boot/slot_update.c),
55# disk layout aienos-slots-inbox (Store + slots + update inbox):
56# 12 update from active A writes the inbox image into B and stages it; a second
57# update is refused (candidate staged); A's bytes unchanged; next boot tries B
58# and the kernel promotes it.
59# 13 QEMU killed mid-image-write (TEST-only "update halt-after=1"): control and A
60# untouched, the loader refuses the half-written B and boots A, a new update works.
61# 14 inbox signed by the wrong key / with a flipped image byte: refused, slots
62# partition byte-identical.
63# 15 update refused while the Store is LOCKED; a TEST-key updater image is refused
64# by make under CK_HARDWARE_STAGING.
65#
66# Output: one PASS/FAIL line per check, then
67# AIENOS_CK_SLOT_LOADER: PASS|FAIL|NOT_RUN [(...)]
68# NOT_RUN (exit 3) while the machine quiet flag is held (read only) or another
69# gate holds the QEMU gate lock (scripts/lib_gate_hold.sh, aienos#278); exit 2
70# when QEMU or AAVMF is missing. No Python.
71set -euo pipefail
72repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
73cd "${repo_root}"
74tag="AIENOS_CK_SLOT_LOADER"
75code_fd="${AAVMF_CODE:-/usr/share/AAVMF/AAVMF_CODE.no-secboot.fd}"
76vars_fd="${AAVMF_VARS:-/usr/share/AAVMF/AAVMF_VARS.fd}"
77command -v qemu-system-aarch64 >/dev/null || { echo "qemu-system-aarch64 not installed"; echo "${tag}: NOT_RUN (no qemu-system-aarch64)"; exit 2; }
78[[ -r "${code_fd}" && -r "${vars_fd}" ]] || { echo "AAVMF firmware not found"; echo "${tag}: NOT_RUN (no AAVMF)"; exit 2; }
79cross=""
80if [ "$(uname -m)" != "aarch64" ]; then cross="aarch64-linux-gnu-"; fi
81commit="$(git rev-parse HEAD 2>/dev/null || echo 0000000000000000000000000000000000000000)"
82out="${repo_root}/target/native-kernel-slot-loader"
83mk() { make -s -C native/kernel CROSS="${cross}" "$@" >/dev/null; }
84mk OUT="${out}" AIENOS_COMMIT="${commit}" CK_TEST_SLOT_KEY=1 slot-loader slot-tool gpt-image
85mk OUT="${out}/payload-a" AIENOS_COMMIT="slotA-${commit}"
86mk OUT="${out}/payload-b" AIENOS_COMMIT="slotB-${commit}"
87# P11 cut 2b service payloads (rows 9-11): TEST-key service image as A and B, the plain
88# service image (no production keys: stays LOCKED) as L.
89mk OUT="${out}/svc-a" AIENOS_COMMIT="slotA-${commit}" CK_SERVICE=1 CK_SERVICE_TEST_KEYS=1 full
90mk OUT="${out}/svc-b" AIENOS_COMMIT="slotB-${commit}" CK_SERVICE=1 CK_SERVICE_TEST_KEYS=1 full
91mk OUT="${out}/svc-l" AIENOS_COMMIT="slotL-${commit}" CK_SERVICE=1 full
92tool="${out}/host/ck_slot_tool"
93gpt="${out}/host/ck_gpt_image"
94img_a="${out}/payload-a/BOOTAA64.EFI"
95img_b="${out}/payload-b/BOOTAA64.EFI"
96svc_a="${out}/svc-a/full-service-testkeys/BOOTAA64.EFI"
97svc_b="${out}/svc-b/full-service-testkeys/BOOTAA64.EFI"
98svc_l="${out}/svc-l/full-service/BOOTAA64.EFI"
99
100. "${repo_root}/scripts/lib_gate_hold.sh"
101if ! gh_quiet_check || ! gh_lock_take qemu_ck_slot_loader_test "${AIENOS_GATE_MINUTES:-60}"; then
102 echo "NOT_RUN ${gh_why}"
103 echo "${tag}: NOT_RUN (${gh_why})"
104 exit 3
105fi
106work="$(mktemp -d)"
107cleanup() {
108 [[ -z "${qpid:-}" ]] || kill "${qpid}" 2>/dev/null || true
109 rm -rf "${work}"
110 gh_lock_release
111}
112trap cleanup EXIT
113
114fails=0
115checks=0
116boots=0
117qemu_secs=0
118ok() { checks=$((checks + 1)); echo "PASS $*"; }
119bad() { checks=$((checks + 1)); fails=$((fails + 1)); echo "FAIL $*"; }
120
121# ---- fixtures: ESP, slots disk, manifests, control records -----------------------
122mkdir -p "${work}/esp/EFI/BOOT" "${work}/esp/EFI/AIENOS"
123touch "${work}/esp/EFI/AIENOS/BOOTREPORT.TXT"
124cp "${out}/SLOTLDR.EFI" "${work}/esp/EFI/BOOT/BOOTAA64.EFI"
125disk="${work}/slots.img"
126gline="$("${gpt}" create "${disk}" 512 48 slots)"
127first="$(sed -n 's/.*slots_first_lba=\([0-9]*\).*/\1/p' <<<"${gline}")"
128last="$(sed -n 's/.*slots_last_lba=\([0-9]*\).*/\1/p' <<<"${gline}")"
129[[ -n "${first}" && -n "${last}" ]] || { echo "FAIL ck_gpt_image gave no slots geometry: ${gline}"; echo "${tag}: FAIL"; exit 1; }
130cp "${disk}" "${work}/blank.img"
131
132mm() { # name image generation [policy] [--test2]
133 "${tool}" make-manifest --image "$2" --generation "$3" --policy-generation "${4:-0}" --commit "${commit}" \
134 --provenance "slot loader gate" --timestamp 1760000000 --out "${work}/$1.u" >/dev/null
135 "${tool}" sign-test "${work}/$1.u" --out "${work}/$1" ${5:-} >/dev/null
136}
137mm A1 "${img_a}" 1
138mm A2 "${img_a}" 2 2
139mm B1 "${img_b}" 1
140mm B2 "${img_b}" 2
141mm B2k2 "${img_b}" 2 0 --test2
142"${tool}" control-init --active 0 --out "${work}/c_init_a" >/dev/null
143"${tool}" stage "${work}/c_init_a" --slot 1 --generation 2 --out "${work}/c_stage_b" >/dev/null
144"${tool}" control-init --active 1 --out "${work}/c_f0" >/dev/null
145"${tool}" stage "${work}/c_f0" --slot 0 --generation 2 --out "${work}/c_f1" >/dev/null
146"${tool}" promote "${work}/c_f1" --slot 0 --generation 2 --policy-generation 2 --out "${work}/c_f2" >/dev/null
147"${tool}" stage "${work}/c_f2" --slot 1 --generation 3 --out "${work}/c_floor" >/dev/null
148
149geo=""
150slots() { # slots-image args...: fresh disk, then write
151 cp "${work}/blank.img" "${disk}"
152 geo="$("${tool}" slots-image --disk "${disk}" --bs 512 --first "${first}" --last "${last}" "$@" | grep "^slots:" || true)"
153 [[ -n "${geo}" ]] || bad "slots-image refused: $*"
154}
155geo_val() { sed -n "s/.* $1=\([0-9]*\).*/\1/p" <<<"${geo}"; }
156flip() { # file byte-offset: xor 0x01
157 local b
158 b="$(od -An -tu1 -j "$2" -N1 "$1" | tr -d ' ')"
159 # shellcheck disable=SC2059
160 printf "$(printf '\\%03o' $((b ^ 1)))" | dd of="$1" bs=1 seek="$2" conv=notrunc status=none
161}
162region() { # extract the 4-unit control region to $1
163 dd if="${disk}" of="$1" bs=512 skip="${first}" count=32 status=none
164}
165ctl_now() { # the control record as the tool recovers it from the disk
166 region "${work}/region.now"
167 "${tool}" control-recover --region "${work}/region.now" | grep -E '^(control|seq)' | tr '\n' ' ' || true
168}
169
170# ---- one boot ------------------------------------------------------------------
171boot() { # name timeout-seconds
172 local name="$1" to="$2" t0 rc
173 cp "${vars_fd}" "${work}/vars.fd"
174 t0="$(date +%s)"
175 set +e
176 timeout "${to}" qemu-system-aarch64 \
177 -M virt,virtualization=on,gic-version=3 -accel tcg,thread=single -cpu max -smp 4 -m 2048 \
178 -drive if=pflash,format=raw,readonly=on,file="${code_fd}" \
179 -drive if=pflash,format=raw,file="${work}/vars.fd" \
180 -drive if=none,id=esp,format=raw,file=fat:rw:"${work}/esp" \
181 -device virtio-blk-pci,drive=esp \
182 -drive if=none,id=slots,format=raw,file="${disk}" \
183 -device virtio-blk-pci,drive=slots \
184 -device ramfb -display none -nic none \
185 -serial file:"${work}/${name}.raw" -no-reboot
186 rc=$?
187 set -e
188 boots=$((boots + 1))
189 qemu_secs=$((qemu_secs + $(date +%s) - t0))
190 tr -d '\r' <"${work}/${name}.raw" >"${work}/${name}.log"
191 [[ -z "${AIENOS_LOG_DIR:-}" ]] || cp "${work}/${name}.log" "${AIENOS_LOG_DIR}/qemu_ck_slot_loader_${name}.log"
192 echo "boot ${name}: qemu exit ${rc} after $(( $(date +%s) - t0 )) s"
193 last_rc="${rc}"
194 last_log="${work}/${name}.log"
195}
196has() { # row label fixed-text
197 if grep -qF -- "$3" "${last_log}"; then ok "row $1: $2 [$3]"; else bad "row $1: $2 (no serial line containing: $3)"; show=1; fi
198}
199lacks() { # row label fixed-text
200 if grep -qF -- "$3" "${last_log}"; then bad "row $1: $2 (serial has: $3)"; show=1; else ok "row $1: $2 [no \"$3\"]"; fi
201}
202ran() { # row slot(A|B): the payload of that slot ran to its kernel and reset cleanly
203 has "$1" "slot $2 payload ran" "aienos_commit: slot$2-${commit}"
204 has "$1" "kernel entered" "kernel: alive"
205 if [[ "${last_rc}" == 0 ]]; then ok "row $1: QEMU exit 0 (PSCI reset)"; else bad "row $1: QEMU exit ${last_rc}"; show=1; fi
206}
207ctl_is() { # row label expected-substring
208 local c
209 c="$(ctl_now)"
210 if grep -qF -- "$3" <<<"${c}"; then ok "row $1: $2 [disk: ${c}]"; else bad "row $1: $2 (disk control: ${c}; want ${3})"; fi
211}
212tool_agrees() { # row control-file a-spec b-spec expected-decision
213 local cap d
214 cap="$(geo_val image_cap)"
215 d="$("${tool}" select --control "$2" --a "$3" --b "$4" --test-key --cap "${cap}" | grep '^decision:' || true)"
216 if grep -qF -- "$5" <<<"${d}"; then ok "row $1: host tool decides the same [${d}]"; else bad "row $1: host tool decision ${d}; want ${5}"; fi
217}
218row_end() { # row
219 if [[ "${show:-0}" == 1 ]]; then echo "---- serial (last 60 lines) of row $1 ----"; tail -n 60 "${last_log}"; fi
220 show=0
221}
222
223A1="${work}/A1,${img_a}"
224A2="${work}/A2,${img_a}"
225B1="${work}/B1,${img_b}"
226B2="${work}/B2,${img_b}"
227B2k2="${work}/B2k2,${img_b}"
228
229# ---- row 1: fresh media, A valid, B empty --------------------------------------
230slots --a "${A1}" --control "${work}/c_init_a"
231boot r1 180
232has 1 "TEST key announced" "slot_loader: TEST-ONLY key"
233has 1 "slots partition found" "slot_loader: slots partition first_lba=${first} last_lba=${last}"
234has 1 "empty slot B refused" "slot_loader: slot B refused (bad magic)"
235has 1 "decision" "slot_loader: boot=A reason=active gen=1 tries=0 floor=0"
236has 1 "chained stub sees the boot volume (LoadImage device path)" "model_map: absent (no \\EFI\\AIENOS\\MODEL.MAP on the boot volume)"
237ran 1 A
238ctl_is 1 "control untouched" "seq=1 control: active=0 candidate=none tries=0"
239tool_agrees 1 "${work}/c_init_a" "${A1}" none "boot_slot=A reason=active loader_write=0"
240row_end 1
241
242# ---- row 2: candidate B, three tries, then rollback to A -----------------------
243slots --a "${A1}" --b "${B2}" --control "${work}/c_stage_b"
244tool_agrees 2 "${work}/c_stage_b" "${A1}" "${B2}" "boot_slot=B reason=candidate_try loader_write=1"
245for t in 2 1 0; do
246 boot "r2-tries${t}" 180
247 has 2 "candidate try committed before the jump" "slot_loader: control committed seq=$((4 - t)) tries=${t}"
248 has 2 "decision" "slot_loader: boot=B reason=candidate_try gen=2 tries=${t} floor=0"
249 ran 2 B
250 ctl_is 2 "tries on disk after the boot" "seq=$((4 - t)) control: active=0 candidate=1 tries=${t} "
251 row_end 2
252done
253region "${work}/c_exhausted.region"
254"${tool}" control-recover --region "${work}/c_exhausted.region" --out "${work}/c_exhausted" >/dev/null
255boot r2-exhausted 180
256has 2 "decision after the third try" "slot_loader: boot=A reason=candidate_exhausted_active gen=1 tries=0 floor=0"
257lacks 2 "nothing written when exhausted" "slot_loader: control committed"
258ran 2 A
259ctl_is 2 "control unchanged (candidate left for the kernel to abandon, cut 2b)" "seq=4 control: active=0 candidate=1 tries=0 "
260tool_agrees 2 "${work}/c_exhausted" "${A1}" "${B2}" "boot_slot=A reason=candidate_exhausted_active loader_write=0"
261row_end 2
262
263# ---- row 3: B manifest flipped inside the signed bytes --------------------------
264slots --a "${A1}" --b "${B2}" --control "${work}/c_stage_b"
265flip "${disk}" $(( $(geo_val b_off) + 321 )) # timestamp byte 1: still well formed, signature broken
266boot r3 180
267has 3 "B refused" "slot_loader: slot B refused (signature does not verify)"
268has 3 "decision" "slot_loader: boot=A reason=candidate_invalid_active gen=1 tries=3 floor=0"
269lacks 3 "no try consumed" "slot_loader: control committed"
270ran 3 A
271ctl_is 3 "control untouched" "seq=1 control: active=0 candidate=1 tries=3 "
272row_end 3
273
274# ---- row 4: B signed by an untrusted key (RFC 8032 TEST 2) ----------------------
275slots --a "${A1}" --b "${B2k2}" --control "${work}/c_stage_b"
276boot r4 180
277has 4 "B refused" "slot_loader: slot B refused (signer_id names no trusted key)"
278has 4 "decision" "slot_loader: boot=A reason=candidate_invalid_active gen=1 tries=3 floor=0"
279ran 4 A
280tool_agrees 4 "${work}/c_stage_b" "${A1}" "${B2k2}" "boot_slot=A reason=candidate_invalid_active loader_write=0"
281row_end 4
282
283# ---- row 5: B image tampered, manifest intact ------------------------------------
284slots --a "${A1}" --b "${B2}" --control "${work}/c_stage_b"
285flip "${disk}" $(( $(geo_val b_off) + 4096 + 1000 ))
286boot r5 180
287has 5 "B refused" "slot_loader: slot B refused (image SHA-512 mismatch)"
288has 5 "decision" "slot_loader: boot=A reason=candidate_invalid_active gen=1 tries=3 floor=0"
289ran 5 A
290row_end 5
291
292# ---- row 6: torn control write ---------------------------------------------------
293slots --a "${A1}" --b "${B2}" --control "${work}/c_init_a"
294region "${work}/r6.old"
295cp "${work}/r6.old" "${work}/r6.full"
296"${tool}" control-commit --region "${work}/r6.full" --record "${work}/c_stage_b" >/dev/null
297if cmp -s -n 4096 "${work}/r6.old" "${work}/r6.full"; then torn_off=8192; else torn_off=0; fi
298# Power cut after half of the new body: 2048 bytes of it land, its commit header never does.
299dd if="${work}/r6.full" of="${disk}" bs=1 skip="${torn_off}" seek=$(( first * 512 + torn_off )) count=2048 \
300 conv=notrunc status=none
301ctl_is 6 "host tool recovers the previous record" "seq=1 control: active=0 candidate=none tries=0"
302tool_agrees 6 "${work}/c_init_a" "${A1}" "${B2}" "boot_slot=A reason=active loader_write=0"
303# Control: had the staging record landed whole, the decision would have been a try of B.
304d6="$("${tool}" select --control "${work}/c_stage_b" --a "${A1}" --b "${B2}" --test-key --cap "$(geo_val image_cap)" | grep "^decision:" || true)"
305if grep -qF "boot_slot=B reason=candidate_try" <<<"${d6}"; then ok "row 6: control: the unfinished record would have tried B [${d6}]"; else bad "row 6: control decision ${d6}; want a try of B"; fi
306boot r6 180
307has 6 "previous record recovered" "slot_loader: control seq=1 active=A candidate=- tries=0"
308has 6 "decision per the old record" "slot_loader: boot=A reason=active gen=1 tries=0 floor=0"
309lacks 6 "B not tried" "reason=candidate_try"
310ran 6 A
311row_end 6
312
313# ---- row 7: both slots invalid -> recovery required --------------------------------
314slots --a "${A1}" --b "${B2k2}" --control "${work}/c_init_a"
315flip "${disk}" $(( $(geo_val a_off) + 4096 + 1000 ))
316boot r7 "${AIENOS_SLOT_RECOVERY_TIMEOUT:-60}"
317has 7 "recovery required, both reasons" "slot_loader: recovery_required (A: image SHA-512 mismatch; B: signer_id names no trusted key)"
318lacks 7 "no slot started" "slot_loader: starting slot"
319lacks 7 "no kernel ran" "kernel: alive"
320lacks 7 "no payload ran" "aienos_commit: slot"
321ctl_is 7 "control untouched" "seq=1 control: active=0 candidate=none tries=0"
322row_end 7
323
324# ---- row 8: B below the generation floor ---------------------------------------------
325slots --a "${A2}" --b "${B1}" --control "${work}/c_floor"
326boot r8 180
327has 8 "B valid but below the floor" "slot_loader: slot B valid gen=1 policy=0"
328has 8 "floor named" "(below the generation floor)"
329has 8 "decision" "slot_loader: boot=A reason=candidate_invalid_active gen=2 tries=3 floor=2"
330lacks 8 "no try consumed" "slot_loader: control committed"
331ran 8 A
332tool_agrees 8 "${work}/c_floor" "${A2}" "${B1}" "boot_slot=A reason=candidate_invalid_active loader_write=0"
333row_end 8
334
335
336# ==== P11 cut 2b: the service kernel promotes / abandons (svc/slot_service.c) =====
337# One NVMe disk (ck_gpt_image layout aienos-slots: AIENOS Store partition + slots
338# partition), the ESP as above. Payloads: the TEST-key service image built twice
339# (slotA- / slotB- commits: Store formats, continuity provisions, lifecycle READY =
340# healthy) and the plain service image as slot L (no production keys in a QEMU
341# build: the Store stays LOCKED = never healthy). The operator line "shutdown" is
342# sent over the PL011 pipe once the lifecycle is ready; the image then resets.
343gline="$("${gpt}" create "${work}/svc.img" 512 64 aienos-slots)"
344first="$(sed -n 's/.*slots_first_lba=\([0-9]*\).*/\1/p' <<<"${gline}")"
345last="$(sed -n 's/.*slots_last_lba=\([0-9]*\).*/\1/p' <<<"${gline}")"
346[[ -n "${first}" && -n "${last}" ]] || { bad "ck_gpt_image aienos-slots gave no slots geometry: ${gline}"; first=0; last=0; }
347disk="${work}/svc.img"
348cp "${disk}" "${work}/blank.img"
349mm SA1 "${svc_a}" 1
350mm SB2 "${svc_b}" 2 2
351mm SL2 "${svc_l}" 2 2
352SA1="${work}/SA1,${svc_a}"
353SB2="${work}/SB2,${svc_b}"
354SL2="${work}/SL2,${svc_l}"
355# c_stage_b with tries 1: the loader's own decision applied twice (select --out).
356slots --a "${SA1}" --b "${SL2}" --control "${work}/c_stage_b"
357cap_s="$(geo_val image_cap)"
358"${tool}" select --control "${work}/c_stage_b" --a "${SA1}" --b "${SL2}" --test-key --cap "${cap_s}" --out "${work}/c_t2" >/dev/null || true
359"${tool}" select --control "${work}/c_t2" --a "${SA1}" --b "${SL2}" --test-key --cap "${cap_s}" --out "${work}/c_t1" >/dev/null || true
360
361# Operator lines sboot sends once the lifecycle is ready (P11 cut 3), and the
362# answer each one waits for.
363sops=()
364sans='^slot: update (staged|REFUSED)|^slot: TEST-ONLY update halted|^lifecycle: REFUSED verb=update'
365swait() { # raw-file regex count pid: until count answers are on the serial (or QEMU exits)
366 while kill -0 "$4" 2>/dev/null && [[ "$(tr -d '\r' <"$1" | grep -cE "$2" || true)" -lt "$3" ]]; do sleep 1; done
367}
368
369skilled=0 # 1 when sboot itself killed QEMU (the power cut of row 13)
370qpid=""
371sboot() { # name timeout-seconds [efi]: ESP with SLOTLDR (or efi), NVMe ${disk}; "shutdown" once ready
372 local name="$1" to="$2" efi="${3:-${out}/SLOTLDR.EFI}" w t0 rc dpid
373 skilled=0
374 w="${work}/s-${name}"
375 mkdir -p "${w}/esp/EFI/BOOT" "${w}/esp/EFI/AIENOS"
376 touch "${w}/esp/EFI/AIENOS/BOOTREPORT.TXT"
377 cp "${efi}" "${w}/esp/EFI/BOOT/BOOTAA64.EFI"
378 cp "${vars_fd}" "${w}/vars.fd"
379 mkfifo "${w}/ser.in" "${w}/ser.out"
380 : >"${w}/serial.raw"
381 t0="$(date +%s)"
382 timeout "${to}" qemu-system-aarch64 \
383 -M virt,virtualization=on,gic-version=3,iommu=smmuv3 -accel tcg,thread=single -cpu max -smp 4 -m 2048 \
384 -drive if=pflash,format=raw,readonly=on,file="${code_fd}" \
385 -drive if=pflash,format=raw,file="${w}/vars.fd" \
386 -drive if=none,id=esp,format=raw,file=fat:rw:"${w}/esp" \
387 -device virtio-blk-pci,drive=esp \
388 -drive if=none,id=nvme0,format=raw,file="${disk}" \
389 -device nvme,drive=nvme0,serial=aienos-slot-test \
390 -device ramfb -display none -nic none -monitor none \
391 -chardev pipe,id=ser,path="${w}/ser" -serial chardev:ser -no-reboot 2>"${w}/qemu.err" &
392 qpid=$!
393 cat "${w}/ser.out" >>"${w}/serial.raw" &
394 dpid=$!
395 exec 4>"${w}/ser.in"
396 while kill -0 "${qpid}" 2>/dev/null; do
397 if tr -d '\r' <"${w}/serial.raw" | grep -qE '^lifecycle: ready state=|^report_kind: (panic|fault|final)'; then break; fi
398 sleep 1
399 done
400 if tr -d '\r' <"${w}/serial.raw" | grep -q '^lifecycle: ready state='; then
401 sleep 1
402 # P11 cut 3: operator lines (sops) first, each answered before the next.
403 local op n=0 halted=0
404 for op in "${sops[@]}"; do
405 n=$((n + 1))
406 printf '%s\r' "${op}" >&4 || true
407 swait "${w}/serial.raw" "${sans}" "${n}" "${qpid}"
408 if tr -d '\r' <"${w}/serial.raw" | grep -q '^slot: TEST-ONLY update halted'; then halted=1; break; fi
409 done
410 if [[ "${halted}" == 1 ]]; then
411 kill "${qpid}" 2>/dev/null || true # the power cut: QEMU dies mid-update
412 skilled=1
413 else
414 printf 'shutdown\r' >&4 || true
415 fi
416 fi
417 set +e
418 wait "${qpid}"
419 rc=$?
420 set -e
421 qpid=""
422 exec 4>&- 2>/dev/null || true
423 wait "${dpid}" 2>/dev/null || true
424 boots=$((boots + 1))
425 qemu_secs=$((qemu_secs + $(date +%s) - t0))
426 tr -d '\r' <"${w}/serial.raw" >"${w}/serial.log"
427 [[ -z "${AIENOS_LOG_DIR:-}" ]] || cp "${w}/serial.log" "${AIENOS_LOG_DIR}/qemu_ck_slot_loader_${name}.log"
428 echo "boot ${name}: qemu exit ${rc} after $(( $(date +%s) - t0 )) s"
429 last_rc="${rc}"
430 last_log="${w}/serial.log"
431}
432before() { # row label first-text second-text: both present, first earlier
433 local a b
434 a="$({ grep -nF -m1 -- "$3" "${last_log}" || true; } | cut -d: -f1)"
435 b="$({ grep -nF -m1 -- "$4" "${last_log}" || true; } | cut -d: -f1)"
436 if [[ -n "${a}" && -n "${b}" && "${a}" -lt "${b}" ]]; then ok "row $1: $2 (lines ${a} < ${b})"; else bad "row $1: $2 (lines ${a:-none} ${b:-none})"; show=1; fi
437}
438svc_to="${AIENOS_SLOT_SERVICE_TIMEOUT:-420}"
439
440# ---- row 9: candidate B healthy -> promoted by the kernel; next boot steady ------
441slots --a "${SA1}" --b "${SB2}" --control "${work}/c_stage_b"
442sboot r9-try "${svc_to}"
443has 9 "candidate try committed by the loader" "slot_loader: control committed seq=2 tries=2"
444has 9 "boot record handed over" "slot_loader: boot record handed over type=0x80000a1e slot=B reason=candidate_try seq=2"
445has 9 "kernel read the record" "slot: booted slot B reason=candidate_try generation=2 tries=2 control_seq=2"
446has 9 "kernel promoted B after health" "slot: promoted slot B to active generation=2 floor=2 seq=3"
447has 9 "health: lifecycle READY" "lifecycle: ready state=ready store=open"
448before 9 "continuity committed before the promotion" "continuity: PROVISIONED" "slot: promoted slot B"
449ran 9 B
450ctl_is 9 "control on disk: B active, floor raised to its policy generation" "seq=3 control: active=1 candidate=none tries=0 flags=0x00 floor=2 last_good=2"
451sboot r9-steady "${svc_to}"
452has 9 "next boot: B is the active slot" "slot_loader: boot=B reason=active gen=2 tries=0 floor=2"
453lacks 9 "next boot: loader writes nothing" "slot_loader: control committed"
454has 9 "next boot: kernel writes nothing" "slot: nothing to write (nothing to write) active=B"
455ran 9 B
456ctl_is 9 "control unchanged by the steady boot" "seq=3 control: active=1 candidate=none tries=0"
457row_end 9
458
459# ---- row 10: candidate never healthy -> not promoted; exhausted -> abandoned; A stays
460slots --a "${SA1}" --b "${SL2}" --control "${work}/c_t1"
461ctl_is 10 "fixture: candidate B with one try left" "seq=1 control: active=0 candidate=1 tries=1"
462sboot r10-locked "${svc_to}"
463has 10 "last try committed" "slot_loader: control committed seq=2 tries=0"
464has 10 "candidate L booted" "aienos_commit: slotL-${commit}"
465has 10 "Store stays locked (no keys)" "lifecycle: ready state=locked"
466has 10 "kernel waits for health" "slot: candidate B waiting for health (tries left 0): not promoted yet"
467has 10 "stop order says not promoted" "slot: candidate B NOT promoted this boot"
468lacks 10 "no promotion" "slot: promoted"
469ctl_is 10 "control: tries spent, nothing promoted" "seq=2 control: active=0 candidate=1 tries=0 flags=0x00"
470sboot r10-exhausted "${svc_to}"
471has 10 "loader falls back to A" "slot_loader: boot=A reason=candidate_exhausted_active gen=1 tries=0"
472has 10 "kernel read the record" "slot: booted slot A reason=candidate_exhausted_active"
473has 10 "kernel abandoned the candidate" "slot: candidate abandoned (marked failed) active=A stays seq=3"
474ran 10 A
475ctl_is 10 "control: candidate cleared, failed flag, A still active" "seq=3 control: active=0 candidate=none tries=0 flags=0x01"
476region "${work}/c10.region"
477"${tool}" control-recover --region "${work}/c10.region" --out "${work}/c10" >/dev/null || true
478tool_agrees 10 "${work}/c10" "${SA1}" "${SL2}" "boot_slot=A reason=active loader_write=0"
479row_end 10
480
481# ---- row 11: negative control: no boot record (service started without SLOTLDR) ---
482slots --a "${SA1}" --b "${SB2}" --control "${work}/c_stage_b"
483sboot r11-direct "${svc_to}" "${svc_a}"
484has 11 "kernel says it has no record" "slot: no boot record (not started by SLOTLDR.EFI): slot service idle, nothing written"
485has 11 "healthy service" "lifecycle: ready state=ready store=open"
486lacks 11 "no promotion without the loader's record" "slot: promoted"
487ctl_is 11 "control untouched" "seq=1 control: active=0 candidate=1 tries=3"
488row_end 11
489
490# ==== P11 cut 3: the inactive-slot updater (operator verb `update`) ================
491# Disk layout aienos-slots-inbox: AIENOS Store + slots + the update inbox partition
492# (ck_slot_tool inbox-image writes a signed candidate there; the kernel reads it).
493# The running service (slot A, TEST keys) verifies the inbox image (signature + digest)
494# before writing anything, writes the INACTIVE slot only, reads it back, then stages it.
495gline="$("${gpt}" create "${work}/upd.img" 512 80 aienos-slots-inbox)"
496first="$(sed -n 's/.*slots_first_lba=\([0-9]*\).*/\1/p' <<<"${gline}")"
497last="$(sed -n 's/.*slots_last_lba=\([0-9]*\).*/\1/p' <<<"${gline}")"
498ifirst="$(sed -n 's/.*inbox_first_lba=\([0-9]*\).*/\1/p' <<<"${gline}")"
499ilast="$(sed -n 's/.*inbox_last_lba=\([0-9]*\).*/\1/p' <<<"${gline}")"
500[[ -n "${first}" && -n "${last}" && -n "${ifirst}" && -n "${ilast}" ]] || { bad "ck_gpt_image aienos-slots-inbox gave no geometry: ${gline}"; first=0; last=0; ifirst=0; ilast=0; }
501disk="${work}/upd.img"
502cp "${disk}" "${work}/blank.img"
503inbox() { # manifest,image: write the inbox partition
504 "${tool}" inbox-image --disk "${disk}" --bs 512 --first "${ifirst}" --last "${ilast}" --m "$1" | grep -q '^inbox:' || bad "inbox-image refused: $1"
505}
506slot_sum() { # A|B: SHA-256 of that slot's whole byte range on the disk
507 local off
508 off="$(geo_val "$(tr 'AB' 'ab' <<<"$1")_off")"
509 dd if="${disk}" bs=4096 skip="$((off / 4096))" count="$(( $(geo_val image_cap) / 4096 + 1 ))" status=none | sha256sum | cut -c1-64
510}
511part_sum() { # SHA-256 of the whole slots partition (control region + both slots)
512 dd if="${disk}" bs=512 skip="${first}" count="$((last - first + 1))" status=none | sha256sum | cut -c1-64
513}
514cp "${svc_b}" "${work}/svc_b_bad"
515flip "${work}/svc_b_bad" 4242
516mm SB2k2 "${svc_b}" 2 2 --test2
517SB2k2="${work}/SB2k2,${svc_b}"
518SB2bad="${work}/SB2,${work}/svc_b_bad"
519mm SL1 "${svc_l}" 1
520SL1="${work}/SL1,${svc_l}"
521
522# ---- row 12: update writes B from the inbox, stages it; next boot tries + promotes ----
523slots --a "${SA1}" --control "${work}/c_init_a"
524inbox "${SB2}"
525a_sum="$(slot_sum A)"
526sops=("update" "update")
527sboot r12-update "${svc_to}"
528sops=()
529has 12 "service booted from active A" "slot: booted slot A reason=active"
530has 12 "update verified, wrote and staged B" "slot: update staged slot B as candidate generation=2"
531has 12 "second update refused: candidate already staged" "slot: update REFUSED a candidate is already staged"
532ran 12 A
533ctl_is 12 "control: B candidate with 3 tries, A active" "seq=2 control: active=0 candidate=1 tries=3"
534if [[ "$(slot_sum A)" == "${a_sum}" ]]; then ok "row 12: slot A bytes unchanged by the update"; else bad "row 12: slot A bytes changed"; fi
535region "${work}/c12.region"
536"${tool}" control-recover --region "${work}/c12.region" --out "${work}/c12" >/dev/null || true
537tool_agrees 12 "${work}/c12" "${SA1}" "${SB2}" "boot_slot=B reason=candidate_try loader_write=1"
538sboot r12-try "${svc_to}"
539has 12 "loader tries the written B" "slot_loader: boot=B reason=candidate_try gen=2"
540has 12 "kernel promoted the updated B" "slot: promoted slot B to active generation=2 floor=2"
541ran 12 B
542ctl_is 12 "control: B active" "control: active=1 candidate=none tries=0 flags=0x00 floor=2 last_good=2"
543row_end 12
544
545# ---- row 13: interrupted update (QEMU killed mid-write) -> B invalid, control untouched
546slots --a "${SA1}" --control "${work}/c_init_a"
547inbox "${SB2}"
548a_sum="$(slot_sum A)"
549sops=("update halt-after=1")
550sboot r13-halt "${svc_to}"
551sops=()
552has 13 "update started" "slot: update from the inbox into the inactive slot (booted A, keys=1)"
553has 13 "halted mid-image (power cut model)" "slot: TEST-ONLY update halted after 64 of"
554lacks 13 "never staged" "slot: update staged"
555if [[ "${skilled}" == 1 ]]; then ok "row 13: QEMU killed mid-update by the gate (power cut model)"; else bad "row 13: QEMU was not killed mid-update"; fi
556ctl_is 13 "control record untouched" "seq=1 control: active=0 candidate=none tries=0"
557if [[ "$(slot_sum A)" == "${a_sum}" ]]; then ok "row 13: slot A bytes unchanged"; else bad "row 13: slot A bytes changed"; fi
558sops=("update")
559sboot r13-after "${svc_to}"
560sops=()
561has 13 "loader refuses the half-written B" "slot_loader: slot B refused"
562has 13 "loader boots A" "slot_loader: boot=A reason=active gen=1"
563ran 13 A
564has 13 "the update is repeatable after the interruption" "slot: update staged slot B as candidate generation=2"
565ctl_is 13 "control: B staged by the repeated update" "seq=2 control: active=0 candidate=1 tries=3"
566row_end 13
567
568# ---- row 14: negative controls: wrong key, wrong digest -> refused, nothing written ----
569for k in key digest; do
570 slots --a "${SA1}" --control "${work}/c_init_a"
571 if [[ "${k}" == key ]]; then inbox "${SB2k2}"; else inbox "${SB2bad}"; fi
572 p_sum="$(part_sum)"
573 sops=("update")
574 sboot "r14-${k}" "${svc_to}"
575 sops=()
576 has 14 "wrong ${k}: refused before any write" "slot: update REFUSED"
577 has 14 "wrong ${k}: nothing written" ": nothing written"
578 lacks 14 "wrong ${k}: never staged" "slot: update staged"
579 ran 14 A
580 ctl_is 14 "wrong ${k}: control untouched" "seq=1 control: active=0 candidate=none tries=0"
581 if [[ "$(part_sum)" == "${p_sum}" ]]; then ok "row 14: wrong ${k}: slots partition byte-identical"; else bad "row 14: wrong ${k}: slots partition changed"; fi
582done
583row_end 14
584
585# ---- row 15: no update without an unlocked Store; TEST keys refused under staging ----
586slots --a "${SL1}" --control "${work}/c_init_a"
587inbox "${SB2}"
588p_sum="$(part_sum)"
589sops=("update")
590sboot r15-locked "${svc_to}"
591sops=()
592has 15 "plain service image stays LOCKED" "lifecycle: ready state=locked"
593has 15 "update refused while locked" "lifecycle: REFUSED verb=update state=locked reason=\"locked: unlock before updating a slot\""
594if [[ "$(part_sum)" == "${p_sum}" ]]; then ok "row 15: slots partition byte-identical"; else bad "row 15: slots partition changed"; fi
595mk_out="$(make -n -C native/kernel CROSS="${cross}" OUT="${work}/hs" CK_SERVICE=1 CK_SERVICE_TEST_KEYS=1 CK_HARDWARE_STAGING=1 full 2>&1 || true)"
596if grep -qF -- "CK_SERVICE_TEST_KEYS (TEST keys) cannot be combined with CK_HARDWARE_STAGING" <<<"${mk_out}"; then
597 ok "row 15: TEST-key updater image refused under CK_HARDWARE_STAGING (make)"
598else
599 bad "row 15: make accepted a TEST-key service image under CK_HARDWARE_STAGING"
600fi
601row_end 15
602
603gh_lock_release
604echo "slot loader gate: ${boots} boots, ${checks} checks, ${fails} failures, QEMU ${qemu_secs} s (commit ${commit:0:12}; QEMU only, hardware NOT_RUN)"
605if [[ "${fails}" == 0 ]]; then
606 echo "${tag}: PASS (15 rows, ${boots} boots, ${checks} checks; QEMU, not hardware)"
607else
608 echo "${tag}: FAIL (${fails} of ${checks} checks)"
609 exit 1
610fi