dm vdo: add the dm-vdo deduplication and compression DM target
Subsystems (4)
Matthew Sakai
maintainerPATCH v5 1/40 dm: add documentation for dm-vdo target
In reply to Matthew SakaiThis adds the admin-guide documentation for dm-vdo.
vdo.rst is the guide to using dm-vdo. vdo-design is an overview of the design of dm-vdo.
--- .../admin-guide/device-mapper/vdo-design.rst | 415 ++++++++++++++++++ .../admin-guide/device-mapper/vdo.rst | 388 ++++++++++++++++ 2 files changed, 803 insertions(+) create mode 100644 Documentation/admin-guide/device-mapper/vdo-design.rst create mode 100644 Documentation/admin-guide/device-mapper/vdo.rst
Documentation/admin-guide/device-mapper/vdo-design.rst new file +415 -0
@@ -0,0 +1,415 @@ +.. SPDX-License-Identifier: GPL-2.0-only + +================ +Design of dm-vdo +================ + +The dm-vdo (virtual data optimizer) target provides inline deduplication, +compression, zero-block elimination, and thin provisioning. A dm-vdo target +can be backed by up to 256TB of storage, and can present a logical size of +up to 4PB. This target was originally developed at Permabit Technology +Corp. starting in 2009. It was first released in 2013 and has been used in +production environments ever since. It was made open-source in 2017 after +Permabit was acquired by Red Hat. This document describes the design of +dm-vdo. For usage, see vdo.rst in the same directory as this file. + +Because deduplication rates fall drastically as the block size increases, a +vdo target has a maximum block size of 4K. However, it can achieve +deduplication rates of 254:1, i.e. up to 254 copies of a given 4K block can +reference a single 4K of actual storage. It can achieve compression rates +of 14:1. All zero blocks consume no storage at all. + +Theory of Operation +=================== + +The design of dm-vdo is based on the idea that deduplication is a two-part +problem. The first is to recognize duplicate data. The second is to avoid +storing multiple copies of those duplicates. Therefore, dm-vdo has two main +parts: a deduplication index (called UDS) that is used to discover +duplicate data, and a data store with a reference counted block map that +maps from logical block addresses to the actual storage location of the +data. + +Zones and Threading +------------------- + +Due to the complexity of data optimization, the number of metadata +structures involved in a single write operation to a vdo target is larger +than most other targets. Furthermore, because vdo must operate on small +block sizes in order to achieve good deduplication rates, acceptable +performance can only be achieved through parallelism. Therefore, vdo's +design attempts to be lock-free. Most of a vdo's main data structures are +designed to be easily divided into "zones" such that any given bio must +only access a single zone of any zoned structure. Safety with minimal +locking is achieved by ensuring that during normal operation, each zone is +assigned to a specific thread, and only that thread will access the portion +of that data structure in that zone. Associated with each thread is a work +queue. Each bio is associated with a request object which can be added to a +work queue when the next phase of its operation requires access to the +structures in the zone associated with that queue. Although each structure +may be divided into zones, this division is not reflected in the on-disk +representation of each data structure. Therefore, the number of zones for +each structure, and hence the number of threads, is configured each time a +vdo target is started. + +The Deduplication Index +----------------------- + +In order to identify duplicate data efficiently, vdo was designed to +leverage some common characteristics of duplicate data. From empirical +observations, we gathered two key insights. The first is that in most data +sets with significant amounts of duplicate data, the duplicates tend to +have temporal locality. When a duplicate appears, it is more likely that +other duplicates will be detected, and that those duplicates will have been +written at about the same time. This is why the index keeps records in +temporal order. The second insight is that new data is more likely to +duplicate recent data than it is to duplicate older data and in general, +there are diminishing returns to looking further back in time. Therefore, +when the index is full, it should cull its oldest records to make space for +new ones. Another important idea behind the design of the index is that the +ultimate goal of deduplication is to reduce storage costs. Since there is a +trade-off between the storage saved and the resources expended to achieve +those savings, vdo does not attempt to find every last duplicate block. It +is sufficient to find and eliminate most of the redundancy. + +Each block of data is hashed to produce a 16-byte block name. An index +record consists of this block name paired with the presumed location of +that data on the underlying storage. However, it is not possible to +guarantee that the index is accurate. Most often, this occurs because it is +too costly to update the index when a block is over-written or discarded. +Doing so would require either storing the block name along with the blocks, +which is difficult to do efficiently in block-based storage, or reading and +rehashing each block before overwriting it. Inaccuracy can also result from +a hash collision where two different blocks have the same name. In +practice, this is extremely unlikely, but because vdo does not use a +cryptographic hash, a malicious workload can be constructed. Because of +these inaccuracies, vdo treats the locations in the index as hints, and +reads each indicated block to verify that it is indeed a duplicate before +sharing the existing block with a new one. + +Records are collected into groups called chapters. New records are added to +the newest chapter, called the open chapter. This chapter is stored in a +format optimized for adding and modifying records, and the content of the +open chapter is not finalized until it runs out of space for new records. +When the open chapter fills up, it is closed and a new open chapter is +created to collect new records. + +Closing a chapter converts it to a different format which is optimized for +writing. The records are written to a series of record pages based on the +order in which they were received. This means that records with temporal +locality should be on a small number of pages, reducing the I/O required to +retrieve them. The chapter also compiles an index that indicates which +record page contains any given name. This index means that a request for a +name can determine exactly which record page may contain that record, +without having to load the entire chapter from storage. This index uses +only a subset of the block name as its key, so it cannot guarantee that an +index entry refers to the desired block name. It can only guarantee that if +there is a record for this name, it will be on the indicated page. The +contents of a closed chapter are never altered in any way; these chapters +are read-only structures. + +Once enough records have been written to fill up all the available index +space, the oldest chapter gets removed to make space for new chapters. Any +time a request finds a matching record in the index, that record is copied +to the open chapter. This ensures that useful block names remain available +in the index, while unreferenced block names are forgotten. + +In order to find records in older chapters, the index also maintains a +higher level structure called the volume index, which contains entries +mapping a block name to the chapter containing its newest record. This +mapping is updated as records for the block name are copied or updated, +ensuring that only the newer record for a given block name is findable. +Older records for a block name can no longer be found even though they have +not been deleted. Like the chapter index, the volume index uses only a +subset of the block name as its key and can not definitively say that a +record exists for a name. It can only say which chapter would contain the +record if a record exists. The volume index is stored entirely in memory +and is saved to storage only when the vdo target is shut down. + +From the viewpoint of a request for a particular block name, first it will +look up the name in the volume index which will indicate either that the +record is new, or which chapter to search. If the latter, the request looks +up its name in the chapter index to determine if the record is new, or +which record page to search. Finally, if not new, the request will look for +its record on the indicated record page. This process may require up to two +page reads per request (one for the chapter index page and one for the +request page). However, recently accessed pages are cached so that these +page reads can be amortized across many block name requests. + +The volume index and the chapter indexes are implemented using a +memory-efficient structure called a delta index. Instead of storing the +entire key (the block name) for each entry, the entries are sorted by name +and only the difference between adjacent keys (the delta) is stored. +Because we expect the hashes to be evenly distributed, the size of the +deltas follows an exponential distribution. Because of this distribution, +the deltas are expressed in a Huffman code to take up even less space. The +entire sorted list of keys is called a delta list. This structure allows +the index to use many fewer bytes per entry than a traditional hash table, +but it is slightly more expensive to look up entries, because a request +must read every entry in a delta list to add up the deltas in order to find +the record it needs. The delta index reduces this lookup cost by splitting +its key space into many sub-lists, each starting at a fixed key value, so +that each individual list is short. + +The default index size can hold 64 million records, corresponding to about +256GB. This means that the index can identify duplicate data if the +original data was written within the last 256GB of writes. This range is +called the deduplication window. If new writes duplicate data that is older +than that, the index will not be able to find it because the records of the +older data have been removed. So when writing a 200 GB file to a vdo +target, and then immediately writing it again, the two copies will +deduplicate perfectly. Doing the same with a 500 GB file will result in no +deduplication, because the beginning of the file will no longer be in the +index by the time the second write begins (assuming there is no duplication +within the file itself). + +If you anticipate a data workload that will see useful deduplication beyond +the 256GB threshold, vdo can be configured to use a larger index with a +correspondingly larger deduplication window. (This configuration can only +be set when the target is created, not altered later. It is important to +consider the expected workload for a vdo target before configuring it.) +There are two ways to do this. + +One way is to increase the memory size of the index, which also increases +the amount of backing storage required. Doubling the size of the index will +double the length of the deduplication window at the expense of doubling +the storage size and the memory requirements. + +The other way is to enable sparse indexing. Sparse indexing increases the +deduplication window by a factor of 10, at the expense of also increasing +the storage size by a factor of 10. However with sparse indexing, the +memory requirements do not increase; the trade-off is slightly more +computation per request, and a slight decrease in the amount of +deduplication detected. (For workloads with significant amounts of +duplicate data, sparse indexing will detect 97-99% of the deduplication +that a standard, or "dense", index will detect.) + +The Data Store +-------------- + +The data store is implemented by three main data structures, all of which +work in concert to reduce or amortize metadata updates across as many data +writes as possible. + +*The Slab Depot* + +Most of the vdo volume belongs to the slab depot. The depot contains a +collection of slabs. The slabs can be up to 32GB, and are divided into +three sections. Most of a slab consists of a linear sequence of 4K blocks. +These blocks are used either to store data, or to hold portions of the +block map (see below). In addition to the data blocks, each slab has a set +of reference counters, using 1 byte for each data block. Finally each slab +has a journal. Reference updates are written to the slab journal, which is +written out one block at a time as each block fills. A copy of the +reference counters are kept in memory, and are written out a block at a +time, in oldest-dirtied-order whenever there is a need to reclaim slab +journal space. The journal is used both to ensure that the main recovery +journal (see below) can regularly free up space, and also to amortize the +cost of updating individual reference blocks. + +Each slab is independent of every other. They are assigned to "physical +zones" in round-robin fashion. If there are P physical zones, then slab n +is assigned to zone n mod P. + +The slab depot maintains an additional small data structure, the "slab +summary," which is used to reduce the amount of work needed to come back +online after a crash. The slab summary maintains an entry for each slab +indicating whether or not the slab has ever been used, whether it is clean +(i.e. all of its reference count updates have been persisted to storage), +and approximately how full it is. During recovery, each physical zone will +attempt to recover at least one slab, stopping whenever it has recovered a +slab which has some free blocks. Once each zone has some space (or has +determined that none is available), the target can resume normal operation +in a degraded mode. Read and write requests can be serviced, perhaps with +degraded performance, while the remainder of the dirty slabs are recovered. + +*The Block Map* + +The block map contains the logical to physical mapping. It can be thought +of as an array with one entry per logical address. Each entry is 5 bytes, +36 bits of which contain the physical block number which holds the data for +the given logical address. The other 4 bits are used to indicate the nature +of the mapping. Of the 16 possible states, one represents a logical address +which is unmapped (i.e. it has never been written, or has been discarded), +one represents an uncompressed block, and the other 14 states are used to +indicate that the mapped data is compressed, and which of the compression +slots in the compressed block this logical address maps to (see below). + +In practice, the array of mapping entries is divided into "block map +pages," each of which fits in a single 4K block. Each block map page +consists of a header, and 812 mapping entries (812 being the number that +fit). Each mapping page is actually a leaf of a radix tree which consists +of block map pages at each level. There are 60 radix trees which are +assigned to "logical zones" in round robin fashion (if there are L logical +zones, tree n will belong to zone n mod L). At each level, the trees are +interleaved, so logical addresses 0-811 belong to tree 0, logical addresses +812-1623 belong to tree 1, and so on. The interleaving is maintained all +the way up the forest. 60 was chosen as the number of trees because it is +highly composite and hence results in an evenly distributed number of trees +per zone for a large number of possible logical zone counts. The storage +for the 60 tree roots is allocated at format time. All other block map +pages are allocated out of the slabs as needed. This flexible allocation +avoids the need to pre-allocate space for the entire set of logical +mappings and also makes growing the logical size of a vdo easy to +implement. + +In operation, the block map maintains two caches. It is prohibitive to keep +the entire leaf level of the trees in memory, so each logical zone +maintains its own cache of leaf pages. The size of this cache is +configurable at target start time. The second cache is allocated at start +time, and is large enough to hold all the non-leaf pages of the entire +block map. This cache is populated as needed. + +*The Recovery Journal* + +The recovery journal is used to amortize updates across the block map and +slab depot. Each write request causes an entry to be made in the journal. +Entries are either "data remappings" or "block map remappings." For a data +remapping, the journal records the logical address affected and its old and +new physical mappings. For a block map remapping, the journal records the +block map page number and the physical block allocated for it (block map +pages are never reclaimed, so the old mapping is always 0). Each journal +entry and the data write it represents must be stable on disk before the +other metadata structures may be updated to reflect the operation. + +*Write Path* + +A write bio is first assigned a "data_vio," the request object which will +operate on behalf of the bio. (A "vio," from Vdo I/O, is vdo's wrapper for +bios; metadata operations use a vio, whereas submitted bios require the +much larger data_vio.) There is a fixed pool of 2048 data_vios. This number +was chosen both to bound the amount of work that is required to recover +from a crash, and because measurements indicate that increasing it consumes +more resources, but does not improve performance. These measurements have +been, and should continue to be, revisited over time. + +Once a data_vio is assigned, the following steps are performed: + +1. The bio's data is checked to see if it is all zeros, and copied if not. + +2. A lock is obtained on the logical address of the bio. Because + deduplication involves sharing blocks, it is vital to prevent + simultaneous modifications of the same block. + +3. The block map tree is traversed, loading any non-leaf pages which cover + the logical address and are not already in memory. If any of these + pages, or the leaf page which covers the logical address have not been + allocated, and the block is not all zeros, they are allocated at this + time. + +4. If the block is a zero block, skip to step 9. Otherwise, an attempt is + made to allocate a free data block. + +5. If an allocation was obtained, the bio is acknowledged. + +6. The bio's data is hashed. + +7. The data_vio obtains or joins a "hash lock," which represents all of + the bios currently writing the same data. + +8. If the hash lock does not already have a data_vio acting as its agent, + the current one assumes that role. As the agent: + + a) The index is queried. + + b) If an entry is found, the indicated block is read and compared + to the data being written. + + c) If the data matches, we have identified duplicate data. As many + of the data_vios as there are references available for that + block (including the agent) are shared. If there are more + data_vios in the hash lock than there are references available, + one of them becomes the new agent and continues as if there was + no duplicate found. + + d) If no duplicate was found, and the agent in the hash lock does + not have an allocation (fron step 3), another data_vio in the + hash lock will become the agent and write the data. If no + data_vio in the hash lock has an allocation, the data_vios will + be marked out of space and go to step 13 for cleanup. + + If there is an allocation, the data being written will be + compressed. If the compressed size is sufficiently small, the + data_vio will go to the packer where it may be placed in a bin + along with other data_vios. + + e) Once a bin is full, either because it is out of space, or + because all 14 of its slots are in use, it is written out. + + f) Each data_vio from the bin just written is the agent of some + hash lock, it will now proceed to treat the just written + compressed block as if it were a duplicate and share it with as + many other data_vios in its hash lock as possible. + + g) If the agent's data is not compressed, it will attempt to write + its data to the block it has allocated. + + h) If the data was written, this new block is treated as a + duplicate and shared as much as possible with any other + data_vios in the hash lock. + + i) If the agent wrote new data (whether compressed or not), the + index is updated to reflect the new entry. + +9. The block map is queried to determine the previous mapping of the + logical address. + +10. An entry is made in the recovery journal. The data_vio will block in + the journal until a flush has completed to ensure the data it may have + written is stable. It must also wait until its journal entry is stable + on disk. (Journal writes are all issued with the FUA bit set.) + +11. Once the recovery journal entry is stable, the data_vio makes two slab + journal entries: an increment entry for the new mapping, and a + decrement entry for the old mapping, if that mapping was non-zero. For + correctness during recovery, the slab journal entries in any given slab + journal must be in the same order as the corresponding recovery journal + entries. Therefore, if the two entries are in different zones, they are + made concurrently, and if they are in the same zone, the increment is + always made before the decrement in order to avoid underflow. After + each slab journal entry is made in memory, the associated reference + count is also updated in memory. Each of these updates will get written + out as needed. (Slab journal blocks are written out either when they + are full, or when the recovery journal requests they do so in order to + allow the recovery journal to free up space; reference count blocks are + written out whenever the associated slab journal requests they do so in + order to free up slab journal space.) + +12. Once all the reference count updates are done, the block map is updated + and the write is complete. + +13. If the data_vio did not use its allocation, it releases the allocated + block, the hash lock (if it has one), and its logical lock. The + data_vio then returns to the pool. + +*Read Path* + +Reads are much simpler than writes. After a data_vio is assigned to the +bio, and the logical lock is obtained, the block map is queried. If the +block is mapped, the appropriate physical block is read, and if necessary, +decompressed. + +*Recovery* + +When a vdo is restarted after a crash, it will attempt to recover from the +recovery journal. During the pre-resume phase of the next start, the +recovery journal is read. The increment portion of valid entries are played +into the block map. Next, valid entries are played, in order as required, +into the slab journals. Finally, each physical zone attempts to replay at +least one slab journal to reconstruct the reference counts of one slab. +Once each zone has some free space (or has determined that it has none), +the vdo comes back online, while the remainder of the slab journals are +used to reconstruct the rest of the reference counts. + +*Read-only Rebuild* + +If a vdo encounters an unrecoverable error, it will enter read-only mode. +This mode indicates that some previously acknowledged data may have been +lost. The vdo may be instructed to rebuild as best it can in order to +return to a writable state. However, this is never done automatically due +to the likelihood that data has been lost. During a read-only rebuild, the +block map is recovered from the recovery journal as before. However, the +reference counts are not rebuilt from the slab journals. Rather, the +reference counts are zeroed, and then the entire block map is traversed, +and the reference counts are updated from it. While this may lose some +data, it ensures that the block map and reference counts are consistent.
Documentation/admin-guide/device-mapper/vdo.rst new file +388 -0
388 lines not on this page · raw message
Signature · 1 line
2.40.0
Matthew Sakai
maintainerv5 cover dm vdo: add the dm-vdo deduplication and compression DM target
The dm-vdo target provides inline deduplication, compression, zero-block elimination, and thin provisioning. A dm-vdo target can be backed by up to 256TB of storage, and can present a logical size of up to 4PB. This target was originally developed at Permabit Technology Corp. starting in 2009. It was first released in 2013 and has been used in production environments ever since. It was made open-source in 2017 after Permabit was acquired by Red Hat.
Because deduplication rates fall drastically as the block size increases, a vdo target has a maximum block size of 4KB. However, it can achieve deduplication rates of 254:1, i.e. up to 254 copies of a given 4KB block can reference a single 4KB of actual storage. It can achieve compression rates of 14:1. All zero blocks consume no storage at all.
https://github.com/dm-vdo/dm-linux contains the most recent dm-vdo updates.
Design Summary
--------------
This is a high-level summary of the ideas behind dm-vdo. For details about the implementation and various design choices, refer to vdo-design.rst included in this patch set.
Deduplication is a two-part problem. The first part is recognizing duplicate data; the second part is avoiding multiple copies of the duplicated data. Therefore, vdo has two main sections: a deduplication index that is used to discover potential duplicate data, and a data store with a reference counted block map that maps from logical block addresses to the actual storage location of the data.
Hashing:
In order to identify blocks, vdo hashes each 4KB block to produce a 128-bit block name. Since vdo only requires these names to be evenly distributed, it uses MurmurHash3, a non-cryptographic hash algorithm which is faster than cryptographic hashes.
The Deduplication Index:
The index is a set of mappings between a block name (the hash of its contents) and a hint indicating where the block might be stored. These mappings are stored in temporal order because groups of blocks that are written together (such as a large file) tend to be rewritten together as well. The index uses a least-recently-used (LRU) scheme to keep frequently used names in the index while older names are discarded.
The index uses a structure called a delta-index to store its mappings, which is more space-efficient than using a hashtable. It uses a variable length encoding with the property that the average size of an entry decreases as the number of entries increases, resulting in a roughly constant size as the index fills.
Because storing hashes along with the data, or rehashing blocks on overwrite is expensive, entries are never explicitly deleted from the index. Instead, the vdo must always check the data at the physical location provided by the index to ensure that the hint is still valid.
The Data Store:
The data store is implemented by three main data structures: the block map, the slab depot, and the recovery journal. These structures work in concert to amortize metadata updates across as many data writes as possible.
The block map contains the mapping from logical addresses to physical locations. For each logical address it indicates whether that address is unused, all zeros, or which physical block holds its contents and whether or not it is compressed. The array of mappings is represented as a tree, with nodes that are allocated as needed from the available physical space.
The slab depot tracks the physical space available for storing user data. The depot also maintains a reference count for each physical block. Each block can have up to 254 logical references.
The recovery journal is a transaction log of the logical-to-physical mappings made by data writes. Committing this journal regularly allows a vdo to reduce the frequency of other metadata writes and allows it to reconstruct its metadata in the event of a crash.
Zones and Threading:
Due to the complexity of deduplication, the number of metadata structures involved in a single write operation to a vdo target is larger than most other targets. Furthermore, because vdo operates on small block sizes in order to achieve good deduplication rates, parallelism is key to good performance. The deduplication index, the block map, and the slab depot are all designed to be easily divided into disjoint zones such that any piece of metadata is handled by a single zone. Each zone is then assigned to a single thread so that all metadata operations in that zone can proceed without locking. Each bio is associated with a request object which can be enqueued on each zone thread it needs to access. The zone divisions are not reflected in the on-disk representation of the data structures, so the number of zones, and hence the number of threads, can be configured each time a vdo target is started.
Existing facilities
-------------------
In a few cases, we found that existing kernel facilities did not meet vdo's needs, either because of performance or due to a mismatch of semantics. These are detailed here:
Work Queues:
Handling a single bio requires a number of small operations across a number of zones. The per-zone worker threads can be very busy, often using upwards of 30% CPU time. Kernel work queues seem targeted for lighter work loads. They do not let us easily prioritize individual tasks within a zone, and make CPU affinity control at a per-thread level more difficult.
The threads scanning and updating the in-memory portion of the deduplication index process a large number of queries through a single function. It uses its own "request queue" mechanism to process these efficiently in dedicated threads. In experiments using kernel work queues for the index lookups, we observed an overall throughput drop of up to almost 10%. In the following table, randwrite% and write% represent the change in throughput when switching to kernel work queues for random and sequential write workloads, respectively.
| compression% | deduplication% | randwrite% | write% | |--------------+----------------+------------+--------| | 0 | 0 | -8.3 | -6.4 | | 55 | 0 | -7.9 | -8.5 | | 90 | 0 | -9.3 | -8.9 | | 0 | 50 | -4.9 | -4.5 | | 55 | 50 | -4.4 | -4.4 | | 90 | 50 | -4.2 | -4.7 | | 0 | 90 | -1.0 | 0.7 | | 55 | 90 | 0.2 | -0.4 | | 90 | 90 | -0.5 | 0.2 |
Mempools:
There are two types of object pools in the vdo implementation for which the existing mempool structure was not appropriate. The first of these are pools of structures wrapping the bios used for vdo's metadata I/O. Since each of these pools is only accessed from a single thread, the locking done by mempool is a needless cost. The second of these, the single pool of the wrappers for incoming bios, has more complicated locking semantics than mempool provides. When a thread attempts to submit a bio to vdo, but the pool is exhausted, the thread is put to sleep. The pool is designed to only wake that thread once, when it is certain that the bio submitted by that thread will be processed. It is not desirable to merely allocate more wrappers as a number of other vdo structures are designed to handle only a fixed number of concurrent requests. This limit is also necessary to bound the amount of work needed when recovering after a crash.
MurmurHash:
MurmurHash3 was selected for its hash quality, performance on 4KB blocks, and its 128-bit output size (vdo needs significantly more than 64 uniformly distributed bits for its in-memory and on-disk indexing). For cross-platform compatibility, vdo uses a modified version which always produces the same output as the original x64 variant, rather than being optimized per platform.
For newly created devices, vdo could potentially use another hash algorithm with similar qualities such as xxhash. For existing devices, however, changing the hash algorithm means losing all previous deduplication information. So for existing installations it is highly desirable to retain support for MurmurHash3.
Matthew Sakai (40):
dm: add documentation for dm-vdo target
dm vdo: add the MurmurHash3 fast hashing algorithm
dm vdo: add memory allocation utilities
dm vdo: add basic logging and support utilities
dm vdo: add vdo type declarations, constants, and simple data
structures
dm vdo: add thread and synchronization utilities
dm vdo: add specialized request queueing functionality
dm vdo: add basic hash map data structures
dm vdo: add deduplication configuration structures
dm vdo: add deduplication index storage interface
dm vdo: implement the delta index
dm vdo: implement the volume index
dm vdo: implement the open chapter and chapter indexes
dm vdo: implement the chapter volume store
dm vdo: implement top-level deduplication index
dm vdo: implement external deduplication index interface dm vdo: add administrative state and action manager
dm vdo: add vio, the request object for vdo metadata
dm vdo: add data_vio, the request object which services incoming bios dm vdo: add flush support
dm vdo: add the vdo io_submitter
dm vdo: add hash locks and hash zones
dm vdo: add use of deduplication index in hash zones
dm vdo: add the compressed block bin packer
dm vdo: add slab structure, slab journal and reference counters dm vdo: add the slab summary
dm vdo: add the block allocators and physical zones
dm vdo: add the slab depot
dm vdo: add the block map
dm vdo: implement the block map page cache
dm vdo: add the recovery journal
dm vdo: add repair of damaged vdo volumes
dm vdo: add the primary vdo structure
dm vdo: add the on-disk formats and marshalling of vdo structures dm vdo: add statistics reporting
dm vdo: add sysfs support for setting parameters and fetching stats dm vdo: add debugging support
dm vdo: add the top-level DM target
dm vdo: enable configuration and building of dm-vdo
dm vdo: add MAINTAINERS file entry
.../admin-guide/device-mapper/vdo-design.rst | 415 ++ .../admin-guide/device-mapper/vdo.rst | 388 ++ MAINTAINERS | 9 + drivers/md/Kconfig | 16 + drivers/md/Makefile | 2 + drivers/md/dm-vdo-target.c | 2952 ++++++++++ drivers/md/dm-vdo/action-manager.c | 388 ++ drivers/md/dm-vdo/action-manager.h | 110 + drivers/md/dm-vdo/admin-state.c | 506 ++ drivers/md/dm-vdo/admin-state.h | 178 + drivers/md/dm-vdo/block-map.c | 3323 +++++++++++ drivers/md/dm-vdo/block-map.h | 379 ++ drivers/md/dm-vdo/chapter-index.c | 291 + drivers/md/dm-vdo/chapter-index.h | 63 + drivers/md/dm-vdo/completion.c | 140 + drivers/md/dm-vdo/completion.h | 152 + drivers/md/dm-vdo/config.c | 378 ++ drivers/md/dm-vdo/config.h | 124 + drivers/md/dm-vdo/constants.c | 15 + drivers/md/dm-vdo/constants.h | 102 + drivers/md/dm-vdo/cpu.h | 59 + drivers/md/dm-vdo/data-vio.c | 2057 +++++++ drivers/md/dm-vdo/data-vio.h | 669 +++ drivers/md/dm-vdo/dedupe.c | 3068 ++++++++++ drivers/md/dm-vdo/dedupe.h | 120 + drivers/md/dm-vdo/delta-index.c | 1990 +++++++ drivers/md/dm-vdo/delta-index.h | 278 + drivers/md/dm-vdo/dump.c | 278 + drivers/md/dm-vdo/dump.h | 17 + drivers/md/dm-vdo/encodings.c | 1481 +++++ drivers/md/dm-vdo/encodings.h | 1299 +++++ drivers/md/dm-vdo/errors.c | 312 + drivers/md/dm-vdo/errors.h | 81 + drivers/md/dm-vdo/flush.c | 558 ++ drivers/md/dm-vdo/flush.h | 44 + drivers/md/dm-vdo/funnel-queue.c | 171 + drivers/md/dm-vdo/funnel-queue.h | 110 + drivers/md/dm-vdo/funnel-requestqueue.c | 283 + drivers/md/dm-vdo/funnel-requestqueue.h | 31 + drivers/md/dm-vdo/funnel-workqueue.c | 638 +++ drivers/md/dm-vdo/funnel-workqueue.h | 51 + drivers/md/dm-vdo/geometry.c | 201 + drivers/md/dm-vdo/geometry.h | 138 + drivers/md/dm-vdo/hash-utils.h | 65 + drivers/md/dm-vdo/index-layout.c | 1768 ++++++ drivers/md/dm-vdo/index-layout.h | 43 + drivers/md/dm-vdo/index-page-map.c | 175 + drivers/md/dm-vdo/index-page-map.h | 50 + drivers/md/dm-vdo/index-session.c | 756 +++ drivers/md/dm-vdo/index-session.h | 84 + drivers/md/dm-vdo/index.c | 1400 +++++ drivers/md/dm-vdo/index.h | 83 + drivers/md/dm-vdo/int-map.c | 718 +++ drivers/md/dm-vdo/int-map.h | 40 + drivers/md/dm-vdo/io-factory.c | 415 ++ drivers/md/dm-vdo/io-factory.h | 64 + drivers/md/dm-vdo/io-submitter.c | 480 ++ drivers/md/dm-vdo/io-submitter.h | 47 + drivers/md/dm-vdo/logger.c | 291 + drivers/md/dm-vdo/logger.h | 105 + drivers/md/dm-vdo/logical-zone.c | 375 ++ drivers/md/dm-vdo/logical-zone.h | 89 + drivers/md/dm-vdo/memory-alloc.c | 442 ++ drivers/md/dm-vdo/memory-alloc.h | 162 + drivers/md/dm-vdo/message-stats.c | 1215 ++++ drivers/md/dm-vdo/message-stats.h | 13 + drivers/md/dm-vdo/murmurhash3.c | 175 + drivers/md/dm-vdo/murmurhash3.h | 15 + drivers/md/dm-vdo/numeric.h | 78 + drivers/md/dm-vdo/open-chapter.c | 427 ++ drivers/md/dm-vdo/open-chapter.h | 79 + drivers/md/dm-vdo/packer.c | 784 +++ drivers/md/dm-vdo/packer.h | 122 + drivers/md/dm-vdo/permassert.c | 26 + drivers/md/dm-vdo/permassert.h | 46 + drivers/md/dm-vdo/physical-zone.c | 646 +++ drivers/md/dm-vdo/physical-zone.h | 115 + drivers/md/dm-vdo/pointer-map.c | 696 +++ drivers/md/dm-vdo/pointer-map.h | 81 + drivers/md/dm-vdo/pool-sysfs-stats.c | 2063 +++++++ drivers/md/dm-vdo/pool-sysfs.c | 198 + drivers/md/dm-vdo/pool-sysfs.h | 19 + drivers/md/dm-vdo/priority-table.c | 226 + drivers/md/dm-vdo/priority-table.h | 47 + drivers/md/dm-vdo/radix-sort.c | 332 ++ drivers/md/dm-vdo/radix-sort.h | 26 + drivers/md/dm-vdo/recovery-journal.c | 1761 ++++++ drivers/md/dm-vdo/recovery-journal.h | 312 + drivers/md/dm-vdo/repair.c | 1757 ++++++ drivers/md/dm-vdo/repair.h | 14 + drivers/md/dm-vdo/slab-depot.c | 5095 +++++++++++++++++ drivers/md/dm-vdo/slab-depot.h | 595 ++ drivers/md/dm-vdo/sparse-cache.c | 580 ++ drivers/md/dm-vdo/sparse-cache.h | 46 + drivers/md/dm-vdo/statistics.h | 278 + drivers/md/dm-vdo/status-codes.c | 123 + drivers/md/dm-vdo/status-codes.h | 112 + drivers/md/dm-vdo/string-utils.c | 28 + drivers/md/dm-vdo/string-utils.h | 23 + drivers/md/dm-vdo/sysfs.c | 82 + drivers/md/dm-vdo/thread-cond-var.c | 46 + drivers/md/dm-vdo/thread-device.c | 36 + drivers/md/dm-vdo/thread-device.h | 20 + drivers/md/dm-vdo/thread-registry.c | 92 + drivers/md/dm-vdo/thread-registry.h | 32 + drivers/md/dm-vdo/time-utils.h | 28 + drivers/md/dm-vdo/types.h | 393 ++ drivers/md/dm-vdo/uds-sysfs.c | 186 + drivers/md/dm-vdo/uds-sysfs.h | 12 + drivers/md/dm-vdo/uds-threads.c | 183 + drivers/md/dm-vdo/uds-threads.h | 115 + drivers/md/dm-vdo/uds.h | 329 ++ drivers/md/dm-vdo/vdo.c | 1784 ++++++ drivers/md/dm-vdo/vdo.h | 376 ++ drivers/md/dm-vdo/vio.c | 501 ++ drivers/md/dm-vdo/vio.h | 199 + drivers/md/dm-vdo/volume-index.c | 1290 +++++ drivers/md/dm-vdo/volume-index.h | 192 + drivers/md/dm-vdo/volume.c | 1711 ++++++ drivers/md/dm-vdo/volume.h | 171 + drivers/md/dm-vdo/wait-queue.c | 225 + drivers/md/dm-vdo/wait-queue.h | 131 + 122 files changed, 57804 insertions(+) create mode 100644 Documentation/admin-guide/device-mapper/vdo-design.rst create mode 100644 Documentation/admin-guide/device-mapper/vdo.rst create mode 100644 drivers/md/dm-vdo-target.c create mode 100644 drivers/md/dm-vdo/action-manager.c create mode 100644 drivers/md/dm-vdo/action-manager.h create mode 100644 drivers/md/dm-vdo/admin-state.c create mode 100644 drivers/md/dm-vdo/admin-state.h create mode 100644 drivers/md/dm-vdo/block-map.c create mode 100644 drivers/md/dm-vdo/block-map.h create mode 100644 drivers/md/dm-vdo/chapter-index.c create mode 100644 drivers/md/dm-vdo/chapter-index.h create mode 100644 drivers/md/dm-vdo/completion.c create mode 100644 drivers/md/dm-vdo/completion.h create mode 100644 drivers/md/dm-vdo/config.c create mode 100644 drivers/md/dm-vdo/config.h create mode 100644 drivers/md/dm-vdo/constants.c create mode 100644 drivers/md/dm-vdo/constants.h create mode 100644 drivers/md/dm-vdo/cpu.h create mode 100644 drivers/md/dm-vdo/data-vio.c create mode 100644 drivers/md/dm-vdo/data-vio.h create mode 100644 drivers/md/dm-vdo/dedupe.c create mode 100644 drivers/md/dm-vdo/dedupe.h create mode 100644 drivers/md/dm-vdo/delta-index.c create mode 100644 drivers/md/dm-vdo/delta-index.h create mode 100644 drivers/md/dm-vdo/dump.c create mode 100644 drivers/md/dm-vdo/dump.h create mode 100644 drivers/md/dm-vdo/encodings.c create mode 100644 drivers/md/dm-vdo/encodings.h create mode 100644 drivers/md/dm-vdo/errors.c create mode 100644 drivers/md/dm-vdo/errors.h create mode 100644 drivers/md/dm-vdo/flush.c create mode 100644 drivers/md/dm-vdo/flush.h create mode 100644 drivers/md/dm-vdo/funnel-queue.c create mode 100644 drivers/md/dm-vdo/funnel-queue.h create mode 100644 drivers/md/dm-vdo/funnel-requestqueue.c create mode 100644 drivers/md/dm-vdo/funnel-requestqueue.h create mode 100644 drivers/md/dm-vdo/funnel-workqueue.c create mode 100644 drivers/md/dm-vdo/funnel-workqueue.h create mode 100644 drivers/md/dm-vdo/geometry.c create mode 100644 drivers/md/dm-vdo/geometry.h create mode 100644 drivers/md/dm-vdo/hash-utils.h create mode 100644 drivers/md/dm-vdo/index-layout.c create mode 100644 drivers/md/dm-vdo/index-layout.h create mode 100644 drivers/md/dm-vdo/index-page-map.c create mode 100644 drivers/md/dm-vdo/index-page-map.h create mode 100644 drivers/md/dm-vdo/index-session.c create mode 100644 drivers/md/dm-vdo/index-session.h create mode 100644 drivers/md/dm-vdo/index.c create mode 100644 drivers/md/dm-vdo/index.h create mode 100644 drivers/md/dm-vdo/int-map.c create mode 100644 drivers/md/dm-vdo/int-map.h create mode 100644 drivers/md/dm-vdo/io-factory.c create mode 100644 drivers/md/dm-vdo/io-factory.h create mode 100644 drivers/md/dm-vdo/io-submitter.c create mode 100644 drivers/md/dm-vdo/io-submitter.h create mode 100644 drivers/md/dm-vdo/logger.c create mode 100644 drivers/md/dm-vdo/logger.h create mode 100644 drivers/md/dm-vdo/logical-zone.c create mode 100644 drivers/md/dm-vdo/logical-zone.h create mode 100644 drivers/md/dm-vdo/memory-alloc.c create mode 100644 drivers/md/dm-vdo/memory-alloc.h create mode 100644 drivers/md/dm-vdo/message-stats.c create mode 100644 drivers/md/dm-vdo/message-stats.h create mode 100644 drivers/md/dm-vdo/murmurhash3.c create mode 100644 drivers/md/dm-vdo/murmurhash3.h create mode 100644 drivers/md/dm-vdo/numeric.h create mode 100644 drivers/md/dm-vdo/open-chapter.c create mode 100644 drivers/md/dm-vdo/open-chapter.h create mode 100644 drivers/md/dm-vdo/packer.c create mode 100644 drivers/md/dm-vdo/packer.h create mode 100644 drivers/md/dm-vdo/permassert.c create mode 100644 drivers/md/dm-vdo/permassert.h create mode 100644 drivers/md/dm-vdo/physical-zone.c create mode 100644 drivers/md/dm-vdo/physical-zone.h create mode 100644 drivers/md/dm-vdo/pointer-map.c create mode 100644 drivers/md/dm-vdo/pointer-map.h create mode 100644 drivers/md/dm-vdo/pool-sysfs-stats.c create mode 100644 drivers/md/dm-vdo/pool-sysfs.c create mode 100644 drivers/md/dm-vdo/pool-sysfs.h create mode 100644 drivers/md/dm-vdo/priority-table.c create mode 100644 drivers/md/dm-vdo/priority-table.h create mode 100644 drivers/md/dm-vdo/radix-sort.c create mode 100644 drivers/md/dm-vdo/radix-sort.h create mode 100644 drivers/md/dm-vdo/recovery-journal.c create mode 100644 drivers/md/dm-vdo/recovery-journal.h create mode 100644 drivers/md/dm-vdo/repair.c create mode 100644 drivers/md/dm-vdo/repair.h create mode 100644 drivers/md/dm-vdo/slab-depot.c create mode 100644 drivers/md/dm-vdo/slab-depot.h create mode 100644 drivers/md/dm-vdo/sparse-cache.c create mode 100644 drivers/md/dm-vdo/sparse-cache.h create mode 100644 drivers/md/dm-vdo/statistics.h create mode 100644 drivers/md/dm-vdo/status-codes.c create mode 100644 drivers/md/dm-vdo/status-codes.h create mode 100644 drivers/md/dm-vdo/string-utils.c create mode 100644 drivers/md/dm-vdo/string-utils.h create mode 100644 drivers/md/dm-vdo/sysfs.c create mode 100644 drivers/md/dm-vdo/thread-cond-var.c create mode 100644 drivers/md/dm-vdo/thread-device.c create mode 100644 drivers/md/dm-vdo/thread-device.h create mode 100644 drivers/md/dm-vdo/thread-registry.c create mode 100644 drivers/md/dm-vdo/thread-registry.h create mode 100644 drivers/md/dm-vdo/time-utils.h create mode 100644 drivers/md/dm-vdo/types.h create mode 100644 drivers/md/dm-vdo/uds-sysfs.c create mode 100644 drivers/md/dm-vdo/uds-sysfs.h create mode 100644 drivers/md/dm-vdo/uds-threads.c create mode 100644 drivers/md/dm-vdo/uds-threads.h create mode 100644 drivers/md/dm-vdo/uds.h create mode 100644 drivers/md/dm-vdo/vdo.c create mode 100644 drivers/md/dm-vdo/vdo.h create mode 100644 drivers/md/dm-vdo/vio.c create mode 100644 drivers/md/dm-vdo/vio.h create mode 100644 drivers/md/dm-vdo/volume-index.c create mode 100644 drivers/md/dm-vdo/volume-index.h create mode 100644 drivers/md/dm-vdo/volume.c create mode 100644 drivers/md/dm-vdo/volume.h create mode 100644 drivers/md/dm-vdo/wait-queue.c create mode 100644 drivers/md/dm-vdo/wait-queue.h
Signature · 1 line
2.40.0
Matthew Sakai
maintainerPATCH v5 4/40 dm vdo: add basic logging and support utilities
Add various support utilities for the vdo target and deduplication index, including logging utilities, string and time management, and index-specific error codes.
--- drivers/md/dm-vdo/errors.c | 312 +++++++++++++++++++++++++++++++ drivers/md/dm-vdo/errors.h | 81 ++++++++ drivers/md/dm-vdo/logger.c | 291 ++++++++++++++++++++++++++++ drivers/md/dm-vdo/logger.h | 105 +++++++++++ drivers/md/dm-vdo/permassert.c | 26 +++ drivers/md/dm-vdo/permassert.h | 46 +++++ drivers/md/dm-vdo/string-utils.c | 28 +++ drivers/md/dm-vdo/string-utils.h | 23 +++ drivers/md/dm-vdo/time-utils.h | 28 +++ 9 files changed, 940 insertions(+) create mode 100644 drivers/md/dm-vdo/errors.c create mode 100644 drivers/md/dm-vdo/errors.h create mode 100644 drivers/md/dm-vdo/logger.c create mode 100644 drivers/md/dm-vdo/logger.h create mode 100644 drivers/md/dm-vdo/permassert.c create mode 100644 drivers/md/dm-vdo/permassert.h create mode 100644 drivers/md/dm-vdo/string-utils.c create mode 100644 drivers/md/dm-vdo/string-utils.h create mode 100644 drivers/md/dm-vdo/time-utils.h
drivers/md/dm-vdo/errors.c new file +312 -0
@@ -0,0 +1,312 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* +* Copyright 2023 Red Hat +*/ + +#include "errors.h" + +#include <linux/compiler.h> +#include <linux/errno.h> + +#include "logger.h" +#include "permassert.h" +#include "string-utils.h" + +static const struct error_info successful = {"UDS_SUCCESS" ,"Success" }; + +static const char *const message_table[] = { + [EPERM ] ="Operation not permitted" , + [ENOENT ] ="No such file or directory" , + [ESRCH ] ="No such process" , + [EINTR ] ="Interrupted system call" , + [EIO ] ="Input/output error" , + [ENXIO ] ="No such device or address" , + [E2BIG ] ="Argument list too long" , + [ENOEXEC ] ="Exec format error" , + [EBADF ] ="Bad file descriptor" , + [ECHILD ] ="No child processes" , + [EAGAIN ] ="Resource temporarily unavailable" , + [ENOMEM ] ="Cannot allocate memory" , + [EACCES ] ="Permission denied" , + [EFAULT ] ="Bad address" , + [ENOTBLK ] ="Block device required" , + [EBUSY ] ="Device or resource busy" , + [EEXIST ] ="File exists" , + [EXDEV ] ="Invalid cross-device link" , + [ENODEV ] ="No such device" , + [ENOTDIR ] ="Not a directory" , + [EISDIR ] ="Is a directory" , + [EINVAL ] ="Invalid argument" , + [ENFILE ] ="Too many open files in system" , + [EMFILE ] ="Too many open files" , + [ENOTTY ] ="Inappropriate ioctl for device" , + [ETXTBSY ] ="Text file busy" , + [EFBIG ] ="File too large" , + [ENOSPC ] ="No space left on device" , + [ESPIPE ] ="Illegal seek" , + [EROFS ] ="Read-only file system" , + [EMLINK ] ="Too many links" , + [EPIPE ] ="Broken pipe" , + [EDOM ] ="Numerical argument out of domain" , + [ERANGE ] ="Numerical result out of range" +}; + +static const struct error_info error_list[] = { + {"UDS_OVERFLOW" ,"Index overflow" }, + {"UDS_INVALID_ARGUMENT" ,"Invalid argument passed to internal routine" }, + {"UDS_BAD_STATE" ,"UDS data structures are in an invalid state" }, + {"UDS_DUPLICATE_NAME" ,"Attempt to enter the same name into a delta index twice" }, + {"UDS_ASSERTION_FAILED" ,"Assertion failed" }, + {"UDS_QUEUED" ,"Request queued" }, + {"UDS_BUFFER_ERROR" ,"Buffer error" }, + {"UDS_NO_DIRECTORY" ,"Expected directory is missing" }, + {"UDS_ALREADY_REGISTERED" ,"Error range already registered" }, + {"UDS_OUT_OF_RANGE" ,"Cannot access data outside specified limits" }, + {"UDS_EMODULE_LOAD" ,"Could not load modules" }, + {"UDS_DISABLED" ,"UDS library context is disabled" }, + {"UDS_UNKNOWN_ERROR" ,"Unknown error" }, + {"UDS_UNSUPPORTED_VERSION" ,"Unsupported version" }, + {"UDS_CORRUPT_DATA" ,"Some index structure is corrupt" }, + {"UDS_NO_INDEX" ,"No index found" }, + {"UDS_INDEX_NOT_SAVED_CLEANLY" ,"Index not saved cleanly" }, +}; + +struct error_block { +const char *name; +int base; +int last; +int max; +const struct error_info *infos; +}; + +enum { +MAX_ERROR_BLOCKS =6 , +}; + +static struct { +int allocated; +int count; +struct error_block blocks[MAX_ERROR_BLOCKS ]; +} registered_errors = { + .allocated =MAX_ERROR_BLOCKS , + .count =1 , + .blocks = { { + .name ="UDS Error" , + .base =UDS_ERROR_CODE_BASE , + .last =UDS_ERROR_CODE_LAST , + .max =UDS_ERROR_CODE_BLOCK_END , + .infos = error_list, + } }, +}; + +/* Get the error info for an error number. Also returns the name of the error block, if known. */ +static const char *get_error_info (int errnum,const struct error_info **info_ptr) +{ +struct error_block *block; + +if (errnum ==UDS_SUCCESS ) { + *info_ptr = &successful; +return NULL ; + } + +for (block = registered_errors.blocks; + block < registered_errors.blocks + registered_errors.count; + block++) { +if ((errnum >= block->base) && (errnum < block->last)) { + *info_ptr = block->infos + (errnum - block->base); +return block->name; + }else if ((errnum >= block->last) && (errnum < block->max)) { + *info_ptr =NULL ; +return block->name; + } + } + +return NULL ; +} + +/* Return a string describing a system error message. */ +static const char *system_string_error (int errnum,char *buf,size_t buflen) +{ +size_t len; +const char *error_string =NULL ; + +if ((errnum >0 ) && (errnum <ARRAY_SIZE (message_table))) + error_string = message_table[errnum]; + + len = ((error_string ==NULL ) ? +snprintf (buf, buflen,"Unknown error %d" , errnum) : +snprintf (buf, buflen,"%s" , error_string)); +if (len < buflen) +return buf; + + buf[0 ] ='\0' ; +return "System error" ; +} + +/* Convert an error code to a descriptive string. */ +const char *uds_string_error (int errnum,char *buf,size_t buflen) +{ +char *buffer = buf; +char *buf_end = buf + buflen; +const struct error_info *info =NULL ; +const char *block_name; + +if (buf ==NULL ) +return NULL ; + +if (errnum <0 ) + errnum = -errnum; + + block_name =get_error_info (errnum, &info); +if (block_name !=NULL ) { +if (info !=NULL ) { + buffer =uds_append_to_buffer (buffer, buf_end,"%s: %s" , + block_name, info->message); + }else { + buffer =uds_append_to_buffer (buffer, buf_end,"Unknown %s %d" , + block_name, errnum); + } + }else if (info !=NULL ) { + buffer =uds_append_to_buffer (buffer, buf_end,"%s" , info->message); + }else { +const char *tmp =system_string_error (errnum, buffer, buf_end - buffer); + +if (tmp != buffer) + buffer =uds_append_to_buffer (buffer, buf_end,"%s" , tmp); +else + buffer +=strlen (tmp); + } + +return buf; +} + +/* Convert an error code to its name. */ +const char *uds_string_error_name (int errnum,char *buf,size_t buflen) +{ +char *buffer = buf; +char *buf_end = buf + buflen; +const struct error_info *info =NULL ; +const char *block_name; + +if (errnum <0 ) + errnum = -errnum; + + block_name =get_error_info (errnum, &info); +if (block_name !=NULL ) { +if (info !=NULL ) { + buffer =uds_append_to_buffer (buffer, buf_end,"%s" , info->name); + }else { + buffer =uds_append_to_buffer (buffer, buf_end,"%s %d" , + block_name, errnum); + } + }else if (info !=NULL ) { + buffer =uds_append_to_buffer (buffer, buf_end,"%s" , info->name); + }else { +const char *tmp; + + tmp =system_string_error (errnum, buffer, buf_end - buffer); +if (tmp != buffer) + buffer =uds_append_to_buffer (buffer, buf_end,"%s" , tmp); +else + buffer +=strlen (tmp); + } + +return buf; +} + +/* +* Translate an error code into a value acceptable to the kernel. The input error code may be a +* system-generated value (such as -EIO), or an internal UDS status code. The result will be a +* negative errno value. +*/ +int uds_map_to_system_error (int error) +{ +char error_name[UDS_MAX_ERROR_NAME_SIZE ]; +char error_message[UDS_MAX_ERROR_MESSAGE_SIZE ]; + +/* 0 is success, and negative values are already system error codes. */ +if (likely (error <=0 )) +return error; + +if (error <1024 ) { +/* This is probably an errno from userspace. */ +return -error; + } + +/* Internal UDS errors */ +switch (error) { +case UDS_NO_INDEX : +case UDS_CORRUPT_DATA : +/* The index doesn't exist or can't be recovered. */ +return -ENOENT ; + +case UDS_INDEX_NOT_SAVED_CLEANLY : +case UDS_UNSUPPORTED_VERSION : +/* +* The index exists, but can't be loaded. Tell the client it exists so they don't +* destroy it inadvertently. +*/ +return -EEXIST ; + +case UDS_DISABLED : +/* The session is unusable; only returned by requests. */ +return -EIO ; + +default : +/* Translate an unexpected error into something generic. */ +uds_log_info ("%s: mapping status code %d (%s: %s) to -EIO" , + __func__, error, +uds_string_error_name (error, error_name, +sizeof (error_name)), +uds_string_error (error, error_message, +sizeof (error_message))); +return -EIO ; + } +} + +/* +* Register a block of error codes. +* +* @block_name: the name of the block of error codes +* @first_error: the first error code in the block +* @next_free_error: one past the highest possible error in the block +* @infos: a pointer to the error info array for the block +* @info_size: the size of the error info array +*/ +int uds_register_error_block (const char *block_name,int first_error, +int next_free_error,const struct error_info *infos, +size_t info_size) +{ +int result; +struct error_block *block; +struct error_block new_block = { + .name = block_name, + .base = first_error, + .last = first_error + (info_size /sizeof (struct error_info )), + .max = next_free_error, + .infos = infos, + }; + + result =ASSERT (first_error < next_free_error,"well-defined error block range" ); +if (result !=UDS_SUCCESS ) +return result; + +if (registered_errors.count == registered_errors.allocated) { +/* This should never happen. */ +return UDS_OVERFLOW ; + } + +for (block = registered_errors.blocks; + block < registered_errors.blocks + registered_errors.count; + block++) { +if (strcmp (block_name, block->name) ==0 ) +return UDS_DUPLICATE_NAME ; + +/* Ensure error ranges do not overlap. */ +if ((first_error < block->max) && (next_free_error > block->base)) +return UDS_ALREADY_REGISTERED ; + } + + registered_errors.blocks[registered_errors.count++] = new_block; +return UDS_SUCCESS ; +}
drivers/md/dm-vdo/errors.h new file +81 -0
81 lines not on this page · raw message
drivers/md/dm-vdo/logger.c new file +291 -0
291 lines not on this page · raw message
drivers/md/dm-vdo/logger.h new file +105 -0
105 lines not on this page · raw message
drivers/md/dm-vdo/permassert.c new file +26 -0
@@ -0,0 +1,26 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* +* Copyright 2023 Red Hat +*/ + +#include "permassert.h" + +#include "errors.h" +#include "logger.h" + +int uds_assertion_failed (const char *expression_string,const char *file_name, +int line_number,const char *format, ...) +{ +va_list args; + +va_start (args, format); + +uds_log_embedded_message (UDS_LOG_ERR ,UDS_LOGGING_MODULE_NAME ,"assertion \"" , + format, args,"\" (%s) failed at %s:%d" , + expression_string, file_name, line_number); +uds_log_backtrace (UDS_LOG_ERR ); + +va_end (args); + +return UDS_ASSERTION_FAILED ; +}
drivers/md/dm-vdo/permassert.h new file +46 -0
46 lines not on this page · raw message
drivers/md/dm-vdo/string-utils.c new file +28 -0
@@ -0,0 +1,28 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* +* Copyright 2023 Red Hat +*/ + +#include "string-utils.h" + +#include "errors.h" +#include "logger.h" +#include "memory-alloc.h" +#include "permassert.h" +#include "uds.h" + +char *uds_append_to_buffer (char *buffer,char *buf_end,const char *fmt, ...) +{ +va_list args; +size_t n; + +va_start (args, fmt); + n =vsnprintf (buffer, buf_end - buffer, fmt, args); +if (n >= (size_t ) (buf_end - buffer)) + buffer = buf_end; +else + buffer += n; +va_end (args); + +return buffer; +}
drivers/md/dm-vdo/string-utils.h new file +23 -0
@@ -0,0 +1,23 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +/* +* Copyright 2023 Red Hat +*/ + +#ifndef UDS_STRING_UTILS_H +#define UDS_STRING_UTILS_H + +#include <linux/kernel.h> +#include <linux/string.h> + +/* Utilities related to string manipulation */ + +static inline const char *uds_bool_to_string (bool value) +{ +return value ?"true" :"false" ; +} + +/* Append a formatted string to the end of a buffer. */ +char *uds_append_to_buffer (char *buffer,char *buf_end,const char *fmt, ...) +__printf (3 ,4 ); + +#endif /* UDS_STRING_UTILS_H */
drivers/md/dm-vdo/time-utils.h new file +28 -0
@@ -0,0 +1,28 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +/* +* Copyright 2023 Red Hat +*/ + +#ifndef UDS_TIME_UTILS_H +#define UDS_TIME_UTILS_H + +#include <linux/ktime.h> +#include <linux/time.h> +#include <linux/types.h> + +static inline s64 ktime_to_seconds (ktime_t reltime) +{ +return reltime /NSEC_PER_SEC ; +} + +static inline ktime_t current_time_ns (clockid_t clock) +{ +return clock ==CLOCK_MONOTONIC ?ktime_get_ns () :ktime_get_real_ns (); +} + +static inline ktime_t current_time_us (void ) +{ +return current_time_ns (CLOCK_REALTIME ) /NSEC_PER_USEC ; +} + +#endif /* UDS_TIME_UTILS_H */
Signature · 1 line
2.40.0
Matthew Sakai
maintainerPATCH v5 6/40 dm vdo: add thread and synchronization utilities
In reply to Matthew SakaiThis patch adds utilities for managing and using named threads, as well as several locking and synchronization utilities. These utilities help dm-vdo minimize thread transitions and manage interactions between threads.
--- drivers/md/dm-vdo/thread-cond-var.c | 46 +++++++ drivers/md/dm-vdo/thread-device.c | 36 ++++++ drivers/md/dm-vdo/thread-device.h | 20 +++ drivers/md/dm-vdo/thread-registry.c | 92 ++++++++++++++ drivers/md/dm-vdo/thread-registry.h | 32 +++++ drivers/md/dm-vdo/uds-threads.c | 183 ++++++++++++++++++++++++++++ drivers/md/dm-vdo/uds-threads.h | 115 +++++++++++++++++ 7 files changed, 524 insertions(+) create mode 100644 drivers/md/dm-vdo/thread-cond-var.c create mode 100644 drivers/md/dm-vdo/thread-device.c create mode 100644 drivers/md/dm-vdo/thread-device.h create mode 100644 drivers/md/dm-vdo/thread-registry.c create mode 100644 drivers/md/dm-vdo/thread-registry.h create mode 100644 drivers/md/dm-vdo/uds-threads.c create mode 100644 drivers/md/dm-vdo/uds-threads.h
drivers/md/dm-vdo/thread-cond-var.c new file +46 -0
@@ -0,0 +1,46 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* +* Copyright 2023 Red Hat +*/ + +#include <linux/jiffies.h> +#include <linux/minmax.h> + +#include "errors.h" +#include "time-utils.h" +#include "uds-threads.h" + +int uds_init_cond (struct cond_var *cv) +{ +init_waitqueue_head (&cv->wait_queue); +return UDS_SUCCESS ; +} + +int uds_signal_cond (struct cond_var *cv) +{ +wake_up (&cv->wait_queue); +return UDS_SUCCESS ; +} + +int uds_broadcast_cond (struct cond_var *cv) +{ +wake_up_all (&cv->wait_queue); +return UDS_SUCCESS ; +} + +int uds_wait_cond (struct cond_var *cv,struct mutex *mutex) +{ +DEFINE_WAIT (__wait); + +prepare_to_wait (&cv->wait_queue, &__wait,TASK_IDLE ); +uds_unlock_mutex (mutex); +schedule (); +finish_wait (&cv->wait_queue, &__wait); +uds_lock_mutex (mutex); +return UDS_SUCCESS ; +} + +int uds_destroy_cond (struct cond_var *cv) +{ +return UDS_SUCCESS ; +}
drivers/md/dm-vdo/thread-device.c new file +36 -0
@@ -0,0 +1,36 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* +* Copyright 2023 Red Hat +*/ + +#include "thread-device.h" + +#include "thread-registry.h" + +/* A registry of threads associated with device id numbers. */ +static struct thread_registry device_id_thread_registry; + +/* Any registered thread must be unregistered. */ +void uds_register_thread_device_id (struct registered_thread *new_thread, +unsigned int *id_ptr) +{ +uds_register_thread (&device_id_thread_registry, new_thread, id_ptr); +} + +void uds_unregister_thread_device_id (void ) +{ +uds_unregister_thread (&device_id_thread_registry); +} + +int uds_get_thread_device_id (void ) +{ +const unsigned int *pointer; + + pointer =uds_lookup_thread (&device_id_thread_registry); +return (pointer !=NULL ) ? *pointer :-1 ; +} + +void uds_initialize_thread_device_registry (void ) +{ +uds_initialize_thread_registry (&device_id_thread_registry); +}
drivers/md/dm-vdo/thread-device.h new file +20 -0
@@ -0,0 +1,20 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +/* +* Copyright 2023 Red Hat +*/ + +#ifndef UDS_THREAD_DEVICE_H +#define UDS_THREAD_DEVICE_H + +#include "thread-registry.h" + +void uds_register_thread_device_id (struct registered_thread *new_thread, +unsigned int *id_ptr); + +void uds_unregister_thread_device_id (void ); + +int uds_get_thread_device_id (void ); + +void uds_initialize_thread_device_registry (void ); + +#endif /* UDS_THREAD_DEVICE_H */
drivers/md/dm-vdo/thread-registry.c new file +92 -0
92 lines not on this page · raw message
drivers/md/dm-vdo/thread-registry.h new file +32 -0
@@ -0,0 +1,32 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +/* +* Copyright 2023 Red Hat +*/ + +#ifndef UDS_THREAD_REGISTRY_H +#define UDS_THREAD_REGISTRY_H + +#include <linux/list.h> +#include <linux/spinlock.h> + +struct thread_registry { +struct list_head links; +spinlock_t lock; +}; + +struct registered_thread { +struct list_head links; +const void *pointer; +struct task_struct *task; +}; + +void uds_initialize_thread_registry (struct thread_registry *registry); + +void uds_register_thread (struct thread_registry *registry, +struct registered_thread *new_thread,const void *pointer); + +void uds_unregister_thread (struct thread_registry *registry); + +const void *uds_lookup_thread (struct thread_registry *registry); + +#endif /* UDS_THREAD_REGISTRY_H */
drivers/md/dm-vdo/uds-threads.c new file +183 -0
183 lines not on this page · raw message
drivers/md/dm-vdo/uds-threads.h new file +115 -0
115 lines not on this page · raw message
Signature · 1 line
2.40.0
Matthew Sakai
maintainerPATCH v5 9/40 dm vdo: add deduplication configuration structures
In reply to Matthew SakaiAdd structures which record the configuration of various deduplication index parameters. This also includes facilities for saving and loading the configuration and validating its integrity.
--- drivers/md/dm-vdo/config.c | 378 +++++++++++++++++++++++++++++++++++ drivers/md/dm-vdo/config.h | 124 ++++++++++++ drivers/md/dm-vdo/geometry.c | 201 +++++++++++++++++++ drivers/md/dm-vdo/geometry.h | 138 +++++++++++++ 4 files changed, 841 insertions(+) create mode 100644 drivers/md/dm-vdo/config.c create mode 100644 drivers/md/dm-vdo/config.h create mode 100644 drivers/md/dm-vdo/geometry.c create mode 100644 drivers/md/dm-vdo/geometry.h
drivers/md/dm-vdo/config.c new file +378 -0
@@ -0,0 +1,378 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* +* Copyright 2023 Red Hat +*/ + +#include "config.h" + +#include "logger.h" +#include "memory-alloc.h" +#include "numeric.h" +#include "string-utils.h" +#include "uds-threads.h" + +static const u8 INDEX_CONFIG_MAGIC [] ="ALBIC" ; +static const u8 INDEX_CONFIG_VERSION_6_02 [] ="06.02" ; +static const u8 INDEX_CONFIG_VERSION_8_02 [] ="08.02" ; + +enum { +DEFAULT_VOLUME_READ_THREADS =2 , +MAX_VOLUME_READ_THREADS =16 , +INDEX_CONFIG_MAGIC_LENGTH =sizeof (INDEX_CONFIG_MAGIC ) -1 , +INDEX_CONFIG_VERSION_LENGTH =sizeof (INDEX_CONFIG_VERSION_6_02 ) -1 , +}; + +static bool is_version (const u8 *version,u8 *buffer) +{ +return memcmp (version, buffer,INDEX_CONFIG_VERSION_LENGTH ) ==0 ; +} + +static bool are_matching_configurations (struct configuration *saved_config, +struct geometry *saved_geometry, +struct configuration *user) +{ +struct geometry *geometry = user->geometry; +bool result = true; + +if (saved_geometry->record_pages_per_chapter != geometry->record_pages_per_chapter) { +uds_log_error ("Record pages per chapter (%u) does not match (%u)" , + saved_geometry->record_pages_per_chapter, + geometry->record_pages_per_chapter); + result = false; + } + +if (saved_geometry->chapters_per_volume != geometry->chapters_per_volume) { +uds_log_error ("Chapter count (%u) does not match (%u)" , + saved_geometry->chapters_per_volume, + geometry->chapters_per_volume); + result = false; + } + +if (saved_geometry->sparse_chapters_per_volume != geometry->sparse_chapters_per_volume) { +uds_log_error ("Sparse chapter count (%u) does not match (%u)" , + saved_geometry->sparse_chapters_per_volume, + geometry->sparse_chapters_per_volume); + result = false; + } + +if (saved_config->cache_chapters != user->cache_chapters) { +uds_log_error ("Cache size (%u) does not match (%u)" , + saved_config->cache_chapters, user->cache_chapters); + result = false; + } + +if (saved_config->volume_index_mean_delta != user->volume_index_mean_delta) { +uds_log_error ("Volume index mean delta (%u) does not match (%u)" , + saved_config->volume_index_mean_delta, + user->volume_index_mean_delta); + result = false; + } + +if (saved_geometry->bytes_per_page != geometry->bytes_per_page) { +uds_log_error ("Bytes per page value (%zu) does not match (%zu)" , + saved_geometry->bytes_per_page, geometry->bytes_per_page); + result = false; + } + +if (saved_config->sparse_sample_rate != user->sparse_sample_rate) { +uds_log_error ("Sparse sample rate (%u) does not match (%u)" , + saved_config->sparse_sample_rate, + user->sparse_sample_rate); + result = false; + } + +if (saved_config->nonce != user->nonce) { +uds_log_error ("Nonce (%llu) does not match (%llu)" , + (unsigned long long ) saved_config->nonce, + (unsigned long long ) user->nonce); + result = false; + } + +return result; +} + +/* Read the configuration and validate it against the provided one. */ +int uds_validate_config_contents (struct buffered_reader *reader, +struct configuration *user_config) +{ +int result; +struct configuration config; +struct geometry geometry; +u8 version_buffer[INDEX_CONFIG_VERSION_LENGTH ]; +u32 bytes_per_page; +u8 buffer[sizeof (struct uds_configuration_6_02 )]; +size_t offset =0 ; + + result =uds_verify_buffered_data (reader,INDEX_CONFIG_MAGIC , +INDEX_CONFIG_MAGIC_LENGTH ); +if (result !=UDS_SUCCESS ) +return result; + + result =uds_read_from_buffered_reader (reader, version_buffer, +INDEX_CONFIG_VERSION_LENGTH ); +if (result !=UDS_SUCCESS ) +return uds_log_error_strerror (result,"cannot read index config version" ); + +if (!is_version (INDEX_CONFIG_VERSION_6_02 , version_buffer) && + !is_version (INDEX_CONFIG_VERSION_8_02 , version_buffer)) { +return uds_log_error_strerror (UDS_CORRUPT_DATA , +"unsupported configuration version: '%.*s'" , +INDEX_CONFIG_VERSION_LENGTH , + version_buffer); + } + + result =uds_read_from_buffered_reader (reader, buffer,sizeof (buffer)); +if (result !=UDS_SUCCESS ) +return uds_log_error_strerror (result,"cannot read config data" ); + +decode_u32_le (buffer, &offset, &geometry.record_pages_per_chapter); +decode_u32_le (buffer, &offset, &geometry.chapters_per_volume); +decode_u32_le (buffer, &offset, &geometry.sparse_chapters_per_volume); +decode_u32_le (buffer, &offset, &config.cache_chapters); + offset +=sizeof (u32); +decode_u32_le (buffer, &offset, &config.volume_index_mean_delta); +decode_u32_le (buffer, &offset, &bytes_per_page); + geometry.bytes_per_page = bytes_per_page; +decode_u32_le (buffer, &offset, &config.sparse_sample_rate); +decode_u64_le (buffer, &offset, &config.nonce); + + result =ASSERT (offset ==sizeof (struct uds_configuration_6_02 ), +"%zu bytes read but not decoded" , +sizeof (struct uds_configuration_6_02 ) - offset); +if (result !=UDS_SUCCESS ) +return UDS_CORRUPT_DATA ; + +if (is_version (INDEX_CONFIG_VERSION_6_02 , version_buffer)) { + user_config->geometry->remapped_virtual =0 ; + user_config->geometry->remapped_physical =0 ; + }else { +u8 remapping[sizeof (u64) +sizeof (u64)]; + + result =uds_read_from_buffered_reader (reader, remapping, +sizeof (remapping)); +if (result !=UDS_SUCCESS ) +return uds_log_error_strerror (result,"cannot read converted config" ); + + offset =0 ; +decode_u64_le (remapping, &offset, + &user_config->geometry->remapped_virtual); +decode_u64_le (remapping, &offset, + &user_config->geometry->remapped_physical); + } + +if (!are_matching_configurations (&config, &geometry, user_config)) { +uds_log_warning ("Supplied configuration does not match save" ); +return UDS_NO_INDEX ; + } + +return UDS_SUCCESS ; +} + +/* +* Write the configuration to stable storage. If the superblock version is < 4, write the 6.02 +* version; otherwise write the 8.02 version, indicating the configuration is for an index that has +* been reduced by one chapter. +*/ +int uds_write_config_contents (struct buffered_writer *writer, +struct configuration *config,u32 version) +{ +int result; +struct geometry *geometry = config->geometry; +u8 buffer[sizeof (struct uds_configuration_8_02 )]; +size_t offset =0 ; + + result =uds_write_to_buffered_writer (writer,INDEX_CONFIG_MAGIC , +INDEX_CONFIG_MAGIC_LENGTH ); +if (result !=UDS_SUCCESS ) +return result; + +/* +* If version is < 4, the index has not been reduced by a chapter so it must be written out +* as version 6.02 so that it is still compatible with older versions of UDS. +*/ +if (version >=4 ) { + result =uds_write_to_buffered_writer (writer,INDEX_CONFIG_VERSION_8_02 , +INDEX_CONFIG_VERSION_LENGTH ); +if (result !=UDS_SUCCESS ) +return result; + }else { + result =uds_write_to_buffered_writer (writer,INDEX_CONFIG_VERSION_6_02 , +INDEX_CONFIG_VERSION_LENGTH ); +if (result !=UDS_SUCCESS ) +return result; + } + +encode_u32_le (buffer, &offset, geometry->record_pages_per_chapter); +encode_u32_le (buffer, &offset, geometry->chapters_per_volume); +encode_u32_le (buffer, &offset, geometry->sparse_chapters_per_volume); +encode_u32_le (buffer, &offset, config->cache_chapters); +encode_u32_le (buffer, &offset,0 ); +encode_u32_le (buffer, &offset, config->volume_index_mean_delta); +encode_u32_le (buffer, &offset, geometry->bytes_per_page); +encode_u32_le (buffer, &offset, config->sparse_sample_rate); +encode_u64_le (buffer, &offset, config->nonce); + + result =ASSERT (offset ==sizeof (struct uds_configuration_6_02 ), +"%zu bytes encoded, of %zu expected" , offset, +sizeof (struct uds_configuration_6_02 )); +if (result !=UDS_SUCCESS ) +return result; + +if (version >=4 ) { +encode_u64_le (buffer, &offset, geometry->remapped_virtual); +encode_u64_le (buffer, &offset, geometry->remapped_physical); + } + +return uds_write_to_buffered_writer (writer, buffer, offset); +} + +/* Compute configuration parameters that depend on memory size. */ +static int compute_memory_sizes (uds_memory_config_size_t mem_gb,bool sparse, +u32 *chapters_per_volume,u32 *record_pages_per_chapter, +u32 *sparse_chapters_per_volume) +{ +u32 reduced_chapters =0 ; +u32 base_chapters; + +if (mem_gb ==UDS_MEMORY_CONFIG_256MB ) { + base_chapters =DEFAULT_CHAPTERS_PER_VOLUME ; + *record_pages_per_chapter =SMALL_RECORD_PAGES_PER_CHAPTER ; + }else if (mem_gb ==UDS_MEMORY_CONFIG_512MB ) { + base_chapters =DEFAULT_CHAPTERS_PER_VOLUME ; + *record_pages_per_chapter =2 *SMALL_RECORD_PAGES_PER_CHAPTER ; + }else if (mem_gb ==UDS_MEMORY_CONFIG_768MB ) { + base_chapters =DEFAULT_CHAPTERS_PER_VOLUME ; + *record_pages_per_chapter =3 *SMALL_RECORD_PAGES_PER_CHAPTER ; + }else if ((mem_gb >=1 ) && (mem_gb <=UDS_MEMORY_CONFIG_MAX )) { + base_chapters = mem_gb *DEFAULT_CHAPTERS_PER_VOLUME ; + *record_pages_per_chapter =DEFAULT_RECORD_PAGES_PER_CHAPTER ; + }else if (mem_gb ==UDS_MEMORY_CONFIG_REDUCED_256MB ) { + reduced_chapters =1 ; + base_chapters =DEFAULT_CHAPTERS_PER_VOLUME ; + *record_pages_per_chapter =SMALL_RECORD_PAGES_PER_CHAPTER ; + }else if (mem_gb ==UDS_MEMORY_CONFIG_REDUCED_512MB ) { + reduced_chapters =1 ; + base_chapters =DEFAULT_CHAPTERS_PER_VOLUME ; + *record_pages_per_chapter =2 *SMALL_RECORD_PAGES_PER_CHAPTER ; + }else if (mem_gb ==UDS_MEMORY_CONFIG_REDUCED_768MB ) { + reduced_chapters =1 ; + base_chapters =DEFAULT_CHAPTERS_PER_VOLUME ; + *record_pages_per_chapter =3 *SMALL_RECORD_PAGES_PER_CHAPTER ; + }else if ((mem_gb >=1 +UDS_MEMORY_CONFIG_REDUCED ) && + (mem_gb <=UDS_MEMORY_CONFIG_REDUCED_MAX )) { + reduced_chapters =1 ; + base_chapters = ((mem_gb -UDS_MEMORY_CONFIG_REDUCED ) * +DEFAULT_CHAPTERS_PER_VOLUME ); + *record_pages_per_chapter =DEFAULT_RECORD_PAGES_PER_CHAPTER ; + }else { +uds_log_error ("received invalid memory size" ); +return -EINVAL ; + } + +if (sparse) { +/* Make 95% of chapters sparse, allowing 10x more records. */ + *sparse_chapters_per_volume = (19 * base_chapters) /2 ; + base_chapters *=10 ; + }else { + *sparse_chapters_per_volume =0 ; + } + + *chapters_per_volume = base_chapters - reduced_chapters; +return UDS_SUCCESS ; +} + +static unsigned int __must_check normalize_zone_count (unsigned int requested) +{ +unsigned int zone_count = requested; + +if (zone_count ==0 ) + zone_count =num_online_cpus () /2 ; + +if (zone_count <1 ) + zone_count =1 ; + +if (zone_count >MAX_ZONES ) + zone_count =MAX_ZONES ; + +uds_log_info ("Using %u indexing zone%s for concurrency." , + zone_count, zone_count ==1 ?"" :"s" ); +return zone_count; +} + +static unsigned int __must_check normalize_read_threads (unsigned int requested) +{ +unsigned int read_threads = requested; + +if (read_threads <1 ) + read_threads =DEFAULT_VOLUME_READ_THREADS ; + +if (read_threads >MAX_VOLUME_READ_THREADS ) + read_threads =MAX_VOLUME_READ_THREADS ; + +return read_threads; +} + +int uds_make_configuration (const struct uds_parameters *params, +struct configuration **config_ptr) +{ +struct configuration *config; +u32 chapters_per_volume =0 ; +u32 record_pages_per_chapter =0 ; +u32 sparse_chapters_per_volume =0 ; +int result; + + result =compute_memory_sizes (params->memory_size, params->sparse, + &chapters_per_volume, &record_pages_per_chapter, + &sparse_chapters_per_volume); +if (result !=UDS_SUCCESS ) +return result; + + result = uds_allocate(1, struct configuration, __func__, &config); +if (result !=UDS_SUCCESS ) +return result; + + result =uds_make_geometry (DEFAULT_BYTES_PER_PAGE , record_pages_per_chapter, + chapters_per_volume, sparse_chapters_per_volume,0 ,0 , + &config->geometry); +if (result !=UDS_SUCCESS ) { +uds_free_configuration (config); +return result; + } + + config->zone_count =normalize_zone_count (params->zone_count); + config->read_threads =normalize_read_threads (params->read_threads); + + config->cache_chapters =DEFAULT_CACHE_CHAPTERS ; + config->volume_index_mean_delta =DEFAULT_VOLUME_INDEX_MEAN_DELTA ; + config->sparse_sample_rate = (params->sparse ?DEFAULT_SPARSE_SAMPLE_RATE :0 ); + config->nonce = params->nonce; + config->bdev = params->bdev; + config->offset = params->offset; + config->size = params->size; + + *config_ptr = config; +return UDS_SUCCESS ; +} + +void uds_free_configuration (struct configuration *config) +{ +if (config !=NULL ) { +uds_free_geometry (config->geometry); +uds_free (config); + } +} + +void uds_log_configuration (struct configuration *config) +{ +struct geometry *geometry = config->geometry; + +uds_log_debug ("Configuration:" ); +uds_log_debug (" Record pages per chapter: %10u" , geometry->record_pages_per_chapter); +uds_log_debug (" Chapters per volume: %10u" , geometry->chapters_per_volume); +uds_log_debug (" Sparse chapters per volume: %10u" , geometry->sparse_chapters_per_volume); +uds_log_debug (" Cache size (chapters): %10u" , config->cache_chapters); +uds_log_debug (" Volume index mean delta: %10u" , config->volume_index_mean_delta); +uds_log_debug (" Bytes per page: %10zu" , geometry->bytes_per_page); +uds_log_debug (" Sparse sample rate: %10u" , config->sparse_sample_rate); +uds_log_debug (" Nonce: %llu" , (unsigned long long ) config->nonce); +}
drivers/md/dm-vdo/config.h new file +124 -0
124 lines not on this page · raw message
drivers/md/dm-vdo/geometry.c new file +201 -0
201 lines not on this page · raw message
drivers/md/dm-vdo/geometry.h new file +138 -0
138 lines not on this page · raw message
Signature · 1 line
2.40.0
Matthew Sakai
maintainerPATCH v5 13/40 dm vdo: implement the open chapter and chapter indexes
In reply to Matthew SakaiDeduplication records are stored in groups called chapters. New records are collected in a structure called the open chapter, which is optimized for adding, removing, and sorting records.
When a chapter fills, it is packed into a read-only structure called a closed chapter, which is optimized for searching and reading. The closed chapter includes a delta index, called the chapter index, which maps each record name to the record page containing the record and allows the index to read at most one record page when looking up a record.
--- drivers/md/dm-vdo/chapter-index.c | 291 ++++++++++++++++++++ drivers/md/dm-vdo/chapter-index.h | 63 +++++ drivers/md/dm-vdo/open-chapter.c | 427 ++++++++++++++++++++++++++++++ drivers/md/dm-vdo/open-chapter.h | 79 ++++++ 4 files changed, 860 insertions(+) create mode 100644 drivers/md/dm-vdo/chapter-index.c create mode 100644 drivers/md/dm-vdo/chapter-index.h create mode 100644 drivers/md/dm-vdo/open-chapter.c create mode 100644 drivers/md/dm-vdo/open-chapter.h
drivers/md/dm-vdo/chapter-index.c new file +291 -0
@@ -0,0 +1,291 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* +* Copyright 2023 Red Hat +*/ + +#include "chapter-index.h" + +#include "errors.h" +#include "hash-utils.h" +#include "logger.h" +#include "memory-alloc.h" +#include "permassert.h" +#include "uds.h" + +int uds_make_open_chapter_index (struct open_chapter_index **chapter_index, +const struct geometry *geometry,u64 volume_nonce) +{ +int result; +size_t memory_size; +struct open_chapter_index *index; + + result = uds_allocate(1, struct open_chapter_index, "open chapter index", + &index); +if (result !=UDS_SUCCESS ) +return result; + +/* +* The delta index will rebalance delta lists when memory gets tight, +* so give the chapter index one extra page. +*/ + memory_size = ((geometry->index_pages_per_chapter +1 ) * geometry->bytes_per_page); + index->geometry = geometry; + index->volume_nonce = volume_nonce; + result =uds_initialize_delta_index (&index->delta_index,1 , + geometry->delta_lists_per_chapter, + geometry->chapter_mean_delta, + geometry->chapter_payload_bits, + memory_size,'m' ); +if (result !=UDS_SUCCESS ) { +uds_free (index); +return result; + } + + index->memory_size = index->delta_index.memory_size +sizeof (struct open_chapter_index ); + *chapter_index = index; +return UDS_SUCCESS ; +} + +void uds_free_open_chapter_index (struct open_chapter_index *chapter_index) +{ +if (chapter_index ==NULL ) +return ; + +uds_uninitialize_delta_index (&chapter_index->delta_index); +uds_free (chapter_index); +} + +/* Re-initialize an open chapter index for a new chapter. */ +void uds_empty_open_chapter_index (struct open_chapter_index *chapter_index, +u64 virtual_chapter_number) +{ +uds_reset_delta_index (&chapter_index->delta_index); + chapter_index->virtual_chapter_number = virtual_chapter_number; +} + +static inline bool was_entry_found (const struct delta_index_entry *entry,u32 address) +{ +return (!entry->at_end) && (entry->key == address); +} + +/* Associate a record name with the record page containing its metadata. */ +int uds_put_open_chapter_index_record (struct open_chapter_index *chapter_index, +const struct uds_record_name *name, +u32 page_number) +{ +int result; +struct delta_index_entry entry; +u32 address; +u32 list_number; +const u8 *found_name; +bool found; +const struct geometry *geometry = chapter_index->geometry; +u64 chapter_number = chapter_index->virtual_chapter_number; +u32 record_pages = geometry->record_pages_per_chapter; + + result =ASSERT (page_number < record_pages, +"Page number within chapter (%u) exceeds the maximum value %u" , + page_number, record_pages); +if (result !=UDS_SUCCESS ) +return UDS_INVALID_ARGUMENT ; + + address =uds_hash_to_chapter_delta_address (name, geometry); + list_number =uds_hash_to_chapter_delta_list (name, geometry); + result =uds_get_delta_index_entry (&chapter_index->delta_index, list_number, + address, name->name, &entry); +if (result !=UDS_SUCCESS ) +return result; + + found =was_entry_found (&entry, address); + result =ASSERT (!(found && entry.is_collision), +"Chunk appears more than once in chapter %llu" , + (unsigned long long ) chapter_number); +if (result !=UDS_SUCCESS ) +return UDS_BAD_STATE ; + + found_name = (found ? name->name :NULL ); +return uds_put_delta_index_entry (&entry, address, page_number, found_name); +} + +/* +* Pack a section of an open chapter index into a chapter index page. A range of delta lists +* (starting with a specified list index) is copied from the open chapter index into a memory page. +* The number of lists copied onto the page is returned to the caller on success. +* +* @chapter_index: The open chapter index +* @memory: The memory page to use +* @first_list: The first delta list number to be copied +* @last_page: If true, this is the last page of the chapter index and all the remaining lists must +* be packed onto this page +* @lists_packed: The number of delta lists that were packed onto this page +*/ +int uds_pack_open_chapter_index_page (struct open_chapter_index *chapter_index, +u8 *memory,u32 first_list,bool last_page, +u32 *lists_packed) +{ +int result; +struct delta_index *delta_index = &chapter_index->delta_index; +struct delta_index_stats stats; +u64 nonce = chapter_index->volume_nonce; +u64 chapter_number = chapter_index->virtual_chapter_number; +const struct geometry *geometry = chapter_index->geometry; +u32 list_count = geometry->delta_lists_per_chapter; +unsigned int removals =0 ; +struct delta_index_entry entry; +u32 next_list; +s32 list_number; + +for (;;) { + result =uds_pack_delta_index_page (delta_index, nonce, memory, + geometry->bytes_per_page, + chapter_number, first_list, + lists_packed); +if (result !=UDS_SUCCESS ) +return result; + +if ((first_list + *lists_packed) == list_count) { +/* All lists are packed. */ +break ; + }else if (*lists_packed ==0 ) { +/* +* The next delta list does not fit on a page. This delta list will be +* removed. +*/ + }else if (last_page) { +/* +* This is the last page and there are lists left unpacked, but all of the +* remaining lists must fit on the page. Find a list that contains entries +* and remove the entire list. Try the first list that does not fit. If it +* is empty, we will select the last list that already fits and has any +* entries. +*/ + }else { +/* This page is done. */ +break ; + } + +if (removals ==0 ) { +uds_get_delta_index_stats (delta_index, &stats); +uds_log_warning ("The chapter index for chapter %llu contains %llu entries with %llu collisions" , + (unsigned long long ) chapter_number, + (unsigned long long ) stats.record_count, + (unsigned long long ) stats.collision_count); + } + + list_number = *lists_packed; +do { +if (list_number <0 ) +return UDS_OVERFLOW ; + + next_list = first_list + list_number--, + result =uds_start_delta_index_search (delta_index, next_list,0 , + &entry); +if (result !=UDS_SUCCESS ) +return result; + + result =uds_next_delta_index_entry (&entry); +if (result !=UDS_SUCCESS ) +return result; + }while (entry.at_end); + +do { + result =uds_remove_delta_index_entry (&entry); +if (result !=UDS_SUCCESS ) +return result; + + removals++; + }while (!entry.at_end); + } + +if (removals >0 ) +uds_log_warning ("To avoid chapter index page overflow in chapter %llu, %u entries were removed from the chapter index" , + (unsigned long long ) chapter_number, removals); + +return UDS_SUCCESS ; +} + +/* Make a new chapter index page, initializing it with the data from a given index_page buffer. */ +int uds_initialize_chapter_index_page (struct delta_index_page *index_page, +const struct geometry *geometry,u8 *page_buffer, +u64 volume_nonce) +{ +return uds_initialize_delta_index_page (index_page, volume_nonce, + geometry->chapter_mean_delta, + geometry->chapter_payload_bits, + page_buffer, geometry->bytes_per_page); +} + +/* Validate a chapter index page read during rebuild. */ +int uds_validate_chapter_index_page (const struct delta_index_page *index_page, +const struct geometry *geometry) +{ +int result; +const struct delta_index *delta_index = &index_page->delta_index; +u32 first = index_page->lowest_list_number; +u32 last = index_page->highest_list_number; +u32 list_number; + +/* We walk every delta list from start to finish. */ +for (list_number = first; list_number <= last; list_number++) { +struct delta_index_entry entry; + + result =uds_start_delta_index_search (delta_index, list_number - first, +0 , &entry); +if (result !=UDS_SUCCESS ) +return result; + +for (;;) { + result =uds_next_delta_index_entry (&entry); +if (result !=UDS_SUCCESS ) { +/* +* A random bit stream is highly likely to arrive here when we go +* past the end of the delta list. +*/ +return result; + } + +if (entry.at_end) +break ; + +/* Also make sure that the record page field contains a plausible value. */ +if (uds_get_delta_entry_value (&entry) >= + geometry->record_pages_per_chapter) +/* +* Do not log this as an error. It happens in normal operation when +* we are doing a rebuild but haven't written the entire volume +* once. +*/ +return UDS_CORRUPT_DATA ; + } + } +return UDS_SUCCESS ; +} + +/* +* Search a chapter index page for a record name, returning the record page number that may contain +* the name. +*/ +int uds_search_chapter_index_page (struct delta_index_page *index_page, +const struct geometry *geometry, +const struct uds_record_name *name, +u16 *record_page_ptr) +{ +int result; +struct delta_index *delta_index = &index_page->delta_index; +u32 address =uds_hash_to_chapter_delta_address (name, geometry); +u32 delta_list_number =uds_hash_to_chapter_delta_list (name, geometry); +u32 sub_list_number = delta_list_number - index_page->lowest_list_number; +struct delta_index_entry entry; + + result =uds_get_delta_index_entry (delta_index, sub_list_number, address, + name->name, &entry); +if (result !=UDS_SUCCESS ) +return result; + +if (was_entry_found (&entry, address)) + *record_page_ptr =uds_get_delta_entry_value (&entry); +else + *record_page_ptr =NO_CHAPTER_INDEX_ENTRY ; + +return UDS_SUCCESS ; +}
drivers/md/dm-vdo/chapter-index.h new file +63 -0
63 lines not on this page · raw message
drivers/md/dm-vdo/open-chapter.c new file +427 -0
427 lines not on this page · raw message
drivers/md/dm-vdo/open-chapter.h new file +79 -0
79 lines not on this page · raw message
Signature · 1 line
2.40.0
Matthew Sakai
maintainerPATCH v5 2/40 dm vdo: add the MurmurHash3 fast hashing algorithm
In reply to Matthew SakaiMurmurHash3 is a fast, non-cryptographic, 128-bit hash. It was originally written by Austin Appleby and placed in the public domain. This version has been modified to produce the same result on both big endian and little endian processors, making it suitable for use in portable persistent data.
--- drivers/md/dm-vdo/murmurhash3.c | 175 ++++++++++++++++++++++++++++++++ drivers/md/dm-vdo/murmurhash3.h | 15 +++ 2 files changed, 190 insertions(+) create mode 100644 drivers/md/dm-vdo/murmurhash3.c create mode 100644 drivers/md/dm-vdo/murmurhash3.h
drivers/md/dm-vdo/murmurhash3.c new file +175 -0
@@ -0,0 +1,175 @@ +// SPDX-License-Identifier: LGPL-2.1+ +/* +* MurmurHash3 was written by Austin Appleby, and is placed in the public +* domain. The author hereby disclaims copyright to this source code. +* +* Adapted by John Wiele ([email protected]). +*/ + +#include "murmurhash3.h" + +static inline u64 rotl64 (u64 x,s8 r) +{ +return (x << r) | (x >> (64 - r)); +} + +#define ROTL64 (x, y) rotl64(x, y) +static __always_inline u64 getblock64(const u64 *p, int i) +{ +#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ +return p[i]; +#elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ +return __builtin_bswap64 (p[i]); +#else +#error "can't figure out byte order" +#endif +} + +static __always_inline void putblock64(u64 *p, int i, u64 value) +{ +#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ + p[i] = value; +#elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ + p[i] =__builtin_bswap64 (value); +#else +#error "can't figure out byte order" +#endif +} + +/* Finalization mix - force all bits of a hash block to avalanche */ + +static __always_inline u64 fmix64(u64 k) +{ + k ^= k >>33 ; + k *=0xff51afd7ed558ccdLLU ; + k ^= k >>33 ; + k *=0xc4ceb9fe1a85ec53LLU ; + k ^= k >>33 ; + +return k; +} + +void murmurhash3_128 (const void *key,const int len,const u32 seed,void *out) +{ +const u8 *data = key; +const int nblocks = len /16 ; + +u64 h1 = seed; +u64 h2 = seed; + +const u64 c1 =0x87c37b91114253d5LLU ; +const u64 c2 =0x4cf5ad432745937fLLU ; + +/* body */ + +const u64 *blocks = (const u64 *)(data); + +int i; + +for (i =0 ; i < nblocks; i++) { +u64 k1 =getblock64 (blocks, i *2 +0 ); +u64 k2 =getblock64 (blocks, i *2 +1 ); + + k1 *= c1; + k1 =ROTL64 (k1,31 ); + k1 *= c2; + h1 ^= k1; + + h1 =ROTL64 (h1,27 ); + h1 += h2; + h1 = h1 *5 +0x52dce729 ; + + k2 *= c2; + k2 =ROTL64 (k2,33 ); + k2 *= c1; + h2 ^= k2; + + h2 =ROTL64 (h2,31 ); + h2 += h1; + h2 = h2 *5 +0x38495ab5 ; + } + +/* tail */ + + { +const u8 *tail = (const u8 *)(data + nblocks *16 ); + +u64 k1 =0 ; +u64 k2 =0 ; + +switch (len &15 ) { +case 15 : + k2 ^= ((u64 )tail[14 ]) <<48 ; + fallthrough; +case 14 : + k2 ^= ((u64 )tail[13 ]) <<40 ; + fallthrough; +case 13 : + k2 ^= ((u64 )tail[12 ]) <<32 ; + fallthrough; +case 12 : + k2 ^= ((u64 )tail[11 ]) <<24 ; + fallthrough; +case 11 : + k2 ^= ((u64 )tail[10 ]) <<16 ; + fallthrough; +case 10 : + k2 ^= ((u64 )tail[9 ]) <<8 ; + fallthrough; +case 9 : + k2 ^= ((u64 )tail[8 ]) <<0 ; + k2 *= c2; + k2 =ROTL64 (k2,33 ); + k2 *= c1; + h2 ^= k2; + fallthrough; + +case 8 : + k1 ^= ((u64 )tail[7 ]) <<56 ; + fallthrough; +case 7 : + k1 ^= ((u64 )tail[6 ]) <<48 ; + fallthrough; +case 6 : + k1 ^= ((u64 )tail[5 ]) <<40 ; + fallthrough; +case 5 : + k1 ^= ((u64 )tail[4 ]) <<32 ; + fallthrough; +case 4 : + k1 ^= ((u64 )tail[3 ]) <<24 ; + fallthrough; +case 3 : + k1 ^= ((u64 )tail[2 ]) <<16 ; + fallthrough; +case 2 : + k1 ^= ((u64 )tail[1 ]) <<8 ; + fallthrough; +case 1 : + k1 ^= ((u64 )tail[0 ]) <<0 ; + k1 *= c1; + k1 =ROTL64 (k1,31 ); + k1 *= c2; + h1 ^= k1; +break ; +default : +break ; + }; + } +/* finalization */ + + h1 ^= len; + h2 ^= len; + + h1 += h2; + h2 += h1; + + h1 =fmix64 (h1); + h2 =fmix64 (h2); + + h1 += h2; + h2 += h1; + +putblock64 ((u64 *)out,0 , h1); +putblock64 ((u64 *)out,1 , h2); +}
drivers/md/dm-vdo/murmurhash3.h new file +15 -0
@@ -0,0 +1,15 @@ +/* SPDX-License-Identifier: LGPL-2.1+ */ +/* +* MurmurHash3 was written by Austin Appleby, and is placed in the public +* domain. The author hereby disclaims copyright to this source code. +*/ + +#ifndef _MURMURHASH3_H_ +#define _MURMURHASH3_H_ + +#include <linux/compiler.h> +#include <linux/types.h> + +void murmurhash3_128 (const void *key,int len,u32 seed,void *out); + +#endif /* _MURMURHASH3_H_ */
Signature · 1 line
2.40.0
Matthew Sakai
maintainerPATCH v5 5/40 dm vdo: add vdo type declarations, constants, and simple data structures
In reply to Matthew SakaiAdd definitions of constants defining the fixed parameters of a VDO volume, and the default and maximum values of configurable or dynamic parameters.
Add definitions of internal status codes used for internal communication within the module and for logging.
Add definitions of types and structs used to manage the processing of an I/O operation.
--- drivers/md/dm-vdo/constants.c | 15 ++ drivers/md/dm-vdo/constants.h | 102 ++++++++ drivers/md/dm-vdo/status-codes.c | 123 ++++++++++ drivers/md/dm-vdo/status-codes.h | 112 +++++++++ drivers/md/dm-vdo/types.h | 393 +++++++++++++++++++++++++++++++ drivers/md/dm-vdo/wait-queue.c | 225 ++++++++++++++++++ drivers/md/dm-vdo/wait-queue.h | 131 +++++++++++ 7 files changed, 1101 insertions(+) create mode 100644 drivers/md/dm-vdo/constants.c create mode 100644 drivers/md/dm-vdo/constants.h create mode 100644 drivers/md/dm-vdo/status-codes.c create mode 100644 drivers/md/dm-vdo/status-codes.h create mode 100644 drivers/md/dm-vdo/types.h create mode 100644 drivers/md/dm-vdo/wait-queue.c create mode 100644 drivers/md/dm-vdo/wait-queue.h
drivers/md/dm-vdo/constants.c new file +15 -0
@@ -0,0 +1,15 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* +* Copyright 2023 Red Hat +*/ + +#include "types.h" + +/* The maximum logical space is 4 petabytes, which is 1 terablock. */ +const block_count_t MAXIMUM_VDO_LOGICAL_BLOCKS =1024ULL *1024 *1024 *1024 ; + +/* The maximum physical space is 256 terabytes, which is 64 gigablocks. */ +const block_count_t MAXIMUM_VDO_PHYSICAL_BLOCKS =1024ULL *1024 *1024 *64 ; + +/* unit test minimum */ +const block_count_t MINIMUM_VDO_SLAB_JOURNAL_BLOCKS =2 ;
drivers/md/dm-vdo/constants.h new file +102 -0
102 lines not on this page · raw message
drivers/md/dm-vdo/status-codes.c new file +123 -0
123 lines not on this page · raw message
drivers/md/dm-vdo/status-codes.h new file +112 -0
112 lines not on this page · raw message
drivers/md/dm-vdo/types.h new file +393 -0
393 lines not on this page · raw message
drivers/md/dm-vdo/wait-queue.c new file +225 -0
225 lines not on this page · raw message
drivers/md/dm-vdo/wait-queue.h new file +131 -0
131 lines not on this page · raw message
Signature · 1 line
2.40.0
Matthew Sakai
maintainerPATCH v5 7/40 dm vdo: add specialized request queueing functionality
In reply to Matthew SakaiThis patch adds funnel_queue, a mostly lock-free multi-producer, single-consumer queue. It also adds the request queue used by the dm-vdo deduplication index, and the work_queue used by the dm-vdo data store. Both of these are built on top of funnel queue and are intended to support the dispatching of many short-running tasks. The work_queue also supports priorities. Finally, this patch adds vdo_completion, the structure which is enqueued on work_queues.
--- drivers/md/dm-vdo/completion.c | 140 ++++++ drivers/md/dm-vdo/completion.h | 152 ++++++ drivers/md/dm-vdo/cpu.h | 59 +++ drivers/md/dm-vdo/funnel-queue.c | 171 +++++++ drivers/md/dm-vdo/funnel-queue.h | 110 ++++ drivers/md/dm-vdo/funnel-requestqueue.c | 283 +++++++++++ drivers/md/dm-vdo/funnel-requestqueue.h | 31 ++ drivers/md/dm-vdo/funnel-workqueue.c | 638 ++++++++++++++++++++++++ drivers/md/dm-vdo/funnel-workqueue.h | 51 ++ 9 files changed, 1635 insertions(+) create mode 100644 drivers/md/dm-vdo/completion.c create mode 100644 drivers/md/dm-vdo/completion.h create mode 100644 drivers/md/dm-vdo/cpu.h create mode 100644 drivers/md/dm-vdo/funnel-queue.c create mode 100644 drivers/md/dm-vdo/funnel-queue.h create mode 100644 drivers/md/dm-vdo/funnel-requestqueue.c create mode 100644 drivers/md/dm-vdo/funnel-requestqueue.h create mode 100644 drivers/md/dm-vdo/funnel-workqueue.c create mode 100644 drivers/md/dm-vdo/funnel-workqueue.h
drivers/md/dm-vdo/completion.c new file +140 -0
@@ -0,0 +1,140 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* +* Copyright 2023 Red Hat +*/ + +#include "completion.h" + +#include <linux/kernel.h> + +#include "logger.h" +#include "permassert.h" + +#include "status-codes.h" +#include "types.h" +#include "vio.h" +#include "vdo.h" + +/** +* DOC: vdo completions. +* +* Most of vdo's data structures are lock free, each either belonging to a single "zone," or +* divided into a number of zones whose accesses to the structure do not overlap. During normal +* operation, at most one thread will be operating in any given zone. Each zone has a +* vdo_work_queue which holds vdo_completions that are to be run in that zone. A completion may +* only be enqueued on one queue or operating in a single zone at a time. +* +* At each step of a multi-threaded operation, the completion performing the operation is given a +* callback, error handler, and thread id for the next step. A completion is "run" when it is +* operating on the correct thread (as specified by its callback_thread_id). If the value of its +* "result" field is an error (i.e. not VDO_SUCCESS), the function in its "error_handler" will be +* invoked. If the error_handler is NULL, or there is no error, the function set as its "callback" +* will be invoked. Generally, a completion will not be run directly, but rather will be +* "launched." In this case, it will check whether it is operating on the correct thread. If it is, +* it will run immediately. Otherwise, it will be enqueue on the vdo_work_queue associated with the +* completion's "callback_thread_id". When it is dequeued, it will be on the correct thread, and +* will get run. In some cases, the completion should get queued instead of running immediately, +* even if it is being launched from the correct thread. This is usually in cases where there is a +* long chain of callbacks, all on the same thread, which could overflow the stack. In such cases, +* the completion's "requeue" field should be set to true. Doing so will skip the current thread +* check and simply enqueue the completion. +* +* A completion may be "finished," in which case its "complete" field will be set to true before it +* is next run. It is a bug to attempt to set the result or re-finish a finished completion. +* Because a completion's fields are not safe to examine from any thread other than the one on +* which the completion is currently operating, this field is used only to aid in detecting +* programming errors. It can not be used for cross-thread checking on the status of an operation. +* A completion must be "reset" before it can be reused after it has been finished. Resetting will +* also clear any error from the result field. +**/ + +void vdo_initialize_completion (struct vdo_completion *completion, +struct vdo *vdo, +enum vdo_completion_type type) +{ +memset (completion,0 ,sizeof (*completion)); + completion->vdo = vdo; + completion->type = type; +vdo_reset_completion (completion); +} + +static inline void assert_incomplete (struct vdo_completion *completion) +{ +ASSERT_LOG_ONLY (!completion->complete,"completion is not complete" ); +} + +/** +* vdo_set_completion_result() - Set the result of a completion. +* +* Older errors will not be masked. +*/ +void vdo_set_completion_result (struct vdo_completion *completion,int result) +{ +assert_incomplete (completion); +if (completion->result ==VDO_SUCCESS ) + completion->result = result; +} + +/** +* vdo_launch_completion_with_priority() - Run or enqueue a completion. +* @priority: The priority at which to enqueue the completion. +* +* If called on the correct thread (i.e. the one specified in the completion's callback_thread_id +* field) and not marked for requeue, the completion will be run immediately. Otherwise, the +* completion will be enqueued on the specified thread. +*/ +void vdo_launch_completion_with_priority (struct vdo_completion *completion, +enum vdo_completion_priority priority) +{ +thread_id_t callback_thread = completion->callback_thread_id; + +if (completion->requeue || (callback_thread !=vdo_get_callback_thread_id ())) { +vdo_enqueue_completion (completion, priority); +return ; + } + +vdo_run_completion (completion); +} + +/** vdo_finish_completion() - Mark a completion as complete and then launch it. */ +void vdo_finish_completion (struct vdo_completion *completion) +{ +assert_incomplete (completion); + completion->complete = true; +if (completion->callback !=NULL ) +vdo_launch_completion (completion); +} + +void vdo_enqueue_completion (struct vdo_completion *completion, +enum vdo_completion_priority priority) +{ +struct vdo *vdo = completion->vdo; +thread_id_t thread_id = completion->callback_thread_id; + +if (ASSERT (thread_id < vdo->thread_config.thread_count, +"thread_id %u (completion type %d) is less than thread count %u" , + thread_id, completion->type, + vdo->thread_config.thread_count) !=UDS_SUCCESS ) +BUG (); + + completion->requeue = false; + completion->priority = priority; + completion->my_queue =NULL ; +vdo_enqueue_work_queue (vdo->threads[thread_id].queue, completion); +} + +/** +* vdo_requeue_completion_if_needed() - Requeue a completion if not called on the specified thread. +* +* Return: True if the completion was requeued; callers may not access the completion in this case. +*/ +bool vdo_requeue_completion_if_needed (struct vdo_completion *completion, +thread_id_t callback_thread_id) +{ +if (vdo_get_callback_thread_id () == callback_thread_id) +return false; + + completion->callback_thread_id = callback_thread_id; +vdo_enqueue_completion (completion,VDO_WORK_Q_DEFAULT_PRIORITY ); +return true; +}
drivers/md/dm-vdo/completion.h new file +152 -0
152 lines not on this page · raw message
drivers/md/dm-vdo/cpu.h new file +59 -0
59 lines not on this page · raw message
drivers/md/dm-vdo/funnel-queue.c new file +171 -0
171 lines not on this page · raw message
drivers/md/dm-vdo/funnel-queue.h new file +110 -0
110 lines not on this page · raw message
drivers/md/dm-vdo/funnel-requestqueue.c new file +283 -0
283 lines not on this page · raw message
drivers/md/dm-vdo/funnel-requestqueue.h new file +31 -0
@@ -0,0 +1,31 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +/* +* Copyright 2023 Red Hat +*/ + +#ifndef UDS_REQUEST_QUEUE_H +#define UDS_REQUEST_QUEUE_H + +#include "uds.h" + +/* +* A simple request queue which will handle new requests in the order in which they are received, +* and will attempt to handle requeued requests before new ones. However, the nature of the +* implementation means that it cannot guarantee this ordering; the prioritization is merely a +* hint. +*/ + +struct uds_request_queue ; + +typedef void (*uds_request_queue_processor_fn )(struct uds_request *); + +int __must_check uds_make_request_queue (const char *queue_name, +uds_request_queue_processor_fn processor, +struct uds_request_queue **queue_ptr); + +void uds_request_queue_enqueue (struct uds_request_queue *queue, +struct uds_request *request); + +void uds_request_queue_finish (struct uds_request_queue *queue); + +#endif /* UDS_REQUEST_QUEUE_H */
drivers/md/dm-vdo/funnel-workqueue.c new file +638 -0
638 lines not on this page · raw message
drivers/md/dm-vdo/funnel-workqueue.h new file +51 -0
51 lines not on this page · raw message
Signature · 1 line
2.40.0
Matthew Sakai
maintainerPATCH v5 12/40 dm vdo: implement the volume index
In reply to Matthew SakaiThe volume index is a large delta index that maps each record name to the chapter which contains the newest record for that name. The volume index can contain several million records and is stored entirely in memory while the index is operating, accounting for the majority of the deduplication index's memory budget.
The volume index is composed of two subindexes in order to handle sparse hook names separately from regular names. If sparse indexing is not enabled, the sparse hook portion of the volume index is not used or instantiated.
--- drivers/md/dm-vdo/volume-index.c | 1290 ++++++++++++++++++++++++++++++ drivers/md/dm-vdo/volume-index.h | 192 +++++ 2 files changed, 1482 insertions(+) create mode 100644 drivers/md/dm-vdo/volume-index.c create mode 100644 drivers/md/dm-vdo/volume-index.h
drivers/md/dm-vdo/volume-index.c new file +1290 -0
@@ -0,0 +1,1290 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* +* Copyright 2023 Red Hat +*/ +#include "volume-index.h" + +#include <linux/bitops.h> +#include <linux/bits.h> +#include <linux/cache.h> +#include <linux/compiler.h> +#include <linux/log2.h> + +#include "config.h" +#include "errors.h" +#include "geometry.h" +#include "hash-utils.h" +#include "logger.h" +#include "memory-alloc.h" +#include "numeric.h" +#include "permassert.h" +#include "uds.h" +#include "uds-threads.h" + +/* +* The volume index is a combination of two separate subindexes, one containing sparse hook entries +* (retained for all chapters), and one containing the remaining entries (retained only for the +* dense chapters). If there are no sparse chapters, only the non-hook sub index is used, and it +* will contain all records for all chapters. +* +* The volume index is also divided into zones, with one thread operating on each zone. Each +* incoming request is dispatched to the appropriate thread, and then to the appropriate subindex. +* Each delta list is handled by a single zone. To ensure that the distribution of delta lists to +* zones doesn't underflow (leaving some zone with no delta lists), the minimum number of delta +* lists must be the square of the maximum zone count for both subindexes. +* +* Each subindex zone is a delta index where the payload is a chapter number. The volume index can +* compute the delta list number, address, and zone number from the record name in order to +* dispatch record handling to the correct structures. +* +* Most operations that use all the zones take place either before request processing is allowed, +* or after all requests have been flushed in order to shut down. The only multi-threaded operation +* supported during normal operation is the uds_lookup_volume_index_name() method, used to determine +* whether a new chapter should be loaded into the sparse index cache. This operation only uses the +* sparse hook subindex, and the zone mutexes are used to make this operation safe. +* +* There are three ways of expressing chapter numbers in the volume index: virtual, index, and +* rolling. The interface to the volume index uses virtual chapter numbers, which are 64 bits long. +* Internally the subindex stores only the minimal number of bits necessary by masking away the +* high-order bits. When the index needs to deal with ordering of index chapter numbers, as when +* flushing entries from older chapters, it rolls the index chapter number around so that the +* smallest one in use is mapped to 0. See convert_index_to_virtual() or flush_invalid_entries() +* for an example of this technique. +* +* For efficiency, when older chapter numbers become invalid, the index does not immediately remove +* the invalidated entries. Instead it lazily removes them from a given delta list the next time it +* walks that list during normal operation. Because of this, the index size must be increased +* somewhat to accommodate all the invalid entries that have not yet been removed. For the standard +* index sizes, this requires about 4 chapters of old entries per 1024 chapters of valid entries in +* the index. +*/ + +struct sub_index_parameters { +/* The number of bits in address mask */ +u8 address_bits; +/* The number of bits in chapter number */ +u8 chapter_bits; +/* The mean delta */ +u32 mean_delta; +/* The number of delta lists */ +u64 list_count; +/* The number of chapters used */ +u32 chapter_count; +/* The number of bits per chapter */ +size_t chapter_size_in_bits; +/* The number of bytes of delta list memory */ +size_t memory_size; +/* The number of bytes the index should keep free at all times */ +size_t target_free_bytes; +}; + +struct split_config { +/* The hook subindex configuration */ +struct configuration hook_config; +struct geometry hook_geometry; + +/* The non-hook subindex configuration */ +struct configuration non_hook_config; +struct geometry non_hook_geometry; +}; + +struct chapter_range { +u32 chapter_start; +u32 chapter_count; +}; + +enum {MAGIC_SIZE =8 }; +static const char MAGIC_START_5 [] ="MI5-0005" ; + +struct sub_index_data { +char magic[MAGIC_SIZE ];/* MAGIC_START_5 */ +u64 volume_nonce; +u64 virtual_chapter_low; +u64 virtual_chapter_high; +u32 first_list; +u32 list_count; +}; + +static const char MAGIC_START_6 [] ="MI6-0001" ; + +struct volume_index_data { +char magic[MAGIC_SIZE ];/* MAGIC_START_6 */ +u32 sparse_sample_rate; +}; + +static inline u32 extract_address (const struct volume_sub_index *sub_index, +const struct uds_record_name *name) +{ +return uds_extract_volume_index_bytes (name) & sub_index->address_mask; +} + +static inline u32 extract_dlist_num (const struct volume_sub_index *sub_index, +const struct uds_record_name *name) +{ +u64 bits =uds_extract_volume_index_bytes (name); + +return (bits >> sub_index->address_bits) % sub_index->list_count; +} + +static inline const struct volume_sub_index_zone * +get_zone_for_record (const struct volume_index_record *record) +{ +return &record->sub_index->zones[record->zone_number]; +} + +static inline u64 convert_index_to_virtual (const struct volume_index_record *record, +u32 index_chapter) +{ +const struct volume_sub_index_zone *volume_index_zone =get_zone_for_record (record); +u32 rolling_chapter = ((index_chapter - volume_index_zone->virtual_chapter_low) & + record->sub_index->chapter_mask); + +return volume_index_zone->virtual_chapter_low + rolling_chapter; +} + +static inline u32 convert_virtual_to_index (const struct volume_sub_index *sub_index, +u64 virtual_chapter) +{ +return virtual_chapter & sub_index->chapter_mask; +} + +static inline bool is_virtual_chapter_indexed (const struct volume_index_record *record, +u64 virtual_chapter) +{ +const struct volume_sub_index_zone *volume_index_zone =get_zone_for_record (record); + +return ((virtual_chapter >= volume_index_zone->virtual_chapter_low) && + (virtual_chapter <= volume_index_zone->virtual_chapter_high)); +} + +static inline bool has_sparse (const struct volume_index *volume_index) +{ +return volume_index->sparse_sample_rate >0 ; +} + +bool uds_is_volume_index_sample (const struct volume_index *volume_index, +const struct uds_record_name *name) +{ +if (!has_sparse (volume_index)) +return false; + +return (uds_extract_sampling_bytes (name) % volume_index->sparse_sample_rate) ==0 ; +} + +static inline const struct volume_sub_index * +get_volume_sub_index (const struct volume_index *volume_index, +const struct uds_record_name *name) +{ +return (uds_is_volume_index_sample (volume_index, name) ? + &volume_index->vi_hook : + &volume_index->vi_non_hook); +} + +static unsigned int get_volume_sub_index_zone (const struct volume_sub_index *sub_index, +const struct uds_record_name *name) +{ +return extract_dlist_num (sub_index, name) / sub_index->delta_index.lists_per_zone; +} + +unsigned int uds_get_volume_index_zone (const struct volume_index *volume_index, +const struct uds_record_name *name) +{ +return get_volume_sub_index_zone (get_volume_sub_index (volume_index, name), name); +} + +static int compute_volume_sub_index_parameters (const struct configuration *config, +struct sub_index_parameters *params) +{ +enum {DELTA_LIST_SIZE =256 }; +u64 entries_in_volume_index, address_span; +u32 chapters_in_volume_index, invalid_chapters; +u32 rounded_chapters; +u64 delta_list_records; +u32 address_count; +u64 index_size_in_bits; +size_t expected_index_size; +u64 min_delta_lists =MAX_ZONES *MAX_ZONES ; +struct geometry *geometry = config->geometry; +u64 records_per_chapter = geometry->records_per_chapter; + + params->chapter_count = geometry->chapters_per_volume; +/* +* Make sure that the number of delta list records in the volume index does not change when +* the volume is reduced by one chapter. This preserves the mapping from name to volume +* index delta list. +*/ + rounded_chapters = params->chapter_count; +if (uds_is_reduced_geometry (geometry)) + rounded_chapters +=1 ; + delta_list_records = records_per_chapter * rounded_chapters; + address_count = config->volume_index_mean_delta *DELTA_LIST_SIZE ; + params->list_count =max (delta_list_records /DELTA_LIST_SIZE , min_delta_lists); + params->address_bits =bits_per (address_count -1 ); + params->chapter_bits =bits_per (rounded_chapters -1 ); +if ((u32 ) params->list_count != params->list_count) { +return uds_log_warning_strerror (UDS_INVALID_ARGUMENT , +"cannot initialize volume index with %llu delta lists" , + (unsigned long long ) params->list_count); + } + +if (params->address_bits >31 ) { +return uds_log_warning_strerror (UDS_INVALID_ARGUMENT , +"cannot initialize volume index with %u address bits" , + params->address_bits); + } + +/* +* The probability that a given delta list is not touched during the writing of an entire +* chapter is: +* +* double p_not_touched = pow((double) (params->list_count - 1) / params->list_count, +* records_per_chapter); +* +* For the standard index sizes, about 78% of the delta lists are not touched, and +* therefore contain old index entries that have not been eliminated by the lazy LRU +* processing. Then the number of old index entries that accumulate over the entire index, +* in terms of full chapters worth of entries, is: +* +* double invalid_chapters = p_not_touched / (1.0 - p_not_touched); +* +* For the standard index sizes, the index needs about 3.5 chapters of space for the old +* entries in a 1024 chapter index, so round this up to use 4 chapters per 1024 chapters in +* the index. +*/ + invalid_chapters =max (rounded_chapters /256 ,2U ); + chapters_in_volume_index = rounded_chapters + invalid_chapters; + entries_in_volume_index = records_per_chapter * chapters_in_volume_index; + + address_span = params->list_count << params->address_bits; + params->mean_delta = address_span / entries_in_volume_index; + +/* +* Compute the expected size of a full index, then set the total memory to be 6% larger +* than that expected size. This number should be large enough that there are not many +* rebalances when the index is full. +*/ + params->chapter_size_in_bits =uds_compute_delta_index_size (records_per_chapter, + params->mean_delta, + params->chapter_bits); + index_size_in_bits = params->chapter_size_in_bits * chapters_in_volume_index; + expected_index_size = index_size_in_bits /BITS_PER_BYTE ; + params->memory_size = expected_index_size *106 /100 ; + + params->target_free_bytes = expected_index_size /20 ; +return UDS_SUCCESS ; +} + +static void uninitialize_volume_sub_index (struct volume_sub_index *sub_index) +{ +uds_free (uds_forget (sub_index->flush_chapters)); +uds_free (uds_forget (sub_index->zones)); +uds_uninitialize_delta_index (&sub_index->delta_index); +} + +void uds_free_volume_index (struct volume_index *volume_index) +{ +if (volume_index ==NULL ) +return ; + +if (volume_index->zones !=NULL ) { +unsigned int zone; + +for (zone =0 ; zone < volume_index->zone_count; zone++) +uds_destroy_mutex (&volume_index->zones[zone].hook_mutex); +uds_free (uds_forget (volume_index->zones)); + } + +uninitialize_volume_sub_index (&volume_index->vi_non_hook); +uninitialize_volume_sub_index (&volume_index->vi_hook); +uds_free (volume_index); +} + + +static int compute_volume_sub_index_save_bytes (const struct configuration *config, +size_t *bytes) +{ +struct sub_index_parameters params = { .address_bits =0 }; +int result; + + result =compute_volume_sub_index_parameters (config, ¶ms); +if (result !=UDS_SUCCESS ) +return result; + + *bytes = (sizeof (struct sub_index_data ) + params.list_count *sizeof (u64) + +uds_compute_delta_index_save_bytes (params.list_count, + params.memory_size)); +return UDS_SUCCESS ; +} + +/* This function is only useful if the configuration includes sparse chapters. */ +static void split_configuration (const struct configuration *config, +struct split_config *split) +{ +u64 sample_rate, sample_records; +u64 dense_chapters, sparse_chapters; + +/* Start with copies of the base configuration. */ + split->hook_config = *config; + split->hook_geometry = *config->geometry; + split->hook_config.geometry = &split->hook_geometry; + split->non_hook_config = *config; + split->non_hook_geometry = *config->geometry; + split->non_hook_config.geometry = &split->non_hook_geometry; + + sample_rate = config->sparse_sample_rate; + sparse_chapters = config->geometry->sparse_chapters_per_volume; + dense_chapters = config->geometry->chapters_per_volume - sparse_chapters; + sample_records = config->geometry->records_per_chapter / sample_rate; + +/* Adjust the number of records indexed for each chapter. */ + split->hook_geometry.records_per_chapter = sample_records; + split->non_hook_geometry.records_per_chapter -= sample_records; + +/* Adjust the number of chapters indexed. */ + split->hook_geometry.sparse_chapters_per_volume =0 ; + split->non_hook_geometry.sparse_chapters_per_volume =0 ; + split->non_hook_geometry.chapters_per_volume = dense_chapters; +} + +static int compute_volume_index_save_bytes (const struct configuration *config, +size_t *bytes) +{ +size_t hook_bytes, non_hook_bytes; +struct split_config split; +int result; + +if (!uds_is_sparse_geometry (config->geometry)) +return compute_volume_sub_index_save_bytes (config, bytes); + +split_configuration (config, &split); + result =compute_volume_sub_index_save_bytes (&split.hook_config, &hook_bytes); +if (result !=UDS_SUCCESS ) +return result; + + result =compute_volume_sub_index_save_bytes (&split.non_hook_config, + &non_hook_bytes); +if (result !=UDS_SUCCESS ) +return result; + + *bytes =sizeof (struct volume_index_data ) + hook_bytes + non_hook_bytes; +return UDS_SUCCESS ; +} + +int uds_compute_volume_index_save_blocks (const struct configuration *config, +size_t block_size,u64 *block_count) +{ +size_t bytes; +int result; + + result =compute_volume_index_save_bytes (config, &bytes); +if (result !=UDS_SUCCESS ) +return result; + + bytes +=sizeof (struct delta_list_save_info ); + *block_count =DIV_ROUND_UP (bytes, block_size) +MAX_ZONES ; +return UDS_SUCCESS ; +} + +/* Flush invalid entries while walking the delta list. */ +static inline int flush_invalid_entries (struct volume_index_record *record, +struct chapter_range *flush_range, +u32 *next_chapter_to_invalidate) +{ +int result; + + result =uds_next_delta_index_entry (&record->delta_entry); +if (result !=UDS_SUCCESS ) +return result; + +while (!record->delta_entry.at_end) { +u32 index_chapter =uds_get_delta_entry_value (&record->delta_entry); +u32 relative_chapter = ((index_chapter - flush_range->chapter_start) & + record->sub_index->chapter_mask); + +if (likely (relative_chapter >= flush_range->chapter_count)) { +if (relative_chapter < *next_chapter_to_invalidate) + *next_chapter_to_invalidate = relative_chapter; +break ; + } + + result =uds_remove_delta_index_entry (&record->delta_entry); +if (result !=UDS_SUCCESS ) +return result; + } + +return UDS_SUCCESS ; +} + +/* Find the matching record, or the list offset where the record would go. */ +static int get_volume_index_entry (struct volume_index_record *record,u32 list_number, +u32 key,struct chapter_range *flush_range) +{ +struct volume_index_record other_record; +const struct volume_sub_index *sub_index = record->sub_index; +u32 next_chapter_to_invalidate = sub_index->chapter_mask; +int result; + + result =uds_start_delta_index_search (&sub_index->delta_index, list_number,0 , + &record->delta_entry); +if (result !=UDS_SUCCESS ) +return result; + +do { + result =flush_invalid_entries (record, flush_range, + &next_chapter_to_invalidate); +if (result !=UDS_SUCCESS ) +return result; + }while (!record->delta_entry.at_end && (key > record->delta_entry.key)); + + result =uds_remember_delta_index_offset (&record->delta_entry); +if (result !=UDS_SUCCESS ) +return result; + +/* Check any collision records for a more precise match. */ + other_record = *record; +if (!other_record.delta_entry.at_end && (key == other_record.delta_entry.key)) { +for (;;) { +u8 collision_name[UDS_RECORD_NAME_SIZE ]; + + result =flush_invalid_entries (&other_record, flush_range, + &next_chapter_to_invalidate); +if (result !=UDS_SUCCESS ) +return result; + +if (other_record.delta_entry.at_end || + !other_record.delta_entry.is_collision) +break ; + + result =uds_get_delta_entry_collision (&other_record.delta_entry, + collision_name); +if (result !=UDS_SUCCESS ) +return result; + +if (memcmp (collision_name, record->name,UDS_RECORD_NAME_SIZE ) ==0 ) { + *record = other_record; +break ; + } + } + } +while (!other_record.delta_entry.at_end) { + result =flush_invalid_entries (&other_record, flush_range, + &next_chapter_to_invalidate); +if (result !=UDS_SUCCESS ) +return result; + } + next_chapter_to_invalidate += flush_range->chapter_start; + next_chapter_to_invalidate &= sub_index->chapter_mask; + flush_range->chapter_start = next_chapter_to_invalidate; + flush_range->chapter_count =0 ; +return UDS_SUCCESS ; +} + +static int get_volume_sub_index_record (struct volume_sub_index *sub_index, +const struct uds_record_name *name, +struct volume_index_record *record) +{ +int result; +const struct volume_sub_index_zone *volume_index_zone; +u32 address =extract_address (sub_index, name); +u32 delta_list_number =extract_dlist_num (sub_index, name); +u64 flush_chapter = sub_index->flush_chapters[delta_list_number]; + + record->sub_index = sub_index; + record->mutex =NULL ; + record->name = name; + record->zone_number = delta_list_number / sub_index->delta_index.lists_per_zone; + volume_index_zone =get_zone_for_record (record); + +if (flush_chapter < volume_index_zone->virtual_chapter_low) { +struct chapter_range range; +u64 flush_count = volume_index_zone->virtual_chapter_low - flush_chapter; + + range.chapter_start =convert_virtual_to_index (sub_index, flush_chapter); + range.chapter_count = (flush_count > sub_index->chapter_mask ? + sub_index->chapter_mask +1 : + flush_count); + result =get_volume_index_entry (record, delta_list_number, address, + &range); + flush_chapter =convert_index_to_virtual (record, range.chapter_start); +if (flush_chapter > volume_index_zone->virtual_chapter_high) + flush_chapter = volume_index_zone->virtual_chapter_high; + sub_index->flush_chapters[delta_list_number] = flush_chapter; + }else { + result =uds_get_delta_index_entry (&sub_index->delta_index, + delta_list_number, address, + name->name, &record->delta_entry); + } + +if (result !=UDS_SUCCESS ) +return result; + + record->is_found = + (!record->delta_entry.at_end && (record->delta_entry.key == address)); +if (record->is_found) { +u32 index_chapter =uds_get_delta_entry_value (&record->delta_entry); + + record->virtual_chapter =convert_index_to_virtual (record, index_chapter); + } + + record->is_collision = record->delta_entry.is_collision; +return UDS_SUCCESS ; +} + +int uds_get_volume_index_record (struct volume_index *volume_index, +const struct uds_record_name *name, +struct volume_index_record *record) +{ +int result; + +if (uds_is_volume_index_sample (volume_index, name)) { +/* +* Other threads cannot be allowed to call uds_lookup_volume_index_name() while +* this thread is finding the volume index record. Due to the lazy LRU flushing of +* the volume index, uds_get_volume_index_record() is not a read-only operation. +*/ +unsigned int zone = +get_volume_sub_index_zone (&volume_index->vi_hook, name); +struct mutex *mutex = &volume_index->zones[zone].hook_mutex; + +uds_lock_mutex (mutex); + result =get_volume_sub_index_record (&volume_index->vi_hook, name, + record); +uds_unlock_mutex (mutex); +/* Remember the mutex so that other operations on the index record can use it. */ + record->mutex = mutex; + }else { + result =get_volume_sub_index_record (&volume_index->vi_non_hook, name, + record); + } + +return result; +} + +int uds_put_volume_index_record (struct volume_index_record *record,u64 virtual_chapter) +{ +int result; +u32 address; +const struct volume_sub_index *sub_index = record->sub_index; + +if (!is_virtual_chapter_indexed (record, virtual_chapter)) { +u64 low =get_zone_for_record (record)->virtual_chapter_low; +u64 high =get_zone_for_record (record)->virtual_chapter_high; + +return uds_log_warning_strerror (UDS_INVALID_ARGUMENT , +"cannot put record into chapter number %llu that is out of the valid range %llu to %llu" , + (unsigned long long ) virtual_chapter, + (unsigned long long ) low, + (unsigned long long ) high); + } + address =extract_address (sub_index, record->name); +if (unlikely (record->mutex !=NULL )) +uds_lock_mutex (record->mutex); + result =uds_put_delta_index_entry (&record->delta_entry, address, +convert_virtual_to_index (sub_index, + virtual_chapter), + record->is_found ? record->name->name :NULL ); +if (unlikely (record->mutex !=NULL )) +uds_unlock_mutex (record->mutex); +switch (result) { +case UDS_SUCCESS : + record->virtual_chapter = virtual_chapter; + record->is_collision = record->delta_entry.is_collision; + record->is_found = true; +break ; +case UDS_OVERFLOW : +uds_log_ratelimit (uds_log_warning_strerror,UDS_OVERFLOW , +"Volume index entry dropped due to overflow condition" ); +uds_log_delta_index_entry (&record->delta_entry); +break ; +default : +break ; + } + +return result; +} + +int uds_remove_volume_index_record (struct volume_index_record *record) +{ +int result; + +if (!record->is_found) +return uds_log_warning_strerror (UDS_BAD_STATE , +"illegal operation on new record" ); + +/* Mark the record so that it cannot be used again */ + record->is_found = false; +if (unlikely (record->mutex !=NULL )) +uds_lock_mutex (record->mutex); + result =uds_remove_delta_index_entry (&record->delta_entry); +if (unlikely (record->mutex !=NULL )) +uds_unlock_mutex (record->mutex); +return result; +} + +static void set_volume_sub_index_zone_open_chapter (struct volume_sub_index *sub_index, +unsigned int zone_number, +u64 virtual_chapter) +{ +u64 used_bits =0 ; +struct volume_sub_index_zone *zone = &sub_index->zones[zone_number]; +struct delta_zone *delta_zone; +u32 i; + + zone->virtual_chapter_low = (virtual_chapter >= sub_index->chapter_count ? + virtual_chapter - sub_index->chapter_count +1 : +0 ); + zone->virtual_chapter_high = virtual_chapter; + +/* Check to see if the new zone data is too large. */ + delta_zone = &sub_index->delta_index.delta_zones[zone_number]; +for (i =1 ; i <= delta_zone->list_count; i++) + used_bits += delta_zone->delta_lists[i].size; + +if (used_bits > sub_index->max_zone_bits) { +/* Expire enough chapters to free the desired space. */ +u64 expire_count = +1 + (used_bits - sub_index->max_zone_bits) / sub_index->chapter_zone_bits; + +if (expire_count ==1 ) { +uds_log_ratelimit (uds_log_info, +"zone %u: At chapter %llu, expiring chapter %llu early" , + zone_number, + (unsigned long long ) virtual_chapter, + (unsigned long long ) zone->virtual_chapter_low); + zone->early_flushes++; + zone->virtual_chapter_low++; + }else { +u64 first_expired = zone->virtual_chapter_low; + +if (first_expired + expire_count < zone->virtual_chapter_high) { + zone->early_flushes += expire_count; + zone->virtual_chapter_low += expire_count; + }else { + zone->early_flushes += + zone->virtual_chapter_high - zone->virtual_chapter_low; + zone->virtual_chapter_low = zone->virtual_chapter_high; + } +uds_log_ratelimit (uds_log_info, +"zone %u: At chapter %llu, expiring chapters %llu to %llu early" , + zone_number, + (unsigned long long ) virtual_chapter, + (unsigned long long ) first_expired, + (unsigned long long ) zone->virtual_chapter_low -1 ); + } + } +} + +void uds_set_volume_index_zone_open_chapter (struct volume_index *volume_index, +unsigned int zone_number, +u64 virtual_chapter) +{ +struct mutex *mutex = &volume_index->zones[zone_number].hook_mutex; + +set_volume_sub_index_zone_open_chapter (&volume_index->vi_non_hook, zone_number, + virtual_chapter); + +/* +* Other threads cannot be allowed to call uds_lookup_volume_index_name() while the open +* chapter number is changing. +*/ +if (has_sparse (volume_index)) { +uds_lock_mutex (mutex); +set_volume_sub_index_zone_open_chapter (&volume_index->vi_hook, + zone_number, virtual_chapter); +uds_unlock_mutex (mutex); + } +} + +/* +* Set the newest open chapter number for the index, while also advancing the oldest valid chapter +* number. +*/ +void uds_set_volume_index_open_chapter (struct volume_index *volume_index, +u64 virtual_chapter) +{ +unsigned int zone; + +for (zone =0 ; zone < volume_index->zone_count; zone++) +uds_set_volume_index_zone_open_chapter (volume_index, zone, virtual_chapter); +} + +int uds_set_volume_index_record_chapter (struct volume_index_record *record, +u64 virtual_chapter) +{ +const struct volume_sub_index *sub_index = record->sub_index; +int result; + +if (!record->is_found) +return uds_log_warning_strerror (UDS_BAD_STATE , +"illegal operation on new record" ); + +if (!is_virtual_chapter_indexed (record, virtual_chapter)) { +u64 low =get_zone_for_record (record)->virtual_chapter_low; +u64 high =get_zone_for_record (record)->virtual_chapter_high; + +return uds_log_warning_strerror (UDS_INVALID_ARGUMENT , +"cannot set chapter number %llu that is out of the valid range %llu to %llu" , + (unsigned long long ) virtual_chapter, + (unsigned long long ) low, + (unsigned long long ) high); + } + +if (unlikely (record->mutex !=NULL )) +uds_lock_mutex (record->mutex); + result =uds_set_delta_entry_value (&record->delta_entry, +convert_virtual_to_index (sub_index, + virtual_chapter)); +if (unlikely (record->mutex !=NULL )) +uds_unlock_mutex (record->mutex); +if (result !=UDS_SUCCESS ) +return result; + + record->virtual_chapter = virtual_chapter; +return UDS_SUCCESS ; +} + +static u64 lookup_volume_sub_index_name (const struct volume_sub_index *sub_index, +const struct uds_record_name *name) +{ +int result; +u32 address =extract_address (sub_index, name); +u32 delta_list_number =extract_dlist_num (sub_index, name); +unsigned int zone_number =get_volume_sub_index_zone (sub_index, name); +const struct volume_sub_index_zone *zone = &sub_index->zones[zone_number]; +u64 virtual_chapter; +u32 index_chapter; +u32 rolling_chapter; +struct delta_index_entry delta_entry; + + result =uds_get_delta_index_entry (&sub_index->delta_index, delta_list_number, + address, name->name, &delta_entry); +if (result !=UDS_SUCCESS ) +return NO_CHAPTER ; + +if (delta_entry.at_end || (delta_entry.key != address)) +return NO_CHAPTER ; + + index_chapter =uds_get_delta_entry_value (&delta_entry); + rolling_chapter = (index_chapter - zone->virtual_chapter_low) & sub_index->chapter_mask; + + virtual_chapter = zone->virtual_chapter_low + rolling_chapter; +if (virtual_chapter > zone->virtual_chapter_high) +return NO_CHAPTER ; + +return virtual_chapter; +} + +/* Do a read-only lookup of the record name for sparse cache management. */ +u64 uds_lookup_volume_index_name (const struct volume_index *volume_index, +const struct uds_record_name *name) +{ +unsigned int zone_number =uds_get_volume_index_zone (volume_index, name); +struct mutex *mutex = &volume_index->zones[zone_number].hook_mutex; +u64 virtual_chapter; + +if (!uds_is_volume_index_sample (volume_index, name)) +return NO_CHAPTER ; + +uds_lock_mutex (mutex); + virtual_chapter =lookup_volume_sub_index_name (&volume_index->vi_hook, name); +uds_unlock_mutex (mutex); + +return virtual_chapter; +} + +static void abort_restoring_volume_sub_index (struct volume_sub_index *sub_index) +{ +uds_reset_delta_index (&sub_index->delta_index); +} + +static void abort_restoring_volume_index (struct volume_index *volume_index) +{ +abort_restoring_volume_sub_index (&volume_index->vi_non_hook); +if (has_sparse (volume_index)) +abort_restoring_volume_sub_index (&volume_index->vi_hook); +} + +static int start_restoring_volume_sub_index (struct volume_sub_index *sub_index, +struct buffered_reader **readers, +unsigned int reader_count) +{ +unsigned int z; +int result; +u64 virtual_chapter_low =0 , virtual_chapter_high =0 ; +unsigned int i; + +for (i =0 ; i < reader_count; i++) { +struct sub_index_data header; +u8 buffer[sizeof (struct sub_index_data )]; +size_t offset =0 ; +u32 j; + + result =uds_read_from_buffered_reader (readers[i], buffer, +sizeof (buffer)); +if (result !=UDS_SUCCESS ) { +return uds_log_warning_strerror (result, +"failed to read volume index header" ); + } + +memcpy (&header.magic, buffer,MAGIC_SIZE ); + offset +=MAGIC_SIZE ; +decode_u64_le (buffer, &offset, &header.volume_nonce); +decode_u64_le (buffer, &offset, &header.virtual_chapter_low); +decode_u64_le (buffer, &offset, &header.virtual_chapter_high); +decode_u32_le (buffer, &offset, &header.first_list); +decode_u32_le (buffer, &offset, &header.list_count); + + result =ASSERT (offset =sizeof (buffer), +"%zu bytes decoded of %zu expected" , offset, +sizeof (buffer)); +if (result !=UDS_SUCCESS ) + result =UDS_CORRUPT_DATA ; + +if (memcmp (header.magic,MAGIC_START_5 ,MAGIC_SIZE ) !=0 ) { +return uds_log_warning_strerror (UDS_CORRUPT_DATA , +"volume index file had bad magic number" ); + } + +if (sub_index->volume_nonce ==0 ) { + sub_index->volume_nonce = header.volume_nonce; + }else if (header.volume_nonce != sub_index->volume_nonce) { +return uds_log_warning_strerror (UDS_CORRUPT_DATA , +"volume index volume nonce incorrect" ); + } + +if (i ==0 ) { + virtual_chapter_low = header.virtual_chapter_low; + virtual_chapter_high = header.virtual_chapter_high; + }else if (virtual_chapter_high != header.virtual_chapter_high) { +u64 low = header.virtual_chapter_low; +u64 high = header.virtual_chapter_high; + +return uds_log_warning_strerror (UDS_CORRUPT_DATA , +"Inconsistent volume index zone files: Chapter range is [%llu,%llu], chapter range %d is [%llu,%llu]" , + (unsigned long long ) virtual_chapter_low, + (unsigned long long ) virtual_chapter_high, + i, (unsigned long long ) low, + (unsigned long long ) high); + }else if (virtual_chapter_low < header.virtual_chapter_low) { + virtual_chapter_low = header.virtual_chapter_low; + } + +for (j =0 ; j < header.list_count; j++) { +u8 decoded[sizeof (u64)]; + + result =uds_read_from_buffered_reader (readers[i], decoded, +sizeof (u64)); +if (result !=UDS_SUCCESS ) { +return uds_log_warning_strerror (result, +"failed to read volume index flush ranges" ); + } + + sub_index->flush_chapters[header.first_list + j] = +get_unaligned_le64 (decoded); + } + } + +for (z =0 ; z < sub_index->zone_count; z++) { +memset (&sub_index->zones[z],0 ,sizeof (struct volume_sub_index_zone )); + sub_index->zones[z].virtual_chapter_low = virtual_chapter_low; + sub_index->zones[z].virtual_chapter_high = virtual_chapter_high; + } + + result =uds_start_restoring_delta_index (&sub_index->delta_index, readers, + reader_count); +if (result !=UDS_SUCCESS ) +return uds_log_warning_strerror (result,"restoring delta index failed" ); + +return UDS_SUCCESS ; +} + +static int start_restoring_volume_index (struct volume_index *volume_index, +struct buffered_reader **buffered_readers, +unsigned int reader_count) +{ +unsigned int i; +int result; + +if (!has_sparse (volume_index)) { +return start_restoring_volume_sub_index (&volume_index->vi_non_hook, + buffered_readers, reader_count); + } + +for (i =0 ; i < reader_count; i++) { +struct volume_index_data header; +u8 buffer[sizeof (struct volume_index_data )]; +size_t offset =0 ; + + result =uds_read_from_buffered_reader (buffered_readers[i], buffer, +sizeof (buffer)); +if (result !=UDS_SUCCESS ) { +return uds_log_warning_strerror (result, +"failed to read volume index header" ); + } + +memcpy (&header.magic, buffer,MAGIC_SIZE ); + offset +=MAGIC_SIZE ; +decode_u32_le (buffer, &offset, &header.sparse_sample_rate); + + result =ASSERT (offset ==sizeof (buffer), +"%zu bytes decoded of %zu expected" , offset, +sizeof (buffer)); +if (result !=UDS_SUCCESS ) + result =UDS_CORRUPT_DATA ; + +if (memcmp (header.magic,MAGIC_START_6 ,MAGIC_SIZE ) !=0 ) +return uds_log_warning_strerror (UDS_CORRUPT_DATA , +"volume index file had bad magic number" ); + +if (i ==0 ) { + volume_index->sparse_sample_rate = header.sparse_sample_rate; + }else if (volume_index->sparse_sample_rate != header.sparse_sample_rate) { +uds_log_warning_strerror (UDS_CORRUPT_DATA , +"Inconsistent sparse sample rate in delta index zone files: %u vs. %u" , + volume_index->sparse_sample_rate, + header.sparse_sample_rate); +return UDS_CORRUPT_DATA ; + } + } + + result =start_restoring_volume_sub_index (&volume_index->vi_non_hook, + buffered_readers, reader_count); +if (result !=UDS_SUCCESS ) +return result; + +return start_restoring_volume_sub_index (&volume_index->vi_hook, buffered_readers, + reader_count); +} + +static int finish_restoring_volume_sub_index (struct volume_sub_index *sub_index, +struct buffered_reader **buffered_readers, +unsigned int reader_count) +{ +return uds_finish_restoring_delta_index (&sub_index->delta_index, + buffered_readers, reader_count); +} + +static int finish_restoring_volume_index (struct volume_index *volume_index, +struct buffered_reader **buffered_readers, +unsigned int reader_count) +{ +int result; + + result =finish_restoring_volume_sub_index (&volume_index->vi_non_hook, + buffered_readers, reader_count); +if ((result ==UDS_SUCCESS ) &&has_sparse (volume_index)) { + result =finish_restoring_volume_sub_index (&volume_index->vi_hook, + buffered_readers, + reader_count); + } + +return result; +} + +int uds_load_volume_index (struct volume_index *volume_index, +struct buffered_reader **readers,unsigned int reader_count) +{ +int result; + +/* Start by reading the header section of the stream. */ + result =start_restoring_volume_index (volume_index, readers, reader_count); +if (result !=UDS_SUCCESS ) +return result; + + result =finish_restoring_volume_index (volume_index, readers, reader_count); +if (result !=UDS_SUCCESS ) { +abort_restoring_volume_index (volume_index); +return result; + } + +/* Check the final guard lists to make sure there is no extra data. */ + result =uds_check_guard_delta_lists (readers, reader_count); +if (result !=UDS_SUCCESS ) +abort_restoring_volume_index (volume_index); + +return result; +} + +static int start_saving_volume_sub_index (const struct volume_sub_index *sub_index, +unsigned int zone_number, +struct buffered_writer *buffered_writer) +{ +int result; +struct volume_sub_index_zone *volume_index_zone = &sub_index->zones[zone_number]; +u32 first_list = sub_index->delta_index.delta_zones[zone_number].first_list; +u32 list_count = sub_index->delta_index.delta_zones[zone_number].list_count; +u8 buffer[sizeof (struct sub_index_data )]; +size_t offset =0 ; +u32 i; + +memcpy (buffer,MAGIC_START_5 ,MAGIC_SIZE ); + offset +=MAGIC_SIZE ; +encode_u64_le (buffer, &offset, sub_index->volume_nonce); +encode_u64_le (buffer, &offset, volume_index_zone->virtual_chapter_low); +encode_u64_le (buffer, &offset, volume_index_zone->virtual_chapter_high); +encode_u32_le (buffer, &offset, first_list); +encode_u32_le (buffer, &offset, list_count); + + result =ASSERT (offset ==sizeof (struct sub_index_data ), +"%zu bytes of config written, of %zu expected" , offset, +sizeof (struct sub_index_data )); +if (result !=UDS_SUCCESS ) +return result; + + result =uds_write_to_buffered_writer (buffered_writer, buffer, offset); +if (result !=UDS_SUCCESS ) +return uds_log_warning_strerror (result, +"failed to write volume index header" ); + +for (i =0 ; i < list_count; i++) { +u8 encoded[sizeof (u64)]; + +put_unaligned_le64 (sub_index->flush_chapters[first_list + i], &encoded); + result =uds_write_to_buffered_writer (buffered_writer, encoded, +sizeof (u64)); +if (result !=UDS_SUCCESS ) { +return uds_log_warning_strerror (result, +"failed to write volume index flush ranges" ); + } + } + +return uds_start_saving_delta_index (&sub_index->delta_index, zone_number, + buffered_writer); +} + +static int start_saving_volume_index (const struct volume_index *volume_index, +unsigned int zone_number, +struct buffered_writer *writer) +{ +u8 buffer[sizeof (struct volume_index_data )]; +size_t offset =0 ; +int result; + +if (!has_sparse (volume_index)) { +return start_saving_volume_sub_index (&volume_index->vi_non_hook, + zone_number, writer); + } + +memcpy (buffer,MAGIC_START_6 ,MAGIC_SIZE ); + offset +=MAGIC_SIZE ; +encode_u32_le (buffer, &offset, volume_index->sparse_sample_rate); + result =ASSERT (offset ==sizeof (struct volume_index_data ), +"%zu bytes of header written, of %zu expected" , offset, +sizeof (struct volume_index_data )); +if (result !=UDS_SUCCESS ) +return result; + + result =uds_write_to_buffered_writer (writer, buffer, offset); +if (result !=UDS_SUCCESS ) { +uds_log_warning_strerror (result,"failed to write volume index header" ); +return result; + } + + result =start_saving_volume_sub_index (&volume_index->vi_non_hook, zone_number, + writer); +if (result !=UDS_SUCCESS ) +return result; + +return start_saving_volume_sub_index (&volume_index->vi_hook, zone_number, + writer); +} + +static int finish_saving_volume_sub_index (const struct volume_sub_index *sub_index, +unsigned int zone_number) +{ +return uds_finish_saving_delta_index (&sub_index->delta_index, zone_number); +} + +static int finish_saving_volume_index (const struct volume_index *volume_index, +unsigned int zone_number) +{ +int result; + + result =finish_saving_volume_sub_index (&volume_index->vi_non_hook, zone_number); +if ((result ==UDS_SUCCESS ) &&has_sparse (volume_index)) + result =finish_saving_volume_sub_index (&volume_index->vi_hook, zone_number); +return result; +} + +int uds_save_volume_index (struct volume_index *volume_index, +struct buffered_writer **writers,unsigned int writer_count) +{ +int result =UDS_SUCCESS ; +unsigned int zone; + +for (zone =0 ; zone < writer_count; zone++) { + result =start_saving_volume_index (volume_index, zone, writers[zone]); +if (result !=UDS_SUCCESS ) +break ; + + result =finish_saving_volume_index (volume_index, zone); +if (result !=UDS_SUCCESS ) +break ; + + result =uds_write_guard_delta_list (writers[zone]); +if (result !=UDS_SUCCESS ) +break ; + + result =uds_flush_buffered_writer (writers[zone]); +if (result !=UDS_SUCCESS ) +break ; + } + +return result; +} + +static void get_volume_sub_index_stats (const struct volume_sub_index *sub_index, +struct volume_index_stats *stats) +{ +struct delta_index_stats dis; +unsigned int z; + +uds_get_delta_index_stats (&sub_index->delta_index, &dis); + stats->rebalance_time = dis.rebalance_time; + stats->rebalance_count = dis.rebalance_count; + stats->record_count = dis.record_count; + stats->collision_count = dis.collision_count; + stats->discard_count = dis.discard_count; + stats->overflow_count = dis.overflow_count; + stats->delta_lists = dis.list_count; + stats->early_flushes =0 ; +for (z =0 ; z < sub_index->zone_count; z++) + stats->early_flushes += sub_index->zones[z].early_flushes; +} + +void uds_get_volume_index_stats (const struct volume_index *volume_index, +struct volume_index_stats *stats) +{ +struct volume_index_stats sparse_stats; + +get_volume_sub_index_stats (&volume_index->vi_non_hook, stats); +if (!has_sparse (volume_index)) +return ; + +get_volume_sub_index_stats (&volume_index->vi_hook, &sparse_stats); + stats->rebalance_time += sparse_stats.rebalance_time; + stats->rebalance_count += sparse_stats.rebalance_count; + stats->record_count += sparse_stats.record_count; + stats->collision_count += sparse_stats.collision_count; + stats->discard_count += sparse_stats.discard_count; + stats->overflow_count += sparse_stats.overflow_count; + stats->delta_lists += sparse_stats.delta_lists; + stats->early_flushes += sparse_stats.early_flushes; +} + +static int initialize_volume_sub_index (const struct configuration *config, +u64 volume_nonce,u8 tag, +struct volume_sub_index *sub_index) +{ +struct sub_index_parameters params = { .address_bits =0 }; +unsigned int zone_count = config->zone_count; +u64 available_bytes =0 ; +unsigned int z; +int result; + + result =compute_volume_sub_index_parameters (config, ¶ms); +if (result !=UDS_SUCCESS ) +return result; + + sub_index->address_bits = params.address_bits; + sub_index->address_mask = (1u << params.address_bits) -1 ; + sub_index->chapter_bits = params.chapter_bits; + sub_index->chapter_mask = (1u << params.chapter_bits) -1 ; + sub_index->chapter_count = params.chapter_count; + sub_index->list_count = params.list_count; + sub_index->zone_count = zone_count; + sub_index->chapter_zone_bits = params.chapter_size_in_bits / zone_count; + sub_index->volume_nonce = volume_nonce; + + result =uds_initialize_delta_index (&sub_index->delta_index, zone_count, + params.list_count, params.mean_delta, + params.chapter_bits, params.memory_size, + tag); +if (result !=UDS_SUCCESS ) +return result; + +for (z =0 ; z < sub_index->delta_index.zone_count; z++) + available_bytes += sub_index->delta_index.delta_zones[z].size; + available_bytes -= params.target_free_bytes; + sub_index->max_zone_bits = (available_bytes *BITS_PER_BYTE ) / zone_count; + sub_index->memory_size = (sub_index->delta_index.memory_size + +sizeof (struct volume_sub_index ) + + (params.list_count *sizeof (u64)) + + (zone_count *sizeof (struct volume_sub_index_zone ))); + +/* The following arrays are initialized to all zeros. */ + result =uds_allocate (params.list_count, u64,"first chapter to flush" , + &sub_index->flush_chapters); +if (result !=UDS_SUCCESS ) +return result; + + return uds_allocate(zone_count, struct volume_sub_index_zone, +"volume index zones" , &sub_index->zones); +} + +int uds_make_volume_index (const struct configuration *config,u64 volume_nonce, +struct volume_index **volume_index_ptr) +{ +struct split_config split; +unsigned int zone; +struct volume_index *volume_index; +int result; + + result = uds_allocate(1, struct volume_index, "volume index", &volume_index); +if (result !=UDS_SUCCESS ) +return result; + + volume_index->zone_count = config->zone_count; + +if (!uds_is_sparse_geometry (config->geometry)) { + result =initialize_volume_sub_index (config, volume_nonce,'m' , + &volume_index->vi_non_hook); +if (result !=UDS_SUCCESS ) { +uds_free_volume_index (volume_index); +return result; + } + + volume_index->memory_size = volume_index->vi_non_hook.memory_size; + *volume_index_ptr = volume_index; +return UDS_SUCCESS ; + } + + volume_index->sparse_sample_rate = config->sparse_sample_rate; + + result = uds_allocate(config->zone_count, struct volume_index_zone, +"volume index zones" , &volume_index->zones); +if (result !=UDS_SUCCESS ) { +uds_free_volume_index (volume_index); +return result; + } + +for (zone =0 ; zone < config->zone_count; zone++) { + result =uds_init_mutex (&volume_index->zones[zone].hook_mutex); +if (result !=UDS_SUCCESS ) { +uds_free_volume_index (volume_index); +return result; + } + } + +split_configuration (config, &split); + result =initialize_volume_sub_index (&split.non_hook_config, volume_nonce,'d' , + &volume_index->vi_non_hook); +if (result !=UDS_SUCCESS ) { +uds_free_volume_index (volume_index); +return uds_log_error_strerror (result, +"Error creating non hook volume index" ); + } + + result =initialize_volume_sub_index (&split.hook_config, volume_nonce,'s' , + &volume_index->vi_hook); +if (result !=UDS_SUCCESS ) { +uds_free_volume_index (volume_index); +return uds_log_error_strerror (result, +"Error creating hook volume index" ); + } + + volume_index->memory_size = + volume_index->vi_non_hook.memory_size + volume_index->vi_hook.memory_size; + *volume_index_ptr = volume_index; +return UDS_SUCCESS ; +}
drivers/md/dm-vdo/volume-index.h new file +192 -0
192 lines not on this page · raw message
Signature · 1 line
2.40.0
Matthew Sakai
maintainerPATCH v5 14/40 dm vdo: implement the chapter volume store
In reply to Matthew SakaiThe volume store structures manage the reading and writing of chapter pages. When a chapter is closed, it is packed into a read-only structure, split across several pages, and written to storage.
The volume store also contains a cache and specialized queues that sort and batch requests by the page they need, in order to minimize latency and I/O requests when records have to be read from storage. The cache and queues also coordinate with the volume index to ensure that the volume does not waste resources reading pages that are no longer valid.
--- drivers/md/dm-vdo/index-page-map.c | 175 +++ drivers/md/dm-vdo/index-page-map.h | 50 + drivers/md/dm-vdo/radix-sort.c | 332 ++++++ drivers/md/dm-vdo/radix-sort.h | 26 + drivers/md/dm-vdo/volume.c | 1711 ++++++++++++++++++++++++++++ drivers/md/dm-vdo/volume.h | 171 +++ 6 files changed, 2465 insertions(+) create mode 100644 drivers/md/dm-vdo/index-page-map.c create mode 100644 drivers/md/dm-vdo/index-page-map.h create mode 100644 drivers/md/dm-vdo/radix-sort.c create mode 100644 drivers/md/dm-vdo/radix-sort.h create mode 100644 drivers/md/dm-vdo/volume.c create mode 100644 drivers/md/dm-vdo/volume.h
drivers/md/dm-vdo/index-page-map.c new file +175 -0
@@ -0,0 +1,175 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* +* Copyright 2023 Red Hat +*/ + +#include "index-page-map.h" + +#include "errors.h" +#include "hash-utils.h" +#include "logger.h" +#include "memory-alloc.h" +#include "numeric.h" +#include "permassert.h" +#include "string-utils.h" +#include "uds-threads.h" +#include "uds.h" + +/* +* The index page map is conceptually a two-dimensional array indexed by chapter number and index +* page number within the chapter. Each entry contains the number of the last delta list on that +* index page. In order to save memory, the information for the last page in each chapter is not +* recorded, as it is known from the geometry. +*/ + +static const u8 PAGE_MAP_MAGIC [] ="ALBIPM02" ; + +enum { +PAGE_MAP_MAGIC_LENGTH =sizeof (PAGE_MAP_MAGIC ) -1 , +}; + +static inline u32 get_entry_count (const struct geometry *geometry) +{ +return geometry->chapters_per_volume * (geometry->index_pages_per_chapter -1 ); +} + +int uds_make_index_page_map (const struct geometry *geometry, +struct index_page_map **map_ptr) +{ +int result; +struct index_page_map *map; + + result = uds_allocate(1, struct index_page_map, "page map", &map); +if (result !=UDS_SUCCESS ) +return result; + + map->geometry = geometry; + map->entries_per_chapter = geometry->index_pages_per_chapter -1 ; + result =uds_allocate (get_entry_count (geometry), u16,"Index Page Map Entries" , + &map->entries); +if (result !=UDS_SUCCESS ) { +uds_free_index_page_map (map); +return result; + } + + *map_ptr = map; +return UDS_SUCCESS ; +} + +void uds_free_index_page_map (struct index_page_map *map) +{ +if (map !=NULL ) { +uds_free (map->entries); +uds_free (map); + } +} + +void uds_update_index_page_map (struct index_page_map *map,u64 virtual_chapter_number, +u32 chapter_number,u32 index_page_number, +u32 delta_list_number) +{ +size_t slot; + + map->last_update = virtual_chapter_number; +if (index_page_number == map->entries_per_chapter) +return ; + + slot = (chapter_number * map->entries_per_chapter) + index_page_number; + map->entries[slot] = delta_list_number; +} + +u32 uds_find_index_page_number (const struct index_page_map *map, +const struct uds_record_name *name,u32 chapter_number) +{ +u32 delta_list_number =uds_hash_to_chapter_delta_list (name, map->geometry); +u32 slot = chapter_number * map->entries_per_chapter; +u32 page; + +for (page =0 ; page < map->entries_per_chapter; page++) { +if (delta_list_number <= map->entries[slot + page]) +break ; + } + +return page; +} + +void uds_get_list_number_bounds (const struct index_page_map *map,u32 chapter_number, +u32 index_page_number,u32 *lowest_list, +u32 *highest_list) +{ +u32 slot = chapter_number * map->entries_per_chapter; + + *lowest_list = ((index_page_number ==0 ) ? +0 : + map->entries[slot + index_page_number -1 ] +1 ); + *highest_list = ((index_page_number < map->entries_per_chapter) ? + map->entries[slot + index_page_number] : + map->geometry->delta_lists_per_chapter -1 ); +} + +u64 uds_compute_index_page_map_save_size (const struct geometry *geometry) +{ +return PAGE_MAP_MAGIC_LENGTH +sizeof (u64) +sizeof (u16) *get_entry_count (geometry); +} + +int uds_write_index_page_map (struct index_page_map *map,struct buffered_writer *writer) +{ +int result; +u8 *buffer; +size_t offset =0 ; +u64 saved_size =uds_compute_index_page_map_save_size (map->geometry); +u32 i; + + result =uds_allocate (saved_size, u8,"page map data" , &buffer); +if (result !=UDS_SUCCESS ) +return result; + +memcpy (buffer,PAGE_MAP_MAGIC ,PAGE_MAP_MAGIC_LENGTH ); + offset +=PAGE_MAP_MAGIC_LENGTH ; +encode_u64_le (buffer, &offset, map->last_update); +for (i =0 ; i <get_entry_count (map->geometry); i++) +encode_u16_le (buffer, &offset, map->entries[i]); + + result =uds_write_to_buffered_writer (writer, buffer, offset); +uds_free (buffer); +if (result !=UDS_SUCCESS ) +return result; + +return uds_flush_buffered_writer (writer); +} + +int uds_read_index_page_map (struct index_page_map *map,struct buffered_reader *reader) +{ +int result; +u8 magic[PAGE_MAP_MAGIC_LENGTH ]; +u8 *buffer; +size_t offset =0 ; +u64 saved_size =uds_compute_index_page_map_save_size (map->geometry); +u32 i; + + result =uds_allocate (saved_size, u8,"page map data" , &buffer); +if (result !=UDS_SUCCESS ) +return result; + + result =uds_read_from_buffered_reader (reader, buffer, saved_size); +if (result !=UDS_SUCCESS ) { +uds_free (buffer); +return result; + } + +memcpy (&magic, buffer,PAGE_MAP_MAGIC_LENGTH ); + offset +=PAGE_MAP_MAGIC_LENGTH ; +if (memcmp (magic,PAGE_MAP_MAGIC ,PAGE_MAP_MAGIC_LENGTH ) !=0 ) { +uds_free (buffer); +return UDS_CORRUPT_DATA ; + } + +decode_u64_le (buffer, &offset, &map->last_update); +for (i =0 ; i <get_entry_count (map->geometry); i++) +decode_u16_le (buffer, &offset, &map->entries[i]); + +uds_free (buffer); +uds_log_debug ("read index page map, last update %llu" , + (unsigned long long ) map->last_update); +return UDS_SUCCESS ; +}
drivers/md/dm-vdo/index-page-map.h new file +50 -0
50 lines not on this page · raw message
drivers/md/dm-vdo/radix-sort.c new file +332 -0
332 lines not on this page · raw message
drivers/md/dm-vdo/radix-sort.h new file +26 -0
@@ -0,0 +1,26 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +/* +* Copyright 2023 Red Hat +*/ + +#ifndef UDS_RADIX_SORT_H +#define UDS_RADIX_SORT_H + +/* +* Radix sort is implemented using an American Flag sort, an unstable, in-place 8-bit radix +* exchange sort. This is adapted from the algorithm in the paper by Peter M. McIlroy, Keith +* Bostic, and M. Douglas McIlroy, "Engineering Radix Sort". +* +* http://www.usenix.org/publications/compsystems/1993/win_mcilroy.pdf +*/ + +struct radix_sorter ; + +int __must_check uds_make_radix_sorter (unsigned int count,struct radix_sorter **sorter); + +void uds_free_radix_sorter (struct radix_sorter *sorter); + +int __must_check uds_radix_sort (struct radix_sorter *sorter,const unsigned char *keys[], +unsigned int count,unsigned short length); + +#endif /* UDS_RADIX_SORT_H */
drivers/md/dm-vdo/volume.c new file +1711 -0
1,711 lines not on this page · raw message
drivers/md/dm-vdo/volume.h new file +171 -0
171 lines not on this page · raw message
Signature · 1 line
2.40.0
Matthew Sakai
maintainerPATCH v5 17/40 dm vdo: add administrative state and action manager
In reply to Matthew SakaiThis patch adds the admin_state structures which are used to track the states of individual vdo components for handling of operations like suspend and resume. It also adds the action manager which is used to schedule and manage cross-thread administrative and internal operations.
--- drivers/md/dm-vdo/action-manager.c | 388 ++++++++++++++++++++++ drivers/md/dm-vdo/action-manager.h | 110 +++++++ drivers/md/dm-vdo/admin-state.c | 506 +++++++++++++++++++++++++++++ drivers/md/dm-vdo/admin-state.h | 178 ++++++++++ 4 files changed, 1182 insertions(+) create mode 100644 drivers/md/dm-vdo/action-manager.c create mode 100644 drivers/md/dm-vdo/action-manager.h create mode 100644 drivers/md/dm-vdo/admin-state.c create mode 100644 drivers/md/dm-vdo/admin-state.h
drivers/md/dm-vdo/action-manager.c new file +388 -0
@@ -0,0 +1,388 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* +* Copyright 2023 Red Hat +*/ + +#include "action-manager.h" + +#include "memory-alloc.h" +#include "permassert.h" + +#include "admin-state.h" +#include "completion.h" +#include "status-codes.h" +#include "types.h" +#include "vdo.h" + +/** +* struct action - An action to be performed in each of a set of zones. +* @in_use: Whether this structure is in use. +* @operation: The admin operation associated with this action. +* @preamble: The method to run on the initiator thread before the action is applied to each zone. +* @zone_action: The action to be performed in each zone. +* @conclusion: The method to run on the initiator thread after the action is applied to each zone. +* @parent: The object to notify when the action is complete. +* @context: The action specific context. +* @next: The action to perform after this one. +*/ +struct action { +bool in_use; +const struct admin_state_code *operation; +vdo_action_preamble_fn preamble; +vdo_zone_action_fn zone_action; +vdo_action_conclusion_fn conclusion; +struct vdo_completion *parent; +void *context; +struct action *next; +}; + +/** +* struct action_manager - Definition of an action manager. +* @completion: The completion for performing actions. +* @state: The state of this action manager. +* @actions: The two action slots. +* @current_action: The current action slot. +* @zones: The number of zones in which an action is to be applied. +* @Scheduler: A function to schedule a default next action. +* @get_zone_thread_id: A function to get the id of the thread on which to apply an action to a +* zone. +* @initiator_thread_id: The ID of the thread on which actions may be initiated. +* @context: Opaque data associated with this action manager. +* @acting_zone: The zone currently being acted upon. +*/ +struct action_manager { +struct vdo_completion completion; +struct admin_state state; +struct action actions[2 ]; +struct action *current_action; +zone_count_t zones; +vdo_action_scheduler_fn scheduler; +vdo_zone_thread_getter_fn get_zone_thread_id; +thread_id_t initiator_thread_id; +void *context; +zone_count_t acting_zone; +}; + +static inline struct action_manager *as_action_manager (struct vdo_completion *completion) +{ +vdo_assert_completion_type (completion,VDO_ACTION_COMPLETION ); + return container_of(completion, struct action_manager, completion); +} + +/* Implements vdo_action_scheduler_fn. */ +static bool no_default_action (void *context__always_unused ) +{ +return false; +} + +/* Implements vdo_action_preamble_fn. */ +static void no_preamble (void *context__always_unused ,struct vdo_completion *completion) +{ +vdo_finish_completion (completion); +} + +/* Implements vdo_action_conclusion_fn. */ +static int no_conclusion (void *context__always_unused ) +{ +return VDO_SUCCESS ; +} + +/** +* vdo_make_action_manager() - Make an action manager. +* @zones: The number of zones to which actions will be applied. +* @get_zone_thread_id: A function to get the thread id associated with a zone. +* @initiator_thread_id: The thread on which actions may initiated. +* @context: The object which holds the per-zone context for the action. +* @scheduler: A function to schedule a next action after an action concludes if there is no +* pending action (may be NULL). +* @vdo: The vdo used to initialize completions. +* @manager_ptr: A pointer to hold the new action manager. +* +* Return: VDO_SUCCESS or an error code. +*/ +int vdo_make_action_manager (zone_count_t zones, +vdo_zone_thread_getter_fn get_zone_thread_id, +thread_id_t initiator_thread_id,void *context, +vdo_action_scheduler_fn scheduler,struct vdo *vdo, +struct action_manager **manager_ptr) +{ +struct action_manager *manager; + int result = uds_allocate(1, struct action_manager, __func__, &manager); + +if (result !=VDO_SUCCESS ) +return result; + + *manager = (struct action_manager ) { + .zones = zones, + .scheduler = + ((scheduler ==NULL ) ? no_default_action : scheduler), + .get_zone_thread_id = get_zone_thread_id, + .initiator_thread_id = initiator_thread_id, + .context = context, + }; + + manager->actions[0 ].next = &manager->actions[1 ]; + manager->current_action = manager->actions[1 ].next = + &manager->actions[0 ]; +vdo_set_admin_state_code (&manager->state,VDO_ADMIN_STATE_NORMAL_OPERATION ); +vdo_initialize_completion (&manager->completion, vdo,VDO_ACTION_COMPLETION ); + *manager_ptr = manager; +return VDO_SUCCESS ; +} + +const struct admin_state_code *vdo_get_current_manager_operation (struct action_manager *manager) +{ +return vdo_get_admin_state_code (&manager->state); +} + +void *vdo_get_current_action_context (struct action_manager *manager) +{ +return manager->current_action->in_use ? manager->current_action->context :NULL ; +} + +static void finish_action_callback (struct vdo_completion *completion); +static void apply_to_zone (struct vdo_completion *completion); + +static thread_id_t get_acting_zone_thread_id (struct action_manager *manager) +{ +return manager->get_zone_thread_id (manager->context, manager->acting_zone); +} + +static void preserve_error (struct vdo_completion *completion) +{ +if (completion->parent !=NULL ) +vdo_set_completion_result (completion->parent, completion->result); + +vdo_reset_completion (completion); +vdo_run_completion (completion); +} + +static void prepare_for_next_zone (struct action_manager *manager) +{ +vdo_prepare_completion_for_requeue (&manager->completion, apply_to_zone, + preserve_error, +get_acting_zone_thread_id (manager), + manager->current_action->parent); +} + +static void prepare_for_conclusion (struct action_manager *manager) +{ +vdo_prepare_completion_for_requeue (&manager->completion, finish_action_callback, + preserve_error, manager->initiator_thread_id, + manager->current_action->parent); +} + +static void apply_to_zone (struct vdo_completion *completion) +{ +zone_count_t zone; +struct action_manager *manager =as_action_manager (completion); + +ASSERT_LOG_ONLY ((vdo_get_callback_thread_id () ==get_acting_zone_thread_id (manager)), +"%s() called on acting zones's thread" , __func__); + + zone = manager->acting_zone++; +if (manager->acting_zone == manager->zones) { +/* +* We are about to apply to the last zone. Once that is finished, we're done, so go +* back to the initiator thread and finish up. +*/ +prepare_for_conclusion (manager); + }else { +/* Prepare to come back on the next zone */ +prepare_for_next_zone (manager); + } + + manager->current_action->zone_action (manager->context, zone, completion); +} + +static void handle_preamble_error (struct vdo_completion *completion) +{ +/* Skip the zone actions since the preamble failed. */ + completion->callback = finish_action_callback; +preserve_error (completion); +} + +static void launch_current_action (struct action_manager *manager) +{ +struct action *action = manager->current_action; +int result =vdo_start_operation (&manager->state, action->operation); + +if (result !=VDO_SUCCESS ) { +if (action->parent !=NULL ) +vdo_set_completion_result (action->parent, result); + +/* We aren't going to run the preamble, so don't run the conclusion */ + action->conclusion = no_conclusion; +finish_action_callback (&manager->completion); +return ; + } + +if (action->zone_action ==NULL ) { +prepare_for_conclusion (manager); + }else { + manager->acting_zone =0 ; +vdo_prepare_completion_for_requeue (&manager->completion, apply_to_zone, + handle_preamble_error, +get_acting_zone_thread_id (manager), + manager->current_action->parent); + } + + action->preamble (manager->context, &manager->completion); +} + +/** +* vdo_schedule_default_action() - Attempt to schedule the default action. +* @manager: The action manager. +* +* If the manager is not operating normally, the action will not be scheduled. +* +* Return: true if an action was scheduled. +*/ +bool vdo_schedule_default_action (struct action_manager *manager) +{ +/* Don't schedule a default action if we are operating or not in normal operation. */ +const struct admin_state_code *code =vdo_get_current_manager_operation (manager); + +return ((code ==VDO_ADMIN_STATE_NORMAL_OPERATION ) && + manager->scheduler (manager->context)); +} + +static void finish_action_callback (struct vdo_completion *completion) +{ +bool has_next_action; +int result; +struct action_manager *manager =as_action_manager (completion); +struct action action = *(manager->current_action); + + manager->current_action->in_use = false; + manager->current_action = manager->current_action->next; + +/* +* We need to check this now to avoid use-after-free issues if running the conclusion or +* notifying the parent results in the manager being freed. +*/ + has_next_action = + (manager->current_action->in_use ||vdo_schedule_default_action (manager)); + result = action.conclusion (manager->context); +vdo_finish_operation (&manager->state,VDO_SUCCESS ); +if (action.parent !=NULL ) +vdo_continue_completion (action.parent, result); + +if (has_next_action) +launch_current_action (manager); +} + +/** +* vdo_schedule_action() - Schedule an action to be applied to all zones. +* @manager: The action manager to schedule the action on. +* @preamble: A method to be invoked on the initiator thread once this action is started but before +* applying to each zone; may be NULL. +* @action: The action to apply to each zone; may be NULL. +* @conclusion: A method to be invoked back on the initiator thread once the action has been +* applied to all zones; may be NULL. +* @parent: The object to notify once the action is complete or if the action can not be scheduled; +* may be NULL. +* +* The action will be launched immediately if there is no current action, or as soon as the current +* action completes. If there is already a pending action, this action will not be scheduled, and, +* if it has a parent, that parent will be notified. At least one of the preamble, action, or +* conclusion must not be NULL. +* +* Return: true if the action was scheduled. +*/ +bool vdo_schedule_action (struct action_manager *manager,vdo_action_preamble_fn preamble, +vdo_zone_action_fn action,vdo_action_conclusion_fn conclusion, +struct vdo_completion *parent) +{ +return vdo_schedule_operation (manager,VDO_ADMIN_STATE_OPERATING , preamble, + action, conclusion, parent); +} + +/** +* vdo_schedule_operation() - Schedule an operation to be applied to all zones. +* @manager: The action manager to schedule the action on. +* @operation: The operation this action will perform +* @preamble: A method to be invoked on the initiator thread once this action is started but before +* applying to each zone; may be NULL. +* @action: The action to apply to each zone; may be NULL. +* @conclusion: A method to be invoked back on the initiator thread once the action has been +* applied to all zones; may be NULL. +* @parent: The object to notify once the action is complete or if the action can not be scheduled; +* may be NULL. +* +* The operation's action will be launched immediately if there is no current action, or as soon as +* the current action completes. If there is already a pending action, this operation will not be +* scheduled, and, if it has a parent, that parent will be notified. At least one of the preamble, +* action, or conclusion must not be NULL. +* +* Return: true if the action was scheduled. +*/ +bool vdo_schedule_operation (struct action_manager *manager, +const struct admin_state_code *operation, +vdo_action_preamble_fn preamble,vdo_zone_action_fn action, +vdo_action_conclusion_fn conclusion, +struct vdo_completion *parent) +{ +return vdo_schedule_operation_with_context (manager, operation, preamble, action, + conclusion,NULL , parent); +} + +/** +* vdo_schedule_operation_with_context() - Schedule an operation on all zones. +* @manager: The action manager to schedule the action on. +* @operation: The operation this action will perform. +* @preamble: A method to be invoked on the initiator thread once this action is started but before +* applying to each zone; may be NULL. +* @action: The action to apply to each zone; may be NULL. +* @conclusion: A method to be invoked back on the initiator thread once the action has been +* applied to all zones; may be NULL. +* @context: An action-specific context which may be retrieved via +* vdo_get_current_action_context(); may be NULL. +* @parent: The object to notify once the action is complete or if the action can not be scheduled; +* may be NULL. +* +* The operation's action will be launched immediately if there is no current action, or as soon as +* the current action completes. If there is already a pending action, this operation will not be +* scheduled, and, if it has a parent, that parent will be notified. At least one of the preamble, +* action, or conclusion must not be NULL. +* +* Return: true if the action was scheduled +*/ +bool vdo_schedule_operation_with_context (struct action_manager *manager, +const struct admin_state_code *operation, +vdo_action_preamble_fn preamble, +vdo_zone_action_fn action, +vdo_action_conclusion_fn conclusion, +void *context,struct vdo_completion *parent) +{ +struct action *current_action; + +ASSERT_LOG_ONLY ((vdo_get_callback_thread_id () == manager->initiator_thread_id), +"action initiated from correct thread" ); +if (!manager->current_action->in_use) { + current_action = manager->current_action; + }else if (!manager->current_action->next->in_use) { + current_action = manager->current_action->next; + }else { +if (parent !=NULL ) +vdo_continue_completion (parent,VDO_COMPONENT_BUSY ); + +return false; + } + + *current_action = (struct action ) { + .in_use = true, + .operation = operation, + .preamble = (preamble ==NULL ) ? no_preamble : preamble, + .zone_action = action, + .conclusion = (conclusion ==NULL ) ? no_conclusion : conclusion, + .context = context, + .parent = parent, + .next = current_action->next, + }; + +if (current_action == manager->current_action) +launch_current_action (manager); + +return true; +}
drivers/md/dm-vdo/action-manager.h new file +110 -0
110 lines not on this page · raw message
drivers/md/dm-vdo/admin-state.c new file +506 -0
506 lines not on this page · raw message
drivers/md/dm-vdo/admin-state.h new file +178 -0
178 lines not on this page · raw message
Signature · 1 line
2.40.0
Matthew Sakai
maintainerPATCH v5 8/40 dm vdo: add basic hash map data structures
In reply to Matthew SakaiThis patch adds two hash maps, one keyed by integers, the other by pointers, and also a priority heap. The integer map is used for locking of logical and physical addresses. The pointer map is used for managing concurrent writes of the same data, ensuring that those writes are deduplicated. The priority heap is used to minimize the search time for free blocks.
--- drivers/md/dm-vdo/int-map.c | 718 +++++++++++++++++++++++++++++ drivers/md/dm-vdo/int-map.h | 40 ++ drivers/md/dm-vdo/pointer-map.c | 696 ++++++++++++++++++++++++++++ drivers/md/dm-vdo/pointer-map.h | 81 ++++ drivers/md/dm-vdo/priority-table.c | 226 +++++++++ drivers/md/dm-vdo/priority-table.h | 47 ++ 6 files changed, 1808 insertions(+) create mode 100644 drivers/md/dm-vdo/int-map.c create mode 100644 drivers/md/dm-vdo/int-map.h create mode 100644 drivers/md/dm-vdo/pointer-map.c create mode 100644 drivers/md/dm-vdo/pointer-map.h create mode 100644 drivers/md/dm-vdo/priority-table.c create mode 100644 drivers/md/dm-vdo/priority-table.h
drivers/md/dm-vdo/int-map.c new file +718 -0
@@ -0,0 +1,718 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* +* Copyright 2023 Red Hat +*/ + +/** +* DOC: +* +* Hash table implementation of a map from integers to pointers, implemented using the Hopscotch +* Hashing algorithm by Herlihy, Shavit, and Tzafrir (see +* http://en.wikipedia.org/wiki/Hopscotch_hashing). This implementation does not contain any of the +* locking/concurrency features of the algorithm, just the collision resolution scheme. +* +* Hopscotch Hashing is based on hashing with open addressing and linear probing. All the entries +* are stored in a fixed array of buckets, with no dynamic allocation for collisions. Unlike linear +* probing, all the entries that hash to a given bucket are stored within a fixed neighborhood +* starting at that bucket. Chaining is effectively represented as a bit vector relative to each +* bucket instead of as pointers or explicit offsets. +* +* When an empty bucket cannot be found within a given neighborhood, subsequent neighborhoods are +* searched, and one or more entries will "hop" into those neighborhoods. When this process works, +* an empty bucket will move into the desired neighborhood, allowing the entry to be added. When +* that process fails (typically when the buckets are around 90% full), the table must be resized +* and the all entries rehashed and added to the expanded table. +* +* Unlike linear probing, the number of buckets that must be searched in the worst case has a fixed +* upper bound (the size of the neighborhood). Those entries occupy a small number of memory cache +* lines, leading to improved use of the cache (fewer misses on both successful and unsuccessful +* searches). Hopscotch hashing outperforms linear probing at much higher load factors, so even +* with the increased memory burden for maintaining the hop vectors, less memory is needed to +* achieve that performance. Hopscotch is also immune to "contamination" from deleting entries +* since entries are genuinely removed instead of being replaced by a placeholder. +* +* The published description of the algorithm used a bit vector, but the paper alludes to an offset +* scheme which is used by this implementation. Since the entries in the neighborhood are within N +* entries of the hash bucket at the start of the neighborhood, a pair of small offset fields each +* log2(N) bits wide is all that's needed to maintain the hops as a linked list. In order to encode +* "no next hop" (i.e. NULL) as the natural initial value of zero, the offsets are biased by one +* (i.e. 0 => NULL, 1 => offset=0, 2 => offset=1, etc.) We can represent neighborhoods of up to 255 +* entries with just 8+8=16 bits per entry. The hop list is sorted by hop offset so the first entry +* in the list is always the bucket closest to the start of the neighborhood. +* +* While individual accesses tend to be very fast, the table resize operations are very, very +* expensive. If an upper bound on the latency of adding an entry to the table is needed, we either +* need to ensure the table is pre-sized to be large enough so no resize is ever needed, or we'll +* need to develop an approach to incrementally resize the table. +*/ + +#include "int-map.h" + +#include <linux/minmax.h> + +#include "errors.h" +#include "logger.h" +#include "memory-alloc.h" +#include "numeric.h" +#include "permassert.h" + +enum { +DEFAULT_CAPACITY =16 ,/* the number of neighborhoods in a new table */ +NEIGHBORHOOD =255 ,/* the number of buckets in each neighborhood */ +MAX_PROBES =1024 ,/* limit on the number of probes for a free bucket */ +NULL_HOP_OFFSET =0 ,/* the hop offset value terminating the hop list */ +DEFAULT_LOAD =75 /* a compromise between memory use and performance */ +}; + +/** +* struct bucket - hash bucket +* +* Buckets are packed together to reduce memory usage and improve cache efficiency. It would be +* tempting to encode the hop offsets separately and maintain alignment of key/value pairs, but +* it's crucial to keep the hop fields near the buckets that they use them so they'll tend to share +* cache lines. +*/ +struct __packed bucket { +/** +* @first_hop: The biased offset of the first entry in the hop list of the neighborhood +* that hashes to this bucket. +*/ +u8 first_hop; +/** @next_hop: The biased offset of the next bucket in the hop list. */ +u8 next_hop; +/** @key: The key stored in this bucket. */ +u64 key; +/** @value: The value stored in this bucket (NULL if empty). */ +void *value; +}; + +/** +* struct int_map - The concrete definition of the opaque int_map type. +* +* To avoid having to wrap the neighborhoods of the last entries back around to the start of the +* bucket array, we allocate a few more buckets at the end of the array instead, which is why +* capacity and bucket_count are different. +*/ +struct int_map { +/** @size: The number of entries stored in the map. */ +size_t size; +/** @capacity: The number of neighborhoods in the map. */ +size_t capacity; +/* @bucket_count: The number of buckets in the bucket array. */ +size_t bucket_count; +/** @buckets: The array of hash buckets. */ +struct bucket *buckets; +}; + +/** +* mix() - The Google CityHash 16-byte hash mixing function. +* @input1: The first input value. +* @input2: The second input value. +* +* Return: A hash of the two inputs. +*/ +static u64 mix (u64 input1,u64 input2) +{ +static const u64 CITY_MULTIPLIER =0x9ddfea08eb382d69ULL ; +u64 hash = (input1 ^ input2); + + hash *=CITY_MULTIPLIER ; + hash ^= (hash >>47 ); + hash ^= input2; + hash *=CITY_MULTIPLIER ; + hash ^= (hash >>47 ); + hash *=CITY_MULTIPLIER ; +return hash; +} + +/** +* hash_key() - Calculate a 64-bit non-cryptographic hash value for the provided 64-bit integer +* key. +* @key: The mapping key. +* +* The implementation is based on Google's CityHash, only handling the specific case of an 8-byte +* input. +* +* Return: The hash of the mapping key. +*/ +static u64 hash_key (u64 key) +{ +/* +* Aliasing restrictions forbid us from casting pointer types, so use a union to convert a +* single u64 to two u32 values. +*/ +union { +u64 u64; +u32 u32[2 ]; + } pun = {.u64 = key}; + +return mix (sizeof (key) + (((u64 ) pun.u32[0 ]) <<3 ), pun.u32[1 ]); +} + +/** +* allocate_buckets() - Initialize an int_map. +* @map: The map to initialize. +* @capacity: The initial capacity of the map. +* +* Return: UDS_SUCCESS or an error code. +*/ +static int allocate_buckets (struct int_map *map,size_t capacity) +{ + map->size =0 ; + map->capacity = capacity; + +/* +* Allocate NEIGHBORHOOD - 1 extra buckets so the last bucket can have a full neighborhood +* without have to wrap back around to element zero. +*/ + map->bucket_count = capacity + (NEIGHBORHOOD -1 ); + return uds_allocate(map->bucket_count, struct bucket, +"struct int_map buckets" , &map->buckets); +} + +/** +* vdo_make_int_map() - Allocate and initialize an int_map. +* @initial_capacity: The number of entries the map should initially be capable of holding (zero +* tells the map to use its own small default). +* @initial_load: The load factor of the map, expressed as an integer percentage (typically in the +* range 50 to 90, with zero telling the map to use its own default). +* @map_ptr: Output, a pointer to hold the new int_map. +* +* Return: UDS_SUCCESS or an error code. +*/ +int vdo_make_int_map (size_t initial_capacity,unsigned int initial_load,struct int_map **map_ptr) +{ +struct int_map *map; +int result; +size_t capacity; + +/* Use the default initial load if the caller did not specify one. */ +if (initial_load ==0 ) + initial_load =DEFAULT_LOAD ; +if (initial_load >100 ) +return UDS_INVALID_ARGUMENT ; + + result = uds_allocate(1, struct int_map, "struct int_map", &map); +if (result !=UDS_SUCCESS ) +return result; + +/* Use the default capacity if the caller did not specify one. */ + capacity = (initial_capacity >0 ) ? initial_capacity :DEFAULT_CAPACITY ; + +/* +* Scale up the capacity by the specified initial load factor. (i.e to hold 1000 entries at +* 80% load we need a capacity of 1250) +*/ + capacity = capacity *100 / initial_load; + + result =allocate_buckets (map, capacity); +if (result !=UDS_SUCCESS ) { +vdo_free_int_map (uds_forget (map)); +return result; + } + + *map_ptr = map; +return UDS_SUCCESS ; +} + +/** +* vdo_free_int_map() - Free an int_map. +* @map: The int_map to free. +* +* NOTE: The map does not own the pointer values stored in the map and they are not freed by this +* call. +*/ +void vdo_free_int_map (struct int_map *map) +{ +if (map ==NULL ) +return ; + +uds_free (uds_forget (map->buckets)); +uds_free (uds_forget (map)); +} + +/** +* vdo_int_map_size() - Get the number of entries stored in an int_map. +* @map: The int_map to query. +* +* Return: The number of entries in the map. +*/ +size_t vdo_int_map_size (const struct int_map *map) +{ +return map->size; +} + +/** +* dereference_hop() - Convert a biased hop offset within a neighborhood to a pointer to the bucket +* it references. +* @neighborhood: The first bucket in the neighborhood. +* @hop_offset: The biased hop offset to the desired bucket. +* +* Return: NULL if hop_offset is zero, otherwise a pointer to the bucket in the neighborhood at +* hop_offset - 1. +*/ +static struct bucket *dereference_hop (struct bucket *neighborhood,unsigned int hop_offset) +{ +BUILD_BUG_ON (NULL_HOP_OFFSET !=0 ); +if (hop_offset ==NULL_HOP_OFFSET ) +return NULL ; + +return &neighborhood[hop_offset -1 ]; +} + +/** +* insert_in_hop_list() - Add a bucket into the hop list for the neighborhood. +* @neighborhood: The first bucket in the neighborhood. +* @new_bucket: The bucket to add to the hop list. +* +* The bucket is inserted it into the list so the hop list remains sorted by hop offset. +*/ +static void insert_in_hop_list (struct bucket *neighborhood,struct bucket *new_bucket) +{ +/* Zero indicates a NULL hop offset, so bias the hop offset by one. */ +int hop_offset =1 + (new_bucket - neighborhood); + +/* Handle the special case of adding a bucket at the start of the list. */ +int next_hop = neighborhood->first_hop; + +if ((next_hop ==NULL_HOP_OFFSET ) || (next_hop > hop_offset)) { + new_bucket->next_hop = next_hop; + neighborhood->first_hop = hop_offset; +return ; + } + +/* Search the hop list for the insertion point that maintains the sort order. */ +for (;;) { +struct bucket *bucket =dereference_hop (neighborhood, next_hop); + + next_hop = bucket->next_hop; + +if ((next_hop ==NULL_HOP_OFFSET ) || (next_hop > hop_offset)) { + new_bucket->next_hop = next_hop; + bucket->next_hop = hop_offset; +return ; + } + } +} + +/** +* select_bucket() - Select and return the hash bucket for a given search key. +* @map: The map to search. +* @key: The mapping key. +*/ +static struct bucket *select_bucket (const struct int_map *map,u64 key) +{ +/* +* Calculate a good hash value for the provided key. We want exactly 32 bits, so mask the +* result. +*/ +u64 hash =hash_key (key) &0xFFFFFFFF ; + +/* +* Scale the 32-bit hash to a bucket index by treating it as a binary fraction and +* multiplying that by the capacity. If the hash is uniformly distributed over [0 .. +* 2^32-1], then (hash * capacity / 2^32) should be uniformly distributed over [0 .. +* capacity-1]. The multiply and shift is much faster than a divide (modulus) on X86 CPUs. +*/ +return &map->buckets[(hash * map->capacity) >>32 ]; +} + +/** +* search_hop_list() - Search the hop list associated with given hash bucket for a given search +* key. +* @map: The map being searched. +* @bucket: The map bucket to search for the key. +* @key: The mapping key. +* @previous_ptr: Output. if not NULL, a pointer in which to store the bucket in the list preceding +* the one that had the matching key +* +* If the key is found, returns a pointer to the entry (bucket or collision), otherwise returns +* NULL. +* +* Return: An entry that matches the key, or NULL if not found. +*/ +static struct bucket *search_hop_list (struct int_map *map__always_unused , +struct bucket *bucket, +u64 key, +struct bucket **previous_ptr) +{ +struct bucket *previous =NULL ; +unsigned int next_hop = bucket->first_hop; + +while (next_hop !=NULL_HOP_OFFSET ) { +/* +* Check the neighboring bucket indexed by the offset for the +* desired key. +*/ +struct bucket *entry =dereference_hop (bucket, next_hop); + +if ((key == entry->key) && (entry->value !=NULL )) { +if (previous_ptr !=NULL ) + *previous_ptr = previous; +return entry; + } + next_hop = entry->next_hop; + previous = entry; + } + +return NULL ; +} + +/** +* vdo_int_map_get() - Retrieve the value associated with a given key from the int_map. +* @map: The int_map to query. +* @key: The key to look up. +* +* Return: The value associated with the given key, or NULL if the key is not mapped to any value. +*/ +void *vdo_int_map_get (struct int_map *map,u64 key) +{ +struct bucket *match =search_hop_list (map,select_bucket (map, key), key,NULL ); + +return ((match !=NULL ) ? match->value :NULL ); +} + +/** +* resize_buckets() - Increase the number of hash buckets. +* @map: The map to resize. +* +* Resizes and rehashes all the existing entries, storing them in the new buckets. +* +* Return: UDS_SUCCESS or an error code. +*/ +static int resize_buckets (struct int_map *map) +{ +int result; +size_t i; + +/* Copy the top-level map data to the stack. */ +struct int_map old_map = *map; + +/* Re-initialize the map to be empty and 50% larger. */ +size_t new_capacity = map->capacity /2 *3 ; + +uds_log_info ("%s: attempting resize from %zu to %zu, current size=%zu" , + __func__, map->capacity, new_capacity, map->size); + result =allocate_buckets (map, new_capacity); +if (result !=UDS_SUCCESS ) { + *map = old_map; +return result; + } + +/* Populate the new hash table from the entries in the old bucket array. */ +for (i =0 ; i < old_map.bucket_count; i++) { +struct bucket *entry = &old_map.buckets[i]; + +if (entry->value ==NULL ) +continue ; + + result =vdo_int_map_put (map, entry->key, entry->value, true,NULL ); +if (result !=UDS_SUCCESS ) { +/* Destroy the new partial map and restore the map from the stack. */ +uds_free (uds_forget (map->buckets)); + *map = old_map; +return result; + } + } + +/* Destroy the old bucket array. */ +uds_free (uds_forget (old_map.buckets)); +return UDS_SUCCESS ; +} + +/** +* find_empty_bucket() - Probe the bucket array starting at the given bucket for the next empty +* bucket, returning a pointer to it. +* @map: The map containing the buckets to search. +* @bucket: The bucket at which to start probing. +* @max_probes: The maximum number of buckets to search. +* +* NULL will be returned if the search reaches the end of the bucket array or if the number of +* linear probes exceeds a specified limit. +* +* Return: The next empty bucket, or NULL if the search failed. +*/ +static struct bucket * +find_empty_bucket (struct int_map *map,struct bucket *bucket,unsigned int max_probes) +{ +/* +* Limit the search to either the nearer of the end of the bucket array or a fixed distance +* beyond the initial bucket. +*/ +ptrdiff_t remaining = &map->buckets[map->bucket_count] - bucket; +struct bucket *sentinel = &bucket[min_t (ptrdiff_t, remaining, max_probes)]; +struct bucket *entry; + +for (entry = bucket; entry < sentinel; entry++) { +if (entry->value ==NULL ) +return entry; + } + +return NULL ; +} + +/** +* move_empty_bucket() - Move an empty bucket closer to the start of the bucket array. +* @map: The map containing the bucket. +* @hole: The empty bucket to fill with an entry that precedes it in one of its enclosing +* neighborhoods. +* +* This searches the neighborhoods that contain the empty bucket for a non-empty bucket closer to +* the start of the array. If such a bucket is found, this swaps the two buckets by moving the +* entry to the empty bucket. +* +* Return: The bucket that was vacated by moving its entry to the provided hole, or NULL if no +* entry could be moved. +*/ +static struct bucket *move_empty_bucket (struct int_map *map__always_unused ,struct bucket *hole) +{ +/* +* Examine every neighborhood that the empty bucket is part of, starting with the one in +* which it is the last bucket. No boundary check is needed for the negative array +* arithmetic since this function is only called when hole is at least NEIGHBORHOOD cells +* deeper into the array than a valid bucket. +*/ +struct bucket *bucket; + +for (bucket = &hole[1 -NEIGHBORHOOD ]; bucket < hole; bucket++) { +/* +* Find the entry that is nearest to the bucket, which means it will be nearest to +* the hash bucket whose neighborhood is full. +*/ +struct bucket *new_hole =dereference_hop (bucket, bucket->first_hop); + +if (new_hole ==NULL ) { +/* +* There are no buckets in this neighborhood that are in use by this one +* (they must all be owned by overlapping neighborhoods). +*/ +continue ; + } + +/* +* Skip this bucket if its first entry is actually further away than the hole that +* we're already trying to fill. +*/ +if (hole < new_hole) +continue ; + +/* +* We've found an entry in this neighborhood that we can "hop" further away, moving +* the hole closer to the hash bucket, if not all the way into its neighborhood. +*/ + +/* +* The entry that will be the new hole is the first bucket in the list, so setting +* first_hop is all that's needed remove it from the list. +*/ + bucket->first_hop = new_hole->next_hop; + new_hole->next_hop =NULL_HOP_OFFSET ; + +/* Move the entry into the original hole. */ + hole->key = new_hole->key; + hole->value = new_hole->value; + new_hole->value =NULL ; + +/* Insert the filled hole into the hop list for the neighborhood. */ +insert_in_hop_list (bucket, hole); +return new_hole; + } + +/* We couldn't find an entry to relocate to the hole. */ +return NULL ; +} + +/** +* update_mapping() - Find and update any existing mapping for a given key, returning the value +* associated with the key in the provided pointer. +* @map: The int_map to attempt to modify. +* @neighborhood: The first bucket in the neighborhood that would contain the search key +* @key: The key with which to associate the new value. +* @new_value: The value to be associated with the key. +* @update: Whether to overwrite an existing value. +* @old_value_ptr: a pointer in which to store the old value (unmodified if no mapping was found) +* +* Return: true if the map contains a mapping for the key, false if it does not. +*/ +static bool update_mapping (struct int_map *map, +struct bucket *neighborhood, +u64 key, +void *new_value, +bool update, +void **old_value_ptr) +{ +struct bucket *bucket =search_hop_list (map, neighborhood, key,NULL ); + +if (bucket ==NULL ) { +/* There is no bucket containing the key in the neighborhood. */ +return false; + } + +/* +* Return the value of the current mapping (if desired) and update the mapping with the new +* value (if desired). +*/ +if (old_value_ptr !=NULL ) + *old_value_ptr = bucket->value; +if (update) + bucket->value = new_value; +return true; +} + +/** +* find_or_make_vacancy() - Find an empty bucket. +* @map: The int_map to search or modify. +* @neighborhood: The first bucket in the neighborhood in which an empty bucket is needed for a new +* mapping. +* +* Find an empty bucket in a specified neighborhood for a new mapping or attempt to re-arrange +* mappings so there is such a bucket. This operation may fail (returning NULL) if an empty bucket +* is not available or could not be relocated to the neighborhood. +* +* Return: a pointer to an empty bucket in the desired neighborhood, or NULL if a vacancy could not +* be found or arranged. +*/ +static struct bucket *find_or_make_vacancy (struct int_map *map,struct bucket *neighborhood) +{ +/* Probe within and beyond the neighborhood for the first empty bucket. */ +struct bucket *hole =find_empty_bucket (map, neighborhood,MAX_PROBES ); + +/* +* Keep trying until the empty bucket is in the bucket's neighborhood or we are unable to +* move it any closer by swapping it with a filled bucket. +*/ +while (hole !=NULL ) { +int distance = hole - neighborhood; + +if (distance <NEIGHBORHOOD ) { +/* +* We've found or relocated an empty bucket close enough to the initial +* hash bucket to be referenced by its hop vector. +*/ +return hole; + } + +/* +* The nearest empty bucket isn't within the neighborhood that must contain the new +* entry, so try to swap it with bucket that is closer. +*/ + hole =move_empty_bucket (map, hole); + } + +return NULL ; +} + +/** +* vdo_int_map_put() - Try to associate a value with an integer. +* @map: The int_map to attempt to modify. +* @key: The key with which to associate the new value. +* @new_value: The value to be associated with the key. +* @update: Whether to overwrite an existing value. +* @old_value_ptr: A pointer in which to store either the old value (if the key was already mapped) +* or NULL if the map did not contain the key; NULL may be provided if the caller +* does not need to know the old value +* +* Try to associate a value (a pointer) with an integer in an int_map. If the map already contains +* a mapping for the provided key, the old value is only replaced with the specified value if +* update is true. In either case the old value is returned. If the map does not already contain a +* value for the specified key, the new value is added regardless of the value of update. +* +* Return: UDS_SUCCESS or an error code. +*/ +int vdo_int_map_put (struct int_map *map,u64 key,void *new_value,bool update,void **old_value_ptr) +{ +struct bucket *neighborhood, *bucket; + +if (new_value ==NULL ) +return UDS_INVALID_ARGUMENT ; + +/* +* Select the bucket at the start of the neighborhood that must contain any entry for the +* provided key. +*/ + neighborhood =select_bucket (map, key); + +/* +* Check whether the neighborhood already contains an entry for the key, in which case we +* optionally update it, returning the old value. +*/ +if (update_mapping (map, neighborhood, key, new_value, update, old_value_ptr)) +return UDS_SUCCESS ; + +/* +* Find an empty bucket in the desired neighborhood for the new entry or re-arrange entries +* in the map so there is such a bucket. This operation will usually succeed; the loop body +* will only be executed on the rare occasions that we have to resize the map. +*/ +while ((bucket =find_or_make_vacancy (map, neighborhood)) ==NULL ) { +int result; + +/* +* There is no empty bucket in which to put the new entry in the current map, so +* we're forced to allocate a new bucket array with a larger capacity, re-hash all +* the entries into those buckets, and try again (a very expensive operation for +* large maps). +*/ + result =resize_buckets (map); +if (result !=UDS_SUCCESS ) +return result; + +/* +* Resizing the map invalidates all pointers to buckets, so recalculate the +* neighborhood pointer. +*/ + neighborhood =select_bucket (map, key); + } + +/* Put the new entry in the empty bucket, adding it to the neighborhood. */ + bucket->key = key; + bucket->value = new_value; +insert_in_hop_list (neighborhood, bucket); + map->size +=1 ; + +/* There was no existing entry, so there was no old value to be returned. */ +if (old_value_ptr !=NULL ) + *old_value_ptr =NULL ; +return UDS_SUCCESS ; +} + +/** +* vdo_int_map_remove() - Remove the mapping for a given key from the int_map. +* @map: The int_map from which to remove the mapping. +* @key: The key whose mapping is to be removed. +* +* Return: the value that was associated with the key, or NULL if it was not mapped. +*/ +void *vdo_int_map_remove (struct int_map *map,u64 key) +{ +void *value; + +/* Select the bucket to search and search it for an existing entry. */ +struct bucket *bucket =select_bucket (map, key); +struct bucket *previous; +struct bucket *victim =search_hop_list (map, bucket, key, &previous); + +if (victim ==NULL ) { +/* There is no matching entry to remove. */ +return NULL ; + } + +/* +* We found an entry to remove. Save the mapped value to return later and empty the bucket. +*/ + map->size -=1 ; + value = victim->value; + victim->value =NULL ; + victim->key =0 ; + +/* The victim bucket is now empty, but it still needs to be spliced out of the hop list. */ +if (previous ==NULL ) { +/* The victim is the head of the list, so swing first_hop. */ + bucket->first_hop = victim->next_hop; + }else { + previous->next_hop = victim->next_hop; + } + + victim->next_hop =NULL_HOP_OFFSET ; +return value; +}
drivers/md/dm-vdo/int-map.h new file +40 -0
@@ -0,0 +1,40 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +/* +* Copyright 2023 Red Hat +*/ + +#ifndef VDO_INT_MAP_H +#define VDO_INT_MAP_H + +#include <linux/compiler.h> +#include <linux/types.h> + +/** +* DOC: int_map +* +* An int_map associates pointers (void *) with integer keys (u64). NULL pointer values are +* not supported. +* +* The map is implemented as hash table, which should provide constant-time insert, query, and +* remove operations, although the insert may occasionally grow the table, which is linear in the +* number of entries in the map. The table will grow as needed to hold new entries, but will not +* shrink as entries are removed. +*/ + +struct int_map ; + +int __must_check +vdo_make_int_map (size_t initial_capacity,unsigned int initial_load,struct int_map **map_ptr); + +void vdo_free_int_map (struct int_map *map); + +size_t vdo_int_map_size (const struct int_map *map); + +void *vdo_int_map_get (struct int_map *map,u64 key); + +int __must_check +vdo_int_map_put (struct int_map *map,u64 key,void *new_value,bool update,void **old_value_ptr); + +void *vdo_int_map_remove (struct int_map *map,u64 key); + +#endif /* VDO_INT_MAP_H */
drivers/md/dm-vdo/pointer-map.c new file +696 -0
696 lines not on this page · raw message
drivers/md/dm-vdo/pointer-map.h new file +81 -0
81 lines not on this page · raw message
drivers/md/dm-vdo/priority-table.c new file +226 -0
226 lines not on this page · raw message
drivers/md/dm-vdo/priority-table.h new file +47 -0
47 lines not on this page · raw message
Signature · 1 line
2.40.0
Matthew Sakai
maintainerPATCH v5 10/40 dm vdo: add deduplication index storage interface
In reply to Matthew SakaiThis patch adds infrastructure for managing reads and writes to the underlying storage layer for the deduplication index. The deduplication index uses dm-bufio for all of its reads and writes, so part of this infrastructure is managing the various dm-bufio clients required. It also adds the buffered reader and buffered writer abstractions, which simplify reading and writing metadata structures that span several blocks.
This patch also includes structures and utilities for encoding and decoding all of the deduplication index metadata, collectively called the index layout.
--- drivers/md/dm-vdo/index-layout.c | 1768 ++++++++++++++++++++++++++++++ drivers/md/dm-vdo/index-layout.h | 43 + drivers/md/dm-vdo/io-factory.c | 415 +++++++ drivers/md/dm-vdo/io-factory.h | 64 ++ drivers/md/dm-vdo/numeric.h | 78 ++ 5 files changed, 2368 insertions(+) create mode 100644 drivers/md/dm-vdo/index-layout.c create mode 100644 drivers/md/dm-vdo/index-layout.h create mode 100644 drivers/md/dm-vdo/io-factory.c create mode 100644 drivers/md/dm-vdo/io-factory.h create mode 100644 drivers/md/dm-vdo/numeric.h
drivers/md/dm-vdo/index-layout.c new file +1768 -0
@@ -0,0 +1,1768 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* +* Copyright 2023 Red Hat +*/ + +#include "index-layout.h" + +#include <linux/random.h> + +#include "config.h" +#include "logger.h" +#include "memory-alloc.h" +#include "murmurhash3.h" +#include "numeric.h" +#include "open-chapter.h" +#include "time-utils.h" +#include "volume-index.h" + +/* +* The UDS layout on storage media is divided into a number of fixed-size regions, the sizes of +* which are computed when the index is created. Every header and region begins on 4K block +* boundary. Save regions are further sub-divided into regions of their own. +* +* Each region has a kind and an instance number. Some kinds only have one instance and therefore +* use RL_SOLE_INSTANCE (-1) as the instance number. The RL_KIND_INDEX used to use instances to +* represent sub-indices; now, however there is only ever one sub-index and therefore one instance. +* The RL_KIND_VOLUME_INDEX uses instances to record which zone is being saved. +* +* Every region header has a type and version. +* +* +-+-+---------+--------+--------+-+ +* | | | I N D E X 0 101, 0 | | +* |H|C+---------+--------+--------+S| +* |D|f| Volume | Save | Save |e| +* |R|g| Region | Region | Region |a| +* | | | 201, -1 | 202, 0 | 202, 1 |l| +* +-+-+--------+---------+--------+-+ +* +* The header contains the encoded region layout table as well as some index configuration data. +* The sub-index region and its subdivisions are maintained in the same table. +* +* There are two save regions to preserve the old state in case saving the new state is incomplete. +* They are used in alternation. Each save region is further divided into sub-regions. +* +* +-+-----+------+------+-----+-----+ +* |H| IPM | MI | MI | | OC | +* |D| | zone | zone | ... | | +* |R| 301 | 302 | 302 | | 303 | +* | | -1 | 0 | 1 | | -1 | +* +-+-----+------+------+-----+-----+ +* +* The header contains the encoded region layout table as well as index state data for that save. +* Each save also has a unique nonce. +*/ + +enum { +MAGIC_SIZE =32 , +NONCE_INFO_SIZE =32 , +MAX_SAVES =2 , +}; + +enum region_kind { +RL_KIND_EMPTY =0 , +RL_KIND_HEADER =1 , +RL_KIND_CONFIG =100 , +RL_KIND_INDEX =101 , +RL_KIND_SEAL =102 , +RL_KIND_VOLUME =201 , +RL_KIND_SAVE =202 , +RL_KIND_INDEX_PAGE_MAP =301 , +RL_KIND_VOLUME_INDEX =302 , +RL_KIND_OPEN_CHAPTER =303 , +}; + +/* Some region types are historical and are no longer used. */ +enum region_type { +RH_TYPE_FREE =0 ,/* unused */ +RH_TYPE_SUPER =1 , +RH_TYPE_SAVE =2 , +RH_TYPE_CHECKPOINT =3 ,/* unused */ +RH_TYPE_UNSAVED =4 , +}; + +enum { +RL_SOLE_INSTANCE =65535 , +}; + +/* +* Super block version 2 is the first released version. +* +* Super block version 3 is the normal version used from RHEL 8.2 onwards. +* +* Super block versions 4 through 6 were incremental development versions and +* are not supported. +* +* Super block version 7 is used for volumes which have been reduced in size by one chapter in +* order to make room to prepend LVM metadata to a volume originally created without lvm. This +* allows the index to retain most its deduplication records. +*/ +enum { +SUPER_VERSION_MINIMUM =3 , +SUPER_VERSION_CURRENT =3 , +SUPER_VERSION_MAXIMUM =7 , +}; + +static const u8 LAYOUT_MAGIC [MAGIC_SIZE ] ="*ALBIREO*SINGLE*FILE*LAYOUT*001*" ; +static const u64 REGION_MAGIC =0x416c6252676e3031 ;/* 'AlbRgn01' */ + +struct region_header { +u64 magic; +u64 region_blocks; +u16 type; +/* Currently always version 1 */ +u16 version; +u16 region_count; +u16 payload; +}; + +struct layout_region { +u64 start_block; +u64 block_count; +u32 __unused; +u16 kind; +u16 instance; +}; + +struct region_table { +size_t encoded_size; +struct region_header header; +struct layout_region regions[]; +}; + +struct index_save_data { +u64 timestamp; +u64 nonce; +/* Currently always version 1 */ +u32 version; +u32 unused__; +}; + +struct index_state_version { +s32 signature; +s32 version_id; +}; + +static const struct index_state_version INDEX_STATE_VERSION_301 = { + .signature =-1 , + .version_id =301 , +}; + +struct index_state_data301 { +struct index_state_version version; +u64 newest_chapter; +u64 oldest_chapter; +u64 last_save; +u32 unused; +u32 padding; +}; + +struct index_save_layout { +unsigned int zone_count; +struct layout_region index_save; +struct layout_region header; +struct layout_region index_page_map; +struct layout_region free_space; +struct layout_region volume_index_zones[MAX_ZONES ]; +struct layout_region open_chapter; +struct index_save_data save_data; +struct index_state_data301 state_data; +}; + +struct sub_index_layout { +u64 nonce; +struct layout_region sub_index; +struct layout_region volume; +struct index_save_layout *saves; +}; + +struct super_block_data { +u8 magic_label[MAGIC_SIZE ]; +u8 nonce_info[NONCE_INFO_SIZE ]; +u64 nonce; +u32 version; +u32 block_size; +u16 index_count; +u16 max_saves; +/* Padding reflects a blank field on permanent storage */ +u8 padding[4 ]; +u64 open_chapter_blocks; +u64 page_map_blocks; +u64 volume_offset; +u64 start_offset; +}; + +struct index_layout { +struct io_factory *factory; +size_t factory_size; +off_t offset; +struct super_block_data super; +struct layout_region header; +struct layout_region config; +struct sub_index_layout index; +struct layout_region seal; +u64 total_blocks; +}; + +struct save_layout_sizes { +unsigned int save_count; +size_t block_size; +u64 volume_blocks; +u64 volume_index_blocks; +u64 page_map_blocks; +u64 open_chapter_blocks; +u64 save_blocks; +u64 sub_index_blocks; +u64 total_blocks; +size_t total_size; +}; + +static inline bool is_converted_super_block (struct super_block_data *super) +{ +return super->version ==7 ; +} + +static int __must_check compute_sizes (const struct configuration *config, +struct save_layout_sizes *sls) +{ +int result; +struct geometry *geometry = config->geometry; + +memset (sls,0 ,sizeof (*sls)); + sls->save_count =MAX_SAVES ; + sls->block_size =UDS_BLOCK_SIZE ; + sls->volume_blocks = geometry->bytes_per_volume / sls->block_size; + + result =uds_compute_volume_index_save_blocks (config, sls->block_size, + &sls->volume_index_blocks); +if (result !=UDS_SUCCESS ) +return uds_log_error_strerror (result,"cannot compute index save size" ); + + sls->page_map_blocks = +DIV_ROUND_UP (uds_compute_index_page_map_save_size (geometry), + sls->block_size); + sls->open_chapter_blocks = +DIV_ROUND_UP (uds_compute_saved_open_chapter_size (geometry), + sls->block_size); + sls->save_blocks = +1 + (sls->volume_index_blocks + sls->page_map_blocks + sls->open_chapter_blocks); + sls->sub_index_blocks = sls->volume_blocks + (sls->save_count * sls->save_blocks); + sls->total_blocks =3 + sls->sub_index_blocks; + sls->total_size = sls->total_blocks * sls->block_size; + +return UDS_SUCCESS ; +} + +int uds_compute_index_size (const struct uds_parameters *parameters,u64 *index_size) +{ +int result; +struct configuration *index_config; +struct save_layout_sizes sizes; + +if (index_size ==NULL ) { +uds_log_error ("Missing output size pointer" ); +return -EINVAL ; + } + + result =uds_make_configuration (parameters, &index_config); +if (result !=UDS_SUCCESS ) { +uds_log_error_strerror (result,"cannot compute index size" ); +return uds_map_to_system_error (result); + } + + result =compute_sizes (index_config, &sizes); +uds_free_configuration (index_config); +if (result !=UDS_SUCCESS ) +return uds_map_to_system_error (result); + + *index_size = sizes.total_size; +return UDS_SUCCESS ; +} + +/* Create unique data using the current time and a pseudorandom number. */ +static void create_unique_nonce_data (u8 *buffer) +{ +ktime_t now =current_time_ns (CLOCK_REALTIME ); +u32 rand; +size_t offset =0 ; + +get_random_bytes (&rand,sizeof (u32)); +memcpy (buffer + offset, &now,sizeof (now)); + offset +=sizeof (now); +memcpy (buffer + offset, &rand,sizeof (rand)); + offset +=sizeof (rand); +while (offset <NONCE_INFO_SIZE ) { +size_t len =min (NONCE_INFO_SIZE - offset, offset); + +memcpy (buffer + offset, buffer, len); + offset += len; + } +} + +static u64 hash_stuff (u64 start,const void *data,size_t len) +{ +u32 seed = start ^ (start >>27 ); +u8 hash_buffer[16 ]; + +murmurhash3_128 (data, len, seed, hash_buffer); +return get_unaligned_le64 (hash_buffer +4 ); +} + +/* Generate a primary nonce from the provided data. */ +static u64 generate_primary_nonce (const void *data,size_t len) +{ +return hash_stuff (0xa1b1e0fc , data, len); +} + +/* +* Deterministically generate a secondary nonce from an existing nonce and some arbitrary data by +* hashing the original nonce and the data to produce a new nonce. +*/ +static u64 generate_secondary_nonce (u64 nonce,const void *data,size_t len) +{ +return hash_stuff (nonce +1 , data, len); +} + +static int __must_check open_layout_reader (struct index_layout *layout, +struct layout_region *lr,off_t offset, +struct buffered_reader **reader_ptr) +{ +return uds_make_buffered_reader (layout->factory, lr->start_block + offset, + lr->block_count, reader_ptr); +} + +static int open_region_reader (struct index_layout *layout,struct layout_region *region, +struct buffered_reader **reader_ptr) +{ +return open_layout_reader (layout, region, -layout->super.start_offset, + reader_ptr); +} + +static int __must_check open_layout_writer (struct index_layout *layout, +struct layout_region *lr,off_t offset, +struct buffered_writer **writer_ptr) +{ +return uds_make_buffered_writer (layout->factory, lr->start_block + offset, + lr->block_count, writer_ptr); +} + +static int open_region_writer (struct index_layout *layout,struct layout_region *region, +struct buffered_writer **writer_ptr) +{ +return open_layout_writer (layout, region, -layout->super.start_offset, + writer_ptr); +} + +static void generate_super_block_data (struct save_layout_sizes *sls, +struct super_block_data *super) +{ +memset (super,0 ,sizeof (*super)); +memcpy (super->magic_label,LAYOUT_MAGIC ,MAGIC_SIZE ); +create_unique_nonce_data (super->nonce_info); + + super->nonce =generate_primary_nonce (super->nonce_info, +sizeof (super->nonce_info)); + super->version =SUPER_VERSION_CURRENT ; + super->block_size = sls->block_size; + super->index_count =1 ; + super->max_saves = sls->save_count; + super->open_chapter_blocks = sls->open_chapter_blocks; + super->page_map_blocks = sls->page_map_blocks; + super->volume_offset =0 ; + super->start_offset =0 ; +} + +static void define_sub_index_nonce (struct index_layout *layout) +{ +struct sub_index_nonce_data { +u64 offset; +u16 index_id; + }; +struct sub_index_layout *sil = &layout->index; +u64 primary_nonce = layout->super.nonce; +u8 buffer[sizeof (struct sub_index_nonce_data )] = {0 }; +size_t offset =0 ; + +encode_u64_le (buffer, &offset, sil->sub_index.start_block); +encode_u16_le (buffer, &offset,0 ); + sil->nonce =generate_secondary_nonce (primary_nonce, buffer,sizeof (buffer)); +if (sil->nonce ==0 ) + sil->nonce =generate_secondary_nonce (~primary_nonce +1 , buffer, +sizeof (buffer)); +} + +static void setup_sub_index (struct index_layout *layout,u64 start_block, +struct save_layout_sizes *sls) +{ +struct sub_index_layout *sil = &layout->index; +u64 next_block = start_block; +unsigned int i; + + sil->sub_index = (struct layout_region ) { + .start_block = start_block, + .block_count = sls->sub_index_blocks, + .kind =RL_KIND_INDEX , + .instance =0 , + }; + + sil->volume = (struct layout_region ) { + .start_block = next_block, + .block_count = sls->volume_blocks, + .kind =RL_KIND_VOLUME , + .instance =RL_SOLE_INSTANCE , + }; + + next_block += sls->volume_blocks; + +for (i =0 ; i < sls->save_count; i++) { + sil->saves[i].index_save = (struct layout_region ) { + .start_block = next_block, + .block_count = sls->save_blocks, + .kind =RL_KIND_SAVE , + .instance = i, + }; + + next_block += sls->save_blocks; + } + +define_sub_index_nonce (layout); +} + +static void initialize_layout (struct index_layout *layout,struct save_layout_sizes *sls) +{ +u64 next_block = layout->offset / sls->block_size; + + layout->total_blocks = sls->total_blocks; +generate_super_block_data (sls, &layout->super); + layout->header = (struct layout_region ) { + .start_block = next_block++, + .block_count =1 , + .kind =RL_KIND_HEADER , + .instance =RL_SOLE_INSTANCE , + }; + + layout->config = (struct layout_region ) { + .start_block = next_block++, + .block_count =1 , + .kind =RL_KIND_CONFIG , + .instance =RL_SOLE_INSTANCE , + }; + +setup_sub_index (layout, next_block, sls); + next_block += sls->sub_index_blocks; + + layout->seal = (struct layout_region ) { + .start_block = next_block, + .block_count =1 , + .kind =RL_KIND_SEAL , + .instance =RL_SOLE_INSTANCE , + }; +} + +static int __must_check make_index_save_region_table (struct index_save_layout *isl, +struct region_table **table_ptr) +{ +int result; +unsigned int z; +struct region_table *table; +struct layout_region *lr; +u16 region_count; +size_t payload; +size_t type; + +if (isl->zone_count >0 ) { +/* +* Normal save regions: header, page map, volume index zones, +* open chapter, and possibly free space. +*/ + region_count =3 + isl->zone_count; +if (isl->free_space.block_count >0 ) + region_count++; + + payload =sizeof (isl->save_data) +sizeof (isl->state_data); + type =RH_TYPE_SAVE ; + }else { +/* Empty save regions: header, page map, free space. */ + region_count =3 ; + payload =sizeof (isl->save_data); + type =RH_TYPE_UNSAVED ; + } + + result = uds_allocate_extended(struct region_table, region_count, + struct layout_region, +"layout region table for ISL" , &table); +if (result !=UDS_SUCCESS ) +return result; + + lr = &table->regions[0 ]; + *lr++ = isl->header; + *lr++ = isl->index_page_map; +for (z =0 ; z < isl->zone_count; z++) + *lr++ = isl->volume_index_zones[z]; + +if (isl->zone_count >0 ) + *lr++ = isl->open_chapter; + +if (isl->free_space.block_count >0 ) + *lr++ = isl->free_space; + + table->header = (struct region_header ) { + .magic =REGION_MAGIC , + .region_blocks = isl->index_save.block_count, + .type = type, + .version =1 , + .region_count = region_count, + .payload = payload, + }; + + table->encoded_size = (sizeof (struct region_header ) + payload + + region_count *sizeof (struct layout_region )); + *table_ptr = table; +return UDS_SUCCESS ; +} + +static void encode_region_table (u8 *buffer,size_t *offset,struct region_table *table) +{ +unsigned int i; + +encode_u64_le (buffer, offset,REGION_MAGIC ); +encode_u64_le (buffer, offset, table->header.region_blocks); +encode_u16_le (buffer, offset, table->header.type); +encode_u16_le (buffer, offset, table->header.version); +encode_u16_le (buffer, offset, table->header.region_count); +encode_u16_le (buffer, offset, table->header.payload); + +for (i =0 ; i < table->header.region_count; i++) { +encode_u64_le (buffer, offset, table->regions[i].start_block); +encode_u64_le (buffer, offset, table->regions[i].block_count); +encode_u32_le (buffer, offset,0 ); +encode_u16_le (buffer, offset, table->regions[i].kind); +encode_u16_le (buffer, offset, table->regions[i].instance); + } +} + +static int __must_check write_index_save_header (struct index_save_layout *isl, +struct region_table *table, +struct buffered_writer *writer) +{ +int result; +u8 *buffer; +size_t offset =0 ; + + result =uds_allocate (table->encoded_size, u8,"index save data" , &buffer); +if (result !=UDS_SUCCESS ) +return result; + +encode_region_table (buffer, &offset, table); +encode_u64_le (buffer, &offset, isl->save_data.timestamp); +encode_u64_le (buffer, &offset, isl->save_data.nonce); +encode_u32_le (buffer, &offset, isl->save_data.version); +encode_u32_le (buffer, &offset,0 ); +if (isl->zone_count >0 ) { +encode_u32_le (buffer, &offset,INDEX_STATE_VERSION_301 .signature); +encode_u32_le (buffer, &offset,INDEX_STATE_VERSION_301 .version_id); +encode_u64_le (buffer, &offset, isl->state_data.newest_chapter); +encode_u64_le (buffer, &offset, isl->state_data.oldest_chapter); +encode_u64_le (buffer, &offset, isl->state_data.last_save); +encode_u64_le (buffer, &offset,0 ); + } + + result =uds_write_to_buffered_writer (writer, buffer, offset); +uds_free (buffer); +if (result !=UDS_SUCCESS ) +return result; + +return uds_flush_buffered_writer (writer); +} + +static int write_index_save_layout (struct index_layout *layout, +struct index_save_layout *isl) +{ +int result; +struct region_table *table; +struct buffered_writer *writer; + + result =make_index_save_region_table (isl, &table); +if (result !=UDS_SUCCESS ) +return result; + + result =open_region_writer (layout, &isl->header, &writer); +if (result !=UDS_SUCCESS ) { +uds_free (table); +return result; + } + + result =write_index_save_header (isl, table, writer); +uds_free (table); +uds_free_buffered_writer (writer); + +return result; +} + +static void reset_index_save_layout (struct index_save_layout *isl,u64 page_map_blocks) +{ +u64 free_blocks; +u64 next_block = isl->index_save.start_block; + + isl->zone_count =0 ; +memset (&isl->save_data,0 ,sizeof (isl->save_data)); + + isl->header = (struct layout_region ) { + .start_block = next_block++, + .block_count =1 , + .kind =RL_KIND_HEADER , + .instance =RL_SOLE_INSTANCE , + }; + + isl->index_page_map = (struct layout_region ) { + .start_block = next_block, + .block_count = page_map_blocks, + .kind =RL_KIND_INDEX_PAGE_MAP , + .instance =RL_SOLE_INSTANCE , + }; + + next_block += page_map_blocks; + + free_blocks = isl->index_save.block_count - page_map_blocks -1 ; + isl->free_space = (struct layout_region ) { + .start_block = next_block, + .block_count = free_blocks, + .kind =RL_KIND_EMPTY , + .instance =RL_SOLE_INSTANCE , + }; +} + +static int __must_check invalidate_old_save (struct index_layout *layout, +struct index_save_layout *isl) +{ +reset_index_save_layout (isl, layout->super.page_map_blocks); +return write_index_save_layout (layout, isl); +} + +static int discard_index_state_data (struct index_layout *layout) +{ +int result; +int saved_result =UDS_SUCCESS ; +unsigned int i; + +for (i =0 ; i < layout->super.max_saves; i++) { + result =invalidate_old_save (layout, &layout->index.saves[i]); +if (result !=UDS_SUCCESS ) + saved_result = result; + } + +if (saved_result !=UDS_SUCCESS ) +return uds_log_error_strerror (result, +"%s: cannot destroy all index saves" , + __func__); + +return UDS_SUCCESS ; +} + +static int __must_check make_layout_region_table (struct index_layout *layout, +struct region_table **table_ptr) +{ +int result; +unsigned int i; +/* Regions: header, config, index, volume, saves, seal */ +u16 region_count =5 + layout->super.max_saves; +u16 payload; +struct region_table *table; +struct layout_region *lr; + + result = uds_allocate_extended(struct region_table, region_count, + struct layout_region, "layout region table", + &table); +if (result !=UDS_SUCCESS ) +return result; + + lr = &table->regions[0 ]; + *lr++ = layout->header; + *lr++ = layout->config; + *lr++ = layout->index.sub_index; + *lr++ = layout->index.volume; + +for (i =0 ; i < layout->super.max_saves; i++) + *lr++ = layout->index.saves[i].index_save; + + *lr++ = layout->seal; + +if (is_converted_super_block (&layout->super)) { + payload =sizeof (struct super_block_data ); + }else { + payload = (sizeof (struct super_block_data ) - +sizeof (layout->super.volume_offset) - +sizeof (layout->super.start_offset)); + } + + table->header = (struct region_header ) { + .magic =REGION_MAGIC , + .region_blocks = layout->total_blocks, + .type =RH_TYPE_SUPER , + .version =1 , + .region_count = region_count, + .payload = payload, + }; + + table->encoded_size = (sizeof (struct region_header ) + payload + + region_count *sizeof (struct layout_region )); + *table_ptr = table; +return UDS_SUCCESS ; +} + +static int __must_check write_layout_header (struct index_layout *layout, +struct region_table *table, +struct buffered_writer *writer) +{ +int result; +u8 *buffer; +size_t offset =0 ; + + result =uds_allocate (table->encoded_size, u8,"layout data" , &buffer); +if (result !=UDS_SUCCESS ) +return result; + +encode_region_table (buffer, &offset, table); +memcpy (buffer + offset, &layout->super.magic_label,MAGIC_SIZE ); + offset +=MAGIC_SIZE ; +memcpy (buffer + offset, &layout->super.nonce_info,NONCE_INFO_SIZE ); + offset +=NONCE_INFO_SIZE ; +encode_u64_le (buffer, &offset, layout->super.nonce); +encode_u32_le (buffer, &offset, layout->super.version); +encode_u32_le (buffer, &offset, layout->super.block_size); +encode_u16_le (buffer, &offset, layout->super.index_count); +encode_u16_le (buffer, &offset, layout->super.max_saves); +encode_u32_le (buffer, &offset,0 ); +encode_u64_le (buffer, &offset, layout->super.open_chapter_blocks); +encode_u64_le (buffer, &offset, layout->super.page_map_blocks); + +if (is_converted_super_block (&layout->super)) { +encode_u64_le (buffer, &offset, layout->super.volume_offset); +encode_u64_le (buffer, &offset, layout->super.start_offset); + } + + result =uds_write_to_buffered_writer (writer, buffer, offset); +uds_free (buffer); +if (result !=UDS_SUCCESS ) +return result; + +return uds_flush_buffered_writer (writer); +} + +static int __must_check write_uds_index_config (struct index_layout *layout, +struct configuration *config, +off_t offset) +{ +int result; +struct buffered_writer *writer =NULL ; + + result =open_layout_writer (layout, &layout->config, offset, &writer); +if (result !=UDS_SUCCESS ) +return uds_log_error_strerror (result,"failed to open config region" ); + + result =uds_write_config_contents (writer, config, layout->super.version); +if (result !=UDS_SUCCESS ) { +uds_free_buffered_writer (writer); +return uds_log_error_strerror (result,"failed to write config region" ); + } + + result =uds_flush_buffered_writer (writer); +if (result !=UDS_SUCCESS ) { +uds_free_buffered_writer (writer); +return uds_log_error_strerror (result,"cannot flush config writer" ); + } + +uds_free_buffered_writer (writer); +return UDS_SUCCESS ; +} + +static int __must_check save_layout (struct index_layout *layout,off_t offset) +{ +int result; +struct buffered_writer *writer =NULL ; +struct region_table *table; + + result =make_layout_region_table (layout, &table); +if (result !=UDS_SUCCESS ) +return result; + + result =open_layout_writer (layout, &layout->header, offset, &writer); +if (result !=UDS_SUCCESS ) { +uds_free (table); +return result; + } + + result =write_layout_header (layout, table, writer); +uds_free (table); +uds_free_buffered_writer (writer); + +return result; +} + +static int create_index_layout (struct index_layout *layout,struct configuration *config) +{ +int result; +struct save_layout_sizes sizes; + + result =compute_sizes (config, &sizes); +if (result !=UDS_SUCCESS ) +return result; + + result = uds_allocate(sizes.save_count, struct index_save_layout, __func__, + &layout->index.saves); +if (result !=UDS_SUCCESS ) +return result; + +initialize_layout (layout, &sizes); + + result =discard_index_state_data (layout); +if (result !=UDS_SUCCESS ) +return result; + + result =write_uds_index_config (layout, config,0 ); +if (result !=UDS_SUCCESS ) +return result; + +return save_layout (layout,0 ); +} + +static u64 generate_index_save_nonce (u64 volume_nonce,struct index_save_layout *isl) +{ +struct save_nonce_data { +struct index_save_data data; +u64 offset; + } nonce_data; +u8 buffer[sizeof (nonce_data)]; +size_t offset =0 ; + +encode_u64_le (buffer, &offset, isl->save_data.timestamp); +encode_u64_le (buffer, &offset,0 ); +encode_u32_le (buffer, &offset, isl->save_data.version); +encode_u32_le (buffer, &offset,0U ); +encode_u64_le (buffer, &offset, isl->index_save.start_block); +ASSERT_LOG_ONLY (offset ==sizeof (nonce_data), +"%zu bytes encoded of %zu expected" , offset,sizeof (nonce_data)); +return generate_secondary_nonce (volume_nonce, buffer,sizeof (buffer)); +} + +static u64 validate_index_save_layout (struct index_save_layout *isl,u64 volume_nonce) +{ +if ((isl->zone_count ==0 ) || (isl->save_data.timestamp ==0 )) +return 0 ; + +if (isl->save_data.nonce !=generate_index_save_nonce (volume_nonce, isl)) +return 0 ; + +return isl->save_data.timestamp; +} + +static int find_latest_uds_index_save_slot (struct index_layout *layout, +struct index_save_layout **isl_ptr) +{ +struct index_save_layout *latest =NULL ; +struct index_save_layout *isl; +unsigned int i; +u64 save_time =0 ; +u64 latest_time =0 ; + +for (i =0 ; i < layout->super.max_saves; i++) { + isl = &layout->index.saves[i]; + save_time =validate_index_save_layout (isl, layout->index.nonce); +if (save_time > latest_time) { + latest = isl; + latest_time = save_time; + } + } + +if (latest ==NULL ) { +uds_log_error ("No valid index save found" ); +return UDS_INDEX_NOT_SAVED_CLEANLY ; + } + + *isl_ptr = latest; +return UDS_SUCCESS ; +} + +int uds_discard_open_chapter (struct index_layout *layout) +{ +int result; +struct index_save_layout *isl; +struct buffered_writer *writer; + + result =find_latest_uds_index_save_slot (layout, &isl); +if (result !=UDS_SUCCESS ) +return result; + + result =open_region_writer (layout, &isl->open_chapter, &writer); +if (result !=UDS_SUCCESS ) +return result; + + result =uds_write_to_buffered_writer (writer,NULL ,UDS_BLOCK_SIZE ); +if (result !=UDS_SUCCESS ) { +uds_free_buffered_writer (writer); +return result; + } + + result =uds_flush_buffered_writer (writer); +uds_free_buffered_writer (writer); +return result; +} + +int uds_load_index_state (struct index_layout *layout,struct uds_index *index) +{ +int result; +unsigned int zone; +struct index_save_layout *isl; +struct buffered_reader *readers[MAX_ZONES ]; + + result =find_latest_uds_index_save_slot (layout, &isl); +if (result !=UDS_SUCCESS ) +return result; + + index->newest_virtual_chapter = isl->state_data.newest_chapter; + index->oldest_virtual_chapter = isl->state_data.oldest_chapter; + index->last_save = isl->state_data.last_save; + + result =open_region_reader (layout, &isl->open_chapter, &readers[0 ]); +if (result !=UDS_SUCCESS ) +return result; + + result =uds_load_open_chapter (index, readers[0 ]); +uds_free_buffered_reader (readers[0 ]); +if (result !=UDS_SUCCESS ) +return result; + +for (zone =0 ; zone < isl->zone_count; zone++) { + result =open_region_reader (layout, &isl->volume_index_zones[zone], + &readers[zone]); +if (result !=UDS_SUCCESS ) { +for (; zone >0 ; zone--) +uds_free_buffered_reader (readers[zone -1 ]); + +return result; + } + } + + result =uds_load_volume_index (index->volume_index, readers, isl->zone_count); +for (zone =0 ; zone < isl->zone_count; zone++) +uds_free_buffered_reader (readers[zone]); +if (result !=UDS_SUCCESS ) +return result; + + result =open_region_reader (layout, &isl->index_page_map, &readers[0 ]); +if (result !=UDS_SUCCESS ) +return result; + + result =uds_read_index_page_map (index->volume->index_page_map, readers[0 ]); +uds_free_buffered_reader (readers[0 ]); + +return result; +} + +static struct index_save_layout *select_oldest_index_save_layout (struct index_layout *layout) +{ +struct index_save_layout *oldest =NULL ; +struct index_save_layout *isl; +unsigned int i; +u64 save_time =0 ; +u64 oldest_time =0 ; + +for (i =0 ; i < layout->super.max_saves; i++) { + isl = &layout->index.saves[i]; + save_time =validate_index_save_layout (isl, layout->index.nonce); +if (oldest ==NULL || save_time < oldest_time) { + oldest = isl; + oldest_time = save_time; + } + } + +return oldest; +} + +static void instantiate_index_save_layout (struct index_save_layout *isl, +struct super_block_data *super, +u64 volume_nonce,unsigned int zone_count) +{ +unsigned int z; +u64 next_block; +u64 free_blocks; +u64 volume_index_blocks; + + isl->zone_count = zone_count; +memset (&isl->save_data,0 ,sizeof (isl->save_data)); + isl->save_data.timestamp =ktime_to_ms (current_time_ns (CLOCK_REALTIME )); + isl->save_data.version =1 ; + isl->save_data.nonce =generate_index_save_nonce (volume_nonce, isl); + + next_block = isl->index_save.start_block; + isl->header = (struct layout_region ) { + .start_block = next_block++, + .block_count =1 , + .kind =RL_KIND_HEADER , + .instance =RL_SOLE_INSTANCE , + }; + + isl->index_page_map = (struct layout_region ) { + .start_block = next_block, + .block_count = super->page_map_blocks, + .kind =RL_KIND_INDEX_PAGE_MAP , + .instance =RL_SOLE_INSTANCE , + }; + next_block += super->page_map_blocks; + + free_blocks = (isl->index_save.block_count -1 - + super->page_map_blocks - + super->open_chapter_blocks); + volume_index_blocks = free_blocks / isl->zone_count; +for (z =0 ; z < isl->zone_count; z++) { + isl->volume_index_zones[z] = (struct layout_region ) { + .start_block = next_block, + .block_count = volume_index_blocks, + .kind =RL_KIND_VOLUME_INDEX , + .instance = z, + }; + + next_block += volume_index_blocks; + free_blocks -= volume_index_blocks; + } + + isl->open_chapter = (struct layout_region ) { + .start_block = next_block, + .block_count = super->open_chapter_blocks, + .kind =RL_KIND_OPEN_CHAPTER , + .instance =RL_SOLE_INSTANCE , + }; + + next_block += super->open_chapter_blocks; + + isl->free_space = (struct layout_region ) { + .start_block = next_block, + .block_count = free_blocks, + .kind =RL_KIND_EMPTY , + .instance =RL_SOLE_INSTANCE , + }; +} + +static int setup_uds_index_save_slot (struct index_layout *layout, +unsigned int zone_count, +struct index_save_layout **isl_ptr) +{ +int result; +struct index_save_layout *isl; + + isl =select_oldest_index_save_layout (layout); + result =invalidate_old_save (layout, isl); +if (result !=UDS_SUCCESS ) +return result; + +instantiate_index_save_layout (isl, &layout->super, layout->index.nonce, + zone_count); + + *isl_ptr = isl; +return UDS_SUCCESS ; +} + +static void cancel_uds_index_save (struct index_save_layout *isl) +{ +memset (&isl->save_data,0 ,sizeof (isl->save_data)); +memset (&isl->state_data,0 ,sizeof (isl->state_data)); + isl->zone_count =0 ; +} + +int uds_save_index_state (struct index_layout *layout,struct uds_index *index) +{ +int result; +unsigned int zone; +struct index_save_layout *isl; +struct buffered_writer *writers[MAX_ZONES ]; + + result =setup_uds_index_save_slot (layout, index->zone_count, &isl); +if (result !=UDS_SUCCESS ) +return result; + + isl->state_data = (struct index_state_data301 ) { + .newest_chapter = index->newest_virtual_chapter, + .oldest_chapter = index->oldest_virtual_chapter, + .last_save = index->last_save, + }; + + result =open_region_writer (layout, &isl->open_chapter, &writers[0 ]); +if (result !=UDS_SUCCESS ) { +cancel_uds_index_save (isl); +return result; + } + + result =uds_save_open_chapter (index, writers[0 ]); +uds_free_buffered_writer (writers[0 ]); +if (result !=UDS_SUCCESS ) { +cancel_uds_index_save (isl); +return result; + } + +for (zone =0 ; zone < index->zone_count; zone++) { + result =open_region_writer (layout, &isl->volume_index_zones[zone], + &writers[zone]); +if (result !=UDS_SUCCESS ) { +for (; zone >0 ; zone--) +uds_free_buffered_writer (writers[zone -1 ]); + +cancel_uds_index_save (isl); +return result; + } + } + + result =uds_save_volume_index (index->volume_index, writers, index->zone_count); +for (zone =0 ; zone < index->zone_count; zone++) +uds_free_buffered_writer (writers[zone]); +if (result !=UDS_SUCCESS ) { +cancel_uds_index_save (isl); +return result; + } + + result =open_region_writer (layout, &isl->index_page_map, &writers[0 ]); +if (result !=UDS_SUCCESS ) { +cancel_uds_index_save (isl); +return result; + } + + result =uds_write_index_page_map (index->volume->index_page_map, writers[0 ]); +uds_free_buffered_writer (writers[0 ]); +if (result !=UDS_SUCCESS ) { +cancel_uds_index_save (isl); +return result; + } + +return write_index_save_layout (layout, isl); +} + +static int __must_check load_region_table (struct buffered_reader *reader, +struct region_table **table_ptr) +{ +int result; +unsigned int i; +struct region_header header; +struct region_table *table; +u8 buffer[sizeof (struct region_header )]; +size_t offset =0 ; + + result =uds_read_from_buffered_reader (reader, buffer,sizeof (buffer)); +if (result !=UDS_SUCCESS ) +return uds_log_error_strerror (result,"cannot read region table header" ); + +decode_u64_le (buffer, &offset, &header.magic); +decode_u64_le (buffer, &offset, &header.region_blocks); +decode_u16_le (buffer, &offset, &header.type); +decode_u16_le (buffer, &offset, &header.version); +decode_u16_le (buffer, &offset, &header.region_count); +decode_u16_le (buffer, &offset, &header.payload); + +if (header.magic !=REGION_MAGIC ) +return UDS_NO_INDEX ; + +if (header.version !=1 ) { +return uds_log_error_strerror (UDS_UNSUPPORTED_VERSION , +"unknown region table version %hu" , + header.version); + } + + result = uds_allocate_extended(struct region_table, header.region_count, + struct layout_region, +"single file layout region table" , &table); +if (result !=UDS_SUCCESS ) +return result; + + table->header = header; +for (i =0 ; i < header.region_count; i++) { +u8 region_buffer[sizeof (struct layout_region )]; + + offset =0 ; + result =uds_read_from_buffered_reader (reader, region_buffer, +sizeof (region_buffer)); +if (result !=UDS_SUCCESS ) { +uds_free (table); +return uds_log_error_strerror (UDS_CORRUPT_DATA , +"cannot read region table layouts" ); + } + +decode_u64_le (region_buffer, &offset, &table->regions[i].start_block); +decode_u64_le (region_buffer, &offset, &table->regions[i].block_count); + offset +=sizeof (u32); +decode_u16_le (region_buffer, &offset, &table->regions[i].kind); +decode_u16_le (region_buffer, &offset, &table->regions[i].instance); + } + + *table_ptr = table; +return UDS_SUCCESS ; +} + +static int __must_check read_super_block_data (struct buffered_reader *reader, +struct index_layout *layout, +size_t saved_size) +{ +int result; +struct super_block_data *super = &layout->super; +u8 *buffer; +size_t offset =0 ; + + result =uds_allocate (saved_size, u8,"super block data" , &buffer); +if (result !=UDS_SUCCESS ) +return result; + + result =uds_read_from_buffered_reader (reader, buffer, saved_size); +if (result !=UDS_SUCCESS ) { +uds_free (buffer); +return uds_log_error_strerror (result,"cannot read region table header" ); + } + +memcpy (&super->magic_label, buffer,MAGIC_SIZE ); + offset +=MAGIC_SIZE ; +memcpy (&super->nonce_info, buffer + offset,NONCE_INFO_SIZE ); + offset +=NONCE_INFO_SIZE ; +decode_u64_le (buffer, &offset, &super->nonce); +decode_u32_le (buffer, &offset, &super->version); +decode_u32_le (buffer, &offset, &super->block_size); +decode_u16_le (buffer, &offset, &super->index_count); +decode_u16_le (buffer, &offset, &super->max_saves); + offset +=sizeof (u32); +decode_u64_le (buffer, &offset, &super->open_chapter_blocks); +decode_u64_le (buffer, &offset, &super->page_map_blocks); + +if (is_converted_super_block (super)) { +decode_u64_le (buffer, &offset, &super->volume_offset); +decode_u64_le (buffer, &offset, &super->start_offset); + }else { + super->volume_offset =0 ; + super->start_offset =0 ; + } + +uds_free (buffer); + +if (memcmp (super->magic_label,LAYOUT_MAGIC ,MAGIC_SIZE ) !=0 ) +return uds_log_error_strerror (UDS_CORRUPT_DATA , +"unknown superblock magic label" ); + +if ((super->version <SUPER_VERSION_MINIMUM ) || + (super->version ==4 ) || + (super->version ==5 ) || + (super->version ==6 ) || + (super->version >SUPER_VERSION_MAXIMUM )) { +return uds_log_error_strerror (UDS_UNSUPPORTED_VERSION , +"unknown superblock version number %u" , + super->version); + } + +if (super->volume_offset < super->start_offset) { +return uds_log_error_strerror (UDS_CORRUPT_DATA , +"inconsistent offsets (start %llu, volume %llu)" , + (unsigned long long ) super->start_offset, + (unsigned long long ) super->volume_offset); + } + +/* Sub-indexes are no longer used but the layout retains this field. */ +if (super->index_count !=1 ) { +return uds_log_error_strerror (UDS_CORRUPT_DATA , +"invalid subindex count %u" , + super->index_count); + } + +if (generate_primary_nonce (super->nonce_info,sizeof (super->nonce_info)) != super->nonce) { +return uds_log_error_strerror (UDS_CORRUPT_DATA , +"inconsistent superblock nonce" ); + } + +return UDS_SUCCESS ; +} + +static int __must_check verify_region (struct layout_region *lr,u64 start_block, +enum region_kind kind,unsigned int instance) +{ +if (lr->start_block != start_block) +return uds_log_error_strerror (UDS_CORRUPT_DATA , +"incorrect layout region offset" ); + +if (lr->kind != kind) +return uds_log_error_strerror (UDS_CORRUPT_DATA , +"incorrect layout region kind" ); + +if (lr->instance != instance) { +return uds_log_error_strerror (UDS_CORRUPT_DATA , +"incorrect layout region instance" ); + } + +return UDS_SUCCESS ; +} + +static int __must_check verify_sub_index (struct index_layout *layout,u64 start_block, +struct region_table *table) +{ +int result; +unsigned int i; +struct sub_index_layout *sil = &layout->index; +u64 next_block = start_block; + + sil->sub_index = table->regions[2 ]; + result =verify_region (&sil->sub_index, next_block,RL_KIND_INDEX ,0 ); +if (result !=UDS_SUCCESS ) +return result; + +define_sub_index_nonce (layout); + + sil->volume = table->regions[3 ]; + result =verify_region (&sil->volume, next_block,RL_KIND_VOLUME , +RL_SOLE_INSTANCE ); +if (result !=UDS_SUCCESS ) +return result; + + next_block += sil->volume.block_count + layout->super.volume_offset; + +for (i =0 ; i < layout->super.max_saves; i++) { + sil->saves[i].index_save = table->regions[i +4 ]; + result =verify_region (&sil->saves[i].index_save, next_block, +RL_KIND_SAVE , i); +if (result !=UDS_SUCCESS ) +return result; + + next_block += sil->saves[i].index_save.block_count; + } + + next_block -= layout->super.volume_offset; +if (next_block != start_block + sil->sub_index.block_count) { +return uds_log_error_strerror (UDS_CORRUPT_DATA , +"sub index region does not span all saves" ); + } + +return UDS_SUCCESS ; +} + +static int __must_check reconstitute_layout (struct index_layout *layout, +struct region_table *table,u64 first_block) +{ +int result; +u64 next_block = first_block; + + result = uds_allocate(layout->super.max_saves, struct index_save_layout, + __func__, &layout->index.saves); +if (result !=UDS_SUCCESS ) +return result; + + layout->total_blocks = table->header.region_blocks; + + layout->header = table->regions[0 ]; + result =verify_region (&layout->header, next_block++,RL_KIND_HEADER , +RL_SOLE_INSTANCE ); +if (result !=UDS_SUCCESS ) +return result; + + layout->config = table->regions[1 ]; + result =verify_region (&layout->config, next_block++,RL_KIND_CONFIG , +RL_SOLE_INSTANCE ); +if (result !=UDS_SUCCESS ) +return result; + + result =verify_sub_index (layout, next_block, table); +if (result !=UDS_SUCCESS ) +return result; + + next_block += layout->index.sub_index.block_count; + + layout->seal = table->regions[table->header.region_count -1 ]; + result =verify_region (&layout->seal, next_block + layout->super.volume_offset, +RL_KIND_SEAL ,RL_SOLE_INSTANCE ); +if (result !=UDS_SUCCESS ) +return result; + +if (++next_block != (first_block + layout->total_blocks)) { +return uds_log_error_strerror (UDS_CORRUPT_DATA , +"layout table does not span total blocks" ); + } + +return UDS_SUCCESS ; +} + +static int __must_check load_super_block (struct index_layout *layout,size_t block_size, +u64 first_block,struct buffered_reader *reader) +{ +int result; +struct region_table *table =NULL ; +struct super_block_data *super = &layout->super; + + result =load_region_table (reader, &table); +if (result !=UDS_SUCCESS ) +return result; + +if (table->header.type !=RH_TYPE_SUPER ) { +uds_free (table); +return uds_log_error_strerror (UDS_CORRUPT_DATA , +"not a superblock region table" ); + } + + result =read_super_block_data (reader, layout, table->header.payload); +if (result !=UDS_SUCCESS ) { +uds_free (table); +return uds_log_error_strerror (result,"unknown superblock format" ); + } + +if (super->block_size != block_size) { +uds_free (table); +return uds_log_error_strerror (UDS_CORRUPT_DATA , +"superblock saved block_size %u differs from supplied block_size %zu" , + super->block_size, block_size); + } + + first_block -= (super->volume_offset - super->start_offset); + result =reconstitute_layout (layout, table, first_block); +uds_free (table); +return result; +} + +static int __must_check read_index_save_data (struct buffered_reader *reader, +struct index_save_layout *isl, +size_t saved_size) +{ +int result; +struct index_state_version file_version; +u8 buffer[sizeof (struct index_save_data ) +sizeof (struct index_state_data301 )]; +size_t offset =0 ; + +if (saved_size !=sizeof (buffer)) { +return uds_log_error_strerror (UDS_CORRUPT_DATA , +"unexpected index save data size %zu" , + saved_size); + } + + result =uds_read_from_buffered_reader (reader, buffer,sizeof (buffer)); +if (result !=UDS_SUCCESS ) +return uds_log_error_strerror (result,"cannot read index save data" ); + +decode_u64_le (buffer, &offset, &isl->save_data.timestamp); +decode_u64_le (buffer, &offset, &isl->save_data.nonce); +decode_u32_le (buffer, &offset, &isl->save_data.version); + offset +=sizeof (u32); + +if (isl->save_data.version >1 ) { +return uds_log_error_strerror (UDS_UNSUPPORTED_VERSION , +"unknown index save version number %u" , + isl->save_data.version); + } + +decode_s32_le (buffer, &offset, &file_version.signature); +decode_s32_le (buffer, &offset, &file_version.version_id); + +if ((file_version.signature !=INDEX_STATE_VERSION_301 .signature) || + (file_version.version_id !=INDEX_STATE_VERSION_301 .version_id)) { +return uds_log_error_strerror (UDS_UNSUPPORTED_VERSION , +"index state version %d,%d is unsupported" , + file_version.signature, + file_version.version_id); + } + +decode_u64_le (buffer, &offset, &isl->state_data.newest_chapter); +decode_u64_le (buffer, &offset, &isl->state_data.oldest_chapter); +decode_u64_le (buffer, &offset, &isl->state_data.last_save); +/* Skip past some historical fields that are now unused */ + offset +=sizeof (u32) +sizeof (u32); +return UDS_SUCCESS ; +} + +static int __must_check reconstruct_index_save (struct index_save_layout *isl, +struct region_table *table) +{ +int result; +unsigned int z; +struct layout_region *last_region; +u64 next_block = isl->index_save.start_block; +u64 last_block = next_block + isl->index_save.block_count; + + isl->zone_count = table->header.region_count -3 ; + + last_region = &table->regions[table->header.region_count -1 ]; +if (last_region->kind ==RL_KIND_EMPTY ) { + isl->free_space = *last_region; + isl->zone_count--; + }else { + isl->free_space = (struct layout_region ) { + .start_block = last_block, + .block_count =0 , + .kind =RL_KIND_EMPTY , + .instance =RL_SOLE_INSTANCE , + }; + } + + isl->header = table->regions[0 ]; + result =verify_region (&isl->header, next_block++,RL_KIND_HEADER , +RL_SOLE_INSTANCE ); +if (result !=UDS_SUCCESS ) +return result; + + isl->index_page_map = table->regions[1 ]; + result =verify_region (&isl->index_page_map, next_block,RL_KIND_INDEX_PAGE_MAP , +RL_SOLE_INSTANCE ); +if (result !=UDS_SUCCESS ) +return result; + + next_block += isl->index_page_map.block_count; + +for (z =0 ; z < isl->zone_count; z++) { + isl->volume_index_zones[z] = table->regions[z +2 ]; + result =verify_region (&isl->volume_index_zones[z], next_block, +RL_KIND_VOLUME_INDEX , z); +if (result !=UDS_SUCCESS ) +return result; + + next_block += isl->volume_index_zones[z].block_count; + } + + isl->open_chapter = table->regions[isl->zone_count +2 ]; + result =verify_region (&isl->open_chapter, next_block,RL_KIND_OPEN_CHAPTER , +RL_SOLE_INSTANCE ); +if (result !=UDS_SUCCESS ) +return result; + + next_block += isl->open_chapter.block_count; + + result =verify_region (&isl->free_space, next_block,RL_KIND_EMPTY , +RL_SOLE_INSTANCE ); +if (result !=UDS_SUCCESS ) +return result; + + next_block += isl->free_space.block_count; +if (next_block != last_block) { +return uds_log_error_strerror (UDS_CORRUPT_DATA , +"index save layout table incomplete" ); + } + +return UDS_SUCCESS ; +} + +static int __must_check load_index_save (struct index_save_layout *isl, +struct buffered_reader *reader, +unsigned int instance) +{ +int result; +struct region_table *table =NULL ; + + result =load_region_table (reader, &table); +if (result !=UDS_SUCCESS ) { +return uds_log_error_strerror (result,"cannot read index save %u header" , + instance); + } + +if (table->header.region_blocks != isl->index_save.block_count) { +u64 region_blocks = table->header.region_blocks; + +uds_free (table); +return uds_log_error_strerror (UDS_CORRUPT_DATA , +"unexpected index save %u region block count %llu" , + instance, + (unsigned long long ) region_blocks); + } + +if (table->header.type ==RH_TYPE_UNSAVED ) { +uds_free (table); +reset_index_save_layout (isl,0 ); +return UDS_SUCCESS ; + } + + +if (table->header.type !=RH_TYPE_SAVE ) { +uds_free (table); +return uds_log_error_strerror (UDS_CORRUPT_DATA , +"unexpected index save %u header type %u" , + instance, table->header.type); + } + + result =read_index_save_data (reader, isl, table->header.payload); +if (result !=UDS_SUCCESS ) { +uds_free (table); +return uds_log_error_strerror (result, +"unknown index save %u data format" , + instance); + } + + result =reconstruct_index_save (isl, table); +uds_free (table); +if (result !=UDS_SUCCESS ) { +return uds_log_error_strerror (result,"cannot reconstruct index save %u" , + instance); + } + +return UDS_SUCCESS ; +} + +static int __must_check load_sub_index_regions (struct index_layout *layout) +{ +int result; +unsigned int j; +struct index_save_layout *isl; +struct buffered_reader *reader; + +for (j =0 ; j < layout->super.max_saves; j++) { + isl = &layout->index.saves[j]; + result =open_region_reader (layout, &isl->index_save, &reader); + +if (result !=UDS_SUCCESS ) { +uds_log_error_strerror (result, +"cannot get reader for index 0 save %u" , + j); +return result; + } + + result =load_index_save (isl, reader, j); +uds_free_buffered_reader (reader); +if (result !=UDS_SUCCESS ) { +/* Another save slot might be valid. */ +reset_index_save_layout (isl,0 ); +continue ; + } + } + +return UDS_SUCCESS ; +} + +static int __must_check verify_uds_index_config (struct index_layout *layout, +struct configuration *config) +{ +int result; +struct buffered_reader *reader =NULL ; +u64 offset; + + offset = layout->super.volume_offset - layout->super.start_offset; + result =open_layout_reader (layout, &layout->config, offset, &reader); +if (result !=UDS_SUCCESS ) +return uds_log_error_strerror (result,"failed to open config reader" ); + + result =uds_validate_config_contents (reader, config); +if (result !=UDS_SUCCESS ) { +uds_free_buffered_reader (reader); +return uds_log_error_strerror (result,"failed to read config region" ); + } + +uds_free_buffered_reader (reader); +return UDS_SUCCESS ; +} + +static int load_index_layout (struct index_layout *layout,struct configuration *config) +{ +int result; +struct buffered_reader *reader; + + result =uds_make_buffered_reader (layout->factory, + layout->offset /UDS_BLOCK_SIZE ,1 , &reader); +if (result !=UDS_SUCCESS ) +return uds_log_error_strerror (result,"unable to read superblock" ); + + result =load_super_block (layout,UDS_BLOCK_SIZE , + layout->offset /UDS_BLOCK_SIZE , reader); +uds_free_buffered_reader (reader); +if (result !=UDS_SUCCESS ) +return result; + + result =verify_uds_index_config (layout, config); +if (result !=UDS_SUCCESS ) +return result; + +return load_sub_index_regions (layout); +} + +static int create_layout_factory (struct index_layout *layout, +const struct configuration *config) +{ +int result; +size_t writable_size; +struct io_factory *factory =NULL ; + + result =uds_make_io_factory (config->bdev, &factory); +if (result !=UDS_SUCCESS ) +return result; + + writable_size =uds_get_writable_size (factory) & -UDS_BLOCK_SIZE ; +if (writable_size < config->size + config->offset) { +uds_put_io_factory (factory); +uds_log_error ("index storage (%zu) is smaller than the requested size %zu" , + writable_size, config->size + config->offset); +return -ENOSPC ; + } + + layout->factory = factory; + layout->factory_size = (config->size >0 ) ? config->size : writable_size; + layout->offset = config->offset; +return UDS_SUCCESS ; +} + +int uds_make_index_layout (struct configuration *config,bool new_layout, +struct index_layout **layout_ptr) +{ +int result; +struct index_layout *layout =NULL ; +struct save_layout_sizes sizes; + + result =compute_sizes (config, &sizes); +if (result !=UDS_SUCCESS ) +return result; + + result = uds_allocate(1, struct index_layout, __func__, &layout); +if (result !=UDS_SUCCESS ) +return result; + + result =create_layout_factory (layout, config); +if (result !=UDS_SUCCESS ) { +uds_free_index_layout (layout); +return result; + } + +if (layout->factory_size < sizes.total_size) { +uds_log_error ("index storage (%zu) is smaller than the required size %llu" , + layout->factory_size, + (unsigned long long ) sizes.total_size); +uds_free_index_layout (layout); +return -ENOSPC ; + } + +if (new_layout) + result =create_index_layout (layout, config); +else + result =load_index_layout (layout, config); +if (result !=UDS_SUCCESS ) { +uds_free_index_layout (layout); +return result; + } + + *layout_ptr = layout; +return UDS_SUCCESS ; +} + +void uds_free_index_layout (struct index_layout *layout) +{ +if (layout ==NULL ) +return ; + +uds_free (layout->index.saves); +if (layout->factory !=NULL ) +uds_put_io_factory (layout->factory); + +uds_free (layout); +} + +int uds_replace_index_layout_storage (struct index_layout *layout, +struct block_device *bdev) +{ +return uds_replace_storage (layout->factory, bdev); +} + +/* Obtain a dm_bufio_client for the volume region. */ +int uds_open_volume_bufio (struct index_layout *layout,size_t block_size, +unsigned int reserved_buffers, +struct dm_bufio_client **client_ptr) +{ +off_t offset = (layout->index.volume.start_block + + layout->super.volume_offset - + layout->super.start_offset); + +return uds_make_bufio (layout->factory, offset, block_size, reserved_buffers, + client_ptr); +} + +u64 uds_get_volume_nonce (struct index_layout *layout) +{ +return layout->index.nonce; +}
drivers/md/dm-vdo/index-layout.h new file +43 -0
43 lines not on this page · raw message
drivers/md/dm-vdo/io-factory.c new file +415 -0
415 lines not on this page · raw message
drivers/md/dm-vdo/io-factory.h new file +64 -0
64 lines not on this page · raw message
drivers/md/dm-vdo/numeric.h new file +78 -0
78 lines not on this page · raw message
Signature · 1 line
2.40.0
Matthew Sakai
maintainerPATCH v5 15/40 dm vdo: implement top-level deduplication index
In reply to Matthew SakaiThe top-level deduplication index brings all the earlier components together. The top-level index creates the separate zone structures that enable the index to handle several requests in parallel, handles dispatching requests to the right zones and components, and coordinates metadata to ensure that it remain consistent. It also coordinates recovery in the event of an unexpected index failure.
If sparse caching is enabled, the top-level index also handles the coordination required by the sparse chapter index cache, which (unlike most index structures) is shared among all zones.
--- drivers/md/dm-vdo/index.c | 1400 ++++++++++++++++++++++++++++++ drivers/md/dm-vdo/index.h | 83 ++ drivers/md/dm-vdo/sparse-cache.c | 580 +++++++++++++ drivers/md/dm-vdo/sparse-cache.h | 46 + 4 files changed, 2109 insertions(+) create mode 100644 drivers/md/dm-vdo/index.c create mode 100644 drivers/md/dm-vdo/index.h create mode 100644 drivers/md/dm-vdo/sparse-cache.c create mode 100644 drivers/md/dm-vdo/sparse-cache.h
drivers/md/dm-vdo/index.c new file +1400 -0
@@ -0,0 +1,1400 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* +* Copyright 2023 Red Hat +*/ + + +#include "index.h" + +#include "funnel-requestqueue.h" +#include "hash-utils.h" +#include "logger.h" +#include "memory-alloc.h" +#include "sparse-cache.h" + +static const u64 NO_LAST_SAVE =U64_MAX ; + +/* +* When searching for deduplication records, the index first searches the volume index, and then +* searches the chapter index for the relevant chapter. If the chapter has been fully committed to +* storage, the chapter pages are loaded into the page cache. If the chapter has not yet been +* committed (either the open chapter or a recently closed one), the index searches the in-memory +* representation of the chapter. Finally, if the volume index does not find a record and the index +* is sparse, the index will search the sparse cache. +* +* The index send two kinds of messages to coordinate between zones: chapter close messages for the +* chapter writer, and sparse cache barrier messages for the sparse cache. +* +* The chapter writer is responsible for committing chapters of records to storage. Since zones can +* get different numbers of records, some zones may fall behind others. Each time a zone fills up +* its available space in a chapter, it informs the chapter writer that the chapter is complete, +* and also informs all other zones that it has closed the chapter. Each other zone will then close +* the chapter immediately, regardless of how full it is, in order to minimize skew between zones. +* Once every zone has closed the chapter, the chapter writer will commit that chapter to storage. +* +* The last zone to close the chapter also removes the oldest chapter from the volume index. +* Although that chapter is invalid for zones that have moved on, the existence of the open chapter +* means that those zones will never ask the volume index about it. No zone is allowed to get more +* than one chapter ahead of any other. If a zone is so far ahead that it tries to close another +* chapter before the previous one has been closed by all zones, it is forced to wait. +* +* The sparse cache relies on having the same set of chapter indexes available to all zones. When a +* request wants to add a chapter to the sparse cache, it sends a barrier message to each zone +* during the triage stage that acts as a rendezvous. Once every zone has reached the barrier and +* paused its operations, the cache membership is changed and each zone is then informed that it +* can proceed. More details can be found in the sparse cache documentation. +* +* If a sparse cache has only one zone, it will not create a triage queue, but it still needs the +* barrier message to change the sparse cache membership, so the index simulates the message by +* invoking the handler directly. +*/ + +struct chapter_writer { +/* The index to which we belong */ +struct uds_index *index; +/* The thread to do the writing */ +struct thread *thread; +/* The lock protecting the following fields */ +struct mutex mutex; +/* The condition signalled on state changes */ +struct cond_var cond; +/* Set to true to stop the thread */ +bool stop; +/* The result from the most recent write */ +int result; +/* The number of bytes allocated by the chapter writer */ +size_t memory_size; +/* The number of zones which have submitted a chapter for writing */ +unsigned int zones_to_write; +/* Open chapter index used by uds_close_open_chapter() */ +struct open_chapter_index *open_chapter_index; +/* Collated records used by uds_close_open_chapter() */ +struct uds_volume_record *collated_records; +/* The chapters to write (one per zone) */ +struct open_chapter_zone *chapters[]; +}; + +static bool is_zone_chapter_sparse (const struct index_zone *zone,u64 virtual_chapter) +{ +return uds_is_chapter_sparse (zone->index->volume->geometry, + zone->oldest_virtual_chapter, + zone->newest_virtual_chapter, virtual_chapter); +} + +static int launch_zone_message (struct uds_zone_message message,unsigned int zone, +struct uds_index *index) +{ +int result; +struct uds_request *request; + + result = uds_allocate(1, struct uds_request, __func__, &request); +if (result !=UDS_SUCCESS ) +return result; + + request->index = index; + request->unbatched = true; + request->zone_number = zone; + request->zone_message = message; + +uds_enqueue_request (request,STAGE_MESSAGE ); +return UDS_SUCCESS ; +} + +static void enqueue_barrier_messages (struct uds_index *index,u64 virtual_chapter) +{ +struct uds_zone_message message = { + .type =UDS_MESSAGE_SPARSE_CACHE_BARRIER , + .virtual_chapter = virtual_chapter, + }; +unsigned int zone; + +for (zone =0 ; zone < index->zone_count; zone++) { +int result =launch_zone_message (message, zone, index); + +ASSERT_LOG_ONLY ((result ==UDS_SUCCESS ),"barrier message allocation" ); + } +} + +/* +* Determine whether this request should trigger a sparse cache barrier message to change the +* membership of the sparse cache. If a change in membership is desired, the function returns the +* chapter number to add. +*/ +static u64 triage_index_request (struct uds_index *index,struct uds_request *request) +{ +u64 virtual_chapter; +struct index_zone *zone; + + virtual_chapter =uds_lookup_volume_index_name (index->volume_index, + &request->record_name); +if (virtual_chapter ==NO_CHAPTER ) +return NO_CHAPTER ; + + zone = index->zones[request->zone_number]; +if (!is_zone_chapter_sparse (zone, virtual_chapter)) +return NO_CHAPTER ; + +/* +* FIXME: Optimize for a common case by remembering the chapter from the most recent +* barrier message and skipping this chapter if is it the same. +*/ + +return virtual_chapter; +} + +/* +* Simulate a message to change the sparse cache membership for a single-zone sparse index. This +* allows us to forgo the complicated locking required by a multi-zone sparse index. Any other kind +* of index does nothing here. +*/ +static int simulate_index_zone_barrier_message (struct index_zone *zone, +struct uds_request *request) +{ +u64 sparse_virtual_chapter; + +if ((zone->index->zone_count >1 ) || + !uds_is_sparse_geometry (zone->index->volume->geometry)) +return UDS_SUCCESS ; + + sparse_virtual_chapter =triage_index_request (zone->index, request); +if (sparse_virtual_chapter ==NO_CHAPTER ) +return UDS_SUCCESS ; + +return uds_update_sparse_cache (zone, sparse_virtual_chapter); +} + +/* This is the request processing function for the triage queue. */ +static void triage_request (struct uds_request *request) +{ +struct uds_index *index = request->index; +u64 sparse_virtual_chapter =triage_index_request (index, request); + +if (sparse_virtual_chapter !=NO_CHAPTER ) +enqueue_barrier_messages (index, sparse_virtual_chapter); + +uds_enqueue_request (request,STAGE_INDEX ); +} + +static int finish_previous_chapter (struct uds_index *index,u64 current_chapter_number) +{ +int result; +struct chapter_writer *writer = index->chapter_writer; + +uds_lock_mutex (&writer->mutex); +while (index->newest_virtual_chapter < current_chapter_number) +uds_wait_cond (&writer->cond, &writer->mutex); + result = writer->result; +uds_unlock_mutex (&writer->mutex); + +if (result !=UDS_SUCCESS ) +return uds_log_error_strerror (result, +"Writing of previous open chapter failed" ); + +return UDS_SUCCESS ; +} + +static int swap_open_chapter (struct index_zone *zone) +{ +int result; +struct open_chapter_zone *temporary_chapter; + + result =finish_previous_chapter (zone->index, zone->newest_virtual_chapter); +if (result !=UDS_SUCCESS ) +return result; + + temporary_chapter = zone->open_chapter; + zone->open_chapter = zone->writing_chapter; + zone->writing_chapter = temporary_chapter; +return UDS_SUCCESS ; +} + +/* +* Inform the chapter writer that this zone is done with this chapter. The chapter won't start +* writing until all zones have closed it. +*/ +static unsigned int start_closing_chapter (struct uds_index *index, +unsigned int zone_number, +struct open_chapter_zone *chapter) +{ +unsigned int finished_zones; +struct chapter_writer *writer = index->chapter_writer; + +uds_lock_mutex (&writer->mutex); + finished_zones = ++writer->zones_to_write; + writer->chapters[zone_number] = chapter; +uds_broadcast_cond (&writer->cond); +uds_unlock_mutex (&writer->mutex); + +return finished_zones; +} + +static int announce_chapter_closed (struct index_zone *zone,u64 closed_chapter) +{ +int result; +unsigned int i; +struct uds_zone_message zone_message = { + .type =UDS_MESSAGE_ANNOUNCE_CHAPTER_CLOSED , + .virtual_chapter = closed_chapter, + }; + +for (i =0 ; i < zone->index->zone_count; i++) { +if (zone->id == i) +continue ; + + result =launch_zone_message (zone_message, i, zone->index); +if (result !=UDS_SUCCESS ) +return result; + } + +return UDS_SUCCESS ; +} + +static int open_next_chapter (struct index_zone *zone) +{ +int result; +u64 closed_chapter; +u64 expiring; +unsigned int finished_zones; +u32 expire_chapters; + +uds_log_debug ("closing chapter %llu of zone %u after %u entries (%u short)" , + (unsigned long long ) zone->newest_virtual_chapter, zone->id, + zone->open_chapter->size, + zone->open_chapter->capacity - zone->open_chapter->size); + + result =swap_open_chapter (zone); +if (result !=UDS_SUCCESS ) +return result; + + closed_chapter = zone->newest_virtual_chapter++; +uds_set_volume_index_zone_open_chapter (zone->index->volume_index, zone->id, + zone->newest_virtual_chapter); +uds_reset_open_chapter (zone->open_chapter); + + finished_zones =start_closing_chapter (zone->index, zone->id, + zone->writing_chapter); +if ((finished_zones ==1 ) && (zone->index->zone_count >1 )) { + result =announce_chapter_closed (zone, closed_chapter); +if (result !=UDS_SUCCESS ) +return result; + } + + expiring = zone->oldest_virtual_chapter; + expire_chapters =uds_chapters_to_expire (zone->index->volume->geometry, + zone->newest_virtual_chapter); + zone->oldest_virtual_chapter += expire_chapters; + +if (finished_zones < zone->index->zone_count) +return UDS_SUCCESS ; + +while (expire_chapters-- >0 ) +uds_forget_chapter (zone->index->volume, expiring++); + +return UDS_SUCCESS ; +} + +static int handle_chapter_closed (struct index_zone *zone,u64 virtual_chapter) +{ +if (zone->newest_virtual_chapter == virtual_chapter) +return open_next_chapter (zone); + +return UDS_SUCCESS ; +} + +static int dispatch_index_zone_control_request (struct uds_request *request) +{ +struct uds_zone_message *message = &request->zone_message; +struct index_zone *zone = request->index->zones[request->zone_number]; + +switch (message->type) { +case UDS_MESSAGE_SPARSE_CACHE_BARRIER : +return uds_update_sparse_cache (zone, message->virtual_chapter); + +case UDS_MESSAGE_ANNOUNCE_CHAPTER_CLOSED : +return handle_chapter_closed (zone, message->virtual_chapter); + +default : +uds_log_error ("invalid message type: %d" , message->type); +return UDS_INVALID_ARGUMENT ; + } +} + +static void set_request_location (struct uds_request *request, +enum uds_index_region new_location) +{ + request->location = new_location; + request->found = ((new_location ==UDS_LOCATION_IN_OPEN_CHAPTER ) || + (new_location ==UDS_LOCATION_IN_DENSE ) || + (new_location ==UDS_LOCATION_IN_SPARSE )); +} + +static void set_chapter_location (struct uds_request *request, +const struct index_zone *zone,u64 virtual_chapter) +{ + request->found = true; +if (virtual_chapter == zone->newest_virtual_chapter) + request->location =UDS_LOCATION_IN_OPEN_CHAPTER ; +else if (is_zone_chapter_sparse (zone, virtual_chapter)) + request->location =UDS_LOCATION_IN_SPARSE ; +else + request->location =UDS_LOCATION_IN_DENSE ; +} + +static int search_sparse_cache_in_zone (struct index_zone *zone,struct uds_request *request, +u64 virtual_chapter,bool *found) +{ +int result; +struct volume *volume; +u16 record_page_number; +u32 chapter; + + result =uds_search_sparse_cache (zone, &request->record_name, &virtual_chapter, + &record_page_number); +if ((result !=UDS_SUCCESS ) || (virtual_chapter ==NO_CHAPTER )) +return result; + + request->virtual_chapter = virtual_chapter; + volume = zone->index->volume; + chapter =uds_map_to_physical_chapter (volume->geometry, virtual_chapter); +return uds_search_cached_record_page (volume, request, chapter, + record_page_number, found); +} + +static int get_record_from_zone (struct index_zone *zone,struct uds_request *request, +bool *found) +{ +struct volume *volume; + +if (request->location ==UDS_LOCATION_RECORD_PAGE_LOOKUP ) { + *found = true; +return UDS_SUCCESS ; + }else if (request->location ==UDS_LOCATION_UNAVAILABLE ) { + *found = false; +return UDS_SUCCESS ; + } + +if (request->virtual_chapter == zone->newest_virtual_chapter) { +uds_search_open_chapter (zone->open_chapter, &request->record_name, + &request->old_metadata, found); +return UDS_SUCCESS ; + } + +if ((zone->newest_virtual_chapter >0 ) && + (request->virtual_chapter == (zone->newest_virtual_chapter -1 )) && + (zone->writing_chapter->size >0 )) { +uds_search_open_chapter (zone->writing_chapter, &request->record_name, + &request->old_metadata, found); +return UDS_SUCCESS ; + } + + volume = zone->index->volume; +if (is_zone_chapter_sparse (zone, request->virtual_chapter) && +uds_sparse_cache_contains (volume->sparse_cache, request->virtual_chapter, + request->zone_number)) +return search_sparse_cache_in_zone (zone, request, + request->virtual_chapter, found); + +return uds_search_volume_page_cache (volume, request, found); +} + +static int put_record_in_zone (struct index_zone *zone,struct uds_request *request, +const struct uds_record_data *metadata) +{ +unsigned int remaining; + + remaining =uds_put_open_chapter (zone->open_chapter, &request->record_name, + metadata); +if (remaining ==0 ) +return open_next_chapter (zone); + +return UDS_SUCCESS ; +} + +static int search_index_zone (struct index_zone *zone,struct uds_request *request) +{ +int result; +struct volume_index_record record; +bool overflow_record, found = false; +struct uds_record_data *metadata; +u64 chapter; + + result =uds_get_volume_index_record (zone->index->volume_index, + &request->record_name, &record); +if (result !=UDS_SUCCESS ) +return result; + +if (record.is_found) { +if (request->requeued && request->virtual_chapter != record.virtual_chapter) +set_request_location (request,UDS_LOCATION_UNKNOWN ); + + request->virtual_chapter = record.virtual_chapter; + result =get_record_from_zone (zone, request, &found); +if (result !=UDS_SUCCESS ) +return result; + } + +if (found) +set_chapter_location (request, zone, record.virtual_chapter); + +/* +* If a record has overflowed a chapter index in more than one chapter (or overflowed in +* one chapter and collided with an existing record), it will exist as a collision record +* in the volume index, but we won't find it in the volume. This case needs special +* handling. +*/ + overflow_record = (record.is_found && record.is_collision && !found); + chapter = zone->newest_virtual_chapter; +if (found || overflow_record) { +if ((request->type ==UDS_QUERY_NO_UPDATE ) || + ((request->type ==UDS_QUERY ) && overflow_record)) { +/* There is nothing left to do. */ +return UDS_SUCCESS ; + } + +if (record.virtual_chapter != chapter) { +/* +* Update the volume index to reference the new chapter for the block. If +* the record had been deleted or dropped from the chapter index, it will +* be back. +*/ + result =uds_set_volume_index_record_chapter (&record, chapter); + }else if (request->type !=UDS_UPDATE ) { +/* The record is already in the open chapter. */ +return UDS_SUCCESS ; + } + }else { +/* +* The record wasn't in the volume index, so check whether the +* name is in a cached sparse chapter. If we found the name on +* a previous search, use that result instead. +*/ +if (request->location ==UDS_LOCATION_RECORD_PAGE_LOOKUP ) { + found = true; + }else if (request->location ==UDS_LOCATION_UNAVAILABLE ) { + found = false; + }else if (uds_is_sparse_geometry (zone->index->volume->geometry) && + !uds_is_volume_index_sample (zone->index->volume_index, + &request->record_name)) { + result =search_sparse_cache_in_zone (zone, request,NO_CHAPTER , + &found); +if (result !=UDS_SUCCESS ) +return result; + } + +if (found) +set_request_location (request,UDS_LOCATION_IN_SPARSE ); + +if ((request->type ==UDS_QUERY_NO_UPDATE ) || + ((request->type ==UDS_QUERY ) && !found)) { +/* There is nothing left to do. */ +return UDS_SUCCESS ; + } + +/* +* Add a new entry to the volume index referencing the open chapter. This needs to +* be done both for new records, and for records from cached sparse chapters. +*/ + result =uds_put_volume_index_record (&record, chapter); + } + +if (result ==UDS_OVERFLOW ) { +/* +* The volume index encountered a delta list overflow. The condition was already +* logged. We will go on without adding the record to the open chapter. +*/ +return UDS_SUCCESS ; + } + +if (result !=UDS_SUCCESS ) +return result; + +if (!found || (request->type ==UDS_UPDATE )) { +/* This is a new record or we're updating an existing record. */ + metadata = &request->new_metadata; + }else { +/* Move the existing record to the open chapter. */ + metadata = &request->old_metadata; + } + +return put_record_in_zone (zone, request, metadata); +} + +static int remove_from_index_zone (struct index_zone *zone,struct uds_request *request) +{ +int result; +struct volume_index_record record; + + result =uds_get_volume_index_record (zone->index->volume_index, + &request->record_name, &record); +if (result !=UDS_SUCCESS ) +return result; + +if (!record.is_found) +return UDS_SUCCESS ; + +/* If the request was requeued, check whether the saved state is still valid. */ + +if (record.is_collision) { +set_chapter_location (request, zone, record.virtual_chapter); + }else { +/* Non-collision records are hints, so resolve the name in the chapter. */ +bool found; + +if (request->requeued && request->virtual_chapter != record.virtual_chapter) +set_request_location (request,UDS_LOCATION_UNKNOWN ); + + request->virtual_chapter = record.virtual_chapter; + result =get_record_from_zone (zone, request, &found); +if (result !=UDS_SUCCESS ) +return result; + +if (!found) { +/* There is no record to remove. */ +return UDS_SUCCESS ; + } + } + +set_chapter_location (request, zone, record.virtual_chapter); + +/* +* Delete the volume index entry for the named record only. Note that a later search might +* later return stale advice if there is a colliding name in the same chapter, but it's a +* very rare case (1 in 2^21). +*/ + result =uds_remove_volume_index_record (&record); +if (result !=UDS_SUCCESS ) +return result; + +/* +* If the record is in the open chapter, we must remove it or mark it deleted to avoid +* trouble if the record is added again later. +*/ +if (request->location ==UDS_LOCATION_IN_OPEN_CHAPTER ) +uds_remove_from_open_chapter (zone->open_chapter, &request->record_name); + +return UDS_SUCCESS ; +} + +static int dispatch_index_request (struct uds_index *index,struct uds_request *request) +{ +int result; +struct index_zone *zone = index->zones[request->zone_number]; + +if (!request->requeued) { + result =simulate_index_zone_barrier_message (zone, request); +if (result !=UDS_SUCCESS ) +return result; + } + +switch (request->type) { +case UDS_POST : +case UDS_UPDATE : +case UDS_QUERY : +case UDS_QUERY_NO_UPDATE : + result =search_index_zone (zone, request); +break ; + +case UDS_DELETE : + result =remove_from_index_zone (zone, request); +break ; + +default : + result =uds_log_warning_strerror (UDS_INVALID_ARGUMENT , +"invalid request type: %d" , + request->type); +break ; + } + +return result; +} + +/* This is the request processing function invoked by each zone's thread. */ +static void execute_zone_request (struct uds_request *request) +{ +int result; +struct uds_index *index = request->index; + +if (request->zone_message.type !=UDS_MESSAGE_NONE ) { + result =dispatch_index_zone_control_request (request); +if (result !=UDS_SUCCESS ) { +uds_log_error_strerror (result,"error executing message: %d" , + request->zone_message.type); + } + +/* Once the message is processed it can be freed. */ +uds_free (uds_forget (request)); +return ; + } + + index->need_to_save = true; +if (request->requeued && (request->status !=UDS_SUCCESS )) { +set_request_location (request,UDS_LOCATION_UNAVAILABLE ); + index->callback (request); +return ; + } + + result =dispatch_index_request (index, request); +if (result ==UDS_QUEUED ) { +/* The request has been requeued so don't let it complete. */ +return ; + } + +if (!request->found) +set_request_location (request,UDS_LOCATION_UNAVAILABLE ); + + request->status = result; + index->callback (request); +} + +static int initialize_index_queues (struct uds_index *index, +const struct geometry *geometry) +{ +int result; +unsigned int i; + +for (i =0 ; i < index->zone_count; i++) { + result =uds_make_request_queue ("indexW" , &execute_zone_request, + &index->zone_queues[i]); +if (result !=UDS_SUCCESS ) +return result; + } + +/* The triage queue is only needed for sparse multi-zone indexes. */ +if ((index->zone_count >1 ) &&uds_is_sparse_geometry (geometry)) { + result =uds_make_request_queue ("triageW" , &triage_request, + &index->triage_queue); +if (result !=UDS_SUCCESS ) +return result; + } + +return UDS_SUCCESS ; +} + +/* This is the driver function for the chapter writer thread. */ +static void close_chapters (void *arg) +{ +int result; +struct chapter_writer *writer = arg; +struct uds_index *index = writer->index; + +uds_log_debug ("chapter writer starting" ); +uds_lock_mutex (&writer->mutex); +for (;;) { +while (writer->zones_to_write < index->zone_count) { +if (writer->stop && (writer->zones_to_write ==0 )) { +/* +* We've been told to stop, and all of the zones are in the same +* open chapter, so we can exit now. +*/ +uds_unlock_mutex (&writer->mutex); +uds_log_debug ("chapter writer stopping" ); +return ; + } +uds_wait_cond (&writer->cond, &writer->mutex); + } + +/* +* Release the lock while closing a chapter. We probably don't need to do this, but +* it seems safer in principle. It's OK to access the chapter and chapter_number +* fields without the lock since those aren't allowed to change until we're done. +*/ +uds_unlock_mutex (&writer->mutex); + +if (index->has_saved_open_chapter) { +/* +* Remove the saved open chapter the first time we close an open chapter +* after loading from a clean shutdown, or after doing a clean save. The +* lack of the saved open chapter will indicate that a recovery is +* necessary. +*/ + index->has_saved_open_chapter = false; + result =uds_discard_open_chapter (index->layout); +if (result ==UDS_SUCCESS ) +uds_log_debug ("Discarding saved open chapter" ); + } + + result =uds_close_open_chapter (writer->chapters, index->zone_count, + index->volume, + writer->open_chapter_index, + writer->collated_records, + index->newest_virtual_chapter); + +uds_lock_mutex (&writer->mutex); + index->newest_virtual_chapter++; + index->oldest_virtual_chapter += +uds_chapters_to_expire (index->volume->geometry, + index->newest_virtual_chapter); + writer->result = result; + writer->zones_to_write =0 ; +uds_broadcast_cond (&writer->cond); + } +} + +static void stop_chapter_writer (struct chapter_writer *writer) +{ +struct thread *writer_thread =0 ; + +uds_lock_mutex (&writer->mutex); +if (writer->thread !=0 ) { + writer_thread = writer->thread; + writer->thread =0 ; + writer->stop = true; +uds_broadcast_cond (&writer->cond); + } +uds_unlock_mutex (&writer->mutex); + +if (writer_thread !=0 ) +uds_join_threads (writer_thread); +} + +static void free_chapter_writer (struct chapter_writer *writer) +{ +if (writer ==NULL ) +return ; + +stop_chapter_writer (writer); +uds_destroy_mutex (&writer->mutex); +uds_destroy_cond (&writer->cond); +uds_free_open_chapter_index (writer->open_chapter_index); +uds_free (writer->collated_records); +uds_free (writer); +} + +static int make_chapter_writer (struct uds_index *index, +struct chapter_writer **writer_ptr) +{ +int result; +struct chapter_writer *writer; +size_t collated_records_size = + (sizeof (struct uds_volume_record ) * index->volume->geometry->records_per_chapter); + + result = uds_allocate_extended(struct chapter_writer, index->zone_count, + struct open_chapter_zone *, "Chapter Writer", + &writer); +if (result !=UDS_SUCCESS ) +return result; + + writer->index = index; + result =uds_init_mutex (&writer->mutex); +if (result !=UDS_SUCCESS ) { +uds_free (writer); +return result; + } + + result =uds_init_cond (&writer->cond); +if (result !=UDS_SUCCESS ) { +uds_destroy_mutex (&writer->mutex); +uds_free (writer); +return result; + } + + result =uds_allocate_cache_aligned (collated_records_size,"collated records" , + &writer->collated_records); +if (result !=UDS_SUCCESS ) { +free_chapter_writer (writer); +return result; + } + + result =uds_make_open_chapter_index (&writer->open_chapter_index, + index->volume->geometry, + index->volume->nonce); +if (result !=UDS_SUCCESS ) { +free_chapter_writer (writer); +return result; + } + + writer->memory_size = (sizeof (struct chapter_writer ) + + index->zone_count *sizeof (struct open_chapter_zone *) + + collated_records_size + + writer->open_chapter_index->memory_size); + + result =uds_create_thread (close_chapters, writer,"writer" , &writer->thread); +if (result !=UDS_SUCCESS ) { +free_chapter_writer (writer); +return result; + } + + *writer_ptr = writer; +return UDS_SUCCESS ; +} + +static int load_index (struct uds_index *index) +{ +int result; +u64 last_save_chapter; + + result =uds_load_index_state (index->layout, index); +if (result !=UDS_SUCCESS ) +return UDS_INDEX_NOT_SAVED_CLEANLY ; + + last_save_chapter = ((index->last_save !=NO_LAST_SAVE ) ? index->last_save :0 ); + +uds_log_info ("loaded index from chapter %llu through chapter %llu" , + (unsigned long long ) index->oldest_virtual_chapter, + (unsigned long long ) last_save_chapter); + +return UDS_SUCCESS ; +} + +static int rebuild_index_page_map (struct uds_index *index,u64 vcn) +{ +int result; +struct delta_index_page *chapter_index_page; +struct geometry *geometry = index->volume->geometry; +u32 chapter =uds_map_to_physical_chapter (geometry, vcn); +u32 expected_list_number =0 ; +u32 index_page_number; +u32 lowest_delta_list; +u32 highest_delta_list; + +for (index_page_number =0 ; + index_page_number < geometry->index_pages_per_chapter; + index_page_number++) { + result =uds_get_volume_index_page (index->volume, chapter, + index_page_number, + &chapter_index_page); +if (result !=UDS_SUCCESS ) { +return uds_log_error_strerror (result, +"failed to read index page %u in chapter %u" , + index_page_number, chapter); + } + + lowest_delta_list = chapter_index_page->lowest_list_number; + highest_delta_list = chapter_index_page->highest_list_number; +if (lowest_delta_list != expected_list_number) { +return uds_log_error_strerror (UDS_CORRUPT_DATA , +"chapter %u index page %u is corrupt" , + chapter, index_page_number); + } + +uds_update_index_page_map (index->volume->index_page_map, vcn, chapter, + index_page_number, highest_delta_list); + expected_list_number = highest_delta_list +1 ; + } + +return UDS_SUCCESS ; +} + +static int replay_record (struct uds_index *index,const struct uds_record_name *name, +u64 virtual_chapter,bool will_be_sparse_chapter) +{ +int result; +struct volume_index_record record; +bool update_record; + +if (will_be_sparse_chapter && + !uds_is_volume_index_sample (index->volume_index, name)) { +/* +* This entry will be in a sparse chapter after the rebuild completes, and it is +* not a sample, so just skip over it. +*/ +return UDS_SUCCESS ; + } + + result =uds_get_volume_index_record (index->volume_index, name, &record); +if (result !=UDS_SUCCESS ) +return result; + +if (record.is_found) { +if (record.is_collision) { +if (record.virtual_chapter == virtual_chapter) { +/* The record is already correct. */ +return UDS_SUCCESS ; + } + + update_record = true; + }else if (record.virtual_chapter == virtual_chapter) { +/* +* There is a volume index entry pointing to the current chapter, but we +* don't know if it is for the same name as the one we are currently +* working on or not. For now, we're just going to assume that it isn't. +* This will create one extra collision record if there was a deleted +* record in the current chapter. +*/ + update_record = false; + }else { +/* +* If we're rebuilding, we don't normally want to go to disk to see if the +* record exists, since we will likely have just read the record from disk +* (i.e. we know it's there). The exception to this is when we find an +* entry in the volume index that has a different chapter. In this case, we +* need to search that chapter to determine if the volume index entry was +* for the same record or a different one. +*/ + result =uds_search_volume_page_cache_for_rebuild (index->volume, + name, + record.virtual_chapter, + &update_record); +if (result !=UDS_SUCCESS ) +return result; + } + }else { + update_record = false; + } + +if (update_record) { +/* +* Update the volume index to reference the new chapter for the block. If the +* record had been deleted or dropped from the chapter index, it will be back. +*/ + result =uds_set_volume_index_record_chapter (&record, virtual_chapter); + }else { +/* +* Add a new entry to the volume index referencing the open chapter. This should be +* done regardless of whether we are a brand new record or a sparse record, i.e. +* one that doesn't exist in the index but does on disk, since for a sparse record, +* we would want to un-sparsify if it did exist. +*/ + result =uds_put_volume_index_record (&record, virtual_chapter); + } + +if ((result ==UDS_DUPLICATE_NAME ) || (result ==UDS_OVERFLOW )) { +/* The rebuilt index will lose these records. */ +return UDS_SUCCESS ; + } + +return result; +} + +static bool check_for_suspend (struct uds_index *index) +{ +bool closing; + +if (index->load_context ==NULL ) +return false; + +uds_lock_mutex (&index->load_context->mutex); +if (index->load_context->status !=INDEX_SUSPENDING ) { +uds_unlock_mutex (&index->load_context->mutex); +return false; + } + +/* Notify that we are suspended and wait for the resume. */ + index->load_context->status =INDEX_SUSPENDED ; +uds_broadcast_cond (&index->load_context->cond); + +while ((index->load_context->status !=INDEX_OPENING ) && + (index->load_context->status !=INDEX_FREEING )) +uds_wait_cond (&index->load_context->cond, &index->load_context->mutex); + + closing = (index->load_context->status ==INDEX_FREEING ); +uds_unlock_mutex (&index->load_context->mutex); +return closing; +} + +static int replay_chapter (struct uds_index *index,u64 virtual,bool sparse) +{ +int result; +u32 i; +u32 j; +const struct geometry *geometry; +u32 physical_chapter; + +if (check_for_suspend (index)) { +uds_log_info ("Replay interrupted by index shutdown at chapter %llu" , + (unsigned long long ) virtual); +return -EBUSY ; + } + + geometry = index->volume->geometry; + physical_chapter =uds_map_to_physical_chapter (geometry, virtual); +uds_prefetch_volume_chapter (index->volume, physical_chapter); +uds_set_volume_index_open_chapter (index->volume_index, virtual); + + result =rebuild_index_page_map (index, virtual); +if (result !=UDS_SUCCESS ) { +return uds_log_error_strerror (result, +"could not rebuild index page map for chapter %u" , + physical_chapter); + } + +for (i =0 ; i < geometry->record_pages_per_chapter; i++) { +u8 *record_page; +u32 record_page_number; + + record_page_number = geometry->index_pages_per_chapter + i; + result =uds_get_volume_record_page (index->volume, physical_chapter, + record_page_number, &record_page); +if (result !=UDS_SUCCESS ) { +return uds_log_error_strerror (result,"could not get page %d" , + record_page_number); + } + +for (j =0 ; j < geometry->records_per_page; j++) { +const u8 *name_bytes; +struct uds_record_name name; + + name_bytes = record_page + (j *BYTES_PER_RECORD ); +memcpy (&name.name, name_bytes,UDS_RECORD_NAME_SIZE ); + result =replay_record (index, &name, virtual, sparse); +if (result !=UDS_SUCCESS ) +return result; + } + } + +return UDS_SUCCESS ; +} + +static int replay_volume (struct uds_index *index) +{ +int result; +u64 old_map_update; +u64 new_map_update; +u64 virtual; +u64 from_virtual = index->oldest_virtual_chapter; +u64 upto_virtual = index->newest_virtual_chapter; +bool will_be_sparse; + +uds_log_info ("Replaying volume from chapter %llu through chapter %llu" , + (unsigned long long ) from_virtual, + (unsigned long long ) upto_virtual); + +/* +* The index failed to load, so the volume index is empty. Add records to the volume index +* in order, skipping non-hooks in chapters which will be sparse to save time. +* +* Go through each record page of each chapter and add the records back to the volume +* index. This should not cause anything to be written to either the open chapter or the +* on-disk volume. Also skip the on-disk chapter corresponding to upto_virtual, as this +* would have already been purged from the volume index when the chapter was opened. +* +* Also, go through each index page for each chapter and rebuild the index page map. +*/ + old_map_update = index->volume->index_page_map->last_update; +for (virtual = from_virtual; virtual < upto_virtual; virtual++) { + will_be_sparse =uds_is_chapter_sparse (index->volume->geometry, + from_virtual, upto_virtual, + virtual); + result =replay_chapter (index, virtual, will_be_sparse); +if (result !=UDS_SUCCESS ) +return result; + } + +/* Also reap the chapter being replaced by the open chapter. */ +uds_set_volume_index_open_chapter (index->volume_index, upto_virtual); + + new_map_update = index->volume->index_page_map->last_update; +if (new_map_update != old_map_update) { +uds_log_info ("replay changed index page map update from %llu to %llu" , + (unsigned long long ) old_map_update, + (unsigned long long ) new_map_update); + } + +return UDS_SUCCESS ; +} + +static int rebuild_index (struct uds_index *index) +{ +int result; +u64 lowest; +u64 highest; +bool is_empty = false; +u32 chapters_per_volume = index->volume->geometry->chapters_per_volume; + + index->volume->lookup_mode =LOOKUP_FOR_REBUILD ; + result =uds_find_volume_chapter_boundaries (index->volume, &lowest, &highest, + &is_empty); +if (result !=UDS_SUCCESS ) { +return uds_log_fatal_strerror (result, +"cannot rebuild index: unknown volume chapter boundaries" ); + } + +if (is_empty) { + index->newest_virtual_chapter =0 ; + index->oldest_virtual_chapter =0 ; + index->volume->lookup_mode =LOOKUP_NORMAL ; +return UDS_SUCCESS ; + } + + index->newest_virtual_chapter = highest +1 ; + index->oldest_virtual_chapter = lowest; +if (index->newest_virtual_chapter == + (index->oldest_virtual_chapter + chapters_per_volume)) { +/* Skip the chapter shadowed by the open chapter. */ + index->oldest_virtual_chapter++; + } + + result =replay_volume (index); +if (result !=UDS_SUCCESS ) +return result; + + index->volume->lookup_mode =LOOKUP_NORMAL ; +return UDS_SUCCESS ; +} + +static void free_index_zone (struct index_zone *zone) +{ +if (zone ==NULL ) +return ; + +uds_free_open_chapter (zone->open_chapter); +uds_free_open_chapter (zone->writing_chapter); +uds_free (zone); +} + +static int make_index_zone (struct uds_index *index,unsigned int zone_number) +{ +int result; +struct index_zone *zone; + + result = uds_allocate(1, struct index_zone, "index zone", &zone); +if (result !=UDS_SUCCESS ) +return result; + + result =uds_make_open_chapter (index->volume->geometry, index->zone_count, + &zone->open_chapter); +if (result !=UDS_SUCCESS ) { +free_index_zone (zone); +return result; + } + + result =uds_make_open_chapter (index->volume->geometry, index->zone_count, + &zone->writing_chapter); +if (result !=UDS_SUCCESS ) { +free_index_zone (zone); +return result; + } + + zone->index = index; + zone->id = zone_number; + index->zones[zone_number] = zone; + +return UDS_SUCCESS ; +} + +int uds_make_index (struct configuration *config,enum uds_open_index_type open_type, +struct index_load_context *load_context,index_callback_fn callback, +struct uds_index **new_index) +{ +int result; +bool loaded = false; +bool new = (open_type ==UDS_CREATE ); +struct uds_index *index =NULL ; +struct index_zone *zone; +u64 nonce; +unsigned int z; + + result = uds_allocate_extended(struct uds_index, config->zone_count, + struct uds_request_queue *, "index", &index); +if (result !=UDS_SUCCESS ) +return result; + + index->zone_count = config->zone_count; + + result =uds_make_index_layout (config, new, &index->layout); +if (result !=UDS_SUCCESS ) { +uds_free_index (index); +return result; + } + + result = uds_allocate(index->zone_count, struct index_zone *, "zones", + &index->zones); +if (result !=UDS_SUCCESS ) { +uds_free_index (index); +return result; + } + + result =uds_make_volume (config, index->layout, &index->volume); +if (result !=UDS_SUCCESS ) { +uds_free_index (index); +return result; + } + + index->volume->lookup_mode =LOOKUP_NORMAL ; +for (z =0 ; z < index->zone_count; z++) { + result =make_index_zone (index, z); +if (result !=UDS_SUCCESS ) { +uds_free_index (index); +return uds_log_error_strerror (result, +"Could not create index zone" ); + } + } + + nonce =uds_get_volume_nonce (index->layout); + result =uds_make_volume_index (config, nonce, &index->volume_index); +if (result !=UDS_SUCCESS ) { +uds_free_index (index); +return uds_log_error_strerror (result,"could not make volume index" ); + } + + index->load_context = load_context; + index->callback = callback; + + result =initialize_index_queues (index, config->geometry); +if (result !=UDS_SUCCESS ) { +uds_free_index (index); +return result; + } + + result =make_chapter_writer (index, &index->chapter_writer); +if (result !=UDS_SUCCESS ) { +uds_free_index (index); +return result; + } + +if (!new) { + result =load_index (index); +switch (result) { +case UDS_SUCCESS : + loaded = true; +break ; +case -ENOMEM : +/* We should not try a rebuild for this error. */ +uds_log_error_strerror (result,"index could not be loaded" ); +break ; +default : +uds_log_error_strerror (result,"index could not be loaded" ); +if (open_type ==UDS_LOAD ) { + result =rebuild_index (index); +if (result !=UDS_SUCCESS ) { +uds_log_error_strerror (result, +"index could not be rebuilt" ); + } + } +break ; + } + } + +if (result !=UDS_SUCCESS ) { +uds_free_index (index); +return uds_log_error_strerror (result,"fatal error in %s()" , __func__); + } + +for (z =0 ; z < index->zone_count; z++) { + zone = index->zones[z]; + zone->oldest_virtual_chapter = index->oldest_virtual_chapter; + zone->newest_virtual_chapter = index->newest_virtual_chapter; + } + +if (index->load_context !=NULL ) { +uds_lock_mutex (&index->load_context->mutex); + index->load_context->status =INDEX_READY ; +/* +* If we get here, suspend is meaningless, but notify any thread trying to suspend +* us so it doesn't hang. +*/ +uds_broadcast_cond (&index->load_context->cond); +uds_unlock_mutex (&index->load_context->mutex); + } + + index->has_saved_open_chapter = loaded; + index->need_to_save = !loaded; + *new_index = index; +return UDS_SUCCESS ; +} + +void uds_free_index (struct uds_index *index) +{ +unsigned int i; + +if (index ==NULL ) +return ; + +uds_request_queue_finish (index->triage_queue); +for (i =0 ; i < index->zone_count; i++) +uds_request_queue_finish (index->zone_queues[i]); + +free_chapter_writer (index->chapter_writer); + +uds_free_volume_index (index->volume_index); +if (index->zones !=NULL ) { +for (i =0 ; i < index->zone_count; i++) +free_index_zone (index->zones[i]); +uds_free (index->zones); + } + +uds_free_volume (index->volume); +uds_free_index_layout (uds_forget (index->layout)); +uds_free (index); +} + +/* Wait for the chapter writer to complete any outstanding writes. */ +void uds_wait_for_idle_index (struct uds_index *index) +{ +struct chapter_writer *writer = index->chapter_writer; + +uds_lock_mutex (&writer->mutex); +while (writer->zones_to_write >0 ) +uds_wait_cond (&writer->cond, &writer->mutex); +uds_unlock_mutex (&writer->mutex); +} + +/* This function assumes that all requests have been drained. */ +int uds_save_index (struct uds_index *index) +{ +int result; + +if (!index->need_to_save) +return UDS_SUCCESS ; + +uds_wait_for_idle_index (index); + index->prev_save = index->last_save; + index->last_save = ((index->newest_virtual_chapter ==0 ) ? +NO_LAST_SAVE : + index->newest_virtual_chapter -1 ); +uds_log_info ("beginning save (vcn %llu)" , (unsigned long long ) index->last_save); + + result =uds_save_index_state (index->layout, index); +if (result !=UDS_SUCCESS ) { +uds_log_info ("save index failed" ); + index->last_save = index->prev_save; + }else { + index->has_saved_open_chapter = true; + index->need_to_save = false; +uds_log_info ("finished save (vcn %llu)" , + (unsigned long long ) index->last_save); + } + +return result; +} + +int uds_replace_index_storage (struct uds_index *index,struct block_device *bdev) +{ +return uds_replace_volume_storage (index->volume, index->layout, bdev); +} + +/* Accessing statistics should be safe from any thread. */ +void uds_get_index_stats (struct uds_index *index,struct uds_index_stats *counters) +{ +struct volume_index_stats stats; + +uds_get_volume_index_stats (index->volume_index, &stats); + counters->entries_indexed = stats.record_count; + counters->collisions = stats.collision_count; + counters->entries_discarded = stats.discard_count; + + counters->memory_used = (index->volume_index->memory_size + + index->volume->cache_size + + index->chapter_writer->memory_size); +} + +void uds_enqueue_request (struct uds_request *request,enum request_stage stage) +{ +struct uds_index *index = request->index; +struct uds_request_queue *queue; + +switch (stage) { +case STAGE_TRIAGE : +if (index->triage_queue !=NULL ) { + queue = index->triage_queue; +break ; + } + + fallthrough; + +case STAGE_INDEX : + request->zone_number = +uds_get_volume_index_zone (index->volume_index, &request->record_name); + fallthrough; + +case STAGE_MESSAGE : + queue = index->zone_queues[request->zone_number]; +break ; + +default : +ASSERT_LOG_ONLY (false,"invalid index stage: %d" , stage); +return ; + } + +uds_request_queue_enqueue (queue, request); +}
drivers/md/dm-vdo/index.h new file +83 -0
83 lines not on this page · raw message
drivers/md/dm-vdo/sparse-cache.c new file +580 -0
580 lines not on this page · raw message
drivers/md/dm-vdo/sparse-cache.h new file +46 -0
46 lines not on this page · raw message
Signature · 1 line
2.40.0
Matthew Sakai
maintainerPATCH v5 18/40 dm vdo: add vio, the request object for vdo metadata
In reply to Matthew SakaiAdd the data and methods that implement the vio object that is basic unit of I/O in vdo.
--- drivers/md/dm-vdo/vio.c | 501 ++++++++++++++++++++++++++++++++++++++++ drivers/md/dm-vdo/vio.h | 199 ++++++++++++++++ 2 files changed, 700 insertions(+) create mode 100644 drivers/md/dm-vdo/vio.c create mode 100644 drivers/md/dm-vdo/vio.h
drivers/md/dm-vdo/vio.c new file +501 -0
@@ -0,0 +1,501 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* +* Copyright 2023 Red Hat +*/ + +#include "vio.h" + +#include <linux/bio.h> +#include <linux/blkdev.h> +#include <linux/kernel.h> +#include <linux/ratelimit.h> + +#include "logger.h" +#include "memory-alloc.h" +#include "permassert.h" + +#include "constants.h" +#include "io-submitter.h" +#include "vdo.h" + +/* A vio_pool is a collection of preallocated vios. */ +struct vio_pool { +/** The number of objects managed by the pool */ +size_t size; +/** The list of objects which are available */ +struct list_head available; +/** The queue of requestors waiting for objects from the pool */ +struct wait_queue waiting; +/** The number of objects currently in use */ +size_t busy_count; +/** The list of objects which are in use */ +struct list_head busy; +/** The ID of the thread on which this pool may be used */ +thread_id_t thread_id; +/** The buffer backing the pool's vios */ +char *buffer; +/** The pool entries */ +struct pooled_vio vios[]; +}; + +physical_block_number_t pbn_from_vio_bio (struct bio *bio) +{ +struct vio *vio = bio->bi_private; +struct vdo *vdo = vio->completion.vdo; +physical_block_number_t pbn = bio->bi_iter.bi_sector /VDO_SECTORS_PER_BLOCK ; + +return ((pbn ==VDO_GEOMETRY_BLOCK_LOCATION ) ? pbn : pbn + vdo->geometry.bio_offset); +} + +static int create_multi_block_bio (block_count_t size,struct bio **bio_ptr) +{ +struct bio *bio =NULL ; +int result; + + result = uds_allocate_extended(struct bio, size + 1, struct bio_vec, +"bio" , &bio); +if (result !=VDO_SUCCESS ) +return result; + + *bio_ptr = bio; +return VDO_SUCCESS ; +} + +int vdo_create_bio (struct bio **bio_ptr) +{ +return create_multi_block_bio (1 , bio_ptr); +} + +void vdo_free_bio (struct bio *bio) +{ +if (bio ==NULL ) +return ; + +bio_uninit (bio); +uds_free (uds_forget (bio)); +} + +int allocate_vio_components (struct vdo *vdo,enum vio_type vio_type, +enum vio_priority priority,void *parent, +unsigned int block_count,char *data,struct vio *vio) +{ +struct bio *bio; +int result; + + result =ASSERT (block_count <=MAX_BLOCKS_PER_VIO , +"block count %u does not exceed maximum %u" , block_count, +MAX_BLOCKS_PER_VIO ); +if (result !=VDO_SUCCESS ) +return result; + + result =ASSERT (((vio_type !=VIO_TYPE_UNINITIALIZED ) && (vio_type !=VIO_TYPE_DATA )), +"%d is a metadata type" , vio_type); +if (result !=VDO_SUCCESS ) +return result; + + result =create_multi_block_bio (block_count, &bio); +if (result !=VDO_SUCCESS ) +return result; + +initialize_vio (vio, bio, block_count, vio_type, priority, vdo); + vio->completion.parent = parent; + vio->data = data; +return VDO_SUCCESS ; +} + +/** +* create_multi_block_metadata_vio() - Create a vio. +* @vdo: The vdo on which the vio will operate. +* @vio_type: The type of vio to create. +* @priority: The relative priority to assign to the vio. +* @parent: The parent of the vio. +* @block_count: The size of the vio in blocks. +* @data: The buffer. +* @vio_ptr: A pointer to hold the new vio. +* +* Return: VDO_SUCCESS or an error. +*/ +int create_multi_block_metadata_vio (struct vdo *vdo,enum vio_type vio_type, +enum vio_priority priority,void *parent, +unsigned int block_count,char *data, +struct vio **vio_ptr) +{ +struct vio *vio; +int result; + +/* If struct vio grows past 256 bytes, we'll lose benefits of VDOSTORY-176. */ +BUILD_BUG_ON (sizeof (struct vio ) >256 ); + +/* +* Metadata vios should use direct allocation and not use the buffer pool, which is +* reserved for submissions from the linux block layer. +*/ + result = uds_allocate(1, struct vio, __func__, &vio); +if (result !=VDO_SUCCESS ) { +uds_log_error ("metadata vio allocation failure %d" , result); +return result; + } + + result =allocate_vio_components (vdo, vio_type, priority, parent, block_count, + data, vio); +if (result !=VDO_SUCCESS ) { +uds_free (vio); +return result; + } + + *vio_ptr = vio; +return VDO_SUCCESS ; +} + +/** +* free_vio_components() - Free the components of a vio embedded in a larger structure. +* @vio: The vio to destroy +*/ +void free_vio_components (struct vio *vio) +{ +if (vio ==NULL ) +return ; + +BUG_ON (is_data_vio (vio)); +vdo_free_bio (uds_forget (vio->bio)); +} + +/** +* free_vio() - Destroy a vio. +* @vio: The vio to destroy. +*/ +void free_vio (struct vio *vio) +{ +free_vio_components (vio); +uds_free (vio); +} + +/* Set bio properties for a VDO read or write. */ +void vdo_set_bio_properties (struct bio *bio,struct vio *vio,bio_end_io_t callback, +unsigned int bi_opf,physical_block_number_t pbn) +{ +struct vdo *vdo = vio->completion.vdo; +struct device_config *config = vdo->device_config; + + pbn -= vdo->geometry.bio_offset; + vio->bio_zone = ((pbn / config->thread_counts.bio_rotation_interval) % + config->thread_counts.bio_threads); + + bio->bi_private = vio; + bio->bi_end_io = callback; + bio->bi_opf = bi_opf; + bio->bi_iter.bi_sector = pbn *VDO_SECTORS_PER_BLOCK ; +} + +/* +* Prepares the bio to perform IO with the specified buffer. May only be used on a VDO-allocated +* bio, as it assumes the bio wraps a 4k buffer that is 4k aligned, but there does not have to be a +* vio associated with the bio. +*/ +int vio_reset_bio (struct vio *vio,char *data,bio_end_io_t callback, +unsigned int bi_opf,physical_block_number_t pbn) +{ +int bvec_count, offset, len, i; +struct bio *bio = vio->bio; + +bio_reset (bio, bio->bi_bdev, bi_opf); +vdo_set_bio_properties (bio, vio, callback, bi_opf, pbn); +if (data ==NULL ) +return VDO_SUCCESS ; + + bio->bi_io_vec = bio->bi_inline_vecs; + bio->bi_max_vecs = vio->block_count +1 ; + len =VDO_BLOCK_SIZE * vio->block_count; + offset =offset_in_page (data); + bvec_count =DIV_ROUND_UP (offset + len,PAGE_SIZE ); + +/* +* If we knew that data was always on one page, or contiguous pages, we wouldn't need the +* loop. But if we're using vmalloc, it's not impossible that the data is in different +* pages that can't be merged in bio_add_page... +*/ +for (i =0 ; (i < bvec_count) && (len >0 ); i++) { +struct page *page; +int bytes_added; +int bytes =PAGE_SIZE - offset; + +if (bytes > len) + bytes = len; + + page =is_vmalloc_addr (data) ?vmalloc_to_page (data) :virt_to_page (data); + bytes_added =bio_add_page (bio, page, bytes, offset); + +if (bytes_added != bytes) { +return uds_log_error_strerror (VDO_BIO_CREATION_FAILED , +"Could only add %i bytes to bio" , + bytes_added); + } + + data += bytes; + len -= bytes; + offset =0 ; + } + +return VDO_SUCCESS ; +} + +/** +* update_vio_error_stats() - Update per-vio error stats and log the error. +* @vio: The vio which got an error. +* @format: The format of the message to log (a printf style format). +*/ +void update_vio_error_stats (struct vio *vio,const char *format, ...) +{ + static DEFINE_RATELIMIT_STATE(error_limiter, DEFAULT_RATELIMIT_INTERVAL, + DEFAULT_RATELIMIT_BURST); +va_list args; +int priority; +struct vdo *vdo = vio->completion.vdo; + +switch (vio->completion.result) { +case VDO_READ_ONLY : +atomic64_inc (&vdo->stats.read_only_error_count); +return ; + +case VDO_NO_SPACE : +atomic64_inc (&vdo->stats.no_space_error_count); + priority =UDS_LOG_DEBUG ; +break ; + +default : + priority =UDS_LOG_ERR ; + } + +if (!__ratelimit (&error_limiter)) +return ; + +va_start (args, format); +uds_vlog_strerror (priority, vio->completion.result,UDS_LOGGING_MODULE_NAME , + format, args); +va_end (args); +} + +void vio_record_metadata_io_error (struct vio *vio) +{ +const char *description; +physical_block_number_t pbn =pbn_from_vio_bio (vio->bio); + +if (bio_op (vio->bio) ==REQ_OP_READ ) { + description ="read" ; + }else if ((vio->bio->bi_opf &REQ_PREFLUSH ) ==REQ_PREFLUSH ) { + description = (((vio->bio->bi_opf &REQ_FUA ) ==REQ_FUA ) ? +"write+preflush+fua" : +"write+preflush" ); + }else if ((vio->bio->bi_opf &REQ_FUA ) ==REQ_FUA ) { + description ="write+fua" ; + }else { + description ="write" ; + } + +update_vio_error_stats (vio, +"Completing %s vio of type %u for physical block %llu with error" , + description, vio->type, (unsigned long long ) pbn); +} + +/** +* make_vio_pool() - Create a new vio pool. +* @vdo: The vdo. +* @pool_size: The number of vios in the pool. +* @thread_id: The ID of the thread using this pool. +* @vio_type: The type of vios in the pool. +* @priority: The priority with which vios from the pool should be enqueued. +* @context: The context that each entry will have. +* @pool_ptr: The resulting pool. +* +* Return: A success or error code. +*/ +int make_vio_pool (struct vdo *vdo,size_t pool_size,thread_id_t thread_id, +enum vio_type vio_type,enum vio_priority priority,void *context, +struct vio_pool **pool_ptr) +{ +struct vio_pool *pool; +char *ptr; +int result; + + result = uds_allocate_extended(struct vio_pool, pool_size, struct pooled_vio, + __func__, &pool); +if (result !=VDO_SUCCESS ) +return result; + + pool->thread_id = thread_id; +INIT_LIST_HEAD (&pool->available); +INIT_LIST_HEAD (&pool->busy); + + result =uds_allocate (pool_size *VDO_BLOCK_SIZE , char, +"VIO pool buffer" , &pool->buffer); +if (result !=VDO_SUCCESS ) { +free_vio_pool (pool); +return result; + } + + ptr = pool->buffer; +for (pool->size =0 ; pool->size < pool_size; pool->size++, ptr +=VDO_BLOCK_SIZE ) { +struct pooled_vio *pooled = &pool->vios[pool->size]; + + result =allocate_vio_components (vdo, vio_type, priority,NULL ,1 , ptr, + &pooled->vio); +if (result !=VDO_SUCCESS ) { +free_vio_pool (pool); +return result; + } + + pooled->context = context; +list_add_tail (&pooled->pool_entry, &pool->available); + } + + *pool_ptr = pool; +return VDO_SUCCESS ; +} + +/** +* free_vio_pool() - Destroy a vio pool. +* @pool: The pool to free. +*/ +void free_vio_pool (struct vio_pool *pool) +{ +struct pooled_vio *pooled, *tmp; + +if (pool ==NULL ) +return ; + +/* Remove all available vios from the object pool. */ +ASSERT_LOG_ONLY (!vdo_has_waiters (&pool->waiting), +"VIO pool must not have any waiters when being freed" ); +ASSERT_LOG_ONLY ((pool->busy_count ==0 ), +"VIO pool must not have %zu busy entries when being freed" , + pool->busy_count); +ASSERT_LOG_ONLY (list_empty (&pool->busy), +"VIO pool must not have busy entries when being freed" ); + +list_for_each_entry_safe (pooled, tmp, &pool->available, pool_entry) { +list_del (&pooled->pool_entry); +free_vio_components (&pooled->vio); + pool->size--; + } + +ASSERT_LOG_ONLY (pool->size ==0 , +"VIO pool must not have missing entries when being freed" ); + +uds_free (uds_forget (pool->buffer)); +uds_free (pool); +} + +/** +* is_vio_pool_busy() - Check whether an vio pool has outstanding entries. +* +* Return: true if the pool is busy. +*/ +bool is_vio_pool_busy (struct vio_pool *pool) +{ +return (pool->busy_count !=0 ); +} + +/** +* acquire_vio_from_pool() - Acquire a vio and buffer from the pool (asynchronous). +* @pool: The vio pool. +* @waiter: Object that is requesting a vio. +*/ +void acquire_vio_from_pool (struct vio_pool *pool,struct waiter *waiter) +{ +struct pooled_vio *pooled; + +ASSERT_LOG_ONLY ((pool->thread_id ==vdo_get_callback_thread_id ()), +"acquire from active vio_pool called from correct thread" ); + +if (list_empty (&pool->available)) { +vdo_enqueue_waiter (&pool->waiting, waiter); +return ; + } + + pooled = list_first_entry(&pool->available, struct pooled_vio, pool_entry); + pool->busy_count++; +list_move_tail (&pooled->pool_entry, &pool->busy); + (*waiter->callback)(waiter, pooled); +} + +/** +* return_vio_to_pool() - Return a vio to the pool +* @pool: The vio pool. +* @vio: The pooled vio to return. +*/ +void return_vio_to_pool (struct vio_pool *pool,struct pooled_vio *vio) +{ +ASSERT_LOG_ONLY ((pool->thread_id ==vdo_get_callback_thread_id ()), +"vio pool entry returned on same thread as it was acquired" ); + + vio->vio.completion.error_handler =NULL ; + vio->vio.completion.parent =NULL ; +if (vdo_has_waiters (&pool->waiting)) { +vdo_notify_next_waiter (&pool->waiting,NULL , vio); +return ; + } + +list_move_tail (&vio->pool_entry, &pool->available); + --pool->busy_count; +} + +/* +* Various counting functions for statistics. +* These are used for bios coming into VDO, as well as bios generated by VDO. +*/ +void vdo_count_bios (struct atomic_bio_stats *bio_stats,struct bio *bio) +{ +if (((bio->bi_opf &REQ_PREFLUSH ) !=0 ) && (bio->bi_iter.bi_size ==0 )) { +atomic64_inc (&bio_stats->empty_flush); +atomic64_inc (&bio_stats->flush); +return ; + } + +switch (bio_op (bio)) { +case REQ_OP_WRITE : +atomic64_inc (&bio_stats->write); +break ; +case REQ_OP_READ : +atomic64_inc (&bio_stats->read); +break ; +case REQ_OP_DISCARD : +atomic64_inc (&bio_stats->discard); +break ; +/* +* All other operations are filtered out in dmvdo.c, or not created by VDO, so +* shouldn't exist. +*/ +default : +ASSERT_LOG_ONLY (0 ,"Bio operation %d not a write, read, discard, or empty flush" , +bio_op (bio)); + } + +if ((bio->bi_opf &REQ_PREFLUSH ) !=0 ) +atomic64_inc (&bio_stats->flush); +if (bio->bi_opf &REQ_FUA ) +atomic64_inc (&bio_stats->fua); +} + +static void count_all_bios_completed (struct vio *vio,struct bio *bio) +{ +struct atomic_statistics *stats = &vio->completion.vdo->stats; + +if (is_data_vio (vio)) { +vdo_count_bios (&stats->bios_out_completed, bio); +return ; + } + +vdo_count_bios (&stats->bios_meta_completed, bio); +if (vio->type ==VIO_TYPE_RECOVERY_JOURNAL ) +vdo_count_bios (&stats->bios_journal_completed, bio); +else if (vio->type ==VIO_TYPE_BLOCK_MAP ) +vdo_count_bios (&stats->bios_page_cache_completed, bio); +} + +void vdo_count_completed_bios (struct bio *bio) +{ +struct vio *vio = (struct vio *) bio->bi_private; + +atomic64_inc (&vio->completion.vdo->stats.bios_completed); +count_all_bios_completed (vio, bio); +}
drivers/md/dm-vdo/vio.h new file +199 -0
199 lines not on this page · raw message
Signature · 1 line
2.40.0
Matthew Sakai
maintainerPATCH v5 19/40 dm vdo: add data_vio, the request object which services incoming bios
In reply to Matthew SakaiAdd the data and methods that implement the data_vio object that handles user data bios as they are processed.
--- drivers/md/dm-vdo/data-vio.c | 2057 ++++++++++++++++++++++++++++++++++ drivers/md/dm-vdo/data-vio.h | 669 +++++++++++ 2 files changed, 2726 insertions(+) create mode 100644 drivers/md/dm-vdo/data-vio.c create mode 100644 drivers/md/dm-vdo/data-vio.h
drivers/md/dm-vdo/data-vio.c new file +2057 -0
@@ -0,0 +1,2057 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* +* Copyright 2023 Red Hat +*/ + +#include "data-vio.h" + +#include <linux/atomic.h> +#include <linux/bio.h> +#include <linux/blkdev.h> +#include <linux/delay.h> +#include <linux/device-mapper.h> +#include <linux/jiffies.h> +#include <linux/kernel.h> +#include <linux/list.h> +#include <linux/lz4.h> +#include <linux/minmax.h> +#include <linux/sched.h> +#include <linux/spinlock.h> +#include <linux/wait.h> + +#include "logger.h" +#include "memory-alloc.h" +#include "murmurhash3.h" +#include "permassert.h" + +#include "block-map.h" +#include "dump.h" +#include "encodings.h" +#include "int-map.h" +#include "io-submitter.h" +#include "logical-zone.h" +#include "packer.h" +#include "recovery-journal.h" +#include "slab-depot.h" +#include "status-codes.h" +#include "types.h" +#include "vdo.h" +#include "vio.h" +#include "wait-queue.h" + +/** +* DOC: Bio flags. +* +* For certain flags set on user bios, if the user bio has not yet been acknowledged, setting those +* flags on our own bio(s) for that request may help underlying layers better fulfill the user +* bio's needs. This constant contains the aggregate of those flags; VDO strips all the other +* flags, as they convey incorrect information. +* +* These flags are always irrelevant if we have already finished the user bio as they are only +* hints on IO importance. If VDO has finished the user bio, any remaining IO done doesn't care how +* important finishing the finished bio was. +* +* Note that bio.c contains the complete list of flags we believe may be set; the following list +* explains the action taken with each of those flags VDO could receive: +* +* * REQ_SYNC: Passed down if the user bio is not yet completed, since it indicates the user bio +* completion is required for further work to be done by the issuer. +* * REQ_META: Passed down if the user bio is not yet completed, since it may mean the lower layer +* treats it as more urgent, similar to REQ_SYNC. +* * REQ_PRIO: Passed down if the user bio is not yet completed, since it indicates the user bio is +* important. +* * REQ_NOMERGE: Set only if the incoming bio was split; irrelevant to VDO IO. +* * REQ_IDLE: Set if the incoming bio had more IO quickly following; VDO's IO pattern doesn't +* match incoming IO, so this flag is incorrect for it. +* * REQ_FUA: Handled separately, and irrelevant to VDO IO otherwise. +* * REQ_RAHEAD: Passed down, as, for reads, it indicates trivial importance. +* * REQ_BACKGROUND: Not passed down, as VIOs are a limited resource and VDO needs them recycled +* ASAP to service heavy load, which is the only place where REQ_BACKGROUND might aid in load +* prioritization. +*/ +static unsigned int PASSTHROUGH_FLAGS = (REQ_PRIO |REQ_META |REQ_SYNC |REQ_RAHEAD ); + +/** +* DOC: +* +* The data_vio_pool maintains the pool of data_vios which a vdo uses to service incoming bios. For +* correctness, and in order to avoid potentially expensive or blocking memory allocations during +* normal operation, the number of concurrently active data_vios is capped. Furthermore, in order +* to avoid starvation of reads and writes, at most 75% of the data_vios may be used for +* discards. The data_vio_pool is responsible for enforcing these limits. Threads submitting bios +* for which a data_vio or discard permit are not available will block until the necessary +* resources are available. The pool is also responsible for distributing resources to blocked +* threads and waking them. Finally, the pool attempts to batch the work of recycling data_vios by +* performing the work of actually assigning resources to blocked threads or placing data_vios back +* into the pool on a single cpu at a time. +* +* The pool contains two "limiters", one for tracking data_vios and one for tracking discard +* permits. The limiters also provide safe cross-thread access to pool statistics without the need +* to take the pool's lock. When a thread submits a bio to a vdo device, it will first attempt to +* get a discard permit if it is a discard, and then to get a data_vio. If the necessary resources +* are available, the incoming bio will be assigned to the acquired data_vio, and it will be +* launched. However, if either of these are unavailable, the arrival time of the bio is recorded +* in the bio's bi_private field, the bio and its submitter are both queued on the appropriate +* limiter and the submitting thread will then put itself to sleep. (note that this mechanism will +* break if jiffies are only 32 bits.) +* +* Whenever a data_vio has completed processing for the bio it was servicing, release_data_vio() +* will be called on it. This function will add the data_vio to a funnel queue, and then check the +* state of the pool. If the pool is not currently processing released data_vios, the pool's +* completion will be enqueued on a cpu queue. This obviates the need for the releasing threads to +* hold the pool's lock, and also batches release work while avoiding starvation of the cpu +* threads. +* +* Whenever the pool's completion is run on a cpu thread, it calls process_release_callback() which +* processes a batch of returned data_vios (currently at most 32) from the pool's funnel queue. For +* each data_vio, it first checks whether that data_vio was processing a discard. If so, and there +* is a blocked bio waiting for a discard permit, that permit is notionally transferred to the +* eldest discard waiter, and that waiter is moved to the end of the list of discard bios waiting +* for a data_vio. If there are no discard waiters, the discard permit is returned to the pool. +* Next, the data_vio is assigned to the oldest blocked bio which either has a discard permit, or +* doesn't need one and relaunched. If neither of these exist, the data_vio is returned to the +* pool. Finally, if any waiting bios were launched, the threads which blocked trying to submit +* them are awakened. +*/ + +enum { +DATA_VIO_RELEASE_BATCH_SIZE =128 , +}; + +static const unsigned int VDO_SECTORS_PER_BLOCK_MASK =VDO_SECTORS_PER_BLOCK -1 ; +static const u32 COMPRESSION_STATUS_MASK =0xff ; +static const u32 MAY_NOT_COMPRESS_MASK =0x80000000 ; + +struct limiter ; +typedef void (*assigner_fn )(struct limiter *limiter); + +/* Bookkeeping structure for a single type of resource. */ +struct limiter { +/* The data_vio_pool to which this limiter belongs */ +struct data_vio_pool *pool; +/* The maximum number of data_vios available */ +data_vio_count_t limit; +/* The number of resources in use */ +data_vio_count_t busy; +/* The maximum number of resources ever simultaneously in use */ +data_vio_count_t max_busy; +/* The number of resources to release */ +data_vio_count_t release_count; +/* The number of waiters to wake */ +data_vio_count_t wake_count; +/* The list of waiting bios which are known to process_release_callback() */ +struct bio_list waiters; +/* The list of waiting bios which are not yet known to process_release_callback() */ +struct bio_list new_waiters; +/* The list of waiters which have their permits */ +struct bio_list *permitted_waiters; +/* The function for assigning a resource to a waiter */ +assigner_fn assigner; +/* The queue of blocked threads */ +wait_queue_head_t blocked_threads; +/* The arrival time of the eldest waiter */ +u64 arrival; +}; + +/* +* A data_vio_pool is a collection of preallocated data_vios which may be acquired from any thread, +* and are released in batches. +*/ +struct data_vio_pool { +/* Completion for scheduling releases */ +struct vdo_completion completion; +/* The administrative state of the pool */ +struct admin_state state; +/* Lock protecting the pool */ +spinlock_t lock; +/* The main limiter controlling the total data_vios in the pool. */ +struct limiter limiter; +/* The limiter controlling data_vios for discard */ +struct limiter discard_limiter; +/* The list of bios which have discard permits but still need a data_vio */ +struct bio_list permitted_discards; +/* The list of available data_vios */ +struct list_head available; +/* The queue of data_vios waiting to be returned to the pool */ +struct funnel_queue *queue; +/* Whether the pool is processing, or scheduled to process releases */ +atomic_t processing; +/* The data vios in the pool */ +struct data_vio data_vios[]; +}; + +static const char *const ASYNC_OPERATION_NAMES [] = { +"launch" , +"acknowledge_write" , +"acquire_hash_lock" , +"attempt_logical_block_lock" , +"lock_duplicate_pbn" , +"check_for_duplication" , +"cleanup" , +"compress_data_vio" , +"find_block_map_slot" , +"get_mapped_block_for_read" , +"get_mapped_block_for_write" , +"hash_data_vio" , +"journal_remapping" , +"vdo_attempt_packing" , +"put_mapped_block" , +"read_data_vio" , +"update_dedupe_index" , +"update_reference_counts" , +"verify_duplication" , +"write_data_vio" , +}; + +/* The steps taken cleaning up a VIO, in the order they are performed. */ +enum data_vio_cleanup_stage { +VIO_CLEANUP_START , +VIO_RELEASE_HASH_LOCK =VIO_CLEANUP_START , +VIO_RELEASE_ALLOCATED , +VIO_RELEASE_RECOVERY_LOCKS , +VIO_RELEASE_LOGICAL , +VIO_CLEANUP_DONE +}; + +static inline struct data_vio_pool *__must_check +as_data_vio_pool (struct vdo_completion *completion) +{ +vdo_assert_completion_type (completion,VDO_DATA_VIO_POOL_COMPLETION ); + return container_of(completion, struct data_vio_pool, completion); +} + +static inline u64 get_arrival_time (struct bio *bio) +{ +return (u64 ) bio->bi_private; +} + +/** +* check_for_drain_complete_locked() - Check whether a data_vio_pool has no outstanding data_vios +* or waiters while holding the pool's lock. +*/ +static bool check_for_drain_complete_locked (struct data_vio_pool *pool) +{ +if (pool->limiter.busy >0 ) +return false; + +ASSERT_LOG_ONLY ((pool->discard_limiter.busy ==0 ), +"no outstanding discard permits" ); + +return (bio_list_empty (&pool->limiter.new_waiters) && +bio_list_empty (&pool->discard_limiter.new_waiters)); +} + +static void initialize_lbn_lock (struct data_vio *data_vio,logical_block_number_t lbn) +{ +struct vdo *vdo =vdo_from_data_vio (data_vio); +zone_count_t zone_number; +struct lbn_lock *lock = &data_vio->logical; + + lock->lbn = lbn; + lock->locked = false; +vdo_initialize_wait_queue (&lock->waiters); + zone_number =vdo_compute_logical_zone (data_vio); + lock->zone = &vdo->logical_zones->zones[zone_number]; +} + +static void launch_locked_request (struct data_vio *data_vio) +{ + data_vio->logical.locked = true; +if (data_vio->write) { +struct vdo *vdo =vdo_from_data_vio (data_vio); + +if (vdo_is_read_only (vdo)) { +continue_data_vio_with_error (data_vio,VDO_READ_ONLY ); +return ; + } + } + + data_vio->last_async_operation =VIO_ASYNC_OP_FIND_BLOCK_MAP_SLOT ; +vdo_find_block_map_slot (data_vio); +} + +static void acknowledge_data_vio (struct data_vio *data_vio) +{ +struct vdo *vdo =vdo_from_data_vio (data_vio); +struct bio *bio = data_vio->user_bio; +int error =vdo_map_to_system_error (data_vio->vio.completion.result); + +if (bio ==NULL ) +return ; + +ASSERT_LOG_ONLY ((data_vio->remaining_discard <= + (u32) (VDO_BLOCK_SIZE - data_vio->offset)), +"data_vio to acknowledge is not an incomplete discard" ); + + data_vio->user_bio =NULL ; +vdo_count_bios (&vdo->stats.bios_acknowledged, bio); +if (data_vio->is_partial) +vdo_count_bios (&vdo->stats.bios_acknowledged_partial, bio); + + bio->bi_status =errno_to_blk_status (error); +bio_endio (bio); +} + +static void copy_to_bio (struct bio *bio,char *data_ptr) +{ +struct bio_vec biovec; +struct bvec_iter iter; + +bio_for_each_segment (biovec, bio, iter) { +memcpy_to_bvec (&biovec, data_ptr); + data_ptr += biovec.bv_len; + } +} + +struct data_vio_compression_status get_data_vio_compression_status (struct data_vio *data_vio) +{ +u32 packed =atomic_read (&data_vio->compression.status); + +/* pairs with cmpxchg in set_data_vio_compression_status */ +smp_rmb (); +return (struct data_vio_compression_status ) { + .stage = packed &COMPRESSION_STATUS_MASK , + .may_not_compress = ((packed &MAY_NOT_COMPRESS_MASK ) !=0 ), + }; +} + +/** +* pack_status() - Convert a data_vio_compression_status into a u32 which may be stored +* atomically. +* @status: The state to convert. +* +* Return: The compression state packed into a u32. +*/ +static u32 __must_check pack_status (struct data_vio_compression_status status) +{ +return status.stage | (status.may_not_compress ?MAY_NOT_COMPRESS_MASK :0 ); +} + +/** +* set_data_vio_compression_status() - Set the compression status of a data_vio. +* @state: The expected current status of the data_vio. +* @new_state: The status to set. +* +* Return: true if the new status was set, false if the data_vio's compression status did not +* match the expected state, and so was left unchanged. +*/ +static bool __must_check +set_data_vio_compression_status (struct data_vio *data_vio, +struct data_vio_compression_status status, +struct data_vio_compression_status new_status) +{ +u32 actual; +u32 expected =pack_status (status); +u32 replacement =pack_status (new_status); + +/* +* Extra barriers because this was original developed using a CAS operation that implicitly +* had them. +*/ +smp_mb__before_atomic (); + actual =atomic_cmpxchg (&data_vio->compression.status, expected, replacement); +/* same as before_atomic */ +smp_mb__after_atomic (); +return (expected == actual); +} + +struct data_vio_compression_status advance_data_vio_compression_stage (struct data_vio *data_vio) +{ +for (;;) { +struct data_vio_compression_status status = +get_data_vio_compression_status (data_vio); +struct data_vio_compression_status new_status = status; + +if (status.stage ==DATA_VIO_POST_PACKER ) { +/* We're already in the last stage. */ +return status; + } + +if (status.may_not_compress) { +/* +* Compression has been dis-allowed for this VIO, so skip the rest of the +* path and go to the end. +*/ + new_status.stage =DATA_VIO_POST_PACKER ; + }else { +/* Go to the next state. */ + new_status.stage++; + } + +if (set_data_vio_compression_status (data_vio, status, new_status)) +return new_status; + +/* Another thread changed the status out from under us so try again. */ + } +} + +/** +* cancel_data_vio_compression() - Prevent this data_vio from being compressed or packed. +* +* Return: true if the data_vio is in the packer and the caller was the first caller to cancel it. +*/ +bool cancel_data_vio_compression (struct data_vio *data_vio) +{ +struct data_vio_compression_status status, new_status; + +for (;;) { + status =get_data_vio_compression_status (data_vio); +if (status.may_not_compress || (status.stage ==DATA_VIO_POST_PACKER )) { +/* This data_vio is already set up to not block in the packer. */ +break ; + } + + new_status.stage = status.stage; + new_status.may_not_compress = true; + +if (set_data_vio_compression_status (data_vio, status, new_status)) +break ; + } + +return ((status.stage ==DATA_VIO_PACKING ) && !status.may_not_compress); +} + +/** +* attempt_logical_block_lock() - Attempt to acquire the lock on a logical block. +* @completion: The data_vio for an external data request as a completion. +* +* This is the start of the path for all external requests. It is registered in launch_data_vio(). +*/ +static void attempt_logical_block_lock (struct vdo_completion *completion) +{ +struct data_vio *data_vio =as_data_vio (completion); +struct lbn_lock *lock = &data_vio->logical; +struct vdo *vdo =vdo_from_data_vio (data_vio); +struct data_vio *lock_holder; +int result; + +assert_data_vio_in_logical_zone (data_vio); + +if (data_vio->logical.lbn >= vdo->states.vdo.config.logical_blocks) { +continue_data_vio_with_error (data_vio,VDO_OUT_OF_RANGE ); +return ; + } + + result =vdo_int_map_put (lock->zone->lbn_operations, lock->lbn, + data_vio, false, (void **) &lock_holder); +if (result !=VDO_SUCCESS ) { +continue_data_vio_with_error (data_vio, result); +return ; + } + +if (lock_holder ==NULL ) { +/* We got the lock */ +launch_locked_request (data_vio); +return ; + } + + result =ASSERT (lock_holder->logical.locked,"logical block lock held" ); +if (result !=VDO_SUCCESS ) { +continue_data_vio_with_error (data_vio, result); +return ; + } + +/* +* If the new request is a pure read request (not read-modify-write) and the lock_holder is +* writing and has received an allocation (VDO-2683), service the read request immediately +* by copying data from the lock_holder to avoid having to flush the write out of the +* packer just to prevent the read from waiting indefinitely. If the lock_holder does not +* yet have an allocation, prevent it from blocking in the packer and wait on it. +*/ +if (!data_vio->write &&READ_ONCE (lock_holder->allocation_succeeded)) { +copy_to_bio (data_vio->user_bio, lock_holder->vio.data + data_vio->offset); +acknowledge_data_vio (data_vio); +complete_data_vio (completion); +return ; + } + + data_vio->last_async_operation =VIO_ASYNC_OP_ATTEMPT_LOGICAL_BLOCK_LOCK ; +vdo_enqueue_waiter (&lock_holder->logical.waiters, &data_vio->waiter); + +/* +* Prevent writes and read-modify-writes from blocking indefinitely on lock holders in the +* packer. +*/ +if (lock_holder->write &&cancel_data_vio_compression (lock_holder)) { + data_vio->compression.lock_holder = lock_holder; +launch_data_vio_packer_callback (data_vio, + vdo_remove_lock_holder_from_packer); + } +} + +/** +* launch_data_vio() - (Re)initialize a data_vio to have a new logical block number, keeping the +* same parent and other state and send it on its way. +*/ +static void launch_data_vio (struct data_vio *data_vio,logical_block_number_t lbn) +{ +struct vdo_completion *completion = &data_vio->vio.completion; + +/* +* Clearing the tree lock must happen before initializing the LBN lock, which also adds +* information to the tree lock. +*/ +memset (&data_vio->tree_lock,0 ,sizeof (data_vio->tree_lock)); +initialize_lbn_lock (data_vio, lbn); +INIT_LIST_HEAD (&data_vio->hash_lock_entry); +INIT_LIST_HEAD (&data_vio->write_entry); + +memset (&data_vio->allocation,0 ,sizeof (data_vio->allocation)); + + data_vio->is_duplicate = false; + +memset (&data_vio->record_name,0 ,sizeof (data_vio->record_name)); +memset (&data_vio->duplicate,0 ,sizeof (data_vio->duplicate)); +vdo_reset_completion (completion); + completion->error_handler = handle_data_vio_error; +set_data_vio_logical_callback (data_vio, attempt_logical_block_lock); +vdo_enqueue_completion (completion,VDO_DEFAULT_Q_MAP_BIO_PRIORITY ); +} + +static bool is_zero_block (char *block) +{ +int i; + +for (i =0 ; i <VDO_BLOCK_SIZE ; i +=sizeof (u64)) { +if (*((u64 *) &block[i])) +return false; + } + +return true; +} + +static void copy_from_bio (struct bio *bio,char *data_ptr) +{ +struct bio_vec biovec; +struct bvec_iter iter; + +bio_for_each_segment (biovec, bio, iter) { +memcpy_from_bvec (data_ptr, &biovec); + data_ptr += biovec.bv_len; + } +} + +static void launch_bio (struct vdo *vdo,struct data_vio *data_vio,struct bio *bio) +{ +logical_block_number_t lbn; +/* +* Zero out the fields which don't need to be preserved (i.e. which are not pointers to +* separately allocated objects). +*/ +memset (data_vio,0 , offsetof(struct data_vio , vio)); +memset (&data_vio->compression,0 , offsetof(struct compression_state , block)); + + data_vio->user_bio = bio; + data_vio->offset =to_bytes (bio->bi_iter.bi_sector &VDO_SECTORS_PER_BLOCK_MASK ); + data_vio->is_partial = (bio->bi_iter.bi_size <VDO_BLOCK_SIZE ) || (data_vio->offset !=0 ); + +/* +* Discards behave very differently than other requests when coming in from device-mapper. +* We have to be able to handle any size discards and various sector offsets within a +* block. +*/ +if (bio_op (bio) ==REQ_OP_DISCARD ) { + data_vio->remaining_discard = bio->bi_iter.bi_size; + data_vio->write = true; + data_vio->is_trim = true; +if (data_vio->is_partial) { +vdo_count_bios (&vdo->stats.bios_in_partial, bio); + data_vio->read = true; + } + }else if (data_vio->is_partial) { +vdo_count_bios (&vdo->stats.bios_in_partial, bio); + data_vio->read = true; +if (bio_data_dir (bio) ==WRITE ) + data_vio->write = true; + }else if (bio_data_dir (bio) ==READ ) { + data_vio->read = true; + }else { +/* +* Copy the bio data to a char array so that we can continue to use the data after +* we acknowledge the bio. +*/ +copy_from_bio (bio, data_vio->vio.data); + data_vio->is_zero =is_zero_block (data_vio->vio.data); + data_vio->write = true; + } + +if (data_vio->user_bio->bi_opf &REQ_FUA ) + data_vio->fua = true; + + lbn = (bio->bi_iter.bi_sector - vdo->starting_sector_offset) /VDO_SECTORS_PER_BLOCK ; +launch_data_vio (data_vio, lbn); +} + +static void assign_data_vio (struct limiter *limiter,struct data_vio *data_vio) +{ +struct bio *bio =bio_list_pop (limiter->permitted_waiters); + +launch_bio (limiter->pool->completion.vdo, data_vio, bio); + limiter->wake_count++; + + bio =bio_list_peek (limiter->permitted_waiters); + limiter->arrival = ((bio ==NULL ) ?U64_MAX :get_arrival_time (bio)); +} + +static void assign_discard_permit (struct limiter *limiter) +{ +struct bio *bio =bio_list_pop (&limiter->waiters); + +if (limiter->arrival ==U64_MAX ) + limiter->arrival =get_arrival_time (bio); + +bio_list_add (limiter->permitted_waiters, bio); +} + +static void get_waiters (struct limiter *limiter) +{ +bio_list_merge (&limiter->waiters, &limiter->new_waiters); +bio_list_init (&limiter->new_waiters); +} + +static inline struct data_vio *get_available_data_vio (struct data_vio_pool *pool) +{ +struct data_vio *data_vio = + list_first_entry(&pool->available, struct data_vio, pool_entry); + +list_del_init (&data_vio->pool_entry); +return data_vio; +} + +static void assign_data_vio_to_waiter (struct limiter *limiter) +{ +assign_data_vio (limiter,get_available_data_vio (limiter->pool)); +} + +static void update_limiter (struct limiter *limiter) +{ +struct bio_list *waiters = &limiter->waiters; +data_vio_count_t available = limiter->limit - limiter->busy; + +ASSERT_LOG_ONLY ((limiter->release_count <= limiter->busy), +"Release count %u is not more than busy count %u" , + limiter->release_count, limiter->busy); + +get_waiters (limiter); +for (; (limiter->release_count >0 ) && !bio_list_empty (waiters); limiter->release_count--) + limiter->assigner (limiter); + +if (limiter->release_count >0 ) { +WRITE_ONCE (limiter->busy, limiter->busy - limiter->release_count); + limiter->release_count =0 ; +return ; + } + +for (; (available >0 ) && !bio_list_empty (waiters); available--) + limiter->assigner (limiter); + +WRITE_ONCE (limiter->busy, limiter->limit - available); +if (limiter->max_busy < limiter->busy) +WRITE_ONCE (limiter->max_busy, limiter->busy); +} + +/** +* schedule_releases() - Ensure that release processing is scheduled. +* +* If this call switches the state to processing, enqueue. Otherwise, some other thread has already +* done so. +*/ +static void schedule_releases (struct data_vio_pool *pool) +{ +/* Pairs with the barrier in process_release_callback(). */ +smp_mb__before_atomic (); +if (atomic_cmpxchg (&pool->processing, false, true)) +return ; + + pool->completion.requeue = true; +vdo_launch_completion_with_priority (&pool->completion, +CPU_Q_COMPLETE_VIO_PRIORITY ); +} + +static void reuse_or_release_resources (struct data_vio_pool *pool, +struct data_vio *data_vio, +struct list_head *returned) +{ +if (data_vio->remaining_discard >0 ) { +if (bio_list_empty (&pool->discard_limiter.waiters)) { +/* Return the data_vio's discard permit. */ + pool->discard_limiter.release_count++; + }else { +assign_discard_permit (&pool->discard_limiter); + } + } + +if (pool->limiter.arrival < pool->discard_limiter.arrival) { +assign_data_vio (&pool->limiter, data_vio); + }else if (pool->discard_limiter.arrival <U64_MAX ) { +assign_data_vio (&pool->discard_limiter, data_vio); + }else { +list_add (&data_vio->pool_entry, returned); + pool->limiter.release_count++; + } +} + +/** +* process_release_callback() - Process a batch of data_vio releases. +* @completion: The pool with data_vios to release. +*/ +static void process_release_callback (struct vdo_completion *completion) +{ +struct data_vio_pool *pool =as_data_vio_pool (completion); +bool reschedule; +bool drained; +data_vio_count_t processed; +data_vio_count_t to_wake; +data_vio_count_t discards_to_wake; +LIST_HEAD (returned); + +spin_lock (&pool->lock); +get_waiters (&pool->discard_limiter); +get_waiters (&pool->limiter); +spin_unlock (&pool->lock); + +if (pool->limiter.arrival ==U64_MAX ) { +struct bio *bio =bio_list_peek (&pool->limiter.waiters); + +if (bio !=NULL ) + pool->limiter.arrival =get_arrival_time (bio); + } + +for (processed =0 ; processed <DATA_VIO_RELEASE_BATCH_SIZE ; processed++) { +struct data_vio *data_vio; +struct funnel_queue_entry *entry =uds_funnel_queue_poll (pool->queue); + +if (entry ==NULL ) +break ; + + data_vio = as_data_vio(container_of(entry, struct vdo_completion, + work_queue_entry_link)); +acknowledge_data_vio (data_vio); +reuse_or_release_resources (pool, data_vio, &returned); + } + +spin_lock (&pool->lock); +/* +* There is a race where waiters could be added while we are in the unlocked section above. +* Those waiters could not see the resources we are now about to release, so we assign +* those resources now as we have no guarantee of being rescheduled. This is handled in +* update_limiter(). +*/ +update_limiter (&pool->discard_limiter); +list_splice (&returned, &pool->available); +update_limiter (&pool->limiter); + to_wake = pool->limiter.wake_count; + pool->limiter.wake_count =0 ; + discards_to_wake = pool->discard_limiter.wake_count; + pool->discard_limiter.wake_count =0 ; + +atomic_set (&pool->processing, false); +/* Pairs with the barrier in schedule_releases(). */ +smp_mb (); + + reschedule = !uds_is_funnel_queue_empty (pool->queue); + drained = (!reschedule && +vdo_is_state_draining (&pool->state) && +check_for_drain_complete_locked (pool)); +spin_unlock (&pool->lock); + +if (to_wake >0 ) +wake_up_nr (&pool->limiter.blocked_threads, to_wake); + +if (discards_to_wake >0 ) +wake_up_nr (&pool->discard_limiter.blocked_threads, discards_to_wake); + +if (reschedule) +schedule_releases (pool); +else if (drained) +vdo_finish_draining (&pool->state); +} + +static void initialize_limiter (struct limiter *limiter,struct data_vio_pool *pool, +assigner_fn assigner,data_vio_count_t limit) +{ + limiter->pool = pool; + limiter->assigner = assigner; + limiter->limit = limit; + limiter->arrival =U64_MAX ; +init_waitqueue_head (&limiter->blocked_threads); +} + +/** +* initialize_data_vio() - Allocate the components of a data_vio. +* +* The caller is responsible for cleaning up the data_vio on error. +* +* Return: VDO_SUCCESS or an error. +*/ +static int initialize_data_vio (struct data_vio *data_vio,struct vdo *vdo) +{ +struct bio *bio; +int result; + +BUILD_BUG_ON (VDO_BLOCK_SIZE >PAGE_SIZE ); + result =uds_allocate_memory (VDO_BLOCK_SIZE ,0 ,"data_vio data" , + &data_vio->vio.data); +if (result !=VDO_SUCCESS ) +return uds_log_error_strerror (result, +"data_vio data allocation failure" ); + + result =uds_allocate_memory (VDO_BLOCK_SIZE ,0 ,"compressed block" , + &data_vio->compression.block); +if (result !=VDO_SUCCESS ) { +return uds_log_error_strerror (result, +"data_vio compressed block allocation failure" ); + } + + result =uds_allocate_memory (VDO_BLOCK_SIZE ,0 ,"vio scratch" , + &data_vio->scratch_block); +if (result !=VDO_SUCCESS ) +return uds_log_error_strerror (result, +"data_vio scratch allocation failure" ); + + result =vdo_create_bio (&bio); +if (result !=VDO_SUCCESS ) +return uds_log_error_strerror (result, +"data_vio data bio allocation failure" ); + +vdo_initialize_completion (&data_vio->decrement_completion, vdo, +VDO_DECREMENT_COMPLETION ); +initialize_vio (&data_vio->vio, bio,1 ,VIO_TYPE_DATA ,VIO_PRIORITY_DATA , vdo); + +return VDO_SUCCESS ; +} + +static void destroy_data_vio (struct data_vio *data_vio) +{ +if (data_vio ==NULL ) +return ; + +vdo_free_bio (uds_forget (data_vio->vio.bio)); +uds_free (uds_forget (data_vio->vio.data)); +uds_free (uds_forget (data_vio->compression.block)); +uds_free (uds_forget (data_vio->scratch_block)); +} + +/** +* make_data_vio_pool() - Initialize a data_vio pool. +* @vdo: The vdo to which the pool will belong. +* @pool_size: The number of data_vios in the pool. +* @discard_limit: The maximum number of data_vios which may be used for discards. +* @pool: A pointer to hold the newly allocated pool. +*/ +int make_data_vio_pool (struct vdo *vdo,data_vio_count_t pool_size, +data_vio_count_t discard_limit,struct data_vio_pool **pool_ptr) +{ +int result; +struct data_vio_pool *pool; +data_vio_count_t i; + + result = uds_allocate_extended(struct data_vio_pool, pool_size, struct data_vio, + __func__, &pool); +if (result !=UDS_SUCCESS ) +return result; + +ASSERT_LOG_ONLY ((discard_limit <= pool_size), +"discard limit does not exceed pool size" ); +initialize_limiter (&pool->discard_limiter, pool, assign_discard_permit, + discard_limit); + pool->discard_limiter.permitted_waiters = &pool->permitted_discards; +initialize_limiter (&pool->limiter, pool, assign_data_vio_to_waiter, pool_size); + pool->limiter.permitted_waiters = &pool->limiter.waiters; +INIT_LIST_HEAD (&pool->available); +spin_lock_init (&pool->lock); +vdo_set_admin_state_code (&pool->state,VDO_ADMIN_STATE_NORMAL_OPERATION ); +vdo_initialize_completion (&pool->completion, vdo,VDO_DATA_VIO_POOL_COMPLETION ); +vdo_prepare_completion (&pool->completion, process_release_callback, + process_release_callback, vdo->thread_config.cpu_thread, +NULL ); + + result =uds_make_funnel_queue (&pool->queue); +if (result !=UDS_SUCCESS ) { +free_data_vio_pool (uds_forget (pool)); +return result; + } + +for (i =0 ; i < pool_size; i++) { +struct data_vio *data_vio = &pool->data_vios[i]; + + result =initialize_data_vio (data_vio, vdo); +if (result !=VDO_SUCCESS ) { +destroy_data_vio (data_vio); +free_data_vio_pool (pool); +return result; + } + +list_add (&data_vio->pool_entry, &pool->available); + } + + *pool_ptr = pool; +return VDO_SUCCESS ; +} + +/** +* free_data_vio_pool() - Free a data_vio_pool and the data_vios in it. +* +* All data_vios must be returned to the pool before calling this function. +*/ +void free_data_vio_pool (struct data_vio_pool *pool) +{ +struct data_vio *data_vio, *tmp; + +if (pool ==NULL ) +return ; + +/* +* Pairs with the barrier in process_release_callback(). Possibly not needed since it +* caters to an enqueue vs. free race. +*/ +smp_mb (); +BUG_ON (atomic_read (&pool->processing)); + +spin_lock (&pool->lock); +ASSERT_LOG_ONLY ((pool->limiter.busy ==0 ), +"data_vio pool must not have %u busy entries when being freed" , + pool->limiter.busy); +ASSERT_LOG_ONLY ((bio_list_empty (&pool->limiter.waiters) && +bio_list_empty (&pool->limiter.new_waiters)), +"data_vio pool must not have threads waiting to read or write when being freed" ); +ASSERT_LOG_ONLY ((bio_list_empty (&pool->discard_limiter.waiters) && +bio_list_empty (&pool->discard_limiter.new_waiters)), +"data_vio pool must not have threads waiting to discard when being freed" ); +spin_unlock (&pool->lock); + +list_for_each_entry_safe (data_vio, tmp, &pool->available, pool_entry) { +list_del_init (&data_vio->pool_entry); +destroy_data_vio (data_vio); + } + +uds_free_funnel_queue (uds_forget (pool->queue)); +uds_free (pool); +} + +static bool acquire_permit (struct limiter *limiter,struct bio *bio) +{ +if (limiter->busy >= limiter->limit) { +DEFINE_WAIT (wait); + +bio_list_add (&limiter->new_waiters, bio); +prepare_to_wait_exclusive (&limiter->blocked_threads, &wait, +TASK_UNINTERRUPTIBLE ); +spin_unlock (&limiter->pool->lock); +io_schedule (); +finish_wait (&limiter->blocked_threads, &wait); +return false; + } + +WRITE_ONCE (limiter->busy, limiter->busy +1 ); +if (limiter->max_busy < limiter->busy) +WRITE_ONCE (limiter->max_busy, limiter->busy); + +return true; +} + +/** +* vdo_launch_bio() - Acquire a data_vio from the pool, assign the bio to it, and launch it. +* +* This will block if data_vios or discard permits are not available. +*/ +void vdo_launch_bio (struct data_vio_pool *pool,struct bio *bio) +{ +struct data_vio *data_vio; + +ASSERT_LOG_ONLY (!vdo_is_state_quiescent (&pool->state), +"data_vio_pool not quiescent on acquire" ); + + bio->bi_private = (void *) jiffies; +spin_lock (&pool->lock); +if ((bio_op (bio) ==REQ_OP_DISCARD ) && + !acquire_permit (&pool->discard_limiter, bio)) +return ; + +if (!acquire_permit (&pool->limiter, bio)) +return ; + + data_vio =get_available_data_vio (pool); +spin_unlock (&pool->lock); +launch_bio (pool->completion.vdo, data_vio, bio); +} + +/* Implements vdo_admin_initiator_fn. */ +static void initiate_drain (struct admin_state *state) +{ +bool drained; + struct data_vio_pool *pool = container_of(state, struct data_vio_pool, state); + +spin_lock (&pool->lock); + drained =check_for_drain_complete_locked (pool); +spin_unlock (&pool->lock); + +if (drained) +vdo_finish_draining (state); +} + +static void assert_on_vdo_cpu_thread (const struct vdo *vdo,const char *name) +{ +ASSERT_LOG_ONLY ((vdo_get_callback_thread_id () == vdo->thread_config.cpu_thread), +"%s called on cpu thread" , name); +} + +/** +* drain_data_vio_pool() - Wait asynchronously for all data_vios to be returned to the pool. +* @completion: The completion to notify when the pool has drained. +*/ +void drain_data_vio_pool (struct data_vio_pool *pool,struct vdo_completion *completion) +{ +assert_on_vdo_cpu_thread (completion->vdo, __func__); +vdo_start_draining (&pool->state,VDO_ADMIN_STATE_SUSPENDING , completion, + initiate_drain); +} + +/** +* resume_data_vio_pool() - Resume a data_vio pool. +* @completion: The completion to notify when the pool has resumed. +*/ +void resume_data_vio_pool (struct data_vio_pool *pool,struct vdo_completion *completion) +{ +assert_on_vdo_cpu_thread (completion->vdo, __func__); +vdo_continue_completion (completion,vdo_resume_if_quiescent (&pool->state)); +} + +static void dump_limiter (const char *name,struct limiter *limiter) +{ +uds_log_info ("%s: %u of %u busy (max %u), %s" , name, limiter->busy, + limiter->limit, limiter->max_busy, + ((bio_list_empty (&limiter->waiters) && +bio_list_empty (&limiter->new_waiters)) ? +"no waiters" :"has waiters" )); +} + +/** +* dump_data_vio_pool() - Dump a data_vio pool to the log. +* @dump_vios: Whether to dump the details of each busy data_vio as well. +*/ +void dump_data_vio_pool (struct data_vio_pool *pool,bool dump_vios) +{ +/* +* In order that syslog can empty its buffer, sleep after 35 elements for 4ms (till the +* second clock tick). These numbers were picked based on experiments with lab machines. +*/ +enum {ELEMENTS_PER_BATCH =35 }; +enum {SLEEP_FOR_SYSLOG =4000 }; + +if (pool ==NULL ) +return ; + +spin_lock (&pool->lock); +dump_limiter ("data_vios" , &pool->limiter); +dump_limiter ("discard permits" , &pool->discard_limiter); +if (dump_vios) { +int i; +int dumped =0 ; + +for (i =0 ; i < pool->limiter.limit; i++) { +struct data_vio *data_vio = &pool->data_vios[i]; + +if (!list_empty (&data_vio->pool_entry)) +continue ; + +dump_data_vio (data_vio); +if (++dumped >=ELEMENTS_PER_BATCH ) { +spin_unlock (&pool->lock); + dumped =0 ; +fsleep (SLEEP_FOR_SYSLOG ); +spin_lock (&pool->lock); + } + } + } + +spin_unlock (&pool->lock); +} + +data_vio_count_t get_data_vio_pool_active_discards (struct data_vio_pool *pool) +{ +return READ_ONCE (pool->discard_limiter.busy); +} + +data_vio_count_t get_data_vio_pool_discard_limit (struct data_vio_pool *pool) +{ +return READ_ONCE (pool->discard_limiter.limit); +} + +data_vio_count_t get_data_vio_pool_maximum_discards (struct data_vio_pool *pool) +{ +return READ_ONCE (pool->discard_limiter.max_busy); +} + +int set_data_vio_pool_discard_limit (struct data_vio_pool *pool,data_vio_count_t limit) +{ +if (get_data_vio_pool_request_limit (pool) < limit) { +// The discard limit may not be higher than the data_vio limit. +return -EINVAL ; + } + +spin_lock (&pool->lock); + pool->discard_limiter.limit = limit; +spin_unlock (&pool->lock); + +return VDO_SUCCESS ; +} + +data_vio_count_t get_data_vio_pool_active_requests (struct data_vio_pool *pool) +{ +return READ_ONCE (pool->limiter.busy); +} + +data_vio_count_t get_data_vio_pool_request_limit (struct data_vio_pool *pool) +{ +return READ_ONCE (pool->limiter.limit); +} + +data_vio_count_t get_data_vio_pool_maximum_requests (struct data_vio_pool *pool) +{ +return READ_ONCE (pool->limiter.max_busy); +} + +static void update_data_vio_error_stats (struct data_vio *data_vio) +{ +u8 index =0 ; +static const char *const operations[] = { + [0 ] ="empty" , + [1 ] ="read" , + [2 ] ="write" , + [3 ] ="read-modify-write" , + [5 ] ="read+fua" , + [6 ] ="write+fua" , + [7 ] ="read-modify-write+fua" , + }; + +if (data_vio->read) + index =1 ; + +if (data_vio->write) + index +=2 ; + +if (data_vio->fua) + index +=4 ; + +update_vio_error_stats (&data_vio->vio, +"Completing %s vio for LBN %llu with error after %s" , + operations[index], + (unsigned long long ) data_vio->logical.lbn, +get_data_vio_operation_name (data_vio)); +} + +static void perform_cleanup_stage (struct data_vio *data_vio, +enum data_vio_cleanup_stage stage); + +/** +* release_allocated_lock() - Release the PBN lock and/or the reference on the allocated block at +* the end of processing a data_vio. +*/ +static void release_allocated_lock (struct vdo_completion *completion) +{ +struct data_vio *data_vio =as_data_vio (completion); + +assert_data_vio_in_allocated_zone (data_vio); +release_data_vio_allocation_lock (data_vio, false); +perform_cleanup_stage (data_vio,VIO_RELEASE_RECOVERY_LOCKS ); +} + +/** release_lock() - Release an uncontended LBN lock. */ +static void release_lock (struct data_vio *data_vio,struct lbn_lock *lock) +{ +struct int_map *lock_map = lock->zone->lbn_operations; +struct data_vio *lock_holder; + +if (!lock->locked) { +/* The lock is not locked, so it had better not be registered in the lock map. */ +struct data_vio *lock_holder =vdo_int_map_get (lock_map, lock->lbn); + +ASSERT_LOG_ONLY ((data_vio != lock_holder), +"no logical block lock held for block %llu" , + (unsigned long long ) lock->lbn); +return ; + } + +/* Release the lock by removing the lock from the map. */ + lock_holder =vdo_int_map_remove (lock_map, lock->lbn); +ASSERT_LOG_ONLY ((data_vio == lock_holder), +"logical block lock mismatch for block %llu" , + (unsigned long long ) lock->lbn); + lock->locked = false; +} + +/** transfer_lock() - Transfer a contended LBN lock to the eldest waiter. */ +static void transfer_lock (struct data_vio *data_vio,struct lbn_lock *lock) +{ +struct data_vio *lock_holder, *next_lock_holder; +int result; + +ASSERT_LOG_ONLY (lock->locked,"lbn_lock with waiters is not locked" ); + +/* Another data_vio is waiting for the lock, transfer it in a single lock map operation. */ + next_lock_holder = +waiter_as_data_vio (vdo_dequeue_next_waiter (&lock->waiters)); + +/* Transfer the remaining lock waiters to the next lock holder. */ +vdo_transfer_all_waiters (&lock->waiters, + &next_lock_holder->logical.waiters); + + result =vdo_int_map_put (lock->zone->lbn_operations, lock->lbn, + next_lock_holder, true, (void **) &lock_holder); +if (result !=VDO_SUCCESS ) { +continue_data_vio_with_error (next_lock_holder, result); +return ; + } + +ASSERT_LOG_ONLY ((lock_holder == data_vio), +"logical block lock mismatch for block %llu" , + (unsigned long long ) lock->lbn); + lock->locked = false; + +/* +* If there are still waiters, other data_vios must be trying to get the lock we just +* transferred. We must ensure that the new lock holder doesn't block in the packer. +*/ +if (vdo_has_waiters (&next_lock_holder->logical.waiters)) +cancel_data_vio_compression (next_lock_holder); + +/* +* Avoid stack overflow on lock transfer. +* FIXME: this is only an issue in the 1 thread config. +*/ + next_lock_holder->vio.completion.requeue = true; +launch_locked_request (next_lock_holder); +} + +/** +* release_logical_lock() - Release the logical block lock and flush generation lock at the end of +* processing a data_vio. +*/ +static void release_logical_lock (struct vdo_completion *completion) +{ +struct data_vio *data_vio =as_data_vio (completion); +struct lbn_lock *lock = &data_vio->logical; + +assert_data_vio_in_logical_zone (data_vio); + +if (vdo_has_waiters (&lock->waiters)) +transfer_lock (data_vio, lock); +else +release_lock (data_vio, lock); + +vdo_release_flush_generation_lock (data_vio); +perform_cleanup_stage (data_vio,VIO_CLEANUP_DONE ); +} + +/** clean_hash_lock() - Release the hash lock at the end of processing a data_vio. */ +static void clean_hash_lock (struct vdo_completion *completion) +{ +struct data_vio *data_vio =as_data_vio (completion); + +assert_data_vio_in_hash_zone (data_vio); +if (completion->result !=VDO_SUCCESS ) { +vdo_clean_failed_hash_lock (data_vio); +return ; + } + +vdo_release_hash_lock (data_vio); +perform_cleanup_stage (data_vio,VIO_RELEASE_LOGICAL ); +} + +/** +* finish_cleanup() - Make some assertions about a data_vio which has finished cleaning up. +* +* If it is part of a multi-block discard, starts on the next block, otherwise, returns it to the +* pool. +*/ +static void finish_cleanup (struct data_vio *data_vio) +{ +struct vdo_completion *completion = &data_vio->vio.completion; + +ASSERT_LOG_ONLY (data_vio->allocation.lock ==NULL , +"complete data_vio has no allocation lock" ); +ASSERT_LOG_ONLY (data_vio->hash_lock ==NULL , +"complete data_vio has no hash lock" ); +if ((data_vio->remaining_discard <=VDO_BLOCK_SIZE ) || + (completion->result !=VDO_SUCCESS )) { +struct data_vio_pool *pool = completion->vdo->data_vio_pool; + +uds_funnel_queue_put (pool->queue, &completion->work_queue_entry_link); +schedule_releases (pool); +return ; + } + + data_vio->remaining_discard -=min_t (u32, data_vio->remaining_discard, +VDO_BLOCK_SIZE - data_vio->offset); + data_vio->is_partial = (data_vio->remaining_discard <VDO_BLOCK_SIZE ); + data_vio->read = data_vio->is_partial; + data_vio->offset =0 ; + completion->requeue = true; +launch_data_vio (data_vio, data_vio->logical.lbn +1 ); +} + +/** perform_cleanup_stage() - Perform the next step in the process of cleaning up a data_vio. */ +static void perform_cleanup_stage (struct data_vio *data_vio, +enum data_vio_cleanup_stage stage) +{ +struct vdo *vdo =vdo_from_data_vio (data_vio); + +switch (stage) { +case VIO_RELEASE_HASH_LOCK : +if (data_vio->hash_lock !=NULL ) { +launch_data_vio_hash_zone_callback (data_vio, clean_hash_lock); +return ; + } + fallthrough; + +case VIO_RELEASE_ALLOCATED : +if (data_vio_has_allocation (data_vio)) { +launch_data_vio_allocated_zone_callback (data_vio, + release_allocated_lock); +return ; + } + fallthrough; + +case VIO_RELEASE_RECOVERY_LOCKS : +if ((data_vio->recovery_sequence_number >0 ) && + (READ_ONCE (vdo->read_only_notifier.read_only_error) ==VDO_SUCCESS ) && + (data_vio->vio.completion.result !=VDO_READ_ONLY )) +uds_log_warning ("VDO not read-only when cleaning data_vio with RJ lock" ); + fallthrough; + +case VIO_RELEASE_LOGICAL : +launch_data_vio_logical_callback (data_vio, release_logical_lock); +return ; + +default : +finish_cleanup (data_vio); + } +} + +void complete_data_vio (struct vdo_completion *completion) +{ +struct data_vio *data_vio =as_data_vio (completion); + + completion->error_handler =NULL ; + data_vio->last_async_operation =VIO_ASYNC_OP_CLEANUP ; +perform_cleanup_stage (data_vio, + (data_vio->write ?VIO_CLEANUP_START :VIO_RELEASE_LOGICAL )); +} + +static void enter_read_only_mode (struct vdo_completion *completion) +{ +if (vdo_is_read_only (completion->vdo)) +return ; + +if (completion->result !=VDO_READ_ONLY ) { +struct data_vio *data_vio =as_data_vio (completion); + +uds_log_error_strerror (completion->result, +"Preparing to enter read-only mode: data_vio for LBN %llu (becoming mapped to %llu, previously mapped to %llu, allocated %llu) is completing with a fatal error after operation %s" , + (unsigned long long ) data_vio->logical.lbn, + (unsigned long long ) data_vio->new_mapped.pbn, + (unsigned long long ) data_vio->mapped.pbn, + (unsigned long long ) data_vio->allocation.pbn, +get_data_vio_operation_name (data_vio)); + } + +vdo_enter_read_only_mode (completion->vdo, completion->result); +} + +void handle_data_vio_error (struct vdo_completion *completion) +{ +struct data_vio *data_vio =as_data_vio (completion); + +if ((completion->result ==VDO_READ_ONLY ) || (data_vio->user_bio ==NULL )) +enter_read_only_mode (completion); + +update_data_vio_error_stats (data_vio); +complete_data_vio (completion); +} + +/** +* get_data_vio_operation_name() - Get the name of the last asynchronous operation performed on a +* data_vio. +*/ +const char *get_data_vio_operation_name (struct data_vio *data_vio) +{ +BUILD_BUG_ON ((MAX_VIO_ASYNC_OPERATION_NUMBER -MIN_VIO_ASYNC_OPERATION_NUMBER ) != +ARRAY_SIZE (ASYNC_OPERATION_NAMES )); + +return ((data_vio->last_async_operation <MAX_VIO_ASYNC_OPERATION_NUMBER ) ? +ASYNC_OPERATION_NAMES [data_vio->last_async_operation] : +"unknown async operation" ); +} + +/** +* data_vio_allocate_data_block() - Allocate a data block. +* +* @write_lock_type: The type of write lock to obtain on the block. +* @callback: The callback which will attempt an allocation in the current zone and continue if it +* succeeds. +* @error_handler: The handler for errors while allocating. +*/ +void data_vio_allocate_data_block (struct data_vio *data_vio, +enum pbn_lock_type write_lock_type, +vdo_action_fn callback,vdo_action_fn error_handler) +{ +struct allocation *allocation = &data_vio->allocation; + +ASSERT_LOG_ONLY ((allocation->pbn ==VDO_ZERO_BLOCK ), +"data_vio does not have an allocation" ); + allocation->write_lock_type = write_lock_type; + allocation->zone =vdo_get_next_allocation_zone (data_vio->logical.zone); + allocation->first_allocation_zone = allocation->zone->zone_number; + + data_vio->vio.completion.error_handler = error_handler; +launch_data_vio_allocated_zone_callback (data_vio, callback); +} + +/** +* release_data_vio_allocation_lock() - Release the PBN lock on a data_vio's allocated block. +* @reset: If true, the allocation will be reset (i.e. any allocated pbn will be forgotten). +* +* If the reference to the locked block is still provisional, it will be released as well. +*/ +void release_data_vio_allocation_lock (struct data_vio *data_vio,bool reset) +{ +struct allocation *allocation = &data_vio->allocation; +physical_block_number_t locked_pbn = allocation->pbn; + +assert_data_vio_in_allocated_zone (data_vio); + +if (reset ||vdo_pbn_lock_has_provisional_reference (allocation->lock)) + allocation->pbn =VDO_ZERO_BLOCK ; + +vdo_release_physical_zone_pbn_lock (allocation->zone, locked_pbn, +uds_forget (allocation->lock)); +} + +/** +* uncompress_data_vio() - Uncompress the data a data_vio has just read. +* @mapping_state: The mapping state indicating which fragment to decompress. +* @buffer: The buffer to receive the uncompressed data. +*/ +int uncompress_data_vio (struct data_vio *data_vio, +enum block_mapping_state mapping_state,char *buffer) +{ +int size; +u16 fragment_offset, fragment_size; +struct compressed_block *block = data_vio->compression.block; +int result =vdo_get_compressed_block_fragment (mapping_state, block, + &fragment_offset, &fragment_size); + +if (result !=VDO_SUCCESS ) { +uds_log_debug ("%s: compressed fragment error %d" , __func__, result); +return result; + } + + size =LZ4_decompress_safe ((block->data + fragment_offset), buffer, + fragment_size,VDO_BLOCK_SIZE ); +if (size !=VDO_BLOCK_SIZE ) { +uds_log_debug ("%s: lz4 error" , __func__); +return VDO_INVALID_FRAGMENT ; + } + +return VDO_SUCCESS ; +} + +/** +* modify_for_partial_write() - Do the modify-write part of a read-modify-write cycle. +* @completion: The data_vio which has just finished its read. +* +* This callback is registered in read_block(). +*/ +static void modify_for_partial_write (struct vdo_completion *completion) +{ +struct data_vio *data_vio =as_data_vio (completion); +char *data = data_vio->vio.data; +struct bio *bio = data_vio->user_bio; + +assert_data_vio_on_cpu_thread (data_vio); + +if (bio_op (bio) ==REQ_OP_DISCARD ) { +memset (data + data_vio->offset,'\0' ,min_t (u32, + data_vio->remaining_discard, +VDO_BLOCK_SIZE - data_vio->offset)); + }else { +copy_from_bio (bio, data + data_vio->offset); + } + + data_vio->is_zero =is_zero_block (data); + data_vio->read = false; +launch_data_vio_logical_callback (data_vio, + continue_data_vio_with_block_map_slot); +} + +static void complete_read (struct vdo_completion *completion) +{ +struct data_vio *data_vio =as_data_vio (completion); +char *data = data_vio->vio.data; +bool compressed =vdo_is_state_compressed (data_vio->mapped.state); + +assert_data_vio_on_cpu_thread (data_vio); + +if (compressed) { +int result =uncompress_data_vio (data_vio, data_vio->mapped.state, data); + +if (result !=VDO_SUCCESS ) { +continue_data_vio_with_error (data_vio, result); +return ; + } + } + +if (data_vio->write) { +modify_for_partial_write (completion); +return ; + } + +if (compressed || data_vio->is_partial) +copy_to_bio (data_vio->user_bio, data + data_vio->offset); + +acknowledge_data_vio (data_vio); +complete_data_vio (completion); +} + +static void read_endio (struct bio *bio) +{ +struct data_vio *data_vio =vio_as_data_vio (bio->bi_private); +int result =blk_status_to_errno (bio->bi_status); + +vdo_count_completed_bios (bio); +if (result !=VDO_SUCCESS ) { +continue_data_vio_with_error (data_vio, result); +return ; + } + +launch_data_vio_cpu_callback (data_vio, complete_read, +CPU_Q_COMPLETE_READ_PRIORITY ); +} + +static void complete_zero_read (struct vdo_completion *completion) +{ +struct data_vio *data_vio =as_data_vio (completion); + +assert_data_vio_on_cpu_thread (data_vio); + +if (data_vio->is_partial) { +memset (data_vio->vio.data,0 ,VDO_BLOCK_SIZE ); +if (data_vio->write) { +modify_for_partial_write (completion); +return ; + } + }else { +zero_fill_bio (data_vio->user_bio); + } + +complete_read (completion); +} + +/** +* read_block() - Read a block asynchronously. +* +* This is the callback registered in read_block_mapping(). +*/ +static void read_block (struct vdo_completion *completion) +{ +struct data_vio *data_vio =as_data_vio (completion); +struct vio *vio =as_vio (completion); +int result =VDO_SUCCESS ; + +if (data_vio->mapped.pbn ==VDO_ZERO_BLOCK ) { +launch_data_vio_cpu_callback (data_vio, complete_zero_read, +CPU_Q_COMPLETE_VIO_PRIORITY ); +return ; + } + + data_vio->last_async_operation =VIO_ASYNC_OP_READ_DATA_VIO ; +if (vdo_is_state_compressed (data_vio->mapped.state)) { + result =vio_reset_bio (vio, (char *) data_vio->compression.block, + read_endio,REQ_OP_READ , data_vio->mapped.pbn); + }else { +int opf = ((data_vio->user_bio->bi_opf &PASSTHROUGH_FLAGS ) |REQ_OP_READ ); + +if (data_vio->is_partial) { + result =vio_reset_bio (vio, vio->data, read_endio, opf, + data_vio->mapped.pbn); + }else { +/* A full 4k read. Use the incoming bio to avoid having to copy the data */ +bio_reset (vio->bio, vio->bio->bi_bdev, opf); +bio_init_clone (data_vio->user_bio->bi_bdev, vio->bio, + data_vio->user_bio,GFP_KERNEL ); + +/* Copy over the original bio iovec and opflags. */ +vdo_set_bio_properties (vio->bio, vio, read_endio, opf, + data_vio->mapped.pbn); + } + } + +if (result !=VDO_SUCCESS ) { +continue_data_vio_with_error (data_vio, result); +return ; + } + +submit_data_vio_io (data_vio); +} + +static inline struct data_vio * +reference_count_update_completion_as_data_vio (struct vdo_completion *completion) +{ +if (completion->type ==VIO_COMPLETION ) +return as_data_vio (completion); + + return container_of(completion, struct data_vio, decrement_completion); +} + +/** +* update_block_map() - Rendezvous of the data_vio and decrement completions after each has +* made its reference updates. Handle any error from either, or proceed +* to updating the block map. +* @completion: The completion of the write in progress. +*/ +static void update_block_map (struct vdo_completion *completion) +{ +struct data_vio *data_vio =reference_count_update_completion_as_data_vio (completion); + +assert_data_vio_in_logical_zone (data_vio); + +if (!data_vio->first_reference_operation_complete) { +/* Rendezvous, we're first */ + data_vio->first_reference_operation_complete = true; +return ; + } + + completion = &data_vio->vio.completion; +vdo_set_completion_result (completion, data_vio->decrement_completion.result); +if (completion->result !=VDO_SUCCESS ) { +handle_data_vio_error (completion); +return ; + } + + completion->error_handler = handle_data_vio_error; +if (data_vio->hash_lock !=NULL ) +set_data_vio_hash_zone_callback (data_vio, vdo_continue_hash_lock); +else + completion->callback = complete_data_vio; + + data_vio->last_async_operation =VIO_ASYNC_OP_PUT_MAPPED_BLOCK ; +vdo_put_mapped_block (data_vio); +} + +static void decrement_reference_count (struct vdo_completion *completion) +{ + struct data_vio *data_vio = container_of(completion, struct data_vio, + decrement_completion); + +assert_data_vio_in_mapped_zone (data_vio); + +vdo_set_completion_callback (completion, update_block_map, + data_vio->logical.zone->thread_id); + completion->error_handler = update_block_map; +vdo_modify_reference_count (completion, &data_vio->decrement_updater); +} + +static void increment_reference_count (struct vdo_completion *completion) +{ +struct data_vio *data_vio =as_data_vio (completion); + +assert_data_vio_in_new_mapped_zone (data_vio); + +if (data_vio->downgrade_allocation_lock) { +/* +* Now that the data has been written, it's safe to deduplicate against the +* block. Downgrade the allocation lock to a read lock so it can be used later by +* the hash lock. This is done here since it needs to happen sometime before we +* return to the hash zone, and we are currently on the correct thread. For +* compressed blocks, the downgrade will have already been done. +*/ +vdo_downgrade_pbn_write_lock (data_vio->allocation.lock, false); + } + +set_data_vio_logical_callback (data_vio, update_block_map); + completion->error_handler = update_block_map; +vdo_modify_reference_count (completion, &data_vio->increment_updater); +} + +/** journal_remapping() - Add a recovery journal entry for a data remapping. */ +static void journal_remapping (struct vdo_completion *completion) +{ +struct data_vio *data_vio =as_data_vio (completion); + +assert_data_vio_in_journal_zone (data_vio); + + data_vio->decrement_updater.operation =VDO_JOURNAL_DATA_REMAPPING ; + data_vio->decrement_updater.zpbn = data_vio->mapped; +if (data_vio->new_mapped.pbn ==VDO_ZERO_BLOCK ) { + data_vio->first_reference_operation_complete = true; +if (data_vio->mapped.pbn ==VDO_ZERO_BLOCK ) +set_data_vio_logical_callback (data_vio, update_block_map); + }else { +set_data_vio_new_mapped_zone_callback (data_vio, + increment_reference_count); + } + +if (data_vio->mapped.pbn ==VDO_ZERO_BLOCK ) { + data_vio->first_reference_operation_complete = true; + }else { +vdo_set_completion_callback (&data_vio->decrement_completion, + decrement_reference_count, + data_vio->mapped.zone->thread_id); + } + + data_vio->last_async_operation =VIO_ASYNC_OP_JOURNAL_REMAPPING ; +vdo_add_recovery_journal_entry (completion->vdo->recovery_journal, data_vio); +} + +/** +* read_old_block_mapping() - Get the previous PBN/LBN mapping of an in-progress write. +* +* Gets the previous PBN mapped to this LBN from the block map, so as to make an appropriate +* journal entry referencing the removal of this LBN->PBN mapping. +*/ +static void read_old_block_mapping (struct vdo_completion *completion) +{ +struct data_vio *data_vio =as_data_vio (completion); + +assert_data_vio_in_logical_zone (data_vio); + + data_vio->last_async_operation =VIO_ASYNC_OP_GET_MAPPED_BLOCK_FOR_WRITE ; +set_data_vio_journal_callback (data_vio, journal_remapping); +vdo_get_mapped_block (data_vio); +} + +void update_metadata_for_data_vio_write (struct data_vio *data_vio,struct pbn_lock *lock) +{ + data_vio->increment_updater = (struct reference_updater ) { + .operation =VDO_JOURNAL_DATA_REMAPPING , + .increment = true, + .zpbn = data_vio->new_mapped, + .lock = lock, + }; + +launch_data_vio_logical_callback (data_vio, read_old_block_mapping); +} + +/** +* pack_compressed_data() - Attempt to pack the compressed data_vio into a block. +* +* This is the callback registered in launch_compress_data_vio(). +*/ +static void pack_compressed_data (struct vdo_completion *completion) +{ +struct data_vio *data_vio =as_data_vio (completion); + +assert_data_vio_in_packer_zone (data_vio); + +if (!vdo_get_compressing (vdo_from_data_vio (data_vio)) || +get_data_vio_compression_status (data_vio).may_not_compress) { +write_data_vio (data_vio); +return ; + } + + data_vio->last_async_operation =VIO_ASYNC_OP_ATTEMPT_PACKING ; +vdo_attempt_packing (data_vio); +} + +/** +* compress_data_vio() - Do the actual work of compressing the data on a CPU queue. +* +* This callback is registered in launch_compress_data_vio(). +*/ +static void compress_data_vio (struct vdo_completion *completion) +{ +struct data_vio *data_vio =as_data_vio (completion); +int size; + +assert_data_vio_on_cpu_thread (data_vio); + +/* +* By putting the compressed data at the start of the compressed block data field, we won't +* need to copy it if this data_vio becomes a compressed write agent. +*/ + size =LZ4_compress_default (data_vio->vio.data, + data_vio->compression.block->data,VDO_BLOCK_SIZE , +VDO_MAX_COMPRESSED_FRAGMENT_SIZE , + (char *)vdo_get_work_queue_private_data ()); +if ((size >0 ) && (size <VDO_COMPRESSED_BLOCK_DATA_SIZE )) { + data_vio->compression.size = size; +launch_data_vio_packer_callback (data_vio, pack_compressed_data); +return ; + } + +write_data_vio (data_vio); +} + +/** +* launch_compress_data_vio() - Continue a write by attempting to compress the data. +* +* This is a re-entry point to vio_write used by hash locks. +*/ +void launch_compress_data_vio (struct data_vio *data_vio) +{ +ASSERT_LOG_ONLY (!data_vio->is_duplicate,"compressing a non-duplicate block" ); +ASSERT_LOG_ONLY (data_vio->hash_lock !=NULL , +"data_vio to compress has a hash_lock" ); +ASSERT_LOG_ONLY (data_vio_has_allocation (data_vio), +"data_vio to compress has an allocation" ); + +/* +* There are 4 reasons why a data_vio which has reached this point will not be eligible for +* compression: +* +* 1) Since data_vios can block indefinitely in the packer, it would be bad to do so if the +* write request also requests FUA. +* +* 2) A data_vio should not be compressed when compression is disabled for the vdo. +* +* 3) A data_vio could be doing a partial write on behalf of a larger discard which has not +* yet been acknowledged and hence blocking in the packer would be bad. +* +* 4) Some other data_vio may be waiting on this data_vio in which case blocking in the +* packer would also be bad. +*/ +if (data_vio->fua || + !vdo_get_compressing (vdo_from_data_vio (data_vio)) || + ((data_vio->user_bio !=NULL ) && (bio_op (data_vio->user_bio) ==REQ_OP_DISCARD )) || + (advance_data_vio_compression_stage (data_vio).stage !=DATA_VIO_COMPRESSING )) { +write_data_vio (data_vio); +return ; + } + + data_vio->last_async_operation =VIO_ASYNC_OP_COMPRESS_DATA_VIO ; +launch_data_vio_cpu_callback (data_vio, compress_data_vio, +CPU_Q_COMPRESS_BLOCK_PRIORITY ); +} + +/** +* hash_data_vio() - Hash the data in a data_vio and set the hash zone (which also flags the record +* name as set). + +* This callback is registered in prepare_for_dedupe(). +*/ +static void hash_data_vio (struct vdo_completion *completion) +{ +struct data_vio *data_vio =as_data_vio (completion); + +assert_data_vio_on_cpu_thread (data_vio); +ASSERT_LOG_ONLY (!data_vio->is_zero,"zero blocks should not be hashed" ); + +murmurhash3_128 (data_vio->vio.data,VDO_BLOCK_SIZE ,0x62ea60be , + &data_vio->record_name); + + data_vio->hash_zone =vdo_select_hash_zone (vdo_from_data_vio (data_vio)->hash_zones, + &data_vio->record_name); + data_vio->last_async_operation =VIO_ASYNC_OP_ACQUIRE_VDO_HASH_LOCK ; +launch_data_vio_hash_zone_callback (data_vio, vdo_acquire_hash_lock); +} + +/** prepare_for_dedupe() - Prepare for the dedupe path after attempting to get an allocation. */ +static void prepare_for_dedupe (struct data_vio *data_vio) +{ +/* We don't care what thread we are on. */ +ASSERT_LOG_ONLY (!data_vio->is_zero,"must not prepare to dedupe zero blocks" ); + +/* +* Before we can dedupe, we need to know the record name, so the first +* step is to hash the block data. +*/ + data_vio->last_async_operation =VIO_ASYNC_OP_HASH_DATA_VIO ; +launch_data_vio_cpu_callback (data_vio, hash_data_vio,CPU_Q_HASH_BLOCK_PRIORITY ); +} + +/** +* write_bio_finished() - This is the bio_end_io function registered in write_block() to be called +* when a data_vio's write to the underlying storage has completed. +*/ +static void write_bio_finished (struct bio *bio) +{ +struct data_vio *data_vio =vio_as_data_vio ((struct vio *) bio->bi_private); + +vdo_count_completed_bios (bio); +vdo_set_completion_result (&data_vio->vio.completion, +blk_status_to_errno (bio->bi_status)); + data_vio->downgrade_allocation_lock = true; +update_metadata_for_data_vio_write (data_vio, data_vio->allocation.lock); +} + +/** write_data_vio() - Write a data block to storage without compression. */ +void write_data_vio (struct data_vio *data_vio) +{ +struct data_vio_compression_status status, new_status; +int result; + +if (!data_vio_has_allocation (data_vio)) { +/* +* There was no space to write this block and we failed to deduplicate or compress +* it. +*/ +continue_data_vio_with_error (data_vio,VDO_NO_SPACE ); +return ; + } + + new_status = (struct data_vio_compression_status ) { + .stage =DATA_VIO_POST_PACKER , + .may_not_compress = true, + }; + +do { + status =get_data_vio_compression_status (data_vio); + }while ((status.stage !=DATA_VIO_POST_PACKER ) && + !set_data_vio_compression_status (data_vio, status, new_status)); + +/* Write the data from the data block buffer. */ + result =vio_reset_bio (&data_vio->vio, data_vio->vio.data, + write_bio_finished,REQ_OP_WRITE , + data_vio->allocation.pbn); +if (result !=VDO_SUCCESS ) { +continue_data_vio_with_error (data_vio, result); +return ; + } + + data_vio->last_async_operation =VIO_ASYNC_OP_WRITE_DATA_VIO ; +submit_data_vio_io (data_vio); +} + +/** +* acknowledge_write_callback() - Acknowledge a write to the requestor. +* +* This callback is registered in allocate_block() and continue_write_with_block_map_slot(). +*/ +static void acknowledge_write_callback (struct vdo_completion *completion) +{ +struct data_vio *data_vio =as_data_vio (completion); +struct vdo *vdo = completion->vdo; + +ASSERT_LOG_ONLY ((!vdo_uses_bio_ack_queue (vdo) || + (vdo_get_callback_thread_id () == vdo->thread_config.bio_ack_thread)), +"%s() called on bio ack queue" , __func__); +ASSERT_LOG_ONLY (data_vio_has_flush_generation_lock (data_vio), +"write VIO to be acknowledged has a flush generation lock" ); +acknowledge_data_vio (data_vio); +if (data_vio->new_mapped.pbn ==VDO_ZERO_BLOCK ) { +/* This is a zero write or discard */ +update_metadata_for_data_vio_write (data_vio,NULL ); +return ; + } + +prepare_for_dedupe (data_vio); +} + +/** +* allocate_block() - Attempt to allocate a block in the current allocation zone. +* +* This callback is registered in continue_write_with_block_map_slot(). +*/ +static void allocate_block (struct vdo_completion *completion) +{ +struct data_vio *data_vio =as_data_vio (completion); + +assert_data_vio_in_allocated_zone (data_vio); + +if (!vdo_allocate_block_in_zone (data_vio)) +return ; + + completion->error_handler = handle_data_vio_error; +WRITE_ONCE (data_vio->allocation_succeeded, true); + data_vio->new_mapped = (struct zoned_pbn ) { + .zone = data_vio->allocation.zone, + .pbn = data_vio->allocation.pbn, + .state =VDO_MAPPING_STATE_UNCOMPRESSED , + }; + +if (data_vio->fua) { +prepare_for_dedupe (data_vio); +return ; + } + + data_vio->last_async_operation =VIO_ASYNC_OP_ACKNOWLEDGE_WRITE ; +launch_data_vio_on_bio_ack_queue (data_vio, acknowledge_write_callback); +} + +/** +* handle_allocation_error() - Handle an error attempting to allocate a block. +* +* This error handler is registered in continue_write_with_block_map_slot(). +*/ +static void handle_allocation_error (struct vdo_completion *completion) +{ +struct data_vio *data_vio =as_data_vio (completion); + +if (completion->result ==VDO_NO_SPACE ) { +/* We failed to get an allocation, but we can try to dedupe. */ +vdo_reset_completion (completion); + completion->error_handler = handle_data_vio_error; +prepare_for_dedupe (data_vio); +return ; + } + +/* We got a "real" error, not just a failure to allocate, so fail the request. */ +handle_data_vio_error (completion); +} + +static int assert_is_trim (struct data_vio *data_vio) +{ +int result =ASSERT (data_vio->is_trim, +"data_vio with no block map page is a trim" ); + +return ((result ==VDO_SUCCESS ) ? result :VDO_READ_ONLY ); +} + +/** +* continue_data_vio_with_block_map_slot() - Read the data_vio's mapping from the block map. +* +* This callback is registered in launch_read_data_vio(). +*/ +void continue_data_vio_with_block_map_slot (struct vdo_completion *completion) +{ +struct data_vio *data_vio =as_data_vio (completion); + +assert_data_vio_in_logical_zone (data_vio); +if (data_vio->read) { +set_data_vio_logical_callback (data_vio, read_block); + data_vio->last_async_operation =VIO_ASYNC_OP_GET_MAPPED_BLOCK_FOR_READ ; +vdo_get_mapped_block (data_vio); +return ; + } + +vdo_acquire_flush_generation_lock (data_vio); + +if (data_vio->tree_lock.tree_slots[0 ].block_map_slot.pbn ==VDO_ZERO_BLOCK ) { +/* +* This is a trim for a block on a block map page which has not been allocated, so +* there's nothing more we need to do. +*/ + completion->callback = complete_data_vio; +continue_data_vio_with_error (data_vio,assert_is_trim (data_vio)); +return ; + } + +/* +* We need an allocation if this is neither a full-block trim nor a +* full-block zero write. +*/ +if (!data_vio->is_zero && (!data_vio->is_trim || data_vio->is_partial)) { +data_vio_allocate_data_block (data_vio,VIO_WRITE_LOCK , allocate_block, + handle_allocation_error); +return ; + } + + +/* +* We don't need to write any data, so skip allocation and just update the block map and +* reference counts (via the journal). +*/ + data_vio->new_mapped.pbn =VDO_ZERO_BLOCK ; +if (data_vio->is_zero) + data_vio->new_mapped.state =VDO_MAPPING_STATE_UNCOMPRESSED ; + +if (data_vio->remaining_discard >VDO_BLOCK_SIZE ) { +/* This is not the final block of a discard so we can't acknowledge it yet. */ +update_metadata_for_data_vio_write (data_vio,NULL ); +return ; + } + + data_vio->last_async_operation =VIO_ASYNC_OP_ACKNOWLEDGE_WRITE ; +launch_data_vio_on_bio_ack_queue (data_vio, acknowledge_write_callback); +}
drivers/md/dm-vdo/data-vio.h new file +669 -0
669 lines not on this page · raw message
Signature · 1 line
2.40.0
Matthew Sakai
maintainerPATCH v5 21/40 dm vdo: add the vdo io_submitter
In reply to Matthew SakaiThe io_submitter handles bio submission from vdo data store to the storage below. It will merge bios when possible.
--- drivers/md/dm-vdo/io-submitter.c | 480 +++++++++++++++++++++++++++++++ drivers/md/dm-vdo/io-submitter.h | 47 +++ 2 files changed, 527 insertions(+) create mode 100644 drivers/md/dm-vdo/io-submitter.c create mode 100644 drivers/md/dm-vdo/io-submitter.h
drivers/md/dm-vdo/io-submitter.c new file +480 -0
@@ -0,0 +1,480 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* +* Copyright 2023 Red Hat +*/ + +#include "io-submitter.h" + +#include <linux/bio.h> +#include <linux/kernel.h> +#include <linux/mutex.h> + +#include "memory-alloc.h" +#include "permassert.h" + +#include "data-vio.h" +#include "logger.h" +#include "types.h" +#include "vdo.h" +#include "vio.h" + +/* +* Submission of bio operations to the underlying storage device will go through a separate work +* queue thread (or more than one) to prevent blocking in other threads if the storage device has a +* full queue. The plug structure allows that thread to do better batching of requests to make the +* I/O more efficient. +* +* When multiple worker threads are used, a thread is chosen for a I/O operation submission based +* on the PBN, so a given PBN will consistently wind up on the same thread. Flush operations are +* assigned round-robin. +* +* The map (protected by the mutex) collects pending I/O operations so that the worker thread can +* reorder them to try to encourage I/O request merging in the request queue underneath. +*/ +struct bio_queue_data { +struct vdo_work_queue *queue; +struct blk_plug plug; +struct int_map *map; +struct mutex lock; +unsigned int queue_number; +}; + +struct io_submitter { +unsigned int num_bio_queues_used; +unsigned int bio_queue_rotation_interval; +struct bio_queue_data bio_queue_data[]; +}; + +static void start_bio_queue (void *ptr) +{ +struct bio_queue_data *bio_queue_data = ptr; + +blk_start_plug (&bio_queue_data->plug); +} + +static void finish_bio_queue (void *ptr) +{ +struct bio_queue_data *bio_queue_data = ptr; + +blk_finish_plug (&bio_queue_data->plug); +} + +static const struct vdo_work_queue_type bio_queue_type = { + .start = start_bio_queue, + .finish = finish_bio_queue, + .max_priority =BIO_Q_MAX_PRIORITY , + .default_priority =BIO_Q_DATA_PRIORITY , +}; + +/** +* count_all_bios() - Determine which bio counter to use. +* @vio: The vio associated with the bio. +* @bio: The bio to count. +*/ +static void count_all_bios (struct vio *vio,struct bio *bio) +{ +struct atomic_statistics *stats = &vio->completion.vdo->stats; + +if (is_data_vio (vio)) { +vdo_count_bios (&stats->bios_out, bio); +return ; + } + +vdo_count_bios (&stats->bios_meta, bio); +if (vio->type ==VIO_TYPE_RECOVERY_JOURNAL ) +vdo_count_bios (&stats->bios_journal, bio); +else if (vio->type ==VIO_TYPE_BLOCK_MAP ) +vdo_count_bios (&stats->bios_page_cache, bio); +} + +/** +* assert_in_bio_zone() - Assert that a vio is in the correct bio zone and not in interrupt +* context. +* @vio: The vio to check. +*/ +static void assert_in_bio_zone (struct vio *vio) +{ +ASSERT_LOG_ONLY (!in_interrupt (),"not in interrupt context" ); +assert_vio_in_bio_zone (vio); +} + +/** +* send_bio_to_device() - Update stats and tracing info, then submit the supplied bio to the OS for +* processing. +* @vio: The vio associated with the bio. +* @bio: The bio to submit to the OS. +*/ +static void send_bio_to_device (struct vio *vio,struct bio *bio) +{ +struct vdo *vdo = vio->completion.vdo; + +assert_in_bio_zone (vio); +atomic64_inc (&vdo->stats.bios_submitted); +count_all_bios (vio, bio); +bio_set_dev (bio,vdo_get_backing_device (vdo)); +submit_bio_noacct (bio); +} + +static sector_t get_bio_sector (struct bio *bio) +{ +return bio->bi_iter.bi_sector; +} + +/** +* process_vio_io() - Submits a vio's bio to the underlying block device. May block if the device +* is busy. This callback should be used by vios which did not attempt to merge. +*/ +void process_vio_io (struct vdo_completion *completion) +{ +struct vio *vio =as_vio (completion); + +send_bio_to_device (vio, vio->bio); +} + +/** +* get_bio_list() - Extract the list of bios to submit from a vio. +* @vio: The vio submitting I/O. +* +* The list will always contain at least one entry (the bio for the vio on which it is called), but +* other bios may have been merged with it as well. +* +* Return: bio The head of the bio list to submit. +*/ +static struct bio *get_bio_list (struct vio *vio) +{ +struct bio *bio; +struct io_submitter *submitter = vio->completion.vdo->io_submitter; +struct bio_queue_data *bio_queue_data = &(submitter->bio_queue_data[vio->bio_zone]); + +assert_in_bio_zone (vio); + +mutex_lock (&bio_queue_data->lock); +vdo_int_map_remove (bio_queue_data->map,get_bio_sector (vio->bios_merged.head)); +vdo_int_map_remove (bio_queue_data->map,get_bio_sector (vio->bios_merged.tail)); + bio = vio->bios_merged.head; +bio_list_init (&vio->bios_merged); +mutex_unlock (&bio_queue_data->lock); + +return bio; +} + +/** +* process_data_vio_io() - Submit a data_vio's bio to the storage below along with any bios that +* have been merged with it. +* +* Context: This call may block and so should only be called from a bio thread. +*/ +static void process_data_vio_io (struct vdo_completion *completion) +{ +struct bio *bio, *next; +struct vio *vio =as_vio (completion); + +assert_in_bio_zone (vio); +for (bio =get_bio_list (vio); bio !=NULL ; bio = next) { + next = bio->bi_next; + bio->bi_next =NULL ; +send_bio_to_device ((struct vio *) bio->bi_private, bio); + } +} + +/** +* get_mergeable_locked() - Attempt to find an already queued bio that the current bio can be +* merged with. +* @map: The bio map to use for merging. +* @vio: The vio we want to merge. +* @back_merge: Set to true for a back merge, false for a front merge. +* +* There are two types of merging possible, forward and backward, which are distinguished by a flag +* that uses kernel elevator terminology. +* +* Return: the vio to merge to, NULL if no merging is possible. +*/ +static struct vio *get_mergeable_locked (struct int_map *map,struct vio *vio, +bool back_merge) +{ +struct bio *bio = vio->bio; +sector_t merge_sector =get_bio_sector (bio); +struct vio *vio_merge; + +if (back_merge) + merge_sector -=VDO_SECTORS_PER_BLOCK ; +else + merge_sector +=VDO_SECTORS_PER_BLOCK ; + + vio_merge =vdo_int_map_get (map, merge_sector); + +if (vio_merge ==NULL ) +return NULL ; + +if (vio->completion.priority != vio_merge->completion.priority) +return NULL ; + +if (bio_data_dir (bio) !=bio_data_dir (vio_merge->bio)) +return NULL ; + +if (bio_list_empty (&vio_merge->bios_merged)) +return NULL ; + +if (back_merge) { +return (get_bio_sector (vio_merge->bios_merged.tail) == merge_sector ? + vio_merge :NULL ); + } + +return (get_bio_sector (vio_merge->bios_merged.head) == merge_sector ? + vio_merge :NULL ); +} + +static int map_merged_vio (struct int_map *bio_map,struct vio *vio) +{ +int result; + + result =vdo_int_map_put (bio_map,get_bio_sector (vio->bios_merged.head), vio, + true,NULL ); +if (result !=VDO_SUCCESS ) +return result; + +return vdo_int_map_put (bio_map,get_bio_sector (vio->bios_merged.tail), vio, true, +NULL ); +} + +static int merge_to_prev_tail (struct int_map *bio_map,struct vio *vio, +struct vio *prev_vio) +{ +vdo_int_map_remove (bio_map,get_bio_sector (prev_vio->bios_merged.tail)); +bio_list_merge (&prev_vio->bios_merged, &vio->bios_merged); +return map_merged_vio (bio_map, prev_vio); +} + +static int merge_to_next_head (struct int_map *bio_map,struct vio *vio, +struct vio *next_vio) +{ +/* +* Handle "next merge" and "gap fill" cases the same way so as to reorder bios in a way +* that's compatible with using funnel queues in work queues. This avoids removing an +* existing completion. +*/ +vdo_int_map_remove (bio_map,get_bio_sector (next_vio->bios_merged.head)); +bio_list_merge_head (&next_vio->bios_merged, &vio->bios_merged); +return map_merged_vio (bio_map, next_vio); +} + +/** +* try_bio_map_merge() - Attempt to merge a vio's bio with other pending I/Os. +* @vio: The vio to merge. +* +* Currently this is only used for data_vios, but is broken out for future use with metadata vios. +* +* Return: whether or not the vio was merged. +*/ +static bool try_bio_map_merge (struct vio *vio) +{ +int result; +bool merged = true; +struct bio *bio = vio->bio; +struct vio *prev_vio, *next_vio; +struct vdo *vdo = vio->completion.vdo; +struct bio_queue_data *bio_queue_data = + &vdo->io_submitter->bio_queue_data[vio->bio_zone]; + + bio->bi_next =NULL ; +bio_list_init (&vio->bios_merged); +bio_list_add (&vio->bios_merged, bio); + +mutex_lock (&bio_queue_data->lock); + prev_vio =get_mergeable_locked (bio_queue_data->map, vio, true); + next_vio =get_mergeable_locked (bio_queue_data->map, vio, false); +if (prev_vio == next_vio) + next_vio =NULL ; + +if ((prev_vio ==NULL ) && (next_vio ==NULL )) { +/* no merge. just add to bio_queue */ + merged = false; + result =vdo_int_map_put (bio_queue_data->map, +get_bio_sector (bio), + vio, true,NULL ); + }else if (next_vio ==NULL ) { +/* Only prev. merge to prev's tail */ + result =merge_to_prev_tail (bio_queue_data->map, vio, prev_vio); + }else { +/* Only next. merge to next's head */ + result =merge_to_next_head (bio_queue_data->map, vio, next_vio); + } + +mutex_unlock (&bio_queue_data->lock); + +/* We don't care about failure of int_map_put in this case. */ +ASSERT_LOG_ONLY (result ==UDS_SUCCESS ,"bio map insertion succeeds" ); +return merged; +} + +/** +* submit_data_vio_io() - Submit I/O for a data_vio. +* @data_vio: the data_vio for which to issue I/O. +* +* If possible, this I/O will be merged other pending I/Os. Otherwise, the data_vio will be sent to +* the appropriate bio zone directly. +*/ +void submit_data_vio_io (struct data_vio *data_vio) +{ +if (try_bio_map_merge (&data_vio->vio)) +return ; + +launch_data_vio_bio_zone_callback (data_vio, process_data_vio_io); +} + +/** +* vdo_submit_metadata_io() - Submit I/O for a metadata vio. +* @vio: the vio for which to issue I/O +* @physical: the physical block number to read or write +* @callback: the bio endio function which will be called after the I/O completes +* @error_handler: the handler for submission or I/O errors (may be NULL) +* @operation: the type of I/O to perform +* @data: the buffer to read or write (may be NULL) +* +* The vio is enqueued on a vdo bio queue so that bio submission (which may block) does not block +* other vdo threads. +* +* That the error handler will run on the correct thread is only true so long as the thread calling +* this function, and the thread set in the endio callback are the same, as well as the fact that +* no error can occur on the bio queue. Currently this is true for all callers, but additional care +* will be needed if this ever changes. +*/ +void vdo_submit_metadata_io (struct vio *vio,physical_block_number_t physical, +bio_end_io_t callback,vdo_action_fn error_handler, +unsigned int operation,char *data) +{ +struct vdo_completion *completion = &vio->completion; +int result; +const struct admin_state_code *code =vdo_get_admin_state (completion->vdo); + + +ASSERT_LOG_ONLY (!code->quiescent,"I/O not allowed in state %s" , code->name); +ASSERT_LOG_ONLY (vio->bio->bi_next ==NULL ,"metadata bio has no next bio" ); + +vdo_reset_completion (completion); + completion->error_handler = error_handler; + result =vio_reset_bio (vio, data, callback, operation |REQ_META , physical); +if (result !=VDO_SUCCESS ) { +continue_vio (vio, result); +return ; + } + +vdo_set_completion_callback (completion, process_vio_io, +get_vio_bio_zone_thread_id (vio)); +vdo_launch_completion_with_priority (completion,get_metadata_priority (vio)); +} + +/** +* vdo_make_io_submitter() - Create an io_submitter structure. +* @thread_count: Number of bio-submission threads to set up. +* @rotation_interval: Interval to use when rotating between bio-submission threads when enqueuing +* completions. +* @max_requests_active: Number of bios for merge tracking. +* @vdo: The vdo which will use this submitter. +* @io_submitter: pointer to the new data structure. +* +* Return: VDO_SUCCESS or an error. +*/ +int vdo_make_io_submitter (unsigned int thread_count,unsigned int rotation_interval, +unsigned int max_requests_active,struct vdo *vdo, +struct io_submitter **io_submitter_ptr) +{ +unsigned int i; +struct io_submitter *io_submitter; +int result; + + result = uds_allocate_extended(struct io_submitter, thread_count, + struct bio_queue_data, "bio submission data", + &io_submitter); +if (result !=UDS_SUCCESS ) +return result; + + io_submitter->bio_queue_rotation_interval = rotation_interval; + +/* Setup for each bio-submission work queue */ +for (i =0 ; i < thread_count; i++) { +struct bio_queue_data *bio_queue_data = &io_submitter->bio_queue_data[i]; + +mutex_init (&bio_queue_data->lock); +/* +* One I/O operation per request, but both first & last sector numbers. +* +* If requests are assigned to threads round-robin, they should be distributed +* quite evenly. But if they're assigned based on PBN, things can sometimes be very +* uneven. So for now, we'll assume that all requests *may* wind up on one thread, +* and thus all in the same map. +*/ + result =vdo_make_int_map (max_requests_active *2 ,0 , + &bio_queue_data->map); +if (result !=0 ) { +/* +* Clean up the partially initialized bio-queue entirely and indicate that +* initialization failed. +*/ +uds_log_error ("bio map initialization failed %d" , result); +vdo_cleanup_io_submitter (io_submitter); +vdo_free_io_submitter (io_submitter); +return result; + } + + bio_queue_data->queue_number = i; + result =vdo_make_thread (vdo, vdo->thread_config.bio_threads[i], + &bio_queue_type,1 , (void **) &bio_queue_data); +if (result !=VDO_SUCCESS ) { +/* +* Clean up the partially initialized bio-queue entirely and indicate that +* initialization failed. +*/ +vdo_free_int_map (uds_forget (bio_queue_data->map)); +uds_log_error ("bio queue initialization failed %d" , result); +vdo_cleanup_io_submitter (io_submitter); +vdo_free_io_submitter (io_submitter); +return result; + } + + bio_queue_data->queue = vdo->threads[vdo->thread_config.bio_threads[i]].queue; + io_submitter->num_bio_queues_used++; + } + + *io_submitter_ptr = io_submitter; + +return VDO_SUCCESS ; +} + +/** +* vdo_cleanup_io_submitter() - Tear down the io_submitter fields as needed for a physical layer. +* @io_submitter: The I/O submitter data to tear down (may be NULL). +*/ +void vdo_cleanup_io_submitter (struct io_submitter *io_submitter) +{ +int i; + +if (io_submitter ==NULL ) +return ; + +for (i = io_submitter->num_bio_queues_used -1 ; i >=0 ; i--) +vdo_finish_work_queue (io_submitter->bio_queue_data[i].queue); +} + +/** +* vdo_free_io_submitter() - Free the io_submitter fields and structure as needed. +* @io_submitter: The I/O submitter data to destroy. +* +* This must be called after vdo_cleanup_io_submitter(). It is used to release resources late in +* the shutdown process to avoid or reduce the chance of race conditions. +*/ +void vdo_free_io_submitter (struct io_submitter *io_submitter) +{ +int i; + +if (io_submitter ==NULL ) +return ; + +for (i = io_submitter->num_bio_queues_used -1 ; i >=0 ; i--) { + io_submitter->num_bio_queues_used--; +/* vdo_destroy() will free the work queue, so just give up our reference to it. */ +uds_forget (io_submitter->bio_queue_data[i].queue); +vdo_free_int_map (uds_forget (io_submitter->bio_queue_data[i].map)); + } +uds_free (io_submitter); +}
drivers/md/dm-vdo/io-submitter.h new file +47 -0
47 lines not on this page · raw message
Signature · 1 line
2.40.0
Matthew Sakai
maintainerPATCH v5 23/40 dm vdo: add use of deduplication index in hash zones
In reply to Matthew SakaiAdd the data and methods that manage queries to the deduplication index and the responses from the index.
--- drivers/md/dm-vdo/dedupe.c | 625 +++++++++++++++++++++++++++++++++++++ drivers/md/dm-vdo/dedupe.h | 26 ++ 2 files changed, 651 insertions(+)
drivers/md/dm-vdo/dedupe.c +625 -0
@@ -143,6 +143,48 @@#include "vdo.h" #include "wait-queue.h" +struct uds_attribute { +struct attribute attr; +const char *(*show_string)(struct hash_zones *hash_zones); +}; + +enum timer_state { +DEDUPE_QUERY_TIMER_IDLE , +DEDUPE_QUERY_TIMER_RUNNING , +DEDUPE_QUERY_TIMER_FIRED , +}; + +enum dedupe_context_state { +DEDUPE_CONTEXT_IDLE , +DEDUPE_CONTEXT_PENDING , +DEDUPE_CONTEXT_TIMED_OUT , +DEDUPE_CONTEXT_COMPLETE , +DEDUPE_CONTEXT_TIMED_OUT_COMPLETE , +}; + +/* Possible index states: closed, opened, or transitioning between those two. */ +enum index_state { +IS_CLOSED , +IS_CHANGING , +IS_OPENED , +}; + +static const char *CLOSED ="closed" ; +static const char *CLOSING ="closing" ; +static const char *ERROR ="error" ; +static const char *OFFLINE ="offline" ; +static const char *ONLINE ="online" ; +static const char *OPENING ="opening" ; +static const char *SUSPENDED ="suspended" ; +static const char *UNKNOWN ="unknown" ; + +/* Version 2 uses the kernel space UDS index and is limited to 16 bytes */ +enum { +UDS_ADVICE_VERSION =2 , +/* version byte + state byte + 64-bit little-endian PBN */ +UDS_ADVICE_SIZE =1 +1 +sizeof (u64), +}; +enum hash_lock_state {/* State for locks that are not in use or are being initialized. */ VDO_HASH_LOCK_INITIALIZING ,
@@ -264,6 +306,13 @@ struct hash_zones {struct hash_zone zones[]; }; +/* These are in milliseconds. */ +unsigned int vdo_dedupe_index_timeout_interval =5000 ; +unsigned int vdo_dedupe_index_min_timer_interval =100 ; +/* Same two variables, in jiffies for easier consumption. */ +static u64 vdo_dedupe_index_timeout_jiffies; +static u64 vdo_dedupe_index_min_timer_jiffies; +static inline struct hash_zone *as_hash_zone (struct vdo_completion *completion) {vdo_assert_completion_type (completion,VDO_HASH_ZONE_COMPLETION );
@@ -282,6 +331,16 @@ static inline void assert_in_hash_zone(struct hash_zone *zone, const char *name) "%s called on hash zone thread", name); } +static inline bool change_context_state (struct dedupe_context *context,int old,int new) +{ +return (atomic_cmpxchg (&context->state, old, new) == old); +} + +static inline bool change_timer_state (struct hash_zone *zone,int old,int new) +{ +return (atomic_cmpxchg (&zone->timer_state, old, new) == old); +} +/** * return_hash_lock_to_pool() - (Re)initialize a hash lock and return it to its pool. * @zone: The zone from which the lock was borrowed.
@@ -1968,6 +2027,379 @@ static u32 hash_key(const void *key)return get_unaligned_le32 (&name->name[4 ]); } +static void dedupe_kobj_release (struct kobject *directory) +{ +uds_free (container_of(directory ,struct hash_zones ,dedupe_directory )); +} + +static ssize_t dedupe_status_show (struct kobject *directory,struct attribute *attr, +char *buf) +{ + struct uds_attribute *ua = container_of(attr, struct uds_attribute, attr); + struct hash_zones *zones = container_of(directory, struct hash_zones, + dedupe_directory); + +if (ua->show_string !=NULL ) +return sprintf (buf,"%s\n" , ua->show_string (zones)); +else +return -EINVAL ; +} + +static ssize_t dedupe_status_store (struct kobject *kobj__always_unused , +struct attribute *attr__always_unused , +const char *buf__always_unused , +size_t length__always_unused ) +{ +return -EINVAL ; +} + +/*----------------------------------------------------------------------*/ + +static const struct sysfs_ops dedupe_sysfs_ops = { + .show = dedupe_status_show, + .store = dedupe_status_store, +}; + +static struct uds_attribute dedupe_status_attribute = { + .attr = {.name ="status" , .mode =0444 , }, + .show_string = vdo_get_dedupe_index_state_name, +}; + +static struct attribute *dedupe_attrs[] = { + &dedupe_status_attribute.attr, +NULL , +}; +ATTRIBUTE_GROUPS (dedupe); + +static const struct kobj_type dedupe_directory_type = { + .release = dedupe_kobj_release, + .sysfs_ops = &dedupe_sysfs_ops, + .default_groups = dedupe_groups, +}; + +static void start_uds_queue (void *ptr) +{ +/* +* Allow the UDS dedupe worker thread to do memory allocations. It will only do allocations +* during the UDS calls that open or close an index, but those allocations can safely sleep +* while reserving a large amount of memory. We could use an allocations_allowed boolean +* (like the base threads do), but it would be an unnecessary embellishment. +*/ +struct vdo_thread *thread =vdo_get_work_queue_owner (vdo_get_current_work_queue ()); + +uds_register_allocating_thread (&thread->allocating_thread,NULL ); +} + +static void finish_uds_queue (void *ptr__always_unused ) +{ +uds_unregister_allocating_thread (); +} + +static void close_index (struct hash_zones *zones) +{ +int result; + +/* +* Change the index state so that get_index_statistics() will not try to use the index +* session we are closing. +*/ + zones->index_state =IS_CHANGING ; +/* Close the index session, while not holding the lock. */ +spin_unlock (&zones->lock); + result =uds_close_index (zones->index_session); + +if (result !=UDS_SUCCESS ) +uds_log_error_strerror (result,"Error closing index" ); +spin_lock (&zones->lock); + zones->index_state =IS_CLOSED ; + zones->error_flag |= result !=UDS_SUCCESS ; +/* ASSERTION: We leave in IS_CLOSED state. */ +} + +static void open_index (struct hash_zones *zones) +{ +/* ASSERTION: We enter in IS_CLOSED state. */ +int result; +bool create_flag = zones->create_flag; + + zones->create_flag = false; +/* +* Change the index state so that the it will be reported to the outside world as +* "opening". +*/ + zones->index_state =IS_CHANGING ; + zones->error_flag = false; + +/* Open the index session, while not holding the lock */ +spin_unlock (&zones->lock); + result =uds_open_index (create_flag ?UDS_CREATE :UDS_LOAD , + &zones->parameters, zones->index_session); +if (result !=UDS_SUCCESS ) +uds_log_error_strerror (result,"Error opening index" ); + +spin_lock (&zones->lock); +if (!create_flag) { +switch (result) { +case -ENOENT : +/* +* Either there is no index, or there is no way we can recover the index. +* We will be called again and try to create a new index. +*/ + zones->index_state =IS_CLOSED ; + zones->create_flag = true; +return ; +default : +break ; + } + } +if (result ==UDS_SUCCESS ) { + zones->index_state =IS_OPENED ; + }else { + zones->index_state =IS_CLOSED ; + zones->index_target =IS_CLOSED ; + zones->error_flag = true; +spin_unlock (&zones->lock); +uds_log_info ("Setting UDS index target state to error" ); +spin_lock (&zones->lock); + } +/* +* ASSERTION: On success, we leave in IS_OPENED state. +* ASSERTION: On failure, we leave in IS_CLOSED state. +*/ +} + +static void change_dedupe_state (struct vdo_completion *completion) +{ +struct hash_zones *zones =as_hash_zones (completion); + +spin_lock (&zones->lock); + +/* Loop until the index is in the target state and the create flag is clear. */ +while (vdo_is_state_normal (&zones->state) && + ((zones->index_state != zones->index_target) || zones->create_flag)) { +if (zones->index_state ==IS_OPENED ) +close_index (zones); +else +open_index (zones); + } + + zones->changing = false; +spin_unlock (&zones->lock); +} + +static void start_expiration_timer (struct dedupe_context *context) +{ +u64 start_time = context->submission_jiffies; +u64 end_time; + +if (!change_timer_state (context->zone,DEDUPE_QUERY_TIMER_IDLE , +DEDUPE_QUERY_TIMER_RUNNING )) +return ; + + end_time =max (start_time + vdo_dedupe_index_timeout_jiffies, + jiffies + vdo_dedupe_index_min_timer_jiffies); +mod_timer (&context->zone->timer, end_time); +} + +/** +* report_dedupe_timeouts() - Record and eventually report that some dedupe requests reached their +* expiration time without getting answers, so we timed them out. +* @zones: the hash zones. +* @timeouts: the number of newly timed out requests. +*/ +static void report_dedupe_timeouts (struct hash_zones *zones,unsigned int timeouts) +{ +atomic64_add (timeouts, &zones->timeouts); +spin_lock (&zones->lock); +if (__ratelimit (&zones->ratelimiter)) { +u64 unreported =atomic64_read (&zones->timeouts); + + unreported -= zones->reported_timeouts; +uds_log_debug ("UDS index timeout on %llu requests" , + (unsigned long long ) unreported); + zones->reported_timeouts += unreported; + } +spin_unlock (&zones->lock); +} + +static int initialize_index (struct vdo *vdo,struct hash_zones *zones) +{ +int result; +off_t uds_offset; +struct volume_geometry geometry = vdo->geometry; +static const struct vdo_work_queue_type uds_queue_type = { + .start = start_uds_queue, + .finish = finish_uds_queue, + .max_priority =UDS_Q_MAX_PRIORITY , + .default_priority =UDS_Q_PRIORITY , + }; + +vdo_set_dedupe_index_timeout_interval (vdo_dedupe_index_timeout_interval); +vdo_set_dedupe_index_min_timer_interval (vdo_dedupe_index_min_timer_interval); + +/* +* Since we will save up the timeouts that would have been reported but were ratelimited, +* we don't need to report ratelimiting. +*/ +ratelimit_default_init (&zones->ratelimiter); +ratelimit_set_flags (&zones->ratelimiter,RATELIMIT_MSG_ON_RELEASE ); + uds_offset = ((vdo_get_index_region_start (geometry) - + geometry.bio_offset) *VDO_BLOCK_SIZE ); + zones->parameters = (struct uds_parameters ) { + .bdev = vdo->device_config->owned_device->bdev, + .offset = uds_offset, + .size = (vdo_get_index_region_size (geometry) *VDO_BLOCK_SIZE ), + .memory_size = geometry.index_config.mem, + .sparse = geometry.index_config.sparse, + .nonce = (u64 ) geometry.nonce, + }; + + result =uds_create_index_session (&zones->index_session); +if (result !=UDS_SUCCESS ) +return result; + + result =vdo_make_thread (vdo, vdo->thread_config.dedupe_thread, &uds_queue_type, +1 ,NULL ); +if (result !=VDO_SUCCESS ) { +uds_destroy_index_session (uds_forget (zones->index_session)); +uds_log_error ("UDS index queue initialization failed (%d)" , result); +return result; + } + +vdo_initialize_completion (&zones->completion, vdo,VDO_HASH_ZONES_COMPLETION ); +vdo_set_completion_callback (&zones->completion, change_dedupe_state, + vdo->thread_config.dedupe_thread); +kobject_init (&zones->dedupe_directory, &dedupe_directory_type); +return VDO_SUCCESS ; +} + +/** +* finish_index_operation() - This is the UDS callback for index queries. +* @request: The uds request which has just completed. +*/ +static void finish_index_operation (struct uds_request *request) +{ + struct dedupe_context *context = container_of(request, struct dedupe_context, + request); + +if (change_context_state (context,DEDUPE_CONTEXT_PENDING , +DEDUPE_CONTEXT_COMPLETE )) { +/* +* This query has not timed out, so send its data_vio back to its hash zone to +* process the results. +*/ +continue_data_vio (context->requestor); +return ; + } + +/* +* This query has timed out, so try to mark it complete and hence eligible for reuse. Its +* data_vio has already moved on. +*/ +if (!change_context_state (context,DEDUPE_CONTEXT_TIMED_OUT , +DEDUPE_CONTEXT_TIMED_OUT_COMPLETE )) +ASSERT_LOG_ONLY (false,"uds request was timed out (state %d)" , +atomic_read (&context->state)); + +uds_funnel_queue_put (context->zone->timed_out_complete, &context->queue_entry); +} + +/** +* check_for_drain_complete() - Check whether this zone has drained. +* @zone: The zone to check. +*/ +static void check_for_drain_complete (struct hash_zone *zone) +{ +data_vio_count_t recycled =0 ; + +if (!vdo_is_state_draining (&zone->state)) +return ; + +if ((atomic_read (&zone->timer_state) ==DEDUPE_QUERY_TIMER_IDLE ) || +change_timer_state (zone,DEDUPE_QUERY_TIMER_RUNNING , +DEDUPE_QUERY_TIMER_IDLE )) { +del_timer_sync (&zone->timer); + }else { +/* +* There is an in flight time-out, which must get processed before we can continue. +*/ +return ; + } + +for (;;) { +struct dedupe_context *context; +struct funnel_queue_entry *entry; + + entry =uds_funnel_queue_poll (zone->timed_out_complete); +if (entry ==NULL ) +break ; + + context = container_of(entry, struct dedupe_context, queue_entry); +atomic_set (&context->state,DEDUPE_CONTEXT_IDLE ); +list_add (&context->list_entry, &zone->available); + recycled++; + } + +if (recycled >0 ) +WRITE_ONCE (zone->active, zone->active - recycled); +ASSERT_LOG_ONLY (READ_ONCE (zone->active) ==0 ,"all contexts inactive" ); +vdo_finish_draining (&zone->state); +} + +static void timeout_index_operations_callback (struct vdo_completion *completion) +{ +struct dedupe_context *context, *tmp; +struct hash_zone *zone =as_hash_zone (completion); +u64 timeout_jiffies =msecs_to_jiffies (vdo_dedupe_index_timeout_interval); +unsigned long cutoff = jiffies - timeout_jiffies; +unsigned int timed_out =0 ; + +atomic_set (&zone->timer_state,DEDUPE_QUERY_TIMER_IDLE ); +list_for_each_entry_safe (context, tmp, &zone->pending, list_entry) { +if (cutoff <= context->submission_jiffies) { +/* +* We have reached the oldest query which has not timed out yet, so restart +* the timer. +*/ +start_expiration_timer (context); +break ; + } + +if (!change_context_state (context,DEDUPE_CONTEXT_PENDING , +DEDUPE_CONTEXT_TIMED_OUT )) { +/* +* This context completed between the time the timeout fired, and now. We +* can treat it as a a successful query, its requestor is already enqueued +* to process it. +*/ +continue ; + } + +/* +* Remove this context from the pending list so we won't look at it again on a +* subsequent timeout. Once the index completes it, it will be reused. Meanwhile, +* send its requestor on its way. +*/ +list_del_init (&context->list_entry); +continue_data_vio (context->requestor); + timed_out++; + } + +if (timed_out >0 ) +report_dedupe_timeouts (completion->vdo->hash_zones, timed_out); + +check_for_drain_complete (zone); +} + +static void timeout_index_operations (struct timer_list *t) +{ +struct hash_zone *zone =from_timer (zone, t, timer); + +if (change_timer_state (zone,DEDUPE_QUERY_TIMER_RUNNING , +DEDUPE_QUERY_TIMER_FIRED )) +vdo_launch_completion (&zone->completion); +} +static int __must_check initialize_zone (struct vdo *vdo,struct hash_zones *zones,zone_count_t zone_number) {
@@ -2441,3 +2873,196 @@ void vdo_dump_hash_zones(struct hash_zones *zones)for (zone =0 ; zone < zones->zone_count; zone++)dump_hash_zone (&zones->zones[zone]); } + +void vdo_set_dedupe_index_timeout_interval (unsigned int value) +{ +u64 alb_jiffies; + +/* Arbitrary maximum value is two minutes */ +if (value >120000 ) + value =120000 ; +/* Arbitrary minimum value is 2 jiffies */ + alb_jiffies =msecs_to_jiffies (value); + +if (alb_jiffies <2 ) { + alb_jiffies =2 ; + value =jiffies_to_msecs (alb_jiffies); + } + vdo_dedupe_index_timeout_interval = value; + vdo_dedupe_index_timeout_jiffies = alb_jiffies; +} + +void vdo_set_dedupe_index_min_timer_interval (unsigned int value) +{ +u64 min_jiffies; + +/* Arbitrary maximum value is one second */ +if (value >1000 ) + value =1000 ; + +/* Arbitrary minimum value is 2 jiffies */ + min_jiffies =msecs_to_jiffies (value); + +if (min_jiffies <2 ) { + min_jiffies =2 ; + value =jiffies_to_msecs (min_jiffies); + } + + vdo_dedupe_index_min_timer_interval = value; + vdo_dedupe_index_min_timer_jiffies = min_jiffies; +} + +/** +* acquire_context() - Acquire a dedupe context from a hash_zone if any are available. +* @zone: the hash zone +* +* Return: A dedupe_context or NULL if none are available +*/ +static struct dedupe_context *__must_check acquire_context (struct hash_zone *zone) +{ +struct dedupe_context *context; +struct funnel_queue_entry *entry; + +assert_in_hash_zone (zone, __func__); + +if (!list_empty (&zone->available)) { +WRITE_ONCE (zone->active, zone->active +1 ); + context = list_first_entry(&zone->available, struct dedupe_context, + list_entry); +list_del_init (&context->list_entry); +return context; + } + + entry =uds_funnel_queue_poll (zone->timed_out_complete); +return ((entry ==NULL ) ? + NULL : container_of(entry, struct dedupe_context, queue_entry)); +} + +static void prepare_uds_request (struct uds_request *request,struct data_vio *data_vio, +enum uds_request_type operation) +{ + request->record_name = data_vio->record_name; + request->type = operation; +if ((operation ==UDS_POST ) || (operation ==UDS_UPDATE )) { +size_t offset =0 ; +struct uds_record_data *encoding = &request->new_metadata; + + encoding->data[offset++] =UDS_ADVICE_VERSION ; + encoding->data[offset++] = data_vio->new_mapped.state; +put_unaligned_le64 (data_vio->new_mapped.pbn, &encoding->data[offset]); + offset +=sizeof (u64); +BUG_ON (offset !=UDS_ADVICE_SIZE ); + } +} + +/* +* The index operation will inquire about data_vio.record_name, providing (if the operation is +* appropriate) advice from the data_vio's new_mapped fields. The advice found in the index (or +* NULL if none) will be returned via receive_data_vio_dedupe_advice(). dedupe_context.status is +* set to the return status code of any asynchronous index processing. +*/ +static void query_index (struct data_vio *data_vio,enum uds_request_type operation) +{ +int result; +struct dedupe_context *context; +struct vdo *vdo =vdo_from_data_vio (data_vio); +struct hash_zone *zone = data_vio->hash_zone; + +assert_data_vio_in_hash_zone (data_vio); + +if (!READ_ONCE (vdo->hash_zones->dedupe_flag)) { +continue_data_vio (data_vio); +return ; + } + + context =acquire_context (zone); +if (context ==NULL ) { +atomic64_inc (&vdo->hash_zones->dedupe_context_busy); +continue_data_vio (data_vio); +return ; + } + + data_vio->dedupe_context = context; + context->requestor = data_vio; + context->submission_jiffies = jiffies; +prepare_uds_request (&context->request, data_vio, operation); +atomic_set (&context->state,DEDUPE_CONTEXT_PENDING ); +list_add_tail (&context->list_entry, &zone->pending); +start_expiration_timer (context); + result =uds_launch_request (&context->request); +if (result !=UDS_SUCCESS ) { + context->request.status = result; +finish_index_operation (&context->request); + } +} + +static void set_target_state (struct hash_zones *zones,enum index_state target, +bool change_dedupe,bool dedupe,bool set_create) +{ +const char *old_state, *new_state; + +spin_lock (&zones->lock); + old_state =index_state_to_string (zones, zones->index_target); +if (change_dedupe) +WRITE_ONCE (zones->dedupe_flag, dedupe); + +if (set_create) + zones->create_flag = true; + + zones->index_target = target; +launch_dedupe_state_change (zones); + new_state =index_state_to_string (zones, zones->index_target); +spin_unlock (&zones->lock); + +if (old_state != new_state) +uds_log_info ("Setting UDS index target state to %s" , new_state); +} + +const char *vdo_get_dedupe_index_state_name (struct hash_zones *zones) +{ +const char *state; + +spin_lock (&zones->lock); + state =index_state_to_string (zones, zones->index_state); +spin_unlock (&zones->lock); + +return state; +} + +/* Handle a dmsetup message relevant to the index. */ +int vdo_message_dedupe_index (struct hash_zones *zones,const char *name) +{ +if (strcasecmp (name,"index-close" ) ==0 ) { +set_target_state (zones,IS_CLOSED , false, false, false); +return 0 ; + }else if (strcasecmp (name,"index-create" ) ==0 ) { +set_target_state (zones,IS_OPENED , false, false, true); +return 0 ; + }else if (strcasecmp (name,"index-disable" ) ==0 ) { +set_target_state (zones,IS_OPENED , true, false, false); +return 0 ; + }else if (strcasecmp (name,"index-enable" ) ==0 ) { +set_target_state (zones,IS_OPENED , true, true, false); +return 0 ; + } + +return -EINVAL ; +} + +int vdo_add_dedupe_index_sysfs (struct hash_zones *zones) +{ +int result =kobject_add (&zones->dedupe_directory, + &zones->completion.vdo->vdo_directory,"dedupe" ); + +if (result ==0 ) +vdo_set_admin_state_code (&zones->state, +VDO_ADMIN_STATE_NORMAL_OPERATION ); + +return result; +} + +/* If create_flag, create a new index without first attempting to load an existing index. */ +void vdo_start_dedupe_index (struct hash_zones *zones,bool create_flag) +{ +set_target_state (zones,IS_OPENED , true, true, create_flag); +}
drivers/md/dm-vdo/dedupe.h +26 -0
@@ -91,4 +91,30 @@ struct hash_zone * __must_check vdo_select_hash_zone(struct hash_zones *zones,void vdo_dump_hash_zones (struct hash_zones *zones); +const char *vdo_get_dedupe_index_state_name (struct hash_zones *zones); + +u64 vdo_get_dedupe_index_timeout_count (struct hash_zones *zones); + +int vdo_message_dedupe_index (struct hash_zones *zones,const char *name); + +int vdo_add_dedupe_index_sysfs (struct hash_zones *zones); + +void vdo_start_dedupe_index (struct hash_zones *zones,bool create_flag); + +void vdo_resume_hash_zones (struct hash_zones *zones,struct vdo_completion *parent); + +void vdo_finish_dedupe_index (struct hash_zones *zones); + +/* Interval (in milliseconds) from submission until switching to fast path and skipping UDS. */ +extern unsigned int vdo_dedupe_index_timeout_interval; + +/* +* Minimum time interval (in milliseconds) between timer invocations to check for requests waiting +* for UDS that should now time out. +*/ +extern unsigned int vdo_dedupe_index_min_timer_interval; + +void vdo_set_dedupe_index_timeout_interval (unsigned int value); +void vdo_set_dedupe_index_min_timer_interval (unsigned int value); +#endif /* VDO_DEDUPE_H */
Signature · 1 line
2.40.0
Matthew Sakai
maintainerPATCH v5 24/40 dm vdo: add the compressed block bin packer
In reply to Matthew SakaiWhen blocks do not deduplicate, vdo will attempt to compress them. Up to 14 compressed blocks may be packed into a single data block (this limitation is imposed by the block map). The packer implements a simple best-fit packing algorithm and also manages the formatting and writing of compressed blocks when bins fill.
--- drivers/md/dm-vdo/packer.c | 784 +++++++++++++++++++++++++++++++++++++ drivers/md/dm-vdo/packer.h | 122 ++++++ 2 files changed, 906 insertions(+) create mode 100644 drivers/md/dm-vdo/packer.c create mode 100644 drivers/md/dm-vdo/packer.h
drivers/md/dm-vdo/packer.c new file +784 -0
@@ -0,0 +1,784 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* +* Copyright 2023 Red Hat +*/ + +#include "packer.h" + +#include <linux/atomic.h> +#include <linux/blkdev.h> + +#include "logger.h" +#include "memory-alloc.h" +#include "permassert.h" +#include "string-utils.h" + +#include "admin-state.h" +#include "completion.h" +#include "constants.h" +#include "data-vio.h" +#include "dedupe.h" +#include "encodings.h" +#include "io-submitter.h" +#include "physical-zone.h" +#include "status-codes.h" +#include "vdo.h" +#include "vio.h" + +static const struct version_number COMPRESSED_BLOCK_1_0 = { + .major_version =1 , + .minor_version =0 , +}; + +enum { +COMPRESSED_BLOCK_1_0_SIZE =4 +4 + (2 *VDO_MAX_COMPRESSION_SLOTS ), +}; + +/** +* vdo_get_compressed_block_fragment() - Get a reference to a compressed fragment from a compressed +* block. +* @mapping_state [in] The mapping state for the look up. +* @compressed_block [in] The compressed block that was read from disk. +* @fragment_offset [out] The offset of the fragment within a compressed block. +* @fragment_size [out] The size of the fragment. +* +* Return: If a valid compressed fragment is found, VDO_SUCCESS; otherwise, VDO_INVALID_FRAGMENT if +* the fragment is invalid. +*/ +int vdo_get_compressed_block_fragment (enum block_mapping_state mapping_state, +struct compressed_block *block, +u16 *fragment_offset,u16 *fragment_size) +{ +u16 compressed_size; +u16 offset =0 ; +unsigned int i; +u8 slot; +struct version_number version; + +if (!vdo_is_state_compressed (mapping_state)) +return VDO_INVALID_FRAGMENT ; + + version =vdo_unpack_version_number (block->header.version); +if (!vdo_are_same_version (version,COMPRESSED_BLOCK_1_0 )) +return VDO_INVALID_FRAGMENT ; + + slot = mapping_state -VDO_MAPPING_STATE_COMPRESSED_BASE ; +if (slot >=VDO_MAX_COMPRESSION_SLOTS ) +return VDO_INVALID_FRAGMENT ; + + compressed_size =__le16_to_cpu (block->header.sizes[slot]); +for (i =0 ; i < slot; i++) { + offset +=__le16_to_cpu (block->header.sizes[i]); +if (offset >=VDO_COMPRESSED_BLOCK_DATA_SIZE ) +return VDO_INVALID_FRAGMENT ; + } + +if ((offset + compressed_size) >VDO_COMPRESSED_BLOCK_DATA_SIZE ) +return VDO_INVALID_FRAGMENT ; + + *fragment_offset = offset; + *fragment_size = compressed_size; +return VDO_SUCCESS ; +} + +/** +* assert_on_packer_thread() - Check that we are on the packer thread. +* @packer: The packer. +* @caller: The function which is asserting. +*/ +static inline void assert_on_packer_thread (struct packer *packer,const char *caller) +{ +ASSERT_LOG_ONLY ((vdo_get_callback_thread_id () == packer->thread_id), +"%s() called from packer thread" , caller); +} + +/** +* insert_in_sorted_list() - Insert a bin to the list. +* @packer: The packer. +* @bin: The bin to move to its sorted position. +* +* The list is in ascending order of free space. Since all bins are already in the list, this +* actually moves the bin to the correct position in the list. +*/ +static void insert_in_sorted_list (struct packer *packer,struct packer_bin *bin) +{ +struct packer_bin *active_bin; + +list_for_each_entry (active_bin, &packer->bins, list) +if (active_bin->free_space > bin->free_space) { +list_move_tail (&bin->list, &active_bin->list); +return ; + } + +list_move_tail (&bin->list, &packer->bins); +} + +/** +* make_bin() - Allocate a bin and put it into the packer's list. +* @packer: The packer. +*/ +static int __must_check make_bin (struct packer *packer) +{ +struct packer_bin *bin; +int result; + + result = uds_allocate_extended(struct packer_bin, VDO_MAX_COMPRESSION_SLOTS, + struct vio *, __func__, &bin); +if (result !=VDO_SUCCESS ) +return result; + + bin->free_space =VDO_COMPRESSED_BLOCK_DATA_SIZE ; +INIT_LIST_HEAD (&bin->list); +list_add_tail (&bin->list, &packer->bins); +return VDO_SUCCESS ; +} + +/** +* vdo_make_packer() - Make a new block packer. +* +* @vdo: The vdo to which this packer belongs. +* @bin_count: The number of partial bins to keep in memory. +* @packer_ptr: A pointer to hold the new packer. +* +* Return: VDO_SUCCESS or an error +*/ +int vdo_make_packer (struct vdo *vdo,block_count_t bin_count,struct packer **packer_ptr) +{ +struct packer *packer; +block_count_t i; +int result; + + result = uds_allocate(1, struct packer, __func__, &packer); +if (result !=VDO_SUCCESS ) +return result; + + packer->thread_id = vdo->thread_config.packer_thread; + packer->size = bin_count; +INIT_LIST_HEAD (&packer->bins); +vdo_set_admin_state_code (&packer->state,VDO_ADMIN_STATE_NORMAL_OPERATION ); + +for (i =0 ; i < bin_count; i++) { + result =make_bin (packer); +if (result !=VDO_SUCCESS ) { +vdo_free_packer (packer); +return result; + } + } + +/* +* The canceled bin can hold up to half the number of user vios. Every canceled vio in the +* bin must have a canceler for which it is waiting, and any canceler will only have +* canceled one lock holder at a time. +*/ + result = uds_allocate_extended(struct packer_bin, MAXIMUM_VDO_USER_VIOS / 2, + struct vio *, __func__, &packer->canceled_bin); +if (result !=VDO_SUCCESS ) { +vdo_free_packer (packer); +return result; + } + + result =vdo_make_default_thread (vdo, packer->thread_id); +if (result !=VDO_SUCCESS ) { +vdo_free_packer (packer); +return result; + } + + *packer_ptr = packer; +return VDO_SUCCESS ; +} + +/** +* vdo_free_packer() - Free a block packer. +* @packer: The packer to free. +*/ +void vdo_free_packer (struct packer *packer) +{ +struct packer_bin *bin, *tmp; + +if (packer ==NULL ) +return ; + +list_for_each_entry_safe (bin, tmp, &packer->bins, list) { +list_del_init (&bin->list); +uds_free (bin); + } + +uds_free (uds_forget (packer->canceled_bin)); +uds_free (packer); +} + +/** +* get_packer_from_data_vio() - Get the packer from a data_vio. +* @data_vio: The data_vio. +* +* Return: The packer from the VDO to which the data_vio belongs. +*/ +static inline struct packer *get_packer_from_data_vio (struct data_vio *data_vio) +{ +return vdo_from_data_vio (data_vio)->packer; +} + +/** +* vdo_get_packer_statistics() - Get the current statistics from the packer. +* @packer: The packer to query. +* +* Return: a copy of the current statistics for the packer. +*/ +struct packer_statistics vdo_get_packer_statistics (const struct packer *packer) +{ +const struct packer_statistics *stats = &packer->statistics; + +return (struct packer_statistics ) { + .compressed_fragments_written =READ_ONCE (stats->compressed_fragments_written), + .compressed_blocks_written =READ_ONCE (stats->compressed_blocks_written), + .compressed_fragments_in_packer =READ_ONCE (stats->compressed_fragments_in_packer), + }; +} + +/** +* abort_packing() - Abort packing a data_vio. +* @data_vio: The data_vio to abort. +*/ +static void abort_packing (struct data_vio *data_vio) +{ +struct packer *packer =get_packer_from_data_vio (data_vio); + +WRITE_ONCE (packer->statistics.compressed_fragments_in_packer, + packer->statistics.compressed_fragments_in_packer -1 ); + +write_data_vio (data_vio); +} + +/** +* release_compressed_write_waiter() - Update a data_vio for which a successful compressed write +* has completed and send it on its way. + +* @data_vio: The data_vio to release. +* @allocation: The allocation to which the compressed block was written. +*/ +static void release_compressed_write_waiter (struct data_vio *data_vio, +struct allocation *allocation) +{ + data_vio->new_mapped = (struct zoned_pbn ) { + .pbn = allocation->pbn, + .zone = allocation->zone, + .state = data_vio->compression.slot +VDO_MAPPING_STATE_COMPRESSED_BASE , + }; + +vdo_share_compressed_write_lock (data_vio, allocation->lock); +update_metadata_for_data_vio_write (data_vio, allocation->lock); +} + +/** +* finish_compressed_write() - Finish a compressed block write. +* @completion: The compressed write completion. +* +* This callback is registered in continue_after_allocation(). +*/ +static void finish_compressed_write (struct vdo_completion *completion) +{ +struct data_vio *agent =as_data_vio (completion); +struct data_vio *client, *next; + +assert_data_vio_in_allocated_zone (agent); + +/* +* Process all the non-agent waiters first to ensure that the pbn lock can not be released +* until all of them have had a chance to journal their increfs. +*/ +for (client = agent->compression.next_in_batch; client !=NULL ; client = next) { + next = client->compression.next_in_batch; +release_compressed_write_waiter (client, &agent->allocation); + } + + completion->error_handler = handle_data_vio_error; +release_compressed_write_waiter (agent, &agent->allocation); +} + +static void handle_compressed_write_error (struct vdo_completion *completion) +{ +struct data_vio *agent =as_data_vio (completion); +struct allocation *allocation = &agent->allocation; +struct data_vio *client, *next; + +if (vdo_requeue_completion_if_needed (completion, allocation->zone->thread_id)) +return ; + +update_vio_error_stats (as_vio (completion), +"Completing compressed write vio for physical block %llu with error" , + (unsigned long long ) allocation->pbn); + +for (client = agent->compression.next_in_batch; client !=NULL ; client = next) { + next = client->compression.next_in_batch; +write_data_vio (client); + } + +/* Now that we've released the batch from the packer, forget the error and continue on. */ +vdo_reset_completion (completion); + completion->error_handler = handle_data_vio_error; +write_data_vio (agent); +} + +/** +* add_to_bin() - Put a data_vio in a specific packer_bin in which it will definitely fit. +* @bin: The bin in which to put the data_vio. +* @data_vio: The data_vio to add. +*/ +static void add_to_bin (struct packer_bin *bin,struct data_vio *data_vio) +{ + data_vio->compression.bin = bin; + data_vio->compression.slot = bin->slots_used; + bin->incoming[bin->slots_used++] = data_vio; +} + +/** +* remove_from_bin() - Get the next data_vio whose compression has not been canceled from a bin. +* @packer: The packer. +* @bin: The bin from which to get a data_vio. +* +* Any canceled data_vios will be moved to the canceled bin. +* Return: An uncanceled data_vio from the bin or NULL if there are none. +*/ +static struct data_vio *remove_from_bin (struct packer *packer,struct packer_bin *bin) +{ +while (bin->slots_used >0 ) { +struct data_vio *data_vio = bin->incoming[--bin->slots_used]; + +if (!advance_data_vio_compression_stage (data_vio).may_not_compress) { + data_vio->compression.bin =NULL ; +return data_vio; + } + +add_to_bin (packer->canceled_bin, data_vio); + } + +/* The bin is now empty. */ + bin->free_space =VDO_COMPRESSED_BLOCK_DATA_SIZE ; +return NULL ; +} + +/** +* initialize_compressed_block() - Initialize a compressed block. +* @block: The compressed block to initialize. +* @size: The size of the agent's fragment. +* +* This method initializes the compressed block in the compressed write agent. Because the +* compressor already put the agent's compressed fragment at the start of the compressed block's +* data field, it needn't be copied. So all we need do is initialize the header and set the size of +* the agent's fragment. +*/ +static void initialize_compressed_block (struct compressed_block *block,u16 size) +{ +/* +* Make sure the block layout isn't accidentally changed by changing the length of the +* block header. +*/ +BUILD_BUG_ON (sizeof (struct compressed_block_header ) !=COMPRESSED_BLOCK_1_0_SIZE ); + + block->header.version =vdo_pack_version_number (COMPRESSED_BLOCK_1_0 ); + block->header.sizes[0 ] =__cpu_to_le16 (size); +} + +/** +* pack_fragment() - Pack a data_vio's fragment into the compressed block in which it is already +* known to fit. +* @compression: The agent's compression_state to pack in to. +* @data_vio: The data_vio to pack. +* @offset: The offset into the compressed block at which to pack the fragment. +* @compressed_block: The compressed block which will be written out when batch is fully packed. +* +* Return: The new amount of space used. +*/ +static block_size_t __must_check pack_fragment (struct compression_state *compression, +struct data_vio *data_vio, +block_size_t offset,slot_number_t slot, +struct compressed_block *block) +{ +struct compression_state *to_pack = &data_vio->compression; +char *fragment = to_pack->block->data; + + to_pack->next_in_batch = compression->next_in_batch; + compression->next_in_batch = data_vio; + to_pack->slot = slot; + block->header.sizes[slot] =__cpu_to_le16 (to_pack->size); +memcpy (&block->data[offset], fragment, to_pack->size); +return (offset + to_pack->size); +} + +/** +* compressed_write_end_io() - The bio_end_io for a compressed block write. +* @bio: The bio for the compressed write. +*/ +static void compressed_write_end_io (struct bio *bio) +{ +struct data_vio *data_vio =vio_as_data_vio (bio->bi_private); + +vdo_count_completed_bios (bio); +set_data_vio_allocated_zone_callback (data_vio, finish_compressed_write); +continue_data_vio_with_error (data_vio,blk_status_to_errno (bio->bi_status)); +} + +/** +* write_bin() - Write out a bin. +* @packer: The packer. +* @bin: The bin to write. +*/ +static void write_bin (struct packer *packer,struct packer_bin *bin) +{ +int result; +block_size_t offset; +slot_number_t slot =1 ; +struct compression_state *compression; +struct compressed_block *block; +struct data_vio *agent =remove_from_bin (packer, bin); +struct data_vio *client; +struct packer_statistics *stats; + +if (agent ==NULL ) +return ; + + compression = &agent->compression; + compression->slot =0 ; + block = compression->block; +initialize_compressed_block (block, compression->size); + offset = compression->size; + +while ((client =remove_from_bin (packer, bin)) !=NULL ) + offset =pack_fragment (compression, client, offset, slot++, block); + +/* +* If the batch contains only a single vio, then we save nothing by saving the compressed +* form. Continue processing the single vio in the batch. +*/ +if (slot ==1 ) { +abort_packing (agent); +return ; + } + +if (slot <VDO_MAX_COMPRESSION_SLOTS ) { +/* Clear out the sizes of the unused slots */ +memset (&block->header.sizes[slot],0 , + (VDO_MAX_COMPRESSION_SLOTS - slot) *sizeof (__le16)); + } + + agent->vio.completion.error_handler = handle_compressed_write_error; +if (vdo_is_read_only (vdo_from_data_vio (agent))) { +continue_data_vio_with_error (agent,VDO_READ_ONLY ); +return ; + } + + result =vio_reset_bio (&agent->vio, (char *) block, compressed_write_end_io, +REQ_OP_WRITE , agent->allocation.pbn); +if (result !=VDO_SUCCESS ) { +continue_data_vio_with_error (agent, result); +return ; + } + +/* +* Once the compressed write is submitted, the fragments are no longer in the packer, so +* update stats now. +*/ + stats = &packer->statistics; +WRITE_ONCE (stats->compressed_fragments_in_packer, + (stats->compressed_fragments_in_packer - slot)); +WRITE_ONCE (stats->compressed_fragments_written, + (stats->compressed_fragments_written + slot)); +WRITE_ONCE (stats->compressed_blocks_written, + stats->compressed_blocks_written +1 ); + +submit_data_vio_io (agent); +} + +/** +* add_data_vio_to_packer_bin() - Add a data_vio to a bin's incoming queue +* @packer: The packer. +* @bin: The bin to which to add the data_vio. +* @data_vio: The data_vio to add to the bin's queue. +* +* Adds a data_vio to a bin's incoming queue, handles logical space change, and calls physical +* space processor. +*/ +static void add_data_vio_to_packer_bin (struct packer *packer,struct packer_bin *bin, +struct data_vio *data_vio) +{ +/* If the selected bin doesn't have room, start a new batch to make room. */ +if (bin->free_space < data_vio->compression.size) +write_bin (packer, bin); + +add_to_bin (bin, data_vio); + bin->free_space -= data_vio->compression.size; + +/* If we happen to exactly fill the bin, start a new batch. */ +if ((bin->slots_used ==VDO_MAX_COMPRESSION_SLOTS ) || + (bin->free_space ==0 )) +write_bin (packer, bin); + +/* Now that we've finished changing the free space, restore the sort order. */ +insert_in_sorted_list (packer, bin); +} + +/** +* select_bin() - Select the bin that should be used to pack the compressed data in a data_vio with +* other data_vios. +* @packer: The packer. +* @data_vio: The data_vio. +*/ +static struct packer_bin *__must_check select_bin (struct packer *packer, +struct data_vio *data_vio) +{ +/* +* First best fit: select the bin with the least free space that has enough room for the +* compressed data in the data_vio. +*/ +struct packer_bin *bin, *fullest_bin; + +list_for_each_entry (bin, &packer->bins, list) { +if (bin->free_space >= data_vio->compression.size) +return bin; + } + +/* +* None of the bins have enough space for the data_vio. We're not allowed to create new +* bins, so we have to overflow one of the existing bins. It's pretty intuitive to select +* the fullest bin, since that "wastes" the least amount of free space in the compressed +* block. But if the space currently used in the fullest bin is smaller than the compressed +* size of the incoming block, it seems wrong to force that bin to write when giving up on +* compressing the incoming data_vio would likewise "waste" the least amount of free space. +*/ + fullest_bin = list_first_entry(&packer->bins, struct packer_bin, list); +if (data_vio->compression.size >= + (VDO_COMPRESSED_BLOCK_DATA_SIZE - fullest_bin->free_space)) +return NULL ; + +/* +* The fullest bin doesn't have room, but writing it out and starting a new batch with the +* incoming data_vio will increase the packer's free space. +*/ +return fullest_bin; +} + +/** +* vdo_attempt_packing() - Attempt to rewrite the data in this data_vio as part of a compressed +* block. +* @data_vio: The data_vio to pack. +*/ +void vdo_attempt_packing (struct data_vio *data_vio) +{ +int result; +struct packer_bin *bin; +struct data_vio_compression_status status =get_data_vio_compression_status (data_vio); +struct packer *packer =get_packer_from_data_vio (data_vio); + +assert_on_packer_thread (packer, __func__); + + result =ASSERT ((status.stage ==DATA_VIO_COMPRESSING ), +"attempt to pack data_vio not ready for packing, stage: %u" , + status.stage); +if (result !=VDO_SUCCESS ) +return ; + +/* +* Increment whether or not this data_vio will be packed or not since abort_packing() +* always decrements the counter. +*/ +WRITE_ONCE (packer->statistics.compressed_fragments_in_packer, + packer->statistics.compressed_fragments_in_packer +1 ); + +/* +* If packing of this data_vio is disallowed for administrative reasons, give up before +* making any state changes. +*/ +if (!vdo_is_state_normal (&packer->state) || + (data_vio->flush_generation < packer->flush_generation)) { +abort_packing (data_vio); +return ; + } + +/* +* The check of may_vio_block_in_packer() here will set the data_vio's compression state to +* VIO_PACKING if the data_vio is allowed to be compressed (if it has already been +* canceled, we'll fall out here). Once the data_vio is in the VIO_PACKING state, it must +* be guaranteed to be put in a bin before any more requests can be processed by the packer +* thread. Otherwise, a canceling data_vio could attempt to remove the canceled data_vio +* from the packer and fail to rendezvous with it (VDO-2809). We must also make sure that +* we will actually bin the data_vio and not give up on it as being larger than the space +* used in the fullest bin. Hence we must call select_bin() before calling +* may_vio_block_in_packer() (VDO-2826). +*/ + bin =select_bin (packer, data_vio); +if ((bin ==NULL ) || + (advance_data_vio_compression_stage (data_vio).stage !=DATA_VIO_PACKING )) { +abort_packing (data_vio); +return ; + } + +add_data_vio_to_packer_bin (packer, bin, data_vio); +} + +/** +* check_for_drain_complete() - Check whether the packer has drained. +* @packer: The packer. +*/ +static void check_for_drain_complete (struct packer *packer) +{ +if (vdo_is_state_draining (&packer->state) && (packer->canceled_bin->slots_used ==0 )) +vdo_finish_draining (&packer->state); +} + +/** +* write_all_non_empty_bins() - Write out all non-empty bins on behalf of a flush or suspend. +* @packer: The packer being flushed. +*/ +static void write_all_non_empty_bins (struct packer *packer) +{ +struct packer_bin *bin; + +list_for_each_entry (bin, &packer->bins, list) +write_bin (packer, bin); +/* +* We don't need to re-sort the bin here since this loop will make every bin have +* the same amount of free space, so every ordering is sorted. +*/ + +check_for_drain_complete (packer); +} + +/** +* vdo_flush_packer() - Request that the packer flush asynchronously. +* @packer: The packer to flush. +* +* All bins with at least two compressed data blocks will be written out, and any solitary pending +* VIOs will be released from the packer. While flushing is in progress, any VIOs submitted to +* vdo_attempt_packing() will be continued immediately without attempting to pack them. +*/ +void vdo_flush_packer (struct packer *packer) +{ +assert_on_packer_thread (packer, __func__); +if (vdo_is_state_normal (&packer->state)) +write_all_non_empty_bins (packer); +} + +/** +* vdo_remove_lock_holder_from_packer() - Remove a lock holder from the packer. +* @completion: The data_vio which needs a lock held by a data_vio in the packer. The data_vio's +* compression.lock_holder field will point to the data_vio to remove. +*/ +void vdo_remove_lock_holder_from_packer (struct vdo_completion *completion) +{ +struct data_vio *data_vio =as_data_vio (completion); +struct packer *packer =get_packer_from_data_vio (data_vio); +struct data_vio *lock_holder; +struct packer_bin *bin; +slot_number_t slot; + +assert_data_vio_in_packer_zone (data_vio); + + lock_holder =uds_forget (data_vio->compression.lock_holder); + bin = lock_holder->compression.bin; +ASSERT_LOG_ONLY ((bin !=NULL ),"data_vio in packer has a bin" ); + + slot = lock_holder->compression.slot; + bin->slots_used--; +if (slot < bin->slots_used) { + bin->incoming[slot] = bin->incoming[bin->slots_used]; + bin->incoming[slot]->compression.slot = slot; + } + + lock_holder->compression.bin =NULL ; + lock_holder->compression.slot =0 ; + +if (bin != packer->canceled_bin) { + bin->free_space += lock_holder->compression.size; +insert_in_sorted_list (packer, bin); + } + +abort_packing (lock_holder); +check_for_drain_complete (packer); +} + +/** +* vdo_increment_packer_flush_generation() - Increment the flush generation in the packer. +* @packer: The packer. +* +* This will also cause the packer to flush so that any VIOs from previous generations will exit +* the packer. +*/ +void vdo_increment_packer_flush_generation (struct packer *packer) +{ +assert_on_packer_thread (packer, __func__); + packer->flush_generation++; +vdo_flush_packer (packer); +} + +/** +* initiate_drain() - Initiate a drain. +* +* Implements vdo_admin_initiator_fn. +*/ +static void initiate_drain (struct admin_state *state) +{ + struct packer *packer = container_of(state, struct packer, state); + +write_all_non_empty_bins (packer); +} + +/** +* vdo_drain_packer() - Drain the packer by preventing any more VIOs from entering the packer and +* then flushing. +* @packer: The packer to drain. +* @completion: The completion to finish when the packer has drained. +*/ +void vdo_drain_packer (struct packer *packer,struct vdo_completion *completion) +{ +assert_on_packer_thread (packer, __func__); +vdo_start_draining (&packer->state,VDO_ADMIN_STATE_SUSPENDING , completion, + initiate_drain); +} + +/** +* vdo_resume_packer() - Resume a packer which has been suspended. +* @packer: The packer to resume. +* @parent: The completion to finish when the packer has resumed. +*/ +void vdo_resume_packer (struct packer *packer,struct vdo_completion *parent) +{ +assert_on_packer_thread (packer, __func__); +vdo_continue_completion (parent,vdo_resume_if_quiescent (&packer->state)); +} + +static void dump_packer_bin (const struct packer_bin *bin,bool canceled) +{ +if (bin->slots_used ==0 ) +/* Don't dump empty bins. */ +return ; + +uds_log_info (" %sBin slots_used=%u free_space=%zu" , + (canceled ?"Canceled" :"" ), bin->slots_used, bin->free_space); + +/* +* FIXME: dump vios in bin->incoming? The vios should have been dumped from the vio pool. +* Maybe just dump their addresses so it's clear they're here? +*/ +} + +/** +* vdo_dump_packer() - Dump the packer. +* @packer: The packer. +* +* Context: dumps in a thread-unsafe fashion. +*/ +void vdo_dump_packer (const struct packer *packer) +{ +struct packer_bin *bin; + +uds_log_info ("packer" ); +uds_log_info (" flushGeneration=%llu state %s packer_bin_count=%llu" , + (unsigned long long ) packer->flush_generation, +vdo_get_admin_state_code (&packer->state)->name, + (unsigned long long ) packer->size); + +list_for_each_entry (bin, &packer->bins, list) +dump_packer_bin (bin, false); + +dump_packer_bin (packer->canceled_bin, true); +}
drivers/md/dm-vdo/packer.h new file +122 -0
122 lines not on this page · raw message
Signature · 1 line
2.40.0