btree.c 64 KB

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