diff --git a/CLAUDE.md b/CLAUDE.md index fe73caecab..ddff79484a 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -63,9 +63,12 @@ software development. When approaching a new problem: rather than planning and implementing entire features in one pass. Research and analysis notes are a first-class output, not just -scaffolding for implementation. They should be dated and checked into the -repository under `.claude/` so that future developers (human and AI) can -see what's been analyzed and what was decided. +scaffolding for implementation. They go in `.claude/`, dated, so that +later work can see what's been analyzed and what was decided. + +`.claude/` is deliberately untracked — these are working notes, not +documentation for general consumption. Anything that belongs in the +repository proper goes in `doc/`, written for that audience. ### Calibrate to the risk diff --git a/Cargo.lock b/Cargo.lock index 435794cae8..1b1324bb3c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -56,7 +56,7 @@ version = "1.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" dependencies = [ - "windows-sys", + "windows-sys 0.60.2", ] [[package]] @@ -67,7 +67,7 @@ checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" dependencies = [ "anstyle", "once_cell_polyfill", - "windows-sys", + "windows-sys 0.60.2", ] [[package]] @@ -131,7 +131,7 @@ dependencies = [ [[package]] name = "bcachefs-tools" -version = "1.38.8" +version = "1.39.0" dependencies = [ "anyhow", "bcachefs-kernel", @@ -150,6 +150,7 @@ dependencies = [ "owo-colors", "rustc-demangle", "rustix", + "rustyline", "serde", "serde_json", "strum", @@ -377,6 +378,15 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9" +[[package]] +name = "clipboard-win" +version = "5.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bde03770d3df201d4fb868f2c9c59e66a3e4e2bd06692a0fe701e7103c7e84d4" +dependencies = [ + "error-code", +] + [[package]] name = "colorchoice" version = "1.0.5" @@ -436,6 +446,12 @@ version = "1.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "91622ff5e7162018101f2fea40d6ebf4a78bbe5a49736a2020649edf9693679e" +[[package]] +name = "endian-type" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c34f04666d835ff5d62e058c3995147c06f42fe86ff053337632bca83e42702d" + [[package]] name = "env_logger" version = "0.10.2" @@ -458,7 +474,24 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys", + "windows-sys 0.59.0", +] + +[[package]] +name = "error-code" +version = "3.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dea2df4cf52843e0452895c455a1a2cfbb842a1e7329671acf418fdc53ed4c59" + +[[package]] +name = "fd-lock" +version = "4.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ce92ff622d6dadf7349484f42c93271a0d49b7cc4d466a936405bacbe10aa78" +dependencies = [ + "cfg-if", + "rustix", + "windows-sys 0.59.0", ] [[package]] @@ -525,6 +558,15 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" +[[package]] +name = "home" +version = "0.5.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589533453244b0995c858700322199b2becb13b627df2851f64a2775d024abcf" +dependencies = [ + "windows-sys 0.59.0", +] + [[package]] name = "httpdate" version = "1.0.3" @@ -609,7 +651,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4979f22fdb869068da03c9f7528f8297c6fd2606bc3a4affe42e6a823fdb8da4" dependencies = [ "cfg-if", - "windows-targets", + "windows-targets 0.52.6", ] [[package]] @@ -679,7 +721,16 @@ dependencies = [ "libc", "log", "wasi", - "windows-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "nibble_vec" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77a5d83df9f36fe23f0c3648c6bbb8b0298bb5f1939c8f2704431371f4b84d43" +dependencies = [ + "smallvec", ] [[package]] @@ -857,6 +908,16 @@ version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" +[[package]] +name = "radix_trie" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c069c179fcdc6a2fe24d8d18305cf085fdbd4f922c041943e203685d6a1c58fd" +dependencies = [ + "endian-type", + "nibble_vec", +] + [[package]] name = "redox_syscall" version = "0.5.18" @@ -937,7 +998,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys", - "windows-sys", + "windows-sys 0.59.0", ] [[package]] @@ -946,6 +1007,28 @@ version = "1.0.22" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" +[[package]] +name = "rustyline" +version = "17.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e902948a25149d50edc1a8e0141aad50f54e22ba83ff988cf8f7c9ef07f50564" +dependencies = [ + "bitflags 2.13.0", + "cfg-if", + "clipboard-win", + "fd-lock", + "home", + "libc", + "log", + "memchr", + "nix", + "radix_trie", + "unicode-segmentation", + "unicode-width", + "utf8parse", + "windows-sys 0.60.2", +] + [[package]] name = "scopeguard" version = "1.2.0" @@ -1123,7 +1206,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "230a1b821ccbd75b185820a1f1ff7b14d21da1e442e22c0863ea5f08771a8874" dependencies = [ "rustix", - "windows-sys", + "windows-sys 0.59.0", ] [[package]] @@ -1222,6 +1305,18 @@ version = "1.0.24" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" +[[package]] +name = "unicode-segmentation" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" + +[[package]] +name = "unicode-width" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" + [[package]] name = "utf8parse" version = "0.2.2" @@ -1312,7 +1407,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys", + "windows-sys 0.59.0", ] [[package]] @@ -1380,6 +1475,24 @@ dependencies = [ "windows-link", ] +[[package]] +name = "windows-sys" +version = "0.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +dependencies = [ + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-sys" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb" +dependencies = [ + "windows-targets 0.53.5", +] + [[package]] name = "windows-sys" version = "0.61.2" @@ -1395,14 +1508,31 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" dependencies = [ - "windows_aarch64_gnullvm", - "windows_aarch64_msvc", - "windows_i686_gnu", - "windows_i686_gnullvm", - "windows_i686_msvc", - "windows_x86_64_gnu", - "windows_x86_64_gnullvm", - "windows_x86_64_msvc", + "windows_aarch64_gnullvm 0.52.6", + "windows_aarch64_msvc 0.52.6", + "windows_i686_gnu 0.52.6", + "windows_i686_gnullvm 0.52.6", + "windows_i686_msvc 0.52.6", + "windows_x86_64_gnu 0.52.6", + "windows_x86_64_gnullvm 0.52.6", + "windows_x86_64_msvc 0.52.6", +] + +[[package]] +name = "windows-targets" +version = "0.53.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3" +dependencies = [ + "windows-link", + "windows_aarch64_gnullvm 0.53.1", + "windows_aarch64_msvc 0.53.1", + "windows_i686_gnu 0.53.1", + "windows_i686_gnullvm 0.53.1", + "windows_i686_msvc 0.53.1", + "windows_x86_64_gnu 0.53.1", + "windows_x86_64_gnullvm 0.53.1", + "windows_x86_64_msvc 0.53.1", ] [[package]] @@ -1411,48 +1541,96 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53" + [[package]] name = "windows_aarch64_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" +[[package]] +name = "windows_aarch64_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006" + [[package]] name = "windows_i686_gnu" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" +[[package]] +name = "windows_i686_gnu" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3" + [[package]] name = "windows_i686_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" +[[package]] +name = "windows_i686_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c" + [[package]] name = "windows_i686_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" +[[package]] +name = "windows_i686_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2" + [[package]] name = "windows_x86_64_gnu" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" +[[package]] +name = "windows_x86_64_gnu" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499" + [[package]] name = "windows_x86_64_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1" + [[package]] name = "windows_x86_64_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" +[[package]] +name = "windows_x86_64_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" + [[package]] name = "winnow" version = "0.7.15" diff --git a/Cargo.toml b/Cargo.toml index 0296e1b9dc..7a97a837f1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,7 +5,7 @@ default-members = [".", "fs"] [package] name = "bcachefs-tools" -version = "1.38.8" +version = "1.39.0" authors = ["Yuxuan Shui ", "Kayla Firestack ", "Kent Overstreet " ] edition = "2021" rust-version = "1.85.0" @@ -43,6 +43,8 @@ tiny_http = "0.12.0" rustc-demangle = "0.1" chrono = { version = "0.4.43", default-features = false, features = ["clock"] } fuser = { version = "0.17", optional = true } +# rustyline 18 requires home 0.5.12, which requires rustc 1.88 (> our 1.85 MSRV) +rustyline = "17.0.2" [dependencies.env_logger] version = "0.10" diff --git a/Changelog.mdwn b/Changelog.mdwn index f3c87b5672..9a7fdfed1d 100644 --- a/Changelog.mdwn +++ b/Changelog.mdwn @@ -1,5 +1,182 @@ # Changelog +## v1.39.0 - Mon Aug 3 2026 + +Feature release on top of v1.38.8, with an on-disk format change: +bcachefs_metadata_version_per_dev_fragmentation_lru + +Major changes: + +- Per-device fragmentation LRUs +- Failure domains +- File level damage tracking +- bcachefs kvdb +- Snapshot hardening + +### Features + +#### Per-device bucket fragmentation LRUs + +The fragmentation LRU, used by copygc, is now per device instead of filesystem +wide. This solves long standing contention issues between reconcile and copygc, +particularly with tiered setups. + +#### Failure domains + +Devices can be tagged with a failure domain — a shelf, a chassis, a rack, +whatever the thing is that fails together — and replicas are spread across +domains rather than merely across devices. This covers data allocation, journal +replicas, and erasure-coded stripe blocks, which now require distinct domains. +Set it with the new `failure_domain` per-device option; `bcachefs fs +failure-domains` shows the layout. + +Note that failure domains are only a hard constraint for erasure coding; normal +replicated allocations will reuse a failure domain if necessary to meet replicas +requirements; erasure coding will shorten stripes to the number of failure +domains available. + +#### Damage tracking + +What was lost is now recorded persistently, in a new btree, instead of being +printed once during fsck and thereafter recoverable only from logs. fsck records +inode-scoped damage keyed by `bch_sb_error_id`, and data lost to device +force-removal and to read errors is recorded the same way. + +`bcachefs damage` shows what's recorded; the list can also be walked from +userspace through the new readdir/damage ioctls, and is exposed in debugfs. fsck +summarizes damaged paths at the end of recovery, resolving them through surviving +snapshot versions and naming the parent directory for inodes whose own dirent is +gone. + +#### bcachefs kvdb + +A new REPL for reading and editing btree keys and the superblock directly — the +tool most of this release's repair work was built and debugged with. It has +readline, tab completion for commands and btree names, and ^C interrupts the +running command. Read-only norecovery open is the default, with `--rw` to edit, +`--nostart` for superblock-only access, and `--journal` for `list_journal`. + +Reads and writes go down to individual fields: `get`/`peek` take trailing field +paths, and vartail fields, named bitmask fields and enum value names for state +fields all work. There's a session snapshot context, overridable per-command with +an explicit `:snapshot` in a pos. Underneath it is new runtime type information +for the C structs (`#[derive(TypeInfo)]`). + +#### Snapshot hardening + +Snapshot deletion is the most destructive thing the filesystem does, and what +licenses it is metadata. That used to be a flag bit: one flipped bit, a torn +deletion or a half-finished repair could make a live snapshot look deletable. + +Three things now have to agree before anything is deleted. The state fields are +enums whose values are at least 14 bits apart rather than bitflags, so no single +bit flip can turn one valid state into another. Deletion is no longer triggered +by the snapshot node alone: the snapshots and subvolumes btrees are independent +records of the same fact and both have to agree. And per-snapshot key counts let +deletion verify it actually moved everything, refusing and scheduling repair if +not. Deletion also no longer destroys information, and damage found at runtime +defers to repair instead of BUG_ON. + +There's a lot of new repair code for damaged snapshot trees that would previously +have been refused, and it's tested by injection: `bcachefs kvdb` writes specific +corruptions into the btree, and the new `snapshot-inject` suite — 68 cases — +asserts that fsck detects the error, repairs it, converges, and the data +survives. + +Credit to ZorbaTHut (Ben Rog-Wilhelm), who reported this and worked with us +extensively, providing metadata dumps and tests; several people jumped in on +this one. + +#### Performance + +ACL and per-inode-option lookups are skipped entirely when the inode has none, +via the new `has_access_acl`, `has_default_acl` and `has_inode_opts` flags. +Bucket allocation can be targeted. Erasure coding allocates stripe blocks near +the stripe's centroid and reallocates outliers. + +#### Portability + +PREEMPT_RT: new `mutex_noio` and `percpu_rwsem_noio`, with `sb_lock`, +`mark_lock`, the btree cache lock and the journal buf lock converted; `GFP_NOFS` +replaced with `GFP_NOIO`; data writes set `PF_MEMALLOC_NOIO`; `time_stats` uses +`local_lock`. 32-bit builds get `__aeabi_uldivmod`/`__aeabi_ldivmod` stubs for +ARM modules, 64-bit divisions via `div64_u64`, and a `mul_u64_u64_div_u64` fix +(#795). Also builds on `CONFIG_SCHED_ALT` (BMQ/PDS) kernels, with `WQ_PERCPU` +compat for kernels older than 6.17 and slab realloc compat for older than 6.18. + +#### Tools + +Offline `set-fs-option` and `set-state` actually write the superblock now. +`bcachefs list` works on mounted filesystems, `dump --single-replica` produces +de-replicated metadata dumps, and `kill_btree_node --error` can inject a csum +error type. + +### Behaviour changes + +**Reverted from v1.38.7:** multi-device filesystems no longer show the filesystem +UUID as the mount source. + +A subvolume can now be deleted by rename-overwrite of its root, and `bcachefs +subvolume snapshot` takes `--rw`. Devices with durability=0 are excluded from +normal allocation logic, which changes placement on cache and tiering setups. + +Commit-time validation of snapshot and subvolume state invariants is now on: a +buggy writer is caught in the act with a backtrace instead of leaving the mess +for fsck. It can be turned off with `no_commit_validate`. + +New `btree_cache_shrinker_seeks` option (runtime, default 2) controls how readily +the shrinker reclaims btree nodes relative to other caches; `ratelimit_errors` is +now runtime-settable too. The unclean-shutdown journal sequence skip was widened +from 64 to 4096, the passphrase prompt is usable on raw early-boot consoles, and +`format` rejects `--version` together with `--source`. + +### New ioctls + +`BCH_IOCTL_QUERY_BTREE_KEYS` queries btree keys directly, with +slots/prev/all_snapshots/nofilter_whiteouts flags; it's what backs `bcachefs +kvdb` and `bcachefs list` on a mounted filesystem. `BCHFS_IOC_GET_DAMAGE`, +`BCHFS_IOC_CLEAR_DAMAGE` and `BCHFS_IOC_READDIR_FLAGS` (with a recursive damaged +mode) expose the damage btree. Also `BCH_IOCTL_SNAPSHOT_TREE_v2`. + +### Bug fixes + +Two buffered read bugs could return wrong data. A read that took an internal +retry could resume with a stale `bi_iter`, and separately a stale +`BCH_READ_last_fragment` could persist across retries — in both cases the read +completed successfully with the wrong bytes, silently. Reported by jrt37, with +an exceptional analysis pinning both. + +Extent merging could corrupt compressed data: extents compressed in different +blobs were merged as though they were compatible. Reported by KatalinSB, who hit +it as akonadi database corruption under zstd. Relatedly, checksum type changes on +compressed extents and MAC width changes on encrypted extents were both mishandled +— reported by Zorba, with ktest reproducers for each. + +Inode numbers were truncated to 32 bits in the VFS layer, so filesystems that had +allocated past 2^32 could return the wrong inode to userspace; readdir dirent +translation had a matching bug on 32-bit. + +fsck: a `-ENOMEM` in `check_dirents` and unbounded transaction memory in the +`check_dirents`, `check_xattr` and `insert_snapshot_whiteouts` repair loops could +each stop a repair partway. `bch2_reattach_inode()` is now resumable under +partial commits, so a large orphan chain doesn't lose progress when a commit +splits. Also a null deref in `reconstruct_inode()` on an extent-less inum, and +`bch2_check_key_has_inode()` on inodes with only error keys — reported by +sickness, after a power outage took out both his replicas. + +Elsewhere: deleting compressed snapshot extents could NULL-deref on a missing +disk reservation (reported by pio2398); a cross-snapshot `str_hash` duplicate +could BUG_ON; emergency read-only could remove a device that still had journal on +it; and a 34-device array on an 8GB box could OOM partway through fsck from +undeduplicated async btree ops (reported by Zorba). + +### Documentation + +New Principles of Operation sections: safety mechanisms, snapshots and snapshot +deletion, failure domains, and how `ec_max_data_blocks` and failure domains bound +stripe width (that last after doot asked on IRC). `bcachefs kvdb` documentation +is shared between `--help` and the PoO. + ## v1.38.8 - Fri Jul 3 2026 - Fix dpkg builds. diff --git a/Makefile b/Makefile index 1754a8dbe4..47910d857b 100644 --- a/Makefile +++ b/Makefile @@ -263,7 +263,11 @@ build/%.o: %.c $(Q)$(CC) $(CPPFLAGS) $(CFLAGS) -c -o $@ $< BCACHEFS_DEPS=libbcachefs.a -RUST_SRCS:=$(shell find src fs bch_bindgen/src -type f ! -path 'fs/vendor/kernel-rust/*' -iname '*.rs') +# Whole crate dirs, not just their src/: a build script is a source file too, +# and bch_bindgen's generates every binding and x-macro table we have. Leaving +# it out meant editing it changed nothing until something else happened to make +# cargo run - a stale binary that looks like a rebuilt one. +RUST_SRCS:=$(shell find src fs bch_bindgen bcachefs-shim -type f ! -path 'fs/vendor/kernel-rust/*' -iname '*.rs') build.rs bcachefs: $(BCACHEFS_DEPS) $(RUST_SRCS) $(Q)$(CARGO_BUILD) diff --git a/bcachefs-shim/src/wrapper.h b/bcachefs-shim/src/wrapper.h index aa4d7384d1..1d91b9271f 100644 --- a/bcachefs-shim/src/wrapper.h +++ b/bcachefs-shim/src/wrapper.h @@ -6,6 +6,7 @@ #include "include/linux/idr.h" #include "include/linux/kernel.h" #include "include/linux/llist.h" +#include "include/linux/local_lock.h" #include "include/linux/percpu-refcount.h" #include "include/linux/percpu-rwsem.h" #include "include/linux/ratelimit.h" diff --git a/bcachefs-tools.spec b/bcachefs-tools.spec index ca5fd98b9d..128fa4d1f9 100644 --- a/bcachefs-tools.spec +++ b/bcachefs-tools.spec @@ -145,6 +145,11 @@ Requires: gcc Requires: make Requires: perl Requires: python3 +# fetch-module.sh: openssl verifies the module signature, xz decompresses the +# published module. Without either it silently gives up on the prebuilt and +# does a full local build. +Requires: openssl +Requires: xz Obsoletes: fuse-bcachefs < %{version}-%{release} diff --git a/bch_bindgen/build.rs b/bch_bindgen/build.rs index 7b437297b9..0e76fdc9a6 100644 --- a/bch_bindgen/build.rs +++ b/bch_bindgen/build.rs @@ -375,8 +375,17 @@ impl bindgen::callbacks::ParseCallbacks for Fix753 { fn watch_dir(dir: &str) { let Ok(entries) = std::fs::read_dir(dir) else { return }; for entry in entries.flatten() { + // file_type() reads the dirent directly - unlike Path::is_dir() it does + // NOT follow symlinks. This crate only walks bounded source dirs so it + // wasn't the one that stalled, but the shared shape follows the same + // trap: a symlink (e.g. ktest-out/kernel) into a large tree would + // stat-storm over virtiofs. Keep both watchers symlink-safe. + let Ok(file_type) = entry.file_type() else { continue }; let path = entry.path(); - if path.is_dir() { + if file_type.is_dir() { + if matches!(entry.file_name().to_str(), Some("target" | "ktest-out" | ".git")) { + continue; + } watch_dir(&path.to_string_lossy()); } else if path.extension().is_some_and(|ext| ext == "h" || ext == "c") { println!("cargo:rerun-if-changed={}", path.display()); @@ -449,6 +458,9 @@ fn main() { .bitfield_enum("btree_iter_update_trigger_flags") .bitfield_enum("bch_trans_commit_flags") .bitfield_enum("bch_write_flags") + // Block device ioctl numbers - see the note in c_src/rust_shims.h for + // why these are C constants and not macros for bindgen to evaluate. + .allowlist_var("BCH_BLK.*") .allowlist_function("raid_init") .allowlist_function("linux_shrinkers_init") .allowlist_function("sysfs_.*") diff --git a/c_src/eytzinger_test.c b/c_src/eytzinger_test.c new file mode 100644 index 0000000000..c48414176c --- /dev/null +++ b/c_src/eytzinger_test.c @@ -0,0 +1,252 @@ +// SPDX-License-Identifier: GPL-2.0 + +/* + * Unit test for the eytzinger sort + search primitive and the darray 1-based + * wrapper (darray_eytzinger1_sort / darray_eytzinger1_find) that + * snapshot_id_dying() relies on. + * + * The eytzinger layout is subtle: eytzinger1_sort() rearranges elements into + * a layout whose in-order traversal is ascending, and eytzinger1_find() does + * a BST descent over that exact layout. The two must agree on element count + * and base pointer, or find() silently returns the wrong entry - or NULL - + * for a present key. The darray wrapper adds a sentinel at index 0 and passes + * nr - 1 as the count; this pins down that off-by-one bookkeeping too. + * + * Each size runs TRIALS randomized rounds with distinct keys drawn from the + * full u32 range (snapshot ids live near U32_MAX). Every round: + * - verifies the sort DIRECTLY: eytzinger1_for_each() in-order traversal + * must equal the ascending-sorted elements, key and payload - so a + * dropped, duplicated, or mis-swapped element is caught independently of + * find(); + * - checks find() against a brute-force linear-search oracle for every + * present key plus present-adjacent and random probes. + * + * The test body is plain C so it can use the macros/static-inlines directly; + * a Rust #[test] wrapper (src/eytzinger_test.rs) invokes rust_eytzinger_test() + * so it runs under `cargo test` with no kernel. + */ + +#include + +#include "libbcachefs.h" + +#include "fs/util/darray.h" +#include "fs/util/eytzinger.h" + +#include "rust_shims.h" + +struct eyt_test_elem { u32 key; u32 tag; }; + +static int eyt_test_cmp(const void *_a, const void *_b) +{ + const struct eyt_test_elem *a = _a, *b = _b; + return (a->key > b->key) - (a->key < b->key); +} + +/* deterministic xorshift so runs are reproducible */ +static u32 eyt_rng(u32 *state) +{ + u32 x = *state; + x ^= x << 13; + x ^= x >> 17; + x ^= x << 5; + return *state = x; +} + +#define MAX_N 256 +#define TRIALS 16 + +#define TEST_FAIL(...) ({ fprintf(stderr, "rust_eytzinger_test FAIL: " __VA_ARGS__); fputc('\n', stderr); 1; }) + +/* n distinct nonzero keys (0 is never a real snapshot id), tag = index */ +static void gen_elems(struct eyt_test_elem *ref, unsigned n, u32 *seed) +{ + for (unsigned i = 0; i < n; i++) { + u32 k; +retry: + k = eyt_rng(seed); + if (!k) + goto retry; + for (unsigned j = 0; j < i; j++) + if (ref[j].key == k) + goto retry; + ref[i] = (struct eyt_test_elem){ .key = k, .tag = i }; + } +} + +/* brute-force oracle */ +static const struct eyt_test_elem *ref_find(const struct eyt_test_elem *ref, + unsigned n, u32 key) +{ + for (unsigned i = 0; i < n; i++) + if (ref[i].key == key) + return &ref[i]; + return NULL; +} + +/* ascending insertion sort of a copy, for the direct sort check (n small) */ +static void ref_sort(struct eyt_test_elem *r, unsigned n) +{ + for (unsigned i = 1; i < n; i++) { + struct eyt_test_elem v = r[i]; + unsigned j = i; + while (j && r[j - 1].key > v.key) { + r[j] = r[j - 1]; + j--; + } + r[j] = v; + } +} + +/* + * Raw eytzinger1: 1-based, elements at base[1..n], base[0] unused - mirror + * that with a size n+1 array passed as the base. + */ +static int test_eytzinger1_raw(void) +{ + int fails = 0; + u32 seed = 0x9e3779b9; + struct eyt_test_elem a[MAX_N + 1], ref[MAX_N], sorted[MAX_N]; + + for (unsigned n = 1; n <= MAX_N; n++) + for (unsigned trial = 0; trial < TRIALS; trial++) { + gen_elems(ref, n, &seed); + for (unsigned i = 0; i < n; i++) + a[i + 1] = ref[i]; + + eytzinger1_sort(a, n, sizeof(a[0]), eyt_test_cmp, NULL); + + /* direct sort check: in-order traversal == ascending sorted */ + memcpy(sorted, ref, n * sizeof(ref[0])); + ref_sort(sorted, n); + unsigned pos = 0; + eytzinger1_for_each(i, n) { + if (pos >= n) + fails += TEST_FAIL("raw n=%u: traversal longer than %u", n, n); + else if (a[i].key != sorted[pos].key || a[i].tag != sorted[pos].tag) + fails += TEST_FAIL("raw n=%u trial=%u: inorder[%u] = {%u,%u}, want {%u,%u}", + n, trial, pos, a[i].key, a[i].tag, sorted[pos].key, sorted[pos].tag); + pos++; + } + if (pos != n) + fails += TEST_FAIL("raw n=%u: traversal visited %u of %u", n, pos, n); + + /* find every present key -> the element carrying it */ + for (unsigned i = 0; i < n; i++) { + struct eyt_test_elem s = { .key = ref[i].key }; + int idx = eytzinger1_find(a, n, sizeof(a[0]), eyt_test_cmp, &s); + if (!idx) + fails += TEST_FAIL("raw n=%u: present key %u not found", n, ref[i].key); + else if (a[idx].key != ref[i].key || a[idx].tag != ref[i].tag) + fails += TEST_FAIL("raw n=%u: find(%u) = {%u,%u}, want {%u,%u}", + n, ref[i].key, a[idx].key, a[idx].tag, ref[i].key, ref[i].tag); + } + + /* probes vs oracle: present-adjacent and random keys */ + for (unsigned i = 0; i < n; i++) + for (int d = -1; d <= 1; d += 2) { + u32 key = ref[i].key + d; + struct eyt_test_elem s = { .key = key }; + int idx = eytzinger1_find(a, n, sizeof(a[0]), eyt_test_cmp, &s); + const struct eyt_test_elem *o = ref_find(ref, n, key); + if (!o != !idx) + fails += TEST_FAIL("raw n=%u: find(%u) idx=%d, oracle=%s", + n, key, idx, o ? "present" : "absent"); + } + for (unsigned p = 0; p < 2 * n; p++) { + u32 key = eyt_rng(&seed); + struct eyt_test_elem s = { .key = key }; + int idx = eytzinger1_find(a, n, sizeof(a[0]), eyt_test_cmp, &s); + const struct eyt_test_elem *o = ref_find(ref, n, key); + if (!o != !idx) + fails += TEST_FAIL("raw n=%u: find(%u) idx=%d, oracle=%s", + n, key, idx, o ? "present" : "absent"); + else if (o && a[idx].key != key) + fails += TEST_FAIL("raw n=%u: find(%u) returned key %u", n, key, a[idx].key); + } + } + + return fails; +} + +/* + * The darray 1-based wrapper exactly as snapshot_id_dying() uses it: sentinel + * at index 0, real elements at 1..nr-1, sorted and searched with nr - 1. + */ +static int test_darray_eytzinger1(void) +{ + int fails = 0; + u32 seed = 0x12345678; + struct eyt_test_elem ref[MAX_N], sorted[MAX_N]; + + for (unsigned n = 1; n <= MAX_N; n++) + for (unsigned trial = 0; trial < TRIALS; trial++) { + DARRAY(struct eyt_test_elem) d = {}; + + if (darray_push(&d, ((struct eyt_test_elem){}))) + return fails + TEST_FAIL("darray n=%u: sentinel push failed", n); + + gen_elems(ref, n, &seed); + for (unsigned i = 0; i < n; i++) + if (darray_push(&d, ref[i])) { + fails += TEST_FAIL("darray n=%u: element push failed", n); + goto next; + } + + if (d.nr != n + 1) + fails += TEST_FAIL("darray n=%u: nr=%zu, expected %u", n, d.nr, n + 1); + + darray_eytzinger1_sort(d, eyt_test_cmp); + + /* direct sort check over the sorted data[1..n] */ + memcpy(sorted, ref, n * sizeof(ref[0])); + ref_sort(sorted, n); + unsigned pos = 0; + eytzinger1_for_each(i, n) { + if (pos < n && + (d.data[i].key != sorted[pos].key || d.data[i].tag != sorted[pos].tag)) + fails += TEST_FAIL("darray n=%u trial=%u: inorder[%u] = {%u,%u}, want {%u,%u}", + n, trial, pos, d.data[i].key, d.data[i].tag, sorted[pos].key, sorted[pos].tag); + pos++; + } + if (pos != n) + fails += TEST_FAIL("darray n=%u: traversal visited %u of %u", n, pos, n); + + for (unsigned i = 0; i < n; i++) { + struct eyt_test_elem s = { .key = ref[i].key }; + struct eyt_test_elem *e = darray_eytzinger1_find(d, eyt_test_cmp, &s); + if (!e) + fails += TEST_FAIL("darray n=%u: present key %u not found", n, ref[i].key); + else if (e->key != ref[i].key || e->tag != ref[i].tag) + fails += TEST_FAIL("darray n=%u: find(%u) = {%u,%u}, want {%u,%u}", + n, ref[i].key, e->key, e->tag, ref[i].key, ref[i].tag); + } + + for (unsigned p = 0; p < 2 * n; p++) { + u32 key = eyt_rng(&seed); + struct eyt_test_elem s = { .key = key }; + struct eyt_test_elem *e = darray_eytzinger1_find(d, eyt_test_cmp, &s); + const struct eyt_test_elem *o = ref_find(ref, n, key); + if (!o != !e) + fails += TEST_FAIL("darray n=%u: find(%u) %s, oracle=%s", + n, key, e ? "hit" : "miss", o ? "present" : "absent"); + else if (o && (e->key != key || e->tag != o->tag)) + fails += TEST_FAIL("darray n=%u: find(%u) = {%u,%u}, want {%u,%u}", + n, key, e->key, e->tag, o->key, o->tag); + } +next: + darray_exit(&d); + } + + return fails; +} + +int rust_eytzinger_test(void) +{ + int fails = test_eytzinger1_raw() + test_darray_eytzinger1(); + + if (!fails) + fprintf(stderr, "rust_eytzinger_test: all cases passed (n=1..%u, %u trials each)\n", + MAX_N, TRIALS); + return fails; +} diff --git a/c_src/rust_shims.c b/c_src/rust_shims.c index bf2f968f00..b859097b6b 100644 --- a/c_src/rust_shims.c +++ b/c_src/rust_shims.c @@ -55,7 +55,7 @@ void strip_fs_alloc(struct bch_fs *c) swap(u64s, clean->field.u64s); bch2_sb_field_resize(&c->disk_sb, clean, u64s); - scoped_guard(percpu_write, &c->capacity.mark_lock) { + scoped_guard(percpu_write_noio, &c->capacity.mark_lock) { kfree(c->replicas.entries); c->replicas.entries = NULL; c->replicas.nr = 0; @@ -79,10 +79,9 @@ void strip_fs_alloc(struct bch_fs *c) void rust_strip_alloc_do(struct bch_fs *c) { - mutex_lock(&c->sb_lock); + guard(mutex_noio)(&c->sb_lock); strip_fs_alloc(c); bch2_write_super(c); - mutex_unlock(&c->sb_lock); } struct rust_journal_entries rust_collect_journal_entries(struct bch_fs *c) diff --git a/c_src/rust_shims.h b/c_src/rust_shims.h index 13183399a8..314bb89b08 100644 --- a/c_src/rust_shims.h +++ b/c_src/rust_shims.h @@ -7,6 +7,35 @@ * functions or functions whose types don't work well with bindgen. */ +#include +#include + +/* + * Block device ioctl numbers, for Rust. + * + * These encode the direction bits and sizeof() of the argument type, both of + * which vary by architecture and word size, so they can't be written down - + * they have to come from the kernel headers for the target. + * + * Taking them as bindgen macros meant going through clang_macro_fallback, which + * compiles a throwaway probe per macro and never checks whether the probe + * compiled: reparse() looks at CXErrorCode, which says whether the reparse ran + * rather than whether the code was valid, and nothing reads the diagnostics. + * Both ways that can go wrong turned up in the field in the same week - one + * build dropped BLKGETSIZE64 and failed at the use site, another kept it with + * the size field 1 instead of 8 and shipped a binary that sent the kernel an + * ioctl it answered with ENOTTY, partway through a device resize. + * + * So don't ask bindgen to evaluate these. Evaluate them the way everything else + * here gets evaluated - by the C compiler, against the real headers - and hand + * Rust a plain integer. Note that nothing below restates what _IO() and _IOR() + * mean, which is the other trap: an open-coded 0x127E for BLKROTATIONAL is + * correct on exactly the architectures whose _IOC layout you had in mind. + */ +static const unsigned long BCH_BLKGETSIZE64 = BLKGETSIZE64; +static const unsigned long BCH_BLKPBSZGET = BLKPBSZGET; +static const unsigned long BCH_BLKROTATIONAL = BLKROTATIONAL; + struct bch_fs; struct bch_sb; struct bch_csum; @@ -101,4 +130,12 @@ struct bpos; void rust_accounting_mem_read(struct bch_fs *c, struct bpos p, __u64 *v, unsigned nr); +/* + * Unit test for the eytzinger sort/search primitive and the darray 1-based + * wrapper (snapshot_id_dying's lookup path). Runs under `cargo test` via a + * Rust #[test] wrapper. Returns the number of failed assertions (0 == pass); + * failure details are printed to stderr. + */ +int rust_eytzinger_test(void); + #endif /* _RUST_SHIMS_H */ diff --git a/debian/control b/debian/control index a0daa4b231..a3a9d402b1 100644 --- a/debian/control +++ b/debian/control @@ -62,6 +62,7 @@ Architecture: linux-any Section: kernel Depends: ${misc:Depends}, openssl, + xz-utils, initramfs-tools | linux-initramfs-tool, linux-headers-generic (>= 6.16) | proxmox-headers-6.17 [amd64] | diff --git a/doc/apt.bcachefs.org-README.md b/doc/apt.bcachefs.org-README.md index 404b113f96..4458de6d64 100644 --- a/doc/apt.bcachefs.org-README.md +++ b/doc/apt.bcachefs.org-README.md @@ -10,6 +10,7 @@ URIs: https://apt.bcachefs.org/unstable/ # Or replace unstable with your distro's release name Suites: bcachefs-tools-release Components: main +Architectures: $(dpkg --print-architecture) Signed-By: /etc/apt/keyrings/apt.bcachefs.org.asc EOF sudo apt update diff --git a/doc/bcachefs-principles-of-operation.tex b/doc/bcachefs-principles-of-operation.tex index 54496865ec..62500ec679 100644 --- a/doc/bcachefs-principles-of-operation.tex +++ b/doc/bcachefs-principles-of-operation.tex @@ -608,6 +608,10 @@ \subsubsection{Device labels and targets} options: If we specify ssd in a target option, that will refer to all devices with the label ssd or labels that start with ssd. (e.g. ssd.ssd1, ssd.ssd2). +Device labels are used only for targeting. How replicas are spread across +devices to survive hardware failures is a separate, per-device property; see +\hyperref[sec:failure-domains]{Failure domains}. + Four target options exist. All may be set at the filesystem level (at format time, at mount time, or at runtime via sysfs). All except \texttt{metadata\_target} may also be set on a particular file or directory: @@ -638,20 +642,21 @@ \subsubsection{Caching and durability} \paragraph{Tiered storage with replication} Replication interacts with targets naturally: the filesystem satisfies the -configured \texttt{data\_replicas} count using durability-weighted copies, -regardless of which target they are on. For example, with -\texttt{data\_replicas=2}, \texttt{foreground\_target=ssd}, and +configured \texttt{data\_replicas} count using durability-weighted copies. +Foreground writes place all of the required durable copies on the foreground +target; the reconcile subsystem then moves them to the background target. For +example, with \texttt{data\_replicas=2}, \texttt{foreground\_target=ssd}, and \texttt{background\_target=hdd}: \begin{itemize} -\item Data is initially written to the SSD target -\item The background mover copies it to the HDD target -\item Since both SSD and HDD copies have \texttt{durability=1} by default, - each counts as one replica---the two copies together satisfy the replica - requirement -\item To use the SSDs as a pure write cache (data evictable once on HDD), - set \texttt{durability=0} on the SSD devices; the allocator will then - write two durable copies on the HDD target +\item Foreground writes place both durable copies on the SSD target, assuming + the SSD devices have enough total durability for \texttt{data\_replicas} +\item Reconcile then moves those copies to the HDD target---both replicas end + up on the HDD target, not split one per tier +\item The SSD retains a copy only as a cache: set \texttt{promote\_target=ssd} + to keep a cached copy there for fast reads (added on read, not counted as a + replica, and evicted in LRU order under space pressure), or set + \texttt{durability=0} on the SSD devices to use them as a pure write cache \end{itemize} See \hyperref[sec:devices]{Device management} in subsystem details for @@ -1095,6 +1100,58 @@ \subsection{Online self-healing} audit trail of what has been detected and repaired. The counts are visible in \texttt{bcachefs show-super} output and via the sysfs \texttt{errors} file. +\subsection{Safety mechanisms} +\label{sec:safety-mechanisms} + +\subsubsection{Subvolumes and snapshots must agree} + +A subvolume names the snapshot it is the live view of; that snapshot names the +subvolume back. Both are required: + +\begin{itemize} +\item Snapshot deletion will not reclaim a snapshot marked \texttt{will\_delete} + unless a subvolume still points at it. +\item \texttt{check\_inodes} will not reconstruct a missing subvolume key unless + the root inode's \texttt{bi\_subvol} names it \emph{and} the snapshot that inode + lives at names the same subvolume back. If only one of the two says so, + \texttt{bi\_subvol} is cleared instead of a subvolume being invented. +\end{itemize} + +Inodes and dirents reference each other the same way: an inode's +\texttt{bi\_dir} and \texttt{bi\_dir\_offset} locate its dirent, and the dirent +names the inode. Extents and the alloc btree are checked against each other +through \hyperref[sec:backpointers]{backpointers}. Snapshot parent and child +pointers must agree in both directions. + +\subsubsection{Every key implies an inode key at its snapshot} + +An extent, dirent or xattr in snapshot $X$ requires a key in the inodes btree at +$X$ for the same inode number --- an inode or a whiteout, either will do. + +Snapshot deletion relies on this to find keys: it walks the inodes btree and +descends into an inode's other btrees only where it finds a key at a dying +snapshot. A content key whose snapshot has no inodes-btree key is never +reached, so it is never migrated. The content passes enforce the requirement, +which is why they run before deletion. + +\subsubsection{Accounting} + +Accounting counters are maintained by triggers as keys are committed, not by +walking the btrees, so they are arrived at independently of the keys they +count. Snapshot deletion checks them twice: + +\begin{itemize} +\item It will not delete a dying snapshot's inode keys unless accounting reads + zero for that snapshot's extents, dirents and xattrs --- deleting them + destroys the index above, so anything left would become unreachable. +\item It will not empty or remove a node unless accounting reads zero for it. +\end{itemize} + +Either refusal schedules the content pass for the btree still holding data, +which repairs the missing inode key so the next run can find it. +\texttt{check\_allocations} rebuilds accounting from a full mark of the btrees, +which is how a stale counter is told from keys that really are still there. + \subsection{Fsck} The \texttt{bcachefs fsck} subcommand (also available as \texttt{fsck.bcachefs}) @@ -1640,6 +1697,11 @@ \subsubsection{bcachefs dump} to send the developers only the required metadata. Encrypted filesystems must first be unlocked with \texttt{bcachefs remove-passphrase}. +\subsection{kvdb: the btree REPL} +\label{sec:kvdb} + +\bchdoc{kvdb} + \section{Subsystem details} \subsection{Data paths} @@ -1657,6 +1719,11 @@ \subsection{Allocator} \bchdoc{allocator} +\subsection{Failure domains} +\label{sec:failure-domains} + +\bchdoc{failure-domains} + \subsection{Subvolumes and snapshots} \label{sec:snapshots} diff --git a/doc/docgen/src/main.rs b/doc/docgen/src/main.rs index 8e31129edf..d0b63d9844 100644 --- a/doc/docgen/src/main.rs +++ b/doc/docgen/src/main.rs @@ -155,17 +155,66 @@ fn walk_c_files(dir: &Path, f: &mut dyn FnMut(&Path)) { let path = entry.path(); if path.is_dir() { walk_c_files(&path, f); - } else if matches!(path.extension().and_then(|e| e.to_str()), Some("h" | "c")) { + } else if matches!(path.extension().and_then(|e| e.to_str()), Some("h" | "c" | "rs")) { f(&path); } } } +/// Parse a Rust string literal starting at the first `"` in @text: returns +/// the unescaped contents and the byte length consumed through the closing +/// quote. Handles \n, \t, \", \\, and \ line continuations (which, +/// like rustc, skip all following whitespace). +fn parse_rust_string_literal(text: &str) -> Option<(String, usize)> { + let start = text.find('"')?; + let mut out = String::new(); + let mut chars = text[start + 1..].char_indices().peekable(); + while let Some((i, ch)) = chars.next() { + match ch { + '"' => return Some((out, start + 1 + i + ch.len_utf8())), + '\\' => match chars.next()?.1 { + 'n' => out.push('\n'), + 't' => out.push('\t'), + '\\' => out.push('\\'), + '"' => out.push('"'), + '\n' => { + while chars.peek().is_some_and(|&(_, c)| c.is_whitespace()) { + chars.next(); + } + } + other => out.push(other), + }, + _ => out.push(ch), + } + } + None +} + fn extract_doc_blocks_from(path: &Path, source: &str, blocks: &mut Vec) { let lines: Vec<&str> = source.lines().collect(); let mut i = 0; while i < lines.len() { let trimmed = lines[i].trim(); + // DOC_STRING(key) — the following Rust string literal (typically a + // helptext constant, so one text serves --help and the PoO), + // converted like a DOC() block. + if let Some(rest) = trimmed.strip_prefix("// DOC_STRING(") { + if let Some(key) = rest.strip_suffix(')') { + let remaining = lines[i + 1..].join("\n"); + if let Some((content, consumed)) = parse_rust_string_literal(&remaining) { + blocks.push(DocBlock { + raw_latex: false, + key: key.trim().to_string(), + content: content.trim().to_string(), + file: path.to_path_buf(), + line: i + 2, + }); + i += remaining[..consumed].matches('\n').count() + 1; + } + } + i += 1; + continue; + } // DOC_LATEX(key) — raw LaTeX, passed through verbatim // DOC(key) — simple markup, converted to LaTeX let (rest, raw_latex) = if let Some(rest) = trimmed.strip_prefix("/* DOC_LATEX(") { @@ -326,8 +375,30 @@ fn markup_to_latex(content: &str) -> String { #[derive(PartialEq)] enum ListState { None, Itemize, Description } let mut list_state = ListState::None; + let mut in_verbatim = false; for line in content.lines() { + // Lines indented four or more spaces form a verbatim block - + // command tables, examples - emitted raw: + if line.starts_with(" ") { + if !in_verbatim { + match list_state { + ListState::Itemize => out.push_str("\\end{itemize}\n"), + ListState::Description => out.push_str("\\end{description}\n"), + ListState::None => {} + } + list_state = ListState::None; + out.push_str("\\begin{verbatim}\n"); + in_verbatim = true; + } + out.push_str(line); + out.push('\n'); + continue; + } + if in_verbatim { + out.push_str("\\end{verbatim}\n"); + in_verbatim = false; + } if line.is_empty() { match list_state { ListState::Itemize => { @@ -383,8 +454,8 @@ fn markup_to_latex(content: &str) -> String { out.push_str(&convert_inline(line)); out.push('\n'); } - } else if line.starts_with(" ") && list_state == ListState::Description { - // Continuation of previous description item + } else if line.starts_with(" ") && list_state != ListState::None { + // Continuation of the previous item out.push_str(&convert_inline(line.trim_start())); out.push('\n'); } else { @@ -400,6 +471,9 @@ fn markup_to_latex(content: &str) -> String { out.push('\n'); } } + if in_verbatim { + out.push_str("\\end{verbatim}\n"); + } match list_state { ListState::Itemize => out.push_str("\\end{itemize}\n"), ListState::Description => out.push_str("\\end{description}\n"), @@ -984,9 +1058,10 @@ fn main() { let mut available_keys = HashSet::new(); let mut errors = 0; - // --- DOC() blocks from C sources --- + // --- DOC() blocks from C and Rust sources --- let mut doc_blocks = extract_doc_blocks(&root.join("fs")); doc_blocks.append(&mut extract_doc_blocks(&root.join("c_src"))); + doc_blocks.append(&mut extract_doc_blocks(&root.join("src"))); for block in &doc_blocks { let latex = if block.raw_latex { diff --git a/flake.lock b/flake.lock index c4852971d7..6e2b3f8823 100644 --- a/flake.lock +++ b/flake.lock @@ -2,11 +2,11 @@ "nodes": { "crane": { "locked": { - "lastModified": 1780099841, - "narHash": "sha256-EVZd2RsbpreRUDSi9rBwPY+ZxoyMaiEBbZxxhljbaS4=", + "lastModified": 1785782307, + "narHash": "sha256-MPaRdVkf6zZP5fCPxYCi8Dr4pZzgmXzg8T9nVEbp3Mw=", "owner": "ipetkov", "repo": "crane", - "rev": "0532eb17955225173906d671fb36306bdeb1e2dc", + "rev": "2c71e194474d13de031d729b729c968ddbe3507f", "type": "github" }, "original": { @@ -36,11 +36,11 @@ "nixpkgs-lib": "nixpkgs-lib" }, "locked": { - "lastModified": 1778716662, - "narHash": "sha256-m1Yf0wZ8j1OHjTc2UwHwyQRSnNeSgLJOd7q5Y45hzi4=", + "lastModified": 1785627969, + "narHash": "sha256-4dtXQk/NMePegK/nWp5NSeuZKLATItOq61lpEvmXqGw=", "owner": "hercules-ci", "repo": "flake-parts", - "rev": "f7c1a2d347e4c52d5fb8d10cb4d94b5884e546fb", + "rev": "427bf4bd9435fdf21321c8cc628c24efc14c0f7a", "type": "github" }, "original": { @@ -71,11 +71,11 @@ }, "nixpkgs": { "locked": { - "lastModified": 1782467914, - "narHash": "sha256-pGvFkM8N0xEkIIXDe5YYfbEAvHrk4IxBrjB/x8OomhE=", + "lastModified": 1785967620, + "narHash": "sha256-IItrdb7Puk05RqOBWZYFC5X6Wl1sJmCfh5MWVHw5iMM=", "owner": "nixos", "repo": "nixpkgs", - "rev": "e73de5be04e0eff4190a1432b946d469c794e7b4", + "rev": "b7c2ada94fe99c15b0dbcf4d11fd7850b957a436", "type": "github" }, "original": { @@ -87,11 +87,11 @@ }, "nixpkgs-lib": { "locked": { - "lastModified": 1777168982, - "narHash": "sha256-GOkGPcboWE9BmGCRMLX3worL4EMnsnG8MyKmXNeYuhQ=", + "lastModified": 1785031560, + "narHash": "sha256-OmshNvn2vupOFpYinLUu+1Dnpu4n7Q5N3ggGVNHpkUI=", "owner": "nix-community", "repo": "nixpkgs.lib", - "rev": "f5901329dade4a6ea039af1433fb087bd9c1fe14", + "rev": "0e79af5e3d4dcfcd676ab5ba3f95d2e3352e078c", "type": "github" }, "original": { @@ -118,11 +118,11 @@ ] }, "locked": { - "lastModified": 1780110990, - "narHash": "sha256-6QBThUi7SuK+dgA+DCaEkQGZN4kYx6DpXmK45+MG9zI=", + "lastModified": 1786076960, + "narHash": "sha256-jfR6OhwurCKn1tREyfOcK/Omxf1Q/DzDDFbnEr1mBLs=", "owner": "oxalica", "repo": "rust-overlay", - "rev": "85570ef134d92a8702de6afd1f6f0209c863fa91", + "rev": "57a23bfaf4f7017267294b161175db1e32eb1c85", "type": "github" }, "original": { @@ -138,11 +138,11 @@ ] }, "locked": { - "lastModified": 1775636079, - "narHash": "sha256-pc20NRoMdiar8oPQceQT47UUZMBTiMdUuWrYu2obUP0=", + "lastModified": 1785945821, + "narHash": "sha256-NLSyTCW4K4ofhNBllt3omPasm6QpralXH1DBZOc91Dw=", "owner": "numtide", "repo": "treefmt-nix", - "rev": "790751ff7fd3801feeaf96d7dc416a8d581265ba", + "rev": "ae7910970dddc408fe6ab1c8e4b277bb21d72dc0", "type": "github" }, "original": { diff --git a/flake.nix b/flake.nix index 5b8f4f132c..4376d66914 100644 --- a/flake.nix +++ b/flake.nix @@ -126,20 +126,52 @@ packages // { default = self'.packages.${cargoToml.package.name}; + # The whole repo is the source, not just ./doc: most of the + # document is generated from it. bch-docgen extracts DOC_LATEX + # blocks out of fs/**.{c,h,rs} and the option x-macros, and + # `bcachefs _doc_gen` emits the CLI reference from the clap + # definitions. Both locate the tree by walking up for fs/ and + # write into doc/generated/, which is not checked in - so they + # have to run here, from the source root, before pdflatex. doc = pkgs.stdenv.mkDerivation { pname = "bcachefs-tools-doc"; inherit version; - src = ./doc; - buildInputs = with pkgs; [ + src = ./.; + nativeBuildInputs = [ latexDerivation + pkgs.rustc + self'.packages.default ]; buildPhase = '' - pdflatex bcachefs-principles-of-operation.tex - pdflatex bcachefs-principles-of-operation.tex + runHook preBuild + + # bch-docgen is a dependency-free single file, so plain + # rustc builds it - no need to drag in the cargo workspace. + # _doc_gen runs first: it writes cli-reference.tex, and + # bch-docgen checks that every \bchdoc{} in the PoO resolves. + rustc -O doc/docgen/src/main.rs -o bch-docgen + bcachefs _doc_gen + ./bch-docgen + # As an argument, not a format string: printf would read the + # \r and \b in the LaTeX as carriage return and backspace. + printf '%s\n' '\renewcommand{\bchdocversion}{${version}}' \ + > doc/generated/build-version.tex + + # Twice, to resolve the table of contents and cross-references: + for i in 1 2; do + pdflatex -interaction=nonstopmode -halt-on-error \ + doc/bcachefs-principles-of-operation.tex + done + + runHook postBuild ''; + # share/doc, not doc: stdenv's move-docs hook relocates $out/doc + # anyway, so name the real path rather than let it be moved. installPhase = '' - mkdir -p $out/doc - cp bcachefs-principles-of-operation.pdf $out/doc + runHook preInstall + mkdir -p $out/share/doc + cp bcachefs-principles-of-operation.pdf $out/share/doc + runHook postInstall ''; }; }; diff --git a/fs/Makefile b/fs/Makefile index 971e8e680c..93c731ef52 100644 --- a/fs/Makefile +++ b/fs/Makefile @@ -16,6 +16,10 @@ ifneq ($(bcachefs-version),) ifeq ($(shell $(CONFIG_SHELL) $(src)/scripts/fetch-module.sh '$(KERNELRELEASE)' '$(bcachefs-version)' '$(obj)/bcachefs.ko' && echo hit),hit) CONFIG_BCACHEFS_FS := endif +else +# No version means no lookup key — say so rather than silently compiling: +# the missing file is the tell that this tree wasn't staged the supported way. +$(warning bcachefs: no version in $(src)/version.h - not looking for a prebuilt module (version.h is staged by bcachefs-tools 'make install_dkms'; a hand-copied kernel fs/bcachefs/ tree lacks it)) endif endif @@ -156,6 +160,7 @@ bcachefs-y := \ fs/xattr.o \ init/chardev.o \ init/dev.o \ + init/damage.o \ init/error.o \ init/fs.o \ init/progress.o \ @@ -185,6 +190,7 @@ bcachefs-y := \ util/enumerated_ref.o \ util/eytzinger.o \ util/fast_list.o \ + util/locking.o \ util/mean_and_variance.o \ util/printbuf.o \ util/rcu_pending.o \ @@ -215,7 +221,14 @@ ifndef BCACHEFS_DKMS endif ifdef BCACHEFS_DKMS +ifneq ($(wildcard $(src)/module-version.c),) bcachefs-y += module-version.o +else +# Staged by bcachefs-tools 'make install_dkms'; a hand-copied kernel +# fs/bcachefs/ tree lacks it. Degrade rather than fail with a bare +# "no rule to make target" (field report: CRCinAU, 2026-07-23). +$(warning bcachefs: $(src)/module-version.c missing - module will carry no MODULE_VERSION) +endif endif # Rust support — optional, gated on CONFIG_RUST. The C side owns the module @@ -437,10 +450,23 @@ $(obj)/rust/extern.c: $(obj)/rust/bcachefs.rs ; CFLAGS_rust/extern.o += -Wno-missing-prototypes -Wno-missing-declarations # Kernel trees < 6.18 pass -Zno-jump-tables in KBUILD_RUSTFLAGS, written for -# their era's pinned rustc; ours has it stabilized as -Cjump-tables=n. Rewrite -# the underlying variable - rust_flags expands it lazily, so this covers every -# Rust rule below and in the vendored includes. +# their era's pinned rustc; newer rustc has it stabilized as -Cjump-tables=n. +# Rewrite the underlying variable - rust_flags expands it lazily, so this covers +# every Rust rule below and in the vendored includes. +# +# Only rewrite when $(RUSTC) actually accepts the stable spelling. rustc from +# before the stabilization rejects it outright: +# +# $ rustc -Cjump-tables=n --print=sysroot +# error: unknown codegen option: `jump-tables` +# +# so rewriting unconditionally turns a working build into a hard failure on +# those toolchains, which is worse than leaving the flag the kernel chose. +rustc-has-cjump-tables := $(shell $(RUSTC) -Cjump-tables=n --print=sysroot \ + >/dev/null 2>&1 && echo y || echo n) +ifeq ($(rustc-has-cjump-tables),y) KBUILD_RUSTFLAGS := $(patsubst -Zno-jump-tables,-Cjump-tables=n,$(KBUILD_RUSTFLAGS)) +endif # mod.rs keys on cfg(kernel) to source the kernel-compat types from the kernel # crate (vs bcachefs-shim in userspace); the kernel build doesn't set it on its @@ -485,6 +511,19 @@ $(obj)/bitfield.o: $(src)/vendor/bitfield/src/lib.rs FORCE $(obj)/bitflags.o: $(src)/vendor/bitflags/src/lib.rs FORCE $(call if_changed_dep,bch_library) +# The kernel builds Rust with -Wrust_2018_idioms, which CONFIG_WERROR turns +# into -Dwarnings; the vendored uuid predates both of the lifetime lints that +# implies and trips 11 of them. Those lints are a statement about how we want +# our own code written - they say nothing about whether someone else's crate is +# correct - so allow them here rather than patching a vendored tree we would +# have to re-patch on every refresh. +# +# Both are needed: elided_lifetimes_in_paths accounts for 6 and +# mismatched_lifetime_syntaxes for the other 5, so allowing only the one named +# in the bug report leaves the build broken. bitfield and bitflags are clean +# under the same flags, which is why this is scoped to uuid.o. +RUSTFLAGS_uuid.o += -Aelided_lifetimes_in_paths -Amismatched_lifetime_syntaxes + $(obj)/uuid.o: $(src)/vendor/uuid/src/lib.rs FORCE $(call if_changed_dep,bch_library) diff --git a/fs/alloc/accounting.c b/fs/alloc/accounting.c index 9817de59e2..5d54239c91 100644 --- a/fs/alloc/accounting.c +++ b/fs/alloc/accounting.c @@ -1,14 +1,21 @@ // SPDX-License-Identifier: GPL-2.0 +#include "alloc/background.h" +#include "alloc/format.h" #include "bcachefs.h" +#include "bcachefs_format.h" #include "bcachefs_ioctl.h" +#include "alloc/accounting_format.h" #include "alloc/accounting.h" #include "alloc/buckets.h" #include "alloc/replicas.h" +#include "btree/bkey_types.h" #include "btree/cache.h" +#include "btree/iter.h" #include "btree/journal_overlay.h" +#include "btree/types.h" #include "btree/update.h" #include "btree/write_buffer.h" @@ -98,9 +105,15 @@ static inline void accounting_key_init(struct bkey_i *k, struct disk_accounting_ static int bch2_accounting_update_sb_one(struct bch_fs *, struct bpos); -int bch2_disk_accounting_mod(struct btree_trans *trans, +int bch2_accounting_mem_add(struct btree_trans *trans, struct bkey_s_c_accounting a, + enum bch_accounting_mode mode, bool write_locked) +{ + return bch2_accounting_mem_add_inlined(trans, a, mode, write_locked); +} + +int bch2_disk_accounting_mod_normal(struct btree_trans *trans, struct disk_accounting_pos *k, - s64 *d, unsigned nr, bool gc) + s64 *d, unsigned nr) { BUG_ON(nr > BCH_ACCOUNTING_MAX_COUNTERS); @@ -115,46 +128,71 @@ int bch2_disk_accounting_mod(struct btree_trans *trans, } struct bpos pos = disk_accounting_pos_to_bpos(k); + struct bkey_i_accounting *a; + + for (a = btree_trans_subbuf_base(trans, &trans->accounting); + a != btree_trans_subbuf_top(trans, &trans->accounting); + a = (void *) bkey_next(&a->k_i)) + if (bpos_eq(a->k.p, pos) && + bch2_accounting_counters(&a->k) == nr) { + acc_u64s(a->v.d, d, nr); + + if (bch2_accounting_key_is_zero(accounting_i_to_s_c(a))) { + unsigned offset = (u64 *) a - + (u64 *) btree_trans_subbuf_base(trans, &trans->accounting); + + trans->accounting.u64s -= a->k.u64s; + memmove_u64s_down(a, + bkey_next(&a->k_i), + trans->accounting.u64s - offset); + } + return 0; + } - if (likely(!gc)) { - struct bkey_i_accounting *a; + unsigned u64s = sizeof(*a) / sizeof(u64) + nr; + a = errptr_try(bch2_trans_subbuf_alloc(trans, &trans->accounting, u64s)); - for (a = btree_trans_subbuf_base(trans, &trans->accounting); - a != btree_trans_subbuf_top(trans, &trans->accounting); - a = (void *) bkey_next(&a->k_i)) - if (bpos_eq(a->k.p, pos) && - bch2_accounting_counters(&a->k) == nr) { - acc_u64s(a->v.d, d, nr); + __accounting_key_init(&a->k_i, pos, d, nr); + return 0; +} - if (bch2_accounting_key_is_zero(accounting_i_to_s_c(a))) { - unsigned offset = (u64 *) a - - (u64 *) btree_trans_subbuf_base(trans, &trans->accounting); +int bch2_disk_accounting_mod_gc(struct btree_trans *trans, + struct disk_accounting_pos *k, + s64 *d, unsigned nr) +{ + BUG_ON(nr > BCH_ACCOUNTING_MAX_COUNTERS); - trans->accounting.u64s -= a->k.u64s; - memmove_u64s_down(a, - bkey_next(&a->k_i), - trans->accounting.u64s - offset); - } - return 0; - } + BUG_ON(k->type >= BCH_DISK_ACCOUNTING_TYPE_NR); + EBUG_ON(nr != bch2_accounting_type_nr_counters[k->type]); - unsigned u64s = sizeof(*a) / sizeof(u64) + nr; - a = errptr_try(bch2_trans_subbuf_alloc(trans, &trans->accounting, u64s)); + /* Normalize: */ + switch (k->type) { + case BCH_DISK_ACCOUNTING_replicas: + bubble_sort(k->replicas.devs, k->replicas.nr_devs, u8_cmp); + break; + } - __accounting_key_init(&a->k_i, pos, d, nr); - return 0; - } else { - struct { __BKEY_PADDED(k, BCH_ACCOUNTING_MAX_COUNTERS); } k_i; + struct { __BKEY_PADDED(k, BCH_ACCOUNTING_MAX_COUNTERS); } k_i; - __accounting_key_init(&k_i.k, pos, d, nr); + __accounting_key_init(&k_i.k, disk_accounting_pos_to_bpos(k), d, nr); - int ret = bch2_accounting_mem_add(trans, bkey_i_to_s_c_accounting(&k_i.k), true); - if (ret == -BCH_ERR_btree_insert_need_mark_replicas) - ret = drop_locks_do(trans, - bch2_accounting_update_sb_one(trans->c, disk_accounting_pos_to_bpos(k))) ?: - bch2_accounting_mem_add(trans, bkey_i_to_s_c_accounting(&k_i.k), true); - return ret; + int ret = 0; + + while (true) { + scoped_guard(percpu_read_noio, &trans->c->capacity.mark_lock) + ret = bch2_accounting_mem_add_inlined(trans, + bkey_i_to_s_c_accounting(&k_i.k), + BCH_ACCOUNTING_gc, + false); + if (likely(ret != -BCH_ERR_btree_insert_need_mark_replicas)) + break; + + ret = drop_locks_do(trans, bch2_accounting_update_sb_one(trans->c, k_i.k.k.p)); + if (ret) + break; } + + return ret; } int bch2_mod_dev_cached_sectors(struct btree_trans *trans, @@ -431,14 +469,17 @@ int bch2_accounting_mem_insert(struct bch_fs *c, struct bkey_s_c_accounting a, !bch2_replicas_marked_locked(c, &r.e)) return bch_err_throw(c, btree_insert_need_mark_replicas); - percpu_up_read(&c->capacity.mark_lock); + /* + * Raw of the inner rwsem: our caller holds mark_lock read via + * percpu_read_noio, so PF_MEMALLOC_NOIO stays set across this temporary + * upgrade to write - the raw up/down only move the lock, not the + * memalloc scope. + */ + percpu_up_read(&c->capacity.mark_lock.lock); int ret; - scoped_guard(percpu_write, &c->capacity.mark_lock) { - guard(memalloc_flags)(PF_MEMALLOC_NOFS); - + scoped_guard(percpu_write_noio, &c->capacity.mark_lock) ret = __bch2_accounting_mem_insert(c, a); - } - percpu_down_read(&c->capacity.mark_lock); + percpu_down_read(&c->capacity.mark_lock.lock); return ret; } @@ -477,9 +518,8 @@ void __bch2_accounting_maybe_kill(struct bch_fs *c, struct bpos pos) !bch2_request_incompat_feature(c, bcachefs_metadata_version_no_sb_user_data_replicas)) return; - guard(memalloc_flags)(PF_MEMALLOC_NOFS); - guard(mutex)(&c->sb_lock); - scoped_guard(percpu_write, &c->capacity.mark_lock) { + guard(mutex_noio)(&c->sb_lock); + scoped_guard(percpu_write_noio, &c->capacity.mark_lock) { struct bch_accounting_mem *acc = &c->accounting; @@ -510,7 +550,7 @@ void bch2_accounting_mem_gc(struct bch_fs *c) { struct bch_accounting_mem *acc = &c->accounting; - guard(percpu_write)(&c->capacity.mark_lock); + guard(percpu_write_noio)(&c->capacity.mark_lock); struct accounting_mem_entry *dst = acc->k.data; darray_for_each(acc->k, src) { @@ -539,7 +579,7 @@ int bch2_fs_replicas_usage_read(struct bch_fs *c, darray_char *usage) { struct bch_accounting_mem *acc = &c->accounting; - guard(percpu_read)(&c->capacity.mark_lock); + guard(percpu_read_noio)(&c->capacity.mark_lock); darray_for_each(acc->k, i) { union { u8 bytes[struct_size_t(struct bch_replicas_usage, r.devs, @@ -571,7 +611,7 @@ int bch2_fs_accounting_read(struct bch_fs *c, darray_char *out_buf, unsigned acc darray_init(out_buf); - guard(percpu_read)(&c->capacity.mark_lock); + guard(percpu_read_noio)(&c->capacity.mark_lock); darray_for_each(acc->k, i) { struct disk_accounting_pos a_p; bpos_to_disk_accounting_pos(&a_p, i->pos); @@ -634,8 +674,7 @@ int bch2_gc_accounting_start(struct bch_fs *c) struct bch_accounting_mem *acc = &c->accounting; int ret = 0; - guard(percpu_write)(&c->capacity.mark_lock); - guard(memalloc_flags)(PF_MEMALLOC_NOFS); + guard(percpu_write_noio)(&c->capacity.mark_lock); darray_for_each(acc->k, e) { e->v[1] = __alloc_percpu_gfp(e->nr_counters * sizeof(u64), @@ -659,8 +698,7 @@ int bch2_gc_accounting_done(struct bch_fs *c) struct bpos pos = POS_MIN; int ret = 0; - guard(percpu_write)(&c->capacity.mark_lock); - guard(memalloc_flags)(PF_MEMALLOC_NOFS); + guard(percpu_write_noio)(&c->capacity.mark_lock); while (1) { unsigned idx = eytzinger0_find_ge(acc->k.data, acc->k.nr, sizeof(acc->k.data[0]), @@ -704,11 +742,18 @@ int bch2_gc_accounting_done(struct bch_fs *c) bch2_trans_unlock_long(trans); if (fsck_err(c, accounting_mismatch, "%s", buf.buf)) { - percpu_up_write(&c->capacity.mark_lock); + /* + * Raw drop/retake of just the lock to run + * commit_do: the guard(percpu_write_noio) at the + * top of the function keeps PF_MEMALLOC_NOIO set + * the whole time, even though the trans was + * unlocked above. + */ + percpu_up_write(&c->capacity.mark_lock.lock); ret = commit_do(trans, NULL, NULL, BCH_TRANS_COMMIT_skip_accounting_apply, bch2_disk_accounting_mod(trans, &acc_k, src_v, nr, false)); - percpu_down_write(&c->capacity.mark_lock); + percpu_down_write(&c->capacity.mark_lock.lock); if (ret) goto err; @@ -717,7 +762,7 @@ int bch2_gc_accounting_done(struct bch_fs *c) struct { __BKEY_PADDED(k, BCH_ACCOUNTING_MAX_COUNTERS); } k_i; accounting_key_init(&k_i.k, &acc_k, src_v, nr); - bch2_accounting_mem_mod_locked(trans, + bch2_accounting_mem_add(trans, bkey_i_to_s_c_accounting(&k_i.k), BCH_ACCOUNTING_normal, true); @@ -865,8 +910,16 @@ static int bch2_disk_accounting_validate_late(struct btree_trans *trans, "accounting not marked in superblock replicas\n%s", (printbuf_reset(&buf), bch2_accounting_key_to_text(&buf, c, acc), - buf.buf))) + buf.buf))) { try(bch2_mark_replicas(c, &r.e)); + /* + * bch2_mark_replicas() updates the superblock, not the + * transaction, so commit here to flush the fsck_err log + * entry - the caller loops back into a lockrestart_do + * whose trans_begin would otherwise discard it. + */ + try(bch2_trans_commit(trans, NULL, NULL, BCH_TRANS_COMMIT_no_enospc)); + } break; } @@ -1214,6 +1267,55 @@ int bch2_accounting_read(struct bch_fs *c) return accounting_read_mem_fixups(trans); } +int bch2_dev_truncate_accounting(struct bch_fs *c, struct bch_dev *ca, u64 old_nbuckets, u64 cutoff) { + struct bpos start = POS(ca->dev_idx, cutoff); + struct bpos end = POS(ca->dev_idx, old_nbuckets); + + CLASS(btree_trans, trans)(c); + + /* accumulate deltas per data type, then apply them */ + return commit_do(trans, NULL, NULL, 0, ({ + s64 delta[BCH_DATA_NR][3] = {}; + s64 keys = 0; + struct bkey_s_c k; + int ret = 0; + + for_each_btree_key_max_norestart(trans, iter, BTREE_ID_alloc, start, end, BTREE_ITER_prefetch, k, ret) { + if (!k.k->type) + continue; + + struct bch_alloc_v4 _alloc; + const struct bch_alloc_v4 *alloc = bch2_alloc_to_v4(k, &_alloc); + + enum bch_data_type data_type = alloc->data_type; + + delta[data_type][0] -= 1; + delta[data_type][1] -= bch2_bucket_sectors(*alloc); + delta[data_type][2] -= bch2_bucket_sectors_fragmented(ca, *alloc); + + s64 unstriped = bch2_bucket_sectors_unstriped(*alloc); + if (unstriped) { + delta[BCH_DATA_unstriped][0] -= 1; + delta[BCH_DATA_unstriped][1] -= unstriped; + } + + keys++; + } + if (!ret) { + delta[BCH_DATA_free][0] -= (old_nbuckets - cutoff) - keys; + + for (unsigned type = 0; type < BCH_DATA_NR; type++) { + ret = bch2_disk_accounting_mod2(trans, false, delta[type], dev_data_type, .dev = ca->dev_idx, .data_type = type); + + if (ret) + break; + } + } + + ret; + })); +} + int bch2_dev_usage_remove(struct bch_fs *c, struct bch_dev *ca) { CLASS(btree_trans, trans)(c); @@ -1392,7 +1494,7 @@ void bch2_verify_accounting_clean(struct bch_fs *c) void bch2_accounting_gc_free(struct bch_fs *c) { - lockdep_assert_held(&c->capacity.mark_lock); + lockdep_assert_held(&c->capacity.mark_lock.lock); struct bch_accounting_mem *acc = &c->accounting; diff --git a/fs/alloc/accounting.h b/fs/alloc/accounting.h index 11b4317392..9cd500f1a4 100644 --- a/fs/alloc/accounting.h +++ b/fs/alloc/accounting.h @@ -97,8 +97,19 @@ static inline struct bpos disk_accounting_pos_to_bpos(struct disk_accounting_pos return p; } -int bch2_disk_accounting_mod(struct btree_trans *, struct disk_accounting_pos *, - s64 *, unsigned, bool); +int bch2_disk_accounting_mod_normal(struct btree_trans *, struct disk_accounting_pos *, + s64 *, unsigned); +int bch2_disk_accounting_mod_gc(struct btree_trans *, struct disk_accounting_pos *, + s64 *, unsigned); + +static inline int bch2_disk_accounting_mod(struct btree_trans *trans, + struct disk_accounting_pos *k, + s64 *d, unsigned nr, bool gc) +{ + return likely(!gc) + ? bch2_disk_accounting_mod_normal(trans, k, d, nr) + : bch2_disk_accounting_mod_gc(trans, k, d, nr); +} #define disk_accounting_key_init(_k, _type, ...) \ do { \ @@ -151,7 +162,6 @@ void bch2_accounting_mem_gc(struct bch_fs *); static inline bool bch2_accounting_is_mem(struct disk_accounting_pos *acc) { return acc->type < BCH_DISK_ACCOUNTING_TYPE_NR && - acc->type != BCH_DISK_ACCOUNTING_snapshot && acc->type != BCH_DISK_ACCOUNTING_inum; } @@ -169,10 +179,11 @@ static inline bool bch2_bkey_is_accounting_mem(struct bkey *k) * Update in memory counters so they match the btree update we're doing; called * from transaction commit path */ -static inline int bch2_accounting_mem_mod_locked(struct btree_trans *trans, - struct bkey_s_c_accounting a, - enum bch_accounting_mode mode, - bool write_locked) +static __always_inline +int bch2_accounting_mem_add_inlined(struct btree_trans *trans, + struct bkey_s_c_accounting a, + enum bch_accounting_mode mode, + bool write_locked) { struct bch_fs *c = trans->c; struct bch_accounting_mem *acc = &c->accounting; @@ -230,11 +241,8 @@ static inline int bch2_accounting_mem_mod_locked(struct btree_trans *trans, return 0; } -static inline int bch2_accounting_mem_add(struct btree_trans *trans, struct bkey_s_c_accounting a, bool gc) -{ - guard(percpu_read)(&trans->c->capacity.mark_lock); - return bch2_accounting_mem_mod_locked(trans, a, gc ? BCH_ACCOUNTING_gc : BCH_ACCOUNTING_normal, false); -} +int bch2_accounting_mem_add(struct btree_trans *, struct bkey_s_c_accounting, + enum bch_accounting_mode, bool); static inline void bch2_accounting_mem_read_counters(struct bch_accounting_mem *acc, unsigned idx, u64 *v, unsigned nr, bool gc) @@ -255,7 +263,20 @@ static inline void bch2_accounting_mem_read_counters(struct bch_accounting_mem * static inline void bch2_accounting_mem_read_locked(struct bch_fs *c, struct bpos p, u64 *v, unsigned nr) { - percpu_rwsem_assert_held(&c->capacity.mark_lock); + percpu_rwsem_assert_held(&c->capacity.mark_lock.lock); + + /* + * Types not in the mem table read back as zeros - not an error, a + * silently wrong answer: bch2_snapshot_node_check_no_data()'s empty + * check read zeros from the day it was added, licensing no_keys + * transitions that stranded live keys. Non-mem types must be read + * from the accounting btree. + */ + EBUG_ON(({ + struct disk_accounting_pos acc_k; + bpos_to_disk_accounting_pos(&acc_k, p); + !bch2_accounting_is_mem(&acc_k); + })); struct bch_accounting_mem *acc = &c->accounting; unsigned idx = eytzinger0_find(acc->k.data, acc->k.nr, sizeof(acc->k.data[0]), @@ -267,7 +288,7 @@ static inline void bch2_accounting_mem_read_locked(struct bch_fs *c, struct bpos static inline void bch2_accounting_mem_read(struct bch_fs *c, struct bpos p, u64 *v, unsigned nr) { - guard(percpu_read)(&c->capacity.mark_lock); + guard(percpu_read_noio)(&c->capacity.mark_lock); bch2_accounting_mem_read_locked(c, p, v, nr); } @@ -291,7 +312,7 @@ static inline int bch2_accounting_trans_commit_hook(struct btree_trans *trans, EBUG_ON(bversion_zero(a->k.bversion)); return likely(!(commit_flags & BCH_TRANS_COMMIT_skip_accounting_apply)) - ? bch2_accounting_mem_mod_locked(trans, accounting_i_to_s_c(a), BCH_ACCOUNTING_normal, false) + ? bch2_accounting_mem_add_inlined(trans, accounting_i_to_s_c(a), BCH_ACCOUNTING_normal, false) : 0; } @@ -303,7 +324,7 @@ static inline void bch2_accounting_trans_commit_revert(struct btree_trans *trans struct bkey_s_accounting a = accounting_i_to_s(a_i); bch2_accounting_neg(a); - bch2_accounting_mem_mod_locked(trans, a.c, BCH_ACCOUNTING_normal, false); + bch2_accounting_mem_add(trans, a.c, BCH_ACCOUNTING_normal, false); bch2_accounting_neg(a); } } @@ -324,6 +345,9 @@ int bch2_gc_accounting_done(struct bch_fs *); int bch2_accounting_read(struct bch_fs *); + +int bch2_dev_truncate_accounting(struct bch_fs *, struct bch_dev *, u64, u64); + int bch2_dev_usage_remove(struct bch_fs *, struct bch_dev *); int bch2_dev_usage_init(struct bch_dev *, bool); diff --git a/fs/alloc/accounting_format.h b/fs/alloc/accounting_format.h index 81df920a0a..e8b9bbf7f8 100644 --- a/fs/alloc/accounting_format.h +++ b/fs/alloc/accounting_format.h @@ -10,7 +10,7 @@ * Here, the key has considerably more structure than a typical key (bpos); an * accounting key is 'struct disk_accounting_pos', which is a union of bpos. * - * More specifically: a key is just a muliword integer (where word endianness + * More specifically: a key is just a multiword integer (where word endianness * matches native byte order), so we're treating bpos as an opaque 20 byte * integer and mapping bch_accounting_key to that. * diff --git a/fs/alloc/background.c b/fs/alloc/background.c index d05370d18b..7b8bf2e589 100644 --- a/fs/alloc/background.c +++ b/fs/alloc/background.c @@ -433,8 +433,9 @@ * metadata if \texttt{metadata\_target} is not set. * \item[\texttt{metadata\_target}] Btree node writes. * \item[\texttt{background\_target}] If set, user data is moved to this target - * in the background by the reconcile subsystem. The original copy is left in - * place but marked as cached. + * in the background by the reconcile subsystem. The durable copies are moved + * off the foreground target; a copy is left on the original target only if it + * is a cache (see \texttt{promote\_target} or \texttt{durability=0}). * \item[\texttt{promote\_target}] If set, a cached copy is created on this * target when data is read, if no copy exists there already. * \end{description} @@ -800,13 +801,13 @@ static inline __cold void __bch2_alloc_v4_to_text(struct printbuf *out, struct b bch2_prt_data_type(out, a->data_type); prt_newline(out); prt_printf(out, "journal_seq_nonempty %llu\n", a->journal_seq_nonempty); - if (bkey_val_bytes(k.k) > offsetof(struct bch_alloc_v4, journal_seq_empty)) + if (bkey_has_field(k.k, alloc_v4, journal_seq_empty)) prt_printf(out, "journal_seq_empty %llu\n", a->journal_seq_empty); prt_printf(out, "need_discard %llu\n", BCH_ALLOC_V4_NEED_DISCARD(a)); prt_printf(out, "need_inc_gen %llu\n", BCH_ALLOC_V4_NEED_INC_GEN(a)); prt_printf(out, "dirty_sectors %u\n", a->dirty_sectors); - if (bkey_val_bytes(k.k) > offsetof(struct bch_alloc_v4, stripe_sectors)) + if (bkey_has_field(k.k, alloc_v4, stripe_sectors)) prt_printf(out, "stripe_sectors %u\n", a->stripe_sectors); prt_printf(out, "cached_sectors %u\n", a->cached_sectors); prt_printf(out, "stripe_refcount %u\n", a->stripe_refcount); @@ -1099,6 +1100,52 @@ int bch2_alloc_read(struct bch_fs *c) return ret; } +int bch2_dev_remove_bucket_gens(struct bch_fs *c, struct bch_dev *ca, u64 cutoff) +{ + unsigned offset; + struct bpos pos = alloc_gens_pos(POS(ca->dev_idx, cutoff), &offset); + + /* cutoff on key boundary */ + if (!offset) + return bch2_btree_delete_range(c, BTREE_ID_bucket_gens, + pos, + POS(ca->dev_idx, U64_MAX), + BTREE_TRIGGER_norun); + + /* Cutoff mid-key + * + * Scope the zero-tail-gens transaction so it is cleared + * before bch2_btree_delete_range creates its own transaction. + */ + { + CLASS(btree_trans, trans)(c); + + /* zero tail gens */ + try(commit_do(trans, NULL, NULL, BCH_TRANS_COMMIT_no_enospc, ({ + CLASS(btree_iter, iter)(trans, BTREE_ID_bucket_gens, pos, BTREE_ITER_intent); + struct bkey_s_c k = bkey_try(bch2_btree_iter_peek_slot(&iter)); + + try(bkey_err(k)); + + if (k.k->type == KEY_TYPE_bucket_gens) { + struct bkey_i_bucket_gens *g = + errptr_try(bch2_trans_kmalloc(trans, sizeof(*g))); + + bkey_reassemble(&g->k_i, k); + memset(&g->v.gens[offset], 0, sizeof(g->v.gens) - offset); + try(bch2_trans_update(trans, &iter, &g->k_i, 0)); + } + 0; + }))); + } + + /* delete remaining keys */ + return bch2_btree_delete_range(c, BTREE_ID_bucket_gens, + bpos_nosnap_successor(pos), + POS(ca->dev_idx, U64_MAX), + BTREE_TRIGGER_norun); +} + /* Free space/discard btree: */ int bch2_bucket_do_freespace_index(struct btree_trans *trans, @@ -1488,9 +1535,9 @@ int bch2_trigger_alloc(struct btree_trans *trans, struct btree_trigger_op op) return ret; } -/* device removal */ +/* device removal / shrinking */ -static int bch2_dev_remove_need_discard(struct bch_fs *c, struct bch_dev *ca) +static int bch2_dev_remove_need_discard(struct bch_fs *c, struct bch_dev *ca, u64 cutoff) { CLASS(btree_trans, trans)(c); unsigned dev_idx = ca->dev_idx; @@ -1498,37 +1545,39 @@ static int bch2_dev_remove_need_discard(struct bch_fs *c, struct bch_dev *ca) return for_each_btree_key_commit(trans, iter, BTREE_ID_need_discard, POS_MIN, BTREE_ITER_intent|BTREE_ITER_prefetch, k, - NULL, NULL, BCH_TRANS_COMMIT_no_enospc, ({ + NULL, NULL, BCH_WATERMARK_reclaim| + BCH_TRANS_COMMIT_no_enospc, ({ struct bpos bucket = u64_to_bucket(k.k->p.offset); - (bucket.inode == dev_idx) + (bucket.inode == dev_idx && bucket.offset >= cutoff) ? bch2_btree_delete_at(trans, &iter, BTREE_TRIGGER_norun) : 0; })); } -int bch2_dev_remove_alloc(struct bch_fs *c, struct bch_dev *ca) +int bch2_dev_remove_alloc(struct bch_fs *c, struct bch_dev *ca, u64 cutoff) { - struct bpos start = POS(ca->dev_idx, 0); + struct bpos start = POS(ca->dev_idx, cutoff); struct bpos end = POS(ca->dev_idx, U64_MAX); + struct bpos bp_start = bucket_pos_to_bp_start(ca, start); + struct bpos bp_end = POS(ca->dev_idx + 1, 0); int ret; /* * We clear the LRU and need_discard btrees first so that we don't race - * with bch2_do_invalidates() and bch2_do_discards_async() + * with bch2_do_invalidates() and bch2_do_discards() */ - ret = bch2_dev_remove_lrus(c, ca) ?: - bch2_dev_remove_need_discard(c, ca) ?: + ret = bch2_dev_remove_lrus(c, ca, cutoff) ?: + bch2_dev_remove_need_discard(c, ca, cutoff) ?: bch2_btree_delete_range(c, BTREE_ID_freespace, start, end, BTREE_TRIGGER_norun) ?: - bch2_btree_delete_range(c, BTREE_ID_backpointers, start, end, - BTREE_TRIGGER_norun) ?: - bch2_btree_delete_range(c, BTREE_ID_bucket_gens, start, end, + bch2_btree_delete_range(c, BTREE_ID_backpointers, bp_start, bp_end, BTREE_TRIGGER_norun) ?: + bch2_dev_remove_bucket_gens(c, ca, cutoff) ?: bch2_btree_delete_range(c, BTREE_ID_alloc, start, end, - BTREE_TRIGGER_norun) ?: - bch2_dev_usage_remove(c, ca); - bch_err_msg_dev(ca, ret, "removing dev alloc info"); + BTREE_TRIGGER_norun); + bch_err_msg_dev(ca, ret, "%s dev alloc info", + cutoff ? "truncating" : "removing"); return ret; } @@ -1711,7 +1760,7 @@ void bch2_dev_allocator_remove(struct bch_fs *c, struct bch_dev *ca) */ bch2_recalc_capacity(c); - bch2_open_buckets_stop(c, ca, false); + bch2_open_buckets_stop(c, ca, false, 0); /* * Wake up threads that were blocked on allocation, so they can notice @@ -1747,7 +1796,7 @@ void bch2_fs_allocator_background_init(struct bch_fs *c) void bch2_fs_capacity_exit(struct bch_fs *c) { - percpu_free_rwsem(&c->capacity.mark_lock); + percpu_free_rwsem(&c->capacity.mark_lock.lock); if (c->capacity.pcpu) { u64 v = percpu_u64_get(&c->capacity.pcpu->online_reserved); WARN(v, "online_reserved not 0 at shutdown: %lli", v); @@ -1760,7 +1809,7 @@ int bch2_fs_capacity_init(struct bch_fs *c) { spin_lock_init(&c->capacity.sectors_available_lock); - try(percpu_init_rwsem(&c->capacity.mark_lock)); + try(percpu_init_rwsem(&c->capacity.mark_lock.lock)); if (!(c->capacity.pcpu = alloc_percpu(struct bch_fs_capacity_pcpu))) return bch_err_throw(c, ENOMEM_fs_other_alloc); diff --git a/fs/alloc/background.h b/fs/alloc/background.h index b60b586f9c..bb454cfac8 100644 --- a/fs/alloc/background.h +++ b/fs/alloc/background.h @@ -297,6 +297,7 @@ void bch2_bucket_gens_to_text(struct printbuf *, struct bch_fs *, struct bkey_s_ }) int bch2_bucket_gens_init(struct bch_fs *); +int bch2_dev_remove_bucket_gens(struct bch_fs *, struct bch_dev *, u64); int bch2_alloc_read(struct bch_fs *); @@ -308,7 +309,7 @@ int bch2_alloc_key_to_dev_counters(struct btree_trans *, struct bch_dev *, const struct bch_alloc_v4 *, unsigned); int bch2_trigger_alloc(struct btree_trans *, struct btree_trigger_op); -int bch2_dev_remove_alloc(struct bch_fs *, struct bch_dev *); +int bch2_dev_remove_alloc(struct bch_fs *, struct bch_dev *, u64); void bch2_recalc_capacity(struct bch_fs *); unsigned long bch2_fs_ra_pages(struct bch_fs *); diff --git a/fs/alloc/backpointers.c b/fs/alloc/backpointers.c index 39dab816d2..50e1c320f5 100644 --- a/fs/alloc/backpointers.c +++ b/fs/alloc/backpointers.c @@ -18,6 +18,7 @@ #include "sb/io.h" +#include "init/damage.h" #include "init/error.h" #include "init/progress.h" #include "init/passes.h" @@ -627,12 +628,23 @@ static int check_bp_dup(struct btree_trans *trans, prt_newline(&buf); bch2_bkey_val_to_text(&buf, c, other_extent); - if (ret_fsck_err(trans, dup_extents_to_reflink, "%s", buf.buf)) + /* + * Both files are damaged - sharing physical space + * means at least one of them reads the other's bytes. + * The pos-ful report records against the first inode; + * record the second explicitly (KEY_TYPE_extent only + * lives in the extents btree, so both attribute): + */ + if (ret_inode_fsck_err(trans, extent.k->p, + dup_extents_to_reflink, "%s", buf.buf)) { + try(bch2_damage_record(trans, other_extent.k->p, + BCH_FSCK_ERR_dup_extents_to_reflink)); try(extents_to_reflink(trans, bp->v.btree_id, bp->v.level, extent, k1_overlap_start, k1_overlap_end, other_bp.v->btree_id, other_bp.v->level, other_extent, k2_overlap_start, k2_overlap_end)); + } return 0; } @@ -1228,7 +1240,8 @@ int bch2_check_bucket_backpointer_mismatch(struct btree_trans *trans, BCH_RECOVERY_PASS_check_extents_to_backpointers, nr < allowed ? RUN_RECOVERY_PASS_ratelimit : 0); - bch2_print_str(c, KERN_ERR, buf.buf); + if (!bch2_ratelimit(c)) + bch2_print_str(c, KERN_ERR, buf.buf); return 0; } diff --git a/fs/alloc/buckets.c b/fs/alloc/buckets.c index c5891014e9..72327e28c2 100644 --- a/fs/alloc/buckets.c +++ b/fs/alloc/buckets.c @@ -90,7 +90,7 @@ __bch2_fs_usage_read_short(struct bch_fs *c) struct bch_fs_usage_short bch2_fs_usage_read_short(struct bch_fs *c) { - guard(percpu_read)(&c->capacity.mark_lock); + guard(percpu_read_noio)(&c->capacity.mark_lock); return __bch2_fs_usage_read_short(c); } @@ -197,8 +197,7 @@ int __bch2_bucket_ref_update(struct btree_trans *trans, struct bch_dev *ca, trans, stale_ptr_with_no_stale_ptrs_feature, "stale cached ptr, but have no_stale_ptrs feature\n%s", (bch2_bkey_val_to_text(&buf, c, k), buf.buf))) { - guard(memalloc_flags)(PF_MEMALLOC_NOFS); - guard(mutex)(&c->sb_lock); + guard(mutex_noio)(&c->sb_lock); c->disk_sb.sb->compat[0] &= ~cpu_to_le64(BIT_ULL(BCH_COMPAT_no_stale_ptrs)); bch2_write_super(c); } @@ -251,7 +250,7 @@ void bch2_trans_account_disk_usage_change(struct btree_trans *trans) { struct bch_fs *c = trans->c; - lockdep_assert_held(&c->capacity.mark_lock); + lockdep_assert_held(&c->capacity.mark_lock.lock); u64 disk_res_sectors = trans->disk_res ? trans->disk_res->sectors : 0; static int warned_disk_usage = 0; @@ -315,6 +314,22 @@ static int __mark_pointer(struct btree_trans *trans, struct bch_dev *ca, return 0; } +static noinline int +trigger_pointer_dev_missing(struct btree_trans *trans, + struct bkey_s_c k, unsigned dev, + bool insert) +{ + struct bch_fs *c = trans->c; + int ret = insert + ? bch_err_throw(c, trigger_pointer) + : 0; + + CLASS(bch_log_msg_ratelimited, msg)(c); + prt_printf(&msg.m, "Error while %s key:\n", insert ? "inserting" : "deleting"); + ret = bch2_dev_missing_bkey_msg(c, k, dev, &msg.m); + return ret; +} + static int bch2_trigger_pointer(struct btree_trans *trans, enum btree_id btree_id, unsigned level, struct bkey_s_c k, struct extent_ptr_decoded p, @@ -343,19 +358,8 @@ static int bch2_trigger_pointer(struct btree_trans *trans, } CLASS(bch2_dev_tryget_noerror, ca)(c, p.ptr.dev); - if (unlikely(!ca)) { - int ret = insert - ? bch_err_throw(c, trigger_pointer) - : 0; - - if (p.ptr.dev != BCH_SB_MEMBER_INVALID) { - CLASS(bch_log_msg_ratelimited, msg)(c); - prt_printf(&msg.m, "Error while %s key:\n", insert ? "inserting" : "deleting"); - ret = bch2_dev_missing_bkey_msg(c, k, p.ptr.dev, &msg.m); - } - - return ret; - } + if (unlikely(!ca)) + return trigger_pointer_dev_missing(trans, k, p.ptr.dev, insert); struct bpos bucket = PTR_BUCKET_POS(ca, &p.ptr); if (!bucket_valid(ca, bucket.offset)) { @@ -373,13 +377,7 @@ static int bch2_trigger_pointer(struct btree_trans *trans, } if (flags & BTREE_TRIGGER_gc) { - CLASS(printbuf, buf)(); struct bucket *g = gc_bucket(ca, bucket.offset); - if (bch2_fs_inconsistent_on(!g, c, "reference to invalid bucket on device %u\n %s", - p.ptr.dev, - (bch2_bkey_val_to_text(&buf, c, k), buf.buf))) - return bch_err_throw(c, trigger_pointer); - struct bch_alloc_v4 old, new; scoped_guard(bucket_lock, g) { @@ -607,6 +605,80 @@ static int __trigger_extent(struct btree_trans *trans, return 0; } +/* in-place update RECONCILE_PHYS if it is the only thing that changed */ +static int bch2_trigger_extent_reconcile_phys_update(struct btree_trans *trans, + enum btree_id btree, + unsigned level, + struct bkey_s_c old, + struct bkey_s new, + bool *handled) +{ + struct bch_fs *c = trans->c; + struct bkey_i_backpointer old_bp[BCH_REPLICAS_MAX * 2]; + struct bkey_i_backpointer new_bp[BCH_REPLICAS_MAX * 2]; + struct bkey_ptrs_c ptrs; + const union bch_extent_entry *entry; + struct extent_ptr_decoded p; + unsigned nr_old = 0, nr_new = 0; + unsigned i; + + *handled = false; + if (level) + return 0; + + ptrs = bch2_bkey_ptrs_c(old); + bkey_for_each_ptr_decode(old.k, ptrs, p, entry) { + BUG_ON(nr_old == ARRAY_SIZE(old_bp)); + bch2_extent_ptr_to_bp(c, btree, level, old, p, entry, &old_bp[nr_old++]); + } + + ptrs = bch2_bkey_ptrs_c(new.s_c); + bkey_for_each_ptr_decode(new.k, ptrs, p, entry) { + BUG_ON(nr_new == ARRAY_SIZE(new_bp)); + bch2_extent_ptr_to_bp(c, btree, level, new.s_c, p, entry, &new_bp[nr_new++]); + } + + if (nr_old != nr_new) + return 0; + + for (i = 0; i < nr_old; i++) { + struct bch_backpointer old_v = old_bp[i].v; + struct bch_backpointer new_v = new_bp[i].v; + + SET_BACKPOINTER_RECONCILE_PHYS(&old_v, 0); + SET_BACKPOINTER_RECONCILE_PHYS(&new_v, 0); + + if (!bpos_eq(old_bp[i].k.p, new_bp[i].k.p) || + memcmp(&old_v, &new_v, sizeof(old_v))) + return 0; + } + + for (i = 0; i < nr_old; i++) { + unsigned old_phys = BACKPOINTER_RECONCILE_PHYS(&old_bp[i].v); + unsigned new_phys = BACKPOINTER_RECONCILE_PHYS(&new_bp[i].v); + + if (!old_phys && !new_phys) + continue; + + if (old_phys) + try(bch2_btree_bit_mod_buffered(trans, + reconcile_work_phys_btree[old_phys], + old_bp[i].k.p, false)); + + if (new_phys) + try(bch2_btree_bit_mod_buffered(trans, + reconcile_work_phys_btree[new_phys], + new_bp[i].k.p, true)); + + try(bch2_trans_update_buffered(trans, + backpointer_btree(&new_bp[i].v), + &new_bp[i].k_i)); + } + + *handled = true; + return 0; +} + int bch2_trigger_extent(struct btree_trans *trans, struct btree_trigger_op op) { struct bkey_ptrs_c new_ptrs = bch2_bkey_ptrs_c(op.new.s_c); @@ -614,7 +686,15 @@ int bch2_trigger_extent(struct btree_trans *trans, struct btree_trigger_op op) unsigned new_ptrs_bytes = (void *) new_ptrs.end - (void *) new_ptrs.start; unsigned old_ptrs_bytes = (void *) old_ptrs.end - (void *) old_ptrs.start; - /* if pointers aren't changing - nothing to do: */ + /* optimization for in-place updates to reconcile_phys to avoid delete-insert churn */ + if (op.level == 0 && + op.new.k->u64s == op.old.k->u64s) { + bool handled; + + try(bch2_trigger_extent_reconcile_phys_update(trans, op.btree, op.level, op.old, op.new, &handled)); + if (handled) + return bch2_trigger_extent_reconcile(trans, op); + } if (new_ptrs_bytes == old_ptrs_bytes && !memcmp(new_ptrs.start, old_ptrs.start, @@ -870,7 +950,7 @@ static int __bch2_trans_mark_dev_sb(struct btree_trans *trans, struct bch_dev *c struct bch_fs *c = trans->c; struct bch_sb_layout layout; - scoped_guard(mutex, &c->sb_lock) + scoped_guard(mutex_noio, &c->sb_lock) layout = ca->disk_sb.sb->layout; u64 bucket = 0; diff --git a/fs/alloc/buckets.h b/fs/alloc/buckets.h index 00feb3ec2a..b8f5594d90 100644 --- a/fs/alloc/buckets.h +++ b/fs/alloc/buckets.h @@ -246,7 +246,8 @@ static inline struct bch_dev_usage_full bch2_dev_usage_full_read(struct bch_dev void bch2_dev_usage_to_text(struct printbuf *, struct bch_dev *, struct bch_dev_usage_full *); -static inline u64 bch2_dev_buckets_reserved(struct bch_dev *ca, enum bch_watermark watermark) +static inline u64 __bch2_dev_buckets_reserved(u64 nbuckets, unsigned nr_btree_reserve, + enum bch_watermark watermark) { s64 reserved = 0; @@ -254,16 +255,16 @@ static inline u64 bch2_dev_buckets_reserved(struct bch_dev *ca, enum bch_waterma case BCH_WATERMARK_NR: BUG(); case BCH_WATERMARK_stripe: - reserved += ca->mi.nbuckets >> 6; + reserved += nbuckets >> 6; fallthrough; case BCH_WATERMARK_normal: - reserved += ca->mi.nbuckets >> 6; + reserved += nbuckets >> 6; fallthrough; case BCH_WATERMARK_copygc: - reserved += ca->nr_btree_reserve; + reserved += nr_btree_reserve; fallthrough; case BCH_WATERMARK_btree: - reserved += ca->nr_btree_reserve; + reserved += nr_btree_reserve; fallthrough; case BCH_WATERMARK_btree_copygc: case BCH_WATERMARK_reclaim: @@ -274,14 +275,29 @@ static inline u64 bch2_dev_buckets_reserved(struct bch_dev *ca, enum bch_waterma return reserved; } +static inline u64 bch2_dev_buckets_reserved(struct bch_dev *ca, enum bch_watermark watermark) +{ + return __bch2_dev_buckets_reserved(ca->mi.nbuckets, ca->nr_btree_reserve, watermark); +} + static inline u64 __dev_buckets_free(struct bch_dev *ca, struct bch_dev_usage usage, enum bch_watermark watermark) { + u64 free = usage.buckets[BCH_DATA_free]; + u64 nbuckets = READ_ONCE(ca->mi.nbuckets); + + /* buckets in shrink tail are not allocatable and thus shouldn't count as free */ + u64 tail_free = atomic64_read(&ca->shrinking_tail_free); + if (unlikely(tail_free)) + free -= min(free, tail_free); + if (unlikely(bch2_dev_is_shrinking(ca))) + nbuckets = bch2_dev_resize_target(ca); + return max_t(s64, 0, - usage.buckets[BCH_DATA_free]- + free - ca->nr_open_buckets - - bch2_dev_buckets_reserved(ca, watermark)); + __bch2_dev_buckets_reserved(nbuckets, ca->nr_btree_reserve, watermark)); } static inline u64 dev_buckets_free(struct bch_dev *ca, diff --git a/fs/alloc/check.c b/fs/alloc/check.c index 8492e313c6..043ba45da5 100644 --- a/fs/alloc/check.c +++ b/fs/alloc/check.c @@ -125,7 +125,7 @@ int bch2_need_discard_or_freespace_err(struct btree_trans *trans, bch2_bkey_val_to_text(&buf, c, alloc_k); - int ret = __bch2_fsck_err(NULL, trans, flags, err_id, + int ret = __bch2_fsck_err(NULL, trans, POS_MIN, flags, err_id, "bucket incorrectly %sset in %s btree\n%s", set ? "" : "un", bch2_btree_id_str(btree), @@ -838,9 +838,7 @@ int bch2_dev_freespace_init(struct bch_fs *c, struct bch_dev *ca, try(lockrestart_do(trans, dev_freespace_init_iter(trans, ca, &iter, end))); } - scoped_guard(memalloc_flags, PF_MEMALLOC_NOFS) { - guard(mutex)(&c->sb_lock); - guard(memalloc_flags)(PF_MEMALLOC_NOFS); + scoped_guard(mutex_noio, &c->sb_lock) { struct bch_member *m = bch2_members_v2_get_mut(c->disk_sb.sb, ca->dev_idx); SET_BCH_MEMBER_FREESPACE_INITIALIZED(m, true); } @@ -872,8 +870,7 @@ int bch2_fs_freespace_init(struct bch_fs *c) } if (doing_init) { - guard(memalloc_flags)(PF_MEMALLOC_NOFS); - guard(mutex)(&c->sb_lock); + guard(mutex_noio)(&c->sb_lock); bch2_write_super(c); bch_verbose(c, "done initializing freespace"); } diff --git a/fs/alloc/check_data.c b/fs/alloc/check_data.c index 01e9b3cc19..3f971b0b19 100644 --- a/fs/alloc/check_data.c +++ b/fs/alloc/check_data.c @@ -389,8 +389,16 @@ static int bch2_no_valid_pointers_repair(struct btree_trans *trans, CLASS(printbuf, buf)(); bch2_bkey_val_to_text(&buf, c, *k); + /* + * Inode-scoped when we can attribute it: an extents btree position + * names an inum, so the error records damage against the file. An + * indirect extent's doesn't - POS_MIN reports without recording: + */ + struct bpos damage_pos = btree == BTREE_ID_extents ? new->k.p : POS_MIN; + if (found_good_cached_pointer) { - ret_fsck_err(trans, extent_ptrs_all_invalid_but_cached, + ret_inode_fsck_err(trans, damage_pos, + extent_ptrs_all_invalid_but_cached, "extent without valid dirty pointers\n%s", buf.buf); struct bch_inode_opts opts; @@ -399,7 +407,8 @@ static int bch2_no_valid_pointers_repair(struct btree_trans *trans, BKEY_EXTENT_U64s_MAX, SET_NEEDS_RECONCILE_opt_change, 0)); } else { - ret_fsck_err(trans, extent_ptrs_all_invalid, + ret_inode_fsck_err(trans, damage_pos, + extent_ptrs_all_invalid, "extent without valid pointers\n%s", buf.buf); bch2_set_bkey_error(c, new, KEY_TYPE_ERROR_no_valid_pointers_repair); } @@ -471,7 +480,7 @@ int bch2_check_fix_ptrs(struct btree_trans *trans, struct btree_iter *iter, BKEY_EXTENT_U64s_MAX, SET_NEEDS_RECONCILE_opt_change, 0)); if (bkey_is_btree_ptr(&new->k)) - trans->extra_disk_res = (u64) bch2_bkey_nr_ptrs_allocated(c, bkey_i_to_s_c(new)) * + trans->extra_disk_res = (u64) bch2_bkey_durability_safe(c, bkey_i_to_s_c(new)).total * btree_sectors(c); if (!level) { diff --git a/fs/alloc/discard.c b/fs/alloc/discard.c index 81b8e24a45..f587192c96 100644 --- a/fs/alloc/discard.c +++ b/fs/alloc/discard.c @@ -12,6 +12,7 @@ #include "btree/update.h" #include "btree/write_buffer.h" +#include "init/damage.h" #include "init/fs.h" #include "journal/journal.h" @@ -453,6 +454,16 @@ static void calculate_discard_sectors_to_release(struct btree_trans *trans) s->r.flush_journal = true; } +static bool bch2_discard_blocked_by_resize(struct bch_fs *c, struct bpos bucket) +{ + guard(rcu)(); + struct bch_dev *ca = bch2_dev_rcu_noerror(c, bucket.inode); + + return ca && + bch2_dev_is_shrinking(ca) && + bucket.offset >= bch2_dev_resize_target(ca); +} + static void bch2_do_discards(struct bch_fs *c) { struct bch_fs_discards *d = &c->discards; @@ -471,6 +482,10 @@ static void bch2_do_discards(struct bch_fs *c) /* * Iterate need_discard btree (sorted by journal_seq). * Stop when we hit a seq beyond rewind_seq_ondisk. + * + * Drop need_discard iterator before we update alloc and + * commit to avoid deadlock against alloc/freespace updates + * when removing the corresponding index entry */ ret = for_each_btree_key(trans, iter, BTREE_ID_need_discard, POS_MIN, 0, k, ({ @@ -482,6 +497,15 @@ static void bch2_do_discards(struct bch_fs *c) c->journal.flushed_seq_ondisk + 1)) break; + /* + * Leave buckets in the shrink tail queued, as the + * alloc update can deadlock with reconcile. + */ + if (bch2_discard_blocked_by_resize(c, bucket)) { + s->pos = iter.pos; + continue; + } + if (!bpos_eq(s->pos, iter.pos)) s->seen += bucket_size; s->pos = iter.pos; @@ -687,8 +711,11 @@ static int invalidate_one_bp(struct btree_trans *trans, bch2_bkey_drop_device_noerror(c, bkey_i_to_s(n), ca->dev_idx); - if (!bch2_bkey_can_read(c, bkey_i_to_s_c(n))) + if (!bch2_bkey_can_read(c, bkey_i_to_s_c(n))) { bch2_set_bkey_error(c, n, KEY_TYPE_ERROR_device_removed); + try(bch2_damage_record_data_loss(trans, bp.v->btree_id, n->k.p, + BCH_FSCK_ERR_data_lost_device_removed)); + } return 0; } diff --git a/fs/alloc/disk_groups.c b/fs/alloc/disk_groups.c index 8b4f19c83e..b544ecf66e 100644 --- a/fs/alloc/disk_groups.c +++ b/fs/alloc/disk_groups.c @@ -1,4 +1,62 @@ // SPDX-License-Identifier: GPL-2.0 + +/* DOC_LATEX(failure-domains) + * A \emph{failure domain} is a set of devices expected to fail together: a + * shared controller, host, or rack. Spreading a filesystem's replicas across + * failure domains is what lets it survive one failing --- losing a whole + * domain then costs at most one replica of any extent. + * + * Each device may be given a failure domain: a free-form string, set with the + * \texttt{failure\_domain} device option at format time, at device add time, + * or at runtime. Two devices are in the same failure domain when their strings + * are equal; a device with no failure domain set is a domain of its own. + * + * This is a flat, intrinsic device property with no relationship to the disk + * label tree used for \hyperref[sec:io-path-options]{targeting}: a device's + * label positions it for target options, its failure domain describes physical + * fault isolation, and the two need not agree --- devices labeled by + * performance class (\texttt{ssd}, \texttt{hdd}) may sit in racks that cut + * across those classes. + * + * \subsubsection{Spreading replicas} + * + * When allocating, candidate devices are sorted by how many replicas of the + * current write already sit in each device's failure domain, so each replica + * goes to the least occupied domain, ties broken by the usual free space round + * robin. The journal spreads its replicas the same way. + * + * For replicated data this is a preference, not a requirement: if every + * remaining domain already holds a replica --- too few domains for the + * replication level, or the empty ones are full --- replicas double up rather + * than failing the allocation. Data sharing a domain with another of its + * replicas is still intact; it just isn't protected against that domain's loss. + * + * \subsubsection{Erasure coding} + * + * For erasure coding, distinct failure domains are a hard requirement rather + * than a preference: a stripe survives losing a domain only if no more than + * \texttt{nr\_redundant} of its blocks are in it, and a stripe that loses too + * many blocks cannot be reconstructed --- landing poorly is not merely + * unprotected, as for replicated data, but unrecoverable. So stripe block + * allocation excludes devices sharing an already-placed block's domain, and + * stripe width is capped at the number of failure domains with allocatable + * devices: if a domain becomes unavailable, new stripes are allocated narrower + * rather than doubling up. + * + * \subsubsection{Checking failure domains} + * + * \texttt{bcachefs fs failure-domains} shows the failure domains and what + * losing each would cost, computed from the replicas accounting: for each + * domain, the data that would be lost if it failed --- too few copies or stripe + * blocks left to reconstruct --- and the data that would survive degraded. + * Nonzero lost data means failure domain separation is being violated. With no + * failure domains configured each device is its own domain, so this becomes the + * per device view. + * + * Existing data is not rewritten when failure domains change: the report shows + * what a future rewrite pass would need to move. + */ + #include "bcachefs.h" #include "alloc/disk_groups.h" @@ -138,7 +196,7 @@ int bch2_sb_disk_groups_to_cpu(struct bch_fs *c) struct bch_disk_groups_cpu *cpu_g, *old_g; unsigned i, g, nr_groups; - lockdep_assert_held(&c->sb_lock); + lockdep_assert_held(&c->sb_lock.lock); groups = bch2_sb_field_get(c->disk_sb.sb, disk_groups); nr_groups = disk_groups_nr(groups); @@ -177,7 +235,7 @@ int bch2_sb_disk_groups_to_cpu(struct bch_fs *c) } old_g = rcu_dereference_protected(c->disk_groups, - lockdep_is_held(&c->sb_lock)); + lockdep_is_held(&c->sb_lock.lock)); rcu_assign_pointer(c->disk_groups, cpu_g); if (old_g) kfree_rcu(old_g, rcu); @@ -212,6 +270,77 @@ const struct bch_devs_mask *bch2_target_to_mask(struct bch_fs *c, unsigned targe } } +/* Interned failure domain id of a device, 0 = unset. Caller holds rcu. */ +static inline u16 dev_failure_domain(struct bch_fs *c, unsigned dev) +{ + struct bch_dev *ca = bch2_dev_rcu_noerror(c, dev); + return ca ? ca->mi.failure_domain : 0; +} + +/* + * Spreading key for a candidate device: the number of already-chosen replicas + * in its failure domain. Sorting candidates by this ascending fills empty + * domains first, then doubles up - the failure-domain preference for + * replicated data. A device with no failure domain (id 0) always keys 0: it + * never shares a domain, so it sorts first and is never excluded. + * + * Called in batches - caller holds the rcu read lock. + */ +u64 bch2_dev_domain_key(struct bch_fs *c, + const struct bch_devs_mask *chosen, unsigned dev) +{ + u16 d = dev_failure_domain(c, dev); + if (!d) + return 0; + + u64 key = 0; + unsigned i; + for_each_set_bit(i, chosen->d, BCH_SB_MEMBERS_MAX) + key += dev_failure_domain(c, i) == d; + + return key; +} + +/* + * Number of distinct failure domains @devs spans: each set domain counted + * once, each device with no domain counted as its own. This caps stripe width + * when failure domains are a hard requirement - a stripe can't have more + * blocks than domains to spread them across. + */ +unsigned bch2_target_nr_domains(struct bch_fs *c, + const struct bch_devs_mask *devs) +{ + unsigned nr = 0; + + guard(rcu)(); + + unsigned i; + for_each_set_bit(i, devs->d, BCH_SB_MEMBERS_MAX) { + u16 d = dev_failure_domain(c, i); + + /* no failure domain - a domain of its own: */ + if (!d) { + nr++; + continue; + } + + /* count each domain at its first device: */ + bool first = true; + unsigned j; + for_each_set_bit(j, devs->d, BCH_SB_MEMBERS_MAX) { + if (j >= i) + break; + if (dev_failure_domain(c, j) == d) { + first = false; + break; + } + } + nr += first; + } + + return nr; +} + bool bch2_dev_in_target_rcu(struct bch_fs *c, unsigned dev, unsigned target) { if (dev == BCH_SB_MEMBER_INVALID) @@ -476,7 +605,7 @@ static int dev_label_resolve(struct bch_fs *c, const char *name) int __bch2_dev_group_set(struct bch_fs *c, struct bch_dev *ca, const char *name) { - lockdep_assert_held(&c->sb_lock); + lockdep_assert_held(&c->sb_lock.lock); int v = dev_label_resolve(c, name); if (v < 0) @@ -495,7 +624,7 @@ int bch2_opt_disk_label_parse(struct bch_fs *c, const char *val, u64 *res, if (!c) return -BCH_ERR_option_needs_open_fs; - scoped_guard(mutex, &c->sb_lock) { + scoped_guard(mutex_noio, &c->sb_lock) { int v = dev_label_resolve(c, val); if (v < 0) return v; @@ -541,7 +670,7 @@ int bch2_opt_target_parse(struct bch_fs *c, const char *val, u64 *res, return 0; } - scoped_guard(mutex, &c->sb_lock) + scoped_guard(mutex_noio, &c->sb_lock) g = bch2_disk_path_find(&c->disk_sb, val); if (g >= 0) { diff --git a/fs/alloc/disk_groups.h b/fs/alloc/disk_groups.h index 93bcd4e38f..02917218c7 100644 --- a/fs/alloc/disk_groups.h +++ b/fs/alloc/disk_groups.h @@ -3,6 +3,7 @@ #define _BCACHEFS_DISK_GROUPS_H #include "disk_groups_types.h" +#include "sb/members.h" extern const struct bch_sb_field_ops bch_sb_field_ops_disk_groups; @@ -57,6 +58,8 @@ static inline struct target target_decode(unsigned target) } const struct bch_devs_mask *bch2_target_to_mask(struct bch_fs *, unsigned); +u64 bch2_dev_domain_key(struct bch_fs *, const struct bch_devs_mask *, unsigned); +unsigned bch2_target_nr_domains(struct bch_fs *, const struct bch_devs_mask *); static inline struct bch_devs_mask target_rw_devs(struct bch_fs *c, enum bch_data_type data_type, @@ -78,6 +81,22 @@ static inline bool bch2_target_accepts_data(struct bch_fs *c, return !bitmap_empty(rw_devs.d, BCH_SB_MEMBERS_MAX); } +static inline bool bch2_target_has_non_shrinking_dev(struct bch_fs *c, + enum bch_data_type data_type, + u16 target) +{ + struct bch_devs_mask devs = target_rw_devs(c, data_type, target); + + guard(rcu)(); + unsigned i; + for_each_set_bit(i, devs.d, BCH_SB_MEMBERS_MAX) { + struct bch_dev *ca = bch2_dev_rcu_noerror(c, i); + if (ca && !bch2_dev_is_shrinking(ca)) + return true; + } + return false; +} + bool bch2_dev_in_target_rcu(struct bch_fs *, unsigned, unsigned); static inline bool bch2_dev_in_target(struct bch_fs *c, unsigned dev, unsigned target) diff --git a/fs/alloc/foreground.c b/fs/alloc/foreground.c index df1a29695b..26f39dccf8 100644 --- a/fs/alloc/foreground.c +++ b/fs/alloc/foreground.c @@ -41,6 +41,7 @@ #include "init/error.h" #include "journal/journal.h" +#include "journal/reclaim.h" #include "sb/counters.h" @@ -278,7 +279,9 @@ static struct open_bucket *__try_alloc_bucket(struct bch_fs *c, if (unlikely(is_superblock_bucket(c, ca, bucket))) return NULL; - if (unlikely(bch2_bucket_nouse(ca, bucket))) { + if (unlikely(bch2_bucket_nouse(ca, bucket) || + (bch2_dev_is_shrinking(ca) && + bucket >= bch2_dev_resize_target(ca)))) { req->counters.skipped_nouse++; return NULL; } @@ -654,7 +657,7 @@ static noinline __cold void bucket_alloc_to_text(struct printbuf *out, if (req->ca) { prt_printf(out, "dev\t%s (%u)\n", req->ca->name, req->ca->dev_idx); prt_printf(out, "avail\t%llu\n", __dev_buckets_free(req->ca, req->usage, req->watermark)); - scoped_guard(percpu_read, &c->capacity.mark_lock) + scoped_guard(percpu_read_noio, &c->capacity.mark_lock) prt_printf(out, "copygc dev wait\t%lli\n", bch2_copygc_dev_wait_amount(req->ca)); } @@ -786,7 +789,7 @@ struct open_bucket *bch2_bucket_alloc_trans(struct btree_trans *trans, c->recovery.pass_done < BCH_RECOVERY_PASS_check_allocations) goto alloc; - scoped_guard(percpu_read, &c->capacity.mark_lock) + scoped_guard(percpu_read_noio, &c->capacity.mark_lock) copygc_can_make_progress = bch2_copygc_can_make_progress(ca); if (copygc_can_make_progress) { req->copygc_can_make_progress = true; @@ -843,6 +846,19 @@ struct open_bucket *bch2_bucket_alloc_trans(struct btree_trans *trans, if (!ret) { ob->data_type = req->data_type; + /* + * We just consumed an open bucket. If the pool is getting low, poke + * the journal watermark: it factors in open-bucket usage and will + * throttle new journal-reserving work before the reclaim path starves + * (see bch2_journal_set_watermark()). freelist_lock has been dropped + * by now, so taking j->lock here doesn't nest the two. + */ + if (unlikely(READ_ONCE(c->allocator.open_buckets_nr_free) < + bch2_open_buckets_journal_reserved())) { + guard(spinlock)(&c->journal.lock); + bch2_journal_set_watermark(&c->journal); + } + event_inc_trace(c, bucket_alloc, buf, bucket_alloc_to_text(&buf, c, req, ob)); } else if (bch2_err_matches(ret, BCH_ERR_open_buckets_empty) || @@ -906,10 +922,20 @@ static void dev_stripe_state_sync(struct dev_stripe_state *stripe, stripe->cached_devs = *devs; } -void bch2_dev_alloc_list(struct bch_fs *c, - struct dev_stripe_state *stripe, - struct bch_devs_mask *devs, - struct dev_alloc_list *ret) +/* + * Devices are ordered by failure domain occupancy first - so replicas + * spread across failure domains - with the free space round robin breaking + * ties: + */ +#define dev_alloc_cmp(l, r) \ + ((domain_keys ? cmp_int(domain_keys[l], domain_keys[r]) : 0) ?:\ + __dev_stripe_cmp(stripe, l, r)) + +static void __dev_alloc_list(struct bch_fs *c, + struct dev_stripe_state *stripe, + struct bch_devs_mask *devs, + const u64 *domain_keys, + struct dev_alloc_list *ret) { dev_stripe_state_sync(stripe, devs); @@ -919,7 +945,60 @@ void bch2_dev_alloc_list(struct bch_fs *c, for_each_set_bit(i, devs->d, BCH_SB_MEMBERS_MAX) ret->data[ret->nr++] = i; - bubble_sort(ret->data, ret->nr, dev_stripe_cmp); + bubble_sort(ret->data, ret->nr, dev_alloc_cmp); +} + +/* + * Refresh req->domain_keys for every device we may allocate from - one rcu + * section per batch. Recomputed whenever devs_chosen changes (each pick + * changes the occupancy the next pick should avoid): + */ +static void bch2_dev_domain_keys_update(struct bch_fs *c, struct alloc_request *req) +{ + unsigned i; + scoped_guard(rcu) + for_each_set_bit(i, req->devs_may_alloc.d, BCH_SB_MEMBERS_MAX) + req->domain_keys[i] = bch2_dev_domain_key(c, &req->devs_chosen, i); + + /* + * For erasure coding failure domains are a hard requirement, not a + * preference: exclude every device sharing a domain with an + * already-chosen block (domain_key > 0) so the allocation fails, or + * narrows, rather than doubling up. + */ + if (req->failure_domains_required) + for_each_set_bit(i, req->devs_may_alloc.d, BCH_SB_MEMBERS_MAX) + if (req->domain_keys[i]) + __clear_bit(i, req->devs_may_alloc.d); +} + +/* + * The journal's device selection: domain keys live in the caller's scratch + * buffer rather than an alloc_request: + */ +void bch2_dev_alloc_list_devs(struct bch_fs *c, + struct dev_stripe_state *stripe, + struct bch_devs_mask *devs, + const struct bch_devs_mask *devs_chosen, + u64 *domain_keys, + struct dev_alloc_list *ret) +{ + unsigned i; + scoped_guard(rcu) + for_each_set_bit(i, devs->d, BCH_SB_MEMBERS_MAX) + domain_keys[i] = bch2_dev_domain_key(c, devs_chosen, i); + + __dev_alloc_list(c, stripe, devs, domain_keys, ret); +} + +void bch2_dev_alloc_list(struct bch_fs *c, + struct dev_stripe_state *stripe, + struct alloc_request *req) +{ + bch2_dev_domain_keys_update(c, req); + + __dev_alloc_list(c, stripe, &req->devs_may_alloc, + req->domain_keys, &req->devs_sorted); } static const u64 stripe_clock_hand_rescale = 1ULL << 62; /* trigger rescale at */ @@ -998,6 +1077,7 @@ static int add_new_bucket(struct bch_fs *c, BUG_ON(req->nr_effective >= req->nr_replicas && durability); __clear_bit(ob->dev, req->devs_may_alloc.d); + __set_bit(ob->dev, req->devs_chosen.d); req->nr_effective += durability; ob_push(c, &req->ptrs, ob); @@ -1018,38 +1098,59 @@ int bch2_bucket_alloc_set_trans(struct btree_trans *trans, { struct bch_fs *c = trans->c; int ret = 0; + bool progress; BUG_ON(req->nr_effective >= req->nr_replicas); - bch2_dev_alloc_list(c, stripe, &req->devs_may_alloc, &req->devs_sorted); + bch2_dev_alloc_list(c, stripe, req); + /* + * Evaluated once, on the full candidate list: this classifies the + * whole allocation for tracing/bailing, and must not flip as the + * list shrinks below. + */ if (req->devs_sorted.nr <= 1) req->will_retry_target_devices = false; - darray_for_each(req->devs_sorted, i) { - req->ca = bch2_dev_tryget_noerror(c, *i); - if (!req->ca) - continue; + do { + progress = false; - req->will_retry_set_devices = - i + 1 < req->devs_sorted.data + req->devs_sorted.nr; + darray_for_each(req->devs_sorted, i) { + req->ca = bch2_dev_tryget_noerror(c, *i); + if (!req->ca) + continue; - struct open_bucket *ob = bch2_bucket_alloc_trans(trans, req); - if (!IS_ERR(ob)) - bch2_dev_stripe_increment_inlined(req->ca, stripe, &req->usage); + req->will_retry_set_devices = + i + 1 < req->devs_sorted.data + req->devs_sorted.nr; - bch2_dev_put(req->ca); - req->ca = NULL; + struct open_bucket *ob = bch2_bucket_alloc_trans(trans, req); + if (!IS_ERR(ob)) + bch2_dev_stripe_increment_inlined(req->ca, stripe, &req->usage); - if (IS_ERR(ob)) { /* don't squash error */ - ret = PTR_ERR(ob); - if (bch2_err_matches(ret, BCH_ERR_transaction_restart) || - bch2_err_matches(ret, BCH_ERR_operation_blocked) || - bch2_err_matches(ret, BCH_ERR_open_buckets_empty)) - return ret; - } else if (add_new_bucket(c, req, ob)) - return 0; - } + bch2_dev_put(req->ca); + req->ca = NULL; + + if (IS_ERR(ob)) { /* don't squash error */ + ret = PTR_ERR(ob); + if (bch2_err_matches(ret, BCH_ERR_transaction_restart) || + bch2_err_matches(ret, BCH_ERR_operation_blocked) || + bch2_err_matches(ret, BCH_ERR_open_buckets_empty)) + return ret; + } else if (add_new_bucket(c, req, ob)) { + return 0; + } else { + progress = true; + break; + } + } + + /* + * Each allocation changes which failure domains the next + * replica should avoid - re-sort and go again: + */ + if (progress) + bch2_dev_alloc_list(c, stripe, req); + } while (progress); return ret ?: alloc_trace_add(req, BCH_SB_MEMBER_INVALID, bch_err_throw(c, insufficient_devices), 0, 0, false); @@ -1073,7 +1174,7 @@ static int bucket_alloc_from_stripe(struct btree_trans *trans, if (!h) return 0; - bch2_dev_alloc_list(c, &req->wp->stripe, &req->devs_may_alloc, &req->devs_sorted); + bch2_dev_alloc_list(c, &req->wp->stripe, req); darray_for_each(req->devs_sorted, i) for (unsigned ec_idx = 0; ec_idx < ec_stripe_new_nr_data(h->s); ec_idx++) { @@ -1166,23 +1267,43 @@ static int bucket_alloc_set_partial(struct bch_fs *c, guard(spinlock)(&a->freelist_lock); - if (!a->open_buckets_partial_nr) - return 0; + /* + * Pick the domain-best usable candidate each round, not the first + * match: on a steady-state filesystem most allocations are satisfied + * here, and first-fit would undo the failure domain spreading + * bch2_bucket_alloc_set_trans() does for fresh buckets. Each pick + * updates devs_chosen (via add_new_bucket), so the keys are + * recomputed per round - same shape as the fresh-bucket re-sort loop. + */ + while (a->open_buckets_partial_nr) { + int best = -1; + u64 best_key = U64_MAX; - for (int i = a->open_buckets_partial_nr - 1; i >= 0; --i) { - struct open_bucket *ob = a->open_buckets + a->open_buckets_partial[i]; + bch2_dev_domain_keys_update(c, req); + + for (int i = a->open_buckets_partial_nr - 1; i >= 0; --i) { + struct open_bucket *ob = a->open_buckets + a->open_buckets_partial[i]; + + if (!want_bucket(c, req, ob)) + continue; - if (want_bucket(c, req, ob)) { struct bch_dev *ca = ob_dev(c, ob); - u64 avail; bch2_dev_usage_read_fast(ca, &req->usage); - avail = __dev_buckets_free(ca, req->usage, req->watermark) + ca->nr_partial_buckets; - if (!avail) + if (!(__dev_buckets_free(ca, req->usage, req->watermark) + + ca->nr_partial_buckets)) continue; - try(partial_bucket_alloc(c, req, i)); + if (req->domain_keys[ob->dev] < best_key) { + best = i; + best_key = req->domain_keys[ob->dev]; + } } + + if (best < 0) + return 0; + + try(partial_bucket_alloc(c, req, best)); } return 0; @@ -1245,20 +1366,21 @@ static int bucket_alloc_cached(struct btree_trans *trans, struct alloc_request * * @ec: if true, we're shutting down erasure coding and killing all ec * open_buckets * otherwise, return true + * @tail_cutoff: if != 0 only drop buckets after the cutoff * Returns: true if we should kill this open_bucket * * We're killing open_buckets because we're shutting down a device, erasure * coding, or the entire filesystem - check if this open_bucket matches: */ static bool should_drop_bucket(struct open_bucket *ob, struct bch_fs *c, - struct bch_dev *ca, bool ec) + struct bch_dev *ca, bool ec, u64 tail_cutoff) { struct bch_fs_allocator *a = &c->allocator; if (ec) { return ob->ec != NULL; } else if (ca) { - bool drop = ob->dev == ca->dev_idx; + bool drop = dev_and_region_matches(ob, ca, tail_cutoff); if (!drop && ob->ec) { guard(mutex)(&ob->ec->lock); @@ -1269,8 +1391,12 @@ static bool should_drop_bucket(struct open_bucket *ob, struct bch_fs *c, continue; struct open_bucket *ob2 = a->open_buckets + ob->ec->blocks[i]; - drop |= ob2->dev == ca->dev_idx; + drop |= dev_and_region_matches(ob2, ca, tail_cutoff); } + + if (!drop && ob->ec->have_old_stripe) + drop = stripe_dev_and_region_matches(c, ca, + &ob->ec->old_stripe.key.v, tail_cutoff); } return drop; @@ -1280,7 +1406,7 @@ static bool should_drop_bucket(struct open_bucket *ob, struct bch_fs *c, } static void bch2_writepoint_stop(struct bch_fs *c, struct bch_dev *ca, - bool ec, struct write_point *wp) + bool ec, struct write_point *wp, u64 tail_cutoff) { struct open_buckets ptrs = { .nr = 0 }; struct open_bucket *ob; @@ -1288,26 +1414,27 @@ static void bch2_writepoint_stop(struct bch_fs *c, struct bch_dev *ca, guard(mutex)(&wp->lock); open_bucket_for_each(c, &wp->ptrs, ob, i) - if (should_drop_bucket(ob, c, ca, ec)) + if (should_drop_bucket(ob, c, ca, ec, tail_cutoff)) bch2_open_bucket_put(c, ob); else ob_push(c, &ptrs, ob); wp->ptrs = ptrs; } +/* stop open buckets on @ca, if tail_cutoff isn't zero, only after the cutoff */ void bch2_open_buckets_stop(struct bch_fs *c, struct bch_dev *ca, - bool ec) + bool ec, u64 tail_cutoff) { struct bch_fs_allocator *a = &c->allocator; unsigned i; - /* Next, close write points that point to this device... */ + /* Next, close write points that point to this device or the to-be-shrunk region... */ for (i = 0; i < ARRAY_SIZE(a->write_points); i++) - bch2_writepoint_stop(c, ca, ec, &a->write_points[i]); + bch2_writepoint_stop(c, ca, ec, &a->write_points[i], tail_cutoff); - bch2_writepoint_stop(c, ca, ec, &c->copygc.write_point); - bch2_writepoint_stop(c, ca, ec, &a->reconcile_write_point); - bch2_writepoint_stop(c, ca, ec, &a->btree_write_point); + bch2_writepoint_stop(c, ca, ec, &c->copygc.write_point, tail_cutoff); + bch2_writepoint_stop(c, ca, ec, &a->reconcile_write_point, tail_cutoff); + bch2_writepoint_stop(c, ca, ec, &a->btree_write_point, tail_cutoff); scoped_guard(mutex, &c->btree.reserve_cache.lock) while (c->btree.reserve_cache.nr) { @@ -1323,7 +1450,7 @@ void bch2_open_buckets_stop(struct bch_fs *c, struct bch_dev *ca, struct open_bucket *ob = a->open_buckets + a->open_buckets_partial[i]; - if (should_drop_bucket(ob, c, ca, ec)) { + if (should_drop_bucket(ob, c, ca, ec, tail_cutoff)) { --a->open_buckets_partial_nr; swap(a->open_buckets_partial[i], a->open_buckets_partial[a->open_buckets_partial_nr]); @@ -1341,7 +1468,7 @@ void bch2_open_buckets_stop(struct bch_fs *c, struct bch_dev *ca, } } - bch2_ec_stop_dev(c, ca); + bch2_ec_stop_dev_cutoff(c, ca, tail_cutoff); } static inline struct hlist_head *writepoint_hash(struct bch_fs_allocator *a, @@ -1548,12 +1675,21 @@ int bch2_alloc_sectors_req(struct btree_trans *trans, cached_devs.d, BCH_SB_MEMBERS_MAX); } - /* Don't allocate from devices we already have pointers to: */ - darray_for_each(*req->devs_have, i) + /* + * Don't allocate from devices we already have pointers to - + * and spread away from their failure domains: + */ + memset(&req->devs_chosen, 0, sizeof(req->devs_chosen)); + + darray_for_each(*req->devs_have, i) { __clear_bit(*i, req->devs_may_alloc.d); + __set_bit(*i, req->devs_chosen.d); + } - open_bucket_for_each(c, &req->ptrs, ob, i) + open_bucket_for_each(c, &req->ptrs, ob, i) { __clear_bit(ob->dev, req->devs_may_alloc.d); + __set_bit(ob->dev, req->devs_chosen.d); + } ret = bucket_alloc_set_writepoint(c, req) ?: bucket_alloc_set_partial(c, req) ?: @@ -2166,7 +2302,7 @@ static bool alloc_wait_advanced(struct bch_fs *c, struct alloc_request *req) if (unlikely(req->trace_alloc_failed)) return true; - guard(percpu_read)(&c->capacity.mark_lock); + guard(percpu_read_noio)(&c->capacity.mark_lock); guard(rcu)(); bool found = false; diff --git a/fs/alloc/foreground.h b/fs/alloc/foreground.h index 41d60ffde1..59bf9a35cf 100644 --- a/fs/alloc/foreground.h +++ b/fs/alloc/foreground.h @@ -53,6 +53,8 @@ struct alloc_request { bool will_retry_set_devices:1; bool copygc_can_make_progress:1; bool trace_alloc_failed:1; + /* failure domains are a hard requirement, not a preference (erasure coding): */ + bool failure_domains_required:1; enum bch_watermark watermark; enum bch_write_flags flags; enum bch_data_type data_type; @@ -64,8 +66,16 @@ struct alloc_request { unsigned nr_effective; /* sum of @ptrs durability */ struct bch_devs_mask devs_may_alloc; + /* + * Devices already holding a replica of what we're allocating for - + * devs_have plus buckets allocated so far - for spreading replicas + * across failure domains, see bch2_dev_domain_key(): + */ + struct bch_devs_mask devs_chosen; + /* bch2_bucket_alloc_set_trans(): */ struct dev_alloc_list devs_sorted; + u64 domain_keys[BCH_SB_MEMBERS_MAX]; struct bch_dev_usage usage; /* bch2_bucket_alloc_trans(): */ @@ -140,10 +150,15 @@ static inline int alloc_trace_add(struct alloc_request *req, return err; } +void bch2_dev_alloc_list_devs(struct bch_fs *, + struct dev_stripe_state *, + struct bch_devs_mask *, + const struct bch_devs_mask *, + u64 *, + struct dev_alloc_list *); void bch2_dev_alloc_list(struct bch_fs *, struct dev_stripe_state *, - struct bch_devs_mask *, - struct dev_alloc_list *); + struct alloc_request *); void bch2_dev_stripe_increment(struct bch_dev *, struct dev_stripe_state *); static inline struct bch_dev *ob_dev(struct bch_fs *c, struct open_bucket *ob) @@ -168,6 +183,18 @@ static inline unsigned bch2_open_buckets_reserved(enum bch_watermark watermark) } } +/* + * Free open buckets we keep in reserve for the reclaim path (write-buffer flush + * -> journal -> writeback), which both frees open buckets and needs them to make + * progress. When free drops below this, bch2_journal_set_watermark() raises the + * journal watermark so new journal-reserving work throttles at reservation time, + * before it can drain the pool below the reclaim reserve (BCH_WATERMARK_reclaim). + */ +static inline unsigned bch2_open_buckets_journal_reserved(void) +{ + return OPEN_BUCKETS_COUNT / 4; +} + struct open_bucket *bch2_bucket_alloc_trans(struct btree_trans *, struct alloc_request *); /* @@ -264,6 +291,31 @@ static inline void bch2_alloc_sectors_done_inlined(struct bch_fs *c, struct writ bch2_open_buckets_put(c, &ptrs); } +/* + * Give up on the open buckets in @wp that have less than @sectors free, so the + * next allocation gets fresh ones instead of handing the same too-small write + * point straight back. + * + * For writes that can't be split and so need that much contiguous room: a btree + * node, or a compressed extent we can't decompress. The tail of each retired + * bucket is fragmentation, which copygc reclaims. + * + * Only ask for something a fresh bucket can hold, or the caller loops. + */ +static inline void bch2_alloc_sectors_retire_short(struct bch_fs *c, + struct write_point *wp, + unsigned sectors) +{ + struct open_bucket *ob; + unsigned i; + + open_bucket_for_each(c, &wp->ptrs, ob, i) + if (ob->sectors_free < sectors) + ob->sectors_free = 0; + + bch2_alloc_sectors_done_inlined(c, wp); +} + static inline void bch2_open_bucket_get(struct bch_fs *c, struct write_point *wp, struct open_buckets *ptrs) @@ -329,6 +381,25 @@ enum bch_write_flags; int bch2_bucket_alloc_set_trans(struct btree_trans *, struct alloc_request *, struct dev_stripe_state *); +/* Returns whether the @open_buckets device matches @ca and whether the @open_bucket falls behind the cutoff */ +static inline bool dev_and_region_matches(struct open_bucket *ob, struct bch_dev *ca, u64 tail_cutoff) { + return ob->dev == ca->dev_idx && ob->bucket >= tail_cutoff; +} + +/* Whether any block of @v references @ca's region at/after @tail_cutoff */ +static inline bool stripe_dev_and_region_matches(struct bch_fs *c, struct bch_dev *ca, + struct bch_stripe *v, u64 tail_cutoff) +{ + guard(rcu)(); + for (unsigned i = 0; i < v->nr_blocks; i++) { + struct bch_dev *oca = bch2_dev_rcu_noerror(c, v->ptrs[i].dev); + if (oca && oca->dev_idx == ca->dev_idx && + PTR_BUCKET_NR(oca, &v->ptrs[i]) >= tail_cutoff) + return true; + } + return false; +} + int bch2_alloc_sectors_req(struct btree_trans *, struct alloc_request *, struct write_point_specifier, struct write_point **); @@ -368,12 +439,14 @@ static inline struct alloc_request *alloc_request_get(struct btree_trans *trans, req->will_retry_target_devices = false; req->will_retry_set_devices = false; req->copygc_can_make_progress = false; + req->failure_domains_required = false; req->trace_alloc_failed = false; req->target_frac = 0; req->devs_sorted.nr = 0; - /* bch2_alloc_sectors_req() overwrites this; bch2_bucket_alloc_trans() - * callers (e.g. journal resize) don't, so zero it here for them: */ + /* bch2_alloc_sectors_req() overwrites these; bch2_bucket_alloc_trans() + * callers (e.g. journal resize) don't, so zero them here for them: */ memset(&req->devs_may_alloc, 0, sizeof(req->devs_may_alloc)); + memset(&req->devs_chosen, 0, sizeof(req->devs_chosen)); darray_init(&req->trace); return req; } @@ -449,7 +522,7 @@ void bch2_alloc_sectors_append_ptrs(struct bch_fs *, struct write_point *, struct bkey_i *, unsigned, bool); void bch2_alloc_sectors_done(struct bch_fs *, struct write_point *); -void bch2_open_buckets_stop(struct bch_fs *c, struct bch_dev *, bool); +void bch2_open_buckets_stop(struct bch_fs *c, struct bch_dev *, bool, u64 tail_cutoff); static inline struct write_point_specifier writepoint_hashed(unsigned long v) { diff --git a/fs/alloc/lru.c b/fs/alloc/lru.c index 08bf0977af..c9eca0c3cb 100644 --- a/fs/alloc/lru.c +++ b/fs/alloc/lru.c @@ -2,6 +2,7 @@ #include "bcachefs.h" +#include "alloc/backpointers.h" #include "alloc/background.h" #include "alloc/lru.h" @@ -118,7 +119,8 @@ static struct bbpos lru_pos_to_bp(struct bkey_s_c lru_k) } } -int bch2_dev_remove_lrus(struct bch_fs *c, struct bch_dev *ca) + +int bch2_dev_remove_lrus(struct bch_fs *c, struct bch_dev *ca, u64 cutoff) { CLASS(btree_trans, trans)(c); int ret = bch2_btree_write_buffer_flush_sync(trans) ?: @@ -126,7 +128,7 @@ int bch2_dev_remove_lrus(struct bch_fs *c, struct bch_dev *ca) BTREE_ID_lru, POS_MIN, BTREE_ITER_prefetch, k, ({ struct bbpos bp = lru_pos_to_bp(k); - bp.btree == BTREE_ID_alloc && bp.pos.inode == ca->dev_idx + bp.btree == BTREE_ID_alloc && bp.pos.inode == ca->dev_idx && bp.pos.offset >= cutoff ? (bch2_btree_delete_at(trans, &iter, 0) ?: bch2_trans_commit(trans, NULL, NULL, 0)) : 0; diff --git a/fs/alloc/lru.h b/fs/alloc/lru.h index e3074fde3d..7f19b43914 100644 --- a/fs/alloc/lru.h +++ b/fs/alloc/lru.h @@ -81,7 +81,7 @@ static inline int bch2_lru_change(struct btree_trans *trans, : 0; } -int bch2_dev_remove_lrus(struct bch_fs *, struct bch_dev *); +int bch2_dev_remove_lrus(struct bch_fs *, struct bch_dev *, u64); struct wb_maybe_flush; int bch2_lru_check_set(struct btree_trans *, u16, u64, u64, struct bkey_s_c, diff --git a/fs/alloc/replicas.c b/fs/alloc/replicas.c index 7ef0e15744..92bba087cb 100644 --- a/fs/alloc/replicas.c +++ b/fs/alloc/replicas.c @@ -294,7 +294,7 @@ bool bch2_replicas_marked(struct bch_fs *c, c->sb.version_incompat >= bcachefs_metadata_version_no_sb_user_data_replicas) return true; - guard(percpu_read)(&c->capacity.mark_lock); + guard(percpu_read_noio)(&c->capacity.mark_lock); return bch2_replicas_marked_locked(c, search); } @@ -337,11 +337,10 @@ static int bch2_mark_replicas_slowpath(struct bch_fs *c, { verify_replicas_entry(new_entry); - guard(memalloc_flags)(PF_MEMALLOC_NOFS); - guard(mutex)(&c->sb_lock); + guard(mutex_noio)(&c->sb_lock); bool write_sb = false; - scoped_guard(percpu_write, &c->capacity.mark_lock) { + scoped_guard(percpu_write_noio, &c->capacity.mark_lock) { if (!replicas_entry_search(&c->replicas, new_entry)) { CLASS(bch_replicas_cpu, new_r)(); @@ -385,8 +384,8 @@ static void __replicas_entry_kill(struct bch_fs *c, struct bch_replicas_entry_cp void bch2_replicas_entry_kill(struct bch_fs *c, struct bch_replicas_entry_v1 *kill) { - lockdep_assert_held(&c->capacity.mark_lock); - lockdep_assert_held(&c->sb_lock); + lockdep_assert_held(&c->capacity.mark_lock.lock); + lockdep_assert_held(&c->sb_lock.lock); struct bch_replicas_entry_cpu *e = replicas_entry_search(&c->replicas, kill); @@ -423,9 +422,7 @@ void bch2_replicas_entry_put_many(struct bch_fs *c, struct bch_replicas_entry_v1 BUG_ON(r->data_type != BCH_DATA_journal); verify_replicas_entry(r); - guard(memalloc_flags)(PF_MEMALLOC_NOFS); - - scoped_guard(percpu_read, &c->capacity.mark_lock) { + scoped_guard(percpu_read_noio, &c->capacity.mark_lock) { int ret = __replicas_entry_put(c, r, nr); if (!ret) return; @@ -437,8 +434,8 @@ void bch2_replicas_entry_put_many(struct bch_fs *c, struct bch_replicas_entry_v1 } } - guard(mutex)(&c->sb_lock); - scoped_guard(percpu_write, &c->capacity.mark_lock) { + guard(mutex_noio)(&c->sb_lock); + scoped_guard(percpu_write_noio, &c->capacity.mark_lock) { struct bch_replicas_entry_cpu *e = replicas_entry_search(&c->replicas, r); if (e && !atomic_read(&e->ref)) __replicas_entry_kill(c, e); @@ -449,7 +446,7 @@ void bch2_replicas_entry_put_many(struct bch_fs *c, struct bch_replicas_entry_v1 static inline bool bch2_replicas_entry_get_inmem(struct bch_fs *c, struct bch_replicas_entry_v1 *r) { - guard(percpu_read)(&c->capacity.mark_lock); + guard(percpu_read_noio)(&c->capacity.mark_lock); struct bch_replicas_entry_cpu *e = replicas_entry_search(&c->replicas, r); if (e) atomic_inc(&e->ref); @@ -473,9 +470,8 @@ int bch2_replicas_gc_reffed(struct bch_fs *c) { bool write_sb = false; - guard(memalloc_flags)(PF_MEMALLOC_NOFS); - guard(mutex)(&c->sb_lock); - scoped_guard(percpu_write, &c->capacity.mark_lock) { + guard(mutex_noio)(&c->sb_lock); + scoped_guard(percpu_write_noio, &c->capacity.mark_lock) { unsigned dst = 0; for (unsigned i = 0; i < c->replicas.nr; i++) { struct bch_replicas_entry_cpu *e = @@ -507,9 +503,8 @@ int bch2_replicas_gc_accounted(struct bch_fs *c) bch2_accounting_mem_gc(c); - guard(memalloc_flags)(PF_MEMALLOC_NOFS); - guard(mutex)(&c->sb_lock); - scoped_guard(percpu_write, &c->capacity.mark_lock) { + guard(mutex_noio)(&c->sb_lock); + scoped_guard(percpu_write_noio, &c->capacity.mark_lock) { struct bch_replicas_cpu new = { .entry_size = c->replicas.entry_size, .entries = kvcalloc(c->replicas.nr, c->replicas.entry_size, GFP_KERNEL), @@ -669,7 +664,7 @@ int bch2_sb_replicas_to_cpu_replicas(struct bch_fs *c) bch2_cpu_replicas_sort(&new_r); - guard(percpu_write)(&c->capacity.mark_lock); + guard(percpu_write_noio)(&c->capacity.mark_lock); swap(c->replicas, new_r); return 0; @@ -911,7 +906,7 @@ bool bch2_can_read_replicas_with_devs(struct bch_fs *c, struct bch_devs_mask *de bool bch2_can_read_fs_with_devs(struct bch_fs *c, struct bch_devs_mask *devs, unsigned flags, struct printbuf *err) { - guard(percpu_read)(&c->capacity.mark_lock); + guard(percpu_read_noio)(&c->capacity.mark_lock); for_each_cpu_replicas_entry(&c->replicas, i) { if (replicas_entry_obsolete(c, i->e.data_type)) continue; @@ -1044,8 +1039,7 @@ unsigned bch2_sb_dev_has_data(struct bch_sb *sb, unsigned dev) unsigned bch2_dev_has_data(struct bch_fs *c, struct bch_dev *ca) { - guard(memalloc_flags)(PF_MEMALLOC_NOFS); - guard(mutex)(&c->sb_lock); + guard(mutex_noio)(&c->sb_lock); return bch2_sb_dev_has_data(c->disk_sb.sb, ca->dev_idx); } diff --git a/fs/alloc/types.h b/fs/alloc/types.h index 8cc2afd7cf..0b8cb8321b 100644 --- a/fs/alloc/types.h +++ b/fs/alloc/types.h @@ -10,6 +10,7 @@ #include "alloc/buckets_types.h" #include "util/clock_types.h" #include "util/fifo.h" +#include "util/locking.h" #define BCH_WATERMARKS() \ x(stripe) \ @@ -158,7 +159,7 @@ struct bch_fs_capacity { struct bch_fs_capacity_pcpu __percpu *pcpu; - struct percpu_rw_semaphore mark_lock; + struct percpu_rwsem_noio mark_lock; }; struct bch_fs_allocator { diff --git a/fs/bcachefs.h b/fs/bcachefs.h index 56bf95352d..cd1d6e1ce8 100644 --- a/fs/bcachefs.h +++ b/fs/bcachefs.h @@ -33,10 +33,13 @@ #define race_fault(...) dynamic_fault("bcachefs:race") +struct task_struct; + #include #include #include #include +#include #include #include #include @@ -72,6 +75,7 @@ #include "util/enumerated_ref_types.h" #include "util/fast_list.h" #include "util/fifo.h" +#include "util/locking.h" #include "util/seqmutex.h" #include "util/time_stats.h" #include "util/thread_with_file_types.h" @@ -375,6 +379,9 @@ BCH_DEBUG_PARAMS_ALL() x(blocked_journal_low_on_pin, \ "Blocked: journal pins (dirty btree nodes, " \ "key cache entries) not flushed fast enough") \ + x(blocked_journal_low_on_open_buckets, \ + "Blocked: open buckets running low, throttling new " \ + "journal work so reclaim can free them") \ x(blocked_journal_max_in_flight, \ "Blocked: too many journal writes in flight") \ x(blocked_journal_max_open, \ @@ -535,7 +542,6 @@ struct bch_dev { struct bch_sb *sb_read_scratch; int sb_write_error; dev_t dev; - atomic_t flush_seq; struct bch_devs_mask self; @@ -573,7 +579,14 @@ struct bch_dev { unsigned nr_partial_buckets; unsigned nr_btree_reserve; + atomic64_t shrinking_tail_free; + struct work_struct invalidate_work; + spinlock_t resize_lock; + u64 resize_seq; + wait_queue_head_t resize_wait; + int resize_status; + struct task_struct *resize_thread; struct work_struct discard_fast_work; darray_u64 discard_fast; @@ -621,9 +634,9 @@ struct bch_dev { x(write_disable_complete) \ x(clean_shutdown) \ x(in_recovery) \ + x(running_recovery_passes) \ x(in_fsck) \ x(initial_gc_unfixed) \ - x(need_delete_dead_snapshots) \ x(error) \ x(topology_error) \ x(errors_fixed) \ @@ -670,7 +683,6 @@ struct journal_seq_blacklist_table { x(discard_fast) \ x(check_discard_freespace_key) \ x(invalidate) \ - x(delete_dead_snapshots) \ x(gc_gens) \ x(presplit_shard_boundaries) \ x(snapshot_delete_pagecache) \ @@ -744,7 +756,7 @@ struct bch_fs { struct bch_sb_cpu sb; struct bch_sb_handle disk_sb; struct closure sb_write; - struct mutex sb_lock; + struct mutex_noio sb_lock; unsigned long incompat_versions_requested[BITS_TO_LONGS(BCH_VERSION_MINOR(bcachefs_metadata_version_current))]; struct unicode_map *cf_encoding; @@ -864,6 +876,22 @@ int __bch2_err_throw(struct bch_fs *, int); #define bch_err_throw(_c, _err) __bch2_err_throw(_c, -BCH_ERR_##_err) +/* + * Have we been told to stop? For long-running kthread work, so the check can be + * try()d where it belongs instead of open coded: + * + * try(bch2_kthread_cancelled(c)); + * + * Returns 0 outside a kthread, so paths shared with user context are unaffected. + */ +static inline int bch2_kthread_cancelled(struct bch_fs *c) +{ + if ((current->flags & PF_KTHREAD) && kthread_should_stop()) + return bch_err_throw(c, kthread_cancelled); + + return 0; +} + /* Read-only refs: */ static inline bool bch2_ro_ref_tryget(struct bch_fs *c) @@ -1016,8 +1044,11 @@ struct bch_log_msg { static inline void bch2_log_msg_exit(struct bch_log_msg *msg) { - if (!msg->m.suppress) + if (!msg->m.suppress) { + /* elastic tabstops: align any raw \t/\r columns */ + bch2_printbuf_tabstop_align(&msg->m); bch2_print_str_loglevel(msg->c, msg->loglevel, msg->m.buf); + } printbuf_exit(&msg->m); } diff --git a/fs/bcachefs_format.h b/fs/bcachefs_format.h index ec4a1bcdc8..5685cdb184 100644 --- a/fs/bcachefs_format.h +++ b/fs/bcachefs_format.h @@ -473,7 +473,11 @@ enum bch_bkey_type_flags { "Whiteout specific to the extents btree, blocking " \ "visibility of ancestor snapshot extent versions") \ x(logged_op_stripe_update, 37, BKEY_TYPE_strict_btree_checks, \ - "Logged stripe creation/update operation for crash recovery") + "Logged stripe creation/update operation for crash recovery") \ + x(damage, 38, BKEY_TYPE_strict_btree_checks, \ + "Errors that damaged an inode, recorded in the same " \ + "transaction as the repair that did the damage: a sorted " \ + "list of bch_sb_error_id") enum bch_bkey_type { #define x(name, nr, ...) KEY_TYPE_##name = nr, @@ -500,11 +504,38 @@ struct bch_error { u8 pad[7]; }; -#define KEY_TYPE_ERRORS() \ - x(unknown, 0) \ - x(device_removed, 1) \ - x(double_allocation, 2) \ - x(no_valid_pointers_repair, 3) +/* + * Why an extent became a KEY_TYPE_error key, recorded in the tombstone so a + * later reader can tell what killed the data without the damage btree, which + * fsck can prune. + * + * The decompress_ reasons are the data_decompress_err_ list in + * sb/errors_format.h, name for name: the superblock counts how often a + * decompression failed each way, and the key says which of those killed this + * extent. bch2_decompress_key_type_error() maps between them off the same + * table that produces the sb error ids, so the two can't drift - adding a + * decompress error id without a reason here breaks the build. + */ +#define KEY_TYPE_ERRORS() \ + x(unknown, 0) \ + x(device_removed, 1) \ + x(double_allocation, 2) \ + x(no_valid_pointers_repair, 3) \ + x(decompress_exceeded_max_encoded_extent, 4) \ + x(decompress_lz4_old, 5) \ + x(decompress_lz4, 6) \ + x(decompress_gzip, 7) \ + x(decompress_gzip_size_mismatch, 8) \ + x(decompress_zstd_src_len_bad, 9) \ + x(decompress_zstd_size_mismatch, 10) \ + x(decompress_zstd_corruption_detected, 11) \ + x(decompress_zstd_checksum_wrong, 12) \ + x(decompress_zstd_prefix_unknown, 13) \ + x(decompress_zstd_src_size_wrong, 14) \ + x(decompress_zstd_dst_size_too_small, 15) \ + x(decompress_zstd_memory_allocation, 16) \ + x(decompress_zstd_unknown, 17) \ + x(decompress_unknown, 18) enum bch_key_type_errors { #define x(n, t) KEY_TYPE_ERROR_##n = t, @@ -613,7 +644,10 @@ struct bch_sb_field { "Tracks which recovery passes have been run " \ "successfully") \ x(extent_type_u64s, 16, \ - "Per-extent-type size limits") + "Per-extent-type size limits") \ + x(errors_v2, 17, \ + "Persistent error log, v2: adds the time of " \ + "first occurrence to each entry") enum btree_id_flags { BTREE_IS_extents = BIT(0), @@ -759,6 +793,11 @@ enum btree_id_flags { BTREE_IS_write_buffer, \ BIT_ULL(KEY_TYPE_backpointer), \ "Stripe backpointers") \ + x(damage, 28, \ + BTREE_IS_snapshots, \ + BIT_ULL(KEY_TYPE_whiteout)| \ + BIT_ULL(KEY_TYPE_damage), \ + "Inodes damaged by errors and repairs") \ enum btree_id { #define x(name, nr, ...) BTREE_ID_##name = nr, @@ -781,6 +820,7 @@ enum btree_id { #include "fs/logged_ops_format.h" #include "fs/quota_format.h" #include "fs/xattr_format.h" +#include "init/damage_format.h" #include "init/passes_format.h" #include "journal/seq_blacklist_format.h" #include "sb/counters_format.h" @@ -1271,6 +1311,12 @@ LE64_BITMASK(BCH_SB_EXTENT_BP_SHIFT, struct bch_sb, flags[6], 40, 48); LE64_BITMASK(BCH_SB_SCRUB_JOURNAL, struct bch_sb, flags[6], 48, 50); LE64_BITMASK(BCH_SB_EC_MAX_DATA_BLOCKS, struct bch_sb, flags[6], 50, 58); LE64_BITMASK(BCH_SB_MOVE_WRITES_FUA, struct bch_sb, flags[6], 58, 59); +/* + * Set by `bcachefs dump --sanitize` when it scrubs dirent names: the names + * (and therefore their str_hash positions) are meaningless, so fsck must skip + * the dirent hash-consistency check rather than "repair" the artifacts. + */ +LE64_BITMASK(BCH_SB_DIRENTS_SANITIZED, struct bch_sb, flags[6], 59, 60); #define BCH_SB_EXTENT_BP_SHIFT_DEFAULT 10 diff --git a/fs/bcachefs_ioctl.h b/fs/bcachefs_ioctl.h index 95ff38325a..fc2384f8ad 100644 --- a/fs/bcachefs_ioctl.h +++ b/fs/bcachefs_ioctl.h @@ -74,6 +74,7 @@ #define BCH_IOCTL_SUBVOLUME_TO_PATH _IOWR(0xbc, 32, struct bch_ioctl_subvol_to_path) #define BCH_IOCTL_SNAPSHOT_TREE _IOWR(0xbc, 33, struct bch_ioctl_snapshot_tree_query) #define BCH_IOCTL_QUERY_BTREE_KEYS _IOWR(0xbc, 34, struct bch_ioctl_query_btree_keys) +#define BCH_IOCTL_SNAPSHOT_TREE_v2 _IOWR(0xbc, 35, struct bch_ioctl_snapshot_tree_query_v2) /* ioctl below act on a particular file, not the filesystem as a whole: */ @@ -82,6 +83,88 @@ #define BCHFS_IOC_PROPAGATE_REFLINK_P_OPTS _IO(0xbc, 66) #define BCHFS_IOC_PREAD_RAW _IOWR(0xbc, 67, struct bch_ioctl_pread_raw) #define BCHFS_IOC_UNPOISON _IOW(0xbc, 68, struct bch_ioctl_unpoison) +#define BCHFS_IOC_GET_DAMAGE _IOWR(0xbc, 70, struct bch_ioctl_get_damage) +#define BCHFS_IOC_READDIR_FLAGS _IOWR(0xbc, 69, struct bch_ioctl_readdir_flags) + +/* + * BCHFS_IOC_CLEAR_DAMAGE: clear the file's damage record, in the calling + * subvolume's view - snapshots keep theirs (on disk the clear is a + * whiteout when an older version still needs the record). Requires + * ownership or CAP_FOWNER, like chattr. + */ +#define BCHFS_IOC_CLEAR_DAMAGE _IO(0xbc, 71) + +/* + * BCHFS_IOC_GET_DAMAGE: the accumulated damage record for this file - the + * union of damage recorded against its inode in the file's snapshot and + * all ancestor snapshot versions, since damage done to an ancestor version + * is damage to the file seen here. + * + * @nr_entries - in: capacity of @entries; out: number present. A result + * exceeding the capacity reports the true count - retry + * with more room. + * @entries - sorted by error id; the same records the errors + * superblock section keeps (bch_sb_field_error_entry_v2): + * the id, a saturating occurrence count and the times of + * first and last occurrence, unpacked with + * BCH_SB_ERROR_ENTRY_V2_ID/NR/FIRST/LAST + */ +struct bch_ioctl_get_damage { + __u32 nr_entries; + __u32 pad; + bch_sb_field_error_entry_v2 entries[]; +}; + +/* + * BCHFS_IOC_READDIR_FLAGS: readdir with filters, on the directory the + * ioctl is called on. + * + * recursive: entries from the whole subtree, names become paths relative + * to the fd's directory. The filters pick the iteration: damaged + * walks the damage btree (cost proportional to recorded damage, not tree + * size), subvolumes_only walks the subvolume tree, an unfiltered + * recursive listing is an honest tree walk. + * + * damaged: only entries whose inode has recorded damage, in its + * snapshot version or an ancestor. + * + * Permissions are those of readdir: the caller learns nothing beyond the + * directory they opened. + * + * @flags - BCH_READDIR_* + * @pos - opaque resume cursor: zero to start; copied back out + * past the last entry returned. Iterate until @used == 0. + * @buf_size, + * @buf - userspace buffer, filled with struct + * bch_ioctl_readdir_entry records + * @used - out: bytes of @buf filled + */ +#define BCH_READDIR_recursive (1U << 0) +#define BCH_READDIR_damaged (1U << 2) +#define BCH_READDIR_subvolumes_only (1U << 1) + +struct bch_ioctl_readdir_flags { + __u64 pos[2]; + __u64 buf; + __u32 buf_size; + __u32 flags; + __u32 used; + __u32 pad; +}; + +/* + * One entry: the NUL-terminated name - a relative path, under recursive - + * follows the fixed header; entries are padded to 8-byte alignment. + * Deliberately knows nothing about the filters that selected it: damage + * details come from BCHFS_IOC_GET_DAMAGE on the file itself. + */ +struct bch_ioctl_readdir_entry { + __u64 inum; + __u8 d_type; + __u8 pad; + __u16 name_len; /* including the NUL */ + __u8 name[]; +}; struct bch_ioctl_err_msg { __u64 msg_ptr; @@ -580,6 +663,13 @@ struct bch_ioctl_subvol_to_path { * * Returns -ERANGE if nr < total (nr and total are still written back) */ +/* + * FROZEN. The ioctl number encodes sizeof(the header), not of the array + * element, so growing this struct is invisible to the ioctl machinery and + * silently overruns the buffer of any userspace built against the older + * layout. It happened once (nr_keys/key_bytes, reverted); don't do it again - + * add fields to bch_ioctl_snapshot_node_v2, which is size-negotiated. + */ struct bch_ioctl_snapshot_node { __u32 id; /* snapshot ID */ __u32 parent; /* parent snapshot ID, 0 for root */ @@ -589,8 +679,6 @@ struct bch_ioctl_snapshot_node { __u32 pad[2]; /* BCH_DISK_ACCOUNTING_snapshot, summed over the snapshot btrees: */ __u64 sectors; /* external (on-disk data) sectors */ - __u64 nr_keys; - __u64 key_bytes; }; struct bch_ioctl_snapshot_tree_query { @@ -603,6 +691,37 @@ struct bch_ioctl_snapshot_tree_query { struct bch_ioctl_snapshot_node nodes[]; }; +/* + * v2: same query, but the header states the array element size, so either + * side can grow bch_ioctl_snapshot_node_v2 without breaking the other. + * The kernel writes min(node_size, its own sizeof) bytes per entry and + * strides by node_size, so a shorter node from either direction truncates + * instead of overrunning. New fields go on the end, and both sides read + * node_size to know what's present. + */ +struct bch_ioctl_snapshot_node_v2 { + __u32 id; /* snapshot ID */ + __u32 parent; /* parent snapshot ID, 0 for root */ + __u32 children[2]; + __u32 subvol; /* subvolume ID, 0 for interior */ + __u32 flags; + __u32 pad[2]; + /* BCH_DISK_ACCOUNTING_snapshot, summed over the snapshot btrees: */ + __u64 sectors; /* external (on-disk data) sectors */ + __u64 nr_keys; + __u64 key_bytes; +}; + +struct bch_ioctl_snapshot_tree_query_v2 { + __u32 tree_id; /* in: 0 = infer from fd's subvol */ + __u32 master_subvol; /* out */ + __u32 root_snapshot; /* out */ + __u32 nr; /* in: capacity; out: returned */ + __u32 total; /* out: total nodes */ + __u32 node_size; /* in: caller's sizeof; out: ours */ + struct bch_ioctl_snapshot_node_v2 nodes[]; +}; + /* * BCHFS_IOC_PREAD_RAW: O_DIRECT read with extended error reporting. * @@ -691,6 +810,7 @@ struct bch_ioctl_unpoison { #define BCH_IOCTL_QUERY_BTREE_KEYS_slots (1U << 0) #define BCH_IOCTL_QUERY_BTREE_KEYS_prev (1U << 1) #define BCH_IOCTL_QUERY_BTREE_KEYS_all_snapshots (1U << 2) +#define BCH_IOCTL_QUERY_BTREE_KEYS_nofilter_whiteouts (1U << 3) struct bch_ioctl_query_btree_keys { __u32 btree; diff --git a/fs/btree/bkey.rs b/fs/btree/bkey.rs index 675fe744b2..dc6924e80f 100644 --- a/fs/btree/bkey.rs +++ b/fs/btree/bkey.rs @@ -279,10 +279,26 @@ impl<'a> BkeySC<'a> { } } + /// Key only - type, pos, size - without rendering the value. + #[cfg(feature = "std")] + pub fn to_text_key(&self) -> BkeySCKeyToText<'a> { + BkeySCKeyToText { + k: BkeySC { k: self.k, v: self.v, iter: PhantomData }, + } + } + pub fn v(&self) -> BkeyValSC<'a> { unsafe { BkeyValSC::from_raw(self.k, self.v) } } + /// The value as raw bytes: its full u64s extent past the key header. + pub fn val_bytes(&self) -> &'a [u8] { + let u64s = self.k.u64s as usize - core::mem::size_of::() / 8; + unsafe { + core::slice::from_raw_parts(self.v as *const c::bch_val as *const u8, u64s * 8) + } + } + pub fn pos(&self) -> c::bpos { self.k.p } @@ -396,6 +412,18 @@ impl fmt::Display for BkeySCToText<'_, '_> { } } +#[cfg(feature = "std")] +pub struct BkeySCKeyToText<'a> { + k: BkeySC<'a>, +} + +#[cfg(feature = "std")] +impl fmt::Display for BkeySCKeyToText<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + unsafe { printbuf_to_formatter(f, |buf| c::bch2_bkey_to_text(buf, self.k.k)) } + } +} + #[inline(always)] pub fn bpos_lt(l: Bpos, r: Bpos) -> bool { if l.inode != r.inode { diff --git a/fs/btree/bkey_methods.c b/fs/btree/bkey_methods.c index e227d8adb9..c66adfddcc 100644 --- a/fs/btree/bkey_methods.c +++ b/fs/btree/bkey_methods.c @@ -21,6 +21,7 @@ #include "fs/quota.h" #include "fs/xattr.h" +#include "init/damage.h" #include "init/error.h" #include "sb/io.h" diff --git a/fs/btree/bkey_methods.h b/fs/btree/bkey_methods.h index a2bfe2ffab..eb22127e88 100644 --- a/fs/btree/bkey_methods.h +++ b/fs/btree/bkey_methods.h @@ -83,7 +83,14 @@ static inline int bch2_key_trigger(struct btree_trans *trans, ? ops->trigger(trans, op) : 0; - return ret ?: bch2_trigger_snapshot_nr_keys(trans, op); + /* + * Gate matches the trans-commit dispatch: only snapshotted btrees get + * per-snapshot key counts. Snapshot-field btrees (reconcile_pending) + * carry a snapshot in their bpos but must not be counted. + */ + return ret ?: (btree_type_has_snapshots(op.btree) + ? bch2_trigger_snapshot_nr_keys(trans, op) + : 0); } static inline int bch2_key_trigger_old(struct btree_trans *trans, diff --git a/fs/btree/bkey_types.h b/fs/btree/bkey_types.h index 812cb619cf..669be124e8 100644 --- a/fs/btree/bkey_types.h +++ b/fs/btree/bkey_types.h @@ -116,6 +116,18 @@ static inline void set_bkey_val_bytes(struct bkey *k, unsigned bytes) #define bkey_val_end(_k) ((void *) (((u64 *) (_k).v) + bkey_val_u64s((_k).k))) +/* + * Was this key written with @field? + * + * Values grow: a key written by an older version stops short of the fields + * added since, and the length is the only record of which ones it had. Reading + * such a field off a raw bkey reads the next key in the bset, and reading it + * off a padded copy reads 0 - which is indistinguishable from a stored 0. + */ +#define bkey_has_field(_k, _type, _field) \ + (bkey_val_bytes(_k) >= offsetof(struct bch_##_type, _field) + \ + sizeof(((struct bch_##_type *) NULL)->_field)) + #define bkey_deleted(_k) ((_k)->type == KEY_TYPE_deleted) #define bkey_whiteout(_k) \ diff --git a/fs/btree/cache.c b/fs/btree/cache.c index 90b344e5ff..bed92798e7 100644 --- a/fs/btree/cache.c +++ b/fs/btree/cache.c @@ -313,7 +313,7 @@ void bch2_node_pin(struct bch_fs *c, struct btree *b) { struct bch_fs_btree_cache *bc = &c->btree.cache; - guard(mutex)(&bc->lock); + guard(mutex_noio)(&bc->lock); if (!btree_node_is_root(c, b) && !btree_node_pinned(b)) { set_btree_node_pinned(b); @@ -339,7 +339,7 @@ void bch2_btree_cache_unpin(struct bch_fs *c) struct bch_fs_btree_cache *bc = &c->btree.cache; struct btree *b, *n; - guard(mutex)(&bc->lock); + guard(mutex_noio)(&bc->lock); bc->pinned_nodes_mask[0] = 0; bc->pinned_nodes_mask[1] = 0; @@ -378,7 +378,7 @@ int bch2_btree_node_transition_state_locked(struct bch_fs_btree_cache *bc, struc bool pinned = btree_node_pinned(b); int ret = 0; - lockdep_assert_held(&bc->lock); + lockdep_assert_held(&bc->lock.lock); /* * Write lock required for transitions that touch the data buffer or * hash table; CLEAN↔DIRTY swap only moves the node between live[] @@ -395,8 +395,21 @@ int bch2_btree_node_transition_state_locked(struct bch_fs_btree_cache *bc, struc * The dirty bit is what makes the cache_state DIRTY, so a FREEABLE * node with the bit set is an inconsistent state — and consumers that * need to scrub dirty nodes can rely on walking only live[].dirty. + * Warn with the node dumped — the flags identify which path leaked + * the dirty bit (write_blocked/never_write/noevict/need_write) — then + * clear it and carry on: the state bookkeeping below handles the + * DIRTY exit either way. */ - EBUG_ON(!btree_node_state_hashed(new) && btree_node_dirty(b)); + if (WARN_ONCE(!btree_node_state_hashed(new) && btree_node_dirty(b), + "bcachefs: dirty node in unhashed state transition")) { + struct bch_fs *c = container_of(bc, struct bch_fs, btree.cache); + CLASS(bch_log_msg, msg)(c); + prt_printf(&msg.m, "dirty node in unhashed state transition %u -> %u\n", + old, new); + prt_printf(&msg.m, "btree=%u level=%u cache_state=%u flags=0x%lx hash_val=0x%llx\n", + b->c.btree_id, b->c.level, b->cache_state, b->flags, b->hash_val); + clear_btree_node_dirty(b); + } if (old == new) return 0; @@ -510,7 +523,7 @@ void bch2_btree_node_set_dirty(struct bch_fs *c, struct btree *b) { struct bch_fs_btree_cache *bc = &c->btree.cache; - guard(mutex)(&bc->lock); + guard(mutex_noio)(&bc->lock); if (test_and_set_bit(BTREE_NODE_dirty, &b->flags)) return; if (btree_node_state_hashed(b->cache_state)) @@ -532,7 +545,7 @@ void bch2_btree_node_write_done_clean(struct bch_fs *c, struct btree *b) { struct bch_fs_btree_cache *bc = &c->btree.cache; - guard(mutex)(&bc->lock); + guard(mutex_noio)(&bc->lock); if (btree_node_state_hashed(b->cache_state)) bch2_btree_node_transition_state_locked(bc, b, btree_node_live_state(b)); } @@ -540,7 +553,7 @@ void bch2_btree_node_write_done_clean(struct bch_fs *c, struct btree *b) int bch2_btree_node_transition_state(struct bch_fs_btree_cache *bc, struct btree *b, enum btree_node_cache_state target) { - guard(mutex)(&bc->lock); + guard(mutex_noio)(&bc->lock); return bch2_btree_node_transition_state_locked(bc, b, target); } @@ -586,7 +599,7 @@ static int __btree_node_reclaim_checks(struct bch_fs *c, struct btree *b, { struct bch_fs_btree_cache *bc = &c->btree.cache; - lockdep_assert_held(&bc->lock); + lockdep_assert_held(&bc->lock.lock); if (btree_node_permanent(b)) return btree_node_noreclaim(c, flags, BCH_BTREE_CACHE_NOT_FREED_permanent); @@ -625,7 +638,7 @@ static int btree_node_reclaim(struct bch_fs *c, struct btree *b, struct bch_fs_btree_cache *bc = &c->btree.cache; int ret = 0; - lockdep_assert_held(&bc->lock); + lockdep_assert_held(&bc->lock.lock); while (true) { try(__btree_node_reclaim_checks(c, b, flags)); @@ -674,8 +687,7 @@ static unsigned long bch2_btree_cache_scan(struct shrinker *shrink, return SHRINK_STOP; u64 start_time = local_clock(); - guard(mutex)(&bc->lock); - guard(memalloc_flags)(PF_MEMALLOC_NOFS); + guard(mutex_noio)(&bc->lock); /* * It's _really_ critical that we don't free too many btree nodes - we @@ -840,7 +852,7 @@ static struct btree *bch2_btree_node_grab(struct bch_fs *c, struct list_head *he enum btree_node_reclaim_flags flags) { struct bch_fs_btree_cache *bc = &c->btree.cache; - guard(mutex)(&bc->lock); + guard(mutex_noio)(&bc->lock); struct btree *b; list_for_each_entry(b, head, list) if (pcpu_read_locks == (b->c.lock.readers != NULL) && @@ -1532,7 +1544,7 @@ void bch2_btree_node_evict(struct btree_trans *trans, const struct bkey_i *k) void bch2_fs_btree_cache_init_early(struct bch_fs_btree_cache *bc) { mutex_init(&bc->root_lock); - mutex_init(&bc->lock); + mutex_noio_init(&bc->lock); for (unsigned i = 0; i < ARRAY_SIZE(bc->live); i++) { bc->live[i].idx = i; INIT_LIST_HEAD(&bc->live[i].clean); @@ -1647,6 +1659,21 @@ static void btree_cache_exit_drain_node(struct bch_fs *c, btree_cache_exit_locked_dump(c, b, "write held"); BUG(); } + + /* + * Dirty nodes can survive to exit on a dead journal: the going-RO + * path's bch2_btree_cancel_all_writes() only catches nodes dirty at + * that instant, and the window between going-RO and unmount can + * redirty a node (btree node reads wanting a rewrite, interior + * update teardown). With the journal dead they can never be written; + * cancel here too. Dirty at exit with a live journal is a bug, but + * we're freeing everything regardless — warn, don't die. + */ + if (btree_node_dirty(b)) { + WARN_ON_ONCE(!bch2_journal_error(&c->journal)); + clear_btree_node_dirty(b); + } + bch2_btree_node_transition_state_locked(bc, b, BTREE_NODE_CACHE_FREED); six_unlock_write(&b->c.lock); six_unlock_intent(&b->c.lock); @@ -1672,9 +1699,7 @@ void bch2_fs_btree_cache_exit(struct bch_fs *c) drain_workqueue(c->btree.write_complete_wq); /* vfree() can allocate memory: */ - scoped_guard(memalloc_flags, PF_MEMALLOC_NOFS) { - guard(mutex)(&bc->lock); - + scoped_guard(mutex_noio, &bc->lock) { for (unsigned i = 0; i < ARRAY_SIZE(bc->live); i++) { struct list_head *heads[] = { &bc->live[i].dirty, diff --git a/fs/btree/cache.h b/fs/btree/cache.h index 0294e388ea..e295830459 100644 --- a/fs/btree/cache.h +++ b/fs/btree/cache.h @@ -288,7 +288,7 @@ static inline void btree_node_buf_swap_account(struct bch_fs *c, void *old, void (int) is_vmalloc_addr(old); if (vmalloc_delta) { - guard(mutex)(&c->btree.cache.lock); + guard(mutex_noio)(&c->btree.cache.lock); c->btree.cache.nr_vmalloc += vmalloc_delta; } } diff --git a/fs/btree/check.c b/fs/btree/check.c index 3796f1bc46..53786974e8 100644 --- a/fs/btree/check.c +++ b/fs/btree/check.c @@ -188,6 +188,24 @@ static int set_node_max(struct bch_fs *c, struct btree *b, struct bpos new_max) return 0; } +/* + * Commit the fsck "repaired" log entry queued by mustfix_fsck_err(). + * + * Topology repair runs before we go rw and applies its fixes through journal + * keys (not transactional updates), so nothing else here commits - but the log + * is a transaction update, and the next bch2_trans_begin() would silently drop + * it. Commit it here, at the check, *before* the mutation: a commit can return + * a transaction restart (fault injection, journal, ...), and doing it first + * means the restart re-runs only the check - which re-queues the log - never + * the non-transactional mutation, which must run exactly once. + */ +static int commit_topology_repair_log(struct btree_trans *trans) +{ + return bch2_trans_has_updates(trans) + ? bch2_trans_commit(trans, NULL, NULL, BCH_TRANS_COMMIT_no_enospc) + : 0; +} + static int btree_check_node_boundaries(struct btree_trans *trans, struct btree *b, struct btree *prev, struct btree *cur) { @@ -234,6 +252,7 @@ static int btree_check_node_boundaries(struct btree_trans *trans, struct btree * if (mustfix_fsck_err(trans, btree_node_topology_gap_between_nodes, "gap between btree nodes%s", buf.buf)) { + try(commit_topology_repair_log(trans)); if (nodes_found) return bch_err_throw(c, topology_repair_did_fill_from_scan); else @@ -243,22 +262,30 @@ static int btree_check_node_boundaries(struct btree_trans *trans, struct btree * if (prev && BTREE_NODE_SEQ(cur->data) > BTREE_NODE_SEQ(prev->data)) { /* cur overwrites prev */ if (bpos_ge(prev->data->min_key, cur->data->min_key)) { /* fully? */ if (mustfix_fsck_err(trans, btree_node_topology_overwritten_by_next_node, - "btree node overwritten by next node%s", buf.buf)) + "btree node overwritten by next node%s", buf.buf)) { + try(commit_topology_repair_log(trans)); return bch_err_throw(c, topology_repair_drop_prev_node); + } } else { if (mustfix_fsck_err(trans, btree_node_topology_bad_max_key, - "btree node with incorrect max_key%s", buf.buf)) + "btree node with incorrect max_key%s", buf.buf)) { + try(commit_topology_repair_log(trans)); return set_node_max(c, prev, bpos_predecessor(cur->data->min_key)); + } } } else { if (bpos_ge(expected_start, cur->data->max_key)) { /* fully? */ if (mustfix_fsck_err(trans, btree_node_topology_overwritten_by_prev_node, - "btree node overwritten by prev node%s", buf.buf)) + "btree node overwritten by prev node%s", buf.buf)) { + try(commit_topology_repair_log(trans)); return bch_err_throw(c, topology_repair_drop_this_node); + } } else { if (mustfix_fsck_err(trans, btree_node_topology_bad_min_key, - "btree node with incorrect min_key%s", buf.buf)) + "btree node with incorrect min_key%s", buf.buf)) { + try(commit_topology_repair_log(trans)); return set_node_min(c, cur, expected_start); + } } } } @@ -317,6 +344,7 @@ static int btree_repair_node_end(struct btree_trans *trans, struct btree *b, str if (mustfix_fsck_err(trans, btree_node_topology_bad_max_key, "btree node with incorrect max_key%s", buf.buf)) { + try(commit_topology_repair_log(trans)); if (nodes_found) return bch_err_throw(c, topology_repair_did_fill_from_scan); @@ -587,7 +615,13 @@ static int bch2_topology_check_root(struct btree_trans *trans, enum btree_id btr } } - return 0; + /* + * Commit any fsck_err log entry queued above before returning: this + * runs pre-RW (so the commit is queued for journal replay), and the + * caller's per-btree loop starts each iteration with a bch2_trans_begin + * that would otherwise discard it. + */ + return bch2_trans_commit(trans, NULL, NULL, BCH_TRANS_COMMIT_no_enospc); } static void ratelimit_reset(struct ratelimit_state *rs) @@ -1134,9 +1168,7 @@ int bch2_check_allocations(struct bch_fs *c) bch2_gc_stripes_done(c) ?: bch2_gc_reflink_done(c); out: - scoped_guard(percpu_write, &c->capacity.mark_lock) { - guard(memalloc_flags)(PF_MEMALLOC_NOFS); - + scoped_guard(percpu_write_noio, &c->capacity.mark_lock) { /* Indicates that gc is no longer in progress: */ __gc_pos_set(c, gc_phase(GC_PHASE_not_running)); bch2_gc_free(c); @@ -1260,8 +1292,7 @@ int bch2_gc_gens(struct bch_fs *c) event_inc_trace(c, gc_gens_end, buf); if (!(c->sb.compat & BIT_ULL(BCH_COMPAT_no_stale_ptrs))) { - guard(memalloc_flags)(PF_MEMALLOC_NOFS); - guard(mutex)(&c->sb_lock); + guard(mutex_noio)(&c->sb_lock); c->disk_sb.sb->compat[0] |= cpu_to_le64(BIT_ULL(BCH_COMPAT_no_stale_ptrs)); bch2_write_super(c); } diff --git a/fs/btree/commit.c b/fs/btree/commit.c index 0f7d08132e..601f2728a9 100644 --- a/fs/btree/commit.c +++ b/fs/btree/commit.c @@ -260,11 +260,24 @@ static int __btree_node_flush(struct journal *j, struct journal_entry_pin *pin, unsigned long old, new; unsigned idx = w - b->writes; + /* + * The journal pin doesn't pin the node: another thread can write the + * node and drop the pin while we run, and reclaim can then reuse the + * node's memory. Snapshot the identity to arm the reuse check: gone + * already (unhashed nodes can't be dirty), or going while we'd sleep + * on the lock (aborting the attempt), means the pinned write is done + * and there's nothing to flush. + */ + u64 hash_val = READ_ONCE(b->hash_val); + if (!hash_val) + return 0; + CLASS(btree_trans, trans)(c); - return lockrestart_do(trans, ({ + int ret = lockrestart_do(trans, ({ btree_path_idx_t path_idx; - int ret = bch2_btree_node_lock_with_path(trans, &b->c, SIX_LOCK_read, &path_idx); - if (!ret) { + int _ret = bch2_btree_node_lock_with_path(trans, &b->c, SIX_LOCK_read, + hash_val, &path_idx); + if (!_ret) { old = READ_ONCE(b->flags); do { new = old; @@ -282,8 +295,10 @@ static int __btree_node_flush(struct journal *j, struct journal_entry_pin *pin, __bch2_btree_node_write(trans, b, BTREE_WRITE_only_if_need); bch2_btree_node_unlock_with_path(trans, path_idx, b->c.level); } - ret; + _ret; })); + + return bch2_err_matches(ret, BCH_ERR_no_btree_node_reused) ? 0 : ret; } int bch2_btree_node_flush0(struct journal *j, struct journal_entry_pin *pin, u64 seq) @@ -909,13 +924,19 @@ do_bch2_trans_commit_to_journal_replay(struct btree_trans *trans, int ret = 0; retry: memset(&trans->fs_usage_delta, 0, sizeof(trans->fs_usage_delta)); - percpu_down_read(&c->capacity.mark_lock); + /* + * Raw lock of the inner rwsem, not the percpu_read_noio guard: + * transaction commit runs with the trans locked, so PF_MEMALLOC_NOIO is + * already held, and this read section is released mid-function on the + * revert paths below, which a guard's scope can't express. + */ + percpu_down_read(&c->capacity.mark_lock.lock); for (accounting = btree_trans_subbuf_base(trans, &trans->accounting); accounting != btree_trans_subbuf_top(trans, &trans->accounting); accounting = bkey_next(accounting)) { ret = likely(!(flags & BCH_TRANS_COMMIT_skip_accounting_apply)) - ? bch2_accounting_mem_mod_locked(trans, bkey_i_to_s_c_accounting(accounting), - BCH_ACCOUNTING_normal, false) + ? bch2_accounting_mem_add(trans, bkey_i_to_s_c_accounting(accounting), + BCH_ACCOUNTING_normal, false) : 0; if (ret) goto revert_fs_usage; @@ -923,7 +944,7 @@ do_bch2_trans_commit_to_journal_replay(struct btree_trans *trans, /* Only fatal errors are possible later, so no need to revert this */ bch2_trans_account_disk_usage_change(trans); - percpu_up_read(&c->capacity.mark_lock); + percpu_up_read(&c->capacity.mark_lock.lock); trans_for_each_update(trans, i) { ret = bch2_journal_key_insert(c, i->btree_id, i->level, i->k); @@ -962,18 +983,22 @@ do_bch2_trans_commit_to_journal_replay(struct btree_trans *trans, goto fatal_err; } - event_inc_trace(c, transaction_commit, buf, prt_str(&buf, trans->fn)); + event_inc_trace(c, transaction_commit, buf, ({ + prt_printf(&buf, "%s\nseq %llu\n", trans->fn, trans->journal_res.seq); + bch2_trans_updates_to_text(&buf, trans); + })); return 0; fatal_err: bch2_fs_fatal_error(c, "fatal error in transaction commit: %s", bch2_err_str(ret)); - percpu_down_read(&c->capacity.mark_lock); + /* Raw re-take for the revert below; still the trans-locked commit path (NOIO held). */ + percpu_down_read(&c->capacity.mark_lock.lock); revert_fs_usage: for (struct bkey_i *i = btree_trans_subbuf_base(trans, &trans->accounting); i != accounting; i = bkey_next(i)) bch2_accounting_trans_commit_revert(trans, bkey_i_to_accounting(i), flags); - percpu_up_read(&c->capacity.mark_lock); + percpu_up_read(&c->capacity.mark_lock.lock); if (bch2_err_matches(ret, BCH_ERR_btree_insert_need_mark_replicas)) { ret = drop_locks_do(trans, bch2_accounting_update_sb(trans)); @@ -1046,7 +1071,10 @@ static int trans_commit_merge(struct btree_trans *trans, noinline __cold static void transaction_commit_trace(struct btree_trans *trans) { - __event_trace(trans->c, transaction_commit, buf, prt_str(&buf, trans->fn)); + __event_trace(trans->c, transaction_commit, buf, ({ + prt_printf(&buf, "%s\nseq %llu\n", trans->fn, trans->journal_res.seq); + bch2_trans_updates_to_text(&buf, trans); + })); } static inline bool update_is_noop(struct btree_insert_entry *i, enum bch_trans_commit_flags flags) @@ -1138,7 +1166,7 @@ bch2_trans_commit_write_locked(struct btree_trans *trans, h = h->next; } - scoped_guard(percpu_read, &c->capacity.mark_lock) { + scoped_guard(percpu_read_noio, &c->capacity.mark_lock) { for (struct bkey_i *accounting = btree_trans_subbuf_base(trans, &trans->accounting); accounting != btree_trans_subbuf_top(trans, &trans->accounting); accounting = bkey_next(accounting)) { @@ -1194,6 +1222,8 @@ bch2_trans_commit_write_locked(struct btree_trans *trans, } #endif + event_inc_trace_fn(c, transaction_commit, transaction_commit_trace(trans)); + if (likely(!(flags & BCH_TRANS_COMMIT_no_journal_res))) { struct journal *j = &c->journal; struct jset_entry *start = journal_res_entry(j, &trans->journal_res), *entry = start; @@ -1464,14 +1494,18 @@ int __bch2_trans_commit(struct btree_trans *trans, enum bch_trans_commit_flags f goto err; trans->commit_count++; - event_inc_trace_fn(c, transaction_commit, transaction_commit_trace(trans)); out: if (likely(!(flags & BCH_TRANS_COMMIT_no_check_rw))) enumerated_ref_put(&c->writes, BCH_WRITE_REF_trans); if (!ret) bch2_trans_downgrade(trans); - if (lazy) + /* + * Lazy commits signal success via transaction_restart_commit; a real + * error must not be masked into a restart, or the caller's restart + * loop retries a failing commit forever: + */ + if (lazy && !ret) ret = bch_err_throw(trans->c, transaction_restart_commit); out_reset: bch2_trans_reset_updates(trans); diff --git a/fs/btree/interior.c b/fs/btree/interior.c index 70dc359d35..a956906a3f 100644 --- a/fs/btree/interior.c +++ b/fs/btree/interior.c @@ -183,6 +183,14 @@ static const char * const bch2_btree_update_modes[] = { NULL }; +static unsigned btree_alloc_target(struct bch_fs *c, unsigned target) +{ + target = target ?: c->opts.metadata_target ?: c->opts.foreground_target; + return target && bch2_target_has_non_shrinking_dev(c, BCH_DATA_btree, target) + ? target + : 0; +} + static __cold void bch2_btree_update_to_text(struct printbuf *, struct btree_update *); static int bch2_btree_insert_node(struct btree_update *, struct btree_trans *, @@ -471,14 +479,7 @@ static struct btree *__bch2_btree_node_alloc(struct btree_trans *trans, goto err; if (wp->sectors_free < btree_sectors(c)) { - struct open_bucket *ob; - unsigned i; - - open_bucket_for_each(c, &wp->ptrs, ob, i) - if (ob->sectors_free < btree_sectors(c)) - ob->sectors_free = 0; - - bch2_alloc_sectors_done(c, wp); + bch2_alloc_sectors_retire_short(c, wp, btree_sectors(c)); goto retry; } @@ -783,8 +784,7 @@ static void btree_update_new_nodes_mark_sb(struct btree_update *as) { struct bch_fs *c = as->c; - guard(memalloc_flags)(PF_MEMALLOC_NOFS); - guard(mutex)(&c->sb_lock); + guard(mutex_noio)(&c->sb_lock); bool write_sb = false; darray_for_each(as->new_nodes, i) bch2_dev_btree_bitmap_mark_locked(c, bkey_i_to_s_c(&i->key), &write_sb); @@ -793,7 +793,7 @@ static void btree_update_new_nodes_mark_sb(struct btree_update *as) bch2_write_super(c); } -static void bkey_strip_reconcile(const struct bch_fs *c, struct bkey_s k) +static void bkey_strip_reconcile(struct bch_fs *c, struct bkey_s k) { if (bkey_deleted(k.k)) return; @@ -815,7 +815,7 @@ static void bkey_strip_reconcile(const struct bch_fs *c, struct bkey_s k) bch2_bkey_drop_ptrs_noerror(k, p, entry, p.ptr.dev == BCH_SB_MEMBER_INVALID); - BUG_ON(!bch2_bkey_nr_dirty_ptrs(c, k.s_c)); + BUG_ON(!bch2_bkey_durability_safe(c, k.s_c).nr_ptrs); } static bool bkey_has_reconcile(const struct bch_fs *c, struct bkey_s_c k) @@ -968,10 +968,29 @@ static void btree_update_nodes_written(struct btree_update *as) darray_for_each(as->old_nodes, i) { bool seq_matches = false; + /* + * i->b is a stale pointer: this update deleted the node, so + * btree_node_reclaim may have reused its memory — e.g. as + * another update's prealloc node, whose owner holds it + * intent+write while possibly blocked on the allocator. The + * open buckets the allocator is waiting on are released by + * this workqueue (bch2_open_bucket_put below), so sleeping on + * the node here closes the loop and deadlocks. Arm the + * identity check with the old key's hash: if we'd sleep on a + * node that's no longer ours, the lock attempt aborts. + * + * An abort means no wait is owed. Sustained write locks on an + * unhashed node come only from reclaim (which requires + * write_in_flight clear before grabbing) or the write + * completion path (which runs after the bio finished) — either + * way the IO this wait guards against is already done. + */ ret = lockrestart_do(trans, ({ btree_path_idx_t path_idx; int _ret = bch2_btree_node_lock_with_path(trans, &i->b->c, - SIX_LOCK_read, &path_idx); + SIX_LOCK_read, + btree_ptr_hash_val(&i->key), + &path_idx); if (!_ret) { seq_matches = btree_node_seq_matches(i->b, i->seq); bch2_btree_node_unlock_with_path(trans, path_idx, @@ -1064,8 +1083,17 @@ static void btree_update_nodes_written(struct btree_update *as) */ lockrestart_do(trans, ({ btree_path_idx_t path_idx; + /* + * Unarmed take: this block owns clearing b's + * write_blocked (the list_del below), which is what + * makes b unreclaimable - so the reuse race can't + * reach it, and skipping on a spurious abort would + * leak write_blocked and leave b unwritable forever. + * The reparent race is handled by the as->b recheck + * under interior_updates.lock. + */ int _ret = bch2_btree_node_lock_with_path(trans, &b->c, - SIX_LOCK_intent, &path_idx); + SIX_LOCK_intent, 0, &path_idx); if (!_ret) { struct btree_path *path = trans->paths + path_idx; @@ -1133,8 +1161,15 @@ static void btree_update_nodes_written(struct btree_update *as) if (i->b) { lockrestart_do(trans, ({ btree_path_idx_t path_idx; + /* + * Unarmed take: new nodes are dirty until + * written, hence unreclaimable - the reuse + * race can't reach them, and a spurious skip + * here would leave a node that never gets its + * write kicked. + */ int _ret = bch2_btree_node_lock_with_path(trans, &i->b->c, - SIX_LOCK_read, &path_idx); + SIX_LOCK_read, 0, &path_idx); if (!_ret) { btree_node_write_if_need(trans, i->b, SIX_LOCK_read); bch2_btree_node_unlock_with_path(trans, path_idx, @@ -1401,13 +1436,18 @@ static const char * const btree_node_reawrite_reason_strs[] = { }; static struct btree_update * -bch2_btree_update_start(struct btree_trans *trans, struct btree_path *path, +bch2_btree_update_start(struct btree_trans *trans, btree_path_idx_t path_idx, unsigned level_start, bool split, unsigned target, enum bch_trans_commit_flags commit_flags, enum bch_write_flags write_flags) { struct bch_fs *c = trans->c; + /* + * Only valid until bch2_btree_reserve_get(): the allocator's btree + * iterators can grow and thus reallocate trans->paths + */ + struct btree_path *path = trans->paths + path_idx; struct btree_update *as; u64 start_time = local_clock(); int disk_res_flags = (commit_flags & BCH_TRANS_COMMIT_no_enospc) @@ -1475,7 +1515,7 @@ bch2_btree_update_start(struct btree_trans *trans, struct btree_path *path, } } - as = mempool_alloc(&c->btree.interior_updates.pool, GFP_NOFS); + as = mempool_alloc(&c->btree.interior_updates.pool, GFP_NOIO); memset(as, 0, sizeof(*as)); closure_init(&as->cl, NULL); as->c = c; @@ -1526,17 +1566,16 @@ bch2_btree_update_start(struct btree_trans *trans, struct btree_path *path, goto err; struct bch_devs_list devs_have = (struct bch_devs_list) { 0 }; + unsigned alloc_target = btree_alloc_target(c, target); req = alloc_request_get(trans, - target ?: - c->opts.metadata_target ?: - c->opts.foreground_target, - false, - &devs_have, - as->disk_res.nr_replicas, - as->disk_res.nr_replicas, - watermark, - write_flags, - NULL); + alloc_target, + false, + &devs_have, + as->disk_res.nr_replicas, + as->disk_res.nr_replicas, + watermark, + write_flags, + NULL); ret = PTR_ERR_OR_ZERO(req); if (ret) goto err; @@ -1610,7 +1649,7 @@ static void bch2_btree_set_root_inmem(struct bch_fs *c, struct btree *b) * btree_node_permanent and skips. Roots stay on bc->list, * counted normally; cache_exit's teardown sweep finds them. */ - scoped_guard(mutex, &c->btree.cache.lock) + scoped_guard(mutex_noio, &c->btree.cache.lock) set_btree_node_permanent(b); scoped_guard(mutex, &c->btree.cache.root_lock) { @@ -2288,7 +2327,7 @@ int bch2_btree_split_leaf(struct btree_trans *trans, int ret = 0; - as = bch2_btree_update_start(trans, trans->paths + path, + as = bch2_btree_update_start(trans, path, trans->paths[path].level, true, 0, flags, 0); if (IS_ERR(as)) @@ -2357,7 +2396,7 @@ static int __btree_increase_depth(struct btree_update *as, struct btree_trans *t * the flag, not by being off-list), so no list/hash work is * needed here. */ - scoped_guard(mutex, &c->btree.cache.lock) + scoped_guard(mutex_noio, &c->btree.cache.lock) clear_btree_node_permanent(b); bch2_trans_verify_locks(trans); @@ -2373,7 +2412,7 @@ int bch2_btree_increase_depth(struct btree_trans *trans, btree_path_idx_t path, return bch2_btree_split_leaf(trans, path, 0, flags); struct btree_update *as = - bch2_btree_update_start(trans, trans->paths + path, b->c.level, + bch2_btree_update_start(trans, path, b->c.level, true, 0, flags, 0); if (IS_ERR(as)) return PTR_ERR(as); @@ -3063,7 +3102,7 @@ int __bch2_foreground_maybe_merge(struct btree_trans *trans, BUG_ON(nr_dsts > 2); - as = bch2_btree_update_start(trans, trans->paths + path, level, nr_dsts == 2, + as = bch2_btree_update_start(trans, path, level, nr_dsts == 2, 0, BCH_TRANS_COMMIT_no_enospc|flags, 0); ret = PTR_ERR_OR_ZERO(as); if (ret) { @@ -3289,12 +3328,19 @@ int bch2_btree_node_rewrite(struct btree_trans *trans, struct btree_path *path = btree_iter_path(trans, iter); parent = btree_node_parent(path, b); struct btree_update *as = - bch2_btree_update_start(trans, path, b->c.level, false, target, + bch2_btree_update_start(trans, iter->path, b->c.level, false, target, commit_flags, write_flags); int ret = PTR_ERR_OR_ZERO(as); if (ret) goto out; + /* + * update_start allocates btree nodes, and the allocator's btree + * iterators can grow and thus reallocate trans->paths: re-resolve, so + * the write lock is recorded on the live path, not the old array + */ + path = btree_iter_path(trans, iter); + ret = bch2_btree_node_lock_write(trans, path, &b->c); if (ret) goto err_free_update; @@ -3478,7 +3524,7 @@ void bch2_async_btree_op(struct bch_fs *c, struct btree *b, return; struct async_btree_rewrite *a = - kzalloc(sizeof(*a), GFP_NOFS|__GFP_NORETRY|__GFP_NOWARN); + kzalloc(sizeof(*a), GFP_NOIO|__GFP_NORETRY|__GFP_NOWARN); if (!a) return; diff --git a/fs/btree/iter.c b/fs/btree/iter.c index 4237d0ea89..40c5e847f8 100644 --- a/fs/btree/iter.c +++ b/fs/btree/iter.c @@ -1830,6 +1830,13 @@ void bch2_trans_updates_to_text(struct printbuf *buf, struct btree_trans *trans) bch2_journal_entry_to_text(buf, trans->c, e); prt_newline(buf); } + + for (struct bkey_i *k = btree_trans_subbuf_base(trans, &trans->accounting); + k != btree_trans_subbuf_top(trans, &trans->accounting); + k = bkey_next(k)) { + bch2_bkey_val_to_text(buf, trans->c, bkey_i_to_s_c(k)); + prt_newline(buf); + } } noinline __cold @@ -3757,6 +3764,18 @@ u32 bch2_trans_begin(struct btree_trans *trans) unsigned i; u64 now; + /* + * Discarding queued updates is correct after a transaction restart + * (the restart loop re-queues them) and on error unwind — but a new + * iteration starting with updates queued and no restart in flight + * means the previous iteration forgot to commit them, and they're + * about to be lost silently: + */ + WARN_ON_ONCE(IS_ENABLED(CONFIG_BCACHEFS_DEBUG) && + bch2_trans_has_updates(trans) && + !trans->restarted && !trans->in_traverse_all && + !trans->begin_may_drop_updates); + bch2_trans_reset_updates(trans); trans->restart_count++; @@ -3897,7 +3916,7 @@ static inline struct btree_trans *bch2_trans_alloc(struct bch_fs *c) } } - struct btree_trans *trans = mempool_alloc(&c->btree.trans.pool, GFP_NOFS); + struct btree_trans *trans = mempool_alloc(&c->btree.trans.pool, GFP_NOIO); memset(trans, 0, sizeof(*trans)); seqmutex_lock(&c->btree.trans.lock); @@ -4147,11 +4166,19 @@ static void bch2_btree_bkey_cached_common_to_text(struct printbuf *out, c.n[0], c.n[1], c.n[2], pid); } +static char btree_lock_type_char(int lock_type) +{ + static const char lock_types[] = { 'r', 'i', 'w' }; + + return lock_type >= 0 && lock_type < ARRAY_SIZE(lock_types) + ? lock_types[lock_type] + : '?'; +} + __cold void bch2_btree_trans_to_text(struct printbuf *out, struct btree_trans *trans) { struct btree_bkey_cached_common *b; - static char lock_types[] = { 'r', 'i', 'w' }; struct task_struct *task = READ_ONCE(trans->locking_wait.task); unsigned l, idx; @@ -4192,10 +4219,12 @@ void bch2_btree_trans_to_text(struct printbuf *out, struct btree_trans *trans) prt_newline(out); for (l = 0; l < BTREE_MAX_DEPTH; l++) { - if (btree_node_locked(path, l) && + int lock_type = btree_node_locked_type(path, l); + + if (lock_type != BTREE_NODE_UNLOCKED && !IS_ERR_OR_NULL(b = (void *) READ_ONCE(path->l[l].b))) { prt_printf(out, " %c l=%u ", - lock_types[btree_node_locked_type(path, l)], l); + btree_lock_type_char(lock_type), l); bch2_btree_bkey_cached_common_to_text(out, b); prt_newline(out); } @@ -4205,7 +4234,8 @@ void bch2_btree_trans_to_text(struct printbuf *out, struct btree_trans *trans) b = READ_ONCE(trans->locking); if (b) { prt_printf(out, " blocked on:\n"); - prt_printf(out, " %c", lock_types[trans->locking_wait.lock_want]); + prt_printf(out, " %c", + btree_lock_type_char(READ_ONCE(trans->locking_wait.lock_want))); bch2_btree_bkey_cached_common_to_text(out, b); prt_newline(out); } diff --git a/fs/btree/iter.h b/fs/btree/iter.h index 31c49064fa..91511331ad 100644 --- a/fs/btree/iter.h +++ b/fs/btree/iter.h @@ -877,6 +877,19 @@ static inline struct bkey_s_c __bch2_bkey_get_typed(struct btree_iter *iter, #define bch2_bkey_get_typed(_iter, _type) \ bkey_s_c_to_##_type(__bch2_bkey_get_typed(_iter, KEY_TYPE_##_type)) +/* + * Copy a value out of a key, zeroing whatever the key is too short to hold. + * + * Values grow: a key written by an older version stops short of the fields + * added since, and we have no defaults, so a field the key predates reads as + * 0. To ask whether the key was written with a field at all, test + * bkey_val_bytes() against offsetof() - that's the only thing that answers it, + * and it's what to_text() and validate() use. + * + * The typed mut helpers pass min_bytes = sizeof(struct bkey_i_) and + * widen u64s to match, so a caller may assign a field the on-disk key was too + * short for and have it committed - see __bch2_bkey_make_mut_noupdate(). + */ static inline void __bkey_val_copy_pad(void *dst_v, unsigned dst_size, struct bkey_s_c src_k) { unsigned b = min_t(unsigned, dst_size, bkey_val_bytes(src_k.k)); @@ -909,6 +922,38 @@ static inline int __bch2_bkey_get_val_typed(struct btree_trans *trans, __bch2_bkey_get_val_typed(_trans, _btree_id, _pos, _flags, \ KEY_TYPE_##_type, sizeof(*_val), _val) +/* + * As bch2_bkey_get_val_typed(), but fetches the whole key into a caller-stack + * bkey_i_, so an error message can print the key instead of the fields + * whoever wrote the message happened to name. + * + * u64s keeps the on-disk length: the key is never written back, and + * to_text() reports u64s and gates fields on it, so widening would print + * fields the key doesn't have. Clamping to val_size is required in the other + * direction - an on-disk val longer than the caller's struct would leave u64s + * claiming val we didn't copy, and to_text() would read past the stack. + */ +static inline int __bch2_bkey_get_i_typed(struct btree_trans *trans, + enum btree_id btree, struct bpos pos, + enum btree_iter_update_trigger_flags flags, + enum bch_bkey_type type, + unsigned val_size, struct bkey_i *dst) +{ + CLASS(btree_iter, iter)(trans, btree, pos, flags); + struct bkey_s_c k = __bch2_bkey_get_typed(&iter, type); + int ret = bkey_err(k); + if (!ret) { + dst->k = *k.k; + set_bkey_val_bytes(&dst->k, min_t(unsigned, val_size, bkey_val_bytes(k.k))); + __bkey_val_copy_pad(&dst->v, val_size, k); + } + return ret; +} + +#define bch2_bkey_get_i_typed(_trans, _btree_id, _pos, _flags, _type, _k)\ + __bch2_bkey_get_i_typed(_trans, _btree_id, _pos, _flags, \ + KEY_TYPE_##_type, sizeof((_k)->v), &(_k)->k_i) + u32 bch2_trans_begin(struct btree_trans *); #define for_each_btree_node(_trans, _iter, _btree_id, _start, \ @@ -1043,6 +1088,7 @@ static inline int btree_trans_too_many_iters(struct btree_trans *trans) int _ret2; \ \ _restart_count = _orig_restart_count = (_trans)->restart_count; \ + (_trans)->begin_may_drop_updates = true; \ \ while (bch2_err_matches(_ret2 = (_do), BCH_ERR_transaction_restart))\ _restart_count = bch2_trans_begin(_trans); \ diff --git a/fs/btree/iter.rs b/fs/btree/iter.rs index 6ef7648f68..7b50583602 100644 --- a/fs/btree/iter.rs +++ b/fs/btree/iter.rs @@ -279,6 +279,46 @@ impl<'a, 't> TransAttempt<'a, 't> { Ok(dst) } + /// bkey_reassemble() into a buffer with `val_u64s` of value space: + /// the copied value is zero-extended (or truncated) to the new size. + pub fn bkey_reassemble_resized(&self, k: BkeySC<'_>, val_u64s: usize) + -> Result, BchError> + { + const BKEY_U64S: usize = size_of::() / size_of::(); + + let mut dst = self.bkey_alloc((BKEY_U64S + val_u64s) as u32)?; + dst.as_mut_u64s().fill(0); + + let copy_val = (k.k.u64s as usize - BKEY_U64S).min(val_u64s); + unsafe { + core::ptr::copy_nonoverlapping(k.k, &mut dst.k_i_mut().k, 1); + core::ptr::copy_nonoverlapping( + k.v as *const c::bch_val as *const u64, + &mut dst.as_mut_u64s()[BKEY_U64S] as *mut u64, + copy_val, + ); + } + dst.k_mut().u64s = (BKEY_U64S + val_u64s) as u8; + + Ok(dst) + } + + /// A fresh key: bkey_init()ed header with `type_` at `pos`, and + /// `val_u64s` of zeroed value space. + pub fn bkey_alloc_init(&self, val_u64s: usize, type_: u8, pos: c::bpos) + -> Result, BchError> + { + const BKEY_U64S: usize = size_of::() / size_of::(); + + let mut k = self.bkey_alloc((BKEY_U64S + val_u64s) as u32)?; + k.as_mut_u64s().fill(0); + unsafe { c::bkey_init(k.k_mut()) }; + k.k_mut().u64s = (BKEY_U64S + val_u64s) as u8; + k.k_mut().type_ = type_; + k.k_mut().p = pos; + Ok(k) + } + pub fn bkey_make_mut_noupdate(&self, k: BkeySC<'_>) -> Result, BchError> { let raw = c::bkey_s_c { k: k.k, @@ -507,6 +547,7 @@ bitflags! { const SNAPSHOT_FIELD = c::btree_iter_update_trigger_flags::BTREE_ITER_snapshot_field.0; const ALL_SNAPSHOTS = c::btree_iter_update_trigger_flags::BTREE_ITER_all_snapshots.0; const FILTER_SNAPSHOTS = c::btree_iter_update_trigger_flags::BTREE_ITER_filter_snapshots.0; + const NOFILTER_WHITEOUTS = c::btree_iter_update_trigger_flags::BTREE_ITER_nofilter_whiteouts.0; const NOPRESERVE = c::btree_iter_update_trigger_flags::BTREE_ITER_nopreserve.0; const CACHED_NOFILL = c::btree_iter_update_trigger_flags::BTREE_ITER_cached_nofill.0; const KEY_CACHE_FILL = c::btree_iter_update_trigger_flags::BTREE_ITER_key_cache_fill.0; diff --git a/fs/btree/key_cache.c b/fs/btree/key_cache.c index 269e203b6e..00f4fb4897 100644 --- a/fs/btree/key_cache.c +++ b/fs/btree/key_cache.c @@ -548,7 +548,7 @@ int bch2_btree_key_cache_journal_flush(struct journal *j, ret = lockrestart_do(trans, ({ btree_path_idx_t path_idx; int _ret = bch2_btree_node_lock_with_path(trans, &ck->c, - SIX_LOCK_intent, &path_idx); + SIX_LOCK_intent, 0, &path_idx); bool do_flush = false; if (!_ret) { diff --git a/fs/btree/locking.c b/fs/btree/locking.c index 1dc3f6ef2e..e88a2437bf 100644 --- a/fs/btree/locking.c +++ b/fs/btree/locking.c @@ -757,6 +757,20 @@ int bch2_btree_node_lock_write_contended(struct btree_trans *trans, struct btree * temporary unlocked path, take the lock, then record the lock on the path * so the cycle detector can find us as the holder. * + * @hash_val is the node's expected identity — btree_ptr_hash_val() of the key + * it was found under, or a snapshot of b->hash_val taken while the pointer + * was known valid. It arms the node-reuse check in + * bch2_six_check_for_deadlock(): if the identity is gone by the time we'd + * sleep, the lock attempt aborts with no_btree_node_reused rather than + * parking behind an off-path holder (btree_node_reclaim's trylocks) that may + * hold the reused node's lock indefinitely. + * + * Pass 0 only when reclaim genuinely can't take the node — e.g. the write + * completion path, which owns the write_in_flight that blocks reclaim — or + * for key cache locks, which the check doesn't cover. Beware flags another + * thread can clear: a journal pin doesn't pin (the node can be written and + * the pin dropped concurrently), and neither does dirty on its own. + * * Caller releases via bch2_btree_node_unlock_with_path(). * * May return a transaction_restart; wrap in lockrestart_do(). @@ -765,15 +779,14 @@ int __must_check bch2_btree_node_lock_with_path(struct btree_trans *trans, struct btree_bkey_cached_common *b, enum six_lock_type type, + u64 hash_val, btree_path_idx_t *path_idx_out) { btree_path_idx_t path_idx = bch2_path_get_unlocked_mut(trans, b->btree_id, b->level, btree_node_pos(b), b->cached); struct btree_path *path = trans->paths + path_idx; - /* No key context here — caller already has the b. Skip the hash_val - * check; we're acquiring on a node the caller already validated. */ - trans->locking_hash_val = 0; + trans->locking_hash_val = hash_val; trans->locking_root_id = -1; int ret = btree_node_lock(trans, path, b, b->level, type); if (ret) { @@ -1249,6 +1262,19 @@ void bch2_trans_unlock(struct btree_trans *trans) bch2_btree_cache_cannibalize_unlock(trans); } +/* + * Slow devices legitimately hold the srcu lock across submit_bio() for a long + * time (e.g. scanning the inodes btree off a slow disk during snapshot + * deletion), so scale the "held too long" warning past the worst observed + * device latency rather than spamming the log when the real problem is just + * slow storage. The lock is held over btree node reads on any online device, + * so that's the latency we key off. + */ +static unsigned long srcu_hold_warn_thresh(struct bch_fs *c) +{ + return max(bch2_dev_latency_max(c, &c->devs_online, READ) * 2, HZ * 10UL); +} + void bch2_trans_unlock_long(struct btree_trans *trans) { bch2_trans_unlock(trans); @@ -1265,7 +1291,9 @@ void bch2_trans_unlock_long(struct btree_trans *trans) if (unlikely(trans->srcu_held && !trans->srcu_io_submitted && - time_after(jiffies, trans->srcu_lock_time + HZ * 10))) { + time_after(jiffies, trans->srcu_lock_time + HZ * 10) && + time_after(jiffies, trans->srcu_lock_time + + srcu_hold_warn_thresh(c)))) { CLASS(bch_log_msg_ratelimited, msg)(c); prt_printf(&msg.m, "btree trans held srcu lock (delaying memory reclaim) for %lu seconds\n", diff --git a/fs/btree/locking.h b/fs/btree/locking.h index c0c4e6dabe..d925d6a902 100644 --- a/fs/btree/locking.h +++ b/fs/btree/locking.h @@ -75,8 +75,8 @@ static inline void trans_set_locked(struct btree_trans *trans, bool try) trans->last_unlock_ip = 0; lock_acquire_exclusive(&trans->dep_map, 0, try, NULL, _THIS_IP_); - trans->pf_memalloc_nofs = (current->flags & PF_MEMALLOC_NOFS) != 0; - current->flags |= PF_MEMALLOC_NOFS; + trans->pf_memalloc_noio = (current->flags & PF_MEMALLOC_NOIO) != 0; + current->flags |= PF_MEMALLOC_NOIO; trans_maybe_disable_migrate(trans); } @@ -89,8 +89,8 @@ static inline void trans_set_unlocked(struct btree_trans *trans) trans->last_unlock_ip = _RET_IP_; lock_release(&trans->dep_map, _THIS_IP_); - if (!trans->pf_memalloc_nofs) - current->flags &= ~PF_MEMALLOC_NOFS; + if (!trans->pf_memalloc_noio) + current->flags &= ~PF_MEMALLOC_NOIO; } } @@ -415,7 +415,8 @@ static inline void bch2_btree_node_lock_write_nofail(struct btree_trans *trans, int __must_check bch2_btree_node_lock_with_path(struct btree_trans *, struct btree_bkey_cached_common *, - enum six_lock_type, btree_path_idx_t *); + enum six_lock_type, u64 hash_val, + btree_path_idx_t *); /* relock: */ diff --git a/fs/btree/read.c b/fs/btree/read.c index c023c2f479..7186e0d5b0 100644 --- a/fs/btree/read.c +++ b/fs/btree/read.c @@ -117,6 +117,18 @@ static void btree_err_msg(struct printbuf *out, struct bch_fs *c, struct bch_dev prt_newline(out); } +/* + * Damage we were able to work around while parsing: the in-memory node is + * usable, but what's on disk isn't, so the repair only means something once + * it's been written back. + */ +static int btree_err_degraded(struct bch_fs *c, struct btree *b) +{ + set_btree_node_need_rewrite(b); + set_btree_node_need_rewrite_error(b); + return bch_err_throw(c, fsck_fix); +} + __printf(11, 12) static int __btree_err(enum bch_fsck_flags flags, struct bch_fs *c, @@ -151,10 +163,21 @@ static int __btree_err(enum bch_fsck_flags flags, bkey_i_to_s_c(&b->key), failed, &pick, 0, 0) == 1; - return !have_retry && - (flags & FSCK_CAN_FIX) && - bch2_fsck_err_opt(c, FSCK_CAN_FIX, err_type) == -BCH_ERR_fsck_fix - ? bch_err_throw(c, fsck_fix) + /* + * Reading is not repairing, so fix_errors has no say here: it + * decides whether a repair is persisted, not whether a node can + * be read. Consulting it meant a node that parses fine was + * reported unreadable whenever the run wasn't fixing errors - + * which is every ordinary mount, since fix_errors defaults to + * exit and bset_bad_csum isn't autofix. Topology repair then + * dropped a node that was sitting right there, leaving a gap + * that btree node scan filled with the same node, forever. + * + * The write is gated where it belongs: bch2_async_btree_op() + * only queues a rewrite once the fs can take a write ref. + */ + return !have_retry && (flags & FSCK_CAN_FIX) + ? btree_err_degraded(c, b) : bch_err_throw(c, btree_node_validate_err); } else { CLASS(bch_log_msg, msg)(c); @@ -269,8 +292,7 @@ int bch2_validate_bset(struct bch_fs *c, struct bch_dev *ca, "bset version %u older than superblock version_min %u", version, c->sb.version_min)) { if (bch2_version_compatible(version)) { - guard(memalloc_flags)(PF_MEMALLOC_NOFS); - guard(mutex)(&c->sb_lock); + guard(mutex_noio)(&c->sb_lock); c->disk_sb.sb->version_min = cpu_to_le16(version); bch2_write_super(c); } else { @@ -286,8 +308,7 @@ int bch2_validate_bset(struct bch_fs *c, struct bch_dev *ca, btree_node_bset_newer_than_sb, "bset version %u newer than superblock version %u", version, c->sb.version)) { - guard(memalloc_flags)(PF_MEMALLOC_NOFS); - guard(mutex)(&c->sb_lock); + guard(mutex_noio)(&c->sb_lock); c->disk_sb.sb->version = cpu_to_le16(version); bch2_write_super(c); } @@ -594,7 +615,7 @@ int bch2_btree_node_read_done(struct bch_fs *c, struct bch_dev *ca, /* We might get called multiple times on read retry: */ b->written = 0; - iter = mempool_alloc(&c->btree.fill_iter, GFP_NOFS); + iter = mempool_alloc(&c->btree.fill_iter, GFP_NOIO); sort_iter_init(iter, b, (btree_blocks(c) + 1) * 2); if (bch2_meta_read_fault("btree")) @@ -1058,7 +1079,7 @@ void bch2_btree_node_read(struct btree_trans *trans, struct btree *b, bio = bio_alloc_bioset(NULL, buf_nr_bvecs(b->data, btree_buf_bytes(b)), REQ_OP_READ|REQ_SYNC|REQ_META, - GFP_NOFS, + GFP_NOIO, &c->btree.bio); rb = container_of(bio, struct btree_read_bio, bio); rb->c = c; diff --git a/fs/btree/sort.c b/fs/btree/sort.c index bdedf0243f..53c7fbf51f 100644 --- a/fs/btree/sort.c +++ b/fs/btree/sort.c @@ -249,7 +249,7 @@ void *bch2_btree_bounce_alloc_noprof(struct bch_fs *c, size_t size, bool *used_m { BUG_ON(size > c->opts.btree_node_size); - guard(memalloc_flags)(PF_MEMALLOC_NOFS); + guard(memalloc_flags)(PF_MEMALLOC_NOIO); *used_mempool = false; #if defined(__KERNEL__) && LINUX_VERSION_CODE < KERNEL_VERSION(6,18,0) @@ -266,7 +266,7 @@ void *bch2_btree_bounce_alloc_noprof(struct bch_fs *c, size_t size, bool *used_m #endif if (!p) { *used_mempool = true; - p = mempool_alloc_noprof(&c->btree.bounce_pool, GFP_NOFS|__GFP_ACCOUNT|__GFP_RECLAIMABLE); + p = mempool_alloc_noprof(&c->btree.bounce_pool, GFP_NOIO|__GFP_ACCOUNT|__GFP_RECLAIMABLE); } return p; } diff --git a/fs/btree/types.h b/fs/btree/types.h index 179c9fc29b..0eb661f84e 100644 --- a/fs/btree/types.h +++ b/fs/btree/types.h @@ -5,6 +5,8 @@ #include #include +#include "util/locking.h" + #include "alloc/buckets_types.h" #include "alloc/replicas_types.h" @@ -272,7 +274,7 @@ struct bch_fs_btree_cache { * common to delete and allocate btree nodes in quick succession. It * should never grow past ~2-3 nodes in practice. */ - struct mutex lock; + struct mutex_noio lock; struct list_head freeable; struct list_head freed_pcpu; struct list_head freed_nonpcpu; @@ -677,7 +679,7 @@ struct btree_trans { */ bool srcu_io_submitted:1; bool btree_cache_cannibalize_locked:1; - bool pf_memalloc_nofs:1; + bool pf_memalloc_noio:1; bool used_mempool:1; bool in_traverse_all:1; bool paths_sorted:1; @@ -685,6 +687,16 @@ struct btree_trans { bool journal_transaction_names:1; bool journal_replay_not_finished:1; bool notrace_relock_fail:1; + /* + * Exempt bch2_trans_begin() from the dropped-updates warning. Set + * around a nested transaction - one that grabs trans->restart_count, + * does work whose inner commits discard the outer's queued updates, and + * returns trans_was_restarted() (e.g. fsck counting i_sectors, which + * spans too many extents to be a single transaction). The begin can't + * see the restart that's about to be returned, so the caller vouches + * for it here. + */ + bool begin_may_drop_updates:1; bool has_interior_updates:1; enum bch_errcode restarted:16; u32 restart_count; diff --git a/fs/btree/update.c b/fs/btree/update.c index 2a97457c72..3b773bd4fc 100644 --- a/fs/btree/update.c +++ b/fs/btree/update.c @@ -125,6 +125,18 @@ int __bch2_insert_snapshot_whiteouts(struct btree_trans *trans, snapshot_id_list *s) { darray_for_each(*s, id) { + /* + * In fsck, a repair can fan whiteouts across an unbounded + * number of snapshots: commit and restart before the batch + * hits the trans mem cap. The re-drive converges - committed + * whiteouts fail the KEY_TYPE_deleted check below and are + * skipped. Runtime callers (extent splits) are excluded so + * their whiteouts stay atomic with the extent update: + */ + if (test_bit(BCH_FS_in_fsck, &trans->c->flags)) + try(bch2_trans_commit_lazy_if_full(trans, NULL, NULL, + BCH_TRANS_COMMIT_no_enospc)); + pos.snapshot = *id; CLASS(btree_iter, iter)(trans, btree, pos, BTREE_ITER_not_extents|BTREE_ITER_intent); @@ -177,7 +189,7 @@ int bch2_trans_update_extent_overwrite(struct btree_trans *trans, * reservation: */ if (nr_splits > 1 && - (compressed_sectors = bch2_bkey_sectors_compressed(c, old))) + (compressed_sectors = bch2_bkey_durability_safe(c, old).sectors_compressed)) trans->extra_disk_res += compressed_sectors * (nr_splits - 1); if (front_split) { diff --git a/fs/btree/update.h b/fs/btree/update.h index 86313b174e..375b345548 100644 --- a/fs/btree/update.h +++ b/fs/btree/update.h @@ -356,6 +356,31 @@ static inline int bch2_trans_commit_lazy(struct btree_trans *trans, return __bch2_trans_commit(trans, flags, true); } +/* + * For repair loops that batch unbounded work - an update per snapshot + * version, typically - into one transaction: once substantial work has + * accumulated, commit and signal a restart (transaction_restart_commit) + * so the caller's restart loop re-drives, instead of the bump allocator + * running into BTREE_TRANS_MEM_MAX. + * + * The re-drive runs with the partial batch committed: callers must + * re-check on-disk state and skip already-committed repairs, so the + * re-drive shrinks - otherwise it trips this at the same point again + * and the restart loop can't make forward progress. + */ +static inline int bch2_trans_commit_lazy_if_full(struct btree_trans *trans, + struct disk_reservation *disk_res, + u64 *journal_seq, + unsigned flags) +{ + /* disk_accounting_mod allocations grow by powers of 2; max / 2 is too + * small of a limit to avoid hiting ENOMEMS + */ + return likely(trans->mem_top < BTREE_TRANS_MEM_MAX / 4) + ? 0 + : bch2_trans_commit_lazy(trans, disk_res, journal_seq, flags); +} + #define commit_do(_trans, _disk_res, _journal_seq, _flags, _do) \ lockrestart_do(_trans, _do ?: bch2_trans_commit(_trans, (_disk_res),\ (_journal_seq), (_flags))) @@ -382,6 +407,15 @@ static __always_inline struct bkey_i *__bch2_bkey_make_mut_noupdate(struct btree if (!IS_ERR(mut)) { bkey_reassemble(mut, k); + /* + * Writes extend: the typed helpers pass min_bytes = + * sizeof(struct bkey_i_), and widening u64s is what lets + * the caller assign any field of the current struct and have it + * committed. Without it an assignment past the on-disk val + * would land in memory we allocated, and be dropped on the + * floor at commit. The bytes we add are zero, which is what + * those fields already read as - see __bkey_val_copy_pad(). + */ if (unlikely(bytes > bkey_bytes(k.k))) { memset((void *) mut + bkey_bytes(k.k), 0, bytes - bkey_bytes(k.k)); diff --git a/fs/btree/write.c b/fs/btree/write.c index b0532aca35..602c14a63a 100644 --- a/fs/btree/write.c +++ b/fs/btree/write.c @@ -102,7 +102,7 @@ static int btree_node_write_update_key(struct btree_trans *trans, bch2_bkey_drop_ptrs_noerror(bkey_i_to_s(n), p, entry, bch2_dev_io_failures(&wbio->wbio.failed, p.ptr.dev)); - if (!bch2_bkey_nr_dirty_ptrs(c, bkey_i_to_s_c(n))) + if (!bch2_bkey_durability_safe(c, bkey_i_to_s_c(n)).nr_ptrs) return bch_err_throw(c, btree_node_write_all_failed); if (wbio->wbio.failed.nr) { @@ -179,7 +179,8 @@ static void btree_node_write_work(struct work_struct *work) lockrestart_do(trans, ({ btree_path_idx_t path_idx; - int ret = bch2_btree_node_lock_with_path(trans, &b->c, SIX_LOCK_read, &path_idx); + /* identity pinned: write_in_flight (cleared below) blocks reclaim */ + int ret = bch2_btree_node_lock_with_path(trans, &b->c, SIX_LOCK_read, 0, &path_idx); if (!ret) { __btree_node_write_done(trans, b); bch2_btree_node_unlock_with_path(trans, path_idx, b->c.level); @@ -527,7 +528,7 @@ void __bch2_btree_node_write(struct btree_trans *trans, struct btree *b, unsigne wbio = container_of(bio_alloc_bioset(NULL, buf_nr_bvecs(data, sectors_to_write << 9), REQ_OP_WRITE|REQ_META|REQ_SYNC|REQ_IDLE, - GFP_NOFS, + GFP_NOIO, &c->btree.bio), struct btree_write_bio, wbio.bio); wbio_init(&wbio->wbio.bio); @@ -770,7 +771,7 @@ static bool __bch2_btree_flush_all(struct bch_fs *c, unsigned flag) while (true) { struct btree *waiting = NULL, *b; - scoped_guard(mutex, &bc->lock) + scoped_guard(mutex_noio, &bc->lock) list_for_each_entry(b, &bc->freeable, list) if (test_bit(flag, &b->flags)) { waiting = b; @@ -829,7 +830,7 @@ void bch2_btree_cancel_all_writes(struct bch_fs *c) if (!bc->table_init_done) return; - scoped_guard(mutex, &bc->lock) { + scoped_guard(mutex_noio, &bc->lock) { for (unsigned i = 0; i < ARRAY_SIZE(bc->live); i++) { struct btree *b, *t; list_for_each_entry_safe(b, t, &bc->live[i].dirty, list) { diff --git a/fs/btree/write_buffer.c b/fs/btree/write_buffer.c index 60c26116a2..4045326148 100644 --- a/fs/btree/write_buffer.c +++ b/fs/btree/write_buffer.c @@ -603,16 +603,22 @@ static int bch2_btree_write_buffer_flush_locked(struct btree_trans *trans, bool accounting_replay_done = test_bit(BCH_FS_accounting_replay_done, &c->flags); int ret = 0; + /* + * The flush allocates under the write buffer locks (flush shards, key + * array resizes), and with swap on bcachefs those locks are on the + * reclaim path - all of flush runs NOIO so allocations can't recurse + * into the IO this flush is needed to complete: + */ + guard(memalloc_flags)(PF_MEMALLOC_NOIO); + try(bch2_journal_error(&c->journal)); - scoped_guard(memalloc_flags, PF_MEMALLOC_NOFS) { - if (!wb->flushing.keys.nr) { - guard(mutex)(&wb->inc.lock); - move_keys_from_inc_to_flushing(wb); - } else if (mutex_trylock(&wb->inc.lock)) { - move_keys_from_inc_to_flushing(wb); - mutex_unlock(&wb->inc.lock); - } + if (!wb->flushing.keys.nr) { + guard(mutex)(&wb->inc.lock); + move_keys_from_inc_to_flushing(wb); + } else if (mutex_trylock(&wb->inc.lock)) { + move_keys_from_inc_to_flushing(wb); + mutex_unlock(&wb->inc.lock); } if (!wb->flushing.keys.nr) @@ -833,6 +839,14 @@ static int bch2_btree_write_buffer_flush_locked(struct btree_trans *trans, static void bch2_journal_keys_to_write_buffer_lock(struct bch_fs *c, struct journal_keys_to_wb *dst) { + /* + * Intake allocates under the write buffer locks (key array resizes, + * accounting pushes), which sit on the reclaim path when swap is on + * bcachefs: callers must have established a NOIO scope. Both current + * callers hold j->buf_lock, a mutex_noio, across the whole bracket: + */ + EBUG_ON(!(current->flags & PF_MEMALLOC_NOIO)); + memset(dst, 0, sizeof(*dst)); for (enum bch_wb_btree idx = 0; idx < BCH_WB_BTREE_NR; idx++) { @@ -931,7 +945,7 @@ static int fetch_wb_keys_from_journal(struct bch_fs *c, u64 max_seq) bool blocked; int ret = 0; - guard(mutex)(&j->buf_lock); + guard(mutex_noio)(&j->buf_lock); bch2_journal_keys_to_write_buffer_lock(c, &dst); while (!ret && (buf = bch2_next_write_buffer_flush_journal_buf(j, max_seq, &blocked))) { @@ -1053,6 +1067,16 @@ static int bch2_btree_write_buffer_journal_flush(struct journal *j, return 0; } +/* + * Drops the transaction's locks - it commits the buffered keys itself. Call + * bch2_trans_begin() before touching the btree again. + * + * Every caller today satisfies that only by happening to follow this with a + * for_each_btree_key* or commit_do, which begin on their own. Put a plain read + * after it instead and you get "trans should be locked, unlocked by + * btree_write_buffer_flush_seq" - at runtime, in a kernel build, and nowhere + * that a tools build or a compile would show you. + */ int bch2_btree_write_buffer_flush_sync(struct btree_trans *trans) { struct bch_fs *c = trans->c; @@ -1199,7 +1223,7 @@ static void bch2_btree_write_buffer_flush_work_fn(struct work_struct *work) struct bch_fs *c = wb->c; enum wb_flush_caller caller = READ_ONCE(wb->flush_work_caller); - scoped_guard(memalloc_flags, PF_MEMALLOC_NOFS) { + scoped_guard(memalloc_flags, PF_MEMALLOC_NOIO) { guard(mutex)(&wb->flushing.lock); CLASS(btree_trans, trans)(c); while (1) { @@ -1354,6 +1378,9 @@ int bch2_journal_keys_to_write_buffer_end(struct bch_fs *c, struct journal_keys_ int bch2_btree_write_buffer_resize(struct bch_fs *c, size_t new_size) { + /* Reallocates the key arrays under the write buffer locks: */ + guard(memalloc_flags)(PF_MEMALLOC_NOIO); + for (unsigned i = 0; i < BCH_WB_BTREE_NR; i++) { struct bch_fs_btree_write_buffer *wb = &c->btree.write_buffer[i]; try(wb_keys_resize(&wb->flushing, new_size)); @@ -1393,10 +1420,10 @@ __cold void bch2_btree_write_buffer_to_text(struct printbuf *out, struct bch_fs prt_printf(out, "shards total:\t%llu\n", wb->nr_shards_total); if (wb->nr_flushes) prt_printf(out, "avg shards/flush:\t%llu\n", - wb->nr_shards_total / wb->nr_flushes); + div64_u64(wb->nr_shards_total, wb->nr_flushes)); if (wb->nr_shards_total) prt_printf(out, "avg shard size:\t%llu\n", - wb->nr_keys_flushed / wb->nr_shards_total); + div64_u64(wb->nr_keys_flushed, wb->nr_shards_total)); prt_printf(out, "flush work:\t%s\n", work_busy(&wb->flush_work) ? "busy" : "idle"); diff --git a/fs/build.rs b/fs/build.rs index 9c19ecf58f..d410fa4a7c 100644 --- a/fs/build.rs +++ b/fs/build.rs @@ -13,8 +13,19 @@ include!("codegen.rs"); fn watch_dir(dir: &str) { let Ok(entries) = std::fs::read_dir(dir) else { return }; for entry in entries.flatten() { + // file_type() reads the dirent directly - unlike Path::is_dir() it does + // NOT follow symlinks. Following them descends ktest-out/kernel into a + // full kernel tree and ktest-out/vm into /tmp; over virtiofs in the test + // VM that stat-storm makes the build crawl. We walk "..", so this is + // reachable whenever a build has been run in-tree. + let Ok(file_type) = entry.file_type() else { continue }; let path = entry.path(); - if path.is_dir() { + if file_type.is_dir() { + // Build output and VCS dirs hold no wrapper-included C/H, only huge + // file counts - don't recurse into them. + if matches!(entry.file_name().to_str(), Some("target" | "ktest-out" | ".git")) { + continue; + } watch_dir(&path.to_string_lossy()); } else if path.extension().is_some_and(|e| e == "h" || e == "c") { println!("cargo:rerun-if-changed={}", path.display()); diff --git a/fs/codegen.rs b/fs/codegen.rs index 16040b1514..8baf2f6b62 100644 --- a/fs/codegen.rs +++ b/fs/codegen.rs @@ -32,13 +32,19 @@ const HEADERS: &[&str] = &[ // Translated 1:1 from the bindgen builder calls in build.rs. const ALLOWLIST_FUNCTION: &[&str] = &[ - ".*bch2_.*", "block_bytes", "match_string", "printbuf.*", "_bch2_err_matches", + // rust_* are C shims that exist solely for Rust to call (e.g. util/locking.h + // wraps the memalloc_flags_* static inlines, which don't reach Rust). Same + // convention as bch_bindgen's allowlist. + ".*bch2_.*", "rust_.*", "block_bytes", "match_string", "printbuf.*", "_bch2_err_matches", "bpos_.*", "bkey_init", "bkey_.*_init", "bkey_i_to_s", "bkey_i_to_s_c", "btree_iter_path", "extent_entry_u64s", "enumerated_ref_put", // crypto helpers for the dump sanitize path (static inlines, not // bch2_-prefixed): nonce constructors + bset_encrypt, driven from Rust // over the already-wrapped bch2_checksum / bch2_encrypt. "journal_nonce", "btree_nonce", "bset_encrypt", + // hand-rolled error-entry field accessors (sb/errors_format.h): the + // damage command unpacks BCHFS_IOC_GET_DAMAGE entries through them. + "BCH_SB_ERROR_ENTRY_V2_.*", ]; const BLOCKLIST_FUNCTION: &[&str] = &["bch2_prt_vprintf", ".*bch2_snapshot_id_state"]; const BLOCKLIST_TYPE: &[&str] = &["bch_ioctl_data_event", "bch_replicas_padded__bindgen_ty_.*"]; @@ -87,6 +93,7 @@ const DERIVE_READD: &[&str] = &[ "bpos", "bbpos", "subvol_inum", "bch_opts", "bch_ioctl_snapshot_node", + "bch_ioctl_snapshot_node_v2", ]; // bch_key/bch_encrypted_key hold key material: they get a hand-written Clone @@ -216,11 +223,33 @@ fn regex_escape(s: &str) -> String { } /// Default blocklist dirs for the userspace build: types from the kernel-compat -/// `include/` shim and from `/usr` are resolved through bcachefs-shim, not -/// re-emitted. The kernel build passes its own header trees instead. +/// `include/` shim and from system headers are resolved through bcachefs-shim, +/// not re-emitted. The kernel build passes its own header trees instead. +/// +/// Why path regexes and not something structural: bindgen has no notion of +/// "system header" (nothing keyed off -isystem), only file-path patterns. And +/// --allowlist-file can't replace these: allowlisting makes every item in a +/// matching file a *root*, so --wrap-static-fns then wraps every static inline +/// in the tree - which breaks on functions whose signatures use +/// structs-defined-within-structs (bindgen's mangled names for those aren't +/// real C types, so the generated extern.c doesn't compile). Curated +/// allowlists pick the roots; these patterns prune dependencies back to the +/// shim. +/// +/// The patterns keep a leading wildcard so sysroot'd cross builds stay +/// covered (--sysroot puts system headers at $sysroot/usr/include), but +/// require the /usr/include (etc.) path component: a bare `.*/usr/.*` also +/// matched source trees under paths like /usr/src/RPM/BUILD (#801). On +/// distros where system headers live elsewhere entirely (NixOS: /nix/store) +/// these are inert and the shim include/ entry does all the pruning - do NOT +/// "fix" that with a store-path pattern, nix builds put the source tree in +/// the store too, which is #801 all over again. pub fn default_blocklist(src: &str) -> Vec { let include_dir = format!("{}/include", parent(src)); - vec![format!("{}/.*", regex_escape(&include_dir)), ".*/usr/.*".to_string()] + vec![format!("{}/.*", regex_escape(&include_dir)), + ".*/usr/include/.*".to_string(), + ".*/usr/local/include/.*".to_string(), + ".*/usr/lib/.*".to_string()] } /// Generate the x-macro-derived *_gen.rs files from the *_format.h headers. @@ -400,6 +429,13 @@ pub fn gen_xmacros(src: &str, out: &str) { generate_btree_ids_known(&btree_ids), ) .expect("write btree_ids_gen.rs"); + + let ioctl_h = std::fs::read_to_string(format!("{src}/bcachefs_ioctl.h")) + .expect("reading bcachefs_ioctl.h"); + let ioctls = parse_ioctls(&ioctl_h); + assert!(!ioctls.is_empty(), "failed to parse any _IO*() defines"); + std::fs::write(format!("{out}/ioctls_gen.rs"), generate_ioctls(&ioctls)) + .expect("write ioctls_gen.rs"); } // --------------------------------------------------------------------------- @@ -887,6 +923,19 @@ fn generate_btree_ids_known(entries: &[Vec]) -> String { } out.push_str("];\n"); + let mut mask: u64 = 0; + for e in entries { + let nr: u32 = e[1].trim().parse().expect("BCH_BTREE_IDS: numeric id"); + if e[2].contains("BTREE_IS_snapshots") { + mask |= 1 << nr; + } + } + out.push_str(&format!( + "\n/// Btrees whose keys are snapshotted; mirrors the C btree_has_snapshots_mask\n\ + /// (a static const bindgen can't see).\n\ + pub const BTREE_HAS_SNAPSHOTS_MASK: u64 = {mask:#x};\n" + )); + out } @@ -1101,6 +1150,96 @@ fn packed_and_align_fix(bindings: String, ptr_width: &str) -> String { out } +/// One `#define BCH_IOCTL_* _IO*(0xbc, nr[, type])` from bcachefs_ioctl.h. +struct IoctlDef { + name: String, + /// _IOC direction bits: 1 = kernel reads the argument (_IOW), + /// 2 = kernel writes it (_IOR), 3 = both (_IOWR), 0 = no argument. + dir: u32, + nr: u32, + /// Rust type of the argument; None for _IO(). + arg: Option, +} + +fn parse_ioctls(header: &str) -> Vec { + let mut out = Vec::new(); + for line in header.lines() { + let Some(rest) = line.strip_prefix("#define ") else { continue }; + let mut it = rest.splitn(2, char::is_whitespace); + let (Some(name), Some(body)) = (it.next(), it.next()) else { continue }; + let Some((mac, args)) = body.trim().split_once('(') else { continue }; + let dir = match mac.trim() { + "_IO" => 0, + "_IOW" => 1, + "_IOR" => 2, + "_IOWR" => 3, + _ => continue, + }; + let Some(args) = args.trim_end().strip_suffix(')') else { continue }; + let args: Vec<&str> = args.splitn(3, ',').map(str::trim).collect(); + assert_eq!(args[0], "0xbc", "{name}: unexpected ioctl magic {}", args[0]); + let nr: u32 = args[1].parse() + .unwrap_or_else(|_| panic!("{name}: bad ioctl nr {}", args[1])); + let arg = (args.len() > 2).then(|| ioctl_arg_to_rust(name, args[2])); + assert_eq!(arg.is_none(), dir == 0, "{name}: _IO() iff no argument"); + out.push(IoctlDef { name: name.to_string(), dir, nr, arg }); + } + out +} + +fn ioctl_arg_to_rust(name: &str, ty: &str) -> String { + if let Some(s) = ty.strip_prefix("struct ") { + format!("c::{}", s.trim()) + } else if ty == "const char __user *" { + "*const core::ffi::c_char".to_string() + } else { + panic!("{name}: unhandled ioctl argument type: {ty}"); + } +} + +fn generate_ioctls(defs: &[IoctlDef]) -> String { + let mut out = String::from("\ +// Auto-generated from bcachefs_ioctl.h — do not edit +// +// A zero-sized marker type per ioctl, named exactly as the C macro, +// binding the opcode to its argument type so a call site can't pair the +// wrong two: the opcode's size bits are computed from the very type the +// call layer makes you pass. Opcodes use the generic asm-generic/ioctl.h +// layout (dir at bit 30, size at 16, magic at 8, nr at 0); architectures +// with a different _IOC layout (alpha, mips, ppc, sparc) would need +// opcode() adjusted. + +use crate::c; + +/// An ioctl definition: the request opcode and its argument type. +pub trait Ioctl { + const OPCODE: u32; + /// _IOC direction bits: 1 = kernel reads the argument (_IOW), + /// 2 = kernel writes it (_IOR), 3 = both (_IOWR), 0 = no argument. + const DIR: u32; + type Arg; +} + +const fn opcode(dir: u32, nr: u32, size: usize) -> u32 { + (dir << 30) | ((size as u32) << 16) | (0xbc << 8) | nr +} + +"); + for d in defs { + let arg = d.arg.as_deref().unwrap_or("()"); + out += &format!("\ +pub struct {name}; +impl Ioctl for {name} {{ + const DIR: u32 = {dir}; + const OPCODE: u32 = opcode({dir}, {nr}, core::mem::size_of::<{arg}>()); + type Arg = {arg}; +}} + +", name = d.name, dir = d.dir, nr = d.nr, arg = arg); + } + out +} + fn parent(p: &str) -> String { std::path::Path::new(p).parent().expect("src has a parent").to_string_lossy().into_owned() } diff --git a/fs/data/checksum.c b/fs/data/checksum.c index 12651d72dd..0218734bc8 100644 --- a/fs/data/checksum.c +++ b/fs/data/checksum.c @@ -580,8 +580,7 @@ int bch2_decrypt_sb_key(struct bch_fs *c, */ int bch2_disable_encryption(struct bch_fs *c) { - guard(memalloc_flags)(PF_MEMALLOC_NOFS); - guard(mutex)(&c->sb_lock); + guard(mutex_noio)(&c->sb_lock); struct bch_sb_field_crypt *crypt = bch2_sb_field_get(c->disk_sb.sb, crypt); if (!crypt) @@ -614,8 +613,7 @@ int bch2_enable_encryption(struct bch_fs *c, bool keyed) struct bch_sb_field_crypt *crypt; int ret = -EINVAL; - guard(memalloc_flags)(PF_MEMALLOC_NOFS); - guard(mutex)(&c->sb_lock); + guard(mutex_noio)(&c->sb_lock); /* Do we already have an encryption key? */ if (bch2_sb_field_get(c->disk_sb.sb, crypt)) diff --git a/fs/data/compress.c b/fs/data/compress.c index c19846f6ea..cad22cce43 100644 --- a/fs/data/compress.c +++ b/fs/data/compress.c @@ -36,6 +36,7 @@ #include "data/extents.h" #include "data/write.h" +#include "sb/errors.h" #include "sb/io.h" #include "init/error.h" @@ -68,20 +69,9 @@ static inline enum bch_compression_opts bch2_compression_type_to_opt(enum bch_co } } -/* Bounce buffer: */ -struct bbuf { - struct bch_fs *c; - void *b; - enum bbuf_type { - BB_none, - BB_vmap, - BB_kmalloc, - BB_mempool, - } type; - int rw; -}; +/* Bounce buffer: struct bbuf lives in compress.h, the write path uses it */ -static void bbuf_exit(struct bbuf *buf) +void bch2_bbuf_exit(struct bbuf *buf) { switch (buf->type) { case BB_none: @@ -98,7 +88,7 @@ static void bbuf_exit(struct bbuf *buf) } } -static struct bbuf __bounce_alloc(struct bch_fs *c, unsigned size, int rw) +struct bbuf bch2_bounce_alloc(struct bch_fs *c, unsigned size, int rw) { void *b; @@ -113,10 +103,10 @@ static struct bbuf __bounce_alloc(struct bch_fs *c, unsigned size, int rw) * read, or its unwritten tail is never consumed. By case: * * - READ bounces (compression input, decompression compressed-input): - * bio_bounce() memcpy_from_bio()s the entire buffer before anything + * bch2_bio_bounce() memcpy_from_bio()s the entire buffer before anything * reads it. * - * - decompression output: buf_uncompress() verifies it produced the + * - decompression output: bch2_buf_uncompress() verifies it produced the * full uncompressed_size (lz4/zstd check the returned length, gzip * checks avail_out); on a decompress error the buffer is discarded, * not consumed. @@ -134,20 +124,20 @@ static struct bbuf __bounce_alloc(struct bch_fs *c, unsigned size, int rw) * The mempool fallback below is not flagged: mempool reuse returns * elements without re-zeroing, so it never pays the init_on_alloc cost. */ - b = kmalloc(size, GFP_NOFS|__GFP_NOWARN|__GFP_SKIP_ZERO); + b = kmalloc(size, GFP_NOIO|__GFP_NOWARN|__GFP_SKIP_ZERO); if (b) return (struct bbuf) { .c = c, .b = b, .type = BB_kmalloc, .rw = rw }; - b = mempool_alloc(&c->compress.bounce[rw], GFP_NOFS); + b = mempool_alloc(&c->compress.bounce[rw], GFP_NOIO); if (b) return (struct bbuf) { .c = c, .b = b, .type = BB_mempool, .rw = rw }; BUG(); } -static struct bbuf bio_bounce(struct bch_fs *c, struct bio *bio, struct bvec_iter start, int rw) +struct bbuf bch2_bio_bounce(struct bch_fs *c, struct bio *bio, struct bvec_iter start, int rw) { - struct bbuf ret = __bounce_alloc(c, start.bi_size, rw); + struct bbuf ret = bch2_bounce_alloc(c, start.bi_size, rw); if (rw == READ) memcpy_from_bio(ret.b, bio, start); @@ -172,7 +162,7 @@ static bool bio_phys_contig(struct bio *bio, struct bvec_iter start) return true; } -static struct bbuf __bio_map_or_bounce(struct bch_fs *c, struct bio *bio, +static struct bbuf __bch2_bio_map_or_bounce(struct bch_fs *c, struct bio *bio, struct bvec_iter start, int rw) { BUG_ON(start.bi_size > c->opts.encoded_extent_max); @@ -201,11 +191,11 @@ static struct bbuf __bio_map_or_bounce(struct bch_fs *c, struct bio *bio, if (iter.bi_size != start.bi_size && bv.bv_offset) - return bio_bounce(c, bio, start, rw); + return bch2_bio_bounce(c, bio, start, rw); if (bv.bv_len < iter.bi_size && bv.bv_offset + bv.bv_len < PAGE_SIZE) - return bio_bounce(c, bio, start, rw); + return bch2_bio_bounce(c, bio, start, rw); nr_pages++; } @@ -214,10 +204,10 @@ static struct bbuf __bio_map_or_bounce(struct bch_fs *c, struct bio *bio, struct page *stack_pages[16]; struct page **pages = nr_pages > ARRAY_SIZE(stack_pages) - ? kmalloc_array(nr_pages, sizeof(struct page *), GFP_NOFS) + ? kmalloc_array(nr_pages, sizeof(struct page *), GFP_NOIO) : stack_pages; if (!pages) - return bio_bounce(c, bio, start, rw); + return bch2_bio_bounce(c, bio, start, rw); nr_pages = 0; __bio_for_each_segment(bv, bio, iter, start) @@ -236,12 +226,12 @@ static struct bbuf __bio_map_or_bounce(struct bch_fs *c, struct bio *bio, }; #endif /* __KERNEL__ */ - return bio_bounce(c, bio, start, rw); + return bch2_bio_bounce(c, bio, start, rw); } -static struct bbuf bio_map_or_bounce(struct bch_fs *c, struct bio *bio, int rw) +struct bbuf bch2_bio_map_or_bounce(struct bch_fs *c, struct bio *bio, int rw) { - return __bio_map_or_bounce(c, bio, bio->bi_iter, rw); + return __bch2_bio_map_or_bounce(c, bio, bio->bi_iter, rw); } static inline void zlib_set_workspace(z_stream *strm, void *workspace) @@ -251,7 +241,7 @@ static inline void zlib_set_workspace(z_stream *strm, void *workspace) #endif } -static int buf_uncompress(struct bch_fs *c, +int bch2_buf_uncompress(struct bch_fs *c, void *dst, void *src, struct bch_extent_crc_unpacked crc) { @@ -274,7 +264,9 @@ static int buf_uncompress(struct bch_fs *c, case BCH_COMPRESSION_TYPE_lz4: { int ret = LZ4_decompress_safe_partial(src, dst, src_len, dst_len, dst_len); if (ret != dst_len) - return bch_err_throw(c, decompress_lz4); + return crc.compression_type == BCH_COMPRESSION_TYPE_lz4_old + ? bch_err_throw(c, decompress_lz4_old) + : bch_err_throw(c, decompress_lz4); break; } case BCH_COMPRESSION_TYPE_gzip: { @@ -285,7 +277,7 @@ static int buf_uncompress(struct bch_fs *c, .avail_out = dst_len, }; - void *workspace = mempool_alloc(workspace_pool, GFP_NOFS); + void *workspace = mempool_alloc(workspace_pool, GFP_NOIO); zlib_set_workspace(&strm, workspace); zlib_inflateInit2(&strm, -MAX_WBITS); @@ -306,7 +298,7 @@ static int buf_uncompress(struct bch_fs *c, if (real_src_len > src_len - 4) return bch_err_throw(c, decompress_zstd_src_len_bad); - void *workspace = mempool_alloc(workspace_pool, GFP_NOFS); + void *workspace = mempool_alloc(workspace_pool, GFP_NOIO); ctx = zstd_init_dctx(workspace, zstd_dctx_workspace_bound()); size_t ret = zstd_decompress_dctx(ctx, @@ -332,53 +324,25 @@ static int buf_uncompress(struct bch_fs *c, return 0; } -int bch2_bio_uncompress_inplace(struct bch_write_op *op, - struct bio *bio) +/* + * Every failed decompression attempt gets counted, from the read path and + * from the write path both - the move path decompresses when it can't + * write the extent through as-is, and that's where a filesystem full of + * unmovable compressed extents shows itself. Which compression type + * failed, and for zstd why, is the first thing such a report has to + * answer. + * + * Not under no_data_io, where decompressing whatever was in the buffer is + * expected to fail and says nothing about the filesystem. + */ +int bch2_decompress_err(struct bch_fs *c, int ret) { - struct bch_fs *c = op->c; - struct bch_extent_crc_unpacked *crc = &op->crc; - size_t dst_len = crc->uncompressed_size << 9; - - /* bio must own its pages: */ - BUG_ON(!bio->bi_vcnt); - BUG_ON(DIV_ROUND_UP(crc->live_size, PAGE_SECTORS) > bio->bi_max_vecs); - BUG_ON(bio->bi_iter.bi_size != crc->compressed_size << 9); - - if (crc->uncompressed_size << 9 > c->opts.encoded_extent_max) { - bch2_write_op_error(op, false, op->pos.offset, - "extent too big to decompress (%u > %u)", - crc->uncompressed_size << 9, c->opts.encoded_extent_max); - return bch_err_throw(c, decompress_exceeded_max_encoded_extent); - } - - struct bbuf dst_buf __cleanup(bbuf_exit) = __bounce_alloc(c, dst_len, WRITE); - struct bbuf src_buf __cleanup(bbuf_exit) = bio_map_or_bounce(c, bio, READ); - - int ret = buf_uncompress(c, dst_buf.b, src_buf.b, *crc); - if (c->opts.no_data_io) - ret = 0; - if (ret) { - bch2_write_op_error(op, false, op->pos.offset, "%s", bch2_err_str(ret)); - return ret; - } - - /* - * XXX: don't have a good way to assert that the bio was allocated with - * enough space, we depend on bch2_move_extent doing the right thing - */ - bio->bi_iter.bi_size = crc->live_size << 9; - - memcpy_to_bio(bio, bio->bi_iter, dst_buf.b + (crc->offset << 9)); - - crc->csum_type = 0; - crc->compression_type = 0; - crc->compressed_size = crc->live_size; - crc->uncompressed_size = crc->live_size; - crc->offset = 0; - crc->csum = (struct bch_csum) { 0, 0 }; - return 0; + if (ret && !c->opts.no_data_io) + bch2_sb_error_count(c, bch2_decompress_sb_err(ret)); + return ret; } + int bch2_bio_uncompress(struct bch_fs *c, struct bio *src, struct bio *dst, struct bvec_iter dst_iter, struct bch_extent_crc_unpacked crc) @@ -390,14 +354,14 @@ int bch2_bio_uncompress(struct bch_fs *c, struct bio *src, if (crc.uncompressed_size << 9 > c->opts.encoded_extent_max || crc.compressed_size << 9 > c->opts.encoded_extent_max) - return bch_err_throw(c, decompress_exceeded_max_encoded_extent); + return bch2_decompress_err(c, bch_err_throw(c, decompress_exceeded_max_encoded_extent)); - struct bbuf dst_buf __cleanup(bbuf_exit) = dst_len == dst_iter.bi_size - ? __bio_map_or_bounce(c, dst, dst_iter, WRITE) - : __bounce_alloc(c, dst_len, WRITE); - struct bbuf src_buf __cleanup(bbuf_exit) = bio_map_or_bounce(c, src, READ); + struct bbuf dst_buf __cleanup(bch2_bbuf_exit) = dst_len == dst_iter.bi_size + ? __bch2_bio_map_or_bounce(c, dst, dst_iter, WRITE) + : bch2_bounce_alloc(c, dst_len, WRITE); + struct bbuf src_buf __cleanup(bch2_bbuf_exit) = bch2_bio_map_or_bounce(c, src, READ); - try(buf_uncompress(c, dst_buf.b, src_buf.b, crc)); + try(bch2_decompress_err(c, bch2_buf_uncompress(c, dst_buf.b, src_buf.b, crc))); if (dst_buf.type != BB_none && dst_buf.type != BB_vmap) @@ -541,7 +505,7 @@ static unsigned bch2_compress(struct bch_fs *c, } } - void *workspace = mempool_alloc(workspace_pool, GFP_NOFS); + void *workspace = mempool_alloc(workspace_pool, GFP_NOIO); /* * XXX: this algorithm sucks when the compression code doesn't tell us @@ -602,8 +566,8 @@ static unsigned bch2_compress(struct bch_fs *c, .compression_type = compression_type, }; - struct bbuf verify __cleanup(bbuf_exit) = __bounce_alloc(c, *src_len, WRITE); - ret = buf_uncompress(c, verify.b, dst, crc); + struct bbuf verify __cleanup(bch2_bbuf_exit) = bch2_bounce_alloc(c, *src_len, WRITE); + ret = bch2_buf_uncompress(c, verify.b, dst, crc); BUG_ON(ret); if (memcmp(verify.b, src, *src_len)) { @@ -643,10 +607,10 @@ unsigned bch2_bio_compress(struct bch_fs *c, *src_len = src->bi_iter.bi_size; *dst_len = dst->bi_iter.bi_size; - struct bbuf dst_data __cleanup(bbuf_exit) = bio_map_or_bounce(c, dst, WRITE); - struct bbuf src_data __cleanup(bbuf_exit) = bounce_source - ? bio_bounce(c, src, src->bi_iter, READ) - : bio_map_or_bounce(c, src, READ); + struct bbuf dst_data __cleanup(bch2_bbuf_exit) = bch2_bio_map_or_bounce(c, dst, WRITE); + struct bbuf src_data __cleanup(bch2_bbuf_exit) = bounce_source + ? bch2_bio_bounce(c, src, src->bi_iter, READ) + : bch2_bio_map_or_bounce(c, src, READ); unsigned compression_type = bch2_compress(c, @@ -687,8 +651,7 @@ static int __bch2_check_set_has_compressed_data(struct bch_fs *c, u64 f) if ((c->sb.features & f) == f) return 0; - guard(memalloc_flags)(PF_MEMALLOC_NOFS); - guard(mutex)(&c->sb_lock); + guard(mutex_noio)(&c->sb_lock); if ((c->sb.features & f) == f) return 0; diff --git a/fs/data/compress.h b/fs/data/compress.h index 60846500ef..56d359a8ea 100644 --- a/fs/data/compress.h +++ b/fs/data/compress.h @@ -33,8 +33,31 @@ static inline enum bch_compression_type bch2_compression_opt_to_type(unsigned v) return __bch2_compression_opt_to_type[((union bch_compression_opt){ .value = v }).type]; } -struct bch_write_op; -int bch2_bio_uncompress_inplace(struct bch_write_op *, struct bio *); +/* + * Bounce buffer for the encode/decode paths: either a direct mapping of a + * bio's pages (BB_none/BB_vmap - no copy) or a private allocation the caller + * can scribble on without touching the bio. Exported because the write path + * assembles its own decode sequence out of these. + */ +struct bbuf { + struct bch_fs *c; + void *b; + enum bbuf_type { + BB_none, + BB_vmap, + BB_kmalloc, + BB_mempool, + } type; + int rw; +}; + +void bch2_bbuf_exit(struct bbuf *); +struct bbuf bch2_bounce_alloc(struct bch_fs *, unsigned, int); +struct bbuf bch2_bio_bounce(struct bch_fs *, struct bio *, struct bvec_iter, int); +struct bbuf bch2_bio_map_or_bounce(struct bch_fs *, struct bio *, int); +int bch2_buf_uncompress(struct bch_fs *, void *, void *, struct bch_extent_crc_unpacked); +int bch2_decompress_err(struct bch_fs *, int); + int bch2_bio_uncompress(struct bch_fs *, struct bio *, struct bio *, struct bvec_iter, struct bch_extent_crc_unpacked); diff --git a/fs/data/copygc.c b/fs/data/copygc.c index 5993cffcfa..67305b08d3 100644 --- a/fs/data/copygc.c +++ b/fs/data/copygc.c @@ -246,7 +246,7 @@ static int copygc_dev_list(struct bch_fs *c, darray_copygc_dev *devs, u64 *wait) try(darray_make_room(devs, c->sb.nr_devices)); - scoped_guard(percpu_read, &c->capacity.mark_lock) + scoped_guard(percpu_read_noio, &c->capacity.mark_lock) scoped_guard(rcu) for_each_rw_member_rcu(c, ca) { s64 v = bch2_copygc_dev_wait_amount(ca); @@ -302,7 +302,7 @@ static int copygc_dev_get_bucket(struct moving_context *ctxt, */ static bool copygc_dev_still_needed(struct bch_fs *c, struct copygc_dev *d) { - guard(percpu_read)(&c->capacity.mark_lock); + guard(percpu_read_noio)(&c->capacity.mark_lock); guard(rcu)(); struct bch_dev *ca = bch2_dev_rcu_noerror(c, d->dev); @@ -516,6 +516,10 @@ static int bch2_copygc(struct moving_context *ctxt, if (bch2_err_matches(ret, ENOENT)) ret = 0; + /* we're being stopped - normal, not something to report: */ + if (bch2_err_matches(ret, BCH_ERR_kthread_cancelled)) + ret = 0; + if (ret < 0 && !bch2_err_matches(ret, EROFS)) bch_err_msg(c, ret, "from bch2_move_data()"); @@ -567,6 +571,10 @@ bool bch2_copygc_can_make_progress(struct bch_dev *ca) * Caller must hold mark_lock (read), for the dev_leaving accounting read - * and must take it outside any rcu read section, mark_lock can block. * + * Free buckets in the shrink tail aren't allocatable + * and don't count, and while a shrink is in progress the device counts as + * target-sized. + * * The allowance at the limit - when the device is full - is the space we * reserved in bch2_recalc_capacity; we can't have more than that amount of * disk space stranded due to fragmentation and store everything we have @@ -596,9 +604,18 @@ s64 bch2_copygc_dev_wait_amount(struct bch_dev *ca) bch2_accounting_mem_read_locked(c, disk_accounting_pos_to_bpos(&pos), &leaving, 1); leaving = max(0LL, leaving); + /* + * Free buckets in the shrink tail aren't allocatable + */ + u64 free_buckets = usage.buckets[BCH_DATA_free]; + u64 nbuckets = bch2_dev_resize_target(ca); + u64 tail_free = atomic64_read(&ca->shrinking_tail_free); + if (unlikely(tail_free)) + free_buckets -= min(free_buckets, tail_free); + /* Don't start until less than 20% of the device is free: */ - s64 free = usage.buckets[BCH_DATA_free] * ca->mi.bucket_size + leaving; - s64 wait = free * 5 - ca->mi.nbuckets * ca->mi.bucket_size; + s64 free = free_buckets * ca->mi.bucket_size + leaving; + s64 wait = free * 5 - nbuckets * ca->mi.bucket_size; if (wait > 0) return wait; @@ -636,7 +653,7 @@ __cold void bch2_copygc_wait_to_text(struct printbuf *out, struct bch_fs *c) bch2_printbuf_make_room(out, 4096); struct task_struct *t; - scoped_guard(percpu_read, &c->capacity.mark_lock) + scoped_guard(percpu_read_noio, &c->capacity.mark_lock) scoped_guard(rcu) { guard(printbuf_atomic)(out); prt_printf(out, "Currently calculated wait:\n"); diff --git a/fs/data/ec/create.c b/fs/data/ec/create.c index 2d68741ca0..eea957386e 100644 --- a/fs/data/ec/create.c +++ b/fs/data/ec/create.c @@ -295,13 +295,19 @@ static int stripe_update_extent(struct btree_trans *trans, if (p.ec.idx == new_stripe->k.p.offset) return 0; - if (old_stripe == new_stripe || - p.ec.idx != old_stripe->k.p.offset) { - CLASS(printbuf, buf)(); - ret_log_fsck_err(trans, stripe_update_stale_stripe_ptr, - "dropping stale stripe pointer (idx %llu) while updating extent\n%s", - (u64) p.ec.idx, - (bch2_bkey_val_to_text(&buf, c, k), buf.buf)); + if (p.ec.idx != old_stripe->k.p.offset) { + /* + * The extent references a stripe that no longer owns this block. + * Let the migration below handle it, and just log it as an fsck + * error for check_allocations to verify. + */ + CLASS(bch_log_msg_ratelimited, msg)(c); + prt_printf(&msg.m, "dropping stale stripe pointer (idx %llu) while updating extent\n", + (u64) p.ec.idx); + bch2_bkey_val_to_text(&msg.m, c, k); + prt_newline(&msg.m); + + bch2_count_fsck_err(c, stripe_update_stale_stripe_ptr, &msg.m); } } @@ -436,6 +442,56 @@ static int stripe_update_bucket(struct btree_trans *trans, stats.nr_done, stats.sectors_done); })); + /* + * count deltas are unreliable under concurrency, leading to phantom counts + * that are never drained. No extent references (old_stripe, old_blocknr) + * any more, so just zero the count. + * + * Safe because the scan covers the whole bucket, and an extent referencing + * the old stripe block always has a backpointer in this bucket, and will + * thus be removed. + * + * TODO: a cleaner / possibly more robust solution would be solving the + * concurrency unrealiability directly + */ + if (old_stripe != new_stripe) { + lockrestart_do(trans, ({ + struct bkey_i_stripe *s = bch2_bkey_get_mut_typed(trans, + BTREE_ID_stripes, POS(0, old_stripe->k.p.offset), + BTREE_ITER_cached, stripe); + int ret = PTR_ERR_OR_ZERO(s); + + if (ret) { + if (bch2_err_matches(ret, ENOENT)) + ret = 0; /* stripe already deleted */ + } else { + stripe_blockcount_set(&s->v, old_blocknr, 0); + ret = bch2_trans_commit(trans, NULL, NULL, BCH_TRANS_COMMIT_no_enospc); + } + ret; + })); + + /* + * The block count also has the same concurrency / key-cached RMW unreliability, + * so set it manually here as well. + */ + lockrestart_do(trans, ({ + struct bkey_i_stripe *s = bch2_bkey_get_mut_typed(trans, + BTREE_ID_stripes, POS(0, new_stripe->k.p.offset), + BTREE_ITER_cached, stripe); + int ret = PTR_ERR_OR_ZERO(s); + + if (ret) { + if (bch2_err_matches(ret, ENOENT)) + ret = 0; /* stripe already deleted - nothing to fix */ + } else { + stripe_blockcount_set(&s->v, new_blocknr, stats.sectors_done); + ret = bch2_trans_commit(trans, NULL, NULL, BCH_TRANS_COMMIT_no_enospc); + } + ret; + })); + } + return 0; } @@ -543,9 +599,22 @@ static void zero_out_rest_of_ec_bucket(struct bch_fs *c, void bch2_ec_stripe_new_free(struct bch_fs *c, struct ec_stripe_new *s) { + bool had_old_stripe = s->old_stripe_handle.idx != 0; + bch2_stripe_new_buckets_del(c, s); bch2_stripe_handle_put(c, &s->new_stripe_handle); bch2_stripe_handle_put(c, &s->old_stripe_handle); + + /* + * If this create had an old stripe, it may have become empty while we + * held it open: the trigger defers the delete to the LRU work, which + * skips open stripes, and nothing re-queues it once we release the + * handle. Re-trigger it now that the stripe is closed so the deferred + * delete actually runs. + */ + if (had_old_stripe) + bch2_do_stripe_deletes(c); + kfree(s); } @@ -850,15 +919,26 @@ unsigned bch2_disk_label_ec_devs(struct bch_fs *c, unsigned disk_label, /* * Can a stripe with @redundancy parity blocks be formed in @target right now? * - * Minimum stripe size is redundancy + 1 (one data block + parity), and all - * blocks in a stripe must share a single bucket_size. So we need at least - * redundancy + 1 RW devices in the target that agree on bucket_size. + * This must model what ec_stripe_head_devs_update() computes as + * insufficient_devs, because that is what actually refuses to allocate. Both + * of its conditions apply: + * + * - at least redundancy + 2 devices agreeing on bucket_size. Not + 1: a + * stripe of one data block plus parity is strictly worse than replication, + * so that case is rejected rather than formed. + * - at least redundancy + 2 distinct failure domains. One block per domain is + * a hard requirement for erasure coding, not a preference - the allocator + * excludes devices sharing an already-placed block's domain. With no + * failure domains configured every device is its own domain and this is + * the device count again, so it only bites where devices share one. * * bch2_disk_label_ec_devs already returns the filtered device mask (RW members * with durability > 0, narrowed to the picked best bucket_size). * * Used by reconcile to avoid queueing EC work that can't make progress — - * otherwise reconcile spins re-queueing data_update_fail forever. + * otherwise reconcile spins re-queueing data_update_fail forever. Modelling + * only the device count let configurations through that the allocator then + * refused, costing one wasted rewrite of every affected extent. */ bool bch2_can_form_ec_stripe(struct bch_fs *c, unsigned target, unsigned redundancy) { @@ -866,14 +946,26 @@ bool bch2_can_form_ec_stripe(struct bch_fs *c, unsigned target, unsigned redunda return false; struct target t = target_decode(target); - unsigned disk_label = t.type == TARGET_GROUP && t.group <= U8_MAX + + /* + * A group above U8_MAX cannot be a disk label, and __ec_stripe_head_get() + * refuses it outright ("cannot create a stripe when disk_label > U8_MAX"). + * Folding it to disk_label 0 here would ask about every device in the + * filesystem and answer yes to a target the allocator will not serve -- + * the same shape of mismatch this function is being fixed for. + */ + if (t.type == TARGET_GROUP && t.group > U8_MAX) + return false; + + unsigned disk_label = t.type == TARGET_GROUP ? t.group + 1 : 0; struct bch_devs_mask devs; bch2_disk_label_ec_devs(c, disk_label, &devs, 0); - return dev_mask_nr(&devs) >= redundancy + 1; + return dev_mask_nr(&devs) >= redundancy + 2 && + bch2_target_nr_domains(c, &devs) >= redundancy + 2; } /* @@ -1051,6 +1143,20 @@ static int __new_stripe_alloc_buckets(struct btree_trans *trans, unsigned i, j, nr_have_parity = 0, nr_have_data = 0; req->new_stripe_alloc = true; + /* + * For erasure coding, distinct failure domains are a hard requirement, + * not a preference: the allocator excludes devices sharing an + * already-placed block's domain (see bch2_dev_domain_keys_update()). + */ + req->failure_domains_required = true; + + /* + * Rebuilt below from the current stripe blocks. We may be called twice + * on the same req (full-stripe attempt, then stripe reuse), and the + * released first-attempt buckets must not linger here - a stale bit + * would wrongly exclude that device's whole domain, above. + */ + memset(&req->devs_chosen, 0, sizeof(req->devs_chosen)); /* * We bypass the sector allocator which normally does this: */ bitmap_and(req->devs_may_alloc.d, req->devs_may_alloc.d, @@ -1063,8 +1169,11 @@ static int __new_stripe_alloc_buckets(struct btree_trans *trans, * walk backpointers and update all extents that point to that * block when updating the stripe */ - if (v->ptrs[i].dev != BCH_SB_MEMBER_INVALID) + if (v->ptrs[i].dev != BCH_SB_MEMBER_INVALID) { __clear_bit(v->ptrs[i].dev, req->devs_may_alloc.d); + /* spread new blocks away from existing blocks' domains: */ + __set_bit(v->ptrs[i].dev, req->devs_chosen.d); + } if (i < nr_data) nr_have_data++; @@ -1257,7 +1366,7 @@ static int stripe_reallocate_outliers(struct btree_trans *trans, static bool copygc_can_run_on_devs(struct bch_fs *c, struct bch_devs_mask *devs) { - guard(percpu_read)(&c->capacity.mark_lock); + guard(percpu_read_noio)(&c->capacity.mark_lock); guard(rcu)(); for_each_member_device_rcu(c, ca, devs) if (bch2_copygc_dev_wait_amount(ca) <= 0) @@ -1413,13 +1522,17 @@ static bool may_reuse_stripe(struct bch_fs *c, old->nr_redundant != new->new_stripe.key.v.nr_redundant) return false; + for (unsigned i = 0; i < old->nr_blocks; i++) + if (bch2_ptr_bad_or_evacuating(c, &old->ptrs[i])) + return false; + struct bch_devs_mask devs_may_alloc = new->devs; unsigned nr_data = old->nr_blocks - old->nr_redundant; unsigned live_data = 0; for_each_data_block(i, nr_data) if (stripe_blockcount_get(old, i)) { - if (!bch2_dev_bad_or_evacuating(c, old->ptrs[i].dev)) + if (!bch2_ptr_bad_or_evacuating(c, &old->ptrs[i])) __clear_bit(old->ptrs[i].dev, devs_may_alloc.d); live_data++; } @@ -1523,7 +1636,7 @@ static void init_new_stripe_from_old(struct bch_fs *c, struct ec_stripe_new *s, for_each_data_block(i, old_nr_data) { if (stripe_blockcount_get(old_v, i)) { - if (!bch2_dev_bad_or_evacuating(c, old_v->ptrs[i].dev)) + if (!bch2_ptr_bad_or_evacuating(c, &old_v->ptrs[i])) __set_bit(s->old_blocks_nr, s->blocks_gotten); else __set_bit(s->old_blocks_nr, s->blocks_moving); @@ -1531,6 +1644,14 @@ static void init_new_stripe_from_old(struct bch_fs *c, struct ec_stripe_new *s, new_v->ptrs[s->old_blocks_nr] = old_v->ptrs[i]; + /* + * Per-extent key-cache RMW deltas aren't reliable under + * concurrency, so just set the new stripe's blockcount to + * the old stripe's value directly. + */ + stripe_blockcount_set(new_v, s->old_blocks_nr, + stripe_blockcount_get(old_v, i)); + s->old_block_map[s->old_blocks_nr++] = i; BUG_ON(s->old_blocks_nr + !repair > new_nr_data); } @@ -1769,6 +1890,16 @@ static void ec_stripe_head_devs_update(struct bch_fs *c, struct ec_stripe_head * */ h->insufficient_devs = h->nr_active_devs < h->redundancy + 2; + /* + * One block per failure domain is a hard requirement (see + * __new_stripe_alloc_buckets): too few domains for redundancy to mean + * anything means no stripes at all. With no failure domains configured + * each device is its own domain, so this only tightens the device-count + * check above when devices share domains. + */ + unsigned nr_domains = bch2_target_nr_domains(c, &h->devs); + h->insufficient_devs |= nr_domains < h->redundancy + 2; + struct bch_devs_mask devs_leaving; bitmap_andnot(devs_leaving.d, old_devs.d, h->devs.d, BCH_SB_MEMBERS_MAX); @@ -1895,6 +2026,17 @@ struct ec_stripe_head *bch2_ec_stripe_head_get(struct btree_trans *trans, unsigned nr_data = min_t(unsigned, active - h->redundancy, req->ec_max_data_blocks ?: ~0U); + /* + * One block per failure domain: the stripe can't be wider than + * the domains available. If a domain becomes unavailable, the + * next stripe is allocated narrower rather than doubling up. + * With no failure domains each device is its own domain, so this + * is the usual device-count cap. + */ + unsigned nr_domains = bch2_target_nr_domains(c, &h->devs); + /* insufficient_devs was checked - at least redundancy + 2 domains: */ + nr_data = min(nr_data, nr_domains - h->redundancy); + h->s = ec_new_stripe_alloc(c, h->devs, h->watermark, @@ -1983,7 +2125,7 @@ struct ec_stripe_head *bch2_ec_stripe_head_get(struct btree_trans *trans, static bool stripe_degraded(struct bch_fs *c, const struct bch_stripe *s) { for (unsigned i = 0; i < s->nr_blocks; i++) - if (bch2_dev_bad_or_evacuating(c, s->ptrs[i].dev)) + if (bch2_ptr_bad_or_evacuating(c, &s->ptrs[i])) return true; return false; } @@ -2015,8 +2157,21 @@ int bch2_stripe_repair(struct moving_context *ctxt, for_each_data_block(i, nr_data) nr_live_data_blocks += stripe_blockcount_get(old_s, i) != 0; - if (!nr_live_data_blocks) + if (!nr_live_data_blocks) { + /* + * Nothing to repair - the stripe is empty, so it should just be + * deleted. Clear needs_reconcile so reconcile stops re-queueing this work. + */ + if (old_s->needs_reconcile) { + struct bkey_i_stripe *n = + errptr_try(bch2_bkey_make_mut_typed(trans, iter, &s.s_c, 0, stripe)); + n->v.needs_reconcile = 0; + + try(bch2_trans_commit(trans, NULL, NULL, BCH_TRANS_COMMIT_no_enospc)); + } + return 0; + } struct bch_devs_mask devs; bch2_disk_label_ec_devs(c, old_s->disk_label, &devs, le16_to_cpu(old_s->sectors)); diff --git a/fs/data/ec/init.c b/fs/data/ec/init.c index 9234998267..5d783e9602 100644 --- a/fs/data/ec/init.c +++ b/fs/data/ec/init.c @@ -169,7 +169,7 @@ int bch2_dev_remove_stripes(struct bch_fs *c, unsigned dev_idx, /* startup/shutdown */ -static bool should_cancel_stripe(struct bch_fs *c, struct ec_stripe_new *s, struct bch_dev *ca) +static bool should_cancel_stripe(struct bch_fs *c, struct ec_stripe_new *s, struct bch_dev *ca, u64 tail_cutoff) { if (!ca) return true; @@ -177,10 +177,10 @@ static bool should_cancel_stripe(struct bch_fs *c, struct ec_stripe_new *s, stru struct bch_stripe *v = &s->new_stripe.key.v; for (unsigned i = 0; i < v->nr_blocks; i++) { - /* Freshly allocated block - check the open_bucket's device: */ + /* Freshly allocated block - check the open_bucket's device and region: */ if (s->blocks[i]) { struct open_bucket *ob = c->allocator.open_buckets + s->blocks[i]; - if (ob->dev == ca->dev_idx) + if (dev_and_region_matches(ob, ca, tail_cutoff)) return true; } @@ -195,29 +195,38 @@ static bool should_cancel_stripe(struct bch_fs *c, struct ec_stripe_new *s, stru return true; } + if (s->have_old_stripe && + stripe_dev_and_region_matches(c, ca, &s->old_stripe.key.v, tail_cutoff)) + return true; + return false; } -static void __bch2_ec_stop(struct bch_fs *c, struct bch_dev *ca) +static void __bch2_ec_stop(struct bch_fs *c, struct bch_dev *ca, u64 tail_cutoff) { struct ec_stripe_head *h; guard(mutex)(&c->ec.stripe_head_lock); list_for_each_entry(h, &c->ec.stripe_head_list, list) { guard(mutex)(&h->lock); - if (h->s && should_cancel_stripe(c, h->s, ca)) + if (h->s && should_cancel_stripe(c, h->s, ca, tail_cutoff)) bch2_ec_stripe_new_cancel(c, h, -BCH_ERR_erofs_no_writes); } } +void bch2_ec_stop_dev_cutoff(struct bch_fs *c, struct bch_dev *ca, u64 tail_cutoff) +{ + __bch2_ec_stop(c, ca, tail_cutoff); +} + void bch2_ec_stop_dev(struct bch_fs *c, struct bch_dev *ca) { - __bch2_ec_stop(c, ca); + __bch2_ec_stop(c, ca, 0); } void bch2_fs_ec_stop(struct bch_fs *c) { - __bch2_ec_stop(c, NULL); + __bch2_ec_stop(c, NULL, 0); } static bool bch2_fs_ec_flush_done(struct bch_fs *c) diff --git a/fs/data/ec/init.h b/fs/data/ec/init.h index 0e7c3ba000..d2bf3f4687 100644 --- a/fs/data/ec/init.h +++ b/fs/data/ec/init.h @@ -7,6 +7,7 @@ int bch2_invalidate_stripe_to_dev(struct btree_trans *, struct btree_iter *, unsigned, struct printbuf *, bool *); int bch2_dev_remove_stripes(struct bch_fs *, unsigned, unsigned, struct printbuf *); +void bch2_ec_stop_dev_cutoff(struct bch_fs *, struct bch_dev *, u64); void bch2_ec_stop_dev(struct bch_fs *, struct bch_dev *); void bch2_fs_ec_stop(struct bch_fs *); void bch2_fs_ec_flush(struct bch_fs *); @@ -23,4 +24,3 @@ int bch2_bucket_nr_stripes(struct btree_trans *, struct bpos); int bch2_check_stripe_refs(struct btree_trans *); #endif /* _BCACHEFS_DATA_EC_INIT_H */ - diff --git a/fs/data/ec/io.c b/fs/data/ec/io.c index 3ea190e7d5..63968304f8 100644 --- a/fs/data/ec/io.c +++ b/fs/data/ec/io.c @@ -586,9 +586,9 @@ int bch2_ec_read_extent(struct btree_trans *trans, struct bch_read_bio *rbio, * and a live stripe key referencing a stale-gen bucket is an * allocator inconsistency regardless of whether the stripe is pinned * - hence no is_open gating here, unlike the validate-time check. - * Lock-currency is the liveness witness at this site; the pin is the - * witness post-IO in bch2_stripe_buf_validate(), where the key may - * have been legitimately deleted while the IO was in flight. + * Here the btree lock is what proves the key is live; post-IO, in + * bch2_stripe_buf_validate(), the pin is, because the key may have + * been legitimately deleted while the IO was in flight. */ bool have_stale = false; scoped_guard(rcu) { diff --git a/fs/data/extents.c b/fs/data/extents.c index 5be4416057..4f9baf5ff0 100644 --- a/fs/data/extents.c +++ b/fs/data/extents.c @@ -728,60 +728,6 @@ void bch2_extent_crc_append(const struct bch_fs *c, /* Generic code for keys with pointers: */ -unsigned bch2_bkey_nr_dirty_ptrs(const struct bch_fs *c, struct bkey_s_c k) -{ - struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k); - unsigned ret = 0; - - bkey_for_each_ptr(ptrs, ptr) - ret += !ptr->cached && ptr->dev != BCH_SB_MEMBER_INVALID; - return ret; -} - -unsigned bch2_bkey_nr_ptrs_allocated(const struct bch_fs *c, struct bkey_s_c k) -{ - if (k.k->type == KEY_TYPE_reservation) { - return bkey_s_c_to_reservation(k).v->nr_replicas; - } else { - unsigned ret = 0; - struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k); - - bkey_for_each_ptr(ptrs, ptr) - ret += !ptr->cached; - return ret; - } -} - -unsigned bch2_bkey_nr_ptrs_fully_allocated(const struct bch_fs *c, struct bkey_s_c k) -{ - if (k.k->type == KEY_TYPE_reservation) { - return bkey_s_c_to_reservation(k).v->nr_replicas; - } else { - struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k); - const union bch_extent_entry *entry; - struct extent_ptr_decoded p; - unsigned ret = 0; - - bkey_for_each_ptr_decode(k.k, ptrs, p, entry) - ret += !p.ptr.cached && !crc_is_compressed(p.crc); - return ret; - } -} - -unsigned bch2_bkey_sectors_compressed(const struct bch_fs *c, struct bkey_s_c k) -{ - struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k); - const union bch_extent_entry *entry; - struct extent_ptr_decoded p; - unsigned ret = 0; - - bkey_for_each_ptr_decode(k.k, ptrs, p, entry) - if (!p.ptr.cached && crc_is_compressed(p.crc)) - ret += p.crc.compressed_size; - - return ret; -} - bool bch2_bkey_is_incompressible(const struct bch_fs *c, struct bkey_s_c k) { struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k); @@ -827,26 +773,6 @@ void bch2_bkey_propagate_incompressible(const struct bch_fs *c, struct bkey_i *d } } -unsigned bch2_bkey_replicas(struct bch_fs *c, struct bkey_s_c k) -{ - struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k); - const union bch_extent_entry *entry; - struct extent_ptr_decoded p = { 0 }; - unsigned replicas = 0; - - bkey_for_each_ptr_decode(k.k, ptrs, p, entry) { - if (p.ptr.cached) - continue; - - if (p.has_ec) - replicas += p.ec.redundancy; - - replicas++; - - } - - return replicas; -} unsigned bch2_dev_durability(struct bch_fs *c, unsigned dev) { @@ -1026,6 +952,35 @@ int __bch2_extent_ptr_durability(struct btree_trans *trans, struct extent_ptr_de return ret ?: (int) (desired ? desired_total : d.total); } +/* + * A reservation is space promised but not yet written: it has no pointers, so + * the walk below would report nothing at all. What it does have is a replica + * count, and that is the answer to every question this struct is asked about + * how much space the key accounts for - so report it as the durability. + * + * online == total because nothing about a reservation depends on which devices + * are up; it is a claim against the filesystem's free space, not data sitting + * somewhere. nr_ptrs stays 0, which is the truth and what the pointer walk + * would have said. + */ +static bool bkey_reservation_durability(struct bkey_s_c k, struct bkey_durability *ret) +{ + if (k.k->type != KEY_TYPE_reservation) + return false; + + u8 nr_replicas = bkey_s_c_to_reservation(k).v->nr_replicas; + + *ret = (struct bkey_durability) { + .online = nr_replicas, + .total = nr_replicas, + .nr_overwritable = nr_replicas, + .nr_replicas = nr_replicas, + .replicas = nr_replicas, + .min_durability = U8_MAX, + }; + return true; +} + int bch2_bkey_durability(struct btree_trans *trans, struct bkey_s_c k, struct bkey_durability *ret) { struct bch_fs *c = trans->c; @@ -1034,12 +989,22 @@ int bch2_bkey_durability(struct btree_trans *trans, struct bkey_s_c k, struct bk struct extent_ptr_decoded p; struct durability_dedup seen = {}; - *ret = (struct bkey_durability) { .min_durability = INT_MAX }; + if (bkey_reservation_durability(k, ret)) + return 0; + + *ret = (struct bkey_durability) { .min_durability = U8_MAX }; bkey_for_each_ptr_decode(k.k, ptrs, p, entry) { if (p.ptr.cached) continue; + ret->nr_ptrs += p.ptr.dev != BCH_SB_MEMBER_INVALID; + ret->nr_replicas += p.ptr.dev != BCH_SB_MEMBER_INVALID; + ret->replicas += 1 + (p.has_ec ? p.ec.redundancy : 0); + ret->nr_overwritable += !crc_is_compressed(p.crc); + if (crc_is_compressed(p.crc)) + ret->sectors_compressed += p.crc.compressed_size; + unsigned desired = 0; if (p.has_ec) { @@ -1073,7 +1038,7 @@ int bch2_bkey_durability(struct btree_trans *trans, struct bkey_s_c k, struct bk * evacuating device reads as durability 0 for the minimum. */ ret->acct += desired; - unsigned d_min = !p.has_ec && bch2_dev_bad_or_evacuating(c, p.ptr.dev) + unsigned d_min = !p.has_ec && bch2_ptr_bad_or_evacuating(c, &p.ptr) ? 0 : desired; ret->min_durability = min(ret->min_durability, d_min); } @@ -1114,26 +1079,46 @@ bool bch2_bkey_can_read(const struct bch_fs *c, struct bkey_s_c k) return false; } -/* desired durability, no btree lookups for stripes: */ -static unsigned bch2_bkey_durability_safe(struct bch_fs *c, struct bkey_s_c k) +/* + * As bch2_bkey_durability(), but without the btree lookups: an erasure coded + * pointer's durability is taken as redundancy + 1 rather than read from the + * stripe, so this needs no transaction and can't fail. Online vs total isn't + * distinguishable without those lookups, so only @total is filled in. + */ +struct bkey_durability bch2_bkey_durability_safe(const struct bch_fs *c, struct bkey_s_c k) { struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k); const union bch_extent_entry *entry; - struct extent_ptr_decoded p; - unsigned durability = 0; + /* p.ec is only filled in when p.has_ec; zero it so gcc can see that */ + struct extent_ptr_decoded p = { 0 }; + struct bkey_durability ret; + + if (bkey_reservation_durability(k, &ret)) + return ret; + + ret = (struct bkey_durability) { .min_durability = U8_MAX }; guard(rcu)(); - bkey_for_each_ptr_decode(k.k, ptrs, p, entry) - if (p.ptr.cached) { - /* nothing */ - } else if (p.has_ec) { - durability += p.ec.redundancy + 1; - } else { + bkey_for_each_ptr_decode(k.k, ptrs, p, entry) { + if (p.ptr.cached) + continue; + + ret.nr_ptrs += p.ptr.dev != BCH_SB_MEMBER_INVALID; + ret.nr_replicas += p.ptr.dev != BCH_SB_MEMBER_INVALID; + ret.replicas += 1 + (p.has_ec ? p.ec.redundancy : 0); + ret.nr_overwritable += !crc_is_compressed(p.crc); + if (crc_is_compressed(p.crc)) + ret.sectors_compressed += p.crc.compressed_size; + + if (p.has_ec) { + ret.total += p.ec.redundancy + 1; + } else if (p.ptr.dev != BCH_SB_MEMBER_INVALID) { struct bch_dev *ca = bch2_dev_rcu_noerror(c, p.ptr.dev); - durability += ca ? ca->mi.durability : 1; + ret.total += ca ? ca->mi.durability : 1; } + } - return durability; + return ret; } void bch2_bkey_extent_entry_drop_s(const struct bch_fs *c, struct bkey_s k, union bch_extent_entry *entry) @@ -1384,12 +1369,12 @@ bool bch2_bkey_in_target(struct bch_fs *c, struct bkey_s_c k, unsigned target) return true; } -bool bch2_bkey_has_dev_bad_or_evacuating(struct bch_fs *c, struct bkey_s_c k) +bool bch2_bkey_has_ptr_bad_or_evacuating(struct bch_fs *c, struct bkey_s_c k) { guard(rcu)(); struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k); bkey_for_each_ptr(ptrs, ptr) - if (bch2_dev_bad_or_evacuating_rcu(c, ptr->dev)) + if (bch2_ptr_bad_or_evacuating_rcu(c, ptr)) return true; return false; } @@ -1534,6 +1519,9 @@ static bool maybe_drop_cached_ptr(struct bch_fs *c, struct bch_inode_opts *opts, return drop_cached_pointer_trace(c, k, ptr, "pointer is stale"); if (!ca || ca->mi.state == BCH_MEMBER_STATE_evacuating) return drop_cached_pointer_trace(c, k, ptr, "device bad or evacuating"); + if (bch2_dev_is_shrinking(ca) && + bch2_dev_resize_target(ca) <= PTR_BUCKET_NR(ca, ptr)) + return drop_cached_pointer_trace(c, k, ptr, "past shrink cutoff"); unsigned target = opts->promote_target ?: opts->foreground_target; if (target && !bch2_dev_in_target_rcu(c, ptr->dev, target)) @@ -1823,7 +1811,7 @@ __cold void bch2_bkey_ptrs_to_text(struct printbuf *out, struct bch_fs *c, return; } - prt_printf(out, "durability: %u ", bch2_bkey_durability_safe(c, k)); + prt_printf(out, "durability: %u ", bch2_bkey_durability_safe(c, k).total); guard(printbuf_atomic)(out); guard(rcu)(); diff --git a/fs/data/extents.h b/fs/data/extents.h index 23861683a3..f2e38ce8a2 100644 --- a/fs/data/extents.h +++ b/fs/data/extents.h @@ -580,14 +580,9 @@ static inline struct bch_devs_list bch2_bkey_devs(const struct bch_fs *c, struct return ret; } -unsigned bch2_bkey_nr_dirty_ptrs(const struct bch_fs *, struct bkey_s_c); -unsigned bch2_bkey_nr_ptrs_allocated(const struct bch_fs *, struct bkey_s_c); -unsigned bch2_bkey_nr_ptrs_fully_allocated(const struct bch_fs *, struct bkey_s_c); bool bch2_bkey_is_incompressible(const struct bch_fs *, struct bkey_s_c); void bch2_bkey_propagate_incompressible(const struct bch_fs *, struct bkey_i *, struct bkey_s_c); -unsigned bch2_bkey_sectors_compressed(const struct bch_fs *, struct bkey_s_c); -unsigned bch2_bkey_replicas(struct bch_fs *, struct bkey_s_c); unsigned bch2_dev_durability(struct bch_fs *, unsigned); @@ -603,12 +598,63 @@ static inline int bch2_extent_ptr_durability(struct btree_trans *trans, struct e return __bch2_extent_ptr_durability(trans, p, false); } +/* + * Everything one walk of a key's pointer list can say about its replication. + * + * Gathered together because the walk is the expensive part - and for the exact + * version, a stripe read per erasure coded pointer - while callers routinely + * want several of these at once. bch2_sum_sector_overwrites() asks four + * separate single-value helpers for them, on the same two keys, three of the + * calls inside a loop. + * + * The durability counts are weighted by each device's mi.durability and skip + * BCH_SB_MEMBER_INVALID placeholders - those are added by + * bch2_bkey_set_needs_reconcile() on a degraded write, to stand for a replica + * that isn't there. The raw counts below are unweighted. + * + * u8 except the sector count: BCH_MEMBER_DURABILITY is a two bit field and + * BCH_REPLICAS_MAX is 4, so none of these can come near 255. + * + * Not handled here: KEY_TYPE_reservation, which several of the older + * single-value helpers report as v->nr_replicas. Callers that need that still + * special-case it themselves. + */ struct bkey_durability { - unsigned online, total; - unsigned acct, min_durability; + u8 online, total; + u8 acct, min_durability; + + u8 nr_ptrs; /* real device pointers */ + u8 nr_overwritable; /* uncompressed - an overwrite reclaims these */ + unsigned sectors_compressed; + + /* + * Copies this key occupies, for disk space accounting. + * + * Deliberately not weighted by mi.durability, unlike the counts above: + * durability is OPT_RUNTIME, and accounting is persistent, so a + * durability change would retroactively invalidate space already + * accounted for. This has to be a function of what is physically on + * disk. + * + * Differs from nr_ptrs only for a reservation, which occupies the space + * it reserved while having no pointers at all. + */ + u8 nr_replicas; + + /* + * Copies for the purpose of "does this write increase replication" - + * erasure coding counts, because a stripe genuinely provides it. + * + * Distinct from nr_replicas on purpose: parity is accounted separately + * as BCH_DATA_parity at the stripe, so counting redundancy in a + * per-extent space figure would charge the same parity to every extent + * sharing the stripe. Space and replication are different questions. + */ + u8 replicas; }; int bch2_bkey_durability(struct btree_trans *, struct bkey_s_c, struct bkey_durability *); +struct bkey_durability bch2_bkey_durability_safe(const struct bch_fs *, struct bkey_s_c); struct bkey_durability bch2_btree_ptr_durability(struct bch_fs *, struct bkey_s_c); bool bch2_bkey_can_read(const struct bch_fs *, struct bkey_s_c); @@ -642,7 +688,7 @@ bool bch2_bkey_devs_rw(struct bch_fs *, struct bkey_s_c); bool bch2_bkey_has_target(struct bch_fs *, struct bkey_s_c, unsigned); bool bch2_bkey_in_target(struct bch_fs *, struct bkey_s_c, unsigned); -bool bch2_bkey_has_dev_bad_or_evacuating(struct bch_fs *, struct bkey_s_c); +bool bch2_bkey_has_ptr_bad_or_evacuating(struct bch_fs *, struct bkey_s_c); void bch2_bkey_extent_entry_drop_s(const struct bch_fs *, struct bkey_s, union bch_extent_entry *); void bch2_bkey_extent_entry_drop(const struct bch_fs *, struct bkey_i *, union bch_extent_entry *); diff --git a/fs/data/extents_sb.c b/fs/data/extents_sb.c index 06a2854ef9..e9c55948f2 100644 --- a/fs/data/extents_sb.c +++ b/fs/data/extents_sb.c @@ -48,7 +48,7 @@ void bch2_sb_extent_type_u64s_to_cpu(struct bch_fs *c) int bch2_sb_extent_type_u64s_from_cpu(struct bch_fs *c) { - lockdep_assert_held(&c->sb_lock); + lockdep_assert_held(&c->sb_lock.lock); struct bch_sb_field_extent_type_u64s *e = bch2_sb_field_get_minsize(&c->disk_sb, extent_type_u64s, diff --git a/fs/data/io_misc.c b/fs/data/io_misc.c index 00ce24e5b3..c88f8f31fc 100644 --- a/fs/data/io_misc.c +++ b/fs/data/io_misc.c @@ -54,7 +54,7 @@ int bch2_extent_fallocate(struct btree_trans *trans, sectors = min_t(u64, sectors, k.k->p.offset - iter->pos.offset); new_replicas = max(0, (int) opts.data_replicas - - (int) bch2_bkey_nr_ptrs_fully_allocated(c, k)); + (int) bch2_bkey_durability_safe(c, k).nr_overwritable); /* * Get a disk reservation before (in the nocow case) calling @@ -150,6 +150,16 @@ int bch2_fpunch_snapshot(struct btree_trans *trans, struct bpos start, struct bp CLASS(disk_reservation, res)(c); unsigned max_sectors = KEY_SIZE_MAX & (~0 << c->block_bits); + /* + * We run our own commit loop, and its leading trans_begin() would + * discard the caller's queued updates — commit them instead: fsck + * callers reach us right after an fsck_err() that queued the journal + * log entry recording the repair, and once we've punched the extents + * the repair won't re-trigger to re-queue it + */ + if (bch2_trans_has_updates(trans)) + try(bch2_trans_commit(trans, NULL, NULL, BCH_TRANS_COMMIT_no_enospc)); + return for_each_btree_key_max_commit(trans, iter, BTREE_ID_extents, start, end, 0, k, &res.r, NULL, BCH_TRANS_COMMIT_no_enospc, ({ @@ -434,7 +444,7 @@ case LOGGED_OP_FINSERT_shift_extents: if (snapshot != k.k->p.snapshot) { ret = bch2_disk_reservation_add(c, &disk_res, copy->k.size * - bch2_bkey_nr_ptrs_allocated(c, bkey_i_to_s_c(copy)), + bch2_bkey_durability_safe(c, bkey_i_to_s_c(copy)).total, 0); if (ret) goto btree_err; @@ -447,7 +457,7 @@ case LOGGED_OP_FINSERT_shift_extents: if (snapshot == k.k->p.snapshot) bch2_disk_reservation_add(c, &disk_res, copy->k.size * - bch2_bkey_nr_ptrs_allocated(c, bkey_i_to_s_c(copy)), + bch2_bkey_durability_safe(c, bkey_i_to_s_c(copy)).total, BCH_DISK_RESERVATION_NOFAIL); } diff --git a/fs/data/keylist.c b/fs/data/keylist.c index a44ccbdb26..f824458a53 100644 --- a/fs/data/keylist.c +++ b/fs/data/keylist.c @@ -18,7 +18,7 @@ int bch2_keylist_realloc(struct keylist *l, u64 *inline_u64s, (old_buf && roundup_pow_of_two(oldsize) == newsize)) return 0; - new_keys = krealloc(old_buf, sizeof(u64) * newsize, GFP_NOFS); + new_keys = krealloc(old_buf, sizeof(u64) * newsize, GFP_NOIO); if (!new_keys) return -ENOMEM; diff --git a/fs/data/migrate.c b/fs/data/migrate.c index 3ad75485e7..df833539ef 100644 --- a/fs/data/migrate.c +++ b/fs/data/migrate.c @@ -26,6 +26,7 @@ #include "sb/io.h" +#include "init/damage.h" #include "init/progress.h" static struct bkey_i *drop_dev_ptrs(struct btree_trans *trans, struct bkey_s_c k, unsigned dev_idx, @@ -99,6 +100,10 @@ static int bch2_dev_usrdata_drop_key(struct btree_trans *trans, if (!n) return 0; + if (n->k.type == KEY_TYPE_error) + try(bch2_damage_record_data_loss(trans, iter->btree_id, k.k->p, + BCH_FSCK_ERR_data_lost_device_removed)); + /* * Since we're not inserting through an extent iterator * (BTREE_ITER_all_snapshots iterators aren't extent iterators), diff --git a/fs/data/move.c b/fs/data/move.c index 2e2afb3d24..5e7d250aab 100644 --- a/fs/data/move.c +++ b/fs/data/move.c @@ -389,7 +389,7 @@ int bch2_move_extent(struct moving_context *ctxt, ret = bch2_btree_node_rewrite_pos(trans, iter->btree_id, level, k.k->p, data_opts->target, - data_opts->commit_flags, + commit_flags, data_opts->write_flags); /* ENOMEM becomes a restart below and gets retried - not an outcome */ @@ -474,8 +474,7 @@ int bch2_move_ratelimit(struct moving_context *ctxt) do { delay = ctxt->rate ? bch2_ratelimit_delay(ctxt->rate) : 0; - if (is_kthread && kthread_should_stop()) - return 1; + try(bch2_kthread_cancelled(c)); if (delay) move_ctxt_wait_event_timeout(ctxt, @@ -578,9 +577,6 @@ int bch2_move_data_btree(struct moving_context *ctxt, break; } - /* ratelimit told us to stop (kthread_should_stop), not an error */ - if (ret > 0) - ret = 0; return ret; } @@ -754,11 +750,14 @@ static int __bch2_move_data_phys(struct moving_context *ctxt, bch2_btree_iter_advance(&bp_iter); } - /* ratelimit told us to stop (kthread_should_stop), not an error */ - if (ret > 0) - ret = 0; - - while (ca && + /* + * Audit the buckets the walk didn't reach - but only if it actually + * finished. If we were cancelled or hit an error we didn't skip those + * buckets because they had nothing to walk, we just stopped; auditing + * them is then both wrong and slow, and this loop is slow enough to be + * the thing a user waits on after hitting ctrl-C. + */ + while (!ret && ca && check_mismatch_done < sector_to_bucket(ca, sector_end)) bch2_check_bucket_backpointer_mismatch(trans, ca, check_mismatch_done++, copygc, &last_flushed); @@ -1109,8 +1108,7 @@ int bch2_scrub_journal(struct bch_fs *c, u64 *rewind_seq) prt_printf(&msg.m, " dev%u", i); } - guard(memalloc_flags)(PF_MEMALLOC_NOFS); - guard(mutex)(&c->sb_lock); + guard(mutex_noio)(&c->sb_lock); for_each_set_bit(i, stats.devs_error_uncorrected.d, BCH_SB_MEMBERS_MAX) { struct bch_member *m = bch2_members_v2_get_mut(c->disk_sb.sb, i); if (m) diff --git a/fs/data/read.c b/fs/data/read.c index 50040ef180..91cfa347f5 100644 --- a/fs/data/read.c +++ b/fs/data/read.c @@ -42,6 +42,7 @@ #include "debug/async_objs.h" +#include "init/damage.h" #include "init/error.h" #include "sb/counters.h" @@ -687,7 +688,7 @@ static int rbio_mark_io_failure(struct bch_read_bio *rbio, } - if (ret == BCH_ERR_BLK_STS_INVAL) { + if (ret == -BCH_ERR_BLK_STS_INVAL) { prt_printf(&failed->ec_msg, "Failing bio, after block layer completion:\n"); guard(printbuf_indent)(&failed->ec_msg); bch2_bio_to_text(&failed->ec_msg, &rbio->bio); @@ -696,6 +697,12 @@ static int rbio_mark_io_failure(struct bch_read_bio *rbio, return ret; } +static bool data_read_err_is_csum(int ret) +{ + return bch2_err_matches(ret, BCH_ERR_data_read_retry_csum_err) || + bch2_err_matches(ret, BCH_ERR_data_read_retry_csum_err_maybe_userspace); +} + static void bch2_rbio_retry(struct work_struct *work) { struct bch_read_bio *rbio = @@ -708,6 +715,7 @@ static void bch2_rbio_retry(struct work_struct *work) .inum = rbio->read_pos.inode, }; struct bpos read_pos = rbio->read_pos; + int orig_ret = rbio->ret; CLASS(bch_io_failures, failed)(); flags &= ~BCH_READ_hard_require_read_device; @@ -785,6 +793,60 @@ static void bch2_rbio_retry(struct work_struct *work) mutex_unlock(&rbio->err_report->lock); } + /* + * The persistent record: count what happened - recovered via + * retry vs. hard failure, io error vs. checksum error - and + * record damage against the file. Best effort: a bookkeeping + * failure doesn't fail the read. Only user reads name an inum + * (a data update read may be an indirect extent): + */ + if (failed.nr || ret) { + enum bch_sb_error_id e = !ret + ? (data_read_err_is_csum(orig_ret) + ? BCH_FSCK_ERR_data_read_csum_err_recovered + : BCH_FSCK_ERR_data_read_io_err_recovered) + : (data_read_err_is_csum(ret) + ? BCH_FSCK_ERR_data_read_csum_err + : BCH_FSCK_ERR_data_read_io_err); + + bch2_sb_error_count(c, e); + + /* + * Also count what the device said, per failure: the + * outcome counters above say a read failed, these say + * why - media errors, timeouts and rejected requests + * are entirely different problems. + * + * Only for failures that came back from the block + * layer: errcode also holds our own verdicts (device + * offline, stale pointer, decompress error), and those + * aren't block statuses to be counted as unknown ones. + * Decompression failures are counted where they happen, + * in bch2_bio_uncompress(). + */ + darray_for_each(failed, f) { + if (bch2_err_matches(f->errcode, BCH_ERR_blockdev_io_error)) + bch2_sb_error_count(c, bch2_blk_sts_sb_err(f->errcode)); + if (bch2_err_matches(f->ec_errcode, BCH_ERR_blockdev_io_error)) + bch2_sb_error_count(c, bch2_blk_sts_sb_err(f->ec_errcode)); + } + + /* + * Damage names the reason where we have one: a file + * whose extents won't decompress is a different repair + * problem from one with bad checksums, and which + * compression type failed is the first thing we'd ask. + */ + enum bch_sb_error_id damage = + bch2_err_matches(ret, BCH_ERR_decompress) + ? bch2_decompress_sb_err(ret) + : e; + + if (!rbio->data_update && inum.subvol && !bkey_deleted(&sk.k->k)) + commit_do(trans, NULL, NULL, BCH_TRANS_COMMIT_no_enospc, + bch2_damage_record(trans, read_pos, damage)); + } + /* drop trans before calling rbio_done() */ } @@ -903,7 +965,7 @@ static int __bch2_read_endio_work(struct bch_read_bio *rbio) struct bch_csum csum; int ret; - guard(memalloc_flags)(PF_MEMALLOC_NOFS); + guard(memalloc_flags)(PF_MEMALLOC_NOIO); if (bch2_read_corrupt_device == rbio->pick.ptr.dev || bch2_read_corrupt_device < 0) @@ -1243,11 +1305,11 @@ static inline struct bch_read_bio *read_extent_rbio_alloc(struct btree_trans *tr rbio = rbio_init_fragment(bio_alloc_bioset(NULL, DIV_ROUND_UP(sectors, PAGE_SECTORS), 0, - GFP_NOFS, + GFP_NOIO, &c->bio_read_split), orig, failed); - gfp_t gfp = GFP_NOFS; + gfp_t gfp = GFP_NOIO; /* * Only skip zeroing if we can detect if the device lied and @@ -1272,7 +1334,7 @@ static inline struct bch_read_bio *read_extent_rbio_alloc(struct btree_trans *tr * from the whole bio, in which case we don't want to retry and * lose the error) */ - rbio = rbio_init_fragment(bio_alloc_clone(NULL, &orig->bio, GFP_NOFS, + rbio = rbio_init_fragment(bio_alloc_clone(NULL, &orig->bio, GFP_NOIO, &c->bio_read_split), orig, failed); rbio->bio.bi_iter = iter; @@ -1724,6 +1786,17 @@ int bch2_read(struct btree_trans *trans, struct bch_read_bio *rbio, if (ret && !data_read_err_should_retry(ret)) break; + + /* + * A stale BCH_READ_last_fragment on the retry would falsely + * terminate the read: bvec_iter is stable across attempts but + * the extent isn't - if it shrank (a concurrent write + * splitting it), the retried fragment is no longer the last + * and the rest of the buffer would never be read. must_clone + * stays: splits demand cloning for error attribution. + */ + if (ret) + flags &= ~BCH_READ_last_fragment; } if (unlikely(ret)) { diff --git a/fs/data/reconcile/trigger.c b/fs/data/reconcile/trigger.c index 3a082f97a5..96aa95ae19 100644 --- a/fs/data/reconcile/trigger.c +++ b/fs/data/reconcile/trigger.c @@ -498,7 +498,7 @@ static int bch2_bkey_needs_reconcile(struct btree_trans *trans, struct bkey_s_c incompressible |= p.crc.compression_type == BCH_COMPRESSION_TYPE_incompressible; unwritten |= p.ptr.unwritten; - bool evacuating = bch2_dev_bad_or_evacuating(c, p.ptr.dev) && !p.has_ec; + bool evacuating = bch2_ptr_bad_or_evacuating(c, &p.ptr) && !p.has_ec; if (!poisoned && !btree && @@ -539,8 +539,14 @@ static int bch2_bkey_needs_reconcile(struct btree_trans *trans, struct bkey_s_c if (k.k->type == KEY_TYPE_stripe) { *ret = r; - return (r.need_rb & BIT(BCH_RECONCILE_data_replicas)) && - !bkey_s_c_to_stripe(k).v->needs_reconcile; + /* + * A repair pass can lose the stripe's work item (e.g. a stale + * needs_reconcile read racing the scan's flag update), and unless + * the scan re-queues it the stripe stays flagged-but-never-repaired + * forever. + * TODO: a cleaner fix would be avoiding the race in the first place + */ + return r.need_rb & BIT(BCH_RECONCILE_data_replicas); } if (unwritten || incompressible) @@ -729,6 +735,16 @@ static int new_needs_rb_allowed(struct btree_trans *trans, return 0; } + /* + * Shrink/evacuation can mark an extent under-replicated as soon as one + * pointer falls onto a bad/evacuating location, before the device scan + * has rewritten the reconcile entry. That's a transient physical-state + * change, not a missing io-opts propagation cookie. + */ + if ((new_need_rb & BIT(BCH_RECONCILE_data_replicas)) && + bch2_bkey_has_ptr_bad_or_evacuating(c, k)) + return 0; + /* * Either the extent data or the extent io options (from * bch_extent_reconcile) should match the io_opts from the @@ -751,7 +767,14 @@ static int new_needs_rb_allowed(struct btree_trans *trans, if (ret) return min(ret, 0); - if (new_need_rb == BIT(BCH_RECONCILE_data_replicas)) { + /* + * Device scans can add evacuation/rereplicate work on top of existing + * reconcile state, e.g. an extent that was already waiting on + * erasure-code conversion. While that scan cookie is pending, tolerate + * missing data_replicas/hipri state even if other reconcile bits are + * also set; the scan will rewrite the full reconcile entry. + */ + if (new_need_rb & BIT(BCH_RECONCILE_data_replicas)) { ret = check_dev_reconcile_scan_cookie(trans, k, s ? &s->dev_cookie : NULL); if (ret) return min(ret, 0); @@ -805,6 +828,17 @@ static int set_needs_reconcile_stripe(struct btree_trans *trans, } s.v->needs_reconcile = new_needs_reconcile; + + /* + * A repair pass can lose the stripe's work item (e.g. a stale + * needs_reconcile read racing the scan's flag update), and unless + * the scan re-queues it the stripe stays flagged-but-never-repaired + * forever. + * TODO: a cleaner fix would be avoiding the race in the first place + */ + if (new_needs_reconcile) + try(reconcile_work_mod(trans, k.s_c, RECONCILE_WORK_hipri, + data_to_rb_work_pos(BTREE_ID_stripes, k.k->p), true)); return 0; } @@ -1025,25 +1059,35 @@ int bch2_bkey_get_io_opts(struct btree_trans *trans, if (snapshot_opts->cur_inum != k.k->p.inode) { snapshot_opts->d.nr = 0; - try(for_each_btree_key_max(trans, iter, BTREE_ID_inodes, - SPOS(0, k.k->p.inode, 0), - SPOS(0, k.k->p.inode, U32_MAX), - BTREE_ITER_all_snapshots, inode_k, ({ - struct bch_inode_unpacked inode; + /* + * norestart: callers (e.g. fsck repair paths) + * may have updates queued; an internal + * trans_begin() would clobber them + */ + struct bkey_s_c inode_k; + int ret = 0; + for_each_btree_key_max_norestart(trans, iter, BTREE_ID_inodes, + SPOS(0, k.k->p.inode, 0), + SPOS(0, k.k->p.inode, U32_MAX), + BTREE_ITER_all_snapshots, inode_k, ret) { if (!bkey_is_inode(inode_k.k)) continue; + + struct bch_inode_unpacked inode; bch2_inode_unpack(c, inode_k, &inode); struct snapshot_io_opts_entry e = { .snapshot = inode_k.k->p.snapshot }; bch2_inode_opts_get_inode(c, &inode, &e.io_opts); - darray_push(&snapshot_opts->d, e); - }))); + ret = darray_push(&snapshot_opts->d, e); + if (ret) + break; + } + if (ret) + return ret; snapshot_opts->cur_inum = k.k->p.inode; snapshot_opts->inum_scan_cookie = false; - - return bch_err_throw(c, transaction_restart_nested); } struct snapshot_io_opts_entry *i = diff --git a/fs/data/reconcile/types.h b/fs/data/reconcile/types.h index 127b6abcc8..434bc8d130 100644 --- a/fs/data/reconcile/types.h +++ b/fs/data/reconcile/types.h @@ -2,6 +2,8 @@ #ifndef _BCACHEFS_REBALANCE_TYPES_H #define _BCACHEFS_REBALANCE_TYPES_H +#include + #include "btree/bbpos_types.h" #include "data/move_types.h" #include "init/progress.h" @@ -11,7 +13,9 @@ struct bch_fs_reconcile { struct task_struct __rcu *thread; - u32 kick; + atomic_t kick; + wait_queue_head_t wait; + atomic_t completed_kick; bool running; u64 wait_iotime_start; diff --git a/fs/data/reconcile/work.c b/fs/data/reconcile/work.c index 1aac461414..5e79cb3055 100644 --- a/fs/data/reconcile/work.c +++ b/fs/data/reconcile/work.c @@ -349,14 +349,23 @@ static struct bkey_s_c next_reconcile_entry(struct btree_trans *trans, if (work_pos->btree == BTREE_ID_reconcile_scan) { buf->nr = 0; - int ret = for_each_btree_key_max(trans, iter, work_pos->btree, work_pos->pos, end, - flags, k, ({ - bkey_reassemble(&darray_top(*buf), k); - return bkey_i_to_s_c(&darray_top(*buf)); - 0; - })); + /* + * Do not return out of a for_each_btree_key_* body here: we want + * the iterator fully dropped before reconcile starts mutating the + * extent that this work item points at. Keeping the reconcile_scan + * path pinned across the later move/rewrite can deadlock against + * alloc/freespace updates from the same transaction. + */ + CLASS(btree_iter, iter)(trans, work_pos->btree, work_pos->pos, flags); + struct bkey_s_c k = bch2_btree_iter_peek(&iter); + + if (bkey_err(k)) + return bkey_s_c_err(bkey_err(k)); + if (!k.k || bpos_gt(k.k->p, end)) + return bkey_s_c_null; - return ret ? bkey_s_c_err(ret) : bkey_s_c_null; + bkey_reassemble(&darray_top(*buf), k); + return bkey_i_to_s_c(&darray_top(*buf)); } if (unlikely(!buf->nr)) { @@ -442,7 +451,8 @@ static int reconcile_set_data_opts(struct btree_trans *trans, * (data_update_useless_write_fail). Better to fail with freelist_empty * and retry from a fresh read. */ - data_opts->write_flags |= BCH_WRITE_alloc_nowait; + if (!bkey_is_btree_ptr(k.k)) + data_opts->write_flags |= BCH_WRITE_alloc_nowait; /* * we can't add/drop replicas from btree nodes incrementally, we always @@ -467,7 +477,7 @@ static int reconcile_set_data_opts(struct btree_trans *trans, guard(rcu)(); bkey_for_each_ptr(ptrs, ptr) { - if (bch2_dev_bad_or_evacuating(c, ptr->dev)) + if (bch2_ptr_bad_or_evacuating_rcu(c, ptr)) data_opts->ptrs_kill |= ptr_bit; ptr_bit <<= 1; } @@ -499,7 +509,7 @@ static int reconcile_set_data_opts(struct btree_trans *trans, !test_bit(ptr->dev, c->devs_online.d); if (!ptr->cached && (online_floor || offline)) { - bool force = bch2_dev_bad_or_evacuating(c, ptr->dev); + bool force = bch2_ptr_bad_or_evacuating(c, ptr); ptr->cached = true; struct bkey_durability d; @@ -518,7 +528,7 @@ static int reconcile_set_data_opts(struct btree_trans *trans, * reads as durability=0, but we drop it once the * required durability is held by other devices. */ - if (have >= r->data_replicas && + if ((force || have >= r->data_replicas) && (force || have < was)) { data_opts->ptrs_kill |= ptr_bit; cur = d; @@ -706,10 +716,17 @@ static int check_reconcile_pending_err(struct btree_trans *trans, { struct bch_fs *c = trans->c; - if (!bch2_err_matches(err, BCH_ERR_data_update_fail_no_rw_devs) && - !bch2_err_matches(err, BCH_ERR_insufficient_devices) && - !bch2_err_matches(err, ENOSPC)) - return err; + /* + * Reconcile can park transient allocation failures on the pending list + * and retry after space becomes available. The allocator's internal + * no_buckets_found code is the same class of "try again later" failure + * as ENOSPC, but it bypasses the errno-based match. + */ + if (!bch2_err_matches(err, BCH_ERR_data_update_fail_no_rw_devs) && + !bch2_err_matches(err, BCH_ERR_insufficient_devices) && + !bch2_err_matches(err, BCH_ERR_freelist_empty) && + !bch2_err_matches(err, ENOSPC)) + return err; s64 sectors = bkey_is_btree_ptr(k.k) ? btree_sectors(c) : k.k->size; @@ -884,8 +901,10 @@ static int __do_reconcile_extent(struct moving_context *ctxt, if (ret) { WARN_ONCE(!bch2_err_matches(ret, EROFS) && !bch2_err_matches(ret, BCH_ERR_snapshot) && - ret != -BCH_ERR_data_update_fail_no_snapshot && - ret != -BCH_ERR_data_update_fail_in_flight, + !bch2_err_matches(ret, BCH_ERR_data_update_fail_no_snapshot) && + !bch2_err_matches(ret, BCH_ERR_data_update_fail_in_flight) && + !bch2_err_matches(ret, BCH_ERR_freelist_empty) && + !bch2_err_matches(ret, BCH_ERR_open_buckets_empty), "unhandled error from move_extent: %s", bch2_err_str(ret)); /* skip it and continue */ } @@ -907,13 +926,17 @@ static int do_reconcile_extent(struct moving_context *ctxt, struct bch_fs *c = trans->c; struct bbpos data_pos = rb_work_to_data_pos(work.pos); - /* We require holding an intent lock when calling - * bch2_stripe_handle_tryget(), to avoid racing with the stripe trigger - * deleting the stripe */ - enum btree_iter_update_trigger_flags flags = data_pos.btree == BTREE_ID_stripes - ? BTREE_ITER_intent : 0; + /* + * Reconcile always mutates the key it is looking at, either by updating + * reconcile state or by queueing a move. Start with an intent iterator + * so we do not pay one transaction restart_upgrade per extent just to + * upgrade the lock during commit. Stripe keys also require intent before + * bch2_stripe_handle_tryget() can safely race with stripe deletion. + */ + enum btree_iter_update_trigger_flags flags = + BTREE_ITER_all_snapshots|BTREE_ITER_intent; - CLASS(btree_iter, iter)(trans, data_pos.btree, data_pos.pos, BTREE_ITER_all_snapshots|flags); + CLASS(btree_iter, iter)(trans, data_pos.btree, data_pos.pos, flags); struct bkey_s_c k = bkey_try(bch2_btree_iter_peek_slot(&iter)); if (!k.k) return 0; @@ -957,11 +980,13 @@ static int do_reconcile_extent_phys(struct moving_context *ctxt, if (bch2_data_update_in_flight(c, &pos, BCH_DATA_UPDATE_reconcile)) return 0; - /* We require holding an intent lock when calling - * bch2_stripe_handle_tryget(), to avoid racing with the stripe trigger - * deleting the stripe */ - enum btree_iter_update_trigger_flags flags = bp.v->btree_id == BTREE_ID_stripes - ? BTREE_ITER_intent : 0; + /* + * Phys reconcile reaches the owning extent through a backpointer and + * then updates that extent in the same transaction. Take the extent + * iterator in intent mode up front to avoid restart_upgrade churn when + * many adjacent extents are being reprocessed after shrink. + */ + enum btree_iter_update_trigger_flags flags = BTREE_ITER_intent; CLASS(btree_iter_uninit, iter)(trans); struct bkey_s_c k = bkey_try(bch2_backpointer_get_key(trans, bp, &iter, flags, last_flushed)); @@ -1097,12 +1122,27 @@ static int do_reconcile_scan_bps(struct moving_context *ctxt, struct btree_trans *trans = ctxt->trans; struct bch_fs *c = trans->c; struct bch_fs_reconcile *r = &c->reconcile; + struct bpos start = POS(s.dev, 0); + struct bch_dev *ca; - r->scan_start = BBPOS(BTREE_ID_backpointers, POS(s.dev, 0)); + /* + * Shrink only needs reconcile work for the tail that will be truncated. + * Scanning the whole device requeues metadata below the retained region, + * which can churn btree rewrites for tens of seconds before the resize + * worker ever gets to commit the smaller size. + */ + scoped_guard(rcu) { + ca = bch2_dev_rcu_noerror(c, s.dev); + if (ca && bch2_dev_is_shrinking(ca)) + start = bucket_pos_to_bp_start(ca, + POS(s.dev, bch2_dev_resize_target(ca))); + } + + r->scan_start = BBPOS(BTREE_ID_backpointers, start); r->scan_end = BBPOS(BTREE_ID_backpointers, POS(s.dev, U64_MAX)); return backpointer_scan_for_each(trans, iter, BTREE_ID_backpointers, - POS(s.dev, 0), POS(s.dev, U64_MAX), + start, POS(s.dev, U64_MAX), last_flushed, NULL, bp, ({ ctxt->stats->pos = BBPOS(BTREE_ID_backpointers, iter.pos); @@ -1354,10 +1394,10 @@ static void reconcile_wait(struct bch_fs *c, u32 kick) r->wait_iotime_end = now + (min_member_capacity >> 6); - if (r->running) { + if (READ_ONCE(r->running)) { r->wait_iotime_start = now; r->wait_wallclock_start = ktime_get_real_ns(); - r->running = false; + WRITE_ONCE(r->running, false); } /* @@ -1366,7 +1406,7 @@ static void reconcile_wait(struct bch_fs *c, u32 kick) * wakeups: */ set_current_state(TASK_INTERRUPTIBLE); - if (kick == READ_ONCE(r->kick)) + if (kick == atomic_read(&r->kick)) bch2_kthread_io_clock_wait_once(clock, r->wait_iotime_end, MAX_SCHEDULE_TIMEOUT); __set_current_state(TASK_RUNNING); } @@ -1488,6 +1528,15 @@ static CLOSURE_CALLBACK(do_reconcile_phys_thread) k.k->p.inode != thr->dev) break; + /* + * Drop any cached search paths from next_reconcile_entry() before + * we start the actual move work: otherwise reconcile_scan or + * backpointer paths looked up to choose the work item can stay + * pinned in this transaction and deadlock against alloc/freespace + * updates during btree node rewrites. + */ + bch2_trans_begin(trans); + int ret = lockrestart_do(trans, do_reconcile_extent_phys(&ctxt, &snapshot_io_opts, BBPOS(work_pos.btree, k.k->p), @@ -1634,7 +1683,7 @@ static int do_reconcile_phase_iter(struct reconcile_pass *p, u32 kick, while (!bch2_move_ratelimit(ctxt) && !test_bit(BCH_FS_going_ro, &c->flags) && bch2_reconcile_enabled(c) && - kick == r->kick) { + kick == atomic_read(&r->kick)) { bch2_trans_begin(trans); struct bkey_s_c k = next_reconcile_entry(trans, p->work, &r->work_pos, @@ -1723,8 +1772,9 @@ static int do_reconcile(struct moving_context *ctxt) struct bch_fs *c = trans->c; struct bch_fs_reconcile *r = &c->reconcile; u64 sectors_scanned = 0; - u32 kick = r->kick; + u32 kick = atomic_read(&r->kick); u32 copygc_run_count = c->copygc.run_count; + bool pass_complete = false; int ret = 0; CLASS(darray_reconcile_work, work)(); @@ -1775,7 +1825,7 @@ static int do_reconcile(struct moving_context *ctxt) * uses this latest value to decide whether anyone is still * asking for more work. */ - kick = r->kick; + kick = atomic_read(&r->kick); for (r->phase = 0; r->phase < ARRAY_SIZE(reconcile_phases); r->phase++) { reconcile_phase_start(c); @@ -1796,7 +1846,7 @@ static int do_reconcile(struct moving_context *ctxt) work.nr = 0; - if (kick != r->kick || + if (kick != atomic_read(&r->kick) || test_bit(BCH_FS_going_ro, &c->flags) || bch2_move_ratelimit(ctxt)) break; @@ -1806,21 +1856,37 @@ static int do_reconcile(struct moving_context *ctxt) } /* Completed a clean pass through all phases — we're done. */ - if (r->phase == ARRAY_SIZE(reconcile_phases)) + if (r->phase == ARRAY_SIZE(reconcile_phases)) { + pass_complete = true; break; + } } out: if (!ret && !bkey_deleted(&pending_cookie.k)) try(bch2_clear_reconcile_needs_scan(trans, pending_cookie.k.p, pending_cookie.v.cookie)); + /* + * A completed kick means reconcile drained every phase for the current + * request generation without being superseded by a newer wakeup. + * Shrink uses this as the point where all scan-generated downstream + * work has been attempted before it decides a tail is still impossible + * to evacuate. + */ + if (!ret && + pass_complete && + kick == atomic_read(&r->kick)) { + atomic_set(&r->completed_kick, kick); + wake_up_all(&r->wait); + } + bch2_move_stats_exit(&r->work_stats, c); if (!ret && !kthread_should_stop() && !atomic64_read(&r->work_stats.sectors_seen) && !sectors_scanned && - kick == r->kick) { + kick == atomic_read(&r->kick)) { bch2_moving_ctxt_flush_all(ctxt); bch2_trans_unlock_long(trans); reconcile_wait(c, kick); @@ -2035,6 +2101,10 @@ int bch2_fs_reconcile_init(struct bch_fs *c) { struct bch_fs_reconcile *r = &c->reconcile; + atomic_set(&r->kick, 0); + init_waitqueue_head(&r->wait); + atomic_set(&r->completed_kick, 0); + mutex_init(&r->scans_in_flight_lock); try(rhashtable_init(&r->scans_in_flight, &reconcile_scan_in_flight_params)); r->scans_in_flight_init_done = true; diff --git a/fs/data/reconcile/work.h b/fs/data/reconcile/work.h index f945cfa212..e84cacace2 100644 --- a/fs/data/reconcile/work.h +++ b/fs/data/reconcile/work.h @@ -64,13 +64,24 @@ int bch2_set_fs_needs_reconcile(struct bch_fs *); int bch2_reconcile_scan_cookie_is_set(struct btree_trans *, u64); -static inline void bch2_reconcile_wakeup(struct bch_fs *c) +static inline u32 bch2_reconcile_kick(struct bch_fs *c) { - c->reconcile.kick++; + u32 kick = atomic_inc_return(&c->reconcile.kick); guard(rcu)(); struct task_struct *p = rcu_dereference(c->reconcile.thread); if (p) wake_up_process(p); + return kick; +} + +static inline void bch2_reconcile_wakeup(struct bch_fs *c) +{ + bch2_reconcile_kick(c); +} + +static inline u32 bch2_reconcile_completed_kick(struct bch_fs *c) +{ + return atomic_read(&c->reconcile.completed_kick); } static inline int bch2_reconcile_pending_wakeup(struct bch_fs *c) diff --git a/fs/data/reflink.c b/fs/data/reflink.c index a412e5344f..ed2651c0f0 100644 --- a/fs/data/reflink.c +++ b/fs/data/reflink.c @@ -207,7 +207,8 @@ static int bch2_indirect_extent_missing_error(struct btree_trans *trans, prt_printf(&buf, "\nmissing reflink btree range %llu-%llu", missing_start, missing_end); - if (ret_fsck_err(trans, reflink_p_to_missing_reflink_v, "%s", buf.buf)) { + if (ret_inode_fsck_err(trans, p.k->p, + reflink_p_to_missing_reflink_v, "%s", buf.buf)) { struct bkey_i_reflink_p *new = errptr_try(bch2_bkey_make_mut_noupdate_typed(trans, p.s_c, reflink_p)); diff --git a/fs/data/update.c b/fs/data/update.c index 81ffd53600..829e07f45c 100644 --- a/fs/data/update.c +++ b/fs/data/update.c @@ -744,7 +744,20 @@ bool bch2_data_update_fail_should_trace(enum bch_data_update_types type, int ret bch2_err_matches(ret, BCH_ERR_operation_blocked) || ((type == BCH_DATA_UPDATE_reconcile || type == BCH_DATA_UPDATE_promote) && - bch2_err_matches(ret, BCH_ERR_data_update_fail_no_rw_devs))) + (bch2_err_matches(ret, BCH_ERR_data_update_fail_no_rw_devs) || + /* + * The allocator reports a fully-exhausted retry sequence as + * BCH_ERR_freelist_empty/no_buckets_found. Reconcile demotes + * that to pending work just like ENOSPC, so don't count it as a + * hard data-update failure. + */ + bch2_err_matches(ret, BCH_ERR_freelist_empty) || + /* + * Reconcile promotes ENOSPC-class write failures to pending work + * and retries after space/stripe availability changes, so don't + * count those transient allocation misses as data update failures. + */ + bch2_err_matches(ret, ENOSPC)))) return false; return true; @@ -1028,7 +1041,7 @@ static unsigned durability_available_on_target(struct bch_fs *c, } /* bch2_copygc_can_make_progress needs to read accounting for dev_leaving */ - guard(percpu_read)(&c->capacity.mark_lock); + guard(percpu_read_noio)(&c->capacity.mark_lock); guard(rcu)(); struct bch_devs_mask devs = target_rw_devs(c, data_type, target); unsigned durability = 0; @@ -1088,11 +1101,9 @@ static bool bch2_btree_ptr_has_dev_evacuating(struct bch_fs *c, struct bkey_s_c struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k); guard(rcu)(); - bkey_for_each_ptr(ptrs, ptr) { - struct bch_dev *ca = bch2_dev_rcu_noerror(c, ptr->dev); - if (ca && ca->mi.state == BCH_MEMBER_STATE_evacuating) + bkey_for_each_ptr(ptrs, ptr) + if (bch2_ptr_bad_or_evacuating_rcu(c, ptr)) return true; - } return false; } @@ -1125,7 +1136,7 @@ static int bch2_can_do_write_btree(struct bch_fs *c, bool evacuating = bch2_btree_ptr_has_dev_evacuating(c, k); /* Dropping excess replicas is progress regardless of placement: */ - if (bch2_bkey_nr_dirty_ptrs(c, k) > opts->data_replicas) + if (bch2_bkey_durability_safe(c, k).nr_ptrs > opts->data_replicas) return 0; unsigned durability = bch2_btree_ptr_durability(c, k).total; @@ -1249,9 +1260,13 @@ int bch2_can_do_data_update(struct btree_trans *trans, .ec_replicas = opts->data_replicas + data_opts->extra_replicas, .watermark = BCH_WATERMARK_normal, }; + darray_init(&req.trace); struct ec_stripe_head *h = bch2_ec_stripe_head_get(trans, &req, 0); + + darray_exit(&req.trace); + if (IS_ERR_OR_NULL(h)) return bch_err_throw(c, ec_alloc_failed); bch2_ec_stripe_head_put(c, h); @@ -1473,8 +1488,24 @@ int bch2_data_update_init(struct btree_trans *trans, goto out; } - if (!rhltable_insert_key(&c->update_table, &m->pos, &m->hash, bch_update_params)) - m->on_hashtable = true; + /* + * Phys reconcile can queue the same logical extent from multiple + * source devices. The lookup above is only a fast path; another + * mover can still win the race and claim @m->pos before we insert. + * Use the non-list insert helper so only one update owns the key. + */ + ret = rhashtable_lookup_insert_fast(&c->update_table.ht, + &m->hash.rhead, + bch_update_params); + if (ret == -EEXIST) { + event_inc(c, data_update_in_flight); + ret = bch_err_throw(c, data_update_fail_in_flight); + goto out; + } + if (ret) + goto out; + + m->on_hashtable = true; } else { if (unwritten) { ret = bch_err_throw(c, data_update_done_unwritten); diff --git a/fs/data/write.c b/fs/data/write.c index 5e6a9e44a5..b1d5014037 100644 --- a/fs/data/write.c +++ b/fs/data/write.c @@ -377,8 +377,13 @@ * candidates is chosen; devices with a different bucket size are excluded). The * minimum is \texttt{redundancy + 2} devices (3 for RAID-5, 4 for RAID-6). With * $n$ eligible devices, a stripe has $n - \mathrm{redundancy}$ data blocks and - * \texttt{redundancy} parity blocks, maximizing storage efficiency. There is no - * configuration to limit stripe width to a subset of available devices. + * \texttt{redundancy} parity blocks, maximizing storage efficiency. Data blocks + * per stripe may be capped with the \texttt{ec\_max\_data\_blocks} option; the + * cap excludes parity (a cap of 9 with 2 parity blocks gives stripes 11 blocks + * wide). When \hyperref[sec:failure-domains]{failure domains} are configured, a + * stripe takes at most one block per domain, so width is also bounded by the + * number of available domains. Which devices are used within these bounds is + * not configurable. * * Stripe fragmentation is tracked in the LRU btree. When all data blocks in a * stripe become empty (sector count zero), the stripe is automatically deleted. @@ -862,8 +867,7 @@ int bch2_sum_sector_overwrites(struct btree_trans *trans, s64 *disk_sectors_delta) { struct bch_fs *c = trans->c; - unsigned new_replicas = bch2_bkey_replicas(c, bkey_i_to_s_c(new)); - bool new_compressed = bch2_bkey_sectors_compressed(c, bkey_i_to_s_c(new)); + struct bkey_durability new_d = bch2_bkey_durability_safe(c, bkey_i_to_s_c(new)); *usage_increasing = false; *i_sectors_delta = 0; @@ -878,19 +882,34 @@ int bch2_sum_sector_overwrites(struct btree_trans *trans, max(bkey_start_offset(&new->k), bkey_start_offset(old.k)); + struct bkey_durability old_d = bch2_bkey_durability_safe(c, old); + *i_sectors_delta += sectors * (bkey_extent_is_allocation(&new->k) - bkey_extent_is_allocation(old.k)); - *disk_sectors_delta += sectors * bch2_bkey_nr_ptrs_allocated(c, bkey_i_to_s_c(new)); + /* + * What the new key will occupy, less what overwriting the old + * one gives back. Only the old key's uncompressed replicas + * count against us: a compressed extent holds fewer sectors + * than it covers, so crediting its full extent would hand back + * space that was never taken. + * + * nr_replicas, not total: this is space accounting, and it must + * not depend on mi.durability. Durability is OPT_RUNTIME while + * accounting is persistent, so weighting by it would let a + * device setting change retroactively invalidate space already + * accounted for. + */ + *disk_sectors_delta += sectors * new_d.nr_replicas; *disk_sectors_delta -= new->k.p.snapshot == old.k->p.snapshot - ? sectors * bch2_bkey_nr_ptrs_fully_allocated(c, old) + ? sectors * old_d.nr_overwritable : 0; if (!*usage_increasing && (new->k.p.snapshot != old.k->p.snapshot || - new_replicas > bch2_bkey_replicas(c, old) || - (!new_compressed && bch2_bkey_sectors_compressed(c, old)))) + new_d.replicas > old_d.replicas || + (!new_d.sectors_compressed && old_d.sectors_compressed))) *usage_increasing = true; if (bkey_ge(old.k->p, new->k.p)) @@ -1210,7 +1229,7 @@ void bch2_submit_wbio_replicas(struct bch_write_bio *wbio, struct bch_fs *c, : bch2_dev_get_ioref(c, ptr->dev, ref_rw, ref_idx); if (ptr != last) { - n = to_wbio(bio_alloc_clone(NULL, &wbio->bio, GFP_NOFS, &c->replica_set)); + n = to_wbio(bio_alloc_clone(NULL, &wbio->bio, GFP_NOIO, &c->replica_set)); n->bio.bi_end_io = wbio->bio.bi_end_io; n->bio.bi_private = wbio->bio.bi_private; @@ -1301,7 +1320,7 @@ static noinline int bch2_write_drop_io_error_ptrs(struct bch_write_op *op) bch2_bkey_drop_ptrs_noerror(bkey_i_to_s(src), p, entry, bch2_dev_io_failures(&op->wbio.failed, p.ptr.dev)); - if (!bch2_bkey_nr_dirty_ptrs(c, bkey_i_to_s_c(src))) + if (!bch2_bkey_durability_safe(c, bkey_i_to_s_c(src)).nr_ptrs) return bch_err_throw(c, data_write_io); } @@ -1324,6 +1343,14 @@ static void __bch2_write_index(struct bch_write_op *op) struct keylist *keys = &op->insert_keys; int ret = 0; + /* + * the btree code sets PF_MEMALLOC_NOIO when it has btree locks held, + * but will drop locks and do GFP_KERNEL allocations + * + * But here, our btree updates really are required for memory reclaim: + */ + guard(memalloc_flags)(PF_MEMALLOC_NOIO); + if (unlikely(op->io_error)) { ret = bch2_write_drop_io_error_ptrs(op); @@ -1581,7 +1608,7 @@ static struct bio *bch2_write_bio_alloc(struct bch_fs *c, pages = min(pages, BIO_MAX_VECS); - bio = bio_alloc_bioset(NULL, pages, 0, GFP_NOFS, &c->bio_write); + bio = bio_alloc_bioset(NULL, pages, 0, GFP_NOIO, &c->bio_write); wbio = wbio_init(bio); wbio->put_bio = true; /* copy WRITE_SYNC flag */ @@ -1608,13 +1635,13 @@ static struct bio *bch2_write_bio_alloc(struct bch_fs *c, bch2_bio_alloc_pages(bio, c->opts.block_size, output_available, - GFP_NOFS|__GFP_SKIP_ZERO); + GFP_NOIO|__GFP_SKIP_ZERO); unsigned required = min(output_available, c->opts.encoded_extent_max); if (unlikely(bio->bi_iter.bi_size < required)) __bch2_bio_alloc_pages_pool(c, bio, c->opts.block_size, required, - GFP_NOFS|__GFP_SKIP_ZERO); + GFP_NOIO|__GFP_SKIP_ZERO); return bio; } @@ -1643,11 +1670,83 @@ static int bch2_write_rechecksum(struct bch_fs *c, return 0; } +/* + * Decode an encoded extent in @bio in place: decrypt if encrypted, then + * decompress, and only put the result back once we have all of it. This is the + * inverse of the compress/encrypt the write path does on the way out, which is + * why it lives here - the decode is a write-path concern, and compress.c owns + * the primitives it's built from. + * + * @bio and @op->crc are untouched unless this returns 0, so a caller that can't + * use the plaintext still has the extent exactly as it arrived. + */ +static int bch2_write_op_decode(struct bch_write_op *op, struct bio *bio) +{ + struct bch_fs *c = op->c; + struct bch_extent_crc_unpacked *crc = &op->crc; + size_t dst_len = crc->uncompressed_size << 9; + + /* bio must own its pages: */ + BUG_ON(!bio->bi_vcnt); + BUG_ON(DIV_ROUND_UP(crc->live_size, PAGE_SECTORS) > bio->bi_max_vecs); + BUG_ON(bio->bi_iter.bi_size != crc->compressed_size << 9); + + if (crc->uncompressed_size << 9 > c->opts.encoded_extent_max) { + bch2_write_op_error(op, false, op->pos.offset, + "extent too big to decompress (%u > %u)", + crc->uncompressed_size << 9, c->opts.encoded_extent_max); + return bch2_decompress_err(c, bch_err_throw(c, decompress_exceeded_max_encoded_extent)); + } + + struct bbuf dst_buf __cleanup(bch2_bbuf_exit) = bch2_bounce_alloc(c, dst_len, WRITE); + + /* + * Encrypted data has to be decrypted before it can be decompressed, and + * @bio has to stay untouched until we know we have something to put + * back: if the data won't decompress, the caller writes the extent + * exactly as it found it. So take a private copy rather than letting + * bch2_bio_map_or_bounce() hand us the bio's own pages, and decrypt that. + */ + bool encrypted = bch2_csum_type_is_encryption(crc->csum_type); + struct bbuf src_buf __cleanup(bch2_bbuf_exit) = encrypted + ? bch2_bio_bounce(c, bio, bio->bi_iter, READ) + : bch2_bio_map_or_bounce(c, bio, READ); + + if (encrypted) + try(bch2_encrypt(c, crc->csum_type, extent_nonce(op->version, *crc), + src_buf.b, crc->compressed_size << 9)); + + int ret = bch2_buf_uncompress(c, dst_buf.b, src_buf.b, *crc); + if (c->opts.no_data_io) + ret = 0; + if (ret) { + bch2_write_op_error(op, false, op->pos.offset, "%s", bch2_err_str(ret)); + return bch2_decompress_err(c, ret); + } + + /* + * XXX: don't have a good way to assert that the bio was allocated with + * enough space, we depend on bch2_move_extent doing the right thing + */ + bio->bi_iter.bi_size = crc->live_size << 9; + + memcpy_to_bio(bio, bio->bi_iter, dst_buf.b + (crc->offset << 9)); + + crc->csum_type = 0; + crc->compression_type = 0; + crc->compressed_size = crc->live_size; + crc->uncompressed_size = crc->live_size; + crc->offset = 0; + crc->csum = (struct bch_csum) { 0, 0 }; + return 0; +} + static noinline int bch2_write_prep_encoded_data(struct bch_write_op *op, struct write_point *wp) { struct bch_fs *c = op->c; struct bio *bio = &op->wbio.bio; struct bch_csum csum; + int ret; BUG_ON(bio_sectors(bio) != op->crc.compressed_size); @@ -1714,14 +1813,36 @@ static noinline int bch2_write_prep_encoded_data(struct bch_write_op *op, struct if (bch2_crc_cmp(op->crc.csum, csum) && !c->opts.no_data_io) goto csum_err; - if (bch2_csum_type_is_encryption(op->crc.csum_type)) { - try(bch2_encrypt_bio(c, op->crc.csum_type, nonce, bio)); + /* + * Decryption happens inside bch2_write_op_decode(), on + * its own copy - @bio and @op->crc are left exactly as they are + * until the decompressed data is ready to go back. So if the + * data won't decompress there is nothing to undo, and writing + * the extent as we found it is still on the table: + */ + ret = bch2_write_op_decode(op, bio); + if (ret) { + if (!bch2_err_matches(ret, BCH_ERR_decompress)) + return ret; - op->crc.csum_type = 0; - op->crc.csum = (struct bch_csum) { 0, 0 }; - } + /* + * Nothing will ever decompress this. Preserve what we + * have rather than failing the write: the extent goes + * out byte-for-byte as it came in, still encrypted, + * still compressed, @op->crc still describing it. + * + * A compressed extent can't be split, so this needs a + * write point with room for the whole thing. If we + * haven't got one, say so and let __bch2_write() retire + * the short buckets and come back with fresh ones. That + * only ever happens here, so healthy compressed data + * never pays the fragmentation for it. + */ + if (op->crc.compressed_size > wp->sectors_free) + return bch_err_throw(c, data_write_need_fresh_buckets); - try(bch2_bio_uncompress_inplace(op, bio)); + return 1; + } } /* @@ -1968,7 +2089,7 @@ static int bch2_write_extent(struct bch_write_op *op, struct write_point *wp, BUG_ON(total_output != total_input); dst = bio_split(src, total_input >> 9, - GFP_NOFS, &c->bio_write); + GFP_NOIO, &c->bio_write); wbio_init(dst)->put_bio = true; /* copy WRITE_SYNC flag */ dst->bi_opf = src->bi_opf; @@ -2361,6 +2482,7 @@ static void __bch2_write(struct bch_write_op *op) struct bch_fs *c = op->c; struct write_point *wp = NULL; struct bio *bio = NULL; + bool retried_for_encoded = false; int ret; /* @@ -2374,7 +2496,7 @@ static void __bch2_write(struct bch_write_op *op) (!(op->flags & BCH_WRITE_submitted) && !(op->flags & BCH_WRITE_in_worker)); - guard(memalloc_flags)(PF_MEMALLOC_NOFS); + guard(memalloc_flags)(PF_MEMALLOC_NOIO); if (unlikely(op->opts.nocow && c->opts.nocow_enabled) && @@ -2442,6 +2564,25 @@ static void __bch2_write(struct bch_write_op *op) bch2_open_bucket_get(c, wp, &op->open_buckets); ret = bch2_write_extent(op, wp, &bio); + /* + * The extent wouldn't decompress, so it has to go out as it came + * in - and it can't be split, so it needs a write point with room + * for the whole compressed extent. Retire the buckets that came up + * short and allocate fresh, the way __bch2_btree_node_alloc() does + * for a btree node. + * + * Once only: nothing constrains encoded_extent_max against bucket + * size, so fresh buckets aren't guaranteed to be big enough either + * and retrying on that would never end. Giving up means the write + * fails, which is what happened before any of this. + */ + if (unlikely(bch2_err_matches(ret, BCH_ERR_data_write_need_fresh_buckets)) && + !retried_for_encoded) { + retried_for_encoded = true; + bch2_alloc_sectors_retire_short(c, wp, op->crc.compressed_size); + goto again; + } + bch2_alloc_sectors_done_inlined(c, wp); err: if (ret <= 0) { diff --git a/fs/data/write_types.h b/fs/data/write_types.h index a15149f7a9..b0dc9839e5 100644 --- a/fs/data/write_types.h +++ b/fs/data/write_types.h @@ -87,8 +87,18 @@ struct bch_write_op { s16 error; /* dio write path expects it to hold -ERESTARTSYS... */ u8 io_error; + /* + * What we want the data to be. Seeded from @opts at init + * (bch2_write_op_init()), but allowed to diverge from it: the data + * update path forces an encrypted extent to stay encrypted even if the + * file's options no longer ask for encryption, so this is the resolved + * intent for *this* write, not the filesystem's policy. + * + * Read these, not @opts, when deciding what to produce. + */ unsigned compression_opt:8; unsigned csum_type:4; + unsigned nr_replicas:4; unsigned watermark:3; unsigned incompressible:1; @@ -97,13 +107,29 @@ struct bch_write_op { struct bch_devs_list devs_have; u16 target; u16 nonce; + + /* + * The fs/file's configured options - policy, not intent. @csum_type and + * @compression_opt above are what we actually resolved to; where the two + * disagree, they do so deliberately. + */ struct bch_inode_opts opts; u32 subvol; struct bpos pos; struct bversion version; - /* For BCH_WRITE_data_encoded: */ + /* + * For BCH_WRITE_data_encoded: what the data we're holding currently + * *is* - as opposed to @csum_type/@compression_opt above, which are + * what we want it to become. It tracks the buffer: decrypting in place + * zeroes crc.csum_type because the buffer really is unencrypted and + * unchecksummed now, and decompressing clears crc.compression_type for + * the same reason. + * + * So the three layers are: @opts is policy, @csum_type is intent, @crc + * is fact. Anything that changes the buffer must update @crc with it. + */ struct bch_extent_crc_unpacked crc; struct write_point_specifier write_point; diff --git a/fs/debug/debug.c b/fs/debug/debug.c index 465043c043..3c9e0b4b57 100644 --- a/fs/debug/debug.c +++ b/fs/debug/debug.c @@ -74,7 +74,7 @@ __cold void bch2_btree_node_ondisk_to_text(struct printbuf *out, struct bch_fs * bio = bio_alloc_bioset(ca->disk_sb.bdev, buf_nr_bvecs(n_ondisk, btree_buf_bytes(b)), REQ_OP_READ|REQ_META, - GFP_NOFS, + GFP_NOIO, &c->btree.bio); bio->bi_iter.bi_sector = pick.ptr.offset; bch2_bio_map(bio, n_ondisk, btree_buf_bytes(b)); @@ -811,6 +811,60 @@ static const struct file_operations btree_node_scan_ops = { .read = bch2_btree_node_scan_read, }; +/* + * The full fsck damaged-paths list, untruncated: the end-of-fsck summary + * prints only the first FSCK_DAMAGED_PATHS_PRINT entries, which isn't enough + * when triaging a badly damaged filesystem. Interim surface until the damage + * btree lands. + */ +static ssize_t bch2_fsck_damaged_paths_read(struct file *file, char __user *buf, + size_t size, loff_t *ppos) +{ + struct dump_iter *i = file->private_data; + struct bch_fs *c = i->c; + + i->ubuf = buf; + i->size = size; + i->ret = 0; + + if (!test_bit(BCH_FS_may_go_rw, &c->flags)) + return 0; + + CLASS(btree_trans, trans)(c); + + while (1) { + try(bch2_debugfs_flush_buf(i)); + + /* + * Snapshot the entry under the lock, resolve outside it: path + * resolution takes btree locks, and fsck error paths take + * msgs_lock under those. + */ + struct fsck_damaged_path entry; + bool done; + + scoped_guard(mutex, &c->errors.msgs_lock) { + done = i->iter >= c->errors.damaged_paths.nr; + if (!done) + entry = c->errors.damaged_paths.data[i->iter]; + } + if (done) + break; + + bch2_fsck_damaged_path_to_text(&i->buf, trans, &entry); + i->iter++; + } + + return bch2_debugfs_flush_buf(i) ?: i->ret; +} + +static const struct file_operations fsck_damaged_paths_ops = { + .owner = THIS_MODULE, + .open = bch2_dump_open, + .release = bch2_dump_release, + .read = bch2_fsck_damaged_paths_read, +}; + void bch2_fs_debug_exit(struct bch_fs *c) { if (!IS_ERR_OR_NULL(c->fs_debug_dir)) @@ -870,6 +924,9 @@ void bch2_fs_debug_init(struct bch_fs *c) debugfs_create_file("btree_node_scan", 0400, c->fs_debug_dir, c->btree_debug, &btree_node_scan_ops); + debugfs_create_file("fsck_damaged_paths", 0400, c->fs_debug_dir, + c->btree_debug, &fsck_damaged_paths_ops); + debugfs_create_file("write_points", 0400, c->fs_debug_dir, c->btree_debug, &write_points_ops); diff --git a/fs/debug/sysfs.c b/fs/debug/sysfs.c index bb2d65fc1f..cb59fe6a95 100644 --- a/fs/debug/sysfs.c +++ b/fs/debug/sysfs.c @@ -498,8 +498,11 @@ STORE(bch2_fs) if (attr == &sysfs_trigger_gc) bch2_gc_gens(c); - if (attr == &sysfs_trigger_delete_dead_snapshots) - __bch2_delete_dead_snapshots(c); + if (attr == &sysfs_trigger_delete_dead_snapshots) { + /* debug force: bypass auto_snapshot_deletion; serialize via run_lock */ + scoped_guard(mutex, &c->recovery.run_lock) + __bch2_delete_dead_snapshots(c); + } if (attr == &sysfs_trigger_emergency_read_only) { CLASS(bch_log_msg, msg)(c); @@ -774,6 +777,14 @@ static ssize_t sysfs_opt_show(struct bch_fs *c, u64 v; if (ca) { + if (opt->type == BCH_OPT_STR_MEMBER) { + /* The value lives in the member, not a u64 - render it here: */ + guard(mutex_noio)(&c->sb_lock); + struct bch_member m = bch2_sb_member_get(c->disk_sb.sb, ca->dev_idx); + prt_printf(out, "%.*s\n", (int) opt->member_size, + (char *) &m + opt->member_offset); + return 0; + } if (!((opt->flags & OPT_DEVICE) && opt->get_member)) return bch_err_throw(c, EINVAL_sysfs_opt_not_found); v = bch2_opt_from_sb(c->disk_sb.sb, id, ca->dev_idx); @@ -807,20 +818,22 @@ static ssize_t sysfs_opt_store(struct bch_fs *c, if (unlikely(!enumerated_ref_tryget(&c->writes, BCH_WRITE_REF_sysfs))) return -EROFS; - guard(memalloc_flags)(PF_MEMALLOC_NOFS); + guard(memalloc_flags)(PF_MEMALLOC_NOIO); guard(opt_change_lock)(c); CLASS(opt_change_scope, opt_scope)(c); + char *val = strim(tmp); u64 v; - ret = bch2_opt_parse(c, opt, strim(tmp), &v, NULL) ?: + ret = bch2_opt_parse(c, opt, val, &v, NULL) ?: bch2_opt_hook_pre_set(c, ca, 0, id, v, true, &opt_scope); if (!ret) { - bool is_sb = opt->get_sb || opt->get_member || opt->get_ext; + bool is_sb = opt->get_sb || opt->get_member || opt->get_ext || + opt->type == BCH_OPT_STR_MEMBER; bool changed = false; if (is_sb) { - changed = bch2_opt_set_sb(c, ca, opt, v); + changed = bch2_opt_set_sb(c, ca, opt, v, val); } else if (!ca) { changed = bch2_opt_get_by_id(&c->opts, id) != v; } else { diff --git a/fs/errcode.h b/fs/errcode.h index 1bd7ea7e72..6c8fb65077 100644 --- a/fs/errcode.h +++ b/fs/errcode.h @@ -64,9 +64,6 @@ x(EIO, blockdev_io_error) \ BLK_ERRS() \ x(BCH_ERR_blockdev_io_error, BLK_STS_UNKNOWN) \ - x(EIO, zstd_error) \ - ZSTD_ERRS() \ - x(BCH_ERR_zstd_error, ZSTD_error_unknown) \ x(ERANGE, ERANGE_option_too_small) \ x(ERANGE, ERANGE_option_too_big) \ x(ERANGE, projid_too_big) \ @@ -186,6 +183,7 @@ x(ENOENT, ENOENT_not_directory) \ x(ENOENT, ENOENT_directory_dead) \ x(ENOENT, ENOENT_subvolume) \ + x(ENOENT, ENOENT_subvolume_deleted) \ x(ENOENT, ENOENT_snapshot) \ x(ENOENT, ENOENT_snapshot_tree) \ x(ENOENT, ENOENT_dirent_doesnt_match_inode) \ @@ -291,6 +289,7 @@ x(EINVAL, bucket_size_too_small) \ x(EINVAL, device_size_too_small) \ x(EINVAL, device_size_too_big) \ + x(EINVAL, device_already_resizing) \ x(EINVAL, device_not_a_member_of_filesystem) \ x(EINVAL, device_has_been_removed) \ x(EINVAL, device_splitbrain) \ @@ -310,6 +309,7 @@ x(EINVAL, inode_unpack_error) \ x(EINVAL, inode_not_unlinked) \ x(EINVAL, inode_has_child_snapshot) \ + x(EINVAL, inode_is_subvolume_root) \ x(EINVAL, varint_decode_error) \ x(EINVAL, erasure_coding_found_btree_node) \ x(EINVAL, erasure_coding_stripe_update_err) \ @@ -410,8 +410,8 @@ x(EINVAL, EINVAL_snapshot_delete_bad_topology) \ x(EINVAL, EINVAL_snapshot_parent_missing_child_ptr) \ x(EINVAL, EINVAL_snapshot_child_bad_parent) \ + x(EINVAL, EINVAL_snapshot_edge_to_missing_node) \ x(EINVAL, EINVAL_snapshot_bad_subvol_flag) \ - x(EINVAL, EINVAL_snapshot_subvol_edge_bad) \ x(EINVAL, EINVAL_opt_parse_uint_required) \ x(EINVAL, EINVAL_opt_parse_str_required) \ x(EINVAL, EINVAL_test_zero_nr_or_threads) \ @@ -543,16 +543,21 @@ x(EIO, recompute_checksum) \ x(BCH_ERR_data_read_retry_avoid,decompress) \ x(BCH_ERR_decompress, decompress_exceeded_max_encoded_extent) \ + x(BCH_ERR_decompress, decompress_lz4_old) \ x(BCH_ERR_decompress, decompress_lz4) \ x(BCH_ERR_decompress, decompress_gzip) \ x(BCH_ERR_decompress, decompress_gzip_size_mismatch) \ x(BCH_ERR_decompress, decompress_zstd_src_len_bad) \ x(BCH_ERR_decompress, decompress_zstd_size_mismatch) \ + x(BCH_ERR_decompress, zstd_error) \ + ZSTD_ERRS() \ + x(BCH_ERR_zstd_error, ZSTD_error_unknown) \ x(EIO, data_write) \ x(BCH_ERR_data_write, data_write_io) \ x(BCH_ERR_data_write, data_write_csum) \ x(BCH_ERR_data_write, data_write_invalid_ptr) \ x(BCH_ERR_data_write, data_write_misaligned) \ + x(BCH_ERR_data_write, data_write_need_fresh_buckets) \ x(EIO, data_read) \ x(BCH_ERR_data_read, no_device_to_read_from) \ x(BCH_ERR_data_read, no_devices_valid) \ @@ -585,12 +590,15 @@ x(0, snapshot) \ x(BCH_ERR_snapshot, invalid_snapshot_node) \ x(BCH_ERR_snapshot, snapshot_multiple_descendents) \ + x(BCH_ERR_snapshot, snapshot_lostfound_unreachable) \ x(0, option_needs_open_fs) \ x(0, remove_disk_accounting_entry) \ x(0, nocow_trylock_fail) \ x(BCH_ERR_nocow_trylock_fail, nocow_trylock_contended) \ x(BCH_ERR_nocow_trylock_fail, nocow_trylock_bucket_full) \ - x(EINTR, recovery_cancelled) \ + x(EINTR, cancelled) \ + x(BCH_ERR_cancelled, recovery_cancelled) \ + x(BCH_ERR_cancelled, kthread_cancelled) \ x(0, shutdown_with_errors) \ x(BCH_ERR_shutdown_with_errors, shutdown_with_errors_fixed) \ x(BCH_ERR_shutdown_with_errors, shutdown_with_errors_unfixed) \ diff --git a/fs/fs/acl.c b/fs/fs/acl.c index 0d4a796e10..42db58749e 100644 --- a/fs/fs/acl.c +++ b/fs/fs/acl.c @@ -372,7 +372,7 @@ static int __bch2_set_acl(struct btree_trans *trans, struct posix_acl *acl, int type) { u32 snapshot; - try(bch2_subvol_is_ro_trans(trans, inode->ei_inum.subvol, &snapshot)); + try(bch2_subvol_is_ro_trans(trans, inode_inum(inode).subvol, &snapshot)); CLASS(btree_iter_uninit, inode_iter)(trans); struct bch_inode_unpacked inode_u; diff --git a/fs/fs/check.c b/fs/fs/check.c index 491cbacd65..c4ed3e245c 100644 --- a/fs/fs/check.c +++ b/fs/fs/check.c @@ -112,26 +112,12 @@ static int find_snapshot_tree_subvol(struct btree_trans *trans, static struct qstr lostfound_str = QSTR("lost+found"); -static int create_lostfound(struct btree_trans *trans, u32 snapshot_tree, +static int create_lostfound(struct btree_trans *trans, u32 snapshot, subvol_inum root_inum, struct bch_inode_unpacked *root_inode, struct bch_inode_unpacked *lostfound) { struct bch_fs *c = trans->c; - /* - * We always create lost+found in the root snapshot; we don't want - * different branches of the snapshot tree to have different lost+found - */ - struct bch_snapshot_tree st; - try(bch2_snapshot_tree_lookup(trans, snapshot_tree, &st)); - - u32 snapshot; - if (bch2_snapshot_live_descendent(c, le32_to_cpu(st.root_snapshot), &snapshot) || - !snapshot) { - bch_err(c, "snapshot tree %u has no live snapshot, cannot create lost+found", - snapshot_tree); - return bch_err_throw(c, ENOENT_snapshot); - } CLASS(bch_log_msg_level, msg)(c, LOGLEVEL_notice); prt_printf(&msg.m, "creating "); @@ -145,8 +131,6 @@ static int create_lostfound(struct btree_trans *trans, u32 snapshot_tree, lostfound->bi_dir = root_inode->bi_inum; lostfound->bi_snapshot = snapshot; - root_inode->bi_nlink++; - CLASS(btree_iter_uninit, lostfound_iter)(trans); try(bch2_inode_create(trans, &lostfound_iter, lostfound, snapshot, inode_opt_get(c, root_inode, inodes_32bit))); @@ -154,17 +138,171 @@ static int create_lostfound(struct btree_trans *trans, u32 snapshot_tree, bch2_btree_iter_set_snapshot(&lostfound_iter, snapshot); try(bch2_btree_iter_traverse(&lostfound_iter)); - try(bch2_dirent_create_snapshot(trans, - 0, snapshot, root_inode, + int ret = bch2_dirent_create_snapshot(trans, + root_inum.subvol, snapshot, root_inode, mode_to_type(lostfound->bi_mode), &lostfound_str, lostfound->bi_inum, &lostfound->bi_dir_offset, BTREE_UPDATE_internal_snapshot_node| - STR_HASH_must_create)); + STR_HASH_must_create); + if (ret) { + if (!bch2_err_matches(ret, BCH_ERR_transaction_restart)) { + msg.loglevel = LOGLEVEL_err; + prt_printf(&msg.m, "\nerror creating dirent: %s", bch2_err_str(ret)); + } + return ret; + } + + return bch2_inode_write_flags(trans, &lostfound_iter, lostfound, + BTREE_UPDATE_internal_snapshot_node); +} + +/* + * The snapshot tree has a lost+found, but @snapshot hasn't: it was deleted + * there. Give @snapshot a dirent for the same inode - one lost+found per tree + * is the invariant, not one dirent. + * + * A fresh dirent, deliberately, rather than removing the whiteout in place: + * dirents are a hash table, so let the table pick the slot. It goes back into + * the slot that was freed in the normal case, and probes past whatever took it + * otherwise. One inode with different dirent positions in different snapshots + * is what a directory renamed after a snapshot already looks like. + */ +static int restore_lostfound(struct btree_trans *trans, u32 snapshot, + u32 root_snapshot, + subvol_inum root_inum, + struct bch_inode_unpacked *root_inode, + u64 inum, unsigned d_type, + struct bch_inode_unpacked *lostfound) +{ + struct bch_fs *c = trans->c; + + if (d_type != DT_DIR) { + bch_err(c, "lost+found in snapshot %u is not a directory (type %u), cannot restore it in snapshot %u", + root_snapshot, d_type, snapshot); + return bch_err_throw(c, ENOENT_not_directory); + } + + /* + * The inode is normally still visible here - only the dirent was + * shadowed - but if the directory was deleted rather than unlinked it's + * shadowed too, and we have to go get it from the root snapshot. + */ + int ret = bch2_inode_find_by_inum_snapshot(trans, inum, snapshot, lostfound, 0); + if (bch2_err_matches(ret, ENOENT)) + ret = bch2_inode_find_by_inum_snapshot(trans, inum, root_snapshot, lostfound, 0); + if (ret) { + bch_err_msg(c, ret, "looking up lost+found inode %llu in snapshot %u or %u", + inum, snapshot, root_snapshot); + return ret; + } + + CLASS(bch_log_msg_level, msg)(c, LOGLEVEL_notice); + prt_printf(&msg.m, "restoring "); + try(bch2_inum_to_path(trans, root_inum, &msg.m)); + prt_printf(&msg.m, "/lost+found in subvol %llu snapshot %u: inode %llu, deleted here, still in snapshot %u", + root_inum.subvol, snapshot, inum, root_snapshot); + + lostfound->bi_dir = root_inode->bi_inum; + lostfound->bi_snapshot = snapshot; + + ret = bch2_dirent_create_snapshot(trans, + root_inum.subvol, snapshot, root_inode, + d_type, + &lostfound_str, + inum, + &lostfound->bi_dir_offset, + BTREE_UPDATE_internal_snapshot_node| + STR_HASH_must_create); + if (ret) { + if (!bch2_err_matches(ret, BCH_ERR_transaction_restart)) { + msg.loglevel = LOGLEVEL_err; + prt_printf(&msg.m, "\nerror creating dirent: %s", bch2_err_str(ret)); + } + return ret; + } + + return __bch2_fsck_write_inode(trans, lostfound); +} + +/* + * lost+found is a subdirectory of the root inode in @snapshot, so the root + * inode gains a link there. Take it on the version @snapshot sees and write it + * back at @snapshot: writing it where that version lives would hand the link to + * sibling branches that haven't got a lost+found. + */ +static int lostfound_dir_link(struct btree_trans *trans, u64 dir_inum, u32 snapshot) +{ + struct bch_inode_unpacked dir; + try(bch2_inode_find_by_inum_snapshot(trans, dir_inum, snapshot, &dir, 0)); + + dir.bi_nlink++; + dir.bi_snapshot = snapshot; + return __bch2_fsck_write_inode(trans, &dir); +} + +/* + * @snapshot needs a lost+found and hasn't got one. There's one per snapshot + * tree, in the tree's root snapshot so that every branch inherits the same one, + * so either the tree hasn't got one at all or it has and it was deleted here. + */ +static int create_or_restore_lostfound(struct btree_trans *trans, u32 snapshot_tree, + u32 snapshot, + subvol_inum root_inum, + struct bch_inode_unpacked *root_inode, + struct bch_hash_info root_hash_info, + struct bch_inode_unpacked *lostfound) +{ + struct bch_fs *c = trans->c; + + struct bch_snapshot_tree st; + try(bch2_snapshot_tree_lookup(trans, snapshot_tree, &st)); - try(bch2_inode_write_flags(trans, &lostfound_iter, lostfound, - BTREE_UPDATE_internal_snapshot_node)); + u32 root_snapshot; + if (bch2_snapshot_live_descendent(c, le32_to_cpu(st.root_snapshot), &root_snapshot) || + !root_snapshot) { + bch_err(c, "snapshot tree %u has no live snapshot, cannot create lost+found", + snapshot_tree); + return bch_err_throw(c, ENOENT_snapshot); + } + + /* + * Keeping lost+found in the root snapshot only gives every branch the + * same one if they all inherit from it. If this snapshot doesn't, we + * can neither find what's there nor create something it will see. + */ + if (!bch2_snapshot_is_ancestor(trans, snapshot, root_snapshot)) { + bch_err(c, "lost+found for snapshot %u belongs in snapshot %u, which it does not inherit from" + " (snapshot tree %u, root snapshot %u)", + snapshot, root_snapshot, snapshot_tree, le32_to_cpu(st.root_snapshot)); + return bch_err_throw(c, snapshot_lostfound_unreachable); + } + + /* + * root_hash_info came from the root inode as @snapshot sees it, and + * we're about to hash with it in another snapshot: fine, because all + * versions of an inode must have the same hash seed and type, and + * bch2_check_dirents has already run and repaired any that didn't + * (check_inode_hash_info_matches_root()). + */ + u64 inum = 0; + unsigned d_type = 0; + u32 dirent_snapshot = 0; + int ret = lookup_dirent_in_snapshot(trans, root_hash_info, root_inum, + &lostfound_str, &inum, &d_type, root_snapshot); + if (!ret) { + dirent_snapshot = snapshot; + ret = restore_lostfound(trans, snapshot, root_snapshot, root_inum, + root_inode, inum, d_type, lostfound); + } else if (bch2_err_matches(ret, ENOENT)) { + dirent_snapshot = root_snapshot; + ret = create_lostfound(trans, root_snapshot, root_inum, root_inode, lostfound); + } + if (ret) + return ret; + + try(lostfound_dir_link(trans, root_inum.inum, dirent_snapshot)); return bch2_trans_commit_lazy(trans, NULL, NULL, BCH_TRANS_COMMIT_no_enospc); } @@ -185,13 +323,13 @@ static int lookup_lostfound(struct btree_trans *trans, u32 snapshot, if (ret) return ret; - struct bch_subvolume subvol; - ret = bch2_subvolume_get(trans, subvolid, false, &subvol); + struct bkey_i_subvolume subvol; + ret = bch2_subvolume_get_key(trans, subvolid, false, &subvol); bch_err_msg(c, ret, "looking up subvol %u for snapshot %u", subvolid, snapshot); if (ret) return ret; - if (!subvol.inode) { + if (!subvol.v.inode) { struct bkey_i_subvolume *subvol = errptr_try(bch2_bkey_get_mut_typed(trans, BTREE_ID_subvolumes, POS(0, subvolid), 0, subvolume)); @@ -201,15 +339,24 @@ static int lookup_lostfound(struct btree_trans *trans, u32 snapshot, subvol_inum root_inum = { .subvol = subvolid, - .inum = le64_to_cpu(subvol.inode) + .inum = le64_to_cpu(subvol.v.inode) }; struct bch_inode_unpacked root_inode; ret = bch2_inode_find_by_inum_snapshot(trans, root_inum.inum, snapshot, &root_inode, 0); - bch_err_msg(c, ret, "looking up root inode %llu for subvol %u", - root_inum.inum, subvolid); - if (ret) + if (ret) { + /* + * The inum came out of the subvolume key, so print the key: + * which snapshot it points at is what says whether the root + * inode is missing or we're looking in the wrong place. + */ + CLASS(printbuf, buf)(); + + bch2_bkey_val_to_text(&buf, c, bkey_i_to_s_c(&subvol.k_i)); + bch_err_msg(c, ret, "looking up root inode %llu in snapshot %u, from\n %s", + root_inum.inum, snapshot, buf.buf); return ret; + } struct bch_hash_info root_hash_info; try(bch2_hash_info_init(c, &root_inode, &root_hash_info)); @@ -223,8 +370,9 @@ static int lookup_lostfound(struct btree_trans *trans, u32 snapshot, * We always create lost_found in its own transaction; this will * return a transaction restart: */ - ret = create_lostfound(trans, snapshot_tree, root_inum, &root_inode, lostfound); - bch_err_msg(c, ret, "creating lost+found"); + ret = create_or_restore_lostfound(trans, snapshot_tree, snapshot, root_inum, + &root_inode, root_hash_info, lostfound); + bch_err_msg(c, ret, "getting lost+found for snapshot %u", snapshot); return ret; } @@ -326,8 +474,7 @@ int bch2_reattach_inode(struct btree_trans *trans, struct bch_inode_unpacked *in subvol->v.fs_path_parent = BCACHEFS_ROOT_SUBVOL; - u64 root_inum; - try(subvol_lookup(trans, inode->bi_parent_subvol, &dirent_snapshot, &root_inum)); + try(bch2_subvolume_get_snapshot(trans, inode->bi_parent_subvol, &dirent_snapshot)); snprintf(name_buf, sizeof(name_buf), "subvol-%u", inode->bi_subvol); } else { @@ -338,33 +485,91 @@ int bch2_reattach_inode(struct btree_trans *trans, struct bch_inode_unpacked *in bch_verbose(c, "got lostfound inum %llu", lostfound.bi_inum); - lostfound.bi_nlink += S_ISDIR(inode->bi_mode); + struct qstr name = QSTR(name_buf); + + /* + * Adopt instead of create: the child fixup loop below commits in + * chunks (bch2_trans_commit_lazy_if_full()), so a re-drive can find + * the reattach dirent already committed - at our snapshot or an + * ancestor, when the committed fixups moved the oldest-needing- + * reattach point down. The name is deterministic, so look it up: + * adopting avoids the STR_HASH_must_create collision and re-bumping + * lost+found's nlink. + */ + struct bch_hash_info lostfound_hash; + try(bch2_hash_info_init(c, &lostfound, &lostfound_hash)); + + bool adopted = false; + { + CLASS(btree_iter_uninit, d_iter)(trans); + struct bkey_s_c k = bch2_hash_lookup_in_snapshot(trans, &d_iter, + bch2_dirent_hash_desc, &lostfound_hash, + (subvol_inum) { inode->bi_parent_subvol, lostfound.bi_inum }, + &name, 0, dirent_snapshot); + ret = bkey_err(k); + if (ret && !bch2_err_matches(ret, ENOENT)) + return ret; + + if (!ret) { + struct bkey_s_c_dirent d = bkey_s_c_to_dirent(k); + u64 target = d.v->d_type == DT_SUBVOL + ? le32_to_cpu(d.v->d_child_subvol) + : le64_to_cpu(d.v->d_inum); + + if (target != (inode->bi_subvol ?: inode->bi_inum)) { + CLASS(printbuf, buf)(); + bch2_bkey_val_to_text(&buf, c, k); + bch_err(c, "reattaching inode %llu:%u: lost+found entry %s exists but points elsewhere:\n%s", + inode->bi_inum, inode->bi_snapshot, name_buf, buf.buf); + return bch_err_throw(c, fsck_repair_unimplemented); + } - /* ensure lost+found inode is also present in inode snapshot */ - if (!inode->bi_subvol) { - BUG_ON(!bch2_snapshot_is_ancestor(trans, inode->bi_snapshot, lostfound.bi_snapshot)); - lostfound.bi_snapshot = inode->bi_snapshot; + inode->bi_dir = lostfound.bi_inum; + inode->bi_dir_offset = d.k->p.offset; + adopted = true; + } } - try(__bch2_fsck_write_inode(trans, &lostfound)); + /* + * is_subdir_for_nlink(), not S_ISDIR(): a subvolume root is named by a + * DT_SUBVOL dirent, which doesn't count towards its parent's link + * count. Bumping it here for one leaves check_nlinks() to disagree. + */ + if (!adopted) + lostfound.bi_nlink += is_subdir_for_nlink(inode); - struct qstr name = QSTR(name_buf); + /* + * Ensure lost+found has an inode version in the snapshot we're about to + * create the dirent in, or we leave a key in a snapshot whose inode only + * exists in an ancestor - snapshot_key_missing_inode_snapshot, which the + * next check_dirents has to clean up after us. + * + * dirent_snapshot is the inode's own snapshot for an ordinary inode, and + * the parent subvolume's for a subvolume root (above); lookup_lostfound() + * resolved lost+found from it, so it is at worst an ancestor of it. + */ + BUG_ON(!bch2_snapshot_is_ancestor(trans, dirent_snapshot, lostfound.bi_snapshot)); + lostfound.bi_snapshot = dirent_snapshot; - inode->bi_dir = lostfound.bi_inum; + try(__bch2_fsck_write_inode(trans, &lostfound)); - ret = bch2_dirent_create_snapshot(trans, - inode->bi_parent_subvol, - dirent_snapshot, - &lostfound, - inode_d_type(inode), - &name, - inode->bi_subvol ?: inode->bi_inum, - &inode->bi_dir_offset, - BTREE_UPDATE_internal_snapshot_node| - STR_HASH_must_create); - if (ret) { - bch_err_msg(c, ret, "error creating dirent"); - return ret; + if (!adopted) { + inode->bi_dir = lostfound.bi_inum; + + ret = bch2_dirent_create_snapshot(trans, + inode->bi_parent_subvol, + dirent_snapshot, + &lostfound, + inode_d_type(inode), + &name, + inode->bi_subvol ?: inode->bi_inum, + &inode->bi_dir_offset, + BTREE_UPDATE_internal_snapshot_node| + STR_HASH_must_create); + if (ret) { + bch_err_msg(c, ret, "error creating dirent"); + return ret; + } } try(__bch2_fsck_write_inode(trans, inode)); @@ -374,7 +579,10 @@ int bch2_reattach_inode(struct btree_trans *trans, struct bch_inode_unpacked *in try(bch2_inum_snapshot_to_path(trans, inode->bi_inum, inode->bi_snapshot, NULL, &buf)); - bch_info(c, "reattached at %s", buf.buf); + if (adopted) + bch_verbose(c, "resuming reattach at %s", buf.buf); + else + bch_info(c, "reattached at %s", buf.buf); } /* @@ -394,6 +602,18 @@ int bch2_reattach_inode(struct btree_trans *trans, struct bch_inode_unpacked *in if (k.k->p.offset != inode->bi_inum) break; + /* + * This loop batches an update per descendant snapshot + * version into one transaction; a fat chain overflows + * the bump allocator. Commit once substantial work has + * accumulated - the restart re-drives us, the adopt + * path above resumes without duplicating the reattach + * dirent, and already-fixed children are skipped + * below: + */ + try(bch2_trans_commit_lazy_if_full(trans, NULL, NULL, + BCH_TRANS_COMMIT_no_enospc)); + if (!bkey_is_inode(k.k) || !bch2_snapshot_is_ancestor(trans, k.k->p.snapshot, inode->bi_snapshot) || snapshot_list_has_ancestor(trans, &whiteouts_done, k.k->p.snapshot)) @@ -402,6 +622,18 @@ int bch2_reattach_inode(struct btree_trans *trans, struct bch_inode_unpacked *in struct bch_inode_unpacked child_inode; bch2_inode_unpack(c, k, &child_inode); + /* + * Fixed by a previous partial commit: its backpointer + * already names our reattach dirent. Must be checked + * before inode_should_reattach() - having a + * backpointer, it would fall into the whiteout arm + * and turn the committed fixup into a dangling + * backpointer: + */ + if (child_inode.bi_dir == inode->bi_dir && + child_inode.bi_dir_offset == inode->bi_dir_offset) + continue; + if (!inode_should_reattach(&child_inode)) { try(maybe_delete_dirent(trans, SPOS(lostfound.bi_inum, inode->bi_dir_offset, @@ -422,7 +654,7 @@ int bch2_reattach_inode(struct btree_trans *trans, struct bch_inode_unpacked *in return ret; } -static int reconstruct_subvol(struct btree_trans *trans, u32 snapshotid, u32 subvolid, u64 inum) +int bch2_reconstruct_subvol(struct btree_trans *trans, u32 snapshotid, u32 subvolid, u64 inum) { struct bch_fs *c = trans->c; @@ -432,25 +664,42 @@ static int reconstruct_subvol(struct btree_trans *trans, u32 snapshotid, u32 sub } /* - * If inum isn't set, that means we're being called from check_dirents, - * not check_inodes - the root of this subvolume doesn't exist or we - * would have found it there: + * Without an inum from the caller, find the root inode rather than + * minting one: the inode carrying bi_subvol == subvolid is the root, + * and when it's the subvolume key that went missing that inode is + * still there. Creating a second one would leave two claimants for the + * same subvolume and the real contents orphaned behind the new empty + * root. + * + * It can't be deferred to a later pass either - bch2_subvolume_validate() + * rejects a subvolume key with inode == 0 (subvol_inode_bad), so the + * key can't be written at all until we know it. */ if (!inum) { - CLASS(btree_iter_uninit, inode_iter)(trans); - struct bch_inode_unpacked new_inode; + struct bkey_s_c k; + int ret = 0; - bch2_inode_init_early(c, &new_inode); - bch2_inode_init_late(c, &new_inode, bch2_current_time(c), 0, 0, S_IFDIR|0755, 0, NULL); + for_each_btree_key_norestart(trans, iter, BTREE_ID_inodes, POS_MIN, + BTREE_ITER_prefetch|BTREE_ITER_all_snapshots, k, ret) { + if (!bkey_is_inode(k.k)) + continue; - new_inode.bi_subvol = subvolid; + struct bch_inode_unpacked candidate; + bch2_inode_unpack(c, k, &candidate); - try(bch2_inode_create(trans, &inode_iter, &new_inode, snapshotid, false)); - bch2_btree_iter_set_snapshot(&inode_iter, snapshotid); - try(bch2_btree_iter_traverse(&inode_iter)); - try(bch2_inode_write(trans, &inode_iter, &new_inode)); + if (candidate.bi_subvol == subvolid) { + inum = candidate.bi_inum; + break; + } + } + if (ret) + return ret; - inum = new_inode.bi_inum; + if (!inum) { + bch_err(c, "no root inode found for subvol %u, can't reconstruct", + subvolid); + return bch_err_throw(c, fsck_repair_unimplemented); + } } bch_info(c, "reconstructing subvol %u with root inode %llu", subvolid, inum); @@ -501,7 +750,9 @@ static int reconstruct_inode(struct btree_trans *trans, enum btree_id btree, u32 CLASS(btree_iter, iter)(trans, BTREE_ID_extents, SPOS(inum, U64_MAX, snapshot), 0); struct bkey_s_c k = bkey_try(bch2_btree_iter_peek_prev_min(&iter, POS(inum, 0))); - i_size = k.k->p.offset << 9; + /* may race with repair deleting the extents that triggered us: */ + if (k.k) + i_size = k.k->p.offset << 9; break; } case BTREE_ID_dirents: @@ -701,8 +952,10 @@ lookup_inode_for_snapshot(struct btree_trans *trans, struct inode_walker *w, str { struct bch_fs *c = trans->c; + u32 k_snapshot = bch2_snapshot_redundant_interior(c, k.k->p.snapshot) ?: k.k->p.snapshot; + struct inode_walker_entry *i = darray_find_p(w->inodes, i, - bch2_snapshot_is_ancestor(trans, k.k->p.snapshot, i->inode.bi_snapshot)); + bch2_snapshot_is_ancestor(trans, k_snapshot, i->inode.bi_snapshot)); if (!i) return NULL; @@ -710,7 +963,9 @@ lookup_inode_for_snapshot(struct btree_trans *trans, struct inode_walker *w, str CLASS(printbuf, buf)(); int ret = 0; - if (fsck_err_on(k.k->p.snapshot != i->inode.bi_snapshot, + u32 inode_snapshot = bch2_snapshot_redundant_interior(c, i->inode.bi_snapshot) ?: i->inode.bi_snapshot; + + if (fsck_err_on(k_snapshot != inode_snapshot, trans, snapshot_key_missing_inode_snapshot, "have key for inode %llu:%u but have inode in ancestor snapshot %u\n" "unexpected because we should always update the inode when we update a key in that inode\n" @@ -805,13 +1060,60 @@ int bch2_fsck_update_backpointers(struct btree_trans *trans, CLASS(inode_walker, target)(); if (d->v.d_type == DT_SUBVOL) { - bch_err(trans->c, "%s does not support DT_SUBVOL", __func__); - return bch_err_throw(trans->c, fsck_repair_unimplemented); + /* + * A subvolume dirent's backpointer lives on the child + * subvolume's root inode (bi_dir_offset), same as a regular + * inode - see bch2_inode_get_dirent(). Resolve child_subvol -> root + * inode and update it. A dangling subvol dirent (subvol or root + * inode gone) is check_subvols/check_dirents' problem, not ours. + */ + struct bch_subvolume subvol; + int ret = bch2_subvolume_get(trans, le32_to_cpu(d->v.d_child_subvol), + false, &subvol); + if (bch2_err_matches(ret, ENOENT)) + return 0; + if (ret) + return ret; + + struct bch_inode_unpacked root_inode; + ret = bch2_inode_find_by_inum_snapshot(trans, le64_to_cpu(subvol.inode), + le32_to_cpu(subvol.snapshot), + &root_inode, 0); + if (bch2_err_matches(ret, ENOENT)) + return 0; + if (ret) + return ret; + + if (root_inode.bi_dir == d->k.p.inode && + root_inode.bi_dir_offset == d->k.p.offset) + return 0; + + root_inode.bi_dir = d->k.p.inode; + root_inode.bi_dir_offset = d->k.p.offset; + return __bch2_fsck_write_inode(trans, &root_inode); } else { try(get_visible_inodes(trans, &target, s, le64_to_cpu(d->v.d_inum))); + /* + * A backpointer is the (bi_dir, bi_dir_offset) pair - compare + * and set both, or an offset match into the wrong directory + * skips a broken backpointer, and an offset-only write + * manufactures one. + * + * Skip before the write: __bch2_fsck_write_inode allocates a + * bkey_inode_buf of trans mem per call, and this loop runs once + * per visible snapshot version in one transaction - an + * already-correct backpointer must cost nothing, both to bound + * trans mem and so a re-run over partially-repaired state + * shrinks instead of repeating the whole batch. + */ darray_for_each(target.inodes, i) { - i->inode.bi_dir_offset = d->k.p.offset; + if (i->inode.bi_dir == d->k.p.inode && + i->inode.bi_dir_offset == d->k.p.offset) + continue; + + i->inode.bi_dir = d->k.p.inode; + i->inode.bi_dir_offset = d->k.p.offset; try(__bch2_fsck_write_inode(trans, &i->inode)); } @@ -819,21 +1121,6 @@ int bch2_fsck_update_backpointers(struct btree_trans *trans, } } -static struct bkey_s_c_dirent inode_get_dirent(struct btree_trans *trans, - struct btree_iter *iter, - struct bch_inode_unpacked *inode, - u32 *snapshot) -{ - if (inode->bi_subvol) { - u64 inum; - int ret = subvol_lookup(trans, inode->bi_parent_subvol, snapshot, &inum); - if (ret) - return ((struct bkey_s_c_dirent) { .k = ERR_PTR(ret) }); - } - - return dirent_get_by_pos(trans, iter, SPOS(inode->bi_dir, inode->bi_dir_offset, *snapshot)); -} - static int check_inode_deleted_list(struct btree_trans *trans, struct bpos p) { CLASS(btree_iter, iter)(trans, BTREE_ID_deleted_inodes, p, 0); @@ -850,7 +1137,7 @@ static int check_inode_dirent_inode(struct btree_trans *trans, u32 inode_snapshot = inode->bi_snapshot; CLASS(btree_iter_uninit, dirent_iter)(trans); - struct bkey_s_c_dirent d = inode_get_dirent(trans, &dirent_iter, inode, &inode_snapshot); + struct bkey_s_c_dirent d = bch2_inode_get_dirent(trans, &dirent_iter, inode, &inode_snapshot); int ret = bkey_err(d); if (ret && !bch2_err_matches(ret, ENOENT)) return ret; @@ -872,12 +1159,14 @@ static int check_inode_dirent_inode(struct btree_trans *trans, return 0; } - if (fsck_err_on(ret, - trans, inode_points_to_missing_dirent, + if (inode_fsck_err_on(ret, + trans, SPOS(0, inode->bi_inum, inode->bi_snapshot), + inode_points_to_missing_dirent, "inode points to missing dirent\n%s", (bch2_inode_unpacked_to_text(&buf, inode), buf.buf)) || - fsck_err_on(!ret && dirent_points_to_inode_nowarn(c, d, inode), - trans, inode_points_to_wrong_dirent, + inode_fsck_err_on(!ret && dirent_points_to_inode_nowarn(c, d, inode), + trans, SPOS(0, inode->bi_inum, inode->bi_snapshot), + inode_points_to_wrong_dirent, "%s", (printbuf_reset(&buf), bch2_dirent_inode_mismatch_msg(&buf, c, d, inode), @@ -893,6 +1182,27 @@ static int check_inode_dirent_inode(struct btree_trans *trans, *write_inode = true; } + if (!ret && + !dirent_points_to_inode_nowarn(c, d, inode) && + fsck_err_on(inode->bi_flags & BCH_INODE_unlinked, + trans, inode_unlinked_but_has_dirent, + "inode unlinked but has dirent\n%s", + (printbuf_reset(&buf), + bch2_inode_unpacked_to_text(&buf, inode), + prt_newline(&buf), + bch2_bkey_val_to_text(&buf, c, d.s_c), + buf.buf))) { + /* + * The dirent was just verified to point at this inode, so the + * unlinked flag is wrong - and the flag clear is the complete + * repair: bi_nlink counts links beyond the first, so this + * yields nlink 1 (check_nlinks recounts hardlinks), and the + * inode trigger removes the deleted_inodes entry. + */ + inode->bi_flags &= ~BCH_INODE_unlinked; + *write_inode = true; + } + ret = 0; fsck_err: bch_err_fn(c, ret); @@ -963,38 +1273,45 @@ static int check_inode(struct btree_trans *trans, if (bch2_inode_has_backpointer(&u)) try(check_inode_dirent_inode(trans, &u, &do_update)); - if (fsck_err_on(bch2_inode_has_backpointer(&u) && - (u.bi_flags & BCH_INODE_unlinked), - trans, inode_unlinked_but_has_dirent, - "inode unlinked but has dirent\n%s", - (printbuf_reset(&buf), - bch2_inode_unpacked_to_text(&buf, &u), - buf.buf))) { - u.bi_flags &= ~BCH_INODE_unlinked; - do_update = true; - } - if (S_ISDIR(u.bi_mode) && (u.bi_flags & BCH_INODE_unlinked)) { - /* Check for this early so that check_unreachable_inode() will reattach it */ - - ret = bch2_empty_dir_snapshot(trans, k.k->p.offset, 0, k.k->p.snapshot); - if (ret && ret != -BCH_ERR_ENOTEMPTY_dir_not_empty) + /* + * BCH_INODE_unlinked is allowed on a directory only if it's a + * subvolume root and the subvolume is unlinked - the root is + * then legitimately non-empty, since the snapshot sweep is + * what deletes the contents. Anything else: strip the flag so + * check_unreachable_inodes() reattaches it. + */ + ret = bch2_inode_is_subvolume_root(&u) + ? bch2_subvolume_is_unlinked(trans, u.bi_subvol) + : 0; + if (ret < 0) return ret; - fsck_err_on(ret, trans, inode_dir_unlinked_but_not_empty, - "dir unlinked but not empty\n%s", - (printbuf_reset(&buf), - bch2_inode_unpacked_to_text(&buf, &u), - buf.buf)); - u.bi_flags &= ~BCH_INODE_unlinked; - do_update = true; + if (!ret) { + /* Check for this early so that check_unreachable_inode() will reattach it */ + + ret = bch2_empty_dir_snapshot(trans, k.k->p.offset, 0, k.k->p.snapshot); + if (ret && ret != -BCH_ERR_ENOTEMPTY_dir_not_empty) + return ret; + + inode_fsck_err_on(ret, trans, k.k->p, + inode_dir_unlinked_but_not_empty, + "dir unlinked but not empty\n%s", + (printbuf_reset(&buf), + bch2_inode_unpacked_to_text(&buf, &u), + buf.buf)); + u.bi_flags &= ~BCH_INODE_unlinked; + do_update = true; + } ret = 0; } if (fsck_err_on(S_ISDIR(u.bi_mode) && u.bi_size, trans, inode_dir_has_nonzero_i_size, - "directory %llu:%u with nonzero i_size %lli", - u.bi_inum, u.bi_snapshot, u.bi_size)) { + "directory with nonzero i_size\n%s", + (printbuf_reset(&buf), + bch2_inode_unpacked_to_text(&buf, &u), + buf.buf))) { u.bi_size = 0; do_update = true; } @@ -1018,7 +1335,13 @@ static int check_inode(struct btree_trans *trans, } ret = 0; + /* + * Unlinked subvolume roots are skipped here: their deletion belongs + * to the subvolume path (check_subvols() resumes it after a crash), + * not the inode reaper or the deleted_inodes btree: + */ if ((u.bi_flags & BCH_INODE_unlinked) && + !bch2_inode_is_subvolume_root(&u) && !(u.bi_flags & BCH_INODE_has_child_snapshot)) { if (!test_bit(BCH_FS_started, &c->flags)) { /* @@ -1037,8 +1360,10 @@ static int check_inode(struct btree_trans *trans, fsck_err_on(!ret, trans, unlinked_inode_not_on_deleted_list, - "inode %llu:%u unlinked, but not on deleted list", - u.bi_inum, k.k->p.snapshot); + "inode unlinked, but not on deleted list\n%s", + (printbuf_reset(&buf), + bch2_inode_unpacked_to_text(&buf, &u), + buf.buf)); try(bch2_btree_bit_mod_buffered(trans, BTREE_ID_deleted_inodes, k.k->p, 1)); ret = 0; @@ -1049,8 +1374,10 @@ static int check_inode(struct btree_trans *trans, if (fsck_err_on(!ret, trans, inode_unlinked_and_not_open, - "inode %llu:%u unlinked and not open", - u.bi_inum, u.bi_snapshot)) { + "inode unlinked and not open\n%s", + (printbuf_reset(&buf), + bch2_inode_unpacked_to_text(&buf, &u), + buf.buf))) { ret = bch2_inode_rm_snapshot(trans, u.bi_inum, iter->pos.snapshot); bch_err_msg(c, ret, "in fsck deleting inode"); return ret; @@ -1063,8 +1390,10 @@ static int check_inode(struct btree_trans *trans, (u.bi_subvol == 0 || u.bi_subvol == BCACHEFS_ROOT_SUBVOL), trans, inode_bi_parent_nonzero, - "inode %llu:%u has subvol %u but nonzero parent subvol %u", - u.bi_inum, k.k->p.snapshot, u.bi_subvol, u.bi_parent_subvol)) { + "inode has nonzero bi_parent_subvol but is not a subvolume root\n%s", + (printbuf_reset(&buf), + bch2_inode_unpacked_to_text(&buf, &u), + buf.buf))) { u.bi_parent_subvol = 0; do_update = true; } @@ -1075,8 +1404,11 @@ static int check_inode(struct btree_trans *trans, #undef x if (fsck_err_on((bool) (u.bi_flags & BCH_INODE_has_inode_opts) != has_opts, trans, inode_has_inode_opts_flag_wrong, - "inode %llu:%u has_inode_opts flag wrong, should be %u", - u.bi_inum, u.bi_snapshot, has_opts)) { + "inode has_inode_opts flag wrong, should be %u\n%s", + has_opts, + (printbuf_reset(&buf), + bch2_inode_unpacked_to_text(&buf, &u), + buf.buf))) { u.bi_flags &= ~BCH_INODE_has_inode_opts; if (has_opts) u.bi_flags |= BCH_INODE_has_inode_opts; @@ -1096,8 +1428,10 @@ static int check_inode(struct btree_trans *trans, if (has < 0) return has; if (fsck_err_on(!has, trans, inode_has_access_acl_flag_wrong, - "inode %llu:%u has BCH_INODE_has_access_acl set but no acl xattr", - u.bi_inum, u.bi_snapshot)) { + "inode has BCH_INODE_has_access_acl set but no acl xattr\n%s", + (printbuf_reset(&buf), + bch2_inode_unpacked_to_text(&buf, &u), + buf.buf))) { u.bi_flags &= ~BCH_INODE_has_access_acl; do_update = true; } @@ -1109,38 +1443,107 @@ static int check_inode(struct btree_trans *trans, if (has < 0) return has; if (fsck_err_on(!has, trans, inode_has_default_acl_flag_wrong, - "inode %llu:%u has BCH_INODE_has_default_acl set but no acl xattr", - u.bi_inum, u.bi_snapshot)) { + "inode has BCH_INODE_has_default_acl set but no acl xattr\n%s", + (printbuf_reset(&buf), + bch2_inode_unpacked_to_text(&buf, &u), + buf.buf))) { u.bi_flags &= ~BCH_INODE_has_default_acl; do_update = true; } } - if (u.bi_subvol && bch2_snapshot_is_leaf(c, u.bi_snapshot)) { + /* + * Not gated on the snapshot being a leaf: taking a snapshot rewrites + * the root inode of the new subvolume, not of the old, so a live + * subvolume's root inode key stays at a node that has since become + * interior. Leaf-ness therefore skipped this block for every subvolume + * that had ever been snapshotted - so a lost subvolume key was never + * reconstructed and bi_subvol was never validated for exactly the + * subvolumes with the most history behind them. + * + * Live versus stale is decided below instead, by inode_bi_subvol_wrong: + * the subvolume's snapshot has to have this key's snapshot as an + * ancestor, which is the actual question leaf-ness was standing in for. + */ + if (u.bi_subvol) { struct bch_subvolume s; ret = bch2_subvolume_get(trans, u.bi_subvol, false, &s); if (ret && !bch2_err_matches(ret, ENOENT)) return ret; - if (ret && (c->sb.btrees_lost_data & BIT_ULL(BTREE_ID_subvolumes))) { + struct bch_snapshot snapshot; + int snapshot_ret = bch2_snapshot_lookup(trans, u.bi_snapshot, &snapshot); + if (snapshot_ret && !bch2_err_matches(snapshot_ret, ENOENT)) + return snapshot_ret; + + /* + * A missing subvolume is reconstructed in two cases. If the + * subvolumes btree is known to have lost data, reconstruct. Or + * if this root inode names the subvolume and the live snapshot + * it lives at names the same subvolume in its backref, + * reconstruct: two keys point at the edge and only the + * subvolume key is gone. + * + * If the snapshot is will_delete, don't - there the missing + * subvolume is a deletion in flight, and reconstructing it live + * would revert the deletion; the sweep owns those keys. + * Anything else falls through to the conservative arms below, + * which strip the reference. + */ + bool snapshot_agrees = !snapshot_ret && + bch2_snapshot_state_compat(&snapshot) == SNAPSHOT_STATE_live && + le32_to_cpu(snapshot.subvol) == u.bi_subvol; + + if (ret && + ((c->sb.btrees_lost_data & BIT_ULL(BTREE_ID_subvolumes)) || + snapshot_agrees)) { ret = 0; - try(reconstruct_subvol(trans, k.k->p.snapshot, u.bi_subvol, u.bi_inum)); + try(bch2_reconstruct_subvol(trans, k.k->p.snapshot, u.bi_subvol, u.bi_inum)); goto do_update; } - if (fsck_err_on(ret, + printbuf_reset(&buf); + bch2_inode_unpacked_to_text(&buf, &u); + prt_printf(&buf, "\nsnapshot %u: ", u.bi_snapshot); + if (!snapshot_ret) + bch2_snapshot_to_text(&buf, &snapshot); + else + prt_str(&buf, "(missing)"); + + /* + * No exemption for a missing subvolume: an unlinked subvolume + * still resolves, and once it's tombstoned the snapshot is + * will_delete and we never visit these keys - the sweep owns + * them. A root inode pointing at a subvolume that's actually + * gone is damage, and the repair below must run or + * check_unreachable_inodes() meets an orphan whose bi_subvol + * points nowhere and the reattach fail-stops the pass (field + * report, 2026-07-21). + * + * A reference to the root subvolume is never the broken side: + * subvol 1's existence is an invariant, and check_root() + * recreates it if lost. Stripping bi_subvol around the + * absence takes a valid backref off the root inode - and + * check_unreachable_inodes() then reattaches the root + * directory into lost+found: + */ + bool root_subvol_ref = ret && u.bi_subvol == BCACHEFS_ROOT_SUBVOL; + + if (!root_subvol_ref && + (fsck_err_on(ret, trans, inode_bi_subvol_missing, - "inode %llu:%u bi_subvol points to missing subvolume %u", - u.bi_inum, k.k->p.snapshot, u.bi_subvol) || - fsck_err_on(le64_to_cpu(s.inode) != u.bi_inum || + "inode bi_subvol points to missing subvolume %u\n%s", + u.bi_subvol, buf.buf) || + fsck_err_on(le64_to_cpu(s.inode) != u.bi_inum || !bch2_snapshot_is_ancestor(trans, le32_to_cpu(s.snapshot), k.k->p.snapshot), trans, inode_bi_subvol_wrong, - "inode %llu:%u points to subvol %u, but subvol points to %llu:%u", - u.bi_inum, k.k->p.snapshot, u.bi_subvol, + "inode points to subvol %u, but subvol points to %llu:%u\n%s", + u.bi_subvol, le64_to_cpu(s.inode), - le32_to_cpu(s.snapshot))) { + le32_to_cpu(s.snapshot), + buf.buf))) { u.bi_subvol = 0; u.bi_parent_subvol = 0; do_update = true; @@ -1224,9 +1627,227 @@ static int find_oldest_inode_needs_reattach(struct btree_trans *trans, return ret; } +/* + * An unreachable inode version may still be attached in a descendant + * snapshot: incomplete snapshot deletion can move a dirent further down the + * snapshot tree than the inode that points to it (an interrupted pass + * resumes against new topology, so the two stop at different termini), + * leaving ancestor views orphaned while the descendant view is intact. + * + * check_inodes zeroed this version's backpointer, but the attached + * descendant version still carries its verified one - find that dirent, so + * we can propagate a copy up to this version's snapshot instead of + * reattaching in lost+found. + * + * Requirements checked here: the dirent names this inode from a strict + * descendant, the parent directory is visible (and not unlinked) in this + * version's view, the dirent's name hashes to its offset under that + * directory's hash info (a mismatched seed - e.g. a reconstructed directory + * inode - would get the propagated dirent rehashed by the next + * check_dirents, dangling every backpointer to it), and the destination + * slot is empty - a whiteout there means the entry was deliberately deleted + * in this view, and must not be resurrected. + * + * Returns a copy in transaction memory: the caller uses it across + * fsck_err(), which can cycle transaction locks, so a reference into a + * btree node buffer would be a use after unlock. + */ +static struct bkey_i *find_attached_dirent_in_descendant(struct btree_trans *trans, + struct bch_inode_unpacked *inode) +{ + struct bch_fs *c = trans->c; + struct bch_inode_unpacked child; + bool found = false; + struct bkey_s_c k; + int ret = 0; + + /* + * Dirents pointing to subvolume roots live in the parent subvolume - + * a different snapshot space; those take the reattach path: + */ + if (inode->bi_subvol) + return NULL; + + for_each_btree_key_norestart(trans, iter, BTREE_ID_inodes, + SPOS(0, inode->bi_inum, 0), + BTREE_ITER_all_snapshots, k, ret) { + if (k.k->p.offset != inode->bi_inum || + k.k->p.snapshot >= inode->bi_snapshot) + break; + + if (!bkey_is_inode(k.k) || + !bch2_snapshot_is_ancestor(trans, k.k->p.snapshot, inode->bi_snapshot)) + continue; + + bch2_inode_unpack(c, k, &child); + if (bch2_inode_has_backpointer(&child) && !child.bi_parent_subvol) { + found = true; + break; + } + } + if (ret) + return ERR_PTR(ret); + if (!found) + return NULL; + + u32 snapshot = child.bi_snapshot; + CLASS(btree_iter_uninit, dirent_iter)(trans); + struct bkey_s_c_dirent d = bch2_inode_get_dirent(trans, &dirent_iter, &child, &snapshot); + ret = bkey_err(d); + if (bch2_err_matches(ret, ENOENT)) + return NULL; + if (ret) + return ERR_PTR(ret); + + if (dirent_points_to_inode_nowarn(c, d, inode)) + return NULL; + + /* + * Classify our snapshot's view of that position. (d is visible at + * the descendant, so it lies on the descendant's rootward path and + * is always comparable with our snapshot - no separate ancestry + * check is needed.) + * + * - matching dirent already visible (a propagation done at an older + * version of this inode earlier in the pass): only the + * backpointer needs fixing. No further requirements - there's no + * insert, and falling back to lost+found would create a duplicate + * link to a reachable file + * - nothing visible and the slot is empty: propagate a copy, which + * also requires the parent directory to be visible and not + * unlinked. (No hash check needed: check_dirents verified the + * dirent at the descendant's view, and hash info is invariant + * across an inode's snapshot versions - enforced by check_inodes - + * so it hashes identically under the directory here.) + * - a different inode's dirent visible: the name belongs to someone + * else in this view, and inserting over it would hide that file + * from every view below; a whiteout in the slot: the entry was + * deliberately deleted here. Both fall back to lost+found. + */ + CLASS(btree_iter, vis_iter)(trans, BTREE_ID_dirents, + SPOS(d.k->p.inode, d.k->p.offset, inode->bi_snapshot), 0); + struct bkey_s_c vis = bch2_btree_iter_peek_slot(&vis_iter); + ret = bkey_err(vis); + if (ret) + return ERR_PTR(ret); + + if (vis.k->type == KEY_TYPE_dirent) { + if (dirent_points_to_inode_nowarn(c, bkey_s_c_to_dirent(vis), inode)) + return NULL; + } else { + struct bch_inode_unpacked dir; + ret = bch2_inode_find_by_inum_snapshot(trans, d.k->p.inode, + inode->bi_snapshot, &dir, 0); + if (bch2_err_matches(ret, ENOENT)) + return NULL; + if (ret) + return ERR_PTR(ret); + + if (dir.bi_flags & BCH_INODE_unlinked) + return NULL; + + CLASS(btree_iter, dst_iter)(trans, BTREE_ID_dirents, + SPOS(d.k->p.inode, d.k->p.offset, inode->bi_snapshot), + BTREE_ITER_all_snapshots); + struct bkey_s_c dst = bch2_btree_iter_peek_slot(&dst_iter); + ret = bkey_err(dst); + if (ret) + return ERR_PTR(ret); + if (!bkey_deleted(dst.k)) + return NULL; + } + + return bch2_bkey_make_mut_noupdate(trans, d.s_c); +} + +static int reattach_via_descendant_dirent(struct btree_trans *trans, + struct bch_inode_unpacked *inode, + struct bkey_i *new) +{ + struct bch_fs *c = trans->c; + + new->k.p.snapshot = inode->bi_snapshot; + + /* + * Re-classify under the intent lock: the probe ran before fsck_err(), + * which can cycle transaction locks, and this pass can run online. A + * matching dirent that's become visible only needs the backpointer + * set; anything else now occupying the position must not be + * clobbered. + */ + CLASS(btree_iter, vis_iter)(trans, BTREE_ID_dirents, new->k.p, + BTREE_ITER_intent); + struct bkey_s_c vis = bkey_try(bch2_btree_iter_peek_slot(&vis_iter)); + + bool have_dirent = vis.k->type == KEY_TYPE_dirent && + !dirent_points_to_inode_nowarn(c, bkey_s_c_to_dirent(vis), inode); + + if (!have_dirent) { + if (vis.k->type == KEY_TYPE_dirent) + goto bail; + + CLASS(btree_iter, dst_iter)(trans, BTREE_ID_dirents, new->k.p, + BTREE_ITER_all_snapshots|BTREE_ITER_intent); + struct bkey_s_c dst = bkey_try(bch2_btree_iter_peek_slot(&dst_iter)); + if (!bkey_deleted(dst.k)) + goto bail; + + try(bch2_trans_update(trans, &dst_iter, new, BTREE_UPDATE_internal_snapshot_node)); + } + + inode->bi_dir = new->k.p.inode; + inode->bi_dir_offset = new->k.p.offset; + return __bch2_fsck_write_inode(trans, inode); +bail: + bch_err(c, "not propagating dirent for inode %llu:%u: destination %llu:%llu:%u now occupied", + inode->bi_inum, inode->bi_snapshot, + new->k.p.inode, new->k.p.offset, new->k.p.snapshot); + return 0; +} + +/* + * Is this inode number a subvolume root? Answered once per inum, from the first + * version we see. + * + * bi_subvol cannot be read off an arbitrary version. Taking a snapshot updates + * the root inode of the new subvolume but not of the old, so the version left + * behind at the now-interior node is still the live root of the old subvolume + * and was never rewritten; versions older still may predate the subvolume + * entirely. An old version of a subvolume root legitimately reads bi_subvol == + * 0, and trusting that is how we ended up reattaching one into lost+found. + * + * The first version we see for an inum is different, and one bool taken from it + * then carries to the rest: + * + * 1. We iterate BTREE_ID_inodes with all_snapshots from POS_MIN, and inode + * keys sort by (inum, snapshot) - so within an inum we visit snapshot IDs + * in ascending order. + * 2. A snapshot's ID is always strictly less than its parent's; the snapshot + * key validator enforces it (snapshot_parent_bad, bch2_snapshot_validate()). + * So every descendant of a node sorts before that node. + * 3. Version B shadows version A only if B lives at a descendant of A's + * snapshot. By (2) B sorts before A, so by (1) we would already have seen + * B when we reach A. + * 4. Hence nothing shadows the first version we see for an inum: some live + * view resolves to it. That is the version fsck maintains bi_subvol on - + * check_subvols() ran before us and repairs it there, and check_inode() + * only validates bi_subvol where it is meaningful. + * 5. Whether an inum is a subvolume root is a property of the number, not of + * any one version, so the answer is good for all of them. + * + * Only the boolean is carried, not the subvolume ID: the first version we land + * on may belong to any of the subvolumes rooted at this inum, and which one it + * is says nothing. + */ +struct subvol_root_seen { + u64 inum; + bool is_subvol_root; +}; + static int check_unreachable_inode(struct btree_trans *trans, struct btree_iter *iter, - struct bkey_s_c k) + struct bkey_s_c k, + struct subvol_root_seen *seen) { CLASS(printbuf, buf)(); int ret = 0; @@ -1237,12 +1858,58 @@ static int check_unreachable_inode(struct btree_trans *trans, struct bch_inode_unpacked inode; bch2_inode_unpack(trans->c, k, &inode); + /* Before the early return below: every version has to advance this. */ + if (inode.bi_inum != seen->inum) { + seen->inum = inode.bi_inum; + seen->is_subvol_root = inode.bi_subvol != 0; + } + if (!inode_should_reattach(&inode)) return 0; - try(find_oldest_inode_needs_reattach(trans, &inode)); + /* + * Not for a subvolume root. A subvolume root has exactly one dirent, + * in the parent subvolume, and dirents to subvolumes aren't versioned + * - so there is no chain of unreachable ancestor versions to walk back + * to, and the version we were handed is the one to reattach. + * + * Note that leaf-ness can't stand in for this: taking a snapshot + * updates the root inode of the new subvolume, but not of the old, so + * a live subvolume's root inode key stays at a snapshot that has since + * become interior. + * + * Climbing anyway picks some ancestor version, reattaches that - and + * because the ancestor doesn't carry bi_subvol, it gets filed into + * lost+found as a plain directory named after its inode number, whose + * backpointer is then propagated back down over the live versions + * below it. The subvolume root ends up reachable both by its own + * DT_SUBVOL dirent and by the manufactured one, which is + * inode_dir_multiple_links -> emergency read-only at runtime. + * (field report, 2026-08-04) + */ + if (!seen->is_subvol_root) + try(find_oldest_inode_needs_reattach(trans, &inode)); + + /* + * Attached in a descendant snapshot? Then this version has a proper + * home; propagate the dirent up to our snapshot rather than + * manufacturing a lost+found entry visible in every view below: + */ + struct bkey_i *d = errptr_try(find_attached_dirent_in_descendant(trans, &inode)); + + if (d) { + if (inode_fsck_err(trans, SPOS(0, inode.bi_inum, inode.bi_snapshot), + inode_unreachable_dirent_in_descendant, + "unreachable inode with dirent in descendant snapshot %u, propagating:\n%s", + d->k.p.snapshot, + (bch2_inode_unpacked_to_text(&buf, &inode), + buf.buf))) + try(reattach_via_descendant_dirent(trans, &inode, d)); + return ret; + } - if (fsck_err(trans, inode_unreachable, + if (inode_fsck_err(trans, SPOS(0, inode.bi_inum, inode.bi_snapshot), + inode_unreachable, "unreachable inode:\n%s", (bch2_inode_unpacked_to_text(&buf, &inode), buf.buf))) @@ -1266,13 +1933,15 @@ int bch2_check_unreachable_inodes(struct bch_fs *c) struct progress_indicator progress; bch2_progress_init(&progress, __func__, c, BIT_ULL(BTREE_ID_inodes), 0); + struct subvol_root_seen seen = {}; + CLASS(btree_trans, trans)(c); return for_each_btree_key_commit(trans, iter, BTREE_ID_inodes, POS_MIN, BTREE_ITER_prefetch|BTREE_ITER_all_snapshots, k, NULL, NULL, BCH_TRANS_COMMIT_no_enospc, ({ bch2_progress_update_iter(trans, &progress, &iter) ?: - check_unreachable_inode(trans, &iter, k); + check_unreachable_inode(trans, &iter, k, &seen); })); } @@ -1389,7 +2058,8 @@ int bch2_check_key_has_inode(struct btree_trans *trans, if (inode_looks_deleted) prt_str(&buf, "inode was deleted, will delete key\n"); - if (ret_fsck_err(trans, key_in_missing_inode, "%s", buf.buf)) { + if (ret_inode_fsck_err(trans, k.k->p, + key_in_missing_inode, "%s", buf.buf)) { if (inode_looks_deleted) return bch2_btree_delete_at(trans, iter, BTREE_UPDATE_internal_snapshot_node); @@ -1403,12 +2073,22 @@ int bch2_check_key_has_inode(struct btree_trans *trans, u32 snapshot = i->inode.bi_snapshot; i->inode = good_ancestor->inode; i->inode.bi_snapshot = snapshot; - try(bch2_fsck_write_inode(trans, &i->inode)); + /* + * __ (non-committing) version: we're inside the + * caller's commit_do(). The self-committing one + * eats restarts, and when the following lazy + * commit then has nothing to do it returns 0 - + * leaking the advanced restart_count to the + * caller's verify (panic, restart_count N + * should be M): + */ + try(__bch2_fsck_write_inode(trans, &i->inode)); try(bch2_trans_commit_lazy(trans, NULL, NULL, BCH_TRANS_COMMIT_no_enospc)); } } } else { - if (ret_fsck_err(trans, key_in_wrong_inode_type, "%s", buf.buf)) { + if (ret_inode_fsck_err(trans, k.k->p, + key_in_wrong_inode_type, "%s", buf.buf)) { int nr_extents = iter->btree_id == BTREE_ID_extents ? nr_keys : count_inode_keys(trans, inode_pos, BTREE_ID_extents, NULL); if (nr_extents < 0) @@ -1431,7 +2111,8 @@ int bch2_check_key_has_inode(struct btree_trans *trans, else i->inode.bi_mode |= S_IFREG; - try(bch2_fsck_write_inode(trans, &i->inode)); + /* __: see above - don't eat restarts under the caller's commit_do() */ + try(__bch2_fsck_write_inode(trans, &i->inode)); try(bch2_trans_commit_lazy(trans, NULL, NULL, BCH_TRANS_COMMIT_no_enospc)); } } @@ -1457,7 +2138,8 @@ static int maybe_reconstruct_inum_btree(struct btree_trans *trans, if (ret <= 0) return ret; - if (fsck_err(trans, missing_inode_with_contents, + if (inode_fsck_err(trans, SPOS(0, inum, snapshot), + missing_inode_with_contents, "inode %llu:%u type %s missing, but contents found: reconstruct?", inum, snapshot, btree == BTREE_ID_extents ? "reg" : "dir")) @@ -1506,6 +2188,8 @@ static int check_subdir_count_notnested(struct btree_trans *trans, struct inode_ lockrestart_do(trans, bch2_inum_snapshot_to_path(trans, w->last_pos.inode, i->inode.bi_snapshot, NULL, &buf)); + prt_newline(&buf); + bch2_inode_unpacked_to_text(&buf, &i->inode); if (fsck_err_on(i->inode.bi_nlink != i->count, trans, inode_dir_wrong_nlink, @@ -1525,9 +2209,18 @@ static int check_subdir_count_notnested(struct btree_trans *trans, struct inode_ static int check_subdir_dirents_count(struct btree_trans *trans, struct inode_walker *w) { + /* + * Nested transaction, like check_i_sectors(): the inner + * bch2_fsck_write_inode() commits discard the fsck_err logs queued in + * check_subdir_count_notnested() and we return a restart - exempt those + * begins from the dropped-updates warning. + */ u32 restart_count = trans->restart_count; - return check_subdir_count_notnested(trans, w) ?: - trans_was_restarted(trans, restart_count); + trans->begin_may_drop_updates = true; + int ret = check_subdir_count_notnested(trans, w); + trans->begin_may_drop_updates = false; + + return ret ?: trans_was_restarted(trans, restart_count); } /* find a subvolume that's a descendent of @snapshot: */ @@ -1561,14 +2254,26 @@ static int check_dirent_to_subvol(struct btree_trans *trans, struct btree_iter * u32 target_subvol = le32_to_cpu(d.v->d_child_subvol); u32 parent_snapshot; u32 new_parent_subvol = 0; - u64 parent_inum; CLASS(printbuf, buf)(); int ret = 0; - ret = subvol_lookup(trans, parent_subvol, &parent_snapshot, &parent_inum); + ret = bch2_subvolume_get_snapshot(trans, parent_subvol, &parent_snapshot); if (ret && !bch2_err_matches(ret, ENOENT)) return ret; + if (ret && parent_subvol == BCACHEFS_ROOT_SUBVOL) { + /* + * A reference to the root subvolume is never the broken side: + * subvol 1's existence is an invariant, and check_root() + * recreates it if lost. Rewiring parent_subvol around the + * absence reparents the root directory's subvolume dirents + * onto arbitrary subvolumes; left alone, they're valid the + * moment the root subvolume is back: + */ + ret = 0; + goto check_target; + } + if (ret || (!ret && !bch2_snapshot_is_ancestor(trans, parent_snapshot, d.k->p.snapshot))) { ret = find_snapshot_subvol(trans, d.k->p.snapshot, &new_parent_subvol); @@ -1584,7 +2289,7 @@ static int check_dirent_to_subvol(struct btree_trans *trans, struct btree_iter * * Couldn't find a subvol for dirent's snapshot - but we lost * subvols, so we need to reconstruct: */ - try(reconstruct_subvol(trans, d.k->p.snapshot, parent_subvol, 0)); + try(bch2_reconstruct_subvol(trans, d.k->p.snapshot, parent_subvol, 0)); parent_snapshot = d.k->p.snapshot; } @@ -1603,19 +2308,47 @@ static int check_dirent_to_subvol(struct btree_trans *trans, struct btree_iter * return bch_err_throw(c, fsck_repair_unimplemented); } - struct bkey_i_dirent *new_dirent = errptr_try(bch2_bkey_make_mut_typed(trans, iter, &d.s_c, 0, dirent)); + /* + * The dirent is rewritten at its own position, which may be an + * interior snapshot node - dirents in old snapshots need this + * repair too: + */ + struct bkey_i_dirent *new_dirent = + errptr_try(bch2_bkey_make_mut_typed(trans, iter, &d.s_c, + BTREE_UPDATE_internal_snapshot_node, dirent)); new_dirent->v.d_parent_subvol = cpu_to_le32(new_parent_subvol); + + /* + * The fs_path_parent check below repairs the subvolume to agree + * with the dirent, so it has to agree with the dirent we just + * wrote and not the one we replaced - otherwise a single pass + * writes two different answers, and each subsequent fsck moves + * one to match the other's stale value. + */ + parent_subvol = new_parent_subvol; } +check_target: bch2_trans_iter_init(trans, &subvol_iter, BTREE_ID_subvolumes, POS(0, target_subvol), 0); struct bkey_s_c_subvolume s = bch2_bkey_get_typed(&subvol_iter, subvolume); ret = bkey_err(s.s_c); if (ret && !bch2_err_matches(ret, ENOENT)) return ret; + /* + * A deleted-state subvolume is a tombstone pending the snapshot + * sweep: bch2_subvolume_get() reports those as ENOENT, but this is a + * raw read (the fs_path_parent repair below needs the key). Treat it + * as missing here too - otherwise the dirent outlives the subvolume, + * and fsck stops converging once the sweep removes the key: + */ + if (!ret && bch2_subvolume_state_compat(s.v) == SUBVOLUME_STATE_deleted) + ret = bch_err_throw(c, ENOENT_subvolume_deleted); + if (ret) { - if (fsck_err(trans, dirent_to_missing_subvol, + if (inode_fsck_err(trans, d.k->p, + dirent_to_missing_subvol, "dirent points to missing subvolume\n%s", (bch2_bkey_val_to_text(&buf, c, d.s_c), buf.buf))) return bch2_fsck_remove_dirent(trans, d.k->p); @@ -1625,7 +2358,7 @@ static int check_dirent_to_subvol(struct btree_trans *trans, struct btree_iter * if (le32_to_cpu(s.v->fs_path_parent) != parent_subvol) { printbuf_reset(&buf); - prt_printf(&buf, "subvol with wrong fs_path_parent, should be be %u\n", + prt_printf(&buf, "subvol with wrong fs_path_parent, should be %u\n", parent_subvol); try(bch2_inum_to_path(trans, (subvol_inum) { s.k->p.offset, @@ -1756,12 +2489,36 @@ static int check_dirent(struct btree_trans *trans, struct btree_iter *iter, * exists. The second pass revisits the copies for the * target checks and directory counts: */ - if (fsck_err(trans, dirent_to_inode_in_descendant_snapshot, + if (inode_fsck_err(trans, d.k->p, + dirent_to_inode_in_descendant_snapshot, "dirent with inode(s) only in descendant snapshots:\n%s", (printbuf_reset(&buf), bch2_bkey_val_to_text(&buf, c, k), buf.buf))) { darray_for_each(target->inodes, i) { + try(bch2_trans_commit_lazy_if_full(trans, NULL, NULL, + BCH_TRANS_COMMIT_no_enospc)); + + /* + * The inode-side state firing this repair is + * unchanged by the copies, so a re-drive after a + * partially-committed batch fires it again: skip + * the copies already committed, or the + * commit_lazy_if_full() restart can't make + * forward progress: + */ + CLASS(btree_iter, probe)(trans, BTREE_ID_dirents, + SPOS(k.k->p.inode, k.k->p.offset, + i->inode.bi_snapshot), 0); + struct bkey_s_c old = + bkey_try(bch2_btree_iter_peek_slot(&probe)); + + if (old.k->p.snapshot == i->inode.bi_snapshot && + old.k->type == k.k->type && + bkey_val_bytes(old.k) == bkey_val_bytes(k.k) && + !memcmp(old.v, k.v, bkey_val_bytes(k.k))) + continue; + struct bkey_i *n = errptr_try(bch2_bkey_make_mut_noupdate(trans, k)); @@ -1787,35 +2544,66 @@ static int check_dirent(struct btree_trans *trans, struct btree_iter *iter, } } - if (fsck_err_on(!target->inodes.nr, - trans, dirent_to_missing_inode, + if (inode_fsck_err_on(!target->inodes.nr, + trans, d.k->p, + dirent_to_missing_inode, "dirent points to missing inode:\n%s", (printbuf_reset(&buf), bch2_bkey_val_to_text(&buf, c, k), buf.buf))) try(bch2_fsck_remove_dirent(trans, d.k->p)); - darray_for_each(target->inodes, i) + darray_for_each(target->inodes, i) { + /* + * One repair per snapshot version of the target inode: + * bounded only by snapshot count, so commit-and-restart + * before the batch outgrows the trans bump allocator. + * The re-drive converges: get_visible_inodes() rereads + * the versions and committed repairs no longer fire. + */ + try(bch2_trans_commit_lazy_if_full(trans, NULL, NULL, + BCH_TRANS_COMMIT_no_enospc)); + try(bch2_check_dirent_target(trans, iter, d, &i->inode, true)); + } + + darray_for_each(target->deletes, i) { + if (snapshot_list_has_id(&s->ids, *i)) + continue; + + try(bch2_trans_commit_lazy_if_full(trans, NULL, NULL, + BCH_TRANS_COMMIT_no_enospc)); + + CLASS(btree_iter, delete_iter)(trans, + BTREE_ID_dirents, + SPOS(k.k->p.inode, k.k->p.offset, *i), + BTREE_ITER_intent); + /* + * The deletes list is derived from inode-side state the + * whiteouts don't change: check whether the dirent is + * still visible in this snapshot, both so a re-drive + * after a partially-committed batch skips the committed + * whiteouts (or the commit_lazy_if_full() restart can't + * make forward progress), and so an already-invisible + * dirent isn't reported and "repaired" redundantly: + */ + struct bkey_s_c visible = + bkey_try(bch2_btree_iter_peek_slot(&delete_iter)); + if (visible.k->type != KEY_TYPE_dirent) + continue; - darray_for_each(target->deletes, i) - if (fsck_err_on(!snapshot_list_has_id(&s->ids, *i), - trans, dirent_to_overwritten_inode, - "dirent points to inode overwritten in snapshot %u:\n%s", - *i, - (printbuf_reset(&buf), - bch2_bkey_val_to_text(&buf, c, k), - buf.buf))) { - CLASS(btree_iter, delete_iter)(trans, - BTREE_ID_dirents, - SPOS(k.k->p.inode, k.k->p.offset, *i), - BTREE_ITER_intent); - try(bch2_btree_iter_traverse(&delete_iter)); + if (inode_fsck_err(trans, visible.k->p, + dirent_to_overwritten_inode, + "dirent points to inode overwritten in snapshot %u:\n%s", + *i, + (printbuf_reset(&buf), + bch2_bkey_val_to_text(&buf, c, k), + buf.buf))) try(bch2_hash_delete_at(trans, bch2_dirent_hash_desc, hash_info, &delete_iter, BTREE_UPDATE_internal_snapshot_node)); - } + } } /* @@ -1857,8 +2645,21 @@ int bch2_check_dirents(struct bch_fs *c) bch2_progress_update_iter(trans, &progress, &iter) ?: check_dirent(trans, &iter, k, &hash_info, &dir, &target, &s, &need_second_pass); - })) ?: - check_subdir_count_notnested(trans, &dir); + })); + if (!ret) { + /* + * Final flush of the last directory's subdir count. Exempt the + * inner fsck_write_inode commits from the dropped-updates warning + * as check_subdir_dirents_count() does - but call _notnested + * directly, NOT the nested wrapper: that returns + * trans_was_restarted() for an in-loop caller to retry on, and at + * this post-loop flush the restart has no handler and faults + * recovery (it broke every transaction-restart-injection test). + */ + trans->begin_may_drop_updates = true; + ret = check_subdir_count_notnested(trans, &dir); + trans->begin_may_drop_updates = false; + } if (!ret && need_second_pass && !did_second_pass) { bch_info(c, "check_dirents requires second pass"); @@ -1881,6 +2682,7 @@ static int check_xattr(struct btree_trans *trans, struct btree_iter *iter, struct inode_walker *inode) { struct bch_fs *c = trans->c; + CLASS(printbuf, buf)(); int ret = bch2_check_key_has_snapshot(trans, iter, k); if (ret < 0) @@ -1919,29 +2721,52 @@ static int check_xattr(struct btree_trans *trans, struct btree_iter *iter, unsigned x_type = bkey_s_c_to_xattr(k).v->x_type; struct inode_walker_entry *i2; + /* + * One repair per visible snapshot version, bounded only by + * snapshot count: commit-and-restart before the batch + * outgrows the trans bump allocator. The re-drive converges - + * the walker revalidates on commit (commit_count), so + * committed flag repairs no longer fire: + */ if (x_type == KEY_TYPE_XATTR_INDEX_POSIX_ACL_ACCESS) - for_each_visible_inode(trans, s, inode, k.k->p.snapshot, i2) + for_each_visible_inode(trans, s, inode, k.k->p.snapshot, i2) { + try(bch2_trans_commit_lazy_if_full(trans, NULL, NULL, + BCH_TRANS_COMMIT_no_enospc)); + if (!i2->whiteout && fsck_err_on(!(i2->inode.bi_flags & BCH_INODE_has_access_acl), trans, inode_has_access_acl_flag_wrong, - "inode %llu:%u has an access acl xattr but BCH_INODE_has_access_acl not set", - i2->inode.bi_inum, i2->inode.bi_snapshot)) { + "inode has an access acl xattr but BCH_INODE_has_access_acl not set\n%s", + (printbuf_reset(&buf), + bch2_inode_unpacked_to_text(&buf, &i2->inode), + prt_newline(&buf), + bch2_bkey_val_to_text(&buf, c, k), + buf.buf))) { struct bch_inode_unpacked inode_u = i2->inode; inode_u.bi_flags |= BCH_INODE_has_access_acl; try(__bch2_fsck_write_inode(trans, &inode_u)); } + } if (x_type == KEY_TYPE_XATTR_INDEX_POSIX_ACL_DEFAULT) - for_each_visible_inode(trans, s, inode, k.k->p.snapshot, i2) + for_each_visible_inode(trans, s, inode, k.k->p.snapshot, i2) { + try(bch2_trans_commit_lazy_if_full(trans, NULL, NULL, + BCH_TRANS_COMMIT_no_enospc)); + if (!i2->whiteout && fsck_err_on(!(i2->inode.bi_flags & BCH_INODE_has_default_acl), trans, inode_has_default_acl_flag_wrong, - "inode %llu:%u has a default acl xattr but BCH_INODE_has_default_acl not set", - i2->inode.bi_inum, i2->inode.bi_snapshot)) { + "inode has a default acl xattr but BCH_INODE_has_default_acl not set\n%s", + (printbuf_reset(&buf), + bch2_inode_unpacked_to_text(&buf, &i2->inode), + prt_newline(&buf), + bch2_bkey_val_to_text(&buf, c, k), + buf.buf))) { struct bch_inode_unpacked inode_u = i2->inode; inode_u.bi_flags |= BCH_INODE_has_default_acl; try(__bch2_fsck_write_inode(trans, &inode_u)); } + } } bool need_second_pass = false; @@ -1993,12 +2818,44 @@ static int check_root_trans(struct btree_trans *trans) if (ret && !bch2_err_matches(ret, ENOENT)) return ret; + /* + * The missing subvolume key is not the only record of root's active + * snapshot: snapshot nodes carry a subvol backref, so root's active + * snapshot is the leaf claiming BCACHEFS_ROOT_SUBVOL. Only when no + * node does (fresh filesystem, or the snapshots btree is gone too) + * is U32_MAX - the initial snapshot id - correct; on a snapshotted + * filesystem U32_MAX is an interior node, and a subvolume pointing + * at it is subvol_snapshot_not_leaf, which has no repair. + * + * _norestart: we're inside the caller's commit_do(), so restarts must + * propagate out to it: + */ + u32 root_snapshot = 0; + if (ret) { + struct bkey_s_c k; + int ret2 = 0; + + for_each_btree_key_norestart(trans, iter, BTREE_ID_snapshots, + POS_MIN, 0, k, ret2) { + if (k.k->type == KEY_TYPE_snapshot) { + struct bkey_s_c_snapshot s = bkey_s_c_to_snapshot(k); + + if (le32_to_cpu(s.v->subvol) == BCACHEFS_ROOT_SUBVOL && + !s.v->children[0]) { + root_snapshot = k.k->p.offset; + break; + } + } + } + try(ret2); + } + if (mustfix_fsck_err_on(ret, trans, root_subvol_missing, "root subvol missing")) { struct bkey_i_subvolume *root_subvol = errptr_try(bch2_trans_kmalloc(trans, sizeof(*root_subvol))); - snapshot = U32_MAX; + snapshot = root_snapshot ?: U32_MAX; inum = BCACHEFS_ROOT_INO; bkey_subvolume_init(&root_subvol->k_i); @@ -2018,15 +2875,24 @@ static int check_root_trans(struct btree_trans *trans) if (mustfix_fsck_err_on(ret, trans, root_dir_missing, - "root directory missing") || - mustfix_fsck_err_on(!S_ISDIR(root_inode.bi_mode), - trans, root_inode_not_dir, - "root inode not a directory")) { + "root directory missing")) { bch2_inode_init(c, &root_inode, 0, 0, S_IFDIR|0755, 0, NULL); root_inode.bi_inum = inum; root_inode.bi_snapshot = snapshot; + ret = __bch2_fsck_write_inode(trans, &root_inode); + bch_err_msg(c, ret, "writing root inode"); + } else if (mustfix_fsck_err_on(!S_ISDIR(root_inode.bi_mode), + trans, root_inode_not_dir, + "root inode not a directory")) { + /* + * The inode exists: fix only the mode. Reinitializing it + * generates a fresh hash_seed - invalidating the hash offset + * of every dirent in the root directory - and wipes bi_subvol: + */ + root_inode.bi_mode = S_IFDIR|0755; + ret = __bch2_fsck_write_inode(trans, &root_inode); bch_err_msg(c, ret, "writing root inode"); } @@ -2093,7 +2959,7 @@ int bch2_fs_fsck_errcode(struct bch_fs *c, struct printbuf *msg) } if (test_bit(BCH_FS_emergency_ro, &c->flags)) { prt_printf(msg, "%s: fatal error (went emergency read-only)\n", c->name); - ret |= 4; + ret |= 8; } return ret; @@ -2125,9 +2991,16 @@ static int bch2_fsck_offline_thread_fn(struct thread_with_stdio *stdio) int ret = bch2_fs_start(c); CLASS(printbuf, buf)(); - if (ret) + if (ret) { prt_printf(&buf, "%s: error starting filesystem: %s\n", c->name, bch2_err_str(ret)); - else + /* + * What we return is an fsck(8) exit status, not an errcode - + * see bch2_fs_fsck_errcode(). A filesystem we couldn't start + * is an operational error, same as the online path reports + * for recovery passes that fail outright. + */ + ret = 8; + } else ret = bch2_fs_fsck_errcode(c, &buf); if (ret) bch2_stdio_redirect_write(&stdio->stdio, false, buf.buf, buf.pos); diff --git a/fs/fs/check.h b/fs/fs/check.h index 281f13c875..d4a1ec1002 100644 --- a/fs/fs/check.h +++ b/fs/fs/check.h @@ -77,6 +77,17 @@ void bch2_dirent_inode_mismatch_msg(struct printbuf *, struct bch_fs *, int bch2_reattach_inode(struct btree_trans *, struct bch_inode_unpacked *); +/* + * Recreate a missing subvolume key: (snapshot, subvol, root inum). Pass 0 for + * the inum to have it found from the inode carrying bi_subvol. + * + * The snapshot must be a leaf - the key it writes sets that snapshot's subvol + * backref, and bch2_snapshot_validate() rejects a subvol on a node with + * children. check_snapshots() is the natural caller for that reason: the + * snapshot it's holding claims the subvolume, so it's a leaf by construction. + */ +int bch2_reconstruct_subvol(struct btree_trans *, u32, u32, u64); + int bch2_fsck_update_backpointers(struct btree_trans *, struct snapshots_seen *, const struct bch_hash_desc, diff --git a/fs/fs/check_dir_structure.c b/fs/fs/check_dir_structure.c index 816a524cd9..75af8b4dfe 100644 --- a/fs/fs/check_dir_structure.c +++ b/fs/fs/check_dir_structure.c @@ -27,13 +27,24 @@ static int remove_backpointer(struct btree_trans *trans, u32 snapshot = inode->bi_snapshot; - if (inode->bi_parent_subvol) - try(bch2_subvolume_get_snapshot(trans, inode->bi_parent_subvol, &snapshot)); - struct bch_fs *c = trans->c; + CLASS(btree_iter_uninit, iter)(trans); - struct bkey_s_c_dirent d = bkey_try(dirent_get_by_pos(trans, &iter, - SPOS(inode->bi_dir, inode->bi_dir_offset, snapshot))); + struct bkey_s_c_dirent d = bch2_inode_get_dirent(trans, &iter, inode, &snapshot); + + /* + * bch2_inode_get_dirent() returns an ERR_PTR in the bkey, and for a + * subvolume root it resolves the dirent through bi_parent_subvol - so a + * missing parent subvolume lands here as an error, not as a not-found + * dirent. That is exactly the state reattach_subvol() is called for, + * and dereferencing it oopsed in dirent_points_to_inode(). + * + * Nothing to remove is success: the caller's next move is to reattach, + * and it can't if we hand it an error. + */ + int ret = bkey_err(d); + if (ret) + return bch2_err_matches(ret, ENOENT) ? 0 : ret; try(dirent_points_to_inode(c, d, inode)); try(bch2_fsck_remove_dirent(trans, d.k->p)); @@ -97,7 +108,9 @@ static int check_subvol_path(struct btree_trans *trans, struct btree_iter *iter, try(bch2_inum_to_path(trans, start, &buf)); - if (fsck_err(trans, subvol_loop, "%s", buf.buf)) + if (inode_fsck_err(trans, SPOS(0, le64_to_cpu(s.v->inode), + le32_to_cpu(s.v->snapshot)), + subvol_loop, "%s", buf.buf)) ret = reattach_subvol(trans, s); break; } @@ -105,8 +118,10 @@ static int check_subvol_path(struct btree_trans *trans, struct btree_iter *iter, bch2_btree_iter_set_pos(&parent_iter, POS(0, parent)); k = bkey_try(bch2_btree_iter_peek_slot(&parent_iter)); - if (fsck_err_on(k.k->type != KEY_TYPE_subvolume, - trans, subvol_unreachable, + if (inode_fsck_err_on(k.k->type != KEY_TYPE_subvolume, + trans, SPOS(0, le64_to_cpu(s.v->inode), + le32_to_cpu(s.v->snapshot)), + subvol_unreachable, "unreachable subvolume %s", (printbuf_reset(&buf), bch2_bkey_val_to_text(&buf, c, s.s_c), @@ -188,6 +203,19 @@ static int check_path_loop(struct btree_trans *trans, struct bkey_s_c inode_k) struct bch_inode_unpacked inode; bch2_inode_unpack(c, inode_k, &inode); + /* + * If this inode sits at a redundant interior snapshot node that + * delete_dead_snapshots will collapse into a live descendant, do the whole + * path traversal in the descendant's view: an interrupted collapse migrated + * the naming dirents and parent inodes down there, and that's the state the + * subtree is converging on - otherwise a half-migrated dirent reads as a + * spurious unreachable-inode. Computed once (the walk stays in one + * snapshot); no-op on a healthy fs. + */ + u32 collapse_terminal = bch2_snapshot_redundant_interior(c, snapshot); + if (collapse_terminal) + snapshot = collapse_terminal; + CLASS(btree_iter, inode_iter)(trans, BTREE_ID_inodes, POS_MIN, 0); /* @@ -205,10 +233,19 @@ static int check_path_loop(struct btree_trans *trans, struct bkey_s_c inode_k) return ret; if (bch2_err_matches(ret, ENOENT)) { + /* + * The naming dirent is gone, so we can't recover the + * filename - but bi_dir still tells us which directory + * the inode was in. Print that path so the user can see + * what was lost. A restart from the path walk just + * propagates to the enclosing for_each_..._commit loop. + */ printbuf_reset(&buf); - bch2_bkey_val_to_text(&buf, c, inode_k); - bch_err(c, "unreachable inode in check_directory_structure: %s\n%s", - bch2_err_str(ret), buf.buf); + prt_str(&buf, "unreachable inode, naming dirent missing; was in directory "); + try(bch2_inum_snapshot_to_path(trans, inode.bi_dir, snapshot, NULL, &buf)); + prt_newline(&buf); + bch2_inode_unpacked_to_text(&buf, &inode); + bch_err(c, "%s", buf.buf); return ret; } @@ -249,7 +286,8 @@ static int check_path_loop(struct btree_trans *trans, struct bkey_s_c inode_k) prt_printf(&buf, "%llu ", *i); } - if (fsck_err(trans, dir_loop, "%s", buf.buf)) { + if (inode_fsck_err(trans, SPOS(0, inode.bi_inum, inode.bi_snapshot), + dir_loop, "%s", buf.buf)) { ret = remove_backpointer(trans, &inode); bch_err_msg(c, ret, "removing dirent"); if (ret) diff --git a/fs/fs/check_extents.c b/fs/fs/check_extents.c index f45d11372e..5ef4f7c8a4 100644 --- a/fs/fs/check_extents.c +++ b/fs/fs/check_extents.c @@ -63,6 +63,8 @@ static int check_i_sectors_notnested(struct btree_trans *trans, struct inode_wal bch2_inum_snapshot_to_path(trans, i->inode.bi_inum, i->inode.bi_snapshot, NULL, &buf)); + prt_newline(&buf); + bch2_inode_unpacked_to_text(&buf, &i->inode); count2 = bch2_count_inode_sectors(trans, w->last_pos.inode, i->inode.bi_snapshot); @@ -93,9 +95,18 @@ static int check_i_sectors_notnested(struct btree_trans *trans, struct inode_wal static int check_i_sectors(struct btree_trans *trans, struct inode_walker *w) { + /* + * Counting i_sectors spans too many extents to fit one transaction, so + * this is a nested transaction: the inner commits (bch2_fsck_write_inode) + * discard the fsck_err logs queued here and we return a restart. Exempt + * those begins from the dropped-updates warning for the duration. + */ u32 restart_count = trans->restart_count; - return check_i_sectors_notnested(trans, w) ?: - trans_was_restarted(trans, restart_count); + trans->begin_may_drop_updates = true; + int ret = check_i_sectors_notnested(trans, w); + trans->begin_may_drop_updates = false; + + return ret ?: trans_was_restarted(trans, restart_count); } struct extent_end { @@ -223,7 +234,8 @@ static int overlapping_extents_found(struct btree_trans *trans, prt_printf(&buf, "\noverwriting %s extent", first ? "first" : "second"); - if (ret_fsck_err(trans, extent_overlapping, "%s", buf.buf)) { + if (ret_inode_fsck_err(trans, k1.k->p, + extent_overlapping, "%s", buf.buf)) { struct btree_iter *old_iter = &iter1; if (!first) { @@ -237,7 +249,7 @@ static int overlapping_extents_found(struct btree_trans *trans, BTREE_UPDATE_internal_snapshot_node)); n->k.type = KEY_TYPE_whiteout; } else { - trans->extra_disk_res += bch2_bkey_sectors_compressed(c, k2); + trans->extra_disk_res += bch2_bkey_durability_safe(c, k2).sectors_compressed; try(bch2_trans_update_extent_overwrite(trans, old_iter, BTREE_UPDATE_internal_snapshot_node, @@ -384,14 +396,17 @@ static int check_extent(struct btree_trans *trans, struct btree_iter *iter, i->inode.bi_inum, i->inode.bi_snapshot, i->inode.bi_size, (bch2_bkey_val_to_text(&buf, c, k), buf.buf))) { try(snapshots_seen_add_inorder(c, s, i->inode.bi_snapshot)); + + /* + * fpunch_snapshot() commits internally, so it + * always returns transaction_restart_nested — + * this try() never falls through + */ try(bch2_fpunch_snapshot(trans, SPOS(i->inode.bi_inum, last_block, i->inode.bi_snapshot), POS(i->inode.bi_inum, U64_MAX))); - - iter->k.type = KEY_TYPE_whiteout; - break; } } } @@ -435,14 +450,29 @@ int bch2_check_extents(struct bch_fs *c) struct progress_indicator progress; bch2_progress_init(&progress, __func__, c, BIT_ULL(BTREE_ID_extents), 0); - return for_each_btree_key(trans, iter, BTREE_ID_extents, + int ret = for_each_btree_key(trans, iter, BTREE_ID_extents, POS(BCACHEFS_ROOT_INO, 0), BTREE_ITER_prefetch|BTREE_ITER_all_snapshots, k, ({ bch2_disk_reservation_put(c, &res.r); bch2_progress_update_iter(trans, &progress, &iter) ?: check_extent(trans, &iter, k, &w, &s, &extent_ends, &res.r); - })) ?: - check_i_sectors_notnested(trans, &w); + })); + if (!ret) { + /* + * Final flush of the last inode's i_sectors. The inner + * fsck_write_inode() commits must be exempt from the trans_begin + * dropped-updates warning, so set begin_may_drop_updates as + * check_i_sectors() does - but call _notnested directly, NOT the + * nested check_i_sectors(): that returns trans_was_restarted() + * for an in-loop caller to retry on, and at this post-loop flush + * the restart has no handler and faults recovery (it broke every + * transaction-restart-injection test). + */ + trans->begin_may_drop_updates = true; + ret = check_i_sectors_notnested(trans, &w); + trans->begin_may_drop_updates = false; + } + return ret; } int bch2_check_indirect_extents(struct bch_fs *c) diff --git a/fs/fs/check_nlinks.c b/fs/fs/check_nlinks.c index dd6f8ae060..6d4c2b8e18 100644 --- a/fs/fs/check_nlinks.c +++ b/fs/fs/check_nlinks.c @@ -162,6 +162,7 @@ static int check_nlinks_update_inode(struct btree_trans *trans, struct btree_ite { struct bch_inode_unpacked u; struct nlink *link = &links->d[*idx]; + CLASS(printbuf, buf)(); int ret = 0; if (k.k->p.offset >= range_end) @@ -188,9 +189,9 @@ static int check_nlinks_update_inode(struct btree_trans *trans, struct btree_ite ((u.bi_flags & BCH_INODE_unlinked) && u.bi_nlink), trans, inode_wrong_nlink, - "inode %llu type %s has wrong i_nlink (%u, should be %u)", - u.bi_inum, bch2_d_types[mode_to_type(u.bi_mode)], - bch2_inode_nlink_get(&u), link->count)) { + "inode has wrong i_nlink (%u, should be %u)\n%s", + bch2_inode_nlink_get(&u), link->count, + (bch2_inode_unpacked_to_text(&buf, &u), buf.buf))) { bch2_inode_nlink_set(&u, link->count); ret = __bch2_fsck_write_inode(trans, &u); } diff --git a/fs/fs/inode.c b/fs/fs/inode.c index b1a4816d2c..f0c5be4404 100644 --- a/fs/fs/inode.c +++ b/fs/fs/inode.c @@ -22,6 +22,7 @@ #include "vfs/fs.h" +#include "init/damage.h" #include "init/error.h" #include "init/passes.h" @@ -1050,9 +1051,10 @@ unsigned bch2_shard_inode_numbers_bits_default(unsigned nr_cpus, * => 2^bits <= fs_size / (400 * btree_node_bytes) */ u64 denom = 400ULL * btree_node_bytes; - unsigned size_bits = btree_node_bytes && fs_size >= denom - ? ilog2(fs_size / denom) - : 0; + unsigned size_bits = 0; + + if (denom && fs_size >= denom) + size_bits = ilog2(div64_u64(fs_size, denom)); return min(min(cpu_bits, size_bits), 8U); } @@ -1249,7 +1251,8 @@ static int bch2_inode_rm_trans(struct btree_trans *trans, subvol_inum inum, u32 return bch_err_throw(trans->c, ENOENT_inode); } - return bch2_btree_delete_at(trans, &iter, 0); + return bch2_btree_delete_at(trans, &iter, 0) ?: + bch2_damage_delete(trans, inum.inum, *snapshot); } int bch2_inode_rm(struct bch_fs *c, subvol_inum inum) @@ -1411,22 +1414,48 @@ int bch2_inode_set_casefold(struct btree_trans *trans, subvol_inum inum, static noinline int __bch2_inode_rm_snapshot(struct btree_trans *trans, u64 inum, u32 snapshot) { - bch2_btree_delete_range_trans(trans, BTREE_ID_extents, - SPOS(inum, 0, snapshot), - SPOS(inum, U64_MAX, snapshot), - BTREE_UPDATE_internal_snapshot_node); - bch2_btree_delete_range_trans(trans, BTREE_ID_dirents, - SPOS(inum, 0, snapshot), - SPOS(inum, U64_MAX, snapshot), - BTREE_UPDATE_internal_snapshot_node); - bch2_btree_delete_range_trans(trans, BTREE_ID_xattrs, - SPOS(inum, 0, snapshot), - SPOS(inum, U64_MAX, snapshot), - BTREE_UPDATE_internal_snapshot_node); - try(commit_do(trans, NULL, NULL, BCH_TRANS_COMMIT_no_enospc, - bch2_btree_delete(trans, BTREE_ID_inodes, SPOS(0, inum, snapshot), - BTREE_UPDATE_internal_snapshot_node))); - return 0; + static const enum btree_id content_btrees[] = { + BTREE_ID_extents, + BTREE_ID_dirents, + BTREE_ID_xattrs, + }; + int ret = 0; + + for (unsigned i = 0; i < ARRAY_SIZE(content_btrees); i++) { + int ret2 = bch2_btree_delete_range_trans(trans, content_btrees[i], + SPOS(inum, 0, snapshot), + SPOS(inum, U64_MAX, snapshot), + BTREE_UPDATE_internal_snapshot_node); + /* handled restarts are an FYI - the range was fully deleted: */ + if (bch2_err_matches(ret2, BCH_ERR_transaction_restart)) + ret2 = 0; + ret = ret ?: ret2; + } + + if (!ret) + return commit_do(trans, NULL, NULL, BCH_TRANS_COMMIT_no_enospc, + bch2_btree_delete(trans, BTREE_ID_inodes, + SPOS(0, inum, snapshot), + BTREE_UPDATE_internal_snapshot_node) ?: + bch2_damage_delete(trans, inum, snapshot)); + + /* + * Content left behind: whiteout the inode key instead of deleting it, + * so the ancestor's version doesn't resurface here and the deletion + * scan/fsck can still find this position: + */ + bch_err_msg(trans->c, ret, "deleting content of inode %llu:%u, leaving whiteout", + inum, snapshot); + + struct bkey_i whiteout; + bkey_init(&whiteout.k); + whiteout.k.type = KEY_TYPE_whiteout; + whiteout.k.p = SPOS(0, inum, snapshot); + + return commit_do(trans, NULL, NULL, BCH_TRANS_COMMIT_no_enospc, + bch2_btree_insert_trans(trans, BTREE_ID_inodes, &whiteout, + BTREE_UPDATE_internal_snapshot_node) ?: + bch2_damage_delete(trans, inum, snapshot)) ?: ret; } /* @@ -1483,6 +1512,21 @@ static int may_delete_deleted_inode(struct btree_trans *trans, struct bpos pos, bch2_inode_unpack(trans->c, k, inode); + /* + * Subvolume roots are deleted by the subvolume deletion path, never + * the inode reaper (see bch2_inode_is_subvolume_root()). A + * deleted_inodes entry for one is expected, not damage - the trigger + * enrolls any inode transitioning to unlinked - but consuming it here + * would race the snapshot sweep; crash recovery for subvolume deletion + * is check_subvols(), keyed off SUBVOLUME_STATE_unlinked. Just drop + * the entry: + */ + if (bch2_inode_is_subvolume_root(inode)) { + if (from_deleted_inodes) + goto delete; + return bch_err_throw(c, inode_is_subvolume_root); + } + if (S_ISDIR(inode->bi_mode)) { ret = bch2_empty_dir_snapshot(trans, pos.offset, 0, pos.snapshot); if (fsck_err_on(from_deleted_inodes && diff --git a/fs/fs/inode.h b/fs/fs/inode.h index 4a3fccae9e..04ea8e760a 100644 --- a/fs/fs/inode.h +++ b/fs/fs/inode.h @@ -277,6 +277,19 @@ static inline bool bch2_inode_has_backpointer(const struct bch_inode_unpacked *b return bi->bi_dir || bi->bi_dir_offset; } +/* + * Subvolume root inodes are deleted by the subvolume deletion path - + * subvolume state set to unlinked, VFS eviction, then the snapshot sweep + * deletes the keys - never by the inode reaper (VFS eviction -> + * bch2_inode_rm(), or the deleted_inodes btree): BCH_INODE_unlinked on a + * subvolume root only records that no dirent points at it, not that the + * inode reaper may delete it. + */ +static inline bool bch2_inode_is_subvolume_root(const struct bch_inode_unpacked *bi) +{ + return bi->bi_subvol != 0; +} + /* i_nlink: */ static inline unsigned nlink_bias(umode_t mode) diff --git a/fs/fs/inode_format.h b/fs/fs/inode_format.h index dd27c48b63..e02df71479 100644 --- a/fs/fs/inode_format.h +++ b/fs/fs/inode_format.h @@ -131,6 +131,21 @@ enum inode_opt_id { }; /* + * BCH_INODE_unlinked means we definitively know that there isn't, and + * shouldn't be, a dirent pointing to this inode: it is (or is about to + * be) deleted. check_unreachable_inodes() keys off it to distinguish + * "unreachable by design" from damage needing reattach, and setting it + * enrolls the inode in the deleted_inodes btree (bch2_trigger_inode()) + * so a crash can't leak the inode. + * + * Ordinary inodes carrying it are deleted by the inode reaper - VFS + * eviction -> bch2_inode_rm(), or bch2_delete_dead_inodes() after a + * crash. Subvolume root inodes carry it too once their subvolume has + * been unlinked, but their deletion belongs to the subvolume deletion + * path (subvolume state unlinked -> VFS eviction -> snapshot sweep) and + * the inode reaper must leave them alone - see + * bch2_inode_is_subvolume_root(). + * * BCH_INODE_has_case_insensitive is set if any descendent is case insensitive - * for overlayfs * diff --git a/fs/fs/namei.c b/fs/fs/namei.c index 63aea3cbb6..d9bac7494d 100644 --- a/fs/fs/namei.c +++ b/fs/fs/namei.c @@ -24,11 +24,6 @@ static inline subvol_inum parent_inum(subvol_inum inum, struct bch_inode_unpacke }; } -static inline int is_subdir_for_nlink(struct bch_inode_unpacked *inode) -{ - return S_ISDIR(inode->bi_mode) && !inode->bi_subvol; -} - int bch2_create_trans(struct btree_trans *trans, subvol_inum dir, struct bch_inode_unpacked *dir_u, @@ -276,6 +271,13 @@ int bch2_unlink_trans(struct btree_trans *trans, if (deleting_subvol || inode_u->bi_subvol) { try(bch2_subvolume_unlink(trans, inode_u->bi_subvol)); + /* + * No dirent will ever point at this inode again - deletion + * belongs to the subvolume path, though: the inode reaper keys + * off bch2_inode_is_subvolume_root() to leave it alone. + */ + inode_u->bi_flags |= BCH_INODE_unlinked; + struct bkey_s_c k = bkey_try(bch2_btree_iter_peek_slot(&dirent_iter)); /* @@ -465,8 +467,22 @@ int bch2_rename_trans(struct btree_trans *trans, src_dir_u->bi_nlink += mode == BCH_RENAME_EXCHANGE; } - if (mode == BCH_RENAME_OVERWRITE) - bch2_inode_nlink_dec(trans, dst_inode_u); + if (mode == BCH_RENAME_OVERWRITE) { + /* + * Overwriting a subvolume root deletes the subvolume, same as + * unlink (the victim was empty or a bare file, per the checks + * above): hand it to the subvolume deletion path, don't treat + * it as an ordinary inode losing its last link - see + * bch2_unlink_trans(): + */ + if (dst_inode_u->bi_subvol) { + try(bch2_subvol_has_children(trans, dst_inode_u->bi_subvol)); + try(bch2_subvolume_unlink(trans, dst_inode_u->bi_subvol)); + dst_inode_u->bi_flags |= BCH_INODE_unlinked; + } else { + bch2_inode_nlink_dec(trans, dst_inode_u); + } + } src_dir_u->bi_mtime = now; src_dir_u->bi_ctime = now; @@ -498,6 +514,28 @@ int bch2_rename_trans(struct btree_trans *trans, return 0; } +struct bkey_s_c_dirent bch2_inode_get_dirent(struct btree_trans *trans, + struct btree_iter *iter, + struct bch_inode_unpacked *inode, + u32 *snapshot) +{ + if (inode->bi_parent_subvol) { + int ret = bch2_subvolume_get_snapshot(trans, inode->bi_parent_subvol, snapshot);; + if (ret) + return ((struct bkey_s_c_dirent) { .k = ERR_PTR(ret) }); + } + + /* + * If we're running after an interrupted snapshot deletion, the dirent + * may have been moved to a child snapshot (when cleaning up redundant + * interior node snapshots) but not the inode - do the lookup in the + * child snapshot we'll be moving to: + */ + *snapshot = bch2_snapshot_redundant_interior(trans->c, *snapshot) ?: *snapshot; + + return dirent_get_by_pos(trans, iter, SPOS(inode->bi_dir, inode->bi_dir_offset, *snapshot)); +} + /* inum_to_path */ static inline void reverse_bytes(void *b, size_t n) @@ -606,16 +644,8 @@ static int bch2_inum_to_path_reversed(struct btree_trans *trans, break; } - if (inode.bi_parent_subvol) { - subvol = inode.bi_parent_subvol; - ret = bch2_subvolume_get_snapshot(trans, inode.bi_parent_subvol, &snapshot); - if (ret) - break; - } - - CLASS(btree_iter, d_iter)(trans, BTREE_ID_dirents, - SPOS(inode.bi_dir, inode.bi_dir_offset, snapshot), 0); - struct bkey_s_c_dirent d = bch2_bkey_get_typed(&d_iter, dirent); + CLASS(btree_iter_uninit, d_iter)(trans); + struct bkey_s_c_dirent d = bch2_inode_get_dirent(trans, &d_iter, &inode, &snapshot); ret = bkey_err(d.s_c); if (ret) break; @@ -625,6 +655,15 @@ static int bch2_inum_to_path_reversed(struct btree_trans *trans, prt_bytes_reversed(path, dirent_name.name, dirent_name.len); prt_char(path, '/'); + /* + * Track the subvol as we cross boundaries: the loop-detection key + * above is (subvol ?: snapshot, inum), and inode numbers repeat + * across subvolumes (a snapshot shares its source's root inum), so + * without this the key collides and a valid path reads as a loop. + */ + if (inode.bi_parent_subvol) + subvol = inode.bi_parent_subvol; + inum = inode.bi_dir; } @@ -680,8 +719,70 @@ int bch2_inum_snapshot_to_path(struct btree_trans *trans, u64 inum, u32 snapshot return __bch2_inum_to_path(trans, 0, inum, snapshot, 0, 0, path); } +/* + * Is @inum a descendant of @ancestor? The bi_dir walk from path + * resolution, minus the names: look up the inode, ascend bi_dir - + * crossing subvolume boundaries - until we hit @ancestor or the root. + * > 0 yes, 0 no (including disconnected or looped ancestry), < 0 error. + */ +int bch2_inum_is_descendant(struct btree_trans *trans, subvol_inum inum, + subvol_inum ancestor) +{ + u32 subvol = inum.subvol, snapshot; + u64 cur = inum.inum; + CLASS(darray_subvol_inum, inums)(); + + try(bch2_subvolume_get_snapshot(trans, subvol, &snapshot)); + + while (true) { + if (subvol == ancestor.subvol && cur == ancestor.inum) + return 1; + + subvol_inum n = (subvol_inum) { subvol, cur }; + if (darray_find_p(inums, i, + i->subvol == n.subvol && i->inum == n.inum)) + return 0; + try(darray_push(&inums, n)); + + struct bch_inode_unpacked inode; + int ret = bch2_inode_find_by_inum_snapshot(trans, cur, snapshot, + &inode, 0); + if (ret) + return bch2_err_matches(ret, ENOENT) ? 0 : ret; + + if ((inode.bi_subvol == BCACHEFS_ROOT_SUBVOL && + inode.bi_inum == BCACHEFS_ROOT_INO) || + (!inode.bi_dir && !inode.bi_dir_offset)) + return 0; + + if (inode.bi_parent_subvol) { + subvol = inode.bi_parent_subvol; + try(bch2_subvolume_get_snapshot(trans, subvol, + &snapshot)); + } + cur = inode.bi_dir; + } +} + /* fsck */ +/* + * Is this dirent the name of @target, given that @target is a subvolume root? + * + * A subvolume root's name is not ambiguous: it is the DT_SUBVOL dirent that + * names its subvolume, and inode_d_type() says so from the other side. + * dirent_points_to_inode_nowarn() is not enough to pick it out - for a + * subvolume root it also accepts a DT_DIR dirent naming bi_inum, which is + * exactly what a reattach into lost+found manufactures. + */ +static bool dirent_is_subvol_root_name(struct bch_fs *c, + struct bkey_s_c_dirent d, + struct bch_inode_unpacked *target) +{ + return d.v->d_type == DT_SUBVOL && + !dirent_points_to_inode_nowarn(c, d, target); +} + static int bch2_check_dirent_inode_dirent(struct btree_trans *trans, struct bkey_s_c_dirent d, struct bch_inode_unpacked *target, @@ -732,14 +833,18 @@ static int bch2_check_dirent_inode_dirent(struct btree_trans *trans, if (!backpointer_exists) { if (fsck_err(trans, inode_wrong_backpointer, - "inode %llu:%u has wrong backpointer:\n" + "inode has wrong backpointer:\n" "got %llu:%llu\n" - "should be %llu:%llu", - target->bi_inum, target->bi_snapshot, + "should be %llu:%llu\n%s", target->bi_dir, target->bi_dir_offset, d.k->p.inode, - d.k->p.offset)) { + d.k->p.offset, + (printbuf_reset(&buf), + bch2_inode_unpacked_to_text(&buf, target), + prt_newline(&buf), + bch2_bkey_val_to_text(&buf, c, d.s_c), + buf.buf))) { target->bi_dir = d.k->p.inode; target->bi_dir_offset = d.k->p.offset; try(__bch2_fsck_write_inode(trans, target)); @@ -752,19 +857,61 @@ static int bch2_check_dirent_inode_dirent(struct btree_trans *trans, if (S_ISDIR(target->bi_mode) || target->bi_subvol) { /* - * XXX: verify connectivity of the other dirent - * up to the root before removing this one + * Which of the two is wrong? + * + * For a subvolume root we can say: its name is the + * DT_SUBVOL dirent naming its subvolume, so if exactly + * one of the two qualifies, the other one goes - + * whichever of them we happen to be holding. A reattach + * that didn't recognise a subvolume root manufactures a + * DT_DIR dirent naming bi_inum in lost+found and points + * the inode's backpointer at it, so the impostor is + * routinely the one the backpointer names; dropping the + * dirent in hand would take the real name instead + * (field report 2026-08-04). + * + * If neither or both qualify we're guessing again, so + * fall back to dropping the dirent in hand. + * + * XXX: for a plain directory we still can't tell, and + * verifying connectivity of the other dirent up to the + * root before removing this one is still to do. * * Additionally, bch2_lookup would need to cope with the * dirent it found being removed - or should we remove * the other one, even though the inode points to it? */ + struct bpos remove = d.k->p; + bool repoint_backpointer = false; + + if (target->bi_subvol && + dirent_is_subvol_root_name(c, d, target) && + !dirent_is_subvol_root_name(c, bp_dirent, target)) { + remove = bp_dirent.k->p; + repoint_backpointer = true; + + prt_printf(&buf, "\nremoving %llu:%llu: a subvolume root's name is its DT_SUBVOL dirent", + remove.inode, remove.offset); + } + if (in_fsck) { if (fsck_err(trans, inode_dir_multiple_links, "%s %llu:%u with multiple links\n%s", S_ISDIR(target->bi_mode) ? "directory" : "subvolume", - target->bi_inum, target->bi_snapshot, buf.buf)) - ret = bch2_fsck_remove_dirent(trans, d.k->p); + target->bi_inum, target->bi_snapshot, buf.buf)) { + ret = bch2_fsck_remove_dirent(trans, remove); + + /* + * We just removed the dirent the inode + * named - point it at the survivor, or + * we've left a dangling backpointer. + */ + if (!ret && repoint_backpointer) { + target->bi_dir = d.k->p.inode; + target->bi_dir_offset = d.k->p.offset; + ret = __bch2_fsck_write_inode(trans, target); + } + } } else { bch2_fs_inconsistent(c, "%s %llu:%u with multiple links\n%s", diff --git a/fs/fs/namei.h b/fs/fs/namei.h index 76577b6857..78725f46fb 100644 --- a/fs/fs/namei.h +++ b/fs/fs/namei.h @@ -6,6 +6,19 @@ struct posix_acl; +/* + * Does linking this inode into a directory bump that directory's i_nlink? + * + * A subvolume root doesn't: it's named by a DT_SUBVOL dirent, and those don't + * count towards the parent's link count. Anything creating or repairing such a + * link has to agree with the create path here, or check_nlinks() disagrees with + * it afterwards. + */ +static inline int is_subdir_for_nlink(struct bch_inode_unpacked *inode) +{ + return S_ISDIR(inode->bi_mode) && !inode->bi_subvol; +} + #define BCH_CREATE_TMPFILE (1U << 0) #define BCH_CREATE_SUBVOL (1U << 1) #define BCH_CREATE_SNAPSHOT (1U << 2) @@ -43,12 +56,16 @@ int bch2_rename_trans(struct btree_trans *, bool bch2_reinherit_attrs(struct bch_inode_unpacked *, struct bch_inode_unpacked *); +struct bkey_s_c_dirent bch2_inode_get_dirent(struct btree_trans *, struct btree_iter *, + struct bch_inode_unpacked *, u32 *); + int bch2_inum_to_path(struct btree_trans *, subvol_inum, struct printbuf *); #define INUM_TO_PATH_FAIL_ON_ERR (1 << 0) int bch2_inum_to_path_in_subvol(struct btree_trans *, subvol_inum, u32, unsigned, struct printbuf *); +int bch2_inum_is_descendant(struct btree_trans *, subvol_inum, subvol_inum); int bch2_inum_snapshot_to_path(struct btree_trans *, u64, u32, snapshot_id_list *, struct printbuf *); diff --git a/fs/fs/quota.c b/fs/fs/quota.c index 77775a996e..24677ebee8 100644 --- a/fs/fs/quota.c +++ b/fs/fs/quota.c @@ -524,8 +524,7 @@ static int bch2_fs_quota_read_inode(struct btree_trans *trans, int bch2_fs_quota_read(struct bch_fs *c) { - scoped_guard(memalloc_flags, PF_MEMALLOC_NOFS) { - guard(mutex)(&c->sb_lock); + scoped_guard(mutex_noio, &c->sb_lock) { struct bch_sb_field_quota *sb_quota = bch2_sb_get_or_create_quota(&c->disk_sb); if (!sb_quota) return bch_err_throw(c, ENOSPC_sb_quota); @@ -568,8 +567,7 @@ static int bch2_quota_enable(struct super_block *sb, unsigned uflags) if (uflags & FS_QUOTA_PDQ_ENFD && !c->opts.prjquota) return bch_err_throw(c, EINVAL_quota_enable_prjquota); - guard(memalloc_flags)(PF_MEMALLOC_NOFS); - guard(mutex)(&c->sb_lock); + guard(mutex_noio)(&c->sb_lock); sb_quota = bch2_sb_get_or_create_quota(&c->disk_sb); if (!sb_quota) { int ret = bch_err_throw(c, ENOSPC_sb_quota); @@ -597,8 +595,7 @@ static int bch2_quota_disable(struct super_block *sb, unsigned uflags) if (sb->s_flags & SB_RDONLY) return -EROFS; - guard(memalloc_flags)(PF_MEMALLOC_NOFS); - guard(mutex)(&c->sb_lock); + guard(mutex_noio)(&c->sb_lock); if (uflags & FS_QUOTA_UDQ_ENFD) SET_BCH_SB_USRQUOTA(c->disk_sb.sb, false); @@ -708,8 +705,7 @@ static int bch2_quota_set_info(struct super_block *sb, int type, ~(QC_SPC_TIMER|QC_INO_TIMER|QC_SPC_WARNS|QC_INO_WARNS)) return bch_err_throw(c, EINVAL_quota_set_info_bad_field); - guard(memalloc_flags)(PF_MEMALLOC_NOFS); - guard(mutex)(&c->sb_lock); + guard(mutex_noio)(&c->sb_lock); sb_quota = bch2_sb_get_or_create_quota(&c->disk_sb); if (!sb_quota) { int ret = bch_err_throw(c, ENOSPC_sb_quota); diff --git a/fs/fs/str_hash.c b/fs/fs/str_hash.c index e48e40f762..74c8325d5c 100644 --- a/fs/fs/str_hash.c +++ b/fs/fs/str_hash.c @@ -80,6 +80,10 @@ static int bch2_fsck_rename_dirent(struct btree_trans *trans, char *renamed_buf = errptr_try(bch2_trans_kmalloc(trans, old_name.len + 20)); + /* dirents already at each fsck_renamed-N name, gathered for diagnosis */ + CLASS(printbuf, collisions)(); + bool renamed = false; + for (unsigned i = 0; i < 1000; i++) { new->k.u64s = BKEY_U64s_MAX; @@ -89,18 +93,45 @@ static int bch2_fsck_rename_dirent(struct btree_trans *trans, try(bch2_dirent_init_name(c, new, hash_info, &renamed_name, NULL)); - ret = bch2_hash_set_in_snapshot(trans, bch2_dirent_hash_desc, hash_info, - (subvol_inum) { 0, old.k->p.inode }, - old.k->p.snapshot, &new->k_i, - BTREE_UPDATE_internal_snapshot_node| - STR_HASH_must_create); - if (ret && !bch2_err_matches(ret, EEXIST)) + CLASS(btree_iter_uninit, iter)(trans); + struct bkey_s_c dup = + bch2_hash_set_or_get_in_snapshot(trans, &iter, bch2_dirent_hash_desc, hash_info, + (subvol_inum) { 0, old.k->p.inode }, + old.k->p.snapshot, &new->k_i, + BTREE_UPDATE_internal_snapshot_node| + STR_HASH_must_create); + ret = bkey_err(dup); + if (ret) break; - if (!ret) { + + if (!dup.k) { if (bpos_lt(new->k.p, old.k->p)) *updated_before_k_pos = true; + renamed = true; break; } + + /* name taken - record a sample of the dirents that hold them */ + if (i < 10) { + prt_newline(&collisions); + bch2_bkey_val_to_text(&collisions, c, dup); + } + } + + if (!ret && !renamed) { + CLASS(printbuf, buf)(); + prt_str(&buf, "couldn't rename dirent to resolve hash collision: all 1000 \""); + prt_bytes(&buf, old_name.name, old_name.len); + prt_printf(&buf, ".fsck_renamed-N\" names in dir inum %llu snapshot %u are taken\n", + old.k->p.inode, old.k->p.snapshot); + prt_str(&buf, "renaming:\n "); + bch2_bkey_val_to_text(&buf, c, old.s_c); + prt_str(&buf, "\ncollided with:"); + scoped_guard(printbuf_indent, &buf) + prt_str(&buf, collisions.buf); + bch_err(c, "%s", buf.buf); + + ret = bch_err_throw(c, EEXIST_str_hash_set); } ret = ret ?: bch2_fsck_update_backpointers(trans, s, desc, hash_info, &new->k_i); @@ -238,10 +269,12 @@ static int str_hash_dup_entries(struct btree_trans *trans, prt_newline(&buf); bch2_bkey_val_to_text(&buf, c, dup_k); - if (!ret_fsck_err(trans, hash_table_key_duplicate, "%s", buf.buf)) + if (!ret_inode_fsck_err(trans, k.k->p, + hash_table_key_duplicate, "%s", buf.buf)) return 0; - if (ret == 2) { + bool renamed = ret == 2; + if (renamed) { try(bch2_fsck_rename_dirent(trans, s, *desc, hash_info, bkey_s_c_to_dirent(k), updated_before_k_pos)); @@ -249,17 +282,21 @@ static int str_hash_dup_entries(struct btree_trans *trans, ret = 1; } - if (ret) - swap(k, dup_k); /* @dup_k wins, delete @k */ - /* - * delete @dup_k, in @k's snapshot: if they're in different snapshots, - * @dup is older + * @k is the key being checked; @dup_k was found via lookup from @k's + * snapshot, so if they're in different snapshots @k is the descendant. + * Deleting the loser at @k's (pre-swap) snapshot is correct for both + * outcomes: if @dup_k loses, this whiteouts the ancestor's entry from + * the descendant's view without touching the ancestor's own; if @k + * loses, it's a deletion of @k at its own snapshot. */ - BUG_ON(dup_k.k->p.snapshot < k.k->p.snapshot); + u32 del_snapshot = k.k->p.snapshot; + + if (ret) + swap(k, dup_k); /* @dup_k wins, delete @k */ CLASS(btree_iter, del_iter)(trans, desc->btree_id, - SPOS(dup_k.k->p.inode, dup_k.k->p.offset, k.k->p.snapshot), + SPOS(dup_k.k->p.inode, dup_k.k->p.offset, del_snapshot), BTREE_ITER_slots); try(bch2_btree_iter_traverse(&del_iter)); try(bch2_hash_delete_at(trans, *desc, hash_info, &del_iter, 0)); diff --git a/fs/fs/str_hash.h b/fs/fs/str_hash.h index 3f794cc0f5..b22159f3ee 100644 --- a/fs/fs/str_hash.h +++ b/fs/fs/str_hash.h @@ -407,6 +407,16 @@ static inline int bch2_str_hash_check_key(struct btree_trans *trans, bool *updated_before_k_pos, bool *repaired_inode) { + /* + * `bcachefs dump --sanitize` scrubs dirent names in place without + * updating their hash positions, so every dirent looks misplaced and + * same-length names collide. Don't check or "repair" that on such an + * image - the names are meaningless. + */ + if (desc->btree_id == BTREE_ID_dirents && + trans->c->sb.dirents_sanitized) + return 0; + return str_hash_key_needs_check(desc, hash_info, hash_k) ? __bch2_str_hash_check_key(trans, s, desc, hash_info, hash_k, updated_before_k_pos, repaired_inode) diff --git a/fs/fs/xattr.c b/fs/fs/xattr.c index 61fa763a2e..7b40fd460a 100644 --- a/fs/fs/xattr.c +++ b/fs/fs/xattr.c @@ -325,7 +325,7 @@ ssize_t bch2_xattr_list(struct dentry *dentry, char *buffer, size_t buffer_size) int ret = for_each_btree_key_in_subvolume_max(trans, iter, BTREE_ID_xattrs, POS(inum, offset), POS(inum, U64_MAX), - inode->ei_inum.subvol, 0, k, ({ + inode_inum(inode).subvol, 0, k, ({ if (k.k->type != KEY_TYPE_xattr) continue; @@ -533,7 +533,7 @@ static int __bch2_xattr_bcachefs_set(const struct xattr_handler *handler, struct inode_opt_set s = { .id = inode_opt_id, .defined = value != NULL }; u64 v = 0; - guard(memalloc_flags)(PF_MEMALLOC_NOFS); + guard(memalloc_flags)(PF_MEMALLOC_NOIO); guard(opt_change_lock)(c); CLASS(opt_change_scope, opt_scope)(c); diff --git a/fs/init/chardev.c b/fs/init/chardev.c index caa31bc7bc..1e97097877 100644 --- a/fs/init/chardev.c +++ b/fs/init/chardev.c @@ -597,8 +597,7 @@ static long bch2_ioctl_read_super(struct bch_fs *c, arg.pad) return bch_err_throw(c, EINVAL_ioctl_read_super_bad_flags); - guard(memalloc_flags)(PF_MEMALLOC_NOFS); - guard(mutex)(&c->sb_lock); + guard(mutex_noio)(&c->sb_lock); if (arg.flags & BCH_READ_DEV) { ca = errptr_try(bch2_device_lookup(c, arg.dev, arg.flags)); @@ -719,6 +718,7 @@ static const unsigned query_btree_keys_flags_to_iter_flags[] = { [ilog2(BCH_IOCTL_QUERY_BTREE_KEYS_slots)] = BTREE_ITER_slots, [ilog2(BCH_IOCTL_QUERY_BTREE_KEYS_prev)] = BTREE_ITER_prev, [ilog2(BCH_IOCTL_QUERY_BTREE_KEYS_all_snapshots)] = BTREE_ITER_all_snapshots, + [ilog2(BCH_IOCTL_QUERY_BTREE_KEYS_nofilter_whiteouts)] = BTREE_ITER_nofilter_whiteouts, }; static long bch2_ioctl_query_btree_keys(struct bch_fs *c, diff --git a/fs/init/damage.c b/fs/init/damage.c new file mode 100644 index 0000000000..8756b2f524 --- /dev/null +++ b/fs/init/damage.c @@ -0,0 +1,385 @@ +// SPDX-License-Identifier: GPL-2.0 + +/* + * The damage btree: persistent record of which inodes have been damaged + * by errors and repairs. See damage_format.h for the value format and + * damage.h for the design notes. + */ + +#include "bcachefs.h" + +#include "btree/iter.h" +#include "btree/update.h" +#include "fs/inode.h" +#include "init/damage.h" +#include "init/error.h" +#include "sb/errors.h" +#include "snapshots/snapshot.h" +#include "snapshots/subvolume.h" + +int bch2_damage_validate(struct bch_fs *c, struct bkey_s_c k, + const struct bkey_validate_context *from) +{ + struct bkey_s_c_damage d = bkey_s_c_to_damage(k); + unsigned nr = bkey_val_bytes(k.k) / sizeof(d.v->entries[0]); + unsigned prev = 0; + int ret = 0; + + bkey_fsck_err_on(bkey_val_bytes(k.k) % sizeof(d.v->entries[0]), + c, damage_entries_bad, + "val size %zu not a multiple of entry size", + bkey_val_bytes(k.k)); + + for (unsigned i = 0; i < nr; i++) { + const bch_sb_field_error_entry_v2 *e = &d.v->entries[i]; + unsigned id = BCH_SB_ERROR_ENTRY_V2_ID(e); + + /* Strictly ascending ids: covers unsorted, dup and zero: */ + bkey_fsck_err_on(id <= prev, + c, damage_entries_bad, + "entry %u: id %u nr %llu (prev id %u)", + i, id, BCH_SB_ERROR_ENTRY_V2_NR(e), prev); + prev = id; + + bkey_fsck_err_on(BCH_SB_ERROR_ENTRY_V2_FIRST(e) > + BCH_SB_ERROR_ENTRY_V2_LAST(e), + c, damage_entries_bad, + "entry %u: first occurrence after last", i); + } +fsck_err: + return ret; +} + +void bch2_damage_to_text(struct printbuf *out, struct bch_fs *c, struct bkey_s_c k) +{ + struct bkey_s_c_damage d = bkey_s_c_to_damage(k); + unsigned nr = bkey_val_bytes(k.k) / sizeof(d.v->entries[0]); + + for (unsigned i = 0; i < nr; i++) { + const bch_sb_field_error_entry_v2 *e = &d.v->entries[i]; + + if (i) + prt_newline(out); + bch2_sb_error_id_to_text(out, BCH_SB_ERROR_ENTRY_V2_ID(e)); + prt_str(out, " nr "); + bch2_prt_error_nr(out, BCH_SB_ERROR_ENTRY_V2_NR(e)); + prt_str(out, " first "); + bch2_prt_datetime(out, BCH_SB_ERROR_ENTRY_V2_FIRST(e)); + prt_str(out, " last "); + bch2_prt_datetime(out, BCH_SB_ERROR_ENTRY_V2_LAST(e)); + } +} + +/* + * Record that @err damaged the inode at @pos, in the caller's transaction + * - the record commits with the repair that does the damage, so a crash + * can't separate the two, and a discarded restart discards the increment + * along with the repair it belonged to. Both key-position conventions are + * accepted: a zero inode field means the inum is in the offset field + * (inode keys live at (0, inum, snapshot)). + * + * Also feeds the in-memory damaged-paths report (the end-of-fsck summary + * and the fsck_damaged_paths debugfs file), which stays the reporting + * surface until reporting reads the damage btree. In -n mode the btree + * update never commits while the in-memory report still populates - + * exactly right. + */ +int bch2_damage_record(struct btree_trans *trans, struct bpos pos, + enum bch_sb_error_id err) +{ + u64 inum = pos.inode ?: pos.offset; + + bch2_fsck_damaged(trans, pos, err); + + CLASS(btree_iter, iter)(trans, BTREE_ID_damage, + SPOS(0, inum, pos.snapshot), + BTREE_ITER_all_snapshots|BTREE_ITER_intent); + struct bkey_s_c k = bkey_try(bch2_btree_iter_peek_slot(&iter)); + + const bch_sb_field_error_entry_v2 *old = NULL; + unsigned nr = 0, idx = 0; + bool found = false; + + if (k.k->type == KEY_TYPE_damage) { + struct bkey_s_c_damage d = bkey_s_c_to_damage(k); + + old = d.v->entries; + nr = bkey_val_bytes(k.k) / sizeof(d.v->entries[0]); + + while (idx < nr && BCH_SB_ERROR_ENTRY_V2_ID(&old[idx]) < err) + idx++; + found = idx < nr && BCH_SB_ERROR_ENTRY_V2_ID(&old[idx]) == err; + } + + unsigned bytes = (nr + !found) * sizeof(*old); + + /* + * bkey.u64s is a u8 - growing the value past the max would wrap it, + * corrupting the key, in the same transaction as a repair. Skip + * recording new error ids once full; the in-memory report above + * still surfaces them: + */ + if (!found && bytes > BKEY_VAL_U64s_MAX * sizeof(u64)) + return 0; + + struct bkey_i_damage *n = + errptr_try(bch2_trans_kmalloc(trans, sizeof(*n) + bytes)); + + bkey_damage_init(&n->k_i); + n->k.p = iter.pos; + set_bkey_val_bytes(&n->k, bytes); + if (nr) + memcpy(n->v.entries, old, nr * sizeof(*old)); + + u64 now = ktime_get_real_seconds(); + + bch_sb_field_error_entry_v2 *e = &n->v.entries[idx]; + if (!found) { + memmove(e + 1, e, (nr - idx) * sizeof(*e)); + e->v[0] = 0; + e->v[1] = 0; + SET_BCH_SB_ERROR_ENTRY_V2_ID(e, err); + SET_BCH_SB_ERROR_ENTRY_V2_FIRST(e, now); + } + /* the setter saturates; a wrapped count would be zero, which validate rejects */ + SET_BCH_SB_ERROR_ENTRY_V2_NR(e, BCH_SB_ERROR_ENTRY_V2_NR(e) + 1); + SET_BCH_SB_ERROR_ENTRY_V2_LAST(e, now); + + return bch2_trans_update(trans, &iter, &n->k_i, BTREE_UPDATE_internal_snapshot_node); +} + +/* + * For inode deletion: drop the damage key for this exact version, in the + * same transaction as the inode key's deletion. Only this version's record + * dies with it - damage at ancestor versions belongs to their inode + * versions and is reaped when those are (or merged down by snapshot + * deletion). Most inodes have no damage, so don't queue a deletion for a + * key that isn't there: + */ +int bch2_damage_delete(struct btree_trans *trans, u64 inum, u32 snapshot) +{ + CLASS(btree_iter, iter)(trans, BTREE_ID_damage, + SPOS(0, inum, snapshot), + BTREE_ITER_all_snapshots); + struct bkey_s_c k = bkey_try(bch2_btree_iter_peek_slot(&iter)); + + /* whiteouts (cleared damage) die with the inode too: */ + if (k.k->type != KEY_TYPE_damage && + k.k->type != KEY_TYPE_whiteout) + return 0; + + return bch2_btree_delete_at(trans, &iter, BTREE_UPDATE_internal_snapshot_node); +} + +/* + * Clear the damage record for @inum in the calling subvolume's view: a + * filtered delete, so it's a real delete when no older version needs the + * record and a whiteout when one does - snapshots keep their view, and + * the whiteout hides inherited damage from this view and its + * descendants. Clearing a clean file is a no-op. + */ +int bch2_damage_clear(struct btree_trans *trans, subvol_inum inum) +{ + u32 snapshot; + try(bch2_subvolume_get_snapshot(trans, inum.subvol, &snapshot)); + + CLASS(btree_iter, iter)(trans, BTREE_ID_damage, + SPOS(0, inum.inum, snapshot), + BTREE_ITER_intent); + struct bkey_s_c k = bkey_try(bch2_btree_iter_peek_slot(&iter)); + + if (k.k->type != KEY_TYPE_damage) + return 0; + + return bch2_btree_delete_at(trans, &iter, 0); +} + +/* + * Runtime data damage - loss or corruption found outside fsck_err() + * reporting (device removal dropping the last replica, read errors): + * count the sb error and record against the inode. Only extents btree + * positions name an inum; an indirect extent's damage is counted but + * unattributed - finding its inodes would mean walking reflink + * pointers backwards. + */ +int bch2_damage_record_data_loss(struct btree_trans *trans, enum btree_id btree, + struct bpos pos, enum bch_sb_error_id err) +{ + bch2_sb_error_count(trans->c, err); + + return btree == BTREE_ID_extents + ? bch2_damage_record(trans, pos, err) + : 0; +} + +/* + * A damage key has an inode at its exact position: records are written at + * repaired keys' positions, which are inode keys themselves or content + * keys - and a content key at snapshot X implies an inode at snapshot X. + * The inode removal paths delete the two together; a damage key without + * its inode was left behind by a kernel without the damage btree, and if + * the inum is reused the stale key would claim the new file's history. + */ +static int check_damage_key(struct btree_trans *trans, struct btree_iter *iter, + struct bkey_s_c k) +{ + if (k.k->type != KEY_TYPE_damage) + return 0; + + CLASS(btree_iter, inode_iter)(trans, BTREE_ID_inodes, + SPOS(0, k.k->p.offset, k.k->p.snapshot), + BTREE_ITER_all_snapshots); + struct bkey_s_c inode_k = bkey_try(bch2_btree_iter_peek_slot(&inode_iter)); + + CLASS(printbuf, buf)(); + if (ret_fsck_err_on(!bkey_is_inode(inode_k.k), + trans, damage_key_no_inode, + "damage key with no inode:\n%s", + (bch2_bkey_val_to_text(&buf, trans->c, k), buf.buf))) + return bch2_btree_delete_at(trans, iter, BTREE_UPDATE_internal_snapshot_node); + + return 0; +} + +int bch2_check_damage(struct bch_fs *c) +{ + CLASS(btree_trans, trans)(c); + return for_each_btree_key_commit(trans, iter, BTREE_ID_damage, POS_MIN, + BTREE_ITER_all_snapshots|BTREE_ITER_prefetch, k, + NULL, NULL, BCH_TRANS_COMMIT_no_enospc, + check_damage_key(trans, &iter, k)); +} + +/* + * Merge two damage keys' entries into a new key at @pos: the sorted-by-id + * union, occurrence counts saturating-summed, last-occurrence times maxed. + * For delete_dead_snapshots collapsing a dying snapshot node's key into its + * live child's - the dying key can hold counts recorded after the child's + * key was created, so plain copy-if-empty would lose them. + * + * Entries past the bkey size limit are dropped (lowest error ids kept), + * matching bch2_damage_record()'s skip-on-full policy. + */ +struct bkey_i *bch2_damage_keys_merge(struct btree_trans *trans, struct bpos pos, + struct bkey_s_c a, struct bkey_s_c b) +{ + struct bkey_s_c_damage da = bkey_s_c_to_damage(a); + struct bkey_s_c_damage db = bkey_s_c_to_damage(b); + unsigned nr_a = bkey_val_bytes(a.k) / sizeof(da.v->entries[0]); + unsigned nr_b = bkey_val_bytes(b.k) / sizeof(db.v->entries[0]); + unsigned max_entries = (BKEY_VAL_U64s_MAX * sizeof(u64)) / + sizeof(da.v->entries[0]); + + struct bkey_i_damage *n = bch2_trans_kmalloc(trans, sizeof(*n) + + min(nr_a + nr_b, max_entries) * sizeof(da.v->entries[0])); + if (IS_ERR(n)) + return ERR_CAST(n); + + bkey_damage_init(&n->k_i); + n->k.p = pos; + + unsigned i = 0, j = 0, out = 0; + while ((i < nr_a || j < nr_b) && out < max_entries) { + const bch_sb_field_error_entry_v2 *ea = i < nr_a ? &da.v->entries[i] : NULL; + const bch_sb_field_error_entry_v2 *eb = j < nr_b ? &db.v->entries[j] : NULL; + bch_sb_field_error_entry_v2 *e = &n->v.entries[out++]; + + unsigned id_a = ea ? BCH_SB_ERROR_ENTRY_V2_ID(ea) : UINT_MAX; + unsigned id_b = eb ? BCH_SB_ERROR_ENTRY_V2_ID(eb) : UINT_MAX; + + if (id_a == id_b) { + e->v[0] = 0; + e->v[1] = 0; + SET_BCH_SB_ERROR_ENTRY_V2_ID(e, id_a); + SET_BCH_SB_ERROR_ENTRY_V2_NR(e, + BCH_SB_ERROR_ENTRY_V2_NR(ea) + + BCH_SB_ERROR_ENTRY_V2_NR(eb)); + SET_BCH_SB_ERROR_ENTRY_V2_FIRST(e, + min(BCH_SB_ERROR_ENTRY_V2_FIRST(ea), + BCH_SB_ERROR_ENTRY_V2_FIRST(eb))); + SET_BCH_SB_ERROR_ENTRY_V2_LAST(e, + max(BCH_SB_ERROR_ENTRY_V2_LAST(ea), + BCH_SB_ERROR_ENTRY_V2_LAST(eb))); + i++; + j++; + } else if (id_a < id_b) { + *e = *ea; + i++; + } else { + *e = *eb; + j++; + } + } + + set_bkey_val_bytes(&n->k, out * sizeof(n->v.entries[0])); + return &n->k_i; +} + +/* + * Does this inode have recorded damage, in @snapshot or an ancestor + * version? The readdir filter: > 0 yes, 0 no, < 0 error. Everything about + * how damage is stored stays behind this. + */ +int bch2_inode_has_damage(struct btree_trans *trans, u64 inum, u32 snapshot) +{ + CLASS(btree_iter, iter)(trans, BTREE_ID_damage, SPOS(0, inum, snapshot), 0); + struct bkey_s_c k = bkey_try(bch2_btree_iter_peek_slot(&iter)); + + return k.k->type == KEY_TYPE_damage; +} + +/* + * The union of an inode's damage across a snapshot and all its ancestors: + * damage recorded against an ancestor version happened to the data a + * descendant sees. Callers pass the view's snapshot (a subvolume's, for a + * file the user has open). + * + * @out stays sorted by id; accumulating into a non-empty list is a merge - + * counts sum, first-occurrence times min, last max. + */ +int bch2_damage_accumulate(struct btree_trans *trans, u64 inum, u32 snapshot, + bch_sb_errors_cpu *out) +{ + struct bch_fs *c = trans->c; + + do { + CLASS(btree_iter, iter)(trans, BTREE_ID_damage, SPOS(0, inum, snapshot), 0); + struct bkey_s_c k = bkey_try(bch2_btree_iter_peek_slot(&iter)); + + if (k.k->type != KEY_TYPE_damage) + break; + + struct bkey_s_c_damage d = bkey_s_c_to_damage(k); + unsigned nr = bkey_val_bytes(k.k) / sizeof(d.v->entries[0]); + + for (unsigned i = 0; i < nr; i++) { + const bch_sb_field_error_entry_v2 *e = &d.v->entries[i]; + unsigned eid = BCH_SB_ERROR_ENTRY_V2_ID(e); + u64 first = BCH_SB_ERROR_ENTRY_V2_FIRST(e); + u64 last = BCH_SB_ERROR_ENTRY_V2_LAST(e); + + unsigned j = 0; + while (j < out->nr && out->data[j].id < eid) + j++; + if (j < out->nr && out->data[j].id == eid) { + out->data[j].nr += BCH_SB_ERROR_ENTRY_V2_NR(e); + out->data[j].first_error_time = + min(out->data[j].first_error_time, first); + out->data[j].last_error_time = + max(out->data[j].last_error_time, last); + continue; + } + try(darray_insert_item(out, j, + ((struct bch_sb_error_entry_cpu) { + .id = eid, + .nr = BCH_SB_ERROR_ENTRY_V2_NR(e), + .first_error_time = first, + .last_error_time = last, + }))); + } + + snapshot = bch2_snapshot_parent(c, k.k->p.snapshot); + } while (snapshot); + + return 0; +} diff --git a/fs/init/damage.h b/fs/init/damage.h new file mode 100644 index 0000000000..3225f484aa --- /dev/null +++ b/fs/init/damage.h @@ -0,0 +1,41 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#ifndef _BCACHEFS_DAMAGE_H +#define _BCACHEFS_DAMAGE_H + +#include "sb/errors_types.h" + +/* + * The damage btree: a persistent record of which inodes have been damaged + * by errors and repairs, one key per damaged inode at (0, inum, snapshot). + * + * The in-memory fsck damage accounting (bch2_fsck_damaged) dies with the + * mount; this is its durable counterpart, written in the same transaction + * as the repair that does the damage. The value holds the same records + * the errors superblock section keeps - per bch_sb_error_id, an + * occurrence count and the time of last occurrence - so a damage key + * points back at exactly what happened, in the same vocabulary the error + * counters and fsck use. + */ + +int bch2_damage_validate(struct bch_fs *, struct bkey_s_c, + const struct bkey_validate_context *); +void bch2_damage_to_text(struct printbuf *, struct bch_fs *, struct bkey_s_c); + +#define bch2_bkey_ops_damage ((struct bkey_ops) { \ + .key_validate = bch2_damage_validate, \ + .val_to_text = bch2_damage_to_text, \ + .min_val_size = 16, \ +}) + +int bch2_inode_has_damage(struct btree_trans *, u64, u32); +int bch2_damage_accumulate(struct btree_trans *, u64, u32, bch_sb_errors_cpu *); +struct bkey_i *bch2_damage_keys_merge(struct btree_trans *, struct bpos, + struct bkey_s_c, struct bkey_s_c); +int bch2_damage_delete(struct btree_trans *, u64, u32); +int bch2_damage_clear(struct btree_trans *, subvol_inum); +int bch2_damage_record_data_loss(struct btree_trans *, enum btree_id, + struct bpos, enum bch_sb_error_id); + +int bch2_check_damage(struct bch_fs *); + +#endif /* _BCACHEFS_DAMAGE_H */ diff --git a/fs/init/damage_format.h b/fs/init/damage_format.h new file mode 100644 index 0000000000..b9ab82bce7 --- /dev/null +++ b/fs/init/damage_format.h @@ -0,0 +1,25 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#ifndef _BCACHEFS_DAMAGE_FORMAT_H +#define _BCACHEFS_DAMAGE_FORMAT_H + +#include "sb/errors_format.h" + +/* + * Damage tracking: one key per damaged inode at (0, inum, snapshot), + * recording which errors damaged it. Written in the same transaction as + * the repair that did the damage, so the record can't be lost to a crash + * between repair and bookkeeping. + * + * The value is the same records the errors superblock section keeps, + * sorted by error id: bch_sb_field_error_entry_v2 packs the id, a + * saturating occurrence count and the times of first and last + * occurrence (BCH_SB_ERROR_ENTRY_V2_ID/NR/FIRST/LAST). One vocabulary + * for "what happened": the sb section counts per-filesystem, damage + * keys count per-inode. + */ +struct bch_damage { + struct bch_val v; + bch_sb_field_error_entry_v2 entries[]; +}; + +#endif /* _BCACHEFS_DAMAGE_FORMAT_H */ diff --git a/fs/init/dev.c b/fs/init/dev.c index e52949e84d..0c0262735f 100644 --- a/fs/init/dev.c +++ b/fs/init/dev.c @@ -167,14 +167,39 @@ * * \subsubsection{Resize} * - * \texttt{bcachefs device resize} grows a device to use additional space - * (shrinking is not yet supported). If no size is specified, the device grows to + * \texttt{bcachefs device resize} resizes a device to use more or less space. + * If no size is specified, the device grows to * fill its underlying block device. Resize works online---no unmount required. + * Resize is executed by a per-device kthread, which is restarted when a + * newer request overwrites an in-progress resize, automatically cancelling the old resize. + * Resizes are persisted as \texttt{target\_nbuckets} and will be automatically resumed across restarts. + * + * \subsubsubsection{Growing} * The new size is subject to a maximum bucket count * (\texttt{BCH\_MEMBER\_NBUCKETS\_MAX}); resize will fail if the requested size * would exceed this limit. After resize, the reconcile subsystem is notified to * account for the newly available space. * + * \subsubsubsection{Shrinking} + * Shrinking removes the tail region of a device and evacuates any data + * located there. If this is not possible, the operation will fail with \texttt{-ENOSPC}. + * + * Once \texttt{target\_nbuckets < nbuckets} is persisted, the allocator + * refuses new allocations in the tail, cached pointers past the cutoff are + * treated as stale, and metadata allocation spills to non-shrinking devices + * so shrink does not deadlock on its own journal or btree-rewrite needs. + * Reconcile is then used to discover and evacuate the remaining data. + * + * Before draining the tail, the worker relocates any journal buckets in the truncating region explicitly + * (\texttt{move\_journal\_past\_cutoff()}) so journal activity does not keep + * reintroducing references into the region being evacuated. + * + * Once the tail is empty, the worker finalises under \texttt{state\_lock}: + * it flushes journal pins, clears \texttt{NEED\_DISCARD} bookkeeping for + * the removed buckets, drops superblock copies and alloc metadata past the + * cutoff, then commits \texttt{nbuckets = target\_nbuckets} to the + * superblock. + * * \texttt{bcachefs device resize-journal} adjusts the per-device journal size * independently of the data area. * @@ -204,28 +229,51 @@ #include "bcachefs.h" +#include "alloc/buckets.h" #include "alloc/accounting.h" #include "alloc/background.h" #include "alloc/backpointers.h" #include "alloc/check.h" #include "alloc/discard.h" #include "alloc/replicas.h" +#include "alloc/foreground.h" + +#include "asm/byteorder.h" +#include "bcachefs_format.h" +#include "btree/bkey_methods.h" +#include "btree/bkey_types.h" #include "btree/interior.h" +#include "btree/iter.h" +#include "btree/update.h" +#include "btree/types.h" +#include "btree/write_buffer.h" #include "data/ec/init.h" +#include "data/extents.h" #include "data/migrate.h" #include "data/reconcile/work.h" #include "debug/sysfs.h" #include "journal/init.h" +#include "journal/journal.h" #include "journal/reclaim.h" #include "init/dev.h" #include "init/fs.h" +#include "init/passes.h" +#include "linux/bitmap.h" +#include "linux/kthread.h" +#include "linux/sched.h" +#include "linux/sched/signal.h" +#include "sb/io.h" #include "sb/members.h" +#include "sb/members_format.h" +#include "util/util.h" + +static void bch2_dev_resize_thread_stop(struct bch_dev *); #define x(n) #n, const char * const bch2_dev_read_refs[] = { @@ -422,7 +470,7 @@ static void __bch2_dev_read_only(struct bch_fs *c, struct bch_dev *ca) /* * may_reuse_stripe() / init_new_stripe_from_old() check - * bch2_dev_bad_or_evacuating at stripe allocation time, but state can + * bch2_ptr_bad_or_evacuating at stripe allocation time, but state can * flip to non-rw between that check and the stripe commit. Stripes * still on stripe_head_list were cancelled by bch2_ec_stop_dev() via * bch2_dev_allocator_remove() above; stripes that had moved to @@ -497,6 +545,8 @@ void bch2_dev_free(struct bch_dev *ca) WARN_ON(!enumerated_ref_is_zero(&ca->io_ref[WRITE])); WARN_ON(!enumerated_ref_is_zero(&ca->io_ref[READ])); + bch2_dev_resize_thread_stop(ca); + bch2_dev_unlink(ca); if (ca->kobj.state_in_sysfs) @@ -584,6 +634,9 @@ static struct bch_dev *__bch2_dev_alloc(struct bch_fs *c, init_completion(&ca->ref_completion); refcount_set(&ca->ref_outer, 1); init_completion(&ca->ref_outer_completion); + spin_lock_init(&ca->resize_lock); + init_waitqueue_head(&ca->resize_wait); + ca->resize_status = 0; INIT_WORK(&ca->io_error_work, bch2_io_error_work); @@ -871,8 +924,6 @@ int __bch2_dev_set_state(struct bch_fs *c, struct bch_dev *ca, enum bch_member_state new_state, int flags, struct printbuf *err) { - int ret = 0; - bool was_rw = ca->mi.state == BCH_MEMBER_STATE_rw; bool do_reconcile_scan = new_state == BCH_MEMBER_STATE_rw || @@ -899,7 +950,7 @@ int __bch2_dev_set_state(struct bch_fs *c, struct bch_dev *ca, if (do_reconcile_scan) try(bch2_set_reconcile_needs_scan(c, s, false)); - scoped_guard(mutex, &c->sb_lock) { + scoped_guard(mutex_noio, &c->sb_lock) { struct bch_member *m = bch2_members_v2_get_mut(c->disk_sb.sb, ca->dev_idx); SET_BCH_MEMBER_STATE(m, new_state); bch2_write_super(c); @@ -926,7 +977,7 @@ int __bch2_dev_set_state(struct bch_fs *c, struct bch_dev *ca, if (do_reconcile_scan) try(bch2_set_reconcile_needs_scan(c, s, true)); - return ret; + return 0; } int bch2_dev_set_state(struct bch_fs *c, struct bch_dev *ca, @@ -1032,11 +1083,16 @@ static int __bch2_dev_remove(struct bch_fs *c, struct bch_dev *ca, */ __bch2_dev_offline(c, ca); - ret = bch2_dev_remove_alloc(c, ca); + ret = bch2_dev_remove_alloc(c, ca, 0); if (ret) { prt_printf(err, "bch2_dev_remove_alloc() error: %s\n", bch2_err_str(ret)); goto err; } + ret = bch2_dev_usage_remove(c, ca); + if (ret) { + prt_printf(err, "bch2_dev_usage_remove() error: %s\n", bch2_err_str(ret)); + goto err; + } /* * dev_remove_alloc issued btree deletes that need to be durable before @@ -1068,7 +1124,7 @@ static int __bch2_dev_remove(struct bch_fs *c, struct bch_dev *ca, goto err; } - scoped_guard(mutex, &c->sb_lock) + scoped_guard(mutex_noio, &c->sb_lock) rcu_assign_pointer(c->devs[ca->dev_idx], NULL); #ifndef CONFIG_BCACHEFS_DEBUG @@ -1113,8 +1169,7 @@ int bch2_dev_remove(struct bch_fs *c, struct bch_dev *ca, int flags, * Free this device's slot in the bch_member array - all pointers to * this device must be gone: */ - scoped_guard(memalloc_flags, PF_MEMALLOC_NOFS) { - guard(mutex)(&c->sb_lock); + scoped_guard(mutex_noio, &c->sb_lock) { struct bch_member *m = bch2_members_v2_get_mut(c->disk_sb.sb, dev_idx); if (fast_device_removal) @@ -1131,7 +1186,7 @@ int bch2_dev_remove(struct bch_fs *c, struct bch_dev *ca, int flags, static int bch2_dev_set_initialized(struct bch_fs *c, struct bch_dev *ca, enum bch_member_initialized state) { - guard(mutex)(&c->sb_lock); + guard(mutex_noio)(&c->sb_lock); struct bch_member *m = bch2_members_v2_get_mut(c->disk_sb.sb, ca->dev_idx); SET_BCH_MEMBER_INITIALIZED(m, state); return bch2_write_super(c); @@ -1163,11 +1218,9 @@ int bch2_dev_add_initialize(struct bch_fs *c, struct bch_dev *ca) /* Add new device to running filesystem: */ int bch2_dev_add(struct bch_fs *c, const char *path, struct printbuf *err) { - int ret = 0; - struct bch_opts opts = bch2_opts_empty(); struct bch_sb_handle sb __cleanup(bch2_free_super) = {}; - ret = bch2_read_super(path, &opts, &sb); + int ret = bch2_read_super(path, &opts, &sb); if (ret) { prt_printf(err, "error reading superblock: %s\n", bch2_err_str(ret)); return ret; @@ -1216,11 +1269,18 @@ int bch2_dev_add(struct bch_fs *c, const char *path, struct printbuf *err) * only thing that adds a device to a not-started filesystem: */ try(bch2_set_reconcile_needs_scan(c, s, false)); + + /* + * Adding a device grows the EC widening target (RW members of + * the disk_label) for existing stripes. + */ + try(bch2_set_reconcile_needs_scan(c, + (struct reconcile_scan) { .type = RECONCILE_SCAN_stripes }, false)); } scoped_guard(rwsem_write, &c->state_lock) { - scoped_guard(memalloc_flags, PF_MEMALLOC_NOFS) { - guard(mutex)(&c->sb_lock); + scoped_guard(memalloc_flags, PF_MEMALLOC_NOIO) { + guard(mutex_noio)(&c->sb_lock); SET_BCH_SB_MULTI_DEVICE(c->disk_sb.sb, true); ret = bch2_sb_from_fs(c, ca); @@ -1261,6 +1321,12 @@ int bch2_dev_add(struct bch_fs *c, const char *path, struct printbuf *err) } } + /* + * The failure domain string carried over with the + * member copy above; re-intern so the new device gets + * its failure_domain id. + */ + bch2_sb_members_to_cpu(c); bool write_sb = false; bch2_dev_mi_field_upgrades_locked(c, ca, &identity, &write_sb); @@ -1374,8 +1440,7 @@ int bch2_dev_online(struct bch_fs *c, const char *path, struct printbuf *err) } } - scoped_guard(memalloc_flags, PF_MEMALLOC_NOFS) { - guard(mutex)(&c->sb_lock); + scoped_guard(mutex_noio, &c->sb_lock) { bch2_members_v2_get_mut(c->disk_sb.sb, ca->dev_idx)->last_mount = cpu_to_le64(ktime_get_real_seconds()); bch2_write_super(c); @@ -1431,44 +1496,198 @@ int bch2_dev_offline(struct bch_fs *c, struct bch_dev *ca, int flags, struct pri return 0; } -int bch2_dev_resize(struct bch_fs *c, struct bch_dev *ca, u64 nbuckets, struct printbuf *err) +static u64 bch2_dev_resize_seq(struct bch_dev *ca) { - u64 old_nbuckets; - int ret = 0; + scoped_guard(spinlock, &ca->resize_lock) + return ca->resize_seq; +} + +static bool bch2_dev_resize_wait_done(struct bch_dev *ca, u64 seq, int *status) +{ + scoped_guard(spinlock, &ca->resize_lock) { + if (ca->resize_seq != seq) { + *status = -ECANCELED; + return true; + } + if (ca->resize_status != -EINPROGRESS) { + *status = ca->resize_status; + return true; + } + } + + return false; +} + +static int bch2_dev_resize_wait(struct bch_dev *ca, u64 seq) +{ + int status = -EINPROGRESS; + int ret = wait_event_killable(ca->resize_wait, + bch2_dev_resize_wait_done(ca, seq, &status)); + + return ret ? -EINTR : status; +} + +static bool bch2_dev_resize_finish(struct bch_dev *ca, u64 seq, int status) +{ + bool is_current; + + scoped_guard(spinlock, &ca->resize_lock) { + is_current = ca->resize_seq == seq; + if (is_current) + ca->resize_status = status; + } + + if (is_current) { + wake_up_all(&ca->resize_wait); + + /* Discards are deferred during resize to avoid allocator/journal deadlocks, restart them now that we are done */ + bch2_do_discards_async(ca->fs); + } + + return is_current; +} + +/* checks for kthread interruption, and resize seq having changed */ +static int bch2_dev_resize_restart_check(struct bch_dev *ca, u64 seq) +{ + if (kthread_should_stop()) + return -EINTR; + + return bch2_dev_resize_seq(ca) != seq ? -EAGAIN : 0; +} + +static int bch2_dev_resize_thread(void *arg); + +static int bch2_dev_resize_thread_start(struct bch_dev *ca) +{ + struct bch_fs *c = ca->fs; + + lockdep_assert_held(&c->state_lock); + + if (ca->resize_thread) + return 0; + + struct task_struct *p = + kthread_create(bch2_dev_resize_thread, ca, + "bch-resize/%s:%u", c->name, ca->dev_idx); + try(PTR_ERR_OR_ZERO(p)); + + get_task_struct(p); + ca->resize_thread = p; + wake_up_process(p); + return 0; +} + +static void bch2_dev_resize_thread_stop(struct bch_dev *ca) +{ + scoped_guard(spinlock, &ca->resize_lock) { + ca->resize_seq++; + ca->resize_status = -EINTR; + } + + if (ca->resize_thread) { + kthread_stop(ca->resize_thread); + put_task_struct(ca->resize_thread); + ca->resize_thread = NULL; + } + + wake_up_all(&ca->resize_wait); +} + +void bch2_dev_resize_threads_stop(struct bch_fs *c) +{ + for_each_member_device(c, ca) + bch2_dev_resize_thread_stop(ca); +} + +static int bch2_dev_resize_validate_target(struct bch_fs *c, struct bch_dev *ca, + u64 target_nbuckets, struct printbuf *err) +{ + lockdep_assert_held(&c->state_lock); + + /* validate target_nbuckets */ + u64 old_nbuckets = ca->mi.nbuckets; + + if (target_nbuckets > BCH_MEMBER_NBUCKETS_MAX) { + prt_printf(err, "New device size too big (%llu greater than max %u)\n", + target_nbuckets, BCH_MEMBER_NBUCKETS_MAX); + return bch_err_throw(c, device_size_too_big); + } + + if (target_nbuckets < old_nbuckets && + target_nbuckets < ca->mi.first_bucket + BCH_MIN_NR_NBUCKETS) { + prt_printf(err, "New device size too small (%llu smaller than min %llu)\n", + target_nbuckets, + (u64) ca->mi.first_bucket + BCH_MIN_NR_NBUCKETS); + return bch_err_throw(c, device_size_too_small); + } + + if (target_nbuckets > old_nbuckets && + bch2_dev_is_online(ca) && + get_capacity(ca->disk_sb.bdev->bd_disk) < + ca->mi.bucket_size * target_nbuckets) { + prt_printf(err, "New size %llu larger than device size %llu\n", + ca->mi.bucket_size * target_nbuckets, + get_capacity(ca->disk_sb.bdev->bd_disk)); + return bch_err_throw(c, device_size_too_small); + } + + return 0; +} + +static int bch2_dev_resize_set_target(struct bch_fs *c, struct bch_dev *ca, u64 target_nbuckets) +{ + lockdep_assert_held(&c->state_lock); + + /* commit target_nbuckets */ + scoped_guard(mutex_noio, &c->sb_lock) { + struct bch_member *m = bch2_members_v2_get_mut(c->disk_sb.sb, ca->dev_idx); + + m->target_nbuckets = cpu_to_le64(target_nbuckets); + try(bch2_write_super(c)); + } + + return 0; +} +static int __bch2_dev_grow(struct bch_fs *c, struct bch_dev *ca, + u64 new_nbuckets, struct printbuf *err) +{ guard(rwsem_write)(&c->state_lock); + int ret = 0; + if (READ_ONCE(ca->removing)) return bch_err_throw(c, device_has_been_removed); - old_nbuckets = ca->mi.nbuckets; + u64 old_nbuckets = ca->mi.nbuckets; - if (nbuckets < ca->mi.nbuckets) { - prt_printf(err, "Cannot shrink yet\n"); - return bch_err_throw(c, EINVAL_dev_resize_shrink); + if (new_nbuckets <= old_nbuckets) { + return 0; } - bool wakeup_reconcile_pending = nbuckets > ca->mi.nbuckets; + /* we have more space -> wake up pending */ + bool wakeup_reconcile_pending = new_nbuckets > old_nbuckets; struct reconcile_scan s = { .type = RECONCILE_SCAN_pending }; if (wakeup_reconcile_pending) try(bch2_set_reconcile_needs_scan(c, s, false)); - if (nbuckets > BCH_MEMBER_NBUCKETS_MAX) { + if (new_nbuckets > BCH_MEMBER_NBUCKETS_MAX) { prt_printf(err, "New device size too big (%llu greater than max %u)\n", - nbuckets, BCH_MEMBER_NBUCKETS_MAX); + new_nbuckets, BCH_MEMBER_NBUCKETS_MAX); return bch_err_throw(c, device_size_too_big); } if (bch2_dev_is_online(ca) && get_capacity(ca->disk_sb.bdev->bd_disk) < - ca->mi.bucket_size * nbuckets) { + ca->mi.bucket_size * new_nbuckets) { prt_printf(err, "New size %llu larger than device size %llu\n", - ca->mi.bucket_size * nbuckets, + ca->mi.bucket_size * new_nbuckets, get_capacity(ca->disk_sb.bdev->bd_disk)); return bch_err_throw(c, device_size_too_small); } - ret = bch2_dev_buckets_resize(c, ca, nbuckets); + ret = bch2_dev_buckets_resize(c, ca, new_nbuckets); if (ret) { prt_printf(err, "bch2_dev_buckets_resize() error: %s\n", bch2_err_str(ret)); return ret; @@ -1480,16 +1699,17 @@ int bch2_dev_resize(struct bch_fs *c, struct bch_dev *ca, u64 nbuckets, struct p return ret; } - scoped_guard(memalloc_flags, PF_MEMALLOC_NOFS) { - guard(mutex)(&c->sb_lock); + scoped_guard(mutex_noio, &c->sb_lock) { struct bch_member *m = bch2_members_v2_get_mut(c->disk_sb.sb, ca->dev_idx); - m->nbuckets = cpu_to_le64(nbuckets); + m->nbuckets = cpu_to_le64(new_nbuckets); + if (bch2_dev_resize_target(ca) == new_nbuckets) + m->target_nbuckets = 0; bch2_write_super(c); } if (ca->mi.freespace_initialized) { - ret = __bch2_dev_resize_alloc(ca, old_nbuckets, nbuckets); + ret = __bch2_dev_resize_alloc(ca, old_nbuckets, new_nbuckets); if (ret) { prt_printf(err, "__bch2_dev_resize_alloc() error: %s\n", bch2_err_str(ret)); return ret; @@ -1503,12 +1723,680 @@ int bch2_dev_resize(struct bch_fs *c, struct bch_dev *ca, u64 nbuckets, struct p return 0; } +static int drop_sbs_after_cutoff(struct bch_fs *c, struct bch_dev *ca, u64 cutoff) { + u64 cutoff_sector = bucket_to_sector(ca, cutoff); + + guard(mutex_noio)(&c->sb_lock); + + struct bch_sb_layout *layout = &ca->disk_sb.sb->layout; + + u64 max_sectors = 1 << layout->sb_max_size_bits; + + u8 i; + /* offsets are sorted in ascending order, see validate_sb_layout() overlapping checks for evidence */ + for (i = 0; i < layout->nr_superblocks; i++) { + u64 offset = le64_to_cpu(layout->sb_offset[i]); + if (offset + max_sectors > cutoff_sector) { + break; + } + } + + /* this should never happen, as we only call to this function after checking the cutoff against the minimum fs size, + * which includes at least the first sb copy */ + BUG_ON(i == 0); + + layout->nr_superblocks = i; + + return bch2_write_super(c); +} + +static int move_journal_past_cutoff(struct bch_fs *c, struct bch_dev *ca, + u64 cutoff, struct printbuf *err) +{ + bool grew = false; + + while (true) { + u64 bucket_to_delete = 0; + unsigned nr = 0, nr_past_cutoff = 0; + bool cur_bucket_past_cutoff = false; + int ret; + + scoped_guard(spinlock, &c->journal.lock) { + struct journal_device *ja = &ca->journal; + + nr = ja->nr; + if (!nr) + break; + + cur_bucket_past_cutoff = ja->buckets[ja->cur_idx] >= cutoff; + + for (unsigned i = 0; i < ja->nr; i++) { + if (ja->buckets[i] < cutoff) + continue; + + nr_past_cutoff++; + if (i != ja->cur_idx && !bucket_to_delete) + bucket_to_delete = ja->buckets[i]; + } + } + + if (!nr_past_cutoff) + return 0; + + if (!grew) { + ret = bch2_set_nr_journal_buckets(c, ca, nr + nr_past_cutoff); + if (ret) { + prt_printf(err, "Failed to relocate journal buckets: %s\n", + bch2_err_str(ret)); + return ret; + } + grew = true; + continue; + } + + if (!bucket_to_delete && cur_bucket_past_cutoff) { + scoped_guard(spinlock, &c->journal.lock) { + struct journal_device *ja = &ca->journal; + + if (ja->nr && + ja->buckets[ja->cur_idx] >= cutoff) + ja->sectors_free = 0; + } + + scoped_guard(mutex_noio, &c->sb_lock) { + ret = bch2_write_super(c); + } + if (ret) { + prt_printf(err, "Failed to advance journal off shrink tail: %s\n", + bch2_err_str(ret)); + return ret; + } + + ret = bch2_journal_flush(&c->journal); + if (ret) { + prt_printf(err, "Failed to flush relocated journal: %s\n", + bch2_err_str(ret)); + return ret; + } + continue; + } + + ret = bch2_dev_journal_bucket_delete(ca, bucket_to_delete); + if (ret) { + prt_printf(err, "Failed to drop journal bucket %llu from shrink tail: %s\n", + bucket_to_delete, bch2_err_str(ret)); + return ret; + } + } +} + +struct shrink_tail_head { + struct bpos bucket; + struct bpos first_bp; + unsigned nr_backpointers; +}; + + + +static inline bool shrink_tail_head_empty(const struct shrink_tail_head *head) +{ + return bpos_eq(head->first_bp, SPOS_MAX); +} + +static bool shrink_tail_head_progressed(const struct shrink_tail_head *old, + const struct shrink_tail_head *new) +{ + if (shrink_tail_head_empty(new)) + return true; + + if (shrink_tail_head_empty(old)) + return false; + + if (!bpos_eq(new->bucket, old->bucket)) + return bpos_gt(new->bucket, old->bucket); + + if (!bpos_eq(new->first_bp, old->first_bp)) + return bpos_gt(new->first_bp, old->first_bp); + + return new->nr_backpointers < old->nr_backpointers; +} + +/* + * Make sure everything is caught here: this snapshots backpointer-visible tail + * data. Journal buckets and superblock copies in the shrink tail are handled by + * move_journal_past_cutoff() and drop_sbs_after_cutoff(). + */ +static int tail_head_snapshot(struct bch_fs *c, struct bch_dev *ca, + u64 new_nbuckets, struct shrink_tail_head *head) +{ + struct bpos bp_start = bucket_pos_to_bp_start(ca, POS(ca->dev_idx, new_nbuckets)); + struct bpos bp_end = bucket_pos_to_bp_start(ca, POS(ca->dev_idx, ca->mi.nbuckets)); + + CLASS(btree_trans, trans)(c); + CLASS(backpointer_scan_iter, iter)(BTREE_ID_backpointers, bp_start, NULL); + + struct wb_maybe_flush last_flushed __cleanup(wb_maybe_flush_exit); + wb_maybe_flush_init(&last_flushed); + + struct bkey_s_c_backpointer bp = bch2_bp_scan_iter_peek(trans, &iter, bp_end, &last_flushed); + + try(bkey_err(bp)); + + *head = (struct shrink_tail_head) { + .bucket = SPOS_MAX, + .first_bp = SPOS_MAX, + }; + + if (!bp.k) + return 0; + + head->bucket = bp_pos_to_bucket(ca, bp.k->p); + head->first_bp = bp.k->p; + + do { + head->nr_backpointers++; + bch2_bp_scan_iter_advance(&iter); + bp = bch2_bp_scan_iter_peek(trans, &iter, bp_end, &last_flushed); + try(bkey_err(bp)); + } while (bp.k && bpos_eq(bp_pos_to_bucket(ca, bp.k->p), head->bucket)); + + return 0; +} + + + +static int tail_is_empty(struct bch_fs *c, struct bch_dev *ca, u64 new_nbuckets, + bool *empty) +{ + struct shrink_tail_head head; + + try(tail_head_snapshot(c, ca, new_nbuckets, &head)); + *empty = shrink_tail_head_empty(&head); + return 0; +} + + + + + + +static int bch2_dev_shrink_queue_reconcile(struct bch_fs *c, struct bch_dev *ca, + bool scan_device, u32 *kick, + struct printbuf *err) +{ + if (scan_device) { + struct reconcile_scan s = { + .type = RECONCILE_SCAN_device, // TODO(performance): make this range-based + .dev = ca->dev_idx, + }; + + int ret = bch2_set_reconcile_needs_scan(c, s, false); + if (ret) { + prt_printf(err, "Failed to queue device reconcile scan: %s\n", + bch2_err_str(ret)); + return ret; + } + } + + /* + * Shrink waits for a completed reconcile pass, not just for the device + * scan cookie to disappear. Queue the pending phase alongside the scan + * so the same pass also retries any work that evacuation demoted to the + * pending list. + */ + int ret = bch2_set_reconcile_needs_scan(c, + (struct reconcile_scan) { .type = RECONCILE_SCAN_pending }, false); + if (ret) { + prt_printf(err, "Failed to queue pending reconcile scan: %s\n", + bch2_err_str(ret)); + return ret; + } + + *kick = bch2_reconcile_kick(c); + return 0; +} + +static int bch2_dev_shrink_wait_reconcile(struct bch_dev *ca, u64 new_nbuckets, + u64 seq, u32 kick, + const struct shrink_tail_head *head_before, + bool *kick_complete, + struct printbuf *err) +{ + struct bch_fs *c = ca->fs; + + while (true) { + bool completed; + try(bch2_dev_resize_restart_check(ca, seq)); + + /* + * We only need reconcile to keep running until the shrink tail is + * actually empty. A kick can continue chewing through unrelated + * global reconcile work for minutes after the truncating region is + * already evacuated, especially with fragmented variable-bucket + * workloads. Poll the head of the shrink tail and bound each wait + * to a one-second slice so shrink can rescan its own state instead + * of sitting behind one long reconcile kick. + */ + struct shrink_tail_head head_after; + + try(tail_head_snapshot(c, ca, new_nbuckets, &head_after)); + completed = bch2_reconcile_completed_kick(c) >= kick; + + if (shrink_tail_head_empty(&head_after) || + shrink_tail_head_progressed(head_before, &head_after) || + completed) { + *kick_complete = completed; + return 0; + } + + int ret = wait_event_killable_timeout(c->reconcile.wait, + bch2_reconcile_completed_kick(c) >= kick || + bch2_dev_resize_seq(ca) != seq || + kthread_should_stop(), + HZ); + if (ret < 0) + return -EINTR; + if (!ret) { + *kick_complete = false; + return 0; + } + } +} + +static int bch2_dev_shrink_clear_target(struct bch_fs *c, struct bch_dev *ca, + u64 new_nbuckets, u64 seq, + struct printbuf *err) +{ + scoped_guard(rwsem_write, &c->state_lock) { + try(bch2_dev_resize_restart_check(ca, seq)); + + if (bch2_dev_resize_target(ca) != new_nbuckets || + !bch2_dev_is_shrinking(ca)) + return -EAGAIN; + + try(bch2_dev_resize_set_target(c, ca, 0)); + } + + atomic64_set(&ca->shrinking_tail_free, 0); + + /* allocations are now no longer blocked after the cutoff, so there may now be more usable space */ + int ret = bch2_reconcile_pending_wakeup(c); + if (ret) + bch_err_fn(c, ret); + + return 0; +} + +static int bch2_dev_count_tail_free(struct bch_fs *c, struct bch_dev *ca, + u64 new_nbuckets) +{ + struct bpos start = POS(ca->dev_idx, new_nbuckets); + struct bpos end = POS(ca->dev_idx, ca->mi.nbuckets); + u64 count = 0; + + CLASS(btree_trans, trans)(c); + try(for_each_btree_key_max(trans, iter, BTREE_ID_freespace, + start, end, 0, k, ({ + u64 first = max_t(u64, new_nbuckets, + bkey_start_offset(k.k)); + u64 last = min_t(u64, ca->mi.nbuckets, + k.k->p.offset); + if (last > first) + count += last - first; + 0; + }))); + + atomic64_set(&ca->shrinking_tail_free, count); + return 0; +} + +static int bch2_dev_shrink_finalize(struct bch_fs *c, struct bch_dev *ca, + u64 old_nbuckets, u64 new_nbuckets, + u64 seq, struct printbuf *err) +{ + scoped_guard(rwsem_write, &c->state_lock) { + bool empty = false; + + try(bch2_dev_resize_restart_check(ca, seq)); + + if (bch2_dev_resize_target(ca) != new_nbuckets || + !bch2_dev_is_shrinking(ca)) + return -EAGAIN; + + /* flush interior updates - mirroring dev remove path */ + bch2_btree_interior_updates_flush(c); + + /* + * Only flush pins that were already outstanding when shrink + * entered the final commit path. Reconcile can continue + * generating unrelated key-cache journal pins on newer + * sequences while the tail is already empty; waiting for every + * future pin here can turn shrink into an unbounded global + * journal drain. + */ + bch2_journal_flush_outstanding_pins(&c->journal); + + int ret = bch2_journal_flush_device_pins(&c->journal, ca->dev_idx); + if (ret) { + prt_printf(err, "bch2_journal_flush_device_pins() error: %s\n", + bch2_err_str(ret)); + return ret; + } + + ret = bch2_journal_flush(&c->journal); + if (ret) { + prt_printf(err, "bch2_journal_flush() error: %s\n", + bch2_err_str(ret)); + return ret; + } + + /* re-check that tail is really empty */ + try(tail_is_empty(c, ca, new_nbuckets, &empty)); + + if (!empty) { + prt_printf(err, "Shrink failed: still has data\n"); + return -EBUSY; + } + + /* drop references to now-truncated superblock copies */ + ret = drop_sbs_after_cutoff(c, ca, new_nbuckets); + if (ret) { + prt_printf(err, "Error dropping superblocks after cutoff: %s\n", + bch2_err_str(ret)); + return ret; + } + + /* update accounting info - has to happen before truncating alloc info */ + ret = bch2_dev_truncate_accounting(c, ca, old_nbuckets, new_nbuckets); + if (ret) { + prt_printf(err, "error updating accounting info: %s\n", + bch2_err_str(ret)); + return ret; + } + + /* truncate alloc info */ + ret = bch2_dev_remove_alloc(c, ca, new_nbuckets); + if (ret) { + prt_printf(err, "error truncating alloc info: %s\n", + bch2_err_str(ret)); + return ret; + } + + /* + * Commit the shrink only after the truncated tail has been + * removed from alloc metadata, so later transactions can't see + * stale tail buckets after the new size is visible. + */ + scoped_guard(mutex_noio, &c->sb_lock) { + struct bch_member *m = bch2_members_v2_get_mut(c->disk_sb.sb, ca->dev_idx); + m->nbuckets = cpu_to_le64(new_nbuckets); + if (bch2_dev_resize_target(ca) == new_nbuckets) + m->target_nbuckets = 0; + + try(bch2_write_super(c)); + } + + /* resize buckets */ + ret = bch2_dev_buckets_resize(c, ca, new_nbuckets); + if (ret) { + prt_printf(err, "bch2_dev_buckets_resize() error: %s\n", + bch2_err_str(ret)); + return ret; + } + + bch2_recalc_capacity(c); + atomic64_set(&ca->shrinking_tail_free, 0); + } + + return 0; +} + + +static int __bch2_dev_shrink(struct bch_fs *c, struct bch_dev *ca, + u64 new_nbuckets, u64 seq, struct printbuf *err) +{ + u64 old_nbuckets = ca->mi.nbuckets; + + scoped_guard(rwsem_write, &c->state_lock) { + /* validate shrink size */ + if (new_nbuckets >= old_nbuckets) { + return -EAGAIN; + } + + try(bch2_dev_resize_restart_check(ca, seq)); + + if (bch2_dev_resize_target(ca) != new_nbuckets || + !bch2_dev_is_shrinking(ca)) + return -EAGAIN; + + /* close open buckets in the to-be-shrunk region */ + bch2_open_buckets_stop(c, ca, false, new_nbuckets); + bch2_reset_alloc_cursors(c); // avoid churn + }; + + try(bch2_dev_resize_restart_check(ca, seq)); + + /* + * Shrink can start while a discard worker from earlier freespace + * churn is still in flight. Drain that work before we begin the + * evacuation/journal-flush path: once shrink has started, later + * discard passes skip the shrinking device, but an already-running + * discard can still race in and deadlock against resize/reconcile's + * allocator and btree rewrite work. + */ + flush_work(&c->discards.work); + flush_work(&ca->discard_fast_work); + + try(bch2_dev_resize_restart_check(ca, seq)); + + /* + * Move journal buckets out of the tail up front: otherwise the journal + * can keep reintroducing metadata references in the region we're trying + * to evacuate while reconcile is draining backpointers from it. + */ + try(move_journal_past_cutoff(c, ca, new_nbuckets, err)); + + try(bch2_dev_resize_restart_check(ca, seq)); + + /* wait for to-be-shrunk region to be empty */ + const unsigned stalled_kicks_limit = 32; + struct shrink_tail_head best_head = { + .bucket = SPOS_MAX, + .first_bp = SPOS_MAX, + }; + bool scan_device = true; + unsigned stalled_kicks = 0; + + /* initialize, will be updated in the loop */ + try(bch2_dev_count_tail_free(c, ca, new_nbuckets)); + + /* + * AI output below for detailed reference. TLDR: EC accounting is currently slightly off, so just + * schedule an accounting pass for the next mount. + * + * The stripe repair re-points extents from a stripe with a block in the + * shrink tail to the rebuilt stripe on the surviving devices, and the + * re-pointed extent is committed without a stripe_ptr the insert trigger + * can see - so the new stripe's replicas entry is never incremented and + * the old stripe's entry is left overcounted. + * + * Proper fix (TODO): find why the re-pointed extent's insert loses its + * stripe_ptr. The old-key overwrite triggers but no insert for the new + * stripes ever does; the stripe_ptr must be dropped or rewritten in + * stripe_update_extent()'s key construction or the extent update/merge + * path. Once the insert trigger sees the new stripe_ptr, the accounting + * follows the migration online and this scheduling can go away. + */ + CLASS(bch_log_msg, msg)(c); + int ret = bch2_run_explicit_recovery_pass(c, &msg.m, BCH_RECOVERY_PASS_check_allocations, 0); + if (bch2_err_matches(ret, BCH_ERR_recovery_will_run)) + ret = 0; /* pass will run on next mount */ + try(ret); + + for (unsigned pass = 0; ; pass++) { + bool kick_complete; + struct shrink_tail_head head; + u32 kick; + bool did_scan = pass == 0 || scan_device; + + try(bch2_dev_resize_restart_check(ca, seq)); + + try(tail_head_snapshot(c, ca, new_nbuckets, &head)); + + /* do a definitive check */ + if (shrink_tail_head_empty(&head)) { + { + CLASS(btree_trans, trans)(c); + try(bch2_btree_write_buffer_flush_sync(trans)); + } + + try(tail_head_snapshot(c, ca, new_nbuckets, &head)); + if (shrink_tail_head_empty(&head)) + break; + } + + try(bch2_dev_shrink_queue_reconcile(c, ca, did_scan, &kick, err)); + + try(bch2_dev_shrink_wait_reconcile(ca, new_nbuckets, seq, kick, + &head, &kick_complete, err)); + + bch2_fs_ec_flush_outstanding(c); + + /* Free buckets may have been changed during reconcile; refresh the count */ + try(bch2_dev_count_tail_free(c, ca, new_nbuckets)); + + try(tail_head_snapshot(c, ca, new_nbuckets, &head)); + if (shrink_tail_head_empty(&head)) + break; + + if (shrink_tail_head_progressed(&best_head, &head)) { + best_head = head; + scan_device = false; + stalled_kicks = 0; + } else if (kick_complete) { + /* + * Reconcile drained a full pass but the head didn't + * advance. If we haven't yet tried a full device rescan, + * do one. If we have and it also made no progress, this + * tail is genuinely impossible to evacuate. + */ + if (!did_scan) { + scan_device = true; + } else if (++stalled_kicks >= stalled_kicks_limit) { + prt_printf(err, + "Shrink failed: evacuating all data from the shrink tail not possible\n"); + try(bch2_dev_shrink_clear_target(c, ca, new_nbuckets, seq, err)); + return -ENOSPC; + } + } + } + + return bch2_dev_shrink_finalize(c, ca, old_nbuckets, new_nbuckets, seq, err); +} + +static int bch2_dev_resize_thread(void *arg) +{ + struct bch_dev *ca = arg; + struct bch_fs *c = ca->fs; + u64 seen_seq = 0; + + set_freezable(); + + while (!kthread_should_stop()) { + kthread_wait_freezable(kthread_should_stop() || + bch2_dev_resize_seq(ca) != seen_seq); + if (kthread_should_stop()) + break; + + while (!kthread_should_stop()) { + u64 seq = bch2_dev_resize_seq(ca); + u64 target = bch2_dev_resize_target(ca); + int ret; + CLASS(printbuf, err)(); + + if (target == ca->mi.nbuckets) { + ret = 0; + } else if (target > ca->mi.nbuckets) { + ret = __bch2_dev_grow(c, ca, target, &err); + } else { + ret = __bch2_dev_shrink(c, ca, target, seq, &err); + } + + if (ret == -EAGAIN) + continue; + + if (ret && err.pos) + bch_err_dev(ca, "%s", err.buf); + else if (ret && ret != -EINTR) + bch_err_fn_dev(ca, ret); + + seen_seq = bch2_dev_resize_seq(ca); + if (ret == -EINTR) + break; + if (!bch2_dev_resize_finish(ca, seq, ret)) + continue; + break; + } + } + + return 0; +} + +static int bch2_dev_resize_kick(struct bch_dev *ca) +{ + u64 seq; + + scoped_guard(spinlock, &ca->resize_lock) { + seq = ++ca->resize_seq; + ca->resize_status = -EINPROGRESS; + } + + wake_up_process(ca->resize_thread); + return bch2_dev_resize_wait(ca, seq); +} + +int bch2_dev_resize(struct bch_fs *c, struct bch_dev *ca, u64 target_nbuckets, struct printbuf *err) +{ + scoped_guard(rwsem_write, &c->state_lock) { + try(bch2_dev_resize_validate_target(c, ca, target_nbuckets, err)); + + // normalize + target_nbuckets = target_nbuckets == ca->mi.nbuckets ? 0 : target_nbuckets; + + try(bch2_dev_resize_thread_start(ca)); + try(bch2_dev_resize_set_target(c, ca, target_nbuckets)); + } + + int ret = bch2_dev_resize_kick(ca); + if (ret == -ECANCELED) + prt_printf(err, "Resize request superseded by a newer target\n"); + else if (ret && ret != -EINTR && !err->pos) + prt_printf(err, "Resize worker failed; see kernel log for details\n"); + return ret; +} + +int bch2_dev_resize_resume(struct bch_fs *c, struct bch_dev *ca, + struct printbuf *err) +{ + if (!bch2_dev_resize_pending(ca)) + return 0; + + scoped_guard(rwsem_write, &c->state_lock) { + try(bch2_dev_resize_thread_start(ca)); + } + + int ret = bch2_dev_resize_kick(ca); + if (ret && ret != -ECANCELED && ret != -EINTR && !err->pos) + prt_printf(err, "Resize resume failed; see kernel log for details\n"); + return ret; +} + /* Resize on mount */ int __bch2_dev_resize_alloc(struct bch_dev *ca, u64 old_nbuckets, u64 new_nbuckets) { struct bch_fs *c = ca->fs; - u64 v[3] = { new_nbuckets - old_nbuckets, 0, 0 }; + s64 v[3] = { (s64) new_nbuckets - (s64) old_nbuckets, 0, 0 }; return bch2_trans_commit_do(ca->fs, NULL, NULL, 0, bch2_disk_accounting_mod2(trans, false, v, dev_data_type, diff --git a/fs/init/dev.h b/fs/init/dev.h index b87fc4b2ed..c680a4733b 100644 --- a/fs/init/dev.h +++ b/fs/init/dev.h @@ -38,6 +38,8 @@ int bch2_dev_add(struct bch_fs *, const char *, struct printbuf *); int bch2_dev_online(struct bch_fs *, const char *, struct printbuf *); int bch2_dev_offline(struct bch_fs *, struct bch_dev *, int, struct printbuf *); int bch2_dev_resize(struct bch_fs *, struct bch_dev *, u64, struct printbuf *); +int bch2_dev_resize_resume(struct bch_fs *, struct bch_dev *, struct printbuf *); +void bch2_dev_resize_threads_stop(struct bch_fs *); int __bch2_dev_resize_alloc(struct bch_dev *, u64, u64); diff --git a/fs/init/error.c b/fs/init/error.c index 24e12ca981..c1b1f9c26a 100644 --- a/fs/init/error.c +++ b/fs/init/error.c @@ -300,19 +300,11 @@ static enum ask_yn bch2_fsck_ask_yn(struct bch_fs *c, struct btree_trans *trans) static struct fsck_err_state *fsck_err_get(struct bch_fs *c, enum bch_sb_error_id id) { - struct fsck_err_state *s; - - list_for_each_entry(s, &c->errors.msgs, list) - if (s->id == id) { - /* - * move it to the head of the list: repeated fsck errors - * are common - */ - list_move(&s->list, &c->errors.msgs); - return s; - } + darray_for_each(c->errors.msgs, i) + if ((*i)->id == id) + return *i; - s = kzalloc(sizeof(*s), GFP_NOFS); + struct fsck_err_state *s = kzalloc(sizeof(*s), GFP_NOIO); if (!s) { if (!c->errors.msgs_alloc_err) bch_err(c, "kmalloc err, cannot ratelimit fsck errs"); @@ -320,12 +312,40 @@ static struct fsck_err_state *fsck_err_get(struct bch_fs *c, return NULL; } - INIT_LIST_HEAD(&s->list); s->id = id; - list_add(&s->list, &c->errors.msgs); + + if (darray_push(&c->errors.msgs, s)) { + if (!c->errors.msgs_alloc_err) + bch_err(c, "kmalloc err, cannot ratelimit fsck errs"); + c->errors.msgs_alloc_err = true; + kfree(s); + return NULL; + } + return s; } +static int fsck_err_nr_cmp(const void *_l, const void *_r) +{ + const struct fsck_err_state *l = *((const struct fsck_err_state **) _l); + const struct fsck_err_state *r = *((const struct fsck_err_state **) _r); + + return cmp_int(r->nr, l->nr); +} + +void bch2_fsck_err_counts_to_text(struct printbuf *out, struct bch_fs *c) +{ + guard(mutex)(&c->errors.msgs_lock); + + sort_nonatomic(c->errors.msgs.data, c->errors.msgs.nr, + sizeof(c->errors.msgs.data[0]), fsck_err_nr_cmp, NULL); + + darray_for_each(c->errors.msgs, i) { + bch2_sb_error_id_to_text(out, (*i)->id); + prt_printf(out, "\t%llu\n", (*i)->nr); + } +} + /* s/fix?/fixing/ s/recreate?/recreating/ */ static void prt_actioning(struct printbuf *out, const char *action) { @@ -467,6 +487,7 @@ int bch2_fsck_err_opt(struct bch_fs *c, int __bch2_fsck_err(struct bch_fs *c, struct btree_trans *trans, + struct bpos pos, enum bch_fsck_flags flags, enum bch_sb_error_id err, const char *fmt, ...) @@ -485,6 +506,15 @@ int __bch2_fsck_err(struct bch_fs *c, if (!c) c = trans->c; + /* + * An inode-scoped error (pos != POS_MIN) records damage against the + * inode before the outcome below is decided: the error is the damage, + * whether or not we fix it - and silent/ratelimited instances still + * record (recording is idempotent). + */ + if (!bpos_eq(pos, POS_MIN) && !WARN_ON(!trans)) + try(bch2_damage_record(trans, pos, err)); + /* * Ugly: if there's a transaction in the current task it has to be * passed in to unlock if we prompt for user input. @@ -738,24 +768,25 @@ int __bch2_bkey_fsck_err(struct bch_fs *c, prt_vprintf(&buf, fmt, args); va_end(args); - int ret = __bch2_fsck_err(c, NULL, fsck_flags, err, "%s, delete?", buf.buf); + int ret = __bch2_fsck_err(c, NULL, POS_MIN, fsck_flags, err, "%s, delete?", buf.buf); return ret; } static void __bch2_flush_fsck_errs(struct bch_fs *c, bool print) { - struct fsck_err_state *s, *n; - guard(mutex)(&c->errors.msgs_lock); - list_for_each_entry_safe(s, n, &c->errors.msgs, list) { + darray_for_each(c->errors.msgs, i) { + struct fsck_err_state *s = *i; + if (print && s->ratelimited && s->last_msg) bch_err(c, "Saw %llu errors like:\n %s", s->nr, s->last_msg); - list_del(&s->list); kfree(s->last_msg); kfree(s); } + + darray_exit(&c->errors.msgs); } void bch2_flush_fsck_errs(struct bch_fs *c) @@ -768,6 +799,155 @@ void bch2_free_fsck_errs(struct bch_fs *c) __bch2_flush_fsck_errs(c, false); } +/* + * Paths damaged during fsck, remembered for the end-of-fsck summary - see + * struct fsck_damaged_path. Recorded when an inode-scoped error is reported + * (__bch2_fsck_err() with a pos), deduped by (inum, snapshot) with error ids + * merged. Dedup is what makes this restart-safe: an error re-reported after a + * transaction restart just re-merges the same id. + */ + +#define FSCK_DAMAGED_PATHS_MAX 4096 +#define FSCK_DAMAGED_PATHS_PRINT 200 + +static void fsck_damaged_path_add_err(struct fsck_damaged_path *i, + enum bch_sb_error_id err) +{ + for (unsigned j = 0; j < i->nr_errors; j++) + if (i->errors[j] == err) + return; + + if (i->nr_errors < ARRAY_SIZE(i->errors)) + i->errors[i->nr_errors++] = err; +} + +/* + * The in-memory half of damage recording, feeding the end-of-fsck summary + * and the fsck_damaged_paths debugfs file; called from bch2_damage_record() + * alongside the durable damage btree write. Goes away once reporting reads + * the damage btree. + */ +void bch2_fsck_damaged(struct btree_trans *trans, struct bpos pos, + enum bch_sb_error_id err) +{ + struct bch_fs *c = trans->c; + + /* + * Both key-position conventions land here: extent-style keys carry + * the inum in pos.inode; inode keys live at (0, inum, snapshot), so + * a zero inode field means the inum is in the offset field: + */ + u64 inum = pos.inode ?: pos.offset; + + guard(mutex)(&c->errors.msgs_lock); + + /* Damage on one inode arrives in runs - check the last entry first: */ + if (c->errors.damaged_paths.nr) { + struct fsck_damaged_path *last = &darray_last(c->errors.damaged_paths); + if (last->inum == inum && last->snapshot == pos.snapshot) { + fsck_damaged_path_add_err(last, err); + return; + } + } + + darray_for_each(c->errors.damaged_paths, i) + if (i->inum == inum && i->snapshot == pos.snapshot) { + fsck_damaged_path_add_err(i, err); + return; + } + + if (c->errors.damaged_paths.nr >= FSCK_DAMAGED_PATHS_MAX || + darray_push(&c->errors.damaged_paths, ((struct fsck_damaged_path) { + .inum = inum, + .snapshot = pos.snapshot, + .nr_errors = 1, + .errors = { err }, + }))) + c->errors.damaged_paths_alloc_err = true; +} + +/* + * A damage entry's snapshot may itself be dead by report time - that's + * exactly how keys_deleted entries arise - so a failed resolution retries + * through the inode's surviving snapshot versions: the path in a live view + * still names the file for the user. + */ +static int damaged_path_resolve(struct btree_trans *trans, u64 inum, + u32 snapshot, struct printbuf *path) +{ + printbuf_reset(path); + int ret = bch2_inum_snapshot_to_path(trans, inum, snapshot, NULL, path); + if (!ret || bch2_err_matches(ret, BCH_ERR_transaction_restart)) + return ret; + + struct bkey_s_c k; + for_each_btree_key_norestart(trans, iter, BTREE_ID_inodes, POS(0, inum), + BTREE_ITER_all_snapshots, k, ret) { + if (k.k->p.offset != inum) + break; + if (k.k->p.snapshot == snapshot || !bkey_is_inode(k.k)) + continue; + + printbuf_reset(path); + ret = bch2_inum_snapshot_to_path(trans, inum, k.k->p.snapshot, + NULL, path); + if (!ret || bch2_err_matches(ret, BCH_ERR_transaction_restart)) + return ret; + } + + return ret ?: bch_err_throw(trans->c, ENOENT_inode); +} + +void bch2_fsck_damaged_path_to_text(struct printbuf *out, struct btree_trans *trans, + const struct fsck_damaged_path *i) +{ + CLASS(printbuf, path)(); + + /* Resolve into a temp buffer so a restart doesn't duplicate output: */ + int ret = lockrestart_do(trans, + damaged_path_resolve(trans, i->inum, i->snapshot, &path)); + if (!ret) + prt_str(out, path.buf); + else + prt_printf(out, "inum %llu:%u", i->inum, i->snapshot); + + prt_str(out, ": "); + + for (unsigned j = 0; j < i->nr_errors; j++) { + if (j) + prt_str(out, ", "); + prt_str(out, bch2_sb_error_strs[i->errors[j]]); + } + prt_newline(out); +} + +void bch2_fsck_damaged_paths_to_text(struct printbuf *out, struct bch_fs *c) +{ + if (!c->errors.damaged_paths.nr) + return; + + prt_printf(out, "%zu paths damaged by fsck", c->errors.damaged_paths.nr); + if (c->errors.damaged_paths_alloc_err) + prt_str(out, " (list incomplete)"); + prt_str(out, ":\n"); + bch2_printbuf_indent_add(out, 2); + + CLASS(btree_trans, trans)(c); + u32 nr_printed = 0; + + darray_for_each(c->errors.damaged_paths, i) { + if (nr_printed++ >= FSCK_DAMAGED_PATHS_PRINT) { + prt_printf(out, "... and %zu more (untruncated list in debugfs: fsck_damaged_paths)\n", + c->errors.damaged_paths.nr - FSCK_DAMAGED_PATHS_PRINT); + break; + } + + bch2_fsck_damaged_path_to_text(out, trans, i); + } + + bch2_printbuf_indent_sub(out, 2); +} + int bch2_inum_offset_err_msg_trans_norestart(struct btree_trans *trans, struct printbuf *out, u32 subvol, struct bpos pos) { @@ -796,12 +976,14 @@ void bch2_inum_offset_err_msg_trans(struct btree_trans *trans, struct printbuf * void bch2_fs_errors_exit(struct bch_fs *c) { + darray_exit(&c->errors.damaged_paths); darray_exit(&c->errors.counts); } void bch2_fs_errors_init_early(struct bch_fs *c) { - INIT_LIST_HEAD(&c->errors.msgs); + darray_init(&c->errors.msgs); + darray_init(&c->errors.damaged_paths); mutex_init(&c->errors.msgs_lock); mutex_init(&c->errors.counts_lock); diff --git a/fs/init/error.h b/fs/init/error.h index 6ca48df4e1..6b2d55c1fd 100644 --- a/fs/init/error.h +++ b/fs/init/error.h @@ -63,7 +63,6 @@ int bch2_fs_topology_error(struct bch_fs *, const char *, ...); */ struct fsck_err_state { - struct list_head list; enum bch_sb_error_id id; u64 nr; bool ratelimited; @@ -78,19 +77,35 @@ bool __bch2_count_fsck_err(struct bch_fs *, enum bch_sb_error_id, struct printbu #define bch2_count_fsck_err(_c, _err, ...) \ __bch2_count_fsck_err(_c, BCH_FSCK_ERR_##_err, __VA_ARGS__) +void bch2_fsck_err_counts_to_text(struct printbuf *, struct bch_fs *); + int bch2_fsck_err_opt(struct bch_fs *, enum bch_fsck_flags, enum bch_sb_error_id); -__printf(5, 6) __cold +__printf(6, 7) __cold int __bch2_fsck_err(struct bch_fs *, struct btree_trans *, + struct bpos, enum bch_fsck_flags, enum bch_sb_error_id, const char *, ...); #define bch2_fsck_err(c, _flags, _err_type, ...) \ __bch2_fsck_err(type_is(c, struct bch_fs *) ? (struct bch_fs *) c : NULL,\ type_is(c, struct btree_trans *) ? (struct btree_trans *) c : NULL,\ - _flags, BCH_FSCK_ERR_##_err_type, __VA_ARGS__) + POS_MIN, _flags, BCH_FSCK_ERR_##_err_type, __VA_ARGS__) + +/* + * Record damage to an inode: which errors happened to it, as + * bch_sb_error_id - the same identifiers the superblock error counters + * and fsck use. Writes the damage btree (init/damage.c) and feeds the + * in-memory list behind the end-of-fsck summary and the + * fsck_damaged_paths debugfs file. + */ +int bch2_damage_record(struct btree_trans *, struct bpos, enum bch_sb_error_id); +void bch2_fsck_damaged(struct btree_trans *, struct bpos, enum bch_sb_error_id); +void bch2_fsck_damaged_path_to_text(struct printbuf *, struct btree_trans *, + const struct fsck_damaged_path *); +void bch2_fsck_damaged_paths_to_text(struct printbuf *, struct bch_fs *); void bch2_flush_fsck_errs(struct bch_fs *); void bch2_free_fsck_errs(struct bch_fs *); @@ -146,6 +161,37 @@ void bch2_free_fsck_errs(struct bch_fs *); _ret; \ }) +/* + * The fsck_err() variants for errors that are about a specific inode: the + * error is recorded as damage against the inode - unconditionally, before + * the fix/ignore outcome is decided (see __bch2_fsck_err()): the error + * is the damage, whether or not we decide to fix it. Recording + * completeness comes from these being the only way an inode-scoped error + * is reported - not from remembering to call a helper at each repair + * site. + */ + +#define __inode_fsck_err(_trans, _pos, _flags, _err_type, ...) \ + fsck_err_wrap(__bch2_fsck_err(NULL, _trans, _pos, _flags, \ + BCH_FSCK_ERR_##_err_type, __VA_ARGS__)) + +#define __inode_fsck_err_on(cond, _trans, _pos, _flags, _err_type, ...) \ +({ \ + might_sleep(); \ + unlikely(cond) \ + ? __inode_fsck_err(_trans, _pos, _flags, _err_type, \ + __VA_ARGS__) \ + : false; \ +}) + +#define inode_fsck_err(_trans, _pos, _err_type, ...) \ + __inode_fsck_err(_trans, _pos, \ + FSCK_CAN_FIX|FSCK_CAN_IGNORE, _err_type, __VA_ARGS__) + +#define inode_fsck_err_on(cond, _trans, _pos, _err_type, ...) \ + __inode_fsck_err_on(cond, _trans, _pos, \ + FSCK_CAN_FIX|FSCK_CAN_IGNORE, _err_type, __VA_ARGS__) + #define ret_fsck_err_wrap(_do) \ ({ \ int _ret = _do; \ @@ -174,6 +220,11 @@ void bch2_free_fsck_errs(struct bch_fs *); #define ret_fsck_err_on(cond, c, _err_type, ...) \ __ret_fsck_err_on(cond, c, FSCK_CAN_FIX|FSCK_CAN_IGNORE, _err_type, __VA_ARGS__) +#define ret_inode_fsck_err(_trans, _pos, _err_type, ...) \ + ret_fsck_err_wrap(__bch2_fsck_err(NULL, _trans, _pos, \ + FSCK_CAN_FIX|FSCK_CAN_IGNORE, \ + BCH_FSCK_ERR_##_err_type, __VA_ARGS__)) + #define ret_log_fsck_err(c, _err_type, ...) \ __ret_fsck_err(c, FSCK_CAN_IGNORE, _err_type, __VA_ARGS__) diff --git a/fs/init/error_types.h b/fs/init/error_types.h index d4d2a80991..d5284c1181 100644 --- a/fs/init/error_types.h +++ b/fs/init/error_types.h @@ -4,11 +4,32 @@ #include "sb/errors_types.h" +struct fsck_err_state; + +/* + * A path that fsck damaged or couldn't fully recover, remembered so we can + * print a short per-path summary at the end instead of burying it in the error + * firehose. Keyed by (inum, snapshot); reasons is a bitmask of enum + * bch_fsck_damage_type - deduped and OR'd on insert, so one line per path lists + * everything that happened to it, and re-recording on transaction restart is a + * no-op. + */ +struct fsck_damaged_path { + u64 inum; + u32 snapshot; + /* bch_sb_error_id, deduped; 0 terminated (error 0 is fs-level) */ + u16 nr_errors; + u16 errors[7]; +}; + struct bch_fs_errors { - struct list_head msgs; + DARRAY(struct fsck_err_state *) msgs; struct mutex msgs_lock; bool msgs_alloc_err; + DARRAY(struct fsck_damaged_path) damaged_paths; + bool damaged_paths_alloc_err; + bch_sb_errors_cpu counts; struct mutex counts_lock; }; diff --git a/fs/init/fs.c b/fs/init/fs.c index c7cdd96c62..bd0b93c440 100644 --- a/fs/init/fs.c +++ b/fs/init/fs.c @@ -320,8 +320,7 @@ static void __bch2_fs_read_only(struct bch_fs *c) u64 seq = 0; bch2_maybe_schedule_btree_bitmap_gc_stop(c); - bch2_fs_ec_stop(c); - bch2_open_buckets_stop(c, NULL, true); + bch2_open_buckets_stop(c, NULL, true, 0); bch2_copygc_stop(c); bch2_btree_write_buffer_stop(c); bch2_fs_ec_flush(c); @@ -409,6 +408,34 @@ void bch2_fs_read_only(struct bch_fs *c) bch_verbose(c, "going read-only"); + /* + * Close write points before stopping background data movers. Shrink can + * leave copygc waiting on allocator space from its dedicated + * write_point; dropping those open buckets first breaks that dependency + * so kthread_stop() does not hang behind a move write that's blocked in + * the allocator. + */ + bch2_open_buckets_stop(c, NULL, true, 0); + + /* + * Stop per-device resize workers while writes are still available. + * A pending resize may be in the middle of transactional alloc/accounting + * updates; if it survives into clean shutdown it can trip write-path + * assertions while the filesystem is already going read-only. + */ + bch2_dev_resize_threads_stop(c); + + /* + * Stop background data movers before disabling writes globally: + * reconcile/copygc move writes don't hold c->writes refs, but they do + * still need journal/btree write access to finish their final index + * updates. If we shut off writes first they'll trip -EROFS during + * shutdown and spuriously account data_update failures. + */ + bch2_fs_ec_stop(c); + bch2_reconcile_stop(c); + bch2_copygc_stop(c); + /* * Block new foreground-end write operations from starting - any new * writes will return -EROFS. Set before stopping reconcile so the @@ -476,8 +503,7 @@ void bch2_fs_read_only(struct bch_fs *c) bch2_verify_accounting_clean(c); } else { /* Make sure error counts/counters are persisted */ - guard(memalloc_flags)(PF_MEMALLOC_NOFS); - guard(mutex)(&c->sb_lock); + guard(mutex_noio)(&c->sb_lock); bch2_write_super(c); bch_verbose(c, "done going read-only, filesystem not clean"); @@ -603,8 +629,7 @@ static int __bch2_fs_read_write(struct bch_fs *c, bool early) set_bit(BCH_FS_was_rw, &c->flags); if (test_and_clear_bit(BCH_FS_sb_dirty, &c->flags)) { - guard(memalloc_flags)(PF_MEMALLOC_NOFS); - guard(mutex)(&c->sb_lock); + guard(mutex_noio)(&c->sb_lock); bch2_write_super(c); } @@ -1023,8 +1048,7 @@ static int bch2_fs_opt_version_init(struct bch_fs *c, struct printbuf *out) if (c->opts.journal_rewind) prt_printf(out, "rewinding journal, fsck required\n"); - scoped_guard(memalloc_flags, PF_MEMALLOC_NOFS) { - guard(mutex)(&c->sb_lock); + scoped_guard(mutex_noio, &c->sb_lock) { struct bch_sb_field_ext *ext = bch2_sb_field_get(c->disk_sb.sb, ext); __le64 now = cpu_to_le64(ktime_get_real_seconds()); @@ -1157,7 +1181,7 @@ static int bch2_fs_init(struct bch_fs *c, struct bch_sb *sb, c->disk_sb.fs_sb = true; init_rwsem(&c->state_lock); - mutex_init(&c->sb_lock); + mutex_noio_init(&c->sb_lock); INIT_WORK(&c->read_only_work, bch2_fs_read_only_work); refcount_set(&c->ro_ref, 1); @@ -1204,8 +1228,7 @@ static int bch2_fs_init(struct bch_fs *c, struct bch_sb *sb, try(bch2_fs_capacity_init(c)); - scoped_guard(memalloc_flags, PF_MEMALLOC_NOFS) { - guard(mutex)(&c->sb_lock); + scoped_guard(mutex_noio, &c->sb_lock) { try(bch2_sb_to_fs(c, sb)); sb = c->disk_sb.sb; @@ -1552,42 +1575,79 @@ static bool bch2_fs_will_resize_on_mount(struct bch_fs *c) int bch2_fs_resize_on_mount(struct bch_fs *c) { - for_each_online_member(c, ca, BCH_DEV_READ_REF_fs_resize_on_mount) { - if (bch2_dev_will_resize_on_mount(ca)) { - u64 old_nbuckets = ca->mi.nbuckets; - u64 new_nbuckets = div64_u64(get_capacity(ca->disk_sb.bdev->bd_disk), - ca->mi.bucket_size); - - bch_info_dev(ca, "resizing to size %llu", new_nbuckets * ca->mi.bucket_size); - int ret = bch2_dev_buckets_resize(c, ca, new_nbuckets); - bch_err_fn_dev(ca, ret); - if (ret) { - enumerated_ref_put(&ca->io_ref[READ], - BCH_DEV_READ_REF_fs_resize_on_mount); - return ret; - } - - scoped_guard(memalloc_flags, PF_MEMALLOC_NOFS) { - guard(mutex)(&c->sb_lock); - struct bch_member *m = - bch2_members_v2_get_mut(c->disk_sb.sb, ca->dev_idx); - m->nbuckets = cpu_to_le64(new_nbuckets); - SET_BCH_MEMBER_RESIZE_ON_MOUNT(m, false); - - c->disk_sb.sb->features[0] &= ~cpu_to_le64(BIT_ULL(BCH_FEATURE_small_image)); - bch2_write_super(c); - } - - if (ca->mi.freespace_initialized) { - ret = __bch2_dev_resize_alloc(ca, old_nbuckets, new_nbuckets); + scoped_guard(rwsem_write, &c->state_lock) { + for_each_online_member(c, ca, BCH_DEV_READ_REF_fs_resize_on_mount) { + if (bch2_dev_will_resize_on_mount(ca)) { + u64 old_nbuckets = ca->mi.nbuckets; + u64 new_nbuckets = div64_u64(get_capacity(ca->disk_sb.bdev->bd_disk), + ca->mi.bucket_size); + + bch_info_dev(ca, "resizing to size %llu", new_nbuckets * ca->mi.bucket_size); + int ret = bch2_dev_buckets_resize(c, ca, new_nbuckets); + bch_err_fn_dev(ca, ret); if (ret) { enumerated_ref_put(&ca->io_ref[READ], - BCH_DEV_READ_REF_fs_resize_on_mount); + BCH_DEV_READ_REF_fs_resize_on_mount); return ret; } + + scoped_guard(mutex_noio, &c->sb_lock) { + struct bch_member *m = + bch2_members_v2_get_mut(c->disk_sb.sb, ca->dev_idx); + m->nbuckets = cpu_to_le64(new_nbuckets); + SET_BCH_MEMBER_RESIZE_ON_MOUNT(m, false); + + c->disk_sb.sb->features[0] &= ~cpu_to_le64(BIT_ULL(BCH_FEATURE_small_image)); + bch2_write_super(c); + } + + if (ca->mi.freespace_initialized) { + ret = __bch2_dev_resize_alloc(ca, old_nbuckets, new_nbuckets); + if (ret) { + enumerated_ref_put(&ca->io_ref[READ], + BCH_DEV_READ_REF_fs_resize_on_mount); + return ret; + } + } } } } + + /* + * A pending shrink needs reconcile_scan and backpointer btree access. + * The early resize-on-mount hook runs before btree roots are read so it + * can handle grow-on-mount image expansion; defer shrink resume until a + * later call once BCH_FS_btree_running is set. + */ + if (!test_bit(BCH_FS_btree_running, &c->flags)) + return 0; + + if (c->opts.read_only || + (c->sb.features & (BIT_ULL(BCH_FEATURE_small_image) | + BIT_ULL(BCH_FEATURE_no_default_sb)))) + return 0; + + for_each_online_member(c, ca, BCH_DEV_READ_REF_fs_resize_on_mount) { + if (!bch2_dev_resize_pending(ca)) + continue; + + CLASS(printbuf, err)(); + int ret; + + bch_info_dev(ca, "resuming resize to size %llu", + bch2_dev_resize_target(ca) * ca->mi.bucket_size); + ret = bch2_dev_resize_resume(c, ca, &err); + if (ret) { + if (err.pos) + bch_err_dev(ca, "%s", err.buf); + else + bch_err_fn_dev(ca, ret); + + enumerated_ref_put(&ca->io_ref[READ], + BCH_DEV_READ_REF_fs_resize_on_mount); + return ret; + } + } return 0; } diff --git a/fs/init/fs.rs b/fs/init/fs.rs index 1be3ec5a63..b6b2a8ccfd 100644 --- a/fs/init/fs.rs +++ b/fs/init/fs.rs @@ -3,6 +3,7 @@ use crate::btree::bkey::AsBkeyI; use crate::errcode::{bch_err_throw, bch_errcode, ret_to_result_void as ret_to_result, BchError}; use crate::alloc::buckets::DiskReservation; use crate::btree::iter::{BtreeIterFlags, CommitOpts, UpdateTriggerFlags}; +use crate::util::locking::MemallocFlags; use core::ops::ControlFlow; /// RAII guard for a device reference. Calls bch2_dev_put on drop. @@ -16,6 +17,11 @@ impl DevRef { pub fn as_mut_ptr(&self) -> *mut c::bch_dev { self.0 } + + /// The device name (sdX etc). + pub fn name(&self) -> &core::ffi::CStr { + unsafe { core::ffi::CStr::from_ptr((*self.0).name.as_ptr()) } + } } impl core::ops::Deref for DevRef { @@ -32,13 +38,19 @@ impl Drop for DevRef { } /// RAII guard for bch_fs::sb_lock. Unlocks on drop. +/// +/// Mirrors the C `mutex_noio` guard: sb_lock is held precisely to guard +/// allocations that must not recurse into reclaim IO, so the lock brackets a +/// PF_MEMALLOC_NOIO scope. The explicit Drop below runs before the `_noio` +/// field is dropped, so the order is unlock-then-restore - matching the C side. pub struct SbLockGuard<'a> { fs: &'a Fs, + _noio: MemallocFlags, } impl Drop for SbLockGuard<'_> { fn drop(&mut self) { - unsafe { c::mutex_unlock(&mut (*self.fs.raw).sb_lock ); } + unsafe { c::mutex_unlock(&mut (*self.fs.raw).sb_lock.lock); } } } @@ -70,6 +82,25 @@ impl BorrowedFs { } impl Fs { + /// The filesystem's options, as resolved at open. + pub fn opts(&self) -> &c::bch_opts { + unsafe { &(*self.raw).opts } + } + + /// log2 of the filesystem block size in 512-byte sectors. + pub fn block_bits(&self) -> u32 { + unsafe { (*self.raw).block_bits as u32 } + } + + pub fn chacha20_key_set(&self) -> bool { + unsafe { (*self.raw).chacha20_key_set } + } + + /// The filesystem's superblock handle. + pub fn disk_sb(&self) -> &c::bch_sb_handle { + unsafe { &(*self.raw).disk_sb } + } + /// Create a non-owning `Fs` view from a raw pointer. /// /// Returns `ManuallyDrop` to prevent `Fs::drop` from calling @@ -93,8 +124,9 @@ impl Fs { /// Acquire the superblock lock, returning a guard that releases it on drop. pub fn sb_lock(&self) -> SbLockGuard<'_> { - unsafe { c::mutex_lock(&mut (*self.raw).sb_lock); } - SbLockGuard { fs: self } + let _noio = MemallocFlags::noio(); + unsafe { c::mutex_lock(&mut (*self.raw).sb_lock.lock); } + SbLockGuard { fs: self, _noio } } /// Write superblock to disk. Caller must hold sb_lock. @@ -203,6 +235,29 @@ impl Fs { if ca.is_null() { None } else { Some(DevRef(ca)) } } + /// Run an option's pre-set hook; None dev = filesystem scope. + pub fn opt_hook_pre_set(&self, dev: Option<&DevRef>, id: c::bch_opt_id, v: u64) + -> Result<(), BchError> + { + ret_to_result(unsafe { + c::bch2_opt_hook_pre_set(self.raw, + dev.map_or(core::ptr::null_mut(), |d| d.as_mut_ptr()), + 0, id, v, true, core::ptr::null_mut()) + }) + } + + /// Set an option in the superblock; None dev = filesystem scope. + pub fn opt_set_sb(&self, dev: Option<&DevRef>, opt: &c::bch_option, v: u64, + val_str: Option<&core::ffi::CStr>) + { + unsafe { + c::bch2_opt_set_sb(self.raw, + dev.map_or(core::ptr::null_mut(), |d| d.as_mut_ptr()), + opt, v, + val_str.map_or(core::ptr::null(), |s| s.as_ptr())); + } + } + /// Start the filesystem (recovery, journal replay, etc). pub fn start(&self) -> Result<(), BchError> { ret_to_result(unsafe { c::bch2_fs_start(self.raw) }) @@ -224,6 +279,21 @@ impl Fs { ret_to_result(unsafe { c::bch2_write_super(self.raw) }) } + /// bch2_write_super(), lifting nochanges around the write: inspection + /// opens (norecovery/nostart) imply nochanges, which makes write_super + /// a silent no-op - the right default, except when an offline admin + /// command is performing the user's explicitly requested write. + /// Caller must hold sb_lock. + pub fn write_super_force(&self) -> Result<(), BchError> { + unsafe { + let saved = (*self.raw).opts.nochanges; + (*self.raw).opts.nochanges = 0; + let ret = c::bch2_write_super(self.raw); + (*self.raw).opts.nochanges = saved; + ret_to_result(ret) + } + } + /// Check if a device index exists and has a device pointer. pub fn dev_exists(&self, dev: u32) -> bool { unsafe { diff --git a/fs/init/passes.c b/fs/init/passes.c index 5136fdf8c1..f74ff72b33 100644 --- a/fs/init/passes.c +++ b/fs/init/passes.c @@ -29,6 +29,7 @@ #include "snapshots/snapshot.h" #include "snapshots/subvolume.h" +#include "init/damage.h" #include "init/recovery.h" #include "init/passes.h" #include "init/fs.h" @@ -129,7 +130,7 @@ static struct recovery_pass_entry *bch2_sb_recovery_pass_entry(struct bch_fs *c, { enum bch_recovery_pass_stable stable = bch2_recovery_pass_to_stable(pass); - lockdep_assert_held(&c->sb_lock); + lockdep_assert_held(&c->sb_lock.lock); struct bch_sb_field_recovery_passes *r = bch2_sb_field_get(c->disk_sb.sb, recovery_passes); @@ -151,8 +152,7 @@ static void bch2_sb_recovery_pass_complete(struct bch_fs *c, enum bch_recovery_pass pass, s64 start_time) { - guard(memalloc_flags)(PF_MEMALLOC_NOFS); - guard(mutex)(&c->sb_lock); + guard(mutex_noio)(&c->sb_lock); struct bch_sb_field_ext *ext = bch2_sb_field_get(c->disk_sb.sb, ext); __clear_bit_le64(bch2_recovery_pass_to_stable(pass), ext->recovery_passes_required); @@ -175,8 +175,7 @@ static void bch2_sb_recovery_pass_complete(struct bch_fs *c, void bch2_recovery_pass_set_no_ratelimit(struct bch_fs *c, enum bch_recovery_pass pass) { - guard(memalloc_flags)(PF_MEMALLOC_NOFS); - guard(mutex)(&c->sb_lock); + guard(mutex_noio)(&c->sb_lock); struct recovery_pass_entry *e = bch2_sb_recovery_pass_entry(c, pass); if (e && !BCH_RECOVERY_PASS_NO_RATELIMIT(e)) { @@ -188,7 +187,7 @@ void bch2_recovery_pass_set_no_ratelimit(struct bch_fs *c, static bool bch2_recovery_pass_entry_get_locked(struct bch_fs *c, enum bch_recovery_pass pass, struct recovery_pass_entry *e) { - lockdep_assert_held(&c->sb_lock); + lockdep_assert_held(&c->sb_lock.lock); struct bch_sb_field_recovery_passes *r = bch2_sb_field_get(c->disk_sb.sb, recovery_passes); @@ -228,8 +227,7 @@ static bool bch2_recovery_pass_want_ratelimit_locked(struct bch_fs *c, enum bch_ bool bch2_recovery_pass_want_ratelimit(struct bch_fs *c, enum bch_recovery_pass pass, unsigned runtime_fraction) { - guard(memalloc_flags)(PF_MEMALLOC_NOFS); - guard(mutex)(&c->sb_lock); + guard(mutex_noio)(&c->sb_lock); return bch2_recovery_pass_want_ratelimit_locked(c, pass, runtime_fraction); } @@ -325,9 +323,9 @@ static bool recovery_pass_needs_rewind(struct bch_fs *c, enum bch_recovery_pass pass) { struct bch_fs_recovery *r = &c->recovery; - return test_bit(BCH_FS_in_recovery, &c->flags) && + return test_bit(BCH_FS_running_recovery_passes, &c->flags) && r->current_pass > pass && - !(r->passes_complete & BIT_ULL(pass)); + !(r->passes_attempted & BIT_ULL(pass)); } static bool recovery_pass_needs_set(struct bch_fs *c, @@ -343,6 +341,10 @@ static bool recovery_pass_needs_set(struct bch_fs *c, if (pass == BCH_RECOVERY_PASS_scan_for_btree_nodes) *flags |= RUN_RECOVERY_PASS_nopersistent; + if ((*flags & RUN_RECOVERY_PASS_skip_if_complete) && + (r->passes_complete & BIT_ULL(pass))) + return false; + if ((*flags & RUN_RECOVERY_PASS_ratelimit) && !bch2_recovery_pass_want_ratelimit_locked(c, pass, 100)) *flags &= ~RUN_RECOVERY_PASS_ratelimit; @@ -383,7 +385,12 @@ int __bch2_run_explicit_recovery_pass(struct bch_fs *c, { struct bch_fs_recovery *r = &c->recovery; - lockdep_assert_held(&c->sb_lock); + if (!(flags & RUN_RECOVERY_PASS_ephemeral)) + lockdep_assert_held(&c->sb_lock.lock); + + if (c->opts.norecovery || + (c->opts.recovery_passes_exclude & BIT_ULL(pass))) + return 0; bch2_printbuf_make_room(out, 1024); guard(printbuf_atomic)(out); @@ -394,10 +401,10 @@ int __bch2_run_explicit_recovery_pass(struct bch_fs *c, out->suppress = false; - bool in_recovery = test_bit(BCH_FS_in_recovery, &c->flags); + bool running = test_bit(BCH_FS_running_recovery_passes, &c->flags); bool ratelimit = flags & RUN_RECOVERY_PASS_ratelimit; - if (flags & RUN_RECOVERY_PASS_nopersistent) { + if (flags & (RUN_RECOVERY_PASS_nopersistent|RUN_RECOVERY_PASS_ephemeral)) { r->scheduled_passes_ephemeral |= BIT_ULL(pass); } else { struct bch_sb_field_ext *ext = bch2_sb_field_get(c->disk_sb.sb, ext); @@ -405,6 +412,16 @@ int __bch2_run_explicit_recovery_pass(struct bch_fs *c, ext->recovery_passes_required); } + /* + * Recorded above, but not run: repair found mid-mount is still repair, + * and a tool that opened this filesystem to inspect it doesn't want a + * pass starting underneath it - accounting underflow scheduling + * check_allocations is the one that bites. The requirement stays in the + * superblock, so the next mount that isn't skipping does the work. + */ + if (c->opts.recovery_passes_skip_scheduled) + return 0; + if (pass < BCH_RECOVERY_PASS_set_may_go_rw && test_bit(BCH_FS_may_go_rw, &c->flags)) { prt_printf(out, "need recovery pass %s (%u), but already rw\n", @@ -417,9 +434,35 @@ int __bch2_run_explicit_recovery_pass(struct bch_fs *c, else r->passes_ratelimiting &= ~BIT_ULL(pass); - if (in_recovery && !ratelimit && !recovery_pass_should_defer(pass, r->current_passes)) { - bool rewind = recovery_pass_needs_rewind(c, pass); + bool rewind = recovery_pass_needs_rewind(c, pass); + + /* + * A pass that already ran this run - completed OR failed - must never + * be re-run in the same loop: that's the rewind invariant, which + * recovery_pass_needs_rewind enforces by gating on passes_attempted. + * (Gating on passes_complete looped: a failing pass never completes, + * so under errors=continue a later pass re-requesting it rewound + * forever.) The "run it now because it can't be deferred to the + * background" arm has to honor the same invariant: otherwise a pass + * that reschedules an earlier, already-run pass (check_key_has_snapshot + * scheduling check_inodes/check_extents while running check_xattrs, + * once the dead-snapshot keys those passes would clean are still + * present) injects it back into current_passes and we re-run the whole + * content-check range out of order, looping. + */ + bool run_now = rewind || + (!recovery_pass_should_defer(pass, r->current_passes) && + !(r->passes_attempted & BIT_ULL(pass))); + /* + * Ephemeral scheduling is best-effort and must never rewind: the caller + * may be a BTREE_TRIGGER_atomic trigger committed to its commit, which + * can't restart recovery (and ignores our return). If the pass already + * ran, the scheduled_passes_ephemeral backstop reruns it via the async + * runner instead. + */ + if (running && !ratelimit && run_now && + !(rewind && (flags & RUN_RECOVERY_PASS_ephemeral))) { prt_printf(out, "running recovery pass %s (%u), currently at %s (%u)%s\n", bch2_recovery_passes[pass], pass, bch2_recovery_passes[r->current_pass], r->current_pass, @@ -428,9 +471,19 @@ int __bch2_run_explicit_recovery_pass(struct bch_fs *c, r->current_passes |= BIT_ULL(pass); if (rewind) { - r->rewound_to = r->rewound_to + unsigned rewound_to = r->rewound_to ? min(r->rewound_to, pass) : pass; + /* + * Only log when the rewind target actually changes - the + * same rewind gets re-requested on every call that finds the + * same damage, and we don't want to spam for those. + */ + if (rewound_to != r->rewound_to) + bch_info(c, "recovery: rewinding to %s (%u), currently running %s (%u)", + bch2_recovery_passes[pass], pass, + bch2_recovery_passes[r->current_pass], r->current_pass); + r->rewound_to = rewound_to; return bch_err_throw(c, restart_recovery); } } else { @@ -459,8 +512,19 @@ int bch2_run_explicit_recovery_pass(struct bch_fs *c, !recovery_pass_needs_set(c, pass, &flags)) return 0; - guard(memalloc_flags)(PF_MEMALLOC_NOFS); - guard(mutex)(&c->sb_lock); + /* + * An ephemeral schedule only touches in-memory recovery state under + * r->lock and never writes the superblock, so it doesn't need (and must + * not take) sb_lock - callers may hold btree locks: + */ + if (flags & RUN_RECOVERY_PASS_ephemeral) { + bool write_sb = false; + int ret = __bch2_run_explicit_recovery_pass(c, out, pass, flags, &write_sb); + WARN_ON(write_sb); + return ret; + } + + guard(mutex_noio)(&c->sb_lock); bool write_sb = false; int ret = __bch2_run_explicit_recovery_pass(c, out, pass, flags, &write_sb); if (write_sb) @@ -477,18 +541,24 @@ int bch2_require_recovery_pass(struct bch_fs *c, struct printbuf *out, enum bch_recovery_pass pass) { - if (test_bit(BCH_FS_in_recovery, &c->flags) && + if (test_bit(BCH_FS_running_recovery_passes, &c->flags) && c->recovery.passes_complete & BIT_ULL(pass)) return 0; - guard(memalloc_flags)(PF_MEMALLOC_NOFS); - guard(mutex)(&c->sb_lock); + guard(mutex_noio)(&c->sb_lock); if (bch2_recovery_pass_want_ratelimit_locked(c, pass, 100)) return 0; enum bch_run_recovery_pass_flags flags = 0; + /* + * If the required pass is in our past, __bch2_run_explicit_recovery_pass + * arms a rewind and returns restart_recovery; otherwise it schedules the + * pass and returns 0, and it'll run later - recovery_pass_will_run. + * (restart_recovery must only come from an actually-armed rewind, or the + * loop sees restart_recovery with rewound_to unset and fails.) + */ bool write_sb = false; int ret = __bch2_run_explicit_recovery_pass(c, out, pass, flags, &write_sb) ?: bch_err_throw(c, recovery_pass_will_run); @@ -509,20 +579,22 @@ static int bch2_run_recovery_pass(struct bch_fs *c, enum bch_recovery_pass pass) s64 start_time = ktime_get_real_seconds(); int ret = p->fn(c); if (ret) { - s64 end_time = ktime_get_real_seconds(); - bch_err(c, "%s(): error %s", p->name, bch2_err_str(ret)); - r->passes_failing |= BIT_ULL(pass); - /* - * Ratelimit retries the same way the sb ratelimits expensive - * passes, but in memory - a failing pass doesn't get to write - * the superblock. flags stays 0, so this throttle applies even - * to passes the sb marks NO_RATELIMIT: that flag is about not - * throttling successful reruns, not about hammering failures. - */ - r->passes_failing_ratelimit[pass] = (struct recovery_pass_entry) { - .last_run = cpu_to_le64(end_time), - .last_runtime = cpu_to_le32(max(0, end_time - start_time)), - }; + if (!bch2_err_matches(ret, BCH_ERR_restart_recovery)) { + s64 end_time = ktime_get_real_seconds(); + bch_err(c, "%s(): error %s", p->name, bch2_err_str(ret)); + r->passes_failing |= BIT_ULL(pass); + /* + * Ratelimit retries the same way the sb ratelimits expensive + * passes, but in memory - a failing pass doesn't get to write + * the superblock. flags stays 0, so this throttle applies even + * to passes the sb marks NO_RATELIMIT: that flag is about not + * throttling successful reruns, not about hammering failures. + */ + r->passes_failing_ratelimit[pass] = (struct recovery_pass_entry) { + .last_run = cpu_to_le64(end_time), + .last_runtime = cpu_to_le32(max(0, end_time - start_time)), + }; + } return ret; } @@ -550,6 +622,14 @@ int bch2_run_recovery_passes(struct bch_fs *c, u64 orig_passes_to_run, bool fail struct bch_fs_recovery *r = &c->recovery; int ret = 0; + /* + * The rewind machinery (recovery_pass_needs_rewind, require, __bch2_run) + * keys on this, not BCH_FS_in_recovery: we can rewind whenever the pass + * loop is running, which includes the async runner - not only during + * mount. BCH_FS_in_recovery is cleared before the async runner starts. + */ + set_bit(BCH_FS_running_recovery_passes, &c->flags); + spin_lock_irq(&r->lock); if (c->sb.features & BIT_ULL(BCH_FEATURE_no_alloc_info)) @@ -580,14 +660,32 @@ int bch2_run_recovery_passes(struct bch_fs *c, u64 orig_passes_to_run, bool fail } r->current_passes = orig_passes_to_run; + /* + * Fresh attempt-epoch per run: a pass attempted in a previous + * (online) run is fair game again; within one run, attempted passes + * are never rewound to or re-queued behind current_pass. + */ + r->passes_attempted = 0; + + /* + * Passes scheduled ephemerally mid-run (e.g. delete_dead_snapshots via a + * trigger) land in current_passes but not orig_passes_to_run; accumulate + * everything that's actually been scheduled so a rewind restores those + * too - otherwise the pass that triggered the rewind is dropped from the + * run and never reruns. + */ + u64 scheduled = orig_passes_to_run; enum bch_recovery_pass prev = 0; while (r->current_passes) { + scheduled |= r->current_passes; + unsigned pass = __ffs64(r->current_passes); r->current_pass = pass; r->current_passes &= ~BIT_ULL(pass); r->scheduled_passes_ephemeral &= ~BIT_ULL(pass); + r->passes_attempted |= BIT_ULL(pass); spin_unlock_irq(&r->lock); @@ -598,8 +696,8 @@ int bch2_run_recovery_passes(struct bch_fs *c, u64 orig_passes_to_run, bool fail if (r->rewound_to) { r->rewound_from = max(r->rewound_from, pass); - /* Restore r->current_passses up to and including r->rewound_to */ - r->current_passes |= orig_passes_to_run & (~0ULL << r->rewound_to); + /* Restore current_passes up to and including rewound_to */ + r->current_passes |= scheduled & (~0ULL << r->rewound_to); r->rewound_to = 0; } else if (!ret2) { r->pass_done = max(r->pass_done, pass); @@ -623,6 +721,8 @@ int bch2_run_recovery_passes(struct bch_fs *c, u64 orig_passes_to_run, bool fail r->current_pass = 0; spin_unlock_irq(&r->lock); + clear_bit(BCH_FS_running_recovery_passes, &c->flags); + return ret; } @@ -646,6 +746,15 @@ static void bch2_async_recovery_passes_work(struct work_struct *work) void bch2_run_async_recovery_passes(struct bch_fs *c) { + /* + * A nochanges mount goes fake-rw during recovery for fsck, then back to + * ro before completing (we can't hold fake-rw indefinitely - we'd oom), + * so a background pass would fire when we're no longer rw. Don't schedule + * them at all. + */ + if (c->opts.nochanges) + return; + if (!enumerated_ref_tryget(&c->writes, BCH_WRITE_REF_async_recovery_passes)) return; @@ -661,12 +770,22 @@ int bch2_run_recovery_passes_startup(struct bch_fs *c, enum bch_recovery_pass fr r->scheduled_passes_ephemeral = c->opts.recovery_passes; + /* + * Scheduled passes are repair the superblock is asking for - an upgrade + * wanting accounting rebuilt, damage found on a previous mount. Skipping + * them doesn't clear them: they stay in the superblock and run at the + * next mount that doesn't skip. For tools that open a filesystem to look + * at it rather than fix it, where check_allocations rebuilding the world + * before the first command is the opposite of what was asked for. + */ u64 passes = bch2_recovery_passes_match(PASS_ALWAYS) | (!c->sb.clean ? bch2_recovery_passes_match(PASS_UNCLEAN) : 0) | (c->opts.fsck ? bch2_recovery_passes_match(PASS_FSCK) : 0) | c->opts.recovery_passes | - c->sb.recovery_passes_required; + (!c->opts.recovery_passes_skip_scheduled + ? c->sb.recovery_passes_required + : 0); if (c->opts.recovery_pass_last) passes &= BIT_ULL(c->opts.recovery_pass_last + 1) - 1; @@ -706,9 +825,19 @@ int bch2_run_recovery_passes_startup(struct bch_fs *c, enum bch_recovery_pass fr prt_bitflags(&msg.m, bch2_recovery_passes, defer); r->scheduled_passes_ephemeral |= defer; - bch2_run_async_recovery_passes(c); } + /* + * Kick the async runner for everything scheduled to run in the + * background: the defer passes above, and passes scheduled ephemerally + * during recovery (e.g. delete_dead_snapshots via a trigger), which land + * in scheduled_passes_ephemeral but not defer. They were scheduled before + * we went rw, so their own kick was a no-op. (Itself a no-op in + * nochanges - see bch2_run_async_recovery_passes.) + */ + if (r->scheduled_passes_ephemeral) + bch2_run_async_recovery_passes(c); + return 0; } diff --git a/fs/init/passes.h b/fs/init/passes.h index e25dad3158..708345da26 100644 --- a/fs/init/passes.h +++ b/fs/init/passes.h @@ -17,6 +17,21 @@ void bch2_recovery_pass_set_no_ratelimit(struct bch_fs *, enum bch_recovery_pass enum bch_run_recovery_pass_flags { RUN_RECOVERY_PASS_nopersistent = BIT(0), RUN_RECOVERY_PASS_ratelimit = BIT(1), + /* + * Schedule ephemerally (like nopersistent) but without taking sb_lock, + * so it's safe from contexts that hold btree locks (e.g. triggers): the + * schedule touches only in-memory recovery state and never writes the + * superblock. The need is re-derivable, so persistence isn't required. + */ + RUN_RECOVERY_PASS_ephemeral = BIT(2), + /* + * Don't schedule if the pass already completed successfully this + * instance: for callers that schedule cleanup passes on encountering + * damage those passes might not fix. If the pass ran and the damage is + * still here, rescheduling can't help - it just re-arms the pass in the + * superblock on every encounter, forcing fsck on every subsequent mount. + */ + RUN_RECOVERY_PASS_skip_if_complete = BIT(3), }; static inline bool go_rw_in_recovery(struct bch_fs *c) diff --git a/fs/init/passes_format.h b/fs/init/passes_format.h index d2a52fa5c8..57c5e878bb 100644 --- a/fs/init/passes_format.h +++ b/fs/init/passes_format.h @@ -151,12 +151,14 @@ "One-time migration: set bi_subvol on root inode " \ "for pre-subvolumes filesystems") \ x(check_inodes, 24, PASS_FSCK, \ - BIT_ULL(BCH_RECOVERY_PASS_check_snapshots), \ + BIT_ULL(BCH_RECOVERY_PASS_check_snapshots)| \ + BIT_ULL(BCH_RECOVERY_PASS_delete_dead_snapshots), \ "Validate inode fields (mode, flags, i_size, " \ "bi_subvol), delete orphaned unlinked inodes, " \ "repair invalid backpointers") \ x(check_extents, 25, PASS_FSCK, \ - BIT_ULL(BCH_RECOVERY_PASS_check_inodes), \ + BIT_ULL(BCH_RECOVERY_PASS_check_inodes)| \ + BIT_ULL(BCH_RECOVERY_PASS_delete_dead_snapshots), \ "Validate extent keys: owning inode exists, " \ "snapshot valid, no overlaps, i_size and " \ "i_sectors consistent") \ @@ -166,14 +168,21 @@ "device pointers whose generation no longer " \ "matches") \ x(check_dirents, 27, PASS_FSCK, \ - BIT_ULL(BCH_RECOVERY_PASS_check_inodes), \ + BIT_ULL(BCH_RECOVERY_PASS_check_inodes)| \ + BIT_ULL(BCH_RECOVERY_PASS_delete_dead_snapshots), \ "Validate directory entries: target inode exists " \ "in correct snapshot, d_type matches inode mode, " \ "hash values correct") \ x(check_xattrs, 28, PASS_FSCK, \ - BIT_ULL(BCH_RECOVERY_PASS_check_inodes), \ + BIT_ULL(BCH_RECOVERY_PASS_check_inodes)| \ + BIT_ULL(BCH_RECOVERY_PASS_delete_dead_snapshots), \ "Validate xattr entries: owning inode exists " \ "in valid snapshot, hash correct; delete orphans") \ + x(check_damage, 49, PASS_FSCK, \ + BIT_ULL(BCH_RECOVERY_PASS_check_inodes), \ + "Delete damage keys with no inode at the " \ + "same position - left behind by kernels " \ + "without the damage btree") \ x(check_root, 29, PASS_ONLINE|PASS_FSCK, \ BIT_ULL(BCH_RECOVERY_PASS_check_inodes), \ "Ensure root subvolume and root directory inode " \ diff --git a/fs/init/passes_types.h b/fs/init/passes_types.h index fb888b2aef..3ff7d8f615 100644 --- a/fs/init/passes_types.h +++ b/fs/init/passes_types.h @@ -18,6 +18,16 @@ struct bch_fs_recovery { /* bitmask of recovery passes that we actually ran */ u64 passes_complete; + /* + * Every pass this run dispatched, successful or not - the rewind + * gate: we never rewind to (or re-queue behind us) a pass that + * already ran this run. Gating on passes_complete alone looped: a + * pass that runs and fails never completes, so under + * errors=continue a later pass re-requesting it rewound forever + * (delete_dead_snapshots <-> check_subvols on an unrepairable + * snapshot/subvol edge). + */ + u64 passes_attempted; u64 passes_failing; u64 passes_ratelimiting; diff --git a/fs/init/recovery.c b/fs/init/recovery.c index bab281e2c0..a402a1737f 100644 --- a/fs/init/recovery.c +++ b/fs/init/recovery.c @@ -51,8 +51,7 @@ int bch2_btree_lost_data(struct bch_fs *c, { int ret = 0; - guard(memalloc_flags)(PF_MEMALLOC_NOFS); - guard(mutex)(&c->sb_lock); + guard(mutex_noio)(&c->sb_lock); bool write_sb = false; struct bch_sb_field_ext *ext = bch2_sb_field_get(c->disk_sb.sb, ext); @@ -153,8 +152,7 @@ void bch2_set_btree_clean(struct bch_fs *c, enum btree_id btree) if (c->sb.btrees_clean & BIT_ULL(btree)) return; - guard(memalloc_flags)(PF_MEMALLOC_NOFS); - guard(mutex)(&c->sb_lock); + guard(mutex_noio)(&c->sb_lock); if (!(c->sb.btrees_clean & BIT_ULL(btree))) { struct bch_sb_field_ext *ext = bch2_sb_field_get(c->disk_sb.sb, ext); __test_and_set_bit_le64(btree, &ext->btrees_clean); @@ -168,8 +166,7 @@ void bch2_clear_btree_clean(struct bch_fs *c, enum btree_id btree) if (!(c->sb.btrees_clean & BIT_ULL(btree))) return; - guard(memalloc_flags)(PF_MEMALLOC_NOFS); - guard(mutex)(&c->sb_lock); + guard(mutex_noio)(&c->sb_lock); if (c->sb.btrees_clean & BIT_ULL(btree)) { struct bch_sb_field_ext *ext = bch2_sb_field_get(c->disk_sb.sb, ext); __clear_bit_le64(btree, &ext->btrees_clean); @@ -187,8 +184,7 @@ static void kill_btree(struct bch_fs *c, enum btree_id btree) /* for -o reconstruct_alloc: */ static void bch2_reconstruct_alloc(struct bch_fs *c) { - guard(memalloc_flags)(PF_MEMALLOC_NOFS); - guard(mutex)(&c->sb_lock); + guard(mutex_noio)(&c->sb_lock); struct bch_sb_field_ext *ext = bch2_sb_field_get(c->disk_sb.sb, ext); __set_bit_le64(BCH_RECOVERY_PASS_STABLE_check_allocations, ext->recovery_passes_required); @@ -246,8 +242,7 @@ void bch2_ignore_journal_rewind_errors(struct bch_fs *c) * will be stale for buckets whose state changed between the rewind * point and the original journal head. */ - guard(memalloc_flags)(PF_MEMALLOC_NOFS); - guard(mutex)(&c->sb_lock); + guard(mutex_noio)(&c->sb_lock); struct bch_sb_field_ext *ext = bch2_sb_field_get(c->disk_sb.sb, ext); @@ -837,8 +832,7 @@ static int __bch2_fs_recovery(struct bch_fs *c) try(journal_replay_early(c, clean)); - scoped_guard(rwsem_write, &c->state_lock) - try(bch2_fs_resize_on_mount(c)); + try(bch2_fs_resize_on_mount(c)); if (c->sb.features & BIT_ULL(BCH_FEATURE_small_image)) { bch_info(c, "filesystem is an unresized image file, mounting ro"); @@ -974,6 +968,8 @@ static int __bch2_fs_recovery(struct bch_fs *c) set_bit(BCH_FS_may_go_rw, &c->flags); clear_bit(BCH_FS_in_fsck, &c->flags); + try(bch2_fs_resize_on_mount(c)); + /* in case we don't run journal replay, i.e. norecovery mode */ set_bit(BCH_FS_accounting_replay_done, &c->flags); @@ -988,6 +984,13 @@ static int __bch2_fs_recovery(struct bch_fs *c) bch2_journal_meta(&c->journal); } + if (c->errors.msgs.nr) { + CLASS(bch_log_msg, msg)(c); + prt_printf(&msg.m, "errors this recovery:\n"); + bch2_fsck_err_counts_to_text(&msg.m, c); + bch2_fsck_damaged_paths_to_text(&msg.m, c); + } + /* If we fixed errors, verify that fs is actually clean now: */ if (IS_ENABLED(CONFIG_BCACHEFS_DEBUG) && errors_fixed && @@ -1019,7 +1022,7 @@ static int __bch2_fs_recovery(struct bch_fs *c) bch_verbose(c, "quotas done"); } - scoped_guard(mutex, &c->sb_lock) { + scoped_guard(mutex_noio, &c->sb_lock) { struct bch_sb_field_ext *ext = bch2_sb_field_get(c->disk_sb.sb, ext); bool write_sb = false; @@ -1078,12 +1081,6 @@ static int __bch2_fs_recovery(struct bch_fs *c) bch2_write_super(c); } - if (test_bit(BCH_FS_need_delete_dead_snapshots, &c->flags) && - !c->opts.nochanges) { - bch2_fs_read_write_early(c); - bch2_delete_dead_snapshots_async(c); - } - /* * (Hopefully unnecessary) cleanup, once per mount - we should be * killing replicas entries when accounting entries go to 0, but - old @@ -1118,8 +1115,7 @@ int bch2_fs_initialize(struct bch_fs *c) bch_notice(c, "initializing new filesystem"); set_bit(BCH_FS_new_fs, &c->flags); - scoped_guard(memalloc_flags, PF_MEMALLOC_NOFS) { - guard(mutex)(&c->sb_lock); + scoped_guard(mutex_noio, &c->sb_lock) { c->disk_sb.sb->compat[0] |= cpu_to_le64(BIT_ULL(BCH_COMPAT_extents_above_btree_updates_done)); c->disk_sb.sb->compat[0] |= cpu_to_le64(BIT_ULL(BCH_COMPAT_bformat_overflow_done)); c->disk_sb.sb->compat[0] |= cpu_to_le64(BIT_ULL(BCH_COMPAT_no_stale_ptrs)); @@ -1213,8 +1209,7 @@ int bch2_fs_initialize(struct bch_fs *c) bch_info(c, "fs initialized, journal seq %llu rewind_seq %llu", init_seq - 1, init_seq); - scoped_guard(memalloc_flags, PF_MEMALLOC_NOFS) { - guard(mutex)(&c->sb_lock); + scoped_guard(mutex_noio, &c->sb_lock) { SET_BCH_SB_INITIALIZED(c->disk_sb.sb, true); SET_BCH_SB_CLEAN(c->disk_sb.sb, false); diff --git a/fs/journal/init.c b/fs/journal/init.c index 43c0345b50..3c60846453 100644 --- a/fs/journal/init.c +++ b/fs/journal/init.c @@ -75,8 +75,7 @@ static int bch2_set_nr_journal_buckets_iter(struct bch_dev *ca, unsigned nr, ret = 0; scoped_guard(journal_block, &c->journal) { - guard(memalloc_flags)(PF_MEMALLOC_NOFS); - guard(mutex)(&c->sb_lock); + guard(mutex_noio)(&c->sb_lock); memcpy(new_buckets, ja->buckets, ja->nr * sizeof(u64)); memcpy(new_bucket_seq, ja->bucket_seq, ja->nr * sizeof(u64)); @@ -198,8 +197,7 @@ int bch2_dev_journal_bucket_delete(struct bch_dev *ca, u64 b) struct journal *j = &c->journal; struct journal_device *ja = &ca->journal; - guard(memalloc_flags)(PF_MEMALLOC_NOFS); - guard(mutex)(&c->sb_lock); + guard(mutex_noio)(&c->sb_lock); unsigned pos; for (pos = 0; pos < ja->nr; pos++) if (ja->buckets[pos] == b) @@ -219,37 +217,53 @@ int bch2_dev_journal_bucket_delete(struct bch_dev *ca, u64 b) &new_buckets[pos + 1], (ja->nr - 1 - pos) * sizeof(new_buckets[0])); - int ret = bch2_journal_buckets_to_sb(c, ca, ja->buckets, ja->nr - 1) ?: - bch2_write_super(c); + int ret; + + scoped_guard(journal_block, &c->journal) { + ret = bch2_journal_buckets_to_sb(c, ca, new_buckets, ja->nr - 1) ?: + bch2_write_super(c); + if (ret) + break; + + scoped_guard(spinlock, &j->lock) { + if (pos < ja->discard_idx) + --ja->discard_idx; + if (pos < ja->dirty_idx_ondisk) + --ja->dirty_idx_ondisk; + if (pos < ja->dirty_idx) + --ja->dirty_idx; + if (pos < ja->cur_idx) + --ja->cur_idx; + + ja->nr--; + + memmove(&ja->buckets[pos], + &ja->buckets[pos + 1], + (ja->nr - pos) * sizeof(ja->buckets[0])); + + memmove(&ja->bucket_seq[pos], + &ja->bucket_seq[pos + 1], + (ja->nr - pos) * sizeof(ja->bucket_seq[0])); + + bch2_journal_space_available(j); + } + } + if (ret) { kfree(new_buckets); return ret; } - scoped_guard(spinlock, &j->lock) { - if (pos < ja->discard_idx) - --ja->discard_idx; - if (pos < ja->dirty_idx_ondisk) - --ja->dirty_idx_ondisk; - if (pos < ja->dirty_idx) - --ja->dirty_idx; - if (pos < ja->cur_idx) - --ja->cur_idx; - - ja->nr--; - - memmove(&ja->buckets[pos], - &ja->buckets[pos + 1], - (ja->nr - pos) * sizeof(ja->buckets[0])); - - memmove(&ja->bucket_seq[pos], - &ja->bucket_seq[pos + 1], - (ja->nr - pos) * sizeof(ja->bucket_seq[0])); - - bch2_journal_space_available(j); + kfree(new_buckets); + + { + CLASS(btree_trans, trans)(c); + ret = commit_do(trans, NULL, NULL, 0, + bch2_trans_mark_metadata_bucket(trans, ca, b, + BCH_DATA_free, 0, + BTREE_TRIGGER_transactional)); } - kfree(new_buckets); return 0; } @@ -282,7 +296,7 @@ int bch2_dev_journal_alloc(struct bch_dev *ca, bool new_fs) */ nr = clamp_t(unsigned, nr, BCH_JOURNAL_BUCKETS_MIN, - system_totalram_bytes() / 4 / bucket_bytes(ca)); + div64_u64(system_totalram_bytes() / 4, bucket_bytes(ca))); ret = bch2_set_nr_journal_buckets_loop(c, ca, nr, new_fs); err: @@ -737,7 +751,7 @@ void bch2_fs_journal_init_early(struct journal *j) { static struct lock_class_key res_key; - mutex_init(&j->buf_lock); + mutex_noio_init(&j->buf_lock); spin_lock_init(&j->lock); spin_lock_init(&j->err_lock); INIT_DELAYED_WORK(&j->write_work, bch2_journal_write_work); diff --git a/fs/journal/journal.c b/fs/journal/journal.c index 8f86c9e36d..08d9f90fed 100644 --- a/fs/journal/journal.c +++ b/fs/journal/journal.c @@ -780,7 +780,7 @@ static void journal_buf_prealloc(struct journal *j) unsigned buf_size = j->buf_size_want; spin_unlock(&j->lock); - void *buf = kvmalloc(buf_size, GFP_NOFS); + void *buf = kvmalloc(buf_size, GFP_NOIO); spin_lock(&j->lock); if (!buf) @@ -934,17 +934,6 @@ static int __journal_res_get(struct journal *j, struct journal_res *res, return ret; } -static unsigned max_dev_latency(struct bch_fs *c) -{ - u64 nsecs = 0; - - guard(rcu)(); - for_each_member_device_rcu(c, ca, &c->allocator.rw_devs[BCH_DATA_journal]) - nsecs = max(nsecs, ca->io_latency[WRITE].stats.max_duration); - - return nsecs_to_jiffies(nsecs); -} - /* * Essentially the entry function to the journaling code. When bcachefs is doing * a btree insert, it calls this function to get the current journal write. @@ -963,7 +952,14 @@ int bch2_journal_res_get_slowpath(struct journal *j, struct journal_res *res, return __journal_res_get(j, res, flags); struct bch_fs *c = container_of(j, struct bch_fs, journal); - long total_wait = max(max_dev_latency(c) * 2, HZ * 10); + /* + * Over every online device, not just the journal's: a flushing commit + * preflushes every rw member (journal_write_preflush()), so a member + * that carries no journal at all still paces the wait. Sizing this from + * the journal devices alone reports "stuck" routinely on an array whose + * slowest member is not a journal member. + */ + long total_wait = max(bch2_dev_latency_max(c, &c->devs_online, WRITE) * 2, HZ * 10); int ret; if (trans_wait_event_timeout(trans, &j->async_wait, @@ -973,7 +969,8 @@ int bch2_journal_res_get_slowpath(struct journal *j, struct journal_res *res, return ret; CLASS(printbuf, buf)(); - prt_printf(&buf, bch2_fmt(c, "Journal stuck? Waited for 10 seconds, err %s"), bch2_err_str(ret)); + prt_printf(&buf, bch2_fmt(c, "Journal stuck? Waited for %lis, err %s"), + total_wait / HZ, bch2_err_str(ret)); bch2_journal_debug_to_text(&buf, j); bch2_print_str(c, KERN_ERR, buf.buf); @@ -1210,8 +1207,12 @@ int bch2_journal_flush_seq(struct journal *j, u64 seq, unsigned task_state) * Don't report stuck until we've waited longer than an IO could * legitimately take: twice the longest write latency we've seen, or 10s, * whichever is greater (matches bch2_journal_res_get_slowpath()). + * + * Over every online device: a flushing commit waits on a preflush to + * every rw member, so the slowest member bounds this even when it holds + * no journal. */ - long total_wait = max(max_dev_latency(c) * 2, HZ * 10); + long total_wait = max(bch2_dev_latency_max(c, &c->devs_online, WRITE) * 2, HZ * 10); if (closure_sync_timeout(&cl, total_wait)) { CLASS(printbuf, buf)(); diff --git a/fs/journal/read.c b/fs/journal/read.c index deb46243d3..5f83751483 100644 --- a/fs/journal/read.c +++ b/fs/journal/read.c @@ -23,7 +23,7 @@ void bch2_journal_pos_from_member_info_set(struct bch_fs *c) { - lockdep_assert_held(&c->sb_lock); + lockdep_assert_held(&c->sb_lock.lock); for_each_member_device(c, ca) { struct bch_member *m = bch2_members_v2_get_mut(c->disk_sb.sb, ca->dev_idx); @@ -35,8 +35,7 @@ void bch2_journal_pos_from_member_info_set(struct bch_fs *c) void bch2_journal_pos_from_member_info_resume(struct bch_fs *c) { - guard(memalloc_flags)(PF_MEMALLOC_NOFS); - guard(mutex)(&c->sb_lock); + guard(mutex_noio)(&c->sb_lock); for_each_member_device(c, ca) { struct bch_member m = bch2_sb_member_get(c->disk_sb.sb, ca->dev_idx); diff --git a/fs/journal/reclaim.c b/fs/journal/reclaim.c index bd0059836e..2bb6a1ef3b 100644 --- a/fs/journal/reclaim.c +++ b/fs/journal/reclaim.c @@ -3,6 +3,7 @@ #include "bcachefs.h" #include "alloc/buckets.h" +#include "alloc/foreground.h" #include "alloc/replicas.h" #include "btree/key_cache.h" @@ -77,18 +78,31 @@ void bch2_journal_set_watermark(struct journal *j) j->space[journal_space_total].total; bool low_on_pin = fifo_free(&j->pin) < j->pin.size / 4; bool low_on_wb = bch2_btree_write_buffer_must_wait(c); + /* + * Open buckets are a fixed pool that btree nodes hold until their update's + * journal commit lands; the reclaim path (write-buffer flush -> journal -> + * writeback) both frees them and, to make progress, allocates them. If new + * journal-reserving work (fsck repair) drains the pool, that reclaim path + * can't get the buckets it needs to advance the journal and everything + * wedges. Throttle new work early, keeping headroom above the reclaim + * reserve - the reclaim path itself is exempt (no_journal_res). + */ + bool low_on_open_buckets = + c->allocator.open_buckets_nr_free < bch2_open_buckets_journal_reserved(); - unsigned watermark = low_on_space || low_on_pin || low_on_wb + unsigned watermark = low_on_space || low_on_pin || low_on_wb || low_on_open_buckets ? BCH_WATERMARK_reclaim : BCH_WATERMARK_stripe; if (track_event_change(&c->times[BCH_TIME_blocked_journal_low_on_space], low_on_space) | track_event_change(&c->times[BCH_TIME_blocked_journal_low_on_pin], low_on_pin) | + track_event_change(&c->times[BCH_TIME_blocked_journal_low_on_open_buckets], low_on_open_buckets) | track_event_change(&c->times[BCH_TIME_blocked_write_buffer_full], low_on_wb)) event_inc_trace(c, journal_full, buf, ({ guard(printbuf_atomic)(&buf); prt_printf(&buf, "low_on_space %u\n", low_on_space); prt_printf(&buf, "low_on_pin %u\n", low_on_pin); + prt_printf(&buf, "low_on_open_buckets %u\n", low_on_open_buckets); prt_printf(&buf, "low_on_wb %u\n", low_on_wb); if (low_on_wb) bch2_btree_write_buffer_to_text(&buf, c); @@ -99,6 +113,7 @@ void bch2_journal_set_watermark(struct journal *j) mod_bit(JOURNAL_low_on_space, &j->flags, low_on_space); mod_bit(JOURNAL_low_on_pin, &j->flags, low_on_pin); mod_bit(JOURNAL_low_on_wb, &j->flags, low_on_wb); + mod_bit(JOURNAL_low_on_open_buckets, &j->flags, low_on_open_buckets); swap(watermark, j->watermark); if (watermark > j->watermark) @@ -383,7 +398,7 @@ static void bch2_journal_dev_do_discards(struct journal_device *ja) blkdev_issue_discard(ca->disk_sb.bdev, bucket_to_sector(ca, ja->buckets[ja->discard_idx]), - ca->mi.bucket_size, GFP_NOFS); + ca->mi.bucket_size, GFP_NOIO); scoped_guard(spinlock, &j->lock) { ja->discard_idx = (ja->discard_idx + 1) % ja->nr; @@ -639,8 +654,16 @@ void bch2_journal_pin_copy(struct journal *j, spin_lock_nested(&dst_l->lock, 1); } + /* + * Keep-oldest, like bch2_journal_pin_add(): a dst already + * pinning an older seq must not be moved forward, or we + * release an obligation - the callers (interior update pin + * transfers: reparent, will_free_node) copy several pins into + * one and need the min. A pin at an older seq covers src_seq. + */ + bool keep = dst_seq && dst_seq <= src_seq; bool reclaim = false, race = src_seq != src->seq || dst_seq != dst->seq; - if (!race) + if (!race && !keep) reclaim = bch2_journal_pin_set_locked(j, dst_l, src_l, dst, src_seq, flush_fn); if (dst_l && dst_l != src_l) @@ -652,7 +675,7 @@ void bch2_journal_pin_copy(struct journal *j, * If the journal is currently full, we might want to call flush_fn * immediately: */ - if (src_seq == j->last_seq) + if (!keep && src_seq == j->last_seq) journal_wake(j); if (reclaim) bch2_journal_maybe_update_last_seq(j); @@ -935,7 +958,7 @@ static int __bch2_journal_reclaim(struct journal *j, bool direct, bool kicked) * we're holding the reclaim lock: */ lockdep_assert_held(&j->reclaim_lock); - guard(memalloc_flags)(PF_MEMALLOC_NOFS); + guard(memalloc_flags)(PF_MEMALLOC_NOIO); do { if (kthread && kthread_should_stop()) @@ -1402,6 +1425,7 @@ __cold void bch2_journal_reclaim_to_text(struct printbuf *out, struct journal *j prt_printf(out, "Blocked time stats:\tcount\tavg\tmax\n"); bch2_time_stats_summary_to_text(out, " low_on_space", &c->times[BCH_TIME_blocked_journal_low_on_space]); bch2_time_stats_summary_to_text(out, " low_on_pin", &c->times[BCH_TIME_blocked_journal_low_on_pin]); + bch2_time_stats_summary_to_text(out, " low_on_open_buckets", &c->times[BCH_TIME_blocked_journal_low_on_open_buckets]); bch2_time_stats_summary_to_text(out, " max_in_flight", &c->times[BCH_TIME_blocked_journal_max_in_flight]); bch2_time_stats_summary_to_text(out, " max_open", &c->times[BCH_TIME_blocked_journal_max_open]); bch2_time_stats_summary_to_text(out, " write_buffer_full", &c->times[BCH_TIME_blocked_write_buffer_full]); diff --git a/fs/journal/sb.c b/fs/journal/sb.c index c9350312de..6a2ac0aea3 100644 --- a/fs/journal/sb.c +++ b/fs/journal/sb.c @@ -178,7 +178,7 @@ int bch2_journal_buckets_to_sb(struct bch_fs *c, struct bch_dev *ca, { unsigned dst = 0, nr_compacted = 1; - lockdep_assert_held(&c->sb_lock); + lockdep_assert_held(&c->sb_lock.lock); if (!nr) { bch2_sb_field_delete(&ca->disk_sb, BCH_SB_FIELD_journal); @@ -229,8 +229,7 @@ int bch2_sb_journal_sort(struct bch_fs *c) BUG_ON(!c->sb.clean); BUG_ON(test_bit(BCH_FS_rw, &c->flags)); - guard(memalloc_flags)(PF_MEMALLOC_NOFS); - guard(mutex)(&c->sb_lock); + guard(mutex_noio)(&c->sb_lock); bool write_sb = false; for_each_online_member(c, ca, BCH_DEV_READ_REF_sb_journal_sort) { diff --git a/fs/journal/seq_blacklist.c b/fs/journal/seq_blacklist.c index aae57a5c8b..d14642e514 100644 --- a/fs/journal/seq_blacklist.c +++ b/fs/journal/seq_blacklist.c @@ -51,8 +51,7 @@ int bch2_journal_seq_blacklist_add(struct bch_fs *c, u64 start, u64 end) struct bch_sb_field_journal_seq_blacklist *bl; unsigned i = 0, nr; - guard(memalloc_flags)(PF_MEMALLOC_NOFS); - guard(mutex)(&c->sb_lock); + guard(mutex_noio)(&c->sb_lock); bl = bch2_sb_field_get(c->disk_sb.sb, journal_seq_blacklist); nr = blacklist_nr_entries(bl); diff --git a/fs/journal/types.h b/fs/journal/types.h index e7fd3ab329..45caaa665e 100644 --- a/fs/journal/types.h +++ b/fs/journal/types.h @@ -221,7 +221,8 @@ enum journal_space_from { x(med_on_space) \ x(low_on_space) \ x(low_on_pin) \ - x(low_on_wb) + x(low_on_wb) \ + x(low_on_open_buckets) enum journal_flags { #define x(n) JOURNAL_##n, @@ -284,7 +285,7 @@ struct journal { * reservation: for synchronization between the btree write buffer code * and the journal write path: */ - struct mutex buf_lock; + struct mutex_noio buf_lock; /* * Ring of slots indexed by seq & JOURNAL_STATE_BUF_MASK; only used by * the reservation fastpath. Updated in journal_entry_open() when a new @@ -380,6 +381,11 @@ struct journal { u64 replay_journal_seq_end; struct write_point wp; + /* + * Failure domain keys scratch for journal_write_alloc() - like + * wp.stripe, protected by journal writes being allocated in order: + */ + u64 wp_domain_keys[BCH_SB_MEMBERS_MAX]; spinlock_t err_lock; struct mutex reclaim_lock; diff --git a/fs/journal/write.c b/fs/journal/write.c index 6edae50c59..0e0d913318 100644 --- a/fs/journal/write.c +++ b/fs/journal/write.c @@ -23,18 +23,28 @@ #include "sb/clean.h" #include "sb/counters.h" +#include "sb/members.h" #include +static unsigned journal_alloc_target(struct bch_fs *c) +{ + unsigned target = c->opts.metadata_target ?: c->opts.foreground_target; + return target && bch2_target_has_non_shrinking_dev(c, BCH_DATA_journal, target) + ? target + : 0; +} + static void journal_advance_devs_to_next_bucket(struct journal *j, - struct dev_alloc_list *devs, + struct bch_devs_mask *devs, unsigned sectors, __le64 seq) { struct bch_fs *c = container_of(j, struct bch_fs, journal); + unsigned i; guard(rcu)(); - darray_for_each(*devs, i) { - struct bch_dev *ca = rcu_dereference(c->devs[*i]); + for_each_set_bit(i, devs->d, BCH_SB_MEMBERS_MAX) { + struct bch_dev *ca = rcu_dereference(c->devs[i]); if (!ca) continue; @@ -58,32 +68,57 @@ static void journal_advance_devs_to_next_bucket(struct journal *j, static void __journal_write_alloc(struct journal *j, struct journal_buf *w, - struct dev_alloc_list *devs, + struct bch_devs_mask *devs, unsigned sectors, unsigned *replicas, unsigned replicas_want) { struct bch_fs *c = container_of(j, struct bch_fs, journal); - darray_for_each(*devs, i) { - struct bch_dev *ca = bch2_dev_get_ioref(c, *i, WRITE, - BCH_DEV_WRITE_REF_journal_write); - if (!ca) - continue; - - struct journal_device *ja = &ca->journal; - + while (*replicas < replicas_want) { /* - * Check that we can use this device, and aren't already using - * it: + * Journal replicas spread across failure domains, like data: + * one pick per sort, since each pick changes the occupancy + * the next should avoid: */ - if (!ja->nr || - bch2_bkey_has_device_c(c, bkey_i_to_s_c(&w->key), ca->dev_idx) || - sectors > ja->sectors_free) { - enumerated_ref_put(&ca->io_ref[WRITE], BCH_DEV_WRITE_REF_journal_write); - continue; + struct bch_devs_mask chosen = {}; + bkey_for_each_ptr(bch2_bkey_ptrs_c(bkey_i_to_s_c(&w->key)), ptr) + __set_bit(ptr->dev, chosen.d); + + struct dev_alloc_list devs_sorted; + bch2_dev_alloc_list_devs(c, &j->wp.stripe, devs, + &chosen, j->wp_domain_keys, &devs_sorted); + + struct bch_dev *ca = NULL; + darray_for_each(devs_sorted, i) { + ca = bch2_dev_get_ioref(c, *i, WRITE, + BCH_DEV_WRITE_REF_journal_write); + if (!ca) + continue; + + struct journal_device *ja = &ca->journal; + + /* + * Check that we can use this device, and aren't + * already using it: + */ + if (!ja->nr || + bch2_bkey_has_device_c(c, bkey_i_to_s_c(&w->key), ca->dev_idx) || + sectors > ja->sectors_free) { + enumerated_ref_put(&ca->io_ref[WRITE], + BCH_DEV_WRITE_REF_journal_write); + ca = NULL; + continue; + } + + break; } + if (!ca) + return; + + struct journal_device *ja = &ca->journal; + bch2_dev_stripe_increment(ca, &j->wp.stripe); bch2_bkey_append_ptr(c, &w->key, @@ -103,9 +138,6 @@ static void __journal_write_alloc(struct journal *j, ja->bucket_seq[ja->cur_idx] = le64_to_cpu(w->data->seq); *replicas += ca->mi.durability; - - if (*replicas >= replicas_want) - break; } } @@ -114,24 +146,21 @@ static int journal_write_alloc(struct journal *j, struct journal_buf *w, { struct bch_fs *c = container_of(j, struct bch_fs, journal); struct bch_devs_mask devs; - struct dev_alloc_list devs_sorted; unsigned sectors = vstruct_sectors(w->data, c->block_bits); - unsigned target = c->opts.metadata_target ?: - c->opts.foreground_target; + unsigned target = journal_alloc_target(c); unsigned replicas_want = READ_ONCE(c->opts.metadata_replicas); bool advance_done = false; retry_target: devs = target_rw_devs(c, BCH_DATA_journal, target); - bch2_dev_alloc_list(c, &j->wp.stripe, &devs, &devs_sorted); retry_alloc: - __journal_write_alloc(j, w, &devs_sorted, sectors, replicas, replicas_want); + __journal_write_alloc(j, w, &devs, sectors, replicas, replicas_want); if (likely(*replicas >= replicas_want)) goto done; if (!advance_done) { - journal_advance_devs_to_next_bucket(j, &devs_sorted, sectors, w->data->seq); + journal_advance_devs_to_next_bucket(j, &devs, sectors, w->data->seq); advance_done = true; goto retry_alloc; } @@ -174,7 +203,7 @@ static void journal_buf_realloc(struct journal *j, struct journal_buf *buf) if (bch2_btree_write_buffer_resize(c, btree_write_buffer_size)) return; - new_buf = kvmalloc(new_size, GFP_NOFS|__GFP_NOWARN); + new_buf = kvmalloc(new_size, GFP_NOIO|__GFP_NOWARN); if (!new_buf) return; @@ -253,79 +282,86 @@ static CLOSURE_CALLBACK(journal_write_done) * Lock ordering: buf_lock, pin_resize_lock, then j->lock - same as the * flusher and the journal write path. */ - mutex_lock(&j->buf_lock); /* - * pin_resize_lock held across the journal pin FIFO updates below; it - * keeps the pin_list stable while we rebuild temp replicas entries from - * the compact device list for refcount updates. + * kvfree can sleep, so it can't run under j->lock (or any lock here): + * function scope defers the cleanup until return, after every lock is + * dropped. Declared inside the scoped_guard below, it would run at the + * block's closing brace - where j->lock, taken inside the block, is + * still held for the completion loop that follows: */ - percpu_down_read(&j->pin_resize_lock); - struct journal_entry_pin_list *pin = journal_seq_pin(j, seq_wrote); - - if (unlikely(w->failed.nr)) { - union bch_replicas_padded r; - journal_pin_devs_to_replicas(&r, pin); - bch2_replicas_entry_put(c, &r.e); - pin->devs.nr = 0; - } - - if (!pin->devs.nr && !w->empty) { - union bch_replicas_padded r; - bch2_devlist_to_replicas(&r.e, BCH_DATA_journal, w->devs_written); - err = bch2_replicas_entry_get(c, &r.e); - if (!err) - journal_pin_set_devs(pin, &w->devs_written); - } - - if (unlikely(w->failed.nr || err)) { - CLASS(bch_log_msg, msg)(c); + void *buf_to_free __free(kvfree) = NULL; - /* Separate ratelimit_states for hard and soft errors */ - msg.m.suppress = !err - ? bch2_ratelimit(c) - : bch2_ratelimit(c); + CLASS(darray_replicas_entry_refs, replicas_refs)(); + scoped_guard(mutex_noio, &j->buf_lock) { + /* + * pin_resize_lock held across the journal pin FIFO updates below; it + * keeps the pin_list stable while we rebuild temp replicas entries from + * the compact device list for refcount updates. + */ + percpu_down_read(&j->pin_resize_lock); + struct journal_entry_pin_list *pin = journal_seq_pin(j, seq_wrote); - prt_printf(&msg.m, "error writing journal entry %llu\n", seq_wrote); - bch2_io_failures_to_text(&msg.m, c, &w->failed); + if (unlikely(w->failed.nr)) { + union bch_replicas_padded r; + journal_pin_devs_to_replicas(&r, pin); + bch2_replicas_entry_put(c, &r.e); + pin->devs.nr = 0; + } - if (!w->devs_written.nr) - err = bch_err_throw(c, journal_write_err); + if (!pin->devs.nr && !w->empty) { + union bch_replicas_padded r; + bch2_devlist_to_replicas(&r.e, BCH_DATA_journal, w->devs_written); + err = bch2_replicas_entry_get(c, &r.e); + if (!err) + journal_pin_set_devs(pin, &w->devs_written); + } - if (!err) { - prt_printf(&msg.m, "wrote degraded to "); - bch2_devs_list_to_text(&msg.m, c, &w->devs_written); - prt_newline(&msg.m); - } else { - prt_printf(&msg.m, "error %s\n", bch2_err_str(err)); - percpu_up_read(&j->pin_resize_lock); - bch2_fs_emergency_read_only(c, &msg.m); - percpu_down_read(&j->pin_resize_lock); + if (unlikely(w->failed.nr || err)) { + CLASS(bch_log_msg, msg)(c); + + /* Separate ratelimit_states for hard and soft errors */ + msg.m.suppress = !err + ? bch2_ratelimit(c) + : bch2_ratelimit(c); + + prt_printf(&msg.m, "error writing journal entry %llu\n", seq_wrote); + bch2_io_failures_to_text(&msg.m, c, &w->failed); + + if (!w->devs_written.nr) + err = bch_err_throw(c, journal_write_err); + + if (!err) { + prt_printf(&msg.m, "wrote degraded to "); + bch2_devs_list_to_text(&msg.m, c, &w->devs_written); + prt_newline(&msg.m); + } else { + prt_printf(&msg.m, "error %s\n", bch2_err_str(err)); + percpu_up_read(&j->pin_resize_lock); + bch2_fs_emergency_read_only(c, &msg.m); + percpu_down_read(&j->pin_resize_lock); + } } - } - closure_debug_destroy(cl); + closure_debug_destroy(cl); - CLASS(darray_replicas_entry_refs, replicas_refs)(); + spin_lock(&j->lock); + BUG_ON(seq_wrote < j->pin.front); + if (err && (!j->err_seq || seq_wrote < j->err_seq)) + j->err_seq = seq_wrote; - spin_lock(&j->lock); - BUG_ON(seq_wrote < j->pin.front); - if (err && (!j->err_seq || seq_wrote < j->err_seq)) - j->err_seq = seq_wrote; + j->flushes_outstanding -= w->flush; - j->flushes_outstanding -= w->flush; + if (!j->free_buf || j->free_buf_size < w->buf_size) { + swap(j->free_buf, w->data); + swap(j->free_buf_size, w->buf_size); + } - if (!j->free_buf || j->free_buf_size < w->buf_size) { - swap(j->free_buf, w->data); - swap(j->free_buf_size, w->buf_size); + buf_to_free = w->data; + w->data = NULL; + w->buf_size = 0; } - /* kvfree can allocate memory, and can't be called under j->lock */ - void *buf_to_free __free(kvfree) = w->data; - w->data = NULL; - w->buf_size = 0; - mutex_unlock(&j->buf_lock); - bool completed = false; bool last_seq_ondisk_updated = false; @@ -557,7 +593,7 @@ static CLOSURE_CALLBACK(journal_write_submit) */ struct bio *bio = bch2_bio_map_and_chain(ca->disk_sb.bdev, w->data, sectors << 9, ptr->offset, - opf, GFP_NOFS, &ja->bio_set); + opf, GFP_NOIO, &ja->bio_set); struct journal_bio *jbio = container_of(bio, struct journal_bio, bio); @@ -597,7 +633,7 @@ static CLOSURE_CALLBACK(journal_write_preflush) struct bio *bio = bio_alloc_bioset(ca->disk_sb.bdev, 0, REQ_OP_WRITE|REQ_SYNC|REQ_IDLE| REQ_META|REQ_PREFLUSH, - GFP_NOFS, &ja->bio_set); + GFP_NOIO, &ja->bio_set); struct journal_bio *jbio = container_of(bio, struct journal_bio, bio); jbio->ca = ca; @@ -789,11 +825,11 @@ CLOSURE_CALLBACK(bch2_journal_write) BUG_ON(w->write_allocated); BUG_ON(w->write_done); - guard(memalloc_flags)(PF_MEMALLOC_NOFS); + guard(memalloc_flags)(PF_MEMALLOC_NOIO); j->write_start_time = local_clock(); - scoped_guard(mutex, &j->buf_lock) { + scoped_guard(mutex_noio, &j->buf_lock) { journal_buf_realloc(j, w); ret = bch2_journal_write_prep(j, w); diff --git a/fs/mod.rs b/fs/mod.rs index d14afe24d1..a55695d2db 100644 --- a/fs/mod.rs +++ b/fs/mod.rs @@ -44,6 +44,13 @@ pub mod sb; pub mod snapshot_states { include!(concat!(env!("OUT_DIR"), "/snapshot_states_gen.rs")); } +/// Typed ioctl inventory, generated from the _IO*() defines in +/// bcachefs_ioctl.h: a marker type per ioctl binding its opcode to its +/// argument type. The tools' src/wrappers/ioctl.rs builds the calls on top. +pub mod ioctl { + #![allow(non_camel_case_types)] + include!(concat!(env!("OUT_DIR"), "/ioctls_gen.rs")); +} #[path = "fs/str_hash.rs"] pub mod str_hash; pub mod typeinfo; pub mod util; @@ -302,3 +309,61 @@ impl From for u32 { t.0 } } + +// ── ARM32 Kernel EABI Division Helpers ────────────────────────── +// +// On 32-bit ARM, raw 64-bit integer division lowers to compiler-rt calls. +// Since the Linux kernel does not export these symbols to out-of-tree modules, +// we declare them globally using assembly stubs that call the kernel's real +// exported math functions. We restrict this to non-std (kernel) ARM32 builds. + +#[cfg(all(target_arch = "arm", not(feature = "std")))] +core::arch::global_asm!( + ".global __aeabi_uldivmod", + ".type __aeabi_uldivmod, %function", + "__aeabi_uldivmod:", + " .fnstart", + // Push r8 specifically to push exactly 6 registers (24 bytes) total, + // maintaining the AAPCS required 8-byte stack alignment for the C call. + " push {{r4, r5, r6, r7, r8, lr}}", + " .save {{r4, r5, r6, r7, r8, lr}}", + " mov r4, r0", + " mov r5, r1", + " mov r6, r2", + " mov r7, r3", + " bl div64_u64", + " umull r2, r3, r0, r6", + " mla r3, r0, r7, r3", + " mla r3, r1, r6, r3", + " subs r2, r4, r2", + " sbc r3, r5, r3", + " pop {{r4, r5, r6, r7, r8, pc}}", + " .fnend", + ".size __aeabi_uldivmod, . - __aeabi_uldivmod" +); + + +#[cfg(all(target_arch = "arm", not(feature = "std")))] +core::arch::global_asm!( + ".global __aeabi_ldivmod", + ".type __aeabi_ldivmod, %function", + "__aeabi_ldivmod:", + " .fnstart", + // Push r8 specifically to push exactly 6 registers (24 bytes) total, + // maintaining the AAPCS required 8-byte stack alignment for the C call. + " push {{r4, r5, r6, r7, r8, lr}}", + " .save {{r4, r5, r6, r7, r8, lr}}", + " mov r4, r0", + " mov r5, r1", + " mov r6, r2", + " mov r7, r3", + " bl div64_s64", + " umull r2, r3, r0, r6", + " mla r3, r0, r7, r3", + " mla r3, r1, r6, r3", + " subs r2, r4, r2", + " sbc r3, r5, r3", + " pop {{r4, r5, r6, r7, r8, pc}}", + " .fnend", + ".size __aeabi_ldivmod, . - __aeabi_ldivmod" +); \ No newline at end of file diff --git a/fs/opts.c b/fs/opts.c index 71adf44446..506d3caf6c 100644 --- a/fs/opts.c +++ b/fs/opts.c @@ -295,6 +295,9 @@ const struct bch_option bch2_opt_table[] = { .choices = _choices, \ .choices_allowed_mask = _choices_allowed_mask #define OPT_FN(_fn) .type = BCH_OPT_FN, .fn = _fn +#define OPT_STR_MEMBER(_field) .type = BCH_OPT_STR_MEMBER, \ + .member_offset = offsetof(struct bch_member, _field),\ + .member_size = sizeof(((struct bch_member *) NULL)->_field) #define x(_name, _bits, _flags, _type, _sb_opt, _default, _hint, _help) \ [Opt_##_name] = { \ @@ -481,6 +484,20 @@ int bch2_opt_parse(struct bch_fs *c, *res = v; break; } + case BCH_OPT_STR_MEMBER: + if (!val) { + prt_printf(err, "%s: required value", opt->attr.name); + return -BCH_ERR_EINVAL_opt_parse_str_required; + } + if (strlen(val) > opt->member_size) { + if (err) + prt_printf(err, "%s: too long (max %u bytes)", + opt->attr.name, opt->member_size); + return -ENAMETOOLONG; + } + /* Applied to the member directly in __bch2_opt_set_sb(): */ + *res = 0; + break; case BCH_OPT_FN: ret = opt->fn.parse(c, val, res, err); @@ -536,6 +553,9 @@ __cold void bch2_opt_to_text(struct printbuf *out, case BCH_OPT_FN: opt->fn.to_text(out, c, sb, v); break; + case BCH_OPT_STR_MEMBER: + /* Rendered per-device from the member (see bch2_member_to_text) */ + break; default: BUG(); } @@ -628,18 +648,24 @@ static int opt_hook_io(struct bch_fs *c, struct bch_dev *ca, u64 inum, enum bch_ (struct reconcile_scan) { .type = RECONCILE_SCAN_stripes }, post, scope)); break; case Opt_label: + case Opt_failure_domain: /* * Refresh the cpu label tree before the scan wakes: reconcile * reads the group devs masks. Errors here (ENOMEM) just leave * the cpu copy stale until the next superblock swap: */ if (post) { - scoped_guard(mutex, &c->sb_lock) + scoped_guard(mutex_noio, &c->sb_lock) bch_err_fn(c, bch2_sb_disk_groups_to_cpu(c)); } - try(reconcile_scan_bracket(c, - (struct reconcile_scan) { .type = RECONCILE_SCAN_pending }, post, scope)); + /* + * Only the label affects targeting - a failure domain change + * only affects the spreading of future allocations, no rescan: + */ + if (id == Opt_label) + try(reconcile_scan_bracket(c, + (struct reconcile_scan) { .type = RECONCILE_SCAN_pending }, post, scope)); break; default: break; @@ -714,8 +740,7 @@ void bch2_opt_hook_post_set(struct bch_fs *c, struct bch_dev *ca, u64 inum, break; case Opt_discard: if (!ca) { - guard(memalloc_flags)(PF_MEMALLOC_NOFS); - guard(mutex)(&c->sb_lock); + guard(mutex_noio)(&c->sb_lock); for_each_member_device(c, ca) { struct bch_member *m = bch2_members_v2_get_mut(ca->disk_sb.sb, ca->dev_idx); @@ -919,7 +944,7 @@ int bch2_opts_from_sb(struct bch_opts *opts, struct bch_sb *sb) } bool __bch2_opt_set_sb(struct bch_sb *sb, int dev_idx, - const struct bch_option *opt, u64 v) + const struct bch_option *opt, u64 v, const char *val) { bool changed = false; @@ -954,15 +979,33 @@ bool __bch2_opt_set_sb(struct bch_sb *sb, int dev_idx, opt->set_member(m, v); } + if (opt->type == BCH_OPT_STR_MEMBER && + (opt->flags & OPT_DEVICE) && dev_idx >= 0) { + if (WARN(!bch2_member_exists(sb, dev_idx), + "tried to set device option %s on nonexistent device %i", + opt->attr.name, dev_idx)) + return false; + + struct bch_member *m = bch2_members_v2_get_mut(sb, dev_idx); + char *field = (char *) m + opt->member_offset; + size_t len = val ? strlen(val) : 0; + + /* zero-padded, so equal strings compare equal in the interning: */ + for (unsigned i = 0; i < opt->member_size; i++) { + char want = i < len ? val[i] : 0; + changed |= field[i] != want; + field[i] = want; + } + } + return changed; } bool bch2_opt_set_sb(struct bch_fs *c, struct bch_dev *ca, - const struct bch_option *opt, u64 v) + const struct bch_option *opt, u64 v, const char *val) { - guard(memalloc_flags)(PF_MEMALLOC_NOFS); - guard(mutex)(&c->sb_lock); - bool changed = __bch2_opt_set_sb(c->disk_sb.sb, ca ? ca->dev_idx : -1, opt, v); + guard(mutex_noio)(&c->sb_lock); + bool changed = __bch2_opt_set_sb(c->disk_sb.sb, ca ? ca->dev_idx : -1, opt, v, val); if (changed) bch2_write_super(c); return changed; diff --git a/fs/opts.h b/fs/opts.h index 4e81449a40..4f4a98c28c 100644 --- a/fs/opts.h +++ b/fs/opts.h @@ -81,6 +81,8 @@ enum opt_type { BCH_OPT_STR, BCH_OPT_BITFIELD, BCH_OPT_FN, + /* A free-form string stored directly in a bch_member char[] field: */ + BCH_OPT_STR_MEMBER, }; struct bch_opt_fn { @@ -384,7 +386,7 @@ enum fsck_err_opts { BCH2_NO_SB_OPT, FSCK_FIX_exit, \ NULL, "Fix errors during fsck without asking") \ x(ratelimit_errors, u8, \ - OPT_FS|OPT_MOUNT, \ + OPT_FS|OPT_MOUNT|OPT_RUNTIME, \ OPT_BOOL(), \ BCH2_NO_SB_OPT, RATELIMIT_ERRORS_DEFAULT, \ NULL, "Ratelimit error messages during fsck") \ @@ -442,6 +444,13 @@ enum fsck_err_opts { OPT_STR_NOLIMIT(bch2_recovery_passes), \ BCH2_NO_SB_OPT, 0, \ NULL, "Exit recovery after specified pass") \ + x(recovery_passes_skip_scheduled, u8, \ + OPT_FS|OPT_MOUNT, \ + OPT_BOOL(), \ + BCH2_NO_SB_OPT, false, \ + NULL, "Don't run repair passes, whether the superblock had "\ + "them scheduled or something schedules them mid-mount; "\ + "they stay scheduled for the next mount") \ x(retain_recovery_info, u8, \ 0, \ OPT_BOOL(), \ @@ -565,6 +574,14 @@ enum fsck_err_opts { OPT_FN(bch2_opt_disk_label), \ BCH_MEMBER_GROUP, 0, \ "(label)", "Device label: position in the label tree") \ + x(failure_domain, u8, \ + OPT_DEVICE|OPT_FORMAT|OPT_RUNTIME, \ + OPT_STR_MEMBER(failure_domain), \ + BCH2_NO_SB_OPT, 0, \ + "(domain)", "Failure domain: devices sharing a name are in the\n"\ + "same failure domain; allocation spreads replicas\n"\ + "across domains (a hard requirement for erasure\n"\ + "coded stripe blocks)") \ x(bucket_size, u32, \ OPT_DEVICE|OPT_HUMAN_READABLE|OPT_SB_FIELD_SECTORS, \ OPT_UINT(0, S64_MAX), \ @@ -694,6 +711,9 @@ struct bch_option { u64 (*get_ext)(const struct bch_sb_field_ext *); void (*set_ext)(struct bch_sb_field_ext *, u64); + /* BCH_OPT_STR_MEMBER: the bch_member char[] field the string lives in */ + unsigned member_offset; + unsigned member_size; }; extern const struct bch_option bch2_opt_table[]; @@ -704,10 +724,10 @@ void bch2_opt_set_by_id(struct bch_opts *, enum bch_opt_id, u64); u64 bch2_opt_from_sb(struct bch_sb *, enum bch_opt_id, int); int bch2_opts_from_sb(struct bch_opts *, struct bch_sb *); -bool __bch2_opt_set_sb(struct bch_sb *, int, const struct bch_option *, u64); +bool __bch2_opt_set_sb(struct bch_sb *, int, const struct bch_option *, u64, const char *); struct bch_dev; -bool bch2_opt_set_sb(struct bch_fs *, struct bch_dev *, const struct bch_option *, u64); +bool bch2_opt_set_sb(struct bch_fs *, struct bch_dev *, const struct bch_option *, u64, const char *); int bch2_opt_lookup(const char *); int bch2_opt_validate(const struct bch_option *, u64, struct printbuf *); diff --git a/fs/opts.rs b/fs/opts.rs index 1f9a3271c3..4361d05b0d 100644 --- a/fs/opts.rs +++ b/fs/opts.rs @@ -1,9 +1,7 @@ use crate::c; +use crate::fs::Fs; use crate::util::printbuf::Printbuf; use core::ffi::CStr; -// Used only by the std-gated mount-option helpers below. -#[cfg(feature = "std")] -use crate::fs::Fs; #[cfg(feature = "std")] use core::ffi::c_char; #[cfg(feature = "std")] @@ -86,7 +84,8 @@ pub fn opts_default() -> &'static c::bch_opts { /// Set a superblock option from the opt table. pub fn opt_set_sb(sb: &mut c::bch_sb, dev_idx: i32, opt: &c::bch_option, v: u64) { - unsafe { c::__bch2_opt_set_sb(sb, dev_idx, opt, v); } + // val is only used by BCH_OPT_STR_MEMBER options, not set through this path: + unsafe { c::__bch2_opt_set_sb(sb, dev_idx, opt, v, core::ptr::null()); } } /// Set an option value in a bch_opts struct by id. @@ -217,3 +216,25 @@ pub fn prt_compression_type(out: &mut Printbuf, t: c::bch_compression_type) { pub fn prt_reconcile_type(out: &mut Printbuf, t: c::bch_reconcile_accounting_type) { unsafe { c::bch2_prt_reconcile_accounting_type(out.as_raw(), t) } } + +/// Look up an option by name. The typed id plus the table entry. +pub fn opt_lookup(name: &core::ffi::CStr) -> Option<(c::bch_opt_id, &'static c::bch_option)> { + let id = unsafe { c::bch2_opt_lookup(name.as_ptr()) }; + if id < 0 || id as usize >= opt_table().len() { + return None; + } + Some((opt_id(id as usize), &opt_table()[id as usize])) +} + +/// Parse an option value string; a filesystem context enables options +/// that need one. Err is the negative bch_errcode from the parser. +pub fn opt_parse(fs: Option<&Fs>, opt: &c::bch_option, val: &core::ffi::CStr, + err: Option<&mut Printbuf>) -> Result { + let mut v = 0u64; + let ret = unsafe { + c::bch2_opt_parse(fs.map_or(core::ptr::null_mut(), |f| f.raw), + opt, val.as_ptr(), &mut v, + err.map_or(core::ptr::null_mut(), |e| e.as_raw())) + }; + if ret < 0 { Err(ret) } else { Ok(v) } +} diff --git a/fs/sb/clean.c b/fs/sb/clean.c index 41effd239c..1a9a83a797 100644 --- a/fs/sb/clean.c +++ b/fs/sb/clean.c @@ -150,8 +150,7 @@ struct bch_sb_field_clean *bch2_read_superblock_clean(struct bch_fs *c) struct bch_sb_field_clean *clean, *sb_clean; int ret; - guard(memalloc_flags)(PF_MEMALLOC_NOFS); - guard(mutex)(&c->sb_lock); + guard(mutex_noio)(&c->sb_lock); sb_clean = bch2_sb_field_get(c->disk_sb.sb, clean); if (fsck_err_on(!sb_clean, c, diff --git a/fs/sb/downgrade.c b/fs/sb/downgrade.c index 9940a5827b..26136b8546 100644 --- a/fs/sb/downgrade.c +++ b/fs/sb/downgrade.c @@ -126,6 +126,7 @@ BCH_FSCK_ERR_need_discard_key_wrong, \ BCH_FSCK_ERR_need_discard_freespace_key_to_invalid_dev_bucket)\ x(per_dev_fragmentation_lru, \ + BIT_ULL(BCH_RECOVERY_PASS_check_allocations)| \ BIT_ULL(BCH_RECOVERY_PASS_check_lrus)| \ BIT_ULL(BCH_RECOVERY_PASS_check_alloc_to_lru_refs)| \ BIT_ULL(BCH_RECOVERY_PASS_check_inodes)| \ @@ -133,6 +134,7 @@ BIT_ULL(BCH_RECOVERY_PASS_check_snapshots)| \ BIT_ULL(BCH_RECOVERY_PASS_check_subvols)| \ BIT_ULL(BCH_RECOVERY_PASS_delete_dead_snapshots), \ + BCH_FSCK_ERR_accounting_mismatch, \ BCH_FSCK_ERR_lru_entry_bad, \ BCH_FSCK_ERR_alloc_key_to_missing_lru_entry, \ BCH_FSCK_ERR_inode_has_inode_opts_flag_wrong, \ @@ -206,10 +208,12 @@ BCH_FSCK_ERR_need_discard_key_wrong, \ BCH_FSCK_ERR_need_discard_freespace_key_to_invalid_dev_bucket)\ x(per_dev_fragmentation_lru, \ + BIT_ULL(BCH_RECOVERY_PASS_check_allocations)| \ BIT_ULL(BCH_RECOVERY_PASS_check_lrus)| \ BIT_ULL(BCH_RECOVERY_PASS_check_alloc_to_lru_refs), \ BCH_FSCK_ERR_lru_entry_bad, \ - BCH_FSCK_ERR_alloc_key_to_missing_lru_entry) \ + BCH_FSCK_ERR_alloc_key_to_missing_lru_entry, \ + BCH_FSCK_ERR_accounting_mismatch) \ x(snapshot_nr_keys, \ BIT_ULL(BCH_RECOVERY_PASS_check_allocations), \ BCH_FSCK_ERR_accounting_mismatch) @@ -266,8 +270,7 @@ int bch2_sb_set_upgrade_extra(struct bch_fs *c) bool write_sb = false; int ret = 0; - guard(memalloc_flags)(PF_MEMALLOC_NOFS); - guard(mutex)(&c->sb_lock); + guard(mutex_noio)(&c->sb_lock); struct bch_sb_field_ext *ext = bch2_sb_field_get(c->disk_sb.sb, ext); if (old_version < bcachefs_metadata_version_bucket_stripe_sectors && @@ -291,7 +294,7 @@ static void __bch2_sb_set_upgrade(struct bch_fs *c, const struct upgrade_downgrade_entry *table, size_t nr_entries) { - lockdep_assert_held(&c->sb_lock); + lockdep_assert_held(&c->sb_lock.lock); struct bch_sb_field_ext *ext = bch2_sb_field_get(c->disk_sb.sb, ext); diff --git a/fs/sb/errors.c b/fs/sb/errors.c index 7cab91e3d7..63867927c4 100644 --- a/fs/sb/errors.c +++ b/fs/sb/errors.c @@ -127,6 +127,106 @@ const struct bch_sb_field_ops bch_sb_field_ops_errors = { .to_text = bch2_sb_errors_to_text, }; +/* v2: adds the time of first occurrence */ + +static inline unsigned bch2_sb_field_errors_v2_nr_entries(struct bch_sb_field_errors_v2 *e) +{ + return bch2_sb_field_nr_entries(e); +} + +static inline unsigned bch2_sb_field_errors_v2_u64s(unsigned nr) +{ + return (sizeof(struct bch_sb_field_errors_v2) + + sizeof(struct bch_sb_field_error_entry_v2) * nr) / sizeof(u64); +} + +/* A saturated count is a floor, not an exact value: */ +void bch2_prt_error_nr(struct printbuf *out, u64 nr) +{ + prt_u64(out, nr); + if (nr >= BCH_SB_ERROR_ENTRY_V2_NR_MAX) + prt_char(out, '+'); +} + +static int bch2_sb_errors_v2_validate(struct bch_sb *sb, struct bch_sb_field *f, + enum bch_validate_flags flags, struct printbuf *err) +{ + struct bch_sb_field_errors_v2 *e = field_to_type(f, errors_v2); + unsigned i, nr = bch2_sb_field_errors_v2_nr_entries(e); + + for (i = 0; i < nr; i++) { + if (!BCH_SB_ERROR_ENTRY_V2_NR(&e->entries[i])) { + prt_printf(err, "entry with count 0 (id "); + bch2_sb_error_id_to_text(err, BCH_SB_ERROR_ENTRY_V2_ID(&e->entries[i])); + prt_printf(err, ")"); + return -BCH_ERR_invalid_sb_errors; + } + + if (BCH_SB_ERROR_ENTRY_V2_FIRST(&e->entries[i]) > + BCH_SB_ERROR_ENTRY_V2_LAST(&e->entries[i])) { + prt_printf(err, "entry with first occurrence after last (id "); + bch2_sb_error_id_to_text(err, BCH_SB_ERROR_ENTRY_V2_ID(&e->entries[i])); + prt_printf(err, ")"); + return -BCH_ERR_invalid_sb_errors; + } + + if (i + 1 < nr && + BCH_SB_ERROR_ENTRY_V2_ID(&e->entries[i]) >= + BCH_SB_ERROR_ENTRY_V2_ID(&e->entries[i + 1])) { + prt_printf(err, "entries out of order"); + return -BCH_ERR_invalid_sb_errors; + } + } + + return 0; +} + +static int error_entry_v2_cmp(const void *_l, const void *_r) +{ + const struct bch_sb_field_error_entry_v2 *l = _l; + const struct bch_sb_field_error_entry_v2 *r = _r; + + return -cmp_int(BCH_SB_ERROR_ENTRY_V2_LAST(l), + BCH_SB_ERROR_ENTRY_V2_LAST(r)); +} + +DEFINE_DARRAY(bch_sb_field_error_entry_v2); + +static __cold void bch2_sb_errors_v2_to_text(struct printbuf *out, + struct bch_fs *c, + struct bch_sb *sb, + struct bch_sb_field *f) +{ + struct bch_sb_field_errors_v2 *e = field_to_type(f, errors_v2); + unsigned nr = bch2_sb_field_errors_v2_nr_entries(e); + + if (out->nr_tabstops <= 1) + printbuf_tabstop_push(out, 16); + + CLASS(darray_bch_sb_field_error_entry_v2, sorted)(); + + for (struct bch_sb_field_error_entry_v2 *i = e->entries; i < e->entries + nr; i++) + darray_push(&sorted, *i); + + darray_sort(sorted, error_entry_v2_cmp); + + darray_for_each(sorted, i) { + bch2_sb_error_id_to_text(out, BCH_SB_ERROR_ENTRY_V2_ID(i)); + prt_tab(out); + bch2_prt_error_nr(out, BCH_SB_ERROR_ENTRY_V2_NR(i)); + prt_tab(out); + bch2_prt_datetime(out, BCH_SB_ERROR_ENTRY_V2_FIRST(i)); + prt_tab(out); + bch2_prt_datetime(out, BCH_SB_ERROR_ENTRY_V2_LAST(i)); + prt_newline(out); + } +} + +const struct bch_sb_field_ops bch_sb_field_ops_errors_v2 = { + .validate = bch2_sb_errors_v2_validate, + .to_text = bch2_sb_errors_v2_to_text, +}; + __cold void bch2_fs_errors_to_text(struct printbuf *out, struct bch_fs *c) { if (out->nr_tabstops < 1) @@ -135,6 +235,8 @@ __cold void bch2_fs_errors_to_text(struct printbuf *out, struct bch_fs *c) printbuf_tabstop_push(out, 8); if (out->nr_tabstops < 3) printbuf_tabstop_push(out, 16); + if (out->nr_tabstops < 4) + printbuf_tabstop_push(out, 16); guard(mutex)(&c->errors.counts_lock); @@ -144,19 +246,73 @@ __cold void bch2_fs_errors_to_text(struct printbuf *out, struct bch_fs *c) prt_tab(out); prt_u64(out, i->nr); prt_tab(out); + bch2_prt_datetime(out, i->first_error_time); + prt_tab(out); bch2_prt_datetime(out, i->last_error_time); prt_newline(out); } } +/* @err is a BCH_ERR_BLK_STS_* errcode, as thrown by blk_status_to_bch_err() */ +enum bch_sb_error_id bch2_blk_sts_sb_err(int err) +{ + switch (abs(err)) { +#define x(_blk_sts, _name) \ + case BCH_ERR_BLK_STS_##_blk_sts: \ + return BCH_FSCK_ERR_blk_sts_##_name; + BCH_BLK_STS_SB_ERRS() +#undef x + default: + return BCH_FSCK_ERR_blk_sts_unknown; + } +} + +/* @err is a BCH_ERR_decompress errcode, as thrown by buf_uncompress() */ +enum bch_sb_error_id bch2_decompress_sb_err(int err) +{ + switch (abs(err)) { +#define x(_errcode, _name) \ + case BCH_ERR_##_errcode: \ + return BCH_FSCK_ERR_data_decompress_err_##_name; + BCH_DECOMPRESS_SB_ERRS() +#undef x + default: + return bch2_err_matches(err, BCH_ERR_zstd_error) + ? BCH_FSCK_ERR_data_decompress_err_zstd_unknown + : BCH_FSCK_ERR_data_decompress_err_unknown; + } +} + +/* + * Same errcode, same table, same names as bch2_decompress_sb_err() above - the + * reason we stamp into a KEY_TYPE_error key when this is what we finally gave + * up on. The sb counter says how often decompression failed this way; the key + * says which extent it cost us. + */ +enum bch_key_type_errors bch2_decompress_key_type_error(int err) +{ + switch (abs(err)) { +#define x(_errcode, _name) \ + case BCH_ERR_##_errcode: \ + return KEY_TYPE_ERROR_decompress_##_name; + BCH_DECOMPRESS_SB_ERRS() +#undef x + default: + return bch2_err_matches(err, BCH_ERR_zstd_error) + ? KEY_TYPE_ERROR_decompress_zstd_unknown + : KEY_TYPE_ERROR_decompress_unknown; + } +} + void bch2_sb_error_count(struct bch_fs *c, enum bch_sb_error_id err) { bch_sb_errors_cpu *e = &c->errors.counts; struct bch_sb_error_entry_cpu n = { .id = err, .nr = 1, - .last_error_time = ktime_get_real_seconds() + .first_error_time = ktime_get_real_seconds(), }; + n.last_error_time = n.first_error_time; unsigned i; guard(mutex)(&c->errors.counts_lock); @@ -182,40 +338,86 @@ void bch2_sb_errors_from_cpu(struct bch_fs *c) guard(mutex)(&c->errors.counts_lock); bch_sb_errors_cpu *src = &c->errors.counts; - struct bch_sb_field_errors *dst = - bch2_sb_field_resize(&c->disk_sb, errors, - bch2_sb_field_errors_u64s(src->nr)); + struct bch_sb_field_errors_v2 *dst = + bch2_sb_field_resize(&c->disk_sb, errors_v2, + bch2_sb_field_errors_v2_u64s(src->nr)); if (!dst) return; for (unsigned i = 0; i < src->nr; i++) { - SET_BCH_SB_ERROR_ENTRY_ID(&dst->entries[i], src->data[i].id); - SET_BCH_SB_ERROR_ENTRY_NR(&dst->entries[i], src->data[i].nr); - dst->entries[i].last_error_time = cpu_to_le64(src->data[i].last_error_time); + SET_BCH_SB_ERROR_ENTRY_V2_ID(&dst->entries[i], src->data[i].id); + SET_BCH_SB_ERROR_ENTRY_V2_NR(&dst->entries[i], src->data[i].nr); + SET_BCH_SB_ERROR_ENTRY_V2_FIRST(&dst->entries[i], src->data[i].first_error_time); + SET_BCH_SB_ERROR_ENTRY_V2_LAST(&dst->entries[i], src->data[i].last_error_time); } + + bch2_sb_field_delete(&c->disk_sb, BCH_SB_FIELD_errors); } +/* + * Reading counts in merges both sections, because both present at once + * means the filesystem was downgraded: writing v2 always deletes legacy + * in the same superblock write, so a legacy section coexisting with v2 + * was recreated by an old kernel afterwards and holds exactly the counts + * accrued since. Sum the counts, take the union of the time ranges (a + * legacy timestamp is both first and last: the error happened at least + * that recently), and the next writeout folds everything back into v2 - + * nothing lost or double counted across downgrade/upgrade cycles. + * + * Both sections are validated strictly ascending by id, so this is a + * plain sorted merge. + */ int bch2_sb_errors_to_cpu(struct bch_fs *c) { guard(mutex)(&c->errors.counts_lock); - struct bch_sb_field_errors *src = bch2_sb_field_get(c->disk_sb.sb, errors); bch_sb_errors_cpu *dst = &c->errors.counts; - unsigned nr = bch2_sb_field_errors_nr_entries(src); - - if (!nr) - return 0; - int ret = darray_make_room(dst, nr); - if (ret) - return ret; - - dst->nr = nr; + struct bch_sb_field_errors_v2 *v2 = bch2_sb_field_get(c->disk_sb.sb, errors_v2); + struct bch_sb_field_errors *legacy = bch2_sb_field_get(c->disk_sb.sb, errors); + unsigned nr_v2 = bch2_sb_field_errors_v2_nr_entries(v2); + unsigned nr_l = bch2_sb_field_errors_nr_entries(legacy); + + try(darray_make_room(dst, nr_v2 + nr_l)); + dst->nr = 0; + + unsigned i = 0, j = 0; + while (i < nr_v2 || j < nr_l) { + u64 id_v2 = i < nr_v2 ? BCH_SB_ERROR_ENTRY_V2_ID(&v2->entries[i]) : U64_MAX; + u64 id_l = j < nr_l ? BCH_SB_ERROR_ENTRY_ID(&legacy->entries[j]) : U64_MAX; + struct bch_sb_error_entry_cpu n; + + if (id_v2 < id_l) { + n = (struct bch_sb_error_entry_cpu) { + .id = id_v2, + .nr = BCH_SB_ERROR_ENTRY_V2_NR(&v2->entries[i]), + .first_error_time = BCH_SB_ERROR_ENTRY_V2_FIRST(&v2->entries[i]), + .last_error_time = BCH_SB_ERROR_ENTRY_V2_LAST(&v2->entries[i]), + }; + i++; + } else if (id_l < id_v2) { + u64 t = le64_to_cpu(legacy->entries[j].last_error_time); + n = (struct bch_sb_error_entry_cpu) { + .id = id_l, + .nr = BCH_SB_ERROR_ENTRY_NR(&legacy->entries[j]), + .first_error_time = t, + .last_error_time = t, + }; + j++; + } else { + u64 t = le64_to_cpu(legacy->entries[j].last_error_time); + n = (struct bch_sb_error_entry_cpu) { + .id = id_v2, + .nr = BCH_SB_ERROR_ENTRY_V2_NR(&v2->entries[i]) + + BCH_SB_ERROR_ENTRY_NR(&legacy->entries[j]), + .first_error_time = min(BCH_SB_ERROR_ENTRY_V2_FIRST(&v2->entries[i]), t), + .last_error_time = max(BCH_SB_ERROR_ENTRY_V2_LAST(&v2->entries[i]), t), + }; + i++; + j++; + } - for (unsigned i = 0; i < nr; i++) { - dst->data[i].id = BCH_SB_ERROR_ENTRY_ID(&src->entries[i]); - dst->data[i].nr = BCH_SB_ERROR_ENTRY_NR(&src->entries[i]); - dst->data[i].last_error_time = le64_to_cpu(src->entries[i].last_error_time); + dst->data[dst->nr++] = n; } return 0; diff --git a/fs/sb/errors.h b/fs/sb/errors.h index 59eb6a6342..054c64395e 100644 --- a/fs/sb/errors.h +++ b/fs/sb/errors.h @@ -7,12 +7,86 @@ extern const char * const bch2_sb_error_strs[]; void bch2_sb_error_id_to_text(struct printbuf *, enum bch_sb_error_id); +void bch2_prt_error_nr(struct printbuf *, u64); void bch2_fs_errors_to_text(struct printbuf *, struct bch_fs *); extern const struct bch_sb_field_ops bch_sb_field_ops_errors; +extern const struct bch_sb_field_ops bch_sb_field_ops_errors_v2; void bch2_sb_error_count(struct bch_fs *, enum bch_sb_error_id); +/* + * Block statuses we count separately: what the device said is the first + * thing worth knowing from a filesystem that's logging IO errors - media + * errors mean the drive is going, timeouts mean it's hanging, transport + * errors point at the fabric, and INVAL means the request itself was + * rejected: not an error the device hit, an error in what we handed it. + * + * Curated by hand rather than generated from BLK_ERRS(): sb error ids are + * permanent on-disk numbers, so we don't spend them on statuses that can't + * reach a bcachefs completion - DM_REQUEUE is consumed inside dm, and the + * zone codes want zoned device support we don't have. Anything left out + * counts as blk_sts_unknown; to promote one, add it here and add a + * numbered entry in errors_format.h - the build breaks if you forget. + */ +#define BCH_BLK_STS_SB_ERRS() \ + x(NOTSUPP, notsupp) \ + x(TIMEOUT, timeout) \ + x(NOSPC, nospc) \ + x(TRANSPORT, transport) \ + x(TARGET, target) \ + x(RESV_CONFLICT, resv_conflict) \ + x(MEDIUM, medium) \ + x(PROTECTION, protection) \ + x(RESOURCE, resource) \ + x(IOERR, ioerr) \ + x(AGAIN, again) \ + x(DEV_RESOURCE, dev_resource) \ + x(OFFLINE, offline) \ + x(DURATION_LIMIT, duration_limit) \ + x(INVAL, inval) \ + x(REMOVED, removed) + +enum bch_sb_error_id bch2_blk_sts_sb_err(int); + +/* + * Decompression failures we count separately: an extent that won't + * decompress is a different animal from one that won't read or won't + * checksum - as far as the checksum can tell the data came off the device + * intact, and then didn't decode. Counting per compression type answers + * the first question such a report raises, which is whether one algorithm + * is at fault or all of them are. + * + * The zstd codes separate that further: corruption_detected and + * checksum_wrong say the compressed data is bad, dst_size_too_small and + * memory_allocation say we drove zstd wrong or couldn't allocate. + * + * Curated by hand for the same reason as the block statuses above - sb + * error ids are permanent on-disk numbers. zstd defines 27 error codes, + * most of which zstd_decompress_dctx() can't return for the single raw + * frame we hand it; those count as data_decompress_err_zstd_unknown, and + * anything not a decompress errcode at all as data_decompress_err_unknown. + * To promote one, add it here and add a numbered entry in + * errors_format.h - the build breaks if you forget. + */ +#define BCH_DECOMPRESS_SB_ERRS() \ + x(decompress_exceeded_max_encoded_extent, exceeded_max_encoded_extent) \ + x(decompress_lz4_old, lz4_old) \ + x(decompress_lz4, lz4) \ + x(decompress_gzip, gzip) \ + x(decompress_gzip_size_mismatch, gzip_size_mismatch) \ + x(decompress_zstd_src_len_bad, zstd_src_len_bad) \ + x(decompress_zstd_size_mismatch, zstd_size_mismatch) \ + x(ZSTD_error_corruption_detected, zstd_corruption_detected) \ + x(ZSTD_error_checksum_wrong, zstd_checksum_wrong) \ + x(ZSTD_error_prefix_unknown, zstd_prefix_unknown) \ + x(ZSTD_error_srcSize_wrong, zstd_src_size_wrong) \ + x(ZSTD_error_dstSize_tooSmall, zstd_dst_size_too_small) \ + x(ZSTD_error_memory_allocation, zstd_memory_allocation) + +enum bch_sb_error_id bch2_decompress_sb_err(int); +enum bch_key_type_errors bch2_decompress_key_type_error(int); + void bch2_sb_errors_from_cpu(struct bch_fs *); int bch2_sb_errors_to_cpu(struct bch_fs *); diff --git a/fs/sb/errors_format.h b/fs/sb/errors_format.h index 05fbfcf2f0..a8245cf3a3 100644 --- a/fs/sb/errors_format.h +++ b/fs/sb/errors_format.h @@ -55,7 +55,7 @@ enum bch_fsck_flags { x(btree_node_replicas_sectors_written_mismatch, 39, 0) \ x(btree_node_replicas_data_mismatch, 40, 0) \ x(bset_unknown_csum, 41, 0) \ - x(bset_bad_csum, 42, 0) \ + x(bset_bad_csum, 42, FSCK_AUTOFIX) \ x(bset_past_end_of_btree_node, 43, 0) \ x(bset_wrong_sector_offset, 44, 0) \ x(bset_empty, 45, 0) \ @@ -227,9 +227,13 @@ enum bch_fsck_flags { x(snapshot_edge_bad, 371, 0) \ x(snapshot_state_bad, 373, FSCK_AUTOFIX) \ x(snapshot_state_bitflip, 379, FSCK_AUTOFIX) \ - x(snapshot_will_delete_but_subvol_live, 376, FSCK_AUTOFIX) \ + x(snapshot_state_stale_tombstone, 382, FSCK_AUTOFIX) \ + x(snapshot_subvol_state_mismatch, 386, FSCK_AUTOFIX) \ + x(snapshot_deleted_but_subvol_live, 376, FSCK_AUTOFIX) \ x(snapshot_deleted_has_live_children, 381, FSCK_AUTOFIX) \ - x(snapshot_subvol_backref_wrong, 377, 0) \ + x(snapshot_deleted_but_linked, 384, FSCK_AUTOFIX) \ + x(snapshot_deleted_but_has_data, 385, FSCK_AUTOFIX) \ + x(snapshot_subvol_backref_wrong, 377, FSCK_AUTOFIX) \ x(snapshot_no_keys_childless, 378, FSCK_AUTOFIX) \ x(snapshot_should_not_have_subvol, 182, 0) \ x(snapshot_subvol_flag_wrong, 369, FSCK_AUTOFIX) \ @@ -244,6 +248,7 @@ enum bch_fsck_flags { x(subvol_not_master_and_not_snapshot, 187, FSCK_AUTOFIX) \ x(subvol_to_missing_root, 188, FSCK_AUTOFIX) \ x(subvol_root_wrong_bi_subvol, 189, FSCK_AUTOFIX) \ + x(subvol_root_unlinked_flag_missing, 383, FSCK_AUTOFIX) \ x(bkey_in_missing_snapshot, 190, 0) \ x(bkey_in_deleted_snapshot, 315, FSCK_AUTOFIX) \ x(inode_pos_inode_nonzero, 191, 0) \ @@ -257,7 +262,7 @@ enum bch_fsck_flags { x(inode_unlinked_but_clean, 197, 0) \ x(inode_unlinked_but_nlink_nonzero, 198, 0) \ x(inode_unlinked_and_not_open, 281, 0) \ - x(inode_unlinked_but_has_dirent, 285, 0) \ + x(inode_unlinked_but_has_dirent, 285, FSCK_AUTOFIX) \ x(unlinked_inode_not_on_deleted_list, 244, FSCK_AUTOFIX) \ x(inode_checksum_type_invalid, 199, 0) \ x(inode_compression_type_invalid, 200, 0) \ @@ -275,6 +280,7 @@ enum bch_fsck_flags { x(inode_wrong_nlink, 209, FSCK_AUTOFIX) \ x(inode_has_child_snapshots_wrong, 287, FSCK_AUTOFIX) \ x(inode_unreachable, 210, FSCK_AUTOFIX) \ + x(inode_unreachable_dirent_in_descendant, 427, FSCK_AUTOFIX) \ x(inode_journal_seq_in_future, 299, FSCK_AUTOFIX) \ x(inode_i_sectors_underflow, 312, FSCK_AUTOFIX) \ x(inode_has_case_insensitive_not_set, 316, FSCK_AUTOFIX) \ @@ -287,7 +293,7 @@ enum bch_fsck_flags { x(deleted_inode_is_dir, 213, FSCK_AUTOFIX) \ x(deleted_inode_not_unlinked, 214, FSCK_AUTOFIX) \ x(deleted_inode_has_child_snapshots, 288, FSCK_AUTOFIX) \ - x(extent_overlapping, 215, 0) \ + x(extent_overlapping, 215, FSCK_AUTOFIX) \ x(key_in_missing_inode, 216, FSCK_AUTOFIX) \ x(key_in_wrong_inode_type, 217, 0) \ x(extent_past_end_of_inode, 218, FSCK_AUTOFIX) \ @@ -298,12 +304,12 @@ enum bch_fsck_flags { x(dirent_name_dot_or_dotdot, 223, 0) \ x(dirent_name_has_slash, 224, 0) \ x(dirent_d_type_wrong, 225, FSCK_AUTOFIX) \ - x(inode_bi_parent_wrong, 226, 0) \ + x(inode_bi_parent_wrong, 226, FSCK_AUTOFIX) \ x(dirent_in_missing_dir_inode, 227, 0) \ x(dirent_in_non_dir_inode, 228, 0) \ x(dirent_to_missing_inode, 229, FSCK_AUTOFIX) \ x(dirent_to_overwritten_inode, 302, FSCK_AUTOFIX) \ - x(dirent_to_missing_subvol, 230, 0) \ + x(dirent_to_missing_subvol, 230, FSCK_AUTOFIX) \ x(dirent_to_itself, 231, 0) \ x(dirent_casefold_mismatch, 318, FSCK_AUTOFIX) \ x(quota_type_invalid, 232, 0) \ @@ -312,23 +318,23 @@ enum bch_fsck_flags { x(xattr_invalid_type, 235, 0) \ x(xattr_name_invalid_chars, 236, 0) \ x(xattr_in_missing_inode, 237, 0) \ - x(root_subvol_missing, 238, 0) \ - x(root_dir_missing, 239, 0) \ - x(root_inode_not_dir, 240, 0) \ + x(root_subvol_missing, 238, FSCK_AUTOFIX) \ + x(root_dir_missing, 239, FSCK_AUTOFIX) \ + x(root_inode_not_dir, 240, FSCK_AUTOFIX) \ x(dir_loop, 241, FSCK_AUTOFIX) \ x(hash_table_key_duplicate, 242, FSCK_AUTOFIX) \ x(hash_table_key_wrong_offset, 243, FSCK_AUTOFIX) \ x(reflink_p_front_pad_bad, 245, 0) \ x(journal_entry_dup_same_device, 246, 0) \ - x(inode_bi_subvol_missing, 247, 0) \ - x(inode_bi_subvol_wrong, 248, 0) \ + x(inode_bi_subvol_missing, 247, FSCK_AUTOFIX) \ + x(inode_bi_subvol_wrong, 248, FSCK_AUTOFIX) \ x(inode_points_to_missing_dirent, 249, FSCK_AUTOFIX) \ x(inode_points_to_wrong_dirent, 250, FSCK_AUTOFIX) \ x(inode_bi_parent_nonzero, 251, 0) \ x(missing_inode_with_contents, 321, FSCK_AUTOFIX) \ x(dirent_to_missing_parent_subvol, 252, 0) \ - x(dirent_not_visible_in_parent_subvol, 253, 0) \ - x(subvol_fs_path_parent_wrong, 254, 0) \ + x(dirent_not_visible_in_parent_subvol, 253, FSCK_AUTOFIX) \ + x(subvol_fs_path_parent_wrong, 254, FSCK_AUTOFIX) \ x(subvol_root_fs_path_parent_nonzero, 255, 0) \ x(subvol_children_not_set, 256, 0) \ x(subvol_children_bad, 257, 0) \ @@ -393,7 +399,47 @@ enum bch_fsck_flags { x(inode_has_access_acl_flag_wrong, 366, FSCK_AUTOFIX) \ x(inode_has_default_acl_flag_wrong, 367, FSCK_AUTOFIX) \ x(dirent_to_inode_in_descendant_snapshot, 368, FSCK_AUTOFIX) \ - x(MAX, 382, 0) + x(damage_entries_bad, 387, 0) \ + x(damage_key_no_inode, 388, FSCK_AUTOFIX) \ + x(data_read_io_err_recovered, 389, 0) \ + x(data_read_io_err, 390, 0) \ + x(data_read_csum_err_recovered, 391, 0) \ + x(data_read_csum_err, 392, 0) \ + x(data_lost_device_removed, 393, 0) \ + x(blk_sts_notsupp, 394, 0) \ + x(blk_sts_timeout, 395, 0) \ + x(blk_sts_nospc, 396, 0) \ + x(blk_sts_transport, 397, 0) \ + x(blk_sts_target, 398, 0) \ + x(blk_sts_resv_conflict, 399, 0) \ + x(blk_sts_medium, 400, 0) \ + x(blk_sts_protection, 401, 0) \ + x(blk_sts_resource, 402, 0) \ + x(blk_sts_ioerr, 403, 0) \ + x(blk_sts_again, 404, 0) \ + x(blk_sts_dev_resource, 405, 0) \ + x(blk_sts_offline, 406, 0) \ + x(blk_sts_duration_limit, 407, 0) \ + x(blk_sts_inval, 408, 0) \ + x(blk_sts_removed, 409, 0) \ + x(blk_sts_unknown, 410, 0) \ + x(data_decompress_err_exceeded_max_encoded_extent, 411, 0) \ + x(data_decompress_err_lz4_old, 412, 0) \ + x(data_decompress_err_lz4, 413, 0) \ + x(data_decompress_err_gzip, 414, 0) \ + x(data_decompress_err_gzip_size_mismatch, 415, 0) \ + x(data_decompress_err_zstd_src_len_bad, 416, 0) \ + x(data_decompress_err_zstd_size_mismatch, 417, 0) \ + x(data_decompress_err_zstd_corruption_detected, 418, 0) \ + x(data_decompress_err_zstd_checksum_wrong, 419, 0) \ + x(data_decompress_err_zstd_prefix_unknown, 420, 0) \ + x(data_decompress_err_zstd_src_size_wrong, 421, 0) \ + x(data_decompress_err_zstd_dst_size_too_small, 422, 0) \ + x(data_decompress_err_zstd_memory_allocation, 423, 0) \ + x(data_decompress_err_zstd_unknown, 424, 0) \ + x(data_decompress_err_unknown, 425, 0) \ + x(snapshot_child_missing_but_accounted, 426, FSCK_AUTOFIX) \ + x(MAX, 428, 0) enum bch_sb_error_id { #define x(t, n, ...) BCH_FSCK_ERR_##t = n, @@ -414,4 +460,81 @@ struct bch_sb_field_errors { LE64_BITMASK(BCH_SB_ERROR_ENTRY_ID, struct bch_sb_field_error_entry, v, 0, 16); LE64_BITMASK(BCH_SB_ERROR_ENTRY_NR, struct bch_sb_field_error_entry, v, 16, 64); +/* + * v2 entries add the time of first occurrence: id (16 bits), a + * saturating occurrence count (32), and two 40-bit second-resolution + * timestamps - good until the year ~36,800 - packed exactly into 128 + * bits. No 64-bit boundary partition fits {16, 32, 40, 40}, so + * last_error_time spans the two words and the accessors are hand + * rolled; the setters saturate, since a wrapped count or timestamp + * would be worse than a pinned one. + * + * v[0]: id 0..16, nr 16..48, last_error_time 48..64 (low 16 bits) + * v[1]: last_error_time 0..24 (high 24 bits), first_error_time 24..64 + */ +typedef struct bch_sb_field_error_entry_v2 { + __le64 v[2]; +} bch_sb_field_error_entry_v2; + +struct bch_sb_field_errors_v2 { + struct bch_sb_field field; + bch_sb_field_error_entry_v2 entries[]; +}; + +#define BCH_SB_ERROR_ENTRY_V2_NR_MAX ((1ULL << 32) - 1) +#define BCH_SB_ERROR_ENTRY_V2_TIME_MAX ((1ULL << 40) - 1) + +static inline __u64 BCH_SB_ERROR_ENTRY_V2_ID(const struct bch_sb_field_error_entry_v2 *e) +{ + return __le64_to_cpu(e->v[0]) & 0xffff; +} + +static inline void SET_BCH_SB_ERROR_ENTRY_V2_ID(struct bch_sb_field_error_entry_v2 *e, __u64 id) +{ + e->v[0] = __cpu_to_le64((__le64_to_cpu(e->v[0]) & ~0xffffULL) | + (id & 0xffff)); +} + +static inline __u64 BCH_SB_ERROR_ENTRY_V2_NR(const struct bch_sb_field_error_entry_v2 *e) +{ + return (__le64_to_cpu(e->v[0]) >> 16) & 0xffffffffULL; +} + +static inline void SET_BCH_SB_ERROR_ENTRY_V2_NR(struct bch_sb_field_error_entry_v2 *e, __u64 nr) +{ + if (nr > BCH_SB_ERROR_ENTRY_V2_NR_MAX) + nr = BCH_SB_ERROR_ENTRY_V2_NR_MAX; + e->v[0] = __cpu_to_le64((__le64_to_cpu(e->v[0]) & ~(0xffffffffULL << 16)) | + (nr << 16)); +} + +static inline __u64 BCH_SB_ERROR_ENTRY_V2_LAST(const struct bch_sb_field_error_entry_v2 *e) +{ + return (__le64_to_cpu(e->v[0]) >> 48) | + ((__le64_to_cpu(e->v[1]) & 0xffffffULL) << 16); +} + +static inline void SET_BCH_SB_ERROR_ENTRY_V2_LAST(struct bch_sb_field_error_entry_v2 *e, __u64 t) +{ + if (t > BCH_SB_ERROR_ENTRY_V2_TIME_MAX) + t = BCH_SB_ERROR_ENTRY_V2_TIME_MAX; + e->v[0] = __cpu_to_le64((__le64_to_cpu(e->v[0]) & ~(0xffffULL << 48)) | + ((t & 0xffff) << 48)); + e->v[1] = __cpu_to_le64((__le64_to_cpu(e->v[1]) & ~0xffffffULL) | + (t >> 16)); +} + +static inline __u64 BCH_SB_ERROR_ENTRY_V2_FIRST(const struct bch_sb_field_error_entry_v2 *e) +{ + return __le64_to_cpu(e->v[1]) >> 24; +} + +static inline void SET_BCH_SB_ERROR_ENTRY_V2_FIRST(struct bch_sb_field_error_entry_v2 *e, __u64 t) +{ + if (t > BCH_SB_ERROR_ENTRY_V2_TIME_MAX) + t = BCH_SB_ERROR_ENTRY_V2_TIME_MAX; + e->v[1] = __cpu_to_le64((__le64_to_cpu(e->v[1]) & 0xffffffULL) | + (t << 24)); +} + #endif /* _BCACHEFS_SB_ERRORS_FORMAT_H */ diff --git a/fs/sb/errors_types.h b/fs/sb/errors_types.h index 98281724ad..02a3adff12 100644 --- a/fs/sb/errors_types.h +++ b/fs/sb/errors_types.h @@ -7,6 +7,7 @@ struct bch_sb_error_entry_cpu { u64 id:16, nr:48; + u64 first_error_time; u64 last_error_time; }; diff --git a/fs/sb/io.c b/fs/sb/io.c index 4d35121a0a..2b5b365a19 100644 --- a/fs/sb/io.c +++ b/fs/sb/io.c @@ -214,8 +214,7 @@ int bch2_set_version_incompat(struct bch_fs *c, enum bcachefs_metadata_version v { if (((c->sb.features & BIT_ULL(BCH_FEATURE_incompat_version_field)) && version <= c->sb.version_incompat_allowed)) { - guard(memalloc_flags)(PF_MEMALLOC_NOFS); - guard(mutex)(&c->sb_lock); + guard(mutex_noio)(&c->sb_lock); if (version > c->sb.version_incompat) { SET_BCH_SB_VERSION_INCOMPAT(c->disk_sb.sb, @@ -361,7 +360,7 @@ int bch2_sb_realloc(struct bch_sb_handle *sb, unsigned u64s) if (dynamic_fault("bcachefs:add:super_realloc")) return -BCH_ERR_ENOMEM_sb_realloc_injected; - new_sb = kvrealloc(sb->sb, new_buffer_size, GFP_NOFS|__GFP_ZERO); + new_sb = kvrealloc(sb->sb, new_buffer_size, GFP_NOIO|__GFP_ZERO); if (!new_sb) return -BCH_ERR_ENOMEM_sb_buf_realloc; @@ -399,7 +398,7 @@ struct bch_sb_field *bch2_sb_field_resize_id(struct bch_sb_handle *sb, if (sb->fs_sb) { struct bch_fs *c = container_of(sb, struct bch_fs, disk_sb); - lockdep_assert_held(&c->sb_lock); + lockdep_assert_held(&c->sb_lock.lock); /* XXX: we're not checking that offline device have enough space */ @@ -692,7 +691,7 @@ static void bch2_sb_update(struct bch_fs *c) { struct bch_sb *src = c->disk_sb.sb; - lockdep_assert_held(&c->sb_lock); + lockdep_assert_held(&c->sb_lock.lock); c->sb.uuid = src->uuid; c->sb.user_uuid = src->user_uuid; @@ -720,6 +719,7 @@ static void bch2_sb_update(struct bch_fs *c) c->sb.features = le64_to_cpu(src->features[0]); c->sb.compat = le64_to_cpu(src->compat[0]); c->sb.multi_device = BCH_SB_MULTI_DEVICE(src); + c->sb.dirents_sanitized = BCH_SB_DIRENTS_SANITIZED(src); struct bch_sb_field_ext *ext = bch2_sb_field_get(src, ext); if (ext) { @@ -798,7 +798,7 @@ static int __copy_super(struct bch_sb_handle *dst_handle, struct bch_sb *src) int bch2_sb_to_fs(struct bch_fs *c, struct bch_sb *src) { - lockdep_assert_held(&c->sb_lock); + lockdep_assert_held(&c->sb_lock.lock); try(bch2_sb_realloc(&c->disk_sb, 0)); try(__copy_super(&c->disk_sb, src)); @@ -1208,7 +1208,7 @@ static int __bch2_write_super(struct bch_fs *c) if (c->opts.degraded == BCH_DEGRADED_very) degraded_flags |= BCH_FORCE_IF_LOST; - lockdep_assert_held(&c->sb_lock); + lockdep_assert_held(&c->sb_lock.lock); closure_init_stack(cl); @@ -1439,8 +1439,7 @@ int bch2_write_super(struct bch_fs *c) void __bch2_check_set_feature(struct bch_fs *c, unsigned feat) { - guard(memalloc_flags)(PF_MEMALLOC_NOFS); - guard(mutex)(&c->sb_lock); + guard(mutex_noio)(&c->sb_lock); if (!(c->sb.features & BIT_ULL(feat))) { c->disk_sb.sb->features[0] |= cpu_to_le64(BIT_ULL(feat)); @@ -1453,7 +1452,7 @@ bool bch2_check_version_downgrade(struct bch_fs *c) { bool ret = bcachefs_metadata_version_current < c->sb.version; - lockdep_assert_held(&c->sb_lock); + lockdep_assert_held(&c->sb_lock.lock); /* * Downgrade, if superblock is at a higher version than currently @@ -1476,7 +1475,7 @@ bool bch2_check_version_downgrade(struct bch_fs *c) void bch2_sb_upgrade(struct bch_fs *c, unsigned new_version, bool incompat) { - lockdep_assert_held(&c->sb_lock); + lockdep_assert_held(&c->sb_lock.lock); if (BCH_VERSION_MAJOR(new_version) > BCH_VERSION_MAJOR(le16_to_cpu(c->disk_sb.sb->version))) @@ -1493,8 +1492,7 @@ void bch2_sb_upgrade(struct bch_fs *c, unsigned new_version, bool incompat) void bch2_sb_upgrade_incompat(struct bch_fs *c) { - guard(memalloc_flags)(PF_MEMALLOC_NOFS); - guard(mutex)(&c->sb_lock); + guard(mutex_noio)(&c->sb_lock); if (c->sb.version == c->sb.version_incompat_allowed) return; @@ -1740,6 +1738,10 @@ __cold void bch2_sb_to_text(struct printbuf *out, prt_newline(out); prt_printf(out, "Clean:\t%llu\n", BCH_SB_CLEAN(sb)); + + if (BCH_SB_DIRENTS_SANITIZED(sb)) + prt_printf(out, "Dirents sanitized:\t1\n"); + prt_printf(out, "Devices:\t%u\n", bch2_sb_nr_devices(sb)); prt_printf(out, "Sections:\t"); diff --git a/fs/sb/io.rs b/fs/sb/io.rs index e8f35ee9aa..b79d94fa9f 100644 --- a/fs/sb/io.rs +++ b/fs/sb/io.rs @@ -85,6 +85,50 @@ impl bch_sb_handle { sb_field_get_minsize(self, min_u64s) } + /// Delete a superblock field by type. + pub fn field_delete(&mut self, ty: c::bch_sb_field_type) { + unsafe { c::bch2_sb_field_delete(self, ty) } + } + + /// Reallocate the superblock buffer for at least `u64s` (0 = minimum). + pub fn sb_realloc(&mut self, u64s: u32) -> Result<(), i32> { + match unsafe { c::bch2_sb_realloc(self, u64s) } { + 0 => Ok(()), + e => Err(e), + } + } + + /// Copy members_v2 into the members_v1 mirror, for old-kernel compat. + pub fn members_cpy_v2_v1(&mut self) { + unsafe { c::bch2_sb_members_cpy_v2_v1(self) }; + } + + /// Find a disk path (label group) by name. + pub fn disk_path_find(&mut self, name: &core::ffi::CStr) -> Option { + let v = unsafe { c::bch2_disk_path_find(self, name.as_ptr()) }; + (v >= 0).then_some(v as u32) + } + + /// Find or create a disk path; Err(errno) on failure. + pub fn disk_path_find_or_create(&mut self, name: &core::ffi::CStr) -> Result { + let v = unsafe { c::bch2_disk_path_find_or_create(self, name.as_ptr()) }; + if v >= 0 { Ok(v as u32) } else { Err(-v) } + } + + /// The superblock's full vstruct extent as bytes. + pub fn sb_bytes(&self) -> &[u8] { + let bytes = core::mem::size_of::() + + u32::from_le(self.sb().u64s) as usize * 8; + unsafe { core::slice::from_raw_parts(self.sb as *const u8, bytes) } + } + + /// The superblock's full vstruct extent, mutably. + pub fn sb_bytes_mut(&mut self) -> &mut [u8] { + let bytes = core::mem::size_of::() + + u32::from_le(self.sb().u64s) as usize * 8; + unsafe { core::slice::from_raw_parts_mut(self.sb as *mut u8, bytes) } + } + /// Get a mutable reference to a single member entry by device index. /// /// This is the simple accessor for one-shot field mutation. For @@ -173,6 +217,248 @@ pub fn sb_field_get_minsize( } } +// Safe wrappers over the hand-rolled v2 error entry accessors +// (sb/errors_format.h): they only read through the pointer. +impl c::bch_sb_field_error_entry_v2 { + pub fn id(&self) -> u16 { + unsafe { c::BCH_SB_ERROR_ENTRY_V2_ID(self) as u16 } + } + + pub fn nr(&self) -> u64 { + unsafe { c::BCH_SB_ERROR_ENTRY_V2_NR(self) } + } + + pub fn first_error_time(&self) -> u64 { + unsafe { c::BCH_SB_ERROR_ENTRY_V2_FIRST(self) } + } + + pub fn last_error_time(&self) -> u64 { + unsafe { c::BCH_SB_ERROR_ENTRY_V2_LAST(self) } + } +} + +// --------------------------------------------------------------------------- +// Raw-buffer superblock views +// +// For superblocks in plain byte buffers (device scans, recovery) rather +// than a C bch_sb_handle. Construction validates every extent once - +// header within the buffer, vstruct extent within the buffer, each +// field's extent within the superblock - so typed access afterwards is +// safe: the C field lookups walk exactly the extents parse() checked. +// Semantic validity remains bch2_sb_validate()'s job; these views +// guarantee memory safety only. Raw buffers can't be reallocated, so +// mutation is in-place only - field resize/delete stay on bch_sb_handle. +// --------------------------------------------------------------------------- + +pub const BCACHE_MAGIC: [u8; 16] = [ + 0xc6, 0x85, 0x73, 0xf6, 0x4e, 0x1a, 0x45, 0xca, + 0x82, 0x65, 0xf5, 0x7f, 0x48, 0xba, 0x6d, 0x81, +]; +pub const BCHFS_MAGIC: [u8; 16] = [ + 0xc6, 0x85, 0x73, 0xf6, 0x66, 0xce, 0x90, 0xa9, + 0xd9, 0x6a, 0x60, 0xcf, 0x80, 0x3d, 0xf7, 0xef, +]; + +/// Why a buffer failed to parse as a superblock. Precise by design: +/// recovery reports these against scan candidates. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SbParseError { + BufferTooSmall { need: usize, have: usize }, + Misaligned, + BadMagic, + ExtentBeyondBuffer { need: usize, have: usize }, + FieldBeyondSb { field_offset: usize }, + FieldBadU64s { field_offset: usize }, +} + +impl core::fmt::Display for SbParseError { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match self { + SbParseError::BufferTooSmall { need, have } => + write!(f, "buffer too small for superblock header: need {need}, have {have}"), + SbParseError::Misaligned => + write!(f, "buffer not sufficiently aligned for a superblock"), + SbParseError::BadMagic => + write!(f, "not a bcachefs superblock (bad magic)"), + SbParseError::ExtentBeyondBuffer { need, have } => + write!(f, "superblock u64s extends beyond buffer: need {need}, have {have}"), + SbParseError::FieldBeyondSb { field_offset } => + write!(f, "superblock field at offset {field_offset} extends beyond superblock"), + SbParseError::FieldBadU64s { field_offset } => + write!(f, "superblock field at offset {field_offset} with u64s 0"), + } + } +} + +/// Validate the extents; returns the vstruct size in bytes. +fn sb_parse_checks(buf: &[u8]) -> Result { + let hdr = core::mem::size_of::(); + if buf.len() < hdr { + return Err(SbParseError::BufferTooSmall { need: hdr, have: buf.len() }); + } + if buf.as_ptr() as usize % core::mem::align_of::() != 0 { + return Err(SbParseError::Misaligned); + } + /* header extent and alignment just validated: */ + let sb = unsafe { &*(buf.as_ptr() as *const bch_sb) }; + + if sb.magic.b != BCACHE_MAGIC && sb.magic.b != BCHFS_MAGIC { + return Err(SbParseError::BadMagic); + } + + let bytes = hdr + u32::from_le(sb.u64s) as usize * 8; + if bytes > buf.len() { + return Err(SbParseError::ExtentBeyondBuffer { need: bytes, have: buf.len() }); + } + + let mut off = hdr; + while off < bytes { + if bytes - off < core::mem::size_of::() { + return Err(SbParseError::FieldBeyondSb { field_offset: off }); + } + /* field header extent just validated: */ + let f = unsafe { &*(buf.as_ptr().add(off) as *const c::bch_sb_field) }; + let f_u64s = u32::from_le(f.u64s) as u64; + if f_u64s == 0 { + return Err(SbParseError::FieldBadU64s { field_offset: off }); + } + let next = off as u64 + f_u64s * 8; + if next > bytes as u64 { + return Err(SbParseError::FieldBeyondSb { field_offset: off }); + } + off = next as usize; + } + + Ok(bytes) +} + +/// A validated read-only superblock in a byte buffer. +pub struct SbRef<'a> { + buf: &'a [u8], + bytes: usize, +} + +impl<'a> SbRef<'a> { + pub fn parse(buf: &'a [u8]) -> Result { + let bytes = sb_parse_checks(buf)?; + Ok(SbRef { buf, bytes }) + } + + pub fn sb(&self) -> &'a bch_sb { + unsafe { &*(self.buf.as_ptr() as *const bch_sb) } + } + + /// The superblock's full vstruct extent. + pub fn bytes(&self) -> &'a [u8] { + &self.buf[..self.bytes] + } + + pub fn field(&self) -> Option<&'a F> { + sb_field_get(self.sb()) + } +} + +/// A validated superblock in a byte buffer, for in-place mutation. +pub struct SbMut<'a> { + buf: &'a mut [u8], + bytes: usize, +} + +impl<'a> SbMut<'a> { + pub fn parse(buf: &'a mut [u8]) -> Result { + let bytes = sb_parse_checks(buf)?; + Ok(SbMut { buf, bytes }) + } + + pub fn sb(&self) -> &bch_sb { + unsafe { &*(self.buf.as_ptr() as *const bch_sb) } + } + + pub fn sb_mut(&mut self) -> &mut bch_sb { + unsafe { &mut *(self.buf.as_mut_ptr() as *mut bch_sb) } + } + + /// The superblock's full vstruct extent. + pub fn bytes(&self) -> &[u8] { + &self.buf[..self.bytes] + } + + pub fn field(&self) -> Option<&F> { + sb_field_get(self.sb()) + } +} + +/// Anything holding a superblock that can be viewed as bytes and +/// mutated in place: SbMut/SbBuf over raw buffers, bch_sb_handle for +/// C-owned superblocks. Superblock IO takes any of them. +pub trait SbAccess { + fn sb(&self) -> &bch_sb; + fn sb_mut(&mut self) -> &mut bch_sb; + /// The superblock's full vstruct extent. + fn sb_bytes(&self) -> &[u8]; +} + +impl SbAccess for bch_sb_handle { + fn sb(&self) -> &bch_sb { bch_sb_handle::sb(self) } + fn sb_mut(&mut self) -> &mut bch_sb { bch_sb_handle::sb_mut(self) } + fn sb_bytes(&self) -> &[u8] { bch_sb_handle::sb_bytes(self) } +} + +impl SbAccess for SbMut<'_> { + fn sb(&self) -> &bch_sb { SbMut::sb(self) } + fn sb_mut(&mut self) -> &mut bch_sb { SbMut::sb_mut(self) } + fn sb_bytes(&self) -> &[u8] { SbMut::bytes(self) } +} + +/// An owned superblock: aligned storage, extents validated at +/// construction. The owned counterpart of SbRef/SbMut, for recovery +/// flows that carry superblocks around as values. +#[cfg(feature = "std")] +pub struct SbBuf { + buf: Vec, + bytes: usize, +} + +#[cfg(feature = "std")] +impl SbBuf { + /// Copy a superblock out of `src` (no alignment requirement) and + /// validate it. + pub fn from_bytes(src: &[u8]) -> Result { + let mut buf = vec![0u64; src.len().div_ceil(8)]; + let dst = unsafe { + core::slice::from_raw_parts_mut(buf.as_mut_ptr() as *mut u8, src.len()) + }; + dst.copy_from_slice(src); + + let bytes = sb_parse_checks(&dst[..])?; + Ok(SbBuf { buf, bytes }) + } + + pub fn sb(&self) -> &bch_sb { + unsafe { &*(self.buf.as_ptr() as *const bch_sb) } + } + + pub fn sb_mut(&mut self) -> &mut bch_sb { + unsafe { &mut *(self.buf.as_mut_ptr() as *mut bch_sb) } + } + + /// The superblock's full vstruct extent. + pub fn bytes(&self) -> &[u8] { + unsafe { core::slice::from_raw_parts(self.buf.as_ptr() as *const u8, self.bytes) } + } + + pub fn field(&self) -> Option<&F> { + sb_field_get(self.sb()) + } +} + +#[cfg(feature = "std")] +impl SbAccess for SbBuf { + fn sb(&self) -> &bch_sb { SbBuf::sb(self) } + fn sb_mut(&mut self) -> &mut bch_sb { SbBuf::sb_mut(self) } + fn sb_bytes(&self) -> &[u8] { SbBuf::bytes(self) } +} + // LE64_BITMASK accessors — pure Rust replacements for C shims in rust_shims.c. // Each field is defined by: struct type, flags field + index, C constant prefix. diff --git a/fs/sb/io_types.h b/fs/sb/io_types.h index fd6d611e29..2781aac662 100644 --- a/fs/sb/io_types.h +++ b/fs/sb/io_types.h @@ -16,6 +16,7 @@ struct bch_sb_cpu { u8 nr_devices; u8 clean; bool multi_device; /* true if we've ever had more than one device */ + bool dirents_sanitized; u8 encryption_type; diff --git a/fs/sb/members.c b/fs/sb/members.c index 7c5e65348e..18a48ce27e 100644 --- a/fs/sb/members.c +++ b/fs/sb/members.c @@ -216,6 +216,29 @@ static int validate_member(struct printbuf *err, return -BCH_ERR_invalid_sb_members; } + u64 target_nbuckets = le64_to_cpu(m.target_nbuckets); + + if (target_nbuckets) { + if (target_nbuckets < first_bucket) { + prt_printf(err, "device %u: target buckets starts before first bucket (got %llu, first %u)", + i, target_nbuckets, first_bucket); + return -BCH_ERR_invalid_sb_members; + } + + if (target_nbuckets < nbuckets && + target_nbuckets - first_bucket < BCH_MIN_NR_NBUCKETS) { + prt_printf(err, "device %u: not enough target buckets (got %llu, min %u)", + i, target_nbuckets - first_bucket, BCH_MIN_NR_NBUCKETS); + return -BCH_ERR_invalid_sb_members; + } + + if (target_nbuckets > BCH_MEMBER_NBUCKETS_MAX) { + prt_printf(err, "device %u: target buckets too big (got %llu, max %u)", + i, target_nbuckets, BCH_MEMBER_NBUCKETS_MAX); + return -BCH_ERR_invalid_sb_members; + } + } + return 0; } @@ -227,6 +250,7 @@ __cold void bch2_member_to_text(struct printbuf *out, { u64 bucket_size = le16_to_cpu(m->bucket_size); u64 device_size = le64_to_cpu(m->nbuckets) * bucket_size; + u64 target_device_size = le64_to_cpu(m->target_nbuckets) * bucket_size; prt_printf(out, "Label:\t"); if (BCH_MEMBER_GROUP(m)) @@ -236,6 +260,10 @@ __cold void bch2_member_to_text(struct printbuf *out, prt_printf(out, "(none)"); prt_newline(out); + if (m->failure_domain[0]) + prt_printf(out, "Failure domain:\t%.*s\n", + (int) sizeof(m->failure_domain), m->failure_domain); + prt_printf(out, "UUID:\t"); pr_uuid(out, m->uuid.b); prt_newline(out); @@ -244,6 +272,14 @@ __cold void bch2_member_to_text(struct printbuf *out, prt_units_u64(out, device_size << 9); prt_newline(out); + prt_printf(out, "Target size:\t"); + if (target_device_size) { + prt_units_u64(out, target_device_size << 9); + } else { + prt_printf(out, "Inactive"); + } + prt_newline(out); + for (unsigned i = 0; i < BCH_MEMBER_ERROR_NR; i++) prt_printf(out, "%s errors:\t%llu\n", bch2_member_error_strs[i], le64_to_cpu(m->errors[i])); @@ -257,6 +293,14 @@ __cold void bch2_member_to_text(struct printbuf *out, prt_printf(out, "First bucket:\t%u\n", le16_to_cpu(m->first_bucket)); prt_printf(out, "Buckets:\t%llu\n", le64_to_cpu(m->nbuckets)); + prt_printf(out, "Target buckets:\t"); + if (target_device_size) { + prt_printf(out, "%llu", le64_to_cpu(m->target_nbuckets)); + } else { + prt_printf(out, "Inactive"); + } + prt_newline(out); + prt_printf(out, "Last mount:\t"); if (m->last_mount) bch2_prt_datetime(out, le64_to_cpu(m->last_mount)); @@ -329,6 +373,10 @@ static void bch2_member_to_text_short_sb(struct printbuf *out, prt_newline(out); } + if (m->failure_domain[0]) + prt_printf(out, "Failure domain:\t%.*s\n", + (int) sizeof(m->failure_domain), m->failure_domain); + prt_printf(out, "Device:\t%.*s\n", (int) sizeof(m->device_name), m->device_name); prt_printf(out, "Model:\t%.*s\n", (int) sizeof(m->device_model), m->device_model); prt_printf(out, "Serial:\t%.*s\n", (int) sizeof(m->device_serial), m->device_serial); @@ -360,8 +408,7 @@ void bch2_member_to_text_short(struct printbuf *out, struct bch_fs *c, struct bch_dev *ca) { - guard(memalloc_flags)(PF_MEMALLOC_NOFS); - guard(mutex)(&c->sb_lock); + guard(mutex_noio)(&c->sb_lock); bch2_member_to_text_short_locked(out, c, ca); } @@ -498,8 +545,15 @@ void bch2_sb_members_from_cpu(struct bch_fs *c) } } +struct failure_domain { + u8 name[32]; +}; + void bch2_sb_members_to_cpu(struct bch_fs *c) { + BUILD_BUG_ON(sizeof(((struct failure_domain *) NULL)->name) != + sizeof(((struct bch_member *) NULL)->failure_domain)); + for_each_member_device(c, ca) { struct bch_member m = bch2_sb_member_get(c->disk_sb.sb, ca->dev_idx); ca->mi = bch2_mi_to_cpu(&m); @@ -507,6 +561,37 @@ void bch2_sb_members_to_cpu(struct bch_fs *c) mod_bit(ca->dev_idx, c->devs_rotational.d, ca->mi.rotational); } + /* + * Intern failure domain strings to small ids: two devices are in the + * same failure domain iff their (non-empty) strings match. The id is the + * 1-based index into the set of distinct strings, 0 = unset. The table is + * transient - the ids stored on ca->mi are what we keep. + */ + DARRAY(struct failure_domain) domains = {}; + for_each_member_device(c, ca) { + struct bch_member m = bch2_sb_member_get(c->disk_sb.sb, ca->dev_idx); + if (!m.failure_domain[0]) + continue; + + u16 id = 0; + darray_for_each(domains, d) + if (!memcmp(d->name, m.failure_domain, sizeof(d->name))) { + id = (d - domains.data) + 1; + break; + } + + if (!id) { + struct failure_domain d; + memcpy(d.name, m.failure_domain, sizeof(d.name)); + if (darray_push(&domains, d)) + continue; /* -ENOMEM: leave unset, safe */ + id = domains.nr; + } + + ca->mi.failure_domain = id; + } + darray_exit(&domains); + struct bch_sb_field_members_v2 *mi2 = bch2_sb_field_get(c->disk_sb.sb, members_v2); if (mi2) for (unsigned i = 0; i < c->sb.nr_devices; i++) { @@ -521,10 +606,8 @@ __cold void bch2_dev_io_errors_to_text(struct printbuf *out, struct bch_dev *ca) struct bch_fs *c = ca->fs; struct bch_member m; - scoped_guard(memalloc_flags, PF_MEMALLOC_NOFS) { - guard(mutex)(&c->sb_lock); + scoped_guard(mutex_noio, &c->sb_lock) m = bch2_sb_member_get(c->disk_sb.sb, ca->dev_idx); - } printbuf_tabstop_push(out, 12); @@ -554,8 +637,7 @@ void bch2_dev_errors_reset(struct bch_dev *ca) { struct bch_fs *c = ca->fs; - guard(memalloc_flags)(PF_MEMALLOC_NOFS); - guard(mutex)(&c->sb_lock); + guard(mutex_noio)(&c->sb_lock); struct bch_member *m = bch2_members_v2_get_mut(c->disk_sb.sb, ca->dev_idx); for (unsigned i = 0; i < ARRAY_SIZE(m->errors_at_reset); i++) @@ -641,7 +723,7 @@ static void __bch2_dev_btree_bitmap_mark(struct bch_dev *ca, void bch2_dev_btree_bitmap_mark_locked(struct bch_fs *c, struct bkey_s_c k, bool *write_sb) { - lockdep_assert_held(&c->sb_lock); + lockdep_assert_held(&c->sb_lock.lock); struct bch_sb_field_members_v2 *mi = bch2_sb_field_get(c->disk_sb.sb, members_v2); @@ -657,8 +739,7 @@ void bch2_dev_btree_bitmap_mark_locked(struct bch_fs *c, struct bkey_s_c k, bool void bch2_dev_btree_bitmap_mark(struct bch_fs *c, struct bkey_s_c k) { - guard(memalloc_flags)(PF_MEMALLOC_NOFS); - guard(mutex)(&c->sb_lock); + guard(mutex_noio)(&c->sb_lock); bool write_sb = false; bch2_dev_btree_bitmap_mark_locked(c, k, &write_sb); if (write_sb) @@ -687,8 +768,7 @@ int bch2_btree_bitmap_gc(struct bch_fs *c) struct progress_indicator progress; bch2_progress_init(&progress, __func__, c, 0, ~0ULL); - scoped_guard(memalloc_flags, PF_MEMALLOC_NOFS) { - guard(mutex)(&c->sb_lock); + scoped_guard(mutex_noio, &c->sb_lock) { guard(rcu)(); for_each_member_device_rcu(c, ca, NULL) ca->btree_allocated_bitmap_gc = 0; @@ -713,8 +793,7 @@ int bch2_btree_bitmap_gc(struct bch_fs *c) u64 sectors_marked_old = 0, sectors_marked_new = 0; - scoped_guard(memalloc_flags, PF_MEMALLOC_NOFS) { - guard(mutex)(&c->sb_lock); + scoped_guard(mutex_noio, &c->sb_lock) { struct bch_sb_field_members_v2 *mi = bch2_sb_field_get(c->disk_sb.sb, members_v2); scoped_guard(rcu) @@ -795,6 +874,21 @@ unsigned bch2_sb_nr_devices(const struct bch_sb *sb) return nr; } +/* + * Worst observed IO latency (@rw) across @devs, in jiffies - used to scale + * timeouts and "held too long" warnings so slow storage doesn't trip them. + */ +unsigned long bch2_dev_latency_max(struct bch_fs *c, struct bch_devs_mask *devs, int rw) +{ + u64 nsecs = 0; + + guard(rcu)(); + for_each_member_device_rcu(c, ca, devs) + nsecs = max(nsecs, ca->io_latency[rw].stats.max_duration); + + return nsecs_to_jiffies(nsecs); +} + static int bch2_sb_member_find_slot(struct bch_fs *c) { int best = -1; @@ -858,8 +952,7 @@ int bch2_sb_member_alloc(struct bch_fs *c) void bch2_sb_members_clean_deleted(struct bch_fs *c) { - guard(memalloc_flags)(PF_MEMALLOC_NOFS); - guard(mutex)(&c->sb_lock); + guard(mutex_noio)(&c->sb_lock); bool write_sb = false; for (unsigned i = 0; i < c->sb.nr_devices; i++) { @@ -907,7 +1000,7 @@ void bch2_dev_mi_field_upgrades_locked(struct bch_fs *c, struct bch_dev *ca, const struct bch_dev_identity *identity, bool *write_sb) { - lockdep_assert_held(&c->sb_lock); + lockdep_assert_held(&c->sb_lock.lock); struct bch_member *m = bch2_members_v2_get_mut(c->disk_sb.sb, ca->dev_idx); @@ -929,8 +1022,7 @@ void bch2_dev_mi_field_upgrades(struct bch_dev *ca) struct bch_dev_identity identity; bch2_dev_mi_field_read(ca, &identity); - guard(memalloc_flags)(PF_MEMALLOC_NOFS); - guard(mutex)(&c->sb_lock); + guard(mutex_noio)(&c->sb_lock); bool write_sb = false; bch2_dev_mi_field_upgrades_locked(c, ca, &identity, &write_sb); @@ -951,14 +1043,12 @@ void bch2_fs_mi_field_upgrades(struct bch_fs *c) bch2_dev_mi_field_read(ca, &identity); - guard(memalloc_flags)(PF_MEMALLOC_NOFS); - guard(mutex)(&c->sb_lock); + guard(mutex_noio)(&c->sb_lock); bch2_dev_mi_field_upgrades_locked(c, ca, &identity, &write_sb); } if (write_sb) { - guard(memalloc_flags)(PF_MEMALLOC_NOFS); - guard(mutex)(&c->sb_lock); + guard(mutex_noio)(&c->sb_lock); bch2_write_super(c); } } diff --git a/fs/sb/members.h b/fs/sb/members.h index 1bccfaf4ea..f4463097e5 100644 --- a/fs/sb/members.h +++ b/fs/sb/members.h @@ -50,6 +50,8 @@ void bch2_member_to_text_short_locked(struct printbuf *, struct bch_fs *, struct void bch2_member_to_text_short(struct printbuf *, struct bch_fs *, struct bch_dev *); void bch2_devs_mask_to_text_locked(struct printbuf *, struct bch_fs *, struct bch_devs_mask *); +unsigned long bch2_dev_latency_max(struct bch_fs *, struct bch_devs_mask *, int); + /* Device online state: */ static inline bool bch2_dev_is_online(struct bch_dev *ca) @@ -57,7 +59,7 @@ static inline bool bch2_dev_is_online(struct bch_dev *ca) return !enumerated_ref_is_zero(&ca->io_ref[READ]); } -static inline struct bch_dev *bch2_dev_rcu_noerror(struct bch_fs *, unsigned); +static inline struct bch_dev *bch2_dev_rcu_noerror(const struct bch_fs *, unsigned); static inline bool bch2_dev_idx_is_online(struct bch_fs *c, unsigned dev) { @@ -256,29 +258,60 @@ static inline struct bch_dev *bch2_dev_locked(struct bch_fs *c, unsigned dev) EBUG_ON(!bch2_dev_exists(c, dev)); return rcu_dereference_protected(c->devs[dev], - lockdep_is_held(&c->sb_lock) || + lockdep_is_held(&c->sb_lock.lock) || lockdep_is_held(&c->state_lock)); } -static inline struct bch_dev *bch2_dev_rcu_noerror(struct bch_fs *c, unsigned dev) +static inline struct bch_dev *bch2_dev_rcu_noerror(const struct bch_fs *c, unsigned dev) { return c && dev < c->sb.nr_devices ? rcu_dereference(c->devs[dev]) : NULL; } -static inline bool bch2_dev_bad_or_evacuating_rcu(struct bch_fs *c, unsigned dev) +static inline u64 bch2_dev_resize_target(const struct bch_dev *ca) { - struct bch_dev *ca = bch2_dev_rcu_noerror(c, dev); - return !ca || ca->mi.state == BCH_MEMBER_STATE_evacuating; + u64 target = READ_ONCE(ca->mi.target_nbuckets); + + return target ?: READ_ONCE(ca->mi.nbuckets); +} + +static inline bool bch2_dev_resize_pending(const struct bch_dev *ca) +{ + return bch2_dev_resize_target(ca) != READ_ONCE(ca->mi.nbuckets); } -static inline bool bch2_dev_bad_or_evacuating(struct bch_fs *c, unsigned dev) +static inline bool bch2_dev_is_shrinking(const struct bch_dev *ca) +{ + return bch2_dev_resize_target(ca) < READ_ONCE(ca->mi.nbuckets); +} + +static inline bool bch2_dev_is_growing(const struct bch_dev *ca) +{ + return bch2_dev_resize_target(ca) > READ_ONCE(ca->mi.nbuckets); +} + +static inline bool bch2_ptr_bad_or_evacuating_rcu(struct bch_fs *c, const struct bch_extent_ptr *ptr) +{ + struct bch_dev *ca = bch2_dev_rcu_noerror(c, ptr->dev); + u64 resize_target; + + if (!ca || ca->mi.state == BCH_MEMBER_STATE_evacuating) + return true; + + resize_target = bch2_dev_resize_target(ca); + + return resize_target < READ_ONCE(ca->mi.nbuckets) && + ptr->offset >= resize_target * ca->mi.bucket_size; +} + +static inline bool bch2_ptr_bad_or_evacuating(struct bch_fs *c, const struct bch_extent_ptr *ptr) { guard(rcu)(); - return bch2_dev_bad_or_evacuating_rcu(c, dev); + return bch2_ptr_bad_or_evacuating_rcu(c, ptr); } + int bch2_dev_missing_bkey_msg(struct bch_fs *, struct bkey_s_c, unsigned, struct printbuf *out); int bch2_dev_missing_bkey(struct bch_fs *, struct bkey_s_c, unsigned); @@ -420,19 +453,21 @@ static inline struct bch_member_cpu bch2_mi_to_cpu(struct bch_member *mi) .first_bucket = le16_to_cpu(mi->first_bucket), .bucket_size = le16_to_cpu(mi->bucket_size), .group = BCH_MEMBER_GROUP(mi), + /* .failure_domain is interned in bch2_sb_members_to_cpu() */ .state = BCH_MEMBER_STATE(mi), .discard = BCH_MEMBER_DISCARD(mi), .data_allowed = BCH_MEMBER_DATA_ALLOWED(mi), .durability = BCH_MEMBER_DURABILITY(mi) ? BCH_MEMBER_DURABILITY(mi) - 1 : 1, - .freespace_initialized = BCH_MEMBER_FREESPACE_INITIALIZED(mi), + .freespace_initialized = BCH_MEMBER_FREESPACE_INITIALIZED(mi), .initialized = BCH_MEMBER_INITIALIZED(mi), .resize_on_mount = BCH_MEMBER_RESIZE_ON_MOUNT(mi), .rotational = BCH_MEMBER_ROTATIONAL(mi), .valid = bch2_member_alive(mi), .btree_bitmap_shift = mi->btree_bitmap_shift, .btree_allocated_bitmap = le64_to_cpu(mi->btree_allocated_bitmap), + .target_nbuckets = le64_to_cpu(mi->target_nbuckets), }; } diff --git a/fs/sb/members_format.h b/fs/sb/members_format.h index 3aa3003435..fd4147eb12 100644 --- a/fs/sb/members_format.h +++ b/fs/sb/members_format.h @@ -76,6 +76,16 @@ struct bch_member { __u8 device_model[64] __nonstring; __le64 flush_errors; __u8 device_serial[64] __nonstring; + /* + * Failure domain: devices sharing a (non-empty) string are in the same + * failure domain, and allocation spreads replicas - and, for erasure + * coding, requires stripe blocks - across domains. A flat, intrinsic + * device property with no relationship to the disk_groups label tree. + * Interned to a small id in memory (bch_member_cpu.failure_domain) for + * the allocation path. + */ + __u8 failure_domain[32] __nonstring; + __le64 target_nbuckets; /* 0 => idle, nbuckets => idle, < nbuckets => shrink target, > nbuckets => grow target */ }; /* @@ -105,6 +115,7 @@ LE64_BITMASK(BCH_MEMBER_RESIZE_ON_MOUNT,struct bch_member, flags, 31, 32) LE64_BITMASK(BCH_MEMBER_ROTATIONAL, struct bch_member, flags, 32, 33) LE64_BITMASK(BCH_MEMBER_ROTATIONAL_SET, struct bch_member, flags, 33, 34) LE64_BITMASK(BCH_MEMBER_INITIALIZED, struct bch_member, flags, 34, 38) +/* 38-46 free, was FAILURE_DOMAIN (now a string, member.failure_domain) */ #if 0 LE64_BITMASK(BCH_MEMBER_NR_READ_ERRORS, struct bch_member, flags[1], 0, 20); diff --git a/fs/sb/members_types.h b/fs/sb/members_types.h index c57fc9f379..d48ce65182 100644 --- a/fs/sb/members_types.h +++ b/fs/sb/members_types.h @@ -8,6 +8,7 @@ struct bch_member_cpu { u16 first_bucket; /* index of first bucket used */ u16 bucket_size; /* sectors */ u16 group; + u16 failure_domain; u8 state; u8 discard; u8 data_allowed; @@ -19,6 +20,7 @@ struct bch_member_cpu { u8 valid; u8 btree_bitmap_shift; u64 btree_allocated_bitmap; + u64 target_nbuckets; /* 0 => idle, nbuckets => idle, < nbuckets => shrink target, > nbuckets => grow target */ }; #endif /* _BCACHEFS_SB_MEMBERS_H */ diff --git a/fs/scripts/fetch-module.sh b/fs/scripts/fetch-module.sh index f84a40870c..f111b78e25 100755 --- a/fs/scripts/fetch-module.sh +++ b/fs/scripts/fetch-module.sh @@ -73,6 +73,7 @@ fall_back() [ -n "$dest" ] || fall_back "no destination path" command -v modinfo >/dev/null 2>&1 || fall_back "no modinfo to verify the module" command -v openssl >/dev/null 2>&1 || fall_back "no openssl to verify the module signature" +command -v xz >/dev/null 2>&1 || fall_back "no xz to decompress the module" # The signing CA (public root) is bundled next to this script; an env override # helps testing. Resolve it up front so we fail fast before downloading. @@ -208,9 +209,19 @@ work=$(mktemp -d) || fall_back "could not create a working directory" trap 'rm -rf "$work"' EXIT ko=$work/bcachefs.ko -echo "bcachefs: trying prebuilt module $url" >&2 -download "$url" "$ko" || +# The farm publishes xz-compressed (~6x: 6.6M of module is 1.1M on the wire), +# and only that - no uncompressed fallback. Nothing published before this is +# reachable anyway: the abbrev fix renames every snapshot, so the store gets +# republished wholesale. +# +# Compression is applied after signing, so it must be undone before anything +# reads the trailer - both verify_signature and the vermagic check below parse +# it. Decompress here and everything downstream sees a plain signed .ko. +echo "bcachefs: trying prebuilt module $url.xz" >&2 +download "$url.xz" "$ko.xz" || fall_back "not available for $distro/$arch/$pkgver bcachefs $ref" +xz -d -c -- "$ko.xz" >"$ko" || + fall_back "could not decompress $url.xz" # Authenticity gate: refuse anything not signed by the bcachefs key, so a bad # mirror or MITM can't get a module installed. (ABI gate — vermagic — follows.) diff --git a/fs/snapshots/check_snapshots.c b/fs/snapshots/check_snapshots.c index 09b5a54c20..8b1591cded 100644 --- a/fs/snapshots/check_snapshots.c +++ b/fs/snapshots/check_snapshots.c @@ -1,10 +1,39 @@ // SPDX-License-Identifier: GPL-2.0 +/* + * Snapshot fsck: the passes over the snapshots and snapshot_trees btrees. + * + * check_snapshot_trees: every tree key names a live root and master subvol. + * + * check_snapshots: per-node, in three stages - check_snapshot_state() + * recovers the state field itself; check_snapshot_deleted() checks a + * non-live state against the child snapshots, the subvolume and the + * accounting; then the topology checks (edges, tree pointer, depth, + * skiplists, subvol backref). + * + * reconstruct_snapshots: rebuild missing snapshot nodes from the keys + * that reference them. + * + * __bch2_check_key_has_snapshot: per-key repair for keys whose snapshot + * node is missing or dead; also called from runtime paths. + * + * Repair philosophy: enumerate which writers can produce a state before + * repairing it. Unconstructible combinations are rejected at commit + * (bch2_snapshot_validate()); real damage is repaired toward the side + * the rest of the metadata agrees with - child snapshots, the subvolume + * (deletion tombstones it in the same transaction that condemns its + * snapshot), the per-snapshot accounting (nothing we write deletes a + * node with data). Ambiguity fail-stops rather than guessing. + */ #include "bcachefs.h" #include "alloc/accounting.h" #include "btree/cache.h" #include "btree/update.h" +#include "btree/write_buffer.h" + +#include "fs/check.h" +#include "fs/inode.h" #include "snapshots/snapshot.h" #include "snapshots/subvolume.h" @@ -95,6 +124,8 @@ static int bch2_snapshot_tree_master_subvol(struct btree_trans *trans, return 0; } +/* check_snapshot_trees: */ + static int check_snapshot_tree(struct btree_trans *trans, struct btree_iter *iter, struct bkey_s_c k) @@ -139,12 +170,27 @@ static int check_snapshot_tree(struct btree_trans *trans, if (ret && !bch2_err_matches(ret, ENOENT)) return ret; - if (fsck_err_on(ret, + /* + * A missing subvolume is what we're checking for, not a failure to + * check - so keep it as a fact and clear ret. Left in ret it leaks out + * of the pass whenever the repair below is declined: the fsck_err_on() + * chain short-circuits (the later arms test !ret), nothing overwrites + * ret, and "fsck_err: return ret" hands back the lookup's errcode - + * ENOENT_bkey_type_mismatch, because the subvolume slot holds a deleted + * key. That failed the whole pass with an errcode about key types. + * + * It only shows when the repair is declined; applying it overwrites ret + * below. + */ + bool subvol_missing = ret != 0; + ret = 0; + + if (fsck_err_on(subvol_missing, trans, snapshot_tree_to_missing_subvol, "snapshot tree points to missing subvolume:\n%s", (printbuf_reset(&buf), bch2_bkey_val_to_text(&buf, c, st.s_c), buf.buf)) || - fsck_err_on(!ret && + fsck_err_on(!subvol_missing && !bch2_snapshot_is_ancestor(trans, le32_to_cpu(subvol.snapshot), root_id), @@ -152,7 +198,7 @@ static int check_snapshot_tree(struct btree_trans *trans, "snapshot tree points to subvolume that does not point to snapshot in this tree:\n%s", (printbuf_reset(&buf), bch2_bkey_val_to_text(&buf, c, st.s_c), buf.buf)) || - fsck_err_on(!ret && BCH_SUBVOLUME_SNAP(&subvol), + fsck_err_on(!subvol_missing && BCH_SUBVOLUME_SNAP(&subvol), trans, snapshot_tree_to_snapshot_subvol, "snapshot tree points to snapshot subvolume:\n%s", (printbuf_reset(&buf), @@ -198,6 +244,8 @@ int bch2_check_snapshot_trees(struct bch_fs *c) * Look up snapshot tree for @tree_id and find root, * make sure @snap_id is a descendent: */ +/* check_snapshots: */ + static int snapshot_tree_ptr_good(struct btree_trans *trans, u32 snap_id, u32 tree_id) { @@ -271,6 +319,24 @@ static int snapshot_tree_ptr_repair(struct btree_trans *trans, return 0; } +/* Find a subvolume claiming snapshot @id, to restore a wiped backref: */ +static int subvol_claiming_snapshot(struct btree_trans *trans, u32 id, + u32 *subvol_id) +{ + struct bkey_s_c k; + int ret; + + for_each_btree_key_norestart(trans, iter, BTREE_ID_subvolumes, POS_MIN, + 0, k, ret) + if (k.k->type == KEY_TYPE_subvolume && + le32_to_cpu(bkey_s_c_to_subvolume(k).v->snapshot) == id) { + *subvol_id = k.k->p.offset; + break; + } + + return ret; +} + static int check_snapshot_to_subvol(struct btree_trans *trans, struct btree_iter *iter, struct bkey_s_c k, @@ -285,51 +351,126 @@ static int check_snapshot_to_subvol(struct btree_trans *trans, bch2_snapshot_state(s) == SNAPSHOT_STATE_will_delete); if (s->subvol) { - /* dangling snapshot will be handled later */ u32 id = le32_to_cpu(s->subvol); - struct bch_subvolume subvol; - int ret = bch2_subvolume_get(trans, id, false, &subvol); - if (bch2_err_matches(ret, ENOENT)) { - bch_err(c, "snapshot points to nonexistent subvolume:\n %s", - (bch2_bkey_val_to_text(&buf, c, k), buf.buf)); - return 0; - } - if (ret) + /* + * Raw read: bch2_subvolume_get() reports deleted subvolumes + * as ENOENT, and the message should show what's actually + * there: + */ + CLASS(btree_iter, subvol_iter)(trans, BTREE_ID_subvolumes, POS(0, id), 0); + struct bkey_s_c_subvolume subvol_k = bch2_bkey_get_typed(&subvol_iter, subvolume); + int ret = bkey_err(subvol_k); + if (ret && !bch2_err_matches(ret, ENOENT)) return ret; - if (bch2_subvolume_state_compat(&subvol) == SUBVOLUME_STATE_live) { - /* - * A live subvolume that doesn't point back isn't this - * leaf's owner - the leaf needs its own subvolume - * created, which we can't do yet: - */ - if (le32_to_cpu(subvol.snapshot) != k.k->p.offset) { - CLASS(bch_log_msg, msg)(c); + struct bch_subvolume subvol = {}; + if (!ret) + bkey_val_copy_pad(&subvol, subvol_k); - prt_printf(&msg.m, "snapshot points to live subvolume %u, which points to snapshot %u:\n", - id, le32_to_cpu(subvol.snapshot)); - bch2_bkey_val_to_text(&msg.m, c, k); - msg.m.suppress = !bch2_count_fsck_err(c, snapshot_subvol_backref_wrong, &msg.m); + bool snap_deleting = bch2_snapshot_state(s) == SNAPSHOT_STATE_will_delete; + bool subvol_deleted = !ret && + bch2_subvolume_state_compat(&subvol) == SUBVOLUME_STATE_deleted; + bool points_back = !ret && + le32_to_cpu(subvol.snapshot) == k.k->p.offset; - return bch_err_throw(c, fsck_repair_unimplemented); - } + /* + * A missing subvolume can be rebuilt from right here, and only + * from here: this snapshot names it, and a snapshot carrying a + * subvol backref is a leaf - which is what + * bch2_reconstruct_subvol() needs and what its other callers + * can't promise, since an inode's or dirent's snapshot may be + * interior. Left to them, a subvolume whose key was lost after + * it had been snapshotted was never reconstructed at all. + * + * Not while the snapshot is deleting, though: there the missing + * subvolume is a tombstoned deletion in flight, and rebuilding + * it would revert it. + */ + if (ret && !snap_deleting) { + /* id is the subvolume being rebuilt; the snapshot is k */ + int recon_ret = bch2_reconstruct_subvol(trans, + k.k->p.offset, id, 0); + if (recon_ret && + !bch2_err_matches(recon_ret, BCH_ERR_fsck_repair_unimplemented)) + return recon_ret; + if (!recon_ret) + return 0; + /* couldn't find a root inode for it - fall through and report */ + } + if (ret || !points_back) { /* - * Deletion tombstones the subvolume in the same - * transaction that marks the leaf will_delete, so - * will_delete with a live owner pointing back means - * the node's state is what's wrong: + * Wrong backref, or a missing subvolume we couldn't + * rebuild: repair needs the subvolume side validated + * first - it belongs to the dedicated pass after + * check_subvols. Report only; an error return here + * would regress mounts of filesystems mid-deletion: */ - if (ret_fsck_err_on(bch2_snapshot_state(s) == SNAPSHOT_STATE_will_delete, - trans, snapshot_will_delete_but_subvol_live, - "snapshot marked will_delete but its subvolume is live - resurrecting:\n%s", - (bch2_bkey_val_to_text(&buf, c, k), buf.buf))) { - u = u ?: errptr_try(bch2_bkey_make_mut_typed(trans, iter, &k, 0, snapshot)); - - bch2_snapshot_state_set(&u->v, SNAPSHOT_STATE_live); - *s = u->v; + CLASS(bch_log_msg, msg)(c); + + if (ret) + prt_printf(&msg.m, "snapshot points to missing subvolume %u:\n", id); + else + prt_printf(&msg.m, "snapshot's subvolume doesn't point back at it:\n"); + bch2_bkey_val_to_text(&msg.m, c, k); + if (!ret) { + prt_newline(&msg.m); + bch2_bkey_val_to_text(&msg.m, c, subvol_k.s_c); } + msg.m.suppress = !bch2_count_fsck_err(c, snapshot_subvol_backref_wrong, &msg.m); + return 0; + } + + /* + * The deletion machinery couples exactly one bit on each + * side: a snapshot is will_delete iff its subvolume is + * tombstoned (live vs unlinked is the subvolume's own + * user-visibility business, invisible to the snapshot). + * With the edge intact, a state mismatch repairs in one + * direction only: the subvolume implies the snapshot state + * exactly, while the reverse would have to guess between + * live and unlinked. + */ + if (ret_fsck_err_on(snap_deleting != subvol_deleted, + trans, snapshot_subvol_state_mismatch, + "snapshot %s but its subvolume is %s:\n%s", + snap_deleting ? "will_delete" : "live", + subvol_deleted ? "deleted" : "not deleted", + (printbuf_reset(&buf), + bch2_bkey_val_to_text(&buf, c, k), + prt_newline(&buf), + bch2_bkey_val_to_text(&buf, c, subvol_k.s_c), + buf.buf))) { + u = u ?: errptr_try(bch2_bkey_make_mut_typed(trans, iter, &k, 0, snapshot)); + bch2_snapshot_state_set(&u->v, + subvol_deleted + ? SNAPSHOT_STATE_will_delete + : SNAPSHOT_STATE_live); + *s = u->v; + } + } else if (should_have_subvol && + bch2_snapshot_state(s) == SNAPSHOT_STATE_live) { + /* + * A live leaf with no backref: a subvolume still pointing at + * it means the backref was wiped - restore it. (A second + * claimant, if damage minted one, still hits check_subvols' + * doesn't-point-back fail-stop.) No claimant is an orphan + * leaf, whose repair (creating a subvolume) is + * unimplemented, as above. + */ + u32 subvol_id = 0; + try(subvol_claiming_snapshot(trans, k.k->p.offset, &subvol_id)); + + if (subvol_id && + ret_fsck_err(trans, snapshot_subvol_backref_wrong, + "snapshot leaf missing subvol backref, subvolume %u points at it - restoring:\n%s", + subvol_id, + (bch2_bkey_val_to_text(&buf, c, k), buf.buf))) { + u = u ?: errptr_try(bch2_bkey_make_mut_typed(trans, iter, &k, 0, snapshot)); + u->v.subvol = cpu_to_le32(subvol_id); + SET_BCH_SNAPSHOT_SUBVOL_OBSOLETE(&u->v, true); + *s = u->v; } } @@ -348,14 +489,35 @@ static int check_snapshot_to_subvol(struct btree_trans *trans, *s = u->v; } - if (ret_fsck_err_on(BCH_SNAPSHOT_SUBVOL_OBSOLETE(s) != (s->subvol != 0), - trans, snapshot_subvol_flag_wrong, - "snapshot node %llu has wrong subvol flag", - k.k->p.offset)) { - u = u ?: errptr_try(bch2_bkey_make_mut_typed(trans, iter, &k, 0, snapshot)); + /* + * Live nodes only: the _OBSOLETE flags are old-format compat bits, + * and bch2_snapshot_state_set() clears SUBVOL_OBSOLETE for every + * non-live state even when the subvol backref is retained (a + * will_delete leaf keeps it; deletion checks it) - old kernels must + * not read a dying snapshot as a live subvolume leaf: + */ + if (bch2_snapshot_state(s) == SNAPSHOT_STATE_live && + BCH_SNAPSHOT_SUBVOL_OBSOLETE(s) != (s->subvol != 0)) { + printbuf_reset(&buf); + prt_printf(&buf, "snapshot node %llu has wrong subvol flag:\n", + k.k->p.offset); + bch2_bkey_val_to_text(&buf, c, k); - SET_BCH_SNAPSHOT_SUBVOL_OBSOLETE(&u->v, s->subvol != 0); - *s = u->v; + if (s->subvol) { + CLASS(btree_iter, subvol_iter)(trans, BTREE_ID_subvolumes, + POS(0, le32_to_cpu(s->subvol)), 0); + struct bkey_s_c subvol_k = bkey_try(bch2_btree_iter_peek_slot(&subvol_iter)); + + prt_newline(&buf); + bch2_bkey_val_to_text(&buf, c, subvol_k); + } + + if (ret_fsck_err(trans, snapshot_subvol_flag_wrong, "%s", buf.buf)) { + u = u ?: errptr_try(bch2_bkey_make_mut_typed(trans, iter, &k, 0, snapshot)); + + SET_BCH_SNAPSHOT_SUBVOL_OBSOLETE(&u->v, s->subvol != 0); + *s = u->v; + } } return 0; @@ -364,12 +526,12 @@ static int check_snapshot_to_subvol(struct btree_trans *trans, /* * Parent <-> child edge checks and repair. * - * An edge is repaired only when doubly attested: the surviving pointer plus - * corroboration (id ordering, tree, depth - checked before the depth/skip - * autofixes rewrite them). Ambiguous evidence fail-stops; a wrong join or - * split moves keys between subvolume visibilities. Never write "I don't - * know" to disk: a node with a zeroed parent masquerades as a tree root and - * gets consumed by the tree-pointer repair or the deletion machinery. + * An edge is repaired only if the surviving pointer and the two nodes' id + * ordering, tree and depth all agree (those are checked before the depth/skip + * autofixes rewrite them). If they don't, fail-stop: a wrong join or split + * moves keys between subvolume visibilities. Never write "I don't know" to + * disk: a node with a zeroed parent masquerades as a tree root and gets + * consumed by the tree-pointer repair or the deletion machinery. * Repairs commit and restart, so decisions only see settled state. The * in-memory snapshot table serves as the reverse index (live nodes only: * a tombstone's child pointer is a splice breadcrumb, not a claim - I1). @@ -377,6 +539,8 @@ static int check_snapshot_to_subvol(struct btree_trans *trans, enum { EDGE_PARENT, EDGE_CHILD }; +/* snapshot edge repair: */ + static bool snapshot_node_points_back(const struct bch_snapshot *s, unsigned side, u32 other) { return side == EDGE_PARENT @@ -421,17 +585,40 @@ static u32 snapshot_table_find_edge(struct bch_fs *c, const struct bch_snapshot return found; } -static u64 snapshot_data_sectors(struct bch_fs *c, u32 id) +/* + * Does snapshot @id own anything at all? + * + * Any nonzero counter in any snapshotted btree says yes - keys, their bytes, + * or sectors. Only the existence of evidence matters here, not what it means, + * so there's nothing to version gate: a filesystem from before the per-btree + * key counts still accounts sectors, and on one that has them a snapshot + * holding only dirents or xattrs shows up in nr_keys where sectors alone would + * read as empty. + * + * In-memory read: current as of the last applied delta, so unlike a btree read + * it needs no write buffer flush to be trustworthy. + */ +static bool snapshot_has_accounting(struct bch_fs *c, u32 id) { - struct disk_accounting_pos acc; - memset(&acc, 0, sizeof(acc)); - acc.type = BCH_DISK_ACCOUNTING_snapshot; - acc.snapshot.id = id; - - /* btree 0 (extents, the default) is the only one with external_sectors (counter 2) */ - u64 v[3] = {}; - bch2_accounting_mem_read(c, disk_accounting_pos_to_bpos(&acc), v, ARRAY_SIZE(v)); - return v[2]; + for (unsigned btree = 0; btree < BTREE_ID_NR; btree++) { + if (!btree_type_has_snapshots(btree)) + continue; + + struct disk_accounting_pos acc; + memset(&acc, 0, sizeof(acc)); + acc.type = BCH_DISK_ACCOUNTING_snapshot; + acc.snapshot.id = id; + acc.snapshot.btree = btree; + + u64 v[3] = {}; + bch2_accounting_mem_read(c, disk_accounting_pos_to_bpos(&acc), v, ARRAY_SIZE(v)); + + for (unsigned i = 0; i < ARRAY_SIZE(v); i++) + if (v[i]) + return true; + } + + return false; } static bool snapshot_parent_child_consistent(const struct bch_snapshot *s, u32 id, unsigned side, @@ -448,10 +635,40 @@ static bool snapshot_parent_child_consistent(const struct bch_snapshot *s, u32 i } /* - * Does @n (in role @side) have a pointer position that's empty, or whose - * current target doesn't reciprocate? Returns the displaced value in - * @old_id; empty positions are preferred, so a refuted value keeps its shot - * at repair via its own scan: + * Look up a snapshot node that fsck has no right to assume exists. + * + * A missing node is a fact about the filesystem here, not an error, so it + * comes back in @found - and the key comes back whole, because the topology + * checks report on nodes they didn't start from, and naming one by id alone + * leaves a field report with no way to see what was wrong with it. + * + * bch2_snapshot_lookup{,_key}() throw ENOENT_bkey_type_mismatch instead, which + * is right for callers entitled to assume the node is there and wrong for + * every caller in this file: each one has to launder the errcode back into a + * boolean, and check_snapshot_edge() then returned the value it had just + * decided was benign as the pass's error - taking recovery emergency + * read-only over a filesystem whose only problem was a dangling child + * pointer. Absence reported as a value can't be returned by mistake. + */ +static int snapshot_lookup_key_absent_ok(struct btree_trans *trans, u32 id, + struct bkey_i_snapshot *k, bool *found) +{ + int ret = bch2_snapshot_lookup_key(trans, id, k); + + if (bch2_err_matches(ret, ENOENT)) { + *found = false; + return 0; + } + + *found = !ret; + return ret; +} + +/* + * Does @n (in role @side) have a pointer slot that's empty, or whose current + * target doesn't reciprocate? Returns the displaced value in @old_id. Empty + * slots are checked first, so a stale pointer keeps its own shot at repair + * when its node is scanned: */ static int snapshot_edge_ptr_available(struct btree_trans *trans, const struct bch_snapshot *n, u32 n_id, @@ -476,12 +693,11 @@ static int snapshot_edge_ptr_available(struct btree_trans *trans, } for (unsigned i = 0; i < nr; i++) { - struct bch_snapshot t; - int ret = bch2_snapshot_lookup(trans, ptrs[i], &t); - if (ret && !bch2_err_matches(ret, ENOENT)) - return ret; + struct bkey_i_snapshot t; + bool exists; + try(snapshot_lookup_key_absent_ok(trans, ptrs[i], &t, &exists)); - if (ret || !snapshot_node_points_back(&t, !side, n_id)) { + if (!exists || !snapshot_node_points_back(&t.v, !side, n_id)) { *old_id = ptrs[i]; return 1; } @@ -490,6 +706,24 @@ static int snapshot_edge_ptr_available(struct btree_trans *trans, return 0; } +/* + * Put a node the accounting says is alive back into the tree. + * + * Two children means nothing ever spliced this node out: the structure is + * intact and only the state field is wrong, so setting it live is the whole + * repair. bch2_snapshot_node_undelete() is for undoing a splice, and rejects + * that shape outright. + */ +static int snapshot_undelete_owns_data(struct btree_trans *trans, struct bkey_i_snapshot *u) +{ + if (u->v.children[1]) { + bch2_snapshot_state_set(&u->v, SNAPSHOT_STATE_live); + return 0; + } + + return bch2_snapshot_node_undelete(trans, u); +} + static int snapshot_edge_repair_commit(struct btree_trans *trans) { try(bch2_trans_commit(trans, NULL, NULL, BCH_TRANS_COMMIT_no_enospc)); @@ -497,6 +731,62 @@ static int snapshot_edge_repair_commit(struct btree_trans *trans) return bch_err_throw(trans->c, transaction_restart_nested); } +/* + * Put back a child node that isn't there at all. + * + * Same argument as undeleting a tombstone that still owns data, one step + * further along: nothing we write removes a snapshot node with keys still + * accounted to it, so a node that's missing while its keys are not is a node + * that was destroyed, not deleted. Its keys are still on disk and still + * reachable from every view that inherits from it - only the node naming that + * view is gone. Recreate it, and they stay reachable. + * + * A leaf, because that's the shape we can justify: @parent_id names it as a + * child, so parent, tree, depth and skiplists all follow from a node we can + * see, and nothing attests to any children of its own. If it did have + * descendants, their own parent pointers bring them back on a later pass + * through the same edge check. + * + * The subvolume, if one claims this id, comes back with it: a subvolume whose + * snapshot went missing is exactly what a resurrected leaf should carry, and + * zeroing it would strand the subvolume instead. + */ +static int snapshot_resurrect_child(struct btree_trans *trans, u32 parent_id, u32 id) +{ + struct bch_fs *c = trans->c; + + struct bkey_i_snapshot parent; + bool parent_exists; + try(snapshot_lookup_key_absent_ok(trans, parent_id, &parent, &parent_exists)); + if (!parent_exists) + return bch_err_throw(c, EINVAL_snapshot_edge_to_missing_node); + + struct bkey_i_snapshot *n = bch2_trans_kmalloc(trans, sizeof(*n)); + try(PTR_ERR_OR_ZERO(n)); + + bkey_snapshot_init(&n->k_i); + n->k.p = POS(0, id); + n->v.parent = cpu_to_le32(parent_id); + n->v.tree = parent.v.tree; + n->v.depth = cpu_to_le32(bch2_snapshot_depth(c, parent_id)); + n->v.btime.lo = cpu_to_le64(bch2_current_time(c)); + + for (unsigned i = 0; i < ARRAY_SIZE(n->v.skip); i++) + n->v.skip[i] = cpu_to_le32(bch2_snapshot_skiplist_get(c, parent_id)); + bubble_sort(n->v.skip, ARRAY_SIZE(n->v.skip), cmp_le32); + + u32 subvol_id = 0; + try(subvol_claiming_snapshot(trans, id, &subvol_id)); + n->v.subvol = cpu_to_le32(subvol_id); + + bch2_snapshot_state_set(&n->v, SNAPSHOT_STATE_live); + + try(bch2_snapshot_table_make_room(c, id)); + try(bch2_btree_insert_trans(trans, BTREE_ID_snapshots, &n->k_i, 0)); + + return snapshot_edge_repair_commit(trans); +} + /* Rewrite @node_id's reference to @old_id (0 clears a child slot): */ static int snapshot_edge_set_ptr(struct btree_trans *trans, u32 node_id, unsigned side, u32 old_id, u32 new_id) @@ -521,71 +811,206 @@ static int snapshot_edge_set_ptr(struct btree_trans *trans, u32 node_id, return snapshot_edge_repair_commit(trans); } +/* + * Name the nodes an edge repair is between, keys and all. Which pointer is + * wrong is only decidable from parent/children/tree/depth across both sides, + * so a message naming them by id reports the conclusion and none of the + * evidence - and a field report is whatever the message printed. + */ +static const char *edge_nodes_to_text(struct printbuf *out, struct bch_fs *c, + struct bkey_s_c node, + struct bkey_i_snapshot *target, + struct bkey_i_snapshot *claimant) +{ + prt_str(out, "\nnode: "); + bch2_bkey_val_to_text(out, c, node); + + if (target) { + prt_str(out, "\ntarget: "); + bch2_bkey_val_to_text(out, c, bkey_i_to_s_c(&target->k_i)); + } + + if (claimant) { + prt_str(out, "\nclaimant: "); + bch2_bkey_val_to_text(out, c, bkey_i_to_s_c(&claimant->k_i)); + } + + return out->buf; +} + static int check_snapshot_edge(struct btree_trans *trans, - const struct bch_snapshot *s, u32 id, + struct bkey_s_c k, const struct bch_snapshot *s, unsigned side, u32 other_id) { struct bch_fs *c = trans->c; + u32 id = k.k->p.offset; + CLASS(printbuf, buf)(); + + struct bkey_i_snapshot other; + bool other_exists; + try(snapshot_lookup_key_absent_ok(trans, other_id, &other, &other_exists)); - struct bch_snapshot other; - int other_ret = bch2_snapshot_lookup(trans, other_id, &other); - if (other_ret && !bch2_err_matches(other_ret, ENOENT)) - return other_ret; - bool other_exists = !other_ret; + /* + * Connectivity: the live tree must be closed over not-deleted nodes. + * A deleted target is history - an interrupted deletion left our edge + * pointing into it - so rewrite our own edge past it: parent edges + * walk up the tombstone's retained parent chain, child edges walk + * down retained children, to the nearest not-deleted node (or + * nothing, if that direction is all dead). The tombstone itself is + * untouched; depth/skiplist fallout is repaired by the checks + * downstream. + * + * Only for a tombstone that owns no data - see below. We cannot lean on + * check_snapshot_deleted() having already adjudicated the target: the + * walk is reverse from POS_MAX and snapshot ids descend from the root, + * so a parent always reaches a deleted child's edge before that child + * is visited at all. + */ + if (other_exists && + bch2_snapshot_state_compat(&other.v) == SNAPSHOT_STATE_deleted) { + /* + * Data is definitive: nothing we write deletes a node with keys + * still accounted to it, so a deleted node that still owns data + * has a state field that lies, and routing the tree around it + * strands those keys. Undelete it and leave our edge alone - the + * node's own visit validates the result. + * + * The check belongs here and not only in check_snapshot_deleted(): + * bch2_check_snapshots_trans() walks in reverse from POS_MAX and + * snapshot ids descend from the root, so a parent always reaches + * a deleted child's edge before that child is ever visited. The + * splice below used to assume the reverse. + */ + u64 keys, sectors; + try(bch2_snapshot_accounting_totals(c, other_id, &keys, §ors, NULL, NULL)); + + if (keys || sectors) { + if (ret_fsck_err(trans, snapshot_deleted_but_has_data, + "snapshot %u %s pointer %u is deleted but has %llu keys, %llu sectors accounted - undeleting rather than splicing past it:%s", + id, side == EDGE_CHILD ? "parent" : "child", + other_id, keys, sectors, + (printbuf_reset(&buf), + edge_nodes_to_text(&buf, c, k, &other, NULL)))) { + struct bkey_i_snapshot *n = + errptr_try(bch2_bkey_get_mut_typed(trans, BTREE_ID_snapshots, + POS(0, other_id), 0, snapshot)); + try(snapshot_undelete_owns_data(trans, n)); + return snapshot_edge_repair_commit(trans); + } + return 0; + } + + u32 repl = other_id; + struct bkey_i_snapshot t = other; + + for (unsigned iters = 0; ; iters++) { + if (iters > BTREE_MAX_DEPTH * 64) /* damaged chain, cycle? don't guess */ + return 0; + + repl = le32_to_cpu(side == EDGE_CHILD ? t.v.parent : t.v.children[0]); + if (!repl) + break; - if (other_exists && snapshot_node_points_back(&other, !side, id)) + bool repl_exists; + try(snapshot_lookup_key_absent_ok(trans, repl, &t, &repl_exists)); + if (!repl_exists) { + repl = 0; + break; + } + + if (bch2_snapshot_state_compat(&t.v) != SNAPSHOT_STATE_deleted) + break; + } + + if (ret_fsck_err(trans, snapshot_deleted_but_linked, + "snapshot %u %s pointer %u is a deleted node - %s %u%s", + id, side == EDGE_CHILD ? "parent" : "child", other_id, + repl ? "re-linking past it to" : "clearing, dead in that direction:", + repl, + (printbuf_reset(&buf), + edge_nodes_to_text(&buf, c, k, &other, NULL)))) + return snapshot_edge_set_ptr(trans, id, side, other_id, repl); + return 0; + } + + if (other_exists && snapshot_node_points_back(&other.v, !side, id)) return 0; /* - * Our claim completes the edge if the target's position toward us is - * empty or refuted - but never un-tombstone a node: + * Our pointer completes the edge if the target's slot toward us is + * empty or holds a stale pointer - but never un-tombstone a node: */ if (other_exists && - bch2_snapshot_state_compat(&other) != SNAPSHOT_STATE_deleted && - snapshot_parent_child_consistent(s, id, side, &other, other_id)) { + bch2_snapshot_state_compat(&other.v) != SNAPSHOT_STATE_deleted && + snapshot_parent_child_consistent(s, id, side, &other.v, other_id)) { u32 old = 0; - int avail = snapshot_edge_ptr_available(trans, &other, other_id, !side, &old); + int avail = snapshot_edge_ptr_available(trans, &other.v, other_id, !side, &old); if (avail < 0) return avail; if (avail && ret_fsck_err(trans, snapshot_edge_bad, "snapshot %u %s pointer %u is not reciprocated, but is corroborated by\n" - "tree and depth and the target's position (%u) is unattested - completing the edge", - id, side == EDGE_CHILD ? "parent" : "child", other_id, old)) + "tree and depth and the target's position (%u) is unattested - completing the edge%s", + id, side == EDGE_CHILD ? "parent" : "child", other_id, old, + (printbuf_reset(&buf), + edge_nodes_to_text(&buf, c, k, &other, NULL)))) return snapshot_edge_set_ptr(trans, other_id, !side, old, id); } - /* Or a corroborated claimant is the true counterpart - re-aim ours: */ + /* Or another node claims the edge and tree and depth agree - re-aim ours: */ u32 repl = snapshot_table_find_edge(c, s, id, !side); - struct bch_snapshot r; - int repl_ret = repl ? bch2_snapshot_lookup(trans, repl, &r) : -ENOENT; - if (repl_ret && !bch2_err_matches(repl_ret, ENOENT)) - return repl_ret; + struct bkey_i_snapshot r; + bool repl_exists = false; + if (repl) + try(snapshot_lookup_key_absent_ok(trans, repl, &r, &repl_exists)); - if (!repl_ret && - snapshot_parent_child_consistent(s, id, side, &r, repl) && + if (repl_exists && + snapshot_parent_child_consistent(s, id, side, &r.v, repl) && ret_fsck_err(trans, snapshot_edge_bad, "snapshot %u %s pointer %u is broken (target %s), but node %u claims the\n" - "edge, corroborated by tree and depth - repairing", + "edge, corroborated by tree and depth - repairing%s", id, side == EDGE_CHILD ? "parent" : "child", other_id, other_exists ? "does not reciprocate" : "does not exist", - repl)) + repl, + (printbuf_reset(&buf), + edge_nodes_to_text(&buf, c, k, + other_exists ? &other : NULL, &r)))) return snapshot_edge_set_ptr(trans, id, side, other_id, repl); - /* A dangling child pointer with no data accounted to it may be cleared: */ + /* + * A child pointer naming a node that isn't there. The accounting says + * which way to go: keys accounted to it mean the node was destroyed + * rather than deleted, and putting it back is what keeps them + * reachable. Nothing accounted means there's nothing to lose, and + * clearing is the smaller repair - which also means a garbage child id + * gets cleared instead of conjuring a snapshot out of one stomped + * field. + */ if (side == EDGE_PARENT && !other_exists) { u32 sibling = le32_to_cpu(s->children[0]) == other_id ? le32_to_cpu(s->children[1]) : le32_to_cpu(s->children[0]); - u64 sectors = snapshot_data_sectors(c, other_id); - if (!sectors && sibling && + if (snapshot_has_accounting(c, other_id)) { + if (ret_fsck_err(trans, snapshot_child_missing_but_accounted, + "snapshot %u child pointer %u does not exist, but keys are\n" + "accounted to %u - recreating it as a leaf so they stay reachable%s", + id, other_id, other_id, + (printbuf_reset(&buf), + edge_nodes_to_text(&buf, c, k, NULL, NULL)))) + return snapshot_resurrect_child(trans, id, other_id); + return 0; + } + + if (sibling && ret_fsck_err(trans, snapshot_edge_bad, "snapshot %u child pointer %u does not exist: nothing claims %u as\n" - "parent and no data is accounted to it - clearing", - id, other_id, id)) + "parent and nothing is accounted to it - clearing%s", + id, other_id, id, + (printbuf_reset(&buf), + edge_nodes_to_text(&buf, c, k, NULL, NULL)))) return snapshot_edge_set_ptr(trans, id, side, other_id, 0); } @@ -597,7 +1022,7 @@ static int check_snapshot_edge(struct btree_trans *trans, * than attempt topology surgery on a conjunction of corruptions: */ { - CLASS(printbuf, buf)(); + printbuf_reset(&buf); prt_printf(&buf, "snapshot topology damage is beyond single-corruption repair:\n" "node %u's %s pointer names %u, which %s\n", id, side == EDGE_CHILD ? "parent" : "child", other_id, @@ -605,24 +1030,16 @@ static int check_snapshot_edge(struct btree_trans *trans, ? "exists but does not point back, and tree/depth do not identify them as parent and child" : "does not exist"); - prt_printf(&buf, "no other node passes the parent/child consistency checks for this edge\n"); + prt_printf(&buf, "no other node passes the parent/child consistency checks for this edge"); - prt_printf(&buf, "node: "); - bch2_snapshot_to_text(&buf, s); - prt_newline(&buf); + edge_nodes_to_text(&buf, c, k, other_exists ? &other : NULL, NULL); - if (other_exists) { - prt_printf(&buf, "target: "); - bch2_snapshot_to_text(&buf, &other); - prt_newline(&buf); - } - - prt_printf(&buf, "not repairing: run fsck; if damage is extensive, reconstruct_snapshots rebuilds topology from key evidence"); + prt_printf(&buf, "\nnot repairing: run fsck; if damage is extensive, reconstruct_snapshots rebuilds topology from key evidence"); bch_err(c, "%s", buf.buf); } if (!other_exists) - return other_ret; + return bch_err_throw(c, EINVAL_snapshot_edge_to_missing_node); return side == EDGE_CHILD ? bch_err_throw(c, EINVAL_snapshot_parent_missing_child_ptr) @@ -650,11 +1067,10 @@ static int snapshot_referenced(struct btree_trans *trans, } if (s->parent) { - struct bch_snapshot p; - int ret = bch2_snapshot_lookup(trans, le32_to_cpu(s->parent), &p); - if (ret && !bch2_err_matches(ret, ENOENT)) - return ret; - if (!ret && snapshot_node_points_back(&p, EDGE_PARENT, id)) + struct bkey_i_snapshot p; + bool exists; + try(snapshot_lookup_key_absent_ok(trans, le32_to_cpu(s->parent), &p, &exists)); + if (exists && snapshot_node_points_back(&p.v, EDGE_PARENT, id)) return 0; } @@ -662,11 +1078,10 @@ static int snapshot_referenced(struct btree_trans *trans, if (!s->children[i]) continue; - struct bch_snapshot ch; - int ret = bch2_snapshot_lookup(trans, le32_to_cpu(s->children[i]), &ch); - if (ret && !bch2_err_matches(ret, ENOENT)) - return ret; - if (!ret && snapshot_node_points_back(&ch, EDGE_CHILD, id)) + struct bkey_i_snapshot ch; + bool exists; + try(snapshot_lookup_key_absent_ok(trans, le32_to_cpu(s->children[i]), &ch, &exists)); + if (exists && snapshot_node_points_back(&ch.v, EDGE_CHILD, id)) return 0; } @@ -674,20 +1089,19 @@ static int snapshot_referenced(struct btree_trans *trans, return 0; } -static int check_snapshot(struct btree_trans *trans, - struct btree_iter *iter, - struct bkey_s_c k) +/* + * Recover the state field itself: stamp it from the legacy flags when + * unset, decode a corrupted value back to the nearest codeword, and + * correct a state left stale by a legacy flags-only tombstone. + */ +static int check_snapshot_state(struct btree_trans *trans, + struct btree_iter *iter, + struct bkey_s_c k, + struct bch_snapshot *s, + struct bkey_i_snapshot **u) { struct bch_fs *c = trans->c; CLASS(printbuf, buf)(); - struct bkey_i_snapshot *u = NULL; - int ret = 0; - - if (k.k->type != KEY_TYPE_snapshot) - return 0; - - struct bch_snapshot s; - bkey_val_copy_pad(&s, bkey_s_c_to_snapshot(k)); /* * A zero state field means the key predates the state field, or was @@ -698,16 +1112,16 @@ static int check_snapshot(struct btree_trans *trans, * ran) heals too. Mid-upgrade this is the expected migration and silent; * post-upgrade an unset state is unexpected, so surface it (autofix). */ - if (!bch2_snapshot_state(&s)) { + if (!bch2_snapshot_state(s)) { bool upgrading = c->sb.version_upgrade_complete < bcachefs_metadata_version_per_dev_fragmentation_lru; if (upgrading || ret_fsck_err(trans, snapshot_state_bad, "snapshot state unset, recovering from legacy flags:\n%s", (bch2_bkey_val_to_text(&buf, c, k), buf.buf))) { - u = u ?: errptr_try(bch2_bkey_make_mut_typed(trans, iter, &k, 0, snapshot)); - u->v.state = cpu_to_le32(bch2_snapshot_state_from_flags(&s)); - s = u->v; + *u = *u ?: errptr_try(bch2_bkey_make_mut_typed(trans, iter, &k, 0, snapshot)); + (*u)->v.state = cpu_to_le32(bch2_snapshot_state_from_flags(s)); + *s = (*u)->v; } } @@ -717,10 +1131,10 @@ static int check_snapshot(struct btree_trans *trans, * is corruption. No repair yet, and state-keyed repairs must not run * on a state we can't read: */ - if (!bch2_snapshot_state_valid(bch2_snapshot_state(&s))) { + if (!bch2_snapshot_state_valid(bch2_snapshot_state(s))) { unsigned dist; enum bch_snapshot_state nearest = - bch2_snapshot_state_nearest(le32_to_cpu(s.state), &dist); + bch2_snapshot_state_nearest(le32_to_cpu(s->state), &dist); /* * Codewords are >= 14 apart, so anything <= 6 bits out is @@ -732,22 +1146,22 @@ static int check_snapshot(struct btree_trans *trans, if (dist <= 2) { if (ret_fsck_err(trans, snapshot_state_bitflip, "snapshot state 0x%x is a %u-bit flip of %s - correcting:\n%s", - le32_to_cpu(s.state), dist, + le32_to_cpu(s->state), dist, bch2_snapshot_state_str(nearest), (bch2_bkey_val_to_text(&buf, c, k), buf.buf))) { - u = u ?: errptr_try(bch2_bkey_make_mut_typed(trans, iter, &k, 0, snapshot)); - bch2_snapshot_state_set(&u->v, nearest); - s = u->v; + *u = *u ?: errptr_try(bch2_bkey_make_mut_typed(trans, iter, &k, 0, snapshot)); + bch2_snapshot_state_set(&(*u)->v, nearest); + *s = (*u)->v; } } else if (dist <= 6) { if (ret_fsck_err(trans, snapshot_state_bad, "snapshot state 0x%x is %u bits from %s - correcting:\n%s", - le32_to_cpu(s.state), dist, + le32_to_cpu(s->state), dist, bch2_snapshot_state_str(nearest), (bch2_bkey_val_to_text(&buf, c, k), buf.buf))) { - u = u ?: errptr_try(bch2_bkey_make_mut_typed(trans, iter, &k, 0, snapshot)); - bch2_snapshot_state_set(&u->v, nearest); - s = u->v; + *u = *u ?: errptr_try(bch2_bkey_make_mut_typed(trans, iter, &k, 0, snapshot)); + bch2_snapshot_state_set(&(*u)->v, nearest); + *s = (*u)->v; } } else { /* @@ -757,24 +1171,24 @@ static int check_snapshot(struct btree_trans *trans, * unreferenced garbage node we can't place: fail-stop. */ bool ref; - int ret2 = snapshot_referenced(trans, &s, k.k->p.offset, &ref); + int ret2 = snapshot_referenced(trans, s, k.k->p.offset, &ref); if (ret2) return ret2; if (ref) { if (ret_fsck_err(trans, snapshot_state_bad, "snapshot state 0x%x is garbage, but the node is referenced - marking live:\n%s", - le32_to_cpu(s.state), + le32_to_cpu(s->state), (bch2_bkey_val_to_text(&buf, c, k), buf.buf))) { - u = u ?: errptr_try(bch2_bkey_make_mut_typed(trans, iter, &k, 0, snapshot)); - bch2_snapshot_state_set(&u->v, SNAPSHOT_STATE_live); - s = u->v; + *u = *u ?: errptr_try(bch2_bkey_make_mut_typed(trans, iter, &k, 0, snapshot)); + bch2_snapshot_state_set(&(*u)->v, SNAPSHOT_STATE_live); + *s = (*u)->v; } } else { CLASS(bch_log_msg, msg)(c); prt_printf(&msg.m, "snapshot has invalid state 0x%x (nearest codeword %s is %u bits away, node unreferenced):\n", - le32_to_cpu(s.state), bch2_snapshot_state_str(nearest), dist); + le32_to_cpu(s->state), bch2_snapshot_state_str(nearest), dist); bch2_bkey_val_to_text(&msg.m, c, k); msg.m.suppress = !bch2_count_fsck_err(c, snapshot_state_bad, &msg.m); @@ -783,6 +1197,51 @@ static int check_snapshot(struct btree_trans *trans, } } + /* + * A valid state that contradicts the legacy flags: current writers + * dual-write both via bch2_snapshot_state_set(), so only a legacy + * flags-only writer leaves them disagreeing - the flags are the fresher + * write. But the flags are single unprotected bits, so check the + * node's shape before trusting them over a codeword: a node tombstoned + * by a legacy bch2_snapshot_node_delete() carries the tombstone wipe, + * and no live, will_delete or no_keys node ever has tree == 0. A bare + * DELETED bit on a live-shaped node stays with the state field. + * + * Left as-is, the interior-deletion collector reads the stale no_keys + * state, queues the tombstone, and the breadcrumb child pointer + * fail-stops the edge checks - wedging every mount (the 2026-07-20 + * field report; snapshot-inject/stale_state_tombstone). + */ + if (bch2_snapshot_state(s) != SNAPSHOT_STATE_deleted && + BCH_SNAPSHOT_DELETED_OBSOLETE(s) && + !s->tree && + ret_fsck_err(trans, snapshot_state_stale_tombstone, + "snapshot spliced out by a legacy kernel (tombstone shape, legacy deleted flag)\n" + "but the state field is stale at %s - correcting to deleted:\n%s", + bch2_snapshot_state_str(bch2_snapshot_state(s)), + (bch2_bkey_val_to_text(&buf, c, k), buf.buf))) { + *u = *u ?: errptr_try(bch2_bkey_make_mut_typed(trans, iter, &k, 0, snapshot)); + bch2_snapshot_state_set(&(*u)->v, SNAPSHOT_STATE_deleted); + *s = (*u)->v; + } + + return 0; +} + +/* + * A non-live state, checked against the child snapshots, the subvolume + * and the accounting. Returns 1 if the node was deleted or is a settled + * tombstone: no further checking. + */ +static int check_snapshot_deleted(struct btree_trans *trans, + struct btree_iter *iter, + struct bkey_s_c k, + struct bch_snapshot *s, + struct bkey_i_snapshot **u) +{ + struct bch_fs *c = trans->c; + CLASS(printbuf, buf)(); + /* * A non-live node with two live children that both point back at it is a * lie: it's a branching interior that two subtrees still depend on as @@ -801,50 +1260,145 @@ static int check_snapshot(struct btree_trans *trans, * Do this before the deleted early-out, then fall through so the * edge/depth/tree checks validate the now-live node. */ - if (bch2_snapshot_state(&s) != SNAPSHOT_STATE_live) { + if (bch2_snapshot_state(s) != SNAPSHOT_STATE_live) { unsigned nr_live_children = 0; for (unsigned i = 0; i < 2; i++) { - if (!s.children[i]) + if (!s->children[i]) continue; - struct bch_snapshot child; - int ret2 = bch2_snapshot_lookup(trans, le32_to_cpu(s.children[i]), &child); - if (ret2 && !bch2_err_matches(ret2, ENOENT)) - return ret2; + struct bkey_i_snapshot child; + bool exists; + try(snapshot_lookup_key_absent_ok(trans, le32_to_cpu(s->children[i]), + &child, &exists)); - nr_live_children += !ret2 && - bch2_snapshot_state_compat(&child) == SNAPSHOT_STATE_live && - snapshot_node_points_back(&child, EDGE_CHILD, k.k->p.offset); + nr_live_children += exists && + bch2_snapshot_state_compat(&child.v) == SNAPSHOT_STATE_live && + snapshot_node_points_back(&child.v, EDGE_CHILD, k.k->p.offset); } if (ret_fsck_err_on(nr_live_children == 2, trans, snapshot_deleted_has_live_children, "snapshot marked %s but has two live children - reviving:\n%s", - bch2_snapshot_state_str(bch2_snapshot_state(&s)), + bch2_snapshot_state_str(bch2_snapshot_state(s)), (bch2_bkey_val_to_text(&buf, c, k), buf.buf))) { - u = u ?: errptr_try(bch2_bkey_make_mut_typed(trans, iter, &k, 0, snapshot)); - bch2_snapshot_state_set(&u->v, SNAPSHOT_STATE_live); - s = u->v; + *u = *u ?: errptr_try(bch2_bkey_make_mut_typed(trans, iter, &k, 0, snapshot)); + bch2_snapshot_state_set(&(*u)->v, SNAPSHOT_STATE_live); + *s = (*u)->v; + } + + /* + * Same check via the subvolume: deletion tombstones the + * subvolume in the same transaction that marks its snapshot, + * so a non-live leaf whose subvolume is live and points back + * has a bad state field. This also fixes, in the same pass, a + * bad state stamped by the zero-state migration above from a + * corrupt legacy flag. (A tombstoned subvolume reads as + * ENOENT here: that's normal mid-deletion, not evidence.) + */ + if (!s->children[0] && s->subvol) { + struct bch_subvolume subvol; + int ret2 = bch2_subvolume_get(trans, le32_to_cpu(s->subvol), + false, &subvol); + if (ret2 && !bch2_err_matches(ret2, ENOENT)) + return ret2; + + if (!ret2 && + bch2_subvolume_state_compat(&subvol) == SUBVOLUME_STATE_live && + le32_to_cpu(subvol.snapshot) == k.k->p.offset && + ret_fsck_err(trans, snapshot_deleted_but_subvol_live, + "snapshot marked %s but its subvolume is live - reviving:\n%s", + bch2_snapshot_state_str(bch2_snapshot_state(s)), + (bch2_bkey_val_to_text(&buf, c, k), buf.buf))) { + *u = *u ?: errptr_try(bch2_bkey_make_mut_typed(trans, iter, &k, 0, snapshot)); + bch2_snapshot_state_set(&(*u)->v, SNAPSHOT_STATE_live); + *s = (*u)->v; + } } } - if (bch2_snapshot_state(&s) == SNAPSHOT_STATE_deleted) + return bch2_snapshot_state(s) == SNAPSHOT_STATE_deleted; +} + +static int check_snapshot(struct btree_trans *trans, + struct btree_iter *iter, + struct bkey_s_c k) +{ + struct bch_fs *c = trans->c; + CLASS(printbuf, buf)(); + struct bkey_i_snapshot *u = NULL; + int ret = 0; + + if (k.k->type != KEY_TYPE_snapshot) return 0; + struct bch_snapshot s; + bkey_val_copy_pad(&s, bkey_s_c_to_snapshot(k)); + + try(check_snapshot_state(trans, iter, k, &s, &u)); + + /* + * Data first, before anything else reasons about the state field: + * nothing we write deletes a node with keys still accounted to it, so + * data means the state field is the lie, whatever the rest of the node + * says. Settling it here means every check below - and every edge + * repair a parent runs against this node - sees a state that has + * already been held up against the accounting. + * + * No data: settled tombstone, and the checks below handle it. + * + * How the state gets put right depends on which lie it is. deleted + * means the node was spliced out of the tree, so reviving it means + * undoing that splice. no_keys is only ever marked - it says "this + * node's keys have migrated down", and the node stays where it is - so + * there is nothing to relink and setting the state live is the whole + * repair. + */ + enum bch_snapshot_state state = bch2_snapshot_state(&s); + + if (state == SNAPSHOT_STATE_deleted || + state == SNAPSHOT_STATE_no_keys) { + u64 keys, sectors; + CLASS(printbuf, breakdown)(); + try(bch2_snapshot_accounting_totals(c, k.k->p.offset, &keys, §ors, + NULL, &breakdown)); + + if (ret_fsck_err_on(keys || sectors, + trans, snapshot_deleted_but_has_data, + "%s snapshot node has data accounted - %s:%s\n%s", + bch2_snapshot_state_str(state), + state == SNAPSHOT_STATE_no_keys ? "clearing state" : "undeleting", + breakdown.buf, + (printbuf_reset(&buf), + bch2_bkey_val_to_text(&buf, c, k), buf.buf))) { + u = errptr_try(bch2_bkey_make_mut_typed(trans, iter, &k, 0, snapshot)); + + if (state == SNAPSHOT_STATE_no_keys) + bch2_snapshot_state_set(&u->v, SNAPSHOT_STATE_live); + else + try(snapshot_undelete_owns_data(trans, u)); + s = u->v; + } + } + + ret = check_snapshot_deleted(trans, iter, k, &s, &u); + if (ret) + return ret < 0 ? ret : 0; + if (s.parent) - try(check_snapshot_edge(trans, &s, k.k->p.offset, + try(check_snapshot_edge(trans, k, &s, EDGE_CHILD, le32_to_cpu(s.parent))); for (unsigned i = 0; i < 2; i++) if (s.children[i]) - try(check_snapshot_edge(trans, &s, k.k->p.offset, + try(check_snapshot_edge(trans, k, &s, EDGE_PARENT, le32_to_cpu(s.children[i]))); - struct bch_snapshot parent = {}; + struct bkey_i_snapshot parent; u32 parent_id = le32_to_cpu(s.parent); + bool parent_exists = false; if (parent_id) - try(bch2_snapshot_lookup(trans, parent_id, &parent)); + try(snapshot_lookup_key_absent_ok(trans, parent_id, &parent, &parent_exists)); ret = snapshot_tree_ptr_good(trans, k.k->p.offset, le32_to_cpu(s.tree)); if (ret < 0) @@ -857,7 +1411,17 @@ static int check_snapshot(struct btree_trans *trans, try(snapshot_tree_ptr_repair(trans, iter, k, &s)); ret = 0; - u32 real_depth = parent_id ? le32_to_cpu(parent.depth) + 1 : 0; + /* + * Depth is derived from the parent, so with the parent missing there's + * nothing to derive it from - and "no parent" would give 0, flattening + * an interior node to a root. check_snapshot_edge() has already + * reported the dangling pointer; leave depth alone until that's + * resolved and the node is visited again. + */ + u32 real_depth = parent_exists ? le32_to_cpu(parent.v.depth) + 1 : 0; + + if (parent_id && !parent_exists) + goto skiplists; if (ret_fsck_err_on(le32_to_cpu(s.depth) != real_depth, trans, snapshot_bad_depth, @@ -868,6 +1432,7 @@ static int check_snapshot(struct btree_trans *trans, u->v.depth = cpu_to_le32(real_depth); s = u->v; } +skiplists: for (unsigned i = 0; i < 3; i++) { u32 skip = le32_to_cpu(s.skip[i]); @@ -947,6 +1512,8 @@ int bch2_check_snapshots(struct bch_fs *c) return ret; } +/* reconstruct_snapshots: */ + static int check_snapshot_exists(struct btree_trans *trans, u32 id) { struct bch_fs *c = trans->c; @@ -981,14 +1548,9 @@ static int check_snapshot_exists(struct btree_trans *trans, u32 id) snapshot->v.tree = cpu_to_le32(tree_id); snapshot->v.btime.lo = cpu_to_le64(bch2_current_time(c)); - for_each_btree_key_norestart(trans, iter, BTREE_ID_subvolumes, POS_MIN, - 0, k, ret) { - if (k.k->type == KEY_TYPE_subvolume && - le32_to_cpu(bkey_s_c_to_subvolume(k).v->snapshot) == id) { - snapshot->v.subvol = cpu_to_le32(k.k->p.offset); - break; - } - } + u32 subvol_id = 0; + try(subvol_claiming_snapshot(trans, id, &subvol_id)); + snapshot->v.subvol = cpu_to_le32(subvol_id); bch2_snapshot_state_set(&snapshot->v, SNAPSHOT_STATE_live); @@ -1048,6 +1610,32 @@ static int get_snapshot_trees(struct bch_fs *c, struct snapshot_tree_reconstruct return snapshot_list_add_nodup(c, &r->cur_ids, pos.snapshot); } +/* + * Recreate one missing snapshot node, committed as a single unit: the + * fsck_err queues its journal log entry and check_snapshot_exists() queues the + * new node, and commit_do() commits both. Kept inside the commit_do() body (a + * lockrestart_do, which begins with bch2_trans_begin) so the queued log isn't + * discarded before the commit - the caller must not queue it outside. + */ +static int reconstruct_snapshot_node(struct btree_trans *trans, u32 id, + unsigned tree_nr, struct printbuf *buf) +{ + struct bch_fs *c = trans->c; + + if (ret_fsck_err_on(bch2_snapshot_id_state(c, id) == SNAPSHOT_ID_empty, + trans, snapshot_node_missing, + "snapshot node %u from tree %s missing, recreate?", id, buf->buf)) { + if (tree_nr > 1) { + bch_err(c, "cannot reconstruct snapshot trees with multiple nodes"); + return bch_err_throw(c, fsck_repair_unimplemented); + } + + return check_snapshot_exists(trans, id); + } + + return 0; +} + int bch2_reconstruct_snapshots(struct bch_fs *c) { CLASS(btree_trans, trans)(c); @@ -1076,24 +1664,48 @@ int bch2_reconstruct_snapshots(struct bch_fs *c) printbuf_reset(&buf); bch2_snapshot_id_list_to_text(&buf, t); - darray_for_each(*t, id) { - if (fsck_err_on(bch2_snapshot_id_state(c, *id) == SNAPSHOT_ID_empty, - trans, snapshot_node_missing, - "snapshot node %u from tree %s missing, recreate?", *id, buf.buf)) { - if (t->nr > 1) { - bch_err(c, "cannot reconstruct snapshot trees with multiple nodes"); - return bch_err_throw(c, fsck_repair_unimplemented); - } - - try(commit_do(trans, NULL, NULL, BCH_TRANS_COMMIT_no_enospc, - check_snapshot_exists(trans, *id))); - } - } + darray_for_each(*t, id) + try(commit_do(trans, NULL, NULL, BCH_TRANS_COMMIT_no_enospc, + reconstruct_snapshot_node(trans, *id, t->nr, &buf))); } -fsck_err: + return ret; } +/* + * When we migrate a key out of a deleted snapshot to its live descendant, the + * snapshot-deletion scan's premise - "a key in snapshot X implies an inode in + * snapshot X" - has to hold at the destination too, or the key gets stranded + * again on the next deletion. If the inode is only inherited from an ancestor + * of the descendant, copy it down. A genuinely missing inode is left for a + * full fsck to reconstruct; we don't do that or schedule passes here. + */ +/* check_key_has_snapshot - per-key repair, also called at runtime: */ + +static int check_key_has_inode_in_snapshot(struct btree_trans *trans, + enum btree_id btree, u64 inum, u32 snapshot) +{ + switch (btree) { + case BTREE_ID_extents: + case BTREE_ID_dirents: + case BTREE_ID_xattrs: + break; + default: + return 0; + } + + struct bch_inode_unpacked inode; + int ret = bch2_inode_find_by_inum_snapshot(trans, inum, snapshot, &inode, 0); + if (ret) + return bch2_err_matches(ret, ENOENT) ? 0 : ret; + + if (inode.bi_snapshot == snapshot) + return 0; + + inode.bi_snapshot = snapshot; + return __bch2_fsck_write_inode(trans, &inode); +} + int __bch2_check_key_has_snapshot(struct btree_trans *trans, struct btree_iter *iter, struct bkey_s_c k) @@ -1111,6 +1723,53 @@ int __bch2_check_key_has_snapshot(struct btree_trans *trans, state != SNAPSHOT_ID_empty) return 0; + /* + * The incomplete snapshot deletion that stranded this key almost + * certainly stranded sibling keys across the content btrees too - left + * alone they only surface later, when copygc/reconcile trips over them. + * Schedule the content passes so the whole cascade of damage gets + * repaired in this fsck run rather than festering. require_recovery_pass + * only returns the unwind error (deferring this key's own repair) when + * it actually needs to rewind to an earlier pass; scheduling a + * later-or-current pass just marks it to run. + * + * skip_if_complete: at most one sweep per instance. These passes don't + * repair every stranded-key state - if they already ran and this key is + * still here, rescheduling can't fix it, but it would re-arm the passes + * in the superblock on every encounter, forcing fsck on every mount. + */ + ret = bch2_run_explicit_recovery_pass(c, &buf, BCH_RECOVERY_PASS_check_inodes, + RUN_RECOVERY_PASS_skip_if_complete) ?: ret; + ret = bch2_run_explicit_recovery_pass(c, &buf, BCH_RECOVERY_PASS_check_extents, + RUN_RECOVERY_PASS_skip_if_complete) ?: ret; + ret = bch2_run_explicit_recovery_pass(c, &buf, BCH_RECOVERY_PASS_check_dirents, + RUN_RECOVERY_PASS_skip_if_complete) ?: ret; + ret = bch2_run_explicit_recovery_pass(c, &buf, BCH_RECOVERY_PASS_check_xattrs, + RUN_RECOVERY_PASS_skip_if_complete) ?: ret; + + /* + * A key in a deleted snapshot means that snapshot has data, and + * check_snapshot() holds a deleted node up against the accounting and + * undeletes it when it does - nothing we write deletes a node with keys + * still accounted to it, so the state field is the lie. If we are + * standing here looking at the key, that corroboration hasn't happened: + * either check_snapshots hasn't run, or it ran before whatever put the + * node in this state. + * + * So require it, and let the node be undeleted before anything below + * decides what to do with the key - the alternatives there are deleting + * it or migrating it to a live descendant, and both are irreversible on + * the strength of a state field the accounting disagrees with. + * + * Requiring it rewinds if we are past it, so the key is retried once + * the node is live again. If check_snapshots has already run this + * recovery and the key is still in a deleted snapshot, the corroboration + * saw it and let it stand - require_recovery_pass returns 0 and the + * repair below proceeds. + */ + if (state == SNAPSHOT_ID_deleted) + ret = bch2_require_recovery_pass(c, &buf, BCH_RECOVERY_PASS_check_snapshots) ?: ret; + /* * Both repairs below destroy or relocate a key based on the in-memory * snapshot table. Only trust it if the snapshots and subvolumes btrees @@ -1122,25 +1781,13 @@ int __bch2_check_key_has_snapshot(struct btree_trans *trans, * ran this mount (or was ratelimited) - it must have run since the last * mutation. */ - bool snapshots_clean = bch2_btree_is_clean(c, BTREE_ID_snapshots) && - bch2_btree_is_clean(c, BTREE_ID_subvolumes); - - if (!snapshots_clean) { + if (!bch2_btree_is_clean(c, BTREE_ID_snapshots) || + !bch2_btree_is_clean(c, BTREE_ID_subvolumes)) { ret = bch2_require_recovery_pass(c, &buf, BCH_RECOVERY_PASS_check_snapshots) ?: ret; ret = bch2_require_recovery_pass(c, &buf, BCH_RECOVERY_PASS_check_subvols) ?: ret; } - /* - * Snapshot missing entirely: we should have caught this with - * btree_lost_data and kicked off reconstruct_snapshots, so if we end up - * here we have no idea what happened - force reconstruct too. - */ - if (state == SNAPSHOT_ID_empty && - c->sb.btrees_lost_data & BIT_ULL(BTREE_ID_snapshots)) - ret = bch2_require_recovery_pass(c, &buf, BCH_RECOVERY_PASS_reconstruct_snapshots) ?: ret; - - if (!snapshots_clean) - return ret; + try(ret); unsigned repair_flags = FSCK_CAN_IGNORE | (!ret ? FSCK_CAN_FIX : 0); @@ -1167,8 +1814,9 @@ int __bch2_check_key_has_snapshot(struct btree_trans *trans, goto fsck_err; } - if (__fsck_err_on(!live_child, - trans, repair_flags, bkey_in_deleted_snapshot, + if (__inode_fsck_err_on(!live_child, + trans, k.k->p, + repair_flags, bkey_in_deleted_snapshot, "key in deleted snapshot %s, delete?", (bch2_btree_id_to_text(&buf, iter->btree_id), prt_char(&buf, ' '), @@ -1178,13 +1826,17 @@ int __bch2_check_key_has_snapshot(struct btree_trans *trans, if (__fsck_err_on(live_child, trans, repair_flags, bkey_in_deleted_interior_snapshot, - "key in deleted interior snapshot %s, migrate to live descendant?", + "key in deleted interior snapshot %s, migrating to live descendant %u", (bch2_btree_id_to_text(&buf, iter->btree_id), prt_char(&buf, ' '), - bch2_bkey_val_to_text(&buf, c, k), buf.buf))) - ret = bch2_delete_dead_snapshot_key(trans, iter, k, live_child) ?: 1; + bch2_bkey_val_to_text(&buf, c, k), buf.buf), live_child)) + ret = bch2_delete_dead_snapshot_key(trans, iter, k, live_child) ?: + check_key_has_inode_in_snapshot(trans, iter->btree_id, + k.k->p.inode, live_child) ?: + 1; } else { - if (__fsck_err(trans, repair_flags, bkey_in_missing_snapshot, + if (__inode_fsck_err(trans, k.k->p, + repair_flags, bkey_in_missing_snapshot, "key in missing snapshot %s, delete?", (bch2_btree_id_to_text(&buf, iter->btree_id), prt_char(&buf, ' '), diff --git a/fs/snapshots/delete.c b/fs/snapshots/delete.c index 7a1dce575a..db3c392eaa 100644 --- a/fs/snapshots/delete.c +++ b/fs/snapshots/delete.c @@ -8,6 +8,7 @@ #include "btree/update.h" #include "init/error.h" +#include "init/damage.h" #include "init/progress.h" #include "init/passes.h" @@ -109,17 +110,6 @@ __cold void bch2_snapshot_delete_status_to_text(struct printbuf *out, struct bch prt_newline(out); bch2_snapshot_delete_nodes_to_text(out, d, false); } - - struct task_struct *t; - scoped_guard(rcu) { - t = rcu_dereference(d->thread); - if (t) - get_task_struct(t); - } - if (t) { - bch2_prt_task_backtrace(out, t, 0, GFP_KERNEL); - put_task_struct(t); - } } /* @@ -140,8 +130,8 @@ int bch2_snapshot_node_set_deleted(struct btree_trans *trans, u32 id) /* * The backref is retained: it now points at the subvolume's - * tombstone, and deletion requires that testimony - a will_delete - * leaf without a subvolume pointing back is an invalid state + * tombstone, and deletion checks it - a will_delete leaf without a + * subvolume pointing back is an invalid state * (check_should_delete_leaf): */ bch2_snapshot_state_set(&s->v, SNAPSHOT_STATE_will_delete); @@ -167,20 +157,25 @@ int bch2_snapshot_node_set_deleted(struct btree_trans *trans, u32 id) * * The key count catches metadata-only stranding (dirents, xattrs, empty * inodes) that the sectors counter can't see. It's only trusted once - * check_allocations has rebuilt it (scheduled by the snapshot_nr_keys + * check_allocations has rebuilt it (scheduled by the per_dev_fragmentation_lru * upgrade); before that version we fall back to the sectors-only check. Either * way it's an in-memory read per snapshot btree, and the per-btree breakdown * points at where any stranded keys live. */ -static int bch2_snapshot_node_check_no_data(struct btree_trans *trans, u32 id) +/* + * Total keys/sectors accounted to snapshot @id across the snapshotted + * btrees, with a per-btree breakdown appended to @breakdown if non-NULL. + * (nr_keys counters exist only post-upgrade and read as zero before.) + */ +int bch2_snapshot_accounting_totals(struct bch_fs *c, u32 id, + u64 *total_keys, u64 *total_sectors, + u64 *btrees_with_keys, + struct printbuf *breakdown) { - struct bch_fs *c = trans->c; - bool trust_keys = c->sb.version_upgrade_complete >= - bcachefs_metadata_version_snapshot_nr_keys; + bcachefs_metadata_version_per_dev_fragmentation_lru; - CLASS(printbuf, buf)(); - u64 total_keys = 0, total_sectors = 0; + *total_keys = *total_sectors = 0; for (unsigned btree = 0; btree < BTREE_ID_NR; btree++) { if (!btree_type_has_snapshots(btree)) @@ -192,6 +187,12 @@ static int bch2_snapshot_node_check_no_data(struct btree_trans *trans, u32 id) acc.snapshot.id = id; acc.snapshot.btree = btree; + /* + * In-mem: bch2_accounting_is_mem() covers everything but + * BCH_DISK_ACCOUNTING_inum, so the counters are current as + * deltas are applied. No btree read, no transaction, and no + * write buffer flush to make the values trustworthy. + */ u64 v[3] = {}; bch2_accounting_mem_read(c, disk_accounting_pos_to_bpos(&acc), v, ARRAY_SIZE(v)); @@ -202,32 +203,225 @@ static int bch2_snapshot_node_check_no_data(struct btree_trans *trans, u32 id) if (!nr_keys && !sectors) continue; - total_keys += nr_keys; - total_sectors += sectors; + *total_keys += nr_keys; + *total_sectors += sectors; + if (btrees_with_keys) + *btrees_with_keys |= BIT_ULL(btree); - prt_str(&buf, "\n "); - bch2_btree_id_to_text(&buf, btree); - prt_printf(&buf, ": %llu keys (%llu bytes), %llu sectors", - nr_keys, key_bytes, sectors); + if (breakdown) { + prt_str(breakdown, "\n "); + bch2_btree_id_to_text(breakdown, btree); + prt_printf(breakdown, ": %llu keys (%llu bytes), %llu sectors", + nr_keys, key_bytes, sectors); + } } + return 0; +} + +static inline u32 interior_delete_has_id(interior_delete_list *l, u32 id) +{ + struct snapshot_interior_delete *i = darray_find_p(*l, i, i->id == id); + return i ? i->live_child : 0; +} + +/* + * @op is the operation delete_dead_snapshots was performing - set_no_keys, + * leaf delete, or interior delete - which the node key does not tell you, and + * which is the first thing you need: whether we were emptying a node whose + * keys should already have migrated down, or splicing out an interior. + * + * The node is printed too, because operation and shape are independent and + * their disagreement is the signal: an interior delete refused on a node that + * still reads as a leaf means something quite different from a leaf delete + * refused on a redundant interior whose migration was interrupted partway. + */ +/* + * Keys stranded in @btrees: schedule the content pass for each, which is what + * repairs the cause (a key with no inode at its own snapshot) and so lets the + * next deletion find them. + */ +static int schedule_content_passes(struct bch_fs *c, struct printbuf *msg, u64 btrees) +{ + int ret = 0; + + for (unsigned btree = 0; btree < BTREE_ID_NR; btree++) { + if (!(btrees & BIT_ULL(btree))) + continue; + + enum bch_recovery_pass pass; + switch (btree) { + case BTREE_ID_extents: pass = BCH_RECOVERY_PASS_check_extents; break; + case BTREE_ID_inodes: pass = BCH_RECOVERY_PASS_check_inodes; break; + case BTREE_ID_dirents: pass = BCH_RECOVERY_PASS_check_dirents; break; + case BTREE_ID_xattrs: pass = BCH_RECOVERY_PASS_check_xattrs; break; + default: continue; + } + + ret = bch2_run_explicit_recovery_pass(c, msg, pass, 0) ?: ret; + } + + return ret; +} + +static int bch2_snapshot_node_check_no_data(struct btree_trans *trans, u32 id, + const char *op) +{ + struct bch_fs *c = trans->c; + + CLASS(printbuf, buf)(); + u64 total_keys, total_sectors, btrees_with_keys = 0; + + try(bch2_snapshot_accounting_totals(c, id, &total_keys, &total_sectors, + &btrees_with_keys, &buf)); + if (likely(!total_keys && !total_sectors)) return 0; + /* Only the refusal below needs the node itself: */ + struct bkey_i_snapshot s; + int ret = bch2_snapshot_lookup_key(trans, id, &s); + bch2_fs_inconsistent_on(bch2_err_matches(ret, ENOENT), c, "missing snapshot %u", id); + if (ret) + return ret; + + /* + * Whether an interior has a single live child is what the deletion + * recorded when it built its lists, not something to re-derive from the + * snapshot table: live_child is the migration target the deletion + * actually used, so if the two ever disagreed the list is the one that + * describes what happened. + */ + struct snapshot_delete *d = &c->snapshots.delete; + u32 live_child = interior_delete_has_id(&d->delete_interior, id) ?: + interior_delete_has_id(&d->no_keys, id); + + const char *shape = !s.v.children[0] + ? "leaf" + : (live_child ? "redundant interior" : "interior"); + CLASS(printbuf, msg)(); - prt_printf(&msg, "snapshot node %u still has %llu keys / %llu sectors accounted to it - refusing to delete/empty, to prevent data loss; scheduling repair:%s\n", - id, total_keys, total_sectors, buf.buf); + prt_printf(&msg, "%s snapshot node %u (%s) still has %llu keys / %llu sectors accounted to it - refusing, to prevent data loss; scheduling repair:%s\n ", + op, id, shape, total_keys, total_sectors, buf.buf); + bch2_bkey_val_to_text(&msg, c, bkey_i_to_s_c(&s.k_i)); + prt_newline(&msg); - int ret = bch2_require_recovery_pass(c, &msg, BCH_RECOVERY_PASS_check_allocations); - ret = bch2_require_recovery_pass(c, &msg, BCH_RECOVERY_PASS_check_inodes) ?: ret; + /* + * Schedule the passes whose key_has_snapshot repairs can actually + * remove the stranded keys - per btree, from the accounting breakdown. + * check_inodes alone can't repair a stranded dirent; scheduling only + * it left the refusal firing forever. Plus check_allocations, since + * here the count itself may be what's wrong: + */ + ret = bch2_run_explicit_recovery_pass(c, &msg, BCH_RECOVERY_PASS_check_allocations, 0); + + ret = schedule_content_passes(c, &msg, btrees_with_keys) ?: ret; bch_err(c, "%s", msg.buf); + /* + * At runtime the passes can't rewind - but the requirement was + * persisted to the superblock before cannot_rewind_recovery was + * returned, so they run at next mount and the refusal below is the + * complete runtime response: + */ + if (bch2_err_matches(ret, BCH_ERR_cannot_rewind_recovery)) + ret = 0; + return ret ?: bch_err_throw(c, EINVAL_snapshot_delete_with_data); } +static int snapshot_node_data_to_text(struct printbuf *out, struct bch_fs *c, + u32 id, u32 live_child) +{ + CLASS(printbuf, breakdown)(); + u64 nr_keys, sectors; + + try(bch2_snapshot_accounting_totals(c, id, &nr_keys, §ors, NULL, &breakdown)); + + prt_printf(out, "\n %s %u", live_child ? "interior" : "leaf", id); + if (live_child) + prt_printf(out, " -> %u", live_child); + prt_printf(out, ": %llu keys, %llu sectors%s", nr_keys, sectors, breakdown.buf); + return 0; +} + +/* + * Every node we're about to delete, and what it holds. Renders into @out for + * the caller to log: this runs under lockrestart_do, so printing here would + * hold btree locks across a printk of one line per node, and a restart + * re-drive would append a second copy. Reset for that re-drive. + */ +static int bch2_snapshot_delete_data_to_text(struct printbuf *out, + struct bch_fs *c, + struct snapshot_delete *d) +{ + printbuf_reset(out); + + prt_printf(out, "snapshot deletion, data accounted per node:"); + + darray_for_each(d->delete_leaves, i) + try(snapshot_node_data_to_text(out, c, *i, 0)); + + darray_for_each(d->delete_interior, i) + try(snapshot_node_data_to_text(out, c, i->id, i->live_child)); + + return 0; +} + +/* + * Inodes excluded: those are what we're about to delete, accounted until we do. + * + * Pre-per_dev_fragmentation_lru the key counters aren't populated yet, so this + * sees sectors only - a dirents- or xattrs-only stranding is invisible there. + */ +static int snapshot_content_empty(struct bch_fs *c, u32 id, + struct printbuf *msg, u64 *bad_btrees) +{ + u64 nr_keys, sectors, btrees = 0; + CLASS(printbuf, breakdown)(); + + try(bch2_snapshot_accounting_totals(c, id, &nr_keys, §ors, + &btrees, &breakdown)); + + btrees &= ~BIT_ULL(BTREE_ID_inodes); + if (!btrees) + return 0; + + if (!*bad_btrees) + prt_printf(msg, "content still accounted to dying snapshots - refusing to " + "delete their inode keys, which is how the deletion scan finds " + "these keys at all:"); + + *bad_btrees |= btrees; + prt_printf(msg, "\n snapshot %u:%s", id, breakdown.buf); + return 0; +} + +/* + * Which content btrees still have keys accounted to a dying snapshot, as a + * mask. Nothing may remain in them by the time we delete the inode keys - see + * the caller. + */ +static int dying_snapshots_content_btrees(struct bch_fs *c, + struct snapshot_delete *d, + struct printbuf *msg, + u64 *bad_btrees) +{ + darray_for_each(d->delete_leaves, i) + try(snapshot_content_empty(c, *i, msg, bad_btrees)); + + darray_for_each(d->delete_interior, i) + try(snapshot_content_empty(c, i->id, msg, bad_btrees)); + + return 0; +} + static int bch2_snapshot_node_set_no_keys(struct btree_trans *trans, u32 id) { + /* Before the get_mut below queues anything - see bch2_snapshot_node_check_deletable() */ + try(bch2_snapshot_node_check_no_data(trans, id, "set_no_keys")); + struct bkey_i_snapshot *s = bch2_bkey_get_mut_typed(trans, BTREE_ID_snapshots, POS(0, id), 0, snapshot); int ret = PTR_ERR_OR_ZERO(s); @@ -235,8 +429,6 @@ static int bch2_snapshot_node_set_no_keys(struct btree_trans *trans, u32 id) if (unlikely(ret)) return ret; - try(bch2_snapshot_node_check_no_data(trans, id)); - bch2_snapshot_state_set(&s->v, SNAPSHOT_STATE_no_keys); return 0; } @@ -247,26 +439,46 @@ static inline void normalize_snapshot_child_pointers(struct bch_snapshot *s) swap(s->children[0], s->children[1]); } -static int bch2_snapshot_node_delete(struct btree_trans *trans, u32 id, bool delete_interior) +/* + * Every reason we decline to delete a snapshot node, decided without touching + * anything. + * + * These have to be answered before the deletion starts, never partway through + * it. bch2_bkey_get_mut_typed() queues its update the moment it's called, so a + * refusal after the first one leaves the transaction holding a fragment of a + * deletion, which the caller then drops on the floor. + * + * And callers commit work ahead of the deletion that assumes it will happen: + * bch2_delete_dead_interior_snapshots() rewrites every child's depth and skip[] + * for the tree shape the deletion is going to produce, and commits that, before + * it deletes a single node. A node refused after that leaves the tree + * describing a deletion that never happened - skip[] entries pointing above + * parent, which validation rejects on the next write, taking the filesystem + * read only. + * + * So this is separable from the deletion on purpose: a caller that is about to + * commit to a set of nodes asks first, and drops the refused ones. + */ +static int bch2_snapshot_node_check_deletable(struct btree_trans *trans, u32 id, + bool delete_interior) { struct bch_fs *c = trans->c; - struct bkey_i_snapshot *s = - bch2_bkey_get_mut_typed(trans, BTREE_ID_snapshots, POS(0, id), 0, snapshot); - int ret = PTR_ERR_OR_ZERO(s); + try(bch2_snapshot_node_check_no_data(trans, id, + delete_interior ? "interior delete" : "leaf delete")); + + struct bkey_i_snapshot s; + int ret = bch2_snapshot_lookup_key(trans, id, &s); bch2_fs_inconsistent_on(bch2_err_matches(ret, ENOENT), c, "missing snapshot %u", id); - if (ret) return ret; - try(bch2_snapshot_node_check_no_data(trans, id)); - - if (bch2_trans_inconsistent_on(bch2_snapshot_state(&s->v) == SNAPSHOT_STATE_deleted, trans, + if (bch2_trans_inconsistent_on(bch2_snapshot_state(&s.v) == SNAPSHOT_STATE_deleted, trans, "deleting snapshot node %u: already in state deleted", id)) return bch_err_throw(c, EINVAL_snapshot_delete_already_deleted); - if (s->v.children[1]) { + if (s.v.children[1]) { CLASS(bch_log_msg, msg)(c); prt_printf(&msg.m, "deleting node with two children:\n"); bch2_snapshot_tree_keys_to_text(&msg.m, trans, id); @@ -274,23 +486,60 @@ static int bch2_snapshot_node_delete(struct btree_trans *trans, u32 id, bool del return bch_err_throw(c, EINVAL_snapshot_delete_has_two_children); } - if (s->v.subvol) { + if (s.v.subvol) { + /* deletion path: see the deleted tombstone directly, as in + * check_should_delete_leaf() - bch2_subvolume_get() would report + * it as ENOENT_subvolume_deleted */ struct bch_subvolume subvol; - try(bch2_subvolume_get(trans, le32_to_cpu(s->v.subvol), true, &subvol)); + try(bch2_bkey_get_val_typed(trans, BTREE_ID_subvolumes, + POS(0, le32_to_cpu(s.v.subvol)), + BTREE_ITER_cached, subvolume, &subvol)); - if (s->v.children[0] || + if (s.v.children[0] || (bch2_subvolume_state(&subvol) != SUBVOLUME_STATE_deleted && c->sb.version_upgrade_complete >= bcachefs_metadata_version_per_dev_fragmentation_lru)) { CLASS(bch_log_msg, msg)(c); prt_printf(&msg.m, "deleting node with bad subvolume pointer:\n"); - bch2_bkey_val_to_text(&msg.m, c, bkey_i_to_s_c(&s->k_i)); + bch2_bkey_val_to_text(&msg.m, c, bkey_i_to_s_c(&s.k_i)); return bch_err_throw(c, EINVAL_snapshot_delete_bad_subvol); } + } - try(bch2_btree_delete(trans, BTREE_ID_subvolumes, POS(0, le32_to_cpu(s->v.subvol)), 0)); + if (s.v.children[0] && !delete_interior) { + CLASS(bch_log_msg, msg)(c); + prt_printf(&msg.m, "deleting interior node %u with child %u at runtime:\n", + id, le32_to_cpu(s.v.children[0])); + bch2_snapshot_tree_keys_to_text(&msg.m, trans, id); + bch2_snapshot_delete_nodes_to_text(&msg.m, &c->snapshots.delete, true); + return bch_err_throw(c, EINVAL_snapshot_delete_interior_at_runtime); } + return 0; +} + +/* + * Callers are responsible for bch2_snapshot_node_check_deletable() first: from + * here on we only fail on errors that take the whole thing down, never on a + * refusal. + */ +int bch2_snapshot_node_delete(struct btree_trans *trans, u32 id) +{ + struct bch_fs *c = trans->c; + + struct bkey_i_snapshot *s = + bch2_bkey_get_mut_typed(trans, BTREE_ID_snapshots, POS(0, id), 0, snapshot); + int ret = PTR_ERR_OR_ZERO(s); + bch2_fs_inconsistent_on(bch2_err_matches(ret, ENOENT), c, + "missing snapshot %u", id); + + if (ret) + return ret; + + if (s->v.subvol) + try(bch2_btree_delete(trans, BTREE_ID_subvolumes, + POS(0, le32_to_cpu(s->v.subvol)), 0)); + u32 parent_id = le32_to_cpu(s->v.parent); u32 child_id = le32_to_cpu(s->v.children[0]); @@ -321,15 +570,6 @@ static int bch2_snapshot_node_delete(struct btree_trans *trans, u32 id, bool del } if (child_id) { - if (!delete_interior) { - CLASS(bch_log_msg, msg)(c); - prt_printf(&msg.m, "deleting interior node %llu with child %u at runtime:\n", - s->k.p.offset, child_id); - bch2_snapshot_tree_keys_to_text(&msg.m, trans, id); - bch2_snapshot_delete_nodes_to_text(&msg.m, &c->snapshots.delete, true); - return bch_err_throw(c, EINVAL_snapshot_delete_interior_at_runtime); - } - struct bkey_i_snapshot *child = bch2_bkey_get_mut_typed(trans, BTREE_ID_snapshots, POS(0, child_id), 0, snapshot); @@ -361,18 +601,11 @@ static int bch2_snapshot_node_delete(struct btree_trans *trans, u32 id, bool del } if (!bch2_request_incompat_feature(c, bcachefs_metadata_version_snapshot_deletion_v2)) { - s->v.parent = 0; /* - * Retain the pointer to our live descendant: the node is spliced - * out of the live tree, but a stray key later found in this - * deleted snapshot must still be migrated to where it's visible, - * and bch2_snapshot_live_descendent() walks children[0] to find - * it. (child_id is 0 for a leaf - nothing to retain.) + * Retain parent/child pointers; don't destroy information if we + * have to repair: */ - s->v.children[0] = cpu_to_le32(child_id); - s->v.children[1] = 0; s->v.subvol = 0; - s->v.tree = 0; s->v.depth = 0; s->v.skip[0] = 0; s->v.skip[1] = 0; @@ -384,24 +617,187 @@ static int bch2_snapshot_node_delete(struct btree_trans *trans, u32 id, bool del } /* - * Delete accounting - one key per snapshot btree. Note that designated - * initializers will not reliably cause a struct to be zeroed if it's a - * union: + * Nothing here touches this snapshot's accounting. Accounting is + * derived: the triggers on the keys we just deleted are what took the + * counters to zero. A counter still nonzero here is a bug to find, not + * a number to correct - and check_no_data() above has already refused + * the deletion if that's the case. */ - for (unsigned btree = 0; btree < BTREE_ID_NR; btree++) { - if (!btree_type_has_snapshots(btree)) - continue; + return 0; +} - struct disk_accounting_pos acc; - memset(&acc, 0, sizeof(acc)); - acc.type = BCH_DISK_ACCOUNTING_snapshot; - acc.snapshot.id = id; - acc.snapshot.btree = btree; +/* + * Can we relink to this node? Only a deleted node has been spliced out of the + * tree. no_keys is an emptied interior - kept in the tree until the next + * remount precisely so ancestry still resolves - and carries child pointers + * like any other node, so it is a perfectly ordinary neighbour to attach to. + */ +static bool snapshot_in_tree(const struct bch_snapshot *s) +{ + return bch2_snapshot_state_compat(s) != SNAPSHOT_STATE_deleted; +} + +/* + * Reinsert an undeleted node into the live tree: the inverse of the splice in + * bch2_snapshot_node_delete(). The tombstone retained its pointers as history: + * if the parent's child slot (or the snapshot_tree root, for a deleted root) + * currently holds one of our retained children, that's where the splice took + * us out - take the slot back and take the child back. If the slot holds us + * already, the deletion never got that far and there's nothing to relink. If + * the topology has moved on, or an old wiped tombstone retained nothing, the + * node revives unlinked and the tree pointer checks handle it downstream. + */ +int bch2_snapshot_node_undelete(struct btree_trans *trans, struct bkey_i_snapshot *u) +{ + struct bch_fs *c = trans->c; + u32 id = u->k.p.offset; + u32 child_id = le32_to_cpu(u->v.children[0]); + + CLASS(bch_log_msg, msg)(c); + + bch2_bkey_val_to_text(&msg.m, c, bkey_i_to_s_c(&u->k_i)); + prt_newline(&msg.m); + + if (u->v.children[1]) { + bch_err(c, "cannot undelete a node with two children"); + return bch_err_throw(c, fsck_repair_unimplemented); + } + + if (!u->v.children[0]) { + /* + * Childless: no splice to undo - our retained parent pointer is + * intact. Handle the simple case, parent still live: revive in + * place, and if our slot in the parent was cleared, the edge + * repairs complete it from our side. A dead parent would need + * undeleting too - unexpected, so fail rather than guess. + * + * A childless root has no parent to relink through and no + * children to take back: it is the entire tree, so setting it + * live is the whole repair. That is the shape of a filesystem + * that has never been snapshotted, where refusing means + * refusing to mount at all. Whether a snapshot_tree still + * points at it is the tree pointer checks' business, as for any + * node that revives unlinked. + */ + u32 parent_id = le32_to_cpu(u->v.parent); + if (parent_id) { + struct bkey_i_snapshot *parent = + bch2_bkey_get_mut_typed(trans, BTREE_ID_snapshots, + POS(0, parent_id), 0, snapshot); + int ret = PTR_ERR_OR_ZERO(parent); + if (bch2_err_matches(ret, ENOENT)) { + prt_printf(&msg.m, "cannot undelete: parent no longer exists"); + return bch_err_throw(c, fsck_repair_unimplemented); + } + if (ret) + return ret; - try(bch2_btree_bit_mod_buffered(trans, BTREE_ID_accounting, - disk_accounting_pos_to_bpos(&acc), - false)); + if (!snapshot_in_tree(&parent->v)) { + prt_printf(&msg.m, "cannot undelete: parent is itself deleted"); + return bch_err_throw(c, fsck_repair_unimplemented); + } + + if (le32_to_cpu(parent->v.children[0]) != id && + le32_to_cpu(parent->v.children[1]) != id) { + if (parent->v.children[0] && parent->v.children[1]) { + prt_printf(&msg.m, "cannot undelete: parent's child slots are full"); + return bch_err_throw(c, fsck_repair_unimplemented); + } + + unsigned i = !parent->v.children[0] ? 0 : 1; + parent->v.children[i] = cpu_to_le32(id); + normalize_snapshot_child_pointers(&parent->v); + } + } + + bch2_snapshot_state_set(&u->v, SNAPSHOT_STATE_live); + return 0; + } + + struct bkey_i_snapshot *child = + bch2_bkey_get_mut_typed(trans, BTREE_ID_snapshots, POS(0, child_id), 0, snapshot); + int ret = PTR_ERR_OR_ZERO(child); + if (bch2_err_matches(ret, ENOENT)) { + bch_err(c, "cannot undelete: child no longer exists"); + return bch_err_throw(c, fsck_repair_unimplemented); } + if (ret) + return ret; + + prt_printf(&msg.m, "attaching to child "); + bch2_bkey_val_to_text(&msg.m, c, bkey_i_to_s_c(&child->k_i)); + prt_newline(&msg.m); + + if (!snapshot_in_tree(&child->v)) { + prt_printf(&msg.m, "cannot undelete: child is itself deleted"); + return bch_err_throw(c, fsck_repair_unimplemented); + } + + u32 parent_id = le32_to_cpu(child->v.parent); + if (parent_id && parent_id <= id) { + prt_printf(&msg.m, "cannot undelete: parent of child < node to undelete"); + return bch_err_throw(c, fsck_repair_unimplemented); + } + + child->v.parent = cpu_to_le32(id); + + if (parent_id) { + struct bkey_i_snapshot *parent = + bch2_bkey_get_mut_typed(trans, BTREE_ID_snapshots, + POS(0, parent_id), 0, snapshot); + int ret = PTR_ERR_OR_ZERO(parent); + if (ret && !bch2_err_matches(ret, ENOENT)) + return ret; + + if (ret) { + prt_printf(&msg.m, "cannot undelete: parent no longer exists"); + return bch_err_throw(c, fsck_repair_unimplemented); + } + + prt_printf(&msg.m, "attaching to parent "); + bch2_bkey_val_to_text(&msg.m, c, bkey_i_to_s_c(&parent->k_i)); + prt_newline(&msg.m); + + if (!snapshot_in_tree(&parent->v)) { + prt_printf(&msg.m, "cannot undelete: parent is itself deleted"); + return bch_err_throw(c, fsck_repair_unimplemented); + } + + for (unsigned i = 0; i < 2; i++) { + u32 p_child = le32_to_cpu(parent->v.children[i]); + + if (p_child == child_id) { + parent->v.children[i] = cpu_to_le32(id); + normalize_snapshot_child_pointers(&parent->v); + break; + } + } + } else if (child->v.tree) { + struct bkey_i_snapshot_tree *s_t = + bch2_bkey_get_mut_typed(trans, BTREE_ID_snapshot_trees, + POS(0, le32_to_cpu(child->v.tree)), + 0, snapshot_tree); + int ret = PTR_ERR_OR_ZERO(s_t); + if (ret && !bch2_err_matches(ret, ENOENT)) + return ret; + + if (!ret && le32_to_cpu(s_t->v.root_snapshot) == child_id) { + s_t->v.root_snapshot = cpu_to_le32(id); + + prt_printf(&msg.m, "updated tree "); + bch2_bkey_val_to_text(&msg.m, c, bkey_i_to_s_c(&s_t->k_i)); + prt_newline(&msg.m); + } + } + + u->v.parent = cpu_to_le32(parent_id); + u->v.tree = child->v.tree; + bch2_snapshot_state_set(&u->v, SNAPSHOT_STATE_live); + + u->v.depth = cpu_to_le32(bch2_snapshot_depth(c, parent_id)); + for (unsigned j = 0; j < ARRAY_SIZE(u->v.skip); j++) + u->v.skip[j] = cpu_to_le32(bch2_snapshot_skiplist_get(c, parent_id)); + bubble_sort(u->v.skip, ARRAY_SIZE(u->v.skip), cmp_le32); return 0; } @@ -424,12 +820,6 @@ static int bch2_snapshot_node_delete(struct btree_trans *trans, u32 id, bool del * that key to snapshot leaf nodes, where we can mutate it */ -static inline u32 interior_delete_has_id(interior_delete_list *l, u32 id) -{ - struct snapshot_interior_delete *i = darray_find_p(*l, i, i->id == id); - return i ? i->live_child : 0; -} - static int snapshot_interior_delete_cmp(const void *_l, const void *_r) { const struct snapshot_interior_delete *l = _l; @@ -490,6 +880,18 @@ int bch2_delete_dead_snapshot_key(struct btree_trans *trans, struct btree_iter * new->k.p = dst; try(bch2_trans_update(trans, &dst_iter, new, BTREE_UPDATE_internal_snapshot_node)); + } else if (iter->btree_id == BTREE_ID_damage && + k.k->type == KEY_TYPE_damage && + dst_k.k->type == KEY_TYPE_damage) { + /* + * Damage entries merge instead of dropping: the dying + * key can hold counts recorded after the descendant's + * key was created, so "descendant overwrote it" never + * applies: + */ + struct bkey_i *new = errptr_try(bch2_damage_keys_merge(trans, dst, dst_k, k)); + try(bch2_trans_update(trans, &dst_iter, new, + BTREE_UPDATE_internal_snapshot_node)); } } @@ -516,31 +918,24 @@ static int delete_dead_snapshots_process_key(struct btree_trans *trans, return bch2_delete_dead_snapshot_key(trans, iter, k, dying->live_child); } -static bool skip_unrelated_snapshot_tree(struct btree_trans *trans, struct btree_iter *iter, u64 *prev_inum) +static int delete_dead_snapshot_keys_v1_btree(struct btree_trans *trans, enum btree_id btree) { struct bch_fs *c = trans->c; struct snapshot_delete *d = &c->snapshots.delete; - u64 inum = iter->btree_id != BTREE_ID_inodes - ? iter->pos.inode - : iter->pos.offset; - - if (*prev_inum == inum) - return false; + CLASS(disk_reservation, res)(c); - *prev_inum = inum; + try(for_each_btree_key_commit(trans, iter, + btree, POS_MIN, + BTREE_ITER_prefetch|BTREE_ITER_all_snapshots, k, + &res.r, NULL, BCH_TRANS_COMMIT_no_enospc, ({ + bch2_progress_update_iter(trans, &d->progress, &iter); - bool ret = !snapshot_list_has_id(&d->deleting_from_trees, - bch2_snapshot_tree(c, iter->pos.snapshot)); - if (unlikely(ret)) { - struct bpos pos = iter->pos; - pos.snapshot = 0; - if (iter->btree_id != BTREE_ID_inodes) - pos.offset = U64_MAX; - bch2_btree_iter_set_pos(iter, bpos_nosnap_successor(pos)); - } + bch2_disk_reservation_put(c, &res.r); + delete_dead_snapshots_process_key(trans, &iter, k); + }))); - return ret; + return 0; } static int delete_dead_snapshot_keys_v1(struct btree_trans *trans) @@ -552,26 +947,14 @@ static int delete_dead_snapshot_keys_v1(struct btree_trans *trans) d->progress.silent = true; d->version = 1; - for (unsigned btree = 0; btree < BTREE_ID_NR; btree++) { - CLASS(disk_reservation, res)(c); - u64 prev_inum = 0; + for (unsigned btree = 0; btree < BTREE_ID_NR; btree++) + if (btree_type_has_snapshots(btree) && btree != BTREE_ID_inodes) + try(delete_dead_snapshot_keys_v1_btree(trans, btree)); - if (!btree_type_has_snapshots(btree)) - continue; - - try(for_each_btree_key_commit(trans, iter, - btree, POS_MIN, - BTREE_ITER_prefetch|BTREE_ITER_all_snapshots, k, - &res.r, NULL, BCH_TRANS_COMMIT_no_enospc, ({ - bch2_progress_update_iter(trans, &d->progress, &iter); - - if (skip_unrelated_snapshot_tree(trans, &iter, &prev_inum)) - continue; - - bch2_disk_reservation_put(c, &res.r); - delete_dead_snapshots_process_key(trans, &iter, k); - }))); - } + /* + * fsck assumes that we'll process the inodes btree last: + */ + try(delete_dead_snapshot_keys_v1_btree(trans, BTREE_ID_inodes)); return 0; } @@ -597,7 +980,6 @@ static int delete_dead_snapshot_keys_v2(struct btree_trans *trans) struct bch_fs *c = trans->c; struct snapshot_delete *d = &c->snapshots.delete; CLASS(disk_reservation, res)(c); - u64 prev_inum = 0; bch2_progress_init(&d->progress, __func__, c, BIT_ULL(BTREE_ID_inodes), 0); d->progress.silent = true; @@ -607,11 +989,12 @@ static int delete_dead_snapshot_keys_v2(struct btree_trans *trans) BTREE_ITER_prefetch|BTREE_ITER_all_snapshots); /* - * First, delete extents/dirents/xattrs + * First, delete extents/dirents/xattrs and damage keys * * If an extent/dirent/xattr is present in a given snapshot ID an inode - * must also be present in that same snapshot ID, so we can use this to - * greatly accelerate scanning: + * must also be present in that same snapshot ID (and a damage key has + * an inode at its exact position - enforced by check_damage), so we + * can use this to greatly accelerate scanning: */ while (1) { @@ -623,9 +1006,6 @@ static int delete_dead_snapshot_keys_v2(struct btree_trans *trans) bch2_progress_update_iter(trans, &d->progress, &iter); - if (skip_unrelated_snapshot_tree(trans, &iter, &prev_inum)) - continue; - if (snapshot_id_dying(d, k.k->p.snapshot)) { struct bpos start = POS(k.k->p.offset, 0); struct bpos end = POS(k.k->p.offset, U64_MAX); @@ -633,6 +1013,9 @@ static int delete_dead_snapshot_keys_v2(struct btree_trans *trans) try(delete_dead_snapshot_keys_range(trans, &res.r, BTREE_ID_extents, start, end)); try(delete_dead_snapshot_keys_range(trans, &res.r, BTREE_ID_dirents, start, end)); try(delete_dead_snapshot_keys_range(trans, &res.r, BTREE_ID_xattrs, start, end)); + try(delete_dead_snapshot_keys_range(trans, &res.r, BTREE_ID_damage, + POS(0, k.k->p.offset), + SPOS(0, k.k->p.offset, U32_MAX))); bch2_btree_iter_set_pos(&iter, POS(0, k.k->p.offset + 1)); } else { @@ -640,16 +1023,73 @@ static int delete_dead_snapshot_keys_v2(struct btree_trans *trans) } } + /* + * The scan above located keys through the inodes btree, so deleting + * inode keys destroys the index it used: anything left in the other + * btrees at a dying snapshot becomes unfindable, by this pass and by + * every later one. Check while it's still repairable - the + * check_no_data licenses at the end of deletion only fire once the + * inodes are already gone. + */ + CLASS(printbuf, msg)(); + u64 bad_btrees = 0; + try(dying_snapshots_content_btrees(c, d, &msg, &bad_btrees)); + + if (unlikely(bad_btrees)) { + /* + * Accounting is derived from the keys themselves, so it doesn't + * go through the index above and can see what that scan missed. + * The v1 scan doesn't use the index either - rescan with it, on + * the btrees accounting named and no others. + */ + prt_str(&msg, "\nfalling back to the v1 scan"); + bch2_print_str(c, KERN_NOTICE, msg.buf); + + /* + * Retarget the progress indicator: it was initialized for the + * inodes btree, which is not what we're about to walk. Nothing + * after this loop updates progress, so this is the last word, + * and version says the run degraded. + */ + bch2_progress_init(&d->progress, __func__, c, bad_btrees, 0); + d->progress.silent = true; + d->version = 1; + + for (unsigned btree = 0; btree < BTREE_ID_NR; btree++) + if (bad_btrees & BIT_ULL(btree)) + try(delete_dead_snapshot_keys_v1_btree(trans, btree)); + + printbuf_reset(&msg); + bad_btrees = 0; + try(dying_snapshots_content_btrees(c, d, &msg, &bad_btrees)); + } + + if (unlikely(bad_btrees)) { + /* + * v1 found nothing and the keys are still accounted, so nothing + * is hiding behind a missing inode - the count is what's wrong. + * No content passes: their key_has_snapshot repairs exist to + * uphold the invariant v1 doesn't need. Refuse anyway - the + * inode keys below are the only way left to find anything that + * is in fact stranded. + */ + int ret = bch2_run_explicit_recovery_pass(c, &msg, + BCH_RECOVERY_PASS_check_allocations, 0); + + bch_err(c, "%s", msg.buf); + + if (bch2_err_matches(ret, BCH_ERR_cannot_rewind_recovery)) + ret = 0; + + return ret ?: bch_err_throw(c, EINVAL_snapshot_delete_with_data); + } + /* Then the inodes */ - prev_inum = 0; try(for_each_btree_key_commit(trans, iter, BTREE_ID_inodes, POS_MIN, BTREE_ITER_prefetch|BTREE_ITER_all_snapshots, k, &res.r, NULL, BCH_TRANS_COMMIT_no_enospc, ({ - if (skip_unrelated_snapshot_tree(trans, &iter, &prev_inum)) - continue; - bch2_disk_reservation_put(c, &res.r); delete_dead_snapshots_process_key(trans, &iter, k); }))); @@ -669,13 +1109,26 @@ static int check_should_delete_leaf(struct btree_trans *trans, struct bkey_s_c_s return 0; case SNAPSHOT_STATE_will_delete: if (!s.v->subvol) { - if (bch2_fs_inconsistent_on(c->sb.version_upgrade_complete >= - bcachefs_metadata_version_per_dev_fragmentation_lru, - c, "snapshot leaf in invalid state\n%s", buf.buf)) - return 0; + /* + * A will_delete leaf with no subvolume backref is safe to + * delete once check_subvols has confirmed no live subvolume + * points at a non-live snapshot (it halts recovery if one + * does). Require that pass - it can run online - rather than + * scanning the subvolumes btree here, or trusting the + * filesystem version, which can't distinguish a legacy + * will_delete leaf from real corruption. + */ + try(bch2_require_recovery_pass(c, &buf, BCH_RECOVERY_PASS_check_subvols)); } else { + /* + * Raw lookup, not bch2_subvolume_get(): this is the + * deletion path, the one caller that must see the deleted + * tombstone rather than have it reported as ENOENT. + */ struct bch_subvolume subvol; - try(bch2_subvolume_get(trans, le32_to_cpu(s.v->subvol), true, &subvol)); + try(bch2_bkey_get_val_typed(trans, BTREE_ID_subvolumes, + POS(0, le32_to_cpu(s.v->subvol)), + BTREE_ITER_cached, subvolume, &subvol)); if (bch2_fs_inconsistent_on(bch2_subvolume_state(&subvol) != SUBVOLUME_STATE_deleted, c, "snapshot marked for deletion but subvolume not marked for deletion\n%s", @@ -709,9 +1162,21 @@ static int check_should_delete_leaf(struct btree_trans *trans, struct bkey_s_c_s } /* - * For a given snapshot, if it doesn't have a subvolume that points to it, and - * it doesn't have child snapshot nodes - it's now redundant and we can mark it - * as deleted. + * Sort one node: dead (no live descendant - keys are dropped) or redundant + * (exactly one live child - keys migrate to live_child). Two live children: + * nothing to do. + * + * The caller scans in ascending id order and a node's id is always below its + * parent's, so children are sorted before parents. Both cases need that: + * + * - A node whose children are all already on delete_leaves is itself dead and + * joins them, so a dead subtree accumulates bottom-up. It's torn down in + * that same order later, each node childless by its turn because deleting a + * child splices this node's pointer to zero. + * + * - A child that's itself redundant already has its own live_child recorded, + * so the lookup below returns the terminal of the whole collapse chain + * rather than the next node down, and keys move there in one hop. */ static int check_should_delete_snapshot(struct btree_trans *trans, struct bkey_s_c k) { @@ -731,14 +1196,12 @@ static int check_should_delete_snapshot(struct btree_trans *trans, struct bkey_s } /* - * The leaf check above is this body's last restart point: everything - * below is in-memory table lookups and list pushes, so a transaction - * restart replays the body having collected nothing. The lists aren't - * transactional - keep restartable work above this line, or - * collection double-adds on replay. (Repairs invalidate collected - * state differently: the deletion path resets the lists wholesale - * and rescans.) - * + * The loop's per-key commit can restart after the pushes below and + * replay this body - the lists aren't transactional, so every push + * must be idempotent: nodup adds and has_id guards, or collection + * double-adds on replay. (Repairs invalidate collected state + * differently: the deletion path resets the lists wholesale and + * rescans.) */ struct snapshot_delete *d = &c->snapshots.delete; u32 live_child = 0, nr_live_children = 0; @@ -788,7 +1251,7 @@ static int check_should_delete_snapshot(struct btree_trans *trans, struct bkey_s bch2_snapshot_tree(c, s.k->p.offset))); if (!nr_live_children) { - try(snapshot_list_add(c, &d->delete_leaves, s.k->p.offset)); + try(snapshot_list_add_nodup(c, &d->delete_leaves, s.k->p.offset)); } else { struct snapshot_interior_delete n = { .id = s.k->p.offset, @@ -800,10 +1263,13 @@ static int check_should_delete_snapshot(struct btree_trans *trans, struct bkey_s * nodes, but we still track them so that we can find * the correct live_child when deleting parents, above: */ - if (bch2_snapshot_state(s.v) != SNAPSHOT_STATE_no_keys) - try(darray_push(&d->delete_interior, n)); - else - try(darray_push(&d->no_keys, n)); + if (bch2_snapshot_state(s.v) != SNAPSHOT_STATE_no_keys) { + if (!interior_delete_has_id(&d->delete_interior, n.id)) + try(darray_push(&d->delete_interior, n)); + } else { + if (!interior_delete_has_id(&d->no_keys, n.id)) + try(darray_push(&d->no_keys, n)); + } } } @@ -887,9 +1353,16 @@ static int delete_dead_snapshots_locked(struct bch_fs *c) /* * For every snapshot node: If we have no live children and it's not - * pointed to by a subvolume, delete it: + * pointed to by a subvolume, delete it. + * + * The per-key commit is for the childless-no_keys fsck_err: its fix + * is out-of-band (the node is only collected here, deleted later), + * but the fsck_err queues its repair log entry on this trans - which + * would otherwise never commit, only be dropped at the next + * trans_begin (the iter.c dropped-updates WARN): */ - try(for_each_btree_key(trans, iter, BTREE_ID_snapshots, POS_MIN, 0, k, + try(for_each_btree_key_commit(trans, iter, BTREE_ID_snapshots, POS_MIN, 0, k, + NULL, NULL, 0, check_should_delete_snapshot(trans, k))); struct snapshot_delete *d = &c->snapshots.delete; @@ -911,13 +1384,40 @@ static int delete_dead_snapshots_locked(struct bch_fs *c) bch2_snapshot_delete_nodes_to_text(&buf, d, false); try(commit_do(trans, NULL, NULL, 0, bch2_trans_log_msg(trans, &buf))); + /* + * What each node holds going in - the same counters the check_no_data + * licenses read on the way out, so whatever is still there at the end + * is what the migration didn't move. + */ + CLASS(printbuf, node_data)(); + try(bch2_snapshot_delete_data_to_text(&node_data, c, d)); + bch_info(c, "%s", node_data.buf); + try(!bch2_request_incompat_feature(c, bcachefs_metadata_version_snapshot_deletion_v2) ? delete_dead_snapshot_keys_v2(trans) : delete_dead_snapshot_keys_v1(trans)); + /* + * Refusals first, and a refusal stops the whole deletion: nodes go one + * commit at a time, so refusing partway leaves the ones already deleted + * describing a tree shape the rest of the deletion no longer produces. + * The refusal schedules its own repair - deletion runs again after it. + * + * This can't precede the migration above: what the check reads is + * whether the keys that were supposed to move actually did. + */ + darray_for_each(d->delete_leaves, i) + try(lockrestart_do(trans, + bch2_snapshot_node_check_no_data(trans, *i, "leaf delete"))); + + darray_for_each(d->delete_interior, i) + try(lockrestart_do(trans, + bch2_snapshot_node_check_no_data(trans, i->id, "set_no_keys"))); + darray_for_each(d->delete_leaves, i) try(commit_do(trans, NULL, NULL, 0, - bch2_snapshot_node_delete(trans, *i, false))); + bch2_snapshot_node_check_deletable(trans, *i, false) ?: + bch2_snapshot_node_delete(trans, *i))); darray_for_each(d->delete_interior, i) try(commit_do(trans, NULL, NULL, 0, @@ -926,22 +1426,41 @@ static int delete_dead_snapshots_locked(struct bch_fs *c) return 0; } +/* + * A refusal means "repair first, then retry", not failure: the check that + * refused has scheduled the passes that fix what it found, and deletion is + * rescheduled the next time a dying snapshot is seen (bch2_mark_snapshot, + * bch2_check_snapshot_needs_deletion). Nothing has been done, so there is + * nothing wrong with the filesystem that going read-only would protect. + * + * These run as recovery passes, and bch2_run_recovery_passes() returns the + * first pass error it sees - which at startup fails the mount. So the refusals + * stop here. + */ +static bool snapshot_delete_refused(int ret) +{ + return ret == -BCH_ERR_EINVAL_snapshot_delete_with_data || + ret == -BCH_ERR_EINVAL_snapshot_delete_bad_topology; +} + +/* + * Serialization is recovery.run_lock, asserted below: the delete_dead_snapshots + * pass .fn runs under it (the framework holds run_lock while running passes), + * and the sysfs force-trigger takes it explicitly. So no separate lock is + * needed, and passes never run this concurrently. + */ int __bch2_delete_dead_snapshots(struct bch_fs *c) { struct snapshot_delete *d = &c->snapshots.delete; - if (!mutex_trylock(&d->lock)) - return 0; - - if (!test_and_clear_bit(BCH_FS_need_delete_dead_snapshots, &c->flags)) { - mutex_unlock(&d->lock); - return 0; - } + lockdep_assert_held(&c->recovery.run_lock); d->running = true; d->progress.pos = BBPOS_MIN; int ret = delete_dead_snapshots_locked(c); + if (snapshot_delete_refused(ret)) + ret = 0; scoped_guard(mutex, &d->progress_lock) { darray_exit(&d->deleting_from_trees); @@ -954,7 +1473,6 @@ int __bch2_delete_dead_snapshots(struct bch_fs *c) bch2_recovery_pass_set_no_ratelimit(c, BCH_RECOVERY_PASS_check_snapshots); - mutex_unlock(&d->lock); return ret; } @@ -966,33 +1484,6 @@ int bch2_delete_dead_snapshots(struct bch_fs *c) return __bch2_delete_dead_snapshots(c); } -void bch2_delete_dead_snapshots_work(struct work_struct *work) -{ - struct bch_fs *c = container_of(work, struct bch_fs, snapshots.delete.work); - - set_worker_desc("bcachefs-delete-dead-snapshots/%s", c->name); - - rcu_assign_pointer(c->snapshots.delete.thread, current); - bch2_delete_dead_snapshots(c); - rcu_assign_pointer(c->snapshots.delete.thread, NULL); - - enumerated_ref_put(&c->writes, BCH_WRITE_REF_delete_dead_snapshots); -} - -void bch2_delete_dead_snapshots_async(struct bch_fs *c) -{ - if (!c->opts.auto_snapshot_deletion) - return; - - if (!enumerated_ref_tryget(&c->writes, BCH_WRITE_REF_delete_dead_snapshots)) - return; - - BUG_ON(!test_bit(BCH_FS_may_go_rw, &c->flags)); - - if (!queue_work(system_long_wq, &c->snapshots.delete.work)) - enumerated_ref_put(&c->writes, BCH_WRITE_REF_delete_dead_snapshots); -} - static int bch2_get_dead_interior_snapshots(struct btree_trans *trans, struct bkey_s_c k, interior_delete_list *delete) { @@ -1025,7 +1516,7 @@ static int bch2_get_dead_interior_snapshots(struct btree_trans *trans, struct bk return 0; } -int bch2_delete_dead_interior_snapshots(struct bch_fs *c) +static int delete_dead_interior_snapshots(struct bch_fs *c) { CLASS(btree_trans, trans)(c); CLASS(interior_delete_list, delete)(); @@ -1044,6 +1535,29 @@ int bch2_delete_dead_interior_snapshots(struct bch_fs *c) try(bch2_check_snapshots_trans(trans)); + /* + * check_snapshots is licensed to change node states (e.g. + * repairing a stale-state legacy tombstone to deleted), so the + * pre-check collection is only good for deciding whether to run + * it - re-collect for the authoritative delete list: + */ + delete.nr = 0; + try(for_each_btree_key(trans, iter, BTREE_ID_snapshots, POS_MIN, 0, k, + bch2_get_dead_interior_snapshots(trans, k, &delete))); + } + + if (delete.nr) { + /* + * Refusals first: the fixup below commits every surviving child's + * new depth and skip[] for the tree shape these deletions produce, + * so a node refused after it leaves the children describing a + * deletion that never happened - skip[] pointing above parent, + * which validation rejects on the next write. + */ + darray_for_each(delete, i) + try(lockrestart_do(trans, + bch2_snapshot_node_check_deletable(trans, i->id, true))); + /* * Fixing children of deleted snapshots can't be done completely * atomically, if we crash between here and when we delete the interior @@ -1056,7 +1570,7 @@ int bch2_delete_dead_interior_snapshots(struct bch_fs *c) darray_for_each(delete, i) { int ret = commit_do(trans, NULL, NULL, 0, - bch2_snapshot_node_delete(trans, i->id, true)); + bch2_snapshot_node_delete(trans, i->id)); if (!bch2_err_matches(ret, EROFS)) bch_err_msg(c, ret, "deleting snapshot %u", i->id); if (ret) @@ -1067,6 +1581,15 @@ int bch2_delete_dead_interior_snapshots(struct bch_fs *c) return 0; } +int bch2_delete_dead_interior_snapshots(struct bch_fs *c) +{ + if (!c->opts.auto_snapshot_deletion) + return 0; + + int ret = delete_dead_interior_snapshots(c); + return snapshot_delete_refused(ret) ? 0 : ret; +} + static bool interior_snapshot_needs_delete(const struct bch_snapshot *s) { /* If there's one child, it's redundant and keys will be moved to the child */ @@ -1090,8 +1613,18 @@ int bch2_check_snapshot_needs_deletion(struct btree_trans *trans, struct bkey_s_ if (state == SNAPSHOT_STATE_no_keys) *nr_empty_interior += 1; else if (state == SNAPSHOT_STATE_will_delete || - interior_snapshot_needs_delete(&s)) - set_bit(BCH_FS_need_delete_dead_snapshots, &c->flags); + interior_snapshot_needs_delete(&s)) { + /* + * Schedule the deleter through the recovery-pass machinery, + * like bch2_mark_snapshot - this catches the interior + * single-child case, which mark_snapshot (will_delete only) + * doesn't. Ephemeral + best-effort: ignore the return. + */ + CLASS(printbuf, buf)(); + bch2_run_explicit_recovery_pass(c, &buf, + BCH_RECOVERY_PASS_delete_dead_snapshots, + RUN_RECOVERY_PASS_ephemeral); + } return 0; } diff --git a/fs/snapshots/snapshot.c b/fs/snapshots/snapshot.c index 5428795c1d..e14c2f024b 100644 --- a/fs/snapshots/snapshot.c +++ b/fs/snapshots/snapshot.c @@ -73,35 +73,171 @@ * creation is O(1) regardless of filesystem size. Many thousands or millions of * snapshots can be created, limited only by disk space. * + * \subsubsection{Snapshot invariants} + * + * Four properties hold on a consistent filesystem. They are stated here + * because the deletion process below depends on them, and because a violation + * of any one is repaired by a different fsck pass. + * + * \begin{description} + * \item[Key implies inode]\ A key in snapshot $X$ implies a key in the inodes + * btree at $X$, for the same inode number. Not merely an inode: a whiteout + * also satisfies it. This is what makes an inode's content locatable from + * the inodes btree alone, which is how deletion finds keys (below), so it is + * the load-bearing one. Enforced by \texttt{bch2\_check\_key\_has\_inode()} + * in every content pass. + * + * \item[Writes update the inode]\ Writing a key into a snapshot updates that + * inode in the same snapshot, which is what maintains the above. + * + * \item[Extents align across snapshots]\ Two extents in different snapshots + * either occupy exactly the same range or do not overlap at all. Partial + * overlap is invalid; the write path splits ancestors' extents so that a + * descendant's write lands exactly aligned. Checked by + * \texttt{check\_overlapping\_extents}. + * + * \item[Subvolumes point at leaves]\ A subvolume's snapshot field always names + * a leaf node, never an interior one, and snapshot deletion never repoints a + * subvolume --- only snapshot creation does. + * \end{description} + * * \subsubsection{Snapshot deletion} * - * Deleting a snapshot (or subvolume) marks it for asynchronous cleanup by a - * background thread. The cost of deletion is proportional to the volume of data - * in the deleted snapshot, since the thread must walk every snapshot-aware btree - * to remove or relocate affected keys. + * Deletion is not a single operation. It marks nodes, then reclaims them over + * one or more runs of the \texttt{delete\_dead\_snapshots} recovery pass, which + * also runs online. Cost is proportional to the data in the deleted snapshot: + * the pass has to find and move or drop every key stamped with its id. + * + * A node passes through states (\texttt{bch\_snapshot\_state}): + * + * \begin{description} + * \item[\texttt{live}]\ Normal. + * \item[\texttt{will\_delete}]\ A leaf no longer referenced by a subvolume, + * pending reclaim. The subvolume backref is kept: deletion checks it, and a + * \texttt{will\_delete} leaf with no subvolume pointing back is invalid. + * \item[\texttt{no\_keys}]\ An interior node whose keys have all been moved + * down. It stays in the tree because removing an interior node means + * rewriting depth and skiplist fields across arbitrarily many children, + * which cannot be done atomically at runtime. The splice happens at the next + * mount, in the single-threaded recovery context, where + * \texttt{check\_snapshots} can run afterwards. + * \item[\texttt{deleted}]\ Spliced out. + * \end{description} + * + * \texttt{delete\_dead\_snapshots} handles dead leaf nodes and redundant + * interior nodes: + * + * \begin{description} + * \item[Dead]\ No live descendant: a leaf no subvolume points at, or an + * interior node whose children are all dead. Nothing that survives sees its + * keys, so they're dropped. + * \item[Redundant]\ An interior node with exactly one live child. That child + * still sees the node's keys through inheritance, so they move down to it + * instead of being dropped. Where they move is \texttt{live\_child}. With + * two live children there's nowhere to collapse into and the node stays --- + * delete one child first. + * \end{description} + * + * One scan of the snapshots btree sorts every node into those two cases, in + * ascending id order. A node's id is always below its parent's (ids are + * allocated downward), so children are sorted before parents, and that gives + * two things. + * + * A node whose children are all dead is itself dead, and its children are + * already on the delete list when it's examined - so a dead subtree + * accumulates bottom-up. It's torn down in that same order, each node + * childless by its turn because deleting a child splices the parent's pointer + * to zero. \texttt{bch2\_snapshot\_node\_delete()} refuses a node that still + * has a child, which is what enforces it. + * + * And a node collapsing into a child that's itself collapsing gets that + * child's destination, already recorded. So \texttt{live\_child} is the + * terminal of the whole chain, not the next node down, and keys move there in + * one hop. * - * Deletion is two-phase: + * A pass collects the dying nodes, then: * * \begin{enumerate} - * \item \textbf{Runtime}: The background thread walks snapshot-aware btrees and - * removes keys belonging to dead snapshots. For leaf snapshots, keys are - * deleted or converted to whiteouts where ancestor visibility must be - * preserved. For interior nodes that have lost all but one child, keys are - * moved to the surviving child. - * - * \item \textbf{Next mount}: Interior node removal is deferred to recovery - * because it requires updating depth and skiplist fields atomically across - * the subtree, which is only safe in the single-threaded recovery context. + * \item \textbf{Content keys.} For each inode with a key in the inodes btree + * at a dying snapshot, move or drop that inum's extents, dirents, xattrs and + * damage keys. Note the direction: the scan is driven \emph{from} the inodes + * btree, and descends into the other btrees only for inums it finds there. + * That is the acceleration --- and it is why the key-implies-inode invariant + * is load-bearing. A content key whose snapshot has no inodes-btree key is + * invisible to this scan and is silently left behind. + * + * \item \textbf{Verify.} Before touching the inodes btree, check per-snapshot + * accounting for the content btrees. Deleting the inode keys destroys the + * index step 1 just navigated by, so anything still accounted at this point + * would become unfindable by this pass and every later one. If anything + * remains, stop without deleting. + * + * \item \textbf{Inode keys.} Now safe to move or drop. + * + * \item \textbf{Nodes.} Delete leaves; mark emptied interiors \texttt{no\_keys}. + * Both are gated on per-snapshot accounting reading zero --- a node with data + * still accounted to it is refused rather than emptied, to prevent data loss. * \end{enumerate} * - * A snapshot with two children cannot be deleted directly --- you must first - * delete one of its child snapshots. Multiple snapshot deletions are batched - * and processed together in a single pass. + * If accounting says step 1 didn't evict every key at a dying snapshot id, + * then there was a key with no inodes-btree key at its snapshot, and the scan + * never reached it. If that happens, the pass doesn't delete: it schedules + * \texttt{check\_extents}, \texttt{check\_dirents} or \texttt{check\_xattrs} + * for the btree that still accounts data. If that pass finds a key with no + * inodes-btree key at its snapshot, \texttt{bch2\_check\_key\_has\_inode()} + * inserts one --- an inode or a whiteout. Then the next + * \texttt{delete\_dead\_snapshots} run reaches the key through it. + * + * Keys move \emph{down}, from a dying node to its live descendant, and the + * inodes btree is always processed last. So the only skew an interrupted run + * can leave is a content key already moved while its inode has not been: the + * reverse cannot occur, and checks may rely on that. * - * Progress can be monitored via - * \texttt{/sys/fs/bcachefs//snapshot\_delete\_status}. The - * \texttt{auto\_snapshot\_deletion} mount option controls whether the background - * deletion thread runs automatically. + * Collapsing migrates keys down, so an interrupted run leaves them split + * between the node and its live child; see equivalence classes, below. + * + * Progress: \texttt{/sys/fs/bcachefs//snapshot\_delete\_status}. The + * \texttt{auto\_snapshot\_deletion} option controls whether it runs + * automatically. + * + * \subsubsection{Equivalence classes} + * + * If \texttt{delete\_dead\_snapshots} is interrupted partway through + * collapsing a redundant interior node, its keys are left split: some moved + * down to the live child, some still at the node. fsck runs before + * \texttt{delete\_dead\_snapshots}, so it runs on that. It can't wait for the + * collapse to finish either: if the pass stops at step 2 or 4, the tree stays + * that way across mounts, and what unblocks it is a repair fsck makes. + * + * If fsck compares raw snapshot ids, a split node looks like two snapshots + * that disagree. \texttt{check\_extents} counts the inode version at the node + * and the version at the child over keys divided between them, and gets + * \texttt{i\_sectors} wrong for both. \texttt{check\_overlapping\_extents} + * reads the two halves as extents in different snapshots, and reports invalid + * partial overlap. + * + * So fsck compares in the collapsed frame. + * \texttt{bch2\_snapshot\_redundant\_interior()} walks the collapse chain down + * and returns its terminal: the node the chain is provably collapsing into. + * Every node on the chain returns the same terminal, and those nodes are one + * equivalence class. Converting both sides before comparing makes the node and + * its child the same snapshot, so a half-migrated key is not a false positive. + * \texttt{inode\_walker} keeps one entry per class, at the terminal, so an + * inode a repair writes back lands in the destination snapshot; + * \texttt{snapshots\_seen} keeps its overwrite list in terminals + * (\texttt{pos\_equiv}). + * + * A comparison belongs in the collapsed frame only if what consumes its answer + * does. \texttt{bch2\_check\_key\_has\_inode()} does not: + * \texttt{delete\_dead\_snapshot\_keys\_v2()} descends into an inum's content + * btrees only where the inodes btree has a key at exactly the dying snapshot + * id, whiteouts included. If that check compared terminals, then a key at the + * interior node whose inode key exists only at the child would look fine --- + * and that is the one case that breaks the scan. Those keys were never + * reported, never repaired and never migrated, and the node could never be + * emptied. So it compares raw ids, against + * \texttt{inode\_walker.inode\_snapshots}, which records every id the inodes + * btree has for that inum. * * \subsubsection{Space accounting} * @@ -219,6 +355,52 @@ bool bch2_snapshot_is_ancestor_early(struct bch_fs *c, u32 id, u32 ancestor) return __bch2_snapshot_is_ancestor_early(rcu_dereference(c->snapshots.table), id, ancestor); } +/* + * A redundant interior node: a live interior node with exactly one child that + * isn't being deleted. delete_dead_snapshots will collapse it into that child, + * migrating its keys down; interrupted, that leaves half-migrated keys split + * between the node and the child. + * + * fsck uses this to check such a node's keys/paths in the live child's view - + * the state the subtree is provably collapsing into - so a half-migrated key + * isn't a false positive. On a healthy fs there are none: taking a snapshot + * always makes a 2-child split, so a single-child interior only exists as the + * residue of a deletion. + * + * Walks the collapse chain and returns the live terminal it collapses into, or + * 0 if @id isn't a redundant interior. + */ +u32 bch2_snapshot_redundant_interior(struct bch_fs *c, u32 id) +{ + u32 orig = id; + guard(rcu)(); + struct snapshot_table *t = rcu_dereference(c->snapshots.table); + const struct snapshot_t *s = __snapshot_t(t, id); + if (!s) + return 0; + + while (true) { + u32 child = 0; + + for (unsigned i = 0; i < ARRAY_SIZE(s->children); i++) { + enum snapshot_id_state state = __bch2_snapshot_id_state(t, s->children[i]); + if (state == SNAPSHOT_ID_live) { + if (child) { + child = 0; + break; + } + child = s->children[i]; + } + } + + if (!child) + return s->state == SNAPSHOT_ID_live && id != orig ? id : 0; + + id = child; + s = __snapshot_t(t, id); + } +} + static inline u32 get_ancestor_below(struct snapshot_table *t, u32 id, u32 ancestor) { const struct snapshot_t *s = __snapshot_t(t, id); @@ -458,7 +640,43 @@ __cold void bch2_snapshot_to_text(struct printbuf *out, const struct bch_snapsho le32_to_cpu(s->skip[1]), le32_to_cpu(s->skip[2])); - prt_printf(out, " %s", bch2_snapshot_state_str(bch2_snapshot_state_compat(s))); + static const char * const obsolete_flag_strs[] = { + "will_delete", "subvol", "deleted", "no_keys", NULL + }; + u32 state = le32_to_cpu(s->state); + u32 flags = le32_to_cpu(s->flags); + + if (!state) { + /* Not upgraded: no state field, the obsolete flags are the truth */ + prt_printf(out, " %s (not upgraded, flags 0x%x:", + bch2_snapshot_state_str(bch2_snapshot_state_from_flags(s)), + flags); + prt_bitflags(out, obsolete_flag_strs, flags); + prt_printf(out, ")"); + } else if (!bch2_snapshot_state_valid(state)) { + prt_printf(out, " state 0x%x invalid (flags 0x%x:", state, flags); + prt_bitflags(out, obsolete_flag_strs, flags); + prt_printf(out, ")"); + } else { + prt_printf(out, " %s", bch2_snapshot_state_str(state)); + + /* + * The obsolete flags are dual-written shadows of the state field + * and subvol pointer (bch2_snapshot_state_set()); recompute what + * the dual-write would produce and print only divergence: + */ + struct bch_snapshot expect = *s; + bch2_snapshot_state_set(&expect, state); + + if (BCH_SNAPSHOT_WILL_DELETE_OBSOLETE(s) != BCH_SNAPSHOT_WILL_DELETE_OBSOLETE(&expect)) + prt_printf(out, " will_delete_obsolete=%llu", BCH_SNAPSHOT_WILL_DELETE_OBSOLETE(s)); + if (BCH_SNAPSHOT_SUBVOL_OBSOLETE(s) != BCH_SNAPSHOT_SUBVOL_OBSOLETE(&expect)) + prt_printf(out, " subvol_obsolete=%llu", BCH_SNAPSHOT_SUBVOL_OBSOLETE(s)); + if (BCH_SNAPSHOT_DELETED_OBSOLETE(s) != BCH_SNAPSHOT_DELETED_OBSOLETE(&expect)) + prt_printf(out, " deleted_obsolete=%llu", BCH_SNAPSHOT_DELETED_OBSOLETE(s)); + if (BCH_SNAPSHOT_NO_KEYS_OBSOLETE(s) != BCH_SNAPSHOT_NO_KEYS_OBSOLETE(&expect)) + prt_printf(out, " no_keys_obsolete=%llu", BCH_SNAPSHOT_NO_KEYS_OBSOLETE(s)); + } } __cold void bch2_snapshot_key_to_text(struct printbuf *out, struct bch_fs *c, @@ -506,7 +724,7 @@ int bch2_snapshot_validate(struct bch_fs *c, struct bkey_s_c k, id, k.k->p.offset); } - if (bkey_val_bytes(k.k) > offsetof(struct bch_snapshot, skip)) { + if (bkey_has_field(k.k, snapshot, skip)) { bkey_fsck_err_on(le32_to_cpu(s.v->skip[0]) > le32_to_cpu(s.v->skip[1]) || le32_to_cpu(s.v->skip[1]) > le32_to_cpu(s.v->skip[2]), c, snapshot_skiplist_not_normalized, @@ -521,7 +739,7 @@ int bch2_snapshot_validate(struct bch_fs *c, struct bkey_s_c k, } } - if (bkey_val_bytes(k.k) > offsetof(struct bch_snapshot, pad)) + if (bkey_has_field(k.k, snapshot, pad)) bkey_fsck_err_on(s.v->pad, c, snapshot_pad_nonzero, "reserved pad field nonzero"); @@ -535,15 +753,31 @@ int bch2_snapshot_validate(struct bch_fs *c, struct bkey_s_c k, * touched: */ if (from->from == BKEY_VALIDATE_commit && !c->opts.no_commit_validate) { - if (bkey_val_bytes(k.k) > offsetof(struct bch_snapshot, state)) - bkey_fsck_err_on(s.v->state && - !bch2_snapshot_state_valid(bch2_snapshot_state(s.v)), - c, snapshot_state_bad, - "invalid state 0x%x", le32_to_cpu(s.v->state)); + u32 state = bkey_has_field(k.k, snapshot, state) + ? bch2_snapshot_state(s.v) + : 0; + + bkey_fsck_err_on(state && !bch2_snapshot_state_valid(state), + c, snapshot_state_bad, + "invalid state 0x%x", state); - bkey_fsck_err_on(s.v->children[0] && s.v->subvol, + /* + * A subvol backref is only legal on a live or will_delete leaf: + * subvolumes only reference leaves, and no_keys/deleted nodes + * were interior when they were emptied - a dead leaf is deleted + * outright; the no_keys parking state exists only because an + * interior node can't be removed from the tree at runtime. + * will_delete retains the backref: it points at the subvolume's + * tombstone, which the deletion path checks + * (check_should_delete_leaf()). + */ + bkey_fsck_err_on(s.v->subvol && + (s.v->children[0] || + (state && + state != SNAPSHOT_STATE_live && + state != SNAPSHOT_STATE_will_delete)), c, snapshot_should_not_have_subvol, - "interior node with subvol (subvolumes only reference leaves)"); + "snapshot with subvol must be a live or will_delete leaf"); } fsck_err: return ret; @@ -599,9 +833,22 @@ static int bch2_mark_snapshot(struct btree_trans *trans, struct bkey_s_c new) memcpy(t->is_ancestor, is_ancestor, sizeof(t->is_ancestor)); if (state == SNAPSHOT_STATE_will_delete) { - set_bit(BCH_FS_need_delete_dead_snapshots, &c->flags); - if (c->recovery.pass_done > BCH_RECOVERY_PASS_delete_dead_snapshots) - bch2_delete_dead_snapshots_async(c); + /* + * Schedule the deleter. bch2_mark_snapshot may run as a + * BTREE_TRIGGER_atomic trigger - btree write locks held, + * committed to the commit - so the schedule must be + * ephemeral (no sb_lock) and best-effort: we ignore the + * return, since an error here would take the filesystem + * emergency read-only. + * + * In recovery this injects delete_dead_snapshots into the + * running passes so it runs (in listing order) before the + * content checks; otherwise it schedules the async runner. + */ + CLASS(printbuf, buf)(); + bch2_run_explicit_recovery_pass(c, &buf, + BCH_RECOVERY_PASS_delete_dead_snapshots, + RUN_RECOVERY_PASS_ephemeral); } } else { memset(t, 0, sizeof(*t)); @@ -679,6 +926,17 @@ int bch2_snapshot_lookup(struct btree_trans *trans, u32 id, return bch2_bkey_get_val_typed(trans, BTREE_ID_snapshots, POS(0, id), 0, snapshot, s); } +/* + * As bch2_snapshot_lookup(), but keeps the key: the topology checks report on + * nodes they didn't start from, and naming one by id alone leaves a field + * report with no way to see what was wrong with it. + */ +int bch2_snapshot_lookup_key(struct btree_trans *trans, u32 id, + struct bkey_i_snapshot *k) +{ + return bch2_bkey_get_i_typed(trans, BTREE_ID_snapshots, POS(0, id), 0, snapshot, k); +} + /* Key snapshot overwrite checks: */ int __bch2_get_snapshot_overwrites(struct btree_trans *trans, @@ -899,8 +1157,6 @@ void bch2_fs_snapshots_init_early(struct bch_fs *c) { mutex_init(&c->snapshots.table_lock); - INIT_WORK(&c->snapshots.delete.work, bch2_delete_dead_snapshots_work); - mutex_init(&c->snapshots.delete.lock); mutex_init(&c->snapshots.delete.progress_lock); mutex_init(&c->snapshots.unlinked_lock); diff --git a/fs/snapshots/snapshot.h b/fs/snapshots/snapshot.h index 71b9f7b120..771f42eff4 100644 --- a/fs/snapshots/snapshot.h +++ b/fs/snapshots/snapshot.h @@ -211,6 +211,8 @@ static inline bool bch2_snapshot_exists(struct bch_fs *c, u32 id) return bch2_snapshot_id_state(c, id) == SNAPSHOT_ID_live; } +u32 bch2_snapshot_redundant_interior(struct bch_fs *, u32); + static inline int bch2_snapshot_is_internal_node(struct bch_fs *c, u32 id) { guard(rcu)(); @@ -350,8 +352,8 @@ u32 bch2_snapshot_tree_next(struct bch_fs *, u32, unsigned *); int bch2_snapshot_lookup(struct btree_trans *trans, u32 id, struct bch_snapshot *s); -int bch2_snapshot_get_subvol(struct btree_trans *, u32, - struct bch_subvolume *); +int bch2_snapshot_lookup_key(struct btree_trans *trans, u32 id, + struct bkey_i_snapshot *k); /* only exported for tests: */ int bch2_snapshot_node_create(struct btree_trans *, u32, @@ -391,6 +393,10 @@ static inline int bch2_get_snapshot_overwrites(struct btree_trans *trans, } int bch2_snapshot_node_set_deleted(struct btree_trans *, u32); +int bch2_snapshot_node_delete(struct btree_trans *, u32); +int bch2_snapshot_node_undelete(struct btree_trans *, struct bkey_i_snapshot *); +int bch2_snapshot_accounting_totals(struct bch_fs *, u32, u64 *, u64 *, + u64 *, struct printbuf *); int __bch2_key_has_snapshot_overwrites(struct btree_trans *, enum btree_id, struct bpos); @@ -410,8 +416,6 @@ int bch2_delete_dead_snapshot_key(struct btree_trans *, struct btree_iter *, int __bch2_delete_dead_snapshots(struct bch_fs *); int bch2_delete_dead_snapshots(struct bch_fs *); -void bch2_delete_dead_snapshots_work(struct work_struct *); -void bch2_delete_dead_snapshots_async(struct bch_fs *); void bch2_snapshot_delete_status_to_text(struct printbuf *, struct bch_fs *); int bch2_delete_dead_interior_snapshots(struct bch_fs *); diff --git a/fs/snapshots/subvolume.c b/fs/snapshots/subvolume.c index 324f90cae9..32d50fba68 100644 --- a/fs/snapshots/subvolume.c +++ b/fs/snapshots/subvolume.c @@ -127,9 +127,9 @@ static int check_subvol(struct btree_trans *trans, } /* - * A tombstone: it exists only as deletion's witness, reaped when its - * snapshot node is deleted - none of the live-subvolume invariants - * apply (the sweep may already have erased its root inode): + * A tombstone: it exists only so deletion can check it, and is reaped + * when its snapshot node is deleted - none of the live-subvolume + * invariants apply (the sweep may already have erased its root inode): */ if (bch2_subvolume_state_compat(&subvol) == SUBVOLUME_STATE_deleted) return 0; @@ -151,6 +151,36 @@ static int check_subvol(struct btree_trans *trans, if (ret) return ret; + /* + * Settle the edge before anything else looks at this snapshot. We are + * walking a ref, so the backref is what says whether we own the target, + * and every repair below acts on the snapshot as if we do. A second + * subvolume pointing at the same node is the case that makes this load + * bearing: the backref names the real owner, so establish that first + * rather than letting whichever subvolume iterates last take the node. + */ + u32 backref = le32_to_cpu(snapshot.subvol); + + if (backref && backref != k.k->p.offset) { + struct bch_subvolume other; + int ret2 = bch2_subvolume_get(trans, backref, false, &other); + if (ret2 && !bch2_err_matches(ret2, ENOENT)) + return ret2; + + if (!ret2 && le32_to_cpu(other.snapshot) == snapid) { + CLASS(bch_log_msg, msg)(c); + + prt_printf(&msg.m, "snapshot %u is claimed by subvolume %u, which it backrefs, and also by %llu:\n", + snapid, backref, k.k->p.offset); + bch2_bkey_val_to_text(&msg.m, c, k); + prt_newline(&msg.m); + bch2_snapshot_to_text(&msg.m, &snapshot); + msg.m.suppress = !bch2_count_fsck_err(c, snapshot_subvol_backref_wrong, &msg.m); + + return bch_err_throw(c, fsck_repair_unimplemented); + } + } + /* * Subvolumes only reference leaves; an interior target means a pointer * was re-aimed by damage or a snapshot creation half-completed. No @@ -177,26 +207,51 @@ static int check_subvol(struct btree_trans *trans, } /* - * A live subvolume's snapshot must be live, unconditionally - a - * fraudulent deletion state poisons every later pass that touches - * this snapshot's keys, whether or not the backref still agrees: + * A live subvolume's snapshot must be live and must point back at it, + * and the subvolume is authoritative for both: a fraudulent deletion + * state poisons every later pass that touches this snapshot's keys, and + * the subvolume knows its own id. + * + * It has to be repaired from this side because check_snapshots deadlocks + * on it: its state repair (snapshot_subvol_state_mismatch) is gated on + * the backref, and its backref repair is gated on the state already + * being live - so a node that is both non-live and backref-less is + * invisible to each. That is exactly what a torn snapshot deletion + * leaves behind: will_delete set and the backref cleared, but the + * subvolume tombstone never landed. Here there is no ambiguity and + * nothing to search for - we are the claimant. + * + * Backref before state: SUBVOL_OBSOLETE is derived from ->subvol, so + * bch2_snapshot_state_set() needs it already assigned. */ - if (bch2_snapshot_state_compat(&snapshot) != SNAPSHOT_STATE_live) { - prt_printf(&buf, "subvolume points to a snapshot that isn't live:\n"); - bch2_bkey_val_to_text(&buf, c, k); - prt_str(&buf, "\n"); - bch2_snapshot_to_text(&buf, &snapshot); - bch_err(c, "%s", buf.buf); - return bch_err_throw(c, EINVAL_snapshot_subvol_edge_bad); + struct bkey_i_snapshot *n = NULL; + + if (fsck_err_on(backref != k.k->p.offset, + trans, snapshot_subvol_backref_wrong, + "subvolume points to a snapshot that doesn't point back:\n%s", + (printbuf_reset(&buf), + bch2_bkey_val_to_text(&buf, c, k), + prt_newline(&buf), + bch2_snapshot_to_text(&buf, &snapshot), + buf.buf))) { + n = errptr_try(bch2_bkey_get_mut_typed(trans, BTREE_ID_snapshots, + POS(0, snapid), 0, snapshot)); + n->v.subvol = cpu_to_le32(k.k->p.offset); + snapshot = n->v; } - if (le32_to_cpu(snapshot.subvol) != k.k->p.offset) { - prt_printf(&buf, "subvolume points to a snapshot that doesn't point back:\n"); - bch2_bkey_val_to_text(&buf, c, k); - prt_str(&buf, "\n"); - bch2_snapshot_to_text(&buf, &snapshot); - bch_err(c, "%s", buf.buf); - return bch_err_throw(c, EINVAL_snapshot_subvol_edge_bad); + if (fsck_err_on(bch2_snapshot_state_compat(&snapshot) != SNAPSHOT_STATE_live, + trans, snapshot_subvol_state_mismatch, + "subvolume points to a snapshot that isn't live:\n%s", + (printbuf_reset(&buf), + bch2_bkey_val_to_text(&buf, c, k), + prt_newline(&buf), + bch2_snapshot_to_text(&buf, &snapshot), + buf.buf))) { + n = n ?: errptr_try(bch2_bkey_get_mut_typed(trans, BTREE_ID_snapshots, + POS(0, snapid), 0, snapshot)); + bch2_snapshot_state_set(&n->v, SNAPSHOT_STATE_live); + snapshot = n->v; } if (fsck_err_on(k.k->p.offset == BCACHEFS_ROOT_SUBVOL && @@ -328,6 +383,7 @@ static int check_subvol_child(struct btree_trans *trans, return ret; if (fsck_err_on(ret || + bch2_subvolume_state_compat(&s) != SUBVOLUME_STATE_live || le32_to_cpu(s.fs_path_parent) != child_k.k->p.inode, trans, subvol_children_bad, "incorrect entry in subvolume_children btree %llu:%llu", @@ -335,8 +391,8 @@ static int check_subvol_child(struct btree_trans *trans, try(bch2_btree_delete_at(trans, child_iter, 0)); /* - * A missing subvolume was the verdict (entry is stray, deleted - * above), not an error - don't fail the pass with it: + * A missing or deleted subvolume was the verdict (entry is stray, + * deleted above), not an error - don't fail the pass with it: */ ret = 0; fsck_err: @@ -373,7 +429,7 @@ int bch2_subvolume_validate(struct bch_fs *c, struct bkey_s_c k, c, subvol_inode_bad, "invalid inode"); - if (bkey_val_bytes(k.k) > offsetof(struct bch_subvolume, pad)) + if (bkey_has_field(k.k, subvolume, pad)) bkey_fsck_err_on(subvol.v->pad, c, subvol_pad_nonzero, "reserved pad field nonzero"); @@ -386,7 +442,7 @@ int bch2_subvolume_validate(struct bch_fs *c, struct bkey_s_c k, * the trigger has seen them: */ if (from->from == BKEY_VALIDATE_commit && !c->opts.no_commit_validate) { - if (bkey_val_bytes(k.k) > offsetof(struct bch_subvolume, state)) + if (bkey_has_field(k.k, subvolume, state)) bkey_fsck_err_on(subvol.v->state && !bch2_subvolume_state_valid(bch2_subvolume_state(subvol.v)), c, subvol_state_bad, @@ -435,7 +491,7 @@ __cold void bch2_subvolume_to_text(struct printbuf *out, struct bch_fs *c, le64_to_cpu(s.v->inode), le32_to_cpu(s.v->snapshot)); - if (bkey_val_bytes(s.k) > offsetof(struct bch_subvolume, creation_parent)) { + if (bkey_has_field(s.k, subvolume, creation_parent)) { prt_printf(out, " creation_parent %u", le32_to_cpu(s.v->creation_parent)); prt_printf(out, " fs_parent %u", le32_to_cpu(s.v->fs_path_parent)); } @@ -447,7 +503,24 @@ __cold void bch2_subvolume_to_text(struct printbuf *out, struct bch_fs *c, struct bch_subvolume v; bkey_val_copy_pad(&v, s); - prt_printf(out, " %s", bch2_subvolume_state_str(bch2_subvolume_state_compat(&v))); + + u32 state = le32_to_cpu(v.state); + if (!state) { + /* Not upgraded: no state field, the obsolete flag is the truth */ + prt_printf(out, " %s (not upgraded, unlinked_obsolete=%llu)", + bch2_subvolume_state_str(bch2_subvolume_state_from_flags(&v)), + BCH_SUBVOLUME_UNLINKED_OBSOLETE(&v)); + } else if (!bch2_subvolume_state_valid(state)) { + prt_printf(out, " state 0x%x invalid (unlinked_obsolete=%llu)", + state, BCH_SUBVOLUME_UNLINKED_OBSOLETE(&v)); + } else { + prt_printf(out, " %s", bch2_subvolume_state_str(state)); + + /* dual-written shadow (bch2_subvolume_state_set()); print divergence: */ + if (BCH_SUBVOLUME_UNLINKED_OBSOLETE(&v) != (state != SUBVOLUME_STATE_live)) + prt_printf(out, " unlinked_obsolete=%llu", + BCH_SUBVOLUME_UNLINKED_OBSOLETE(&v)); + } } static int subvolume_children_mod(struct btree_trans *trans, struct bpos pos, bool set) @@ -485,18 +558,51 @@ int bch2_subvol_has_children(struct btree_trans *trans, u32 subvol) : 0; } +static __always_inline int +bch2_subvolume_get_key_inlined(struct btree_trans *trans, unsigned subvol, + bool inconsistent_if_not_found, + struct bkey_i_subvolume *k) +{ + int ret = bch2_bkey_get_i_typed(trans, BTREE_ID_subvolumes, POS(0, subvol), + BTREE_ITER_cached, subvolume, k); + /* + * A deleted subvolume is a tombstone, kept for deletion to check and + * not yet reaped: to everyone but the deletion/reaping path it's gone, so + * report it as such rather than handing back a dead subvolume - and let + * it flow into the inconsistent_if_not_found handling below. + */ + if (!ret && bch2_subvolume_state_compat(&k->v) == SUBVOLUME_STATE_deleted) + ret = bch_err_throw(trans->c, ENOENT_subvolume_deleted); + if (bch2_err_matches(ret, ENOENT) && inconsistent_if_not_found) + ret = bch2_subvolume_missing(trans->c, subvol) ?: ret; + return ret; +} + static __always_inline int bch2_subvolume_get_inlined(struct btree_trans *trans, unsigned subvol, bool inconsistent_if_not_found, struct bch_subvolume *s) { - int ret = bch2_bkey_get_val_typed(trans, BTREE_ID_subvolumes, POS(0, subvol), - BTREE_ITER_cached, subvolume, s); - if (bch2_err_matches(ret, ENOENT) && inconsistent_if_not_found) - ret = bch2_subvolume_missing(trans->c, subvol) ?: ret; + struct bkey_i_subvolume k; + int ret = bch2_subvolume_get_key_inlined(trans, subvol, + inconsistent_if_not_found, &k); + if (!ret) + *s = k.v; return ret; } +/* + * Fetch the whole key, not just the value: fsck uses this so its error + * messages can print the subvolume, which is how a reader tells a missing + * root inode from a subvolume pointing at the wrong snapshot. + */ +int bch2_subvolume_get_key(struct btree_trans *trans, unsigned subvol, + bool inconsistent_if_not_found, + struct bkey_i_subvolume *k) +{ + return bch2_subvolume_get_key_inlined(trans, subvol, inconsistent_if_not_found, k); +} + int bch2_subvolume_get(struct btree_trans *trans, unsigned subvol, bool inconsistent_if_not_found, struct bch_subvolume *s) @@ -504,6 +610,29 @@ int bch2_subvolume_get(struct btree_trans *trans, unsigned subvol, return bch2_subvolume_get_inlined(trans, subvol, inconsistent_if_not_found, s); } +/* + * BCH_INODE_unlinked is allowed on a directory only if it's a subvolume + * root and the subvolume is unlinked - this answers the second half. + * + * That's the only window fsck can see a legitimately flagged directory: + * once the subvolume is tombstoned its snapshot is will_delete and + * check_inode skips those keys - the sweep owns them. A tombstoned or + * missing subvolume here is the caller's cue to repair, not exempt. + * + * Returns: < 0 error, 0 no, 1 yes + */ +int bch2_subvolume_is_unlinked(struct btree_trans *trans, u32 subvolid) +{ + struct bch_subvolume s; + int ret = bch2_subvolume_get(trans, subvolid, false, &s); + if (bch2_err_matches(ret, ENOENT)) + return 0; + if (ret) + return ret; + + return bch2_subvolume_state_compat(&s) == SUBVOLUME_STATE_unlinked; +} + int bch2_subvol_is_ro_trans(struct btree_trans *trans, u32 subvol, u32 *snapid) { struct bch_subvolume s; @@ -524,15 +653,6 @@ int bch2_subvol_is_ro(struct bch_fs *c, u32 subvol) return lockrestart_do(trans, bch2_subvol_is_ro_trans(trans, subvol, &snapshot)); } -int bch2_snapshot_get_subvol(struct btree_trans *trans, u32 snapshot, - struct bch_subvolume *subvol) -{ - struct bch_snapshot snap; - - return bch2_snapshot_lookup(trans, snapshot, &snap) ?: - bch2_subvolume_get(trans, le32_to_cpu(snap.subvol), true, subvol); -} - int __bch2_subvolume_get_snapshot(struct btree_trans *trans, u32 subvolid, u32 *snapid, bool warn) { @@ -562,7 +682,12 @@ static int bch2_subvolume_reparent(struct btree_trans *trans, if (k.k->type != KEY_TYPE_subvolume) return 0; - if (bkey_val_bytes(k.k) > offsetof(struct bch_subvolume, creation_parent) && + /* + * A key with no creation_parent predates the field, so it isn't known + * to be anyone's child - skip it, same as one naming a different + * parent. + */ + if (!bkey_has_field(k.k, subvolume, creation_parent) || le32_to_cpu(bkey_s_c_to_subvolume(k).v->creation_parent) != old_parent) return 0; @@ -662,7 +787,16 @@ static int __bch2_subvolume_set_deleted(struct btree_trans *trans, u32 subvolid) static int bch2_subvolume_set_deleted(struct btree_trans *trans, u32 subvolid) { - int ret = bch2_subvolumes_reparent(trans, subvolid) ?: + /* + * The fsck caller (check_subvol's unlinked branch) can arrive with + * repairs - and their fsck_err journal log entries - still queued; + * reparent's lockrestart_do would drop them at trans_begin (the + * iter.c dropped-updates WARN). Flush first: commit_lazy is free + * when nothing is queued, and its restart-on-success re-drives + * check_subvol, whose committed fixes don't refire: + */ + int ret = bch2_trans_commit_lazy(trans, NULL, NULL, BCH_TRANS_COMMIT_no_enospc) ?: + bch2_subvolumes_reparent(trans, subvolid) ?: commit_do(trans, NULL, NULL, BCH_TRANS_COMMIT_no_enospc, __bch2_subvolume_set_deleted(trans, subvolid)); return ret; diff --git a/fs/snapshots/subvolume.h b/fs/snapshots/subvolume.h index e6c068e7ca..d3820fbc7e 100644 --- a/fs/snapshots/subvolume.h +++ b/fs/snapshots/subvolume.h @@ -75,6 +75,9 @@ int bch2_subvolume_trigger(struct btree_trans *, struct btree_trigger_op); int bch2_subvol_has_children(struct btree_trans *, u32); int bch2_subvolume_get(struct btree_trans *, unsigned, bool, struct bch_subvolume *); +int bch2_subvolume_get_key(struct btree_trans *, unsigned, + bool, struct bkey_i_subvolume *); +int bch2_subvolume_is_unlinked(struct btree_trans *, u32); int __bch2_subvolume_get_snapshot(struct btree_trans *, u32, u32 *, bool); int bch2_subvolume_get_snapshot(struct btree_trans *, u32, u32 *); diff --git a/fs/snapshots/types.h b/fs/snapshots/types.h index ddfaa6c53b..fcc9b6ee5d 100644 --- a/fs/snapshots/types.h +++ b/fs/snapshots/types.h @@ -61,10 +61,6 @@ struct snapshot_interior_delete { DEFINE_DARRAY_NAMED(interior_delete_list, struct snapshot_interior_delete); struct snapshot_delete { - struct mutex lock; - struct work_struct work; - struct task_struct __rcu *thread; - struct mutex progress_lock; snapshot_id_list deleting_from_trees; snapshot_id_list delete_leaves; diff --git a/fs/util/locking.c b/fs/util/locking.c new file mode 100644 index 0000000000..94b3597236 --- /dev/null +++ b/fs/util/locking.c @@ -0,0 +1,20 @@ +// SPDX-License-Identifier: GPL-2.0 + +/* + * Out-of-line homes for the util/locking.h Rust shims. See the header for why + * these can't be static inlines (duplicate wrap_static_fns wrappers across the + * two bindgen passes). + */ + +#include "bcachefs.h" +#include "util/locking.h" + +unsigned int rust_memalloc_noio_save(void) +{ + return memalloc_flags_save(PF_MEMALLOC_NOIO); +} + +void rust_memalloc_flags_restore(unsigned int flags) +{ + memalloc_flags_restore(flags); +} diff --git a/fs/util/locking.h b/fs/util/locking.h new file mode 100644 index 0000000000..2ba458baf7 --- /dev/null +++ b/fs/util/locking.h @@ -0,0 +1,87 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#ifndef _BCACHEFS_LOCKING_H +#define _BCACHEFS_LOCKING_H + +/* + * bcachefs locking primitives that bundle a lock with the memory-reclaim + * context it implies. See util/locking.rs for the Rust counterparts. + */ + +#include +#include +#include +#include + +/* + * mutex_noio - a mutex that also establishes a PF_MEMALLOC_NOIO scope while + * held. + * + * Many bcachefs mutexes - sb_lock above all - are taken precisely to guard + * allocations that must not recurse into reclaim IO: a filesystem that drives + * the block layer directly can't let reclaim loop back through the device it's + * allocating for. Pairing every such lock with a separate + * guard(memalloc_flags)(PF_MEMALLOC_NOIO) is easy to forget (and was, on many + * sb_lock sites). Folding the NOIO scope into the lock type makes it a property + * of the lock: holding it _is_ the NOIO context, and you can't take it without. + * + * Guard-only by design. The saved memalloc flags live in the guard object, so a + * raw lock/unlock pair would have nowhere to stash them; scoped use also + * guarantees the LIFO nesting that memalloc_flags_save/restore require. Use + * guard(mutex_noio)(&m) or scoped_guard(mutex_noio, &m). + */ +struct mutex_noio { + struct mutex lock; +}; + +static inline void mutex_noio_init(struct mutex_noio *m) +{ + mutex_init(&m->lock); +} + +DEFINE_LOCK_GUARD_1(mutex_noio, struct mutex_noio, + _T->flags = memalloc_flags_save(PF_MEMALLOC_NOIO); mutex_lock(&_T->lock->lock), + mutex_unlock(&_T->lock->lock); memalloc_flags_restore(_T->flags), + unsigned int flags) + +/* + * percpu_rwsem_noio - a percpu_rwsem that establishes a PF_MEMALLOC_NOIO scope + * while held, the percpu_rwsem analogue of mutex_noio. Used for rwsems like + * capacity.mark_lock that are taken over allocating work. Guards mirror the + * kernel's percpu_read/percpu_write, with _noio. + * + * A few hot paths take the lock raw (percpu_down_read on the inner + * percpu_rw_semaphore) rather than via the guard - that's sound only where the + * caller is already in a NOIO context (e.g. holding a locked btree_trans); + * such sites reach through .lock with a comment saying why. + */ +struct percpu_rwsem_noio { + struct percpu_rw_semaphore lock; +}; + +DEFINE_LOCK_GUARD_1(percpu_read_noio, struct percpu_rwsem_noio, + _T->flags = memalloc_flags_save(PF_MEMALLOC_NOIO); percpu_down_read(&_T->lock->lock), + percpu_up_read(&_T->lock->lock); memalloc_flags_restore(_T->flags), + unsigned int flags) + +DEFINE_LOCK_GUARD_1(percpu_write_noio, struct percpu_rwsem_noio, + _T->flags = memalloc_flags_save(PF_MEMALLOC_NOIO); percpu_down_write(&_T->lock->lock), + percpu_up_write(&_T->lock->lock); memalloc_flags_restore(_T->flags), + unsigned int flags) + +/* + * Bindgen shims for the Rust memalloc guards (util/locking.rs). + * memalloc_flags_save/restore are kernel static inlines outside bcachefs, and + * PF_MEMALLOC_NOIO is a bare #define that doesn't reach Rust; wrap them under + * bcachefs-owned rust_* names so the flag stays on the C side. Save is + * per-flag; restore just replays saved flags. + * + * These are real (out-of-line) functions, defined in util/locking.c, not static + * inlines: both the fs and bch_bindgen bindgen passes see this header, and a + * static inline would have each emit its own wrap_static_fns wrapper for the + * same symbol - a duplicate at link. A plain declaration binds to one shared + * definition. + */ +unsigned int rust_memalloc_noio_save(void); +void rust_memalloc_flags_restore(unsigned int flags); + +#endif /* _BCACHEFS_LOCKING_H */ diff --git a/fs/util/locking.rs b/fs/util/locking.rs new file mode 100644 index 0000000000..ab25e7f857 --- /dev/null +++ b/fs/util/locking.rs @@ -0,0 +1,42 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Rust counterparts to the primitives in util/locking.h. +//! +//! bcachefs establishes a memory-reclaim scope (PF_MEMALLOC_NOIO) while holding +//! certain locks, so allocations under the lock can't recurse into reclaim IO - +//! a filesystem driving the block layer directly mustn't let reclaim loop back +//! through the device it's allocating for. On the C side the lock type carries +//! the scope (`struct mutex_noio`); on the Rust side the guard is composed +//! explicitly, holding a [`MemallocFlags`] alongside the lock. +//! +//! [`MemallocFlags`] saves the current flags on construction and restores them +//! on drop, mirroring the C memalloc_flags_save/restore pairing - scoped (LIFO) +//! use only, as those primitives require. The flag itself stays on the C side +//! (util/locking.h's rust_memalloc_* shims): the PF_MEMALLOC_* #defines don't +//! reach Rust through bindgen. + +use crate::c; + +/// RAII guard for a process-context memalloc scope. Restores the previous +/// flags when dropped. +#[must_use = "the memalloc scope ends as soon as the guard is dropped"] +pub struct MemallocFlags { + saved: u32, +} + +impl MemallocFlags { + /// Enter a PF_MEMALLOC_NOIO scope: allocations may not recurse into reclaim + /// IO for as long as the guard is held. + pub fn noio() -> Self { + // SAFETY: rust_memalloc_noio_save only touches current->flags and + // returns the previous value, to be replayed by the paired restore. + Self { saved: unsafe { c::rust_memalloc_noio_save() } } + } +} + +impl Drop for MemallocFlags { + fn drop(&mut self) { + // SAFETY: `saved` is the value returned by the paired save above. + unsafe { c::rust_memalloc_flags_restore(self.saved) } + } +} diff --git a/fs/util/mod.rs b/fs/util/mod.rs index 70d82f37ee..494ef7bbf7 100644 --- a/fs/util/mod.rs +++ b/fs/util/mod.rs @@ -2,6 +2,7 @@ pub mod async_exec; pub mod bitmask; pub mod darray; pub mod kernel; +pub mod locking; pub mod printbuf; pub mod vstructs; diff --git a/fs/util/time_stats.c b/fs/util/time_stats.c index ff1d91785a..05dce0b2c4 100644 --- a/fs/util/time_stats.c +++ b/fs/util/time_stats.c @@ -104,8 +104,15 @@ static inline void time_stats_update_one(struct bch2_time_stats *stats, void __bch2_time_stats_clear_buffer(struct bch2_time_stats *stats, struct time_stat_buffer *b) { + /* + * The to_seq_buf paths flush other cpus' partially-full buffers: + * only [0, nr) hold real entries, the tail is leftovers from the + * previous fill cycle. (nr is read racily against the owning cpu's + * append; the bound also keeps a bad value from walking off the + * array.) + */ for (struct time_stat_buffer_entry *i = b->entries; - i < b->entries + ARRAY_SIZE(b->entries); + i < b->entries + min_t(size_t, b->nr, ARRAY_SIZE(b->entries)); i++) time_stats_update_one(stats, i->start, i->end); b->nr = 0; @@ -131,16 +138,39 @@ void __bch2_time_stats_update(struct bch2_time_stats *stats, u64 start, u64 end) if (!stats->buffer && mean_and_variance_get_median(stats->freq_stats_weighted) < 32000 && - stats->duration_stats.n > 1024) - stats->buffer = + stats->duration_stats.n > 1024) { + struct time_stat_buffer __percpu *b = alloc_percpu_gfp(struct time_stat_buffer, GFP_ATOMIC); + if (b) { + int cpu; + for_each_possible_cpu(cpu) + local_lock_init(&per_cpu_ptr(b, cpu)->lock); + stats->buffer = b; + } + } spin_unlock_irqrestore(&stats->lock, flags); } else { - guard(irqsave)(); + /* + * local_lock rather than plain irqsave: pins the cpu and + * excludes same-cpu updaters on all preemption models, and on + * PREEMPT_RT it's a sleeping lock, making the nested + * stats->lock in the buffer-full flush below legal there. + */ + local_lock_irqsave(&stats->buffer->lock, flags); struct time_stat_buffer *b = this_cpu_ptr(stats->buffer); - BUG_ON(b->nr >= ARRAY_SIZE(b->entries)); + /* + * Can't happen via the update paths themselves (per-cpu + * locked, flushed at exactly capacity): a bad nr means the + * buffer was scribbled or freed under us. Seen in the field + * (7.1.3, read completion path) - note it and discard rather + * than taking down the machine for a stats glitch. + */ + if (WARN_ONCE(b->nr >= ARRAY_SIZE(b->entries), + "bch2_time_stats: pcpu buffer nr %u >= %zu (corrupt), discarding", + b->nr, ARRAY_SIZE(b->entries))) + b->nr = 0; b->entries[b->nr++] = (struct time_stat_buffer_entry) { .start = start, .end = end @@ -148,6 +178,7 @@ void __bch2_time_stats_update(struct bch2_time_stats *stats, u64 start, u64 end) if (unlikely(b->nr == ARRAY_SIZE(b->entries))) time_stats_clear_buffer(stats, b); + local_unlock_irqrestore(&stats->buffer->lock, flags); } } diff --git a/fs/util/time_stats.h b/fs/util/time_stats.h index ac880c5230..e9e2cb7b98 100644 --- a/fs/util/time_stats.h +++ b/fs/util/time_stats.h @@ -24,6 +24,7 @@ #ifndef _BCACHEFS_TIME_STATS_H #define _BCACHEFS_TIME_STATS_H +#include #include #include #include @@ -60,6 +61,14 @@ struct quantiles { }; struct time_stat_buffer { + /* + * Protects nr/entries on the owning cpu: irq/preempt disable on + * !PREEMPT_RT, a real per-cpu lock on RT - which is what makes + * taking stats->lock (sleeping on RT) from the buffer-full flush + * legal there. Cross-cpu readers (to_seq_buf, reset) don't take + * it; they race the owner by design, bounded by nr. + */ + local_lock_t lock; unsigned nr; struct time_stat_buffer_entry { u64 start; diff --git a/fs/util/varint.c b/fs/util/varint.c index 6620ecae26..3349f21eb9 100644 --- a/fs/util/varint.c +++ b/fs/util/varint.c @@ -26,7 +26,7 @@ int bch2_varint_encode(u8 *out, u64 v) if (likely(bytes < 9)) { v <<= bytes; - v |= ~(~0 << (bytes - 1)); + v |= ~(~0U << (bytes - 1)); v_le = cpu_to_le64(v); memcpy(out, &v_le, bytes); } else { @@ -39,17 +39,18 @@ int bch2_varint_encode(u8 *out, u64 v) } /** - * bch2_varint_decode - encode a variable length integer + * bch2_varint_decode - decode a variable length integer * @in: varint to decode * @end: end of buffer to decode from * @out: on success, decoded integer - * Returns: size in bytes of the decoded integer - or -1 on failure (would - * have read past the end of the buffer) + * Returns: size in bytes of the decoded integer - or + * -BCH_ERR_varint_decode_error on failure (would have read past the end of + * the buffer) */ int bch2_varint_decode(const u8 *in, const u8 *end, u64 *out) { unsigned bytes = likely(in < end) - ? ffz(*in & 255) + 1 + ? ffz(*in) + 1 : 1; u64 v; @@ -101,8 +102,9 @@ int bch2_varint_encode_fast(u8 *out, u64 v) * @in: varint to decode * @end: end of buffer to decode from * @out: on success, decoded integer - * Returns: size in bytes of the decoded integer - or -1 on failure (would - * have read past the end of the buffer) + * Returns: size in bytes of the decoded integer - or + * -BCH_ERR_varint_decode_error on failure (would have read past the end of + * the buffer) * * This version assumes that it is safe to read at most 8 bytes past the end of * @end (we still return an error if the varint extends past @end). diff --git a/fs/vendor/kernel-rust/bindings/bindings_helper.h b/fs/vendor/kernel-rust/bindings/bindings_helper.h index 4547275a96..cfe9118fba 100644 --- a/fs/vendor/kernel-rust/bindings/bindings_helper.h +++ b/fs/vendor/kernel-rust/bindings/bindings_helper.h @@ -53,6 +53,7 @@ #include #include #include +#include // vendored: local_lock_t, embedded in time_stat_buffer #include #include #include diff --git a/fs/vfs/buffered.c b/fs/vfs/buffered.c index 6075bbe0a1..895add539d 100644 --- a/fs/vfs/buffered.c +++ b/fs/vfs/buffered.c @@ -253,33 +253,21 @@ static void bchfs_read(struct btree_trans *trans, ret = bch2_read_extent(trans, rbio, iter.pos, data_btree, k, offset_into_extent, flags); - if (ret) - goto err; - /* - * Careful there's a landmine here if bch2_read_extent() ever - * starts returning transaction restarts here. - * - * We've changed rbio->bi_iter.bi_size to be "bytes we can read - * from this extent" with the swap call, and we restore it - * below. That restore needs to come before checking for - * errors. - * - * But unlike bch2_read(), we use the rbio bvec iter, not one - * on the stack, so we can't do the restore right after the - * bch2_read_extent() call: we don't own that iterator anymore - * if BCH_READ_last_fragment is set, since we may have submitted - * that rbio instead of cloning it. - */ - if (flags & BCH_READ_last_fragment) + /* On successful BCH_READ_last_fragment submit we no longer own rbio: */ + if (!ret && (flags & BCH_READ_last_fragment)) break; swap(rbio->bio.bi_iter.bi_size, bytes); - bio_advance(&rbio->bio, bytes); err: - if (ret && - !bch2_err_matches(ret, BCH_ERR_transaction_restart)) + if (bch2_err_matches(ret, BCH_ERR_transaction_restart)) { + flags &= ~BCH_READ_last_fragment; + continue; + } + if (ret) break; + + bio_advance(&rbio->bio, bytes); } if (ret) { @@ -529,8 +517,8 @@ static void bch2_writepage_io_alloc(struct bch_fs *c, op->nr_replicas = nr_replicas; op->res.nr_replicas = nr_replicas; op->write_point = writepoint_hashed(inode->ei_last_dirtied); - op->subvol = inode->ei_inum.subvol; - op->pos = POS(inode->v.i_ino, sector); + op->subvol = inode_inum(inode).subvol; + op->pos = POS(inode_inum(inode).inum, sector); op->end_io = bch2_writepage_io_done; op->devs_need_flush = &inode->ei_devs_need_flush; op->wbio.bio.bi_iter.bi_sector = sector; @@ -705,9 +693,9 @@ static int __bch2_writepage(struct folio *folio, int bch2_writepages(struct address_space *mapping, struct writeback_control *wbc) { struct bch_fs *c = mapping->host->i_sb->s_fs_info; - struct bch_writepage_state *w = kzalloc(sizeof(*w), GFP_NOFS|__GFP_NOFAIL); + struct bch_writepage_state *w = kzalloc(sizeof(*w), GFP_NOIO|__GFP_NOFAIL); - w->tmp = mempool_alloc(&c->vfs.writepage_buf_pool, GFP_NOFS); + w->tmp = mempool_alloc(&c->vfs.writepage_buf_pool, GFP_NOIO); bch2_inode_opts_get_inode(c, &to_bch_ei(mapping->host)->ei_inode, &w->opts); diff --git a/fs/vfs/direct.c b/fs/vfs/direct.c index 6c604f10ca..2da8564867 100644 --- a/fs/vfs/direct.c +++ b/fs/vfs/direct.c @@ -263,8 +263,8 @@ static bool bch2_check_range_allocated(struct bch_fs *c, subvol_inum inum, break; if (k.k->p.snapshot != snapshot || - nr_replicas > bch2_bkey_replicas(c, k) || - (!compressed && bch2_bkey_sectors_compressed(c, k))) + nr_replicas > bch2_bkey_durability_safe(c, k).total || + (!compressed && bch2_bkey_durability_safe(c, k).sectors_compressed)) return false; } err: @@ -456,8 +456,8 @@ static __always_inline long bch2_dio_write_loop(struct dio_write *dio) dio->op.target = dio->op.opts.foreground_target; dio->op.write_point = writepoint_hashed((unsigned long) current); dio->op.nr_replicas = dio->op.opts.data_replicas; - dio->op.subvol = inode->ei_inum.subvol; - dio->op.pos = POS(inode->v.i_ino, (u64) req->ki_pos >> 9); + dio->op.subvol = inode_inum(inode).subvol; + dio->op.pos = POS(inode_inum(inode).inum, (u64) req->ki_pos >> 9); dio->op.devs_need_flush = &inode->ei_devs_need_flush; if (sync) diff --git a/fs/vfs/fiemap.c b/fs/vfs/fiemap.c index c744ffc0fc..1bb0ad9ec8 100644 --- a/fs/vfs/fiemap.c +++ b/fs/vfs/fiemap.c @@ -154,7 +154,7 @@ bch2_next_fiemap_pagecache_extent(struct btree_trans *trans, struct bch_inode_in */ bch2_bkey_buf_realloc(&cur->kbuf, sizeof(*delextent) / sizeof(u64)); delextent = bkey_extent_init(cur->kbuf.k); - delextent->k.p = POS(inode->ei_inum.inum, dend >> 9); + delextent->k.p = POS(inode_inum(inode).inum, dend >> 9); delextent->k.size = (dend - dstart) >> 9; bch2_bkey_append_ptr(trans->c, &delextent->k_i, ptr); @@ -169,11 +169,11 @@ static int bch2_next_fiemap_extent(struct btree_trans *trans, struct bch_fiemap_extent *cur) { u32 snapshot; - try(bch2_subvolume_get_snapshot(trans, inode->ei_inum.subvol, &snapshot)); + try(bch2_subvolume_get_snapshot(trans, inode_inum(inode).subvol, &snapshot)); CLASS(btree_iter, iter)(trans, BTREE_ID_extents, - SPOS(inode->ei_inum.inum, start, snapshot), 0); - struct bkey_s_c k = bkey_try(bch2_btree_iter_peek_max(&iter, &POS(inode->ei_inum.inum, end))); + SPOS(inode_inum(inode).inum, start, snapshot), 0); + struct bkey_s_c k = bkey_try(bch2_btree_iter_peek_max(&iter, &POS(inode_inum(inode).inum, end))); u64 pagecache_end = k.k ? max(start, bkey_start_offset(k.k)) : end; @@ -200,7 +200,7 @@ static int bch2_next_fiemap_extent(struct btree_trans *trans, pagecache_start)) { bch2_bkey_buf_reassemble(&cur->kbuf, k); bch2_cut_front(trans->c, iter.pos, cur->kbuf.k); - bch2_cut_back(POS(inode->ei_inum.inum, end), cur->kbuf.k); + bch2_cut_back(POS(inode_inum(inode).inum, end), cur->kbuf.k); cur->flags = 0; } else if (k.k) { bch2_cut_back(bkey_start_pos(k.k), cur->kbuf.k); diff --git a/fs/vfs/fs.c b/fs/vfs/fs.c index 1419ac8465..3a1a887a40 100644 --- a/fs/vfs/fs.c +++ b/fs/vfs/fs.c @@ -84,7 +84,7 @@ void bch2_inode_update_after_write(struct btree_trans *trans, { struct bch_fs *c = trans->c; - BUG_ON(bi->bi_inum != inode->v.i_ino); + BUG_ON(bi->bi_inum != inode_inum(inode).inum); bch2_assert_pos_locked(trans, BTREE_ID_inodes, POS(0, bi->bi_inum)); @@ -237,7 +237,7 @@ static u32 bch2_vfs_inode_obj_hash_fn(const void *data, u32 len, u32 seed) { const struct bch_inode_info *inode = data; - return bch2_vfs_inode_hash_fn(&inode->ei_inum, sizeof(inode->ei_inum), seed); + return bch2_vfs_inode_hash_fn(&inode->ei_inum_hash.inum, sizeof(inode->ei_inum_hash.inum), seed); } static int bch2_vfs_inode_cmp_fn(struct rhashtable_compare_arg *arg, @@ -246,12 +246,12 @@ static int bch2_vfs_inode_cmp_fn(struct rhashtable_compare_arg *arg, const struct bch_inode_info *inode = obj; const subvol_inum *v = arg->key; - return !subvol_inum_eq(inode->ei_inum, *v); + return !subvol_inum_eq(inode_inum(inode), *v); } static const struct rhashtable_params bch2_vfs_inodes_params = { .head_offset = offsetof(struct bch_inode_info, hash), - .key_offset = offsetof(struct bch_inode_info, ei_inum), + .key_offset = offsetof(struct bch_inode_info, ei_inum_hash.inum), .key_len = sizeof(subvol_inum), .hashfn = bch2_vfs_inode_hash_fn, .obj_hashfn = bch2_vfs_inode_obj_hash_fn, @@ -259,9 +259,13 @@ static const struct rhashtable_params bch2_vfs_inodes_params = { .automatic_shrinking = true, }; +/* + * Offsets are relative to bch_inum_hash_entry, not bch_inode_info: entries in + * this table are not required to be embedded in one. + */ static const struct rhashtable_params bch2_vfs_inodes_by_inum_params = { - .head_offset = offsetof(struct bch_inode_info, by_inum_hash), - .key_offset = offsetof(struct bch_inode_info, ei_inum.inum), + .head_offset = offsetof(struct bch_inum_hash_entry, hash), + .key_offset = offsetof(struct bch_inum_hash_entry, inum.inum), .key_len = sizeof(u64), .automatic_shrinking = true, }; @@ -299,11 +303,11 @@ int bch2_inode_or_descendents_is_open(struct btree_trans *trans, struct bpos p) hash = rht_key_hashfn(&ht->ht, tbl, &inum, bch2_vfs_inodes_by_inum_params); bkt = rht_bucket(tbl, hash); do { - struct bch_inode_info *inode; + struct bch_inum_hash_entry *e; - rht_for_each_entry_rcu_from(inode, he, rht_ptr_rcu(bkt), tbl, hash, hash) { - if (inode->ei_inum.inum == inum) { - int ret = darray_push_gfp(&subvols, inode->ei_inum.subvol, GFP_NOWAIT); + rht_for_each_entry_rcu_from(e, he, rht_ptr_rcu(bkt), tbl, hash, hash.rhead) { + if (e->inum.inum == inum) { + int ret = darray_push_gfp(&subvols, e->inum.subvol, GFP_NOWAIT); if (ret) { rcu_read_unlock(); try(darray_make_room(&subvols, 1)); @@ -393,7 +397,7 @@ static void bch2_inode_hash_remove(struct bch_fs *c, struct bch_inode_info *inod if (remove) { int ret = rhltable_remove(&c->vfs.inodes_by_inum_table, - &inode->by_inum_hash, bch2_vfs_inodes_by_inum_params); + &inode->ei_inum_hash.hash, bch2_vfs_inodes_by_inum_params); BUG_ON(ret); ret = rhashtable_remove_fast(&c->vfs.inodes_table, @@ -408,6 +412,75 @@ static void bch2_inode_hash_remove(struct bch_fs *c, struct bch_inode_info *inod } } +/* + * Marks an inode number as held for as long as the guard is in scope, without + * an inode to hang it on. + * + * O_TMPFILE commits an inode that is already unlinked, so from + * bch2_trans_commit() onwards a scanning fsck pass can see the key - while + * __bch2_create() is still several steps away from having a hashed VFS inode. + * bch2_inode_or_descendents_is_open() would answer "not open" for a file the + * caller is about to be handed a descriptor for, and check_inode() deletes + * exactly that. + * + * The entry is freed through RCU: rhltable_remove() unlinks it but leaves it + * traversable, so a reader already inside bch2_inode_or_descendents_is_open() + * may still be walking it. + */ +struct guard_inum_entry { + struct bch_inum_hash_entry e; + struct rcu_head rcu; +}; + +struct inum_hash_guard { + struct bch_fs *c; + struct guard_inum_entry *e; +}; + +static void inum_hash_guard_exit(struct inum_hash_guard *g) +{ + if (g->e) { + int ret = rhltable_remove(&g->c->vfs.inodes_by_inum_table, + &g->e->e.hash, bch2_vfs_inodes_by_inum_params); + BUG_ON(ret); + kfree_rcu(g->e, rcu); + g->e = NULL; + } +} + +static struct inum_hash_guard inum_hash_guard_init(struct bch_fs *c) +{ + return (struct inum_hash_guard) { .c = c }; +} + +DEFINE_CLASS(inum_hash_guard, struct inum_hash_guard, + inum_hash_guard_exit(&_T), + inum_hash_guard_init(c), struct bch_fs *c) + +/* + * Re-arms: the caller's arm point is inside a transaction retry loop, and a + * restart can allocate a different inode number. + */ +static int inum_hash_guard_set(struct inum_hash_guard *g, subvol_inum inum) +{ + inum_hash_guard_exit(g); + + struct guard_inum_entry *e = kmalloc(sizeof(*e), GFP_NOFS); + if (!e) + return -ENOMEM; + + e->e.inum = inum; + int ret = rhltable_insert(&g->c->vfs.inodes_by_inum_table, + &e->e.hash, bch2_vfs_inodes_by_inum_params); + if (ret) { + kfree(e); + return ret; + } + + g->e = e; + return 0; +} + static struct bch_inode_info *bch2_inode_hash_insert(struct bch_fs *c, struct btree_trans *trans, struct bch_inode_info *inode) @@ -417,10 +490,10 @@ static struct bch_inode_info *bch2_inode_hash_insert(struct bch_fs *c, set_bit(EI_INODE_HASHED, &inode->ei_flags); retry: if (unlikely(rhashtable_lookup_insert_key(&c->vfs.inodes_table, - &inode->ei_inum, + &inode->ei_inum_hash.inum, &inode->hash, bch2_vfs_inodes_params))) { - old = bch2_inode_hash_find(c, trans, inode->ei_inum); + old = bch2_inode_hash_find(c, trans, inode_inum(inode)); if (!old) goto retry; @@ -442,7 +515,7 @@ static struct bch_inode_info *bch2_inode_hash_insert(struct bch_fs *c, return old; } else { int ret = rhltable_insert(&c->vfs.inodes_by_inum_table, - &inode->by_inum_hash, + &inode->ei_inum_hash.hash, bch2_vfs_inodes_by_inum_params); BUG_ON(ret); @@ -512,7 +585,7 @@ static struct bch_inode_info *bch2_new_inode(struct btree_trans *trans) struct bch_inode_info *inode = __bch2_new_inode(trans->c, GFP_NOWAIT); if (unlikely(!inode)) { - int ret = drop_locks_do(trans, (inode = __bch2_new_inode(trans->c, GFP_NOFS)) ? 0 : -ENOMEM); + int ret = drop_locks_do(trans, (inode = __bch2_new_inode(trans->c, GFP_NOIO)) ? 0 : -ENOMEM); if (ret && inode) { __destroy_inode(&inode->v); fast_list_put_idx(&trans->c->vfs.inodes, inode->ei_inodes_idx); @@ -660,7 +733,7 @@ __bch2_create(struct mnt_idmap *idmap, return ERR_PTR(ret); } - inode = __bch2_new_inode(c, GFP_NOFS); + inode = __bch2_new_inode(c, GFP_NOIO); if (unlikely(!inode)) return ERR_PTR(-ENOMEM); @@ -673,6 +746,7 @@ __bch2_create(struct mnt_idmap *idmap, * ours until after, ei->update_lock must also be taken first: */ CLASS(btree_trans, trans)(c); + CLASS(inum_hash_guard, guard)(c); retry: bch2_trans_begin(trans); @@ -689,10 +763,18 @@ __bch2_create(struct mnt_idmap *idmap, if (unlikely(ret)) goto err_before_quota; - inum.subvol = inode_u.bi_subvol ?: dir->ei_inum.subvol; + inum.subvol = inode_u.bi_subvol ?: inode_inum(dir).subvol; inum.inum = inode_u.bi_inum; - ret = bch2_inode_init_security(trans, dir, inode, + /* + * Before the commit publishes the key. Only a tmpfile needs it: every + * other create commits with a dirent and nlink 1, which check_inode() + * doesn't touch. + */ + ret = ((flags & BCH_CREATE_TMPFILE) + ? inum_hash_guard_set(&guard, inum) + : 0) ?: + bch2_inode_init_security(trans, dir, inode, !(flags & BCH_CREATE_TMPFILE) ? &dentry->d_name : NULL, inum, &inode_u) ?: @@ -1030,8 +1112,8 @@ static int bch2_link(struct dentry *old_dentry, struct inode *vdir, lockdep_assert_held(&inode->v.i_rwsem); - ret = bch2_subvol_is_ro(c, dir->ei_inum.subvol) ?: - bch2_subvol_is_ro(c, inode->ei_inum.subvol) ?: + ret = bch2_subvol_is_ro(c, inode_inum(dir).subvol) ?: + bch2_subvol_is_ro(c, inode_inum(inode).subvol) ?: __bch2_link(c, inode, dir, dentry); if (unlikely(ret)) return bch2_err_class(ret); @@ -1156,8 +1238,8 @@ static int bch2_rename2(struct mnt_idmap *idmap, u32 src_snapshot, dst_snapshot; ret = lockrestart_do(trans, - bch2_subvol_is_ro_trans(trans, src_dir->ei_inum.subvol, &src_snapshot) ?: - bch2_subvol_is_ro_trans(trans, dst_dir->ei_inum.subvol, &dst_snapshot)); + bch2_subvol_is_ro_trans(trans, inode_inum(src_dir).subvol, &src_snapshot) ?: + bch2_subvol_is_ro_trans(trans, inode_inum(dst_dir).subvol, &dst_snapshot)); if (ret) goto err; @@ -1223,9 +1305,9 @@ static int bch2_rename2(struct mnt_idmap *idmap, goto err; } - BUG_ON(src_inode->v.i_ino != src_inode_u.bi_inum); + BUG_ON(inode_inum(src_inode).inum != src_inode_u.bi_inum); BUG_ON(dst_inode && - dst_inode->v.i_ino != dst_inode_u.bi_inum); + inode_inum(dst_inode).inum != dst_inode_u.bi_inum); bch2_inode_update_after_write(trans, src_dir, &src_dir_u, ATTR_MTIME|ATTR_CTIME|ATTR_SIZE); @@ -1383,7 +1465,7 @@ static int bch2_getattr(struct mnt_idmap *idmap, vfsgid_t vfsgid = i_gid_into_vfsgid(idmap, &inode->v); stat->dev = inode->v.i_sb->s_dev; - stat->ino = inode->v.i_ino; + stat->ino = inode_inum(inode).inum; stat->mode = inode->v.i_mode; stat->nlink = inode->v.i_nlink; stat->uid = vfsuid_into_kuid(vfsuid); @@ -1398,7 +1480,7 @@ static int bch2_getattr(struct mnt_idmap *idmap, stat->blksize = block_bytes(c); stat->blocks = inode->v.i_blocks; - stat->subvol = inode->ei_inum.subvol; + stat->subvol = inode_inum(inode).subvol; stat->result_mask |= STATX_SUBVOL; if ((request_mask & STATX_DIOALIGN) && S_ISREG(inode->v.i_mode)) { @@ -1439,7 +1521,7 @@ static int bch2_setattr(struct mnt_idmap *idmap, lockdep_assert_held(&inode->v.i_rwsem); - int ret = bch2_subvol_is_ro(c, inode->ei_inum.subvol) ?: + int ret = bch2_subvol_is_ro(c, inode_inum(inode).subvol) ?: setattr_prepare(idmap, dentry, iattr) ?: (iattr->ia_valid & ATTR_SIZE ? bchfs_truncate(idmap, inode, iattr) @@ -1672,7 +1754,7 @@ static int bch2_open(struct inode *vinode, struct file *file) struct bch_inode_info *inode = to_bch_ei(vinode); struct bch_fs *c = inode->v.i_sb->s_fs_info; - try(bch2_subvol_is_ro(c, inode->ei_inum.subvol)); + try(bch2_subvol_is_ro(c, inode_inum(inode).subvol)); } file->f_mode |= FMODE_CAN_ODIRECT; @@ -1813,7 +1895,7 @@ static int bch2_fileattr_set(struct mnt_idmap *idmap, } mutex_lock(&inode->ei_update_lock); - ret = bch2_subvol_is_ro(c, inode->ei_inum.subvol) ?: + ret = bch2_subvol_is_ro(c, inode_inum(inode).subvol) ?: (s.set_project ? bch2_set_projid(c, inode, fa->fsx_projid) : 0) ?: @@ -1955,8 +2037,8 @@ static int bcachefs_fid_valid(int fh_len, int fh_type) static struct bcachefs_fid bch2_inode_to_fid(struct bch_inode_info *inode) { return (struct bcachefs_fid) { - .inum = inode->ei_inum.inum, - .subvol = inode->ei_inum.subvol, + .inum = inode_inum(inode).inum, + .subvol = inode_inum(inode).subvol, .generation = inode->ei_inode.bi_generation, }; } @@ -2052,7 +2134,7 @@ static struct dentry *bch2_get_parent(struct dentry *child) struct bch_fs *c = inode->v.i_sb->s_fs_info; subvol_inum parent_inum = { .subvol = inode->ei_inode.bi_parent_subvol ?: - inode->ei_inum.subvol, + inode_inum(inode).subvol, .inum = inode->ei_inode.bi_dir, }; @@ -2085,7 +2167,7 @@ static int bch2_get_name(struct dentry *parent, char *name, struct dentry *child retry: bch2_trans_begin(trans); - ret = bch2_subvolume_get_snapshot(trans, dir->ei_inum.subvol, &snapshot); + ret = bch2_subvolume_get_snapshot(trans, inode_inum(dir).subvol, &snapshot); if (ret) goto err; @@ -2116,7 +2198,7 @@ static int bch2_get_name(struct dentry *parent, char *name, struct dentry *child if (ret) goto err; - if (subvol_inum_eq(target, inode->ei_inum)) + if (subvol_inum_eq(target, inode_inum(inode))) goto found; } else { /* @@ -2137,7 +2219,7 @@ static int bch2_get_name(struct dentry *parent, char *name, struct dentry *child if (ret) continue; - if (subvol_inum_eq(target, inode->ei_inum)) + if (subvol_inum_eq(target, inode_inum(inode))) goto found; } } @@ -2172,7 +2254,7 @@ static void bch2_vfs_inode_init(struct btree_trans *trans, struct bch_subvolume *subvol) { inode->v.i_ino = inum.inum; - inode->ei_inum = inum; + inode->ei_inum_hash.inum = inum; inode->ei_inode.bi_inum = inum.inum; bch2_inode_update_after_write(trans, inode, bi, ~0); @@ -2257,7 +2339,15 @@ static void bch2_evict_inode(struct inode *vinode) { struct bch_fs *c = vinode->i_sb->s_fs_info; struct bch_inode_info *inode = to_bch_ei(vinode); - bool delete = !inode->v.i_nlink && !is_bad_inode(&inode->v); + /* + * An unlinked subvolume's root inode reads i_nlink == 0, but its + * deletion belongs to the subvolume deletion path, not us (see + * bch2_inode_is_subvolume_root()): this eviction completing is what + * bch2_subvolume_wait_for_pagecache_and_delete() is waiting on to + * tombstone the subvolume and hand the keys to the snapshot sweep. + */ + bool delete = !inode->v.i_nlink && !is_bad_inode(&inode->v) && + !bch2_inode_is_subvolume_root(&inode->ei_inode); /* * evict() has waited for outstanding writeback, we'll do no more IO @@ -2357,7 +2447,7 @@ void bch2_evict_subvolume_inodes(struct bch_fs *c, snapshot_id_list *s) struct bch_inode_info *inode; fast_list_for_each(&c->vfs.inodes, iter, inode) { - if (!snapshot_list_has_id(s, inode->ei_inum.subvol)) + if (!snapshot_list_has_id(s, inode_inum(inode).subvol)) continue; if (!(inode_state_read_once(&inode->v) & I_DONTCACHE) && @@ -2377,7 +2467,7 @@ void bch2_evict_subvolume_inodes(struct bch_fs *c, snapshot_id_list *s) found = false; fast_list_for_each(&c->vfs.inodes, iter, inode) { - if (!snapshot_list_has_id(s, inode->ei_inum.subvol)) + if (!snapshot_list_has_id(s, inode_inum(inode).subvol)) continue; found = true; diff --git a/fs/vfs/fs.h b/fs/vfs/fs.h index 48b0f8cc59..8f1ffd69df 100644 --- a/fs/vfs/fs.h +++ b/fs/vfs/fs.h @@ -7,6 +7,7 @@ #include "fs/quota_types.h" #include "util/two_state_shared_lock.h" +#include "vfs/types.h" #include #include @@ -32,8 +33,12 @@ static inline void inode_state_set_raw(struct inode *inode, unsigned flags) struct bch_inode_info { struct inode v; struct rhash_head hash; - struct rhlist_head by_inum_hash; - subvol_inum ei_inum; + /* + * Read it with inode_inum(); the layout is private so that + * bch2_inode_or_descendents_is_open() can walk entries without knowing + * about bch_inode_info at all. + */ + struct bch_inum_hash_entry ei_inum_hash; /* * Cached extent allocation state for [start, end), for skipping btree @@ -98,9 +103,9 @@ DEFINE_GUARD(bch2_pagecache_block, struct bch_inode_info *, bch2_pagecache_block_get(_T), bch2_pagecache_block_put(_T)); -static inline subvol_inum inode_inum(struct bch_inode_info *inode) +static inline subvol_inum inode_inum(const struct bch_inode_info *inode) { - return inode->ei_inum; + return inode->ei_inum_hash.inum; } /* diff --git a/fs/vfs/io.c b/fs/vfs/io.c index 908a54ab46..e586715da6 100644 --- a/fs/vfs/io.c +++ b/fs/vfs/io.c @@ -145,7 +145,7 @@ void __bch2_i_sectors_acct(struct bch_fs *c, struct bch_inode_info *inode, if (unlikely((s64) inode->v.i_blocks + sectors < 0)) { CLASS(bch_log_msg, msg)(c); prt_printf(&msg.m, "subvol %llu inode %llu i_blocks underflow: %llu + %lli < 0 (ondisk %lli)", - (u64) inode->ei_inum.subvol, (u64) inode->v.i_ino, + (u64) inode_inum(inode).subvol, (u64) inode_inum(inode).inum, (u64) inode->v.i_blocks, sectors, inode->ei_inode.bi_sectors); @@ -251,8 +251,8 @@ int bch2_fsync(struct file *file, loff_t start, loff_t end, int datasync) ret = err; event_inc_trace(c, fsync, buf, ({ - prt_printf(&buf, "inum: %llu\n", (u64) inode->ei_inum.inum); - prt_printf(&buf, "subvol: %llu\n", (u64) inode->ei_inum.subvol); + prt_printf(&buf, "inum: %llu\n", (u64) inode_inum(inode).inum); + prt_printf(&buf, "subvol: %llu\n", (u64) inode_inum(inode).subvol); prt_printf(&buf, "flushed_seq: %llu\n", flushed_seq); prt_printf(&buf, "datasync: %u\n", datasync); prt_printf(&buf, "journal_flush_disabled: %u\n", c->opts.journal_flush_disabled); @@ -315,9 +315,9 @@ static int __bch2_truncate_folio(struct bch_inode_info *inode, * XXX: we're doing two index lookups when we end up reading the * folio */ - ret = range_has_data(c, inode->ei_inum.subvol, - POS(inode->v.i_ino, (index << PAGE_SECTORS_SHIFT)), - POS(inode->v.i_ino, (index << PAGE_SECTORS_SHIFT) + PAGE_SECTORS)); + ret = range_has_data(c, inode_inum(inode).subvol, + POS(inode_inum(inode).inum, (index << PAGE_SECTORS_SHIFT)), + POS(inode_inum(inode).inum, (index << PAGE_SECTORS_SHIFT) + PAGE_SECTORS)); if (ret <= 0) return ret; @@ -550,7 +550,7 @@ int bchfs_truncate(struct mnt_idmap *idmap, CLASS(bch_log_msg, msg)(c); prt_printf(&msg.m, "inode %llu truncated to 0 but i_blocks %llu (ondisk %lli)", - (u64) inode->v.i_ino, (u64) inode->v.i_blocks, + (u64) inode_inum(inode).inum, (u64) inode->v.i_blocks, inode->ei_inode.bi_sectors); msg.m.suppress = !bch2_count_fsck_err(c, vfs_inode_i_blocks_not_zero_at_truncate, &msg.m); @@ -650,7 +650,7 @@ static noinline int __bchfs_fallocate(struct bch_inode_info *inode, int mode, u64 start_sector, u64 end_sector) { struct bch_fs *c = inode->v.i_sb->s_fs_info; - struct bpos end_pos = POS(inode->v.i_ino, end_sector); + struct bpos end_pos = POS(inode_inum(inode).inum, end_sector); struct bch_inode_opts opts; int ret = 0; @@ -658,7 +658,7 @@ static noinline int __bchfs_fallocate(struct bch_inode_info *inode, int mode, CLASS(btree_trans, trans)(c); CLASS(btree_iter, iter)(trans, BTREE_ID_extents, - POS(inode->v.i_ino, start_sector), + POS(inode_inum(inode).inum, start_sector), BTREE_ITER_slots|BTREE_ITER_intent); while (!ret) { @@ -676,7 +676,7 @@ static noinline int __bchfs_fallocate(struct bch_inode_info *inode, int mode, break; ret = bch2_subvolume_get_snapshot(trans, - inode->ei_inum.subvol, &snapshot); + inode_inum(inode).subvol, &snapshot); if (ret) goto bkey_err; @@ -692,7 +692,7 @@ static noinline int __bchfs_fallocate(struct bch_inode_info *inode, int mode, /* already reserved */ if (bkey_extent_is_reservation(c, k) && - bch2_bkey_nr_ptrs_fully_allocated(c, k) >= opts.data_replicas) { + bch2_bkey_durability_safe(c, k).nr_overwritable >= opts.data_replicas) { bch2_btree_iter_advance(&iter); continue; } @@ -879,9 +879,9 @@ static int quota_reserve_range(struct bch_inode_info *inode, CLASS(btree_trans, trans)(c); int ret = for_each_btree_key_in_subvolume_max(trans, iter, BTREE_ID_extents, - POS(inode->v.i_ino, start), - POS(inode->v.i_ino, end - 1), - inode->ei_inum.subvol, 0, k, ({ + POS(inode_inum(inode).inum, start), + POS(inode_inum(inode).inum, end - 1), + inode_inum(inode).subvol, 0, k, ({ if (bkey_extent_is_allocation(k.k)) { u64 s = min(end, k.k->p.offset) - max(start, bkey_start_offset(k.k)); @@ -1014,8 +1014,8 @@ static loff_t bch2_seek_data(struct file *file, u64 offset) try(bch2_trans_run(c, for_each_btree_key_in_subvolume_max(trans, iter, BTREE_ID_extents, - POS(inode->v.i_ino, offset >> 9), - POS(inode->v.i_ino, U64_MAX), + POS(inode_inum(inode).inum, offset >> 9), + POS(inode_inum(inode).inum, U64_MAX), inum.subvol, 0, k, ({ if (bkey_extent_is_data(k.k)) { next_data = max(offset, bkey_start_offset(k.k) << 9); @@ -1048,15 +1048,15 @@ static loff_t bch2_seek_hole(struct file *file, u64 offset) CLASS(btree_trans, trans)(c); try(for_each_btree_key_in_subvolume_max(trans, iter, BTREE_ID_extents, - POS(inode->v.i_ino, offset >> 9), - POS(inode->v.i_ino, U64_MAX), + POS(inode_inum(inode).inum, offset >> 9), + POS(inode_inum(inode).inum, U64_MAX), inum.subvol, BTREE_ITER_slots, k, ({ - if (k.k->p.inode != inode->v.i_ino || + if (k.k->p.inode != inode_inum(inode).inum || !bkey_extent_is_data(k.k)) { - loff_t start_offset = k.k->p.inode == inode->v.i_ino + loff_t start_offset = k.k->p.inode == inode_inum(inode).inum ? max(offset, bkey_start_offset(k.k) << 9) : offset; - loff_t end_offset = k.k->p.inode == inode->v.i_ino + loff_t end_offset = k.k->p.inode == inode_inum(inode).inum ? MAX_LFS_FILESIZE : k.k->p.offset << 9; diff --git a/fs/vfs/ioctl.c b/fs/vfs/ioctl.c index edf4e6c5db..3404024090 100644 --- a/fs/vfs/ioctl.c +++ b/fs/vfs/ioctl.c @@ -6,6 +6,7 @@ #include "fs/dirent.h" #include "fs/inode.h" #include "fs/namei.h" +#include "init/damage.h" #include "fs/quota.h" #include "snapshots/snapshot.h" @@ -219,7 +220,7 @@ static int bch2_ioc_getlabel(struct bch_fs *c, char __user *user_label) BUILD_BUG_ON(BCH_SB_LABEL_SIZE >= FSLABEL_MAX); - scoped_guard(mutex, &c->sb_lock) + scoped_guard(mutex_noio, &c->sb_lock) memcpy(label, c->disk_sb.sb->label, BCH_SB_LABEL_SIZE); len = strnlen(label, BCH_SB_LABEL_SIZE); @@ -256,8 +257,7 @@ static int bch2_ioc_setlabel(struct bch_fs *c, try(mnt_want_write_file(file)); int ret; - scoped_guard(memalloc_flags, PF_MEMALLOC_NOFS) { - guard(mutex)(&c->sb_lock); + scoped_guard(mutex_noio, &c->sb_lock) { strscpy(c->disk_sb.sb->label, label, BCH_SB_LABEL_SIZE); ret = bch2_write_super(c); } @@ -733,6 +733,481 @@ static long bch2_ioctl_subvolume_to_path(struct bch_fs *c, struct file *filp, return 0; } +static long bch2_ioc_get_damage(struct bch_fs *c, struct file *filp, + struct bch_ioctl_get_damage __user *user_arg) +{ + struct bch_ioctl_get_damage arg; + try(copy_from_user_errcode(&arg, user_arg, sizeof(arg))); + + if (arg.pad) + return -EINVAL; + + subvol_inum inum = inode_inum(file_bch_inode(filp)); + + CLASS(btree_trans, trans)(c); + bch_sb_errors_cpu errors = {}; + + int ret = lockrestart_do(trans, ({ + errors.nr = 0; + u32 snapshot; + bch2_subvolume_get_snapshot(trans, inum.subvol, &snapshot) ?: + bch2_damage_accumulate(trans, inum.inum, snapshot, &errors); + })); + + for (u32 i = 0; !ret && i < min_t(u32, errors.nr, arg.nr_entries); i++) { + bch_sb_field_error_entry_v2 e = {}; + SET_BCH_SB_ERROR_ENTRY_V2_ID(&e, errors.data[i].id); + SET_BCH_SB_ERROR_ENTRY_V2_NR(&e, errors.data[i].nr); + SET_BCH_SB_ERROR_ENTRY_V2_FIRST(&e, errors.data[i].first_error_time); + SET_BCH_SB_ERROR_ENTRY_V2_LAST(&e, errors.data[i].last_error_time); + + ret = copy_to_user_errcode(&user_arg->entries[i], &e, sizeof(e)); + } + if (!ret) + ret = put_user((u32) errors.nr, &user_arg->nr_entries); + + darray_exit(&errors); + return ret; +} + +static long bch2_ioc_clear_damage(struct bch_fs *c, struct file *filp) +{ + struct bch_inode_info *inode = file_bch_inode(filp); + + /* forensic metadata: erasing it takes ownership, like chattr */ + if (!inode_owner_or_capable(file_mnt_idmap(filp), &inode->v)) + return -EPERM; + + try(mnt_want_write_file(filp)); + + CLASS(btree_trans, trans)(c); + int ret = commit_do(trans, NULL, NULL, BCH_TRANS_COMMIT_no_enospc, + bch2_damage_clear(trans, inode_inum(inode))); + + mnt_drop_write_file(filp); + return ret; +} + +static int bch2_readdir_flags_emit(const struct qstr *name, u64 inum, + u8 d_type, + char __user *buf, u32 buf_size, u32 *used) +{ + u32 name_offset = offsetof(struct bch_ioctl_readdir_entry, name); + u32 name_bytes = name->len + 1; + u32 reclen = ALIGN(name_offset + name_bytes, 8); + + if (*used + reclen > buf_size) + return 1; + + struct bch_ioctl_readdir_entry ent = { + .inum = inum, + .d_type = d_type, + .name_len = name_bytes, + }; + + try(copy_to_user_errcode(buf + *used, &ent, name_offset)); + try(copy_to_user_errcode(buf + *used + name_offset, name->name, name->len)); + + u32 written = name_offset + name->len; + if (clear_user(buf + *used + written, reclen - written)) + return -EFAULT; + + *used += reclen; + return 0; +} + +#define BCH_READDIR_FLAGS_ALL (BCH_READDIR_recursive| \ + BCH_READDIR_damaged|\ + BCH_READDIR_subvolumes_only) + +/* + * Does this entry pass the requested filter? > 0 keep, 0 skip, < 0 + * error. New filters are new cases; the iteration doesn't change. + */ +static int bch2_readdir_filter(struct btree_trans *trans, u32 flags, + subvol_inum dir, u32 view, + struct bkey_s_c_dirent d, subvol_inum target) +{ + switch (flags & ~BCH_READDIR_recursive) { + case 0: + return 1; + case BCH_READDIR_damaged: { + /* A subvolume dirent's target has its own lineage: */ + u32 snap = view; + if (target.subvol != dir.subvol) + try(bch2_subvolume_get_snapshot(trans, target.subvol, + &snap)); + + return bch2_inode_has_damage(trans, target.inum, snap); + } + case BCH_READDIR_subvolumes_only: + return d.v->d_type == DT_SUBVOL; + default: + return -EINVAL; + } +} + +/* + * Shared machinery for the recursive modes: each iterates its filter's + * candidate set (the damage btree, the subvolumes btree) rather than + * scanning dirents, then qualifies every candidate the same way - is it + * under this directory, and what is its path relative to it? + */ +struct readdir_recursive { + subvol_inum dir; + struct mnt_idmap *idmap; + struct printbuf *dir_path; + struct printbuf *path; + char __user *buf; + u32 buf_size; + u32 used; +}; + +enum readdir_recursive_res { + READDIR_EMITTED, + READDIR_BUF_FULL, + READDIR_SKIP, +}; + +/* + * A recursive listing tunnels past the directories a dirent walk would + * have to descend through, so enforce the permissions that walk would + * have hit: MAY_READ on the candidate's parent (the candidate's name is + * that directory's content), MAY_EXEC on every directory above it, up + * to but excluding the fd's directory, which open() already checked. + * Full VFS permission stack (POSIX ACLs, LSM hooks), same shape as + * bch2_check_path_accessible(). Returns 0 if accessible, 1 to skip, + * negative on error; racing renames and unreachable parents skip. + */ +static int readdir_recursive_path_accessible(struct btree_trans *trans, + struct mnt_idmap *idmap, + subvol_inum n, subvol_inum dir) +{ + struct bch_inode_info *inode = bch2_vfs_inode_get_trans(trans, n, __func__); + if (IS_ERR(inode)) + return bch2_err_matches(PTR_ERR(inode), ENOENT) ? 1 : PTR_ERR(inode); + + subvol_inum parent = { + .subvol = inode->ei_inode.bi_parent_subvol ?: n.subvol, + .inum = inode->ei_inode.bi_dir, + }; + iput(&inode->v); + + CLASS(darray_inode, check_inodes)(); + unsigned depth = 0; + + while (parent.subvol != dir.subvol || parent.inum != dir.inum) { + /* + * bch2_inum_is_descendant() just vetted this chain cycle-free; + * the depth cap only guards against a rename racing in between: + */ + if (!parent.inum || ++depth > 4096) + return 1; + + inode = bch2_vfs_inode_get_trans(trans, parent, __func__); + if (IS_ERR(inode)) + return bch2_err_matches(PTR_ERR(inode), ENOENT) + ? 1 : PTR_ERR(inode); + + int ret = darray_push(&check_inodes, inode); + if (ret) { + iput(&inode->v); + return ret; + } + + parent = (subvol_inum) { + .subvol = inode->ei_inode.bi_parent_subvol ?: parent.subvol, + .inum = inode->ei_inode.bi_dir, + }; + } + + /* + * Unlock the transaction before calling inode_permission(), which + * may trigger bch2_get_acl() needing its own transaction: + */ + bch2_trans_unlock(trans); + + darray_for_each(check_inodes, i) { + unsigned mask = i == check_inodes.data ? MAY_READ : MAY_EXEC; + if (inode_permission(idmap, &(*i)->v, mask)) + return 1; + } + + return bch2_trans_relock(trans); +} + +/* + * Qualify @n and emit it: check it's under the directory, build its path, + * relativize against the directory's own path, check the caller may see + * it, copy out. Disagreement between the descendant walk and path + * resolution (racing rename) just skips the entry - as does the + * directory itself, whose relative path would be empty. + */ +static int readdir_recursive_emit(struct btree_trans *trans, + struct readdir_recursive *r, + subvol_inum n, u8 d_type) +{ + int ret = bch2_inum_is_descendant(trans, n, r->dir); + if (ret <= 0) + return ret ?: READDIR_SKIP; + + printbuf_reset(r->path); + try(bch2_inum_to_path(trans, n, r->path)); + + u32 plen = r->dir_path->pos; + if (!(r->path->pos > plen && + !memcmp(r->path->buf, r->dir_path->buf, plen) && + (plen == 1 || r->path->buf[plen] == '/'))) + return READDIR_SKIP; + + u32 rel = plen == 1 ? 1 : plen + 1; + struct qstr name = { + .name = r->path->buf + rel, + .len = r->path->pos - rel, + }; + + /* name_len is u16 in the entry format; don't truncate, skip: */ + if (name.len + 1 > U16_MAX) + return READDIR_SKIP; + + ret = readdir_recursive_path_accessible(trans, r->idmap, n, r->dir); + if (ret) + return ret < 0 ? ret : READDIR_SKIP; + + ret = bch2_readdir_flags_emit(&name, n.inum, d_type, + r->buf, r->buf_size, &r->used); + return ret < 0 ? ret : ret ? READDIR_BUF_FULL : READDIR_EMITTED; +} + +/* + * Recursive damaged doesn't scan dirents: it iterates the damage + * btree - cost proportional to recorded damage, not tree size - and + * checks each candidate inode for being under this directory. Damage + * keys are sorted by inum, so consecutive snapshot versions of one + * inode dedup by remembering the last inum emitted. + */ +static long bch2_ioc_readdir_recursive_damaged(struct bch_fs *c, + struct file *filp, + struct bch_ioctl_readdir_flags *arg, + struct bch_ioctl_readdir_flags __user *user_arg) +{ + struct bpos pos = SPOS(0, arg->pos[0], arg->pos[1]); + + CLASS(btree_trans, trans)(c); + CLASS(printbuf, dir_path)(); + CLASS(printbuf, path)(); + struct readdir_recursive r = { + .dir = inode_inum(file_bch_inode(filp)), + .idmap = file_mnt_idmap(filp), + .dir_path = &dir_path, + .path = &path, + .buf = (char __user *)(unsigned long)arg->buf, + .buf_size = arg->buf_size, + }; + + u32 view; + try(lockrestart_do(trans, ({ + printbuf_reset(&dir_path); + bch2_subvolume_get_snapshot(trans, r.dir.subvol, &view) ?: + bch2_inum_to_path(trans, r.dir, &dir_path); + }))); + + u64 last_handled = 0; + int ret = for_each_btree_key(trans, iter, BTREE_ID_damage, pos, + BTREE_ITER_prefetch|BTREE_ITER_all_snapshots, k, ({ + int ret2 = 0; + u64 inum = k.k->p.offset; + + if (inum != last_handled && + bch2_snapshot_is_ancestor(trans, view, k.k->p.snapshot)) { + if (k.k->type != KEY_TYPE_damage) { + /* + * A whiteout: damage was cleared in this view, + * which also hides what ancestor versions + * recorded - skip the inum entirely: + */ + last_handled = inum; + } else { + ret2 = readdir_recursive_emit(trans, &r, + (subvol_inum) { r.dir.subvol, inum }, + DT_UNKNOWN); + if (ret2 == READDIR_BUF_FULL) + break; + if (ret2 == READDIR_EMITTED) + last_handled = inum; + if (ret2 > 0) + ret2 = 0; + } + } + + /* + * Once an inum is handled its other snapshot versions are + * irrelevant, and the resume cursor must reflect that: if the + * buffer filled between two versions of one inode, restarting + * at the next key would emit the inum a second time. + */ + if (!ret2) + pos = inum == last_handled + ? SPOS(0, inum + 1, 0) + : bpos_successor(k.k->p); + ret2; + })); + + if (ret) + return ret; + + try(put_user(pos.offset, &user_arg->pos[0])); + try(put_user((u64) pos.snapshot, &user_arg->pos[1])); + try(put_user(r.used, &user_arg->used)); + + return 0; +} + +/* + * Recursive subvolumes_only iterates the subvolumes btree - cost + * proportional to the number of subvolumes - qualifying each live + * subvolume's root by ancestry through the shared machinery. One key + * per subvolume, so no dedup, and the cursor is just the next + * subvolume id. + */ +static long bch2_ioc_readdir_recursive_subvols(struct bch_fs *c, + struct file *filp, + struct bch_ioctl_readdir_flags *arg, + struct bch_ioctl_readdir_flags __user *user_arg) +{ + u64 pos = arg->pos[0]; + + CLASS(btree_trans, trans)(c); + CLASS(printbuf, dir_path)(); + CLASS(printbuf, path)(); + struct readdir_recursive r = { + .dir = inode_inum(file_bch_inode(filp)), + .idmap = file_mnt_idmap(filp), + .dir_path = &dir_path, + .path = &path, + .buf = (char __user *)(unsigned long)arg->buf, + .buf_size = arg->buf_size, + }; + + try(lockrestart_do(trans, ({ + printbuf_reset(&dir_path); + bch2_inum_to_path(trans, r.dir, &dir_path); + }))); + + int ret = for_each_btree_key(trans, iter, BTREE_ID_subvolumes, + POS(0, pos), BTREE_ITER_prefetch, k, ({ + int ret2 = 0; + + if (k.k->type == KEY_TYPE_subvolume) { + struct bkey_s_c_subvolume s = bkey_s_c_to_subvolume(k); + + /* + * Live subvolumes only: unlinked and deleted ones have + * no dirent - they're in nobody's namespace, and path + * resolution would fail: + */ + if (bch2_subvolume_state_compat(s.v) == SUBVOLUME_STATE_live) { + ret2 = readdir_recursive_emit(trans, &r, + (subvol_inum) { k.k->p.offset, + le64_to_cpu(s.v->inode) }, + DT_SUBVOL); + if (ret2 == READDIR_BUF_FULL) + break; + if (ret2 > 0) + ret2 = 0; + } + } + if (!ret2) + pos = k.k->p.offset + 1; + ret2; + })); + + if (ret) + return ret; + + try(put_user(pos, &user_arg->pos[0])); + try(put_user((u64) 0, &user_arg->pos[1])); + try(put_user(r.used, &user_arg->used)); + + return 0; +} + +static long bch2_ioc_readdir_flags(struct bch_fs *c, struct file *filp, + struct bch_ioctl_readdir_flags __user *user_arg) +{ + struct bch_ioctl_readdir_flags arg; + try(copy_from_user_errcode(&arg, user_arg, sizeof(arg))); + + if (arg.pad || arg.used || + (arg.flags & ~BCH_READDIR_FLAGS_ALL)) + return -EINVAL; + + struct bch_inode_info *dir_inode = file_bch_inode(filp); + if (!S_ISDIR(dir_inode->v.i_mode)) + return -ENOTDIR; + + if (arg.flags & BCH_READDIR_recursive) + switch (arg.flags & ~BCH_READDIR_recursive) { + case BCH_READDIR_damaged: + return bch2_ioc_readdir_recursive_damaged(c, filp, + &arg, user_arg); + case BCH_READDIR_subvolumes_only: + return bch2_ioc_readdir_recursive_subvols(c, filp, + &arg, user_arg); + default: + /* plain recursive: an honest tree walk, not yet */ + return -EOPNOTSUPP; + } + + subvol_inum dir = inode_inum(dir_inode); + char __user *buf = (char __user *)(unsigned long)arg.buf; + u32 used = 0; + u64 pos = arg.pos[0]; + + CLASS(btree_trans, trans)(c); + + u32 view; + int ret = lockrestart_do(trans, + bch2_subvolume_get_snapshot(trans, dir.subvol, &view)); + + ret = ret ?: for_each_btree_key_in_subvolume_max_in_trans(trans, iter, + BTREE_ID_dirents, + POS(dir.inum, pos), POS(dir.inum, U64_MAX), + dir.subvol, 0, k, ({ + if (k.k->type != KEY_TYPE_dirent) + continue; + + struct bkey_s_c_dirent d = bkey_s_c_to_dirent(k); + subvol_inum target; + + int ret2 = bch2_dirent_read_target(trans, dir, d, &target); + if (ret2 > 0) + continue; + + ret2 = ret2 ?: bch2_readdir_filter(trans, arg.flags, dir, + view, d, target); + if (ret2 > 0) { + struct qstr name = bch2_dirent_get_name(d); + ret2 = bch2_readdir_flags_emit(&name, target.inum, + d.v->d_type, + buf, arg.buf_size, &used); + if (ret2 > 0) + break; /* buffer full - resume at pos */ + } + if (!ret2) + pos = k.k->p.offset + 1; + ret2; + })); + + if (ret) + return ret; + + try(put_user(pos, &user_arg->pos[0])); + try(put_user(used, &user_arg->used)); + + return 0; +} + static int bch2_ioctl_snapshot_tree_resolve(struct btree_trans *trans, struct file *filp, u32 arg_tree_id, u32 *tree_id, struct bch_snapshot_tree *st) @@ -753,31 +1228,35 @@ static int bch2_ioctl_snapshot_tree_resolve(struct btree_trans *trans, return bch2_snapshot_tree_lookup(trans, *tree_id, st); } -static long bch2_ioctl_snapshot_tree(struct bch_fs *c, struct file *filp, - struct bch_ioctl_snapshot_tree_query __user *user_arg) +/* + * Shared by BCH_IOCTL_SNAPSHOT_TREE and _v2: a v1 node is a byte-prefix of a + * v2 node, so both are served by writing @node_size bytes of a v2 node per + * entry. v1 passes its frozen sizeof; v2 passes what the caller asked for, + * clamped to what we have. + */ +static long __bch2_ioctl_snapshot_tree(struct bch_fs *c, struct file *filp, + u32 tree_id_arg, u32 size, u32 node_size, + void __user *user_nodes, + u32 __user *user_master_subvol, + u32 __user *user_root_snapshot, + u32 __user *user_nr, + u32 __user *user_total) { - struct bch_ioctl_snapshot_tree_query arg; - try(copy_from_user_errcode(&arg, user_arg, sizeof(arg))); - - if (arg.pad) - return bch_err_throw(c, EINVAL_snapshot_tree_query_pad); - /* Querying a specific tree by ID requires CAP_SYS_ADMIN */ - if (arg.tree_id && !capable(CAP_SYS_ADMIN)) + if (tree_id_arg && !capable(CAP_SYS_ADMIN)) return bch_err_throw(c, EPERM_non_admin); - u32 tree_id = arg.tree_id; + u32 tree_id = tree_id_arg; struct bch_snapshot_tree st; { CLASS(btree_trans, trans)(c); int ret = lockrestart_do(trans, - bch2_ioctl_snapshot_tree_resolve(trans, filp, arg.tree_id, &tree_id, &st)); + bch2_ioctl_snapshot_tree_resolve(trans, filp, tree_id_arg, &tree_id, &st)); if (ret) return ret; } - u32 size = arg.nr; u32 nr = 0; u32 total = 0; @@ -824,7 +1303,7 @@ static long bch2_ioctl_snapshot_tree(struct bch_fs *c, struct file *filp, total++; if (nr < size) { - struct bch_ioctl_snapshot_node node = { + struct bch_ioctl_snapshot_node_v2 node = { .id = k.k->p.offset, .parent = le32_to_cpu(snap.v->parent), .children = { @@ -838,8 +1317,8 @@ static long bch2_ioctl_snapshot_tree(struct bch_fs *c, struct file *filp, .key_bytes = key_bytes, }; - _ret = copy_to_user_errcode(&user_arg->nodes[nr], &node, - sizeof(node)); + _ret = copy_to_user_errcode(user_nodes + (size_t) nr * node_size, + &node, node_size); if (!_ret) nr++; } @@ -850,10 +1329,10 @@ static long bch2_ioctl_snapshot_tree(struct bch_fs *c, struct file *filp, if (ret) return ret; - try(put_user(le32_to_cpu(st.master_subvol), &user_arg->master_subvol)); - try(put_user(le32_to_cpu(st.root_snapshot), &user_arg->root_snapshot)); - try(put_user(nr, &user_arg->nr)); - try(put_user(total, &user_arg->total)); + try(put_user(le32_to_cpu(st.master_subvol), user_master_subvol)); + try(put_user(le32_to_cpu(st.root_snapshot), user_root_snapshot)); + try(put_user(nr, user_nr)); + try(put_user(total, user_total)); if (size && size < total) return -ERANGE; @@ -861,6 +1340,53 @@ static long bch2_ioctl_snapshot_tree(struct bch_fs *c, struct file *filp, return 0; } +static long bch2_ioctl_snapshot_tree(struct bch_fs *c, struct file *filp, + struct bch_ioctl_snapshot_tree_query __user *user_arg) +{ + struct bch_ioctl_snapshot_tree_query arg; + try(copy_from_user_errcode(&arg, user_arg, sizeof(arg))); + + if (arg.pad) + return bch_err_throw(c, EINVAL_snapshot_tree_query_pad); + + return __bch2_ioctl_snapshot_tree(c, filp, arg.tree_id, arg.nr, + sizeof(struct bch_ioctl_snapshot_node), + &user_arg->nodes, + &user_arg->master_subvol, + &user_arg->root_snapshot, + &user_arg->nr, + &user_arg->total); +} + +static long bch2_ioctl_snapshot_tree_v2(struct bch_fs *c, struct file *filp, + struct bch_ioctl_snapshot_tree_query_v2 __user *user_arg) +{ + struct bch_ioctl_snapshot_tree_query_v2 arg; + try(copy_from_user_errcode(&arg, user_arg, sizeof(arg))); + + /* + * A caller that doesn't know its own node size can't be given one + * safely - we'd have to guess its stride: + */ + if (!arg.node_size) + return bch_err_throw(c, EINVAL_snapshot_tree_query_pad); + + u32 node_size = min_t(u32, arg.node_size, + sizeof(struct bch_ioctl_snapshot_node_v2)); + + /* Tell the caller what we have, so it knows which fields are set: */ + try(put_user((u32) sizeof(struct bch_ioctl_snapshot_node_v2), + &user_arg->node_size)); + + return __bch2_ioctl_snapshot_tree(c, filp, arg.tree_id, arg.nr, + node_size, + &user_arg->nodes, + &user_arg->master_subvol, + &user_arg->root_snapshot, + &user_arg->nr, + &user_arg->total); +} + static int bch2_propagate_opts_to_reflink_v(struct btree_trans *trans, struct bch_inode_opts *opts, struct bkey_s_c_reflink_p p) @@ -1090,6 +1616,18 @@ long bch2_fs_file_ioctl(struct file *file, unsigned cmd, unsigned long arg) (void __user *) arg); break; + case BCHFS_IOC_GET_DAMAGE: + ret = bch2_ioc_get_damage(c, file, (void __user *) arg); + break; + + case BCHFS_IOC_READDIR_FLAGS: + ret = bch2_ioc_readdir_flags(c, file, (void __user *) arg); + break; + + case BCHFS_IOC_CLEAR_DAMAGE: + ret = bch2_ioc_clear_damage(c, file); + break; + case BCHFS_IOC_SET_REFLINK_P_MAY_UPDATE_OPTS: ret = bch2_ioc_set_reflink_p_may_update_opts(c, file, inode); break; @@ -1169,6 +1707,11 @@ long bch2_fs_file_ioctl(struct file *file, unsigned cmd, unsigned long arg) (struct bch_ioctl_snapshot_tree_query __user *) arg); break; + case BCH_IOCTL_SNAPSHOT_TREE_v2: + ret = bch2_ioctl_snapshot_tree_v2(c, file, + (struct bch_ioctl_snapshot_tree_query_v2 __user *) arg); + break; + case BCHFS_IOC_PREAD_RAW: ret = bch2_ioc_pread_raw(file, inode, (struct bch_ioctl_pread_raw __user *) arg); diff --git a/fs/vfs/pagecache.c b/fs/vfs/pagecache.c index e06400a096..094d6f410f 100644 --- a/fs/vfs/pagecache.c +++ b/fs/vfs/pagecache.c @@ -228,10 +228,10 @@ int bch2_folio_set(struct bch_fs *c, int ret = bch2_trans_run(c, for_each_btree_key_in_subvolume_max(trans, iter, BTREE_ID_extents, - POS(inode->ei_inum.inum, offset), - POS(inode->ei_inum.inum, U64_MAX), - inode->ei_inum.subvol, BTREE_ITER_slots, k, ({ - unsigned nr_ptrs = bch2_bkey_nr_ptrs_fully_allocated(c, k); + POS(inode_inum(inode).inum, offset), + POS(inode_inum(inode).inum, U64_MAX), + inode_inum(inode).subvol, BTREE_ITER_slots, k, ({ + unsigned nr_ptrs = bch2_bkey_durability_safe(c, k).nr_overwritable; unsigned state = bkey_to_sector_state(c, k); while (folio_idx < nr_folios) { @@ -287,7 +287,7 @@ void bch2_bio_page_state_set(const struct bch_fs *c, struct bio *bio, struct bke struct bvec_iter iter; struct folio_vec fv; unsigned nr_ptrs = k.k->type == KEY_TYPE_reflink_v - ? 0 : bch2_bkey_nr_ptrs_fully_allocated(c, k); + ? 0 : bch2_bkey_durability_safe(c, k).nr_overwritable; unsigned state = bkey_to_sector_state(c, k); bio_for_each_folio(fv, bio, iter) diff --git a/fs/vfs/types.h b/fs/vfs/types.h index 02cf90deff..996222474d 100644 --- a/fs/vfs/types.h +++ b/fs/vfs/types.h @@ -3,12 +3,40 @@ #define _BCACHEFS_VFS_TYPES_H #include +#include +#include "snapshots/types.h" #include "util/fast_list.h" +/* + * An inode number that something in memory is holding: membership in + * @inodes_by_inum_table below. + * + * bch2_inode_or_descendents_is_open() consults that table and nothing else, so + * that fsck won't delete an unlinked inode out from under a live reference. + * Membership - not the existence of a bch_inode_info - is therefore what + * matters, and this is a standalone type so an entry can be held without one: + * an unlinked on-disk inode becomes visible to a scanning fsck pass at + * bch2_trans_commit(), which for O_TMPFILE is before __bch2_create() has a VFS + * inode to hash. + * + * @inum is kept whole rather than split into its fields because + * @inodes_table keys on the entire subvol_inum. + */ +struct bch_inum_hash_entry { + struct rhlist_head hash; + subvol_inum inum; +}; + struct bch_fs_vfs { struct fast_list inodes; struct rhashtable inodes_table; + /* + * Keyed on the inode number alone, not (subvol, inum): a query asks + * whether any snapshot version of an inode number is held, so every + * version has to land in one bucket. Hence an rhltable - the key is + * deliberately non-unique. + */ struct rhltable inodes_by_inum_table; struct bio_set writepage_bioset; diff --git a/include/linux/bits.h b/include/linux/bits.h index 4b0c214155..1b19aedc39 100644 --- a/include/linux/bits.h +++ b/include/linux/bits.h @@ -54,7 +54,6 @@ #define GENMASK_U16(h, l) GENMASK_TYPE(u16, h, l) #define GENMASK_U32(h, l) GENMASK_TYPE(u32, h, l) #define GENMASK_U64(h, l) GENMASK_TYPE(u64, h, l) -#define GENMASK_U128(h, l) GENMASK_TYPE(u128, h, l) #else /* defined(__ASSEMBLY__) */ diff --git a/include/linux/kernel.h b/include/linux/kernel.h index d71a124aad..92bb7fe5de 100644 --- a/include/linux/kernel.h +++ b/include/linux/kernel.h @@ -52,7 +52,6 @@ typedef unsigned gfp_t; typedef __u64 u64; typedef __s64 s64; -typedef unsigned __int128 u128; typedef __u32 u32; typedef __s32 s32; typedef __u16 u16; diff --git a/include/linux/local_lock.h b/include/linux/local_lock.h new file mode 100644 index 0000000000..01c5b3467d --- /dev/null +++ b/include/linux/local_lock.h @@ -0,0 +1,26 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#ifndef __LINUX_LOCAL_LOCK_H +#define __LINUX_LOCAL_LOCK_H + +/* + * Userspace shim: in the kernel, local_lock pins the cpu and provides + * per-cpu mutual exclusion (a real lock on PREEMPT_RT, irq/preempt + * disable otherwise). The userspace tools don't have percpu data in the + * kernel sense - these are the same no-ops the irqsave shim provides. + */ + +typedef struct local_lock { + unsigned char pad; /* zero-sized structs confuse bindgen */ +} local_lock_t; + +#define INIT_LOCAL_LOCK(name) {} + +#define local_lock_init(l) do {} while (0) + +#define local_lock_irqsave(l, flags) \ + do { (void) (l); flags = 0; } while (0) + +#define local_unlock_irqrestore(l, flags) \ + do { (void) (l); (void) (flags); } while (0) + +#endif /* __LINUX_LOCAL_LOCK_H */ diff --git a/include/linux/math64.h b/include/linux/math64.h index c641688cdb..1bd541fb43 100644 --- a/include/linux/math64.h +++ b/include/linux/math64.h @@ -56,10 +56,51 @@ static inline u64 div64_u64(u64 dividend, u64 divisor) * mul_u64_u64_div_u64 - unsigned 64bit multiply then divide, with a 128bit * intermediate */ +#ifdef __SIZEOF_INT128__ static inline u64 mul_u64_u64_div_u64(u64 a, u64 b, u64 c) { return (unsigned __int128) a * b / c; } +#else +/* + * Portable fallback for targets without __int128 (32-bit): full 128-bit + * product by parts, then restoring shift-subtract division. Slow but + * obviously correct; saturates when the quotient won't fit 64 bits (a + * caller bug either way). + */ +static inline u64 mul_u64_u64_div_u64(u64 a, u64 b, u64 c) +{ + u64 t1 = (a >> 32) * (b & 0xffffffff); + u64 t2 = (a & 0xffffffff) * (b >> 32); + u64 lo = (a & 0xffffffff) * (b & 0xffffffff); + u64 hi = (a >> 32) * (b >> 32); + + u64 mid = t1 + t2; + if (mid < t1) + hi += 1ULL << 32; + hi += mid >> 32; + + u64 mid_lo = mid << 32; + lo += mid_lo; + if (lo < mid_lo) + hi++; + + if (hi >= c) + return U64_MAX; + + u64 rem = hi, q = 0; + for (int i = 63; i >= 0; i--) { + int ovf = rem >> 63; + + rem = (rem << 1) | ((lo >> i) & 1); + if (ovf || rem >= c) { + rem -= c; + q |= 1ULL << i; + } + } + return q; +} +#endif /** * div64_s64 - signed 64bit divide with 64bit divisor diff --git a/include/linux/percpu.h b/include/linux/percpu.h index 695da3f6b0..a4e4212d44 100644 --- a/include/linux/percpu.h +++ b/include/linux/percpu.h @@ -48,7 +48,14 @@ extern char __start_bch_percpu[], __stop_bch_percpu[]; * Static section is sized at link time (__stop_bch_percpu - __start_bch_percpu); * dynamic arena is BCH_PERCPU_DYNAMIC_SIZE bytes for alloc_percpu(). */ -#define BCH_PERCPU_DYNAMIC_SIZE (512 * 1024) +/* + * Address space per chunk, not memory: chunks are NORESERVE anonymous + * mappings, so pages materialize only as allocations touch them. Sized + * for the largest consumer - gc's accounting table allocates a percpu + * counter set per accounting key, and a large filesystem with many + * snapshots has hundreds of thousands of those. + */ +#define BCH_PERCPU_DYNAMIC_SIZE (256UL * 1024 * 1024) extern __thread void *bch_percpu_my_chunk; extern __thread int bch_percpu_my_id; diff --git a/include/linux/rcupdate.h b/include/linux/rcupdate.h index 9ddaee34e1..81462b752f 100644 --- a/include/linux/rcupdate.h +++ b/include/linux/rcupdate.h @@ -12,10 +12,57 @@ #define rcu_dereference_protected(p, c) rcu_dereference(p) #define rcu_access_pointer(p) READ_ONCE(p) -#define kfree_rcu(ptr, rcu_head) kfree(ptr) /* XXX */ -#define kfree_rcu_mightsleep(ptr) kfree(ptr) /* XXX */ -#define kvfree_rcu(ptr, rcu_head) kfree(ptr) /* XXX */ -#define kvfree_rcu_mightsleep(ptr) kfree(ptr) /* XXX */ +/* + * These defer the free to the end of a grace period, as the kernel versions + * do. They previously expanded to a plain kfree(), which is a use-after-free + * anywhere a reader is concurrent - and shared fs/ code is written against + * the kernel's semantics: bch2_snapshot_table_make() frees the snapshot table + * this way while every rcu_dereference(c->snapshots.table) reader is live, and + * bch2_btree_bkey_cached_common_lock_held()'s neighbours in btree/interior.c + * carry a comment saying a concurrent lookup will memcmp freed memory + * otherwise. + * + * The rcu_head embedded in the object can't be used directly: call_rcu() hands + * the callback &obj->rcu, and free() needs the base of the allocation, which + * isn't recoverable from that without knowing the field's offset. So carry the + * pointer in a wrapper. + * + * If the wrapper can't be allocated, block for a grace period rather than free + * under readers - slow, but the alternative is the bug this replaced. + */ +struct rcu_free_wrapper { + struct rcu_head rcu; + void *p; +}; + +static inline void rcu_free_wrapper_cb(struct rcu_head *head) +{ + struct rcu_free_wrapper *w = + container_of(head, struct rcu_free_wrapper, rcu); + + free(w->p); + free(w); +} + +static inline void rcu_free_ptr(void *p) +{ + if (!p) + return; + + struct rcu_free_wrapper *w = malloc(sizeof(*w)); + if (w) { + w->p = p; + call_rcu(&w->rcu, rcu_free_wrapper_cb); + } else { + synchronize_rcu(); + free(p); + } +} + +#define kfree_rcu(ptr, rcu_head) rcu_free_ptr(ptr) +#define kfree_rcu_mightsleep(ptr) rcu_free_ptr(ptr) +#define kvfree_rcu(ptr, rcu_head) rcu_free_ptr(ptr) +#define kvfree_rcu_mightsleep(ptr) rcu_free_ptr(ptr) #define RCU_INIT_POINTER(p, v) WRITE_ONCE(p, v) diff --git a/include/linux/wait.h b/include/linux/wait.h index bfd40a5f45..ec4fdb2227 100644 --- a/include/linux/wait.h +++ b/include/linux/wait.h @@ -113,6 +113,8 @@ do { \ __ret; \ }) +#define wait_event_killable_timeout(wq, condition, timeout) ({wait_event_timeout(wq, condition, timeout); 0; }) + void wake_up_bit(void *, int); void __wait_on_bit(void *, int, unsigned); void __wait_on_bit_lock(void *, int, unsigned); diff --git a/linux/percpu.c b/linux/percpu.c index 7a2ea598be..174e2f8bde 100644 --- a/linux/percpu.c +++ b/linux/percpu.c @@ -31,7 +31,7 @@ * * The dynamic allocator is bump + freelist. Allocations return zeroed * memory across all live chunks; new threads get zeroed chunks via - * calloc, which preserves the contract on subsequent allocations. + * anonymous mmap, which preserves the contract on subsequent allocations. * * Caller contract for alloc_percpu(): zero-init must be a valid initial * state. Things that need real per-instance setup (semaphores etc.) @@ -42,6 +42,7 @@ #include #include #include +#include #include @@ -128,18 +129,31 @@ void bch_percpu_thread_init(void) pthread_mutex_lock(&bch_percpu_lock); - if (!bch_percpu_static_size) + if (!bch_percpu_static_size) { bch_percpu_static_size = __stop_bch_percpu - __start_bch_percpu; + /* + * The resolve macro distinguishes static-section addresses + * from dynamic offsets with a single threshold check: + */ + if ((uintptr_t) __start_bch_percpu < + bch_percpu_static_size + BCH_PERCPU_DYNAMIC_SIZE) { + fprintf(stderr, "bch_percpu: static section below dynamic offset range\n"); + abort(); + } + } + + /* Address space, not memory - pages fault in as they're touched: */ size_t chunk_size = bch_percpu_static_size + BCH_PERCPU_DYNAMIC_SIZE; - void *chunk = calloc(1, chunk_size); - if (!chunk) { + void *chunk = mmap(NULL, chunk_size, PROT_READ|PROT_WRITE, + MAP_PRIVATE|MAP_ANONYMOUS|MAP_NORESERVE, -1, 0); + if (chunk == MAP_FAILED) { pthread_mutex_unlock(&bch_percpu_lock); - fprintf(stderr, "bch_percpu_thread_init: out of memory\n"); + fprintf(stderr, "bch_percpu_thread_init: chunk mmap failed\n"); abort(); } - int my_id = bch_percpu_nr_cpus++; + int my_id = bch_percpu_nr_cpus; if (my_id >= BCH_PERCPU_MAX_CPUS) { pthread_mutex_unlock(&bch_percpu_lock); fprintf(stderr, "bch_percpu_thread_init: too many threads (max %d)\n", @@ -158,6 +172,15 @@ void bch_percpu_thread_init(void) darray_for_each(dynamic_inits, di) di->init(__bch_percpu_resolve(di->pcv, chunk), di->ctx, my_id); + /* + * Publish the slot last. Readers don't take bch_percpu_lock: they walk + * [0, bch_percpu_nr_cpus) and per_cpu_ptr() dereferences the chunk + * without a NULL check, so bumping the count before the chunk is + * installed and initialized hands them a NULL - or a chunk whose + * counters haven't been zeroed yet. + */ + smp_store_release(&bch_percpu_nr_cpus, my_id + 1); + pthread_mutex_unlock(&bch_percpu_lock); } @@ -228,7 +251,7 @@ void *__alloc_percpu_gfp(size_t size, size_t align, gfp_t gfp) size_at_grain[off / BCH_PERCPU_GRAIN] = size / BCH_PERCPU_GRAIN; /* Zero across all live chunks (covers reuse from free list; new - * threads get calloc'd chunks so the slot is already zero in chunks + * threads get zero-filled mmap'd chunks so the slot is already zero in chunks * created later). */ size_t chunk_off = bch_percpu_static_size + off; for (int cpu = 0; cpu < bch_percpu_nr_cpus; cpu++) @@ -295,7 +318,7 @@ static void bch_percpu_module_exit(void) if (callbacks[i].exit_one) callbacks[i].exit_one(__bch_percpu_resolve(callbacks[i].pcv, chunk)); - free(chunk); + munmap(chunk, bch_percpu_static_size + BCH_PERCPU_DYNAMIC_SIZE); bch_percpu_chunks[cpu] = NULL; } darray_exit(&free_runs); diff --git a/package-ci/scripts/generate-status-html.sh b/package-ci/scripts/generate-status-html.sh new file mode 100755 index 0000000000..3ad8dfa36d --- /dev/null +++ b/package-ci/scripts/generate-status-html.sh @@ -0,0 +1,106 @@ +#!/bin/bash +# Generate static CI status page at $PUBLIC_HTML/ci.html +# +# Called by the orchestrator after each build status change. + +STATE_DIR="${STATE_DIR:-/home/aptbcachefsorg/package-ci}" +PUBLIC_HTML="${PUBLIC_HTML:-/home/aptbcachefsorg/public_html}" +GIT_REPO="${GIT_REPO:-/var/www/git/bcachefs-tools.git}" + +DESIRED_FILE="$STATE_DIR/desired" +[ -f "$DESIRED_FILE" ] || exit 0 +DESIRED="$(cat "$DESIRED_FILE")" + +# A queued release. The page knew only about "desired", so a release that was +# never queued - or queued and not yet built - looked identical to nothing +# happening. That is how v1.39.0 sat misversioned in the release suite for a +# day with every job on this page green. +DESIRED_RELEASE="$(cat "$STATE_DIR/desired-release" 2>/dev/null)" + +# sha -> tag, in one git call rather than a describe per commit: this runs on +# every status change and there are hundreds of build dirs. show-ref -d prints +# the annotated tag object and then the peeled commit as "^{}", so both +# the tag object and the commit resolve to the name. +declare -A TAGS +while read -r sha ref; do + ref="${ref%^\{\}}" + TAGS["$sha"]="${ref#refs/tags/}" +done < <(git --git-dir="$GIT_REPO" show-ref --tags -d 2>/dev/null) + +OUTPUT="$PUBLIC_HTML/ci.html" +TMP="$OUTPUT.tmp$$" +# Don't strand the temp file when generate fails: there has been a +# ci.html.tmp662915 sitting in the web root since June. +trap 'rm -f "$TMP"' EXIT + +generate() { + cat << 'EOF' + + + + + +bcachefs-tools CI + + + +

bcachefs-tools CI

+EOF + + for commit_dir in $(ls -dt "$STATE_DIR/builds"/*/); do + commit="$(basename "$commit_dir")" + short="${commit:0:12}" + marker="" + [ "$commit" = "$DESIRED" ] && marker=" ← desired" + [ -n "$DESIRED_RELEASE" ] && [ "$commit" = "$DESIRED_RELEASE" ] && + marker="$marker ← release queued" + + # Name the tag if there is one. Without this a release is + # indistinguishable from any other commit on this page. + tag="${TAGS[$commit]}" + [ -n "$tag" ] && short="$tag $short" + + echo "

commit $short$marker

" + echo "" + echo "" + + total=0; ndone=0; nfailed=0; nbuilding=0 + for job_dir in $(ls -d "$commit_dir"*/); do + job="$(basename "$job_dir")" + [ "$job" = "source" ] && continue + status="$(cat "$job_dir/status" 2>/dev/null || echo pending)" + ((total++)) + case "$status" in + done) ((ndone++)); sym="✓" ;; + failed) ((nfailed++)); sym="✗" ;; + building) ((nbuilding++)); sym="…" ;; + *) sym="·" ;; + esac + echo "" + done + + echo "
jobstatus
$job$sym $statuslog
" + echo -n "

$ndone/$total done" + [ "$nfailed" -gt 0 ] && echo -n ", $nfailed failed" + [ "$nbuilding" -gt 0 ] && echo -n ", $nbuilding building" + echo "

" + done + + UPDATED="$(date -u '+%Y-%m-%d %H:%M UTC')" + echo "

updated $UPDATED · refreshes every 30s

" + echo "" +} + +generate > "$TMP" && mv "$TMP" "$OUTPUT" diff --git a/package-ci/scripts/post-receive b/package-ci/scripts/post-receive index 7eae8f7085..2db67d0061 100755 --- a/package-ci/scripts/post-receive +++ b/package-ci/scripts/post-receive @@ -16,18 +16,47 @@ queue_build() { local commit=$1 local file=${2:-desired} - echo "$commit" > "$STATE_DIR/$file" + # Check the write. This used to be unconditional and printed "queued" even + # when the redirect had failed. v1.39.0's release build was never queued - + # the state dir wasn't writable by the pushing user, so creating + # desired-release got EACCES - and the push reported success anyway. It went + # out as a snapshot version, sorting below the 1.38.8 already in the suite, + # and nobody found out for a day. + if ! echo "$commit" > "$STATE_DIR/$file" 2>/dev/null; then + echo "CI: FAILED to queue ${commit:0:12}: cannot write $STATE_DIR/$file" >&2 + echo "CI: this build will NOT happen" >&2 + return 1 + fi echo "CI: queued build for ${commit:0:12} ($file)" - if [ -f "$PID_FILE" ]; then - kill -USR1 "$(cat "$PID_FILE")" 2>/dev/null || true + # Waking the orchestrator is best-effort and doesn't currently work at all: + # the hook runs as the pushing user, which can't signal the orchestrator's + # uid. Verified 2026-08-04 - kent got EPERM signalling the running + # aptbcachefsorg process. Presumably it has been that way since the uids + # were split, but that's inference; what's measured is today. + # + # It costs latency rather than correctness, since the reconcile loop polls + # anyway - but don't print that we did it when we didn't. + if [ -f "$PID_FILE" ] && kill -USR1 "$(cat "$PID_FILE")" 2>/dev/null; then + echo "CI: woke orchestrator" fi } +# publish_doc COMMIT +# Rebuilds the Principles of Operation and installs it for bcachefs.org. +# Detached: this is a full nix build of the tools plus LaTeX, and a push +# must not block on it. A failed build leaves the published PDF alone and +# says so in /var/log/publish-poo.log. +publish_doc() { + setsid /usr/local/bin/publish-poo "$1" /dev/null 2>&1 & + echo "doc: queued PoO build for ${1:0:12}" +} + while read oldrev newrev refname; do case "$refname" in refs/heads/master) queue_build "$newrev" + publish_doc "$newrev" ;; refs/tags/v*) # Release tags may be pushed without (or after) a branch diff --git a/package-ci/scripts/publish.sh b/package-ci/scripts/publish.sh index cd41233c18..dc0585ae3c 100755 --- a/package-ci/scripts/publish.sh +++ b/package-ci/scripts/publish.sh @@ -170,7 +170,7 @@ cat >> "$PUBLISH_ROOT/.footer/README.html" << 'FOOTER' sudo tee /etc/apt/sources.list.d/apt.bcachefs.org.sources > /dev/null <<SOURCES Types: deb deb-src -URIs: https://apt.bcachefs.org/unstable/ +URIs: https://apt.bcachefs.org/$(. /etc/os-release && echo ${VERSION_CODENAME})/ Suites: bcachefs-tools-release Components: main Signed-By: /etc/apt/keyrings/apt.bcachefs.org.asc @@ -179,6 +179,16 @@ SOURCES sudo apt update sudo apt install bcachefs-tools +

Important: packages are built per distribution — the URI must +name your release codename (the snippet above fills it in from +/etc/os-release). Repositories exist for the directories listed +above (e.g. trixie, forky, plucky, +questing, resolute); unstable is built +against Debian sid and its dependencies will often not be installable on +stable releases. If you previously configured this repo with +unstable in the URI and you're not on sid, edit +/etc/apt/sources.list.d/apt.bcachefs.org.sources and replace it +with your codename.

Note: For latest git master packages, replace bcachefs-tools-release with bcachefs-tools-snapshot.

Stable channel: Suites: bcachefs-tools-release

Snapshot/nightly channel: Suites: bcachefs-tools-snapshot

diff --git a/src/bcachefs.rs b/src/bcachefs.rs index aa534ce4bf..df5f656474 100644 --- a/src/bcachefs.rs +++ b/src/bcachefs.rs @@ -8,7 +8,9 @@ mod logging; mod qcow2; mod util; mod wrappers; -mod http; +pub mod http; +#[cfg(test)] +mod eytzinger_test; use std::process::ExitCode; use bch_bindgen::c; diff --git a/src/commands/attr.rs b/src/commands/attr.rs index 37eb070d9c..6977bab73f 100644 --- a/src/commands/attr.rs +++ b/src/commands/attr.rs @@ -10,18 +10,9 @@ use rustix::fs::{XattrFlags, setxattr, removexattr}; use super::opts; -const BCHFS_IOC_REINHERIT_ATTRS: libc::Ioctl = 0x8008bc40u32 as libc::Ioctl; -const BCHFS_IOC_SET_REFLINK_P_MAY_UPDATE_OPTS: libc::Ioctl = 0xbc41u32 as libc::Ioctl; -const BCHFS_IOC_PROPAGATE_REFLINK_P_OPTS: libc::Ioctl = 0xbc42u32 as libc::Ioctl; - -/// Call a no-argument ioctl, returning io::Result. -fn ioctl_none(fd: i32, request: libc::Ioctl) -> std::io::Result<()> { - if unsafe { libc::ioctl(fd, request) } < 0 { - Err(std::io::Error::last_os_error()) - } else { - Ok(()) - } -} +use crate::wrappers::ioctl::{ioctl_none, Ioctl, + BCHFS_IOC_PROPAGATE_REFLINK_P_OPTS, BCHFS_IOC_REINHERIT_ATTRS, + BCHFS_IOC_SET_REFLINK_P_MAY_UPDATE_OPTS}; fn propagate_recurse(dir_path: &Path) { let inner = || -> std::io::Result<()> { @@ -31,7 +22,12 @@ fn propagate_recurse(dir_path: &Path) { if ft.is_symlink() { continue } let Ok(name) = CString::new(entry.file_name().as_bytes().to_vec()) else { continue }; - let ret = unsafe { libc::ioctl(dir.as_raw_fd(), BCHFS_IOC_REINHERIT_ATTRS, name.as_ptr()) }; + /* the argument is the name pointer itself, not a pointer to a struct */ + let ret = unsafe { + libc::ioctl(dir.as_raw_fd(), + BCHFS_IOC_REINHERIT_ATTRS::OPCODE as libc::Ioctl, + name.as_ptr()) + }; if ret < 0 { eprintln!("{}: {}", entry.path().display(), std::io::Error::last_os_error()); continue; @@ -233,14 +229,13 @@ the flag on such pointers before propagating.") fn do_reflink_propagate(path: &str, set_may_update: bool) -> Result<()> { let file = std::fs::File::open(path)?; - let fd = file.as_raw_fd(); if set_may_update { - ioctl_none(fd, BCHFS_IOC_SET_REFLINK_P_MAY_UPDATE_OPTS) + ioctl_none::(&file) .context("set may_update_opts")?; } - ioctl_none(fd, BCHFS_IOC_PROPAGATE_REFLINK_P_OPTS).map_err(|e| { + ioctl_none::(&file).map_err(|e| { if e.raw_os_error() == Some(libc::EPERM) { anyhow!("reflink_p extents without may_update_options set;\n\ rerun as root with --set-may-update") diff --git a/src/commands/damage.rs b/src/commands/damage.rs new file mode 100644 index 0000000000..ee6ee9a2be --- /dev/null +++ b/src/commands/damage.rs @@ -0,0 +1,301 @@ +// commands/damage.rs — show recorded filesystem damage +// +// The damage btree persistently records which inodes were damaged by +// errors and repairs. Two ioctls, layered: BCHFS_IOC_READDIR_FLAGS with +// damaged finds the files - cost proportional to recorded damage, +// not tree size - and BCHFS_IOC_GET_DAMAGE per file returns its +// accumulated error list (unioned across ancestor snapshots) as +// bch_sb_error_id, printed with the same names fsck and the superblock +// error counters use. + +use std::mem; +use std::os::fd::OwnedFd; +use std::path::{Path, PathBuf}; + +use anyhow::{bail, Context, Result}; +use bch_bindgen::c; +use clap::{Parser, Subcommand}; + +use crate::util::{open_dir, sb_error_name}; +use crate::wrappers::ioctl::{ioctl_none, ioctl_ptr, ioctl_rw, IoctlBuf, + BCHFS_IOC_CLEAR_DAMAGE, BCHFS_IOC_GET_DAMAGE, BCHFS_IOC_READDIR_FLAGS}; + +/// DT_SUBVOL from dirent_format.h; not in the generated bindings. +const DT_SUBVOL: u8 = 16; + +/// Show recorded damage +#[derive(Parser, Debug)] +#[command(args_conflicts_with_subcommands = true)] +pub struct Cli { + #[command(subcommand)] + subcommands: Option, + + /// File to report recorded damage on + path: Option, +} + +#[derive(Subcommand, Debug)] +enum Subcommands { + /// List damaged files in a directory + Ls { + /// Recurse: damaged files anywhere under this directory + #[arg(short = 'R')] + recursive: bool, + + /// Directory to list (default: current directory) + path: Option, + }, + + /// Clear recorded damage. Requires owning the file, like chattr; + /// snapshots keep their view of the record. + Clear { + /// Recurse: also clear every damaged file under this directory + #[arg(short = 'R')] + recursive: bool, + + path: PathBuf, + }, +} + +// ---- Ioctl layer ---- + +/// One accumulated damage record, unpacked from +/// bch_sb_field_error_entry_v2 - the same record the errors superblock +/// section keeps: error id, a saturating occurrence count, and first and +/// last occurrence times. +struct DamageEntry { + id: u32, + nr: u64, + first: i64, + last: i64, +} + +fn fmt_time(t: i64) -> String { + chrono::DateTime::from_timestamp(t, 0) + .map(|t| t.format("%Y-%m-%d %H:%M:%S").to_string()) + .unwrap_or_else(|| t.to_string()) +} + +impl DamageEntry { + fn first_seen(&self) -> String { + fmt_time(self.first) + } + fn last_seen(&self) -> String { + fmt_time(self.last) + } +} + +/// BCHFS_IOC_GET_DAMAGE: nr_entries in is capacity, out is the true +/// count - retry bigger if we undershot. +fn get_damage(fd: &OwnedFd) -> std::io::Result> { + let mut cap = 16u32; + loop { + let mut buf = IoctlBuf::::new::(cap as usize); + buf.hdr_mut().nr_entries = cap; + unsafe { ioctl_ptr::(fd, buf.as_mut_ptr())? }; + + let nr = buf.hdr().nr_entries; + if nr > cap { + cap = nr; + continue; + } + + return Ok(unsafe { buf.hdr().entries.as_slice(nr as usize) }.iter() + .map(|e| DamageEntry { + id: e.id() as u32, + nr: e.nr(), + first: e.first_error_time() as i64, + last: e.last_error_time() as i64, + }).collect()); + } +} + +struct Entry { + d_type: u8, + /// A name, or in recursive mode a path relative to the ioctl'd + /// directory + name: Vec, +} + +/// One BCHFS_IOC_READDIR_FLAGS call, advancing the opaque cursor. An +/// empty result means enumeration is complete. +fn readdir_flags(fd: &OwnedFd, flags: u32, pos: &mut [u64; 2]) -> std::io::Result> { + let mut buf = vec![0u8; 64 << 10]; + let mut arg = c::bch_ioctl_readdir_flags { + pos: *pos, + buf: buf.as_mut_ptr() as u64, + buf_size: buf.len() as u32, + flags, + used: 0, + pad: 0, + }; + + ioctl_rw::(fd, &mut arg)?; + *pos = arg.pos; + + const D_TYPE: usize = mem::offset_of!(c::bch_ioctl_readdir_entry, d_type); + const NAME_LEN: usize = mem::offset_of!(c::bch_ioctl_readdir_entry, name_len); + const NAME: usize = mem::offset_of!(c::bch_ioctl_readdir_entry, name); + + let mut entries = Vec::new(); + let mut offset = 0usize; + while offset + NAME < arg.used as usize { + let rec = &buf[offset..]; + let name_len = u16::from_ne_bytes(rec[NAME_LEN..NAME_LEN + 2].try_into().unwrap()) as usize; + let reclen = (NAME + name_len).next_multiple_of(8); + if name_len == 0 || offset + reclen > arg.used as usize { + break; + } + + entries.push(Entry { + d_type: rec[D_TYPE], + /* name_len includes the nul */ + name: rec[NAME..NAME + name_len - 1].to_vec(), + }); + offset += reclen; + } + Ok(entries) +} + +// ---- Commands ---- + +/// The damage details for a listed entry, best effort: only inode types +/// we can open and ioctl (a device node's fd would take the ioctl to +/// the device driver). Recursive mode reports DT_UNKNOWN, so stat then. +fn entry_errors(dir: &OwnedFd, e: &Entry) -> Option> { + let mut d_type = e.d_type; + if d_type == libc::DT_UNKNOWN { + let st = rustix::fs::statat(dir, &*e.name, + rustix::fs::AtFlags::SYMLINK_NOFOLLOW).ok()?; + d_type = match st.st_mode & libc::S_IFMT { + libc::S_IFREG => libc::DT_REG, + libc::S_IFDIR => libc::DT_DIR, + _ => return None, + }; + } + if d_type != libc::DT_REG && d_type != libc::DT_DIR && d_type != DT_SUBVOL { + return None; + } + + let fd = rustix::fs::openat(dir, &*e.name, + rustix::fs::OFlags::RDONLY | rustix::fs::OFlags::CLOEXEC | rustix::fs::OFlags::NOFOLLOW, + rustix::fs::Mode::empty()).ok()?; + get_damage(&fd).ok() +} + +fn cmd_ls(path: &Path, recursive: bool) -> Result<()> { + let dir = open_dir(path)?; + let flags = c::BCH_READDIR_damaged | + if recursive { c::BCH_READDIR_recursive } else { 0 }; + + let mut pos = [0u64; 2]; + loop { + let entries = readdir_flags(&dir, flags, &mut pos) + .context("BCHFS_IOC_READDIR_FLAGS")?; + if entries.is_empty() { + return Ok(()); + } + + for e in &entries { + let name = String::from_utf8_lossy(&e.name); + match entry_errors(&dir, e) { + Some(errs) if !errs.is_empty() => + println!("{name}: {}", + errs.iter().map(|e| sb_error_name(e.id)) + .collect::>().join(" ")), + _ => println!("{name}"), + } + } + } +} + +fn cmd_show(path: &Path) -> Result<()> { + let meta = std::fs::metadata(path) + .with_context(|| format!("statting {}", path.display()))?; + if !meta.is_file() && !meta.is_dir() { + bail!("{}: not a regular file or directory", path.display()); + } + + let f = std::fs::File::open(path) + .with_context(|| format!("opening {}", path.display()))?; + let errs = get_damage(&f.into()).context("BCHFS_IOC_GET_DAMAGE")?; + + for e in errs { + println!("{:<48} nr {:<8} first {} last {}", + sb_error_name(e.id), e.nr, e.first_seen(), e.last_seen()); + } + Ok(()) +} + +fn clear_fd(fd: &OwnedFd) -> std::io::Result<()> { + ioctl_none::(fd).map(|_| ()) +} + +fn cmd_clear(path: &Path, recursive: bool) -> Result<()> { + let f = std::fs::File::open(path) + .with_context(|| format!("opening {}", path.display()))?; + clear_fd(&f.into()) + .with_context(|| format!("clearing damage on {}", path.display()))?; + + if !recursive { + return Ok(()); + } + + /* + * The damaged-only recursive listing is also the work list: entries + * vanish from it as they're cleared, and the cursor only moves + * forward, so clearing behind it is safe. Per-entry failures + * (ownership, racing renames) are reported and skipped. + */ + let dir = open_dir(path)?; + let flags = c::BCH_READDIR_damaged | c::BCH_READDIR_recursive; + let mut failed = 0u64; + + let mut pos = [0u64; 2]; + loop { + let entries = readdir_flags(&dir, flags, &mut pos) + .context("BCHFS_IOC_READDIR_FLAGS")?; + if entries.is_empty() { + break; + } + + for e in &entries { + let name = String::from_utf8_lossy(&e.name).into_owned(); + + let fd = match rustix::fs::openat(&dir, &*e.name, + rustix::fs::OFlags::RDONLY | rustix::fs::OFlags::CLOEXEC | rustix::fs::OFlags::NOFOLLOW, + rustix::fs::Mode::empty()) + { + Ok(fd) => fd, + Err(err) => { + eprintln!("{name}: {err}"); + failed += 1; + continue; + } + }; + + if let Err(err) = clear_fd(&fd) { + eprintln!("{name}: {err}"); + failed += 1; + } + } + } + + if failed != 0 { + bail!("failed to clear {failed} files"); + } + Ok(()) +} + +pub fn damage(cli: Cli) -> Result<()> { + match cli.subcommands { + Some(Subcommands::Ls { recursive, path }) => + cmd_ls(&path.unwrap_or_else(|| ".".into()), recursive), + Some(Subcommands::Clear { recursive, path }) => + cmd_clear(&path, recursive), + None => + cmd_show(&cli.path.context("a path, or the ls subcommand, is required")?), + } +} + +pub const CMD: super::CmdDef = typed_cmd!("damage", "Show recorded filesystem damage", Cli, damage); diff --git a/src/commands/data_read.rs b/src/commands/data_read.rs index 0745ec7548..2ca20a93e3 100644 --- a/src/commands/data_read.rs +++ b/src/commands/data_read.rs @@ -6,36 +6,13 @@ use std::fs::OpenOptions; use std::os::unix::fs::OpenOptionsExt; -use std::os::unix::io::AsRawFd; +use bch_bindgen::c; use clap::Parser; -const SECTOR_SIZE: u64 = 512; - -/// ioctl number: _IOWR(0xbc, 67, struct bch_ioctl_pread_raw) -const fn bchfs_ioc_pread_raw() -> libc::Ioctl { - let size = std::mem::size_of::() as u32; - ((3u32 << 30) | (size << 16) | (0xbcu32 << 8) | 67) as libc::Ioctl -} - -#[repr(C)] -#[derive(Default)] -struct BchIoctlErrMsg { - msg_ptr: u64, - msg_len: u32, - pad: u32, -} +use crate::wrappers::ioctl::{ioctl_rw, BCHFS_IOC_PREAD_RAW}; -#[repr(C)] -#[derive(Default)] -struct BchIoctlPreadRaw { - offset: u64, - len: u64, - buf: u64, - flags: u32, - errors: u32, - err: BchIoctlErrMsg, -} +const SECTOR_SIZE: u64 = 512; #[derive(Parser, Debug)] #[command(name = "data-read")] @@ -100,22 +77,20 @@ fn cmd_data_read_inner(cli: &Cli) -> anyhow::Result<()> { let mut err_msg_buf = vec![0u8; 4096]; - let mut arg = BchIoctlPreadRaw { + let mut arg = c::bch_ioctl_pread_raw { offset: cli.offset, len: cli.len, buf: buf as u64, flags: if cli.no_poison_check { 1 << 0 } else { 0 }, errors: 0, - err: BchIoctlErrMsg { + err: c::bch_ioctl_err_msg { msg_ptr: err_msg_buf.as_mut_ptr() as u64, msg_len: err_msg_buf.len() as u32, pad: 0, }, }; - let ret = unsafe { - libc::ioctl(file.as_raw_fd(), bchfs_ioc_pread_raw(), &mut arg as *mut _) - }; + let ret = ioctl_rw::(&file, &mut arg); // Show error info if arg.errors != 0 { @@ -134,8 +109,7 @@ fn cmd_data_read_inner(cli: &Cli) -> anyhow::Result<()> { eprintln!("kernel: {}", msg); } - if ret < 0 { - let errno = std::io::Error::last_os_error(); + if let Err(errno) = &ret { eprintln!("ioctl returned error: {}", errno); // Still dump whatever data we got — that's the point } @@ -173,7 +147,7 @@ fn cmd_data_read_inner(cli: &Cli) -> anyhow::Result<()> { unsafe { std::alloc::dealloc(buf, layout); } - if ret < 0 { + if ret.is_err() { std::process::exit(1); } diff --git a/src/commands/device.rs b/src/commands/device.rs index 06af1205d0..e8dc34b3c3 100644 --- a/src/commands/device.rs +++ b/src/commands/device.rs @@ -101,8 +101,8 @@ fn cmd_device_add_offline( force: bool, matches: &clap::ArgMatches, ) -> Result<()> { - let block_size = unsafe { (*fs.raw).opts.block_size as u32 }; - let btree_node_size = unsafe { (*fs.raw).opts.btree_node_size }; + let block_size = fs.opts().block_size as u32; + let btree_node_size = fs.opts().btree_node_size; device_add_format(dev_path, force, matches, block_size, btree_node_size)?; @@ -355,29 +355,30 @@ fn cmd_device_set_state(cli: SetStateCli) -> Result<()> { } fn set_state_offline(device: &str, new_state: u32) -> Result<()> { - use crate::wrappers::bch_err_str; - let c_path = CString::new(device)?; let mut opts: c::bch_opts = Default::default(); opt_set!(opts, nostart, 1); opt_set!(opts, degraded, bch_degraded_actions::BCH_DEGRADED_very as u8); // Read superblock to get dev_idx - let mut sb_handle: c::bch_sb_handle = Default::default(); - let ret = unsafe { c::bch2_read_super(c_path.as_ptr(), &mut opts, &mut sb_handle) }; - if ret != 0 { - return Err(anyhow!("error opening {}: {}", device, bch_err_str(ret))); - } + let sb_handle = bch_bindgen::sb::io::read_super_opts(Path::new(device), opts) + .map_err(|e| anyhow!("error opening {}: {}", device, e))?; let dev_idx = sb_handle.sb().dev_idx as u32; drop(sb_handle); let fs = crate::device_scan::open_scan(&[PathBuf::from(device)], opts) .map_err(|e| anyhow!("Error opening filesystem: {}", e))?; + if fs.disk_sb().sb().sb_initialized() == 0 { + return Err(anyhow!("superblock not initialized (filesystem was never started): \ + bch2_write_super would silently skip the write; mount it once first")); + } + { let _lock = fs.sb_lock(); unsafe { fs.member_mut(dev_idx) }.set_member_state(new_state as u64); - fs.write_super(); + fs.write_super_force() + .map_err(|e| anyhow!("error writing superblock: {}", e))?; } Ok(()) } @@ -388,25 +389,38 @@ pub struct ResizeCli { /// Device path device: String, - /// New size (human-readable, e.g. 1G); defaults to device size + /// New size (human-readable, e.g. 1G) or "cancel" (resizes to the currently persisted size); defaults to device size size: Option, } +enum SizeOrCancel { + Size(u64), + Cancel, +} fn cmd_device_resize(cli: ResizeCli) -> Result<()> { + use SizeOrCancel::*; let size_bytes = match cli.size { - Some(ref s) => parse_human_size(s)?, - None => device_size(&cli.device)?, + Some(ref s) => match s.as_str() { + "cancel" | "Cancel" => Cancel, + other => Size(parse_human_size(other)?), + }, + None => Size(device_size(&cli.device)?), + }; + let size_sectors = match size_bytes { + Size(bytes) => Size(bytes >> 9), + Cancel => Cancel, }; - let size_sectors = size_bytes >> 9; match open_dev(&cli.device) { Ok((handle, dev_idx)) => { println!("Doing online resize of {}", cli.device); - let usage = handle.dev_usage(dev_idx) - .context("querying device usage")?; - let nbuckets = size_sectors / usage.bucket_size as u64; + let usage = handle.dev_usage(dev_idx).context("querying device usage")?; + let nbuckets = match size_sectors { + Size(sectors) => sectors / usage.bucket_size as u64, + Cancel => usage.nr_buckets, + }; let shrinking = nbuckets < usage.nr_buckets; println!("resizing {} to {} buckets", cli.device, nbuckets); @@ -422,7 +436,7 @@ fn cmd_device_resize(cli: ResizeCli) -> Result<()> { Err(_) if Path::new(&cli.device).exists() => { println!("Doing offline resize of {}", cli.device); resize_offline(&cli.device, size_sectors)?; - } + }, Err(e) => return Err(e), } @@ -453,8 +467,10 @@ fn find_single_online_dev(fs: &Fs) -> Result { .ok_or_else(|| anyhow!("could not get reference to device {}", found_idx)) } -fn resize_offline(device: &str, size_sectors: u64) -> Result<()> { +fn resize_offline(device: &str, size_sectors: SizeOrCancel) -> Result<()> { use bcachefs_kernel::util::printbuf::Printbuf; + use SizeOrCancel::*; + let opts: c::bch_opts = Default::default(); let fs = crate::device_scan::open_scan(&[PathBuf::from(device)], opts) @@ -462,7 +478,10 @@ fn resize_offline(device: &str, size_sectors: u64) -> Result<()> { let ca = find_single_online_dev(&fs)?; - let nbuckets = size_sectors / ca.mi.bucket_size as u64; + let nbuckets = match size_sectors { + Size(sectors) => sectors / ca.mi.bucket_size as u64, + Cancel => ca.mi.nbuckets, + }; if nbuckets < ca.mi.nbuckets { bail!("shrinking not supported (requested {} buckets, have {})", diff --git a/src/commands/dump.rs b/src/commands/dump.rs index 10806ddb8f..0f90e0f676 100644 --- a/src/commands/dump.rs +++ b/src/commands/dump.rs @@ -325,8 +325,8 @@ fn sanitize_journal_keys( /// zero inline data, optionally scramble filenames, clear checksums. fn sanitize_journal(fs_raw: *mut c::bch_fs, buf: &mut [u8], opts: SanitizeOpts) { let fs = unsafe { Fs::borrow_raw(fs_raw) }; - let jset_magic = jset_magic(unsafe { &*(*fs_raw).disk_sb.sb }); - let block_bits = unsafe { (*fs_raw).block_bits } as usize; + let jset_magic = jset_magic(fs.disk_sb().sb()); + let block_bits = fs.block_bits() as usize; let mut pos = 0; while pos + JSET_HDR <= buf.len() { @@ -344,7 +344,7 @@ fn sanitize_journal(fs_raw: *mut c::bch_fs, buf: &mut [u8], opts: SanitizeOpts) let mut modified = false; if csum_type_is_encryption(csum_type) { - if !unsafe { (*fs_raw).chacha20_key_set } { + if !fs.chacha20_key_set() { eprintln!("found encrypted journal entry on non-encrypted filesystem"); return; } @@ -399,8 +399,8 @@ fn sanitize_journal(fs_raw: *mut c::bch_fs, buf: &mut [u8], opts: SanitizeOpts) /// encryption, zero inline data, optionally scramble filenames. fn sanitize_btree(fs_raw: *mut c::bch_fs, buf: &mut [u8], opts: SanitizeOpts) { let fs = unsafe { Fs::borrow_raw(fs_raw) }; - let bset_magic = bset_magic(unsafe { &*(*fs_raw).disk_sb.sb }); - let block_bits = unsafe { (*fs_raw).block_bits } as usize; + let bset_magic = bset_magic(fs.disk_sb().sb()); + let block_bits = fs.block_bits() as usize; // The node's packed-key format lives in the btree_node header at the start // of the buffer; packed keys are unpacked against it. @@ -453,7 +453,7 @@ fn sanitize_btree(fs_raw: *mut c::bch_fs, buf: &mut [u8], opts: SanitizeOpts) { let mut modified = false; if csum_type_is_encryption(csum_type) { - if !unsafe { (*fs_raw).chacha20_key_set } { + if !fs.chacha20_key_set() { eprintln!("found encrypted btree node on non-encrypted filesystem"); return; } @@ -702,8 +702,8 @@ fn dump_fs(fs: &Fs, cli: &DumpCli, sanitize: bool, sanitize_filenames: bool) -> let mut devs: Vec = (0..nr_devices).map(|_| DumpDev::new()).collect(); let entire_journal = !cli.nojournal; - let btree_node_size = unsafe { (*fs.raw).opts.btree_node_size as u64 }; - let block_size = unsafe { (*fs.raw).opts.block_size as u32 }; + let btree_node_size = fs.opts().btree_node_size as u64; + let block_size = fs.opts().block_size as u32; let mut nr_online = 0u32; let mut bucket_err: Option = None; diff --git a/src/commands/format.rs b/src/commands/format.rs index 878dbca335..befaf122f2 100644 --- a/src/commands/format.rs +++ b/src/commands/format.rs @@ -192,7 +192,7 @@ fn warn_same_parent_disk_replicas(cfg: &FormatConfig, devices: &[DevOpts]) { let mut by_parent: HashMap> = HashMap::new(); for dev in devices { - if let Some(parent) = crate::wrappers::bdev::fd_to_parent_disk_sysfs(dev.fd) { + if let Some(parent) = crate::wrappers::bdev::fd_to_parent_disk_sysfs(dev.fd()) { by_parent .entry(parent.display().to_string()) .or_default() @@ -323,7 +323,16 @@ fn parse_format_args(argv: Vec) -> Result { } } Some(v) => { - if opt.flags as u32 & c::opt_flags::OPT_DEVICE as u32 != 0 { + // String-member options (failure_domain) parse to a + // placeholder 0 - the parse is validation only, the + // value is the string itself, applied to the + // bch_member at superblock write time (the + // Opt_failure_domain arm in format_util.rs). + // Routing the placeholder into bch_opts would drop + // the string silently: + if opt.type_ == c::opt_type::BCH_OPT_STR_MEMBER { + push_dev_opt_str!(opt_id, val_str); + } else if opt.flags as u32 & c::opt_flags::OPT_DEVICE as u32 != 0 { bcachefs_kernel::opts::opt_set_by_id(&mut cur_dev_opts, opt_id, v); unconsumed_dev_option = true; } else if opt.flags as u32 & c::opt_flags::OPT_FS as u32 != 0 { @@ -442,6 +451,14 @@ fn parse_format_args(argv: Vec) -> Result { bail!("--source, --no_initialize are incompatible"); } + if source.is_some() && format_version.is_some() { + bail!("--version cannot be used with --source: populating the \ + filesystem runs the current code's write path, which upgrades \ + it to the current version as soon as it goes read-write - the \ + requested version would not survive. Format with --version \ + alone, then populate using tools of that version."); + } + if passphrase_file.is_some() && !encrypted { bail!("--passphrase_file requires --encrypted"); } @@ -587,7 +604,7 @@ fn cmd_format(argv: Vec) -> Result<()> { // user didn't specify them. let total_fs_size: u64 = devices.iter_mut().map(|d| { if d.fs_size == 0 { - d.fs_size = crate::wrappers::bdev::get_size(d.fd); + d.fs_size = crate::wrappers::bdev::get_size(d.fd()); } d.fs_size }).sum(); diff --git a/src/commands/format_util.rs b/src/commands/format_util.rs index 21b641f8ec..a5d6db170d 100644 --- a/src/commands/format_util.rs +++ b/src/commands/format_util.rs @@ -3,19 +3,21 @@ //! Rust implementation of bch2_format and bch2_format_for_device_add. use std::ffi::{CStr, CString}; +use std::os::fd::{AsFd, AsRawFd, BorrowedFd, OwnedFd}; use std::os::unix::fs::FileExt; -use std::os::unix::io::{IntoRawFd, RawFd}; +use std::os::unix::io::RawFd; use bch_bindgen::c; use bcachefs_kernel::{metadata_version, opt_defined, opt_get, opt_set}; -use crate::wrappers::super_io::{die, BCHFS_MAGIC, SUPERBLOCK_SIZE_DEFAULT}; +use crate::wrappers::super_io::{die, SUPERBLOCK_SIZE_DEFAULT}; +use bcachefs_kernel::sb::io::BCHFS_MAGIC; /// Device options for formatting — Rust replacement for C struct dev_opts. /// -/// Owns the file descriptor and string data. The fd is closed on drop. +/// Owns the file descriptor and string data. pub struct DevOpts { - pub fd: RawFd, + file: Option, pub path: CString, /// Deferred device options (labels): their values are resolved against /// the superblock being built, after it exists. @@ -31,7 +33,7 @@ impl DevOpts { /// Create a new DevOpts with the given path, no fd yet. pub fn new(path: CString) -> Self { DevOpts { - fd: -1, + file: None, path, opt_strs: Vec::new(), sb_offset: 0, @@ -42,6 +44,16 @@ impl DevOpts { } } + /// The device fd, for interfaces that take raw fds. + pub fn fd(&self) -> RawFd { + self.file.as_ref().map_or(-1, |f| f.as_raw_fd()) + } + + /// The device fd; panics if the device hasn't been opened. + pub fn as_fd(&self) -> BorrowedFd<'_> { + self.file.as_ref().expect("device not open").as_fd() + } + /// Open the device for formatting, with blkid checks. /// /// Adds READ|WRITE|EXCL|BUFFERED to the given extra flags @@ -49,26 +61,18 @@ impl DevOpts { pub fn open(&mut self, extra_mode: u32, force: bool) -> Result<(), i32> { use crate::wrappers::bdev::*; let mode = BLK_OPEN_READ | BLK_OPEN_WRITE | BLK_OPEN_EXCL | BLK_OPEN_BUFFERED | extra_mode; - self.fd = open_device(&self.path, mode)?.into_raw_fd(); - blkid_check(self.fd, &self.path, force); + self.file = Some(open_device(&self.path, mode)?); + blkid_check(self.fd(), &self.path, force); Ok(()) } /// Open the device without blkid checks or default flags (for migrate). pub fn open_no_blkid(&mut self, mode: u32) -> Result<(), i32> { - self.fd = crate::wrappers::bdev::open_device(&self.path, mode)?.into_raw_fd(); + self.file = Some(crate::wrappers::bdev::open_device(&self.path, mode)?); Ok(()) } } -impl Drop for DevOpts { - fn drop(&mut self) { - if self.fd >= 0 { - unsafe { libc::close(self.fd) }; - } - } -} - /// Features enabled on all new filesystems. /// Must match BCH_SB_FEATURES_ALL in bcachefs_format.h. const BCH_SB_FEATURES_ALL: u64 = { @@ -117,9 +121,8 @@ fn parse_target( } } - let idx = unsafe { c::bch2_disk_path_find(sb, s) }; - if idx >= 0 { - return group_to_target(idx as u32); + if let Some(idx) = sb.disk_path_find(target_str) { + return group_to_target(idx); } die(&format!("Invalid target {}", target_str.to_string_lossy())); @@ -157,7 +160,7 @@ pub fn format( // Get device size if not specified (needed for block size threshold) for dev in dev_slice.iter_mut() { if dev.fs_size == 0 { - dev.fs_size = crate::wrappers::bdev::get_size(dev.fd); + dev.fs_size = crate::wrappers::bdev::get_size(dev.fd()); } } @@ -214,7 +217,7 @@ pub fn format( // ManuallyDrop: we return sb.sb to the caller (who frees it), // so we must not let bch_sb_handle's Drop call bch2_free_super. let mut sb = std::mem::ManuallyDrop::new(c::bch_sb_handle::default()); - if unsafe { c::bch2_sb_realloc(&mut *sb, 0) } != 0 { + if sb.sb_realloc(0).is_err() { die("insufficient memory"); } @@ -283,7 +286,7 @@ pub fn format( m.nbuckets = dev.nbuckets.to_le(); m.first_bucket = 0; - let fd = dev.fd; + let fd = dev.fd(); let opts = &mut dev.opts; if opt_defined!(opts, rotational) == 0 { let nonrot = crate::wrappers::bdev::nonrot(fd); @@ -294,21 +297,28 @@ pub fn format( sb.member_mut(idx as u32).unwrap().set_member_rotational_set(1); } - // Deferred device options - labels: resolve against the sb we just built + // Deferred device options: labels resolve to a disk path against the sb we + // just built; the failure domain is a plain string stored in the member. for (idx, dev) in dev_slice.iter().enumerate() { for (opt_id, val) in &dev.opt_strs { - let path_idx = unsafe { c::bch2_disk_path_find_or_create(&mut *sb, val.as_ptr()) }; - if path_idx < 0 { - die(&format!( - "error creating disk path: {}", - std::io::Error::from_raw_os_error(-path_idx) - )); - } - - // Recompute m after sb modification (memory may have been reallocated) - let m = sb.member_mut(idx as u32).unwrap(); match *opt_id { - c::bch_opt_id::Opt_label => m.set_member_group(path_idx as u64 + 1), + c::bch_opt_id::Opt_label => { + let path_idx = sb.disk_path_find_or_create(val).unwrap_or_else(|e| + die(&format!("error creating disk path: {}", + std::io::Error::from_raw_os_error(e)))); + // Recompute m after sb modification (may have been reallocated) + sb.member_mut(idx as u32).unwrap().set_member_group(path_idx as u64 + 1); + } + c::bch_opt_id::Opt_failure_domain => { + let bytes = val.to_bytes(); + let m = sb.member_mut(idx as u32).unwrap(); + if bytes.len() > m.failure_domain.len() { + die(&format!("failure domain name too long (max {} bytes)", + m.failure_domain.len())); + } + m.failure_domain.fill(0); + m.failure_domain[..bytes.len()].copy_from_slice(bytes); + } _ => die(&format!("can't resolve option {:?} at format time", opt_id)), } } @@ -337,7 +347,7 @@ pub fn format( sb.sb_mut().set_sb_encryption_type(1); } - unsafe { c::bch2_sb_members_cpy_v2_v1(&mut *sb) }; + sb.members_cpy_v2_v1(); // Write superblocks to each device for (idx, dev) in dev_slice.iter_mut().enumerate() { @@ -362,7 +372,7 @@ pub fn format( return std::ptr::null_mut(); } - let fd = dev.fd; + let fd = dev.fd(); if dev.sb_offset == c::BCH_SB_SECTOR as u64 { // Zero start of disk @@ -372,7 +382,7 @@ pub fn format( .unwrap_or_else(|e| die(&format!("zeroing start of disk: {}", e))); } - crate::wrappers::super_io::bch2_super_write(fd, sb.sb); + crate::wrappers::super_io::bch2_super_write(fd, &mut *sb); } let paths: Vec<&str> = dev_slice @@ -494,7 +504,7 @@ pub fn pick_block_size(_fs_opts: &c::bch_opts, dev_slice: &[DevOpts]) -> u32 { let block_size = if total_size >= 1u64 << 30 { let mut bs = 4096u32; for dev in dev_slice.iter() { - bs = bs.max(crate::wrappers::bdev::get_blocksize_physical_hint(dev.fd)); + bs = bs.max(crate::wrappers::bdev::get_blocksize_physical_hint(dev.fd())); } bs } else { diff --git a/src/commands/fs_failure_domains.rs b/src/commands/fs_failure_domains.rs new file mode 100644 index 0000000000..3061b44430 --- /dev/null +++ b/src/commands/fs_failure_domains.rs @@ -0,0 +1,602 @@ +//! bcachefs fs failure-domains - what failure domain losses would cost, +//! from the replicas accounting. +//! +//! The replicas accounting gives us, for every distinct replica set in the +//! filesystem, the exact device list and sector count: a complete inventory +//! of what fails together, entirely in userspace. +//! +//! An entry tolerates some number of failed devices among its set: +//! - replicated data (nr_required <= 1): all but one may fail +//! - erasure coded stripes (nr_required = nr_data): nr_redundant may fail +//! +//! One table: the failure domains, with what losing each would cost. A +//! nonzero 'lost' cell is a separation violation - data that a single domain +//! failure would take out. Devices with no failure domain set are their own +//! domains, so with none configured this is the per device view. +//! +//! Limits: this is aggregate - it says how much data is exposed, not which +//! extents (that's reconcile's job to find and fix). Extents whose copies +//! are partly in stripes (nr_required = 0 entries) are protected by their +//! stripes and reported via the stripe entries. + +use std::collections::{BTreeMap, HashMap, HashSet}; +use std::fmt::Write as FmtWrite; + +use anyhow::{anyhow, Result}; +use clap::Parser; + +use crate::commands::DeviceNameArgs; +use crate::wrappers::accounting::{AccountingEntry, DiskAccountingKind, data_type, disk_accounting_type}; +use crate::wrappers::handle::BcachefsHandle; +use crate::wrappers::sysfs::{self, DeviceNameMode, DevInfo}; +use bcachefs_kernel::util::printbuf::Printbuf; + +#[derive(Parser, Debug)] +#[command(name = "failure-domains", + about = "Show failure domains and what losing each would cost", + long_about = "Analyzes the replicas accounting to show, for each failure \ +domain, the data that would be lost if it failed - too few copies or stripe \ +blocks left to reconstruct - and the data that would survive degraded. Lost \ +data means failure domain separation is being violated. Devices with no \ +failure domain set are their own failure domains.", + disable_help_flag = true)] +pub struct Cli { + /// Print help + #[arg(long = "help", action = clap::ArgAction::Help)] + _help: (), + + /// Human-readable units + #[arg(short = 'h', long = "human-readable", default_value = "true")] + human_readable: bool, + + /// JSON output: sizes in bytes; named domains carry a "devices" count, + /// single-device rows don't + #[arg(long = "json")] + json: bool, + + /// Render a synthetic demo scenario instead of a filesystem: + /// domains, no-domains, partly-off + #[arg(long = "demo", hide = true)] + demo: Option, + + #[command(flatten)] + device_names: DeviceNameArgs, + + /// Filesystem mountpoint + #[arg(default_value = ".")] + mountpoint: String, +} + +// ── The exposure engine ────────────────────────────────────────────── + +/// One replicas accounting entry, reduced to what failure analysis needs. +struct Entry { + devs: Vec, + /// Failed devices tolerated before data is lost: + tolerates: u8, + sectors: u64, +} + +struct Exposure { + entries: Vec, + /// dev idx -> indices into entries, for scoring device sets: + by_dev: HashMap>, + /// All sectors with durability to lose - replicated + stripes: + total: u64, +} + +fn accounting_replicas_entries(acct: &[&AccountingEntry]) -> Vec { + let mut ret = Vec::new(); + + for e in acct { + let DiskAccountingKind::Replicas { data_type: dt, nr_devs, nr_required, devs } = e.pos.decode() + else { continue }; + let sectors = e.counter(0); + + // Cached data has no durability to lose; nr_required == 0 extents + // are backed by stripes, accounted via the stripe entries: + if sectors == 0 || dt == data_type::cached || nr_required == 0 { + continue; + } + + let devs: Vec = devs[..nr_devs as usize].iter() + .copied() + .filter(|&d| d != 255) /* BCH_SB_MEMBER_INVALID: dead stripe blocks */ + .collect(); + if devs.is_empty() { + continue; + } + + // Replicated: survives until every copy is gone. Erasure coded + // (nr_required = nr_data > 1): survives nr_redundant failures. + let tolerates = if nr_required > 1 { + nr_devs - nr_required + } else { + devs.len() as u8 - 1 + }; + + ret.push(Entry { devs, tolerates, sectors }); + } + + ret +} + +/// What failing a device set does, per bucket of sectors: +#[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Debug)] +struct Score { + /// Unreadable - too few copies or stripe blocks survive: + lost: u64, + /// Survives, with less redundancy: + degraded: u64, +} + +impl Exposure { + fn new(acct: &[&AccountingEntry]) -> Exposure { + Self::from_entries(accounting_replicas_entries(acct)) + } + + fn from_entries(entries: Vec) -> Exposure { + let mut by_dev: HashMap> = HashMap::new(); + let mut total = 0; + + for (i, e) in entries.iter().enumerate() { + total += e.sectors; + + for &d in &e.devs { + by_dev.entry(d).or_default().push(i as u32); + } + } + + Exposure { entries, by_dev, total } + } + + /// What failing exactly the devices in @f does: + fn score(&self, f: &[u8]) -> Score { + let mut seen = HashSet::new(); + let mut s = Score::default(); + + for &d in f { + let Some(list) = self.by_dev.get(&d) else { continue }; + for &i in list { + if !seen.insert(i) { + continue; + } + let e = &self.entries[i as usize]; + let nr_failed = e.devs.iter().filter(|d| f.contains(d)).count(); + if nr_failed > e.tolerates as usize { + s.lost += e.sectors; + } else { + s.degraded += e.sectors; + } + } + } + + s + } +} + +// ── The failure domains ────────────────────────────────────────────── + +/// One row of the report: a named failure domain, or a single device with no +/// failure domain set (which is a domain of its own). +struct Row { + name: String, + /// Device count for named domains, None for a lone unlabeled device: + nr_devs: Option, + nr_offline: usize, + score: Score, +} + +/// One row per failure domain: devices sharing a failure_domain string are +/// grouped and scored together; a device with none set is its own single +/// device domain. Named domains first (sorted), then the lone devices. +fn domain_rows(e: &Exposure, devs: &[DevInfo]) -> Vec { + let mut domains: BTreeMap<&str, Vec<&DevInfo>> = BTreeMap::new(); + let mut loners: Vec<&DevInfo> = Vec::new(); + + for d in devs { + match d.failure_domain.as_deref() { + Some(fd) => domains.entry(fd).or_default().push(d), + None => loners.push(d), + } + } + + let mut rows = Vec::new(); + + for (name, members) in domains { + let mut f: Vec = members.iter().map(|d| d.idx as u8).collect(); + f.sort(); + rows.push(Row { + name: name.to_string(), + nr_devs: Some(f.len()), + nr_offline: members.iter().filter(|d| !d.online).count(), + score: e.score(&f), + }); + } + + for d in loners { + rows.push(Row { + name: d.dev.clone(), + nr_devs: None, + nr_offline: !d.online as usize, + score: e.score(&[d.idx as u8]), + }); + } + + rows +} + +// ── Output ─────────────────────────────────────────────────────────── + +fn header_to_text(out: &mut Printbuf, e: &Exposure, devs: &[DevInfo]) { + let offline = devs.iter().filter(|d| !d.online).count(); + + write!(out, "Devices: {}", devs.len()).unwrap(); + if offline != 0 { + write!(out, " ({} offline)", offline).unwrap(); + } + writeln!(out).unwrap(); + + write!(out, "Data: ").unwrap(); + out.units_sectors(e.total); + writeln!(out).unwrap(); +} + +/// The same report as machine-readable JSON: what the tests and scripts +/// consume, so they parse data rather than table formatting. Sizes are in +/// bytes; "devices" is present only on named domain rows. +fn report_to_json(e: &Exposure, devs: &[DevInfo]) -> serde_json::Value { + let rows = domain_rows(e, devs); + + let domains: Vec = rows.iter().map(|r| { + let mut o = serde_json::json!({ + "domain": r.name, + "offline_devices": r.nr_offline, + "lost_bytes": r.score.lost << 9, + "degraded_bytes": r.score.degraded << 9, + }); + if let Some(n) = r.nr_devs { + o["devices"] = n.into(); + } + o + }).collect(); + + serde_json::json!({ + "devices": devs.len(), + "offline_devices": devs.iter().filter(|d| !d.online).count(), + "data_bytes": e.total << 9, + "separation_violated": rows.iter().any(|r| r.score.lost != 0), + "domains": domains, + }) +} + +fn report_to_text(out: &mut Printbuf, e: &Exposure, devs: &[DevInfo]) { + let rows = domain_rows(e, devs); + let unlabeled = devs.iter().all(|d| d.failure_domain.is_none()); + + writeln!(out).unwrap(); + if unlabeled { + writeln!(out, "No failure domains configured: each device is its own failure domain").unwrap(); + } + + /* The verdict: does any single domain failure lose data? */ + if let Some(worst) = rows.iter().max_by_key(|r| r.score.lost) { + let what = if unlabeled { "device" } else { "failure domain" }; + + if worst.score.lost != 0 { + write!(out, "Failure domain separation violated: ").unwrap(); + out.units_sectors(worst.score.lost); + writeln!(out, " lost if {} {} fails", what, worst.name).unwrap(); + } else { + writeln!(out, "All data survives losing any one {}", what).unwrap(); + } + } + + writeln!(out, "\nWhat losing each failure domain would cost:").unwrap(); + out.aligned(|sub| { + writeln!(sub, "domain\tdevices\rlost\rdegraded\r").unwrap(); + + for r in rows { + write!(sub, "{}\t", r.name).unwrap(); + /* online/total: */ + match (r.nr_devs, r.nr_offline) { + (Some(n), o) => write!(sub, "{}/{}", n - o, n).unwrap(), + (None, 0) => (), + (None, _) => write!(sub, "0/1").unwrap(), + } + write!(sub, "\r").unwrap(); + sub.units_sectors(r.score.lost); + write!(sub, "\r").unwrap(); + sub.units_sectors(r.score.degraded); + write!(sub, "\r\n").unwrap(); + } + }); +} + +fn fs_failure_domains_to_text(out: &mut Printbuf, cli: &Cli, name_mode: DeviceNameMode) -> Result<()> { + let path = &cli.mountpoint; + + let handle = BcachefsHandle::open(path) + .map_err(|e| anyhow!("opening filesystem '{}': {}", path, e))?; + let sysfs_path = sysfs::sysfs_path_from_fd(handle.sysfs_fd())?; + let devs = sysfs::fs_get_devices(&sysfs_path, name_mode)?; + + let acct = handle.query_accounting(disk_accounting_type::replicas.bit()) + .map_err(|e| anyhow!("query_accounting ioctl failed (kernel too old?): {}", e))?; + let acct_refs: Vec<&AccountingEntry> = acct.entries.iter().collect(); + + let e = Exposure::new(&acct_refs); + let uuid = uuid::Uuid::from_bytes(handle.uuid()); + + if cli.json { + let mut j = report_to_json(&e, &devs); + j["filesystem"] = uuid.hyphenated().to_string().into(); + writeln!(out, "{:#}", j).unwrap(); + return Ok(()); + } + + writeln!(out, "Filesystem: {}", uuid.hyphenated()).unwrap(); + header_to_text(out, &e, &devs); + report_to_text(out, &e, &devs); + Ok(()) +} + +// ── Demo scenarios - synthetic replica sets, no filesystem needed ──── + +mod demo { + use super::*; + + /// Deterministic - same output every run: + struct Rng(u64); + + impl Rng { + fn next(&mut self, bound: u64) -> u64 { + self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + (self.0 >> 33) % bound + } + } + + fn dev(idx: u32, rack: Option) -> DevInfo { + DevInfo { + idx, + dev: format!("dev{}", idx), + label: None, + failure_domain: rack.map(|r| format!("rack{}", r)), + durability: 1, + online: true, + } + } + + fn entries_from_pairs(pairs: HashMap<[u8; 2], u64>) -> Vec { + pairs.into_iter() + .map(|(devs, sectors)| Entry { + devs: devs.to_vec(), + tolerates: 1, + sectors, + }) + .collect() + } + + /// Six racks of ten, replicas=2 spread correctly: copies always cross + /// racks. No whole rack failure loses anything. + fn racks_spread() -> (Vec, Vec) { + let devs: Vec = (0..60).map(|i| dev(i, Some(i / 10))).collect(); + let mut rng = Rng(1); + let mut pairs: HashMap<[u8; 2], u64> = HashMap::new(); + + for _ in 0..6000 { + let a = rng.next(60) as u8; + let b = loop { + let b = rng.next(60) as u8; + if b / 10 != a / 10 { + break b; + } + }; + let mut key = [a, b]; + key.sort(); + *pairs.entry(key).or_default() += (rng.next(7) + 1) * 2048; + } + + (entries_from_pairs(pairs), devs) + } + + /// No failure domains, and the filesystem grew in stages: heavy old + /// data on the first eight devices, later data spread wider. The old + /// device pairs carry correlated risk: + fn grew_in_stages() -> (Vec, Vec) { + let devs: Vec = (0..60).map(|i| dev(i, None)).collect(); + let mut rng = Rng(2); + let mut pairs: HashMap<[u8; 2], u64> = HashMap::new(); + + let mut era = |nr_devs: u64, writes: u64, size: u64| { + for _ in 0..writes { + let a = rng.next(nr_devs) as u8; + let b = loop { + let b = rng.next(nr_devs) as u8; + if b != a { + break b; + } + }; + let mut key = [a, b]; + key.sort(); + *pairs.entry(key).or_default() += (rng.next(7) + 1) * size; + } + }; + + era(8, 3000, 4096); /* the early days: 8 devices, lots of data */ + era(28, 1500, 2048); /* first expansion */ + era(60, 800, 2048); /* current */ + + (entries_from_pairs(pairs), devs) + } + + /// Failure domains, but partly off: a stretch of data was written with + /// copies landing in one rack (domains misconfigured, a rack's worth of + /// devices down, data predating the labels...): + fn partly_off() -> (Vec, Vec) { + let mut devs: Vec = (0..60).map(|i| dev(i, Some(i / 10))).collect(); + + /* rack5 is down - one of the ways data ends up under-spread: */ + for d in &mut devs[50..60] { + d.online = false; + } + let devs = devs; + let mut rng = Rng(3); + let mut pairs: HashMap<[u8; 2], u64> = HashMap::new(); + + for i in 0..6000 { + let a = rng.next(60) as u8; + let same_rack = i % 8 == 0; + let b = loop { + let b = rng.next(60) as u8; + if b != a && ((b / 10 == a / 10) == same_rack) { + break b; + } + }; + let mut key = [a, b]; + key.sort(); + *pairs.entry(key).or_default() += (rng.next(7) + 1) * 2048; + } + + (entries_from_pairs(pairs), devs) + } + + pub fn scenario(name: &str) -> Option<(Vec, Vec)> { + match name { + "domains" => Some(racks_spread()), + "no-domains" => Some(grew_in_stages()), + "partly-off" => Some(partly_off()), + _ => None, + } + } +} + +fn fs_failure_domains(cli: Cli) -> Result<()> { + let mut out = Printbuf::new(); + out.set_human_readable(cli.human_readable); + let name_mode = cli.device_names.name_mode(); + + if let Some(name) = &cli.demo { + let (entries, devs) = demo::scenario(name) + .ok_or_else(|| anyhow!("unknown scenario '{}' (have: domains, no-domains, partly-off)", name))?; + + let e = Exposure::from_entries(entries); + if cli.json { + writeln!(out, "{:#}", report_to_json(&e, &devs)).unwrap(); + } else { + writeln!(out, "Demo scenario: {}", name).unwrap(); + header_to_text(&mut out, &e, &devs); + report_to_text(&mut out, &e, &devs); + } + } else { + fs_failure_domains_to_text(&mut out, &cli, name_mode)?; + } + print!("{}", out); + Ok(()) +} + +pub const CMD: super::CmdDef = typed_cmd!("failure-domains", + "Show failure domains and what losing each would cost", + Cli, fs_failure_domains); + +#[cfg(test)] +mod tests { + use super::*; + + fn entry(devs: &[u8], tolerates: u8, sectors: u64) -> Entry { + Entry { devs: devs.to_vec(), tolerates, sectors } + } + + /// Two racks of two devices ({0,2} and {1,3}), replicas=2 spread + /// correctly: every entry crosses racks. + fn cross_rack() -> Exposure { + Exposure::from_entries(vec![ + entry(&[0, 1], 1, 100), + entry(&[0, 3], 1, 100), + entry(&[1, 2], 1, 100), + entry(&[2, 3], 1, 100), + ]) + } + + fn rack_devs() -> Vec { + (0..4).map(|i| DevInfo { + idx: i, + dev: format!("dev{}", i), + label: None, + failure_domain: Some(format!("rack{}", i % 2)), + durability: 1, + online: true, + }).collect() + } + + #[test] + fn spread_replicas() { + let e = cross_rack(); + + /* failing a whole rack: everything survives, degraded: */ + assert_eq!(e.score(&[0, 2]), + Score { lost: 0, degraded: 400 }); + + /* a cross rack pair kills its entry, degrades the overlapping + * entries, never touches the disjoint one: */ + assert_eq!(e.score(&[0, 1]), + Score { lost: 100, degraded: 200 }); + } + + #[test] + fn domains() { + let rows = domain_rows(&cross_rack(), &rack_devs()); + + /* two racks, nothing lost if either fails whole: */ + assert_eq!(rows.len(), 2); + assert_eq!(rows[0].name, "rack0"); + assert_eq!(rows[0].nr_devs, Some(2)); + assert_eq!(rows[0].score, Score { lost: 0, degraded: 400 }); + assert_eq!(rows[1].name, "rack1"); + assert_eq!(rows[1].score.lost, 0); + } + + #[test] + fn violation_shows_as_lost() { + /* both copies in rack 0 (devices 0 and 2): */ + let e = Exposure::from_entries(vec![ + entry(&[0, 2], 1, 100), + entry(&[0, 1], 1, 100), + ]); + + let rows = domain_rows(&e, &rack_devs()); + + assert_eq!(rows[0].name, "rack0"); + assert_eq!(rows[0].score.lost, 100); + } + + #[test] + fn ec_stripe() { + /* one 4+2 stripe across six devices: */ + let e = Exposure::from_entries(vec![entry(&[0, 1, 2, 3, 4, 5], 2, 600)]); + + assert_eq!(e.score(&[0]), Score { lost: 0, degraded: 600 }); + assert_eq!(e.score(&[0, 1]), Score { lost: 0, degraded: 600 }); + assert_eq!(e.score(&[0, 1, 2]), Score { lost: 600, degraded: 0 }); + } + + #[test] + fn unlabeled_devices_are_domains() { + let e = Exposure::from_entries(vec![entry(&[0, 1], 1, 100)]); + let devs: Vec = (0..2).map(|i| DevInfo { + idx: i, + dev: format!("dev{}", i), + label: None, + failure_domain: None, + durability: 1, + online: true, + }).collect(); + + let rows = domain_rows(&e, &devs); + + assert_eq!(rows.len(), 2); + assert_eq!(rows[0].name, "dev0"); + assert_eq!(rows[0].nr_devs, None); + assert_eq!(rows[0].score, Score { lost: 0, degraded: 100 }); + } +} diff --git a/src/commands/fsck.rs b/src/commands/fsck.rs index c2a6721f14..d3903854d6 100644 --- a/src/commands/fsck.rs +++ b/src/commands/fsck.rs @@ -20,10 +20,7 @@ use crate::device_multipath::{find_multipath_holder, warn_multipath_component}; use crate::wrappers::sysfs; use crate::device_scan; -// _IOW(0xbc, 19, struct bch_ioctl_fsck_offline) — sizeof = 24 -const BCH_IOCTL_FSCK_OFFLINE: libc::Ioctl = 0x4018bc13u32 as libc::Ioctl; -// _IOW(0xbc, 20, struct bch_ioctl_fsck_online) — sizeof = 16 -const BCH_IOCTL_FSCK_ONLINE: libc::Ioctl = 0x4010bc14u32 as libc::Ioctl; +use crate::wrappers::ioctl::{ioctl_ptr, ioctl_w, IoctlBuf, BCH_IOCTL_FSCK_OFFLINE, BCH_IOCTL_FSCK_ONLINE}; /// Filesystem check and repair #[derive(Parser, Debug)] @@ -141,13 +138,9 @@ fn fsck_online(fs: &BcachefsHandle, opt_str: &str) -> Result { opts: c_opts.as_ptr() as u64, }; - let fsck_fd = unsafe { - libc::ioctl(fs.ioctl_fd_raw(), BCH_IOCTL_FSCK_ONLINE, &fsck) - }; - if fsck_fd < 0 { - let errno = io::Error::last_os_error().raw_os_error().unwrap_or(0); - return Err(anyhow!("BCH_IOCTL_FSCK_ONLINE error: {}", crate::wrappers::bch_err_str(errno))); - } + let fsck_fd = ioctl_w::(fs.ioctl_fd(), &fsck) + .map_err(|e| anyhow!("BCH_IOCTL_FSCK_ONLINE error: {}", + crate::wrappers::bch_err_str(e.raw_os_error().unwrap_or(0))))?; let fd = unsafe { BorrowedFd::borrow_raw(fsck_fd) }; Ok(splice_fd_to_stdinout(fd)) @@ -359,44 +352,33 @@ fn cmd_fsck(cli: FsckCli) -> Result<()> { } } - // Allocate fsck struct with flexible array - let base_size = std::mem::size_of::(); - let total_size = base_size + dev_ptrs.len() * std::mem::size_of::(); - let layout = std::alloc::Layout::from_size_align(total_size, 8).unwrap(); - let fsck_ptr = unsafe { std::alloc::alloc_zeroed(layout) } as *mut c::bch_ioctl_fsck_offline; - + let mut buf = IoctlBuf::::new::(dev_ptrs.len()); let c_opts = CString::new(opts_str.as_str())?; - unsafe { - (*fsck_ptr).opts = c_opts.as_ptr() as u64; - (*fsck_ptr).nr_devs = dev_ptrs.len() as u64; - let devs_array = (*fsck_ptr).devs.as_mut_ptr(); - for (i, ptr) in dev_ptrs.iter().enumerate() { - *devs_array.add(i) = *ptr; - } - } + let hdr = buf.hdr_mut(); + hdr.opts = c_opts.as_ptr() as u64; + hdr.nr_devs = dev_ptrs.len() as u64; + unsafe { hdr.devs.as_mut_slice(dev_ptrs.len()).copy_from_slice(&dev_ptrs) }; let fsck_fd = match std::fs::OpenOptions::new() .read(true).write(true) .open("/dev/bcachefs-ctl") { Ok(ctl_file) => unsafe { - libc::ioctl(ctl_file.as_raw_fd(), BCH_IOCTL_FSCK_OFFLINE, fsck_ptr) + ioctl_ptr::(&ctl_file, buf.as_mut_ptr()) }, - Err(_) => -1, + Err(e) => Err(e), }; - unsafe { std::alloc::dealloc(fsck_ptr as *mut u8, layout); } - for l in &loopdevs { loopdev_free(l); } - if fsck_fd < 0 && kernel.is_none() { - return run_userspace_fsck(devices, fs_opts); - } - - if fsck_fd < 0 { - let errno = io::Error::last_os_error().raw_os_error().unwrap_or(0); - return Err(anyhow!("BCH_IOCTL_FSCK_OFFLINE error: {}", crate::wrappers::bch_err_str(errno))); - } + let fsck_fd = match fsck_fd { + Ok(fd) => fd, + Err(_) if kernel.is_none() => + return run_userspace_fsck(devices, fs_opts), + Err(e) => + return Err(anyhow!("BCH_IOCTL_FSCK_OFFLINE error: {}", + crate::wrappers::bch_err_str(e.raw_os_error().unwrap_or(0)))), + }; let fd = unsafe { BorrowedFd::borrow_raw(fsck_fd) }; let ret = splice_fd_to_stdinout(fd); diff --git a/src/commands/fusemount.rs b/src/commands/fusemount.rs index 43aaa122a0..d75dc9346b 100644 --- a/src/commands/fusemount.rs +++ b/src/commands/fusemount.rs @@ -15,6 +15,8 @@ // requests get read-modify-write treatment in the write handler. use std::cell::Cell; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::Arc; use std::ffi::OsStr; use std::fs::File; use std::io::{Read, Write}; @@ -128,10 +130,42 @@ fn dtype_to_filetype(dtype: u32) -> FileType { } } +/// Bytes the daemonising child sends its parent over the sync pipe. +/// +/// The parent cannot see the child's stderr -- daemon mode sends it to +/// /dev/null, deliberately, since 8d2ea5aef1 -- so anything it is to report has +/// to come through here. Reporting every failure as a FUSE problem sends people +/// looking in the wrong place. +const CHILD_OK: u8 = 0; +const CHILD_ERR_FS_START: u8 = 1; +const CHILD_ERR_MOUNT: u8 = 2; +/// Between the two: the filesystem is up but we never reached fuser::mount2. +const CHILD_ERR_SETUP: u8 = 3; + +/// Bounded well under a pipe buffer so the child never blocks writing it, even +/// if the parent is slow to read. +const CHILD_MSG_MAX: usize = 512; + fn signal_parent(fd: OwnedFd, byte: u8) { let _ = File::from(fd).write_all(&[byte]); } +/// Report a failure stage and why, in one write. +fn signal_parent_err(fd: OwnedFd, byte: u8, reason: &str) { + let mut buf = Vec::with_capacity(1 + CHILD_MSG_MAX); + buf.push(byte); + // Truncate on a character boundary, keeping whole characters: the parent + // decodes this as UTF-8. + let end = reason + .char_indices() + .map(|(i, ch)| i + ch.len_utf8()) + .take_while(|&e| e <= CHILD_MSG_MAX) + .last() + .unwrap_or(0); + buf.extend_from_slice(reason[..end].as_bytes()); + let _ = File::from(fd).write_all(&buf); +} + /// Convert a raw C return value (negative bcachefs error code) to a fuser Errno. /// Walks the bcachefs error hierarchy to the root standard errno. fn err(ret: i32) -> Errno { @@ -361,6 +395,16 @@ struct BcachefsFs { /// Write end of a pipe used to signal the parent process that the /// FUSE mount is established. Written in init(), None in foreground mode. signal_fd: Option, + /// Set by destroy() once bch2_fs_exit() has run. + /// + /// fuser::mount2() is Session::new().and_then(|se| se.run()), and the two + /// halves differ: Session::new() mounts before wrapping us in a + /// FilesystemHolder, whose Drop calls destroy(). So a mount failure never + /// shuts the filesystem down and the caller must, while a failure after + /// the session is established already has. mount2 returns one io::Result + /// for both, so the caller cannot tell them apart -- it asks this instead + /// of guessing, which also keeps it correct if fuser's internals change. + destroyed: Arc, } // Safety: bch_fs is internally synchronized with its own locking. @@ -414,7 +458,7 @@ impl Filesystem for BcachefsFs { // Signal parent that mount is established if let Some(fd) = self.signal_fd.take() { eprintln!("bcachefs fuse: signaling parent"); - signal_parent(fd, 0); + signal_parent(fd, CHILD_OK); } eprintln!("bcachefs fuse: init returning Ok"); Ok(()) @@ -423,6 +467,7 @@ impl Filesystem for BcachefsFs { fn destroy(&mut self) { eprintln!("bcachefs fuse: destroy"); unsafe { c::bch2_fs_exit(self.c) }; + self.destroyed.store(true, Ordering::SeqCst); } fn lookup(&self, _req: &Request, parent: INodeNo, name: &OsStr, reply: ReplyEntry) { @@ -509,25 +554,23 @@ impl Filesystem for BcachefsFs { let fs = self.fs(); - let (atime_flag, atime_val): (i32, u64) = match &atime { - None => (0, 0), - Some(TimeOrNow::Now) => (2, 0), - Some(TimeOrNow::SpecificTime(t)) => { - let d = t.duration_since(UNIX_EPOCH).unwrap_or_default(); - let ts = c::timespec { tv_sec: d.as_secs() as _, tv_nsec: d.subsec_nanos() as _ }; - (1, fs.timespec_to_time(ts) as u64) - } - }; - let (mtime_flag, mtime_val): (i32, u64) = match &mtime { + let parse_time = |time: &Option| match time { None => (0, 0), Some(TimeOrNow::Now) => (2, 0), Some(TimeOrNow::SpecificTime(t)) => { let d = t.duration_since(UNIX_EPOCH).unwrap_or_default(); - let ts = c::timespec { tv_sec: d.as_secs() as _, tv_nsec: d.subsec_nanos() as _ }; + let ts = c::timespec { + tv_sec: d.as_secs() as _, + tv_nsec: d.subsec_nanos() as _, + ..unsafe { std::mem::zeroed() } + }; (1, fs.timespec_to_time(ts) as u64) } }; + let (atime_flag, atime_val) = parse_time(&atime); + let (mtime_flag, mtime_val) = parse_time(&mtime); + let bi = match fuse_setattr( &fs, inum, @@ -1056,8 +1099,18 @@ pub fn cmd_fusemount(cli: Cli) -> anyhow::Result<()> { unsafe { c::bch2_fs_exit(fs_raw) }; anyhow::bail!("Error starting filesystem: {}", e); } - let bcachefs_fs = BcachefsFs { c: fs_raw, signal_fd: None }; - fuser::mount2(bcachefs_fs, &cli.mountpoint, &config)?; + let destroyed = Arc::new(AtomicBool::new(false)); + let bcachefs_fs = BcachefsFs { + c: fs_raw, + signal_fd: None, + destroyed: Arc::clone(&destroyed), + }; + if let Err(e) = fuser::mount2(bcachefs_fs, &cli.mountpoint, &config) { + if !destroyed.load(Ordering::SeqCst) { + unsafe { c::bch2_fs_exit(fs_raw) }; + } + anyhow::bail!("Error mounting filesystem: {}", e); + } return Ok(()); } @@ -1080,16 +1133,46 @@ pub fn cmd_fusemount(cli: Cli) -> anyhow::Result<()> { if pid > 0 { // Parent: wait for child to signal mount readiness drop(write_fd); - let mut buf = [0u8; 1]; - let n = File::from(read_fd).read(&mut buf)?; + let mut pipe = File::from(read_fd); + + // Read the status byte on its own. On success the child carries on as + // the daemon, holding its end of the pipe open, so there is no EOF to + // wait for and reading to end here would hang the mount. + let mut status = [0u8; 1]; + let got = pipe.read(&mut status)?; - if n == 1 && buf[0] == 0 { + if got == 1 && status[0] == CHILD_OK { std::process::exit(0); } else { + // A failing child writes stage and reason in a single write and + // then exits, so the rest is already queued and EOF follows. + let mut buf = Vec::with_capacity(1 + CHILD_MSG_MAX); + if got == 1 { + buf.push(status[0]); + } + let _ = pipe.take(CHILD_MSG_MAX as u64).read_to_end(&mut buf); let pid = rustix::process::Pid::from_raw(pid) .ok_or_else(|| anyhow::anyhow!("invalid child pid {}", pid))?; let _ = rustix::process::waitpid(Some(pid), rustix::process::WaitOptions::empty()); - anyhow::bail!("FUSE mount failed in child process"); + + let reason = String::from_utf8_lossy(buf.get(1..).unwrap_or_default()); + let reason = reason.trim(); + match buf.first().copied() { + Some(CHILD_ERR_FS_START) if !reason.is_empty() => + anyhow::bail!("error starting filesystem: {reason}"), + Some(CHILD_ERR_FS_START) => + anyhow::bail!("error starting filesystem"), + Some(CHILD_ERR_MOUNT) if !reason.is_empty() => + anyhow::bail!("FUSE mount failed: {reason}"), + Some(CHILD_ERR_MOUNT) => + anyhow::bail!("FUSE mount failed"), + Some(CHILD_ERR_SETUP) if !reason.is_empty() => + anyhow::bail!("filesystem started but the mount was never attempted: {reason}"), + Some(CHILD_ERR_SETUP) => + anyhow::bail!("filesystem started but the mount was never attempted"), + _ => + anyhow::bail!("child exited without reporting a reason"), + } } } @@ -1097,6 +1180,13 @@ pub fn cmd_fusemount(cli: Cli) -> anyhow::Result<()> { drop(read_fd); rustix::process::setsid()?; + // The daemon needs its own http server: only the calling thread survives + // fork(), so the parent's is gone. This is the call that used to happen + // from a pthread_atfork child handler -- which also fired in the child of + // every other fork, including the one that execs fusermount3, where + // binding a socket and spawning threads is not allowed. + crate::http::bch2_start_http_lazy(); + // Daemon mode must not inherit the caller's stderr or grow a fixed log // file under /tmp; foreground mode still leaves debug output visible. if let Ok(f) = std::fs::File::create("/dev/null") { @@ -1109,12 +1199,30 @@ pub fn cmd_fusemount(cli: Cli) -> anyhow::Result<()> { if let Err(e) = start_fs(fs_raw) { eprintln!("fusemount: bch2_fs_start failed: {}", e); unsafe { c::bch2_fs_exit(fs_raw) }; - signal_parent(write_fd, 1); + signal_parent_err(write_fd, CHILD_ERR_FS_START, &format!("{e:#}")); std::process::exit(1); } eprintln!("fusemount: filesystem started, calling fuser::mount2"); - let bcachefs_fs = BcachefsFs { c: fs_raw, signal_fd: Some(write_fd.try_clone()?) }; + let destroyed = Arc::new(AtomicBool::new(false)); + // Not `?`: the filesystem is started by now, and returning here without + // shutting it down leaves the same dirty superblock this commit exists to + // prevent -- just reached through fd exhaustion rather than a failed mount. + let signal_fd = match write_fd.try_clone() { + Ok(fd) => fd, + Err(e) => { + eprintln!("fusemount: couldn't duplicate the signal fd: {e}"); + unsafe { c::bch2_fs_exit(fs_raw) }; + signal_parent_err(write_fd, CHILD_ERR_SETUP, + &format!("couldn't duplicate the signal fd: {e}")); + std::process::exit(1); + } + }; + let bcachefs_fs = BcachefsFs { + c: fs_raw, + signal_fd: Some(signal_fd), + destroyed: Arc::clone(&destroyed), + }; match fuser::mount2(bcachefs_fs, &cli.mountpoint, &config) { Ok(()) => { @@ -1122,7 +1230,16 @@ pub fn cmd_fusemount(cli: Cli) -> anyhow::Result<()> { } Err(e) => { eprintln!("fusemount: fuser::mount2 failed: {}", e); - signal_parent(write_fd, 1); + // If the mount itself failed we were never handed to a + // FilesystemHolder, so destroy() has not run and nothing has shut + // the filesystem down -- leaving the superblock dirty after + // recovery and any version upgrade have already been committed. + // If the session did start, destroy() has run and calling + // bch2_fs_exit() again would be a double free. + if !destroyed.load(Ordering::SeqCst) { + unsafe { c::bch2_fs_exit(fs_raw) }; + } + signal_parent_err(write_fd, CHILD_ERR_MOUNT, &format!("{e}")); std::process::exit(1); } } diff --git a/src/commands/image.rs b/src/commands/image.rs index 988a27d8e0..a47cad92bc 100644 --- a/src/commands/image.rs +++ b/src/commands/image.rs @@ -481,7 +481,7 @@ fn image_create_inner( dev.open(bdev::BLK_OPEN_CREAT, false).map_err(|e| { anyhow!("Error opening {}: {}", dev.path.to_string_lossy(), std::io::Error::from_raw_os_error(e)) })?; - if unsafe { libc::ftruncate(dev.fd, target_size as libc::off_t) } != 0 { + if rustix::fs::ftruncate(dev.as_fd(), target_size).is_err() { bail!("ftruncate error: {}", std::io::Error::last_os_error()); } } @@ -622,17 +622,17 @@ fn image_update_inner( let metadata_dev_size = std::cmp::max( input_bytes, std::cmp::max( - unsafe { (*fs.raw).opts.btree_node_size as u64 * c::BCH_MIN_NR_NBUCKETS as u64 }, + fs.opts().btree_node_size as u64 * c::BCH_MIN_NR_NBUCKETS as u64, 64 << 20, ), ); - if unsafe { libc::ftruncate(dev_opts.fd, metadata_dev_size as libc::off_t) } != 0 { + if rustix::fs::ftruncate(dev_opts.as_fd(), metadata_dev_size).is_err() { bail!("ftruncate error: {}", std::io::Error::last_os_error()); } - let block_size = unsafe { (*fs.raw).opts.block_size as u32 }; - let btree_node_size = unsafe { (*fs.raw).opts.btree_node_size }; + let block_size = fs.opts().block_size as u32; + let btree_node_size = fs.opts().btree_node_size; let ret = crate::commands::format_util::format_for_device_add( &mut dev_opts, block_size, btree_node_size, ); diff --git a/src/commands/kill_btree_node.rs b/src/commands/kill_btree_node.rs index 2c3361584e..52d8ea3a31 100644 --- a/src/commands/kill_btree_node.rs +++ b/src/commands/kill_btree_node.rs @@ -1,12 +1,45 @@ // kill_btree_node: Debugging tool for corrupting specific btree nodes. // -// Walks the btree at a given level and writes zeroes to the on-disk location -// of the Nth node, simulating media corruption. Used for testing recovery -// paths — fsck should detect and repair the damage. +// Walks the btree at a given level and damages the on-disk location of the Nth +// node, simulating media corruption. Used for testing recovery paths — fsck +// should detect and repair the damage. +// +// --error picks what the damage looks like, because recovery takes visibly +// different paths depending on how far a node gets through validation: +// +// zero the first block is gone, so nothing parses and there is no evidence +// the node was ever there beyond the parent's pointer +// csum the node header is intact - the parent's btree_ptr_v2 seq matches, +// min_key and the written count are readable - and one bset fails its +// checksum, with every key in it still byte-for-byte correct. This is +// the shape field reports arrive in, and it isolates the read path's +// accept-or-reject decision from any question of key damage. +// keys same, but the flipped byte is in the key data, so the bset fails its +// checksum *and* holds a corrupt key. This is what exercises per-key +// validation, which is the only thing between an accepted bad-checksum +// bset and the btree. +// +// The checksum covers [sizeof(bch_csum), vstruct_end), and vstruct_end is +// sizeof(btree_node) + keys.u64s * 8 - not the whole block. So the byte to flip +// has to be one the bset actually reaches: presplit_shard_boundaries leaves +// plenty of nodes whose first bset is empty, and on those the first key byte is +// already past the end, so flipping it changes nothing and the injection is a +// silent no-op. +// +// Anything that stops the requested damage from landing is a hard error here, +// never a warning: this is a test instrument, and a caller that asked for +// corruption and silently didn't get it goes on to "verify" recovery against an +// intact filesystem and passes. Exit status is the only signal a shell script +// gets, so it has to mean "the node is damaged". +// +// Injecting a *structural* error (bad min_key, wrong seq, bogus u64s) that +// reaches the validation code as itself rather than as a checksum failure means +// recomputing the checksum after the edit - which this doesn't do yet. // // Safety: Opens the filesystem read-only (no in-memory modifications), then -// does raw pwrite() to the block device fd. The O_DIRECT alignment constraint -// comes from the block device being opened with O_DIRECT by the kernel code. +// does raw pread()/pwrite() to the block device fd. The O_DIRECT alignment +// constraint comes from the block device being opened with O_DIRECT by the +// kernel code. use std::ops::ControlFlow; use std::path::PathBuf; @@ -25,6 +58,17 @@ struct KillNode { idx: u64, } +/// What the damage should look like to the read path. +#[derive(clap::ValueEnum, Clone, Copy, Debug, PartialEq)] +enum ErrorType { + /// Zero the first block - nothing parses + Zero, + /// Flip a bset header byte - checksum fails, every key still intact + Csum, + /// Flip a byte inside key data - checksum fails and one key is corrupt + Keys, +} + /// Make btree nodes unreadable (debugging tool) #[derive(Parser, Debug)] #[command(about = "Kill a specific btree node (debugging)")] @@ -33,6 +77,10 @@ pub struct KillBtreeNodeCli { #[arg(short, long = "node")] nodes: Vec, + /// Kind of damage to inject + #[arg(short, long, value_enum, default_value_t = ErrorType::Zero)] + error: ErrorType, + /// Device index (default: kill all replicas) #[arg(short, long)] dev: Option, @@ -74,6 +122,88 @@ fn parse_kill_node(s: &str) -> Result { Ok(KillNode { btree, level, idx }) } +/// Pick the byte to flip for --error csum: the journal_seq of the first bset in +/// the node that actually holds keys. Returns (byte offset, the bset's sector +/// offset within the node, its u64s). +/// +/// journal_seq because it sits in the bset header, so it's covered by the +/// checksum whatever u64s is, and nothing reads it before the checksum is +/// verified - the node header stays parseable and the parent's btree_ptr_v2 seq +/// still matches. +/// +/// Skipping empty bsets matters: the first bset comes back u64s 0 not just on +/// freshly split nodes but on plenty of populated ones, and corrupting an empty +/// bset gives the read path nothing to decide - no key is at risk, so the +/// accept-vs-reject behaviour we're trying to exercise never runs. +/// +/// Layout is what bch2_btree_node_read_done() walks: the first bset is the +/// btree_node itself, each later one a btree_node_entry at the running sector +/// offset, each occupying vstruct_sectors i.e. round_up(header + u64s * 8, +/// block_size). +struct BsetLoc { + /// byte offset of the bset within the node + at: usize, + /// sector offset of its container, for reporting (matches the read path's + /// "node offset N/written") + sector: usize, + u64s: usize, +} + +/// The node's first bset, keys or not. +/// +/// --error csum doesn't need a key to be at stake, and a node whose bsets are all +/// empty still has to be corruptible: on a freshly formatted filesystem every +/// btree leaf is one of those, which is exactly what the spin repro formats. +fn first_bset(node: &[u8]) -> BsetLoc { + let at = size_of::() - size_of::(); + let u64s_at = at + std::mem::offset_of!(c::bset, u64s); + + BsetLoc { + at, + sector: 0, + u64s: u16::from_le_bytes([node[u64s_at], node[u64s_at + 1]]) as usize, + } +} + +fn first_bset_with_keys(node: &[u8], written_sectors: usize, block_size: usize) + -> Option +{ + let u64s_in_bset = std::mem::offset_of!(c::bset, u64s); + + let mut off = 0; + + while off < written_sectors * 512 { + // offset of the bset within its container, and the container's size - + // which is offsetof(_data), i.e. where this bset's keys begin + let (bset_at, header) = if off == 0 { + (size_of::() - size_of::(), size_of::()) + } else { + (off + size_of::() - size_of::(), + size_of::()) + }; + + let u64s_at = bset_at + u64s_in_bset; + if u64s_at + 2 > node.len() { + break; + } + + let u64s = u16::from_le_bytes([node[u64s_at], node[u64s_at + 1]]) as usize; + + if u64s != 0 { + return Some(BsetLoc { at: bset_at, sector: off / 512, u64s }); + } + + /* empty bset: skip past it and try the next */ + let sectors = (header + u64s * 8).div_ceil(block_size) * block_size / 512; + if sectors == 0 { + break; + } + off += sectors * 512; + } + + None +} + fn cmd_kill_btree_node(cli: KillBtreeNodeCli) -> Result<()> { if cli.nodes.is_empty() { @@ -89,21 +219,18 @@ fn cmd_kill_btree_node(cli: KillBtreeNodeCli) -> Result<()> { let fs = crate::device_scan::open_scan(&cli.devices, fs_opts)?; - let block_size = unsafe { (*fs.raw).opts.block_size } as usize; + let block_size = fs.opts().block_size as usize; let dev_idx = cli.dev.unwrap_or(-1); // O_DIRECT requires aligned buffers; bd_fd is opened with O_DIRECT - let mut zeroes: *mut libc::c_void = std::ptr::null_mut(); - let r = unsafe { libc::posix_memalign(&mut zeroes, block_size, block_size) }; - if r != 0 { - bail!("posix_memalign failed: {}", std::io::Error::from_raw_os_error(r)); - } - unsafe { std::ptr::write_bytes(zeroes as *mut u8, 0, block_size) }; + let zeroes = crate::util::AlignedBuf::new(block_size); let trans = BtreeTrans::new(&fs); for kill in &mut kill_nodes { let mut found = false; + let mut damaged = 0; + let mut damage_err: Option = None; let mut iter = BtreeNodeIter::new( &trans, @@ -137,30 +264,87 @@ fn cmd_kill_btree_node(cli: KillBtreeNodeCli) -> Result<()> { continue; }; - eprintln!("killing btree node on dev {} {} l={}\n {}", - dev, kill.btree, kill.level, k.to_text(&fs)); + eprintln!("damaging btree node ({:?}) on dev {} {} l={}\n {}", + cli.error, dev, kill.btree, kill.level, k.to_text(&fs)); let fd = unsafe { (*ca.disk_sb.bdev).bd_fd }; - let offset = (ptr.offset() as libc::off_t) << 9; - let ret = unsafe { - libc::pwrite(fd, zeroes, block_size, offset) + let file = crate::wrappers::super_io::borrowed_file(fd); + let offset = (ptr.offset() as u64) << 9; + + let damage = || -> Result<()> { + match cli.error { + ErrorType::Zero => + std::os::unix::fs::FileExt::write_all_at(&*file, &zeroes, offset)?, + ErrorType::Csum | ErrorType::Keys => { + /* the whole written extent, so we can walk its bsets */ + let written = b.written as usize; + let mut buf = crate::util::AlignedBuf::new((written * 512).max(block_size)); + + std::os::unix::fs::FileExt::read_exact_at(&*file, &mut buf, offset)?; + + let bset = first_bset_with_keys(&buf, written, block_size) + .or_else(|| (cli.error == ErrorType::Csum) + .then(|| first_bset(&buf))) + .ok_or_else(|| anyhow!( + "no bset with keys in this {written} sector node, so \ + --error keys has nothing to corrupt"))?; + + let (victim, what) = if cli.error == ErrorType::Csum { + (bset.at + std::mem::offset_of!(c::bset, journal_seq), + "bset header") + } else { + /* midway into the keys: inside the checksummed + * region, and corrupts a key rather than a + * header field the keys don't depend on */ + (bset.at + size_of::() + bset.u64s * 8 / 2, + "key data") + }; + + if victim >= buf.len() { + bail!("bset at node offset {} claims u64s {}, putting the byte \ + to corrupt ({victim}) past the end of the {} byte node", + bset.sector, bset.u64s, buf.len()); + } + + eprintln!(" corrupting {what} of bset at node offset {}/{written}, u64s {}", + bset.sector, bset.u64s); + + buf[victim] ^= 0xff; + std::os::unix::fs::FileExt::write_all_at(&*file, &buf, offset)?; + } + } + Ok(()) }; - if ret as usize != block_size { - eprintln!("pwrite error: expected {} got {} {}", - block_size, ret, std::io::Error::last_os_error()); + + /* + * Stop on the first failure rather than carrying on: a caller + * that asked for damage and didn't get it will otherwise go on + * to "verify" recovery against an intact filesystem. + */ + if let Err(e) = damage() { + damage_err = Some(anyhow!("dev {dev}: {e}")); + return ControlFlow::Break(()); } + damaged += 1; } ControlFlow::Break(()) }).map_err(|e| anyhow!("error walking btree nodes: {}", e))?; if !found { - unsafe { libc::free(zeroes) }; bail!("node at specified index not found"); } + + if let Some(e) = damage_err { + return Err(e); + } + + if damaged == 0 { + bail!("{} l={} idx found, but no replica was damaged - no pointer matched --dev {}", + kill.btree, kill.level, dev_idx); + } } - unsafe { libc::free(zeroes) }; Ok(()) } diff --git a/src/commands/kvdb.rs b/src/commands/kvdb.rs index 0f659f0dbb..d063449fd6 100644 --- a/src/commands/kvdb.rs +++ b/src/commands/kvdb.rs @@ -10,24 +10,36 @@ //! //! Ops: get / peek / peek_prev / list (read), update (read-modify-write //! fields of an existing key), set (construct and insert a whole key — -//! `set deleted` deletes). One-shot via -c, REPL on stdin -//! otherwise; the REPL reads commands line by line, so tests can pipe a -//! script in. +//! `set deleted` deletes), snapshot (session view context), +//! list_journal (transaction search, --journal opens). One-shot via -c, +//! REPL on stdin otherwise; the REPL reads commands line by line, so tests +//! can pipe a script in. //! -//! Scope notes: values are addressed raw (BTREE_ITER_all_snapshots — the -//! position's snapshot field is taken literally, no visibility filtering; -//! harmlessly dropped on btrees without a snapshot field). Fixed-layout vals -//! are fully editable; varint-packed (inode) and entry-stream (extent) vals -//! only up to their fixed header. Updates run the normal triggers and key -//! validation — per-key-invalid keys are (correctly) rejected; whether we -//! want a validation-bypass mode for injecting those is an open question. - -use std::io::{stdin, stdout, IsTerminal, Write}; +//! The default open is norecovery (read-only, no replay, no repair passes) - +//! inspection must not disturb the state under inspection. --rw opts into +//! journal replay and writes, and stops there: repair passes must not run +//! either, or they rewrite the state an editing session opened rw to build. +//! +//! Visibility: without a snapshot context, reads are raw +//! (BTREE_ITER_all_snapshots - positions taken literally). With a context, +//! reads without an explicit :snapshot run snapshot-filtered at the context +//! (runtime visibility resolution, whiteouts shown); an explicit :snapshot +//! makes that command raw again. Writes always target the exact key. +//! Full semantics: doc/kvdb.md. +//! +//! Fixed-layout vals are fully editable; varint-packed (inode) and +//! entry-stream (extent) vals only up to their fixed header. Updates run the +//! normal triggers and key validation — per-key-invalid keys are (correctly) +//! rejected; whether we want a validation-bypass mode for injecting those is +//! an open question. + +use std::io::{stdin, stdout, IsTerminal}; use std::ops::ControlFlow; use std::path::PathBuf; +use std::sync::atomic::{AtomicBool, Ordering}; use anyhow::{anyhow, bail, Result}; -use bcachefs_kernel::btree::bkey::{BkeySC, POS_MIN, SPOS_MAX}; +use bcachefs_kernel::btree::bkey::{BkeyS, BkeySC, POS_MIN, SPOS_MAX}; use bcachefs_kernel::btree::iter::{ commit_do, lockrestart_do, BtreeIter, BtreeIterFlags, BtreeTrans, CommitFlags, CommitOpts, TransError, UpdateTriggerFlags, @@ -47,28 +59,129 @@ use crate::wrappers::online_iter::{OnlineBtreeIter, OnlineIterFlags}; const BKEY_U64S: usize = size_of::() / size_of::(); +// The canonical kvdb documentation: this constant is the --help long text, +// and docgen extracts it into the Principles of Operation (doc/generated/ +// kvdb.tex, included from the Debugging tools section). Markup: blank-line +// paragraphs, `- ` bullets, [term] description items, backticks for code, +// 4-space-indented lines render verbatim. +// DOC_STRING(kvdb) +const KVDB_DOC: &str = "\ +kvdb is an interactive debugger for bcachefs metadata: it reads and writes +btree keys by field name, using generated runtime type information for the +on-disk structs. Its two jobs are forensics - inspecting a damaged +filesystem's state precisely, without disturbing it - and injection: +constructing exact corruption for fsck/repair tests, or performing +field-level surgery on a filesystem wedged in the field. + +Commands come from the REPL (readline editing, history, tab completion for +command and btree names), from -c arguments, or from piped stdin. In a +piped script an error aborts, since later commands likely depend on earlier +ones; interactively, errors are reported and the session continues. ctrl-C +interrupts a long-running command and returns to the prompt; ctrl-D or +`quit` exits. + +Opening modes: the default open is read-only with recovery capped +(norecovery). Inspection is the primary use, and a full-recovery open of a +damaged filesystem can repair - rewrite - the very state under inspection; +the default is guaranteed not to write. The journal is still read and +overlaid on btree reads, so listings show current state, but it is never +replayed and no repair passes run. + +- `--rw`: journal replay and writes enabled - recovery stops there, at + going read-write. Repair passes are not run: they would rewrite the + state you opened rw to construct, before your first command. Whatever + the superblock requires stays recorded and runs at the next real mount. + Version upgrades still happen; see the traps below. Required for + update/set/sb set. +- `--journal`: retain the entire journal in memory for `list_journal`; + costs memory proportional to journal size. +- `--nostart`: superblock only, the btree is never started. For sb get/set + on an image that can't or shouldn't be started. +- On a mounted filesystem, reads go through the kernel query ioctl and + writes are refused. + +Two traps: an `--rw` open of a not-yet-upgraded filesystem rewrites +metadata via the version upgrade (for example the snapshot and subvolume +state fields), destroying not-upgraded evidence. And the default open of a +formatted-but-never-started image silently runs first-start initialization +in memory: listings then show a root inode that does not exist on disk. + +Commands: + + get [-k] exact lookup (slot iteration) + peek [-k] first key >= pos + peek_prev [-k] last key <= pos + list [-k] [start] [end] keys in range + update ... modify fields of a key + set [-s] [field=val]... insert a whole new key + sb get read a superblock field + sb set write one + snapshot [|none] session snapshot context + list_journal [-k ] journal transactions + help, quit + +Positions are inode:offset[:snapshot], or POS_MIN/POS_MAX/SPOS_MAX. `-k` on +the read commands prints keys only - type, position, size - without +rendering values; useful when mapping out what exists. + +Fields are value-struct fields addressed by path (parent, children[1], +btime.hi). Declared flag bits (LE*_BITMASK) resolve by name, qualified as +flags.subvol when a name collides, and fields holding enum codewords accept +value names: state=will_delete. Values are decimal, 0x hex, or negative +decimal. `set deleted` removes the exact key; with -s it +deletes within pos's snapshot instead (inserting whiteouts, like a runtime +delete). + +The snapshot context. Snapshot visibility is the subtle dimension of every +bcachefs lookup: a key at snapshot S is visible at S and its descendants +unless overwritten, and a lookup in a snapshot resolves to the nearest +visible version. The `snapshot` command gives the session a view, and reads +then answer 'what does this view see?' instead of 'what is at this exact +position?'. Precisely: + +- No context: reads are raw (all snapshots, positions taken literally); an + omitted :snapshot parses as 0. +- Context set, pos written without :snapshot: the pos picks up the context + and the read runs snapshot-filtered at it - ancestor versions resolve, + siblings and descendants are invisible - exactly what a runtime lookup in + that snapshot sees. Whiteouts are shown, not skipped: in forensics the + whiteout doing the shadowing is data. +- Context set, pos written with an explicit :snapshot: that command is + fully raw - unfiltered, exact position, context bypassed. Explicit means + exact. +- The context only applies to btrees whose keys are snapshotted, and never + filters writes: update/set target the exact key, the context only fills + an omitted :snapshot. + +For a filtered `list`, the start position names the view: its snapshot +field carries the context whether given, defaulted, or POS_MIN. + +Journal search: with `--journal` at open, `list_journal -k ` prints +only the journal transactions containing updates to the given key ranges - +the who-touched-this-key question. Ranges are btree:pos or +btree:pos-btree:pos, comma separated, optionally prefixed + or -, the same +syntax as the standalone list_journal command. Each transaction prints with +its name, overwrites, and new keys. + +Editing goes through the normal transactional path - journalled, triggers +run, key validation applies - in an instance opened with commit-time +validation relaxed and background workers (snapshot deletion, copygc, +reconcile) disabled, so the tool neither refuses the states fsck is being +tested against nor consumes its own injections. This tool can corrupt a +filesystem in precise, surgical ways; that is its purpose. + +One editing trap: snapshot IDs allocate descending from U32_MAX and the +in-memory snapshot table is id-indexed; inserting a snapshot key with an +unrealistically low id asks the table to span billions of entries and fails +with ENOMEM_mark_snapshot. Use realistic, near-U32_MAX ids when fabricating +snapshots. Varint-packed values (inodes) and entry-stream values (extents) +are editable only up to their fixed header; fixed-layout values are fully +editable. +"; + /// Btree read/write REPL (debug) #[derive(Parser, Debug)] -#[command(long_about = "\ -Read and write btree keys by field name, using generated runtime type \ -information for the on-disk structs. Without -c, reads commands from stdin \ -(a REPL; pipe a script in for non-interactive use).\n\n\ -Commands:\n\ - get exact lookup, dump fields\n\ - peek first key >= pos\n\ - peek_prev last key <= pos\n\ - list [start] [end] keys in range\n\ - update ... modify fields of an existing key\n\ - set [field=val]... insert a whole new key\n\n\ -pos is inode:offset[:snapshot], or POS_MIN/POS_MAX/SPOS_MAX. Fields are \ -val struct fields: parent, children[1], btime.hi, ... Declared flag bits \ -(LE*_BITMASK) resolve by name too: no_keys=1, or qualified as flags.subvol=0 \ -when the name collides with a field. get decodes them: flags: 10 (subvol|no_keys). \ -Values are decimal, 0x hex, or negative decimal. `set deleted` \ -deletes a key.\n\n\ -Updates go through the normal transactional path: journalled, triggers run, \ -key validation applies. This tool can corrupt a filesystem in precise, \ -surgical ways - that is its purpose. Use accordingly.")] +#[command(long_about = KVDB_DOC)] pub struct Cli { /// Command to run (repeatable; skips the REPL) #[arg(short = 'c', long = "command")] @@ -82,6 +195,30 @@ pub struct Cli { #[arg(short, long, action = clap::ArgAction::Count)] verbose: u8, + /// Open without starting the filesystem (no recovery, no journal): only + /// `sb get`/`sb set` work, the btree is inaccessible. For superblock edits + /// on an image that can't or shouldn't be started. + #[arg(long)] + nostart: bool, + + /// Read-only, no journal replay or repair passes (recovery capped at + /// snapshots_read; journal keys still overlay reads). This is the + /// default; the flag is accepted for compatibility. + #[arg(long)] + norecovery: bool, + + /// Open read-write with full recovery: journal replay, scheduled repair + /// passes, version upgrades. Required for update/set/sb set. On a + /// damaged filesystem this can repair - rewrite - the state you may + /// have wanted to inspect. + #[arg(long)] + rw: bool, + + /// Retain the entire journal in memory for the list_journal command + /// (costs memory proportional to journal size). + #[arg(long)] + journal: bool, + #[arg(required(true))] devices: Vec, } @@ -94,6 +231,27 @@ fn parse_btree(s: &str) -> Result { .map_err(|_| anyhow!("invalid btree '{s}' (try: snapshots, subvolumes, extents, ...)")) } +/// Position parse honoring the session snapshot context: a pos written +/// without the :snapshot component picks it up from the context. Explicit +/// :snapshot and the named positions (POS_MIN etc.) are left alone. +fn parse_pos_ctx(s: &str, snapshot: Option) -> Result { + let mut pos = parse_pos(s)?; + if let Some(snap) = snapshot { + if s.matches(':').count() == 1 { + pos.snapshot = snap; + } + } + Ok(pos) +} + +/// An explicit :snapshot in a pos means a raw lookup at exactly that +/// position - it disables the snapshot context for the command, rather than +/// the command running filtered (which would resolve visibility and could +/// return a different version than the one asked for). +fn pos_has_explicit_snapshot(s: &str) -> bool { + s.matches(':').count() >= 2 +} + fn parse_pos(s: &str) -> Result { s.parse() .map_err(|_| anyhow!("invalid pos '{s}' (inode:offset[:snapshot], POS_MIN, SPOS_MAX)")) @@ -157,33 +315,82 @@ fn field_val(type_: u8, path: &str, v: &FieldVal) -> Result { } } -// --------------------------------------------------------------------------- -// value access - -fn val_bytes<'a>(k: &BkeySC<'a>) -> &'a [u8] { - let len = k.k.u64s as usize * 8 - size_of::(); - unsafe { std::slice::from_raw_parts(k.v as *const c::bch_val as *const u8, len) } +/// The bcachefs to_text methods are the faithful rendering of the on-disk +/// structs - that is their purpose. The typeinfo field tables are for +/// addressing fields on the write side (update/set), not for display. +fn render_key(fs: &Fs, k: &BkeySC<'_>, key_only: bool) -> String { + if key_only { + format!("{}\n", k.to_text_key()) + } else { + format!("{}\n", k.to_text(fs)) + } } -fn render_key(fs: &Fs, k: &BkeySC<'_>, fields: bool) -> String { - let mut out = format!("{}\n", k.to_text(fs)); - if !fields { - return out; - } - let Some(info) = typeinfo::bkey_val_info(k.k.type_ as u32) else { - return out; +/// The read half of the field engine: selected fields of a key's value as +/// bare values, one line per path - the same paths update addresses for +/// writes, so scripts get a stable contract instead of scraping the +/// human-oriented to_text display. Whole arrays print space-separated. +/// A field beyond the end of a short (older-format) value reads as zero, +/// mirroring update's grow-zero-filled write semantics. +fn render_key_fields(k: &BkeySC<'_>, paths: &[&str]) -> Result { + use std::fmt::Write as _; + use typeinfo::{AccessError, FieldKind, FieldRef}; + + let val = k.val_bytes(); + + let read_int = |path: &str, r: &FieldRef| -> Result { + let v = match typeinfo::read_scalar(val, r) { + Ok(v) => v, + Err(AccessError::OutOfBounds { .. }) => 0, + Err(e) => bail!("{path}: {e}"), + }; + Ok(match r.kind { + FieldKind::Int { signed: true, bytes, .. } => + typeinfo::sign_extend(v, *bytes).to_string(), + _ => v.to_string(), + }) }; - if info.fields.is_empty() { - return out; - } - let mut dump = String::new(); - let _ = typeinfo::struct_to_text(&mut dump, info, val_bytes(k)); - for l in dump.lines() { - out.push_str(" "); - out.push_str(l); - out.push('\n'); + + let mut out = String::new(); + for path in paths { + let (r, bm) = resolve_field(k.k.type_, path)?; + let line = match bm { + Some(bm) => match typeinfo::read_bits(val, &r, bm) { + Ok(v) => v.to_string(), + Err(AccessError::OutOfBounds { .. }) => "0".to_string(), + Err(e) => bail!("{path}: {e}"), + }, + None => match r.kind { + FieldKind::Int { .. } => read_int(path, &r)?, + FieldKind::Array { elem, n, stride } + if matches!(elem, FieldKind::Int { .. }) => { + (0..*n) + .map(|i| read_int(path, &FieldRef { + offset: r.offset + i * stride, + kind: elem, + len: *stride, + })) + .collect::>>()? + .join(" ") + } + // A vartail's length is however much value remains: + FieldKind::VarTail { elem, stride } + if matches!(elem, FieldKind::Int { .. }) => { + (0..(val.len().saturating_sub(r.offset) / stride)) + .map(|i| read_int(path, &FieldRef { + offset: r.offset + i * stride, + kind: elem, + len: *stride, + })) + .collect::>>()? + .join(" ") + } + _ => bail!("{path}: not a scalar or integer-array field"), + }, + }; + writeln!(out, "{line}").unwrap(); } - out + Ok(out) } /// A resolved assignment target: a field, or a declared bit range within one @@ -216,48 +423,174 @@ fn write_field( /// a snapshot field, so passing it unconditionally is fine. const RAW_EXACT: BtreeIterFlags = BtreeIterFlags::SLOTS.union(BtreeIterFlags::ALL_SNAPSHOTS); -fn cmd_get(fs: &Fs, btree: c::btree_id, pos: c::bpos) -> Result { - let trans = BtreeTrans::new(fs); - Ok(lockrestart_do(&trans, |t| { - let mut iter = BtreeIter::new(t.trans(), btree, pos, RAW_EXACT); - let out = iter - .peek_max_flags(SPOS_MAX, BtreeIterFlags::SLOTS) - .map(|k| match k { - Some(k) => render_key(fs, &k, true), - None => "(no key)\n".to_string(), - }); - t.result_value(out) - })?) +/// The snapshot context only applies to btrees whose keys are actually +/// snapshotted - on anything else it would corrupt positions (snapshots +/// btree keys live at snapshot 0) and filtering is meaningless. +fn btree_uses_snapshots(btree: c::btree_id) -> bool { + bcachefs_kernel::BTREE_HAS_SNAPSHOTS_MASK & (1u64 << btree as u64) != 0 } -fn cmd_peek(fs: &Fs, btree: c::btree_id, pos: c::bpos, prev: bool) -> Result { +/// With a snapshot context active, reads drop ALL_SNAPSHOTS - the iterator +/// runs snapshot-filtered (BTREE_ITER_filter_snapshots) at pos.snapshot, so +/// lookups resolve visibility the way runtime lookups do - and set +/// NOFILTER_WHITEOUTS: a forensics tool must show the whiteout doing the +/// shadowing, not silently hide the deletion. +fn iter_flags(base: BtreeIterFlags, filtered: bool) -> BtreeIterFlags { + if filtered { + base.difference(BtreeIterFlags::ALL_SNAPSHOTS) + .union(BtreeIterFlags::NOFILTER_WHITEOUTS) + } else { + base + } +} + +/// What a read command prints for a matched key: the C to_text line (the +/// faithful display), the key alone (-k), or selected value fields as bare +/// values (trailing field paths). A deleted slot is "no key" for a field +/// read - scripts reading fields need the miss to fail, not to read zeros - +/// while the display modes do show deleted slots and whiteouts. +#[derive(Clone, Copy)] +enum Render<'a> { + Full, + KeyOnly, + Fields(&'a [&'a str]), +} + +fn render_read(fs: &Fs, k: &BkeySC<'_>, how: Render<'_>) -> Result { + match how { + Render::Full => Ok(render_key(fs, k, false)), + Render::KeyOnly => Ok(render_key(fs, k, true)), + Render::Fields(_) if k.is_deleted() => { + let (inode, offset, snapshot) = (k.k.p.inode, k.k.p.offset, k.k.p.snapshot); + Err(anyhow!("no key at {inode}:{offset}:{snapshot}")) + } + Render::Fields(paths) => render_key_fields(k, paths), + } +} + +/// The one-key read commands differ only in how they position the +/// iterator: get is an exact slot lookup, peek/peek_prev scan for the +/// nearest key. +#[derive(Clone, Copy, PartialEq)] +enum ReadOp { + Get, + Peek, + PeekPrev, +} + +fn cmd_read(fs: &Fs, op: ReadOp, btree: c::btree_id, pos: c::bpos, filtered: bool, + how: Render<'_>) -> Result { let trans = BtreeTrans::new(fs); - Ok(lockrestart_do(&trans, |t| { - let mut iter = BtreeIter::new(t.trans(), btree, pos, BtreeIterFlags::ALL_SNAPSHOTS); - let out = if prev { - iter.peek_prev() - } else { - iter.peek() + let mut user_err: Option = None; + let out = lockrestart_do(&trans, |t| { + let base = match op { + ReadOp::Get => RAW_EXACT, + _ => BtreeIterFlags::ALL_SNAPSHOTS, + }; + let mut iter = BtreeIter::new(t.trans(), btree, pos, iter_flags(base, filtered)); + let out = match op { + ReadOp::Get => iter.peek_max_flags(SPOS_MAX, BtreeIterFlags::SLOTS), + ReadOp::Peek => iter.peek(), + ReadOp::PeekPrev => iter.peek_prev(), } - .map(|k| match k { - Some(k) => render_key(fs, &k, true), - None => "(no key)\n".to_string(), + .and_then(|k| match k { + Some(k) => render_read(fs, &k, how).map_err(|e| { + // Render errors (bad field path, no key for a field read) + // are the user's, not the transaction's: stash and abort + // the retry loop with a stand-in errcode. + user_err = Some(e); + BchError::from_errcode(bch_errcode::BCH_ERR_ENOENT_bkey_type_mismatch) + }), + None => Ok("(no key)\n".to_string()), }); t.result_value(out) - })?) + }); + match user_err { + Some(e) => Err(e), + None => Ok(out?), + } +} + +/// Tab completion: command names for the first word, btree names (from the +/// same string table FromStr parses) after a key command, get/set after sb. +struct KvdbHelper { + btrees: Vec, +} + + +impl rustyline::completion::Completer for KvdbHelper { + type Candidate = String; + + fn complete( + &self, + line: &str, + pos: usize, + _: &rustyline::Context<'_>, + ) -> rustyline::Result<(usize, Vec)> { + let start = line[..pos].rfind(char::is_whitespace).map_or(0, |i| i + 1); + let word = &line[start..pos]; + let prior: Vec<&str> = line[..start].split_whitespace().collect(); + + let candidates: Vec = match prior.as_slice() { + [] => COMMANDS.iter().map(|c| c.name.to_string()).collect(), + [op] => match COMMANDS.iter().find(|c| c.name == *op || c.aliases.contains(op)) { + Some(c) if c.completes_btree => self.btrees.clone(), + Some(c) => c.subcommands.iter().map(|s| s.to_string()).collect(), + None => vec![], + }, + _ => vec![], + }; + Ok(( + start, + candidates + .into_iter() + .filter(|c| c.starts_with(word)) + .collect(), + )) + } +} + +impl rustyline::hint::Hinter for KvdbHelper { + type Hint = String; } +impl rustyline::highlight::Highlighter for KvdbHelper {} +impl rustyline::validate::Validator for KvdbHelper {} +impl rustyline::Helper for KvdbHelper {} -fn cmd_list(fs: &Fs, btree: c::btree_id, start: c::bpos, end: c::bpos) -> Result { +/// ^C during a long-running command: the REPL installs a SIGINT handler that +/// sets this flag (rustyline's raw mode swallows ^C at the prompt itself, so +/// the handler only ever fires mid-command). Iteration loops poll it and stop, +/// returning what they've collected; the flag is cleared before each command. +static INTERRUPTED: AtomicBool = AtomicBool::new(false); + +extern "C" fn kvdb_sigint(_: libc::c_int) { + INTERRUPTED.store(true, Ordering::Relaxed); +} + +fn take_interrupt() -> bool { + INTERRUPTED.swap(false, Ordering::Relaxed) +} + +fn cmd_list(fs: &Fs, btree: c::btree_id, start: c::bpos, end: c::bpos, + filtered: bool, key_only: bool) -> Result { let trans = BtreeTrans::new(fs); let mut out = String::new(); let mut iter = BtreeIter::new( &trans, btree, start, - BtreeIterFlags::ALL_SNAPSHOTS | BtreeIterFlags::PREFETCH, + iter_flags(BtreeIterFlags::ALL_SNAPSHOTS | BtreeIterFlags::PREFETCH, filtered), ); iter.for_each_max(&trans, end, |k| { - out.push_str(&format!("{}\n", k.to_text(fs))); + if take_interrupt() { + out.push_str("(interrupted)\n"); + return ControlFlow::Break(()); + } + if key_only { + out.push_str(&format!("{}\n", k.to_text_key())); + } else { + out.push_str(&format!("{}\n", k.to_text(fs))); + } ControlFlow::Continue(()) })?; Ok(out) @@ -267,40 +600,57 @@ fn cmd_list(fs: &Fs, btree: c::btree_id, start: c::bpos, end: c::bpos) -> Result /// exact pos; peek/peek_prev: first key at/after (at/before) pos. fn online_one_key(handle: &BcachefsHandle, fs: &Fs, btree: c::btree_id, pos: c::bpos, - flags: OnlineIterFlags, fields: bool) -> Result { + flags: OnlineIterFlags, how: Render<'_>) -> Result { // Small buffer: the kernel fills the whole thing per call, and we only // want one key (it grows automatically if the key doesn't fit): let mut iter = OnlineBtreeIter::with_buf_size(handle, btree, 0, pos, if flags.0 & OnlineIterFlags::PREV.0 != 0 { POS_MIN } else { SPOS_MAX }, flags, 4096); - Ok(match iter.next().map_err(|e| anyhow!("BCH_IOCTL_QUERY_BTREE_KEYS: {e}"))? { - Some(k) => render_key(fs, &k, fields), - None => "(no key)\n".to_string(), - }) + match iter.next().map_err(|e| anyhow!("BCH_IOCTL_QUERY_BTREE_KEYS: {e}"))? { + Some(k) => render_read(fs, &k, how), + None => Ok("(no key)\n".to_string()), + } } -fn cmd_get_online(handle: &BcachefsHandle, fs: &Fs, - btree: c::btree_id, pos: c::bpos) -> Result { - online_one_key(handle, fs, btree, pos, - OnlineIterFlags::SLOTS | OnlineIterFlags::ALL_SNAPSHOTS, true) +/// Online counterpart of iter_flags(): the ioctl maps its flags 1:1 into +/// btree iter flags, so omitting all_snapshots gets filtered iteration +/// kernel-side. (nofilter_whiteouts is rejected by kernels predating the +/// bit - run a matching kernel for online filtered reads.) +fn online_snapshots_flag(filtered: bool) -> OnlineIterFlags { + if filtered { + OnlineIterFlags::NOFILTER_WHITEOUTS + } else { + OnlineIterFlags::ALL_SNAPSHOTS + } } -fn cmd_peek_online(handle: &BcachefsHandle, fs: &Fs, - btree: c::btree_id, pos: c::bpos, prev: bool) -> Result { - let mut flags = OnlineIterFlags::ALL_SNAPSHOTS; - if prev { - flags = flags | OnlineIterFlags::PREV; - } - online_one_key(handle, fs, btree, pos, flags, true) +fn cmd_read_online(handle: &BcachefsHandle, fs: &Fs, op: ReadOp, + btree: c::btree_id, pos: c::bpos, filtered: bool, + how: Render<'_>) -> Result { + let flags = online_snapshots_flag(filtered) | match op { + ReadOp::Get => OnlineIterFlags::SLOTS, + ReadOp::Peek => OnlineIterFlags(0), + ReadOp::PeekPrev => OnlineIterFlags::PREV, + }; + online_one_key(handle, fs, btree, pos, flags, how) } fn cmd_list_online(handle: &BcachefsHandle, fs: &Fs, - btree: c::btree_id, start: c::bpos, end: c::bpos) -> Result { + btree: c::btree_id, start: c::bpos, end: c::bpos, + filtered: bool, key_only: bool) -> Result { let mut out = String::new(); let mut iter = OnlineBtreeIter::new(handle, btree, 0, start, end, - OnlineIterFlags::ALL_SNAPSHOTS); + online_snapshots_flag(filtered)); iter.for_each(|k| { - out.push_str(&format!("{}\n", k.to_text(fs))); + if take_interrupt() { + out.push_str("(interrupted)\n"); + return ControlFlow::Break(()); + } + if key_only { + out.push_str(&format!("{}\n", k.to_text_key())); + } else { + out.push_str(&format!("{}\n", k.to_text(fs))); + } ControlFlow::Continue(()) }).map_err(|e| anyhow!("BCH_IOCTL_QUERY_BTREE_KEYS: {e}"))?; Ok(out) @@ -364,29 +714,15 @@ fn cmd_update( } } - // BkeySC is a split key: k (unpacked header) and v are separate - // pointers, so copy them separately. - let cur_val = k.k.u64s as usize - BKEY_U64S; - let val_u64s = cur_val.max(need.div_ceil(8)); - let mut new = t.bkey_alloc((BKEY_U64S + val_u64s) as u32) + let val_u64s = (k.k.u64s as usize - BKEY_U64S).max(need.div_ceil(8)); + let mut new = t.bkey_reassemble_resized(k, val_u64s) .map_err(TransError::from)?; - new.as_mut_u64s().fill(0); - unsafe { - core::ptr::copy_nonoverlapping(k.k, new.k_mut(), 1); - core::ptr::copy_nonoverlapping( - k.v as *const c::bch_val as *const u64, - new.as_mut_u64s()[BKEY_U64S..].as_mut_ptr(), - cur_val, - ); - } - new.k_mut().u64s = (BKEY_U64S + val_u64s) as u8; - let val = &mut new.as_mut_u64s()[BKEY_U64S..]; - let val: &mut [u8] = unsafe { - std::slice::from_raw_parts_mut(val.as_mut_ptr() as *mut u8, val.len() * 8) - }; + let type_ = new.k().type_; + let mut val_view = BkeyS::from(new.k_i_mut()); + let val = val_view.val_bytes_mut(); for (path, v) in &resolved { - let target = resolve_field(new.k().type_, path).expect("resolved above"); + let target = resolve_field(type_, path).expect("resolved above"); if let Err(e) = write_field(val, &target, *v) { user_err = Some(anyhow!("{path}: {e}")); return Err(no_key_err()); @@ -409,10 +745,19 @@ fn cmd_set( pos: c::bpos, type_name: &str, assigns: &[(&str, FieldVal)], + in_snapshot: bool, ) -> Result { let ti = typeinfo::bkey_type_info_by_name(type_name) .ok_or_else(|| anyhow!("unknown key type '{type_name}'"))?; - let val_u64s = ti.info.size.div_ceil(8); + + // The value needs the struct's fixed size, extended by whatever the + // assignments reach - vartail elements (damage errors[n]) lie beyond it: + let mut need = ti.info.size; + for (path, _) in assigns { + let (r, _) = resolve_field(ti.type_ as u8, path)?; + need = need.max(r.offset + r.len); + } + let val_u64s = need.div_ceil(8); let assigns = assigns .iter() @@ -427,18 +772,34 @@ fn cmd_set( None, CommitOpts::new().flags(CommitFlags::NO_ENOSPC), |t| { - let mut new = t.bkey_alloc((BKEY_U64S + val_u64s) as u32) - .map_err(TransError::from)?; - new.as_mut_u64s().fill(0); - unsafe { c::bkey_init(new.k_mut()) }; - new.k_mut().u64s = (BKEY_U64S + val_u64s) as u8; - new.k_mut().type_ = ti.type_ as u8; - new.k_mut().p = pos; - - let val = &mut new.as_mut_u64s()[BKEY_U64S..]; - let val: &mut [u8] = unsafe { - std::slice::from_raw_parts_mut(val.as_mut_ptr() as *mut u8, val.len() * 8) + // Deletion has two meanings. Raw (the default): remove this + // exact key - a filtered iter would have bch2_trans_update() + // convert the deletion into a whiteout whenever the key is + // visible in an ancestor snapshot, so deleting a whiteout + // silently rewrites it as itself. -s: delete within pos's + // snapshot - the filtered iter gets exactly that conversion, + // the same semantics as a runtime delete. The peek is just + // the traverse bch2_trans_update() requires. + let (iter_flags, update_flags) = if in_snapshot { + (BtreeIterFlags::INTENT, UpdateTriggerFlags::empty()) + } else { + (RAW_EXACT | BtreeIterFlags::INTENT, + UpdateTriggerFlags::INTERNAL_SNAPSHOT_NODE) }; + let mut iter = BtreeIter::new( + t.trans(), + btree, + pos, + iter_flags, + ); + iter.peek_max_flags(SPOS_MAX, BtreeIterFlags::SLOTS) + .map_err(TransError::from)?; + + let mut new = t.bkey_alloc_init(val_u64s, ti.type_ as u8, pos) + .map_err(TransError::from)?; + + let mut val_view = BkeyS::from(new.k_i_mut()); + let val = val_view.val_bytes_mut(); for (path, v) in &assigns { let target = match typeinfo::resolve_with_bits(ti.info, path) { Ok(t) => t, @@ -453,7 +814,7 @@ fn cmd_set( } } - t.insert_nonextent(btree, new, UpdateTriggerFlags::INTERNAL_SNAPSHOT_NODE) + t.update(&mut iter, new, update_flags) }, ); @@ -463,19 +824,95 @@ fn cmd_set( } } +// --------------------------------------------------------------------------- +// superblock fields — same field engine as keys, anchored on bch_sb::INFO +// (which carries the BCH_SB_* LE64_BITMASK fields), written back via +// bch2_write_super so the csum is recomputed and every sb copy updated. + +fn sb_field(field: &str) -> Result { + typeinfo::resolve_with_bits(::INFO, field) + .map_err(|e| anyhow!("{e}")) +} + +fn cmd_sb_get(fs: &Fs, field: &str) -> Result { + let (r, bm) = sb_field(field)?; + let buf = fs.disk_sb().sb_bytes(); + let v = match bm { + Some(bm) => typeinfo::read_bits(buf, &r, bm), + None => typeinfo::read_scalar(buf, &r), + }.map_err(|e| anyhow!("{field}: {e}"))?; + Ok(format!("{field} = {v} (0x{v:x})\n")) +} + +fn cmd_sb_set(fs: &Fs, field: &str, v: u64) -> Result { + let target = sb_field(field)?; + + let _lock = unsafe { crate::wrappers::sb_lock(fs.raw) }; + + // bch2_write_super() silently skips uninitialized superblocks (the gate + // that keeps format from writing a half-built sb). An opened-from-disk + // sb is complete, but never-started images (fresh format) still have + // INITIALIZED unset - fail loudly rather than claim success. + { + let (r, bm) = sb_field("initialized")?; + let buf = fs.disk_sb().sb_bytes(); + let initialized = match bm { + Some(bm) => typeinfo::read_bits(buf, &r, bm), + None => typeinfo::read_scalar(buf, &r), + }.map_err(|e| anyhow!("initialized: {e}"))?; + if initialized == 0 { + bail!("superblock not initialized (filesystem has never been started): \ + bch2_write_super would silently skip the write; \ + start the fs once (mount, or kvdb --rw) first"); + } + } + + /* sb_lock is held above - disk_sb_mut's contract: */ + let buf = unsafe { fs.disk_sb_mut() }.sb_bytes_mut(); + write_field(buf, &target, v).map_err(|e| anyhow!("{field}: {e}"))?; + + // Every kvdb open short of --rw runs with nochanges (norecovery implies + // it, init/fs.c), which turns bch2_write_super() into a silent no-op. + // That protection is load-bearing - the open path makes version-upgrade + // decisions an inspection-mode open must never persist - so don't weaken + // the open; lift nochanges around this one write, which is the user's + // explicit request. + fs.write_super_force() + .map_err(|e| anyhow!("bch2_write_super failed: {e}"))?; + Ok(String::new()) +} + // --------------------------------------------------------------------------- // command dispatch + REPL const HELP: &str = "\ -get exact lookup, dump fields -peek first key >= pos -peek_prev last key <= pos -list [start] [end] keys in range +get [-k] [..] exact lookup (slot iteration) +peek [-k] [..] first key >= pos +peek_prev [..] last key <= pos ([-k] too) +list [-k] [start] [end] keys in range + -k prints keys only, without rendering values + trailing field paths print those fields as bare values, one per + line, instead of the display rendering - the same paths update + takes (depth, btime.lo, skip[1]); a whole array prints its + elements space-separated update ... modify fields of an existing key -set [field=val]... insert a whole new key +set [-s] [field=val]... insert a whole new key values are integers; fields holding enum codewords (snapshot/ subvolume state) also accept the value name, e.g. state=will_delete + `set deleted` removes the exact key; with -s it deletes + within pos's snapshot instead (whiteouts, like a runtime delete) +sb get read a superblock field/flag +sb set write one, then bch2_write_super +list_journal [-k [+-][-],...] journal transactions, filtered to + those referencing the given key + ranges (needs --journal at open) +snapshot [|none] set/show/clear the session snapshot + context: reads (get/peek/list) run + snapshot-filtered in that view, and + a without :snapshot uses it; + writes (update/set) stay exact-key help this text +quit exit (also ^D) "; /// A kvdb session: fully offline (read + write via libbcachefs), or against @@ -487,78 +924,323 @@ enum KvdbFs { Online(BcachefsHandle, Fs), } -fn run_line(kvdb_fs: &KvdbFs, line: &str) -> Result<()> { - let args: Vec<&str> = line.split_whitespace().collect(); - let Some((&op, args)) = args.split_first() else { - return Ok(()); - }; +impl KvdbFs { + /// The userspace Fs handle, for reads that don't go through the kernel + /// (superblock access; the sb is loaded in both the offline and online + /// cases). + fn fs(&self) -> &Fs { + match self { + KvdbFs::Offline(fs) | KvdbFs::Online(_, fs) => fs, + } + } - let out = match op { - "get" | "peek" | "peek_prev" => { - let [btree, pos] = args else { - bail!("usage: {op} "); - }; - let (btree, pos) = (parse_btree(btree)?, parse_pos(pos)?); - match kvdb_fs { - KvdbFs::Offline(fs) => match op { - "get" => cmd_get(fs, btree, pos)?, - "peek" => cmd_peek(fs, btree, pos, false)?, - _ => cmd_peek(fs, btree, pos, true)?, - }, - KvdbFs::Online(handle, fs) => match op { - "get" => cmd_get_online(handle, fs, btree, pos)?, - "peek" => cmd_peek_online(handle, fs, btree, pos, false)?, - _ => cmd_peek_online(handle, fs, btree, pos, true)?, - }, - } + /// The offline Fs, for operations that need libbcachefs btree/journal + /// access (writes, list_journal). + fn offline(&self) -> Result<&Fs> { + match self { + KvdbFs::Offline(fs) => Ok(fs), + KvdbFs::Online(..) => bail!( + "filesystem is mounted: this command needs offline access \ + (online kvdb reads via the kernel, read-only)" + ), } - "list" => { - let (btree, rest) = args - .split_first() - .ok_or_else(|| anyhow!("usage: list [start] [end]"))?; - let start = rest.first().map_or(Ok(POS_MIN), |s| parse_pos(s))?; - let end = rest.get(1).map_or(Ok(SPOS_MAX), |s| parse_pos(s))?; - let btree = parse_btree(btree)?; - match kvdb_fs { - KvdbFs::Offline(fs) => cmd_list(fs, btree, start, end)?, - KvdbFs::Online(handle, fs) => cmd_list_online(handle, fs, btree, start, end)?, - } + } + + fn read(&self, op: ReadOp, btree: c::btree_id, pos: c::bpos, filtered: bool, + how: Render<'_>) -> Result { + match self { + KvdbFs::Offline(fs) => cmd_read(fs, op, btree, pos, filtered, how), + KvdbFs::Online(handle, fs) => + cmd_read_online(handle, fs, op, btree, pos, filtered, how), } - "update" => { - let [btree, pos, assigns @ ..] = args else { - bail!("usage: update ..."); - }; - if assigns.is_empty() { - bail!("usage: update ..."); - } - let KvdbFs::Offline(fs) = kvdb_fs else { - bail!("filesystem is mounted: kvdb is read-only on mounted filesystems"); - }; - let assigns = assigns - .iter() - .map(|s| parse_assign(s)) - .collect::>>()?; - cmd_update(fs, parse_btree(btree)?, parse_pos(pos)?, &assigns)? + } + + fn list(&self, btree: c::btree_id, start: c::bpos, end: c::bpos, filtered: bool, + key_only: bool) -> Result { + match self { + KvdbFs::Offline(fs) => cmd_list(fs, btree, start, end, filtered, key_only), + KvdbFs::Online(handle, fs) => + cmd_list_online(handle, fs, btree, start, end, filtered, key_only), + } + } +} + +/// Session state threaded to command handlers: the open filesystem, the +/// open-mode capabilities, and the snapshot context. +struct Repl<'a> { + fs: &'a KvdbFs, + nostart: bool, + journal: bool, + rw: bool, + snapshot: Option, +} + +type CmdHandler = fn(&mut Repl, &Cmd, &[&str]) -> Result>; + +/// One entry per command; dispatch, capability gating, usage messages, and +/// tab completion all read from this table, so they can't drift. +struct Cmd { + name: &'static str, + aliases: &'static [&'static str], + usage: &'static str, + /// second word completes as a btree name + completes_btree: bool, + /// second-word completions for commands with subcommands + subcommands: &'static [&'static str], + /// available under --nostart (superblock-only open) + nostart_ok: bool, + /// write command: requires --rw + needs_rw: bool, + /// requires --journal + needs_journal: bool, + handler: CmdHandler, +} + +const COMMANDS: &[Cmd] = &[ + Cmd { name: "get", aliases: &[], usage: "get [-k] [..]", + completes_btree: true, subcommands: &[], + nostart_ok: false, needs_rw: false, needs_journal: false, handler: h_read }, + Cmd { name: "peek", aliases: &[], usage: "peek [-k] [..]", + completes_btree: true, subcommands: &[], + nostart_ok: false, needs_rw: false, needs_journal: false, handler: h_read }, + Cmd { name: "peek_prev", aliases: &[], usage: "peek_prev [-k] [..]", + completes_btree: true, subcommands: &[], + nostart_ok: false, needs_rw: false, needs_journal: false, handler: h_read }, + Cmd { name: "list", aliases: &[], usage: "list [-k] [start] [end]", + completes_btree: true, subcommands: &[], + nostart_ok: false, needs_rw: false, needs_journal: false, handler: h_list }, + Cmd { name: "update", aliases: &[], usage: "update ...", + completes_btree: true, subcommands: &[], + nostart_ok: false, needs_rw: true, needs_journal: false, handler: h_update }, + Cmd { name: "set", aliases: &[], usage: "set [-s] [field=val]...", + completes_btree: true, subcommands: &[], + nostart_ok: false, needs_rw: true, needs_journal: false, handler: h_set }, + Cmd { name: "sb", aliases: &[], usage: "sb get | sb set ", + completes_btree: false, subcommands: &["get", "set"], + nostart_ok: true, needs_rw: false, needs_journal: false, handler: h_sb }, + Cmd { name: "snapshot", aliases: &[], usage: "snapshot [|none]", + completes_btree: false, subcommands: &[], + nostart_ok: true, needs_rw: false, needs_journal: false, handler: h_snapshot }, + Cmd { name: "list_journal", aliases: &[], + usage: "list_journal [-k [+-]:[-:],...]", + completes_btree: false, subcommands: &[], + nostart_ok: false, needs_rw: false, needs_journal: true, handler: h_list_journal }, + Cmd { name: "help", aliases: &["?"], usage: "help", + completes_btree: false, subcommands: &[], + nostart_ok: true, needs_rw: false, needs_journal: false, handler: h_help }, + Cmd { name: "quit", aliases: &["exit", "q"], usage: "quit", + completes_btree: false, subcommands: &[], + nostart_ok: true, needs_rw: false, needs_journal: false, handler: h_quit }, +]; + +fn h_quit(_: &mut Repl, _: &Cmd, _: &[&str]) -> Result> { + Ok(ControlFlow::Break(())) +} + +fn h_help(_: &mut Repl, _: &Cmd, _: &[&str]) -> Result> { + Ok(ControlFlow::Continue(HELP.to_string())) +} + +fn h_snapshot(repl: &mut Repl, cmd: &Cmd, args: &[&str]) -> Result> { + Ok(ControlFlow::Continue(match args { + [] => match repl.snapshot { + Some(s) => format!("snapshot context: {s}\n"), + None => "no snapshot context\n".to_string(), + }, + ["none"] | ["clear"] => { + repl.snapshot = None; + String::new() + } + [s] => { + repl.snapshot = Some(u32::try_from(parse_int(s)?)?); + String::new() + } + _ => bail!("usage: {}", cmd.usage), + })) +} + +fn h_read(repl: &mut Repl, cmd: &Cmd, args: &[&str]) -> Result> { + let (key_only, args) = match args { + ["-k", rest @ ..] => (true, rest), + _ => (false, args), + }; + let [btree, pos, fields @ ..] = args else { + bail!("usage: {}", cmd.usage); + }; + let how = match (key_only, fields) { + (false, []) => Render::Full, + (true, []) => Render::KeyOnly, + (false, fields) => Render::Fields(fields), + (true, _) => bail!("-k and field selection are mutually exclusive"), + }; + let btree = parse_btree(btree)?; + let ctx = repl.snapshot + .filter(|_| btree_uses_snapshots(btree) && !pos_has_explicit_snapshot(pos)); + let mut pos = parse_pos(pos)?; + if let Some(snap) = ctx { + pos.snapshot = snap; + } + let filtered = ctx.is_some(); + let op = match cmd.name { + "get" => ReadOp::Get, + "peek" => ReadOp::Peek, + _ => ReadOp::PeekPrev, + }; + Ok(ControlFlow::Continue(repl.fs.read(op, btree, pos, filtered, how)?)) +} + +fn h_list(repl: &mut Repl, cmd: &Cmd, args: &[&str]) -> Result> { + let (key_only, args) = match args { + ["-k", rest @ ..] => (true, rest), + _ => (false, args), + }; + let (btree, rest) = args + .split_first() + .ok_or_else(|| anyhow!("usage: {}", cmd.usage))?; + let btree = parse_btree(btree)?; + let ctx = repl.snapshot.filter(|_| { + btree_uses_snapshots(btree) + && !rest.iter().take(2).any(|s| pos_has_explicit_snapshot(s)) + }); + let mut start = rest.first().map_or(Ok(POS_MIN), |s| parse_pos(s))?; + let end = rest.get(1).map_or(Ok(SPOS_MAX), |s| parse_pos_ctx(s, ctx))?; + // A filtered iterator's snapshot comes from the start pos - it's the + // view - so it must carry the context whether the start was given, + // defaulted, or POS_MIN (snapshot 0 is never a valid view): + if let Some(snap) = ctx { + start.snapshot = snap; + } + let filtered = ctx.is_some(); + Ok(ControlFlow::Continue(repl.fs.list(btree, start, end, filtered, key_only)?)) +} + +fn h_update(repl: &mut Repl, cmd: &Cmd, args: &[&str]) -> Result> { + let [btree, pos, assigns @ ..] = args else { + bail!("usage: {}", cmd.usage); + }; + if assigns.is_empty() { + bail!("usage: {}", cmd.usage); + } + let fs = repl.fs.offline()?; + let assigns = assigns + .iter() + .map(|s| parse_assign(s)) + .collect::>>()?; + let btree = parse_btree(btree)?; + let ctx = repl.snapshot.filter(|_| btree_uses_snapshots(btree)); + Ok(ControlFlow::Continue(cmd_update(fs, btree, parse_pos_ctx(pos, ctx)?, &assigns)?)) +} + +fn h_set(repl: &mut Repl, cmd: &Cmd, args: &[&str]) -> Result> { + let (in_snapshot, args) = match args { + ["-s", rest @ ..] => (true, rest), + _ => (false, args), + }; + let [btree, pos, type_name, assigns @ ..] = args else { + bail!("usage: {}", cmd.usage); + }; + if in_snapshot && *type_name != "deleted" { + bail!("-s (delete within pos's snapshot) only applies to deletions"); + } + let fs = repl.fs.offline()?; + let assigns = assigns + .iter() + .map(|s| parse_assign(s)) + .collect::>>()?; + let btree = parse_btree(btree)?; + let ctx = repl.snapshot.filter(|_| btree_uses_snapshots(btree)); + Ok(ControlFlow::Continue( + cmd_set(fs, btree, parse_pos_ctx(pos, ctx)?, type_name, &assigns, in_snapshot)?, + )) +} + +fn h_sb(repl: &mut Repl, cmd: &Cmd, args: &[&str]) -> Result> { + let (&sub, rest) = args.split_first() + .ok_or_else(|| anyhow!("usage: {}", cmd.usage))?; + Ok(ControlFlow::Continue(match sub { + "get" => { + let [field] = rest else { bail!("usage: sb get "); }; + cmd_sb_get(repl.fs.fs(), field)? } "set" => { - let [btree, pos, type_name, assigns @ ..] = args else { - bail!("usage: set [field=val]..."); - }; - let KvdbFs::Offline(fs) = kvdb_fs else { - bail!("filesystem is mounted: kvdb is read-only on mounted filesystems"); + let [assign] = rest else { bail!("usage: sb set "); }; + // Under the default norecovery open, nochanges makes + // bch2_write_super() a silent no-op - refuse rather than claim + // success. (Not table-gated needs_rw: sb get is fine read-only, + // and --nostart is the sb-editing mode and never sets nochanges.) + if !repl.rw && !repl.nostart { + bail!("read-only (the default is norecovery): \ + reopen with --rw, or --nostart for sb-only edits"); + } + let (field, val) = parse_assign(assign)?; + let FieldVal::Int(v) = val else { + bail!("sb set: expected an integer value"); }; - let assigns = assigns - .iter() - .map(|s| parse_assign(s)) - .collect::>>()?; - cmd_set(fs, parse_btree(btree)?, parse_pos(pos)?, type_name, &assigns)? + cmd_sb_set(repl.fs.offline()?, field, v)? } - "help" | "?" => HELP.to_string(), - _ => bail!("unknown command '{op}' (try: help)"), + _ => bail!("usage: {}", cmd.usage), + })) +} + +fn h_list_journal(repl: &mut Repl, cmd: &Cmd, args: &[&str]) -> Result> { + let fs = repl.fs.offline()?; + let mut f = super::list_journal::JournalFilter::default(); + // Searching the journal, not auditing it: gaps in the sequence aren't + // what we're here for, and on a damaged fs they're endless spam. + f.print_missing = false; + let mut args = args; + while let Some((&flag, rest)) = args.split_first() { + match flag { + "-k" => { + let Some((&ranges, rest)) = rest.split_first() else { + bail!("usage: {}", cmd.usage); + }; + let (sign, r) = super::list_journal::parse_sign(ranges); + for part in r.split(',') { + let range = bcachefs_kernel::bbpos_range_parse(part) + .map_err(|e| anyhow!("{e}: {part}"))?; + f.key.ranges.push((sign, range)); + } + f.filtering = true; + args = rest; + } + _ => bail!("list_journal: unknown arg '{flag}' (supported: -k )"), + } + } + let interrupt: &dyn Fn() -> bool = &take_interrupt; + super::list_journal::list_journal_run(fs.raw, &f, false, 0, u64::MAX, None, + Some(interrupt))?; + Ok(ControlFlow::Continue(String::new())) +} + +fn run_line(repl: &mut Repl, line: &str) -> Result> { + let args: Vec<&str> = line.split_whitespace().collect(); + let Some((&op, args)) = args.split_first() else { + return Ok(ControlFlow::Continue(())); }; - print!("{out}"); - Ok(()) + let Some(cmd) = COMMANDS.iter() + .find(|c| c.name == op || c.aliases.contains(&op)) else { + bail!("unknown command '{op}' (try: help)"); + }; + + if repl.nostart && !cmd.nostart_ok { + bail!("--nostart: the btree isn't started, only sb commands are available"); + } + if cmd.needs_rw && !repl.rw { + bail!("read-only (the default is norecovery): reopen with --rw to edit"); + } + if cmd.needs_journal && !repl.journal { + bail!("{}: reopen with --journal (retains the whole journal in memory)", cmd.name); + } + + match (cmd.handler)(repl, cmd, args)? { + ControlFlow::Continue(out) => { + print!("{out}"); + Ok(ControlFlow::Continue(())) + } + ControlFlow::Break(()) => Ok(ControlFlow::Break(())), + } } fn kvdb(cli: Cli) -> Result<()> { @@ -588,6 +1270,39 @@ fn kvdb(cli: Cli) -> Result<()> { if cli.verbose > 0 { opt_set!(fs_opts, verbose, 1); } + // sb-only mode: open the sb but don't run recovery or touch the btree. + if cli.nostart { + opt_set!(fs_opts, nostart, 1); + } + // Whatever repair the superblock has scheduled is not what we came for: + // check_allocations is pass 5, so recovery_pass_last below is a ceiling it + // sits under, not a filter that excludes it - a filesystem carrying an + // upgrade's scheduled passes rebuilds accounting before the first command + // runs. It stays scheduled, and runs at the next real mount. + opt_set!(fs_opts, recovery_passes_skip_scheduled, 1); + if cli.rw && cli.norecovery { + bail!("--rw and --norecovery are mutually exclusive"); + } + // Inspection is the primary use, and a full-recovery open can repair - + // rewrite - the state under inspection; rw is opt-in. + if !cli.rw { + opt_set!(fs_opts, norecovery, 1); + } else { + // Go read-write, and stop there. Everything through journal_replay is + // what makes the filesystem writable and consistent to write to - + // bch2_fs_read_write() refuses to go rw with recovery_pass_last below + // it. Everything after is repair, and repair is the one thing an + // injection must not have: the passes run at open, before the first + // command, so they rewrite the state we were about to construct. (A + // snapshot deletion that consumed the very node a test had staged is + // what prompted this.) Whatever the superblock still requires stays + // recorded and runs at the next real mount. + opt_set!(fs_opts, recovery_pass_last, c::bch_recovery_pass::BCH_RECOVERY_PASS_journal_replay as u8); + } + if cli.journal { + opt_set!(fs_opts, retain_recovery_info, 1); + opt_set!(fs_opts, read_entire_journal, 1); + } let kvdb_fs = match crate::device_scan::open_online_or_offline(&cli.devices, fs_opts)? { OpenedFs::Offline(fs) => KvdbFs::Offline(fs), @@ -612,32 +1327,78 @@ fn kvdb(cli: Cli) -> Result<()> { } }; let fs = &kvdb_fs; + let mut repl = Repl { + fs, + nostart: cli.nostart, + journal: cli.journal, + rw: cli.rw, + snapshot: None, + }; if !cli.commands.is_empty() { for line in &cli.commands { - run_line(fs, line)?; + if run_line(&mut repl, line)?.is_break() { + break; + } } return Ok(()); } - let interactive = stdin().is_terminal(); - let mut lines = stdin().lines(); - loop { - if interactive { - print!("kvdb> "); - stdout().flush()?; + // In a piped script an error must abort (a test's later commands likely + // depend on earlier ones); interactively, report and go on. + if !stdin().is_terminal() { + for line in stdin().lines() { + if run_line(&mut repl, &line?)?.is_break() { + break; + } } - let Some(line) = lines.next() else { break }; - let line = line?; - // In a piped script an error must abort (a test's later commands - // likely depend on earlier ones); interactively, report and go on. - match run_line(fs, &line) { - Err(e) if interactive => eprintln!("{e}"), - other => other?, + return Ok(()); + } + + unsafe { + libc::signal(libc::SIGINT, kvdb_sigint as *const () as libc::sighandler_t); + } + + let mut rl: rustyline::Editor = + rustyline::Editor::new()?; + rl.set_helper(Some(KvdbHelper { + btrees: bcachefs_kernel::BTREE_IDS_KNOWN + .iter() + .map(|id| id.to_string()) + .collect(), + })); + let history = std::env::var_os("HOME") + .map(|home| PathBuf::from(home).join(".cache/bcachefs-kvdb-history")); + if let Some(h) = &history { + let _ = rl.load_history(h); + } + loop { + let prompt = match repl.snapshot { + Some(s) => format!("kvdb[{s}]> "), + None => "kvdb> ".to_string(), + }; + match rl.readline(&prompt) { + Ok(line) => { + if !line.trim().is_empty() { + let _ = rl.add_history_entry(&line); + } + INTERRUPTED.store(false, Ordering::Relaxed); + match run_line(&mut repl, &line) { + Ok(ControlFlow::Break(())) => break, + Ok(ControlFlow::Continue(())) => {} + Err(e) => eprintln!("{e}"), + } + } + Err(rustyline::error::ReadlineError::Interrupted) => continue, + Err(rustyline::error::ReadlineError::Eof) => break, + Err(e) => return Err(e.into()), } } - if interactive { - println!(); // ^D at the prompt: don't glue it to the shell's + if let Some(h) = &history { + if let Some(dir) = h.parent() { + let _ = std::fs::create_dir_all(dir); + } + let _ = rl.save_history(h); } Ok(()) } diff --git a/src/commands/list_journal.rs b/src/commands/list_journal.rs index cddce99d8a..1d2ad9e8b2 100644 --- a/src/commands/list_journal.rs +++ b/src/commands/list_journal.rs @@ -89,29 +89,54 @@ fn entry_is_non_transaction(entry: &c::jset_entry) -> bool { // ---- filter types ---- -struct TransactionMsgFilter { - sign: i32, - patterns: Vec, +pub(crate) struct TransactionMsgFilter { + pub(crate) sign: i32, + pub(crate) patterns: Vec, } -struct TransactionKeyFilter { - ranges: Vec<(i32, BbposRange)>, // (sign, range) +pub(crate) struct TransactionKeyFilter { + pub(crate) ranges: Vec<(i32, BbposRange)>, // (sign, range) } -struct JournalFilter { - blacklisted: bool, - flush_only: bool, - datetime_only: bool, - headers_only: bool, - all_headers: bool, - log: bool, - log_only: bool, - print_offset: bool, - filtering: bool, - btree_filter: u64, - transaction: TransactionMsgFilter, - key: TransactionKeyFilter, - bkey_val: bool, +pub(crate) struct JournalFilter { + pub(crate) blacklisted: bool, + pub(crate) flush_only: bool, + pub(crate) datetime_only: bool, + pub(crate) headers_only: bool, + pub(crate) all_headers: bool, + pub(crate) log: bool, + pub(crate) log_only: bool, + pub(crate) print_offset: bool, + /// Report gaps in the journal sequence ("missing N entries at ..."): + /// wanted when auditing the journal itself, spam when searching it + /// (kvdb's list_journal, on a damaged filesystem, disables this). + pub(crate) print_missing: bool, + pub(crate) filtering: bool, + pub(crate) btree_filter: u64, + pub(crate) transaction: TransactionMsgFilter, + pub(crate) key: TransactionKeyFilter, + pub(crate) bkey_val: bool, +} + +impl Default for JournalFilter { + fn default() -> Self { + JournalFilter { + blacklisted: false, + flush_only: false, + datetime_only: false, + headers_only: false, + all_headers: false, + log: false, + log_only: false, + print_offset: false, + print_missing: true, + filtering: false, + btree_filter: !0u64, + transaction: TransactionMsgFilter { sign: 0, patterns: Vec::new() }, + key: TransactionKeyFilter { ranges: Vec::new() }, + bkey_val: true, + } + } } // ---- filter logic ---- @@ -521,7 +546,7 @@ fn parse_seq_range(arg: &str) -> Result<(u64, u64)> { // ---- sign parsing ---- -fn parse_sign(s: &str) -> (i32, &str) { +pub(crate) fn parse_sign(s: &str) -> (i32, &str) { if let Some(rest) = s.strip_prefix('+') { (1, rest) } else if let Some(rest) = s.strip_prefix('-') { @@ -680,6 +705,7 @@ fn cmd_list_journal(cli: Cli) -> Result<()> { log: cli.log, log_only: cli.log_only, print_offset: cli.offset, + print_missing: true, filtering: false, btree_filter: !0u64, transaction: TransactionMsgFilter { @@ -738,6 +764,20 @@ fn cmd_list_journal(cli: Cli) -> Result<()> { let c_fs = fs.raw; + list_journal_run(c_fs, &f, contiguous_only, seq_start, seq_end, cli.nr_entries, None) +} + +/// The listing core, shared with kvdb's list_journal command. @interrupted +/// is polled per journal entry so a ^C can stop a long dump. +pub(crate) fn list_journal_run( + c_fs: *mut c::bch_fs, + f: &JournalFilter, + contiguous_only: bool, + seq_start: u64, + seq_end: u64, + nr_entries: Option, + interrupted: Option<&dyn Fn() -> bool>, +) -> Result<()> { let je = JournalEntries::collect(c_fs); let entries = je.as_slice(); @@ -769,7 +809,7 @@ fn cmd_list_journal(cli: Cli) -> Result<()> { } } - if let Some(nr) = cli.nr_entries { + if let Some(nr) = nr_entries { // journal.seq isn't set in read_journal_only mode, so compute // the max seq from the entries we actually collected let max_seq = entries.iter() @@ -785,6 +825,11 @@ fn cmd_list_journal(cli: Cli) -> Result<()> { let last_seq_ondisk = unsafe { (*c_fs).journal.last_seq_ondisk }; for &ep in entries { + if interrupted.is_some_and(|i| i()) { + println!("(interrupted)"); + break; + } + let p = unsafe { &*ep }; let p_seq = u64::from_le(p.j.seq); @@ -812,17 +857,19 @@ fn cmd_list_journal(cli: Cli) -> Result<()> { if missing.start == 0 { break; } - println!( - "missing {} entries at {}-{}{}", - missing.end - missing.start, - missing.start, - missing.end - 1, - if missing.end < last_seq_ondisk { - " (not dirty)" - } else { - "" - }, - ); + if f.print_missing { + println!( + "missing {} entries at {}-{}{}", + missing.end - missing.start, + missing.start, + missing.end - 1, + if missing.end < last_seq_ondisk { + " (not dirty)" + } else { + "" + }, + ); + } seq = missing.end; } diff --git a/src/commands/migrate.rs b/src/commands/migrate.rs index 6b804f7cd2..aad8658044 100644 --- a/src/commands/migrate.rs +++ b/src/commands/migrate.rs @@ -353,7 +353,7 @@ fn migrate_fs( let file_path = format!("{}/bcachefs", fs_path); println!("Creating new filesystem on {} in space reserved at {}", dev_path, file_path); - let dev_size = crate::wrappers::bdev::get_size(c_dev.fd); + let dev_size = crate::wrappers::bdev::get_size(c_dev.fd()); c_dev.fs_size = dev_size; let block_size = crate::commands::format_util::pick_block_size(&fs_opts, std::slice::from_ref(&c_dev)); @@ -507,11 +507,10 @@ fn migrate_superblock(dev_path: &str, sb_offset: u64) -> Result<()> { .open(dev_path) .map_err(|e| anyhow!("Error opening {}: {}", dev_path, e))?; - let sb = super_io::__bch2_super_read(dev_file.as_raw_fd(), sb_offset); - let sb_ref = unsafe { &mut *sb }; + let mut sb = super_io::super_read(dev_file.as_raw_fd(), sb_offset)?; // Validate and add default layout (catches errors early) - let sb_size = add_default_sb_layout(sb_ref)?; + let sb_size = add_default_sb_layout(sb.sb_mut())?; // Zero the start of the disk to blow away the old superblock let zeroes_len = ((c::BCH_SB_SECTOR as usize) << 9) + std::mem::size_of::(); @@ -522,7 +521,7 @@ fn migrate_superblock(dev_path: &str, sb_offset: u64) -> Result<()> { .map_err(|e| anyhow!("Error zeroing start of disk: {}", e))?; } drop(dev_file); - unsafe { libc::free(sb as *mut _) }; + drop(sb); // Open the filesystem with nostart + sb offset let dev_path_pb = std::path::PathBuf::from(dev_path); diff --git a/src/commands/mod.rs b/src/commands/mod.rs index 28ca56ece9..f60562ad32 100644 --- a/src/commands/mod.rs +++ b/src/commands/mod.rs @@ -89,11 +89,13 @@ macro_rules! raw_cmd { pub mod attr; pub mod completions; pub mod counters; +pub mod damage; pub mod data_read; pub mod device; pub mod dump; pub mod format; pub mod format_util; +pub mod fs_failure_domains; pub mod fs_usage; pub mod fsck; #[cfg(feature = "fuse")] @@ -212,7 +214,7 @@ pub fn defers_shrinkers(name: &str) -> bool { static FS_CMD: CmdDef = CmdDef { name: "fs", about: "Manage a running filesystem", aliases: &[], - kind: CmdKind::Group { children: &[&fs_usage::CMD, &top::CMD, ×tats::CMD] }, + kind: CmdKind::Group { children: &[&fs_usage::CMD, &fs_failure_domains::CMD, &top::CMD, ×tats::CMD] }, }; // ── Version (no module, trivial) ───────────────────────────────────── @@ -241,7 +243,7 @@ pub const COMMAND_GROUPS: &[GroupDef] = &[ &fusemount::CMD, &wait_devices::CMD, ]}, - GroupDef { heading: "Repair", commands: &[&fsck::CMD, &journal_rewind_info::CMD, &recovery_pass::CMD] }, + GroupDef { heading: "Repair", commands: &[&fsck::CMD, &journal_rewind_info::CMD, &recovery_pass::CMD, &damage::CMD] }, GroupDef { heading: "Running filesystem", commands: &[&FS_CMD] }, GroupDef { heading: "Devices", commands: &[&device::CMD] }, GroupDef { heading: "Subvolumes and snapshots", commands: &[&subvolume::CMD] }, diff --git a/src/commands/opts.rs b/src/commands/opts.rs index a5d316a482..226177be91 100644 --- a/src/commands/opts.rs +++ b/src/commands/opts.rs @@ -170,13 +170,7 @@ pub fn bch_opt_lookup_negated(name: &str) -> Option<(c::bch_opt_id, &'static c:: /// Look up a bcachefs option by name. Returns the typed option id and reference. pub fn bch_opt_lookup(name: &str) -> Option<(c::bch_opt_id, &'static c::bch_option)> { let c_name = std::ffi::CString::new(name).ok()?; - let id = unsafe { c::bch2_opt_lookup(c_name.as_ptr()) }; - if id < 0 || id as u32 >= bch_bindgen::opt_id::nr.0 { - return None; - } - let opt_id = bch_bindgen::opts::opt_id(id as usize); - let opt = unsafe { &*c::bch2_opt_table.as_ptr().add(id as usize) }; - Some((opt_id, opt)) + bcachefs_kernel::opts::opt_lookup(&c_name) } /// Option names matching the filter. @@ -213,29 +207,16 @@ pub(crate) fn parse_opt_val( val_str: &str, ) -> Result> { let c_val = CString::new(val_str)?; - let mut v: u64 = 0; let mut err = Printbuf::new(); - let ret = unsafe { - c::bch2_opt_parse( - std::ptr::null_mut(), - opt, - c_val.as_ptr(), - &mut v, - err.as_raw(), - ) - }; - - if ret == -(c::bch_errcode::BCH_ERR_option_needs_open_fs as i32) { - return Ok(None); - } - - if ret != 0 { - let msg = err.as_str(); - if msg.is_empty() { - bail!("invalid option: {}", val_str); + match bcachefs_kernel::opts::opt_parse(None, opt, &c_val, Some(&mut err)) { + Ok(v) => Ok(Some(v)), + Err(e) if e == -(c::bch_errcode::BCH_ERR_option_needs_open_fs as i32) => Ok(None), + Err(_) => { + let msg = err.as_str(); + if msg.is_empty() { + bail!("invalid option: {}", val_str); + } + bail!("invalid option: {}", msg); } - bail!("invalid option: {}", msg); } - - Ok(Some(v)) } diff --git a/src/commands/recover_super.rs b/src/commands/recover_super.rs index b2e3b7b9eb..4f79246777 100644 --- a/src/commands/recover_super.rs +++ b/src/commands/recover_super.rs @@ -10,8 +10,9 @@ use bch_bindgen::sb::sb_field_type; use clap::Parser; use crate::util::{file_size, parse_human_size}; +use bcachefs_kernel::sb::io::{SbBuf, SbParseError, BCACHE_MAGIC, BCHFS_MAGIC}; use bcachefs_kernel::util::printbuf::Printbuf; -use crate::wrappers::super_io::{self, BCACHE_MAGIC, BCHFS_MAGIC, SUPERBLOCK_SIZE_DEFAULT}; +use crate::wrappers::super_io::{self, SUPERBLOCK_SIZE_DEFAULT}; // bch2_sb_validate's flags parameter is a bch_validate_flags enum in bindgen, // but C passes 0 (no flags). Since 0 isn't a valid Rust enum variant, declare @@ -63,25 +64,6 @@ pub struct RecoverSuperCli { device: String, } -/// Interpret a byte buffer as a `&bch_sb`. -/// -/// SAFETY: `buf` must be large enough to contain a `bch_sb` header and the -/// pointer must be suitably aligned (any 512-byte-aligned buffer suffices). -unsafe fn buf_as_sb(buf: &[u8]) -> &c::bch_sb { - &*(buf.as_ptr() as *const c::bch_sb) -} - -/// Interpret a byte buffer as a `&mut bch_sb`. -/// -/// SAFETY: same as `buf_as_sb`. -unsafe fn buf_as_sb_mut(buf: &mut [u8]) -> &mut c::bch_sb { - &mut *(buf.as_mut_ptr() as *mut c::bch_sb) -} - -fn sb_magic_matches(sb: &c::bch_sb) -> bool { - sb.magic.b == BCACHE_MAGIC || sb.magic.b == BCHFS_MAGIC -} - fn sb_last_mount_time(sb: &c::bch_sb) -> u64 { (0..sb.nr_devices as i32) .map(|i| { @@ -105,15 +87,15 @@ fn prt_offset(offset: u64) -> Printbuf { hr } -fn probe_one_super(dev: &File, sb_size: usize, offset: u64, verbose: bool) -> Option> { +fn probe_one_super(dev: &File, sb_size: usize, offset: u64, verbose: bool) -> Option { let mut buf = vec![0u8; sb_size]; let r = dev.read_at(&mut buf, offset).ok()?; if r < sb_size { return None; } - let sb = unsafe { buf_as_sb_mut(&mut buf) }; - let (ret, _err) = validate_sb(sb, offset >> 9); + let mut sb = SbBuf::from_bytes(&buf).ok()?; + let (ret, _err) = validate_sb(sb.sb_mut(), offset >> 9); if ret != 0 { return None; } @@ -122,11 +104,10 @@ fn probe_one_super(dev: &File, sb_size: usize, offset: u64, verbose: bool) -> Op println!("found superblock at {}", prt_offset(offset)); } - let bytes = super_io::vstruct_bytes_sb(unsafe { buf_as_sb(&buf) }); - Some(buf[..bytes].to_vec()) + Some(sb) } -fn probe_sb_range(dev: &File, start: u64, end: u64, verbose: bool) -> Vec> { +fn probe_sb_range(dev: &File, start: u64, end: u64, verbose: bool) -> Vec { let start = start & !511u64; let end = end & !511u64; let buflen = (end - start) as usize; @@ -137,26 +118,34 @@ fn probe_sb_range(dev: &File, start: u64, end: u64, verbose: bool) -> Vec buflen { - eprintln!("found sb {} size {} that overran buffer", start + offset as u64, bytes); - offset += 512; - continue; - } + let mut sb = match SbBuf::from_bytes(&buf[offset..]) { + Ok(sb) => sb, + Err(e @ (SbParseError::ExtentBeyondBuffer { .. } | + SbParseError::FieldBeyondSb { .. } | + SbParseError::FieldBadU64s { .. })) => { + eprintln!("found sb {} {}", start + offset as u64, e); + offset += 512; + continue; + } + Err(_) => { + offset += 512; + continue; + } + }; - let sb = unsafe { buf_as_sb_mut(&mut buf[offset..]) }; - let (ret, err) = validate_sb(sb, (start + offset as u64) >> 9); + let (ret, err) = validate_sb(sb.sb_mut(), (start + offset as u64) >> 9); if ret != 0 { eprintln!("found sb {} that failed to validate: {}", start + offset as u64, err); offset += 512; @@ -167,7 +156,7 @@ fn probe_sb_range(dev: &File, start: u64, end: u64, verbose: bool) -> Vec Result> { - let mut sbs = if offset != 0 { +) -> Result { + let mut sbs: Vec = if offset != 0 { probe_one_super(dev, SUPERBLOCK_SIZE_DEFAULT as usize * 512, offset, verbose) .into_iter().collect() } else { @@ -195,11 +184,11 @@ fn recover_from_scan( } // Pick the most recently mounted superblock - sbs.sort_by_key(|sb| sb_last_mount_time(unsafe { buf_as_sb(sb) })); + sbs.sort_by_key(|sb| sb_last_mount_time(sb.sb())); Ok(sbs.pop().unwrap()) } -fn recover_from_member(src_device: &str, dev_idx: i32, dev_size: u64) -> Result> { +fn recover_from_member(src_device: &str, dev_idx: i32, dev_size: u64) -> Result { let mut opts = c::bch_opts::default(); opt_set!(opts, noexcl, 1); opt_set!(opts, nochanges, 1); @@ -218,10 +207,8 @@ fn recover_from_member(src_device: &str, dev_idx: i32, dev_size: u64) -> Result< return Err(anyhow!("Member {} does not exist in source superblock", dev_idx)); } - unsafe { - c::bch2_sb_field_delete(&mut src_sb, sb_field_type::journal); - c::bch2_sb_field_delete(&mut src_sb, sb_field_type::journal_v2); - } + src_sb.field_delete(sb_field_type::journal); + src_sb.field_delete(sb_field_type::journal_v2); src_sb.sb_mut().dev_idx = dev_idx as u8; // Read fields safely before layout mutation @@ -240,13 +227,9 @@ fn recover_from_member(src_device: &str, dev_idx: i32, dev_size: u64) -> Result< false, )?; - // Copy to owned buffer; src_sb's Drop will free the C allocation - let bytes = super_io::vstruct_bytes_sb(src_sb.sb()); - let sb_buf = unsafe { - std::slice::from_raw_parts(src_sb.sb as *const u8, bytes).to_vec() - }; - - Ok(sb_buf) + // Copy to an owned buffer; src_sb's Drop will free the C allocation + SbBuf::from_bytes(src_sb.sb_bytes()) + .map_err(|e| anyhow!("copying superblock from {}: {}", src_device, e)) } fn cmd_recover_super(cli: RecoverSuperCli) -> Result<()> { @@ -294,7 +277,7 @@ fn cmd_recover_super(cli: RecoverSuperCli) -> Result<()> { unsafe { buf.sb_to_text( std::ptr::null_mut(), - buf_as_sb(&sb_buf), + sb_buf.sb(), true, sb_field_type::members_v2.bit(), ); @@ -308,10 +291,7 @@ fn cmd_recover_super(cli: RecoverSuperCli) -> Result<()> { } if cli.yes || unsafe { bch_bindgen::c::ask_yn() } { - crate::wrappers::super_io::bch2_super_write( - dev_file.as_raw_fd(), - unsafe { buf_as_sb_mut(&mut sb_buf) }, - ); + crate::wrappers::super_io::bch2_super_write(dev_file.as_raw_fd(), &mut sb_buf); } let _ = std::process::Command::new("udevadm") diff --git a/src/commands/scrub.rs b/src/commands/scrub.rs index d156025a33..f607a50bbc 100644 --- a/src/commands/scrub.rs +++ b/src/commands/scrub.rs @@ -16,7 +16,7 @@ use clap::Parser; use crate::commands::DeviceNameArgs; use crate::util::{fmt_bytes_human, fmt_sectors_human}; use crate::wrappers::handle::BcachefsHandle; -use crate::wrappers::ioctl::bch_ioc_w; +use crate::wrappers::ioctl::{ioctl_w, BCH_IOCTL_DATA}; use crate::wrappers::sysfs::{fs_get_devices, sysfs_path_from_fd}; static INTERRUPTED: AtomicBool = AtomicBool::new(false); @@ -25,8 +25,6 @@ extern "C" fn sigint_handler(_: libc::c_int) { INTERRUPTED.store(true, Ordering::Relaxed); } -const BCH_IOCTL_DATA_NR: u32 = 10; - /// bch_ioctl_data_event is blocklisted from bindgen (packed+aligned conflict), /// so we read raw bytes and extract fields manually. /// Layout: u8 type, u8 ret, u8 pad[6], bch_ioctl_data_progress, padding to 128. @@ -47,7 +45,7 @@ fn read_data_event(fd: &mut std::fs::File) -> io::Result<(u8, u8, bch_ioctl_data Ok((event_type, event_ret, p)) } -fn start_scrub(ioctl_fd: i32, dev_idx: u32, data_types: u32) -> Result { +fn start_scrub(ioctl_fd: std::os::fd::BorrowedFd, dev_idx: u32, data_types: u32) -> Result { let mut cmd = bch_ioctl_data { op: bch_bindgen::c::bch_data_ops::BCH_DATA_OP_scrub as u16, ..Default::default() @@ -65,11 +63,7 @@ fn start_scrub(ioctl_fd: i32, dev_idx: u32, data_types: u32) -> Result(BCH_IOCTL_DATA_NR); - let ret = unsafe { libc::ioctl(ioctl_fd, request, &mut cmd as *mut bch_ioctl_data) }; - if ret < 0 { - return Err(std::io::Error::last_os_error().into()); - } + let ret = ioctl_w::(ioctl_fd, &cmd)?; Ok(unsafe { std::fs::File::from_raw_fd(ret) }) } @@ -144,7 +138,7 @@ fn scrub(cli: Cli) -> Result<()> { let name_mode = cli.device_names.name_mode(); let devices = fs_get_devices(&sysfs_path, name_mode)?; - let ioctl_fd = handle.ioctl_fd_raw(); + let ioctl_fd = handle.ioctl_fd(); let dev_idx = handle.dev_idx(); let mut scrub_devs: Vec = Vec::new(); @@ -263,6 +257,16 @@ fn scrub(cli: Cli) -> Result<()> { writeln!(io::stdout())?; eprintln!("Interrupted"); exit_code |= 1; + + // Parallelize kthread_stop() so we don't block on each thread serially + let stops: Vec<_> = scrub_devs + .iter_mut() + .filter_map(|dev| dev.progress_fd.take()) + .map(|fd| thread::spawn(move || drop(fd))) + .collect(); + for t in stops { + let _ = t.join(); + } break; } diff --git a/src/commands/set_option.rs b/src/commands/set_option.rs index 0908cc05f6..0e2cf8c0d7 100644 --- a/src/commands/set_option.rs +++ b/src/commands/set_option.rs @@ -122,6 +122,8 @@ fn set_option_offline( dev_idxs: &[u32], opts: &[(String, String)], ) -> Result<()> { + let mut modified = false; + for (name, value) in opts { let Some((opt_id, opt)) = bch_opt_lookup(name) else { eprintln!("Unknown option: {name}"); @@ -135,24 +137,18 @@ fn set_option_offline( } let c_value = CString::new(value.as_str())?; - let mut val: u64 = 0; - let ret = unsafe { - c::bch2_opt_parse(fs.raw, opt, c_value.as_ptr(), &mut val, std::ptr::null_mut()) - }; - if ret < 0 { + let Ok(val) = bcachefs_kernel::opts::opt_parse(Some(&fs), opt, &c_value, None) else { eprintln!("Error parsing {name}={value}"); continue; - } + }; if flags & c::opt_flags::OPT_FS as u32 != 0 { - let ret = unsafe { - c::bch2_opt_hook_pre_set(fs.raw, std::ptr::null_mut(), 0, opt_id, val, true, std::ptr::null_mut()) - }; - if ret < 0 { - eprintln!("Error setting {name}: {ret}"); + if let Err(e) = fs.opt_hook_pre_set(None, opt_id, val) { + eprintln!("Error setting {name}: {e}"); continue; } - unsafe { c::bch2_opt_set_sb(fs.raw, std::ptr::null_mut(), opt, val); } + fs.opt_set_sb(None, opt, val, Some(&c_value)); + modified = true; } if flags & c::opt_flags::OPT_DEVICE as u32 != 0 { @@ -160,51 +156,43 @@ fn set_option_offline( dev_idxs.to_vec() } else { devices.iter().filter_map(|dev| { - name_to_dev_idx(fs.raw, dev).map(|i| i as u32) + name_to_dev_idx(&fs, dev).map(|i| i as u32) }).collect() }; for idx in indices { - let ca = unsafe { (*fs.raw).devs[idx as usize] }; - if ca.is_null() { + let Some(ca) = fs.dev_get(idx) else { eprintln!("Couldn't look up device {idx}"); continue; - } - - let ret = unsafe { - c::bch2_opt_hook_pre_set(fs.raw, ca, 0, opt_id, val, true, std::ptr::null_mut()) }; - if ret < 0 { - eprintln!("Error setting {name}: {ret}"); + + if let Err(e) = fs.opt_hook_pre_set(Some(&ca), opt_id, val) { + eprintln!("Error setting {name}: {e}"); continue; } - unsafe { c::bch2_opt_set_sb(fs.raw, ca, opt, val); } + fs.opt_set_sb(Some(&ca), opt, val, Some(&c_value)); + modified = true; } } } + if modified { + if fs.disk_sb().sb().sb_initialized() == 0 { + bail!("superblock not initialized (filesystem was never started): \ + bch2_write_super would silently skip the write; mount it once first"); + } + let _lock = fs.sb_lock(); + fs.write_super_force() + .map_err(|e| anyhow::anyhow!("error writing superblock: {e}"))?; + } + Ok(()) } -fn name_to_dev_idx(c: *mut c::bch_fs, name: &str) -> Option { - let devs_len = unsafe { (*c).devs.len() }; - for i in 0..devs_len { - let ca = unsafe { (*c).devs[i] }; - if ca.is_null() { continue; } - // bch_dev.name is a [c_char; 32] array, not a pointer - let ca_name_bytes = unsafe { &(*ca).name }; - // Find the null terminator - let len = ca_name_bytes.iter().position(|&b| b == 0).unwrap_or(32); - // c_char is i8, but from_utf8 wants u8 - use from_raw_parts to reinterpret - let ca_name_bytes_u8 = unsafe { - std::slice::from_raw_parts(ca_name_bytes[..len].as_ptr() as *const u8, len) - }; - let ca_name = std::str::from_utf8(ca_name_bytes_u8).ok()?; - if ca_name == name { - return Some(i); - } - } - None +fn name_to_dev_idx(fs: &Fs, name: &str) -> Option { + (0..fs.nr_devices()) + .find(|&i| fs.dev_get(i).is_some_and(|ca| ca.name().to_bytes() == name.as_bytes())) + .map(|i| i as usize) } pub const CMD: super::CmdDef = raw_cmd!("set-fs-option", "Set filesystem options", cmd_set_option); diff --git a/src/commands/subvolume.rs b/src/commands/subvolume.rs index a4b71a2512..fcddd3a254 100644 --- a/src/commands/subvolume.rs +++ b/src/commands/subvolume.rs @@ -1,16 +1,19 @@ -use std::{collections::HashMap, env, ffi::CStr, mem, os::fd::{AsRawFd, OwnedFd}, path::{Path, PathBuf}}; +use std::{collections::HashMap, env, ffi::CStr, mem, os::fd::OwnedFd, path::{Path, PathBuf}}; use chrono::{Local, TimeZone}; use anyhow::{Context, Result}; use bch_bindgen::c::{ - BCH_SUBVOL_SNAPSHOT_RO, bch_ioctl_snapshot_node, bch_ioctl_subvol_dirent, - bch_ioctl_subvol_readdir, + BCH_SUBVOL_SNAPSHOT_RO, bch_ioctl_snapshot_node, bch_ioctl_snapshot_node_v2, + bch_ioctl_snapshot_tree_query, bch_ioctl_snapshot_tree_query_v2, + bch_ioctl_subvol_dirent, bch_ioctl_subvol_readdir, bch_ioctl_subvol_to_path, }; use clap::{Parser, Subcommand, ValueEnum}; -use crate::util::{fmt_sectors_human, fmt_bytes_human, fmt_num_human}; +use crate::util::{fmt_sectors_human, fmt_bytes_human, fmt_num_human, open_dir}; use crate::wrappers::handle::BcachefsHandle; -use crate::wrappers::ioctl::bch_ioc_wr; +use crate::wrappers::ioctl::{ioctl_ptr, ioctl_rw, Ioctl, IoctlBuf, + BCH_IOCTL_SNAPSHOT_TREE, BCH_IOCTL_SNAPSHOT_TREE_v2, + BCH_IOCTL_SUBVOLUME_LIST, BCH_IOCTL_SUBVOLUME_TO_PATH}; // ---- CLI definitions ---- @@ -157,7 +160,7 @@ struct SubvolEntry { path: String, } -type SnapshotNode = bch_ioctl_snapshot_node; +type SnapshotNode = bch_ioctl_snapshot_node_v2; struct SnapshotTreeResult { master_subvol: u32, @@ -167,105 +170,64 @@ struct SnapshotTreeResult { // ---- Ioctl layer ---- -const BCH_IOCTL_SUBVOLUME_LIST: u32 = 31; -const BCH_IOCTL_SUBVOLUME_TO_PATH: u32 = 32; -const BCH_IOCTL_SNAPSHOT_TREE_USAGE: u32 = 33; - const BCH_SUBVOLUME_RO: u32 = 1 << 0; const BCH_SUBVOLUME_UNLINKED: u32 = 1 << 2; -fn bcachefs_ioctl(fd: &OwnedFd, nr: u32, arg: &mut T) -> std::io::Result<()> { - let ret = unsafe { libc::ioctl(fd.as_raw_fd(), bch_ioc_wr::(nr), arg as *mut T) }; - if ret < 0 { - Err(std::io::Error::last_os_error()) - } else { - Ok(()) - } -} - -trait FlexArrayIoctl: Copy { +/// A header-plus-flexible-array ioctl with capacity/total retry protocol: +/// nr in is capacity, ERANGE reports the required total. +trait FlexArrayIoctl: Sized { type Node: Copy; - const NR: u32; + type Ioc: Ioctl; fn set_capacity(&mut self, n: u32); fn nr(&self) -> u32; fn total(&self) -> u32; + /// The trailing array, through the struct's flexible array member. + /// Caller guarantees `nr` entries exist past the header. + unsafe fn nodes(&self, nr: usize) -> &[Self::Node]; } fn bcachefs_flex_ioctl( fd: &OwnedFd, mut arg: H, ) -> Result<(H, Vec)> { - let hdr_size = mem::size_of::(); - let node_size = mem::size_of::(); - let request = bch_ioc_wr::(H::NR); let mut capacity = 256u32; loop { arg.set_capacity(capacity); - let buf_size = hdr_size + node_size * capacity as usize; - let mut buf = vec![0u8; buf_size]; + let mut buf = IoctlBuf::::new::(capacity as usize); + unsafe { std::ptr::copy_nonoverlapping(&arg, buf.as_mut_ptr(), 1) }; - unsafe { - std::ptr::copy_nonoverlapping( - &arg as *const H as *const u8, buf.as_mut_ptr(), hdr_size); - } - - let ret = unsafe { libc::ioctl(fd.as_raw_fd(), request, buf.as_mut_ptr()) }; - if ret < 0 { - let err = std::io::Error::last_os_error(); - if err.raw_os_error() == Some(libc::ERANGE) { - let hdr = unsafe { &*(buf.as_ptr() as *const H) }; - capacity = hdr.total(); + match unsafe { ioctl_ptr::(fd, buf.as_mut_ptr()) } { + Ok(_) => {} + Err(e) if e.raw_os_error() == Some(libc::ERANGE) => { + capacity = buf.hdr().total(); continue; } - return Err(err.into()); + Err(e) => return Err(e.into()), } - let hdr = unsafe { *(buf.as_ptr() as *const H) }; - let nr = hdr.nr() as usize; - let nodes = (0..nr).map(|i| unsafe { - std::ptr::read_unaligned( - buf.as_ptr().add(hdr_size + i * node_size) as *const H::Node) - }).collect(); - - return Ok((hdr, nodes)); + let nr = (buf.hdr().nr() as usize).min(capacity as usize); + let nodes = unsafe { buf.hdr().nodes(nr) }.to_vec(); + return Ok((unsafe { std::ptr::read(buf.hdr()) }, nodes)); } } -#[repr(C)] -struct BchIoctlSubvolToPath { - subvolid: u32, - buf_size: u32, - buf: u64, -} - -#[repr(C)] -#[derive(Copy, Clone, Default)] -struct BchIoctlSnapshotTreeQuery { - tree_id: u32, - master_subvol: u32, - root_snapshot: u32, - nr: u32, - total: u32, - pad: u32, -} - -impl FlexArrayIoctl for BchIoctlSnapshotTreeQuery { +impl FlexArrayIoctl for bch_ioctl_snapshot_tree_query { type Node = bch_ioctl_snapshot_node; - const NR: u32 = BCH_IOCTL_SNAPSHOT_TREE_USAGE; + type Ioc = BCH_IOCTL_SNAPSHOT_TREE; fn set_capacity(&mut self, n: u32) { self.nr = n; } fn nr(&self) -> u32 { self.nr } fn total(&self) -> u32 { self.total } + unsafe fn nodes(&self, nr: usize) -> &[Self::Node] { self.nodes.as_slice(nr) } } -fn open_dir(path: &Path) -> Result { - use std::os::unix::fs::OpenOptionsExt; - let f = std::fs::OpenOptions::new() - .read(true) - .custom_flags(libc::O_DIRECTORY) - .open(path) - .with_context(|| format!("Failed to open {}", path.display()))?; - Ok(f.into()) +impl FlexArrayIoctl for bch_ioctl_snapshot_tree_query_v2 { + type Node = bch_ioctl_snapshot_node_v2; + type Ioc = BCH_IOCTL_SNAPSHOT_TREE_v2; + fn set_capacity(&mut self, n: u32) { self.nr = n; } + fn nr(&self) -> u32 { self.nr } + fn total(&self) -> u32 { self.total } + unsafe fn nodes(&self, nr: usize) -> &[Self::Node] { self.nodes.as_slice(nr) } } fn subvol_readdir(fd: &OwnedFd, pos: &mut u32) -> Result> { @@ -279,7 +241,7 @@ fn subvol_readdir(fd: &OwnedFd, pos: &mut u32) -> Result> { pad: 0, }; - bcachefs_ioctl(fd, BCH_IOCTL_SUBVOLUME_LIST, &mut arg) + ioctl_rw::(fd, &mut arg) .context("BCH_IOCTL_SUBVOLUME_LIST")?; *pos = arg.pos; @@ -325,13 +287,13 @@ fn list_children(fd: &OwnedFd) -> Result> { fn subvol_to_path(fd: &OwnedFd, subvolid: u32) -> Result { let mut buf = vec![0u8; 4096]; - let mut arg = BchIoctlSubvolToPath { + let mut arg = bch_ioctl_subvol_to_path { subvolid, buf_size: buf.len() as u32, buf: buf.as_mut_ptr() as u64, }; - bcachefs_ioctl(fd, BCH_IOCTL_SUBVOLUME_TO_PATH, &mut arg) + ioctl_rw::(fd, &mut arg) .context("BCH_IOCTL_SUBVOLUME_TO_PATH")?; let path = CStr::from_bytes_until_nul(&buf) @@ -346,16 +308,40 @@ fn resolve_subvol_path(fd: &OwnedFd, subvolid: u32) -> Option { } fn query_snapshot_tree(fd: &OwnedFd, tree_id: u32) -> Result { - let (hdr, nodes) = bcachefs_flex_ioctl(fd, BchIoctlSnapshotTreeQuery { + match bcachefs_flex_ioctl(fd, bch_ioctl_snapshot_tree_query_v2 { tree_id, + node_size: mem::size_of::() as u32, ..Default::default() - })?; - - Ok(SnapshotTreeResult { - master_subvol: hdr.master_subvol, - root_snapshot: hdr.root_snapshot, - nodes, - }) + }) { + Ok((hdr, nodes)) => Ok(SnapshotTreeResult { + master_subvol: hdr.master_subvol, + root_snapshot: hdr.root_snapshot, + nodes, + }), + /* Kernel predates v2: fall back, without the key counters */ + Err(e) if e.downcast_ref::() + .and_then(|e| e.raw_os_error()) == Some(libc::ENOTTY) => { + let (hdr, v1) = bcachefs_flex_ioctl(fd, bch_ioctl_snapshot_tree_query { + tree_id, + ..Default::default() + })?; + + Ok(SnapshotTreeResult { + master_subvol: hdr.master_subvol, + root_snapshot: hdr.root_snapshot, + nodes: v1.iter().map(|n| bch_ioctl_snapshot_node_v2 { + id: n.id, + parent: n.parent, + children: n.children, + subvol: n.subvol, + flags: n.flags, + sectors: n.sectors, + ..Default::default() + }).collect(), + }) + } + Err(e) => Err(e), + } } fn compute_subvol_sizes(tree: &SnapshotTreeResult) -> HashMap { diff --git a/src/commands/top.rs b/src/commands/top.rs index f069414d5a..cf1723d4c0 100644 --- a/src/commands/top.rs +++ b/src/commands/top.rs @@ -1,7 +1,6 @@ use std::collections::{HashMap, VecDeque}; use std::fs::{self, OpenOptions}; use std::io::{self, IsTerminal, Read, Write}; -use std::mem; use std::os::unix::fs::OpenOptionsExt; use std::path::{Path, PathBuf}; use std::process; @@ -23,36 +22,23 @@ use serde::Deserialize; use crate::commands::DeviceNameArgs; use crate::util::{fmt_bytes_human, fmt_num_human, run_tui}; use crate::wrappers::handle::BcachefsHandle; -use crate::wrappers::ioctl::bch_ioc_w; +use crate::wrappers::ioctl::{ioctl_ptr, IoctlBuf, BCH_IOCTL_QUERY_COUNTERS}; use crate::wrappers::sysfs::{DeviceNameMode, dev_display_name_from_sysfs, sysfs_path_from_fd}; -// ioctl constants - -const BCH_IOCTL_QUERY_COUNTERS_NR: u32 = 21; const BCH_IOCTL_QUERY_COUNTERS_MOUNT: u16 = 1 << 0; // ioctl query -fn read_counters(fd: i32, flags: u16, nr_stable: u16) -> Result> { - let hdr_size = mem::size_of::(); - let buf_size = hdr_size + (nr_stable as usize) * mem::size_of::(); - let mut buf = vec![0u8; buf_size]; - - unsafe { - let hdr = &mut *(buf.as_mut_ptr() as *mut bch_ioctl_query_counters); - hdr.nr = nr_stable; - hdr.flags = flags; - } +fn read_counters(fd: std::os::fd::BorrowedFd, flags: u16, nr_stable: u16) -> Result> { + let mut buf = IoctlBuf::::new::(nr_stable as usize); + let hdr = buf.hdr_mut(); + hdr.nr = nr_stable; + hdr.flags = flags; - let request = bch_ioc_w::(BCH_IOCTL_QUERY_COUNTERS_NR); - let ret = unsafe { libc::ioctl(fd, request, buf.as_mut_ptr()) }; - if ret < 0 { - return Err(std::io::Error::last_os_error().into()); - } + unsafe { ioctl_ptr::(fd, buf.as_mut_ptr())? }; - let actual_nr = unsafe { (*(buf.as_ptr() as *const bch_ioctl_query_counters)).nr } as usize; - let data = unsafe { buf.as_ptr().add(hdr_size) as *const u64 }; - Ok((0..actual_nr).map(|i| unsafe { std::ptr::read_unaligned(data.add(i)) }).collect()) + let nr = (buf.hdr().nr as usize).min(nr_stable as usize); + Ok(unsafe { buf.hdr().d.as_slice(nr) }.to_vec()) } // Per-device IO from sysfs (io_done is JSON: {"read": {...}, "write": {...}}, values in bytes) @@ -325,7 +311,7 @@ impl Page { } struct TopState { - ioctl_fd: i32, + handle: BcachefsHandle, nr_stable: u16, mount_vals: Vec, start_vals: Vec, @@ -345,11 +331,11 @@ struct TopState { impl TopState { fn new( - handle: &BcachefsHandle, + handle: BcachefsHandle, human_readable: bool, name_mode: DeviceNameMode, ) -> Result { - let ioctl_fd = handle.ioctl_fd_raw(); + let ioctl_fd = handle.ioctl_fd(); let nr_stable = COUNTERS.iter().map(|c| c.stable_id).max().unwrap_or(0) + 1; let mount_vals = read_counters(ioctl_fd, BCH_IOCTL_QUERY_COUNTERS_MOUNT, nr_stable)?; @@ -362,7 +348,7 @@ impl TopState { .unwrap_or_default(); Ok(TopState { - ioctl_fd, nr_stable, + handle, nr_stable, mount_vals, start_vals, prev_vals, prev_dev_io: HashMap::new(), human_readable, @@ -585,7 +571,7 @@ fn run_non_interactive( delay: u32, name_mode: DeviceNameMode, ) -> Result<()> { - let ioctl_fd = handle.ioctl_fd_raw(); + let ioctl_fd = handle.ioctl_fd(); let nr_stable = COUNTERS.iter().map(|c| c.stable_id).max().unwrap_or(0) + 1; let mount_vals = read_counters(ioctl_fd, BCH_IOCTL_QUERY_COUNTERS_MOUNT, nr_stable)?; let sysfs_path = sysfs_path_from_fd(handle.sysfs_fd())?; @@ -618,7 +604,7 @@ fn run_interactive( delay: u32, name_mode: DeviceNameMode, ) -> Result<()> { - let mut state = TopState::new(&handle, human_readable, name_mode)?; + let mut state = TopState::new(handle, human_readable, name_mode)?; state.interval_secs = delay.max(1); /* Sample once up front; prev == curr so the first frame shows zero rates. @@ -626,7 +612,7 @@ fn run_interactive( * advance the rate baseline) on the interval timeout, never on a keypress - * otherwise scrolling would resample with ~no elapsed time and zero the * rate column. */ - let mut curr = read_counters(state.ioctl_fd, 0, state.nr_stable)?; + let mut curr = read_counters(state.handle.ioctl_fd(), 0, state.nr_stable)?; state.prev_vals = curr.clone(); let mut dev_io = read_device_io(&state.sysfs_path, state.name_mode); state.prev_dev_io = dev_io.iter() @@ -730,7 +716,7 @@ fn run_interactive( state.prev_dev_io = dev_io.into_iter() .map(|d| (d.label, (d.read_bytes, d.write_bytes))) .collect(); - curr = read_counters(state.ioctl_fd, 0, state.nr_stable)?; + curr = read_counters(state.handle.ioctl_fd(), 0, state.nr_stable)?; dev_io = read_device_io(&state.sysfs_path, state.name_mode); } }) diff --git a/src/commands/unpoison.rs b/src/commands/unpoison.rs index dfcafabfdd..831b6d98bb 100644 --- a/src/commands/unpoison.rs +++ b/src/commands/unpoison.rs @@ -10,26 +10,13 @@ // (e.g. restored from backup) or if you accept the data as-is. use std::fs::OpenOptions; -use std::os::unix::io::AsRawFd; +use bch_bindgen::c; use clap::Parser; -const SECTOR_SIZE: u64 = 512; - -/// ioctl number: _IOW(0xbc, 68, struct bch_ioctl_unpoison) -const fn bchfs_ioc_unpoison() -> libc::Ioctl { - let size = std::mem::size_of::() as u32; - ((1u32 << 30) | (size << 16) | (0xbcu32 << 8) | 68) as libc::Ioctl -} +use crate::wrappers::ioctl::{ioctl_w, BCHFS_IOC_UNPOISON}; -#[repr(C)] -#[derive(Default)] -struct BchIoctlUnpoison { - offset: u64, - len: u64, - flags: u32, - pad: u32, -} +const SECTOR_SIZE: u64 = 512; #[derive(Parser, Debug)] #[command(name = "unpoison")] @@ -91,19 +78,14 @@ fn cmd_unpoison(cli: Cli) -> anyhow::Result<()> { .write(true) .open(&cli.file)?; - let arg = BchIoctlUnpoison { + let arg = c::bch_ioctl_unpoison { offset: cli.offset, len, flags: 0, pad: 0, }; - let ret = unsafe { - libc::ioctl(file.as_raw_fd(), bchfs_ioc_unpoison(), &arg as *const _) - }; - - if ret < 0 { - let errno = std::io::Error::last_os_error(); + if let Err(errno) = ioctl_w::(&file, &arg) { anyhow::bail!("ioctl failed: {}", errno); } diff --git a/src/commands/wait_devices.rs b/src/commands/wait_devices.rs index 3e4adff7c4..d224e379d6 100644 --- a/src/commands/wait_devices.rs +++ b/src/commands/wait_devices.rs @@ -107,8 +107,14 @@ impl WaitInitialized { return Ok(()); } let dev_idx = sb.dev_idx; - if u32::from(dev_idx) >= sb.number_of_devices() { - warn!("superblock with invalid dev_idx: {dev_idx} >= {}", sb.number_of_devices()); + // dev_idx indexes the member array, sb.nr_devices long; + // number_of_devices() counts only live members - smaller whenever a + // removed device left a tombstoned slot behind: + if u32::from(dev_idx) >= sb.nr_devices as u32 { + warn!( + "superblock with invalid dev_idx: {dev_idx} >= {}", + sb.nr_devices + ); return Ok(()); } diff --git a/src/copy_fs.rs b/src/copy_fs.rs index c25b0b9aad..db6b485b76 100644 --- a/src/copy_fs.rs +++ b/src/copy_fs.rs @@ -300,11 +300,18 @@ fn xattr_resolve_name(name: &[u8]) -> Option<(i32, &[u8])> { } fn copy_times(fs: &Fs, dst: &mut c::bch_inode_unpacked, src: &rustix::fs::Stat) { - let make_ts = |sec, nsec| c::timespec64 { tv_sec: sec, tv_nsec: nsec }; + let to_bch_time = |sec: i64, nsec: i64| { + let ts = c::timespec64 { + tv_sec: sec as _, + tv_nsec: nsec as _, + ..unsafe { std::mem::zeroed() } + }; + fs.timespec_to_time(ts) as u64 + }; - dst.bi_atime = fs.timespec_to_time(make_ts(src.st_atime, src.st_atime_nsec as _)) as u64; - dst.bi_mtime = fs.timespec_to_time(make_ts(src.st_mtime, src.st_mtime_nsec as _)) as u64; - dst.bi_ctime = fs.timespec_to_time(make_ts(src.st_ctime, src.st_ctime_nsec as _)) as u64; + dst.bi_atime = to_bch_time(src.st_atime as i64, src.st_atime_nsec as i64); + dst.bi_mtime = to_bch_time(src.st_mtime as i64, src.st_mtime_nsec as i64); + dst.bi_ctime = to_bch_time(src.st_ctime as i64, src.st_ctime_nsec as i64); } fn copy_xattrs( diff --git a/src/eytzinger_test.rs b/src/eytzinger_test.rs new file mode 100644 index 0000000000..378dc5946c --- /dev/null +++ b/src/eytzinger_test.rs @@ -0,0 +1,18 @@ +//! Rust `#[test]` wrapper for the eytzinger sort/search unit test. +//! +//! The assertions live in C (`c_src/eytzinger_test.c`) so they can reach the +//! macros and static-inlines directly - `eytzinger1_find` and the +//! `darray_eytzinger1_*` wrappers that `snapshot_id_dying()` uses aren't +//! visible through bindgen. This just invokes the C runner and reports the +//! failure count, so the whole thing runs under `cargo test` with no kernel. + +#[test] +fn eytzinger_sort_find() { + // SAFETY: rust_eytzinger_test() is self-contained - it allocates and frees + // its own memory and touches no global state. + let fails = unsafe { bch_bindgen::c::rust_eytzinger_test() }; + assert_eq!( + fails, 0, + "rust_eytzinger_test reported {fails} failed assertion(s); see stderr" + ); +} diff --git a/src/http.rs b/src/http.rs index 802c02c94b..cd1be91e89 100644 --- a/src/http.rs +++ b/src/http.rs @@ -81,19 +81,8 @@ extern "C" fn cleanup_socket() { static STARTED_FOR_PID: AtomicU32 = AtomicU32::new(0); static ATEXIT_REGISTERED: AtomicBool = AtomicBool::new(false); -static ATFORK_REGISTERED: AtomicBool = AtomicBool::new(false); static INIT_LOCK: Mutex<()> = Mutex::new(()); -/* - * pthread_atfork child handler: bind a fresh socket in the new child - * process. The parent's http thread doesn't survive fork (only the - * calling thread does), so the child needs its own server bound at - * /run/.../.sock. - */ -extern "C" fn child_after_fork() { - bch2_start_http_lazy(); -} - /* * Bind a unix socket and spawn a thread serving sysfs/debugfs over HTTP. * Idempotent within a process: only the first call per pid actually @@ -106,9 +95,17 @@ extern "C" fn child_after_fork() { * Fork handling: process-local Once doesn't work — a child of a process * that already started the server would skip startup and have no http * thread (the parent's thread doesn't survive fork). We track the pid - * the server started for, and a pthread_atfork child handler re-runs - * init in any forked child. Each child binds its own socket at - * /run/.../.sock. + * the server started for, so a forked child that wants a server calls + * this again and binds its own at /run/.../.sock. + * + * That call must be explicit. It used to happen from a pthread_atfork + * child handler, which is process-wide: it fired in the child of *any* + * fork, including the short-lived one Command::spawn makes to exec + * fusermount3. Allocating, binding a socket and creating threads between + * fork() and execve() is not allowed, and when pthread_create there + * returned EAGAIN the crate-wide panic = "abort" made it fatal, so the + * mount failed. It also leaked a socket per exec'ing child, since those + * never reach the atexit handler. * * Cleanup is via an atexit handler that unlinks the current pid's * socket on normal exit. Sockets from killed-by-signal / panicked @@ -135,16 +132,11 @@ pub extern "C" fn bch2_start_http_lazy() { match tiny_http::Server::http_unix(std::path::Path::new(&path)) { Ok(server) => { - // atexit / pthread_atfork registrations are inherited across - // fork; only register once per process to avoid duplicates. + // atexit registrations are inherited across fork; only register + // once per process to avoid duplicates. if !ATEXIT_REGISTERED.swap(true, Ordering::AcqRel) { unsafe { libc::atexit(cleanup_socket); } } - if !ATFORK_REGISTERED.swap(true, Ordering::AcqRel) { - unsafe { - libc::pthread_atfork(None, None, Some(child_after_fork)); - } - } STARTED_FOR_PID.store(my_pid, Ordering::Release); std::thread::spawn(move || http_thread(server)); } diff --git a/src/qcow2.rs b/src/qcow2.rs index 1808f78fa0..9ec9d47a9a 100644 --- a/src/qcow2.rs +++ b/src/qcow2.rs @@ -331,7 +331,7 @@ fn file_size_fd(fd: BorrowedFd<'_>) -> Result { let stat = fstat(fd)?; if FileType::from_raw_mode(stat.st_mode) == FileType::BlockDevice { - const BLKGETSIZE64: ioctl::Opcode = ioctl::opcode::read::(0x12, 114); + const BLKGETSIZE64: ioctl::Opcode = bch_bindgen::c::BCH_BLKGETSIZE64 as ioctl::Opcode; Ok(unsafe { rustix::ioctl::ioctl(fd, Getter::::new()) }?) } else { Ok(stat.st_size as u64) diff --git a/src/util.rs b/src/util.rs index 189d8579ab..cc228db931 100644 --- a/src/util.rs +++ b/src/util.rs @@ -1,10 +1,12 @@ -use std::ffi::CString; +use std::ffi::{CStr, CString}; use std::fs::File; use std::io; +use std::os::fd::OwnedFd; use std::os::raw::c_char; use std::os::unix::fs::FileTypeExt; +use std::path::Path; -use anyhow::{anyhow, bail, Result}; +use anyhow::{anyhow, bail, Context, Result}; use bch_bindgen::c; use crossterm::{cursor, execute, terminal}; use rustix::ioctl::{self, Getter}; @@ -46,6 +48,29 @@ impl Drop for AlignedBuf { } } +/// Open a directory fd for directory-scoped ioctls and *at() calls. +pub fn open_dir(path: &Path) -> Result { + use std::os::unix::fs::OpenOptionsExt; + let f = std::fs::OpenOptions::new() + .read(true) + .custom_flags(libc::O_DIRECTORY) + .open(path) + .with_context(|| format!("Failed to open {}", path.display()))?; + Ok(f.into()) +} + +/// The name of a bch_sb_error_id - the same table fsck and the +/// superblock error counters use. +pub fn sb_error_name(id: u32) -> String { + if id < c::bch_sb_error_id::BCH_FSCK_ERR_MAX as u32 { + unsafe { CStr::from_ptr(*c::bch2_sb_error_strs.as_ptr().add(id as usize)) } + .to_string_lossy() + .into_owned() + } else { + format!("(unknown error {id})") + } +} + /// Parse a human-readable size string (e.g. "1G", "512M") via bch2_strtoull_h. pub fn parse_human_size(s: &str) -> Result { let cstr = CString::new(s)?; @@ -103,8 +128,10 @@ pub fn fmt_num_human(n: u64) -> String { pub fn file_size(f: &File) -> Result { let meta = f.metadata()?; if meta.file_type().is_block_device() { - // BLKGETSIZE64 = _IOR(0x12, 114, size_t) - const BLKGETSIZE64: ioctl::Opcode = ioctl::opcode::read::(0x12, 114); + // _IOR(0x12, 114, size_t): the size encoded in the number is + // sizeof(size_t), not of the u64 we read into - they differ on 32 + // bit, so take the number bindgen computed for the target. + const BLKGETSIZE64: ioctl::Opcode = bch_bindgen::c::BCH_BLKGETSIZE64 as ioctl::Opcode; Ok(unsafe { ioctl::ioctl(f, Getter::::new()) }?) } else { Ok(meta.len()) diff --git a/src/wrappers/accounting.rs b/src/wrappers/accounting.rs index d814da0dcb..ecf7b17838 100644 --- a/src/wrappers/accounting.rs +++ b/src/wrappers/accounting.rs @@ -2,7 +2,7 @@ use bch_bindgen::c; use bcachefs_kernel::metadata_version; use super::handle::BcachefsHandle; -use super::ioctl::bch_ioc_w; +use super::ioctl::{ioctl_ptr, IoctlBuf, BCH_IOCTL_QUERY_ACCOUNTING}; use super::sysfs::bcachefs_kernel_version; // Re-export types and functions from bcachefs_kernel::accounting for consumers @@ -17,61 +17,39 @@ pub struct AccountingResult { pub entries: Vec, } -/// Header of bch_ioctl_query_accounting (fixed part before flex array). -#[repr(C)] -struct QueryAccountingHeader { - capacity: u64, - used: u64, - online_reserved: u64, - accounting_u64s: u32, - accounting_types_mask: u32, -} - impl BcachefsHandle { /// Query filesystem accounting data via BCH_IOCTL_QUERY_ACCOUNTING. /// Returns None on ENOTTY (old kernel without this ioctl). pub fn query_accounting(&self, type_mask: u32) -> Result { - let hdr_size = std::mem::size_of::(); let mut accounting_u64s: u32 = 128; loop { - let total_bytes = hdr_size + (accounting_u64s as usize) * 8; - let mut buf = vec![0u8; total_bytes]; - - // Fill header - let hdr = unsafe { &mut *(buf.as_mut_ptr() as *mut QueryAccountingHeader) }; + let mut buf = IoctlBuf::::new::(accounting_u64s as usize); + let hdr = buf.hdr_mut(); hdr.accounting_u64s = accounting_u64s; hdr.accounting_types_mask = type_mask; - // BCH_IOCTL_QUERY_ACCOUNTING is _IOW(0xbc, 21, struct bch_ioctl_query_accounting) - // The struct has a flex array, so the kernel uses the header size for the ioctl nr. - // We use bch_ioc_w with the header size. - let request = bch_ioc_w::(21); - let ret = unsafe { libc::ioctl(self.ioctl_fd_raw(), request, buf.as_mut_ptr()) }; - - if ret == 0 { - let hdr = unsafe { &*(buf.as_ptr() as *const QueryAccountingHeader) }; - let entries = parse_accounting_entries( - &buf[hdr_size..hdr_size + (hdr.accounting_u64s as usize) * 8], - ); - - return Ok(AccountingResult { - capacity: hdr.capacity, - used: hdr.used, - online_reserved: hdr.online_reserved, - entries, - }); - } - - let errno = std::io::Error::last_os_error().raw_os_error().unwrap_or(0); - if errno == libc::ENOTTY { - return Err(errno::Errno(libc::ENOTTY)); - } - if errno == libc::ERANGE { - accounting_u64s *= 2; - continue; + let ret = unsafe { + ioctl_ptr::(&self.ioctl_fd(), buf.as_mut_ptr()) + }; + + match ret { + Ok(_) => { + let hdr = buf.hdr(); + /* trailing records are variable-size bkey_i_accounting, parsed from bytes */ + let entries = parse_accounting_entries( + buf.trailing_bytes(hdr.accounting_u64s as usize * 8)); + + return Ok(AccountingResult { + capacity: hdr.capacity, + used: hdr.used, + online_reserved: hdr.online_reserved, + entries, + }); + } + Err(e) if e.raw_os_error() == Some(libc::ERANGE) => accounting_u64s *= 2, + Err(e) => return Err(errno::Errno(e.raw_os_error().unwrap_or(libc::EIO))), } - return Err(errno::Errno(errno)); } } } diff --git a/src/wrappers/bdev.rs b/src/wrappers/bdev.rs index 6f88609f1e..5824f7e58e 100644 --- a/src/wrappers/bdev.rs +++ b/src/wrappers/bdev.rs @@ -11,32 +11,12 @@ use std::os::unix::fs::{FileTypeExt, MetadataExt}; use std::os::unix::io::RawFd; use std::path::PathBuf; -use libc::BLKPBSZGET; - -// linux/fs.h ioctl constants not exposed by libc crate. Note that some -// architectures use a 3-bit ioctl direction field. -#[cfg(any( - target_arch = "powerpc", - target_arch = "powerpc64", - target_arch = "mips", - target_arch = "mips32r6", - target_arch = "mips64", - target_arch = "mips64r6", - target_arch = "sparc", - target_arch = "sparc64", -))] -const BLKGETSIZE64: libc::Ioctl = 0x40081272u32 as libc::Ioctl; -#[cfg(not(any( - target_arch = "powerpc", - target_arch = "powerpc64", - target_arch = "mips", - target_arch = "mips32r6", - target_arch = "mips64", - target_arch = "mips64r6", - target_arch = "sparc", - target_arch = "sparc64", -)))] -const BLKGETSIZE64: libc::Ioctl = 0x80081272u32 as libc::Ioctl; +// The block ioctl numbers encode sizeof() of the argument type and the +// direction bits differ between architectures, so they can't be written down +// here: the C compiler evaluates them from linux/fs.h for the target and +// exports them as constants. See c_src/rust_shims.h. +const BLKGETSIZE64: libc::Ioctl = bch_bindgen::c::BCH_BLKGETSIZE64 as libc::Ioctl; +const BLKPBSZGET: libc::Ioctl = bch_bindgen::c::BCH_BLKPBSZGET as libc::Ioctl; /// Returns the size of a file or block device in bytes. /// @@ -149,11 +129,10 @@ pub fn fd_to_parent_disk_sysfs(fd: RawFd) -> Option { /// /// For regular files (image files) the ioctl fails and we default to false. pub fn nonrot(fd: RawFd) -> bool { - // BLKROTATIONAL = _IO(0x12, 126). Kernel returns !bdev_nonrot(bdev) via - // put_ushort — bdev_nonrot internally uses bdev_get_queue(bdev), which - // resolves to the parent disk's queue for partitions and handles LVM, - // md, loop devices, etc. uniformly. - const BLKROTATIONAL: libc::Ioctl = 0x127E as libc::Ioctl; + // Kernel returns !bdev_nonrot(bdev) via put_ushort — bdev_nonrot internally + // uses bdev_get_queue(bdev), which resolves to the parent disk's queue for + // partitions and handles LVM, md, loop devices, etc. uniformly. + const BLKROTATIONAL: libc::Ioctl = bch_bindgen::c::BCH_BLKROTATIONAL as libc::Ioctl; let mut rotational: u16 = 0; let ret = unsafe { libc::ioctl(fd, BLKROTATIONAL, &mut rotational) }; ret == 0 && rotational == 0 diff --git a/src/wrappers/handle.rs b/src/wrappers/handle.rs index ccad392b7b..c65448ce60 100644 --- a/src/wrappers/handle.rs +++ b/src/wrappers/handle.rs @@ -1,5 +1,4 @@ use std::ffi::CStr; -use std::io; use std::mem; use std::os::fd::{AsFd, AsRawFd, BorrowedFd, OwnedFd}; use std::path::Path; @@ -12,17 +11,20 @@ use bch_bindgen::c::{ bch_ioctl_disk_resize, bch_ioctl_disk_resize_v2, bch_ioctl_disk_resize_journal, bch_ioctl_disk_resize_journal_v2, bch_ioctl_subvolume, bch_ioctl_subvolume_v2, - bch_ioctl_query_btree_keys, + bch_ioctl_query_btree_keys, bch_ioctl_query_uuid, bch_ioctl_read_super, BCH_BY_INDEX, BCH_SUBVOL_SNAPSHOT_CREATE, }; use bch_bindgen::accounting::data_type; -use crate::wrappers::ioctl::{bch_ioc_w, bch_ioc_wr}; +use crate::wrappers::ioctl::*; use crate::wrappers::sysfs; use bch_bindgen::c::bch_sb; use bcachefs_kernel::errcode::BchError; use bcachefs_kernel::path_to_cstr; use errno::Errno; -use rustix::ioctl::{self, Setter}; + +fn io_errno(e: std::io::Error) -> Errno { + Errno(e.raw_os_error().unwrap_or(libc::EIO)) +} /// Try a v2 ioctl (with error message buffer), falling back to v1 on ENOTTY. macro_rules! v2_v1_ioctl { @@ -32,62 +34,22 @@ macro_rules! v2_v1_ioctl { arg.err.msg_ptr = err_buf.as_mut_ptr() as u64; arg.err.msg_len = err_buf.len() as u32; - match unsafe { ioctl::ioctl($fd, Setter::<$V2, _>::new(arg)) } { - Ok(()) => Ok(()), - Err(e) if e == rustix::io::Errno::NOTTY => { - unsafe { ioctl::ioctl($fd, Setter::<$V1, _>::new($v1_arg)) } - .map_err(|e| Errno(e.raw_os_error())) - } + match ioctl_w::<$V2>($fd, &arg) { + Ok(_) => Ok(()), + Err(e) if e.raw_os_error() == Some(libc::ENOTTY) => + ioctl_w::<$V1>($fd, &$v1_arg).map(|_| ()).map_err(io_errno), Err(e) => { print_errmsg(&err_buf); - Err(Errno(e.raw_os_error())) + Err(io_errno(e)) } } }}; } -// Subvolume ioctl opcodes -const SUBVOL_CREATE_OPCODE: ioctl::Opcode = ioctl::opcode::write::(0xbc, 16); -const SUBVOL_CREATE_V2_OPCODE: ioctl::Opcode = ioctl::opcode::write::(0xbc, 29); -const SUBVOL_DESTROY_OPCODE: ioctl::Opcode = ioctl::opcode::write::(0xbc, 17); -const SUBVOL_DESTROY_V2_OPCODE: ioctl::Opcode = ioctl::opcode::write::(0xbc, 30); - -// Disk ioctl opcodes (_IOW(0xbc, N, struct)) -const DISK_ADD_OPCODE: ioctl::Opcode = ioctl::opcode::write::(0xbc, 4); -const DISK_ADD_V2_OPCODE: ioctl::Opcode = ioctl::opcode::write::(0xbc, 23); -const DISK_REMOVE_OPCODE: ioctl::Opcode = ioctl::opcode::write::(0xbc, 5); -const DISK_REMOVE_V2_OPCODE: ioctl::Opcode = ioctl::opcode::write::(0xbc, 24); -const DISK_ONLINE_OPCODE: ioctl::Opcode = ioctl::opcode::write::(0xbc, 6); -const DISK_ONLINE_V2_OPCODE: ioctl::Opcode = ioctl::opcode::write::(0xbc, 25); -const DISK_OFFLINE_OPCODE: ioctl::Opcode = ioctl::opcode::write::(0xbc, 7); -const DISK_OFFLINE_V2_OPCODE: ioctl::Opcode = ioctl::opcode::write::(0xbc, 26); -const DISK_SET_STATE_OPCODE: ioctl::Opcode = ioctl::opcode::write::(0xbc, 8); -const DISK_SET_STATE_V2_OPCODE: ioctl::Opcode = ioctl::opcode::write::(0xbc, 22); -const DISK_RESIZE_OPCODE: ioctl::Opcode = ioctl::opcode::write::(0xbc, 14); -const DISK_RESIZE_V2_OPCODE: ioctl::Opcode = ioctl::opcode::write::(0xbc, 27); -const DISK_RESIZE_JOURNAL_OPCODE: ioctl::Opcode = ioctl::opcode::write::(0xbc, 15); -const DISK_RESIZE_JOURNAL_V2_OPCODE: ioctl::Opcode = - ioctl::opcode::write::(0xbc, 28); - const SYSFS_BASE: &str = "/sys/fs/bcachefs/"; -/// BCH_IOCTL_QUERY_UUID: _IOR(0xbc, 1, struct bch_ioctl_query_uuid) -/// Returns the user-visible filesystem UUID. -#[repr(C)] -#[derive(Default)] -struct BchIoctlQueryUuid { - uuid: [u8; 16], -} - -/// Compute _IOR(type, nr, size) -const fn ioc_r(type_: u32, nr: u32, size: u32) -> libc::Ioctl { - ((2u32 << 30) | (size << 16) | (type_ << 8) | nr) as libc::Ioctl -} - -const BCH_IOCTL_QUERY_UUID: libc::Ioctl = - ioc_r(0xbc, 1, mem::size_of::() as u32); - -/// FS_IOC_GETFSSYSFSPATH: _IOR(0x15, 1, struct fs_sysfs_path) +/// FS_IOC_GETFSSYSFSPATH: _IOR(0x15, 1, struct fs_sysfs_path) — generic +/// VFS ioctl (linux/fs.h), not in our generated inventory. #[repr(C)] struct FsSysfsPath { len: u8, @@ -95,7 +57,7 @@ struct FsSysfsPath { } const FS_IOC_GETFSSYSFSPATH: libc::Ioctl = - ioc_r(0x15, 1, mem::size_of::() as u32); + ((2u32 << 30) | ((mem::size_of::() as u32) << 16) | (0x15 << 8) | 1) as libc::Ioctl; /// A handle to a bcachefs filesystem, with RAII close. pub(crate) struct BcachefsHandle { @@ -110,10 +72,6 @@ impl BcachefsHandle { self.sysfs_fd.as_fd() } - pub(crate) fn ioctl_fd_raw(&self) -> i32 { - self.ioctl_fd.as_raw_fd() - } - /// Device index when opened via a block device path; -1 when opened via mount point. pub(crate) fn dev_idx(&self) -> i32 { self.dev_idx @@ -194,12 +152,9 @@ impl BcachefsHandle { } // Try BCH_IOCTL_QUERY_UUID — if it succeeds, it's a mounted fs path - let mut query_uuid = BchIoctlQueryUuid::default(); - let ret = unsafe { - libc::ioctl(path_fd.as_raw_fd(), BCH_IOCTL_QUERY_UUID, &mut query_uuid) - }; - if ret == 0 { - return Self::open_mounted_path(path_fd, query_uuid.uuid).map(Some); + let mut query_uuid = bch_ioctl_query_uuid::default(); + if ioctl_rw::(&path_fd, &mut query_uuid).is_ok() { + return Self::open_mounted_path(path_fd, query_uuid.uuid.b).map(Some); } // Drop path_fd — we'll re-open via sysfs/ctl @@ -360,18 +315,22 @@ impl BcachefsHandle { Ok(handle) } - fn ioctl_fd(&self) -> BorrowedFd<'_> { + pub(crate) fn ioctl_fd(&self) -> BorrowedFd<'_> { self.ioctl_fd.as_fd() } - fn subvol_ioctl( + fn subvol_ioctl( &self, flags: u32, dirfd: u32, mode: u16, dst_ptr: u64, src_ptr: u64, - ) -> Result<(), Errno> { + ) -> Result<(), Errno> + where + V2: Ioctl, + V1: Ioctl, + { v2_v1_ioctl!( self.ioctl_fd(), V2, V1, bch_ioctl_subvolume_v2 { flags, dirfd, mode, dst_ptr, src_ptr, ..Default::default() }, @@ -383,7 +342,7 @@ impl BcachefsHandle { /// at the given path pub fn create_subvolume>(&self, dst: P) -> Result<(), Errno> { let dst = path_to_cstr(dst); - self.subvol_ioctl::( + self.subvol_ioctl::( 0, libc::AT_FDCWD as u32, 0o777, @@ -396,7 +355,7 @@ impl BcachefsHandle { /// for this bcachefs filesystem pub fn delete_subvolume>(&self, dst: P) -> Result<(), Errno> { let dst = path_to_cstr(dst); - self.subvol_ioctl::( + self.subvol_ioctl::( 0, libc::AT_FDCWD as u32, 0o777, @@ -415,7 +374,7 @@ impl BcachefsHandle { ) -> Result<(), Errno> { let src = src.map(|src| path_to_cstr(src)); let dst = path_to_cstr(dst); - self.subvol_ioctl::( + self.subvol_ioctl::( BCH_SUBVOL_SNAPSHOT_CREATE | extra_flags, libc::AT_FDCWD as u32, 0o777, @@ -424,9 +383,11 @@ impl BcachefsHandle { ) } - fn disk_ioctl( - &self, flags: u32, dev: u64, - ) -> Result<(), Errno> { + fn disk_ioctl(&self, flags: u32, dev: u64) -> Result<(), Errno> + where + V2: Ioctl, + V1: Ioctl, + { v2_v1_ioctl!( self.ioctl_fd(), V2, V1, bch_ioctl_disk_v2 { flags, dev, ..Default::default() }, @@ -436,28 +397,28 @@ impl BcachefsHandle { /// Add a new device to this filesystem. pub(crate) fn disk_add(&self, dev_path: &CStr) -> Result<(), Errno> { - self.disk_ioctl::( + self.disk_ioctl::( 0, dev_path.as_ptr() as u64, ) } /// Remove a device (by index) from this filesystem. pub(crate) fn disk_remove(&self, dev_idx: u32, flags: u32) -> Result<(), Errno> { - self.disk_ioctl::( + self.disk_ioctl::( flags | BCH_BY_INDEX, dev_idx as u64, ) } /// Re-add an offline device to this filesystem. pub(crate) fn disk_online(&self, dev_path: &CStr) -> Result<(), Errno> { - self.disk_ioctl::( + self.disk_ioctl::( 0, dev_path.as_ptr() as u64, ) } /// Take a device offline without removing it. pub(crate) fn disk_offline(&self, dev_idx: u32, flags: u32) -> Result<(), Errno> { - self.disk_ioctl::( + self.disk_ioctl::( flags | BCH_BY_INDEX, dev_idx as u64, ) } @@ -465,7 +426,7 @@ impl BcachefsHandle { /// Change device state (rw, ro, evacuating, spare). pub(crate) fn disk_set_state(&self, dev_idx: u32, new_state: u32, flags: u32) -> Result<(), Errno> { v2_v1_ioctl!( - self.ioctl_fd(), DISK_SET_STATE_V2_OPCODE, DISK_SET_STATE_OPCODE, + self.ioctl_fd(), BCH_IOCTL_DISK_SET_STATE_v2, BCH_IOCTL_DISK_SET_STATE, bch_ioctl_disk_set_state_v2 { flags: flags | BCH_BY_INDEX, new_state: new_state as u8, dev: dev_idx as u64, ..Default::default() }, bch_ioctl_disk_set_state { flags: flags | BCH_BY_INDEX, new_state: new_state as u8, dev: dev_idx as u64, ..Default::default() } ) @@ -474,7 +435,7 @@ impl BcachefsHandle { /// Resize filesystem on a device. pub(crate) fn disk_resize(&self, dev_idx: u32, nbuckets: u64) -> Result<(), Errno> { v2_v1_ioctl!( - self.ioctl_fd(), DISK_RESIZE_V2_OPCODE, DISK_RESIZE_OPCODE, + self.ioctl_fd(), BCH_IOCTL_DISK_RESIZE_v2, BCH_IOCTL_DISK_RESIZE, bch_ioctl_disk_resize_v2 { flags: BCH_BY_INDEX, dev: dev_idx as u64, nbuckets, ..Default::default() }, bch_ioctl_disk_resize { flags: BCH_BY_INDEX, dev: dev_idx as u64, nbuckets, ..Default::default() } ) @@ -483,7 +444,7 @@ impl BcachefsHandle { /// Resize journal on a device. pub(crate) fn disk_resize_journal(&self, dev_idx: u32, nbuckets: u64) -> Result<(), Errno> { v2_v1_ioctl!( - self.ioctl_fd(), DISK_RESIZE_JOURNAL_V2_OPCODE, DISK_RESIZE_JOURNAL_OPCODE, + self.ioctl_fd(), BCH_IOCTL_DISK_RESIZE_JOURNAL_v2, BCH_IOCTL_DISK_RESIZE_JOURNAL, bch_ioctl_disk_resize_journal_v2 { flags: BCH_BY_INDEX, dev: dev_idx as u64, nbuckets, ..Default::default() }, bch_ioctl_disk_resize_journal { flags: BCH_BY_INDEX, dev: dev_idx as u64, nbuckets, ..Default::default() } ) @@ -500,36 +461,18 @@ impl BcachefsHandle { loop { let mut buf = vec![0u8; size]; - #[repr(C)] - struct BchIoctlReadSuper { - flags: u32, - pad: u32, - dev: u64, - size: u64, - sb: u64, - } - - let arg = BchIoctlReadSuper { - flags: 0, - pad: 0, - dev: 0, - size: size as u64, - sb: buf.as_mut_ptr() as u64, + let arg = bch_ioctl_read_super { + size: size as u64, + sb: buf.as_mut_ptr() as u64, + ..Default::default() }; - let request = bch_ioc_w::(12); - let ret = unsafe { libc::ioctl(self.ioctl_fd_raw(), request, &arg) }; - - if ret == 0 { - return Ok(buf); - } - - let err = io::Error::last_os_error().raw_os_error().unwrap_or(libc::EIO); - if err == libc::ERANGE && size < 1 << 20 { - size *= 4; - continue; + match ioctl_w::(self.ioctl_fd(), &arg) { + Ok(_) => return Ok(buf), + Err(e) if e.raw_os_error() == Some(libc::ERANGE) && size < 1 << 20 => + size *= 4, + Err(e) => return Err(io_errno(e)), } - return Err(Errno(err)); } } @@ -539,13 +482,8 @@ impl BcachefsHandle { /// `arg.done` is set. Returns ERANGE if `arg.buf_size` can't hold even /// a single key. pub(crate) fn query_btree_keys(&self, arg: &mut bch_ioctl_query_btree_keys) -> Result<(), Errno> { - let request = bch_ioc_wr::(34); - let ret = unsafe { libc::ioctl(self.ioctl_fd_raw(), request, arg as *mut _) }; - if ret == 0 { - Ok(()) - } else { - Err(Errno(io::Error::last_os_error().raw_os_error().unwrap_or(libc::EIO))) - } + ioctl_rw::(self.ioctl_fd(), arg) + .map(|_| ()).map_err(io_errno) } /// Read the on-disk metadata version from the filesystem superblock. @@ -561,44 +499,34 @@ impl BcachefsHandle { /// Query device usage (v2 with flex array, v1 fallback). pub(crate) fn dev_usage(&self, dev_idx: u32) -> Result { let nr_data_types = data_type::nr.0 as usize; - let entry_size = mem::size_of::(); - let hdr_size = mem::size_of::(); - let buf_size = hdr_size + nr_data_types * entry_size; - let mut buf = vec![0u8; buf_size]; - // Fill header - let hdr = unsafe { &mut *(buf.as_mut_ptr() as *mut bch_ioctl_dev_usage_v2) }; + let mut buf = IoctlBuf::::new::(nr_data_types); + let hdr = buf.hdr_mut(); hdr.dev = dev_idx as u64; hdr.flags = BCH_BY_INDEX; hdr.nr_data_types = nr_data_types as u8; - let request = bch_ioc_wr::(18); - let ret = unsafe { libc::ioctl(self.ioctl_fd_raw(), request, buf.as_mut_ptr()) }; - - if ret == 0 { - // v2 succeeded — parse result - let hdr = unsafe { &*(buf.as_ptr() as *const bch_ioctl_dev_usage_v2) }; - let actual_nr = hdr.nr_data_types as usize; - let data_ptr = unsafe { buf.as_ptr().add(hdr_size) } - as *const bch_ioctl_dev_usage_bch_ioctl_dev_usage_type; + let ret = unsafe { + ioctl_ptr::(self.ioctl_fd(), buf.as_mut_ptr()) + }; - let mut data_types = Vec::with_capacity(actual_nr); - for i in 0..actual_nr { - let d = unsafe { std::ptr::read_unaligned(data_ptr.add(i)) }; - data_types.push(DevUsageType { buckets: d.buckets, sectors: d.sectors, fragmented: d.fragmented }); - } + if ret.is_ok() { + let hdr = buf.hdr(); + let nr = (hdr.nr_data_types as usize).min(nr_data_types); return Ok(DevUsage { state: hdr.state, bucket_size: hdr.bucket_size, nr_buckets: hdr.nr_buckets, - data_types, + data_types: unsafe { hdr.d.as_slice(nr) }.iter() + .map(|d| DevUsageType { buckets: d.buckets, sectors: d.sectors, fragmented: d.fragmented }) + .collect(), }); } - let errno = io::Error::last_os_error().raw_os_error().unwrap_or(0); - if errno != libc::ENOTTY { - return Err(Errno(errno)); + let err = ret.unwrap_err(); + if err.raw_os_error() != Some(libc::ENOTTY) { + return Err(io_errno(err)); } // v1 fallback @@ -607,11 +535,7 @@ impl BcachefsHandle { flags: BCH_BY_INDEX, ..Default::default() }; - let request_v1 = bch_ioc_wr::(11); - let ret = unsafe { libc::ioctl(self.ioctl_fd_raw(), request_v1, &mut u_v1 as *mut _) }; - if ret < 0 { - return Err(Errno(io::Error::last_os_error().raw_os_error().unwrap_or(0))); - } + ioctl_rw::(self.ioctl_fd(), &mut u_v1).map_err(io_errno)?; let mut data_types = Vec::new(); for d in &u_v1.d { diff --git a/src/wrappers/ioctl.rs b/src/wrappers/ioctl.rs index 078a9d6ffa..582c4e8563 100644 --- a/src/wrappers/ioctl.rs +++ b/src/wrappers/ioctl.rs @@ -1,14 +1,103 @@ -use std::mem; +//! Typed ioctl calls over the generated inventory. +//! +//! `bcachefs_kernel::ioctl` (re-exported here) carries one marker type per +//! `_IO*()` define in bcachefs_ioctl.h, binding the opcode to its argument +//! type — the opcode's size bits are computed from the very type these +//! call shapes make you pass, so a call site can't pair the wrong two. +//! This module adds the calls themselves: direction-checked argument +//! passing and one errno-to-io::Error conversion for the whole tree. +//! +//! Positive return values pass through — several bcachefs ioctls return +//! fds (BCH_IOCTL_DATA, BCH_IOCTL_FSCK_*) or counts. -/// Compute a bcachefs _IOW ioctl number. +use std::io; +use std::os::fd::{AsFd, AsRawFd}; + +pub use bcachefs_kernel::ioctl::*; + +fn ret(r: libc::c_int) -> io::Result { + if r < 0 { + Err(io::Error::last_os_error()) + } else { + Ok(r) + } +} + +/// _IO: no argument. +pub fn ioctl_none>(fd: impl AsFd) -> io::Result { + ret(unsafe { libc::ioctl(fd.as_fd().as_raw_fd(), I::OPCODE as libc::Ioctl) }) +} + +/// _IOW: the kernel only reads the argument. +pub fn ioctl_w(fd: impl AsFd, arg: &I::Arg) -> io::Result { + const { assert!(I::DIR == 1, "not an _IOW ioctl") }; + ret(unsafe { + libc::ioctl(fd.as_fd().as_raw_fd(), I::OPCODE as libc::Ioctl, arg as *const I::Arg) + }) +} + +/// _IOR/_IOWR: the kernel writes (or updates) the argument. +pub fn ioctl_rw(fd: impl AsFd, arg: &mut I::Arg) -> io::Result { + const { assert!(I::DIR & 2 != 0, "not an _IOR/_IOWR ioctl") }; + ret(unsafe { + libc::ioctl(fd.as_fd().as_raw_fd(), I::OPCODE as libc::Ioctl, arg as *mut I::Arg) + }) +} + +/// Argument in a caller-managed allocation — for the ioctls whose argument +/// struct ends in a flexible array member: the caller allocates header + +/// entries and passes a pointer to the header. The opcode's size bits only +/// cover the header (sizeof a FAM struct), matching the C definition. +/// +/// # Safety +/// `arg` must point to a live, writable allocation laid out as the kernel +/// expects for `I`: at least `I::Arg`, plus whatever trailing entries its +/// header fields promise. +pub unsafe fn ioctl_ptr(fd: impl AsFd, arg: *mut I::Arg) -> io::Result { + ret(libc::ioctl(fd.as_fd().as_raw_fd(), I::OPCODE as libc::Ioctl, arg)) +} + +/// Owned, zeroed allocation for a flexible-array-member ioctl argument: +/// header `H` followed by trailing entries. The header is read and +/// written through the real struct, and trailing entries through its +/// `__IncompleteArrayField` accessors - the one place that knows the +/// layout is the C definition. /// -/// Equivalent to `_IOW(0xbc, nr, T)` — write direction, bcachefs magic, -/// size encoded from the type parameter. -pub const fn bch_ioc_w(nr: u32) -> libc::Ioctl { - ((1u32 << 30) | ((mem::size_of::() as u32) << 16) | (0xbcu32 << 8) | nr) as libc::Ioctl +/// `H` must be a plain-old-data bindgen ioctl struct (zero-initialized +/// is valid, align <= 8 - asserted at compile time). +pub struct IoctlBuf { + buf: Vec, + _arg: std::marker::PhantomData, } -/// Compute a bcachefs _IOWR ioctl number. -pub const fn bch_ioc_wr(nr: u32) -> libc::Ioctl { - ((3u32 << 30) | ((mem::size_of::() as u32) << 16) | (0xbcu32 << 8) | nr) as libc::Ioctl +impl IoctlBuf { + /// Room for the header plus `nr` trailing elements of `T`. + pub fn new(nr: usize) -> Self { + const { assert!(std::mem::align_of::() <= 8) }; + let bytes = std::mem::size_of::() + nr * std::mem::size_of::(); + IoctlBuf { buf: vec![0u64; bytes.div_ceil(8)], _arg: std::marker::PhantomData } + } + + pub fn hdr(&self) -> &H { + unsafe { &*(self.buf.as_ptr() as *const H) } + } + + pub fn hdr_mut(&mut self) -> &mut H { + unsafe { &mut *(self.buf.as_mut_ptr() as *mut H) } + } + + pub fn as_mut_ptr(&mut self) -> *mut H { + self.buf.as_mut_ptr() as *mut H + } + + /// The trailing region as raw bytes, for arguments whose trailing + /// records are variable-size. Panics if `bytes` overruns the + /// allocation (a kernel echoing back more than it was given). + pub fn trailing_bytes(&self, bytes: usize) -> &[u8] { + let off = std::mem::size_of::(); + assert!(off + bytes <= self.buf.len() * 8); + unsafe { + std::slice::from_raw_parts((self.buf.as_ptr() as *const u8).add(off), bytes) + } + } } diff --git a/src/wrappers/online_iter.rs b/src/wrappers/online_iter.rs index eb26ff49a8..ed679867e4 100644 --- a/src/wrappers/online_iter.rs +++ b/src/wrappers/online_iter.rs @@ -28,6 +28,8 @@ impl OnlineIterFlags { pub const SLOTS: Self = Self(c::BCH_IOCTL_QUERY_BTREE_KEYS_slots); pub const PREV: Self = Self(c::BCH_IOCTL_QUERY_BTREE_KEYS_prev); pub const ALL_SNAPSHOTS: Self = Self(c::BCH_IOCTL_QUERY_BTREE_KEYS_all_snapshots); + pub const NOFILTER_WHITEOUTS: Self = + Self(c::BCH_IOCTL_QUERY_BTREE_KEYS_nofilter_whiteouts); } impl std::ops::BitOr for OnlineIterFlags { diff --git a/src/wrappers/super_io.rs b/src/wrappers/super_io.rs index 6a00750593..51916b9a8c 100644 --- a/src/wrappers/super_io.rs +++ b/src/wrappers/super_io.rs @@ -35,44 +35,37 @@ fn csum_vstruct_sb(sb: *mut c::bch_sb) -> c::bch_csum { /// Write superblock to all layout locations on disk. /// -/// # Safety -/// `sb` must point to a valid, fully initialized `bch_sb`. -/// /// Exits on I/O errors (matches C `die()` behavior). -pub fn bch2_super_write(fd: i32, sb: *mut c::bch_sb) { +pub fn bch2_super_write(fd: i32, sb: &mut S) { let file = borrowed_file(fd); let bs = crate::wrappers::bdev::get_blocksize_physical_hint(fd) as usize; - let sb_ref = unsafe { &mut *sb }; + let layout_range = { + let off = std::mem::offset_of!(c::bch_sb, layout); + off..off + std::mem::size_of::() + }; - let nr_superblocks = sb_ref.layout.nr_superblocks as usize; + let nr_superblocks = sb.sb().layout.nr_superblocks as usize; for i in 0..nr_superblocks { - sb_ref.offset = sb_ref.layout.sb_offset[i]; - - let offset_sectors = u64::from_le(sb_ref.offset); + let offset_le = sb.sb().layout.sb_offset[i]; + let offset_sectors = u64::from_le(offset_le); - sb_ref.csum = csum_vstruct_sb(sb); + sb.sb_mut().offset = offset_le; + sb.sb_mut().csum = csum_vstruct_sb(sb.sb_mut()); - let sb_bytes = vstruct_bytes_sb(unsafe { &*sb }); + let sb_src = sb.sb_bytes(); + let sb_bytes = sb_src.len(); + let layout_src = &sb_src[layout_range.clone()]; if offset_sectors == c::BCH_SB_SECTOR as u64 && bs > 4096 { // Layout and superblock are in the same aligned block; // write them together. let layout_offset = (c::BCH_SB_LAYOUT_SECTOR as usize) << 9; - let layout_bytes = std::mem::size_of::(); let sb_offset = (offset_sectors as usize) << 9; let write_len = round_up(sb_offset + sb_bytes, bs); let mut buf = vec![0u8; write_len]; - let layout_src = unsafe { - std::slice::from_raw_parts( - &sb_ref.layout as *const _ as *const u8, - layout_bytes, - ) - }; - buf[layout_offset..layout_offset + layout_bytes].copy_from_slice(layout_src); - - let sb_src = unsafe { std::slice::from_raw_parts(sb as *const u8, sb_bytes) }; + buf[layout_offset..layout_offset + layout_src.len()].copy_from_slice(layout_src); buf[sb_offset..sb_offset + sb_bytes].copy_from_slice(sb_src); pwrite_exact(&file, &buf, 0); @@ -84,21 +77,13 @@ pub fn bch2_super_write(fd: i32, sb: *mut c::bch_sb) { file.read_exact_at(&mut buf, 4096 - bs as u64) .unwrap_or_else(|e| die(&format!("pread failed at offset {}: {}", 4096 - bs, e))); - let layout_bytes = std::mem::size_of::(); - let layout_src = unsafe { - std::slice::from_raw_parts( - &sb_ref.layout as *const _ as *const u8, - layout_bytes, - ) - }; - buf[bs - layout_bytes..].copy_from_slice(layout_src); + buf[bs - layout_src.len()..].copy_from_slice(layout_src); pwrite_exact(&file, &buf, 4096 - bs as u64); } let write_len = round_up(sb_bytes, bs); let mut buf = vec![0u8; write_len]; - let sb_src = unsafe { std::slice::from_raw_parts(sb as *const u8, sb_bytes) }; buf[..sb_bytes].copy_from_slice(sb_src); pwrite_exact(&file, &buf, offset_sectors << 9); @@ -110,39 +95,27 @@ pub fn bch2_super_write(fd: i32, sb: *mut c::bch_sb) { } } -/// Read a superblock from disk at the given sector offset. -/// -/// Returns a malloc'd `bch_sb` pointer (caller must free). -/// -/// Exits if the magic doesn't match or on I/O error. -pub fn __bch2_super_read(fd: i32, sector: u64) -> *mut c::bch_sb { +/// Read a superblock from disk at the given sector offset, into an +/// owned, validated buffer. +pub fn super_read(fd: i32, sector: u64) -> anyhow::Result { let file = borrowed_file(fd); - // Read the fixed-size header first + // Read the fixed-size header to learn the full extent let header_size = std::mem::size_of::(); - let mut header_buf = vec![0u8; header_size]; - file.read_exact_at(&mut header_buf, sector << 9) - .unwrap_or_else(|e| die(&format!("pread failed at offset {}: {}", sector << 9, e))); + let mut buf = vec![0u8; header_size]; + file.read_exact_at(&mut buf, sector << 9) + .map_err(|e| anyhow::anyhow!("pread failed at offset {}: {}", sector << 9, e))?; - let sb_header = unsafe { &*(header_buf.as_ptr() as *const c::bch_sb) }; - - if sb_header.magic.b != BCACHE_MAGIC && sb_header.magic.b != BCHFS_MAGIC { - die("not a bcachefs superblock"); - } - - let bytes = vstruct_bytes_sb(sb_header); - - // Use malloc so the caller can free() it (C callers expect this) - let ptr = unsafe { libc::malloc(bytes) as *mut u8 }; - if ptr.is_null() { - die(&format!("allocation failed for superblock ({} bytes)", bytes)); - } + let u64s_off = std::mem::offset_of!(c::bch_sb, u64s); + let u64s = u32::from_le_bytes(buf[u64s_off..u64s_off + 4].try_into().unwrap()); + let bytes = header_size + u64s as usize * 8; - let buf = unsafe { std::slice::from_raw_parts_mut(ptr, bytes) }; - file.read_exact_at(buf, sector << 9) - .unwrap_or_else(|e| die(&format!("pread failed at offset {}: {}", sector << 9, e))); + buf.resize(bytes, 0); + file.read_exact_at(&mut buf, sector << 9) + .map_err(|e| anyhow::anyhow!("pread failed at offset {}: {}", sector << 9, e))?; - ptr as *mut c::bch_sb + SbBuf::from_bytes(&buf) + .map_err(|e| anyhow::anyhow!("superblock at sector {}: {}", sector, e)) } fn round_up(val: usize, align: usize) -> usize { @@ -155,14 +128,7 @@ fn pwrite_exact(file: &std::fs::File, buf: &[u8], offset: u64) { .unwrap_or_else(|e| die(&format!("pwrite failed at offset {}: {}", offset, e))); } -pub const BCACHE_MAGIC: [u8; 16] = [ - 0xc6, 0x85, 0x73, 0xf6, 0x4e, 0x1a, 0x45, 0xca, - 0x82, 0x65, 0xf5, 0x7f, 0x48, 0xba, 0x6d, 0x81, -]; -pub const BCHFS_MAGIC: [u8; 16] = [ - 0xc6, 0x85, 0x73, 0xf6, 0x66, 0xce, 0x90, 0xa9, - 0xd9, 0x6a, 0x60, 0xcf, 0x80, 0x3d, 0xf7, 0xef, -]; +use bcachefs_kernel::sb::io::{SbAccess, SbBuf}; /// Default superblock size in 512-byte sectors pub const SUPERBLOCK_SIZE_DEFAULT: u32 = 2048; @@ -182,7 +148,7 @@ pub fn sb_layout_init( ) -> anyhow::Result<()> { *l = Default::default(); - l.magic.b = BCHFS_MAGIC; + l.magic.b = bcachefs_kernel::sb::io::BCHFS_MAGIC; l.layout_type = 0; l.nr_superblocks = 2; l.sb_max_size_bits = sb_size.ilog2() as u8; diff --git a/src/wrappers/sysfs.rs b/src/wrappers/sysfs.rs index 0b9cc17433..7ebbcf8346 100644 --- a/src/wrappers/sysfs.rs +++ b/src/wrappers/sysfs.rs @@ -114,6 +114,8 @@ pub struct DevInfo { /// Human-facing device name selected by [`DeviceNameMode`]. pub dev: String, pub label: Option, + /// Failure domain name - see bch_member.failure_domain. + pub failure_domain: Option, pub durability: u32, pub online: bool, } @@ -144,15 +146,19 @@ pub fn fs_get_devices( let online = fs::metadata(dev_path.join("block")).is_ok(); let dev = dev_display_name_from_sysfs(&dev_path, name_mode); - let label = fs::read_to_string(dev_path.join("label")) - .ok() - .map(|s| s.trim().to_string()) - .filter(|s| !s.is_empty()); + let read_label = |name: &str| { + fs::read_to_string(dev_path.join(name)) + .ok() + .map(|s| s.trim().to_string()) + .filter(|s| !s.is_empty() && s != "none") + }; + let label = read_label("label"); + let failure_domain = read_label("failure_domain"); let durability = read_sysfs_u64(&dev_path.join("durability")) .unwrap_or(1) as u32; - devs.push(DevInfo { idx, dev, label, durability, online }); + devs.push(DevInfo { idx, dev, label, failure_domain, durability, online }); } devs.sort_by_key(|d| d.idx); Ok(devs)