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