dm-bufio.c 71 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. /*
  3. * Copyright (C) 2009-2011 Red Hat, Inc.
  4. *
  5. * Author: Mikulas Patocka <mpatocka@redhat.com>
  6. *
  7. * This file is released under the GPL.
  8. */
  9. #include <linux/dm-bufio.h>
  10. #include <linux/device-mapper.h>
  11. #include <linux/dm-io.h>
  12. #include <linux/slab.h>
  13. #include <linux/sched/mm.h>
  14. #include <linux/jiffies.h>
  15. #include <linux/vmalloc.h>
  16. #include <linux/shrinker.h>
  17. #include <linux/module.h>
  18. #include <linux/rbtree.h>
  19. #include <linux/stacktrace.h>
  20. #include <linux/jump_label.h>
  21. #include "dm.h"
  22. #define DM_MSG_PREFIX "bufio"
  23. /*
  24. * Memory management policy:
  25. * Limit the number of buffers to DM_BUFIO_MEMORY_PERCENT of main memory
  26. * or DM_BUFIO_VMALLOC_PERCENT of vmalloc memory (whichever is lower).
  27. * Always allocate at least DM_BUFIO_MIN_BUFFERS buffers.
  28. * Start background writeback when there are DM_BUFIO_WRITEBACK_PERCENT
  29. * dirty buffers.
  30. */
  31. #define DM_BUFIO_MIN_BUFFERS 8
  32. #define DM_BUFIO_MEMORY_PERCENT 2
  33. #define DM_BUFIO_VMALLOC_PERCENT 25
  34. #define DM_BUFIO_WRITEBACK_RATIO 3
  35. #define DM_BUFIO_LOW_WATERMARK_RATIO 16
  36. /*
  37. * Check buffer ages in this interval (seconds)
  38. */
  39. #define DM_BUFIO_WORK_TIMER_SECS 30
  40. /*
  41. * Free buffers when they are older than this (seconds)
  42. */
  43. #define DM_BUFIO_DEFAULT_AGE_SECS 300
  44. /*
  45. * The nr of bytes of cached data to keep around.
  46. */
  47. #define DM_BUFIO_DEFAULT_RETAIN_BYTES (256 * 1024)
  48. /*
  49. * Align buffer writes to this boundary.
  50. * Tests show that SSDs have the highest IOPS when using 4k writes.
  51. */
  52. #define DM_BUFIO_WRITE_ALIGN 4096
  53. /*
  54. * dm_buffer->list_mode
  55. */
  56. #define LIST_CLEAN 0
  57. #define LIST_DIRTY 1
  58. #define LIST_SIZE 2
  59. #define SCAN_RESCHED_CYCLE 16
  60. /*--------------------------------------------------------------*/
  61. /*
  62. * Rather than use an LRU list, we use a clock algorithm where entries
  63. * are held in a circular list. When an entry is 'hit' a reference bit
  64. * is set. The least recently used entry is approximated by running a
  65. * cursor around the list selecting unreferenced entries. Referenced
  66. * entries have their reference bit cleared as the cursor passes them.
  67. */
  68. struct lru_entry {
  69. struct list_head list;
  70. atomic_t referenced;
  71. };
  72. struct lru_iter {
  73. struct lru *lru;
  74. struct list_head list;
  75. struct lru_entry *stop;
  76. struct lru_entry *e;
  77. };
  78. struct lru {
  79. struct list_head *cursor;
  80. unsigned long count;
  81. struct list_head iterators;
  82. };
  83. /*--------------*/
  84. static void lru_init(struct lru *lru)
  85. {
  86. lru->cursor = NULL;
  87. lru->count = 0;
  88. INIT_LIST_HEAD(&lru->iterators);
  89. }
  90. static void lru_destroy(struct lru *lru)
  91. {
  92. WARN_ON_ONCE(lru->cursor);
  93. WARN_ON_ONCE(!list_empty(&lru->iterators));
  94. }
  95. /*
  96. * Insert a new entry into the lru.
  97. */
  98. static void lru_insert(struct lru *lru, struct lru_entry *le)
  99. {
  100. /*
  101. * Don't be tempted to set to 1, makes the lru aspect
  102. * perform poorly.
  103. */
  104. atomic_set(&le->referenced, 0);
  105. if (lru->cursor) {
  106. list_add_tail(&le->list, lru->cursor);
  107. } else {
  108. INIT_LIST_HEAD(&le->list);
  109. lru->cursor = &le->list;
  110. }
  111. lru->count++;
  112. }
  113. /*--------------*/
  114. /*
  115. * Convert a list_head pointer to an lru_entry pointer.
  116. */
  117. static inline struct lru_entry *to_le(struct list_head *l)
  118. {
  119. return container_of(l, struct lru_entry, list);
  120. }
  121. /*
  122. * Initialize an lru_iter and add it to the list of cursors in the lru.
  123. */
  124. static void lru_iter_begin(struct lru *lru, struct lru_iter *it)
  125. {
  126. it->lru = lru;
  127. it->stop = lru->cursor ? to_le(lru->cursor->prev) : NULL;
  128. it->e = lru->cursor ? to_le(lru->cursor) : NULL;
  129. list_add(&it->list, &lru->iterators);
  130. }
  131. /*
  132. * Remove an lru_iter from the list of cursors in the lru.
  133. */
  134. static inline void lru_iter_end(struct lru_iter *it)
  135. {
  136. list_del(&it->list);
  137. }
  138. /* Predicate function type to be used with lru_iter_next */
  139. typedef bool (*iter_predicate)(struct lru_entry *le, void *context);
  140. /*
  141. * Advance the cursor to the next entry that passes the
  142. * predicate, and return that entry. Returns NULL if the
  143. * iteration is complete.
  144. */
  145. static struct lru_entry *lru_iter_next(struct lru_iter *it,
  146. iter_predicate pred, void *context)
  147. {
  148. struct lru_entry *e;
  149. while (it->e) {
  150. e = it->e;
  151. /* advance the cursor */
  152. if (it->e == it->stop)
  153. it->e = NULL;
  154. else
  155. it->e = to_le(it->e->list.next);
  156. if (pred(e, context))
  157. return e;
  158. }
  159. return NULL;
  160. }
  161. /*
  162. * Invalidate a specific lru_entry and update all cursors in
  163. * the lru accordingly.
  164. */
  165. static void lru_iter_invalidate(struct lru *lru, struct lru_entry *e)
  166. {
  167. struct lru_iter *it;
  168. list_for_each_entry(it, &lru->iterators, list) {
  169. /* Move c->e forwards if necc. */
  170. if (it->e == e) {
  171. it->e = to_le(it->e->list.next);
  172. if (it->e == e)
  173. it->e = NULL;
  174. }
  175. /* Move it->stop backwards if necc. */
  176. if (it->stop == e) {
  177. it->stop = to_le(it->stop->list.prev);
  178. if (it->stop == e)
  179. it->stop = NULL;
  180. }
  181. }
  182. }
  183. /*--------------*/
  184. /*
  185. * Remove a specific entry from the lru.
  186. */
  187. static void lru_remove(struct lru *lru, struct lru_entry *le)
  188. {
  189. lru_iter_invalidate(lru, le);
  190. if (lru->count == 1) {
  191. lru->cursor = NULL;
  192. } else {
  193. if (lru->cursor == &le->list)
  194. lru->cursor = lru->cursor->next;
  195. list_del(&le->list);
  196. }
  197. lru->count--;
  198. }
  199. /*
  200. * Mark as referenced.
  201. */
  202. static inline void lru_reference(struct lru_entry *le)
  203. {
  204. atomic_set(&le->referenced, 1);
  205. }
  206. /*--------------*/
  207. /*
  208. * Remove the least recently used entry (approx), that passes the predicate.
  209. * Returns NULL on failure.
  210. */
  211. enum evict_result {
  212. ER_EVICT,
  213. ER_DONT_EVICT,
  214. ER_STOP, /* stop looking for something to evict */
  215. };
  216. typedef enum evict_result (*le_predicate)(struct lru_entry *le, void *context);
  217. static struct lru_entry *lru_evict(struct lru *lru, le_predicate pred, void *context, bool no_sleep)
  218. {
  219. unsigned long tested = 0;
  220. struct list_head *h = lru->cursor;
  221. struct lru_entry *le;
  222. if (!h)
  223. return NULL;
  224. /*
  225. * In the worst case we have to loop around twice. Once to clear
  226. * the reference flags, and then again to discover the predicate
  227. * fails for all entries.
  228. */
  229. while (tested < lru->count) {
  230. le = container_of(h, struct lru_entry, list);
  231. if (atomic_read(&le->referenced)) {
  232. atomic_set(&le->referenced, 0);
  233. } else {
  234. tested++;
  235. switch (pred(le, context)) {
  236. case ER_EVICT:
  237. /*
  238. * Adjust the cursor, so we start the next
  239. * search from here.
  240. */
  241. lru->cursor = le->list.next;
  242. lru_remove(lru, le);
  243. return le;
  244. case ER_DONT_EVICT:
  245. break;
  246. case ER_STOP:
  247. lru->cursor = le->list.next;
  248. return NULL;
  249. }
  250. }
  251. h = h->next;
  252. if (!no_sleep)
  253. cond_resched();
  254. }
  255. return NULL;
  256. }
  257. /*--------------------------------------------------------------*/
  258. /*
  259. * Buffer state bits.
  260. */
  261. #define B_READING 0
  262. #define B_WRITING 1
  263. #define B_DIRTY 2
  264. /*
  265. * Describes how the block was allocated:
  266. * kmem_cache_alloc(), __get_free_pages() or vmalloc().
  267. * See the comment at alloc_buffer_data.
  268. */
  269. enum data_mode {
  270. DATA_MODE_SLAB = 0,
  271. DATA_MODE_GET_FREE_PAGES = 1,
  272. DATA_MODE_VMALLOC = 2,
  273. DATA_MODE_LIMIT = 3
  274. };
  275. struct dm_buffer {
  276. /* protected by the locks in dm_buffer_cache */
  277. struct rb_node node;
  278. /* immutable, so don't need protecting */
  279. sector_t block;
  280. void *data;
  281. unsigned char data_mode; /* DATA_MODE_* */
  282. /*
  283. * These two fields are used in isolation, so do not need
  284. * a surrounding lock.
  285. */
  286. atomic_t hold_count;
  287. unsigned long last_accessed;
  288. /*
  289. * Everything else is protected by the mutex in
  290. * dm_bufio_client
  291. */
  292. unsigned long state;
  293. struct lru_entry lru;
  294. unsigned char list_mode; /* LIST_* */
  295. blk_status_t read_error;
  296. blk_status_t write_error;
  297. unsigned int dirty_start;
  298. unsigned int dirty_end;
  299. unsigned int write_start;
  300. unsigned int write_end;
  301. struct list_head write_list;
  302. struct dm_bufio_client *c;
  303. void (*end_io)(struct dm_buffer *b, blk_status_t bs);
  304. #ifdef CONFIG_DM_DEBUG_BLOCK_STACK_TRACING
  305. #define MAX_STACK 10
  306. unsigned int stack_len;
  307. unsigned long stack_entries[MAX_STACK];
  308. #endif
  309. };
  310. /*--------------------------------------------------------------*/
  311. /*
  312. * The buffer cache manages buffers, particularly:
  313. * - inc/dec of holder count
  314. * - setting the last_accessed field
  315. * - maintains clean/dirty state along with lru
  316. * - selecting buffers that match predicates
  317. *
  318. * It does *not* handle:
  319. * - allocation/freeing of buffers.
  320. * - IO
  321. * - Eviction or cache sizing.
  322. *
  323. * cache_get() and cache_put() are threadsafe, you do not need to
  324. * protect these calls with a surrounding mutex. All the other
  325. * methods are not threadsafe; they do use locking primitives, but
  326. * only enough to ensure get/put are threadsafe.
  327. */
  328. struct buffer_tree {
  329. union {
  330. struct rw_semaphore lock;
  331. rwlock_t spinlock;
  332. } u;
  333. struct rb_root root;
  334. } ____cacheline_aligned_in_smp;
  335. struct dm_buffer_cache {
  336. struct lru lru[LIST_SIZE];
  337. /*
  338. * We spread entries across multiple trees to reduce contention
  339. * on the locks.
  340. */
  341. unsigned int num_locks;
  342. bool no_sleep;
  343. struct buffer_tree trees[];
  344. };
  345. static DEFINE_STATIC_KEY_FALSE(no_sleep_enabled);
  346. static inline unsigned int cache_index(sector_t block, unsigned int num_locks)
  347. {
  348. return dm_hash_locks_index(block, num_locks);
  349. }
  350. static inline void cache_read_lock(struct dm_buffer_cache *bc, sector_t block)
  351. {
  352. if (static_branch_unlikely(&no_sleep_enabled) && bc->no_sleep)
  353. read_lock_bh(&bc->trees[cache_index(block, bc->num_locks)].u.spinlock);
  354. else
  355. down_read(&bc->trees[cache_index(block, bc->num_locks)].u.lock);
  356. }
  357. static inline void cache_read_unlock(struct dm_buffer_cache *bc, sector_t block)
  358. {
  359. if (static_branch_unlikely(&no_sleep_enabled) && bc->no_sleep)
  360. read_unlock_bh(&bc->trees[cache_index(block, bc->num_locks)].u.spinlock);
  361. else
  362. up_read(&bc->trees[cache_index(block, bc->num_locks)].u.lock);
  363. }
  364. static inline void cache_write_lock(struct dm_buffer_cache *bc, sector_t block)
  365. {
  366. if (static_branch_unlikely(&no_sleep_enabled) && bc->no_sleep)
  367. write_lock_bh(&bc->trees[cache_index(block, bc->num_locks)].u.spinlock);
  368. else
  369. down_write(&bc->trees[cache_index(block, bc->num_locks)].u.lock);
  370. }
  371. static inline void cache_write_unlock(struct dm_buffer_cache *bc, sector_t block)
  372. {
  373. if (static_branch_unlikely(&no_sleep_enabled) && bc->no_sleep)
  374. write_unlock_bh(&bc->trees[cache_index(block, bc->num_locks)].u.spinlock);
  375. else
  376. up_write(&bc->trees[cache_index(block, bc->num_locks)].u.lock);
  377. }
  378. /*
  379. * Sometimes we want to repeatedly get and drop locks as part of an iteration.
  380. * This struct helps avoid redundant drop and gets of the same lock.
  381. */
  382. struct lock_history {
  383. struct dm_buffer_cache *cache;
  384. bool write;
  385. unsigned int previous;
  386. unsigned int no_previous;
  387. };
  388. static void lh_init(struct lock_history *lh, struct dm_buffer_cache *cache, bool write)
  389. {
  390. lh->cache = cache;
  391. lh->write = write;
  392. lh->no_previous = cache->num_locks;
  393. lh->previous = lh->no_previous;
  394. }
  395. static void __lh_lock(struct lock_history *lh, unsigned int index)
  396. {
  397. if (lh->write) {
  398. if (static_branch_unlikely(&no_sleep_enabled) && lh->cache->no_sleep)
  399. write_lock_bh(&lh->cache->trees[index].u.spinlock);
  400. else
  401. down_write(&lh->cache->trees[index].u.lock);
  402. } else {
  403. if (static_branch_unlikely(&no_sleep_enabled) && lh->cache->no_sleep)
  404. read_lock_bh(&lh->cache->trees[index].u.spinlock);
  405. else
  406. down_read(&lh->cache->trees[index].u.lock);
  407. }
  408. }
  409. static void __lh_unlock(struct lock_history *lh, unsigned int index)
  410. {
  411. if (lh->write) {
  412. if (static_branch_unlikely(&no_sleep_enabled) && lh->cache->no_sleep)
  413. write_unlock_bh(&lh->cache->trees[index].u.spinlock);
  414. else
  415. up_write(&lh->cache->trees[index].u.lock);
  416. } else {
  417. if (static_branch_unlikely(&no_sleep_enabled) && lh->cache->no_sleep)
  418. read_unlock_bh(&lh->cache->trees[index].u.spinlock);
  419. else
  420. up_read(&lh->cache->trees[index].u.lock);
  421. }
  422. }
  423. /*
  424. * Make sure you call this since it will unlock the final lock.
  425. */
  426. static void lh_exit(struct lock_history *lh)
  427. {
  428. if (lh->previous != lh->no_previous) {
  429. __lh_unlock(lh, lh->previous);
  430. lh->previous = lh->no_previous;
  431. }
  432. }
  433. /*
  434. * Named 'next' because there is no corresponding
  435. * 'up/unlock' call since it's done automatically.
  436. */
  437. static void lh_next(struct lock_history *lh, sector_t b)
  438. {
  439. unsigned int index = cache_index(b, lh->no_previous); /* no_previous is num_locks */
  440. if (lh->previous != lh->no_previous) {
  441. if (lh->previous != index) {
  442. __lh_unlock(lh, lh->previous);
  443. __lh_lock(lh, index);
  444. lh->previous = index;
  445. }
  446. } else {
  447. __lh_lock(lh, index);
  448. lh->previous = index;
  449. }
  450. }
  451. static inline struct dm_buffer *le_to_buffer(struct lru_entry *le)
  452. {
  453. return container_of(le, struct dm_buffer, lru);
  454. }
  455. static struct dm_buffer *list_to_buffer(struct list_head *l)
  456. {
  457. struct lru_entry *le = list_entry(l, struct lru_entry, list);
  458. return le_to_buffer(le);
  459. }
  460. static void cache_init(struct dm_buffer_cache *bc, unsigned int num_locks, bool no_sleep)
  461. {
  462. unsigned int i;
  463. bc->num_locks = num_locks;
  464. bc->no_sleep = no_sleep;
  465. for (i = 0; i < bc->num_locks; i++) {
  466. if (no_sleep)
  467. rwlock_init(&bc->trees[i].u.spinlock);
  468. else
  469. init_rwsem(&bc->trees[i].u.lock);
  470. bc->trees[i].root = RB_ROOT;
  471. }
  472. lru_init(&bc->lru[LIST_CLEAN]);
  473. lru_init(&bc->lru[LIST_DIRTY]);
  474. }
  475. static void cache_destroy(struct dm_buffer_cache *bc)
  476. {
  477. unsigned int i;
  478. for (i = 0; i < bc->num_locks; i++)
  479. WARN_ON_ONCE(!RB_EMPTY_ROOT(&bc->trees[i].root));
  480. lru_destroy(&bc->lru[LIST_CLEAN]);
  481. lru_destroy(&bc->lru[LIST_DIRTY]);
  482. }
  483. /*--------------*/
  484. /*
  485. * not threadsafe, or racey depending how you look at it
  486. */
  487. static inline unsigned long cache_count(struct dm_buffer_cache *bc, int list_mode)
  488. {
  489. return bc->lru[list_mode].count;
  490. }
  491. static inline unsigned long cache_total(struct dm_buffer_cache *bc)
  492. {
  493. return cache_count(bc, LIST_CLEAN) + cache_count(bc, LIST_DIRTY);
  494. }
  495. /*--------------*/
  496. /*
  497. * Gets a specific buffer, indexed by block.
  498. * If the buffer is found then its holder count will be incremented and
  499. * lru_reference will be called.
  500. *
  501. * threadsafe
  502. */
  503. static struct dm_buffer *__cache_get(const struct rb_root *root, sector_t block)
  504. {
  505. struct rb_node *n = root->rb_node;
  506. struct dm_buffer *b;
  507. while (n) {
  508. b = container_of(n, struct dm_buffer, node);
  509. if (b->block == block)
  510. return b;
  511. n = block < b->block ? n->rb_left : n->rb_right;
  512. }
  513. return NULL;
  514. }
  515. static void __cache_inc_buffer(struct dm_buffer *b)
  516. {
  517. atomic_inc(&b->hold_count);
  518. WRITE_ONCE(b->last_accessed, jiffies);
  519. }
  520. static struct dm_buffer *cache_get(struct dm_buffer_cache *bc, sector_t block)
  521. {
  522. struct dm_buffer *b;
  523. cache_read_lock(bc, block);
  524. b = __cache_get(&bc->trees[cache_index(block, bc->num_locks)].root, block);
  525. if (b) {
  526. lru_reference(&b->lru);
  527. __cache_inc_buffer(b);
  528. }
  529. cache_read_unlock(bc, block);
  530. return b;
  531. }
  532. /*--------------*/
  533. /*
  534. * Returns true if the hold count hits zero.
  535. * threadsafe
  536. */
  537. static bool cache_put(struct dm_buffer_cache *bc, struct dm_buffer *b)
  538. {
  539. bool r;
  540. cache_read_lock(bc, b->block);
  541. BUG_ON(!atomic_read(&b->hold_count));
  542. r = atomic_dec_and_test(&b->hold_count);
  543. cache_read_unlock(bc, b->block);
  544. return r;
  545. }
  546. /*--------------*/
  547. typedef enum evict_result (*b_predicate)(struct dm_buffer *, void *);
  548. /*
  549. * Evicts a buffer based on a predicate. The oldest buffer that
  550. * matches the predicate will be selected. In addition to the
  551. * predicate the hold_count of the selected buffer will be zero.
  552. */
  553. struct evict_wrapper {
  554. struct lock_history *lh;
  555. b_predicate pred;
  556. void *context;
  557. };
  558. /*
  559. * Wraps the buffer predicate turning it into an lru predicate. Adds
  560. * extra test for hold_count.
  561. */
  562. static enum evict_result __evict_pred(struct lru_entry *le, void *context)
  563. {
  564. struct evict_wrapper *w = context;
  565. struct dm_buffer *b = le_to_buffer(le);
  566. lh_next(w->lh, b->block);
  567. if (atomic_read(&b->hold_count))
  568. return ER_DONT_EVICT;
  569. return w->pred(b, w->context);
  570. }
  571. static struct dm_buffer *__cache_evict(struct dm_buffer_cache *bc, int list_mode,
  572. b_predicate pred, void *context,
  573. struct lock_history *lh)
  574. {
  575. struct evict_wrapper w = {.lh = lh, .pred = pred, .context = context};
  576. struct lru_entry *le;
  577. struct dm_buffer *b;
  578. le = lru_evict(&bc->lru[list_mode], __evict_pred, &w, bc->no_sleep);
  579. if (!le)
  580. return NULL;
  581. b = le_to_buffer(le);
  582. /* __evict_pred will have locked the appropriate tree. */
  583. rb_erase(&b->node, &bc->trees[cache_index(b->block, bc->num_locks)].root);
  584. return b;
  585. }
  586. static struct dm_buffer *cache_evict(struct dm_buffer_cache *bc, int list_mode,
  587. b_predicate pred, void *context)
  588. {
  589. struct dm_buffer *b;
  590. struct lock_history lh;
  591. lh_init(&lh, bc, true);
  592. b = __cache_evict(bc, list_mode, pred, context, &lh);
  593. lh_exit(&lh);
  594. return b;
  595. }
  596. /*--------------*/
  597. /*
  598. * Mark a buffer as clean or dirty. Not threadsafe.
  599. */
  600. static void cache_mark(struct dm_buffer_cache *bc, struct dm_buffer *b, int list_mode)
  601. {
  602. cache_write_lock(bc, b->block);
  603. if (list_mode != b->list_mode) {
  604. lru_remove(&bc->lru[b->list_mode], &b->lru);
  605. b->list_mode = list_mode;
  606. lru_insert(&bc->lru[b->list_mode], &b->lru);
  607. }
  608. cache_write_unlock(bc, b->block);
  609. }
  610. /*--------------*/
  611. /*
  612. * Runs through the lru associated with 'old_mode', if the predicate matches then
  613. * it moves them to 'new_mode'. Not threadsafe.
  614. */
  615. static void __cache_mark_many(struct dm_buffer_cache *bc, int old_mode, int new_mode,
  616. b_predicate pred, void *context, struct lock_history *lh)
  617. {
  618. struct lru_entry *le;
  619. struct dm_buffer *b;
  620. struct evict_wrapper w = {.lh = lh, .pred = pred, .context = context};
  621. while (true) {
  622. le = lru_evict(&bc->lru[old_mode], __evict_pred, &w, bc->no_sleep);
  623. if (!le)
  624. break;
  625. b = le_to_buffer(le);
  626. b->list_mode = new_mode;
  627. lru_insert(&bc->lru[b->list_mode], &b->lru);
  628. }
  629. }
  630. static void cache_mark_many(struct dm_buffer_cache *bc, int old_mode, int new_mode,
  631. b_predicate pred, void *context)
  632. {
  633. struct lock_history lh;
  634. lh_init(&lh, bc, true);
  635. __cache_mark_many(bc, old_mode, new_mode, pred, context, &lh);
  636. lh_exit(&lh);
  637. }
  638. /*--------------*/
  639. /*
  640. * Iterates through all clean or dirty entries calling a function for each
  641. * entry. The callback may terminate the iteration early. Not threadsafe.
  642. */
  643. /*
  644. * Iterator functions should return one of these actions to indicate
  645. * how the iteration should proceed.
  646. */
  647. enum it_action {
  648. IT_NEXT,
  649. IT_COMPLETE,
  650. };
  651. typedef enum it_action (*iter_fn)(struct dm_buffer *b, void *context);
  652. static void __cache_iterate(struct dm_buffer_cache *bc, int list_mode,
  653. iter_fn fn, void *context, struct lock_history *lh)
  654. {
  655. struct lru *lru = &bc->lru[list_mode];
  656. struct lru_entry *le, *first;
  657. if (!lru->cursor)
  658. return;
  659. first = le = to_le(lru->cursor);
  660. do {
  661. struct dm_buffer *b = le_to_buffer(le);
  662. lh_next(lh, b->block);
  663. switch (fn(b, context)) {
  664. case IT_NEXT:
  665. break;
  666. case IT_COMPLETE:
  667. return;
  668. }
  669. cond_resched();
  670. le = to_le(le->list.next);
  671. } while (le != first);
  672. }
  673. static void cache_iterate(struct dm_buffer_cache *bc, int list_mode,
  674. iter_fn fn, void *context)
  675. {
  676. struct lock_history lh;
  677. lh_init(&lh, bc, false);
  678. __cache_iterate(bc, list_mode, fn, context, &lh);
  679. lh_exit(&lh);
  680. }
  681. /*--------------*/
  682. /*
  683. * Passes ownership of the buffer to the cache. Returns false if the
  684. * buffer was already present (in which case ownership does not pass).
  685. * eg, a race with another thread.
  686. *
  687. * Holder count should be 1 on insertion.
  688. *
  689. * Not threadsafe.
  690. */
  691. static bool __cache_insert(struct rb_root *root, struct dm_buffer *b)
  692. {
  693. struct rb_node **new = &root->rb_node, *parent = NULL;
  694. struct dm_buffer *found;
  695. while (*new) {
  696. found = container_of(*new, struct dm_buffer, node);
  697. if (found->block == b->block)
  698. return false;
  699. parent = *new;
  700. new = b->block < found->block ?
  701. &found->node.rb_left : &found->node.rb_right;
  702. }
  703. rb_link_node(&b->node, parent, new);
  704. rb_insert_color(&b->node, root);
  705. return true;
  706. }
  707. static bool cache_insert(struct dm_buffer_cache *bc, struct dm_buffer *b)
  708. {
  709. bool r;
  710. if (WARN_ON_ONCE(b->list_mode >= LIST_SIZE))
  711. return false;
  712. cache_write_lock(bc, b->block);
  713. BUG_ON(atomic_read(&b->hold_count) != 1);
  714. r = __cache_insert(&bc->trees[cache_index(b->block, bc->num_locks)].root, b);
  715. if (r)
  716. lru_insert(&bc->lru[b->list_mode], &b->lru);
  717. cache_write_unlock(bc, b->block);
  718. return r;
  719. }
  720. /*--------------*/
  721. /*
  722. * Removes buffer from cache, ownership of the buffer passes back to the caller.
  723. * Fails if the hold_count is not one (ie. the caller holds the only reference).
  724. *
  725. * Not threadsafe.
  726. */
  727. static bool cache_remove(struct dm_buffer_cache *bc, struct dm_buffer *b)
  728. {
  729. bool r;
  730. cache_write_lock(bc, b->block);
  731. if (atomic_read(&b->hold_count) != 1) {
  732. r = false;
  733. } else {
  734. r = true;
  735. rb_erase(&b->node, &bc->trees[cache_index(b->block, bc->num_locks)].root);
  736. lru_remove(&bc->lru[b->list_mode], &b->lru);
  737. }
  738. cache_write_unlock(bc, b->block);
  739. return r;
  740. }
  741. /*--------------*/
  742. typedef void (*b_release)(struct dm_buffer *);
  743. static struct dm_buffer *__find_next(struct rb_root *root, sector_t block)
  744. {
  745. struct rb_node *n = root->rb_node;
  746. struct dm_buffer *b;
  747. struct dm_buffer *best = NULL;
  748. while (n) {
  749. b = container_of(n, struct dm_buffer, node);
  750. if (b->block == block)
  751. return b;
  752. if (block <= b->block) {
  753. n = n->rb_left;
  754. best = b;
  755. } else {
  756. n = n->rb_right;
  757. }
  758. }
  759. return best;
  760. }
  761. static void __remove_range(struct dm_buffer_cache *bc,
  762. struct rb_root *root,
  763. sector_t begin, sector_t end,
  764. b_predicate pred, b_release release)
  765. {
  766. struct dm_buffer *b;
  767. while (true) {
  768. cond_resched();
  769. b = __find_next(root, begin);
  770. if (!b || (b->block >= end))
  771. break;
  772. begin = b->block + 1;
  773. if (atomic_read(&b->hold_count))
  774. continue;
  775. if (pred(b, NULL) == ER_EVICT) {
  776. rb_erase(&b->node, root);
  777. lru_remove(&bc->lru[b->list_mode], &b->lru);
  778. release(b);
  779. }
  780. }
  781. }
  782. static void cache_remove_range(struct dm_buffer_cache *bc,
  783. sector_t begin, sector_t end,
  784. b_predicate pred, b_release release)
  785. {
  786. unsigned int i;
  787. BUG_ON(bc->no_sleep);
  788. for (i = 0; i < bc->num_locks; i++) {
  789. down_write(&bc->trees[i].u.lock);
  790. __remove_range(bc, &bc->trees[i].root, begin, end, pred, release);
  791. up_write(&bc->trees[i].u.lock);
  792. }
  793. }
  794. /*----------------------------------------------------------------*/
  795. /*
  796. * Linking of buffers:
  797. * All buffers are linked to buffer_cache with their node field.
  798. *
  799. * Clean buffers that are not being written (B_WRITING not set)
  800. * are linked to lru[LIST_CLEAN] with their lru_list field.
  801. *
  802. * Dirty and clean buffers that are being written are linked to
  803. * lru[LIST_DIRTY] with their lru_list field. When the write
  804. * finishes, the buffer cannot be relinked immediately (because we
  805. * are in an interrupt context and relinking requires process
  806. * context), so some clean-not-writing buffers can be held on
  807. * dirty_lru too. They are later added to lru in the process
  808. * context.
  809. */
  810. struct dm_bufio_client {
  811. struct block_device *bdev;
  812. unsigned int block_size;
  813. s8 sectors_per_block_bits;
  814. bool no_sleep;
  815. struct mutex lock;
  816. spinlock_t spinlock;
  817. int async_write_error;
  818. void (*alloc_callback)(struct dm_buffer *buf);
  819. void (*write_callback)(struct dm_buffer *buf);
  820. struct kmem_cache *slab_buffer;
  821. struct kmem_cache *slab_cache;
  822. struct dm_io_client *dm_io;
  823. struct list_head reserved_buffers;
  824. unsigned int need_reserved_buffers;
  825. unsigned int minimum_buffers;
  826. sector_t start;
  827. struct shrinker *shrinker;
  828. struct work_struct shrink_work;
  829. atomic_long_t need_shrink;
  830. wait_queue_head_t free_buffer_wait;
  831. struct list_head client_list;
  832. /*
  833. * Used by global_cleanup to sort the clients list.
  834. */
  835. unsigned long oldest_buffer;
  836. struct dm_buffer_cache cache; /* must be last member */
  837. };
  838. /*----------------------------------------------------------------*/
  839. #define dm_bufio_in_request() (!!current->bio_list)
  840. static void dm_bufio_lock(struct dm_bufio_client *c)
  841. {
  842. if (static_branch_unlikely(&no_sleep_enabled) && c->no_sleep)
  843. spin_lock_bh(&c->spinlock);
  844. else
  845. mutex_lock_nested(&c->lock, dm_bufio_in_request());
  846. }
  847. static void dm_bufio_unlock(struct dm_bufio_client *c)
  848. {
  849. if (static_branch_unlikely(&no_sleep_enabled) && c->no_sleep)
  850. spin_unlock_bh(&c->spinlock);
  851. else
  852. mutex_unlock(&c->lock);
  853. }
  854. /*----------------------------------------------------------------*/
  855. /*
  856. * Default cache size: available memory divided by the ratio.
  857. */
  858. static unsigned long dm_bufio_default_cache_size;
  859. /*
  860. * Total cache size set by the user.
  861. */
  862. static unsigned long dm_bufio_cache_size;
  863. /*
  864. * A copy of dm_bufio_cache_size because dm_bufio_cache_size can change
  865. * at any time. If it disagrees, the user has changed cache size.
  866. */
  867. static unsigned long dm_bufio_cache_size_latch;
  868. static DEFINE_SPINLOCK(global_spinlock);
  869. /*
  870. * Buffers are freed after this timeout
  871. */
  872. static unsigned int dm_bufio_max_age = DM_BUFIO_DEFAULT_AGE_SECS;
  873. static unsigned long dm_bufio_retain_bytes = DM_BUFIO_DEFAULT_RETAIN_BYTES;
  874. static unsigned long dm_bufio_peak_allocated;
  875. static unsigned long dm_bufio_allocated_kmem_cache;
  876. static unsigned long dm_bufio_allocated_get_free_pages;
  877. static unsigned long dm_bufio_allocated_vmalloc;
  878. static unsigned long dm_bufio_current_allocated;
  879. /*----------------------------------------------------------------*/
  880. /*
  881. * The current number of clients.
  882. */
  883. static int dm_bufio_client_count;
  884. /*
  885. * The list of all clients.
  886. */
  887. static LIST_HEAD(dm_bufio_all_clients);
  888. /*
  889. * This mutex protects dm_bufio_cache_size_latch and dm_bufio_client_count
  890. */
  891. static DEFINE_MUTEX(dm_bufio_clients_lock);
  892. static struct workqueue_struct *dm_bufio_wq;
  893. static struct delayed_work dm_bufio_cleanup_old_work;
  894. static struct work_struct dm_bufio_replacement_work;
  895. #ifdef CONFIG_DM_DEBUG_BLOCK_STACK_TRACING
  896. static void buffer_record_stack(struct dm_buffer *b)
  897. {
  898. b->stack_len = stack_trace_save(b->stack_entries, MAX_STACK, 2);
  899. }
  900. #endif
  901. /*----------------------------------------------------------------*/
  902. static void adjust_total_allocated(struct dm_buffer *b, bool unlink)
  903. {
  904. unsigned char data_mode;
  905. long diff;
  906. static unsigned long * const class_ptr[DATA_MODE_LIMIT] = {
  907. &dm_bufio_allocated_kmem_cache,
  908. &dm_bufio_allocated_get_free_pages,
  909. &dm_bufio_allocated_vmalloc,
  910. };
  911. data_mode = b->data_mode;
  912. diff = (long)b->c->block_size;
  913. if (unlink)
  914. diff = -diff;
  915. spin_lock(&global_spinlock);
  916. *class_ptr[data_mode] += diff;
  917. dm_bufio_current_allocated += diff;
  918. if (dm_bufio_current_allocated > dm_bufio_peak_allocated)
  919. dm_bufio_peak_allocated = dm_bufio_current_allocated;
  920. if (!unlink) {
  921. if (dm_bufio_current_allocated > dm_bufio_cache_size)
  922. queue_work(dm_bufio_wq, &dm_bufio_replacement_work);
  923. }
  924. spin_unlock(&global_spinlock);
  925. }
  926. /*
  927. * Change the number of clients and recalculate per-client limit.
  928. */
  929. static void __cache_size_refresh(void)
  930. {
  931. if (WARN_ON(!mutex_is_locked(&dm_bufio_clients_lock)))
  932. return;
  933. if (WARN_ON(dm_bufio_client_count < 0))
  934. return;
  935. dm_bufio_cache_size_latch = READ_ONCE(dm_bufio_cache_size);
  936. /*
  937. * Use default if set to 0 and report the actual cache size used.
  938. */
  939. if (!dm_bufio_cache_size_latch) {
  940. (void)cmpxchg(&dm_bufio_cache_size, 0,
  941. dm_bufio_default_cache_size);
  942. dm_bufio_cache_size_latch = dm_bufio_default_cache_size;
  943. }
  944. }
  945. /*
  946. * Allocating buffer data.
  947. *
  948. * Small buffers are allocated with kmem_cache, to use space optimally.
  949. *
  950. * For large buffers, we choose between get_free_pages and vmalloc.
  951. * Each has advantages and disadvantages.
  952. *
  953. * __get_free_pages can randomly fail if the memory is fragmented.
  954. * __vmalloc won't randomly fail, but vmalloc space is limited (it may be
  955. * as low as 128M) so using it for caching is not appropriate.
  956. *
  957. * If the allocation may fail we use __get_free_pages. Memory fragmentation
  958. * won't have a fatal effect here, but it just causes flushes of some other
  959. * buffers and more I/O will be performed. Don't use __get_free_pages if it
  960. * always fails (i.e. order > MAX_PAGE_ORDER).
  961. *
  962. * If the allocation shouldn't fail we use __vmalloc. This is only for the
  963. * initial reserve allocation, so there's no risk of wasting all vmalloc
  964. * space.
  965. */
  966. static void *alloc_buffer_data(struct dm_bufio_client *c, gfp_t gfp_mask,
  967. unsigned char *data_mode)
  968. {
  969. if (unlikely(c->slab_cache != NULL)) {
  970. *data_mode = DATA_MODE_SLAB;
  971. return kmem_cache_alloc(c->slab_cache, gfp_mask);
  972. }
  973. if (c->block_size <= KMALLOC_MAX_SIZE &&
  974. gfp_mask & __GFP_NORETRY) {
  975. *data_mode = DATA_MODE_GET_FREE_PAGES;
  976. return (void *)__get_free_pages(gfp_mask,
  977. c->sectors_per_block_bits - (PAGE_SHIFT - SECTOR_SHIFT));
  978. }
  979. *data_mode = DATA_MODE_VMALLOC;
  980. return __vmalloc(c->block_size, gfp_mask);
  981. }
  982. /*
  983. * Free buffer's data.
  984. */
  985. static void free_buffer_data(struct dm_bufio_client *c,
  986. void *data, unsigned char data_mode)
  987. {
  988. switch (data_mode) {
  989. case DATA_MODE_SLAB:
  990. kmem_cache_free(c->slab_cache, data);
  991. break;
  992. case DATA_MODE_GET_FREE_PAGES:
  993. free_pages((unsigned long)data,
  994. c->sectors_per_block_bits - (PAGE_SHIFT - SECTOR_SHIFT));
  995. break;
  996. case DATA_MODE_VMALLOC:
  997. vfree(data);
  998. break;
  999. default:
  1000. DMCRIT("dm_bufio_free_buffer_data: bad data mode: %d",
  1001. data_mode);
  1002. BUG();
  1003. }
  1004. }
  1005. /*
  1006. * Allocate buffer and its data.
  1007. */
  1008. static struct dm_buffer *alloc_buffer(struct dm_bufio_client *c, gfp_t gfp_mask)
  1009. {
  1010. struct dm_buffer *b = kmem_cache_alloc(c->slab_buffer, gfp_mask);
  1011. if (!b)
  1012. return NULL;
  1013. b->c = c;
  1014. b->data = alloc_buffer_data(c, gfp_mask, &b->data_mode);
  1015. if (!b->data) {
  1016. kmem_cache_free(c->slab_buffer, b);
  1017. return NULL;
  1018. }
  1019. adjust_total_allocated(b, false);
  1020. #ifdef CONFIG_DM_DEBUG_BLOCK_STACK_TRACING
  1021. b->stack_len = 0;
  1022. #endif
  1023. return b;
  1024. }
  1025. /*
  1026. * Free buffer and its data.
  1027. */
  1028. static void free_buffer(struct dm_buffer *b)
  1029. {
  1030. struct dm_bufio_client *c = b->c;
  1031. adjust_total_allocated(b, true);
  1032. free_buffer_data(c, b->data, b->data_mode);
  1033. kmem_cache_free(c->slab_buffer, b);
  1034. }
  1035. /*
  1036. *--------------------------------------------------------------------------
  1037. * Submit I/O on the buffer.
  1038. *
  1039. * Bio interface is faster but it has some problems:
  1040. * the vector list is limited (increasing this limit increases
  1041. * memory-consumption per buffer, so it is not viable);
  1042. *
  1043. * the memory must be direct-mapped, not vmalloced;
  1044. *
  1045. * If the buffer is small enough (up to DM_BUFIO_INLINE_VECS pages) and
  1046. * it is not vmalloced, try using the bio interface.
  1047. *
  1048. * If the buffer is big, if it is vmalloced or if the underlying device
  1049. * rejects the bio because it is too large, use dm-io layer to do the I/O.
  1050. * The dm-io layer splits the I/O into multiple requests, avoiding the above
  1051. * shortcomings.
  1052. *--------------------------------------------------------------------------
  1053. */
  1054. /*
  1055. * dm-io completion routine. It just calls b->bio.bi_end_io, pretending
  1056. * that the request was handled directly with bio interface.
  1057. */
  1058. static void dmio_complete(unsigned long error, void *context)
  1059. {
  1060. struct dm_buffer *b = context;
  1061. b->end_io(b, unlikely(error != 0) ? BLK_STS_IOERR : 0);
  1062. }
  1063. static void use_dmio(struct dm_buffer *b, enum req_op op, sector_t sector,
  1064. unsigned int n_sectors, unsigned int offset,
  1065. unsigned short ioprio)
  1066. {
  1067. int r;
  1068. struct dm_io_request io_req = {
  1069. .bi_opf = op,
  1070. .notify.fn = dmio_complete,
  1071. .notify.context = b,
  1072. .client = b->c->dm_io,
  1073. };
  1074. struct dm_io_region region = {
  1075. .bdev = b->c->bdev,
  1076. .sector = sector,
  1077. .count = n_sectors,
  1078. };
  1079. if (b->data_mode != DATA_MODE_VMALLOC) {
  1080. io_req.mem.type = DM_IO_KMEM;
  1081. io_req.mem.ptr.addr = (char *)b->data + offset;
  1082. } else {
  1083. io_req.mem.type = DM_IO_VMA;
  1084. io_req.mem.ptr.vma = (char *)b->data + offset;
  1085. }
  1086. r = dm_io(&io_req, 1, &region, NULL, ioprio);
  1087. if (unlikely(r))
  1088. b->end_io(b, errno_to_blk_status(r));
  1089. }
  1090. static void bio_complete(struct bio *bio)
  1091. {
  1092. struct dm_buffer *b = bio->bi_private;
  1093. blk_status_t status = bio->bi_status;
  1094. bio_uninit(bio);
  1095. kfree(bio);
  1096. b->end_io(b, status);
  1097. }
  1098. static void use_bio(struct dm_buffer *b, enum req_op op, sector_t sector,
  1099. unsigned int n_sectors, unsigned int offset,
  1100. unsigned short ioprio)
  1101. {
  1102. struct bio *bio;
  1103. char *ptr;
  1104. unsigned int len;
  1105. bio = bio_kmalloc(1, GFP_NOWAIT | __GFP_NORETRY | __GFP_NOWARN);
  1106. if (!bio) {
  1107. use_dmio(b, op, sector, n_sectors, offset, ioprio);
  1108. return;
  1109. }
  1110. bio_init(bio, b->c->bdev, bio->bi_inline_vecs, 1, op);
  1111. bio->bi_iter.bi_sector = sector;
  1112. bio->bi_end_io = bio_complete;
  1113. bio->bi_private = b;
  1114. bio->bi_ioprio = ioprio;
  1115. ptr = (char *)b->data + offset;
  1116. len = n_sectors << SECTOR_SHIFT;
  1117. __bio_add_page(bio, virt_to_page(ptr), len, offset_in_page(ptr));
  1118. submit_bio(bio);
  1119. }
  1120. static inline sector_t block_to_sector(struct dm_bufio_client *c, sector_t block)
  1121. {
  1122. sector_t sector;
  1123. if (likely(c->sectors_per_block_bits >= 0))
  1124. sector = block << c->sectors_per_block_bits;
  1125. else
  1126. sector = block * (c->block_size >> SECTOR_SHIFT);
  1127. sector += c->start;
  1128. return sector;
  1129. }
  1130. static void submit_io(struct dm_buffer *b, enum req_op op, unsigned short ioprio,
  1131. void (*end_io)(struct dm_buffer *, blk_status_t))
  1132. {
  1133. unsigned int n_sectors;
  1134. sector_t sector;
  1135. unsigned int offset, end;
  1136. b->end_io = end_io;
  1137. sector = block_to_sector(b->c, b->block);
  1138. if (op != REQ_OP_WRITE) {
  1139. n_sectors = b->c->block_size >> SECTOR_SHIFT;
  1140. offset = 0;
  1141. } else {
  1142. if (b->c->write_callback)
  1143. b->c->write_callback(b);
  1144. offset = b->write_start;
  1145. end = b->write_end;
  1146. offset &= -DM_BUFIO_WRITE_ALIGN;
  1147. end += DM_BUFIO_WRITE_ALIGN - 1;
  1148. end &= -DM_BUFIO_WRITE_ALIGN;
  1149. if (unlikely(end > b->c->block_size))
  1150. end = b->c->block_size;
  1151. sector += offset >> SECTOR_SHIFT;
  1152. n_sectors = (end - offset) >> SECTOR_SHIFT;
  1153. }
  1154. if (b->data_mode != DATA_MODE_VMALLOC)
  1155. use_bio(b, op, sector, n_sectors, offset, ioprio);
  1156. else
  1157. use_dmio(b, op, sector, n_sectors, offset, ioprio);
  1158. }
  1159. /*
  1160. *--------------------------------------------------------------
  1161. * Writing dirty buffers
  1162. *--------------------------------------------------------------
  1163. */
  1164. /*
  1165. * The endio routine for write.
  1166. *
  1167. * Set the error, clear B_WRITING bit and wake anyone who was waiting on
  1168. * it.
  1169. */
  1170. static void write_endio(struct dm_buffer *b, blk_status_t status)
  1171. {
  1172. b->write_error = status;
  1173. if (unlikely(status)) {
  1174. struct dm_bufio_client *c = b->c;
  1175. (void)cmpxchg(&c->async_write_error, 0,
  1176. blk_status_to_errno(status));
  1177. }
  1178. BUG_ON(!test_bit(B_WRITING, &b->state));
  1179. smp_mb__before_atomic();
  1180. clear_bit(B_WRITING, &b->state);
  1181. smp_mb__after_atomic();
  1182. wake_up_bit(&b->state, B_WRITING);
  1183. }
  1184. /*
  1185. * Initiate a write on a dirty buffer, but don't wait for it.
  1186. *
  1187. * - If the buffer is not dirty, exit.
  1188. * - If there some previous write going on, wait for it to finish (we can't
  1189. * have two writes on the same buffer simultaneously).
  1190. * - Submit our write and don't wait on it. We set B_WRITING indicating
  1191. * that there is a write in progress.
  1192. */
  1193. static void __write_dirty_buffer(struct dm_buffer *b,
  1194. struct list_head *write_list)
  1195. {
  1196. if (!test_bit(B_DIRTY, &b->state))
  1197. return;
  1198. clear_bit(B_DIRTY, &b->state);
  1199. wait_on_bit_lock_io(&b->state, B_WRITING, TASK_UNINTERRUPTIBLE);
  1200. b->write_start = b->dirty_start;
  1201. b->write_end = b->dirty_end;
  1202. if (!write_list)
  1203. submit_io(b, REQ_OP_WRITE, IOPRIO_DEFAULT, write_endio);
  1204. else
  1205. list_add_tail(&b->write_list, write_list);
  1206. }
  1207. static void __flush_write_list(struct list_head *write_list)
  1208. {
  1209. struct blk_plug plug;
  1210. blk_start_plug(&plug);
  1211. while (!list_empty(write_list)) {
  1212. struct dm_buffer *b =
  1213. list_entry(write_list->next, struct dm_buffer, write_list);
  1214. list_del(&b->write_list);
  1215. submit_io(b, REQ_OP_WRITE, IOPRIO_DEFAULT, write_endio);
  1216. cond_resched();
  1217. }
  1218. blk_finish_plug(&plug);
  1219. }
  1220. /*
  1221. * Wait until any activity on the buffer finishes. Possibly write the
  1222. * buffer if it is dirty. When this function finishes, there is no I/O
  1223. * running on the buffer and the buffer is not dirty.
  1224. */
  1225. static void __make_buffer_clean(struct dm_buffer *b)
  1226. {
  1227. BUG_ON(atomic_read(&b->hold_count));
  1228. /* smp_load_acquire() pairs with read_endio()'s smp_mb__before_atomic() */
  1229. if (!smp_load_acquire(&b->state)) /* fast case */
  1230. return;
  1231. wait_on_bit_io(&b->state, B_READING, TASK_UNINTERRUPTIBLE);
  1232. __write_dirty_buffer(b, NULL);
  1233. wait_on_bit_io(&b->state, B_WRITING, TASK_UNINTERRUPTIBLE);
  1234. }
  1235. static enum evict_result is_clean(struct dm_buffer *b, void *context)
  1236. {
  1237. struct dm_bufio_client *c = context;
  1238. /* These should never happen */
  1239. if (WARN_ON_ONCE(test_bit(B_WRITING, &b->state)))
  1240. return ER_DONT_EVICT;
  1241. if (WARN_ON_ONCE(test_bit(B_DIRTY, &b->state)))
  1242. return ER_DONT_EVICT;
  1243. if (WARN_ON_ONCE(b->list_mode != LIST_CLEAN))
  1244. return ER_DONT_EVICT;
  1245. if (static_branch_unlikely(&no_sleep_enabled) && c->no_sleep &&
  1246. unlikely(test_bit(B_READING, &b->state)))
  1247. return ER_DONT_EVICT;
  1248. return ER_EVICT;
  1249. }
  1250. static enum evict_result is_dirty(struct dm_buffer *b, void *context)
  1251. {
  1252. /* These should never happen */
  1253. if (WARN_ON_ONCE(test_bit(B_READING, &b->state)))
  1254. return ER_DONT_EVICT;
  1255. if (WARN_ON_ONCE(b->list_mode != LIST_DIRTY))
  1256. return ER_DONT_EVICT;
  1257. return ER_EVICT;
  1258. }
  1259. /*
  1260. * Find some buffer that is not held by anybody, clean it, unlink it and
  1261. * return it.
  1262. */
  1263. static struct dm_buffer *__get_unclaimed_buffer(struct dm_bufio_client *c)
  1264. {
  1265. struct dm_buffer *b;
  1266. b = cache_evict(&c->cache, LIST_CLEAN, is_clean, c);
  1267. if (b) {
  1268. /* this also waits for pending reads */
  1269. __make_buffer_clean(b);
  1270. return b;
  1271. }
  1272. if (static_branch_unlikely(&no_sleep_enabled) && c->no_sleep)
  1273. return NULL;
  1274. b = cache_evict(&c->cache, LIST_DIRTY, is_dirty, NULL);
  1275. if (b) {
  1276. __make_buffer_clean(b);
  1277. return b;
  1278. }
  1279. return NULL;
  1280. }
  1281. /*
  1282. * Wait until some other threads free some buffer or release hold count on
  1283. * some buffer.
  1284. *
  1285. * This function is entered with c->lock held, drops it and regains it
  1286. * before exiting.
  1287. */
  1288. static void __wait_for_free_buffer(struct dm_bufio_client *c)
  1289. {
  1290. DECLARE_WAITQUEUE(wait, current);
  1291. add_wait_queue(&c->free_buffer_wait, &wait);
  1292. set_current_state(TASK_UNINTERRUPTIBLE);
  1293. dm_bufio_unlock(c);
  1294. /*
  1295. * It's possible to miss a wake up event since we don't always
  1296. * hold c->lock when wake_up is called. So we have a timeout here,
  1297. * just in case.
  1298. */
  1299. io_schedule_timeout(5 * HZ);
  1300. remove_wait_queue(&c->free_buffer_wait, &wait);
  1301. dm_bufio_lock(c);
  1302. }
  1303. enum new_flag {
  1304. NF_FRESH = 0,
  1305. NF_READ = 1,
  1306. NF_GET = 2,
  1307. NF_PREFETCH = 3
  1308. };
  1309. /*
  1310. * Allocate a new buffer. If the allocation is not possible, wait until
  1311. * some other thread frees a buffer.
  1312. *
  1313. * May drop the lock and regain it.
  1314. */
  1315. static struct dm_buffer *__alloc_buffer_wait_no_callback(struct dm_bufio_client *c, enum new_flag nf)
  1316. {
  1317. struct dm_buffer *b;
  1318. bool tried_noio_alloc = false;
  1319. /*
  1320. * dm-bufio is resistant to allocation failures (it just keeps
  1321. * one buffer reserved in cases all the allocations fail).
  1322. * So set flags to not try too hard:
  1323. * GFP_NOWAIT: don't wait; if we need to sleep we'll release our
  1324. * mutex and wait ourselves.
  1325. * __GFP_NORETRY: don't retry and rather return failure
  1326. * __GFP_NOMEMALLOC: don't use emergency reserves
  1327. * __GFP_NOWARN: don't print a warning in case of failure
  1328. *
  1329. * For debugging, if we set the cache size to 1, no new buffers will
  1330. * be allocated.
  1331. */
  1332. while (1) {
  1333. if (dm_bufio_cache_size_latch != 1) {
  1334. b = alloc_buffer(c, GFP_NOWAIT | __GFP_NORETRY | __GFP_NOMEMALLOC | __GFP_NOWARN);
  1335. if (b)
  1336. return b;
  1337. }
  1338. if (nf == NF_PREFETCH)
  1339. return NULL;
  1340. if (dm_bufio_cache_size_latch != 1 && !tried_noio_alloc) {
  1341. dm_bufio_unlock(c);
  1342. b = alloc_buffer(c, GFP_NOIO | __GFP_NORETRY | __GFP_NOMEMALLOC | __GFP_NOWARN);
  1343. dm_bufio_lock(c);
  1344. if (b)
  1345. return b;
  1346. tried_noio_alloc = true;
  1347. }
  1348. if (!list_empty(&c->reserved_buffers)) {
  1349. b = list_to_buffer(c->reserved_buffers.next);
  1350. list_del(&b->lru.list);
  1351. c->need_reserved_buffers++;
  1352. return b;
  1353. }
  1354. b = __get_unclaimed_buffer(c);
  1355. if (b)
  1356. return b;
  1357. __wait_for_free_buffer(c);
  1358. }
  1359. }
  1360. static struct dm_buffer *__alloc_buffer_wait(struct dm_bufio_client *c, enum new_flag nf)
  1361. {
  1362. struct dm_buffer *b = __alloc_buffer_wait_no_callback(c, nf);
  1363. if (!b)
  1364. return NULL;
  1365. if (c->alloc_callback)
  1366. c->alloc_callback(b);
  1367. return b;
  1368. }
  1369. /*
  1370. * Free a buffer and wake other threads waiting for free buffers.
  1371. */
  1372. static void __free_buffer_wake(struct dm_buffer *b)
  1373. {
  1374. struct dm_bufio_client *c = b->c;
  1375. b->block = -1;
  1376. if (!c->need_reserved_buffers)
  1377. free_buffer(b);
  1378. else {
  1379. list_add(&b->lru.list, &c->reserved_buffers);
  1380. c->need_reserved_buffers--;
  1381. }
  1382. /*
  1383. * We hold the bufio lock here, so no one can add entries to the
  1384. * wait queue anyway.
  1385. */
  1386. if (unlikely(waitqueue_active(&c->free_buffer_wait)))
  1387. wake_up(&c->free_buffer_wait);
  1388. }
  1389. static enum evict_result cleaned(struct dm_buffer *b, void *context)
  1390. {
  1391. if (WARN_ON_ONCE(test_bit(B_READING, &b->state)))
  1392. return ER_DONT_EVICT; /* should never happen */
  1393. if (test_bit(B_DIRTY, &b->state) || test_bit(B_WRITING, &b->state))
  1394. return ER_DONT_EVICT;
  1395. else
  1396. return ER_EVICT;
  1397. }
  1398. static void __move_clean_buffers(struct dm_bufio_client *c)
  1399. {
  1400. cache_mark_many(&c->cache, LIST_DIRTY, LIST_CLEAN, cleaned, NULL);
  1401. }
  1402. struct write_context {
  1403. int no_wait;
  1404. struct list_head *write_list;
  1405. };
  1406. static enum it_action write_one(struct dm_buffer *b, void *context)
  1407. {
  1408. struct write_context *wc = context;
  1409. if (wc->no_wait && test_bit(B_WRITING, &b->state))
  1410. return IT_COMPLETE;
  1411. __write_dirty_buffer(b, wc->write_list);
  1412. return IT_NEXT;
  1413. }
  1414. static void __write_dirty_buffers_async(struct dm_bufio_client *c, int no_wait,
  1415. struct list_head *write_list)
  1416. {
  1417. struct write_context wc = {.no_wait = no_wait, .write_list = write_list};
  1418. __move_clean_buffers(c);
  1419. cache_iterate(&c->cache, LIST_DIRTY, write_one, &wc);
  1420. }
  1421. /*
  1422. * Check if we're over watermark.
  1423. * If we are over threshold_buffers, start freeing buffers.
  1424. * If we're over "limit_buffers", block until we get under the limit.
  1425. */
  1426. static void __check_watermark(struct dm_bufio_client *c,
  1427. struct list_head *write_list)
  1428. {
  1429. if (cache_count(&c->cache, LIST_DIRTY) >
  1430. cache_count(&c->cache, LIST_CLEAN) * DM_BUFIO_WRITEBACK_RATIO)
  1431. __write_dirty_buffers_async(c, 1, write_list);
  1432. }
  1433. /*
  1434. *--------------------------------------------------------------
  1435. * Getting a buffer
  1436. *--------------------------------------------------------------
  1437. */
  1438. static void cache_put_and_wake(struct dm_bufio_client *c, struct dm_buffer *b)
  1439. {
  1440. /*
  1441. * Relying on waitqueue_active() is racey, but we sleep
  1442. * with schedule_timeout anyway.
  1443. */
  1444. if (cache_put(&c->cache, b) &&
  1445. unlikely(waitqueue_active(&c->free_buffer_wait)))
  1446. wake_up(&c->free_buffer_wait);
  1447. }
  1448. /*
  1449. * This assumes you have already checked the cache to see if the buffer
  1450. * is already present (it will recheck after dropping the lock for allocation).
  1451. */
  1452. static struct dm_buffer *__bufio_new(struct dm_bufio_client *c, sector_t block,
  1453. enum new_flag nf, int *need_submit,
  1454. struct list_head *write_list)
  1455. {
  1456. struct dm_buffer *b, *new_b = NULL;
  1457. *need_submit = 0;
  1458. /* This can't be called with NF_GET */
  1459. if (WARN_ON_ONCE(nf == NF_GET))
  1460. return NULL;
  1461. new_b = __alloc_buffer_wait(c, nf);
  1462. if (!new_b)
  1463. return NULL;
  1464. /*
  1465. * We've had a period where the mutex was unlocked, so need to
  1466. * recheck the buffer tree.
  1467. */
  1468. b = cache_get(&c->cache, block);
  1469. if (b) {
  1470. __free_buffer_wake(new_b);
  1471. goto found_buffer;
  1472. }
  1473. __check_watermark(c, write_list);
  1474. b = new_b;
  1475. atomic_set(&b->hold_count, 1);
  1476. WRITE_ONCE(b->last_accessed, jiffies);
  1477. b->block = block;
  1478. b->read_error = 0;
  1479. b->write_error = 0;
  1480. b->list_mode = LIST_CLEAN;
  1481. if (nf == NF_FRESH)
  1482. b->state = 0;
  1483. else {
  1484. b->state = 1 << B_READING;
  1485. *need_submit = 1;
  1486. }
  1487. /*
  1488. * We mustn't insert into the cache until the B_READING state
  1489. * is set. Otherwise another thread could get it and use
  1490. * it before it had been read.
  1491. */
  1492. cache_insert(&c->cache, b);
  1493. return b;
  1494. found_buffer:
  1495. if (nf == NF_PREFETCH) {
  1496. cache_put_and_wake(c, b);
  1497. return NULL;
  1498. }
  1499. /*
  1500. * Note: it is essential that we don't wait for the buffer to be
  1501. * read if dm_bufio_get function is used. Both dm_bufio_get and
  1502. * dm_bufio_prefetch can be used in the driver request routine.
  1503. * If the user called both dm_bufio_prefetch and dm_bufio_get on
  1504. * the same buffer, it would deadlock if we waited.
  1505. */
  1506. if (nf == NF_GET && unlikely(test_bit_acquire(B_READING, &b->state))) {
  1507. cache_put_and_wake(c, b);
  1508. return NULL;
  1509. }
  1510. return b;
  1511. }
  1512. /*
  1513. * The endio routine for reading: set the error, clear the bit and wake up
  1514. * anyone waiting on the buffer.
  1515. */
  1516. static void read_endio(struct dm_buffer *b, blk_status_t status)
  1517. {
  1518. b->read_error = status;
  1519. BUG_ON(!test_bit(B_READING, &b->state));
  1520. smp_mb__before_atomic();
  1521. clear_bit(B_READING, &b->state);
  1522. smp_mb__after_atomic();
  1523. wake_up_bit(&b->state, B_READING);
  1524. }
  1525. /*
  1526. * A common routine for dm_bufio_new and dm_bufio_read. Operation of these
  1527. * functions is similar except that dm_bufio_new doesn't read the
  1528. * buffer from the disk (assuming that the caller overwrites all the data
  1529. * and uses dm_bufio_mark_buffer_dirty to write new data back).
  1530. */
  1531. static void *new_read(struct dm_bufio_client *c, sector_t block,
  1532. enum new_flag nf, struct dm_buffer **bp,
  1533. unsigned short ioprio)
  1534. {
  1535. int need_submit = 0;
  1536. struct dm_buffer *b;
  1537. LIST_HEAD(write_list);
  1538. *bp = NULL;
  1539. /*
  1540. * Fast path, hopefully the block is already in the cache. No need
  1541. * to get the client lock for this.
  1542. */
  1543. b = cache_get(&c->cache, block);
  1544. if (b) {
  1545. if (nf == NF_PREFETCH) {
  1546. cache_put_and_wake(c, b);
  1547. return NULL;
  1548. }
  1549. /*
  1550. * Note: it is essential that we don't wait for the buffer to be
  1551. * read if dm_bufio_get function is used. Both dm_bufio_get and
  1552. * dm_bufio_prefetch can be used in the driver request routine.
  1553. * If the user called both dm_bufio_prefetch and dm_bufio_get on
  1554. * the same buffer, it would deadlock if we waited.
  1555. */
  1556. if (nf == NF_GET && unlikely(test_bit_acquire(B_READING, &b->state))) {
  1557. cache_put_and_wake(c, b);
  1558. return NULL;
  1559. }
  1560. }
  1561. if (!b) {
  1562. if (nf == NF_GET)
  1563. return NULL;
  1564. dm_bufio_lock(c);
  1565. b = __bufio_new(c, block, nf, &need_submit, &write_list);
  1566. dm_bufio_unlock(c);
  1567. }
  1568. #ifdef CONFIG_DM_DEBUG_BLOCK_STACK_TRACING
  1569. if (b && (atomic_read(&b->hold_count) == 1))
  1570. buffer_record_stack(b);
  1571. #endif
  1572. __flush_write_list(&write_list);
  1573. if (!b)
  1574. return NULL;
  1575. if (need_submit)
  1576. submit_io(b, REQ_OP_READ, ioprio, read_endio);
  1577. if (nf != NF_GET) /* we already tested this condition above */
  1578. wait_on_bit_io(&b->state, B_READING, TASK_UNINTERRUPTIBLE);
  1579. if (b->read_error) {
  1580. int error = blk_status_to_errno(b->read_error);
  1581. dm_bufio_release(b);
  1582. return ERR_PTR(error);
  1583. }
  1584. *bp = b;
  1585. return b->data;
  1586. }
  1587. void *dm_bufio_get(struct dm_bufio_client *c, sector_t block,
  1588. struct dm_buffer **bp)
  1589. {
  1590. return new_read(c, block, NF_GET, bp, IOPRIO_DEFAULT);
  1591. }
  1592. EXPORT_SYMBOL_GPL(dm_bufio_get);
  1593. static void *__dm_bufio_read(struct dm_bufio_client *c, sector_t block,
  1594. struct dm_buffer **bp, unsigned short ioprio)
  1595. {
  1596. if (WARN_ON_ONCE(dm_bufio_in_request()))
  1597. return ERR_PTR(-EINVAL);
  1598. return new_read(c, block, NF_READ, bp, ioprio);
  1599. }
  1600. void *dm_bufio_read(struct dm_bufio_client *c, sector_t block,
  1601. struct dm_buffer **bp)
  1602. {
  1603. return __dm_bufio_read(c, block, bp, IOPRIO_DEFAULT);
  1604. }
  1605. EXPORT_SYMBOL_GPL(dm_bufio_read);
  1606. void *dm_bufio_read_with_ioprio(struct dm_bufio_client *c, sector_t block,
  1607. struct dm_buffer **bp, unsigned short ioprio)
  1608. {
  1609. return __dm_bufio_read(c, block, bp, ioprio);
  1610. }
  1611. EXPORT_SYMBOL_GPL(dm_bufio_read_with_ioprio);
  1612. void *dm_bufio_new(struct dm_bufio_client *c, sector_t block,
  1613. struct dm_buffer **bp)
  1614. {
  1615. if (WARN_ON_ONCE(dm_bufio_in_request()))
  1616. return ERR_PTR(-EINVAL);
  1617. return new_read(c, block, NF_FRESH, bp, IOPRIO_DEFAULT);
  1618. }
  1619. EXPORT_SYMBOL_GPL(dm_bufio_new);
  1620. static void __dm_bufio_prefetch(struct dm_bufio_client *c,
  1621. sector_t block, unsigned int n_blocks,
  1622. unsigned short ioprio)
  1623. {
  1624. struct blk_plug plug;
  1625. LIST_HEAD(write_list);
  1626. if (WARN_ON_ONCE(dm_bufio_in_request()))
  1627. return; /* should never happen */
  1628. blk_start_plug(&plug);
  1629. for (; n_blocks--; block++) {
  1630. int need_submit;
  1631. struct dm_buffer *b;
  1632. b = cache_get(&c->cache, block);
  1633. if (b) {
  1634. /* already in cache */
  1635. cache_put_and_wake(c, b);
  1636. continue;
  1637. }
  1638. dm_bufio_lock(c);
  1639. b = __bufio_new(c, block, NF_PREFETCH, &need_submit,
  1640. &write_list);
  1641. if (unlikely(!list_empty(&write_list))) {
  1642. dm_bufio_unlock(c);
  1643. blk_finish_plug(&plug);
  1644. __flush_write_list(&write_list);
  1645. blk_start_plug(&plug);
  1646. dm_bufio_lock(c);
  1647. }
  1648. if (unlikely(b != NULL)) {
  1649. dm_bufio_unlock(c);
  1650. if (need_submit)
  1651. submit_io(b, REQ_OP_READ, ioprio, read_endio);
  1652. dm_bufio_release(b);
  1653. cond_resched();
  1654. if (!n_blocks)
  1655. goto flush_plug;
  1656. dm_bufio_lock(c);
  1657. }
  1658. dm_bufio_unlock(c);
  1659. }
  1660. flush_plug:
  1661. blk_finish_plug(&plug);
  1662. }
  1663. void dm_bufio_prefetch(struct dm_bufio_client *c, sector_t block, unsigned int n_blocks)
  1664. {
  1665. return __dm_bufio_prefetch(c, block, n_blocks, IOPRIO_DEFAULT);
  1666. }
  1667. EXPORT_SYMBOL_GPL(dm_bufio_prefetch);
  1668. void dm_bufio_prefetch_with_ioprio(struct dm_bufio_client *c, sector_t block,
  1669. unsigned int n_blocks, unsigned short ioprio)
  1670. {
  1671. return __dm_bufio_prefetch(c, block, n_blocks, ioprio);
  1672. }
  1673. EXPORT_SYMBOL_GPL(dm_bufio_prefetch_with_ioprio);
  1674. void dm_bufio_release(struct dm_buffer *b)
  1675. {
  1676. struct dm_bufio_client *c = b->c;
  1677. /*
  1678. * If there were errors on the buffer, and the buffer is not
  1679. * to be written, free the buffer. There is no point in caching
  1680. * invalid buffer.
  1681. */
  1682. if ((b->read_error || b->write_error) &&
  1683. !test_bit_acquire(B_READING, &b->state) &&
  1684. !test_bit(B_WRITING, &b->state) &&
  1685. !test_bit(B_DIRTY, &b->state)) {
  1686. dm_bufio_lock(c);
  1687. /* cache remove can fail if there are other holders */
  1688. if (cache_remove(&c->cache, b)) {
  1689. __free_buffer_wake(b);
  1690. dm_bufio_unlock(c);
  1691. return;
  1692. }
  1693. dm_bufio_unlock(c);
  1694. }
  1695. cache_put_and_wake(c, b);
  1696. }
  1697. EXPORT_SYMBOL_GPL(dm_bufio_release);
  1698. void dm_bufio_mark_partial_buffer_dirty(struct dm_buffer *b,
  1699. unsigned int start, unsigned int end)
  1700. {
  1701. struct dm_bufio_client *c = b->c;
  1702. BUG_ON(start >= end);
  1703. BUG_ON(end > b->c->block_size);
  1704. dm_bufio_lock(c);
  1705. BUG_ON(test_bit(B_READING, &b->state));
  1706. if (!test_and_set_bit(B_DIRTY, &b->state)) {
  1707. b->dirty_start = start;
  1708. b->dirty_end = end;
  1709. cache_mark(&c->cache, b, LIST_DIRTY);
  1710. } else {
  1711. if (start < b->dirty_start)
  1712. b->dirty_start = start;
  1713. if (end > b->dirty_end)
  1714. b->dirty_end = end;
  1715. }
  1716. dm_bufio_unlock(c);
  1717. }
  1718. EXPORT_SYMBOL_GPL(dm_bufio_mark_partial_buffer_dirty);
  1719. void dm_bufio_mark_buffer_dirty(struct dm_buffer *b)
  1720. {
  1721. dm_bufio_mark_partial_buffer_dirty(b, 0, b->c->block_size);
  1722. }
  1723. EXPORT_SYMBOL_GPL(dm_bufio_mark_buffer_dirty);
  1724. void dm_bufio_write_dirty_buffers_async(struct dm_bufio_client *c)
  1725. {
  1726. LIST_HEAD(write_list);
  1727. if (WARN_ON_ONCE(dm_bufio_in_request()))
  1728. return; /* should never happen */
  1729. dm_bufio_lock(c);
  1730. __write_dirty_buffers_async(c, 0, &write_list);
  1731. dm_bufio_unlock(c);
  1732. __flush_write_list(&write_list);
  1733. }
  1734. EXPORT_SYMBOL_GPL(dm_bufio_write_dirty_buffers_async);
  1735. /*
  1736. * For performance, it is essential that the buffers are written asynchronously
  1737. * and simultaneously (so that the block layer can merge the writes) and then
  1738. * waited upon.
  1739. *
  1740. * Finally, we flush hardware disk cache.
  1741. */
  1742. static bool is_writing(struct lru_entry *e, void *context)
  1743. {
  1744. struct dm_buffer *b = le_to_buffer(e);
  1745. return test_bit(B_WRITING, &b->state);
  1746. }
  1747. int dm_bufio_write_dirty_buffers(struct dm_bufio_client *c)
  1748. {
  1749. int a, f;
  1750. unsigned long nr_buffers;
  1751. struct lru_entry *e;
  1752. struct lru_iter it;
  1753. LIST_HEAD(write_list);
  1754. dm_bufio_lock(c);
  1755. __write_dirty_buffers_async(c, 0, &write_list);
  1756. dm_bufio_unlock(c);
  1757. __flush_write_list(&write_list);
  1758. dm_bufio_lock(c);
  1759. nr_buffers = cache_count(&c->cache, LIST_DIRTY);
  1760. lru_iter_begin(&c->cache.lru[LIST_DIRTY], &it);
  1761. while ((e = lru_iter_next(&it, is_writing, c))) {
  1762. struct dm_buffer *b = le_to_buffer(e);
  1763. __cache_inc_buffer(b);
  1764. BUG_ON(test_bit(B_READING, &b->state));
  1765. if (nr_buffers) {
  1766. nr_buffers--;
  1767. dm_bufio_unlock(c);
  1768. wait_on_bit_io(&b->state, B_WRITING, TASK_UNINTERRUPTIBLE);
  1769. dm_bufio_lock(c);
  1770. } else {
  1771. wait_on_bit_io(&b->state, B_WRITING, TASK_UNINTERRUPTIBLE);
  1772. }
  1773. if (!test_bit(B_DIRTY, &b->state) && !test_bit(B_WRITING, &b->state))
  1774. cache_mark(&c->cache, b, LIST_CLEAN);
  1775. cache_put_and_wake(c, b);
  1776. cond_resched();
  1777. }
  1778. lru_iter_end(&it);
  1779. wake_up(&c->free_buffer_wait);
  1780. dm_bufio_unlock(c);
  1781. a = xchg(&c->async_write_error, 0);
  1782. f = dm_bufio_issue_flush(c);
  1783. if (a)
  1784. return a;
  1785. return f;
  1786. }
  1787. EXPORT_SYMBOL_GPL(dm_bufio_write_dirty_buffers);
  1788. /*
  1789. * Use dm-io to send an empty barrier to flush the device.
  1790. */
  1791. int dm_bufio_issue_flush(struct dm_bufio_client *c)
  1792. {
  1793. struct dm_io_request io_req = {
  1794. .bi_opf = REQ_OP_WRITE | REQ_PREFLUSH | REQ_SYNC,
  1795. .mem.type = DM_IO_KMEM,
  1796. .mem.ptr.addr = NULL,
  1797. .client = c->dm_io,
  1798. };
  1799. struct dm_io_region io_reg = {
  1800. .bdev = c->bdev,
  1801. .sector = 0,
  1802. .count = 0,
  1803. };
  1804. if (WARN_ON_ONCE(dm_bufio_in_request()))
  1805. return -EINVAL;
  1806. return dm_io(&io_req, 1, &io_reg, NULL, IOPRIO_DEFAULT);
  1807. }
  1808. EXPORT_SYMBOL_GPL(dm_bufio_issue_flush);
  1809. /*
  1810. * Use dm-io to send a discard request to flush the device.
  1811. */
  1812. int dm_bufio_issue_discard(struct dm_bufio_client *c, sector_t block, sector_t count)
  1813. {
  1814. struct dm_io_request io_req = {
  1815. .bi_opf = REQ_OP_DISCARD | REQ_SYNC,
  1816. .mem.type = DM_IO_KMEM,
  1817. .mem.ptr.addr = NULL,
  1818. .client = c->dm_io,
  1819. };
  1820. struct dm_io_region io_reg = {
  1821. .bdev = c->bdev,
  1822. .sector = block_to_sector(c, block),
  1823. .count = block_to_sector(c, count),
  1824. };
  1825. if (WARN_ON_ONCE(dm_bufio_in_request()))
  1826. return -EINVAL; /* discards are optional */
  1827. return dm_io(&io_req, 1, &io_reg, NULL, IOPRIO_DEFAULT);
  1828. }
  1829. EXPORT_SYMBOL_GPL(dm_bufio_issue_discard);
  1830. static bool forget_buffer(struct dm_bufio_client *c, sector_t block)
  1831. {
  1832. struct dm_buffer *b;
  1833. b = cache_get(&c->cache, block);
  1834. if (b) {
  1835. if (likely(!smp_load_acquire(&b->state))) {
  1836. if (cache_remove(&c->cache, b))
  1837. __free_buffer_wake(b);
  1838. else
  1839. cache_put_and_wake(c, b);
  1840. } else {
  1841. cache_put_and_wake(c, b);
  1842. }
  1843. }
  1844. return b ? true : false;
  1845. }
  1846. /*
  1847. * Free the given buffer.
  1848. *
  1849. * This is just a hint, if the buffer is in use or dirty, this function
  1850. * does nothing.
  1851. */
  1852. void dm_bufio_forget(struct dm_bufio_client *c, sector_t block)
  1853. {
  1854. dm_bufio_lock(c);
  1855. forget_buffer(c, block);
  1856. dm_bufio_unlock(c);
  1857. }
  1858. EXPORT_SYMBOL_GPL(dm_bufio_forget);
  1859. static enum evict_result idle(struct dm_buffer *b, void *context)
  1860. {
  1861. return b->state ? ER_DONT_EVICT : ER_EVICT;
  1862. }
  1863. void dm_bufio_forget_buffers(struct dm_bufio_client *c, sector_t block, sector_t n_blocks)
  1864. {
  1865. dm_bufio_lock(c);
  1866. cache_remove_range(&c->cache, block, block + n_blocks, idle, __free_buffer_wake);
  1867. dm_bufio_unlock(c);
  1868. }
  1869. EXPORT_SYMBOL_GPL(dm_bufio_forget_buffers);
  1870. void dm_bufio_set_minimum_buffers(struct dm_bufio_client *c, unsigned int n)
  1871. {
  1872. c->minimum_buffers = n;
  1873. }
  1874. EXPORT_SYMBOL_GPL(dm_bufio_set_minimum_buffers);
  1875. unsigned int dm_bufio_get_block_size(struct dm_bufio_client *c)
  1876. {
  1877. return c->block_size;
  1878. }
  1879. EXPORT_SYMBOL_GPL(dm_bufio_get_block_size);
  1880. sector_t dm_bufio_get_device_size(struct dm_bufio_client *c)
  1881. {
  1882. sector_t s = bdev_nr_sectors(c->bdev);
  1883. if (s >= c->start)
  1884. s -= c->start;
  1885. else
  1886. s = 0;
  1887. if (likely(c->sectors_per_block_bits >= 0))
  1888. s >>= c->sectors_per_block_bits;
  1889. else
  1890. sector_div(s, c->block_size >> SECTOR_SHIFT);
  1891. return s;
  1892. }
  1893. EXPORT_SYMBOL_GPL(dm_bufio_get_device_size);
  1894. struct dm_io_client *dm_bufio_get_dm_io_client(struct dm_bufio_client *c)
  1895. {
  1896. return c->dm_io;
  1897. }
  1898. EXPORT_SYMBOL_GPL(dm_bufio_get_dm_io_client);
  1899. sector_t dm_bufio_get_block_number(struct dm_buffer *b)
  1900. {
  1901. return b->block;
  1902. }
  1903. EXPORT_SYMBOL_GPL(dm_bufio_get_block_number);
  1904. void *dm_bufio_get_block_data(struct dm_buffer *b)
  1905. {
  1906. return b->data;
  1907. }
  1908. EXPORT_SYMBOL_GPL(dm_bufio_get_block_data);
  1909. void *dm_bufio_get_aux_data(struct dm_buffer *b)
  1910. {
  1911. return b + 1;
  1912. }
  1913. EXPORT_SYMBOL_GPL(dm_bufio_get_aux_data);
  1914. struct dm_bufio_client *dm_bufio_get_client(struct dm_buffer *b)
  1915. {
  1916. return b->c;
  1917. }
  1918. EXPORT_SYMBOL_GPL(dm_bufio_get_client);
  1919. static enum it_action warn_leak(struct dm_buffer *b, void *context)
  1920. {
  1921. bool *warned = context;
  1922. WARN_ON(!(*warned));
  1923. *warned = true;
  1924. DMERR("leaked buffer %llx, hold count %u, list %d",
  1925. (unsigned long long)b->block, atomic_read(&b->hold_count), b->list_mode);
  1926. #ifdef CONFIG_DM_DEBUG_BLOCK_STACK_TRACING
  1927. stack_trace_print(b->stack_entries, b->stack_len, 1);
  1928. /* mark unclaimed to avoid WARN_ON at end of drop_buffers() */
  1929. atomic_set(&b->hold_count, 0);
  1930. #endif
  1931. return IT_NEXT;
  1932. }
  1933. static void drop_buffers(struct dm_bufio_client *c)
  1934. {
  1935. int i;
  1936. struct dm_buffer *b;
  1937. if (WARN_ON(dm_bufio_in_request()))
  1938. return; /* should never happen */
  1939. /*
  1940. * An optimization so that the buffers are not written one-by-one.
  1941. */
  1942. dm_bufio_write_dirty_buffers_async(c);
  1943. dm_bufio_lock(c);
  1944. while ((b = __get_unclaimed_buffer(c)))
  1945. __free_buffer_wake(b);
  1946. for (i = 0; i < LIST_SIZE; i++) {
  1947. bool warned = false;
  1948. cache_iterate(&c->cache, i, warn_leak, &warned);
  1949. }
  1950. #ifdef CONFIG_DM_DEBUG_BLOCK_STACK_TRACING
  1951. while ((b = __get_unclaimed_buffer(c)))
  1952. __free_buffer_wake(b);
  1953. #endif
  1954. for (i = 0; i < LIST_SIZE; i++)
  1955. WARN_ON(cache_count(&c->cache, i));
  1956. dm_bufio_unlock(c);
  1957. }
  1958. static unsigned long get_retain_buffers(struct dm_bufio_client *c)
  1959. {
  1960. unsigned long retain_bytes = READ_ONCE(dm_bufio_retain_bytes);
  1961. if (likely(c->sectors_per_block_bits >= 0))
  1962. retain_bytes >>= c->sectors_per_block_bits + SECTOR_SHIFT;
  1963. else
  1964. retain_bytes /= c->block_size;
  1965. return retain_bytes;
  1966. }
  1967. static void __scan(struct dm_bufio_client *c)
  1968. {
  1969. int l;
  1970. struct dm_buffer *b;
  1971. unsigned long freed = 0;
  1972. unsigned long retain_target = get_retain_buffers(c);
  1973. unsigned long count = cache_total(&c->cache);
  1974. for (l = 0; l < LIST_SIZE; l++) {
  1975. while (true) {
  1976. if (count - freed <= retain_target)
  1977. atomic_long_set(&c->need_shrink, 0);
  1978. if (!atomic_long_read(&c->need_shrink))
  1979. break;
  1980. b = cache_evict(&c->cache, l,
  1981. l == LIST_CLEAN ? is_clean : is_dirty, c);
  1982. if (!b)
  1983. break;
  1984. __make_buffer_clean(b);
  1985. __free_buffer_wake(b);
  1986. atomic_long_dec(&c->need_shrink);
  1987. freed++;
  1988. if (unlikely(freed % SCAN_RESCHED_CYCLE == 0)) {
  1989. dm_bufio_unlock(c);
  1990. cond_resched();
  1991. dm_bufio_lock(c);
  1992. }
  1993. }
  1994. }
  1995. }
  1996. static void shrink_work(struct work_struct *w)
  1997. {
  1998. struct dm_bufio_client *c = container_of(w, struct dm_bufio_client, shrink_work);
  1999. dm_bufio_lock(c);
  2000. __scan(c);
  2001. dm_bufio_unlock(c);
  2002. }
  2003. static unsigned long dm_bufio_shrink_scan(struct shrinker *shrink, struct shrink_control *sc)
  2004. {
  2005. struct dm_bufio_client *c;
  2006. c = shrink->private_data;
  2007. atomic_long_add(sc->nr_to_scan, &c->need_shrink);
  2008. queue_work(dm_bufio_wq, &c->shrink_work);
  2009. return sc->nr_to_scan;
  2010. }
  2011. static unsigned long dm_bufio_shrink_count(struct shrinker *shrink, struct shrink_control *sc)
  2012. {
  2013. struct dm_bufio_client *c = shrink->private_data;
  2014. unsigned long count = cache_total(&c->cache);
  2015. unsigned long retain_target = get_retain_buffers(c);
  2016. unsigned long queued_for_cleanup = atomic_long_read(&c->need_shrink);
  2017. if (unlikely(count < retain_target))
  2018. count = 0;
  2019. else
  2020. count -= retain_target;
  2021. if (unlikely(count < queued_for_cleanup))
  2022. count = 0;
  2023. else
  2024. count -= queued_for_cleanup;
  2025. return count;
  2026. }
  2027. /*
  2028. * Create the buffering interface
  2029. */
  2030. struct dm_bufio_client *dm_bufio_client_create(struct block_device *bdev, unsigned int block_size,
  2031. unsigned int reserved_buffers, unsigned int aux_size,
  2032. void (*alloc_callback)(struct dm_buffer *),
  2033. void (*write_callback)(struct dm_buffer *),
  2034. unsigned int flags)
  2035. {
  2036. int r;
  2037. unsigned int num_locks;
  2038. struct dm_bufio_client *c;
  2039. char slab_name[64];
  2040. static atomic_t seqno = ATOMIC_INIT(0);
  2041. if (!block_size || block_size & ((1 << SECTOR_SHIFT) - 1)) {
  2042. DMERR("%s: block size not specified or is not multiple of 512b", __func__);
  2043. r = -EINVAL;
  2044. goto bad_client;
  2045. }
  2046. num_locks = dm_num_hash_locks();
  2047. c = kzalloc(sizeof(*c) + (num_locks * sizeof(struct buffer_tree)), GFP_KERNEL);
  2048. if (!c) {
  2049. r = -ENOMEM;
  2050. goto bad_client;
  2051. }
  2052. cache_init(&c->cache, num_locks, (flags & DM_BUFIO_CLIENT_NO_SLEEP) != 0);
  2053. c->bdev = bdev;
  2054. c->block_size = block_size;
  2055. if (is_power_of_2(block_size))
  2056. c->sectors_per_block_bits = __ffs(block_size) - SECTOR_SHIFT;
  2057. else
  2058. c->sectors_per_block_bits = -1;
  2059. c->alloc_callback = alloc_callback;
  2060. c->write_callback = write_callback;
  2061. if (flags & DM_BUFIO_CLIENT_NO_SLEEP) {
  2062. c->no_sleep = true;
  2063. static_branch_inc(&no_sleep_enabled);
  2064. }
  2065. mutex_init(&c->lock);
  2066. spin_lock_init(&c->spinlock);
  2067. INIT_LIST_HEAD(&c->reserved_buffers);
  2068. c->need_reserved_buffers = reserved_buffers;
  2069. dm_bufio_set_minimum_buffers(c, DM_BUFIO_MIN_BUFFERS);
  2070. init_waitqueue_head(&c->free_buffer_wait);
  2071. c->async_write_error = 0;
  2072. c->dm_io = dm_io_client_create();
  2073. if (IS_ERR(c->dm_io)) {
  2074. r = PTR_ERR(c->dm_io);
  2075. goto bad_dm_io;
  2076. }
  2077. if (block_size <= KMALLOC_MAX_SIZE &&
  2078. (block_size < PAGE_SIZE || !is_power_of_2(block_size))) {
  2079. unsigned int align = min(1U << __ffs(block_size), (unsigned int)PAGE_SIZE);
  2080. snprintf(slab_name, sizeof(slab_name), "dm_bufio_cache-%u-%u",
  2081. block_size, atomic_inc_return(&seqno));
  2082. c->slab_cache = kmem_cache_create(slab_name, block_size, align,
  2083. SLAB_RECLAIM_ACCOUNT, NULL);
  2084. if (!c->slab_cache) {
  2085. r = -ENOMEM;
  2086. goto bad;
  2087. }
  2088. }
  2089. if (aux_size)
  2090. snprintf(slab_name, sizeof(slab_name), "dm_bufio_buffer-%u-%u",
  2091. aux_size, atomic_inc_return(&seqno));
  2092. else
  2093. snprintf(slab_name, sizeof(slab_name), "dm_bufio_buffer-%u",
  2094. atomic_inc_return(&seqno));
  2095. c->slab_buffer = kmem_cache_create(slab_name, sizeof(struct dm_buffer) + aux_size,
  2096. 0, SLAB_RECLAIM_ACCOUNT, NULL);
  2097. if (!c->slab_buffer) {
  2098. r = -ENOMEM;
  2099. goto bad;
  2100. }
  2101. while (c->need_reserved_buffers) {
  2102. struct dm_buffer *b = alloc_buffer(c, GFP_KERNEL);
  2103. if (!b) {
  2104. r = -ENOMEM;
  2105. goto bad;
  2106. }
  2107. __free_buffer_wake(b);
  2108. }
  2109. INIT_WORK(&c->shrink_work, shrink_work);
  2110. atomic_long_set(&c->need_shrink, 0);
  2111. c->shrinker = shrinker_alloc(0, "dm-bufio:(%u:%u)",
  2112. MAJOR(bdev->bd_dev), MINOR(bdev->bd_dev));
  2113. if (!c->shrinker) {
  2114. r = -ENOMEM;
  2115. goto bad;
  2116. }
  2117. c->shrinker->count_objects = dm_bufio_shrink_count;
  2118. c->shrinker->scan_objects = dm_bufio_shrink_scan;
  2119. c->shrinker->seeks = 1;
  2120. c->shrinker->batch = 0;
  2121. c->shrinker->private_data = c;
  2122. shrinker_register(c->shrinker);
  2123. mutex_lock(&dm_bufio_clients_lock);
  2124. dm_bufio_client_count++;
  2125. list_add(&c->client_list, &dm_bufio_all_clients);
  2126. __cache_size_refresh();
  2127. mutex_unlock(&dm_bufio_clients_lock);
  2128. return c;
  2129. bad:
  2130. while (!list_empty(&c->reserved_buffers)) {
  2131. struct dm_buffer *b = list_to_buffer(c->reserved_buffers.next);
  2132. list_del(&b->lru.list);
  2133. free_buffer(b);
  2134. }
  2135. kmem_cache_destroy(c->slab_cache);
  2136. kmem_cache_destroy(c->slab_buffer);
  2137. dm_io_client_destroy(c->dm_io);
  2138. bad_dm_io:
  2139. mutex_destroy(&c->lock);
  2140. if (c->no_sleep)
  2141. static_branch_dec(&no_sleep_enabled);
  2142. kfree(c);
  2143. bad_client:
  2144. return ERR_PTR(r);
  2145. }
  2146. EXPORT_SYMBOL_GPL(dm_bufio_client_create);
  2147. /*
  2148. * Free the buffering interface.
  2149. * It is required that there are no references on any buffers.
  2150. */
  2151. void dm_bufio_client_destroy(struct dm_bufio_client *c)
  2152. {
  2153. unsigned int i;
  2154. drop_buffers(c);
  2155. shrinker_free(c->shrinker);
  2156. flush_work(&c->shrink_work);
  2157. mutex_lock(&dm_bufio_clients_lock);
  2158. list_del(&c->client_list);
  2159. dm_bufio_client_count--;
  2160. __cache_size_refresh();
  2161. mutex_unlock(&dm_bufio_clients_lock);
  2162. WARN_ON(c->need_reserved_buffers);
  2163. while (!list_empty(&c->reserved_buffers)) {
  2164. struct dm_buffer *b = list_to_buffer(c->reserved_buffers.next);
  2165. list_del(&b->lru.list);
  2166. free_buffer(b);
  2167. }
  2168. for (i = 0; i < LIST_SIZE; i++)
  2169. if (cache_count(&c->cache, i))
  2170. DMERR("leaked buffer count %d: %lu", i, cache_count(&c->cache, i));
  2171. for (i = 0; i < LIST_SIZE; i++)
  2172. WARN_ON(cache_count(&c->cache, i));
  2173. cache_destroy(&c->cache);
  2174. kmem_cache_destroy(c->slab_cache);
  2175. kmem_cache_destroy(c->slab_buffer);
  2176. dm_io_client_destroy(c->dm_io);
  2177. mutex_destroy(&c->lock);
  2178. if (c->no_sleep)
  2179. static_branch_dec(&no_sleep_enabled);
  2180. kfree(c);
  2181. }
  2182. EXPORT_SYMBOL_GPL(dm_bufio_client_destroy);
  2183. void dm_bufio_client_reset(struct dm_bufio_client *c)
  2184. {
  2185. drop_buffers(c);
  2186. flush_work(&c->shrink_work);
  2187. }
  2188. EXPORT_SYMBOL_GPL(dm_bufio_client_reset);
  2189. void dm_bufio_set_sector_offset(struct dm_bufio_client *c, sector_t start)
  2190. {
  2191. c->start = start;
  2192. }
  2193. EXPORT_SYMBOL_GPL(dm_bufio_set_sector_offset);
  2194. /*--------------------------------------------------------------*/
  2195. static unsigned int get_max_age_hz(void)
  2196. {
  2197. unsigned int max_age = READ_ONCE(dm_bufio_max_age);
  2198. if (max_age > UINT_MAX / HZ)
  2199. max_age = UINT_MAX / HZ;
  2200. return max_age * HZ;
  2201. }
  2202. static bool older_than(struct dm_buffer *b, unsigned long age_hz)
  2203. {
  2204. return time_after_eq(jiffies, READ_ONCE(b->last_accessed) + age_hz);
  2205. }
  2206. struct evict_params {
  2207. gfp_t gfp;
  2208. unsigned long age_hz;
  2209. /*
  2210. * This gets updated with the largest last_accessed (ie. most
  2211. * recently used) of the evicted buffers. It will not be reinitialised
  2212. * by __evict_many(), so you can use it across multiple invocations.
  2213. */
  2214. unsigned long last_accessed;
  2215. };
  2216. /*
  2217. * We may not be able to evict this buffer if IO pending or the client
  2218. * is still using it.
  2219. *
  2220. * And if GFP_NOFS is used, we must not do any I/O because we hold
  2221. * dm_bufio_clients_lock and we would risk deadlock if the I/O gets
  2222. * rerouted to different bufio client.
  2223. */
  2224. static enum evict_result select_for_evict(struct dm_buffer *b, void *context)
  2225. {
  2226. struct evict_params *params = context;
  2227. if (!(params->gfp & __GFP_FS) ||
  2228. (static_branch_unlikely(&no_sleep_enabled) && b->c->no_sleep)) {
  2229. if (test_bit_acquire(B_READING, &b->state) ||
  2230. test_bit(B_WRITING, &b->state) ||
  2231. test_bit(B_DIRTY, &b->state))
  2232. return ER_DONT_EVICT;
  2233. }
  2234. return older_than(b, params->age_hz) ? ER_EVICT : ER_STOP;
  2235. }
  2236. static unsigned long __evict_many(struct dm_bufio_client *c,
  2237. struct evict_params *params,
  2238. int list_mode, unsigned long max_count)
  2239. {
  2240. unsigned long count;
  2241. unsigned long last_accessed;
  2242. struct dm_buffer *b;
  2243. for (count = 0; count < max_count; count++) {
  2244. b = cache_evict(&c->cache, list_mode, select_for_evict, params);
  2245. if (!b)
  2246. break;
  2247. last_accessed = READ_ONCE(b->last_accessed);
  2248. if (time_after_eq(params->last_accessed, last_accessed))
  2249. params->last_accessed = last_accessed;
  2250. __make_buffer_clean(b);
  2251. __free_buffer_wake(b);
  2252. if (need_resched()) {
  2253. dm_bufio_unlock(c);
  2254. cond_resched();
  2255. dm_bufio_lock(c);
  2256. }
  2257. }
  2258. return count;
  2259. }
  2260. static void evict_old_buffers(struct dm_bufio_client *c, unsigned long age_hz)
  2261. {
  2262. struct evict_params params = {.gfp = 0, .age_hz = age_hz, .last_accessed = 0};
  2263. unsigned long retain = get_retain_buffers(c);
  2264. unsigned long count;
  2265. LIST_HEAD(write_list);
  2266. dm_bufio_lock(c);
  2267. __check_watermark(c, &write_list);
  2268. if (unlikely(!list_empty(&write_list))) {
  2269. dm_bufio_unlock(c);
  2270. __flush_write_list(&write_list);
  2271. dm_bufio_lock(c);
  2272. }
  2273. count = cache_total(&c->cache);
  2274. if (count > retain)
  2275. __evict_many(c, &params, LIST_CLEAN, count - retain);
  2276. dm_bufio_unlock(c);
  2277. }
  2278. static void cleanup_old_buffers(void)
  2279. {
  2280. unsigned long max_age_hz = get_max_age_hz();
  2281. struct dm_bufio_client *c;
  2282. mutex_lock(&dm_bufio_clients_lock);
  2283. __cache_size_refresh();
  2284. list_for_each_entry(c, &dm_bufio_all_clients, client_list)
  2285. evict_old_buffers(c, max_age_hz);
  2286. mutex_unlock(&dm_bufio_clients_lock);
  2287. }
  2288. static void work_fn(struct work_struct *w)
  2289. {
  2290. cleanup_old_buffers();
  2291. queue_delayed_work(dm_bufio_wq, &dm_bufio_cleanup_old_work,
  2292. DM_BUFIO_WORK_TIMER_SECS * HZ);
  2293. }
  2294. /*--------------------------------------------------------------*/
  2295. /*
  2296. * Global cleanup tries to evict the oldest buffers from across _all_
  2297. * the clients. It does this by repeatedly evicting a few buffers from
  2298. * the client that holds the oldest buffer. It's approximate, but hopefully
  2299. * good enough.
  2300. */
  2301. static struct dm_bufio_client *__pop_client(void)
  2302. {
  2303. struct list_head *h;
  2304. if (list_empty(&dm_bufio_all_clients))
  2305. return NULL;
  2306. h = dm_bufio_all_clients.next;
  2307. list_del(h);
  2308. return container_of(h, struct dm_bufio_client, client_list);
  2309. }
  2310. /*
  2311. * Inserts the client in the global client list based on its
  2312. * 'oldest_buffer' field.
  2313. */
  2314. static void __insert_client(struct dm_bufio_client *new_client)
  2315. {
  2316. struct dm_bufio_client *c;
  2317. struct list_head *h = dm_bufio_all_clients.next;
  2318. while (h != &dm_bufio_all_clients) {
  2319. c = container_of(h, struct dm_bufio_client, client_list);
  2320. if (time_after_eq(c->oldest_buffer, new_client->oldest_buffer))
  2321. break;
  2322. h = h->next;
  2323. }
  2324. list_add_tail(&new_client->client_list, h);
  2325. }
  2326. static unsigned long __evict_a_few(unsigned long nr_buffers)
  2327. {
  2328. unsigned long count;
  2329. struct dm_bufio_client *c;
  2330. struct evict_params params = {
  2331. .gfp = GFP_KERNEL,
  2332. .age_hz = 0,
  2333. /* set to jiffies in case there are no buffers in this client */
  2334. .last_accessed = jiffies
  2335. };
  2336. c = __pop_client();
  2337. if (!c)
  2338. return 0;
  2339. dm_bufio_lock(c);
  2340. count = __evict_many(c, &params, LIST_CLEAN, nr_buffers);
  2341. dm_bufio_unlock(c);
  2342. if (count)
  2343. c->oldest_buffer = params.last_accessed;
  2344. __insert_client(c);
  2345. return count;
  2346. }
  2347. static void check_watermarks(void)
  2348. {
  2349. LIST_HEAD(write_list);
  2350. struct dm_bufio_client *c;
  2351. mutex_lock(&dm_bufio_clients_lock);
  2352. list_for_each_entry(c, &dm_bufio_all_clients, client_list) {
  2353. dm_bufio_lock(c);
  2354. __check_watermark(c, &write_list);
  2355. dm_bufio_unlock(c);
  2356. }
  2357. mutex_unlock(&dm_bufio_clients_lock);
  2358. __flush_write_list(&write_list);
  2359. }
  2360. static void evict_old(void)
  2361. {
  2362. unsigned long threshold = dm_bufio_cache_size -
  2363. dm_bufio_cache_size / DM_BUFIO_LOW_WATERMARK_RATIO;
  2364. mutex_lock(&dm_bufio_clients_lock);
  2365. while (dm_bufio_current_allocated > threshold) {
  2366. if (!__evict_a_few(64))
  2367. break;
  2368. cond_resched();
  2369. }
  2370. mutex_unlock(&dm_bufio_clients_lock);
  2371. }
  2372. static void do_global_cleanup(struct work_struct *w)
  2373. {
  2374. check_watermarks();
  2375. evict_old();
  2376. }
  2377. /*
  2378. *--------------------------------------------------------------
  2379. * Module setup
  2380. *--------------------------------------------------------------
  2381. */
  2382. /*
  2383. * This is called only once for the whole dm_bufio module.
  2384. * It initializes memory limit.
  2385. */
  2386. static int __init dm_bufio_init(void)
  2387. {
  2388. __u64 mem;
  2389. dm_bufio_allocated_kmem_cache = 0;
  2390. dm_bufio_allocated_get_free_pages = 0;
  2391. dm_bufio_allocated_vmalloc = 0;
  2392. dm_bufio_current_allocated = 0;
  2393. mem = (__u64)mult_frac(totalram_pages() - totalhigh_pages(),
  2394. DM_BUFIO_MEMORY_PERCENT, 100) << PAGE_SHIFT;
  2395. if (mem > ULONG_MAX)
  2396. mem = ULONG_MAX;
  2397. #ifdef CONFIG_MMU
  2398. if (mem > mult_frac(VMALLOC_TOTAL, DM_BUFIO_VMALLOC_PERCENT, 100))
  2399. mem = mult_frac(VMALLOC_TOTAL, DM_BUFIO_VMALLOC_PERCENT, 100);
  2400. #endif
  2401. dm_bufio_default_cache_size = mem;
  2402. mutex_lock(&dm_bufio_clients_lock);
  2403. __cache_size_refresh();
  2404. mutex_unlock(&dm_bufio_clients_lock);
  2405. dm_bufio_wq = alloc_workqueue("dm_bufio_cache", WQ_MEM_RECLAIM, 0);
  2406. if (!dm_bufio_wq)
  2407. return -ENOMEM;
  2408. INIT_DELAYED_WORK(&dm_bufio_cleanup_old_work, work_fn);
  2409. INIT_WORK(&dm_bufio_replacement_work, do_global_cleanup);
  2410. queue_delayed_work(dm_bufio_wq, &dm_bufio_cleanup_old_work,
  2411. DM_BUFIO_WORK_TIMER_SECS * HZ);
  2412. return 0;
  2413. }
  2414. /*
  2415. * This is called once when unloading the dm_bufio module.
  2416. */
  2417. static void __exit dm_bufio_exit(void)
  2418. {
  2419. int bug = 0;
  2420. cancel_delayed_work_sync(&dm_bufio_cleanup_old_work);
  2421. destroy_workqueue(dm_bufio_wq);
  2422. if (dm_bufio_client_count) {
  2423. DMCRIT("%s: dm_bufio_client_count leaked: %d",
  2424. __func__, dm_bufio_client_count);
  2425. bug = 1;
  2426. }
  2427. if (dm_bufio_current_allocated) {
  2428. DMCRIT("%s: dm_bufio_current_allocated leaked: %lu",
  2429. __func__, dm_bufio_current_allocated);
  2430. bug = 1;
  2431. }
  2432. if (dm_bufio_allocated_get_free_pages) {
  2433. DMCRIT("%s: dm_bufio_allocated_get_free_pages leaked: %lu",
  2434. __func__, dm_bufio_allocated_get_free_pages);
  2435. bug = 1;
  2436. }
  2437. if (dm_bufio_allocated_vmalloc) {
  2438. DMCRIT("%s: dm_bufio_vmalloc leaked: %lu",
  2439. __func__, dm_bufio_allocated_vmalloc);
  2440. bug = 1;
  2441. }
  2442. WARN_ON(bug); /* leaks are not worth crashing the system */
  2443. }
  2444. module_init(dm_bufio_init)
  2445. module_exit(dm_bufio_exit)
  2446. module_param_named(max_cache_size_bytes, dm_bufio_cache_size, ulong, 0644);
  2447. MODULE_PARM_DESC(max_cache_size_bytes, "Size of metadata cache");
  2448. module_param_named(max_age_seconds, dm_bufio_max_age, uint, 0644);
  2449. MODULE_PARM_DESC(max_age_seconds, "Max age of a buffer in seconds");
  2450. module_param_named(retain_bytes, dm_bufio_retain_bytes, ulong, 0644);
  2451. MODULE_PARM_DESC(retain_bytes, "Try to keep at least this many bytes cached in memory");
  2452. module_param_named(peak_allocated_bytes, dm_bufio_peak_allocated, ulong, 0644);
  2453. MODULE_PARM_DESC(peak_allocated_bytes, "Tracks the maximum allocated memory");
  2454. module_param_named(allocated_kmem_cache_bytes, dm_bufio_allocated_kmem_cache, ulong, 0444);
  2455. MODULE_PARM_DESC(allocated_kmem_cache_bytes, "Memory allocated with kmem_cache_alloc");
  2456. module_param_named(allocated_get_free_pages_bytes, dm_bufio_allocated_get_free_pages, ulong, 0444);
  2457. MODULE_PARM_DESC(allocated_get_free_pages_bytes, "Memory allocated with get_free_pages");
  2458. module_param_named(allocated_vmalloc_bytes, dm_bufio_allocated_vmalloc, ulong, 0444);
  2459. MODULE_PARM_DESC(allocated_vmalloc_bytes, "Memory allocated with vmalloc");
  2460. module_param_named(current_allocated_bytes, dm_bufio_current_allocated, ulong, 0444);
  2461. MODULE_PARM_DESC(current_allocated_bytes, "Memory currently used by the cache");
  2462. MODULE_AUTHOR("Mikulas Patocka <dm-devel@lists.linux.dev>");
  2463. MODULE_DESCRIPTION(DM_NAME " buffered I/O library");
  2464. MODULE_LICENSE("GPL");