xref: /linux/fs/bcachefs/btree_update_interior.c (revision b8e85e6f3a09fc56b0ff574887798962ef8a8f80)
1 // SPDX-License-Identifier: GPL-2.0
2 
3 #include "bcachefs.h"
4 #include "alloc_foreground.h"
5 #include "bkey_methods.h"
6 #include "btree_cache.h"
7 #include "btree_gc.h"
8 #include "btree_journal_iter.h"
9 #include "btree_update.h"
10 #include "btree_update_interior.h"
11 #include "btree_io.h"
12 #include "btree_iter.h"
13 #include "btree_locking.h"
14 #include "buckets.h"
15 #include "clock.h"
16 #include "error.h"
17 #include "extents.h"
18 #include "journal.h"
19 #include "journal_reclaim.h"
20 #include "keylist.h"
21 #include "replicas.h"
22 #include "super-io.h"
23 #include "trace.h"
24 
25 #include <linux/random.h>
26 
27 static int bch2_btree_insert_node(struct btree_update *, struct btree_trans *,
28 				  btree_path_idx_t, struct btree *,
29 				  struct keylist *, unsigned);
30 static void bch2_btree_update_add_new_node(struct btree_update *, struct btree *);
31 
32 static btree_path_idx_t get_unlocked_mut_path(struct btree_trans *trans,
33 					      enum btree_id btree_id,
34 					      unsigned level,
35 					      struct bpos pos)
36 {
37 	btree_path_idx_t path_idx = bch2_path_get(trans, btree_id, pos, level + 1, level,
38 			     BTREE_ITER_NOPRESERVE|
39 			     BTREE_ITER_INTENT, _RET_IP_);
40 	path_idx = bch2_btree_path_make_mut(trans, path_idx, true, _RET_IP_);
41 
42 	struct btree_path *path = trans->paths + path_idx;
43 	bch2_btree_path_downgrade(trans, path);
44 	__bch2_btree_path_unlock(trans, path);
45 	return path_idx;
46 }
47 
48 /* Debug code: */
49 
50 /*
51  * Verify that child nodes correctly span parent node's range:
52  */
53 static void btree_node_interior_verify(struct bch_fs *c, struct btree *b)
54 {
55 #ifdef CONFIG_BCACHEFS_DEBUG
56 	struct bpos next_node = b->data->min_key;
57 	struct btree_node_iter iter;
58 	struct bkey_s_c k;
59 	struct bkey_s_c_btree_ptr_v2 bp;
60 	struct bkey unpacked;
61 	struct printbuf buf1 = PRINTBUF, buf2 = PRINTBUF;
62 
63 	BUG_ON(!b->c.level);
64 
65 	if (!test_bit(JOURNAL_REPLAY_DONE, &c->journal.flags))
66 		return;
67 
68 	bch2_btree_node_iter_init_from_start(&iter, b);
69 
70 	while (1) {
71 		k = bch2_btree_node_iter_peek_unpack(&iter, b, &unpacked);
72 		if (k.k->type != KEY_TYPE_btree_ptr_v2)
73 			break;
74 		bp = bkey_s_c_to_btree_ptr_v2(k);
75 
76 		if (!bpos_eq(next_node, bp.v->min_key)) {
77 			bch2_dump_btree_node(c, b);
78 			bch2_bpos_to_text(&buf1, next_node);
79 			bch2_bpos_to_text(&buf2, bp.v->min_key);
80 			panic("expected next min_key %s got %s\n", buf1.buf, buf2.buf);
81 		}
82 
83 		bch2_btree_node_iter_advance(&iter, b);
84 
85 		if (bch2_btree_node_iter_end(&iter)) {
86 			if (!bpos_eq(k.k->p, b->key.k.p)) {
87 				bch2_dump_btree_node(c, b);
88 				bch2_bpos_to_text(&buf1, b->key.k.p);
89 				bch2_bpos_to_text(&buf2, k.k->p);
90 				panic("expected end %s got %s\n", buf1.buf, buf2.buf);
91 			}
92 			break;
93 		}
94 
95 		next_node = bpos_successor(k.k->p);
96 	}
97 #endif
98 }
99 
100 /* Calculate ideal packed bkey format for new btree nodes: */
101 
102 static void __bch2_btree_calc_format(struct bkey_format_state *s, struct btree *b)
103 {
104 	struct bkey_packed *k;
105 	struct bset_tree *t;
106 	struct bkey uk;
107 
108 	for_each_bset(b, t)
109 		bset_tree_for_each_key(b, t, k)
110 			if (!bkey_deleted(k)) {
111 				uk = bkey_unpack_key(b, k);
112 				bch2_bkey_format_add_key(s, &uk);
113 			}
114 }
115 
116 static struct bkey_format bch2_btree_calc_format(struct btree *b)
117 {
118 	struct bkey_format_state s;
119 
120 	bch2_bkey_format_init(&s);
121 	bch2_bkey_format_add_pos(&s, b->data->min_key);
122 	bch2_bkey_format_add_pos(&s, b->data->max_key);
123 	__bch2_btree_calc_format(&s, b);
124 
125 	return bch2_bkey_format_done(&s);
126 }
127 
128 static size_t btree_node_u64s_with_format(struct btree_nr_keys nr,
129 					  struct bkey_format *old_f,
130 					  struct bkey_format *new_f)
131 {
132 	/* stupid integer promotion rules */
133 	ssize_t delta =
134 	    (((int) new_f->key_u64s - old_f->key_u64s) *
135 	     (int) nr.packed_keys) +
136 	    (((int) new_f->key_u64s - BKEY_U64s) *
137 	     (int) nr.unpacked_keys);
138 
139 	BUG_ON(delta + nr.live_u64s < 0);
140 
141 	return nr.live_u64s + delta;
142 }
143 
144 /**
145  * bch2_btree_node_format_fits - check if we could rewrite node with a new format
146  *
147  * @c:		filesystem handle
148  * @b:		btree node to rewrite
149  * @nr:		number of keys for new node (i.e. b->nr)
150  * @new_f:	bkey format to translate keys to
151  *
152  * Returns: true if all re-packed keys will be able to fit in a new node.
153  *
154  * Assumes all keys will successfully pack with the new format.
155  */
156 static bool bch2_btree_node_format_fits(struct bch_fs *c, struct btree *b,
157 				 struct btree_nr_keys nr,
158 				 struct bkey_format *new_f)
159 {
160 	size_t u64s = btree_node_u64s_with_format(nr, &b->format, new_f);
161 
162 	return __vstruct_bytes(struct btree_node, u64s) < btree_buf_bytes(b);
163 }
164 
165 /* Btree node freeing/allocation: */
166 
167 static void __btree_node_free(struct btree_trans *trans, struct btree *b)
168 {
169 	struct bch_fs *c = trans->c;
170 
171 	trace_and_count(c, btree_node_free, trans, b);
172 
173 	BUG_ON(btree_node_write_blocked(b));
174 	BUG_ON(btree_node_dirty(b));
175 	BUG_ON(btree_node_need_write(b));
176 	BUG_ON(b == btree_node_root(c, b));
177 	BUG_ON(b->ob.nr);
178 	BUG_ON(!list_empty(&b->write_blocked));
179 	BUG_ON(b->will_make_reachable);
180 
181 	clear_btree_node_noevict(b);
182 
183 	mutex_lock(&c->btree_cache.lock);
184 	list_move(&b->list, &c->btree_cache.freeable);
185 	mutex_unlock(&c->btree_cache.lock);
186 }
187 
188 static void bch2_btree_node_free_inmem(struct btree_trans *trans,
189 				       struct btree_path *path,
190 				       struct btree *b)
191 {
192 	struct bch_fs *c = trans->c;
193 	unsigned i, level = b->c.level;
194 
195 	bch2_btree_node_lock_write_nofail(trans, path, &b->c);
196 	bch2_btree_node_hash_remove(&c->btree_cache, b);
197 	__btree_node_free(trans, b);
198 	six_unlock_write(&b->c.lock);
199 	mark_btree_node_locked_noreset(path, level, BTREE_NODE_INTENT_LOCKED);
200 
201 	trans_for_each_path(trans, path, i)
202 		if (path->l[level].b == b) {
203 			btree_node_unlock(trans, path, level);
204 			path->l[level].b = ERR_PTR(-BCH_ERR_no_btree_node_init);
205 		}
206 }
207 
208 static void bch2_btree_node_free_never_used(struct btree_update *as,
209 					    struct btree_trans *trans,
210 					    struct btree *b)
211 {
212 	struct bch_fs *c = as->c;
213 	struct prealloc_nodes *p = &as->prealloc_nodes[b->c.lock.readers != NULL];
214 	struct btree_path *path;
215 	unsigned i, level = b->c.level;
216 
217 	BUG_ON(!list_empty(&b->write_blocked));
218 	BUG_ON(b->will_make_reachable != (1UL|(unsigned long) as));
219 
220 	b->will_make_reachable = 0;
221 	closure_put(&as->cl);
222 
223 	clear_btree_node_will_make_reachable(b);
224 	clear_btree_node_accessed(b);
225 	clear_btree_node_dirty_acct(c, b);
226 	clear_btree_node_need_write(b);
227 
228 	mutex_lock(&c->btree_cache.lock);
229 	list_del_init(&b->list);
230 	bch2_btree_node_hash_remove(&c->btree_cache, b);
231 	mutex_unlock(&c->btree_cache.lock);
232 
233 	BUG_ON(p->nr >= ARRAY_SIZE(p->b));
234 	p->b[p->nr++] = b;
235 
236 	six_unlock_intent(&b->c.lock);
237 
238 	trans_for_each_path(trans, path, i)
239 		if (path->l[level].b == b) {
240 			btree_node_unlock(trans, path, level);
241 			path->l[level].b = ERR_PTR(-BCH_ERR_no_btree_node_init);
242 		}
243 }
244 
245 static struct btree *__bch2_btree_node_alloc(struct btree_trans *trans,
246 					     struct disk_reservation *res,
247 					     struct closure *cl,
248 					     bool interior_node,
249 					     unsigned flags)
250 {
251 	struct bch_fs *c = trans->c;
252 	struct write_point *wp;
253 	struct btree *b;
254 	BKEY_PADDED_ONSTACK(k, BKEY_BTREE_PTR_VAL_U64s_MAX) tmp;
255 	struct open_buckets obs = { .nr = 0 };
256 	struct bch_devs_list devs_have = (struct bch_devs_list) { 0 };
257 	enum bch_watermark watermark = flags & BCH_WATERMARK_MASK;
258 	unsigned nr_reserve = watermark > BCH_WATERMARK_reclaim
259 		? BTREE_NODE_RESERVE
260 		: 0;
261 	int ret;
262 
263 	mutex_lock(&c->btree_reserve_cache_lock);
264 	if (c->btree_reserve_cache_nr > nr_reserve) {
265 		struct btree_alloc *a =
266 			&c->btree_reserve_cache[--c->btree_reserve_cache_nr];
267 
268 		obs = a->ob;
269 		bkey_copy(&tmp.k, &a->k);
270 		mutex_unlock(&c->btree_reserve_cache_lock);
271 		goto mem_alloc;
272 	}
273 	mutex_unlock(&c->btree_reserve_cache_lock);
274 
275 retry:
276 	ret = bch2_alloc_sectors_start_trans(trans,
277 				      c->opts.metadata_target ?:
278 				      c->opts.foreground_target,
279 				      0,
280 				      writepoint_ptr(&c->btree_write_point),
281 				      &devs_have,
282 				      res->nr_replicas,
283 				      min(res->nr_replicas,
284 					  c->opts.metadata_replicas_required),
285 				      watermark, 0, cl, &wp);
286 	if (unlikely(ret))
287 		return ERR_PTR(ret);
288 
289 	if (wp->sectors_free < btree_sectors(c)) {
290 		struct open_bucket *ob;
291 		unsigned i;
292 
293 		open_bucket_for_each(c, &wp->ptrs, ob, i)
294 			if (ob->sectors_free < btree_sectors(c))
295 				ob->sectors_free = 0;
296 
297 		bch2_alloc_sectors_done(c, wp);
298 		goto retry;
299 	}
300 
301 	bkey_btree_ptr_v2_init(&tmp.k);
302 	bch2_alloc_sectors_append_ptrs(c, wp, &tmp.k, btree_sectors(c), false);
303 
304 	bch2_open_bucket_get(c, wp, &obs);
305 	bch2_alloc_sectors_done(c, wp);
306 mem_alloc:
307 	b = bch2_btree_node_mem_alloc(trans, interior_node);
308 	six_unlock_write(&b->c.lock);
309 	six_unlock_intent(&b->c.lock);
310 
311 	/* we hold cannibalize_lock: */
312 	BUG_ON(IS_ERR(b));
313 	BUG_ON(b->ob.nr);
314 
315 	bkey_copy(&b->key, &tmp.k);
316 	b->ob = obs;
317 
318 	return b;
319 }
320 
321 static struct btree *bch2_btree_node_alloc(struct btree_update *as,
322 					   struct btree_trans *trans,
323 					   unsigned level)
324 {
325 	struct bch_fs *c = as->c;
326 	struct btree *b;
327 	struct prealloc_nodes *p = &as->prealloc_nodes[!!level];
328 	int ret;
329 
330 	BUG_ON(level >= BTREE_MAX_DEPTH);
331 	BUG_ON(!p->nr);
332 
333 	b = p->b[--p->nr];
334 
335 	btree_node_lock_nopath_nofail(trans, &b->c, SIX_LOCK_intent);
336 	btree_node_lock_nopath_nofail(trans, &b->c, SIX_LOCK_write);
337 
338 	set_btree_node_accessed(b);
339 	set_btree_node_dirty_acct(c, b);
340 	set_btree_node_need_write(b);
341 
342 	bch2_bset_init_first(b, &b->data->keys);
343 	b->c.level	= level;
344 	b->c.btree_id	= as->btree_id;
345 	b->version_ondisk = c->sb.version;
346 
347 	memset(&b->nr, 0, sizeof(b->nr));
348 	b->data->magic = cpu_to_le64(bset_magic(c));
349 	memset(&b->data->_ptr, 0, sizeof(b->data->_ptr));
350 	b->data->flags = 0;
351 	SET_BTREE_NODE_ID(b->data, as->btree_id);
352 	SET_BTREE_NODE_LEVEL(b->data, level);
353 
354 	if (b->key.k.type == KEY_TYPE_btree_ptr_v2) {
355 		struct bkey_i_btree_ptr_v2 *bp = bkey_i_to_btree_ptr_v2(&b->key);
356 
357 		bp->v.mem_ptr		= 0;
358 		bp->v.seq		= b->data->keys.seq;
359 		bp->v.sectors_written	= 0;
360 	}
361 
362 	SET_BTREE_NODE_NEW_EXTENT_OVERWRITE(b->data, true);
363 
364 	bch2_btree_build_aux_trees(b);
365 
366 	ret = bch2_btree_node_hash_insert(&c->btree_cache, b, level, as->btree_id);
367 	BUG_ON(ret);
368 
369 	trace_and_count(c, btree_node_alloc, trans, b);
370 	bch2_increment_clock(c, btree_sectors(c), WRITE);
371 	return b;
372 }
373 
374 static void btree_set_min(struct btree *b, struct bpos pos)
375 {
376 	if (b->key.k.type == KEY_TYPE_btree_ptr_v2)
377 		bkey_i_to_btree_ptr_v2(&b->key)->v.min_key = pos;
378 	b->data->min_key = pos;
379 }
380 
381 static void btree_set_max(struct btree *b, struct bpos pos)
382 {
383 	b->key.k.p = pos;
384 	b->data->max_key = pos;
385 }
386 
387 static struct btree *bch2_btree_node_alloc_replacement(struct btree_update *as,
388 						       struct btree_trans *trans,
389 						       struct btree *b)
390 {
391 	struct btree *n = bch2_btree_node_alloc(as, trans, b->c.level);
392 	struct bkey_format format = bch2_btree_calc_format(b);
393 
394 	/*
395 	 * The keys might expand with the new format - if they wouldn't fit in
396 	 * the btree node anymore, use the old format for now:
397 	 */
398 	if (!bch2_btree_node_format_fits(as->c, b, b->nr, &format))
399 		format = b->format;
400 
401 	SET_BTREE_NODE_SEQ(n->data, BTREE_NODE_SEQ(b->data) + 1);
402 
403 	btree_set_min(n, b->data->min_key);
404 	btree_set_max(n, b->data->max_key);
405 
406 	n->data->format		= format;
407 	btree_node_set_format(n, format);
408 
409 	bch2_btree_sort_into(as->c, n, b);
410 
411 	btree_node_reset_sib_u64s(n);
412 	return n;
413 }
414 
415 static struct btree *__btree_root_alloc(struct btree_update *as,
416 				struct btree_trans *trans, unsigned level)
417 {
418 	struct btree *b = bch2_btree_node_alloc(as, trans, level);
419 
420 	btree_set_min(b, POS_MIN);
421 	btree_set_max(b, SPOS_MAX);
422 	b->data->format = bch2_btree_calc_format(b);
423 
424 	btree_node_set_format(b, b->data->format);
425 	bch2_btree_build_aux_trees(b);
426 
427 	return b;
428 }
429 
430 static void bch2_btree_reserve_put(struct btree_update *as, struct btree_trans *trans)
431 {
432 	struct bch_fs *c = as->c;
433 	struct prealloc_nodes *p;
434 
435 	for (p = as->prealloc_nodes;
436 	     p < as->prealloc_nodes + ARRAY_SIZE(as->prealloc_nodes);
437 	     p++) {
438 		while (p->nr) {
439 			struct btree *b = p->b[--p->nr];
440 
441 			mutex_lock(&c->btree_reserve_cache_lock);
442 
443 			if (c->btree_reserve_cache_nr <
444 			    ARRAY_SIZE(c->btree_reserve_cache)) {
445 				struct btree_alloc *a =
446 					&c->btree_reserve_cache[c->btree_reserve_cache_nr++];
447 
448 				a->ob = b->ob;
449 				b->ob.nr = 0;
450 				bkey_copy(&a->k, &b->key);
451 			} else {
452 				bch2_open_buckets_put(c, &b->ob);
453 			}
454 
455 			mutex_unlock(&c->btree_reserve_cache_lock);
456 
457 			btree_node_lock_nopath_nofail(trans, &b->c, SIX_LOCK_intent);
458 			btree_node_lock_nopath_nofail(trans, &b->c, SIX_LOCK_write);
459 			__btree_node_free(trans, b);
460 			six_unlock_write(&b->c.lock);
461 			six_unlock_intent(&b->c.lock);
462 		}
463 	}
464 }
465 
466 static int bch2_btree_reserve_get(struct btree_trans *trans,
467 				  struct btree_update *as,
468 				  unsigned nr_nodes[2],
469 				  unsigned flags,
470 				  struct closure *cl)
471 {
472 	struct btree *b;
473 	unsigned interior;
474 	int ret = 0;
475 
476 	BUG_ON(nr_nodes[0] + nr_nodes[1] > BTREE_RESERVE_MAX);
477 
478 	/*
479 	 * Protects reaping from the btree node cache and using the btree node
480 	 * open bucket reserve:
481 	 */
482 	ret = bch2_btree_cache_cannibalize_lock(trans, cl);
483 	if (ret)
484 		return ret;
485 
486 	for (interior = 0; interior < 2; interior++) {
487 		struct prealloc_nodes *p = as->prealloc_nodes + interior;
488 
489 		while (p->nr < nr_nodes[interior]) {
490 			b = __bch2_btree_node_alloc(trans, &as->disk_res, cl,
491 						    interior, flags);
492 			if (IS_ERR(b)) {
493 				ret = PTR_ERR(b);
494 				goto err;
495 			}
496 
497 			p->b[p->nr++] = b;
498 		}
499 	}
500 err:
501 	bch2_btree_cache_cannibalize_unlock(trans);
502 	return ret;
503 }
504 
505 /* Asynchronous interior node update machinery */
506 
507 static void bch2_btree_update_free(struct btree_update *as, struct btree_trans *trans)
508 {
509 	struct bch_fs *c = as->c;
510 
511 	if (as->took_gc_lock)
512 		up_read(&c->gc_lock);
513 	as->took_gc_lock = false;
514 
515 	bch2_journal_pin_drop(&c->journal, &as->journal);
516 	bch2_journal_pin_flush(&c->journal, &as->journal);
517 	bch2_disk_reservation_put(c, &as->disk_res);
518 	bch2_btree_reserve_put(as, trans);
519 
520 	bch2_time_stats_update(&c->times[BCH_TIME_btree_interior_update_total],
521 			       as->start_time);
522 
523 	mutex_lock(&c->btree_interior_update_lock);
524 	list_del(&as->unwritten_list);
525 	list_del(&as->list);
526 
527 	closure_debug_destroy(&as->cl);
528 	mempool_free(as, &c->btree_interior_update_pool);
529 
530 	/*
531 	 * Have to do the wakeup with btree_interior_update_lock still held,
532 	 * since being on btree_interior_update_list is our ref on @c:
533 	 */
534 	closure_wake_up(&c->btree_interior_update_wait);
535 
536 	mutex_unlock(&c->btree_interior_update_lock);
537 }
538 
539 static void btree_update_add_key(struct btree_update *as,
540 				 struct keylist *keys, struct btree *b)
541 {
542 	struct bkey_i *k = &b->key;
543 
544 	BUG_ON(bch2_keylist_u64s(keys) + k->k.u64s >
545 	       ARRAY_SIZE(as->_old_keys));
546 
547 	bkey_copy(keys->top, k);
548 	bkey_i_to_btree_ptr_v2(keys->top)->v.mem_ptr = b->c.level + 1;
549 
550 	bch2_keylist_push(keys);
551 }
552 
553 /*
554  * The transactional part of an interior btree node update, where we journal the
555  * update we did to the interior node and update alloc info:
556  */
557 static int btree_update_nodes_written_trans(struct btree_trans *trans,
558 					    struct btree_update *as)
559 {
560 	struct jset_entry *e = bch2_trans_jset_entry_alloc(trans, as->journal_u64s);
561 	int ret = PTR_ERR_OR_ZERO(e);
562 	if (ret)
563 		return ret;
564 
565 	memcpy(e, as->journal_entries, as->journal_u64s * sizeof(u64));
566 
567 	trans->journal_pin = &as->journal;
568 
569 	for_each_keylist_key(&as->old_keys, k) {
570 		unsigned level = bkey_i_to_btree_ptr_v2(k)->v.mem_ptr;
571 
572 		ret = bch2_key_trigger_old(trans, as->btree_id, level, bkey_i_to_s_c(k),
573 					   BTREE_TRIGGER_TRANSACTIONAL);
574 		if (ret)
575 			return ret;
576 	}
577 
578 	for_each_keylist_key(&as->new_keys, k) {
579 		unsigned level = bkey_i_to_btree_ptr_v2(k)->v.mem_ptr;
580 
581 		ret = bch2_key_trigger_new(trans, as->btree_id, level, bkey_i_to_s(k),
582 					   BTREE_TRIGGER_TRANSACTIONAL);
583 		if (ret)
584 			return ret;
585 	}
586 
587 	return 0;
588 }
589 
590 static void btree_update_nodes_written(struct btree_update *as)
591 {
592 	struct bch_fs *c = as->c;
593 	struct btree *b;
594 	struct btree_trans *trans = bch2_trans_get(c);
595 	u64 journal_seq = 0;
596 	unsigned i;
597 	int ret;
598 
599 	/*
600 	 * If we're already in an error state, it might be because a btree node
601 	 * was never written, and we might be trying to free that same btree
602 	 * node here, but it won't have been marked as allocated and we'll see
603 	 * spurious disk usage inconsistencies in the transactional part below
604 	 * if we don't skip it:
605 	 */
606 	ret = bch2_journal_error(&c->journal);
607 	if (ret)
608 		goto err;
609 
610 	/*
611 	 * Wait for any in flight writes to finish before we free the old nodes
612 	 * on disk:
613 	 */
614 	for (i = 0; i < as->nr_old_nodes; i++) {
615 		__le64 seq;
616 
617 		b = as->old_nodes[i];
618 
619 		btree_node_lock_nopath_nofail(trans, &b->c, SIX_LOCK_read);
620 		seq = b->data ? b->data->keys.seq : 0;
621 		six_unlock_read(&b->c.lock);
622 
623 		if (seq == as->old_nodes_seq[i])
624 			wait_on_bit_io(&b->flags, BTREE_NODE_write_in_flight_inner,
625 				       TASK_UNINTERRUPTIBLE);
626 	}
627 
628 	/*
629 	 * We did an update to a parent node where the pointers we added pointed
630 	 * to child nodes that weren't written yet: now, the child nodes have
631 	 * been written so we can write out the update to the interior node.
632 	 */
633 
634 	/*
635 	 * We can't call into journal reclaim here: we'd block on the journal
636 	 * reclaim lock, but we may need to release the open buckets we have
637 	 * pinned in order for other btree updates to make forward progress, and
638 	 * journal reclaim does btree updates when flushing bkey_cached entries,
639 	 * which may require allocations as well.
640 	 */
641 	ret = commit_do(trans, &as->disk_res, &journal_seq,
642 			BCH_WATERMARK_reclaim|
643 			BCH_TRANS_COMMIT_no_enospc|
644 			BCH_TRANS_COMMIT_no_check_rw|
645 			BCH_TRANS_COMMIT_journal_reclaim,
646 			btree_update_nodes_written_trans(trans, as));
647 	bch2_trans_unlock(trans);
648 
649 	bch2_fs_fatal_err_on(ret && !bch2_journal_error(&c->journal), c,
650 			     "%s(): error %s", __func__, bch2_err_str(ret));
651 err:
652 	if (as->b) {
653 
654 		b = as->b;
655 		btree_path_idx_t path_idx = get_unlocked_mut_path(trans,
656 						as->btree_id, b->c.level, b->key.k.p);
657 		struct btree_path *path = trans->paths + path_idx;
658 		/*
659 		 * @b is the node we did the final insert into:
660 		 *
661 		 * On failure to get a journal reservation, we still have to
662 		 * unblock the write and allow most of the write path to happen
663 		 * so that shutdown works, but the i->journal_seq mechanism
664 		 * won't work to prevent the btree write from being visible (we
665 		 * didn't get a journal sequence number) - instead
666 		 * __bch2_btree_node_write() doesn't do the actual write if
667 		 * we're in journal error state:
668 		 */
669 
670 		/*
671 		 * Ensure transaction is unlocked before using
672 		 * btree_node_lock_nopath() (the use of which is always suspect,
673 		 * we need to work on removing this in the future)
674 		 *
675 		 * It should be, but get_unlocked_mut_path() -> bch2_path_get()
676 		 * calls bch2_path_upgrade(), before we call path_make_mut(), so
677 		 * we may rarely end up with a locked path besides the one we
678 		 * have here:
679 		 */
680 		bch2_trans_unlock(trans);
681 		btree_node_lock_nopath_nofail(trans, &b->c, SIX_LOCK_intent);
682 		mark_btree_node_locked(trans, path, b->c.level, BTREE_NODE_INTENT_LOCKED);
683 		path->l[b->c.level].lock_seq = six_lock_seq(&b->c.lock);
684 		path->l[b->c.level].b = b;
685 
686 		bch2_btree_node_lock_write_nofail(trans, path, &b->c);
687 
688 		mutex_lock(&c->btree_interior_update_lock);
689 
690 		list_del(&as->write_blocked_list);
691 		if (list_empty(&b->write_blocked))
692 			clear_btree_node_write_blocked(b);
693 
694 		/*
695 		 * Node might have been freed, recheck under
696 		 * btree_interior_update_lock:
697 		 */
698 		if (as->b == b) {
699 			BUG_ON(!b->c.level);
700 			BUG_ON(!btree_node_dirty(b));
701 
702 			if (!ret) {
703 				struct bset *last = btree_bset_last(b);
704 
705 				last->journal_seq = cpu_to_le64(
706 							     max(journal_seq,
707 								 le64_to_cpu(last->journal_seq)));
708 
709 				bch2_btree_add_journal_pin(c, b, journal_seq);
710 			} else {
711 				/*
712 				 * If we didn't get a journal sequence number we
713 				 * can't write this btree node, because recovery
714 				 * won't know to ignore this write:
715 				 */
716 				set_btree_node_never_write(b);
717 			}
718 		}
719 
720 		mutex_unlock(&c->btree_interior_update_lock);
721 
722 		mark_btree_node_locked_noreset(path, b->c.level, BTREE_NODE_INTENT_LOCKED);
723 		six_unlock_write(&b->c.lock);
724 
725 		btree_node_write_if_need(c, b, SIX_LOCK_intent);
726 		btree_node_unlock(trans, path, b->c.level);
727 		bch2_path_put(trans, path_idx, true);
728 	}
729 
730 	bch2_journal_pin_drop(&c->journal, &as->journal);
731 
732 	mutex_lock(&c->btree_interior_update_lock);
733 	for (i = 0; i < as->nr_new_nodes; i++) {
734 		b = as->new_nodes[i];
735 
736 		BUG_ON(b->will_make_reachable != (unsigned long) as);
737 		b->will_make_reachable = 0;
738 		clear_btree_node_will_make_reachable(b);
739 	}
740 	mutex_unlock(&c->btree_interior_update_lock);
741 
742 	for (i = 0; i < as->nr_new_nodes; i++) {
743 		b = as->new_nodes[i];
744 
745 		btree_node_lock_nopath_nofail(trans, &b->c, SIX_LOCK_read);
746 		btree_node_write_if_need(c, b, SIX_LOCK_read);
747 		six_unlock_read(&b->c.lock);
748 	}
749 
750 	for (i = 0; i < as->nr_open_buckets; i++)
751 		bch2_open_bucket_put(c, c->open_buckets + as->open_buckets[i]);
752 
753 	bch2_btree_update_free(as, trans);
754 	bch2_trans_put(trans);
755 }
756 
757 static void btree_interior_update_work(struct work_struct *work)
758 {
759 	struct bch_fs *c =
760 		container_of(work, struct bch_fs, btree_interior_update_work);
761 	struct btree_update *as;
762 
763 	while (1) {
764 		mutex_lock(&c->btree_interior_update_lock);
765 		as = list_first_entry_or_null(&c->btree_interior_updates_unwritten,
766 					      struct btree_update, unwritten_list);
767 		if (as && !as->nodes_written)
768 			as = NULL;
769 		mutex_unlock(&c->btree_interior_update_lock);
770 
771 		if (!as)
772 			break;
773 
774 		btree_update_nodes_written(as);
775 	}
776 }
777 
778 static CLOSURE_CALLBACK(btree_update_set_nodes_written)
779 {
780 	closure_type(as, struct btree_update, cl);
781 	struct bch_fs *c = as->c;
782 
783 	mutex_lock(&c->btree_interior_update_lock);
784 	as->nodes_written = true;
785 	mutex_unlock(&c->btree_interior_update_lock);
786 
787 	queue_work(c->btree_interior_update_worker, &c->btree_interior_update_work);
788 }
789 
790 /*
791  * We're updating @b with pointers to nodes that haven't finished writing yet:
792  * block @b from being written until @as completes
793  */
794 static void btree_update_updated_node(struct btree_update *as, struct btree *b)
795 {
796 	struct bch_fs *c = as->c;
797 
798 	mutex_lock(&c->btree_interior_update_lock);
799 	list_add_tail(&as->unwritten_list, &c->btree_interior_updates_unwritten);
800 
801 	BUG_ON(as->mode != BTREE_INTERIOR_NO_UPDATE);
802 	BUG_ON(!btree_node_dirty(b));
803 	BUG_ON(!b->c.level);
804 
805 	as->mode	= BTREE_INTERIOR_UPDATING_NODE;
806 	as->b		= b;
807 
808 	set_btree_node_write_blocked(b);
809 	list_add(&as->write_blocked_list, &b->write_blocked);
810 
811 	mutex_unlock(&c->btree_interior_update_lock);
812 }
813 
814 static int bch2_update_reparent_journal_pin_flush(struct journal *j,
815 				struct journal_entry_pin *_pin, u64 seq)
816 {
817 	return 0;
818 }
819 
820 static void btree_update_reparent(struct btree_update *as,
821 				  struct btree_update *child)
822 {
823 	struct bch_fs *c = as->c;
824 
825 	lockdep_assert_held(&c->btree_interior_update_lock);
826 
827 	child->b = NULL;
828 	child->mode = BTREE_INTERIOR_UPDATING_AS;
829 
830 	bch2_journal_pin_copy(&c->journal, &as->journal, &child->journal,
831 			      bch2_update_reparent_journal_pin_flush);
832 }
833 
834 static void btree_update_updated_root(struct btree_update *as, struct btree *b)
835 {
836 	struct bkey_i *insert = &b->key;
837 	struct bch_fs *c = as->c;
838 
839 	BUG_ON(as->mode != BTREE_INTERIOR_NO_UPDATE);
840 
841 	BUG_ON(as->journal_u64s + jset_u64s(insert->k.u64s) >
842 	       ARRAY_SIZE(as->journal_entries));
843 
844 	as->journal_u64s +=
845 		journal_entry_set((void *) &as->journal_entries[as->journal_u64s],
846 				  BCH_JSET_ENTRY_btree_root,
847 				  b->c.btree_id, b->c.level,
848 				  insert, insert->k.u64s);
849 
850 	mutex_lock(&c->btree_interior_update_lock);
851 	list_add_tail(&as->unwritten_list, &c->btree_interior_updates_unwritten);
852 
853 	as->mode	= BTREE_INTERIOR_UPDATING_ROOT;
854 	mutex_unlock(&c->btree_interior_update_lock);
855 }
856 
857 /*
858  * bch2_btree_update_add_new_node:
859  *
860  * This causes @as to wait on @b to be written, before it gets to
861  * bch2_btree_update_nodes_written
862  *
863  * Additionally, it sets b->will_make_reachable to prevent any additional writes
864  * to @b from happening besides the first until @b is reachable on disk
865  *
866  * And it adds @b to the list of @as's new nodes, so that we can update sector
867  * counts in bch2_btree_update_nodes_written:
868  */
869 static void bch2_btree_update_add_new_node(struct btree_update *as, struct btree *b)
870 {
871 	struct bch_fs *c = as->c;
872 
873 	closure_get(&as->cl);
874 
875 	mutex_lock(&c->btree_interior_update_lock);
876 	BUG_ON(as->nr_new_nodes >= ARRAY_SIZE(as->new_nodes));
877 	BUG_ON(b->will_make_reachable);
878 
879 	as->new_nodes[as->nr_new_nodes++] = b;
880 	b->will_make_reachable = 1UL|(unsigned long) as;
881 	set_btree_node_will_make_reachable(b);
882 
883 	mutex_unlock(&c->btree_interior_update_lock);
884 
885 	btree_update_add_key(as, &as->new_keys, b);
886 
887 	if (b->key.k.type == KEY_TYPE_btree_ptr_v2) {
888 		unsigned bytes = vstruct_end(&b->data->keys) - (void *) b->data;
889 		unsigned sectors = round_up(bytes, block_bytes(c)) >> 9;
890 
891 		bkey_i_to_btree_ptr_v2(&b->key)->v.sectors_written =
892 			cpu_to_le16(sectors);
893 	}
894 }
895 
896 /*
897  * returns true if @b was a new node
898  */
899 static void btree_update_drop_new_node(struct bch_fs *c, struct btree *b)
900 {
901 	struct btree_update *as;
902 	unsigned long v;
903 	unsigned i;
904 
905 	mutex_lock(&c->btree_interior_update_lock);
906 	/*
907 	 * When b->will_make_reachable != 0, it owns a ref on as->cl that's
908 	 * dropped when it gets written by bch2_btree_complete_write - the
909 	 * xchg() is for synchronization with bch2_btree_complete_write:
910 	 */
911 	v = xchg(&b->will_make_reachable, 0);
912 	clear_btree_node_will_make_reachable(b);
913 	as = (struct btree_update *) (v & ~1UL);
914 
915 	if (!as) {
916 		mutex_unlock(&c->btree_interior_update_lock);
917 		return;
918 	}
919 
920 	for (i = 0; i < as->nr_new_nodes; i++)
921 		if (as->new_nodes[i] == b)
922 			goto found;
923 
924 	BUG();
925 found:
926 	array_remove_item(as->new_nodes, as->nr_new_nodes, i);
927 	mutex_unlock(&c->btree_interior_update_lock);
928 
929 	if (v & 1)
930 		closure_put(&as->cl);
931 }
932 
933 static void bch2_btree_update_get_open_buckets(struct btree_update *as, struct btree *b)
934 {
935 	while (b->ob.nr)
936 		as->open_buckets[as->nr_open_buckets++] =
937 			b->ob.v[--b->ob.nr];
938 }
939 
940 static int bch2_btree_update_will_free_node_journal_pin_flush(struct journal *j,
941 				struct journal_entry_pin *_pin, u64 seq)
942 {
943 	return 0;
944 }
945 
946 /*
947  * @b is being split/rewritten: it may have pointers to not-yet-written btree
948  * nodes and thus outstanding btree_updates - redirect @b's
949  * btree_updates to point to this btree_update:
950  */
951 static void bch2_btree_interior_update_will_free_node(struct btree_update *as,
952 						      struct btree *b)
953 {
954 	struct bch_fs *c = as->c;
955 	struct btree_update *p, *n;
956 	struct btree_write *w;
957 
958 	set_btree_node_dying(b);
959 
960 	if (btree_node_fake(b))
961 		return;
962 
963 	mutex_lock(&c->btree_interior_update_lock);
964 
965 	/*
966 	 * Does this node have any btree_update operations preventing
967 	 * it from being written?
968 	 *
969 	 * If so, redirect them to point to this btree_update: we can
970 	 * write out our new nodes, but we won't make them visible until those
971 	 * operations complete
972 	 */
973 	list_for_each_entry_safe(p, n, &b->write_blocked, write_blocked_list) {
974 		list_del_init(&p->write_blocked_list);
975 		btree_update_reparent(as, p);
976 
977 		/*
978 		 * for flush_held_btree_writes() waiting on updates to flush or
979 		 * nodes to be writeable:
980 		 */
981 		closure_wake_up(&c->btree_interior_update_wait);
982 	}
983 
984 	clear_btree_node_dirty_acct(c, b);
985 	clear_btree_node_need_write(b);
986 	clear_btree_node_write_blocked(b);
987 
988 	/*
989 	 * Does this node have unwritten data that has a pin on the journal?
990 	 *
991 	 * If so, transfer that pin to the btree_update operation -
992 	 * note that if we're freeing multiple nodes, we only need to keep the
993 	 * oldest pin of any of the nodes we're freeing. We'll release the pin
994 	 * when the new nodes are persistent and reachable on disk:
995 	 */
996 	w = btree_current_write(b);
997 	bch2_journal_pin_copy(&c->journal, &as->journal, &w->journal,
998 			      bch2_btree_update_will_free_node_journal_pin_flush);
999 	bch2_journal_pin_drop(&c->journal, &w->journal);
1000 
1001 	w = btree_prev_write(b);
1002 	bch2_journal_pin_copy(&c->journal, &as->journal, &w->journal,
1003 			      bch2_btree_update_will_free_node_journal_pin_flush);
1004 	bch2_journal_pin_drop(&c->journal, &w->journal);
1005 
1006 	mutex_unlock(&c->btree_interior_update_lock);
1007 
1008 	/*
1009 	 * Is this a node that isn't reachable on disk yet?
1010 	 *
1011 	 * Nodes that aren't reachable yet have writes blocked until they're
1012 	 * reachable - now that we've cancelled any pending writes and moved
1013 	 * things waiting on that write to wait on this update, we can drop this
1014 	 * node from the list of nodes that the other update is making
1015 	 * reachable, prior to freeing it:
1016 	 */
1017 	btree_update_drop_new_node(c, b);
1018 
1019 	btree_update_add_key(as, &as->old_keys, b);
1020 
1021 	as->old_nodes[as->nr_old_nodes] = b;
1022 	as->old_nodes_seq[as->nr_old_nodes] = b->data->keys.seq;
1023 	as->nr_old_nodes++;
1024 }
1025 
1026 static void bch2_btree_update_done(struct btree_update *as, struct btree_trans *trans)
1027 {
1028 	struct bch_fs *c = as->c;
1029 	u64 start_time = as->start_time;
1030 
1031 	BUG_ON(as->mode == BTREE_INTERIOR_NO_UPDATE);
1032 
1033 	if (as->took_gc_lock)
1034 		up_read(&as->c->gc_lock);
1035 	as->took_gc_lock = false;
1036 
1037 	bch2_btree_reserve_put(as, trans);
1038 
1039 	continue_at(&as->cl, btree_update_set_nodes_written,
1040 		    as->c->btree_interior_update_worker);
1041 
1042 	bch2_time_stats_update(&c->times[BCH_TIME_btree_interior_update_foreground],
1043 			       start_time);
1044 }
1045 
1046 static struct btree_update *
1047 bch2_btree_update_start(struct btree_trans *trans, struct btree_path *path,
1048 			unsigned level, bool split, unsigned flags)
1049 {
1050 	struct bch_fs *c = trans->c;
1051 	struct btree_update *as;
1052 	u64 start_time = local_clock();
1053 	int disk_res_flags = (flags & BCH_TRANS_COMMIT_no_enospc)
1054 		? BCH_DISK_RESERVATION_NOFAIL : 0;
1055 	unsigned nr_nodes[2] = { 0, 0 };
1056 	unsigned update_level = level;
1057 	enum bch_watermark watermark = flags & BCH_WATERMARK_MASK;
1058 	int ret = 0;
1059 	u32 restart_count = trans->restart_count;
1060 
1061 	BUG_ON(!path->should_be_locked);
1062 
1063 	if (watermark == BCH_WATERMARK_copygc)
1064 		watermark = BCH_WATERMARK_btree_copygc;
1065 	if (watermark < BCH_WATERMARK_btree)
1066 		watermark = BCH_WATERMARK_btree;
1067 
1068 	flags &= ~BCH_WATERMARK_MASK;
1069 	flags |= watermark;
1070 
1071 	if (!(flags & BCH_TRANS_COMMIT_journal_reclaim) &&
1072 	    watermark < c->journal.watermark) {
1073 		struct journal_res res = { 0 };
1074 
1075 		ret = drop_locks_do(trans,
1076 			bch2_journal_res_get(&c->journal, &res, 1,
1077 					     watermark|JOURNAL_RES_GET_CHECK));
1078 		if (ret)
1079 			return ERR_PTR(ret);
1080 	}
1081 
1082 	while (1) {
1083 		nr_nodes[!!update_level] += 1 + split;
1084 		update_level++;
1085 
1086 		ret = bch2_btree_path_upgrade(trans, path, update_level + 1);
1087 		if (ret)
1088 			return ERR_PTR(ret);
1089 
1090 		if (!btree_path_node(path, update_level)) {
1091 			/* Allocating new root? */
1092 			nr_nodes[1] += split;
1093 			update_level = BTREE_MAX_DEPTH;
1094 			break;
1095 		}
1096 
1097 		/*
1098 		 * Always check for space for two keys, even if we won't have to
1099 		 * split at prior level - it might have been a merge instead:
1100 		 */
1101 		if (bch2_btree_node_insert_fits(path->l[update_level].b,
1102 						BKEY_BTREE_PTR_U64s_MAX * 2))
1103 			break;
1104 
1105 		split = path->l[update_level].b->nr.live_u64s > BTREE_SPLIT_THRESHOLD(c);
1106 	}
1107 
1108 	if (!down_read_trylock(&c->gc_lock)) {
1109 		ret = drop_locks_do(trans, (down_read(&c->gc_lock), 0));
1110 		if (ret) {
1111 			up_read(&c->gc_lock);
1112 			return ERR_PTR(ret);
1113 		}
1114 	}
1115 
1116 	as = mempool_alloc(&c->btree_interior_update_pool, GFP_NOFS);
1117 	memset(as, 0, sizeof(*as));
1118 	closure_init(&as->cl, NULL);
1119 	as->c		= c;
1120 	as->start_time	= start_time;
1121 	as->mode	= BTREE_INTERIOR_NO_UPDATE;
1122 	as->took_gc_lock = true;
1123 	as->btree_id	= path->btree_id;
1124 	as->update_level = update_level;
1125 	INIT_LIST_HEAD(&as->list);
1126 	INIT_LIST_HEAD(&as->unwritten_list);
1127 	INIT_LIST_HEAD(&as->write_blocked_list);
1128 	bch2_keylist_init(&as->old_keys, as->_old_keys);
1129 	bch2_keylist_init(&as->new_keys, as->_new_keys);
1130 	bch2_keylist_init(&as->parent_keys, as->inline_keys);
1131 
1132 	mutex_lock(&c->btree_interior_update_lock);
1133 	list_add_tail(&as->list, &c->btree_interior_update_list);
1134 	mutex_unlock(&c->btree_interior_update_lock);
1135 
1136 	/*
1137 	 * We don't want to allocate if we're in an error state, that can cause
1138 	 * deadlock on emergency shutdown due to open buckets getting stuck in
1139 	 * the btree_reserve_cache after allocator shutdown has cleared it out.
1140 	 * This check needs to come after adding us to the btree_interior_update
1141 	 * list but before calling bch2_btree_reserve_get, to synchronize with
1142 	 * __bch2_fs_read_only().
1143 	 */
1144 	ret = bch2_journal_error(&c->journal);
1145 	if (ret)
1146 		goto err;
1147 
1148 	ret = bch2_disk_reservation_get(c, &as->disk_res,
1149 			(nr_nodes[0] + nr_nodes[1]) * btree_sectors(c),
1150 			c->opts.metadata_replicas,
1151 			disk_res_flags);
1152 	if (ret)
1153 		goto err;
1154 
1155 	ret = bch2_btree_reserve_get(trans, as, nr_nodes, flags, NULL);
1156 	if (bch2_err_matches(ret, ENOSPC) ||
1157 	    bch2_err_matches(ret, ENOMEM)) {
1158 		struct closure cl;
1159 
1160 		/*
1161 		 * XXX: this should probably be a separate BTREE_INSERT_NONBLOCK
1162 		 * flag
1163 		 */
1164 		if (bch2_err_matches(ret, ENOSPC) &&
1165 		    (flags & BCH_TRANS_COMMIT_journal_reclaim) &&
1166 		    watermark != BCH_WATERMARK_reclaim) {
1167 			ret = -BCH_ERR_journal_reclaim_would_deadlock;
1168 			goto err;
1169 		}
1170 
1171 		closure_init_stack(&cl);
1172 
1173 		do {
1174 			ret = bch2_btree_reserve_get(trans, as, nr_nodes, flags, &cl);
1175 
1176 			bch2_trans_unlock(trans);
1177 			closure_sync(&cl);
1178 		} while (bch2_err_matches(ret, BCH_ERR_operation_blocked));
1179 	}
1180 
1181 	if (ret) {
1182 		trace_and_count(c, btree_reserve_get_fail, trans->fn,
1183 				_RET_IP_, nr_nodes[0] + nr_nodes[1], ret);
1184 		goto err;
1185 	}
1186 
1187 	ret = bch2_trans_relock(trans);
1188 	if (ret)
1189 		goto err;
1190 
1191 	bch2_trans_verify_not_restarted(trans, restart_count);
1192 	return as;
1193 err:
1194 	bch2_btree_update_free(as, trans);
1195 	if (!bch2_err_matches(ret, ENOSPC) &&
1196 	    !bch2_err_matches(ret, EROFS))
1197 		bch_err_fn_ratelimited(c, ret);
1198 	return ERR_PTR(ret);
1199 }
1200 
1201 /* Btree root updates: */
1202 
1203 static void bch2_btree_set_root_inmem(struct bch_fs *c, struct btree *b)
1204 {
1205 	/* Root nodes cannot be reaped */
1206 	mutex_lock(&c->btree_cache.lock);
1207 	list_del_init(&b->list);
1208 	mutex_unlock(&c->btree_cache.lock);
1209 
1210 	mutex_lock(&c->btree_root_lock);
1211 	BUG_ON(btree_node_root(c, b) &&
1212 	       (b->c.level < btree_node_root(c, b)->c.level ||
1213 		!btree_node_dying(btree_node_root(c, b))));
1214 
1215 	bch2_btree_id_root(c, b->c.btree_id)->b = b;
1216 	mutex_unlock(&c->btree_root_lock);
1217 
1218 	bch2_recalc_btree_reserve(c);
1219 }
1220 
1221 static void bch2_btree_set_root(struct btree_update *as,
1222 				struct btree_trans *trans,
1223 				struct btree_path *path,
1224 				struct btree *b)
1225 {
1226 	struct bch_fs *c = as->c;
1227 	struct btree *old;
1228 
1229 	trace_and_count(c, btree_node_set_root, trans, b);
1230 
1231 	old = btree_node_root(c, b);
1232 
1233 	/*
1234 	 * Ensure no one is using the old root while we switch to the
1235 	 * new root:
1236 	 */
1237 	bch2_btree_node_lock_write_nofail(trans, path, &old->c);
1238 
1239 	bch2_btree_set_root_inmem(c, b);
1240 
1241 	btree_update_updated_root(as, b);
1242 
1243 	/*
1244 	 * Unlock old root after new root is visible:
1245 	 *
1246 	 * The new root isn't persistent, but that's ok: we still have
1247 	 * an intent lock on the new root, and any updates that would
1248 	 * depend on the new root would have to update the new root.
1249 	 */
1250 	bch2_btree_node_unlock_write(trans, path, old);
1251 }
1252 
1253 /* Interior node updates: */
1254 
1255 static void bch2_insert_fixup_btree_ptr(struct btree_update *as,
1256 					struct btree_trans *trans,
1257 					struct btree_path *path,
1258 					struct btree *b,
1259 					struct btree_node_iter *node_iter,
1260 					struct bkey_i *insert)
1261 {
1262 	struct bch_fs *c = as->c;
1263 	struct bkey_packed *k;
1264 	struct printbuf buf = PRINTBUF;
1265 	unsigned long old, new, v;
1266 
1267 	BUG_ON(insert->k.type == KEY_TYPE_btree_ptr_v2 &&
1268 	       !btree_ptr_sectors_written(insert));
1269 
1270 	if (unlikely(!test_bit(JOURNAL_REPLAY_DONE, &c->journal.flags)))
1271 		bch2_journal_key_overwritten(c, b->c.btree_id, b->c.level, insert->k.p);
1272 
1273 	if (bch2_bkey_invalid(c, bkey_i_to_s_c(insert),
1274 			      btree_node_type(b), WRITE, &buf) ?:
1275 	    bch2_bkey_in_btree_node(c, b, bkey_i_to_s_c(insert), &buf)) {
1276 		printbuf_reset(&buf);
1277 		prt_printf(&buf, "inserting invalid bkey\n  ");
1278 		bch2_bkey_val_to_text(&buf, c, bkey_i_to_s_c(insert));
1279 		prt_printf(&buf, "\n  ");
1280 		bch2_bkey_invalid(c, bkey_i_to_s_c(insert),
1281 				  btree_node_type(b), WRITE, &buf);
1282 		bch2_bkey_in_btree_node(c, b, bkey_i_to_s_c(insert), &buf);
1283 
1284 		bch2_fs_inconsistent(c, "%s", buf.buf);
1285 		dump_stack();
1286 	}
1287 
1288 	BUG_ON(as->journal_u64s + jset_u64s(insert->k.u64s) >
1289 	       ARRAY_SIZE(as->journal_entries));
1290 
1291 	as->journal_u64s +=
1292 		journal_entry_set((void *) &as->journal_entries[as->journal_u64s],
1293 				  BCH_JSET_ENTRY_btree_keys,
1294 				  b->c.btree_id, b->c.level,
1295 				  insert, insert->k.u64s);
1296 
1297 	while ((k = bch2_btree_node_iter_peek_all(node_iter, b)) &&
1298 	       bkey_iter_pos_cmp(b, k, &insert->k.p) < 0)
1299 		bch2_btree_node_iter_advance(node_iter, b);
1300 
1301 	bch2_btree_bset_insert_key(trans, path, b, node_iter, insert);
1302 	set_btree_node_dirty_acct(c, b);
1303 
1304 	v = READ_ONCE(b->flags);
1305 	do {
1306 		old = new = v;
1307 
1308 		new &= ~BTREE_WRITE_TYPE_MASK;
1309 		new |= BTREE_WRITE_interior;
1310 		new |= 1 << BTREE_NODE_need_write;
1311 	} while ((v = cmpxchg(&b->flags, old, new)) != old);
1312 
1313 	printbuf_exit(&buf);
1314 }
1315 
1316 static void
1317 __bch2_btree_insert_keys_interior(struct btree_update *as,
1318 				  struct btree_trans *trans,
1319 				  struct btree_path *path,
1320 				  struct btree *b,
1321 				  struct btree_node_iter node_iter,
1322 				  struct keylist *keys)
1323 {
1324 	struct bkey_i *insert = bch2_keylist_front(keys);
1325 	struct bkey_packed *k;
1326 
1327 	BUG_ON(btree_node_type(b) != BKEY_TYPE_btree);
1328 
1329 	while ((k = bch2_btree_node_iter_prev_all(&node_iter, b)) &&
1330 	       (bkey_cmp_left_packed(b, k, &insert->k.p) >= 0))
1331 		;
1332 
1333 	while (!bch2_keylist_empty(keys)) {
1334 		insert = bch2_keylist_front(keys);
1335 
1336 		if (bpos_gt(insert->k.p, b->key.k.p))
1337 			break;
1338 
1339 		bch2_insert_fixup_btree_ptr(as, trans, path, b, &node_iter, insert);
1340 		bch2_keylist_pop_front(keys);
1341 	}
1342 }
1343 
1344 /*
1345  * Move keys from n1 (original replacement node, now lower node) to n2 (higher
1346  * node)
1347  */
1348 static void __btree_split_node(struct btree_update *as,
1349 			       struct btree_trans *trans,
1350 			       struct btree *b,
1351 			       struct btree *n[2])
1352 {
1353 	struct bkey_packed *k;
1354 	struct bpos n1_pos = POS_MIN;
1355 	struct btree_node_iter iter;
1356 	struct bset *bsets[2];
1357 	struct bkey_format_state format[2];
1358 	struct bkey_packed *out[2];
1359 	struct bkey uk;
1360 	unsigned u64s, n1_u64s = (b->nr.live_u64s * 3) / 5;
1361 	struct { unsigned nr_keys, val_u64s; } nr_keys[2];
1362 	int i;
1363 
1364 	memset(&nr_keys, 0, sizeof(nr_keys));
1365 
1366 	for (i = 0; i < 2; i++) {
1367 		BUG_ON(n[i]->nsets != 1);
1368 
1369 		bsets[i] = btree_bset_first(n[i]);
1370 		out[i] = bsets[i]->start;
1371 
1372 		SET_BTREE_NODE_SEQ(n[i]->data, BTREE_NODE_SEQ(b->data) + 1);
1373 		bch2_bkey_format_init(&format[i]);
1374 	}
1375 
1376 	u64s = 0;
1377 	for_each_btree_node_key(b, k, &iter) {
1378 		if (bkey_deleted(k))
1379 			continue;
1380 
1381 		i = u64s >= n1_u64s;
1382 		u64s += k->u64s;
1383 		uk = bkey_unpack_key(b, k);
1384 		if (!i)
1385 			n1_pos = uk.p;
1386 		bch2_bkey_format_add_key(&format[i], &uk);
1387 
1388 		nr_keys[i].nr_keys++;
1389 		nr_keys[i].val_u64s += bkeyp_val_u64s(&b->format, k);
1390 	}
1391 
1392 	btree_set_min(n[0], b->data->min_key);
1393 	btree_set_max(n[0], n1_pos);
1394 	btree_set_min(n[1], bpos_successor(n1_pos));
1395 	btree_set_max(n[1], b->data->max_key);
1396 
1397 	for (i = 0; i < 2; i++) {
1398 		bch2_bkey_format_add_pos(&format[i], n[i]->data->min_key);
1399 		bch2_bkey_format_add_pos(&format[i], n[i]->data->max_key);
1400 
1401 		n[i]->data->format = bch2_bkey_format_done(&format[i]);
1402 
1403 		unsigned u64s = nr_keys[i].nr_keys * n[i]->data->format.key_u64s +
1404 			nr_keys[i].val_u64s;
1405 		if (__vstruct_bytes(struct btree_node, u64s) > btree_buf_bytes(b))
1406 			n[i]->data->format = b->format;
1407 
1408 		btree_node_set_format(n[i], n[i]->data->format);
1409 	}
1410 
1411 	u64s = 0;
1412 	for_each_btree_node_key(b, k, &iter) {
1413 		if (bkey_deleted(k))
1414 			continue;
1415 
1416 		i = u64s >= n1_u64s;
1417 		u64s += k->u64s;
1418 
1419 		if (bch2_bkey_transform(&n[i]->format, out[i], bkey_packed(k)
1420 					? &b->format: &bch2_bkey_format_current, k))
1421 			out[i]->format = KEY_FORMAT_LOCAL_BTREE;
1422 		else
1423 			bch2_bkey_unpack(b, (void *) out[i], k);
1424 
1425 		out[i]->needs_whiteout = false;
1426 
1427 		btree_keys_account_key_add(&n[i]->nr, 0, out[i]);
1428 		out[i] = bkey_p_next(out[i]);
1429 	}
1430 
1431 	for (i = 0; i < 2; i++) {
1432 		bsets[i]->u64s = cpu_to_le16((u64 *) out[i] - bsets[i]->_data);
1433 
1434 		BUG_ON(!bsets[i]->u64s);
1435 
1436 		set_btree_bset_end(n[i], n[i]->set);
1437 
1438 		btree_node_reset_sib_u64s(n[i]);
1439 
1440 		bch2_verify_btree_nr_keys(n[i]);
1441 
1442 		if (b->c.level)
1443 			btree_node_interior_verify(as->c, n[i]);
1444 	}
1445 }
1446 
1447 /*
1448  * For updates to interior nodes, we've got to do the insert before we split
1449  * because the stuff we're inserting has to be inserted atomically. Post split,
1450  * the keys might have to go in different nodes and the split would no longer be
1451  * atomic.
1452  *
1453  * Worse, if the insert is from btree node coalescing, if we do the insert after
1454  * we do the split (and pick the pivot) - the pivot we pick might be between
1455  * nodes that were coalesced, and thus in the middle of a child node post
1456  * coalescing:
1457  */
1458 static void btree_split_insert_keys(struct btree_update *as,
1459 				    struct btree_trans *trans,
1460 				    btree_path_idx_t path_idx,
1461 				    struct btree *b,
1462 				    struct keylist *keys)
1463 {
1464 	struct btree_path *path = trans->paths + path_idx;
1465 
1466 	if (!bch2_keylist_empty(keys) &&
1467 	    bpos_le(bch2_keylist_front(keys)->k.p, b->data->max_key)) {
1468 		struct btree_node_iter node_iter;
1469 
1470 		bch2_btree_node_iter_init(&node_iter, b, &bch2_keylist_front(keys)->k.p);
1471 
1472 		__bch2_btree_insert_keys_interior(as, trans, path, b, node_iter, keys);
1473 
1474 		btree_node_interior_verify(as->c, b);
1475 	}
1476 }
1477 
1478 static int btree_split(struct btree_update *as, struct btree_trans *trans,
1479 		       btree_path_idx_t path, struct btree *b,
1480 		       struct keylist *keys, unsigned flags)
1481 {
1482 	struct bch_fs *c = as->c;
1483 	struct btree *parent = btree_node_parent(trans->paths + path, b);
1484 	struct btree *n1, *n2 = NULL, *n3 = NULL;
1485 	btree_path_idx_t path1 = 0, path2 = 0;
1486 	u64 start_time = local_clock();
1487 	int ret = 0;
1488 
1489 	BUG_ON(!parent && (b != btree_node_root(c, b)));
1490 	BUG_ON(parent && !btree_node_intent_locked(trans->paths + path, b->c.level + 1));
1491 
1492 	bch2_btree_interior_update_will_free_node(as, b);
1493 
1494 	if (b->nr.live_u64s > BTREE_SPLIT_THRESHOLD(c)) {
1495 		struct btree *n[2];
1496 
1497 		trace_and_count(c, btree_node_split, trans, b);
1498 
1499 		n[0] = n1 = bch2_btree_node_alloc(as, trans, b->c.level);
1500 		n[1] = n2 = bch2_btree_node_alloc(as, trans, b->c.level);
1501 
1502 		__btree_split_node(as, trans, b, n);
1503 
1504 		if (keys) {
1505 			btree_split_insert_keys(as, trans, path, n1, keys);
1506 			btree_split_insert_keys(as, trans, path, n2, keys);
1507 			BUG_ON(!bch2_keylist_empty(keys));
1508 		}
1509 
1510 		bch2_btree_build_aux_trees(n2);
1511 		bch2_btree_build_aux_trees(n1);
1512 
1513 		bch2_btree_update_add_new_node(as, n1);
1514 		bch2_btree_update_add_new_node(as, n2);
1515 		six_unlock_write(&n2->c.lock);
1516 		six_unlock_write(&n1->c.lock);
1517 
1518 		path1 = get_unlocked_mut_path(trans, as->btree_id, n1->c.level, n1->key.k.p);
1519 		six_lock_increment(&n1->c.lock, SIX_LOCK_intent);
1520 		mark_btree_node_locked(trans, trans->paths + path1, n1->c.level, BTREE_NODE_INTENT_LOCKED);
1521 		bch2_btree_path_level_init(trans, trans->paths + path1, n1);
1522 
1523 		path2 = get_unlocked_mut_path(trans, as->btree_id, n2->c.level, n2->key.k.p);
1524 		six_lock_increment(&n2->c.lock, SIX_LOCK_intent);
1525 		mark_btree_node_locked(trans, trans->paths + path2, n2->c.level, BTREE_NODE_INTENT_LOCKED);
1526 		bch2_btree_path_level_init(trans, trans->paths + path2, n2);
1527 
1528 		/*
1529 		 * Note that on recursive parent_keys == keys, so we
1530 		 * can't start adding new keys to parent_keys before emptying it
1531 		 * out (which we did with btree_split_insert_keys() above)
1532 		 */
1533 		bch2_keylist_add(&as->parent_keys, &n1->key);
1534 		bch2_keylist_add(&as->parent_keys, &n2->key);
1535 
1536 		if (!parent) {
1537 			/* Depth increases, make a new root */
1538 			n3 = __btree_root_alloc(as, trans, b->c.level + 1);
1539 
1540 			bch2_btree_update_add_new_node(as, n3);
1541 			six_unlock_write(&n3->c.lock);
1542 
1543 			trans->paths[path2].locks_want++;
1544 			BUG_ON(btree_node_locked(trans->paths + path2, n3->c.level));
1545 			six_lock_increment(&n3->c.lock, SIX_LOCK_intent);
1546 			mark_btree_node_locked(trans, trans->paths + path2, n3->c.level, BTREE_NODE_INTENT_LOCKED);
1547 			bch2_btree_path_level_init(trans, trans->paths + path2, n3);
1548 
1549 			n3->sib_u64s[0] = U16_MAX;
1550 			n3->sib_u64s[1] = U16_MAX;
1551 
1552 			btree_split_insert_keys(as, trans, path, n3, &as->parent_keys);
1553 		}
1554 	} else {
1555 		trace_and_count(c, btree_node_compact, trans, b);
1556 
1557 		n1 = bch2_btree_node_alloc_replacement(as, trans, b);
1558 
1559 		if (keys) {
1560 			btree_split_insert_keys(as, trans, path, n1, keys);
1561 			BUG_ON(!bch2_keylist_empty(keys));
1562 		}
1563 
1564 		bch2_btree_build_aux_trees(n1);
1565 		bch2_btree_update_add_new_node(as, n1);
1566 		six_unlock_write(&n1->c.lock);
1567 
1568 		path1 = get_unlocked_mut_path(trans, as->btree_id, n1->c.level, n1->key.k.p);
1569 		six_lock_increment(&n1->c.lock, SIX_LOCK_intent);
1570 		mark_btree_node_locked(trans, trans->paths + path1, n1->c.level, BTREE_NODE_INTENT_LOCKED);
1571 		bch2_btree_path_level_init(trans, trans->paths + path1, n1);
1572 
1573 		if (parent)
1574 			bch2_keylist_add(&as->parent_keys, &n1->key);
1575 	}
1576 
1577 	/* New nodes all written, now make them visible: */
1578 
1579 	if (parent) {
1580 		/* Split a non root node */
1581 		ret = bch2_btree_insert_node(as, trans, path, parent, &as->parent_keys, flags);
1582 		if (ret)
1583 			goto err;
1584 	} else if (n3) {
1585 		bch2_btree_set_root(as, trans, trans->paths + path, n3);
1586 	} else {
1587 		/* Root filled up but didn't need to be split */
1588 		bch2_btree_set_root(as, trans, trans->paths + path, n1);
1589 	}
1590 
1591 	if (n3) {
1592 		bch2_btree_update_get_open_buckets(as, n3);
1593 		bch2_btree_node_write(c, n3, SIX_LOCK_intent, 0);
1594 	}
1595 	if (n2) {
1596 		bch2_btree_update_get_open_buckets(as, n2);
1597 		bch2_btree_node_write(c, n2, SIX_LOCK_intent, 0);
1598 	}
1599 	bch2_btree_update_get_open_buckets(as, n1);
1600 	bch2_btree_node_write(c, n1, SIX_LOCK_intent, 0);
1601 
1602 	/*
1603 	 * The old node must be freed (in memory) _before_ unlocking the new
1604 	 * nodes - else another thread could re-acquire a read lock on the old
1605 	 * node after another thread has locked and updated the new node, thus
1606 	 * seeing stale data:
1607 	 */
1608 	bch2_btree_node_free_inmem(trans, trans->paths + path, b);
1609 
1610 	if (n3)
1611 		bch2_trans_node_add(trans, trans->paths + path, n3);
1612 	if (n2)
1613 		bch2_trans_node_add(trans, trans->paths + path2, n2);
1614 	bch2_trans_node_add(trans, trans->paths + path1, n1);
1615 
1616 	if (n3)
1617 		six_unlock_intent(&n3->c.lock);
1618 	if (n2)
1619 		six_unlock_intent(&n2->c.lock);
1620 	six_unlock_intent(&n1->c.lock);
1621 out:
1622 	if (path2) {
1623 		__bch2_btree_path_unlock(trans, trans->paths + path2);
1624 		bch2_path_put(trans, path2, true);
1625 	}
1626 	if (path1) {
1627 		__bch2_btree_path_unlock(trans, trans->paths + path1);
1628 		bch2_path_put(trans, path1, true);
1629 	}
1630 
1631 	bch2_trans_verify_locks(trans);
1632 
1633 	bch2_time_stats_update(&c->times[n2
1634 			       ? BCH_TIME_btree_node_split
1635 			       : BCH_TIME_btree_node_compact],
1636 			       start_time);
1637 	return ret;
1638 err:
1639 	if (n3)
1640 		bch2_btree_node_free_never_used(as, trans, n3);
1641 	if (n2)
1642 		bch2_btree_node_free_never_used(as, trans, n2);
1643 	bch2_btree_node_free_never_used(as, trans, n1);
1644 	goto out;
1645 }
1646 
1647 static void
1648 bch2_btree_insert_keys_interior(struct btree_update *as,
1649 				struct btree_trans *trans,
1650 				struct btree_path *path,
1651 				struct btree *b,
1652 				struct keylist *keys)
1653 {
1654 	struct btree_path *linked;
1655 	unsigned i;
1656 
1657 	__bch2_btree_insert_keys_interior(as, trans, path, b,
1658 					  path->l[b->c.level].iter, keys);
1659 
1660 	btree_update_updated_node(as, b);
1661 
1662 	trans_for_each_path_with_node(trans, b, linked, i)
1663 		bch2_btree_node_iter_peek(&linked->l[b->c.level].iter, b);
1664 
1665 	bch2_trans_verify_paths(trans);
1666 }
1667 
1668 /**
1669  * bch2_btree_insert_node - insert bkeys into a given btree node
1670  *
1671  * @as:			btree_update object
1672  * @trans:		btree_trans object
1673  * @path_idx:		path that points to current node
1674  * @b:			node to insert keys into
1675  * @keys:		list of keys to insert
1676  * @flags:		transaction commit flags
1677  *
1678  * Returns: 0 on success, typically transaction restart error on failure
1679  *
1680  * Inserts as many keys as it can into a given btree node, splitting it if full.
1681  * If a split occurred, this function will return early. This can only happen
1682  * for leaf nodes -- inserts into interior nodes have to be atomic.
1683  */
1684 static int bch2_btree_insert_node(struct btree_update *as, struct btree_trans *trans,
1685 				  btree_path_idx_t path_idx, struct btree *b,
1686 				  struct keylist *keys, unsigned flags)
1687 {
1688 	struct bch_fs *c = as->c;
1689 	struct btree_path *path = trans->paths + path_idx;
1690 	int old_u64s = le16_to_cpu(btree_bset_last(b)->u64s);
1691 	int old_live_u64s = b->nr.live_u64s;
1692 	int live_u64s_added, u64s_added;
1693 	int ret;
1694 
1695 	lockdep_assert_held(&c->gc_lock);
1696 	BUG_ON(!btree_node_intent_locked(path, b->c.level));
1697 	BUG_ON(!b->c.level);
1698 	BUG_ON(!as || as->b);
1699 	bch2_verify_keylist_sorted(keys);
1700 
1701 	ret = bch2_btree_node_lock_write(trans, path, &b->c);
1702 	if (ret)
1703 		return ret;
1704 
1705 	bch2_btree_node_prep_for_write(trans, path, b);
1706 
1707 	if (!bch2_btree_node_insert_fits(b, bch2_keylist_u64s(keys))) {
1708 		bch2_btree_node_unlock_write(trans, path, b);
1709 		goto split;
1710 	}
1711 
1712 	btree_node_interior_verify(c, b);
1713 
1714 	bch2_btree_insert_keys_interior(as, trans, path, b, keys);
1715 
1716 	live_u64s_added = (int) b->nr.live_u64s - old_live_u64s;
1717 	u64s_added = (int) le16_to_cpu(btree_bset_last(b)->u64s) - old_u64s;
1718 
1719 	if (b->sib_u64s[0] != U16_MAX && live_u64s_added < 0)
1720 		b->sib_u64s[0] = max(0, (int) b->sib_u64s[0] + live_u64s_added);
1721 	if (b->sib_u64s[1] != U16_MAX && live_u64s_added < 0)
1722 		b->sib_u64s[1] = max(0, (int) b->sib_u64s[1] + live_u64s_added);
1723 
1724 	if (u64s_added > live_u64s_added &&
1725 	    bch2_maybe_compact_whiteouts(c, b))
1726 		bch2_trans_node_reinit_iter(trans, b);
1727 
1728 	bch2_btree_node_unlock_write(trans, path, b);
1729 
1730 	btree_node_interior_verify(c, b);
1731 	return 0;
1732 split:
1733 	/*
1734 	 * We could attempt to avoid the transaction restart, by calling
1735 	 * bch2_btree_path_upgrade() and allocating more nodes:
1736 	 */
1737 	if (b->c.level >= as->update_level) {
1738 		trace_and_count(c, trans_restart_split_race, trans, _THIS_IP_, b);
1739 		return btree_trans_restart(trans, BCH_ERR_transaction_restart_split_race);
1740 	}
1741 
1742 	return btree_split(as, trans, path_idx, b, keys, flags);
1743 }
1744 
1745 int bch2_btree_split_leaf(struct btree_trans *trans,
1746 			  btree_path_idx_t path,
1747 			  unsigned flags)
1748 {
1749 	/* btree_split & merge may both cause paths array to be reallocated */
1750 
1751 	struct btree *b = path_l(trans->paths + path)->b;
1752 	struct btree_update *as;
1753 	unsigned l;
1754 	int ret = 0;
1755 
1756 	as = bch2_btree_update_start(trans, trans->paths + path,
1757 				     trans->paths[path].level,
1758 				     true, flags);
1759 	if (IS_ERR(as))
1760 		return PTR_ERR(as);
1761 
1762 	ret = btree_split(as, trans, path, b, NULL, flags);
1763 	if (ret) {
1764 		bch2_btree_update_free(as, trans);
1765 		return ret;
1766 	}
1767 
1768 	bch2_btree_update_done(as, trans);
1769 
1770 	for (l = trans->paths[path].level + 1;
1771 	     btree_node_intent_locked(&trans->paths[path], l) && !ret;
1772 	     l++)
1773 		ret = bch2_foreground_maybe_merge(trans, path, l, flags);
1774 
1775 	return ret;
1776 }
1777 
1778 int __bch2_foreground_maybe_merge(struct btree_trans *trans,
1779 				  btree_path_idx_t path,
1780 				  unsigned level,
1781 				  unsigned flags,
1782 				  enum btree_node_sibling sib)
1783 {
1784 	struct bch_fs *c = trans->c;
1785 	struct btree_update *as;
1786 	struct bkey_format_state new_s;
1787 	struct bkey_format new_f;
1788 	struct bkey_i delete;
1789 	struct btree *b, *m, *n, *prev, *next, *parent;
1790 	struct bpos sib_pos;
1791 	size_t sib_u64s;
1792 	enum btree_id btree = trans->paths[path].btree_id;
1793 	btree_path_idx_t sib_path = 0, new_path = 0;
1794 	u64 start_time = local_clock();
1795 	int ret = 0;
1796 
1797 	BUG_ON(!trans->paths[path].should_be_locked);
1798 	BUG_ON(!btree_node_locked(&trans->paths[path], level));
1799 
1800 	b = trans->paths[path].l[level].b;
1801 
1802 	if ((sib == btree_prev_sib && bpos_eq(b->data->min_key, POS_MIN)) ||
1803 	    (sib == btree_next_sib && bpos_eq(b->data->max_key, SPOS_MAX))) {
1804 		b->sib_u64s[sib] = U16_MAX;
1805 		return 0;
1806 	}
1807 
1808 	sib_pos = sib == btree_prev_sib
1809 		? bpos_predecessor(b->data->min_key)
1810 		: bpos_successor(b->data->max_key);
1811 
1812 	sib_path = bch2_path_get(trans, btree, sib_pos,
1813 				 U8_MAX, level, BTREE_ITER_INTENT, _THIS_IP_);
1814 	ret = bch2_btree_path_traverse(trans, sib_path, false);
1815 	if (ret)
1816 		goto err;
1817 
1818 	btree_path_set_should_be_locked(trans->paths + sib_path);
1819 
1820 	m = trans->paths[sib_path].l[level].b;
1821 
1822 	if (btree_node_parent(trans->paths + path, b) !=
1823 	    btree_node_parent(trans->paths + sib_path, m)) {
1824 		b->sib_u64s[sib] = U16_MAX;
1825 		goto out;
1826 	}
1827 
1828 	if (sib == btree_prev_sib) {
1829 		prev = m;
1830 		next = b;
1831 	} else {
1832 		prev = b;
1833 		next = m;
1834 	}
1835 
1836 	if (!bpos_eq(bpos_successor(prev->data->max_key), next->data->min_key)) {
1837 		struct printbuf buf1 = PRINTBUF, buf2 = PRINTBUF;
1838 
1839 		bch2_bpos_to_text(&buf1, prev->data->max_key);
1840 		bch2_bpos_to_text(&buf2, next->data->min_key);
1841 		bch_err(c,
1842 			"%s(): btree topology error:\n"
1843 			"  prev ends at   %s\n"
1844 			"  next starts at %s",
1845 			__func__, buf1.buf, buf2.buf);
1846 		printbuf_exit(&buf1);
1847 		printbuf_exit(&buf2);
1848 		bch2_topology_error(c);
1849 		ret = -EIO;
1850 		goto err;
1851 	}
1852 
1853 	bch2_bkey_format_init(&new_s);
1854 	bch2_bkey_format_add_pos(&new_s, prev->data->min_key);
1855 	__bch2_btree_calc_format(&new_s, prev);
1856 	__bch2_btree_calc_format(&new_s, next);
1857 	bch2_bkey_format_add_pos(&new_s, next->data->max_key);
1858 	new_f = bch2_bkey_format_done(&new_s);
1859 
1860 	sib_u64s = btree_node_u64s_with_format(b->nr, &b->format, &new_f) +
1861 		btree_node_u64s_with_format(m->nr, &m->format, &new_f);
1862 
1863 	if (sib_u64s > BTREE_FOREGROUND_MERGE_HYSTERESIS(c)) {
1864 		sib_u64s -= BTREE_FOREGROUND_MERGE_HYSTERESIS(c);
1865 		sib_u64s /= 2;
1866 		sib_u64s += BTREE_FOREGROUND_MERGE_HYSTERESIS(c);
1867 	}
1868 
1869 	sib_u64s = min(sib_u64s, btree_max_u64s(c));
1870 	sib_u64s = min(sib_u64s, (size_t) U16_MAX - 1);
1871 	b->sib_u64s[sib] = sib_u64s;
1872 
1873 	if (b->sib_u64s[sib] > c->btree_foreground_merge_threshold)
1874 		goto out;
1875 
1876 	parent = btree_node_parent(trans->paths + path, b);
1877 	as = bch2_btree_update_start(trans, trans->paths + path, level, false,
1878 				     BCH_TRANS_COMMIT_no_enospc|flags);
1879 	ret = PTR_ERR_OR_ZERO(as);
1880 	if (ret)
1881 		goto err;
1882 
1883 	trace_and_count(c, btree_node_merge, trans, b);
1884 
1885 	bch2_btree_interior_update_will_free_node(as, b);
1886 	bch2_btree_interior_update_will_free_node(as, m);
1887 
1888 	n = bch2_btree_node_alloc(as, trans, b->c.level);
1889 
1890 	SET_BTREE_NODE_SEQ(n->data,
1891 			   max(BTREE_NODE_SEQ(b->data),
1892 			       BTREE_NODE_SEQ(m->data)) + 1);
1893 
1894 	btree_set_min(n, prev->data->min_key);
1895 	btree_set_max(n, next->data->max_key);
1896 
1897 	n->data->format	 = new_f;
1898 	btree_node_set_format(n, new_f);
1899 
1900 	bch2_btree_sort_into(c, n, prev);
1901 	bch2_btree_sort_into(c, n, next);
1902 
1903 	bch2_btree_build_aux_trees(n);
1904 	bch2_btree_update_add_new_node(as, n);
1905 	six_unlock_write(&n->c.lock);
1906 
1907 	new_path = get_unlocked_mut_path(trans, btree, n->c.level, n->key.k.p);
1908 	six_lock_increment(&n->c.lock, SIX_LOCK_intent);
1909 	mark_btree_node_locked(trans, trans->paths + new_path, n->c.level, BTREE_NODE_INTENT_LOCKED);
1910 	bch2_btree_path_level_init(trans, trans->paths + new_path, n);
1911 
1912 	bkey_init(&delete.k);
1913 	delete.k.p = prev->key.k.p;
1914 	bch2_keylist_add(&as->parent_keys, &delete);
1915 	bch2_keylist_add(&as->parent_keys, &n->key);
1916 
1917 	bch2_trans_verify_paths(trans);
1918 
1919 	ret = bch2_btree_insert_node(as, trans, path, parent, &as->parent_keys, flags);
1920 	if (ret)
1921 		goto err_free_update;
1922 
1923 	bch2_trans_verify_paths(trans);
1924 
1925 	bch2_btree_update_get_open_buckets(as, n);
1926 	bch2_btree_node_write(c, n, SIX_LOCK_intent, 0);
1927 
1928 	bch2_btree_node_free_inmem(trans, trans->paths + path, b);
1929 	bch2_btree_node_free_inmem(trans, trans->paths + sib_path, m);
1930 
1931 	bch2_trans_node_add(trans, trans->paths + path, n);
1932 
1933 	bch2_trans_verify_paths(trans);
1934 
1935 	six_unlock_intent(&n->c.lock);
1936 
1937 	bch2_btree_update_done(as, trans);
1938 
1939 	bch2_time_stats_update(&c->times[BCH_TIME_btree_node_merge], start_time);
1940 out:
1941 err:
1942 	if (new_path)
1943 		bch2_path_put(trans, new_path, true);
1944 	bch2_path_put(trans, sib_path, true);
1945 	bch2_trans_verify_locks(trans);
1946 	return ret;
1947 err_free_update:
1948 	bch2_btree_node_free_never_used(as, trans, n);
1949 	bch2_btree_update_free(as, trans);
1950 	goto out;
1951 }
1952 
1953 int bch2_btree_node_rewrite(struct btree_trans *trans,
1954 			    struct btree_iter *iter,
1955 			    struct btree *b,
1956 			    unsigned flags)
1957 {
1958 	struct bch_fs *c = trans->c;
1959 	struct btree *n, *parent;
1960 	struct btree_update *as;
1961 	btree_path_idx_t new_path = 0;
1962 	int ret;
1963 
1964 	flags |= BCH_TRANS_COMMIT_no_enospc;
1965 
1966 	struct btree_path *path = btree_iter_path(trans, iter);
1967 	parent = btree_node_parent(path, b);
1968 	as = bch2_btree_update_start(trans, path, b->c.level, false, flags);
1969 	ret = PTR_ERR_OR_ZERO(as);
1970 	if (ret)
1971 		goto out;
1972 
1973 	bch2_btree_interior_update_will_free_node(as, b);
1974 
1975 	n = bch2_btree_node_alloc_replacement(as, trans, b);
1976 
1977 	bch2_btree_build_aux_trees(n);
1978 	bch2_btree_update_add_new_node(as, n);
1979 	six_unlock_write(&n->c.lock);
1980 
1981 	new_path = get_unlocked_mut_path(trans, iter->btree_id, n->c.level, n->key.k.p);
1982 	six_lock_increment(&n->c.lock, SIX_LOCK_intent);
1983 	mark_btree_node_locked(trans, trans->paths + new_path, n->c.level, BTREE_NODE_INTENT_LOCKED);
1984 	bch2_btree_path_level_init(trans, trans->paths + new_path, n);
1985 
1986 	trace_and_count(c, btree_node_rewrite, trans, b);
1987 
1988 	if (parent) {
1989 		bch2_keylist_add(&as->parent_keys, &n->key);
1990 		ret = bch2_btree_insert_node(as, trans, iter->path,
1991 					     parent, &as->parent_keys, flags);
1992 		if (ret)
1993 			goto err;
1994 	} else {
1995 		bch2_btree_set_root(as, trans, btree_iter_path(trans, iter), n);
1996 	}
1997 
1998 	bch2_btree_update_get_open_buckets(as, n);
1999 	bch2_btree_node_write(c, n, SIX_LOCK_intent, 0);
2000 
2001 	bch2_btree_node_free_inmem(trans, btree_iter_path(trans, iter), b);
2002 
2003 	bch2_trans_node_add(trans, trans->paths + iter->path, n);
2004 	six_unlock_intent(&n->c.lock);
2005 
2006 	bch2_btree_update_done(as, trans);
2007 out:
2008 	if (new_path)
2009 		bch2_path_put(trans, new_path, true);
2010 	bch2_trans_downgrade(trans);
2011 	return ret;
2012 err:
2013 	bch2_btree_node_free_never_used(as, trans, n);
2014 	bch2_btree_update_free(as, trans);
2015 	goto out;
2016 }
2017 
2018 struct async_btree_rewrite {
2019 	struct bch_fs		*c;
2020 	struct work_struct	work;
2021 	struct list_head	list;
2022 	enum btree_id		btree_id;
2023 	unsigned		level;
2024 	struct bpos		pos;
2025 	__le64			seq;
2026 };
2027 
2028 static int async_btree_node_rewrite_trans(struct btree_trans *trans,
2029 					  struct async_btree_rewrite *a)
2030 {
2031 	struct bch_fs *c = trans->c;
2032 	struct btree_iter iter;
2033 	struct btree *b;
2034 	int ret;
2035 
2036 	bch2_trans_node_iter_init(trans, &iter, a->btree_id, a->pos,
2037 				  BTREE_MAX_DEPTH, a->level, 0);
2038 	b = bch2_btree_iter_peek_node(&iter);
2039 	ret = PTR_ERR_OR_ZERO(b);
2040 	if (ret)
2041 		goto out;
2042 
2043 	if (!b || b->data->keys.seq != a->seq) {
2044 		struct printbuf buf = PRINTBUF;
2045 
2046 		if (b)
2047 			bch2_bkey_val_to_text(&buf, c, bkey_i_to_s_c(&b->key));
2048 		else
2049 			prt_str(&buf, "(null");
2050 		bch_info(c, "%s: node to rewrite not found:, searching for seq %llu, got\n%s",
2051 			 __func__, a->seq, buf.buf);
2052 		printbuf_exit(&buf);
2053 		goto out;
2054 	}
2055 
2056 	ret = bch2_btree_node_rewrite(trans, &iter, b, 0);
2057 out:
2058 	bch2_trans_iter_exit(trans, &iter);
2059 
2060 	return ret;
2061 }
2062 
2063 static void async_btree_node_rewrite_work(struct work_struct *work)
2064 {
2065 	struct async_btree_rewrite *a =
2066 		container_of(work, struct async_btree_rewrite, work);
2067 	struct bch_fs *c = a->c;
2068 	int ret;
2069 
2070 	ret = bch2_trans_do(c, NULL, NULL, 0,
2071 		      async_btree_node_rewrite_trans(trans, a));
2072 	bch_err_fn(c, ret);
2073 	bch2_write_ref_put(c, BCH_WRITE_REF_node_rewrite);
2074 	kfree(a);
2075 }
2076 
2077 void bch2_btree_node_rewrite_async(struct bch_fs *c, struct btree *b)
2078 {
2079 	struct async_btree_rewrite *a;
2080 	int ret;
2081 
2082 	a = kmalloc(sizeof(*a), GFP_NOFS);
2083 	if (!a) {
2084 		bch_err(c, "%s: error allocating memory", __func__);
2085 		return;
2086 	}
2087 
2088 	a->c		= c;
2089 	a->btree_id	= b->c.btree_id;
2090 	a->level	= b->c.level;
2091 	a->pos		= b->key.k.p;
2092 	a->seq		= b->data->keys.seq;
2093 	INIT_WORK(&a->work, async_btree_node_rewrite_work);
2094 
2095 	if (unlikely(!test_bit(BCH_FS_may_go_rw, &c->flags))) {
2096 		mutex_lock(&c->pending_node_rewrites_lock);
2097 		list_add(&a->list, &c->pending_node_rewrites);
2098 		mutex_unlock(&c->pending_node_rewrites_lock);
2099 		return;
2100 	}
2101 
2102 	if (!bch2_write_ref_tryget(c, BCH_WRITE_REF_node_rewrite)) {
2103 		if (test_bit(BCH_FS_started, &c->flags)) {
2104 			bch_err(c, "%s: error getting c->writes ref", __func__);
2105 			kfree(a);
2106 			return;
2107 		}
2108 
2109 		ret = bch2_fs_read_write_early(c);
2110 		bch_err_msg(c, ret, "going read-write");
2111 		if (ret) {
2112 			kfree(a);
2113 			return;
2114 		}
2115 
2116 		bch2_write_ref_get(c, BCH_WRITE_REF_node_rewrite);
2117 	}
2118 
2119 	queue_work(c->btree_interior_update_worker, &a->work);
2120 }
2121 
2122 void bch2_do_pending_node_rewrites(struct bch_fs *c)
2123 {
2124 	struct async_btree_rewrite *a, *n;
2125 
2126 	mutex_lock(&c->pending_node_rewrites_lock);
2127 	list_for_each_entry_safe(a, n, &c->pending_node_rewrites, list) {
2128 		list_del(&a->list);
2129 
2130 		bch2_write_ref_get(c, BCH_WRITE_REF_node_rewrite);
2131 		queue_work(c->btree_interior_update_worker, &a->work);
2132 	}
2133 	mutex_unlock(&c->pending_node_rewrites_lock);
2134 }
2135 
2136 void bch2_free_pending_node_rewrites(struct bch_fs *c)
2137 {
2138 	struct async_btree_rewrite *a, *n;
2139 
2140 	mutex_lock(&c->pending_node_rewrites_lock);
2141 	list_for_each_entry_safe(a, n, &c->pending_node_rewrites, list) {
2142 		list_del(&a->list);
2143 
2144 		kfree(a);
2145 	}
2146 	mutex_unlock(&c->pending_node_rewrites_lock);
2147 }
2148 
2149 static int __bch2_btree_node_update_key(struct btree_trans *trans,
2150 					struct btree_iter *iter,
2151 					struct btree *b, struct btree *new_hash,
2152 					struct bkey_i *new_key,
2153 					unsigned commit_flags,
2154 					bool skip_triggers)
2155 {
2156 	struct bch_fs *c = trans->c;
2157 	struct btree_iter iter2 = { NULL };
2158 	struct btree *parent;
2159 	int ret;
2160 
2161 	if (!skip_triggers) {
2162 		ret   = bch2_key_trigger_old(trans, b->c.btree_id, b->c.level + 1,
2163 					     bkey_i_to_s_c(&b->key),
2164 					     BTREE_TRIGGER_TRANSACTIONAL) ?:
2165 			bch2_key_trigger_new(trans, b->c.btree_id, b->c.level + 1,
2166 					     bkey_i_to_s(new_key),
2167 					     BTREE_TRIGGER_TRANSACTIONAL);
2168 		if (ret)
2169 			return ret;
2170 	}
2171 
2172 	if (new_hash) {
2173 		bkey_copy(&new_hash->key, new_key);
2174 		ret = bch2_btree_node_hash_insert(&c->btree_cache,
2175 				new_hash, b->c.level, b->c.btree_id);
2176 		BUG_ON(ret);
2177 	}
2178 
2179 	parent = btree_node_parent(btree_iter_path(trans, iter), b);
2180 	if (parent) {
2181 		bch2_trans_copy_iter(&iter2, iter);
2182 
2183 		iter2.path = bch2_btree_path_make_mut(trans, iter2.path,
2184 				iter2.flags & BTREE_ITER_INTENT,
2185 				_THIS_IP_);
2186 
2187 		struct btree_path *path2 = btree_iter_path(trans, &iter2);
2188 		BUG_ON(path2->level != b->c.level);
2189 		BUG_ON(!bpos_eq(path2->pos, new_key->k.p));
2190 
2191 		btree_path_set_level_up(trans, path2);
2192 
2193 		trans->paths_sorted = false;
2194 
2195 		ret   = bch2_btree_iter_traverse(&iter2) ?:
2196 			bch2_trans_update(trans, &iter2, new_key, BTREE_TRIGGER_NORUN);
2197 		if (ret)
2198 			goto err;
2199 	} else {
2200 		BUG_ON(btree_node_root(c, b) != b);
2201 
2202 		struct jset_entry *e = bch2_trans_jset_entry_alloc(trans,
2203 				       jset_u64s(new_key->k.u64s));
2204 		ret = PTR_ERR_OR_ZERO(e);
2205 		if (ret)
2206 			return ret;
2207 
2208 		journal_entry_set(e,
2209 				  BCH_JSET_ENTRY_btree_root,
2210 				  b->c.btree_id, b->c.level,
2211 				  new_key, new_key->k.u64s);
2212 	}
2213 
2214 	ret = bch2_trans_commit(trans, NULL, NULL, commit_flags);
2215 	if (ret)
2216 		goto err;
2217 
2218 	bch2_btree_node_lock_write_nofail(trans, btree_iter_path(trans, iter), &b->c);
2219 
2220 	if (new_hash) {
2221 		mutex_lock(&c->btree_cache.lock);
2222 		bch2_btree_node_hash_remove(&c->btree_cache, new_hash);
2223 		bch2_btree_node_hash_remove(&c->btree_cache, b);
2224 
2225 		bkey_copy(&b->key, new_key);
2226 		ret = __bch2_btree_node_hash_insert(&c->btree_cache, b);
2227 		BUG_ON(ret);
2228 		mutex_unlock(&c->btree_cache.lock);
2229 	} else {
2230 		bkey_copy(&b->key, new_key);
2231 	}
2232 
2233 	bch2_btree_node_unlock_write(trans, btree_iter_path(trans, iter), b);
2234 out:
2235 	bch2_trans_iter_exit(trans, &iter2);
2236 	return ret;
2237 err:
2238 	if (new_hash) {
2239 		mutex_lock(&c->btree_cache.lock);
2240 		bch2_btree_node_hash_remove(&c->btree_cache, b);
2241 		mutex_unlock(&c->btree_cache.lock);
2242 	}
2243 	goto out;
2244 }
2245 
2246 int bch2_btree_node_update_key(struct btree_trans *trans, struct btree_iter *iter,
2247 			       struct btree *b, struct bkey_i *new_key,
2248 			       unsigned commit_flags, bool skip_triggers)
2249 {
2250 	struct bch_fs *c = trans->c;
2251 	struct btree *new_hash = NULL;
2252 	struct btree_path *path = btree_iter_path(trans, iter);
2253 	struct closure cl;
2254 	int ret = 0;
2255 
2256 	ret = bch2_btree_path_upgrade(trans, path, b->c.level + 1);
2257 	if (ret)
2258 		return ret;
2259 
2260 	closure_init_stack(&cl);
2261 
2262 	/*
2263 	 * check btree_ptr_hash_val() after @b is locked by
2264 	 * btree_iter_traverse():
2265 	 */
2266 	if (btree_ptr_hash_val(new_key) != b->hash_val) {
2267 		ret = bch2_btree_cache_cannibalize_lock(trans, &cl);
2268 		if (ret) {
2269 			ret = drop_locks_do(trans, (closure_sync(&cl), 0));
2270 			if (ret)
2271 				return ret;
2272 		}
2273 
2274 		new_hash = bch2_btree_node_mem_alloc(trans, false);
2275 	}
2276 
2277 	path->intent_ref++;
2278 	ret = __bch2_btree_node_update_key(trans, iter, b, new_hash, new_key,
2279 					   commit_flags, skip_triggers);
2280 	--path->intent_ref;
2281 
2282 	if (new_hash) {
2283 		mutex_lock(&c->btree_cache.lock);
2284 		list_move(&new_hash->list, &c->btree_cache.freeable);
2285 		mutex_unlock(&c->btree_cache.lock);
2286 
2287 		six_unlock_write(&new_hash->c.lock);
2288 		six_unlock_intent(&new_hash->c.lock);
2289 	}
2290 	closure_sync(&cl);
2291 	bch2_btree_cache_cannibalize_unlock(trans);
2292 	return ret;
2293 }
2294 
2295 int bch2_btree_node_update_key_get_iter(struct btree_trans *trans,
2296 					struct btree *b, struct bkey_i *new_key,
2297 					unsigned commit_flags, bool skip_triggers)
2298 {
2299 	struct btree_iter iter;
2300 	int ret;
2301 
2302 	bch2_trans_node_iter_init(trans, &iter, b->c.btree_id, b->key.k.p,
2303 				  BTREE_MAX_DEPTH, b->c.level,
2304 				  BTREE_ITER_INTENT);
2305 	ret = bch2_btree_iter_traverse(&iter);
2306 	if (ret)
2307 		goto out;
2308 
2309 	/* has node been freed? */
2310 	if (btree_iter_path(trans, &iter)->l[b->c.level].b != b) {
2311 		/* node has been freed: */
2312 		BUG_ON(!btree_node_dying(b));
2313 		goto out;
2314 	}
2315 
2316 	BUG_ON(!btree_node_hashed(b));
2317 
2318 	struct bch_extent_ptr *ptr;
2319 	bch2_bkey_drop_ptrs(bkey_i_to_s(new_key), ptr,
2320 			    !bch2_bkey_has_device(bkey_i_to_s(&b->key), ptr->dev));
2321 
2322 	ret = bch2_btree_node_update_key(trans, &iter, b, new_key,
2323 					 commit_flags, skip_triggers);
2324 out:
2325 	bch2_trans_iter_exit(trans, &iter);
2326 	return ret;
2327 }
2328 
2329 /* Init code: */
2330 
2331 /*
2332  * Only for filesystem bringup, when first reading the btree roots or allocating
2333  * btree roots when initializing a new filesystem:
2334  */
2335 void bch2_btree_set_root_for_read(struct bch_fs *c, struct btree *b)
2336 {
2337 	BUG_ON(btree_node_root(c, b));
2338 
2339 	bch2_btree_set_root_inmem(c, b);
2340 }
2341 
2342 static int __bch2_btree_root_alloc(struct btree_trans *trans, enum btree_id id)
2343 {
2344 	struct bch_fs *c = trans->c;
2345 	struct closure cl;
2346 	struct btree *b;
2347 	int ret;
2348 
2349 	closure_init_stack(&cl);
2350 
2351 	do {
2352 		ret = bch2_btree_cache_cannibalize_lock(trans, &cl);
2353 		closure_sync(&cl);
2354 	} while (ret);
2355 
2356 	b = bch2_btree_node_mem_alloc(trans, false);
2357 	bch2_btree_cache_cannibalize_unlock(trans);
2358 
2359 	set_btree_node_fake(b);
2360 	set_btree_node_need_rewrite(b);
2361 	b->c.level	= 0;
2362 	b->c.btree_id	= id;
2363 
2364 	bkey_btree_ptr_init(&b->key);
2365 	b->key.k.p = SPOS_MAX;
2366 	*((u64 *) bkey_i_to_btree_ptr(&b->key)->v.start) = U64_MAX - id;
2367 
2368 	bch2_bset_init_first(b, &b->data->keys);
2369 	bch2_btree_build_aux_trees(b);
2370 
2371 	b->data->flags = 0;
2372 	btree_set_min(b, POS_MIN);
2373 	btree_set_max(b, SPOS_MAX);
2374 	b->data->format = bch2_btree_calc_format(b);
2375 	btree_node_set_format(b, b->data->format);
2376 
2377 	ret = bch2_btree_node_hash_insert(&c->btree_cache, b,
2378 					  b->c.level, b->c.btree_id);
2379 	BUG_ON(ret);
2380 
2381 	bch2_btree_set_root_inmem(c, b);
2382 
2383 	six_unlock_write(&b->c.lock);
2384 	six_unlock_intent(&b->c.lock);
2385 	return 0;
2386 }
2387 
2388 void bch2_btree_root_alloc(struct bch_fs *c, enum btree_id id)
2389 {
2390 	bch2_trans_run(c, __bch2_btree_root_alloc(trans, id));
2391 }
2392 
2393 void bch2_btree_updates_to_text(struct printbuf *out, struct bch_fs *c)
2394 {
2395 	struct btree_update *as;
2396 
2397 	mutex_lock(&c->btree_interior_update_lock);
2398 	list_for_each_entry(as, &c->btree_interior_update_list, list)
2399 		prt_printf(out, "%p m %u w %u r %u j %llu\n",
2400 		       as,
2401 		       as->mode,
2402 		       as->nodes_written,
2403 		       closure_nr_remaining(&as->cl),
2404 		       as->journal.seq);
2405 	mutex_unlock(&c->btree_interior_update_lock);
2406 }
2407 
2408 static bool bch2_btree_interior_updates_pending(struct bch_fs *c)
2409 {
2410 	bool ret;
2411 
2412 	mutex_lock(&c->btree_interior_update_lock);
2413 	ret = !list_empty(&c->btree_interior_update_list);
2414 	mutex_unlock(&c->btree_interior_update_lock);
2415 
2416 	return ret;
2417 }
2418 
2419 bool bch2_btree_interior_updates_flush(struct bch_fs *c)
2420 {
2421 	bool ret = bch2_btree_interior_updates_pending(c);
2422 
2423 	if (ret)
2424 		closure_wait_event(&c->btree_interior_update_wait,
2425 				   !bch2_btree_interior_updates_pending(c));
2426 	return ret;
2427 }
2428 
2429 void bch2_journal_entry_to_btree_root(struct bch_fs *c, struct jset_entry *entry)
2430 {
2431 	struct btree_root *r = bch2_btree_id_root(c, entry->btree_id);
2432 
2433 	mutex_lock(&c->btree_root_lock);
2434 
2435 	r->level = entry->level;
2436 	r->alive = true;
2437 	bkey_copy(&r->key, (struct bkey_i *) entry->start);
2438 
2439 	mutex_unlock(&c->btree_root_lock);
2440 }
2441 
2442 struct jset_entry *
2443 bch2_btree_roots_to_journal_entries(struct bch_fs *c,
2444 				    struct jset_entry *end,
2445 				    unsigned long skip)
2446 {
2447 	unsigned i;
2448 
2449 	mutex_lock(&c->btree_root_lock);
2450 
2451 	for (i = 0; i < btree_id_nr_alive(c); i++) {
2452 		struct btree_root *r = bch2_btree_id_root(c, i);
2453 
2454 		if (r->alive && !test_bit(i, &skip)) {
2455 			journal_entry_set(end, BCH_JSET_ENTRY_btree_root,
2456 					  i, r->level, &r->key, r->key.k.u64s);
2457 			end = vstruct_next(end);
2458 		}
2459 	}
2460 
2461 	mutex_unlock(&c->btree_root_lock);
2462 
2463 	return end;
2464 }
2465 
2466 void bch2_fs_btree_interior_update_exit(struct bch_fs *c)
2467 {
2468 	if (c->btree_interior_update_worker)
2469 		destroy_workqueue(c->btree_interior_update_worker);
2470 	mempool_exit(&c->btree_interior_update_pool);
2471 }
2472 
2473 void bch2_fs_btree_interior_update_init_early(struct bch_fs *c)
2474 {
2475 	mutex_init(&c->btree_reserve_cache_lock);
2476 	INIT_LIST_HEAD(&c->btree_interior_update_list);
2477 	INIT_LIST_HEAD(&c->btree_interior_updates_unwritten);
2478 	mutex_init(&c->btree_interior_update_lock);
2479 	INIT_WORK(&c->btree_interior_update_work, btree_interior_update_work);
2480 
2481 	INIT_LIST_HEAD(&c->pending_node_rewrites);
2482 	mutex_init(&c->pending_node_rewrites_lock);
2483 }
2484 
2485 int bch2_fs_btree_interior_update_init(struct bch_fs *c)
2486 {
2487 	c->btree_interior_update_worker =
2488 		alloc_workqueue("btree_update", WQ_UNBOUND|WQ_MEM_RECLAIM, 1);
2489 	if (!c->btree_interior_update_worker)
2490 		return -BCH_ERR_ENOMEM_btree_interior_update_worker_init;
2491 
2492 	if (mempool_init_kmalloc_pool(&c->btree_interior_update_pool, 1,
2493 				      sizeof(struct btree_update)))
2494 		return -BCH_ERR_ENOMEM_btree_interior_update_pool_init;
2495 
2496 	return 0;
2497 }
2498