bset.c 30 KB

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