btree.c 56 KB

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