xref: /linux/fs/bcachefs/recovery.c (revision b8e4b0529d59a3ccd0b25a31d3cfc8b0f3b34068)
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 	return cmp_int(l->journal_seq, r->journal_seq);
245 }
246 
247 int bch2_journal_replay(struct bch_fs *c)
248 {
249 	struct journal_keys *keys = &c->journal_keys;
250 	DARRAY(struct journal_key *) keys_sorted = { 0 };
251 	struct journal *j = &c->journal;
252 	u64 start_seq	= c->journal_replay_seq_start;
253 	u64 end_seq	= c->journal_replay_seq_start;
254 	struct btree_trans *trans = NULL;
255 	bool immediate_flush = false;
256 	int ret = 0;
257 
258 	if (keys->nr) {
259 		ret = bch2_journal_log_msg(c, "Starting journal replay (%zu keys in entries %llu-%llu)",
260 					   keys->nr, start_seq, end_seq);
261 		if (ret)
262 			goto err;
263 	}
264 
265 	BUG_ON(!atomic_read(&keys->ref));
266 
267 	move_gap(keys, keys->nr);
268 	trans = bch2_trans_get(c);
269 
270 	/*
271 	 * Replay accounting keys first: we can't allow the write buffer to
272 	 * flush accounting keys until we're done
273 	 */
274 	darray_for_each(*keys, k) {
275 		if (!(k->k->k.type == KEY_TYPE_accounting && !k->allocated))
276 			continue;
277 
278 		cond_resched();
279 
280 		ret = commit_do(trans, NULL, NULL,
281 				BCH_TRANS_COMMIT_no_enospc|
282 				BCH_TRANS_COMMIT_journal_reclaim|
283 				BCH_TRANS_COMMIT_skip_accounting_apply|
284 				BCH_TRANS_COMMIT_no_journal_res,
285 			     bch2_journal_replay_accounting_key(trans, k));
286 		if (bch2_fs_fatal_err_on(ret, c, "error replaying accounting; %s", bch2_err_str(ret)))
287 			goto err;
288 
289 		k->overwritten = true;
290 	}
291 
292 	set_bit(BCH_FS_accounting_replay_done, &c->flags);
293 
294 	/*
295 	 * First, attempt to replay keys in sorted order. This is more
296 	 * efficient - better locality of btree access -  but some might fail if
297 	 * that would cause a journal deadlock.
298 	 */
299 	darray_for_each(*keys, k) {
300 		cond_resched();
301 
302 		/*
303 		 * k->allocated means the key wasn't read in from the journal,
304 		 * rather it was from early repair code
305 		 */
306 		if (k->allocated)
307 			immediate_flush = true;
308 
309 		/* Skip fastpath if we're low on space in the journal */
310 		ret = c->journal.watermark ? -1 :
311 			commit_do(trans, NULL, NULL,
312 				  BCH_TRANS_COMMIT_no_enospc|
313 				  BCH_TRANS_COMMIT_journal_reclaim|
314 				  BCH_TRANS_COMMIT_skip_accounting_apply|
315 				  (!k->allocated ? BCH_TRANS_COMMIT_no_journal_res : 0),
316 			     bch2_journal_replay_key(trans, k));
317 		BUG_ON(!ret && !k->overwritten && k->k->k.type != KEY_TYPE_accounting);
318 		if (ret) {
319 			ret = darray_push(&keys_sorted, k);
320 			if (ret)
321 				goto err;
322 		}
323 	}
324 
325 	/*
326 	 * Now, replay any remaining keys in the order in which they appear in
327 	 * the journal, unpinning those journal entries as we go:
328 	 */
329 	sort(keys_sorted.data, keys_sorted.nr,
330 	     sizeof(keys_sorted.data[0]),
331 	     journal_sort_seq_cmp, NULL);
332 
333 	darray_for_each(keys_sorted, kp) {
334 		cond_resched();
335 
336 		struct journal_key *k = *kp;
337 
338 		if (k->journal_seq)
339 			replay_now_at(j, k->journal_seq);
340 		else
341 			replay_now_at(j, j->replay_journal_seq_end);
342 
343 		ret = commit_do(trans, NULL, NULL,
344 				BCH_TRANS_COMMIT_no_enospc|
345 				BCH_TRANS_COMMIT_skip_accounting_apply|
346 				(!k->allocated
347 				 ? BCH_TRANS_COMMIT_no_journal_res|BCH_WATERMARK_reclaim
348 				 : 0),
349 			     bch2_journal_replay_key(trans, k));
350 		bch_err_msg(c, ret, "while replaying key at btree %s level %u:",
351 			    bch2_btree_id_str(k->btree_id), k->level);
352 		if (ret)
353 			goto err;
354 
355 		BUG_ON(k->btree_id != BTREE_ID_accounting && !k->overwritten);
356 	}
357 
358 	/*
359 	 * We need to put our btree_trans before calling flush_all_pins(), since
360 	 * that will use a btree_trans internally
361 	 */
362 	bch2_trans_put(trans);
363 	trans = NULL;
364 
365 	if (!c->opts.retain_recovery_info &&
366 	    c->recovery_pass_done >= BCH_RECOVERY_PASS_journal_replay)
367 		bch2_journal_keys_put_initial(c);
368 
369 	replay_now_at(j, j->replay_journal_seq_end);
370 	j->replay_journal_seq = 0;
371 
372 	bch2_journal_set_replay_done(j);
373 
374 	/* if we did any repair, flush it immediately */
375 	if (immediate_flush) {
376 		bch2_journal_flush_all_pins(&c->journal);
377 		ret = bch2_journal_meta(&c->journal);
378 	}
379 
380 	if (keys->nr)
381 		bch2_journal_log_msg(c, "journal replay finished");
382 err:
383 	if (trans)
384 		bch2_trans_put(trans);
385 	darray_exit(&keys_sorted);
386 	bch_err_fn(c, ret);
387 	return ret;
388 }
389 
390 /* journal replay early: */
391 
392 static int journal_replay_entry_early(struct bch_fs *c,
393 				      struct jset_entry *entry)
394 {
395 	int ret = 0;
396 
397 	switch (entry->type) {
398 	case BCH_JSET_ENTRY_btree_root: {
399 		struct btree_root *r;
400 
401 		if (fsck_err_on(entry->btree_id >= BTREE_ID_NR_MAX,
402 				c, invalid_btree_id,
403 				"invalid btree id %u (max %u)",
404 				entry->btree_id, BTREE_ID_NR_MAX))
405 			return 0;
406 
407 		while (entry->btree_id >= c->btree_roots_extra.nr + BTREE_ID_NR) {
408 			ret = darray_push(&c->btree_roots_extra, (struct btree_root) { NULL });
409 			if (ret)
410 				return ret;
411 		}
412 
413 		r = bch2_btree_id_root(c, entry->btree_id);
414 
415 		if (entry->u64s) {
416 			r->level = entry->level;
417 			bkey_copy(&r->key, (struct bkey_i *) entry->start);
418 			r->error = 0;
419 		} else {
420 			r->error = -BCH_ERR_btree_node_read_error;
421 		}
422 		r->alive = true;
423 		break;
424 	}
425 	case BCH_JSET_ENTRY_usage: {
426 		struct jset_entry_usage *u =
427 			container_of(entry, struct jset_entry_usage, entry);
428 
429 		switch (entry->btree_id) {
430 		case BCH_FS_USAGE_key_version:
431 			atomic64_set(&c->key_version, le64_to_cpu(u->v));
432 			break;
433 		}
434 		break;
435 	}
436 	case BCH_JSET_ENTRY_blacklist: {
437 		struct jset_entry_blacklist *bl_entry =
438 			container_of(entry, struct jset_entry_blacklist, entry);
439 
440 		ret = bch2_journal_seq_blacklist_add(c,
441 				le64_to_cpu(bl_entry->seq),
442 				le64_to_cpu(bl_entry->seq) + 1);
443 		break;
444 	}
445 	case BCH_JSET_ENTRY_blacklist_v2: {
446 		struct jset_entry_blacklist_v2 *bl_entry =
447 			container_of(entry, struct jset_entry_blacklist_v2, entry);
448 
449 		ret = bch2_journal_seq_blacklist_add(c,
450 				le64_to_cpu(bl_entry->start),
451 				le64_to_cpu(bl_entry->end) + 1);
452 		break;
453 	}
454 	case BCH_JSET_ENTRY_clock: {
455 		struct jset_entry_clock *clock =
456 			container_of(entry, struct jset_entry_clock, entry);
457 
458 		atomic64_set(&c->io_clock[clock->rw].now, le64_to_cpu(clock->time));
459 	}
460 	}
461 fsck_err:
462 	return ret;
463 }
464 
465 static int journal_replay_early(struct bch_fs *c,
466 				struct bch_sb_field_clean *clean)
467 {
468 	if (clean) {
469 		for (struct jset_entry *entry = clean->start;
470 		     entry != vstruct_end(&clean->field);
471 		     entry = vstruct_next(entry)) {
472 			int ret = journal_replay_entry_early(c, entry);
473 			if (ret)
474 				return ret;
475 		}
476 	} else {
477 		struct genradix_iter iter;
478 		struct journal_replay *i, **_i;
479 
480 		genradix_for_each(&c->journal_entries, iter, _i) {
481 			i = *_i;
482 
483 			if (journal_replay_ignore(i))
484 				continue;
485 
486 			vstruct_for_each(&i->j, entry) {
487 				int ret = journal_replay_entry_early(c, entry);
488 				if (ret)
489 					return ret;
490 			}
491 		}
492 	}
493 
494 	return 0;
495 }
496 
497 /* sb clean section: */
498 
499 static int read_btree_roots(struct bch_fs *c)
500 {
501 	int ret = 0;
502 
503 	for (unsigned i = 0; i < btree_id_nr_alive(c); i++) {
504 		struct btree_root *r = bch2_btree_id_root(c, i);
505 
506 		if (!r->alive)
507 			continue;
508 
509 		if (btree_id_is_alloc(i) && c->opts.reconstruct_alloc)
510 			continue;
511 
512 		if (mustfix_fsck_err_on((ret = r->error),
513 					c, btree_root_bkey_invalid,
514 					"invalid btree root %s",
515 					bch2_btree_id_str(i)) ||
516 		    mustfix_fsck_err_on((ret = r->error = bch2_btree_root_read(c, i, &r->key, r->level)),
517 					c, btree_root_read_error,
518 					"error reading btree root %s l=%u: %s",
519 					bch2_btree_id_str(i), r->level, bch2_err_str(ret))) {
520 			if (btree_id_is_alloc(i)) {
521 				c->recovery_passes_explicit |= BIT_ULL(BCH_RECOVERY_PASS_check_allocations);
522 				c->recovery_passes_explicit |= BIT_ULL(BCH_RECOVERY_PASS_check_alloc_info);
523 				c->recovery_passes_explicit |= BIT_ULL(BCH_RECOVERY_PASS_check_lrus);
524 				c->recovery_passes_explicit |= BIT_ULL(BCH_RECOVERY_PASS_check_extents_to_backpointers);
525 				c->recovery_passes_explicit |= BIT_ULL(BCH_RECOVERY_PASS_check_alloc_to_lru_refs);
526 				c->sb.compat &= ~(1ULL << BCH_COMPAT_alloc_info);
527 				r->error = 0;
528 			} else if (!(c->recovery_passes_explicit & BIT_ULL(BCH_RECOVERY_PASS_scan_for_btree_nodes))) {
529 				bch_info(c, "will run btree node scan");
530 				c->recovery_passes_explicit |= BIT_ULL(BCH_RECOVERY_PASS_scan_for_btree_nodes);
531 				c->recovery_passes_explicit |= BIT_ULL(BCH_RECOVERY_PASS_check_topology);
532 			}
533 
534 			ret = 0;
535 			bch2_btree_lost_data(c, i);
536 		}
537 	}
538 
539 	for (unsigned i = 0; i < BTREE_ID_NR; i++) {
540 		struct btree_root *r = bch2_btree_id_root(c, i);
541 
542 		if (!r->b && !r->error) {
543 			r->alive = false;
544 			r->level = 0;
545 			bch2_btree_root_alloc_fake(c, i, 0);
546 		}
547 	}
548 fsck_err:
549 	return ret;
550 }
551 
552 static bool check_version_upgrade(struct bch_fs *c)
553 {
554 	unsigned latest_version	= bcachefs_metadata_version_current;
555 	unsigned latest_compatible = min(latest_version,
556 					 bch2_latest_compatible_version(c->sb.version));
557 	unsigned old_version = c->sb.version_upgrade_complete ?: c->sb.version;
558 	unsigned new_version = 0;
559 
560 	if (old_version < bcachefs_metadata_required_upgrade_below) {
561 		if (c->opts.version_upgrade == BCH_VERSION_UPGRADE_incompatible ||
562 		    latest_compatible < bcachefs_metadata_required_upgrade_below)
563 			new_version = latest_version;
564 		else
565 			new_version = latest_compatible;
566 	} else {
567 		switch (c->opts.version_upgrade) {
568 		case BCH_VERSION_UPGRADE_compatible:
569 			new_version = latest_compatible;
570 			break;
571 		case BCH_VERSION_UPGRADE_incompatible:
572 			new_version = latest_version;
573 			break;
574 		case BCH_VERSION_UPGRADE_none:
575 			new_version = min(old_version, latest_version);
576 			break;
577 		}
578 	}
579 
580 	if (new_version > old_version) {
581 		struct printbuf buf = PRINTBUF;
582 
583 		if (old_version < bcachefs_metadata_required_upgrade_below)
584 			prt_str(&buf, "Version upgrade required:\n");
585 
586 		if (old_version != c->sb.version) {
587 			prt_str(&buf, "Version upgrade from ");
588 			bch2_version_to_text(&buf, c->sb.version_upgrade_complete);
589 			prt_str(&buf, " to ");
590 			bch2_version_to_text(&buf, c->sb.version);
591 			prt_str(&buf, " incomplete\n");
592 		}
593 
594 		prt_printf(&buf, "Doing %s version upgrade from ",
595 			   BCH_VERSION_MAJOR(old_version) != BCH_VERSION_MAJOR(new_version)
596 			   ? "incompatible" : "compatible");
597 		bch2_version_to_text(&buf, old_version);
598 		prt_str(&buf, " to ");
599 		bch2_version_to_text(&buf, new_version);
600 		prt_newline(&buf);
601 
602 		struct bch_sb_field_ext *ext = bch2_sb_field_get(c->disk_sb.sb, ext);
603 		__le64 passes = ext->recovery_passes_required[0];
604 		bch2_sb_set_upgrade(c, old_version, new_version);
605 		passes = ext->recovery_passes_required[0] & ~passes;
606 
607 		if (passes) {
608 			prt_str(&buf, "  running recovery passes: ");
609 			prt_bitflags(&buf, bch2_recovery_passes,
610 				     bch2_recovery_passes_from_stable(le64_to_cpu(passes)));
611 		}
612 
613 		bch_info(c, "%s", buf.buf);
614 
615 		bch2_sb_upgrade(c, new_version);
616 
617 		printbuf_exit(&buf);
618 		return true;
619 	}
620 
621 	return false;
622 }
623 
624 int bch2_fs_recovery(struct bch_fs *c)
625 {
626 	struct bch_sb_field_clean *clean = NULL;
627 	struct jset *last_journal_entry = NULL;
628 	u64 last_seq = 0, blacklist_seq, journal_seq;
629 	int ret = 0;
630 
631 	if (c->sb.clean) {
632 		clean = bch2_read_superblock_clean(c);
633 		ret = PTR_ERR_OR_ZERO(clean);
634 		if (ret)
635 			goto err;
636 
637 		bch_info(c, "recovering from clean shutdown, journal seq %llu",
638 			 le64_to_cpu(clean->journal_seq));
639 	} else {
640 		bch_info(c, "recovering from unclean shutdown");
641 	}
642 
643 	if (!(c->sb.features & (1ULL << BCH_FEATURE_new_extent_overwrite))) {
644 		bch_err(c, "feature new_extent_overwrite not set, filesystem no longer supported");
645 		ret = -EINVAL;
646 		goto err;
647 	}
648 
649 	if (!c->sb.clean &&
650 	    !(c->sb.features & (1ULL << BCH_FEATURE_extents_above_btree_updates))) {
651 		bch_err(c, "filesystem needs recovery from older version; run fsck from older bcachefs-tools to fix");
652 		ret = -EINVAL;
653 		goto err;
654 	}
655 
656 	if (c->opts.norecovery)
657 		c->opts.recovery_pass_last = BCH_RECOVERY_PASS_journal_replay - 1;
658 
659 	mutex_lock(&c->sb_lock);
660 	struct bch_sb_field_ext *ext = bch2_sb_field_get(c->disk_sb.sb, ext);
661 	bool write_sb = false;
662 
663 	if (BCH_SB_HAS_TOPOLOGY_ERRORS(c->disk_sb.sb)) {
664 		ext->recovery_passes_required[0] |=
665 			cpu_to_le64(bch2_recovery_passes_to_stable(BIT_ULL(BCH_RECOVERY_PASS_check_topology)));
666 		write_sb = true;
667 	}
668 
669 	u64 sb_passes = bch2_recovery_passes_from_stable(le64_to_cpu(ext->recovery_passes_required[0]));
670 	if (sb_passes) {
671 		struct printbuf buf = PRINTBUF;
672 		prt_str(&buf, "superblock requires following recovery passes to be run:\n  ");
673 		prt_bitflags(&buf, bch2_recovery_passes, sb_passes);
674 		bch_info(c, "%s", buf.buf);
675 		printbuf_exit(&buf);
676 	}
677 
678 	if (bch2_check_version_downgrade(c)) {
679 		struct printbuf buf = PRINTBUF;
680 
681 		prt_str(&buf, "Version downgrade required:");
682 
683 		__le64 passes = ext->recovery_passes_required[0];
684 		bch2_sb_set_downgrade(c,
685 				      BCH_VERSION_MINOR(bcachefs_metadata_version_current),
686 				      BCH_VERSION_MINOR(c->sb.version));
687 		passes = ext->recovery_passes_required[0] & ~passes;
688 		if (passes) {
689 			prt_str(&buf, "\n  running recovery passes: ");
690 			prt_bitflags(&buf, bch2_recovery_passes,
691 				     bch2_recovery_passes_from_stable(le64_to_cpu(passes)));
692 		}
693 
694 		bch_info(c, "%s", buf.buf);
695 		printbuf_exit(&buf);
696 		write_sb = true;
697 	}
698 
699 	if (check_version_upgrade(c))
700 		write_sb = true;
701 
702 	c->recovery_passes_explicit |= bch2_recovery_passes_from_stable(le64_to_cpu(ext->recovery_passes_required[0]));
703 
704 	if (write_sb)
705 		bch2_write_super(c);
706 	mutex_unlock(&c->sb_lock);
707 
708 	if (c->opts.fsck && IS_ENABLED(CONFIG_BCACHEFS_DEBUG))
709 		c->recovery_passes_explicit |= BIT_ULL(BCH_RECOVERY_PASS_check_topology);
710 
711 	if (c->opts.fsck)
712 		set_bit(BCH_FS_fsck_running, &c->flags);
713 
714 	ret = bch2_blacklist_table_initialize(c);
715 	if (ret) {
716 		bch_err(c, "error initializing blacklist table");
717 		goto err;
718 	}
719 
720 	bch2_journal_pos_from_member_info_resume(c);
721 
722 	if (!c->sb.clean || c->opts.retain_recovery_info) {
723 		struct genradix_iter iter;
724 		struct journal_replay **i;
725 
726 		bch_verbose(c, "starting journal read");
727 		ret = bch2_journal_read(c, &last_seq, &blacklist_seq, &journal_seq);
728 		if (ret)
729 			goto err;
730 
731 		/*
732 		 * note: cmd_list_journal needs the blacklist table fully up to date so
733 		 * it can asterisk ignored journal entries:
734 		 */
735 		if (c->opts.read_journal_only)
736 			goto out;
737 
738 		genradix_for_each_reverse(&c->journal_entries, iter, i)
739 			if (!journal_replay_ignore(*i)) {
740 				last_journal_entry = &(*i)->j;
741 				break;
742 			}
743 
744 		if (mustfix_fsck_err_on(c->sb.clean &&
745 					last_journal_entry &&
746 					!journal_entry_empty(last_journal_entry), c,
747 				clean_but_journal_not_empty,
748 				"filesystem marked clean but journal not empty")) {
749 			c->sb.compat &= ~(1ULL << BCH_COMPAT_alloc_info);
750 			SET_BCH_SB_CLEAN(c->disk_sb.sb, false);
751 			c->sb.clean = false;
752 		}
753 
754 		if (!last_journal_entry) {
755 			fsck_err_on(!c->sb.clean, c,
756 				    dirty_but_no_journal_entries,
757 				    "no journal entries found");
758 			if (clean)
759 				goto use_clean;
760 
761 			genradix_for_each_reverse(&c->journal_entries, iter, i)
762 				if (*i) {
763 					last_journal_entry = &(*i)->j;
764 					(*i)->ignore_blacklisted = false;
765 					(*i)->ignore_not_dirty= false;
766 					/*
767 					 * This was probably a NO_FLUSH entry,
768 					 * so last_seq was garbage - but we know
769 					 * we're only using a single journal
770 					 * entry, set it here:
771 					 */
772 					(*i)->j.last_seq = (*i)->j.seq;
773 					break;
774 				}
775 		}
776 
777 		ret = bch2_journal_keys_sort(c);
778 		if (ret)
779 			goto err;
780 
781 		if (c->sb.clean && last_journal_entry) {
782 			ret = bch2_verify_superblock_clean(c, &clean,
783 						      last_journal_entry);
784 			if (ret)
785 				goto err;
786 		}
787 	} else {
788 use_clean:
789 		if (!clean) {
790 			bch_err(c, "no superblock clean section found");
791 			ret = -BCH_ERR_fsck_repair_impossible;
792 			goto err;
793 
794 		}
795 		blacklist_seq = journal_seq = le64_to_cpu(clean->journal_seq) + 1;
796 	}
797 
798 	c->journal_replay_seq_start	= last_seq;
799 	c->journal_replay_seq_end	= blacklist_seq - 1;
800 
801 	if (c->opts.reconstruct_alloc)
802 		bch2_reconstruct_alloc(c);
803 
804 	zero_out_btree_mem_ptr(&c->journal_keys);
805 
806 	ret = journal_replay_early(c, clean);
807 	if (ret)
808 		goto err;
809 
810 	/*
811 	 * After an unclean shutdown, skip then next few journal sequence
812 	 * numbers as they may have been referenced by btree writes that
813 	 * happened before their corresponding journal writes - those btree
814 	 * writes need to be ignored, by skipping and blacklisting the next few
815 	 * journal sequence numbers:
816 	 */
817 	if (!c->sb.clean)
818 		journal_seq += 8;
819 
820 	if (blacklist_seq != journal_seq) {
821 		ret =   bch2_journal_log_msg(c, "blacklisting entries %llu-%llu",
822 					     blacklist_seq, journal_seq) ?:
823 			bch2_journal_seq_blacklist_add(c,
824 					blacklist_seq, journal_seq);
825 		if (ret) {
826 			bch_err_msg(c, ret, "error creating new journal seq blacklist entry");
827 			goto err;
828 		}
829 	}
830 
831 	ret =   bch2_journal_log_msg(c, "starting journal at entry %llu, replaying %llu-%llu",
832 				     journal_seq, last_seq, blacklist_seq - 1) ?:
833 		bch2_fs_journal_start(&c->journal, journal_seq);
834 	if (ret)
835 		goto err;
836 
837 	/*
838 	 * Skip past versions that might have possibly been used (as nonces),
839 	 * but hadn't had their pointers written:
840 	 */
841 	if (c->sb.encryption_type && !c->sb.clean)
842 		atomic64_add(1 << 16, &c->key_version);
843 
844 	ret = read_btree_roots(c);
845 	if (ret)
846 		goto err;
847 
848 	set_bit(BCH_FS_btree_running, &c->flags);
849 
850 	ret = bch2_sb_set_upgrade_extra(c);
851 
852 	ret = bch2_run_recovery_passes(c);
853 	if (ret)
854 		goto err;
855 
856 	clear_bit(BCH_FS_fsck_running, &c->flags);
857 
858 	/* fsync if we fixed errors */
859 	if (test_bit(BCH_FS_errors_fixed, &c->flags) &&
860 	    bch2_write_ref_tryget(c, BCH_WRITE_REF_fsync)) {
861 		bch2_journal_flush_all_pins(&c->journal);
862 		bch2_journal_meta(&c->journal);
863 		bch2_write_ref_put(c, BCH_WRITE_REF_fsync);
864 	}
865 
866 	/* If we fixed errors, verify that fs is actually clean now: */
867 	if (IS_ENABLED(CONFIG_BCACHEFS_DEBUG) &&
868 	    test_bit(BCH_FS_errors_fixed, &c->flags) &&
869 	    !test_bit(BCH_FS_errors_not_fixed, &c->flags) &&
870 	    !test_bit(BCH_FS_error, &c->flags)) {
871 		bch2_flush_fsck_errs(c);
872 
873 		bch_info(c, "Fixed errors, running fsck a second time to verify fs is clean");
874 		clear_bit(BCH_FS_errors_fixed, &c->flags);
875 
876 		c->curr_recovery_pass = BCH_RECOVERY_PASS_check_alloc_info;
877 
878 		ret = bch2_run_recovery_passes(c);
879 		if (ret)
880 			goto err;
881 
882 		if (test_bit(BCH_FS_errors_fixed, &c->flags) ||
883 		    test_bit(BCH_FS_errors_not_fixed, &c->flags)) {
884 			bch_err(c, "Second fsck run was not clean");
885 			set_bit(BCH_FS_errors_not_fixed, &c->flags);
886 		}
887 
888 		set_bit(BCH_FS_errors_fixed, &c->flags);
889 	}
890 
891 	if (enabled_qtypes(c)) {
892 		bch_verbose(c, "reading quotas");
893 		ret = bch2_fs_quota_read(c);
894 		if (ret)
895 			goto err;
896 		bch_verbose(c, "quotas done");
897 	}
898 
899 	mutex_lock(&c->sb_lock);
900 	ext = bch2_sb_field_get(c->disk_sb.sb, ext);
901 	write_sb = false;
902 
903 	if (BCH_SB_VERSION_UPGRADE_COMPLETE(c->disk_sb.sb) != le16_to_cpu(c->disk_sb.sb->version)) {
904 		SET_BCH_SB_VERSION_UPGRADE_COMPLETE(c->disk_sb.sb, le16_to_cpu(c->disk_sb.sb->version));
905 		write_sb = true;
906 	}
907 
908 	if (!test_bit(BCH_FS_error, &c->flags) &&
909 	    !(c->disk_sb.sb->compat[0] & cpu_to_le64(1ULL << BCH_COMPAT_alloc_info))) {
910 		c->disk_sb.sb->compat[0] |= cpu_to_le64(1ULL << BCH_COMPAT_alloc_info);
911 		write_sb = true;
912 	}
913 
914 	if (!test_bit(BCH_FS_error, &c->flags) &&
915 	    !bch2_is_zero(ext->errors_silent, sizeof(ext->errors_silent))) {
916 		memset(ext->errors_silent, 0, sizeof(ext->errors_silent));
917 		write_sb = true;
918 	}
919 
920 	if (c->opts.fsck &&
921 	    !test_bit(BCH_FS_error, &c->flags) &&
922 	    c->recovery_pass_done == BCH_RECOVERY_PASS_NR - 1 &&
923 	    ext->btrees_lost_data) {
924 		ext->btrees_lost_data = 0;
925 		write_sb = true;
926 	}
927 
928 	if (c->opts.fsck &&
929 	    !test_bit(BCH_FS_error, &c->flags) &&
930 	    !test_bit(BCH_FS_errors_not_fixed, &c->flags)) {
931 		SET_BCH_SB_HAS_ERRORS(c->disk_sb.sb, 0);
932 		SET_BCH_SB_HAS_TOPOLOGY_ERRORS(c->disk_sb.sb, 0);
933 		write_sb = true;
934 	}
935 
936 	if (bch2_blacklist_entries_gc(c))
937 		write_sb = true;
938 
939 	if (write_sb)
940 		bch2_write_super(c);
941 	mutex_unlock(&c->sb_lock);
942 
943 	if (!(c->sb.compat & (1ULL << BCH_COMPAT_extents_above_btree_updates_done)) ||
944 	    c->sb.version_min < bcachefs_metadata_version_btree_ptr_sectors_written) {
945 		struct bch_move_stats stats;
946 
947 		bch2_move_stats_init(&stats, "recovery");
948 
949 		struct printbuf buf = PRINTBUF;
950 		bch2_version_to_text(&buf, c->sb.version_min);
951 		bch_info(c, "scanning for old btree nodes: min_version %s", buf.buf);
952 		printbuf_exit(&buf);
953 
954 		ret =   bch2_fs_read_write_early(c) ?:
955 			bch2_scan_old_btree_nodes(c, &stats);
956 		if (ret)
957 			goto err;
958 		bch_info(c, "scanning for old btree nodes done");
959 	}
960 
961 	ret = 0;
962 out:
963 	bch2_flush_fsck_errs(c);
964 
965 	if (!c->opts.retain_recovery_info) {
966 		bch2_journal_keys_put_initial(c);
967 		bch2_find_btree_nodes_exit(&c->found_btree_nodes);
968 	}
969 	if (!IS_ERR(clean))
970 		kfree(clean);
971 
972 	if (!ret &&
973 	    test_bit(BCH_FS_need_delete_dead_snapshots, &c->flags) &&
974 	    !c->opts.nochanges) {
975 		bch2_fs_read_write_early(c);
976 		bch2_delete_dead_snapshots_async(c);
977 	}
978 
979 	bch_err_fn(c, ret);
980 	return ret;
981 err:
982 fsck_err:
983 	bch2_fs_emergency_read_only(c);
984 	goto out;
985 }
986 
987 int bch2_fs_initialize(struct bch_fs *c)
988 {
989 	struct bch_inode_unpacked root_inode, lostfound_inode;
990 	struct bkey_inode_buf packed_inode;
991 	struct qstr lostfound = QSTR("lost+found");
992 	int ret;
993 
994 	bch_notice(c, "initializing new filesystem");
995 	set_bit(BCH_FS_new_fs, &c->flags);
996 
997 	mutex_lock(&c->sb_lock);
998 	c->disk_sb.sb->compat[0] |= cpu_to_le64(1ULL << BCH_COMPAT_extents_above_btree_updates_done);
999 	c->disk_sb.sb->compat[0] |= cpu_to_le64(1ULL << BCH_COMPAT_bformat_overflow_done);
1000 
1001 	bch2_check_version_downgrade(c);
1002 
1003 	if (c->opts.version_upgrade != BCH_VERSION_UPGRADE_none) {
1004 		bch2_sb_upgrade(c, bcachefs_metadata_version_current);
1005 		SET_BCH_SB_VERSION_UPGRADE_COMPLETE(c->disk_sb.sb, bcachefs_metadata_version_current);
1006 		bch2_write_super(c);
1007 	}
1008 	mutex_unlock(&c->sb_lock);
1009 
1010 	c->curr_recovery_pass = BCH_RECOVERY_PASS_NR;
1011 	set_bit(BCH_FS_btree_running, &c->flags);
1012 	set_bit(BCH_FS_may_go_rw, &c->flags);
1013 
1014 	for (unsigned i = 0; i < BTREE_ID_NR; i++)
1015 		bch2_btree_root_alloc_fake(c, i, 0);
1016 
1017 	ret = bch2_fs_journal_alloc(c);
1018 	if (ret)
1019 		goto err;
1020 
1021 	/*
1022 	 * journal_res_get() will crash if called before this has
1023 	 * set up the journal.pin FIFO and journal.cur pointer:
1024 	 */
1025 	bch2_fs_journal_start(&c->journal, 1);
1026 	set_bit(BCH_FS_accounting_replay_done, &c->flags);
1027 	bch2_journal_set_replay_done(&c->journal);
1028 
1029 	ret = bch2_fs_read_write_early(c);
1030 	if (ret)
1031 		goto err;
1032 
1033 	for_each_member_device(c, ca) {
1034 		ret = bch2_dev_usage_init(ca, false);
1035 		if (ret) {
1036 			bch2_dev_put(ca);
1037 			goto err;
1038 		}
1039 	}
1040 
1041 	/*
1042 	 * Write out the superblock and journal buckets, now that we can do
1043 	 * btree updates
1044 	 */
1045 	bch_verbose(c, "marking superblocks");
1046 	ret = bch2_trans_mark_dev_sbs(c);
1047 	bch_err_msg(c, ret, "marking superblocks");
1048 	if (ret)
1049 		goto err;
1050 
1051 	for_each_online_member(c, ca)
1052 		ca->new_fs_bucket_idx = 0;
1053 
1054 	ret = bch2_fs_freespace_init(c);
1055 	if (ret)
1056 		goto err;
1057 
1058 	ret = bch2_initialize_subvolumes(c);
1059 	if (ret)
1060 		goto err;
1061 
1062 	bch_verbose(c, "reading snapshots table");
1063 	ret = bch2_snapshots_read(c);
1064 	if (ret)
1065 		goto err;
1066 	bch_verbose(c, "reading snapshots done");
1067 
1068 	bch2_inode_init(c, &root_inode, 0, 0, S_IFDIR|0755, 0, NULL);
1069 	root_inode.bi_inum	= BCACHEFS_ROOT_INO;
1070 	root_inode.bi_subvol	= BCACHEFS_ROOT_SUBVOL;
1071 	bch2_inode_pack(&packed_inode, &root_inode);
1072 	packed_inode.inode.k.p.snapshot = U32_MAX;
1073 
1074 	ret = bch2_btree_insert(c, BTREE_ID_inodes, &packed_inode.inode.k_i, NULL, 0, 0);
1075 	bch_err_msg(c, ret, "creating root directory");
1076 	if (ret)
1077 		goto err;
1078 
1079 	bch2_inode_init_early(c, &lostfound_inode);
1080 
1081 	ret = bch2_trans_do(c, NULL, NULL, 0,
1082 		bch2_create_trans(trans,
1083 				  BCACHEFS_ROOT_SUBVOL_INUM,
1084 				  &root_inode, &lostfound_inode,
1085 				  &lostfound,
1086 				  0, 0, S_IFDIR|0700, 0,
1087 				  NULL, NULL, (subvol_inum) { 0 }, 0));
1088 	bch_err_msg(c, ret, "creating lost+found");
1089 	if (ret)
1090 		goto err;
1091 
1092 	c->recovery_pass_done = BCH_RECOVERY_PASS_NR - 1;
1093 
1094 	if (enabled_qtypes(c)) {
1095 		ret = bch2_fs_quota_read(c);
1096 		if (ret)
1097 			goto err;
1098 	}
1099 
1100 	ret = bch2_journal_flush(&c->journal);
1101 	bch_err_msg(c, ret, "writing first journal entry");
1102 	if (ret)
1103 		goto err;
1104 
1105 	mutex_lock(&c->sb_lock);
1106 	SET_BCH_SB_INITIALIZED(c->disk_sb.sb, true);
1107 	SET_BCH_SB_CLEAN(c->disk_sb.sb, false);
1108 
1109 	bch2_write_super(c);
1110 	mutex_unlock(&c->sb_lock);
1111 
1112 	return 0;
1113 err:
1114 	bch_err_fn(c, ret);
1115 	return ret;
1116 }
1117