XFS Online Fsck Design

This document captures the design of the online filesystem check feature for XFS. The purpose of writing this document is to help code reviewers to familiarize themselves with the relevant concepts and design points ahead of time. The purpose of preserving this document alongside the kernel code is to capture the reasons for why upper level decisions were made, which it is hoped will assist anyone trying to maintain the system.

The first section will define what fsck tools are and the motivations for writing a new one. The second and third sections present a high level overview of how online fsck process works and how it will be tested. The fourth section discusses the user interface and the intended usage modes of the program. Sections five and six constitutes the bulk of the discussion wherein specific aspects of the design will be presented. Specific attention will be paid to parts that are more technically complex; are fairly novel for Linux filesystems; or are rather more tightly coupled to the rest of the (file)system. The final section of this document will capture anticipated future work and users of the functionality.

This document is licensed under the terms of the GNU Public License, v2. The primary author is Darrick J. Wong.

Contents

What is a Filesystem Check?

A Unix filesystem has three main jobs: to provide a hierarchy of names through which application programs can associate arbitrary blobs of data for any length of time, to virtualize physical storage media across those names, and to retrieve the named data blobs at any time. The filesystem check (fsck) tool examines all the metadata in a filesystem to look for errors. Simple tools only check for obvious corruptions, but the more sophisticated ones cross-reference metadata records to look for inconsistencies. People do not like losing data, so most fsck tools also contains some ability to deal with any problems found. As a word of caution – the primary goal of most Linux fsck tools is to restore the filesystem metadata to a consistent state, not maximize the data recovered. We will not challenge that precedent here.

Filesystems of the 20th century generally lacked any redundancy in the ondisk format, which means that fsck can only respond to errors by erasing files until errors are gone. More recent filesystem designs contain enough redundancy in their metadata that it is now possible to regenerate data structures when non-catastrophic errors occur. Over the past few years, XFS has added a storage space reverse mapping index to make it easy to find which files or metadata objects think they own a particular range of storage. Efforts are under way to develop a similar reverse mapping index for the naming hierarchy, which will involve storing directory parent pointers in each file. With these two pieces in place, XFS can use that secondary information to perform more sophisticated repairs.

Existing Tools

The online fsck tool described here will be the third tool in the history of XFS (on Linux) to check and repair filesystems. Two programs precede it:

The first program, xfs_check, was created as part of the XFS debugger (xfs_db) and can only be used with unmounted filesystems. It walks all metadata in the filesystem looking for inconsistencies in the metadata, though it lacks any ability to repair what it finds. Due to its high memory requirements and inability to repair things, this program is now deprecated and will not be discussed further.

The second program, xfs_repair, was created to be faster and more robust than the first program. Like its predecessor, it can only be used with unmounted filesystems. It uses extent-based in-memory data structures to reduce memory consumption, and tries to schedule readahead IO appropriately to reduce I/O waiting time while it scans the metadata of the entire filesystem. The most important feature of this tool is its ability to respond to inconsistencies in file metadata and directory tree by erasing files as needed to eliminate problems. All other space usage metadata are rebuilt from the observed file metadata.

Problem Statement

The current XFS tools leave several problems unsolved:

  1. User programs suddenly lose access to information in the computer when unexpected shutdowns occur as a result of silent corruptions in the filesystem metadata. These occur unpredictably and often without warning.
  2. System administrators cannot schedule a maintenance window to deal with corruptions if they lack the means to assess filesystem health while the filesystem is online.
  3. Users experience a total loss of service during the recovery period after an unexpected shutdown occurs.
  4. Fleet monitoring tools cannot automate periodic checks of filesystem health when doing so requires manual intervention and downtime.
  5. The filesystem is also completely inaccessible to users if the filesystem is taken offline to look for problems proactively.
  6. Data owners cannot check the integrity of their stored data without reading all of it. This may expose them to substantial billing costs when a linear media scan might suffice.
  7. Users can be tricked into doing things they do not desire when malicious actors exploit quirks of Unicode to place misleading names in directories.

Having defined the problems we would like to solve and the actors affected by that lack of solutions, let us move on to the proposed solution.

This new third program has three components: an in-kernel facility to check metadata, an in-kernel facility to repair metadata, and a userspace driver program to drive fsck activity on a live filesystem. xfs_scrub is the name of the driver program. The rest of this document presents the goals and use cases of the new fsck tool, describes its major design points in connection to those goals, and discusses the similarities and differences with existing tools.

Note:
Throughout this document, the existing offline fsck tool may be referred to by its current name “xfs_repair”. The two kernel pieces may be referred to as “online scrub” or “online repair”, and the driver program will be referred to as “xfs_scrub”.

Secondary metadata indices give us the opportunity to reconstruct parts of a damaged primary metadata object from secondary information. XFS filesystems shard themselves into multiple primary objects to enable better performance on highly threaded systems and to contain the blast radius when problems happen. The naming hierarchy is broken up into objects known as directories; and the physical space is split into pieces known as allocation groups. The division of the filesystem into principal objects means that there are ample opportunities to perform targeted checks and repairs on a subset of the filesystem. While this is going on, other parts continue processing IO requests. Even if a piece of filesystem metadata can only be regenerated by scanning the entire system, the scan can still be done in the background while other file operations continue.

In summary, online fsck takes advantage of resource sharding and redundant metadata to enable targeted checking and repair operations while the system is running. This capability will be coupled to automatic system management so that autonomous self-healing of XFS maximizes service availability.

Theory of Operation

Because it is necessary for online fsck to lock and scan live metadata objects, online fsck consists of two separate code components. The first is the userspace driver program xfs_scrub, which is responsible for identifying individual metadata items, scheduling work items for them, reacting to the outcomes appropriately, and reporting results to the system administrator. The second is the kernel, which must implement functions to check and repair each type of online fsck work item.

Note:
For brevity, this document shortens the phrase “online fsck work item” to “scrub item”.

Scrub item types are delineated in a manner consistent with the Unix design philosophy, which is to say that each item should handle one aspect of a metadata structure, and handle it well.

Scope

Broadly speaking, online fsck should be able to check and to repair nearly everything that the offline fsck program can handle. However, implicit in the adjective online is the limitation that online fsck cannot deal with anything that prevents the filesystem from mounting. Because of this, maintenance of the offline fsck tool will continue. A second limitation of online fsck is that it must follow the same resource sharing and lock acquisition rules as the regular filesystem. This means that scrub cannot take any shortcuts to save time, because doing so could lead to concurrency problems. In other words, online fsck will never be able to fix 100% of the inconsistencies that offline fsck can repair, and a complete run of online fsck may take longer. However, both of these limitations are acceptable tradeoffs to satisfy the different motivation of online fsck, which is to minimize system downtime and to increase predictability of operation.

Phases of Work

The userspace driver program xfs_scrub splits the work of checking and repairing an entire filesystem into seven phases. Each phase concentrates on checking specific types of scrub items and depends on the success of all previous phases. The seven phases are as follows:

  1. Collect geometry information about the mounted filesystem and computer, discover the online fsck capabilities of the kernel, and open the underlying storage devices.
  2. Check allocation group metadata, all realtime volume metadata, and all quota files. Each metadata structure is scheduled as a separate scrub item. If corruption is found in the inode header or btree and repairs are permitted, the repairs are performed early to prepare for phase 3. Optimizations and all other repairs are deferred to phase 4.
  3. Check all metadata of every file in the filesystem. Each metadata structure is also scheduled as a separate scrub item. Repairs, if permitted, are attempted as soon as they are found. If any problems were found during phase 2, all repairs are deferred to phase 4. Optimizations and unsuccessful repairs are deferred to phase 4.
  4. All remaining repairs and scheduled optimizations are performed during this phase, if the caller permitted this; if there is no work to be done, this phase is skipped. Before starting repairs, the summary counters are checked and any necessary repairs are performed so that subsequent repairs proceed with accurate resource reservations. Unsuccesful repair attempts will be requeued as long as forward progress on repairs is made anywhere in the filesystem. Free space in the filesystem is trimmed at the end of phase 4 if the filesystem is clean.
  5. By the start of this phase, all filesystem metadata (with the possible exception of summary information) should be correct. Any summary information that has not previously been checked is checked now. Next, directory entry names and extended attribute names are checked for suspicious entries such as control characters or confusing Unicode sequences appearing in names.
  6. Read all allocated and written data file extents in the filesystem, if the caller asked for a media scan. The ability to use hardware-assisted data file integrity checking is new to online fsck; neither of the previous tools have this capability.
  7. The final phase re-checks the summary counters and presents the caller with a summary of space usage and file counts.

This allocation of responsibilities will be revisited later in this document.

Steps for Each Scrub Item

The kernel scrub code uses a three-step strategy for checking and repairing the aspect of a metadata object represented by a scrub item:

  1. The scrub item of interest is checked for corruptions; opportunities for optimization; and for values that are directly controlled by the system administrator but look suspicious. If the item is not corrupt or does not need optimization, the positive scan results are returned to userspace and no further action is necessary. If the item is corrupt or could be optimized but the caller did not permit this, the negative scan results are returned to userspace. Otherwise, the kernel moves on to the second step.
  2. For the second step, resources and locks obtained in the first step are retained, and the repair function is called. Repair functions will generally choose rebuild a structure from other metadata rather than try to salvage the existing structure. If the repair fails, the scan results from the first step are returned to userspace. Otherwise, the kernel moves on to the third step.
  3. In the third step, the kernel runs the same checks over the new metadata item to assess the efficacy of the repairs. The results of the third step are returned to userspace.

Classification of Metadata

Each type of metadata object (and therefore each type of scrub item) can be classified as follows:

Primary Metadata

Metadata structures in this category should be most familiar to filesystem users either because they are directly created by the user or they index objects created by the user Most filesystem objects fall into this class. Resource and lock acquisition for scrub code follows the same order as regular filesystem accesses.

Primary metadata objects are the simplest for scrub to process. The principal filesystem object (either an allocation group or an inode) that owns the item being scrubbed is locked to guard against concurrent updates. The check function examines every record associated with the type for obvious errors and cross-references healthy records against other metadata to look for inconsistencies. Repairs for this class of scrub item are simple, since the repair function starts by holding all the resources acquired in the previous step. The repair function scans available metadata as needed to record all the observations needed to complete the structure. Next, it stages the observations in a new ondisk structure and commits it atomically to complete the repair. Finally, the storage from the old data structure are carefully reaped.

Because we lock a primary object for the duration of the repair, this is effectively an offline repair operation performed on a subset of the filesystem. This minimizes the complexity of the repair code because it is not necessary to handle concurrent updates from other threads, nor is it necessary to access any other part of the filesystem. As a result, indexed structures can be rebuilt very quickly, and programs trying to access the damaged structure will be blocked until repairs complete. The only infrastructure needed by the repair code are the staging area for observations and a means to write new structures to disk. Despite these limitations, the advantage that online repair holds is clear: targeted work on individual shards of the filesystem avoids total loss of service.

This mechanism is described in section 2.1 (“Off-Line Algorithm”) of V. Srinivasan and M. J. Carey, “Performance of On-Line Index Construction Algorithms”, Extending Database Technology, pp. 293-309, 1992.

Most primary repair functions stage their intermediate results in an in-memory array prior to formatting the new ondisk structure, which is very similar to the list-based algorithm discussed in section 2.3 (“List-Based Algorithms”) of Srinivasan. However, any data structure builder that maintains a resource lock for the duration of the repair is always an offline algorithm.

Secondary Metadata

Metadata structures in this category reflect records found in primary metadata, but are only needed for online fsck or for reorganization of the filesystem. Resource and lock acquisition for scrub code do not follow the same order the same paths as regular filesystem access, and may involve full filesystem scans.

Secondary metadata objects are difficult for scrub to process, because scrub attaches to the secondary object but needs to check primary metadata, which runs counter to the usual acquisition order. Check functions can be limited in scope to reduce runtime. Repairs, however, require a full scan of primary metadata, which can take a long time to complete. For both of these reasons, we cannot lock resources for the entire duration of the repair.

Instead, repair functions set up an in-memory staging structure to store observations. Depending on the requirements of the specific repair function, the staging index can have the same format as the ondisk structure, or it can have a design specific to that repair function. The second step is to release all locks and start the filesystem scan. When the repair scanner needs to record an observation, the staging data are locked long enough to apply the update. Simultaneously, the repair function hooks relevant parts of the filesystem to apply updates to the staging data if the the update pertains to an object that has already been scanned by the index builder. Once the scan is done, the owning object is re-locked, the live data is used to write a new ondisk structure, and the repairs are committed atomically. The hooks are disabled and the staging staging area is freed. Finally, the storage from the old data structure are carefully reaped.

Introducing concurrency helps us to avoid various locking problems, but at a high cost to code complexity. Live filesystem code has to be hooked so that the repair function can observe updates in progress. The staging area has to become a fully functional parallel structure so that updates can be merged from the hooks. Finally, the hook, the filesystem scan, and the inode locking model must be sufficiently well integrated that a hook event can decide if a given update should be applied to the staging structure.

In theory, the scrub implementation could apply these same techniques for primary metadata, but doing so would make it massively more complex and less performant. Programs attempting to access the damaged structures are not blocked from operation, which may cause application failure or an unplanned filesystem shutdown.

Inspiration for the secondary metadata repair strategy was drawn from section 2.4 of Srinivasan above, and sections 2 (“NSF: Inded Build Without Side-File”) and 3.1.1 (“Duplicate Key Insert Problem”) in C. Mohan, “Algorithms for Creating Indexes for Very Large Tables Without Quiescing Updates”, 1992.

The sidecar index mentioned above bears some resemblance to the side file method mentioned in Srinivasan and Mohan. Their method consists of an index builder that extracts relevant record data to build the new structure as quickly as possible; and an auxiliary structure that captures all updates that would be committed to the index by other threads were the new index already online. After the index building scan finishes, the updates recorded in the side file are applied to the new index. To avoid conflicts between the index builder and other writer threads, the builder maintains a publicly visible cursor that tracks the progress of the scan through the record space. To avoid duplication of work between the side file and the index builder, side file updates are elided when the record ID for the update is greater than the cursor position within the record ID space.

To minimize changes to the rest of the codebase, XFS online repair keeps the replacement index hidden until it’s completely ready to go. In other words, there is no attempt to expose the keyspace of the new index while repair is running. As a result, online repair uses an indexed side file (the in-memory btree) to determine what goes in the new ondisk structure and a scan cursor to control what goes into the side file.

Summary Information

Metadata structures in this last category summarize the contents of primary metadata records. These are often used to speed up resource usage queries, and are many times smaller than the primary metadata which they represent. Check and repair both require full filesystem scans, but resource and lock acquisition follow the same paths as regular filesystem accesses.

The superblock summary counters have special requirements due to the underlying implementation of the incore counters, and will be treated separately. Check and repair of the other types of summary counters (quotas and file link counts) employ the same filesystem scanning and hooking techniques as outlined above, but because the underlying data are arrays of integer counters, the staging data need not be a fully functional mirror of the ondisk structure.

Inspiration for quota and file link count repair strategies were drawn from sections 2.12 (“Online Index Operations”) through 2.14 (“Incremental View Maintenace”) of G. Graefe, “Concurrent Queries and Updates in Summary Views and Their Indexes”, 2011.

Since quotas are non-negative integer counts of resource usage, online quotacheck can use the incremental view deltas described in section 2.14 to track pending changes to the block and inode usage counts in each transaction, and commit those changes to a dquot side file when the transaction commits. Delta tracking is necessary for dquots because the index builder scans inodes, whereas the data structure being rebuilt is an index of dquots. Link count checking combines the view deltas and commit step into one because we’re setting attributes of the objects being scanned, and not building a separate data structure. Each online fsck function will be discussed as case studies later in this document.

