Skip to contentSkip to conversation

xfs: all pending online scrub improvements

PATCH In review Darrick J. Wong 5 participants 216 messages Dec 30, 2022 – Mar 7, 2023 Page 2 of 5

Subsystems (3)
lore
Share & tools
lore
#32 lore raw

PATCH 7/14 xfs: document pageable kernel memory

In reply to Darrick J. Wong

From: Darrick J. Wong <[email protected]>

Add a discussion of pageable kernel memory, since online fsck needs quite a bit more memory than most other parts of the filesystem to stage records and other information.

---
 .../filesystems/xfs-online-fsck-design.rst         |  490 ++++++++++++++++++++
 1 file changed, 490 insertions(+)
Documentation/filesystems/xfs-online-fsck-design.rst +490 -0
index 419eb54ee200..9d7a2ef1d0dd 100644
@@ -383,6 +383,8 @@ 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:
+
 Secondary Metadata
 ``````````````````
 
@@ -1746,3 +1748,491 @@ Scrub teardown disables all static keys obtained by ``xchk_fshooks_enable``.
 
 For more information, please see the kernel documentation of
 Documentation/staging/static-keys.rst.
+
+.. _xfile:
+
+Pageable Kernel Memory
+----------------------
+
+Demonstrations of the first few prototypes of online repair revealed new
+technical requirements that were not originally identified.
+For the first demonstration, 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 subpar since any additional corruption or runtime errors encountered
+during the walk would shut down the filesystem.
+After remount, the blocks containing the half-rebuilt data structure would not
+be accessible until another repair was attempted.
+Solving the problem of half-rebuilt data structures will be discussed in the
+next section.
+
+For the second demonstration, 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.
+However, even this approach needed improving upon.
+
+There are four reasons why traditional Linux kernel memory management isn't
+suitable for storing large datasets:
+
+1. 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.
+
+2. While 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.
+
+3. To overcome these two difficulties, the implementation was adjusted to use
+   doubly linked lists, which means every record object needed two 64-bit list
+   head pointers, which is a lot of overhead.
+
+4. 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 rejected for some types of repairs 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: shmfs.
+In-kernel graphics drivers (most notably i915) take advantage of shmfs files
+to store intermediate data that doesn't need to be in memory at all times, so
+that usage precedent is already established.
+Hence, the ``xfile`` was born!
+
+xfile Access Models
+```````````````````
+
+A survey of the intended uses of xfiles suggested these use cases:
+
+1. Arrays of fixed-sized records (space management btrees, directory and
+   extended attribute entries)
+
+2. Sparse arrays of fixed-sized records (quotas and link counts)
+
+3. Large binary objects (BLOBs) of variable sizes (directory and extended
+   attribute names and values)
+
+4. Staging btrees in memory (reverse mapping btrees)
+
+5. Arbitrary contents (realtime space management)
+
+To support the first four use cases, high level data structures wrap the xfile
+to share functionality between online fsck functions.
+The rest of this section discusses the interfaces that the xfile presents to
+four of those five higher level data structures.
+The fifth use case is discussed in the :ref:`realtime summary <rtsummary>` case
+study.
+
+The most general storage interface supported by the xfile enables the reading
+and writing of arbitrary quantities of data at arbitrary offsets in the xfile.
+This capability is provided by ``xfile_pread`` and ``xfile_pwrite`` functions,
+which behave similarly to their userspace counterparts.
+XFS is very record-based, which suggests that the ability to load and store
+complete records is important.
+To support these cases, a pair of ``xfile_obj_load`` and ``xfile_obj_store``
+functions are provided to read and persist objects into an xfile.
+They are internally the same as pread and pwrite, except that they treat any
+error as an out of memory error.
+For online repair, squashing error conditions in this manner is an acceptable
+behavior because the only reaction is to abort the operation back to userspace.
+All five xfile usecases can be serviced by these four functions.
+
+However, no discussion of file access idioms is complete without answering the
+question, "But what about mmap?"
+It would be *much* more convenient if kernel code could access pageable kernel
+memory with pointers, just like userspace code does with regular memory.
+Like any other filesystem that uses the page cache, reads and writes of xfile
+data lock the cache page and map it into the kernel address space for the
+duration of the operation.
+Unfortunately, shmfs can only write a file page to the swap device if the page
+is unmapped and unlocked, which means the xfile risks causing OOM problems
+unless it is careful not to pin too many pages.
+Therefore, the xfile steers most of its users towards programmatic access so
+that backing pages are not kept locked in memory for longer than is necessary.
+However, for callers performing quick linear scans of xfile data,
+``xfile_get_page`` and ``xfile_put_page`` functions are provided to pin a page
+in memory.
+So far, the only code to use these functions are the xfarray :ref:`sorting
+<xfarray_sort>` algorithms.
+
+xfile Access Coordination
+`````````````````````````
+
+For security reasons, xfiles must be owned privately by the kernel.
+They are marked ``S_PRIVATE`` to prevent interference from the security system,
+must never be mapped into process file descriptor tables, and their pages must
+never be mapped into userspace processes.
+
+To avoid locking recursion issues with the VFS, all accesses to the shmfs file
+are performed by manipulating the page cache directly.
+xfile writes call the ``->write_begin`` and ``->write_end`` functions of the
+xfile's address space to grab writable pages, copy the caller's buffer into the
+page, and release the pages.
+xfile reads call ``shmem_read_mapping_page_gfp`` to grab pages directly before
+copying the contents into the caller's buffer.
+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 and
+freeze locks.
+
+If an xfile is shared between threads to stage repairs, the caller must provide
+its own locks to coordinate access.
+
+.. _xfarray:
+
+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.
+Directories have a set of fixed-size dirent records that point to the names,
+and extended attributes have a set of fixed-size attribute keys that point to
+names and values.
+Quota counters and file link counters index records with numbers.
+During a repair, scrub needs to stage new records during the gathering step and
+retrieve them during the btree building step.
+
+Although this requirement can be satisfied by calling the read and write
+methods of the xfile directly, it is simpler for callers for there to be a
+higher level abstraction to take care of computing array offsets, to provide
+iterator functions, and to deal with sparse records and sorting.
+The ``xfarray`` abstraction presents a linear array for fixed-size records atop
+the byte-accessible xfile.
+
+.. _xfarray_access_patterns:
+
+Array Access Patterns
+^^^^^^^^^^^^^^^^^^^^^
+
+Array access patterns in online fsck tend to fall into three categories.
+Iteration of records is assumed to be necessary for all cases and will be
+covered in the next section.
+
+The first type of caller handles records that are indexed by position.
+Gaps may exist between records, and a record may be updated multiple times
+during the collection step.
+In other words, these callers want a sparse linearly addressed table file.
+The typical use case are quota records or file link count records.
+Access to array elements is performed programmatically via ``xfarray_load`` and
+``xfarray_store`` functions, which wrap the similarly-named xfile functions to
+provide loading and storing of array elements at arbitrary array indices.
+Gaps are defined to be null records, and null records are defined to be a
+sequence of all zero bytes.
+Null records are detected by calling ``xfarray_element_is_null``.
+They are created either by calling ``xfarray_unset`` to null out an existing
+record or by never storing anything to an array index.
+
+The second type of caller handles records that are not indexed by position
+and do not require multiple updates to a record.
+The typical use case here is rebuilding space btrees and key/value btrees.
+These callers can add records to the array without caring about array indices
+via the ``xfarray_append`` function, which stores a record at the end of the
+array.
+For callers that require records to be presentable in a specific order (e.g.
+rebuilding btree data), the ``xfarray_sort`` function can arrange the sorted
+records; this function will be covered later.
+
+The third type of caller is a bag, which is useful for counting records.
+The typical use case here is constructing space extent reference counts from
+reverse mapping information.
+Records can be put in the bag in any order, they can be removed from the bag
+at any time, and uniqueness of records is left to callers.
+The ``xfarray_store_anywhere`` function is used to insert a record in any
+null record slot in the bag; and the ``xfarray_unset`` function removes a
+record from the bag.
+
+The proposed patchset is the
+`big in-memory array
+<https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/log/?h=big-array>`_.
+
+Iterating Array Elements
+^^^^^^^^^^^^^^^^^^^^^^^^
+
+Most users of the xfarray require the ability to iterate the records stored in
+the array.
+Callers can probe every possible array index with the following:
+
+.. code-block:: c
+
+	xfarray_idx_t i;
+	foreach_xfarray_idx(array, i) {
+	    xfarray_load(array, i, &rec);
+
+	    /* do something with rec */
+	}
+
+All users of this idiom must be prepared to handle null records or must already
+know that there aren't any.
+
+For xfarray users that want to iterate a sparse array, the ``xfarray_iter``
+function ignores indices in the xfarray that have never been written to by
+calling ``xfile_seek_data`` (which internally uses ``SEEK_DATA``) to skip areas
+of the array that are not populated with memory pages.
+Once it finds a page, it will skip the zeroed areas of the page.
+
+.. code-block:: c
+
+	xfarray_idx_t i = XFARRAY_CURSOR_INIT;
+	while ((ret = xfarray_iter(array, &i, &rec)) == 1) {
+	    /* do something with rec */
+	}
+
+.. _xfarray_sort:
+
+Sorting Array Elements
+^^^^^^^^^^^^^^^^^^^^^^
+
+During the fourth demonstration of online repair, 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 a heapsort subalgorithm in the spirit of
+`Sedgewick <https://algs4.cs.princeton.edu/23quicksort/>`_ and
+`pdqsort <https://github.com/orlp/pdqsort>`_, with customizations for the Linux
+kernel.
+To sort records in a reasonably short amount of time, ``xfarray`` takes
+advantage of the binary subpartitioning offered by quicksort, but it also uses
+heapsort to hedge aginst performance collapse if the chosen quicksort pivots
+are poor.
+Both algorithms are (in general) O(n * lg(n)), but there is a wide performance
+gulf between the two implementations.
+
+The Linux kernel already contains a reasonably fast 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, ``xfarray`` uses heapsort to constrain the nested recursion of
+quicksort, thereby mitigating quicksort's worst runtime behavior.
+
+Choosing a quicksort pivot is a tricky business.
+A good pivot splits the set to sort in half, leading to the divide and conquer
+behavior that is crucial to  O(n * lg(n)) performance.
+A poor pivot barely splits the subset at all, leading to O(n\ :sup:`2`)
+runtime.
+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.
+
+Most modern quicksort implementations employ Tukey's "ninther" to select a
+pivot from a classic C array.
+Typical ninther implementations pick three unique triads of records, sort each
+of the triads, and then sort the middle value of each triad to determine the
+ninther value.
+As stated previously, however, xfile accesses are not entirely cheap.
+It turned out to be much more performant to read the nine elements into a
+memory buffer, run the kernel's in-memory heapsort on the buffer, and choose
+the 4th element of that buffer as the pivot.
+Tukey's ninthers are described in J. W. Tukey, `The ninther, a technique for
+low-effort robust (resistant) location in large samples`, in *Contributions to
+Survey Sampling and Applied Statistics*, edited by H. David, (Academic Press,
+1978), pp. 251–257.
+
+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.
+Each directory entry record needs to store entry name,
+and each extended attribute needs to store both the attribute name and value.
+The names, keys, and values can consume a large amount of memory, so the
+``xfblob`` abstraction was created to simplify management of these blobs
+atop an xfile.
+
+Blob arrays provide ``xfblob_load`` and ``xfblob_store`` functions to retrieve
+and persist objects.
+The store function returns a magic cookie for every object that it persists.
+Later, callers provide this cookie to the ``xblob_load`` to recall the object.
+The ``xfblob_free`` function frees a specific blob, and the ``xfblob_truncate``
+function frees them all because compaction is not needed.
+
+The details of repairing directories and extended attributes will be discussed
+in a subsequent section about atomic extent swapping.
+However, it should be noted that these repair functions only use blob storage
+to cache a small number of entries before adding them to a temporary ondisk
+file, which is why compaction is not required.
+
+The proposed patchset is at the start of the
+`extended attribute repair
+<https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/log/?h=repair-xattrs>`_ series.
+
+.. _xfbtree:
+
+In-Memory B+Trees
+`````````````````
+
+The chapter about :ref:`secondary metadata<secondary_metadata>` mentioned that
+checking and repairing of secondary metadata commonly requires coordination
+between a live metadata scan of the filesystem and writer threads that are
+updating that metadata.
+Keeping the scan data up to date requires requires the ability to propagate
+metadata updates from the filesystem into the data being collected by the scan.
+This *can* be done by appending concurrent updates into a separate log file and
+applying them before writing the new metadata to disk, but this leads to
+unbounded memory consumption if the rest of the system is very busy.
+Another option is to skip the side-log and commit live updates from the
+filesystem directly into the scan data, which trades more overhead for a lower
+maximum memory requirement.
+In both cases, the data structure holding the scan results must support indexed
+access to perform well.
+
+Given that indexed lookups of scan data is required for both strategies, online
+fsck employs the second strategy of committing live updates directly into
+scan data.
+Because xfarrays are not indexed and do not enforce record ordering, they
+are not suitable for this task.
+Conveniently, however, XFS has a library to create and maintain ordered reverse
+mapping records: the existing rmap btree code!
+If only there was a means to create one in memory.
+
+Recall that the :ref:`xfile <xfile>` abstraction represents memory pages as a
+regular file, which means that the kernel can create byte or block addressable
+virtual address spaces at will.
+The XFS buffer cache specializes in abstracting IO to block-oriented  address
+spaces, which means that adaptation of the buffer cache to interface with
+xfiles enables reuse of the entire btree library.
+Btrees built atop an xfile are collectively known as ``xfbtrees``.
+The next few sections describe how they actually work.
+
+The proposed patchset is the
+`in-memory btree
+<https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/log/?h=in-memory-btrees>`_
+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 modify the buffer ``ioapply`` function to "read" cached
+pages from the xfile and "write" cached pages back to the xfile.
+Multiple access to individual buffers is controlled by the ``xfs_buf`` lock,
+since the xfile does not provide any locking on its own.
+With this adaptation in place, users of the xfile-backed buffer cache use
+exactly the same APIs as users of the disk-backed buffer cache.
+The separation between xfile and buffer cache implies higher memory usage since
+they do not share pages, but this property could some day enable transactional
+updates to an in-memory btree.
+Today, however, it simply eliminates the need for new code.
+
+Space Management with an xfbtree
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Space management for an xfile is very simple -- each btree block is one memory
+page in size.
+These blocks use the same header format as an on-disk btree, but the in-memory
+block verifiers ignore the checksums, assuming that xfile memory is no more
+corruption-prone than regular DRAM.
+Reusing existing code here is more important than absolute memory efficiency.
+
+The very first block of an xfile backing an xfbtree contains a header block.
+The header describes the owner, height, and the block number of the root
+xfbtree block.
+
+To allocate a btree block, use ``xfile_seek_data`` to find a gap in the file.
+If there are no gaps, create one by extending the length of the xfile.
+Preallocate space for the block with ``xfile_prealloc``, and hand back the
+location.
+To free an xfbtree block, use ``xfile_discard`` (which internally uses
+``FALLOC_FL_PUNCH_HOLE``) to remove the memory page from the xfile.
+
+Populating an xfbtree
+^^^^^^^^^^^^^^^^^^^^^
+
+An online fsck function that wants to create an xfbtree should proceed as
+follows:
+
+1. Call ``xfile_create`` to create an xfile.
+
+2. Call ``xfs_alloc_memory_buftarg`` to create a buffer cache target structure
+   pointing to the xfile.
+
+3. Pass the buffer cache target, buffer ops, and other information to
+   ``xfbtree_create`` to write an initial tree header and root block to the
+   xfile.
+   Each btree type should define a wrapper that passes necessary arguments to
+   the creation function.
+   For example, rmap btrees define ``xfs_rmapbt_mem_create`` to take care of
+   all the necessary details for callers.
+   A ``struct xfbtree`` object will be returned.
+
+4. Pass the xfbtree object to the btree cursor creation function for the
+   btree type.
+   Following the example above, ``xfs_rmapbt_mem_cursor`` takes care of this
+   for callers.
+
+5. Pass the btree cursor to the regular btree functions to make queries against
+   and to update the in-memory btree.
+   For example, a btree cursor for an rmap xfbtree can be passed to the
+   ``xfs_rmap_*`` functions just like any other btree cursor.
+   See the :ref:`next section<xfbtree_commit>` for information on dealing with
+   xfbtree updates that are logged to a transaction.
+
+6. When finished, delete the btree cursor, destroy the xfbtree object, free the
+   buffer target, and the destroy the xfile to release all resources.
+
+.. _xfbtree_commit:
+
+Committing Logged xfbtree Buffers
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Although it is a clever hack to reuse the rmap btree code to handle the staging
+structure, the ephemeral nature of the in-memory btree block storage presents
+some challenges of its own.
+The XFS transaction manager must not commit buffer log items for buffers backed
+by an xfile because the log format does not understand updates for devices
+other than the data device.
+An ephemeral xfbtree probably will not exist by the time the AIL checkpoints
+log transactions back into the filesystem, and certainly won't exist during
+log recovery.
+For these reasons, any code updating an xfbtree in transaction context must
+remove the buffer log items from the transaction and write the updates into the
+backing xfile before committing or cancelling the transaction.
+
+The ``xfbtree_trans_commit`` and ``xfbtree_trans_cancel`` functions implement
+this functionality as follows:
+
+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
+   that were detached in step 3.
+
+6. Submit the delwri list to commit the changes to the xfile, if the updates
+   are being committed.
+
+After removing xfile logged buffers from the transaction in this manner, the
+transaction can be committed or cancelled.
#33 lore raw

Re: [PATCH 07/14] xfs: document pageable kernel memory

Quoted 84 lines · Darrick J. Wong

From: Darrick J. Wong <[email protected]>

Add a discussion of pageable kernel memory, since online fsck needs quite a bit more memory than most other parts of the filesystem to stage
records and other information.

---
 .../filesystems/xfs-online-fsck-design.rst         |  490
++++++++++++++++++++

 1 file changed, 490 insertions(+)
Documentation/filesystems/xfs-online-fsck-design.rst +0 -0
index 419eb54ee200..9d7a2ef1d0dd 100644
@@ -383,6 +383,8 @@ 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:
+
 Secondary Metadata
 ``````````````````

Documentation/filesystems/xfs-online-fsck-design.rst +0 -0
@@ -1746,3 +1748,491 @@ Scrub teardown disables all static keys

obtained by ``xchk_fshooks_enable``.

 For more information, please see the kernel documentation of Documentation/staging/static-keys.rst.

Documentation/filesystems/xfs-online-fsck-design.rst +7 -0
+
+.. _xfile:
+
+Pageable Kernel Memory
+----------------------
+
+Demonstrations of the first few prototypes of online repair revealed

new

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+technical requirements that were not originally identified.
+For the first demonstration, the code walked whatever filesystem
+metadata it needed to synthesize new records and inserted records

into a new

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+btree as it found them.
+This was subpar since any additional corruption or runtime errors

encountered

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+during the walk would shut down the filesystem.
+After remount, the blocks containing the half-rebuilt data structure

would not

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+be accessible until another repair was attempted.
+Solving the problem of half-rebuilt data structures will be

discussed in the

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+next section.
+
+For the second demonstration, the synthesized records were instead

stored in

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+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.

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+However, even this approach needed improving upon.
+
+There are four reasons why traditional Linux kernel memory

management isn't

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+suitable for storing large datasets:
+
+1. 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. +
+2. While 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.
+
+3. To overcome these two difficulties, the implementation was adjusted to use

Quoted 8 lines

+   doubly linked lists, which means every record object needed two 64-bit list
+   head pointers, which is a lot of overhead.
+
+4. Kernel memory is pinned, which can drive the system out of memory, leading
+   to OOM kills of unrelated processes.
+

I think I maybe might just jump to what ever the current plan is instead of trying to keep a record of the dev history in the document. I'm sure we're not done yet, dev really never is, so in order for the documentation to be maintained, it would just get bigger and bigger to keep documenting it this way. It's not that the above isnt valuable, but maybe a different kind of document really.

Quoted 2 lines

+For the third iteration, attention swung back to the possibility of using

Due to the large volume of metadata that needs to be processed, ofsck uses...

Quoted 74 lines

+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

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+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 rejected for some types of repairs because a filesystem with
+compromised space and inode metadata should never be used to fix compromised

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+space or inode metadata.
+However, the kernel already has a facility for byte-addressable and

pageable

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+storage: shmfs.
+In-kernel graphics drivers (most notably i915) take advantage of

shmfs files
+to store intermediate data that doesn't need to be in memory at all times, so

Documentation/filesystems/xfs-online-fsck-design.rst +9 -0
+that usage precedent is already established.
+Hence, the ``xfile`` was born!
+
+xfile Access Models
+```````````````````
+
+A survey of the intended uses of xfiles suggested these use cases:
+
+1. Arrays of fixed-sized records (space management btrees, directory

and
+   extended attribute entries)

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+
+2. Sparse arrays of fixed-sized records (quotas and link counts)
+
+3. Large binary objects (BLOBs) of variable sizes (directory and

extended
+   attribute names and values)

Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+
+4. Staging btrees in memory (reverse mapping btrees)
+
+5. Arbitrary contents (realtime space management)
+
+To support the first four use cases, high level data structures wrap

the xfile

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+to share functionality between online fsck functions.
+The rest of this section discusses the interfaces that the xfile

presents to

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+four of those five higher level data structures.
+The fifth use case is discussed in the :ref:`realtime summary

<rtsummary>` case

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+study.
+
+The most general storage interface supported by the xfile enables

the reading
+and writing of arbitrary quantities of data at arbitrary offsets in the xfile.
+This capability is provided by ``xfile_pread`` and ``xfile_pwrite`` functions,

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+which behave similarly to their userspace counterparts.
+XFS is very record-based, which suggests that the ability to load

and store

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+complete records is important.
+To support these cases, a pair of ``xfile_obj_load`` and

``xfile_obj_store``

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+functions are provided to read and persist objects into an xfile.
+They are internally the same as pread and pwrite, except that they

treat any

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+error as an out of memory error.
+For online repair, squashing error conditions in this manner is an

acceptable
+behavior because the only reaction is to abort the operation back to userspace.

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+All five xfile usecases can be serviced by these four functions.
+
+However, no discussion of file access idioms is complete without
Quoted 2 lines

answering the
+question, "But what about mmap?"

I actually wouldn't spend too much time discussing solutions that didn't work for what ever reason, unless someones really asking for it. I think this section would read just fine to trim off the last paragraph here

Quoted 43 lines

+It would be *much* more convenient if kernel code could access pageable kernel
+memory with pointers, just like userspace code does with regular memory.
+Like any other filesystem that uses the page cache, reads and writes of xfile
+data lock the cache page and map it into the kernel address space for the

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+duration of the operation.
+Unfortunately, shmfs can only write a file page to the swap device

if the page
+is unmapped and unlocked, which means the xfile risks causing OOM problems

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+unless it is careful not to pin too many pages.
+Therefore, the xfile steers most of its users towards programmatic

access so
+that backing pages are not kept locked in memory for longer than is necessary.
+However, for callers performing quick linear scans of xfile data, +``xfile_get_page`` and ``xfile_put_page`` functions are provided to pin a page

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+in memory.
+So far, the only code to use these functions are the xfarray

:ref:`sorting
+<xfarray_sort>` algorithms.

Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+
+xfile Access Coordination
+`````````````````````````
+
+For security reasons, xfiles must be owned privately by the kernel.
+They are marked ``S_PRIVATE`` to prevent interference from the

security system,
+must never be mapped into process file descriptor tables, and their pages must

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+never be mapped into userspace processes.
+
+To avoid locking recursion issues with the VFS, all accesses to the

shmfs file

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+are performed by manipulating the page cache directly.
+xfile writes call the ``->write_begin`` and ``->write_end``

functions of the
+xfile's address space to grab writable pages, copy the caller's buffer into the

Documentation/filesystems/xfs-online-fsck-design.rst

Quoted 2 lines
Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+page, and release the pages.
+xfile reads call ``shmem_read_mapping_page_gfp`` to grab pages

xfile readers

Quoted 11 lines

directly before

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+copying the contents into the caller's buffer.
+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 and

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+freeze locks.
+
+If an xfile is shared between threads to stage repairs, the caller

must provide
+its own locks to coordinate access.

Ofsck threads that share an xfile between stage repairs will use their own locks to coordinate access with each other.

?

Quoted 240 lines
Documentation/filesystems/xfs-online-fsck-design.rst +7 -0
+
+.. _xfarray:
+
+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

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+records indexed with a classic B+ tree.
+Directories have a set of fixed-size dirent records that point to

the names,
+and extended attributes have a set of fixed-size attribute keys that point to

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+names and values.
+Quota counters and file link counters index records with numbers.
+During a repair, scrub needs to stage new records during the

gathering step and

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+retrieve them during the btree building step.
+
+Although this requirement can be satisfied by calling the read and

write
+methods of the xfile directly, it is simpler for callers for there to be a
+higher level abstraction to take care of computing array offsets, to provide

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+iterator functions, and to deal with sparse records and sorting.
+The ``xfarray`` abstraction presents a linear array for fixed-size

records atop

Documentation/filesystems/xfs-online-fsck-design.rst +8 -0
+the byte-accessible xfile.
+
+.. _xfarray_access_patterns:
+
+Array Access Patterns
+^^^^^^^^^^^^^^^^^^^^^
+
+Array access patterns in online fsck tend to fall into three

categories.
+Iteration of records is assumed to be necessary for all cases and will be

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+covered in the next section.
+
+The first type of caller handles records that are indexed by

position.
+Gaps may exist between records, and a record may be updated multiple times

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+during the collection step.
+In other words, these callers want a sparse linearly addressed table

file.

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+The typical use case are quota records or file link count records.
+Access to array elements is performed programmatically via

``xfarray_load`` and
+``xfarray_store`` functions, which wrap the similarly-named xfile functions to
+provide loading and storing of array elements at arbitrary array indices.
+Gaps are defined to be null records, and null records are defined to be a

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+sequence of all zero bytes.
+Null records are detected by calling ``xfarray_element_is_null``.
+They are created either by calling ``xfarray_unset`` to null out an

existing

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+record or by never storing anything to an array index.
+
+The second type of caller handles records that are not indexed by

position

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+and do not require multiple updates to a record.
+The typical use case here is rebuilding space btrees and key/value

btrees.
+These callers can add records to the array without caring about array indices
+via the ``xfarray_append`` function, which stores a record at the end of the

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+array.
+For callers that require records to be presentable in a specific

order (e.g.
+rebuilding btree data), the ``xfarray_sort`` function can arrange the sorted

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+records; this function will be covered later.
+
+The third type of caller is a bag, which is useful for counting

records.
+The typical use case here is constructing space extent reference counts from

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+reverse mapping information.
+Records can be put in the bag in any order, they can be removed from

the bag

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+at any time, and uniqueness of records is left to callers.
+The ``xfarray_store_anywhere`` function is used to insert a record

in any
+null record slot in the bag; and the ``xfarray_unset`` function removes a

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+record from the bag.
+
+The proposed patchset is the
+`big in-memory array
+<

https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/
log/?h=big-array>`_.

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+
+Iterating Array Elements
+^^^^^^^^^^^^^^^^^^^^^^^^
+
+Most users of the xfarray require the ability to iterate the records

stored in

Documentation/filesystems/xfs-online-fsck-design.rst +13 -0
+the array.
+Callers can probe every possible array index with the following:
+
+.. code-block:: c
+
+       xfarray_idx_t i;
+       foreach_xfarray_idx(array, i) {
+           xfarray_load(array, i, &rec);
+
+           /* do something with rec */
+       }
+
+All users of this idiom must be prepared to handle null records or

must already

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+know that there aren't any.
+
+For xfarray users that want to iterate a sparse array, the

``xfarray_iter``
+function ignores indices in the xfarray that have never been written to by
+calling ``xfile_seek_data`` (which internally uses ``SEEK_DATA``) to skip areas

Documentation/filesystems/xfs-online-fsck-design.rst +16 -0
+of the array that are not populated with memory pages.
+Once it finds a page, it will skip the zeroed areas of the page.
+
+.. code-block:: c
+
+       xfarray_idx_t i = XFARRAY_CURSOR_INIT;
+       while ((ret = xfarray_iter(array, &i, &rec)) == 1) {
+           /* do something with rec */
+       }
+
+.. _xfarray_sort:
+
+Sorting Array Elements
+^^^^^^^^^^^^^^^^^^^^^^
+
+During the fourth demonstration of online repair, 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

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+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

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+set prior to bulk loading.
+
+The sorting algorithm used in the xfarray is actually a combination

of adaptive
+quicksort and a heapsort subalgorithm in the spirit of +Sedgewick <https://algs4.cs.princeton.edu/23quicksort/>_ and +pdqsort <https://github.com/orlp/pdqsort>_, with customizations for the Linux

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+kernel.
+To sort records in a reasonably short amount of time, ``xfarray``

takes
+advantage of the binary subpartitioning offered by quicksort, but it also uses
+heapsort to hedge aginst performance collapse if the chosen quicksort pivots

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+are poor.
+Both algorithms are (in general) O(n * lg(n)), but there is a wide

performance

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+gulf between the two implementations.
+
+The Linux kernel already contains a reasonably fast implementation

of heapsort.
+It only operates on regular C arrays, which limits the scope of its usefulness.

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+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.

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+In other words, ``xfarray`` uses heapsort to constrain the nested

recursion of

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+quicksort, thereby mitigating quicksort's worst runtime behavior.
+
+Choosing a quicksort pivot is a tricky business.
+A good pivot splits the set to sort in half, leading to the divide

and conquer

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+behavior that is crucial to  O(n * lg(n)) performance.
+A poor pivot barely splits the subset at all, leading to O(n\

:sup:2)

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+runtime.
+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

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+median of the nine.
+
+Most modern quicksort implementations employ Tukey's "ninther" to

select a

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+pivot from a classic C array.
+Typical ninther implementations pick three unique triads of records,

sort each
+of the triads, and then sort the middle value of each triad to determine the

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+ninther value.
+As stated previously, however, xfile accesses are not entirely

cheap.
+It turned out to be much more performant to read the nine elements into a
+memory buffer, run the kernel's in-memory heapsort on the buffer, and choose

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+the 4th element of that buffer as the pivot.
+Tukey's ninthers are described in J. W. Tukey, `The ninther, a

technique for
+low-effort robust (resistant) location in large samples`, in *Contributions to
+Survey Sampling and Applied Statistics*, edited by H. David, (Academic Press,
+1978), pp. 251–257.

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+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.

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+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

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+reduce map/unmap cycles.
+Surprisingly, this reduces overall sort runtime by nearly half again
Quoted 3 lines

after
+accounting for the application of heapsort directly onto xfile pages.

This sorting section is insightful, but I think I'd be ok with out it too. Or maybe save it for later in the document as an "implementation details" section, or something similar. It seems like there's still a lot to cover about how ofsck works in general before we start drilling into things like the runtime complexity of the sorting algorithm it uses.

Quoted 257 lines
Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+
+Blob Storage
+````````````
+
+Extended attributes and directories add an additional requirement

for staging

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+records: arbitrary byte sequences of finite length.
+Each directory entry record needs to store entry name,
+and each extended attribute needs to store both the attribute name

and value.
+The names, keys, and values can consume a large amount of memory, so the
+``xfblob`` abstraction was created to simplify management of these blobs

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+atop an xfile.
+
+Blob arrays provide ``xfblob_load`` and ``xfblob_store`` functions

to retrieve

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+and persist objects.
+The store function returns a magic cookie for every object that it

persists.
+Later, callers provide this cookie to the ``xblob_load`` to recall the object.
+The ``xfblob_free`` function frees a specific blob, and the ``xfblob_truncate``

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+function frees them all because compaction is not needed.
+
+The details of repairing directories and extended attributes will be

discussed

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+in a subsequent section about atomic extent swapping.
+However, it should be noted that these repair functions only use

blob storage
+to cache a small number of entries before adding them to a temporary ondisk

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+file, which is why compaction is not required.
+
+The proposed patchset is at the start of the
+`extended attribute repair
+<

https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/
log/?h=repair-xattrs>`_ series.

Documentation/filesystems/xfs-online-fsck-design.rst +7 -0
+
+.. _xfbtree:
+
+In-Memory B+Trees
+`````````````````
+
+The chapter about :ref:`secondary metadata<secondary_metadata>`

mentioned that
+checking and repairing of secondary metadata commonly requires coordination
+between a live metadata scan of the filesystem and writer threads that are

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+updating that metadata.
+Keeping the scan data up to date requires requires the ability to

propagate
+metadata updates from the filesystem into the data being collected by the scan.
+This *can* be done by appending concurrent updates into a separate log file and
+applying them before writing the new metadata to disk, but this leads to

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+unbounded memory consumption if the rest of the system is very busy.
+Another option is to skip the side-log and commit live updates from

the
+filesystem directly into the scan data, which trades more overhead for a lower

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+maximum memory requirement.
+In both cases, the data structure holding the scan results must

support indexed

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+access to perform well.
+
+Given that indexed lookups of scan data is required for both

strategies, online
+fsck employs the second strategy of committing live updates directly into

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+scan data.
+Because xfarrays are not indexed and do not enforce record ordering,

they

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+are not suitable for this task.
+Conveniently, however, XFS has a library to create and maintain

ordered reverse

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+mapping records: the existing rmap btree code!
+If only there was a means to create one in memory.
+
+Recall that the :ref:`xfile <xfile>` abstraction represents memory

pages as a
+regular file, which means that the kernel can create byte or block addressable

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+virtual address spaces at will.
+The XFS buffer cache specializes in abstracting IO to block-

oriented  address
+spaces, which means that adaptation of the buffer cache to interface with

Documentation/filesystems/xfs-online-fsck-design.rst +7 -0
+xfiles enables reuse of the entire btree library.
+Btrees built atop an xfile are collectively known as ``xfbtrees``.
+The next few sections describe how they actually work.
+
+The proposed patchset is the
+`in-memory btree
+<

https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/
log/?h=in-memory-btrees>`_

Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+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

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+per-AG structure.
+The second change is to modify the buffer ``ioapply`` function to

"read" cached

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+pages from the xfile and "write" cached pages back to the xfile.
+Multiple access to individual buffers is controlled by the

``xfs_buf`` lock,

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+since the xfile does not provide any locking on its own.
+With this adaptation in place, users of the xfile-backed buffer

cache use

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+exactly the same APIs as users of the disk-backed buffer cache.
+The separation between xfile and buffer cache implies higher memory

usage since
+they do not share pages, but this property could some day enable transactional

Documentation/filesystems/xfs-online-fsck-design.rst +7 -0
+updates to an in-memory btree.
+Today, however, it simply eliminates the need for new code.
+
+Space Management with an xfbtree
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Space management for an xfile is very simple -- each btree block is

one memory

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+page in size.
+These blocks use the same header format as an on-disk btree, but the

in-memory
+block verifiers ignore the checksums, assuming that xfile memory is no more

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+corruption-prone than regular DRAM.
+Reusing existing code here is more important than absolute memory

efficiency.

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+The very first block of an xfile backing an xfbtree contains a

header block.
+The header describes the owner, height, and the block number of the root

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+xfbtree block.
+
+To allocate a btree block, use ``xfile_seek_data`` to find a gap in

the file.
+If there are no gaps, create one by extending the length of the xfile.
+Preallocate space for the block with ``xfile_prealloc``, and hand back the

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+location.
+To free an xfbtree block, use ``xfile_discard`` (which internally

uses
+``FALLOC_FL_PUNCH_HOLE``) to remove the memory page from the xfile.

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+
+Populating an xfbtree
+^^^^^^^^^^^^^^^^^^^^^
+
+An online fsck function that wants to create an xfbtree should

proceed as

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+follows:
+
+1. Call ``xfile_create`` to create an xfile.
+
+2. Call ``xfs_alloc_memory_buftarg`` to create a buffer cache target

structure
+   pointing to the xfile.
+
+3. Pass the buffer cache target, buffer ops, and other information to
+   ``xfbtree_create`` to write an initial tree header and root block to the
+   xfile.
+   Each btree type should define a wrapper that passes necessary arguments to
+   the creation function.
+   For example, rmap btrees define ``xfs_rmapbt_mem_create`` to take care of
+   all the necessary details for callers.
+   A ``struct xfbtree`` object will be returned.
+
+4. Pass the xfbtree object to the btree cursor creation function for the
+   btree type.
+   Following the example above, ``xfs_rmapbt_mem_cursor`` takes care of this
+   for callers.
+
+5. Pass the btree cursor to the regular btree functions to make queries against
+   and to update the in-memory btree.
+   For example, a btree cursor for an rmap xfbtree can be passed to the
+   ``xfs_rmap_*`` functions just like any other btree cursor. +   See the :ref:next section<xfbtree_commit> for information on dealing with
+   xfbtree updates that are logged to a transaction.
+
+6. When finished, delete the btree cursor, destroy the xfbtree object, free the
+   buffer target, and the destroy the xfile to release all resources.

Documentation/filesystems/xfs-online-fsck-design.rst +7 -0
+
+.. _xfbtree_commit:
+
+Committing Logged xfbtree Buffers
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Although it is a clever hack to reuse the rmap btree code to handle

the staging
+structure, the ephemeral nature of the in-memory btree block storage presents

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+some challenges of its own.
+The XFS transaction manager must not commit buffer log items for

buffers backed
+by an xfile because the log format does not understand updates for devices

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+other than the data device.
+An ephemeral xfbtree probably will not exist by the time the AIL

checkpoints
+log transactions back into the filesystem, and certainly won't exist during

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+log recovery.
+For these reasons, any code updating an xfbtree in transaction

context must
+remove the buffer log items from the transaction and write the updates into the

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+backing xfile before committing or cancelling the transaction.
+
+The ``xfbtree_trans_commit`` and ``xfbtree_trans_cancel`` functions

implement

Documentation/filesystems/xfs-online-fsck-design.rst +11 -0
+this functionality as follows:
+
+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
+   that were detached in step 3.
+
+6. Submit the delwri list to commit the changes to the xfile, if the updates
+   are being committed.

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+After removing xfile logged buffers from the transaction in this
Quoted 2 lines

manner, the
+transaction can be committed or cancelled.

Rest of this looks pretty good, organizing nits aside.

Allison

Quoted 1 line
#34 lore raw

Re: [PATCH 07/14] xfs: document pageable kernel memory

Quoted 91 lines · Allison Henderson
Quoted 90 lines · Darrick J. Wong

From: Darrick J. Wong <[email protected]>

Add a discussion of pageable kernel memory, since online fsck needs quite a bit more memory than most other parts of the filesystem to stage
records and other information.

---
 .../filesystems/xfs-online-fsck-design.rst         |  490
++++++++++++++++++++

 1 file changed, 490 insertions(+)
Documentation/filesystems/xfs-online-fsck-design.rst +0 -0
index 419eb54ee200..9d7a2ef1d0dd 100644
@@ -383,6 +383,8 @@ 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:
+
 Secondary Metadata
 ``````````````````

Documentation/filesystems/xfs-online-fsck-design.rst +0 -0
@@ -1746,3 +1748,491 @@ Scrub teardown disables all static keys

obtained by ``xchk_fshooks_enable``.

 For more information, please see the kernel documentation of Documentation/staging/static-keys.rst.

Documentation/filesystems/xfs-online-fsck-design.rst +7 -0
+
+.. _xfile:
+
+Pageable Kernel Memory
+----------------------
+
+Demonstrations of the first few prototypes of online repair revealed

new

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+technical requirements that were not originally identified.
+For the first demonstration, the code walked whatever filesystem
+metadata it needed to synthesize new records and inserted records

into a new

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+btree as it found them.
+This was subpar since any additional corruption or runtime errors

encountered

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+during the walk would shut down the filesystem.
+After remount, the blocks containing the half-rebuilt data structure

would not

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+be accessible until another repair was attempted.
+Solving the problem of half-rebuilt data structures will be

discussed in the

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+next section.
+
+For the second demonstration, the synthesized records were instead

stored in

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+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.

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+However, even this approach needed improving upon.
+
+There are four reasons why traditional Linux kernel memory

management isn't

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+suitable for storing large datasets:
+
+1. 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. +
+2. While 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.
+
+3. To overcome these two difficulties, the implementation was adjusted to use
+   doubly linked lists, which means every record object needed two 64-bit list
+   head pointers, which is a lot of overhead.
+
+4. Kernel memory is pinned, which can drive the system out of memory, leading

Quoted 8 lines
Quoted 2 lines

+   to OOM kills of unrelated processes.
+

I think I maybe might just jump to what ever the current plan is instead of trying to keep a record of the dev history in the document. I'm sure we're not done yet, dev really never is, so in order for the documentation to be maintained, it would just get bigger and bigger to keep documenting it this way. It's not that the above isnt valuable, but maybe a different kind of document really.

OK, I've shortened this introduction to outline the requirements, and trimmed the historical information to a sidebar:

"Some online checking functions work by scanning the filesystem to build a shadow copy of an ondisk metadata structure in memory and comparing the two copies. For online repair to rebuild a metadata structure, it must compute the record set that will be stored in the new structure before it can persist that new structure to disk. Ideally, repairs complete with a single atomic commit that introduces a new data structure. To meet these goals, the kernel needs to collect a large amount of information in a place that doesn’t require the correct operation of the filesystem.

"Kernel memory isn’t suitable because:

* Allocating a contiguous region of memory to create a C array is very
difficult, especially on 32-bit systems.

* Linked lists of records introduce double pointer overhead which is
very high and eliminate the possibility of indexed lookups.

* Kernel memory is pinned, which can drive the system into OOM
conditions.

* The system might not have sufficient memory to stage all the
information.

"At any given time, online fsck does not need to keep the entire record set in memory, which means that individual records can be paged out if necessary. Continued development of online fsck demonstrated that the ability to perform indexed data storage would also be very useful. Fortunately, the Linux kernel already has a facility for byte-addressable and pageable storage: tmpfs. In-kernel graphics drivers (most notably i915) take advantage of tmpfs files to store intermediate data that doesn’t need to be in memory at all times, so that usage precedent is already established. Hence, the xfile was born!

Historical Sidebar
------------------

"The first edition of online repair inserted records into a new btree as it found them, which failed because filesystem could shut down with a built data structure, which would be live after recovery finished.

"The second edition solved the half-rebuilt structure problem by storing everything in memory, but frequently ran the system out of memory.

"The third edition solved the OOM problem by using linked lists, but the list overhead was extreme."

Quoted 80 lines
Quoted 4 lines

+For the third iteration, attention swung back to the possibility of using

Due to the large volume of metadata that needs to be processed, ofsck uses...

Quoted 72 lines

+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

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+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 rejected for some types of repairs because a filesystem with
+compromised space and inode metadata should never be used to fix compromised

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+space or inode metadata.
+However, the kernel already has a facility for byte-addressable and

pageable

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+storage: shmfs.
+In-kernel graphics drivers (most notably i915) take advantage of

shmfs files
+to store intermediate data that doesn't need to be in memory at all times, so

Documentation/filesystems/xfs-online-fsck-design.rst +9 -0
+that usage precedent is already established.
+Hence, the ``xfile`` was born!
+
+xfile Access Models
+```````````````````
+
+A survey of the intended uses of xfiles suggested these use cases:
+
+1. Arrays of fixed-sized records (space management btrees, directory

and
+   extended attribute entries)

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+
+2. Sparse arrays of fixed-sized records (quotas and link counts)
+
+3. Large binary objects (BLOBs) of variable sizes (directory and

extended
+   attribute names and values)

Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+
+4. Staging btrees in memory (reverse mapping btrees)
+
+5. Arbitrary contents (realtime space management)
+
+To support the first four use cases, high level data structures wrap

the xfile

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+to share functionality between online fsck functions.
+The rest of this section discusses the interfaces that the xfile

presents to

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+four of those five higher level data structures.
+The fifth use case is discussed in the :ref:`realtime summary

<rtsummary>` case

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+study.
+
+The most general storage interface supported by the xfile enables

the reading
+and writing of arbitrary quantities of data at arbitrary offsets in the xfile.
+This capability is provided by ``xfile_pread`` and ``xfile_pwrite`` functions,

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+which behave similarly to their userspace counterparts.
+XFS is very record-based, which suggests that the ability to load

and store

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+complete records is important.
+To support these cases, a pair of ``xfile_obj_load`` and

``xfile_obj_store``

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+functions are provided to read and persist objects into an xfile.
+They are internally the same as pread and pwrite, except that they

treat any

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+error as an out of memory error.
+For online repair, squashing error conditions in this manner is an

acceptable
+behavior because the only reaction is to abort the operation back to userspace.
+All five xfile usecases can be serviced by these four functions.

Quoted 8 lines
Quoted 4 lines
Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+However, no discussion of file access idioms is complete without

answering the
+question, "But what about mmap?"

I actually wouldn't spend too much time discussing solutions that didn't work for what ever reason, unless someones really asking for it. I think this section would read just fine to trim off the last paragraph here

Since I wrote this, I've been experimenting with wiring up the tmpfs file page cache folios to the xfs buffer cache. Pinning the folios in this manner makes it so that online fsck can (more or less) directly access the xfile contents. Much to my surprise, this has actually held up in testing, so ... it's no longer a solution that "didn't really work". :)

I also need to s/page/folio/ now that willy has finished that conversion. This section has been rewritten as such:

"However, no discussion of file access idioms is complete without answering the question, “But what about mmap?” It is convenient to access storage directly with pointers, just like userspace code does with regular memory. Online fsck must not drive the system into OOM conditions, which means that xfiles must be responsive to memory reclamation. tmpfs can only push a pagecache folio to the swap cache if the folio is neither pinned nor locked, which means the xfile must not pin too many folios.

"Short term direct access to xfile contents is done by locking the pagecache folio and mapping it into kernel address space. Programmatic access (e.g. pread and pwrite) uses this mechanism. Folio locks are not supposed to be held for long periods of time, so long term direct access to xfile contents is done by bumping the folio refcount, mapping it into kernel address space, and dropping the folio lock. These long term users must be responsive to memory reclaim by hooking into the shrinker infrastructure to know when to release folios.

"The xfile_get_page and xfile_put_page functions are provided to retrieve the (locked) folio that backs part of an xfile and to release it. The only code to use these folio lease functions are the xfarray sorting algorithms and the in-memory btrees."

Quoted 38 lines
Quoted 38 lines

+It would be *much* more convenient if kernel code could access pageable kernel
+memory with pointers, just like userspace code does with regular memory.
+Like any other filesystem that uses the page cache, reads and writes of xfile
+data lock the cache page and map it into the kernel address space for the

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+duration of the operation.
+Unfortunately, shmfs can only write a file page to the swap device

if the page
+is unmapped and unlocked, which means the xfile risks causing OOM problems

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+unless it is careful not to pin too many pages.
+Therefore, the xfile steers most of its users towards programmatic

access so
+that backing pages are not kept locked in memory for longer than is necessary.
+However, for callers performing quick linear scans of xfile data, +``xfile_get_page`` and ``xfile_put_page`` functions are provided to pin a page

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+in memory.
+So far, the only code to use these functions are the xfarray

:ref:`sorting
+<xfarray_sort>` algorithms.

Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+
+xfile Access Coordination
+`````````````````````````
+
+For security reasons, xfiles must be owned privately by the kernel.
+They are marked ``S_PRIVATE`` to prevent interference from the

security system,
+must never be mapped into process file descriptor tables, and their pages must

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+never be mapped into userspace processes.
+
+To avoid locking recursion issues with the VFS, all accesses to the

shmfs file

Quoted 8 lines

Documentation/filesystems/xfs-online-fsck-design.rst

Quoted 7 lines
Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+are performed by manipulating the page cache directly.
+xfile writes call the ``->write_begin`` and ``->write_end``

functions of the
+xfile's address space to grab writable pages, copy the caller's buffer into the

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+page, and release the pages.
+xfile reads call ``shmem_read_mapping_page_gfp`` to grab pages

xfile readers

OK.

Quoted 14 lines
Quoted 11 lines

directly before

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+copying the contents into the caller's buffer.
+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 and

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+freeze locks.
+
+If an xfile is shared between threads to stage repairs, the caller

must provide
+its own locks to coordinate access.

Ofsck threads that share an xfile between stage repairs will use their own locks to coordinate access with each other.

Quoted 1 line

?

Hm. I wonder if there's a misunderstanding here?

Online fsck functions themselves are single-threaded, which is to say that they themselves neither queue workers nor start kthreads. However, an xfile created by a running fsck function can be accessed from other thread if the fsck function also hooks itself into filesystem code.

The live update section has a nice diagram of how that works:
https://djwong.org/docs/xfs-online-fsck-design/#filesystem-hooks

Quoted 241 lines
Quoted 241 lines
Documentation/filesystems/xfs-online-fsck-design.rst +7 -0
+
+.. _xfarray:
+
+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

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+records indexed with a classic B+ tree.
+Directories have a set of fixed-size dirent records that point to

the names,
+and extended attributes have a set of fixed-size attribute keys that point to

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+names and values.
+Quota counters and file link counters index records with numbers.
+During a repair, scrub needs to stage new records during the

gathering step and

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+retrieve them during the btree building step.
+
+Although this requirement can be satisfied by calling the read and

write
+methods of the xfile directly, it is simpler for callers for there to be a
+higher level abstraction to take care of computing array offsets, to provide

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+iterator functions, and to deal with sparse records and sorting.
+The ``xfarray`` abstraction presents a linear array for fixed-size

records atop

Documentation/filesystems/xfs-online-fsck-design.rst +8 -0
+the byte-accessible xfile.
+
+.. _xfarray_access_patterns:
+
+Array Access Patterns
+^^^^^^^^^^^^^^^^^^^^^
+
+Array access patterns in online fsck tend to fall into three

categories.
+Iteration of records is assumed to be necessary for all cases and will be

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+covered in the next section.
+
+The first type of caller handles records that are indexed by

position.
+Gaps may exist between records, and a record may be updated multiple times

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+during the collection step.
+In other words, these callers want a sparse linearly addressed table

file.

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+The typical use case are quota records or file link count records.
+Access to array elements is performed programmatically via

``xfarray_load`` and
+``xfarray_store`` functions, which wrap the similarly-named xfile functions to
+provide loading and storing of array elements at arbitrary array indices.
+Gaps are defined to be null records, and null records are defined to be a

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+sequence of all zero bytes.
+Null records are detected by calling ``xfarray_element_is_null``.
+They are created either by calling ``xfarray_unset`` to null out an

existing

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+record or by never storing anything to an array index.
+
+The second type of caller handles records that are not indexed by

position

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+and do not require multiple updates to a record.
+The typical use case here is rebuilding space btrees and key/value

btrees.
+These callers can add records to the array without caring about array indices
+via the ``xfarray_append`` function, which stores a record at the end of the

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+array.
+For callers that require records to be presentable in a specific

order (e.g.
+rebuilding btree data), the ``xfarray_sort`` function can arrange the sorted

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+records; this function will be covered later.
+
+The third type of caller is a bag, which is useful for counting

records.
+The typical use case here is constructing space extent reference counts from

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+reverse mapping information.
+Records can be put in the bag in any order, they can be removed from

the bag

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+at any time, and uniqueness of records is left to callers.
+The ``xfarray_store_anywhere`` function is used to insert a record

in any
+null record slot in the bag; and the ``xfarray_unset`` function removes a

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+record from the bag.
+
+The proposed patchset is the
+`big in-memory array
+<

https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/
log/?h=big-array>`_.

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+
+Iterating Array Elements
+^^^^^^^^^^^^^^^^^^^^^^^^
+
+Most users of the xfarray require the ability to iterate the records

stored in

Documentation/filesystems/xfs-online-fsck-design.rst +13 -0
+the array.
+Callers can probe every possible array index with the following:
+
+.. code-block:: c
+
+       xfarray_idx_t i;
+       foreach_xfarray_idx(array, i) {
+           xfarray_load(array, i, &rec);
+
+           /* do something with rec */
+       }
+
+All users of this idiom must be prepared to handle null records or

must already

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+know that there aren't any.
+
+For xfarray users that want to iterate a sparse array, the

``xfarray_iter``
+function ignores indices in the xfarray that have never been written to by
+calling ``xfile_seek_data`` (which internally uses ``SEEK_DATA``) to skip areas

Documentation/filesystems/xfs-online-fsck-design.rst +16 -0
+of the array that are not populated with memory pages.
+Once it finds a page, it will skip the zeroed areas of the page.
+
+.. code-block:: c
+
+       xfarray_idx_t i = XFARRAY_CURSOR_INIT;
+       while ((ret = xfarray_iter(array, &i, &rec)) == 1) {
+           /* do something with rec */
+       }
+
+.. _xfarray_sort:
+
+Sorting Array Elements
+^^^^^^^^^^^^^^^^^^^^^^
+
+During the fourth demonstration of online repair, 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

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+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

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+set prior to bulk loading.
+
+The sorting algorithm used in the xfarray is actually a combination

of adaptive
+quicksort and a heapsort subalgorithm in the spirit of +Sedgewick <https://algs4.cs.princeton.edu/23quicksort/>_ and +pdqsort <https://github.com/orlp/pdqsort>_, with customizations for the Linux

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+kernel.
+To sort records in a reasonably short amount of time, ``xfarray``

takes
+advantage of the binary subpartitioning offered by quicksort, but it also uses
+heapsort to hedge aginst performance collapse if the chosen quicksort pivots

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+are poor.
+Both algorithms are (in general) O(n * lg(n)), but there is a wide

performance

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+gulf between the two implementations.
+
+The Linux kernel already contains a reasonably fast implementation

of heapsort.
+It only operates on regular C arrays, which limits the scope of its usefulness.

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+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.

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+In other words, ``xfarray`` uses heapsort to constrain the nested

recursion of

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+quicksort, thereby mitigating quicksort's worst runtime behavior.
+
+Choosing a quicksort pivot is a tricky business.
+A good pivot splits the set to sort in half, leading to the divide

and conquer

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+behavior that is crucial to  O(n * lg(n)) performance.
+A poor pivot barely splits the subset at all, leading to O(n\

:sup:2)

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+runtime.
+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

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+median of the nine.
+
+Most modern quicksort implementations employ Tukey's "ninther" to

select a

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+pivot from a classic C array.
+Typical ninther implementations pick three unique triads of records,

sort each
+of the triads, and then sort the middle value of each triad to determine the

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+ninther value.
+As stated previously, however, xfile accesses are not entirely

cheap.
+It turned out to be much more performant to read the nine elements into a
+memory buffer, run the kernel's in-memory heapsort on the buffer, and choose

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+the 4th element of that buffer as the pivot.
+Tukey's ninthers are described in J. W. Tukey, `The ninther, a

technique for
+low-effort robust (resistant) location in large samples`, in *Contributions to
+Survey Sampling and Applied Statistics*, edited by H. David, (Academic Press,
+1978), pp. 251–257.

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+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.

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+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

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+reduce map/unmap cycles.
+Surprisingly, this reduces overall sort runtime by nearly half again

after

Quoted 8 lines
Quoted 2 lines

+accounting for the application of heapsort directly onto xfile pages.

This sorting section is insightful, but I think I'd be ok with out it too. Or maybe save it for later in the document as an "implementation details" section, or something similar. It seems like there's still a lot to cover about how ofsck works in general before we start drilling into things like the runtime complexity of the sorting algorithm it uses.

How about I demote the details of how sorting works to a case study?

Quoted 252 lines
Quoted 252 lines
Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+
+Blob Storage
+````````````
+
+Extended attributes and directories add an additional requirement

for staging

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+records: arbitrary byte sequences of finite length.
+Each directory entry record needs to store entry name,
+and each extended attribute needs to store both the attribute name

and value.
+The names, keys, and values can consume a large amount of memory, so the
+``xfblob`` abstraction was created to simplify management of these blobs

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+atop an xfile.
+
+Blob arrays provide ``xfblob_load`` and ``xfblob_store`` functions

to retrieve

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+and persist objects.
+The store function returns a magic cookie for every object that it

persists.
+Later, callers provide this cookie to the ``xblob_load`` to recall the object.
+The ``xfblob_free`` function frees a specific blob, and the ``xfblob_truncate``

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+function frees them all because compaction is not needed.
+
+The details of repairing directories and extended attributes will be

discussed

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+in a subsequent section about atomic extent swapping.
+However, it should be noted that these repair functions only use

blob storage
+to cache a small number of entries before adding them to a temporary ondisk

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+file, which is why compaction is not required.
+
+The proposed patchset is at the start of the
+`extended attribute repair
+<

https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/
log/?h=repair-xattrs>`_ series.

Documentation/filesystems/xfs-online-fsck-design.rst +7 -0
+
+.. _xfbtree:
+
+In-Memory B+Trees
+`````````````````
+
+The chapter about :ref:`secondary metadata<secondary_metadata>`

mentioned that
+checking and repairing of secondary metadata commonly requires coordination
+between a live metadata scan of the filesystem and writer threads that are

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+updating that metadata.
+Keeping the scan data up to date requires requires the ability to

propagate
+metadata updates from the filesystem into the data being collected by the scan.
+This *can* be done by appending concurrent updates into a separate log file and
+applying them before writing the new metadata to disk, but this leads to

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+unbounded memory consumption if the rest of the system is very busy.
+Another option is to skip the side-log and commit live updates from

the
+filesystem directly into the scan data, which trades more overhead for a lower

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+maximum memory requirement.
+In both cases, the data structure holding the scan results must

support indexed

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+access to perform well.
+
+Given that indexed lookups of scan data is required for both

strategies, online
+fsck employs the second strategy of committing live updates directly into

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+scan data.
+Because xfarrays are not indexed and do not enforce record ordering,

they

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+are not suitable for this task.
+Conveniently, however, XFS has a library to create and maintain

ordered reverse

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+mapping records: the existing rmap btree code!
+If only there was a means to create one in memory.
+
+Recall that the :ref:`xfile <xfile>` abstraction represents memory

pages as a
+regular file, which means that the kernel can create byte or block addressable

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+virtual address spaces at will.
+The XFS buffer cache specializes in abstracting IO to block-

oriented  address
+spaces, which means that adaptation of the buffer cache to interface with

Documentation/filesystems/xfs-online-fsck-design.rst +7 -0
+xfiles enables reuse of the entire btree library.
+Btrees built atop an xfile are collectively known as ``xfbtrees``.
+The next few sections describe how they actually work.
+
+The proposed patchset is the
+`in-memory btree
+<

https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/
log/?h=in-memory-btrees>`_

Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+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

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+per-AG structure.
+The second change is to modify the buffer ``ioapply`` function to

"read" cached

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+pages from the xfile and "write" cached pages back to the xfile.
+Multiple access to individual buffers is controlled by the

``xfs_buf`` lock,

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+since the xfile does not provide any locking on its own.
+With this adaptation in place, users of the xfile-backed buffer

cache use

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+exactly the same APIs as users of the disk-backed buffer cache.
+The separation between xfile and buffer cache implies higher memory

usage since
+they do not share pages, but this property could some day enable transactional

Documentation/filesystems/xfs-online-fsck-design.rst +7 -0
+updates to an in-memory btree.
+Today, however, it simply eliminates the need for new code.
+
+Space Management with an xfbtree
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Space management for an xfile is very simple -- each btree block is

one memory

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+page in size.
+These blocks use the same header format as an on-disk btree, but the

in-memory
+block verifiers ignore the checksums, assuming that xfile memory is no more

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+corruption-prone than regular DRAM.
+Reusing existing code here is more important than absolute memory

efficiency.

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+The very first block of an xfile backing an xfbtree contains a

header block.
+The header describes the owner, height, and the block number of the root

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+xfbtree block.
+
+To allocate a btree block, use ``xfile_seek_data`` to find a gap in

the file.
+If there are no gaps, create one by extending the length of the xfile.
+Preallocate space for the block with ``xfile_prealloc``, and hand back the

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+location.
+To free an xfbtree block, use ``xfile_discard`` (which internally

uses
+``FALLOC_FL_PUNCH_HOLE``) to remove the memory page from the xfile.

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+
+Populating an xfbtree
+^^^^^^^^^^^^^^^^^^^^^
+
+An online fsck function that wants to create an xfbtree should

proceed as

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+follows:
+
+1. Call ``xfile_create`` to create an xfile.
+
+2. Call ``xfs_alloc_memory_buftarg`` to create a buffer cache target

structure
+   pointing to the xfile.
+
+3. Pass the buffer cache target, buffer ops, and other information to
+   ``xfbtree_create`` to write an initial tree header and root block to the
+   xfile.
+   Each btree type should define a wrapper that passes necessary arguments to
+   the creation function.
+   For example, rmap btrees define ``xfs_rmapbt_mem_create`` to take care of
+   all the necessary details for callers.
+   A ``struct xfbtree`` object will be returned.
+
+4. Pass the xfbtree object to the btree cursor creation function for the
+   btree type.
+   Following the example above, ``xfs_rmapbt_mem_cursor`` takes care of this
+   for callers.
+
+5. Pass the btree cursor to the regular btree functions to make queries against
+   and to update the in-memory btree.
+   For example, a btree cursor for an rmap xfbtree can be passed to the
+   ``xfs_rmap_*`` functions just like any other btree cursor. +   See the :ref:next section<xfbtree_commit> for information on dealing with
+   xfbtree updates that are logged to a transaction.
+
+6. When finished, delete the btree cursor, destroy the xfbtree object, free the
+   buffer target, and the destroy the xfile to release all resources.

Documentation/filesystems/xfs-online-fsck-design.rst +7 -0
+
+.. _xfbtree_commit:
+
+Committing Logged xfbtree Buffers
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Although it is a clever hack to reuse the rmap btree code to handle

the staging
+structure, the ephemeral nature of the in-memory btree block storage presents

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+some challenges of its own.
+The XFS transaction manager must not commit buffer log items for

buffers backed
+by an xfile because the log format does not understand updates for devices

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+other than the data device.
+An ephemeral xfbtree probably will not exist by the time the AIL

checkpoints
+log transactions back into the filesystem, and certainly won't exist during

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+log recovery.
+For these reasons, any code updating an xfbtree in transaction

context must
+remove the buffer log items from the transaction and write the updates into the

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+backing xfile before committing or cancelling the transaction.
+
+The ``xfbtree_trans_commit`` and ``xfbtree_trans_cancel`` functions

implement

Documentation/filesystems/xfs-online-fsck-design.rst +11 -0
+this functionality as follows:
+
+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
+   that were detached in step 3.
+

Quoted 8 lines
Quoted 7 lines

+6. Submit the delwri list to commit the changes to the xfile, if the updates
+   are being committed.

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+After removing xfile logged buffers from the transaction in this

manner, the
+transaction can be committed or cancelled.

Rest of this looks pretty good, organizing nits aside.

Cool, thank you!!

--D

Quoted 3 lines

Allison

Quoted 1 line
#35 lore raw

Re: [PATCH 07/14] xfs: document pageable kernel memory

Quoted 170 lines · Darrick J. Wong
Quoted 108 lines · Allison Henderson
Quoted 97 lines · Darrick J. Wong

From: Darrick J. Wong <[email protected]>

Add a discussion of pageable kernel memory, since online fsck needs
quite a bit more memory than most other parts of the filesystem to
stage
records and other information.

---
 .../filesystems/xfs-online-fsck-design.rst         |  490
++++++++++++++++++++

 1 file changed, 490 insertions(+)
Documentation/filesystems/xfs-online-fsck-design.rst +0 -0
index 419eb54ee200..9d7a2ef1d0dd 100644
@@ -383,6 +383,8 @@ 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:
+
 Secondary Metadata
 ``````````````````

Documentation/filesystems/xfs-online-fsck-design.rst +0 -0
@@ -1746,3 +1748,491 @@ Scrub teardown disables all static keys

obtained by ``xchk_fshooks_enable``.

 For more information, please see the kernel documentation of Documentation/staging/static-keys.rst.

Documentation/filesystems/xfs-online-fsck-design.rst +7 -0
+
+.. _xfile:
+
+Pageable Kernel Memory
+----------------------
+
+Demonstrations of the first few prototypes of online repair

revealed
new

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+technical requirements that were not originally identified.
+For the first demonstration, the code walked whatever filesystem
+metadata it needed to synthesize new records and inserted

records
into a new

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+btree as it found them.
+This was subpar since any additional corruption or runtime

errors
encountered

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+during the walk would shut down the filesystem.
+After remount, the blocks containing the half-rebuilt data

structure
would not

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+be accessible until another repair was attempted.
+Solving the problem of half-rebuilt data structures will be

discussed in the

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+next section.
+
+For the second demonstration, the synthesized records were

instead
stored in

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+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.

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+However, even this approach needed improving upon.
+
+There are four reasons why traditional Linux kernel memory

management isn't

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+suitable for storing large datasets:
+
+1. 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. +
+2. While 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.
+
+3. To overcome these two difficulties, the implementation was adjusted to use
+   doubly linked lists, which means every record object needed

Quoted 8 lines

two
64-bit list
+   head pointers, which is a lot of overhead.
+
+4. Kernel memory is pinned, which can drive the system out of memory, leading
+   to OOM kills of unrelated processes.
+

I think I maybe might just jump to what ever the current plan is instead of trying to keep a record of the dev history in the

Quoted 8 lines

document.
I'm sure we're not done yet, dev really never is, so in order for the
documentation to be maintained, it would just get bigger and bigger to
keep documenting it this way.  It's not that the above isnt valuable,
but maybe a different kind of document really.

OK, I've shortened this introduction to outline the requirements, and trimmed the historical information to a sidebar:

"Some online checking functions work by scanning the filesystem to build
a shadow copy of an ondisk metadata structure in memory and comparing the two copies. For online repair to rebuild a metadata structure, it must compute the record set that will be stored in the new structure before it can persist that new structure to disk. Ideally, repairs complete with a single atomic commit that introduces a new data structure. To meet these goals, the kernel needs to collect a large amount of information in a place that doesn’t require the correct operation of the filesystem.

"Kernel memory isn’t suitable because:

*   Allocating a contiguous region of memory to create a C array is very
    difficult, especially on 32-bit systems.

*   Linked lists of records introduce double pointer overhead which is
    very high and eliminate the possibility of indexed lookups.

*   Kernel memory is pinned, which can drive the system into OOM conditions.

*   The system might not have sufficient memory to stage all the information.

"At any given time, online fsck does not need to keep the entire record
set in memory, which means that individual records can be paged out if
necessary. Continued development of online fsck demonstrated that the ability to perform indexed data storage would also be very useful. Fortunately, the Linux kernel already has a facility for byte-addressable and pageable storage: tmpfs. In-kernel graphics drivers
(most notably i915) take advantage of tmpfs files to store intermediate
data that doesn’t need to be in memory at all times, so that usage precedent is already established. Hence, the xfile was born!

Historical Sidebar
------------------

"The first edition of online repair inserted records into a new btree as
it found them, which failed because filesystem could shut down with a built data structure, which would be live after recovery finished.

Quoted 7 lines

"The second edition solved the half-rebuilt structure problem by storing
everything in memory, but frequently ran the system out of memory.

"The third edition solved the OOM problem by using linked lists, but the
list overhead was extreme."

Ok, I think that's cleaner

Quoted 145 lines
Quoted 99 lines
Quoted 6 lines

+For the third iteration, attention swung back to the possibility of
using

Due to the large volume of metadata that needs to be processed, ofsck
uses...

Quoted 88 lines

+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

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+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 rejected for some types of repairs because a filesystem with
+compromised space and inode metadata should never be used to fix compromised

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+space or inode metadata.
+However, the kernel already has a facility for byte-addressable

and
pageable

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+storage: shmfs.
+In-kernel graphics drivers (most notably i915) take advantage of

shmfs files
+to store intermediate data that doesn't need to be in memory at all
times, so

Documentation/filesystems/xfs-online-fsck-design.rst +7 -0
+that usage precedent is already established.
+Hence, the ``xfile`` was born!
+
+xfile Access Models
+```````````````````
+
+A survey of the intended uses of xfiles suggested these use

cases:
+
+1. Arrays of fixed-sized records (space management btrees, directory
and
+   extended attribute entries)

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+
+2. Sparse arrays of fixed-sized records (quotas and link counts)
+
+3. Large binary objects (BLOBs) of variable sizes (directory and

extended
+   attribute names and values)

Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+
+4. Staging btrees in memory (reverse mapping btrees)
+
+5. Arbitrary contents (realtime space management)
+
+To support the first four use cases, high level data structures

wrap
the xfile

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+to share functionality between online fsck functions.
+The rest of this section discusses the interfaces that the xfile

presents to

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+four of those five higher level data structures.
+The fifth use case is discussed in the :ref:`realtime summary

<rtsummary>` case

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+study.
+
+The most general storage interface supported by the xfile

enables
the reading
+and writing of arbitrary quantities of data at arbitrary offsets in
the xfile.
+This capability is provided by ``xfile_pread`` and ``xfile_pwrite``
functions,

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+which behave similarly to their userspace counterparts.
+XFS is very record-based, which suggests that the ability to

load
and store

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+complete records is important.
+To support these cases, a pair of ``xfile_obj_load`` and

``xfile_obj_store``
+functions are provided to read and persist objects into an xfile.
+They are internally the same as pread and pwrite, except that they
treat any

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+error as an out of memory error.
+For online repair, squashing error conditions in this manner is

an
acceptable
+behavior because the only reaction is to abort the operation back to
userspace.

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+All five xfile usecases can be serviced by these four functions.
+
Quoted 8 lines
Quoted 3 lines

+However, no discussion of file access idioms is complete without answering the
+question, "But what about mmap?"

I actually wouldn't spend too much time discussing solutions that didn't work for what ever reason, unless someones really asking for it.
 I think this section would read just fine to trim off the last paragraph here

Since I wrote this, I've been experimenting with wiring up the tmpfs file page cache folios to the xfs buffer cache.  Pinning the folios in
this manner makes it so that online fsck can (more or less) directly access the xfile contents.  Much to my surprise, this has actually held
up in testing, so ... it's no longer a solution that "didn't really work". :)

I also need to s/page/folio/ now that willy has finished that conversion.  This section has been rewritten as such:

"However, no discussion of file access idioms is complete without answering the question, “But what about mmap?” It is convenient to access storage directly with pointers, just like userspace code does with regular memory. Online fsck must not drive the system into OOM conditions, which means that xfiles must be responsive to memory reclamation. tmpfs can only push a pagecache folio to the swap cache if
the folio is neither pinned nor locked, which means the xfile must not
pin too many folios.

"Short term direct access to xfile contents is done by locking the pagecache folio and mapping it into kernel address space. Programmatic
access (e.g. pread and pwrite) uses this mechanism. Folio locks are not
supposed to be held for long periods of time, so long term direct access
to xfile contents is done by bumping the folio refcount, mapping it into
kernel address space, and dropping the folio lock. These long term users
must be responsive to memory reclaim by hooking into the shrinker infrastructure to know when to release folios.

Quoted 5 lines

"The xfile_get_page and xfile_put_page functions are provided to retrieve the (locked) folio that backs part of an xfile and to release
it. The only code to use these folio lease functions are the xfarray sorting algorithms and the in-memory btrees."

Alrighty, sounds like a good upate then

Quoted 90 lines
Quoted 50 lines
Quoted 50 lines

+It would be *much* more convenient if kernel code could access pageable kernel
+memory with pointers, just like userspace code does with regular memory.
+Like any other filesystem that uses the page cache, reads and writes
of xfile
+data lock the cache page and map it into the kernel address space
for the

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+duration of the operation.
+Unfortunately, shmfs can only write a file page to the swap

device
if the page
+is unmapped and unlocked, which means the xfile risks causing OOM
problems

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+unless it is careful not to pin too many pages.
+Therefore, the xfile steers most of its users towards

programmatic
access so
+that backing pages are not kept locked in memory for longer than is
necessary.
+However, for callers performing quick linear scans of xfile data,
+``xfile_get_page`` and ``xfile_put_page`` functions are provided to
pin a page

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+in memory.
+So far, the only code to use these functions are the xfarray

:ref:`sorting
+<xfarray_sort>` algorithms.

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+
+xfile Access Coordination
+`````````````````````````
+
+For security reasons, xfiles must be owned privately by the

kernel.
+They are marked ``S_PRIVATE`` to prevent interference from the security system,
+must never be mapped into process file descriptor tables, and their
pages must

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+never be mapped into userspace processes.
+
+To avoid locking recursion issues with the VFS, all accesses to

the
shmfs file

Quoted 8 lines

Documentation/filesystems/xfs-online-fsck-design.rst

Quoted 7 lines
Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+are performed by manipulating the page cache directly.
+xfile writes call the ``->write_begin`` and ``->write_end``

functions of the
+xfile's address space to grab writable pages, copy the caller's buffer into the

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+page, and release the pages.
+xfile reads call ``shmem_read_mapping_page_gfp`` to grab pages

xfile readers

OK.

Quoted 18 lines
Quoted 11 lines

directly before

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+copying the contents into the caller's buffer.
+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
and

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+freeze locks.
+
+If an xfile is shared between threads to stage repairs, the
Quoted 3 lines

caller
must provide
+its own locks to coordinate access.

Ofsck threads that share an xfile between stage repairs will use their
own locks to coordinate access with each other.

Quoted 1 line

?

Hm.  I wonder if there's a misunderstanding here?

Online fsck functions themselves are single-threaded, which is to say that they themselves neither queue workers nor start kthreads. However,
an xfile created by a running fsck function can be accessed from other
thread if the fsck function also hooks itself into filesystem code.

Quoted 3 lines

The live update section has a nice diagram of how that works:
https://djwong.org/docs/xfs-online-fsck-design/#filesystem-hooks

Oh ok, I think I got hung up on who the callers were. How about "xfiles shared between threads running from hooked filesystem functions will use their own locks to coordinate access with each other."

Quoted 299 lines
Quoted 290 lines
Quoted 284 lines
Documentation/filesystems/xfs-online-fsck-design.rst +7 -0
+
+.. _xfarray:
+
+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

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+records indexed with a classic B+ tree.
+Directories have a set of fixed-size dirent records that point

to
the names,
+and extended attributes have a set of fixed-size attribute keys that
point to

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+names and values.
+Quota counters and file link counters index records with

numbers.
+During a repair, scrub needs to stage new records during the gathering step and

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+retrieve them during the btree building step.
+
+Although this requirement can be satisfied by calling the read

and
write
+methods of the xfile directly, it is simpler for callers for there
to be a
+higher level abstraction to take care of computing array offsets, to
provide

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+iterator functions, and to deal with sparse records and sorting.
+The ``xfarray`` abstraction presents a linear array for fixed-

size
records atop

Documentation/filesystems/xfs-online-fsck-design.rst +8 -0
+the byte-accessible xfile.
+
+.. _xfarray_access_patterns:
+
+Array Access Patterns
+^^^^^^^^^^^^^^^^^^^^^
+
+Array access patterns in online fsck tend to fall into three

categories.
+Iteration of records is assumed to be necessary for all cases and
will be

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+covered in the next section.
+
+The first type of caller handles records that are indexed by

position.
+Gaps may exist between records, and a record may be updated multiple
times

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+during the collection step.
+In other words, these callers want a sparse linearly addressed

table
file.
+The typical use case are quota records or file link count records.
+Access to array elements is performed programmatically via ``xfarray_load`` and
+``xfarray_store`` functions, which wrap the similarly-named xfile
functions to
+provide loading and storing of array elements at arbitrary array indices.
+Gaps are defined to be null records, and null records are defined to
be a

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+sequence of all zero bytes.
+Null records are detected by calling

``xfarray_element_is_null``.
+They are created either by calling ``xfarray_unset`` to null out an
existing

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+record or by never storing anything to an array index.
+
+The second type of caller handles records that are not indexed

by
position

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+and do not require multiple updates to a record.
+The typical use case here is rebuilding space btrees and

key/value
btrees.
+These callers can add records to the array without caring about array indices
+via the ``xfarray_append`` function, which stores a record at the
end of the

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+array.
+For callers that require records to be presentable in a specific

order (e.g.
+rebuilding btree data), the ``xfarray_sort`` function can arrange
the sorted

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+records; this function will be covered later.
+
+The third type of caller is a bag, which is useful for counting

records.
+The typical use case here is constructing space extent reference counts from

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+reverse mapping information.
+Records can be put in the bag in any order, they can be removed

from
the bag

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+at any time, and uniqueness of records is left to callers.
+The ``xfarray_store_anywhere`` function is used to insert a

record
in any
+null record slot in the bag; and the ``xfarray_unset`` function removes a

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+record from the bag.
+
+The proposed patchset is the
+`big in-memory array
+<

https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/
log/?h=big-array>`_.

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+
+Iterating Array Elements
+^^^^^^^^^^^^^^^^^^^^^^^^
+
+Most users of the xfarray require the ability to iterate the

records
stored in

Documentation/filesystems/xfs-online-fsck-design.rst +13 -0
+the array.
+Callers can probe every possible array index with the following:
+
+.. code-block:: c
+
+       xfarray_idx_t i;
+       foreach_xfarray_idx(array, i) {
+           xfarray_load(array, i, &rec);
+
+           /* do something with rec */
+       }
+
+All users of this idiom must be prepared to handle null records

or
must already

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+know that there aren't any.
+
+For xfarray users that want to iterate a sparse array, the

``xfarray_iter``
+function ignores indices in the xfarray that have never been written
to by
+calling ``xfile_seek_data`` (which internally uses ``SEEK_DATA``) to
skip areas

Documentation/filesystems/xfs-online-fsck-design.rst +16 -0
+of the array that are not populated with memory pages.
+Once it finds a page, it will skip the zeroed areas of the page.
+
+.. code-block:: c
+
+       xfarray_idx_t i = XFARRAY_CURSOR_INIT;
+       while ((ret = xfarray_iter(array, &i, &rec)) == 1) {
+           /* do something with rec */
+       }
+
+.. _xfarray_sort:
+
+Sorting Array Elements
+^^^^^^^^^^^^^^^^^^^^^^
+
+During the fourth demonstration of online repair, 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

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+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

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+set prior to bulk loading.
+
+The sorting algorithm used in the xfarray is actually a

combination
of adaptive
+quicksort and a heapsort subalgorithm in the spirit of +Sedgewick <https://algs4.cs.princeton.edu/23quicksort/>_ and +pdqsort <https://github.com/orlp/pdqsort>_, with customizations
for the Linux

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+kernel.
+To sort records in a reasonably short amount of time,

``xfarray``
takes
+advantage of the binary subpartitioning offered by quicksort, but it
also uses
+heapsort to hedge aginst performance collapse if the chosen quicksort pivots

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+are poor.
+Both algorithms are (in general) O(n * lg(n)), but there is a

wide
performance

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+gulf between the two implementations.
+
+The Linux kernel already contains a reasonably fast

implementation
of heapsort.
+It only operates on regular C arrays, which limits the scope of its
usefulness.

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+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.

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+In other words, ``xfarray`` uses heapsort to constrain the

nested
recursion of
+quicksort, thereby mitigating quicksort's worst runtime behavior.

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+
+Choosing a quicksort pivot is a tricky business.
+A good pivot splits the set to sort in half, leading to the

divide
and conquer

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+behavior that is crucial to  O(n * lg(n)) performance.
+A poor pivot barely splits the subset at all, leading to O(n\

:sup:2)

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+runtime.
+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

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+median of the nine.
+
+Most modern quicksort implementations employ Tukey's "ninther"

to
select a

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+pivot from a classic C array.
+Typical ninther implementations pick three unique triads of

records,
sort each
+of the triads, and then sort the middle value of each triad to determine the

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+ninther value.
+As stated previously, however, xfile accesses are not entirely

cheap.
+It turned out to be much more performant to read the nine elements
into a
+memory buffer, run the kernel's in-memory heapsort on the buffer,
and choose

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+the 4th element of that buffer as the pivot.
+Tukey's ninthers are described in J. W. Tukey, `The ninther, a

technique for
+low-effort robust (resistant) location in large samples`, in *Contributions to
+Survey Sampling and Applied Statistics*, edited by H. David, (Academic Press,
+1978), pp. 251–257.

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+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.

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+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

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+reduce map/unmap cycles.
+Surprisingly, this reduces overall sort runtime by nearly half
Quoted 4 lines

again
after
+accounting for the application of heapsort directly onto xfile pages.

This sorting section is insightful, but I think I'd be ok with out it

Quoted 8 lines

too.  Or maybe save it for later in the document as an "implementation
details" section, or something similar.  It seems like there's still a
lot to cover about how ofsck works in general before we start drilling
into things like the runtime complexity of the sorting algorithm it uses.

Quoted 1 line

How about I demote the details of how sorting works to a case study?

Sure, sounds good

Quoted 319 lines
Quoted 303 lines
Quoted 303 lines
Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+
+Blob Storage
+````````````
+
+Extended attributes and directories add an additional

requirement
for staging

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+records: arbitrary byte sequences of finite length.
+Each directory entry record needs to store entry name,
+and each extended attribute needs to store both the attribute

name
and value.
+The names, keys, and values can consume a large amount of memory, so
the
+``xfblob`` abstraction was created to simplify management of these
blobs

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+atop an xfile.
+
+Blob arrays provide ``xfblob_load`` and ``xfblob_store``

functions
to retrieve

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+and persist objects.
+The store function returns a magic cookie for every object that

it
persists.
+Later, callers provide this cookie to the ``xblob_load`` to recall
the object.
+The ``xfblob_free`` function frees a specific blob, and the ``xfblob_truncate``

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+function frees them all because compaction is not needed.
+
+The details of repairing directories and extended attributes

will be
discussed

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+in a subsequent section about atomic extent swapping.
+However, it should be noted that these repair functions only use

blob storage
+to cache a small number of entries before adding them to a temporary
ondisk

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+file, which is why compaction is not required.
+
+The proposed patchset is at the start of the
+`extended attribute repair
+<

https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/
log/?h=repair-xattrs>`_ series.

Documentation/filesystems/xfs-online-fsck-design.rst +7 -0
+
+.. _xfbtree:
+
+In-Memory B+Trees
+`````````````````
+
+The chapter about :ref:`secondary metadata<secondary_metadata>`

mentioned that
+checking and repairing of secondary metadata commonly requires coordination
+between a live metadata scan of the filesystem and writer threads
that are

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+updating that metadata.
+Keeping the scan data up to date requires requires the ability

to
propagate
+metadata updates from the filesystem into the data being collected
by the scan.
+This *can* be done by appending concurrent updates into a separate
log file and
+applying them before writing the new metadata to disk, but this leads to
+unbounded memory consumption if the rest of the system is very busy.
+Another option is to skip the side-log and commit live updates from
the
+filesystem directly into the scan data, which trades more overhead
for a lower

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+maximum memory requirement.
+In both cases, the data structure holding the scan results must

support indexed

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+access to perform well.
+
+Given that indexed lookups of scan data is required for both

strategies, online
+fsck employs the second strategy of committing live updates directly
into

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+scan data.
+Because xfarrays are not indexed and do not enforce record

ordering,
they

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+are not suitable for this task.
+Conveniently, however, XFS has a library to create and maintain

ordered reverse

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+mapping records: the existing rmap btree code!
+If only there was a means to create one in memory.
+
+Recall that the :ref:`xfile <xfile>` abstraction represents

memory
pages as a
+regular file, which means that the kernel can create byte or block
addressable

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+virtual address spaces at will.
+The XFS buffer cache specializes in abstracting IO to block-

oriented  address
+spaces, which means that adaptation of the buffer cache to interface
with

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+xfiles enables reuse of the entire btree library.
+Btrees built atop an xfile are collectively known as

``xfbtrees``.

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+The next few sections describe how they actually work.
+
+The proposed patchset is the
+`in-memory btree
+<

https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/
log/?h=in-memory-btrees>`_

Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+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

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+per-AG structure.
+The second change is to modify the buffer ``ioapply`` function

to
"read" cached

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+pages from the xfile and "write" cached pages back to the xfile.
+Multiple access to individual buffers is controlled by the

``xfs_buf`` lock,

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+since the xfile does not provide any locking on its own.
+With this adaptation in place, users of the xfile-backed buffer

cache use

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+exactly the same APIs as users of the disk-backed buffer cache.
+The separation between xfile and buffer cache implies higher

memory
usage since
+they do not share pages, but this property could some day enable transactional

Documentation/filesystems/xfs-online-fsck-design.rst +7 -0
+updates to an in-memory btree.
+Today, however, it simply eliminates the need for new code.
+
+Space Management with an xfbtree
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Space management for an xfile is very simple -- each btree block

is
one memory

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+page in size.
+These blocks use the same header format as an on-disk btree, but

the
in-memory
+block verifiers ignore the checksums, assuming that xfile memory is
no more

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+corruption-prone than regular DRAM.
+Reusing existing code here is more important than absolute

memory
efficiency.

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+The very first block of an xfile backing an xfbtree contains a

header block.
+The header describes the owner, height, and the block number of the
root

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+xfbtree block.
+
+To allocate a btree block, use ``xfile_seek_data`` to find a gap

in
the file.
+If there are no gaps, create one by extending the length of the xfile.
+Preallocate space for the block with ``xfile_prealloc``, and hand
back the

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+location.
+To free an xfbtree block, use ``xfile_discard`` (which

internally
uses
+``FALLOC_FL_PUNCH_HOLE``) to remove the memory page from the xfile.

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+
+Populating an xfbtree
+^^^^^^^^^^^^^^^^^^^^^
+
+An online fsck function that wants to create an xfbtree should

proceed as

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+follows:
+
+1. Call ``xfile_create`` to create an xfile.
+
+2. Call ``xfs_alloc_memory_buftarg`` to create a buffer cache

target
structure
+   pointing to the xfile.
+
+3. Pass the buffer cache target, buffer ops, and other information
to
+   ``xfbtree_create`` to write an initial tree header and root block
to the
+   xfile.
+   Each btree type should define a wrapper that passes necessary arguments to
+   the creation function.
+   For example, rmap btrees define ``xfs_rmapbt_mem_create`` to take
care of
+   all the necessary details for callers.
+   A ``struct xfbtree`` object will be returned.
+
+4. Pass the xfbtree object to the btree cursor creation function for
the
+   btree type.
+   Following the example above, ``xfs_rmapbt_mem_cursor`` takes care
of this
+   for callers.
+
+5. Pass the btree cursor to the regular btree functions to make queries against
+   and to update the in-memory btree.
+   For example, a btree cursor for an rmap xfbtree can be passed to
the
+   ``xfs_rmap_*`` functions just like any other btree cursor. +   See the :ref:next section<xfbtree_commit> for information on
dealing with
+   xfbtree updates that are logged to a transaction.
+
+6. When finished, delete the btree cursor, destroy the xfbtree object, free the
+   buffer target, and the destroy the xfile to release all resources.

Documentation/filesystems/xfs-online-fsck-design.rst +7 -0
+
+.. _xfbtree_commit:
+
+Committing Logged xfbtree Buffers
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Although it is a clever hack to reuse the rmap btree code to

handle
the staging
+structure, the ephemeral nature of the in-memory btree block storage
presents

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+some challenges of its own.
+The XFS transaction manager must not commit buffer log items for

buffers backed
+by an xfile because the log format does not understand updates for
devices

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+other than the data device.
+An ephemeral xfbtree probably will not exist by the time the AIL

checkpoints
+log transactions back into the filesystem, and certainly won't exist
during

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+log recovery.
+For these reasons, any code updating an xfbtree in transaction

context must
+remove the buffer log items from the transaction and write the updates into the

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+backing xfile before committing or cancelling the transaction.
+
+The ``xfbtree_trans_commit`` and ``xfbtree_trans_cancel``

functions
implement

Documentation/filesystems/xfs-online-fsck-design.rst +11 -0
+this functionality as follows:
+
+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
+   that were detached in step 3.
+
+6. Submit the delwri list to commit the changes to the xfile, if

Quoted 8 lines
Quoted 7 lines

the
updates
+   are being committed.

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+After removing xfile logged buffers from the transaction in this

manner, the
+transaction can be committed or cancelled.

Rest of this looks pretty good, organizing nits aside.

Cool, thank you!!

--D

Quoted 3 lines

Allison

Quoted 1 line
#36 lore raw

Re: [PATCH 07/14] xfs: document pageable kernel memory

Quoted 422 lines · Allison Henderson
Quoted 170 lines · Darrick J. Wong
Quoted 108 lines · Allison Henderson
Quoted 97 lines · Darrick J. Wong

From: Darrick J. Wong <[email protected]>

Add a discussion of pageable kernel memory, since online fsck needs
quite a bit more memory than most other parts of the filesystem to
stage
records and other information.

---
 .../filesystems/xfs-online-fsck-design.rst         |  490
++++++++++++++++++++

 1 file changed, 490 insertions(+)
Documentation/filesystems/xfs-online-fsck-design.rst +0 -0
index 419eb54ee200..9d7a2ef1d0dd 100644
@@ -383,6 +383,8 @@ 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:
+
 Secondary Metadata
 ``````````````````

Documentation/filesystems/xfs-online-fsck-design.rst +0 -0
@@ -1746,3 +1748,491 @@ Scrub teardown disables all static keys

obtained by ``xchk_fshooks_enable``.

 For more information, please see the kernel documentation of Documentation/staging/static-keys.rst.

Documentation/filesystems/xfs-online-fsck-design.rst +7 -0
+
+.. _xfile:
+
+Pageable Kernel Memory
+----------------------
+
+Demonstrations of the first few prototypes of online repair

revealed
new

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+technical requirements that were not originally identified.
+For the first demonstration, the code walked whatever filesystem
+metadata it needed to synthesize new records and inserted

records
into a new

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+btree as it found them.
+This was subpar since any additional corruption or runtime

errors
encountered

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+during the walk would shut down the filesystem.
+After remount, the blocks containing the half-rebuilt data

structure
would not

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+be accessible until another repair was attempted.
+Solving the problem of half-rebuilt data structures will be

discussed in the

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+next section.
+
+For the second demonstration, the synthesized records were

instead
stored in

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+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.

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+However, even this approach needed improving upon.
+
+There are four reasons why traditional Linux kernel memory

management isn't

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+suitable for storing large datasets:
+
+1. 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. +
+2. While 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.
+
+3. To overcome these two difficulties, the implementation was adjusted to use
+   doubly linked lists, which means every record object needed

Quoted 8 lines

two
64-bit list
+   head pointers, which is a lot of overhead.
+
+4. Kernel memory is pinned, which can drive the system out of memory, leading
+   to OOM kills of unrelated processes.
+

I think I maybe might just jump to what ever the current plan is instead of trying to keep a record of the dev history in the

Quoted 8 lines

document.
I'm sure we're not done yet, dev really never is, so in order for the
documentation to be maintained, it would just get bigger and bigger to
keep documenting it this way.  It's not that the above isnt valuable,
but maybe a different kind of document really.

OK, I've shortened this introduction to outline the requirements, and trimmed the historical information to a sidebar:

"Some online checking functions work by scanning the filesystem to build
a shadow copy of an ondisk metadata structure in memory and comparing the two copies. For online repair to rebuild a metadata structure, it must compute the record set that will be stored in the new structure before it can persist that new structure to disk. Ideally, repairs complete with a single atomic commit that introduces a new data structure. To meet these goals, the kernel needs to collect a large amount of information in a place that doesn’t require the correct operation of the filesystem.

"Kernel memory isn’t suitable because:

*   Allocating a contiguous region of memory to create a C array is very
    difficult, especially on 32-bit systems.

*   Linked lists of records introduce double pointer overhead which is
    very high and eliminate the possibility of indexed lookups.

*   Kernel memory is pinned, which can drive the system into OOM conditions.

*   The system might not have sufficient memory to stage all the information.

"At any given time, online fsck does not need to keep the entire record
set in memory, which means that individual records can be paged out if
necessary. Continued development of online fsck demonstrated that the ability to perform indexed data storage would also be very useful. Fortunately, the Linux kernel already has a facility for byte-addressable and pageable storage: tmpfs. In-kernel graphics drivers
(most notably i915) take advantage of tmpfs files to store intermediate
data that doesn’t need to be in memory at all times, so that usage precedent is already established. Hence, the xfile was born!

Historical Sidebar
------------------

"The first edition of online repair inserted records into a new btree as
it found them, which failed because filesystem could shut down with a built data structure, which would be live after recovery finished.

Quoted 7 lines

"The second edition solved the half-rebuilt structure problem by storing
everything in memory, but frequently ran the system out of memory.

"The third edition solved the OOM problem by using linked lists, but the
list overhead was extreme."

Ok, I think that's cleaner

Quoted 145 lines
Quoted 99 lines
Quoted 6 lines

+For the third iteration, attention swung back to the possibility of
using

Due to the large volume of metadata that needs to be processed, ofsck
uses...

Quoted 88 lines

+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

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+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 rejected for some types of repairs because a filesystem with
+compromised space and inode metadata should never be used to fix compromised

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+space or inode metadata.
+However, the kernel already has a facility for byte-addressable

and
pageable

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+storage: shmfs.
+In-kernel graphics drivers (most notably i915) take advantage of

shmfs files
+to store intermediate data that doesn't need to be in memory at all
times, so

Documentation/filesystems/xfs-online-fsck-design.rst +7 -0
+that usage precedent is already established.
+Hence, the ``xfile`` was born!
+
+xfile Access Models
+```````````````````
+
+A survey of the intended uses of xfiles suggested these use

cases:
+
+1. Arrays of fixed-sized records (space management btrees, directory
and
+   extended attribute entries)

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+
+2. Sparse arrays of fixed-sized records (quotas and link counts)
+
+3. Large binary objects (BLOBs) of variable sizes (directory and

extended
+   attribute names and values)

Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+
+4. Staging btrees in memory (reverse mapping btrees)
+
+5. Arbitrary contents (realtime space management)
+
+To support the first four use cases, high level data structures

wrap
the xfile

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+to share functionality between online fsck functions.
+The rest of this section discusses the interfaces that the xfile

presents to

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+four of those five higher level data structures.
+The fifth use case is discussed in the :ref:`realtime summary

<rtsummary>` case

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+study.
+
+The most general storage interface supported by the xfile

enables
the reading
+and writing of arbitrary quantities of data at arbitrary offsets in
the xfile.
+This capability is provided by ``xfile_pread`` and ``xfile_pwrite``
functions,

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+which behave similarly to their userspace counterparts.
+XFS is very record-based, which suggests that the ability to

load
and store

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+complete records is important.
+To support these cases, a pair of ``xfile_obj_load`` and

``xfile_obj_store``
+functions are provided to read and persist objects into an xfile.
+They are internally the same as pread and pwrite, except that they
treat any

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+error as an out of memory error.
+For online repair, squashing error conditions in this manner is

an
acceptable
+behavior because the only reaction is to abort the operation back to
userspace.

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+All five xfile usecases can be serviced by these four functions.
+
Quoted 8 lines
Quoted 3 lines

+However, no discussion of file access idioms is complete without answering the
+question, "But what about mmap?"

I actually wouldn't spend too much time discussing solutions that didn't work for what ever reason, unless someones really asking for it.
 I think this section would read just fine to trim off the last paragraph here

Since I wrote this, I've been experimenting with wiring up the tmpfs file page cache folios to the xfs buffer cache.  Pinning the folios in
this manner makes it so that online fsck can (more or less) directly access the xfile contents.  Much to my surprise, this has actually held
up in testing, so ... it's no longer a solution that "didn't really work". :)

I also need to s/page/folio/ now that willy has finished that conversion.  This section has been rewritten as such:

"However, no discussion of file access idioms is complete without answering the question, “But what about mmap?” It is convenient to access storage directly with pointers, just like userspace code does with regular memory. Online fsck must not drive the system into OOM conditions, which means that xfiles must be responsive to memory reclamation. tmpfs can only push a pagecache folio to the swap cache if
the folio is neither pinned nor locked, which means the xfile must not
pin too many folios.

"Short term direct access to xfile contents is done by locking the pagecache folio and mapping it into kernel address space. Programmatic
access (e.g. pread and pwrite) uses this mechanism. Folio locks are not
supposed to be held for long periods of time, so long term direct access
to xfile contents is done by bumping the folio refcount, mapping it into
kernel address space, and dropping the folio lock. These long term users
must be responsive to memory reclaim by hooking into the shrinker infrastructure to know when to release folios.

Quoted 5 lines

"The xfile_get_page and xfile_put_page functions are provided to retrieve the (locked) folio that backs part of an xfile and to release
it. The only code to use these folio lease functions are the xfarray sorting algorithms and the in-memory btrees."

Alrighty, sounds like a good upate then

Quoted 90 lines
Quoted 50 lines
Quoted 50 lines

+It would be *much* more convenient if kernel code could access pageable kernel
+memory with pointers, just like userspace code does with regular memory.
+Like any other filesystem that uses the page cache, reads and writes
of xfile
+data lock the cache page and map it into the kernel address space
for the

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+duration of the operation.
+Unfortunately, shmfs can only write a file page to the swap

device
if the page
+is unmapped and unlocked, which means the xfile risks causing OOM
problems

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+unless it is careful not to pin too many pages.
+Therefore, the xfile steers most of its users towards

programmatic
access so
+that backing pages are not kept locked in memory for longer than is
necessary.
+However, for callers performing quick linear scans of xfile data,
+``xfile_get_page`` and ``xfile_put_page`` functions are provided to
pin a page

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+in memory.
+So far, the only code to use these functions are the xfarray

:ref:`sorting
+<xfarray_sort>` algorithms.

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+
+xfile Access Coordination
+`````````````````````````
+
+For security reasons, xfiles must be owned privately by the

kernel.
+They are marked ``S_PRIVATE`` to prevent interference from the security system,
+must never be mapped into process file descriptor tables, and their
pages must

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+never be mapped into userspace processes.
+
+To avoid locking recursion issues with the VFS, all accesses to

the
shmfs file

Quoted 8 lines

Documentation/filesystems/xfs-online-fsck-design.rst

Quoted 7 lines
Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+are performed by manipulating the page cache directly.
+xfile writes call the ``->write_begin`` and ``->write_end``

functions of the
+xfile's address space to grab writable pages, copy the caller's buffer into the

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+page, and release the pages.
+xfile reads call ``shmem_read_mapping_page_gfp`` to grab pages

xfile readers

OK.

Quoted 18 lines
Quoted 11 lines

directly before

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+copying the contents into the caller's buffer.
+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
and

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+freeze locks.
+
+If an xfile is shared between threads to stage repairs, the
Quoted 3 lines

caller
must provide
+its own locks to coordinate access.

Ofsck threads that share an xfile between stage repairs will use their
own locks to coordinate access with each other.

Quoted 1 line

?

Hm.  I wonder if there's a misunderstanding here?

Online fsck functions themselves are single-threaded, which is to say that they themselves neither queue workers nor start kthreads. However,
an xfile created by a running fsck function can be accessed from other
thread if the fsck function also hooks itself into filesystem code.

Quoted 7 lines
Quoted 3 lines

The live update section has a nice diagram of how that works:
https://djwong.org/docs/xfs-online-fsck-design/#filesystem-hooks

Oh ok, I think I got hung up on who the callers were. How about "xfiles shared between threads running from hooked filesystem functions will use their own locks to coordinate access with each other."

I don't want to mention filesystem hooks before the chapter that introduces them. How about:

"For example, if a scrub function stores scan results in an xfile and needs other threads to provide updates to the scanned data, the scrub function must provide a lock for all threads to share."

--D

#37 lore raw

Re: [PATCH 07/14] xfs: document pageable kernel memory

Quoted 516 lines · Darrick J. Wong
Quoted 506 lines · Allison Henderson
Quoted 206 lines · Darrick J. Wong
Quoted 122 lines · Allison Henderson
Quoted 108 lines · Darrick J. Wong

From: Darrick J. Wong <[email protected]>

Add a discussion of pageable kernel memory, since online fsck needs
quite a bit more memory than most other parts of the filesystem
to
stage
records and other information.

---
 .../filesystems/xfs-online-fsck-design.rst         |  490
++++++++++++++++++++

 1 file changed, 490 insertions(+)
(quoted diff) +0 -0

design.rst b/Documentation/filesystems/xfs-online-fsck-design.rst index 419eb54ee200..9d7a2ef1d0dd 100644

Documentation/filesystems/xfs-online-fsck-design.rst +0 -0
@@ -383,6 +383,8 @@ 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:
+
 Secondary Metadata
 ``````````````````

Documentation/filesystems/xfs-online-fsck-design.rst +0 -0
@@ -1746,3 +1748,491 @@ Scrub teardown disables all static

keys
obtained by ``xchk_fshooks_enable``.

 For more information, please see the kernel documentation of Documentation/staging/static-keys.rst.

Documentation/filesystems/xfs-online-fsck-design.rst +7 -0
+
+.. _xfile:
+
+Pageable Kernel Memory
+----------------------
+
+Demonstrations of the first few prototypes of online repair

revealed
new

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+technical requirements that were not originally identified.
+For the first demonstration, the code walked whatever

filesystem
+metadata it needed to synthesize new records and inserted records
into a new

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+btree as it found them.
+This was subpar since any additional corruption or runtime

errors
encountered

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+during the walk would shut down the filesystem.
+After remount, the blocks containing the half-rebuilt data

structure
would not

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+be accessible until another repair was attempted.
+Solving the problem of half-rebuilt data structures will be

discussed in the

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+next section.
+
+For the second demonstration, the synthesized records were

instead
stored in

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+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.

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+However, even this approach needed improving upon.
+
+There are four reasons why traditional Linux kernel memory

management isn't

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+suitable for storing large datasets:
+
+1. 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. +
+2. While 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.
+
+3. To overcome these two difficulties, the implementation was
adjusted to use
+   doubly linked lists, which means every record object needed
two

Quoted 8 lines

64-bit list
+   head pointers, which is a lot of overhead.
+
+4. Kernel memory is pinned, which can drive the system out of
memory, leading
+   to OOM kills of unrelated processes.
+

I think I maybe might just jump to what ever the current plan is
instead of trying to keep a record of the dev history in the document.
I'm sure we're not done yet, dev really never is, so in order

Quoted 8 lines

for
the
documentation to be maintained, it would just get bigger and bigger
to
keep documenting it this way.  It's not that the above isnt valuable,
but maybe a different kind of document really.

OK, I've shortened this introduction to outline the requirements, and
trimmed the historical information to a sidebar:

"Some online checking functions work by scanning the filesystem to
build
a shadow copy of an ondisk metadata structure in memory and comparing
the two copies. For online repair to rebuild a metadata structure, it
must compute the record set that will be stored in the new structure
before it can persist that new structure to disk. Ideally, repairs
complete with a single atomic commit that introduces a new data structure. To meet these goals, the kernel needs to collect a large
amount of information in a place that doesn’t require the correct operation of the filesystem.

"Kernel memory isn’t suitable because:

*   Allocating a contiguous region of memory to create a C array is
very
    difficult, especially on 32-bit systems.

*   Linked lists of records introduce double pointer overhead which
is
    very high and eliminate the possibility of indexed lookups.

*   Kernel memory is pinned, which can drive the system into OOM conditions.

*   The system might not have sufficient memory to stage all the information.

"At any given time, online fsck does not need to keep the entire record
set in memory, which means that individual records can be paged out
if
necessary. Continued development of online fsck demonstrated that the
ability to perform indexed data storage would also be very useful.
Fortunately, the Linux kernel already has a facility for byte-addressable and pageable storage: tmpfs. In-kernel graphics drivers
(most notably i915) take advantage of tmpfs files to store intermediate
data that doesn’t need to be in memory at all times, so that usage
precedent is already established. Hence, the xfile was born!

Historical Sidebar
------------------

"The first edition of online repair inserted records into a new btree
as
it found them, which failed because filesystem could shut down with a
built data structure, which would be live after recovery finished.

"The second edition solved the half-rebuilt structure problem by storing
everything in memory, but frequently ran the system out of memory.

Quoted 4 lines

"The third edition solved the OOM problem by using linked lists, but
the
list overhead was extreme."

Ok, I think that's cleaner

Quoted 179 lines
Quoted 119 lines
Quoted 7 lines

+For the third iteration, attention swung back to the possibility
of
using

Due to the large volume of metadata that needs to be processed, ofsck
uses...

Quoted 107 lines

+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 rejected for some types of repairs because a
filesystem with
+compromised space and inode metadata should never be used to fix
compromised

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+space or inode metadata.
+However, the kernel already has a facility for byte-

addressable
and
pageable

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+storage: shmfs.
+In-kernel graphics drivers (most notably i915) take

advantage of
shmfs files
+to store intermediate data that doesn't need to be in memory at
all
times, so

Documentation/filesystems/xfs-online-fsck-design.rst +7 -0
+that usage precedent is already established.
+Hence, the ``xfile`` was born!
+
+xfile Access Models
+```````````````````
+
+A survey of the intended uses of xfiles suggested these use

cases:
+
+1. Arrays of fixed-sized records (space management btrees, directory
and
+   extended attribute entries)
+
+2. Sparse arrays of fixed-sized records (quotas and link counts)
+
+3. Large binary objects (BLOBs) of variable sizes (directory and
extended
+   attribute names and values)

Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+
+4. Staging btrees in memory (reverse mapping btrees)
+
+5. Arbitrary contents (realtime space management)
+
+To support the first four use cases, high level data

structures
wrap
the xfile

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+to share functionality between online fsck functions.
+The rest of this section discusses the interfaces that the

xfile
presents to

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+four of those five higher level data structures.
+The fifth use case is discussed in the :ref:`realtime

summary
<rtsummary>` case

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+study.
+
+The most general storage interface supported by the xfile

enables
the reading
+and writing of arbitrary quantities of data at arbitrary offsets
in
the xfile.
+This capability is provided by ``xfile_pread`` and ``xfile_pwrite``
functions,

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+which behave similarly to their userspace counterparts.
+XFS is very record-based, which suggests that the ability to

load
and store

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+complete records is important.
+To support these cases, a pair of ``xfile_obj_load`` and

``xfile_obj_store``
+functions are provided to read and persist objects into an xfile.
+They are internally the same as pread and pwrite, except that
they
treat any

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+error as an out of memory error.
+For online repair, squashing error conditions in this manner

is
an
acceptable
+behavior because the only reaction is to abort the operation back to
userspace.
+All five xfile usecases can be serviced by these four functions.

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+However, no discussion of file access idioms is complete

without
answering the

Quoted 8 lines
Quoted 1 line

+question, "But what about mmap?"

I actually wouldn't spend too much time discussing solutions that
didn't work for what ever reason, unless someones really asking for
it.
 I think this section would read just fine to trim off the last paragraph here

Since I wrote this, I've been experimenting with wiring up the tmpfs
file page cache folios to the xfs buffer cache.  Pinning the folios
in
this manner makes it so that online fsck can (more or less) directly
access the xfile contents.  Much to my surprise, this has actually
held
up in testing, so ... it's no longer a solution that "didn't really
work". :)

I also need to s/page/folio/ now that willy has finished that conversion.  This section has been rewritten as such:

"However, no discussion of file access idioms is complete without answering the question, “But what about mmap?” It is convenient to
access storage directly with pointers, just like userspace code does
with regular memory. Online fsck must not drive the system into OOM
conditions, which means that xfiles must be responsive to memory reclamation. tmpfs can only push a pagecache folio to the swap cache
if
the folio is neither pinned nor locked, which means the xfile must
not
pin too many folios.

"Short term direct access to xfile contents is done by locking the
pagecache folio and mapping it into kernel address space. Programmatic
access (e.g. pread and pwrite) uses this mechanism. Folio locks are
not
supposed to be held for long periods of time, so long term direct access
to xfile contents is done by bumping the folio refcount, mapping it
into
kernel address space, and dropping the folio lock. These long term
users
must be responsive to memory reclaim by hooking into the shrinker infrastructure to know when to release folios.

Quoted 6 lines

"The xfile_get_page and xfile_put_page functions are provided to retrieve the (locked) folio that backs part of an xfile and to release
it. The only code to use these folio lease functions are the xfarray
sorting algorithms and the in-memory btrees."

Alrighty, sounds like a good upate then

Quoted 106 lines
Quoted 61 lines
Quoted 61 lines

+It would be *much* more convenient if kernel code could access
pageable kernel
+memory with pointers, just like userspace code does with regular
memory.
+Like any other filesystem that uses the page cache, reads and
writes
of xfile
+data lock the cache page and map it into the kernel address space
for the

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+duration of the operation.
+Unfortunately, shmfs can only write a file page to the swap

device
if the page
+is unmapped and unlocked, which means the xfile risks causing
OOM
problems

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+unless it is careful not to pin too many pages.
+Therefore, the xfile steers most of its users towards

programmatic
access so
+that backing pages are not kept locked in memory for longer than
is
necessary.
+However, for callers performing quick linear scans of xfile data,
+``xfile_get_page`` and ``xfile_put_page`` functions are provided
to
pin a page

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+in memory.
+So far, the only code to use these functions are the xfarray

:ref:`sorting
+<xfarray_sort>` algorithms.

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+
+xfile Access Coordination
+`````````````````````````
+
+For security reasons, xfiles must be owned privately by the

kernel.
+They are marked ``S_PRIVATE`` to prevent interference from the
security system,
+must never be mapped into process file descriptor tables, and
their
pages must

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+never be mapped into userspace processes.
+
+To avoid locking recursion issues with the VFS, all accesses

to
the
shmfs file

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+are performed by manipulating the page cache directly.
+xfile writes call the ``->write_begin`` and ``->write_end``
Quoted 8 lines
Quoted 7 lines

functions of the
+xfile's address space to grab writable pages, copy the caller's
buffer into the

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+page, and release the pages.
+xfile reads call ``shmem_read_mapping_page_gfp`` to grab

pages

xfile readers

OK.

Quoted 21 lines
Quoted 13 lines

directly before

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+copying the contents into the caller's buffer.
+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
and

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+freeze locks.
+
+If an xfile is shared between threads to stage repairs, the
Quoted 3 lines

caller
must provide
+its own locks to coordinate access.

Ofsck threads that share an xfile between stage repairs will use
their
own locks to coordinate access with each other.

Quoted 1 line

?

Hm.  I wonder if there's a misunderstanding here?

Online fsck functions themselves are single-threaded, which is to say
that they themselves neither queue workers nor start kthreads. However,
an xfile created by a running fsck function can be accessed from other
thread if the fsck function also hooks itself into filesystem code.

Quoted 8 lines
Quoted 3 lines

The live update section has a nice diagram of how that works:
https://djwong.org/docs/xfs-online-fsck-design/#filesystem-hooks

Oh ok, I think I got hung up on who the callers were.  How about "xfiles shared between threads running from hooked filesystem functions
will use their own locks to coordinate access with each other."

Quoted 6 lines

I don't want to mention filesystem hooks before the chapter that introduces them.  How about:

"For example, if a scrub function stores scan results in an xfile and needs other threads to provide updates to the scanned data, the scrub function must provide a lock for all threads to share."

Oh, I didnt see this response....

Ok, i think that sounds fine. Alternately I think if patch 10 were to move up, then it would have sounded fine since we introduce hooks there, but I think either way works

Allison

Quoted 2 lines

--D

#38 lore raw

PATCH 8/14 xfs: document btree bulk loading

In reply to Darrick J. Wong

From: Darrick J. Wong <[email protected]>

Add a discussion of the btree bulk loading code, which makes it easy to take an in-memory recordset and write it out to disk in an efficient manner. This also enables atomic switchover from the old to the new structure with minimal potential for leaking the old blocks.

---
 .../filesystems/xfs-online-fsck-design.rst         |  632 ++++++++++++++++++++
 1 file changed, 632 insertions(+)
Documentation/filesystems/xfs-online-fsck-design.rst +632 -0
index 9d7a2ef1d0dd..eb61d867e55c 100644
@@ -2236,3 +2236,635 @@ this functionality as follows:
 
 After removing xfile logged buffers from the transaction in this manner, the
 transaction can be committed or cancelled.
+
+Bulk Loading of Ondisk B+Trees
+------------------------------
+
+As mentioned previously, early iterations of online repair built new btree
+structures by creating a new btree and adding observations 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, but was very slow and leaked
+blocks if the system went down during a repair.
+Loading records one at a time also meant that repair could not 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.
+This was implemented rather inefficiently code-wise, since ``xfs_repair``
+had separate copy-pasted implementations for each btree type.
+
+To prepare for online fsck, each of the four bulk loaders were studied, notes
+were taken, and the four were refactored into a single generic btree bulk
+loading mechanism.
+Those notes in turn have been refreshed and are presented below.
+
+Geometry Computation
+````````````````````
+
+The zeroth step of bulk loading is to assemble the entire record set that will
+be stored in the new btree, and sort the records.
+Next, call ``xfs_btree_bload_compute_geometry`` to compute the shape of the
+btree from the record set, the type of btree, and any load factor preferences.
+This information is required for resource reservation.
+
+First, the geometry computation computes the minimum and maximum records that
+will fit in a leaf block from the size of a btree block and the size of 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)
+
+The entire computation is performed recursively until the current level only
+needs one block.
+The resulting geometry is as follows:
+
+- For AG-rooted btrees, this level is the root level, so the height of the new
+  tree is ``level + 1`` and the space needed is the summation of the number of
+  blocks on each level.
+
+- For inode-rooted btrees where the records in the top level do not fit in the
+  inode fork area, the height is ``level + 2``, the space needed is the
+  summation of the number of blocks on each level, and the inode fork points to
+  the root block.
+
+- For inode-rooted btrees where the records in the top level can be stored in
+  the inode fork area, then the root block can be stored in the inode, the
+  height is ``level + 1``, and the space needed is one less than the summation
+  of the number of blocks on each level.
+  This only becomes relevant when non-bmap btrees gain the ability to root in
+  an inode, which is a future patchset and only included here for completeness.
+
+.. _newbt:
+
+Reserving New B+Tree Blocks
+```````````````````````````
+
+Once repair knows the number of blocks needed for the new btree, it allocates
+those blocks using the free space information.
+Each reserved extent is tracked separately by the btree builder state data.
+To improve crash resilience, the reservation code also logs an Extent Freeing
+Intent (EFI) item in the same transaction as each space allocation and attaches
+its in-memory ``struct xfs_extent_free_item`` object to the space reservation.
+If the system goes down, log recovery will use the unfinished EFIs to free the
+unused space, the free space, leaving the filesystem unchanged.
+
+Each time the btree builder claims a block for the btree from a reserved
+extent, it updates the in-memory reservation to reflect the claimed space.
+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 ondisk 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 must not 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 and reaping phases; please see the
+next section and the section about :ref:`reaping<reaping>` for more details.
+
+Proposed patchsets are the
+`bitmap rework
+<https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/log/?h=repair-bitmap-rework>`_
+and the
+`preparation for bulk loading btrees
+<https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/log/?h=repair-prep-for-bulk-loading>`_.
+
+
+Writing the New Tree
+````````````````````
+
+This part is pretty simple -- the btree builder (``xfs_btree_bulkload``) claims
+a block from the reserved list, writes the new btree block header, fills the
+rest of the block with records, and adds the new leaf block to a list of
+written blocks.
+Sibling pointers are set every time a new block is added to the level.
+When it finishes writing the record leaf blocks, it moves on to the node
+blocks.
+To fill a node block, it walks each block in the next level down in the tree
+to compute the relevant keys and write them into the parent node.
+When it reaches the root level, it is ready to commit the new btree!
+
+The first step to commit the new btree is to persist the btree blocks to disk
+synchronously.
+This is a little complicated because a new btree block could have been freed
+in the recent past, so the builder must use ``xfs_buf_delwri_queue_here`` to
+remove the (stale) buffer from the AIL list before it can write the new blocks
+to disk.
+Blocks are queued for IO using a delwri list and written in one large batch
+with ``xfs_buf_delwri_submit``.
+
+Once the new blocks have been persisted to disk, control returns to the
+individual repair function that called the bulk loader.
+The repair function must log the location of the new root in a transaction,
+clean up the space reservations that were made for the new btree, and reap the
+old metadata blocks:
+
+1. Commit the location of the new btree root.
+
+2. For each incore reservation:
+
+   a. Log Extent Freeing Done (EFD) items for all the space that was consumed
+      by the btree builder.  The new EFDs must point to the EFIs attached to
+      the reservation to prevent log recovery from freeing the new blocks.
+
+   b. For unclaimed portions of incore reservations, create a regular deferred
+      extent free work item to be free the unused space later in the
+      transaction chain.
+
+   c. The EFDs and EFIs logged in steps 2a and 2b must not overrun the
+      reservation of the committing transaction.
+      If the btree loading code suspects this might be about to happen, it must
+      call ``xrep_defer_finish`` to clear out the deferred work and obtain a
+      fresh transaction.
+
+3. Clear out the deferred work a second time to finish the commit and clean
+   the repair transaction.
+
+The transaction rolling in steps 2c and 3 represent a weakness in the repair
+algorithm, because a log flush and a crash before the end of the reap step can
+result in space leaking.
+Online repair functions minimize the chances of this occuring by using very
+large transactions, which each can accomodate many thousands of block freeing
+instructions.
+Repair moves on to reaping the old blocks, which will be presented in a
+subsequent :ref:`section<reaping>` after a few case studies of bulk loading.
+
+Case Study: Rebuilding the Inode Index
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+The high level process to rebuild the inode index btree is:
+
+1. Walk the reverse mapping records to generate ``struct xfs_inobt_rec``
+   records from the inode chunk information and a bitmap of the old inode btree
+   blocks.
+
+2. Append the records to an xfarray in inode order.
+
+3. Use the ``xfs_btree_bload_compute_geometry`` function to compute the number
+   of blocks needed for the inode btree.
+   If the free space inode btree is enabled, call it again to estimate the
+   geometry of the finobt.
+
+4. Allocate the number of blocks computed in the previous step.
+
+5. Use ``xfs_btree_bload`` to write the xfarray records to btree blocks and
+   generate the internal node blocks.
+   If the free space inode btree is enabled, call it again to load the finobt.
+
+6. Commit the location of the new btree root block(s) to the AGI.
+
+7. Reap the old btree blocks using the bitmap created in step 1.
+
+Details are as follows.
+
+The inode btree maps inumbers to the ondisk location of the associated
+inode records, which means that the inode btrees can be rebuilt from the
+reverse mapping information.
+Reverse mapping records with an owner of ``XFS_RMAP_OWN_INOBT`` marks the
+location of the old inode btree blocks.
+Each reverse mapping record with an owner of ``XFS_RMAP_OWN_INODES`` marks 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 the space represented by each inode cluster, 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
+(``xfs_dinode.i_mode != 0``) or free (``xfs_dinode.i_mode == 0``).
+Accumulate the results of successive inode cluster buffer reads until there is
+enough information to fill a single inode chunk record, which is 64 consecutive
+numbers in the inumber keyspace.
+If the chunk is sparse, the chunk record may include holes.
+
+Once the repair function accumulates one chunk's worth of data, it calls
+``xfarray_append`` to add the inode btree record to the xfarray.
+This xfarray is walked twice during the btree creation step -- once to populate
+the inode btree with all inode chunk records, and a second time to populate the
+free inode btree 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 inode chunk
+records are stored in the xfarray.
+
+The proposed patchset is the
+`AG btree repair
+<https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/log/?h=repair-ag-btrees>`_
+series.
+
+Case Study: Rebuilding the Space Reference Counts
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+The high level process to rebuild the reference count btree is:
+
+1. Walk the reverse mapping records to generate ``struct xfs_refcount_irec``
+   records for any space having more than one reverse mapping and add them to
+   the xfarray.
+   Any records owned by ``XFS_RMAP_OWN_COW`` are also added to the xfarray.
+   Use any records owned by ``XFS_RMAP_OWN_REFC`` to create a bitmap of old
+   refcount btree blocks.
+
+2. Sort the records in physical extent order, putting the CoW staging extents
+   at the end of the xfarray.
+
+3. Use the ``xfs_btree_bload_compute_geometry`` function to compute the number
+   of blocks needed for the new tree.
+
+4. Allocate the number of blocks computed in the previous step.
+
+5. Use ``xfs_btree_bload`` to write the xfarray records to btree blocks and
+   generate the internal node blocks.
+
+6. Commit the location of new btree root block to the AGF.
+
+7. Reap the old btree blocks using the bitmap created in step 1.
+
+Details are as follows; the same algorithm is used by ``xfs_repair`` to
+generate refcount information from reverse mapping records.
+
+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.
+From the diagram below, it is apparent that a reference count record must start
+or end 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
+
+The ondisk reference count btree does not store the refcount == 0 cases because
+the free space btree already records 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``), reference count information is constructed from reverse mapping data
+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,
+
+   a. Remove from the bag all mappings where ``rm_startblock`` +
+      ``rm_blockcount`` == ``np``.
+
+   b. Add to the bag all reverse mappings where ``rm_startblock`` == ``np``.
+
+   c. If the bag size isn't ``old_bag_size``, store the refcount record
+      ``(sp, np - sp, old_bag_size)`` in the refcount xfarray.
+
+   d. If the bag is empty, break out of this inner loop.
+
+   e. Set ``old_bag_size`` to ``bag_size``.
+
+   f. Set ``sp`` = ``np``.
+
+   g. Set ``np`` to the physical block where the bag size will change.
+      Go to step 3 above.
+
+The bag-like structure in this case is a type 2 xfarray as discussed in the
+:ref:`xfarray access patterns<xfarray_access_patterns>` section.
+Reverse mappings are added to the bag using ``xfarray_store_anywhere`` and
+removed via ``xfarray_unset``.
+Bag members are examined through ``xfarray_iter`` loops.
+
+The proposed patchset is the
+`AG btree repair
+<https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/log/?h=repair-ag-btrees>`_
+series.
+
+Case Study: Rebuilding File Fork Mapping Indices
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+The high level process to rebuild a data/attr fork mapping btree is:
+
+1. Walk the reverse mapping records to generate ``struct xfs_bmbt_rec``
+   records from the reverse mapping records for that inode and fork.
+   Append these records to an xfarray.
+   Compute the bitmap of the old bmap btree blocks from the ``BMBT_BLOCK``
+   records.
+
+2. Use the ``xfs_btree_bload_compute_geometry`` function to compute the number
+   of blocks needed for the new tree.
+
+3. Sort the records in file offset order.
+
+4. If the extent records would fit in the inode fork immediate area, commit the
+   records to that immediate area and skip to step 8.
+
+5. Allocate the number of blocks computed in the previous step.
+
+6. Use ``xfs_btree_bload`` to write the xfarray records to btree blocks and
+   generate the internal node blocks.
+
+7. Commit the new btree root block to the inode fork immediate area.
+
+8. Reap the old btree blocks using the bitmap created in step 1.
+
+There are some 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, which may require a conversion.
+Third, the incore extent map must be reloaded carefully to avoid disturbing
+any delayed allocation extents.
+
+The proposed patchset is the
+`file repair
+<https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/log/?h=repair-inodes>`_
+series.
+
+.. _reaping:
+
+Reaping Old Metadata Blocks
+---------------------------
+
+Whenever online fsck builds a new data structure to replace one that is
+suspect, there is a question of how to find and dispose of the blocks that
+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.
+Hopefully, someone will schedule a rebuild of the free space information to
+plug all those leaks.
+Offline repair rebuilds all space metadata after recording the usage of
+the files and directories that it decides not to clear, hence it can build new
+structures in the discovered free space and avoid the question of reaping.
+
+As part of a repair, online fsck relies heavily on the reverse mapping records
+to find space that is owned by the corresponding rmap owner yet truly free.
+Cross referencing rmap records with other rmap records is necessary 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.
+
+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 must be preserved.
+   The space reservations used to create the new metadata can be used here if
+   the same rmap owner code is used to denote all of the objects being rebuilt.
+
+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 candidate 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:
+
+4. For each candidate extent, 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.
+
+5. 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.
+
+6. If the region is crosslinked, delete the reverse mapping entry for the
+   structure being repaired and move on to the next region.
+
+7. If the region is to be freed, mark any corresponding buffers in the buffer
+   cache as stale to prevent log writeback.
+
+8. Free the region and move on.
+
+However, there is one complication to this procedure.
+Transactions are of finite size, so the reaping process must be careful to roll
+the transactions to avoid overruns.
+Overruns come from two sources:
+
+a. EFIs logged on behalf of space that is no longer occupied
+
+b. Log items for buffer invalidations
+
+This is also a window in which a crash during the reaping process can leak
+blocks.
+As stated earlier, online repair functions use very large transactions to
+minimize the chances of this occurring.
+
+The proposed patchset is the
+`preparation for bulk loading btrees
+<https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/log/?h=repair-prep-for-bulk-loading>`_
+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 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 corresponding to the
+   metadata structure being rebuilt, 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)``
+   are the blocks that might be freeable.
+
+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
+`````````````````````````````````````````````
+
+The high level process to rebuild the free space indices is:
+
+1. Walk the reverse mapping records to generate ``struct xfs_alloc_rec_incore``
+   records from the gaps in the reverse mapping btree.
+
+2. Append the records to an xfarray.
+
+3. Use the ``xfs_btree_bload_compute_geometry`` function to compute the number
+   of blocks needed for each new tree.
+
+4. Allocate the number of blocks computed in the previous step from the free
+   space information collected.
+
+5. Use ``xfs_btree_bload`` to write the xfarray records to btree blocks and
+   generate the internal node blocks for the free space by block index.
+   Call it again for the free space by length index.
+
+6. Commit the locations of the new btree root blocks to the AGF.
+
+7. Reap the old btree blocks by looking for space that is not recorded by the
+   reverse mapping btree, the new free space btrees, or the AGFL.
+
+Repairing the free space btrees has three key complications over a regular
+btree repair:
+
+First, 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.
+
+Second, free space repairs cannot use the common btree reservation code because
+new blocks are reserved out of the free space btrees.
+This is 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 the new
+free space btrees are constructed in what the ondisk filesystem thinks is
+unowned 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, repair must ensure that reverse mappings
+are created for the reserved blocks 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, similar to the other btree repair functions.
+
+Third, finding the blocks to reap after the repair is not overly
+straightforward.
+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 repair walks reverse mapping records to synthesize free space records, it
+creates a bitmap (``ag_owner_bitmap``) of all the space claimed by
+``XFS_RMAP_OWN_AG`` records.
+The repair context maintains a second bitmap 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)`` computes the extents that 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
+<https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/log/?h=repair-ag-btrees>`_
+series.
+
+.. _rmap_reap:
+
+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
+:ref:`live rebuilds of rmap data <rmap_repair>`, but a crucial point from that
+discussion is that the new rmap btree will not contain any records for the old
+rmap btree, nor will 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 and the current AGFL
+blocks.
+The result ``(new_rmapbt_gaps & ~(agfl | bnobt_records))`` are reaped using the
+methods outlined above.
+
+The rest of the process of rebuildng the reverse mapping btree is discussed
+in a separate :ref:`case study<rmap_repair>`.
+
+The proposed patchset is the
+`AG btree repair
+<https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/log/?h=repair-ag-btrees>`_
+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.
#39 lore raw

Re: [PATCH 08/14] xfs: document btree bulk loading

Quoted 93 lines · Darrick J. Wong

From: Darrick J. Wong <[email protected]>

Add a discussion of the btree bulk loading code, which makes it easy to
take an in-memory recordset and write it out to disk in an efficient manner.  This also enables atomic switchover from the old to the new structure with minimal potential for leaking the old blocks.

---
 .../filesystems/xfs-online-fsck-design.rst         |  632
++++++++++++++++++++

 1 file changed, 632 insertions(+)
Documentation/filesystems/xfs-online-fsck-design.rst +0 -0
index 9d7a2ef1d0dd..eb61d867e55c 100644
@@ -2236,3 +2236,635 @@ this functionality as follows:


 After removing xfile logged buffers from the transaction in this manner, the
 transaction can be committed or cancelled.

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+
+Bulk Loading of Ondisk B+Trees
+------------------------------
+
+As mentioned previously, early iterations of online repair built new

btree
+structures by creating a new btree and adding observations 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, but was very slow and leaked

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+blocks if the system went down during a repair.
+Loading records one at a time also meant that repair could not

control the

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+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.
+This was implemented rather inefficiently code-wise, since ``xfs_repair``

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+had separate copy-pasted implementations for each btree type.
+
+To prepare for online fsck, each of the four bulk loaders were

studied, notes
+were taken, and the four were refactored into a single generic btree bulk

Documentation/filesystems/xfs-online-fsck-design.rst +7 -0
+loading mechanism.
+Those notes in turn have been refreshed and are presented below.
+
+Geometry Computation
+````````````````````
+
+The zeroth step of bulk loading is to assemble the entire record set

that will

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+be stored in the new btree, and sort the records.
+Next, call ``xfs_btree_bload_compute_geometry`` to compute the shape

of the
+btree from the record set, the type of btree, and any load factor preferences.

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+This information is required for resource reservation.
+
+First, the geometry computation computes the minimum and maximum

records that
+will fit in a leaf block from the size of a btree block and the size of the

Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+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,

Documentation/filesystems/xfs-online-fsck-design.rst +8 -0
+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

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+drop in performance immediately afterwards.
+The default loading factor was chosen to be 75% of maxrecs, which
Quoted 2 lines

provides a
+reasonably compact structure without any immediate split penalties.

	default_lload_factor = (maxrecs + minrecs) / 2;
Quoted 6 lines

+If space is tight, the loading factor will be set to maxrecs to try to avoid

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+running out of space::
+
+        leaf_load_factor = enough space ? (maxrecs + minrecs) / 2 :

maxrecs

leaf_load_factor = enough space ? default_lload_factor :
maxrecs;

Just more readable i think

Documentation/filesystems/xfs-online-fsck-design.rst this functionality as follows: · line 2299

Quoted 7 lines
Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+Load factor is computed for btree node blocks using the combined

size of the

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+btree key and pointer as the record size::
+
+        maxrecs = (block_size - header_size) / (key_size + ptr_size)
+        minrecs = maxrecs / 2
	default_nload_factor = (maxrecs + minrecs) / 2;
Quoted 2 lines

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

node_load_factor = enough space ? default_nload_factor :
maxrecs;

Quoted 124 lines
Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+Once that's done, the number of leaf blocks required to store the

record set

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+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

Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+is computed as::
+
+        n_blocks = (n == 0 ? leaf_blocks : node_blocks[n])
+        node_blocks[n + 1] = ceil(n_blocks / node_load_factor)
+
+The entire computation is performed recursively until the current

level only

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+needs one block.
+The resulting geometry is as follows:
+
+- For AG-rooted btrees, this level is the root level, so the height

of the new
+  tree is ``level + 1`` and the space needed is the summation of the number of
+  blocks on each level.
+
+- For inode-rooted btrees where the records in the top level do not fit in the
+  inode fork area, the height is ``level + 2``, the space needed is the
+  summation of the number of blocks on each level, and the inode fork points to
+  the root block.
+
+- For inode-rooted btrees where the records in the top level can be stored in
+  the inode fork area, then the root block can be stored in the inode, the
+  height is ``level + 1``, and the space needed is one less than the summation
+  of the number of blocks on each level.
+  This only becomes relevant when non-bmap btrees gain the ability to root in
+  an inode, which is a future patchset and only included here for completeness.

Documentation/filesystems/xfs-online-fsck-design.rst +7 -0
+
+.. _newbt:
+
+Reserving New B+Tree Blocks
+```````````````````````````
+
+Once repair knows the number of blocks needed for the new btree, it

allocates

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+those blocks using the free space information.
+Each reserved extent is tracked separately by the btree builder

state data.
+To improve crash resilience, the reservation code also logs an Extent Freeing
+Intent (EFI) item in the same transaction as each space allocation and attaches
+its in-memory ``struct xfs_extent_free_item`` object to the space reservation.
+If the system goes down, log recovery will use the unfinished EFIs to free the

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+unused space, the free space, leaving the filesystem unchanged.
+
+Each time the btree builder claims a block for the btree from a

reserved
+extent, it updates the in-memory reservation to reflect the claimed space.
+Block reservation tries to allocate as much contiguous space as possible to

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+reduce the number of EFIs in play.
+
+While repair is writing these new btree blocks, the EFIs created for

the space

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+reservations pin the tail of the ondisk log.
+It's possible that other parts of the system will remain busy and

push the head

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+of the log towards the pinned tail.
+To avoid livelocking the filesystem, the EFIs must not pin the tail

of the log

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+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

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+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.

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+EFIs have a role to play during the commit and reaping phases;

please see the
+next section and the section about :ref:reaping<reaping> for more details.

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+
+Proposed patchsets are the
+`bitmap rework
+<

https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/
log/?h=repair-bitmap-rework>`_
+and the
+`preparation for bulk loading btrees
+<
https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/
log/?h=repair-prep-for-bulk-loading>`_.

Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+
+
+Writing the New Tree
+````````````````````
+
+This part is pretty simple -- the btree builder

(``xfs_btree_bulkload``) claims
+a block from the reserved list, writes the new btree block header, fills the
+rest of the block with records, and adds the new leaf block to a list of

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+written blocks.
+Sibling pointers are set every time a new block is added to the

level.
+When it finishes writing the record leaf blocks, it moves on to the node

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+blocks.
+To fill a node block, it walks each block in the next level down in

the tree

Documentation/filesystems/xfs-online-fsck-design.rst this functionality as follows: · line 2386

Quoted 2 lines
Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+to compute the relevant keys and write them into the parent node.
+When it reaches the root level, it is ready to commit the new btree!

I think most of this is as straight forward as it can be, but it's a lot visualizing too, which makes me wonder if it would benefit from an simple illustration if possible.

On a side note: In a prior team I discovered power points, while a lot work, were also really effective for quickly moving a crowd of people through connected graph navigation/manipulations. Because each one of these steps was another slide that illustrated how the structure evolved through the updates. I realize that's not something that fits in the scheme of a document like this, but maybe something supplemental to add later.  While it was a time eater, i noticed a lot of confused expressions just seemed to shake loose, so sometimes it was worth it.

Quoted 164 lines
Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+The first step to commit the new btree is to persist the btree

blocks to disk

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+synchronously.
+This is a little complicated because a new btree block could have

been freed
+in the recent past, so the builder must use ``xfs_buf_delwri_queue_here`` to
+remove the (stale) buffer from the AIL list before it can write the new blocks

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+to disk.
+Blocks are queued for IO using a delwri list and written in one

large batch

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+with ``xfs_buf_delwri_submit``.
+
+Once the new blocks have been persisted to disk, control returns to

the

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+individual repair function that called the bulk loader.
+The repair function must log the location of the new root in a

transaction,
+clean up the space reservations that were made for the new btree, and reap the

Documentation/filesystems/xfs-online-fsck-design.rst +7 -0
+old metadata blocks:
+
+1. Commit the location of the new btree root.
+
+2. For each incore reservation:
+
+   a. Log Extent Freeing Done (EFD) items for all the space that was

consumed
+      by the btree builder.  The new EFDs must point to the EFIs attached to
+      the reservation to prevent log recovery from freeing the new blocks.
+
+   b. For unclaimed portions of incore reservations, create a regular deferred
+      extent free work item to be free the unused space later in the +      transaction chain.
+
+   c. The EFDs and EFIs logged in steps 2a and 2b must not overrun the
+      reservation of the committing transaction.
+      If the btree loading code suspects this might be about to happen, it must
+      call ``xrep_defer_finish`` to clear out the deferred work and obtain a
+      fresh transaction.
+
+3. Clear out the deferred work a second time to finish the commit and clean
+   the repair transaction.

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+The transaction rolling in steps 2c and 3 represent a weakness in

the repair
+algorithm, because a log flush and a crash before the end of the reap step can

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+result in space leaking.
+Online repair functions minimize the chances of this occuring by

using very
+large transactions, which each can accomodate many thousands of block freeing

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+instructions.
+Repair moves on to reaping the old blocks, which will be presented

in a
+subsequent :ref:section<reaping> after a few case studies of bulk loading.

Documentation/filesystems/xfs-online-fsck-design.rst +7 -0
+
+Case Study: Rebuilding the Inode Index
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+The high level process to rebuild the inode index btree is:
+
+1. Walk the reverse mapping records to generate ``struct

xfs_inobt_rec``
+   records from the inode chunk information and a bitmap of the old inode btree
+   blocks.

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+
+2. Append the records to an xfarray in inode order.
+
+3. Use the ``xfs_btree_bload_compute_geometry`` function to compute

the number
+   of blocks needed for the inode btree.
+   If the free space inode btree is enabled, call it again to estimate the
+   geometry of the finobt.

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+
+4. Allocate the number of blocks computed in the previous step.
+
+5. Use ``xfs_btree_bload`` to write the xfarray records to btree

blocks and
+   generate the internal node blocks.
+   If the free space inode btree is enabled, call it again to load the finobt.

Documentation/filesystems/xfs-online-fsck-design.rst +8 -0
+
+6. Commit the location of the new btree root block(s) to the AGI.
+
+7. Reap the old btree blocks using the bitmap created in step 1.
+
+Details are as follows.
+
+The inode btree maps inumbers to the ondisk location of the

associated
+inode records, which means that the inode btrees can be rebuilt from the

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+reverse mapping information.
+Reverse mapping records with an owner of ``XFS_RMAP_OWN_INOBT``

marks the

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+location of the old inode btree blocks.
+Each reverse mapping record with an owner of ``XFS_RMAP_OWN_INODES``

marks the

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+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.

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+For the space represented by each inode cluster, 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

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+operation.
+Otherwise, read each cluster buffer to check that its contents

appear to be

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+ondisk inodes and to decide if the file is allocated
+(``xfs_dinode.i_mode != 0``) or free (``xfs_dinode.i_mode == 0``).
+Accumulate the results of successive inode cluster buffer reads

until there is
+enough information to fill a single inode chunk record, which is 64 consecutive

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+numbers in the inumber keyspace.
+If the chunk is sparse, the chunk record may include holes.
+
+Once the repair function accumulates one chunk's worth of data, it

calls
+``xfarray_append`` to add the inode btree record to the xfarray. +This xfarray is walked twice during the btree creation step -- once to populate
+the inode btree with all inode chunk records, and a second time to populate the
+free inode btree 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 inode chunk

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+records are stored in the xfarray.
+
+The proposed patchset is the
+`AG btree repair
+<

https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/
log/?h=repair-ag-btrees>`_

Documentation/filesystems/xfs-online-fsck-design.rst +8 -0
+series.
+
+Case Study: Rebuilding the Space Reference Counts
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+The high level process to rebuild the reference count btree is:
+
+1. Walk the reverse mapping records to generate ``struct
Quoted 6 lines

xfs_refcount_irec``
+   records for any space having more than one reverse mapping and add them to
+   the xfarray.
+   Any records owned by ``XFS_RMAP_OWN_COW`` are also added to the xfarray.

Any records owned by ``XFS_RMAP_OWN_COW`` are also added to the xfarray even if they only have one mapping

?

You haven't mentioned any owners being disallowed, you've only stated that you're collecting records with more than one rmap, so that would be the inferred meaning.

Also I think you also need to mention why. The documentation is starting to read a little more like pseudo code, but if it's not explaining why it's doing things, we may as well just go to the code

Quoted 7 lines

+   Use any records owned by ``XFS_RMAP_OWN_REFC`` to create a bitmap of old
+   refcount btree blocks.
+
+2. Sort the records in physical extent order, putting the CoW staging extents
+   at the end of the xfarray.

Why?

Quoted 45 lines

+
+3. Use the ``xfs_btree_bload_compute_geometry`` function to compute the number
+   of blocks needed for the new tree.

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+
+4. Allocate the number of blocks computed in the previous step.
+
+5. Use ``xfs_btree_bload`` to write the xfarray records to btree

blocks and
+   generate the internal node blocks.

Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+
+6. Commit the location of new btree root block to the AGF.
+
+7. Reap the old btree blocks using the bitmap created in step 1.
+
+Details are as follows; the same algorithm is used by ``xfs_repair``

to

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+generate refcount information from reverse mapping records.
+
+Reverse mapping records are used to rebuild the reference count

information.
+Reference counts are required for correct operation of copy on write for shared

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+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

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+overlap each other.
+From the diagram below, it is apparent that a reference count record

must start

Documentation/filesystems/xfs-online-fsck-design.rst +11 -0
+or end 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
+
+The ondisk reference count btree does not store the refcount == 0

cases because

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+the free space btree already records which blocks are free.
+Extents being used to stage copy-on-write operations should be the
Quoted 2 lines

only records
+with refcount == 1.

So here you explain it... I think maybe the pseudo code would read easier if you put it after the high level explanations of what we're doing

Quoted 15 lines

+Single-owner file blocks aren't recorded in either the free space or the

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+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``), reference count information is constructed from reverse mapping data

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+as follows:
+
+While there are still unprocessed mappings in the reverse mapping
Quoted 8 lines

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``.

Hmm, if this were code, I could tag the rm_startblock symbol, but that doesnt work for a document. While I could go look at the code to answer this, you want your document to explain the code, not the other way around... further commentary below...

Quoted 28 lines

+
+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).

Documentation/filesystems/xfs-online-fsck-design.rst +9 -0
+
+4. Record the bag size as ``old_bag_size``.
+
+5. While the bag isn't empty,
+
+   a. Remove from the bag all mappings where ``rm_startblock`` +
+      ``rm_blockcount`` == ``np``.
+
+   b. Add to the bag all reverse mappings where ``rm_startblock`` ==

``np``.
+
+   c. If the bag size isn't ``old_bag_size``, store the refcount record
+      ``(sp, np - sp, old_bag_size)`` in the refcount xfarray.

Documentation/filesystems/xfs-online-fsck-design.rst +8 -0
+
+   d. If the bag is empty, break out of this inner loop.
+
+   e. Set ``old_bag_size`` to ``bag_size``.
+
+   f. Set ``sp`` = ``np``.
+
+   g. Set ``np`` to the physical block where the bag size will
Quoted 2 lines

change.
+      Go to step 3 above.

I don't think verbalizing literal lines of code is any more explanatory than the code. I think it's easier just give the high level description and then just go look at it.

I notice you have the exact same verbiage in the code, you could just link it:
https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/commit/?h=repair-ag-btrees&id=771fa17dd5fd7d3d125c61232c4390e8f7ac0fb0#:~:text=*%20While%20there%20are%20still%20unprocessed%20rmaps%20in%20the%20array,and%20(startblock%20%2B%20len%20of%20each%20rmap%20in%20the%20bag)
.

Also that may cut down on future maintenance if this ever changes since people might not think to update the document along with the code

Hmm, just thinking outside the box, what do you think of this method of presentation:

- Iterate over btree
records tinyurl.com/4mp3j3pw
- Find the corresponding reverse
mapping tinyurl.com/27n7h5fa
- Collect all shared mappings with the same starting
block tinyurl.com/mwdfy52b
- Advance to the next block with a ref count
change tinyurl.com/28689ufz
This position will either be the next unprocessed rmap, or the combined length all the collected mappings, which ever is
smaller
- Iterate over the collected
mappings, tinyurl.com/ye673rwa
- Remove all mappings that start after this
position tinyurl.com/22yp7p6u
- Re-collect all mappings that start on this
position tinyurl.com/2p8vytmv
- If the size of the collection increased, update the ref
count tinyurl.com/ecu7tud7
- If more mappings were found, advance to the next block
with tinyurl.com/47p4dfac
a ref count change. Continue until no more mappings are
found

It pulls the pseudo code up to a little higher level, plus the quick links to jump deeper if needed and then people have all the navigation utilities they are used to. I just found a quick url shortener, so I'm not really sure how long they keep those, but maybe we can find an appropriate shorter

Quoted 44 lines
Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+The bag-like structure in this case is a type 2 xfarray as discussed

in the
+:ref:xfarray access patterns<xfarray_access_patterns> section. +Reverse mappings are added to the bag using ``xfarray_store_anywhere`` and

Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+removed via ``xfarray_unset``.
+Bag members are examined through ``xfarray_iter`` loops.
+
+The proposed patchset is the
+`AG btree repair
+<

https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/
log/?h=repair-ag-btrees>`_

Documentation/filesystems/xfs-online-fsck-design.rst +8 -0
+series.
+
+Case Study: Rebuilding File Fork Mapping Indices
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+The high level process to rebuild a data/attr fork mapping btree is:
+
+1. Walk the reverse mapping records to generate ``struct

xfs_bmbt_rec``
+   records from the reverse mapping records for that inode and fork. +   Append these records to an xfarray.
+   Compute the bitmap of the old bmap btree blocks from the ``BMBT_BLOCK``
+   records.
+
+2. Use the ``xfs_btree_bload_compute_geometry`` function to compute the number
+   of blocks needed for the new tree.

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+
+3. Sort the records in file offset order.
+
+4. If the extent records would fit in the inode fork immediate area,

commit the
+   records to that immediate area and skip to step 8.

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+
+5. Allocate the number of blocks computed in the previous step.
+
+6. Use ``xfs_btree_bload`` to write the xfarray records to btree

blocks and
+   generate the internal node blocks.

Documentation/filesystems/xfs-online-fsck-design.rst this functionality as follows: · line 2626

Quoted 4 lines
Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+
+7. Commit the new btree root block to the inode fork immediate area.
+
+8. Reap the old btree blocks using the bitmap created in step 1.

This description is not bad, but I had a hard time finding something that resembled the description in the link below. Maybe its in a different branch?

Quoted 16 lines
Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+
+There are some 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

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+EXTENTS format instead of BMBT, which may require a conversion.
+Third, the incore extent map must be reloaded carefully to avoid

disturbing

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+any delayed allocation extents.
+
+The proposed patchset is the
+`file repair
+<
Quoted 3 lines

https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/
log/?h=repair-inodes>`_
+series.

So I'm assuming links to kernel.org are acceptable as it looks like you use them here, but it does imply that they need to sort of live forever, or at least as long as any document that uses them?

Quoted 87 lines
Documentation/filesystems/xfs-online-fsck-design.rst +7 -0
+
+.. _reaping:
+
+Reaping Old Metadata Blocks
+---------------------------
+
+Whenever online fsck builds a new data structure to replace one that

is
+suspect, there is a question of how to find and dispose of the blocks that

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+belonged to the old structure.
+The laziest method of course is not to deal with them at all, but

this slowly

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+leads to service degradations as space leaks out of the filesystem.
+Hopefully, someone will schedule a rebuild of the free space

information to

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+plug all those leaks.
+Offline repair rebuilds all space metadata after recording the usage

of
+the files and directories that it decides not to clear, hence it can build new
+structures in the discovered free space and avoid the question of reaping.

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+As part of a repair, online fsck relies heavily on the reverse

mapping records
+to find space that is owned by the corresponding rmap owner yet truly free.
+Cross referencing rmap records with other rmap records is necessary because
+there may be other data structures that also think they own some of those

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+blocks (e.g. crosslinked trees).
+Permitting the block allocator to hand them out again will not push

the system

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+towards consistency.
+
+For space metadata, the process of finding extents to dispose of

generally

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+follows this format:
+
+1. Create a bitmap of space used by data structures that must be

preserved.
+   The space reservations used to create the new metadata can be used here if
+   the same rmap owner code is used to denote all of the objects being rebuilt.
+
+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 candidate extents that could be freed.
+   The process moves on to step 4 below.

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+Repairs for file-based metadata such as extended attributes,

directories,
+symbolic links, quota files and realtime bitmaps are performed by building a

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+new structure attached to a temporary file and swapping the forks.
+Afterward, the mappings in the old file fork are the candidate

blocks for

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+disposal.
+
+The process for disposing of old extents is as follows:
+
+4. For each candidate extent, 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.

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+
+   - 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.
+
+5. 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.
+
+6. If the region is crosslinked, delete the reverse mapping entry

Quoted 8 lines

for the
+   structure being repaired and move on to the next region. +
+7. If the region is to be freed, mark any corresponding buffers in the buffer
+   cache as stale to prevent log writeback.
+
+8. Free the region and move on.

I think this part is as straightforward as it can be. I like links, but they do have maintenance issues if the branch ever goes away. It may be worth it though just while the code is going through review, I think it really helps to be able to just jump right into the code its trying to describe rather than trying to track down based on the description.

https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/tree/fs/xfs/scrub/reap.c?h=repair-ag-btrees&id=d866f0e470b077806c994f4434bbe64e4a3a8662#n471:~:text=xrep_reap_ag_metadata(

I think that's the right one? Tiny links nice for when steps are buried in sub functions too

Quoted 60 lines
Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+
+However, there is one complication to this procedure.
+Transactions are of finite size, so the reaping process must be

careful to roll

Documentation/filesystems/xfs-online-fsck-design.rst +8 -0
+the transactions to avoid overruns.
+Overruns come from two sources:
+
+a. EFIs logged on behalf of space that is no longer occupied
+
+b. Log items for buffer invalidations
+
+This is also a window in which a crash during the reaping process

can leak

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+blocks.
+As stated earlier, online repair functions use very large

transactions to

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+minimize the chances of this occurring.
+
+The proposed patchset is the
+`preparation for bulk loading btrees
+<

https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/
log/?h=repair-prep-for-bulk-loading>`_

Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+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 the old btree blocks is quite simple,

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+conceptually:
+
+1. Lock the relevant AGI/AGF header buffers to prevent allocation

and frees.
+
+2. For each reverse mapping record with an rmap owner corresponding to the
+   metadata structure being rebuilt, set the corresponding range in a bitmap.

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+
+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)``
+   are the blocks that might be freeable.

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+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

Documentation/filesystems/xfs-online-fsck-design.rst this functionality as follows: · line 2755

Quoted 6 lines
Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+mapping record walk that creates the records for the new btree.
+
+Case Study: Rebuilding the Free Space Indices
+`````````````````````````````````````````````
+
+The high level process to rebuild the free space indices is:

Looks like this one
https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/commit/?h=repair-ag-btrees&id=bf5f10a91ca58d883ef1231a406fa0646c4c4e50#:~:text=%2B%20*/-,%2BSTATIC%20int,-%2Bxrep_abt_build_new_trees(

Quoted 12 lines

+
+1. Walk the reverse mapping records to generate ``struct xfs_alloc_rec_incore``
+   records from the gaps in the reverse mapping btree.

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+
+2. Append the records to an xfarray.
+
+3. Use the ``xfs_btree_bload_compute_geometry`` function to compute

the number
+   of blocks needed for each new tree.
+
+4. Allocate the number of blocks computed in the previous step from

Quoted 8 lines

the free
+   space information collected.
+
+5. Use ``xfs_btree_bload`` to write the xfarray records to btree blocks and
+   generate the internal node blocks for the free space by block index.
+   Call it again for the free space by length index.

nit: these two loads are flipped

Quoted 74 lines
Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+
+6. Commit the locations of the new btree root blocks to the AGF.
+
+7. Reap the old btree blocks by looking for space that is not

recorded by the
+   reverse mapping btree, the new free space btrees, or the AGFL.

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+Repairing the free space btrees has three key complications over a

regular

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+btree repair:
+
+First, 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

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+space component of the keyspace of the reverse mapping btree.
+
+Second, free space repairs cannot use the common btree reservation

code because

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+new blocks are reserved out of the free space btrees.
+This is 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

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+supply the blocks for the new free space btrees.
+It is not necessary to back each reserved extent with an EFI because

the new
+free space btrees are constructed in what the ondisk filesystem thinks is

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+unowned 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

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+reservation is sufficient.
+As part of committing the new btrees, repair must ensure that

reverse mappings
+are created for the reserved blocks and that unused reserved blocks are

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+inserted into the free space btrees.
+Deferrred rmap and freeing operations are used to ensure that this

transition

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+is atomic, similar to the other btree repair functions.
+
+Third, finding the blocks to reap after the repair is not overly
+straightforward.
+Blocks for the free space btrees and the reverse mapping btrees are

supplied by

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+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

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+btrees or the reverse mapping btrees.
+When repair walks reverse mapping records to synthesize free space

records, it

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+creates a bitmap (``ag_owner_bitmap``) of all the space claimed by
+``XFS_RMAP_OWN_AG`` records.
+The repair context maintains a second bitmap corresponding to the

rmap btree

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+blocks and the AGFL blocks (``rmap_agfl_bitmap``).
+When the walk is complete, the bitmap disunion operation

``(ag_owner_bitmap &
+~rmap_agfl_bitmap)`` computes the extents that are used by the old free space

Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+btrees.
+These blocks can then be reaped using the methods outlined above.
+
+The proposed patchset is the
+`AG btree repair
+<
Quoted 3 lines

https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/
log/?h=repair-ag-btrees>`_
+series.

I think we've repeated this link couple times in the doc. If you like highlight links, we cloud clean out the duplicates

Quoted 59 lines
Documentation/filesystems/xfs-online-fsck-design.rst +7 -0
+
+.. _rmap_reap:
+
+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

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+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
+:ref:live rebuilds of rmap data <rmap_repair>, but a crucial point from that
+discussion is that the new rmap btree will not contain any records for the old
+rmap btree, nor will the old btree blocks be tracked in the free space btrees.

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+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 and the current AGFL

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+blocks.
+The result ``(new_rmapbt_gaps & ~(agfl | bnobt_records))`` are

reaped using the

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+methods outlined above.
+
+The rest of the process of rebuildng the reverse mapping btree is

discussed

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+in a separate :ref:`case study<rmap_repair>`.
+
+The proposed patchset is the
+`AG btree repair
+<

https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/
log/?h=repair-ag-btrees>`_

Documentation/filesystems/xfs-online-fsck-design.rst +8 -0
+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.

Documentation/filesystems/xfs-online-fsck-design.rst this functionality as follows: · line 2870

Quoted 4 lines
Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+
+4. Once the AGFL is full, reap any blocks leftover.
+
+5. The next operation to fix the freelist will right-size the list.

Branch link? Looks like maybe it's missing. In fact this logic looks like it might have been cut off?

In any case, maybe give some thought to the highlight link suggestions.

Allison

#40 lore raw

Re: [PATCH 08/14] xfs: document btree bulk loading

Quoted 106 lines · Allison Henderson
Quoted 93 lines · Darrick J. Wong

From: Darrick J. Wong <[email protected]>

Add a discussion of the btree bulk loading code, which makes it easy to
take an in-memory recordset and write it out to disk in an efficient manner.  This also enables atomic switchover from the old to the new structure with minimal potential for leaking the old blocks.

---
 .../filesystems/xfs-online-fsck-design.rst         |  632
++++++++++++++++++++

 1 file changed, 632 insertions(+)
Documentation/filesystems/xfs-online-fsck-design.rst +0 -0
index 9d7a2ef1d0dd..eb61d867e55c 100644
@@ -2236,3 +2236,635 @@ this functionality as follows:


 After removing xfile logged buffers from the transaction in this manner, the
 transaction can be committed or cancelled.

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+
+Bulk Loading of Ondisk B+Trees
+------------------------------
+
+As mentioned previously, early iterations of online repair built new

btree
+structures by creating a new btree and adding observations 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, but was very slow and leaked

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+blocks if the system went down during a repair.
+Loading records one at a time also meant that repair could not

control the

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+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.
+This was implemented rather inefficiently code-wise, since ``xfs_repair``

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+had separate copy-pasted implementations for each btree type.
+
+To prepare for online fsck, each of the four bulk loaders were

studied, notes
+were taken, and the four were refactored into a single generic btree bulk

Documentation/filesystems/xfs-online-fsck-design.rst +7 -0
+loading mechanism.
+Those notes in turn have been refreshed and are presented below.
+
+Geometry Computation
+````````````````````
+
+The zeroth step of bulk loading is to assemble the entire record set

that will

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+be stored in the new btree, and sort the records.
+Next, call ``xfs_btree_bload_compute_geometry`` to compute the shape

of the
+btree from the record set, the type of btree, and any load factor preferences.

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+This information is required for resource reservation.
+
+First, the geometry computation computes the minimum and maximum

records that
+will fit in a leaf block from the size of a btree block and the size of the

Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+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,

Documentation/filesystems/xfs-online-fsck-design.rst +8 -0
+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

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+drop in performance immediately afterwards.
+The default loading factor was chosen to be 75% of maxrecs, which
Quoted 2 lines

provides a
+reasonably compact structure without any immediate split penalties.

	default_lload_factor = (maxrecs + minrecs) / 2;
Quoted 6 lines

+If space is tight, the loading factor will be set to maxrecs to try to avoid

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+running out of space::
+
+        leaf_load_factor = enough space ? (maxrecs + minrecs) / 2 :

maxrecs

leaf_load_factor = enough space ? default_lload_factor :
maxrecs;

Quoted 1 line

Just more readable i think

Ok, changed.

Quoted 10 lines

Documentation/filesystems/xfs-online-fsck-design.rst this functionality as follows: · line 2299

Quoted 8 lines
Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+Load factor is computed for btree node blocks using the combined

size of the

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+btree key and pointer as the record size::
+
+        maxrecs = (block_size - header_size) / (key_size + ptr_size)
+        minrecs = maxrecs / 2
	default_nload_factor = (maxrecs + minrecs) / 2;
Quoted 4 lines
Quoted 2 lines

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

node_load_factor = enough space ? default_nload_factor :
maxrecs;

Here too.

Quoted 130 lines
Quoted 124 lines
Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+Once that's done, the number of leaf blocks required to store the

record set

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+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

Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+is computed as::
+
+        n_blocks = (n == 0 ? leaf_blocks : node_blocks[n])
+        node_blocks[n + 1] = ceil(n_blocks / node_load_factor)
+
+The entire computation is performed recursively until the current

level only

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+needs one block.
+The resulting geometry is as follows:
+
+- For AG-rooted btrees, this level is the root level, so the height

of the new
+  tree is ``level + 1`` and the space needed is the summation of the number of
+  blocks on each level.
+
+- For inode-rooted btrees where the records in the top level do not fit in the
+  inode fork area, the height is ``level + 2``, the space needed is the
+  summation of the number of blocks on each level, and the inode fork points to
+  the root block.
+
+- For inode-rooted btrees where the records in the top level can be stored in
+  the inode fork area, then the root block can be stored in the inode, the
+  height is ``level + 1``, and the space needed is one less than the summation
+  of the number of blocks on each level.
+  This only becomes relevant when non-bmap btrees gain the ability to root in
+  an inode, which is a future patchset and only included here for completeness.

Documentation/filesystems/xfs-online-fsck-design.rst +7 -0
+
+.. _newbt:
+
+Reserving New B+Tree Blocks
+```````````````````````````
+
+Once repair knows the number of blocks needed for the new btree, it

allocates

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+those blocks using the free space information.
+Each reserved extent is tracked separately by the btree builder

state data.
+To improve crash resilience, the reservation code also logs an Extent Freeing
+Intent (EFI) item in the same transaction as each space allocation and attaches
+its in-memory ``struct xfs_extent_free_item`` object to the space reservation.
+If the system goes down, log recovery will use the unfinished EFIs to free the

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+unused space, the free space, leaving the filesystem unchanged.
+
+Each time the btree builder claims a block for the btree from a

reserved
+extent, it updates the in-memory reservation to reflect the claimed space.
+Block reservation tries to allocate as much contiguous space as possible to

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+reduce the number of EFIs in play.
+
+While repair is writing these new btree blocks, the EFIs created for

the space

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+reservations pin the tail of the ondisk log.
+It's possible that other parts of the system will remain busy and

push the head

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+of the log towards the pinned tail.
+To avoid livelocking the filesystem, the EFIs must not pin the tail

of the log

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+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

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+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.

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+EFIs have a role to play during the commit and reaping phases;

please see the
+next section and the section about :ref:reaping<reaping> for more details.

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+
+Proposed patchsets are the
+`bitmap rework
+<

https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/
log/?h=repair-bitmap-rework>`_
+and the
+`preparation for bulk loading btrees
+<
https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/
log/?h=repair-prep-for-bulk-loading>`_.

Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+
+
+Writing the New Tree
+````````````````````
+
+This part is pretty simple -- the btree builder

(``xfs_btree_bulkload``) claims
+a block from the reserved list, writes the new btree block header, fills the
+rest of the block with records, and adds the new leaf block to a list of

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+written blocks.
+Sibling pointers are set every time a new block is added to the

level.
+When it finishes writing the record leaf blocks, it moves on to the node

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+blocks.
+To fill a node block, it walks each block in the next level down in

the tree

Documentation/filesystems/xfs-online-fsck-design.rst this functionality as follows: · line 2386

Quoted 2 lines
Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+to compute the relevant keys and write them into the parent node.
+When it reaches the root level, it is ready to commit the new btree!

I think most of this is as straight forward as it can be, but it's a lot visualizing too, which makes me wonder if it would benefit from an simple illustration if possible.

Quoted 8 lines

On a side note: In a prior team I discovered power points, while a lot work, were also really effective for quickly moving a crowd of people through connected graph navigation/manipulations. Because each one of these steps was another slide that illustrated how the structure evolved through the updates. I realize that's not something that fits in the scheme of a document like this, but maybe something supplemental to add later.  While it was a time eater, i noticed a lot of confused expressions just seemed to shake loose, so sometimes it was worth it.

That was ... surprisingly less bad than I feared it would be to cut and paste unicode linedraw characters and arrows.

          ┌─────────┐
          │root     │
          │PP       │
          └─────────┘
          ↙         ↘
      ┌────┐       ┌────┐
      │node│──────→│node│
      │PP  │←──────│PP  │
      └────┘       └────┘
      ↙   ↘         ↙   ↘
  ┌────┐ ┌────┐ ┌────┐ ┌────┐
  │leaf│→│leaf│→│leaf│→│leaf│
  │RRR │←│RRR │←│RRR │←│RRR │
  └────┘ └────┘ └────┘ └────┘

(Does someone have a program that does this?)

Quoted 176 lines
Quoted 165 lines
Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+The first step to commit the new btree is to persist the btree

blocks to disk

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+synchronously.
+This is a little complicated because a new btree block could have

been freed
+in the recent past, so the builder must use ``xfs_buf_delwri_queue_here`` to
+remove the (stale) buffer from the AIL list before it can write the new blocks

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+to disk.
+Blocks are queued for IO using a delwri list and written in one

large batch

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+with ``xfs_buf_delwri_submit``.
+
+Once the new blocks have been persisted to disk, control returns to

the

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+individual repair function that called the bulk loader.
+The repair function must log the location of the new root in a

transaction,
+clean up the space reservations that were made for the new btree, and reap the

Documentation/filesystems/xfs-online-fsck-design.rst +7 -0
+old metadata blocks:
+
+1. Commit the location of the new btree root.
+
+2. For each incore reservation:
+
+   a. Log Extent Freeing Done (EFD) items for all the space that was

consumed
+      by the btree builder.  The new EFDs must point to the EFIs attached to
+      the reservation to prevent log recovery from freeing the new blocks.
+
+   b. For unclaimed portions of incore reservations, create a regular deferred
+      extent free work item to be free the unused space later in the +      transaction chain.
+
+   c. The EFDs and EFIs logged in steps 2a and 2b must not overrun the
+      reservation of the committing transaction.
+      If the btree loading code suspects this might be about to happen, it must
+      call ``xrep_defer_finish`` to clear out the deferred work and obtain a
+      fresh transaction.
+
+3. Clear out the deferred work a second time to finish the commit and clean
+   the repair transaction.

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+The transaction rolling in steps 2c and 3 represent a weakness in

the repair
+algorithm, because a log flush and a crash before the end of the reap step can

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+result in space leaking.
+Online repair functions minimize the chances of this occuring by

using very
+large transactions, which each can accomodate many thousands of block freeing

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+instructions.
+Repair moves on to reaping the old blocks, which will be presented

in a
+subsequent :ref:section<reaping> after a few case studies of bulk loading.

Documentation/filesystems/xfs-online-fsck-design.rst +7 -0
+
+Case Study: Rebuilding the Inode Index
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+The high level process to rebuild the inode index btree is:
+
+1. Walk the reverse mapping records to generate ``struct

xfs_inobt_rec``
+   records from the inode chunk information and a bitmap of the old inode btree
+   blocks.

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+
+2. Append the records to an xfarray in inode order.
+
+3. Use the ``xfs_btree_bload_compute_geometry`` function to compute

the number
+   of blocks needed for the inode btree.
+   If the free space inode btree is enabled, call it again to estimate the
+   geometry of the finobt.

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+
+4. Allocate the number of blocks computed in the previous step.
+
+5. Use ``xfs_btree_bload`` to write the xfarray records to btree

blocks and
+   generate the internal node blocks.
+   If the free space inode btree is enabled, call it again to load the finobt.

Documentation/filesystems/xfs-online-fsck-design.rst +8 -0
+
+6. Commit the location of the new btree root block(s) to the AGI.
+
+7. Reap the old btree blocks using the bitmap created in step 1.
+
+Details are as follows.
+
+The inode btree maps inumbers to the ondisk location of the

associated
+inode records, which means that the inode btrees can be rebuilt from the

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+reverse mapping information.
+Reverse mapping records with an owner of ``XFS_RMAP_OWN_INOBT``

marks the

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+location of the old inode btree blocks.
+Each reverse mapping record with an owner of ``XFS_RMAP_OWN_INODES``

marks the

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+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.

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+For the space represented by each inode cluster, 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

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+operation.
+Otherwise, read each cluster buffer to check that its contents

appear to be

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+ondisk inodes and to decide if the file is allocated
+(``xfs_dinode.i_mode != 0``) or free (``xfs_dinode.i_mode == 0``).
+Accumulate the results of successive inode cluster buffer reads

until there is
+enough information to fill a single inode chunk record, which is 64 consecutive

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+numbers in the inumber keyspace.
+If the chunk is sparse, the chunk record may include holes.
+
+Once the repair function accumulates one chunk's worth of data, it

calls
+``xfarray_append`` to add the inode btree record to the xfarray. +This xfarray is walked twice during the btree creation step -- once to populate
+the inode btree with all inode chunk records, and a second time to populate the
+free inode btree 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 inode chunk

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+records are stored in the xfarray.
+
+The proposed patchset is the
+`AG btree repair
+<

https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/
log/?h=repair-ag-btrees>`_

Documentation/filesystems/xfs-online-fsck-design.rst +8 -0
+series.
+
+Case Study: Rebuilding the Space Reference Counts
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+The high level process to rebuild the reference count btree is:
+
+1. Walk the reverse mapping records to generate ``struct
Quoted 6 lines

xfs_refcount_irec``
+   records for any space having more than one reverse mapping and add them to
+   the xfarray.
+   Any records owned by ``XFS_RMAP_OWN_COW`` are also added to the xfarray.

Any records owned by ``XFS_RMAP_OWN_COW`` are also added to the xfarray even if they only have one mapping

?

Quoted 7 lines

You haven't mentioned any owners being disallowed, you've only stated that you're collecting records with more than one rmap, so that would be the inferred meaning.

Also I think you also need to mention why. The documentation is starting to read a little more like pseudo code, but if it's not explaining why it's doing things, we may as well just go to the code

"Any records owned by ``XFS_RMAP_OWN_COW`` are also added to the xfarray because these are extents allocated to stage a copy on write operation and are tracked in the refcount btree."

Quoted 8 lines
Quoted 7 lines

+   Use any records owned by ``XFS_RMAP_OWN_REFC`` to create a bitmap of old
+   refcount btree blocks.
+
+2. Sort the records in physical extent order, putting the CoW staging extents
+   at the end of the xfarray.

Why?

"This matches the sorting order of records in the refcount btree."

Quoted 42 lines
Quoted 42 lines

+
+3. Use the ``xfs_btree_bload_compute_geometry`` function to compute the number
+   of blocks needed for the new tree.

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+
+4. Allocate the number of blocks computed in the previous step.
+
+5. Use ``xfs_btree_bload`` to write the xfarray records to btree

blocks and
+   generate the internal node blocks.

Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+
+6. Commit the location of new btree root block to the AGF.
+
+7. Reap the old btree blocks using the bitmap created in step 1.
+
+Details are as follows; the same algorithm is used by ``xfs_repair``

to

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+generate refcount information from reverse mapping records.
+
+Reverse mapping records are used to rebuild the reference count

information.
+Reference counts are required for correct operation of copy on write for shared

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+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

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+overlap each other.
+From the diagram below, it is apparent that a reference count record

must start

Documentation/filesystems/xfs-online-fsck-design.rst +11 -0
+or end 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
+
+The ondisk reference count btree does not store the refcount == 0
Quoted 8 lines
Quoted 5 lines

cases because

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+the free space btree already records which blocks are free.
+Extents being used to stage copy-on-write operations should be the

only records
+with refcount == 1.

So here you explain it... I think maybe the pseudo code would read easier if you put it after the high level explanations of what we're doing

Good point, I'll flip these two.

Quoted 53 lines
Quoted 15 lines

+Single-owner file blocks aren't recorded in either the free space or the

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+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``), reference count information is constructed from reverse mapping data

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+as follows:
+
+While there are still unprocessed mappings in the reverse mapping
Quoted 8 lines

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``.

Hmm, if this were code, I could tag the rm_startblock symbol, but that doesnt work for a document. While I could go look at the code to answer this, you want your document to explain the code, not the other way around... further commentary below...

Quoted 25 lines

+
+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).

Documentation/filesystems/xfs-online-fsck-design.rst +9 -0
+
+4. Record the bag size as ``old_bag_size``.
+
+5. While the bag isn't empty,
+
+   a. Remove from the bag all mappings where ``rm_startblock`` +
+      ``rm_blockcount`` == ``np``.
+
+   b. Add to the bag all reverse mappings where ``rm_startblock`` ==

``np``.
+
+   c. If the bag size isn't ``old_bag_size``, store the refcount record
+      ``(sp, np - sp, old_bag_size)`` in the refcount xfarray.

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+
+   d. If the bag is empty, break out of this inner loop.
+
+   e. Set ``old_bag_size`` to ``bag_size``.
+
Quoted 8 lines
Quoted 5 lines

+   f. Set ``sp`` = ``np``.
+
+   g. Set ``np`` to the physical block where the bag size will change.
+      Go to step 3 above.

I don't think verbalizing literal lines of code is any more explanatory than the code. I think it's easier just give the high level description and then just go look at it.

Agreed.... (see below)

Quoted 4 lines

I notice you have the exact same verbiage in the code, you could just link it:
https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/commit/?h=repair-ag-btrees&id=771fa17dd5fd7d3d125c61232c4390e8f7ac0fb0#:~:text=*%20While%20there%20are%20still%20unprocessed%20rmaps%20in%20the%20array,and%20(startblock%20%2B%20len%20of%20each%20rmap%20in%20the%20bag)
.

Eventually (aka once we merge this in the kernel) I intend to replace *all* of these patchset links and whatnot with references to the actual
source code in the git repo. I can't make those links at this time
because the design document is first in line ahead of the actual code.

Quoted 32 lines

Also that may cut down on future maintenance if this ever changes since people might not think to update the document along with the code

Hmm, just thinking outside the box, what do you think of this method of presentation:

- Iterate over btree
records tinyurl.com/4mp3j3pw
- Find the corresponding reverse
mapping tinyurl.com/27n7h5fa
- Collect all shared mappings with the same starting
block tinyurl.com/mwdfy52b
- Advance to the next block with a ref count
change tinyurl.com/28689ufz
This position will either be the next unprocessed rmap, or the combined length all the collected mappings, which ever is
smaller
- Iterate over the collected
mappings, tinyurl.com/ye673rwa
- Remove all mappings that start after this
position tinyurl.com/22yp7p6u
- Re-collect all mappings that start on this
position tinyurl.com/2p8vytmv
- If the size of the collection increased, update the ref
count tinyurl.com/ecu7tud7
- If more mappings were found, advance to the next block
with tinyurl.com/47p4dfac
a ref count change. Continue until no more mappings are
found

Quoted 5 lines

It pulls the pseudo code up to a little higher level, plus the quick links to jump deeper if needed and then people have all the navigation utilities they are used to. I just found a quick url shortener, so I'm not really sure how long they keep those, but maybe we can find an appropriate shorter

I really like your version! Can I tweak it a bit?

- Until the reverse mapping btree runs out of records:

- Retrieve the next record from the btree and put it in a bag.

- Collect all records with the same starting block from the btree and put them in the bag.

- While the bag isn't empty:

- Among the mappings in the bag, compute the lowest block number where the reference count changes.
This position will be either the starting block number of the next unprocessed reverse mapping or the next block after the shortest mapping in the bag.

- Remove all mappings from the bag that end at this position.

- Collect all reverse mappings that start at this position from the btree and put them in the bag.

- If the size of the bag changed and is greater than one, create a new refcount record associating the block number range that we just walked to the size of the bag.

Quoted 43 lines
Quoted 43 lines
Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+The bag-like structure in this case is a type 2 xfarray as discussed

in the
+:ref:xfarray access patterns<xfarray_access_patterns> section. +Reverse mappings are added to the bag using ``xfarray_store_anywhere`` and

Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+removed via ``xfarray_unset``.
+Bag members are examined through ``xfarray_iter`` loops.
+
+The proposed patchset is the
+`AG btree repair
+<

https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/
log/?h=repair-ag-btrees>`_

Documentation/filesystems/xfs-online-fsck-design.rst +8 -0
+series.
+
+Case Study: Rebuilding File Fork Mapping Indices
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+The high level process to rebuild a data/attr fork mapping btree is:
+
+1. Walk the reverse mapping records to generate ``struct

xfs_bmbt_rec``
+   records from the reverse mapping records for that inode and fork. +   Append these records to an xfarray.
+   Compute the bitmap of the old bmap btree blocks from the ``BMBT_BLOCK``
+   records.
+
+2. Use the ``xfs_btree_bload_compute_geometry`` function to compute the number
+   of blocks needed for the new tree.

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+
+3. Sort the records in file offset order.
+
+4. If the extent records would fit in the inode fork immediate area,

commit the
+   records to that immediate area and skip to step 8.

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+
+5. Allocate the number of blocks computed in the previous step.
+
+6. Use ``xfs_btree_bload`` to write the xfarray records to btree

blocks and

Quoted 8 lines

Documentation/filesystems/xfs-online-fsck-design.rst this functionality as follows: · line 2626

Quoted 5 lines

+   generate the internal node blocks.

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+
+7. Commit the new btree root block to the inode fork immediate area.
+
+8. Reap the old btree blocks using the bitmap created in step 1.

This description is not bad, but I had a hard time finding something that resembled the description in the link below. Maybe its in a different branch?

Oops, sorry, that url should be:
https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/log/?h=repair-file-mappings

Quoted 14 lines
Quoted 14 lines
Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+
+There are some 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

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+EXTENTS format instead of BMBT, which may require a conversion.
+Third, the incore extent map must be reloaded carefully to avoid

disturbing

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+any delayed allocation extents.
+
+The proposed patchset is the
Quoted 8 lines
Quoted 5 lines

+`file repair
+<
https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/
log/?h=repair-inodes>`_
+series.

So I'm assuming links to kernel.org are acceptable as it looks like you use them here, but it does imply that they need to sort of live forever, or at least as long as any document that uses them?

After all this gets merged I'll replace them with links to fs/xfs/scrub/bmap_repair.c.

Quoted 102 lines
Quoted 87 lines
Documentation/filesystems/xfs-online-fsck-design.rst +7 -0
+
+.. _reaping:
+
+Reaping Old Metadata Blocks
+---------------------------
+
+Whenever online fsck builds a new data structure to replace one that

is
+suspect, there is a question of how to find and dispose of the blocks that

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+belonged to the old structure.
+The laziest method of course is not to deal with them at all, but

this slowly

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+leads to service degradations as space leaks out of the filesystem.
+Hopefully, someone will schedule a rebuild of the free space

information to

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+plug all those leaks.
+Offline repair rebuilds all space metadata after recording the usage

of
+the files and directories that it decides not to clear, hence it can build new
+structures in the discovered free space and avoid the question of reaping.

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+As part of a repair, online fsck relies heavily on the reverse

mapping records
+to find space that is owned by the corresponding rmap owner yet truly free.
+Cross referencing rmap records with other rmap records is necessary because
+there may be other data structures that also think they own some of those

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+blocks (e.g. crosslinked trees).
+Permitting the block allocator to hand them out again will not push

the system

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+towards consistency.
+
+For space metadata, the process of finding extents to dispose of

generally

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+follows this format:
+
+1. Create a bitmap of space used by data structures that must be

preserved.
+   The space reservations used to create the new metadata can be used here if
+   the same rmap owner code is used to denote all of the objects being rebuilt.
+
+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 candidate extents that could be freed.
+   The process moves on to step 4 below.

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+Repairs for file-based metadata such as extended attributes,

directories,
+symbolic links, quota files and realtime bitmaps are performed by building a

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+new structure attached to a temporary file and swapping the forks.
+Afterward, the mappings in the old file fork are the candidate

blocks for

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+disposal.
+
+The process for disposing of old extents is as follows:
+
+4. For each candidate extent, 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.

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+
+   - 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.
+
+5. 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.
+
+6. If the region is crosslinked, delete the reverse mapping entry

Quoted 8 lines

for the
+   structure being repaired and move on to the next region. +
+7. If the region is to be freed, mark any corresponding buffers in the buffer
+   cache as stale to prevent log writeback.
+
+8. Free the region and move on.

I think this part is as straightforward as it can be. I like links, but they do have maintenance issues if the branch ever goes away. It may be worth it though just while the code is going through review, I think it really helps to be able to just jump right into the code its trying to describe rather than trying to track down based on the description.

Quoted 4 lines

https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/tree/fs/xfs/scrub/reap.c?h=repair-ag-btrees&id=d866f0e470b077806c994f4434bbe64e4a3a8662#n471:~:text=xrep_reap_ag_metadata(

I think that's the right one? Tiny links nice for when steps are buried in sub functions too

Maybe? That didn't actually move to line 471 or highlight anything.

Quoted 82 lines
Quoted 60 lines
Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+
+However, there is one complication to this procedure.
+Transactions are of finite size, so the reaping process must be

careful to roll

Documentation/filesystems/xfs-online-fsck-design.rst +8 -0
+the transactions to avoid overruns.
+Overruns come from two sources:
+
+a. EFIs logged on behalf of space that is no longer occupied
+
+b. Log items for buffer invalidations
+
+This is also a window in which a crash during the reaping process

can leak

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+blocks.
+As stated earlier, online repair functions use very large

transactions to

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+minimize the chances of this occurring.
+
+The proposed patchset is the
+`preparation for bulk loading btrees
+<

https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/
log/?h=repair-prep-for-bulk-loading>`_

Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+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 the old btree blocks is quite simple,

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+conceptually:
+
+1. Lock the relevant AGI/AGF header buffers to prevent allocation

and frees.
+
+2. For each reverse mapping record with an rmap owner corresponding to the
+   metadata structure being rebuilt, set the corresponding range in a bitmap.

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+
+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)``
+   are the blocks that might be freeable.

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+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

Documentation/filesystems/xfs-online-fsck-design.rst this functionality as follows: · line 2755

Quoted 6 lines
Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+mapping record walk that creates the records for the new btree.
+
+Case Study: Rebuilding the Free Space Indices
+`````````````````````````````````````````````
+
+The high level process to rebuild the free space indices is:

Looks like this one
https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/commit/?h=repair-ag-btrees&id=bf5f10a91ca58d883ef1231a406fa0646c4c4e50#:~:text=%2B%20*/-,%2BSTATIC%20int,-%2Bxrep_abt_build_new_trees(

Quoted 13 lines

+
+1. Walk the reverse mapping records to generate ``struct xfs_alloc_rec_incore``
+   records from the gaps in the reverse mapping btree.

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+
+2. Append the records to an xfarray.
+
+3. Use the ``xfs_btree_bload_compute_geometry`` function to compute

the number
+   of blocks needed for each new tree.
+
+4. Allocate the number of blocks computed in the previous step from the free

Quoted 8 lines
Quoted 7 lines

+   space information collected.
+
+5. Use ``xfs_btree_bload`` to write the xfarray records to btree blocks and
+   generate the internal node blocks for the free space by block index.
+   Call it again for the free space by length index.

nit: these two loads are flipped

Oops, fixed.

Quoted 137 lines
Quoted 74 lines
Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+
+6. Commit the locations of the new btree root blocks to the AGF.
+
+7. Reap the old btree blocks by looking for space that is not

recorded by the
+   reverse mapping btree, the new free space btrees, or the AGFL.

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+Repairing the free space btrees has three key complications over a

regular

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+btree repair:
+
+First, 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

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+space component of the keyspace of the reverse mapping btree.
+
+Second, free space repairs cannot use the common btree reservation

code because

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+new blocks are reserved out of the free space btrees.
+This is 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

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+supply the blocks for the new free space btrees.
+It is not necessary to back each reserved extent with an EFI because

the new
+free space btrees are constructed in what the ondisk filesystem thinks is

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+unowned 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

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+reservation is sufficient.
+As part of committing the new btrees, repair must ensure that

reverse mappings
+are created for the reserved blocks and that unused reserved blocks are

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+inserted into the free space btrees.
+Deferrred rmap and freeing operations are used to ensure that this

transition

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+is atomic, similar to the other btree repair functions.
+
+Third, finding the blocks to reap after the repair is not overly
+straightforward.
+Blocks for the free space btrees and the reverse mapping btrees are

supplied by

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+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

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+btrees or the reverse mapping btrees.
+When repair walks reverse mapping records to synthesize free space

records, it

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+creates a bitmap (``ag_owner_bitmap``) of all the space claimed by
+``XFS_RMAP_OWN_AG`` records.
+The repair context maintains a second bitmap corresponding to the

rmap btree

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+blocks and the AGFL blocks (``rmap_agfl_bitmap``).
+When the walk is complete, the bitmap disunion operation

``(ag_owner_bitmap &
+~rmap_agfl_bitmap)`` computes the extents that are used by the old free space

Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+btrees.
+These blocks can then be reaped using the methods outlined above.
+
+The proposed patchset is the
+`AG btree repair
+<
Quoted 3 lines

https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/
log/?h=repair-ag-btrees>`_
+series.

I think we've repeated this link couple times in the doc. If you like highlight links, we cloud clean out the duplicates

Quoted 57 lines
Documentation/filesystems/xfs-online-fsck-design.rst +7 -0
+
+.. _rmap_reap:
+
+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

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+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
+:ref:live rebuilds of rmap data <rmap_repair>, but a crucial point from that
+discussion is that the new rmap btree will not contain any records for the old
+rmap btree, nor will the old btree blocks be tracked in the free space btrees.

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+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 and the current AGFL

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+blocks.
+The result ``(new_rmapbt_gaps & ~(agfl | bnobt_records))`` are

reaped using the

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+methods outlined above.
+
+The rest of the process of rebuildng the reverse mapping btree is

discussed

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+in a separate :ref:`case study<rmap_repair>`.
+
+The proposed patchset is the
+`AG btree repair
+<

https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/
log/?h=repair-ag-btrees>`_

Documentation/filesystems/xfs-online-fsck-design.rst +8 -0
+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

Quoted 8 lines

Documentation/filesystems/xfs-online-fsck-design.rst this functionality as follows: · line 2870

Quoted 6 lines

+   other owner, to avoid re-adding crosslinked blocks to the AGFL.

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+
+4. Once the AGFL is full, reap any blocks leftover.
+
+5. The next operation to fix the freelist will right-size the list.

Branch link? Looks like maybe it's missing. In fact this logic looks like it might have been cut off?

OH, heh. I forgot that we already merged the AGFL repair code.

"See `fs/xfs/scrub/agheader_repair.c
<https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/fs/xfs/scrub/agheader_repair.c>`_
for more details."

Quoted 1 line

In any case, maybe give some thought to the highlight link suggestions.

Er... how do those work? In principle I like them, but none of your links actually highlighted anything here. Could you send the link over IRC so that urldefense crapola won't destroy it, please?

--D

Quoted 2 lines

Allison

#41 lore raw

Re: [PATCH 08/14] xfs: document btree bulk loading

Quoted 343 lines · Darrick J. Wong
Quoted 125 lines · Allison Henderson
Quoted 108 lines · Darrick J. Wong

From: Darrick J. Wong <[email protected]>

Add a discussion of the btree bulk loading code, which makes it easy
to
take an in-memory recordset and write it out to disk in an efficient
manner.  This also enables atomic switchover from the old to the new
structure with minimal potential for leaking the old blocks.

---
 .../filesystems/xfs-online-fsck-design.rst         |  632
++++++++++++++++++++

 1 file changed, 632 insertions(+)
Documentation/filesystems/xfs-online-fsck-design.rst +0 -0
index 9d7a2ef1d0dd..eb61d867e55c 100644
@@ -2236,3 +2236,635 @@ this functionality as follows:


 After removing xfile logged buffers from the transaction in this manner, the
 transaction can be committed or cancelled.

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+
+Bulk Loading of Ondisk B+Trees
+------------------------------
+
+As mentioned previously, early iterations of online repair built

new
btree
+structures by creating a new btree and adding observations 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, but was very slow
and leaked

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+blocks if the system went down during a repair.
+Loading records one at a time also meant that repair could not

control the

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+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.
+This was implemented rather inefficiently code-wise, since ``xfs_repair``

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+had separate copy-pasted implementations for each btree type.
+
+To prepare for online fsck, each of the four bulk loaders were

studied, notes
+were taken, and the four were refactored into a single generic btree
bulk

Documentation/filesystems/xfs-online-fsck-design.rst +7 -0
+loading mechanism.
+Those notes in turn have been refreshed and are presented below.
+
+Geometry Computation
+````````````````````
+
+The zeroth step of bulk loading is to assemble the entire record

set
that will

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+be stored in the new btree, and sort the records.
+Next, call ``xfs_btree_bload_compute_geometry`` to compute the

shape
of the
+btree from the record set, the type of btree, and any load factor
preferences.

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+This information is required for resource reservation.
+
+First, the geometry computation computes the minimum and maximum

records that
+will fit in a leaf block from the size of a btree block and the size
of the

Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+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,

Documentation/filesystems/xfs-online-fsck-design.rst +7 -0
+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

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+drop in performance immediately afterwards.
+The default loading factor was chosen to be 75% of maxrecs,
Quoted 4 lines

which
provides a
+reasonably compact structure without any immediate split penalties.

        default_lload_factor = (maxrecs + minrecs) / 2;

Quoted 8 lines

+If space is tight, the loading factor will be set to maxrecs to try
to avoid

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+running out of space::
+
+        leaf_load_factor = enough space ? (maxrecs + minrecs) /

2 :
maxrecs

        leaf_load_factor = enough space ? default_lload_factor :
maxrecs;

Quoted 1 line

Just more readable i think

Ok, changed.

Quoted 11 lines
Quoted 9 lines
Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+Load factor is computed for btree node blocks using the combined

size of the

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+btree key and pointer as the record size::
+
+        maxrecs = (block_size - header_size) / (key_size +

ptr_size)
+        minrecs = maxrecs / 2

        default_nload_factor = (maxrecs + minrecs) / 2;

Quoted 5 lines
Quoted 3 lines

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

        node_load_factor = enough space ? default_nload_factor :
maxrecs;

Here too.

Quoted 159 lines
Quoted 147 lines
Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+Once that's done, the number of leaf blocks required to store

the
record set

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+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

Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+is computed as::
+
+        n_blocks = (n == 0 ? leaf_blocks : node_blocks[n])
+        node_blocks[n + 1] = ceil(n_blocks / node_load_factor)
+
+The entire computation is performed recursively until the

current
level only

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+needs one block.
+The resulting geometry is as follows:
+
+- For AG-rooted btrees, this level is the root level, so the

height
of the new
+  tree is ``level + 1`` and the space needed is the summation of the
number of
+  blocks on each level.
+
+- For inode-rooted btrees where the records in the top level do not
fit in the
+  inode fork area, the height is ``level + 2``, the space needed is
the
+  summation of the number of blocks on each level, and the inode fork points to
+  the root block.
+
+- For inode-rooted btrees where the records in the top level can be
stored in
+  the inode fork area, then the root block can be stored in the inode, the
+  height is ``level + 1``, and the space needed is one less than the
summation
+  of the number of blocks on each level.
+  This only becomes relevant when non-bmap btrees gain the ability
to root in
+  an inode, which is a future patchset and only included here for
completeness.

Documentation/filesystems/xfs-online-fsck-design.rst +7 -0
+
+.. _newbt:
+
+Reserving New B+Tree Blocks
+```````````````````````````
+
+Once repair knows the number of blocks needed for the new btree,

it
allocates

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+those blocks using the free space information.
+Each reserved extent is tracked separately by the btree builder

state data.
+To improve crash resilience, the reservation code also logs an Extent Freeing
+Intent (EFI) item in the same transaction as each space allocation
and attaches
+its in-memory ``struct xfs_extent_free_item`` object to the space
reservation.
+If the system goes down, log recovery will use the unfinished EFIs
to free the

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+unused space, the free space, leaving the filesystem unchanged.
+
+Each time the btree builder claims a block for the btree from a

reserved
+extent, it updates the in-memory reservation to reflect the claimed
space.
+Block reservation tries to allocate as much contiguous space as possible to

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+reduce the number of EFIs in play.
+
+While repair is writing these new btree blocks, the EFIs created

for
the space

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+reservations pin the tail of the ondisk log.
+It's possible that other parts of the system will remain busy

and
push the head

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+of the log towards the pinned tail.
+To avoid livelocking the filesystem, the EFIs must not pin the

tail
of the log

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+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

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+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.

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+EFIs have a role to play during the commit and reaping phases;

please see the
+next section and the section about :ref:reaping<reaping> for more
details.

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+
+Proposed patchsets are the
+`bitmap rework
+<

https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/
log/?h=repair-bitmap-rework>`_
+and the
+`preparation for bulk loading btrees
+<
https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/
log/?h=repair-prep-for-bulk-loading>`_.

Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+
+
+Writing the New Tree
+````````````````````
+
+This part is pretty simple -- the btree builder

(``xfs_btree_bulkload``) claims
+a block from the reserved list, writes the new btree block header,
fills the
+rest of the block with records, and adds the new leaf block to a list of

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+written blocks.
+Sibling pointers are set every time a new block is added to the

level.
+When it finishes writing the record leaf blocks, it moves on to the
node

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+blocks.
+To fill a node block, it walks each block in the next level down
Quoted 6 lines

in
the tree
+to compute the relevant keys and write them into the parent node.
+When it reaches the root level, it is ready to commit the new btree!

I think most of this is as straight forward as it can be, but it's a
lot visualizing too, which makes me wonder if it would benefit from an
simple illustration if possible.

Quoted 15 lines

On a side note: In a prior team I discovered power points, while a lot
work, were also really effective for quickly moving a crowd of people
through connected graph navigation/manipulations.  Because each one of
these steps was another slide that illustrated how the structure evolved through the updates.  I realize that's not something that fits
in the scheme of a document like this, but maybe something supplemental
to add later.  While it was a time eater, i noticed a lot of confused
expressions just seemed to shake loose, so sometimes it was worth it.

That was ... surprisingly less bad than I feared it would be to cut and
paste unicode linedraw characters and arrows.

          ┌─────────┐
          │root     │
          │PP       │
          └─────────┘
          ↙         ↘
      ┌────┐       ┌────┐
      │node│──────→│node│
      │PP  │←──────│PP  │
      └────┘       └────┘
      ↙   ↘         ↙   ↘
  ┌────┐ ┌────┐ ┌────┐ ┌────┐
  │leaf│→│leaf│→│leaf│→│leaf│
  │RRR │←│RRR │←│RRR │←│RRR │
  └────┘ └────┘ └────┘ └────┘
Quoted 1 line

(Does someone have a program that does this?)

I think Catherine mentioned she had used PlantUML for the larp diagram, though for something this simple I think this is fine

Quoted 460 lines
Quoted 217 lines
Quoted 197 lines
Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+The first step to commit the new btree is to persist the btree

blocks to disk

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+synchronously.
+This is a little complicated because a new btree block could

have
been freed
+in the recent past, so the builder must use ``xfs_buf_delwri_queue_here`` to
+remove the (stale) buffer from the AIL list before it can write the
new blocks

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+to disk.
+Blocks are queued for IO using a delwri list and written in one

large batch

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+with ``xfs_buf_delwri_submit``.
+
+Once the new blocks have been persisted to disk, control returns

to
the

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+individual repair function that called the bulk loader.
+The repair function must log the location of the new root in a

transaction,
+clean up the space reservations that were made for the new btree,
and reap the

Documentation/filesystems/xfs-online-fsck-design.rst +7 -0
+old metadata blocks:
+
+1. Commit the location of the new btree root.
+
+2. For each incore reservation:
+
+   a. Log Extent Freeing Done (EFD) items for all the space that

was
consumed
+      by the btree builder.  The new EFDs must point to the EFIs attached to
+      the reservation to prevent log recovery from freeing the new
blocks.
+
+   b. For unclaimed portions of incore reservations, create a regular deferred
+      extent free work item to be free the unused space later in the
+      transaction chain.
+
+   c. The EFDs and EFIs logged in steps 2a and 2b must not overrun
the
+      reservation of the committing transaction.
+      If the btree loading code suspects this might be about to happen, it must
+      call ``xrep_defer_finish`` to clear out the deferred work and
obtain a
+      fresh transaction.
+
+3. Clear out the deferred work a second time to finish the commit
and clean
+   the repair transaction.

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+The transaction rolling in steps 2c and 3 represent a weakness

in
the repair
+algorithm, because a log flush and a crash before the end of the reap step can

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+result in space leaking.
+Online repair functions minimize the chances of this occuring by

using very
+large transactions, which each can accomodate many thousands of block freeing

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+instructions.
+Repair moves on to reaping the old blocks, which will be

presented
in a
+subsequent :ref:section<reaping> after a few case studies of bulk
loading.

Documentation/filesystems/xfs-online-fsck-design.rst +7 -0
+
+Case Study: Rebuilding the Inode Index
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+The high level process to rebuild the inode index btree is:
+
+1. Walk the reverse mapping records to generate ``struct

xfs_inobt_rec``
+   records from the inode chunk information and a bitmap of the old
inode btree
+   blocks.

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+
+2. Append the records to an xfarray in inode order.
+
+3. Use the ``xfs_btree_bload_compute_geometry`` function to

compute
the number
+   of blocks needed for the inode btree.
+   If the free space inode btree is enabled, call it again to estimate the
+   geometry of the finobt.

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+
+4. Allocate the number of blocks computed in the previous step.
+
+5. Use ``xfs_btree_bload`` to write the xfarray records to btree

blocks and
+   generate the internal node blocks.
+   If the free space inode btree is enabled, call it again to load
the finobt.
+
+6. Commit the location of the new btree root block(s) to the AGI.

Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+
+7. Reap the old btree blocks using the bitmap created in step 1.
+
+Details are as follows.
+
+The inode btree maps inumbers to the ondisk location of the

associated
+inode records, which means that the inode btrees can be rebuilt from
the

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+reverse mapping information.
+Reverse mapping records with an owner of ``XFS_RMAP_OWN_INOBT``

marks the

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+location of the old inode btree blocks.
+Each reverse mapping record with an owner of

``XFS_RMAP_OWN_INODES``
marks the

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+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.

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+For the space represented by each inode cluster, 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

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+operation.
+Otherwise, read each cluster buffer to check that its contents

appear to be

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+ondisk inodes and to decide if the file is allocated
+(``xfs_dinode.i_mode != 0``) or free (``xfs_dinode.i_mode ==

0``).
+Accumulate the results of successive inode cluster buffer reads until there is
+enough information to fill a single inode chunk record, which is 64
consecutive

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+numbers in the inumber keyspace.
+If the chunk is sparse, the chunk record may include holes.
+
+Once the repair function accumulates one chunk's worth of data,

it
calls
+``xfarray_append`` to add the inode btree record to the xfarray. +This xfarray is walked twice during the btree creation step -- once
to populate
+the inode btree with all inode chunk records, and a second time to
populate the
+free inode btree 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
inode chunk

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+records are stored in the xfarray.
+
+The proposed patchset is the
+`AG btree repair
+<

https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/
log/?h=repair-ag-btrees>`_

Documentation/filesystems/xfs-online-fsck-design.rst +8 -0
+series.
+
+Case Study: Rebuilding the Space Reference Counts
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+The high level process to rebuild the reference count btree is:
+
+1. Walk the reverse mapping records to generate ``struct
Quoted 8 lines

xfs_refcount_irec``
+   records for any space having more than one reverse mapping and
add them to
+   the xfarray.
+   Any records owned by ``XFS_RMAP_OWN_COW`` are also added to the
xfarray.

Any records owned by ``XFS_RMAP_OWN_COW`` are also added to the xfarray
even if they only have one mapping

?

You haven't mentioned any owners being disallowed, you've only stated
that you're collecting records with more than one rmap, so that would
be the inferred meaning.

Quoted 4 lines

Also I think you also need to mention why.  The documentation is starting to read a little more like pseudo code, but if it's not explaining why it's doing things, we may as well just go to the code

"Any records owned by ``XFS_RMAP_OWN_COW`` are also added to the xfarray
because these are extents allocated to stage a copy on write operation
and are tracked in the refcount btree."

Quoted 9 lines
Quoted 8 lines

+   Use any records owned by ``XFS_RMAP_OWN_REFC`` to create a bitmap
of old
+   refcount btree blocks.
+
+2. Sort the records in physical extent order, putting the CoW staging extents
+   at the end of the xfarray.

Why?

"This matches the sorting order of records in the refcount btree."

Quoted 51 lines
Quoted 51 lines

+
+3. Use the ``xfs_btree_bload_compute_geometry`` function to compute
the number
+   of blocks needed for the new tree.

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+
+4. Allocate the number of blocks computed in the previous step.
+
+5. Use ``xfs_btree_bload`` to write the xfarray records to btree

blocks and
+   generate the internal node blocks.

Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+
+6. Commit the location of new btree root block to the AGF.
+
+7. Reap the old btree blocks using the bitmap created in step 1.
+
+Details are as follows; the same algorithm is used by

``xfs_repair``
to

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+generate refcount information from reverse mapping records.
+
+Reverse mapping records are used to rebuild the reference count

information.
+Reference counts are required for correct operation of copy on write
for shared

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+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

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+overlap each other.
+From the diagram below, it is apparent that a reference count

record
must start

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+or end wherever the height of the stack changes.
+In other words, the record emission stimulus is level-

triggered::

Documentation/filesystems/xfs-online-fsck-design.rst +9 -0
+
+                        █    ███
+              ██      █████ ████   ███        ██████
+        ██   ████     ███████████ ████     █████████
+        ████████████████████████████████ ███████████
+        ^ ^  ^^ ^^    ^ ^^ ^^^  ^^^^  ^ ^^ ^  ^     ^
+        2 1  23 21    3 43 234  2123  1 01 2  3     0
+
+The ondisk reference count btree does not store the refcount ==

0
cases because
+the free space btree already records which blocks are free.

Quoted 8 lines
Quoted 4 lines

+Extents being used to stage copy-on-write operations should be the
only records
+with refcount == 1.

So here you explain it... I think maybe the pseudo code would read easier if you put it after the high level explanations of what we're
doing

Good point, I'll flip these two.

Quoted 65 lines
Quoted 20 lines

+Single-owner file blocks aren't recorded in either the free space or
the

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+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``), reference count information is constructed from reverse
mapping data

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+as follows:
+
+While there are still unprocessed mappings in the reverse

mapping
btree:
+

Quoted 8 lines

+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``.

Hmm, if this were code, I could tag the rm_startblock symbol, but that
doesnt work for a document.  While I could go look at the code to answer this, you want your document to explain the code, not the other
way around... further commentary below...

Quoted 30 lines

+
+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).

Documentation/filesystems/xfs-online-fsck-design.rst +9 -0
+
+4. Record the bag size as ``old_bag_size``.
+
+5. While the bag isn't empty,
+
+   a. Remove from the bag all mappings where ``rm_startblock`` +
+      ``rm_blockcount`` == ``np``.
+
+   b. Add to the bag all reverse mappings where

``rm_startblock`` ==
``np``.
+
+   c. If the bag size isn't ``old_bag_size``, store the refcount record
+      ``(sp, np - sp, old_bag_size)`` in the refcount xfarray.

Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+
+   d. If the bag is empty, break out of this inner loop.
+
+   e. Set ``old_bag_size`` to ``bag_size``.
+
+   f. Set ``sp`` = ``np``.
Quoted 8 lines
Quoted 4 lines

+
+   g. Set ``np`` to the physical block where the bag size will change.
+      Go to step 3 above.

I don't think verbalizing literal lines of code is any more explanatory
than the code.  I think it's easier just give the high level description and then just go look at it.

Agreed.... (see below)

Quoted 5 lines

I notice you have the exact same verbiage in the code, you could just
link it:
https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/commit/?h=repair-ag-btrees&id=771fa17dd5fd7d3d125c61232c4390e8f7ac0fb0#:~:text=*%20While%20there%20are%20still%20unprocessed%20rmaps%20in%20the%20array,and%20(startblock%20%2B%20len%20of%20each%20rmap%20in%20the%20bag)
.

Eventually (aka once we merge this in the kernel) I intend to replace *all* of these patchset links and whatnot with references to the actual
source code in the git repo.   I can't make those links at this time because the design document is first in line ahead of the actual code.

Quoted 38 lines

Also that may cut down on future maintenance if this ever changes since
people might not think to update the document along with the code

Hmm, just thinking outside the box, what do you think of this method of
presentation:

  - Iterate over btree
records                                                 tinyurl.com /4mp3j3pw
     - Find the corresponding reverse
mapping                                 tinyurl.com/27n7h5fa
     - Collect all shared mappings with the same starting block                   tinyurl.com/mwdfy52b
     - Advance to the next block with a ref count
change                  tinyurl.com/28689ufz

       This position will either be the next unprocessed rmap, or the
       combined length all the collected mappings, which ever is smaller
     - Iterate over the collected
mappings,                                       tinyurl.com/ye673rw a
        - Remove all mappings that start after this position                        tinyurl.com/22yp7p6u
        - Re-collect all mappings that start on this position                        tinyurl.com/2p8vytmv
        - If the size of the collection increased, update the ref count           tinyurl.com/ecu7tud7
        - If more mappings were found, advance to the next block with            tinyurl.com/47p4dfac
          a ref count change.  Continue until no more mappings are found

Quoted 8 lines

It pulls the pseudo code up to a little higher level, plus the quick
links to jump deeper if needed and then people have all the navigation
utilities they are used to.  I just found a quick url shortener, so I'm
not really sure how long they keep those, but maybe we can find an appropriate shorter

I really like your version!  Can I tweak it a bit?

- Until the reverse mapping btree runs out of records:

  - Retrieve the next record from the btree and put it in a bag.

  - Collect all records with the same starting block from the btree and
    put them in the bag.

  - While the bag isn't empty:

    - Among the mappings in the bag, compute the lowest block number where the reference count changes.
      This position will be either the starting block number of the next
      unprocessed reverse mapping or the next block after the shortest
      mapping in the bag.

    - Remove all mappings from the bag that end at this position.

Quoted 10 lines

    - Collect all reverse mappings that start at this position from the
      btree and put them in the bag.

    - If the size of the bag changed and is greater than one, create a
      new refcount record associating the block number range that we just walked to the size of the bag.

Sure, that looks fine to me

Quoted 518 lines
Quoted 50 lines
Quoted 50 lines
Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+The bag-like structure in this case is a type 2 xfarray as

discussed
in the
+:ref:xfarray access patterns<xfarray_access_patterns> section. +Reverse mappings are added to the bag using ``xfarray_store_anywhere`` and

Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+removed via ``xfarray_unset``.
+Bag members are examined through ``xfarray_iter`` loops.
+
+The proposed patchset is the
+`AG btree repair
+<

https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/
log/?h=repair-ag-btrees>`_

Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+series.
+
+Case Study: Rebuilding File Fork Mapping Indices
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+The high level process to rebuild a data/attr fork mapping btree

is:
+
+1. Walk the reverse mapping records to generate ``struct xfs_bmbt_rec``
+   records from the reverse mapping records for that inode and fork.
+   Append these records to an xfarray.
+   Compute the bitmap of the old bmap btree blocks from the ``BMBT_BLOCK``
+   records.
+
+2. Use the ``xfs_btree_bload_compute_geometry`` function to compute
the number
+   of blocks needed for the new tree.

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+
+3. Sort the records in file offset order.
+
+4. If the extent records would fit in the inode fork immediate

area,
commit the
+   records to that immediate area and skip to step 8.

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+
+5. Allocate the number of blocks computed in the previous step.
+
+6. Use ``xfs_btree_bload`` to write the xfarray records to btree

blocks and
+   generate the internal node blocks.
+

Quoted 8 lines
Quoted 4 lines

+7. Commit the new btree root block to the inode fork immediate area.
+
+8. Reap the old btree blocks using the bitmap created in step 1.

This description is not bad, but I had a hard time finding something
that resembled the description in the link below.  Maybe its in a different branch?

Oops, sorry, that url should be:
https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/log/?h=repair-file-mappings

Quoted 16 lines
Quoted 16 lines
Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+
+There are some 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

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+EXTENTS format instead of BMBT, which may require a conversion.
+Third, the incore extent map must be reloaded carefully to avoid

disturbing

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+any delayed allocation extents.
+
+The proposed patchset is the
+`file repair
Quoted 8 lines
Quoted 4 lines

+<
https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/
log/?h=repair-inodes>`_
+series.

So I'm assuming links to kernel.org are acceptable as it looks like you
use them here, but it does imply that they need to sort of live forever, or at least as long as any document that uses them?

After all this gets merged I'll replace them with links to fs/xfs/scrub/bmap_repair.c.

Quoted 124 lines
Quoted 105 lines
Documentation/filesystems/xfs-online-fsck-design.rst +7 -0
+
+.. _reaping:
+
+Reaping Old Metadata Blocks
+---------------------------
+
+Whenever online fsck builds a new data structure to replace one

that
is
+suspect, there is a question of how to find and dispose of the blocks that

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+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.
+Hopefully, someone will schedule a rebuild of the free space information to

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+plug all those leaks.
+Offline repair rebuilds all space metadata after recording the

usage
of
+the files and directories that it decides not to clear, hence it can
build new
+structures in the discovered free space and avoid the question of
reaping.

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+As part of a repair, online fsck relies heavily on the reverse

mapping records
+to find space that is owned by the corresponding rmap owner yet truly free.
+Cross referencing rmap records with other rmap records is necessary
because
+there may be other data structures that also think they own some of
those

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+blocks (e.g. crosslinked trees).
+Permitting the block allocator to hand them out again will not

push
the system

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+towards consistency.
+
+For space metadata, the process of finding extents to dispose of

generally

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+follows this format:
+
+1. Create a bitmap of space used by data structures that must be

preserved.
+   The space reservations used to create the new metadata can be used here if
+   the same rmap owner code is used to denote all of the objects being rebuilt.
+
+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 candidate extents that could be
freed.
+   The process moves on to step 4 below.

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+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

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+disposal.
+
+The process for disposing of old extents is as follows:
+
+4. For each candidate extent, 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.

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+
+   - 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.
+
+5. 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.
+
+6. If the region is crosslinked, delete the reverse mapping entry
for the

Quoted 8 lines

+   structure being repaired and move on to the next region. +
+7. If the region is to be freed, mark any corresponding buffers in
the buffer
+   cache as stale to prevent log writeback.
+
+8. Free the region and move on.

I think this part is as straightforward as it can be.  I like links,
but they do have maintenance issues if the branch ever goes away. It
may be worth it though just while the code is going through review, I
think it really helps to be able to just jump right into the code its
trying to describe rather than trying to track down based on the description.

Quoted 4 lines

https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/tree/fs/xfs/scrub/reap.c?h=repair-ag-btrees&id=d866f0e470b077806c994f4434bbe64e4a3a8662#n471:~:text=xrep_reap_ag_metadata(

I think that's the right one?  Tiny links nice for when steps are buried in sub functions too

Maybe?  That didn't actually move to line 471 or highlight anything.

Quoted 92 lines
Quoted 68 lines
Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+
+However, there is one complication to this procedure.
+Transactions are of finite size, so the reaping process must be

careful to roll

Documentation/filesystems/xfs-online-fsck-design.rst +8 -0
+the transactions to avoid overruns.
+Overruns come from two sources:
+
+a. EFIs logged on behalf of space that is no longer occupied
+
+b. Log items for buffer invalidations
+
+This is also a window in which a crash during the reaping

process
can leak

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+blocks.
+As stated earlier, online repair functions use very large

transactions to

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+minimize the chances of this occurring.
+
+The proposed patchset is the
+`preparation for bulk loading btrees
+<

https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/
log/?h=repair-prep-for-bulk-loading>`_

Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+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 the old btree blocks is quite simple,

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+conceptually:
+
+1. Lock the relevant AGI/AGF header buffers to prevent

allocation
and frees.
+
+2. For each reverse mapping record with an rmap owner corresponding
to the
+   metadata structure being rebuilt, 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)``
+   are the blocks that might be freeable.

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+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

Documentation/filesystems/xfs-online-fsck-design.rst this functionality as follows: · line 2755

Quoted 6 lines
Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+mapping record walk that creates the records for the new btree.
+
+Case Study: Rebuilding the Free Space Indices
+`````````````````````````````````````````````
+
+The high level process to rebuild the free space indices is:

Looks like this one
https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/commit/?h=repair-ag-btrees&id=bf5f10a91ca58d883ef1231a406fa0646c4c4e50#:~:text=%2B%20*/-,%2BSTATIC%20int,-%2Bxrep_abt_build_new_trees(

Quoted 15 lines

+
+1. Walk the reverse mapping records to generate ``struct xfs_alloc_rec_incore``
+   records from the gaps in the reverse mapping btree.

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+
+2. Append the records to an xfarray.
+
+3. Use the ``xfs_btree_bload_compute_geometry`` function to

compute
the number
+   of blocks needed for each new tree.
+
+4. Allocate the number of blocks computed in the previous step from
the free

Quoted 8 lines
Quoted 7 lines

+   space information collected.
+
+5. Use ``xfs_btree_bload`` to write the xfarray records to btree blocks and
+   generate the internal node blocks for the free space by block index.
+   Call it again for the free space by length index.

nit: these two loads are flipped

Oops, fixed.

Quoted 174 lines
Quoted 95 lines
Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+
+6. Commit the locations of the new btree root blocks to the AGF.
+
+7. Reap the old btree blocks by looking for space that is not

recorded by the
+   reverse mapping btree, the new free space btrees, or the AGFL.

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+Repairing the free space btrees has three key complications over

a
regular

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+btree repair:
+
+First, 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

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+space component of the keyspace of the reverse mapping btree.
+
+Second, free space repairs cannot use the common btree

reservation
code because

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+new blocks are reserved out of the free space btrees.
+This is 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

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+supply the blocks for the new free space btrees.
+It is not necessary to back each reserved extent with an EFI

because
the new
+free space btrees are constructed in what the ondisk filesystem thinks is

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+unowned 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

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+reservation is sufficient.
+As part of committing the new btrees, repair must ensure that

reverse mappings
+are created for the reserved blocks and that unused reserved blocks
are

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+inserted into the free space btrees.
+Deferrred rmap and freeing operations are used to ensure that

this
transition

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+is atomic, similar to the other btree repair functions.
+
+Third, finding the blocks to reap after the repair is not overly
+straightforward.
+Blocks for the free space btrees and the reverse mapping btrees

are
supplied by

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+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

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+btrees or the reverse mapping btrees.
+When repair walks reverse mapping records to synthesize free

space
records, it
+creates a bitmap (``ag_owner_bitmap``) of all the space claimed by
+``XFS_RMAP_OWN_AG`` records.
+The repair context maintains a second bitmap corresponding to the
rmap btree

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+blocks and the AGFL blocks (``rmap_agfl_bitmap``).
+When the walk is complete, the bitmap disunion operation

``(ag_owner_bitmap &
+~rmap_agfl_bitmap)`` computes the extents that are used by the old
free space

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+btrees.
+These blocks can then be reaped using the methods outlined

above.

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+
+The proposed patchset is the
+`AG btree repair
+<
Quoted 3 lines

https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/
log/?h=repair-ag-btrees>`_
+series.

I think we've repeated this link couple times in the doc.  If you like
highlight links, we cloud clean out the duplicates

Quoted 72 lines
Documentation/filesystems/xfs-online-fsck-design.rst +7 -0
+
+.. _rmap_reap:
+
+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

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+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
+:ref:live rebuilds of rmap data <rmap_repair>, but a crucial point
from that
+discussion is that the new rmap btree will not contain any records
for the old
+rmap btree, nor will 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 and the current AGFL

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+blocks.
+The result ``(new_rmapbt_gaps & ~(agfl | bnobt_records))`` are

reaped using the

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+methods outlined above.
+
+The rest of the process of rebuildng the reverse mapping btree

is
discussed

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+in a separate :ref:`case study<rmap_repair>`.
+
+The proposed patchset is the
+`AG btree repair
+<

https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/
log/?h=repair-ag-btrees>`_

Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+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.
+

Quoted 8 lines
Quoted 5 lines

+4. Once the AGFL is full, reap any blocks leftover. +
+5. The next operation to fix the freelist will right-size the list.

Branch link?  Looks like maybe it's missing.  In fact this logic looks
like it might have been cut off?

OH, heh.  I forgot that we already merged the AGFL repair code.

"See `fs/xfs/scrub/agheader_repair.c
<
https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tre
e/fs/xfs/scrub/agheader_repair.c>`_
for more details."

Quoted 2 lines

In any case, maybe give some thought to the highlight link suggestions.

Quoted 6 lines

Er... how do those work?  In principle I like them, but none of your links actually highlighted anything here.  Could you send the link over
IRC so that urldefense crapola won't destroy it, please?

--D

So I think the last we talked about these, we realized they're a chrome only format. That's a shame, I think they really help people to quickly navigate the code in question. Otherwise I'm pretty much just poking through the branches looking for code that resembles the description.

I also poked around and found there was a firefox plugin that does the same (link to text fragment addon). Though it doesn't look like the links generated are compatible between the browsers.

Maybe something to consider if we have a lot of chrome or ff users. I think if they help facilitate more discussion they're better than nothing at least during review.

Quoted 3 lines
Quoted 3 lines

Allison

#42 lore raw

Re: [PATCH 08/14] xfs: document btree bulk loading

On Thu, Feb 16, 2023 at 03:46:02PM +0000, Allison Henderson wrote:

<snip to the relevant parts>

Quoted 65 lines
Quoted 65 lines
Quoted 30 lines
Quoted 18 lines
Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+Writing the New Tree
+````````````````````
+
+This part is pretty simple -- the btree builder

(``xfs_btree_bulkload``) claims
+a block from the reserved list, writes the new btree block header,
fills the
+rest of the block with records, and adds the new leaf block to a list of

(quoted diff) +2 -0
+written blocks.
+Sibling pointers are set every time a new block is added to the

level.
+When it finishes writing the record leaf blocks, it moves on to the
node

(quoted diff) +2 -0
+blocks.
+To fill a node block, it walks each block in the next level down
Quoted 6 lines

in
the tree
+to compute the relevant keys and write them into the parent node.
+When it reaches the root level, it is ready to commit the new btree!

I think most of this is as straight forward as it can be, but it's a
lot visualizing too, which makes me wonder if it would benefit from an
simple illustration if possible.

Quoted 15 lines

On a side note: In a prior team I discovered power points, while a lot
work, were also really effective for quickly moving a crowd of people
through connected graph navigation/manipulations.  Because each one of
these steps was another slide that illustrated how the structure evolved through the updates.  I realize that's not something that fits
in the scheme of a document like this, but maybe something supplemental
to add later.  While it was a time eater, i noticed a lot of confused
expressions just seemed to shake loose, so sometimes it was worth it.

That was ... surprisingly less bad than I feared it would be to cut and
paste unicode linedraw characters and arrows.

          ┌─────────┐
          │root     │
          │PP       │
          └─────────┘
          ↙         ↘
      ┌────┐       ┌────┐
      │node│──────→│node│
      │PP  │←──────│PP  │
      └────┘       └────┘
      ↙   ↘         ↙   ↘
  ┌────┐ ┌────┐ ┌────┐ ┌────┐
  │leaf│→│leaf│→│leaf│→│leaf│
  │RRR │←│RRR │←│RRR │←│RRR │
  └────┘ └────┘ └────┘ └────┘
Quoted 3 lines
Quoted 1 line

(Does someone have a program that does this?)

I think Catherine mentioned she had used PlantUML for the larp diagram, though for something this simple I think this is fine

<nod>

Quoted 26 lines
Quoted 26 lines

I really like your version!  Can I tweak it a bit?

- Until the reverse mapping btree runs out of records:

  - Retrieve the next record from the btree and put it in a bag.

  - Collect all records with the same starting block from the btree and
    put them in the bag.

  - While the bag isn't empty:

    - Among the mappings in the bag, compute the lowest block number where the reference count changes.
      This position will be either the starting block number of the next
      unprocessed reverse mapping or the next block after the shortest
      mapping in the bag.

    - Remove all mappings from the bag that end at this position.

    - Collect all reverse mappings that start at this position from the
      btree and put them in the bag.

Quoted 7 lines
Quoted 6 lines

    - If the size of the bag changed and is greater than one, create a
      new refcount record associating the block number range that we just walked to the size of the bag.

Sure, that looks fine to me

Ok, will commit.

Quoted 20 lines
Quoted 20 lines
Quoted 3 lines

Branch link?  Looks like maybe it's missing.  In fact this logic looks
like it might have been cut off?

OH, heh.  I forgot that we already merged the AGFL repair code.

"See `fs/xfs/scrub/agheader_repair.c
<
https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tre
e/fs/xfs/scrub/agheader_repair.c>`_
for more details."

Quoted 2 lines

In any case, maybe give some thought to the highlight link suggestions.

Er... how do those work?  In principle I like them, but none of your links actually highlighted anything here.  Could you send the link over
IRC so that urldefense crapola won't destroy it, please?

Quoted 6 lines
Quoted 1 line

--D

So I think the last we talked about these, we realized they're a chrome only format. That's a shame, I think they really help people to quickly navigate the code in question. Otherwise I'm pretty much just poking through the branches looking for code that resembles the description.

Yep. Back in 2020, Google was pushing a "link to text fragment" proposal wherein they'd add some secret sauce to URL anchors:

#:~:text=[prefix-,]textStart[,textEnd][,-suffix]

Which would inspire web browsers to highlight all instances of "text" in a document and autoscroll to the first occurrence. They've since integrated this into Chrome and persuaded Safari to pick it up, but there are serious problems with this hack.

https://wicg.github.io/scroll-to-text-fragment/

The first and biggest problem is that none of the prefix characters here ":~:text=" are invalid characters for a url anchor, nor are they ever invalid for an <a name> tag. This is valid html:

<a name="dork:~:text=farts">cow</a>

And this is valid link to that html anchor:

file:///tmp/a.html#dork:~:text=farts

Web browsers that are unaware of this extension (Firefox, lynx, w3m, etc.) will not know to ignore everything starting with ":~:" when navigating, so they will actually try to find an anchor matching that name. That's why it didn't work for me but worked fine for Allison.

This is even worse if the document also contains:

<a name="dork">frogs</a>

Because now the url "file:///tmp/a.html#dork:~:text=farts" jumps to "cow" on Chrome, and "frogs" on Firefox.

Embrace and extend [with proprietary bullsh*t]. Thanks Google.

Quoted 3 lines

I also poked around and found there was a firefox plugin that does the same (link to text fragment addon). Though it doesn't look like the links generated are compatible between the browsers.

No, they are not.

Quoted 3 lines

Maybe something to consider if we have a lot of chrome or ff users. I think if they help facilitate more discussion they're better than nothing at least during review.

I'll comb through these documents and add some suggestions of where to navigate, e.g.

"For more details, see the function xrep_reap."

Simple and readable by anyone, albeit without the convenient mechanical links.

For more fun reading, apparently terminals support now escape sequences to inject url links too:
https://github.com/Alhadis/OSC8-Adoption

--D

Quoted 4 lines
Quoted 3 lines
Quoted 3 lines

Allison

#43 lore raw

PATCH 9/14 xfs: document online file metadata repair code

In reply to Darrick J. Wong

From: Darrick J. Wong <[email protected]>

Add to the fifth chapter of the online fsck design documentation, where we discuss the details of the data structures and algorithms used by the kernel to repair file metadata.

---
 .../filesystems/xfs-online-fsck-design.rst         |  150 ++++++++++++++++++++
 1 file changed, 150 insertions(+)
Documentation/filesystems/xfs-online-fsck-design.rst +150 -0
index eb61d867e55c..a658da8fe4ae 100644
@@ -2868,3 +2868,153 @@ The allocation group free block list (AGFL) is repaired as follows:
 4. Once the AGFL is full, reap any blocks leftover.
 
 5. The next operation to fix the freelist will right-size the list.
+
+Inode Record Repairs
+--------------------
+
+Inode records must be handled carefully, because they have both ondisk records
+("dinodes") and an in-memory ("cached") representation.
+There is a very high potential for cache coherency issues if online fsck is not
+careful to access the ondisk metadata *only* when the ondisk metadata is so
+badly damaged that the filesystem cannot load the in-memory representation.
+When online fsck wants to open a damaged file for scrubbing, 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.
+
+The only repairs that should be made to the ondisk inode buffers are whatever
+is necessary to get the in-core structure loaded.
+This means fixing whatever is caught by the inode cluster buffer and inode fork
+verifiers, and retrying the ``iget`` operation.
+If the second ``iget`` fails, the repair has failed.
+
+Once the in-memory representation is loaded, repair can lock the inode and can
+subject it to comprehensive checks, repairs, and optimizations.
+Most inode attributes are easy to check and constrain, or are user-controlled
+arbitrary bit patterns; these are both easy to fix.
+Dealing with the data and attr fork extent counts and the file block counts is
+more complicated, because computing the correct value requires traversing the
+forks, or if that fails, leaving the fields invalid and waiting for the fork
+fsck functions to run.
+
+The proposed patchset is the
+`inode
+<https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/log/?h=repair-inodes>`_
+repair series.
+
+Quota Record Repairs
+--------------------
+
+Similar to inodes, quota records ("dquots") also have both ondisk records and
+an in-memory representation, and hence are subject to the same cache coherency
+issues.
+Somewhat confusingly, both are known as dquots in the XFS codebase.
+
+The only repairs that should be made to the ondisk quota record buffers are
+whatever is necessary to get the in-core structure loaded.
+Once the in-memory representation is loaded, the only attributes needing
+checking are obviously bad limits and timer values.
+
+Quota usage counters are checked, repaired, and discussed separately in the
+section about :ref:`live quotacheck <quotacheck>`.
+
+The proposed patchset is the
+`quota
+<https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/log/?h=repair-quota>`_
+repair series.
+
+.. _fscounters:
+
+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 should reflect the ondisk metadata, at least when the filesystem has been
+unmounted cleanly.
+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 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, the in-memory counters must be stabilize while walking 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, scrub can walk the AG free space indexes, the
+inode btrees, and the realtime bitmap to compute the correct value of all
+four summary counters.
+This is very similar to a filesystem freeze.
+
+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:
+
+- The log need not be quiesced 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 XFS flushes the (possibly incorrect) counters to
+  disk as part of cleaning the log.
+
+- 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.
+
+- It does not 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
+<https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/log/?h=repair-fscounters>`_
+series.
#44 lore raw

PATCH 10/14 xfs: document full filesystem scans for online fsck

In reply to Darrick J. Wong

From: Darrick J. Wong <[email protected]>

Certain parts of the online fsck code need to scan every file in the entire filesystem. It is not acceptable to block the entire filesystem while this happens, which means that we need to be clever in allowing scans to coordinate with ongoing filesystem updates. We also need to hook the filesystem so that regular updates propagate to the staging records.

---
 .../filesystems/xfs-online-fsck-design.rst         |  677 ++++++++++++++++++++
 1 file changed, 677 insertions(+)
Documentation/filesystems/xfs-online-fsck-design.rst +677 -0
index a658da8fe4ae..c0f08a773f08 100644
@@ -3018,3 +3018,680 @@ The proposed patchset is the
 `summary counter cleanup
 <https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/log/?h=repair-fscounters>`_
 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.
+Like every other type of online repair, repairs are made by writing those
+observations to disk in a replacement structure and committing it atomically.
+However, it is not practical to shut down the entire filesystem to examine
+hundreds of billions 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 does scrub manage the scan while it is collecting data?
+
+- How does the scan keep abreast of changes being made to the system by other
+  threads?
+
+.. _iscan:
+
+Coordinated Inode Scans
+```````````````````````
+
+In the original Unix filesystems of the 1970s, each directory entry contained
+an index number (*inumber*) which was used as an index into on ondisk array
+(*itable*) of fixed-size records (*inodes*) describing a file's attributes and
+its data block mapping.
+This system is described by J. Lions, `"inode (5659)"
+<http://www.lemis.com/grog/Documentation/Lions/>`_ in *Lions' Commentary on
+UNIX, 6th Edition*, (Dept. of Computer Science, the University of New South
+Wales, November 1977), pp. 18-2; and later by D. Ritchie and K. Thompson,
+`"Implementation of the File System"
+<https://archive.org/details/bstj57-6-1905/page/n8/mode/1up>`_, from *The UNIX
+Time-Sharing System*, (The Bell System Technical Journal, July 1978), pp.
+1913-4.
+
+XFS retains most of this design, except now inumbers are search keys over all
+the space in the data section filesystem.
+They form a continuous keyspace that can be expressed as a 64-bit integer,
+though the inodes themselves are sparsely distributed within the keyspace.
+Scans proceed in a linear fashion across the inumber keyspace, starting from
+``0x0`` and ending at ``0xFFFFFFFFFFFFFFFF``.
+Naturally, a scan through a keyspace requires a scan cursor object to track the
+scan progress.
+Because this keyspace is sparse, this cursor contains two parts.
+The first part of this scan cursor object tracks the inode that will be
+examined next; call this the examination cursor.
+Somewhat less obviously, the scan cursor object must also track which parts of
+the keyspace have already been visited, which is critical for deciding if a
+concurrent filesystem update needs to be incorporated into the scan data.
+Call this the visited inode cursor.
+
+Advancing the scan cursor is a multi-step process encapsulated in
+``xchk_iscan_iter``:
+
+1. Lock the AGI buffer of the AG containing the inode pointed to by the visited
+   inode cursor.
+   This guarantee that inodes in this AG cannot be allocated or freed while
+   advancing the cursor.
+
+2. Use the per-AG inode btree to look up the next inumber after the one that
+   was just visited, since it may not be keyspace adjacent.
+
+3. If there are no more inodes left in this AG:
+
+   a. Move the examination cursor to the point of the inumber keyspace that
+      corresponds to the start of the next AG.
+
+   b. Adjust the visited inode cursor to indicate that it has "visited" the
+      last possible inode in the current AG's inode keyspace.
+      XFS inumbers are segmented, so the cursor needs to be marked as having
+      visited the entire keyspace up to just before the start of the next AG's
+      inode keyspace.
+
+   c. Unlock the AGI and return to step 1 if there are unexamined AGs in the
+      filesystem.
+
+   d. If there are no more AGs to examine, set both cursors to the end of the
+      inumber keyspace.
+      The scan is now complete.
+
+4. Otherwise, there is at least one more inode to scan in this AG:
+
+   a. Move the examination cursor ahead to the next inode marked as allocated
+      by the inode btree.
+
+   b. Adjust the visited inode cursor to point to the inode just prior to where
+      the examination cursor is now.
+      Because the scanner holds the AGI buffer lock, no inodes could have been
+      created in the part of the inode keyspace that the visited inode cursor
+      just advanced.
+
+5. Get the incore inode for the inumber of the examination cursor.
+   By maintaining the AGI buffer lock until this point, the scanner knows that
+   it was safe to advance the examination cursor across the entire keyspace,
+   and that it has stabilized this next inode so that it cannot disappear from
+   the filesystem until the scan releases the incore inode.
+
+6. Drop the AGI lock and return the incore inode to the caller.
+
+Online fsck functions scan all files in the filesystem as follows:
+
+1. Start a scan by calling ``xchk_iscan_start``.
+
+2. Advance the scan cursor (``xchk_iscan_iter``) to get the next inode.
+   If one is provided:
+
+   a. Lock the inode to prevent updates during the scan.
+
+   b. Scan the inode.
+
+   c. While still holding the inode lock, adjust the visited inode cursor
+      (``xchk_iscan_mark_visited``) to point to this inode.
+
+   d. Unlock and release the inode.
+
+8. Call ``xchk_iscan_finish`` to complete 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 the
+`inode scanner
+<https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/log/?h=scrub-iscan>`_
+series.
+
+Inode Management
+````````````````
+
+In regular filesystem code, references to allocated XFS incore inodes are
+always obtained (``xfs_iget``) outside of transaction context because the
+creation of the incore context for ane xisting file does not require metadata
+updates.
+However, it is important to note that references to incore inodes obtained as
+part of file creation must be performed in transaction context because the
+filesystem must ensure the atomicity of the ondisk inode btree index updates
+and the initialization of the actual ondisk inode.
+
+References to incore inodes are always released (``xfs_irele``) outside of
+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 and freeing the inode.
+
+These activities are collectively called inode inactivation.
+Inactivation has two parts -- the VFS part, which initiates writeback on all
+dirty file pages, and the XFS part, which cleans up XFS-specific information
+and frees the inode if it was unlinked.
+If the inode is unlinked (or unconnected after a file handle operation), the
+kernel drops the inode into the inactivation machinery immediately.
+
+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. Log feature enablement.
+
+6. Transaction log space grant.
+
+7. Space on the data and realtime devices for the transaction.
+
+8. Incore dquot references, if a file is being repaired.
+   Note that they are not locked, merely acquired.
+
+9. Inode ``ILOCK`` for file metadata updates.
+
+10. AG header buffer locks / Realtime metadata inode ILOCK.
+
+11. Realtime metadata buffer locks, if applicable.
+
+12. Extent mapping btree blocks, if applicable.
+
+Resources are often released in the reverse order, though this is not required.
+However, online fsck differs from regular XFS operations because it may examine
+an object that normally is acquired in a later stage of the locking order, and
+then decide to cross-reference the object with an object that is acquired
+earlier in the order.
+The next few sections detail the specific ways in which online fsck takes care
+to avoid deadlocks.
+
+iget and irele During a Scrub
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+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, as long as all of the bound resources are acquired
+before the inode reference in the regular filesystem.
+
+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.
+
+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 there is no scrub transaction, 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
+<https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/log/?h=scrub-iget-fixes>`_ and
+`dir iget usage
+<https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/log/?h=scrub-dir-iget-fixes>`_.
+
+Locking Inodes
+^^^^^^^^^^^^^^
+
+In regular filesystem code, the VFS and XFS will acquire multiple IOLOCK locks
+in a well-known order: parent → child when updating the directory tree, and
+``struct inode`` address order otherwise.
+For regular files, the MMAPLOCK can be acquired after the IOLOCK to stop page
+faults.
+If two MMAPLOCKs must be acquired, they are acquired in ``struct
+address_space`` order.
+Due to the structure of existing filesystem code, IOLOCKs and MMAPLOCKs must be
+acquired before transactions are allocated.
+If two ILOCKs must be acquired, they are acquired in inumber order.
+
+Inode lock acquisition must be done carefully during a coordinated inode scan.
+Online fsck cannot abide these conventions, because for a directory tree
+scanner, the scrub process holds the IOLOCK of the file being scanned and it
+needs to take the IOLOCK of the file at the other end of the directory link.
+If the directory tree is corrupt because it contains a cycle, ``xfs_scrub``
+cannot use the regular inode locking functions and avoid becoming trapped in an
+ABBA deadlock.
+
+Solving both of these problems is straightforward -- any time online fsck
+needs to take a second lock of the same class, it uses trylock to avoid an ABBA
+deadlock.
+If the trylock fails, scrub drops 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.
+
+.. _dirparent:
+
+Case Study: Finding a Directory Parent
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Consider the directory parent pointer repair code as an example.
+Online fsck must verify that the dotdot dirent of a directory points up to a
+parent directory, and that the parent directory contains exactly one dirent
+pointing down to the child directory.
+Fully validating this relationship (and repairing it if possible) requires a
+walk of every directory on the filesystem while holding the child locked, and
+while updates to the directory tree are being made.
+The coordinated inode scan provides a way to walk the filesystem without the
+possibility of missing an inode.
+The child directory is kept locked to prevent updates to the dotdot dirent, but
+if the scanner fails to lock a parent, it can drop and relock both the child
+and the prospective parent.
+If the dotdot entry changes while the directory is unlocked, then a move or
+rename operation must have changed the child's parentage, and the scan can
+exit early.
+
+The proposed patchset is the
+`directory repair
+<https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/log/?h=repair-dirs>`_
+series.
+
+.. _fshooks:
+
+Filesystem Hooks
+`````````````````
+
+The second piece of support that online fsck 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: filesystem hooks and :ref:`static keys<jump_labels>`.
+
+Filesystem hooks convey information about an ongoing filesystem operation to
+a downstream consumer.
+In this case, the downstream consumer is always an online fsck function.
+Because multiple fsck functions can run in parallel, online fsck uses the Linux
+notifier call chain facility to dispatch updates to any number of interested
+fsck processes.
+Call chains are a dynamic list, which means that they can be configured at
+run time.
+Because these hooks are private to the XFS module, the information passed along
+contains exactly what the checking function needs to update its observations.
+
+The current implementation of XFS hooks uses SRCU notifier chains to reduce the
+impact to highly threaded workloads.
+Regular blocking notifier chains use a rwsem and seem to have a much lower
+overhead for single-threaded applications.
+However, it may turn out that the combination of blocking chains and static
+keys are a more performant combination; more study is needed here.
+
+The following pieces are necessary to hook a certain point in the filesystem:
+
+- A ``struct xfs_hooks`` object must be embedded in a convenient place such as
+  a well-known incore filesystem object.
+
+- Each hook must define an action code and a structure containing more context
+  about the action.
+
+- Hook providers should provide appropriate wrapper functions and structs
+  around the ``xfs_hooks`` and ``xfs_hook`` objects to take advantage of type
+  checking to ensure correct usage.
+
+- A callsite in the regular filesystem code must be chosen to call
+  ``xfs_hooks_call`` with the action code and data structure.
+  This place should be adjacent to (and not earlier than) the place where
+  the filesystem update is committed to the transaction.
+  In general, when the filesystem calls a hook chain, it should be able to
+  handle sleeping and should not be vulnerable to memory reclaim or locking
+  recursion.
+  However, the exact requirements are very dependent on the context of the hook
+  caller and the callee.
+
+- The online fsck function should define a structure to hold scan data, a lock
+  to coordinate access to the scan data, and a ``struct xfs_hook`` object.
+  The scanner function and the regular filesystem code must acquire resources
+  in the same order; see the next section for details.
+
+- The online fsck code must contain a C function to catch the hook action code
+  and data structure.
+  If the object being updated has already been visited by the scan, then the
+  hook information must be applied to the scan data.
+
+- Prior to unlocking inodes to start the scan, online fsck must call
+  ``xfs_hooks_setup`` to initialize the ``struct xfs_hook``, and
+  ``xfs_hooks_add`` to enable the hook.
+
+- Online fsck must call ``xfs_hooks_del`` to disable the hook once the scan is
+  complete.
+
+The number of hooks should be kept to a minimum to reduce complexity.
+Static keys are used to reduce the overhead of filesystem hooks to nearly
+zero when online fsck is not running.
+
+.. _liveupdate:
+
+Live Updates During a Scan
+``````````````````````````
+
+The code paths of the online fsck scanning code and the :ref:`hooked<fshooks>`
+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.
+
+- Scrub 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 (``xchk_iscan_want_live_update``)
+  for this.
+
+- Scrub hook functions must not change the caller's state, including the
+  transaction that it is running.
+  They must not acquire any resources that might conflict with the filesystem
+  function being hooked.
+
+- The hook function can abort the inode scan to avoid breaking the other rules.
+
+The inode scan APIs are pretty simple:
+
+- ``xchk_iscan_start`` starts a scan
+
+- ``xchk_iscan_iter`` grabs a reference to the next inode in the scan or
+  returns zero if there is nothing left to scan
+
+- ``xchk_iscan_want_live_update`` to decide if an inode has already been
+  visited in the scan.
+  This is critical for hook functions to decide if they need to update the
+  in-memory scan information.
+
+- ``xchk_iscan_mark_visited`` to mark an inode as having been visited in the
+  scan
+
+- ``xchk_iscan_finish`` to finish the scan
+
+The proposed patches are at the start of the
+`online quotacheck
+<https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/log/?h=repair-quota>`_
+series.
+
+.. _quotacheck:
+
+Case Study: Quota Counter Checking
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+It is useful to 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.
+
+Like most online fsck functions, online quotacheck can't write to regular
+filesystem objects until the newly collected metadata reflect all filesystem
+state.
+Therefore, online quotacheck records file resource usage to a shadow dquot
+index implemented with a sparse ``xfarray``, and only writes to the real dquots
+once the scan is complete.
+Handling transactional updates is tricky because quota resource usage updates
+are handled in phases to minimize contention on dquots:
+
+1. The inodes involved are joined and locked to a transaction.
+
+2. For each dquot attached to the file:
+
+   a. The dquot is locked.
+
+   b. A quota reservation is added to the dquot's resource usage.
+      The reservation is recorded in the transaction.
+
+   c. The dquot is unlocked.
+
+3. Changes in actual quota usage are tracked in the transaction.
+
+4. At transaction commit time, each dquot is examined again:
+
+   a. The dquot is locked again.
+
+   b. Quota usage changes are logged and unused reservation is given back to
+      the dquot.
+
+   c. The dquot is unlocked.
+
+For online 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 ``dqtrx`` 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.
+
+The quotacheck scan looks like this:
+
+1. Set up a coordinated inode scan.
+
+2. For each inode returned by the inode scan iterator:
+
+   a. Grab and lock the inode.
+
+   b. Determine that inode's resource usage (data blocks, inode counts,
+      realtime blocks) and add that to the shadow dquots for the user, group,
+      and project ids associated with the inode.
+
+   c. Unlock and release the inode.
+
+3. For each dquot in the system:
+
+   a. Grab and lock the dquot.
+
+   b. Check the dquot against the shadow dquots created by the scan and updated
+      by the live hooks.
+
+Live updates are key to being able to walk every quota record without
+needing to hold any locks for a long duration.
+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
+<https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/log/?h=repair-quota>`_
+series.
+
+.. _nlinks:
+
+Case Study: File Link Count Checking
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+File link count checking also uses live update hooks.
+The coordinated inode scanner is used to visit all directories on the
+filesystem, and per-file link count records are stored in a sparse ``xfarray``
+indexed by inumber.
+During the scanning phase, each entry in a directory generates observation
+data as follows:
+
+1. If the entry is a dotdot (``'..'``) entry of the root directory, the
+   directory's parent link count is bumped because the root directory's dotdot
+   entry is self referential.
+
+2. If the entry is a dotdot entry of a subdirectory, the parent's backref
+   count is bumped.
+
+3. If the entry is neither a dot nor a dotdot entry, the target file's parent
+   count is bumped.
+
+4. If the target is a subdirectory, the parent's child link count is bumped.
+
+A crucial point to understand about how the link count inode scanner interacts
+with the live update hooks is that the scan cursor tracks which *parent*
+directories have been scanned.
+In other words, the live updates ignore any update about ``A → B`` when A has
+not been scanned, even if B has been scanned.
+Furthermore, a subdirectory A with a dotdot entry pointing back to B is
+accounted as a backref counter in the shadow data for A, since child dotdot
+entries affect the parent's link count.
+Live update hooks are carefully placed in all parts of the filesystem that
+create, change, or remove directory entries, since those operations involve
+bumplink and droplink.
+
+For any file, the correct link count is the number of parents plus the number
+of child subdirectories.
+Non-directories never have children of any kind.
+The backref information is used to detect inconsistencies in the number of
+links pointing to child subdirectories and the number of dotdot entries
+pointing back.
+
+After the scan completes, the link count of each file can be checked by locking
+both the inode and the shadow data, and comparing the link counts.
+A second coordinated inode scan cursor is used for comparisons.
+Live updates are key to being able to walk every inode without needing to hold
+any locks between inodes.
+If repairs are desired, the inode's link count is set to the value in the
+shadow information.
+If no parents are found, the file must be :ref:`reparented <orphanage>` to the
+orphanage to prevent the file from being lost forever.
+
+The proposed patchset is the
+`file link count repair
+<https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/log/?h=scrub-nlinks>`_
+series.
+
+.. _rmap_repair:
+
+Case Study: Rebuilding Reverse Mapping Records
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Most repair functions follow the same pattern: lock filesystem resources,
+walk the surviving ondisk metadata looking for replacement metadata records,
+and use an :ref:`in-memory array <xfarray>` to store the gathered observations.
+The primary advantage of this approach is the simplicity and modularity of the
+repair code -- code and data are entirely contained within the scrub module,
+do not require hooks in the main filesystem, and are usually the most efficient
+in memory use.
+A secondary advantage of this repair approach is atomicity -- once the kernel
+decides a structure is corrupt, no other threads can access the metadata until
+the kernel finishes repairing and revalidating the metadata.
+
+For repairs going on within a shard of the filesystem, these advantages
+outweigh the delays inherent in locking the shard while repairing parts of the
+shard.
+Unfortunately, repairs to the reverse mapping btree cannot use the "standard"
+btree repair strategy because it must scan every space mapping of every fork of
+every file in the filesystem, and the filesystem cannot stop.
+Therefore, rmap repair foregoes atomicity between scrub and repair.
+It combines a :ref:`coordinated inode scanner <iscan>`, :ref:`live update hooks
+<liveupdate>`, and an :ref:`in-memory rmap btree <xfbtree>` to complete the
+scan for reverse mapping records.
+
+1. Set up an xfbtree to stage rmap records.
+
+2. While holding the locks on the AGI and AGF buffers acquired during the
+   scrub, generate reverse mappings for all AG metadata: inodes, btrees, CoW
+   staging extents, and the internal log.
+
+3. Set up an inode scanner.
+
+4. Hook into rmap updates for the AG being repaired so that the live scan data
+   can receive updates to the rmap btree from the rest of the filesystem during
+   the file scan.
+
+5. For each space mapping found in either fork of each file scanned,
+   decide if the mapping matches the AG of interest.
+   If so:
+
+   a. Create a btree cursor for the in-memory btree.
+
+   b. Use the rmap code to add the record to the in-memory btree.
+
+   c. Use the :ref:`special commit function <xfbtree_commit>` to write the
+      xfbtree changes to the xfile.
+
+6. For each live update received via the hook, decide if the owner has already
+   been scanned.
+   If so, apply the live update into the scan data:
+
+   a. Create a btree cursor for the in-memory btree.
+
+   b. Replay the operation into the in-memory btree.
+
+   c. Use the :ref:`special commit function <xfbtree_commit>` to write the
+      xfbtree changes to the xfile.
+      This is performed with an empty transaction to avoid changing the
+      caller's state.
+
+7. When the inode scan finishes, create a new scrub transaction and relock the
+   two AG headers.
+
+8. Compute the new btree geometry using the number of rmap records in the
+   shadow btree, like all other btree rebuilding functions.
+
+9. Allocate the number of blocks computed in the previous step.
+
+10. Perform the usual btree bulk loading and commit to install the new rmap
+    btree.
+
+11. Reap the old rmap btree blocks as discussed in the case study about how
+    to :ref:`reap after rmap btree repair <rmap_reap>`.
+
+12. Free the xfbtree now that it not needed.
+
+The proposed patchset is the
+`rmap repair
+<https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/log/?h=repair-rmap-btree>`_
+series.
#45 lore raw

Re: [PATCH 10/14] xfs: document full filesystem scans for online fsck

Quoted 169 lines · Darrick J. Wong

From: Darrick J. Wong <[email protected]>

Certain parts of the online fsck code need to scan every file in the entire filesystem.  It is not acceptable to block the entire filesystem
while this happens, which means that we need to be clever in allowing scans to coordinate with ongoing filesystem updates.  We also need to hook the filesystem so that regular updates propagate to the staging records.

---
 .../filesystems/xfs-online-fsck-design.rst         |  677
++++++++++++++++++++

 1 file changed, 677 insertions(+)
Documentation/filesystems/xfs-online-fsck-design.rst +0 -0
index a658da8fe4ae..c0f08a773f08 100644
@@ -3018,3 +3018,680 @@ The proposed patchset is the

 `summary counter cleanup
 <
https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/
log/?h=repair-fscounters>`_
 series.

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+
+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

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+what's recorded on disk.
+Like every other type of online repair, repairs are made by writing

those
+observations to disk in a replacement structure and committing it atomically.
+However, it is not practical to shut down the entire filesystem to examine
+hundreds of billions of files because the downtime would be excessive.
+Therefore, online fsck must build the infrastructure to manage a live scan of

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+all the files in the filesystem.
+There are two questions that need to be solved to perform a live

walk:

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+
+- How does scrub manage the scan while it is collecting data?
+
+- How does the scan keep abreast of changes being made to the system

by other
+  threads?

Documentation/filesystems/xfs-online-fsck-design.rst +7 -0
+
+.. _iscan:
+
+Coordinated Inode Scans
+```````````````````````
+
+In the original Unix filesystems of the 1970s, each directory entry

contained
+an index number (*inumber*) which was used as an index into on ondisk array
+(*itable*) of fixed-size records (*inodes*) describing a file's attributes and

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+its data block mapping.
+This system is described by J. Lions, `"inode (5659)"
+<http://www.lemis.com/grog/Documentation/Lions/>`_ in *Lions'

Commentary on
+UNIX, 6th Edition*, (Dept. of Computer Science, the University of New South
+Wales, November 1977), pp. 18-2; and later by D. Ritchie and K. Thompson,
+"Implementation of the File System" +<https://archive.org/details/bstj57-6-1905/page/n8/mode/1up>_, from *The UNIX
+Time-Sharing System*, (The Bell System Technical Journal, July 1978), pp.
+1913-4.

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+XFS retains most of this design, except now inumbers are search keys

over all

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+the space in the data section filesystem.
+They form a continuous keyspace that can be expressed as a 64-bit

integer,
+though the inodes themselves are sparsely distributed within the keyspace.
+Scans proceed in a linear fashion across the inumber keyspace, starting from
+``0x0`` and ending at ``0xFFFFFFFFFFFFFFFF``. +Naturally, a scan through a keyspace requires a scan cursor object to track the

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+scan progress.
+Because this keyspace is sparse, this cursor contains two parts.
+The first part of this scan cursor object tracks the inode that will

be

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+examined next; call this the examination cursor.
+Somewhat less obviously, the scan cursor object must also track

which parts of
+the keyspace have already been visited, which is critical for deciding if a
+concurrent filesystem update needs to be incorporated into the scan data.

Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+Call this the visited inode cursor.
+
+Advancing the scan cursor is a multi-step process encapsulated in
+``xchk_iscan_iter``:
+
+1. Lock the AGI buffer of the AG containing the inode pointed to by

the visited
+   inode cursor.
+   This guarantee that inodes in this AG cannot be allocated or freed while
+   advancing the cursor.
+
+2. Use the per-AG inode btree to look up the next inumber after the one that
+   was just visited, since it may not be keyspace adjacent.

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+
+3. If there are no more inodes left in this AG:
+
+   a. Move the examination cursor to the point of the inumber

keyspace that
+      corresponds to the start of the next AG.
+
+   b. Adjust the visited inode cursor to indicate that it has "visited" the
+      last possible inode in the current AG's inode keyspace. +      XFS inumbers are segmented, so the cursor needs to be marked as having
+      visited the entire keyspace up to just before the start of the next AG's
+      inode keyspace.
+
+   c. Unlock the AGI and return to step 1 if there are unexamined AGs in the
+      filesystem.
+
+   d. If there are no more AGs to examine, set both cursors to the end of the
+      inumber keyspace.
+      The scan is now complete.

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+
+4. Otherwise, there is at least one more inode to scan in this AG:
+
+   a. Move the examination cursor ahead to the next inode marked as

allocated
+      by the inode btree.
+
+   b. Adjust the visited inode cursor to point to the inode just prior to where
+      the examination cursor is now.
+      Because the scanner holds the AGI buffer lock, no inodes could have been
+      created in the part of the inode keyspace that the visited inode cursor
+      just advanced.
+
+5. Get the incore inode for the inumber of the examination cursor. +   By maintaining the AGI buffer lock until this point, the scanner knows that
+   it was safe to advance the examination cursor across the entire keyspace,
+   and that it has stabilized this next inode so that it cannot disappear from
+   the filesystem until the scan releases the incore inode.

Documentation/filesystems/xfs-online-fsck-design.rst The proposed patchset is the · line 3125

Quoted 6 lines
Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+
+6. Drop the AGI lock and return the incore inode to the caller.
+
+Online fsck functions scan all files in the filesystem as follows:
+
+1. Start a scan by calling ``xchk_iscan_start``.

Hmm, I actually did not find xchk_iscan_start in the below branch, I found xchk_iscan_iter in "xfs: implement live inode scan for scrub", but it doesnt look like anything uses it yet, at least not in that branch.

Also, it took me a bit to figure out that "initial user" meant "calling function"

Quoted 40 lines

+
+2. Advance the scan cursor (``xchk_iscan_iter``) to get the next inode.
+   If one is provided:

Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+
+   a. Lock the inode to prevent updates during the scan.
+
+   b. Scan the inode.
+
+   c. While still holding the inode lock, adjust the visited inode

cursor
+      (``xchk_iscan_mark_visited``) to point to this inode.

Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+
+   d. Unlock and release the inode.
+
+8. Call ``xchk_iscan_finish`` to complete the scan.
+
+There are subtleties with the inode cache that complicate grabbing

the incore

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+inode for the caller.
+Obviously, it is an absolute requirement that the inode metadata be

consistent

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+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

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+back into a loadable state.
+
+The proposed patches are the
+`inode scanner
+<

https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/
log/?h=scrub-iscan>`_

Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+series.
+
+Inode Management
+````````````````
+
+In regular filesystem code, references to allocated XFS incore
Quoted 4 lines

inodes are
+always obtained (``xfs_iget``) outside of transaction context because the
+creation of the incore context for ane xisting file does not require

an existing

Quoted 145 lines

metadata

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+updates.
+However, it is important to note that references to incore inodes

obtained as
+part of file creation must be performed in transaction context because the
+filesystem must ensure the atomicity of the ondisk inode btree index updates

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+and the initialization of the actual ondisk inode.
+
+References to incore inodes are always released (``xfs_irele``)

outside of
+transaction context because there are a handful of activities that might

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+require ondisk updates:
+
+- The VFS may decide to kick off writeback as part of a

``DONTCACHE`` inode
+  release.

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+
+- 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 and freeing the inode.

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+
+These activities are collectively called inode inactivation.
+Inactivation has two parts -- the VFS part, which initiates

writeback on all
+dirty file pages, and the XFS part, which cleans up XFS-specific information

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+and frees the inode if it was unlinked.
+If the inode is unlinked (or unconnected after a file handle

operation), the

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+kernel drops the inode into the inactivation machinery immediately.
+
+During normal operation, resource acquisition for an update follows

this order

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+to avoid deadlocks:
+
+1. Inode reference (``iget``).
+
+2. Filesystem freeze protection, if repairing

(``mnt_want_write_file``).

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+
+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.

Documentation/filesystems/xfs-online-fsck-design.rst +19 -0
+
+5. Log feature enablement.
+
+6. Transaction log space grant.
+
+7. Space on the data and realtime devices for the transaction.
+
+8. Incore dquot references, if a file is being repaired.
+   Note that they are not locked, merely acquired.
+
+9. Inode ``ILOCK`` for file metadata updates.
+
+10. AG header buffer locks / Realtime metadata inode ILOCK.
+
+11. Realtime metadata buffer locks, if applicable.
+
+12. Extent mapping btree blocks, if applicable.
+
+Resources are often released in the reverse order, though this is

not required.
+However, online fsck differs from regular XFS operations because it may examine
+an object that normally is acquired in a later stage of the locking order, and
+then decide to cross-reference the object with an object that is acquired

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+earlier in the order.
+The next few sections detail the specific ways in which online fsck

takes care

Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+to avoid deadlocks.
+
+iget and irele During a Scrub
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+An inode scan performed on behalf of a scrub operation runs in

transaction

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+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, as long as all of the bound resources are acquired

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+before the inode reference in the regular filesystem.
+
+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

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+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

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+inactivation machinery immediately.
+
+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

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+transaction, and XFS does not support nesting transactions.
+On the other hand, if there is no scrub transaction, it is desirable

to drop

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+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

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+behavior.
+
+Proposed patchsets include fixing
+`scrub iget usage
+<

https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/
log/?h=scrub-iget-fixes>`_ and
+`dir iget usage
+<
https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/
log/?h=scrub-dir-iget-fixes>`_.

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+
+Locking Inodes
+^^^^^^^^^^^^^^
+
+In regular filesystem code, the VFS and XFS will acquire multiple

IOLOCK locks
+in a well-known order: parent → child when updating the directory tree, and
+``struct inode`` address order otherwise.
+For regular files, the MMAPLOCK can be acquired after the IOLOCK to stop page

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+faults.
+If two MMAPLOCKs must be acquired, they are acquired in 
Quoted 2 lines

``struct
+address_space`` order.

the order of their memory address

?

Quoted 270 lines

+Due to the structure of existing filesystem code, IOLOCKs and MMAPLOCKs must be

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+acquired before transactions are allocated.
+If two ILOCKs must be acquired, they are acquired in inumber order.
+
+Inode lock acquisition must be done carefully during a coordinated

inode scan.
+Online fsck cannot abide these conventions, because for a directory tree
+scanner, the scrub process holds the IOLOCK of the file being scanned and it
+needs to take the IOLOCK of the file at the other end of the directory link.
+If the directory tree is corrupt because it contains a cycle, ``xfs_scrub``
+cannot use the regular inode locking functions and avoid becoming trapped in an

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+ABBA deadlock.
+
+Solving both of these problems is straightforward -- any time online

fsck
+needs to take a second lock of the same class, it uses trylock to avoid an ABBA

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+deadlock.
+If the trylock fails, scrub drops all inode locks and use trylock

loops to

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+(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

Documentation/filesystems/xfs-online-fsck-design.rst +9 -0
+react accordingly.
+
+.. _dirparent:
+
+Case Study: Finding a Directory Parent
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Consider the directory parent pointer repair code as an example.
+Online fsck must verify that the dotdot dirent of a directory points

up to a
+parent directory, and that the parent directory contains exactly one dirent

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+pointing down to the child directory.
+Fully validating this relationship (and repairing it if possible)

requires a
+walk of every directory on the filesystem while holding the child locked, and

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+while updates to the directory tree are being made.
+The coordinated inode scan provides a way to walk the filesystem

without the

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+possibility of missing an inode.
+The child directory is kept locked to prevent updates to the dotdot

dirent, but
+if the scanner fails to lock a parent, it can drop and relock both the child

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+and the prospective parent.
+If the dotdot entry changes while the directory is unlocked, then a

move or
+rename operation must have changed the child's parentage, and the scan can

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+exit early.
+
+The proposed patchset is the
+`directory repair
+<

https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/
log/?h=repair-dirs>`_

Documentation/filesystems/xfs-online-fsck-design.rst +8 -0
+series.
+
+.. _fshooks:
+
+Filesystem Hooks
+`````````````````
+
+The second piece of support that online fsck 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

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+in a dynamic environment.
+Two pieces of Linux kernel infrastructure enable online fsck to

monitor regular
+filesystem operations: filesystem hooks and :ref:static keys<jump_labels>.

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+Filesystem hooks convey information about an ongoing filesystem

operation to

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+a downstream consumer.
+In this case, the downstream consumer is always an online fsck

function.
+Because multiple fsck functions can run in parallel, online fsck uses the Linux
+notifier call chain facility to dispatch updates to any number of interested

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+fsck processes.
+Call chains are a dynamic list, which means that they can be

configured at

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+run time.
+Because these hooks are private to the XFS module, the information

passed along
+contains exactly what the checking function needs to update its observations.

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+The current implementation of XFS hooks uses SRCU notifier chains to

reduce the

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+impact to highly threaded workloads.
+Regular blocking notifier chains use a rwsem and seem to have a much

lower

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+overhead for single-threaded applications.
+However, it may turn out that the combination of blocking chains and

static

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+keys are a more performant combination; more study is needed here.
+
+The following pieces are necessary to hook a certain point in the

filesystem:
+
+- A ``struct xfs_hooks`` object must be embedded in a convenient place such as
+  a well-known incore filesystem object.
+
+- Each hook must define an action code and a structure containing more context
+  about the action.
+
+- Hook providers should provide appropriate wrapper functions and structs
+  around the ``xfs_hooks`` and ``xfs_hook`` objects to take advantage of type
+  checking to ensure correct usage.
+
+- A callsite in the regular filesystem code must be chosen to call +  ``xfs_hooks_call`` with the action code and data structure. +  This place should be adjacent to (and not earlier than) the place where
+  the filesystem update is committed to the transaction. +  In general, when the filesystem calls a hook chain, it should be able to
+  handle sleeping and should not be vulnerable to memory reclaim or locking
+  recursion.
+  However, the exact requirements are very dependent on the context of the hook
+  caller and the callee.
+
+- The online fsck function should define a structure to hold scan data, a lock
+  to coordinate access to the scan data, and a ``struct xfs_hook`` object.
+  The scanner function and the regular filesystem code must acquire resources
+  in the same order; see the next section for details.
+
+- The online fsck code must contain a C function to catch the hook action code
+  and data structure.
+  If the object being updated has already been visited by the scan, then the
+  hook information must be applied to the scan data.

Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+
+- Prior to unlocking inodes to start the scan, online fsck must call
+  ``xfs_hooks_setup`` to initialize the ``struct xfs_hook``, and
+  ``xfs_hooks_add`` to enable the hook.
+
+- Online fsck must call ``xfs_hooks_del`` to disable the hook once

the scan is
+  complete.

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+The number of hooks should be kept to a minimum to reduce

complexity.
+Static keys are used to reduce the overhead of filesystem hooks to nearly

Documentation/filesystems/xfs-online-fsck-design.rst +8 -0
+zero when online fsck is not running.
+
+.. _liveupdate:
+
+Live Updates During a Scan
+``````````````````````````
+
+The code paths of the online fsck scanning code and the

:ref:hooked<fshooks>

Documentation/filesystems/xfs-online-fsck-design.rst +29 -0
+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

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+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.
+
+- Scrub 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 (``xchk_iscan_want_live_update``)
+  for this.
+
+- Scrub hook functions must not change the caller's state, including the
+  transaction that it is running.
+  They must not acquire any resources that might conflict with the filesystem
+  function being hooked.
+
+- The hook function can abort the inode scan to avoid breaking the other rules.

Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+
+The inode scan APIs are pretty simple:
+
+- ``xchk_iscan_start`` starts a scan
+
+- ``xchk_iscan_iter`` grabs a reference to the next inode in the

scan or
+  returns zero if there is nothing left to scan
+
+- ``xchk_iscan_want_live_update`` to decide if an inode has already been
+  visited in the scan.
+  This is critical for hook functions to decide if they need to update the
+  in-memory scan information.
+
+- ``xchk_iscan_mark_visited`` to mark an inode as having been visited in the
+  scan

Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+
+- ``xchk_iscan_finish`` to finish the scan
+
+The proposed patches are at the start of the
+`online quotacheck
+<
Quoted 3 lines

https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/
log/?h=repair-quota>`_
+series.

Wrong link? This looks like it goes to the section below.

Quoted 85 lines
Documentation/filesystems/xfs-online-fsck-design.rst +7 -0
+
+.. _quotacheck:
+
+Case Study: Quota Counter Checking
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+It is useful to compare the mount time quotacheck code to the online

repair

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+quotacheck code.
+Mount time quotacheck does not have to contend with concurrent

operations, so

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+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.

Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+
+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.

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+
+4. Write the buffer list to disk.
+
+Like most online fsck functions, online quotacheck can't write to

regular
+filesystem objects until the newly collected metadata reflect all filesystem

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+state.
+Therefore, online quotacheck records file resource usage to a shadow

dquot
+index implemented with a sparse ``xfarray``, and only writes to the real dquots

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+once the scan is complete.
+Handling transactional updates is tricky because quota resource

usage updates

Documentation/filesystems/xfs-online-fsck-design.rst +20 -0
+are handled in phases to minimize contention on dquots:
+
+1. The inodes involved are joined and locked to a transaction.
+
+2. For each dquot attached to the file:
+
+   a. The dquot is locked.
+
+   b. A quota reservation is added to the dquot's resource usage.
+      The reservation is recorded in the transaction.
+
+   c. The dquot is unlocked.
+
+3. Changes in actual quota usage are tracked in the transaction.
+
+4. At transaction commit time, each dquot is examined again:
+
+   a. The dquot is locked again.
+
+   b. Quota usage changes are logged and unused reservation is given

back to
+      the dquot.

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+
+   c. The dquot is unlocked.
+
+For online quotacheck, hooks are placed in steps 2 and 4.
+The step 2 hook creates a shadow version of the transaction dquot

context

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+(``dqtrx``) that operates in a similar manner to the regular code.
+The step 4 hook commits the shadow ``dqtrx`` changes to the shadow

dquots.
+Notice that both hooks are called with the inode locked, which is how the

Documentation/filesystems/xfs-online-fsck-design.rst +11 -0
+live update coordinates with the inode scanner.
+
+The quotacheck scan looks like this:
+
+1. Set up a coordinated inode scan.
+
+2. For each inode returned by the inode scan iterator:
+
+   a. Grab and lock the inode.
+
+   b. Determine that inode's resource usage (data blocks, inode
Quoted 2 lines

counts,
+      realtime blocks)

nit: move this list to the first appearance of "resource usage". Step 2 of the first list I think

Quoted 217 lines

and add that to the shadow dquots for the user, group, +      and project ids associated with the inode.

Documentation/filesystems/xfs-online-fsck-design.rst +8 -0
+
+   c. Unlock and release the inode.
+
+3. For each dquot in the system:
+
+   a. Grab and lock the dquot.
+
+   b. Check the dquot against the shadow dquots created by the scan

and updated
+      by the live hooks.

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+Live updates are key to being able to walk every quota record

without

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+needing to hold any locks for a long duration.
+If repairs are desired, the real and shadow dquots are locked and

their

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+resource counts are set to the values in the shadow dquot.
+
+The proposed patchset is the
+`online quotacheck
+<

https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/
log/?h=repair-quota>`_

Documentation/filesystems/xfs-online-fsck-design.rst +9 -0
+series.
+
+.. _nlinks:
+
+Case Study: File Link Count Checking
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+File link count checking also uses live update hooks.
+The coordinated inode scanner is used to visit all directories on

the
+filesystem, and per-file link count records are stored in a sparse ``xfarray``

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+indexed by inumber.
+During the scanning phase, each entry in a directory generates

observation

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+data as follows:
+
+1. If the entry is a dotdot (``'..'``) entry of the root directory,

the
+   directory's parent link count is bumped because the root directory's dotdot
+   entry is self referential.
+
+2. If the entry is a dotdot entry of a subdirectory, the parent's backref
+   count is bumped.
+
+3. If the entry is neither a dot nor a dotdot entry, the target file's parent
+   count is bumped.
+
+4. If the target is a subdirectory, the parent's child link count is bumped.

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+A crucial point to understand about how the link count inode scanner

interacts
+with the live update hooks is that the scan cursor tracks which *parent*

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+directories have been scanned.
+In other words, the live updates ignore any update about ``A → B``

when A has

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+not been scanned, even if B has been scanned.
+Furthermore, a subdirectory A with a dotdot entry pointing back to B

is
+accounted as a backref counter in the shadow data for A, since child dotdot

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+entries affect the parent's link count.
+Live update hooks are carefully placed in all parts of the

filesystem that
+create, change, or remove directory entries, since those operations involve

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+bumplink and droplink.
+
+For any file, the correct link count is the number of parents plus

the number

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+of child subdirectories.
+Non-directories never have children of any kind.
+The backref information is used to detect inconsistencies in the

number of
+links pointing to child subdirectories and the number of dotdot entries

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+pointing back.
+
+After the scan completes, the link count of each file can be checked

by locking

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+both the inode and the shadow data, and comparing the link counts.
+A second coordinated inode scan cursor is used for comparisons.
+Live updates are key to being able to walk every inode without

needing to hold

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+any locks between inodes.
+If repairs are desired, the inode's link count is set to the value

in the

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+shadow information.
+If no parents are found, the file must be :ref:`reparented

<orphanage>` to the

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+orphanage to prevent the file from being lost forever.
+
+The proposed patchset is the
+`file link count repair
+<

https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/
log/?h=scrub-nlinks>`_

Documentation/filesystems/xfs-online-fsck-design.rst +8 -0
+series.
+
+.. _rmap_repair:
+
+Case Study: Rebuilding Reverse Mapping Records
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Most repair functions follow the same pattern: lock filesystem

resources,
+walk the surviving ondisk metadata looking for replacement metadata records,
+and use an :ref:in-memory array <xfarray> to store the gathered observations.
+The primary advantage of this approach is the simplicity and modularity of the
+repair code -- code and data are entirely contained within the scrub module,
+do not require hooks in the main filesystem, and are usually the most efficient

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+in memory use.
+A secondary advantage of this repair approach is atomicity -- once

the kernel
+decides a structure is corrupt, no other threads can access the metadata until

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+the kernel finishes repairing and revalidating the metadata.
+
+For repairs going on within a shard of the filesystem, these

advantages
+outweigh the delays inherent in locking the shard while repairing parts of the

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+shard.
+Unfortunately, repairs to the reverse mapping btree cannot use the

"standard"
+btree repair strategy because it must scan every space mapping of every fork of

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+every file in the filesystem, and the filesystem cannot stop.
+Therefore, rmap repair foregoes atomicity between scrub and repair.
+It combines a :ref:`coordinated inode scanner <iscan>`, :ref:`live

update hooks
+<liveupdate>, and an :ref:in-memory rmap btree <xfbtree>` to complete the

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+scan for reverse mapping records.
+
+1. Set up an xfbtree to stage rmap records.
+
+2. While holding the locks on the AGI and AGF buffers acquired

during the
+   scrub, generate reverse mappings for all AG metadata: inodes, btrees, CoW
+   staging extents, and the internal log.

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+
+3. Set up an inode scanner.
+
+4. Hook into rmap updates for the AG being repaired so that the live

scan data
+   can receive updates to the rmap btree from the rest of the filesystem during
+   the file scan.

Documentation/filesystems/xfs-online-fsck-design.rst +10 -0
+
+5. For each space mapping found in either fork of each file scanned,
+   decide if the mapping matches the AG of interest.
+   If so:
+
+   a. Create a btree cursor for the in-memory btree.
+
+   b. Use the rmap code to add the record to the in-memory btree.
+
+   c. Use the :ref:`special commit function <xfbtree_commit>` to

write the
+      xfbtree changes to the xfile.
+
+6. For each live update received via the hook, decide if the owner has already
+   been scanned.
+   If so, apply the live update into the scan data:

Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+
+   a. Create a btree cursor for the in-memory btree.
+
+   b. Replay the operation into the in-memory btree.
+
+   c. Use the :ref:`special commit function <xfbtree_commit>` to

write the
+      xfbtree changes to the xfile.
+      This is performed with an empty transaction to avoid changing the
+      caller's state.
+
+7. When the inode scan finishes, create a new scrub transaction and relock the
+   two AG headers.
+
+8. Compute the new btree geometry using the number of rmap records in the
+   shadow btree, like all other btree rebuilding functions.

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+
+9. Allocate the number of blocks computed in the previous step.
+
+10. Perform the usual btree bulk loading and commit to install the

new rmap
+    btree.
+
+11. Reap the old rmap btree blocks as discussed in the case study about how
+    to :ref:reap after rmap btree repair <rmap_reap>.

Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+
+12. Free the xfbtree now that it not needed.
+
+The proposed patchset is the
+`rmap repair
+<
Quoted 4 lines

https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/
log/?h=repair-rmap-btree>`_
+series.

Mostly looks good nits aside, I do sort of wonder if this patch would do better to appear before patch 6 (or move 6 down), since it gets into more challenges concerning locks and hooks, where as here we are mostly discussing what they are and how they work. So it might build better to move this patch up a little.

Allison

#46 lore raw

Re: [PATCH 10/14] xfs: document full filesystem scans for online fsck

Quoted 172 lines · Allison Henderson
Quoted 171 lines · Darrick J. Wong

From: Darrick J. Wong <[email protected]>

Certain parts of the online fsck code need to scan every file in the entire filesystem.  It is not acceptable to block the entire filesystem
while this happens, which means that we need to be clever in allowing scans to coordinate with ongoing filesystem updates.  We also need to hook the filesystem so that regular updates propagate to the staging records.

---
 .../filesystems/xfs-online-fsck-design.rst         |  677
++++++++++++++++++++

 1 file changed, 677 insertions(+)
Documentation/filesystems/xfs-online-fsck-design.rst +0 -0
index a658da8fe4ae..c0f08a773f08 100644
@@ -3018,3 +3018,680 @@ The proposed patchset is the

 `summary counter cleanup
 <
https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/
log/?h=repair-fscounters>`_
 series.

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+
+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

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+what's recorded on disk.
+Like every other type of online repair, repairs are made by writing

those
+observations to disk in a replacement structure and committing it atomically.
+However, it is not practical to shut down the entire filesystem to examine
+hundreds of billions of files because the downtime would be excessive.
+Therefore, online fsck must build the infrastructure to manage a live scan of

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+all the files in the filesystem.
+There are two questions that need to be solved to perform a live

walk:

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+
+- How does scrub manage the scan while it is collecting data?
+
+- How does the scan keep abreast of changes being made to the system

by other
+  threads?

Documentation/filesystems/xfs-online-fsck-design.rst +7 -0
+
+.. _iscan:
+
+Coordinated Inode Scans
+```````````````````````
+
+In the original Unix filesystems of the 1970s, each directory entry

contained
+an index number (*inumber*) which was used as an index into on ondisk array
+(*itable*) of fixed-size records (*inodes*) describing a file's attributes and

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+its data block mapping.
+This system is described by J. Lions, `"inode (5659)"
+<http://www.lemis.com/grog/Documentation/Lions/>`_ in *Lions'

Commentary on
+UNIX, 6th Edition*, (Dept. of Computer Science, the University of New South
+Wales, November 1977), pp. 18-2; and later by D. Ritchie and K. Thompson,
+"Implementation of the File System" +<https://archive.org/details/bstj57-6-1905/page/n8/mode/1up>_, from *The UNIX
+Time-Sharing System*, (The Bell System Technical Journal, July 1978), pp.
+1913-4.

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+XFS retains most of this design, except now inumbers are search keys

over all

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+the space in the data section filesystem.
+They form a continuous keyspace that can be expressed as a 64-bit

integer,
+though the inodes themselves are sparsely distributed within the keyspace.
+Scans proceed in a linear fashion across the inumber keyspace, starting from
+``0x0`` and ending at ``0xFFFFFFFFFFFFFFFF``. +Naturally, a scan through a keyspace requires a scan cursor object to track the

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+scan progress.
+Because this keyspace is sparse, this cursor contains two parts.
+The first part of this scan cursor object tracks the inode that will

be

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+examined next; call this the examination cursor.
+Somewhat less obviously, the scan cursor object must also track

which parts of
+the keyspace have already been visited, which is critical for deciding if a
+concurrent filesystem update needs to be incorporated into the scan data.

Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+Call this the visited inode cursor.
+
+Advancing the scan cursor is a multi-step process encapsulated in
+``xchk_iscan_iter``:
+
+1. Lock the AGI buffer of the AG containing the inode pointed to by

the visited
+   inode cursor.
+   This guarantee that inodes in this AG cannot be allocated or freed while
+   advancing the cursor.
+
+2. Use the per-AG inode btree to look up the next inumber after the one that
+   was just visited, since it may not be keyspace adjacent.

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+
+3. If there are no more inodes left in this AG:
+
+   a. Move the examination cursor to the point of the inumber

keyspace that
+      corresponds to the start of the next AG.
+
+   b. Adjust the visited inode cursor to indicate that it has "visited" the
+      last possible inode in the current AG's inode keyspace. +      XFS inumbers are segmented, so the cursor needs to be marked as having
+      visited the entire keyspace up to just before the start of the next AG's
+      inode keyspace.
+
+   c. Unlock the AGI and return to step 1 if there are unexamined AGs in the
+      filesystem.
+
+   d. If there are no more AGs to examine, set both cursors to the end of the
+      inumber keyspace.
+      The scan is now complete.

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+
+4. Otherwise, there is at least one more inode to scan in this AG:
+
+   a. Move the examination cursor ahead to the next inode marked as

allocated
+      by the inode btree.
+
+   b. Adjust the visited inode cursor to point to the inode just prior to where
+      the examination cursor is now.
+      Because the scanner holds the AGI buffer lock, no inodes could have been
+      created in the part of the inode keyspace that the visited inode cursor
+      just advanced.
+
+5. Get the incore inode for the inumber of the examination cursor. +   By maintaining the AGI buffer lock until this point, the scanner knows that
+   it was safe to advance the examination cursor across the entire keyspace,
+   and that it has stabilized this next inode so that it cannot disappear from
+   the filesystem until the scan releases the incore inode. +
+6. Drop the AGI lock and return the incore inode to the caller.

Quoted 8 lines

Documentation/filesystems/xfs-online-fsck-design.rst The proposed patchset is the · line 3125

Quoted 4 lines
Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+
+Online fsck functions scan all files in the filesystem as follows:
+
+1. Start a scan by calling ``xchk_iscan_start``.

Hmm, I actually did not find xchk_iscan_start in the below branch, I found xchk_iscan_iter in "xfs: implement live inode scan for scrub", but it doesnt look like anything uses it yet, at least not in that branch.

<nod> The topic branch linked below has the implementation, but no users. The first user is online quotacheck, which is in the next branch after that:

https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/log/?h=repair-quotacheck

Specifically, this patch:

https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/commit/?h=repair-quotacheck&id=3640515b9282514d91a407b6aa8d8b73caa123c5

I'll restate what you probably saw in the commit message for this email discussion:

This "one branch to introduce a new infrastructure and a second branch to actually use it" pattern is a result of reviewer requests for smaller more focused branches. This has turned out to be useful in practice because it's easier to move just these pieces up and down in the branch as needed. The inode scan was originally developed for rmapbt repair (which comes *much* later) and moved it up once I realized that quotacheck has far fewer dependencies and hence all of this could come earlier.

You're right that this section ought to point to an actual user of the functionality. Will fix. :)

Quoted 2 lines

Also, it took me a bit to figure out that "initial user" meant "calling function"

Er... are you talking about the sentence "...new code is split out as a separate patch from its initial user" in the patch commit message?

Maybe I should reword that:

"This new code is a separate patch from the patches adding callers for the sake of enabling the author to move patches around his tree..."

Quoted 37 lines
Quoted 37 lines

+
+2. Advance the scan cursor (``xchk_iscan_iter``) to get the next inode.
+   If one is provided:

Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+
+   a. Lock the inode to prevent updates during the scan.
+
+   b. Scan the inode.
+
+   c. While still holding the inode lock, adjust the visited inode

cursor
+      (``xchk_iscan_mark_visited``) to point to this inode.

Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+
+   d. Unlock and release the inode.
+
+8. Call ``xchk_iscan_finish`` to complete the scan.
+
+There are subtleties with the inode cache that complicate grabbing

the incore

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+inode for the caller.
+Obviously, it is an absolute requirement that the inode metadata be

consistent

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+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

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+back into a loadable state.
+
+The proposed patches are the
+`inode scanner
+<

https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/
log/?h=scrub-iscan>`_

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+series.
+
+Inode Management
Quoted 8 lines
Quoted 7 lines

+````````````````

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+In regular filesystem code, references to allocated XFS incore

inodes are
+always obtained (``xfs_iget``) outside of transaction context because the
+creation of the incore context for ane xisting file does not require

an existing

Corrected, thank you.

Quoted 145 lines
Quoted 143 lines

metadata

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+updates.
+However, it is important to note that references to incore inodes

obtained as
+part of file creation must be performed in transaction context because the
+filesystem must ensure the atomicity of the ondisk inode btree index updates

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+and the initialization of the actual ondisk inode.
+
+References to incore inodes are always released (``xfs_irele``)

outside of
+transaction context because there are a handful of activities that might

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+require ondisk updates:
+
+- The VFS may decide to kick off writeback as part of a

``DONTCACHE`` inode
+  release.

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+
+- 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 and freeing the inode.

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+
+These activities are collectively called inode inactivation.
+Inactivation has two parts -- the VFS part, which initiates

writeback on all
+dirty file pages, and the XFS part, which cleans up XFS-specific information

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+and frees the inode if it was unlinked.
+If the inode is unlinked (or unconnected after a file handle

operation), the

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+kernel drops the inode into the inactivation machinery immediately.
+
+During normal operation, resource acquisition for an update follows

this order

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+to avoid deadlocks:
+
+1. Inode reference (``iget``).
+
+2. Filesystem freeze protection, if repairing

(``mnt_want_write_file``).

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+
+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.

Documentation/filesystems/xfs-online-fsck-design.rst +19 -0
+
+5. Log feature enablement.
+
+6. Transaction log space grant.
+
+7. Space on the data and realtime devices for the transaction.
+
+8. Incore dquot references, if a file is being repaired.
+   Note that they are not locked, merely acquired.
+
+9. Inode ``ILOCK`` for file metadata updates.
+
+10. AG header buffer locks / Realtime metadata inode ILOCK.
+
+11. Realtime metadata buffer locks, if applicable.
+
+12. Extent mapping btree blocks, if applicable.
+
+Resources are often released in the reverse order, though this is

not required.
+However, online fsck differs from regular XFS operations because it may examine
+an object that normally is acquired in a later stage of the locking order, and
+then decide to cross-reference the object with an object that is acquired

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+earlier in the order.
+The next few sections detail the specific ways in which online fsck

takes care

Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+to avoid deadlocks.
+
+iget and irele During a Scrub
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+An inode scan performed on behalf of a scrub operation runs in

transaction

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+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, as long as all of the bound resources are acquired

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+before the inode reference in the regular filesystem.
+
+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

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+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

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+inactivation machinery immediately.
+
+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

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+transaction, and XFS does not support nesting transactions.
+On the other hand, if there is no scrub transaction, it is desirable

to drop

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+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

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+behavior.
+
+Proposed patchsets include fixing
+`scrub iget usage
+<

https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/
log/?h=scrub-iget-fixes>`_ and
+`dir iget usage
+<
https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/
log/?h=scrub-dir-iget-fixes>`_.

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+
+Locking Inodes
+^^^^^^^^^^^^^^
+
+In regular filesystem code, the VFS and XFS will acquire multiple

IOLOCK locks
+in a well-known order: parent → child when updating the directory tree, and
+``struct inode`` address order otherwise.
+For regular files, the MMAPLOCK can be acquired after the IOLOCK to stop page

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+faults.
+If two MMAPLOCKs must be acquired, they are acquired in 
Quoted 5 lines
Quoted 2 lines

``struct
+address_space`` order.

the order of their memory address

?

Urghg. I think I need to clarify this more:

"...they are acquired in numerical order of the addresses of their ``struct address_space`` objects."

See filemap_invalidate_lock_two.

Quoted 266 lines
Quoted 266 lines

+Due to the structure of existing filesystem code, IOLOCKs and MMAPLOCKs must be

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+acquired before transactions are allocated.
+If two ILOCKs must be acquired, they are acquired in inumber order.
+
+Inode lock acquisition must be done carefully during a coordinated

inode scan.
+Online fsck cannot abide these conventions, because for a directory tree
+scanner, the scrub process holds the IOLOCK of the file being scanned and it
+needs to take the IOLOCK of the file at the other end of the directory link.
+If the directory tree is corrupt because it contains a cycle, ``xfs_scrub``
+cannot use the regular inode locking functions and avoid becoming trapped in an

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+ABBA deadlock.
+
+Solving both of these problems is straightforward -- any time online

fsck
+needs to take a second lock of the same class, it uses trylock to avoid an ABBA

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+deadlock.
+If the trylock fails, scrub drops all inode locks and use trylock

loops to

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+(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

Documentation/filesystems/xfs-online-fsck-design.rst +9 -0
+react accordingly.
+
+.. _dirparent:
+
+Case Study: Finding a Directory Parent
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Consider the directory parent pointer repair code as an example.
+Online fsck must verify that the dotdot dirent of a directory points

up to a
+parent directory, and that the parent directory contains exactly one dirent

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+pointing down to the child directory.
+Fully validating this relationship (and repairing it if possible)

requires a
+walk of every directory on the filesystem while holding the child locked, and

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+while updates to the directory tree are being made.
+The coordinated inode scan provides a way to walk the filesystem

without the

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+possibility of missing an inode.
+The child directory is kept locked to prevent updates to the dotdot

dirent, but
+if the scanner fails to lock a parent, it can drop and relock both the child

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+and the prospective parent.
+If the dotdot entry changes while the directory is unlocked, then a

move or
+rename operation must have changed the child's parentage, and the scan can

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+exit early.
+
+The proposed patchset is the
+`directory repair
+<

https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/
log/?h=repair-dirs>`_

Documentation/filesystems/xfs-online-fsck-design.rst +8 -0
+series.
+
+.. _fshooks:
+
+Filesystem Hooks
+`````````````````
+
+The second piece of support that online fsck 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

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+in a dynamic environment.
+Two pieces of Linux kernel infrastructure enable online fsck to

monitor regular
+filesystem operations: filesystem hooks and :ref:static keys<jump_labels>.

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+Filesystem hooks convey information about an ongoing filesystem

operation to

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+a downstream consumer.
+In this case, the downstream consumer is always an online fsck

function.
+Because multiple fsck functions can run in parallel, online fsck uses the Linux
+notifier call chain facility to dispatch updates to any number of interested

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+fsck processes.
+Call chains are a dynamic list, which means that they can be

configured at

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+run time.
+Because these hooks are private to the XFS module, the information

passed along
+contains exactly what the checking function needs to update its observations.

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+The current implementation of XFS hooks uses SRCU notifier chains to

reduce the

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+impact to highly threaded workloads.
+Regular blocking notifier chains use a rwsem and seem to have a much

lower

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+overhead for single-threaded applications.
+However, it may turn out that the combination of blocking chains and

static

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+keys are a more performant combination; more study is needed here.
+
+The following pieces are necessary to hook a certain point in the

filesystem:
+
+- A ``struct xfs_hooks`` object must be embedded in a convenient place such as
+  a well-known incore filesystem object.
+
+- Each hook must define an action code and a structure containing more context
+  about the action.
+
+- Hook providers should provide appropriate wrapper functions and structs
+  around the ``xfs_hooks`` and ``xfs_hook`` objects to take advantage of type
+  checking to ensure correct usage.
+
+- A callsite in the regular filesystem code must be chosen to call +  ``xfs_hooks_call`` with the action code and data structure. +  This place should be adjacent to (and not earlier than) the place where
+  the filesystem update is committed to the transaction. +  In general, when the filesystem calls a hook chain, it should be able to
+  handle sleeping and should not be vulnerable to memory reclaim or locking
+  recursion.
+  However, the exact requirements are very dependent on the context of the hook
+  caller and the callee.
+
+- The online fsck function should define a structure to hold scan data, a lock
+  to coordinate access to the scan data, and a ``struct xfs_hook`` object.
+  The scanner function and the regular filesystem code must acquire resources
+  in the same order; see the next section for details.
+
+- The online fsck code must contain a C function to catch the hook action code
+  and data structure.
+  If the object being updated has already been visited by the scan, then the
+  hook information must be applied to the scan data.

Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+
+- Prior to unlocking inodes to start the scan, online fsck must call
+  ``xfs_hooks_setup`` to initialize the ``struct xfs_hook``, and
+  ``xfs_hooks_add`` to enable the hook.
+
+- Online fsck must call ``xfs_hooks_del`` to disable the hook once

the scan is
+  complete.

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+The number of hooks should be kept to a minimum to reduce

complexity.
+Static keys are used to reduce the overhead of filesystem hooks to nearly

Documentation/filesystems/xfs-online-fsck-design.rst +8 -0
+zero when online fsck is not running.
+
+.. _liveupdate:
+
+Live Updates During a Scan
+``````````````````````````
+
+The code paths of the online fsck scanning code and the

:ref:hooked<fshooks>

Documentation/filesystems/xfs-online-fsck-design.rst +29 -0
+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

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+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.
+
+- Scrub 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 (``xchk_iscan_want_live_update``)
+  for this.
+
+- Scrub hook functions must not change the caller's state, including the
+  transaction that it is running.
+  They must not acquire any resources that might conflict with the filesystem
+  function being hooked.
+
+- The hook function can abort the inode scan to avoid breaking the other rules.

Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+
+The inode scan APIs are pretty simple:
+
+- ``xchk_iscan_start`` starts a scan
+
+- ``xchk_iscan_iter`` grabs a reference to the next inode in the

scan or
+  returns zero if there is nothing left to scan
+
+- ``xchk_iscan_want_live_update`` to decide if an inode has already been
+  visited in the scan.
+  This is critical for hook functions to decide if they need to update the
+  in-memory scan information.
+
+- ``xchk_iscan_mark_visited`` to mark an inode as having been visited in the
+  scan
+
+- ``xchk_iscan_finish`` to finish the scan

Quoted 8 lines
Quoted 7 lines
Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+
+The proposed patches are at the start of the
+`online quotacheck
+<

https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/
log/?h=repair-quota>`_
+series.

Wrong link? This looks like it goes to the section below.

Oops. This one should link to scrub-iscan, and the next one should link to repair-quotacheck.

Quoted 81 lines
Quoted 81 lines
Documentation/filesystems/xfs-online-fsck-design.rst +7 -0
+
+.. _quotacheck:
+
+Case Study: Quota Counter Checking
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+It is useful to compare the mount time quotacheck code to the online

repair

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+quotacheck code.
+Mount time quotacheck does not have to contend with concurrent

operations, so

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+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.

Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+
+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.

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+
+4. Write the buffer list to disk.
+
+Like most online fsck functions, online quotacheck can't write to

regular
+filesystem objects until the newly collected metadata reflect all filesystem

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+state.
+Therefore, online quotacheck records file resource usage to a shadow

dquot
+index implemented with a sparse ``xfarray``, and only writes to the real dquots

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+once the scan is complete.
+Handling transactional updates is tricky because quota resource

usage updates

Documentation/filesystems/xfs-online-fsck-design.rst +20 -0
+are handled in phases to minimize contention on dquots:
+
+1. The inodes involved are joined and locked to a transaction.
+
+2. For each dquot attached to the file:
+
+   a. The dquot is locked.
+
+   b. A quota reservation is added to the dquot's resource usage.
+      The reservation is recorded in the transaction.
+
+   c. The dquot is unlocked.
+
+3. Changes in actual quota usage are tracked in the transaction.
+
+4. At transaction commit time, each dquot is examined again:
+
+   a. The dquot is locked again.
+
+   b. Quota usage changes are logged and unused reservation is given

back to
+      the dquot.

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+
+   c. The dquot is unlocked.
+
+For online quotacheck, hooks are placed in steps 2 and 4.
+The step 2 hook creates a shadow version of the transaction dquot

context

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+(``dqtrx``) that operates in a similar manner to the regular code.
+The step 4 hook commits the shadow ``dqtrx`` changes to the shadow

dquots.
+Notice that both hooks are called with the inode locked, which is how the

Documentation/filesystems/xfs-online-fsck-design.rst +7 -0
+live update coordinates with the inode scanner.
+
+The quotacheck scan looks like this:
+
+1. Set up a coordinated inode scan.
+
+2. For each inode returned by the inode scan iterator:
Quoted 8 lines
Quoted 6 lines
Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+
+   a. Grab and lock the inode.
+
+   b. Determine that inode's resource usage (data blocks, inode

counts,
+      realtime blocks)

nit: move this list to the first appearance of "resource usage". Step 2 of the first list I think

I don't understand this proposed change. Are you talking about "2. For each dquot attached to the file:" above? That list describes the steps taken by regular code wanting to allocate file space that's accounted to quotas. This list describes what online quotacheck does. The two don't mix.

Quoted 17 lines
Quoted 17 lines

and add that to the shadow dquots for the user, group, +      and project ids associated with the inode.

Documentation/filesystems/xfs-online-fsck-design.rst +8 -0
+
+   c. Unlock and release the inode.
+
+3. For each dquot in the system:
+
+   a. Grab and lock the dquot.
+
+   b. Check the dquot against the shadow dquots created by the scan

and updated
+      by the live hooks.

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+Live updates are key to being able to walk every quota record

without

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+needing to hold any locks for a long duration.
+If repairs are desired, the real and shadow dquots are locked and
Quoted 8 lines
Quoted 8 lines

their

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+resource counts are set to the values in the shadow dquot.
+
+The proposed patchset is the
+`online quotacheck
+<

https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/
log/?h=repair-quota>`_

Changed from repair-quota to repair-quotacheck.

Quoted 194 lines
Quoted 194 lines
Documentation/filesystems/xfs-online-fsck-design.rst +9 -0
+series.
+
+.. _nlinks:
+
+Case Study: File Link Count Checking
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+File link count checking also uses live update hooks.
+The coordinated inode scanner is used to visit all directories on

the
+filesystem, and per-file link count records are stored in a sparse ``xfarray``

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+indexed by inumber.
+During the scanning phase, each entry in a directory generates

observation

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+data as follows:
+
+1. If the entry is a dotdot (``'..'``) entry of the root directory,

the
+   directory's parent link count is bumped because the root directory's dotdot
+   entry is self referential.
+
+2. If the entry is a dotdot entry of a subdirectory, the parent's backref
+   count is bumped.
+
+3. If the entry is neither a dot nor a dotdot entry, the target file's parent
+   count is bumped.
+
+4. If the target is a subdirectory, the parent's child link count is bumped.

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+A crucial point to understand about how the link count inode scanner

interacts
+with the live update hooks is that the scan cursor tracks which *parent*

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+directories have been scanned.
+In other words, the live updates ignore any update about ``A → B``

when A has

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+not been scanned, even if B has been scanned.
+Furthermore, a subdirectory A with a dotdot entry pointing back to B

is
+accounted as a backref counter in the shadow data for A, since child dotdot

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+entries affect the parent's link count.
+Live update hooks are carefully placed in all parts of the

filesystem that
+create, change, or remove directory entries, since those operations involve

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+bumplink and droplink.
+
+For any file, the correct link count is the number of parents plus

the number

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+of child subdirectories.
+Non-directories never have children of any kind.
+The backref information is used to detect inconsistencies in the

number of
+links pointing to child subdirectories and the number of dotdot entries

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+pointing back.
+
+After the scan completes, the link count of each file can be checked

by locking

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+both the inode and the shadow data, and comparing the link counts.
+A second coordinated inode scan cursor is used for comparisons.
+Live updates are key to being able to walk every inode without

needing to hold

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+any locks between inodes.
+If repairs are desired, the inode's link count is set to the value

in the

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+shadow information.
+If no parents are found, the file must be :ref:`reparented

<orphanage>` to the

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+orphanage to prevent the file from being lost forever.
+
+The proposed patchset is the
+`file link count repair
+<

https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/
log/?h=scrub-nlinks>`_

Documentation/filesystems/xfs-online-fsck-design.rst +8 -0
+series.
+
+.. _rmap_repair:
+
+Case Study: Rebuilding Reverse Mapping Records
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Most repair functions follow the same pattern: lock filesystem

resources,
+walk the surviving ondisk metadata looking for replacement metadata records,
+and use an :ref:in-memory array <xfarray> to store the gathered observations.
+The primary advantage of this approach is the simplicity and modularity of the
+repair code -- code and data are entirely contained within the scrub module,
+do not require hooks in the main filesystem, and are usually the most efficient

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+in memory use.
+A secondary advantage of this repair approach is atomicity -- once

the kernel
+decides a structure is corrupt, no other threads can access the metadata until

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+the kernel finishes repairing and revalidating the metadata.
+
+For repairs going on within a shard of the filesystem, these

advantages
+outweigh the delays inherent in locking the shard while repairing parts of the

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+shard.
+Unfortunately, repairs to the reverse mapping btree cannot use the

"standard"
+btree repair strategy because it must scan every space mapping of every fork of

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+every file in the filesystem, and the filesystem cannot stop.
+Therefore, rmap repair foregoes atomicity between scrub and repair.
+It combines a :ref:`coordinated inode scanner <iscan>`, :ref:`live

update hooks
+<liveupdate>, and an :ref:in-memory rmap btree <xfbtree>` to complete the

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+scan for reverse mapping records.
+
+1. Set up an xfbtree to stage rmap records.
+
+2. While holding the locks on the AGI and AGF buffers acquired

during the
+   scrub, generate reverse mappings for all AG metadata: inodes, btrees, CoW
+   staging extents, and the internal log.

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+
+3. Set up an inode scanner.
+
+4. Hook into rmap updates for the AG being repaired so that the live

scan data
+   can receive updates to the rmap btree from the rest of the filesystem during
+   the file scan.

Documentation/filesystems/xfs-online-fsck-design.rst +10 -0
+
+5. For each space mapping found in either fork of each file scanned,
+   decide if the mapping matches the AG of interest.
+   If so:
+
+   a. Create a btree cursor for the in-memory btree.
+
+   b. Use the rmap code to add the record to the in-memory btree.
+
+   c. Use the :ref:`special commit function <xfbtree_commit>` to

write the
+      xfbtree changes to the xfile.
+
+6. For each live update received via the hook, decide if the owner has already
+   been scanned.
+   If so, apply the live update into the scan data:

Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+
+   a. Create a btree cursor for the in-memory btree.
+
+   b. Replay the operation into the in-memory btree.
+
+   c. Use the :ref:`special commit function <xfbtree_commit>` to

write the
+      xfbtree changes to the xfile.
+      This is performed with an empty transaction to avoid changing the
+      caller's state.
+
+7. When the inode scan finishes, create a new scrub transaction and relock the
+   two AG headers.
+
+8. Compute the new btree geometry using the number of rmap records in the
+   shadow btree, like all other btree rebuilding functions.

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+
+9. Allocate the number of blocks computed in the previous step.
+
+10. Perform the usual btree bulk loading and commit to install the

new rmap
+    btree.
+
+11. Reap the old rmap btree blocks as discussed in the case study about how
+    to :ref:reap after rmap btree repair <rmap_reap>.

Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+
+12. Free the xfbtree now that it not needed.
+
+The proposed patchset is the
+`rmap repair
+<

https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/
log/?h=repair-rmap-btree>`_

Quoted 8 lines
Quoted 2 lines

+series.

Mostly looks good nits aside, I do sort of wonder if this patch would do better to appear before patch 6 (or move 6 down), since it gets into more challenges concerning locks and hooks, where as here we are mostly discussing what they are and how they work. So it might build better to move this patch up a little.

(I might be a tad confused here, bear with me.)

Patch 6, the section about eventual consistency?

Hmm. The intent drains exist to quiesce intent chains targeting specific AGs. It briefly mentions "fshooks" in the context of using jump labels to avoid the overhead of calling notify_all on the drain waitqueue when scrub isn't running. That's perhaps bad naming on my part, since the other "fshooks" are jump labels to avoid bouncing through the notifier chain code when scrub isn't running. The jump labels themselves are not hooks, they're structured dynamic code patching.

I probably should've named those something else. fsgates?

Or maybe you were talking specifically about "Case Study: Rebuilding Reverse Mapping Records"? In which case I remark that the case study needs both the intent drains to quiesce the AG and the live scans to work properly, which is why the case study of it couldn't come earlier. The intent drains section still ought to come before the refcountbt section, because it's the refcountbt scrubber that first hit the coordination problem.

Things are getting pretty awkward like this because there are sooo many interdependent pieces. :(

Regardless, thank you very much for slogging through.

--D

Quoted 2 lines

Allison

#47 lore raw

Re: [PATCH 10/14] xfs: document full filesystem scans for online fsck

Quoted 242 lines · Darrick J. Wong
Quoted 205 lines · Allison Henderson
Quoted 204 lines · Darrick J. Wong

From: Darrick J. Wong <[email protected]>

Certain parts of the online fsck code need to scan every file in the
entire filesystem.  It is not acceptable to block the entire filesystem
while this happens, which means that we need to be clever in allowing
scans to coordinate with ongoing filesystem updates.  We also need to
hook the filesystem so that regular updates propagate to the staging
records.

---
 .../filesystems/xfs-online-fsck-design.rst         |  677
++++++++++++++++++++

 1 file changed, 677 insertions(+)
Documentation/filesystems/xfs-online-fsck-design.rst +0 -0
index a658da8fe4ae..c0f08a773f08 100644
@@ -3018,3 +3018,680 @@ The proposed patchset is the

 `summary counter cleanup
 <
https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/
log/?h=repair-fscounters>`_
 series.

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+
+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

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+what's recorded on disk.
+Like every other type of online repair, repairs are made by

writing
those
+observations to disk in a replacement structure and committing it
atomically.
+However, it is not practical to shut down the entire filesystem to
examine
+hundreds of billions of files because the downtime would be excessive.
+Therefore, online fsck must build the infrastructure to manage a live scan of

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+all the files in the filesystem.
+There are two questions that need to be solved to perform a live

walk:

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+
+- How does scrub manage the scan while it is collecting data?
+
+- How does the scan keep abreast of changes being made to the

system
by other
+  threads?

Documentation/filesystems/xfs-online-fsck-design.rst +7 -0
+
+.. _iscan:
+
+Coordinated Inode Scans
+```````````````````````
+
+In the original Unix filesystems of the 1970s, each directory

entry
contained
+an index number (*inumber*) which was used as an index into on ondisk array
+(*itable*) of fixed-size records (*inodes*) describing a file's attributes and

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+its data block mapping.
+This system is described by J. Lions, `"inode (5659)"
+<http://www.lemis.com/grog/Documentation/Lions/>`_ in *Lions'

Commentary on
+UNIX, 6th Edition*, (Dept. of Computer Science, the University of
New South
+Wales, November 1977), pp. 18-2; and later by D. Ritchie and K. Thompson,
+"Implementation of the File System" +<https://archive.org/details/bstj57-6-1905/page/n8/mode/1up>_, from
*The UNIX
+Time-Sharing System*, (The Bell System Technical Journal, July 1978), pp.
+1913-4.

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+XFS retains most of this design, except now inumbers are search

keys
over all

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+the space in the data section filesystem.
+They form a continuous keyspace that can be expressed as a 64-

bit
integer,
+though the inodes themselves are sparsely distributed within the keyspace.
+Scans proceed in a linear fashion across the inumber keyspace, starting from
+``0x0`` and ending at ``0xFFFFFFFFFFFFFFFF``. +Naturally, a scan through a keyspace requires a scan cursor object
to track the

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+scan progress.
+Because this keyspace is sparse, this cursor contains two parts.
+The first part of this scan cursor object tracks the inode that

will
be

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+examined next; call this the examination cursor.
+Somewhat less obviously, the scan cursor object must also track

which parts of
+the keyspace have already been visited, which is critical for deciding if a
+concurrent filesystem update needs to be incorporated into the scan
data.

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+Call this the visited inode cursor.
+
+Advancing the scan cursor is a multi-step process encapsulated

in
+``xchk_iscan_iter``:
+
+1. Lock the AGI buffer of the AG containing the inode pointed to by
the visited
+   inode cursor.
+   This guarantee that inodes in this AG cannot be allocated or freed while
+   advancing the cursor.
+
+2. Use the per-AG inode btree to look up the next inumber after the
one that
+   was just visited, since it may not be keyspace adjacent.

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+
+3. If there are no more inodes left in this AG:
+
+   a. Move the examination cursor to the point of the inumber

keyspace that
+      corresponds to the start of the next AG.
+
+   b. Adjust the visited inode cursor to indicate that it has "visited" the
+      last possible inode in the current AG's inode keyspace. +      XFS inumbers are segmented, so the cursor needs to be marked
as having
+      visited the entire keyspace up to just before the start of the
next AG's
+      inode keyspace.
+
+   c. Unlock the AGI and return to step 1 if there are unexamined
AGs in the
+      filesystem.
+
+   d. If there are no more AGs to examine, set both cursors to the
end of the
+      inumber keyspace.
+      The scan is now complete.
+
+4. Otherwise, there is at least one more inode to scan in this AG:
+
+   a. Move the examination cursor ahead to the next inode marked as
allocated
+      by the inode btree.
+
+   b. Adjust the visited inode cursor to point to the inode just prior to where
+      the examination cursor is now.
+      Because the scanner holds the AGI buffer lock, no inodes could
have been
+      created in the part of the inode keyspace that the visited inode cursor
+      just advanced.
+
+5. Get the incore inode for the inumber of the examination cursor.
+   By maintaining the AGI buffer lock until this point, the scanner
knows that
+   it was safe to advance the examination cursor across the entire
keyspace,
+   and that it has stabilized this next inode so that it cannot disappear from
+   the filesystem until the scan releases the incore inode.

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+
+6. Drop the AGI lock and return the incore inode to the caller.
+
+Online fsck functions scan all files in the filesystem as

follows:

Quoted 8 lines
Quoted 2 lines

+
+1. Start a scan by calling ``xchk_iscan_start``.

Hmm, I actually did not find xchk_iscan_start in the below branch, I
found xchk_iscan_iter in "xfs: implement live inode scan for scrub",
but it doesnt look like anything uses it yet, at least not in that branch.

<nod> The topic branch linked below has the implementation, but no users.  The first user is online quotacheck, which is in the next branch
after that:

https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/log/?h=repair-quotacheck

Specifically, this patch:

https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/commit/?h=repair-quotacheck&id=3640515b9282514d91a407b6aa8d8b73caa123c5

I'll restate what you probably saw in the commit message for this email discussion:

This "one branch to introduce a new infrastructure and a second branch
to actually use it" pattern is a result of reviewer requests for smaller
more focused branches.  This has turned out to be useful in practice because it's easier to move just these pieces up and down in the branch
as needed.  The inode scan was originally developed for rmapbt repair (which comes *much* later) and moved it up once I realized that quotacheck has far fewer dependencies and hence all of this could come
earlier.

Quoted 3 lines

You're right that this section ought to point to an actual user of the
functionality.  Will fix. :)

Alrighty then, sounds good

Quoted 9 lines
Quoted 4 lines

Also, it took me a bit to figure out that "initial user" meant "calling
function"

Er... are you talking about the sentence "...new code is split out as a
separate patch from its initial user" in the patch commit message?

Quoted 5 lines

Maybe I should reword that:

"This new code is a separate patch from the patches adding callers for
the sake of enabling the author to move patches around his tree..."

Yes, I think that's clearer :-)

Quoted 227 lines
Quoted 44 lines
Quoted 44 lines

+
+2. Advance the scan cursor (``xchk_iscan_iter``) to get the next inode.
+   If one is provided:

Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+
+   a. Lock the inode to prevent updates during the scan.
+
+   b. Scan the inode.
+
+   c. While still holding the inode lock, adjust the visited

inode
cursor
+      (``xchk_iscan_mark_visited``) to point to this inode.

Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+
+   d. Unlock and release the inode.
+
+8. Call ``xchk_iscan_finish`` to complete the scan.
+
+There are subtleties with the inode cache that complicate

grabbing
the incore

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+inode for the caller.
+Obviously, it is an absolute requirement that the inode metadata

be
consistent

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+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

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+back into a loadable state.
+
+The proposed patches are the
+`inode scanner
+<

https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/
log/?h=scrub-iscan>`_

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+series.
+
+Inode Management
+````````````````
Quoted 8 lines
Quoted 7 lines
Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+In regular filesystem code, references to allocated XFS incore

inodes are
+always obtained (``xfs_iget``) outside of transaction context because the
+creation of the incore context for ane xisting file does not require

an existing

Corrected, thank you.

Quoted 172 lines
Quoted 168 lines

metadata

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+updates.
+However, it is important to note that references to incore

inodes
obtained as
+part of file creation must be performed in transaction context because the
+filesystem must ensure the atomicity of the ondisk inode btree index
updates

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+and the initialization of the actual ondisk inode.
+
+References to incore inodes are always released (``xfs_irele``)

outside of
+transaction context because there are a handful of activities that
might

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+require ondisk updates:
+
+- The VFS may decide to kick off writeback as part of a

``DONTCACHE`` inode
+  release.

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+
+- 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 and freeing the inode.

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+
+These activities are collectively called inode inactivation.
+Inactivation has two parts -- the VFS part, which initiates

writeback on all
+dirty file pages, and the XFS part, which cleans up XFS-specific information

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+and frees the inode if it was unlinked.
+If the inode is unlinked (or unconnected after a file handle

operation), the
+kernel drops the inode into the inactivation machinery immediately.

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+During normal operation, resource acquisition for an update

follows
this order

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+to avoid deadlocks:
+
+1. Inode reference (``iget``).
+
+2. Filesystem freeze protection, if repairing

(``mnt_want_write_file``).

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+
+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.

Documentation/filesystems/xfs-online-fsck-design.rst +19 -0
+
+5. Log feature enablement.
+
+6. Transaction log space grant.
+
+7. Space on the data and realtime devices for the transaction.
+
+8. Incore dquot references, if a file is being repaired.
+   Note that they are not locked, merely acquired.
+
+9. Inode ``ILOCK`` for file metadata updates.
+
+10. AG header buffer locks / Realtime metadata inode ILOCK.
+
+11. Realtime metadata buffer locks, if applicable.
+
+12. Extent mapping btree blocks, if applicable.
+
+Resources are often released in the reverse order, though this

is
not required.
+However, online fsck differs from regular XFS operations because it
may examine
+an object that normally is acquired in a later stage of the locking
order, and
+then decide to cross-reference the object with an object that is acquired

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+earlier in the order.
+The next few sections detail the specific ways in which online

fsck
takes care

Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+to avoid deadlocks.
+
+iget and irele During a Scrub
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+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, as long as all of the bound resources
are acquired

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+before the inode reference in the regular filesystem.
+
+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

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+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

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+inactivation machinery immediately.
+
+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

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+transaction, and XFS does not support nesting transactions.
+On the other hand, if there is no scrub transaction, it is

desirable
to drop

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+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

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+behavior.
+
+Proposed patchsets include fixing
+`scrub iget usage
+<

https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/
log/?h=scrub-iget-fixes>`_ and
+`dir iget usage
+<
https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/
log/?h=scrub-dir-iget-fixes>`_.

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+
+Locking Inodes
+^^^^^^^^^^^^^^
+
+In regular filesystem code, the VFS and XFS will acquire

multiple
IOLOCK locks
+in a well-known order: parent → child when updating the directory
tree, and
+``struct inode`` address order otherwise.
+For regular files, the MMAPLOCK can be acquired after the IOLOCK to
stop page

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+faults.
+If two MMAPLOCKs must be acquired, they are acquired in 
Quoted 2 lines

``struct
+address_space`` order.

the order of their memory address

Quoted 9 lines
Quoted 1 line

?

Urghg.  I think I need to clarify this more:

"...they are acquired in numerical order of the addresses of their ``struct address_space`` objects."

See filemap_invalidate_lock_two.

Yep, I think that works

Quoted 437 lines
Quoted 319 lines
Quoted 319 lines

+Due to the structure of existing filesystem code, IOLOCKs and MMAPLOCKs must be

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+acquired before transactions are allocated.
+If two ILOCKs must be acquired, they are acquired in inumber

order.

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+Inode lock acquisition must be done carefully during a

coordinated
inode scan.
+Online fsck cannot abide these conventions, because for a directory
tree
+scanner, the scrub process holds the IOLOCK of the file being scanned and it
+needs to take the IOLOCK of the file at the other end of the directory link.
+If the directory tree is corrupt because it contains a cycle, ``xfs_scrub``
+cannot use the regular inode locking functions and avoid becoming
trapped in an

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+ABBA deadlock.
+
+Solving both of these problems is straightforward -- any time

online
fsck
+needs to take a second lock of the same class, it uses trylock to
avoid an ABBA

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+deadlock.
+If the trylock fails, scrub drops all inode locks and use

trylock
loops to

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+(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

Documentation/filesystems/xfs-online-fsck-design.rst +9 -0
+react accordingly.
+
+.. _dirparent:
+
+Case Study: Finding a Directory Parent
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Consider the directory parent pointer repair code as an example.
+Online fsck must verify that the dotdot dirent of a directory

points
up to a
+parent directory, and that the parent directory contains exactly one
dirent

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+pointing down to the child directory.
+Fully validating this relationship (and repairing it if

possible)
requires a
+walk of every directory on the filesystem while holding the child
locked, and

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+while updates to the directory tree are being made.
+The coordinated inode scan provides a way to walk the filesystem

without the

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+possibility of missing an inode.
+The child directory is kept locked to prevent updates to the

dotdot
dirent, but
+if the scanner fails to lock a parent, it can drop and relock both
the child

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+and the prospective parent.
+If the dotdot entry changes while the directory is unlocked,

then a
move or
+rename operation must have changed the child's parentage, and the
scan can

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+exit early.
+
+The proposed patchset is the
+`directory repair
+<

https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/
log/?h=repair-dirs>`_

Documentation/filesystems/xfs-online-fsck-design.rst +8 -0
+series.
+
+.. _fshooks:
+
+Filesystem Hooks
+`````````````````
+
+The second piece of support that online fsck 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

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+in a dynamic environment.
+Two pieces of Linux kernel infrastructure enable online fsck to

monitor regular
+filesystem operations: filesystem hooks and :ref:static keys<jump_labels>.

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+Filesystem hooks convey information about an ongoing filesystem

operation to

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+a downstream consumer.
+In this case, the downstream consumer is always an online fsck

function.
+Because multiple fsck functions can run in parallel, online fsck uses the Linux
+notifier call chain facility to dispatch updates to any number of
interested

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+fsck processes.
+Call chains are a dynamic list, which means that they can be

configured at

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+run time.
+Because these hooks are private to the XFS module, the

information
passed along
+contains exactly what the checking function needs to update its observations.

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+The current implementation of XFS hooks uses SRCU notifier

chains to
reduce the

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+impact to highly threaded workloads.
+Regular blocking notifier chains use a rwsem and seem to have a

much
lower

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+overhead for single-threaded applications.
+However, it may turn out that the combination of blocking chains

and
static
+keys are a more performant combination; more study is needed here.

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+The following pieces are necessary to hook a certain point in

the
filesystem:
+
+- A ``struct xfs_hooks`` object must be embedded in a convenient place such as
+  a well-known incore filesystem object.
+
+- Each hook must define an action code and a structure containing
more context
+  about the action.
+
+- Hook providers should provide appropriate wrapper functions and
structs
+  around the ``xfs_hooks`` and ``xfs_hook`` objects to take advantage of type
+  checking to ensure correct usage.
+
+- A callsite in the regular filesystem code must be chosen to call
+  ``xfs_hooks_call`` with the action code and data structure. +  This place should be adjacent to (and not earlier than) the place
where
+  the filesystem update is committed to the transaction. +  In general, when the filesystem calls a hook chain, it should be
able to
+  handle sleeping and should not be vulnerable to memory reclaim or
locking
+  recursion.
+  However, the exact requirements are very dependent on the context
of the hook
+  caller and the callee.
+
+- The online fsck function should define a structure to hold scan
data, a lock
+  to coordinate access to the scan data, and a ``struct xfs_hook``
object.
+  The scanner function and the regular filesystem code must acquire
resources
+  in the same order; see the next section for details. +
+- The online fsck code must contain a C function to catch the hook
action code
+  and data structure.
+  If the object being updated has already been visited by the scan,
then the
+  hook information must be applied to the scan data.
+
+- Prior to unlocking inodes to start the scan, online fsck must call
+  ``xfs_hooks_setup`` to initialize the ``struct xfs_hook``, and +  ``xfs_hooks_add`` to enable the hook.
+
+- Online fsck must call ``xfs_hooks_del`` to disable the hook once
the scan is
+  complete.

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+The number of hooks should be kept to a minimum to reduce

complexity.
+Static keys are used to reduce the overhead of filesystem hooks to
nearly

Documentation/filesystems/xfs-online-fsck-design.rst +8 -0
+zero when online fsck is not running.
+
+.. _liveupdate:
+
+Live Updates During a Scan
+``````````````````````````
+
+The code paths of the online fsck scanning code and the

:ref:hooked<fshooks>

Documentation/filesystems/xfs-online-fsck-design.rst +29 -0
+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

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+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. +
+- Scrub 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 (``xchk_iscan_want_live_update``)
+  for this.
+
+- Scrub hook functions must not change the caller's state, including
the
+  transaction that it is running.
+  They must not acquire any resources that might conflict with the
filesystem
+  function being hooked.
+
+- The hook function can abort the inode scan to avoid breaking the
other rules.

Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+
+The inode scan APIs are pretty simple:
+
+- ``xchk_iscan_start`` starts a scan
+
+- ``xchk_iscan_iter`` grabs a reference to the next inode in the

scan or
+  returns zero if there is nothing left to scan
+
+- ``xchk_iscan_want_live_update`` to decide if an inode has already
been
+  visited in the scan.
+  This is critical for hook functions to decide if they need to update the
+  in-memory scan information.
+
+- ``xchk_iscan_mark_visited`` to mark an inode as having been visited in the
+  scan
+
+- ``xchk_iscan_finish`` to finish the scan

Quoted 8 lines
Quoted 7 lines
Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+
+The proposed patches are at the start of the
+`online quotacheck
+<

https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/
log/?h=repair-quota>`_
+series.

Wrong link?  This looks like it goes to the section below.

Oops.  This one should link to scrub-iscan, and the next one should link
to repair-quotacheck.

Quoted 96 lines
Quoted 96 lines
Documentation/filesystems/xfs-online-fsck-design.rst +7 -0
+
+.. _quotacheck:
+
+Case Study: Quota Counter Checking
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+It is useful to compare the mount time quotacheck code to the

online
repair

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+quotacheck code.
+Mount time quotacheck does not have to contend with concurrent

operations, so

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+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.

Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+
+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.

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+
+4. Write the buffer list to disk.
+
+Like most online fsck functions, online quotacheck can't write

to
regular
+filesystem objects until the newly collected metadata reflect all
filesystem

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+state.
+Therefore, online quotacheck records file resource usage to a

shadow
dquot
+index implemented with a sparse ``xfarray``, and only writes to the
real dquots

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+once the scan is complete.
+Handling transactional updates is tricky because quota resource

usage updates

Documentation/filesystems/xfs-online-fsck-design.rst +9 -0
+are handled in phases to minimize contention on dquots:
+
+1. The inodes involved are joined and locked to a transaction.
+
+2. For each dquot attached to the file:
+
+   a. The dquot is locked.
+
+   b. A quota reservation is added to the dquot's resource

usage.
+      The reservation is recorded in the transaction.

Documentation/filesystems/xfs-online-fsck-design.rst +10 -0
+
+   c. The dquot is unlocked.
+
+3. Changes in actual quota usage are tracked in the transaction.
+
+4. At transaction commit time, each dquot is examined again:
+
+   a. The dquot is locked again.
+
+   b. Quota usage changes are logged and unused reservation is

given
back to
+      the dquot.

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+
+   c. The dquot is unlocked.
+
+For online 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 ``dqtrx`` changes to the shadow
dquots.
+Notice that both hooks are called with the inode locked, which is
how the

Documentation/filesystems/xfs-online-fsck-design.rst +8 -0
+live update coordinates with the inode scanner.
+
+The quotacheck scan looks like this:
+
+1. Set up a coordinated inode scan.
+
+2. For each inode returned by the inode scan iterator:
+
Quoted 8 lines
Quoted 5 lines

+   a. Grab and lock the inode.
+
+   b. Determine that inode's resource usage (data blocks, inode counts,
+      realtime blocks)

nit: move this list to the first appearance of "resource usage". Step
2 of the first list I think

Quoted 9 lines

I don't understand this proposed change.  Are you talking about "2. For
each dquot attached to the file:" above?  That list describes the steps
taken by regular code wanting to allocate file space that's accounted to
quotas.  This list describes what online quotacheck does.  The two don't
mix.

Oh, youre right, disregard this one

Quoted 283 lines
Quoted 20 lines
Quoted 20 lines

and add that to the shadow dquots for the user, group, +      and project ids associated with the inode.

Documentation/filesystems/xfs-online-fsck-design.rst +8 -0
+
+   c. Unlock and release the inode.
+
+3. For each dquot in the system:
+
+   a. Grab and lock the dquot.
+
+   b. Check the dquot against the shadow dquots created by the

scan
and updated
+      by the live hooks.

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+Live updates are key to being able to walk every quota record

without

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+needing to hold any locks for a long duration.
+If repairs are desired, the real and shadow dquots are locked

and

Quoted 8 lines
Quoted 8 lines

their

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+resource counts are set to the values in the shadow dquot.
+
+The proposed patchset is the
+`online quotacheck
+<

https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/
log/?h=repair-quota>`_

Changed from repair-quota to repair-quotacheck.

Quoted 230 lines
Quoted 224 lines
Documentation/filesystems/xfs-online-fsck-design.rst +9 -0
+series.
+
+.. _nlinks:
+
+Case Study: File Link Count Checking
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+File link count checking also uses live update hooks.
+The coordinated inode scanner is used to visit all directories

on
the
+filesystem, and per-file link count records are stored in a sparse
``xfarray``

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+indexed by inumber.
+During the scanning phase, each entry in a directory generates

observation

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+data as follows:
+
+1. If the entry is a dotdot (``'..'``) entry of the root

directory,
the
+   directory's parent link count is bumped because the root directory's dotdot
+   entry is self referential.
+
+2. If the entry is a dotdot entry of a subdirectory, the parent's
backref
+   count is bumped.
+
+3. If the entry is neither a dot nor a dotdot entry, the target file's parent
+   count is bumped.
+
+4. If the target is a subdirectory, the parent's child link count is
bumped.

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+A crucial point to understand about how the link count inode

scanner
interacts
+with the live update hooks is that the scan cursor tracks which *parent*

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+directories have been scanned.
+In other words, the live updates ignore any update about ``A →

B``
when A has

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+not been scanned, even if B has been scanned.
+Furthermore, a subdirectory A with a dotdot entry pointing back

to B
is
+accounted as a backref counter in the shadow data for A, since child
dotdot

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+entries affect the parent's link count.
+Live update hooks are carefully placed in all parts of the

filesystem that
+create, change, or remove directory entries, since those operations
involve

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+bumplink and droplink.
+
+For any file, the correct link count is the number of parents

plus
the number

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+of child subdirectories.
+Non-directories never have children of any kind.
+The backref information is used to detect inconsistencies in the

number of
+links pointing to child subdirectories and the number of dotdot entries

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+pointing back.
+
+After the scan completes, the link count of each file can be

checked
by locking
+both the inode and the shadow data, and comparing the link counts.

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+A second coordinated inode scan cursor is used for comparisons.
+Live updates are key to being able to walk every inode without

needing to hold

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+any locks between inodes.
+If repairs are desired, the inode's link count is set to the

value
in the

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+shadow information.
+If no parents are found, the file must be :ref:`reparented

<orphanage>` to the

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+orphanage to prevent the file from being lost forever.
+
+The proposed patchset is the
+`file link count repair
+<

https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/
log/?h=scrub-nlinks>`_

Documentation/filesystems/xfs-online-fsck-design.rst +8 -0
+series.
+
+.. _rmap_repair:
+
+Case Study: Rebuilding Reverse Mapping Records
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Most repair functions follow the same pattern: lock filesystem

resources,
+walk the surviving ondisk metadata looking for replacement metadata
records,
+and use an :ref:in-memory array <xfarray> to store the gathered
observations.
+The primary advantage of this approach is the simplicity and modularity of the
+repair code -- code and data are entirely contained within the scrub
module,
+do not require hooks in the main filesystem, and are usually the most efficient

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+in memory use.
+A secondary advantage of this repair approach is atomicity --

once
the kernel
+decides a structure is corrupt, no other threads can access the metadata until

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+the kernel finishes repairing and revalidating the metadata.
+
+For repairs going on within a shard of the filesystem, these

advantages
+outweigh the delays inherent in locking the shard while repairing
parts of the

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+shard.
+Unfortunately, repairs to the reverse mapping btree cannot use

the
"standard"
+btree repair strategy because it must scan every space mapping of
every fork of

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+every file in the filesystem, and the filesystem cannot stop.
+Therefore, rmap repair foregoes atomicity between scrub and

repair.
+It combines a :ref:coordinated inode scanner <iscan>, :ref:`live
update hooks
+<liveupdate>, and an :ref:in-memory rmap btree <xfbtree>` to complete the

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+scan for reverse mapping records.
+
+1. Set up an xfbtree to stage rmap records.
+
+2. While holding the locks on the AGI and AGF buffers acquired

during the
+   scrub, generate reverse mappings for all AG metadata: inodes, btrees, CoW
+   staging extents, and the internal log.

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+
+3. Set up an inode scanner.
+
+4. Hook into rmap updates for the AG being repaired so that the

live
scan data
+   can receive updates to the rmap btree from the rest of the filesystem during
+   the file scan.
+
+5. For each space mapping found in either fork of each file scanned,
+   decide if the mapping matches the AG of interest. +   If so:

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+
+   a. Create a btree cursor for the in-memory btree.
+
+   b. Use the rmap code to add the record to the in-memory

btree.
+
+   c. Use the :ref:special commit function <xfbtree_commit> to write the
+      xfbtree changes to the xfile.
+
+6. For each live update received via the hook, decide if the owner
has already
+   been scanned.
+   If so, apply the live update into the scan data:

Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+
+   a. Create a btree cursor for the in-memory btree.
+
+   b. Replay the operation into the in-memory btree.
+
+   c. Use the :ref:`special commit function <xfbtree_commit>` to

write the
+      xfbtree changes to the xfile.
+      This is performed with an empty transaction to avoid changing
the
+      caller's state.
+
+7. When the inode scan finishes, create a new scrub transaction and
relock the
+   two AG headers.
+
+8. Compute the new btree geometry using the number of rmap records
in the
+   shadow btree, like all other btree rebuilding functions.

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+
+9. Allocate the number of blocks computed in the previous step.
+
+10. Perform the usual btree bulk loading and commit to install

the
new rmap
+    btree.
+
+11. Reap the old rmap btree blocks as discussed in the case study
about how
+    to :ref:reap after rmap btree repair <rmap_reap>.

Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+
+12. Free the xfbtree now that it not needed.
+
+The proposed patchset is the
+`rmap repair
+<
Quoted 4 lines

https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/
log/?h=repair-rmap-btree>`_
+series.

Mostly looks good nits aside, I do sort of wonder if this patch

Quoted 8 lines

would
do better to appear before patch 6 (or move 6 down), since it gets into
more challenges concerning locks and hooks, where as here we are mostly
discussing what they are and how they work.  So it might build better
to move this patch up a little.

(I might be a tad confused here, bear with me.)

Patch 6, the section about eventual consistency?

Hmm.  The intent drains exist to quiesce intent chains targeting specific AGs.  It briefly mentions "fshooks" in the context of using jump labels to avoid the overhead of calling notify_all on the drain waitqueue when scrub isn't running.  That's perhaps bad naming on my part, since the other "fshooks" are jump labels to avoid bouncing through the notifier chain code when scrub isn't running.  The jump labels themselves are not hooks, they're structured dynamic code patching.

Quoted 1 line

I probably should've named those something else.  fsgates?

Oh, i see, yes I did sort of try to correlate them, so maybe the different name would help.

Quoted 10 lines

Or maybe you were talking specifically about "Case Study: Rebuilding Reverse Mapping Records"?  In which case I remark that the case study needs both the intent drains to quiesce the AG and the live scans to work properly, which is why the case study of it couldn't come earlier.
The intent drains section still ought to come before the refcountbt section, because it's the refcountbt scrubber that first hit the coordination problem.

Quoted 3 lines

Things are getting pretty awkward like this because there are sooo many
interdependent pieces. :(

I see, ok no worries then, I think people will figure it out either way. I mostly look for ways to make the presentation easier but it is getting harder to move stuff with chicken and egg dependencies.

Quoted 7 lines

Regardless, thank you very much for slogging through.

--D

Quoted 2 lines

Allison

#48 lore raw

Re: [PATCH 10/14] xfs: document full filesystem scans for online fsck

On Sat, Feb 25, 2023 at 07:33:38AM +0000, Allison Henderson wrote:

<snip>

Quoted 23 lines
Quoted 23 lines
Quoted 9 lines

Mostly looks good nits aside, I do sort of wonder if this patch would
do better to appear before patch 6 (or move 6 down), since it gets into
more challenges concerning locks and hooks, where as here we are mostly
discussing what they are and how they work.  So it might build better
to move this patch up a little.

(I might be a tad confused here, bear with me.)

Patch 6, the section about eventual consistency?

Hmm.  The intent drains exist to quiesce intent chains targeting specific AGs.  It briefly mentions "fshooks" in the context of using jump labels to avoid the overhead of calling notify_all on the drain waitqueue when scrub isn't running.  That's perhaps bad naming on my part, since the other "fshooks" are jump labels to avoid bouncing through the notifier chain code when scrub isn't running.  The jump labels themselves are not hooks, they're structured dynamic code patching.

Quoted 3 lines
Quoted 1 line

I probably should've named those something else.  fsgates?

Oh, i see, yes I did sort of try to correlate them, so maybe the different name would help.

Done.

Quoted 9 lines
Quoted 9 lines

Or maybe you were talking specifically about "Case Study: Rebuilding Reverse Mapping Records"?  In which case I remark that the case study needs both the intent drains to quiesce the AG and the live scans to work properly, which is why the case study of it couldn't come earlier.
The intent drains section still ought to come before the refcountbt section, because it's the refcountbt scrubber that first hit the coordination problem.

Quoted 7 lines
Quoted 3 lines

Things are getting pretty awkward like this because there are sooo many
interdependent pieces. :(

I see, ok no worries then, I think people will figure it out either way. I mostly look for ways to make the presentation easier but it is getting harder to move stuff with chicken and egg dependencies.

Indeed. Thank you so much for your patience. :)

--D

Quoted 8 lines
Quoted 7 lines

Regardless, thank you very much for slogging through.

--D

Quoted 2 lines

Allison

#49 lore raw

PATCH 11/14 xfs: document metadata file repair

In reply to Darrick J. Wong

From: Darrick J. Wong <[email protected]>

File-based metadata (such as xattrs and directories) can be extremely large. To reduce the memory requirements and maximize code reuse, it is very convenient to create a temporary file, use the regular dir/attr code to store salvaged information, and then atomically swap the extents between the file being repaired and the temporary file. Record the high level concepts behind how temporary files and atomic content swapping should work, and then present some case studies of what the actual repair functions do.

---
 .../filesystems/xfs-online-fsck-design.rst         |  574 ++++++++++++++++++++
 1 file changed, 574 insertions(+)
Documentation/filesystems/xfs-online-fsck-design.rst +574 -0
index c0f08a773f08..e32506acb66f 100644
@@ -3252,6 +3252,8 @@ Proposed patchsets include fixing
 `dir iget usage
 <https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/log/?h=scrub-dir-iget-fixes>`_.
 
+.. _ilocking:
+
 Locking Inodes
 ^^^^^^^^^^^^^^
 
@@ -3695,3 +3697,575 @@ The proposed patchset is the
 `rmap repair
 <https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/log/?h=repair-rmap-btree>`_
 series.
+
+Staging Repairs with Temporary Files on Disk
+--------------------------------------------
+
+XFS stores a substantial amount of metadata in file forks: directories,
+extended attributes, symbolic link targets, 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 file metadata repair, 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 attr fork offset address
+  space.
+
+- Even if repair 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 as part of a range collapse 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 (and hence the fork contents) 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 log recovery.
+
+**Note**: All space usage and inode indices in the filesystem *must* be
+consistent to use a temporary file safely!
+This dependency is the reason why online repair can only use pageable kernel
+memory to stage ondisk space usage information.
+
+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 for correct operation of files 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.
+
+Using a Temporary File
+``````````````````````
+
+Online repair code should use the ``xrep_tempfile_create`` function to create a
+temporary file inside the filesystem.
+This allocates an inode, marks the in-core inode private, and attaches it to
+the scrub context.
+These files are hidden from userspace, may not be added to the directory tree,
+and must be kept private.
+
+Temporary files only use two inode locks: the IOLOCK and the ILOCK.
+The MMAPLOCK is not needed here, because there must not be page faults from
+userspace for data fork blocks.
+The usage patterns of these two locks are the same as for any other XFS file --
+access to file data are controlled via the IOLOCK, and access to file metadata
+are controlled via the ILOCK.
+Locking helpers are provided so that the temporary file and its lock state can
+be cleaned up by the scrub context.
+To comply with the nested locking strategy laid out in the :ref:`inode
+locking<ilocking>` section, it is recommended that scrub functions use the
+xrep_tempfile_ilock*_nowait lock helpers.
+
+Data can be written to a temporary file by two means:
+
+1. ``xrep_tempfile_copyin`` can be used to set the contents of a regular
+   temporary file from an xfile.
+
+2. The regular directory, symbolic link, and extended attribute functions can
+   be used to write to the temporary file.
+
+Once a good copy of a data file has been constructed in a temporary file, it
+must be conveyed to the file being repaired, which is the topic of the next
+section.
+
+The proposed patches are in the
+`realtime summary repair
+<https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/log/?h=repair-rtsummary>`_
+series.
+
+Atomic Extent Swapping
+----------------------
+
+Once repair builds a temporary file with a new data structure written into
+it, it must commit the new changes into the existing file.
+It is not possible to swap the inumbers of two files, so instead the new
+metadata must replace the old.
+This suggests the need for the ability to swap extents, but the existing extent
+swapping code used by the file defragmenting tool ``xfs_fsr`` is not sufficient
+for online repair because:
+
+a. When the reverse-mapping btree is enabled, the swap code must keep the
+   reverse mapping information up to date with every exchange of mappings.
+   Therefore, it can only exchange one mapping per transaction, and each
+   transaction is independent.
+
+b. Reverse-mapping is critical for the operation of online fsck, so the old
+   defragmentation code (which swapped entire extent forks in a single
+   operation) is not useful here.
+
+c. Defragmentation is assumed to occur between two files with identical
+   contents.
+   For this use case, an incomplete exchange will not result in a user-visible
+   change in file contents, even if the operation is interrupted.
+
+d. Online repair needs to swap the contents of two files that are by definition
+   *not* identical.
+   For directory and xattr repairs, the user-visible contents might be the
+   same, but the contents of individual blocks may be very different.
+
+e. Old blocks in the file may be cross-linked with another structure and must
+   not reappear if the system goes down mid-repair.
+
+These problems are overcome by creating a new deferred operation and a new type
+of log intent item to track the progress of an operation to exchange two file
+ranges.
+The new deferred operation type chains together the same transactions used by
+the reverse-mapping extent swap code.
+The new log item records the progress of the exchange to ensure that once an
+exchange begins, it will always run to completion, even there are
+interruptions.
+
+The proposed patchset is the
+`atomic extent swap
+<https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/log/?h=atomic-file-updates>`_
+series.
+
+Using Log-Incompatible Feature Flags
+````````````````````````````````````
+
+Starting with XFS v5, the superblock contains a ``sb_features_log_incompat``
+field to indicate that the log contains records that might not readable by all
+kernels that could mount this filesystem.
+In short, log incompat features protect the log contents against kernels that
+will not understand the contents.
+Unlike the other superblock feature bits, log incompat bits are ephemeral
+because an empty (clean) log does not need protection.
+The log cleans itself after its contents have been committed into the
+filesystem, either as part of an unmount or because the system is otherwise
+idle.
+Because upper level code can be working on a transaction at the same time that
+the log cleans itself, it is necessary for upper level code to communicate to
+the log when it is going to use a log incompatible feature.
+
+The log coordinates access to incompatible features through the use of one
+``struct rw_semaphore`` for each feature.
+The log cleaning code tries to take this rwsem in exclusive mode to clear the
+bit; if the lock attempt fails, the feature bit remains set.
+Filesystem code signals its intention to use a log incompat feature in a
+transaction by calling ``xlog_use_incompat_feat``, which takes the rwsem in
+shared mode.
+The code supporting a log incompat feature should create wrapper functions to
+obtain the log feature and call ``xfs_add_incompat_log_feature`` to set the
+feature bits in the primary superblock.
+The superblock update is performed transactionally, so the wrapper to obtain
+log assistance must be called just prior to the creation of the transaction
+that uses the functionality.
+For a file operation, this step must happen after taking the IOLOCK and the
+MMAPLOCK, but before allocating the transaction.
+When the transaction is complete, the ``xlog_drop_incompat_feat`` function
+is called to release the feature.
+The feature bit will not be cleared from the superblock until the log becomes
+clean.
+
+Log-assisted extended attribute updates and atomic extent swaps both use log
+incompat features and provide convenience wrappers around the functionality.
+
+Mechanics of an Atomic Extent Swap
+``````````````````````````````````
+
+Swapping entire file forks is a complex task.
+The goal is 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 edges 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, inode flags, or conversion of fork data to local
+format.
+This is roughly the format of the new deferred extent swap work item:
+
+.. code-block:: c
+
+	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;
+	};
+
+The new log intent item contains enough information to track two logical fork
+offset ranges: ``(inode1, startoff1, blockcount)`` and ``(inode2, startoff2,
+blockcount)``.
+Each step of a swap operation exchanges the largest file range mapping possible
+from one file to the other.
+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. Call ``xfs_defer_finish`` to start processing of the exchange.
+   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,
+
+   a. Read the block maps of both file ranges starting at ``sxi_startoff1`` and
+      ``sxi_startoff2``, respectively, and compute the longest extent that can
+      be swapped 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.
+      Mutual holes, unwritten extents, and extent mappings to the same physical
+      space are not exchanged.
+
+      For the next few steps, this document will refer to the mapping that came
+      from file 1 as "map1", and the mapping that came from file 2 as "map2".
+
+   b. Create a deferred block mapping update to unmap map1 from file 1.
+
+   c. Create a deferred block mapping update to unmap map2 from file 2.
+
+   d. Create a deferred block mapping update to map map1 into file 2.
+
+   e. Create a deferred block mapping update to map map2 into file 1.
+
+   f. Log the block, quota, and extent count updates for both files.
+
+   g. Extend the ondisk size of either file if necessary.
+
+   h. Log an extent swap done log item for the extent swap intent log item
+      that was read at the start of step 3.
+
+   i. Compute the amount of file range that has just been covered.
+      This quantity is ``(map1.br_startoff + map1.br_blockcount -
+      sxi_startoff1)``, because step 3a could have skipped holes.
+
+   j. Increase the starting offsets of ``sxi_startoff1`` and ``sxi_startoff2``
+      by the number of blocks computed in the previous step, and decrease
+      ``sxi_blockcount`` by the same quantity.
+      This advances the cursor.
+
+   k. Log a new extent swap intent log item reflecting the advanced state of
+      the work item.
+
+   l. 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 back to the start of step 3.
+
+4. Perform any post-processing.
+   This will be discussed in more detail in subsequent sections.
+
+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 extent swapping guarantees 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 fork'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-3 from the procedure above except for
+the new tracking items, 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, the file contents must be
+identical, so the recovery guarantees are not much of a gain.
+
+Atomic extent swapping is much more flexible than the existing swapext
+implementations 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.
+  Stage all writes to a temporary file, and when that is complete, call the
+  atomic extent swap system call with a flag to indicate that holes in the
+  temporary file should be ignored.
+  This emulates an atomic device write in software, and can support arbitrary
+  scattered writes.
+
+Preparation for Extent Swapping
+```````````````````````````````
+
+There are a few things that need to be taken care of before initiating an
+atomic extent swap operation.
+First, regular files require the page cache to be flushed to disk before the
+operation begins, and directio writes to be quiesced.
+Like any filesystem operation, extent swapping 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 it starts dirtying metadata.
+The preparation step scans 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 will be added to each file.
+- Whether or not there are partially written realtime extents.
+  User programs must never be able to access a realtime file extent that maps
+  to different extents on the realtime volume, which could happen if the
+  operation fails to run to completion.
+
+The need for precise estimation increases the run time of the swap operation,
+but it is very important to maintain correct accounting.
+The filesystem must not run completely out of free space, nor can the extent
+swap ever add more extent mappings to a fork than it can support.
+Regular users are required to abide the quota limits, though metadata repairs
+may exceed quota to resolve inconsistent metadata elsewhere.
+
+Special Features for Swapping Metadata File Extents
+```````````````````````````````````````````````````
+
+Extended attributes, symbolic links, and directories can set the fork format to
+"local" and treat the fork as a literal area for data storage.
+Metadata repairs must take extra steps to support these cases:
+
+- If both forks are in local format and the fork areas are large enough, the
+  swap is performed by copying the incore fork contents, logging both forks,
+  and committing.
+  The atomic extent swap mechanism is not necessary, since this can be done
+  with a single transaction.
+
+- If both forks map blocks, then the regular atomic extent swap is used.
+
+- Otherwise, only one fork is in local format.
+  The contents of the local format fork are converted to a block to perform the
+  swap.
+  The conversion to block format must 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 one more time to convert the second file's fork back to local format
+  if possible.
+
+Extended attributes and directories stamp the owning inode into every block,
+but the buffer verifiers do not actually check the inode number!
+Although there is no verification, it is still important to maintain
+referential integrity, so prior to performing the extent swap, online repair
+walks 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 :ref:`file extent
+reaping <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.
+However, this iunlink processing omits the cross-link detection of online
+repair, and is not completely foolproof.
+
+Swapping Temporary File Extents
+```````````````````````````````
+
+To repair a metadata file, online repair proceeds as follows:
+
+1. Create a temporary repair file.
+
+2. Use the staging data to write out new contents into the temporary repair
+   file.
+   The same fork must be written to as is being repaired.
+
+3. Commit the scrub transaction, since the swap estimation step must be
+   completed before transaction reservations are made.
+
+4. Call ``xrep_tempswap_trans_alloc`` to allocate a new scrub transaction with
+   the appropriate resource reservations, locks, and fill out a ``struct
+   xfs_swapext_req`` with the details of the swap operation.
+
+5. Call ``xrep_tempswap_contents`` to swap the contents.
+
+6. Commit the transaction to complete the repair.
+
+.. _rtsummary:
+
+Case Study: Repairing the Realtime Summary File
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+In the "realtime" section of an XFS filesystem, free space is tracked via a
+bitmap, similar to Unix FFS.
+Each bit in the bitmap represents one realtime extent, which is a multiple of
+the filesystem block size between 4KiB and 1GiB in size.
+The realtime summary file indexes the number of free extents of a given size to
+the offset of the block within the realtime free space bitmap where those free
+extents begin.
+In other words, the summary file helps the allocator find free extents by
+length, similar to what the free space by count (cntbt) btree does for the data
+section.
+
+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:
+
+1. Take the ILOCK of both the realtime bitmap and summary files.
+
+2. For each free space extent recorded in the bitmap:
+
+   a. Compute the position in the summary file that contains a counter that
+      represents this free extent.
+
+   b. Read the counter from the xfile.
+
+   c. Increment it, and write it back to the xfile.
+
+3. Compare the contents of the xfile against the ondisk file.
+
+To repair the summary file, write the xfile contents into the temporary file
+and use atomic extent swap to commit the new contents.
+The temporary file is then reaped.
+
+The proposed patchset is the
+`realtime summary repair
+<https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/log/?h=repair-rtsummary>`_
+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 mappings of the file being repaired to find the attribute
+   leaf blocks.
+   When one is found,
+
+   a. Walk the attr leaf block to find candidate keys.
+      When one is found,
+
+      1. Check the name for problems, and ignore the name if there are.
+
+      2. Retrieve the value.
+         If that succeeds, add the name and value to the staging xfarray and
+         xfblob.
+
+2. If the memory usage of the xfarray and xfblob exceed a certain amount of
+   memory or there are no more attr fork blocks to examine, unlock the file and
+   add the staged extended attributes to the temporary file.
+
+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
+<https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/log/?h=repair-xattrs>`_
+series.
#50 lore raw

Re: [PATCH 11/14] xfs: document metadata file repair

Quoted 27 lines · Darrick J. Wong

From: Darrick J. Wong <[email protected]>

File-based metadata (such as xattrs and directories) can be extremely large.  To reduce the memory requirements and maximize code reuse, it is
very convenient to create a temporary file, use the regular dir/attr code to store salvaged information, and then atomically swap the extents
between the file being repaired and the temporary file.  Record the high
level concepts behind how temporary files and atomic content swapping should work, and then present some case studies of what the actual repair functions do.

---
 .../filesystems/xfs-online-fsck-design.rst         |  574
++++++++++++++++++++

 1 file changed, 574 insertions(+)
Documentation/filesystems/xfs-online-fsck-design.rst +0 -0
index c0f08a773f08..e32506acb66f 100644
@@ -3252,6 +3252,8 @@ Proposed patchsets include fixing
Quoted 7 lines

 `dir iget usage
 <
https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/
log/?h=scrub-dir-iget-fixes>`_.

+.. _ilocking:
+

hmm, this little part look like maybe it was supposed to go in the last patch?

Quoted 102 lines

 Locking Inodes
 ^^^^^^^^^^^^^^

Documentation/filesystems/xfs-online-fsck-design.rst +0 -0
@@ -3695,3 +3697,575 @@ The proposed patchset is the

 `rmap repair
 <
https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/
log/?h=repair-rmap-btree>`_
 series.

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+
+Staging Repairs with Temporary Files on Disk
+--------------------------------------------
+
+XFS stores a substantial amount of metadata in file forks:

directories,
+extended attributes, symbolic link targets, free space bitmaps and summary

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+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

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+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

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+the file fork offset address space.
+
 
 
+In the initial iteration of file metadata repair, the damaged

metadata blocks
+would be scanned for salvageable data; the extents in the file fork would be

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+reaped; and then a new structure would be built in its place.
+This strategy did not survive the introduction of the atomic repair

requirement

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+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.

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+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 attr fork offset address
+  space.
+
+- Even if repair 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 as part of a range collapse means rewriting a large number of
+  blocks repeatedly, which is not conducive to quick repairs.

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+The third iteration of the design for file metadata repair went for
Quoted 2 lines

a totally
+new strategy --

All the above looks like something that could be culled or side bared. I know you really like these, but I think the extra dialog is why people are having a hard time getting through it.

Quoted 1 line

create a temporary file in the XFS filesystem, write a new

"The current design for metadata repair creates a temporary file..."

Quoted 230 lines

+structure at the correct offsets into the temporary file, and atomically swap
+the fork mappings (and hence the fork contents) 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

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+during log recovery.
+
+**Note**: All space usage and inode indices in the filesystem *must*

be

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+consistent to use a temporary file safely!
+This dependency is the reason why online repair can only use

pageable kernel

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+memory to stage ondisk space usage information.
+
+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

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+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

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+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 for correct operation of files 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.

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+Temporary files created for repair are similar to ``O_TMPFILE``

files created

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+by userspace.
+They are not linked into a directory and the entire file will be

reaped when

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+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.

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+
+Using a Temporary File
+``````````````````````
+
+Online repair code should use the ``xrep_tempfile_create`` function

to create a

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+temporary file inside the filesystem.
+This allocates an inode, marks the in-core inode private, and

attaches it to

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+the scrub context.
+These files are hidden from userspace, may not be added to the

directory tree,

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+and must be kept private.
+
+Temporary files only use two inode locks: the IOLOCK and the ILOCK.
+The MMAPLOCK is not needed here, because there must not be page

faults from

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+userspace for data fork blocks.
+The usage patterns of these two locks are the same as for any other

XFS file --
+access to file data are controlled via the IOLOCK, and access to file metadata

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+are controlled via the ILOCK.
+Locking helpers are provided so that the temporary file and its lock

state can

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+be cleaned up by the scrub context.
+To comply with the nested locking strategy laid out in the

:ref:`inode
+locking<ilocking>` section, it is recommended that scrub functions use the

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+xrep_tempfile_ilock*_nowait lock helpers.
+
+Data can be written to a temporary file by two means:
+
+1. ``xrep_tempfile_copyin`` can be used to set the contents of a

regular
+   temporary file from an xfile.
+
+2. The regular directory, symbolic link, and extended attribute functions can
+   be used to write to the temporary file.

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+Once a good copy of a data file has been constructed in a temporary

file, it
+must be conveyed to the file being repaired, which is the topic of the next

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+section.
+
+The proposed patches are in the
+`realtime summary repair
+<

https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/
log/?h=repair-rtsummary>`_

Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+series.
+
+Atomic Extent Swapping
+----------------------
+
+Once repair builds a temporary file with a new data structure

written into

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+it, it must commit the new changes into the existing file.
+It is not possible to swap the inumbers of two files, so instead the

new

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+metadata must replace the old.
+This suggests the need for the ability to swap extents, but the

existing extent
+swapping code used by the file defragmenting tool ``xfs_fsr`` is not sufficient

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+for online repair because:
+
+a. When the reverse-mapping btree is enabled, the swap code must

keep the
+   reverse mapping information up to date with every exchange of mappings.
+   Therefore, it can only exchange one mapping per transaction, and each
+   transaction is independent.

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+b. Reverse-mapping is critical for the operation of online fsck, so

the old
+   defragmentation code (which swapped entire extent forks in a single
+   operation) is not useful here.

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+c. Defragmentation is assumed to occur between two files with

identical
+   contents.
+   For this use case, an incomplete exchange will not result in a user-visible
+   change in file contents, even if the operation is interrupted.

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+d. Online repair needs to swap the contents of two files that are by

definition
+   *not* identical.
+   For directory and xattr repairs, the user-visible contents might be the
+   same, but the contents of individual blocks may be very different.

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+e. Old blocks in the file may be cross-linked with another structure

and must
+   not reappear if the system goes down mid-repair.

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+These problems are overcome by creating a new deferred operation and

a new type
+of log intent item to track the progress of an operation to exchange two file

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+ranges.
+The new deferred operation type chains together the same

transactions used by

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+the reverse-mapping extent swap code.
+The new log item records the progress of the exchange to ensure that

once an

Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+exchange begins, it will always run to completion, even there are
+interruptions.
+
+The proposed patchset is the
+`atomic extent swap
+<

https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/
log/?h=atomic-file-updates>`_

Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+series.
+
+Using Log-Incompatible Feature Flags
+````````````````````````````````````
+
+Starting with XFS v5, the superblock contains a

``sb_features_log_incompat``
+field to indicate that the log contains records that might not readable by all

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+kernels that could mount this filesystem.
 
 
+In short, log incompat features protect the log contents against

kernels that

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+will not understand the contents.
+Unlike the other superblock feature bits, log incompat bits are

ephemeral

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+because an empty (clean) log does not need protection.
+The log cleans itself after its contents have been committed into

the
+filesystem, either as part of an unmount or because the system is otherwise

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+idle.
+Because upper level code can be working on a transaction at the same

time that
+the log cleans itself, it is necessary for upper level code to communicate to

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+the log when it is going to use a log incompatible feature.
+
+The log coordinates access to incompatible features through the use

of one
+``struct rw_semaphore`` for each feature.
+The log cleaning code tries to take this rwsem in exclusive mode to clear the

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+bit; if the lock attempt fails, the feature bit remains set.
+Filesystem code signals its intention to use a log incompat feature

in a
+transaction by calling ``xlog_use_incompat_feat``, which takes the rwsem in

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+shared mode.
+The code supporting a log incompat feature should create wrapper

functions to
+obtain the log feature and call ``xfs_add_incompat_log_feature`` to set the

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+feature bits in the primary superblock.
+The superblock update is performed transactionally, so the wrapper

to obtain
+log assistance must be called just prior to the creation of the transaction

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+that uses the functionality.
+For a file operation, this step must happen after taking the IOLOCK

and the

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+MMAPLOCK, but before allocating the transaction.
+When the transaction is complete, the ``xlog_drop_incompat_feat``

function

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+is called to release the feature.
+The feature bit will not be cleared from the superblock until the
Quoted 2 lines

log becomes
+clean.

While this section does make sense, it doesnt really seem like it's specific to ofsck either. Pptrs and possibly other future features use the same incompat bit logic, but the implementation is pretty disjoint and I wouldnt really consider it part of that feature. So I would either remove this part, or move it to its own section. Then I would just give a quick blurb here about how ofsck uses it:

"Since atomic extent swap will introduce a new type of log item, it will also add a new XFS_SB_FEAT_INCOMPAT_LOG_ATOMIC_SWAP bit"

Quoted 5 lines
Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+Log-assisted extended attribute updates and atomic extent swaps both

use log
+incompat features and provide convenience wrappers around the functionality.

"For more information on incompat bits, see...."

Quoted 61 lines
Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+
+Mechanics of an Atomic Extent Swap
+``````````````````````````````````
+
+Swapping entire file forks is a complex task.
+The goal is to exchange all file fork mappings between two file fork

offset

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+ranges.
+There are likely to be many extent mappings in each fork, and the

edges of

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+the mappings aren't necessarily aligned.
+Furthermore, there may be other updates that need to happen after

the swap,
+such as exchanging file sizes, inode flags, or conversion of fork data to local

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+format.
+This is roughly the format of the new deferred extent swap work

item:

Documentation/filesystems/xfs-online-fsck-design.rst +14 -0
+
+.. code-block:: c
+
+       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;

Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+
+           /* XFS_SWAP_EXT_* log operation flags */
+           uint64_t            sxi_flags;
+       };
+
+The new log intent item contains enough information to track two

logical fork
+offset ranges: ``(inode1, startoff1, blockcount)`` and ``(inode2, startoff2,

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+blockcount)``.
+Each step of a swap operation exchanges the largest file range

mapping possible

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+from one file to the other.
+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

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+if the file data fork is the target of the swap operation.
+
+When the extent swap is initiated, the sequence of operations is as
Quoted 8 lines

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. Call ``xfs_defer_finish``

This seems like this should be some sort of defer start wrapper, not finish. It would also help to have a link or function name to see the code it is trying to describe

Quoted 160 lines

to start processing of the exchange.
+   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,
+
+   a. Read the block maps of both file ranges starting at ``sxi_startoff1`` and
+      ``sxi_startoff2``, respectively, and compute the longest extent that can
+      be swapped 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.
+      Mutual holes, unwritten extents, and extent mappings to the same physical
+      space are not exchanged.
+
+      For the next few steps, this document will refer to the mapping that came
+      from file 1 as "map1", and the mapping that came from file 2 as "map2".
+
+   b. Create a deferred block mapping update to unmap map1 from file 1.
+
+   c. Create a deferred block mapping update to unmap map2 from file 2.
+
+   d. Create a deferred block mapping update to map map1 into file 2.
+
+   e. Create a deferred block mapping update to map map2 into file 1.

Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+
+   f. Log the block, quota, and extent count updates for both files.
+
+   g. Extend the ondisk size of either file if necessary.
+
+   h. Log an extent swap done log item for the extent swap intent

log item
+      that was read at the start of step 3.

Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+
+   i. Compute the amount of file range that has just been covered.
+      This quantity is ``(map1.br_startoff + map1.br_blockcount -
+      sxi_startoff1)``, because step 3a could have skipped holes.
+
+   j. Increase the starting offsets of ``sxi_startoff1`` and

``sxi_startoff2``
+      by the number of blocks computed in the previous step, and decrease
+      ``sxi_blockcount`` by the same quantity.
+      This advances the cursor.
+
+   k. Log a new extent swap intent log item reflecting the advanced state of
+      the work item.
+
+   l. 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 back to the start of step 3.

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+
+4. Perform any post-processing.
+   This will be discussed in more detail in subsequent sections.
+
+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

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+there.
+This is how extent swapping guarantees that an outside observer will

either see
+the old broken structure or the new one, and never a mismash of both.

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+
+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

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+raw bytes in each inode fork'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

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+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

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+swap mappings one at a time.
+This mechanism is identical to steps 2-3 from the procedure above

except for
+the new tracking items, because the atomic extent swap mechanism is an

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+iteration of an existing mechanism and not something totally novel.
+For the narrow case of file defragmentation, the file contents must

be

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+identical, so the recovery guarantees are not much of a gain.
+
+Atomic extent swapping is much more flexible than the existing

swapext
+implementations 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

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+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.

Quoted 8 lines

+  Stage all writes to a temporary file, and when that is complete, call the
+  atomic extent swap system call with a flag to indicate that holes in the
+  temporary file should be ignored.
+  This emulates an atomic device write in software, and can support arbitrary
+  scattered writes.

Mmm, this section here I would either let go or move. Since we're not really talking about ofsc anymore, it's more like an "extra use case" section. Side uses are great and all, but they're generally not worth the implementation on their own, so I think we want to keep readers focused on the main ofsck feature and it's mechanics. Once we get that out of the way, we can come back and touch on goodies later at the end of the document.

Quoted 69 lines
Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+
+Preparation for Extent Swapping
+```````````````````````````````
+
+There are a few things that need to be taken care of before

initiating an

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+atomic extent swap operation.
+First, regular files require the page cache to be flushed to disk

before the

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+operation begins, and directio writes to be quiesced.
+Like any filesystem operation, extent swapping 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

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+out of space failure once it starts dirtying metadata.
+The preparation step scans 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 will be added to each file.
+- Whether or not there are partially written realtime extents.

+  User programs must never be able to access a realtime file extent that maps
+  to different extents on the realtime volume, which could happen if the
+  operation fails to run to completion.

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+The need for precise estimation increases the run time of the swap

operation,

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+but it is very important to maintain correct accounting.
+The filesystem must not run completely out of free space, nor can

the extent

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+swap ever add more extent mappings to a fork than it can support.
+Regular users are required to abide the quota limits, though

metadata repairs

Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+may exceed quota to resolve inconsistent metadata elsewhere.
+
+Special Features for Swapping Metadata File Extents
+```````````````````````````````````````````````````
+
+Extended attributes, symbolic links, and directories can set the

fork format to
+"local" and treat the fork as a literal area for data storage.

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+Metadata repairs must take extra steps to support these cases:
+
+- If both forks are in local format and the fork areas are large

enough, the
+  swap is performed by copying the incore fork contents, logging both forks,
+  and committing.
+  The atomic extent swap mechanism is not necessary, since this can be done
+  with a single transaction.
+
+- If both forks map blocks, then the regular atomic extent swap is used.
+
+- Otherwise, only one fork is in local format.
+  The contents of the local format fork are converted to a block to perform the
+  swap.
+  The conversion to block format must be done in the same

Quoted 8 lines

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 one more time to convert the second file's fork back to local format
+  if possible.

I feel like there's probably a function name or link that could go with this

Quoted 46 lines
Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+Extended attributes and directories stamp the owning inode into

every block,

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+but the buffer verifiers do not actually check the inode number!
+Although there is no verification, it is still important to maintain
+referential integrity, so prior to performing the extent swap,

online repair
+walks every block in the new data structure to update the owner field and flush

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+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 :ref:`file extent

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+reaping <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

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+whatever blocks were not reaped.
+However, this iunlink processing omits the cross-link detection of

online

Documentation/filesystems/xfs-online-fsck-design.rst +10 -0
+repair, and is not completely foolproof.
+
+Swapping Temporary File Extents
+```````````````````````````````
+
+To repair a metadata file, online repair proceeds as follows:
+
+1. Create a temporary repair file.
+
+2. Use the staging data to write out new contents into the temporary

repair
+   file.
+   The same fork must be written to as is being repaired. +
+3. Commit the scrub transaction, since the swap estimation step must be
+   completed before transaction reservations are made.
+
+4. Call ``xrep_tempswap_trans_alloc`` to allocate a new scrub transaction with
+   the appropriate resource reservations, locks, and fill out a ``struct
+   xfs_swapext_req`` with the details of the swap operation.

Documentation/filesystems/xfs-online-fsck-design.rst The proposed patchset is the · line 4179

Quoted 4 lines
Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+
+5. Call ``xrep_tempswap_contents`` to swap the contents.
+
+6. Commit the transaction to complete the repair.

Here too. A reference to the code would help to be able to see it side by side

Quoted 56 lines
Documentation/filesystems/xfs-online-fsck-design.rst +7 -0
+
+.. _rtsummary:
+
+Case Study: Repairing the Realtime Summary File
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+In the "realtime" section of an XFS filesystem, free space is

tracked via a

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+bitmap, similar to Unix FFS.
+Each bit in the bitmap represents one realtime extent, which is a

multiple of

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+the filesystem block size between 4KiB and 1GiB in size.
+The realtime summary file indexes the number of free extents of a

given size to
+the offset of the block within the realtime free space bitmap where those free

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+extents begin.
+In other words, the summary file helps the allocator find free

extents by
+length, similar to what the free space by count (cntbt) btree does for the data

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+section.
+
+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

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+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

Documentation/filesystems/xfs-online-fsck-design.rst +9 -0
+and can satisfy a power-of-two allocation request.
+
+To check the summary file against the bitmap:
+
+1. Take the ILOCK of both the realtime bitmap and summary files.
+
+2. For each free space extent recorded in the bitmap:
+
+   a. Compute the position in the summary file that contains a

counter that
+      represents this free extent.

Documentation/filesystems/xfs-online-fsck-design.rst +8 -0
+
+   b. Read the counter from the xfile.
+
+   c. Increment it, and write it back to the xfile.
+
+3. Compare the contents of the xfile against the ondisk file.
+
+To repair the summary file, write the xfile contents into the

temporary file

Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+and use atomic extent swap to commit the new contents.
+The temporary file is then reaped.
+
+The proposed patchset is the
+`realtime summary repair
+<
Quoted 2 lines

https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/
log/?h=repair-rtsummary>`_

I think this is the same link as the last. Did you mean to have a different link here?

Quoted 59 lines
Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+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

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+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

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+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

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+for fast lookup.
+
+Salvaging extended attributes is done as follows:
+
+1. Walk the attr fork mappings of the file being repaired to find

the attribute
+   leaf blocks.
+   When one is found,

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+
+   a. Walk the attr leaf block to find candidate keys.
+      When one is found,
+
+      1. Check the name for problems, and ignore the name if there

are.
+
+      2. Retrieve the value.
+         If that succeeds, add the name and value to the staging xfarray and
+         xfblob.
+
+2. If the memory usage of the xfarray and xfblob exceed a certain amount of
+   memory or there are no more attr fork blocks to examine, unlock the file and
+   add the staged extended attributes to the temporary file. +
+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.

Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+
+4. Reap the temporary file.
+
+The proposed patchset is the
+`extended attribute repair
+<
Quoted 3 lines

https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/
log/?h=repair-xattrs>`_
+series.

I think it mostly looks good, culling and link suggestions aside.

Allison

Quoted 1 line
#51 lore raw

Re: [PATCH 11/14] xfs: document metadata file repair

Quoted 22 lines · Allison Henderson
Quoted 21 lines · Darrick J. Wong

From: Darrick J. Wong <[email protected]>

File-based metadata (such as xattrs and directories) can be extremely large.  To reduce the memory requirements and maximize code reuse, it is
very convenient to create a temporary file, use the regular dir/attr code to store salvaged information, and then atomically swap the extents
between the file being repaired and the temporary file.  Record the high
level concepts behind how temporary files and atomic content swapping should work, and then present some case studies of what the actual repair functions do.

---
 .../filesystems/xfs-online-fsck-design.rst         |  574
++++++++++++++++++++

 1 file changed, 574 insertions(+)
Quoted 15 lines
Quoted 6 lines
Documentation/filesystems/xfs-online-fsck-design.rst +0 -0
index c0f08a773f08..e32506acb66f 100644
@@ -3252,6 +3252,8 @@ Proposed patchsets include fixing
Quoted 7 lines

 `dir iget usage
 <
https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/
log/?h=scrub-dir-iget-fixes>`_.

+.. _ilocking:
+

hmm, this little part look like maybe it was supposed to go in the last patch?

It's a link target for the header header that comes after it. There weren't any links pointing to the target until this patch, so I didn't introduce the target until now.

(I wish that unused link targets would be benign, but the build system complains about them. OTOH there are plenty of other link target warnings until you get to the final patch in this series, so...)

(So I don't really feel like fixing this.)

Quoted 99 lines
Quoted 99 lines

 Locking Inodes
 ^^^^^^^^^^^^^^

Documentation/filesystems/xfs-online-fsck-design.rst +0 -0
@@ -3695,3 +3697,575 @@ The proposed patchset is the

 `rmap repair
 <
https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/
log/?h=repair-rmap-btree>`_
 series.

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+
+Staging Repairs with Temporary Files on Disk
+--------------------------------------------
+
+XFS stores a substantial amount of metadata in file forks:

directories,
+extended attributes, symbolic link targets, free space bitmaps and summary

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+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

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+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

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+the file fork offset address space.
+
 
 
+In the initial iteration of file metadata repair, the damaged

metadata blocks
+would be scanned for salvageable data; the extents in the file fork would be

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+reaped; and then a new structure would be built in its place.
+This strategy did not survive the introduction of the atomic repair

requirement

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+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.

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+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 attr fork offset address
+  space.
+
+- Even if repair 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 as part of a range collapse means rewriting a large number of

Quoted 8 lines
Quoted 5 lines

+  blocks repeatedly, which is not conducive to quick repairs.

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+The third iteration of the design for file metadata repair went for

a totally
+new strategy --

All the above looks like something that could be culled or side bared. I know you really like these, but I think the extra dialog is why people are having a hard time getting through it.

<nod> I'll sidebar all the historical data.

Quoted 2 lines
Quoted 1 line

create a temporary file in the XFS filesystem, write a new

"The current design for metadata repair creates a temporary file..."

This paragraph now reads:

"Because file forks can consume as much space as the entire filesystem, repairs cannot be staged in memory, even when a paging scheme is available. Therefore, online repair of file-based metadata createas a temporary file in the XFS filesystem, writes a new structure at the correct offsets into the temporary file, and atomically swaps the fork mappings (and hence the fork contents) to commit the repair..."

Quoted 239 lines
Quoted 230 lines

+structure at the correct offsets into the temporary file, and atomically swap
+the fork mappings (and hence the fork contents) 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

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+during log recovery.
+
+**Note**: All space usage and inode indices in the filesystem *must*

be

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+consistent to use a temporary file safely!
+This dependency is the reason why online repair can only use

pageable kernel

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+memory to stage ondisk space usage information.
+
+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

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+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

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+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 for correct operation of files 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.

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+Temporary files created for repair are similar to ``O_TMPFILE``

files created

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+by userspace.
+They are not linked into a directory and the entire file will be

reaped when

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+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.

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+
+Using a Temporary File
+``````````````````````
+
+Online repair code should use the ``xrep_tempfile_create`` function

to create a

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+temporary file inside the filesystem.
+This allocates an inode, marks the in-core inode private, and

attaches it to

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+the scrub context.
+These files are hidden from userspace, may not be added to the

directory tree,

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+and must be kept private.
+
+Temporary files only use two inode locks: the IOLOCK and the ILOCK.
+The MMAPLOCK is not needed here, because there must not be page

faults from

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+userspace for data fork blocks.
+The usage patterns of these two locks are the same as for any other

XFS file --
+access to file data are controlled via the IOLOCK, and access to file metadata

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+are controlled via the ILOCK.
+Locking helpers are provided so that the temporary file and its lock

state can

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+be cleaned up by the scrub context.
+To comply with the nested locking strategy laid out in the

:ref:`inode
+locking<ilocking>` section, it is recommended that scrub functions use the

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+xrep_tempfile_ilock*_nowait lock helpers.
+
+Data can be written to a temporary file by two means:
+
+1. ``xrep_tempfile_copyin`` can be used to set the contents of a

regular
+   temporary file from an xfile.
+
+2. The regular directory, symbolic link, and extended attribute functions can
+   be used to write to the temporary file.

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+Once a good copy of a data file has been constructed in a temporary

file, it
+must be conveyed to the file being repaired, which is the topic of the next

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+section.
+
+The proposed patches are in the
+`realtime summary repair
+<

https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/
log/?h=repair-rtsummary>`_

Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+series.
+
+Atomic Extent Swapping
+----------------------
+
+Once repair builds a temporary file with a new data structure

written into

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+it, it must commit the new changes into the existing file.
+It is not possible to swap the inumbers of two files, so instead the

new

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+metadata must replace the old.
+This suggests the need for the ability to swap extents, but the

existing extent
+swapping code used by the file defragmenting tool ``xfs_fsr`` is not sufficient

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+for online repair because:
+
+a. When the reverse-mapping btree is enabled, the swap code must

keep the
+   reverse mapping information up to date with every exchange of mappings.
+   Therefore, it can only exchange one mapping per transaction, and each
+   transaction is independent.

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+b. Reverse-mapping is critical for the operation of online fsck, so

the old
+   defragmentation code (which swapped entire extent forks in a single
+   operation) is not useful here.

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+c. Defragmentation is assumed to occur between two files with

identical
+   contents.
+   For this use case, an incomplete exchange will not result in a user-visible
+   change in file contents, even if the operation is interrupted.

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+d. Online repair needs to swap the contents of two files that are by

definition
+   *not* identical.
+   For directory and xattr repairs, the user-visible contents might be the
+   same, but the contents of individual blocks may be very different.

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+e. Old blocks in the file may be cross-linked with another structure

and must
+   not reappear if the system goes down mid-repair.

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+These problems are overcome by creating a new deferred operation and

a new type
+of log intent item to track the progress of an operation to exchange two file

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+ranges.
+The new deferred operation type chains together the same

transactions used by

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+the reverse-mapping extent swap code.
+The new log item records the progress of the exchange to ensure that

once an

Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+exchange begins, it will always run to completion, even there are
+interruptions.
+
+The proposed patchset is the
+`atomic extent swap
+<

https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/
log/?h=atomic-file-updates>`_

Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+series.
+
+Using Log-Incompatible Feature Flags
+````````````````````````````````````
+
+Starting with XFS v5, the superblock contains a

``sb_features_log_incompat``
+field to indicate that the log contains records that might not readable by all

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+kernels that could mount this filesystem.
 
 
+In short, log incompat features protect the log contents against

kernels that

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+will not understand the contents.
+Unlike the other superblock feature bits, log incompat bits are

ephemeral

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+because an empty (clean) log does not need protection.
+The log cleans itself after its contents have been committed into

the
+filesystem, either as part of an unmount or because the system is otherwise

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+idle.
+Because upper level code can be working on a transaction at the same

time that
+the log cleans itself, it is necessary for upper level code to communicate to

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+the log when it is going to use a log incompatible feature.
+
+The log coordinates access to incompatible features through the use

of one
+``struct rw_semaphore`` for each feature.
+The log cleaning code tries to take this rwsem in exclusive mode to clear the

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+bit; if the lock attempt fails, the feature bit remains set.
+Filesystem code signals its intention to use a log incompat feature

in a
+transaction by calling ``xlog_use_incompat_feat``, which takes the rwsem in

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+shared mode.
+The code supporting a log incompat feature should create wrapper

functions to
+obtain the log feature and call ``xfs_add_incompat_log_feature`` to set the

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+feature bits in the primary superblock.
+The superblock update is performed transactionally, so the wrapper

to obtain
+log assistance must be called just prior to the creation of the transaction

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+that uses the functionality.
+For a file operation, this step must happen after taking the IOLOCK

and the

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+MMAPLOCK, but before allocating the transaction.
+When the transaction is complete, the ``xlog_drop_incompat_feat``

function

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+is called to release the feature.
+The feature bit will not be cleared from the superblock until the
Quoted 2 lines

log becomes
+clean.

While this section does make sense, it doesnt really seem like it's specific to ofsck either. Pptrs and possibly other future features use the same incompat bit logic, but the implementation is pretty disjoint and I wouldnt really consider it part of that feature. So I would either remove this part, or move it to its own section. Then I would just give a quick blurb here about how ofsck uses it:

Quoted 2 lines

"Since atomic extent swap will introduce a new type of log item, it will also add a new XFS_SB_FEAT_INCOMPAT_LOG_ATOMIC_SWAP bit"

Ok, I'll add that at the end of the section above, and turn this into a sidebar.

Quoted 72 lines
Quoted 5 lines
Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+Log-assisted extended attribute updates and atomic extent swaps both

use log
+incompat features and provide convenience wrappers around the functionality.

"For more information on incompat bits, see...."

Quoted 64 lines
Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+
+Mechanics of an Atomic Extent Swap
+``````````````````````````````````
+
+Swapping entire file forks is a complex task.
+The goal is to exchange all file fork mappings between two file fork

offset

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+ranges.
+There are likely to be many extent mappings in each fork, and the

edges of

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+the mappings aren't necessarily aligned.
+Furthermore, there may be other updates that need to happen after

the swap,
+such as exchanging file sizes, inode flags, or conversion of fork data to local

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+format.
+This is roughly the format of the new deferred extent swap work

item:

Documentation/filesystems/xfs-online-fsck-design.rst +14 -0
+
+.. code-block:: c
+
+       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;

Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+
+           /* XFS_SWAP_EXT_* log operation flags */
+           uint64_t            sxi_flags;
+       };
+
+The new log intent item contains enough information to track two

logical fork
+offset ranges: ``(inode1, startoff1, blockcount)`` and ``(inode2, startoff2,

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+blockcount)``.
+Each step of a swap operation exchanges the largest file range

mapping possible

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+from one file to the other.
+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

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+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.

Quoted 8 lines
Quoted 5 lines

+   At the start, it should contain the entirety of the file ranges to be
+   swapped.
+
+2. Call ``xfs_defer_finish``

This seems like this should be some sort of defer start wrapper, not finish. It would also help to have a link or function name to see the code it is trying to describe

It's encapsulated in xrep_tempswap_contents in tempfile.c; I'll make a note of that here.

Quoted 167 lines
Quoted 167 lines

to start processing of the exchange.
+   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,
+
+   a. Read the block maps of both file ranges starting at ``sxi_startoff1`` and
+      ``sxi_startoff2``, respectively, and compute the longest extent that can
+      be swapped 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.
+      Mutual holes, unwritten extents, and extent mappings to the same physical
+      space are not exchanged.
+
+      For the next few steps, this document will refer to the mapping that came
+      from file 1 as "map1", and the mapping that came from file 2 as "map2".
+
+   b. Create a deferred block mapping update to unmap map1 from file 1.
+
+   c. Create a deferred block mapping update to unmap map2 from file 2.
+
+   d. Create a deferred block mapping update to map map1 into file 2.
+
+   e. Create a deferred block mapping update to map map2 into file 1.

Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+
+   f. Log the block, quota, and extent count updates for both files.
+
+   g. Extend the ondisk size of either file if necessary.
+
+   h. Log an extent swap done log item for the extent swap intent

log item
+      that was read at the start of step 3.

Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+
+   i. Compute the amount of file range that has just been covered.
+      This quantity is ``(map1.br_startoff + map1.br_blockcount -
+      sxi_startoff1)``, because step 3a could have skipped holes.
+
+   j. Increase the starting offsets of ``sxi_startoff1`` and

``sxi_startoff2``
+      by the number of blocks computed in the previous step, and decrease
+      ``sxi_blockcount`` by the same quantity.
+      This advances the cursor.
+
+   k. Log a new extent swap intent log item reflecting the advanced state of
+      the work item.
+
+   l. 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 back to the start of step 3.

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+
+4. Perform any post-processing.
+   This will be discussed in more detail in subsequent sections.
+
+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

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+there.
+This is how extent swapping guarantees that an outside observer will

either see
+the old broken structure or the new one, and never a mismash of both.

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+
+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

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+raw bytes in each inode fork'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

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+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

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+swap mappings one at a time.
+This mechanism is identical to steps 2-3 from the procedure above

except for
+the new tracking items, because the atomic extent swap mechanism is an

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+iteration of an existing mechanism and not something totally novel.
+For the narrow case of file defragmentation, the file contents must

be

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+identical, so the recovery guarantees are not much of a gain.
+
+Atomic extent swapping is much more flexible than the existing

swapext
+implementations 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

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+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.
+  Stage all writes to a temporary file, and when that is complete, call the
+  atomic extent swap system call with a flag to indicate that holes in the
+  temporary file should be ignored.
+  This emulates an atomic device write in software, and can support arbitrary

Quoted 8 lines
Quoted 1 line

+  scattered writes.

Mmm, this section here I would either let go or move. Since we're not really talking about ofsc anymore, it's more like an "extra use case" section. Side uses are great and all, but they're generally not worth the implementation on their own, so I think we want to keep readers focused on the main ofsck feature and it's mechanics. Once we get that out of the way, we can come back and touch on goodies later at the end of the document.

Good point. I'll chop this out and put it in the future work section.

Quoted 71 lines
Quoted 71 lines
Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+
+Preparation for Extent Swapping
+```````````````````````````````
+
+There are a few things that need to be taken care of before

initiating an

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+atomic extent swap operation.
+First, regular files require the page cache to be flushed to disk

before the

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+operation begins, and directio writes to be quiesced.
+Like any filesystem operation, extent swapping 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

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+out of space failure once it starts dirtying metadata.
+The preparation step scans 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 will be added to each file.
+- Whether or not there are partially written realtime extents.

+  User programs must never be able to access a realtime file extent that maps
+  to different extents on the realtime volume, which could happen if the
+  operation fails to run to completion.

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+The need for precise estimation increases the run time of the swap

operation,

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+but it is very important to maintain correct accounting.
+The filesystem must not run completely out of free space, nor can

the extent

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+swap ever add more extent mappings to a fork than it can support.
+Regular users are required to abide the quota limits, though

metadata repairs

Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+may exceed quota to resolve inconsistent metadata elsewhere.
+
+Special Features for Swapping Metadata File Extents
+```````````````````````````````````````````````````
+
+Extended attributes, symbolic links, and directories can set the

fork format to
+"local" and treat the fork as a literal area for data storage.

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+Metadata repairs must take extra steps to support these cases:
+
+- If both forks are in local format and the fork areas are large

enough, the
+  swap is performed by copying the incore fork contents, logging both forks,
+  and committing.
+  The atomic extent swap mechanism is not necessary, since this can be done
+  with a single transaction.
+
+- If both forks map blocks, then the regular atomic extent swap is used.
+
+- Otherwise, only one fork is in local format.
+  The contents of the local format fork are converted to a block to perform the
+  swap.
+  The conversion to block format must be done in the same transaction that
+  logs the initial extent swap intent log item.

Quoted 8 lines
Quoted 6 lines

+  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 one more time to convert the second file's fork back to local format
+  if possible.

I feel like there's probably a function name or link that could go with this

It's ... scattered everywhere. For example, the directory repair code converts the temporary file from shortform to block format if necessary. Then it calls xrep_tempswap_contents. The last step of the atomic swap is to convert block metadata back to shortform on the file being scrubbed, which happens before control is returned to the directory repair code.

Before the repair, we don't care if the temporary file could have been shortform, and after the exchange, everything in the file being scrubbed
/must/ be correct. That's why the responsibilities are split the way
they are.

Quoted 44 lines
Quoted 44 lines
Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+
+Extended attributes and directories stamp the owning inode into

every block,

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+but the buffer verifiers do not actually check the inode number!
+Although there is no verification, it is still important to maintain
+referential integrity, so prior to performing the extent swap,

online repair
+walks every block in the new data structure to update the owner field and flush

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+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 :ref:`file extent

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+reaping <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

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+whatever blocks were not reaped.
+However, this iunlink processing omits the cross-link detection of

online

Documentation/filesystems/xfs-online-fsck-design.rst +10 -0
+repair, and is not completely foolproof.
+
+Swapping Temporary File Extents
+```````````````````````````````
+
+To repair a metadata file, online repair proceeds as follows:
+
+1. Create a temporary repair file.
+
+2. Use the staging data to write out new contents into the temporary

repair
+   file.
+   The same fork must be written to as is being repaired. +
+3. Commit the scrub transaction, since the swap estimation step must be
+   completed before transaction reservations are made.
+
+4. Call ``xrep_tempswap_trans_alloc`` to allocate a new scrub transaction with
+   the appropriate resource reservations, locks, and fill out a

Quoted 8 lines

Documentation/filesystems/xfs-online-fsck-design.rst The proposed patchset is the · line 4179

Quoted 6 lines

``struct
+   xfs_swapext_req`` with the details of the swap operation.

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+
+5. Call ``xrep_tempswap_contents`` to swap the contents.
+
+6. Commit the transaction to complete the repair.

Here too. A reference to the code would help to be able to see it side by side

It's the xfs_trans_commit in xchk_teardown, same as any other repair function.

Quoted 52 lines
Quoted 52 lines
Documentation/filesystems/xfs-online-fsck-design.rst +7 -0
+
+.. _rtsummary:
+
+Case Study: Repairing the Realtime Summary File
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+In the "realtime" section of an XFS filesystem, free space is

tracked via a

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+bitmap, similar to Unix FFS.
+Each bit in the bitmap represents one realtime extent, which is a

multiple of

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+the filesystem block size between 4KiB and 1GiB in size.
+The realtime summary file indexes the number of free extents of a

given size to
+the offset of the block within the realtime free space bitmap where those free

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+extents begin.
+In other words, the summary file helps the allocator find free

extents by
+length, similar to what the free space by count (cntbt) btree does for the data

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+section.
+
+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

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+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

Documentation/filesystems/xfs-online-fsck-design.rst +9 -0
+and can satisfy a power-of-two allocation request.
+
+To check the summary file against the bitmap:
+
+1. Take the ILOCK of both the realtime bitmap and summary files.
+
+2. For each free space extent recorded in the bitmap:
+
+   a. Compute the position in the summary file that contains a

counter that
+      represents this free extent.

Documentation/filesystems/xfs-online-fsck-design.rst +8 -0
+
+   b. Read the counter from the xfile.
+
+   c. Increment it, and write it back to the xfile.
+
+3. Compare the contents of the xfile against the ondisk file.
+
+To repair the summary file, write the xfile contents into the

temporary file

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+and use atomic extent swap to commit the new contents.
+The temporary file is then reaped.
Quoted 8 lines
Quoted 6 lines
Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+
+The proposed patchset is the
+`realtime summary repair
+<

https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/
log/?h=repair-rtsummary>`_

I think this is the same link as the last. Did you mean to have a different link here?

Ooh, you're right, it's the previous link that should have bene to the repair-tempfiles branch. Thank you for catching this.

Quoted 56 lines
Quoted 56 lines
Documentation/filesystems/xfs-online-fsck-design.rst +6 -0
+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

Documentation/filesystems/xfs-online-fsck-design.rst +2 -0
+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

Documentation/filesystems/xfs-online-fsck-design.rst +4 -0
+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

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+for fast lookup.
+
+Salvaging extended attributes is done as follows:
+
+1. Walk the attr fork mappings of the file being repaired to find

the attribute
+   leaf blocks.
+   When one is found,

Documentation/filesystems/xfs-online-fsck-design.rst +5 -0
+
+   a. Walk the attr leaf block to find candidate keys.
+      When one is found,
+
+      1. Check the name for problems, and ignore the name if there

are.
+
+      2. Retrieve the value.
+         If that succeeds, add the name and value to the staging xfarray and
+         xfblob.
+
+2. If the memory usage of the xfarray and xfblob exceed a certain amount of
+   memory or there are no more attr fork blocks to examine, unlock the file and
+   add the staged extended attributes to the temporary file. +
+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.

Documentation/filesystems/xfs-online-fsck-design.rst +3 -0
+
+4. Reap the temporary file.
+
Quoted 8 lines
Quoted 6 lines

+The proposed patchset is the
+`extended attribute repair
+<
https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/
log/?h=repair-xattrs>`_
+series.

I think it mostly looks good, culling and link suggestions aside.

Thanks!

--D

Quoted 4 lines

Allison

Quoted 1 line
#52 lore raw

PATCH 12/14 xfs: document directory tree repairs

In reply to Darrick J. Wong

From: Darrick J. Wong <[email protected]>

Directory tree repairs are the least complete part of online fsck, due to the lack of directory parent pointers. However, even without that feature, we can still make some corrections to the directory tree -- we can salvage as many directory entries as we can from a damaged directory, and we can reattach orphaned inodes to the lost+found, just as xfs_repair does now.

---
 .../filesystems/xfs-online-fsck-design.rst         |  236 ++++++++++++++++++++
 1 file changed, 236 insertions(+)
Documentation/filesystems/xfs-online-fsck-design.rst +236 -0
index e32506acb66f..2e20314f1831 100644
@@ -4269,3 +4269,239 @@ The proposed patchset is the
 `extended attribute repair
 <https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/log/?h=repair-xattrs>`_
 series.
+
+Fixing Directories
+------------------
+
+Fixing directories is difficult with currently available filesystem features.
+The offline repair tool scans all inodes to find files with nonzero link count,
+and then it scans all directories to establish parentage of those linked files.
+Damaged files and directories are zapped, and files with no parent are
+moved to the ``/lost+found`` directory.
+It does not try to salvage anything.
+
+The best that online repair can do at this time is to read directory data
+blocks and salvage any dirents that look plausible, correct link counts, and
+move orphans back into the directory tree.
+The salvage process is discussed in the case study at the end of this section.
+The second component to fixing the directory tree online is the :ref:`file link
+count fsck <nlinks>`, since it can scan the entire filesystem to make sure that
+files can neither be deleted while there are still parents nor forgotten after
+all parents sever their links to the child.
+The third part is discussed at the :ref:`end of this section<orphanage>`.
+However, there may be a solution to these deficiencies soon!
+
+Parent Pointers
+```````````````
+
+The lack of secondary directory metadata hinders directory tree reconstruction
+in much the same way that the historic lack of reverse space mapping
+information once hindered reconstruction of filesystem space metadata.
+Specifically, the lack of redundant metadata makes it nearly impossible to
+construct a true replacement for a damaged directory; the best repair can do is
+to salvage the dirents and use the file link count repair function to move
+orphaned files to the lost and found.
+The proposed parent pointer feature, however, will make total directory
+reconstruction possible.
+
+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 was
+augmented by an extended attribute in the child that could be used to identify
+the parent directory.
+Unfortunately, this early implementation had several major shortcomings:
+
+1. 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.
+
+2. Referential integrity was not integrated into either offline repair tool.
+   Checking had to be done online without taking any kernel or inode locks to
+   coordinate access.
+   It is not clear if this actually worked properly.
+
+3. 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.
+
+4. Extended attribute forks only support 65,536 extents, which means that
+   parent pointer attribute creation is likely to fail at some point before the
+   maximum file link count is achieved.
+
+In the second implementation (currently being developed by Allison Henderson
+and Chandan Babu), 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 maximum extent counts of both the data and attribute forks have raised to
+allow for creation of as many parent pointers as possible.
+The parent pointer data will also include the entry name and location within
+the parent.
+In other words, child files will store parent pointer mappings of the form
+``(parent_ino, parent_gen, dirent_pos) → (dirent_name)`` in their 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 the parent pointer feature lands, the directory checking process can be
+strengthened to ensure that the target of each dirent also contains a parent
+pointer pointing back to the dirent.
+The quality of directory repairs will improve because online fsck will be able
+to reconstruct a directory in its entirety instead of skipping unsalvageable
+areas.
+This process is imagined to involve a :ref:`coordinated inode scan <iscan>` and
+a :ref:`directory entry live update hook <liveupdate>`:
+Scan every file in the entire filesystem, and every time the scan encounters a
+file with a parent pointer to the directory that is being reconstructed, record
+this entry in the temporary directory.
+When the scan is complete, atomically swap the contents of the temporary
+directory and the directory being repaired.
+This code has not yet been constructed, so there is not yet a case study laying
+out exactly how this process works.
+
+Parent pointers themselves can be checked by scanning each pointer and
+verifying that the target of the pointer is a directory and that it contains a
+dirent that corresponds to the information recorded in the parent pointer.
+Reconstruction of the parent pointer information will work similarly to
+directory reconstruction -- scan the filesystem, record the dirents pointing to
+the file being repaired, and rebuild that part of the xattr namespace.
+
+**Question**: How will repair ensure that the ``dirent_pos`` fields match in
+the reconstructed directory?
+
+*Answer*: The field could be designated advisory, since the other three values
+are sufficient to find the entry in the parent.
+However, this makes indexed key lookup impossible while repairs are ongoing.
+A second option would be to allow creating directory entries at specified
+offsets, which solves the referential integrity problem but runs the risk that
+dirent creation will fail due to conflicts with the free space in the
+directory.
+These conflicts could be resolved by appending the directory entry and amending
+the xattr code to support updating an xattr key and reindexing the dabtree,
+though this would have to be performed with the parent directory still locked.
+A fourth option would be to remove the parent pointer entry and re-add it
+atomically.
+
+Case Study: Salvaging Directories
+`````````````````````````````````
+
+Unlike extended attributes, 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,
+
+   a. Walk the directory data block to find candidate entries.
+      When an entry is found:
+
+      i. Check the name for problems, and ignore the name if there are.
+
+      ii. Retrieve the inumber and grab the inode.
+          If that succeeds, add the name, inode number, and file type to the
+          staging xfarray and xblob.
+
+3. If the memory usage of the xfarray and xfblob exceed a certain amount of
+   memory or there are no more directory data blocks to examine, unlock the
+   directory and add the staged dirents into the temporary directory.
+   Truncate the staging files.
+
+4. Use atomic extent swapping to exchange the new and old directory structures.
+   The old directory blocks are now attached to the temporary file.
+
+5. Reap the temporary file.
+
+**Question**: Should repair invalidate dentries when rebuilding a directory?
+
+**Question**: Can the dentry cache know about a directory entry that cannot be
+salvaged?
+
+In theory, the dentry cache should be a subset of the directory entries on disk
+because there's no way to load a dentry without having something to read in the
+directory.
+However, it is possible for a coherency problem to be introduced if the ondisk
+structures becomes corrupt *after* the cache loads.
+In theory it is necessary to scan all dentry cache entries for a directory to
+ensure that one of the following apply:
+
+1. The cached dentry reflects an ondisk dirent in the new directory.
+
+2. The cached dentry no longer has a corresponding ondisk dirent in the new
+   directory and the dentry can be purged from the cache.
+
+3. The cached dentry no longer has an ondisk dirent but the dentry cannot be
+   purged.
+   This is bad.
+
+Unfortunately, the dentry cache does not have a means to walk all the dentries
+with a particular directory as a parent.
+This makes detecting situations #2 and #3 impossible, and remains an
+interesting question for research.
+
+The proposed patchset is the
+`directory repair
+<https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/log/?h=repair-dirs>`_
+series.
+
+.. _orphanage:
+
+The Orphanage
+-------------
+
+Filesystems present files as a directed, and hopefully acyclic, graph.
+In other words, a tree.
+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 that isn't pointed
+to by any directory in the filesystem.
+If the file in question has a positive link count, the file in question is an
+orphan.
+
+When orphans are found, they should be reconnected to the directory tree.
+Offline fsck solves the problem by creating a directory ``/lost+found`` to
+serve as an orphanage, and linking orphan files into the orphanage by using the
+inumber as the name.
+Reparenting a file to the orphanage does not reset any of its permissions or
+ACLs.
+
+This process is more involved in the kernel than it is in userspace.
+The directory and file link count repair setup functions must use the regular
+VFS mechanisms to create the orphanage directory with all the necessary
+security attributes and dentry cache entries, just like a regular directory
+tree modification.
+
+Orphaned files are adopted by the orphanage as follows:
+
+1. Call ``xrep_orphanage_try_create`` at the start of the scrub setup function
+   to try to ensure that the lost and found directory actually exists.
+   This also attaches the orphanage directory to the scrub context.
+
+2. If the decision is made to reconnect a file, take the IOLOCK of both the
+   orphanage and the file being reattached.
+   The ``xrep_orphanage_iolock_two`` function follows the inode locking
+   strategy discussed earlier.
+
+3. Call ``xrep_orphanage_compute_blkres`` and ``xrep_orphanage_compute_name``
+   to compute the new name in the orphanage and the block reservation required.
+
+4. Use ``xrep_orphanage_adoption_prep`` to reserve resources to the repair
+   transaction.
+
+5. Call ``xrep_orphanage_adopt`` to reparent the orphaned file into the lost
+   and found, and update the kernel dentry cache.
+
+The proposed patches are in the
+`orphanage adoption
+<https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/log/?h=repair-orphanage>`_
+series.