dm-bufio.c 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191
  1. /*
  2. * Copyright (C) 2009-2011 Red Hat, Inc.
  3. *
  4. * Author: Mikulas Patocka <[email protected]>
  5. *
  6. * This file is released under the GPL.
  7. */
  8. #include <linux/dm-bufio.h>
  9. #include <linux/device-mapper.h>
  10. #include <linux/dm-io.h>
  11. #include <linux/slab.h>
  12. #include <linux/sched/mm.h>
  13. #include <linux/jiffies.h>
  14. #include <linux/vmalloc.h>
  15. #include <linux/shrinker.h>
  16. #include <linux/module.h>
  17. #include <linux/rbtree.h>
  18. #include <linux/stacktrace.h>
  19. #include <linux/jump_label.h>
  20. #include <trace/hooks/mm.h>
  21. #define DM_MSG_PREFIX "bufio"
  22. /*
  23. * Memory management policy:
  24. * Limit the number of buffers to DM_BUFIO_MEMORY_PERCENT of main memory
  25. * or DM_BUFIO_VMALLOC_PERCENT of vmalloc memory (whichever is lower).
  26. * Always allocate at least DM_BUFIO_MIN_BUFFERS buffers.
  27. * Start background writeback when there are DM_BUFIO_WRITEBACK_PERCENT
  28. * dirty buffers.
  29. */
  30. #define DM_BUFIO_MIN_BUFFERS 8
  31. #define DM_BUFIO_MEMORY_PERCENT 2
  32. #define DM_BUFIO_VMALLOC_PERCENT 25
  33. #define DM_BUFIO_WRITEBACK_RATIO 3
  34. #define DM_BUFIO_LOW_WATERMARK_RATIO 16
  35. /*
  36. * Check buffer ages in this interval (seconds)
  37. */
  38. #define DM_BUFIO_WORK_TIMER_SECS 30
  39. /*
  40. * Free buffers when they are older than this (seconds)
  41. */
  42. #define DM_BUFIO_DEFAULT_AGE_SECS 300
  43. /*
  44. * The nr of bytes of cached data to keep around.
  45. */
  46. #define DM_BUFIO_DEFAULT_RETAIN_BYTES (256 * 1024)
  47. /*
  48. * Align buffer writes to this boundary.
  49. * Tests show that SSDs have the highest IOPS when using 4k writes.
  50. */
  51. #define DM_BUFIO_WRITE_ALIGN 4096
  52. /*
  53. * dm_buffer->list_mode
  54. */
  55. #define LIST_CLEAN 0
  56. #define LIST_DIRTY 1
  57. #define LIST_SIZE 2
  58. /*
  59. * Linking of buffers:
  60. * All buffers are linked to buffer_tree with their node field.
  61. *
  62. * Clean buffers that are not being written (B_WRITING not set)
  63. * are linked to lru[LIST_CLEAN] with their lru_list field.
  64. *
  65. * Dirty and clean buffers that are being written are linked to
  66. * lru[LIST_DIRTY] with their lru_list field. When the write
  67. * finishes, the buffer cannot be relinked immediately (because we
  68. * are in an interrupt context and relinking requires process
  69. * context), so some clean-not-writing buffers can be held on
  70. * dirty_lru too. They are later added to lru in the process
  71. * context.
  72. */
  73. struct dm_bufio_client {
  74. struct mutex lock;
  75. spinlock_t spinlock;
  76. bool no_sleep;
  77. struct list_head lru[LIST_SIZE];
  78. unsigned long n_buffers[LIST_SIZE];
  79. struct block_device *bdev;
  80. unsigned int block_size;
  81. s8 sectors_per_block_bits;
  82. void (*alloc_callback)(struct dm_buffer *);
  83. void (*write_callback)(struct dm_buffer *);
  84. struct kmem_cache *slab_buffer;
  85. struct kmem_cache *slab_cache;
  86. struct dm_io_client *dm_io;
  87. struct list_head reserved_buffers;
  88. unsigned int need_reserved_buffers;
  89. unsigned int minimum_buffers;
  90. struct rb_root buffer_tree;
  91. wait_queue_head_t free_buffer_wait;
  92. sector_t start;
  93. int async_write_error;
  94. struct list_head client_list;
  95. struct shrinker shrinker;
  96. struct work_struct shrink_work;
  97. atomic_long_t need_shrink;
  98. };
  99. /*
  100. * Buffer state bits.
  101. */
  102. #define B_READING 0
  103. #define B_WRITING 1
  104. #define B_DIRTY 2
  105. /*
  106. * Describes how the block was allocated:
  107. * kmem_cache_alloc(), __get_free_pages() or vmalloc().
  108. * See the comment at alloc_buffer_data.
  109. */
  110. enum data_mode {
  111. DATA_MODE_SLAB = 0,
  112. DATA_MODE_GET_FREE_PAGES = 1,
  113. DATA_MODE_VMALLOC = 2,
  114. DATA_MODE_LIMIT = 3
  115. };
  116. struct dm_buffer {
  117. struct rb_node node;
  118. struct list_head lru_list;
  119. struct list_head global_list;
  120. sector_t block;
  121. void *data;
  122. unsigned char data_mode; /* DATA_MODE_* */
  123. unsigned char list_mode; /* LIST_* */
  124. blk_status_t read_error;
  125. blk_status_t write_error;
  126. unsigned int accessed;
  127. unsigned int hold_count;
  128. unsigned long state;
  129. unsigned long last_accessed;
  130. unsigned int dirty_start;
  131. unsigned int dirty_end;
  132. unsigned int write_start;
  133. unsigned int write_end;
  134. struct dm_bufio_client *c;
  135. struct list_head write_list;
  136. void (*end_io)(struct dm_buffer *, blk_status_t);
  137. #ifdef CONFIG_DM_DEBUG_BLOCK_STACK_TRACING
  138. #define MAX_STACK 10
  139. unsigned int stack_len;
  140. unsigned long stack_entries[MAX_STACK];
  141. #endif
  142. };
  143. static DEFINE_STATIC_KEY_FALSE(no_sleep_enabled);
  144. /*----------------------------------------------------------------*/
  145. #define dm_bufio_in_request() (!!current->bio_list)
  146. static void dm_bufio_lock(struct dm_bufio_client *c)
  147. {
  148. if (static_branch_unlikely(&no_sleep_enabled) && c->no_sleep)
  149. spin_lock_bh(&c->spinlock);
  150. else
  151. mutex_lock_nested(&c->lock, dm_bufio_in_request());
  152. }
  153. static int dm_bufio_trylock(struct dm_bufio_client *c)
  154. {
  155. if (static_branch_unlikely(&no_sleep_enabled) && c->no_sleep)
  156. return spin_trylock_bh(&c->spinlock);
  157. else
  158. return mutex_trylock(&c->lock);
  159. }
  160. static void dm_bufio_unlock(struct dm_bufio_client *c)
  161. {
  162. if (static_branch_unlikely(&no_sleep_enabled) && c->no_sleep)
  163. spin_unlock_bh(&c->spinlock);
  164. else
  165. mutex_unlock(&c->lock);
  166. }
  167. /*----------------------------------------------------------------*/
  168. /*
  169. * Default cache size: available memory divided by the ratio.
  170. */
  171. static unsigned long dm_bufio_default_cache_size;
  172. /*
  173. * Total cache size set by the user.
  174. */
  175. static unsigned long dm_bufio_cache_size;
  176. /*
  177. * A copy of dm_bufio_cache_size because dm_bufio_cache_size can change
  178. * at any time. If it disagrees, the user has changed cache size.
  179. */
  180. static unsigned long dm_bufio_cache_size_latch;
  181. static DEFINE_SPINLOCK(global_spinlock);
  182. static LIST_HEAD(global_queue);
  183. static unsigned long global_num = 0;
  184. /*
  185. * Buffers are freed after this timeout
  186. */
  187. static unsigned int dm_bufio_max_age = DM_BUFIO_DEFAULT_AGE_SECS;
  188. static unsigned long dm_bufio_retain_bytes = DM_BUFIO_DEFAULT_RETAIN_BYTES;
  189. static unsigned long dm_bufio_peak_allocated;
  190. static unsigned long dm_bufio_allocated_kmem_cache;
  191. static unsigned long dm_bufio_allocated_get_free_pages;
  192. static unsigned long dm_bufio_allocated_vmalloc;
  193. static unsigned long dm_bufio_current_allocated;
  194. /*----------------------------------------------------------------*/
  195. /*
  196. * The current number of clients.
  197. */
  198. static int dm_bufio_client_count;
  199. /*
  200. * The list of all clients.
  201. */
  202. static LIST_HEAD(dm_bufio_all_clients);
  203. /*
  204. * This mutex protects dm_bufio_cache_size_latch and dm_bufio_client_count
  205. */
  206. static DEFINE_MUTEX(dm_bufio_clients_lock);
  207. static struct workqueue_struct *dm_bufio_wq;
  208. static struct delayed_work dm_bufio_cleanup_old_work;
  209. static struct work_struct dm_bufio_replacement_work;
  210. #ifdef CONFIG_DM_DEBUG_BLOCK_STACK_TRACING
  211. static void buffer_record_stack(struct dm_buffer *b)
  212. {
  213. b->stack_len = stack_trace_save(b->stack_entries, MAX_STACK, 2);
  214. }
  215. #endif
  216. /*----------------------------------------------------------------
  217. * A red/black tree acts as an index for all the buffers.
  218. *--------------------------------------------------------------*/
  219. static struct dm_buffer *__find(struct dm_bufio_client *c, sector_t block)
  220. {
  221. struct rb_node *n = c->buffer_tree.rb_node;
  222. struct dm_buffer *b;
  223. while (n) {
  224. b = container_of(n, struct dm_buffer, node);
  225. if (b->block == block)
  226. return b;
  227. n = block < b->block ? n->rb_left : n->rb_right;
  228. }
  229. return NULL;
  230. }
  231. static struct dm_buffer *__find_next(struct dm_bufio_client *c, sector_t block)
  232. {
  233. struct rb_node *n = c->buffer_tree.rb_node;
  234. struct dm_buffer *b;
  235. struct dm_buffer *best = NULL;
  236. while (n) {
  237. b = container_of(n, struct dm_buffer, node);
  238. if (b->block == block)
  239. return b;
  240. if (block <= b->block) {
  241. n = n->rb_left;
  242. best = b;
  243. } else {
  244. n = n->rb_right;
  245. }
  246. }
  247. return best;
  248. }
  249. static void __insert(struct dm_bufio_client *c, struct dm_buffer *b)
  250. {
  251. struct rb_node **new = &c->buffer_tree.rb_node, *parent = NULL;
  252. struct dm_buffer *found;
  253. while (*new) {
  254. found = container_of(*new, struct dm_buffer, node);
  255. if (found->block == b->block) {
  256. BUG_ON(found != b);
  257. return;
  258. }
  259. parent = *new;
  260. new = b->block < found->block ?
  261. &found->node.rb_left : &found->node.rb_right;
  262. }
  263. rb_link_node(&b->node, parent, new);
  264. rb_insert_color(&b->node, &c->buffer_tree);
  265. }
  266. static void __remove(struct dm_bufio_client *c, struct dm_buffer *b)
  267. {
  268. rb_erase(&b->node, &c->buffer_tree);
  269. }
  270. /*----------------------------------------------------------------*/
  271. static void adjust_total_allocated(struct dm_buffer *b, bool unlink)
  272. {
  273. unsigned char data_mode;
  274. long diff;
  275. static unsigned long * const class_ptr[DATA_MODE_LIMIT] = {
  276. &dm_bufio_allocated_kmem_cache,
  277. &dm_bufio_allocated_get_free_pages,
  278. &dm_bufio_allocated_vmalloc,
  279. };
  280. data_mode = b->data_mode;
  281. diff = (long)b->c->block_size;
  282. if (unlink)
  283. diff = -diff;
  284. spin_lock(&global_spinlock);
  285. *class_ptr[data_mode] += diff;
  286. dm_bufio_current_allocated += diff;
  287. if (dm_bufio_current_allocated > dm_bufio_peak_allocated)
  288. dm_bufio_peak_allocated = dm_bufio_current_allocated;
  289. b->accessed = 1;
  290. if (!unlink) {
  291. list_add(&b->global_list, &global_queue);
  292. global_num++;
  293. if (dm_bufio_current_allocated > dm_bufio_cache_size)
  294. queue_work(dm_bufio_wq, &dm_bufio_replacement_work);
  295. } else {
  296. list_del(&b->global_list);
  297. global_num--;
  298. }
  299. spin_unlock(&global_spinlock);
  300. }
  301. /*
  302. * Change the number of clients and recalculate per-client limit.
  303. */
  304. static void __cache_size_refresh(void)
  305. {
  306. BUG_ON(!mutex_is_locked(&dm_bufio_clients_lock));
  307. BUG_ON(dm_bufio_client_count < 0);
  308. dm_bufio_cache_size_latch = READ_ONCE(dm_bufio_cache_size);
  309. /*
  310. * Use default if set to 0 and report the actual cache size used.
  311. */
  312. if (!dm_bufio_cache_size_latch) {
  313. (void)cmpxchg(&dm_bufio_cache_size, 0,
  314. dm_bufio_default_cache_size);
  315. dm_bufio_cache_size_latch = dm_bufio_default_cache_size;
  316. }
  317. }
  318. /*
  319. * Allocating buffer data.
  320. *
  321. * Small buffers are allocated with kmem_cache, to use space optimally.
  322. *
  323. * For large buffers, we choose between get_free_pages and vmalloc.
  324. * Each has advantages and disadvantages.
  325. *
  326. * __get_free_pages can randomly fail if the memory is fragmented.
  327. * __vmalloc won't randomly fail, but vmalloc space is limited (it may be
  328. * as low as 128M) so using it for caching is not appropriate.
  329. *
  330. * If the allocation may fail we use __get_free_pages. Memory fragmentation
  331. * won't have a fatal effect here, but it just causes flushes of some other
  332. * buffers and more I/O will be performed. Don't use __get_free_pages if it
  333. * always fails (i.e. order >= MAX_ORDER).
  334. *
  335. * If the allocation shouldn't fail we use __vmalloc. This is only for the
  336. * initial reserve allocation, so there's no risk of wasting all vmalloc
  337. * space.
  338. */
  339. static void *alloc_buffer_data(struct dm_bufio_client *c, gfp_t gfp_mask,
  340. unsigned char *data_mode)
  341. {
  342. if (unlikely(c->slab_cache != NULL)) {
  343. *data_mode = DATA_MODE_SLAB;
  344. return kmem_cache_alloc(c->slab_cache, gfp_mask);
  345. }
  346. if (c->block_size <= KMALLOC_MAX_SIZE &&
  347. gfp_mask & __GFP_NORETRY) {
  348. *data_mode = DATA_MODE_GET_FREE_PAGES;
  349. return (void *)__get_free_pages(gfp_mask,
  350. c->sectors_per_block_bits - (PAGE_SHIFT - SECTOR_SHIFT));
  351. }
  352. *data_mode = DATA_MODE_VMALLOC;
  353. /*
  354. * __vmalloc allocates the data pages and auxiliary structures with
  355. * gfp_flags that were specified, but pagetables are always allocated
  356. * with GFP_KERNEL, no matter what was specified as gfp_mask.
  357. *
  358. * Consequently, we must set per-process flag PF_MEMALLOC_NOIO so that
  359. * all allocations done by this process (including pagetables) are done
  360. * as if GFP_NOIO was specified.
  361. */
  362. if (gfp_mask & __GFP_NORETRY) {
  363. unsigned int noio_flag = memalloc_noio_save();
  364. void *ptr = __vmalloc(c->block_size, gfp_mask);
  365. memalloc_noio_restore(noio_flag);
  366. return ptr;
  367. }
  368. return __vmalloc(c->block_size, gfp_mask);
  369. }
  370. /*
  371. * Free buffer's data.
  372. */
  373. static void free_buffer_data(struct dm_bufio_client *c,
  374. void *data, unsigned char data_mode)
  375. {
  376. switch (data_mode) {
  377. case DATA_MODE_SLAB:
  378. kmem_cache_free(c->slab_cache, data);
  379. break;
  380. case DATA_MODE_GET_FREE_PAGES:
  381. free_pages((unsigned long)data,
  382. c->sectors_per_block_bits - (PAGE_SHIFT - SECTOR_SHIFT));
  383. break;
  384. case DATA_MODE_VMALLOC:
  385. vfree(data);
  386. break;
  387. default:
  388. DMCRIT("dm_bufio_free_buffer_data: bad data mode: %d",
  389. data_mode);
  390. BUG();
  391. }
  392. }
  393. /*
  394. * Allocate buffer and its data.
  395. */
  396. static struct dm_buffer *alloc_buffer(struct dm_bufio_client *c, gfp_t gfp_mask)
  397. {
  398. struct dm_buffer *b = kmem_cache_alloc(c->slab_buffer, gfp_mask);
  399. if (!b)
  400. return NULL;
  401. b->c = c;
  402. b->data = alloc_buffer_data(c, gfp_mask, &b->data_mode);
  403. if (!b->data) {
  404. kmem_cache_free(c->slab_buffer, b);
  405. return NULL;
  406. }
  407. #ifdef CONFIG_DM_DEBUG_BLOCK_STACK_TRACING
  408. b->stack_len = 0;
  409. #endif
  410. return b;
  411. }
  412. /*
  413. * Free buffer and its data.
  414. */
  415. static void free_buffer(struct dm_buffer *b)
  416. {
  417. struct dm_bufio_client *c = b->c;
  418. free_buffer_data(c, b->data, b->data_mode);
  419. kmem_cache_free(c->slab_buffer, b);
  420. }
  421. /*
  422. * Link buffer to the buffer tree and clean or dirty queue.
  423. */
  424. static void __link_buffer(struct dm_buffer *b, sector_t block, int dirty)
  425. {
  426. struct dm_bufio_client *c = b->c;
  427. c->n_buffers[dirty]++;
  428. b->block = block;
  429. b->list_mode = dirty;
  430. list_add(&b->lru_list, &c->lru[dirty]);
  431. __insert(b->c, b);
  432. b->last_accessed = jiffies;
  433. adjust_total_allocated(b, false);
  434. }
  435. /*
  436. * Unlink buffer from the buffer tree and dirty or clean queue.
  437. */
  438. static void __unlink_buffer(struct dm_buffer *b)
  439. {
  440. struct dm_bufio_client *c = b->c;
  441. BUG_ON(!c->n_buffers[b->list_mode]);
  442. c->n_buffers[b->list_mode]--;
  443. __remove(b->c, b);
  444. list_del(&b->lru_list);
  445. adjust_total_allocated(b, true);
  446. }
  447. /*
  448. * Place the buffer to the head of dirty or clean LRU queue.
  449. */
  450. static void __relink_lru(struct dm_buffer *b, int dirty)
  451. {
  452. struct dm_bufio_client *c = b->c;
  453. b->accessed = 1;
  454. BUG_ON(!c->n_buffers[b->list_mode]);
  455. c->n_buffers[b->list_mode]--;
  456. c->n_buffers[dirty]++;
  457. b->list_mode = dirty;
  458. list_move(&b->lru_list, &c->lru[dirty]);
  459. b->last_accessed = jiffies;
  460. }
  461. /*----------------------------------------------------------------
  462. * Submit I/O on the buffer.
  463. *
  464. * Bio interface is faster but it has some problems:
  465. * the vector list is limited (increasing this limit increases
  466. * memory-consumption per buffer, so it is not viable);
  467. *
  468. * the memory must be direct-mapped, not vmalloced;
  469. *
  470. * If the buffer is small enough (up to DM_BUFIO_INLINE_VECS pages) and
  471. * it is not vmalloced, try using the bio interface.
  472. *
  473. * If the buffer is big, if it is vmalloced or if the underlying device
  474. * rejects the bio because it is too large, use dm-io layer to do the I/O.
  475. * The dm-io layer splits the I/O into multiple requests, avoiding the above
  476. * shortcomings.
  477. *--------------------------------------------------------------*/
  478. /*
  479. * dm-io completion routine. It just calls b->bio.bi_end_io, pretending
  480. * that the request was handled directly with bio interface.
  481. */
  482. static void dmio_complete(unsigned long error, void *context)
  483. {
  484. struct dm_buffer *b = context;
  485. b->end_io(b, unlikely(error != 0) ? BLK_STS_IOERR : 0);
  486. }
  487. static void use_dmio(struct dm_buffer *b, enum req_op op, sector_t sector,
  488. unsigned int n_sectors, unsigned int offset)
  489. {
  490. int r;
  491. struct dm_io_request io_req = {
  492. .bi_opf = op,
  493. .notify.fn = dmio_complete,
  494. .notify.context = b,
  495. .client = b->c->dm_io,
  496. };
  497. struct dm_io_region region = {
  498. .bdev = b->c->bdev,
  499. .sector = sector,
  500. .count = n_sectors,
  501. };
  502. if (b->data_mode != DATA_MODE_VMALLOC) {
  503. io_req.mem.type = DM_IO_KMEM;
  504. io_req.mem.ptr.addr = (char *)b->data + offset;
  505. } else {
  506. io_req.mem.type = DM_IO_VMA;
  507. io_req.mem.ptr.vma = (char *)b->data + offset;
  508. }
  509. r = dm_io(&io_req, 1, &region, NULL);
  510. if (unlikely(r))
  511. b->end_io(b, errno_to_blk_status(r));
  512. }
  513. static void bio_complete(struct bio *bio)
  514. {
  515. struct dm_buffer *b = bio->bi_private;
  516. blk_status_t status = bio->bi_status;
  517. bio_uninit(bio);
  518. kfree(bio);
  519. b->end_io(b, status);
  520. }
  521. static void use_bio(struct dm_buffer *b, enum req_op op, sector_t sector,
  522. unsigned int n_sectors, unsigned int offset)
  523. {
  524. struct bio *bio;
  525. char *ptr;
  526. unsigned int vec_size, len;
  527. vec_size = b->c->block_size >> PAGE_SHIFT;
  528. if (unlikely(b->c->sectors_per_block_bits < PAGE_SHIFT - SECTOR_SHIFT))
  529. vec_size += 2;
  530. bio = bio_kmalloc(vec_size, GFP_NOWAIT | __GFP_NORETRY | __GFP_NOWARN);
  531. if (!bio) {
  532. dmio:
  533. use_dmio(b, op, sector, n_sectors, offset);
  534. return;
  535. }
  536. bio_init(bio, b->c->bdev, bio->bi_inline_vecs, vec_size, op);
  537. bio->bi_iter.bi_sector = sector;
  538. bio->bi_end_io = bio_complete;
  539. bio->bi_private = b;
  540. ptr = (char *)b->data + offset;
  541. len = n_sectors << SECTOR_SHIFT;
  542. do {
  543. unsigned int this_step = min((unsigned int)(PAGE_SIZE - offset_in_page(ptr)), len);
  544. if (!bio_add_page(bio, virt_to_page(ptr), this_step,
  545. offset_in_page(ptr))) {
  546. bio_put(bio);
  547. goto dmio;
  548. }
  549. len -= this_step;
  550. ptr += this_step;
  551. } while (len > 0);
  552. submit_bio(bio);
  553. }
  554. static inline sector_t block_to_sector(struct dm_bufio_client *c, sector_t block)
  555. {
  556. sector_t sector;
  557. if (likely(c->sectors_per_block_bits >= 0))
  558. sector = block << c->sectors_per_block_bits;
  559. else
  560. sector = block * (c->block_size >> SECTOR_SHIFT);
  561. sector += c->start;
  562. return sector;
  563. }
  564. static void submit_io(struct dm_buffer *b, enum req_op op,
  565. void (*end_io)(struct dm_buffer *, blk_status_t))
  566. {
  567. unsigned int n_sectors;
  568. sector_t sector;
  569. unsigned int offset, end;
  570. b->end_io = end_io;
  571. sector = block_to_sector(b->c, b->block);
  572. if (op != REQ_OP_WRITE) {
  573. n_sectors = b->c->block_size >> SECTOR_SHIFT;
  574. offset = 0;
  575. } else {
  576. if (b->c->write_callback)
  577. b->c->write_callback(b);
  578. offset = b->write_start;
  579. end = b->write_end;
  580. offset &= -DM_BUFIO_WRITE_ALIGN;
  581. end += DM_BUFIO_WRITE_ALIGN - 1;
  582. end &= -DM_BUFIO_WRITE_ALIGN;
  583. if (unlikely(end > b->c->block_size))
  584. end = b->c->block_size;
  585. sector += offset >> SECTOR_SHIFT;
  586. n_sectors = (end - offset) >> SECTOR_SHIFT;
  587. }
  588. if (b->data_mode != DATA_MODE_VMALLOC)
  589. use_bio(b, op, sector, n_sectors, offset);
  590. else
  591. use_dmio(b, op, sector, n_sectors, offset);
  592. }
  593. /*----------------------------------------------------------------
  594. * Writing dirty buffers
  595. *--------------------------------------------------------------*/
  596. /*
  597. * The endio routine for write.
  598. *
  599. * Set the error, clear B_WRITING bit and wake anyone who was waiting on
  600. * it.
  601. */
  602. static void write_endio(struct dm_buffer *b, blk_status_t status)
  603. {
  604. b->write_error = status;
  605. if (unlikely(status)) {
  606. struct dm_bufio_client *c = b->c;
  607. (void)cmpxchg(&c->async_write_error, 0,
  608. blk_status_to_errno(status));
  609. }
  610. BUG_ON(!test_bit(B_WRITING, &b->state));
  611. smp_mb__before_atomic();
  612. clear_bit(B_WRITING, &b->state);
  613. smp_mb__after_atomic();
  614. wake_up_bit(&b->state, B_WRITING);
  615. }
  616. /*
  617. * Initiate a write on a dirty buffer, but don't wait for it.
  618. *
  619. * - If the buffer is not dirty, exit.
  620. * - If there some previous write going on, wait for it to finish (we can't
  621. * have two writes on the same buffer simultaneously).
  622. * - Submit our write and don't wait on it. We set B_WRITING indicating
  623. * that there is a write in progress.
  624. */
  625. static void __write_dirty_buffer(struct dm_buffer *b,
  626. struct list_head *write_list)
  627. {
  628. if (!test_bit(B_DIRTY, &b->state))
  629. return;
  630. clear_bit(B_DIRTY, &b->state);
  631. wait_on_bit_lock_io(&b->state, B_WRITING, TASK_UNINTERRUPTIBLE);
  632. b->write_start = b->dirty_start;
  633. b->write_end = b->dirty_end;
  634. if (!write_list)
  635. submit_io(b, REQ_OP_WRITE, write_endio);
  636. else
  637. list_add_tail(&b->write_list, write_list);
  638. }
  639. static void __flush_write_list(struct list_head *write_list)
  640. {
  641. struct blk_plug plug;
  642. blk_start_plug(&plug);
  643. while (!list_empty(write_list)) {
  644. struct dm_buffer *b =
  645. list_entry(write_list->next, struct dm_buffer, write_list);
  646. list_del(&b->write_list);
  647. submit_io(b, REQ_OP_WRITE, write_endio);
  648. cond_resched();
  649. }
  650. blk_finish_plug(&plug);
  651. }
  652. /*
  653. * Wait until any activity on the buffer finishes. Possibly write the
  654. * buffer if it is dirty. When this function finishes, there is no I/O
  655. * running on the buffer and the buffer is not dirty.
  656. */
  657. static void __make_buffer_clean(struct dm_buffer *b)
  658. {
  659. BUG_ON(b->hold_count);
  660. /* smp_load_acquire() pairs with read_endio()'s smp_mb__before_atomic() */
  661. if (!smp_load_acquire(&b->state)) /* fast case */
  662. return;
  663. wait_on_bit_io(&b->state, B_READING, TASK_UNINTERRUPTIBLE);
  664. __write_dirty_buffer(b, NULL);
  665. wait_on_bit_io(&b->state, B_WRITING, TASK_UNINTERRUPTIBLE);
  666. }
  667. /*
  668. * Find some buffer that is not held by anybody, clean it, unlink it and
  669. * return it.
  670. */
  671. static struct dm_buffer *__get_unclaimed_buffer(struct dm_bufio_client *c)
  672. {
  673. struct dm_buffer *b;
  674. list_for_each_entry_reverse(b, &c->lru[LIST_CLEAN], lru_list) {
  675. BUG_ON(test_bit(B_WRITING, &b->state));
  676. BUG_ON(test_bit(B_DIRTY, &b->state));
  677. if (static_branch_unlikely(&no_sleep_enabled) && c->no_sleep &&
  678. unlikely(test_bit_acquire(B_READING, &b->state)))
  679. continue;
  680. if (!b->hold_count) {
  681. __make_buffer_clean(b);
  682. __unlink_buffer(b);
  683. return b;
  684. }
  685. cond_resched();
  686. }
  687. if (static_branch_unlikely(&no_sleep_enabled) && c->no_sleep)
  688. return NULL;
  689. list_for_each_entry_reverse(b, &c->lru[LIST_DIRTY], lru_list) {
  690. BUG_ON(test_bit(B_READING, &b->state));
  691. if (!b->hold_count) {
  692. __make_buffer_clean(b);
  693. __unlink_buffer(b);
  694. return b;
  695. }
  696. cond_resched();
  697. }
  698. return NULL;
  699. }
  700. /*
  701. * Wait until some other threads free some buffer or release hold count on
  702. * some buffer.
  703. *
  704. * This function is entered with c->lock held, drops it and regains it
  705. * before exiting.
  706. */
  707. static void __wait_for_free_buffer(struct dm_bufio_client *c)
  708. {
  709. DECLARE_WAITQUEUE(wait, current);
  710. add_wait_queue(&c->free_buffer_wait, &wait);
  711. set_current_state(TASK_UNINTERRUPTIBLE);
  712. dm_bufio_unlock(c);
  713. io_schedule();
  714. remove_wait_queue(&c->free_buffer_wait, &wait);
  715. dm_bufio_lock(c);
  716. }
  717. enum new_flag {
  718. NF_FRESH = 0,
  719. NF_READ = 1,
  720. NF_GET = 2,
  721. NF_PREFETCH = 3
  722. };
  723. /*
  724. * Allocate a new buffer. If the allocation is not possible, wait until
  725. * some other thread frees a buffer.
  726. *
  727. * May drop the lock and regain it.
  728. */
  729. static struct dm_buffer *__alloc_buffer_wait_no_callback(struct dm_bufio_client *c, enum new_flag nf)
  730. {
  731. struct dm_buffer *b;
  732. bool tried_noio_alloc = false;
  733. /*
  734. * dm-bufio is resistant to allocation failures (it just keeps
  735. * one buffer reserved in cases all the allocations fail).
  736. * So set flags to not try too hard:
  737. * GFP_NOWAIT: don't wait; if we need to sleep we'll release our
  738. * mutex and wait ourselves.
  739. * __GFP_NORETRY: don't retry and rather return failure
  740. * __GFP_NOMEMALLOC: don't use emergency reserves
  741. * __GFP_NOWARN: don't print a warning in case of failure
  742. *
  743. * For debugging, if we set the cache size to 1, no new buffers will
  744. * be allocated.
  745. */
  746. while (1) {
  747. if (dm_bufio_cache_size_latch != 1) {
  748. b = alloc_buffer(c, GFP_NOWAIT | __GFP_NORETRY | __GFP_NOMEMALLOC | __GFP_NOWARN);
  749. if (b)
  750. return b;
  751. }
  752. if (nf == NF_PREFETCH)
  753. return NULL;
  754. if (dm_bufio_cache_size_latch != 1 && !tried_noio_alloc) {
  755. dm_bufio_unlock(c);
  756. b = alloc_buffer(c, GFP_NOIO | __GFP_NORETRY | __GFP_NOMEMALLOC | __GFP_NOWARN);
  757. dm_bufio_lock(c);
  758. if (b)
  759. return b;
  760. tried_noio_alloc = true;
  761. }
  762. if (!list_empty(&c->reserved_buffers)) {
  763. b = list_entry(c->reserved_buffers.next,
  764. struct dm_buffer, lru_list);
  765. list_del(&b->lru_list);
  766. c->need_reserved_buffers++;
  767. return b;
  768. }
  769. b = __get_unclaimed_buffer(c);
  770. if (b)
  771. return b;
  772. __wait_for_free_buffer(c);
  773. }
  774. }
  775. static struct dm_buffer *__alloc_buffer_wait(struct dm_bufio_client *c, enum new_flag nf)
  776. {
  777. struct dm_buffer *b = __alloc_buffer_wait_no_callback(c, nf);
  778. if (!b)
  779. return NULL;
  780. if (c->alloc_callback)
  781. c->alloc_callback(b);
  782. return b;
  783. }
  784. /*
  785. * Free a buffer and wake other threads waiting for free buffers.
  786. */
  787. static void __free_buffer_wake(struct dm_buffer *b)
  788. {
  789. struct dm_bufio_client *c = b->c;
  790. if (!c->need_reserved_buffers)
  791. free_buffer(b);
  792. else {
  793. list_add(&b->lru_list, &c->reserved_buffers);
  794. c->need_reserved_buffers--;
  795. }
  796. wake_up(&c->free_buffer_wait);
  797. }
  798. static void __write_dirty_buffers_async(struct dm_bufio_client *c, int no_wait,
  799. struct list_head *write_list)
  800. {
  801. struct dm_buffer *b, *tmp;
  802. list_for_each_entry_safe_reverse(b, tmp, &c->lru[LIST_DIRTY], lru_list) {
  803. BUG_ON(test_bit(B_READING, &b->state));
  804. if (!test_bit(B_DIRTY, &b->state) &&
  805. !test_bit(B_WRITING, &b->state)) {
  806. __relink_lru(b, LIST_CLEAN);
  807. continue;
  808. }
  809. if (no_wait && test_bit(B_WRITING, &b->state))
  810. return;
  811. __write_dirty_buffer(b, write_list);
  812. cond_resched();
  813. }
  814. }
  815. /*
  816. * Check if we're over watermark.
  817. * If we are over threshold_buffers, start freeing buffers.
  818. * If we're over "limit_buffers", block until we get under the limit.
  819. */
  820. static void __check_watermark(struct dm_bufio_client *c,
  821. struct list_head *write_list)
  822. {
  823. if (c->n_buffers[LIST_DIRTY] > c->n_buffers[LIST_CLEAN] * DM_BUFIO_WRITEBACK_RATIO)
  824. __write_dirty_buffers_async(c, 1, write_list);
  825. }
  826. /*----------------------------------------------------------------
  827. * Getting a buffer
  828. *--------------------------------------------------------------*/
  829. static struct dm_buffer *__bufio_new(struct dm_bufio_client *c, sector_t block,
  830. enum new_flag nf, int *need_submit,
  831. struct list_head *write_list)
  832. {
  833. struct dm_buffer *b, *new_b = NULL;
  834. *need_submit = 0;
  835. b = __find(c, block);
  836. if (b)
  837. goto found_buffer;
  838. if (nf == NF_GET)
  839. return NULL;
  840. new_b = __alloc_buffer_wait(c, nf);
  841. if (!new_b)
  842. return NULL;
  843. /*
  844. * We've had a period where the mutex was unlocked, so need to
  845. * recheck the buffer tree.
  846. */
  847. b = __find(c, block);
  848. if (b) {
  849. __free_buffer_wake(new_b);
  850. goto found_buffer;
  851. }
  852. __check_watermark(c, write_list);
  853. b = new_b;
  854. b->hold_count = 1;
  855. b->read_error = 0;
  856. b->write_error = 0;
  857. __link_buffer(b, block, LIST_CLEAN);
  858. if (nf == NF_FRESH) {
  859. b->state = 0;
  860. return b;
  861. }
  862. b->state = 1 << B_READING;
  863. *need_submit = 1;
  864. return b;
  865. found_buffer:
  866. if (nf == NF_PREFETCH)
  867. return NULL;
  868. /*
  869. * Note: it is essential that we don't wait for the buffer to be
  870. * read if dm_bufio_get function is used. Both dm_bufio_get and
  871. * dm_bufio_prefetch can be used in the driver request routine.
  872. * If the user called both dm_bufio_prefetch and dm_bufio_get on
  873. * the same buffer, it would deadlock if we waited.
  874. */
  875. if (nf == NF_GET && unlikely(test_bit_acquire(B_READING, &b->state)))
  876. return NULL;
  877. b->hold_count++;
  878. __relink_lru(b, test_bit(B_DIRTY, &b->state) ||
  879. test_bit(B_WRITING, &b->state));
  880. return b;
  881. }
  882. /*
  883. * The endio routine for reading: set the error, clear the bit and wake up
  884. * anyone waiting on the buffer.
  885. */
  886. static void read_endio(struct dm_buffer *b, blk_status_t status)
  887. {
  888. b->read_error = status;
  889. BUG_ON(!test_bit(B_READING, &b->state));
  890. smp_mb__before_atomic();
  891. clear_bit(B_READING, &b->state);
  892. smp_mb__after_atomic();
  893. wake_up_bit(&b->state, B_READING);
  894. }
  895. /*
  896. * A common routine for dm_bufio_new and dm_bufio_read. Operation of these
  897. * functions is similar except that dm_bufio_new doesn't read the
  898. * buffer from the disk (assuming that the caller overwrites all the data
  899. * and uses dm_bufio_mark_buffer_dirty to write new data back).
  900. */
  901. static void *new_read(struct dm_bufio_client *c, sector_t block,
  902. enum new_flag nf, struct dm_buffer **bp)
  903. {
  904. int need_submit;
  905. struct dm_buffer *b;
  906. LIST_HEAD(write_list);
  907. dm_bufio_lock(c);
  908. b = __bufio_new(c, block, nf, &need_submit, &write_list);
  909. #ifdef CONFIG_DM_DEBUG_BLOCK_STACK_TRACING
  910. if (b && b->hold_count == 1)
  911. buffer_record_stack(b);
  912. #endif
  913. dm_bufio_unlock(c);
  914. __flush_write_list(&write_list);
  915. if (!b)
  916. return NULL;
  917. if (need_submit)
  918. submit_io(b, REQ_OP_READ, read_endio);
  919. wait_on_bit_io(&b->state, B_READING, TASK_UNINTERRUPTIBLE);
  920. if (b->read_error) {
  921. int error = blk_status_to_errno(b->read_error);
  922. dm_bufio_release(b);
  923. return ERR_PTR(error);
  924. }
  925. *bp = b;
  926. return b->data;
  927. }
  928. void *dm_bufio_get(struct dm_bufio_client *c, sector_t block,
  929. struct dm_buffer **bp)
  930. {
  931. return new_read(c, block, NF_GET, bp);
  932. }
  933. EXPORT_SYMBOL_GPL(dm_bufio_get);
  934. void *dm_bufio_read(struct dm_bufio_client *c, sector_t block,
  935. struct dm_buffer **bp)
  936. {
  937. BUG_ON(dm_bufio_in_request());
  938. return new_read(c, block, NF_READ, bp);
  939. }
  940. EXPORT_SYMBOL_GPL(dm_bufio_read);
  941. void *dm_bufio_new(struct dm_bufio_client *c, sector_t block,
  942. struct dm_buffer **bp)
  943. {
  944. BUG_ON(dm_bufio_in_request());
  945. return new_read(c, block, NF_FRESH, bp);
  946. }
  947. EXPORT_SYMBOL_GPL(dm_bufio_new);
  948. void dm_bufio_prefetch(struct dm_bufio_client *c,
  949. sector_t block, unsigned int n_blocks)
  950. {
  951. struct blk_plug plug;
  952. LIST_HEAD(write_list);
  953. BUG_ON(dm_bufio_in_request());
  954. blk_start_plug(&plug);
  955. dm_bufio_lock(c);
  956. for (; n_blocks--; block++) {
  957. int need_submit;
  958. struct dm_buffer *b;
  959. b = __bufio_new(c, block, NF_PREFETCH, &need_submit,
  960. &write_list);
  961. if (unlikely(!list_empty(&write_list))) {
  962. dm_bufio_unlock(c);
  963. blk_finish_plug(&plug);
  964. __flush_write_list(&write_list);
  965. blk_start_plug(&plug);
  966. dm_bufio_lock(c);
  967. }
  968. if (unlikely(b != NULL)) {
  969. dm_bufio_unlock(c);
  970. if (need_submit)
  971. submit_io(b, REQ_OP_READ, read_endio);
  972. dm_bufio_release(b);
  973. cond_resched();
  974. if (!n_blocks)
  975. goto flush_plug;
  976. dm_bufio_lock(c);
  977. }
  978. }
  979. dm_bufio_unlock(c);
  980. flush_plug:
  981. blk_finish_plug(&plug);
  982. }
  983. EXPORT_SYMBOL_GPL(dm_bufio_prefetch);
  984. void dm_bufio_release(struct dm_buffer *b)
  985. {
  986. struct dm_bufio_client *c = b->c;
  987. dm_bufio_lock(c);
  988. BUG_ON(!b->hold_count);
  989. b->hold_count--;
  990. if (!b->hold_count) {
  991. wake_up(&c->free_buffer_wait);
  992. /*
  993. * If there were errors on the buffer, and the buffer is not
  994. * to be written, free the buffer. There is no point in caching
  995. * invalid buffer.
  996. */
  997. if ((b->read_error || b->write_error) &&
  998. !test_bit_acquire(B_READING, &b->state) &&
  999. !test_bit(B_WRITING, &b->state) &&
  1000. !test_bit(B_DIRTY, &b->state)) {
  1001. __unlink_buffer(b);
  1002. __free_buffer_wake(b);
  1003. }
  1004. }
  1005. dm_bufio_unlock(c);
  1006. }
  1007. EXPORT_SYMBOL_GPL(dm_bufio_release);
  1008. void dm_bufio_mark_partial_buffer_dirty(struct dm_buffer *b,
  1009. unsigned int start, unsigned int end)
  1010. {
  1011. struct dm_bufio_client *c = b->c;
  1012. BUG_ON(start >= end);
  1013. BUG_ON(end > b->c->block_size);
  1014. dm_bufio_lock(c);
  1015. BUG_ON(test_bit(B_READING, &b->state));
  1016. if (!test_and_set_bit(B_DIRTY, &b->state)) {
  1017. b->dirty_start = start;
  1018. b->dirty_end = end;
  1019. __relink_lru(b, LIST_DIRTY);
  1020. } else {
  1021. if (start < b->dirty_start)
  1022. b->dirty_start = start;
  1023. if (end > b->dirty_end)
  1024. b->dirty_end = end;
  1025. }
  1026. dm_bufio_unlock(c);
  1027. }
  1028. EXPORT_SYMBOL_GPL(dm_bufio_mark_partial_buffer_dirty);
  1029. void dm_bufio_mark_buffer_dirty(struct dm_buffer *b)
  1030. {
  1031. dm_bufio_mark_partial_buffer_dirty(b, 0, b->c->block_size);
  1032. }
  1033. EXPORT_SYMBOL_GPL(dm_bufio_mark_buffer_dirty);
  1034. void dm_bufio_write_dirty_buffers_async(struct dm_bufio_client *c)
  1035. {
  1036. LIST_HEAD(write_list);
  1037. BUG_ON(dm_bufio_in_request());
  1038. dm_bufio_lock(c);
  1039. __write_dirty_buffers_async(c, 0, &write_list);
  1040. dm_bufio_unlock(c);
  1041. __flush_write_list(&write_list);
  1042. }
  1043. EXPORT_SYMBOL_GPL(dm_bufio_write_dirty_buffers_async);
  1044. /*
  1045. * For performance, it is essential that the buffers are written asynchronously
  1046. * and simultaneously (so that the block layer can merge the writes) and then
  1047. * waited upon.
  1048. *
  1049. * Finally, we flush hardware disk cache.
  1050. */
  1051. int dm_bufio_write_dirty_buffers(struct dm_bufio_client *c)
  1052. {
  1053. int a, f;
  1054. unsigned long buffers_processed = 0;
  1055. struct dm_buffer *b, *tmp;
  1056. LIST_HEAD(write_list);
  1057. dm_bufio_lock(c);
  1058. __write_dirty_buffers_async(c, 0, &write_list);
  1059. dm_bufio_unlock(c);
  1060. __flush_write_list(&write_list);
  1061. dm_bufio_lock(c);
  1062. again:
  1063. list_for_each_entry_safe_reverse(b, tmp, &c->lru[LIST_DIRTY], lru_list) {
  1064. int dropped_lock = 0;
  1065. if (buffers_processed < c->n_buffers[LIST_DIRTY])
  1066. buffers_processed++;
  1067. BUG_ON(test_bit(B_READING, &b->state));
  1068. if (test_bit(B_WRITING, &b->state)) {
  1069. if (buffers_processed < c->n_buffers[LIST_DIRTY]) {
  1070. dropped_lock = 1;
  1071. b->hold_count++;
  1072. dm_bufio_unlock(c);
  1073. wait_on_bit_io(&b->state, B_WRITING,
  1074. TASK_UNINTERRUPTIBLE);
  1075. dm_bufio_lock(c);
  1076. b->hold_count--;
  1077. } else
  1078. wait_on_bit_io(&b->state, B_WRITING,
  1079. TASK_UNINTERRUPTIBLE);
  1080. }
  1081. if (!test_bit(B_DIRTY, &b->state) &&
  1082. !test_bit(B_WRITING, &b->state))
  1083. __relink_lru(b, LIST_CLEAN);
  1084. cond_resched();
  1085. /*
  1086. * If we dropped the lock, the list is no longer consistent,
  1087. * so we must restart the search.
  1088. *
  1089. * In the most common case, the buffer just processed is
  1090. * relinked to the clean list, so we won't loop scanning the
  1091. * same buffer again and again.
  1092. *
  1093. * This may livelock if there is another thread simultaneously
  1094. * dirtying buffers, so we count the number of buffers walked
  1095. * and if it exceeds the total number of buffers, it means that
  1096. * someone is doing some writes simultaneously with us. In
  1097. * this case, stop, dropping the lock.
  1098. */
  1099. if (dropped_lock)
  1100. goto again;
  1101. }
  1102. wake_up(&c->free_buffer_wait);
  1103. dm_bufio_unlock(c);
  1104. a = xchg(&c->async_write_error, 0);
  1105. f = dm_bufio_issue_flush(c);
  1106. if (a)
  1107. return a;
  1108. return f;
  1109. }
  1110. EXPORT_SYMBOL_GPL(dm_bufio_write_dirty_buffers);
  1111. /*
  1112. * Use dm-io to send an empty barrier to flush the device.
  1113. */
  1114. int dm_bufio_issue_flush(struct dm_bufio_client *c)
  1115. {
  1116. struct dm_io_request io_req = {
  1117. .bi_opf = REQ_OP_WRITE | REQ_PREFLUSH | REQ_SYNC,
  1118. .mem.type = DM_IO_KMEM,
  1119. .mem.ptr.addr = NULL,
  1120. .client = c->dm_io,
  1121. };
  1122. struct dm_io_region io_reg = {
  1123. .bdev = c->bdev,
  1124. .sector = 0,
  1125. .count = 0,
  1126. };
  1127. BUG_ON(dm_bufio_in_request());
  1128. return dm_io(&io_req, 1, &io_reg, NULL);
  1129. }
  1130. EXPORT_SYMBOL_GPL(dm_bufio_issue_flush);
  1131. /*
  1132. * Use dm-io to send a discard request to flush the device.
  1133. */
  1134. int dm_bufio_issue_discard(struct dm_bufio_client *c, sector_t block, sector_t count)
  1135. {
  1136. struct dm_io_request io_req = {
  1137. .bi_opf = REQ_OP_DISCARD | REQ_SYNC,
  1138. .mem.type = DM_IO_KMEM,
  1139. .mem.ptr.addr = NULL,
  1140. .client = c->dm_io,
  1141. };
  1142. struct dm_io_region io_reg = {
  1143. .bdev = c->bdev,
  1144. .sector = block_to_sector(c, block),
  1145. .count = block_to_sector(c, count),
  1146. };
  1147. BUG_ON(dm_bufio_in_request());
  1148. return dm_io(&io_req, 1, &io_reg, NULL);
  1149. }
  1150. EXPORT_SYMBOL_GPL(dm_bufio_issue_discard);
  1151. /*
  1152. * We first delete any other buffer that may be at that new location.
  1153. *
  1154. * Then, we write the buffer to the original location if it was dirty.
  1155. *
  1156. * Then, if we are the only one who is holding the buffer, relink the buffer
  1157. * in the buffer tree for the new location.
  1158. *
  1159. * If there was someone else holding the buffer, we write it to the new
  1160. * location but not relink it, because that other user needs to have the buffer
  1161. * at the same place.
  1162. */
  1163. void dm_bufio_release_move(struct dm_buffer *b, sector_t new_block)
  1164. {
  1165. struct dm_bufio_client *c = b->c;
  1166. struct dm_buffer *new;
  1167. BUG_ON(dm_bufio_in_request());
  1168. dm_bufio_lock(c);
  1169. retry:
  1170. new = __find(c, new_block);
  1171. if (new) {
  1172. if (new->hold_count) {
  1173. __wait_for_free_buffer(c);
  1174. goto retry;
  1175. }
  1176. /*
  1177. * FIXME: Is there any point waiting for a write that's going
  1178. * to be overwritten in a bit?
  1179. */
  1180. __make_buffer_clean(new);
  1181. __unlink_buffer(new);
  1182. __free_buffer_wake(new);
  1183. }
  1184. BUG_ON(!b->hold_count);
  1185. BUG_ON(test_bit(B_READING, &b->state));
  1186. __write_dirty_buffer(b, NULL);
  1187. if (b->hold_count == 1) {
  1188. wait_on_bit_io(&b->state, B_WRITING,
  1189. TASK_UNINTERRUPTIBLE);
  1190. set_bit(B_DIRTY, &b->state);
  1191. b->dirty_start = 0;
  1192. b->dirty_end = c->block_size;
  1193. __unlink_buffer(b);
  1194. __link_buffer(b, new_block, LIST_DIRTY);
  1195. } else {
  1196. sector_t old_block;
  1197. wait_on_bit_lock_io(&b->state, B_WRITING,
  1198. TASK_UNINTERRUPTIBLE);
  1199. /*
  1200. * Relink buffer to "new_block" so that write_callback
  1201. * sees "new_block" as a block number.
  1202. * After the write, link the buffer back to old_block.
  1203. * All this must be done in bufio lock, so that block number
  1204. * change isn't visible to other threads.
  1205. */
  1206. old_block = b->block;
  1207. __unlink_buffer(b);
  1208. __link_buffer(b, new_block, b->list_mode);
  1209. submit_io(b, REQ_OP_WRITE, write_endio);
  1210. wait_on_bit_io(&b->state, B_WRITING,
  1211. TASK_UNINTERRUPTIBLE);
  1212. __unlink_buffer(b);
  1213. __link_buffer(b, old_block, b->list_mode);
  1214. }
  1215. dm_bufio_unlock(c);
  1216. dm_bufio_release(b);
  1217. }
  1218. EXPORT_SYMBOL_GPL(dm_bufio_release_move);
  1219. static void forget_buffer_locked(struct dm_buffer *b)
  1220. {
  1221. if (likely(!b->hold_count) && likely(!smp_load_acquire(&b->state))) {
  1222. __unlink_buffer(b);
  1223. __free_buffer_wake(b);
  1224. }
  1225. }
  1226. /*
  1227. * Free the given buffer.
  1228. *
  1229. * This is just a hint, if the buffer is in use or dirty, this function
  1230. * does nothing.
  1231. */
  1232. void dm_bufio_forget(struct dm_bufio_client *c, sector_t block)
  1233. {
  1234. struct dm_buffer *b;
  1235. dm_bufio_lock(c);
  1236. b = __find(c, block);
  1237. if (b)
  1238. forget_buffer_locked(b);
  1239. dm_bufio_unlock(c);
  1240. }
  1241. EXPORT_SYMBOL_GPL(dm_bufio_forget);
  1242. void dm_bufio_forget_buffers(struct dm_bufio_client *c, sector_t block, sector_t n_blocks)
  1243. {
  1244. struct dm_buffer *b;
  1245. sector_t end_block = block + n_blocks;
  1246. while (block < end_block) {
  1247. dm_bufio_lock(c);
  1248. b = __find_next(c, block);
  1249. if (b) {
  1250. block = b->block + 1;
  1251. forget_buffer_locked(b);
  1252. }
  1253. dm_bufio_unlock(c);
  1254. if (!b)
  1255. break;
  1256. }
  1257. }
  1258. EXPORT_SYMBOL_GPL(dm_bufio_forget_buffers);
  1259. void dm_bufio_set_minimum_buffers(struct dm_bufio_client *c, unsigned int n)
  1260. {
  1261. c->minimum_buffers = n;
  1262. }
  1263. EXPORT_SYMBOL_GPL(dm_bufio_set_minimum_buffers);
  1264. unsigned int dm_bufio_get_block_size(struct dm_bufio_client *c)
  1265. {
  1266. return c->block_size;
  1267. }
  1268. EXPORT_SYMBOL_GPL(dm_bufio_get_block_size);
  1269. sector_t dm_bufio_get_device_size(struct dm_bufio_client *c)
  1270. {
  1271. sector_t s = bdev_nr_sectors(c->bdev);
  1272. if (s >= c->start)
  1273. s -= c->start;
  1274. else
  1275. s = 0;
  1276. if (likely(c->sectors_per_block_bits >= 0))
  1277. s >>= c->sectors_per_block_bits;
  1278. else
  1279. sector_div(s, c->block_size >> SECTOR_SHIFT);
  1280. return s;
  1281. }
  1282. EXPORT_SYMBOL_GPL(dm_bufio_get_device_size);
  1283. struct dm_io_client *dm_bufio_get_dm_io_client(struct dm_bufio_client *c)
  1284. {
  1285. return c->dm_io;
  1286. }
  1287. EXPORT_SYMBOL_GPL(dm_bufio_get_dm_io_client);
  1288. sector_t dm_bufio_get_block_number(struct dm_buffer *b)
  1289. {
  1290. return b->block;
  1291. }
  1292. EXPORT_SYMBOL_GPL(dm_bufio_get_block_number);
  1293. void *dm_bufio_get_block_data(struct dm_buffer *b)
  1294. {
  1295. return b->data;
  1296. }
  1297. EXPORT_SYMBOL_GPL(dm_bufio_get_block_data);
  1298. void *dm_bufio_get_aux_data(struct dm_buffer *b)
  1299. {
  1300. return b + 1;
  1301. }
  1302. EXPORT_SYMBOL_GPL(dm_bufio_get_aux_data);
  1303. struct dm_bufio_client *dm_bufio_get_client(struct dm_buffer *b)
  1304. {
  1305. return b->c;
  1306. }
  1307. EXPORT_SYMBOL_GPL(dm_bufio_get_client);
  1308. static void drop_buffers(struct dm_bufio_client *c)
  1309. {
  1310. struct dm_buffer *b;
  1311. int i;
  1312. bool warned = false;
  1313. BUG_ON(dm_bufio_in_request());
  1314. /*
  1315. * An optimization so that the buffers are not written one-by-one.
  1316. */
  1317. dm_bufio_write_dirty_buffers_async(c);
  1318. dm_bufio_lock(c);
  1319. while ((b = __get_unclaimed_buffer(c)))
  1320. __free_buffer_wake(b);
  1321. for (i = 0; i < LIST_SIZE; i++)
  1322. list_for_each_entry(b, &c->lru[i], lru_list) {
  1323. WARN_ON(!warned);
  1324. warned = true;
  1325. DMERR("leaked buffer %llx, hold count %u, list %d",
  1326. (unsigned long long)b->block, b->hold_count, i);
  1327. #ifdef CONFIG_DM_DEBUG_BLOCK_STACK_TRACING
  1328. stack_trace_print(b->stack_entries, b->stack_len, 1);
  1329. /* mark unclaimed to avoid BUG_ON below */
  1330. b->hold_count = 0;
  1331. #endif
  1332. }
  1333. #ifdef CONFIG_DM_DEBUG_BLOCK_STACK_TRACING
  1334. while ((b = __get_unclaimed_buffer(c)))
  1335. __free_buffer_wake(b);
  1336. #endif
  1337. for (i = 0; i < LIST_SIZE; i++)
  1338. BUG_ON(!list_empty(&c->lru[i]));
  1339. dm_bufio_unlock(c);
  1340. }
  1341. /*
  1342. * We may not be able to evict this buffer if IO pending or the client
  1343. * is still using it. Caller is expected to know buffer is too old.
  1344. *
  1345. * And if GFP_NOFS is used, we must not do any I/O because we hold
  1346. * dm_bufio_clients_lock and we would risk deadlock if the I/O gets
  1347. * rerouted to different bufio client.
  1348. */
  1349. static bool __try_evict_buffer(struct dm_buffer *b, gfp_t gfp)
  1350. {
  1351. if (!(gfp & __GFP_FS) ||
  1352. (static_branch_unlikely(&no_sleep_enabled) && b->c->no_sleep)) {
  1353. if (test_bit_acquire(B_READING, &b->state) ||
  1354. test_bit(B_WRITING, &b->state) ||
  1355. test_bit(B_DIRTY, &b->state))
  1356. return false;
  1357. }
  1358. if (b->hold_count)
  1359. return false;
  1360. __make_buffer_clean(b);
  1361. __unlink_buffer(b);
  1362. __free_buffer_wake(b);
  1363. return true;
  1364. }
  1365. static unsigned long get_retain_buffers(struct dm_bufio_client *c)
  1366. {
  1367. unsigned long retain_bytes = READ_ONCE(dm_bufio_retain_bytes);
  1368. if (likely(c->sectors_per_block_bits >= 0))
  1369. retain_bytes >>= c->sectors_per_block_bits + SECTOR_SHIFT;
  1370. else
  1371. retain_bytes /= c->block_size;
  1372. return retain_bytes;
  1373. }
  1374. static void __scan(struct dm_bufio_client *c)
  1375. {
  1376. int l;
  1377. struct dm_buffer *b, *tmp;
  1378. unsigned long freed = 0;
  1379. unsigned long count = c->n_buffers[LIST_CLEAN] +
  1380. c->n_buffers[LIST_DIRTY];
  1381. unsigned long retain_target = get_retain_buffers(c);
  1382. for (l = 0; l < LIST_SIZE; l++) {
  1383. list_for_each_entry_safe_reverse(b, tmp, &c->lru[l], lru_list) {
  1384. if (count - freed <= retain_target)
  1385. atomic_long_set(&c->need_shrink, 0);
  1386. if (!atomic_long_read(&c->need_shrink))
  1387. return;
  1388. if (__try_evict_buffer(b, GFP_KERNEL)) {
  1389. atomic_long_dec(&c->need_shrink);
  1390. freed++;
  1391. }
  1392. cond_resched();
  1393. }
  1394. }
  1395. }
  1396. static void shrink_work(struct work_struct *w)
  1397. {
  1398. struct dm_bufio_client *c = container_of(w, struct dm_bufio_client, shrink_work);
  1399. dm_bufio_lock(c);
  1400. __scan(c);
  1401. dm_bufio_unlock(c);
  1402. }
  1403. static unsigned long dm_bufio_shrink_scan(struct shrinker *shrink, struct shrink_control *sc)
  1404. {
  1405. struct dm_bufio_client *c;
  1406. bool bypass = false;
  1407. trace_android_vh_dm_bufio_shrink_scan_bypass(
  1408. dm_bufio_current_allocated,
  1409. &bypass);
  1410. if (bypass)
  1411. return 0;
  1412. c = container_of(shrink, struct dm_bufio_client, shrinker);
  1413. atomic_long_add(sc->nr_to_scan, &c->need_shrink);
  1414. queue_work(dm_bufio_wq, &c->shrink_work);
  1415. return sc->nr_to_scan;
  1416. }
  1417. static unsigned long dm_bufio_shrink_count(struct shrinker *shrink, struct shrink_control *sc)
  1418. {
  1419. struct dm_bufio_client *c = container_of(shrink, struct dm_bufio_client, shrinker);
  1420. unsigned long count = READ_ONCE(c->n_buffers[LIST_CLEAN]) +
  1421. READ_ONCE(c->n_buffers[LIST_DIRTY]);
  1422. unsigned long retain_target = get_retain_buffers(c);
  1423. unsigned long queued_for_cleanup = atomic_long_read(&c->need_shrink);
  1424. if (unlikely(count < retain_target))
  1425. count = 0;
  1426. else
  1427. count -= retain_target;
  1428. if (unlikely(count < queued_for_cleanup))
  1429. count = 0;
  1430. else
  1431. count -= queued_for_cleanup;
  1432. return count;
  1433. }
  1434. /*
  1435. * Create the buffering interface
  1436. */
  1437. struct dm_bufio_client *dm_bufio_client_create(struct block_device *bdev, unsigned int block_size,
  1438. unsigned int reserved_buffers, unsigned int aux_size,
  1439. void (*alloc_callback)(struct dm_buffer *),
  1440. void (*write_callback)(struct dm_buffer *),
  1441. unsigned int flags)
  1442. {
  1443. int r;
  1444. struct dm_bufio_client *c;
  1445. unsigned int i;
  1446. char slab_name[27];
  1447. if (!block_size || block_size & ((1 << SECTOR_SHIFT) - 1)) {
  1448. DMERR("%s: block size not specified or is not multiple of 512b", __func__);
  1449. r = -EINVAL;
  1450. goto bad_client;
  1451. }
  1452. c = kzalloc(sizeof(*c), GFP_KERNEL);
  1453. if (!c) {
  1454. r = -ENOMEM;
  1455. goto bad_client;
  1456. }
  1457. c->buffer_tree = RB_ROOT;
  1458. c->bdev = bdev;
  1459. c->block_size = block_size;
  1460. if (is_power_of_2(block_size))
  1461. c->sectors_per_block_bits = __ffs(block_size) - SECTOR_SHIFT;
  1462. else
  1463. c->sectors_per_block_bits = -1;
  1464. c->alloc_callback = alloc_callback;
  1465. c->write_callback = write_callback;
  1466. if (flags & DM_BUFIO_CLIENT_NO_SLEEP) {
  1467. c->no_sleep = true;
  1468. static_branch_inc(&no_sleep_enabled);
  1469. }
  1470. for (i = 0; i < LIST_SIZE; i++) {
  1471. INIT_LIST_HEAD(&c->lru[i]);
  1472. c->n_buffers[i] = 0;
  1473. }
  1474. mutex_init(&c->lock);
  1475. spin_lock_init(&c->spinlock);
  1476. INIT_LIST_HEAD(&c->reserved_buffers);
  1477. c->need_reserved_buffers = reserved_buffers;
  1478. dm_bufio_set_minimum_buffers(c, DM_BUFIO_MIN_BUFFERS);
  1479. init_waitqueue_head(&c->free_buffer_wait);
  1480. c->async_write_error = 0;
  1481. c->dm_io = dm_io_client_create();
  1482. if (IS_ERR(c->dm_io)) {
  1483. r = PTR_ERR(c->dm_io);
  1484. goto bad_dm_io;
  1485. }
  1486. if (block_size <= KMALLOC_MAX_SIZE &&
  1487. (block_size < PAGE_SIZE || !is_power_of_2(block_size))) {
  1488. unsigned int align = min(1U << __ffs(block_size), (unsigned int)PAGE_SIZE);
  1489. snprintf(slab_name, sizeof slab_name, "dm_bufio_cache-%u", block_size);
  1490. c->slab_cache = kmem_cache_create(slab_name, block_size, align,
  1491. SLAB_RECLAIM_ACCOUNT, NULL);
  1492. if (!c->slab_cache) {
  1493. r = -ENOMEM;
  1494. goto bad;
  1495. }
  1496. }
  1497. if (aux_size)
  1498. snprintf(slab_name, sizeof slab_name, "dm_bufio_buffer-%u", aux_size);
  1499. else
  1500. snprintf(slab_name, sizeof slab_name, "dm_bufio_buffer");
  1501. c->slab_buffer = kmem_cache_create(slab_name, sizeof(struct dm_buffer) + aux_size,
  1502. 0, SLAB_RECLAIM_ACCOUNT, NULL);
  1503. if (!c->slab_buffer) {
  1504. r = -ENOMEM;
  1505. goto bad;
  1506. }
  1507. while (c->need_reserved_buffers) {
  1508. struct dm_buffer *b = alloc_buffer(c, GFP_KERNEL);
  1509. if (!b) {
  1510. r = -ENOMEM;
  1511. goto bad;
  1512. }
  1513. __free_buffer_wake(b);
  1514. }
  1515. INIT_WORK(&c->shrink_work, shrink_work);
  1516. atomic_long_set(&c->need_shrink, 0);
  1517. c->shrinker.count_objects = dm_bufio_shrink_count;
  1518. c->shrinker.scan_objects = dm_bufio_shrink_scan;
  1519. c->shrinker.seeks = 1;
  1520. c->shrinker.batch = 0;
  1521. r = register_shrinker(&c->shrinker, "dm-bufio:(%u:%u)",
  1522. MAJOR(bdev->bd_dev), MINOR(bdev->bd_dev));
  1523. if (r)
  1524. goto bad;
  1525. mutex_lock(&dm_bufio_clients_lock);
  1526. dm_bufio_client_count++;
  1527. list_add(&c->client_list, &dm_bufio_all_clients);
  1528. __cache_size_refresh();
  1529. mutex_unlock(&dm_bufio_clients_lock);
  1530. return c;
  1531. bad:
  1532. while (!list_empty(&c->reserved_buffers)) {
  1533. struct dm_buffer *b = list_entry(c->reserved_buffers.next,
  1534. struct dm_buffer, lru_list);
  1535. list_del(&b->lru_list);
  1536. free_buffer(b);
  1537. }
  1538. kmem_cache_destroy(c->slab_cache);
  1539. kmem_cache_destroy(c->slab_buffer);
  1540. dm_io_client_destroy(c->dm_io);
  1541. bad_dm_io:
  1542. mutex_destroy(&c->lock);
  1543. if (c->no_sleep)
  1544. static_branch_dec(&no_sleep_enabled);
  1545. kfree(c);
  1546. bad_client:
  1547. return ERR_PTR(r);
  1548. }
  1549. EXPORT_SYMBOL_GPL(dm_bufio_client_create);
  1550. /*
  1551. * Free the buffering interface.
  1552. * It is required that there are no references on any buffers.
  1553. */
  1554. void dm_bufio_client_destroy(struct dm_bufio_client *c)
  1555. {
  1556. unsigned int i;
  1557. drop_buffers(c);
  1558. unregister_shrinker(&c->shrinker);
  1559. flush_work(&c->shrink_work);
  1560. mutex_lock(&dm_bufio_clients_lock);
  1561. list_del(&c->client_list);
  1562. dm_bufio_client_count--;
  1563. __cache_size_refresh();
  1564. mutex_unlock(&dm_bufio_clients_lock);
  1565. BUG_ON(!RB_EMPTY_ROOT(&c->buffer_tree));
  1566. BUG_ON(c->need_reserved_buffers);
  1567. while (!list_empty(&c->reserved_buffers)) {
  1568. struct dm_buffer *b = list_entry(c->reserved_buffers.next,
  1569. struct dm_buffer, lru_list);
  1570. list_del(&b->lru_list);
  1571. free_buffer(b);
  1572. }
  1573. for (i = 0; i < LIST_SIZE; i++)
  1574. if (c->n_buffers[i])
  1575. DMERR("leaked buffer count %d: %ld", i, c->n_buffers[i]);
  1576. for (i = 0; i < LIST_SIZE; i++)
  1577. BUG_ON(c->n_buffers[i]);
  1578. kmem_cache_destroy(c->slab_cache);
  1579. kmem_cache_destroy(c->slab_buffer);
  1580. dm_io_client_destroy(c->dm_io);
  1581. mutex_destroy(&c->lock);
  1582. if (c->no_sleep)
  1583. static_branch_dec(&no_sleep_enabled);
  1584. kfree(c);
  1585. }
  1586. EXPORT_SYMBOL_GPL(dm_bufio_client_destroy);
  1587. void dm_bufio_set_sector_offset(struct dm_bufio_client *c, sector_t start)
  1588. {
  1589. c->start = start;
  1590. }
  1591. EXPORT_SYMBOL_GPL(dm_bufio_set_sector_offset);
  1592. static unsigned int get_max_age_hz(void)
  1593. {
  1594. unsigned int max_age = READ_ONCE(dm_bufio_max_age);
  1595. if (max_age > UINT_MAX / HZ)
  1596. max_age = UINT_MAX / HZ;
  1597. return max_age * HZ;
  1598. }
  1599. static bool older_than(struct dm_buffer *b, unsigned long age_hz)
  1600. {
  1601. return time_after_eq(jiffies, b->last_accessed + age_hz);
  1602. }
  1603. static void __evict_old_buffers(struct dm_bufio_client *c, unsigned long age_hz)
  1604. {
  1605. struct dm_buffer *b, *tmp;
  1606. unsigned long retain_target = get_retain_buffers(c);
  1607. unsigned long count;
  1608. LIST_HEAD(write_list);
  1609. dm_bufio_lock(c);
  1610. __check_watermark(c, &write_list);
  1611. if (unlikely(!list_empty(&write_list))) {
  1612. dm_bufio_unlock(c);
  1613. __flush_write_list(&write_list);
  1614. dm_bufio_lock(c);
  1615. }
  1616. count = c->n_buffers[LIST_CLEAN] + c->n_buffers[LIST_DIRTY];
  1617. list_for_each_entry_safe_reverse(b, tmp, &c->lru[LIST_CLEAN], lru_list) {
  1618. if (count <= retain_target)
  1619. break;
  1620. if (!older_than(b, age_hz))
  1621. break;
  1622. if (__try_evict_buffer(b, 0))
  1623. count--;
  1624. cond_resched();
  1625. }
  1626. dm_bufio_unlock(c);
  1627. }
  1628. static void do_global_cleanup(struct work_struct *w)
  1629. {
  1630. struct dm_bufio_client *locked_client = NULL;
  1631. struct dm_bufio_client *current_client;
  1632. struct dm_buffer *b;
  1633. unsigned int spinlock_hold_count;
  1634. unsigned long threshold = dm_bufio_cache_size -
  1635. dm_bufio_cache_size / DM_BUFIO_LOW_WATERMARK_RATIO;
  1636. unsigned long loops = global_num * 2;
  1637. mutex_lock(&dm_bufio_clients_lock);
  1638. while (1) {
  1639. cond_resched();
  1640. spin_lock(&global_spinlock);
  1641. if (unlikely(dm_bufio_current_allocated <= threshold))
  1642. break;
  1643. spinlock_hold_count = 0;
  1644. get_next:
  1645. if (!loops--)
  1646. break;
  1647. if (unlikely(list_empty(&global_queue)))
  1648. break;
  1649. b = list_entry(global_queue.prev, struct dm_buffer, global_list);
  1650. if (b->accessed) {
  1651. b->accessed = 0;
  1652. list_move(&b->global_list, &global_queue);
  1653. if (likely(++spinlock_hold_count < 16))
  1654. goto get_next;
  1655. spin_unlock(&global_spinlock);
  1656. continue;
  1657. }
  1658. current_client = b->c;
  1659. if (unlikely(current_client != locked_client)) {
  1660. if (locked_client)
  1661. dm_bufio_unlock(locked_client);
  1662. if (!dm_bufio_trylock(current_client)) {
  1663. spin_unlock(&global_spinlock);
  1664. dm_bufio_lock(current_client);
  1665. locked_client = current_client;
  1666. continue;
  1667. }
  1668. locked_client = current_client;
  1669. }
  1670. spin_unlock(&global_spinlock);
  1671. if (unlikely(!__try_evict_buffer(b, GFP_KERNEL))) {
  1672. spin_lock(&global_spinlock);
  1673. list_move(&b->global_list, &global_queue);
  1674. spin_unlock(&global_spinlock);
  1675. }
  1676. }
  1677. spin_unlock(&global_spinlock);
  1678. if (locked_client)
  1679. dm_bufio_unlock(locked_client);
  1680. mutex_unlock(&dm_bufio_clients_lock);
  1681. }
  1682. static void cleanup_old_buffers(void)
  1683. {
  1684. unsigned long max_age_hz = get_max_age_hz();
  1685. struct dm_bufio_client *c;
  1686. bool bypass = false;
  1687. trace_android_vh_cleanup_old_buffers_bypass(
  1688. dm_bufio_current_allocated,
  1689. &max_age_hz,
  1690. &bypass);
  1691. if (bypass)
  1692. return;
  1693. mutex_lock(&dm_bufio_clients_lock);
  1694. __cache_size_refresh();
  1695. list_for_each_entry(c, &dm_bufio_all_clients, client_list)
  1696. __evict_old_buffers(c, max_age_hz);
  1697. mutex_unlock(&dm_bufio_clients_lock);
  1698. }
  1699. static void work_fn(struct work_struct *w)
  1700. {
  1701. cleanup_old_buffers();
  1702. queue_delayed_work(dm_bufio_wq, &dm_bufio_cleanup_old_work,
  1703. DM_BUFIO_WORK_TIMER_SECS * HZ);
  1704. }
  1705. /*----------------------------------------------------------------
  1706. * Module setup
  1707. *--------------------------------------------------------------*/
  1708. /*
  1709. * This is called only once for the whole dm_bufio module.
  1710. * It initializes memory limit.
  1711. */
  1712. static int __init dm_bufio_init(void)
  1713. {
  1714. __u64 mem;
  1715. dm_bufio_allocated_kmem_cache = 0;
  1716. dm_bufio_allocated_get_free_pages = 0;
  1717. dm_bufio_allocated_vmalloc = 0;
  1718. dm_bufio_current_allocated = 0;
  1719. mem = (__u64)mult_frac(totalram_pages() - totalhigh_pages(),
  1720. DM_BUFIO_MEMORY_PERCENT, 100) << PAGE_SHIFT;
  1721. if (mem > ULONG_MAX)
  1722. mem = ULONG_MAX;
  1723. #ifdef CONFIG_MMU
  1724. if (mem > mult_frac(VMALLOC_TOTAL, DM_BUFIO_VMALLOC_PERCENT, 100))
  1725. mem = mult_frac(VMALLOC_TOTAL, DM_BUFIO_VMALLOC_PERCENT, 100);
  1726. #endif
  1727. dm_bufio_default_cache_size = mem;
  1728. mutex_lock(&dm_bufio_clients_lock);
  1729. __cache_size_refresh();
  1730. mutex_unlock(&dm_bufio_clients_lock);
  1731. dm_bufio_wq = alloc_workqueue("dm_bufio_cache", WQ_MEM_RECLAIM, 0);
  1732. if (!dm_bufio_wq)
  1733. return -ENOMEM;
  1734. INIT_DELAYED_WORK(&dm_bufio_cleanup_old_work, work_fn);
  1735. INIT_WORK(&dm_bufio_replacement_work, do_global_cleanup);
  1736. queue_delayed_work(dm_bufio_wq, &dm_bufio_cleanup_old_work,
  1737. DM_BUFIO_WORK_TIMER_SECS * HZ);
  1738. return 0;
  1739. }
  1740. /*
  1741. * This is called once when unloading the dm_bufio module.
  1742. */
  1743. static void __exit dm_bufio_exit(void)
  1744. {
  1745. int bug = 0;
  1746. cancel_delayed_work_sync(&dm_bufio_cleanup_old_work);
  1747. destroy_workqueue(dm_bufio_wq);
  1748. if (dm_bufio_client_count) {
  1749. DMCRIT("%s: dm_bufio_client_count leaked: %d",
  1750. __func__, dm_bufio_client_count);
  1751. bug = 1;
  1752. }
  1753. if (dm_bufio_current_allocated) {
  1754. DMCRIT("%s: dm_bufio_current_allocated leaked: %lu",
  1755. __func__, dm_bufio_current_allocated);
  1756. bug = 1;
  1757. }
  1758. if (dm_bufio_allocated_get_free_pages) {
  1759. DMCRIT("%s: dm_bufio_allocated_get_free_pages leaked: %lu",
  1760. __func__, dm_bufio_allocated_get_free_pages);
  1761. bug = 1;
  1762. }
  1763. if (dm_bufio_allocated_vmalloc) {
  1764. DMCRIT("%s: dm_bufio_vmalloc leaked: %lu",
  1765. __func__, dm_bufio_allocated_vmalloc);
  1766. bug = 1;
  1767. }
  1768. BUG_ON(bug);
  1769. }
  1770. module_init(dm_bufio_init)
  1771. module_exit(dm_bufio_exit)
  1772. module_param_named(max_cache_size_bytes, dm_bufio_cache_size, ulong, S_IRUGO | S_IWUSR);
  1773. MODULE_PARM_DESC(max_cache_size_bytes, "Size of metadata cache");
  1774. module_param_named(max_age_seconds, dm_bufio_max_age, uint, S_IRUGO | S_IWUSR);
  1775. MODULE_PARM_DESC(max_age_seconds, "Max age of a buffer in seconds");
  1776. module_param_named(retain_bytes, dm_bufio_retain_bytes, ulong, S_IRUGO | S_IWUSR);
  1777. MODULE_PARM_DESC(retain_bytes, "Try to keep at least this many bytes cached in memory");
  1778. module_param_named(peak_allocated_bytes, dm_bufio_peak_allocated, ulong, S_IRUGO | S_IWUSR);
  1779. MODULE_PARM_DESC(peak_allocated_bytes, "Tracks the maximum allocated memory");
  1780. module_param_named(allocated_kmem_cache_bytes, dm_bufio_allocated_kmem_cache, ulong, S_IRUGO);
  1781. MODULE_PARM_DESC(allocated_kmem_cache_bytes, "Memory allocated with kmem_cache_alloc");
  1782. module_param_named(allocated_get_free_pages_bytes, dm_bufio_allocated_get_free_pages, ulong, S_IRUGO);
  1783. MODULE_PARM_DESC(allocated_get_free_pages_bytes, "Memory allocated with get_free_pages");
  1784. module_param_named(allocated_vmalloc_bytes, dm_bufio_allocated_vmalloc, ulong, S_IRUGO);
  1785. MODULE_PARM_DESC(allocated_vmalloc_bytes, "Memory allocated with vmalloc");
  1786. module_param_named(current_allocated_bytes, dm_bufio_current_allocated, ulong, S_IRUGO);
  1787. MODULE_PARM_DESC(current_allocated_bytes, "Memory currently used by the cache");
  1788. MODULE_AUTHOR("Mikulas Patocka <[email protected]>");
  1789. MODULE_DESCRIPTION(DM_NAME " buffered I/O library");
  1790. MODULE_LICENSE("GPL");