btree.c 56 KB

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