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