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