Severability

Online fsck is not necessarily a universally desirable feature for all use cases. Users who demand maximum performance at any cost, including repairability, are not going to want to pay any overhead associated with this feature. To that end, the reverse mapping space index and directory parent pointers can be disabled at format time. Distributors who do not wish to support this feature can disable it from the kernel build with Kconfig, because the online fsck implementation is largely self-contained. Major functionality in the main filesystem that only exist to serve scrub are disabled when online fsck is not built. The userspace driver program and its associated background xfs_scrub can also be stripped from the xfsprogs build.

Testing Plan

As stated before, fsck tools have three main goals:

  1. Detect inconsistencies in the metadata;
  2. Eliminate those inconsistencies; and
  3. Minimize further loss of data.

Demonstrations of correct operation are necessary to build users’ confidence that the software behaves within expectations. Unfortunately, it was not really feasible to perform regular exhaustive testing of every aspect of a fsck tool until the introduction of low-cost virtual machines with high-IOPS storage. With ample hardware availability in mind, the testing strategy for the online fsck project involves differential analysis against the existing fsck tools and systematic testing of every type of metadata. Testing capacity can be split into four major categories, as discussed below.

Integrated Testing with fstests

The primary goal of any free software QA effort is to make testing as inexpensive and widespread as possible to maximize the scaling advantages of community. In other words, we want to maximize the breadth of filesystem configuration scenarios and hardware setups. This improves code quality by enabling the authors of online fsck to find and fix bugs early, and helps developers of new features to find integration issues earlier in their development effort.

The Linux filesystem community shares a common QA testing suite, fstests, for functional and regression testing. Even before development work began on online fsck, fstests (when run on XFS) would run both the xfs_check and xfs_repair -n commands on the test and scratch filesystems between each test. This provides a level of assurance that the kernel and the fsck tools stay in alignment about what constitutes consistent metadata. During development of the online checking code, fstests was modified to run xfs_scrub -n between each test to ensure that the new checking code produces the same rresults as the two existing fsck tools.

To start development of online repair, fstests was modified to run xfs_repair to rebuild the filesystem’s metadata indices between tests. This ensures that offline repair does not crash, leave a corrupt filesystem after it exists, or trigger complaints from the online check. This also established a baseline for what can and cannot be repaired offline. To complete the first phase of development of online repair, fstests was modified to be able to run xfs_scrub in a “force rebuild” mode. This enables a comparison of the effectiveness of online repair as compared to the existing offline repair tools.

General Fuzz Testing of Metadata Blocks

XFS benefits greatly from having a very robust debugging tool, xfs_db.

Before development of online fsck even began, a set of fstests were created to test the rather common fault that entire metadata blocks get corrupted. This required the creation of fstests library code that can create a filesystem containing every possible type of metadata object. Next, individual test cases were created to create a test filesystem, identify a single block of a specific type of metadata object, trash it with the existing blocktrash command in xfs_db, and test the reaction of a particular metadata validation strategy.

This earlier test suite enabled XFS developers to test the ability of the in-kernel validation functions and the ability of the offline fsck tool to detect and eliminate the inconsistent metadata. This part of the test suite was extended to cover online fsck in exactly the same manner.

In other words, for a given fstests configuration, we can check that:

  • For each metadata object existing on the filesystem, we can write garbage to it and…
    • …test the reactions of:
      1. The kernel verifiers to stop obviously bad metadata
      2. Offline repair (xfs_repair) to detect and fix
      3. Online repair (xfs_scrub) to detect and fix

Targeted Fuzz Testing of Metadata Records

A quick conversation with the other XFS developers revealed that the existing test infrastructure should be extended to provide a much more powerful facility: targeted fuzz testing of every metadata field in the filesystem. xfs_db can modify every field of every metadata structure in every block in the filesystem to simulate the effects of memory corruption and software bugs. Given that fstests already contains the ability to create a filesystem containing every metadata format known to the filesystem, we can use xfs_db to perform exhaustive fuzz testing!

For a given fstests configuration, we can check that:

  • For each metadata object existing on the filesystem…

    • For each record inside that metadata object…

      • For each field inside that record…

        • For each conceivable type of transformation that can be applied to a bit field…

          1. Clear all bits
          2. Set all bits
          3. Toggle the most significant bit
          4. Toggle the middle bit
          5. Toggle the least significant bit
          6. Add a small quantity
          7. Subtract a small quantity
          8. Randomize the contents
          • …we can test the reactions of:
            1. The kernel verifiers to stop obviously bad metadata
            2. Offline checking (xfs_repair -n)
            3. Offline repair (xfs_repair)
            4. Online checking (xfs_scrub -n)
            5. Online repair (xfs_scrub)
            6. Both repair tools (xfs_scrub and then xfs_repair if that didn’t work)

This is quite the combinatoric explosion!

Fortunately, having this much test coverage makes it easy for XFS developers to check the responses of XFS’ fsck tools. Since the introduction of the fuzz testing framework, these tests have been used to discover incorrect repair code and missing functionality for entire classes of metadata objects in xfs_repair. They have also been used to finalize the deprecation of xfs_check by confirming that xfs_repair could detect at least as many corruptions.

These tests have been very valuable for xfs_scrub in the same ways – they allow the online fsck developers to compare online fsck against offline fsck, and they enable us to find deficiencies in the code base.

Proposed patchsets include general fuzzer improvements, fuzzing baselines, and improvements in fuzz testing comprehensiveness.

Stress Testing

A unique requirement to online fsck is the ability to operate on a filesystem concurrently with regular workloads. Although it is of course impossible to run xfs_scrub with zero observable impact on the running system, the online repair code should never introduce inconsistencies into the filesystem metadata, and regular workloads should never notice resource starvation. To verify that these conditions are being met, fstests will be enhanced in the following ways:

  • For each scrub item type, create a test to exercise checking that item type while running fsstress.
  • For each scrub item type, create a test to exercise repairing that item type while running fsstress.
  • Race fsstress and xfs_scrub -n to ensure that checking the whole filesystem doesn’t cause problems.
  • Race fsstress and xfs_scrub in force-rebuild mode to ensure that force-repairing the whole filesystem doesn’t cause problems.
  • Race xfs_scrub in check and force-repair mode against fsstress while freezing and thawing the filesystem.
  • Race xfs_scrub in check and force-repair mode against fsstress while remounting the filesystem read-only and read-write.
  • The same, but running fsx instead of fsstress. (Not done yet?)

Success is defined by the ability to run all of these tests without observing any unexpected filesystem shutdowns due to corrupted metadata, kernel hang check warnings, or any other sort of mischief.

Proposed patchsets include general stress testing and the evolution of existing per-function stress testing. Each kernel patchset adding an online repair function will use the same branch name across the kernel, xfsprogs, and fstests git repos.

User Interface

Like offline fsck, the primary user of online fsck should be the system administrator. Online fsck presents two modes of operation to administrators: A foreground CLI process for online fsck on demand, and a background service that performs autonomous checking and repair.

Checking on Demand

For administrators who want the absolute freshest information about the metadata in a filesystem, xfs_scrub can be run as a foreground process on a command line. The program checks every piece of metadata in the filesystem while the administrator waits for the results to be reported, just like the existing xfs_repair tool. Both tools share a -n option to perform a read-only scan, and a -v option to increase the verbosity of the information reported.

A new feature of xfs_scrub is the -x option, which employs the error correction capabilities of the hardware to check data file contents. The media scan is not enabled by default because it may dramatically increase program runtime and consume a lot of bandwidth on older storage hardware.

The output of a foreground invocation will be captured in the system log.

The xfs_scrub_all program walks the list of mounted filesystems and initiates xfs_scrub for each of them in parallel. It serializes scans for any filesystems that resolve to the same top level kernel block device to prevent resource overconsumption.

Background Service

To reduce the workload of system administrators, the xfs_scrub package provides a suite of systemd timers and services that run online fsck automatically on weekends. The background service configures scrub to run with as little privilege as possible (which is quite a lot), the lowest IO priority, and in a single threaded mode to minimize the amount of load generated on the system to avoid starving regular workloads.

The output of the background service will also be captured in the system log. If desired, reports of failures (either due to inconsistencies or mere runtime errors) can be emailed automatically by setting the EMAIL_ADDR environment variable in the following service files:

  • xfs_scrub_fail@.service
  • xfs_scrub_media_fail@.service
  • xfs_scrub_all_fail.service

The decision to enable the background scan is left to the system administrator. This can be done by enabling either of the following services:

  • xfs_scrub_all.timer on systemd systems to enable a weekly scan of the metadata of all mounted filesystems.
  • xfs_scrub_all.cron can be used on non-systemd systems to schedule a weekly scan of all mounted filesystems.

The automatic weekly scan is configured out of the box to perform an additional media scan of all file data once per month. This is less foolproof than, say, storing file data block checksums, but much more performant if application software provides its own integrity checking, redundancy can be provided elsewhere above the filesystem, or the storage device’s integrity guarantees are deemed sufficient.

Question: Are we using systemd unit directives to their maximum advantage to isolate the scrub process and control its resource usage? Question: Should we document how system administrators can modify the xfs_scrub@ service file to contain the QoS hit? Or do we assume admins are familiar with existing systemd documentation? Where do we even document that?

Proposed patchsets include enabling the background service.

Health Reporting

XFS caches a summary of each filesystem’s health status in memory. The information is updated whenever xfs_scrub is run, as well as whenever inconsistencies are detected in the filesystem metadata. System administrators can use the health command of xfs_spaceman to download this information into a human-readable format. If problems have been observed, the administrator can decide to schedule a reduced service window in which to run the online repair tool to correct the problem. Failing that, the administrator can decide to schedule a maintenance window to run the traditional offline repair tool to correct the problem.

Question: Should the health reporting integrate with the new inotify fs error notification system? Question: Should we write a daemon to listen for corruption notifications and initiate a repair?

Proposed patchsets include wiring up health reports to correction returns and preservation of sickness info during memory reclaim.

Kernel Algorithms and Data Structures

In this section, we discuss the key algorithms and data structures of the kernel code that facilitate the ability to check and repair metadata while the system is running. We start with the pieces that provide the foundation for checking metadata and then move on to how XFS actually regenerates itself.

Self Describing Metadata

Starting with XFS version 5 in 2012, XFS updated the format of nearly every ondisk block header to record a magic number, a checksum, a universally “unique” identifier (UUID), an owner code, the ondisk address of the block, and a log sequence number. When loading a block buffer from disk, the magic number, UUID, owner, and ondisk address confirm that the retrieved block matches the specific owner of the current filesystem, and that the information contained in the block is supposed to be found at the ondisk address. The first three components enable checking tools to disregard alleged metadata that doesn’t belong to the filesystem, and the fourth component enables the filesystem to detect lost writes.

The logging code maintains the checksum and the log sequence number of the last transactional update. Checksums are useful for detecting torn writes and other mischief between the computer and its storage devices. Sequence number tracking enables log recovery to avoid applying out of date log updates to the filesystem.

These two features improve overall runtime resiliency by providing a means for the filesystem to detect obvious corruption when reading metadata blocks from disk, but these buffer verifiers cannot provide any consistency checking between metadata structures.

For more details, see Documentation/filesystems/xfs-self-describing-metadata.rst.

Reverse Mapping

The original design of XFS (circa 1993) is an improvement upon 1980s Unix filesystem design. In those days, storage density was expensive, CPU time was scarce, and excessive seek time could kill performance. For performance reasons, filesystem authors were reluctant to add redundancy to the filesystem, even at the cost of data integrity. Filesystems designers in the early 21st century chose different strategies to increase internal redundancy – either by storing nearly identical copies of metadata, or through more space-efficient techniques such as erasure coding. Obvious corruptions are typically repaired by copying replicas or reconstructing from codes.

For XFS, a different redundancy strategy was chosen: the addition of a secondary space usage index that maps allocated disk extents back to their owners. By adding a new index, the filesystem retains most of its ability to scale well to heavily threaded workloads involving large datasets, since the primary file metadata (the directory tree, the file block map, and the allocation groups) remain unchanged. Although the reverse-mapping feature increases overhead costs for space mapping activities just like any other system that improves redundancy, it has one key advantage: the reverse index is key to enabling online fsck and other requested functionality such as filesystem reorganization, better media failure reporting, and shrinking.

A criticism of adding the secondary index is that it does nothing to improve the robustness of user data storage itself. This is valid, but it is a tradeoff – the complexity of the new index is far less than adding volume management and storage device mirroring to XFS. Perfection of RAID 1 and device remapping are best left to existing layers in the kernel.

The information captured in a reverse space mapping record is as follows:

struct xfs_rmap_irec {
    xfs_agblock_t    rm_startblock;   /* extent start block */
    xfs_extlen_t     rm_blockcount;   /* extent length */
    uint64_t         rm_owner;        /* extent owner */
    uint64_t         rm_offset;       /* offset within the owner */
    unsigned int     rm_flags;        /* state flags */
};

The first two fields capture the location and size of the physical space, in units of filesystem blocks. The owner field tells us which metadata structure or file inode have been assigned this space. For space allocated to files, the offset field tells us where the space was mapped within the file fork. Finally, the flags field provides extra information about the space usage usage – is this an attribute fork extent? A file mapping btree extent? Or an unwritten data extent?

Online filesystem checking judges the consistency of each primary metadata record by comparing its space allocation information against all other space indices. The reverse mapping index plays a key role in the consistency checking process because it contains a second copy of all space allocation information. However, program runtime and ease of resource acquisition are the only real limits to what online checking can consult. For example, a file data extent mapping can be checked against:

  • The absence of an entry in the free space information.
  • The absence of an entry in the inode index.
  • The absence of an entry in the reference count data if the file is not marked as having shared extents.
  • The correspondence of an entry in the reverse mapping information.

A key observation here is that only the reverse mapping can provide a positive affirmation of correctness if the primary metadata is in doubt. The checking code for most primary metadata follows a path similar to the one outlined above.

A second observation to make about this secondary index is that proving its consistency with the primary metadata is difficult. Demonstrating that a given reverse mapping record exactly corresponds to the primary space metadata involves a full scan of all primary space metadata, which is very time intensive. Furthermore, scanning activity for online fsck can only use non-blocking lock acquisition primitives if the locking order is not the regular order as used by the rest of the filesystem. Technically speaking, this means that forward progress during this part of a scan of the reverse mapping data cannot be guaranteed if system load is especially heavy. For this reason, it is not practical for online check to detect reverse mapping records that lack a counterpart in the primary metadata. Instead, we rely on rigorous cross-referencing during the primary space mapping structure checks.

Reverse mappings play a key role in reconstruction of primary metadata. The secondary information is general enough for online repair to synthesize a complete copy of any primary space management metadata by locking that resource, querying all reverse mapping indices looking for records matching the relevant resource, and transforming the mapping into an appropriate format. The details of how these records are staged, written to disk, and committed into the filesystem will be covered in subsequent sections.

Checking and Cross-Referencing

The first step of checking a metadata structure is to examine every record contained within the structure and its relationship with the rest of the system. XFS contains multiple layers of checking to try to prevent inconsistent metadata from wreaking havoc on the system. Each of these layers contributes information that helps the kernel to make three decisions about the health of a metadata structure:

  • Is a part of this structure obviously corrupt (XFS_SCRUB_OFLAG_CORRUPT) ?
  • Is this structure inconsistent with the rest of the system (XFS_SCRUB_OFLAG_XCORRUPT) ?
  • Is there so much damage around the filesystem that cross-referencing is not possible (XFS_SCRUB_OFLAG_XFAIL) ?
  • Can the structure be optimized to improve performance or reduce the size of metadata (XFS_SCRUB_OFLAG_PREEN) ?
  • Does the structure contain data that is not inconsistent but deserves review by the system administrator (XFS_SCRUB_OFLAG_WARNING) ?

