btree.c 63 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * Copyright (C) 2010 Kent Overstreet <[email protected]>
  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 void btree_node_write_unlock(struct closure *cl)
  246. {
  247. struct btree *b = container_of(cl, struct btree, io);
  248. up(&b->io_mutex);
  249. }
  250. static void __btree_node_write_done(struct closure *cl)
  251. {
  252. struct btree *b = container_of(cl, 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 void btree_node_write_done(struct closure *cl)
  262. {
  263. struct btree *b = container_of(cl, struct btree, io);
  264. bio_free_pages(b->bio);
  265. __btree_node_write_done(cl);
  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. static struct btree *mca_bucket_alloc(struct cache_set *c,
  451. struct bkey *k, gfp_t gfp)
  452. {
  453. /*
  454. * kzalloc() is necessary here for initialization,
  455. * see code comments in bch_btree_keys_init().
  456. */
  457. struct btree *b = kzalloc(sizeof(struct btree), gfp);
  458. if (!b)
  459. return NULL;
  460. init_rwsem(&b->lock);
  461. lockdep_set_novalidate_class(&b->lock);
  462. mutex_init(&b->write_lock);
  463. lockdep_set_novalidate_class(&b->write_lock);
  464. INIT_LIST_HEAD(&b->list);
  465. INIT_DELAYED_WORK(&b->work, btree_node_write_work);
  466. b->c = c;
  467. sema_init(&b->io_mutex, 1);
  468. mca_data_alloc(b, k, gfp);
  469. return b;
  470. }
  471. static int mca_reap(struct btree *b, unsigned int min_order, bool flush)
  472. {
  473. struct closure cl;
  474. closure_init_stack(&cl);
  475. lockdep_assert_held(&b->c->bucket_lock);
  476. if (!down_write_trylock(&b->lock))
  477. return -ENOMEM;
  478. BUG_ON(btree_node_dirty(b) && !b->keys.set[0].data);
  479. if (b->keys.page_order < min_order)
  480. goto out_unlock;
  481. if (!flush) {
  482. if (btree_node_dirty(b))
  483. goto out_unlock;
  484. if (down_trylock(&b->io_mutex))
  485. goto out_unlock;
  486. up(&b->io_mutex);
  487. }
  488. retry:
  489. /*
  490. * BTREE_NODE_dirty might be cleared in btree_flush_btree() by
  491. * __bch_btree_node_write(). To avoid an extra flush, acquire
  492. * b->write_lock before checking BTREE_NODE_dirty bit.
  493. */
  494. mutex_lock(&b->write_lock);
  495. /*
  496. * If this btree node is selected in btree_flush_write() by journal
  497. * code, delay and retry until the node is flushed by journal code
  498. * and BTREE_NODE_journal_flush bit cleared by btree_flush_write().
  499. */
  500. if (btree_node_journal_flush(b)) {
  501. pr_debug("bnode %p is flushing by journal, retry\n", b);
  502. mutex_unlock(&b->write_lock);
  503. udelay(1);
  504. goto retry;
  505. }
  506. if (btree_node_dirty(b))
  507. __bch_btree_node_write(b, &cl);
  508. mutex_unlock(&b->write_lock);
  509. closure_sync(&cl);
  510. /* wait for any in flight btree write */
  511. down(&b->io_mutex);
  512. up(&b->io_mutex);
  513. return 0;
  514. out_unlock:
  515. rw_unlock(true, b);
  516. return -ENOMEM;
  517. }
  518. static unsigned long bch_mca_scan(struct shrinker *shrink,
  519. struct shrink_control *sc)
  520. {
  521. struct cache_set *c = container_of(shrink, struct cache_set, shrink);
  522. struct btree *b, *t;
  523. unsigned long i, nr = sc->nr_to_scan;
  524. unsigned long freed = 0;
  525. unsigned int btree_cache_used;
  526. if (c->shrinker_disabled)
  527. return SHRINK_STOP;
  528. if (c->btree_cache_alloc_lock)
  529. return SHRINK_STOP;
  530. /* Return -1 if we can't do anything right now */
  531. if (sc->gfp_mask & __GFP_IO)
  532. mutex_lock(&c->bucket_lock);
  533. else if (!mutex_trylock(&c->bucket_lock))
  534. return -1;
  535. /*
  536. * It's _really_ critical that we don't free too many btree nodes - we
  537. * have to always leave ourselves a reserve. The reserve is how we
  538. * guarantee that allocating memory for a new btree node can always
  539. * succeed, so that inserting keys into the btree can always succeed and
  540. * IO can always make forward progress:
  541. */
  542. nr /= c->btree_pages;
  543. if (nr == 0)
  544. nr = 1;
  545. nr = min_t(unsigned long, nr, mca_can_free(c));
  546. i = 0;
  547. btree_cache_used = c->btree_cache_used;
  548. list_for_each_entry_safe_reverse(b, t, &c->btree_cache_freeable, list) {
  549. if (nr <= 0)
  550. goto out;
  551. if (!mca_reap(b, 0, false)) {
  552. mca_data_free(b);
  553. rw_unlock(true, b);
  554. freed++;
  555. }
  556. nr--;
  557. i++;
  558. }
  559. list_for_each_entry_safe_reverse(b, t, &c->btree_cache, list) {
  560. if (nr <= 0 || i >= btree_cache_used)
  561. goto out;
  562. if (!mca_reap(b, 0, false)) {
  563. mca_bucket_free(b);
  564. mca_data_free(b);
  565. rw_unlock(true, b);
  566. freed++;
  567. }
  568. nr--;
  569. i++;
  570. }
  571. out:
  572. mutex_unlock(&c->bucket_lock);
  573. return freed * c->btree_pages;
  574. }
  575. static unsigned long bch_mca_count(struct shrinker *shrink,
  576. struct shrink_control *sc)
  577. {
  578. struct cache_set *c = container_of(shrink, struct cache_set, shrink);
  579. if (c->shrinker_disabled)
  580. return 0;
  581. if (c->btree_cache_alloc_lock)
  582. return 0;
  583. return mca_can_free(c) * c->btree_pages;
  584. }
  585. void bch_btree_cache_free(struct cache_set *c)
  586. {
  587. struct btree *b;
  588. struct closure cl;
  589. closure_init_stack(&cl);
  590. if (c->shrink.list.next)
  591. unregister_shrinker(&c->shrink);
  592. mutex_lock(&c->bucket_lock);
  593. #ifdef CONFIG_BCACHE_DEBUG
  594. if (c->verify_data)
  595. list_move(&c->verify_data->list, &c->btree_cache);
  596. free_pages((unsigned long) c->verify_ondisk, ilog2(meta_bucket_pages(&c->cache->sb)));
  597. #endif
  598. list_splice(&c->btree_cache_freeable,
  599. &c->btree_cache);
  600. while (!list_empty(&c->btree_cache)) {
  601. b = list_first_entry(&c->btree_cache, struct btree, list);
  602. /*
  603. * This function is called by cache_set_free(), no I/O
  604. * request on cache now, it is unnecessary to acquire
  605. * b->write_lock before clearing BTREE_NODE_dirty anymore.
  606. */
  607. if (btree_node_dirty(b)) {
  608. btree_complete_write(b, btree_current_write(b));
  609. clear_bit(BTREE_NODE_dirty, &b->flags);
  610. }
  611. mca_data_free(b);
  612. }
  613. while (!list_empty(&c->btree_cache_freed)) {
  614. b = list_first_entry(&c->btree_cache_freed,
  615. struct btree, list);
  616. list_del(&b->list);
  617. cancel_delayed_work_sync(&b->work);
  618. kfree(b);
  619. }
  620. mutex_unlock(&c->bucket_lock);
  621. }
  622. int bch_btree_cache_alloc(struct cache_set *c)
  623. {
  624. unsigned int i;
  625. for (i = 0; i < mca_reserve(c); i++)
  626. if (!mca_bucket_alloc(c, &ZERO_KEY, GFP_KERNEL))
  627. return -ENOMEM;
  628. list_splice_init(&c->btree_cache,
  629. &c->btree_cache_freeable);
  630. #ifdef CONFIG_BCACHE_DEBUG
  631. mutex_init(&c->verify_lock);
  632. c->verify_ondisk = (void *)
  633. __get_free_pages(GFP_KERNEL|__GFP_COMP,
  634. ilog2(meta_bucket_pages(&c->cache->sb)));
  635. if (!c->verify_ondisk) {
  636. /*
  637. * Don't worry about the mca_rereserve buckets
  638. * allocated in previous for-loop, they will be
  639. * handled properly in bch_cache_set_unregister().
  640. */
  641. return -ENOMEM;
  642. }
  643. c->verify_data = mca_bucket_alloc(c, &ZERO_KEY, GFP_KERNEL);
  644. if (c->verify_data &&
  645. c->verify_data->keys.set->data)
  646. list_del_init(&c->verify_data->list);
  647. else
  648. c->verify_data = NULL;
  649. #endif
  650. c->shrink.count_objects = bch_mca_count;
  651. c->shrink.scan_objects = bch_mca_scan;
  652. c->shrink.seeks = 4;
  653. c->shrink.batch = c->btree_pages * 2;
  654. if (register_shrinker(&c->shrink, "md-bcache:%pU", c->set_uuid))
  655. pr_warn("bcache: %s: could not register shrinker\n",
  656. __func__);
  657. return 0;
  658. }
  659. /* Btree in memory cache - hash table */
  660. static struct hlist_head *mca_hash(struct cache_set *c, struct bkey *k)
  661. {
  662. return &c->bucket_hash[hash_32(PTR_HASH(c, k), BUCKET_HASH_BITS)];
  663. }
  664. static struct btree *mca_find(struct cache_set *c, struct bkey *k)
  665. {
  666. struct btree *b;
  667. rcu_read_lock();
  668. hlist_for_each_entry_rcu(b, mca_hash(c, k), hash)
  669. if (PTR_HASH(c, &b->key) == PTR_HASH(c, k))
  670. goto out;
  671. b = NULL;
  672. out:
  673. rcu_read_unlock();
  674. return b;
  675. }
  676. static int mca_cannibalize_lock(struct cache_set *c, struct btree_op *op)
  677. {
  678. spin_lock(&c->btree_cannibalize_lock);
  679. if (likely(c->btree_cache_alloc_lock == NULL)) {
  680. c->btree_cache_alloc_lock = current;
  681. } else if (c->btree_cache_alloc_lock != current) {
  682. if (op)
  683. prepare_to_wait(&c->btree_cache_wait, &op->wait,
  684. TASK_UNINTERRUPTIBLE);
  685. spin_unlock(&c->btree_cannibalize_lock);
  686. return -EINTR;
  687. }
  688. spin_unlock(&c->btree_cannibalize_lock);
  689. return 0;
  690. }
  691. static struct btree *mca_cannibalize(struct cache_set *c, struct btree_op *op,
  692. struct bkey *k)
  693. {
  694. struct btree *b;
  695. trace_bcache_btree_cache_cannibalize(c);
  696. if (mca_cannibalize_lock(c, op))
  697. return ERR_PTR(-EINTR);
  698. list_for_each_entry_reverse(b, &c->btree_cache, list)
  699. if (!mca_reap(b, btree_order(k), false))
  700. return b;
  701. list_for_each_entry_reverse(b, &c->btree_cache, list)
  702. if (!mca_reap(b, btree_order(k), true))
  703. return b;
  704. WARN(1, "btree cache cannibalize failed\n");
  705. return ERR_PTR(-ENOMEM);
  706. }
  707. /*
  708. * We can only have one thread cannibalizing other cached btree nodes at a time,
  709. * or we'll deadlock. We use an open coded mutex to ensure that, which a
  710. * cannibalize_bucket() will take. This means every time we unlock the root of
  711. * the btree, we need to release this lock if we have it held.
  712. */
  713. void bch_cannibalize_unlock(struct cache_set *c)
  714. {
  715. spin_lock(&c->btree_cannibalize_lock);
  716. if (c->btree_cache_alloc_lock == current) {
  717. c->btree_cache_alloc_lock = NULL;
  718. wake_up(&c->btree_cache_wait);
  719. }
  720. spin_unlock(&c->btree_cannibalize_lock);
  721. }
  722. static struct btree *mca_alloc(struct cache_set *c, struct btree_op *op,
  723. struct bkey *k, int level)
  724. {
  725. struct btree *b;
  726. BUG_ON(current->bio_list);
  727. lockdep_assert_held(&c->bucket_lock);
  728. if (mca_find(c, k))
  729. return NULL;
  730. /* btree_free() doesn't free memory; it sticks the node on the end of
  731. * the list. Check if there's any freed nodes there:
  732. */
  733. list_for_each_entry(b, &c->btree_cache_freeable, list)
  734. if (!mca_reap(b, btree_order(k), false))
  735. goto out;
  736. /* We never free struct btree itself, just the memory that holds the on
  737. * disk node. Check the freed list before allocating a new one:
  738. */
  739. list_for_each_entry(b, &c->btree_cache_freed, list)
  740. if (!mca_reap(b, 0, false)) {
  741. mca_data_alloc(b, k, __GFP_NOWARN|GFP_NOIO);
  742. if (!b->keys.set[0].data)
  743. goto err;
  744. else
  745. goto out;
  746. }
  747. b = mca_bucket_alloc(c, k, __GFP_NOWARN|GFP_NOIO);
  748. if (!b)
  749. goto err;
  750. BUG_ON(!down_write_trylock(&b->lock));
  751. if (!b->keys.set->data)
  752. goto err;
  753. out:
  754. BUG_ON(b->io_mutex.count != 1);
  755. bkey_copy(&b->key, k);
  756. list_move(&b->list, &c->btree_cache);
  757. hlist_del_init_rcu(&b->hash);
  758. hlist_add_head_rcu(&b->hash, mca_hash(c, k));
  759. lock_set_subclass(&b->lock.dep_map, level + 1, _THIS_IP_);
  760. b->parent = (void *) ~0UL;
  761. b->flags = 0;
  762. b->written = 0;
  763. b->level = level;
  764. if (!b->level)
  765. bch_btree_keys_init(&b->keys, &bch_extent_keys_ops,
  766. &b->c->expensive_debug_checks);
  767. else
  768. bch_btree_keys_init(&b->keys, &bch_btree_keys_ops,
  769. &b->c->expensive_debug_checks);
  770. return b;
  771. err:
  772. if (b)
  773. rw_unlock(true, b);
  774. b = mca_cannibalize(c, op, k);
  775. if (!IS_ERR(b))
  776. goto out;
  777. return b;
  778. }
  779. /*
  780. * bch_btree_node_get - find a btree node in the cache and lock it, reading it
  781. * in from disk if necessary.
  782. *
  783. * If IO is necessary and running under submit_bio_noacct, returns -EAGAIN.
  784. *
  785. * The btree node will have either a read or a write lock held, depending on
  786. * level and op->lock.
  787. */
  788. struct btree *bch_btree_node_get(struct cache_set *c, struct btree_op *op,
  789. struct bkey *k, int level, bool write,
  790. struct btree *parent)
  791. {
  792. int i = 0;
  793. struct btree *b;
  794. BUG_ON(level < 0);
  795. retry:
  796. b = mca_find(c, k);
  797. if (!b) {
  798. if (current->bio_list)
  799. return ERR_PTR(-EAGAIN);
  800. mutex_lock(&c->bucket_lock);
  801. b = mca_alloc(c, op, k, level);
  802. mutex_unlock(&c->bucket_lock);
  803. if (!b)
  804. goto retry;
  805. if (IS_ERR(b))
  806. return b;
  807. bch_btree_node_read(b);
  808. if (!write)
  809. downgrade_write(&b->lock);
  810. } else {
  811. rw_lock(write, b, level);
  812. if (PTR_HASH(c, &b->key) != PTR_HASH(c, k)) {
  813. rw_unlock(write, b);
  814. goto retry;
  815. }
  816. BUG_ON(b->level != level);
  817. }
  818. if (btree_node_io_error(b)) {
  819. rw_unlock(write, b);
  820. return ERR_PTR(-EIO);
  821. }
  822. BUG_ON(!b->written);
  823. b->parent = parent;
  824. for (; i <= b->keys.nsets && b->keys.set[i].size; i++) {
  825. prefetch(b->keys.set[i].tree);
  826. prefetch(b->keys.set[i].data);
  827. }
  828. for (; i <= b->keys.nsets; i++)
  829. prefetch(b->keys.set[i].data);
  830. return b;
  831. }
  832. static void btree_node_prefetch(struct btree *parent, struct bkey *k)
  833. {
  834. struct btree *b;
  835. mutex_lock(&parent->c->bucket_lock);
  836. b = mca_alloc(parent->c, NULL, k, parent->level - 1);
  837. mutex_unlock(&parent->c->bucket_lock);
  838. if (!IS_ERR_OR_NULL(b)) {
  839. b->parent = parent;
  840. bch_btree_node_read(b);
  841. rw_unlock(true, b);
  842. }
  843. }
  844. /* Btree alloc */
  845. static void btree_node_free(struct btree *b)
  846. {
  847. trace_bcache_btree_node_free(b);
  848. BUG_ON(b == b->c->root);
  849. retry:
  850. mutex_lock(&b->write_lock);
  851. /*
  852. * If the btree node is selected and flushing in btree_flush_write(),
  853. * delay and retry until the BTREE_NODE_journal_flush bit cleared,
  854. * then it is safe to free the btree node here. Otherwise this btree
  855. * node will be in race condition.
  856. */
  857. if (btree_node_journal_flush(b)) {
  858. mutex_unlock(&b->write_lock);
  859. pr_debug("bnode %p journal_flush set, retry\n", b);
  860. udelay(1);
  861. goto retry;
  862. }
  863. if (btree_node_dirty(b)) {
  864. btree_complete_write(b, btree_current_write(b));
  865. clear_bit(BTREE_NODE_dirty, &b->flags);
  866. }
  867. mutex_unlock(&b->write_lock);
  868. cancel_delayed_work(&b->work);
  869. mutex_lock(&b->c->bucket_lock);
  870. bch_bucket_free(b->c, &b->key);
  871. mca_bucket_free(b);
  872. mutex_unlock(&b->c->bucket_lock);
  873. }
  874. struct btree *__bch_btree_node_alloc(struct cache_set *c, struct btree_op *op,
  875. int level, bool wait,
  876. struct btree *parent)
  877. {
  878. BKEY_PADDED(key) k;
  879. struct btree *b;
  880. mutex_lock(&c->bucket_lock);
  881. retry:
  882. /* return ERR_PTR(-EAGAIN) when it fails */
  883. b = ERR_PTR(-EAGAIN);
  884. if (__bch_bucket_alloc_set(c, RESERVE_BTREE, &k.key, wait))
  885. goto err;
  886. bkey_put(c, &k.key);
  887. SET_KEY_SIZE(&k.key, c->btree_pages * PAGE_SECTORS);
  888. b = mca_alloc(c, op, &k.key, level);
  889. if (IS_ERR(b))
  890. goto err_free;
  891. if (!b) {
  892. cache_bug(c,
  893. "Tried to allocate bucket that was in btree cache");
  894. goto retry;
  895. }
  896. b->parent = parent;
  897. bch_bset_init_next(&b->keys, b->keys.set->data, bset_magic(&b->c->cache->sb));
  898. mutex_unlock(&c->bucket_lock);
  899. trace_bcache_btree_node_alloc(b);
  900. return b;
  901. err_free:
  902. bch_bucket_free(c, &k.key);
  903. err:
  904. mutex_unlock(&c->bucket_lock);
  905. trace_bcache_btree_node_alloc_fail(c);
  906. return b;
  907. }
  908. static struct btree *bch_btree_node_alloc(struct cache_set *c,
  909. struct btree_op *op, int level,
  910. struct btree *parent)
  911. {
  912. return __bch_btree_node_alloc(c, op, level, op != NULL, parent);
  913. }
  914. static struct btree *btree_node_alloc_replacement(struct btree *b,
  915. struct btree_op *op)
  916. {
  917. struct btree *n = bch_btree_node_alloc(b->c, op, b->level, b->parent);
  918. if (!IS_ERR(n)) {
  919. mutex_lock(&n->write_lock);
  920. bch_btree_sort_into(&b->keys, &n->keys, &b->c->sort);
  921. bkey_copy_key(&n->key, &b->key);
  922. mutex_unlock(&n->write_lock);
  923. }
  924. return n;
  925. }
  926. static void make_btree_freeing_key(struct btree *b, struct bkey *k)
  927. {
  928. unsigned int i;
  929. mutex_lock(&b->c->bucket_lock);
  930. atomic_inc(&b->c->prio_blocked);
  931. bkey_copy(k, &b->key);
  932. bkey_copy_key(k, &ZERO_KEY);
  933. for (i = 0; i < KEY_PTRS(k); i++)
  934. SET_PTR_GEN(k, i,
  935. bch_inc_gen(b->c->cache,
  936. PTR_BUCKET(b->c, &b->key, i)));
  937. mutex_unlock(&b->c->bucket_lock);
  938. }
  939. static int btree_check_reserve(struct btree *b, struct btree_op *op)
  940. {
  941. struct cache_set *c = b->c;
  942. struct cache *ca = c->cache;
  943. unsigned int reserve = (c->root->level - b->level) * 2 + 1;
  944. mutex_lock(&c->bucket_lock);
  945. if (fifo_used(&ca->free[RESERVE_BTREE]) < reserve) {
  946. if (op)
  947. prepare_to_wait(&c->btree_cache_wait, &op->wait,
  948. TASK_UNINTERRUPTIBLE);
  949. mutex_unlock(&c->bucket_lock);
  950. return -EINTR;
  951. }
  952. mutex_unlock(&c->bucket_lock);
  953. return mca_cannibalize_lock(b->c, op);
  954. }
  955. /* Garbage collection */
  956. static uint8_t __bch_btree_mark_key(struct cache_set *c, int level,
  957. struct bkey *k)
  958. {
  959. uint8_t stale = 0;
  960. unsigned int i;
  961. struct bucket *g;
  962. /*
  963. * ptr_invalid() can't return true for the keys that mark btree nodes as
  964. * freed, but since ptr_bad() returns true we'll never actually use them
  965. * for anything and thus we don't want mark their pointers here
  966. */
  967. if (!bkey_cmp(k, &ZERO_KEY))
  968. return stale;
  969. for (i = 0; i < KEY_PTRS(k); i++) {
  970. if (!ptr_available(c, k, i))
  971. continue;
  972. g = PTR_BUCKET(c, k, i);
  973. if (gen_after(g->last_gc, PTR_GEN(k, i)))
  974. g->last_gc = PTR_GEN(k, i);
  975. if (ptr_stale(c, k, i)) {
  976. stale = max(stale, ptr_stale(c, k, i));
  977. continue;
  978. }
  979. cache_bug_on(GC_MARK(g) &&
  980. (GC_MARK(g) == GC_MARK_METADATA) != (level != 0),
  981. c, "inconsistent ptrs: mark = %llu, level = %i",
  982. GC_MARK(g), level);
  983. if (level)
  984. SET_GC_MARK(g, GC_MARK_METADATA);
  985. else if (KEY_DIRTY(k))
  986. SET_GC_MARK(g, GC_MARK_DIRTY);
  987. else if (!GC_MARK(g))
  988. SET_GC_MARK(g, GC_MARK_RECLAIMABLE);
  989. /* guard against overflow */
  990. SET_GC_SECTORS_USED(g, min_t(unsigned int,
  991. GC_SECTORS_USED(g) + KEY_SIZE(k),
  992. MAX_GC_SECTORS_USED));
  993. BUG_ON(!GC_SECTORS_USED(g));
  994. }
  995. return stale;
  996. }
  997. #define btree_mark_key(b, k) __bch_btree_mark_key(b->c, b->level, k)
  998. void bch_initial_mark_key(struct cache_set *c, int level, struct bkey *k)
  999. {
  1000. unsigned int i;
  1001. for (i = 0; i < KEY_PTRS(k); i++)
  1002. if (ptr_available(c, k, i) &&
  1003. !ptr_stale(c, k, i)) {
  1004. struct bucket *b = PTR_BUCKET(c, k, i);
  1005. b->gen = PTR_GEN(k, i);
  1006. if (level && bkey_cmp(k, &ZERO_KEY))
  1007. b->prio = BTREE_PRIO;
  1008. else if (!level && b->prio == BTREE_PRIO)
  1009. b->prio = INITIAL_PRIO;
  1010. }
  1011. __bch_btree_mark_key(c, level, k);
  1012. }
  1013. void bch_update_bucket_in_use(struct cache_set *c, struct gc_stat *stats)
  1014. {
  1015. stats->in_use = (c->nbuckets - c->avail_nbuckets) * 100 / c->nbuckets;
  1016. }
  1017. static bool btree_gc_mark_node(struct btree *b, struct gc_stat *gc)
  1018. {
  1019. uint8_t stale = 0;
  1020. unsigned int keys = 0, good_keys = 0;
  1021. struct bkey *k;
  1022. struct btree_iter iter;
  1023. struct bset_tree *t;
  1024. gc->nodes++;
  1025. for_each_key_filter(&b->keys, k, &iter, bch_ptr_invalid) {
  1026. stale = max(stale, btree_mark_key(b, k));
  1027. keys++;
  1028. if (bch_ptr_bad(&b->keys, k))
  1029. continue;
  1030. gc->key_bytes += bkey_u64s(k);
  1031. gc->nkeys++;
  1032. good_keys++;
  1033. gc->data += KEY_SIZE(k);
  1034. }
  1035. for (t = b->keys.set; t <= &b->keys.set[b->keys.nsets]; t++)
  1036. btree_bug_on(t->size &&
  1037. bset_written(&b->keys, t) &&
  1038. bkey_cmp(&b->key, &t->end) < 0,
  1039. b, "found short btree key in gc");
  1040. if (b->c->gc_always_rewrite)
  1041. return true;
  1042. if (stale > 10)
  1043. return true;
  1044. if ((keys - good_keys) * 2 > keys)
  1045. return true;
  1046. return false;
  1047. }
  1048. #define GC_MERGE_NODES 4U
  1049. struct gc_merge_info {
  1050. struct btree *b;
  1051. unsigned int keys;
  1052. };
  1053. static int bch_btree_insert_node(struct btree *b, struct btree_op *op,
  1054. struct keylist *insert_keys,
  1055. atomic_t *journal_ref,
  1056. struct bkey *replace_key);
  1057. static int btree_gc_coalesce(struct btree *b, struct btree_op *op,
  1058. struct gc_stat *gc, struct gc_merge_info *r)
  1059. {
  1060. unsigned int i, nodes = 0, keys = 0, blocks;
  1061. struct btree *new_nodes[GC_MERGE_NODES];
  1062. struct keylist keylist;
  1063. struct closure cl;
  1064. struct bkey *k;
  1065. bch_keylist_init(&keylist);
  1066. if (btree_check_reserve(b, NULL))
  1067. return 0;
  1068. memset(new_nodes, 0, sizeof(new_nodes));
  1069. closure_init_stack(&cl);
  1070. while (nodes < GC_MERGE_NODES && !IS_ERR_OR_NULL(r[nodes].b))
  1071. keys += r[nodes++].keys;
  1072. blocks = btree_default_blocks(b->c) * 2 / 3;
  1073. if (nodes < 2 ||
  1074. __set_blocks(b->keys.set[0].data, keys,
  1075. block_bytes(b->c->cache)) > blocks * (nodes - 1))
  1076. return 0;
  1077. for (i = 0; i < nodes; i++) {
  1078. new_nodes[i] = btree_node_alloc_replacement(r[i].b, NULL);
  1079. if (IS_ERR(new_nodes[i]))
  1080. goto out_nocoalesce;
  1081. }
  1082. /*
  1083. * We have to check the reserve here, after we've allocated our new
  1084. * nodes, to make sure the insert below will succeed - we also check
  1085. * before as an optimization to potentially avoid a bunch of expensive
  1086. * allocs/sorts
  1087. */
  1088. if (btree_check_reserve(b, NULL))
  1089. goto out_nocoalesce;
  1090. for (i = 0; i < nodes; i++)
  1091. mutex_lock(&new_nodes[i]->write_lock);
  1092. for (i = nodes - 1; i > 0; --i) {
  1093. struct bset *n1 = btree_bset_first(new_nodes[i]);
  1094. struct bset *n2 = btree_bset_first(new_nodes[i - 1]);
  1095. struct bkey *k, *last = NULL;
  1096. keys = 0;
  1097. if (i > 1) {
  1098. for (k = n2->start;
  1099. k < bset_bkey_last(n2);
  1100. k = bkey_next(k)) {
  1101. if (__set_blocks(n1, n1->keys + keys +
  1102. bkey_u64s(k),
  1103. block_bytes(b->c->cache)) > blocks)
  1104. break;
  1105. last = k;
  1106. keys += bkey_u64s(k);
  1107. }
  1108. } else {
  1109. /*
  1110. * Last node we're not getting rid of - we're getting
  1111. * rid of the node at r[0]. Have to try and fit all of
  1112. * the remaining keys into this node; we can't ensure
  1113. * they will always fit due to rounding and variable
  1114. * length keys (shouldn't be possible in practice,
  1115. * though)
  1116. */
  1117. if (__set_blocks(n1, n1->keys + n2->keys,
  1118. block_bytes(b->c->cache)) >
  1119. btree_blocks(new_nodes[i]))
  1120. goto out_unlock_nocoalesce;
  1121. keys = n2->keys;
  1122. /* Take the key of the node we're getting rid of */
  1123. last = &r->b->key;
  1124. }
  1125. BUG_ON(__set_blocks(n1, n1->keys + keys, block_bytes(b->c->cache)) >
  1126. btree_blocks(new_nodes[i]));
  1127. if (last)
  1128. bkey_copy_key(&new_nodes[i]->key, last);
  1129. memcpy(bset_bkey_last(n1),
  1130. n2->start,
  1131. (void *) bset_bkey_idx(n2, keys) - (void *) n2->start);
  1132. n1->keys += keys;
  1133. r[i].keys = n1->keys;
  1134. memmove(n2->start,
  1135. bset_bkey_idx(n2, keys),
  1136. (void *) bset_bkey_last(n2) -
  1137. (void *) bset_bkey_idx(n2, keys));
  1138. n2->keys -= keys;
  1139. if (__bch_keylist_realloc(&keylist,
  1140. bkey_u64s(&new_nodes[i]->key)))
  1141. goto out_unlock_nocoalesce;
  1142. bch_btree_node_write(new_nodes[i], &cl);
  1143. bch_keylist_add(&keylist, &new_nodes[i]->key);
  1144. }
  1145. for (i = 0; i < nodes; i++)
  1146. mutex_unlock(&new_nodes[i]->write_lock);
  1147. closure_sync(&cl);
  1148. /* We emptied out this node */
  1149. BUG_ON(btree_bset_first(new_nodes[0])->keys);
  1150. btree_node_free(new_nodes[0]);
  1151. rw_unlock(true, new_nodes[0]);
  1152. new_nodes[0] = NULL;
  1153. for (i = 0; i < nodes; i++) {
  1154. if (__bch_keylist_realloc(&keylist, bkey_u64s(&r[i].b->key)))
  1155. goto out_nocoalesce;
  1156. make_btree_freeing_key(r[i].b, keylist.top);
  1157. bch_keylist_push(&keylist);
  1158. }
  1159. bch_btree_insert_node(b, op, &keylist, NULL, NULL);
  1160. BUG_ON(!bch_keylist_empty(&keylist));
  1161. for (i = 0; i < nodes; i++) {
  1162. btree_node_free(r[i].b);
  1163. rw_unlock(true, r[i].b);
  1164. r[i].b = new_nodes[i];
  1165. }
  1166. memmove(r, r + 1, sizeof(r[0]) * (nodes - 1));
  1167. r[nodes - 1].b = ERR_PTR(-EINTR);
  1168. trace_bcache_btree_gc_coalesce(nodes);
  1169. gc->nodes--;
  1170. bch_keylist_free(&keylist);
  1171. /* Invalidated our iterator */
  1172. return -EINTR;
  1173. out_unlock_nocoalesce:
  1174. for (i = 0; i < nodes; i++)
  1175. mutex_unlock(&new_nodes[i]->write_lock);
  1176. out_nocoalesce:
  1177. closure_sync(&cl);
  1178. while ((k = bch_keylist_pop(&keylist)))
  1179. if (!bkey_cmp(k, &ZERO_KEY))
  1180. atomic_dec(&b->c->prio_blocked);
  1181. bch_keylist_free(&keylist);
  1182. for (i = 0; i < nodes; i++)
  1183. if (!IS_ERR_OR_NULL(new_nodes[i])) {
  1184. btree_node_free(new_nodes[i]);
  1185. rw_unlock(true, new_nodes[i]);
  1186. }
  1187. return 0;
  1188. }
  1189. static int btree_gc_rewrite_node(struct btree *b, struct btree_op *op,
  1190. struct btree *replace)
  1191. {
  1192. struct keylist keys;
  1193. struct btree *n;
  1194. if (btree_check_reserve(b, NULL))
  1195. return 0;
  1196. n = btree_node_alloc_replacement(replace, NULL);
  1197. if (IS_ERR(n))
  1198. return 0;
  1199. /* recheck reserve after allocating replacement node */
  1200. if (btree_check_reserve(b, NULL)) {
  1201. btree_node_free(n);
  1202. rw_unlock(true, n);
  1203. return 0;
  1204. }
  1205. bch_btree_node_write_sync(n);
  1206. bch_keylist_init(&keys);
  1207. bch_keylist_add(&keys, &n->key);
  1208. make_btree_freeing_key(replace, keys.top);
  1209. bch_keylist_push(&keys);
  1210. bch_btree_insert_node(b, op, &keys, NULL, NULL);
  1211. BUG_ON(!bch_keylist_empty(&keys));
  1212. btree_node_free(replace);
  1213. rw_unlock(true, n);
  1214. /* Invalidated our iterator */
  1215. return -EINTR;
  1216. }
  1217. static unsigned int btree_gc_count_keys(struct btree *b)
  1218. {
  1219. struct bkey *k;
  1220. struct btree_iter iter;
  1221. unsigned int ret = 0;
  1222. for_each_key_filter(&b->keys, k, &iter, bch_ptr_bad)
  1223. ret += bkey_u64s(k);
  1224. return ret;
  1225. }
  1226. static size_t btree_gc_min_nodes(struct cache_set *c)
  1227. {
  1228. size_t min_nodes;
  1229. /*
  1230. * Since incremental GC would stop 100ms when front
  1231. * side I/O comes, so when there are many btree nodes,
  1232. * if GC only processes constant (100) nodes each time,
  1233. * GC would last a long time, and the front side I/Os
  1234. * would run out of the buckets (since no new bucket
  1235. * can be allocated during GC), and be blocked again.
  1236. * So GC should not process constant nodes, but varied
  1237. * nodes according to the number of btree nodes, which
  1238. * realized by dividing GC into constant(100) times,
  1239. * so when there are many btree nodes, GC can process
  1240. * more nodes each time, otherwise, GC will process less
  1241. * nodes each time (but no less than MIN_GC_NODES)
  1242. */
  1243. min_nodes = c->gc_stats.nodes / MAX_GC_TIMES;
  1244. if (min_nodes < MIN_GC_NODES)
  1245. min_nodes = MIN_GC_NODES;
  1246. return min_nodes;
  1247. }
  1248. static int btree_gc_recurse(struct btree *b, struct btree_op *op,
  1249. struct closure *writes, struct gc_stat *gc)
  1250. {
  1251. int ret = 0;
  1252. bool should_rewrite;
  1253. struct bkey *k;
  1254. struct btree_iter iter;
  1255. struct gc_merge_info r[GC_MERGE_NODES];
  1256. struct gc_merge_info *i, *last = r + ARRAY_SIZE(r) - 1;
  1257. bch_btree_iter_init(&b->keys, &iter, &b->c->gc_done);
  1258. for (i = r; i < r + ARRAY_SIZE(r); i++)
  1259. i->b = ERR_PTR(-EINTR);
  1260. while (1) {
  1261. k = bch_btree_iter_next_filter(&iter, &b->keys, bch_ptr_bad);
  1262. if (k) {
  1263. r->b = bch_btree_node_get(b->c, op, k, b->level - 1,
  1264. true, b);
  1265. if (IS_ERR(r->b)) {
  1266. ret = PTR_ERR(r->b);
  1267. break;
  1268. }
  1269. r->keys = btree_gc_count_keys(r->b);
  1270. ret = btree_gc_coalesce(b, op, gc, r);
  1271. if (ret)
  1272. break;
  1273. }
  1274. if (!last->b)
  1275. break;
  1276. if (!IS_ERR(last->b)) {
  1277. should_rewrite = btree_gc_mark_node(last->b, gc);
  1278. if (should_rewrite) {
  1279. ret = btree_gc_rewrite_node(b, op, last->b);
  1280. if (ret)
  1281. break;
  1282. }
  1283. if (last->b->level) {
  1284. ret = btree_gc_recurse(last->b, op, writes, gc);
  1285. if (ret)
  1286. break;
  1287. }
  1288. bkey_copy_key(&b->c->gc_done, &last->b->key);
  1289. /*
  1290. * Must flush leaf nodes before gc ends, since replace
  1291. * operations aren't journalled
  1292. */
  1293. mutex_lock(&last->b->write_lock);
  1294. if (btree_node_dirty(last->b))
  1295. bch_btree_node_write(last->b, writes);
  1296. mutex_unlock(&last->b->write_lock);
  1297. rw_unlock(true, last->b);
  1298. }
  1299. memmove(r + 1, r, sizeof(r[0]) * (GC_MERGE_NODES - 1));
  1300. r->b = NULL;
  1301. if (atomic_read(&b->c->search_inflight) &&
  1302. gc->nodes >= gc->nodes_pre + btree_gc_min_nodes(b->c)) {
  1303. gc->nodes_pre = gc->nodes;
  1304. ret = -EAGAIN;
  1305. break;
  1306. }
  1307. if (need_resched()) {
  1308. ret = -EAGAIN;
  1309. break;
  1310. }
  1311. }
  1312. for (i = r; i < r + ARRAY_SIZE(r); i++)
  1313. if (!IS_ERR_OR_NULL(i->b)) {
  1314. mutex_lock(&i->b->write_lock);
  1315. if (btree_node_dirty(i->b))
  1316. bch_btree_node_write(i->b, writes);
  1317. mutex_unlock(&i->b->write_lock);
  1318. rw_unlock(true, i->b);
  1319. }
  1320. return ret;
  1321. }
  1322. static int bch_btree_gc_root(struct btree *b, struct btree_op *op,
  1323. struct closure *writes, struct gc_stat *gc)
  1324. {
  1325. struct btree *n = NULL;
  1326. int ret = 0;
  1327. bool should_rewrite;
  1328. should_rewrite = btree_gc_mark_node(b, gc);
  1329. if (should_rewrite) {
  1330. n = btree_node_alloc_replacement(b, NULL);
  1331. if (!IS_ERR(n)) {
  1332. bch_btree_node_write_sync(n);
  1333. bch_btree_set_root(n);
  1334. btree_node_free(b);
  1335. rw_unlock(true, n);
  1336. return -EINTR;
  1337. }
  1338. }
  1339. __bch_btree_mark_key(b->c, b->level + 1, &b->key);
  1340. if (b->level) {
  1341. ret = btree_gc_recurse(b, op, writes, gc);
  1342. if (ret)
  1343. return ret;
  1344. }
  1345. bkey_copy_key(&b->c->gc_done, &b->key);
  1346. return ret;
  1347. }
  1348. static void btree_gc_start(struct cache_set *c)
  1349. {
  1350. struct cache *ca;
  1351. struct bucket *b;
  1352. if (!c->gc_mark_valid)
  1353. return;
  1354. mutex_lock(&c->bucket_lock);
  1355. c->gc_mark_valid = 0;
  1356. c->gc_done = ZERO_KEY;
  1357. ca = c->cache;
  1358. for_each_bucket(b, ca) {
  1359. b->last_gc = b->gen;
  1360. if (!atomic_read(&b->pin)) {
  1361. SET_GC_MARK(b, 0);
  1362. SET_GC_SECTORS_USED(b, 0);
  1363. }
  1364. }
  1365. mutex_unlock(&c->bucket_lock);
  1366. }
  1367. static void bch_btree_gc_finish(struct cache_set *c)
  1368. {
  1369. struct bucket *b;
  1370. struct cache *ca;
  1371. unsigned int i, j;
  1372. uint64_t *k;
  1373. mutex_lock(&c->bucket_lock);
  1374. set_gc_sectors(c);
  1375. c->gc_mark_valid = 1;
  1376. c->need_gc = 0;
  1377. for (i = 0; i < KEY_PTRS(&c->uuid_bucket); i++)
  1378. SET_GC_MARK(PTR_BUCKET(c, &c->uuid_bucket, i),
  1379. GC_MARK_METADATA);
  1380. /* don't reclaim buckets to which writeback keys point */
  1381. rcu_read_lock();
  1382. for (i = 0; i < c->devices_max_used; i++) {
  1383. struct bcache_device *d = c->devices[i];
  1384. struct cached_dev *dc;
  1385. struct keybuf_key *w, *n;
  1386. if (!d || UUID_FLASH_ONLY(&c->uuids[i]))
  1387. continue;
  1388. dc = container_of(d, struct cached_dev, disk);
  1389. spin_lock(&dc->writeback_keys.lock);
  1390. rbtree_postorder_for_each_entry_safe(w, n,
  1391. &dc->writeback_keys.keys, node)
  1392. for (j = 0; j < KEY_PTRS(&w->key); j++)
  1393. SET_GC_MARK(PTR_BUCKET(c, &w->key, j),
  1394. GC_MARK_DIRTY);
  1395. spin_unlock(&dc->writeback_keys.lock);
  1396. }
  1397. rcu_read_unlock();
  1398. c->avail_nbuckets = 0;
  1399. ca = c->cache;
  1400. ca->invalidate_needs_gc = 0;
  1401. for (k = ca->sb.d; k < ca->sb.d + ca->sb.keys; k++)
  1402. SET_GC_MARK(ca->buckets + *k, GC_MARK_METADATA);
  1403. for (k = ca->prio_buckets;
  1404. k < ca->prio_buckets + prio_buckets(ca) * 2; k++)
  1405. SET_GC_MARK(ca->buckets + *k, GC_MARK_METADATA);
  1406. for_each_bucket(b, ca) {
  1407. c->need_gc = max(c->need_gc, bucket_gc_gen(b));
  1408. if (atomic_read(&b->pin))
  1409. continue;
  1410. BUG_ON(!GC_MARK(b) && GC_SECTORS_USED(b));
  1411. if (!GC_MARK(b) || GC_MARK(b) == GC_MARK_RECLAIMABLE)
  1412. c->avail_nbuckets++;
  1413. }
  1414. mutex_unlock(&c->bucket_lock);
  1415. }
  1416. static void bch_btree_gc(struct cache_set *c)
  1417. {
  1418. int ret;
  1419. struct gc_stat stats;
  1420. struct closure writes;
  1421. struct btree_op op;
  1422. uint64_t start_time = local_clock();
  1423. trace_bcache_gc_start(c);
  1424. memset(&stats, 0, sizeof(struct gc_stat));
  1425. closure_init_stack(&writes);
  1426. bch_btree_op_init(&op, SHRT_MAX);
  1427. btree_gc_start(c);
  1428. /* if CACHE_SET_IO_DISABLE set, gc thread should stop too */
  1429. do {
  1430. ret = bcache_btree_root(gc_root, c, &op, &writes, &stats);
  1431. closure_sync(&writes);
  1432. cond_resched();
  1433. if (ret == -EAGAIN)
  1434. schedule_timeout_interruptible(msecs_to_jiffies
  1435. (GC_SLEEP_MS));
  1436. else if (ret)
  1437. pr_warn("gc failed!\n");
  1438. } while (ret && !test_bit(CACHE_SET_IO_DISABLE, &c->flags));
  1439. bch_btree_gc_finish(c);
  1440. wake_up_allocators(c);
  1441. bch_time_stats_update(&c->btree_gc_time, start_time);
  1442. stats.key_bytes *= sizeof(uint64_t);
  1443. stats.data <<= 9;
  1444. bch_update_bucket_in_use(c, &stats);
  1445. memcpy(&c->gc_stats, &stats, sizeof(struct gc_stat));
  1446. trace_bcache_gc_end(c);
  1447. bch_moving_gc(c);
  1448. }
  1449. static bool gc_should_run(struct cache_set *c)
  1450. {
  1451. struct cache *ca = c->cache;
  1452. if (ca->invalidate_needs_gc)
  1453. return true;
  1454. if (atomic_read(&c->sectors_to_gc) < 0)
  1455. return true;
  1456. return false;
  1457. }
  1458. static int bch_gc_thread(void *arg)
  1459. {
  1460. struct cache_set *c = arg;
  1461. while (1) {
  1462. wait_event_interruptible(c->gc_wait,
  1463. kthread_should_stop() ||
  1464. test_bit(CACHE_SET_IO_DISABLE, &c->flags) ||
  1465. gc_should_run(c));
  1466. if (kthread_should_stop() ||
  1467. test_bit(CACHE_SET_IO_DISABLE, &c->flags))
  1468. break;
  1469. set_gc_sectors(c);
  1470. bch_btree_gc(c);
  1471. }
  1472. wait_for_kthread_stop();
  1473. return 0;
  1474. }
  1475. int bch_gc_thread_start(struct cache_set *c)
  1476. {
  1477. c->gc_thread = kthread_run(bch_gc_thread, c, "bcache_gc");
  1478. return PTR_ERR_OR_ZERO(c->gc_thread);
  1479. }
  1480. /* Initial partial gc */
  1481. static int bch_btree_check_recurse(struct btree *b, struct btree_op *op)
  1482. {
  1483. int ret = 0;
  1484. struct bkey *k, *p = NULL;
  1485. struct btree_iter iter;
  1486. for_each_key_filter(&b->keys, k, &iter, bch_ptr_invalid)
  1487. bch_initial_mark_key(b->c, b->level, k);
  1488. bch_initial_mark_key(b->c, b->level + 1, &b->key);
  1489. if (b->level) {
  1490. bch_btree_iter_init(&b->keys, &iter, NULL);
  1491. do {
  1492. k = bch_btree_iter_next_filter(&iter, &b->keys,
  1493. bch_ptr_bad);
  1494. if (k) {
  1495. btree_node_prefetch(b, k);
  1496. /*
  1497. * initiallize c->gc_stats.nodes
  1498. * for incremental GC
  1499. */
  1500. b->c->gc_stats.nodes++;
  1501. }
  1502. if (p)
  1503. ret = bcache_btree(check_recurse, p, b, op);
  1504. p = k;
  1505. } while (p && !ret);
  1506. }
  1507. return ret;
  1508. }
  1509. static int bch_btree_check_thread(void *arg)
  1510. {
  1511. int ret;
  1512. struct btree_check_info *info = arg;
  1513. struct btree_check_state *check_state = info->state;
  1514. struct cache_set *c = check_state->c;
  1515. struct btree_iter iter;
  1516. struct bkey *k, *p;
  1517. int cur_idx, prev_idx, skip_nr;
  1518. k = p = NULL;
  1519. cur_idx = prev_idx = 0;
  1520. ret = 0;
  1521. /* root node keys are checked before thread created */
  1522. bch_btree_iter_init(&c->root->keys, &iter, NULL);
  1523. k = bch_btree_iter_next_filter(&iter, &c->root->keys, bch_ptr_bad);
  1524. BUG_ON(!k);
  1525. p = k;
  1526. while (k) {
  1527. /*
  1528. * Fetch a root node key index, skip the keys which
  1529. * should be fetched by other threads, then check the
  1530. * sub-tree indexed by the fetched key.
  1531. */
  1532. spin_lock(&check_state->idx_lock);
  1533. cur_idx = check_state->key_idx;
  1534. check_state->key_idx++;
  1535. spin_unlock(&check_state->idx_lock);
  1536. skip_nr = cur_idx - prev_idx;
  1537. while (skip_nr) {
  1538. k = bch_btree_iter_next_filter(&iter,
  1539. &c->root->keys,
  1540. bch_ptr_bad);
  1541. if (k)
  1542. p = k;
  1543. else {
  1544. /*
  1545. * No more keys to check in root node,
  1546. * current checking threads are enough,
  1547. * stop creating more.
  1548. */
  1549. atomic_set(&check_state->enough, 1);
  1550. /* Update check_state->enough earlier */
  1551. smp_mb__after_atomic();
  1552. goto out;
  1553. }
  1554. skip_nr--;
  1555. cond_resched();
  1556. }
  1557. if (p) {
  1558. struct btree_op op;
  1559. btree_node_prefetch(c->root, p);
  1560. c->gc_stats.nodes++;
  1561. bch_btree_op_init(&op, 0);
  1562. ret = bcache_btree(check_recurse, p, c->root, &op);
  1563. /*
  1564. * The op may be added to cache_set's btree_cache_wait
  1565. * in mca_cannibalize(), must ensure it is removed from
  1566. * the list and release btree_cache_alloc_lock before
  1567. * free op memory.
  1568. * Otherwise, the btree_cache_wait will be damaged.
  1569. */
  1570. bch_cannibalize_unlock(c);
  1571. finish_wait(&c->btree_cache_wait, &(&op)->wait);
  1572. if (ret)
  1573. goto out;
  1574. }
  1575. p = NULL;
  1576. prev_idx = cur_idx;
  1577. cond_resched();
  1578. }
  1579. out:
  1580. info->result = ret;
  1581. /* update check_state->started among all CPUs */
  1582. smp_mb__before_atomic();
  1583. if (atomic_dec_and_test(&check_state->started))
  1584. wake_up(&check_state->wait);
  1585. return ret;
  1586. }
  1587. static int bch_btree_chkthread_nr(void)
  1588. {
  1589. int n = num_online_cpus()/2;
  1590. if (n == 0)
  1591. n = 1;
  1592. else if (n > BCH_BTR_CHKTHREAD_MAX)
  1593. n = BCH_BTR_CHKTHREAD_MAX;
  1594. return n;
  1595. }
  1596. int bch_btree_check(struct cache_set *c)
  1597. {
  1598. int ret = 0;
  1599. int i;
  1600. struct bkey *k = NULL;
  1601. struct btree_iter iter;
  1602. struct btree_check_state check_state;
  1603. /* check and mark root node keys */
  1604. for_each_key_filter(&c->root->keys, k, &iter, bch_ptr_invalid)
  1605. bch_initial_mark_key(c, c->root->level, k);
  1606. bch_initial_mark_key(c, c->root->level + 1, &c->root->key);
  1607. if (c->root->level == 0)
  1608. return 0;
  1609. memset(&check_state, 0, sizeof(struct btree_check_state));
  1610. check_state.c = c;
  1611. check_state.total_threads = bch_btree_chkthread_nr();
  1612. check_state.key_idx = 0;
  1613. spin_lock_init(&check_state.idx_lock);
  1614. atomic_set(&check_state.started, 0);
  1615. atomic_set(&check_state.enough, 0);
  1616. init_waitqueue_head(&check_state.wait);
  1617. rw_lock(0, c->root, c->root->level);
  1618. /*
  1619. * Run multiple threads to check btree nodes in parallel,
  1620. * if check_state.enough is non-zero, it means current
  1621. * running check threads are enough, unncessary to create
  1622. * more.
  1623. */
  1624. for (i = 0; i < check_state.total_threads; i++) {
  1625. /* fetch latest check_state.enough earlier */
  1626. smp_mb__before_atomic();
  1627. if (atomic_read(&check_state.enough))
  1628. break;
  1629. check_state.infos[i].result = 0;
  1630. check_state.infos[i].state = &check_state;
  1631. check_state.infos[i].thread =
  1632. kthread_run(bch_btree_check_thread,
  1633. &check_state.infos[i],
  1634. "bch_btrchk[%d]", i);
  1635. if (IS_ERR(check_state.infos[i].thread)) {
  1636. pr_err("fails to run thread bch_btrchk[%d]\n", i);
  1637. for (--i; i >= 0; i--)
  1638. kthread_stop(check_state.infos[i].thread);
  1639. ret = -ENOMEM;
  1640. goto out;
  1641. }
  1642. atomic_inc(&check_state.started);
  1643. }
  1644. /*
  1645. * Must wait for all threads to stop.
  1646. */
  1647. wait_event(check_state.wait, atomic_read(&check_state.started) == 0);
  1648. for (i = 0; i < check_state.total_threads; i++) {
  1649. if (check_state.infos[i].result) {
  1650. ret = check_state.infos[i].result;
  1651. goto out;
  1652. }
  1653. }
  1654. out:
  1655. rw_unlock(0, c->root);
  1656. return ret;
  1657. }
  1658. void bch_initial_gc_finish(struct cache_set *c)
  1659. {
  1660. struct cache *ca = c->cache;
  1661. struct bucket *b;
  1662. bch_btree_gc_finish(c);
  1663. mutex_lock(&c->bucket_lock);
  1664. /*
  1665. * We need to put some unused buckets directly on the prio freelist in
  1666. * order to get the allocator thread started - it needs freed buckets in
  1667. * order to rewrite the prios and gens, and it needs to rewrite prios
  1668. * and gens in order to free buckets.
  1669. *
  1670. * This is only safe for buckets that have no live data in them, which
  1671. * there should always be some of.
  1672. */
  1673. for_each_bucket(b, ca) {
  1674. if (fifo_full(&ca->free[RESERVE_PRIO]) &&
  1675. fifo_full(&ca->free[RESERVE_BTREE]))
  1676. break;
  1677. if (bch_can_invalidate_bucket(ca, b) &&
  1678. !GC_MARK(b)) {
  1679. __bch_invalidate_one_bucket(ca, b);
  1680. if (!fifo_push(&ca->free[RESERVE_PRIO],
  1681. b - ca->buckets))
  1682. fifo_push(&ca->free[RESERVE_BTREE],
  1683. b - ca->buckets);
  1684. }
  1685. }
  1686. mutex_unlock(&c->bucket_lock);
  1687. }
  1688. /* Btree insertion */
  1689. static bool btree_insert_key(struct btree *b, struct bkey *k,
  1690. struct bkey *replace_key)
  1691. {
  1692. unsigned int status;
  1693. BUG_ON(bkey_cmp(k, &b->key) > 0);
  1694. status = bch_btree_insert_key(&b->keys, k, replace_key);
  1695. if (status != BTREE_INSERT_STATUS_NO_INSERT) {
  1696. bch_check_keys(&b->keys, "%u for %s", status,
  1697. replace_key ? "replace" : "insert");
  1698. trace_bcache_btree_insert_key(b, k, replace_key != NULL,
  1699. status);
  1700. return true;
  1701. } else
  1702. return false;
  1703. }
  1704. static size_t insert_u64s_remaining(struct btree *b)
  1705. {
  1706. long ret = bch_btree_keys_u64s_remaining(&b->keys);
  1707. /*
  1708. * Might land in the middle of an existing extent and have to split it
  1709. */
  1710. if (b->keys.ops->is_extents)
  1711. ret -= KEY_MAX_U64S;
  1712. return max(ret, 0L);
  1713. }
  1714. static bool bch_btree_insert_keys(struct btree *b, struct btree_op *op,
  1715. struct keylist *insert_keys,
  1716. struct bkey *replace_key)
  1717. {
  1718. bool ret = false;
  1719. int oldsize = bch_count_data(&b->keys);
  1720. while (!bch_keylist_empty(insert_keys)) {
  1721. struct bkey *k = insert_keys->keys;
  1722. if (bkey_u64s(k) > insert_u64s_remaining(b))
  1723. break;
  1724. if (bkey_cmp(k, &b->key) <= 0) {
  1725. if (!b->level)
  1726. bkey_put(b->c, k);
  1727. ret |= btree_insert_key(b, k, replace_key);
  1728. bch_keylist_pop_front(insert_keys);
  1729. } else if (bkey_cmp(&START_KEY(k), &b->key) < 0) {
  1730. BKEY_PADDED(key) temp;
  1731. bkey_copy(&temp.key, insert_keys->keys);
  1732. bch_cut_back(&b->key, &temp.key);
  1733. bch_cut_front(&b->key, insert_keys->keys);
  1734. ret |= btree_insert_key(b, &temp.key, replace_key);
  1735. break;
  1736. } else {
  1737. break;
  1738. }
  1739. }
  1740. if (!ret)
  1741. op->insert_collision = true;
  1742. BUG_ON(!bch_keylist_empty(insert_keys) && b->level);
  1743. BUG_ON(bch_count_data(&b->keys) < oldsize);
  1744. return ret;
  1745. }
  1746. static int btree_split(struct btree *b, struct btree_op *op,
  1747. struct keylist *insert_keys,
  1748. struct bkey *replace_key)
  1749. {
  1750. bool split;
  1751. struct btree *n1, *n2 = NULL, *n3 = NULL;
  1752. uint64_t start_time = local_clock();
  1753. struct closure cl;
  1754. struct keylist parent_keys;
  1755. closure_init_stack(&cl);
  1756. bch_keylist_init(&parent_keys);
  1757. if (btree_check_reserve(b, op)) {
  1758. if (!b->level)
  1759. return -EINTR;
  1760. else
  1761. WARN(1, "insufficient reserve for split\n");
  1762. }
  1763. n1 = btree_node_alloc_replacement(b, op);
  1764. if (IS_ERR(n1))
  1765. goto err;
  1766. split = set_blocks(btree_bset_first(n1),
  1767. block_bytes(n1->c->cache)) > (btree_blocks(b) * 4) / 5;
  1768. if (split) {
  1769. unsigned int keys = 0;
  1770. trace_bcache_btree_node_split(b, btree_bset_first(n1)->keys);
  1771. n2 = bch_btree_node_alloc(b->c, op, b->level, b->parent);
  1772. if (IS_ERR(n2))
  1773. goto err_free1;
  1774. if (!b->parent) {
  1775. n3 = bch_btree_node_alloc(b->c, op, b->level + 1, NULL);
  1776. if (IS_ERR(n3))
  1777. goto err_free2;
  1778. }
  1779. mutex_lock(&n1->write_lock);
  1780. mutex_lock(&n2->write_lock);
  1781. bch_btree_insert_keys(n1, op, insert_keys, replace_key);
  1782. /*
  1783. * Has to be a linear search because we don't have an auxiliary
  1784. * search tree yet
  1785. */
  1786. while (keys < (btree_bset_first(n1)->keys * 3) / 5)
  1787. keys += bkey_u64s(bset_bkey_idx(btree_bset_first(n1),
  1788. keys));
  1789. bkey_copy_key(&n1->key,
  1790. bset_bkey_idx(btree_bset_first(n1), keys));
  1791. keys += bkey_u64s(bset_bkey_idx(btree_bset_first(n1), keys));
  1792. btree_bset_first(n2)->keys = btree_bset_first(n1)->keys - keys;
  1793. btree_bset_first(n1)->keys = keys;
  1794. memcpy(btree_bset_first(n2)->start,
  1795. bset_bkey_last(btree_bset_first(n1)),
  1796. btree_bset_first(n2)->keys * sizeof(uint64_t));
  1797. bkey_copy_key(&n2->key, &b->key);
  1798. bch_keylist_add(&parent_keys, &n2->key);
  1799. bch_btree_node_write(n2, &cl);
  1800. mutex_unlock(&n2->write_lock);
  1801. rw_unlock(true, n2);
  1802. } else {
  1803. trace_bcache_btree_node_compact(b, btree_bset_first(n1)->keys);
  1804. mutex_lock(&n1->write_lock);
  1805. bch_btree_insert_keys(n1, op, insert_keys, replace_key);
  1806. }
  1807. bch_keylist_add(&parent_keys, &n1->key);
  1808. bch_btree_node_write(n1, &cl);
  1809. mutex_unlock(&n1->write_lock);
  1810. if (n3) {
  1811. /* Depth increases, make a new root */
  1812. mutex_lock(&n3->write_lock);
  1813. bkey_copy_key(&n3->key, &MAX_KEY);
  1814. bch_btree_insert_keys(n3, op, &parent_keys, NULL);
  1815. bch_btree_node_write(n3, &cl);
  1816. mutex_unlock(&n3->write_lock);
  1817. closure_sync(&cl);
  1818. bch_btree_set_root(n3);
  1819. rw_unlock(true, n3);
  1820. } else if (!b->parent) {
  1821. /* Root filled up but didn't need to be split */
  1822. closure_sync(&cl);
  1823. bch_btree_set_root(n1);
  1824. } else {
  1825. /* Split a non root node */
  1826. closure_sync(&cl);
  1827. make_btree_freeing_key(b, parent_keys.top);
  1828. bch_keylist_push(&parent_keys);
  1829. bch_btree_insert_node(b->parent, op, &parent_keys, NULL, NULL);
  1830. BUG_ON(!bch_keylist_empty(&parent_keys));
  1831. }
  1832. btree_node_free(b);
  1833. rw_unlock(true, n1);
  1834. bch_time_stats_update(&b->c->btree_split_time, start_time);
  1835. return 0;
  1836. err_free2:
  1837. bkey_put(b->c, &n2->key);
  1838. btree_node_free(n2);
  1839. rw_unlock(true, n2);
  1840. err_free1:
  1841. bkey_put(b->c, &n1->key);
  1842. btree_node_free(n1);
  1843. rw_unlock(true, n1);
  1844. err:
  1845. WARN(1, "bcache: btree split failed (level %u)", b->level);
  1846. if (n3 == ERR_PTR(-EAGAIN) ||
  1847. n2 == ERR_PTR(-EAGAIN) ||
  1848. n1 == ERR_PTR(-EAGAIN))
  1849. return -EAGAIN;
  1850. return -ENOMEM;
  1851. }
  1852. static int bch_btree_insert_node(struct btree *b, struct btree_op *op,
  1853. struct keylist *insert_keys,
  1854. atomic_t *journal_ref,
  1855. struct bkey *replace_key)
  1856. {
  1857. struct closure cl;
  1858. BUG_ON(b->level && replace_key);
  1859. closure_init_stack(&cl);
  1860. mutex_lock(&b->write_lock);
  1861. if (write_block(b) != btree_bset_last(b) &&
  1862. b->keys.last_set_unwritten)
  1863. bch_btree_init_next(b); /* just wrote a set */
  1864. if (bch_keylist_nkeys(insert_keys) > insert_u64s_remaining(b)) {
  1865. mutex_unlock(&b->write_lock);
  1866. goto split;
  1867. }
  1868. BUG_ON(write_block(b) != btree_bset_last(b));
  1869. if (bch_btree_insert_keys(b, op, insert_keys, replace_key)) {
  1870. if (!b->level)
  1871. bch_btree_leaf_dirty(b, journal_ref);
  1872. else
  1873. bch_btree_node_write(b, &cl);
  1874. }
  1875. mutex_unlock(&b->write_lock);
  1876. /* wait for btree node write if necessary, after unlock */
  1877. closure_sync(&cl);
  1878. return 0;
  1879. split:
  1880. if (current->bio_list) {
  1881. op->lock = b->c->root->level + 1;
  1882. return -EAGAIN;
  1883. } else if (op->lock <= b->c->root->level) {
  1884. op->lock = b->c->root->level + 1;
  1885. return -EINTR;
  1886. } else {
  1887. /* Invalidated all iterators */
  1888. int ret = btree_split(b, op, insert_keys, replace_key);
  1889. if (bch_keylist_empty(insert_keys))
  1890. return 0;
  1891. else if (!ret)
  1892. return -EINTR;
  1893. return ret;
  1894. }
  1895. }
  1896. int bch_btree_insert_check_key(struct btree *b, struct btree_op *op,
  1897. struct bkey *check_key)
  1898. {
  1899. int ret = -EINTR;
  1900. uint64_t btree_ptr = b->key.ptr[0];
  1901. unsigned long seq = b->seq;
  1902. struct keylist insert;
  1903. bool upgrade = op->lock == -1;
  1904. bch_keylist_init(&insert);
  1905. if (upgrade) {
  1906. rw_unlock(false, b);
  1907. rw_lock(true, b, b->level);
  1908. if (b->key.ptr[0] != btree_ptr ||
  1909. b->seq != seq + 1) {
  1910. op->lock = b->level;
  1911. goto out;
  1912. }
  1913. }
  1914. SET_KEY_PTRS(check_key, 1);
  1915. get_random_bytes(&check_key->ptr[0], sizeof(uint64_t));
  1916. SET_PTR_DEV(check_key, 0, PTR_CHECK_DEV);
  1917. bch_keylist_add(&insert, check_key);
  1918. ret = bch_btree_insert_node(b, op, &insert, NULL, NULL);
  1919. BUG_ON(!ret && !bch_keylist_empty(&insert));
  1920. out:
  1921. if (upgrade)
  1922. downgrade_write(&b->lock);
  1923. return ret;
  1924. }
  1925. struct btree_insert_op {
  1926. struct btree_op op;
  1927. struct keylist *keys;
  1928. atomic_t *journal_ref;
  1929. struct bkey *replace_key;
  1930. };
  1931. static int btree_insert_fn(struct btree_op *b_op, struct btree *b)
  1932. {
  1933. struct btree_insert_op *op = container_of(b_op,
  1934. struct btree_insert_op, op);
  1935. int ret = bch_btree_insert_node(b, &op->op, op->keys,
  1936. op->journal_ref, op->replace_key);
  1937. if (ret && !bch_keylist_empty(op->keys))
  1938. return ret;
  1939. else
  1940. return MAP_DONE;
  1941. }
  1942. int bch_btree_insert(struct cache_set *c, struct keylist *keys,
  1943. atomic_t *journal_ref, struct bkey *replace_key)
  1944. {
  1945. struct btree_insert_op op;
  1946. int ret = 0;
  1947. BUG_ON(current->bio_list);
  1948. BUG_ON(bch_keylist_empty(keys));
  1949. bch_btree_op_init(&op.op, 0);
  1950. op.keys = keys;
  1951. op.journal_ref = journal_ref;
  1952. op.replace_key = replace_key;
  1953. while (!ret && !bch_keylist_empty(keys)) {
  1954. op.op.lock = 0;
  1955. ret = bch_btree_map_leaf_nodes(&op.op, c,
  1956. &START_KEY(keys->keys),
  1957. btree_insert_fn);
  1958. }
  1959. if (ret) {
  1960. struct bkey *k;
  1961. pr_err("error %i\n", ret);
  1962. while ((k = bch_keylist_pop(keys)))
  1963. bkey_put(c, k);
  1964. } else if (op.op.insert_collision)
  1965. ret = -ESRCH;
  1966. return ret;
  1967. }
  1968. void bch_btree_set_root(struct btree *b)
  1969. {
  1970. unsigned int i;
  1971. struct closure cl;
  1972. closure_init_stack(&cl);
  1973. trace_bcache_btree_set_root(b);
  1974. BUG_ON(!b->written);
  1975. for (i = 0; i < KEY_PTRS(&b->key); i++)
  1976. BUG_ON(PTR_BUCKET(b->c, &b->key, i)->prio != BTREE_PRIO);
  1977. mutex_lock(&b->c->bucket_lock);
  1978. list_del_init(&b->list);
  1979. mutex_unlock(&b->c->bucket_lock);
  1980. b->c->root = b;
  1981. bch_journal_meta(b->c, &cl);
  1982. closure_sync(&cl);
  1983. }
  1984. /* Map across nodes or keys */
  1985. static int bch_btree_map_nodes_recurse(struct btree *b, struct btree_op *op,
  1986. struct bkey *from,
  1987. btree_map_nodes_fn *fn, int flags)
  1988. {
  1989. int ret = MAP_CONTINUE;
  1990. if (b->level) {
  1991. struct bkey *k;
  1992. struct btree_iter iter;
  1993. bch_btree_iter_init(&b->keys, &iter, from);
  1994. while ((k = bch_btree_iter_next_filter(&iter, &b->keys,
  1995. bch_ptr_bad))) {
  1996. ret = bcache_btree(map_nodes_recurse, k, b,
  1997. op, from, fn, flags);
  1998. from = NULL;
  1999. if (ret != MAP_CONTINUE)
  2000. return ret;
  2001. }
  2002. }
  2003. if (!b->level || flags == MAP_ALL_NODES)
  2004. ret = fn(op, b);
  2005. return ret;
  2006. }
  2007. int __bch_btree_map_nodes(struct btree_op *op, struct cache_set *c,
  2008. struct bkey *from, btree_map_nodes_fn *fn, int flags)
  2009. {
  2010. return bcache_btree_root(map_nodes_recurse, c, op, from, fn, flags);
  2011. }
  2012. int bch_btree_map_keys_recurse(struct btree *b, struct btree_op *op,
  2013. struct bkey *from, btree_map_keys_fn *fn,
  2014. int flags)
  2015. {
  2016. int ret = MAP_CONTINUE;
  2017. struct bkey *k;
  2018. struct btree_iter iter;
  2019. bch_btree_iter_init(&b->keys, &iter, from);
  2020. while ((k = bch_btree_iter_next_filter(&iter, &b->keys, bch_ptr_bad))) {
  2021. ret = !b->level
  2022. ? fn(op, b, k)
  2023. : bcache_btree(map_keys_recurse, k,
  2024. b, op, from, fn, flags);
  2025. from = NULL;
  2026. if (ret != MAP_CONTINUE)
  2027. return ret;
  2028. }
  2029. if (!b->level && (flags & MAP_END_KEY))
  2030. ret = fn(op, b, &KEY(KEY_INODE(&b->key),
  2031. KEY_OFFSET(&b->key), 0));
  2032. return ret;
  2033. }
  2034. int bch_btree_map_keys(struct btree_op *op, struct cache_set *c,
  2035. struct bkey *from, btree_map_keys_fn *fn, int flags)
  2036. {
  2037. return bcache_btree_root(map_keys_recurse, c, op, from, fn, flags);
  2038. }
  2039. /* Keybuf code */
  2040. static inline int keybuf_cmp(struct keybuf_key *l, struct keybuf_key *r)
  2041. {
  2042. /* Overlapping keys compare equal */
  2043. if (bkey_cmp(&l->key, &START_KEY(&r->key)) <= 0)
  2044. return -1;
  2045. if (bkey_cmp(&START_KEY(&l->key), &r->key) >= 0)
  2046. return 1;
  2047. return 0;
  2048. }
  2049. static inline int keybuf_nonoverlapping_cmp(struct keybuf_key *l,
  2050. struct keybuf_key *r)
  2051. {
  2052. return clamp_t(int64_t, bkey_cmp(&l->key, &r->key), -1, 1);
  2053. }
  2054. struct refill {
  2055. struct btree_op op;
  2056. unsigned int nr_found;
  2057. struct keybuf *buf;
  2058. struct bkey *end;
  2059. keybuf_pred_fn *pred;
  2060. };
  2061. static int refill_keybuf_fn(struct btree_op *op, struct btree *b,
  2062. struct bkey *k)
  2063. {
  2064. struct refill *refill = container_of(op, struct refill, op);
  2065. struct keybuf *buf = refill->buf;
  2066. int ret = MAP_CONTINUE;
  2067. if (bkey_cmp(k, refill->end) > 0) {
  2068. ret = MAP_DONE;
  2069. goto out;
  2070. }
  2071. if (!KEY_SIZE(k)) /* end key */
  2072. goto out;
  2073. if (refill->pred(buf, k)) {
  2074. struct keybuf_key *w;
  2075. spin_lock(&buf->lock);
  2076. w = array_alloc(&buf->freelist);
  2077. if (!w) {
  2078. spin_unlock(&buf->lock);
  2079. return MAP_DONE;
  2080. }
  2081. w->private = NULL;
  2082. bkey_copy(&w->key, k);
  2083. if (RB_INSERT(&buf->keys, w, node, keybuf_cmp))
  2084. array_free(&buf->freelist, w);
  2085. else
  2086. refill->nr_found++;
  2087. if (array_freelist_empty(&buf->freelist))
  2088. ret = MAP_DONE;
  2089. spin_unlock(&buf->lock);
  2090. }
  2091. out:
  2092. buf->last_scanned = *k;
  2093. return ret;
  2094. }
  2095. void bch_refill_keybuf(struct cache_set *c, struct keybuf *buf,
  2096. struct bkey *end, keybuf_pred_fn *pred)
  2097. {
  2098. struct bkey start = buf->last_scanned;
  2099. struct refill refill;
  2100. cond_resched();
  2101. bch_btree_op_init(&refill.op, -1);
  2102. refill.nr_found = 0;
  2103. refill.buf = buf;
  2104. refill.end = end;
  2105. refill.pred = pred;
  2106. bch_btree_map_keys(&refill.op, c, &buf->last_scanned,
  2107. refill_keybuf_fn, MAP_END_KEY);
  2108. trace_bcache_keyscan(refill.nr_found,
  2109. KEY_INODE(&start), KEY_OFFSET(&start),
  2110. KEY_INODE(&buf->last_scanned),
  2111. KEY_OFFSET(&buf->last_scanned));
  2112. spin_lock(&buf->lock);
  2113. if (!RB_EMPTY_ROOT(&buf->keys)) {
  2114. struct keybuf_key *w;
  2115. w = RB_FIRST(&buf->keys, struct keybuf_key, node);
  2116. buf->start = START_KEY(&w->key);
  2117. w = RB_LAST(&buf->keys, struct keybuf_key, node);
  2118. buf->end = w->key;
  2119. } else {
  2120. buf->start = MAX_KEY;
  2121. buf->end = MAX_KEY;
  2122. }
  2123. spin_unlock(&buf->lock);
  2124. }
  2125. static void __bch_keybuf_del(struct keybuf *buf, struct keybuf_key *w)
  2126. {
  2127. rb_erase(&w->node, &buf->keys);
  2128. array_free(&buf->freelist, w);
  2129. }
  2130. void bch_keybuf_del(struct keybuf *buf, struct keybuf_key *w)
  2131. {
  2132. spin_lock(&buf->lock);
  2133. __bch_keybuf_del(buf, w);
  2134. spin_unlock(&buf->lock);
  2135. }
  2136. bool bch_keybuf_check_overlapping(struct keybuf *buf, struct bkey *start,
  2137. struct bkey *end)
  2138. {
  2139. bool ret = false;
  2140. struct keybuf_key *p, *w, s;
  2141. s.key = *start;
  2142. if (bkey_cmp(end, &buf->start) <= 0 ||
  2143. bkey_cmp(start, &buf->end) >= 0)
  2144. return false;
  2145. spin_lock(&buf->lock);
  2146. w = RB_GREATER(&buf->keys, s, node, keybuf_nonoverlapping_cmp);
  2147. while (w && bkey_cmp(&START_KEY(&w->key), end) < 0) {
  2148. p = w;
  2149. w = RB_NEXT(w, node);
  2150. if (p->private)
  2151. ret = true;
  2152. else
  2153. __bch_keybuf_del(buf, p);
  2154. }
  2155. spin_unlock(&buf->lock);
  2156. return ret;
  2157. }
  2158. struct keybuf_key *bch_keybuf_next(struct keybuf *buf)
  2159. {
  2160. struct keybuf_key *w;
  2161. spin_lock(&buf->lock);
  2162. w = RB_FIRST(&buf->keys, struct keybuf_key, node);
  2163. while (w && w->private)
  2164. w = RB_NEXT(w, node);
  2165. if (w)
  2166. w->private = ERR_PTR(-EINTR);
  2167. spin_unlock(&buf->lock);
  2168. return w;
  2169. }
  2170. struct keybuf_key *bch_keybuf_next_rescan(struct cache_set *c,
  2171. struct keybuf *buf,
  2172. struct bkey *end,
  2173. keybuf_pred_fn *pred)
  2174. {
  2175. struct keybuf_key *ret;
  2176. while (1) {
  2177. ret = bch_keybuf_next(buf);
  2178. if (ret)
  2179. break;
  2180. if (bkey_cmp(&buf->last_scanned, end) >= 0) {
  2181. pr_debug("scan finished\n");
  2182. break;
  2183. }
  2184. bch_refill_keybuf(c, buf, end, pred);
  2185. }
  2186. return ret;
  2187. }
  2188. void bch_keybuf_init(struct keybuf *buf)
  2189. {
  2190. buf->last_scanned = MAX_KEY;
  2191. buf->keys = RB_ROOT;
  2192. spin_lock_init(&buf->lock);
  2193. array_allocator_init(&buf->freelist);
  2194. }
  2195. void bch_btree_exit(void)
  2196. {
  2197. if (btree_io_wq)
  2198. destroy_workqueue(btree_io_wq);
  2199. }
  2200. int __init bch_btree_init(void)
  2201. {
  2202. btree_io_wq = alloc_workqueue("bch_btree_io", WQ_MEM_RECLAIM, 0);
  2203. if (!btree_io_wq)
  2204. return -ENOMEM;
  2205. return 0;
  2206. }