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