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