btree.c 57 KB

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