Skip to content

bootutil: Make revert fixup survive repeated power loss - #3011

Open
d3zd3z wants to merge 4 commits into
mcu-tools:mainfrom
d3zd3z:fix-revert-fixup-power-loss
Open

d3zd3z wants to merge 4 commits into
mcu-tools:mainfrom
d3zd3z:fix-revert-fixup-power-loss

Conversation

@d3zd3z

@d3zd3z d3zd3z commented Nov 24, 2026

Copy link
Copy Markdown
Member

Two revert bugs in fixup_revert() can each be triggered by a pair of power losses during a revert. One loses the revert, so the unconfirmed image keeps booting (#3009). The other leaves a swap-using-offset device stuck in an assert on every boot (#3010). This PR adds simulator coverage that reproduces both, then fixes them.

Commits

  1. bootutil: Use ASSERT for swap size checks in boot_swap_image. These checks depend on flash contents. ASSERT() maps to the normal assert on every port, so targets are unchanged, but the simulator can catch it and report a test failure instead of aborting the whole test process.
  2. sim: Test power loss tearing the interrupted flash write, by Neil Berkman, taken unchanged from Interrupted-OTA swap-move coverage: sim torn-write test and CI canary #2648. It adds a torn-write mode to the simulator (the interrupted write is left partly programmed) and a single-interruption torn revert sweep for swap-using-move.
  3. sim: Test reverts interrupted twice. A new sweep cuts power at each flash operation of the boot that starts a revert, then again within the first 16 operations of the boot that resumes it, with both clean and torn cuts. It runs for all swap modes and is gated behind MCUBOOT_RUN_SLOW_TESTS.
  4. bootutil: Make revert fixup survive repeated power loss.

Test results

Results of the new double-interruption sweep before and after the fix commit:

Before After
swap-offset, clean cuts fails (#3010 assert) passes
swap-offset, torn writes fails (#3010, revert lost) passes
swap-move, clean cuts passes passes
swap-move, torn writes fails (#3009, revert lost) passes
swap-scratch, both passes passes

The existing revert_with_fails and the torn-write sweep from #2648 pass throughout. The regular suite also passes for default, swap-move, swap-offset, both with max-align-32, both with multiimage, and the RSA-encrypted swap-move and swap-offset CI combinations.

The new sweep is slow: about 100 s for swap-move and about 8 minutes for swap-scratch, per feature combination, which is why it is gated.

This takes over the simulator part of #2648; that PR's CI canary commit is not included.

d3zd3z and others added 4 commits November 24, 2026 09:42
The three checks on reading the image and swap sizes in
boot_swap_image() used the C library assert(). These checks depend on
what is in flash, so a bad flash state can trip them. Switch them to
ASSERT(), which every port maps to its normal assert handler, so
behaviour on targets is unchanged. In the simulator, ASSERT() goes
through sim_assert(), so a test that catches asserts can report a
failure here instead of aborting the whole test process.

The NULL check on the status flash area stays a plain assert(): it is
a programming invariant, and continuing past it would only crash.

Assisted-by: Claude:opus-5.5
Signed-off-by: David Brown <david.brown@linaro.org>
The simulator's power-loss testing interrupts boot_go between whole
flash operations: when the flash counter expires, flash_area_write
aborts before writing anything. Every simulated power cut is therefore
write-atomic, so states left by a write torn partway through, such as
a partially written trailer magic reading back as BOOT_MAGIC_BAD, are
unreachable. That is why the revert interruption tests did not catch
issue mcu-tools#1966: power loss inside boot_write_magic during swap-move revert
fixup left a bad magic that matched no swap table row and bricked the
device.

Add a torn-write mode to the flash counter: on expiry the interrupted
write programs all but the last byte of its payload before the
simulated power loss.  Write alignment is a driver interface
requirement, not a power-fail atomicity guarantee, so the tear point
falls inside the final write unit regardless of max-align.  The
simulated flash marks torn bytes as retryable: one subsequent write of
the same values is allowed, since recovery replays the interrupted
operation, while the write-once discipline stays enforced everywhere
else.

Add run_revert_with_torn_writes, a revert-only sweep: perform a test
upgrade, count the flash operations of an uninterrupted revert, then
for each operation clone the post-upgrade state, tear that write
during revert, and verify the device recovers to the original image
with clean trailers.  Gated to swap-using-move.

With the fix from commit 4f39356 ("bootutil: Fix device brick after
power failure during swap-move revert") reverted, the new test fails
at the fixup_revert magic write, including under max-align-32, while
the existing whole-operation revert_with_fails sweep still passes; on
current code both pass.

Signed-off-by: Neil Berkman <neil@xuku.com>
Signed-off-by: David Brown <david.brown@linaro.org>
The revert interruption sweeps cut power once per run. Some failures
need a second power loss in the boot that resumes the revert, and
neither revert_with_fails nor revert_with_torn_writes can reach them.

Add run_revert_with_double_fails(). It cuts power at each flash
operation of the boot that starts a revert, then again within the
first 16 operations of the boot that resumes it, and checks that the
following boot completes the revert without asserts. Run it twice:
once with clean cuts, and once using the torn-write mode added by Neil
Berkman in the previous commit (from PR mcu-tools#2648), so that each
interrupted write is left partly programmed.

On current main this fails for swap-using-offset in both modes: a
resumed revert re-runs fixup_revert() and leaves the secondary magic
good, so the next boot restarts the revert on a half-swapped primary
slot. With torn writes it also fails for swap-using-move and
swap-using-offset when the fixup's magic write is torn, which loses
the revert. The test is gated behind MCUBOOT_RUN_SLOW_TESTS.

Assisted-by: Claude:opus-5.5
Signed-off-by: David Brown <david.brown@linaro.org>
fixup_revert() protects the start of a revert by writing a trailer in
the secondary slot that makes the revert restartable. Two cases left
it unprotected.

The fixup was only redone when the secondary magic read as unset. A
power loss while writing that magic leaves it reading as bad, so the
next boot skipped the fixup and went on to erase the primary trailer.
A second power loss then left neither slot with a usable trailer, and
the unconfirmed image booted permanently. Redo the fixup whenever the
magic is not good, in both swap-using-move and swap-using-offset.

In swap-using-offset the fixup ran whenever the status index was 0.
Unlike swap-using-move, swap-using-offset has two states per index,
so a revert resumed after its first step ran the fixup again. That
wrote a good secondary magic which swap_run() erased right after; a
power loss between the two made the next boot ignore the recorded
progress and restart the revert on a half-swapped primary slot, which
failed on every boot. Only run the fixup when no status has been
written, using boot_status_is_reset() as swap_run() already does.

Both cases are caught by the double-interruption revert test in the
simulator.

Fixes: mcu-tools#3009
Fixes: mcu-tools#3010
Assisted-by: Claude:opus-5.5
Signed-off-by: David Brown <david.brown@linaro.org>
@d3zd3z
d3zd3z requested a review from davidvincze as a code owner November 24, 2026 17:32
Copilot AI balanced review requested due to automatic review settings November 24, 2026 17:32

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Warning

Copilot couldn't run its full agentic review because it didn't start before the timeout. Make sure your repository has a runner available, or add a copilot-code-review.yml file specifying one with the runs-on attribute. See the docs for more details.

Copilot review overview

5 open issues
What changed in this PR

This PR improves MCUBoot’s resilience to repeated power loss during a revert (including torn write scenarios) and adds simulator coverage to reproduce and prevent regressions for the reported revert/fixup failure modes.

Changes:

  • Add simulator support for “torn” interrupted writes and new revert interruption sweeps (single and double interruption).
  • Update revert fixup logic for swap-move and swap-offset to handle torn magic writes and avoid incorrect re-running of fixup.
  • Make specific boot swap size checks use ASSERT() so simulator can catch failures without aborting the whole process.
File Description
sim/​tests/​core.rs Registers new simulator tests for torn-write and double-interruption revert sweeps.
sim/​src/​lib.rs Adds the torn-write revert sweep to the simulator run list.
sim/​src/​image.rs Implements torn-write revert sweep and the new double-interruption revert sweep logic.
sim/​simflash/​src/​lib.rs Extends flash trait with write_torn, implements torn-write behavior, and adds unit tests.
sim/​mcuboot-sys/​src/​c.rs Adds boot_go_torn() plumbing into the simulator boot invocation.
sim/​mcuboot-sys/​src/​api.rs Extends the simulator context and exports sim_flash_write_torn() FFI hook.
sim/​mcuboot-sys/​csupport/​run.c Implements torn-write behavior on the interruption point in flash_area_write.
docs/​release-notes.d/​swap-revert-fixup-power-loss.md Adds release note for the revert fixup power-loss resilience fix.
docs/​release-notes.d/​sim-torn-writes.md Adds release note for simulator torn-write mode and sweep.
docs/​release-notes.d/​sim-revert-double-fails.md Adds release note for the double-interruption revert sweep.
boot/​bootutil/​src/​swap_offset.c Fixes swap-offset revert fixup gating and retries fixup on bad magic (not just unset).
boot/​bootutil/​src/​swap_move.c Retries revert fixup unless secondary magic is confirmed good.
boot/​bootutil/​src/​loader.c Switches key asserts to ASSERT() so simulator can catch them as test failures.

Review effort: Lite

Comment thread sim/simflash/src/lib.rs
Comment on lines +242 to 265
fn write_torn(&mut self, offset: usize, payload: &[u8]) -> Result<()> {
if offset + payload.len() > self.data.len() {
panic!("Write outside of device");
}

// Verify the alignment (which must be a power of two).
if offset & (self.align - 1) != 0 {
panic!("Misaligned write address");
}

for (i, x) in &mut self.write_safe[offset .. offset + payload.len()].iter_mut().enumerate() {
if self.verify_writes && !(*x) {
panic!("Write to unerased location at 0x{:x}", offset + i);
panic!("Torn write to unerased location at 0x{:x}", offset + i);
}
*x = false;
}

for x in &mut self.retryable[offset .. offset + payload.len()] {
*x = true;
}

let sub = &mut self.data[offset .. offset + payload.len()];
sub.copy_from_slice(payload);
Ok(())
Comment thread sim/simflash/src/lib.rs
Comment on lines 54 to 58
pub trait Flash {
fn erase(&mut self, offset: usize, len: usize) -> Result<()>;
fn write(&mut self, offset: usize, payload: &[u8]) -> Result<()>;
fn write_torn(&mut self, offset: usize, payload: &[u8]) -> Result<()>;
fn read(&self, offset: usize, data: &mut [u8]) -> Result<()>;
Comment thread sim/src/image.rs
Comment on lines +1110 to +1114
if !c::boot_go(&mut upgraded, &self.areadesc, None, None,
false).success() {
error!("Failed upgrade before torn-write revert");
return true;
}
Comment thread sim/src/image.rs
Comment on lines +1123 to +1127
if !c::boot_go(&mut clean, &self.areadesc, Some(&mut counter), None,
false).success() {
error!("Failed uninterrupted revert");
return true;
}
Comment thread sim/src/image.rs
Comment on lines +1140 to +1145
if !c::boot_go(&mut flash, &self.areadesc, None, None,
false).success() {
warn!("Should have finished revert after torn write at {}",
stop);
fails += 1;
}
@pkorec21

Copy link
Copy Markdown

Thanks for the quick fix!

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

5 participants