The following sections describe how the metadata scrubbing process works.

Metadata Buffer Verification

The lowest layer of metadata protection in XFS are the metadata verifiers built into the buffer cache. These functions perform inexpensive internal consistency checking of the block itself, and answer these questions:

  • Does the block belong to this filesystem?
  • Does the block belong to the structure that asked for the read? This assumes that metadata blocks only have one owner, which is always true in XFS.
  • Is the type of data stored in the block within a reasonable range of what we were expecting?
  • Does the physical location of the block match the location we read from?
  • Does the block checksum match the data?

The scope of the protections here are very limited – they can only establish that the filesystem code is reasonably free of gross corruption bugs and that the storage system is reasonably competent at retrieval. Corruption problems observed at runtime cause the generation of health reports, failed system calls, and in the extreme case, filesystem shutdowns if the corrupt metadata force the cancellation of a dirty transaction.

Every online fsck scrubbing function is expected to read every ondisk metadata block of a structure in the course of checking the structure. Corruption problems observed during a check are immediately reported to userspace as corruption; during a cross-reference, they are reported as a failure to cross-reference once the full examination is complete. Reads satisfied by a buffer already in cache (and hence already verified) bypass these checks.

Internal Consistency Checks

The next higher level of metadata protection are the internal record verification code built into the filesystem. These checks are split between the buffer verifiers, the in-filesystem users of the buffer cache, and the scrub code itself, depending on the amount of higher level context required. The scope of checking is still internal to the block. For performance reasons, regular runtime code may skip some of these checks unless debugging is enabled or a write is about to occur. Scrub functions, of course, must check all possible problems. These higher level checking functions answer these questions:

  • Does the type of data stored in the block match what we were expecting?
  • Does the block belong to the owning structure that asked for the read?
  • If the block contains records, do the records fit within the block?
  • If the block tracks internal free space information, is it consistent with the record areas?
  • Are the records contained inside the block free of obvious corruptions?

Record checks in this category are more rigorous and more time-intensive. For example, block and inode pointers are checked to ensure that they point within the dynamically allocated parts of an allocation group and within the filesystem. Names are checked for invalid characters, and flags are checked for invalid combinations. Other record attributes are checked for sensible values. Btree records spanning an interval of the btree keyspace are checked for correct order and lack of mergeability (except for file fork mappings).

Validation of Userspace-Controlled Record Attributes

Various pieces of filesystem metadata are directly controlled by userspace. Because of this nature, validation work cannot be more precise than checking that a value is within the possible range. These fields include:

  • Superblock fields controlled by mount options
  • Filesystem labels
  • File timestamps
  • File permissions
  • File size
  • File flags
  • Names present in directory entries, extended attribute keys, and filesystem labels
  • Extended attribute key namespaces
  • Extended attribute values
  • File data block contents
  • Quota limits
  • Quota timer expiration (if resource usage exceeds the soft limit)

Cross-Referencing Space Metadata

The next higher level of checking is cross-referencing records between metadata structures. For regular runtime code, the cost of these checks is considered prohibitively expensive, but as scrub is dedicated to rooting out inconsistencies, it pursues all avenues of inquiry. The exact set of cross-referencing is highly dependent on the context of the data structure being checked.

The XFS btree code has keyspace scanning functions that online fsck uses to cross reference one structure with another. Specifically, they can scan the key space of an index to determine if that keyspace is fully, sparsely, or not at all mapped to records. For the reverse mapping btree, it is possible to mask parts of the key for the purposes of performing a keyspace scan. This enables us to decide if the rmap btree contains records mapping a certain amount of physical space regardless of the actual owners.

Space allocation records are cross-referenced as follows:

  1. Any space mentioned by any metadata structure are cross-referenced as follows:
    • Does the reverse mapping index list only the appropriate owner as the owner of each block?
    • Are none of the blocks claimed as free space?
    • If these aren’t file data blocks, are none of the blocks claimed as space shared by different owners?
  2. Btree blocks are cross-referenced as follows:
    • Everything in class 1 above.
    • If there’s a parent node block, do the keys listed for this block match the keyspace of this block?
    • Do the sibling pointers point to valid blocks? Of the same level?
    • Do the child pointers point to valid blocks? Of the next level down?
  3. Free space btree records are cross-referenced as follows:
    • Everything in class 1 and 2 above.
    • Does the reverse mapping index list no owners of this space?
    • Is this space not claimed by the inode index for inodes?
    • Is it not mentioned by the reference count index?
    • Is there a matching record in the other free space btree?
  4. Inode btree records are cross-referenced as follows:
    • Everything in class 1 and 2 above.
    • Is there a matching record in free inode btree?
    • Do inodes outside of the holemask correspond with inode clusters?
    • Do inodes in the freemask correspond with inode records with zero link count?
  5. Inode records are cross-referenced as follows:
    • Everything in class 1.
    • Do all the fields that summarize information about the file forks actually match those forks?
    • Does each inode with zero link count correspond to a record in the free inode btree?
  6. File fork space mapping records are cross-referenced as follows:
    • Everything in class 1 and 2 above.
    • Is this space not mentioned by the inode btrees?
    • If this is a CoW fork mapping, does it correspond to a CoW entry in the reference count btree?
  7. Reference count records are cross-referenced as follows:
    • Everything in class 1 and 2 above.
    • Within the space subkeyspace of the rmap btree (that is to say, all records mapped to a particular space extent and ignoring the owner info), can we find the same number of records for each block as the listed reference count?

Proposed patchsets are the series to find gaps in refcount, inode, and rmap records; to find mergeable records; and to improve cross referencing with rmap before starting a repair.

Cross-Referencing Directory Entries

The filesystem directory tree is, like any tree, a directed acylic graph structure. Each directory contains a number of directory entries which associate a name with an inode number. Directory entries can be cross-referenced as follows:

  • Is the inode number valid?
  • Does it point to an inode with nonzero link count?
  • Does the entry’s file type match the file mode?
  • If the child is a subdirectory, does its dotdot pointer point back to the parent?

Checking operations involving parents and file link counts are discussed in more detail in later sections.

Cross-Referencing Summary Counters

XFS maintains three classes of summary counters: available resources, quota resource usage, and file link counts.

In theory, the amount of available resources (data blocks, inodes, realtime extents) can be found by walking the entire filesystem. This would make for very slow reporting, so a transactional filesystem can maintain summaries of this information in the superblock. Cross-referencing these values against the filesystem metadata should be a simple matter of walking the free space and inode metadata in each AG and the realtime bitmap, but there are complications that will be discussed in more detail later.

Quota usage and file link count checking are sufficiently complicated that they get their own sections.

Post-Repair Reverification

After performing a repair, the checking code is run a second time to validate the new structure, and the results of the health assessment are recorded internally and returned to the calling process. This step is critical for enabling system administrator to monitor the status of the filesystem and the progress of any repairs. For developers, it is a useful means to judge the efficacy of error detection and correction in the online and offline checking tools.

Eventual Consistency vs. Online Fsck

Midway through the development of online scrubbing, misinteractions were observed between online fsck and compound transaction chains created by other writer threads that resulted in false reports of metadata inconsistency. The root cause of these reports is the eventual consistency model introduced by the expansion of deferred work items and compound transaction chains when reverse mapping and reflink were introduced.

Originally, transaction chains were added to XFS to avoid deadlocks when unmapping space from files. Deadlock avoidance rules require that AGs only be locked in increasing order, which makes it impossible (say) to free a space extent in AG 7 and then try to free a now superfluous block mapping btree block in AG 3. To avoid these kinds of deadlocks, XFS creates Extent Freeing Intent (EFI) log items so that we can commit to freeing some space in one transaction and put off making the actual metadata updates to a fresh transaction. The transaction sequence looks like this:

  1. The first transaction contains a physical update to the file’s block mapping structures to remove the mapping from the btree blocks. It then attaches to the in-memory transaction an action item (struct xfs_defer_pending) to schedule deferred freeing of space. Returning to the example above, the action item tracks the freeing of both the unmapped space from AG 7 and the block mapping btree (BMBT) block from AG 3. Deferred frees recorded in this manner are committed in the log by creating an EFI log item from the action item, and attaching the log item to the transaction. When the log is persisted to disk, the EFI item is written into the ondisk transaction record. EFIs can list up to 16 extents to free, all sorted in AG order.
  2. The second transaction contains a physical update to the free space btrees of AG 7 to release the unmapped file space and a second physical update to the free space btrees of AG 3 to release the former BMBT block. Attached to the transaction is a an extent free done (EFD) log item. The EFD contains a pointer to the EFI logged in transaction #1 so that log recovery can tell if the EFI needs to be replayed.

If the system goes down after transaction #1 is written back to the filesystem but before #2 is committed, a scan of the filesystem metadata would show inconsistent filesystem metadata because there would not appear to be any owner of the unmapped space. Happily, this inconsistency is also resolved by log recovery – if it recovers an intent log item but does not recover a corresponding intent done log item, it will replay the unfinished intent item. In the example above, the log must replay both frees described in the recovered EFI to complete the recovery phase.

There are two subtleties to XFS’ transaction chaining strategy to consider. The first is that log items must be added to a transaction in the correct order to prevent conflicts with principal objects that are not held by the transaction. In other words, all per-AG metadata updates for an unmapped block must be completed before the last update to free the extent. The second subtlety to consider is the fact that AG header buffers are (usually) released between each transaction in a chain. This means that other threads can observe an AG in an intermediate state, but as long as the first subtlety is handled, this should not affect the correctness of filesystem operations. Unmounting the filesystem flushes all pending work to disk, which means that offline fsck never sees the temporary inconsistencies caused by deferred work item processing. In this manner, XFS employs a form of eventual consistency to avoid deadlocks and increase parallelism.

When the reverse mapping and reflink features were under development, it was deemed impractical to try to cram all the reverse mapping updates into a single transaction because a single file mapping operation can explode into many small updates:

  • The block mapping update itself
  • A reverse mapping update for the block mapping update
  • Fixing the freelist
  • A reverse mapping update for the freelist fix
  • A shape change to the block mapping btree
  • A reverse mapping update for the btree update
  • Fixing the freelist (again)
  • A reverse mapping update for the freelist fix
  • An update to the reference counting information
  • A reverse mapping update for the refcount update
  • Fixing the freelist (a third time)
  • A reverse mapping update for the freelist fix
  • Freeing any space that was unmapped and not owned by any other file
  • Fixing the freelist (a fourth time)
  • A reverse mapping update for the freelist fix
  • Freeing the space used by the block mapping btree
  • Fixing the freelist (a fifth time)
  • A reverse mapping update for the freelist fix

For copy-on-write updates this is even worse, because we have to do this once to remove the space from the staging area, and again to map it into the file!

To deal with this explosion in a calm manner, XFS expanded its use of deferred work items to most reverse mapping updates and all refcount updates. This reduces the worst case size of transaction reservations by breaking the work into a long chain of small updates, which increases the degree of eventual consistency in the system. Again, this generally isn’t a problem because we order the deferred work items carefully to avoid conflicts between owners.

However, online fsck changes the rules – remember that although physical updates to per-AG structures are coordinated by locking the buffers for AG headers, buffer locks are dropped between transactions. Once scrub acquires resources and takes locks for a data structure, it must do all the validation work without releasing the lock. If the lock for a structure is an AG header buffer lock, scrub may have interrupted another thread that is midway through finishing a chain. For example, if the writer thread has completed a reverse mapping update but not the corresponding refcount update, the two AG btrees will appear inconsistent to scrub and an observation of corruption will be recorded. This observation will not be correct. If a repair is attempted in this state, the results will be catastrophic!

Three solutions to this problem were evaluated upon discovery of this flaw:

  1. Add a higher level lock to allocation groups and require writer threads to acquire the higher level lock in AG order. This would be very difficult to implement in practice because we don’t know always know ahead of time which locks we need to grab. Performing a dry run of a file operation to discover necessary locks would make the filesystem very slow.
  2. Make the deferred work coordinator code aware of consecutive intent items targeting the same AG and have it hold the AG header buffers locked across the transaction roll between updates. This would introduce a lot of complexity into the coordinator since it is only loosely coupled with the actual deferred work items. It would also fail to solve the problem because deferred work items can generate new deferred subtasks, but all subtasks must be complete before work can start on a new sibling task.
  3. Recognize that only online fsck has this requirement of total consistency of AG metadata, and that online fsck should be relatively rare as compared to file operations. For each AG, maintain a sloppy count of intent items targetting that AG. When online fsck wants to examine an AG, it should lock the AG header buffers to quiesce all transaction chains that want to modify that AG, and only proceed with the scrub if the count is zero. In other words, scrub only proceeds if it can lock the AG header buffers and there can’t possibly be any intents in progress.

The third solution has been implemented in the current iteration of online fsck, with percpu counters implementing the “sloppy” counter. Updates to the percpu counter from normal writer threads are very fast, which is good for maintaining runtime performance.

There are two key properties to the drain mechanism. First, the counter is incremented when a deferred work item is queued to a transaction, and it is decremented after the associated intent done log item is committed to another transaction. The second property is that deferred work can be added to a transaction without holding an AG header lock, but per-AG work items cannot be marked done without locking that AG header buffer to log the physical updates and the intent done log item. The first property enables scrub to yield to running transaction chains, which is an explicit deprioritization of online fsck to benefit file operations. The second property of the drain is key to the correct coordination of scrub.

The scrub drain works as follows:

  1. Grab the per-AG structure for the AG.
  2. Lock the AGI and AGF header buffers.
  3. If the per-AG intent counter to zero, we know there are no chains in progress and we are good to go.
  4. Otherwise, release the AGI and AGF header buffers.
  5. Wait for the intent counter to reach zero, then go to step 2.

To avoid polling in step 5, the drain provides a waitqueue for scrub threads to be woken up whenever the intent count drops. On architectures that support it, jump labels (aka dynamic code patching) reduces the overhead of the drain waitqueue to nearly zero when scrub is not in use.

The proposed patchset is the scrub intent drain series.

Pageable Kernel Memory

Demonstrations of early prototypes of online repair awoke the XFS community to two new technical requirements that were not originally identified. In the first iteration of online repair, the code walked whatever filesystem metadata it needed to synthesize new records, and inserted records into a new btree as it found them. This was obviously subpar since any additional corruption or runtime errors encountered during the walk would leave the filesystem with a shut down filesystem containing a half-rebuilt data structure. Solving the problem of half-rebuilt data structures will be discussed in the next section.

For the second iteration, the synthesized records were instead stored in kernel slab memory. Doing so enabled online repair to abort without writing to the filesystem if the metadata walk failed, which prevented online fsck from making things worse.

Three unfortunate qualities of kernel memory management make it unsuitable for this purpose. First, although it is tempting to allocate a contiguous block of memory to create a C array, this cannot easily be done in the kernel because it cannot be relied upon to allocate multiple contiguous memory pages. Second, although disparate physical pages can be virtually mapped together, installed memory might still not be large enough to stage the entire record set in memory while constructing a new btree. In response to these two considerations, the implementation was adjusted to use doubly linked lists, which means every record requires two 64-bit list head pointers, which is a lot of overhead. Even this was subpar because of the third unfortunate quality – kernel memory is pinned, which can drive the system out of memory, leading to OOM kills of unrelated processes.

