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