btree.c 55 KB

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