design.rst 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  1. .. SPDX-License-Identifier: GPL-2.0
  2. .. _iomap_design:
  3. ..
  4. Dumb style notes to maintain the author's sanity:
  5. Please try to start sentences on separate lines so that
  6. sentence changes don't bleed colors in diff.
  7. Heading decorations are documented in sphinx.rst.
  8. ==============
  9. Library Design
  10. ==============
  11. .. contents:: Table of Contents
  12. :local:
  13. Introduction
  14. ============
  15. iomap is a filesystem library for handling common file operations.
  16. The library has two layers:
  17. 1. A lower layer that provides an iterator over ranges of file offsets.
  18. This layer tries to obtain mappings of each file ranges to storage
  19. from the filesystem, but the storage information is not necessarily
  20. required.
  21. 2. An upper layer that acts upon the space mappings provided by the
  22. lower layer iterator.
  23. The iteration can involve mappings of file's logical offset ranges to
  24. physical extents, but the storage layer information is not necessarily
  25. required, e.g. for walking cached file information.
  26. The library exports various APIs for implementing file operations such
  27. as:
  28. * Pagecache reads and writes
  29. * Folio write faults to the pagecache
  30. * Writeback of dirty folios
  31. * Direct I/O reads and writes
  32. * fsdax I/O reads, writes, loads, and stores
  33. * FIEMAP
  34. * lseek ``SEEK_DATA`` and ``SEEK_HOLE``
  35. * swapfile activation
  36. This origins of this library is the file I/O path that XFS once used; it
  37. has now been extended to cover several other operations.
  38. Who Should Read This?
  39. =====================
  40. The target audience for this document are filesystem, storage, and
  41. pagecache programmers and code reviewers.
  42. If you are working on PCI, machine architectures, or device drivers, you
  43. are most likely in the wrong place.
  44. How Is This Better?
  45. ===================
  46. Unlike the classic Linux I/O model which breaks file I/O into small
  47. units (generally memory pages or blocks) and looks up space mappings on
  48. the basis of that unit, the iomap model asks the filesystem for the
  49. largest space mappings that it can create for a given file operation and
  50. initiates operations on that basis.
  51. This strategy improves the filesystem's visibility into the size of the
  52. operation being performed, which enables it to combat fragmentation with
  53. larger space allocations when possible.
  54. Larger space mappings improve runtime performance by amortizing the cost
  55. of mapping function calls into the filesystem across a larger amount of
  56. data.
  57. At a high level, an iomap operation `looks like this
  58. <https://lore.kernel.org/all/ZGbVaewzcCysclPt@dread.disaster.area/>`_:
  59. 1. For each byte in the operation range...
  60. 1. Obtain a space mapping via ``->iomap_begin``
  61. 2. For each sub-unit of work...
  62. 1. Revalidate the mapping and go back to (1) above, if necessary.
  63. So far only the pagecache operations need to do this.
  64. 2. Do the work
  65. 3. Increment operation cursor
  66. 4. Release the mapping via ``->iomap_end``, if necessary
  67. Each iomap operation will be covered in more detail below.
  68. This library was covered previously by an `LWN article
  69. <https://lwn.net/Articles/935934/>`_ and a `KernelNewbies page
  70. <https://kernelnewbies.org/KernelProjects/iomap>`_.
  71. The goal of this document is to provide a brief discussion of the
  72. design and capabilities of iomap, followed by a more detailed catalog
  73. of the interfaces presented by iomap.
  74. If you change iomap, please update this design document.
  75. File Range Iterator
  76. ===================
  77. Definitions
  78. -----------
  79. * **buffer head**: Shattered remnants of the old buffer cache.
  80. * ``fsblock``: The block size of a file, also known as ``i_blocksize``.
  81. * ``i_rwsem``: The VFS ``struct inode`` rwsemaphore.
  82. Processes hold this in shared mode to read file state and contents.
  83. Some filesystems may allow shared mode for writes.
  84. Processes often hold this in exclusive mode to change file state and
  85. contents.
  86. * ``invalidate_lock``: The pagecache ``struct address_space``
  87. rwsemaphore that protects against folio insertion and removal for
  88. filesystems that support punching out folios below EOF.
  89. Processes wishing to insert folios must hold this lock in shared
  90. mode to prevent removal, though concurrent insertion is allowed.
  91. Processes wishing to remove folios must hold this lock in exclusive
  92. mode to prevent insertions.
  93. Concurrent removals are not allowed.
  94. * ``dax_read_lock``: The RCU read lock that dax takes to prevent a
  95. device pre-shutdown hook from returning before other threads have
  96. released resources.
  97. * **filesystem mapping lock**: This synchronization primitive is
  98. internal to the filesystem and must protect the file mapping data
  99. from updates while a mapping is being sampled.
  100. The filesystem author must determine how this coordination should
  101. happen; it does not need to be an actual lock.
  102. * **iomap internal operation lock**: This is a general term for
  103. synchronization primitives that iomap functions take while holding a
  104. mapping.
  105. A specific example would be taking the folio lock while reading or
  106. writing the pagecache.
  107. * **pure overwrite**: A write operation that does not require any
  108. metadata or zeroing operations to perform during either submission
  109. or completion.
  110. This implies that the filesystem must have already allocated space
  111. on disk as ``IOMAP_MAPPED`` and the filesystem must not place any
  112. constraints on IO alignment or size.
  113. The only constraints on I/O alignment are device level (minimum I/O
  114. size and alignment, typically sector size).
  115. ``struct iomap``
  116. ----------------
  117. The filesystem communicates to the iomap iterator the mapping of
  118. byte ranges of a file to byte ranges of a storage device with the
  119. structure below:
  120. .. code-block:: c
  121. struct iomap {
  122. u64 addr;
  123. loff_t offset;
  124. u64 length;
  125. u16 type;
  126. u16 flags;
  127. struct block_device *bdev;
  128. struct dax_device *dax_dev;
  129. void *inline_data;
  130. void *private;
  131. const struct iomap_folio_ops *folio_ops;
  132. u64 validity_cookie;
  133. };
  134. The fields are as follows:
  135. * ``offset`` and ``length`` describe the range of file offsets, in
  136. bytes, covered by this mapping.
  137. These fields must always be set by the filesystem.
  138. * ``type`` describes the type of the space mapping:
  139. * **IOMAP_HOLE**: No storage has been allocated.
  140. This type must never be returned in response to an ``IOMAP_WRITE``
  141. operation because writes must allocate and map space, and return
  142. the mapping.
  143. The ``addr`` field must be set to ``IOMAP_NULL_ADDR``.
  144. iomap does not support writing (whether via pagecache or direct
  145. I/O) to a hole.
  146. * **IOMAP_DELALLOC**: A promise to allocate space at a later time
  147. ("delayed allocation").
  148. If the filesystem returns IOMAP_F_NEW here and the write fails, the
  149. ``->iomap_end`` function must delete the reservation.
  150. The ``addr`` field must be set to ``IOMAP_NULL_ADDR``.
  151. * **IOMAP_MAPPED**: The file range maps to specific space on the
  152. storage device.
  153. The device is returned in ``bdev`` or ``dax_dev``.
  154. The device address, in bytes, is returned via ``addr``.
  155. * **IOMAP_UNWRITTEN**: The file range maps to specific space on the
  156. storage device, but the space has not yet been initialized.
  157. The device is returned in ``bdev`` or ``dax_dev``.
  158. The device address, in bytes, is returned via ``addr``.
  159. Reads from this type of mapping will return zeroes to the caller.
  160. For a write or writeback operation, the ioend should update the
  161. mapping to MAPPED.
  162. Refer to the sections about ioends for more details.
  163. * **IOMAP_INLINE**: The file range maps to the memory buffer
  164. specified by ``inline_data``.
  165. For write operation, the ``->iomap_end`` function presumably
  166. handles persisting the data.
  167. The ``addr`` field must be set to ``IOMAP_NULL_ADDR``.
  168. * ``flags`` describe the status of the space mapping.
  169. These flags should be set by the filesystem in ``->iomap_begin``:
  170. * **IOMAP_F_NEW**: The space under the mapping is newly allocated.
  171. Areas that will not be written to must be zeroed.
  172. If a write fails and the mapping is a space reservation, the
  173. reservation must be deleted.
  174. * **IOMAP_F_DIRTY**: The inode will have uncommitted metadata needed
  175. to access any data written.
  176. fdatasync is required to commit these changes to persistent
  177. storage.
  178. This needs to take into account metadata changes that *may* be made
  179. at I/O completion, such as file size updates from direct I/O.
  180. * **IOMAP_F_SHARED**: The space under the mapping is shared.
  181. Copy on write is necessary to avoid corrupting other file data.
  182. * **IOMAP_F_BUFFER_HEAD**: This mapping requires the use of buffer
  183. heads for pagecache operations.
  184. Do not add more uses of this.
  185. * **IOMAP_F_MERGED**: Multiple contiguous block mappings were
  186. coalesced into this single mapping.
  187. This is only useful for FIEMAP.
  188. * **IOMAP_F_XATTR**: The mapping is for extended attribute data, not
  189. regular file data.
  190. This is only useful for FIEMAP.
  191. * **IOMAP_F_PRIVATE**: Starting with this value, the upper bits can
  192. be set by the filesystem for its own purposes.
  193. These flags can be set by iomap itself during file operations.
  194. The filesystem should supply an ``->iomap_end`` function if it needs
  195. to observe these flags:
  196. * **IOMAP_F_SIZE_CHANGED**: The file size has changed as a result of
  197. using this mapping.
  198. * **IOMAP_F_STALE**: The mapping was found to be stale.
  199. iomap will call ``->iomap_end`` on this mapping and then
  200. ``->iomap_begin`` to obtain a new mapping.
  201. Currently, these flags are only set by pagecache operations.
  202. * ``addr`` describes the device address, in bytes.
  203. * ``bdev`` describes the block device for this mapping.
  204. This only needs to be set for mapped or unwritten operations.
  205. * ``dax_dev`` describes the DAX device for this mapping.
  206. This only needs to be set for mapped or unwritten operations, and
  207. only for a fsdax operation.
  208. * ``inline_data`` points to a memory buffer for I/O involving
  209. ``IOMAP_INLINE`` mappings.
  210. This value is ignored for all other mapping types.
  211. * ``private`` is a pointer to `filesystem-private information
  212. <https://lore.kernel.org/all/20180619164137.13720-7-hch@lst.de/>`_.
  213. This value will be passed unchanged to ``->iomap_end``.
  214. * ``folio_ops`` will be covered in the section on pagecache operations.
  215. * ``validity_cookie`` is a magic freshness value set by the filesystem
  216. that should be used to detect stale mappings.
  217. For pagecache operations this is critical for correct operation
  218. because page faults can occur, which implies that filesystem locks
  219. should not be held between ``->iomap_begin`` and ``->iomap_end``.
  220. Filesystems with completely static mappings need not set this value.
  221. Only pagecache operations revalidate mappings; see the section about
  222. ``iomap_valid`` for details.
  223. ``struct iomap_ops``
  224. --------------------
  225. Every iomap function requires the filesystem to pass an operations
  226. structure to obtain a mapping and (optionally) to release the mapping:
  227. .. code-block:: c
  228. struct iomap_ops {
  229. int (*iomap_begin)(struct inode *inode, loff_t pos, loff_t length,
  230. unsigned flags, struct iomap *iomap,
  231. struct iomap *srcmap);
  232. int (*iomap_end)(struct inode *inode, loff_t pos, loff_t length,
  233. ssize_t written, unsigned flags,
  234. struct iomap *iomap);
  235. };
  236. ``->iomap_begin``
  237. ~~~~~~~~~~~~~~~~~
  238. iomap operations call ``->iomap_begin`` to obtain one file mapping for
  239. the range of bytes specified by ``pos`` and ``length`` for the file
  240. ``inode``.
  241. This mapping should be returned through the ``iomap`` pointer.
  242. The mapping must cover at least the first byte of the supplied file
  243. range, but it does not need to cover the entire requested range.
  244. Each iomap operation describes the requested operation through the
  245. ``flags`` argument.
  246. The exact value of ``flags`` will be documented in the
  247. operation-specific sections below.
  248. These flags can, at least in principle, apply generally to iomap
  249. operations:
  250. * ``IOMAP_DIRECT`` is set when the caller wishes to issue file I/O to
  251. block storage.
  252. * ``IOMAP_DAX`` is set when the caller wishes to issue file I/O to
  253. memory-like storage.
  254. * ``IOMAP_NOWAIT`` is set when the caller wishes to perform a best
  255. effort attempt to avoid any operation that would result in blocking
  256. the submitting task.
  257. This is similar in intent to ``O_NONBLOCK`` for network APIs - it is
  258. intended for asynchronous applications to keep doing other work
  259. instead of waiting for the specific unavailable filesystem resource
  260. to become available.
  261. Filesystems implementing ``IOMAP_NOWAIT`` semantics need to use
  262. trylock algorithms.
  263. They need to be able to satisfy the entire I/O request range with a
  264. single iomap mapping.
  265. They need to avoid reading or writing metadata synchronously.
  266. They need to avoid blocking memory allocations.
  267. They need to avoid waiting on transaction reservations to allow
  268. modifications to take place.
  269. They probably should not be allocating new space.
  270. And so on.
  271. If there is any doubt in the filesystem developer's mind as to
  272. whether any specific ``IOMAP_NOWAIT`` operation may end up blocking,
  273. then they should return ``-EAGAIN`` as early as possible rather than
  274. start the operation and force the submitting task to block.
  275. ``IOMAP_NOWAIT`` is often set on behalf of ``IOCB_NOWAIT`` or
  276. ``RWF_NOWAIT``.
  277. If it is necessary to read existing file contents from a `different
  278. <https://lore.kernel.org/all/20191008071527.29304-9-hch@lst.de/>`_
  279. device or address range on a device, the filesystem should return that
  280. information via ``srcmap``.
  281. Only pagecache and fsdax operations support reading from one mapping and
  282. writing to another.
  283. ``->iomap_end``
  284. ~~~~~~~~~~~~~~~
  285. After the operation completes, the ``->iomap_end`` function, if present,
  286. is called to signal that iomap is finished with a mapping.
  287. Typically, implementations will use this function to tear down any
  288. context that were set up in ``->iomap_begin``.
  289. For example, a write might wish to commit the reservations for the bytes
  290. that were operated upon and unreserve any space that was not operated
  291. upon.
  292. ``written`` might be zero if no bytes were touched.
  293. ``flags`` will contain the same value passed to ``->iomap_begin``.
  294. iomap ops for reads are not likely to need to supply this function.
  295. Both functions should return a negative errno code on error, or zero on
  296. success.
  297. Preparing for File Operations
  298. =============================
  299. iomap only handles mapping and I/O.
  300. Filesystems must still call out to the VFS to check input parameters
  301. and file state before initiating an I/O operation.
  302. It does not handle obtaining filesystem freeze protection, updating of
  303. timestamps, stripping privileges, or access control.
  304. Locking Hierarchy
  305. =================
  306. iomap requires that filesystems supply their own locking model.
  307. There are three categories of synchronization primitives, as far as
  308. iomap is concerned:
  309. * The **upper** level primitive is provided by the filesystem to
  310. coordinate access to different iomap operations.
  311. The exact primitive is specific to the filesystem and operation,
  312. but is often a VFS inode, pagecache invalidation, or folio lock.
  313. For example, a filesystem might take ``i_rwsem`` before calling
  314. ``iomap_file_buffered_write`` and ``iomap_file_unshare`` to prevent
  315. these two file operations from clobbering each other.
  316. Pagecache writeback may lock a folio to prevent other threads from
  317. accessing the folio until writeback is underway.
  318. * The **lower** level primitive is taken by the filesystem in the
  319. ``->iomap_begin`` and ``->iomap_end`` functions to coordinate
  320. access to the file space mapping information.
  321. The fields of the iomap object should be filled out while holding
  322. this primitive.
  323. The upper level synchronization primitive, if any, remains held
  324. while acquiring the lower level synchronization primitive.
  325. For example, XFS takes ``ILOCK_EXCL`` and ext4 takes ``i_data_sem``
  326. while sampling mappings.
  327. Filesystems with immutable mapping information may not require
  328. synchronization here.
  329. * The **operation** primitive is taken by an iomap operation to
  330. coordinate access to its own internal data structures.
  331. The upper level synchronization primitive, if any, remains held
  332. while acquiring this primitive.
  333. The lower level primitive is not held while acquiring this
  334. primitive.
  335. For example, pagecache write operations will obtain a file mapping,
  336. then grab and lock a folio to copy new contents.
  337. It may also lock an internal folio state object to update metadata.
  338. The exact locking requirements are specific to the filesystem; for
  339. certain operations, some of these locks can be elided.
  340. All further mentions of locking are *recommendations*, not mandates.
  341. Each filesystem author must figure out the locking for themself.
  342. Bugs and Limitations
  343. ====================
  344. * No support for fscrypt.
  345. * No support for compression.
  346. * No support for fsverity yet.
  347. * Strong assumptions that IO should work the way it does on XFS.
  348. * Does iomap *actually* work for non-regular file data?
  349. Patches welcome!