c919176b9e92e2c68764ba50fa587a6631263eac
[project/make_ext4fs.git] / ext4fixup.c
1 /*
2  * Copyright (C) 2010 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 #include "ext4_utils.h"
17 #include "ext4_extents.h"
18 #include "allocate.h"
19 #include "ext4fixup.h"
20
21 #include <sparse/sparse.h>
22
23 #include <sys/types.h>
24 #include <sys/stat.h>
25 #include <sys/types.h>
26 #include <sys/mman.h>
27 #include <fcntl.h>
28 #include <unistd.h>
29
30 #if defined(__APPLE__) && defined(__MACH__)
31 #define lseek64 lseek
32 #define off64_t off_t
33 #endif
34
35 /* The inode block count for a file/directory is in units of 512 byte blocks,
36  * _NOT_ the filesystem block size!
37  */
38 #define INODE_BLOCK_SIZE 512
39
40 #define MAX_EXT4_BLOCK_SIZE 4096
41
42 /* The two modes the recurse_dir() can be in */
43 #define SANITY_CHECK_PASS 1
44 #define MARK_INODE_NUMS   2
45 #define UPDATE_INODE_NUMS 3
46
47 /* Magic numbers to indicate what state the update process is in */
48 #define MAGIC_STATE_MARKING_INUMS  0x7000151515565512ll
49 #define MAGIC_STATE_UPDATING_INUMS 0x6121131211735123ll
50 #define MAGIC_STATE_UPDATING_SB    0x15e1715151558477ll
51
52 /* Internal state variables corresponding to the magic numbers */
53 #define STATE_UNSET          0
54 #define STATE_MARKING_INUMS  1
55 #define STATE_UPDATING_INUMS 2
56 #define STATE_UPDATING_SB    3
57
58 /* Used for automated testing of this programs ability to stop and be restarted wthout error */
59 static int bail_phase = 0;
60 static int bail_loc = 0;
61 static int bail_count = 0;
62 static int count = 0;
63
64 /* global flags */
65 static int verbose = 0;
66 static int no_write = 0;
67
68 static int new_inodes_per_group = 0;
69
70 static int no_write_fixup_state = 0;
71
72 static int compute_new_inum(unsigned int old_inum)
73 {
74     unsigned int group, offset;
75
76     group = (old_inum - 1) / info.inodes_per_group;
77     offset = (old_inum -1) % info.inodes_per_group;
78
79     return (group * new_inodes_per_group) + offset + 1;
80 }
81
82 static int get_fs_fixup_state(int fd)
83 {
84     unsigned long long magic;
85     int ret, len;
86
87     if (no_write) {
88         return no_write_fixup_state;
89     }
90
91     lseek64(fd, 0, SEEK_SET);
92     len = read(fd, &magic, sizeof(magic));
93     if (len != sizeof(magic)) {
94         critical_error("cannot read fixup_state\n");
95     }
96
97     switch (magic) {
98         case MAGIC_STATE_MARKING_INUMS:
99             ret = STATE_MARKING_INUMS;
100             break;
101         case MAGIC_STATE_UPDATING_INUMS:
102             ret = STATE_UPDATING_INUMS;
103             break;
104         case MAGIC_STATE_UPDATING_SB:
105             ret = STATE_UPDATING_SB;
106             break;
107         default:
108             ret = STATE_UNSET;
109     }
110     return ret;
111 }
112
113 static int set_fs_fixup_state(int fd, int state)
114 {
115     unsigned long long magic;
116     struct ext4_super_block sb;
117     int len;
118
119     if (no_write) {
120         no_write_fixup_state = state;
121         return 0;
122     }
123
124     switch (state) {
125         case STATE_MARKING_INUMS:
126             magic = MAGIC_STATE_MARKING_INUMS;
127             break;
128         case STATE_UPDATING_INUMS:
129             magic = MAGIC_STATE_UPDATING_INUMS;
130             break;
131         case STATE_UPDATING_SB:
132             magic = MAGIC_STATE_UPDATING_SB;
133             break;
134         case STATE_UNSET:
135         default:
136             magic = 0ll;
137             break;
138     }
139
140     lseek64(fd, 0, SEEK_SET);
141     len = write(fd, &magic, sizeof(magic));
142     if (len != sizeof(magic)) {
143         critical_error("cannot write fixup_state\n");
144     }
145
146     read_sb(fd, &sb);
147     if (magic) {
148         /* If we are in the process of updating the filesystem, make it unmountable */
149         sb.s_desc_size |= 1;
150     } else {
151         /* we are done, so make the filesystem mountable again */
152         sb.s_desc_size &= ~1;
153     }
154
155     if (!no_write) {
156         write_sb(fd, 1024, &sb);
157     }
158
159     return 0;
160 }
161
162 static int read_inode(int fd, unsigned int inum, struct ext4_inode *inode)
163 {
164     unsigned int bg_num, bg_offset;
165     off64_t inode_offset;
166     int len;
167
168     bg_num = (inum-1) / info.inodes_per_group;
169     bg_offset = (inum-1) % info.inodes_per_group;
170
171     inode_offset = ((unsigned long long)aux_info.bg_desc[bg_num].bg_inode_table * info.block_size) +
172                     (bg_offset * info.inode_size);
173
174     if (lseek64(fd, inode_offset, SEEK_SET) < 0) {
175         critical_error_errno("failed to seek to inode %d\n", inum);
176     }
177
178     len=read(fd, inode, sizeof(*inode));
179     if (len != sizeof(*inode)) {
180         critical_error_errno("failed to read inode %d\n", inum);
181     }
182
183     return 0;
184 }
185
186 static int read_block(int fd, unsigned long long block_num, void *block)
187 {
188     off64_t off;
189     unsigned int len;
190
191     off = block_num * info.block_size;
192
193     if (lseek64(fd, off, SEEK_SET) , 0) {
194         critical_error_errno("failed to seek to block %lld\n", block_num);
195     }
196
197     len=read(fd, block, info.block_size);
198     if (len != info.block_size) {
199         critical_error_errno("failed to read block %lld\n", block_num);
200     }
201
202     return 0;
203 }
204
205 static int write_block(int fd, unsigned long long block_num, void *block)
206 {
207     off64_t off;
208     unsigned int len;
209
210     if (no_write) {
211         return 0;
212     }
213
214     off = block_num * info.block_size;
215
216     if (lseek64(fd, off, SEEK_SET) < 0) {
217         critical_error_errno("failed to seek to block %lld\n", block_num);
218     }
219
220     len=write(fd, block, info.block_size);
221     if (len != info.block_size) {
222         critical_error_errno("failed to write block %lld\n", block_num);
223     }
224
225     return 0;
226 }
227
228 static void check_inode_bitmap(int fd, unsigned int bg_num)
229 {
230     unsigned int inode_bitmap_block_num;
231     unsigned char block[MAX_EXT4_BLOCK_SIZE];
232     int i, bitmap_updated = 0;
233
234     /* Using the bg_num, aux_info.bg_desc[], info.inodes_per_group and
235      * new_inodes_per_group, retrieve the inode bitmap, and make sure
236      * the bits between the old and new size are clear
237      */
238     inode_bitmap_block_num = aux_info.bg_desc[bg_num].bg_inode_bitmap;
239
240     read_block(fd, inode_bitmap_block_num, block);
241
242     for (i = info.inodes_per_group; i < new_inodes_per_group; i++) {
243         if (bitmap_get_bit(block, i)) {
244             bitmap_clear_bit(block, i);
245             bitmap_updated = 1;
246         }
247     }
248
249     if (bitmap_updated) {
250         if (verbose) {
251             printf("Warning: updated inode bitmap for block group %d\n", bg_num);
252         }
253         write_block(fd, inode_bitmap_block_num, block);
254     }
255
256     return;
257 }
258
259 /* Update the superblock and bgdesc of the specified block group */
260 static int update_superblocks_and_bg_desc(int fd, int state)
261 {
262     off64_t ret;
263     struct ext4_super_block sb;
264     unsigned int num_block_groups, total_new_inodes;
265     unsigned int i;
266
267
268     read_sb(fd, &sb);
269
270     /* Compute how many more inodes are now available */
271     num_block_groups = DIV_ROUND_UP(aux_info.len_blocks, info.blocks_per_group);
272     total_new_inodes = num_block_groups * (new_inodes_per_group - sb.s_inodes_per_group);
273
274     if (verbose) {
275         printf("created %d additional inodes\n", total_new_inodes);
276     }
277
278     /* Update the free inodes count in each block group descriptor */
279     for (i = 0; i < num_block_groups; i++) {
280        if (state == STATE_UPDATING_SB) {
281            aux_info.bg_desc[i].bg_free_inodes_count += (new_inodes_per_group - sb.s_inodes_per_group);
282        }
283        check_inode_bitmap(fd, i);
284     }
285
286     /* First some sanity checks */
287     if ((sb.s_inodes_count + total_new_inodes) != (new_inodes_per_group * num_block_groups)) {
288         critical_error("Failed sanity check on new inode count\n");
289     }
290     if (new_inodes_per_group % (info.block_size/info.inode_size)) {
291         critical_error("Failed sanity check on new inode per group alignment\n");
292     }
293
294     /* Update the free inodes count in the superblock */
295     sb.s_inodes_count += total_new_inodes;
296     sb.s_free_inodes_count += total_new_inodes;
297     sb.s_inodes_per_group = new_inodes_per_group;
298
299     for (i = 0; i < aux_info.groups; i++) {
300         if (ext4_bg_has_super_block(i)) {
301             unsigned int sb_offset;
302
303             if (i == 0) {
304               /* The first superblock is offset by 1K to leave room for boot sectors */
305               sb_offset = 1024;
306             } else {
307               sb_offset = 0;
308             }
309
310             sb.s_block_group_nr = i;
311             /* Don't write out the backup superblocks with the bit set in the s_desc_size
312              * which prevents the filesystem from mounting.  The bit for the primary
313              * superblock will be cleared on the final call to set_fs_fixup_state() */
314             if (i != 0) {
315                 sb.s_desc_size &= ~1;
316             }
317
318             if (!no_write) {
319                 write_sb(fd,
320                          (unsigned long long)i
321                          * info.blocks_per_group * info.block_size
322                          + sb_offset,
323                          &sb);
324             }
325
326             ret = lseek64(fd, ((unsigned long long)i * info.blocks_per_group * info.block_size) +
327                               (info.block_size * (aux_info.first_data_block + 1)), SEEK_SET);
328             if (ret < 0)
329                 critical_error_errno("failed to seek to block group descriptors");
330
331             if (!no_write) {
332                 ret = write(fd, aux_info.bg_desc, info.block_size * aux_info.bg_desc_blocks);
333                 if (ret < 0)
334                     critical_error_errno("failed to write block group descriptors");
335                 if (ret != (int)info.block_size * (int)aux_info.bg_desc_blocks)
336                     critical_error("failed to write all of block group descriptors");
337             }
338         }
339         if ((bail_phase == 4) && ((unsigned int)bail_count == i)) {
340             critical_error("bailing at phase 4\n");
341         }
342     }
343
344     return 0;
345 }
346
347
348 static int get_direct_blocks(struct ext4_inode *inode, unsigned long long *block_list,
349                                                        unsigned int *count)
350 {
351     unsigned int i = 0;
352     unsigned int ret = 0;
353     unsigned int sectors_per_block;
354
355     sectors_per_block = info.block_size / INODE_BLOCK_SIZE;
356     while ((i < (inode->i_blocks_lo / sectors_per_block)) && (i < EXT4_NDIR_BLOCKS)) {
357         block_list[i] = inode->i_block[i];
358         i++;
359     }
360
361     *count += i;
362
363     if ((inode->i_blocks_lo / sectors_per_block) > EXT4_NDIR_BLOCKS) {
364         ret = 1;
365     }
366
367     return ret;
368 }
369
370 static int get_indirect_blocks(int fd, struct ext4_inode *inode,
371                                unsigned long long *block_list, unsigned int *count)
372 {
373     unsigned int i;
374     unsigned int *indirect_block;
375     unsigned int sectors_per_block;
376
377     sectors_per_block = info.block_size / INODE_BLOCK_SIZE;
378
379     indirect_block = (unsigned int *)malloc(info.block_size);
380     if (indirect_block == 0) {
381         critical_error("failed to allocate memory for indirect_block\n");
382     }
383
384     read_block(fd, inode->i_block[EXT4_NDIR_BLOCKS], indirect_block);
385
386     for(i = 0; i < (inode->i_blocks_lo / sectors_per_block - EXT4_NDIR_BLOCKS); i++) {
387        block_list[EXT4_NDIR_BLOCKS+i] = indirect_block[i];
388     }
389
390     *count += i;
391
392     free(indirect_block);
393
394     return 0;
395 }
396
397 static int get_block_list_indirect(int fd, struct ext4_inode *inode, unsigned long long *block_list)
398 {
399     unsigned int count=0;
400
401     if (get_direct_blocks(inode, block_list, &count)) {
402         get_indirect_blocks(fd, inode, block_list, &count);
403     }
404
405     return count;
406 }
407
408 static int get_extent_ents(struct ext4_extent_header *ext_hdr, unsigned long long *block_list)
409 {
410     int i, j;
411     struct ext4_extent *extent;
412     off64_t fs_block_num;
413
414     if (ext_hdr->eh_depth != 0) {
415         critical_error("get_extent_ents called with eh_depth != 0\n");
416     }
417
418     /* The extent entries immediately follow the header, so add 1 to the pointer
419      * and cast it to an extent pointer.
420      */
421     extent = (struct ext4_extent *)(ext_hdr + 1);
422
423     for (i = 0; i < ext_hdr->eh_entries; i++) {
424          fs_block_num = ((off64_t)extent->ee_start_hi << 32) | extent->ee_start_lo;
425          for (j = 0; j < extent->ee_len; j++) {
426              block_list[extent->ee_block+j] = fs_block_num+j;
427          }
428          extent++;
429     }
430
431     return 0;
432 }
433
434 static int get_extent_idx(int fd, struct ext4_extent_header *ext_hdr, unsigned long long *block_list)
435 {
436     int i;
437     struct ext4_extent_idx *extent_idx;
438     struct ext4_extent_header *tmp_ext_hdr;
439     off64_t fs_block_num;
440     unsigned char block[MAX_EXT4_BLOCK_SIZE];
441
442     /* Sanity check */
443     if (ext_hdr->eh_depth == 0) {
444         critical_error("get_extent_idx called with eh_depth == 0\n");
445     }
446
447     /* The extent entries immediately follow the header, so add 1 to the pointer
448      * and cast it to an extent pointer.
449      */
450     extent_idx = (struct ext4_extent_idx *)(ext_hdr + 1);
451
452     for (i = 0; i < ext_hdr->eh_entries; i++) {
453          fs_block_num = ((off64_t)extent_idx->ei_leaf_hi << 32) | extent_idx->ei_leaf_lo;
454          read_block(fd, fs_block_num, block);
455          tmp_ext_hdr = (struct ext4_extent_header *)block;
456
457          if (tmp_ext_hdr->eh_depth == 0) {
458              get_extent_ents(tmp_ext_hdr, block_list); /* leaf node, fill in block_list */
459          } else {
460              get_extent_idx(fd, tmp_ext_hdr, block_list); /* recurse down the tree */
461          }
462     }
463
464     return 0;
465 }
466
467 static int get_block_list_extents(int fd, struct ext4_inode *inode, unsigned long long *block_list)
468 {
469     struct ext4_extent_header *extent_hdr;
470
471     extent_hdr = (struct ext4_extent_header *)inode->i_block;
472
473     if (extent_hdr->eh_magic != EXT4_EXT_MAGIC) {
474         critical_error("extent header has unexpected magic value 0x%4.4x\n",
475                        extent_hdr->eh_magic);
476     }
477
478     if (extent_hdr->eh_depth == 0) {
479          get_extent_ents((struct ext4_extent_header *)inode->i_block, block_list);
480          return 0;
481     }
482
483     get_extent_idx(fd, (struct ext4_extent_header *)inode->i_block, block_list);
484
485     return 0;
486 }
487
488 static int is_entry_dir(int fd, struct ext4_dir_entry_2 *dirp, int pass)
489 {
490     struct ext4_inode inode;
491     int ret = 0;
492
493     if (dirp->file_type == EXT4_FT_DIR) {
494         ret = 1;
495     } else if (dirp->file_type == EXT4_FT_UNKNOWN) {
496         /* Somebody was too lazy to fill in the dir entry,
497          * so we have to go fetch it from the inode. Grrr.
498          */
499         /* if UPDATE_INODE_NUMS pass and the inode high bit is not
500          * set return false so we don't recurse down the tree that is
501          * already updated.  Otherwise, fetch inode, and return answer.
502          */
503         if ((pass == UPDATE_INODE_NUMS) && !(dirp->inode & 0x80000000)) {
504             ret = 0;
505         } else {
506             read_inode(fd, (dirp->inode & 0x7fffffff), &inode);
507             if (S_ISDIR(inode.i_mode)) {
508                 ret = 1;
509             }
510         }
511     }
512
513     return ret;
514 }
515
516 static int recurse_dir(int fd, struct ext4_inode *inode, char *dirbuf, int dirsize, int mode)
517 {
518     unsigned long long *block_list;
519     unsigned int num_blocks;
520     struct ext4_dir_entry_2 *dirp, *prev_dirp = 0;
521     char name[256];
522     unsigned int i, leftover_space, is_dir;
523     struct ext4_inode tmp_inode;
524     int tmp_dirsize;
525     char *tmp_dirbuf;
526
527     switch (mode) {
528         case SANITY_CHECK_PASS:
529         case MARK_INODE_NUMS:
530         case UPDATE_INODE_NUMS:
531             break;
532         default:
533             critical_error("recurse_dir() called witn unknown mode!\n");
534     }
535
536     if (dirsize % info.block_size) {
537         critical_error("dirsize %d not a multiple of block_size %d.  This is unexpected!\n",
538                 dirsize, info.block_size);
539     }
540
541     num_blocks = dirsize / info.block_size;
542
543     block_list = malloc((num_blocks + 1) * sizeof(*block_list));
544     if (block_list == 0) {
545         critical_error("failed to allocate memory for block_list\n");
546     }
547
548     if (inode->i_flags & EXT4_EXTENTS_FL) {
549         get_block_list_extents(fd, inode, block_list);
550     } else {
551         /* A directory that requires doubly or triply indirect blocks in huge indeed,
552          * and will almost certainly not exist, especially since make_ext4fs only creates
553          * directories with extents, and the kernel will too, but check to make sure the
554          * directory is not that big and give an error if so.  Our limit is 12 direct blocks,
555          * plus block_size/4 singly indirect blocks, which for a filesystem with 4K blocks
556          * is a directory 1036 blocks long, or 4,243,456 bytes long!  Assuming an average
557          * filename length of 20 (which I think is generous) thats 20 + 8 bytes overhead
558          * per entry, or 151,552 entries in the directory!
559          */
560         if (num_blocks > (info.block_size / 4 + EXT4_NDIR_BLOCKS)) {
561             critical_error("Non-extent based directory is too big!\n");
562         }
563         get_block_list_indirect(fd, inode, block_list);
564     }
565
566     /* Read in all the blocks for this directory */
567     for (i = 0; i < num_blocks; i++) {
568         read_block(fd, block_list[i], dirbuf + (i * info.block_size));
569     }
570
571     dirp = (struct ext4_dir_entry_2 *)dirbuf;
572     while (dirp < (struct ext4_dir_entry_2 *)(dirbuf + dirsize)) {
573         count++;
574         leftover_space = (char *)(dirbuf + dirsize) - (char *)dirp;
575         if (((mode == SANITY_CHECK_PASS) || (mode == UPDATE_INODE_NUMS)) &&
576             (leftover_space <= 8) && prev_dirp) {
577             /* This is a bug in an older version of make_ext4fs, where it
578              * didn't properly include the rest of the block in rec_len.
579              * Update rec_len on the previous entry to include the rest of
580              * the block and exit the loop.
581              */
582             if (verbose) {
583                 printf("fixing up short rec_len for diretory entry for %s\n", name);
584             }
585             prev_dirp->rec_len += leftover_space;
586             break;
587         }
588
589         if (dirp->inode == 0) {
590             /* This is the last entry in the directory */
591             break;
592         }
593
594         strncpy(name, dirp->name, dirp->name_len);
595         name[dirp->name_len]='\0';
596
597         /* Only recurse on pass UPDATE_INODE_NUMS if the high bit is set.
598          * Otherwise, this inode entry has already been updated
599          * and we'll do the wrong thing.  Also don't recurse on . or ..,
600          * and certainly not on non-directories!
601          */
602         /* Hrm, looks like filesystems made by fastboot on stingray set the file_type
603          * flag, but the lost+found directory has the type set to Unknown, which
604          * seems to imply I need to read the inode and get it.
605          */
606         is_dir = is_entry_dir(fd, dirp, mode);
607         if ( is_dir && (strcmp(name, ".") && strcmp(name, "..")) &&
608             ((mode == SANITY_CHECK_PASS) || (mode == MARK_INODE_NUMS) ||
609               ((mode == UPDATE_INODE_NUMS) && (dirp->inode & 0x80000000))) ) {
610             /* A directory!  Recurse! */
611             read_inode(fd, dirp->inode & 0x7fffffff, &tmp_inode);
612
613             if (!S_ISDIR(tmp_inode.i_mode)) {
614                 critical_error("inode %d for name %s does not point to a directory\n",
615                         dirp->inode & 0x7fffffff, name);
616             }
617             if (verbose) {
618                 printf("inode %d %s use extents\n", dirp->inode & 0x7fffffff,
619                        (tmp_inode.i_flags & EXT4_EXTENTS_FL) ? "does" : "does not");
620             }
621
622             tmp_dirsize = tmp_inode.i_blocks_lo * INODE_BLOCK_SIZE;
623             if (verbose) {
624                 printf("dir size = %d bytes\n", tmp_dirsize);
625             }
626
627             tmp_dirbuf = malloc(tmp_dirsize);
628             if (tmp_dirbuf == 0) {
629                 critical_error("failed to allocate memory for tmp_dirbuf\n");
630             }
631
632             recurse_dir(fd, &tmp_inode, tmp_dirbuf, tmp_dirsize, mode);
633
634             free(tmp_dirbuf);
635         }
636
637         if (verbose) {
638             if (is_dir) {
639                 printf("Directory %s\n", name);
640             } else {
641                 printf("Non-directory %s\n", name);
642             }
643         }
644
645         /* Process entry based on current mode.  Either set high bit or change inode number */
646         if (mode == MARK_INODE_NUMS) {
647             dirp->inode |= 0x80000000;
648         } else if (mode == UPDATE_INODE_NUMS) {
649             if (dirp->inode & 0x80000000) {
650                 dirp->inode = compute_new_inum(dirp->inode & 0x7fffffff);
651             }
652         }
653
654         if ((bail_phase == mode) && (bail_loc == 1) && (bail_count == count)) {
655             critical_error("Bailing at phase %d, loc 1 and count %d\n", mode, count);
656         }
657
658         /* Point dirp at the next entry */
659         prev_dirp = dirp;
660         dirp = (struct ext4_dir_entry_2*)((char *)dirp + dirp->rec_len);
661     }
662
663     /* Write out all the blocks for this directory */
664     for (i = 0; i < num_blocks; i++) {
665         write_block(fd, block_list[i], dirbuf + (i * info.block_size));
666         if ((bail_phase == mode) && (bail_loc == 2) && (bail_count <= count)) {
667             critical_error("Bailing at phase %d, loc 2 and count %d\n", mode, count);
668         }
669     }
670
671     free(block_list);
672
673     return 0;
674 }
675
676 int ext4fixup(char *fsdev)
677 {
678     return ext4fixup_internal(fsdev, 0, 0, 0, 0, 0);
679 }
680
681 int ext4fixup_internal(char *fsdev, int v_flag, int n_flag,
682                        int stop_phase, int stop_loc, int stop_count)
683 {
684     int fd;
685     struct ext4_inode root_inode;
686     unsigned int dirsize;
687     char *dirbuf;
688
689     if (setjmp(setjmp_env))
690         return EXIT_FAILURE; /* Handle a call to longjmp() */
691
692     verbose = v_flag;
693     no_write = n_flag;
694
695     bail_phase = stop_phase;
696     bail_loc = stop_loc;
697     bail_count = stop_count;
698
699     fd = open(fsdev, O_RDWR);
700
701     if (fd < 0)
702         critical_error_errno("failed to open filesystem image");
703
704     read_ext(fd, verbose);
705
706     if (info.feat_incompat & EXT4_FEATURE_INCOMPAT_RECOVER) {
707         critical_error("Filesystem needs recovery first, mount and unmount to do that\n");
708     }
709
710     /* Clear the low bit which is set while this tool is in progress.
711      * If the tool crashes, it will still be set when we restart.
712      * The low bit is set to make the filesystem unmountable while
713      * it is being fixed up.  Also allow 0, which means the old ext2
714      * size is in use.
715      */
716     if (((aux_info.sb->s_desc_size & ~1) != sizeof(struct ext2_group_desc)) &&
717         ((aux_info.sb->s_desc_size & ~1) != 0))
718         critical_error("error: bg_desc_size != sizeof(struct ext2_group_desc)\n");
719
720     if ((info.feat_incompat & EXT4_FEATURE_INCOMPAT_FILETYPE) == 0) {
721         critical_error("Expected filesystem to have filetype flag set\n");
722     }
723
724 #if 0 // If we have to fix the directory rec_len issue, we can't use this check
725     /* Check to see if the inodes/group is copacetic */
726     if (info.inodes_per_blockgroup % (info.block_size/info.inode_size) == 0) {
727              /* This filesystem has either already been updated, or was
728               * made correctly.
729               */
730              if (verbose) {
731                  printf("%s: filesystem correct, no work to do\n", me);
732              }
733              exit(0);
734     }
735 #endif
736
737     /* Compute what the new value of inodes_per_blockgroup will be when we're done */
738     new_inodes_per_group=EXT4_ALIGN(info.inodes_per_group,(info.block_size/info.inode_size));
739
740     read_inode(fd, EXT4_ROOT_INO, &root_inode);
741
742     if (!S_ISDIR(root_inode.i_mode)) {
743         critical_error("root inode %d does not point to a directory\n", EXT4_ROOT_INO);
744     }
745     if (verbose) {
746         printf("inode %d %s use extents\n", EXT4_ROOT_INO,
747                (root_inode.i_flags & EXT4_EXTENTS_FL) ? "does" : "does not");
748     }
749
750     dirsize = root_inode.i_blocks_lo * INODE_BLOCK_SIZE;
751     if (verbose) {
752         printf("root dir size = %d bytes\n", dirsize);
753     }
754
755     dirbuf = malloc(dirsize);
756     if (dirbuf == 0) {
757         critical_error("failed to allocate memory for dirbuf\n");
758     }
759
760     /* Perform a sanity check pass first, try to catch any errors that will occur
761      * before we actually change anything, so we don't leave a filesystem in a
762      * corrupted, unrecoverable state.  Set no_write, make it quiet, and do a recurse
763      * pass and a update_superblock pass.  Set flags back to requested state when done.
764      * Only perform sanity check if the state is unset.  If the state is _NOT_ unset,
765      * then the tool has already been run and interrupted, and it presumably ran and
766      * passed sanity checked before it got interrupted.  It is _NOT_ safe to run sanity
767      * check if state is unset because it assumes inodes are to be computed using the
768      * old inodes/group, but some inode numbers may be updated to the new number.
769      */
770     if (get_fs_fixup_state(fd) == STATE_UNSET) {
771         verbose = 0;
772         no_write = 1;
773         recurse_dir(fd, &root_inode, dirbuf, dirsize, SANITY_CHECK_PASS);
774         update_superblocks_and_bg_desc(fd, STATE_UNSET);
775         verbose = v_flag;
776         no_write = n_flag;
777
778         set_fs_fixup_state(fd, STATE_MARKING_INUMS);
779     }
780
781     if (get_fs_fixup_state(fd) == STATE_MARKING_INUMS) {
782         count = 0; /* Reset debugging counter */
783         if (!recurse_dir(fd, &root_inode, dirbuf, dirsize, MARK_INODE_NUMS)) {
784             set_fs_fixup_state(fd, STATE_UPDATING_INUMS);
785         }
786     }
787
788     if (get_fs_fixup_state(fd) == STATE_UPDATING_INUMS) {
789         count = 0; /* Reset debugging counter */
790         if (!recurse_dir(fd, &root_inode, dirbuf, dirsize, UPDATE_INODE_NUMS)) {
791             set_fs_fixup_state(fd, STATE_UPDATING_SB);
792         }
793     }
794
795     if (get_fs_fixup_state(fd) == STATE_UPDATING_SB) {
796         /* set the new inodes/blockgroup number,
797          * and sets the state back to 0.
798          */
799         if (!update_superblocks_and_bg_desc(fd, STATE_UPDATING_SB)) {
800             set_fs_fixup_state(fd, STATE_UNSET);
801         }
802     }
803
804     close(fd);
805
806     return 0;
807 }