Skip to content

Test for-next (regular, SELF kvm) - #1624

Open
kdave wants to merge 10000 commits into
ci-kvmfrom
for-next
Open

kdave wants to merge 10000 commits into
ci-kvmfrom
for-next

Conversation

@kdave

@kdave kdave commented Mar 5, 2026 •

Copy link
Copy Markdown
Member

Keep this open, the build tests are on self-hosted workers.

@kdave

ghost commented Mar 5, 2026

Copy link
Copy Markdown
Member Author

Re #1623 .

@kdave kdave changed the title Test for-next (regular, GH kvm) 2 Test for-next (regular, GH kvm) Mar 5, 2026
@kdave kdave closed this Mar 5, 2026
@kdave kdave reopened this Mar 5, 2026
@kdave
kdave force-pushed the ci-kvm branch 2 times, most recently from 69fc6c9 to 98bf7e7 Compare March 5, 2026 23:30
@kdave
kdave force-pushed the for-next branch 3 times, most recently from 934d926 to 0cb5a8a Compare March 13, 2026 11:46
@kdave
kdave force-pushed the ci-kvm branch 3 times, most recently from 2cd3911 to c09d7cb Compare March 13, 2026 19:11
@kdave
kdave force-pushed the for-next branch 8 times, most recently from c61e262 to daed989 Compare March 17, 2026 16:00
@kdave
kdave force-pushed the for-next branch 4 times, most recently from 9dc51d6 to d76ed94 Compare March 19, 2026 13:21
Alexander Mikhalitsyn and others added 30 commits November 30, 2026 04:25
Currently, FS_IOC_GETFSUUID fails with ENOTTY. To fix that we should
use super_set_uuid() as other filesystems do.

