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