bset.c 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332
  1. /*
  2. * Code for working with individual keys, and sorted sets of keys with in a
  3. * btree node
  4. *
  5. * Copyright 2012 Google, Inc.
  6. */
  7. #define pr_fmt(fmt) "bcache: %s() " fmt "\n", __func__
  8. #include "util.h"
  9. #include "bset.h"
  10. #include <linux/console.h>
  11. #include <linux/sched/clock.h>
  12. #include <linux/random.h>
  13. #include <linux/prefetch.h>
  14. #ifdef CONFIG_BCACHE_DEBUG
  15. void bch_dump_bset(struct btree_keys *b, struct bset *i, unsigned set)
  16. {
  17. struct bkey *k, *next;
  18. for (k = i->start; k < bset_bkey_last(i); k = next) {
  19. next = bkey_next(k);
  20. printk(KERN_ERR "block %u key %u/%u: ", set,
  21. (unsigned) ((u64 *) k - i->d), i->keys);
  22. if (b->ops->key_dump)
  23. b->ops->key_dump(b, k);
  24. else
  25. printk("%llu:%llu\n", KEY_INODE(k), KEY_OFFSET(k));
  26. if (next < bset_bkey_last(i) &&
  27. bkey_cmp(k, b->ops->is_extents ?
  28. &START_KEY(next) : next) > 0)
  29. printk(KERN_ERR "Key skipped backwards\n");
  30. }
  31. }
  32. void bch_dump_bucket(struct btree_keys *b)
  33. {
  34. unsigned i;
  35. console_lock();
  36. for (i = 0; i <= b->nsets; i++)
  37. bch_dump_bset(b, b->set[i].data,
  38. bset_sector_offset(b, b->set[i].data));
  39. console_unlock();
  40. }
  41. int __bch_count_data(struct btree_keys *b)
  42. {
  43. unsigned ret = 0;
  44. struct btree_iter iter;
  45. struct bkey *k;
  46. if (b->ops->is_extents)
  47. for_each_key(b, k, &iter)
  48. ret += KEY_SIZE(k);
  49. return ret;
  50. }
  51. void __bch_check_keys(struct btree_keys *b, const char *fmt, ...)
  52. {
  53. va_list args;
  54. struct bkey *k, *p = NULL;
  55. struct btree_iter iter;
  56. const char *err;
  57. for_each_key(b, k, &iter) {
  58. if (b->ops->is_extents) {
  59. err = "Keys out of order";
  60. if (p && bkey_cmp(&START_KEY(p), &START_KEY(k)) > 0)
  61. goto bug;
  62. if (bch_ptr_invalid(b, k))
  63. continue;
  64. err = "Overlapping keys";
  65. if (p && bkey_cmp(p, &START_KEY(k)) > 0)
  66. goto bug;
  67. } else {
  68. if (bch_ptr_bad(b, k))
  69. continue;
  70. err = "Duplicate keys";
  71. if (p && !bkey_cmp(p, k))
  72. goto bug;
  73. }
  74. p = k;
  75. }
  76. #if 0
  77. err = "Key larger than btree node key";
  78. if (p && bkey_cmp(p, &b->key) > 0)
  79. goto bug;
  80. #endif
  81. return;
  82. bug:
  83. bch_dump_bucket(b);
  84. va_start(args, fmt);
  85. vprintk(fmt, args);
  86. va_end(args);
  87. panic("bch_check_keys error: %s:\n", err);
  88. }
  89. static void bch_btree_iter_next_check(struct btree_iter *iter)
  90. {
  91. struct bkey *k = iter->data->k, *next = bkey_next(k);
  92. if (next < iter->data->end &&
  93. bkey_cmp(k, iter->b->ops->is_extents ?
  94. &START_KEY(next) : next) > 0) {
  95. bch_dump_bucket(iter->b);
  96. panic("Key skipped backwards\n");
  97. }
  98. }
  99. #else
  100. static inline void bch_btree_iter_next_check(struct btree_iter *iter) {}
  101. #endif
  102. /* Keylists */
  103. int __bch_keylist_realloc(struct keylist *l, unsigned u64s)
  104. {
  105. size_t oldsize = bch_keylist_nkeys(l);
  106. size_t newsize = oldsize + u64s;
  107. uint64_t *old_keys = l->keys_p == l->inline_keys ? NULL : l->keys_p;
  108. uint64_t *new_keys;
  109. newsize = roundup_pow_of_two(newsize);
  110. if (newsize <= KEYLIST_INLINE ||
  111. roundup_pow_of_two(oldsize) == newsize)
  112. return 0;
  113. new_keys = krealloc(old_keys, sizeof(uint64_t) * newsize, GFP_NOIO);
  114. if (!new_keys)
  115. return -ENOMEM;
  116. if (!old_keys)
  117. memcpy(new_keys, l->inline_keys, sizeof(uint64_t) * oldsize);
  118. l->keys_p = new_keys;
  119. l->top_p = new_keys + oldsize;
  120. return 0;
  121. }
  122. struct bkey *bch_keylist_pop(struct keylist *l)
  123. {
  124. struct bkey *k = l->keys;
  125. if (k == l->top)
  126. return NULL;
  127. while (bkey_next(k) != l->top)
  128. k = bkey_next(k);
  129. return l->top = k;
  130. }
  131. void bch_keylist_pop_front(struct keylist *l)
  132. {
  133. l->top_p -= bkey_u64s(l->keys);
  134. memmove(l->keys,
  135. bkey_next(l->keys),
  136. bch_keylist_bytes(l));
  137. }
  138. /* Key/pointer manipulation */
  139. void bch_bkey_copy_single_ptr(struct bkey *dest, const struct bkey *src,
  140. unsigned i)
  141. {
  142. BUG_ON(i > KEY_PTRS(src));
  143. /* Only copy the header, key, and one pointer. */
  144. memcpy(dest, src, 2 * sizeof(uint64_t));
  145. dest->ptr[0] = src->ptr[i];
  146. SET_KEY_PTRS(dest, 1);
  147. /* We didn't copy the checksum so clear that bit. */
  148. SET_KEY_CSUM(dest, 0);
  149. }
  150. bool __bch_cut_front(const struct bkey *where, struct bkey *k)
  151. {
  152. unsigned i, len = 0;
  153. if (bkey_cmp(where, &START_KEY(k)) <= 0)
  154. return false;
  155. if (bkey_cmp(where, k) < 0)
  156. len = KEY_OFFSET(k) - KEY_OFFSET(where);
  157. else
  158. bkey_copy_key(k, where);
  159. for (i = 0; i < KEY_PTRS(k); i++)
  160. SET_PTR_OFFSET(k, i, PTR_OFFSET(k, i) + KEY_SIZE(k) - len);
  161. BUG_ON(len > KEY_SIZE(k));
  162. SET_KEY_SIZE(k, len);
  163. return true;
  164. }
  165. bool __bch_cut_back(const struct bkey *where, struct bkey *k)
  166. {
  167. unsigned len = 0;
  168. if (bkey_cmp(where, k) >= 0)
  169. return false;
  170. BUG_ON(KEY_INODE(where) != KEY_INODE(k));
  171. if (bkey_cmp(where, &START_KEY(k)) > 0)
  172. len = KEY_OFFSET(where) - KEY_START(k);
  173. bkey_copy_key(k, where);
  174. BUG_ON(len > KEY_SIZE(k));
  175. SET_KEY_SIZE(k, len);
  176. return true;
  177. }
  178. /* Auxiliary search trees */
  179. /* 32 bits total: */
  180. #define BKEY_MID_BITS 3
  181. #define BKEY_EXPONENT_BITS 7
  182. #define BKEY_MANTISSA_BITS (32 - BKEY_MID_BITS - BKEY_EXPONENT_BITS)
  183. #define BKEY_MANTISSA_MASK ((1 << BKEY_MANTISSA_BITS) - 1)
  184. struct bkey_float {
  185. unsigned exponent:BKEY_EXPONENT_BITS;
  186. unsigned m:BKEY_MID_BITS;
  187. unsigned mantissa:BKEY_MANTISSA_BITS;
  188. } __packed;
  189. /*
  190. * BSET_CACHELINE was originally intended to match the hardware cacheline size -
  191. * it used to be 64, but I realized the lookup code would touch slightly less
  192. * memory if it was 128.
  193. *
  194. * It definites the number of bytes (in struct bset) per struct bkey_float in
  195. * the auxiliar search tree - when we're done searching the bset_float tree we
  196. * have this many bytes left that we do a linear search over.
  197. *
  198. * Since (after level 5) every level of the bset_tree is on a new cacheline,
  199. * we're touching one fewer cacheline in the bset tree in exchange for one more
  200. * cacheline in the linear search - but the linear search might stop before it
  201. * gets to the second cacheline.
  202. */
  203. #define BSET_CACHELINE 128
  204. /* Space required for the btree node keys */
  205. static inline size_t btree_keys_bytes(struct btree_keys *b)
  206. {
  207. return PAGE_SIZE << b->page_order;
  208. }
  209. static inline size_t btree_keys_cachelines(struct btree_keys *b)
  210. {
  211. return btree_keys_bytes(b) / BSET_CACHELINE;
  212. }
  213. /* Space required for the auxiliary search trees */
  214. static inline size_t bset_tree_bytes(struct btree_keys *b)
  215. {
  216. return btree_keys_cachelines(b) * sizeof(struct bkey_float);
  217. }
  218. /* Space required for the prev pointers */
  219. static inline size_t bset_prev_bytes(struct btree_keys *b)
  220. {
  221. return btree_keys_cachelines(b) * sizeof(uint8_t);
  222. }
  223. /* Memory allocation */
  224. void bch_btree_keys_free(struct btree_keys *b)
  225. {
  226. struct bset_tree *t = b->set;
  227. if (bset_prev_bytes(b) < PAGE_SIZE)
  228. kfree(t->prev);
  229. else
  230. free_pages((unsigned long) t->prev,
  231. get_order(bset_prev_bytes(b)));
  232. if (bset_tree_bytes(b) < PAGE_SIZE)
  233. kfree(t->tree);
  234. else
  235. free_pages((unsigned long) t->tree,
  236. get_order(bset_tree_bytes(b)));
  237. free_pages((unsigned long) t->data, b->page_order);
  238. t->prev = NULL;
  239. t->tree = NULL;
  240. t->data = NULL;
  241. }
  242. EXPORT_SYMBOL(bch_btree_keys_free);
  243. int bch_btree_keys_alloc(struct btree_keys *b, unsigned page_order, gfp_t gfp)
  244. {
  245. struct bset_tree *t = b->set;
  246. BUG_ON(t->data);
  247. b->page_order = page_order;
  248. t->data = (void *) __get_free_pages(gfp, b->page_order);
  249. if (!t->data)
  250. goto err;
  251. t->tree = bset_tree_bytes(b) < PAGE_SIZE
  252. ? kmalloc(bset_tree_bytes(b), gfp)
  253. : (void *) __get_free_pages(gfp, get_order(bset_tree_bytes(b)));
  254. if (!t->tree)
  255. goto err;
  256. t->prev = bset_prev_bytes(b) < PAGE_SIZE
  257. ? kmalloc(bset_prev_bytes(b), gfp)
  258. : (void *) __get_free_pages(gfp, get_order(bset_prev_bytes(b)));
  259. if (!t->prev)
  260. goto err;
  261. return 0;
  262. err:
  263. bch_btree_keys_free(b);
  264. return -ENOMEM;
  265. }
  266. EXPORT_SYMBOL(bch_btree_keys_alloc);
  267. void bch_btree_keys_init(struct btree_keys *b, const struct btree_keys_ops *ops,
  268. bool *expensive_debug_checks)
  269. {
  270. unsigned i;
  271. b->ops = ops;
  272. b->expensive_debug_checks = expensive_debug_checks;
  273. b->nsets = 0;
  274. b->last_set_unwritten = 0;
  275. /* XXX: shouldn't be needed */
  276. for (i = 0; i < MAX_BSETS; i++)
  277. b->set[i].size = 0;
  278. /*
  279. * Second loop starts at 1 because b->keys[0]->data is the memory we
  280. * allocated
  281. */
  282. for (i = 1; i < MAX_BSETS; i++)
  283. b->set[i].data = NULL;
  284. }
  285. EXPORT_SYMBOL(bch_btree_keys_init);
  286. /* Binary tree stuff for auxiliary search trees */
  287. static unsigned inorder_next(unsigned j, unsigned size)
  288. {
  289. if (j * 2 + 1 < size) {
  290. j = j * 2 + 1;
  291. while (j * 2 < size)
  292. j *= 2;
  293. } else
  294. j >>= ffz(j) + 1;
  295. return j;
  296. }
  297. static unsigned inorder_prev(unsigned j, unsigned size)
  298. {
  299. if (j * 2 < size) {
  300. j = j * 2;
  301. while (j * 2 + 1 < size)
  302. j = j * 2 + 1;
  303. } else
  304. j >>= ffs(j);
  305. return j;
  306. }
  307. /* I have no idea why this code works... and I'm the one who wrote it
  308. *
  309. * However, I do know what it does:
  310. * Given a binary tree constructed in an array (i.e. how you normally implement
  311. * a heap), it converts a node in the tree - referenced by array index - to the
  312. * index it would have if you did an inorder traversal.
  313. *
  314. * Also tested for every j, size up to size somewhere around 6 million.
  315. *
  316. * The binary tree starts at array index 1, not 0
  317. * extra is a function of size:
  318. * extra = (size - rounddown_pow_of_two(size - 1)) << 1;
  319. */
  320. static unsigned __to_inorder(unsigned j, unsigned size, unsigned extra)
  321. {
  322. unsigned b = fls(j);
  323. unsigned shift = fls(size - 1) - b;
  324. j ^= 1U << (b - 1);
  325. j <<= 1;
  326. j |= 1;
  327. j <<= shift;
  328. if (j > extra)
  329. j -= (j - extra) >> 1;
  330. return j;
  331. }
  332. static unsigned to_inorder(unsigned j, struct bset_tree *t)
  333. {
  334. return __to_inorder(j, t->size, t->extra);
  335. }
  336. static unsigned __inorder_to_tree(unsigned j, unsigned size, unsigned extra)
  337. {
  338. unsigned shift;
  339. if (j > extra)
  340. j += j - extra;
  341. shift = ffs(j);
  342. j >>= shift;
  343. j |= roundup_pow_of_two(size) >> shift;
  344. return j;
  345. }
  346. static unsigned inorder_to_tree(unsigned j, struct bset_tree *t)
  347. {
  348. return __inorder_to_tree(j, t->size, t->extra);
  349. }
  350. #if 0
  351. void inorder_test(void)
  352. {
  353. unsigned long done = 0;
  354. ktime_t start = ktime_get();
  355. for (unsigned size = 2;
  356. size < 65536000;
  357. size++) {
  358. unsigned extra = (size - rounddown_pow_of_two(size - 1)) << 1;
  359. unsigned i = 1, j = rounddown_pow_of_two(size - 1);
  360. if (!(size % 4096))
  361. printk(KERN_NOTICE "loop %u, %llu per us\n", size,
  362. done / ktime_us_delta(ktime_get(), start));
  363. while (1) {
  364. if (__inorder_to_tree(i, size, extra) != j)
  365. panic("size %10u j %10u i %10u", size, j, i);
  366. if (__to_inorder(j, size, extra) != i)
  367. panic("size %10u j %10u i %10u", size, j, i);
  368. if (j == rounddown_pow_of_two(size) - 1)
  369. break;
  370. BUG_ON(inorder_prev(inorder_next(j, size), size) != j);
  371. j = inorder_next(j, size);
  372. i++;
  373. }
  374. done += size - 1;
  375. }
  376. }
  377. #endif
  378. /*
  379. * Cacheline/offset <-> bkey pointer arithmetic:
  380. *
  381. * t->tree is a binary search tree in an array; each node corresponds to a key
  382. * in one cacheline in t->set (BSET_CACHELINE bytes).
  383. *
  384. * This means we don't have to store the full index of the key that a node in
  385. * the binary tree points to; to_inorder() gives us the cacheline, and then
  386. * bkey_float->m gives us the offset within that cacheline, in units of 8 bytes.
  387. *
  388. * cacheline_to_bkey() and friends abstract out all the pointer arithmetic to
  389. * make this work.
  390. *
  391. * To construct the bfloat for an arbitrary key we need to know what the key
  392. * immediately preceding it is: we have to check if the two keys differ in the
  393. * bits we're going to store in bkey_float->mantissa. t->prev[j] stores the size
  394. * of the previous key so we can walk backwards to it from t->tree[j]'s key.
  395. */
  396. static struct bkey *cacheline_to_bkey(struct bset_tree *t, unsigned cacheline,
  397. unsigned offset)
  398. {
  399. return ((void *) t->data) + cacheline * BSET_CACHELINE + offset * 8;
  400. }
  401. static unsigned bkey_to_cacheline(struct bset_tree *t, struct bkey *k)
  402. {
  403. return ((void *) k - (void *) t->data) / BSET_CACHELINE;
  404. }
  405. static unsigned bkey_to_cacheline_offset(struct bset_tree *t,
  406. unsigned cacheline,
  407. struct bkey *k)
  408. {
  409. return (u64 *) k - (u64 *) cacheline_to_bkey(t, cacheline, 0);
  410. }
  411. static struct bkey *tree_to_bkey(struct bset_tree *t, unsigned j)
  412. {
  413. return cacheline_to_bkey(t, to_inorder(j, t), t->tree[j].m);
  414. }
  415. static struct bkey *tree_to_prev_bkey(struct bset_tree *t, unsigned j)
  416. {
  417. return (void *) (((uint64_t *) tree_to_bkey(t, j)) - t->prev[j]);
  418. }
  419. /*
  420. * For the write set - the one we're currently inserting keys into - we don't
  421. * maintain a full search tree, we just keep a simple lookup table in t->prev.
  422. */
  423. static struct bkey *table_to_bkey(struct bset_tree *t, unsigned cacheline)
  424. {
  425. return cacheline_to_bkey(t, cacheline, t->prev[cacheline]);
  426. }
  427. static inline uint64_t shrd128(uint64_t high, uint64_t low, uint8_t shift)
  428. {
  429. low >>= shift;
  430. low |= (high << 1) << (63U - shift);
  431. return low;
  432. }
  433. static inline unsigned bfloat_mantissa(const struct bkey *k,
  434. struct bkey_float *f)
  435. {
  436. const uint64_t *p = &k->low - (f->exponent >> 6);
  437. return shrd128(p[-1], p[0], f->exponent & 63) & BKEY_MANTISSA_MASK;
  438. }
  439. static void make_bfloat(struct bset_tree *t, unsigned j)
  440. {
  441. struct bkey_float *f = &t->tree[j];
  442. struct bkey *m = tree_to_bkey(t, j);
  443. struct bkey *p = tree_to_prev_bkey(t, j);
  444. struct bkey *l = is_power_of_2(j)
  445. ? t->data->start
  446. : tree_to_prev_bkey(t, j >> ffs(j));
  447. struct bkey *r = is_power_of_2(j + 1)
  448. ? bset_bkey_idx(t->data, t->data->keys - bkey_u64s(&t->end))
  449. : tree_to_bkey(t, j >> (ffz(j) + 1));
  450. BUG_ON(m < l || m > r);
  451. BUG_ON(bkey_next(p) != m);
  452. if (KEY_INODE(l) != KEY_INODE(r))
  453. f->exponent = fls64(KEY_INODE(r) ^ KEY_INODE(l)) + 64;
  454. else
  455. f->exponent = fls64(r->low ^ l->low);
  456. f->exponent = max_t(int, f->exponent - BKEY_MANTISSA_BITS, 0);
  457. /*
  458. * Setting f->exponent = 127 flags this node as failed, and causes the
  459. * lookup code to fall back to comparing against the original key.
  460. */
  461. if (bfloat_mantissa(m, f) != bfloat_mantissa(p, f))
  462. f->mantissa = bfloat_mantissa(m, f) - 1;
  463. else
  464. f->exponent = 127;
  465. }
  466. static void bset_alloc_tree(struct btree_keys *b, struct bset_tree *t)
  467. {
  468. if (t != b->set) {
  469. unsigned j = roundup(t[-1].size,
  470. 64 / sizeof(struct bkey_float));
  471. t->tree = t[-1].tree + j;
  472. t->prev = t[-1].prev + j;
  473. }
  474. while (t < b->set + MAX_BSETS)
  475. t++->size = 0;
  476. }
  477. static void bch_bset_build_unwritten_tree(struct btree_keys *b)
  478. {
  479. struct bset_tree *t = bset_tree_last(b);
  480. BUG_ON(b->last_set_unwritten);
  481. b->last_set_unwritten = 1;
  482. bset_alloc_tree(b, t);
  483. if (t->tree != b->set->tree + btree_keys_cachelines(b)) {
  484. t->prev[0] = bkey_to_cacheline_offset(t, 0, t->data->start);
  485. t->size = 1;
  486. }
  487. }
  488. void bch_bset_init_next(struct btree_keys *b, struct bset *i, uint64_t magic)
  489. {
  490. if (i != b->set->data) {
  491. b->set[++b->nsets].data = i;
  492. i->seq = b->set->data->seq;
  493. } else
  494. get_random_bytes(&i->seq, sizeof(uint64_t));
  495. i->magic = magic;
  496. i->version = 0;
  497. i->keys = 0;
  498. bch_bset_build_unwritten_tree(b);
  499. }
  500. EXPORT_SYMBOL(bch_bset_init_next);
  501. void bch_bset_build_written_tree(struct btree_keys *b)
  502. {
  503. struct bset_tree *t = bset_tree_last(b);
  504. struct bkey *prev = NULL, *k = t->data->start;
  505. unsigned j, cacheline = 1;
  506. b->last_set_unwritten = 0;
  507. bset_alloc_tree(b, t);
  508. t->size = min_t(unsigned,
  509. bkey_to_cacheline(t, bset_bkey_last(t->data)),
  510. b->set->tree + btree_keys_cachelines(b) - t->tree);
  511. if (t->size < 2) {
  512. t->size = 0;
  513. return;
  514. }
  515. t->extra = (t->size - rounddown_pow_of_two(t->size - 1)) << 1;
  516. /* First we figure out where the first key in each cacheline is */
  517. for (j = inorder_next(0, t->size);
  518. j;
  519. j = inorder_next(j, t->size)) {
  520. while (bkey_to_cacheline(t, k) < cacheline)
  521. prev = k, k = bkey_next(k);
  522. t->prev[j] = bkey_u64s(prev);
  523. t->tree[j].m = bkey_to_cacheline_offset(t, cacheline++, k);
  524. }
  525. while (bkey_next(k) != bset_bkey_last(t->data))
  526. k = bkey_next(k);
  527. t->end = *k;
  528. /* Then we build the tree */
  529. for (j = inorder_next(0, t->size);
  530. j;
  531. j = inorder_next(j, t->size))
  532. make_bfloat(t, j);
  533. }
  534. EXPORT_SYMBOL(bch_bset_build_written_tree);
  535. /* Insert */
  536. void bch_bset_fix_invalidated_key(struct btree_keys *b, struct bkey *k)
  537. {
  538. struct bset_tree *t;
  539. unsigned inorder, j = 1;
  540. for (t = b->set; t <= bset_tree_last(b); t++)
  541. if (k < bset_bkey_last(t->data))
  542. goto found_set;
  543. BUG();
  544. found_set:
  545. if (!t->size || !bset_written(b, t))
  546. return;
  547. inorder = bkey_to_cacheline(t, k);
  548. if (k == t->data->start)
  549. goto fix_left;
  550. if (bkey_next(k) == bset_bkey_last(t->data)) {
  551. t->end = *k;
  552. goto fix_right;
  553. }
  554. j = inorder_to_tree(inorder, t);
  555. if (j &&
  556. j < t->size &&
  557. k == tree_to_bkey(t, j))
  558. fix_left: do {
  559. make_bfloat(t, j);
  560. j = j * 2;
  561. } while (j < t->size);
  562. j = inorder_to_tree(inorder + 1, t);
  563. if (j &&
  564. j < t->size &&
  565. k == tree_to_prev_bkey(t, j))
  566. fix_right: do {
  567. make_bfloat(t, j);
  568. j = j * 2 + 1;
  569. } while (j < t->size);
  570. }
  571. EXPORT_SYMBOL(bch_bset_fix_invalidated_key);
  572. static void bch_bset_fix_lookup_table(struct btree_keys *b,
  573. struct bset_tree *t,
  574. struct bkey *k)
  575. {
  576. unsigned shift = bkey_u64s(k);
  577. unsigned j = bkey_to_cacheline(t, k);
  578. /* We're getting called from btree_split() or btree_gc, just bail out */
  579. if (!t->size)
  580. return;
  581. /* k is the key we just inserted; we need to find the entry in the
  582. * lookup table for the first key that is strictly greater than k:
  583. * it's either k's cacheline or the next one
  584. */
  585. while (j < t->size &&
  586. table_to_bkey(t, j) <= k)
  587. j++;
  588. /* Adjust all the lookup table entries, and find a new key for any that
  589. * have gotten too big
  590. */
  591. for (; j < t->size; j++) {
  592. t->prev[j] += shift;
  593. if (t->prev[j] > 7) {
  594. k = table_to_bkey(t, j - 1);
  595. while (k < cacheline_to_bkey(t, j, 0))
  596. k = bkey_next(k);
  597. t->prev[j] = bkey_to_cacheline_offset(t, j, k);
  598. }
  599. }
  600. if (t->size == b->set->tree + btree_keys_cachelines(b) - t->tree)
  601. return;
  602. /* Possibly add a new entry to the end of the lookup table */
  603. for (k = table_to_bkey(t, t->size - 1);
  604. k != bset_bkey_last(t->data);
  605. k = bkey_next(k))
  606. if (t->size == bkey_to_cacheline(t, k)) {
  607. t->prev[t->size] = bkey_to_cacheline_offset(t, t->size, k);
  608. t->size++;
  609. }
  610. }
  611. /*
  612. * Tries to merge l and r: l should be lower than r
  613. * Returns true if we were able to merge. If we did merge, l will be the merged
  614. * key, r will be untouched.
  615. */
  616. bool bch_bkey_try_merge(struct btree_keys *b, struct bkey *l, struct bkey *r)
  617. {
  618. if (!b->ops->key_merge)
  619. return false;
  620. /*
  621. * Generic header checks
  622. * Assumes left and right are in order
  623. * Left and right must be exactly aligned
  624. */
  625. if (!bch_bkey_equal_header(l, r) ||
  626. bkey_cmp(l, &START_KEY(r)))
  627. return false;
  628. return b->ops->key_merge(b, l, r);
  629. }
  630. EXPORT_SYMBOL(bch_bkey_try_merge);
  631. void bch_bset_insert(struct btree_keys *b, struct bkey *where,
  632. struct bkey *insert)
  633. {
  634. struct bset_tree *t = bset_tree_last(b);
  635. BUG_ON(!b->last_set_unwritten);
  636. BUG_ON(bset_byte_offset(b, t->data) +
  637. __set_bytes(t->data, t->data->keys + bkey_u64s(insert)) >
  638. PAGE_SIZE << b->page_order);
  639. memmove((uint64_t *) where + bkey_u64s(insert),
  640. where,
  641. (void *) bset_bkey_last(t->data) - (void *) where);
  642. t->data->keys += bkey_u64s(insert);
  643. bkey_copy(where, insert);
  644. bch_bset_fix_lookup_table(b, t, where);
  645. }
  646. EXPORT_SYMBOL(bch_bset_insert);
  647. unsigned bch_btree_insert_key(struct btree_keys *b, struct bkey *k,
  648. struct bkey *replace_key)
  649. {
  650. unsigned status = BTREE_INSERT_STATUS_NO_INSERT;
  651. struct bset *i = bset_tree_last(b)->data;
  652. struct bkey *m, *prev = NULL;
  653. struct btree_iter iter;
  654. BUG_ON(b->ops->is_extents && !KEY_SIZE(k));
  655. m = bch_btree_iter_init(b, &iter, b->ops->is_extents
  656. ? PRECEDING_KEY(&START_KEY(k))
  657. : PRECEDING_KEY(k));
  658. if (b->ops->insert_fixup(b, k, &iter, replace_key))
  659. return status;
  660. status = BTREE_INSERT_STATUS_INSERT;
  661. while (m != bset_bkey_last(i) &&
  662. bkey_cmp(k, b->ops->is_extents ? &START_KEY(m) : m) > 0)
  663. prev = m, m = bkey_next(m);
  664. /* prev is in the tree, if we merge we're done */
  665. status = BTREE_INSERT_STATUS_BACK_MERGE;
  666. if (prev &&
  667. bch_bkey_try_merge(b, prev, k))
  668. goto merged;
  669. #if 0
  670. status = BTREE_INSERT_STATUS_OVERWROTE;
  671. if (m != bset_bkey_last(i) &&
  672. KEY_PTRS(m) == KEY_PTRS(k) && !KEY_SIZE(m))
  673. goto copy;
  674. #endif
  675. status = BTREE_INSERT_STATUS_FRONT_MERGE;
  676. if (m != bset_bkey_last(i) &&
  677. bch_bkey_try_merge(b, k, m))
  678. goto copy;
  679. bch_bset_insert(b, m, k);
  680. copy: bkey_copy(m, k);
  681. merged:
  682. return status;
  683. }
  684. EXPORT_SYMBOL(bch_btree_insert_key);
  685. /* Lookup */
  686. struct bset_search_iter {
  687. struct bkey *l, *r;
  688. };
  689. static struct bset_search_iter bset_search_write_set(struct bset_tree *t,
  690. const struct bkey *search)
  691. {
  692. unsigned li = 0, ri = t->size;
  693. while (li + 1 != ri) {
  694. unsigned m = (li + ri) >> 1;
  695. if (bkey_cmp(table_to_bkey(t, m), search) > 0)
  696. ri = m;
  697. else
  698. li = m;
  699. }
  700. return (struct bset_search_iter) {
  701. table_to_bkey(t, li),
  702. ri < t->size ? table_to_bkey(t, ri) : bset_bkey_last(t->data)
  703. };
  704. }
  705. static struct bset_search_iter bset_search_tree(struct bset_tree *t,
  706. const struct bkey *search)
  707. {
  708. struct bkey *l, *r;
  709. struct bkey_float *f;
  710. unsigned inorder, j, n = 1;
  711. do {
  712. unsigned p = n << 4;
  713. p &= ((int) (p - t->size)) >> 31;
  714. prefetch(&t->tree[p]);
  715. j = n;
  716. f = &t->tree[j];
  717. /*
  718. * n = (f->mantissa > bfloat_mantissa())
  719. * ? j * 2
  720. * : j * 2 + 1;
  721. *
  722. * We need to subtract 1 from f->mantissa for the sign bit trick
  723. * to work - that's done in make_bfloat()
  724. */
  725. if (likely(f->exponent != 127))
  726. n = j * 2 + (((unsigned)
  727. (f->mantissa -
  728. bfloat_mantissa(search, f))) >> 31);
  729. else
  730. n = (bkey_cmp(tree_to_bkey(t, j), search) > 0)
  731. ? j * 2
  732. : j * 2 + 1;
  733. } while (n < t->size);
  734. inorder = to_inorder(j, t);
  735. /*
  736. * n would have been the node we recursed to - the low bit tells us if
  737. * we recursed left or recursed right.
  738. */
  739. if (n & 1) {
  740. l = cacheline_to_bkey(t, inorder, f->m);
  741. if (++inorder != t->size) {
  742. f = &t->tree[inorder_next(j, t->size)];
  743. r = cacheline_to_bkey(t, inorder, f->m);
  744. } else
  745. r = bset_bkey_last(t->data);
  746. } else {
  747. r = cacheline_to_bkey(t, inorder, f->m);
  748. if (--inorder) {
  749. f = &t->tree[inorder_prev(j, t->size)];
  750. l = cacheline_to_bkey(t, inorder, f->m);
  751. } else
  752. l = t->data->start;
  753. }
  754. return (struct bset_search_iter) {l, r};
  755. }
  756. struct bkey *__bch_bset_search(struct btree_keys *b, struct bset_tree *t,
  757. const struct bkey *search)
  758. {
  759. struct bset_search_iter i;
  760. /*
  761. * First, we search for a cacheline, then lastly we do a linear search
  762. * within that cacheline.
  763. *
  764. * To search for the cacheline, there's three different possibilities:
  765. * * The set is too small to have a search tree, so we just do a linear
  766. * search over the whole set.
  767. * * The set is the one we're currently inserting into; keeping a full
  768. * auxiliary search tree up to date would be too expensive, so we
  769. * use a much simpler lookup table to do a binary search -
  770. * bset_search_write_set().
  771. * * Or we use the auxiliary search tree we constructed earlier -
  772. * bset_search_tree()
  773. */
  774. if (unlikely(!t->size)) {
  775. i.l = t->data->start;
  776. i.r = bset_bkey_last(t->data);
  777. } else if (bset_written(b, t)) {
  778. /*
  779. * Each node in the auxiliary search tree covers a certain range
  780. * of bits, and keys above and below the set it covers might
  781. * differ outside those bits - so we have to special case the
  782. * start and end - handle that here:
  783. */
  784. if (unlikely(bkey_cmp(search, &t->end) >= 0))
  785. return bset_bkey_last(t->data);
  786. if (unlikely(bkey_cmp(search, t->data->start) < 0))
  787. return t->data->start;
  788. i = bset_search_tree(t, search);
  789. } else {
  790. BUG_ON(!b->nsets &&
  791. t->size < bkey_to_cacheline(t, bset_bkey_last(t->data)));
  792. i = bset_search_write_set(t, search);
  793. }
  794. if (btree_keys_expensive_checks(b)) {
  795. BUG_ON(bset_written(b, t) &&
  796. i.l != t->data->start &&
  797. bkey_cmp(tree_to_prev_bkey(t,
  798. inorder_to_tree(bkey_to_cacheline(t, i.l), t)),
  799. search) > 0);
  800. BUG_ON(i.r != bset_bkey_last(t->data) &&
  801. bkey_cmp(i.r, search) <= 0);
  802. }
  803. while (likely(i.l != i.r) &&
  804. bkey_cmp(i.l, search) <= 0)
  805. i.l = bkey_next(i.l);
  806. return i.l;
  807. }
  808. EXPORT_SYMBOL(__bch_bset_search);
  809. /* Btree iterator */
  810. typedef bool (btree_iter_cmp_fn)(struct btree_iter_set,
  811. struct btree_iter_set);
  812. static inline bool btree_iter_cmp(struct btree_iter_set l,
  813. struct btree_iter_set r)
  814. {
  815. return bkey_cmp(l.k, r.k) > 0;
  816. }
  817. static inline bool btree_iter_end(struct btree_iter *iter)
  818. {
  819. return !iter->used;
  820. }
  821. void bch_btree_iter_push(struct btree_iter *iter, struct bkey *k,
  822. struct bkey *end)
  823. {
  824. if (k != end)
  825. BUG_ON(!heap_add(iter,
  826. ((struct btree_iter_set) { k, end }),
  827. btree_iter_cmp));
  828. }
  829. static struct bkey *__bch_btree_iter_init(struct btree_keys *b,
  830. struct btree_iter *iter,
  831. struct bkey *search,
  832. struct bset_tree *start)
  833. {
  834. struct bkey *ret = NULL;
  835. iter->size = ARRAY_SIZE(iter->data);
  836. iter->used = 0;
  837. #ifdef CONFIG_BCACHE_DEBUG
  838. iter->b = b;
  839. #endif
  840. for (; start <= bset_tree_last(b); start++) {
  841. ret = bch_bset_search(b, start, search);
  842. bch_btree_iter_push(iter, ret, bset_bkey_last(start->data));
  843. }
  844. return ret;
  845. }
  846. struct bkey *bch_btree_iter_init(struct btree_keys *b,
  847. struct btree_iter *iter,
  848. struct bkey *search)
  849. {
  850. return __bch_btree_iter_init(b, iter, search, b->set);
  851. }
  852. EXPORT_SYMBOL(bch_btree_iter_init);
  853. static inline struct bkey *__bch_btree_iter_next(struct btree_iter *iter,
  854. btree_iter_cmp_fn *cmp)
  855. {
  856. struct btree_iter_set unused;
  857. struct bkey *ret = NULL;
  858. if (!btree_iter_end(iter)) {
  859. bch_btree_iter_next_check(iter);
  860. ret = iter->data->k;
  861. iter->data->k = bkey_next(iter->data->k);
  862. if (iter->data->k > iter->data->end) {
  863. WARN_ONCE(1, "bset was corrupt!\n");
  864. iter->data->k = iter->data->end;
  865. }
  866. if (iter->data->k == iter->data->end)
  867. heap_pop(iter, unused, cmp);
  868. else
  869. heap_sift(iter, 0, cmp);
  870. }
  871. return ret;
  872. }
  873. struct bkey *bch_btree_iter_next(struct btree_iter *iter)
  874. {
  875. return __bch_btree_iter_next(iter, btree_iter_cmp);
  876. }
  877. EXPORT_SYMBOL(bch_btree_iter_next);
  878. struct bkey *bch_btree_iter_next_filter(struct btree_iter *iter,
  879. struct btree_keys *b, ptr_filter_fn fn)
  880. {
  881. struct bkey *ret;
  882. do {
  883. ret = bch_btree_iter_next(iter);
  884. } while (ret && fn(b, ret));
  885. return ret;
  886. }
  887. /* Mergesort */
  888. void bch_bset_sort_state_free(struct bset_sort_state *state)
  889. {
  890. if (state->pool)
  891. mempool_destroy(state->pool);
  892. }
  893. int bch_bset_sort_state_init(struct bset_sort_state *state, unsigned page_order)
  894. {
  895. spin_lock_init(&state->time.lock);
  896. state->page_order = page_order;
  897. state->crit_factor = int_sqrt(1 << page_order);
  898. state->pool = mempool_create_page_pool(1, page_order);
  899. if (!state->pool)
  900. return -ENOMEM;
  901. return 0;
  902. }
  903. EXPORT_SYMBOL(bch_bset_sort_state_init);
  904. static void btree_mergesort(struct btree_keys *b, struct bset *out,
  905. struct btree_iter *iter,
  906. bool fixup, bool remove_stale)
  907. {
  908. int i;
  909. struct bkey *k, *last = NULL;
  910. BKEY_PADDED(k) tmp;
  911. bool (*bad)(struct btree_keys *, const struct bkey *) = remove_stale
  912. ? bch_ptr_bad
  913. : bch_ptr_invalid;
  914. /* Heapify the iterator, using our comparison function */
  915. for (i = iter->used / 2 - 1; i >= 0; --i)
  916. heap_sift(iter, i, b->ops->sort_cmp);
  917. while (!btree_iter_end(iter)) {
  918. if (b->ops->sort_fixup && fixup)
  919. k = b->ops->sort_fixup(iter, &tmp.k);
  920. else
  921. k = NULL;
  922. if (!k)
  923. k = __bch_btree_iter_next(iter, b->ops->sort_cmp);
  924. if (bad(b, k))
  925. continue;
  926. if (!last) {
  927. last = out->start;
  928. bkey_copy(last, k);
  929. } else if (!bch_bkey_try_merge(b, last, k)) {
  930. last = bkey_next(last);
  931. bkey_copy(last, k);
  932. }
  933. }
  934. out->keys = last ? (uint64_t *) bkey_next(last) - out->d : 0;
  935. pr_debug("sorted %i keys", out->keys);
  936. }
  937. static void __btree_sort(struct btree_keys *b, struct btree_iter *iter,
  938. unsigned start, unsigned order, bool fixup,
  939. struct bset_sort_state *state)
  940. {
  941. uint64_t start_time;
  942. bool used_mempool = false;
  943. struct bset *out = (void *) __get_free_pages(__GFP_NOWARN|GFP_NOWAIT,
  944. order);
  945. if (!out) {
  946. struct page *outp;
  947. BUG_ON(order > state->page_order);
  948. outp = mempool_alloc(state->pool, GFP_NOIO);
  949. out = page_address(outp);
  950. used_mempool = true;
  951. order = state->page_order;
  952. }
  953. start_time = local_clock();
  954. btree_mergesort(b, out, iter, fixup, false);
  955. b->nsets = start;
  956. if (!start && order == b->page_order) {
  957. /*
  958. * Our temporary buffer is the same size as the btree node's
  959. * buffer, we can just swap buffers instead of doing a big
  960. * memcpy()
  961. */
  962. out->magic = b->set->data->magic;
  963. out->seq = b->set->data->seq;
  964. out->version = b->set->data->version;
  965. swap(out, b->set->data);
  966. } else {
  967. b->set[start].data->keys = out->keys;
  968. memcpy(b->set[start].data->start, out->start,
  969. (void *) bset_bkey_last(out) - (void *) out->start);
  970. }
  971. if (used_mempool)
  972. mempool_free(virt_to_page(out), state->pool);
  973. else
  974. free_pages((unsigned long) out, order);
  975. bch_bset_build_written_tree(b);
  976. if (!start)
  977. bch_time_stats_update(&state->time, start_time);
  978. }
  979. void bch_btree_sort_partial(struct btree_keys *b, unsigned start,
  980. struct bset_sort_state *state)
  981. {
  982. size_t order = b->page_order, keys = 0;
  983. struct btree_iter iter;
  984. int oldsize = bch_count_data(b);
  985. __bch_btree_iter_init(b, &iter, NULL, &b->set[start]);
  986. if (start) {
  987. unsigned i;
  988. for (i = start; i <= b->nsets; i++)
  989. keys += b->set[i].data->keys;
  990. order = get_order(__set_bytes(b->set->data, keys));
  991. }
  992. __btree_sort(b, &iter, start, order, false, state);
  993. EBUG_ON(oldsize >= 0 && bch_count_data(b) != oldsize);
  994. }
  995. EXPORT_SYMBOL(bch_btree_sort_partial);
  996. void bch_btree_sort_and_fix_extents(struct btree_keys *b,
  997. struct btree_iter *iter,
  998. struct bset_sort_state *state)
  999. {
  1000. __btree_sort(b, iter, 0, b->page_order, true, state);
  1001. }
  1002. void bch_btree_sort_into(struct btree_keys *b, struct btree_keys *new,
  1003. struct bset_sort_state *state)
  1004. {
  1005. uint64_t start_time = local_clock();
  1006. struct btree_iter iter;
  1007. bch_btree_iter_init(b, &iter, NULL);
  1008. btree_mergesort(b, new->set->data, &iter, false, true);
  1009. bch_time_stats_update(&state->time, start_time);
  1010. new->set->size = 0; // XXX: why?
  1011. }
  1012. #define SORT_CRIT (4096 / sizeof(uint64_t))
  1013. void bch_btree_sort_lazy(struct btree_keys *b, struct bset_sort_state *state)
  1014. {
  1015. unsigned crit = SORT_CRIT;
  1016. int i;
  1017. /* Don't sort if nothing to do */
  1018. if (!b->nsets)
  1019. goto out;
  1020. for (i = b->nsets - 1; i >= 0; --i) {
  1021. crit *= state->crit_factor;
  1022. if (b->set[i].data->keys < crit) {
  1023. bch_btree_sort_partial(b, i, state);
  1024. return;
  1025. }
  1026. }
  1027. /* Sort if we'd overflow */
  1028. if (b->nsets + 1 == MAX_BSETS) {
  1029. bch_btree_sort(b, state);
  1030. return;
  1031. }
  1032. out:
  1033. bch_bset_build_written_tree(b);
  1034. }
  1035. EXPORT_SYMBOL(bch_btree_sort_lazy);
  1036. void bch_btree_keys_stats(struct btree_keys *b, struct bset_stats *stats)
  1037. {
  1038. unsigned i;
  1039. for (i = 0; i <= b->nsets; i++) {
  1040. struct bset_tree *t = &b->set[i];
  1041. size_t bytes = t->data->keys * sizeof(uint64_t);
  1042. size_t j;
  1043. if (bset_written(b, t)) {
  1044. stats->sets_written++;
  1045. stats->bytes_written += bytes;
  1046. stats->floats += t->size - 1;
  1047. for (j = 1; j < t->size; j++)
  1048. if (t->tree[j].exponent == 127)
  1049. stats->failed++;
  1050. } else {
  1051. stats->sets_unwritten++;
  1052. stats->bytes_unwritten += bytes;
  1053. }
  1054. }
  1055. }