]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/recovery.c
Update bcachefs sources to 1569db10e2 bcachefs: Use KEY_TYPE_deleted whitouts for...
[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);
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);
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_bkey_sectors_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                 atomic_end = bpos_min(k->k.p, iter->l[0].b->key.k.p);
276
277                 split_iter = bch2_trans_copy_iter(&trans, iter);
278                 ret = PTR_ERR_OR_ZERO(split_iter);
279                 if (ret)
280                         goto err;
281
282                 split = bch2_trans_kmalloc(&trans, bkey_bytes(&k->k));
283                 ret = PTR_ERR_OR_ZERO(split);
284                 if (ret)
285                         goto err;
286
287                 if (!remark &&
288                     remark_if_split &&
289                     bkey_cmp(atomic_end, k->k.p) < 0) {
290                         ret = bch2_disk_reservation_add(c, &disk_res,
291                                         k->k.size *
292                                         bch2_bkey_nr_ptrs_allocated(bkey_i_to_s_c(k)),
293                                         BCH_DISK_RESERVATION_NOFAIL);
294                         BUG_ON(ret);
295
296                         remark = true;
297                 }
298
299                 bkey_copy(split, k);
300                 bch2_cut_front(split_iter->pos, split);
301                 bch2_cut_back(atomic_end, split);
302
303                 bch2_trans_update(&trans, split_iter, split);
304                 bch2_btree_iter_set_pos(iter, split->k.p);
305         } while (bkey_cmp(iter->pos, k->k.p) < 0);
306
307         if (remark) {
308                 ret = bch2_trans_mark_key(&trans, bkey_i_to_s_c(k),
309                                           0, -((s64) k->k.size),
310                                           BCH_BUCKET_MARK_OVERWRITE) ?:
311                       bch2_trans_commit(&trans, &disk_res, NULL,
312                                         BTREE_INSERT_NOFAIL|
313                                         BTREE_INSERT_LAZY_RW|
314                                         BTREE_INSERT_NOMARK_OVERWRITES);
315         } else {
316                 ret = bch2_trans_commit(&trans, &disk_res, NULL,
317                                         BTREE_INSERT_NOFAIL|
318                                         BTREE_INSERT_LAZY_RW|
319                                         BTREE_INSERT_JOURNAL_REPLAY|
320                                         BTREE_INSERT_NOMARK);
321         }
322
323         if (ret)
324                 goto err;
325 err:
326         if (ret == -EINTR)
327                 goto retry;
328
329         bch2_disk_reservation_put(c, &disk_res);
330
331         return bch2_trans_exit(&trans) ?: ret;
332 }
333
334 static int bch2_journal_replay(struct bch_fs *c,
335                                struct journal_keys keys)
336 {
337         struct journal *j = &c->journal;
338         struct journal_key *i;
339         int ret;
340
341         sort(keys.d, keys.nr, sizeof(keys.d[0]), journal_sort_seq_cmp, NULL);
342
343         for_each_journal_key(keys, i) {
344                 replay_now_at(j, keys.journal_seq_base + i->journal_seq);
345
346                 if (i->btree_id == BTREE_ID_ALLOC)
347                         ret = bch2_alloc_replay_key(c, i->k);
348                 else if (btree_node_type_is_extents(i->btree_id))
349                         ret = bch2_extent_replay_key(c, i->btree_id, i->k);
350                 else
351                         ret = bch2_btree_insert(c, i->btree_id, i->k,
352                                                 NULL, NULL,
353                                                 BTREE_INSERT_NOFAIL|
354                                                 BTREE_INSERT_LAZY_RW|
355                                                 BTREE_INSERT_JOURNAL_REPLAY|
356                                                 BTREE_INSERT_NOMARK);
357
358                 if (ret) {
359                         bch_err(c, "journal replay: error %d while replaying key",
360                                 ret);
361                         return ret;
362                 }
363
364                 cond_resched();
365         }
366
367         replay_now_at(j, j->replay_journal_seq_end);
368         j->replay_journal_seq = 0;
369
370         bch2_journal_set_replay_done(j);
371         bch2_journal_flush_all_pins(j);
372         return bch2_journal_error(j);
373 }
374
375 static bool journal_empty(struct list_head *journal)
376 {
377         return list_empty(journal) ||
378                 journal_entry_empty(&list_last_entry(journal,
379                                         struct journal_replay, list)->j);
380 }
381
382 static int
383 verify_journal_entries_not_blacklisted_or_missing(struct bch_fs *c,
384                                                   struct list_head *journal)
385 {
386         struct journal_replay *i =
387                 list_last_entry(journal, struct journal_replay, list);
388         u64 start_seq   = le64_to_cpu(i->j.last_seq);
389         u64 end_seq     = le64_to_cpu(i->j.seq);
390         u64 seq         = start_seq;
391         int ret = 0;
392
393         list_for_each_entry(i, journal, list) {
394                 fsck_err_on(seq != le64_to_cpu(i->j.seq), c,
395                         "journal entries %llu-%llu missing! (replaying %llu-%llu)",
396                         seq, le64_to_cpu(i->j.seq) - 1,
397                         start_seq, end_seq);
398
399                 seq = le64_to_cpu(i->j.seq);
400
401                 fsck_err_on(bch2_journal_seq_is_blacklisted(c, seq, false), c,
402                             "found blacklisted journal entry %llu", seq);
403
404                 do {
405                         seq++;
406                 } while (bch2_journal_seq_is_blacklisted(c, seq, false));
407         }
408 fsck_err:
409         return ret;
410 }
411
412 /* journal replay early: */
413
414 static int journal_replay_entry_early(struct bch_fs *c,
415                                       struct jset_entry *entry)
416 {
417         int ret = 0;
418
419         switch (entry->type) {
420         case BCH_JSET_ENTRY_btree_root: {
421                 struct btree_root *r;
422
423                 if (entry->btree_id >= BTREE_ID_NR) {
424                         bch_err(c, "filesystem has unknown btree type %u",
425                                 entry->btree_id);
426                         return -EINVAL;
427                 }
428
429                 r = &c->btree_roots[entry->btree_id];
430
431                 if (entry->u64s) {
432                         r->level = entry->level;
433                         bkey_copy(&r->key, &entry->start[0]);
434                         r->error = 0;
435                 } else {
436                         r->error = -EIO;
437                 }
438                 r->alive = true;
439                 break;
440         }
441         case BCH_JSET_ENTRY_usage: {
442                 struct jset_entry_usage *u =
443                         container_of(entry, struct jset_entry_usage, entry);
444
445                 switch (entry->btree_id) {
446                 case FS_USAGE_RESERVED:
447                         if (entry->level < BCH_REPLICAS_MAX)
448                                 c->usage_base->persistent_reserved[entry->level] =
449                                         le64_to_cpu(u->v);
450                         break;
451                 case FS_USAGE_INODES:
452                         c->usage_base->nr_inodes = le64_to_cpu(u->v);
453                         break;
454                 case FS_USAGE_KEY_VERSION:
455                         atomic64_set(&c->key_version,
456                                      le64_to_cpu(u->v));
457                         break;
458                 }
459
460                 break;
461         }
462         case BCH_JSET_ENTRY_data_usage: {
463                 struct jset_entry_data_usage *u =
464                         container_of(entry, struct jset_entry_data_usage, entry);
465                 ret = bch2_replicas_set_usage(c, &u->r,
466                                               le64_to_cpu(u->v));
467                 break;
468         }
469         case BCH_JSET_ENTRY_blacklist: {
470                 struct jset_entry_blacklist *bl_entry =
471                         container_of(entry, struct jset_entry_blacklist, entry);
472
473                 ret = bch2_journal_seq_blacklist_add(c,
474                                 le64_to_cpu(bl_entry->seq),
475                                 le64_to_cpu(bl_entry->seq) + 1);
476                 break;
477         }
478         case BCH_JSET_ENTRY_blacklist_v2: {
479                 struct jset_entry_blacklist_v2 *bl_entry =
480                         container_of(entry, struct jset_entry_blacklist_v2, entry);
481
482                 ret = bch2_journal_seq_blacklist_add(c,
483                                 le64_to_cpu(bl_entry->start),
484                                 le64_to_cpu(bl_entry->end) + 1);
485                 break;
486         }
487         }
488
489         return ret;
490 }
491
492 static int journal_replay_early(struct bch_fs *c,
493                                 struct bch_sb_field_clean *clean,
494                                 struct list_head *journal)
495 {
496         struct jset_entry *entry;
497         int ret;
498
499         if (clean) {
500                 c->bucket_clock[READ].hand = le16_to_cpu(clean->read_clock);
501                 c->bucket_clock[WRITE].hand = le16_to_cpu(clean->write_clock);
502
503                 for (entry = clean->start;
504                      entry != vstruct_end(&clean->field);
505                      entry = vstruct_next(entry)) {
506                         ret = journal_replay_entry_early(c, entry);
507                         if (ret)
508                                 return ret;
509                 }
510         } else {
511                 struct journal_replay *i =
512                         list_last_entry(journal, struct journal_replay, list);
513
514                 c->bucket_clock[READ].hand = le16_to_cpu(i->j.read_clock);
515                 c->bucket_clock[WRITE].hand = le16_to_cpu(i->j.write_clock);
516
517                 list_for_each_entry(i, journal, list)
518                         vstruct_for_each(&i->j, entry) {
519                                 ret = journal_replay_entry_early(c, entry);
520                                 if (ret)
521                                         return ret;
522                         }
523         }
524
525         bch2_fs_usage_initialize(c);
526
527         return 0;
528 }
529
530 /* sb clean section: */
531
532 static struct bkey_i *btree_root_find(struct bch_fs *c,
533                                       struct bch_sb_field_clean *clean,
534                                       struct jset *j,
535                                       enum btree_id id, unsigned *level)
536 {
537         struct bkey_i *k;
538         struct jset_entry *entry, *start, *end;
539
540         if (clean) {
541                 start = clean->start;
542                 end = vstruct_end(&clean->field);
543         } else {
544                 start = j->start;
545                 end = vstruct_last(j);
546         }
547
548         for (entry = start; entry < end; entry = vstruct_next(entry))
549                 if (entry->type == BCH_JSET_ENTRY_btree_root &&
550                     entry->btree_id == id)
551                         goto found;
552
553         return NULL;
554 found:
555         if (!entry->u64s)
556                 return ERR_PTR(-EINVAL);
557
558         k = entry->start;
559         *level = entry->level;
560         return k;
561 }
562
563 static int verify_superblock_clean(struct bch_fs *c,
564                                    struct bch_sb_field_clean **cleanp,
565                                    struct jset *j)
566 {
567         unsigned i;
568         struct bch_sb_field_clean *clean = *cleanp;
569         int ret = 0;
570
571         if (!c->sb.clean || !j)
572                 return 0;
573
574         if (mustfix_fsck_err_on(j->seq != clean->journal_seq, c,
575                         "superblock journal seq (%llu) doesn't match journal (%llu) after clean shutdown",
576                         le64_to_cpu(clean->journal_seq),
577                         le64_to_cpu(j->seq))) {
578                 kfree(clean);
579                 *cleanp = NULL;
580                 return 0;
581         }
582
583         mustfix_fsck_err_on(j->read_clock != clean->read_clock, c,
584                         "superblock read clock doesn't match journal after clean shutdown");
585         mustfix_fsck_err_on(j->write_clock != clean->write_clock, c,
586                         "superblock read clock doesn't match journal after clean shutdown");
587
588         for (i = 0; i < BTREE_ID_NR; i++) {
589                 struct bkey_i *k1, *k2;
590                 unsigned l1 = 0, l2 = 0;
591
592                 k1 = btree_root_find(c, clean, NULL, i, &l1);
593                 k2 = btree_root_find(c, NULL, j, i, &l2);
594
595                 if (!k1 && !k2)
596                         continue;
597
598                 mustfix_fsck_err_on(!k1 || !k2 ||
599                                     IS_ERR(k1) ||
600                                     IS_ERR(k2) ||
601                                     k1->k.u64s != k2->k.u64s ||
602                                     memcmp(k1, k2, bkey_bytes(k1)) ||
603                                     l1 != l2, c,
604                         "superblock btree root doesn't match journal after clean shutdown");
605         }
606 fsck_err:
607         return ret;
608 }
609
610 static struct bch_sb_field_clean *read_superblock_clean(struct bch_fs *c)
611 {
612         struct bch_sb_field_clean *clean, *sb_clean;
613         int ret;
614
615         mutex_lock(&c->sb_lock);
616         sb_clean = bch2_sb_get_clean(c->disk_sb.sb);
617
618         if (fsck_err_on(!sb_clean, c,
619                         "superblock marked clean but clean section not present")) {
620                 SET_BCH_SB_CLEAN(c->disk_sb.sb, false);
621                 c->sb.clean = false;
622                 mutex_unlock(&c->sb_lock);
623                 return NULL;
624         }
625
626         clean = kmemdup(sb_clean, vstruct_bytes(&sb_clean->field),
627                         GFP_KERNEL);
628         if (!clean) {
629                 mutex_unlock(&c->sb_lock);
630                 return ERR_PTR(-ENOMEM);
631         }
632
633         if (le16_to_cpu(c->disk_sb.sb->version) <
634             bcachefs_metadata_version_bkey_renumber)
635                 bch2_sb_clean_renumber(clean, READ);
636
637         mutex_unlock(&c->sb_lock);
638
639         return clean;
640 fsck_err:
641         mutex_unlock(&c->sb_lock);
642         return ERR_PTR(ret);
643 }
644
645 static int read_btree_roots(struct bch_fs *c)
646 {
647         unsigned i;
648         int ret = 0;
649
650         for (i = 0; i < BTREE_ID_NR; i++) {
651                 struct btree_root *r = &c->btree_roots[i];
652
653                 if (!r->alive)
654                         continue;
655
656                 if (i == BTREE_ID_ALLOC &&
657                     c->opts.reconstruct_alloc) {
658                         c->sb.compat &= ~(1ULL << BCH_COMPAT_FEAT_ALLOC_INFO);
659                         continue;
660                 }
661
662
663                 if (r->error) {
664                         __fsck_err(c, i == BTREE_ID_ALLOC
665                                    ? FSCK_CAN_IGNORE : 0,
666                                    "invalid btree root %s",
667                                    bch2_btree_ids[i]);
668                         if (i == BTREE_ID_ALLOC)
669                                 c->sb.compat &= ~(1ULL << BCH_COMPAT_FEAT_ALLOC_INFO);
670                 }
671
672                 ret = bch2_btree_root_read(c, i, &r->key, r->level);
673                 if (ret) {
674                         __fsck_err(c, i == BTREE_ID_ALLOC
675                                    ? FSCK_CAN_IGNORE : 0,
676                                    "error reading btree root %s",
677                                    bch2_btree_ids[i]);
678                         if (i == BTREE_ID_ALLOC)
679                                 c->sb.compat &= ~(1ULL << BCH_COMPAT_FEAT_ALLOC_INFO);
680                 }
681         }
682
683         for (i = 0; i < BTREE_ID_NR; i++)
684                 if (!c->btree_roots[i].b)
685                         bch2_btree_root_alloc(c, i);
686 fsck_err:
687         return ret;
688 }
689
690 int bch2_fs_recovery(struct bch_fs *c)
691 {
692         const char *err = "cannot allocate memory";
693         struct bch_sb_field_clean *clean = NULL;
694         u64 journal_seq;
695         LIST_HEAD(journal_entries);
696         struct journal_keys journal_keys = { NULL };
697         bool wrote = false, write_sb = false;
698         int ret;
699
700         if (c->sb.clean)
701                 clean = read_superblock_clean(c);
702         ret = PTR_ERR_OR_ZERO(clean);
703         if (ret)
704                 goto err;
705
706         if (c->sb.clean)
707                 bch_info(c, "recovering from clean shutdown, journal seq %llu",
708                          le64_to_cpu(clean->journal_seq));
709
710         if (!c->replicas.entries) {
711                 bch_info(c, "building replicas info");
712                 set_bit(BCH_FS_REBUILD_REPLICAS, &c->flags);
713         }
714
715         if (!c->sb.clean || c->opts.fsck) {
716                 struct jset *j;
717
718                 ret = bch2_journal_read(c, &journal_entries);
719                 if (ret)
720                         goto err;
721
722                 if (mustfix_fsck_err_on(c->sb.clean && !journal_empty(&journal_entries), c,
723                                 "filesystem marked clean but journal not empty")) {
724                         c->sb.compat &= ~(1ULL << BCH_COMPAT_FEAT_ALLOC_INFO);
725                         SET_BCH_SB_CLEAN(c->disk_sb.sb, false);
726                         c->sb.clean = false;
727                 }
728
729                 if (!c->sb.clean && list_empty(&journal_entries)) {
730                         bch_err(c, "no journal entries found");
731                         ret = BCH_FSCK_REPAIR_IMPOSSIBLE;
732                         goto err;
733                 }
734
735                 journal_keys = journal_keys_sort(&journal_entries);
736                 if (!journal_keys.d) {
737                         ret = -ENOMEM;
738                         goto err;
739                 }
740
741                 j = &list_last_entry(&journal_entries,
742                                      struct journal_replay, list)->j;
743
744                 ret = verify_superblock_clean(c, &clean, j);
745                 if (ret)
746                         goto err;
747
748                 journal_seq = le64_to_cpu(j->seq) + 1;
749         } else {
750                 journal_seq = le64_to_cpu(clean->journal_seq) + 1;
751         }
752
753         ret = journal_replay_early(c, clean, &journal_entries);
754         if (ret)
755                 goto err;
756
757         if (!c->sb.clean) {
758                 ret = bch2_journal_seq_blacklist_add(c,
759                                                      journal_seq,
760                                                      journal_seq + 4);
761                 if (ret) {
762                         bch_err(c, "error creating new journal seq blacklist entry");
763                         goto err;
764                 }
765
766                 journal_seq += 4;
767         }
768
769         ret = bch2_blacklist_table_initialize(c);
770
771         if (!list_empty(&journal_entries)) {
772                 ret = verify_journal_entries_not_blacklisted_or_missing(c,
773                                                         &journal_entries);
774                 if (ret)
775                         goto err;
776         }
777
778         ret = bch2_fs_journal_start(&c->journal, journal_seq,
779                                     &journal_entries);
780         if (ret)
781                 goto err;
782
783         ret = read_btree_roots(c);
784         if (ret)
785                 goto err;
786
787         bch_verbose(c, "starting alloc read");
788         err = "error reading allocation information";
789         ret = bch2_alloc_read(c, &journal_keys);
790         if (ret)
791                 goto err;
792         bch_verbose(c, "alloc read done");
793
794         bch_verbose(c, "starting stripes_read");
795         err = "error reading stripes";
796         ret = bch2_stripes_read(c, &journal_keys);
797         if (ret)
798                 goto err;
799         bch_verbose(c, "stripes_read done");
800
801         set_bit(BCH_FS_ALLOC_READ_DONE, &c->flags);
802
803         if ((c->sb.compat & (1ULL << BCH_COMPAT_FEAT_ALLOC_INFO)) &&
804             !(c->sb.compat & (1ULL << BCH_COMPAT_FEAT_ALLOC_METADATA))) {
805                 /*
806                  * interior btree node updates aren't consistent with the
807                  * journal; after an unclean shutdown we have to walk all
808                  * pointers to metadata:
809                  */
810                 bch_info(c, "starting metadata mark and sweep");
811                 err = "error in mark and sweep";
812                 ret = bch2_gc(c, NULL, true, true);
813                 if (ret)
814                         goto err;
815                 bch_verbose(c, "mark and sweep done");
816         }
817
818         if (c->opts.fsck ||
819             !(c->sb.compat & (1ULL << BCH_COMPAT_FEAT_ALLOC_INFO)) ||
820             test_bit(BCH_FS_REBUILD_REPLICAS, &c->flags)) {
821                 bch_info(c, "starting mark and sweep");
822                 err = "error in mark and sweep";
823                 ret = bch2_gc(c, &journal_keys, true, false);
824                 if (ret)
825                         goto err;
826                 bch_verbose(c, "mark and sweep done");
827         }
828
829         clear_bit(BCH_FS_REBUILD_REPLICAS, &c->flags);
830         set_bit(BCH_FS_INITIAL_GC_DONE, &c->flags);
831
832         /*
833          * Skip past versions that might have possibly been used (as nonces),
834          * but hadn't had their pointers written:
835          */
836         if (c->sb.encryption_type && !c->sb.clean)
837                 atomic64_add(1 << 16, &c->key_version);
838
839         if (c->opts.norecovery)
840                 goto out;
841
842         bch_verbose(c, "starting journal replay");
843         err = "journal replay failed";
844         ret = bch2_journal_replay(c, journal_keys);
845         if (ret)
846                 goto err;
847         bch_verbose(c, "journal replay done");
848
849         if (!c->opts.nochanges) {
850                 /*
851                  * note that even when filesystem was clean there might be work
852                  * to do here, if we ran gc (because of fsck) which recalculated
853                  * oldest_gen:
854                  */
855                 bch_verbose(c, "writing allocation info");
856                 err = "error writing out alloc info";
857                 ret = bch2_stripes_write(c, BTREE_INSERT_LAZY_RW, &wrote) ?:
858                         bch2_alloc_write(c, BTREE_INSERT_LAZY_RW, &wrote);
859                 if (ret) {
860                         bch_err(c, "error writing alloc info");
861                         goto err;
862                 }
863                 bch_verbose(c, "alloc write done");
864
865                 set_bit(BCH_FS_ALLOC_WRITTEN, &c->flags);
866         }
867
868         if (!c->sb.clean) {
869                 if (!(c->sb.features & (1 << BCH_FEATURE_atomic_nlink))) {
870                         bch_info(c, "checking inode link counts");
871                         err = "error in recovery";
872                         ret = bch2_fsck_inode_nlink(c);
873                         if (ret)
874                                 goto err;
875                         bch_verbose(c, "check inodes done");
876
877                 } else {
878                         bch_verbose(c, "checking for deleted inodes");
879                         err = "error in recovery";
880                         ret = bch2_fsck_walk_inodes_only(c);
881                         if (ret)
882                                 goto err;
883                         bch_verbose(c, "check inodes done");
884                 }
885         }
886
887         if (c->opts.fsck) {
888                 bch_info(c, "starting fsck");
889                 err = "error in fsck";
890                 ret = bch2_fsck_full(c);
891                 if (ret)
892                         goto err;
893                 bch_verbose(c, "fsck done");
894         }
895
896         if (enabled_qtypes(c)) {
897                 bch_verbose(c, "reading quotas");
898                 ret = bch2_fs_quota_read(c);
899                 if (ret)
900                         goto err;
901                 bch_verbose(c, "quotas done");
902         }
903
904         mutex_lock(&c->sb_lock);
905         if (c->opts.version_upgrade) {
906                 if (c->sb.version < bcachefs_metadata_version_new_versioning)
907                         c->disk_sb.sb->version_min =
908                                 le16_to_cpu(bcachefs_metadata_version_min);
909                 c->disk_sb.sb->version = le16_to_cpu(bcachefs_metadata_version_current);
910                 c->disk_sb.sb->features[0] |= 1ULL << BCH_FEATURE_new_siphash;
911                 c->disk_sb.sb->features[0] |= 1ULL << BCH_FEATURE_new_extent_overwrite;
912                 write_sb = true;
913         }
914
915         if (!test_bit(BCH_FS_ERROR, &c->flags)) {
916                 c->disk_sb.sb->compat[0] |= 1ULL << BCH_COMPAT_FEAT_ALLOC_INFO;
917                 write_sb = true;
918         }
919
920         if (c->opts.fsck &&
921             !test_bit(BCH_FS_ERROR, &c->flags)) {
922                 c->disk_sb.sb->features[0] |= 1ULL << BCH_FEATURE_atomic_nlink;
923                 SET_BCH_SB_HAS_ERRORS(c->disk_sb.sb, 0);
924                 write_sb = true;
925         }
926
927         if (write_sb)
928                 bch2_write_super(c);
929         mutex_unlock(&c->sb_lock);
930
931         if (c->journal_seq_blacklist_table &&
932             c->journal_seq_blacklist_table->nr > 128)
933                 queue_work(system_long_wq, &c->journal_seq_blacklist_gc_work);
934 out:
935         ret = 0;
936 err:
937 fsck_err:
938         set_bit(BCH_FS_FSCK_DONE, &c->flags);
939         bch2_flush_fsck_errs(c);
940
941         journal_keys_free(&journal_keys);
942         journal_entries_free(&journal_entries);
943         kfree(clean);
944         if (ret)
945                 bch_err(c, "Error in recovery: %s (%i)", err, ret);
946         else
947                 bch_verbose(c, "ret %i", ret);
948         return ret;
949 }
950
951 int bch2_fs_initialize(struct bch_fs *c)
952 {
953         struct bch_inode_unpacked root_inode, lostfound_inode;
954         struct bkey_inode_buf packed_inode;
955         struct qstr lostfound = QSTR("lost+found");
956         const char *err = "cannot allocate memory";
957         struct bch_dev *ca;
958         LIST_HEAD(journal);
959         unsigned i;
960         int ret;
961
962         bch_notice(c, "initializing new filesystem");
963
964         mutex_lock(&c->sb_lock);
965         for_each_online_member(ca, c, i)
966                 bch2_mark_dev_superblock(c, ca, 0);
967         mutex_unlock(&c->sb_lock);
968
969         set_bit(BCH_FS_ALLOC_READ_DONE, &c->flags);
970         set_bit(BCH_FS_INITIAL_GC_DONE, &c->flags);
971
972         for (i = 0; i < BTREE_ID_NR; i++)
973                 bch2_btree_root_alloc(c, i);
974
975         err = "unable to allocate journal buckets";
976         for_each_online_member(ca, c, i) {
977                 ret = bch2_dev_journal_alloc(ca);
978                 if (ret) {
979                         percpu_ref_put(&ca->io_ref);
980                         goto err;
981                 }
982         }
983
984         /*
985          * journal_res_get() will crash if called before this has
986          * set up the journal.pin FIFO and journal.cur pointer:
987          */
988         bch2_fs_journal_start(&c->journal, 1, &journal);
989         bch2_journal_set_replay_done(&c->journal);
990
991         bch2_inode_init(c, &root_inode, 0, 0,
992                         S_IFDIR|S_IRWXU|S_IRUGO|S_IXUGO, 0, NULL);
993         root_inode.bi_inum = BCACHEFS_ROOT_INO;
994         bch2_inode_pack(&packed_inode, &root_inode);
995
996         err = "error creating root directory";
997         ret = bch2_btree_insert(c, BTREE_ID_INODES,
998                                 &packed_inode.inode.k_i,
999                                 NULL, NULL, BTREE_INSERT_LAZY_RW);
1000         if (ret)
1001                 goto err;
1002
1003         bch2_inode_init_early(c, &lostfound_inode);
1004
1005         err = "error creating lost+found";
1006         ret = bch2_trans_do(c, NULL, NULL, 0,
1007                 bch2_create_trans(&trans, BCACHEFS_ROOT_INO,
1008                                   &root_inode, &lostfound_inode,
1009                                   &lostfound,
1010                                   0, 0, S_IFDIR|0700, 0,
1011                                   NULL, NULL));
1012         if (ret)
1013                 goto err;
1014
1015         if (enabled_qtypes(c)) {
1016                 ret = bch2_fs_quota_read(c);
1017                 if (ret)
1018                         goto err;
1019         }
1020
1021         err = "error writing first journal entry";
1022         ret = bch2_journal_meta(&c->journal);
1023         if (ret)
1024                 goto err;
1025
1026         mutex_lock(&c->sb_lock);
1027         c->disk_sb.sb->version = c->disk_sb.sb->version_min =
1028                 le16_to_cpu(bcachefs_metadata_version_current);
1029         c->disk_sb.sb->features[0] |= 1ULL << BCH_FEATURE_atomic_nlink;
1030         c->disk_sb.sb->features[0] |= 1ULL << BCH_FEATURE_new_siphash;
1031         c->disk_sb.sb->features[0] |= 1ULL << BCH_FEATURE_new_extent_overwrite;
1032
1033         SET_BCH_SB_INITIALIZED(c->disk_sb.sb, true);
1034         SET_BCH_SB_CLEAN(c->disk_sb.sb, false);
1035
1036         bch2_write_super(c);
1037         mutex_unlock(&c->sb_lock);
1038
1039         return 0;
1040 err:
1041         pr_err("Error initializing new filesystem: %s (%i)", err, ret);
1042         return ret;
1043 }