]> git.hungrycats.org Git - linux/commitdiff
btrfs: commit the canceled state when a device replace fails or is canceled
authorZygo Blaxell <ce3g8jdj@umail.furryterror.org>
Fri, 16 Oct 2026 05:19:17 +0000 (01:19 -0400)
committerZygo Blaxell <ce3g8jdj@umail.furryterror.org>
Mon, 2 Nov 2026 02:17:13 +0000 (21:17 -0500)
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
fs/btrfs/dev-replace.c

index 3c48cc714fef2e8447648bdaf873378d84ab9c62..68aaf39020a51bb3f8e5e2e759512c4799f27311 100644 (file)
@@ -977,6 +977,22 @@ error:
                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;