btrfs: write dirty device stats when no transaction is running
Device stats are counted in memory and written to their dev stats items
only by btrfs_run_dev_stats(), which runs inside a transaction commit.
Nothing starts a transaction for them: the transaction kthread commits
only a running transaction, and at unmount close_ctree() calls
btrfs_commit_super(), whose btrfs_commit_current_transaction() only
attaches to a running transaction and returns 0 when there is none.
Read errors, checksum failures and read repair (which rewrites the bad
copy with bios outside any transaction) count stats without starting a
transaction. So on a read-write mount whose workload only reads, every
count since the last commit is lost at unmount, and the next mount
shows the old values. For example, a cold read of a file with one
corrupted raid1 copy counts corruption_errs and repairs the copy, and
after unmount and mount the count is gone.
Start and commit a transaction to write the stats when any device has
dirty stats, the filesystem was mounted read-write and is not read-only,
shut down or in an error state, and no transaction is running:
- the transaction kthread does it at its commit_interval wakeup, so the
counts reach the disk within one commit interval;
- btrfs_commit_super() does it after committing the running transaction,
which covers unmount and remount read-only, including counts made by
the scrub, replace and balance that close_ctree() and
btrfs_remount_ro() stop just before.
btrfs_remount_ro() takes and releases transaction_kthread_mutex after it
sets SB_RDONLY, so a kthread pass that saw the filesystem writable can
not start a transaction after the final commit. A frozen filesystem is
skipped (sb_start_write_trylock()) and its counts are written after
thaw. Log replay at mount happens before BTRFS_FS_OPEN is set and does
not start one. The check reuses the lockless RCU pass of
btrfs_run_dev_stats(), now btrfs_dev_stats_dirty(), so a healthy idle
filesystem pays one list walk per commit interval and gets no new
transactions. The one exception is a filesystem whose devices have no
dev stats item yet: mkfs does not create them, and loading the stats at
mount marks such a device dirty, so the first read-write mount writes
the items in one commit even when idle.
This changes btrfs behaviour. An otherwise read-only workload on a
read-write mount now causes transaction commits and metadata writes
whenever errors were counted: up to one commit per commit interval while
errors keep coming, and one more at unmount. Until now such a workload
wrote no metadata at all, and someone who relies on that, or who prefers
losing the counts to writing to a filesystem that is returning errors,
may reasonably reject this patch.
Read-only mounts are unchanged and still lose their counts at unmount,
as do a crash and a shutdown or aborted filesystem.