]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/recovery.c
Update bcachefs sources to ce9293e9d0 bcachefs: Factor out fs-common.c
[bcachefs-tools-debian] / libbcachefs / recovery.c
1 // SPDX-License-Identifier: GPL-2.0
2
3 #include "bcachefs.h"
4 #include "alloc_background.h"
5 #include "btree_gc.h"
6 #include "btree_update.h"
7 #include "btree_update_interior.h"
8 #include "btree_io.h"
9 #include "buckets.h"
10 #include "dirent.h"
11 #include "ec.h"
12 #include "error.h"
13 #include "fs-common.h"
14 #include "fsck.h"
15 #include "journal_io.h"
16 #include "journal_reclaim.h"
17 #include "journal_seq_blacklist.h"
18 #include "quota.h"
19 #include "recovery.h"
20 #include "replicas.h"
21 #include "super-io.h"
22
23 #include <linux/sort.h>
24 #include <linux/stat.h>
25
26 #define QSTR(n) { { { .len = strlen(n) } }, .name = n }
27
28 /* iterate over keys read from the journal: */
29
30 struct journal_iter bch2_journal_iter_init(struct journal_keys *keys,
31                                            enum btree_id id)
32 {
33         return (struct journal_iter) {
34                 .keys           = keys,
35                 .k              = keys->d,
36                 .btree_id       = id,
37         };
38 }
39
40 struct bkey_s_c bch2_journal_iter_peek(struct journal_iter *iter)
41 {
42         while (1) {
43                 if (iter->k == iter->keys->d + iter->keys->nr)
44                         return bkey_s_c_null;
45
46                 if (iter->k->btree_id == iter->btree_id)
47                         return bkey_i_to_s_c(iter->k->k);
48
49                 iter->k++;
50         }
51
52         return bkey_s_c_null;
53 }
54
55 struct bkey_s_c bch2_journal_iter_next(struct journal_iter *iter)
56 {
57         if (iter->k == iter->keys->d + iter->keys->nr)
58                 return bkey_s_c_null;
59
60         iter->k++;
61         return bch2_journal_iter_peek(iter);
62 }
63
64 /* sort and dedup all keys in the journal: */
65
66 static void journal_entries_free(struct list_head *list)
67 {
68
69         while (!list_empty(list)) {
70                 struct journal_replay *i =
71                         list_first_entry(list, struct journal_replay, list);
72                 list_del(&i->list);
73                 kvpfree(i, offsetof(struct journal_replay, j) +
74                         vstruct_bytes(&i->j));
75         }
76 }
77
78 static int journal_sort_key_cmp(const void *_l, const void *_r)
79 {
80         const struct journal_key *l = _l;
81         const struct journal_key *r = _r;
82
83         return cmp_int(l->btree_id, r->btree_id) ?:
84                 bkey_cmp(l->pos, r->pos) ?:
85                 cmp_int(l->journal_seq, r->journal_seq) ?:
86                 cmp_int(l->journal_offset, r->journal_offset);
87 }
88
89 static int journal_sort_seq_cmp(const void *_l, const void *_r)
90 {
91         const struct journal_key *l = _l;
92         const struct journal_key *r = _r;
93
94         return cmp_int(l->journal_seq, r->journal_seq) ?:
95                 cmp_int(l->btree_id, r->btree_id) ?:
96                 bkey_cmp(l->pos, r->pos);
97 }
98
99 static void journal_keys_sift(struct journal_keys *keys, struct journal_key *i)
100 {
101         while (i + 1 < keys->d + keys->nr &&
102                journal_sort_key_cmp(i, i + 1) > 0) {
103                 swap(i[0], i[1]);
104                 i++;
105         }
106 }
107
108 static void journal_keys_free(struct journal_keys *keys)
109 {
110         struct journal_key *i;
111
112         for_each_journal_key(*keys, i)
113                 if (i->allocated)
114                         kfree(i->k);
115         kvfree(keys->d);
116         keys->d = NULL;
117         keys->nr = 0;
118 }
119
120 static struct journal_keys journal_keys_sort(struct list_head *journal_entries)
121 {
122         struct journal_replay *p;
123         struct jset_entry *entry;
124         struct bkey_i *k, *_n;
125         struct journal_keys keys = { NULL }, keys_deduped = { NULL };
126         struct journal_key *i;
127         size_t nr_keys = 0;
128
129         list_for_each_entry(p, journal_entries, list)
130                 for_each_jset_key(k, _n, entry, &p->j)
131                         nr_keys++;
132
133         keys.journal_seq_base = keys_deduped.journal_seq_base =
134                 le64_to_cpu(list_first_entry(journal_entries,
135                                              struct journal_replay,
136                                              list)->j.seq);
137
138         keys.d = kvmalloc(sizeof(keys.d[0]) * nr_keys, GFP_KERNEL);
139         if (!keys.d)
140                 goto err;
141
142         keys_deduped.d = kvmalloc(sizeof(keys.d[0]) * nr_keys * 2, GFP_KERNEL);
143         if (!keys_deduped.d)
144                 goto err;
145
146         list_for_each_entry(p, journal_entries, list)
147                 for_each_jset_key(k, _n, entry, &p->j)
148                         keys.d[keys.nr++] = (struct journal_key) {
149                                 .btree_id       = entry->btree_id,
150                                 .pos            = bkey_start_pos(&k->k),
151                                 .k              = k,
152                                 .journal_seq    = le64_to_cpu(p->j.seq) -
153                                         keys.journal_seq_base,
154                                 .journal_offset = k->_data - p->j._data,
155                         };
156
157         sort(keys.d, nr_keys, sizeof(keys.d[0]), journal_sort_key_cmp, NULL);
158
159         i = keys.d;
160         while (i < keys.d + keys.nr) {
161                 if (i + 1 < keys.d + keys.nr &&
162                     i[0].btree_id == i[1].btree_id &&
163                     !bkey_cmp(i[0].pos, i[1].pos)) {
164                         if (bkey_cmp(i[0].k->k.p, i[1].k->k.p) <= 0) {
165                                 i++;
166                         } else {
167                                 bch2_cut_front(i[1].k->k.p, i[0].k);
168                                 i[0].pos = i[1].k->k.p;
169                                 journal_keys_sift(&keys, i);
170                         }
171                         continue;
172                 }
173
174                 if (i + 1 < keys.d + keys.nr &&
175                     i[0].btree_id == i[1].btree_id &&
176                     bkey_cmp(i[0].k->k.p, bkey_start_pos(&i[1].k->k)) > 0) {
177                         if ((cmp_int(i[0].journal_seq, i[1].journal_seq) ?:
178                              cmp_int(i[0].journal_offset, i[1].journal_offset)) < 0) {
179                                 if (bkey_cmp(i[0].k->k.p, i[1].k->k.p) <= 0) {
180                                         bch2_cut_back(bkey_start_pos(&i[1].k->k), &i[0].k->k);
181                                 } else {
182                                         struct bkey_i *split =
183                                                 kmalloc(bkey_bytes(i[0].k), GFP_KERNEL);
184
185                                         if (!split)
186                                                 goto err;
187
188                                         bkey_copy(split, i[0].k);
189                                         bch2_cut_back(bkey_start_pos(&i[1].k->k), &split->k);
190                                         keys_deduped.d[keys_deduped.nr++] = (struct journal_key) {
191                                                 .btree_id       = i[0].btree_id,
192                                                 .allocated      = true,
193                                                 .pos            = bkey_start_pos(&split->k),
194                                                 .k              = split,
195                                                 .journal_seq    = i[0].journal_seq,
196                                                 .journal_offset = i[0].journal_offset,
197                                         };
198
199                                         bch2_cut_front(i[1].k->k.p, i[0].k);
200                                         i[0].pos = i[1].k->k.p;
201                                         journal_keys_sift(&keys, i);
202                                         continue;
203                                 }
204                         } else {
205                                 if (bkey_cmp(i[0].k->k.p, i[1].k->k.p) >= 0) {
206                                         i[1] = i[0];
207                                         i++;
208                                         continue;
209                                 } else {
210                                         bch2_cut_front(i[0].k->k.p, i[1].k);
211                                         i[1].pos = i[0].k->k.p;
212                                         journal_keys_sift(&keys, i + 1);
213                                         continue;
214                                 }
215                         }
216                 }
217
218                 keys_deduped.d[keys_deduped.nr++] = *i++;
219         }
220
221         kvfree(keys.d);
222         return keys_deduped;
223 err:
224         journal_keys_free(&keys_deduped);
225         kvfree(keys.d);
226         return (struct journal_keys) { NULL };
227 }
228
229 /* journal replay: */
230
231 static void replay_now_at(struct journal *j, u64 seq)
232 {
233         BUG_ON(seq < j->replay_journal_seq);
234         BUG_ON(seq > j->replay_journal_seq_end);
235
236         while (j->replay_journal_seq < seq)
237                 bch2_journal_pin_put(j, j->replay_journal_seq++);
238 }
239
240 static int bch2_extent_replay_key(struct bch_fs *c, enum btree_id btree_id,
241                                   struct bkey_i *k)
242 {
243         struct btree_trans trans;
244         struct btree_iter *iter, *split_iter;
245         /*
246          * We might cause compressed extents to be split, so we need to pass in
247          * a disk_reservation:
248          */
249         struct disk_reservation disk_res =
250                 bch2_disk_reservation_init(c, 0);
251         struct bkey_i *split;
252         struct bpos atomic_end;
253         /*
254          * Some extents aren't equivalent - w.r.t. what the triggers do
255          * - if they're split:
256          */
257         bool remark_if_split = bch2_extent_is_compressed(bkey_i_to_s_c(k)) ||
258                 k->k.type == KEY_TYPE_reflink_p;
259         bool remark = false;
260         int ret;
261
262         bch2_trans_init(&trans, c, BTREE_ITER_MAX, 0);
263 retry:
264         bch2_trans_begin(&trans);
265
266         iter = bch2_trans_get_iter(&trans, btree_id,
267                                    bkey_start_pos(&k->k),
268                                    BTREE_ITER_INTENT);
269
270         do {
271                 ret = bch2_btree_iter_traverse(iter);
272                 if (ret)
273                         goto err;
274
275                 split_iter = bch2_trans_copy_iter(&trans, iter);
276                 ret = PTR_ERR_OR_ZERO(split_iter);
277                 if (ret)
278                         goto err;
279
280                 split = bch2_trans_kmalloc(&trans, bkey_bytes(&k->k));
281                 ret = PTR_ERR_OR_ZERO(split);
282                 if (ret)
283                         goto err;
284
285                 ret = bch2_extent_atomic_end(split_iter, k, &atomic_end);
286                 if (ret)
287                         goto err;
288
289                 if (!remark &&
290                     remark_if_split &&
291                     bkey_cmp(atomic_end, k->k.p) < 0) {
292                         ret = bch2_disk_reservation_add(c, &disk_res,
293                                         k->k.size *
294                                         bch2_bkey_nr_dirty_ptrs(bkey_i_to_s_c(k)),
295                                         BCH_DISK_RESERVATION_NOFAIL);
296                         BUG_ON(ret);
297
298                         remark = true;
299                 }
300
301                 bkey_copy(split, k);
302                 bch2_cut_front(split_iter->pos, split);
303                 bch2_cut_back(atomic_end, &split->k);
304
305                 bch2_trans_update(&trans, split_iter, split);
306                 bch2_btree_iter_set_pos(iter, split->k.p);
307         } while (bkey_cmp(iter->pos, k->k.p) < 0);
308
309         if (remark) {
310                 ret = bch2_trans_mark_key(&trans, bkey_i_to_s_c(k),
311                                           0, -((s64) k->k.size),
312                                           BCH_BUCKET_MARK_OVERWRITE) ?:
313                       bch2_trans_commit(&trans, &disk_res, NULL,
314                                         BTREE_INSERT_ATOMIC|
315                                         BTREE_INSERT_NOFAIL|
316                                         BTREE_INSERT_LAZY_RW|
317                                         BTREE_INSERT_NOMARK_OVERWRITES|
318                                         BTREE_INSERT_NO_CLEAR_REPLICAS);
319         } else {
320                 ret = bch2_trans_commit(&trans, &disk_res, NULL,
321                                         BTREE_INSERT_ATOMIC|
322                                         BTREE_INSERT_NOFAIL|
323                                         BTREE_INSERT_LAZY_RW|
324                                         BTREE_INSERT_JOURNAL_REPLAY|
325                                         BTREE_INSERT_NOMARK);
326         }
327
328         if (ret)
329                 goto err;
330 err:
331         if (ret == -EINTR)
332                 goto retry;
333
334         bch2_disk_reservation_put(c, &disk_res);
335
336         return bch2_trans_exit(&trans) ?: ret;
337 }
338
339 static int bch2_journal_replay(struct bch_fs *c,
340                                struct journal_keys keys)
341 {
342         struct journal *j = &c->journal;
343         struct journal_key *i;
344         int ret;
345
346         sort(keys.d, keys.nr, sizeof(keys.d[0]), journal_sort_seq_cmp, NULL);
347
348         for_each_journal_key(keys, i) {
349                 replay_now_at(j, keys.journal_seq_base + i->journal_seq);
350
351                 if (i->btree_id == BTREE_ID_ALLOC)
352                         ret = bch2_alloc_replay_key(c, i->k);
353                 else if (btree_node_type_is_extents(i->btree_id))
354                         ret = bch2_extent_replay_key(c, i->btree_id, i->k);
355                 else
356                         ret = bch2_btree_insert(c, i->btree_id, i->k,
357                                                 NULL, NULL,
358                                                 BTREE_INSERT_NOFAIL|
359                                                 BTREE_INSERT_LAZY_RW|
360                                                 BTREE_INSERT_JOURNAL_REPLAY|
361                                                 BTREE_INSERT_NOMARK);
362
363                 if (ret) {
364                         bch_err(c, "journal replay: error %d while replaying key",
365                                 ret);
366                         return ret;
367                 }
368
369                 cond_resched();
370         }
371
372         replay_now_at(j, j->replay_journal_seq_end);
373         j->replay_journal_seq = 0;
374
375         bch2_journal_set_replay_done(j);
376         bch2_journal_flush_all_pins(j);
377         return bch2_journal_error(j);
378 }
379
380 static bool journal_empty(struct list_head *journal)
381 {
382         return list_empty(journal) ||
383                 journal_entry_empty(&list_last_entry(journal,
384                                         struct journal_replay, list)->j);
385 }
386
387 static int
388 verify_journal_entries_not_blacklisted_or_missing(struct bch_fs *c,
389                                                   struct list_head *journal)
390 {
391         struct journal_replay *i =
392                 list_last_entry(journal, struct journal_replay, list);
393         u64 start_seq   = le64_to_cpu(i->j.last_seq);
394         u64 end_seq     = le64_to_cpu(i->j.seq);
395         u64 seq         = start_seq;
396         int ret = 0;
397
398         list_for_each_entry(i, journal, list) {
399                 fsck_err_on(seq != le64_to_cpu(i->j.seq), c,
400                         "journal entries %llu-%llu missing! (replaying %llu-%llu)",
401                         seq, le64_to_cpu(i->j.seq) - 1,
402                         start_seq, end_seq);
403
404                 seq = le64_to_cpu(i->j.seq);
405
406                 fsck_err_on(bch2_journal_seq_is_blacklisted(c, seq, false), c,
407                             "found blacklisted journal entry %llu", seq);
408
409                 do {
410                         seq++;
411                 } while (bch2_journal_seq_is_blacklisted(c, seq, false));
412         }
413 fsck_err:
414         return ret;
415 }
416
417 /* journal replay early: */
418
419 static int journal_replay_entry_early(struct bch_fs *c,
420                                       struct jset_entry *entry)
421 {
422         int ret = 0;
423
424         switch (entry->type) {
425         case BCH_JSET_ENTRY_btree_root: {
426                 struct btree_root *r;
427
428                 if (entry->btree_id >= BTREE_ID_NR) {
429                         bch_err(c, "filesystem has unknown btree type %u",
430                                 entry->btree_id);
431                         return -EINVAL;
432                 }
433
434                 r = &c->btree_roots[entry->btree_id];
435
436                 if (entry->u64s) {
437                         r->level = entry->level;
438                         bkey_copy(&r->key, &entry->start[0]);
439                         r->error = 0;
440                 } else {
441                         r->error = -EIO;
442                 }
443                 r->alive = true;
444                 break;
445         }
446         case BCH_JSET_ENTRY_usage: {
447                 struct jset_entry_usage *u =
448                         container_of(entry, struct jset_entry_usage, entry);
449
450                 switch (entry->btree_id) {
451                 case FS_USAGE_RESERVED:
452                         if (entry->level < BCH_REPLICAS_MAX)
453                                 c->usage_base->persistent_reserved[entry->level] =
454                                         le64_to_cpu(u->v);
455                         break;
456                 case FS_USAGE_INODES:
457                         c->usage_base->nr_inodes = le64_to_cpu(u->v);
458                         break;
459                 case FS_USAGE_KEY_VERSION:
460                         atomic64_set(&c->key_version,
461                                      le64_to_cpu(u->v));
462                         break;
463                 }
464
465                 break;
466         }
467         case BCH_JSET_ENTRY_data_usage: {
468                 struct jset_entry_data_usage *u =
469                         container_of(entry, struct jset_entry_data_usage, entry);
470                 ret = bch2_replicas_set_usage(c, &u->r,
471                                               le64_to_cpu(u->v));
472                 break;
473         }
474         case BCH_JSET_ENTRY_blacklist: {
475                 struct jset_entry_blacklist *bl_entry =
476                         container_of(entry, struct jset_entry_blacklist, entry);
477
478                 ret = bch2_journal_seq_blacklist_add(c,
479                                 le64_to_cpu(bl_entry->seq),
480                                 le64_to_cpu(bl_entry->seq) + 1);
481                 break;
482         }
483         case BCH_JSET_ENTRY_blacklist_v2: {
484                 struct jset_entry_blacklist_v2 *bl_entry =
485                         container_of(entry, struct jset_entry_blacklist_v2, entry);
486
487                 ret = bch2_journal_seq_blacklist_add(c,
488                                 le64_to_cpu(bl_entry->start),
489                                 le64_to_cpu(bl_entry->end) + 1);
490                 break;
491         }
492         }
493
494         return ret;
495 }
496
497 static int journal_replay_early(struct bch_fs *c,
498                                 struct bch_sb_field_clean *clean,
499                                 struct list_head *journal)
500 {
501         struct jset_entry *entry;
502         int ret;
503
504         if (clean) {
505                 c->bucket_clock[READ].hand = le16_to_cpu(clean->read_clock);
506                 c->bucket_clock[WRITE].hand = le16_to_cpu(clean->write_clock);
507
508                 for (entry = clean->start;
509                      entry != vstruct_end(&clean->field);
510                      entry = vstruct_next(entry)) {
511                         ret = journal_replay_entry_early(c, entry);
512                         if (ret)
513                                 return ret;
514                 }
515         } else {
516                 struct journal_replay *i =
517                         list_last_entry(journal, struct journal_replay, list);
518
519                 c->bucket_clock[READ].hand = le16_to_cpu(i->j.read_clock);
520                 c->bucket_clock[WRITE].hand = le16_to_cpu(i->j.write_clock);
521
522                 list_for_each_entry(i, journal, list)
523                         vstruct_for_each(&i->j, entry) {
524                                 ret = journal_replay_entry_early(c, entry);
525                                 if (ret)
526                                         return ret;
527                         }
528         }
529
530         bch2_fs_usage_initialize(c);
531
532         return 0;
533 }
534
535 /* sb clean section: */
536
537 static struct bkey_i *btree_root_find(struct bch_fs *c,
538                                       struct bch_sb_field_clean *clean,
539                                       struct jset *j,
540                                       enum btree_id id, unsigned *level)
541 {
542         struct bkey_i *k;
543         struct jset_entry *entry, *start, *end;
544
545         if (clean) {
546                 start = clean->start;
547                 end = vstruct_end(&clean->field);
548         } else {
549                 start = j->start;
550                 end = vstruct_last(j);
551         }
552
553         for (entry = start; entry < end; entry = vstruct_next(entry))
554                 if (entry->type == BCH_JSET_ENTRY_btree_root &&
555                     entry->btree_id == id)
556                         goto found;
557
558         return NULL;
559 found:
560         if (!entry->u64s)
561                 return ERR_PTR(-EINVAL);
562
563         k = entry->start;
564         *level = entry->level;
565         return k;
566 }
567
568 static int verify_superblock_clean(struct bch_fs *c,
569                                    struct bch_sb_field_clean **cleanp,
570                                    struct jset *j)
571 {
572         unsigned i;
573         struct bch_sb_field_clean *clean = *cleanp;
574         int ret = 0;
575
576         if (!c->sb.clean || !j)
577                 return 0;
578
579         if (mustfix_fsck_err_on(j->seq != clean->journal_seq, c,
580                         "superblock journal seq (%llu) doesn't match journal (%llu) after clean shutdown",
581                         le64_to_cpu(clean->journal_seq),
582                         le64_to_cpu(j->seq))) {
583                 kfree(clean);
584                 *cleanp = NULL;
585                 return 0;
586         }
587
588         mustfix_fsck_err_on(j->read_clock != clean->read_clock, c,
589                         "superblock read clock doesn't match journal after clean shutdown");
590         mustfix_fsck_err_on(j->write_clock != clean->write_clock, c,
591                         "superblock read clock doesn't match journal after clean shutdown");
592
593         for (i = 0; i < BTREE_ID_NR; i++) {
594                 struct bkey_i *k1, *k2;
595                 unsigned l1 = 0, l2 = 0;
596
597                 k1 = btree_root_find(c, clean, NULL, i, &l1);
598                 k2 = btree_root_find(c, NULL, j, i, &l2);
599
600                 if (!k1 && !k2)
601                         continue;
602
603                 mustfix_fsck_err_on(!k1 || !k2 ||
604                                     IS_ERR(k1) ||
605                                     IS_ERR(k2) ||
606                                     k1->k.u64s != k2->k.u64s ||
607                                     memcmp(k1, k2, bkey_bytes(k1)) ||
608                                     l1 != l2, c,
609                         "superblock btree root doesn't match journal after clean shutdown");
610         }
611 fsck_err:
612         return ret;
613 }
614
615 static struct bch_sb_field_clean *read_superblock_clean(struct bch_fs *c)
616 {
617         struct bch_sb_field_clean *clean, *sb_clean;
618         int ret;
619
620         mutex_lock(&c->sb_lock);
621         sb_clean = bch2_sb_get_clean(c->disk_sb.sb);
622
623         if (fsck_err_on(!sb_clean, c,
624                         "superblock marked clean but clean section not present")) {
625                 SET_BCH_SB_CLEAN(c->disk_sb.sb, false);
626                 c->sb.clean = false;
627                 mutex_unlock(&c->sb_lock);
628                 return NULL;
629         }
630
631         clean = kmemdup(sb_clean, vstruct_bytes(&sb_clean->field),
632                         GFP_KERNEL);
633         if (!clean) {
634                 mutex_unlock(&c->sb_lock);
635                 return ERR_PTR(-ENOMEM);
636         }
637
638         if (le16_to_cpu(c->disk_sb.sb->version) <
639             bcachefs_metadata_version_bkey_renumber)
640                 bch2_sb_clean_renumber(clean, READ);
641
642         mutex_unlock(&c->sb_lock);
643
644         return clean;
645 fsck_err:
646         mutex_unlock(&c->sb_lock);
647         return ERR_PTR(ret);
648 }
649
650 static int read_btree_roots(struct bch_fs *c)
651 {
652         unsigned i;
653         int ret = 0;
654
655         for (i = 0; i < BTREE_ID_NR; i++) {
656                 struct btree_root *r = &c->btree_roots[i];
657
658                 if (!r->alive)
659                         continue;
660
661                 if (i == BTREE_ID_ALLOC &&
662                     c->opts.reconstruct_alloc) {
663                         c->sb.compat &= ~(1ULL << BCH_COMPAT_FEAT_ALLOC_INFO);
664                         continue;
665                 }
666
667
668                 if (r->error) {
669                         __fsck_err(c, i == BTREE_ID_ALLOC
670                                    ? FSCK_CAN_IGNORE : 0,
671                                    "invalid btree root %s",
672                                    bch2_btree_ids[i]);
673                         if (i == BTREE_ID_ALLOC)
674                                 c->sb.compat &= ~(1ULL << BCH_COMPAT_FEAT_ALLOC_INFO);
675                 }
676
677                 ret = bch2_btree_root_read(c, i, &r->key, r->level);
678                 if (ret) {
679                         __fsck_err(c, i == BTREE_ID_ALLOC
680                                    ? FSCK_CAN_IGNORE : 0,
681                                    "error reading btree root %s",
682                                    bch2_btree_ids[i]);
683                         if (i == BTREE_ID_ALLOC)
684                                 c->sb.compat &= ~(1ULL << BCH_COMPAT_FEAT_ALLOC_INFO);
685                 }
686         }
687
688         for (i = 0; i < BTREE_ID_NR; i++)
689                 if (!c->btree_roots[i].b)
690                         bch2_btree_root_alloc(c, i);
691 fsck_err:
692         return ret;
693 }
694
695 int bch2_fs_recovery(struct bch_fs *c)
696 {
697         const char *err = "cannot allocate memory";
698         struct bch_sb_field_clean *clean = NULL;
699         u64 journal_seq;
700         LIST_HEAD(journal_entries);
701         struct journal_keys journal_keys = { NULL };
702         bool wrote = false, write_sb = false;
703         int ret;
704
705         if (c->sb.clean)
706                 clean = read_superblock_clean(c);
707         ret = PTR_ERR_OR_ZERO(clean);
708         if (ret)
709                 goto err;
710
711         if (c->sb.clean)
712                 bch_info(c, "recovering from clean shutdown, journal seq %llu",
713                          le64_to_cpu(clean->journal_seq));
714
715         if (!c->replicas.entries) {
716                 bch_info(c, "building replicas info");
717                 set_bit(BCH_FS_REBUILD_REPLICAS, &c->flags);
718         }
719
720         if (!c->sb.clean || c->opts.fsck) {
721                 struct jset *j;
722
723                 ret = bch2_journal_read(c, &journal_entries);
724                 if (ret)
725                         goto err;
726
727                 if (mustfix_fsck_err_on(c->sb.clean && !journal_empty(&journal_entries), c,
728                                 "filesystem marked clean but journal not empty")) {
729                         c->sb.compat &= ~(1ULL << BCH_COMPAT_FEAT_ALLOC_INFO);
730                         SET_BCH_SB_CLEAN(c->disk_sb.sb, false);
731                         c->sb.clean = false;
732                 }
733
734                 if (!c->sb.clean && list_empty(&journal_entries)) {
735                         bch_err(c, "no journal entries found");
736                         ret = BCH_FSCK_REPAIR_IMPOSSIBLE;
737                         goto err;
738                 }
739
740                 journal_keys = journal_keys_sort(&journal_entries);
741                 if (!journal_keys.d) {
742                         ret = -ENOMEM;
743                         goto err;
744                 }
745
746                 j = &list_last_entry(&journal_entries,
747                                      struct journal_replay, list)->j;
748
749                 ret = verify_superblock_clean(c, &clean, j);
750                 if (ret)
751                         goto err;
752
753                 journal_seq = le64_to_cpu(j->seq) + 1;
754         } else {
755                 journal_seq = le64_to_cpu(clean->journal_seq) + 1;
756         }
757
758         ret = journal_replay_early(c, clean, &journal_entries);
759         if (ret)
760                 goto err;
761
762         if (!c->sb.clean) {
763                 ret = bch2_journal_seq_blacklist_add(c,
764                                                      journal_seq,
765                                                      journal_seq + 4);
766                 if (ret) {
767                         bch_err(c, "error creating new journal seq blacklist entry");
768                         goto err;
769                 }
770
771                 journal_seq += 4;
772         }
773
774         ret = bch2_blacklist_table_initialize(c);
775
776         if (!list_empty(&journal_entries)) {
777                 ret = verify_journal_entries_not_blacklisted_or_missing(c,
778                                                         &journal_entries);
779                 if (ret)
780                         goto err;
781         }
782
783         ret = bch2_fs_journal_start(&c->journal, journal_seq,
784                                     &journal_entries);
785         if (ret)
786                 goto err;
787
788         ret = read_btree_roots(c);
789         if (ret)
790                 goto err;
791
792         bch_verbose(c, "starting alloc read");
793         err = "error reading allocation information";
794         ret = bch2_alloc_read(c, &journal_keys);
795         if (ret)
796                 goto err;
797         bch_verbose(c, "alloc read done");
798
799         bch_verbose(c, "starting stripes_read");
800         err = "error reading stripes";
801         ret = bch2_stripes_read(c, &journal_keys);
802         if (ret)
803                 goto err;
804         bch_verbose(c, "stripes_read done");
805
806         set_bit(BCH_FS_ALLOC_READ_DONE, &c->flags);
807
808         if ((c->sb.compat & (1ULL << BCH_COMPAT_FEAT_ALLOC_INFO)) &&
809             !(c->sb.compat & (1ULL << BCH_COMPAT_FEAT_ALLOC_METADATA))) {
810                 /*
811                  * interior btree node updates aren't consistent with the
812                  * journal; after an unclean shutdown we have to walk all
813                  * pointers to metadata:
814                  */
815                 bch_info(c, "starting metadata mark and sweep");
816                 err = "error in mark and sweep";
817                 ret = bch2_gc(c, NULL, true, true);
818                 if (ret)
819                         goto err;
820                 bch_verbose(c, "mark and sweep done");
821         }
822
823         if (c->opts.fsck ||
824             !(c->sb.compat & (1ULL << BCH_COMPAT_FEAT_ALLOC_INFO)) ||
825             test_bit(BCH_FS_REBUILD_REPLICAS, &c->flags)) {
826                 bch_info(c, "starting mark and sweep");
827                 err = "error in mark and sweep";
828                 ret = bch2_gc(c, &journal_keys, true, false);
829                 if (ret)
830                         goto err;
831                 bch_verbose(c, "mark and sweep done");
832         }
833
834         clear_bit(BCH_FS_REBUILD_REPLICAS, &c->flags);
835         set_bit(BCH_FS_INITIAL_GC_DONE, &c->flags);
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         if (c->opts.norecovery)
845                 goto out;
846
847         bch_verbose(c, "starting journal replay");
848         err = "journal replay failed";
849         ret = bch2_journal_replay(c, journal_keys);
850         if (ret)
851                 goto err;
852         bch_verbose(c, "journal replay done");
853
854         if (!c->opts.nochanges) {
855                 /*
856                  * note that even when filesystem was clean there might be work
857                  * to do here, if we ran gc (because of fsck) which recalculated
858                  * oldest_gen:
859                  */
860                 bch_verbose(c, "writing allocation info");
861                 err = "error writing out alloc info";
862                 ret = bch2_stripes_write(c, BTREE_INSERT_LAZY_RW, &wrote) ?:
863                         bch2_alloc_write(c, BTREE_INSERT_LAZY_RW, &wrote);
864                 if (ret) {
865                         bch_err(c, "error writing alloc info");
866                         goto err;
867                 }
868                 bch_verbose(c, "alloc write done");
869         }
870
871         if (!c->sb.clean) {
872                 if (!(c->sb.features & (1 << BCH_FEATURE_ATOMIC_NLINK))) {
873                         bch_info(c, "checking inode link counts");
874                         err = "error in recovery";
875                         ret = bch2_fsck_inode_nlink(c);
876                         if (ret)
877                                 goto err;
878                         bch_verbose(c, "check inodes done");
879
880                 } else {
881                         bch_verbose(c, "checking for deleted inodes");
882                         err = "error in recovery";
883                         ret = bch2_fsck_walk_inodes_only(c);
884                         if (ret)
885                                 goto err;
886                         bch_verbose(c, "check inodes done");
887                 }
888         }
889
890         if (c->opts.fsck) {
891                 bch_info(c, "starting fsck");
892                 err = "error in fsck";
893                 ret = bch2_fsck_full(c);
894                 if (ret)
895                         goto err;
896                 bch_verbose(c, "fsck done");
897         }
898
899         if (enabled_qtypes(c)) {
900                 bch_verbose(c, "reading quotas");
901                 ret = bch2_fs_quota_read(c);
902                 if (ret)
903                         goto err;
904                 bch_verbose(c, "quotas done");
905         }
906
907         mutex_lock(&c->sb_lock);
908         if (c->opts.version_upgrade) {
909                 if (c->sb.version < bcachefs_metadata_version_new_versioning)
910                         c->disk_sb.sb->version_min =
911                                 le16_to_cpu(bcachefs_metadata_version_min);
912                 c->disk_sb.sb->version = le16_to_cpu(bcachefs_metadata_version_current);
913                 write_sb = true;
914         }
915
916         if (!test_bit(BCH_FS_ERROR, &c->flags)) {
917                 c->disk_sb.sb->compat[0] |= 1ULL << BCH_COMPAT_FEAT_ALLOC_INFO;
918                 write_sb = true;
919         }
920
921         if (c->opts.fsck &&
922             !test_bit(BCH_FS_ERROR, &c->flags)) {
923                 c->disk_sb.sb->features[0] |= 1ULL << BCH_FEATURE_ATOMIC_NLINK;
924                 SET_BCH_SB_HAS_ERRORS(c->disk_sb.sb, 0);
925                 write_sb = true;
926         }
927
928         if (write_sb)
929                 bch2_write_super(c);
930         mutex_unlock(&c->sb_lock);
931
932         if (c->journal_seq_blacklist_table &&
933             c->journal_seq_blacklist_table->nr > 128)
934                 queue_work(system_long_wq, &c->journal_seq_blacklist_gc_work);
935 out:
936         ret = 0;
937 err:
938 fsck_err:
939         set_bit(BCH_FS_FSCK_DONE, &c->flags);
940         bch2_flush_fsck_errs(c);
941
942         journal_keys_free(&journal_keys);
943         journal_entries_free(&journal_entries);
944         kfree(clean);
945         if (ret)
946                 bch_err(c, "Error in recovery: %s (%i)", err, ret);
947         else
948                 bch_verbose(c, "ret %i", ret);
949         return ret;
950 }
951
952 int bch2_fs_initialize(struct bch_fs *c)
953 {
954         struct bch_inode_unpacked root_inode, lostfound_inode;
955         struct bkey_inode_buf packed_inode;
956         struct qstr lostfound = QSTR("lost+found");
957         const char *err = "cannot allocate memory";
958         struct bch_dev *ca;
959         LIST_HEAD(journal);
960         unsigned i;
961         int ret;
962
963         bch_notice(c, "initializing new filesystem");
964
965         mutex_lock(&c->sb_lock);
966         for_each_online_member(ca, c, i)
967                 bch2_mark_dev_superblock(c, ca, 0);
968         mutex_unlock(&c->sb_lock);
969
970         set_bit(BCH_FS_ALLOC_READ_DONE, &c->flags);
971         set_bit(BCH_FS_INITIAL_GC_DONE, &c->flags);
972
973         for (i = 0; i < BTREE_ID_NR; i++)
974                 bch2_btree_root_alloc(c, i);
975
976         err = "unable to allocate journal buckets";
977         for_each_online_member(ca, c, i) {
978                 ret = bch2_dev_journal_alloc(ca);
979                 if (ret) {
980                         percpu_ref_put(&ca->io_ref);
981                         goto err;
982                 }
983         }
984
985         /*
986          * journal_res_get() will crash if called before this has
987          * set up the journal.pin FIFO and journal.cur pointer:
988          */
989         bch2_fs_journal_start(&c->journal, 1, &journal);
990         bch2_journal_set_replay_done(&c->journal);
991
992         err = "error going read write";
993         ret = __bch2_fs_read_write(c, true);
994         if (ret)
995                 goto err;
996
997         bch2_inode_init(c, &root_inode, 0, 0,
998                         S_IFDIR|S_IRWXU|S_IRUGO|S_IXUGO, 0, NULL);
999         root_inode.bi_inum = BCACHEFS_ROOT_INO;
1000         bch2_inode_pack(&packed_inode, &root_inode);
1001
1002         err = "error creating root directory";
1003         ret = bch2_btree_insert(c, BTREE_ID_INODES,
1004                                 &packed_inode.inode.k_i,
1005                                 NULL, NULL, 0);
1006         if (ret)
1007                 goto err;
1008
1009         bch2_inode_init_early(c, &lostfound_inode);
1010
1011         err = "error creating lost+found";
1012         ret = bch2_trans_do(c, NULL, BTREE_INSERT_ATOMIC,
1013                 bch2_create_trans(&trans, BCACHEFS_ROOT_INO,
1014                                   &root_inode, &lostfound_inode,
1015                                   &lostfound,
1016                                   0, 0, 0755, 0,
1017                                   NULL, NULL));
1018         if (ret)
1019                 goto err;
1020
1021         if (enabled_qtypes(c)) {
1022                 ret = bch2_fs_quota_read(c);
1023                 if (ret)
1024                         goto err;
1025         }
1026
1027         err = "error writing first journal entry";
1028         ret = bch2_journal_meta(&c->journal);
1029         if (ret)
1030                 goto err;
1031
1032         mutex_lock(&c->sb_lock);
1033         c->disk_sb.sb->version = c->disk_sb.sb->version_min =
1034                 le16_to_cpu(bcachefs_metadata_version_current);
1035         c->disk_sb.sb->features[0] |= 1ULL << BCH_FEATURE_ATOMIC_NLINK;
1036
1037         SET_BCH_SB_INITIALIZED(c->disk_sb.sb, true);
1038         SET_BCH_SB_CLEAN(c->disk_sb.sb, false);
1039
1040         bch2_write_super(c);
1041         mutex_unlock(&c->sb_lock);
1042
1043         return 0;
1044 err:
1045         pr_err("Error initializing new filesystem: %s (%i)", err, ret);
1046         return ret;
1047 }