btree.c 54 KB

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