]> git.hungrycats.org Git - linux/commitdiff
btrfs: replace the balance resume heuristics with a vrange bound
authorZygo Blaxell <ce3g8jdj@umail.furryterror.org>
Wed, 16 Sep 2026 06:29:10 +0000 (02:29 -0400)
committerZygo Blaxell <ce3g8jdj@umail.furryterror.org>
Mon, 9 Nov 2026 03:25:01 +0000 (22:25 -0500)
When a balance is resumed after a pause or an unmount,
update_balance_args() adds a usage=90 filter to every chunk type that is
not being converted.  That changes the set of block groups the original
request selected.  It skips full block groups the interrupted balance had
not reached yet, so the resumed balance can finish without having done
what was asked, and it selects again any block group the interrupted
balance created that is less than 90% full, relocating the same data a
second time.  For the chunk types that are being converted it adds the
soft filter instead, so the resume does not convert again the block
groups the interrupted balance converted, but it also skips the ones
that already had the target profile when the balance started, which the
original request selected.

Replace it with a bound fixed when the balance starts.  Before the
balance item is written, limit the vrange filter of each chunk type to
the addresses below the next chunk to be allocated: add a 0..end range
when the request had no vrange filter, or lower the end of the one it
had.  Every block group that existed when the balance started stays
selected until the balance relocates it.

New chunks are allocated after the last chunk, but relocation can remove
the highest chunks without allocating any (their data fits in free space
lower down), and the next chunk would then reuse their addresses, below
the bound.  A resumed balance would select it again, although the
interrupted one, walking downward, never would have.  So while a balance
item exists, find_next_chunk() never returns an address below the bound:
an in-memory floor, set when the balance starts and when the balance
item is recovered at mount, and cleared when the item is deleted.  Every
chunk allocated in that time, relocation targets included, stays outside
the range, on the first run and after a resume.  The gap the floor can
leave in the logical address space is harmless.

A resume now uses the arguments exactly as they were stored: the bound
already keeps out every block group the interrupted balance created,
converted ones included, so neither the usage filter nor the soft filter
is needed, and update_balance_args() goes away.

The bound does not move as the balance progresses.  Block groups the
balance has relocated are gone, so on resume the walk only revisits the
chunks it left in place above the point where it stopped (filtered out,
ENOSPC, active swapfile) and checks them against the filters again.
Nothing is skipped.

Because the bound is written with the balance item and never changes,
there is no progress to persist: a resume after an unmount or a crash
needs no extra writes.

A balance item recovered at mount is limited in the same way before the
floor is set from it: a vrange 0..end is added to each chunk type that
has none, and a vrange that ends above the next chunk is lowered to it.
That covers items written by older kernels, which have no vrange or a
vrange the user gave, which can end anywhere (a 1 TiB end would put
every new chunk at 1 TiB and above).  A bound written by this kernel
changes only when relocation removed the highest chunks and allocated
none above it; no chunk exists between the next chunk and the old end,
so lowering it drops nothing.  When the recovered arguments change,
they are written back to the balance item once, when the balance
resumes, so a resume that is interrupted again resumes with the same
bound and not with a new one that includes the chunks the first resume
allocated.  If that write fails, the balance is not resumed: as for the
other errors at that point, it ends with the error logged, and its item
is deleted.  Nothing has been relocated yet, so if the item survives (the
delete fails too, or the system crashes first), the next mount bounds it
again to the same chunks.

A balance item written by an older kernel therefore resumes with the
bound and without the usage or soft filter: the resumed balance restarts
from the beginning, relocating again every block group the request
selects, including the ones the interrupted run created or converted,
but it skips none.

The bound is visible: `btrfs balance status -v`, the
BTRFS_IOC_BALANCE_PROGRESS ioctl and the "balance: start" and "balance:
resume" log lines show a vrange the user did not give.

Assisted-by: Codex:gpt-5
Assisted-by: Claude:claude-opus-5-5
fs/btrfs/fs.h
fs/btrfs/volumes.c
fs/btrfs/volumes.h

