1 \documentclass{article}
4 \usepackage[pdfborder={0 0 0}]{hyperref}
7 \title{bcachefs: Principles of Operation}
8 \author{Kent Overstreet}
17 \section{Introduction and overview}
19 Bcachefs is a modern, general purpose, copy on write filesystem descended from
20 bcache, a block layer cache.
22 The internal architecture is very different from most existing filesystems where
23 the inode is central and many data structures hang off of the inode. Instead,
24 bcachefs is architected more like a filesystem on top of a relational database,
25 with tables for the different filesystem data types - extents, inodes, dirents,
28 bcachefs supports almost all of the same features as other modern COW
29 filesystems, such as ZFS and btrfs, but in general with a cleaner, simpler,
30 higher performance design.
32 \subsection{Performance overview}
34 The core of the architecture is a very high performance and very low latency b+
35 tree, which also is not a conventional b+ tree but more of hybrid, taking
36 concepts from compacting data structures: btree nodes are very large, log
37 structured, and compacted (resorted) as necessary in memory. This means our b+
38 trees are very shallow compared to other filesystems.
40 What this means for the end user is that since we require very few seeks or disk
41 reads, filesystem latency is extremely good - especially cache cold filesystem
42 latency, which does not show up in most benchmarks but has a huge impact on real
43 world performance, as well as how fast the system "feels" in normal interactive
44 usage. Latency has been a major focus throughout the codebase - notably, we have
45 assertions that we never hold b+ tree locks while doing IO, and the btree
46 transaction layer makes it easily to aggressively drop and retake locks as
47 needed - one major goal of bcachefs is to be the first general purpose soft
50 Additionally, unlike other COW btrees, btree updates are journalled. This
51 greatly improves our write efficiency on random update workloads, as it means
52 btree writes are only done when we have a large block of updates, or when
53 required by memory reclaim or journal reclaim.
55 \subsection{Bucket based allocation}
57 As mentioned bcachefs is descended from bcache, where the ability to efficiently
58 invalidate cached data and reuse disk space was a core design requirement. To
59 make this possible the allocator divides the disk up into buckets, typically
60 512k to 2M but possibly larger or smaller. Buckets and data pointers have
61 generation numbers: we can reuse a bucket with cached data in it without finding
62 and deleting all the data pointers by incrementing the generation number.
64 In keeping with the copy-on-write theme of avoiding update in place wherever
65 possible, we never rewrite or overwrite data within a bucket - when we allocate
66 a bucket, we write to it sequentially and then we don't write to it again until
67 the bucket has been invalidated and the generation number incremented.
69 This means we require a copying garbage collector to deal with internal
70 fragmentation, when patterns of random writes leave us with many buckets that
71 are partially empty (because the data they contained was overwritten) - copy GC
72 evacuates buckets that are mostly empty by writing the data they contain to new
73 buckets. This also means that we need to reserve space on the device for the
74 copy GC reserve when formatting - typically 8\% or 12\%.
76 There are some advantages to structuring the allocator this way, besides being
77 able to support cached data:
79 \item By maintaining multiple write points that are writing to different buckets,
80 we're able to easily and naturally segregate unrelated IO from different
81 processes, which helps greatly with fragmentation.
83 \item The fast path of the allocator is essentially a simple bump allocator - the
84 disk space allocation is extremely fast
86 \item Fragmentation is generally a non issue unless copygc has to kick
87 in, and it usually doesn't under typical usage patterns. The
88 allocator and copygc are doing essentially the same things as
89 the flash translation layer in SSDs, but within the filesystem
90 we have much greater visibility into where writes are coming
91 from and how to segregate them, as well as which data is
92 actually live - performance is generally more predictable than
93 with SSDs under similar usage patterns.
95 \item The same algorithms will in the future be used for managing SMR
96 hard drives directly, avoiding the translation layer in the hard
97 drive - doing this work within the filesystem should give much
98 better performance and much more predictable latency.
101 \section{Feature overview}
103 \subsection{IO path options}
105 Most options that control the IO path can be set at either the filesystem level
106 or on individual inodes (files and directories). When set on a directory via the
107 \texttt{bcachefs attr} command, they will be automatically applied recursively.
109 \subsubsection{Checksumming}
111 bcachefs supports both metadata and data checksumming - crc32c by default, but
112 stronger checksums are available as well. Enabling data checksumming incurs some
113 performance overhead - besides the checksum calculation, writes have to be
114 bounced for checksum stability (Linux generally cannot guarantee that the buffer
115 being written is not modified in flight), but reads generally do not have to be
118 Checksum granularity in bcachefs is at the level of individual extents, which
119 results in smaller metadata but means we have to read entire extents in order to
120 verify the checksum. By default, checksummed and compressed extents are capped
121 at 64k. For most applications and usage scenarios this is an ideal trade off, but
122 small random \texttt{O\_DIRECT} reads will incur significant overhead. In the
123 future, checksum granularity will be a per-inode option.
125 \subsubsection{Encryption}
127 bcachefs supports authenticated (AEAD style) encryption - ChaCha20/Poly1305.
128 When encryption is enabled, the poly1305 MAC replaces the normal data and
129 metadata checksums. This style of encryption is superior to typical block layer
130 or filesystem level encryption (usually AES-XTS), which only operates on blocks
131 and doesn't have a way to store nonces or MACs. In contrast, we store a nonce
132 and cryptographic MAC alongside data pointers - meaning we have a chain of trust
133 up to the superblock (or journal, in the case of unclean shutdowns) and can
134 definitely tell if metadata has been modified, dropped, or replaced with an
135 earlier version - replay attacks are not possible.
137 Encryption can only be specified for the entire filesystem, not per file or
138 directory - this is because metadata blocks do not belong to a particular file.
139 All metadata except for the superblock is encrypted.
141 In the future we'll probably add AES-GCM for platforms that have hardware
142 acceleration for AES, but in the meantime software implementations of ChaCha20
143 are also quite fast on most platforms.
145 \texttt{scrypt} is used for the key derivation function - for converting the
146 user supplied passphrase to an encryption key.
148 To format a filesystem with encryption, use
149 \begin{quote} \begin{verbatim}
150 bcachefs format --encrypted /dev/sda1
151 \end{verbatim} \end{quote}
153 You will be prompted for a passphrase. Then, to use an encrypted filesystem
155 \begin{quote} \begin{verbatim}
156 bcachefs unlock /dev/sda1
157 \end{verbatim} \end{quote}
159 You will be prompted for the passphrase and the encryption key will be added to
160 your in-kernel keyring; mount, fsck and other commands will then work as usual.
162 The passphrase on an existing encrypted filesystem can be changed with the
163 \texttt{bcachefs set-passphrase} command. To permanently unlock an encrypted
164 filesystem, use the \texttt{bcachefs remove-passphrase} command - this can be
165 useful when dumping filesystem metadata for debugging by the developers.
167 There is a \texttt{wide\_macs} option which controls the size of the
168 cryptographic MACs stored on disk. By default, only 80 bits are stored, which
169 should be sufficient security for most applications. With the
170 \texttt{wide\_macs} option enabled we store the full 128 bit MAC, at the cost of
171 making extents 8 bytes bigger.
173 \subsubsection{Compression}
175 bcachefs supports gzip, lz4 and zstd compression. As with data checksumming, we
176 compress entire extents, not individual disk blocks - this gives us better
177 compression ratios than other filesystems, at the cost of reduced small random
180 Data can also be compressed or recompressed with a different algorithm in the
181 background by the rebalance thread, if the \texttt{background\_compression}
184 \subsection{Multiple devices}
186 bcachefs is a multi-device filesystem. Devices need not be the same size: by
187 default, the allocator will stripe across all available devices but biasing in
188 favor of the devices with more free space, so that all devices in the filesystem
189 fill up at the same rate. Devices need not have the same performance
190 characteristics: we track device IO latency and direct reads to the device that
191 is currently fastest.
193 \subsubsection{Replication}
195 bcachefs supports standard RAID1/10 style redundancy with the
196 \texttt{data\_replicas} and \texttt{metadata\_replicas} options. Layout is not
197 fixed as with RAID10: a given extent can be replicated across any set of
198 devices; the \texttt{bcachefs fs usage} command shows how data is replicated
201 \subsubsection{Erasure coding}
203 bcachefs also supports Reed-Solomon erasure coding - the same algorithm used by
204 most RAID5/6 implementations) When enabled with the \texttt{ec} option, the
205 desired redundancy is taken from the \texttt{data\_replicas} option - erasure
206 coding of metadata is not supported.
208 Erasure coding works significantly differently from both conventional RAID
209 implementations and other filesystems with similar features. In conventional
210 RAID, the "write hole" is a significant problem - doing a small write within a
211 stripe requires the P and Q (recovery) blocks to be updated as well, and since
212 those writes cannot be done atomically there is a window where the P and Q
213 blocks are inconsistent - meaning that if the system crashes and recovers with a
214 drive missing, reconstruct reads for unrelated data within that stripe will be
217 ZFS avoids this by fragmenting individual writes so that every write becomes a
218 new stripe - this works, but the fragmentation has a negative effect on
219 performance: metadata becomes bigger, and both read and write requests are
220 excessively fragmented. Btrfs's erasure coding implementation is more
221 conventional, and still subject to the write hole problem.
223 bcachefs's erasure coding takes advantage of our copy on write nature - since
224 updating stripes in place is a problem, we simply don't do that. And since
225 excessively small stripes is a problem for fragmentation, we don't erasure code
226 individual extents, we erasure code entire buckets - taking advantage of bucket
227 based allocation and copying garbage collection.
229 When erasure coding is enabled, writes are initially replicated, but one of the
230 replicas is allocated from a bucket that is queued up to be part of a new
231 stripe. When we finish filling up the new stripe, we write out the P and Q
232 buckets and then drop the extra replicas for all the data within that stripe -
233 the effect is similar to full data journalling, and it means that after erasure
234 coding is done the layout of our data on disk is ideal.
236 Since disks have write caches that are only flushed when we issue a cache flush
237 command - which we only do on journal commit - if we can tweak the allocator so
238 that the buckets used for the extra replicas are reused (and then overwritten
239 again) immediately, this full data journalling should have negligible overhead -
240 this optimization is not implemented yet, however.
242 \subsubsection{Device labels and targets}
244 By default, writes are striped across all devices in a filesystem, but they may
245 be directed to a specific device or set of devices with the various target
246 options. The allocator only prefers to allocate from devices matching the
247 specified target; if those devices are full, it will fall back to allocating
248 from any device in the filesystem.
250 Target options may refer to a device directly, e.g.
251 \texttt{foreground\_target=/dev/sda1}, or they may refer to a device label. A
252 device label is a path delimited by periods - e.g. ssd.ssd1 (and labels need not
253 be unique). This gives us ways of referring to multiple devices in target
254 options: If we specify ssd in a target option, that will refer to all devices
255 with the label ssd or labels that start with ssd. (e.g. ssd.ssd1, ssd.ssd2).
257 Four target options exist. These options all may be set at the filesystem level
258 (at format time, at mount time, or at runtime via sysfs), or on a particular
262 \item \texttt{foreground\_target}: normal foreground data writes, and
263 metadata if \\ \texttt{metadata\_target} is not set
264 \item \texttt{metadata\_target}: btree writes
265 \item \texttt{background\_target}: If set, user data (not metadata) will
266 be moved to this target in the background
267 \item\texttt{promote\_target}: If set, a cached copy will be added to
268 this target on read, if none exists
271 \subsubsection{Caching}
273 When an extent has multiple copies on different devices, some of those copies
274 may be marked as cached. Buckets containing only cached data are discarded as
275 needed by the allocator in LRU order.
277 When data is moved from one device to another according to the \\
278 \texttt{background\_target} option, the original copy is left in place but
279 marked as cached. With the \texttt{promote\_target} option, the original copy is
280 left unchanged and the new copy on the \texttt{promote\_target} device is marked
283 To do writeback caching, set \texttt{foreground\_target} and
284 \texttt{promote\_target} to the cache device, and \texttt{background\_target} to
285 the backing device. To do writearound caching, set \texttt{foreground\_target}
286 to the backing device and \texttt{promote\_target} to the cache device.
288 \subsubsection{Durability}
290 Some devices may be considered to be more reliable than others. For example, we
291 might have a filesystem composed of a hardware RAID array and several NVME flash
292 devices, to be used as cache. We can set replicas=2 so that losing any of the
293 NVME flash devices will not cause us to lose data, and then additionally we can
294 set durability=2 for the hardware RAID device to tell bcachefs that we don't
295 need extra replicas for data on that device - data on that device will count as
296 two replicas, not just one.
298 The durability option can also be used for writethrough caching: by setting
299 durability=0 for a device, it can be used as a cache and only as a cache -
300 bcachefs won't consider copies on that device to count towards the number of
301 replicas we're supposed to keep.
305 bcachefs supports reflink, similarly to other filesystems with the same feature.
306 \texttt{cp --reflink} will create a copy that shares the underlying storage.
307 Reading from that file will become slightly slower - the extent pointing to that
308 data is moved to the reflink btree (with a refcount added) and in the extents
309 btree we leave a key that points to the indirect extent in the reflink btree,
310 meaning that we now have to do two btree lookups to read from that data instead
313 \subsection{Inline data extents}
315 bcachefs supports inline data extents, controlled by the \texttt{inline\_data}
316 option (on by default). When the end of a file is being written and is smaller
317 than half of the filesystem blocksize, it will be written as an inline data
318 extent. Inline data extents can also be reflinked (moved to the reflink btree
319 with a refcount added): as a todo item we also intend to support compressed
322 \subsection{Subvolumes and snapshots}
324 bcachefs supports subvolumes and snapshots with a similar userspace interface as
325 btrfs. A new subvolume may be created empty, or it may be created as a snapshot
326 of another subvolume. Snapshots are writeable and may be snapshotted again,
327 creating a tree of snapshots.
329 Snapshots are very cheap to create: they're not based on cloning of COW btrees
330 as with btrfs, but instead are based on versioning of individual keys in the
331 btrees. Many thousands or millions of snapshots can be created, with the only
332 limitation being disk space.
334 The following subcommands exist for managing subvolumes and snapshots:
336 \item \texttt{bcachefs subvolume create}: Create a new, empty subvolume
337 \item \texttt{bcachefs subvolume destroy}: Delete an existing subvolume
339 \item \texttt{bcachefs subvolume snapshot}: Create a snapshot of an
343 A subvolume can also be deleting with a normal rmdir after deleting all the
344 contents, as with \texttt{rm -rf}. Still to be implemented: read-only snapshots,
345 recursive snapshot creation, and a method for recursively listing subvolumes.
349 bcachefs supports conventional user/group/project quotas. Quotas do not
350 currently apply to snapshot subvolumes, because if a file changes ownership in
351 the snapshot it would be ambiguous as to what quota data within that file
352 should be charged to.
354 When a directory has a project ID set it is inherited automatically by
355 descendants on creation and rename. When renaming a directory would cause the
356 project ID to change we return -EXDEV so that the move is done file by file, so
357 that the project ID is propagated correctly to descendants - thus, project
358 quotas can be used as subdirectory quotas.
362 \subsection{Formatting}
364 To format a new bcachefs filesystem use the subcommand \texttt{bcachefs
365 format}, or \texttt{mkfs.bcachefs}. All persistent filesystem-wide options can
366 be specified at format time. For an example of a multi device filesystem with
367 compression, encryption, replication and writeback caching:
368 \begin{quote} \begin{verbatim}
369 bcachefs format --compression=lz4 \
372 --label=ssd.ssd1 /dev/sda \
373 --label=ssd.ssd2 /dev/sdb \
374 --label=hdd.hdd1 /dev/sdc \
375 --label=hdd.hdd2 /dev/sdd \
376 --label=hdd.hdd3 /dev/sde \
377 --label=hdd.hdd4 /dev/sdf \
378 --foreground_target=ssd \
379 --promote_target=ssd \
380 --background_target=hdd
381 \end{verbatim} \end{quote}
383 \subsection{Mounting}
385 To mount a multi device filesystem, there are two options. You can specify all
386 component devices, separated by colons, e.g.
387 \begin{quote} \begin{verbatim}
388 mount -t bcachefs /dev/sda:/dev/sdb:/dev/sdc /mnt
389 \end{verbatim} \end{quote}
390 Or, use the mount.bcachefs tool to mount by filesystem UUID. Still todo: improve
391 the mount.bcachefs tool to support mounting by filesystem label.
393 No special handling is needed for recovering from unclean shutdown. Journal
394 replay happens automatically, and diagnostic messages in the dmesg log will
395 indicate whether recovery was from clean or unclean shutdown.
397 The \texttt{-o degraded} option will allow a filesystem to be mounted without
398 all the devices, but will fail if data would be missing. The
399 \texttt{-o very\_degraded} can be used to attempt mounting when data would be
402 Also relevant is the \texttt{-o nochanges} option. It disallows any and all
403 writes to the underlying devices, pinning dirty data in memory as necessary if
404 for example journal replay was necessary - think of it as a "super read-only"
405 mode. It can be used for data recovery, and for testing version upgrades.
407 The \texttt{-o verbose} enables additional log output during the mount process.
411 It is possible to run fsck either in userspace with the \texttt{bcachefs fsck}
412 subcommand (also available as \texttt{fsck.bcachefs}, or in the kernel while
413 mounting by specifying the \texttt{-o fsck} mount option. In either case the
414 exact same fsck implementation is being run, only the environment is different.
415 Running fsck in the kernel at mount time has the advantage of somewhat better
416 performance, while running in userspace has the ability to be stopped with
417 ctrl-c and can prompt the user for fixing errors. To fix errors while running
418 fsck in the kernel, use the \texttt{-o fix\_errors} option.
420 The \texttt{-n} option passed to fsck implies the \texttt{-o nochanges} option;
421 \texttt{bcachefs fsck -ny} can be used to test filesystem repair in dry-run
424 \subsection{Status of data}
426 The \texttt{bcachefs fs usage} may be used to display filesystem usage broken
427 out in various ways. Data usage is broken out by type: superblock, journal,
428 btree, data, cached data, and parity, and by which sets of devices extents are
429 replicated across. We also give per-device usage which includes fragmentation
430 due to partially used buckets.
434 The journal has a number of tunables that affect filesystem performance. Journal
435 commits are fairly expensive operations as they require issuing FLUSH and FUA
436 operations to the underlying devices. By default, we issue a journal flush one
437 second after a filesystem update has been done; this is controlled with the
438 \texttt{journal\_flush\_delay} option, which takes a parameter in milliseconds.
440 Filesystem sync and fsync operations issue journal flushes; this can be disabled
441 with the \texttt{journal\_flush\_disabled} option - the
442 \texttt{journal\_flush\_delay} option will still apply, and in the event of a
443 system crash we will never lose more than (by default) one second of work. This
444 option may be useful on a personal workstation or laptop, and perhaps less
445 appropriate on a server.
447 The journal reclaim thread runs in the background, kicking off btree node writes
448 and btree key cache flushes to free up space in the journal. Even in the absence
449 of space pressure it will run slowly in the background: this is controlled by
450 the \texttt{journal\_reclaim\_delay} parameter, with a default of 100
453 The journal should be sized sufficiently that bursts of activity do not fill up
454 the journal too quickly; also, a larger journal mean that we can queue up larger
455 btree writes. The \texttt{bcachefs device resize-journal} can be used for
456 resizing the journal on disk on a particular device - it can be used on a
457 mounted or unmounted filesystem.
459 In the future, we should implement a method to see how much space is currently
460 utilized in the journal.
462 \subsection{Device management}
464 \subsubsection{Filesystem resize}
466 A filesystem can be resized on a particular device with the
467 \texttt{bcachefs device resize} subcommand. Currently only growing is supported,
470 \subsubsection{Device add/removal}
472 The following subcommands exist for adding and removing devices from a mounted
475 \item \texttt{bcachefs device add}: Formats and adds a new device to an
477 \item \texttt{bcachefs device remove}: Permenantly removes a device from
478 an existing filesystem.
479 \item \texttt{bcachefs device online}: Connects a device to a running
480 filesystem that was mounted without it (i.e. in degraded mode)
481 \item \texttt{bcachefs device offline}: Disconnects a device from a
482 mounted filesystem without removing it.
483 \item \texttt{bcachefs device evacuate}: Migrates data off of a
484 particular device to prepare for removal, setting it read-only
486 \item \texttt{bcachefs device set-state}: Changes the state of a member
487 device: one of rw (readwrite), ro (readonly), failed, or spare.
489 A failed device is considered to have 0 durability, and replicas
490 on that device won't be counted towards the number of replicas
491 an extent should have by rereplicate - however, bcachefs will
492 still attempt to read from devices marked as failed.
495 The \texttt{bcachefs device remove}, \texttt{bcachefs device offline} and
496 \texttt{bcachefs device set-state} commands take force options for when they
497 would leave the filesystem degraded or with data missing. Todo: regularize and
498 improve those options.
500 \subsection{Data management}
502 \subsubsection{Data rereplicate}
504 The \texttt{bcachefs data rereplicate} command may be used to scan for extents
505 that have insufficient replicas and write additional replicas, e.g. after a
506 device has been removed from a filesystem or after replication has been enabled
509 \subsubsection{Rebalance}
511 To be implemented: a command for moving data between devices to equalize usage
512 on each device. Not normally required because the allocator attempts to equalize
513 usage across devices as it stripes, but can be necessary in certain scenarios -
514 i.e. when a two-device filesystem with replication enabled that is very full has
515 a third device added.
517 \subsubsection{Scrub}
519 To be implemented: a command for reading all data within a filesystem and
520 ensuring that checksums are valid, fixing bitrot when a valid copy can be found.
524 Most bcachefs options can be set filesystem wide, and a significant subset can
525 also be set on inodes (files and directories), overriding the global defaults.
526 Filesystem wide options may be set when formatting, when mounting, or at runtime
527 via \texttt{/sys/fs/bcachefs/<uuid>/options/}. When set at runtime via sysfs the
528 persistent options in the superblock are updated as well; when options are
529 passed as mount parameters the persistent options are unmodified.
531 \subsection{File and directory options}
533 <say something here about how attrs must be set via bcachefs attr command>
535 Options set on inodes (files and directories) are automatically inherited by
536 their descendants, and inodes also record whether a given option was explicitly
537 set or inherited from their parent. When renaming a directory would cause
538 inherited attributes to change we fail the rename with -EXDEV, causing userspace
539 to do the rename file by file so that inherited attributes stay consistent.
541 Inode options are available as extended attributes. The options that have been
542 explicitly set are available under the \texttt{bcachefs} namespace, and the effective
543 options (explicitly set and inherited options) are available under the
544 \texttt{bcachefs\_effective} namespace. Examples of listing options with the
547 \begin{quote} \begin{verbatim}
548 $ getfattr -d -m '^bcachefs\.' filename
549 $ getfattr -d -m '^bcachefs_effective\.' filename
550 \end{verbatim} \end{quote}
552 Options may be set via the extended attribute interface, but it is preferable to
553 use the \texttt{bcachefs setattr} command as it will correctly propagate options
556 \subsection{Full option list}
559 \hspace{0.2in} \= \kill
560 \texttt{block\_size} \` \textbf{format} \\
561 \> \parbox{4.3in}{Filesystem block size (default 4k)} \\ \\
563 \texttt{btree\_node\_size} \` \textbf{format} \\
564 \> Btree node size, default 256k \\ \\
566 \texttt{errors} \` \textbf{format,mount,rutime} \\
567 \> Action to take on filesystem error \\ \\
569 \texttt{metadata\_replicas} \` \textbf{format,mount,runtime} \\
570 \> Number of replicas for metadata (journal and btree) \\ \\
572 \texttt{data\_replicas} \` \textbf{format,mount,runtime,inode} \\
573 \> Number of replicas for user data \\ \\
575 \texttt{replicas} \` \textbf{format} \\
576 \> Alias for both metadata\_replicas and data\_replicas \\ \\
578 \texttt{metadata\_checksum} \` \textbf{format,mount,runtime} \\
579 \> Checksum type for metadata writes \\ \\
581 \texttt{data\_checksum} \` \textbf{format,mount,runtime,inode} \\
582 \> Checksum type for data writes \\ \\
584 \texttt{compression} \` \textbf{format,mount,runtime,inode} \\
585 \> Compression type \\ \\
587 \texttt{background\_compression} \` \textbf{format,mount,runtime,inode} \\
588 \> Background compression type \\ \\
590 \texttt{str\_hash} \` \textbf{format,mount,runtime,inode} \\
591 \> Hash function for string hash tables (directories and xattrs) \\ \\
593 \texttt{metadata\_target} \` \textbf{format,mount,runtime,inode} \\
594 \> Preferred target for metadata writes \\ \\
596 \texttt{foreground\_target} \` \textbf{format,mount,runtime,inode} \\
597 \> Preferred target for foreground writes \\ \\
599 \texttt{background\_target} \` \textbf{format,mount,runtime,inode} \\
600 \> Target for data to be moved to in the background \\ \\
602 \texttt{promote\_target} \` \textbf{format,mount,runtime,inode} \\
603 \> Target for data to be copied to on read \\ \\
605 \texttt{erasure\_code} \` \textbf{format,mount,runtime,inode} \\
606 \> Enable erasure coding \\ \\
608 \texttt{inodes\_32bit} \` \textbf{format,mount,runtime} \\
609 \> Restrict new inode numbers to 32 bits \\ \\
611 \texttt{shard\_inode\_numbers} \` \textbf{format,mount,runtime} \\
612 \> Use CPU id for high bits of new inode numbers. \\ \\
614 \texttt{wide\_macs} \` \textbf{format,mount,runtime} \\
615 \> Store full 128 bit cryptographic MACs (default 80) \\ \\
617 \texttt{inline\_data} \` \textbf{format,mount,runtime} \\
618 \> Enable inline data extents (default on) \\ \\
620 \texttt{journal\_flush\_delay} \` \textbf{format,mount,runtime} \\
621 \> Delay in milliseconds before automatic journal commit (default 1000) \\ \\
623 \texttt{journal\_flush\_disabled}\`\textbf{format,mount,runtime} \\
624 \> \begin{minipage}{4.3in}Disables journal flush on sync/fsync.
625 \texttt{journal\_flush\_delay} remains in effect, thus with the
626 default setting not more than 1 second of work will be lost.
629 \texttt{journal\_reclaim\_delay}\` \textbf{format,mount,runtime} \\
630 \> Delay in milliseconds before automatic journal reclaim \\ \\
632 \texttt{acl} \` \textbf{format,mount} \\
633 \> Enable POSIX ACLs \\ \\
635 \texttt{usrquota} \` \textbf{format,mount} \\
636 \> Enable user quotas \\ \\
638 \texttt{grpquota} \` \textbf{format,mount} \\
639 \> Enable group quotas \\ \\
641 \texttt{prjquota} \` \textbf{format,mount} \\
642 \> Enable project quotas \\ \\
644 \texttt{degraded} \` \textbf{mount} \\
645 \> Allow mounting with data degraded \\ \\
647 \texttt{very\_degraded} \` \textbf{mount} \\
648 \> Allow mounting with data missing \\ \\
650 \texttt{verbose} \` \textbf{mount} \\
651 \> Extra debugging info during mount/recovery \\ \\
653 \texttt{fsck} \` \textbf{mount} \\
654 \> Run fsck during mount \\ \\
656 \texttt{fix\_errors} \` \textbf{mount} \\
657 \> Fix errors without asking during fsck \\ \\
659 \texttt{ratelimit\_errors} \` \textbf{mount} \\
660 \> Ratelimit error messages during fsck \\ \\
662 \texttt{read\_only} \` \textbf{mount} \\
663 \> Mount in read only mode \\ \\
665 \texttt{nochanges} \` \textbf{mount} \\
666 \> Issue no writes, even for journal replay \\ \\
668 \texttt{norecovery} \` \textbf{mount} \\
669 \> Don't replay the journal (not recommended) \\ \\
671 \texttt{noexcl} \` \textbf{mount} \\
672 \> Don't open devices in exclusive mode \\ \\
674 \texttt{version\_upgrade} \` \textbf{mount} \\
675 \> Upgrade on disk format to latest version \\ \\
677 \texttt{discard} \` \textbf{device} \\
678 \> Enable discard/TRIM support \\ \\
681 \subsection{Error actions}
682 The \texttt{errors} option is used for inconsistencies that indicate some sort
683 of a bug. Valid error actions are:
685 \item[{\tt continue}] Log the error but continue normal operation
686 \item[{\tt ro}] Emergency read only, immediately halting any changes
687 to the filesystem on disk
688 \item[{\tt panic}] Immediately halt the entire machine, printing a
689 backtrace on the system console
692 \subsection{Checksum types}
693 Valid checksum types are:
696 \item[{\tt crc32c}] (default)
700 \subsection{Compression types}
701 Valid compression types are:
703 \item[{\tt none}] (default)
709 \subsection{String hash types}
710 Valid hash types for string hash tables are:
714 \item[{\tt siphash}] (default)
717 \section{Debugging tools}
719 \subsection{Sysfs interface}
721 Mounted filesystems are available in sysfs at \texttt{/sys/fs/bcachefs/<uuid>/}
722 with various options, performance counters and internal debugging aids.
724 \subsubsection{Options}
726 Filesystem options may be viewed and changed via \\
727 \texttt{/sys/fs/bcachefs/<uuid>/options/}, and settings changed via sysfs will
728 be persistently changed in the superblock as well.
730 \subsubsection{Time stats}
732 bcachefs tracks the latency and frequency of various operations and events, with
733 quantiles for latency/duration in the
734 \texttt{/sys/fs/bcachefs/<uuid>/time\_stats/} directory.
737 \item \texttt{blocked\_allocate} \\
738 Tracks when allocating a bucket must wait because none are
739 immediately available, meaning the copygc thread is not keeping
740 up with evacuating mostly empty buckets or the allocator thread
741 is not keeping up with invalidating and discarding buckets.
743 \item \texttt{blocked\_allocate\_open\_bucket} \\
744 Tracks when allocating a bucket must wait because all of our
745 handles for pinning open buckets are in use (we statically
748 \item \texttt{blocked\_journal} \\
749 Tracks when getting a journal reservation must wait, either
750 because journal reclaim isn't keeping up with reclaiming space
751 in the journal, or because journal writes are taking too long to
752 complete and we already have too many in flight.
754 \item \texttt{btree\_gc} \\
755 Tracks when the btree\_gc code must walk the btree at runtime -
756 for recalculating the oldest outstanding generation number of
757 every bucket in the btree.
759 \item \texttt{btree\_lock\_contended\_read}
760 \item \texttt{btree\_lock\_contended\_intent}
761 \item \texttt{btree\_lock\_contended\_write} \\
762 Track when taking a read, intent or write lock on a btree node
765 \item \texttt{btree\_node\_mem\_alloc} \\
766 Tracks the total time to allocate memory in the btree node cache
767 for a new btree node.
769 \item \texttt{btree\_node\_split} \\
770 Tracks btree node splits - when a btree node becomes full and is
771 split into two new nodes
773 \item \texttt{btree\_node\_compact} \\
774 Tracks btree node compactions - when a btree node becomes full
775 and needs to be compacted on disk.
777 \item \texttt{btree\_node\_merge} \\
778 Tracks when two adjacent btree nodes are merged.
780 \item \texttt{btree\_node\_sort} \\
781 Tracks sorting and resorting entire btree nodes in memory,
782 either after reading them in from disk or for compacting prior
783 to creating a new sorted array of keys.
785 \item \texttt{btree\_node\_read} \\
786 Tracks reading in btree nodes from disk.
788 \item \texttt{btree\_interior\_update\_foreground} \\
789 Tracks foreground time for btree updates that change btree
790 topology - i.e. btree node splits, compactions and merges; the
791 duration measured roughly corresponds to lock held time.
793 \item \texttt{btree\_interior\_update\_total} \\
794 Tracks time to completion for topology changing btree updates;
795 first they have a foreground part that updates btree nodes in
796 memory, then after the new nodes are written there is a
797 transaction phase that records an update to an interior node or
798 a new btree root as well as changes to the alloc btree.
800 \item \texttt{data\_read} \\
801 Tracks the core read path - looking up a request in the extents
802 (and possibly also reflink) btree, allocating bounce buffers if
803 necessary, issuing reads, checksumming, decompressing, decrypting,
804 and delivering completions.
806 \item \texttt{data\_write} \\
807 Tracks the core write path - allocating space on disk for a new
808 write, allocating bounce buffers if necessary,
809 compressing, encrypting, checksumming, issuing writes, and
810 updating the extents btree to point to the new data.
812 \item \texttt{data\_promote} \\
813 Tracks promote operations, which happen when a read operation
814 writes an additional cached copy of an extent to
815 \texttt{promote\_target}. This is done asynchronously from the
818 \item \texttt{journal\_flush\_write} \\
819 Tracks writing of flush journal entries to disk, which first
820 issue cache flush operations to the underlying devices then
821 issue the journal writes as FUA writes. Time is tracked starting
822 from after all journal reservations have released their
823 references or the completion of the previous journal write.
825 \item \texttt{journal\_noflush\_write} \\
826 Tracks writing of non-flush journal entries to disk, which do
827 not issue cache flushes or FUA writes.
829 \item \texttt{journal\_flush\_seq} \\
830 Tracks time to flush a journal sequence number to disk by
831 filesystem sync and fsync operations, as well as the allocator
832 prior to reusing buckets when none that do not need flushing are
836 \subsubsection{Internals}
839 \item \texttt{btree\_cache} \\
840 Shows information on the btree node cache: number of cached
841 nodes, number of dirty nodes, and whether the cannibalize lock
842 (for reclaiming cached nodes to allocate new nodes) is held.
844 \item \texttt{dirty\_btree\_nodes} \\
845 Prints information related to the interior btree node update
846 machinery, which is responsible for ensuring dependent btree
847 node writes are ordered correctly.
849 For each dirty btree node, prints:
851 \item Whether the \texttt{need\_write} flag is set
852 \item The level of the btree node
853 \item The number of sectors written
854 \item Whether writing this node is blocked, waiting for
855 other nodes to be written
856 \item Whether it is waiting on a btree\_update to
857 complete and make it reachable on-disk
860 \item \texttt{btree\_key\_cache} \\
861 Prints infromation on the btree key cache: number of freed keys
862 (which must wait for a sRCU barrier to complete before being
863 freed), number of cached keys, and number of dirty keys.
865 \item \texttt{btree\_transactions} \\
866 Lists each running btree transactions that has locks held,
867 listing which nodes they have locked and what type of lock, what
868 node (if any) the process is blocked attempting to lock, and
869 where the btree transaction was invoked from.
871 \item \texttt{btree\_updates} \\
872 Lists outstanding interior btree updates: the mode (nothing
873 updated yet, or updated a btree node, or wrote a new btree root,
874 or was reparented by another btree update), whether its new
875 btree nodes have finished writing, its embedded closure's
876 refcount (while nonzero, the btree update is still waiting), and
877 the pinned journal sequence number.
879 \item \texttt{journal\_debug} \\
880 Prints a variety of internal journal state.
882 \item \texttt{journal\_pins}
883 Lists items pinning journal entries, preventing them from being
886 \item \texttt{new\_stripes} \\
887 Lists new erasure-coded stripes being created.
889 \item \texttt{stripes\_heap} \\
890 Lists erasure-coded stripes that are available to be reused.
892 \item \texttt{open\_buckets} \\
893 Lists buckets currently being written to, along with data type
896 \item \texttt{io\_timers\_read} \\
897 \item \texttt{io\_timers\_write} \\
898 Lists outstanding IO timers - timers that wait on total reads or
899 writes to the filesystem.
901 \item \texttt{trigger\_journal\_flush} \\
902 Echoing to this file triggers a journal commit.
904 \item \texttt{trigger\_gc} \\
905 Echoing to this file causes the GC code to recalculate each
906 bucket's oldest\_gen field.
908 \item \texttt{prune\_cache} \\
909 Echoing to this file prunes the btree node cache.
911 \item \texttt{read\_realloc\_races} \\
912 This counts events where the read path reads an extent and
913 discovers the bucket that was read from has been reused while
914 the IO was in flight, causing the read to be retried.
916 \item \texttt{extent\_migrate\_done} \\
917 This counts extents moved by the core move path, used by copygc
920 \item \texttt{extent\_migrate\_raced} \\
921 This counts extents that the move path attempted to move but no
922 longer existed when doing the final btree update.
925 \subsubsection{Unit and performance tests}
927 Echoing into \texttt{/sys/fs/bcachefs/<uuid>/perf\_test} runs various low level
928 btree tests, some intended as unit tests and others as performance tests. The
930 \begin{quote} \begin{verbatim}
931 echo <test_name> <nr_iterations> <nr_threads> > perf_test
932 \end{verbatim} \end{quote}
934 When complete, the elapsed time will be printed in the dmesg log. The full list
935 of tests that can be run can be found near the bottom of
936 \texttt{fs/bcachefs/tests.c}.
938 \subsection{Debugfs interface}
940 The contents of every btree, as well as various internal per-btree-node
941 information, are available under \texttt{/sys/kernel/debug/bcachefs/<uuid>/}.
943 For every btree, we have the following files:
946 \item \textit{btree\_name} \\
947 Entire btree contents, one key per line
949 \item \textit{btree\_name}\texttt{-formats} \\
950 Information about each btree node: the size of the packed bkey
951 format, how full each btree node is, number of packed and
952 unpacked keys, and number of nodes and failed nodes in the
953 in-memory search trees.
955 \item \textit{btree\_name}\texttt{-bfloat-failed} \\
956 For each sorted set of keys in a btree node, we construct a
957 binary search tree in eytzinger layout with compressed keys.
958 Sometimes we aren't able to construct a correct compressed
959 search key, which results in slower lookups; this file lists the
960 keys that resulted in these failed nodes.
963 \subsection{Listing and dumping filesystem metadata}
965 \subsubsection{bcachefs show-super}
967 This subcommand is used for examining and printing bcachefs superblocks. It
968 takes two optional parameters:
970 \item \texttt{-l}: Print superblock layout, which records the amount of
971 space reserved for the superblock and the locations of the
973 \item \texttt{-f, --fields=(fields)}: List of superblock sections to
974 print, \texttt{all} to print all sections.
977 \subsubsection{bcachefs list}
979 This subcommand gives access to the same functionality as the debugfs interface,
980 listing btree nodes and contents, but for offline filesystems.
982 \subsubsection{bcachefs list\_journal}
984 This subcommand lists the contents of the journal, which primarily records btree
985 updates ordered by when they occured.
987 \subsubsection{bcachefs dump}
989 This subcommand can dump all metadata in a filesystem (including multi device
990 filesystems) as qcow2 images: when encountering issues that \texttt{fsck} can
991 not recover from and need attention from the developers, this makes it possible
992 to send the developers only the required metadata. Encrypted filesystems must
993 first be unlocked with \texttt{bcachefs remove-passphrase}.
995 \section{ioctl interface}
997 This section documents bcachefs-specific ioctls:
1000 \item \texttt{BCH\_IOCTL\_QUERY\_UUID} \\
1001 Returs the UUID of the filesystem: used to find the sysfs
1002 directory given a path to a mounted filesystem.
1004 \item \texttt{BCH\_IOCTL\_FS\_USAGE} \\
1005 Queries filesystem usage, returning global counters and a list
1006 of counters by \texttt{bch\_replicas} entry.
1008 \item \texttt{BCH\_IOCTL\_DEV\_USAGE} \\
1009 Queries usage for a particular device, as bucket and sector
1010 counts broken out by data type.
1012 \item \texttt{BCH\_IOCTL\_READ\_SUPER} \\
1013 Returns the filesystem superblock, and optionally the superblock
1014 for a particular device given that device's index.
1016 \item \texttt{BCH\_IOCTL\_DISK\_ADD} \\
1017 Given a path to a device, adds it to a mounted and running
1018 filesystem. The device must already have a bcachefs superblock;
1019 options and parameters are read from the new device's superblock
1020 and added to the member info section of the existing
1021 filesystem's superblock.
1023 \item \texttt{BCH\_IOCTL\_DISK\_REMOVE} \\
1024 Given a path to a device or a device index, attempts to remove
1025 it from a mounted and running filesystem. This operation
1026 requires walking the btree to remove all references to this
1027 device, and may fail if data would become degraded or lost,
1028 unless appropriate force flags are set.
1030 \item \texttt{BCH\_IOCTL\_DISK\_ONLINE} \\
1031 Given a path to a device that is a member of a running
1032 filesystem (in degraded mode), brings it back online.
1034 \item \texttt{BCH\_IOCTL\_DISK\_OFFLINE} \\
1035 Given a path or device index of a device in a multi device
1036 filesystem, attempts to close it without removing it, so that
1037 the device may be re-added later and the contents will still be
1040 \item \texttt{BCH\_IOCTL\_DISK\_SET\_STATE} \\
1041 Given a path or device index of a device in a multi device
1042 filesystem, attempts to set its state to one of read-write,
1043 read-only, failed or spare. Takes flags to force if the
1044 filesystem would become degraded.
1046 \item \texttt{BCH\_IOCTL\_DISK\_GET\_IDX} \\
1047 \item \texttt{BCH\_IOCTL\_DISK\_RESIZE} \\
1048 \item \texttt{BCH\_IOCTL\_DISK\_RESIZE\_JOURNAL} \\
1049 \item \texttt{BCH\_IOCTL\_DATA} \\
1050 Starts a data job, which walks all data and/or metadata in a
1051 filesystem performing, performaing some operation on each btree
1052 node and extent. Returns a file descriptor which can be read
1053 from to get the current status of the job, and closing the file
1054 descriptor (i.e. on process exit stops the data job.
1056 \item \texttt{BCH\_IOCTL\_SUBVOLUME\_CREATE} \\
1057 \item \texttt{BCH\_IOCTL\_SUBVOLUME\_DESTROY} \\
1058 \item \texttt{BCHFS\_IOC\_REINHERIT\_ATTRS} \\
1061 \section{On disk format}
1063 \subsection{Superblock}
1065 The superblock is the first thing to be read when accessing a bcachefs
1066 filesystem. It is located 4kb from the start of the device, with redundant
1067 copies elsewhere - typically one immediately after the first superblock, and one
1068 at the end of the device.
1070 The \texttt{bch\_sb\_layout} records the amount of space reserved for the
1071 superblock as well as the locations of all the superblocks. It is included with
1072 every superblock, and additionally written 3584 bytes from the start of the
1073 device (512 bytes before the first superblock).
1075 Most of the superblock is identical across each device. The exceptions are the
1076 \texttt{dev\_idx} field, and the journal section which gives the location of the
1079 The main section of the superblock contains UUIDs, version numbers, number of
1080 devices within the filesystem and device index, block size, filesystem creation
1081 time, and various options and settings. The superblock also has a number of
1082 variable length sections:
1085 \item \texttt{BCH\_SB\_FIELD\_journal} \\
1086 List of buckets used for the journal on this device.
1088 \item \texttt{BCH\_SB\_FIELD\_members} \\
1089 List of member devices, as well as per-device options and
1090 settings, including bucket size, number of buckets and time when
1093 \item \texttt{BCH\_SB\_FIELD\_crypt} \\
1094 Contains the main chacha20 encryption key, encrypted by the
1095 user's passphrase, as well as key derivation function settings.
1097 \item \texttt{BCH\_SB\_FIELD\_replicas} \\
1098 Contains a list of replica entries, which are lists of devices
1099 that have extents replicated across them.
1101 \item \texttt{BCH\_SB\_FIELD\_quota} \\
1102 Contains timelimit and warnlimit fields for each quota type
1103 (user, group and project) and counter (space, inodes).
1105 \item \texttt{BCH\_SB\_FIELD\_disk\_groups} \\
1106 Formerly referred to as disk groups (and still is throughout the
1107 code); this section contains device label strings and records
1108 the tree structure of label paths, allowing a label once parsed
1109 to be referred to by integer ID by the target options.
1111 \item \texttt{BCH\_SB\_FIELD\_clean} \\
1112 When the filesystem is clean, this section contains a list of
1113 journal entries that are normally written with each journal
1114 write (\texttt{struct jset}): btree roots, as well as filesystem
1115 usage and read/write counters (total amount of data read/written
1116 to this filesystem). This allows reading the journal to be
1117 skipped after clean shutdowns.
1120 \subsection{Journal}
1122 Every journal write (\texttt{struct jset}) contains a list of entries:
1123 \texttt{struct jset\_entry}. Below are listed the various journal entry types.
1126 \item \texttt{BCH\_JSET\_ENTRY\_btree\_key} \\
1127 This entry type is used to record every btree update that
1128 happens. It contains one or more btree keys (\texttt{struct
1129 bkey}), and the \texttt{btree\_id} and \texttt{level} fields of
1130 \texttt{jset\_entry} record the btree ID and level the key
1133 \item \texttt{BCH\_JSET\_ENTRY\_btree\_root} \\
1134 This entry type is used for pointers btree roots. In the current
1135 implementation, every journal write still records every btree
1136 root, although that is subject to change. A btree root is a bkey
1137 of type \texttt{KEY\_TYPE\_btree\_ptr\_v2}, and the btree\_id
1138 and level fields of \texttt{jset\_entry} record the btree ID and
1141 \item \texttt{BCH\_JSET\_ENTRY\_clock} \\
1142 Records IO time, not wall clock time - i.e. the amount of reads
1143 and writes, in 512 byte sectors since the filesystem was
1146 \item \texttt{BCH\_JSET\_ENTRY\_usage} \\
1147 Used for certain persistent counters: number of inodes, current
1148 maximum key version, and sectors of persistent reservations.
1150 \item \texttt{BCH\_JSET\_ENTRY\_data\_usage} \\
1151 Stores replica entries with a usage counter, in sectors.
1153 \item \texttt{BCH\_JSET\_ENTRY\_dev\_usage} \\
1154 Stores usage counters for each device: sectors used and buckets
1155 used, broken out by each data type.
1160 \subsection{Btree keys}
1163 \item \texttt{KEY\_TYPE\_deleted}
1164 \item \texttt{KEY\_TYPE\_whiteout}
1165 \item \texttt{KEY\_TYPE\_error}
1166 \item \texttt{KEY\_TYPE\_cookie}
1167 \item \texttt{KEY\_TYPE\_hash\_whiteout}
1168 \item \texttt{KEY\_TYPE\_btree\_ptr}
1169 \item \texttt{KEY\_TYPE\_extent}
1170 \item \texttt{KEY\_TYPE\_reservation}
1171 \item \texttt{KEY\_TYPE\_inode}
1172 \item \texttt{KEY\_TYPE\_inode\_generation}
1173 \item \texttt{KEY\_TYPE\_dirent}
1174 \item \texttt{KEY\_TYPE\_xattr}
1175 \item \texttt{KEY\_TYPE\_alloc}
1176 \item \texttt{KEY\_TYPE\_quota}
1177 \item \texttt{KEY\_TYPE\_stripe}
1178 \item \texttt{KEY\_TYPE\_reflink\_p}
1179 \item \texttt{KEY\_TYPE\_reflink\_v}
1180 \item \texttt{KEY\_TYPE\_inline\_data}
1181 \item \texttt{KEY\_TYPE\_btree\_ptr\_v2}
1182 \item \texttt{KEY\_TYPE\_indirect\_inline\_data}
1183 \item \texttt{KEY\_TYPE\_alloc\_v2}
1184 \item \texttt{KEY\_TYPE\_subvolume}
1185 \item \texttt{KEY\_TYPE\_snapshot}
1186 \item \texttt{KEY\_TYPE\_inode\_v2}
1187 \item \texttt{KEY\_TYPE\_alloc\_v3}