bcachefs: Allocation code refactoring
[linux-block.git] / fs / bcachefs / btree_types.h
1 /* SPDX-License-Identifier: GPL-2.0 */
2 #ifndef _BCACHEFS_BTREE_TYPES_H
3 #define _BCACHEFS_BTREE_TYPES_H
4
5 #include <linux/list.h>
6 #include <linux/rhashtable.h>
7
8 #include "bkey_methods.h"
9 #include "journal_types.h"
10 #include "six.h"
11
12 struct open_bucket;
13 struct btree_update;
14
15 #define MAX_BSETS               3U
16
17 struct btree_nr_keys {
18
19         /*
20          * Amount of live metadata (i.e. size of node after a compaction) in
21          * units of u64s
22          */
23         u16                     live_u64s;
24         u16                     bset_u64s[MAX_BSETS];
25
26         /* live keys only: */
27         u16                     packed_keys;
28         u16                     unpacked_keys;
29 };
30
31 struct bset_tree {
32         /*
33          * We construct a binary tree in an array as if the array
34          * started at 1, so that things line up on the same cachelines
35          * better: see comments in bset.c at cacheline_to_bkey() for
36          * details
37          */
38
39         /* size of the binary tree and prev array */
40         u16                     size;
41
42         /* function of size - precalculated for to_inorder() */
43         u16                     extra;
44
45         u16                     data_offset;
46         u16                     aux_data_offset;
47         u16                     end_offset;
48
49         struct bpos             max_key;
50 };
51
52 struct btree_write {
53         struct journal_entry_pin        journal;
54         struct closure_waitlist         wait;
55 };
56
57 struct btree_alloc {
58         struct open_buckets     ob;
59         BKEY_PADDED(k);
60 };
61
62 struct btree {
63         /* Hottest entries first */
64         struct rhash_head       hash;
65
66         /* Key/pointer for this btree node */
67         __BKEY_PADDED(key, BKEY_BTREE_PTR_VAL_U64s_MAX);
68
69         struct six_lock         lock;
70
71         unsigned long           flags;
72         u16                     written;
73         u8                      level;
74         u8                      btree_id;
75         u8                      nsets;
76         u8                      nr_key_bits;
77
78         struct bkey_format      format;
79
80         struct btree_node       *data;
81         void                    *aux_data;
82
83         /*
84          * Sets of sorted keys - the real btree node - plus a binary search tree
85          *
86          * set[0] is special; set[0]->tree, set[0]->prev and set[0]->data point
87          * to the memory we have allocated for this btree node. Additionally,
88          * set[0]->data points to the entire btree node as it exists on disk.
89          */
90         struct bset_tree        set[MAX_BSETS];
91
92         struct btree_nr_keys    nr;
93         u16                     sib_u64s[2];
94         u16                     whiteout_u64s;
95         u16                     uncompacted_whiteout_u64s;
96         u8                      page_order;
97         u8                      unpack_fn_len;
98
99         /*
100          * XXX: add a delete sequence number, so when bch2_btree_node_relock()
101          * fails because the lock sequence number has changed - i.e. the
102          * contents were modified - we can still relock the node if it's still
103          * the one we want, without redoing the traversal
104          */
105
106         /*
107          * For asynchronous splits/interior node updates:
108          * When we do a split, we allocate new child nodes and update the parent
109          * node to point to them: we update the parent in memory immediately,
110          * but then we must wait until the children have been written out before
111          * the update to the parent can be written - this is a list of the
112          * btree_updates that are blocking this node from being
113          * written:
114          */
115         struct list_head        write_blocked;
116
117         /*
118          * Also for asynchronous splits/interior node updates:
119          * If a btree node isn't reachable yet, we don't want to kick off
120          * another write - because that write also won't yet be reachable and
121          * marking it as completed before it's reachable would be incorrect:
122          */
123         unsigned long           will_make_reachable;
124
125         struct open_buckets     ob;
126
127         /* lru list */
128         struct list_head        list;
129
130         struct btree_write      writes[2];
131
132 #ifdef CONFIG_BCACHEFS_DEBUG
133         bool                    *expensive_debug_checks;
134 #endif
135 };
136
137 struct btree_cache {
138         struct rhashtable       table;
139         bool                    table_init_done;
140         /*
141          * We never free a struct btree, except on shutdown - we just put it on
142          * the btree_cache_freed list and reuse it later. This simplifies the
143          * code, and it doesn't cost us much memory as the memory usage is
144          * dominated by buffers that hold the actual btree node data and those
145          * can be freed - and the number of struct btrees allocated is
146          * effectively bounded.
147          *
148          * btree_cache_freeable effectively is a small cache - we use it because
149          * high order page allocations can be rather expensive, and it's quite
150          * common to delete and allocate btree nodes in quick succession. It
151          * should never grow past ~2-3 nodes in practice.
152          */
153         struct mutex            lock;
154         struct list_head        live;
155         struct list_head        freeable;
156         struct list_head        freed;
157
158         /* Number of elements in live + freeable lists */
159         unsigned                used;
160         unsigned                reserve;
161         struct shrinker         shrink;
162
163         /*
164          * If we need to allocate memory for a new btree node and that
165          * allocation fails, we can cannibalize another node in the btree cache
166          * to satisfy the allocation - lock to guarantee only one thread does
167          * this at a time:
168          */
169         struct task_struct      *alloc_lock;
170         struct closure_waitlist alloc_wait;
171 };
172
173 struct btree_node_iter {
174         struct btree_node_iter_set {
175                 u16     k, end;
176         } data[MAX_BSETS];
177 };
178
179 enum btree_iter_type {
180         BTREE_ITER_KEYS,
181         BTREE_ITER_SLOTS,
182         BTREE_ITER_NODES,
183 };
184
185 #define BTREE_ITER_TYPE                 ((1 << 2) - 1)
186
187 #define BTREE_ITER_INTENT               (1 << 2)
188 #define BTREE_ITER_PREFETCH             (1 << 3)
189 /*
190  * Used in bch2_btree_iter_traverse(), to indicate whether we're searching for
191  * @pos or the first key strictly greater than @pos
192  */
193 #define BTREE_ITER_IS_EXTENTS           (1 << 4)
194 #define BTREE_ITER_ERROR                (1 << 5)
195
196 enum btree_iter_uptodate {
197         BTREE_ITER_UPTODATE             = 0,
198         BTREE_ITER_NEED_PEEK            = 1,
199         BTREE_ITER_NEED_RELOCK          = 2,
200         BTREE_ITER_NEED_TRAVERSE        = 3,
201 };
202
203 /*
204  * @pos                 - iterator's current position
205  * @level               - current btree depth
206  * @locks_want          - btree level below which we start taking intent locks
207  * @nodes_locked        - bitmask indicating which nodes in @nodes are locked
208  * @nodes_intent_locked - bitmask indicating which locks are intent locks
209  */
210 struct btree_iter {
211         struct bch_fs           *c;
212         struct bpos             pos;
213
214         u8                      flags;
215         enum btree_iter_uptodate uptodate:4;
216         enum btree_id           btree_id:4;
217         unsigned                level:4,
218                                 locks_want:4,
219                                 nodes_locked:4,
220                                 nodes_intent_locked:4;
221
222         struct btree_iter_level {
223                 struct btree    *b;
224                 struct btree_node_iter iter;
225                 u32             lock_seq;
226         }                       l[BTREE_MAX_DEPTH];
227
228         /*
229          * Current unpacked key - so that bch2_btree_iter_next()/
230          * bch2_btree_iter_next_slot() can correctly advance pos.
231          */
232         struct bkey             k;
233
234         /*
235          * Circular linked list of linked iterators: linked iterators share
236          * locks (e.g. two linked iterators may have the same node intent
237          * locked, or read and write locked, at the same time), and insertions
238          * through one iterator won't invalidate the other linked iterators.
239          */
240
241         /* Must come last: */
242         struct btree_iter       *next;
243 };
244
245 #define BTREE_ITER_MAX          8
246
247 struct btree_insert_entry {
248         struct btree_iter *iter;
249         struct bkey_i   *k;
250 };
251
252 struct btree_trans {
253         struct bch_fs           *c;
254         size_t                  nr_restarts;
255
256         u8                      nr_iters;
257         u8                      iters_live;
258         u8                      iters_linked;
259         u8                      nr_updates;
260
261         unsigned                mem_top;
262         unsigned                mem_bytes;
263         void                    *mem;
264
265         struct btree_iter       *iters;
266         u64                     iter_ids[BTREE_ITER_MAX];
267
268         struct btree_insert_entry updates[BTREE_ITER_MAX];
269
270         struct btree_iter       iters_onstack[2];
271 };
272
273 #define BTREE_FLAG(flag)                                                \
274 static inline bool btree_node_ ## flag(struct btree *b)                 \
275 {       return test_bit(BTREE_NODE_ ## flag, &b->flags); }              \
276                                                                         \
277 static inline void set_btree_node_ ## flag(struct btree *b)             \
278 {       set_bit(BTREE_NODE_ ## flag, &b->flags); }                      \
279                                                                         \
280 static inline void clear_btree_node_ ## flag(struct btree *b)           \
281 {       clear_bit(BTREE_NODE_ ## flag, &b->flags); }
282
283 enum btree_flags {
284         BTREE_NODE_read_in_flight,
285         BTREE_NODE_read_error,
286         BTREE_NODE_dirty,
287         BTREE_NODE_need_write,
288         BTREE_NODE_noevict,
289         BTREE_NODE_write_idx,
290         BTREE_NODE_accessed,
291         BTREE_NODE_write_in_flight,
292         BTREE_NODE_just_written,
293         BTREE_NODE_dying,
294         BTREE_NODE_fake,
295 };
296
297 BTREE_FLAG(read_in_flight);
298 BTREE_FLAG(read_error);
299 BTREE_FLAG(dirty);
300 BTREE_FLAG(need_write);
301 BTREE_FLAG(noevict);
302 BTREE_FLAG(write_idx);
303 BTREE_FLAG(accessed);
304 BTREE_FLAG(write_in_flight);
305 BTREE_FLAG(just_written);
306 BTREE_FLAG(dying);
307 BTREE_FLAG(fake);
308
309 static inline struct btree_write *btree_current_write(struct btree *b)
310 {
311         return b->writes + btree_node_write_idx(b);
312 }
313
314 static inline struct btree_write *btree_prev_write(struct btree *b)
315 {
316         return b->writes + (btree_node_write_idx(b) ^ 1);
317 }
318
319 static inline struct bset_tree *bset_tree_last(struct btree *b)
320 {
321         EBUG_ON(!b->nsets);
322         return b->set + b->nsets - 1;
323 }
324
325 static inline void *
326 __btree_node_offset_to_ptr(const struct btree *b, u16 offset)
327 {
328         return (void *) ((u64 *) b->data + 1 + offset);
329 }
330
331 static inline u16
332 __btree_node_ptr_to_offset(const struct btree *b, const void *p)
333 {
334         u16 ret = (u64 *) p - 1 - (u64 *) b->data;
335
336         EBUG_ON(__btree_node_offset_to_ptr(b, ret) != p);
337         return ret;
338 }
339
340 static inline struct bset *bset(const struct btree *b,
341                                 const struct bset_tree *t)
342 {
343         return __btree_node_offset_to_ptr(b, t->data_offset);
344 }
345
346 static inline void set_btree_bset_end(struct btree *b, struct bset_tree *t)
347 {
348         t->end_offset =
349                 __btree_node_ptr_to_offset(b, vstruct_last(bset(b, t)));
350 }
351
352 static inline void set_btree_bset(struct btree *b, struct bset_tree *t,
353                                   const struct bset *i)
354 {
355         t->data_offset = __btree_node_ptr_to_offset(b, i);
356         set_btree_bset_end(b, t);
357 }
358
359 static inline struct bset *btree_bset_first(struct btree *b)
360 {
361         return bset(b, b->set);
362 }
363
364 static inline struct bset *btree_bset_last(struct btree *b)
365 {
366         return bset(b, bset_tree_last(b));
367 }
368
369 static inline u16
370 __btree_node_key_to_offset(const struct btree *b, const struct bkey_packed *k)
371 {
372         return __btree_node_ptr_to_offset(b, k);
373 }
374
375 static inline struct bkey_packed *
376 __btree_node_offset_to_key(const struct btree *b, u16 k)
377 {
378         return __btree_node_offset_to_ptr(b, k);
379 }
380
381 static inline unsigned btree_bkey_first_offset(const struct bset_tree *t)
382 {
383         return t->data_offset + offsetof(struct bset, _data) / sizeof(u64);
384 }
385
386 #define btree_bkey_first(_b, _t)                                        \
387 ({                                                                      \
388         EBUG_ON(bset(_b, _t)->start !=                                  \
389                 __btree_node_offset_to_key(_b, btree_bkey_first_offset(_t)));\
390                                                                         \
391         bset(_b, _t)->start;                                            \
392 })
393
394 #define btree_bkey_last(_b, _t)                                         \
395 ({                                                                      \
396         EBUG_ON(__btree_node_offset_to_key(_b, (_t)->end_offset) !=     \
397                 vstruct_last(bset(_b, _t)));                            \
398                                                                         \
399         __btree_node_offset_to_key(_b, (_t)->end_offset);               \
400 })
401
402 static inline unsigned bset_byte_offset(struct btree *b, void *i)
403 {
404         return i - (void *) b->data;
405 }
406
407 /* Type of keys @b contains: */
408 static inline enum bkey_type btree_node_type(struct btree *b)
409 {
410         return b->level ? BKEY_TYPE_BTREE : b->btree_id;
411 }
412
413 static inline const struct bkey_ops *btree_node_ops(struct btree *b)
414 {
415         return &bch2_bkey_ops[btree_node_type(b)];
416 }
417
418 static inline bool btree_node_has_ptrs(struct btree *b)
419 {
420         return btree_type_has_ptrs(btree_node_type(b));
421 }
422
423 static inline bool btree_node_is_extents(struct btree *b)
424 {
425         return btree_node_type(b) == BKEY_TYPE_EXTENTS;
426 }
427
428 struct btree_root {
429         struct btree            *b;
430
431         struct btree_update     *as;
432
433         /* On disk root - see async splits: */
434         __BKEY_PADDED(key, BKEY_BTREE_PTR_VAL_U64s_MAX);
435         u8                      level;
436         u8                      alive;
437 };
438
439 /*
440  * Optional hook that will be called just prior to a btree node update, when
441  * we're holding the write lock and we know what key is about to be overwritten:
442  */
443
444 enum btree_insert_ret {
445         BTREE_INSERT_OK,
446         /* extent spanned multiple leaf nodes: have to traverse to next node: */
447         BTREE_INSERT_NEED_TRAVERSE,
448         /* write lock held for too long */
449         /* leaf node needs to be split */
450         BTREE_INSERT_BTREE_NODE_FULL,
451         BTREE_INSERT_ENOSPC,
452         BTREE_INSERT_NEED_GC_LOCK,
453 };
454
455 enum btree_gc_coalesce_fail_reason {
456         BTREE_GC_COALESCE_FAIL_RESERVE_GET,
457         BTREE_GC_COALESCE_FAIL_KEYLIST_REALLOC,
458         BTREE_GC_COALESCE_FAIL_FORMAT_FITS,
459 };
460
461 enum btree_node_sibling {
462         btree_prev_sib,
463         btree_next_sib,
464 };
465
466 typedef struct btree_nr_keys (*sort_fix_overlapping_fn)(struct bset *,
467                                                         struct btree *,
468                                                         struct btree_node_iter *);
469
470 #endif /* _BCACHEFS_BTREE_TYPES_H */