For the third iteration, attention swung back to the possibility of using byte-indexed array-like storage to reduce the overhead of in-memory records. At any given time, online repair does not need to keep the entire record set in memory, which means that individual records can be paged out. Creating new temporary files in the XFS filesystem to store intermediate data was explored and partially rejected because a filesystem with compromised space and inode metadata should never be used to fix compromised space or inode metadata. However, the kernel already has a facility for byte-addressable and pageable storage: shmemfs. In-kernel graphics drivers (most notably i915) take advantage of shmemfs files to store intermediate data that doesn’t need to be completely in memory, so that usage precedent is already established. Hence, the xfile was born!

A survey of the intended uses of xfiles suggested three main use cases:

  1. Storing arrays of fixed-sized records (space management btrees)
  2. Storing large binary objects (blobs) of variable sizes (directory and extended attribute repairs)
  3. Storing sparse arrays of fixed-sized records (quotas, realtime metadata, and link counts)
  4. Staging btrees in memory (reverse mapping btrees)

For security and performance reasons, the shmem files created by XFS must be owned privately by the repair code. This means that they are never installed in the file descriptor table, nor can the xfile’s memory pages be mapped into userspace processes. If the shmem file is shared between threads to stage repairs, the online fsck code must provide its own locks to coordinate access. shmem file pages can only be mapped into the kernel for brief periods of time because the kernel address space is limited and pinned backing pages cannot be written to swap.

Arrays of Fixed-Sized Records

In XFS, each type of indexed space metadata (free space, inodes, reference counts, file fork space, and reverse mappings) consists of a set of fixed-size records indexed with a classic B+ tree. During a repair, scrub needs to stage new records during the gathering step and retrieve them during the btree building step. A simple load/store interface satisfies this requirement. Ultimately, records must be stored in sorted order in btree leaf blocks. Hence it is necessary to sort the staged records before bulk writing them into a new ondisk btree. To stage these records, the xfarray abstraction was born; it is created as a linear byte array atop an xfile.

The proposed patchset is the big in-memory array.

Pagecache and Inode Locking

Loads and stores of array elements are conceptually similar to what pread(2) and pwrite(2) can do in userspace. However, this is not quite how xfile accesses actually work. Recall the statement that every file is privately owned by the online repair worker that created it, and online fsck is expected to coordinate access explicitly. The xfile code directly calls pagecache_write_{begin,end} when storing records, to ensure that the pagecache state is maintained properly. It directly calls shmem_read_mapping_page_gfp when reading records to avoid dealing with the internal structure of shmemfs. In other words, xfiles ignore the VFS read and write code paths to avoid having to create a dummy struct kiocb and to avoid taking inode locks.

Sorting

During the next iteration after the creation of the xfarray, a community reviewer remarked that for performance reasons, online repair ought to load batches of records into btree record blocks instead of inserting records into a new btree one at a time. The btree insertion code in XFS is responsible for maintaining correct ordering of the records, so naturally the xfarray must also support sorting the record set prior to bulk loading.

The sorting algorithm used in the xfarray is actually a combination of adaptive quicksort and heapsort subalgorithms in spirit of Sedgewick and pdqsort, with refinements for the Linux kernel. To sort records in a reasonably short amount of time, we want to take advantage of the binary subpartitioning offered by quicksort, but we also use heapsort to hedge aginst performance collapse if the chosen quicksort pivots are poor. Both algorithms are (in theory) O(n * lg(n)).

The kernel already contains a reasonably performant implementation of heapsort. It only operates on regular C arrays, which limits the scope of its usefulness. There are two key places where the xfarray uses it:

  • Sorting any record subset backed by a single xfile page.
  • Loading a small number of xfarray records from potentially disparate parts of the xfarray into a memory buffer, and sorting the buffer.

In other words, heapsort is used to constrain the nested recursion of quicksort, which is how we mitigate quicksort’s worst runtime behavior.

Choosing a quicksport pivot is known to be tricky business. A good pivot would split the set to sort in half, leading to the O(n * lg(n)) divide and conquer behavior that is crucial to performance. A poor pivot barely splits the subset at all, leading to O(n ^ 2) performance. The xfarray sort routine tries to avoid picking a bad pivot by sampling nine records into a memory buffer and using the kernel heapsort to identify the median of the nine.

The partitioning of quicksort is fairly textbook – rearrange the record subset around the pivot, then set up the current and next stack frames to sort with the larger and the smaller halves of the pivot, respectively. This keeps the stack space requirements to log2(record count).

As a final performance optimization, the hi and lo scanning phase of quicksort keeps examined xfile pages mapped in the kernel for as long as possible to reduce map/unmap cycles. Surprisingly, this reduces overall sort runtime by nearly half again after accounting for the application of heapsort directly onto xfile pages.

Blob Storage

Extended attributes and directories add an additional requirement for staging records: arbitrary byte sequences of finite length. Directory entries associate a name with a file, and extended attributes implement a key-value store. The names, keys, and values can also be staged in an xfile with the same loads and store technique as the xfarray, so the xfblob abstraction was created to simplify things.

The details of repairing directories and extended attributes will be discussed in a subsequent section about atomic extent swapping. Sorting is not supported for blobs, since the store interface takes the input blob and returns a cookie that can be used to retrieve the blob. No deduplication is performed, but callers can discard all blobs.

The proposed patchset is at the start of the extended attribute repair series.

Sparse Arrays of Fixed-Size Records

Sparse arrays are nearly the same as regular arrays, except for the expectation that there may be long sequences of zeroed areas between written records. The zeroed areas can be written that way explicitly, or they can be unpopulated areas of the xfile mapping. To iterate the non-null records of a sparse xfarray, a special load function uses SEEK_DATA to skip areas of the array that are not populated with memory pages.

Bulk Loading of B+Trees

As mentioned previously, early iterations of online repair built new btree structures by creating a new btree and adding staged records individually. Loading a btree one record at a time had a slight advantage of not requiring the incore records to be sorted prior to commit. Unfortunately, adding records with a separate transaction chain for each record is very slow. Moreover, the lack of log support meant that the old btree blocks would leak if the repair succeeded, and the new btree blocks if the system went down. Loading records one at a time also meant that we cannot control the loading factor of the blocks in the new btree.

Fortunately, the venerable xfs_repair tool had a more efficient means for rebuilding a btree index from a collection of records – bulk btree loading. Darrick studied the existing code, took notes on how it worked, built a new generic implementation, and ported offline repair to use it. Those notes in turn have been refreshed and are presented here.

Geometry Computation

The first step of bulk loading is to compute the shape of the btree from the record set, the type of btree, and any load factor preferences. First and foremost, we must establish the minimum and maximum records that will fit in a leaf block from the size of each btree block and the block header. Roughly speaking, the maximum number of records is:

maxrecs = (block_size - header_size) / record_size

The XFS design specifies that btree blocks should be merged when possible, which means the minimum number of records is half of maxrecs:

minrecs = maxrecs / 2

The next variable to determine is the desired loading factor. This must be at least minrecs and no more than maxrecs. Choosing minrecs is undesirable because it wastes half the block. Choosing maxrecs is also undesirable because adding a single record to each newly rebuilt leaf block will cause a tree split, which causes a noticeable drop in performance immediately afterwards. The default loading factor was chosen to be 75% of maxrecs, which provides a reasonably compact structure without any immediate split penalties. If space is tight, the loading factor will be set to maxrecs to try to avoid running out of space:

leaf_load_factor = enough space ? (maxrecs + minrecs) / 2 : maxrecs

Load factor is computed for btree node blocks using the combined size of the btree key and pointer as the record size:

maxrecs = (block_size - header_size) / (key_size + ptr_size)
minrecs = maxrecs / 2
node_load_factor = enough space ? (maxrecs + minrecs) / 2 : maxrecs

Once that’s done, the number of leaf blocks required to store the record set can be computed as:

leaf_blocks = ceil(record_count / leaf_load_factor)

The number of node blocks needed to point to the next level down in the tree is computed as:

n_blocks = (n == 0 ? leaf_blocks : node_blocks[n])
node_blocks[n + 1] = ceil(n_blocks / node_load_factor)

This computation is performed recursively until the current level only needs one block. At that point we’ve reached the tree root, and we know the height of the new tree. The number of blocks needed for the new tree is the summation of the number of blocks per level.

Reserving New B+Tree Blocks

Once we know the number of blocks that we need for the new btree, we need to allocate those blocks from the free space extents. Each reserved extent is tracked separately by the btree builder state data. To improve crash resilience, we also log an Extent Freeing Intent (EFI) item in the same transaction as the space allocation and attach it to reservation. If the system goes down, log recovery will find the EFIs and put them back in the free space, effectively leaving the filesystem untouched.

Each time we claim a block for the btree from a reserved extent, we update the reservation to reflect the claimed space. When we’ve written the new data structure to disk and are ready to commit to the new structure, we walk the reservation list and log Extent Freeing Done (EFD) items to mark the end of the construction phase. Unclaimed reservations are converted to regular deferred extent free work to be freed after the new structure is committed. The EFDs logged to the committing transaction must not overrun it. For that reason, it is assumed that the buffer update committing the new data structure will be small and the only non-intent item attached to the transaction. Block reservation tries to allocate as much contiguous space as possible to reduce the number of EFIs in play.

While repair is writing these new btree blocks, the EFIs created for the space reservations pin the tail of the log. It’s possible that other parts of the system will remain busy and push the head of the log towards the pinned tail. To avoid livelocking the filesystem, the EFIs cannot pin the tail of the log for too long. To alleviate this problem, the dynamic relogging capability of the deferred ops mechanism is reused here to commit a transaction at the log head containing an EFD for the old EFI and new EFI at the head. This enables the log to release the old EFI to keep the log moving forwards.

EFIs have a role to play during the commit phase; please see the section about Reaping Old Metadata Blocks for more details.

Proposed patchsets are the bitmap rework and the preparation for bulk loading btrees.

Writing the New Tree

This part is pretty simple – the btree builder claims a block from the reserved list, writes the new btree block header, fills the rest of the block with records, and add the block to a list of written blocks. Sibling pointers are set every time a new block is added to the level. When we’ve finished writing the record blocks, we move on to the nodes. To fill a node block, we walk each block in the next level down in the tree computing the relevant keys and writing them into the node. When we’ve reached the root level, we’re ready to commit the new btree!

To commit the new btree, we write the btree blocks to disk synchronously. This is a little complicated because a new btree block could have been freed recently, so we must be careful to remove the (stale) buffer from the AIL list before we can write the new blocks to disk. Once the new blocks have been persisted, we log the location of the new root to a transaction, and commit the transaction to cement the new btree into the filesystem. Repair them moves on to reaping the old blocks, which will be discussed after a few case studies.

Case Study: Rebuilding the Inode Index

The inode btree maps inode numbers to the ondisk location of the associated inode records. This is space usage information, which means that we can rebuild the inode btrees from the reverse mapping information. Each reverse mapping record with an owner of XFS_RMAP_OWN_INODES should tell us the location of at least one inode cluster buffer. A cluster is the smallest number of ondisk inodes that can be allocated or freed in a single transaction; it is never smaller than 1 fs block or 4 inodes.

For each inode space allocation, first ensure that there are no records in the free space btrees nor any records in the reference count btree. If there are, the space metadata inconsistencies are reason enough to abort the operation. Otherwise, read each cluster buffer to check that its contents appear to be ondisk inodes and to decide if the file is allocated (i_mode != 0) or free (i_mode == 0). Accumulate the results of successive inode cluster buffer reads until we have enough to fill a single inode chunk, which is 64 consecutive numbers in the inode number keyspace. If the chunk is sparse, the chunk record may include holes. Once we have accumulated one chunk’s worth of data, we store the inode btree record in the xfarray for the inode btree. The free inode btree is only populated with records for chunks that have free non-sparse inodes. The number of records for the inode btree is the number of xfarray records, but the record count for the free inode btree has to be computed as we add xfarray entries.

Now that we know the number of records to store in each inode btree, compute the geometry of the new btrees, allocate blocks to store the btree, and flush them to disk. When the new btrees have been persisted, commit the new btree root locations to the AGI buffer and move on to reaping the old btree blocks. The old btree blocks occupy the space the the reverse mapping index describes as being owned by XFS_RMAP_OWN_INOBT but cannot be found by visiting each block in the new inode btrees.

The proposed patchset is the AG btree repair series.

Case Study: Rebuilding the Space Reference Counts

This algorithm is also described in the code for xfs_repair, since the implementations are similar.

Reverse mapping records are used to rebuild the reference count information. Reference counts are required for correct operation of copy on write for shared file data. Imagine the reverse mapping entries as rectangles representing extents of physical blocks, and that the rectangles can be laid down to allow them to overlap each other. Then we know that we must have a reference count record starting and ending wherever the height of the stack changes. In other words, the record emission stimulus is level-triggered:

                -    ---
      --      ----- ----   ---        ------
--   ----     ----------- ----     ---------
-------------------------------- -----------
^ ^  ^^ ^^    ^ ^^ ^^^  ^^^^  ^ ^^ ^  ^     ^
2 1  23 21    3 43 234  2123  1 01 2  3     0

Note that in the actual reference count btree we don’t store the refcount == 0 cases because the free space btree tells us which blocks are free. Extents being used to stage copy-on-write operations should be the only records with refcount == 1. Single-owner file blocks aren’t recorded in either the free space or the reference count btrees.

Given the reverse mapping btree, which orders records by physical block number, a starting physical block (sp), a bag-like data structure to hold mappings that cover sp, and the next physical block where the level changes (np), we can reconstruct the reference count information as follows:

While there are still unprocessed mappings in the reverse mapping btree:

  1. Set sp to the physical block of the next unprocessed reverse mapping record.
  2. Add to the bag all the reverse mappings where rm_startblock == sp.
  3. Set np to the physical block where the bag size will change. This is the minimum of (rm_startblock of the next unprocessed mapping) and (rm_startblock + rm_blockcount of each mapping in the bag).
  4. Record the bag size as old_bag_size.
  5. While the bag isn’t empty,
    1. Remove from the bag all mappings where rm_startblock + rm_blockcount == np.
    2. Add to the bag all reverse mappings where rm_startblock == np.
    3. If the bag size isn’t old_bag_size, store the refcount record (sp, np - sp, bag_size) in the refcount xfarray.
    4. If the bag is empty, break out of this inner loop.
    5. Set old_bag_size to bag_size.
    6. Set sp = np.
    7. Set np to the physical block where the bag size will change. Go to step 3 above.
  6. Reference count records should be added for all reverse mappings with an owner of XFS_RMAP_OWN_COW because they represent space extents that are in use to stage copy on write operations.

Like the other btree repair functions, we store the new refcount records in an xfarray and use the btree bulk loading code to persist and commit a new tree. The old btree blocks occupy the space the the reverse mapping index describes as being owned by XFS_RMAP_OWN_REFC but cannot be found by visiting each block in the new refcount btree.

The proposed patchset is the AG btree repair series.

Case Study: Rebuilding File Fork Mapping Indices

Rebuilding the data or attribute forks of a file is straightforward if the fork is in extents or block mapping btree (BMBT) format. The reverse mapping records of each AG are traversed to find all the space mapped to that file fork. Once the collected records are sorted in file offset order, the btree bulk loading code is used to reserve blocks for the new btree, write them to disk, and atomically commit the new structure into the inode.

There are two minor complications here: First, it’s possible to move the fork offset to adjust the sizes of the immediate areas if the data and attr forks are not both in BMBT format. Second, if there are sufficiently few fork mappings, it may be possible to use EXTENTS format instead of BMBT.

The old btree blocks are found by computing the bitmap of all records for that file fork that also have the XFS_RMAP_BMBT_BLOCK flag set, and subtracting the blocks in the new bmap btree. The resulting blocks are passed to the reaping mechanism for disposal.