index 8687cf6952d00a6a6c96fea87c2db465d30fd00f..0f08689d078bc04a75998cead238d72f02900037 100644 (file)
@@ -738,6 +738,12 @@ struct btrfs_fs_info {
        atomic_t balance_cancel_req;
        struct btrfs_balance_control *balance_ctl;
        wait_queue_head_t balance_wait_q;
+       /*
+        * 0, or the end of the balance's vrange bound: while a balance item
+        * exists (running or paused) find_next_chunk() allocates at or above
+        * it, so the balance never selects a chunk it allocated.
+        */
+       u64 balance_chunk_floor;
 
        /* Cancellation requests for chunk relocation */
        atomic_t reloc_cancel_req;
index a1a3023554a494547865547e8d9951b7110fa225..24f50b1ac146e3bc276d701057b252201226a92d 100644 (file)
@@ -2008,7 +2008,7 @@ static u64 find_next_chunk(struct btrfs_fs_info *fs_info)
        }
        read_unlock(&fs_info->mapping_tree_lock);
 
-       return ret;
+       return max(ret, READ_ONCE(fs_info->balance_chunk_floor));
 }
 
 static noinline int find_next_devid(struct btrfs_fs_info *fs_info,
@@ -3767,13 +3767,27 @@ static void btrfs_cpu_balance_args_to_disk(struct btrfs_disk_balance_args *disk,
        disk->stripes_max = cpu_to_le32(cpu->stripes_max);
 }
 
+static void set_balance_item(struct extent_buffer *leaf,
+                            struct btrfs_balance_item *item,
+                            const struct btrfs_balance_control *bctl)
+{
+       struct btrfs_disk_balance_args disk_bargs;
+
+       btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->data);
+       btrfs_set_balance_data(leaf, item, &disk_bargs);
+       btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->meta);
+       btrfs_set_balance_meta(leaf, item, &disk_bargs);
+       btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->sys);
+       btrfs_set_balance_sys(leaf, item, &disk_bargs);
+       btrfs_set_balance_flags(leaf, item, bctl->flags & ~BTRFS_BALANCE_RESUME);
+}
+
 static int insert_balance_item(struct btrfs_fs_info *fs_info,
                               struct btrfs_balance_control *bctl)
 {
        struct btrfs_root *root = fs_info->tree_root;
        struct btrfs_trans_handle *trans;
        struct btrfs_balance_item *item;
-       struct btrfs_disk_balance_args disk_bargs;
        struct btrfs_path *path;
        struct extent_buffer *leaf;
        struct btrfs_key key;
@@ -3802,14 +3816,7 @@ static int insert_balance_item(struct btrfs_fs_info *fs_info,
        item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
 
        memzero_extent_buffer(leaf, (unsigned long)item, sizeof(*item));
-
-       btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->data);
-       btrfs_set_balance_data(leaf, item, &disk_bargs);
-       btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->meta);
-       btrfs_set_balance_meta(leaf, item, &disk_bargs);
-       btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->sys);
-       btrfs_set_balance_sys(leaf, item, &disk_bargs);
-       btrfs_set_balance_flags(leaf, item, bctl->flags);
+       set_balance_item(leaf, item, bctl);
 out:
        btrfs_free_path(path);
        err = btrfs_commit_transaction(trans);
@@ -3818,6 +3825,43 @@ out:
        return ret;
 }
 
+/* Write the arguments of a resumed balance to its existing item. */
+static int update_balance_item(struct btrfs_fs_info *fs_info,
+                              const struct btrfs_balance_control *bctl)
+{
+       struct btrfs_root *root = fs_info->tree_root;
+       struct btrfs_trans_handle *trans;
+       BTRFS_PATH_AUTO_FREE(path);
+       struct btrfs_key key;
+       int ret;
+
+       path = btrfs_alloc_path();
+       if (!path)
+               return -ENOMEM;
+
+       trans = btrfs_start_transaction(root, 0);
+       if (IS_ERR(trans))
+               return PTR_ERR(trans);
+
+       key.objectid = BTRFS_BALANCE_OBJECTID;
+       key.type = BTRFS_TEMPORARY_ITEM_KEY;
+       key.offset = 0;
+
+       ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
+       if (ret > 0)
+               ret = -ENOENT;
+       if (ret < 0) {
+               btrfs_end_transaction(trans);
+               return ret;
+       }
+
+       set_balance_item(path->nodes[0],
+                        btrfs_item_ptr(path->nodes[0], path->slots[0],
+                                       struct btrfs_balance_item), bctl);
+       btrfs_release_path(path);
+       return btrfs_commit_transaction(trans);
+}
+
 static int del_balance_item(struct btrfs_fs_info *fs_info)
 {
        struct btrfs_root *root = fs_info->tree_root;
@@ -3857,47 +3901,61 @@ out:
        return ret;
 }
 
