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