btree.c 57 KB

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