+static bool limit_balance_vrange(struct btrfs_balance_args *bargs, u64 end)
+{
+       if (!(bargs->flags & BTRFS_BALANCE_ARGS_VRANGE)) {
+               bargs->flags |= BTRFS_BALANCE_ARGS_VRANGE;
+               bargs->vstart = 0;
+               bargs->vend = end;
+               return true;
+       }
+       if (bargs->vend <= end)
+               return false;
+       bargs->vend = end;
+       return true;
+}
+
 /*
- * This is a heuristic used to reduce the number of chunks balanced on
- * resume after balance was interrupted.
+ * Limit the request to the chunks that exist now.  The bound is written with
+ * the balance item and never moves, so there is no progress to persist.  New
+ * chunks are allocated after the last chunk, but once relocation has removed
+ * the highest chunks the last chunk is lower than the bound, so while the
+ * balance item exists find_next_chunk() also observes balance_chunk_floor:
+ * every chunk allocated in that time, relocation targets included, stays
+ * outside the range, on this run and after a resume.
+ *
+ * Return true if any of the arguments changed.
  */
-static void update_balance_args(struct btrfs_balance_control *bctl)
+static bool limit_balance_to_existing_chunks(struct btrfs_fs_info *fs_info,
+                                            struct btrfs_balance_control *bctl)
 {
-       /*
-        * Turn on soft mode for chunk types that were being converted.
-        */
-       if (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)
-               bctl->data.flags |= BTRFS_BALANCE_ARGS_SOFT;
-       if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)
-               bctl->sys.flags |= BTRFS_BALANCE_ARGS_SOFT;
-       if (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)
-               bctl->meta.flags |= BTRFS_BALANCE_ARGS_SOFT;
+       const u64 end = find_next_chunk(fs_info);
+       bool changed = false;
 
