dedupe.c 100 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. /*
  3. * Copyright 2023 Red Hat
  4. */
  5. /**
  6. * DOC:
  7. *
  8. * Hash Locks:
  9. *
  10. * A hash_lock controls and coordinates writing, index access, and dedupe among groups of data_vios
  11. * concurrently writing identical blocks, allowing them to deduplicate not only against advice but
  12. * also against each other. This saves on index queries and allows those data_vios to concurrently
  13. * deduplicate against a single block instead of being serialized through a PBN read lock. Only one
  14. * index query is needed for each hash_lock, instead of one for every data_vio.
  15. *
  16. * Hash_locks are assigned to hash_zones by computing a modulus on the hash itself. Each hash_zone
  17. * has a single dedicated queue and thread for performing all operations on the hash_locks assigned
  18. * to that zone. The concurrency guarantees of this single-threaded model allow the code to omit
  19. * more fine-grained locking for the hash_lock structures.
  20. *
  21. * A hash_lock acts like a state machine perhaps more than as a lock. Other than the starting and
  22. * ending states INITIALIZING and BYPASSING, every state represents and is held for the duration of
  23. * an asynchronous operation. All state transitions are performed on the thread of the hash_zone
  24. * containing the lock. An asynchronous operation is almost always performed upon entering a state,
  25. * and the callback from that operation triggers exiting the state and entering a new state.
  26. *
  27. * In all states except DEDUPING, there is a single data_vio, called the lock agent, performing the
  28. * asynchronous operations on behalf of the lock. The agent will change during the lifetime of the
  29. * lock if the lock is shared by more than one data_vio. data_vios waiting to deduplicate are kept
  30. * on a wait queue. Viewed a different way, the agent holds the lock exclusively until the lock
  31. * enters the DEDUPING state, at which point it becomes a shared lock that all the waiters (and any
  32. * new data_vios that arrive) use to share a PBN lock. In state DEDUPING, there is no agent. When
  33. * the last data_vio in the lock calls back in DEDUPING, it becomes the agent and the lock becomes
  34. * exclusive again. New data_vios that arrive in the lock will also go on the wait queue.
  35. *
  36. * The existence of lock waiters is a key factor controlling which state the lock transitions to
  37. * next. When the lock is new or has waiters, it will always try to reach DEDUPING, and when it
  38. * doesn't, it will try to clean up and exit.
  39. *
  40. * Deduping requires holding a PBN lock on a block that is known to contain data identical to the
  41. * data_vios in the lock, so the lock will send the agent to the duplicate zone to acquire the PBN
  42. * lock (LOCKING), to the kernel I/O threads to read and verify the data (VERIFYING), or to write a
  43. * new copy of the data to a full data block or a slot in a compressed block (WRITING).
  44. *
  45. * Cleaning up consists of updating the index when the data location is different from the initial
  46. * index query (UPDATING, triggered by stale advice, compression, and rollover), releasing the PBN
  47. * lock on the duplicate block (UNLOCKING), and if the agent is the last data_vio referencing the
  48. * lock, releasing the hash_lock itself back to the hash zone (BYPASSING).
  49. *
  50. * The shortest sequence of states is for non-concurrent writes of new data:
  51. * INITIALIZING -> QUERYING -> WRITING -> BYPASSING
  52. * This sequence is short because no PBN read lock or index update is needed.
  53. *
  54. * Non-concurrent, finding valid advice looks like this (endpoints elided):
  55. * -> QUERYING -> LOCKING -> VERIFYING -> DEDUPING -> UNLOCKING ->
  56. * Or with stale advice (endpoints elided):
  57. * -> QUERYING -> LOCKING -> VERIFYING -> UNLOCKING -> WRITING -> UPDATING ->
  58. *
  59. * When there are not enough available reference count increments available on a PBN for a data_vio
  60. * to deduplicate, a new lock is forked and the excess waiters roll over to the new lock (which
  61. * goes directly to WRITING). The new lock takes the place of the old lock in the lock map so new
  62. * data_vios will be directed to it. The two locks will proceed independently, but only the new
  63. * lock will have the right to update the index (unless it also forks).
  64. *
  65. * Since rollover happens in a lock instance, once a valid data location has been selected, it will
  66. * not change. QUERYING and WRITING are only performed once per lock lifetime. All other
  67. * non-endpoint states can be re-entered.
  68. *
  69. * The function names in this module follow a convention referencing the states and transitions in
  70. * the state machine. For example, for the LOCKING state, there are start_locking() and
  71. * finish_locking() functions. start_locking() is invoked by the finish function of the state (or
  72. * states) that transition to LOCKING. It performs the actual lock state change and must be invoked
  73. * on the hash zone thread. finish_locking() is called by (or continued via callback from) the
  74. * code actually obtaining the lock. It does any bookkeeping or decision-making required and
  75. * invokes the appropriate start function of the state being transitioned to after LOCKING.
  76. *
  77. * ----------------------------------------------------------------------
  78. *
  79. * Index Queries:
  80. *
  81. * A query to the UDS index is handled asynchronously by the index's threads. When the query is
  82. * complete, a callback supplied with the query will be called from one of the those threads. Under
  83. * heavy system load, the index may be slower to respond than is desirable for reasonable I/O
  84. * throughput. Since deduplication of writes is not necessary for correct operation of a VDO
  85. * device, it is acceptable to timeout out slow index queries and proceed to fulfill a write
  86. * request without deduplicating. However, because the uds_request struct itself is supplied by the
  87. * caller, we can not simply reuse a uds_request object which we have chosen to timeout. Hence,
  88. * each hash_zone maintains a pool of dedupe_contexts which each contain a uds_request along with a
  89. * reference to the data_vio on behalf of which they are performing a query.
  90. *
  91. * When a hash_lock needs to query the index, it attempts to acquire an unused dedupe_context from
  92. * its hash_zone's pool. If one is available, that context is prepared, associated with the
  93. * hash_lock's agent, added to the list of pending contexts, and then sent to the index. The
  94. * context's state will be transitioned from DEDUPE_CONTEXT_IDLE to DEDUPE_CONTEXT_PENDING. If all
  95. * goes well, the dedupe callback will be called by the index which will change the context's state
  96. * to DEDUPE_CONTEXT_COMPLETE, and the associated data_vio will be enqueued to run back in the hash
  97. * zone where the query results will be processed and the context will be put back in the idle
  98. * state and returned to the hash_zone's available list.
  99. *
  100. * The first time an index query is launched from a given hash_zone, a timer is started. When the
  101. * timer fires, the hash_zone's completion is enqueued to run in the hash_zone where the zone's
  102. * pending list will be searched for any contexts in the pending state which have been running for
  103. * too long. Those contexts are transitioned to the DEDUPE_CONTEXT_TIMED_OUT state and moved to the
  104. * zone's timed_out list where they won't be examined again if there is a subsequent time out). The
  105. * data_vios associated with timed out contexts are sent to continue processing their write
  106. * operation without deduplicating. The timer is also restarted.
  107. *
  108. * When the dedupe callback is run for a context which is in the timed out state, that context is
  109. * moved to the DEDUPE_CONTEXT_TIMED_OUT_COMPLETE state. No other action need be taken as the
  110. * associated data_vios have already been dispatched.
  111. *
  112. * If a hash_lock needs a dedupe context, and the available list is empty, the timed_out list will
  113. * be searched for any contexts which are timed out and complete. One of these will be used
  114. * immediately, and the rest will be returned to the available list and marked idle.
  115. */
  116. #include "dedupe.h"
  117. #include <linux/atomic.h>
  118. #include <linux/jiffies.h>
  119. #include <linux/kernel.h>
  120. #include <linux/list.h>
  121. #include <linux/ratelimit.h>
  122. #include <linux/spinlock.h>
  123. #include <linux/timer.h>
  124. #include "logger.h"
  125. #include "memory-alloc.h"
  126. #include "numeric.h"
  127. #include "permassert.h"
  128. #include "string-utils.h"
  129. #include "indexer.h"
  130. #include "action-manager.h"
  131. #include "admin-state.h"
  132. #include "completion.h"
  133. #include "constants.h"
  134. #include "data-vio.h"
  135. #include "int-map.h"
  136. #include "io-submitter.h"
  137. #include "packer.h"
  138. #include "physical-zone.h"
  139. #include "slab-depot.h"
  140. #include "statistics.h"
  141. #include "types.h"
  142. #include "vdo.h"
  143. #include "wait-queue.h"
  144. #define DEDUPE_QUERY_TIMER_IDLE 0
  145. #define DEDUPE_QUERY_TIMER_RUNNING 1
  146. #define DEDUPE_QUERY_TIMER_FIRED 2
  147. enum dedupe_context_state {
  148. DEDUPE_CONTEXT_IDLE,
  149. DEDUPE_CONTEXT_PENDING,
  150. DEDUPE_CONTEXT_TIMED_OUT,
  151. DEDUPE_CONTEXT_COMPLETE,
  152. DEDUPE_CONTEXT_TIMED_OUT_COMPLETE,
  153. };
  154. /* Possible index states: closed, opened, or transitioning between those two. */
  155. enum index_state {
  156. IS_CLOSED,
  157. IS_CHANGING,
  158. IS_OPENED,
  159. };
  160. static const char *CLOSED = "closed";
  161. static const char *CLOSING = "closing";
  162. static const char *ERROR = "error";
  163. static const char *OFFLINE = "offline";
  164. static const char *ONLINE = "online";
  165. static const char *OPENING = "opening";
  166. static const char *SUSPENDED = "suspended";
  167. static const char *UNKNOWN = "unknown";
  168. /* Version 2 uses the kernel space UDS index and is limited to 16 bytes */
  169. #define UDS_ADVICE_VERSION 2
  170. /* version byte + state byte + 64-bit little-endian PBN */
  171. #define UDS_ADVICE_SIZE (1 + 1 + sizeof(u64))
  172. enum hash_lock_state {
  173. /* State for locks that are not in use or are being initialized. */
  174. VDO_HASH_LOCK_INITIALIZING,
  175. /* This is the sequence of states typically used on the non-dedupe path. */
  176. VDO_HASH_LOCK_QUERYING,
  177. VDO_HASH_LOCK_WRITING,
  178. VDO_HASH_LOCK_UPDATING,
  179. /* The remaining states are typically used on the dedupe path in this order. */
  180. VDO_HASH_LOCK_LOCKING,
  181. VDO_HASH_LOCK_VERIFYING,
  182. VDO_HASH_LOCK_DEDUPING,
  183. VDO_HASH_LOCK_UNLOCKING,
  184. /*
  185. * Terminal state for locks returning to the pool. Must be last both because it's the final
  186. * state, and also because it's used to count the states.
  187. */
  188. VDO_HASH_LOCK_BYPASSING,
  189. };
  190. static const char * const LOCK_STATE_NAMES[] = {
  191. [VDO_HASH_LOCK_BYPASSING] = "BYPASSING",
  192. [VDO_HASH_LOCK_DEDUPING] = "DEDUPING",
  193. [VDO_HASH_LOCK_INITIALIZING] = "INITIALIZING",
  194. [VDO_HASH_LOCK_LOCKING] = "LOCKING",
  195. [VDO_HASH_LOCK_QUERYING] = "QUERYING",
  196. [VDO_HASH_LOCK_UNLOCKING] = "UNLOCKING",
  197. [VDO_HASH_LOCK_UPDATING] = "UPDATING",
  198. [VDO_HASH_LOCK_VERIFYING] = "VERIFYING",
  199. [VDO_HASH_LOCK_WRITING] = "WRITING",
  200. };
  201. struct hash_lock {
  202. /* The block hash covered by this lock */
  203. struct uds_record_name hash;
  204. /* When the lock is unused, this list entry allows the lock to be pooled */
  205. struct list_head pool_node;
  206. /*
  207. * A list containing the data VIOs sharing this lock, all having the same record name and
  208. * data block contents, linked by their hash_lock_node fields.
  209. */
  210. struct list_head duplicate_ring;
  211. /* The number of data_vios sharing this lock instance */
  212. data_vio_count_t reference_count;
  213. /* The maximum value of reference_count in the lifetime of this lock */
  214. data_vio_count_t max_references;
  215. /* The current state of this lock */
  216. enum hash_lock_state state;
  217. /* True if the UDS index should be updated with new advice */
  218. bool update_advice;
  219. /* True if the advice has been verified to be a true duplicate */
  220. bool verified;
  221. /* True if the lock has already accounted for an initial verification */
  222. bool verify_counted;
  223. /* True if this lock is registered in the lock map (cleared on rollover) */
  224. bool registered;
  225. /*
  226. * If verified is false, this is the location of a possible duplicate. If verified is true,
  227. * it is the verified location of a true duplicate.
  228. */
  229. struct zoned_pbn duplicate;
  230. /* The PBN lock on the block containing the duplicate data */
  231. struct pbn_lock *duplicate_lock;
  232. /* The data_vio designated to act on behalf of the lock */
  233. struct data_vio *agent;
  234. /*
  235. * Other data_vios with data identical to the agent who are currently waiting for the agent
  236. * to get the information they all need to deduplicate--either against each other, or
  237. * against an existing duplicate on disk.
  238. */
  239. struct vdo_wait_queue waiters;
  240. };
  241. #define LOCK_POOL_CAPACITY MAXIMUM_VDO_USER_VIOS
  242. struct hash_zones {
  243. struct action_manager *manager;
  244. struct uds_parameters parameters;
  245. struct uds_index_session *index_session;
  246. struct ratelimit_state ratelimiter;
  247. atomic64_t timeouts;
  248. atomic64_t dedupe_context_busy;
  249. /* This spinlock protects the state fields and the starting of dedupe requests. */
  250. spinlock_t lock;
  251. /* The fields in the next block are all protected by the lock */
  252. struct vdo_completion completion;
  253. enum index_state index_state;
  254. enum index_state index_target;
  255. struct admin_state state;
  256. bool changing;
  257. bool create_flag;
  258. bool dedupe_flag;
  259. bool error_flag;
  260. u64 reported_timeouts;
  261. /* The number of zones */
  262. zone_count_t zone_count;
  263. /* The hash zones themselves */
  264. struct hash_zone zones[];
  265. };
  266. /* These are in milliseconds. */
  267. unsigned int vdo_dedupe_index_timeout_interval = 5000;
  268. unsigned int vdo_dedupe_index_min_timer_interval = 100;
  269. /* Same two variables, in jiffies for easier consumption. */
  270. static u64 vdo_dedupe_index_timeout_jiffies;
  271. static u64 vdo_dedupe_index_min_timer_jiffies;
  272. static inline struct hash_zone *as_hash_zone(struct vdo_completion *completion)
  273. {
  274. vdo_assert_completion_type(completion, VDO_HASH_ZONE_COMPLETION);
  275. return container_of(completion, struct hash_zone, completion);
  276. }
  277. static inline struct hash_zones *as_hash_zones(struct vdo_completion *completion)
  278. {
  279. vdo_assert_completion_type(completion, VDO_HASH_ZONES_COMPLETION);
  280. return container_of(completion, struct hash_zones, completion);
  281. }
  282. static inline void assert_in_hash_zone(struct hash_zone *zone, const char *name)
  283. {
  284. VDO_ASSERT_LOG_ONLY((vdo_get_callback_thread_id() == zone->thread_id),
  285. "%s called on hash zone thread", name);
  286. }
  287. static inline bool change_context_state(struct dedupe_context *context, int old, int new)
  288. {
  289. return (atomic_cmpxchg(&context->state, old, new) == old);
  290. }
  291. static inline bool change_timer_state(struct hash_zone *zone, int old, int new)
  292. {
  293. return (atomic_cmpxchg(&zone->timer_state, old, new) == old);
  294. }
  295. /**
  296. * return_hash_lock_to_pool() - (Re)initialize a hash lock and return it to its pool.
  297. * @zone: The zone from which the lock was borrowed.
  298. * @lock: The lock that is no longer in use.
  299. */
  300. static void return_hash_lock_to_pool(struct hash_zone *zone, struct hash_lock *lock)
  301. {
  302. memset(lock, 0, sizeof(*lock));
  303. INIT_LIST_HEAD(&lock->pool_node);
  304. INIT_LIST_HEAD(&lock->duplicate_ring);
  305. vdo_waitq_init(&lock->waiters);
  306. list_add_tail(&lock->pool_node, &zone->lock_pool);
  307. }
  308. /**
  309. * vdo_get_duplicate_lock() - Get the PBN lock on the duplicate data location for a data_vio from
  310. * the hash_lock the data_vio holds (if there is one).
  311. * @data_vio: The data_vio to query.
  312. *
  313. * Return: The PBN lock on the data_vio's duplicate location.
  314. */
  315. struct pbn_lock *vdo_get_duplicate_lock(struct data_vio *data_vio)
  316. {
  317. if (data_vio->hash_lock == NULL)
  318. return NULL;
  319. return data_vio->hash_lock->duplicate_lock;
  320. }
  321. /**
  322. * hash_lock_key() - Return hash_lock's record name as a hash code.
  323. * @lock: The hash lock.
  324. *
  325. * Return: The key to use for the int map.
  326. */
  327. static inline u64 hash_lock_key(struct hash_lock *lock)
  328. {
  329. return get_unaligned_le64(&lock->hash.name);
  330. }
  331. /**
  332. * get_hash_lock_state_name() - Get the string representation of a hash lock state.
  333. * @state: The hash lock state.
  334. *
  335. * Return: The short string representing the state
  336. */
  337. static const char *get_hash_lock_state_name(enum hash_lock_state state)
  338. {
  339. /* Catch if a state has been added without updating the name array. */
  340. BUILD_BUG_ON((VDO_HASH_LOCK_BYPASSING + 1) != ARRAY_SIZE(LOCK_STATE_NAMES));
  341. return (state < ARRAY_SIZE(LOCK_STATE_NAMES)) ? LOCK_STATE_NAMES[state] : "INVALID";
  342. }
  343. /**
  344. * assert_hash_lock_agent() - Assert that a data_vio is the agent of its hash lock, and that this
  345. * is being called in the hash zone.
  346. * @data_vio: The data_vio expected to be the lock agent.
  347. * @where: A string describing the function making the assertion.
  348. */
  349. static void assert_hash_lock_agent(struct data_vio *data_vio, const char *where)
  350. {
  351. /* Not safe to access the agent field except from the hash zone. */
  352. assert_data_vio_in_hash_zone(data_vio);
  353. VDO_ASSERT_LOG_ONLY(data_vio == data_vio->hash_lock->agent,
  354. "%s must be for the hash lock agent", where);
  355. }
  356. /**
  357. * set_duplicate_lock() - Set the duplicate lock held by a hash lock. May only be called in the
  358. * physical zone of the PBN lock.
  359. * @hash_lock: The hash lock to update.
  360. * @pbn_lock: The PBN read lock to use as the duplicate lock.
  361. */
  362. static void set_duplicate_lock(struct hash_lock *hash_lock, struct pbn_lock *pbn_lock)
  363. {
  364. VDO_ASSERT_LOG_ONLY((hash_lock->duplicate_lock == NULL),
  365. "hash lock must not already hold a duplicate lock");
  366. pbn_lock->holder_count += 1;
  367. hash_lock->duplicate_lock = pbn_lock;
  368. }
  369. /**
  370. * dequeue_lock_waiter() - Remove the first data_vio from the lock's waitq and return it.
  371. * @lock: The lock containing the wait queue.
  372. *
  373. * Return: The first (oldest) waiter in the queue, or NULL if the queue is empty.
  374. */
  375. static inline struct data_vio *dequeue_lock_waiter(struct hash_lock *lock)
  376. {
  377. return vdo_waiter_as_data_vio(vdo_waitq_dequeue_waiter(&lock->waiters));
  378. }
  379. /**
  380. * set_hash_lock() - Set, change, or clear the hash lock a data_vio is using.
  381. * @data_vio: The data_vio to update.
  382. * @new_lock: The hash lock the data_vio is joining.
  383. *
  384. * Updates the hash lock (or locks) to reflect the change in membership.
  385. */
  386. static void set_hash_lock(struct data_vio *data_vio, struct hash_lock *new_lock)
  387. {
  388. struct hash_lock *old_lock = data_vio->hash_lock;
  389. if (old_lock != NULL) {
  390. VDO_ASSERT_LOG_ONLY(data_vio->hash_zone != NULL,
  391. "must have a hash zone when holding a hash lock");
  392. VDO_ASSERT_LOG_ONLY(!list_empty(&data_vio->hash_lock_entry),
  393. "must be on a hash lock ring when holding a hash lock");
  394. VDO_ASSERT_LOG_ONLY(old_lock->reference_count > 0,
  395. "hash lock reference must be counted");
  396. if ((old_lock->state != VDO_HASH_LOCK_BYPASSING) &&
  397. (old_lock->state != VDO_HASH_LOCK_UNLOCKING)) {
  398. /*
  399. * If the reference count goes to zero in a non-terminal state, we're most
  400. * likely leaking this lock.
  401. */
  402. VDO_ASSERT_LOG_ONLY(old_lock->reference_count > 1,
  403. "hash locks should only become unreferenced in a terminal state, not state %s",
  404. get_hash_lock_state_name(old_lock->state));
  405. }
  406. list_del_init(&data_vio->hash_lock_entry);
  407. old_lock->reference_count -= 1;
  408. data_vio->hash_lock = NULL;
  409. }
  410. if (new_lock != NULL) {
  411. /*
  412. * Keep all data_vios sharing the lock on a ring since they can complete in any
  413. * order and we'll always need a pointer to one to compare data.
  414. */
  415. list_move_tail(&data_vio->hash_lock_entry, &new_lock->duplicate_ring);
  416. new_lock->reference_count += 1;
  417. if (new_lock->max_references < new_lock->reference_count)
  418. new_lock->max_references = new_lock->reference_count;
  419. data_vio->hash_lock = new_lock;
  420. }
  421. }
  422. /* There are loops in the state diagram, so some forward decl's are needed. */
  423. static void start_deduping(struct hash_lock *lock, struct data_vio *agent,
  424. bool agent_is_done);
  425. static void start_locking(struct hash_lock *lock, struct data_vio *agent);
  426. static void start_writing(struct hash_lock *lock, struct data_vio *agent);
  427. static void unlock_duplicate_pbn(struct vdo_completion *completion);
  428. static void transfer_allocation_lock(struct data_vio *data_vio);
  429. /**
  430. * exit_hash_lock() - Bottleneck for data_vios that have written or deduplicated and that are no
  431. * longer needed to be an agent for the hash lock.
  432. * @data_vio: The data_vio to complete and send to be cleaned up.
  433. */
  434. static void exit_hash_lock(struct data_vio *data_vio)
  435. {
  436. /* Release the hash lock now, saving a thread transition in cleanup. */
  437. vdo_release_hash_lock(data_vio);
  438. /* Complete the data_vio and start the clean-up path to release any locks it still holds. */
  439. data_vio->vio.completion.callback = complete_data_vio;
  440. continue_data_vio(data_vio);
  441. }
  442. /**
  443. * set_duplicate_location() - Set the location of the duplicate block for data_vio, updating the
  444. * is_duplicate and duplicate fields from a zoned_pbn.
  445. * @data_vio: The data_vio to modify.
  446. * @source: The location of the duplicate.
  447. */
  448. static void set_duplicate_location(struct data_vio *data_vio,
  449. const struct zoned_pbn source)
  450. {
  451. data_vio->is_duplicate = (source.pbn != VDO_ZERO_BLOCK);
  452. data_vio->duplicate = source;
  453. }
  454. /**
  455. * retire_lock_agent() - Retire the active lock agent, replacing it with the first lock waiter, and
  456. * make the retired agent exit the hash lock.
  457. * @lock: The hash lock to update.
  458. *
  459. * Return: The new lock agent (which will be NULL if there was no waiter)
  460. */
  461. static struct data_vio *retire_lock_agent(struct hash_lock *lock)
  462. {
  463. struct data_vio *old_agent = lock->agent;
  464. struct data_vio *new_agent = dequeue_lock_waiter(lock);
  465. lock->agent = new_agent;
  466. exit_hash_lock(old_agent);
  467. if (new_agent != NULL)
  468. set_duplicate_location(new_agent, lock->duplicate);
  469. return new_agent;
  470. }
  471. /**
  472. * wait_on_hash_lock() - Add a data_vio to the lock's queue of waiters.
  473. * @lock: The hash lock on which to wait.
  474. * @data_vio: The data_vio to add to the queue.
  475. */
  476. static void wait_on_hash_lock(struct hash_lock *lock, struct data_vio *data_vio)
  477. {
  478. vdo_waitq_enqueue_waiter(&lock->waiters, &data_vio->waiter);
  479. /*
  480. * Make sure the agent doesn't block indefinitely in the packer since it now has at least
  481. * one other data_vio waiting on it.
  482. */
  483. if ((lock->state != VDO_HASH_LOCK_WRITING) || !cancel_data_vio_compression(lock->agent))
  484. return;
  485. /*
  486. * Even though we're waiting, we also have to send ourselves as a one-way message to the
  487. * packer to ensure the agent continues executing. This is safe because
  488. * cancel_vio_compression() guarantees the agent won't continue executing until this
  489. * message arrives in the packer, and because the wait queue link isn't used for sending
  490. * the message.
  491. */
  492. data_vio->compression.lock_holder = lock->agent;
  493. launch_data_vio_packer_callback(data_vio, vdo_remove_lock_holder_from_packer);
  494. }
  495. /**
  496. * abort_waiter() - waiter_callback_fn function that shunts waiters to write their blocks without
  497. * optimization.
  498. * @waiter: The data_vio's waiter link.
  499. * @context: Not used.
  500. */
  501. static void abort_waiter(struct vdo_waiter *waiter, void *context __always_unused)
  502. {
  503. write_data_vio(vdo_waiter_as_data_vio(waiter));
  504. }
  505. /**
  506. * start_bypassing() - Stop using the hash lock.
  507. * @lock: The hash lock.
  508. * @agent: The data_vio acting as the agent for the lock.
  509. *
  510. * Stops using the hash lock. This is the final transition for hash locks which did not get an
  511. * error.
  512. */
  513. static void start_bypassing(struct hash_lock *lock, struct data_vio *agent)
  514. {
  515. lock->state = VDO_HASH_LOCK_BYPASSING;
  516. exit_hash_lock(agent);
  517. }
  518. void vdo_clean_failed_hash_lock(struct data_vio *data_vio)
  519. {
  520. struct hash_lock *lock = data_vio->hash_lock;
  521. if (lock->state == VDO_HASH_LOCK_BYPASSING) {
  522. exit_hash_lock(data_vio);
  523. return;
  524. }
  525. if (lock->agent == NULL) {
  526. lock->agent = data_vio;
  527. } else if (data_vio != lock->agent) {
  528. exit_hash_lock(data_vio);
  529. return;
  530. }
  531. lock->state = VDO_HASH_LOCK_BYPASSING;
  532. /* Ensure we don't attempt to update advice when cleaning up. */
  533. lock->update_advice = false;
  534. vdo_waitq_notify_all_waiters(&lock->waiters, abort_waiter, NULL);
  535. if (lock->duplicate_lock != NULL) {
  536. /* The agent must reference the duplicate zone to launch it. */
  537. data_vio->duplicate = lock->duplicate;
  538. launch_data_vio_duplicate_zone_callback(data_vio, unlock_duplicate_pbn);
  539. return;
  540. }
  541. lock->agent = NULL;
  542. data_vio->is_duplicate = false;
  543. exit_hash_lock(data_vio);
  544. }
  545. /**
  546. * finish_unlocking() - Handle the result of the agent for the lock releasing a read lock on
  547. * duplicate candidate.
  548. * @completion: The completion of the data_vio acting as the lock's agent.
  549. *
  550. * This continuation is registered in unlock_duplicate_pbn().
  551. */
  552. static void finish_unlocking(struct vdo_completion *completion)
  553. {
  554. struct data_vio *agent = as_data_vio(completion);
  555. struct hash_lock *lock = agent->hash_lock;
  556. assert_hash_lock_agent(agent, __func__);
  557. VDO_ASSERT_LOG_ONLY(lock->duplicate_lock == NULL,
  558. "must have released the duplicate lock for the hash lock");
  559. if (!lock->verified) {
  560. /*
  561. * UNLOCKING -> WRITING transition: The lock we released was on an unverified
  562. * block, so it must have been a lock on advice we were verifying, not on a
  563. * location that was used for deduplication. Go write (or compress) the block to
  564. * get a location to dedupe against.
  565. */
  566. start_writing(lock, agent);
  567. return;
  568. }
  569. /*
  570. * With the lock released, the verified duplicate block may already have changed and will
  571. * need to be re-verified if a waiter arrived.
  572. */
  573. lock->verified = false;
  574. if (vdo_waitq_has_waiters(&lock->waiters)) {
  575. /*
  576. * UNLOCKING -> LOCKING transition: A new data_vio entered the hash lock while the
  577. * agent was releasing the PBN lock. The current agent exits and the waiter has to
  578. * re-lock and re-verify the duplicate location.
  579. *
  580. * TODO: If we used the current agent to re-acquire the PBN lock we wouldn't need
  581. * to re-verify.
  582. */
  583. agent = retire_lock_agent(lock);
  584. start_locking(lock, agent);
  585. return;
  586. }
  587. /*
  588. * UNLOCKING -> BYPASSING transition: The agent is done with the lock and no other
  589. * data_vios reference it, so remove it from the lock map and return it to the pool.
  590. */
  591. start_bypassing(lock, agent);
  592. }
  593. /**
  594. * unlock_duplicate_pbn() - Release a read lock on the PBN of the block that may or may not have
  595. * contained duplicate data.
  596. * @completion: The completion of the data_vio acting as the lock's agent.
  597. *
  598. * This continuation is launched by start_unlocking(), and calls back to finish_unlocking() on the
  599. * hash zone thread.
  600. */
  601. static void unlock_duplicate_pbn(struct vdo_completion *completion)
  602. {
  603. struct data_vio *agent = as_data_vio(completion);
  604. struct hash_lock *lock = agent->hash_lock;
  605. assert_data_vio_in_duplicate_zone(agent);
  606. VDO_ASSERT_LOG_ONLY(lock->duplicate_lock != NULL,
  607. "must have a duplicate lock to release");
  608. vdo_release_physical_zone_pbn_lock(agent->duplicate.zone, agent->duplicate.pbn,
  609. vdo_forget(lock->duplicate_lock));
  610. if (lock->state == VDO_HASH_LOCK_BYPASSING) {
  611. complete_data_vio(completion);
  612. return;
  613. }
  614. launch_data_vio_hash_zone_callback(agent, finish_unlocking);
  615. }
  616. /**
  617. * start_unlocking() - Release a read lock on the PBN of the block that may or may not have
  618. * contained duplicate data.
  619. * @lock: The hash lock.
  620. * @agent: The data_vio currently acting as the agent for the lock.
  621. */
  622. static void start_unlocking(struct hash_lock *lock, struct data_vio *agent)
  623. {
  624. lock->state = VDO_HASH_LOCK_UNLOCKING;
  625. launch_data_vio_duplicate_zone_callback(agent, unlock_duplicate_pbn);
  626. }
  627. static void release_context(struct dedupe_context *context)
  628. {
  629. struct hash_zone *zone = context->zone;
  630. WRITE_ONCE(zone->active, zone->active - 1);
  631. list_move(&context->list_entry, &zone->available);
  632. }
  633. static void process_update_result(struct data_vio *agent)
  634. {
  635. struct dedupe_context *context = agent->dedupe_context;
  636. if ((context == NULL) ||
  637. !change_context_state(context, DEDUPE_CONTEXT_COMPLETE, DEDUPE_CONTEXT_IDLE))
  638. return;
  639. agent->dedupe_context = NULL;
  640. release_context(context);
  641. }
  642. /**
  643. * finish_updating() - Process the result of a UDS update performed by the agent for the lock.
  644. * @completion: The completion of the data_vio that performed the update
  645. *
  646. * This continuation is registered in start_querying().
  647. */
  648. static void finish_updating(struct vdo_completion *completion)
  649. {
  650. struct data_vio *agent = as_data_vio(completion);
  651. struct hash_lock *lock = agent->hash_lock;
  652. assert_hash_lock_agent(agent, __func__);
  653. process_update_result(agent);
  654. /*
  655. * UDS was updated successfully, so don't update again unless the duplicate location
  656. * changes due to rollover.
  657. */
  658. lock->update_advice = false;
  659. if (vdo_waitq_has_waiters(&lock->waiters)) {
  660. /*
  661. * UPDATING -> DEDUPING transition: A new data_vio arrived during the UDS update.
  662. * Send it on the verified dedupe path. The agent is done with the lock, but the
  663. * lock may still need to use it to clean up after rollover.
  664. */
  665. start_deduping(lock, agent, true);
  666. return;
  667. }
  668. if (lock->duplicate_lock != NULL) {
  669. /*
  670. * UPDATING -> UNLOCKING transition: No one is waiting to dedupe, but we hold a
  671. * duplicate PBN lock, so go release it.
  672. */
  673. start_unlocking(lock, agent);
  674. return;
  675. }
  676. /*
  677. * UPDATING -> BYPASSING transition: No one is waiting to dedupe and there's no lock to
  678. * release.
  679. */
  680. start_bypassing(lock, agent);
  681. }
  682. static void query_index(struct data_vio *data_vio, enum uds_request_type operation);
  683. /**
  684. * start_updating() - Continue deduplication with the last step, updating UDS with the location of
  685. * the duplicate that should be returned as advice in the future.
  686. * @lock: The hash lock.
  687. * @agent: The data_vio currently acting as the agent for the lock.
  688. */
  689. static void start_updating(struct hash_lock *lock, struct data_vio *agent)
  690. {
  691. lock->state = VDO_HASH_LOCK_UPDATING;
  692. VDO_ASSERT_LOG_ONLY(lock->verified, "new advice should have been verified");
  693. VDO_ASSERT_LOG_ONLY(lock->update_advice, "should only update advice if needed");
  694. agent->last_async_operation = VIO_ASYNC_OP_UPDATE_DEDUPE_INDEX;
  695. set_data_vio_hash_zone_callback(agent, finish_updating);
  696. query_index(agent, UDS_UPDATE);
  697. }
  698. /**
  699. * finish_deduping() - Handle a data_vio that has finished deduplicating against the block locked
  700. * by the hash lock.
  701. * @lock: The hash lock.
  702. * @data_vio: The lock holder that has finished deduplicating.
  703. *
  704. * If there are other data_vios still sharing the lock, this will just release the data_vio's share
  705. * of the lock and finish processing the data_vio. If this is the last data_vio holding the lock,
  706. * this makes the data_vio the lock agent and uses it to advance the state of the lock so it can
  707. * eventually be released.
  708. */
  709. static void finish_deduping(struct hash_lock *lock, struct data_vio *data_vio)
  710. {
  711. struct data_vio *agent = data_vio;
  712. VDO_ASSERT_LOG_ONLY(lock->agent == NULL, "shouldn't have an agent in DEDUPING");
  713. VDO_ASSERT_LOG_ONLY(!vdo_waitq_has_waiters(&lock->waiters),
  714. "shouldn't have any lock waiters in DEDUPING");
  715. /* Just release the lock reference if other data_vios are still deduping. */
  716. if (lock->reference_count > 1) {
  717. exit_hash_lock(data_vio);
  718. return;
  719. }
  720. /* The hash lock must have an agent for all other lock states. */
  721. lock->agent = agent;
  722. if (lock->update_advice) {
  723. /*
  724. * DEDUPING -> UPDATING transition: The location of the duplicate block changed
  725. * since the initial UDS query because of compression, rollover, or because the
  726. * query agent didn't have an allocation. The UDS update was delayed in case there
  727. * was another change in location, but with only this data_vio using the hash lock,
  728. * it's time to update the advice.
  729. */
  730. start_updating(lock, agent);
  731. } else {
  732. /*
  733. * DEDUPING -> UNLOCKING transition: Release the PBN read lock on the duplicate
  734. * location so the hash lock itself can be released (contingent on no new data_vios
  735. * arriving in the lock before the agent returns).
  736. */
  737. start_unlocking(lock, agent);
  738. }
  739. }
  740. /**
  741. * acquire_lock() - Get the lock for a record name.
  742. * @zone: The zone responsible for the hash.
  743. * @hash: The hash to lock.
  744. * @replace_lock: If non-NULL, the lock already registered for the hash which should be replaced by
  745. * the new lock.
  746. * @lock_ptr: A pointer to receive the hash lock.
  747. *
  748. * Gets the lock for the hash (record name) of the data in a data_vio, or if one does not exist (or
  749. * if we are explicitly rolling over), initialize a new lock for the hash and register it in the
  750. * zone. This must only be called in the correct thread for the zone.
  751. *
  752. * Return: VDO_SUCCESS or an error code.
  753. */
  754. static int __must_check acquire_lock(struct hash_zone *zone,
  755. const struct uds_record_name *hash,
  756. struct hash_lock *replace_lock,
  757. struct hash_lock **lock_ptr)
  758. {
  759. struct hash_lock *lock, *new_lock;
  760. int result;
  761. /*
  762. * Borrow and prepare a lock from the pool so we don't have to do two int_map accesses
  763. * in the common case of no lock contention.
  764. */
  765. result = VDO_ASSERT(!list_empty(&zone->lock_pool),
  766. "never need to wait for a free hash lock");
  767. if (result != VDO_SUCCESS)
  768. return result;
  769. new_lock = list_entry(zone->lock_pool.prev, struct hash_lock, pool_node);
  770. list_del_init(&new_lock->pool_node);
  771. /*
  772. * Fill in the hash of the new lock so we can map it, since we have to use the hash as the
  773. * map key.
  774. */
  775. new_lock->hash = *hash;
  776. result = vdo_int_map_put(zone->hash_lock_map, hash_lock_key(new_lock),
  777. new_lock, (replace_lock != NULL), (void **) &lock);
  778. if (result != VDO_SUCCESS) {
  779. return_hash_lock_to_pool(zone, vdo_forget(new_lock));
  780. return result;
  781. }
  782. if (replace_lock != NULL) {
  783. /* On mismatch put the old lock back and return a severe error */
  784. VDO_ASSERT_LOG_ONLY(lock == replace_lock,
  785. "old lock must have been in the lock map");
  786. /* TODO: Check earlier and bail out? */
  787. VDO_ASSERT_LOG_ONLY(replace_lock->registered,
  788. "old lock must have been marked registered");
  789. replace_lock->registered = false;
  790. }
  791. if (lock == replace_lock) {
  792. lock = new_lock;
  793. lock->registered = true;
  794. } else {
  795. /* There's already a lock for the hash, so we don't need the borrowed lock. */
  796. return_hash_lock_to_pool(zone, vdo_forget(new_lock));
  797. }
  798. *lock_ptr = lock;
  799. return VDO_SUCCESS;
  800. }
  801. /**
  802. * enter_forked_lock() - Bind the data_vio to a new hash lock.
  803. *
  804. * Implements waiter_callback_fn. Binds the data_vio that was waiting to a new hash lock and waits
  805. * on that lock.
  806. */
  807. static void enter_forked_lock(struct vdo_waiter *waiter, void *context)
  808. {
  809. struct data_vio *data_vio = vdo_waiter_as_data_vio(waiter);
  810. struct hash_lock *new_lock = context;
  811. set_hash_lock(data_vio, new_lock);
  812. wait_on_hash_lock(new_lock, data_vio);
  813. }
  814. /**
  815. * fork_hash_lock() - Fork a hash lock because it has run out of increments on the duplicate PBN.
  816. * @old_lock: The hash lock to fork.
  817. * @new_agent: The data_vio that will be the agent for the new lock.
  818. *
  819. * Transfers the new agent and any lock waiters to a new hash lock instance which takes the place
  820. * of the old lock in the lock map. The old lock remains active, but will not update advice.
  821. */
  822. static void fork_hash_lock(struct hash_lock *old_lock, struct data_vio *new_agent)
  823. {
  824. struct hash_lock *new_lock;
  825. int result;
  826. result = acquire_lock(new_agent->hash_zone, &new_agent->record_name, old_lock,
  827. &new_lock);
  828. if (result != VDO_SUCCESS) {
  829. continue_data_vio_with_error(new_agent, result);
  830. return;
  831. }
  832. /*
  833. * Only one of the two locks should update UDS. The old lock is out of references, so it
  834. * would be poor dedupe advice in the short term.
  835. */
  836. old_lock->update_advice = false;
  837. new_lock->update_advice = true;
  838. set_hash_lock(new_agent, new_lock);
  839. new_lock->agent = new_agent;
  840. vdo_waitq_notify_all_waiters(&old_lock->waiters, enter_forked_lock, new_lock);
  841. new_agent->is_duplicate = false;
  842. start_writing(new_lock, new_agent);
  843. }
  844. /**
  845. * launch_dedupe() - Reserve a reference count increment for a data_vio and launch it on the dedupe
  846. * path.
  847. * @lock: The hash lock.
  848. * @data_vio: The data_vio to deduplicate using the hash lock.
  849. * @has_claim: true if the data_vio already has claimed an increment from the duplicate lock.
  850. *
  851. * If no increments are available, this will roll over to a new hash lock and launch the data_vio
  852. * as the writing agent for that lock.
  853. */
  854. static void launch_dedupe(struct hash_lock *lock, struct data_vio *data_vio,
  855. bool has_claim)
  856. {
  857. if (!has_claim && !vdo_claim_pbn_lock_increment(lock->duplicate_lock)) {
  858. /* Out of increments, so must roll over to a new lock. */
  859. fork_hash_lock(lock, data_vio);
  860. return;
  861. }
  862. /* Deduplicate against the lock's verified location. */
  863. set_duplicate_location(data_vio, lock->duplicate);
  864. data_vio->new_mapped = data_vio->duplicate;
  865. update_metadata_for_data_vio_write(data_vio, lock->duplicate_lock);
  866. }
  867. /**
  868. * start_deduping() - Enter the hash lock state where data_vios deduplicate in parallel against a
  869. * true copy of their data on disk.
  870. * @lock: The hash lock.
  871. * @agent: The data_vio acting as the agent for the lock.
  872. * @agent_is_done: true only if the agent has already written or deduplicated against its data.
  873. *
  874. * If the agent itself needs to deduplicate, an increment for it must already have been claimed
  875. * from the duplicate lock, ensuring the hash lock will still have a data_vio holding it.
  876. */
  877. static void start_deduping(struct hash_lock *lock, struct data_vio *agent,
  878. bool agent_is_done)
  879. {
  880. lock->state = VDO_HASH_LOCK_DEDUPING;
  881. /*
  882. * We don't take the downgraded allocation lock from the agent unless we actually need to
  883. * deduplicate against it.
  884. */
  885. if (lock->duplicate_lock == NULL) {
  886. VDO_ASSERT_LOG_ONLY(!vdo_is_state_compressed(agent->new_mapped.state),
  887. "compression must have shared a lock");
  888. VDO_ASSERT_LOG_ONLY(agent_is_done,
  889. "agent must have written the new duplicate");
  890. transfer_allocation_lock(agent);
  891. }
  892. VDO_ASSERT_LOG_ONLY(vdo_is_pbn_read_lock(lock->duplicate_lock),
  893. "duplicate_lock must be a PBN read lock");
  894. /*
  895. * This state is not like any of the other states. There is no designated agent--the agent
  896. * transitioning to this state and all the waiters will be launched to deduplicate in
  897. * parallel.
  898. */
  899. lock->agent = NULL;
  900. /*
  901. * Launch the agent (if not already deduplicated) and as many lock waiters as we have
  902. * available increments for on the dedupe path. If we run out of increments, rollover will
  903. * be triggered and the remaining waiters will be transferred to the new lock.
  904. */
  905. if (!agent_is_done) {
  906. launch_dedupe(lock, agent, true);
  907. agent = NULL;
  908. }
  909. while (vdo_waitq_has_waiters(&lock->waiters))
  910. launch_dedupe(lock, dequeue_lock_waiter(lock), false);
  911. if (agent_is_done) {
  912. /*
  913. * In the degenerate case where all the waiters rolled over to a new lock, this
  914. * will continue to use the old agent to clean up this lock, and otherwise it just
  915. * lets the agent exit the lock.
  916. */
  917. finish_deduping(lock, agent);
  918. }
  919. }
  920. /**
  921. * increment_stat() - Increment a statistic counter in a non-atomic yet thread-safe manner.
  922. * @stat: The statistic field to increment.
  923. */
  924. static inline void increment_stat(u64 *stat)
  925. {
  926. /*
  927. * Must only be mutated on the hash zone thread. Prevents any compiler shenanigans from
  928. * affecting other threads reading stats.
  929. */
  930. WRITE_ONCE(*stat, *stat + 1);
  931. }
  932. /**
  933. * finish_verifying() - Handle the result of the agent for the lock comparing its data to the
  934. * duplicate candidate.
  935. * @completion: The completion of the data_vio used to verify dedupe
  936. *
  937. * This continuation is registered in start_verifying().
  938. */
  939. static void finish_verifying(struct vdo_completion *completion)
  940. {
  941. struct data_vio *agent = as_data_vio(completion);
  942. struct hash_lock *lock = agent->hash_lock;
  943. assert_hash_lock_agent(agent, __func__);
  944. lock->verified = agent->is_duplicate;
  945. /*
  946. * Only count the result of the initial verification of the advice as valid or stale, and
  947. * not any re-verifications due to PBN lock releases.
  948. */
  949. if (!lock->verify_counted) {
  950. lock->verify_counted = true;
  951. if (lock->verified)
  952. increment_stat(&agent->hash_zone->statistics.dedupe_advice_valid);
  953. else
  954. increment_stat(&agent->hash_zone->statistics.dedupe_advice_stale);
  955. }
  956. /*
  957. * Even if the block is a verified duplicate, we can't start to deduplicate unless we can
  958. * claim a reference count increment for the agent.
  959. */
  960. if (lock->verified && !vdo_claim_pbn_lock_increment(lock->duplicate_lock)) {
  961. agent->is_duplicate = false;
  962. lock->verified = false;
  963. }
  964. if (lock->verified) {
  965. /*
  966. * VERIFYING -> DEDUPING transition: The advice is for a true duplicate, so start
  967. * deduplicating against it, if references are available.
  968. */
  969. start_deduping(lock, agent, false);
  970. } else {
  971. /*
  972. * VERIFYING -> UNLOCKING transition: Either the verify failed or we'd try to
  973. * dedupe and roll over immediately, which would fail because it would leave the
  974. * lock without an agent to release the PBN lock. In both cases, the data will have
  975. * to be written or compressed, but first the advice PBN must be unlocked by the
  976. * VERIFYING agent.
  977. */
  978. lock->update_advice = true;
  979. start_unlocking(lock, agent);
  980. }
  981. }
  982. static bool blocks_equal(char *block1, char *block2)
  983. {
  984. int i;
  985. for (i = 0; i < VDO_BLOCK_SIZE; i += sizeof(u64)) {
  986. if (*((u64 *) &block1[i]) != *((u64 *) &block2[i]))
  987. return false;
  988. }
  989. return true;
  990. }
  991. static void verify_callback(struct vdo_completion *completion)
  992. {
  993. struct data_vio *agent = as_data_vio(completion);
  994. agent->is_duplicate = blocks_equal(agent->vio.data, agent->scratch_block);
  995. launch_data_vio_hash_zone_callback(agent, finish_verifying);
  996. }
  997. static void uncompress_and_verify(struct vdo_completion *completion)
  998. {
  999. struct data_vio *agent = as_data_vio(completion);
  1000. int result;
  1001. result = uncompress_data_vio(agent, agent->duplicate.state,
  1002. agent->scratch_block);
  1003. if (result == VDO_SUCCESS) {
  1004. verify_callback(completion);
  1005. return;
  1006. }
  1007. agent->is_duplicate = false;
  1008. launch_data_vio_hash_zone_callback(agent, finish_verifying);
  1009. }
  1010. static void verify_endio(struct bio *bio)
  1011. {
  1012. struct data_vio *agent = vio_as_data_vio(bio->bi_private);
  1013. int result = blk_status_to_errno(bio->bi_status);
  1014. vdo_count_completed_bios(bio);
  1015. if (result != VDO_SUCCESS) {
  1016. agent->is_duplicate = false;
  1017. launch_data_vio_hash_zone_callback(agent, finish_verifying);
  1018. return;
  1019. }
  1020. if (vdo_is_state_compressed(agent->duplicate.state)) {
  1021. launch_data_vio_cpu_callback(agent, uncompress_and_verify,
  1022. CPU_Q_COMPRESS_BLOCK_PRIORITY);
  1023. return;
  1024. }
  1025. launch_data_vio_cpu_callback(agent, verify_callback,
  1026. CPU_Q_COMPLETE_READ_PRIORITY);
  1027. }
  1028. /**
  1029. * start_verifying() - Begin the data verification phase.
  1030. * @lock: The hash lock (must be LOCKING).
  1031. * @agent: The data_vio to use to read and compare candidate data.
  1032. *
  1033. * Continue the deduplication path for a hash lock by using the agent to read (and possibly
  1034. * decompress) the data at the candidate duplicate location, comparing it to the data in the agent
  1035. * to verify that the candidate is identical to all the data_vios sharing the hash. If so, it can
  1036. * be deduplicated against, otherwise a data_vio allocation will have to be written to and used for
  1037. * dedupe.
  1038. */
  1039. static void start_verifying(struct hash_lock *lock, struct data_vio *agent)
  1040. {
  1041. int result;
  1042. struct vio *vio = &agent->vio;
  1043. char *buffer = (vdo_is_state_compressed(agent->duplicate.state) ?
  1044. (char *) agent->compression.block :
  1045. agent->scratch_block);
  1046. lock->state = VDO_HASH_LOCK_VERIFYING;
  1047. VDO_ASSERT_LOG_ONLY(!lock->verified, "hash lock only verifies advice once");
  1048. agent->last_async_operation = VIO_ASYNC_OP_VERIFY_DUPLICATION;
  1049. result = vio_reset_bio(vio, buffer, verify_endio, REQ_OP_READ,
  1050. agent->duplicate.pbn);
  1051. if (result != VDO_SUCCESS) {
  1052. set_data_vio_hash_zone_callback(agent, finish_verifying);
  1053. continue_data_vio_with_error(agent, result);
  1054. return;
  1055. }
  1056. set_data_vio_bio_zone_callback(agent, vdo_submit_vio);
  1057. vdo_launch_completion_with_priority(&vio->completion, BIO_Q_VERIFY_PRIORITY);
  1058. }
  1059. /**
  1060. * finish_locking() - Handle the result of the agent for the lock attempting to obtain a PBN read
  1061. * lock on the candidate duplicate block.
  1062. * @completion: The completion of the data_vio that attempted to get the read lock.
  1063. *
  1064. * This continuation is registered in lock_duplicate_pbn().
  1065. */
  1066. static void finish_locking(struct vdo_completion *completion)
  1067. {
  1068. struct data_vio *agent = as_data_vio(completion);
  1069. struct hash_lock *lock = agent->hash_lock;
  1070. assert_hash_lock_agent(agent, __func__);
  1071. if (!agent->is_duplicate) {
  1072. VDO_ASSERT_LOG_ONLY(lock->duplicate_lock == NULL,
  1073. "must not hold duplicate_lock if not flagged as a duplicate");
  1074. /*
  1075. * LOCKING -> WRITING transition: The advice block is being modified or has no
  1076. * available references, so try to write or compress the data, remembering to
  1077. * update UDS later with the new advice.
  1078. */
  1079. increment_stat(&agent->hash_zone->statistics.dedupe_advice_stale);
  1080. lock->update_advice = true;
  1081. start_writing(lock, agent);
  1082. return;
  1083. }
  1084. VDO_ASSERT_LOG_ONLY(lock->duplicate_lock != NULL,
  1085. "must hold duplicate_lock if flagged as a duplicate");
  1086. if (!lock->verified) {
  1087. /*
  1088. * LOCKING -> VERIFYING transition: Continue on the unverified dedupe path, reading
  1089. * the candidate duplicate and comparing it to the agent's data to decide whether
  1090. * it is a true duplicate or stale advice.
  1091. */
  1092. start_verifying(lock, agent);
  1093. return;
  1094. }
  1095. if (!vdo_claim_pbn_lock_increment(lock->duplicate_lock)) {
  1096. /*
  1097. * LOCKING -> UNLOCKING transition: The verified block was re-locked, but has no
  1098. * available increments left. Must first release the useless PBN read lock before
  1099. * rolling over to a new copy of the block.
  1100. */
  1101. agent->is_duplicate = false;
  1102. lock->verified = false;
  1103. lock->update_advice = true;
  1104. start_unlocking(lock, agent);
  1105. return;
  1106. }
  1107. /*
  1108. * LOCKING -> DEDUPING transition: Continue on the verified dedupe path, deduplicating
  1109. * against a location that was previously verified or written to.
  1110. */
  1111. start_deduping(lock, agent, false);
  1112. }
  1113. static bool acquire_provisional_reference(struct data_vio *agent, struct pbn_lock *lock,
  1114. struct slab_depot *depot)
  1115. {
  1116. /* Ensure that the newly-locked block is referenced. */
  1117. struct vdo_slab *slab = vdo_get_slab(depot, agent->duplicate.pbn);
  1118. int result = vdo_acquire_provisional_reference(slab, agent->duplicate.pbn, lock);
  1119. if (result == VDO_SUCCESS)
  1120. return true;
  1121. vdo_log_warning_strerror(result,
  1122. "Error acquiring provisional reference for dedupe candidate; aborting dedupe");
  1123. agent->is_duplicate = false;
  1124. vdo_release_physical_zone_pbn_lock(agent->duplicate.zone,
  1125. agent->duplicate.pbn, lock);
  1126. continue_data_vio_with_error(agent, result);
  1127. return false;
  1128. }
  1129. /**
  1130. * lock_duplicate_pbn() - Acquire a read lock on the PBN of the block containing candidate
  1131. * duplicate data (compressed or uncompressed).
  1132. * @completion: The completion of the data_vio attempting to acquire the physical block lock on
  1133. * behalf of its hash lock.
  1134. *
  1135. * If the PBN is already locked for writing, the lock attempt is abandoned and is_duplicate will be
  1136. * cleared before calling back. This continuation is launched from start_locking(), and calls back
  1137. * to finish_locking() on the hash zone thread.
  1138. */
  1139. static void lock_duplicate_pbn(struct vdo_completion *completion)
  1140. {
  1141. unsigned int increment_limit;
  1142. struct pbn_lock *lock;
  1143. int result;
  1144. struct data_vio *agent = as_data_vio(completion);
  1145. struct slab_depot *depot = vdo_from_data_vio(agent)->depot;
  1146. struct physical_zone *zone = agent->duplicate.zone;
  1147. assert_data_vio_in_duplicate_zone(agent);
  1148. set_data_vio_hash_zone_callback(agent, finish_locking);
  1149. /*
  1150. * While in the zone that owns it, find out how many additional references can be made to
  1151. * the block if it turns out to truly be a duplicate.
  1152. */
  1153. increment_limit = vdo_get_increment_limit(depot, agent->duplicate.pbn);
  1154. if (increment_limit == 0) {
  1155. /*
  1156. * We could deduplicate against it later if a reference happened to be released
  1157. * during verification, but it's probably better to bail out now.
  1158. */
  1159. agent->is_duplicate = false;
  1160. continue_data_vio(agent);
  1161. return;
  1162. }
  1163. result = vdo_attempt_physical_zone_pbn_lock(zone, agent->duplicate.pbn,
  1164. VIO_READ_LOCK, &lock);
  1165. if (result != VDO_SUCCESS) {
  1166. continue_data_vio_with_error(agent, result);
  1167. return;
  1168. }
  1169. if (!vdo_is_pbn_read_lock(lock)) {
  1170. /*
  1171. * There are three cases of write locks: uncompressed data block writes, compressed
  1172. * (packed) block writes, and block map page writes. In all three cases, we give up
  1173. * on trying to verify the advice and don't bother to try deduplicate against the
  1174. * data in the write lock holder.
  1175. *
  1176. * 1) We don't ever want to try to deduplicate against a block map page.
  1177. *
  1178. * 2a) It's very unlikely we'd deduplicate against an entire packed block, both
  1179. * because of the chance of matching it, and because we don't record advice for it,
  1180. * but for the uncompressed representation of all the fragments it contains. The
  1181. * only way we'd be getting lock contention is if we've written the same
  1182. * representation coincidentally before, had it become unreferenced, and it just
  1183. * happened to be packed together from compressed writes when we go to verify the
  1184. * lucky advice. Giving up is a minuscule loss of potential dedupe.
  1185. *
  1186. * 2b) If the advice is for a slot of a compressed block, it's about to get
  1187. * smashed, and the write smashing it cannot contain our data--it would have to be
  1188. * writing on behalf of our hash lock, but that's impossible since we're the lock
  1189. * agent.
  1190. *
  1191. * 3a) If the lock is held by a data_vio with different data, the advice is already
  1192. * stale or is about to become stale.
  1193. *
  1194. * 3b) If the lock is held by a data_vio that matches us, we may as well either
  1195. * write it ourselves (or reference the copy we already wrote) instead of
  1196. * potentially having many duplicates wait for the lock holder to write, journal,
  1197. * hash, and finally arrive in the hash lock. We lose a chance to avoid a UDS
  1198. * update in the very rare case of advice for a free block that just happened to be
  1199. * allocated to a data_vio with the same hash. There's also a chance to save on a
  1200. * block write, at the cost of a block verify. Saving on a full block compare in
  1201. * all stale advice cases almost certainly outweighs saving a UDS update and
  1202. * trading a write for a read in a lucky case where advice would have been saved
  1203. * from becoming stale.
  1204. */
  1205. agent->is_duplicate = false;
  1206. continue_data_vio(agent);
  1207. return;
  1208. }
  1209. if (lock->holder_count == 0) {
  1210. if (!acquire_provisional_reference(agent, lock, depot))
  1211. return;
  1212. /*
  1213. * The increment limit we grabbed earlier is still valid. The lock now holds the
  1214. * rights to acquire all those references. Those rights will be claimed by hash
  1215. * locks sharing this read lock.
  1216. */
  1217. lock->increment_limit = increment_limit;
  1218. }
  1219. /*
  1220. * We've successfully acquired a read lock on behalf of the hash lock, so mark it as such.
  1221. */
  1222. set_duplicate_lock(agent->hash_lock, lock);
  1223. /*
  1224. * TODO: Optimization: We could directly launch the block verify, then switch to a hash
  1225. * thread.
  1226. */
  1227. continue_data_vio(agent);
  1228. }
  1229. /**
  1230. * start_locking() - Continue deduplication for a hash lock that has obtained valid advice of a
  1231. * potential duplicate through its agent.
  1232. * @lock: The hash lock (currently must be QUERYING).
  1233. * @agent: The data_vio bearing the dedupe advice.
  1234. */
  1235. static void start_locking(struct hash_lock *lock, struct data_vio *agent)
  1236. {
  1237. VDO_ASSERT_LOG_ONLY(lock->duplicate_lock == NULL,
  1238. "must not acquire a duplicate lock when already holding it");
  1239. lock->state = VDO_HASH_LOCK_LOCKING;
  1240. /*
  1241. * TODO: Optimization: If we arrange to continue on the duplicate zone thread when
  1242. * accepting the advice, and don't explicitly change lock states (or use an agent-local
  1243. * state, or an atomic), we can avoid a thread transition here.
  1244. */
  1245. agent->last_async_operation = VIO_ASYNC_OP_LOCK_DUPLICATE_PBN;
  1246. launch_data_vio_duplicate_zone_callback(agent, lock_duplicate_pbn);
  1247. }
  1248. /**
  1249. * finish_writing() - Re-entry point for the lock agent after it has finished writing or
  1250. * compressing its copy of the data block.
  1251. * @lock: The hash lock, which must be in state WRITING.
  1252. * @agent: The data_vio that wrote its data for the lock.
  1253. *
  1254. * The agent will never need to dedupe against anything, so it's done with the lock, but the lock
  1255. * may not be finished with it, as a UDS update might still be needed.
  1256. *
  1257. * If there are other lock holders, the agent will hand the job to one of them and exit, leaving
  1258. * the lock to deduplicate against the just-written block. If there are no other lock holders, the
  1259. * agent either exits (and later tears down the hash lock), or it remains the agent and updates
  1260. * UDS.
  1261. */
  1262. static void finish_writing(struct hash_lock *lock, struct data_vio *agent)
  1263. {
  1264. /*
  1265. * Dedupe against the data block or compressed block slot the agent wrote. Since we know
  1266. * the write succeeded, there's no need to verify it.
  1267. */
  1268. lock->duplicate = agent->new_mapped;
  1269. lock->verified = true;
  1270. if (vdo_is_state_compressed(lock->duplicate.state) && lock->registered) {
  1271. /*
  1272. * Compression means the location we gave in the UDS query is not the location
  1273. * we're using to deduplicate.
  1274. */
  1275. lock->update_advice = true;
  1276. }
  1277. /* If there are any waiters, we need to start deduping them. */
  1278. if (vdo_waitq_has_waiters(&lock->waiters)) {
  1279. /*
  1280. * WRITING -> DEDUPING transition: an asynchronously-written block failed to
  1281. * compress, so the PBN lock on the written copy was already transferred. The agent
  1282. * is done with the lock, but the lock may still need to use it to clean up after
  1283. * rollover.
  1284. */
  1285. start_deduping(lock, agent, true);
  1286. return;
  1287. }
  1288. /*
  1289. * There are no waiters and the agent has successfully written, so take a step towards
  1290. * being able to release the hash lock (or just release it).
  1291. */
  1292. if (lock->update_advice) {
  1293. /*
  1294. * WRITING -> UPDATING transition: There's no waiter and a UDS update is needed, so
  1295. * retain the WRITING agent and use it to launch the update. The happens on
  1296. * compression, rollover, or the QUERYING agent not having an allocation.
  1297. */
  1298. start_updating(lock, agent);
  1299. } else if (lock->duplicate_lock != NULL) {
  1300. /*
  1301. * WRITING -> UNLOCKING transition: There's no waiter and no update needed, but the
  1302. * compressed write gave us a shared duplicate lock that we must release.
  1303. */
  1304. set_duplicate_location(agent, lock->duplicate);
  1305. start_unlocking(lock, agent);
  1306. } else {
  1307. /*
  1308. * WRITING -> BYPASSING transition: There's no waiter, no update needed, and no
  1309. * duplicate lock held, so both the agent and lock have no more work to do. The
  1310. * agent will release its allocation lock in cleanup.
  1311. */
  1312. start_bypassing(lock, agent);
  1313. }
  1314. }
  1315. /**
  1316. * select_writing_agent() - Search through the lock waiters for a data_vio that has an allocation.
  1317. * @lock: The hash lock to modify.
  1318. *
  1319. * If an allocation is found, swap agents, put the old agent at the head of the wait queue, then
  1320. * return the new agent. Otherwise, just return the current agent.
  1321. */
  1322. static struct data_vio *select_writing_agent(struct hash_lock *lock)
  1323. {
  1324. struct vdo_wait_queue temp_queue;
  1325. struct data_vio *data_vio;
  1326. vdo_waitq_init(&temp_queue);
  1327. /*
  1328. * Move waiters to the temp queue one-by-one until we find an allocation. Not ideal to
  1329. * search, but it only happens when nearly out of space.
  1330. */
  1331. while (((data_vio = dequeue_lock_waiter(lock)) != NULL) &&
  1332. !data_vio_has_allocation(data_vio)) {
  1333. /* Use the lower-level enqueue since we're just moving waiters around. */
  1334. vdo_waitq_enqueue_waiter(&temp_queue, &data_vio->waiter);
  1335. }
  1336. if (data_vio != NULL) {
  1337. /*
  1338. * Move the rest of the waiters over to the temp queue, preserving the order they
  1339. * arrived at the lock.
  1340. */
  1341. vdo_waitq_transfer_all_waiters(&lock->waiters, &temp_queue);
  1342. /*
  1343. * The current agent is being replaced and will have to wait to dedupe; make it the
  1344. * first waiter since it was the first to reach the lock.
  1345. */
  1346. vdo_waitq_enqueue_waiter(&lock->waiters, &lock->agent->waiter);
  1347. lock->agent = data_vio;
  1348. } else {
  1349. /* No one has an allocation, so keep the current agent. */
  1350. data_vio = lock->agent;
  1351. }
  1352. /* Swap all the waiters back onto the lock's queue. */
  1353. vdo_waitq_transfer_all_waiters(&temp_queue, &lock->waiters);
  1354. return data_vio;
  1355. }
  1356. /**
  1357. * start_writing() - Begin the non-duplicate write path.
  1358. * @lock: The hash lock (currently must be QUERYING).
  1359. * @agent: The data_vio currently acting as the agent for the lock.
  1360. *
  1361. * Begins the non-duplicate write path for a hash lock that had no advice, selecting a data_vio
  1362. * with an allocation as a new agent, if necessary, then resuming the agent on the data_vio write
  1363. * path.
  1364. */
  1365. static void start_writing(struct hash_lock *lock, struct data_vio *agent)
  1366. {
  1367. lock->state = VDO_HASH_LOCK_WRITING;
  1368. /*
  1369. * The agent might not have received an allocation and so can't be used for writing, but
  1370. * it's entirely possible that one of the waiters did.
  1371. */
  1372. if (!data_vio_has_allocation(agent)) {
  1373. agent = select_writing_agent(lock);
  1374. /* If none of the waiters had an allocation, the writes all have to fail. */
  1375. if (!data_vio_has_allocation(agent)) {
  1376. /*
  1377. * TODO: Should we keep a variant of BYPASSING that causes new arrivals to
  1378. * fail immediately if they don't have an allocation? It might be possible
  1379. * that on some path there would be non-waiters still referencing the lock,
  1380. * so it would remain in the map as everything is currently spelled, even
  1381. * if the agent and all waiters release.
  1382. */
  1383. continue_data_vio_with_error(agent, VDO_NO_SPACE);
  1384. return;
  1385. }
  1386. }
  1387. /*
  1388. * If the agent compresses, it might wait indefinitely in the packer, which would be bad if
  1389. * there are any other data_vios waiting.
  1390. */
  1391. if (vdo_waitq_has_waiters(&lock->waiters))
  1392. cancel_data_vio_compression(agent);
  1393. /*
  1394. * Send the agent to the compress/pack/write path in vioWrite. If it succeeds, it will
  1395. * return to the hash lock via vdo_continue_hash_lock() and call finish_writing().
  1396. */
  1397. launch_compress_data_vio(agent);
  1398. }
  1399. /*
  1400. * Decode VDO duplicate advice from the old_metadata field of a UDS request.
  1401. * Returns true if valid advice was found and decoded
  1402. */
  1403. static bool decode_uds_advice(struct dedupe_context *context)
  1404. {
  1405. const struct uds_request *request = &context->request;
  1406. struct data_vio *data_vio = context->requestor;
  1407. size_t offset = 0;
  1408. const struct uds_record_data *encoding = &request->old_metadata;
  1409. struct vdo *vdo = vdo_from_data_vio(data_vio);
  1410. struct zoned_pbn *advice = &data_vio->duplicate;
  1411. u8 version;
  1412. int result;
  1413. if ((request->status != UDS_SUCCESS) || !request->found)
  1414. return false;
  1415. version = encoding->data[offset++];
  1416. if (version != UDS_ADVICE_VERSION) {
  1417. vdo_log_error("invalid UDS advice version code %u", version);
  1418. return false;
  1419. }
  1420. advice->state = encoding->data[offset++];
  1421. advice->pbn = get_unaligned_le64(&encoding->data[offset]);
  1422. offset += sizeof(u64);
  1423. BUG_ON(offset != UDS_ADVICE_SIZE);
  1424. /* Don't use advice that's clearly meaningless. */
  1425. if ((advice->state == VDO_MAPPING_STATE_UNMAPPED) || (advice->pbn == VDO_ZERO_BLOCK)) {
  1426. vdo_log_debug("Invalid advice from deduplication server: pbn %llu, state %u. Giving up on deduplication of logical block %llu",
  1427. (unsigned long long) advice->pbn, advice->state,
  1428. (unsigned long long) data_vio->logical.lbn);
  1429. atomic64_inc(&vdo->stats.invalid_advice_pbn_count);
  1430. return false;
  1431. }
  1432. result = vdo_get_physical_zone(vdo, advice->pbn, &advice->zone);
  1433. if ((result != VDO_SUCCESS) || (advice->zone == NULL)) {
  1434. vdo_log_debug("Invalid physical block number from deduplication server: %llu, giving up on deduplication of logical block %llu",
  1435. (unsigned long long) advice->pbn,
  1436. (unsigned long long) data_vio->logical.lbn);
  1437. atomic64_inc(&vdo->stats.invalid_advice_pbn_count);
  1438. return false;
  1439. }
  1440. return true;
  1441. }
  1442. static void process_query_result(struct data_vio *agent)
  1443. {
  1444. struct dedupe_context *context = agent->dedupe_context;
  1445. if (context == NULL)
  1446. return;
  1447. if (change_context_state(context, DEDUPE_CONTEXT_COMPLETE, DEDUPE_CONTEXT_IDLE)) {
  1448. agent->is_duplicate = decode_uds_advice(context);
  1449. agent->dedupe_context = NULL;
  1450. release_context(context);
  1451. }
  1452. }
  1453. /**
  1454. * finish_querying() - Process the result of a UDS query performed by the agent for the lock.
  1455. * @completion: The completion of the data_vio that performed the query.
  1456. *
  1457. * This continuation is registered in start_querying().
  1458. */
  1459. static void finish_querying(struct vdo_completion *completion)
  1460. {
  1461. struct data_vio *agent = as_data_vio(completion);
  1462. struct hash_lock *lock = agent->hash_lock;
  1463. assert_hash_lock_agent(agent, __func__);
  1464. process_query_result(agent);
  1465. if (agent->is_duplicate) {
  1466. lock->duplicate = agent->duplicate;
  1467. /*
  1468. * QUERYING -> LOCKING transition: Valid advice was obtained from UDS. Use the
  1469. * QUERYING agent to start the hash lock on the unverified dedupe path, verifying
  1470. * that the advice can be used.
  1471. */
  1472. start_locking(lock, agent);
  1473. } else {
  1474. /*
  1475. * The agent will be used as the duplicate if has an allocation; if it does, that
  1476. * location was posted to UDS, so no update will be needed.
  1477. */
  1478. lock->update_advice = !data_vio_has_allocation(agent);
  1479. /*
  1480. * QUERYING -> WRITING transition: There was no advice or the advice wasn't valid,
  1481. * so try to write or compress the data.
  1482. */
  1483. start_writing(lock, agent);
  1484. }
  1485. }
  1486. /**
  1487. * start_querying() - Start deduplication for a hash lock.
  1488. * @lock: The initialized hash lock.
  1489. * @data_vio: The data_vio that has just obtained the new lock.
  1490. *
  1491. * Starts deduplication for a hash lock that has finished initializing by making the data_vio that
  1492. * requested it the agent, entering the QUERYING state, and using the agent to perform the UDS
  1493. * query on behalf of the lock.
  1494. */
  1495. static void start_querying(struct hash_lock *lock, struct data_vio *data_vio)
  1496. {
  1497. lock->agent = data_vio;
  1498. lock->state = VDO_HASH_LOCK_QUERYING;
  1499. data_vio->last_async_operation = VIO_ASYNC_OP_CHECK_FOR_DUPLICATION;
  1500. set_data_vio_hash_zone_callback(data_vio, finish_querying);
  1501. query_index(data_vio,
  1502. (data_vio_has_allocation(data_vio) ? UDS_POST : UDS_QUERY));
  1503. }
  1504. /**
  1505. * report_bogus_lock_state() - Complain that a data_vio has entered a hash_lock that is in an
  1506. * unimplemented or unusable state and continue the data_vio with an
  1507. * error.
  1508. * @lock: The hash lock.
  1509. * @data_vio: The data_vio attempting to enter the lock.
  1510. */
  1511. static void report_bogus_lock_state(struct hash_lock *lock, struct data_vio *data_vio)
  1512. {
  1513. VDO_ASSERT_LOG_ONLY(false, "hash lock must not be in unimplemented state %s",
  1514. get_hash_lock_state_name(lock->state));
  1515. continue_data_vio_with_error(data_vio, VDO_LOCK_ERROR);
  1516. }
  1517. /**
  1518. * vdo_continue_hash_lock() - Continue the processing state after writing, compressing, or
  1519. * deduplicating.
  1520. * @data_vio: The data_vio to continue processing in its hash lock.
  1521. *
  1522. * Asynchronously continue processing a data_vio in its hash lock after it has finished writing,
  1523. * compressing, or deduplicating, so it can share the result with any data_vios waiting in the hash
  1524. * lock, or update the UDS index, or simply release its share of the lock.
  1525. *
  1526. * Context: This must only be called in the correct thread for the hash zone.
  1527. */
  1528. void vdo_continue_hash_lock(struct vdo_completion *completion)
  1529. {
  1530. struct data_vio *data_vio = as_data_vio(completion);
  1531. struct hash_lock *lock = data_vio->hash_lock;
  1532. switch (lock->state) {
  1533. case VDO_HASH_LOCK_WRITING:
  1534. VDO_ASSERT_LOG_ONLY(data_vio == lock->agent,
  1535. "only the lock agent may continue the lock");
  1536. finish_writing(lock, data_vio);
  1537. break;
  1538. case VDO_HASH_LOCK_DEDUPING:
  1539. finish_deduping(lock, data_vio);
  1540. break;
  1541. case VDO_HASH_LOCK_BYPASSING:
  1542. /* This data_vio has finished the write path and the lock doesn't need it. */
  1543. exit_hash_lock(data_vio);
  1544. break;
  1545. case VDO_HASH_LOCK_INITIALIZING:
  1546. case VDO_HASH_LOCK_QUERYING:
  1547. case VDO_HASH_LOCK_UPDATING:
  1548. case VDO_HASH_LOCK_LOCKING:
  1549. case VDO_HASH_LOCK_VERIFYING:
  1550. case VDO_HASH_LOCK_UNLOCKING:
  1551. /* A lock in this state should never be re-entered. */
  1552. report_bogus_lock_state(lock, data_vio);
  1553. break;
  1554. default:
  1555. report_bogus_lock_state(lock, data_vio);
  1556. }
  1557. }
  1558. /**
  1559. * is_hash_collision() - Check to see if a hash collision has occurred.
  1560. * @lock: The lock to check.
  1561. * @candidate: The data_vio seeking to share the lock.
  1562. *
  1563. * Check whether the data in data_vios sharing a lock is different than in a data_vio seeking to
  1564. * share the lock, which should only be possible in the extremely unlikely case of a hash
  1565. * collision.
  1566. *
  1567. * Return: true if the given data_vio must not share the lock because it doesn't have the same data
  1568. * as the lock holders.
  1569. */
  1570. static bool is_hash_collision(struct hash_lock *lock, struct data_vio *candidate)
  1571. {
  1572. struct data_vio *lock_holder;
  1573. struct hash_zone *zone;
  1574. bool collides;
  1575. if (list_empty(&lock->duplicate_ring))
  1576. return false;
  1577. lock_holder = list_first_entry(&lock->duplicate_ring, struct data_vio,
  1578. hash_lock_entry);
  1579. zone = candidate->hash_zone;
  1580. collides = !blocks_equal(lock_holder->vio.data, candidate->vio.data);
  1581. if (collides)
  1582. increment_stat(&zone->statistics.concurrent_hash_collisions);
  1583. else
  1584. increment_stat(&zone->statistics.concurrent_data_matches);
  1585. return collides;
  1586. }
  1587. static inline int assert_hash_lock_preconditions(const struct data_vio *data_vio)
  1588. {
  1589. int result;
  1590. /* FIXME: BUG_ON() and/or enter read-only mode? */
  1591. result = VDO_ASSERT(data_vio->hash_lock == NULL,
  1592. "must not already hold a hash lock");
  1593. if (result != VDO_SUCCESS)
  1594. return result;
  1595. result = VDO_ASSERT(list_empty(&data_vio->hash_lock_entry),
  1596. "must not already be a member of a hash lock ring");
  1597. if (result != VDO_SUCCESS)
  1598. return result;
  1599. return VDO_ASSERT(data_vio->recovery_sequence_number == 0,
  1600. "must not hold a recovery lock when getting a hash lock");
  1601. }
  1602. /**
  1603. * vdo_acquire_hash_lock() - Acquire or share a lock on a record name.
  1604. * @data_vio: The data_vio acquiring a lock on its record name.
  1605. *
  1606. * Acquire or share a lock on the hash (record name) of the data in a data_vio, updating the
  1607. * data_vio to reference the lock. This must only be called in the correct thread for the zone. In
  1608. * the unlikely case of a hash collision, this function will succeed, but the data_vio will not get
  1609. * a lock reference.
  1610. */
  1611. void vdo_acquire_hash_lock(struct vdo_completion *completion)
  1612. {
  1613. struct data_vio *data_vio = as_data_vio(completion);
  1614. struct hash_lock *lock;
  1615. int result;
  1616. assert_data_vio_in_hash_zone(data_vio);
  1617. result = assert_hash_lock_preconditions(data_vio);
  1618. if (result != VDO_SUCCESS) {
  1619. continue_data_vio_with_error(data_vio, result);
  1620. return;
  1621. }
  1622. result = acquire_lock(data_vio->hash_zone, &data_vio->record_name, NULL, &lock);
  1623. if (result != VDO_SUCCESS) {
  1624. continue_data_vio_with_error(data_vio, result);
  1625. return;
  1626. }
  1627. if (is_hash_collision(lock, data_vio)) {
  1628. /*
  1629. * Hash collisions are extremely unlikely, but the bogus dedupe would be a data
  1630. * corruption. Bypass optimization entirely. We can't compress a data_vio without
  1631. * a hash_lock as the compressed write depends on the hash_lock to manage the
  1632. * references for the compressed block.
  1633. */
  1634. write_data_vio(data_vio);
  1635. return;
  1636. }
  1637. set_hash_lock(data_vio, lock);
  1638. switch (lock->state) {
  1639. case VDO_HASH_LOCK_INITIALIZING:
  1640. start_querying(lock, data_vio);
  1641. return;
  1642. case VDO_HASH_LOCK_QUERYING:
  1643. case VDO_HASH_LOCK_WRITING:
  1644. case VDO_HASH_LOCK_UPDATING:
  1645. case VDO_HASH_LOCK_LOCKING:
  1646. case VDO_HASH_LOCK_VERIFYING:
  1647. case VDO_HASH_LOCK_UNLOCKING:
  1648. /* The lock is busy, and can't be shared yet. */
  1649. wait_on_hash_lock(lock, data_vio);
  1650. return;
  1651. case VDO_HASH_LOCK_BYPASSING:
  1652. /* We can't use this lock, so bypass optimization entirely. */
  1653. vdo_release_hash_lock(data_vio);
  1654. write_data_vio(data_vio);
  1655. return;
  1656. case VDO_HASH_LOCK_DEDUPING:
  1657. launch_dedupe(lock, data_vio, false);
  1658. return;
  1659. default:
  1660. /* A lock in this state should not be acquired by new VIOs. */
  1661. report_bogus_lock_state(lock, data_vio);
  1662. }
  1663. }
  1664. /**
  1665. * vdo_release_hash_lock() - Release a data_vio's share of a hash lock, if held, and null out the
  1666. * data_vio's reference to it.
  1667. * @data_vio: The data_vio releasing its hash lock.
  1668. *
  1669. * If the data_vio is the only one holding the lock, this also releases any resources or locks used
  1670. * by the hash lock (such as a PBN read lock on a block containing data with the same hash) and
  1671. * returns the lock to the hash zone's lock pool.
  1672. *
  1673. * Context: This must only be called in the correct thread for the hash zone.
  1674. */
  1675. void vdo_release_hash_lock(struct data_vio *data_vio)
  1676. {
  1677. u64 lock_key;
  1678. struct hash_lock *lock = data_vio->hash_lock;
  1679. struct hash_zone *zone = data_vio->hash_zone;
  1680. if (lock == NULL)
  1681. return;
  1682. set_hash_lock(data_vio, NULL);
  1683. if (lock->reference_count > 0) {
  1684. /* The lock is still in use by other data_vios. */
  1685. return;
  1686. }
  1687. lock_key = hash_lock_key(lock);
  1688. if (lock->registered) {
  1689. struct hash_lock *removed;
  1690. removed = vdo_int_map_remove(zone->hash_lock_map, lock_key);
  1691. VDO_ASSERT_LOG_ONLY(lock == removed,
  1692. "hash lock being released must have been mapped");
  1693. } else {
  1694. VDO_ASSERT_LOG_ONLY(lock != vdo_int_map_get(zone->hash_lock_map, lock_key),
  1695. "unregistered hash lock must not be in the lock map");
  1696. }
  1697. VDO_ASSERT_LOG_ONLY(!vdo_waitq_has_waiters(&lock->waiters),
  1698. "hash lock returned to zone must have no waiters");
  1699. VDO_ASSERT_LOG_ONLY((lock->duplicate_lock == NULL),
  1700. "hash lock returned to zone must not reference a PBN lock");
  1701. VDO_ASSERT_LOG_ONLY((lock->state == VDO_HASH_LOCK_BYPASSING),
  1702. "returned hash lock must not be in use with state %s",
  1703. get_hash_lock_state_name(lock->state));
  1704. VDO_ASSERT_LOG_ONLY(list_empty(&lock->pool_node),
  1705. "hash lock returned to zone must not be in a pool ring");
  1706. VDO_ASSERT_LOG_ONLY(list_empty(&lock->duplicate_ring),
  1707. "hash lock returned to zone must not reference DataVIOs");
  1708. return_hash_lock_to_pool(zone, lock);
  1709. }
  1710. /**
  1711. * transfer_allocation_lock() - Transfer a data_vio's downgraded allocation PBN lock to the
  1712. * data_vio's hash lock, converting it to a duplicate PBN lock.
  1713. * @data_vio: The data_vio holding the allocation lock to transfer.
  1714. */
  1715. static void transfer_allocation_lock(struct data_vio *data_vio)
  1716. {
  1717. struct allocation *allocation = &data_vio->allocation;
  1718. struct hash_lock *hash_lock = data_vio->hash_lock;
  1719. VDO_ASSERT_LOG_ONLY(data_vio->new_mapped.pbn == allocation->pbn,
  1720. "transferred lock must be for the block written");
  1721. allocation->pbn = VDO_ZERO_BLOCK;
  1722. VDO_ASSERT_LOG_ONLY(vdo_is_pbn_read_lock(allocation->lock),
  1723. "must have downgraded the allocation lock before transfer");
  1724. hash_lock->duplicate = data_vio->new_mapped;
  1725. data_vio->duplicate = data_vio->new_mapped;
  1726. /*
  1727. * Since the lock is being transferred, the holder count doesn't change (and isn't even
  1728. * safe to examine on this thread).
  1729. */
  1730. hash_lock->duplicate_lock = vdo_forget(allocation->lock);
  1731. }
  1732. /**
  1733. * vdo_share_compressed_write_lock() - Make a data_vio's hash lock a shared holder of the PBN lock
  1734. * on the compressed block to which its data was just written.
  1735. * @data_vio: The data_vio which was just compressed.
  1736. * @pbn_lock: The PBN lock on the compressed block.
  1737. *
  1738. * If the lock is still a write lock (as it will be for the first share), it will be converted to a
  1739. * read lock. This also reserves a reference count increment for the data_vio.
  1740. */
  1741. void vdo_share_compressed_write_lock(struct data_vio *data_vio,
  1742. struct pbn_lock *pbn_lock)
  1743. {
  1744. bool claimed;
  1745. VDO_ASSERT_LOG_ONLY(vdo_get_duplicate_lock(data_vio) == NULL,
  1746. "a duplicate PBN lock should not exist when writing");
  1747. VDO_ASSERT_LOG_ONLY(vdo_is_state_compressed(data_vio->new_mapped.state),
  1748. "lock transfer must be for a compressed write");
  1749. assert_data_vio_in_new_mapped_zone(data_vio);
  1750. /* First sharer downgrades the lock. */
  1751. if (!vdo_is_pbn_read_lock(pbn_lock))
  1752. vdo_downgrade_pbn_write_lock(pbn_lock, true);
  1753. /*
  1754. * Get a share of the PBN lock, ensuring it cannot be released until after this data_vio
  1755. * has had a chance to journal a reference.
  1756. */
  1757. data_vio->duplicate = data_vio->new_mapped;
  1758. data_vio->hash_lock->duplicate = data_vio->new_mapped;
  1759. set_duplicate_lock(data_vio->hash_lock, pbn_lock);
  1760. /*
  1761. * Claim a reference for this data_vio. Necessary since another hash_lock might start
  1762. * deduplicating against it before our incRef.
  1763. */
  1764. claimed = vdo_claim_pbn_lock_increment(pbn_lock);
  1765. VDO_ASSERT_LOG_ONLY(claimed, "impossible to fail to claim an initial increment");
  1766. }
  1767. static void start_uds_queue(void *ptr)
  1768. {
  1769. /*
  1770. * Allow the UDS dedupe worker thread to do memory allocations. It will only do allocations
  1771. * during the UDS calls that open or close an index, but those allocations can safely sleep
  1772. * while reserving a large amount of memory. We could use an allocations_allowed boolean
  1773. * (like the base threads do), but it would be an unnecessary embellishment.
  1774. */
  1775. struct vdo_thread *thread = vdo_get_work_queue_owner(vdo_get_current_work_queue());
  1776. vdo_register_allocating_thread(&thread->allocating_thread, NULL);
  1777. }
  1778. static void finish_uds_queue(void *ptr __always_unused)
  1779. {
  1780. vdo_unregister_allocating_thread();
  1781. }
  1782. static void close_index(struct hash_zones *zones)
  1783. __must_hold(&zones->lock)
  1784. {
  1785. int result;
  1786. /*
  1787. * Change the index state so that get_index_statistics() will not try to use the index
  1788. * session we are closing.
  1789. */
  1790. zones->index_state = IS_CHANGING;
  1791. /* Close the index session, while not holding the lock. */
  1792. spin_unlock(&zones->lock);
  1793. result = uds_close_index(zones->index_session);
  1794. if (result != UDS_SUCCESS)
  1795. vdo_log_error_strerror(result, "Error closing index");
  1796. spin_lock(&zones->lock);
  1797. zones->index_state = IS_CLOSED;
  1798. zones->error_flag |= result != UDS_SUCCESS;
  1799. /* ASSERTION: We leave in IS_CLOSED state. */
  1800. }
  1801. static void open_index(struct hash_zones *zones)
  1802. __must_hold(&zones->lock)
  1803. {
  1804. /* ASSERTION: We enter in IS_CLOSED state. */
  1805. int result;
  1806. bool create_flag = zones->create_flag;
  1807. zones->create_flag = false;
  1808. /*
  1809. * Change the index state so that the it will be reported to the outside world as
  1810. * "opening".
  1811. */
  1812. zones->index_state = IS_CHANGING;
  1813. zones->error_flag = false;
  1814. /* Open the index session, while not holding the lock */
  1815. spin_unlock(&zones->lock);
  1816. result = uds_open_index(create_flag ? UDS_CREATE : UDS_LOAD,
  1817. &zones->parameters, zones->index_session);
  1818. if (result != UDS_SUCCESS)
  1819. vdo_log_error_strerror(result, "Error opening index");
  1820. spin_lock(&zones->lock);
  1821. if (!create_flag) {
  1822. switch (result) {
  1823. case -ENOENT:
  1824. /*
  1825. * Either there is no index, or there is no way we can recover the index.
  1826. * We will be called again and try to create a new index.
  1827. */
  1828. zones->index_state = IS_CLOSED;
  1829. zones->create_flag = true;
  1830. return;
  1831. default:
  1832. break;
  1833. }
  1834. }
  1835. if (result == UDS_SUCCESS) {
  1836. zones->index_state = IS_OPENED;
  1837. } else {
  1838. zones->index_state = IS_CLOSED;
  1839. zones->index_target = IS_CLOSED;
  1840. zones->error_flag = true;
  1841. spin_unlock(&zones->lock);
  1842. vdo_log_info("Setting UDS index target state to error");
  1843. spin_lock(&zones->lock);
  1844. }
  1845. /*
  1846. * ASSERTION: On success, we leave in IS_OPENED state.
  1847. * ASSERTION: On failure, we leave in IS_CLOSED state.
  1848. */
  1849. }
  1850. static void change_dedupe_state(struct vdo_completion *completion)
  1851. {
  1852. struct hash_zones *zones = as_hash_zones(completion);
  1853. spin_lock(&zones->lock);
  1854. /* Loop until the index is in the target state and the create flag is clear. */
  1855. while (vdo_is_state_normal(&zones->state) &&
  1856. ((zones->index_state != zones->index_target) || zones->create_flag)) {
  1857. if (zones->index_state == IS_OPENED)
  1858. close_index(zones);
  1859. else
  1860. open_index(zones);
  1861. }
  1862. zones->changing = false;
  1863. spin_unlock(&zones->lock);
  1864. }
  1865. static void start_expiration_timer(struct dedupe_context *context)
  1866. {
  1867. u64 start_time = context->submission_jiffies;
  1868. u64 end_time;
  1869. if (!change_timer_state(context->zone, DEDUPE_QUERY_TIMER_IDLE,
  1870. DEDUPE_QUERY_TIMER_RUNNING))
  1871. return;
  1872. end_time = max(start_time + vdo_dedupe_index_timeout_jiffies,
  1873. jiffies + vdo_dedupe_index_min_timer_jiffies);
  1874. mod_timer(&context->zone->timer, end_time);
  1875. }
  1876. /**
  1877. * report_dedupe_timeouts() - Record and eventually report that some dedupe requests reached their
  1878. * expiration time without getting answers, so we timed them out.
  1879. * @zones: the hash zones.
  1880. * @timeouts: the number of newly timed out requests.
  1881. */
  1882. static void report_dedupe_timeouts(struct hash_zones *zones, unsigned int timeouts)
  1883. {
  1884. atomic64_add(timeouts, &zones->timeouts);
  1885. spin_lock(&zones->lock);
  1886. if (__ratelimit(&zones->ratelimiter)) {
  1887. u64 unreported = atomic64_read(&zones->timeouts);
  1888. unreported -= zones->reported_timeouts;
  1889. vdo_log_debug("UDS index timeout on %llu requests",
  1890. (unsigned long long) unreported);
  1891. zones->reported_timeouts += unreported;
  1892. }
  1893. spin_unlock(&zones->lock);
  1894. }
  1895. static int initialize_index(struct vdo *vdo, struct hash_zones *zones)
  1896. {
  1897. int result;
  1898. off_t uds_offset;
  1899. struct volume_geometry geometry = vdo->geometry;
  1900. static const struct vdo_work_queue_type uds_queue_type = {
  1901. .start = start_uds_queue,
  1902. .finish = finish_uds_queue,
  1903. .max_priority = UDS_Q_MAX_PRIORITY,
  1904. .default_priority = UDS_Q_PRIORITY,
  1905. };
  1906. vdo_set_dedupe_index_timeout_interval(vdo_dedupe_index_timeout_interval);
  1907. vdo_set_dedupe_index_min_timer_interval(vdo_dedupe_index_min_timer_interval);
  1908. spin_lock_init(&zones->lock);
  1909. /*
  1910. * Since we will save up the timeouts that would have been reported but were ratelimited,
  1911. * we don't need to report ratelimiting.
  1912. */
  1913. ratelimit_default_init(&zones->ratelimiter);
  1914. ratelimit_set_flags(&zones->ratelimiter, RATELIMIT_MSG_ON_RELEASE);
  1915. uds_offset = ((vdo_get_index_region_start(geometry) -
  1916. geometry.bio_offset) * VDO_BLOCK_SIZE);
  1917. zones->parameters = (struct uds_parameters) {
  1918. .bdev = vdo->device_config->owned_device->bdev,
  1919. .offset = uds_offset,
  1920. .size = (vdo_get_index_region_size(geometry) * VDO_BLOCK_SIZE),
  1921. .memory_size = geometry.index_config.mem,
  1922. .sparse = geometry.index_config.sparse,
  1923. .nonce = (u64) geometry.nonce,
  1924. };
  1925. result = uds_create_index_session(&zones->index_session);
  1926. if (result != UDS_SUCCESS)
  1927. return result;
  1928. result = vdo_make_thread(vdo, vdo->thread_config.dedupe_thread, &uds_queue_type,
  1929. 1, NULL);
  1930. if (result != VDO_SUCCESS) {
  1931. uds_destroy_index_session(vdo_forget(zones->index_session));
  1932. vdo_log_error("UDS index queue initialization failed (%d)", result);
  1933. return result;
  1934. }
  1935. vdo_initialize_completion(&zones->completion, vdo, VDO_HASH_ZONES_COMPLETION);
  1936. vdo_set_completion_callback(&zones->completion, change_dedupe_state,
  1937. vdo->thread_config.dedupe_thread);
  1938. return VDO_SUCCESS;
  1939. }
  1940. /**
  1941. * finish_index_operation() - This is the UDS callback for index queries.
  1942. * @request: The uds request which has just completed.
  1943. */
  1944. static void finish_index_operation(struct uds_request *request)
  1945. {
  1946. struct dedupe_context *context = container_of(request, struct dedupe_context,
  1947. request);
  1948. if (change_context_state(context, DEDUPE_CONTEXT_PENDING,
  1949. DEDUPE_CONTEXT_COMPLETE)) {
  1950. /*
  1951. * This query has not timed out, so send its data_vio back to its hash zone to
  1952. * process the results.
  1953. */
  1954. continue_data_vio(context->requestor);
  1955. return;
  1956. }
  1957. /*
  1958. * This query has timed out, so try to mark it complete and hence eligible for reuse. Its
  1959. * data_vio has already moved on.
  1960. */
  1961. if (!change_context_state(context, DEDUPE_CONTEXT_TIMED_OUT,
  1962. DEDUPE_CONTEXT_TIMED_OUT_COMPLETE)) {
  1963. VDO_ASSERT_LOG_ONLY(false, "uds request was timed out (state %d)",
  1964. atomic_read(&context->state));
  1965. }
  1966. vdo_funnel_queue_put(context->zone->timed_out_complete, &context->queue_entry);
  1967. }
  1968. /**
  1969. * check_for_drain_complete() - Check whether this zone has drained.
  1970. * @zone: The zone to check.
  1971. */
  1972. static void check_for_drain_complete(struct hash_zone *zone)
  1973. {
  1974. data_vio_count_t recycled = 0;
  1975. if (!vdo_is_state_draining(&zone->state))
  1976. return;
  1977. if ((atomic_read(&zone->timer_state) == DEDUPE_QUERY_TIMER_IDLE) ||
  1978. change_timer_state(zone, DEDUPE_QUERY_TIMER_RUNNING,
  1979. DEDUPE_QUERY_TIMER_IDLE)) {
  1980. del_timer_sync(&zone->timer);
  1981. } else {
  1982. /*
  1983. * There is an in flight time-out, which must get processed before we can continue.
  1984. */
  1985. return;
  1986. }
  1987. for (;;) {
  1988. struct dedupe_context *context;
  1989. struct funnel_queue_entry *entry;
  1990. entry = vdo_funnel_queue_poll(zone->timed_out_complete);
  1991. if (entry == NULL)
  1992. break;
  1993. context = container_of(entry, struct dedupe_context, queue_entry);
  1994. atomic_set(&context->state, DEDUPE_CONTEXT_IDLE);
  1995. list_add(&context->list_entry, &zone->available);
  1996. recycled++;
  1997. }
  1998. if (recycled > 0)
  1999. WRITE_ONCE(zone->active, zone->active - recycled);
  2000. VDO_ASSERT_LOG_ONLY(READ_ONCE(zone->active) == 0, "all contexts inactive");
  2001. vdo_finish_draining(&zone->state);
  2002. }
  2003. static void timeout_index_operations_callback(struct vdo_completion *completion)
  2004. {
  2005. struct dedupe_context *context, *tmp;
  2006. struct hash_zone *zone = as_hash_zone(completion);
  2007. u64 timeout_jiffies = msecs_to_jiffies(vdo_dedupe_index_timeout_interval);
  2008. unsigned long cutoff = jiffies - timeout_jiffies;
  2009. unsigned int timed_out = 0;
  2010. atomic_set(&zone->timer_state, DEDUPE_QUERY_TIMER_IDLE);
  2011. list_for_each_entry_safe(context, tmp, &zone->pending, list_entry) {
  2012. if (cutoff <= context->submission_jiffies) {
  2013. /*
  2014. * We have reached the oldest query which has not timed out yet, so restart
  2015. * the timer.
  2016. */
  2017. start_expiration_timer(context);
  2018. break;
  2019. }
  2020. if (!change_context_state(context, DEDUPE_CONTEXT_PENDING,
  2021. DEDUPE_CONTEXT_TIMED_OUT)) {
  2022. /*
  2023. * This context completed between the time the timeout fired, and now. We
  2024. * can treat it as a successful query, its requestor is already enqueued
  2025. * to process it.
  2026. */
  2027. continue;
  2028. }
  2029. /*
  2030. * Remove this context from the pending list so we won't look at it again on a
  2031. * subsequent timeout. Once the index completes it, it will be reused. Meanwhile,
  2032. * send its requestor on its way.
  2033. */
  2034. list_del_init(&context->list_entry);
  2035. context->requestor->dedupe_context = NULL;
  2036. continue_data_vio(context->requestor);
  2037. timed_out++;
  2038. }
  2039. if (timed_out > 0)
  2040. report_dedupe_timeouts(completion->vdo->hash_zones, timed_out);
  2041. check_for_drain_complete(zone);
  2042. }
  2043. static void timeout_index_operations(struct timer_list *t)
  2044. {
  2045. struct hash_zone *zone = from_timer(zone, t, timer);
  2046. if (change_timer_state(zone, DEDUPE_QUERY_TIMER_RUNNING,
  2047. DEDUPE_QUERY_TIMER_FIRED))
  2048. vdo_launch_completion(&zone->completion);
  2049. }
  2050. static int __must_check initialize_zone(struct vdo *vdo, struct hash_zones *zones,
  2051. zone_count_t zone_number)
  2052. {
  2053. int result;
  2054. data_vio_count_t i;
  2055. struct hash_zone *zone = &zones->zones[zone_number];
  2056. result = vdo_int_map_create(VDO_LOCK_MAP_CAPACITY, &zone->hash_lock_map);
  2057. if (result != VDO_SUCCESS)
  2058. return result;
  2059. vdo_set_admin_state_code(&zone->state, VDO_ADMIN_STATE_NORMAL_OPERATION);
  2060. zone->zone_number = zone_number;
  2061. zone->thread_id = vdo->thread_config.hash_zone_threads[zone_number];
  2062. vdo_initialize_completion(&zone->completion, vdo, VDO_HASH_ZONE_COMPLETION);
  2063. vdo_set_completion_callback(&zone->completion, timeout_index_operations_callback,
  2064. zone->thread_id);
  2065. INIT_LIST_HEAD(&zone->lock_pool);
  2066. result = vdo_allocate(LOCK_POOL_CAPACITY, struct hash_lock, "hash_lock array",
  2067. &zone->lock_array);
  2068. if (result != VDO_SUCCESS)
  2069. return result;
  2070. for (i = 0; i < LOCK_POOL_CAPACITY; i++)
  2071. return_hash_lock_to_pool(zone, &zone->lock_array[i]);
  2072. INIT_LIST_HEAD(&zone->available);
  2073. INIT_LIST_HEAD(&zone->pending);
  2074. result = vdo_make_funnel_queue(&zone->timed_out_complete);
  2075. if (result != VDO_SUCCESS)
  2076. return result;
  2077. timer_setup(&zone->timer, timeout_index_operations, 0);
  2078. for (i = 0; i < MAXIMUM_VDO_USER_VIOS; i++) {
  2079. struct dedupe_context *context = &zone->contexts[i];
  2080. context->zone = zone;
  2081. context->request.callback = finish_index_operation;
  2082. context->request.session = zones->index_session;
  2083. list_add(&context->list_entry, &zone->available);
  2084. }
  2085. return vdo_make_default_thread(vdo, zone->thread_id);
  2086. }
  2087. /** get_thread_id_for_zone() - Implements vdo_zone_thread_getter_fn. */
  2088. static thread_id_t get_thread_id_for_zone(void *context, zone_count_t zone_number)
  2089. {
  2090. struct hash_zones *zones = context;
  2091. return zones->zones[zone_number].thread_id;
  2092. }
  2093. /**
  2094. * vdo_make_hash_zones() - Create the hash zones.
  2095. *
  2096. * @vdo: The vdo to which the zone will belong.
  2097. * @zones_ptr: A pointer to hold the zones.
  2098. *
  2099. * Return: VDO_SUCCESS or an error code.
  2100. */
  2101. int vdo_make_hash_zones(struct vdo *vdo, struct hash_zones **zones_ptr)
  2102. {
  2103. int result;
  2104. struct hash_zones *zones;
  2105. zone_count_t z;
  2106. zone_count_t zone_count = vdo->thread_config.hash_zone_count;
  2107. if (zone_count == 0)
  2108. return VDO_SUCCESS;
  2109. result = vdo_allocate_extended(struct hash_zones, zone_count, struct hash_zone,
  2110. __func__, &zones);
  2111. if (result != VDO_SUCCESS)
  2112. return result;
  2113. result = initialize_index(vdo, zones);
  2114. if (result != VDO_SUCCESS) {
  2115. vdo_free(zones);
  2116. return result;
  2117. }
  2118. vdo_set_admin_state_code(&zones->state, VDO_ADMIN_STATE_NEW);
  2119. zones->zone_count = zone_count;
  2120. for (z = 0; z < zone_count; z++) {
  2121. result = initialize_zone(vdo, zones, z);
  2122. if (result != VDO_SUCCESS) {
  2123. vdo_free_hash_zones(zones);
  2124. return result;
  2125. }
  2126. }
  2127. result = vdo_make_action_manager(zones->zone_count, get_thread_id_for_zone,
  2128. vdo->thread_config.admin_thread, zones, NULL,
  2129. vdo, &zones->manager);
  2130. if (result != VDO_SUCCESS) {
  2131. vdo_free_hash_zones(zones);
  2132. return result;
  2133. }
  2134. *zones_ptr = zones;
  2135. return VDO_SUCCESS;
  2136. }
  2137. void vdo_finish_dedupe_index(struct hash_zones *zones)
  2138. {
  2139. if (zones == NULL)
  2140. return;
  2141. uds_destroy_index_session(vdo_forget(zones->index_session));
  2142. }
  2143. /**
  2144. * vdo_free_hash_zones() - Free the hash zones.
  2145. * @zones: The zone to free.
  2146. */
  2147. void vdo_free_hash_zones(struct hash_zones *zones)
  2148. {
  2149. zone_count_t i;
  2150. if (zones == NULL)
  2151. return;
  2152. vdo_free(vdo_forget(zones->manager));
  2153. for (i = 0; i < zones->zone_count; i++) {
  2154. struct hash_zone *zone = &zones->zones[i];
  2155. vdo_free_funnel_queue(vdo_forget(zone->timed_out_complete));
  2156. vdo_int_map_free(vdo_forget(zone->hash_lock_map));
  2157. vdo_free(vdo_forget(zone->lock_array));
  2158. }
  2159. if (zones->index_session != NULL)
  2160. vdo_finish_dedupe_index(zones);
  2161. ratelimit_state_exit(&zones->ratelimiter);
  2162. vdo_free(zones);
  2163. }
  2164. static void initiate_suspend_index(struct admin_state *state)
  2165. {
  2166. struct hash_zones *zones = container_of(state, struct hash_zones, state);
  2167. enum index_state index_state;
  2168. spin_lock(&zones->lock);
  2169. index_state = zones->index_state;
  2170. spin_unlock(&zones->lock);
  2171. if (index_state != IS_CLOSED) {
  2172. bool save = vdo_is_state_saving(&zones->state);
  2173. int result;
  2174. result = uds_suspend_index_session(zones->index_session, save);
  2175. if (result != UDS_SUCCESS)
  2176. vdo_log_error_strerror(result, "Error suspending dedupe index");
  2177. }
  2178. vdo_finish_draining(state);
  2179. }
  2180. /**
  2181. * suspend_index() - Suspend the UDS index prior to draining hash zones.
  2182. *
  2183. * Implements vdo_action_preamble_fn
  2184. */
  2185. static void suspend_index(void *context, struct vdo_completion *completion)
  2186. {
  2187. struct hash_zones *zones = context;
  2188. vdo_start_draining(&zones->state,
  2189. vdo_get_current_manager_operation(zones->manager), completion,
  2190. initiate_suspend_index);
  2191. }
  2192. /**
  2193. * initiate_drain() - Initiate a drain.
  2194. *
  2195. * Implements vdo_admin_initiator_fn.
  2196. */
  2197. static void initiate_drain(struct admin_state *state)
  2198. {
  2199. check_for_drain_complete(container_of(state, struct hash_zone, state));
  2200. }
  2201. /**
  2202. * drain_hash_zone() - Drain a hash zone.
  2203. *
  2204. * Implements vdo_zone_action_fn.
  2205. */
  2206. static void drain_hash_zone(void *context, zone_count_t zone_number,
  2207. struct vdo_completion *parent)
  2208. {
  2209. struct hash_zones *zones = context;
  2210. vdo_start_draining(&zones->zones[zone_number].state,
  2211. vdo_get_current_manager_operation(zones->manager), parent,
  2212. initiate_drain);
  2213. }
  2214. /** vdo_drain_hash_zones() - Drain all hash zones. */
  2215. void vdo_drain_hash_zones(struct hash_zones *zones, struct vdo_completion *parent)
  2216. {
  2217. vdo_schedule_operation(zones->manager, parent->vdo->suspend_type, suspend_index,
  2218. drain_hash_zone, NULL, parent);
  2219. }
  2220. static void launch_dedupe_state_change(struct hash_zones *zones)
  2221. __must_hold(&zones->lock)
  2222. {
  2223. /* ASSERTION: We enter with the lock held. */
  2224. if (zones->changing || !vdo_is_state_normal(&zones->state))
  2225. /* Either a change is already in progress, or changes are not allowed. */
  2226. return;
  2227. if (zones->create_flag || (zones->index_state != zones->index_target)) {
  2228. zones->changing = true;
  2229. vdo_launch_completion(&zones->completion);
  2230. return;
  2231. }
  2232. /* ASSERTION: We exit with the lock held. */
  2233. }
  2234. /**
  2235. * resume_index() - Resume the UDS index prior to resuming hash zones.
  2236. *
  2237. * Implements vdo_action_preamble_fn
  2238. */
  2239. static void resume_index(void *context, struct vdo_completion *parent)
  2240. {
  2241. struct hash_zones *zones = context;
  2242. struct device_config *config = parent->vdo->device_config;
  2243. int result;
  2244. zones->parameters.bdev = config->owned_device->bdev;
  2245. result = uds_resume_index_session(zones->index_session, zones->parameters.bdev);
  2246. if (result != UDS_SUCCESS)
  2247. vdo_log_error_strerror(result, "Error resuming dedupe index");
  2248. spin_lock(&zones->lock);
  2249. vdo_resume_if_quiescent(&zones->state);
  2250. if (config->deduplication) {
  2251. zones->index_target = IS_OPENED;
  2252. WRITE_ONCE(zones->dedupe_flag, true);
  2253. } else {
  2254. zones->index_target = IS_CLOSED;
  2255. }
  2256. launch_dedupe_state_change(zones);
  2257. spin_unlock(&zones->lock);
  2258. vdo_finish_completion(parent);
  2259. }
  2260. /**
  2261. * resume_hash_zone() - Resume a hash zone.
  2262. *
  2263. * Implements vdo_zone_action_fn.
  2264. */
  2265. static void resume_hash_zone(void *context, zone_count_t zone_number,
  2266. struct vdo_completion *parent)
  2267. {
  2268. struct hash_zone *zone = &(((struct hash_zones *) context)->zones[zone_number]);
  2269. vdo_fail_completion(parent, vdo_resume_if_quiescent(&zone->state));
  2270. }
  2271. /**
  2272. * vdo_resume_hash_zones() - Resume a set of hash zones.
  2273. * @zones: The hash zones to resume.
  2274. * @parent: The object to notify when the zones have resumed.
  2275. */
  2276. void vdo_resume_hash_zones(struct hash_zones *zones, struct vdo_completion *parent)
  2277. {
  2278. if (vdo_is_read_only(parent->vdo)) {
  2279. vdo_launch_completion(parent);
  2280. return;
  2281. }
  2282. vdo_schedule_operation(zones->manager, VDO_ADMIN_STATE_RESUMING, resume_index,
  2283. resume_hash_zone, NULL, parent);
  2284. }
  2285. /**
  2286. * get_hash_zone_statistics() - Add the statistics for this hash zone to the tally for all zones.
  2287. * @zone: The hash zone to query.
  2288. * @tally: The tally
  2289. */
  2290. static void get_hash_zone_statistics(const struct hash_zone *zone,
  2291. struct hash_lock_statistics *tally)
  2292. {
  2293. const struct hash_lock_statistics *stats = &zone->statistics;
  2294. tally->dedupe_advice_valid += READ_ONCE(stats->dedupe_advice_valid);
  2295. tally->dedupe_advice_stale += READ_ONCE(stats->dedupe_advice_stale);
  2296. tally->concurrent_data_matches += READ_ONCE(stats->concurrent_data_matches);
  2297. tally->concurrent_hash_collisions += READ_ONCE(stats->concurrent_hash_collisions);
  2298. tally->curr_dedupe_queries += READ_ONCE(zone->active);
  2299. }
  2300. static void get_index_statistics(struct hash_zones *zones,
  2301. struct index_statistics *stats)
  2302. {
  2303. enum index_state state;
  2304. struct uds_index_stats index_stats;
  2305. int result;
  2306. spin_lock(&zones->lock);
  2307. state = zones->index_state;
  2308. spin_unlock(&zones->lock);
  2309. if (state != IS_OPENED)
  2310. return;
  2311. result = uds_get_index_session_stats(zones->index_session, &index_stats);
  2312. if (result != UDS_SUCCESS) {
  2313. vdo_log_error_strerror(result, "Error reading index stats");
  2314. return;
  2315. }
  2316. stats->entries_indexed = index_stats.entries_indexed;
  2317. stats->posts_found = index_stats.posts_found;
  2318. stats->posts_not_found = index_stats.posts_not_found;
  2319. stats->queries_found = index_stats.queries_found;
  2320. stats->queries_not_found = index_stats.queries_not_found;
  2321. stats->updates_found = index_stats.updates_found;
  2322. stats->updates_not_found = index_stats.updates_not_found;
  2323. stats->entries_discarded = index_stats.entries_discarded;
  2324. }
  2325. /**
  2326. * vdo_get_dedupe_statistics() - Tally the statistics from all the hash zones and the UDS index.
  2327. * @hash_zones: The hash zones to query
  2328. *
  2329. * Return: The sum of the hash lock statistics from all hash zones plus the statistics from the UDS
  2330. * index
  2331. */
  2332. void vdo_get_dedupe_statistics(struct hash_zones *zones, struct vdo_statistics *stats)
  2333. {
  2334. zone_count_t zone;
  2335. for (zone = 0; zone < zones->zone_count; zone++)
  2336. get_hash_zone_statistics(&zones->zones[zone], &stats->hash_lock);
  2337. get_index_statistics(zones, &stats->index);
  2338. /*
  2339. * zones->timeouts gives the number of timeouts, and dedupe_context_busy gives the number
  2340. * of queries not made because of earlier timeouts.
  2341. */
  2342. stats->dedupe_advice_timeouts =
  2343. (atomic64_read(&zones->timeouts) + atomic64_read(&zones->dedupe_context_busy));
  2344. }
  2345. /**
  2346. * vdo_select_hash_zone() - Select the hash zone responsible for locking a given record name.
  2347. * @zones: The hash_zones from which to select.
  2348. * @name: The record name.
  2349. *
  2350. * Return: The hash zone responsible for the record name.
  2351. */
  2352. struct hash_zone *vdo_select_hash_zone(struct hash_zones *zones,
  2353. const struct uds_record_name *name)
  2354. {
  2355. /*
  2356. * Use a fragment of the record name as a hash code. Eight bits of hash should suffice
  2357. * since the number of hash zones is small.
  2358. * TODO: Verify that the first byte is independent enough.
  2359. */
  2360. u32 hash = name->name[0];
  2361. /*
  2362. * Scale the 8-bit hash fragment to a zone index by treating it as a binary fraction and
  2363. * multiplying that by the zone count. If the hash is uniformly distributed over [0 ..
  2364. * 2^8-1], then (hash * count / 2^8) should be uniformly distributed over [0 .. count-1].
  2365. * The multiply and shift is much faster than a divide (modulus) on X86 CPUs.
  2366. */
  2367. hash = (hash * zones->zone_count) >> 8;
  2368. return &zones->zones[hash];
  2369. }
  2370. /**
  2371. * dump_hash_lock() - Dump a compact description of hash_lock to the log if the lock is not on the
  2372. * free list.
  2373. * @lock: The hash lock to dump.
  2374. */
  2375. static void dump_hash_lock(const struct hash_lock *lock)
  2376. {
  2377. const char *state;
  2378. if (!list_empty(&lock->pool_node)) {
  2379. /* This lock is on the free list. */
  2380. return;
  2381. }
  2382. /*
  2383. * Necessarily cryptic since we can log a lot of these. First three chars of state is
  2384. * unambiguous. 'U' indicates a lock not registered in the map.
  2385. */
  2386. state = get_hash_lock_state_name(lock->state);
  2387. vdo_log_info(" hl %px: %3.3s %c%llu/%u rc=%u wc=%zu agt=%px",
  2388. lock, state, (lock->registered ? 'D' : 'U'),
  2389. (unsigned long long) lock->duplicate.pbn,
  2390. lock->duplicate.state, lock->reference_count,
  2391. vdo_waitq_num_waiters(&lock->waiters), lock->agent);
  2392. }
  2393. static const char *index_state_to_string(struct hash_zones *zones,
  2394. enum index_state state)
  2395. {
  2396. if (!vdo_is_state_normal(&zones->state))
  2397. return SUSPENDED;
  2398. switch (state) {
  2399. case IS_CLOSED:
  2400. return zones->error_flag ? ERROR : CLOSED;
  2401. case IS_CHANGING:
  2402. return zones->index_target == IS_OPENED ? OPENING : CLOSING;
  2403. case IS_OPENED:
  2404. return READ_ONCE(zones->dedupe_flag) ? ONLINE : OFFLINE;
  2405. default:
  2406. return UNKNOWN;
  2407. }
  2408. }
  2409. /**
  2410. * dump_hash_zone() - Dump information about a hash zone to the log for debugging.
  2411. * @zone: The zone to dump.
  2412. */
  2413. static void dump_hash_zone(const struct hash_zone *zone)
  2414. {
  2415. data_vio_count_t i;
  2416. if (zone->hash_lock_map == NULL) {
  2417. vdo_log_info("struct hash_zone %u: NULL map", zone->zone_number);
  2418. return;
  2419. }
  2420. vdo_log_info("struct hash_zone %u: mapSize=%zu",
  2421. zone->zone_number, vdo_int_map_size(zone->hash_lock_map));
  2422. for (i = 0; i < LOCK_POOL_CAPACITY; i++)
  2423. dump_hash_lock(&zone->lock_array[i]);
  2424. }
  2425. /**
  2426. * vdo_dump_hash_zones() - Dump information about the hash zones to the log for debugging.
  2427. * @zones: The zones to dump.
  2428. */
  2429. void vdo_dump_hash_zones(struct hash_zones *zones)
  2430. {
  2431. const char *state, *target;
  2432. zone_count_t zone;
  2433. spin_lock(&zones->lock);
  2434. state = index_state_to_string(zones, zones->index_state);
  2435. target = (zones->changing ? index_state_to_string(zones, zones->index_target) : NULL);
  2436. spin_unlock(&zones->lock);
  2437. vdo_log_info("UDS index: state: %s", state);
  2438. if (target != NULL)
  2439. vdo_log_info("UDS index: changing to state: %s", target);
  2440. for (zone = 0; zone < zones->zone_count; zone++)
  2441. dump_hash_zone(&zones->zones[zone]);
  2442. }
  2443. void vdo_set_dedupe_index_timeout_interval(unsigned int value)
  2444. {
  2445. u64 alb_jiffies;
  2446. /* Arbitrary maximum value is two minutes */
  2447. if (value > 120000)
  2448. value = 120000;
  2449. /* Arbitrary minimum value is 2 jiffies */
  2450. alb_jiffies = msecs_to_jiffies(value);
  2451. if (alb_jiffies < 2) {
  2452. alb_jiffies = 2;
  2453. value = jiffies_to_msecs(alb_jiffies);
  2454. }
  2455. vdo_dedupe_index_timeout_interval = value;
  2456. vdo_dedupe_index_timeout_jiffies = alb_jiffies;
  2457. }
  2458. void vdo_set_dedupe_index_min_timer_interval(unsigned int value)
  2459. {
  2460. u64 min_jiffies;
  2461. /* Arbitrary maximum value is one second */
  2462. if (value > 1000)
  2463. value = 1000;
  2464. /* Arbitrary minimum value is 2 jiffies */
  2465. min_jiffies = msecs_to_jiffies(value);
  2466. if (min_jiffies < 2) {
  2467. min_jiffies = 2;
  2468. value = jiffies_to_msecs(min_jiffies);
  2469. }
  2470. vdo_dedupe_index_min_timer_interval = value;
  2471. vdo_dedupe_index_min_timer_jiffies = min_jiffies;
  2472. }
  2473. /**
  2474. * acquire_context() - Acquire a dedupe context from a hash_zone if any are available.
  2475. * @zone: the hash zone
  2476. *
  2477. * Return: A dedupe_context or NULL if none are available
  2478. */
  2479. static struct dedupe_context * __must_check acquire_context(struct hash_zone *zone)
  2480. {
  2481. struct dedupe_context *context;
  2482. struct funnel_queue_entry *entry;
  2483. assert_in_hash_zone(zone, __func__);
  2484. if (!list_empty(&zone->available)) {
  2485. WRITE_ONCE(zone->active, zone->active + 1);
  2486. context = list_first_entry(&zone->available, struct dedupe_context,
  2487. list_entry);
  2488. list_del_init(&context->list_entry);
  2489. return context;
  2490. }
  2491. entry = vdo_funnel_queue_poll(zone->timed_out_complete);
  2492. return ((entry == NULL) ?
  2493. NULL : container_of(entry, struct dedupe_context, queue_entry));
  2494. }
  2495. static void prepare_uds_request(struct uds_request *request, struct data_vio *data_vio,
  2496. enum uds_request_type operation)
  2497. {
  2498. request->record_name = data_vio->record_name;
  2499. request->type = operation;
  2500. if ((operation == UDS_POST) || (operation == UDS_UPDATE)) {
  2501. size_t offset = 0;
  2502. struct uds_record_data *encoding = &request->new_metadata;
  2503. encoding->data[offset++] = UDS_ADVICE_VERSION;
  2504. encoding->data[offset++] = data_vio->new_mapped.state;
  2505. put_unaligned_le64(data_vio->new_mapped.pbn, &encoding->data[offset]);
  2506. offset += sizeof(u64);
  2507. BUG_ON(offset != UDS_ADVICE_SIZE);
  2508. }
  2509. }
  2510. /*
  2511. * The index operation will inquire about data_vio.record_name, providing (if the operation is
  2512. * appropriate) advice from the data_vio's new_mapped fields. The advice found in the index (or
  2513. * NULL if none) will be returned via receive_data_vio_dedupe_advice(). dedupe_context.status is
  2514. * set to the return status code of any asynchronous index processing.
  2515. */
  2516. static void query_index(struct data_vio *data_vio, enum uds_request_type operation)
  2517. {
  2518. int result;
  2519. struct dedupe_context *context;
  2520. struct vdo *vdo = vdo_from_data_vio(data_vio);
  2521. struct hash_zone *zone = data_vio->hash_zone;
  2522. assert_data_vio_in_hash_zone(data_vio);
  2523. if (!READ_ONCE(vdo->hash_zones->dedupe_flag)) {
  2524. continue_data_vio(data_vio);
  2525. return;
  2526. }
  2527. context = acquire_context(zone);
  2528. if (context == NULL) {
  2529. atomic64_inc(&vdo->hash_zones->dedupe_context_busy);
  2530. continue_data_vio(data_vio);
  2531. return;
  2532. }
  2533. data_vio->dedupe_context = context;
  2534. context->requestor = data_vio;
  2535. context->submission_jiffies = jiffies;
  2536. prepare_uds_request(&context->request, data_vio, operation);
  2537. atomic_set(&context->state, DEDUPE_CONTEXT_PENDING);
  2538. list_add_tail(&context->list_entry, &zone->pending);
  2539. start_expiration_timer(context);
  2540. result = uds_launch_request(&context->request);
  2541. if (result != UDS_SUCCESS) {
  2542. context->request.status = result;
  2543. finish_index_operation(&context->request);
  2544. }
  2545. }
  2546. static void set_target_state(struct hash_zones *zones, enum index_state target,
  2547. bool change_dedupe, bool dedupe, bool set_create)
  2548. {
  2549. const char *old_state, *new_state;
  2550. spin_lock(&zones->lock);
  2551. old_state = index_state_to_string(zones, zones->index_target);
  2552. if (change_dedupe)
  2553. WRITE_ONCE(zones->dedupe_flag, dedupe);
  2554. if (set_create)
  2555. zones->create_flag = true;
  2556. zones->index_target = target;
  2557. launch_dedupe_state_change(zones);
  2558. new_state = index_state_to_string(zones, zones->index_target);
  2559. spin_unlock(&zones->lock);
  2560. if (old_state != new_state)
  2561. vdo_log_info("Setting UDS index target state to %s", new_state);
  2562. }
  2563. const char *vdo_get_dedupe_index_state_name(struct hash_zones *zones)
  2564. {
  2565. const char *state;
  2566. spin_lock(&zones->lock);
  2567. state = index_state_to_string(zones, zones->index_state);
  2568. spin_unlock(&zones->lock);
  2569. return state;
  2570. }
  2571. /* Handle a dmsetup message relevant to the index. */
  2572. int vdo_message_dedupe_index(struct hash_zones *zones, const char *name)
  2573. {
  2574. if (strcasecmp(name, "index-close") == 0) {
  2575. set_target_state(zones, IS_CLOSED, false, false, false);
  2576. return 0;
  2577. } else if (strcasecmp(name, "index-create") == 0) {
  2578. set_target_state(zones, IS_OPENED, false, false, true);
  2579. return 0;
  2580. } else if (strcasecmp(name, "index-disable") == 0) {
  2581. set_target_state(zones, IS_OPENED, true, false, false);
  2582. return 0;
  2583. } else if (strcasecmp(name, "index-enable") == 0) {
  2584. set_target_state(zones, IS_OPENED, true, true, false);
  2585. return 0;
  2586. }
  2587. return -EINVAL;
  2588. }
  2589. void vdo_set_dedupe_state_normal(struct hash_zones *zones)
  2590. {
  2591. vdo_set_admin_state_code(&zones->state, VDO_ADMIN_STATE_NORMAL_OPERATION);
  2592. }
  2593. /* If create_flag, create a new index without first attempting to load an existing index. */
  2594. void vdo_start_dedupe_index(struct hash_zones *zones, bool create_flag)
  2595. {
  2596. set_target_state(zones, IS_OPENED, true, true, create_flag);
  2597. }