When the scrub copying a device replace returns an error, including
-ECANCELED from "btrfs replace cancel" on a running replace,
btrfs_dev_replace_finishing() sets the replace state to CANCELED, marks
the dev_replace item for writeback and destroys the target device, but
returns without committing a transaction.
If no other transaction commits before the filesystem is unmounted (an
idle filesystem), the item on disk still says STARTED. The next mount
then tries to resume the replace and fails:
BTRFS warning (device ...): cannot mount because device replace operation is ongoing and
BTRFS warning (device ...): tgtdev (devid 0) is missing, need to run 'btrfs dev scan'?
BTRFS error (device ...): failed to init dev_replace: -EIO
Commit a transaction after the cleanup, as btrfs_dev_replace_cancel()
already does when it cancels a suspended replace, so the CANCELED state
reaches the disk. A failure to commit is only logged: the replace has
already failed, and its return value is the scrub error.
Assisted-by: Claude:claude-opus-5-5
if (src_device->bdev)
bdev_allow_freeze(src_device->bdev);
btrfs_rm_dev_replace_unblocked(fs_info);
+
+ /*
+ * Write the CANCELED state out now. Nothing else is
+ * guaranteed to commit before an unmount, and a dev_replace
+ * item left in the STARTED state makes the next mount look
+ * for a target device that no longer exists and fail.
+ */
+ trans = btrfs_start_transaction(root, 0);
+ if (IS_ERR(trans))
+ ret = PTR_ERR(trans);
+ else
+ ret = btrfs_commit_transaction(trans);
+ if (ret && !BTRFS_FS_ERROR(fs_info))
+ btrfs_warn(fs_info,
+ "dev_replace: failed to commit the canceled state: %d",
+ ret);
mutex_unlock(&dev_replace->lock_finishing_cancel_unmount);
return scrub_ret;