Whamcloud - gitweb
LU-16067 misc: cleanup compiler warnings
[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         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;
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 void tl_to_darg(struct dentry_info_args *darg,
615                               struct ext4_fc_tl *tl)
616 {
617         struct ext4_fc_dentry_info *fcd;
618
619         fcd = (struct ext4_fc_dentry_info *)ext4_fc_tag_val(tl);
620
621         darg->parent_ino = le32_to_cpu(fcd->fc_parent_ino);
622         darg->ino = le32_to_cpu(fcd->fc_ino);
623         darg->dname = (char *) fcd->fc_dname;
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         memcpy(darg->dname, fcd->fc_dname, darg->dname_len);
628         darg->dname[darg->dname_len] = 0;
629         jbd_debug(1, "%s: %s, ino %d, parent %d\n",
630                   le16_to_cpu(tl->fc_tag) == EXT4_FC_TAG_CREAT ? "create" :
631                   (le16_to_cpu(tl->fc_tag) == EXT4_FC_TAG_LINK ? "link" :
632                    (le16_to_cpu(tl->fc_tag) == EXT4_FC_TAG_UNLINK ? "unlink" :
633                     "error")),
634                   darg->dname, darg->ino, darg->parent_ino);
635 }
636
637 static int ext4_fc_handle_unlink(e2fsck_t ctx, struct ext4_fc_tl *tl)
638 {
639         struct dentry_info_args darg;
640         int ret;
641
642         tl_to_darg(&darg, tl);
643         ext4_fc_flush_extents(ctx, darg.ino);
644         ret = errcode_to_errno(ext2fs_unlink(ctx->fs, darg.parent_ino,
645                                              darg.dname, darg.ino, 0));
646         /* It's okay if the above call fails */
647         free(darg.dname);
648
649         return ret;
650 }
651
652 static int ext4_fc_handle_link_and_create(e2fsck_t ctx, struct ext4_fc_tl *tl)
653 {
654         struct dentry_info_args darg;
655         ext2_filsys fs = ctx->fs;
656         struct ext2_inode_large inode_large;
657         int ret, filetype, mode;
658
659         tl_to_darg(&darg, tl);
660         ext4_fc_flush_extents(ctx, 0);
661         ret = errcode_to_errno(ext2fs_read_inode(fs, darg.ino,
662                                                  (struct ext2_inode *)&inode_large));
663         if (ret)
664                 goto out;
665
666         mode = inode_large.i_mode;
667
668         if (LINUX_S_ISREG(mode))
669                 filetype = EXT2_FT_REG_FILE;
670         else if (LINUX_S_ISDIR(mode))
671                 filetype = EXT2_FT_DIR;
672         else if (LINUX_S_ISCHR(mode))
673                 filetype = EXT2_FT_CHRDEV;
674         else if (LINUX_S_ISBLK(mode))
675                 filetype = EXT2_FT_BLKDEV;
676         else if (LINUX_S_ISLNK(mode))
677                 return EXT2_FT_SYMLINK;
678         else if (LINUX_S_ISFIFO(mode))
679                 filetype = EXT2_FT_FIFO;
680         else if (LINUX_S_ISSOCK(mode))
681                 filetype = EXT2_FT_SOCK;
682         else {
683                 ret = -EINVAL;
684                 goto out;
685         }
686
687         /*
688          * Forcefully unlink if the same name is present and ignore the error
689          * if any, since this dirent might not exist
690          */
691         ext2fs_unlink(fs, darg.parent_ino, darg.dname, darg.ino,
692                         EXT2FS_UNLINK_FORCE);
693
694         ret = errcode_to_errno(
695                        ext2fs_link(fs, darg.parent_ino, darg.dname, darg.ino,
696                                    filetype));
697 out:
698         free(darg.dname);
699         return ret;
700
701 }
702
703 /* This function fixes the i_blocks field in the replayed indoe */
704 static void ext4_fc_replay_fixup_iblocks(struct ext2_inode_large *ondisk_inode,
705         struct ext2_inode_large *fc_inode)
706 {
707         if (ondisk_inode->i_flags & EXT4_EXTENTS_FL) {
708                 struct ext3_extent_header *eh;
709
710                 eh = (struct ext3_extent_header *)(&ondisk_inode->i_block[0]);
711                 if (le16_to_cpu(eh->eh_magic) != EXT3_EXT_MAGIC) {
712                         memset(eh, 0, sizeof(*eh));
713                         eh->eh_magic = cpu_to_le16(EXT3_EXT_MAGIC);
714                         eh->eh_max = cpu_to_le16(
715                                 (sizeof(ondisk_inode->i_block) -
716                                         sizeof(struct ext3_extent_header)) /
717                                 sizeof(struct ext3_extent));
718                 }
719         } else if (ondisk_inode->i_flags & EXT4_INLINE_DATA_FL) {
720                 memcpy(ondisk_inode->i_block, fc_inode->i_block,
721                         sizeof(fc_inode->i_block));
722         }
723 }
724
725 static int ext4_fc_handle_inode(e2fsck_t ctx, struct ext4_fc_tl *tl)
726 {
727         int ino, inode_len = EXT2_GOOD_OLD_INODE_SIZE;
728         struct ext2_inode_large *inode = NULL, *fc_inode = NULL;
729         struct ext4_fc_inode *fc_inode_val;
730         errcode_t err;
731         blk64_t blks;
732
733         fc_inode_val = (struct ext4_fc_inode *)ext4_fc_tag_val(tl);
734         ino = le32_to_cpu(fc_inode_val->fc_ino);
735
736         if (EXT2_INODE_SIZE(ctx->fs->super) > EXT2_GOOD_OLD_INODE_SIZE)
737                 inode_len += ext2fs_le16_to_cpu(
738                         ((struct ext2_inode_large *)fc_inode_val->fc_raw_inode)
739                                 ->i_extra_isize);
740         err = ext2fs_get_mem(inode_len, &inode);
741         if (err)
742                 goto out;
743         err = ext2fs_get_mem(inode_len, &fc_inode);
744         if (err)
745                 goto out;
746         ext4_fc_flush_extents(ctx, ino);
747
748         err = ext2fs_read_inode_full(ctx->fs, ino, (struct ext2_inode *)inode,
749                                         inode_len);
750         if (err)
751                 goto out;
752 #ifdef WORDS_BIGENDIAN
753         ext2fs_swap_inode_full(ctx->fs, fc_inode,
754                                (struct ext2_inode_large *)fc_inode_val->fc_raw_inode,
755                                0, sizeof(*inode));
756 #else
757         memcpy(fc_inode, fc_inode_val->fc_raw_inode, inode_len);
758 #endif
759         memcpy(inode, fc_inode, offsetof(struct ext2_inode_large, i_block));
760         memcpy(&inode->i_generation, &fc_inode->i_generation,
761                 inode_len - offsetof(struct ext2_inode_large, i_generation));
762         ext4_fc_replay_fixup_iblocks(inode, fc_inode);
763         err = ext2fs_count_blocks(ctx->fs, ino, EXT2_INODE(inode), &blks);
764         if (err)
765                 goto out;
766         ext2fs_iblk_set(ctx->fs, EXT2_INODE(inode), blks);
767         ext2fs_inode_csum_set(ctx->fs, ino, inode);
768
769         err = ext2fs_write_inode_full(ctx->fs, ino, (struct ext2_inode *)inode,
770                                         inode_len);
771         if (err)
772                 goto out;
773         if (inode->i_links_count)
774                 ext2fs_mark_inode_bitmap2(ctx->fs->inode_map, ino);
775         else
776                 ext2fs_unmark_inode_bitmap2(ctx->fs->inode_map, ino);
777         ext2fs_mark_ib_dirty(ctx->fs);
778
779 out:
780         ext2fs_free_mem(&inode);
781         ext2fs_free_mem(&fc_inode);
782         return errcode_to_errno(err);
783 }
784
785 /*
786  * Handle add extent replay tag.
787  */
788 static int ext4_fc_handle_add_extent(e2fsck_t ctx, struct ext4_fc_tl *tl)
789 {
790         struct ext2fs_extent extent;
791         struct ext4_fc_add_range *add_range;
792         int ret = 0, ino;
793
794         add_range = (struct ext4_fc_add_range *)ext4_fc_tag_val(tl);
795         ino = le32_to_cpu(add_range->fc_ino);
796         ext4_fc_flush_extents(ctx, ino);
797
798         ret = ext4_fc_read_extents(ctx, ino);
799         if (ret)
800                 return ret;
801         memset(&extent, 0, sizeof(extent));
802         ret = errcode_to_errno(ext2fs_decode_extent(
803                         &extent, (void *)(add_range->fc_ex),
804                         sizeof(add_range->fc_ex)));
805         if (ret)
806                 return ret;
807         return ext4_add_extent_to_list(ctx,
808                 &ctx->fc_replay_state.fc_extent_list, &extent);
809 }
810
811 /*
812  * Handle delete logical range replay tag.
813  */
814 static int ext4_fc_handle_del_range(e2fsck_t ctx, struct ext4_fc_tl *tl)
815 {
816         struct ext2fs_extent extent;
817         struct ext4_fc_del_range *del_range;
818         int ret, ino;
819
820         del_range = (struct ext4_fc_del_range *)ext4_fc_tag_val(tl);
821         ino = le32_to_cpu(del_range->fc_ino);
822         ext4_fc_flush_extents(ctx, ino);
823
824         memset(&extent, 0, sizeof(extent));
825         extent.e_lblk = ext2fs_le32_to_cpu(del_range->fc_lblk);
826         extent.e_len = ext2fs_le32_to_cpu(del_range->fc_len);
827         ret = ext4_fc_read_extents(ctx, ino);
828         if (ret)
829                 return ret;
830         return ext4_del_extent_from_list(ctx,
831                 &ctx->fc_replay_state.fc_extent_list, &extent);
832 }
833
834 /*
835  * Main recovery path entry point. This function returns JBD2_FC_REPLAY_CONTINUE
836  * to indicate that it is expecting more fast commit blocks. It returns
837  * JBD2_FC_REPLAY_STOP to indicate that replay is done.
838  */
839 static int ext4_fc_replay(journal_t *journal, struct buffer_head *bh,
840                                 enum passtype pass, int off, tid_t expected_tid)
841 {
842         e2fsck_t ctx = journal->j_fs_dev->k_ctx;
843         struct e2fsck_fc_replay_state *state = &ctx->fc_replay_state;
844         int ret = JBD2_FC_REPLAY_CONTINUE;
845         struct ext4_fc_tl *tl;
846         __u8 *start, *end;
847
848         if (pass == PASS_SCAN) {
849                 state->fc_current_pass = PASS_SCAN;
850                 return ext4_fc_replay_scan(journal, bh, off, expected_tid);
851         }
852
853         if (state->fc_replay_num_tags == 0)
854                 goto replay_done;
855
856         if (state->fc_current_pass != pass) {
857                 /* Starting replay phase */
858                 state->fc_current_pass = pass;
859                 /* We will reset checksums */
860                 ctx->fs->flags |= EXT2_FLAG_IGNORE_CSUM_ERRORS;
861                 ret = errcode_to_errno(ext2fs_read_bitmaps(ctx->fs));
862                 if (ret) {
863                         jbd_debug(1, "Error %d while reading bitmaps\n", ret);
864                         return ret;
865                 }
866                 state->fc_super_state = ctx->fs->super->s_state;
867                 /*
868                  * Mark the file system to indicate it contains errors. That's
869                  * because the updates performed by fast commit replay code are
870                  * not atomic and may result in incosistent file system if it
871                  * crashes before the replay is complete.
872                  */
873                 ctx->fs->super->s_state |= EXT2_ERROR_FS;
874                 ctx->fs->super->s_state |= EXT4_FC_REPLAY;
875                 ext2fs_mark_super_dirty(ctx->fs);
876                 ext2fs_flush(ctx->fs);
877         }
878
879         start = (__u8 *)bh->b_data;
880         end = (__u8 *)bh->b_data + journal->j_blocksize - 1;
881
882         fc_for_each_tl(start, end, tl) {
883                 if (state->fc_replay_num_tags == 0)
884                         goto replay_done;
885                 jbd_debug(3, "Replay phase processing %s tag\n",
886                                 tag2str(le16_to_cpu(tl->fc_tag)));
887                 state->fc_replay_num_tags--;
888                 switch (le16_to_cpu(tl->fc_tag)) {
889                 case EXT4_FC_TAG_CREAT:
890                 case EXT4_FC_TAG_LINK:
891                         ret = ext4_fc_handle_link_and_create(ctx, tl);
892                         break;
893                 case EXT4_FC_TAG_UNLINK:
894                         ret = ext4_fc_handle_unlink(ctx, tl);
895                         break;
896                 case EXT4_FC_TAG_ADD_RANGE:
897                         ret = ext4_fc_handle_add_extent(ctx, tl);
898                         break;
899                 case EXT4_FC_TAG_DEL_RANGE:
900                         ret = ext4_fc_handle_del_range(ctx, tl);
901                         break;
902                 case EXT4_FC_TAG_INODE:
903                         ret = ext4_fc_handle_inode(ctx, tl);
904                         break;
905                 case EXT4_FC_TAG_TAIL:
906                         ext4_fc_flush_extents(ctx, 0);
907                 case EXT4_FC_TAG_PAD:
908                 case EXT4_FC_TAG_HEAD:
909                         break;
910                 default:
911                         ret = -ECANCELED;
912                         break;
913                 }
914                 if (ret < 0)
915                         break;
916                 ret = JBD2_FC_REPLAY_CONTINUE;
917         }
918         return ret;
919 replay_done:
920         jbd_debug(1, "End of fast commit replay\n");
921         if (state->fc_current_pass != pass)
922                 return JBD2_FC_REPLAY_STOP;
923
924         ext2fs_calculate_summary_stats(ctx->fs, 0 /* update bg also */);
925         ext2fs_write_block_bitmap(ctx->fs);
926         ext2fs_write_inode_bitmap(ctx->fs);
927         ext2fs_mark_super_dirty(ctx->fs);
928         ext2fs_set_gdt_csum(ctx->fs);
929         ctx->fs->super->s_state = state->fc_super_state;
930         ext2fs_flush(ctx->fs);
931
932         return JBD2_FC_REPLAY_STOP;
933 }
934
935 static errcode_t e2fsck_get_journal(e2fsck_t ctx, journal_t **ret_journal)
936 {
937         struct process_block_struct pb;
938         struct ext2_super_block *sb = ctx->fs->super;
939         struct ext2_super_block jsuper;
940         struct problem_context  pctx;
941         struct buffer_head      *bh;
942         struct inode            *j_inode = NULL;
943         struct kdev_s           *dev_fs = NULL, *dev_journal;
944         const char              *journal_name = 0;
945         journal_t               *journal = NULL;
946         errcode_t               retval = 0;
947         io_manager              io_ptr = 0;
948         unsigned long long      start = 0;
949         int                     ret;
950         int                     ext_journal = 0;
951         int                     tried_backup_jnl = 0;
952
953         clear_problem_context(&pctx);
954
955         journal = e2fsck_allocate_memory(ctx, sizeof(journal_t), "journal");
956         if (!journal) {
957                 return EXT2_ET_NO_MEMORY;
958         }
959
960         dev_fs = e2fsck_allocate_memory(ctx, 2*sizeof(struct kdev_s), "kdev");
961         if (!dev_fs) {
962                 retval = EXT2_ET_NO_MEMORY;
963                 goto errout;
964         }
965         dev_journal = dev_fs+1;
966
967         dev_fs->k_ctx = dev_journal->k_ctx = ctx;
968         dev_fs->k_dev = K_DEV_FS;
969         dev_journal->k_dev = K_DEV_JOURNAL;
970
971         journal->j_dev = dev_journal;
972         journal->j_fs_dev = dev_fs;
973         journal->j_inode = NULL;
974         journal->j_blocksize = ctx->fs->blocksize;
975
976         if (uuid_is_null(sb->s_journal_uuid)) {
977                 if (!sb->s_journal_inum) {
978                         retval = EXT2_ET_BAD_INODE_NUM;
979                         goto errout;
980                 }
981                 j_inode = e2fsck_allocate_memory(ctx, sizeof(*j_inode),
982                                                  "journal inode");
983                 if (!j_inode) {
984                         retval = EXT2_ET_NO_MEMORY;
985                         goto errout;
986                 }
987
988                 j_inode->i_ctx = ctx;
989                 j_inode->i_ino = sb->s_journal_inum;
990
991                 if ((retval = ext2fs_read_inode(ctx->fs,
992                                                 sb->s_journal_inum,
993                                                 &j_inode->i_ext2))) {
994                 try_backup_journal:
995                         if (sb->s_jnl_backup_type != EXT3_JNL_BACKUP_BLOCKS ||
996                             tried_backup_jnl)
997                                 goto errout;
998                         memset(&j_inode->i_ext2, 0, sizeof(struct ext2_inode));
999                         memcpy(&j_inode->i_ext2.i_block[0], sb->s_jnl_blocks,
1000                                EXT2_N_BLOCKS*4);
1001                         j_inode->i_ext2.i_size_high = sb->s_jnl_blocks[15];
1002                         j_inode->i_ext2.i_size = sb->s_jnl_blocks[16];
1003                         j_inode->i_ext2.i_links_count = 1;
1004                         j_inode->i_ext2.i_mode = LINUX_S_IFREG | 0600;
1005                         e2fsck_use_inode_shortcuts(ctx, 1);
1006                         ctx->stashed_ino = j_inode->i_ino;
1007                         ctx->stashed_inode = &j_inode->i_ext2;
1008                         tried_backup_jnl++;
1009                 }
1010                 if (!j_inode->i_ext2.i_links_count ||
1011                     !LINUX_S_ISREG(j_inode->i_ext2.i_mode)) {
1012                         retval = EXT2_ET_NO_JOURNAL;
1013                         goto try_backup_journal;
1014                 }
1015                 if (EXT2_I_SIZE(&j_inode->i_ext2) / journal->j_blocksize <
1016                     JBD2_MIN_JOURNAL_BLOCKS) {
1017                         retval = EXT2_ET_JOURNAL_TOO_SMALL;
1018                         goto try_backup_journal;
1019                 }
1020                 pb.last_block = -1;
1021                 retval = ext2fs_block_iterate3(ctx->fs, j_inode->i_ino,
1022                                                BLOCK_FLAG_HOLE, 0,
1023                                                process_journal_block, &pb);
1024                 if ((pb.last_block + 1) * ctx->fs->blocksize <
1025                     (int) EXT2_I_SIZE(&j_inode->i_ext2)) {
1026                         retval = EXT2_ET_JOURNAL_TOO_SMALL;
1027                         goto try_backup_journal;
1028                 }
1029                 if (tried_backup_jnl && !(ctx->options & E2F_OPT_READONLY)) {
1030                         retval = ext2fs_write_inode(ctx->fs, sb->s_journal_inum,
1031                                                     &j_inode->i_ext2);
1032                         if (retval)
1033                                 goto errout;
1034                 }
1035
1036                 journal->j_total_len = EXT2_I_SIZE(&j_inode->i_ext2) /
1037                         journal->j_blocksize;
1038
1039 #ifdef USE_INODE_IO
1040                 retval = ext2fs_inode_io_intern2(ctx->fs, sb->s_journal_inum,
1041                                                  &j_inode->i_ext2,
1042                                                  &journal_name);
1043                 if (retval)
1044                         goto errout;
1045
1046                 io_ptr = inode_io_manager;
1047 #else
1048                 journal->j_inode = j_inode;
1049                 ctx->journal_io = ctx->fs->io;
1050                 if ((ret = jbd2_journal_bmap(journal, 0, &start)) != 0) {
1051                         retval = (errcode_t) (-1 * ret);
1052                         goto errout;
1053                 }
1054 #endif
1055         } else {
1056                 ext_journal = 1;
1057                 if (!ctx->journal_name) {
1058                         char uuid[37];
1059
1060                         uuid_unparse(sb->s_journal_uuid, uuid);
1061                         ctx->journal_name = blkid_get_devname(ctx->blkid,
1062                                                               "UUID", uuid);
1063                         if (!ctx->journal_name)
1064                                 ctx->journal_name = blkid_devno_to_devname(sb->s_journal_dev);
1065                 }
1066                 journal_name = ctx->journal_name;
1067
1068                 if (!journal_name) {
1069                         fix_problem(ctx, PR_0_CANT_FIND_JOURNAL, &pctx);
1070                         retval = EXT2_ET_LOAD_EXT_JOURNAL;
1071                         goto errout;
1072                 }
1073
1074                 jfs_debug(1, "Using journal file %s\n", journal_name);
1075                 io_ptr = unix_io_manager;
1076         }
1077
1078 #if 0
1079         test_io_backing_manager = io_ptr;
1080         io_ptr = test_io_manager;
1081 #endif
1082 #ifndef USE_INODE_IO
1083         if (ext_journal)
1084 #endif
1085         {
1086                 int flags = IO_FLAG_RW;
1087                 if (!(ctx->mount_flags & EXT2_MF_ISROOT &&
1088                       ctx->mount_flags & EXT2_MF_READONLY))
1089                         flags |= IO_FLAG_EXCLUSIVE;
1090                 if ((ctx->mount_flags & EXT2_MF_READONLY) &&
1091                     (ctx->options & E2F_OPT_FORCE))
1092                         flags &= ~IO_FLAG_EXCLUSIVE;
1093
1094
1095                 retval = io_ptr->open(journal_name, flags,
1096                                       &ctx->journal_io);
1097         }
1098         if (retval)
1099                 goto errout;
1100
1101         io_channel_set_blksize(ctx->journal_io, ctx->fs->blocksize);
1102
1103         if (ext_journal) {
1104                 blk64_t maxlen;
1105
1106                 start = ext2fs_journal_sb_start(ctx->fs->blocksize) - 1;
1107                 bh = getblk(dev_journal, start, ctx->fs->blocksize);
1108                 if (!bh) {
1109                         retval = EXT2_ET_NO_MEMORY;
1110                         goto errout;
1111                 }
1112                 ll_rw_block(REQ_OP_READ, 0, 1, &bh);
1113                 if ((retval = bh->b_err) != 0) {
1114                         brelse(bh);
1115                         goto errout;
1116                 }
1117                 memcpy(&jsuper, start ? bh->b_data :  bh->b_data + SUPERBLOCK_OFFSET,
1118                        sizeof(jsuper));
1119 #ifdef WORDS_BIGENDIAN
1120                 if (jsuper.s_magic == ext2fs_swab16(EXT2_SUPER_MAGIC))
1121                         ext2fs_swap_super(&jsuper);
1122 #endif
1123                 if (jsuper.s_magic != EXT2_SUPER_MAGIC ||
1124                     !ext2fs_has_feature_journal_dev(&jsuper)) {
1125                         fix_problem(ctx, PR_0_EXT_JOURNAL_BAD_SUPER, &pctx);
1126                         retval = EXT2_ET_LOAD_EXT_JOURNAL;
1127                         brelse(bh);
1128                         goto errout;
1129                 }
1130                 /* Make sure the journal UUID is correct */
1131                 if (memcmp(jsuper.s_uuid, ctx->fs->super->s_journal_uuid,
1132                            sizeof(jsuper.s_uuid))) {
1133                         fix_problem(ctx, PR_0_JOURNAL_BAD_UUID, &pctx);
1134                         retval = EXT2_ET_LOAD_EXT_JOURNAL;
1135                         brelse(bh);
1136                         goto errout;
1137                 }
1138
1139                 /* Check the superblock checksum */
1140                 if (ext2fs_has_feature_metadata_csum(&jsuper)) {
1141                         struct struct_ext2_filsys fsx;
1142                         struct ext2_super_block superx;
1143                         void *p;
1144
1145                         p = start ? bh->b_data : bh->b_data + SUPERBLOCK_OFFSET;
1146                         memcpy(&fsx, ctx->fs, sizeof(fsx));
1147                         memcpy(&superx, ctx->fs->super, sizeof(superx));
1148                         fsx.super = &superx;
1149                         ext2fs_set_feature_metadata_csum(fsx.super);
1150                         if (!ext2fs_superblock_csum_verify(&fsx, p) &&
1151                             fix_problem(ctx, PR_0_EXT_JOURNAL_SUPER_CSUM_INVALID,
1152                                         &pctx)) {
1153                                 ext2fs_superblock_csum_set(&fsx, p);
1154                                 mark_buffer_dirty(bh);
1155                         }
1156                 }
1157                 brelse(bh);
1158
1159                 maxlen = ext2fs_blocks_count(&jsuper);
1160                 journal->j_total_len = (maxlen < 1ULL << 32) ? maxlen : (1ULL << 32) - 1;
1161                 start++;
1162         }
1163
1164         if (!(bh = getblk(dev_journal, start, journal->j_blocksize))) {
1165                 retval = EXT2_ET_NO_MEMORY;
1166                 goto errout;
1167         }
1168
1169         journal->j_sb_buffer = bh;
1170         journal->j_superblock = (journal_superblock_t *)bh->b_data;
1171         if (ext2fs_has_feature_fast_commit(ctx->fs->super))
1172                 journal->j_fc_replay_callback = ext4_fc_replay;
1173         else
1174                 journal->j_fc_replay_callback = NULL;
1175
1176 #ifdef USE_INODE_IO
1177         if (j_inode)
1178                 ext2fs_free_mem(&j_inode);
1179 #endif
1180
1181         *ret_journal = journal;
1182         e2fsck_use_inode_shortcuts(ctx, 0);
1183         return 0;
1184
1185 errout:
1186         e2fsck_use_inode_shortcuts(ctx, 0);
1187         if (dev_fs)
1188                 ext2fs_free_mem(&dev_fs);
1189         if (j_inode)
1190                 ext2fs_free_mem(&j_inode);
1191         if (journal)
1192                 ext2fs_free_mem(&journal);
1193         return retval;
1194 }
1195
1196 static errcode_t e2fsck_journal_fix_bad_inode(e2fsck_t ctx,
1197                                               struct problem_context *pctx)
1198 {
1199         struct ext2_super_block *sb = ctx->fs->super;
1200         int recover = ext2fs_has_feature_journal_needs_recovery(ctx->fs->super);
1201         int has_journal = ext2fs_has_feature_journal(ctx->fs->super);
1202
1203         if (has_journal || sb->s_journal_inum) {
1204                 /* The journal inode is bogus, remove and force full fsck */
1205                 pctx->ino = sb->s_journal_inum;
1206                 if (fix_problem(ctx, PR_0_JOURNAL_BAD_INODE, pctx)) {
1207                         if (has_journal && sb->s_journal_inum)
1208                                 printf("*** journal has been deleted ***\n\n");
1209                         ext2fs_clear_feature_journal(sb);
1210                         sb->s_journal_inum = 0;
1211                         memset(sb->s_jnl_blocks, 0, sizeof(sb->s_jnl_blocks));
1212                         ctx->flags |= E2F_FLAG_JOURNAL_INODE;
1213                         ctx->fs->flags &= ~EXT2_FLAG_MASTER_SB_ONLY;
1214                         e2fsck_clear_recover(ctx, 1);
1215                         return 0;
1216                 }
1217                 return EXT2_ET_CORRUPT_JOURNAL_SB;
1218         } else if (recover) {
1219                 if (fix_problem(ctx, PR_0_JOURNAL_RECOVER_SET, pctx)) {
1220                         e2fsck_clear_recover(ctx, 1);
1221                         return 0;
1222                 }
1223                 return EXT2_ET_UNSUPP_FEATURE;
1224         }
1225         return 0;
1226 }
1227
1228 #define V1_SB_SIZE      0x0024
1229 static void clear_v2_journal_fields(journal_t *journal)
1230 {
1231         e2fsck_t ctx = journal->j_dev->k_ctx;
1232         struct problem_context pctx;
1233
1234         clear_problem_context(&pctx);
1235
1236         if (!fix_problem(ctx, PR_0_CLEAR_V2_JOURNAL, &pctx))
1237                 return;
1238
1239         ctx->flags |= E2F_FLAG_PROBLEMS_FIXED;
1240         memset(((char *) journal->j_superblock) + V1_SB_SIZE, 0,
1241                ctx->fs->blocksize-V1_SB_SIZE);
1242         mark_buffer_dirty(journal->j_sb_buffer);
1243 }
1244
1245
1246 static errcode_t e2fsck_journal_load(journal_t *journal)
1247 {
1248         e2fsck_t ctx = journal->j_dev->k_ctx;
1249         journal_superblock_t *jsb;
1250         struct buffer_head *jbh = journal->j_sb_buffer;
1251         struct problem_context pctx;
1252
1253         clear_problem_context(&pctx);
1254
1255         ll_rw_block(REQ_OP_READ, 0, 1, &jbh);
1256         if (jbh->b_err) {
1257                 com_err(ctx->device_name, jbh->b_err, "%s",
1258                         _("reading journal superblock\n"));
1259                 return jbh->b_err;
1260         }
1261
1262         jsb = journal->j_superblock;
1263         /* If we don't even have JBD2_MAGIC, we probably have a wrong inode */
1264         if (jsb->s_header.h_magic != htonl(JBD2_MAGIC_NUMBER))
1265                 return e2fsck_journal_fix_bad_inode(ctx, &pctx);
1266
1267         switch (ntohl(jsb->s_header.h_blocktype)) {
1268         case JBD2_SUPERBLOCK_V1:
1269                 journal->j_format_version = 1;
1270                 if (jsb->s_feature_compat ||
1271                     jsb->s_feature_incompat ||
1272                     jsb->s_feature_ro_compat ||
1273                     jsb->s_nr_users)
1274                         clear_v2_journal_fields(journal);
1275                 break;
1276
1277         case JBD2_SUPERBLOCK_V2:
1278                 journal->j_format_version = 2;
1279                 if (ntohl(jsb->s_nr_users) > 1 &&
1280                     uuid_is_null(ctx->fs->super->s_journal_uuid))
1281                         clear_v2_journal_fields(journal);
1282                 if (ntohl(jsb->s_nr_users) > 1) {
1283                         fix_problem(ctx, PR_0_JOURNAL_UNSUPP_MULTIFS, &pctx);
1284                         return EXT2_ET_JOURNAL_UNSUPP_VERSION;
1285                 }
1286                 break;
1287
1288         /*
1289          * These should never appear in a journal super block, so if
1290          * they do, the journal is badly corrupted.
1291          */
1292         case JBD2_DESCRIPTOR_BLOCK:
1293         case JBD2_COMMIT_BLOCK:
1294         case JBD2_REVOKE_BLOCK:
1295                 return EXT2_ET_CORRUPT_JOURNAL_SB;
1296
1297         /* If we don't understand the superblock major type, but there
1298          * is a magic number, then it is likely to be a new format we
1299          * just don't understand, so leave it alone. */
1300         default:
1301                 return EXT2_ET_JOURNAL_UNSUPP_VERSION;
1302         }
1303
1304         if (JBD2_HAS_INCOMPAT_FEATURE(journal, ~JBD2_KNOWN_INCOMPAT_FEATURES))
1305                 return EXT2_ET_UNSUPP_FEATURE;
1306
1307         if (JBD2_HAS_RO_COMPAT_FEATURE(journal, ~JBD2_KNOWN_ROCOMPAT_FEATURES))
1308                 return EXT2_ET_RO_UNSUPP_FEATURE;
1309
1310         /* Checksum v1-3 are mutually exclusive features. */
1311         if (jbd2_has_feature_csum2(journal) && jbd2_has_feature_csum3(journal))
1312                 return EXT2_ET_CORRUPT_JOURNAL_SB;
1313
1314         if (jbd2_journal_has_csum_v2or3(journal) &&
1315             jbd2_has_feature_checksum(journal))
1316                 return EXT2_ET_CORRUPT_JOURNAL_SB;
1317
1318         if (!e2fsck_journal_verify_csum_type(journal, jsb) ||
1319             !e2fsck_journal_sb_csum_verify(journal, jsb))
1320                 return EXT2_ET_CORRUPT_JOURNAL_SB;
1321
1322         if (jbd2_journal_has_csum_v2or3(journal))
1323                 journal->j_csum_seed = jbd2_chksum(journal, ~0, jsb->s_uuid,
1324                                                    sizeof(jsb->s_uuid));
1325
1326         /* We have now checked whether we know enough about the journal
1327          * format to be able to proceed safely, so any other checks that
1328          * fail we should attempt to recover from. */
1329         if (jsb->s_blocksize != htonl(journal->j_blocksize)) {
1330                 com_err(ctx->program_name, EXT2_ET_CORRUPT_JOURNAL_SB,
1331                         _("%s: no valid journal superblock found\n"),
1332                         ctx->device_name);
1333                 return EXT2_ET_CORRUPT_JOURNAL_SB;
1334         }
1335
1336         if (ntohl(jsb->s_maxlen) < journal->j_total_len)
1337                 journal->j_total_len = ntohl(jsb->s_maxlen);
1338         else if (ntohl(jsb->s_maxlen) > journal->j_total_len) {
1339                 com_err(ctx->program_name, EXT2_ET_CORRUPT_JOURNAL_SB,
1340                         _("%s: journal too short\n"),
1341                         ctx->device_name);
1342                 return EXT2_ET_CORRUPT_JOURNAL_SB;
1343         }
1344
1345         journal->j_tail_sequence = ntohl(jsb->s_sequence);
1346         journal->j_transaction_sequence = journal->j_tail_sequence;
1347         journal->j_tail = ntohl(jsb->s_start);
1348         journal->j_first = ntohl(jsb->s_first);
1349         if (jbd2_has_feature_fast_commit(journal)) {
1350                 if (ntohl(jsb->s_maxlen) - jbd2_journal_get_num_fc_blks(jsb)
1351                         < JBD2_MIN_JOURNAL_BLOCKS) {
1352                         com_err(ctx->program_name, EXT2_ET_CORRUPT_JOURNAL_SB,
1353                                 _("%s: incorrect fast commit blocks\n"),
1354                                 ctx->device_name);
1355                         return EXT2_ET_CORRUPT_JOURNAL_SB;
1356                 }
1357                 journal->j_fc_last = ntohl(jsb->s_maxlen);
1358                 journal->j_last = journal->j_fc_last -
1359                                         jbd2_journal_get_num_fc_blks(jsb);
1360                 journal->j_fc_first = journal->j_last + 1;
1361         } else {
1362                 journal->j_last = ntohl(jsb->s_maxlen);
1363         }
1364
1365         return 0;
1366 }
1367
1368 static void e2fsck_journal_reset_super(e2fsck_t ctx, journal_superblock_t *jsb,
1369                                        journal_t *journal)
1370 {
1371         char *p;
1372         union {
1373                 uuid_t uuid;
1374                 __u32 val[4];
1375         } u;
1376         __u32 new_seq = 0;
1377         int i;
1378
1379         /* Leave a valid existing V1 superblock signature alone.
1380          * Anything unrecognisable we overwrite with a new V2
1381          * signature. */
1382
1383         if (jsb->s_header.h_magic != htonl(JBD2_MAGIC_NUMBER) ||
1384             jsb->s_header.h_blocktype != htonl(JBD2_SUPERBLOCK_V1)) {
1385                 jsb->s_header.h_magic = htonl(JBD2_MAGIC_NUMBER);
1386                 jsb->s_header.h_blocktype = htonl(JBD2_SUPERBLOCK_V2);
1387         }
1388
1389         /* Zero out everything else beyond the superblock header */
1390
1391         p = ((char *) jsb) + sizeof(journal_header_t);
1392         memset (p, 0, ctx->fs->blocksize-sizeof(journal_header_t));
1393
1394         jsb->s_blocksize = htonl(ctx->fs->blocksize);
1395         jsb->s_maxlen = htonl(journal->j_total_len);
1396         jsb->s_first = htonl(1);
1397
1398         /* Initialize the journal sequence number so that there is "no"
1399          * chance we will find old "valid" transactions in the journal.
1400          * This avoids the need to zero the whole journal (slow to do,
1401          * and risky when we are just recovering the filesystem).
1402          */
1403         uuid_generate(u.uuid);
1404         for (i = 0; i < 4; i ++)
1405                 new_seq ^= u.val[i];
1406         jsb->s_sequence = htonl(new_seq);
1407         e2fsck_journal_sb_csum_set(journal, jsb);
1408
1409         mark_buffer_dirty(journal->j_sb_buffer);
1410         ll_rw_block(REQ_OP_WRITE, 0, 1, &journal->j_sb_buffer);
1411 }
1412
1413 static errcode_t e2fsck_journal_fix_corrupt_super(e2fsck_t ctx,
1414                                                   journal_t *journal,
1415                                                   struct problem_context *pctx)
1416 {
1417         struct ext2_super_block *sb = ctx->fs->super;
1418         int recover = ext2fs_has_feature_journal_needs_recovery(ctx->fs->super);
1419
1420         if (ext2fs_has_feature_journal(sb)) {
1421                 if (fix_problem(ctx, PR_0_JOURNAL_BAD_SUPER, pctx)) {
1422                         e2fsck_journal_reset_super(ctx, journal->j_superblock,
1423                                                    journal);
1424                         journal->j_transaction_sequence = 1;
1425                         e2fsck_clear_recover(ctx, recover);
1426                         return 0;
1427                 }
1428                 return EXT2_ET_CORRUPT_JOURNAL_SB;
1429         } else if (e2fsck_journal_fix_bad_inode(ctx, pctx))
1430                 return EXT2_ET_CORRUPT_JOURNAL_SB;
1431
1432         return 0;
1433 }
1434
1435 static void e2fsck_journal_release(e2fsck_t ctx, journal_t *journal,
1436                                    int reset, int drop)
1437 {
1438         journal_superblock_t *jsb;
1439
1440         if (drop)
1441                 mark_buffer_clean(journal->j_sb_buffer);
1442         else if (!(ctx->options & E2F_OPT_READONLY)) {
1443                 jsb = journal->j_superblock;
1444                 jsb->s_sequence = htonl(journal->j_tail_sequence);
1445                 if (reset)
1446                         jsb->s_start = 0; /* this marks the journal as empty */
1447                 e2fsck_journal_sb_csum_set(journal, jsb);
1448                 mark_buffer_dirty(journal->j_sb_buffer);
1449         }
1450         brelse(journal->j_sb_buffer);
1451
1452         if (ctx->journal_io) {
1453                 if (ctx->fs && ctx->fs->io != ctx->journal_io)
1454                         io_channel_close(ctx->journal_io);
1455                 ctx->journal_io = 0;
1456         }
1457
1458 #ifndef USE_INODE_IO
1459         if (journal->j_inode)
1460                 ext2fs_free_mem(&journal->j_inode);
1461 #endif
1462         if (journal->j_fs_dev)
1463                 ext2fs_free_mem(&journal->j_fs_dev);
1464         ext2fs_free_mem(&journal);
1465 }
1466
1467 /*
1468  * This function makes sure that the superblock fields regarding the
1469  * journal are consistent.
1470  */
1471 errcode_t e2fsck_check_ext3_journal(e2fsck_t ctx)
1472 {
1473         struct ext2_super_block *sb = ctx->fs->super;
1474         journal_t *journal;
1475         int recover = ext2fs_has_feature_journal_needs_recovery(ctx->fs->super);
1476         struct problem_context pctx;
1477         problem_t problem;
1478         int reset = 0, force_fsck = 0;
1479         errcode_t retval;
1480
1481         /* If we don't have any journal features, don't do anything more */
1482         if (!ext2fs_has_feature_journal(sb) &&
1483             !recover && sb->s_journal_inum == 0 && sb->s_journal_dev == 0 &&
1484             uuid_is_null(sb->s_journal_uuid))
1485                 return 0;
1486
1487         clear_problem_context(&pctx);
1488         pctx.num = sb->s_journal_inum;
1489
1490         retval = e2fsck_get_journal(ctx, &journal);
1491         if (retval) {
1492                 if ((retval == EXT2_ET_BAD_INODE_NUM) ||
1493                     (retval == EXT2_ET_BAD_BLOCK_NUM) ||
1494                     (retval == EXT2_ET_JOURNAL_TOO_SMALL) ||
1495                     (retval == EXT2_ET_NO_JOURNAL))
1496                         return e2fsck_journal_fix_bad_inode(ctx, &pctx);
1497                 return retval;
1498         }
1499
1500         retval = e2fsck_journal_load(journal);
1501         if (retval) {
1502                 if ((retval == EXT2_ET_CORRUPT_JOURNAL_SB) ||
1503                     ((retval == EXT2_ET_UNSUPP_FEATURE) &&
1504                     (!fix_problem(ctx, PR_0_JOURNAL_UNSUPP_INCOMPAT,
1505                                   &pctx))) ||
1506                     ((retval == EXT2_ET_RO_UNSUPP_FEATURE) &&
1507                     (!fix_problem(ctx, PR_0_JOURNAL_UNSUPP_ROCOMPAT,
1508                                   &pctx))) ||
1509                     ((retval == EXT2_ET_JOURNAL_UNSUPP_VERSION) &&
1510                     (!fix_problem(ctx, PR_0_JOURNAL_UNSUPP_VERSION, &pctx))))
1511                         retval = e2fsck_journal_fix_corrupt_super(ctx, journal,
1512                                                                   &pctx);
1513                 e2fsck_journal_release(ctx, journal, 0, 1);
1514                 return retval;
1515         }
1516
1517         /*
1518          * We want to make the flags consistent here.  We will not leave with
1519          * needs_recovery set but has_journal clear.  We can't get in a loop
1520          * with -y, -n, or -p, only if a user isn't making up their mind.
1521          */
1522 no_has_journal:
1523         if (!ext2fs_has_feature_journal(sb)) {
1524                 recover = ext2fs_has_feature_journal_needs_recovery(sb);
1525                 if (fix_problem(ctx, PR_0_JOURNAL_HAS_JOURNAL, &pctx)) {
1526                         if (recover &&
1527                             !fix_problem(ctx, PR_0_JOURNAL_RECOVER_SET, &pctx))
1528                                 goto no_has_journal;
1529                         /*
1530                          * Need a full fsck if we are releasing a
1531                          * journal stored on a reserved inode.
1532                          */
1533                         force_fsck = recover ||
1534                                 (sb->s_journal_inum < EXT2_FIRST_INODE(sb));
1535                         /* Clear all of the journal fields */
1536                         sb->s_journal_inum = 0;
1537                         sb->s_journal_dev = 0;
1538                         memset(sb->s_journal_uuid, 0,
1539                                sizeof(sb->s_journal_uuid));
1540                         e2fsck_clear_recover(ctx, force_fsck);
1541                 } else if (!(ctx->options & E2F_OPT_READONLY)) {
1542                         ext2fs_set_feature_journal(sb);
1543                         ctx->fs->flags &= ~EXT2_FLAG_MASTER_SB_ONLY;
1544                         ext2fs_mark_super_dirty(ctx->fs);
1545                 }
1546         }
1547
1548         if (ext2fs_has_feature_journal(sb) &&
1549             !ext2fs_has_feature_journal_needs_recovery(sb) &&
1550             journal->j_superblock->s_start != 0) {
1551                 /* Print status information */
1552                 fix_problem(ctx, PR_0_JOURNAL_RECOVERY_CLEAR, &pctx);
1553                 if (ctx->superblock)
1554                         problem = PR_0_JOURNAL_RUN_DEFAULT;
1555                 else
1556                         problem = PR_0_JOURNAL_RUN;
1557                 if (fix_problem(ctx, problem, &pctx)) {
1558                         ctx->options |= E2F_OPT_FORCE;
1559                         ext2fs_set_feature_journal_needs_recovery(sb);
1560                         ext2fs_mark_super_dirty(ctx->fs);
1561                 } else if (fix_problem(ctx,
1562                                        PR_0_JOURNAL_RESET_JOURNAL, &pctx)) {
1563                         reset = 1;
1564                         sb->s_state &= ~EXT2_VALID_FS;
1565                         ext2fs_mark_super_dirty(ctx->fs);
1566                 }
1567                 /*
1568                  * If the user answers no to the above question, we
1569                  * ignore the fact that journal apparently has data;
1570                  * accidentally replaying over valid data would be far
1571                  * worse than skipping a questionable recovery.
1572                  *
1573                  * XXX should we abort with a fatal error here?  What
1574                  * will the ext3 kernel code do if a filesystem with
1575                  * !NEEDS_RECOVERY but with a non-zero
1576                  * journal->j_superblock->s_start is mounted?
1577                  */
1578         }
1579
1580         /*
1581          * If we don't need to do replay the journal, check to see if
1582          * the journal's errno is set; if so, we need to mark the file
1583          * system as being corrupt and clear the journal's s_errno.
1584          */
1585         if (!ext2fs_has_feature_journal_needs_recovery(sb) &&
1586             journal->j_superblock->s_errno) {
1587                 ctx->fs->super->s_state |= EXT2_ERROR_FS;
1588                 ext2fs_mark_super_dirty(ctx->fs);
1589                 journal->j_superblock->s_errno = 0;
1590                 e2fsck_journal_sb_csum_set(journal, journal->j_superblock);
1591                 mark_buffer_dirty(journal->j_sb_buffer);
1592         }
1593
1594         e2fsck_journal_release(ctx, journal, reset, 0);
1595         return retval;
1596 }
1597
1598 static errcode_t recover_ext3_journal(e2fsck_t ctx)
1599 {
1600         struct problem_context  pctx;
1601         journal_t *journal;
1602         errcode_t retval;
1603
1604         clear_problem_context(&pctx);
1605
1606         retval = jbd2_journal_init_revoke_record_cache();
1607         if (retval)
1608                 return retval;
1609
1610         retval = jbd2_journal_init_revoke_table_cache();
1611         if (retval)
1612                 return retval;
1613
1614         retval = e2fsck_get_journal(ctx, &journal);
1615         if (retval)
1616                 return retval;
1617
1618         retval = e2fsck_journal_load(journal);
1619         if (retval)
1620                 goto errout;
1621
1622         retval = jbd2_journal_init_revoke(journal, 1024);
1623         if (retval)
1624                 goto errout;
1625
1626         retval = -jbd2_journal_recover(journal);
1627         if (retval)
1628                 goto errout;
1629
1630         if (journal->j_failed_commit) {
1631                 pctx.ino = journal->j_failed_commit;
1632                 fix_problem(ctx, PR_0_JNL_TXN_CORRUPT, &pctx);
1633                 journal->j_superblock->s_errno = -EINVAL;
1634                 mark_buffer_dirty(journal->j_sb_buffer);
1635         }
1636
1637         journal->j_tail_sequence = journal->j_transaction_sequence;
1638
1639 errout:
1640         jbd2_journal_destroy_revoke(journal);
1641         jbd2_journal_destroy_revoke_record_cache();
1642         jbd2_journal_destroy_revoke_table_cache();
1643         e2fsck_journal_release(ctx, journal, 1, 0);
1644         return retval;
1645 }
1646
1647 errcode_t e2fsck_run_ext3_journal(e2fsck_t ctx)
1648 {
1649         io_manager io_ptr = ctx->fs->io->manager;
1650         int blocksize = ctx->fs->blocksize;
1651         errcode_t       retval, recover_retval;
1652         io_stats        stats = 0;
1653         unsigned long long kbytes_written = 0;
1654
1655         printf(_("%s: recovering journal\n"), ctx->device_name);
1656         if (ctx->options & E2F_OPT_READONLY) {
1657                 printf(_("%s: won't do journal recovery while read-only\n"),
1658                        ctx->device_name);
1659                 return EXT2_ET_FILE_RO;
1660         }
1661
1662         if (ctx->fs->flags & EXT2_FLAG_DIRTY)
1663                 ext2fs_flush(ctx->fs);  /* Force out any modifications */
1664
1665         recover_retval = recover_ext3_journal(ctx);
1666
1667         /*
1668          * Reload the filesystem context to get up-to-date data from disk
1669          * because journal recovery will change the filesystem under us.
1670          */
1671         if (ctx->fs->super->s_kbytes_written &&
1672             ctx->fs->io->manager->get_stats)
1673                 ctx->fs->io->manager->get_stats(ctx->fs->io, &stats);
1674         if (stats && stats->bytes_written)
1675                 kbytes_written = stats->bytes_written >> 10;
1676
1677         ext2fs_mmp_stop(ctx->fs);
1678         ext2fs_free(ctx->fs);
1679         retval = ext2fs_open(ctx->filesystem_name, ctx->openfs_flags,
1680                              ctx->superblock, blocksize, io_ptr,
1681                              &ctx->fs);
1682         if (retval) {
1683                 com_err(ctx->program_name, retval,
1684                         _("while trying to re-open %s"),
1685                         ctx->device_name);
1686                 fatal_error(ctx, 0);
1687         }
1688         ctx->fs->priv_data = ctx;
1689         ctx->fs->now = ctx->now;
1690         ctx->fs->flags |= EXT2_FLAG_MASTER_SB_ONLY;
1691         ctx->fs->super->s_kbytes_written += kbytes_written;
1692
1693         /* Set the superblock flags */
1694         e2fsck_clear_recover(ctx, recover_retval != 0);
1695
1696         /*
1697          * Do one last sanity check, and propagate journal->s_errno to
1698          * the EXT2_ERROR_FS flag in the fs superblock if needed.
1699          */
1700         retval = e2fsck_check_ext3_journal(ctx);
1701         return retval ? retval : recover_retval;
1702 }
1703
1704 /*
1705  * This function will move the journal inode from a visible file in
1706  * the filesystem directory hierarchy to the reserved inode if necessary.
1707  */
1708 static const char * const journal_names[] = {
1709         ".journal", "journal", ".journal.dat", "journal.dat", 0 };
1710
1711 void e2fsck_move_ext3_journal(e2fsck_t ctx)
1712 {
1713         struct ext2_super_block *sb = ctx->fs->super;
1714         struct problem_context  pctx;
1715         struct ext2_inode       inode;
1716         ext2_filsys             fs = ctx->fs;
1717         ext2_ino_t              ino;
1718         errcode_t               retval;
1719         const char * const *    cpp;
1720         dgrp_t                  group;
1721         int                     mount_flags;
1722
1723         clear_problem_context(&pctx);
1724
1725         /*
1726          * If the filesystem is opened read-only, or there is no
1727          * journal, then do nothing.
1728          */
1729         if ((ctx->options & E2F_OPT_READONLY) ||
1730             (sb->s_journal_inum == 0) ||
1731             !ext2fs_has_feature_journal(sb))
1732                 return;
1733
1734         /*
1735          * Read in the journal inode
1736          */
1737         if (ext2fs_read_inode(fs, sb->s_journal_inum, &inode) != 0)
1738                 return;
1739
1740         /*
1741          * If it's necessary to backup the journal inode, do so.
1742          */
1743         if ((sb->s_jnl_backup_type == 0) ||
1744             ((sb->s_jnl_backup_type == EXT3_JNL_BACKUP_BLOCKS) &&
1745              memcmp(inode.i_block, sb->s_jnl_blocks, EXT2_N_BLOCKS*4))) {
1746                 if (fix_problem(ctx, PR_0_BACKUP_JNL, &pctx)) {
1747                         memcpy(sb->s_jnl_blocks, inode.i_block,
1748                                EXT2_N_BLOCKS*4);
1749                         sb->s_jnl_blocks[15] = inode.i_size_high;
1750                         sb->s_jnl_blocks[16] = inode.i_size;
1751                         sb->s_jnl_backup_type = EXT3_JNL_BACKUP_BLOCKS;
1752                         ext2fs_mark_super_dirty(fs);
1753                         fs->flags &= ~EXT2_FLAG_MASTER_SB_ONLY;
1754                 }
1755         }
1756
1757         /*
1758          * If the journal is already the hidden inode, then do nothing
1759          */
1760         if (sb->s_journal_inum == EXT2_JOURNAL_INO)
1761                 return;
1762
1763         /*
1764          * The journal inode had better have only one link and not be readable.
1765          */
1766         if (inode.i_links_count != 1)
1767                 return;
1768
1769         /*
1770          * If the filesystem is mounted, or we can't tell whether
1771          * or not it's mounted, do nothing.
1772          */
1773         retval = ext2fs_check_if_mounted(ctx->filesystem_name, &mount_flags);
1774         if (retval || (mount_flags & EXT2_MF_MOUNTED))
1775                 return;
1776
1777         /*
1778          * If we can't find the name of the journal inode, then do
1779          * nothing.
1780          */
1781         for (cpp = journal_names; *cpp; cpp++) {
1782                 retval = ext2fs_lookup(fs, EXT2_ROOT_INO, *cpp,
1783                                        strlen(*cpp), 0, &ino);
1784                 if ((retval == 0) && (ino == sb->s_journal_inum))
1785                         break;
1786         }
1787         if (*cpp == 0)
1788                 return;
1789
1790         /* We need the inode bitmap to be loaded */
1791         retval = ext2fs_read_bitmaps(fs);
1792         if (retval)
1793                 return;
1794
1795         pctx.str = *cpp;
1796         if (!fix_problem(ctx, PR_0_MOVE_JOURNAL, &pctx))
1797                 return;
1798
1799         /*
1800          * OK, we've done all the checks, let's actually move the
1801          * journal inode.  Errors at this point mean we need to force
1802          * an ext2 filesystem check.
1803          */
1804         if ((retval = ext2fs_unlink(fs, EXT2_ROOT_INO, *cpp, ino, 0)) != 0)
1805                 goto err_out;
1806         if ((retval = ext2fs_write_inode(fs, EXT2_JOURNAL_INO, &inode)) != 0)
1807                 goto err_out;
1808         sb->s_journal_inum = EXT2_JOURNAL_INO;
1809         ext2fs_mark_super_dirty(fs);
1810         fs->flags &= ~EXT2_FLAG_MASTER_SB_ONLY;
1811         inode.i_links_count = 0;
1812         inode.i_dtime = ctx->now;
1813         if ((retval = ext2fs_write_inode(fs, ino, &inode)) != 0)
1814                 goto err_out;
1815
1816         group = ext2fs_group_of_ino(fs, ino);
1817         ext2fs_unmark_inode_bitmap2(fs->inode_map, ino);
1818         ext2fs_mark_ib_dirty(fs);
1819         ext2fs_bg_free_inodes_count_set(fs, group, ext2fs_bg_free_inodes_count(fs, group) + 1);
1820         ext2fs_group_desc_csum_set(fs, group);
1821         fs->super->s_free_inodes_count++;
1822         return;
1823
1824 err_out:
1825         pctx.errcode = retval;
1826         fix_problem(ctx, PR_0_ERR_MOVE_JOURNAL, &pctx);
1827         fs->super->s_state &= ~EXT2_VALID_FS;
1828         ext2fs_mark_super_dirty(fs);
1829         return;
1830 }
1831
1832 /*
1833  * This function makes sure the superblock hint for the external
1834  * journal is correct.
1835  */
1836 int e2fsck_fix_ext3_journal_hint(e2fsck_t ctx)
1837 {
1838         struct ext2_super_block *sb = ctx->fs->super;
1839         struct problem_context pctx;
1840         char uuid[37], *journal_name;
1841         struct stat st;
1842
1843         if (!ext2fs_has_feature_journal(sb) ||
1844             uuid_is_null(sb->s_journal_uuid))
1845                 return 0;
1846
1847         uuid_unparse(sb->s_journal_uuid, uuid);
1848         journal_name = blkid_get_devname(ctx->blkid, "UUID", uuid);
1849         if (!journal_name)
1850                 return 0;
1851
1852         if (stat(journal_name, &st) < 0) {
1853                 free(journal_name);
1854                 return 0;
1855         }
1856
1857         if (st.st_rdev != sb->s_journal_dev) {
1858                 clear_problem_context(&pctx);
1859                 pctx.num = st.st_rdev;
1860                 if (fix_problem(ctx, PR_0_EXTERNAL_JOURNAL_HINT, &pctx)) {
1861                         sb->s_journal_dev = st.st_rdev;
1862                         ext2fs_mark_super_dirty(ctx->fs);
1863                 }
1864         }
1865
1866         free(journal_name);
1867         return 0;
1868 }