btree.c 55 KB

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