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