-       /*
-        * Turn on usage filter if is not already used.  The idea is
-        * that chunks that we have already balanced should be
-        * reasonably full.  Don't do it for chunks that are being
-        * converted - that will keep us from relocating unconverted
-        * (albeit full) chunks.
-        */
-       if (!(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE) &&
-           !(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
-           !(bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
-               bctl->data.flags |= BTRFS_BALANCE_ARGS_USAGE;
-               bctl->data.usage = 90;
-       }
-       if (!(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE) &&
-           !(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
-           !(bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
-               bctl->sys.flags |= BTRFS_BALANCE_ARGS_USAGE;
-               bctl->sys.usage = 90;
-       }
-       if (!(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE) &&
-           !(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
-           !(bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
-               bctl->meta.flags |= BTRFS_BALANCE_ARGS_USAGE;
-               bctl->meta.usage = 90;
-       }
+       if (bctl->flags & BTRFS_BALANCE_DATA)
+               changed |= limit_balance_vrange(&bctl->data, end);
+       if (bctl->flags & BTRFS_BALANCE_METADATA)
+               changed |= limit_balance_vrange(&bctl->meta, end);
+       if (bctl->flags & BTRFS_BALANCE_SYSTEM)
+               changed |= limit_balance_vrange(&bctl->sys, end);
+       return changed;
+}
+
+/* The highest vrange end of the selected chunk types, 0 if none has one. */
+static u64 balance_chunk_floor(const struct btrfs_balance_control *bctl)
+{
+       u64 floor = 0;
+
+       if ((bctl->flags & BTRFS_BALANCE_DATA) &&
+           (bctl->data.flags & BTRFS_BALANCE_ARGS_VRANGE))
+               floor = max(floor, bctl->data.vend);
+       if ((bctl->flags & BTRFS_BALANCE_METADATA) &&
+           (bctl->meta.flags & BTRFS_BALANCE_ARGS_VRANGE))
+               floor = max(floor, bctl->meta.vend);
+       if ((bctl->flags & BTRFS_BALANCE_SYSTEM) &&
+           (bctl->sys.flags & BTRFS_BALANCE_ARGS_VRANGE))
+               floor = max(floor, bctl->sys.vend);
+       return floor;
 }
 
 /*
@@ -3916,6 +3974,7 @@ static void reset_balance_state(struct btrfs_fs_info *fs_info)
 
        kfree(bctl);
        ret = del_balance_item(fs_info);
+       WRITE_ONCE(fs_info->balance_chunk_floor, 0);
        if (ret)
                btrfs_handle_fs_error(fs_info, ret, NULL);
 }
@@ -4698,6 +4757,9 @@ int btrfs_balance(struct btrfs_fs_info *fs_info,
                                btrfs_bg_type_to_raid_name(data_target));
        }
 
+       if (!(bctl->flags & BTRFS_BALANCE_RESUME))
+               limit_balance_to_existing_chunks(fs_info, bctl);
+
        ret = insert_balance_item(fs_info, bctl);
        if (ret && ret != -EEXIST)
                goto out;
@@ -4708,11 +4770,26 @@ int btrfs_balance(struct btrfs_fs_info *fs_info,
                spin_lock(&fs_info->balance_lock);
                fs_info->balance_ctl = bctl;
                spin_unlock(&fs_info->balance_lock);
+               WRITE_ONCE(fs_info->balance_chunk_floor,
+                          balance_chunk_floor(bctl));
        } else {
                BUG_ON(ret != -EEXIST);
-               spin_lock(&fs_info->balance_lock);
-               update_balance_args(bctl);
-               spin_unlock(&fs_info->balance_lock);
+               if (bctl->update_item) {
+                       /*
+                        * Nothing has been relocated yet, so the item on disk,
+                        * bounded again at the next mount, is still right.  As
+                        * for the other errors here, the balance ends and its
+                        * item is deleted.
+                        */
+                       ret = update_balance_item(fs_info, bctl);
+                       if (ret) {
+                               btrfs_err(fs_info,
+                       "balance: failed to write the bounded balance item: %d",
+                                         ret);
+                               goto out;
+                       }
+                       bctl->update_item = false;
+               }
        }
 
        ASSERT(!test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
@@ -4865,6 +4942,17 @@ int btrfs_recover_balance(struct btrfs_fs_info *fs_info)
        btrfs_balance_sys(leaf, item, &disk_bargs);
        btrfs_disk_balance_args_to_cpu(&bctl->sys, &disk_bargs);
 
+       /*
+        * Bound the request as a new balance would be: an item written by an
+        * older kernel has no vrange, and one a user gave to such a kernel can
+        * end anywhere.  The floor is still 0, so find_next_chunk() returns the
+        * end of the last chunk, and lowering a vend above it drops no block
+        * group from the range.  The bound is written back to the item when
+        * the balance resumes, so a resume that is interrupted again keeps it.
+        */
+       bctl->update_item = limit_balance_to_existing_chunks(fs_info, bctl);
+       WRITE_ONCE(fs_info->balance_chunk_floor, balance_chunk_floor(bctl));
+
        /*
         * This should never happen, as the paused balance state is recovered
         * during mount without any chance of other exclusive ops to collide.
index 2cbf8080eade061702003d5a8632be0e579e1ccf..b6c68cdd53412bbdecdfe5c0b892a2235fd6f3e2 100644 (file)
@@ -652,6 +652,12 @@ struct btrfs_balance_control {
 
        u64 flags;
 
+       /*
+        * The arguments recovered at mount were bounded and differ from the
+        * balance item: write them back when the balance resumes.
+        */
+       bool update_item;
+
        struct btrfs_balance_progress stat;
 };