The proposed patchset is the inode repair series.

Reaping Old Metadata Blocks

Whenever we build a new data structure to replace one that is suspect, the question arises of how to dispose of the blocks that allegedly belonged to the old structure. The laziest method of course is not to deal with them at all, but this slowly leads to service degradations as space leaks out of the filesystem. If we’re fortunate, someone will schedule a rebuild of the free space information, which will plug all those leaks. Freeing all of the blocks that we think composed an old data structure is naïve, because there may be other data structures that also think they own some of those blocks (e.g. crosslinked trees). Permitting the block allocator to hand them out again will not push the system towards consistency.

Instead, online repair uses the reverse mapping index to discover which subset of the reap candidate extents are not claimed by anything else in the filesystem and frees only those that have no other owners.

For space metadata, the process of finding extents to dispose of generally follows this format:

  1. Create a bitmap of space used by data structures that we want to preserve. Generally, this is the new structure that is being built, and we can reuse the space reservation data from when we wrote the new object.
  2. Survey the reverse mapping data to create a bitmap of space owned by the same XFS_RMAP_OWN_* number for the metadata that is being preserved.
  3. Use the bitmap disunion operator to subtract (1) from (2). The remaining set bits represent extents that could be freed. The process moves on to step 4 below.

Repairs for file-based metadata such as extended attributes, directories, symbolic links, quota files and realtime bitmaps are performed by building a new structure attached to a temporary file and swapping the forks. Afterward, the mappings in the old file fork are the candidate blocks for disposal.

The process for disposing of old extents is as follows:

  1. For each extent in the candidate list, count the number of reverse mapping records for the first block in that extent that do not have the same rmap owner for the data structure being repaired.
    • If zero, the block has a single owner and can be freed.
    • If not, the block is part of a crosslinked structure and must not be freed.
  2. Starting with the next block in the extent, figure out how many more blocks have the same zero/nonzero other owner status as that first block.
  3. If the region is crosslinked, delete the reverse mapping entry for the structure being repaired and move on to the next region.
  4. If the region is to be freed, mark any corresponding buffers in the buffer cache as stale to prevent log writeback.
  5. Free the region and move on.

There are two complications to this procedure. Transactions are of finite size, so we must be careful to roll the transactions used during the reaping process to avoid overruns. Overruns come from two sources:

  1. EFIs logged on behalf of space that we’re freeing,
  2. Log items for buffer invalidations.

To avoid overruns, repair rolls the transaction when it perceives that the transaction reservation is nearly exhausted, and resumes logging updates with the new transaction. This introduces a window in which a crash during the reaping process can leak blocks.

The proposed patchset is the preparation for bulk loading btrees series.

Case Study: Reaping After a Regular Btree Repair

Old reference count and inode btrees are the easiest to reap because they have rmap records with special owner codes: XFS_RMAP_OWN_REFC for the refcount btree, and XFS_RMAP_OWN_INOBT for the inode and free inode btrees. Creating a list of extents to reap that we think are the old btree blocks is quite simple, conceptually:

  1. Lock the relevant AGI/AGF header buffers to prevent allocation and frees.
  2. For each reverse mapping record with an rmap owner that interests us, set the corresponding range in a bitmap.
  3. Walk the current data structures that have the same rmap owner. For each block visited, clear that range in the above bitmap.
  4. Each set bit in the bitmap represents a block that could be a block from the old data structures and hence is a candidate for reaping. In other words, (rmap_records_owned_by & ~blocks_reachable_by_walk). The disunion operation will appear throughout these case studies.

If it is possible to maintain the AGF lock throughout the repair (which is the common case), then step 2 can be performed at the same time as the reverse mapping record walk that creates the records for the new btree.

Case Study: Rebuilding the Free Space Indices

Repairing the free space btrees has three key complications over a regular btree repair. The first complication is that free space is not explicitly tracked in the reverse mapping records. Hence, the new free space records must be inferred from gaps in the physical space component of the keyspace of the reverse mapping btree.

The second complication is much more serious: we can’t use the common btree reservation code. Most btree repair functions assume the free space btrees are consistent, so they share the common code described in the section about reserving new btree blocks to allocate new blocks and use bespoke EFIs to ensure that log recovery will free the blocks if the repair fails to commit the new btree root. This is obviously impossible when repairing the free space btrees themselves. However, repair holds the AGF buffer lock for the duration of the free space index reconstruction, so it can use the collected free space information to supply the blocks for the new free space btrees. It is not necessary to back each reserved extent with an EFI because we’re building the new btrees in what the ondisk filesystem thinks is free space. However, if reserving blocks for the new btrees from the collected free space information changes the number of free space records, repair must re-estimate the new free space btree geometry with the new record count until the reservation is sufficient. As part of committing the new btrees, we must ensure that reverse mappings are created for the reserved blocks that we used and that unused reserved blocks are inserted into the free space btrees. Deferrred rmap and freeing operations are used to ensure that this transition is atomic.

Finding the blocks to reap after the repair is the third complication. Blocks for the free space btrees and the reverse mapping btrees are supplied by the AGFL. Blocks put onto the AGFL have reverse mapping records with the owner XFS_RMAP_OWN_AG. This ownership is retained when blocks move from the AGFL into the free space btrees or the reverse mapping btrees. When we are walking reverse mapping records to synthesize free space records, we also take notice of the XFS_RMAP_OWN_AG records and set the corresponding bits in a bitmap (ag_owner_bitmap). We also maintain a second bitmap in which we set the bits corresponding to the rmap btree blocks and the AGFL blocks (rmap_agfl_bitmap). When the walk is complete, the bitmap disunion operation (ag_owner_bitmap & ~rmap_agfl_bitmap) is used to identify the extents that we think are used by the old free space btrees. These blocks can then be reaped using the methods outlined above.

The proposed patchset is the AG btree repair series.

Case Study: Reaping After Repairing Reverse Mapping Btrees

Old reverse mapping btrees are less difficult to reap after a repair. As mentioned in the previous section, blocks on the AGFL, the two free space btree blocks, and the reverse mapping btree blocks all have reverse mapping records with XFS_RMAP_OWN_AG as the owner. The full process of gathering reverse mapping records and building a new btree are described in the case study of live rebuilds of rmap data, but a crucial point from that discussion is that the new rmap btree will not contain any records for the old rmap btree, nor should the old btree blocks be tracked in the free space btrees. The list of candidate reaping blocks is computed by setting the bits corresponding to the gaps in the new rmap btree records, and then clearing the bits corresponding to extents in the free space btrees. The result (new_rmapbt_gaps & ~bnobt_records) are reaped using the methods outlined above.

The proposed patchset is the AG btree repair series.

Case Study: Rebuilding the AGFL

The allocation group free block list (AGFL) is repaired as follows:

  1. Create a bitmap for all the space that the reverse mapping data claims is owned by XFS_RMAP_OWN_AG.
  2. Subtract the space used by the two free space btrees and the rmap btree.
  3. Subtract any space that the reverse mapping data claims is owned by any other owner, to avoid re-adding crosslinked blocks to the AGFL.
  4. Once the AGFL is full, reap any blocks leftover.
  5. The next operation to fix the freelist will right-size the list.

Inode and Quota Record Repairs

Inode records (dinodes) and quota records (dquots) must be handled carefully, because they have both ondisk metadata and an in-memory (“cached”) representation. There is a very high potential for cache coherency issues if we do not act carefully to access the ondisk metadata only when the ondisk metadata is so badly damaged that the kernel won’t load the in-memory representation. When scrub does this, it must use specialized resource acquisition functions that return either the in-memory representation or a lock on whichever object is necessary to prevent any update to the ondisk location. Similarly, the only repairs we want to do to the ondisk metadata is whatever is necessary to get the in-core structure loaded. Once the in-memory representation is loaded, we lock it and can subject it to whatever comprehensive checks, repairs, and optimizations that we want.

Proposed patchsets include the inode and quota repair series.

Semi-Freezing to Fix Summary Counters

Filesystem summary counters track availability of filesystem resources such as free blocks, free inodes, and allocated inodes. This information could be compiled by walking the free space and inode indexes, but this is a slow process, so XFS maintains a copy in the ondisk superblock that (roughly) reflect the ondisk metadata. For performance reasons, XFS also maintains incore copies of those counters, which are key to enabling resource reservations for active transactions. Writer threads reserve the worst-case quantities of resources from the incore counter and give back whatever they don’t use at commit time. It is therefore only necessary to serialize on the superblock when the superblock is being committed to disk.

The lazy superblock counter feature introduced in XFS v5 took this even further by training log recovery to recompute the summary counters from the AG headers, which eliminated the need for most transactions even to touch the superblock. The only time XFS commits the summary counters is at filesystem unmount. To reduce contention even further, the incore counter is implemented as a percpu counter, which means that each CPU is allocated a batch of blocks from a global incore counter and can satisfy small allocations from the local batch.

The high-performance nature of the summary counters makes it difficult for online fsck to check them, since there is no way to quiesce a percpu counter while the system is running. Although online fsck can read the filesystem metadata to compute the correct values of the summary counters, there’s no good way to hold the value of a percpu counter stable, so it’s quite possible that the counter will be out of date by the time the walk is complete. Earlier versions of online scrub would return to userspace with an incomplete scan flag, but this is not a satisfying outcome for a system administrator. For repairs, we must stabilize the counters while we walk the filesystem metadata to get an accurate reading and install it in the percpu counter.

To satisfy this requirement, online fsck must prevent other programs in the system from initiating new writes to the filesystem, it must disable background garbage collection threads, and it must wait for existing writer programs to exit the kernel. Once that has been established, we can walk the AG free space indexes, the inode btrees, and the realtime bitmap to compute the correct value of all four summary counters. Astute readers may already be thinking that this sounds very similar to freezing the filesystem, and that is more or less the solution that will be presented here.

The initial implementation used the actual VFS filesystem freeze mechanism to quiesce filesystem activity. With the filesystem frozen, it is possible to resolve the counter values with exact precision, but there are many problems with calling the VFS methods directly:

  • Other programs can unfreeze the filesystem without our knowledge. This leads to incorrect scan results and incorrect repairs.
  • Adding an extra lock to prevent others from thawing the filesystem required the addition of a ->freeze_super function to wrap freeze_fs(). This in turn caused other subtle problems because it turns out that the VFS freeze_super and thaw_super functions can drop the last reference to the VFS superblock, and any subsequent access becomes a UAF bug! This can happen if the filesystem is unmounted while the underlying block device has frozen the filesystem. This problem could be solved by grabbing extra references to the superblock, but it felt suboptimal given the other inadequacies of this approach:
  • We don’t need to quiesce the log to check the summary counters, but a VFS freeze initiates one anyway. This adds unnecessary runtime to live fscounter fsck operations.
  • Quiescing the log means that we flush the (possibly incorrect) counters to disk in the form of log cleaning transactions, only to correct them.
  • A bug in the VFS meant that freeze could complete even when sync_filesystem fails to flush the filesystem and returns an error. This bug was fixed in Linux 5.17.

The author established that the only component of online fsck that requires the ability to freeze the filesystem is the fscounter scrubber, so the code for this could be localized to that source file. fscounter freeze behaves the same as the VFS freeze method, except:

  • The final freeze state is set one higher than SB_FREEZE_COMPLETE to prevent other threads from thawing the filesystem.
  • Fsck aborts if the filesystem flush produces errors. Granted, this was fixed in the VFS in early 2022.
  • We don’t quiesce the log.

With this code in place, it is now possible to pause the filesystem for just long enough to check and correct the summary counters.

The proposed patchset is the summary counter cleanup series.

Full Filesystem Scans

Certain types of metadata can only be checked by walking every file in the entire filesystem to record observations and comparing the observations against what’s recorded on disk. Repairs will be made by writing those observations to disk in a replacement structure. However, it is not practical to shut down the entire filesystem to examine hundreds of millions of files because the downtime would be excessive. Therefore, online fsck must build the infrastructure to manage a live scan of all the files in the filesystem. There are two questions that need to be solved to perform a live walk:

  • How do we manage the scan cursor while we’re collecting data?
  • How does the scan keep abreast of changes being made to the system by other threads?

Coordinated Inode Scans

Inode numbers are search keys that filesystems use to identify files uniquely. XFS inode numbers form a continuous keyspace that can be expressed as a 64-bit integer. Note that the inode records themselves are sparsely distributed within the keyspace. Scans therefore proceed in a linear fashion across the keyspace, starting from 0 and ending at 0xFFFFFFFFFFFFFFFF. Naturally, we need a scan coordinator that can track the inode that we want to scan; call this the examination cursor. Somewhat less obviously, the scan coordinator must also track which parts of the keyspace we’ve already scanned, which is key to deciding if a concurrent filesystem update needs to be incorporated into the scan data. Call this the scanned inode cursor.

Advancing the scan is a multi-step process:

  1. Lock the AGI buffer of the AG containing the inode pointed to by the scanned inode cursor. This guarantee that inodes in this AG cannot be allocated or freed while we are moving the cursor.
  2. Use the per-AG inode btree to look up the next inode after the one that we have just scanned, since it may not be keyspace adjacent to the one just examined.
  3. If there are no more inodes left in this AG:
    1. Move the examination cursor to the start of the next AG.
    2. Adjust the scanned inode cursor to indicate that we have “scanned” the last possible inode in this AG’s inode keyspace. Recall that XFS inode numbers are segmented, so we need to mark the as scanned the entire keyspace up to just before the start of the next AG’s inode keyspace.
    3. Unlock the AGI and return to step 1 if there are unexamined AGs in the filesystem.
  4. Otherwise, there is at least one more inode to scan in this AG:
    1. Move the examination cursor ahead to the next inode marked as allocated by the inode btree.
    2. Adjust the scanned inode cursor to point to the inode just prior to where the examination cursor is now. We know there were no inodes in the part of the inode keyspace that we just covered.
  5. Load the incore inode for the selected ondisk inode. By maintaining the AGI lock until this point, we know that it was safe to advance the cursor across the entire keyspace, and that we have stabilized the next inode so that it cannot disappear from memory during the scan.
  6. Drop the AGI lock and return the incore inode to the caller.

The caller then examines the inode:

  1. Lock the incore inode to prevent updates during the scan.
  2. Scan the inode.
  3. While still holding the inode lock, adjust the scanned inode cursor to point to this inode.
  4. Unlock the incore inode.
  5. Advance the scan.

There are subtleties with the inode cache that complicate grabbing the incore inode for the caller. Obviously, it is an absolute requirement that the inode metadata be consistent enough to load it into the inode cache. Second, if the incore inode is stuck in some intermediate state, the scan coordinator must release the AGI and push the main filesystem to get the inode back into a loadable state.

The proposed patches are in the online quotacheck series.

Inode Management

Normally, XFS incore inodes are always grabbed (xfs_iget) and released (xfs_irele) outside of transaction context, because transactions are not a VFS-level concept. The one exception to the first rule is during inode creation because we must ensure the atomicity of the ondisk inode index and the initialization of the actual ondisk inode. irele is never run in transaction context because there are a handful of activities that might require ondisk updates:

  • The VFS may decide to kick off writeback as part of a DONTCACHE inode release
  • Speculative preallocations need to be unreserved
  • An unlinked file may have lost its last reference, in which case the entire file must be inactivated, which involves releasing all of its resources in the ondisk metadata

