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