Reported-by: Lennart Poettering <lennart@amutable.com>
Reviewed-by: Qu Wenruo <wqu@suse.com>
Signed-off-by: Alexander Mikhalitsyn <alex@amutable.com>
Signed-off-by: David Sterba <dsterba@suse.com>
Since commit f4d39cf ("btrfs: set search_commit_root on stripe io
in case of relocation"), reads of the data relocation inode look up the
raid stripe tree in its commit root. A read repair of such a read does
the same. btrfs_get_raid_extent_offset() then searches with
search_commit_root and skip_locking, but nothing holds commit_root_sem.

switch_commit_roots() can then drop the old commit root while
btrfs_search_slot() takes a reference to it:

  relocation read or its repair     transaction commit
  -----------------------------     ------------------
  btrfs_map_block()
    btrfs_get_raid_extent_offset()
      btrfs_search_slot()
        b = root->commit_root
                                    switch_commit_roots()
                                      drops the last reference to b
        refcount_inc(&b->refs)
                                    b is freed after an RCU grace period
        reads b

  refcount_t: addition on 0; use-after-free.
  ...
  BUG: KASAN: slab-use-after-free in btrfs_search_slot+0x2e5f/0x2fc0
   btrfs_get_raid_extent_offset+0x1cb/0x700
   btrfs_map_block+0x5f8/0x27a0
   btrfs_submit_bbio+0x54d/0x2350
   btrfs_check_read_bio+0x758/0x12e0

Scrub sets the same flag. A commit pauses scrub first, but the repair
reads of stripes that are still in flight run from
scrub_stripe_read_repair_worker() and are not covered by the pause.

Take commit_root_sem for read in btrfs_map_block() for these lookups,
and hold it until the mapping is done. Only reads that set
rst_search_commit_root take it. Take it before dev_replace->rwsem. A
read that looks up checksums in the commit root already takes the two
locks in this order. btrfs_lookup_bio_sums() holds commit_root_sem while
it reads csum tree blocks. Each of these reads goes through
btrfs_map_block(). need_commit_sem in the search would take
commit_root_sem inside dev_replace->rwsem instead. During a device
replace, lockdep reports that order as a circular dependency.

Fixes: 9acaa64 ("btrfs: scrub: implement raid stripe tree support")
Fixes: f4d39cf ("btrfs: set search_commit_root on stripe io in case of relocation")
CC: stable@vger.kernel.org # 6.12+
Reviewed-by: Johannes Thumshirn <johannes.thumshirn@wdc.com>
Signed-off-by: Miroslav Cimerman <mc@raidlab.org>
Signed-off-by: David Sterba <dsterba@suse.com>
In handle_indirect_tree_backref(), if we got @cur->level set to 7
(the max level valid), @Level will be 8, then later path->slots[level]
and path->nodes[level] will all go beyond the array boundary.

Fix it by rejecting such high level before calling btrfs_search_slot().

Link: https://sashiko.dev/#/bug/linux-8a4f92b4-daf7-4f57-8369-8e6ef323652f
Reviewed-by: Filipe Manana <fdmanana@suse.com>
Signed-off-by: Qu Wenruo <wqu@suse.com>
Signed-off-by: David Sterba <dsterba@suse.com>
In handle_indirect_tree_backref(), if we got a corrupted backref item
that has a valid level (e.g. 2), but higher than the subvolume root level
(e.g. 0), btrfs_search_slot() will return 0 or 1 depending on if the key
can be found in the leaf.

But the returned path->nodes[] will be all be NULL.

Later we call btrfs_node_blockptr(path->nodes[level]) will trigger a
NULL pointer dereference.

Fix it by checking if we got a valid eb pointer before calling
btrfs_node_blockptr(), and reject it as we can not find the parent tree
block.

Reviewed-by: Filipe Manana <fdmanana@suse.com>
Signed-off-by: Qu Wenruo <wqu@suse.com>
Signed-off-by: David Sterba <dsterba@suse.com>
…em()

check_extent_item() only verifies item_size >= sizeof(*ei) before
reading struct btrfs_tree_block_info on non-skinny tree block extent
items (BTRFS_EXTENT_ITEM_KEY with BTRFS_EXTENT_FLAG_TREE_BLOCK). A
crafted filesystem image with 24 <= item_size < 42 causes
btrfs_tree_block_level() to read past the item and potentially past the
extent buffer's populated folios.

Verify ptr + sizeof(*info) <= end before accessing
btrfs_tree_block_info, matching the inline ref bounds checks below.

Fixes: f82d1c7 ("btrfs: tree-checker: Add EXTENT_ITEM and METADATA_ITEM check")
Cc: stable@vger.kernel.org
Reviewed-by: Qu Wenruo <wqu@suse.com>
Signed-off-by: Elkin Cruz <elkin@google.com>
Signed-off-by: David Sterba <dsterba@suse.com>
In call_zone_finish() the counter for reserved active zones is
incremented without holding the per filesystem zone_active_bgs_lock
potentially leading to a race for the active zone count.

Reported-by: Sashiko <sashiko-bot@kernel.org>
Fixes: a7e1ac7 ("btrfs: zoned: reserve zones for an active metadata/system block group")
Reviewed-by: Damien Le Moal <dlemoal@kernel.org>
Signed-off-by: Johannes Thumshirn <johannes.thumshirn@wdc.com>
Signed-off-by: David Sterba <dsterba@suse.com>
…utdown

After shutting down the filesystem, if we attempt to start/join a
transaction, we will return -EROFS since we don't have any code in
transaction.c to explicitly check for the shutdown state, all we do is
check if fs_info->fs_error is not zero, and if it's not, return -EROFS.

Everywhere else in the code base we return -EIO if btrfs_is_shutdown()
returns true. Probably applications don't care about -EIO versus -EROFS
but this can trigger very sporadic failures in test generic/623 which
does this:

   xfs_io -x -c "mmap 0 4k" \
             -c "mwrite 0 4k" \
             -c shutdown \
             -c fsync \
             -c "mwrite 0 4k" $file

and expects the fsync to fail with -EIO, which normally does since by
the time the fsync is called there's usually delalloc from the mmap write
and when fsync flushes delalloc, it gets -EIO which comes from
cow_file_range(), where we return -EIO when btrfs_is_shutdown() returns
true and it gets propagated up the call chain to the fsync code.

However if delalloc happened to be flushed before fsync is called, due to
memory pressure, then when fsync flushes delalloc it does not get any
error since there is no more delalloc, but then when it attempts to start
a transaction it gets -EROFS and returns it to user space. This makes
generic/623 fail since it explicitly expects -EIO.

So change the transaction code to return -EIO instead of -EROFS when the
filesystem was shutdown. This avoids the very sporaric failures of
generic/623 and makes the return value consistent.

Reviewed-by: Qu Wenruo <wqu@suse.com>
Signed-off-by: Filipe Manana <fdmanana@suse.com>
Signed-off-by: David Sterba <dsterba@suse.com>
When an ordered extent ends at the zone capacity of its block group,
btrfs_zone_finish_endio() finishes the zones of the block group. Since
commit c428b76 ("btrfs: zoned: propagate do_zone_finish() error in
btrfs_zone_finish_endio()"), it returns the error of do_zone_finish().
btrfs_finish_one_ordered() then fails the ordered extent. It skips the
file extent item that points the file to the new data. It also frees the
new extent.

However, the data of the ordered extent is already written. Only the
ZONE_FINISH command failed, for example on one device of a RAID1 block
group. The write is still lost:

  O_DIRECT overwrite, the last extent ends at the zone capacity
  write and sync return 0
  ZONE_FINISH fails on one device
  btrfs_finish_one_ordered(): no file extent item, extent freed
  first O_DIRECT read of the file: -EIO (writeback error of the mapping)
  later reads, also after a remount: the old data of that extent

do_zone_finish() marks the block group as finished before it sends
ZONE_FINISH, so nothing writes to these zones anymore. Report the error
and let the ordered extent complete, as before that commit.

Fixes: c428b76 ("btrfs: zoned: propagate do_zone_finish() error in btrfs_zone_finish_endio()")
CC: stable@vger.kernel.org # 7.3+
Reviewed-by: Johannes Thumshirn <johannes.thumshirn@wdc.com>
Signed-off-by: Miroslav Cimerman <mc@raidlab.org>
Signed-off-by: David Sterba <dsterba@suse.com>
do_zone_finish() sends ZONE_FINISH to the zone of each stripe of a block
group. It stops at the first error and returns it, even if the profile
tolerates the failed device. Since commit 3d16abf ("btrfs: zoned:
directly call do_zone_finish() from btrfs_zone_finish_endio_workfn()"),
btrfs_zone_finish_endio_workfn() handles that error with
btrfs_handle_fs_error(). So one failed device of a RAID1 metadata block
group turns the filesystem read-only.

When the block group is allocated up to the zone capacity and
everything is written, the zones are already full on the devices. A
failed ZONE_FINISH does not change them. In this case, finish the zones
of all stripes. Like a write, fail only if more devices failed than the
profile tolerates. Count a missing device toward the limit. The failed
device keeps the zone counted as active until the zone is reset or the
filesystem is remounted. For metadata, the active zone reservation
comes back only at the next mount.

A partly written block group keeps the current behavior. It stops at
the first error and returns it. Finishing the zones after a failed one
would leave more zones at different write pointers.
btrfs_load_block_group_raid1() refuses such a block group at the next
mount.

Fixes: 3d16abf ("btrfs: zoned: directly call do_zone_finish() from btrfs_zone_finish_endio_workfn()")
CC: stable@vger.kernel.org # 6.18+: a18a6b9: btrfs: zoned: finish active block group cleanup if call_zone_finish() fails
Reviewed-by: Johannes Thumshirn <johannes.thumshirn@wdc.com>
Signed-off-by: Miroslav Cimerman <mc@raidlab.org>
Signed-off-by: David Sterba <dsterba@suse.com>
btrfs_relocate_block_group() finishes the zones of the block group
before it relocates it. Any error other than -EAGAIN hits a WARN_ON().
However, btrfs_zone_finish() also fails when a device fails ZONE_FINISH.
A device error is not a kernel bug, and relocation continues either way.

Print a warning instead.

Fixes: 7ae9bd1 ("btrfs: zoned: finish relocating block group")
Reviewed-by: Johannes Thumshirn <johannes.thumshirn@wdc.com>
Signed-off-by: Miroslav Cimerman <mc@raidlab.org>
Signed-off-by: David Sterba <dsterba@suse.com>
When a btrfs_bio had to be split, btrfs_bio_end_io() saves the first error
of any of its parts in the status field of the original btrfs_bio. The
part that completes last is supposed to load it into bi_status of the
original bio before calling the end_io handler, but that is only done if
that last part was successful:

	if (atomic_dec_and_test(&bbio->pending_ios)) {
		/* Load split bio's error which might be set above. */
		if (status == BLK_STS_OK)
			bbio->bio.bi_status = READ_ONCE(bbio->status);

If the last part failed, the assumption is that bi_status was set at the
top of the function. That is true if the last part is what is left of the
original bio. If it is a split bio, the assignment was done to the split
bio, which was freed right after. If the original bio has completed before
without an error, its bi_status is BLK_STS_OK and stays like that:

  original bio (tail)                 split bio (head)

  btrfs_bio_end_io(orig, OK)
    orig->bio.bi_status = OK
    pending_ios 2 -> 1
                                      btrfs_bio_end_io(split, IOERR)
                                        split->bio.bi_status = IOERR
                                        bio_put(split)
                                        cmpxchg(&orig->status, OK, IOERR)
                                        pending_ios 1 -> 0
                                        orig->end_io(), bi_status is OK

The end_io handler covers the whole range, so for a buffered read all the
folios are marked uptodate, including the ones that were never filled, and
read(2) returns their content instead of -EIO. For a write the ordered
extent is completed as if all the data had reached the device.

This can be reproduced with raid0 data on two devices, one of them slower
than the other and with a bad block, by reading a file whose last stripe
is on the fast device.

The saved status has the first error of all the parts, or BLK_STS_OK if
there was none, so always use it, and drop the store into bi_status at
the top of the function, which nothing reads anymore.

Fixes: d48e1de ("btrfs: fix error propagation of split bios")
CC: stable@vger.kernel.org # 6.6+
Tested-by: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
Tested-by: Miroslav Cimerman <mc@raidlab.org>
Reviewed-by: Qu Wenruo <wqu@suse.com>
Reviewed-by: Filipe Manana <fdmanana@suse.com>
Signed-off-by: Josef Bacik <josef@toxicpanda.com>
Signed-off-by: David Sterba <dsterba@suse.com>
If writepage_delalloc() runs the first delalloc ranges of a folio and
then btrfs_run_delalloc_range() fails, the blocks that already got an
ordered extent are finished with an error through
btrfs_mark_ordered_io_finished(), but their dirty bits are left set. The
next writeback then submits blocks whose ordered extent is gone, or is
about to be completed a second time.

Fix by clearing the dirty bits and cycling the writeback state for those
blocks, as submit_write_sector() does for a block it fails to submit.

Fixes: 72dad8e ("btrfs: fix double accounting race when btrfs_run_delalloc_range() failed")
CC: stable@vger.kernel.org # 5.15+
Reviewed-by: Qu Wenruo <wqu@suse.com>
Reviewed-by: Filipe Manana <fdmanana@suse.com>
Signed-off-by: Josef Bacik <josef@toxicpanda.com>
Signed-off-by: David Sterba <dsterba@suse.com>
If a COW write fails, or its ordered extent is truncated, the extent
maps of the part that was not written still point to the newly
allocated extent until the ordered extent completes. If a fast fsync
logs those extent maps first, replaying the log after a crash replaces
the file's old data with an extent that was never written.

BTRFS_INODE_COW_WRITE_ERROR is meant to make a fast fsync wait for the
ordered extents to complete in that case, but only
btrfs_finish_ordered_extent() sets it. A write that fails before a bio
is submitted, in writepage_delalloc() or submit_write_sector(), finishes
its ordered extent through btrfs_mark_ordered_io_finished(), which does
not set the flag. And since commit 66ff4d3 ("btrfs: fix false IO
failure after falling back to buffered write"), a direct IO write that
stops short truncates the rest of its ordered extent and finishes it as
uptodate, so the flag is not set either.

Fix this by setting the flag, renamed to
BTRFS_INODE_INCOMPLETE_COW_WRITE, in can_finish_ordered_extent() when a
write fails, and in btrfs_mark_ordered_extent_truncated(). Convert the
open-coded truncation in extent_writepage_io() to that helper, so that
every truncation sets the flag. Both places hold the inode's
ordered_tree_lock and run before BTRFS_ORDERED_IO_DONE is set.

The flag stays set until a fast fsync clears it, and that fsync then
waits for all ordered extents to complete, even if the failed or
truncated one completed long before. A direct IO write that stops short
because its buffer was not faulted in costs the next fast fsync one
such wait.

Fixes: f13e01b ("btrfs: ensure fast fsync waits for ordered extents after a write failure")
Fixes: 66ff4d3 ("btrfs: fix false IO failure after falling back to buffered write")
CC: stable@vger.kernel.org # 6.10+
Reviewed-by: Filipe Manana <fdmanana@suse.com>
Reviewed-by: Qu Wenruo <wqu@suse.com>
Signed-off-by: Josef Bacik <josef@toxicpanda.com>
Signed-off-by: David Sterba <dsterba@suse.com>
A fast fsync waits for writeback and then checks whether a write failed
or was truncated, in which case it waits for the ordered extents to
complete. The check can come too early, because end_bbio_data_write()
clears writeback before it finishes the ordered extent, which is where
a failure is recorded:

  end_bbio_data_write()            fsync

  btrfs_folio_clear_writeback()
                                   filemap_fdatawait_range()
                                   BTRFS_INODE_INCOMPLETE_COW_WRITE clear
                                   btrfs_log_changed_extents()
  btrfs_finish_ordered_extent()
    set BTRFS_INODE_INCOMPLETE_COW_WRITE

A direct IO write has no writeback for the fsync to wait for at all, so
the failure of an asynchronous direct IO write still in flight is missed
too.

The buffered case comes from commit a11d691 ("btrfs: remove folio
parameter from ordered io related functions"), which moved the call to
btrfs_finish_ordered_extent() after the loop that clears writeback. The
direct IO case has been there since commit f13e01b ("btrfs: ensure
fast fsync waits for ordered extents after a write failure") added the
flag.

Fix by having a fast fsync wait for BTRFS_ORDERED_IO_DONE on the ordered
extents it collected for logging before it checks. Since "btrfs: make
fsync wait for all incomplete COW writes", a failure or truncation is
recorded before that bit is set, and a barrier in
can_finish_ordered_extent() now orders the two, pairing with the fully
ordered test_and_clear_bit() of the flag in fsync. For a buffered write
the bit is set right after writeback is cleared. The writeback of a
buffered write that is not done yet is started first, and fsync returns
the error if that fails, since the rest of the ordered extent may then
not be submitted.

This depends on "btrfs: make fsync wait for all incomplete COW writes".

Fixes: a11d691 ("btrfs: remove folio parameter from ordered io related functions")
Fixes: f13e01b ("btrfs: ensure fast fsync waits for ordered extents after a write failure")
CC: stable@vger.kernel.org # 6.10+
Reviewed-by: Filipe Manana <fdmanana@suse.com>
Reviewed-by: Qu Wenruo <wqu@suse.com>
Signed-off-by: Josef Bacik <josef@toxicpanda.com>
Signed-off-by: David Sterba <dsterba@suse.com>
When a commit of the log root tree gives up, because the transaction
needs a full commit or writing the log failed, btrfs_sync_log() still
advances log_transid_committed and hands the result to the contexts on
the list. Unlike a successful commit it does not advance log_transid, so
the log transaction it just retired is still the one new syncs join.

A sync that gets to the log root tree after that adds its context to
the emptied list, sees log_transid_committed >= its log_transid and
returns its log_ret, which is still 0:

  fsync A (subvol 1)           rename       fsync B (subvol 2)

                                            btrfs_need_log_full_commit()
                                              -> false
                               btrfs_set_log_full_commit()
  btrfs_need_log_full_commit()
    -> true
  btrfs_remove_all_log_ctxs()
  log_transid_committed = N
  log_transid stays N
                                            log_transid = N, log_ret = 0
                                            log_transid_committed >= N
                                            return 0

btrfs_sync_file() then ends the transaction without committing it, and a
crash before A's transaction commit loses what B was told is durable.
This was reproduced with delays added to btrfs_sync_log().

Fix by advancing log_transid when a commit of the log root tree gives
up, so a later sync joins the next log transaction and either commits it
or gives up itself. The check for an already committed log transaction
can then no longer be true, so warn on debug builds if it is, and force
a full commit.

Fixes: d1433de ("Btrfs: just wait or commit our own log sub-transaction")
CC: stable@vger.kernel.org
Reviewed-by: Filipe Manana <fdmanana@suse.com>
Signed-off-by: Josef Bacik <josef@toxicpanda.com>
Signed-off-by: David Sterba <dsterba@suse.com>
FITRIM also discards the space of every device that is not allocated to a
chunk. btrfs_trim_free_extents() goes over fs_devices->devices and, for
each device that is writeable, discards the ranges that have neither
CHUNK_ALLOCATED nor CHUNK_TRIMMED set in device->alloc_state.

The target device of a running replace operation is on that list and it is
writeable. But its alloc_state is empty. The allocated ranges of the
source device are only copied to it by btrfs_set_target_alloc_state(),
when the replace finishes. Until then the whole device looks unallocated,
so an fstrim discards everything that was copied to it so far, and what is
being written to it in parallel to the source device.

The replace finishes without any error and the source device is dropped.
With a single device filesystem, 700M of data and fstrim called in a loop
while the replace runs:

  BTRFS info: dev_replace from /dev/vdb (devid 1) to /dev/vdc finished
  BTRFS error: bad tree block start, mirror 1 want 30638080 have 0
  BTRFS error: bad tree block start, mirror 2 want 30638080 have 0
  BTRFS info: scrub: not finished on devid 1 with status: -5

Skip the target device, and don't count it in btrfs_ioctl_fitrim()
either. The flag is cleared with the device list mutex held, after the
alloc_state was set up, and the trimming code holds that mutex while it
works on a device.

Fixes: 929be17 ("btrfs: Switch btrfs_trim_free_extents to find_first_clear_extent_bit")
CC: stable@vger.kernel.org
Reviewed-by: Qu Wenruo <wqu@suse.com>
Reviewed-by: Filipe Manana <fdmanana@suse.com>
Signed-off-by: Josef Bacik <josef@toxicpanda.com>
Signed-off-by: David Sterba <dsterba@suse.com>
RECLAIM_ZONES calls btrfs_reclaim_block_groups() to serve data space
tickets. That function takes the super write lock with
sb_start_write(). A writer waiting on such a ticket holds that lock
already, so a freeze waits for the writer while the reclaim waits for
the freeze:

  writer             freeze               async data reclaim
  ------             ------               ------------------
  sb_start_write()
  wait on a data
  space ticket
                     freeze_super()
                       wait for writers
                                          flush_space(RECLAIM_ZONES)
                                            btrfs_reclaim_block_groups()
                                              sb_start_write()
                                              wait for the freeze

Nothing serves the ticket, and all three wait.

Take the lock with sb_start_write_trylock() and skip the reclaim while
the filesystem is being frozen or is frozen. The space flushing goes on
with its next states. If they free nothing, the ticket fails with
ENOSPC, the same as when the reclaim is skipped for a running balance.
The block groups stay on the reclaim list, and the cleaner queues the
reclaim work again after the thaw.

The reclaim worker, which also runs on non-zoned filesystems, skips
during a freeze as well instead of waiting for the thaw. Commit
ca5e4ea ("btrfs: zoned: mark relocation as writing") added the lock
to keep relocations out of a frozen filesystem, and skipping them still
does that.

Fixes: e2a7fd2 ("btrfs: zoned: add zone reclaim flush state for DATA space_info")
CC: stable@vger.kernel.org # 7.1+
Reviewed-by: Johannes Thumshirn <johannes.thumshirn@wdc.com>
Signed-off-by: Miroslav Cimerman <mc@raidlab.org>
Signed-off-by: David Sterba <dsterba@suse.com>
When searching for a block-group to place to allocate data extents from,
honor the hint passed in if the hint falls within the range of an
already active block-group.

If the hint doesn't fall into an active block-group or the hinted
block-group does not have enough available space left, fall back to an
active block-group that has enough space left for the allocation.

Reviewed-by: Damien Le Moal <dlemoal@kernel.org>
Signed-off-by: Johannes Thumshirn <johannes.thumshirn@wdc.com>
Signed-off-by: David Sterba <dsterba@suse.com>
Save the last allocation of a data extent in the inode and if set use it
as a placement hint for a subsequent extent allocation in the extent
allocator.

Reviewed-by: Damien Le Moal <dlemoal@kernel.org>
Signed-off-by: Johannes Thumshirn <johannes.thumshirn@wdc.com>
Signed-off-by: David Sterba <dsterba@suse.com>
On zoned filesystems all data writers share the first active block-group
with free space, so extents of parallel writers interleave. This is
causing high fragmentation in the filesystem, that also potentially
increases the need for garbage collection.

If the allocation hint doesn't hit an active block-group with enough
space, e.g. for a new file or after its block-group filled up, and an
active zone can be spared, allocate from an empty block-group instead.
If no zone can be spared, spread allocations round-robin over the active
block-groups. Never finish a zone for this.

On an example null_blk device with 64M zones, max 12 active zones this
results in:

Test                          files/zone   extents/file
5 parallel O_DIRECT writers   5.0 -> 1.09  966 -> 74
4 files appended round-robin  4.0 -> 1.0   192 -> 3

Buffered parallel writers improve less (4.45 -> 3.09 files per zone):
block-groups with a leftover smaller than the next allocation keep their
active zone.

Reviewed-by: Damien Le Moal <dlemoal@kernel.org>
Signed-off-by: Johannes Thumshirn <johannes.thumshirn@wdc.com>
Signed-off-by: David Sterba <dsterba@suse.com>
If the hinted block-group has less space left than the allocation, the
allocation goes to a new block-group and the old one stays active with
its leftover. With buffered writes this happens for nearly every
block-group, the leftovers use up the active zones and new files fall
back to round-robin.

Shrink the allocation to the space left in the hinted block-group
instead, as long as it is not smaller than min_alloc_size. The
block-group becomes full, gets finished and releases its active zone.

5 parallel buffered writers on null_blk, 64M zones, max 12 active zones:
files per zone 3.09 -> 1.46, extents per file 29.6 -> 5.8.

Reviewed-by: Damien Le Moal <dlemoal@kernel.org>
Signed-off-by: Johannes Thumshirn <johannes.thumshirn@wdc.com>
Signed-off-by: David Sterba <dsterba@suse.com>
btrfs_chunk_alloc() coalesces concurrent allocations, so an empty
block-group request can end up without a chunk of its own when several
new files race.

Retry the chunk allocation a few times before giving up on an empty
block-group.

Reviewed-by: Damien Le Moal <dlemoal@kernel.org>
Signed-off-by: Johannes Thumshirn <johannes.thumshirn@wdc.com>
Signed-off-by: David Sterba <dsterba@suse.com>
Since commit 1dc4888 ("btrfs: scrub: avoid unnecessary extent tree
search preparing stripes") scrub keeps sctx->extent_path and
sctx->csum_path across the stripes of a block group, so the paths are
also held across the implementation of scrub pause in scrub_simple_mirror()
and scrub_raid56_parity_stripe().

Both use searches that set search_commit_root and skip_locking to true.
Meanwhile, the transaction critical section is exactly what issues a pause.
So if we populate sctx->extent_path/csum_path with nodes from a commit root,
then pause, then complete a commit critical section, those nodes refer
to the previous commit root, by construction.

These nodes could have been cowed and thus unpinned by the conclusion
of the transaction. It is generally not safe to refer to nodes from old
commit roots.

Therefore, we must drop these paths across pauses to ensure that after a
pause we do a new search in the current commit root. Otherwise we would
need to block the commit on the scrub which is obviously unacceptable.

This issue becomes particularly nasty with dev-replace scrubs which can
then try to use an invalid reallocated eb to populate the new device.

Fixes: 1dc4888 ("btrfs: scrub: avoid unnecessary extent tree search preparing stripes")
Reviewed-by: Qu Wenruo <wqu@suse.com>
Signed-off-by: Boris Burkov <boris@bur.io>
scrub_throttle_dev_io() sleeps with schedule_timeout_interruptible()
without pausing the scrub, while a transaction cannot enter a critical
section without pausing scrub. Thus, a transaction commit gets blocked
on a scrub throttle, which is completely backwards.

Furthermore, this sleep ignores attempts to cancel the scrub.

Improve the scrub throttling semantics by implementing it as a cancel
aware sleep wrapped in a pause.

Reviewed-by: Qu Wenruo <wqu@suse.com>
Signed-off-by: Boris Burkov <boris@bur.io>
scrub_throttle_dev_io() divides a time slice into up to 64 intervals
with the computation
  div = clamp(bwlimit / (16 * 1024 * 1024), 1, 64);
So at bwlimit below 16MiB/s, the time slice is unitary and above 1GiB/s
the slice is split into 64 intervals.

Each interval represents an opportunity to schedule IO and we set a
throttle deadline to now + time_slice / div. time_slice is 1000ms or 1s.

At each interval we count bio_size against bwlimit / div, or the portion
of the per second bwlimit for that interval. If it is under, we send the
bio with no throttling. Otherwise, we throttle till the end of the
interval then send the bio.

This ensures that we have a hard cap of 64 sleeps in a second which
ensures good throughput for typical unbounded or high limit scrubs.

But because bio_size is always 512KiB and we send at each interval, the
practical minimum limit is 512KiB/s, as we will send at least 512KiB
every second (the longest possible interval when div = 1).

To support lower limits without ruining throughput at higher limits,
change to a model which can sleep for an arbitrary duration to properly
amortize the data sent and acheive an average IO demand below bwlimit
for bwlimit < 512KiB/s.

However, at higher limits, because the unit of sending is still 512KiB,
sleeping between every IO for a naively calculated limit would be far
too many sleeps and adds unacceptable sleeping overhead, ruining our
ability to even submit at those limits. Therefore, we need to allow a
"burst duration" as a floor for the sleeping duration. 10ms is a
reasonable value: it is a similar number of sleeps at high limits (100
vs 64 per second) and is a responsive duration relatively commensurate
in scale with disk latencies and intuitively seems like it would not
be "too bursty" at any speed.

Reviewed-by: Qu Wenruo <wqu@suse.com>
Signed-off-by: Boris Burkov <boris@bur.io>
submit_initial_group_read() charges a whole group of
SCRUB_STRIPES_PER_GROUP stripes to the bwlimit at once and then submits
all of them, so the smallest unit of throttled read IO is 512KiB. With
a low limit that is a long burst followed by a long sleep: at 32KiB/s
it is 512KiB every 16 seconds. This is unnecessarily bursty even if we
do maintain the correct bandwidth on average.

Since the real unit of scrub IO is the stripe of 64k, throttle in
between stripes, rather than stripe groups. The block layer plug is
still in place for situations where the throttle does not kick in and we
don't sleep between stripes.

Reviewed-by: Qu Wenruo <wqu@suse.com>
Signed-off-by: Boris Burkov <boris@bur.io>
When over the dirty limit, relocate_one_folio() waits in
balance_dirty_pages() for the flusher to write back enough. The flusher
skips a filesystem whose s_umount is held for writing, but an unmount
and a remount read-only hold it while they wait for a relocation by the
reclaim work to finish: close_ctree() in cancel_work_sync(), and
btrfs_remount_ro() in btrfs_commit_super() for the cleaner_mutex the
relocation holds. Nothing else is sure to write back the relocated
data, and both hang:

  task:kworker/u16:1   state:D
  Workqueue: events_unbound btrfs_reclaim_bgs_work
   balance_dirty_pages
   relocate_file_extent_cluster
   relocate_data_extent.constprop.0
   relocate_block_group
   btrfs_relocate_block_group
   btrfs_relocate_chunk
   btrfs_reclaim_block_groups
  task:umount          state:D
   cancel_work_sync
   close_ctree
   generic_shutdown_super
   kill_anon_super
   btrfs_kill_super

The same goes for a resumed balance, which both wait for in
btrfs_pause_balance(), and for the relocation of the zoned
RECLAIM_ZONES space flushing, whose work both cancel.

When balance_dirty_pages() would make us wait, start writeback of the
data relocation inode first, then wait as before. Writeback errors are
still reported by btrfs_wait_ordered_range() at the end of the stage.

Fixes: 18bb8bb ("btrfs: zoned: automatically reclaim zones")
CC: stable@vger.kernel.org # 6.1+
Signed-off-by: Miroslav Cimerman <mc@raidlab.org>
Reviewed-by: Johannes Thumshirn <johannes.thumshirn@wdc.com>
When no zone can be activated, buffered writeback in cow_file_range() and
direct IO in btrfs_new_extent_direct() wait uninterruptibly for
BTRFS_FS_NEED_ZONE_FINISH to be cleared, which only happens once a zone
is finished.

After a transaction abort or an emergency shutdown no zone gets finished
anymore, so the waiters sleep forever. With writeback holding locked
folios, btrfs_cleanup_transaction() then blocks in
invalidate_inode_pages2_range() as well. generic/388 hangs this way.

Clear the bit and wake the waiters when the filesystem error is set,
clear it again if it gets set after an error was recorded, and let the
waiters bail out with the filesystem error.

Fixes: 2ce543f ("btrfs: zoned: wait until zone is finished when allocation didn't progress")
Fixes: 776a838 ("btrfs: zoned: wait for data BG to be finished on direct IO allocation")
Reviewed-by: Naohiro Aota <naohiro.aota@wdc.com>
Signed-off-by: Johannes Thumshirn <johannes.thumshirn@wdc.com>
Currently we are allowing rename exchange operations when one of the paths
points to a subvolume stub (created with new_simple_dir(), due to creating
a snapshot of a subvolume that has subvolumes inside it). This results in
a transaction abort, turning the filesystem into RO mode, since the stubs
are mockup dentries that have no underlying inode, so attempting to search
and delete inode ref items fails during the rename exchange, leading to a
transaction abort with -ENOENT:

  $ cat test.sh
  #!/bin/bash

  DEV=/dev/sdi
  MNT=/mnt/sdi

  mkfs.btrfs -f $DEV
  mount $DEV $MNT

  btrfs subvolume create $MNT/subvol
  btrfs subvolume create $MNT/subvol/inner_subvol

  touch $MNT/subvol/file

  btrfs subvolume snapshot $MNT/subvol $MNT/snap

  mv --exchange -T $MNT/snap/file $MNT/snap/inner_subvol

  umount $MNT

Running it:

  $ ./test.sh
  (...)
  Create subvolume '/mnt/sdi/subvol'
  Create subvolume '/mnt/sdi/subvol/inner_subvol'
  Create snapshot of '/mnt/sdi/subvol' in '/mnt/sdi/snap'
  mv: cannot exchange '/mnt/sdi/snap/file' and '/mnt/sdi/snap/inner_subvol': No such file or directory

And dmesg shows a transaction abort:

  $ dmesg
  [277913.996925] BTRFS critical (device sdi): failed to delete reference to inner_subvol, root 258 inode 2 parent 256
  [277913.996950] ------------[ cut here ]------------
  [277913.996951] WARNING: fs/btrfs/inode.c:4399 at __btrfs_unlink_inode+0x3a8/0x420 [btrfs], CPU#0: mv/1549646
  [277914.001156] Modules linked in: btrfs dm_dust loop (...)
  [277914.016365] CPU: 0 UID: 0 PID: 1549646 Comm: mv Tainted: G        W           7.4.0-rc4-btrfs-next-252+ #1 PREEMPT(full)
  [277914.018964] Tainted: [W]=WARN
  [277914.019622] Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS rel-1.16.2-0-gea1b7a073390-prebuilt.qemu.org 04/01/2014
  [277914.021892] RIP: 0010:__btrfs_unlink_inode+0x3a8/0x420 [btrfs]
  [277914.023185] Code: 85 c0 78 (...)
  [277914.026865] RSP: 0018:ffffd33e801dfb80 EFLAGS: 00010206
  [277914.028098] RAX: 00000000fffffffe RBX: ffff8c89cc89e000 RCX: 0000000000000000
  [277914.030305] RDX: 000000000000001c RSI: 0000000000000001 RDI: ffff8c89c4bb12c0
  [277914.031978] RBP: ffff8c8f542a9d80 R08: 3fffffffffefffff R09: 0000000000014b83
  [277914.033448] R10: ffffd33e801df840 R11: 0000000000000002 R12: ffff8c8f543bf838
  [277914.034891] R13: ffffd33e801dfca8 R14: ffff8c89defee000 R15: ffff8c89e4c31a10
  [277914.036370] FS:  00007f709e183840(0000) GS:ffff8c913f2ce000(0000) knlGS:0000000000000000
  [277914.037984] CS:  0010 DS: 0000 ES: 0000 CR0: 0000000080050033
  [277914.039144] CR2: 00007f709e29ba80 CR3: 0000000524f02004 CR4: 0000000000370ef0
  [277914.040585] Call Trace:
  [277914.041107]  <TASK>
  [277914.041584]  btrfs_rename_exchange+0x37b/0xbf0 [btrfs]
  [277914.042734]  ? inode_set_ctime_current+0x3b/0x220
  [277914.043690]  btrfs_rename2+0x53/0x60 [btrfs]
  [277914.044648]  vfs_rename+0x5b4/0xe40
  [277914.045371]  filename_renameat2+0x222/0x450
  [277914.046256]  __x64_sys_renameat2+0x4e/0x70
  [277914.047091]  do_syscall_64+0x8b/0x490
  [277914.047902]  entry_SYSCALL_64_after_hwframe+0x76/0x7e
  [277914.048912] RIP: 0033:0x7f709e29ba8f
  [277914.049717] Code: 44 00 00 (...)
  [277914.054201] RSP: 002b:00007fff08b22438 EFLAGS: 00000202 ORIG_RAX: 000000000000013c
  [277914.055699] RAX: ffffffffffffffda RBX: 00007fff08b242d2 RCX: 00007f709e29ba8f
  [277914.057110] RDX: 00000000ffffff9c RSI: 00007fff08b242d2 RDI: 00000000ffffff9c
  [277914.058534] RBP: 00007fff08b242e5 R08: 0000000000000002 R09: 0000000000000001
  [277914.059942] R10: 00007fff08b242e5 R11: 0000000000000202 R12: 0000000000000002
  [277914.061336] R13: 00000000ffffff9c R14: 00000000ffffff9c R15: 00007fff08b22a90
  [277914.062754]  </TASK>
  [277914.063232] ---[ end trace 0000000000000000 ]---
  [277914.064191] BTRFS error (device sdi state A): Transaction 10 aborted (-ENOENT)
  [277914.064195] BTRFS: error (device sdi state A) in __btrfs_unlink_inode:4399: errno=-2 No such entry
  [277914.064197] BTRFS info (device sdi state EA): forced readonly
  [277914.064199] BTRFS: error (device sdi state EA) in btrfs_rename_exchange:8458: errno=-2 No such entry

Fix this by rejecting rename exchange operations against dentries that are
subvolume stubs.

Reported-by: Tianyu Chen <chentianyu@microsoft.com>
Link: https://lore.kernel.org/linux-btrfs/TY8P153MB237624AA8DAAC5323DE20B46DF412@TY8P153MB2376.APCP153.PROD.OUTLOOK.COM/
Fixes: cdd1fed ("btrfs: add support for RENAME_EXCHANGE and RENAME_WHITEOUT")
Reviewed-by: Qu Wenruo <wqu@suse.com>
Signed-off-by: Filipe Manana <fdmanana@suse.com>
Reviewed-by: David Sterba <dsterba@suse.com>
When btrfs_alloc_tree_block() fails after btrfs_reserve_extent() has
succeeded, its error path gives the block back to the block reserve,
although the block has already left bytes_may_use. Each such failure
leaves bytes_may_use a block short, and it underflows and warns in
space-info.h when the global block reserve is released at unmount, or
earlier.

  btrfs_alloc_tree_block()
  |- btrfs_use_block_rsv()
  |- btrfs_reserve_extent()
  |  \- btrfs_add_reserved_bytes()  <- bytes_may_use -= blocksize
  |- btrfs_init_new_buffer()
  |  \- alloc_extent_buffer()       <- fails with -ENOMEM
  |- btrfs_free_reserved_extent()   <- bytes_reserved -= blocksize
  \- btrfs_unuse_block_rsv()        <- block rsv += blocksize again

Since commit 19d7f65 ("btrfs: convert the buffer_radix to an
xarray") in 6.16, alloc_extent_buffer() can fail this way under memory
cgroup pressure, because fs_info->buffer_tree is memcg-accounted.

Return without giving the block back once btrfs_reserve_extent() has
succeeded.

Fixes: 67b7859 ("btrfs: handle ENOMEM in btrfs_alloc_tree_block")
Cc: stable@vger.kernel.org # 6.16+
Reviewed-by: Boris Burkov <boris@bur.io>
Signed-off-by: Vlad Poenaru <vlad.wing@gmail.com>
Reviewed-by: Qu Wenruo <wqu@suse.com>

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

Development

Successfully merging this pull request may close these issues.