During normal operation, resource acquisition for an update follows this order to avoid deadlocks:

  1. Inode reference (iget).
  2. Filesystem freeze protection, if repairing (mnt_want_write_file).
  3. Inode IOLOCK (VFS i_rwsem) lock to control file IO.
  4. Inode MMAPLOCK (page cache invalidate_lock) lock for operations that can update page cache mappings.
  5. Transaction log space grant.
  6. Space on the data and realtime devices for the transaction.
  7. Incore dquot references, if a file is being repaired. Note that they are not locked, merely acquired.
  8. Inode ILOCK for file metadata updates.
  9. AG header buffer locks / Realtime metadata inode ILOCK.
  10. Realtime metadata buffer locks, if applicable.

Resources are usually released in the reverse order. However, online fsck is a very different animal from most regular XFS operations, because we may be examining an object that normally is acquired late in the above order, and we may need to cross-reference it with something that is acquired earlier in the order. The next few sections detail the specific ways in which online fsck must be very careful to avoid deadlocks.

iget and irele

An inode scan performed on behalf of a scrub operation runs in transaction context, and possibly with resources already locked and bound to it. This isn’t much of a problem for iget since it can operate in the context of an existing transaction.

When the VFS iput function is given a linked inode with no other references, it normally puts the inode on an LRU list in the hope that it can save time if another process re-opens the file before the system runs out of memory and frees it. Filesystem callers can short-circuit the LRU process by setting a DONTCACHE flag on the inode to cause the kernel to try to drop the inode into the inactivation machinery immediately. If the inode is instead unlinked (or unconnected after a file handle operation), it will always drop the inode into the inactivation machinery immediately. Inactivation has two parts – the VFS part, where it initiates writeback on all dirty file pages, and the XFS part, where we need to clean up XFS-private information (speculative preallocations for appends and copy on write) and free the inode if it was unlinked.

In the past, inactivation was always done from the process that dropped the inode, which was a problem for scrub because scrub may already hold a transaction, and XFS does not support nesting transactions. On the other hand, if scrub already dropped the transaction because it is exiting to userspace, it is desirable to drop otherwise unused inodes immediately to avoid polluting caches. To capture these nuances, the online fsck code has a separate xchk_irele function to set or clear the DONTCACHE flag to get the required release behavior.

Proposed patchsets include fixing scrub iget usage and dir iget usage.

Locking

Inode lock acquisition must also be done carefully during a coordinated inode scan. Normally, the VFS and XFS will acquire multiple IOLOCK locks in a well-known order: parent -> child when updating the directory tree and inode number order otherwise. Due to the structure of existing filesystem code, IOLOCKs must be acquired before transactions are allocated. Online fsck upends both of these conventions, because for a directory tree scanner, the scrub process holds the ILOCK of the file being scanned and it needs to take the IOLOCK of the file at the other end of the directory link. In the case of a corrupt directory tree containing a cycle, we cannot guarantee that another thread won’t trap us in an ABBA deadlock.

Solving both of these problems is straightforward – any time online fsck deviates from the accepted acquisition order, it uses trylock loops for resource acquisition to avoid ABBA deadlocks. If the first trylock fails, scrub must drop all inode locks and use trylock loops to (re)acquire all necessary resources. Trylock loops enable scrub to check for pending fatal signals, which is how scrub avoids deadlocking the filesystem or becoming an unresponsive process. However, trylock loops means that online fsck must be prepared to measure the resource being scrubbed before and after the lock cycle to detect changes and react accordingly.

Case Study: Finding a Directory Parent

Consider the directory parent pointer repair code as an example. Online fsck must verify that the dotdot entry of a directory points to exactly one parent directory that contains exactly one entry pointing to the child directory. Validating this relationship (and repairing it if possible) requires a walk of every directory on the filesystem while directory tree updates are being written. The inode scan coordinator provides a way to walk the filesystem without the possibility of missing an inode. The parent pointer scanner uses a neat trick to avoid the need for live update hooks: moving or renaming a directory resets the dotdot entry. The child directory is kept locked to prevent updates, but if the scanner fails to lock a parent, it can drop and relock both inodes. Concurrent updates are detected by watching for a change in the dotdot entry; if one is detected, the scan can exit early.

The proposed patchset is the directory repair series.

Live Update Hooks

The second piece of support that checking functions need during a full filesystem scan is the ability to stay informed about updates being made by other threads in the filesystem, since comparisons against the past are useless in a dynamic environment. Two pieces of Linux kernel infrastructure enable online fsck to monitor regular filesystem operations: notifier call chains and jump labels.

Notifier call chains are used to convey information about a filesystem update to a running online fsck function. In other words, they’re a filesystem hook. Call chains are a dynamic list, which means that they can be configured at run time. In theory there can be multiple checking functions subscribed to a chain at any given time, though in practice this is rare. Because these hooks are private to the XFS module, the struct passed along contains exactly what the checking function needs to update its observations.

Jump labels replace calls to the notifier call chain code with NOP sleds when online fsck is not running, thereby minimizing runtime overhead. Although jump labels are not supported on all architectures that Linux service, they exist on the primary targets for XFS filesystems. Lack of jump labels on a platform results in higher but still minimal overhead.

The code paths of the online fsck scanning code and the hooked filesystem code look like this:

other program
      ↓
inode lock ←────────────────────┐
      ↓                         │
AG header lock                  │
      ↓                         │
filesystem function             │
      ↓                         │
notifier call chain             │    same
      ↓                         ├─── inode
scrub hook function             │    lock
      ↓                         │
scan data mutex ←──┐    same    │
      ↓            ├─── scan    │
update scan data   │    lock    │
      ↑            │            │
scan data mutex ←──┘            │
      ↑                         │
inode lock ←────────────────────┘
      ↑
scrub function
      ↑
inode scanner
      ↑
xfs_scrub

These rules must be followed to ensure correct interactions between the checking code and the code making an update to the filesystem:

  • Prior to invoking the notifier call chain, the filesystem function being hooked must acquire the same lock that the scrub scanning function acquires to scan the inode.
  • The scanning function and the scrub hook function must coordinate access to the scan data by acquiring a lock on the scan data.
  • The scrub hook function must not allocate a new transaction or acquire any locks that might conflict with the filesystem function being hooked.
  • If the hook function adds items to the transaction context of the filesystem function being hooked, it must detach those items before exiting. In other words, the caller’s state must be preserved exactly.
  • The hook function must not add the live update information to the scan observations unless the inode being updated has already been scanned. The scan coordinator has a helper predicate for this.
  • The hook function can abort the inode scan to avoid breaking the other rules.

Notifier call chain functions allow passing of an unsigned long and a pointer to a structure. This is sufficient for current users to pass an operation code and some other details.

The proposed patches are at the start of the online quotacheck series.

Case Study: Live Quota Counter Checking

As a concrete example, let us compare the mount time quotacheck code to the online repair quotacheck code. Mount time quotacheck does not have to contend with concurrent operations, so it does the following:

  1. Make sure the ondisk dquots are in good enough shape that all the incore dquots will actually load, and zero the resource usage counters in the ondisk buffer.
  2. Walk every inode in the filesystem. Add each file’s resource usage to the incore dquot.
  3. Walk each incore dquot. If the incore dquot is not being flushed, add the ondisk buffer backing the incore dquot to a delayed write (delwri) list.
  4. Write the buffer list to disk.

Obviously, online quotacheck (and repair) cannot do this. The strategy for handling both is to create a shadow dquot index using a sparse xfarray and walk the filesystem to account file resource usage to each shadow dquot. However, scrub cannot stop the filesystem while it does this, so it must use live updates. Handling the live updates, however, is tricky because transactional dquot resource usage updates are handled in phases:

  1. The inodes involved are joined and locked to a transaction.
  2. For each dquot attached to the file:
    1. The dquot is locked.
    2. A quota reservation associated with the dquot is made and added to the transaction.
    3. The dquot is unlocked.
  3. Changes in dquot resource usage are tracked by the transaction.
  4. At transaction commit time, each dquot is examined again:
    1. The dquot is locked again.
    2. Quota usage changes are logged and unused reservation is given back to the dquot.
    3. The dquot is unlocked.

For live quotacheck, hooks are placed in steps 2 and 4. The step 2 hook creates a shadow version of the transaction dquot context (dqtrx) that operates in a similar manner to the regular code. The step 4 hook commits the shadow quota changes to the shadow dquots. Notice that both hooks are called with the inode locked, which is how the live update coordinates with the inode scanner.

Checking the counters in the dquot records is a simple matter of locking both the real and the shadow dquots and comparing the resource counts. Live updates are key to being able to walk every quota records without needing to hold any locks between quota records. If repairs are desired, the real and shadow dquots are locked and their resource counts are set to the values in the shadow dquot.

The proposed patchset is the online quotacheck series.

In-Memory Staging B+Trees

Most repair functions lock resources and use an in-memory array to store gathered observations for the new data structure. The primary advantage of this approach is the simplicity of the repair code – it is entirely contained within the scrub module, requires no hooks in the main filesystem, is usually the most efficient in its memory use, and guarantees that once we’ve decided a structure is corrupt, no other threads can access the metadata until we’ve finished repairing and revalidating the metadata. Unfortunately, linear arrays have a major disadvantage: because they do not enforce ordering of their records, they are not suitable for use with live updates, which require indexed lookups for performance reasons.

The reverse mapping btree cannot use the “standard” btree repair strategy because it must scan every file in the filesystem without incurring extended downtime. Live file scans imply live updates to staged data, which means that rmap rebuilding requires the ability to perform indexed lookups into the staging structure. Conveniently, we already have code to create and maintain ordered reverse mapping information: the existing rmap btree code!

Observe that the xfile abstraction represents memory pages as a file, which means that virtual kernel memory are now linearly byte-addressable. This in turn means that we can adapt the XFS buffer cache to direct its attentions to an xfile instead of a block device. Since the existing XFS reverse mapping code talks to the buffer cache, online repair can construct an in-memory rmap btree and live updates can update it as neede until fsck is ready to write the new reverse mapping index to disk. The next few sections describe how xfbtree actually works.

The proposed patchset is the in-memory btree series.

Using xfiles as a Buffer Cache Target

Two modifications are necessary to support xfiles as a buffer cache target. The first is to make it possible for the struct xfs_buftarg structure to host the struct xfs_buf rhashtable, because normally those are held by a per-AG structure. The second change is to add an ioapply function that can “read” cached pages from the xfile and “write” cached pages back to the xfile. Other than that, users of the xfile-backed buffer cache can use exactly the same APIs as users of the disk-backed buffer cache. This imposes the overhead of using more memory pages than is absolutely necessary because the xfile and the buffer cache do not share memory pages. However, this is more than made up for by reducing the need for new code.

Space Management with an xfile Btree

Space management for an xfile is very simple – btree blocks must be one memory page in size. When we free a btree block, we use FALLOC_FL_PUNCH_HOLE to remove the memory page from the xfile. When we need to allocate a btree block, we use SEEK_HOLE to find a gap in the file, fallocate it, and hand it back. If no holes are found, we extend the length of the xfile by one page, fallocate it, and hand it back.

In-memory btree blocks have the same header as a regular btree, which is perhaps overkill for an ephemeral structure since we don’t care about CRCs or filesystem UUIDs. That is a small price to pay to reuse existing code.

Committing Logged xfile Buffers

Although it is a clever hack to reuse the rmap btree code to handle the staging structure, there is another downside – because the in-memory btree is by definition ephemeral, we must not allow the XFS transaction manager to commit logged buffer items for buffers backed by an xfile. Doing so could result in transaction overruns and ephemeral data incorrectly being written to the ondisk log, and a lot of confusion for the AIL and log recovery.

In other words, users of in-memory btrees must perform the following prior to committing a transaction:

  1. Find each buffer log item whose buffer targets the xfile.
  2. Record the dirty/ordered status of the log item.
  3. Detach the log item from the buffer.
  4. Queue the buffer to a special delwri list.
  5. Clear the transaction dirty flag if the only dirty log items were the ones we detached.
  6. Submit the delwri list to commit the changes to the xfile.

Log intent items are not currently needed for in-memory btree updates. After removing xfile logged buffers from the transaction, the transaction be committed.

Case Study: Gathering Reverse Mapping Records

Collecting reverse mapping records requires the use of the inode scanner, the live update hooks, and an in-memory rmap btree.

  1. While we still hold the AGI and AGF buffers locked from when we ran the scrub, generate reverse mappings for all AG metadata: inodes, btrees, and the log.
  2. Set up an inode scanner.
  3. Hook into rmap updates for the AG that we’re interested in, so that we can receive live updates to the rmap btree while we’re scanning the filesystem.
  4. For each space mapping found in either forks of each file scanned, decide if the mapping matches the AG we’re interested in. If so:
    1. Create a btree cursor for the in-memory btree.
    2. Use the rmap code to add the record to the in-memory btree.
    3. Use the special commit function to write the xfile.
  5. For each live update received via the hook, decide if we’ve already scanned the owner in question. If so, we need to absorb the live update:
    1. Create a btree cursor for the in-memory btree.
    2. Replay the operation into the in-memory btree.
    3. Use the special commit function to write the xfile without altering the hooked transaction.
  6. Once we’ve finished the inode scan, create a new scrub transaction and relock the two AG headers.
  7. Perform the usual btree bulk loading and commit to install the new rmap btree.
  8. Reap the old rmap btree blocks as discussed in the case study about how to reap after rmap btree repair.

The proposed patchset is the rmap repair series.

Temporary XFS Files

XFS stores a substantial amount of metadata in file forks: directories, extended attributes, free space bitmaps and summary information for the realtime volume, and quota records. File forks map 64-bit logical file fork space extents to physical storage space extents, similar to how a memory management unit maps 64-bit virtual addresses to physical memory addresses. Therefore, file-based tree structures (such as directories and extended attributes) use blocks mapped in the file fork offset address space that point to other blocks mapped within that same address space, and file-based linear structures (such as bitmaps and quota records) compute array element offsets in the file fork offset address space.

In the initial iteration of the design of file metadata repair design, the damaged metadata blocks would be scanned for salvageable data; the extents in the file fork would be reaped; and then a new structure would be built in its place. This strategy did not survive the introduction of the atomic repair requirement expressed earlier in this document. The second iteration explored building a second structure at a high offset in the fork from the salvage data, reaping the old extents, and using a COLLAPSE_RANGE operation to slide the new extents into place. This had many drawbacks:

  • Array structures are linearly addressed, and the regular filesystem codebase does not have the concept of a linear offset that could be applied to the record offset computation to build an alternate copy.
  • Extended attributes are allowed to use the entire file fork offset address space.
  • Even if we could build an alternate copy of a data structure in a different part of the fork address space, the atomic repair commit requirement means that online repair would have to be able to perform a log assisted COLLAPSE_RANGE operation to ensure that the old structure was completely replaced.
  • A crash after construction of the secondary tree but before the range collapse would leave unreachable blocks in the file fork. This would likely confuse things further.
  • Reaping blocks after a repair is not a simple operation, and initiating a reap operation from a restarted range collapse operation during log recovery is daunting.
  • Directory entry blocks and quota records record the file fork offset in the header area of each block. An atomic range collapse operation would have to rewrite this part of each block header. Rewriting a single field in block headers is not a huge problem, but it’s something to be aware of.
  • Each block in a directory or extended attributes btree index contains sibling and child block pointers. Were the atomic commit to use a range collapse operation, each block would have to be rewritten very carefully to preserve the graph structure. Doing this means rewriting a large number of blocks repeatedly, which is not conducive to quick repairs.

The third iteration of the design for file metadata repair went for a totally new strategy – create a temporary file in the XFS filesystem, write a new structure at the correct offsets into the temporary file, and atomically swap the fork mappings to commit the repair. Once the repair is complete, the old fork can be reaped as necessary; if the system goes down during the reap, the iunlink code will delete the blocks during recovery.

