OSDN Git Service

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