btree.c 57 KB

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