xref: /linux/fs/bcachefs/recovery.c (revision d53b8e36925256097a08d7cb749198d85cbf9b2b)
1 // SPDX-License-Identifier: GPL-2.0
2 
3 #include "bcachefs.h"
4 #include "alloc_background.h"
5 #include "bkey_buf.h"
6 #include "btree_journal_iter.h"
7 #include "btree_node_scan.h"
8 #include "btree_update.h"
9 #include "btree_update_interior.h"
10 #include "btree_io.h"
11 #include "buckets.h"
12 #include "dirent.h"
13 #include "disk_accounting.h"
14 #include "errcode.h"
15 #include "error.h"
16 #include "fs-common.h"
17 #include "journal_io.h"
18 #include "journal_reclaim.h"
19 #include "journal_seq_blacklist.h"
20 #include "logged_ops.h"
21 #include "move.h"
22 #include "quota.h"
23 #include "rebalance.h"
24 #include "recovery.h"
25 #include "recovery_passes.h"
26 #include "replicas.h"
27 #include "sb-clean.h"
28 #include "sb-downgrade.h"
29 #include "snapshot.h"
30 #include "super-io.h"
31 
32 #include <linux/sort.h>
33 #include <linux/stat.h>
34 
35 #define QSTR(n) { { { .len = strlen(n) } }, .name = n }
36 
37 void bch2_btree_lost_data(struct bch_fs *c, enum btree_id btree)
38 {
39 	if (btree >= BTREE_ID_NR_MAX)
40 		return;
41 
42 	u64 b = BIT_ULL(btree);
43 
44 	if (!(c->sb.btrees_lost_data & b)) {
45 		bch_err(c, "flagging btree %s lost data", bch2_btree_id_str(btree));
46 
47 		mutex_lock(&c->sb_lock);
48 		bch2_sb_field_get(c->disk_sb.sb, ext)->btrees_lost_data |= cpu_to_le64(b);
49 		bch2_write_super(c);
50 		mutex_unlock(&c->sb_lock);
51 	}
52 }
53 
54 /* for -o reconstruct_alloc: */
55 static void bch2_reconstruct_alloc(struct bch_fs *c)
56 {
57 	bch2_journal_log_msg(c, "dropping alloc info");
58 	bch_info(c, "dropping and reconstructing all alloc info");
59 
60 	mutex_lock(&c->sb_lock);
61 	struct bch_sb_field_ext *ext = bch2_sb_field_get(c->disk_sb.sb, ext);
62 
63 	__set_bit_le64(BCH_RECOVERY_PASS_STABLE_check_allocations, ext->recovery_passes_required);
64 	__set_bit_le64(BCH_RECOVERY_PASS_STABLE_check_alloc_info, ext->recovery_passes_required);
65 	__set_bit_le64(BCH_RECOVERY_PASS_STABLE_check_lrus, ext->recovery_passes_required);
66 	__set_bit_le64(BCH_RECOVERY_PASS_STABLE_check_extents_to_backpointers, ext->recovery_passes_required);
67 	__set_bit_le64(BCH_RECOVERY_PASS_STABLE_check_alloc_to_lru_refs, ext->recovery_passes_required);
68 
69 	__set_bit_le64(BCH_FSCK_ERR_ptr_to_missing_alloc_key, ext->errors_silent);
70 	__set_bit_le64(BCH_FSCK_ERR_ptr_gen_newer_than_bucket_gen, ext->errors_silent);
71 	__set_bit_le64(BCH_FSCK_ERR_stale_dirty_ptr, ext->errors_silent);
72 
73 	__set_bit_le64(BCH_FSCK_ERR_dev_usage_buckets_wrong, ext->errors_silent);
74 	__set_bit_le64(BCH_FSCK_ERR_dev_usage_sectors_wrong, ext->errors_silent);
75 	__set_bit_le64(BCH_FSCK_ERR_dev_usage_fragmented_wrong, ext->errors_silent);
76 
77 	__set_bit_le64(BCH_FSCK_ERR_fs_usage_btree_wrong, ext->errors_silent);
78 	__set_bit_le64(BCH_FSCK_ERR_fs_usage_cached_wrong, ext->errors_silent);
79 	__set_bit_le64(BCH_FSCK_ERR_fs_usage_persistent_reserved_wrong, ext->errors_silent);
80 	__set_bit_le64(BCH_FSCK_ERR_fs_usage_replicas_wrong, ext->errors_silent);
81 
82 	__set_bit_le64(BCH_FSCK_ERR_alloc_key_data_type_wrong, ext->errors_silent);
83 	__set_bit_le64(BCH_FSCK_ERR_alloc_key_gen_wrong, ext->errors_silent);
84 	__set_bit_le64(BCH_FSCK_ERR_alloc_key_dirty_sectors_wrong, ext->errors_silent);
85 	__set_bit_le64(BCH_FSCK_ERR_alloc_key_cached_sectors_wrong, ext->errors_silent);
86 	__set_bit_le64(BCH_FSCK_ERR_alloc_key_stripe_wrong, ext->errors_silent);
87 	__set_bit_le64(BCH_FSCK_ERR_alloc_key_stripe_redundancy_wrong, ext->errors_silent);
88 	__set_bit_le64(BCH_FSCK_ERR_need_discard_key_wrong, ext->errors_silent);
89 	__set_bit_le64(BCH_FSCK_ERR_freespace_key_wrong, ext->errors_silent);
90 	__set_bit_le64(BCH_FSCK_ERR_bucket_gens_key_wrong, ext->errors_silent);
91 	__set_bit_le64(BCH_FSCK_ERR_freespace_hole_missing, ext->errors_silent);
92 	__set_bit_le64(BCH_FSCK_ERR_ptr_to_missing_backpointer, ext->errors_silent);
93 	__set_bit_le64(BCH_FSCK_ERR_lru_entry_bad, ext->errors_silent);
94 	__set_bit_le64(BCH_FSCK_ERR_accounting_mismatch, ext->errors_silent);
95 	c->sb.compat &= ~(1ULL << BCH_COMPAT_alloc_info);
96 
97 	bch2_write_super(c);
98 	mutex_unlock(&c->sb_lock);
99 
100 	c->recovery_passes_explicit |= bch2_recovery_passes_from_stable(le64_to_cpu(ext->recovery_passes_required[0]));
101 
102 
103 	bch2_shoot_down_journal_keys(c, BTREE_ID_alloc,
104 				     0, BTREE_MAX_DEPTH, POS_MIN, SPOS_MAX);
105 	bch2_shoot_down_journal_keys(c, BTREE_ID_backpointers,
106 				     0, BTREE_MAX_DEPTH, POS_MIN, SPOS_MAX);
107 	bch2_shoot_down_journal_keys(c, BTREE_ID_need_discard,
108 				     0, BTREE_MAX_DEPTH, POS_MIN, SPOS_MAX);
109 	bch2_shoot_down_journal_keys(c, BTREE_ID_freespace,
110 				     0, BTREE_MAX_DEPTH, POS_MIN, SPOS_MAX);
111 	bch2_shoot_down_journal_keys(c, BTREE_ID_bucket_gens,
112 				     0, BTREE_MAX_DEPTH, POS_MIN, SPOS_MAX);
113 }
114 
115 /*
116  * Btree node pointers have a field to stack a pointer to the in memory btree
117  * node; we need to zero out this field when reading in btree nodes, or when
118  * reading in keys from the journal:
119  */
120 static void zero_out_btree_mem_ptr(struct journal_keys *keys)
121 {
122 	darray_for_each(*keys, i)
123 		if (i->k->k.type == KEY_TYPE_btree_ptr_v2)
124 			bkey_i_to_btree_ptr_v2(i->k)->v.mem_ptr = 0;
125 }
126 
127 /* journal replay: */
128 
129 static void replay_now_at(struct journal *j, u64 seq)
130 {
131 	BUG_ON(seq < j->replay_journal_seq);
132 
133 	seq = min(seq, j->replay_journal_seq_end);
134 
135 	while (j->replay_journal_seq < seq)
136 		bch2_journal_pin_put(j, j->replay_journal_seq++);
137 }
138 
139 static int bch2_journal_replay_accounting_key(struct btree_trans *trans,
140 					      struct journal_key *k)
141 {
142 	struct btree_iter iter;
143 	bch2_trans_node_iter_init(trans, &iter, k->btree_id, k->k->k.p,
144 				  BTREE_MAX_DEPTH, k->level,
145 				  BTREE_ITER_intent);
146 	int ret = bch2_btree_iter_traverse(&iter);
147 	if (ret)
148 		goto out;
149 
150 	struct bkey u;
151 	struct bkey_s_c old = bch2_btree_path_peek_slot(btree_iter_path(trans, &iter), &u);
152 
153 	/* Has this delta already been applied to the btree? */
154 	if (bversion_cmp(old.k->version, k->k->k.version) >= 0) {
155 		ret = 0;
156 		goto out;
157 	}
158 
159 	struct bkey_i *new = k->k;
160 	if (old.k->type == KEY_TYPE_accounting) {
161 		new = bch2_bkey_make_mut_noupdate(trans, bkey_i_to_s_c(k->k));
162 		ret = PTR_ERR_OR_ZERO(new);
163 		if (ret)
164 			goto out;
165 
166 		bch2_accounting_accumulate(bkey_i_to_accounting(new),
167 					   bkey_s_c_to_accounting(old));
168 	}
169 
170 	trans->journal_res.seq = k->journal_seq;
171 
172 	ret = bch2_trans_update(trans, &iter, new, BTREE_TRIGGER_norun);
173 out:
174 	bch2_trans_iter_exit(trans, &iter);
175 	return ret;
176 }
177 
178 static int bch2_journal_replay_key(struct btree_trans *trans,
179 				   struct journal_key *k)
180 {
181 	struct btree_iter iter;
182 	unsigned iter_flags =
183 		BTREE_ITER_intent|
184 		BTREE_ITER_not_extents;
185 	unsigned update_flags = BTREE_TRIGGER_norun;
186 	int ret;
187 
188 	if (k->overwritten)
189 		return 0;
190 
191 	trans->journal_res.seq = k->journal_seq;
192 
193 	/*
194 	 * BTREE_UPDATE_key_cache_reclaim disables key cache lookup/update to
195 	 * keep the key cache coherent with the underlying btree. Nothing
196 	 * besides the allocator is doing updates yet so we don't need key cache
197 	 * coherency for non-alloc btrees, and key cache fills for snapshots
198 	 * btrees use BTREE_ITER_filter_snapshots, which isn't available until
199 	 * the snapshots recovery pass runs.
200 	 */
201 	if (!k->level && k->btree_id == BTREE_ID_alloc)
202 		iter_flags |= BTREE_ITER_cached;
203 	else
204 		update_flags |= BTREE_UPDATE_key_cache_reclaim;
205 
206 	bch2_trans_node_iter_init(trans, &iter, k->btree_id, k->k->k.p,
207 				  BTREE_MAX_DEPTH, k->level,
208 				  iter_flags);
209 	ret = bch2_btree_iter_traverse(&iter);
210 	if (ret)
211 		goto out;
212 
213 	struct btree_path *path = btree_iter_path(trans, &iter);
214 	if (unlikely(!btree_path_node(path, k->level))) {
215 		bch2_trans_iter_exit(trans, &iter);
216 		bch2_trans_node_iter_init(trans, &iter, k->btree_id, k->k->k.p,
217 					  BTREE_MAX_DEPTH, 0, iter_flags);
218 		ret =   bch2_btree_iter_traverse(&iter) ?:
219 			bch2_btree_increase_depth(trans, iter.path, 0) ?:
220 			-BCH_ERR_transaction_restart_nested;
221 		goto out;
222 	}
223 
224 	/* Must be checked with btree locked: */
225 	if (k->overwritten)
226 		goto out;
227 
228 	if (k->k->k.type == KEY_TYPE_accounting) {
229 		ret = bch2_trans_update_buffered(trans, BTREE_ID_accounting, k->k);
230 		goto out;
231 	}
232 
233 	ret = bch2_trans_update(trans, &iter, k->k, update_flags);
234 out:
235 	bch2_trans_iter_exit(trans, &iter);
236 	return ret;
237 }
238 
239 static int journal_sort_seq_cmp(const void *_l, const void *_r)
240 {
241 	const struct journal_key *l = *((const struct journal_key **)_l);
242 	const struct journal_key *r = *((const struct journal_key **)_r);
243 
244 	/*
245 	 * Map 0 to U64_MAX, so that keys with journal_seq === 0 come last
246 	 *
247 	 * journal_seq == 0 means that the key comes from early repair, and
248 	 * should be inserted last so as to avoid overflowing the journal
249 	 */
250 	return cmp_int(l->journal_seq - 1, r->journal_seq - 1);
251 }
252 
253 int bch2_journal_replay(struct bch_fs *c)
254 {
255 	struct journal_keys *keys = &c->journal_keys;
256 	DARRAY(struct journal_key *) keys_sorted = { 0 };
257 	struct journal *j = &c->journal;
258 	u64 start_seq	= c->journal_replay_seq_start;
259 	u64 end_seq	= c->journal_replay_seq_start;
260 	struct btree_trans *trans = NULL;
261 	bool immediate_flush = false;
262 	int ret = 0;
263 
264 	if (keys->nr) {
265 		ret = bch2_journal_log_msg(c, "Starting journal replay (%zu keys in entries %llu-%llu)",
266 					   keys->nr, start_seq, end_seq);
267 		if (ret)
268 			goto err;
269 	}
270 
271 	BUG_ON(!atomic_read(&keys->ref));
272 
273 	move_gap(keys, keys->nr);
274 	trans = bch2_trans_get(c);
275 
276 	/*
277 	 * Replay accounting keys first: we can't allow the write buffer to
278 	 * flush accounting keys until we're done
279 	 */
280 	darray_for_each(*keys, k) {
281 		if (!(k->k->k.type == KEY_TYPE_accounting && !k->allocated))
282 			continue;
283 
284 		cond_resched();
285 
286 		ret = commit_do(trans, NULL, NULL,
287 				BCH_TRANS_COMMIT_no_enospc|
288 				BCH_TRANS_COMMIT_journal_reclaim|
289 				BCH_TRANS_COMMIT_skip_accounting_apply|
290 				BCH_TRANS_COMMIT_no_journal_res,
291 			     bch2_journal_replay_accounting_key(trans, k));
292 		if (bch2_fs_fatal_err_on(ret, c, "error replaying accounting; %s", bch2_err_str(ret)))
293 			goto err;
294 
295 		k->overwritten = true;
296 	}
297 
298 	set_bit(BCH_FS_accounting_replay_done, &c->flags);
299 
300 	/*
301 	 * First, attempt to replay keys in sorted order. This is more
302 	 * efficient - better locality of btree access -  but some might fail if
303 	 * that would cause a journal deadlock.
304 	 */
305 	darray_for_each(*keys, k) {
306 		cond_resched();
307 
308 		/*
309 		 * k->allocated means the key wasn't read in from the journal,
310 		 * rather it was from early repair code
311 		 */
312 		if (k->allocated)
313 			immediate_flush = true;
314 
315 		/* Skip fastpath if we're low on space in the journal */
316 		ret = c->journal.watermark ? -1 :
317 			commit_do(trans, NULL, NULL,
318 				  BCH_TRANS_COMMIT_no_enospc|
319 				  BCH_TRANS_COMMIT_journal_reclaim|
320 				  BCH_TRANS_COMMIT_skip_accounting_apply|
321 				  (!k->allocated ? BCH_TRANS_COMMIT_no_journal_res : 0),
322 			     bch2_journal_replay_key(trans, k));
323 		BUG_ON(!ret && !k->overwritten && k->k->k.type != KEY_TYPE_accounting);
324 		if (ret) {
325 			ret = darray_push(&keys_sorted, k);
326 			if (ret)
327 				goto err;
328 		}
329 	}
330 
331 	bch2_trans_unlock_long(trans);
332 	/*
333 	 * Now, replay any remaining keys in the order in which they appear in
334 	 * the journal, unpinning those journal entries as we go:
335 	 */
336 	sort(keys_sorted.data, keys_sorted.nr,
337 	     sizeof(keys_sorted.data[0]),
338 	     journal_sort_seq_cmp, NULL);
339 
340 	darray_for_each(keys_sorted, kp) {
341 		cond_resched();
342 
343 		struct journal_key *k = *kp;
344 
345 		if (k->journal_seq)
346 			replay_now_at(j, k->journal_seq);
347 		else
348 			replay_now_at(j, j->replay_journal_seq_end);
349 
350 		ret = commit_do(trans, NULL, NULL,
351 				BCH_TRANS_COMMIT_no_enospc|
352 				BCH_TRANS_COMMIT_skip_accounting_apply|
353 				(!k->allocated
354 				 ? BCH_TRANS_COMMIT_no_journal_res|BCH_WATERMARK_reclaim
355 				 : 0),
356 			     bch2_journal_replay_key(trans, k));
357 		bch_err_msg(c, ret, "while replaying key at btree %s level %u:",
358 			    bch2_btree_id_str(k->btree_id), k->level);
359 		if (ret)
360 			goto err;
361 
362 		BUG_ON(k->btree_id != BTREE_ID_accounting && !k->overwritten);
363 	}
364 
365 	/*
366 	 * We need to put our btree_trans before calling flush_all_pins(), since
367 	 * that will use a btree_trans internally
368 	 */
369 	bch2_trans_put(trans);
370 	trans = NULL;
371 
372 	if (!c->opts.retain_recovery_info &&
373 	    c->recovery_pass_done >= BCH_RECOVERY_PASS_journal_replay)
374 		bch2_journal_keys_put_initial(c);
375 
376 	replay_now_at(j, j->replay_journal_seq_end);
377 	j->replay_journal_seq = 0;
378 
379 	bch2_journal_set_replay_done(j);
380 
381 	/* if we did any repair, flush it immediately */
382 	if (immediate_flush) {
383 		bch2_journal_flush_all_pins(&c->journal);
384 		ret = bch2_journal_meta(&c->journal);
385 	}
386 
387 	if (keys->nr)
388 		bch2_journal_log_msg(c, "journal replay finished");
389 err:
390 	if (trans)
391 		bch2_trans_put(trans);
392 	darray_exit(&keys_sorted);
393 	bch_err_fn(c, ret);
394 	return ret;
395 }
396 
397 /* journal replay early: */
398 
399 static int journal_replay_entry_early(struct bch_fs *c,
400 				      struct jset_entry *entry)
401 {
402 	int ret = 0;
403 
404 	switch (entry->type) {
405 	case BCH_JSET_ENTRY_btree_root: {
406 		struct btree_root *r;
407 
408 		if (fsck_err_on(entry->btree_id >= BTREE_ID_NR_MAX,
409 				c, invalid_btree_id,
410 				"invalid btree id %u (max %u)",
411 				entry->btree_id, BTREE_ID_NR_MAX))
412 			return 0;
413 
414 		while (entry->btree_id >= c->btree_roots_extra.nr + BTREE_ID_NR) {
415 			ret = darray_push(&c->btree_roots_extra, (struct btree_root) { NULL });
416 			if (ret)
417 				return ret;
418 		}
419 
420 		r = bch2_btree_id_root(c, entry->btree_id);
421 
422 		if (entry->u64s) {
423 			r->level = entry->level;
424 			bkey_copy(&r->key, (struct bkey_i *) entry->start);
425 			r->error = 0;
426 		} else {
427 			r->error = -BCH_ERR_btree_node_read_error;
428 		}
429 		r->alive = true;
430 		break;
431 	}
432 	case BCH_JSET_ENTRY_usage: {
433 		struct jset_entry_usage *u =
434 			container_of(entry, struct jset_entry_usage, entry);
435 
436 		switch (entry->btree_id) {
437 		case BCH_FS_USAGE_key_version:
438 			atomic64_set(&c->key_version, le64_to_cpu(u->v));
439 			break;
440 		}
441 		break;
442 	}
443 	case BCH_JSET_ENTRY_blacklist: {
444 		struct jset_entry_blacklist *bl_entry =
445 			container_of(entry, struct jset_entry_blacklist, entry);
446 
447 		ret = bch2_journal_seq_blacklist_add(c,
448 				le64_to_cpu(bl_entry->seq),
449 				le64_to_cpu(bl_entry->seq) + 1);
450 		break;
451 	}
452 	case BCH_JSET_ENTRY_blacklist_v2: {
453 		struct jset_entry_blacklist_v2 *bl_entry =
454 			container_of(entry, struct jset_entry_blacklist_v2, entry);
455 
456 		ret = bch2_journal_seq_blacklist_add(c,
457 				le64_to_cpu(bl_entry->start),
458 				le64_to_cpu(bl_entry->end) + 1);
459 		break;
460 	}
461 	case BCH_JSET_ENTRY_clock: {
462 		struct jset_entry_clock *clock =
463 			container_of(entry, struct jset_entry_clock, entry);
464 
465 		atomic64_set(&c->io_clock[clock->rw].now, le64_to_cpu(clock->time));
466 	}
467 	}
468 fsck_err:
469 	return ret;
470 }
471 
472 static int journal_replay_early(struct bch_fs *c,
473 				struct bch_sb_field_clean *clean)
474 {
475 	if (clean) {
476 		for (struct jset_entry *entry = clean->start;
477 		     entry != vstruct_end(&clean->field);
478 		     entry = vstruct_next(entry)) {
479 			int ret = journal_replay_entry_early(c, entry);
480 			if (ret)
481 				return ret;
482 		}
483 	} else {
484 		struct genradix_iter iter;
485 		struct journal_replay *i, **_i;
486 
487 		genradix_for_each(&c->journal_entries, iter, _i) {
488 			i = *_i;
489 
490 			if (journal_replay_ignore(i))
491 				continue;
492 
493 			vstruct_for_each(&i->j, entry) {
494 				int ret = journal_replay_entry_early(c, entry);
495 				if (ret)
496 					return ret;
497 			}
498 		}
499 	}
500 
501 	return 0;
502 }
503 
504 /* sb clean section: */
505 
506 static int read_btree_roots(struct bch_fs *c)
507 {
508 	int ret = 0;
509 
510 	for (unsigned i = 0; i < btree_id_nr_alive(c); i++) {
511 		struct btree_root *r = bch2_btree_id_root(c, i);
512 
513 		if (!r->alive)
514 			continue;
515 
516 		if (btree_id_is_alloc(i) && c->opts.reconstruct_alloc)
517 			continue;
518 
519 		if (mustfix_fsck_err_on((ret = r->error),
520 					c, btree_root_bkey_invalid,
521 					"invalid btree root %s",
522 					bch2_btree_id_str(i)) ||
523 		    mustfix_fsck_err_on((ret = r->error = bch2_btree_root_read(c, i, &r->key, r->level)),
524 					c, btree_root_read_error,
525 					"error reading btree root %s l=%u: %s",
526 					bch2_btree_id_str(i), r->level, bch2_err_str(ret))) {
527 			if (btree_id_is_alloc(i)) {
528 				c->recovery_passes_explicit |= BIT_ULL(BCH_RECOVERY_PASS_check_allocations);
529 				c->recovery_passes_explicit |= BIT_ULL(BCH_RECOVERY_PASS_check_alloc_info);
530 				c->recovery_passes_explicit |= BIT_ULL(BCH_RECOVERY_PASS_check_lrus);
531 				c->recovery_passes_explicit |= BIT_ULL(BCH_RECOVERY_PASS_check_extents_to_backpointers);
532 				c->recovery_passes_explicit |= BIT_ULL(BCH_RECOVERY_PASS_check_alloc_to_lru_refs);
533 				c->sb.compat &= ~(1ULL << BCH_COMPAT_alloc_info);
534 				r->error = 0;
535 			} else if (!(c->recovery_passes_explicit & BIT_ULL(BCH_RECOVERY_PASS_scan_for_btree_nodes))) {
536 				bch_info(c, "will run btree node scan");
537 				c->recovery_passes_explicit |= BIT_ULL(BCH_RECOVERY_PASS_scan_for_btree_nodes);
538 				c->recovery_passes_explicit |= BIT_ULL(BCH_RECOVERY_PASS_check_topology);
539 			}
540 
541 			ret = 0;
542 			bch2_btree_lost_data(c, i);
543 		}
544 	}
545 
546 	for (unsigned i = 0; i < BTREE_ID_NR; i++) {
547 		struct btree_root *r = bch2_btree_id_root(c, i);
548 
549 		if (!r->b && !r->error) {
550 			r->alive = false;
551 			r->level = 0;
552 			bch2_btree_root_alloc_fake(c, i, 0);
553 		}
554 	}
555 fsck_err:
556 	return ret;
557 }
558 
559 static bool check_version_upgrade(struct bch_fs *c)
560 {
561 	unsigned latest_version	= bcachefs_metadata_version_current;
562 	unsigned latest_compatible = min(latest_version,
563 					 bch2_latest_compatible_version(c->sb.version));
564 	unsigned old_version = c->sb.version_upgrade_complete ?: c->sb.version;
565 	unsigned new_version = 0;
566 
567 	if (old_version < bcachefs_metadata_required_upgrade_below) {
568 		if (c->opts.version_upgrade == BCH_VERSION_UPGRADE_incompatible ||
569 		    latest_compatible < bcachefs_metadata_required_upgrade_below)
570 			new_version = latest_version;
571 		else
572 			new_version = latest_compatible;
573 	} else {
574 		switch (c->opts.version_upgrade) {
575 		case BCH_VERSION_UPGRADE_compatible:
576 			new_version = latest_compatible;
577 			break;
578 		case BCH_VERSION_UPGRADE_incompatible:
579 			new_version = latest_version;
580 			break;
581 		case BCH_VERSION_UPGRADE_none:
582 			new_version = min(old_version, latest_version);
583 			break;
584 		}
585 	}
586 
587 	if (new_version > old_version) {
588 		struct printbuf buf = PRINTBUF;
589 
590 		if (old_version < bcachefs_metadata_required_upgrade_below)
591 			prt_str(&buf, "Version upgrade required:\n");
592 
593 		if (old_version != c->sb.version) {
594 			prt_str(&buf, "Version upgrade from ");
595 			bch2_version_to_text(&buf, c->sb.version_upgrade_complete);
596 			prt_str(&buf, " to ");
597 			bch2_version_to_text(&buf, c->sb.version);
598 			prt_str(&buf, " incomplete\n");
599 		}
600 
601 		prt_printf(&buf, "Doing %s version upgrade from ",
602 			   BCH_VERSION_MAJOR(old_version) != BCH_VERSION_MAJOR(new_version)
603 			   ? "incompatible" : "compatible");
604 		bch2_version_to_text(&buf, old_version);
605 		prt_str(&buf, " to ");
606 		bch2_version_to_text(&buf, new_version);
607 		prt_newline(&buf);
608 
609 		struct bch_sb_field_ext *ext = bch2_sb_field_get(c->disk_sb.sb, ext);
610 		__le64 passes = ext->recovery_passes_required[0];
611 		bch2_sb_set_upgrade(c, old_version, new_version);
612 		passes = ext->recovery_passes_required[0] & ~passes;
613 
614 		if (passes) {
615 			prt_str(&buf, "  running recovery passes: ");
616 			prt_bitflags(&buf, bch2_recovery_passes,
617 				     bch2_recovery_passes_from_stable(le64_to_cpu(passes)));
618 		}
619 
620 		bch_info(c, "%s", buf.buf);
621 
622 		bch2_sb_upgrade(c, new_version);
623 
624 		printbuf_exit(&buf);
625 		return true;
626 	}
627 
628 	return false;
629 }
630 
631 int bch2_fs_recovery(struct bch_fs *c)
632 {
633 	struct bch_sb_field_clean *clean = NULL;
634 	struct jset *last_journal_entry = NULL;
635 	u64 last_seq = 0, blacklist_seq, journal_seq;
636 	int ret = 0;
637 
638 	if (c->sb.clean) {
639 		clean = bch2_read_superblock_clean(c);
640 		ret = PTR_ERR_OR_ZERO(clean);
641 		if (ret)
642 			goto err;
643 
644 		bch_info(c, "recovering from clean shutdown, journal seq %llu",
645 			 le64_to_cpu(clean->journal_seq));
646 	} else {
647 		bch_info(c, "recovering from unclean shutdown");
648 	}
649 
650 	if (!(c->sb.features & (1ULL << BCH_FEATURE_new_extent_overwrite))) {
651 		bch_err(c, "feature new_extent_overwrite not set, filesystem no longer supported");
652 		ret = -EINVAL;
653 		goto err;
654 	}
655 
656 	if (!c->sb.clean &&
657 	    !(c->sb.features & (1ULL << BCH_FEATURE_extents_above_btree_updates))) {
658 		bch_err(c, "filesystem needs recovery from older version; run fsck from older bcachefs-tools to fix");
659 		ret = -EINVAL;
660 		goto err;
661 	}
662 
663 	if (c->opts.norecovery)
664 		c->opts.recovery_pass_last = BCH_RECOVERY_PASS_journal_replay - 1;
665 
666 	mutex_lock(&c->sb_lock);
667 	struct bch_sb_field_ext *ext = bch2_sb_field_get(c->disk_sb.sb, ext);
668 	bool write_sb = false;
669 
670 	if (BCH_SB_HAS_TOPOLOGY_ERRORS(c->disk_sb.sb)) {
671 		ext->recovery_passes_required[0] |=
672 			cpu_to_le64(bch2_recovery_passes_to_stable(BIT_ULL(BCH_RECOVERY_PASS_check_topology)));
673 		write_sb = true;
674 	}
675 
676 	u64 sb_passes = bch2_recovery_passes_from_stable(le64_to_cpu(ext->recovery_passes_required[0]));
677 	if (sb_passes) {
678 		struct printbuf buf = PRINTBUF;
679 		prt_str(&buf, "superblock requires following recovery passes to be run:\n  ");
680 		prt_bitflags(&buf, bch2_recovery_passes, sb_passes);
681 		bch_info(c, "%s", buf.buf);
682 		printbuf_exit(&buf);
683 	}
684 
685 	if (bch2_check_version_downgrade(c)) {
686 		struct printbuf buf = PRINTBUF;
687 
688 		prt_str(&buf, "Version downgrade required:");
689 
690 		__le64 passes = ext->recovery_passes_required[0];
691 		bch2_sb_set_downgrade(c,
692 				      BCH_VERSION_MINOR(bcachefs_metadata_version_current),
693 				      BCH_VERSION_MINOR(c->sb.version));
694 		passes = ext->recovery_passes_required[0] & ~passes;
695 		if (passes) {
696 			prt_str(&buf, "\n  running recovery passes: ");
697 			prt_bitflags(&buf, bch2_recovery_passes,
698 				     bch2_recovery_passes_from_stable(le64_to_cpu(passes)));
699 		}
700 
701 		bch_info(c, "%s", buf.buf);
702 		printbuf_exit(&buf);
703 		write_sb = true;
704 	}
705 
706 	if (check_version_upgrade(c))
707 		write_sb = true;
708 
709 	c->recovery_passes_explicit |= bch2_recovery_passes_from_stable(le64_to_cpu(ext->recovery_passes_required[0]));
710 
711 	if (write_sb)
712 		bch2_write_super(c);
713 	mutex_unlock(&c->sb_lock);
714 
715 	if (c->opts.fsck && IS_ENABLED(CONFIG_BCACHEFS_DEBUG))
716 		c->recovery_passes_explicit |= BIT_ULL(BCH_RECOVERY_PASS_check_topology);
717 
718 	if (c->opts.fsck)
719 		set_bit(BCH_FS_fsck_running, &c->flags);
720 
721 	ret = bch2_blacklist_table_initialize(c);
722 	if (ret) {
723 		bch_err(c, "error initializing blacklist table");
724 		goto err;
725 	}
726 
727 	bch2_journal_pos_from_member_info_resume(c);
728 
729 	if (!c->sb.clean || c->opts.retain_recovery_info) {
730 		struct genradix_iter iter;
731 		struct journal_replay **i;
732 
733 		bch_verbose(c, "starting journal read");
734 		ret = bch2_journal_read(c, &last_seq, &blacklist_seq, &journal_seq);
735 		if (ret)
736 			goto err;
737 
738 		/*
739 		 * note: cmd_list_journal needs the blacklist table fully up to date so
740 		 * it can asterisk ignored journal entries:
741 		 */
742 		if (c->opts.read_journal_only)
743 			goto out;
744 
745 		genradix_for_each_reverse(&c->journal_entries, iter, i)
746 			if (!journal_replay_ignore(*i)) {
747 				last_journal_entry = &(*i)->j;
748 				break;
749 			}
750 
751 		if (mustfix_fsck_err_on(c->sb.clean &&
752 					last_journal_entry &&
753 					!journal_entry_empty(last_journal_entry), c,
754 				clean_but_journal_not_empty,
755 				"filesystem marked clean but journal not empty")) {
756 			c->sb.compat &= ~(1ULL << BCH_COMPAT_alloc_info);
757 			SET_BCH_SB_CLEAN(c->disk_sb.sb, false);
758 			c->sb.clean = false;
759 		}
760 
761 		if (!last_journal_entry) {
762 			fsck_err_on(!c->sb.clean, c,
763 				    dirty_but_no_journal_entries,
764 				    "no journal entries found");
765 			if (clean)
766 				goto use_clean;
767 
768 			genradix_for_each_reverse(&c->journal_entries, iter, i)
769 				if (*i) {
770 					last_journal_entry = &(*i)->j;
771 					(*i)->ignore_blacklisted = false;
772 					(*i)->ignore_not_dirty= false;
773 					/*
774 					 * This was probably a NO_FLUSH entry,
775 					 * so last_seq was garbage - but we know
776 					 * we're only using a single journal
777 					 * entry, set it here:
778 					 */
779 					(*i)->j.last_seq = (*i)->j.seq;
780 					break;
781 				}
782 		}
783 
784 		ret = bch2_journal_keys_sort(c);
785 		if (ret)
786 			goto err;
787 
788 		if (c->sb.clean && last_journal_entry) {
789 			ret = bch2_verify_superblock_clean(c, &clean,
790 						      last_journal_entry);
791 			if (ret)
792 				goto err;
793 		}
794 	} else {
795 use_clean:
796 		if (!clean) {
797 			bch_err(c, "no superblock clean section found");
798 			ret = -BCH_ERR_fsck_repair_impossible;
799 			goto err;
800 
801 		}
802 		blacklist_seq = journal_seq = le64_to_cpu(clean->journal_seq) + 1;
803 	}
804 
805 	c->journal_replay_seq_start	= last_seq;
806 	c->journal_replay_seq_end	= blacklist_seq - 1;
807 
808 	if (c->opts.reconstruct_alloc)
809 		bch2_reconstruct_alloc(c);
810 
811 	zero_out_btree_mem_ptr(&c->journal_keys);
812 
813 	ret = journal_replay_early(c, clean);
814 	if (ret)
815 		goto err;
816 
817 	/*
818 	 * After an unclean shutdown, skip then next few journal sequence
819 	 * numbers as they may have been referenced by btree writes that
820 	 * happened before their corresponding journal writes - those btree
821 	 * writes need to be ignored, by skipping and blacklisting the next few
822 	 * journal sequence numbers:
823 	 */
824 	if (!c->sb.clean)
825 		journal_seq += 8;
826 
827 	if (blacklist_seq != journal_seq) {
828 		ret =   bch2_journal_log_msg(c, "blacklisting entries %llu-%llu",
829 					     blacklist_seq, journal_seq) ?:
830 			bch2_journal_seq_blacklist_add(c,
831 					blacklist_seq, journal_seq);
832 		if (ret) {
833 			bch_err_msg(c, ret, "error creating new journal seq blacklist entry");
834 			goto err;
835 		}
836 	}
837 
838 	ret =   bch2_journal_log_msg(c, "starting journal at entry %llu, replaying %llu-%llu",
839 				     journal_seq, last_seq, blacklist_seq - 1) ?:
840 		bch2_fs_journal_start(&c->journal, journal_seq);
841 	if (ret)
842 		goto err;
843 
844 	/*
845 	 * Skip past versions that might have possibly been used (as nonces),
846 	 * but hadn't had their pointers written:
847 	 */
848 	if (c->sb.encryption_type && !c->sb.clean)
849 		atomic64_add(1 << 16, &c->key_version);
850 
851 	ret = read_btree_roots(c);
852 	if (ret)
853 		goto err;
854 
855 	set_bit(BCH_FS_btree_running, &c->flags);
856 
857 	ret = bch2_sb_set_upgrade_extra(c);
858 
859 	ret = bch2_run_recovery_passes(c);
860 	if (ret)
861 		goto err;
862 
863 	clear_bit(BCH_FS_fsck_running, &c->flags);
864 
865 	/* fsync if we fixed errors */
866 	if (test_bit(BCH_FS_errors_fixed, &c->flags) &&
867 	    bch2_write_ref_tryget(c, BCH_WRITE_REF_fsync)) {
868 		bch2_journal_flush_all_pins(&c->journal);
869 		bch2_journal_meta(&c->journal);
870 		bch2_write_ref_put(c, BCH_WRITE_REF_fsync);
871 	}
872 
873 	/* If we fixed errors, verify that fs is actually clean now: */
874 	if (IS_ENABLED(CONFIG_BCACHEFS_DEBUG) &&
875 	    test_bit(BCH_FS_errors_fixed, &c->flags) &&
876 	    !test_bit(BCH_FS_errors_not_fixed, &c->flags) &&
877 	    !test_bit(BCH_FS_error, &c->flags)) {
878 		bch2_flush_fsck_errs(c);
879 
880 		bch_info(c, "Fixed errors, running fsck a second time to verify fs is clean");
881 		clear_bit(BCH_FS_errors_fixed, &c->flags);
882 
883 		c->curr_recovery_pass = BCH_RECOVERY_PASS_check_alloc_info;
884 
885 		ret = bch2_run_recovery_passes(c);
886 		if (ret)
887 			goto err;
888 
889 		if (test_bit(BCH_FS_errors_fixed, &c->flags) ||
890 		    test_bit(BCH_FS_errors_not_fixed, &c->flags)) {
891 			bch_err(c, "Second fsck run was not clean");
892 			set_bit(BCH_FS_errors_not_fixed, &c->flags);
893 		}
894 
895 		set_bit(BCH_FS_errors_fixed, &c->flags);
896 	}
897 
898 	if (enabled_qtypes(c)) {
899 		bch_verbose(c, "reading quotas");
900 		ret = bch2_fs_quota_read(c);
901 		if (ret)
902 			goto err;
903 		bch_verbose(c, "quotas done");
904 	}
905 
906 	mutex_lock(&c->sb_lock);
907 	ext = bch2_sb_field_get(c->disk_sb.sb, ext);
908 	write_sb = false;
909 
910 	if (BCH_SB_VERSION_UPGRADE_COMPLETE(c->disk_sb.sb) != le16_to_cpu(c->disk_sb.sb->version)) {
911 		SET_BCH_SB_VERSION_UPGRADE_COMPLETE(c->disk_sb.sb, le16_to_cpu(c->disk_sb.sb->version));
912 		write_sb = true;
913 	}
914 
915 	if (!test_bit(BCH_FS_error, &c->flags) &&
916 	    !(c->disk_sb.sb->compat[0] & cpu_to_le64(1ULL << BCH_COMPAT_alloc_info))) {
917 		c->disk_sb.sb->compat[0] |= cpu_to_le64(1ULL << BCH_COMPAT_alloc_info);
918 		write_sb = true;
919 	}
920 
921 	if (!test_bit(BCH_FS_error, &c->flags) &&
922 	    !bch2_is_zero(ext->errors_silent, sizeof(ext->errors_silent))) {
923 		memset(ext->errors_silent, 0, sizeof(ext->errors_silent));
924 		write_sb = true;
925 	}
926 
927 	if (c->opts.fsck &&
928 	    !test_bit(BCH_FS_error, &c->flags) &&
929 	    c->recovery_pass_done == BCH_RECOVERY_PASS_NR - 1 &&
930 	    ext->btrees_lost_data) {
931 		ext->btrees_lost_data = 0;
932 		write_sb = true;
933 	}
934 
935 	if (c->opts.fsck &&
936 	    !test_bit(BCH_FS_error, &c->flags) &&
937 	    !test_bit(BCH_FS_errors_not_fixed, &c->flags)) {
938 		SET_BCH_SB_HAS_ERRORS(c->disk_sb.sb, 0);
939 		SET_BCH_SB_HAS_TOPOLOGY_ERRORS(c->disk_sb.sb, 0);
940 		write_sb = true;
941 	}
942 
943 	if (bch2_blacklist_entries_gc(c))
944 		write_sb = true;
945 
946 	if (write_sb)
947 		bch2_write_super(c);
948 	mutex_unlock(&c->sb_lock);
949 
950 	if (!(c->sb.compat & (1ULL << BCH_COMPAT_extents_above_btree_updates_done)) ||
951 	    c->sb.version_min < bcachefs_metadata_version_btree_ptr_sectors_written) {
952 		struct bch_move_stats stats;
953 
954 		bch2_move_stats_init(&stats, "recovery");
955 
956 		struct printbuf buf = PRINTBUF;
957 		bch2_version_to_text(&buf, c->sb.version_min);
958 		bch_info(c, "scanning for old btree nodes: min_version %s", buf.buf);
959 		printbuf_exit(&buf);
960 
961 		ret =   bch2_fs_read_write_early(c) ?:
962 			bch2_scan_old_btree_nodes(c, &stats);
963 		if (ret)
964 			goto err;
965 		bch_info(c, "scanning for old btree nodes done");
966 	}
967 
968 	ret = 0;
969 out:
970 	bch2_flush_fsck_errs(c);
971 
972 	if (!c->opts.retain_recovery_info) {
973 		bch2_journal_keys_put_initial(c);
974 		bch2_find_btree_nodes_exit(&c->found_btree_nodes);
975 	}
976 	if (!IS_ERR(clean))
977 		kfree(clean);
978 
979 	if (!ret &&
980 	    test_bit(BCH_FS_need_delete_dead_snapshots, &c->flags) &&
981 	    !c->opts.nochanges) {
982 		bch2_fs_read_write_early(c);
983 		bch2_delete_dead_snapshots_async(c);
984 	}
985 
986 	bch_err_fn(c, ret);
987 	return ret;
988 err:
989 fsck_err:
990 	bch2_fs_emergency_read_only(c);
991 	goto out;
992 }
993 
994 int bch2_fs_initialize(struct bch_fs *c)
995 {
996 	struct bch_inode_unpacked root_inode, lostfound_inode;
997 	struct bkey_inode_buf packed_inode;
998 	struct qstr lostfound = QSTR("lost+found");
999 	int ret;
1000 
1001 	bch_notice(c, "initializing new filesystem");
1002 	set_bit(BCH_FS_new_fs, &c->flags);
1003 
1004 	mutex_lock(&c->sb_lock);
1005 	c->disk_sb.sb->compat[0] |= cpu_to_le64(1ULL << BCH_COMPAT_extents_above_btree_updates_done);
1006 	c->disk_sb.sb->compat[0] |= cpu_to_le64(1ULL << BCH_COMPAT_bformat_overflow_done);
1007 
1008 	bch2_check_version_downgrade(c);
1009 
1010 	if (c->opts.version_upgrade != BCH_VERSION_UPGRADE_none) {
1011 		bch2_sb_upgrade(c, bcachefs_metadata_version_current);
1012 		SET_BCH_SB_VERSION_UPGRADE_COMPLETE(c->disk_sb.sb, bcachefs_metadata_version_current);
1013 		bch2_write_super(c);
1014 	}
1015 	mutex_unlock(&c->sb_lock);
1016 
1017 	c->curr_recovery_pass = BCH_RECOVERY_PASS_NR;
1018 	set_bit(BCH_FS_btree_running, &c->flags);
1019 	set_bit(BCH_FS_may_go_rw, &c->flags);
1020 
1021 	for (unsigned i = 0; i < BTREE_ID_NR; i++)
1022 		bch2_btree_root_alloc_fake(c, i, 0);
1023 
1024 	ret = bch2_fs_journal_alloc(c);
1025 	if (ret)
1026 		goto err;
1027 
1028 	/*
1029 	 * journal_res_get() will crash if called before this has
1030 	 * set up the journal.pin FIFO and journal.cur pointer:
1031 	 */
1032 	bch2_fs_journal_start(&c->journal, 1);
1033 	set_bit(BCH_FS_accounting_replay_done, &c->flags);
1034 	bch2_journal_set_replay_done(&c->journal);
1035 
1036 	ret = bch2_fs_read_write_early(c);
1037 	if (ret)
1038 		goto err;
1039 
1040 	for_each_member_device(c, ca) {
1041 		ret = bch2_dev_usage_init(ca, false);
1042 		if (ret) {
1043 			bch2_dev_put(ca);
1044 			goto err;
1045 		}
1046 	}
1047 
1048 	/*
1049 	 * Write out the superblock and journal buckets, now that we can do
1050 	 * btree updates
1051 	 */
1052 	bch_verbose(c, "marking superblocks");
1053 	ret = bch2_trans_mark_dev_sbs(c);
1054 	bch_err_msg(c, ret, "marking superblocks");
1055 	if (ret)
1056 		goto err;
1057 
1058 	for_each_online_member(c, ca)
1059 		ca->new_fs_bucket_idx = 0;
1060 
1061 	ret = bch2_fs_freespace_init(c);
1062 	if (ret)
1063 		goto err;
1064 
1065 	ret = bch2_initialize_subvolumes(c);
1066 	if (ret)
1067 		goto err;
1068 
1069 	bch_verbose(c, "reading snapshots table");
1070 	ret = bch2_snapshots_read(c);
1071 	if (ret)
1072 		goto err;
1073 	bch_verbose(c, "reading snapshots done");
1074 
1075 	bch2_inode_init(c, &root_inode, 0, 0, S_IFDIR|0755, 0, NULL);
1076 	root_inode.bi_inum	= BCACHEFS_ROOT_INO;
1077 	root_inode.bi_subvol	= BCACHEFS_ROOT_SUBVOL;
1078 	bch2_inode_pack(&packed_inode, &root_inode);
1079 	packed_inode.inode.k.p.snapshot = U32_MAX;
1080 
1081 	ret = bch2_btree_insert(c, BTREE_ID_inodes, &packed_inode.inode.k_i, NULL, 0, 0);
1082 	bch_err_msg(c, ret, "creating root directory");
1083 	if (ret)
1084 		goto err;
1085 
1086 	bch2_inode_init_early(c, &lostfound_inode);
1087 
1088 	ret = bch2_trans_do(c, NULL, NULL, 0,
1089 		bch2_create_trans(trans,
1090 				  BCACHEFS_ROOT_SUBVOL_INUM,
1091 				  &root_inode, &lostfound_inode,
1092 				  &lostfound,
1093 				  0, 0, S_IFDIR|0700, 0,
1094 				  NULL, NULL, (subvol_inum) { 0 }, 0));
1095 	bch_err_msg(c, ret, "creating lost+found");
1096 	if (ret)
1097 		goto err;
1098 
1099 	c->recovery_pass_done = BCH_RECOVERY_PASS_NR - 1;
1100 
1101 	if (enabled_qtypes(c)) {
1102 		ret = bch2_fs_quota_read(c);
1103 		if (ret)
1104 			goto err;
1105 	}
1106 
1107 	ret = bch2_journal_flush(&c->journal);
1108 	bch_err_msg(c, ret, "writing first journal entry");
1109 	if (ret)
1110 		goto err;
1111 
1112 	mutex_lock(&c->sb_lock);
1113 	SET_BCH_SB_INITIALIZED(c->disk_sb.sb, true);
1114 	SET_BCH_SB_CLEAN(c->disk_sb.sb, false);
1115 
1116 	bch2_write_super(c);
1117 	mutex_unlock(&c->sb_lock);
1118 
1119 	return 0;
1120 err:
1121 	bch_err_fn(c, ret);
1122 	return ret;
1123 }
1124