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