Whamcloud - gitweb
e2fsck: update mmp block in one thread
[tools/e2fsprogs.git] / e2fsck / journal.c
1 /*
2  * journal.c --- code for handling the "ext3" journal
3  *
4  * Copyright (C) 2000 Andreas Dilger
5  * Copyright (C) 2000 Theodore Ts'o
6  *
7  * Parts of the code are based on fs/jfs/journal.c by Stephen C. Tweedie
8  * Copyright (C) 1999 Red Hat Software
9  *
10  * This file may be redistributed under the terms of the
11  * GNU General Public License version 2 or at your discretion
12  * any later version.
13  */
14
15 #include "config.h"
16 #ifdef HAVE_SYS_MOUNT_H
17 #include <sys/param.h>
18 #include <sys/mount.h>
19 #define MNT_FL (MS_MGC_VAL | MS_RDONLY)
20 #endif
21 #ifdef HAVE_SYS_STAT_H
22 #include <sys/stat.h>
23 #endif
24
25 #define E2FSCK_INCLUDE_INLINE_FUNCS
26 #include "jfs_user.h"
27 #include "problem.h"
28 #include "uuid/uuid.h"
29
30 #ifdef CONFIG_JBD_DEBUG         /* Enabled by configure --enable-jfs-debug */
31 static int bh_count = 0;
32 #endif
33
34 /*
35  * Define USE_INODE_IO to use the inode_io.c / fileio.c codepaths.
36  * This creates a larger static binary, and a smaller binary using
37  * shared libraries.  It's also probably slightly less CPU-efficient,
38  * which is why it's not on by default.  But, it's a good way of
39  * testing the functions in inode_io.c and fileio.c.
40  */
41 #undef USE_INODE_IO
42
43 /* Checksumming functions */
44 static int e2fsck_journal_verify_csum_type(journal_t *j,
45                                            journal_superblock_t *jsb)
46 {
47         if (!jbd2_journal_has_csum_v2or3(j))
48                 return 1;
49
50         return jsb->s_checksum_type == JBD2_CRC32C_CHKSUM;
51 }
52
53 static __u32 e2fsck_journal_sb_csum(journal_superblock_t *jsb)
54 {
55         __u32 crc, old_crc;
56
57         old_crc = jsb->s_checksum;
58         jsb->s_checksum = 0;
59         crc = ext2fs_crc32c_le(~0, (unsigned char *)jsb,
60                                sizeof(journal_superblock_t));
61         jsb->s_checksum = old_crc;
62
63         return crc;
64 }
65
66 static int e2fsck_journal_sb_csum_verify(journal_t *j,
67                                          journal_superblock_t *jsb)
68 {
69         __u32 provided, calculated;
70
71         if (!jbd2_journal_has_csum_v2or3(j))
72                 return 1;
73
74         provided = ext2fs_be32_to_cpu(jsb->s_checksum);
75         calculated = e2fsck_journal_sb_csum(jsb);
76
77         return provided == calculated;
78 }
79
80 static errcode_t e2fsck_journal_sb_csum_set(journal_t *j,
81                                             journal_superblock_t *jsb)
82 {
83         __u32 crc;
84
85         if (!jbd2_journal_has_csum_v2or3(j))
86                 return 0;
87
88         crc = e2fsck_journal_sb_csum(jsb);
89         jsb->s_checksum = ext2fs_cpu_to_be32(crc);
90         return 0;
91 }
92
93 /* Kernel compatibility functions for handling the journal.  These allow us
94  * to use the recovery.c file virtually unchanged from the kernel, so we
95  * don't have to do much to keep kernel and user recovery in sync.
96  */
97 int jbd2_journal_bmap(journal_t *journal, unsigned long block,
98                       unsigned long long *phys)
99 {
100 #ifdef USE_INODE_IO
101         *phys = block;
102         return 0;
103 #else
104         struct inode    *inode = journal->j_inode;
105         errcode_t       retval;
106         blk64_t         pblk;
107
108         if (!inode) {
109                 *phys = block;
110                 return 0;
111         }
112
113         retval= ext2fs_bmap2(inode->i_ctx->fs, inode->i_ino,
114                              &inode->i_ext2, NULL, 0, (blk64_t) block,
115                              0, &pblk);
116         *phys = pblk;
117         return -1 * ((int) retval);
118 #endif
119 }
120
121 struct buffer_head *getblk(kdev_t kdev, unsigned long long blocknr,
122                            int blocksize)
123 {
124         struct buffer_head *bh;
125         int bufsize = sizeof(*bh) + kdev->k_ctx->fs->blocksize -
126                 sizeof(bh->b_data);
127
128         bh = e2fsck_allocate_memory(kdev->k_ctx, bufsize, "block buffer");
129         if (!bh)
130                 return NULL;
131
132 #ifdef CONFIG_JBD_DEBUG
133         if (journal_enable_debug >= 3)
134                 bh_count++;
135 #endif
136         jfs_debug(4, "getblk for block %llu (%d bytes)(total %d)\n",
137                   blocknr, blocksize, bh_count);
138
139         bh->b_ctx = kdev->k_ctx;
140         if (kdev->k_dev == K_DEV_FS)
141                 bh->b_io = kdev->k_ctx->fs->io;
142         else
143                 bh->b_io = kdev->k_ctx->journal_io;
144         bh->b_size = blocksize;
145         bh->b_blocknr = blocknr;
146
147         return bh;
148 }
149
150 int sync_blockdev(kdev_t kdev)
151 {
152         io_channel      io;
153
154         if (kdev->k_dev == K_DEV_FS)
155                 io = kdev->k_ctx->fs->io;
156         else
157                 io = kdev->k_ctx->journal_io;
158
159         return io_channel_flush(io) ? -EIO : 0;
160 }
161
162 void ll_rw_block(int rw, int op_flags, int nr, struct buffer_head *bhp[])
163 {
164         errcode_t retval;
165         struct buffer_head *bh;
166
167         for (; nr > 0; --nr) {
168                 bh = *bhp++;
169                 if (rw == REQ_OP_READ && !bh->b_uptodate) {
170                         jfs_debug(3, "reading block %llu/%p\n",
171                                   bh->b_blocknr, (void *) bh);
172                         retval = io_channel_read_blk64(bh->b_io,
173                                                      bh->b_blocknr,
174                                                      1, bh->b_data);
175                         if (retval) {
176                                 com_err(bh->b_ctx->device_name, retval,
177                                         "while reading block %llu\n",
178                                         bh->b_blocknr);
179                                 bh->b_err = (int) retval;
180                                 continue;
181                         }
182                         bh->b_uptodate = 1;
183                 } else if (rw == REQ_OP_WRITE && bh->b_dirty) {
184                         jfs_debug(3, "writing block %llu/%p\n",
185                                   bh->b_blocknr,
186                                   (void *) bh);
187                         retval = io_channel_write_blk64(bh->b_io,
188                                                       bh->b_blocknr,
189                                                       1, bh->b_data);
190                         if (retval) {
191                                 com_err(bh->b_ctx->device_name, retval,
192                                         "while writing block %llu\n",
193                                         bh->b_blocknr);
194                                 bh->b_err = (int) retval;
195                                 continue;
196                         }
197                         bh->b_dirty = 0;
198                         bh->b_uptodate = 1;
199                 } else {
200                         jfs_debug(3, "no-op %s for block %llu\n",
201                                   rw == REQ_OP_READ ? "read" : "write",
202                                   bh->b_blocknr);
203                 }
204         }
205 }
206
207 void mark_buffer_dirty(struct buffer_head *bh)
208 {
209         bh->b_dirty = 1;
210 }
211
212 static void mark_buffer_clean(struct buffer_head * bh)
213 {
214         bh->b_dirty = 0;
215 }
216
217 void brelse(struct buffer_head *bh)
218 {
219         if (bh->b_dirty)
220                 ll_rw_block(REQ_OP_WRITE, 0, 1, &bh);
221         jfs_debug(3, "freeing block %llu/%p (total %d)\n",
222                   bh->b_blocknr, (void *) bh, --bh_count);
223         ext2fs_free_mem(&bh);
224 }
225
226 int buffer_uptodate(struct buffer_head *bh)
227 {
228         return bh->b_uptodate;
229 }
230
231 void mark_buffer_uptodate(struct buffer_head *bh, int val)
232 {
233         bh->b_uptodate = val;
234 }
235
236 void wait_on_buffer(struct buffer_head *bh)
237 {
238         if (!bh->b_uptodate)
239                 ll_rw_block(REQ_OP_READ, 0, 1, &bh);
240 }
241
242
243 static void e2fsck_clear_recover(e2fsck_t ctx, int error)
244 {
245         ext2fs_clear_feature_journal_needs_recovery(ctx->fs->super);
246
247         /* if we had an error doing journal recovery, we need a full fsck */
248         if (error)
249                 ctx->fs->super->s_state &= ~EXT2_VALID_FS;
250         ext2fs_mark_super_dirty(ctx->fs);
251 }
252
253 /*
254  * This is a helper function to check the validity of the journal.
255  */
256 struct process_block_struct {
257         e2_blkcnt_t     last_block;
258 };
259
260 static int process_journal_block(ext2_filsys fs,
261                                  blk64_t        *block_nr,
262                                  e2_blkcnt_t blockcnt,
263                                  blk64_t ref_block EXT2FS_ATTR((unused)),
264                                  int ref_offset EXT2FS_ATTR((unused)),
265                                  void *priv_data)
266 {
267         struct process_block_struct *p;
268         blk64_t blk = *block_nr;
269
270         p = (struct process_block_struct *) priv_data;
271
272         if (!blk || blk < fs->super->s_first_data_block ||
273             blk >= ext2fs_blocks_count(fs->super))
274                 return BLOCK_ABORT;
275
276         if (blockcnt >= 0)
277                 p->last_block = blockcnt;
278         return 0;
279 }
280
281 static int ext4_fc_replay_scan(journal_t *j, struct buffer_head *bh,
282                                 int off, tid_t expected_tid)
283 {
284         e2fsck_t ctx = j->j_fs_dev->k_ctx;
285         struct e2fsck_fc_replay_state *state;
286         int ret = JBD2_FC_REPLAY_CONTINUE;
287         struct ext4_fc_add_range *ext;
288         struct ext4_fc_tl *tl;
289         struct ext4_fc_tail *tail;
290         __u8 *start, *end;
291         struct ext4_fc_head *head;
292         struct ext2fs_extent ext2fs_ex = {0};
293
294         state = &ctx->fc_replay_state;
295
296         start = (__u8 *)bh->b_data;
297         end = (__u8 *)bh->b_data + j->j_blocksize - 1;
298
299         jbd_debug(1, "Scan phase starting, expected %d", expected_tid);
300         if (state->fc_replay_expected_off == 0) {
301                 memset(state, 0, sizeof(*state));
302                 /* Check if we can stop early */
303                 if (le16_to_cpu(((struct ext4_fc_tl *)start)->fc_tag)
304                         != EXT4_FC_TAG_HEAD) {
305                         jbd_debug(1, "Ending early!, not a head tag");
306                         return 0;
307                 }
308         }
309
310         if (off != state->fc_replay_expected_off) {
311                 ret = -EFSCORRUPTED;
312                 goto out_err;
313         }
314
315         state->fc_replay_expected_off++;
316         fc_for_each_tl(start, end, tl) {
317                 jbd_debug(3, "Scan phase, tag:%s, blk %lld\n",
318                           tag2str(le16_to_cpu(tl->fc_tag)), bh->b_blocknr);
319                 switch (le16_to_cpu(tl->fc_tag)) {
320                 case EXT4_FC_TAG_ADD_RANGE:
321                         ext = (struct ext4_fc_add_range *)ext4_fc_tag_val(tl);
322                         ret = ext2fs_decode_extent(&ext2fs_ex, (void *)&ext->fc_ex,
323                                                    sizeof(ext->fc_ex));
324                         if (ret)
325                                 ret = JBD2_FC_REPLAY_STOP;
326                         else
327                                 ret = JBD2_FC_REPLAY_CONTINUE;
328                         /* fallthrough */
329                 case EXT4_FC_TAG_DEL_RANGE:
330                 case EXT4_FC_TAG_LINK:
331                 case EXT4_FC_TAG_UNLINK:
332                 case EXT4_FC_TAG_CREAT:
333                 case EXT4_FC_TAG_INODE:
334                 case EXT4_FC_TAG_PAD:
335                         state->fc_cur_tag++;
336                         state->fc_crc = jbd2_chksum(j, state->fc_crc, tl,
337                                         sizeof(*tl) + ext4_fc_tag_len(tl));
338                         break;
339                 case EXT4_FC_TAG_TAIL:
340                         state->fc_cur_tag++;
341                         tail = (struct ext4_fc_tail *)ext4_fc_tag_val(tl);
342                         state->fc_crc = jbd2_chksum(j, state->fc_crc, tl,
343                                                 sizeof(*tl) +
344                                                 offsetof(struct ext4_fc_tail,
345                                                 fc_crc));
346                         jbd_debug(1, "tail tid %d, expected %d\n",
347                                         le32_to_cpu(tail->fc_tid),
348                                         expected_tid);
349                         if (le32_to_cpu(tail->fc_tid) == expected_tid &&
350                                 le32_to_cpu(tail->fc_crc) == state->fc_crc) {
351                                 state->fc_replay_num_tags = state->fc_cur_tag;
352                         } else {
353                                 ret = state->fc_replay_num_tags ?
354                                         JBD2_FC_REPLAY_STOP : -EFSBADCRC;
355                         }
356                         state->fc_crc = 0;
357                         break;
358                 case EXT4_FC_TAG_HEAD:
359                         head = (struct ext4_fc_head *)ext4_fc_tag_val(tl);
360                         if (le32_to_cpu(head->fc_features) &
361                                 ~EXT4_FC_SUPPORTED_FEATURES) {
362                                 ret = -EOPNOTSUPP;
363                                 break;
364                         }
365                         if (le32_to_cpu(head->fc_tid) != expected_tid) {
366                                 ret = -EINVAL;
367                                 break;
368                         }
369                         state->fc_cur_tag++;
370                         state->fc_crc = jbd2_chksum(j, state->fc_crc, tl,
371                                         sizeof(*tl) + ext4_fc_tag_len(tl));
372                         break;
373                 default:
374                         ret = state->fc_replay_num_tags ?
375                                 JBD2_FC_REPLAY_STOP : -ECANCELED;
376                 }
377                 if (ret < 0 || ret == JBD2_FC_REPLAY_STOP)
378                         break;
379         }
380
381 out_err:
382         return ret;
383 }
384
385 static int __errcode_to_errno(errcode_t err, const char *func, int line)
386 {
387         if (err == 0)
388                 return 0;
389         fprintf(stderr, "Error \"%s\" encountered in function %s at line %d\n",
390                 error_message(err), func, line);
391         if (err <= 256)
392                 return -err;
393         return -EFAULT;
394 }
395
396 #define errcode_to_errno(err)   __errcode_to_errno(err, __func__, __LINE__)
397
398 #define ex_end(__ex) ((__ex)->e_lblk + (__ex)->e_len - 1)
399 #define ex_pend(__ex) ((__ex)->e_pblk + (__ex)->e_len - 1)
400
401 static int make_room(struct extent_list *list, int i)
402 {
403         int ret;
404
405         if (list->count == list->size) {
406                 unsigned int new_size = (list->size + 341) *
407                                         sizeof(struct ext2fs_extent);
408                 ret = errcode_to_errno(ext2fs_resize_mem(0, new_size, &list->extents));
409                 if (ret)
410                         return ret;
411                 list->size += 341;
412         }
413
414         memmove(&list->extents[i + 1], &list->extents[i],
415                         sizeof(list->extents[0]) * (list->count - i));
416         list->count++;
417         return 0;
418 }
419
420 static int ex_compar(const void *arg1, const void *arg2)
421 {
422         struct ext2fs_extent *ex1 = (struct ext2fs_extent *)arg1;
423         struct ext2fs_extent *ex2 = (struct ext2fs_extent *)arg2;
424
425         if (ex1->e_lblk < ex2->e_lblk)
426                 return -1;
427         if (ex1->e_lblk > ex2->e_lblk)
428                 return 1;
429         return ex1->e_len - ex2->e_len;
430 }
431
432 static int ex_len_compar(const void *arg1, const void *arg2)
433 {
434         struct ext2fs_extent *ex1 = (struct ext2fs_extent *)arg1;
435         struct ext2fs_extent *ex2 = (struct ext2fs_extent *)arg2;
436
437         if (ex1->e_len < ex2->e_len)
438                 return 1;
439
440         if (ex1->e_lblk > ex2->e_lblk)
441                 return -1;
442
443         return 0;
444 }
445
446 static void ex_sort_and_merge(e2fsck_t ctx, struct extent_list *list)
447 {
448         blk64_t ex_end;
449         int i, j;
450
451         if (list->count < 2)
452                 return;
453
454         /*
455          * Reverse sort by length, that way we strip off all the 0 length
456          * extents
457          */
458         qsort(list->extents, list->count, sizeof(struct ext2fs_extent),
459                 ex_len_compar);
460
461         for (i = 0; i < list->count; i++) {
462                 if (list->extents[i].e_len == 0) {
463                         list->count = i;
464                         break;
465                 }
466         }
467
468         /* Now sort by logical offset */
469         qsort(list->extents, list->count, sizeof(list->extents[0]),
470                 ex_compar);
471
472         /* Merge adjacent extents if they are logically and physically contiguous */
473         i = 0;
474         while (i < list->count - 1) {
475                 if (ex_end(&list->extents[i]) + 1 != list->extents[i + 1].e_lblk ||
476                         ex_pend(&list->extents[i]) + 1 != list->extents[i + 1].e_pblk ||
477                         (list->extents[i].e_flags & EXT2_EXTENT_FLAGS_UNINIT) !=
478                                 (list->extents[i + 1].e_flags & EXT2_EXTENT_FLAGS_UNINIT)) {
479                         i++;
480                         continue;
481                 }
482
483                 list->extents[i].e_len += list->extents[i + 1].e_len;
484                 for (j = i + 1; j < list->count - 1; j++)
485                         list->extents[j] = list->extents[j + 1];
486                 list->count--;
487         }
488 }
489
490 /* must free blocks that are released */
491 static int ext4_modify_extent_list(e2fsck_t ctx, struct extent_list *list,
492                                         struct ext2fs_extent *ex, int del)
493 {
494         int ret;
495         int i, offset;
496         struct ext2fs_extent add_ex = *ex, add_ex2;
497
498         /* First let's create a hole from ex->e_lblk of length ex->e_len */
499         for (i = 0; i < list->count; i++) {
500                 if (ex_end(&list->extents[i]) < add_ex.e_lblk)
501                         continue;
502
503                 /* Case 1: No overlap */
504                 if (list->extents[i].e_lblk > ex_end(&add_ex))
505                         break;
506                 /*
507                  * Unmark all the blocks in bb now. All the blocks get marked
508                  * before we exit this function.
509                  */
510                 ext2fs_unmark_block_bitmap_range2(ctx->fs->block_map,
511                         list->extents[i].e_pblk, list->extents[i].e_len);
512                 /* Case 2: Split */
513                 if (list->extents[i].e_lblk < add_ex.e_lblk &&
514                         ex_end(&list->extents[i]) > ex_end(&add_ex)) {
515                         ret = make_room(list, i + 1);
516                         if (ret)
517                                 return ret;
518                         list->extents[i + 1] = list->extents[i];
519                         offset = ex_end(&add_ex) + 1 - list->extents[i].e_lblk;
520                         list->extents[i + 1].e_lblk += offset;
521                         list->extents[i + 1].e_pblk += offset;
522                         list->extents[i + 1].e_len -= offset;
523                         list->extents[i].e_len =
524                                 add_ex.e_lblk - list->extents[i].e_lblk;
525                         break;
526                 }
527
528                 /* Case 3: Exact overlap */
529                 if (add_ex.e_lblk <= list->extents[i].e_lblk  &&
530                         ex_end(&list->extents[i]) <= ex_end(&add_ex)) {
531
532                         list->extents[i].e_len = 0;
533                         continue;
534                 }
535
536                 /* Case 4: Partial overlap */
537                 if (ex_end(&list->extents[i]) > ex_end(&add_ex)) {
538                         offset = ex_end(&add_ex) + 1 - list->extents[i].e_lblk;
539                         list->extents[i].e_lblk += offset;
540                         list->extents[i].e_pblk += offset;
541                         list->extents[i].e_len -= offset;
542                         break;
543                 }
544
545                 if (ex_end(&add_ex) >= ex_end(&list->extents[i]))
546                         list->extents[i].e_len =
547                                 add_ex.e_lblk > list->extents[i].e_lblk ?
548                                 add_ex.e_lblk - list->extents[i].e_lblk : 0;
549         }
550
551         if (add_ex.e_len && !del) {
552                 make_room(list, list->count);
553                 list->extents[list->count - 1] = add_ex;
554         }
555
556         ex_sort_and_merge(ctx, list);
557
558         /* Mark all occupied blocks allocated */
559         for (i = 0; i < list->count; i++)
560                 ext2fs_mark_block_bitmap_range2(ctx->fs->block_map,
561                         list->extents[i].e_pblk, list->extents[i].e_len);
562         ext2fs_mark_bb_dirty(ctx->fs);
563
564         return 0;
565 }
566
567 static int ext4_add_extent_to_list(e2fsck_t ctx, struct extent_list *list,
568                                         struct ext2fs_extent *ex)
569 {
570         return ext4_modify_extent_list(ctx, list, ex, 0 /* add */);
571 }
572
573 static int ext4_del_extent_from_list(e2fsck_t ctx, struct extent_list *list,
574                                         struct ext2fs_extent *ex)
575 {
576         return ext4_modify_extent_list(ctx, list, ex, 1 /* delete */);
577 }
578
579 static int ext4_fc_read_extents(e2fsck_t ctx, int ino)
580 {
581         struct extent_list *extent_list = &ctx->fc_replay_state.fc_extent_list;
582
583         if (extent_list->ino == ino)
584                 return 0;
585
586         extent_list->ino = ino;
587         return errcode_to_errno(e2fsck_read_extents(ctx, extent_list));
588 }
589
590 /*
591  * Flush extents in replay state on disk. @ino is the inode that is going
592  * to be processed next. So, we hold back flushing of the extent list
593  * if the next inode that's going to be processed is same as the one with
594  * cached extents in our replay state. That allows us to gather multiple extents
595  * for the inode so that we can flush all of them at once and it also saves us
596  * from continuously growing and shrinking the extent tree.
597  */
598 static void ext4_fc_flush_extents(e2fsck_t ctx, int ino)
599 {
600         struct extent_list *extent_list = &ctx->fc_replay_state.fc_extent_list;
601
602         if (extent_list->ino == ino || extent_list->ino == 0)
603                 return;
604         e2fsck_rewrite_extent_tree(ctx, extent_list);
605         ext2fs_free_mem(&extent_list->extents);
606         memset(extent_list, 0, sizeof(*extent_list));
607 }
608
609 /* Helper struct for dentry replay routines */
610 struct dentry_info_args {
611         int parent_ino, dname_len, ino, inode_len;
612         char *dname;
613 };
614
615 static inline void tl_to_darg(struct dentry_info_args *darg,
616                                 struct  ext4_fc_tl *tl)
617 {
618         struct ext4_fc_dentry_info *fcd;
619         int tag = le16_to_cpu(tl->fc_tag);
620
621         fcd = (struct ext4_fc_dentry_info *)ext4_fc_tag_val(tl);
622
623         darg->parent_ino = le32_to_cpu(fcd->fc_parent_ino);
624         darg->ino = le32_to_cpu(fcd->fc_ino);
625         darg->dname = (char *) fcd->fc_dname;
626         darg->dname_len = ext4_fc_tag_len(tl) -
627                         sizeof(struct ext4_fc_dentry_info);
628         darg->dname = malloc(darg->dname_len + 1);
629         memcpy(darg->dname, fcd->fc_dname, darg->dname_len);
630         darg->dname[darg->dname_len] = 0;
631         jbd_debug(1, "%s: %s, ino %d, parent %d\n",
632                 tag == EXT4_FC_TAG_CREAT ? "create" :
633                 (tag == EXT4_FC_TAG_LINK ? "link" :
634                 (tag == EXT4_FC_TAG_UNLINK ? "unlink" : "error")),
635                 darg->dname, darg->ino, darg->parent_ino);
636 }
637
638 static int ext4_fc_handle_unlink(e2fsck_t ctx, struct ext4_fc_tl *tl)
639 {
640         struct ext2_inode inode;
641         struct dentry_info_args darg;
642         ext2_filsys fs = ctx->fs;
643         int ret;
644
645         tl_to_darg(&darg, tl);
646         ext4_fc_flush_extents(ctx, darg.ino);
647         ret = errcode_to_errno(
648                        ext2fs_unlink(ctx->fs, darg.parent_ino,
649                                      darg.dname, darg.ino, 0));
650         /* It's okay if the above call fails */
651         free(darg.dname);
652         return ret;
653 }
654
655 static int ext4_fc_handle_link_and_create(e2fsck_t ctx, struct ext4_fc_tl *tl)
656 {
657         struct dentry_info_args darg;
658         ext2_filsys fs = ctx->fs;
659         struct ext2_inode_large inode_large;
660         int ret, filetype, mode;
661
662         tl_to_darg(&darg, tl);
663         ext4_fc_flush_extents(ctx, 0);
664         ret = errcode_to_errno(ext2fs_read_inode(fs, darg.ino,
665                                                  (struct ext2_inode *)&inode_large));
666         if (ret)
667                 goto out;
668
669         mode = inode_large.i_mode;
670
671         if (LINUX_S_ISREG(mode))
672                 filetype = EXT2_FT_REG_FILE;
673         else if (LINUX_S_ISDIR(mode))
674                 filetype = EXT2_FT_DIR;
675         else if (LINUX_S_ISCHR(mode))
676                 filetype = EXT2_FT_CHRDEV;
677         else if (LINUX_S_ISBLK(mode))
678                 filetype = EXT2_FT_BLKDEV;
679         else if (LINUX_S_ISLNK(mode))
680                 return EXT2_FT_SYMLINK;
681         else if (LINUX_S_ISFIFO(mode))
682                 filetype = EXT2_FT_FIFO;
683         else if (LINUX_S_ISSOCK(mode))
684                 filetype = EXT2_FT_SOCK;
685         else {
686                 ret = -EINVAL;
687                 goto out;
688         }
689
690         /*
691          * Forcefully unlink if the same name is present and ignore the error
692          * if any, since this dirent might not exist
693          */
694         ext2fs_unlink(fs, darg.parent_ino, darg.dname, darg.ino,
695                         EXT2FS_UNLINK_FORCE);
696
697         ret = errcode_to_errno(
698                        ext2fs_link(fs, darg.parent_ino, darg.dname, darg.ino,
699                                    filetype));
700 out:
701         free(darg.dname);
702         return ret;
703
704 }
705
706 /* This function fixes the i_blocks field in the replayed indoe */
707 static void ext4_fc_replay_fixup_iblocks(struct ext2_inode_large *ondisk_inode,
708         struct ext2_inode_large *fc_inode)
709 {
710         if (ondisk_inode->i_flags & EXT4_EXTENTS_FL) {
711                 struct ext3_extent_header *eh;
712
713                 eh = (struct ext3_extent_header *)(&ondisk_inode->i_block[0]);
714                 if (le16_to_cpu(eh->eh_magic) != EXT3_EXT_MAGIC) {
715                         memset(eh, 0, sizeof(*eh));
716                         eh->eh_magic = cpu_to_le16(EXT3_EXT_MAGIC);
717                         eh->eh_max = cpu_to_le16(
718                                 (sizeof(ondisk_inode->i_block) -
719                                         sizeof(struct ext3_extent_header)) /
720                                 sizeof(struct ext3_extent));
721                 }
722         } else if (ondisk_inode->i_flags & EXT4_INLINE_DATA_FL) {
723                 memcpy(ondisk_inode->i_block, fc_inode->i_block,
724                         sizeof(fc_inode->i_block));
725         }
726 }
727
728 static int ext4_fc_handle_inode(e2fsck_t ctx, struct ext4_fc_tl *tl)
729 {
730         struct e2fsck_fc_replay_state *state = &ctx->fc_replay_state;
731         int ino, inode_len = EXT2_GOOD_OLD_INODE_SIZE;
732         struct ext2_inode_large *inode = NULL, *fc_inode = NULL;
733         struct ext4_fc_inode *fc_inode_val;
734         errcode_t err;
735         blk64_t blks;
736
737         fc_inode_val = (struct ext4_fc_inode *)ext4_fc_tag_val(tl);
738         ino = le32_to_cpu(fc_inode_val->fc_ino);
739
740         if (EXT2_INODE_SIZE(ctx->fs->super) > EXT2_GOOD_OLD_INODE_SIZE)
741                 inode_len += ext2fs_le16_to_cpu(
742                         ((struct ext2_inode_large *)fc_inode_val->fc_raw_inode)
743                                 ->i_extra_isize);
744         err = ext2fs_get_mem(inode_len, &inode);
745         if (err)
746                 goto out;
747         err = ext2fs_get_mem(inode_len, &fc_inode);
748         if (err)
749                 goto out;
750         ext4_fc_flush_extents(ctx, ino);
751
752         err = ext2fs_read_inode_full(ctx->fs, ino, (struct ext2_inode *)inode,
753                                         inode_len);
754         if (err)
755                 goto out;
756 #ifdef WORDS_BIGENDIAN
757         ext2fs_swap_inode_full(ctx->fs, fc_inode,
758                                (struct ext2_inode_large *)fc_inode_val->fc_raw_inode,
759                                0, sizeof(*inode));
760 #else
761         memcpy(fc_inode, fc_inode_val->fc_raw_inode, inode_len);
762 #endif
763         memcpy(inode, fc_inode, offsetof(struct ext2_inode_large, i_block));
764         memcpy(&inode->i_generation, &fc_inode->i_generation,
765                 inode_len - offsetof(struct ext2_inode_large, i_generation));
766         ext4_fc_replay_fixup_iblocks(inode, fc_inode);
767         err = ext2fs_count_blocks(ctx->fs, ino, EXT2_INODE(inode), &blks);
768         if (err)
769                 goto out;
770         ext2fs_iblk_set(ctx->fs, EXT2_INODE(inode), blks);
771         ext2fs_inode_csum_set(ctx->fs, ino, inode);
772
773         err = ext2fs_write_inode_full(ctx->fs, ino, (struct ext2_inode *)inode,
774                                         inode_len);
775         if (err)
776                 goto out;
777         if (inode->i_links_count)
778                 ext2fs_mark_inode_bitmap2(ctx->fs->inode_map, ino);
779         else
780                 ext2fs_unmark_inode_bitmap2(ctx->fs->inode_map, ino);
781         ext2fs_mark_ib_dirty(ctx->fs);
782
783 out:
784         ext2fs_free_mem(&inode);
785         ext2fs_free_mem(&fc_inode);
786         return errcode_to_errno(err);
787 }
788
789 /*
790  * Handle add extent replay tag.
791  */
792 static int ext4_fc_handle_add_extent(e2fsck_t ctx, struct ext4_fc_tl *tl)
793 {
794         struct ext2fs_extent extent;
795         struct ext4_fc_add_range *add_range;
796         struct ext4_fc_del_range *del_range;
797         int ret = 0, ino;
798
799         add_range = (struct ext4_fc_add_range *)ext4_fc_tag_val(tl);
800         ino = le32_to_cpu(add_range->fc_ino);
801         ext4_fc_flush_extents(ctx, ino);
802
803         ret = ext4_fc_read_extents(ctx, ino);
804         if (ret)
805                 return ret;
806         memset(&extent, 0, sizeof(extent));
807         ret = errcode_to_errno(ext2fs_decode_extent(
808                         &extent, (void *)(add_range->fc_ex),
809                         sizeof(add_range->fc_ex)));
810         if (ret)
811                 return ret;
812         return ext4_add_extent_to_list(ctx,
813                 &ctx->fc_replay_state.fc_extent_list, &extent);
814 }
815
816 /*
817  * Handle delete logical range replay tag.
818  */
819 static int ext4_fc_handle_del_range(e2fsck_t ctx, struct ext4_fc_tl *tl)
820 {
821         struct ext2fs_extent extent;
822         struct ext4_fc_del_range *del_range;
823         int ret, ino;
824
825         del_range = (struct ext4_fc_del_range *)ext4_fc_tag_val(tl);
826         ino = le32_to_cpu(del_range->fc_ino);
827         ext4_fc_flush_extents(ctx, ino);
828
829         memset(&extent, 0, sizeof(extent));
830         extent.e_lblk = ext2fs_le32_to_cpu(del_range->fc_lblk);
831         extent.e_len = ext2fs_le32_to_cpu(del_range->fc_len);
832         ret = ext4_fc_read_extents(ctx, ino);
833         if (ret)
834                 return ret;
835         return ext4_del_extent_from_list(ctx,
836                 &ctx->fc_replay_state.fc_extent_list, &extent);
837 }
838
839 /*
840  * Main recovery path entry point. This function returns JBD2_FC_REPLAY_CONTINUE
841  * to indicate that it is expecting more fast commit blocks. It returns
842  * JBD2_FC_REPLAY_STOP to indicate that replay is done.
843  */
844 static int ext4_fc_replay(journal_t *journal, struct buffer_head *bh,
845                                 enum passtype pass, int off, tid_t expected_tid)
846 {
847         e2fsck_t ctx = journal->j_fs_dev->k_ctx;
848         struct e2fsck_fc_replay_state *state = &ctx->fc_replay_state;
849         int ret = JBD2_FC_REPLAY_CONTINUE;
850         struct ext4_fc_tl *tl;
851         __u8 *start, *end;
852
853         if (pass == PASS_SCAN) {
854                 state->fc_current_pass = PASS_SCAN;
855                 return ext4_fc_replay_scan(journal, bh, off, expected_tid);
856         }
857
858         if (state->fc_replay_num_tags == 0)
859                 goto replay_done;
860
861         if (state->fc_current_pass != pass) {
862                 /* Starting replay phase */
863                 state->fc_current_pass = pass;
864                 /* We will reset checksums */
865                 ctx->fs->flags |= EXT2_FLAG_IGNORE_CSUM_ERRORS;
866                 ret = errcode_to_errno(ext2fs_read_bitmaps(ctx->fs));
867                 if (ret) {
868                         jbd_debug(1, "Error %d while reading bitmaps\n", ret);
869                         return ret;
870                 }
871                 state->fc_super_state = ctx->fs->super->s_state;
872                 /*
873                  * Mark the file system to indicate it contains errors. That's
874                  * because the updates performed by fast commit replay code are
875                  * not atomic and may result in incosistent file system if it
876                  * crashes before the replay is complete.
877                  */
878                 ctx->fs->super->s_state |= EXT2_ERROR_FS;
879                 ctx->fs->super->s_state |= EXT4_FC_REPLAY;
880                 ext2fs_mark_super_dirty(ctx->fs);
881                 ext2fs_flush(ctx->fs);
882         }
883
884         start = (__u8 *)bh->b_data;
885         end = (__u8 *)bh->b_data + journal->j_blocksize - 1;
886
887         fc_for_each_tl(start, end, tl) {
888                 if (state->fc_replay_num_tags == 0)
889                         goto replay_done;
890                 jbd_debug(3, "Replay phase processing %s tag\n",
891                                 tag2str(le16_to_cpu(tl->fc_tag)));
892                 state->fc_replay_num_tags--;
893                 switch (le16_to_cpu(tl->fc_tag)) {
894                 case EXT4_FC_TAG_CREAT:
895                 case EXT4_FC_TAG_LINK:
896                         ret = ext4_fc_handle_link_and_create(ctx, tl);
897                         break;
898                 case EXT4_FC_TAG_UNLINK:
899                         ret = ext4_fc_handle_unlink(ctx, tl);
900                         break;
901                 case EXT4_FC_TAG_ADD_RANGE:
902                         ret = ext4_fc_handle_add_extent(ctx, tl);
903                         break;
904                 case EXT4_FC_TAG_DEL_RANGE:
905                         ret = ext4_fc_handle_del_range(ctx, tl);
906                         break;
907                 case EXT4_FC_TAG_INODE:
908                         ret = ext4_fc_handle_inode(ctx, tl);
909                         break;
910                 case EXT4_FC_TAG_TAIL:
911                         ext4_fc_flush_extents(ctx, 0);
912                 case EXT4_FC_TAG_PAD:
913                 case EXT4_FC_TAG_HEAD:
914                         break;
915                 default:
916                         ret = -ECANCELED;
917                         break;
918                 }
919                 if (ret < 0)
920                         break;
921                 ret = JBD2_FC_REPLAY_CONTINUE;
922         }
923         return ret;
924 replay_done:
925         jbd_debug(1, "End of fast commit replay\n");
926         if (state->fc_current_pass != pass)
927                 return JBD2_FC_REPLAY_STOP;
928
929         ext2fs_calculate_summary_stats(ctx->fs, 0 /* update bg also */);
930         ext2fs_write_block_bitmap(ctx->fs);
931         ext2fs_write_inode_bitmap(ctx->fs);
932         ext2fs_mark_super_dirty(ctx->fs);
933         ext2fs_set_gdt_csum(ctx->fs);
934         ctx->fs->super->s_state = state->fc_super_state;
935         ext2fs_flush(ctx->fs);
936
937         return JBD2_FC_REPLAY_STOP;
938 }
939
940 static errcode_t e2fsck_get_journal(e2fsck_t ctx, journal_t **ret_journal)
941 {
942         struct process_block_struct pb;
943         struct ext2_super_block *sb = ctx->fs->super;
944         struct ext2_super_block jsuper;
945         struct problem_context  pctx;
946         struct buffer_head      *bh;
947         struct inode            *j_inode = NULL;
948         struct kdev_s           *dev_fs = NULL, *dev_journal;
949         const char              *journal_name = 0;
950         journal_t               *journal = NULL;
951         errcode_t               retval = 0;
952         io_manager              io_ptr = 0;
953         unsigned long long      start = 0;
954         int                     ret;
955         int                     ext_journal = 0;
956         int                     tried_backup_jnl = 0;
957
958         clear_problem_context(&pctx);
959
960         journal = e2fsck_allocate_memory(ctx, sizeof(journal_t), "journal");
961         if (!journal) {
962                 return EXT2_ET_NO_MEMORY;
963         }
964
965         dev_fs = e2fsck_allocate_memory(ctx, 2*sizeof(struct kdev_s), "kdev");
966         if (!dev_fs) {
967                 retval = EXT2_ET_NO_MEMORY;
968                 goto errout;
969         }
970         dev_journal = dev_fs+1;
971
972         dev_fs->k_ctx = dev_journal->k_ctx = ctx;
973         dev_fs->k_dev = K_DEV_FS;
974         dev_journal->k_dev = K_DEV_JOURNAL;
975
976         journal->j_dev = dev_journal;
977         journal->j_fs_dev = dev_fs;
978         journal->j_inode = NULL;
979         journal->j_blocksize = ctx->fs->blocksize;
980
981         if (uuid_is_null(sb->s_journal_uuid)) {
982                 if (!sb->s_journal_inum) {
983                         retval = EXT2_ET_BAD_INODE_NUM;
984                         goto errout;
985                 }
986                 j_inode = e2fsck_allocate_memory(ctx, sizeof(*j_inode),
987                                                  "journal inode");
988                 if (!j_inode) {
989                         retval = EXT2_ET_NO_MEMORY;
990                         goto errout;
991                 }
992
993                 j_inode->i_ctx = ctx;
994                 j_inode->i_ino = sb->s_journal_inum;
995
996                 if ((retval = ext2fs_read_inode(ctx->fs,
997                                                 sb->s_journal_inum,
998                                                 &j_inode->i_ext2))) {
999                 try_backup_journal:
1000                         if (sb->s_jnl_backup_type != EXT3_JNL_BACKUP_BLOCKS ||
1001                             tried_backup_jnl)
1002                                 goto errout;
1003                         memset(&j_inode->i_ext2, 0, sizeof(struct ext2_inode));
1004                         memcpy(&j_inode->i_ext2.i_block[0], sb->s_jnl_blocks,
1005                                EXT2_N_BLOCKS*4);
1006                         j_inode->i_ext2.i_size_high = sb->s_jnl_blocks[15];
1007                         j_inode->i_ext2.i_size = sb->s_jnl_blocks[16];
1008                         j_inode->i_ext2.i_links_count = 1;
1009                         j_inode->i_ext2.i_mode = LINUX_S_IFREG | 0600;
1010                         e2fsck_use_inode_shortcuts(ctx, 1);
1011                         ctx->stashed_ino = j_inode->i_ino;
1012                         ctx->stashed_inode = &j_inode->i_ext2;
1013                         tried_backup_jnl++;
1014                 }
1015                 if (!j_inode->i_ext2.i_links_count ||
1016                     !LINUX_S_ISREG(j_inode->i_ext2.i_mode)) {
1017                         retval = EXT2_ET_NO_JOURNAL;
1018                         goto try_backup_journal;
1019                 }
1020                 if (EXT2_I_SIZE(&j_inode->i_ext2) / journal->j_blocksize <
1021                     JBD2_MIN_JOURNAL_BLOCKS) {
1022                         retval = EXT2_ET_JOURNAL_TOO_SMALL;
1023                         goto try_backup_journal;
1024                 }
1025                 pb.last_block = -1;
1026                 retval = ext2fs_block_iterate3(ctx->fs, j_inode->i_ino,
1027                                                BLOCK_FLAG_HOLE, 0,
1028                                                process_journal_block, &pb);
1029                 if ((pb.last_block + 1) * ctx->fs->blocksize <
1030                     (int) EXT2_I_SIZE(&j_inode->i_ext2)) {
1031                         retval = EXT2_ET_JOURNAL_TOO_SMALL;
1032                         goto try_backup_journal;
1033                 }
1034                 if (tried_backup_jnl && !(ctx->options & E2F_OPT_READONLY)) {
1035                         retval = ext2fs_write_inode(ctx->fs, sb->s_journal_inum,
1036                                                     &j_inode->i_ext2);
1037                         if (retval)
1038                                 goto errout;
1039                 }
1040
1041                 journal->j_total_len = EXT2_I_SIZE(&j_inode->i_ext2) /
1042                         journal->j_blocksize;
1043
1044 #ifdef USE_INODE_IO
1045                 retval = ext2fs_inode_io_intern2(ctx->fs, sb->s_journal_inum,
1046                                                  &j_inode->i_ext2,
1047                                                  &journal_name);
1048                 if (retval)
1049                         goto errout;
1050
1051                 io_ptr = inode_io_manager;
1052 #else
1053                 journal->j_inode = j_inode;
1054                 ctx->journal_io = ctx->fs->io;
1055                 if ((ret = jbd2_journal_bmap(journal, 0, &start)) != 0) {
1056                         retval = (errcode_t) (-1 * ret);
1057                         goto errout;
1058                 }
1059 #endif
1060         } else {
1061                 ext_journal = 1;
1062                 if (!ctx->journal_name) {
1063                         char uuid[37];
1064
1065                         uuid_unparse(sb->s_journal_uuid, uuid);
1066                         ctx->journal_name = blkid_get_devname(ctx->blkid,
1067                                                               "UUID", uuid);
1068                         if (!ctx->journal_name)
1069                                 ctx->journal_name = blkid_devno_to_devname(sb->s_journal_dev);
1070                 }
1071                 journal_name = ctx->journal_name;
1072
1073                 if (!journal_name) {
1074                         fix_problem(ctx, PR_0_CANT_FIND_JOURNAL, &pctx);
1075                         retval = EXT2_ET_LOAD_EXT_JOURNAL;
1076                         goto errout;
1077                 }
1078
1079                 jfs_debug(1, "Using journal file %s\n", journal_name);
1080                 io_ptr = unix_io_manager;
1081         }
1082
1083 #if 0
1084         test_io_backing_manager = io_ptr;
1085         io_ptr = test_io_manager;
1086 #endif
1087 #ifndef USE_INODE_IO
1088         if (ext_journal)
1089 #endif
1090         {
1091                 int flags = IO_FLAG_RW;
1092                 if (!(ctx->mount_flags & EXT2_MF_ISROOT &&
1093                       ctx->mount_flags & EXT2_MF_READONLY))
1094                         flags |= IO_FLAG_EXCLUSIVE;
1095                 if ((ctx->mount_flags & EXT2_MF_READONLY) &&
1096                     (ctx->options & E2F_OPT_FORCE))
1097                         flags &= ~IO_FLAG_EXCLUSIVE;
1098
1099
1100                 retval = io_ptr->open(journal_name, flags,
1101                                       &ctx->journal_io);
1102         }
1103         if (retval)
1104                 goto errout;
1105
1106         io_channel_set_blksize(ctx->journal_io, ctx->fs->blocksize);
1107
1108         if (ext_journal) {
1109                 blk64_t maxlen;
1110
1111                 start = ext2fs_journal_sb_start(ctx->fs->blocksize) - 1;
1112                 bh = getblk(dev_journal, start, ctx->fs->blocksize);
1113                 if (!bh) {
1114                         retval = EXT2_ET_NO_MEMORY;
1115                         goto errout;
1116                 }
1117                 ll_rw_block(REQ_OP_READ, 0, 1, &bh);
1118                 if ((retval = bh->b_err) != 0) {
1119                         brelse(bh);
1120                         goto errout;
1121                 }
1122                 memcpy(&jsuper, start ? bh->b_data :  bh->b_data + SUPERBLOCK_OFFSET,
1123                        sizeof(jsuper));
1124 #ifdef WORDS_BIGENDIAN
1125                 if (jsuper.s_magic == ext2fs_swab16(EXT2_SUPER_MAGIC))
1126                         ext2fs_swap_super(&jsuper);
1127 #endif
1128                 if (jsuper.s_magic != EXT2_SUPER_MAGIC ||
1129                     !ext2fs_has_feature_journal_dev(&jsuper)) {
1130                         fix_problem(ctx, PR_0_EXT_JOURNAL_BAD_SUPER, &pctx);
1131                         retval = EXT2_ET_LOAD_EXT_JOURNAL;
1132                         brelse(bh);
1133                         goto errout;
1134                 }
1135                 /* Make sure the journal UUID is correct */
1136                 if (memcmp(jsuper.s_uuid, ctx->fs->super->s_journal_uuid,
1137                            sizeof(jsuper.s_uuid))) {
1138                         fix_problem(ctx, PR_0_JOURNAL_BAD_UUID, &pctx);
1139                         retval = EXT2_ET_LOAD_EXT_JOURNAL;
1140                         brelse(bh);
1141                         goto errout;
1142                 }
1143
1144                 /* Check the superblock checksum */
1145                 if (ext2fs_has_feature_metadata_csum(&jsuper)) {
1146                         struct struct_ext2_filsys fsx;
1147                         struct ext2_super_block superx;
1148                         void *p;
1149
1150                         p = start ? bh->b_data : bh->b_data + SUPERBLOCK_OFFSET;
1151                         memcpy(&fsx, ctx->fs, sizeof(fsx));
1152                         memcpy(&superx, ctx->fs->super, sizeof(superx));
1153                         fsx.super = &superx;
1154                         ext2fs_set_feature_metadata_csum(fsx.super);
1155                         if (!ext2fs_superblock_csum_verify(&fsx, p) &&
1156                             fix_problem(ctx, PR_0_EXT_JOURNAL_SUPER_CSUM_INVALID,
1157                                         &pctx)) {
1158                                 ext2fs_superblock_csum_set(&fsx, p);
1159                                 mark_buffer_dirty(bh);
1160                         }
1161                 }
1162                 brelse(bh);
1163
1164                 maxlen = ext2fs_blocks_count(&jsuper);
1165                 journal->j_total_len = (maxlen < 1ULL << 32) ? maxlen : (1ULL << 32) - 1;
1166                 start++;
1167         }
1168
1169         if (!(bh = getblk(dev_journal, start, journal->j_blocksize))) {
1170                 retval = EXT2_ET_NO_MEMORY;
1171                 goto errout;
1172         }
1173
1174         journal->j_sb_buffer = bh;
1175         journal->j_superblock = (journal_superblock_t *)bh->b_data;
1176         if (ext2fs_has_feature_fast_commit(ctx->fs->super))
1177                 journal->j_fc_replay_callback = ext4_fc_replay;
1178         else
1179                 journal->j_fc_replay_callback = NULL;
1180
1181 #ifdef USE_INODE_IO
1182         if (j_inode)
1183                 ext2fs_free_mem(&j_inode);
1184 #endif
1185
1186         *ret_journal = journal;
1187         e2fsck_use_inode_shortcuts(ctx, 0);
1188         return 0;
1189
1190 errout:
1191         e2fsck_use_inode_shortcuts(ctx, 0);
1192         if (dev_fs)
1193                 ext2fs_free_mem(&dev_fs);
1194         if (j_inode)
1195                 ext2fs_free_mem(&j_inode);
1196         if (journal)
1197                 ext2fs_free_mem(&journal);
1198         return retval;
1199 }
1200
1201 static errcode_t e2fsck_journal_fix_bad_inode(e2fsck_t ctx,
1202                                               struct problem_context *pctx)
1203 {
1204         struct ext2_super_block *sb = ctx->fs->super;
1205         int recover = ext2fs_has_feature_journal_needs_recovery(ctx->fs->super);
1206         int has_journal = ext2fs_has_feature_journal(ctx->fs->super);
1207
1208         if (has_journal || sb->s_journal_inum) {
1209                 /* The journal inode is bogus, remove and force full fsck */
1210                 pctx->ino = sb->s_journal_inum;
1211                 if (fix_problem(ctx, PR_0_JOURNAL_BAD_INODE, pctx)) {
1212                         if (has_journal && sb->s_journal_inum)
1213                                 printf("*** journal has been deleted ***\n\n");
1214                         ext2fs_clear_feature_journal(sb);
1215                         sb->s_journal_inum = 0;
1216                         memset(sb->s_jnl_blocks, 0, sizeof(sb->s_jnl_blocks));
1217                         ctx->flags |= E2F_FLAG_JOURNAL_INODE;
1218                         ctx->fs->flags &= ~EXT2_FLAG_MASTER_SB_ONLY;
1219                         e2fsck_clear_recover(ctx, 1);
1220                         return 0;
1221                 }
1222                 return EXT2_ET_CORRUPT_JOURNAL_SB;
1223         } else if (recover) {
1224                 if (fix_problem(ctx, PR_0_JOURNAL_RECOVER_SET, pctx)) {
1225                         e2fsck_clear_recover(ctx, 1);
1226                         return 0;
1227                 }
1228                 return EXT2_ET_UNSUPP_FEATURE;
1229         }
1230         return 0;
1231 }
1232
1233 #define V1_SB_SIZE      0x0024
1234 static void clear_v2_journal_fields(journal_t *journal)
1235 {
1236         e2fsck_t ctx = journal->j_dev->k_ctx;
1237         struct problem_context pctx;
1238
1239         clear_problem_context(&pctx);
1240
1241         if (!fix_problem(ctx, PR_0_CLEAR_V2_JOURNAL, &pctx))
1242                 return;
1243
1244         ctx->flags |= E2F_FLAG_PROBLEMS_FIXED;
1245         memset(((char *) journal->j_superblock) + V1_SB_SIZE, 0,
1246                ctx->fs->blocksize-V1_SB_SIZE);
1247         mark_buffer_dirty(journal->j_sb_buffer);
1248 }
1249
1250
1251 static errcode_t e2fsck_journal_load(journal_t *journal)
1252 {
1253         e2fsck_t ctx = journal->j_dev->k_ctx;
1254         journal_superblock_t *jsb;
1255         struct buffer_head *jbh = journal->j_sb_buffer;
1256         struct problem_context pctx;
1257
1258         clear_problem_context(&pctx);
1259
1260         ll_rw_block(REQ_OP_READ, 0, 1, &jbh);
1261         if (jbh->b_err) {
1262                 com_err(ctx->device_name, jbh->b_err, "%s",
1263                         _("reading journal superblock\n"));
1264                 return jbh->b_err;
1265         }
1266
1267         jsb = journal->j_superblock;
1268         /* If we don't even have JBD2_MAGIC, we probably have a wrong inode */
1269         if (jsb->s_header.h_magic != htonl(JBD2_MAGIC_NUMBER))
1270                 return e2fsck_journal_fix_bad_inode(ctx, &pctx);
1271
1272         switch (ntohl(jsb->s_header.h_blocktype)) {
1273         case JBD2_SUPERBLOCK_V1:
1274                 journal->j_format_version = 1;
1275                 if (jsb->s_feature_compat ||
1276                     jsb->s_feature_incompat ||
1277                     jsb->s_feature_ro_compat ||
1278                     jsb->s_nr_users)
1279                         clear_v2_journal_fields(journal);
1280                 break;
1281
1282         case JBD2_SUPERBLOCK_V2:
1283                 journal->j_format_version = 2;
1284                 if (ntohl(jsb->s_nr_users) > 1 &&
1285                     uuid_is_null(ctx->fs->super->s_journal_uuid))
1286                         clear_v2_journal_fields(journal);
1287                 if (ntohl(jsb->s_nr_users) > 1) {
1288                         fix_problem(ctx, PR_0_JOURNAL_UNSUPP_MULTIFS, &pctx);
1289                         return EXT2_ET_JOURNAL_UNSUPP_VERSION;
1290                 }
1291                 break;
1292
1293         /*
1294          * These should never appear in a journal super block, so if
1295          * they do, the journal is badly corrupted.
1296          */
1297         case JBD2_DESCRIPTOR_BLOCK:
1298         case JBD2_COMMIT_BLOCK:
1299         case JBD2_REVOKE_BLOCK:
1300                 return EXT2_ET_CORRUPT_JOURNAL_SB;
1301
1302         /* If we don't understand the superblock major type, but there
1303          * is a magic number, then it is likely to be a new format we
1304          * just don't understand, so leave it alone. */
1305         default:
1306                 return EXT2_ET_JOURNAL_UNSUPP_VERSION;
1307         }
1308
1309         if (JBD2_HAS_INCOMPAT_FEATURE(journal, ~JBD2_KNOWN_INCOMPAT_FEATURES))
1310                 return EXT2_ET_UNSUPP_FEATURE;
1311
1312         if (JBD2_HAS_RO_COMPAT_FEATURE(journal, ~JBD2_KNOWN_ROCOMPAT_FEATURES))
1313                 return EXT2_ET_RO_UNSUPP_FEATURE;
1314
1315         /* Checksum v1-3 are mutually exclusive features. */
1316         if (jbd2_has_feature_csum2(journal) && jbd2_has_feature_csum3(journal))
1317                 return EXT2_ET_CORRUPT_JOURNAL_SB;
1318
1319         if (jbd2_journal_has_csum_v2or3(journal) &&
1320             jbd2_has_feature_checksum(journal))
1321                 return EXT2_ET_CORRUPT_JOURNAL_SB;
1322
1323         if (!e2fsck_journal_verify_csum_type(journal, jsb) ||
1324             !e2fsck_journal_sb_csum_verify(journal, jsb))
1325                 return EXT2_ET_CORRUPT_JOURNAL_SB;
1326
1327         if (jbd2_journal_has_csum_v2or3(journal))
1328                 journal->j_csum_seed = jbd2_chksum(journal, ~0, jsb->s_uuid,
1329                                                    sizeof(jsb->s_uuid));
1330
1331         /* We have now checked whether we know enough about the journal
1332          * format to be able to proceed safely, so any other checks that
1333          * fail we should attempt to recover from. */
1334         if (jsb->s_blocksize != htonl(journal->j_blocksize)) {
1335                 com_err(ctx->program_name, EXT2_ET_CORRUPT_JOURNAL_SB,
1336                         _("%s: no valid journal superblock found\n"),
1337                         ctx->device_name);
1338                 return EXT2_ET_CORRUPT_JOURNAL_SB;
1339         }
1340
1341         if (ntohl(jsb->s_maxlen) < journal->j_total_len)
1342                 journal->j_total_len = ntohl(jsb->s_maxlen);
1343         else if (ntohl(jsb->s_maxlen) > journal->j_total_len) {
1344                 com_err(ctx->program_name, EXT2_ET_CORRUPT_JOURNAL_SB,
1345                         _("%s: journal too short\n"),
1346                         ctx->device_name);
1347                 return EXT2_ET_CORRUPT_JOURNAL_SB;
1348         }
1349
1350         journal->j_tail_sequence = ntohl(jsb->s_sequence);
1351         journal->j_transaction_sequence = journal->j_tail_sequence;
1352         journal->j_tail = ntohl(jsb->s_start);
1353         journal->j_first = ntohl(jsb->s_first);
1354         if (jbd2_has_feature_fast_commit(journal)) {
1355                 if (ntohl(jsb->s_maxlen) - jbd2_journal_get_num_fc_blks(jsb)
1356                         < JBD2_MIN_JOURNAL_BLOCKS) {
1357                         com_err(ctx->program_name, EXT2_ET_CORRUPT_JOURNAL_SB,
1358                                 _("%s: incorrect fast commit blocks\n"),
1359                                 ctx->device_name);
1360                         return EXT2_ET_CORRUPT_JOURNAL_SB;
1361                 }
1362                 journal->j_fc_last = ntohl(jsb->s_maxlen);
1363                 journal->j_last = journal->j_fc_last -
1364                                         jbd2_journal_get_num_fc_blks(jsb);
1365                 journal->j_fc_first = journal->j_last + 1;
1366         } else {
1367                 journal->j_last = ntohl(jsb->s_maxlen);
1368         }
1369
1370         return 0;
1371 }
1372
1373 static void e2fsck_journal_reset_super(e2fsck_t ctx, journal_superblock_t *jsb,
1374                                        journal_t *journal)
1375 {
1376         char *p;
1377         union {
1378                 uuid_t uuid;
1379                 __u32 val[4];
1380         } u;
1381         __u32 new_seq = 0;
1382         int i;
1383
1384         /* Leave a valid existing V1 superblock signature alone.
1385          * Anything unrecognisable we overwrite with a new V2
1386          * signature. */
1387
1388         if (jsb->s_header.h_magic != htonl(JBD2_MAGIC_NUMBER) ||
1389             jsb->s_header.h_blocktype != htonl(JBD2_SUPERBLOCK_V1)) {
1390                 jsb->s_header.h_magic = htonl(JBD2_MAGIC_NUMBER);
1391                 jsb->s_header.h_blocktype = htonl(JBD2_SUPERBLOCK_V2);
1392         }
1393
1394         /* Zero out everything else beyond the superblock header */
1395
1396         p = ((char *) jsb) + sizeof(journal_header_t);
1397         memset (p, 0, ctx->fs->blocksize-sizeof(journal_header_t));
1398
1399         jsb->s_blocksize = htonl(ctx->fs->blocksize);
1400         jsb->s_maxlen = htonl(journal->j_total_len);
1401         jsb->s_first = htonl(1);
1402
1403         /* Initialize the journal sequence number so that there is "no"
1404          * chance we will find old "valid" transactions in the journal.
1405          * This avoids the need to zero the whole journal (slow to do,
1406          * and risky when we are just recovering the filesystem).
1407          */
1408         uuid_generate(u.uuid);
1409         for (i = 0; i < 4; i ++)
1410                 new_seq ^= u.val[i];
1411         jsb->s_sequence = htonl(new_seq);
1412         e2fsck_journal_sb_csum_set(journal, jsb);
1413
1414         mark_buffer_dirty(journal->j_sb_buffer);
1415         ll_rw_block(REQ_OP_WRITE, 0, 1, &journal->j_sb_buffer);
1416 }
1417
1418 static errcode_t e2fsck_journal_fix_corrupt_super(e2fsck_t ctx,
1419                                                   journal_t *journal,
1420                                                   struct problem_context *pctx)
1421 {
1422         struct ext2_super_block *sb = ctx->fs->super;
1423         int recover = ext2fs_has_feature_journal_needs_recovery(ctx->fs->super);
1424
1425         if (ext2fs_has_feature_journal(sb)) {
1426                 if (fix_problem(ctx, PR_0_JOURNAL_BAD_SUPER, pctx)) {
1427                         e2fsck_journal_reset_super(ctx, journal->j_superblock,
1428                                                    journal);
1429                         journal->j_transaction_sequence = 1;
1430                         e2fsck_clear_recover(ctx, recover);
1431                         return 0;
1432                 }
1433                 return EXT2_ET_CORRUPT_JOURNAL_SB;
1434         } else if (e2fsck_journal_fix_bad_inode(ctx, pctx))
1435                 return EXT2_ET_CORRUPT_JOURNAL_SB;
1436
1437         return 0;
1438 }
1439
1440 static void e2fsck_journal_release(e2fsck_t ctx, journal_t *journal,
1441                                    int reset, int drop)
1442 {
1443         journal_superblock_t *jsb;
1444
1445         if (drop)
1446                 mark_buffer_clean(journal->j_sb_buffer);
1447         else if (!(ctx->options & E2F_OPT_READONLY)) {
1448                 jsb = journal->j_superblock;
1449                 jsb->s_sequence = htonl(journal->j_tail_sequence);
1450                 if (reset)
1451                         jsb->s_start = 0; /* this marks the journal as empty */
1452                 e2fsck_journal_sb_csum_set(journal, jsb);
1453                 mark_buffer_dirty(journal->j_sb_buffer);
1454         }
1455         brelse(journal->j_sb_buffer);
1456
1457         if (ctx->journal_io) {
1458                 if (ctx->fs && ctx->fs->io != ctx->journal_io)
1459                         io_channel_close(ctx->journal_io);
1460                 ctx->journal_io = 0;
1461         }
1462
1463 #ifndef USE_INODE_IO
1464         if (journal->j_inode)
1465                 ext2fs_free_mem(&journal->j_inode);
1466 #endif
1467         if (journal->j_fs_dev)
1468                 ext2fs_free_mem(&journal->j_fs_dev);
1469         ext2fs_free_mem(&journal);
1470 }
1471
1472 /*
1473  * This function makes sure that the superblock fields regarding the
1474  * journal are consistent.
1475  */
1476 errcode_t e2fsck_check_ext3_journal(e2fsck_t ctx)
1477 {
1478         struct ext2_super_block *sb = ctx->fs->super;
1479         journal_t *journal;
1480         int recover = ext2fs_has_feature_journal_needs_recovery(ctx->fs->super);
1481         struct problem_context pctx;
1482         problem_t problem;
1483         int reset = 0, force_fsck = 0;
1484         errcode_t retval;
1485
1486         /* If we don't have any journal features, don't do anything more */
1487         if (!ext2fs_has_feature_journal(sb) &&
1488             !recover && sb->s_journal_inum == 0 && sb->s_journal_dev == 0 &&
1489             uuid_is_null(sb->s_journal_uuid))
1490                 return 0;
1491
1492         clear_problem_context(&pctx);
1493         pctx.num = sb->s_journal_inum;
1494
1495         retval = e2fsck_get_journal(ctx, &journal);
1496         if (retval) {
1497                 if ((retval == EXT2_ET_BAD_INODE_NUM) ||
1498                     (retval == EXT2_ET_BAD_BLOCK_NUM) ||
1499                     (retval == EXT2_ET_JOURNAL_TOO_SMALL) ||
1500                     (retval == EXT2_ET_NO_JOURNAL))
1501                         return e2fsck_journal_fix_bad_inode(ctx, &pctx);
1502                 return retval;
1503         }
1504
1505         retval = e2fsck_journal_load(journal);
1506         if (retval) {
1507                 if ((retval == EXT2_ET_CORRUPT_JOURNAL_SB) ||
1508                     ((retval == EXT2_ET_UNSUPP_FEATURE) &&
1509                     (!fix_problem(ctx, PR_0_JOURNAL_UNSUPP_INCOMPAT,
1510                                   &pctx))) ||
1511                     ((retval == EXT2_ET_RO_UNSUPP_FEATURE) &&
1512                     (!fix_problem(ctx, PR_0_JOURNAL_UNSUPP_ROCOMPAT,
1513                                   &pctx))) ||
1514                     ((retval == EXT2_ET_JOURNAL_UNSUPP_VERSION) &&
1515                     (!fix_problem(ctx, PR_0_JOURNAL_UNSUPP_VERSION, &pctx))))
1516                         retval = e2fsck_journal_fix_corrupt_super(ctx, journal,
1517                                                                   &pctx);
1518                 e2fsck_journal_release(ctx, journal, 0, 1);
1519                 return retval;
1520         }
1521
1522         /*
1523          * We want to make the flags consistent here.  We will not leave with
1524          * needs_recovery set but has_journal clear.  We can't get in a loop
1525          * with -y, -n, or -p, only if a user isn't making up their mind.
1526          */
1527 no_has_journal:
1528         if (!ext2fs_has_feature_journal(sb)) {
1529                 recover = ext2fs_has_feature_journal_needs_recovery(sb);
1530                 if (fix_problem(ctx, PR_0_JOURNAL_HAS_JOURNAL, &pctx)) {
1531                         if (recover &&
1532                             !fix_problem(ctx, PR_0_JOURNAL_RECOVER_SET, &pctx))
1533                                 goto no_has_journal;
1534                         /*
1535                          * Need a full fsck if we are releasing a
1536                          * journal stored on a reserved inode.
1537                          */
1538                         force_fsck = recover ||
1539                                 (sb->s_journal_inum < EXT2_FIRST_INODE(sb));
1540                         /* Clear all of the journal fields */
1541                         sb->s_journal_inum = 0;
1542                         sb->s_journal_dev = 0;
1543                         memset(sb->s_journal_uuid, 0,
1544                                sizeof(sb->s_journal_uuid));
1545                         e2fsck_clear_recover(ctx, force_fsck);
1546                 } else if (!(ctx->options & E2F_OPT_READONLY)) {
1547                         ext2fs_set_feature_journal(sb);
1548                         ctx->fs->flags &= ~EXT2_FLAG_MASTER_SB_ONLY;
1549                         ext2fs_mark_super_dirty(ctx->fs);
1550                 }
1551         }
1552
1553         if (ext2fs_has_feature_journal(sb) &&
1554             !ext2fs_has_feature_journal_needs_recovery(sb) &&
1555             journal->j_superblock->s_start != 0) {
1556                 /* Print status information */
1557                 fix_problem(ctx, PR_0_JOURNAL_RECOVERY_CLEAR, &pctx);
1558                 if (ctx->superblock)
1559                         problem = PR_0_JOURNAL_RUN_DEFAULT;
1560                 else
1561                         problem = PR_0_JOURNAL_RUN;
1562                 if (fix_problem(ctx, problem, &pctx)) {
1563                         ctx->options |= E2F_OPT_FORCE;
1564                         ext2fs_set_feature_journal_needs_recovery(sb);
1565                         ext2fs_mark_super_dirty(ctx->fs);
1566                 } else if (fix_problem(ctx,
1567                                        PR_0_JOURNAL_RESET_JOURNAL, &pctx)) {
1568                         reset = 1;
1569                         sb->s_state &= ~EXT2_VALID_FS;
1570                         ext2fs_mark_super_dirty(ctx->fs);
1571                 }
1572                 /*
1573                  * If the user answers no to the above question, we
1574                  * ignore the fact that journal apparently has data;
1575                  * accidentally replaying over valid data would be far
1576                  * worse than skipping a questionable recovery.
1577                  *
1578                  * XXX should we abort with a fatal error here?  What
1579                  * will the ext3 kernel code do if a filesystem with
1580                  * !NEEDS_RECOVERY but with a non-zero
1581                  * journal->j_superblock->s_start is mounted?
1582                  */
1583         }
1584
1585         /*
1586          * If we don't need to do replay the journal, check to see if
1587          * the journal's errno is set; if so, we need to mark the file
1588          * system as being corrupt and clear the journal's s_errno.
1589          */
1590         if (!ext2fs_has_feature_journal_needs_recovery(sb) &&
1591             journal->j_superblock->s_errno) {
1592                 ctx->fs->super->s_state |= EXT2_ERROR_FS;
1593                 ext2fs_mark_super_dirty(ctx->fs);
1594                 journal->j_superblock->s_errno = 0;
1595                 e2fsck_journal_sb_csum_set(journal, journal->j_superblock);
1596                 mark_buffer_dirty(journal->j_sb_buffer);
1597         }
1598
1599         e2fsck_journal_release(ctx, journal, reset, 0);
1600         return retval;
1601 }
1602
1603 static errcode_t recover_ext3_journal(e2fsck_t ctx)
1604 {
1605         struct problem_context  pctx;
1606         journal_t *journal;
1607         errcode_t retval;
1608
1609         clear_problem_context(&pctx);
1610
1611         retval = jbd2_journal_init_revoke_record_cache();
1612         if (retval)
1613                 return retval;
1614
1615         retval = jbd2_journal_init_revoke_table_cache();
1616         if (retval)
1617                 return retval;
1618
1619         retval = e2fsck_get_journal(ctx, &journal);
1620         if (retval)
1621                 return retval;
1622
1623         retval = e2fsck_journal_load(journal);
1624         if (retval)
1625                 goto errout;
1626
1627         retval = jbd2_journal_init_revoke(journal, 1024);
1628         if (retval)
1629                 goto errout;
1630
1631         retval = -jbd2_journal_recover(journal);
1632         if (retval)
1633                 goto errout;
1634
1635         if (journal->j_failed_commit) {
1636                 pctx.ino = journal->j_failed_commit;
1637                 fix_problem(ctx, PR_0_JNL_TXN_CORRUPT, &pctx);
1638                 journal->j_superblock->s_errno = -EINVAL;
1639                 mark_buffer_dirty(journal->j_sb_buffer);
1640         }
1641
1642         journal->j_tail_sequence = journal->j_transaction_sequence;
1643
1644 errout:
1645         jbd2_journal_destroy_revoke(journal);
1646         jbd2_journal_destroy_revoke_record_cache();
1647         jbd2_journal_destroy_revoke_table_cache();
1648         e2fsck_journal_release(ctx, journal, 1, 0);
1649         return retval;
1650 }
1651
1652 errcode_t e2fsck_run_ext3_journal(e2fsck_t ctx)
1653 {
1654         io_manager io_ptr = ctx->fs->io->manager;
1655         int blocksize = ctx->fs->blocksize;
1656         errcode_t       retval, recover_retval;
1657         io_stats        stats = 0;
1658         unsigned long long kbytes_written = 0;
1659
1660         printf(_("%s: recovering journal\n"), ctx->device_name);
1661         if (ctx->options & E2F_OPT_READONLY) {
1662                 printf(_("%s: won't do journal recovery while read-only\n"),
1663                        ctx->device_name);
1664                 return EXT2_ET_FILE_RO;
1665         }
1666
1667         if (ctx->fs->flags & EXT2_FLAG_DIRTY)
1668                 ext2fs_flush(ctx->fs);  /* Force out any modifications */
1669
1670         recover_retval = recover_ext3_journal(ctx);
1671
1672         /*
1673          * Reload the filesystem context to get up-to-date data from disk
1674          * because journal recovery will change the filesystem under us.
1675          */
1676         if (ctx->fs->super->s_kbytes_written &&
1677             ctx->fs->io->manager->get_stats)
1678                 ctx->fs->io->manager->get_stats(ctx->fs->io, &stats);
1679         if (stats && stats->bytes_written)
1680                 kbytes_written = stats->bytes_written >> 10;
1681
1682         ext2fs_mmp_stop(ctx->fs);
1683         ext2fs_free(ctx->fs);
1684         retval = ext2fs_open(ctx->filesystem_name, ctx->openfs_flags,
1685                              ctx->superblock, blocksize, io_ptr,
1686                              &ctx->fs);
1687         if (retval) {
1688                 com_err(ctx->program_name, retval,
1689                         _("while trying to re-open %s"),
1690                         ctx->device_name);
1691                 fatal_error(ctx, 0);
1692         }
1693         ctx->fs->priv_data = ctx;
1694         ctx->fs->now = ctx->now;
1695         ctx->fs->flags |= EXT2_FLAG_MASTER_SB_ONLY;
1696         ctx->fs->super->s_kbytes_written += kbytes_written;
1697
1698         /* Set the superblock flags */
1699         e2fsck_clear_recover(ctx, recover_retval != 0);
1700
1701         /*
1702          * Do one last sanity check, and propagate journal->s_errno to
1703          * the EXT2_ERROR_FS flag in the fs superblock if needed.
1704          */
1705         retval = e2fsck_check_ext3_journal(ctx);
1706         return retval ? retval : recover_retval;
1707 }
1708
1709 /*
1710  * This function will move the journal inode from a visible file in
1711  * the filesystem directory hierarchy to the reserved inode if necessary.
1712  */
1713 static const char * const journal_names[] = {
1714         ".journal", "journal", ".journal.dat", "journal.dat", 0 };
1715
1716 void e2fsck_move_ext3_journal(e2fsck_t ctx)
1717 {
1718         struct ext2_super_block *sb = ctx->fs->super;
1719         struct problem_context  pctx;
1720         struct ext2_inode       inode;
1721         ext2_filsys             fs = ctx->fs;
1722         ext2_ino_t              ino;
1723         errcode_t               retval;
1724         const char * const *    cpp;
1725         dgrp_t                  group;
1726         int                     mount_flags;
1727
1728         clear_problem_context(&pctx);
1729
1730         /*
1731          * If the filesystem is opened read-only, or there is no
1732          * journal, then do nothing.
1733          */
1734         if ((ctx->options & E2F_OPT_READONLY) ||
1735             (sb->s_journal_inum == 0) ||
1736             !ext2fs_has_feature_journal(sb))
1737                 return;
1738
1739         /*
1740          * Read in the journal inode
1741          */
1742         if (ext2fs_read_inode(fs, sb->s_journal_inum, &inode) != 0)
1743                 return;
1744
1745         /*
1746          * If it's necessary to backup the journal inode, do so.
1747          */
1748         if ((sb->s_jnl_backup_type == 0) ||
1749             ((sb->s_jnl_backup_type == EXT3_JNL_BACKUP_BLOCKS) &&
1750              memcmp(inode.i_block, sb->s_jnl_blocks, EXT2_N_BLOCKS*4))) {
1751                 if (fix_problem(ctx, PR_0_BACKUP_JNL, &pctx)) {
1752                         memcpy(sb->s_jnl_blocks, inode.i_block,
1753                                EXT2_N_BLOCKS*4);
1754                         sb->s_jnl_blocks[15] = inode.i_size_high;
1755                         sb->s_jnl_blocks[16] = inode.i_size;
1756                         sb->s_jnl_backup_type = EXT3_JNL_BACKUP_BLOCKS;
1757                         ext2fs_mark_super_dirty(fs);
1758                         fs->flags &= ~EXT2_FLAG_MASTER_SB_ONLY;
1759                 }
1760         }
1761
1762         /*
1763          * If the journal is already the hidden inode, then do nothing
1764          */
1765         if (sb->s_journal_inum == EXT2_JOURNAL_INO)
1766                 return;
1767
1768         /*
1769          * The journal inode had better have only one link and not be readable.
1770          */
1771         if (inode.i_links_count != 1)
1772                 return;
1773
1774         /*
1775          * If the filesystem is mounted, or we can't tell whether
1776          * or not it's mounted, do nothing.
1777          */
1778         retval = ext2fs_check_if_mounted(ctx->filesystem_name, &mount_flags);
1779         if (retval || (mount_flags & EXT2_MF_MOUNTED))
1780                 return;
1781
1782         /*
1783          * If we can't find the name of the journal inode, then do
1784          * nothing.
1785          */
1786         for (cpp = journal_names; *cpp; cpp++) {
1787                 retval = ext2fs_lookup(fs, EXT2_ROOT_INO, *cpp,
1788                                        strlen(*cpp), 0, &ino);
1789                 if ((retval == 0) && (ino == sb->s_journal_inum))
1790                         break;
1791         }
1792         if (*cpp == 0)
1793                 return;
1794
1795         /* We need the inode bitmap to be loaded */
1796         retval = ext2fs_read_bitmaps(fs);
1797         if (retval)
1798                 return;
1799
1800         pctx.str = *cpp;
1801         if (!fix_problem(ctx, PR_0_MOVE_JOURNAL, &pctx))
1802                 return;
1803
1804         /*
1805          * OK, we've done all the checks, let's actually move the
1806          * journal inode.  Errors at this point mean we need to force
1807          * an ext2 filesystem check.
1808          */
1809         if ((retval = ext2fs_unlink(fs, EXT2_ROOT_INO, *cpp, ino, 0)) != 0)
1810                 goto err_out;
1811         if ((retval = ext2fs_write_inode(fs, EXT2_JOURNAL_INO, &inode)) != 0)
1812                 goto err_out;
1813         sb->s_journal_inum = EXT2_JOURNAL_INO;
1814         ext2fs_mark_super_dirty(fs);
1815         fs->flags &= ~EXT2_FLAG_MASTER_SB_ONLY;
1816         inode.i_links_count = 0;
1817         inode.i_dtime = ctx->now;
1818         if ((retval = ext2fs_write_inode(fs, ino, &inode)) != 0)
1819                 goto err_out;
1820
1821         group = ext2fs_group_of_ino(fs, ino);
1822         ext2fs_unmark_inode_bitmap2(fs->inode_map, ino);
1823         ext2fs_mark_ib_dirty(fs);
1824         ext2fs_bg_free_inodes_count_set(fs, group, ext2fs_bg_free_inodes_count(fs, group) + 1);
1825         ext2fs_group_desc_csum_set(fs, group);
1826         fs->super->s_free_inodes_count++;
1827         return;
1828
1829 err_out:
1830         pctx.errcode = retval;
1831         fix_problem(ctx, PR_0_ERR_MOVE_JOURNAL, &pctx);
1832         fs->super->s_state &= ~EXT2_VALID_FS;
1833         ext2fs_mark_super_dirty(fs);
1834         return;
1835 }
1836
1837 /*
1838  * This function makes sure the superblock hint for the external
1839  * journal is correct.
1840  */
1841 int e2fsck_fix_ext3_journal_hint(e2fsck_t ctx)
1842 {
1843         struct ext2_super_block *sb = ctx->fs->super;
1844         struct problem_context pctx;
1845         char uuid[37], *journal_name;
1846         struct stat st;
1847
1848         if (!ext2fs_has_feature_journal(sb) ||
1849             uuid_is_null(sb->s_journal_uuid))
1850                 return 0;
1851
1852         uuid_unparse(sb->s_journal_uuid, uuid);
1853         journal_name = blkid_get_devname(ctx->blkid, "UUID", uuid);
1854         if (!journal_name)
1855                 return 0;
1856
1857         if (stat(journal_name, &st) < 0) {
1858                 free(journal_name);
1859                 return 0;
1860         }
1861
1862         if (st.st_rdev != sb->s_journal_dev) {
1863                 clear_problem_context(&pctx);
1864                 pctx.num = st.st_rdev;
1865                 if (fix_problem(ctx, PR_0_EXTERNAL_JOURNAL_HINT, &pctx)) {
1866                         sb->s_journal_dev = st.st_rdev;
1867                         ext2fs_mark_super_dirty(ctx->fs);
1868                 }
1869         }
1870
1871         free(journal_name);
1872         return 0;
1873 }