Swapping extents with a temporary file still requires a rewrite of the owner field of the block headers, but this is much simpler than moving tree blocks individually. Furthermore, the buffer verifiers do not verify owner fields (since they are not aware of the inode that owns the block), which makes reaping of old file blocks much simpler. Extent swapping requires that AG space metadata and the file fork metadata of the file being repaired are all consistent with respect to each other, but that’s already a requirement of the filesystem in general. There is, however, a slight downside – if the system crashes during the reap phase and the fork extents are crosslinked, the iunlink processing will fail because freeing space will find the extra reverse mappings and abort.

Temporary files created for repair are similar to O_TMPFILE files created by userspace. They are not linked into a directory and the entire file will be reaped when the last reference to the file is lost. The key differences are that these files must have no access permission outside the kernel at all, they must be specially marked to prevent them from being opened by handle, and they must never be linked into the directory tree.

The proposed patches are in the realtime summary repair series.

Atomic Extent Swapping

Once we have a temporary file with a new data structure freshly written into it, we must commit the new changes into the existing file in such a way that log recovery can finish the operation if the system goes down. To satisfy that requirement, we need to create a deferred operation and a new type of log intent item so that the log can track the progress of the extent swap operation. The existing fork swap code used by xfs_fsr is not sufficient here because it can only swap extents incrementally when the reverse mapping btree is enabled, and it is assumed that the file contents are byte-for-byte identical. This is never true when rebuilding an inconsistent data structure. However, the atomic extent swapping code is an evolution on the existing incremental swap method for filesystems with reverse mapping.

The proposed patchset is the atomic extent swap series.

Mechanics of an Extent Swap

Swapping entire file forks is a complex task. We want to exchange all file fork mappings between two file fork offset ranges. There are likely to be many extent mappings in each fork, and the offsets of the mappings aren’t necessarily aligned. Furthermore, there may be other updates that need to happen after the swap, such as exchanging file sizes or inode flags. This is roughly the format of the new deferred extent swap work item:

struct xfs_swapext_intent {
    /* Inodes participating in the operation. */
    struct xfs_inode    *sxi_ip1;
    struct xfs_inode    *sxi_ip2;

    /* File offset range information. */
    xfs_fileoff_t       sxi_startoff1;
    xfs_fileoff_t       sxi_startoff2;
    xfs_filblks_t       sxi_blockcount;

    /* Set these file sizes after the operation, unless negative. */
    xfs_fsize_t         sxi_isize1;
    xfs_fsize_t         sxi_isize2;

    /* XFS_SWAP_EXT_* log operation flags */
    uint64_t            sxi_flags;
};

Observe that the new log intent item contains enough information to track two logical fork offset ranges: (inode1, startoff1, blockcount) and (inode2, startoff2, blockcount). After each step in the swap operation, the two startoff fields are incremented and the blockcount field is decremented to reflect the progress made. The flags field captures behavioral parameters such as swapping the attr fork instead of the data fork and other work to be done after the extent swap. The two isize fields are used to swap the file size at the end of the operation, if the file data fork is the target of the swap operation.

When the extent swap is initiated, the sequence of operations is as follows:

  1. Create a deferred work item for the extent swap. At the start, it should contain the entirety of the file ranges to be swapped.

  2. At some point, xfs_defer_finish is called to start processing of the extent swap. This will log an extent swap intent item to the transaction for the deferred extent swap work item.

  3. Until sxi_blockcount of the deferred extent swap work item is zero,

    1. Read the block maps of both file ranges starting at sxi_startoff1 and sxi_startoff2, respectively, and compute the longest extent that we can swap in a single step. This is the minimum of the two br_blockcount s in the mappings. Keep advancing through the file forks until at least one of the mappings contains written blocks.

      For the next few steps, we will refer to the mapping that came from file 1 as “map1”, and the mapping that came from file 2 as “map2”.

    2. Create a deferred block mapping update to unmap map1 from file 1.

    3. Create a deferred block mapping update to unmap map2 from file 2.

    4. Create a deferred block mapping update to map map1 into file 2.

    5. Create a deferred block mapping update to map map2 into file 1.

    6. Log the block, quota, and extent count updates for both files.

    7. Extend the ondisk size of either file if necessary.

    8. Log an extent swap done log item for the extent swap intent log item that we read at the start of step 3.

    9. Compute the amount of file range we just covered. This quantity is (map1.br_startoff + map1.br_blockcount - sxi_startoff1), because step 3a could have skipped holes.

    10. Increase the starting offsets of sxi_startoff1 and sxi_startoff2 by the number of blocks we just computed, and decrease sxi_blockcount by the same quantity. This moves the cursor forward.

    11. Log an extent swap done log item for the extent swap intent log item that we read at the start of step 3.

    12. Log a new extent swap intent log item reflecting the work item state, now that we have advanced it.

    13. Return the proper error code (EAGAIN) to the deferred operation manager to inform it that there is more work to be done. The operation manager completes the deferred work in steps 3b-3e before moving us back to the start of step 3.

  4. Perform any post-processing. This will be discussed in more detail in subsequent sections.

  5. Reap all the extents in the temporary file’s fork.

If the filesystem goes down in the middle of an operation, log recovery will find the most recent unfinished extent swap log intent item and restart from there. This is how we guarantee that an outside observer will either see the old broken structure or the new one, and never a mismash of both.

Extent Swapping with Regular User Files

As mentioned earlier, XFS has long had the ability to swap extents between files, which is used almost exclusively by xfs_fsr to defragment files. The earliest form of this was the fork swap mechanism, where the entire contents of data forks could be exchanged between two files by exchanging the raw bytes in each inode’s immediate area. When XFS v5 came along with self-describing metadata, this old mechanism grew some log support to continue rewriting the owner fields of BMBT blocks during log recovery. When the reverse mapping btree was later added to XFS, the only way to maintain the consistency of the fork mappings with the reverse mapping index was to develop an iterative mechanism that used deferred bmap and rmap operations to swap mappings one at a time. This mechanism is identical to steps 2-4 from the procedure above, because the atomic extent swap mechanism is an iteration of an existing mechanism and not something totally novel. For the narrow case of file defragmentation, we require the file contents to be identical, so the recovery guarantees are not much of a gain.

In a broader context, however, atomic extent swapping is much more flexible than the existing swapext operation because it can guarantee that the caller never sees a mix of old and new contents even after a crash, and it can operate on two arbitrary file fork ranges. The extra flexibility enables several new use cases:

  • Atomic commit of file writes: A userspace process opens a file that it wants to update. Next, it opens a temporary file and calls the file clone operation to reflink the first file’s contents into the temporary file. Writes to the original file should instead be written to the temporary file. Finally, the process calls the atomic extent swap system call (FIEXCHANGE_RANGE) to exchange the file contents, thereby committing all of the updates to the original file, or none of them.
  • Transactional file updates: The same mechanism as above, but the caller only wants the commit to occur if the original file’s contents have not changed. To make this happen, the calling process snapshots the file modification and change timestamps of the original file before reflinking its data to the temporary file. When the program is ready to commit the changes, it passes the timestamps into the kernel as arguments to the atomic extent swap system call. The kernel only commits the changes if the provided timestamps match the original file.
  • Emulation of atomic block device writes: Export a block device with a logical sector size matching the filesystem block size to force all writes to be aligned to the filesystem block size. A flag is passed into atomic extent swap system call to indicate that holes in the temporary file should be ignored. This emulates an atomic device write without the overhead of the initial file clone operation.

Preparation for Extent Swapping

There are a few things that need to be taken care of before initiating an atomic extent swap operation. Atomic extent swapping for regular files requires the page cache to be flushed to disk before the operation begins. Like any filesystem operation, we must determine the maximum amount of disk space and quota that can be consumed on behalf of both files in the operation, and reserve that quantity of resources to avoid an unrecoverable out of space failure once we start dirtying metadata. Specifically, we need to scan the ranges of both files to estimate:

  • Data device blocks needed to handle the repeated updates to the fork mappings.
  • Change in data and realtime block counts for both files.
  • Increase in quota usage for both files, if the two files do not share the same set of quota ids.
  • The number of extent mappings that we’re going to add to each file.
  • Whether or not there are partially written realtime extents. If there’s a chance that the operation could fail to run to completion, we do not want to expose to userspace a realtime file extent that maps to different extents on the realtime volume.

The need for precise estimation increases the run time of the swap operation, but it is very important that we maintain correct accounting. We cannot ever run the filesystem completely out of free space, nor can we ever add more extent mappings to a fork than it can support. Regular users are required to abide the quota limits, though metadata repair will exceed quota to resolve inconsistencies.

Special Features for Swapping Metadata File Extents

Extended attributes, symbolic links, and directories are allowed to set the fork format to “local” and treat the fork as a literal area for data storage. For a metadata repair, we must take some extra steps to support these cases:

  • If both forks are in local format and the fork areas are large enough, the swap can be performed by copying the incore fork contents, logging both forks, and committing. The atomic extent swap mechanism is not necessary.
  • If both forks map blocks, then the regular atomic extent swap can be used.
  • Otherwise, the local format forks must be converted to blocks to perform the swap. The conversions to block format should be done in the same transaction that logs the initial extent swap intent log item. The regular atomic extent swap is used to exchange the mappings. Special flags are set on the swap operation so that the transaction can be rolled on emore time to convert the two forks back to local format if possible.

Extended attributes and directories stamp the owning inode into every block, but nowhere in the buffer verifiers do we actually check the inode number! Prior to performing the extent swap, we must walk every block in the new data structure to update the owner field and flush the buffer to disk.

After a successful swap operation, the repair operation must reap the old fork blocks by processing each fork mapping through the standard extent reaping mechanism that is done post-repair. If the filesystem should go down during the reap part of the repair, the iunlink processing at the end of recovery will free both the temporary file and whatever blocks were not reaped.

Case Study: Repairing the Realtime Summary File

The realtime summary file has a relationship with the realtime free space bitmap that is similar to the one between the free space by count (cntbt) btree and the free space by block (bnobt) btree. In other words, the summary file provides a fast way to find free space extents by length. The summary file itself is a flat file (with no block headers or checksums!) partitioned into log2(total rt extents) sections containing enough 32-bit counters to match the number of blocks in the rt bitmap. Each counter records the number of free extents that start in that bitmap block and can satisfy a power-of-two allocation request.

To check the summary file against the bitmap, we walk the free space extents recorded in the bitmap and construct a new summary file in an xfile. When the incore summary is complete, we compare the contents of the two files to find any discrepancies. Repairing the summary file involves us writing the xfile contents into the temporary file and using atomic extent swap to commit the new contents. The temporary file is then reaped.

The proposed patchset is the realtime summary repair series.

Case Study: Salvaging Extended Attributes

In XFS, extended attributes are implemented as a namespaced name-value store. Values are limited in size to 64KiB, but there is no limit in the number of names. The attribute fork is unpartitioned, which means that the root of the attribute structure is always in logical block zero, but attribute leaf blocks, dabtree index blocks, and remote value blocks are intermixed. Attribute leaf blocks contain variable-sized records that associate user-provided names with the user-provided values. Values larger than a block are allocated separate extents and written there. If the leaf information expands beyond a single block, a directory/attribute btree (dabtree) is created to map hashes of attribute names to entries for fast lookup.

Salvaging extended attributes is done as follows:

  1. Walk the attr fork of the file being repaired to find the attribute leaf blocks. When one is found,
    1. The leaf block is walked linearly to find candidate names. When a name is found with no obvious problems,
      1. Retrieve the value. If that succeeds, add the name and value to the extended attributes of the temporary file.

Next, the extended attribute block headers in the temporary file must be rewritten with the new inode number. The heterogeneous nature of attr fork blocks makes this a little complex, since remote value buffers span all blocks in the extent, whereas the leaf blocks and the name index dabtree blocks are each a single filesystem block.

  1. Walk every attribute name in the temporary file to find the names with remote values.
    1. Read the remote value block.
    2. Change the owner field.
    3. Write it to disk.
    4. Remember the file fork offset range of this remote value.
  2. Walk every extent in the attr fork of the temporary file, excluding the blocks excluded in step 2d. These are the blocks of the leaf blocks and the attribute name index dabtree.
    1. Read the block.
    2. Change the owner field.
    3. Attach the buffer to the transaction as an ordered buffer to force it to disk before the new fork is committed.
  3. Use atomic extent swapping to exchange the new and old extended attribute structures. The old attribute blocks are now attached to the temporary file.
  4. Reap the temporary file.

The proposed patchset is the extended attribute repair series.

Case Study: Salvaging Directories

Directories are implemented in XFS as a file containing three 32GB partitions. The first partition contains directory entry data blocks. Each data block contains variable-sized records associating a user-provided name with an inode number and a file type. If the directory entry data grows beyond one block, the second partition (post-EOF space) is populated to store an index of the names and free space. This makes directory name lookups very fast. If this second partition grows beyond one block, the third partition is populated to store a linear array of free space information for faster expansions. If the free space has been separated and the second partition grows again beyond one block, then a dabtree is used to map hashes of entry names to directory entry locations.

At this time, XFS does not support the ability to have child files point back to the parent(s) that contain the files. This means that we can only salvage directories; we cannot rebuild them by scanning the filesystem. This gap will be closed when the parent pointer feature is merged.

Fortunately, directory blocks are all the same size, so salvaging directories is straightforward:

  1. Find the parent of the directory. If the dotdot entry is not unreadable, try to confirm that the alleged parent has a child entry pointing back to the directory being repaired. Otherwise, walk the filesystem to find it.
  2. Walk the first partition of data fork of the directory to find the directory entry data blocks. When one is found,
    1. The data block is walked linearly to find candidate entries. When a directory entry is found with no obvious problems,
      1. Retrieve the inode number and the inode. If that succeeds, add the name, inode number, and file type to the directory entries of the the temporary file.

Next, the directory block headers must be rewritten with the new inode number for completeness, even though the main filesystem never checks.

  1. Walk every extent in the temporary file’s data fork.
    1. Read the block.
    2. Change the owner field.
    3. Attach the buffer to the transaction as an ordered buffer to force it to disk before the new fork is committed.
  2. Use atomic extent swapping to exchange the new and old directory structures. The old directory blocks are now attached to the temporary file.
  3. Reap the temporary file.

Question: Do we need to invalidate dentries when we rebuild a directory? Question: Can the dentry cache know about a directory entry that we then cannot salvage?

The proposed patchset is the directory repair series.

The Orphanage

Filesystems present files as a directed, and hopefully acyclic, graph. The root of the filesystem is a directory, and each entry in a directory points downwards either to more subdirectories or to non-directory files. Unfortunately, a disruption in the directory graph pointers result in a disconnected graph, which makes files impossible to access via regular path resolution. The directory parent pointer online scrub code can detect a dotdot entry pointing to a parent directory that doesn’t have a link back to the child directory, and the file link count checker can detect a file with positive link count that isn’t pointed to by any directory in the filesystem. If the file in question has a positive link count, we know that the file in question is an orphan.

The question is, how does XFS reconnect these files to the directory tree? Offline fsck solves the problem by attaching unconnected files into /lost+found, and so does online repair. This process is a little more involved in the kernel than it is in userspace: we have to use the regular VFS mechanisms to create the orphanage directory before we initiate repairs to directories or to file link counts. As a result, the orphanage will be created with all the necessary security attributes, just like any other root-owned directory. Files are reconnected with their inode number as the directory entry name, since XFS does not currently store universal directory parent pointers. This naming policy is the same as offline fsck’s. Reparenting a file to the orphanage does not reset any of its permissions or ACLs.

Question: Do we need to invalidate negative dentries when we add something to the orphanage? Question: Do we need to update the parent/child links in the dentry cache when we move something to the orphanage? In theory, no, because we scan the dentry cache to try to find a parent.

