btree.c 64 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * Copyright (C) 2010 Kent Overstreet <kent.overstreet@gmail.com>
  4. *
  5. * Uses a block device as cache for other block devices; optimized for SSDs.
  6. * All allocation is done in buckets, which should match the erase block size
  7. * of the device.
  8. *
  9. * Buckets containing cached data are kept on a heap sorted by priority;
  10. * bucket priority is increased on cache hit, and periodically all the buckets
  11. * on the heap have their priority scaled down. This currently is just used as
  12. * an LRU but in the future should allow for more intelligent heuristics.
  13. *
  14. * Buckets have an 8 bit counter; freeing is accomplished by incrementing the
  15. * counter. Garbage collection is used to remove stale pointers.
  16. *
  17. * Indexing is done via a btree; nodes are not necessarily fully sorted, rather
  18. * as keys are inserted we only sort the pages that have not yet been written.
  19. * When garbage collection is run, we resort the entire node.
  20. *
  21. * All configuration is done via sysfs; see Documentation/admin-guide/bcache.rst.
  22. */
  23. #include "bcache.h"
  24. #include "btree.h"
  25. #include "debug.h"
  26. #include "extents.h"
  27. #include <linux/slab.h>
  28. #include <linux/bitops.h>
  29. #include <linux/hash.h>
  30. #include <linux/kthread.h>
  31. #include <linux/prefetch.h>
  32. #include <linux/random.h>
  33. #include <linux/rcupdate.h>
  34. #include <linux/sched/clock.h>
  35. #include <linux/rculist.h>
  36. #include <linux/delay.h>
  37. #include <trace/events/bcache.h>
  38. /*
  39. * Todo:
  40. * register_bcache: Return errors out to userspace correctly
  41. *
  42. * Writeback: don't undirty key until after a cache flush
  43. *
  44. * Create an iterator for key pointers
  45. *
  46. * On btree write error, mark bucket such that it won't be freed from the cache
  47. *
  48. * Journalling:
  49. * Check for bad keys in replay
  50. * Propagate barriers
  51. * Refcount journal entries in journal_replay
  52. *
  53. * Garbage collection:
  54. * Finish incremental gc
  55. * Gc should free old UUIDs, data for invalid UUIDs
  56. *
  57. * Provide a way to list backing device UUIDs we have data cached for, and
  58. * probably how long it's been since we've seen them, and a way to invalidate
  59. * dirty data for devices that will never be attached again
  60. *
  61. * Keep 1 min/5 min/15 min statistics of how busy a block device has been, so
  62. * that based on that and how much dirty data we have we can keep writeback
  63. * from being starved
  64. *
  65. * Add a tracepoint or somesuch to watch for writeback starvation
  66. *
  67. * When btree depth > 1 and splitting an interior node, we have to make sure
  68. * alloc_bucket() cannot fail. This should be true but is not completely
  69. * obvious.
  70. *
  71. * Plugging?
  72. *
  73. * If data write is less than hard sector size of ssd, round up offset in open
  74. * bucket to the next whole sector
  75. *
  76. * Superblock needs to be fleshed out for multiple cache devices
  77. *
  78. * Add a sysfs tunable for the number of writeback IOs in flight
  79. *
  80. * Add a sysfs tunable for the number of open data buckets
  81. *
  82. * IO tracking: Can we track when one process is doing io on behalf of another?
  83. * IO tracking: Don't use just an average, weigh more recent stuff higher
  84. *
  85. * Test module load/unload
  86. */
  87. #define MAX_NEED_GC 64
  88. #define MAX_SAVE_PRIO 72
  89. #define MAX_GC_TIMES 100
  90. #define MIN_GC_NODES 100
  91. #define GC_SLEEP_MS 100
  92. #define PTR_DIRTY_BIT (((uint64_t) 1 << 36))
  93. #define PTR_HASH(c, k) \
  94. (((k)->ptr[0] >> c->bucket_bits) | PTR_GEN(k, 0))
  95. static struct workqueue_struct *btree_io_wq;
  96. #define insert_lock(s, b) ((b)->level <= (s)->lock)
  97. static inline struct bset *write_block(struct btree *b)
  98. {
  99. return ((void *) btree_bset_first(b)) + b->written * block_bytes(b->c->cache);
  100. }
  101. static void bch_btree_init_next(struct btree *b)
  102. {
  103. /* If not a leaf node, always sort */
  104. if (b->level && b->keys.nsets)
  105. bch_btree_sort(&b->keys, &b->c->sort);
  106. else
  107. bch_btree_sort_lazy(&b->keys, &b->c->sort);
  108. if (b->written < btree_blocks(b))
  109. bch_bset_init_next(&b->keys, write_block(b),
  110. bset_magic(&b->c->cache->sb));
  111. }
  112. /* Btree key manipulation */
  113. void bkey_put(struct cache_set *c, struct bkey *k)
  114. {
  115. unsigned int i;
  116. for (i = 0; i < KEY_PTRS(k); i++)
  117. if (ptr_available(c, k, i))
  118. atomic_dec_bug(&PTR_BUCKET(c, k, i)->pin);
  119. }
  120. /* Btree IO */
  121. static uint64_t btree_csum_set(struct btree *b, struct bset *i)
  122. {
  123. uint64_t crc = b->key.ptr[0];
  124. void *data = (void *) i + 8, *end = bset_bkey_last(i);
  125. crc = crc64_be(crc, data, end - data);
  126. return crc ^ 0xffffffffffffffffULL;
  127. }
  128. void bch_btree_node_read_done(struct btree *b)
  129. {
  130. const char *err = "bad btree header";
  131. struct bset *i = btree_bset_first(b);
  132. struct btree_iter *iter;
  133. /*
  134. * c->fill_iter can allocate an iterator with more memory space
  135. * than static MAX_BSETS.
  136. * See the comment arount cache_set->fill_iter.
  137. */
  138. iter = mempool_alloc(&b->c->fill_iter, GFP_NOIO);
  139. iter->size = b->c->cache->sb.bucket_size / b->c->cache->sb.block_size;
  140. iter->used = 0;
  141. #ifdef CONFIG_BCACHE_DEBUG
  142. iter->b = &b->keys;
  143. #endif
  144. if (!i->seq)
  145. goto err;
  146. for (;
  147. b->written < btree_blocks(b) && i->seq == b->keys.set[0].data->seq;
  148. i = write_block(b)) {
  149. err = "unsupported bset version";
  150. if (i->version > BCACHE_BSET_VERSION)
  151. goto err;
  152. err = "bad btree header";
  153. if (b->written + set_blocks(i, block_bytes(b->c->cache)) >
  154. btree_blocks(b))
  155. goto err;
  156. err = "bad magic";
  157. if (i->magic != bset_magic(&b->c->cache->sb))
  158. goto err;
  159. err = "bad checksum";
  160. switch (i->version) {
  161. case 0:
  162. if (i->csum != csum_set(i))
  163. goto err;
  164. break;
  165. case BCACHE_BSET_VERSION:
  166. if (i->csum != btree_csum_set(b, i))
  167. goto err;
  168. break;
  169. }
  170. err = "empty set";
  171. if (i != b->keys.set[0].data && !i->keys)
  172. goto err;
  173. bch_btree_iter_push(iter, i->start, bset_bkey_last(i));
  174. b->written += set_blocks(i, block_bytes(b->c->cache));
  175. }
  176. err = "corrupted btree";
  177. for (i = write_block(b);
  178. bset_sector_offset(&b->keys, i) < KEY_SIZE(&b->key);
  179. i = ((void *) i) + block_bytes(b->c->cache))
  180. if (i->seq == b->keys.set[0].data->seq)
  181. goto err;
  182. bch_btree_sort_and_fix_extents(&b->keys, iter, &b->c->sort);
  183. i = b->keys.set[0].data;
  184. err = "short btree key";
  185. if (b->keys.set[0].size &&
  186. bkey_cmp(&b->key, &b->keys.set[0].end) < 0)
  187. goto err;
  188. if (b->written < btree_blocks(b))
  189. bch_bset_init_next(&b->keys, write_block(b),
  190. bset_magic(&b->c->cache->sb));
  191. out:
  192. mempool_free(iter, &b->c->fill_iter);
  193. return;
  194. err:
  195. set_btree_node_io_error(b);
  196. bch_cache_set_error(b->c, "%s at bucket %zu, block %u, %u keys",
  197. err, PTR_BUCKET_NR(b->c, &b->key, 0),
  198. bset_block_offset(b, i), i->keys);
  199. goto out;
  200. }
  201. static void btree_node_read_endio(struct bio *bio)
  202. {
  203. struct closure *cl = bio->bi_private;
  204. closure_put(cl);
  205. }
  206. static void bch_btree_node_read(struct btree *b)
  207. {
  208. uint64_t start_time = local_clock();
  209. struct closure cl;
  210. struct bio *bio;
  211. trace_bcache_btree_read(b);
  212. closure_init_stack(&cl);
  213. bio = bch_bbio_alloc(b->c);
  214. bio->bi_iter.bi_size = KEY_SIZE(&b->key) << 9;
  215. bio->bi_end_io = btree_node_read_endio;
  216. bio->bi_private = &cl;
  217. bio->bi_opf = REQ_OP_READ | REQ_META;
  218. bch_bio_map(bio, b->keys.set[0].data);
  219. bch_submit_bbio(bio, b->c, &b->key, 0);
  220. closure_sync(&cl);
  221. if (bio->bi_status)
  222. set_btree_node_io_error(b);
  223. bch_bbio_free(bio, b->c);
  224. if (btree_node_io_error(b))
  225. goto err;
  226. bch_btree_node_read_done(b);
  227. bch_time_stats_update(&b->c->btree_read_time, start_time);
  228. return;
  229. err:
  230. bch_cache_set_error(b->c, "io error reading bucket %zu",
  231. PTR_BUCKET_NR(b->c, &b->key, 0));
  232. }
  233. static void btree_complete_write(struct btree *b, struct btree_write *w)
  234. {
  235. if (w->prio_blocked &&
  236. !atomic_sub_return(w->prio_blocked, &b->c->prio_blocked))
  237. wake_up_allocators(b->c);
  238. if (w->journal) {
  239. atomic_dec_bug(w->journal);
  240. __closure_wake_up(&b->c->journal.wait);
  241. }
  242. w->prio_blocked = 0;
  243. w->journal = NULL;
  244. }
  245. static CLOSURE_CALLBACK(btree_node_write_unlock)
  246. {
  247. closure_type(b, struct btree, io);
  248. up(&b->io_mutex);
  249. }
  250. static CLOSURE_CALLBACK(__btree_node_write_done)
  251. {
  252. closure_type(b, struct btree, io);
  253. struct btree_write *w = btree_prev_write(b);
  254. bch_bbio_free(b->bio, b->c);
  255. b->bio = NULL;
  256. btree_complete_write(b, w);
  257. if (btree_node_dirty(b))
  258. queue_delayed_work(btree_io_wq, &b->work, 30 * HZ);
  259. closure_return_with_destructor(cl, btree_node_write_unlock);
  260. }
  261. static CLOSURE_CALLBACK(btree_node_write_done)
  262. {
  263. closure_type(b, struct btree, io);
  264. bio_free_pages(b->bio);
  265. __btree_node_write_done(&cl->work);
  266. }
  267. static void btree_node_write_endio(struct bio *bio)
  268. {
  269. struct closure *cl = bio->bi_private;
  270. struct btree *b = container_of(cl, struct btree, io);
  271. if (bio->bi_status)
  272. set_btree_node_io_error(b);
  273. bch_bbio_count_io_errors(b->c, bio, bio->bi_status, "writing btree");
  274. closure_put(cl);
  275. }
  276. static void do_btree_node_write(struct btree *b)
  277. {
  278. struct closure *cl = &b->io;
  279. struct bset *i = btree_bset_last(b);
  280. BKEY_PADDED(key) k;
  281. i->version = BCACHE_BSET_VERSION;
  282. i->csum = btree_csum_set(b, i);
  283. BUG_ON(b->bio);
  284. b->bio = bch_bbio_alloc(b->c);
  285. b->bio->bi_end_io = btree_node_write_endio;
  286. b->bio->bi_private = cl;
  287. b->bio->bi_iter.bi_size = roundup(set_bytes(i), block_bytes(b->c->cache));
  288. b->bio->bi_opf = REQ_OP_WRITE | REQ_META | REQ_FUA;
  289. bch_bio_map(b->bio, i);
  290. /*
  291. * If we're appending to a leaf node, we don't technically need FUA -
  292. * this write just needs to be persisted before the next journal write,
  293. * which will be marked FLUSH|FUA.
  294. *
  295. * Similarly if we're writing a new btree root - the pointer is going to
  296. * be in the next journal entry.
  297. *
  298. * But if we're writing a new btree node (that isn't a root) or
  299. * appending to a non leaf btree node, we need either FUA or a flush
  300. * when we write the parent with the new pointer. FUA is cheaper than a
  301. * flush, and writes appending to leaf nodes aren't blocking anything so
  302. * just make all btree node writes FUA to keep things sane.
  303. */
  304. bkey_copy(&k.key, &b->key);
  305. SET_PTR_OFFSET(&k.key, 0, PTR_OFFSET(&k.key, 0) +
  306. bset_sector_offset(&b->keys, i));
  307. if (!bch_bio_alloc_pages(b->bio, __GFP_NOWARN|GFP_NOWAIT)) {
  308. struct bio_vec *bv;
  309. void *addr = (void *) ((unsigned long) i & ~(PAGE_SIZE - 1));
  310. struct bvec_iter_all iter_all;
  311. bio_for_each_segment_all(bv, b->bio, iter_all) {
  312. memcpy(page_address(bv->bv_page), addr, PAGE_SIZE);
  313. addr += PAGE_SIZE;
  314. }
  315. bch_submit_bbio(b->bio, b->c, &k.key, 0);
  316. continue_at(cl, btree_node_write_done, NULL);
  317. } else {
  318. /*
  319. * No problem for multipage bvec since the bio is
  320. * just allocated
  321. */
  322. b->bio->bi_vcnt = 0;
  323. bch_bio_map(b->bio, i);
  324. bch_submit_bbio(b->bio, b->c, &k.key, 0);
  325. closure_sync(cl);
  326. continue_at_nobarrier(cl, __btree_node_write_done, NULL);
  327. }
  328. }
  329. void __bch_btree_node_write(struct btree *b, struct closure *parent)
  330. {
  331. struct bset *i = btree_bset_last(b);
  332. lockdep_assert_held(&b->write_lock);
  333. trace_bcache_btree_write(b);
  334. BUG_ON(current->bio_list);
  335. BUG_ON(b->written >= btree_blocks(b));
  336. BUG_ON(b->written && !i->keys);
  337. BUG_ON(btree_bset_first(b)->seq != i->seq);
  338. bch_check_keys(&b->keys, "writing");
  339. cancel_delayed_work(&b->work);
  340. /* If caller isn't waiting for write, parent refcount is cache set */
  341. down(&b->io_mutex);
  342. closure_init(&b->io, parent ?: &b->c->cl);
  343. clear_bit(BTREE_NODE_dirty, &b->flags);
  344. change_bit(BTREE_NODE_write_idx, &b->flags);
  345. do_btree_node_write(b);
  346. atomic_long_add(set_blocks(i, block_bytes(b->c->cache)) * b->c->cache->sb.block_size,
  347. &b->c->cache->btree_sectors_written);
  348. b->written += set_blocks(i, block_bytes(b->c->cache));
  349. }
  350. void bch_btree_node_write(struct btree *b, struct closure *parent)
  351. {
  352. unsigned int nsets = b->keys.nsets;
  353. lockdep_assert_held(&b->lock);
  354. __bch_btree_node_write(b, parent);
  355. /*
  356. * do verify if there was more than one set initially (i.e. we did a
  357. * sort) and we sorted down to a single set:
  358. */
  359. if (nsets && !b->keys.nsets)
  360. bch_btree_verify(b);
  361. bch_btree_init_next(b);
  362. }
  363. static void bch_btree_node_write_sync(struct btree *b)
  364. {
  365. struct closure cl;
  366. closure_init_stack(&cl);
  367. mutex_lock(&b->write_lock);
  368. bch_btree_node_write(b, &cl);
  369. mutex_unlock(&b->write_lock);
  370. closure_sync(&cl);
  371. }
  372. static void btree_node_write_work(struct work_struct *w)
  373. {
  374. struct btree *b = container_of(to_delayed_work(w), struct btree, work);
  375. mutex_lock(&b->write_lock);
  376. if (btree_node_dirty(b))
  377. __bch_btree_node_write(b, NULL);
  378. mutex_unlock(&b->write_lock);
  379. }
  380. static void bch_btree_leaf_dirty(struct btree *b, atomic_t *journal_ref)
  381. {
  382. struct bset *i = btree_bset_last(b);
  383. struct btree_write *w = btree_current_write(b);
  384. lockdep_assert_held(&b->write_lock);
  385. BUG_ON(!b->written);
  386. BUG_ON(!i->keys);
  387. if (!btree_node_dirty(b))
  388. queue_delayed_work(btree_io_wq, &b->work, 30 * HZ);
  389. set_btree_node_dirty(b);
  390. /*
  391. * w->journal is always the oldest journal pin of all bkeys
  392. * in the leaf node, to make sure the oldest jset seq won't
  393. * be increased before this btree node is flushed.
  394. */
  395. if (journal_ref) {
  396. if (w->journal &&
  397. journal_pin_cmp(b->c, w->journal, journal_ref)) {
  398. atomic_dec_bug(w->journal);
  399. w->journal = NULL;
  400. }
  401. if (!w->journal) {
  402. w->journal = journal_ref;
  403. atomic_inc(w->journal);
  404. }
  405. }
  406. /* Force write if set is too big */
  407. if (set_bytes(i) > PAGE_SIZE - 48 &&
  408. !current->bio_list)
  409. bch_btree_node_write(b, NULL);
  410. }
  411. /*
  412. * Btree in memory cache - allocation/freeing
  413. * mca -> memory cache
  414. */
  415. #define mca_reserve(c) (((!IS_ERR_OR_NULL(c->root) && c->root->level) \
  416. ? c->root->level : 1) * 8 + 16)
  417. #define mca_can_free(c) \
  418. max_t(int, 0, c->btree_cache_used - mca_reserve(c))
  419. static void mca_data_free(struct btree *b)
  420. {
  421. BUG_ON(b->io_mutex.count != 1);
  422. bch_btree_keys_free(&b->keys);
  423. b->c->btree_cache_used--;
  424. list_move(&b->list, &b->c->btree_cache_freed);
  425. }
  426. static void mca_bucket_free(struct btree *b)
  427. {
  428. BUG_ON(btree_node_dirty(b));
  429. b->key.ptr[0] = 0;
  430. hlist_del_init_rcu(&b->hash);
  431. list_move(&b->list, &b->c->btree_cache_freeable);
  432. }
  433. static unsigned int btree_order(struct bkey *k)
  434. {
  435. return ilog2(KEY_SIZE(k) / PAGE_SECTORS ?: 1);
  436. }
  437. static void mca_data_alloc(struct btree *b, struct bkey *k, gfp_t gfp)
  438. {
  439. if (!bch_btree_keys_alloc(&b->keys,
  440. max_t(unsigned int,
  441. ilog2(b->c->btree_pages),
  442. btree_order(k)),
  443. gfp)) {
  444. b->c->btree_cache_used++;
  445. list_move(&b->list, &b->c->btree_cache);
  446. } else {
  447. list_move(&b->list, &b->c->btree_cache_freed);
  448. }
  449. }
  450. #define cmp_int(l, r) ((l > r) - (l < r))
  451. #ifdef CONFIG_PROVE_LOCKING
  452. static int btree_lock_cmp_fn(const struct lockdep_map *_a,
  453. const struct lockdep_map *_b)
  454. {
  455. const struct btree *a = container_of(_a, struct btree, lock.dep_map);
  456. const struct btree *b = container_of(_b, struct btree, lock.dep_map);
  457. return -cmp_int(a->level, b->level) ?: bkey_cmp(&a->key, &b->key);
  458. }
  459. static void btree_lock_print_fn(const struct lockdep_map *map)
  460. {
  461. const struct btree *b = container_of(map, struct btree, lock.dep_map);
  462. printk(KERN_CONT " l=%u %llu:%llu", b->level,
  463. KEY_INODE(&b->key), KEY_OFFSET(&b->key));
  464. }
  465. #endif
  466. static struct btree *mca_bucket_alloc(struct cache_set *c,
  467. struct bkey *k, gfp_t gfp)
  468. {
  469. /*
  470. * kzalloc() is necessary here for initialization,
  471. * see code comments in bch_btree_keys_init().
  472. */
  473. struct btree *b = kzalloc(sizeof(struct btree), gfp);
  474. if (!b)
  475. return NULL;
  476. init_rwsem(&b->lock);
  477. lock_set_cmp_fn(&b->lock, btree_lock_cmp_fn, btree_lock_print_fn);
  478. mutex_init(&b->write_lock);
  479. lockdep_set_novalidate_class(&b->write_lock);
  480. INIT_LIST_HEAD(&b->list);
  481. INIT_DELAYED_WORK(&b->work, btree_node_write_work);
  482. b->c = c;
  483. sema_init(&b->io_mutex, 1);
  484. mca_data_alloc(b, k, gfp);
  485. return b;
  486. }
  487. static int mca_reap(struct btree *b, unsigned int min_order, bool flush)
  488. {
  489. struct closure cl;
  490. closure_init_stack(&cl);
  491. lockdep_assert_held(&b->c->bucket_lock);
  492. if (!down_write_trylock(&b->lock))
  493. return -ENOMEM;
  494. BUG_ON(btree_node_dirty(b) && !b->keys.set[0].data);
  495. if (b->keys.page_order < min_order)
  496. goto out_unlock;
  497. if (!flush) {
  498. if (btree_node_dirty(b))
  499. goto out_unlock;
  500. if (down_trylock(&b->io_mutex))
  501. goto out_unlock;
  502. up(&b->io_mutex);
  503. }
  504. retry:
  505. /*
  506. * BTREE_NODE_dirty might be cleared in btree_flush_btree() by
  507. * __bch_btree_node_write(). To avoid an extra flush, acquire
  508. * b->write_lock before checking BTREE_NODE_dirty bit.
  509. */
  510. mutex_lock(&b->write_lock);
  511. /*
  512. * If this btree node is selected in btree_flush_write() by journal
  513. * code, delay and retry until the node is flushed by journal code
  514. * and BTREE_NODE_journal_flush bit cleared by btree_flush_write().
  515. */
  516. if (btree_node_journal_flush(b)) {
  517. pr_debug("bnode %p is flushing by journal, retry\n", b);
  518. mutex_unlock(&b->write_lock);
  519. udelay(1);
  520. goto retry;
  521. }
  522. if (btree_node_dirty(b))
  523. __bch_btree_node_write(b, &cl);
  524. mutex_unlock(&b->write_lock);
  525. closure_sync(&cl);
  526. /* wait for any in flight btree write */
  527. down(&b->io_mutex);
  528. up(&b->io_mutex);
  529. return 0;
  530. out_unlock:
  531. rw_unlock(true, b);
  532. return -ENOMEM;
  533. }
  534. static unsigned long bch_mca_scan(struct shrinker *shrink,
  535. struct shrink_control *sc)
  536. {
  537. struct cache_set *c = shrink->private_data;
  538. struct btree *b, *t;
  539. unsigned long i, nr = sc->nr_to_scan;
  540. unsigned long freed = 0;
  541. unsigned int btree_cache_used;
  542. if (c->shrinker_disabled)
  543. return SHRINK_STOP;
  544. if (c->btree_cache_alloc_lock)
  545. return SHRINK_STOP;
  546. /* Return -1 if we can't do anything right now */
  547. if (sc->gfp_mask & __GFP_IO)
  548. mutex_lock(&c->bucket_lock);
  549. else if (!mutex_trylock(&c->bucket_lock))
  550. return -1;
  551. /*
  552. * It's _really_ critical that we don't free too many btree nodes - we
  553. * have to always leave ourselves a reserve. The reserve is how we
  554. * guarantee that allocating memory for a new btree node can always
  555. * succeed, so that inserting keys into the btree can always succeed and
  556. * IO can always make forward progress:
  557. */
  558. nr /= c->btree_pages;
  559. if (nr == 0)
  560. nr = 1;
  561. nr = min_t(unsigned long, nr, mca_can_free(c));
  562. i = 0;
  563. btree_cache_used = c->btree_cache_used;
  564. list_for_each_entry_safe_reverse(b, t, &c->btree_cache_freeable, list) {
  565. if (nr <= 0)
  566. goto out;
  567. if (!mca_reap(b, 0, false)) {
  568. mca_data_free(b);
  569. rw_unlock(true, b);
  570. freed++;
  571. }
  572. nr--;
  573. i++;
  574. }
  575. list_for_each_entry_safe_reverse(b, t, &c->btree_cache, list) {
  576. if (nr <= 0 || i >= btree_cache_used)
  577. goto out;
  578. if (!mca_reap(b, 0, false)) {
  579. mca_bucket_free(b);
  580. mca_data_free(b);
  581. rw_unlock(true, b);
  582. freed++;
  583. }
  584. nr--;
  585. i++;
  586. }
  587. out:
  588. mutex_unlock(&c->bucket_lock);
  589. return freed * c->btree_pages;
  590. }
  591. static unsigned long bch_mca_count(struct shrinker *shrink,
  592. struct shrink_control *sc)
  593. {
  594. struct cache_set *c = shrink->private_data;
  595. if (c->shrinker_disabled)
  596. return 0;
  597. if (c->btree_cache_alloc_lock)
  598. return 0;
  599. return mca_can_free(c) * c->btree_pages;
  600. }
  601. void bch_btree_cache_free(struct cache_set *c)
  602. {
  603. struct btree *b;
  604. struct closure cl;
  605. closure_init_stack(&cl);
  606. if (c->shrink)
  607. shrinker_free(c->shrink);
  608. mutex_lock(&c->bucket_lock);
  609. #ifdef CONFIG_BCACHE_DEBUG
  610. if (c->verify_data)
  611. list_move(&c->verify_data->list, &c->btree_cache);
  612. free_pages((unsigned long) c->verify_ondisk, ilog2(meta_bucket_pages(&c->cache->sb)));
  613. #endif
  614. list_splice(&c->btree_cache_freeable,
  615. &c->btree_cache);
  616. while (!list_empty(&c->btree_cache)) {
  617. b = list_first_entry(&c->btree_cache, struct btree, list);
  618. /*
  619. * This function is called by cache_set_free(), no I/O
  620. * request on cache now, it is unnecessary to acquire
  621. * b->write_lock before clearing BTREE_NODE_dirty anymore.
  622. */
  623. if (btree_node_dirty(b)) {
  624. btree_complete_write(b, btree_current_write(b));
  625. clear_bit(BTREE_NODE_dirty, &b->flags);
  626. }
  627. mca_data_free(b);
  628. }
  629. while (!list_empty(&c->btree_cache_freed)) {
  630. b = list_first_entry(&c->btree_cache_freed,
  631. struct btree, list);
  632. list_del(&b->list);
  633. cancel_delayed_work_sync(&b->work);
  634. kfree(b);
  635. }
  636. mutex_unlock(&c->bucket_lock);
  637. }
  638. int bch_btree_cache_alloc(struct cache_set *c)
  639. {
  640. unsigned int i;
  641. for (i = 0; i < mca_reserve(c); i++)
  642. if (!mca_bucket_alloc(c, &ZERO_KEY, GFP_KERNEL))
  643. return -ENOMEM;
  644. list_splice_init(&c->btree_cache,
  645. &c->btree_cache_freeable);
  646. #ifdef CONFIG_BCACHE_DEBUG
  647. mutex_init(&c->verify_lock);
  648. c->verify_ondisk = (void *)
  649. __get_free_pages(GFP_KERNEL|__GFP_COMP,
  650. ilog2(meta_bucket_pages(&c->cache->sb)));
  651. if (!c->verify_ondisk) {
  652. /*
  653. * Don't worry about the mca_rereserve buckets
  654. * allocated in previous for-loop, they will be
  655. * handled properly in bch_cache_set_unregister().
  656. */
  657. return -ENOMEM;
  658. }
  659. c->verify_data = mca_bucket_alloc(c, &ZERO_KEY, GFP_KERNEL);
  660. if (c->verify_data &&
  661. c->verify_data->keys.set->data)
  662. list_del_init(&c->verify_data->list);
  663. else
  664. c->verify_data = NULL;
  665. #endif
  666. c->shrink = shrinker_alloc(0, "md-bcache:%pU", c->set_uuid);
  667. if (!c->shrink) {
  668. pr_warn("bcache: %s: could not allocate shrinker\n", __func__);
  669. return 0;
  670. }
  671. c->shrink->count_objects = bch_mca_count;
  672. c->shrink->scan_objects = bch_mca_scan;
  673. c->shrink->seeks = 4;
  674. c->shrink->batch = c->btree_pages * 2;
  675. c->shrink->private_data = c;
  676. shrinker_register(c->shrink);
  677. return 0;
  678. }
  679. /* Btree in memory cache - hash table */
  680. static struct hlist_head *mca_hash(struct cache_set *c, struct bkey *k)
  681. {
  682. return &c->bucket_hash[hash_32(PTR_HASH(c, k), BUCKET_HASH_BITS)];
  683. }
  684. static struct btree *mca_find(struct cache_set *c, struct bkey *k)
  685. {
  686. struct btree *b;
  687. rcu_read_lock();
  688. hlist_for_each_entry_rcu(b, mca_hash(c, k), hash)
  689. if (PTR_HASH(c, &b->key) == PTR_HASH(c, k))
  690. goto out;
  691. b = NULL;
  692. out:
  693. rcu_read_unlock();
  694. return b;
  695. }
  696. static int mca_cannibalize_lock(struct cache_set *c, struct btree_op *op)
  697. {
  698. spin_lock(&c->btree_cannibalize_lock);
  699. if (likely(c->btree_cache_alloc_lock == NULL)) {
  700. c->btree_cache_alloc_lock = current;
  701. } else if (c->btree_cache_alloc_lock != current) {
  702. if (op)
  703. prepare_to_wait(&c->btree_cache_wait, &op->wait,
  704. TASK_UNINTERRUPTIBLE);
  705. spin_unlock(&c->btree_cannibalize_lock);
  706. return -EINTR;
  707. }
  708. spin_unlock(&c->btree_cannibalize_lock);
  709. return 0;
  710. }
  711. static struct btree *mca_cannibalize(struct cache_set *c, struct btree_op *op,
  712. struct bkey *k)
  713. {
  714. struct btree *b;
  715. trace_bcache_btree_cache_cannibalize(c);
  716. if (mca_cannibalize_lock(c, op))
  717. return ERR_PTR(-EINTR);
  718. list_for_each_entry_reverse(b, &c->btree_cache, list)
  719. if (!mca_reap(b, btree_order(k), false))
  720. return b;
  721. list_for_each_entry_reverse(b, &c->btree_cache, list)
  722. if (!mca_reap(b, btree_order(k), true))
  723. return b;
  724. WARN(1, "btree cache cannibalize failed\n");
  725. return ERR_PTR(-ENOMEM);
  726. }
  727. /*
  728. * We can only have one thread cannibalizing other cached btree nodes at a time,
  729. * or we'll deadlock. We use an open coded mutex to ensure that, which a
  730. * cannibalize_bucket() will take. This means every time we unlock the root of
  731. * the btree, we need to release this lock if we have it held.
  732. */
  733. void bch_cannibalize_unlock(struct cache_set *c)
  734. {
  735. spin_lock(&c->btree_cannibalize_lock);
  736. if (c->btree_cache_alloc_lock == current) {
  737. c->btree_cache_alloc_lock = NULL;
  738. wake_up(&c->btree_cache_wait);
  739. }
  740. spin_unlock(&c->btree_cannibalize_lock);
  741. }
  742. static struct btree *mca_alloc(struct cache_set *c, struct btree_op *op,
  743. struct bkey *k, int level)
  744. {
  745. struct btree *b;
  746. BUG_ON(current->bio_list);
  747. lockdep_assert_held(&c->bucket_lock);
  748. if (mca_find(c, k))
  749. return NULL;
  750. /* btree_free() doesn't free memory; it sticks the node on the end of
  751. * the list. Check if there's any freed nodes there:
  752. */
  753. list_for_each_entry(b, &c->btree_cache_freeable, list)
  754. if (!mca_reap(b, btree_order(k), false))
  755. goto out;
  756. /* We never free struct btree itself, just the memory that holds the on
  757. * disk node. Check the freed list before allocating a new one:
  758. */
  759. list_for_each_entry(b, &c->btree_cache_freed, list)
  760. if (!mca_reap(b, 0, false)) {
  761. mca_data_alloc(b, k, __GFP_NOWARN|GFP_NOIO);
  762. if (!b->keys.set[0].data)
  763. goto err;
  764. else
  765. goto out;
  766. }
  767. b = mca_bucket_alloc(c, k, __GFP_NOWARN|GFP_NOIO);
  768. if (!b)
  769. goto err;
  770. BUG_ON(!down_write_trylock(&b->lock));
  771. if (!b->keys.set->data)
  772. goto err;
  773. out:
  774. BUG_ON(b->io_mutex.count != 1);
  775. bkey_copy(&b->key, k);
  776. list_move(&b->list, &c->btree_cache);
  777. hlist_del_init_rcu(&b->hash);
  778. hlist_add_head_rcu(&b->hash, mca_hash(c, k));
  779. lock_set_subclass(&b->lock.dep_map, level + 1, _THIS_IP_);
  780. b->parent = (void *) ~0UL;
  781. b->flags = 0;
  782. b->written = 0;
  783. b->level = level;
  784. if (!b->level)
  785. bch_btree_keys_init(&b->keys, &bch_extent_keys_ops,
  786. &b->c->expensive_debug_checks);
  787. else
  788. bch_btree_keys_init(&b->keys, &bch_btree_keys_ops,
  789. &b->c->expensive_debug_checks);
  790. return b;
  791. err:
  792. if (b)
  793. rw_unlock(true, b);
  794. b = mca_cannibalize(c, op, k);
  795. if (!IS_ERR(b))
  796. goto out;
  797. return b;
  798. }
  799. /*
  800. * bch_btree_node_get - find a btree node in the cache and lock it, reading it
  801. * in from disk if necessary.
  802. *
  803. * If IO is necessary and running under submit_bio_noacct, returns -EAGAIN.
  804. *
  805. * The btree node will have either a read or a write lock held, depending on
  806. * level and op->lock.
  807. *
  808. * Note: Only error code or btree pointer will be returned, it is unncessary
  809. * for callers to check NULL pointer.
  810. */
  811. struct btree *bch_btree_node_get(struct cache_set *c, struct btree_op *op,
  812. struct bkey *k, int level, bool write,
  813. struct btree *parent)
  814. {
  815. int i = 0;
  816. struct btree *b;
  817. BUG_ON(level < 0);
  818. retry:
  819. b = mca_find(c, k);
  820. if (!b) {
  821. if (current->bio_list)
  822. return ERR_PTR(-EAGAIN);
  823. mutex_lock(&c->bucket_lock);
  824. b = mca_alloc(c, op, k, level);
  825. mutex_unlock(&c->bucket_lock);
  826. if (!b)
  827. goto retry;
  828. if (IS_ERR(b))
  829. return b;
  830. bch_btree_node_read(b);
  831. if (!write)
  832. downgrade_write(&b->lock);
  833. } else {
  834. rw_lock(write, b, level);
  835. if (PTR_HASH(c, &b->key) != PTR_HASH(c, k)) {
  836. rw_unlock(write, b);
  837. goto retry;
  838. }
  839. BUG_ON(b->level != level);
  840. }
  841. if (btree_node_io_error(b)) {
  842. rw_unlock(write, b);
  843. return ERR_PTR(-EIO);
  844. }
  845. BUG_ON(!b->written);
  846. b->parent = parent;
  847. for (; i <= b->keys.nsets && b->keys.set[i].size; i++) {
  848. prefetch(b->keys.set[i].tree);
  849. prefetch(b->keys.set[i].data);
  850. }
  851. for (; i <= b->keys.nsets; i++)
  852. prefetch(b->keys.set[i].data);
  853. return b;
  854. }
  855. static void btree_node_prefetch(struct btree *parent, struct bkey *k)
  856. {
  857. struct btree *b;
  858. mutex_lock(&parent->c->bucket_lock);
  859. b = mca_alloc(parent->c, NULL, k, parent->level - 1);
  860. mutex_unlock(&parent->c->bucket_lock);
  861. if (!IS_ERR_OR_NULL(b)) {
  862. b->parent = parent;
  863. bch_btree_node_read(b);
  864. rw_unlock(true, b);
  865. }
  866. }
  867. /* Btree alloc */
  868. static void btree_node_free(struct btree *b)
  869. {
  870. trace_bcache_btree_node_free(b);
  871. BUG_ON(b == b->c->root);
  872. retry:
  873. mutex_lock(&b->write_lock);
  874. /*
  875. * If the btree node is selected and flushing in btree_flush_write(),
  876. * delay and retry until the BTREE_NODE_journal_flush bit cleared,
  877. * then it is safe to free the btree node here. Otherwise this btree
  878. * node will be in race condition.
  879. */
  880. if (btree_node_journal_flush(b)) {
  881. mutex_unlock(&b->write_lock);
  882. pr_debug("bnode %p journal_flush set, retry\n", b);
  883. udelay(1);
  884. goto retry;
  885. }
  886. if (btree_node_dirty(b)) {
  887. btree_complete_write(b, btree_current_write(b));
  888. clear_bit(BTREE_NODE_dirty, &b->flags);
  889. }
  890. mutex_unlock(&b->write_lock);
  891. cancel_delayed_work(&b->work);
  892. mutex_lock(&b->c->bucket_lock);
  893. bch_bucket_free(b->c, &b->key);
  894. mca_bucket_free(b);
  895. mutex_unlock(&b->c->bucket_lock);
  896. }
  897. /*
  898. * Only error code or btree pointer will be returned, it is unncessary for
  899. * callers to check NULL pointer.
  900. */
  901. struct btree *__bch_btree_node_alloc(struct cache_set *c, struct btree_op *op,
  902. int level, bool wait,
  903. struct btree *parent)
  904. {
  905. BKEY_PADDED(key) k;
  906. struct btree *b;
  907. mutex_lock(&c->bucket_lock);
  908. retry:
  909. /* return ERR_PTR(-EAGAIN) when it fails */
  910. b = ERR_PTR(-EAGAIN);
  911. if (__bch_bucket_alloc_set(c, RESERVE_BTREE, &k.key, wait))
  912. goto err;
  913. bkey_put(c, &k.key);
  914. SET_KEY_SIZE(&k.key, c->btree_pages * PAGE_SECTORS);
  915. b = mca_alloc(c, op, &k.key, level);
  916. if (IS_ERR(b))
  917. goto err_free;
  918. if (!b) {
  919. cache_bug(c,
  920. "Tried to allocate bucket that was in btree cache");
  921. goto retry;
  922. }
  923. b->parent = parent;
  924. bch_bset_init_next(&b->keys, b->keys.set->data, bset_magic(&b->c->cache->sb));
  925. mutex_unlock(&c->bucket_lock);
  926. trace_bcache_btree_node_alloc(b);
  927. return b;
  928. err_free:
  929. bch_bucket_free(c, &k.key);
  930. err:
  931. mutex_unlock(&c->bucket_lock);
  932. trace_bcache_btree_node_alloc_fail(c);
  933. return b;
  934. }
  935. static struct btree *bch_btree_node_alloc(struct cache_set *c,
  936. struct btree_op *op, int level,
  937. struct btree *parent)
  938. {
  939. return __bch_btree_node_alloc(c, op, level, op != NULL, parent);
  940. }
  941. static struct btree *btree_node_alloc_replacement(struct btree *b,
  942. struct btree_op *op)
  943. {
  944. struct btree *n = bch_btree_node_alloc(b->c, op, b->level, b->parent);
  945. if (!IS_ERR(n)) {
  946. mutex_lock(&n->write_lock);
  947. bch_btree_sort_into(&b->keys, &n->keys, &b->c->sort);
  948. bkey_copy_key(&n->key, &b->key);
  949. mutex_unlock(&n->write_lock);
  950. }
  951. return n;
  952. }
  953. static void make_btree_freeing_key(struct btree *b, struct bkey *k)
  954. {
  955. unsigned int i;
  956. mutex_lock(&b->c->bucket_lock);
  957. atomic_inc(&b->c->prio_blocked);
  958. bkey_copy(k, &b->key);
  959. bkey_copy_key(k, &ZERO_KEY);
  960. for (i = 0; i < KEY_PTRS(k); i++)
  961. SET_PTR_GEN(k, i,
  962. bch_inc_gen(b->c->cache,
  963. PTR_BUCKET(b->c, &b->key, i)));
  964. mutex_unlock(&b->c->bucket_lock);
  965. }
  966. static int btree_check_reserve(struct btree *b, struct btree_op *op)
  967. {
  968. struct cache_set *c = b->c;
  969. struct cache *ca = c->cache;
  970. unsigned int reserve = (c->root->level - b->level) * 2 + 1;
  971. mutex_lock(&c->bucket_lock);
  972. if (fifo_used(&ca->free[RESERVE_BTREE]) < reserve) {
  973. if (op)
  974. prepare_to_wait(&c->btree_cache_wait, &op->wait,
  975. TASK_UNINTERRUPTIBLE);
  976. mutex_unlock(&c->bucket_lock);
  977. return -EINTR;
  978. }
  979. mutex_unlock(&c->bucket_lock);
  980. return mca_cannibalize_lock(b->c, op);
  981. }
  982. /* Garbage collection */
  983. static uint8_t __bch_btree_mark_key(struct cache_set *c, int level,
  984. struct bkey *k)
  985. {
  986. uint8_t stale = 0;
  987. unsigned int i;
  988. struct bucket *g;
  989. /*
  990. * ptr_invalid() can't return true for the keys that mark btree nodes as
  991. * freed, but since ptr_bad() returns true we'll never actually use them
  992. * for anything and thus we don't want mark their pointers here
  993. */
  994. if (!bkey_cmp(k, &ZERO_KEY))
  995. return stale;
  996. for (i = 0; i < KEY_PTRS(k); i++) {
  997. if (!ptr_available(c, k, i))
  998. continue;
  999. g = PTR_BUCKET(c, k, i);
  1000. if (gen_after(g->last_gc, PTR_GEN(k, i)))
  1001. g->last_gc = PTR_GEN(k, i);
  1002. if (ptr_stale(c, k, i)) {
  1003. stale = max(stale, ptr_stale(c, k, i));
  1004. continue;
  1005. }
  1006. cache_bug_on(GC_MARK(g) &&
  1007. (GC_MARK(g) == GC_MARK_METADATA) != (level != 0),
  1008. c, "inconsistent ptrs: mark = %llu, level = %i",
  1009. GC_MARK(g), level);
  1010. if (level)
  1011. SET_GC_MARK(g, GC_MARK_METADATA);
  1012. else if (KEY_DIRTY(k))
  1013. SET_GC_MARK(g, GC_MARK_DIRTY);
  1014. else if (!GC_MARK(g))
  1015. SET_GC_MARK(g, GC_MARK_RECLAIMABLE);
  1016. /* guard against overflow */
  1017. SET_GC_SECTORS_USED(g, min_t(unsigned int,
  1018. GC_SECTORS_USED(g) + KEY_SIZE(k),
  1019. MAX_GC_SECTORS_USED));
  1020. BUG_ON(!GC_SECTORS_USED(g));
  1021. }
  1022. return stale;
  1023. }
  1024. #define btree_mark_key(b, k) __bch_btree_mark_key(b->c, b->level, k)
  1025. void bch_initial_mark_key(struct cache_set *c, int level, struct bkey *k)
  1026. {
  1027. unsigned int i;
  1028. for (i = 0; i < KEY_PTRS(k); i++)
  1029. if (ptr_available(c, k, i) &&
  1030. !ptr_stale(c, k, i)) {
  1031. struct bucket *b = PTR_BUCKET(c, k, i);
  1032. b->gen = PTR_GEN(k, i);
  1033. if (level && bkey_cmp(k, &ZERO_KEY))
  1034. b->prio = BTREE_PRIO;
  1035. else if (!level && b->prio == BTREE_PRIO)
  1036. b->prio = INITIAL_PRIO;
  1037. }
  1038. __bch_btree_mark_key(c, level, k);
  1039. }
  1040. void bch_update_bucket_in_use(struct cache_set *c, struct gc_stat *stats)
  1041. {
  1042. stats->in_use = (c->nbuckets - c->avail_nbuckets) * 100 / c->nbuckets;
  1043. }
  1044. static bool btree_gc_mark_node(struct btree *b, struct gc_stat *gc)
  1045. {
  1046. uint8_t stale = 0;
  1047. unsigned int keys = 0, good_keys = 0;
  1048. struct bkey *k;
  1049. struct btree_iter_stack iter;
  1050. struct bset_tree *t;
  1051. gc->nodes++;
  1052. for_each_key_filter(&b->keys, k, &iter, bch_ptr_invalid) {
  1053. stale = max(stale, btree_mark_key(b, k));
  1054. keys++;
  1055. if (bch_ptr_bad(&b->keys, k))
  1056. continue;
  1057. gc->key_bytes += bkey_u64s(k);
  1058. gc->nkeys++;
  1059. good_keys++;
  1060. gc->data += KEY_SIZE(k);
  1061. }
  1062. for (t = b->keys.set; t <= &b->keys.set[b->keys.nsets]; t++)
  1063. btree_bug_on(t->size &&
  1064. bset_written(&b->keys, t) &&
  1065. bkey_cmp(&b->key, &t->end) < 0,
  1066. b, "found short btree key in gc");
  1067. if (b->c->gc_always_rewrite)
  1068. return true;
  1069. if (stale > 10)
  1070. return true;
  1071. if ((keys - good_keys) * 2 > keys)
  1072. return true;
  1073. return false;
  1074. }
  1075. #define GC_MERGE_NODES 4U
  1076. struct gc_merge_info {
  1077. struct btree *b;
  1078. unsigned int keys;
  1079. };
  1080. static int bch_btree_insert_node(struct btree *b, struct btree_op *op,
  1081. struct keylist *insert_keys,
  1082. atomic_t *journal_ref,
  1083. struct bkey *replace_key);
  1084. static int btree_gc_coalesce(struct btree *b, struct btree_op *op,
  1085. struct gc_stat *gc, struct gc_merge_info *r)
  1086. {
  1087. unsigned int i, nodes = 0, keys = 0, blocks;
  1088. struct btree *new_nodes[GC_MERGE_NODES];
  1089. struct keylist keylist;
  1090. struct closure cl;
  1091. struct bkey *k;
  1092. bch_keylist_init(&keylist);
  1093. if (btree_check_reserve(b, NULL))
  1094. return 0;
  1095. memset(new_nodes, 0, sizeof(new_nodes));
  1096. closure_init_stack(&cl);
  1097. while (nodes < GC_MERGE_NODES && !IS_ERR_OR_NULL(r[nodes].b))
  1098. keys += r[nodes++].keys;
  1099. blocks = btree_default_blocks(b->c) * 2 / 3;
  1100. if (nodes < 2 ||
  1101. __set_blocks(b->keys.set[0].data, keys,
  1102. block_bytes(b->c->cache)) > blocks * (nodes - 1))
  1103. return 0;
  1104. for (i = 0; i < nodes; i++) {
  1105. new_nodes[i] = btree_node_alloc_replacement(r[i].b, NULL);
  1106. if (IS_ERR(new_nodes[i]))
  1107. goto out_nocoalesce;
  1108. }
  1109. /*
  1110. * We have to check the reserve here, after we've allocated our new
  1111. * nodes, to make sure the insert below will succeed - we also check
  1112. * before as an optimization to potentially avoid a bunch of expensive
  1113. * allocs/sorts
  1114. */
  1115. if (btree_check_reserve(b, NULL))
  1116. goto out_nocoalesce;
  1117. for (i = 0; i < nodes; i++)
  1118. mutex_lock(&new_nodes[i]->write_lock);
  1119. for (i = nodes - 1; i > 0; --i) {
  1120. struct bset *n1 = btree_bset_first(new_nodes[i]);
  1121. struct bset *n2 = btree_bset_first(new_nodes[i - 1]);
  1122. struct bkey *k, *last = NULL;
  1123. keys = 0;
  1124. if (i > 1) {
  1125. for (k = n2->start;
  1126. k < bset_bkey_last(n2);
  1127. k = bkey_next(k)) {
  1128. if (__set_blocks(n1, n1->keys + keys +
  1129. bkey_u64s(k),
  1130. block_bytes(b->c->cache)) > blocks)
  1131. break;
  1132. last = k;
  1133. keys += bkey_u64s(k);
  1134. }
  1135. } else {
  1136. /*
  1137. * Last node we're not getting rid of - we're getting
  1138. * rid of the node at r[0]. Have to try and fit all of
  1139. * the remaining keys into this node; we can't ensure
  1140. * they will always fit due to rounding and variable
  1141. * length keys (shouldn't be possible in practice,
  1142. * though)
  1143. */
  1144. if (__set_blocks(n1, n1->keys + n2->keys,
  1145. block_bytes(b->c->cache)) >
  1146. btree_blocks(new_nodes[i]))
  1147. goto out_unlock_nocoalesce;
  1148. keys = n2->keys;
  1149. /* Take the key of the node we're getting rid of */
  1150. last = &r->b->key;
  1151. }
  1152. BUG_ON(__set_blocks(n1, n1->keys + keys, block_bytes(b->c->cache)) >
  1153. btree_blocks(new_nodes[i]));
  1154. if (last)
  1155. bkey_copy_key(&new_nodes[i]->key, last);
  1156. memcpy(bset_bkey_last(n1),
  1157. n2->start,
  1158. (void *) bset_bkey_idx(n2, keys) - (void *) n2->start);
  1159. n1->keys += keys;
  1160. r[i].keys = n1->keys;
  1161. memmove(n2->start,
  1162. bset_bkey_idx(n2, keys),
  1163. (void *) bset_bkey_last(n2) -
  1164. (void *) bset_bkey_idx(n2, keys));
  1165. n2->keys -= keys;
  1166. if (__bch_keylist_realloc(&keylist,
  1167. bkey_u64s(&new_nodes[i]->key)))
  1168. goto out_unlock_nocoalesce;
  1169. bch_btree_node_write(new_nodes[i], &cl);
  1170. bch_keylist_add(&keylist, &new_nodes[i]->key);
  1171. }
  1172. for (i = 0; i < nodes; i++)
  1173. mutex_unlock(&new_nodes[i]->write_lock);
  1174. closure_sync(&cl);
  1175. /* We emptied out this node */
  1176. BUG_ON(btree_bset_first(new_nodes[0])->keys);
  1177. btree_node_free(new_nodes[0]);
  1178. rw_unlock(true, new_nodes[0]);
  1179. new_nodes[0] = NULL;
  1180. for (i = 0; i < nodes; i++) {
  1181. if (__bch_keylist_realloc(&keylist, bkey_u64s(&r[i].b->key)))
  1182. goto out_nocoalesce;
  1183. make_btree_freeing_key(r[i].b, keylist.top);
  1184. bch_keylist_push(&keylist);
  1185. }
  1186. bch_btree_insert_node(b, op, &keylist, NULL, NULL);
  1187. BUG_ON(!bch_keylist_empty(&keylist));
  1188. for (i = 0; i < nodes; i++) {
  1189. btree_node_free(r[i].b);
  1190. rw_unlock(true, r[i].b);
  1191. r[i].b = new_nodes[i];
  1192. }
  1193. memmove(r, r + 1, sizeof(r[0]) * (nodes - 1));
  1194. r[nodes - 1].b = ERR_PTR(-EINTR);
  1195. trace_bcache_btree_gc_coalesce(nodes);
  1196. gc->nodes--;
  1197. bch_keylist_free(&keylist);
  1198. /* Invalidated our iterator */
  1199. return -EINTR;
  1200. out_unlock_nocoalesce:
  1201. for (i = 0; i < nodes; i++)
  1202. mutex_unlock(&new_nodes[i]->write_lock);
  1203. out_nocoalesce:
  1204. closure_sync(&cl);
  1205. while ((k = bch_keylist_pop(&keylist)))
  1206. if (!bkey_cmp(k, &ZERO_KEY))
  1207. atomic_dec(&b->c->prio_blocked);
  1208. bch_keylist_free(&keylist);
  1209. for (i = 0; i < nodes; i++)
  1210. if (!IS_ERR_OR_NULL(new_nodes[i])) {
  1211. btree_node_free(new_nodes[i]);
  1212. rw_unlock(true, new_nodes[i]);
  1213. }
  1214. return 0;
  1215. }
  1216. static int btree_gc_rewrite_node(struct btree *b, struct btree_op *op,
  1217. struct btree *replace)
  1218. {
  1219. struct keylist keys;
  1220. struct btree *n;
  1221. if (btree_check_reserve(b, NULL))
  1222. return 0;
  1223. n = btree_node_alloc_replacement(replace, NULL);
  1224. if (IS_ERR(n))
  1225. return 0;
  1226. /* recheck reserve after allocating replacement node */
  1227. if (btree_check_reserve(b, NULL)) {
  1228. btree_node_free(n);
  1229. rw_unlock(true, n);
  1230. return 0;
  1231. }
  1232. bch_btree_node_write_sync(n);
  1233. bch_keylist_init(&keys);
  1234. bch_keylist_add(&keys, &n->key);
  1235. make_btree_freeing_key(replace, keys.top);
  1236. bch_keylist_push(&keys);
  1237. bch_btree_insert_node(b, op, &keys, NULL, NULL);
  1238. BUG_ON(!bch_keylist_empty(&keys));
  1239. btree_node_free(replace);
  1240. rw_unlock(true, n);
  1241. /* Invalidated our iterator */
  1242. return -EINTR;
  1243. }
  1244. static unsigned int btree_gc_count_keys(struct btree *b)
  1245. {
  1246. struct bkey *k;
  1247. struct btree_iter_stack iter;
  1248. unsigned int ret = 0;
  1249. for_each_key_filter(&b->keys, k, &iter, bch_ptr_bad)
  1250. ret += bkey_u64s(k);
  1251. return ret;
  1252. }
  1253. static size_t btree_gc_min_nodes(struct cache_set *c)
  1254. {
  1255. size_t min_nodes;
  1256. /*
  1257. * Since incremental GC would stop 100ms when front
  1258. * side I/O comes, so when there are many btree nodes,
  1259. * if GC only processes constant (100) nodes each time,
  1260. * GC would last a long time, and the front side I/Os
  1261. * would run out of the buckets (since no new bucket
  1262. * can be allocated during GC), and be blocked again.
  1263. * So GC should not process constant nodes, but varied
  1264. * nodes according to the number of btree nodes, which
  1265. * realized by dividing GC into constant(100) times,
  1266. * so when there are many btree nodes, GC can process
  1267. * more nodes each time, otherwise, GC will process less
  1268. * nodes each time (but no less than MIN_GC_NODES)
  1269. */
  1270. min_nodes = c->gc_stats.nodes / MAX_GC_TIMES;
  1271. if (min_nodes < MIN_GC_NODES)
  1272. min_nodes = MIN_GC_NODES;
  1273. return min_nodes;
  1274. }
  1275. static int btree_gc_recurse(struct btree *b, struct btree_op *op,
  1276. struct closure *writes, struct gc_stat *gc)
  1277. {
  1278. int ret = 0;
  1279. bool should_rewrite;
  1280. struct bkey *k;
  1281. struct btree_iter_stack iter;
  1282. struct gc_merge_info r[GC_MERGE_NODES];
  1283. struct gc_merge_info *i, *last = r + ARRAY_SIZE(r) - 1;
  1284. bch_btree_iter_stack_init(&b->keys, &iter, &b->c->gc_done);
  1285. for (i = r; i < r + ARRAY_SIZE(r); i++)
  1286. i->b = ERR_PTR(-EINTR);
  1287. while (1) {
  1288. k = bch_btree_iter_next_filter(&iter.iter, &b->keys,
  1289. bch_ptr_bad);
  1290. if (k) {
  1291. r->b = bch_btree_node_get(b->c, op, k, b->level - 1,
  1292. true, b);
  1293. if (IS_ERR(r->b)) {
  1294. ret = PTR_ERR(r->b);
  1295. break;
  1296. }
  1297. r->keys = btree_gc_count_keys(r->b);
  1298. ret = btree_gc_coalesce(b, op, gc, r);
  1299. if (ret)
  1300. break;
  1301. }
  1302. if (!last->b)
  1303. break;
  1304. if (!IS_ERR(last->b)) {
  1305. should_rewrite = btree_gc_mark_node(last->b, gc);
  1306. if (should_rewrite) {
  1307. ret = btree_gc_rewrite_node(b, op, last->b);
  1308. if (ret)
  1309. break;
  1310. }
  1311. if (last->b->level) {
  1312. ret = btree_gc_recurse(last->b, op, writes, gc);
  1313. if (ret)
  1314. break;
  1315. }
  1316. bkey_copy_key(&b->c->gc_done, &last->b->key);
  1317. /*
  1318. * Must flush leaf nodes before gc ends, since replace
  1319. * operations aren't journalled
  1320. */
  1321. mutex_lock(&last->b->write_lock);
  1322. if (btree_node_dirty(last->b))
  1323. bch_btree_node_write(last->b, writes);
  1324. mutex_unlock(&last->b->write_lock);
  1325. rw_unlock(true, last->b);
  1326. }
  1327. memmove(r + 1, r, sizeof(r[0]) * (GC_MERGE_NODES - 1));
  1328. r->b = NULL;
  1329. if (atomic_read(&b->c->search_inflight) &&
  1330. gc->nodes >= gc->nodes_pre + btree_gc_min_nodes(b->c)) {
  1331. gc->nodes_pre = gc->nodes;
  1332. ret = -EAGAIN;
  1333. break;
  1334. }
  1335. if (need_resched()) {
  1336. ret = -EAGAIN;
  1337. break;
  1338. }
  1339. }
  1340. for (i = r; i < r + ARRAY_SIZE(r); i++)
  1341. if (!IS_ERR_OR_NULL(i->b)) {
  1342. mutex_lock(&i->b->write_lock);
  1343. if (btree_node_dirty(i->b))
  1344. bch_btree_node_write(i->b, writes);
  1345. mutex_unlock(&i->b->write_lock);
  1346. rw_unlock(true, i->b);
  1347. }
  1348. return ret;
  1349. }
  1350. static int bch_btree_gc_root(struct btree *b, struct btree_op *op,
  1351. struct closure *writes, struct gc_stat *gc)
  1352. {
  1353. struct btree *n = NULL;
  1354. int ret = 0;
  1355. bool should_rewrite;
  1356. should_rewrite = btree_gc_mark_node(b, gc);
  1357. if (should_rewrite) {
  1358. n = btree_node_alloc_replacement(b, NULL);
  1359. if (!IS_ERR(n)) {
  1360. bch_btree_node_write_sync(n);
  1361. bch_btree_set_root(n);
  1362. btree_node_free(b);
  1363. rw_unlock(true, n);
  1364. return -EINTR;
  1365. }
  1366. }
  1367. __bch_btree_mark_key(b->c, b->level + 1, &b->key);
  1368. if (b->level) {
  1369. ret = btree_gc_recurse(b, op, writes, gc);
  1370. if (ret)
  1371. return ret;
  1372. }
  1373. bkey_copy_key(&b->c->gc_done, &b->key);
  1374. return ret;
  1375. }
  1376. static void btree_gc_start(struct cache_set *c)
  1377. {
  1378. struct cache *ca;
  1379. struct bucket *b;
  1380. if (!c->gc_mark_valid)
  1381. return;
  1382. mutex_lock(&c->bucket_lock);
  1383. c->gc_done = ZERO_KEY;
  1384. ca = c->cache;
  1385. for_each_bucket(b, ca) {
  1386. b->last_gc = b->gen;
  1387. if (bch_can_invalidate_bucket(ca, b))
  1388. b->reclaimable_in_gc = 1;
  1389. if (!atomic_read(&b->pin)) {
  1390. SET_GC_MARK(b, 0);
  1391. SET_GC_SECTORS_USED(b, 0);
  1392. }
  1393. }
  1394. c->gc_mark_valid = 0;
  1395. mutex_unlock(&c->bucket_lock);
  1396. }
  1397. static void bch_btree_gc_finish(struct cache_set *c)
  1398. {
  1399. struct bucket *b;
  1400. struct cache *ca;
  1401. unsigned int i, j;
  1402. uint64_t *k;
  1403. mutex_lock(&c->bucket_lock);
  1404. set_gc_sectors(c);
  1405. c->gc_mark_valid = 1;
  1406. c->need_gc = 0;
  1407. for (i = 0; i < KEY_PTRS(&c->uuid_bucket); i++)
  1408. SET_GC_MARK(PTR_BUCKET(c, &c->uuid_bucket, i),
  1409. GC_MARK_METADATA);
  1410. /* don't reclaim buckets to which writeback keys point */
  1411. rcu_read_lock();
  1412. for (i = 0; i < c->devices_max_used; i++) {
  1413. struct bcache_device *d = c->devices[i];
  1414. struct cached_dev *dc;
  1415. struct keybuf_key *w, *n;
  1416. if (!d || UUID_FLASH_ONLY(&c->uuids[i]))
  1417. continue;
  1418. dc = container_of(d, struct cached_dev, disk);
  1419. spin_lock(&dc->writeback_keys.lock);
  1420. rbtree_postorder_for_each_entry_safe(w, n,
  1421. &dc->writeback_keys.keys, node)
  1422. for (j = 0; j < KEY_PTRS(&w->key); j++)
  1423. SET_GC_MARK(PTR_BUCKET(c, &w->key, j),
  1424. GC_MARK_DIRTY);
  1425. spin_unlock(&dc->writeback_keys.lock);
  1426. }
  1427. rcu_read_unlock();
  1428. c->avail_nbuckets = 0;
  1429. ca = c->cache;
  1430. ca->invalidate_needs_gc = 0;
  1431. for (k = ca->sb.d; k < ca->sb.d + ca->sb.keys; k++)
  1432. SET_GC_MARK(ca->buckets + *k, GC_MARK_METADATA);
  1433. for (k = ca->prio_buckets;
  1434. k < ca->prio_buckets + prio_buckets(ca) * 2; k++)
  1435. SET_GC_MARK(ca->buckets + *k, GC_MARK_METADATA);
  1436. for_each_bucket(b, ca) {
  1437. c->need_gc = max(c->need_gc, bucket_gc_gen(b));
  1438. if (b->reclaimable_in_gc)
  1439. b->reclaimable_in_gc = 0;
  1440. if (atomic_read(&b->pin))
  1441. continue;
  1442. BUG_ON(!GC_MARK(b) && GC_SECTORS_USED(b));
  1443. if (!GC_MARK(b) || GC_MARK(b) == GC_MARK_RECLAIMABLE)
  1444. c->avail_nbuckets++;
  1445. }
  1446. mutex_unlock(&c->bucket_lock);
  1447. }
  1448. static void bch_btree_gc(struct cache_set *c)
  1449. {
  1450. int ret;
  1451. struct gc_stat stats;
  1452. struct closure writes;
  1453. struct btree_op op;
  1454. uint64_t start_time = local_clock();
  1455. trace_bcache_gc_start(c);
  1456. memset(&stats, 0, sizeof(struct gc_stat));
  1457. closure_init_stack(&writes);
  1458. bch_btree_op_init(&op, SHRT_MAX);
  1459. btree_gc_start(c);
  1460. /* if CACHE_SET_IO_DISABLE set, gc thread should stop too */
  1461. do {
  1462. ret = bcache_btree_root(gc_root, c, &op, &writes, &stats);
  1463. closure_sync(&writes);
  1464. cond_resched();
  1465. if (ret == -EAGAIN)
  1466. schedule_timeout_interruptible(msecs_to_jiffies
  1467. (GC_SLEEP_MS));
  1468. else if (ret)
  1469. pr_warn("gc failed!\n");
  1470. } while (ret && !test_bit(CACHE_SET_IO_DISABLE, &c->flags));
  1471. bch_btree_gc_finish(c);
  1472. wake_up_allocators(c);
  1473. bch_time_stats_update(&c->btree_gc_time, start_time);
  1474. stats.key_bytes *= sizeof(uint64_t);
  1475. stats.data <<= 9;
  1476. bch_update_bucket_in_use(c, &stats);
  1477. memcpy(&c->gc_stats, &stats, sizeof(struct gc_stat));
  1478. trace_bcache_gc_end(c);
  1479. bch_moving_gc(c);
  1480. }
  1481. static bool gc_should_run(struct cache_set *c)
  1482. {
  1483. struct cache *ca = c->cache;
  1484. if (ca->invalidate_needs_gc)
  1485. return true;
  1486. if (atomic_read(&c->sectors_to_gc) < 0)
  1487. return true;
  1488. return false;
  1489. }
  1490. static int bch_gc_thread(void *arg)
  1491. {
  1492. struct cache_set *c = arg;
  1493. while (1) {
  1494. wait_event_interruptible(c->gc_wait,
  1495. kthread_should_stop() ||
  1496. test_bit(CACHE_SET_IO_DISABLE, &c->flags) ||
  1497. gc_should_run(c));
  1498. if (kthread_should_stop() ||
  1499. test_bit(CACHE_SET_IO_DISABLE, &c->flags))
  1500. break;
  1501. set_gc_sectors(c);
  1502. bch_btree_gc(c);
  1503. }
  1504. wait_for_kthread_stop();
  1505. return 0;
  1506. }
  1507. int bch_gc_thread_start(struct cache_set *c)
  1508. {
  1509. c->gc_thread = kthread_run(bch_gc_thread, c, "bcache_gc");
  1510. return PTR_ERR_OR_ZERO(c->gc_thread);
  1511. }
  1512. /* Initial partial gc */
  1513. static int bch_btree_check_recurse(struct btree *b, struct btree_op *op)
  1514. {
  1515. int ret = 0;
  1516. struct bkey *k, *p = NULL;
  1517. struct btree_iter_stack iter;
  1518. for_each_key_filter(&b->keys, k, &iter, bch_ptr_invalid)
  1519. bch_initial_mark_key(b->c, b->level, k);
  1520. bch_initial_mark_key(b->c, b->level + 1, &b->key);
  1521. if (b->level) {
  1522. bch_btree_iter_stack_init(&b->keys, &iter, NULL);
  1523. do {
  1524. k = bch_btree_iter_next_filter(&iter.iter, &b->keys,
  1525. bch_ptr_bad);
  1526. if (k) {
  1527. btree_node_prefetch(b, k);
  1528. /*
  1529. * initiallize c->gc_stats.nodes
  1530. * for incremental GC
  1531. */
  1532. b->c->gc_stats.nodes++;
  1533. }
  1534. if (p)
  1535. ret = bcache_btree(check_recurse, p, b, op);
  1536. p = k;
  1537. } while (p && !ret);
  1538. }
  1539. return ret;
  1540. }
  1541. static int bch_btree_check_thread(void *arg)
  1542. {
  1543. int ret;
  1544. struct btree_check_info *info = arg;
  1545. struct btree_check_state *check_state = info->state;
  1546. struct cache_set *c = check_state->c;
  1547. struct btree_iter_stack iter;
  1548. struct bkey *k, *p;
  1549. int cur_idx, prev_idx, skip_nr;
  1550. k = p = NULL;
  1551. cur_idx = prev_idx = 0;
  1552. ret = 0;
  1553. /* root node keys are checked before thread created */
  1554. bch_btree_iter_stack_init(&c->root->keys, &iter, NULL);
  1555. k = bch_btree_iter_next_filter(&iter.iter, &c->root->keys, bch_ptr_bad);
  1556. BUG_ON(!k);
  1557. p = k;
  1558. while (k) {
  1559. /*
  1560. * Fetch a root node key index, skip the keys which
  1561. * should be fetched by other threads, then check the
  1562. * sub-tree indexed by the fetched key.
  1563. */
  1564. spin_lock(&check_state->idx_lock);
  1565. cur_idx = check_state->key_idx;
  1566. check_state->key_idx++;
  1567. spin_unlock(&check_state->idx_lock);
  1568. skip_nr = cur_idx - prev_idx;
  1569. while (skip_nr) {
  1570. k = bch_btree_iter_next_filter(&iter.iter,
  1571. &c->root->keys,
  1572. bch_ptr_bad);
  1573. if (k)
  1574. p = k;
  1575. else {
  1576. /*
  1577. * No more keys to check in root node,
  1578. * current checking threads are enough,
  1579. * stop creating more.
  1580. */
  1581. atomic_set(&check_state->enough, 1);
  1582. /* Update check_state->enough earlier */
  1583. smp_mb__after_atomic();
  1584. goto out;
  1585. }
  1586. skip_nr--;
  1587. cond_resched();
  1588. }
  1589. if (p) {
  1590. struct btree_op op;
  1591. btree_node_prefetch(c->root, p);
  1592. c->gc_stats.nodes++;
  1593. bch_btree_op_init(&op, 0);
  1594. ret = bcache_btree(check_recurse, p, c->root, &op);
  1595. /*
  1596. * The op may be added to cache_set's btree_cache_wait
  1597. * in mca_cannibalize(), must ensure it is removed from
  1598. * the list and release btree_cache_alloc_lock before
  1599. * free op memory.
  1600. * Otherwise, the btree_cache_wait will be damaged.
  1601. */
  1602. bch_cannibalize_unlock(c);
  1603. finish_wait(&c->btree_cache_wait, &(&op)->wait);
  1604. if (ret)
  1605. goto out;
  1606. }
  1607. p = NULL;
  1608. prev_idx = cur_idx;
  1609. cond_resched();
  1610. }
  1611. out:
  1612. info->result = ret;
  1613. /* update check_state->started among all CPUs */
  1614. smp_mb__before_atomic();
  1615. if (atomic_dec_and_test(&check_state->started))
  1616. wake_up(&check_state->wait);
  1617. return ret;
  1618. }
  1619. static int bch_btree_chkthread_nr(void)
  1620. {
  1621. int n = num_online_cpus()/2;
  1622. if (n == 0)
  1623. n = 1;
  1624. else if (n > BCH_BTR_CHKTHREAD_MAX)
  1625. n = BCH_BTR_CHKTHREAD_MAX;
  1626. return n;
  1627. }
  1628. int bch_btree_check(struct cache_set *c)
  1629. {
  1630. int ret = 0;
  1631. int i;
  1632. struct bkey *k = NULL;
  1633. struct btree_iter_stack iter;
  1634. struct btree_check_state check_state;
  1635. /* check and mark root node keys */
  1636. for_each_key_filter(&c->root->keys, k, &iter, bch_ptr_invalid)
  1637. bch_initial_mark_key(c, c->root->level, k);
  1638. bch_initial_mark_key(c, c->root->level + 1, &c->root->key);
  1639. if (c->root->level == 0)
  1640. return 0;
  1641. memset(&check_state, 0, sizeof(struct btree_check_state));
  1642. check_state.c = c;
  1643. check_state.total_threads = bch_btree_chkthread_nr();
  1644. check_state.key_idx = 0;
  1645. spin_lock_init(&check_state.idx_lock);
  1646. atomic_set(&check_state.started, 0);
  1647. atomic_set(&check_state.enough, 0);
  1648. init_waitqueue_head(&check_state.wait);
  1649. rw_lock(0, c->root, c->root->level);
  1650. /*
  1651. * Run multiple threads to check btree nodes in parallel,
  1652. * if check_state.enough is non-zero, it means current
  1653. * running check threads are enough, unncessary to create
  1654. * more.
  1655. */
  1656. for (i = 0; i < check_state.total_threads; i++) {
  1657. /* fetch latest check_state.enough earlier */
  1658. smp_mb__before_atomic();
  1659. if (atomic_read(&check_state.enough))
  1660. break;
  1661. check_state.infos[i].result = 0;
  1662. check_state.infos[i].state = &check_state;
  1663. check_state.infos[i].thread =
  1664. kthread_run(bch_btree_check_thread,
  1665. &check_state.infos[i],
  1666. "bch_btrchk[%d]", i);
  1667. if (IS_ERR(check_state.infos[i].thread)) {
  1668. pr_err("fails to run thread bch_btrchk[%d]\n", i);
  1669. for (--i; i >= 0; i--)
  1670. kthread_stop(check_state.infos[i].thread);
  1671. ret = -ENOMEM;
  1672. goto out;
  1673. }
  1674. atomic_inc(&check_state.started);
  1675. }
  1676. /*
  1677. * Must wait for all threads to stop.
  1678. */
  1679. wait_event(check_state.wait, atomic_read(&check_state.started) == 0);
  1680. for (i = 0; i < check_state.total_threads; i++) {
  1681. if (check_state.infos[i].result) {
  1682. ret = check_state.infos[i].result;
  1683. goto out;
  1684. }
  1685. }
  1686. out:
  1687. rw_unlock(0, c->root);
  1688. return ret;
  1689. }
  1690. void bch_initial_gc_finish(struct cache_set *c)
  1691. {
  1692. struct cache *ca = c->cache;
  1693. struct bucket *b;
  1694. bch_btree_gc_finish(c);
  1695. mutex_lock(&c->bucket_lock);
  1696. /*
  1697. * We need to put some unused buckets directly on the prio freelist in
  1698. * order to get the allocator thread started - it needs freed buckets in
  1699. * order to rewrite the prios and gens, and it needs to rewrite prios
  1700. * and gens in order to free buckets.
  1701. *
  1702. * This is only safe for buckets that have no live data in them, which
  1703. * there should always be some of.
  1704. */
  1705. for_each_bucket(b, ca) {
  1706. if (fifo_full(&ca->free[RESERVE_PRIO]) &&
  1707. fifo_full(&ca->free[RESERVE_BTREE]))
  1708. break;
  1709. if (bch_can_invalidate_bucket(ca, b) &&
  1710. !GC_MARK(b)) {
  1711. __bch_invalidate_one_bucket(ca, b);
  1712. if (!fifo_push(&ca->free[RESERVE_PRIO],
  1713. b - ca->buckets))
  1714. fifo_push(&ca->free[RESERVE_BTREE],
  1715. b - ca->buckets);
  1716. }
  1717. }
  1718. mutex_unlock(&c->bucket_lock);
  1719. }
  1720. /* Btree insertion */
  1721. static bool btree_insert_key(struct btree *b, struct bkey *k,
  1722. struct bkey *replace_key)
  1723. {
  1724. unsigned int status;
  1725. BUG_ON(bkey_cmp(k, &b->key) > 0);
  1726. status = bch_btree_insert_key(&b->keys, k, replace_key);
  1727. if (status != BTREE_INSERT_STATUS_NO_INSERT) {
  1728. bch_check_keys(&b->keys, "%u for %s", status,
  1729. replace_key ? "replace" : "insert");
  1730. trace_bcache_btree_insert_key(b, k, replace_key != NULL,
  1731. status);
  1732. return true;
  1733. } else
  1734. return false;
  1735. }
  1736. static size_t insert_u64s_remaining(struct btree *b)
  1737. {
  1738. long ret = bch_btree_keys_u64s_remaining(&b->keys);
  1739. /*
  1740. * Might land in the middle of an existing extent and have to split it
  1741. */
  1742. if (b->keys.ops->is_extents)
  1743. ret -= KEY_MAX_U64S;
  1744. return max(ret, 0L);
  1745. }
  1746. static bool bch_btree_insert_keys(struct btree *b, struct btree_op *op,
  1747. struct keylist *insert_keys,
  1748. struct bkey *replace_key)
  1749. {
  1750. bool ret = false;
  1751. int oldsize = bch_count_data(&b->keys);
  1752. while (!bch_keylist_empty(insert_keys)) {
  1753. struct bkey *k = insert_keys->keys;
  1754. if (bkey_u64s(k) > insert_u64s_remaining(b))
  1755. break;
  1756. if (bkey_cmp(k, &b->key) <= 0) {
  1757. if (!b->level)
  1758. bkey_put(b->c, k);
  1759. ret |= btree_insert_key(b, k, replace_key);
  1760. bch_keylist_pop_front(insert_keys);
  1761. } else if (bkey_cmp(&START_KEY(k), &b->key) < 0) {
  1762. BKEY_PADDED(key) temp;
  1763. bkey_copy(&temp.key, insert_keys->keys);
  1764. bch_cut_back(&b->key, &temp.key);
  1765. bch_cut_front(&b->key, insert_keys->keys);
  1766. ret |= btree_insert_key(b, &temp.key, replace_key);
  1767. break;
  1768. } else {
  1769. break;
  1770. }
  1771. }
  1772. if (!ret)
  1773. op->insert_collision = true;
  1774. BUG_ON(!bch_keylist_empty(insert_keys) && b->level);
  1775. BUG_ON(bch_count_data(&b->keys) < oldsize);
  1776. return ret;
  1777. }
  1778. static int btree_split(struct btree *b, struct btree_op *op,
  1779. struct keylist *insert_keys,
  1780. struct bkey *replace_key)
  1781. {
  1782. bool split;
  1783. struct btree *n1, *n2 = NULL, *n3 = NULL;
  1784. uint64_t start_time = local_clock();
  1785. struct closure cl;
  1786. struct keylist parent_keys;
  1787. closure_init_stack(&cl);
  1788. bch_keylist_init(&parent_keys);
  1789. if (btree_check_reserve(b, op)) {
  1790. if (!b->level)
  1791. return -EINTR;
  1792. else
  1793. WARN(1, "insufficient reserve for split\n");
  1794. }
  1795. n1 = btree_node_alloc_replacement(b, op);
  1796. if (IS_ERR(n1))
  1797. goto err;
  1798. split = set_blocks(btree_bset_first(n1),
  1799. block_bytes(n1->c->cache)) > (btree_blocks(b) * 4) / 5;
  1800. if (split) {
  1801. unsigned int keys = 0;
  1802. trace_bcache_btree_node_split(b, btree_bset_first(n1)->keys);
  1803. n2 = bch_btree_node_alloc(b->c, op, b->level, b->parent);
  1804. if (IS_ERR(n2))
  1805. goto err_free1;
  1806. if (!b->parent) {
  1807. n3 = bch_btree_node_alloc(b->c, op, b->level + 1, NULL);
  1808. if (IS_ERR(n3))
  1809. goto err_free2;
  1810. }
  1811. mutex_lock(&n1->write_lock);
  1812. mutex_lock(&n2->write_lock);
  1813. bch_btree_insert_keys(n1, op, insert_keys, replace_key);
  1814. /*
  1815. * Has to be a linear search because we don't have an auxiliary
  1816. * search tree yet
  1817. */
  1818. while (keys < (btree_bset_first(n1)->keys * 3) / 5)
  1819. keys += bkey_u64s(bset_bkey_idx(btree_bset_first(n1),
  1820. keys));
  1821. bkey_copy_key(&n1->key,
  1822. bset_bkey_idx(btree_bset_first(n1), keys));
  1823. keys += bkey_u64s(bset_bkey_idx(btree_bset_first(n1), keys));
  1824. btree_bset_first(n2)->keys = btree_bset_first(n1)->keys - keys;
  1825. btree_bset_first(n1)->keys = keys;
  1826. memcpy(btree_bset_first(n2)->start,
  1827. bset_bkey_last(btree_bset_first(n1)),
  1828. btree_bset_first(n2)->keys * sizeof(uint64_t));
  1829. bkey_copy_key(&n2->key, &b->key);
  1830. bch_keylist_add(&parent_keys, &n2->key);
  1831. bch_btree_node_write(n2, &cl);
  1832. mutex_unlock(&n2->write_lock);
  1833. rw_unlock(true, n2);
  1834. } else {
  1835. trace_bcache_btree_node_compact(b, btree_bset_first(n1)->keys);
  1836. mutex_lock(&n1->write_lock);
  1837. bch_btree_insert_keys(n1, op, insert_keys, replace_key);
  1838. }
  1839. bch_keylist_add(&parent_keys, &n1->key);
  1840. bch_btree_node_write(n1, &cl);
  1841. mutex_unlock(&n1->write_lock);
  1842. if (n3) {
  1843. /* Depth increases, make a new root */
  1844. mutex_lock(&n3->write_lock);
  1845. bkey_copy_key(&n3->key, &MAX_KEY);
  1846. bch_btree_insert_keys(n3, op, &parent_keys, NULL);
  1847. bch_btree_node_write(n3, &cl);
  1848. mutex_unlock(&n3->write_lock);
  1849. closure_sync(&cl);
  1850. bch_btree_set_root(n3);
  1851. rw_unlock(true, n3);
  1852. } else if (!b->parent) {
  1853. /* Root filled up but didn't need to be split */
  1854. closure_sync(&cl);
  1855. bch_btree_set_root(n1);
  1856. } else {
  1857. /* Split a non root node */
  1858. closure_sync(&cl);
  1859. make_btree_freeing_key(b, parent_keys.top);
  1860. bch_keylist_push(&parent_keys);
  1861. bch_btree_insert_node(b->parent, op, &parent_keys, NULL, NULL);
  1862. BUG_ON(!bch_keylist_empty(&parent_keys));
  1863. }
  1864. btree_node_free(b);
  1865. rw_unlock(true, n1);
  1866. bch_time_stats_update(&b->c->btree_split_time, start_time);
  1867. return 0;
  1868. err_free2:
  1869. bkey_put(b->c, &n2->key);
  1870. btree_node_free(n2);
  1871. rw_unlock(true, n2);
  1872. err_free1:
  1873. bkey_put(b->c, &n1->key);
  1874. btree_node_free(n1);
  1875. rw_unlock(true, n1);
  1876. err:
  1877. WARN(1, "bcache: btree split failed (level %u)", b->level);
  1878. if (n3 == ERR_PTR(-EAGAIN) ||
  1879. n2 == ERR_PTR(-EAGAIN) ||
  1880. n1 == ERR_PTR(-EAGAIN))
  1881. return -EAGAIN;
  1882. return -ENOMEM;
  1883. }
  1884. static int bch_btree_insert_node(struct btree *b, struct btree_op *op,
  1885. struct keylist *insert_keys,
  1886. atomic_t *journal_ref,
  1887. struct bkey *replace_key)
  1888. {
  1889. struct closure cl;
  1890. BUG_ON(b->level && replace_key);
  1891. closure_init_stack(&cl);
  1892. mutex_lock(&b->write_lock);
  1893. if (write_block(b) != btree_bset_last(b) &&
  1894. b->keys.last_set_unwritten)
  1895. bch_btree_init_next(b); /* just wrote a set */
  1896. if (bch_keylist_nkeys(insert_keys) > insert_u64s_remaining(b)) {
  1897. mutex_unlock(&b->write_lock);
  1898. goto split;
  1899. }
  1900. BUG_ON(write_block(b) != btree_bset_last(b));
  1901. if (bch_btree_insert_keys(b, op, insert_keys, replace_key)) {
  1902. if (!b->level)
  1903. bch_btree_leaf_dirty(b, journal_ref);
  1904. else
  1905. bch_btree_node_write(b, &cl);
  1906. }
  1907. mutex_unlock(&b->write_lock);
  1908. /* wait for btree node write if necessary, after unlock */
  1909. closure_sync(&cl);
  1910. return 0;
  1911. split:
  1912. if (current->bio_list) {
  1913. op->lock = b->c->root->level + 1;
  1914. return -EAGAIN;
  1915. } else if (op->lock <= b->c->root->level) {
  1916. op->lock = b->c->root->level + 1;
  1917. return -EINTR;
  1918. } else {
  1919. /* Invalidated all iterators */
  1920. int ret = btree_split(b, op, insert_keys, replace_key);
  1921. if (bch_keylist_empty(insert_keys))
  1922. return 0;
  1923. else if (!ret)
  1924. return -EINTR;
  1925. return ret;
  1926. }
  1927. }
  1928. int bch_btree_insert_check_key(struct btree *b, struct btree_op *op,
  1929. struct bkey *check_key)
  1930. {
  1931. int ret = -EINTR;
  1932. uint64_t btree_ptr = b->key.ptr[0];
  1933. unsigned long seq = b->seq;
  1934. struct keylist insert;
  1935. bool upgrade = op->lock == -1;
  1936. bch_keylist_init(&insert);
  1937. if (upgrade) {
  1938. rw_unlock(false, b);
  1939. rw_lock(true, b, b->level);
  1940. if (b->key.ptr[0] != btree_ptr ||
  1941. b->seq != seq + 1) {
  1942. op->lock = b->level;
  1943. goto out;
  1944. }
  1945. }
  1946. SET_KEY_PTRS(check_key, 1);
  1947. get_random_bytes(&check_key->ptr[0], sizeof(uint64_t));
  1948. SET_PTR_DEV(check_key, 0, PTR_CHECK_DEV);
  1949. bch_keylist_add(&insert, check_key);
  1950. ret = bch_btree_insert_node(b, op, &insert, NULL, NULL);
  1951. BUG_ON(!ret && !bch_keylist_empty(&insert));
  1952. out:
  1953. if (upgrade)
  1954. downgrade_write(&b->lock);
  1955. return ret;
  1956. }
  1957. struct btree_insert_op {
  1958. struct btree_op op;
  1959. struct keylist *keys;
  1960. atomic_t *journal_ref;
  1961. struct bkey *replace_key;
  1962. };
  1963. static int btree_insert_fn(struct btree_op *b_op, struct btree *b)
  1964. {
  1965. struct btree_insert_op *op = container_of(b_op,
  1966. struct btree_insert_op, op);
  1967. int ret = bch_btree_insert_node(b, &op->op, op->keys,
  1968. op->journal_ref, op->replace_key);
  1969. if (ret && !bch_keylist_empty(op->keys))
  1970. return ret;
  1971. else
  1972. return MAP_DONE;
  1973. }
  1974. int bch_btree_insert(struct cache_set *c, struct keylist *keys,
  1975. atomic_t *journal_ref, struct bkey *replace_key)
  1976. {
  1977. struct btree_insert_op op;
  1978. int ret = 0;
  1979. BUG_ON(current->bio_list);
  1980. BUG_ON(bch_keylist_empty(keys));
  1981. bch_btree_op_init(&op.op, 0);
  1982. op.keys = keys;
  1983. op.journal_ref = journal_ref;
  1984. op.replace_key = replace_key;
  1985. while (!ret && !bch_keylist_empty(keys)) {
  1986. op.op.lock = 0;
  1987. ret = bch_btree_map_leaf_nodes(&op.op, c,
  1988. &START_KEY(keys->keys),
  1989. btree_insert_fn);
  1990. }
  1991. if (ret) {
  1992. struct bkey *k;
  1993. pr_err("error %i\n", ret);
  1994. while ((k = bch_keylist_pop(keys)))
  1995. bkey_put(c, k);
  1996. } else if (op.op.insert_collision)
  1997. ret = -ESRCH;
  1998. return ret;
  1999. }
  2000. void bch_btree_set_root(struct btree *b)
  2001. {
  2002. unsigned int i;
  2003. struct closure cl;
  2004. closure_init_stack(&cl);
  2005. trace_bcache_btree_set_root(b);
  2006. BUG_ON(!b->written);
  2007. for (i = 0; i < KEY_PTRS(&b->key); i++)
  2008. BUG_ON(PTR_BUCKET(b->c, &b->key, i)->prio != BTREE_PRIO);
  2009. mutex_lock(&b->c->bucket_lock);
  2010. list_del_init(&b->list);
  2011. mutex_unlock(&b->c->bucket_lock);
  2012. b->c->root = b;
  2013. bch_journal_meta(b->c, &cl);
  2014. closure_sync(&cl);
  2015. }
  2016. /* Map across nodes or keys */
  2017. static int bch_btree_map_nodes_recurse(struct btree *b, struct btree_op *op,
  2018. struct bkey *from,
  2019. btree_map_nodes_fn *fn, int flags)
  2020. {
  2021. int ret = MAP_CONTINUE;
  2022. if (b->level) {
  2023. struct bkey *k;
  2024. struct btree_iter_stack iter;
  2025. bch_btree_iter_stack_init(&b->keys, &iter, from);
  2026. while ((k = bch_btree_iter_next_filter(&iter.iter, &b->keys,
  2027. bch_ptr_bad))) {
  2028. ret = bcache_btree(map_nodes_recurse, k, b,
  2029. op, from, fn, flags);
  2030. from = NULL;
  2031. if (ret != MAP_CONTINUE)
  2032. return ret;
  2033. }
  2034. }
  2035. if (!b->level || flags == MAP_ALL_NODES)
  2036. ret = fn(op, b);
  2037. return ret;
  2038. }
  2039. int __bch_btree_map_nodes(struct btree_op *op, struct cache_set *c,
  2040. struct bkey *from, btree_map_nodes_fn *fn, int flags)
  2041. {
  2042. return bcache_btree_root(map_nodes_recurse, c, op, from, fn, flags);
  2043. }
  2044. int bch_btree_map_keys_recurse(struct btree *b, struct btree_op *op,
  2045. struct bkey *from, btree_map_keys_fn *fn,
  2046. int flags)
  2047. {
  2048. int ret = MAP_CONTINUE;
  2049. struct bkey *k;
  2050. struct btree_iter_stack iter;
  2051. bch_btree_iter_stack_init(&b->keys, &iter, from);
  2052. while ((k = bch_btree_iter_next_filter(&iter.iter, &b->keys,
  2053. bch_ptr_bad))) {
  2054. ret = !b->level
  2055. ? fn(op, b, k)
  2056. : bcache_btree(map_keys_recurse, k,
  2057. b, op, from, fn, flags);
  2058. from = NULL;
  2059. if (ret != MAP_CONTINUE)
  2060. return ret;
  2061. }
  2062. if (!b->level && (flags & MAP_END_KEY))
  2063. ret = fn(op, b, &KEY(KEY_INODE(&b->key),
  2064. KEY_OFFSET(&b->key), 0));
  2065. return ret;
  2066. }
  2067. int bch_btree_map_keys(struct btree_op *op, struct cache_set *c,
  2068. struct bkey *from, btree_map_keys_fn *fn, int flags)
  2069. {
  2070. return bcache_btree_root(map_keys_recurse, c, op, from, fn, flags);
  2071. }
  2072. /* Keybuf code */
  2073. static inline int keybuf_cmp(struct keybuf_key *l, struct keybuf_key *r)
  2074. {
  2075. /* Overlapping keys compare equal */
  2076. if (bkey_cmp(&l->key, &START_KEY(&r->key)) <= 0)
  2077. return -1;
  2078. if (bkey_cmp(&START_KEY(&l->key), &r->key) >= 0)
  2079. return 1;
  2080. return 0;
  2081. }
  2082. static inline int keybuf_nonoverlapping_cmp(struct keybuf_key *l,
  2083. struct keybuf_key *r)
  2084. {
  2085. return clamp_t(int64_t, bkey_cmp(&l->key, &r->key), -1, 1);
  2086. }
  2087. struct refill {
  2088. struct btree_op op;
  2089. unsigned int nr_found;
  2090. struct keybuf *buf;
  2091. struct bkey *end;
  2092. keybuf_pred_fn *pred;
  2093. };
  2094. static int refill_keybuf_fn(struct btree_op *op, struct btree *b,
  2095. struct bkey *k)
  2096. {
  2097. struct refill *refill = container_of(op, struct refill, op);
  2098. struct keybuf *buf = refill->buf;
  2099. int ret = MAP_CONTINUE;
  2100. if (bkey_cmp(k, refill->end) > 0) {
  2101. ret = MAP_DONE;
  2102. goto out;
  2103. }
  2104. if (!KEY_SIZE(k)) /* end key */
  2105. goto out;
  2106. if (refill->pred(buf, k)) {
  2107. struct keybuf_key *w;
  2108. spin_lock(&buf->lock);
  2109. w = array_alloc(&buf->freelist);
  2110. if (!w) {
  2111. spin_unlock(&buf->lock);
  2112. return MAP_DONE;
  2113. }
  2114. w->private = NULL;
  2115. bkey_copy(&w->key, k);
  2116. if (RB_INSERT(&buf->keys, w, node, keybuf_cmp))
  2117. array_free(&buf->freelist, w);
  2118. else
  2119. refill->nr_found++;
  2120. if (array_freelist_empty(&buf->freelist))
  2121. ret = MAP_DONE;
  2122. spin_unlock(&buf->lock);
  2123. }
  2124. out:
  2125. buf->last_scanned = *k;
  2126. return ret;
  2127. }
  2128. void bch_refill_keybuf(struct cache_set *c, struct keybuf *buf,
  2129. struct bkey *end, keybuf_pred_fn *pred)
  2130. {
  2131. struct bkey start = buf->last_scanned;
  2132. struct refill refill;
  2133. cond_resched();
  2134. bch_btree_op_init(&refill.op, -1);
  2135. refill.nr_found = 0;
  2136. refill.buf = buf;
  2137. refill.end = end;
  2138. refill.pred = pred;
  2139. bch_btree_map_keys(&refill.op, c, &buf->last_scanned,
  2140. refill_keybuf_fn, MAP_END_KEY);
  2141. trace_bcache_keyscan(refill.nr_found,
  2142. KEY_INODE(&start), KEY_OFFSET(&start),
  2143. KEY_INODE(&buf->last_scanned),
  2144. KEY_OFFSET(&buf->last_scanned));
  2145. spin_lock(&buf->lock);
  2146. if (!RB_EMPTY_ROOT(&buf->keys)) {
  2147. struct keybuf_key *w;
  2148. w = RB_FIRST(&buf->keys, struct keybuf_key, node);
  2149. buf->start = START_KEY(&w->key);
  2150. w = RB_LAST(&buf->keys, struct keybuf_key, node);
  2151. buf->end = w->key;
  2152. } else {
  2153. buf->start = MAX_KEY;
  2154. buf->end = MAX_KEY;
  2155. }
  2156. spin_unlock(&buf->lock);
  2157. }
  2158. static void __bch_keybuf_del(struct keybuf *buf, struct keybuf_key *w)
  2159. {
  2160. rb_erase(&w->node, &buf->keys);
  2161. array_free(&buf->freelist, w);
  2162. }
  2163. void bch_keybuf_del(struct keybuf *buf, struct keybuf_key *w)
  2164. {
  2165. spin_lock(&buf->lock);
  2166. __bch_keybuf_del(buf, w);
  2167. spin_unlock(&buf->lock);
  2168. }
  2169. bool bch_keybuf_check_overlapping(struct keybuf *buf, struct bkey *start,
  2170. struct bkey *end)
  2171. {
  2172. bool ret = false;
  2173. struct keybuf_key *p, *w, s;
  2174. s.key = *start;
  2175. if (bkey_cmp(end, &buf->start) <= 0 ||
  2176. bkey_cmp(start, &buf->end) >= 0)
  2177. return false;
  2178. spin_lock(&buf->lock);
  2179. w = RB_GREATER(&buf->keys, s, node, keybuf_nonoverlapping_cmp);
  2180. while (w && bkey_cmp(&START_KEY(&w->key), end) < 0) {
  2181. p = w;
  2182. w = RB_NEXT(w, node);
  2183. if (p->private)
  2184. ret = true;
  2185. else
  2186. __bch_keybuf_del(buf, p);
  2187. }
  2188. spin_unlock(&buf->lock);
  2189. return ret;
  2190. }
  2191. struct keybuf_key *bch_keybuf_next(struct keybuf *buf)
  2192. {
  2193. struct keybuf_key *w;
  2194. spin_lock(&buf->lock);
  2195. w = RB_FIRST(&buf->keys, struct keybuf_key, node);
  2196. while (w && w->private)
  2197. w = RB_NEXT(w, node);
  2198. if (w)
  2199. w->private = ERR_PTR(-EINTR);
  2200. spin_unlock(&buf->lock);
  2201. return w;
  2202. }
  2203. struct keybuf_key *bch_keybuf_next_rescan(struct cache_set *c,
  2204. struct keybuf *buf,
  2205. struct bkey *end,
  2206. keybuf_pred_fn *pred)
  2207. {
  2208. struct keybuf_key *ret;
  2209. while (1) {
  2210. ret = bch_keybuf_next(buf);
  2211. if (ret)
  2212. break;
  2213. if (bkey_cmp(&buf->last_scanned, end) >= 0) {
  2214. pr_debug("scan finished\n");
  2215. break;
  2216. }
  2217. bch_refill_keybuf(c, buf, end, pred);
  2218. }
  2219. return ret;
  2220. }
  2221. void bch_keybuf_init(struct keybuf *buf)
  2222. {
  2223. buf->last_scanned = MAX_KEY;
  2224. buf->keys = RB_ROOT;
  2225. spin_lock_init(&buf->lock);
  2226. array_allocator_init(&buf->freelist);
  2227. }
  2228. void bch_btree_exit(void)
  2229. {
  2230. if (btree_io_wq)
  2231. destroy_workqueue(btree_io_wq);
  2232. }
  2233. int __init bch_btree_init(void)
  2234. {
  2235. btree_io_wq = alloc_workqueue("bch_btree_io", WQ_MEM_RECLAIM, 0);
  2236. if (!btree_io_wq)
  2237. return -ENOMEM;
  2238. return 0;
  2239. }