summaryrefslogtreecommitdiff
AgeCommit message (Collapse)Author
2026-10-12btrfs: qgroup: fix leak of qgroups in rb tree after failure to enable quotasFilipe Manana
When enabling quotas we add struct btrfs_qroup items to the rbtree fs_info->qgroup_tree, however if there's an error during the quota enable operation after adding those items, we exit without removing the items from the rbtree and freeing them. Fix this by calling btrfs_free_qgroup_config() on error, which also deletes all sysfs entries (it calls btrfs_sysfs_del_qgroups()). Reviewed-by: Qu Wenruo <wqu@suse.com> Signed-off-by: Filipe Manana <fdmanana@suse.com> Reviewed-by: David Sterba <dsterba@suse.com> Signed-off-by: David Sterba <dsterba@suse.com>
2026-10-12btrfs: qgroup: abort transaction on failure to add qgroup relationFilipe Manana
When adding a qgroup relation, if we fail to add the relation item from "dst" to "src", we attempt to delete the relation item from "src" to "dst" that we added just before, however we ignore the deletion result and if we failed to delete we leave an inconsistency in the quota root. So check the result of the deletion and if it fails, abort the transaction to avoid persisting an inconsistent state. Reviewed-by: Qu Wenruo <wqu@suse.com> Signed-off-by: Filipe Manana <fdmanana@suse.com> Reviewed-by: David Sterba <dsterba@suse.com> Signed-off-by: David Sterba <dsterba@suse.com>
2026-10-12btrfs: qgroup: fix swapped blocks existence check when tracing after COWFilipe Manana
In btrfs_qgroup_trace_subtree_after_cow(), after we erase the swapped block, iterate over all possible tree levels to check if we sill have other swapped blocks. However the check is wrong, it considers that there are other swapped blocks if any rbtree for any level is empty, instead of not empty. As a consequence we set blocks->swapped to true basically every time since we always find an empty rbtree at least at level 7, since in practice it's nearly impossible to find such a huge btree. This makes every future call to btrfs_qgroup_trace_subtree_after_cow() do an unnecessary rbtree search instead of returning immediately. Fix this by updating the condition to set swapped to true if we find an rbtree that is not empty. Fixes: f616f5cd9da7 ("btrfs: qgroup: Use delayed subtree rescan for balance") Reviewed-by: Qu Wenruo <wqu@suse.com> Signed-off-by: Filipe Manana <fdmanana@suse.com> Signed-off-by: David Sterba <dsterba@suse.com>
2026-10-12btrfs: introduce more accurate usebackuproot optionsQu Wenruo
Previously we had no way to tell btrfs to use which backup slot, but always use the newest backup, and retry until all backup roots are exhausted. This doesn't give any control to the end user, even if the end user wants to use a specific backup slot. To address this problem, allow more fine-control on usebackuproot rescue option by introducing the following 4 rescue mount options: - rescue=usebackuproot_0 - rescue=usebackuproot_1 - rescue=usebackuproot_2 - rescue=usebackuproot_3 The number 0 means the newest slot, which should be the same as the one recorded in the super block and no need to load any backup root. 1/2/3 means the second/third/fourth(oldest) backup slot to use. The existing "rescue=usebackuproot" is just an alias of "rescue=usebackuproot_1". This will allow users to choose which backup root to use, thus can have a better control than blindly choose any slot that can pass the very basic root node checks. Reviewed-by: Boris Burkov <boris@bur.io> Signed-off-by: Qu Wenruo <wqu@suse.com> Signed-off-by: David Sterba <dsterba@suse.com>
2026-10-12btrfs: always use the second newest slot for rescue=usebackuprootQu Wenruo
[RESCUE FAILURE] There is a bug report that "rescue=usebackuproot" failed to properly mount the fs, but if using btrfs-mod-sb to use the second newest slot, then the fs can even pass the full "btrfs check" and be mounted RW. [CAUSE] During init_tree_roots(), "rescue=usebackuproot" only makes a difference if the tree and chunk roots failed to be load. The loading only requires the root node/leaf to be properly loaded: - tree root - extent tree - block group tree - device tree - data reloc tree - quota tree (optional) - uuid tree - raid stripe tree (for RST feature) And it doesn't really check any child tree blocks, thus for a lot of cases, "rescue=usebackuproot" won't make a difference. [ENHANCEMENT] Instead of trying every slot and settling down on the first passing backup slot, always use the second newest slot. The newest slot should always match the root info in the super block, and if it worked the end user should not even need to bother to use backup root. Older backup slots normally have a very low chance to work. Link: https://github.com/kdave/btrfs-progs/issues/1162#issuecomment-5475477108 Reviewed-by: Boris Burkov <boris@bur.io> Signed-off-by: Qu Wenruo <wqu@suse.com> Signed-off-by: David Sterba <dsterba@suse.com>
2026-10-12btrfs: raid56: do not verify the content if there is no data checksumQu Wenruo
[BUG] There is a bug report that fio can fail to sync the data on a degraded RAID56 mount: # mkfs.btrfs -m raid1 -d raid5 -f $dev1 $dev2 $dev3 # mount $dev1 $mnt # btrfs balance start -d $mnt # umount $mnt # btrfs dev scan -u $dev2 # wipefs -fa $dev2 # mount -o degraded $dev1 $mnt # fio --name=degraded-write --directory=$mnt --rw=randwrite --fdatasync=4 \ --bs=4k --size=512M --randrepeat=1 The run will fail at fsync: fio: io_u error on file /mnt/btrfs/degraded-write.0.0: Input/output error: datasync offset=142254080, buflen=0 fio: pid=2064, err=5/file:io_u.c:2008, func=io_u error, error=Input/output error [CAUSE] With extra debug output, it shows the problem pretty well: rbio=2876243968 faila=0 sectornr=0 rbio=2876243968 error=0-15 csum=2 bio=15 The first line shows the rbio's full stripe logical, and stripe/sector number when verify_one_sector() failed. The second line shows more detail about the rbio, the sector range [0, 16) is corrupted, which indicates the first data stripe is corrupted, matching the missing device. The important part is that the csum bitmap shows the data csum is only for sector number 2, meanwhile the failed verification is at sector number 0. This means we did the checksum verification even if no corresponding checksum is populated. [FIX] There is already a similar check at verify_bio_data_sectors(), but unfortunately there is no such check at verify_one_sector(). Add the missing check to skip the csum verification if there is no corresponding data checksum. Reported-by: Bartosz Fenski <bartosz@fenski.pl> Link: https://lore.kernel.org/linux-btrfs/a72409af-45ef-45df-9970-2e38bcb22ea6@fenski.pl/ Fixes: 7a3150723061 ("btrfs: raid56: do data csum verification during RMW cycle") CC: stable@vger.kernel.org Reviewed-by: Filipe Manana <fdmanana@suse.com> Signed-off-by: Qu Wenruo <wqu@suse.com> Signed-off-by: David Sterba <dsterba@suse.com>
2026-10-12btrfs: qgroup: do not leak -ENOENT from btrfs_remove_qgroup()Qu Wenruo
If btrfs_remove_qgroup() is called on a qgroup that only exists in the rb-tree, then del_qgroup_item() will return -ENOENT, and we tolerate that -ENOENT. However if the to-be-deleted qgroup has no parent qgroups, the @ret will not be updated, and will leak to user space. It will make the ioctl() caller incorrectly assume the operation failed. Fix it by resetting @ret to 0 after a successful or tolerated del_qgroup_item() call, so the -ENOENT from del_qgroup_item() won't be leaked. Assisted-by: LLM (exposing this pre-existing problem) Reviewed-by: Filipe Manana <fdmanana@suse.com> Signed-off-by: Qu Wenruo <wqu@suse.com> Signed-off-by: David Sterba <dsterba@suse.com>
2026-10-12btrfs: qgroup: use qgroup_mark_inconsistent() in quick_update_accounting()Qu Wenruo
When quick_update_accounting() fails to handle a qgroup which is not fully exclusive (its exclusive number doesn't match the reference one), we have to mark the qgroup inconsistent. Unlike other locations we didn't use qgroup_mark_inconsistent(), thus when such problem happens no extra error message is shown. Use the helper in quick_update_accounting(), which does not only show the reason of marking qgroup inconsistent, but also cancels any running rescan and skips dirty accounting, avoiding wasting CPU time on already inconsistent qgroup numbers. Reviewed-by: Filipe Manana <fdmanana@suse.com> Signed-off-by: Qu Wenruo <wqu@suse.com> Signed-off-by: David Sterba <dsterba@suse.com>
2026-10-12btrfs: qgroup: do not treat "ret > 0" as error when deleting a qgroupQu Wenruo
[BUG] There is a bug report that when removing a child qgroup, if removing the qgroup requires a rescan, it will delete the on-disk relation and qgroup items but not the in-memory qgroup rb entry. This makes all later qgroup rescan to fail. [CAUSE] The call chain looks like the following: btrfs_remove_qgroup() |- __del_qgroup_relation() | |- quick_update_accounting() | Which returns 1, showing this operation will require | a qgroup rescan |- if (ret) goto out; Which skips the del_qgroup_rb() call, leaving the in-memory qgroup rb entry still intact. Then later qgroup rescan/update will always fail and mark qgroup inconsistent: btrfs_run_qgroups() |- update_qgroup_info_item() | |- btrfs_search_slot() | Which returns -ENOENT, as the qgroup info item is already | deleted. |- qgroup_mark_inconsistent() |- return -ENOENT; [FIX] Do not treat "ret > 0" as an error. Reported-by: c.f.a@posteo.de Link: https://lore.kernel.org/linux-btrfs/14846642-85d3-4afb-ad99-1b74b22f5f90@posteo.de/ Fixes: 9c8b35b1ba21 ("btrfs: quota: Automatically update related qgroups or mark INCONSISTENT flags when assigning/deleting a qgroup relations.") Reviewed-by: Filipe Manana <fdmanana@suse.com> Signed-off-by: Qu Wenruo <wqu@suse.com> Signed-off-by: David Sterba <dsterba@suse.com>
2026-10-12btrfs: remove unnecessary forward struct declarations in volumes.hFilipe Manana
There is no need to forward declare the structures as their definitions are brought in by the include of the linux/blkdev.h and fs.h files. Reviewed-by: Qu Wenruo <wqu@suse.com> Signed-off-by: Filipe Manana <fdmanana@suse.com> Reviewed-by: David Sterba <dsterba@suse.com> Signed-off-by: David Sterba <dsterba@suse.com>
2026-10-12btrfs: remove pointless qgroup assignment in block_rsv_release_bytes()Filipe Manana
If num_bytes == (u64)-1, there's no point to set qgroup_to_release to block_rsv->qgroup_rsv_size as later on we will overwrite that value without ever reading the variable before that. So simplify things and remove that assignment. Reviewed-by: Qu Wenruo <wqu@suse.com> Signed-off-by: Filipe Manana <fdmanana@suse.com> Reviewed-by: David Sterba <dsterba@suse.com> Signed-off-by: David Sterba <dsterba@suse.com>
2026-10-12btrfs: remove fs_info argument from btrfs_block_rsv_refill()Filipe Manana
The fs_info argument is not used, so remove it. Reviewed-by: Qu Wenruo <wqu@suse.com> Signed-off-by: Filipe Manana <fdmanana@suse.com> Reviewed-by: David Sterba <dsterba@suse.com> Signed-off-by: David Sterba <dsterba@suse.com>
2026-10-12btrfs: remove fs_info argument from btrfs_block_rsv_add()Filipe Manana
The fs_info argument is not used, so remove it. Reviewed-by: Qu Wenruo <wqu@suse.com> Signed-off-by: Filipe Manana <fdmanana@suse.com> Reviewed-by: David Sterba <dsterba@suse.com> Signed-off-by: David Sterba <dsterba@suse.com>
2026-10-12btrfs: fix off-by-one end offset check in report_setget_bounds()Filipe Manana
The addressable range with an extent buffer goes from byte 0 to byte eb->len - 1, so if a byte address matches eb->len, it's already beyond the addressable range and we should log that it's bad start address and not end address. Fixes: 234fdd2815ce ("btrfs: remove redundant check in up check_setget_bounds") Reviewed-by: Qu Wenruo <wqu@suse.com> Reviewed-by: Daniel Vacek <neelx@suse.com> Signed-off-by: Filipe Manana <fdmanana@suse.com> Reviewed-by: David Sterba <dsterba@suse.com> Signed-off-by: David Sterba <dsterba@suse.com>
2026-10-12btrfs: avoid overhead when logging messages if fs state is cleanFilipe Manana
If the fs state does not have any errors and is not in some special state (like emergency shutdown or mounted with rescue options), then in btrfs_state_to_string() we end up doing a memcpy() into the buffer and then later just undo that work by setting the buffer's first element to the NUL terminator, since fs_info->fs_error is 0 and there is no bit set in fs_info->fs_state. Improve on this by returning early if there's no error in the fs and the fs state is clean, which is the expected scenario for a healthy fs that is not mounted with special options like the rescue options. Reviewed-by: Qu Wenruo <wqu@suse.com> Signed-off-by: Filipe Manana <fdmanana@suse.com> Signed-off-by: David Sterba <dsterba@suse.com>
2026-10-12btrfs: remove unnecessary pointer increment in btrfs_state_to_string()Filipe Manana
There's no point in incrementing the local pointer after we set the NUL terminator, as we don't use the pointer anymore after that. Reviewed-by: Qu Wenruo <wqu@suse.com> Signed-off-by: Filipe Manana <fdmanana@suse.com> Reviewed-by: David Sterba <dsterba@suse.com> Signed-off-by: David Sterba <dsterba@suse.com>
2026-10-12btrfs: add missing code for no delayed iput fs state in log messagesFilipe Manana
Add a letter code for the BTRFS_FS_STATE_NO_DELAYED_IPUT fs state, which is currently missing and it's useful to have. Reviewed-by: Qu Wenruo <wqu@suse.com> Signed-off-by: Filipe Manana <fdmanana@suse.com> Reviewed-by: David Sterba <dsterba@suse.com> Signed-off-by: David Sterba <dsterba@suse.com>
2026-10-12btrfs: fix duplicated code in fs state string in logged messagesFilipe Manana
We are using the code 'E' when the fs is in an error state (transaction aborted) and when it's in the emergency shutdown state, which is confusing and not intentional. Fix this by using an unused code such as 'H' for the emergency shutdown state and add a comment over the fs_state_chars array to warn to not use 'E' as its use is not defined in the array but instead in the function btrfs_state_to_string(), since the fs state error is not defined as a bit but as an error code in fs_info->fs_error. Fixes: 9b2839451dfc ("btrfs: introduce a new shutdown state") Reviewed-by: Qu Wenruo <wqu@suse.com> Signed-off-by: Filipe Manana <fdmanana@suse.com> Reviewed-by: David Sterba <dsterba@suse.com> Signed-off-by: David Sterba <dsterba@suse.com>
2026-10-12btrfs: fix incomplete iteration over fs state when logging messagesFilipe Manana
In btrfs_state_to_string() we iterate over all the bits set in fs_info->fs_state using for_each_set_bit(), which requires its third argument to match the number of bits, but we pass it the number of bytes of the type used by fs_info->fs_state, an unsigned long, which is 8 on 64 bits platforms and 4 on 32 bits platforms. This means we are not iterating over bits in the ranges [8, 63] or [4, 31]. Fix this by passing BTRFS_FS_STATE_COUNT instead of sizeof(fs_state). Note that we could pass BITS_PER_TYPE(fs_state), but since BTRFS_FS_STATE_COUNT is 11 and we have no bits beyond that, it would cause pointless iterations over fs_state. This also makes pointless the checks for the bit being inside the limit of BTRFS_FS_STATE_COUNT inside the loop. Fixes: c067da878156 ("btrfs: add filesystems state details to error messages") Reviewed-by: Qu Wenruo <wqu@suse.com> Signed-off-by: Filipe Manana <fdmanana@suse.com> Signed-off-by: David Sterba <dsterba@suse.com>
2026-10-12btrfs: zoned: fix double list add in btrfs_load_block_group_zone_infoJohannes Thumshirn
For DUP and RAID profiles with zones in a mismatching active state, i.e. due to one of the zones of the block-group being on a conventional zone, btrfs_zone_activate() has already put the block group on the list. This leads to a double list add and refcounting problems. Fixes: 265f7237dd25 ("btrfs: zoned: allow DUP on meta-data block groups") Fixes: 568220fa9657 ("btrfs: zoned: support RAID0/1/10 on top of raid stripe tree") Reviewed-by: Daniel Vacek <neelx@suse.com> Signed-off-by: Johannes Thumshirn <johannes.thumshirn@wdc.com> Signed-off-by: David Sterba <dsterba@suse.com>
2026-10-12btrfs: commit after deleting an unused block group if system space is lowBoris Burkov
If the device is fully allocated and the system space_info has no room for a second copy of the chunk tree, deleting many unused block groups in one transaction aborts it with -ENOSPC in btrfs_remove_chunk(). While we can get ahead of this problem in practice by allocating the system space more aggressively, that doesn't help a system that already got into this state anyway. In particular, this would be a problem on systems that got into this state on old code from before that improvement, but it is also a backstop in case we do mess up and still end up with too little system space. The way we end up needing a lot of system chunk space in practice is if we need to delete many bgs at once, resulting in touching many nodes/leaves in the chunk tree. Therefore, if we detect we are in a condition where we are low on system space, commit a single transaction deleting a single bg, which should not need much system chunk space. After this we have the freed bg and can proceed as usual. Any additional chunk allocations (for any reason) will also check the system space and are very likely to allocate more system space, so this should be a relatively robust mechanism. Assisted-by: LLM Reviewed-by: Filipe Manana <fdmanana@suse.com> Signed-off-by: Boris Burkov <boris@bur.io> Signed-off-by: David Sterba <dsterba@suse.com>
2026-10-12btrfs: allocate additional SYSTEM space earlierBoris Burkov
Currently, reserve_chunk_space() allocates a new system chunk when the space left is smaller than the reservation for a single chunk tree update. Therefore, a filesystem in single metadata mode on a very large block device can accumulate tens of thousands (TB) of chunks while never allocating more than the original 4MiB SYSTEM block group created by mkfs. If it then fills up (with large fallocates for example) and then that data is freed, en-masse, we end up trying to delete thousands of block groups in a single transaction in btrfs_delete_unused_bgs(). This process touches most of the nodes and leaves of the chunk tree, essentially trying to allocate roughly double the current usage of the chunk tree for cow. When this runs into needing a fresh system chunk, the fs is full of the empty bgs and we abort with ENOSPC in btrfs_remove_chunk() like: BTRFS error (device loop0 state A): Transaction 30733 aborted (-ENOSPC) space_info SYSTEM (sub-group id 0) has 0 free, is not full space_info total=4194304, used=3276800, pinned=0, reserved=917504, may_use=0, readonly=0 zone_unusable=0 BTRFS: error (device loop0 state A) in btrfs_remove_chunk:3643: errno=-28 No space left This was seen on a 30TiB production filesystem with 10TiB of unused block groups and reproduces on a 30TiB sparse loop device: mkfs with -m single, fallocate 1GiB files until ENOSPC, delete two of every three adjacent files, sync. To fix this, we should allocate the (relatively tiny) system chunks a little bit more eagerly. If we do it when it is half full, we ensure we can delete all of the block groups in one go. To fill up half of a 4MiB system bg requires thousands of block_groups so this should only affect very large fileystems. Assisted-by: LLM Reviewed-by: Filipe Manana <fdmanana@suse.com> Signed-off-by: Boris Burkov <boris@bur.io> Signed-off-by: David Sterba <dsterba@suse.com>
2026-10-12btrfs: remove __TRANS_* flagsQu Wenruo
After patch "btrfs: remove __TRANS_FREEZABLE", each TRANS_* flag is just the corresponding single-bit __TRANS_* flag. There is no need to split __TRANS_* and TRANS_* flags, just remove __TRANS_* flags and use TRANS_* flags instead. Since every TRANS_* flag is a single bit, do extra cleanups: - Add an ASSERT() in start_transaction() To make sure there is only a single bit set in @type - Rename TRANS_EXTWRITERS to TRANS_EXTWRITERS_MASK To follow the naming scheme that a multi-bit value has the _MASK suffix. Reviewed-by: Filipe Manana <fdmanana@suse.com> Signed-off-by: Qu Wenruo <wqu@suse.com> Reviewed-by: David Sterba <dsterba@suse.com> Signed-off-by: David Sterba <dsterba@suse.com>
2026-10-12btrfs: remove __TRANS_FREEZABLEQu Wenruo
Inside transaction.c most TRANS_* flags are just a single bit, but there are 2 exceptions: - TRANS_START Which is (__TRANS_START | __TRANS_FREEZABLE) - TRANS_JOIN Which is (__TRANS_JOIN | __TRANS_FREEZABLE) The extra __TRANS_FREEZABLE flag indicates that those operations need to acquire sb intwrite lock to handle fs freezing. However since there are only two operations requiring sb intwrite lock, there is no need to introduce a dedicated flag for it, we can introduce a new TRANS_SB_INTWRITER_MASK to cover the only two cases, then use that new mask to determine whether the type requires sb intwrite lock. This makes all TRANS_* flags a single bit. Reviewed-by: Filipe Manana <fdmanana@suse.com> Signed-off-by: Qu Wenruo <wqu@suse.com> Reviewed-by: David Sterba <dsterba@suse.com> Signed-off-by: David Sterba <dsterba@suse.com>
2026-10-12btrfs: move __TRANS_* and TRANS_* flags out of transaction.hQu Wenruo
Among all those flags, only __TRANS_DUMMY is used outside of transaction.[ch], and there are only two places using it: - find_parent_nodes() Introduce a helper, btrfs_trans_is_dummy(), for this call site. - btrfs_init_dummy_trans() Move the function into transaction.[ch], and hide it behind CONFIG_BTRFS_FS_RUN_SANITY_TESTS. With the above changes, we can hide __TRANS_* and TRANS_* flags inside transaction.c. This allows us to modify those flags in the future without causing any changes to existing callers. After the flags relocation, now we can also hide __TRANS_DUMMY behind CONFIG_BTRFS_FS_RUN_SANITY_TESTS. Reviewed-by: Filipe Manana <fdmanana@suse.com> Signed-off-by: Qu Wenruo <wqu@suse.com> Reviewed-by: David Sterba <dsterba@suse.com> Signed-off-by: David Sterba <dsterba@suse.com>
2026-10-12btrfs: simplify dir item location setup in btrfs_insert_xattr_item()Filipe Manana
The location (a btrfs_disk_key) of a btrfs_dir_item used for a xattr is always zeroed and we have a complex setup in btrfs_insert_xattr_item() where we declare an on stack btrfs_key, zero it out, convert it into a btrfs_disk_key, also declared on stack, and then pass that btrfs_disk_key to a btrfs_set_dir_item_key() call. We can simplify this, and save stack space (one btrfs_disk_key and one btrfs_key), by simply using memzero_extent_buffer(). Reviewed-by: Qu Wenruo <wqu@suse.com> Signed-off-by: Filipe Manana <fdmanana@suse.com> Signed-off-by: David Sterba <dsterba@suse.com>
2026-10-12btrfs: use assign_bit() where applicablePeng Fan
Convert open-coded if/else with set_bit/clear_bit and their non-atomic __set_bit/__clear_bit variants to the assign_bit/__assign_bit API. Done with Coccinelle semantic patch: // set_bit -> clear_bit => assign_bit @@ expression cond, bit, addr; @@ -if (cond) - set_bit(bit, addr); -else - clear_bit(bit, addr); +assign_bit(bit, addr, cond); // clear_bit -> set_bit => assign_bit @@ expression cond, bit, addr; @@ -if (cond) - clear_bit(bit, addr); -else - set_bit(bit, addr); +assign_bit(bit, addr, !cond); // __set_bit -> __clear_bit => __assign_bit @@ expression cond, bit, addr; @@ -if (cond) - __set_bit(bit, addr); -else - __clear_bit(bit, addr); +__assign_bit(bit, addr, cond); // __clear_bit -> __set_bit => __assign_bit @@ expression cond, bit, addr; @@ -if (cond) - __clear_bit(bit, addr); -else - __set_bit(bit, addr); +__assign_bit(bit, addr, !cond); Signed-off-by: Peng Fan <peng.fan@nxp.com> Reviewed-by: David Sterba <dsterba@suse.com> Signed-off-by: David Sterba <dsterba@suse.com>
2026-10-12btrfs: drop unused uring encoded IO REISSUE stash helpersYang Xiuwei
After not keeping state across -EAGAIN, restoring bc->data on REISSUE is dead. Remove it, stop using the cmd PDU on the write path, and fold the read -EAGAIN check into the existing error path. Signed-off-by: Yang Xiuwei <yangxiuwei@kylinos.cn> Reviewed-by: David Sterba <dsterba@suse.com> Signed-off-by: David Sterba <dsterba@suse.com>
2026-10-12btrfs: zoned: fix block group reference leak in btrfs_repair_one_zone()Wentao Liang
btrfs_repair_one_zone() hands the block group reference taken by btrfs_lookup_block_group() over to relocating_repair_kthread(), which drops it. However the return value of kthread_run() is not checked, so when the kernel thread fails to spawn, nothing executes the put and the block group reference is leaked. Check kthread_run() and drop the reference if the thread failed to start. Fixes: f7ef5287a63d ("btrfs: zoned: relocate block group to repair IO failure in zoned filesystems") CC: stable@vger.kernel.org Reviewed-by: Boris Burkov <boris@bur.io> Signed-off-by: Wentao Liang <vulab@iscas.ac.cn> Reviewed-by: David Sterba <dsterba@suse.com> Signed-off-by: David Sterba <dsterba@suse.com>
2026-10-12btrfs: fix dangling nodes in tree-mod-log after error in ↵Filipe Manana
btrfs_tree_mod_log_insert_root() If in btrfs_tree_mod_log_insert_root() there is an error in the call to tree_mod_log_insert() (the only possible error is -EEXIST, which means we have a bug or some memory corruption maybe) we free all the nodes in the 'tm_list' array but we don't remove them from the tree-mod-log rbtree, which can result in use-after-free bugs later. So make sure we remove the nodes from the rbtree before freeing them after an error. Fixes: 5de865eebb83 ("Btrfs: fix tree mod logging") Assisted-by: LLM (found the bug) Reviewed-by: Boris Burkov <boris@bur.io> Signed-off-by: Filipe Manana <fdmanana@suse.com> Signed-off-by: David Sterba <dsterba@suse.com>
2026-10-12btrfs: assert reloc mutex is held in record_root_in_trans()Filipe Manana
The fs_info->reloc_mutex is supposed to be held when record_root_in_trans() is called and we mention that in a comment inside the function. Add a lockdep assertion to check the lock is held. Reviewed-by: Boris Burkov <boris@bur.io> Reviewed-by: Qu Wenruo <wqu@suse.com> Signed-off-by: Filipe Manana <fdmanana@suse.com> Signed-off-by: David Sterba <dsterba@suse.com>
2026-10-12btrfs: fix barrier usage in btrfs_record_root_in_trans()Filipe Manana
The barrier usage in btrfs_record_root_in_trans() is wrong, as the writer side, in record_root_in_trans(), sets BTRFS_ROOT_IN_TRANS_SETUP, does a write barrier and then sets the root's last transaction. This means the reader side must check the root's last transaction, issue a read barrier and then check for BTRFS_ROOT_IN_TRANS_SETUP. However, currently we issue a read barrier and then check the root's last transaction and the bit BTRFS_ROOT_IN_TRANS_SETUP, which can be problematic because the CPU is free to reorder the checks and the following can happen: 1) Before reading the root's last_trans, it checks that BTRFS_ROOT_IN_TRANS_SETUP is not set. 2) A writer sets BTRFS_ROOT_IN_TRANS_SETUP, does smp_wmb() and updates the root's last_trans. 3) The reader then sees the root's last_trans matches the current transaction and falsely concludes the root setup is completes and returns without waiting for the writer task to complete the setup (calling btrfs_init_reloc_root()). So fix the reading ordered as previously described: check the root's last_trans, issue read barrier and then check BTRFS_ROOT_IN_TRANS_SETUP (the reverse of what the writer side does). Assisted-by: LLM Reviewed-by: Boris Burkov <boris@bur.io> Signed-off-by: Filipe Manana <fdmanana@suse.com> Signed-off-by: David Sterba <dsterba@suse.com>
2026-10-12btrfs: fix off by one super block end offset calculation when writing super ↵Filipe Manana
blocks We are skipping the write of a super block mirror if its end offset matches exactly the device's end offset. This happens because we are using a greater than or equals comparison instead of just a greater than comparison. Fixes: 935e5cc935bc ("Btrfs: fix wrong disk size when writing super blocks") Reviewed-by: Qu Wenruo <wqu@suse.com> Signed-off-by: Filipe Manana <fdmanana@suse.com> Signed-off-by: David Sterba <dsterba@suse.com>
2026-10-12btrfs: downgrade the reflink source inode lock for tree walkingBoris Burkov
When doing a reflink, we are not writing to the src inode or modifying it in any way, so it is counter-intuitive to have to lock it exclusively. This has the cost of blocking other shared lock users of the src file for the duration of any new writeback since the optimistic pre-flush and all the actual reflinking. So we would like to downgrade the lock to shared as much as possible. There are two important gotchas to do with direct io that must be addressed to make this idea work. The first gotcha is that dio writes that come in under EOF try to take inode->i_rwsem shared, which would result in messed up views of the extents in the reflinked file. Therefore, add "being used as a reflink src" as another inode flag exception for the dio write shared tests that already exist to check for other dangerous conditions. In order to ensure that this flag is visible to the dio writer, reflink must first take i_rwsem exclusive, then set the flag, then downgrade to shared. The second is that dio reads increment inode->i_dio_count which blocks inode_dio_wait() in __generic_remap_file_range_prep(). Therefore, we must remain exclusive to dio reads through finishing the prep or risk starving the clone on a stream of dio readers. There is still O(extents) work in btrfs_clone() which can be done without holding the lock exclusive, so we should downgrade to shared and admit dio readers (and other shared lock users like lseek) after we are finished with inode_dio_wait(). By running concurrent clones and lseeks or dio reads on a src file with 32k extents on a vm, I can demonstrate 100ms+ stalls on the readers without this patch and they go away entirely with the patch. Reviewed-by: Filipe Manana <fdmanana@suse.com> Signed-off-by: Boris Burkov <boris@bur.io> Signed-off-by: David Sterba <dsterba@suse.com>
2026-10-12btrfs: skip unlocked reflink source flush if the inode has writersBoris Burkov
The optimistic unlocked flushing is counter-productive if there is an active writer dirtying pages, as it results in doubly writing back any pages that get dirtied again before the locked flush. Therefore, pessimize it slightly and don't do the unlocked flushing if we have outstanding writable file descriptors or memory mappings. Since the inode isn't locked, this is only advisory, any new mapping or fd that sneaks in after the check but before the locking can still cause extra writeback. But it trivially helps quite a bit in simple cases with a long open file descriptor or mapping. I tested this with two similar workloads. One was keeping and fd open and doing continuous writes into the src file while cloning it and doing lseek on it and the other was slightly meaner, constantly opening and closing the fd to try to race this check. Workload 1 shows a huge regression in write amplification and writers and readers who experience userspace wall time stalls of 100ms+ with just the pre-flush, but recovers to normal with this check. Workload 2 is a smaller regression which is mostly helped but not fully resolved with this check. So we must weigh this regression against the benefit of the unlocked flush in the allegedly more common simpler case. Workload 1: fd kept open, 60s of clone/write/lseek looping. kernel clones clone mean s device MiB/clone writer stalls reader stalls for-next 564 0.095 119 10 10 pre-flush (p1) 179 0.338 405 94 93 skip (p1+p2) 540 0.100 116 9 9 Workload 2: same writer, but closing and reopening the fd around each 64 MiB write with some random sleeping to encourage racing. kernel clones clone mean s device MiB/clone writer stalls reader stalls for-next 740 0.070 83 9 9 pre-flush (p1) 255 0.224 246 27 26 skip (p1+p2) 518 0.107 121 11 11 Reviewed-by: Filipe Manana <fdmanana@suse.com> Signed-off-by: Boris Burkov <boris@bur.io> Signed-off-by: David Sterba <dsterba@suse.com>
2026-10-12btrfs: pre-flush reflink source before taking inode locksBoris Burkov
Consider the following sketch of a shell script: dd if=/dev/urandom of=/mnt/src bs=1M count=4096 cp --reflink=always /mnt/src /mnt/dst & sleep 0.1 # let the clone reach its flush time dd if=/mnt/src of=/dev/null bs=4K count=1 iflag=direct The current logic in reflink ensures the existence and stability of both the src and destination inode by locking them both and then flushing all dirty pages / ordered_extents under the inode lock. This blocks concurrent usage by even readers of the inode locks, like direct reads or seeks for the duration of writeback on the entirety of the two files. We observe this particular contention frequently in the Meta fleet. It is also a relatively common pattern to write the src file, then reflink it while it is still dirty, so that typical path naturally hits this contention. This workload motivates a relatively simple optimization: trigger the unavoidable src flushing outside the locked region. Therefore, do an optimistic btrfs_wait_ordered_range() without the locks while relying on the calls to btrfs_wait_ordered_range() under the locks in btrfs_remap_file_range_prep() to ensure correctness. In the worst case with concurrent writes while unlocked, we can end up doing the writeback twice, which I think is a reasonable price to pay to avoid victimizing innocent readers in a common case. With and without this patch, the above reproducer runs the reflink in the same ~0.5s on my system. Without the patch, the direct read blocks for basically the full duration of the reflink while with the patch it returns in a few milliseconds. Reviewed-by: Filipe Manana <fdmanana@suse.com> Signed-off-by: Boris Burkov <boris@bur.io> Signed-off-by: David Sterba <dsterba@suse.com>
2026-10-12btrfs: keep unused block groups queued when a pass failsBoris Burkov
Once any block_group sets ret!=0 in the main loop of btrfs_delete_unused_bgs(), the check if (ret || btrfs_mixed_space_info(space_info)) { btrfs_put_block_group(block_group); continue; } skips the rest of the unused bgs while unlinking them from fs_info->unused_bgs. There is no "level triggered" re-queueing of empty block groups onto fs_info->unused_bgs so it is possible to leak quite a bit of space this way and unless we happen to get a balance or re-use/re-empty one of these bgs, they are leaked for good, which can lead to a spurious enospc later. While I have observed such leaked blocked groups that are empty but not on the unused_bgs list on production systems, I have not observed that it is definitely due to this issue. I also reproduced this behavior by injecting an ENOSPC error from btrfs_start_trans_remove_block_group which can also fail with ENOMEM, so this feels like a legitimate injection point. To fix it, instead of checking ret in the loop, just break out of the loop when ret != 0. Also, link the bg to the retry list at the individual failure sites so that the failing bg is not leaked. Assisted-by: LLM (reproducer/error injection) Reviewed-by: Qu Wenruo <wqu@suse.com> Signed-off-by: Boris Burkov <boris@bur.io> Signed-off-by: David Sterba <dsterba@suse.com>
2026-10-12btrfs: remove duplicate error message when writing super blocksFilipe Manana
If the total error count is greater the maximum allowed number of errors, we print exactly the same error message twice. Remove one of the messages. Reviewed-by: Qu Wenruo <wqu@suse.com> Signed-off-by: Filipe Manana <fdmanana@suse.com> Signed-off-by: David Sterba <dsterba@suse.com>
2026-10-12btrfs: remove redundant eb generation check in btrfs_buffer_uptodate()Filipe Manana
It's pointless to check if the extent buffer's generation does not match the value of 'parent_transid' because if it does, then we have already entered the previous if statement and returned from the function. Reviewed-by: Qu Wenruo <wqu@suse.com> Signed-off-by: Filipe Manana <fdmanana@suse.com> Signed-off-by: David Sterba <dsterba@suse.com>
2026-10-12btrfs: add missing unlikely to a couple error checks during sys chunk array ↵Filipe Manana
validation It's unexpected to find errors during sys chunk array validation and all checks use the unlikely tag except for two of them, so add it. Reviewed-by: Qu Wenruo <wqu@suse.com> Signed-off-by: Filipe Manana <fdmanana@suse.com> Signed-off-by: David Sterba <dsterba@suse.com>
2026-10-12btrfs: simplify heuristic_collect_sample() to handle large folios betterQu Wenruo
Currently heuristic_collect_sample() is purely page size based, and it has a lot of extra handling just inside the page. However we already have large folio support, there is no need to look up the same folio repeatedly. Simplify the handling by: - Use @cur as the iterator instead of page index - Handle the sample copying on a per-folio basis Although kmap_local_folio() requires an offset to handle HIGHMEM page mapping, we have rejected large folios for HIGHMEM systems completely. So we can safely handle all sample copying inside the folio in one go. - Remove unnecessary unaligned range handling All the range passed in should be block aligned, thus there is no need to handle cases where sample crosses the block boundary. Reviewed-by: Boris Burkov <boris@bur.io> Signed-off-by: Qu Wenruo <wqu@suse.com> Signed-off-by: David Sterba <dsterba@suse.com>
2026-10-12btrfs: fix off-by-one end related to inode_need_compress()Qu Wenruo
In most cases btrfs uses @end as the inclusive end bytenr for a range, and this applies to inode_need_compress(). However we have several sites not following the inclusive bytenr: - run_delalloc_inline() Which assigned @blocksize as @end for inode_need_compress() This makes inode_need_compress() always skip the disk_i_size check. - heuristic_collect_sample() Which assigned "start + BTRFS_MAX_UNCOMPRESSED" to @end, which is the exclusive bytenr. Neither is really causing any real problem, as heuristic_collect_sample() has proper checks to avoid reading anything beyond @end, and the sampling read size is 16 bytes, so it has enough headroom to handle that off-by-one problem. But still I do not like anything out of the common scheme, so fix the off-by-one @end for both call sites, and add extra ASSERT()s to catch such unaligned parameters. Reviewed-by: Boris Burkov <boris@bur.io> Signed-off-by: Qu Wenruo <wqu@suse.com> Signed-off-by: David Sterba <dsterba@suse.com>
2026-10-12btrfs: cleanup and rename submit_extent_folio()Qu Wenruo
Cleanup submit_extent_folio() by: - Remove @size parameter Since commit b2e743927fdd ("btrfs: make btrfs_do_readpage() to do block-by-block read"), all callers are passing sectorsize as @size, so there is no need for such parameter. Furthermore since we only write one block at a time, there is no need for a while() loop, nor the advance of various local variables. - Update the comments on the parameter list * @disk_bytenr is shared for both read and write * rename @page to @folio - Update the return value to return 0 or error Since we won't queue multiple blocks anyway, there is no point in returning the queued bytes. It makes more sense to return an error code, although the only error code will be -EUCLEAN for writes. - Rename submit_extent_folio() to submit_one_block() - Rename submit_one_sector() to submit_write_sector() - Update the error message to utilize the new returned error code inside submit_write_sector() Reviewed-by: Boris Burkov <boris@bur.io> Signed-off-by: Qu Wenruo <wqu@suse.com> Signed-off-by: David Sterba <dsterba@suse.com>
2026-10-12btrfs: tree-checker: cache accessor return value in CHECK_FE_ALIGNED()Filipe Manana
We are calling an accessor for a file extent item multiple times in the CHECK_FE_ALIGNED() macro, even when we don't find a corruption (once in the if statement's expression and then once again in the expression for the return value). This adds extra runtime overhead (which is critical since the tree checker runs against every extent buffer when it's read or before persisting it) and increases the module's size. So cache the accessor's return value in a variable and use it, reducing runtime, object size and making the source code shorter too. Also avoid repeating twice the IS_ALIGNED() computation. Before: $ size fs/btrfs/btrfs.ko text data bss dec hex filename 2073340 217928 15624 2306892 23334c fs/btrfs/btrfs.ko After: $ size fs/btrfs/btrfs.ko text data bss dec hex filename 2073076 217928 15624 2306628 233244 fs/btrfs/btrfs.ko Also running the following fsstress test and capturing the runtime of check_extent_data_item() (the only caller of CHECK_FE_ALIGNED()) in nanoseconds (using bpftrace), showed the following runtime improvements: Test: mkfs.btrfs -f /dev/nullb0 mount /dev/nullb0 /mnt fsstress -w -p 8 -n 5000 -s 12345 -d /mnt umount /mnt Before: Count: 2033671 Range: 0.000 - 1336060.000; Mean: 679.642; Median: 656.000; Stddev: 2031.323 Percentiles: 90th: 850.000; 95th: 909.000; 99th: 1272.000 0.000 - 6.647: 11 | 6.647 - 28.241: 36 | 28.241 - 110.807: 176 | 110.807 - 426.512: 38012 # 426.512 - 1633.663: 1983372 ##################################################### 1633.663 - 6249.399: 8315 | 6249.399 - 23898.422: 3243 | 23898.422 - 91382.340: 153 | 91382.340 - 349418.114: 36 | 349418.114 - 1336060.000: 11 | After: Count: 2092797 Range: 0.000 - 1677284.000; Mean: 627.650; Median: 617.000; Stddev: 1848.010 Percentiles: 90th: 809.000; 95th: 859.000; 99th: 1209.000 0.000 - 6.823: 18 | 6.823 - 29.602: 82 | 29.602 - 118.702: 416 | 118.702 - 467.232: 515774 ################# 467.232 - 1830.549: 1565599 ##################################################### 1830.549 - 7163.339: 5297 | 7163.339 - 28023.237: 4186 | 28023.237 - 109619.427: 166 | 109619.427 - 428793.471: 25 | 428793.471 - 1677284.000: 4 | Reviewed-by: Qu Wenruo <wqu@suse.com> Signed-off-by: Filipe Manana <fdmanana@suse.com> Signed-off-by: David Sterba <dsterba@suse.com>
2026-10-12btrfs: increment extent count once when logging extents during fast fsyncFilipe Manana
In btrfs_log_changed_extents() we increment the extent count twice, and we then fallback to a transaction commit if the count reaches a threshold of 32K. However we increment the count twice, which is confusing and pointless. So increment the count only once and reduce the threshold to half (16K). Reviewed-by: Qu Wenruo <wqu@suse.com> Signed-off-by: Filipe Manana <fdmanana@suse.com> Signed-off-by: David Sterba <dsterba@suse.com>
2026-10-12btrfs: use u64 for the page indices in heuristic_collect_sample()Tal Zussman
index and index_end are derived from the u64 start and end offsets, and index is shifted back into a byte offset for offset_in_folio(), which needs a cast to u64 to be safe on 32-bit. Make them u64 instead so the cast goes away. They still fit pgoff_t where they are passed to filemap_get_folio(), as they came from a valid file offset. Signed-off-by: Tal Zussman <tz2294@columbia.edu> Reviewed-by: David Sterba <dsterba@suse.com> Signed-off-by: David Sterba <dsterba@suse.com>
2026-10-12btrfs: use folios for reading super blocks from the block deviceTal Zussman
btrfs_read_disk_super() and the zoned super block log comparison go through read_cache_page_gfp() and page_address(), and btrfs_release_disk_super() recovers the page with virt_to_page(). Use mapping_read_folio_gfp(), folio_address(), and virt_to_folio() instead. This removes the last callers of read_cache_page_gfp() and put_page() in btrfs. Compute the super block address with offset_in_folio() as write_dev_supers() does, rather than assuming it is at the start of the page. Assisted-by: Claude:claude-fable-5-1 Reviewed-by: Qu Wenruo <wqu@suse.com> Signed-off-by: Tal Zussman <tz2294@columbia.edu> Reviewed-by: David Sterba <dsterba@suse.com> Signed-off-by: David Sterba <dsterba@suse.com>
2026-10-12btrfs: fix stale function references in compression commentsTal Zussman
add_ra_bio_pages() was renamed to add_ra_bio_folios(), and btrfs_compress_filemap_get_folio() wraps filemap_get_folio(), not find_get_page(). Update the comments accordingly. Reviewed-by: Qu Wenruo <wqu@suse.com> Signed-off-by: Tal Zussman <tz2294@columbia.edu> Reviewed-by: David Sterba <dsterba@suse.com> Signed-off-by: David Sterba <dsterba@suse.com>
2026-10-12btrfs: convert heuristic_collect_sample() to use foliosTal Zussman
Convert the sampling loop to folios. This removes the last caller of find_get_page() in btrfs and saves a call to compound_head() per sampled page. Document that the lookup is not supposed to fail with an ASSERT(). Reviewed-by: Qu Wenruo <wqu@suse.com> Signed-off-by: Tal Zussman <tz2294@columbia.edu> Reviewed-by: David Sterba <dsterba@suse.com> Signed-off-by: David Sterba <dsterba@suse.com>
2026-10-12btrfs: convert btrfs_compr_pool_scan() to use foliosTal Zussman
The compression pool holds order-0 folios, but btrfs_compr_pool_scan() walks it as struct page through page->lru. Walk it as folios, matching the other compression pool functions. This removes the last use of page->lru in btrfs and saves a call to compound_head() per freed folio. Reviewed-by: Qu Wenruo <wqu@suse.com> Signed-off-by: Tal Zussman <tz2294@columbia.edu> Reviewed-by: David Sterba <dsterba@suse.com> Signed-off-by: David Sterba <dsterba@suse.com>