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