btree.c 57 KB

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