/* SPDX-License-Identifier: GPL-2.0 */1#ifndef _BCACHEFS_BSET_H2#define _BCACHEFS_BSET_H34#include <linux/kernel.h>5#include <linux/types.h>67#include "bcachefs.h"8#include "bkey.h"9#include "bkey_methods.h"10#include "btree_types.h"11#include "util.h" /* for time_stats */12#include "vstructs.h"1314/*15* BKEYS:16*17* A bkey contains a key, a size field, a variable number of pointers, and some18* ancillary flag bits.19*20* We use two different functions for validating bkeys, bkey_invalid and21* bkey_deleted().22*23* The one exception to the rule that ptr_invalid() filters out invalid keys is24* that it also filters out keys of size 0 - these are keys that have been25* completely overwritten. It'd be safe to delete these in memory while leaving26* them on disk, just unnecessary work - so we filter them out when resorting27* instead.28*29* We can't filter out stale keys when we're resorting, because garbage30* collection needs to find them to ensure bucket gens don't wrap around -31* unless we're rewriting the btree node those stale keys still exist on disk.32*33* We also implement functions here for removing some number of sectors from the34* front or the back of a bkey - this is mainly used for fixing overlapping35* extents, by removing the overlapping sectors from the older key.36*37* BSETS:38*39* A bset is an array of bkeys laid out contiguously in memory in sorted order,40* along with a header. A btree node is made up of a number of these, written at41* different times.42*43* There could be many of them on disk, but we never allow there to be more than44* 4 in memory - we lazily resort as needed.45*46* We implement code here for creating and maintaining auxiliary search trees47* (described below) for searching an individial bset, and on top of that we48* implement a btree iterator.49*50* BTREE ITERATOR:51*52* Most of the code in bcache doesn't care about an individual bset - it needs53* to search entire btree nodes and iterate over them in sorted order.54*55* The btree iterator code serves both functions; it iterates through the keys56* in a btree node in sorted order, starting from either keys after a specific57* point (if you pass it a search key) or the start of the btree node.58*59* AUXILIARY SEARCH TREES:60*61* Since keys are variable length, we can't use a binary search on a bset - we62* wouldn't be able to find the start of the next key. But binary searches are63* slow anyways, due to terrible cache behaviour; bcache originally used binary64* searches and that code topped out at under 50k lookups/second.65*66* So we need to construct some sort of lookup table. Since we only insert keys67* into the last (unwritten) set, most of the keys within a given btree node are68* usually in sets that are mostly constant. We use two different types of69* lookup tables to take advantage of this.70*71* Both lookup tables share in common that they don't index every key in the72* set; they index one key every BSET_CACHELINE bytes, and then a linear search73* is used for the rest.74*75* For sets that have been written to disk and are no longer being inserted76* into, we construct a binary search tree in an array - traversing a binary77* search tree in an array gives excellent locality of reference and is very78* fast, since both children of any node are adjacent to each other in memory79* (and their grandchildren, and great grandchildren...) - this means80* prefetching can be used to great effect.81*82* It's quite useful performance wise to keep these nodes small - not just83* because they're more likely to be in L2, but also because we can prefetch84* more nodes on a single cacheline and thus prefetch more iterations in advance85* when traversing this tree.86*87* Nodes in the auxiliary search tree must contain both a key to compare against88* (we don't want to fetch the key from the set, that would defeat the purpose),89* and a pointer to the key. We use a few tricks to compress both of these.90*91* To compress the pointer, we take advantage of the fact that one node in the92* search tree corresponds to precisely BSET_CACHELINE bytes in the set. We have93* a function (to_inorder()) that takes the index of a node in a binary tree and94* returns what its index would be in an inorder traversal, so we only have to95* store the low bits of the offset.96*97* The key is 84 bits (KEY_DEV + key->key, the offset on the device). To98* compress that, we take advantage of the fact that when we're traversing the99* search tree at every iteration we know that both our search key and the key100* we're looking for lie within some range - bounded by our previous101* comparisons. (We special case the start of a search so that this is true even102* at the root of the tree).103*104* So we know the key we're looking for is between a and b, and a and b don't105* differ higher than bit 50, we don't need to check anything higher than bit106* 50.107*108* We don't usually need the rest of the bits, either; we only need enough bits109* to partition the key range we're currently checking. Consider key n - the110* key our auxiliary search tree node corresponds to, and key p, the key111* immediately preceding n. The lowest bit we need to store in the auxiliary112* search tree is the highest bit that differs between n and p.113*114* Note that this could be bit 0 - we might sometimes need all 80 bits to do the115* comparison. But we'd really like our nodes in the auxiliary search tree to be116* of fixed size.117*118* The solution is to make them fixed size, and when we're constructing a node119* check if p and n differed in the bits we needed them to. If they don't we120* flag that node, and when doing lookups we fallback to comparing against the121* real key. As long as this doesn't happen to often (and it seems to reliably122* happen a bit less than 1% of the time), we win - even on failures, that key123* is then more likely to be in cache than if we were doing binary searches all124* the way, since we're touching so much less memory.125*126* The keys in the auxiliary search tree are stored in (software) floating127* point, with an exponent and a mantissa. The exponent needs to be big enough128* to address all the bits in the original key, but the number of bits in the129* mantissa is somewhat arbitrary; more bits just gets us fewer failures.130*131* We need 7 bits for the exponent and 3 bits for the key's offset (since keys132* are 8 byte aligned); using 22 bits for the mantissa means a node is 4 bytes.133* We need one node per 128 bytes in the btree node, which means the auxiliary134* search trees take up 3% as much memory as the btree itself.135*136* Constructing these auxiliary search trees is moderately expensive, and we137* don't want to be constantly rebuilding the search tree for the last set138* whenever we insert another key into it. For the unwritten set, we use a much139* simpler lookup table - it's just a flat array, so index i in the lookup table140* corresponds to the i range of BSET_CACHELINE bytes in the set. Indexing141* within each byte range works the same as with the auxiliary search trees.142*143* These are much easier to keep up to date when we insert a key - we do it144* somewhat lazily; when we shift a key up we usually just increment the pointer145* to it, only when it would overflow do we go to the trouble of finding the146* first key in that range of bytes again.147*/148149enum bset_aux_tree_type {150BSET_NO_AUX_TREE,151BSET_RO_AUX_TREE,152BSET_RW_AUX_TREE,153};154155#define BSET_TREE_NR_TYPES 3156157#define BSET_NO_AUX_TREE_VAL (U16_MAX)158#define BSET_RW_AUX_TREE_VAL (U16_MAX - 1)159160static inline enum bset_aux_tree_type bset_aux_tree_type(const struct bset_tree *t)161{162switch (t->extra) {163case BSET_NO_AUX_TREE_VAL:164EBUG_ON(t->size);165return BSET_NO_AUX_TREE;166case BSET_RW_AUX_TREE_VAL:167EBUG_ON(!t->size);168return BSET_RW_AUX_TREE;169default:170EBUG_ON(!t->size);171return BSET_RO_AUX_TREE;172}173}174175/*176* BSET_CACHELINE was originally intended to match the hardware cacheline size -177* it used to be 64, but I realized the lookup code would touch slightly less178* memory if it was 128.179*180* It definites the number of bytes (in struct bset) per struct bkey_float in181* the auxiliar search tree - when we're done searching the bset_float tree we182* have this many bytes left that we do a linear search over.183*184* Since (after level 5) every level of the bset_tree is on a new cacheline,185* we're touching one fewer cacheline in the bset tree in exchange for one more186* cacheline in the linear search - but the linear search might stop before it187* gets to the second cacheline.188*/189190#define BSET_CACHELINE 256191192static inline size_t btree_keys_cachelines(const struct btree *b)193{194return (1U << b->byte_order) / BSET_CACHELINE;195}196197static inline size_t btree_aux_data_bytes(const struct btree *b)198{199return btree_keys_cachelines(b) * 8;200}201202static inline size_t btree_aux_data_u64s(const struct btree *b)203{204return btree_aux_data_bytes(b) / sizeof(u64);205}206207#define for_each_bset(_b, _t) \208for (struct bset_tree *_t = (_b)->set; _t < (_b)->set + (_b)->nsets; _t++)209210#define for_each_bset_c(_b, _t) \211for (const struct bset_tree *_t = (_b)->set; _t < (_b)->set + (_b)->nsets; _t++)212213#define bset_tree_for_each_key(_b, _t, _k) \214for (_k = btree_bkey_first(_b, _t); \215_k != btree_bkey_last(_b, _t); \216_k = bkey_p_next(_k))217218static inline bool bset_has_ro_aux_tree(const struct bset_tree *t)219{220return bset_aux_tree_type(t) == BSET_RO_AUX_TREE;221}222223static inline bool bset_has_rw_aux_tree(struct bset_tree *t)224{225return bset_aux_tree_type(t) == BSET_RW_AUX_TREE;226}227228static inline void bch2_bset_set_no_aux_tree(struct btree *b,229struct bset_tree *t)230{231BUG_ON(t < b->set);232233for (; t < b->set + ARRAY_SIZE(b->set); t++) {234t->size = 0;235t->extra = BSET_NO_AUX_TREE_VAL;236t->aux_data_offset = U16_MAX;237}238}239240static inline void btree_node_set_format(struct btree *b,241struct bkey_format f)242{243int len;244245b->format = f;246b->nr_key_bits = bkey_format_key_bits(&f);247248len = bch2_compile_bkey_format(&b->format, b->aux_data);249BUG_ON(len < 0 || len > U8_MAX);250251b->unpack_fn_len = len;252253bch2_bset_set_no_aux_tree(b, b->set);254}255256static inline struct bset *bset_next_set(struct btree *b,257unsigned block_bytes)258{259struct bset *i = btree_bset_last(b);260261EBUG_ON(!is_power_of_2(block_bytes));262263return ((void *) i) + round_up(vstruct_bytes(i), block_bytes);264}265266void bch2_btree_keys_init(struct btree *);267268void bch2_bset_init_first(struct btree *, struct bset *);269void bch2_bset_init_next(struct btree *, struct btree_node_entry *);270void bch2_bset_build_aux_tree(struct btree *, struct bset_tree *, bool);271272void bch2_bset_insert(struct btree *, struct bkey_packed *, struct bkey_i *,273unsigned);274void bch2_bset_delete(struct btree *, struct bkey_packed *, unsigned);275276/* Bkey utility code */277278/* packed or unpacked */279static inline int bkey_cmp_p_or_unp(const struct btree *b,280const struct bkey_packed *l,281const struct bkey_packed *r_packed,282const struct bpos *r)283{284EBUG_ON(r_packed && !bkey_packed(r_packed));285286if (unlikely(!bkey_packed(l)))287return bpos_cmp(packed_to_bkey_c(l)->p, *r);288289if (likely(r_packed))290return __bch2_bkey_cmp_packed_format_checked(l, r_packed, b);291292return __bch2_bkey_cmp_left_packed_format_checked(b, l, r);293}294295static inline struct bset_tree *296bch2_bkey_to_bset_inlined(struct btree *b, struct bkey_packed *k)297{298unsigned offset = __btree_node_key_to_offset(b, k);299300for_each_bset(b, t)301if (offset <= t->end_offset) {302EBUG_ON(offset < btree_bkey_first_offset(t));303return t;304}305306BUG();307}308309struct bset_tree *bch2_bkey_to_bset(struct btree *, struct bkey_packed *);310311struct bkey_packed *bch2_bkey_prev_filter(struct btree *, struct bset_tree *,312struct bkey_packed *, unsigned);313314static inline struct bkey_packed *315bch2_bkey_prev_all(struct btree *b, struct bset_tree *t, struct bkey_packed *k)316{317return bch2_bkey_prev_filter(b, t, k, 0);318}319320static inline struct bkey_packed *321bch2_bkey_prev(struct btree *b, struct bset_tree *t, struct bkey_packed *k)322{323return bch2_bkey_prev_filter(b, t, k, 1);324}325326/* Btree key iteration */327328void bch2_btree_node_iter_push(struct btree_node_iter *, struct btree *,329const struct bkey_packed *,330const struct bkey_packed *);331void bch2_btree_node_iter_init(struct btree_node_iter *, struct btree *,332struct bpos *);333void bch2_btree_node_iter_init_from_start(struct btree_node_iter *,334struct btree *);335struct bkey_packed *bch2_btree_node_iter_bset_pos(struct btree_node_iter *,336struct btree *,337struct bset_tree *);338339void bch2_btree_node_iter_sort(struct btree_node_iter *, struct btree *);340void bch2_btree_node_iter_set_drop(struct btree_node_iter *,341struct btree_node_iter_set *);342void bch2_btree_node_iter_advance(struct btree_node_iter *, struct btree *);343344#define btree_node_iter_for_each(_iter, _set) \345for (_set = (_iter)->data; \346_set < (_iter)->data + ARRAY_SIZE((_iter)->data) && \347(_set)->k != (_set)->end; \348_set++)349350static inline bool __btree_node_iter_set_end(struct btree_node_iter *iter,351unsigned i)352{353return iter->data[i].k == iter->data[i].end;354}355356static inline bool bch2_btree_node_iter_end(struct btree_node_iter *iter)357{358return __btree_node_iter_set_end(iter, 0);359}360361/*362* When keys compare equal, deleted keys compare first:363*364* XXX: only need to compare pointers for keys that are both within a365* btree_node_iterator - we need to break ties for prev() to work correctly366*/367static inline int bkey_iter_cmp(const struct btree *b,368const struct bkey_packed *l,369const struct bkey_packed *r)370{371return bch2_bkey_cmp_packed(b, l, r)372?: (int) bkey_deleted(r) - (int) bkey_deleted(l)373?: cmp_int(l, r);374}375376static inline int btree_node_iter_cmp(const struct btree *b,377struct btree_node_iter_set l,378struct btree_node_iter_set r)379{380return bkey_iter_cmp(b,381__btree_node_offset_to_key(b, l.k),382__btree_node_offset_to_key(b, r.k));383}384385/* These assume r (the search key) is not a deleted key: */386static inline int bkey_iter_pos_cmp(const struct btree *b,387const struct bkey_packed *l,388const struct bpos *r)389{390return bkey_cmp_left_packed(b, l, r)391?: -((int) bkey_deleted(l));392}393394static inline int bkey_iter_cmp_p_or_unp(const struct btree *b,395const struct bkey_packed *l,396const struct bkey_packed *r_packed,397const struct bpos *r)398{399return bkey_cmp_p_or_unp(b, l, r_packed, r)400?: -((int) bkey_deleted(l));401}402403static inline struct bkey_packed *404__bch2_btree_node_iter_peek_all(struct btree_node_iter *iter,405struct btree *b)406{407return __btree_node_offset_to_key(b, iter->data->k);408}409410static inline struct bkey_packed *411bch2_btree_node_iter_peek_all(struct btree_node_iter *iter, struct btree *b)412{413return !bch2_btree_node_iter_end(iter)414? __btree_node_offset_to_key(b, iter->data->k)415: NULL;416}417418static inline struct bkey_packed *419bch2_btree_node_iter_peek(struct btree_node_iter *iter, struct btree *b)420{421struct bkey_packed *k;422423while ((k = bch2_btree_node_iter_peek_all(iter, b)) &&424bkey_deleted(k))425bch2_btree_node_iter_advance(iter, b);426427return k;428}429430static inline struct bkey_packed *431bch2_btree_node_iter_next_all(struct btree_node_iter *iter, struct btree *b)432{433struct bkey_packed *ret = bch2_btree_node_iter_peek_all(iter, b);434435if (ret)436bch2_btree_node_iter_advance(iter, b);437438return ret;439}440441struct bkey_packed *bch2_btree_node_iter_prev_all(struct btree_node_iter *,442struct btree *);443struct bkey_packed *bch2_btree_node_iter_prev(struct btree_node_iter *,444struct btree *);445446struct bkey_s_c bch2_btree_node_iter_peek_unpack(struct btree_node_iter *,447struct btree *,448struct bkey *);449450#define for_each_btree_node_key(b, k, iter) \451for (bch2_btree_node_iter_init_from_start((iter), (b)); \452(k = bch2_btree_node_iter_peek((iter), (b))); \453bch2_btree_node_iter_advance(iter, b))454455#define for_each_btree_node_key_unpack(b, k, iter, unpacked) \456for (bch2_btree_node_iter_init_from_start((iter), (b)); \457(k = bch2_btree_node_iter_peek_unpack((iter), (b), (unpacked))).k;\458bch2_btree_node_iter_advance(iter, b))459460/* Accounting: */461462struct btree_nr_keys bch2_btree_node_count_keys(struct btree *);463464static inline void btree_keys_account_key(struct btree_nr_keys *n,465unsigned bset,466struct bkey_packed *k,467int sign)468{469n->live_u64s += k->u64s * sign;470n->bset_u64s[bset] += k->u64s * sign;471472if (bkey_packed(k))473n->packed_keys += sign;474else475n->unpacked_keys += sign;476}477478static inline void btree_keys_account_val_delta(struct btree *b,479struct bkey_packed *k,480int delta)481{482struct bset_tree *t = bch2_bkey_to_bset(b, k);483484b->nr.live_u64s += delta;485b->nr.bset_u64s[t - b->set] += delta;486}487488#define btree_keys_account_key_add(_nr, _bset_idx, _k) \489btree_keys_account_key(_nr, _bset_idx, _k, 1)490#define btree_keys_account_key_drop(_nr, _bset_idx, _k) \491btree_keys_account_key(_nr, _bset_idx, _k, -1)492493#define btree_account_key_add(_b, _k) \494btree_keys_account_key(&(_b)->nr, \495bch2_bkey_to_bset(_b, _k) - (_b)->set, _k, 1)496#define btree_account_key_drop(_b, _k) \497btree_keys_account_key(&(_b)->nr, \498bch2_bkey_to_bset(_b, _k) - (_b)->set, _k, -1)499500struct bset_stats {501struct {502size_t nr, bytes;503} sets[BSET_TREE_NR_TYPES];504505size_t floats;506size_t failed;507};508509void bch2_btree_keys_stats(const struct btree *, struct bset_stats *);510void bch2_bfloat_to_text(struct printbuf *, struct btree *,511struct bkey_packed *);512513/* Debug stuff */514515void bch2_dump_bset(struct bch_fs *, struct btree *, struct bset *, unsigned);516void bch2_dump_btree_node(struct bch_fs *, struct btree *);517void bch2_dump_btree_node_iter(struct btree *, struct btree_node_iter *);518519void __bch2_verify_btree_nr_keys(struct btree *);520void __bch2_btree_node_iter_verify(struct btree_node_iter *, struct btree *);521522static inline void bch2_btree_node_iter_verify(struct btree_node_iter *iter,523struct btree *b)524{525if (static_branch_unlikely(&bch2_debug_check_bset_lookups))526__bch2_btree_node_iter_verify(iter, b);527}528529static inline void bch2_verify_btree_nr_keys(struct btree *b)530{531if (static_branch_unlikely(&bch2_debug_check_btree_accounting))532__bch2_verify_btree_nr_keys(b);533}534535#endif /* _BCACHEFS_BSET_H */536537538