dm-bufio.c 70 KB

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