The proposed patches are in the directory repair series.

Userspace Algorithms and Data Structures

In this chapter, we discuss the key algorithms and data structures employed by the driver program, xfs_scrub, to check and repair metadata, verify file data, and look for other potential problems.

Checking Metadata

Recall the overview of the work phases outlined earlier. This structure follows naturally from the data dependencies designed into the filesystem from its beginnings in 1993. In XFS, there are several groups of metadata dependencies:

  1. Filesystem summary counts depend on consistency within the inode indices, the allocation group space btrees, and the realtime volume space information.
  2. Quota resource counts depend on consistency within the quota file data forks and the file forks of every file on the system.
  3. The naming hierarchy depends on consistency within the directory and extended attribute structures. This includes file link counts.
  4. Directories, extended attributes, and file data depend on consistency within the file forks that map directory and extended attribute data to physical storage media.
  5. The file forks depends on consistency within inode records and the space metadata indices of the allocation groups and the realtime volume. This includes quota and realtime metadata files.
  6. The inode records depends on consistency within the inode metadata indices.
  7. The realtime space metadata depend on the data forks of the realtime metadata inodes.
  8. The allocation group metadata indices (free space, inodes, reference count, and reverse mapping btrees) depend on consistency within the AG headers and between all the AG metadata btrees.
  9. xfs_scrub depends on the filesystem being mounted and kernel support for online fsck functionality.

Therefore, a metadata dependency graph is a convenient way to schedule checking operations in the xfs_scrub program, and that is exactly what we do:

  • Phase 1 checks that the provided path maps to an XFS filesystem and detect the kernel’s scrubbing abilities, which validates group (i).
  • Phase 2 scrubs groups (g) and (h) in parallel using a threaded workqueue.
  • Phase 3 checks groups (f), (e), and (d), in that order. These groups are all file metadata, which means that we can scan the inodes in parallel.
  • Phase 5 starts by checking groups (b) and (c) in parallel before moving on to checking names.
  • Phase 6 depends on phase 2 to have validated all the metadata that it uses to find file data blocks to verify.
  • Phase 7 checks group (a), having validated everything else.

Notice that the data dependencies between groups are enforced by the structure of the program flow.

Parallel Inode Scans

An XFS filesystem can easily contain many millions of inodes. Given that XFS targets installations with large high-performance storage, we’d like to be able to scrub inodes in parallel to minimize runtime. This requires careful scheduling to keep the threads as evenly loaded as possible.

Early iterations of the xfs_scrub inode scanner naïvely created a single workqueue and scheduled a single work item per AG. Each work item walked the inode btree (with XFS_IOC_INUMBERS) to find inode chunks, called bulkstat (XFS_IOC_BULKSTAT) to gather enough information to construct file handles, and invoked a callback function with the bulkstat information and the handle. This leads to thread balancing problems in phase 3 if the filesystem contains one AG with a few large sparse files, and the rest of the AGs contain many smaller files, because we serialized the per-AG part of the inode scan.

Thanks to Dave Chinner, bounded workqueues in userspace enable us to fix this problem with ease by adding a second workqueue. Just like before, the first workqueue is seeded with one work item per AG, and it uses INUMBERS to find inode btree chunks. The second workqueue, however, is created with an upper bound on the number of items that can be pending. Each inode btree chunk found by the first workqueue’s workers are queued as a work item for the second workqueue, and it is this second workqueue that queries BULKSTAT and actually invokes the callback. This doesn’t completely solve the balancing problem, but reduces it enough to move on to more pressing issues.

The proposed patchsets are the scrub performance tweaks and the inode scan rebalance series.

Scheduling Repairs

During phase 2, corruptions and inconsistencies reported in any AGI header or inode btree are repaired immediately, because phase 3 relies on proper functioning of the inode indices to find inodes to scan. Failed repairs are rescheduled to phase 4. Problems and optimization opportunities reported in any other space metadata are deferred to phase 4.

During phase 3, corruptions and inconsistencies reported in any part of a file’s metadata can be repaired immediately if all space metadata were validated. Otherwise, unfixed repairs and optimization opportunities are scheduled for phase 4.

In the original design of xfs_scrub, we thought that repairs would be so infrequent that we could get away with using the struct xfs_scrub_metadata that we use to communicate with the kernel as the primary object to control repairs. Unfortunately, with recent increases in the number of optimizations possible for a given primary filesystem object (allocation group, realtime volume, file, the entire filesystem), it became much more memory-efficient to track all eligible repairs for a given filesystem object with a single repair item.

Phase 4 is responsible for scheduling a lot of repair work in as quick a manner as is practical. The data dependencies outlined earlier still apply, which means that we must try to complete the repair work scheduled by phase 2 before trying the work scheduled by phase 3.

  1. Start a round of repair with a workqueue and enough workers to keep the CPUs as busy as the user desires.
    1. For each repair item queued by phase 2,
      1. Ask the kernel to repair everything listed in the repair item for a given filesystem object.
      2. Make a note if the kernel made any progress in reducing the number of repairs needed for this object.
      3. If the object no longer requires repairs, revalidate all metadata associated with this object. If the revalidation succeeds, drop the repair item. If not, requeue the item for more repairs.
    2. While we’re making progress on repairs, jump back to 1a to retry all the phase 2 items.
    3. For each repair item queued by phase 3,
      1. Ask the kernel to repair everything listed in the repair item for a given filesystem object.
      2. Make a note if the kernel made any progress in reducing the number of repairs needed for this object.
      3. If the object no longer requires repairs, revalidate all metadata associated with this object. If the revalidation succeeds, drop the repair item. If not, requeue the item for more repairs.
    4. While we’re making progress on repairs, jump back to 1c to retry all the phase 3 items.
  2. If step 1 made any repair progress of any kind, jump back to step 1 to start another round of repair.
  3. If there are items left to repair, run them all serially one more time. This time we complain if the repairs were not successful, since this is the last chance to any work in phase 4.

Corruptions and inconsistencies encountered during phases 5 and 7 are repaired immediately.

The proposed patchsets are the repair warning improvements, refactoring of the repair data dependency and object tracking, and the repair scheduling improvement series.

Checking Names for Confusable Unicode Sequences

If xfs_scrub succeeds in validating the filesystem metadata by the end of phase 4, it moves on to checking for suspicious looking names in the filesystem. These names consist of the filesystem label, names in directory entries, and the names of extended attributes. Like most Unix filesystems, XFS imposes the sparest of constraints on the contents of a name – slashes and null bytes are not allowed in directory entries; and null bytes are not allowed in extended attributes and the filesystem label. However, the reality of most modern-day Linux systems is that programs work with Unicode character code points to support international languages. These programs encode those code points in UTF-8 when talking to the kernel, which means that in the common case, names found in an XFS filesystem are actually UTF-8 encoded Unicode data.

To maximize its expressiveness, the Unicode standard defines separate control points for various characters that are rendered similarly or identically in writing systems around the world. For example, the character “Cyrillic Small Letter A” U+0430 “а” often renders identically to “Latin Small Letter A” U+0061 “a”.

The standard also permits characters to be constructed in multiple ways – either by using a defined code point, or by combining one code point with various combining marks. For example, the character “Angstrom Sign U+212B “Å” can also be expressed as “Latin Capital Letter A” U+0041 “A” followed by “Combining Ring Above” U+030A “◌̊”.

Like the standards that preceded it, Unicode also defines various control characters to alter the presentation of text. For example, the character “Right-to-Left Override” U+202E can trick some programs into rendering “moo\xe2\x80\xaegnp.txt” as “mootxt.png”. A second category of rendering problems involves whitespace characters. If the character “Zero Width Space” U+200B is encountered in a file name, the name will be rendered with no whitespace between the previous and the next character. If there is a name in the same name domain with the previous and next characters in sequence but omitting the zero width space, the rendering will be identical and user may be confused by it. The kernel, in its indifference to byte encoding schemes, permits this.

As you can see, the flexibility of Unicode comes at a cost – malicious actors can create names that can be used to mislead users. UTF-8 codecs faithfully translate whatever Unicode sequences are provided, which means that these sequences are persisted to disk.

Techniques for detecting confusable names are explained in great detail in sections 4 and 5 of the Unicode Security Mechanisms document. xfs_scrub, when it detects UTF-8 encoding in use on a system, uses the Unicode normalization form NFD in conjunction with the confusable name detection component of libicu to identify names with a directory or within a file’s extended attributes that could be confused for each other. Names are also checked for control characters, non-rendering characters, and mixing of bidirectional characters. All of these potential issues are reported to the system administrator during phase 5.

Media Verification of File Data Extents

The system administrator can elect to initiate a media scan of all file data blocks. This scan after validation of all filesystem metadata (except for the summary counters) as phase 6. The scan starts by calling FS_IOC_GETFSMAP to scan the filesystem space map to find areas that are allocated to file data fork extents. Gaps betweeen data fork extents that are smaller than 64k are treated as if they were data fork extents to reduce the command setup overhead. When the space map scan accumulates a region larger than 32MB, a media verification request is sent to the disk, either as a SCSI_VERIFY command, or a directio read of the raw block device.

If the verification read fails, we retry with single-block reads to narrow down the failure to the specific region of the media and recorded. When we have finished issuing verification requests, we again use the space map ioctl to map the recorded media errors back to the metadata structures or files that own the space, and report the data have been lost.

Conclusion

It is hoped that the reader of this document has followed the designs laid out in this document and now has some familiarity with how XFS performs online rebuilding of its metadata indices, and how filesystem users can interact with that functionality. Although the scope of this work is daunting, it is hoped that this guide will make it easier for code readers to understand what has been built, for whom it has been built, and why. Please feel free to contact the XFS mailing list with questions.

Future Work

Quite a lot of future XFS work ties into the online fsck feature. Here is a quick discussion of a few pieces that are immediately adjacent.

FIEXCHANGE_RANGE

As discussed earlier, a second frontend to the atomic extent swap mechanism is a new ioctl call that userspace programs can use to commit updates to files atomically. This frontend has been out for review for several years now, though the necessary refinements to online repair and lack of customer demand mean that the proposal has not been pushed very hard.

Vectorized Scrub

As it turns out, the refactoring of repair items mentioned earlier was a catalyst for enabling a vectorized scrub system call. Since 2018, the cost of making a kernel call has increased considerably on some systems to mitigate the effects of speculative execution attacks. This incentivizes us to make as few system calls as possible to reduce the number of times we have to cross a security boundary.

With vectorized scrub, we now push to the kernel the identity of a filesystem object, a list of scrub types to run against that object, and a simple representation of the data dependencies between the selected scrub types. The kernel executes as much of the userspace plan as it can until it hits a dependency that cannot be satisfied due to a corruption, and tells userspace how much was accomplished. It is hoped that io_uring will pick up enough of this functionality that we can use that instead of adding a separate vectored scrub system call to XFS.

The relevant patchsets are the kernel and userspace vectorized scrub series.

Quality of Service Targets for Scrub

One serious shortcoming of the online fsck code is that the amount of time that we can spend in the kernel holding resource locks is basically unbounded. Userspace is allowed to send a fatal signal to the process which will cause xfs_scrub to exit when it reaches a good stopping point, but there’s no way for userspace to provide a time budget to the kernel. Given that we have helpers to detect fatal signals, it shouldn’t be too much work to allow userspace to specify a timeout for a scrub/repair operation and abort the operation if it exceeds budget.

Parent Pointers

Directory parent pointers were first proposed as an XFS feature more than a decade ago by SGI. In that implementation, each link from a parent directory to a child file would be augmented by an extended attribute in the child that could be used to identify the directory. Unfortunately, this early implementation had two major shortcomings: First, the XFS codebase of the late 2000s did not have the infrastructure to enforce strong referential integrity in the directory tree, which is a fancy way to say that it could not guarantee that a change in a forward link would always be followed up by a corresponding change to the reverse links. Second, the extended attribute did not record the name of the directory entry in the parent, so the first parent pointer implementation cannot be used to reconnect the directory tree.

In the second implementation (currently being developed by Allison Henderson), the extended attribute code will be enhanced to use log intent items to guarantee that an extended attribute update can always be completed by log recovery. The parent pointer data will also include the entry name and location in the parent. In other words, we will be storing parent pointer mappings of the form (parent_ino, parent_gen, dirent_pos) => (dirent_name) in the extended attribute data. With that in place, XFS can guarantee strong referential integrity of directory tree operations – forward links will always be complemented with reverse links.

When parent pointers have landed, it will no longer be necessary to salvage damaged directories and hope for the best! Instead, we will set up a coordinated inode scan and a directory entry live update hook. We can then scan the filesystem to find the parent of a directory being repaired, and we can reconstruct the rest of the directory entries from the parent pointer information. The new entries will be written to the temporary directory like they are now, and the atomic extent swap will be used to replace the old directory with the new one.

Question: How do we ensure that the dirent_pos fields match in the reconstructed directory? Is that field merely advisory, since the other three values are sufficient to find the entry in the parent? Or will we have to remove the parent pointer entry and re-add it?

Defragmenting Free Space

We define this operation as clearing a portion of the physical storage so that it becomes a contiguous chunk of free space.

The first piece we need is the ability to read the reverse mapping index from userspace. This already exists in the form of the FS_IOC_GETFSMAP ioctl. The second piece we need is a new fallocate mode (FALLOC_FL_MAP_FREE_SPACE) that allocates the free space in a region and maps it to a file. Call this file the “space collector” file. The third piece is the ability to force an online repair.

To clear all the metadata out of a portion of physical storage, we use the new fallocate call to map any free space in that region to the space collector. Next, we find all metadata blocks in that region by way of GETFSMAP, and issue forced repair requests on the data structure. This will most probably result in the metadata being rebuilt somewhere else. That takes care of everything except inode chunks and file data. After each rebuild operation, we re-call the “map free space” function to collect the newly freed space.

To clear all the file data out of a portion of the physical storage, we again use the FSMAP information to find relevant file data blocks. Once we’ve identified a good target, we use the FICLONERANGE call on that file to try to map the space to a dummy file. Cloning the extent means that the original owners cannot overwrite the contents; any changes will be staged somewhere else via copy-on-write. We can then make our own copy of the frozen extent in an area that we are not clearing, and use FIEDEUPRANGE (or the atomic extent swap feature) to change the target file’s data extent mapping away from the area we’re clearing. After we’ve frozen the file data extent and removed all other mappings, we reflink the space into the space collector file.

There are further optimizations to be had in the above algorithm. If we need to clear a piece of physical storage that has a high sharing factor, we would strongly prefer to retain this sharing factor. In fact, we prefer to relocate highly shared chunks first. To make this work smoothly, we add a fourth piece: a new ioctl (FS_IOC_GETREFCOUNTS) to report the reference count records to userspace. With the refcount information exposed, we can quickly find the longest, most shared data extents in the filesystem, and target them first.

Question: How do we move inode chunks? Dave Chinner has a prototype that creates a new file with the old contents and then locklessly runs around the filesystem updating directory entries. The operation cannot complete if the filesystem goes down. That problem isn’t totally insurmountable: create an inode remapping table hidden behind a jump label, and a log item that tracks the kernel walking the filesystem to update directory entries. The trouble is, we can’t do anything about open files, since we can’t revoke them. Can we abuse jump labels even further to add a revoke-me-hard bailout to every code path coming in from userspace?

The relevant patchsets are the kernel and userspace freespace defrag series.

Shrinking Filesystems

Removing the end of the filesystem ought to be a simple matter of evacuating the data and metadata at the end of the filesystem, and handing the freed space to the shrink code. Unfortunately, that requires an evacuation of the space at end of the filesystem, which sounds an awful lot like free space defragmentation!