xref: /linux/fs/bcachefs/btree_trans_commit.c (revision 24168c5e6dfbdd5b414f048f47f75d64533296ca)
1 // SPDX-License-Identifier: GPL-2.0
2 
3 #include "bcachefs.h"
4 #include "alloc_foreground.h"
5 #include "btree_gc.h"
6 #include "btree_io.h"
7 #include "btree_iter.h"
8 #include "btree_journal_iter.h"
9 #include "btree_key_cache.h"
10 #include "btree_update_interior.h"
11 #include "btree_write_buffer.h"
12 #include "buckets.h"
13 #include "errcode.h"
14 #include "error.h"
15 #include "journal.h"
16 #include "journal_io.h"
17 #include "journal_reclaim.h"
18 #include "replicas.h"
19 #include "snapshot.h"
20 
21 #include <linux/prefetch.h>
22 
23 static const char * const trans_commit_flags_strs[] = {
24 #define x(n, ...) #n,
25 	BCH_TRANS_COMMIT_FLAGS()
26 #undef x
27 	NULL
28 };
29 
30 void bch2_trans_commit_flags_to_text(struct printbuf *out, enum bch_trans_commit_flags flags)
31 {
32 	enum bch_watermark watermark = flags & BCH_WATERMARK_MASK;
33 
34 	prt_printf(out, "watermark=%s", bch2_watermarks[watermark]);
35 
36 	flags >>= BCH_WATERMARK_BITS;
37 	if (flags) {
38 		prt_char(out, ' ');
39 		bch2_prt_bitflags(out, trans_commit_flags_strs, flags);
40 	}
41 }
42 
43 static void verify_update_old_key(struct btree_trans *trans, struct btree_insert_entry *i)
44 {
45 #ifdef CONFIG_BCACHEFS_DEBUG
46 	struct bch_fs *c = trans->c;
47 	struct bkey u;
48 	struct bkey_s_c k = bch2_btree_path_peek_slot_exact(trans->paths + i->path, &u);
49 
50 	if (unlikely(trans->journal_replay_not_finished)) {
51 		struct bkey_i *j_k =
52 			bch2_journal_keys_peek_slot(c, i->btree_id, i->level, i->k->k.p);
53 
54 		if (j_k)
55 			k = bkey_i_to_s_c(j_k);
56 	}
57 
58 	u = *k.k;
59 	u.needs_whiteout = i->old_k.needs_whiteout;
60 
61 	BUG_ON(memcmp(&i->old_k, &u, sizeof(struct bkey)));
62 	BUG_ON(i->old_v != k.v);
63 #endif
64 }
65 
66 static inline struct btree_path_level *insert_l(struct btree_trans *trans, struct btree_insert_entry *i)
67 {
68 	return (trans->paths + i->path)->l + i->level;
69 }
70 
71 static inline bool same_leaf_as_prev(struct btree_trans *trans,
72 				     struct btree_insert_entry *i)
73 {
74 	return i != trans->updates &&
75 		insert_l(trans, &i[0])->b == insert_l(trans, &i[-1])->b;
76 }
77 
78 static inline bool same_leaf_as_next(struct btree_trans *trans,
79 				     struct btree_insert_entry *i)
80 {
81 	return i + 1 < trans->updates + trans->nr_updates &&
82 		insert_l(trans, &i[0])->b == insert_l(trans, &i[1])->b;
83 }
84 
85 inline void bch2_btree_node_prep_for_write(struct btree_trans *trans,
86 					   struct btree_path *path,
87 					   struct btree *b)
88 {
89 	struct bch_fs *c = trans->c;
90 
91 	if (unlikely(btree_node_just_written(b)) &&
92 	    bch2_btree_post_write_cleanup(c, b))
93 		bch2_trans_node_reinit_iter(trans, b);
94 
95 	/*
96 	 * If the last bset has been written, or if it's gotten too big - start
97 	 * a new bset to insert into:
98 	 */
99 	if (want_new_bset(c, b))
100 		bch2_btree_init_next(trans, b);
101 }
102 
103 static noinline int trans_lock_write_fail(struct btree_trans *trans, struct btree_insert_entry *i)
104 {
105 	while (--i >= trans->updates) {
106 		if (same_leaf_as_prev(trans, i))
107 			continue;
108 
109 		bch2_btree_node_unlock_write(trans, trans->paths + i->path, insert_l(trans, i)->b);
110 	}
111 
112 	trace_and_count(trans->c, trans_restart_would_deadlock_write, trans);
113 	return btree_trans_restart(trans, BCH_ERR_transaction_restart_would_deadlock_write);
114 }
115 
116 static inline int bch2_trans_lock_write(struct btree_trans *trans)
117 {
118 	EBUG_ON(trans->write_locked);
119 
120 	trans_for_each_update(trans, i) {
121 		if (same_leaf_as_prev(trans, i))
122 			continue;
123 
124 		if (bch2_btree_node_lock_write(trans, trans->paths + i->path, &insert_l(trans, i)->b->c))
125 			return trans_lock_write_fail(trans, i);
126 
127 		if (!i->cached)
128 			bch2_btree_node_prep_for_write(trans, trans->paths + i->path, insert_l(trans, i)->b);
129 	}
130 
131 	trans->write_locked = true;
132 	return 0;
133 }
134 
135 static inline void bch2_trans_unlock_write(struct btree_trans *trans)
136 {
137 	if (likely(trans->write_locked)) {
138 		trans_for_each_update(trans, i)
139 			if (!same_leaf_as_prev(trans, i))
140 				bch2_btree_node_unlock_write_inlined(trans,
141 						trans->paths + i->path, insert_l(trans, i)->b);
142 		trans->write_locked = false;
143 	}
144 }
145 
146 /* Inserting into a given leaf node (last stage of insert): */
147 
148 /* Handle overwrites and do insert, for non extents: */
149 bool bch2_btree_bset_insert_key(struct btree_trans *trans,
150 				struct btree_path *path,
151 				struct btree *b,
152 				struct btree_node_iter *node_iter,
153 				struct bkey_i *insert)
154 {
155 	struct bkey_packed *k;
156 	unsigned clobber_u64s = 0, new_u64s = 0;
157 
158 	EBUG_ON(btree_node_just_written(b));
159 	EBUG_ON(bset_written(b, btree_bset_last(b)));
160 	EBUG_ON(bkey_deleted(&insert->k) && bkey_val_u64s(&insert->k));
161 	EBUG_ON(bpos_lt(insert->k.p, b->data->min_key));
162 	EBUG_ON(bpos_gt(insert->k.p, b->data->max_key));
163 	EBUG_ON(insert->k.u64s > bch2_btree_keys_u64s_remaining(b));
164 	EBUG_ON(!b->c.level && !bpos_eq(insert->k.p, path->pos));
165 
166 	k = bch2_btree_node_iter_peek_all(node_iter, b);
167 	if (k && bkey_cmp_left_packed(b, k, &insert->k.p))
168 		k = NULL;
169 
170 	/* @k is the key being overwritten/deleted, if any: */
171 	EBUG_ON(k && bkey_deleted(k));
172 
173 	/* Deleting, but not found? nothing to do: */
174 	if (bkey_deleted(&insert->k) && !k)
175 		return false;
176 
177 	if (bkey_deleted(&insert->k)) {
178 		/* Deleting: */
179 		btree_account_key_drop(b, k);
180 		k->type = KEY_TYPE_deleted;
181 
182 		if (k->needs_whiteout)
183 			push_whiteout(b, insert->k.p);
184 		k->needs_whiteout = false;
185 
186 		if (k >= btree_bset_last(b)->start) {
187 			clobber_u64s = k->u64s;
188 			bch2_bset_delete(b, k, clobber_u64s);
189 			goto fix_iter;
190 		} else {
191 			bch2_btree_path_fix_key_modified(trans, b, k);
192 		}
193 
194 		return true;
195 	}
196 
197 	if (k) {
198 		/* Overwriting: */
199 		btree_account_key_drop(b, k);
200 		k->type = KEY_TYPE_deleted;
201 
202 		insert->k.needs_whiteout = k->needs_whiteout;
203 		k->needs_whiteout = false;
204 
205 		if (k >= btree_bset_last(b)->start) {
206 			clobber_u64s = k->u64s;
207 			goto overwrite;
208 		} else {
209 			bch2_btree_path_fix_key_modified(trans, b, k);
210 		}
211 	}
212 
213 	k = bch2_btree_node_iter_bset_pos(node_iter, b, bset_tree_last(b));
214 overwrite:
215 	bch2_bset_insert(b, node_iter, k, insert, clobber_u64s);
216 	new_u64s = k->u64s;
217 fix_iter:
218 	if (clobber_u64s != new_u64s)
219 		bch2_btree_node_iter_fix(trans, path, b, node_iter, k,
220 					 clobber_u64s, new_u64s);
221 	return true;
222 }
223 
224 static int __btree_node_flush(struct journal *j, struct journal_entry_pin *pin,
225 			       unsigned i, u64 seq)
226 {
227 	struct bch_fs *c = container_of(j, struct bch_fs, journal);
228 	struct btree_write *w = container_of(pin, struct btree_write, journal);
229 	struct btree *b = container_of(w, struct btree, writes[i]);
230 	struct btree_trans *trans = bch2_trans_get(c);
231 	unsigned long old, new, v;
232 	unsigned idx = w - b->writes;
233 
234 	btree_node_lock_nopath_nofail(trans, &b->c, SIX_LOCK_read);
235 	v = READ_ONCE(b->flags);
236 
237 	do {
238 		old = new = v;
239 
240 		if (!(old & (1 << BTREE_NODE_dirty)) ||
241 		    !!(old & (1 << BTREE_NODE_write_idx)) != idx ||
242 		    w->journal.seq != seq)
243 			break;
244 
245 		new &= ~BTREE_WRITE_TYPE_MASK;
246 		new |= BTREE_WRITE_journal_reclaim;
247 		new |= 1 << BTREE_NODE_need_write;
248 	} while ((v = cmpxchg(&b->flags, old, new)) != old);
249 
250 	btree_node_write_if_need(c, b, SIX_LOCK_read);
251 	six_unlock_read(&b->c.lock);
252 
253 	bch2_trans_put(trans);
254 	return 0;
255 }
256 
257 int bch2_btree_node_flush0(struct journal *j, struct journal_entry_pin *pin, u64 seq)
258 {
259 	return __btree_node_flush(j, pin, 0, seq);
260 }
261 
262 int bch2_btree_node_flush1(struct journal *j, struct journal_entry_pin *pin, u64 seq)
263 {
264 	return __btree_node_flush(j, pin, 1, seq);
265 }
266 
267 inline void bch2_btree_add_journal_pin(struct bch_fs *c,
268 				       struct btree *b, u64 seq)
269 {
270 	struct btree_write *w = btree_current_write(b);
271 
272 	bch2_journal_pin_add(&c->journal, seq, &w->journal,
273 			     btree_node_write_idx(b) == 0
274 			     ? bch2_btree_node_flush0
275 			     : bch2_btree_node_flush1);
276 }
277 
278 /**
279  * bch2_btree_insert_key_leaf() - insert a key one key into a leaf node
280  * @trans:		btree transaction object
281  * @path:		path pointing to @insert's pos
282  * @insert:		key to insert
283  * @journal_seq:	sequence number of journal reservation
284  */
285 inline void bch2_btree_insert_key_leaf(struct btree_trans *trans,
286 				       struct btree_path *path,
287 				       struct bkey_i *insert,
288 				       u64 journal_seq)
289 {
290 	struct bch_fs *c = trans->c;
291 	struct btree *b = path_l(path)->b;
292 	struct bset_tree *t = bset_tree_last(b);
293 	struct bset *i = bset(b, t);
294 	int old_u64s = bset_u64s(t);
295 	int old_live_u64s = b->nr.live_u64s;
296 	int live_u64s_added, u64s_added;
297 
298 	if (unlikely(!bch2_btree_bset_insert_key(trans, path, b,
299 					&path_l(path)->iter, insert)))
300 		return;
301 
302 	i->journal_seq = cpu_to_le64(max(journal_seq, le64_to_cpu(i->journal_seq)));
303 
304 	bch2_btree_add_journal_pin(c, b, journal_seq);
305 
306 	if (unlikely(!btree_node_dirty(b))) {
307 		EBUG_ON(test_bit(BCH_FS_clean_shutdown, &c->flags));
308 		set_btree_node_dirty_acct(c, b);
309 	}
310 
311 	live_u64s_added = (int) b->nr.live_u64s - old_live_u64s;
312 	u64s_added = (int) bset_u64s(t) - old_u64s;
313 
314 	if (b->sib_u64s[0] != U16_MAX && live_u64s_added < 0)
315 		b->sib_u64s[0] = max(0, (int) b->sib_u64s[0] + live_u64s_added);
316 	if (b->sib_u64s[1] != U16_MAX && live_u64s_added < 0)
317 		b->sib_u64s[1] = max(0, (int) b->sib_u64s[1] + live_u64s_added);
318 
319 	if (u64s_added > live_u64s_added &&
320 	    bch2_maybe_compact_whiteouts(c, b))
321 		bch2_trans_node_reinit_iter(trans, b);
322 }
323 
324 /* Cached btree updates: */
325 
326 /* Normal update interface: */
327 
328 static inline void btree_insert_entry_checks(struct btree_trans *trans,
329 					     struct btree_insert_entry *i)
330 {
331 	struct btree_path *path = trans->paths + i->path;
332 
333 	BUG_ON(!bpos_eq(i->k->k.p, path->pos));
334 	BUG_ON(i->cached	!= path->cached);
335 	BUG_ON(i->level		!= path->level);
336 	BUG_ON(i->btree_id	!= path->btree_id);
337 	EBUG_ON(!i->level &&
338 		btree_type_has_snapshots(i->btree_id) &&
339 		!(i->flags & BTREE_UPDATE_internal_snapshot_node) &&
340 		test_bit(JOURNAL_replay_done, &trans->c->journal.flags) &&
341 		i->k->k.p.snapshot &&
342 		bch2_snapshot_is_internal_node(trans->c, i->k->k.p.snapshot) > 0);
343 }
344 
345 static __always_inline int bch2_trans_journal_res_get(struct btree_trans *trans,
346 						      unsigned flags)
347 {
348 	return bch2_journal_res_get(&trans->c->journal, &trans->journal_res,
349 				    trans->journal_u64s, flags);
350 }
351 
352 #define JSET_ENTRY_LOG_U64s		4
353 
354 static noinline void journal_transaction_name(struct btree_trans *trans)
355 {
356 	struct bch_fs *c = trans->c;
357 	struct journal *j = &c->journal;
358 	struct jset_entry *entry =
359 		bch2_journal_add_entry(j, &trans->journal_res,
360 				       BCH_JSET_ENTRY_log, 0, 0,
361 				       JSET_ENTRY_LOG_U64s);
362 	struct jset_entry_log *l =
363 		container_of(entry, struct jset_entry_log, entry);
364 
365 	strncpy(l->d, trans->fn, JSET_ENTRY_LOG_U64s * sizeof(u64));
366 }
367 
368 static inline int btree_key_can_insert(struct btree_trans *trans,
369 				       struct btree *b, unsigned u64s)
370 {
371 	if (!bch2_btree_node_insert_fits(b, u64s))
372 		return -BCH_ERR_btree_insert_btree_node_full;
373 
374 	return 0;
375 }
376 
377 noinline static int
378 btree_key_can_insert_cached_slowpath(struct btree_trans *trans, unsigned flags,
379 				     struct btree_path *path, unsigned new_u64s)
380 {
381 	struct bkey_cached *ck = (void *) path->l[0].b;
382 	struct bkey_i *new_k;
383 	int ret;
384 
385 	bch2_trans_unlock_write(trans);
386 	bch2_trans_unlock(trans);
387 
388 	new_k = kmalloc(new_u64s * sizeof(u64), GFP_KERNEL);
389 	if (!new_k) {
390 		bch_err(trans->c, "error allocating memory for key cache key, btree %s u64s %u",
391 			bch2_btree_id_str(path->btree_id), new_u64s);
392 		return -BCH_ERR_ENOMEM_btree_key_cache_insert;
393 	}
394 
395 	ret =   bch2_trans_relock(trans) ?:
396 		bch2_trans_lock_write(trans);
397 	if (unlikely(ret)) {
398 		kfree(new_k);
399 		return ret;
400 	}
401 
402 	memcpy(new_k, ck->k, ck->u64s * sizeof(u64));
403 
404 	trans_for_each_update(trans, i)
405 		if (i->old_v == &ck->k->v)
406 			i->old_v = &new_k->v;
407 
408 	kfree(ck->k);
409 	ck->u64s	= new_u64s;
410 	ck->k		= new_k;
411 	return 0;
412 }
413 
414 static int btree_key_can_insert_cached(struct btree_trans *trans, unsigned flags,
415 				       struct btree_path *path, unsigned u64s)
416 {
417 	struct bch_fs *c = trans->c;
418 	struct bkey_cached *ck = (void *) path->l[0].b;
419 	unsigned new_u64s;
420 	struct bkey_i *new_k;
421 	unsigned watermark = flags & BCH_WATERMARK_MASK;
422 
423 	EBUG_ON(path->level);
424 
425 	if (watermark < BCH_WATERMARK_reclaim &&
426 	    !test_bit(BKEY_CACHED_DIRTY, &ck->flags) &&
427 	    bch2_btree_key_cache_must_wait(c))
428 		return -BCH_ERR_btree_insert_need_journal_reclaim;
429 
430 	/*
431 	 * bch2_varint_decode can read past the end of the buffer by at most 7
432 	 * bytes (it won't be used):
433 	 */
434 	u64s += 1;
435 
436 	if (u64s <= ck->u64s)
437 		return 0;
438 
439 	new_u64s	= roundup_pow_of_two(u64s);
440 	new_k		= krealloc(ck->k, new_u64s * sizeof(u64), GFP_NOWAIT|__GFP_NOWARN);
441 	if (unlikely(!new_k))
442 		return btree_key_can_insert_cached_slowpath(trans, flags, path, new_u64s);
443 
444 	trans_for_each_update(trans, i)
445 		if (i->old_v == &ck->k->v)
446 			i->old_v = &new_k->v;
447 
448 	ck->u64s	= new_u64s;
449 	ck->k		= new_k;
450 	return 0;
451 }
452 
453 /* Triggers: */
454 
455 static int run_one_mem_trigger(struct btree_trans *trans,
456 			       struct btree_insert_entry *i,
457 			       unsigned flags)
458 {
459 	struct bkey_s_c old = { &i->old_k, i->old_v };
460 	struct bkey_i *new = i->k;
461 	const struct bkey_ops *old_ops = bch2_bkey_type_ops(old.k->type);
462 	const struct bkey_ops *new_ops = bch2_bkey_type_ops(i->k->k.type);
463 	int ret;
464 
465 	verify_update_old_key(trans, i);
466 
467 	if (unlikely(flags & BTREE_TRIGGER_norun))
468 		return 0;
469 
470 	if (old_ops->trigger == new_ops->trigger) {
471 		ret   = bch2_key_trigger(trans, i->btree_id, i->level,
472 				old, bkey_i_to_s(new),
473 				BTREE_TRIGGER_insert|BTREE_TRIGGER_overwrite|flags);
474 	} else {
475 		ret   = bch2_key_trigger_new(trans, i->btree_id, i->level,
476 				bkey_i_to_s(new), flags) ?:
477 			bch2_key_trigger_old(trans, i->btree_id, i->level,
478 				old, flags);
479 	}
480 
481 	return ret;
482 }
483 
484 static int run_one_trans_trigger(struct btree_trans *trans, struct btree_insert_entry *i,
485 				 bool overwrite)
486 {
487 	/*
488 	 * Transactional triggers create new btree_insert_entries, so we can't
489 	 * pass them a pointer to a btree_insert_entry, that memory is going to
490 	 * move:
491 	 */
492 	struct bkey old_k = i->old_k;
493 	struct bkey_s_c old = { &old_k, i->old_v };
494 	const struct bkey_ops *old_ops = bch2_bkey_type_ops(old.k->type);
495 	const struct bkey_ops *new_ops = bch2_bkey_type_ops(i->k->k.type);
496 	unsigned flags = i->flags|BTREE_TRIGGER_transactional;
497 
498 	verify_update_old_key(trans, i);
499 
500 	if ((i->flags & BTREE_TRIGGER_norun) ||
501 	    !(BTREE_NODE_TYPE_HAS_TRANS_TRIGGERS & (1U << i->bkey_type)))
502 		return 0;
503 
504 	if (!i->insert_trigger_run &&
505 	    !i->overwrite_trigger_run &&
506 	    old_ops->trigger == new_ops->trigger) {
507 		i->overwrite_trigger_run = true;
508 		i->insert_trigger_run = true;
509 		return bch2_key_trigger(trans, i->btree_id, i->level, old, bkey_i_to_s(i->k),
510 					BTREE_TRIGGER_insert|
511 					BTREE_TRIGGER_overwrite|flags) ?: 1;
512 	} else if (overwrite && !i->overwrite_trigger_run) {
513 		i->overwrite_trigger_run = true;
514 		return bch2_key_trigger_old(trans, i->btree_id, i->level, old, flags) ?: 1;
515 	} else if (!overwrite && !i->insert_trigger_run) {
516 		i->insert_trigger_run = true;
517 		return bch2_key_trigger_new(trans, i->btree_id, i->level, bkey_i_to_s(i->k), flags) ?: 1;
518 	} else {
519 		return 0;
520 	}
521 }
522 
523 static int run_btree_triggers(struct btree_trans *trans, enum btree_id btree_id,
524 			      unsigned btree_id_start)
525 {
526 	bool trans_trigger_run;
527 	int ret, overwrite;
528 
529 	for (overwrite = 1; overwrite >= 0; --overwrite) {
530 
531 		/*
532 		 * Running triggers will append more updates to the list of updates as
533 		 * we're walking it:
534 		 */
535 		do {
536 			trans_trigger_run = false;
537 
538 			for (unsigned i = btree_id_start;
539 			     i < trans->nr_updates && trans->updates[i].btree_id <= btree_id;
540 			     i++) {
541 				if (trans->updates[i].btree_id != btree_id)
542 					continue;
543 
544 				ret = run_one_trans_trigger(trans, trans->updates + i, overwrite);
545 				if (ret < 0)
546 					return ret;
547 				if (ret)
548 					trans_trigger_run = true;
549 			}
550 		} while (trans_trigger_run);
551 	}
552 
553 	return 0;
554 }
555 
556 static int bch2_trans_commit_run_triggers(struct btree_trans *trans)
557 {
558 	unsigned btree_id = 0, btree_id_start = 0;
559 	int ret = 0;
560 
561 	/*
562 	 *
563 	 * For a given btree, this algorithm runs insert triggers before
564 	 * overwrite triggers: this is so that when extents are being moved
565 	 * (e.g. by FALLOCATE_FL_INSERT_RANGE), we don't drop references before
566 	 * they are re-added.
567 	 */
568 	for (btree_id = 0; btree_id < BTREE_ID_NR; btree_id++) {
569 		if (btree_id == BTREE_ID_alloc)
570 			continue;
571 
572 		while (btree_id_start < trans->nr_updates &&
573 		       trans->updates[btree_id_start].btree_id < btree_id)
574 			btree_id_start++;
575 
576 		ret = run_btree_triggers(trans, btree_id, btree_id_start);
577 		if (ret)
578 			return ret;
579 	}
580 
581 	for (unsigned idx = 0; idx < trans->nr_updates; idx++) {
582 		struct btree_insert_entry *i = trans->updates + idx;
583 
584 		if (i->btree_id > BTREE_ID_alloc)
585 			break;
586 		if (i->btree_id == BTREE_ID_alloc) {
587 			ret = run_btree_triggers(trans, BTREE_ID_alloc, idx);
588 			if (ret)
589 				return ret;
590 			break;
591 		}
592 	}
593 
594 #ifdef CONFIG_BCACHEFS_DEBUG
595 	trans_for_each_update(trans, i)
596 		BUG_ON(!(i->flags & BTREE_TRIGGER_norun) &&
597 		       (BTREE_NODE_TYPE_HAS_TRANS_TRIGGERS & (1U << i->bkey_type)) &&
598 		       (!i->insert_trigger_run || !i->overwrite_trigger_run));
599 #endif
600 	return 0;
601 }
602 
603 static noinline int bch2_trans_commit_run_gc_triggers(struct btree_trans *trans)
604 {
605 	trans_for_each_update(trans, i) {
606 		/*
607 		 * XXX: synchronization of cached update triggers with gc
608 		 * XXX: synchronization of interior node updates with gc
609 		 */
610 		BUG_ON(i->cached || i->level);
611 
612 		if (btree_node_type_needs_gc(__btree_node_type(i->level, i->btree_id)) &&
613 		    gc_visited(trans->c, gc_pos_btree_node(insert_l(trans, i)->b))) {
614 			int ret = run_one_mem_trigger(trans, i, i->flags|BTREE_TRIGGER_gc);
615 			if (ret)
616 				return ret;
617 		}
618 	}
619 
620 	return 0;
621 }
622 
623 static inline int
624 bch2_trans_commit_write_locked(struct btree_trans *trans, unsigned flags,
625 			       struct btree_insert_entry **stopped_at,
626 			       unsigned long trace_ip)
627 {
628 	struct bch_fs *c = trans->c;
629 	struct btree_trans_commit_hook *h;
630 	unsigned u64s = 0;
631 	int ret;
632 
633 	bch2_trans_verify_not_unlocked(trans);
634 	bch2_trans_verify_not_in_restart(trans);
635 
636 	if (race_fault()) {
637 		trace_and_count(c, trans_restart_fault_inject, trans, trace_ip);
638 		return btree_trans_restart_nounlock(trans, BCH_ERR_transaction_restart_fault_inject);
639 	}
640 
641 	/*
642 	 * Check if the insert will fit in the leaf node with the write lock
643 	 * held, otherwise another thread could write the node changing the
644 	 * amount of space available:
645 	 */
646 
647 	prefetch(&trans->c->journal.flags);
648 
649 	trans_for_each_update(trans, i) {
650 		/* Multiple inserts might go to same leaf: */
651 		if (!same_leaf_as_prev(trans, i))
652 			u64s = 0;
653 
654 		u64s += i->k->k.u64s;
655 		ret = !i->cached
656 			? btree_key_can_insert(trans, insert_l(trans, i)->b, u64s)
657 			: btree_key_can_insert_cached(trans, flags, trans->paths + i->path, u64s);
658 		if (ret) {
659 			*stopped_at = i;
660 			return ret;
661 		}
662 
663 		i->k->k.needs_whiteout = false;
664 	}
665 
666 	/*
667 	 * Don't get journal reservation until after we know insert will
668 	 * succeed:
669 	 */
670 	if (likely(!(flags & BCH_TRANS_COMMIT_no_journal_res))) {
671 		ret = bch2_trans_journal_res_get(trans,
672 				(flags & BCH_WATERMARK_MASK)|
673 				JOURNAL_RES_GET_NONBLOCK);
674 		if (ret)
675 			return ret;
676 
677 		if (unlikely(trans->journal_transaction_names))
678 			journal_transaction_name(trans);
679 	}
680 
681 	/*
682 	 * Not allowed to fail after we've gotten our journal reservation - we
683 	 * have to use it:
684 	 */
685 
686 	if (IS_ENABLED(CONFIG_BCACHEFS_DEBUG) &&
687 	    !(flags & BCH_TRANS_COMMIT_no_journal_res)) {
688 		if (bch2_journal_seq_verify)
689 			trans_for_each_update(trans, i)
690 				i->k->k.version.lo = trans->journal_res.seq;
691 		else if (bch2_inject_invalid_keys)
692 			trans_for_each_update(trans, i)
693 				i->k->k.version = MAX_VERSION;
694 	}
695 
696 	if (trans->fs_usage_deltas &&
697 	    bch2_trans_fs_usage_apply(trans, trans->fs_usage_deltas))
698 		return -BCH_ERR_btree_insert_need_mark_replicas;
699 
700 	/* XXX: we only want to run this if deltas are nonzero */
701 	bch2_trans_account_disk_usage_change(trans);
702 
703 	h = trans->hooks;
704 	while (h) {
705 		ret = h->fn(trans, h);
706 		if (ret)
707 			goto revert_fs_usage;
708 		h = h->next;
709 	}
710 
711 	trans_for_each_update(trans, i)
712 		if (BTREE_NODE_TYPE_HAS_ATOMIC_TRIGGERS & (1U << i->bkey_type)) {
713 			ret = run_one_mem_trigger(trans, i, BTREE_TRIGGER_atomic|i->flags);
714 			if (ret)
715 				goto fatal_err;
716 		}
717 
718 	if (unlikely(c->gc_pos.phase)) {
719 		ret = bch2_trans_commit_run_gc_triggers(trans);
720 		if  (ret)
721 			goto fatal_err;
722 	}
723 
724 	if (likely(!(flags & BCH_TRANS_COMMIT_no_journal_res))) {
725 		struct journal *j = &c->journal;
726 		struct jset_entry *entry;
727 
728 		trans_for_each_update(trans, i) {
729 			if (i->key_cache_already_flushed)
730 				continue;
731 
732 			if (i->flags & BTREE_UPDATE_nojournal)
733 				continue;
734 
735 			verify_update_old_key(trans, i);
736 
737 			if (trans->journal_transaction_names) {
738 				entry = bch2_journal_add_entry(j, &trans->journal_res,
739 						       BCH_JSET_ENTRY_overwrite,
740 						       i->btree_id, i->level,
741 						       i->old_k.u64s);
742 				bkey_reassemble((struct bkey_i *) entry->start,
743 						(struct bkey_s_c) { &i->old_k, i->old_v });
744 			}
745 
746 			entry = bch2_journal_add_entry(j, &trans->journal_res,
747 					       BCH_JSET_ENTRY_btree_keys,
748 					       i->btree_id, i->level,
749 					       i->k->k.u64s);
750 			bkey_copy((struct bkey_i *) entry->start, i->k);
751 		}
752 
753 		memcpy_u64s_small(journal_res_entry(&c->journal, &trans->journal_res),
754 				  trans->journal_entries,
755 				  trans->journal_entries_u64s);
756 
757 		trans->journal_res.offset	+= trans->journal_entries_u64s;
758 		trans->journal_res.u64s		-= trans->journal_entries_u64s;
759 
760 		if (trans->journal_seq)
761 			*trans->journal_seq = trans->journal_res.seq;
762 	}
763 
764 	trans_for_each_update(trans, i) {
765 		struct btree_path *path = trans->paths + i->path;
766 
767 		if (!i->cached) {
768 			bch2_btree_insert_key_leaf(trans, path, i->k, trans->journal_res.seq);
769 		} else if (!i->key_cache_already_flushed)
770 			bch2_btree_insert_key_cached(trans, flags, i);
771 		else {
772 			bch2_btree_key_cache_drop(trans, path);
773 			btree_path_set_dirty(path, BTREE_ITER_NEED_TRAVERSE);
774 		}
775 	}
776 
777 	return 0;
778 fatal_err:
779 	bch2_fatal_error(c);
780 revert_fs_usage:
781 	if (trans->fs_usage_deltas)
782 		bch2_trans_fs_usage_revert(trans, trans->fs_usage_deltas);
783 	return ret;
784 }
785 
786 static noinline void bch2_drop_overwrites_from_journal(struct btree_trans *trans)
787 {
788 	trans_for_each_update(trans, i)
789 		bch2_journal_key_overwritten(trans->c, i->btree_id, i->level, i->k->k.p);
790 }
791 
792 static noinline int bch2_trans_commit_bkey_invalid(struct btree_trans *trans,
793 						   enum bch_validate_flags flags,
794 						   struct btree_insert_entry *i,
795 						   struct printbuf *err)
796 {
797 	struct bch_fs *c = trans->c;
798 
799 	printbuf_reset(err);
800 	prt_printf(err, "invalid bkey on insert from %s -> %ps\n",
801 		   trans->fn, (void *) i->ip_allocated);
802 	printbuf_indent_add(err, 2);
803 
804 	bch2_bkey_val_to_text(err, c, bkey_i_to_s_c(i->k));
805 	prt_newline(err);
806 
807 	bch2_bkey_invalid(c, bkey_i_to_s_c(i->k), i->bkey_type, flags, err);
808 	bch2_print_string_as_lines(KERN_ERR, err->buf);
809 
810 	bch2_inconsistent_error(c);
811 	bch2_dump_trans_updates(trans);
812 
813 	return -EINVAL;
814 }
815 
816 static noinline int bch2_trans_commit_journal_entry_invalid(struct btree_trans *trans,
817 						   struct jset_entry *i)
818 {
819 	struct bch_fs *c = trans->c;
820 	struct printbuf buf = PRINTBUF;
821 
822 	prt_printf(&buf, "invalid bkey on insert from %s\n", trans->fn);
823 	printbuf_indent_add(&buf, 2);
824 
825 	bch2_journal_entry_to_text(&buf, c, i);
826 	prt_newline(&buf);
827 
828 	bch2_print_string_as_lines(KERN_ERR, buf.buf);
829 
830 	bch2_inconsistent_error(c);
831 	bch2_dump_trans_updates(trans);
832 
833 	return -EINVAL;
834 }
835 
836 static int bch2_trans_commit_journal_pin_flush(struct journal *j,
837 				struct journal_entry_pin *_pin, u64 seq)
838 {
839 	return 0;
840 }
841 
842 /*
843  * Get journal reservation, take write locks, and attempt to do btree update(s):
844  */
845 static inline int do_bch2_trans_commit(struct btree_trans *trans, unsigned flags,
846 				       struct btree_insert_entry **stopped_at,
847 				       unsigned long trace_ip)
848 {
849 	struct bch_fs *c = trans->c;
850 	int ret = 0, u64s_delta = 0;
851 
852 	for (unsigned idx = 0; idx < trans->nr_updates; idx++) {
853 		struct btree_insert_entry *i = trans->updates + idx;
854 		if (i->cached)
855 			continue;
856 
857 		u64s_delta += !bkey_deleted(&i->k->k) ? i->k->k.u64s : 0;
858 		u64s_delta -= i->old_btree_u64s;
859 
860 		if (!same_leaf_as_next(trans, i)) {
861 			if (u64s_delta <= 0) {
862 				ret = bch2_foreground_maybe_merge(trans, i->path,
863 							i->level, flags);
864 				if (unlikely(ret))
865 					return ret;
866 			}
867 
868 			u64s_delta = 0;
869 		}
870 	}
871 
872 	ret = bch2_trans_lock_write(trans);
873 	if (unlikely(ret))
874 		return ret;
875 
876 	ret = bch2_trans_commit_write_locked(trans, flags, stopped_at, trace_ip);
877 
878 	if (!ret && unlikely(trans->journal_replay_not_finished))
879 		bch2_drop_overwrites_from_journal(trans);
880 
881 	bch2_trans_unlock_write(trans);
882 
883 	if (!ret && trans->journal_pin)
884 		bch2_journal_pin_add(&c->journal, trans->journal_res.seq,
885 				     trans->journal_pin,
886 				     bch2_trans_commit_journal_pin_flush);
887 
888 	/*
889 	 * Drop journal reservation after dropping write locks, since dropping
890 	 * the journal reservation may kick off a journal write:
891 	 */
892 	if (likely(!(flags & BCH_TRANS_COMMIT_no_journal_res)))
893 		bch2_journal_res_put(&c->journal, &trans->journal_res);
894 
895 	return ret;
896 }
897 
898 static int journal_reclaim_wait_done(struct bch_fs *c)
899 {
900 	int ret = bch2_journal_error(&c->journal) ?:
901 		!bch2_btree_key_cache_must_wait(c);
902 
903 	if (!ret)
904 		journal_reclaim_kick(&c->journal);
905 	return ret;
906 }
907 
908 static noinline
909 int bch2_trans_commit_error(struct btree_trans *trans, unsigned flags,
910 			    struct btree_insert_entry *i,
911 			    int ret, unsigned long trace_ip)
912 {
913 	struct bch_fs *c = trans->c;
914 	enum bch_watermark watermark = flags & BCH_WATERMARK_MASK;
915 
916 	switch (ret) {
917 	case -BCH_ERR_btree_insert_btree_node_full:
918 		ret = bch2_btree_split_leaf(trans, i->path, flags);
919 		if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
920 			trace_and_count(c, trans_restart_btree_node_split, trans,
921 					trace_ip, trans->paths + i->path);
922 		break;
923 	case -BCH_ERR_btree_insert_need_mark_replicas:
924 		ret = drop_locks_do(trans,
925 			bch2_replicas_delta_list_mark(c, trans->fs_usage_deltas));
926 		break;
927 	case -BCH_ERR_journal_res_get_blocked:
928 		/*
929 		 * XXX: this should probably be a separate BTREE_INSERT_NONBLOCK
930 		 * flag
931 		 */
932 		if ((flags & BCH_TRANS_COMMIT_journal_reclaim) &&
933 		    watermark < BCH_WATERMARK_reclaim) {
934 			ret = -BCH_ERR_journal_reclaim_would_deadlock;
935 			break;
936 		}
937 
938 		ret = drop_locks_do(trans,
939 			bch2_trans_journal_res_get(trans,
940 					(flags & BCH_WATERMARK_MASK)|
941 					JOURNAL_RES_GET_CHECK));
942 		break;
943 	case -BCH_ERR_btree_insert_need_journal_reclaim:
944 		bch2_trans_unlock(trans);
945 
946 		trace_and_count(c, trans_blocked_journal_reclaim, trans, trace_ip);
947 
948 		wait_event_freezable(c->journal.reclaim_wait,
949 				     (ret = journal_reclaim_wait_done(c)));
950 		if (ret < 0)
951 			break;
952 
953 		ret = bch2_trans_relock(trans);
954 		break;
955 	default:
956 		BUG_ON(ret >= 0);
957 		break;
958 	}
959 
960 	BUG_ON(bch2_err_matches(ret, BCH_ERR_transaction_restart) != !!trans->restarted);
961 
962 	bch2_fs_inconsistent_on(bch2_err_matches(ret, ENOSPC) &&
963 				(flags & BCH_TRANS_COMMIT_no_enospc), c,
964 		"%s: incorrectly got %s\n", __func__, bch2_err_str(ret));
965 
966 	return ret;
967 }
968 
969 static noinline int
970 bch2_trans_commit_get_rw_cold(struct btree_trans *trans, unsigned flags)
971 {
972 	struct bch_fs *c = trans->c;
973 	int ret;
974 
975 	if (likely(!(flags & BCH_TRANS_COMMIT_lazy_rw)) ||
976 	    test_bit(BCH_FS_started, &c->flags))
977 		return -BCH_ERR_erofs_trans_commit;
978 
979 	ret = drop_locks_do(trans, bch2_fs_read_write_early(c));
980 	if (ret)
981 		return ret;
982 
983 	bch2_write_ref_get(c, BCH_WRITE_REF_trans);
984 	return 0;
985 }
986 
987 /*
988  * This is for updates done in the early part of fsck - btree_gc - before we've
989  * gone RW. we only add the new key to the list of keys for journal replay to
990  * do.
991  */
992 static noinline int
993 do_bch2_trans_commit_to_journal_replay(struct btree_trans *trans)
994 {
995 	struct bch_fs *c = trans->c;
996 	int ret = 0;
997 
998 	trans_for_each_update(trans, i) {
999 		ret = bch2_journal_key_insert(c, i->btree_id, i->level, i->k);
1000 		if (ret)
1001 			break;
1002 	}
1003 
1004 	return ret;
1005 }
1006 
1007 int __bch2_trans_commit(struct btree_trans *trans, unsigned flags)
1008 {
1009 	struct btree_insert_entry *errored_at = NULL;
1010 	struct bch_fs *c = trans->c;
1011 	int ret = 0;
1012 
1013 	bch2_trans_verify_not_unlocked(trans);
1014 	bch2_trans_verify_not_in_restart(trans);
1015 
1016 	if (!trans->nr_updates &&
1017 	    !trans->journal_entries_u64s)
1018 		goto out_reset;
1019 
1020 	memset(&trans->fs_usage_delta, 0, sizeof(trans->fs_usage_delta));
1021 
1022 	ret = bch2_trans_commit_run_triggers(trans);
1023 	if (ret)
1024 		goto out_reset;
1025 
1026 	trans_for_each_update(trans, i) {
1027 		struct printbuf buf = PRINTBUF;
1028 		enum bch_validate_flags invalid_flags = 0;
1029 
1030 		if (!(flags & BCH_TRANS_COMMIT_no_journal_res))
1031 			invalid_flags |= BCH_VALIDATE_write|BCH_VALIDATE_commit;
1032 
1033 		if (unlikely(bch2_bkey_invalid(c, bkey_i_to_s_c(i->k),
1034 					       i->bkey_type, invalid_flags, &buf)))
1035 			ret = bch2_trans_commit_bkey_invalid(trans, invalid_flags, i, &buf);
1036 		btree_insert_entry_checks(trans, i);
1037 		printbuf_exit(&buf);
1038 
1039 		if (ret)
1040 			return ret;
1041 	}
1042 
1043 	for (struct jset_entry *i = trans->journal_entries;
1044 	     i != (void *) ((u64 *) trans->journal_entries + trans->journal_entries_u64s);
1045 	     i = vstruct_next(i)) {
1046 		enum bch_validate_flags invalid_flags = 0;
1047 
1048 		if (!(flags & BCH_TRANS_COMMIT_no_journal_res))
1049 			invalid_flags |= BCH_VALIDATE_write|BCH_VALIDATE_commit;
1050 
1051 		if (unlikely(bch2_journal_entry_validate(c, NULL, i,
1052 					bcachefs_metadata_version_current,
1053 					CPU_BIG_ENDIAN, invalid_flags)))
1054 			ret = bch2_trans_commit_journal_entry_invalid(trans, i);
1055 
1056 		if (ret)
1057 			return ret;
1058 	}
1059 
1060 	if (unlikely(!test_bit(BCH_FS_may_go_rw, &c->flags))) {
1061 		ret = do_bch2_trans_commit_to_journal_replay(trans);
1062 		goto out_reset;
1063 	}
1064 
1065 	if (!(flags & BCH_TRANS_COMMIT_no_check_rw) &&
1066 	    unlikely(!bch2_write_ref_tryget(c, BCH_WRITE_REF_trans))) {
1067 		ret = bch2_trans_commit_get_rw_cold(trans, flags);
1068 		if (ret)
1069 			goto out_reset;
1070 	}
1071 
1072 	EBUG_ON(test_bit(BCH_FS_clean_shutdown, &c->flags));
1073 
1074 	trans->journal_u64s		= trans->journal_entries_u64s;
1075 	trans->journal_transaction_names = READ_ONCE(c->opts.journal_transaction_names);
1076 	if (trans->journal_transaction_names)
1077 		trans->journal_u64s += jset_u64s(JSET_ENTRY_LOG_U64s);
1078 
1079 	trans_for_each_update(trans, i) {
1080 		struct btree_path *path = trans->paths + i->path;
1081 
1082 		EBUG_ON(!path->should_be_locked);
1083 
1084 		ret = bch2_btree_path_upgrade(trans, path, i->level + 1);
1085 		if (unlikely(ret))
1086 			goto out;
1087 
1088 		EBUG_ON(!btree_node_intent_locked(path, i->level));
1089 
1090 		if (i->key_cache_already_flushed)
1091 			continue;
1092 
1093 		if (i->flags & BTREE_UPDATE_nojournal)
1094 			continue;
1095 
1096 		/* we're going to journal the key being updated: */
1097 		trans->journal_u64s += jset_u64s(i->k->k.u64s);
1098 
1099 		/* and we're also going to log the overwrite: */
1100 		if (trans->journal_transaction_names)
1101 			trans->journal_u64s += jset_u64s(i->old_k.u64s);
1102 	}
1103 
1104 	if (trans->extra_disk_res) {
1105 		ret = bch2_disk_reservation_add(c, trans->disk_res,
1106 				trans->extra_disk_res,
1107 				(flags & BCH_TRANS_COMMIT_no_enospc)
1108 				? BCH_DISK_RESERVATION_NOFAIL : 0);
1109 		if (ret)
1110 			goto err;
1111 	}
1112 retry:
1113 	errored_at = NULL;
1114 	bch2_trans_verify_not_unlocked(trans);
1115 	bch2_trans_verify_not_in_restart(trans);
1116 	if (likely(!(flags & BCH_TRANS_COMMIT_no_journal_res)))
1117 		memset(&trans->journal_res, 0, sizeof(trans->journal_res));
1118 
1119 	ret = do_bch2_trans_commit(trans, flags, &errored_at, _RET_IP_);
1120 
1121 	/* make sure we didn't drop or screw up locks: */
1122 	bch2_trans_verify_locks(trans);
1123 
1124 	if (ret)
1125 		goto err;
1126 
1127 	trace_and_count(c, transaction_commit, trans, _RET_IP_);
1128 out:
1129 	if (likely(!(flags & BCH_TRANS_COMMIT_no_check_rw)))
1130 		bch2_write_ref_put(c, BCH_WRITE_REF_trans);
1131 out_reset:
1132 	if (!ret)
1133 		bch2_trans_downgrade(trans);
1134 	bch2_trans_reset_updates(trans);
1135 
1136 	return ret;
1137 err:
1138 	ret = bch2_trans_commit_error(trans, flags, errored_at, ret, _RET_IP_);
1139 	if (ret)
1140 		goto out;
1141 
1142 	/*
1143 	 * We might have done another transaction commit in the error path -
1144 	 * i.e. btree write buffer flush - which will have made use of
1145 	 * trans->journal_res, but with BCH_TRANS_COMMIT_no_journal_res that is
1146 	 * how the journal sequence number to pin is passed in - so we must
1147 	 * restart:
1148 	 */
1149 	if (flags & BCH_TRANS_COMMIT_no_journal_res) {
1150 		ret = -BCH_ERR_transaction_restart_nested;
1151 		goto out;
1152 	}
1153 
1154 	goto retry;
1155 }
1156