btree.c 57 KB

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