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