btree.c 57 KB

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