Whamcloud - gitweb
e2fsck: use the correct block size when salvaging directories
[tools/e2fsprogs.git] / e2fsck / pass2.c
1 /*
2  * pass2.c --- check directory structure
3  *
4  * Copyright (C) 1993, 1994, 1995, 1996, 1997 Theodore Ts'o
5  *
6  * %Begin-Header%
7  * This file may be redistributed under the terms of the GNU Public
8  * License.
9  * %End-Header%
10  *
11  * Pass 2 of e2fsck iterates through all active directory inodes, and
12  * applies to following tests to each directory entry in the directory
13  * blocks in the inodes:
14  *
15  *      - The length of the directory entry (rec_len) should be at
16  *              least 8 bytes, and no more than the remaining space
17  *              left in the directory block.
18  *      - The length of the name in the directory entry (name_len)
19  *              should be less than (rec_len - 8).
20  *      - The inode number in the directory entry should be within
21  *              legal bounds.
22  *      - The inode number should refer to a in-use inode.
23  *      - The first entry should be '.', and its inode should be
24  *              the inode of the directory.
25  *      - The second entry should be '..'.
26  *
27  * To minimize disk seek time, the directory blocks are processed in
28  * sorted order of block numbers.
29  *
30  * Pass 2 also collects the following information:
31  *      - The inode numbers of the subdirectories for each directory.
32  *
33  * Pass 2 relies on the following information from previous passes:
34  *      - The directory information collected in pass 1.
35  *      - The inode_used_map bitmap
36  *      - The inode_bad_map bitmap
37  *      - The inode_dir_map bitmap
38  *
39  * Pass 2 frees the following data structures
40  *      - The inode_bad_map bitmap
41  *      - The inode_reg_map bitmap
42  */
43
44 #define _GNU_SOURCE 1 /* get strnlen() */
45 #include "config.h"
46 #include <string.h>
47
48 #include "e2fsck.h"
49 #include "problem.h"
50 #include "dict.h"
51
52 #ifdef NO_INLINE_FUNCS
53 #define _INLINE_
54 #else
55 #define _INLINE_ inline
56 #endif
57
58 /* #define DX_DEBUG */
59
60 /*
61  * Keeps track of how many times an inode is referenced.
62  */
63 static void deallocate_inode(e2fsck_t ctx, ext2_ino_t ino, char* block_buf);
64 static int check_dir_block(ext2_filsys fs,
65                            struct ext2_db_entry2 *dir_blocks_info,
66                            void *priv_data);
67 static int allocate_dir_block(e2fsck_t ctx,
68                               struct ext2_db_entry2 *dir_blocks_info,
69                               char *buf, struct problem_context *pctx);
70 static void clear_htree(e2fsck_t ctx, ext2_ino_t ino);
71 static int htree_depth(struct dx_dir_info *dx_dir,
72                        struct dx_dirblock_info *dx_db);
73 static EXT2_QSORT_TYPE special_dir_block_cmp(const void *a, const void *b);
74
75 struct check_dir_struct {
76         char *buf;
77         struct problem_context  pctx;
78         int     count, max;
79         e2fsck_t ctx;
80 };
81
82 void e2fsck_pass2(e2fsck_t ctx)
83 {
84         struct ext2_super_block *sb = ctx->fs->super;
85         struct problem_context  pctx;
86         ext2_filsys             fs = ctx->fs;
87         char                    *buf;
88 #ifdef RESOURCE_TRACK
89         struct resource_track   rtrack;
90 #endif
91         struct check_dir_struct cd;
92         struct dx_dir_info      *dx_dir;
93         struct dx_dirblock_info *dx_db, *dx_parent;
94         unsigned int            save_type;
95         int                     b;
96         int                     i, depth;
97         problem_t               code;
98         int                     bad_dir;
99
100         init_resource_track(&rtrack, ctx->fs->io);
101         clear_problem_context(&cd.pctx);
102
103 #ifdef MTRACE
104         mtrace_print("Pass 2");
105 #endif
106
107         if (!(ctx->options & E2F_OPT_PREEN))
108                 fix_problem(ctx, PR_2_PASS_HEADER, &cd.pctx);
109
110         e2fsck_setup_tdb_icount(ctx, EXT2_ICOUNT_OPT_INCREMENT,
111                                 &ctx->inode_count);
112         if (ctx->inode_count)
113                 cd.pctx.errcode = 0;
114         else {
115                 e2fsck_set_bitmap_type(fs, EXT2FS_BMAP64_RBTREE,
116                                        "inode_count", &save_type);
117                 cd.pctx.errcode = ext2fs_create_icount2(fs,
118                                                 EXT2_ICOUNT_OPT_INCREMENT,
119                                                 0, ctx->inode_link_info,
120                                                 &ctx->inode_count);
121                 fs->default_bitmap_type = save_type;
122         }
123         if (cd.pctx.errcode) {
124                 fix_problem(ctx, PR_2_ALLOCATE_ICOUNT, &cd.pctx);
125                 ctx->flags |= E2F_FLAG_ABORT;
126                 return;
127         }
128         buf = (char *) e2fsck_allocate_memory(ctx, 2*fs->blocksize,
129                                               "directory scan buffer");
130
131         /*
132          * Set up the parent pointer for the root directory, if
133          * present.  (If the root directory is not present, we will
134          * create it in pass 3.)
135          */
136         (void) e2fsck_dir_info_set_parent(ctx, EXT2_ROOT_INO, EXT2_ROOT_INO);
137
138         cd.buf = buf;
139         cd.ctx = ctx;
140         cd.count = 1;
141         cd.max = ext2fs_dblist_count2(fs->dblist);
142
143         if (ctx->progress)
144                 (void) (ctx->progress)(ctx, 2, 0, cd.max);
145
146         if (fs->super->s_feature_compat & EXT2_FEATURE_COMPAT_DIR_INDEX)
147                 ext2fs_dblist_sort2(fs->dblist, special_dir_block_cmp);
148
149         cd.pctx.errcode = ext2fs_dblist_iterate2(fs->dblist, check_dir_block,
150                                                  &cd);
151         if (ctx->flags & E2F_FLAG_SIGNAL_MASK || ctx->flags & E2F_FLAG_RESTART)
152                 return;
153
154         if (ctx->flags & E2F_FLAG_RESTART_LATER) {
155                 ctx->flags |= E2F_FLAG_RESTART;
156                 return;
157         }
158
159         if (cd.pctx.errcode) {
160                 fix_problem(ctx, PR_2_DBLIST_ITERATE, &cd.pctx);
161                 ctx->flags |= E2F_FLAG_ABORT;
162                 return;
163         }
164
165 #ifdef ENABLE_HTREE
166         for (i=0; (dx_dir = e2fsck_dx_dir_info_iter(ctx, &i)) != 0;) {
167                 if (ctx->flags & E2F_FLAG_SIGNAL_MASK)
168                         return;
169                 if (dx_dir->numblocks == 0)
170                         continue;
171                 clear_problem_context(&pctx);
172                 bad_dir = 0;
173                 pctx.dir = dx_dir->ino;
174                 dx_db = dx_dir->dx_block;
175                 if (dx_db->flags & DX_FLAG_REFERENCED)
176                         dx_db->flags |= DX_FLAG_DUP_REF;
177                 else
178                         dx_db->flags |= DX_FLAG_REFERENCED;
179                 /*
180                  * Find all of the first and last leaf blocks, and
181                  * update their parent's min and max hash values
182                  */
183                 for (b=0, dx_db = dx_dir->dx_block;
184                      b < dx_dir->numblocks;
185                      b++, dx_db++) {
186                         if ((dx_db->type != DX_DIRBLOCK_LEAF) ||
187                             !(dx_db->flags & (DX_FLAG_FIRST | DX_FLAG_LAST)))
188                                 continue;
189                         dx_parent = &dx_dir->dx_block[dx_db->parent];
190                         /*
191                          * XXX Make sure dx_parent->min_hash > dx_db->min_hash
192                          */
193                         if (dx_db->flags & DX_FLAG_FIRST)
194                                 dx_parent->min_hash = dx_db->min_hash;
195                         /*
196                          * XXX Make sure dx_parent->max_hash < dx_db->max_hash
197                          */
198                         if (dx_db->flags & DX_FLAG_LAST)
199                                 dx_parent->max_hash = dx_db->max_hash;
200                 }
201
202                 for (b=0, dx_db = dx_dir->dx_block;
203                      b < dx_dir->numblocks;
204                      b++, dx_db++) {
205                         pctx.blkcount = b;
206                         pctx.group = dx_db->parent;
207                         code = 0;
208                         if (!(dx_db->flags & DX_FLAG_FIRST) &&
209                             (dx_db->min_hash < dx_db->node_min_hash)) {
210                                 pctx.blk = dx_db->min_hash;
211                                 pctx.blk2 = dx_db->node_min_hash;
212                                 code = PR_2_HTREE_MIN_HASH;
213                                 fix_problem(ctx, code, &pctx);
214                                 bad_dir++;
215                         }
216                         if (dx_db->type == DX_DIRBLOCK_LEAF) {
217                                 depth = htree_depth(dx_dir, dx_db);
218                                 if (depth != dx_dir->depth) {
219                                         pctx.num = dx_dir->depth;
220                                         code = PR_2_HTREE_BAD_DEPTH;
221                                         fix_problem(ctx, code, &pctx);
222                                         bad_dir++;
223                                 }
224                         }
225                         /*
226                          * This test doesn't apply for the root block
227                          * at block #0
228                          */
229                         if (b &&
230                             (dx_db->max_hash > dx_db->node_max_hash)) {
231                                 pctx.blk = dx_db->max_hash;
232                                 pctx.blk2 = dx_db->node_max_hash;
233                                 code = PR_2_HTREE_MAX_HASH;
234                                 fix_problem(ctx, code, &pctx);
235                                 bad_dir++;
236                         }
237                         if (!(dx_db->flags & DX_FLAG_REFERENCED)) {
238                                 code = PR_2_HTREE_NOTREF;
239                                 fix_problem(ctx, code, &pctx);
240                                 bad_dir++;
241                         } else if (dx_db->flags & DX_FLAG_DUP_REF) {
242                                 code = PR_2_HTREE_DUPREF;
243                                 fix_problem(ctx, code, &pctx);
244                                 bad_dir++;
245                         }
246                 }
247                 if (bad_dir && fix_problem(ctx, PR_2_HTREE_CLEAR, &pctx)) {
248                         clear_htree(ctx, dx_dir->ino);
249                         dx_dir->numblocks = 0;
250                 }
251         }
252         e2fsck_free_dx_dir_info(ctx);
253 #endif
254         ext2fs_free_mem(&buf);
255         ext2fs_free_dblist(fs->dblist);
256
257         if (ctx->inode_bad_map) {
258                 ext2fs_free_inode_bitmap(ctx->inode_bad_map);
259                 ctx->inode_bad_map = 0;
260         }
261         if (ctx->inode_reg_map) {
262                 ext2fs_free_inode_bitmap(ctx->inode_reg_map);
263                 ctx->inode_reg_map = 0;
264         }
265
266         clear_problem_context(&pctx);
267         if (ctx->large_files) {
268                 if (!(sb->s_feature_ro_compat &
269                       EXT2_FEATURE_RO_COMPAT_LARGE_FILE) &&
270                     fix_problem(ctx, PR_2_FEATURE_LARGE_FILES, &pctx)) {
271                         sb->s_feature_ro_compat |=
272                                 EXT2_FEATURE_RO_COMPAT_LARGE_FILE;
273                         fs->flags &= ~EXT2_FLAG_MASTER_SB_ONLY;
274                         ext2fs_mark_super_dirty(fs);
275                 }
276                 if (sb->s_rev_level == EXT2_GOOD_OLD_REV &&
277                     fix_problem(ctx, PR_1_FS_REV_LEVEL, &pctx)) {
278                         ext2fs_update_dynamic_rev(fs);
279                         ext2fs_mark_super_dirty(fs);
280                 }
281         }
282
283         print_resource_track(ctx, _("Pass 2"), &rtrack, fs->io);
284 }
285
286 #define MAX_DEPTH 32000
287 static int htree_depth(struct dx_dir_info *dx_dir,
288                        struct dx_dirblock_info *dx_db)
289 {
290         int     depth = 0;
291
292         while (dx_db->type != DX_DIRBLOCK_ROOT && depth < MAX_DEPTH) {
293                 dx_db = &dx_dir->dx_block[dx_db->parent];
294                 depth++;
295         }
296         return depth;
297 }
298
299 static int dict_de_cmp(const void *a, const void *b)
300 {
301         const struct ext2_dir_entry *de_a, *de_b;
302         int     a_len, b_len;
303
304         de_a = (const struct ext2_dir_entry *) a;
305         a_len = ext2fs_dirent_name_len(de_a);
306         de_b = (const struct ext2_dir_entry *) b;
307         b_len = ext2fs_dirent_name_len(de_b);
308
309         if (a_len != b_len)
310                 return (a_len - b_len);
311
312         return strncmp(de_a->name, de_b->name, a_len);
313 }
314
315 /*
316  * This is special sort function that makes sure that directory blocks
317  * with a dirblock of zero are sorted to the beginning of the list.
318  * This guarantees that the root node of the htree directories are
319  * processed first, so we know what hash version to use.
320  */
321 static EXT2_QSORT_TYPE special_dir_block_cmp(const void *a, const void *b)
322 {
323         const struct ext2_db_entry2 *db_a =
324                 (const struct ext2_db_entry2 *) a;
325         const struct ext2_db_entry2 *db_b =
326                 (const struct ext2_db_entry2 *) b;
327
328         if (db_a->blockcnt && !db_b->blockcnt)
329                 return 1;
330
331         if (!db_a->blockcnt && db_b->blockcnt)
332                 return -1;
333
334         if (db_a->blk != db_b->blk)
335                 return (int) (db_a->blk - db_b->blk);
336
337         if (db_a->ino != db_b->ino)
338                 return (int) (db_a->ino - db_b->ino);
339
340         return (int) (db_a->blockcnt - db_b->blockcnt);
341 }
342
343
344 /*
345  * Make sure the first entry in the directory is '.', and that the
346  * directory entry is sane.
347  */
348 static int check_dot(e2fsck_t ctx,
349                      struct ext2_dir_entry *dirent,
350                      ext2_ino_t ino, struct problem_context *pctx)
351 {
352         struct ext2_dir_entry *nextdir;
353         unsigned int    rec_len, new_len;
354         int             status = 0;
355         int             created = 0;
356         problem_t       problem = 0;
357
358         if (!dirent->inode)
359                 problem = PR_2_MISSING_DOT;
360         else if ((ext2fs_dirent_name_len(dirent) != 1) ||
361                  (dirent->name[0] != '.'))
362                 problem = PR_2_1ST_NOT_DOT;
363         else if (dirent->name[1] != '\0')
364                 problem = PR_2_DOT_NULL_TERM;
365
366         (void) ext2fs_get_rec_len(ctx->fs, dirent, &rec_len);
367         if (problem) {
368                 if (fix_problem(ctx, problem, pctx)) {
369                         if (rec_len < 12)
370                                 rec_len = dirent->rec_len = 12;
371                         dirent->inode = ino;
372                         ext2fs_dirent_set_name_len(dirent, 1);
373                         ext2fs_dirent_set_file_type(dirent, EXT2_FT_UNKNOWN);
374                         dirent->name[0] = '.';
375                         dirent->name[1] = '\0';
376                         status = 1;
377                         created = 1;
378                 }
379         }
380         if (dirent->inode != ino) {
381                 if (fix_problem(ctx, PR_2_BAD_INODE_DOT, pctx)) {
382                         dirent->inode = ino;
383                         status = 1;
384                 }
385         }
386         if (rec_len > 12) {
387                 new_len = rec_len - 12;
388                 if (new_len > 12) {
389                         if (created ||
390                             fix_problem(ctx, PR_2_SPLIT_DOT, pctx)) {
391                                 nextdir = (struct ext2_dir_entry *)
392                                         ((char *) dirent + 12);
393                                 dirent->rec_len = 12;
394                                 (void) ext2fs_set_rec_len(ctx->fs, new_len,
395                                                           nextdir);
396                                 nextdir->inode = 0;
397                                 ext2fs_dirent_set_name_len(nextdir, 0);
398                                 ext2fs_dirent_set_file_type(nextdir,
399                                                             EXT2_FT_UNKNOWN);
400                                 status = 1;
401                         }
402                 }
403         }
404         return status;
405 }
406
407 /*
408  * Make sure the second entry in the directory is '..', and that the
409  * directory entry is sane.  We do not check the inode number of '..'
410  * here; this gets done in pass 3.
411  */
412 static int check_dotdot(e2fsck_t ctx,
413                         struct ext2_dir_entry *dirent,
414                         ext2_ino_t ino, struct problem_context *pctx)
415 {
416         problem_t       problem = 0;
417         unsigned int    rec_len;
418
419         if (!dirent->inode)
420                 problem = PR_2_MISSING_DOT_DOT;
421         else if ((ext2fs_dirent_name_len(dirent) != 2) ||
422                  (dirent->name[0] != '.') ||
423                  (dirent->name[1] != '.'))
424                 problem = PR_2_2ND_NOT_DOT_DOT;
425         else if (dirent->name[2] != '\0')
426                 problem = PR_2_DOT_DOT_NULL_TERM;
427
428         (void) ext2fs_get_rec_len(ctx->fs, dirent, &rec_len);
429         if (problem) {
430                 if (fix_problem(ctx, problem, pctx)) {
431                         if (rec_len < 12)
432                                 dirent->rec_len = 12;
433                         /*
434                          * Note: we don't have the parent inode just
435                          * yet, so we will fill it in with the root
436                          * inode.  This will get fixed in pass 3.
437                          */
438                         dirent->inode = EXT2_ROOT_INO;
439                         ext2fs_dirent_set_name_len(dirent, 2);
440                         ext2fs_dirent_set_file_type(dirent, EXT2_FT_UNKNOWN);
441                         dirent->name[0] = '.';
442                         dirent->name[1] = '.';
443                         dirent->name[2] = '\0';
444                         return 1;
445                 }
446                 return 0;
447         }
448         if (e2fsck_dir_info_set_dotdot(ctx, ino, dirent->inode)) {
449                 fix_problem(ctx, PR_2_NO_DIRINFO, pctx);
450                 return -1;
451         }
452         return 0;
453 }
454
455 /*
456  * Check to make sure a directory entry doesn't contain any illegal
457  * characters.
458  */
459 static int check_name(e2fsck_t ctx,
460                       struct ext2_dir_entry *dirent,
461                       ext2_ino_t dir_ino EXT2FS_ATTR((unused)),
462                       struct problem_context *pctx)
463 {
464         int     i;
465         int     fixup = -1;
466         int     ret = 0;
467
468         for ( i = 0; i < ext2fs_dirent_name_len(dirent); i++) {
469                 if (dirent->name[i] == '/' || dirent->name[i] == '\0') {
470                         if (fixup < 0) {
471                                 fixup = fix_problem(ctx, PR_2_BAD_NAME, pctx);
472                         }
473                         if (fixup) {
474                                 dirent->name[i] = '.';
475                                 ret = 1;
476                         }
477                 }
478         }
479         return ret;
480 }
481
482 /*
483  * Check the directory filetype (if present)
484  */
485 static _INLINE_ int check_filetype(e2fsck_t ctx,
486                                    struct ext2_dir_entry *dirent,
487                                    ext2_ino_t dir_ino EXT2FS_ATTR((unused)),
488                                    struct problem_context *pctx)
489 {
490         int     filetype = ext2fs_dirent_file_type(dirent);
491         int     should_be = EXT2_FT_UNKNOWN;
492         struct ext2_inode       inode;
493
494         if (!(ctx->fs->super->s_feature_incompat &
495               EXT2_FEATURE_INCOMPAT_FILETYPE)) {
496                 if (filetype == 0 ||
497                     !fix_problem(ctx, PR_2_CLEAR_FILETYPE, pctx))
498                         return 0;
499                 ext2fs_dirent_set_file_type(dirent, EXT2_FT_UNKNOWN);
500                 return 1;
501         }
502
503         if (ext2fs_test_inode_bitmap2(ctx->inode_dir_map, dirent->inode)) {
504                 should_be = EXT2_FT_DIR;
505         } else if (ext2fs_test_inode_bitmap2(ctx->inode_reg_map,
506                                             dirent->inode)) {
507                 should_be = EXT2_FT_REG_FILE;
508         } else if (ctx->inode_bad_map &&
509                    ext2fs_test_inode_bitmap2(ctx->inode_bad_map,
510                                             dirent->inode))
511                 should_be = 0;
512         else {
513                 e2fsck_read_inode(ctx, dirent->inode, &inode,
514                                   "check_filetype");
515                 should_be = ext2_file_type(inode.i_mode);
516         }
517         if (filetype == should_be)
518                 return 0;
519         pctx->num = should_be;
520
521         if (fix_problem(ctx, filetype ? PR_2_BAD_FILETYPE : PR_2_SET_FILETYPE,
522                         pctx) == 0)
523                 return 0;
524
525         ext2fs_dirent_set_file_type(dirent, should_be);
526         return 1;
527 }
528
529 #ifdef ENABLE_HTREE
530 static void parse_int_node(ext2_filsys fs,
531                            struct ext2_db_entry2 *db,
532                            struct check_dir_struct *cd,
533                            struct dx_dir_info   *dx_dir,
534                            char *block_buf, int failed_csum)
535 {
536         struct          ext2_dx_root_info  *root;
537         struct          ext2_dx_entry *ent;
538         struct          ext2_dx_countlimit *limit;
539         struct dx_dirblock_info *dx_db;
540         int             i, expect_limit, count;
541         blk_t           blk;
542         ext2_dirhash_t  min_hash = 0xffffffff;
543         ext2_dirhash_t  max_hash = 0;
544         ext2_dirhash_t  hash = 0, prev_hash;
545         int             csum_size = 0;
546
547         if (db->blockcnt == 0) {
548                 root = (struct ext2_dx_root_info *) (block_buf + 24);
549
550 #ifdef DX_DEBUG
551                 printf("Root node dump:\n");
552                 printf("\t Reserved zero: %u\n", root->reserved_zero);
553                 printf("\t Hash Version: %d\n", root->hash_version);
554                 printf("\t Info length: %d\n", root->info_length);
555                 printf("\t Indirect levels: %d\n", root->indirect_levels);
556                 printf("\t Flags: %d\n", root->unused_flags);
557 #endif
558
559                 ent = (struct ext2_dx_entry *) (block_buf + 24 + root->info_length);
560
561                 if (failed_csum &&
562                     (e2fsck_dir_will_be_rehashed(cd->ctx, cd->pctx.ino) ||
563                      fix_problem(cd->ctx, PR_2_HTREE_ROOT_CSUM_INVALID,
564                                 &cd->pctx)))
565                         goto clear_and_exit;
566         } else {
567                 ent = (struct ext2_dx_entry *) (block_buf+8);
568
569                 if (failed_csum &&
570                     (e2fsck_dir_will_be_rehashed(cd->ctx, cd->pctx.ino) ||
571                      fix_problem(cd->ctx, PR_2_HTREE_NODE_CSUM_INVALID,
572                                 &cd->pctx)))
573                         goto clear_and_exit;
574         }
575
576         limit = (struct ext2_dx_countlimit *) ent;
577
578 #ifdef DX_DEBUG
579         printf("Number of entries (count): %d\n",
580                ext2fs_le16_to_cpu(limit->count));
581         printf("Number of entries (limit): %d\n",
582                ext2fs_le16_to_cpu(limit->limit));
583 #endif
584
585         count = ext2fs_le16_to_cpu(limit->count);
586         if (EXT2_HAS_RO_COMPAT_FEATURE(fs->super,
587                                        EXT4_FEATURE_RO_COMPAT_METADATA_CSUM))
588                 csum_size = sizeof(struct ext2_dx_tail);
589         expect_limit = (fs->blocksize -
590                         (csum_size + ((char *) ent - block_buf))) /
591                        sizeof(struct ext2_dx_entry);
592         if (ext2fs_le16_to_cpu(limit->limit) != expect_limit) {
593                 cd->pctx.num = ext2fs_le16_to_cpu(limit->limit);
594                 if (fix_problem(cd->ctx, PR_2_HTREE_BAD_LIMIT, &cd->pctx))
595                         goto clear_and_exit;
596         }
597         if (count > expect_limit) {
598                 cd->pctx.num = count;
599                 if (fix_problem(cd->ctx, PR_2_HTREE_BAD_COUNT, &cd->pctx))
600                         goto clear_and_exit;
601                 count = expect_limit;
602         }
603
604         for (i=0; i < count; i++) {
605                 prev_hash = hash;
606                 hash = i ? (ext2fs_le32_to_cpu(ent[i].hash) & ~1) : 0;
607 #ifdef DX_DEBUG
608                 printf("Entry #%d: Hash 0x%08x, block %u\n", i,
609                        hash, ext2fs_le32_to_cpu(ent[i].block));
610 #endif
611                 blk = ext2fs_le32_to_cpu(ent[i].block) & 0x0ffffff;
612                 /* Check to make sure the block is valid */
613                 if (blk >= (blk_t) dx_dir->numblocks) {
614                         cd->pctx.blk = blk;
615                         if (fix_problem(cd->ctx, PR_2_HTREE_BADBLK,
616                                         &cd->pctx))
617                                 goto clear_and_exit;
618                         continue;
619                 }
620                 if (hash < prev_hash &&
621                     fix_problem(cd->ctx, PR_2_HTREE_HASH_ORDER, &cd->pctx))
622                         goto clear_and_exit;
623                 dx_db = &dx_dir->dx_block[blk];
624                 if (dx_db->flags & DX_FLAG_REFERENCED) {
625                         dx_db->flags |= DX_FLAG_DUP_REF;
626                 } else {
627                         dx_db->flags |= DX_FLAG_REFERENCED;
628                         dx_db->parent = db->blockcnt;
629                 }
630                 if (hash < min_hash)
631                         min_hash = hash;
632                 if (hash > max_hash)
633                         max_hash = hash;
634                 dx_db->node_min_hash = hash;
635                 if ((i+1) < count)
636                         dx_db->node_max_hash =
637                           ext2fs_le32_to_cpu(ent[i+1].hash) & ~1;
638                 else {
639                         dx_db->node_max_hash = 0xfffffffe;
640                         dx_db->flags |= DX_FLAG_LAST;
641                 }
642                 if (i == 0)
643                         dx_db->flags |= DX_FLAG_FIRST;
644         }
645 #ifdef DX_DEBUG
646         printf("Blockcnt = %d, min hash 0x%08x, max hash 0x%08x\n",
647                db->blockcnt, min_hash, max_hash);
648 #endif
649         dx_db = &dx_dir->dx_block[db->blockcnt];
650         dx_db->min_hash = min_hash;
651         dx_db->max_hash = max_hash;
652         return;
653
654 clear_and_exit:
655         clear_htree(cd->ctx, cd->pctx.ino);
656         dx_dir->numblocks = 0;
657         e2fsck_rehash_dir_later(cd->ctx, cd->pctx.ino);
658 }
659 #endif /* ENABLE_HTREE */
660
661 /*
662  * Given a busted directory, try to salvage it somehow.
663  *
664  */
665 static void salvage_directory(ext2_filsys fs,
666                               struct ext2_dir_entry *dirent,
667                               struct ext2_dir_entry *prev,
668                               unsigned int *offset,
669                               unsigned int block_len)
670 {
671         char    *cp = (char *) dirent;
672         int left;
673         unsigned int rec_len, prev_rec_len;
674         unsigned int name_len = ext2fs_dirent_name_len(dirent);
675
676         (void) ext2fs_get_rec_len(fs, dirent, &rec_len);
677         left = block_len - *offset - rec_len;
678
679         /*
680          * Special case of directory entry of size 8: copy what's left
681          * of the directory block up to cover up the invalid hole.
682          */
683         if ((left >= 12) && (rec_len == 8)) {
684                 memmove(cp, cp+8, left);
685                 memset(cp + left, 0, 8);
686                 return;
687         }
688         /*
689          * If the directory entry overruns the end of the directory
690          * block, and the name is small enough to fit, then adjust the
691          * record length.
692          */
693         if ((left < 0) &&
694             ((int) rec_len + left > 8) &&
695             ((int) name_len + 8 <= (int) rec_len + left) &&
696             dirent->inode <= fs->super->s_inodes_count &&
697             strnlen(dirent->name, name_len) == name_len) {
698                 (void) ext2fs_set_rec_len(fs, (int) rec_len + left, dirent);
699                 return;
700         }
701         /*
702          * If the record length of the directory entry is a multiple
703          * of four, and not too big, such that it is valid, let the
704          * previous directory entry absorb the invalid one.
705          */
706         if (prev && rec_len && (rec_len % 4) == 0 &&
707             (*offset + rec_len <= block_len)) {
708                 (void) ext2fs_get_rec_len(fs, prev, &prev_rec_len);
709                 prev_rec_len += rec_len;
710                 (void) ext2fs_set_rec_len(fs, prev_rec_len, prev);
711                 *offset += rec_len;
712                 return;
713         }
714         /*
715          * Default salvage method --- kill all of the directory
716          * entries for the rest of the block.  We will either try to
717          * absorb it into the previous directory entry, or create a
718          * new empty directory entry the rest of the directory block.
719          */
720         if (prev) {
721                 (void) ext2fs_get_rec_len(fs, prev, &prev_rec_len);
722                 prev_rec_len += block_len - *offset;
723                 (void) ext2fs_set_rec_len(fs, prev_rec_len, prev);
724                 *offset = fs->blocksize;
725         } else {
726                 rec_len = block_len - *offset;
727                 (void) ext2fs_set_rec_len(fs, rec_len, dirent);
728                 ext2fs_dirent_set_name_len(dirent, 0);
729                 ext2fs_dirent_set_file_type(dirent, EXT2_FT_UNKNOWN);
730                 dirent->inode = 0;
731         }
732 }
733
734 static int is_last_entry(ext2_filsys fs, int inline_data_size,
735                          unsigned int offset, int csum_size)
736 {
737         if (inline_data_size)
738                 return (offset < inline_data_size);
739         else
740                 return (offset < fs->blocksize - csum_size);
741 }
742
743 #define NEXT_DIRENT(d)  ((void *)((char *)(d) + (d)->rec_len))
744 static errcode_t insert_dirent_tail(ext2_filsys fs, void *dirbuf)
745 {
746         struct ext2_dir_entry *d;
747         void *top;
748         struct ext2_dir_entry_tail *t;
749         unsigned int rec_len;
750
751         d = dirbuf;
752         top = EXT2_DIRENT_TAIL(dirbuf, fs->blocksize);
753
754         while (d->rec_len && !(d->rec_len & 0x3) && NEXT_DIRENT(d) <= top)
755                 d = NEXT_DIRENT(d);
756
757         if (d != top) {
758                 size_t min_size = EXT2_DIR_REC_LEN(
759                                 ext2fs_dirent_name_len(dirbuf));
760                 if (min_size > top - (void *)d)
761                         return EXT2_ET_DIR_NO_SPACE_FOR_CSUM;
762                 d->rec_len = top - (void *)d;
763         }
764
765         t = (struct ext2_dir_entry_tail *)top;
766         if (t->det_reserved_zero1 ||
767             t->det_rec_len != sizeof(struct ext2_dir_entry_tail) ||
768             t->det_reserved_name_len != EXT2_DIR_NAME_LEN_CSUM)
769                 ext2fs_initialize_dirent_tail(fs, t);
770
771         return 0;
772 }
773 #undef NEXT_DIRENT
774
775 static int check_dir_block(ext2_filsys fs,
776                            struct ext2_db_entry2 *db,
777                            void *priv_data)
778 {
779         struct dx_dir_info      *dx_dir;
780 #ifdef ENABLE_HTREE
781         struct dx_dirblock_info *dx_db = 0;
782 #endif /* ENABLE_HTREE */
783         struct ext2_dir_entry   *dirent, *prev, dot, dotdot;
784         ext2_dirhash_t          hash;
785         unsigned int            offset = 0;
786         int                     dir_modified = 0;
787         int                     dot_state;
788         unsigned int            rec_len;
789         blk64_t                 block_nr = db->blk;
790         ext2_ino_t              ino = db->ino;
791         ext2_ino_t              subdir_parent;
792         __u16                   links;
793         struct check_dir_struct *cd;
794         char                    *buf;
795         e2fsck_t                ctx;
796         problem_t               problem;
797         struct ext2_dx_root_info *root;
798         struct ext2_dx_countlimit *limit;
799         static dict_t de_dict;
800         struct problem_context  pctx;
801         int     dups_found = 0;
802         int     ret;
803         int     dx_csum_size = 0, de_csum_size = 0;
804         int     failed_csum = 0;
805         int     is_leaf = 1;
806         size_t  inline_data_size = 0;
807         int     filetype = 0;
808
809         cd = (struct check_dir_struct *) priv_data;
810         buf = cd->buf;
811         ctx = cd->ctx;
812
813         if (ctx->flags & E2F_FLAG_SIGNAL_MASK || ctx->flags & E2F_FLAG_RESTART)
814                 return DIRENT_ABORT;
815
816         if (ctx->progress && (ctx->progress)(ctx, 2, cd->count++, cd->max))
817                 return DIRENT_ABORT;
818
819         if (EXT2_HAS_RO_COMPAT_FEATURE(fs->super,
820                                        EXT4_FEATURE_RO_COMPAT_METADATA_CSUM)) {
821                 dx_csum_size = sizeof(struct ext2_dx_tail);
822                 de_csum_size = sizeof(struct ext2_dir_entry_tail);
823         }
824
825         if (EXT2_HAS_INCOMPAT_FEATURE(fs->super,
826                                       EXT2_FEATURE_INCOMPAT_FILETYPE))
827                 filetype = EXT2_FT_DIR << 8;
828
829         /*
830          * Make sure the inode is still in use (could have been
831          * deleted in the duplicate/bad blocks pass.
832          */
833         if (!(ext2fs_test_inode_bitmap2(ctx->inode_used_map, ino)))
834                 return 0;
835
836         cd->pctx.ino = ino;
837         cd->pctx.blk = block_nr;
838         cd->pctx.blkcount = db->blockcnt;
839         cd->pctx.ino2 = 0;
840         cd->pctx.dirent = 0;
841         cd->pctx.num = 0;
842
843         if (EXT2_HAS_INCOMPAT_FEATURE(fs->super,
844                                       EXT4_FEATURE_INCOMPAT_INLINE_DATA)) {
845                 errcode_t ec;
846
847                 ec = ext2fs_inline_data_size(fs, ino, &inline_data_size);
848                 if (ec && ec != EXT2_ET_NO_INLINE_DATA)
849                         return DIRENT_ABORT;
850         }
851
852         if (db->blk == 0 && !inline_data_size) {
853                 if (allocate_dir_block(ctx, db, buf, &cd->pctx))
854                         return 0;
855                 block_nr = db->blk;
856         }
857
858         if (db->blockcnt)
859                 dot_state = 2;
860         else
861                 dot_state = 0;
862
863         if (ctx->dirs_to_hash &&
864             ext2fs_u32_list_test(ctx->dirs_to_hash, ino))
865                 dups_found++;
866
867 #if 0
868         printf("In process_dir_block block %lu, #%d, inode %lu\n", block_nr,
869                db->blockcnt, ino);
870 #endif
871
872         ehandler_operation(_("reading directory block"));
873         if (inline_data_size) {
874                 cd->pctx.errcode = ext2fs_inline_data_get(fs, ino, 0, buf, 0);
875                 if (cd->pctx.errcode)
876                         goto inline_read_fail;
877 #ifdef WORDS_BIGENDIAN
878                 *((__u32 *)buf) = ext2fs_le32_to_cpu(*((__u32 *)buf));
879                 cd->pctx.errcode = ext2fs_dirent_swab_in2(fs,
880                                 buf + EXT4_INLINE_DATA_DOTDOT_SIZE,
881                                 inline_data_size - EXT4_INLINE_DATA_DOTDOT_SIZE,
882                                 0);
883 #endif
884         } else
885                 cd->pctx.errcode = ext2fs_read_dir_block4(fs, block_nr,
886                                                           buf, 0, ino);
887 inline_read_fail:
888         ehandler_operation(0);
889         if (cd->pctx.errcode == EXT2_ET_DIR_CORRUPTED)
890                 cd->pctx.errcode = 0; /* We'll handle this ourselves */
891         else if (cd->pctx.errcode == EXT2_ET_DIR_CSUM_INVALID) {
892                 cd->pctx.errcode = 0; /* We'll handle this ourselves */
893                 failed_csum = 1;
894         }
895         if (cd->pctx.errcode) {
896                 char *buf2;
897                 if (!fix_problem(ctx, PR_2_READ_DIRBLOCK, &cd->pctx)) {
898                         ctx->flags |= E2F_FLAG_ABORT;
899                         return DIRENT_ABORT;
900                 }
901                 ext2fs_new_dir_block(fs, db->blockcnt == 0 ? ino : 0,
902                                      EXT2_ROOT_INO, &buf2);
903                 memcpy(buf, buf2, fs->blocksize);
904                 ext2fs_free_mem(&buf2);
905         }
906 #ifdef ENABLE_HTREE
907         dx_dir = e2fsck_get_dx_dir_info(ctx, ino);
908         if (dx_dir && dx_dir->numblocks) {
909                 if (db->blockcnt >= dx_dir->numblocks) {
910                         if (fix_problem(ctx, PR_2_UNEXPECTED_HTREE_BLOCK,
911                                         &pctx)) {
912                                 clear_htree(ctx, ino);
913                                 dx_dir->numblocks = 0;
914                                 dx_db = 0;
915                                 goto out_htree;
916                         }
917                         fatal_error(ctx, _("Can not continue."));
918                 }
919                 dx_db = &dx_dir->dx_block[db->blockcnt];
920                 dx_db->type = DX_DIRBLOCK_LEAF;
921                 dx_db->phys = block_nr;
922                 dx_db->min_hash = ~0;
923                 dx_db->max_hash = 0;
924
925                 dirent = (struct ext2_dir_entry *) buf;
926                 (void) ext2fs_get_rec_len(fs, dirent, &rec_len);
927                 limit = (struct ext2_dx_countlimit *) (buf+8);
928                 if (db->blockcnt == 0) {
929                         root = (struct ext2_dx_root_info *) (buf + 24);
930                         dx_db->type = DX_DIRBLOCK_ROOT;
931                         dx_db->flags |= DX_FLAG_FIRST | DX_FLAG_LAST;
932                         if ((root->reserved_zero ||
933                              root->info_length < 8 ||
934                              root->indirect_levels > 1) &&
935                             fix_problem(ctx, PR_2_HTREE_BAD_ROOT, &cd->pctx)) {
936                                 clear_htree(ctx, ino);
937                                 dx_dir->numblocks = 0;
938                                 dx_db = 0;
939                         }
940                         dx_dir->hashversion = root->hash_version;
941                         if ((dx_dir->hashversion <= EXT2_HASH_TEA) &&
942                             (fs->super->s_flags & EXT2_FLAGS_UNSIGNED_HASH))
943                                 dx_dir->hashversion += 3;
944                         dx_dir->depth = root->indirect_levels + 1;
945                 } else if ((dirent->inode == 0) &&
946                            (rec_len == fs->blocksize) &&
947                            (ext2fs_dirent_name_len(dirent) == 0) &&
948                            (ext2fs_le16_to_cpu(limit->limit) ==
949                             ((fs->blocksize - (8 + dx_csum_size)) /
950                              sizeof(struct ext2_dx_entry))))
951                         dx_db->type = DX_DIRBLOCK_NODE;
952                 is_leaf = 0;
953         }
954 out_htree:
955 #endif /* ENABLE_HTREE */
956
957         /* Leaf node with no space for csum?  Rebuild dirs in pass 3A. */
958         if (is_leaf && !inline_data_size && failed_csum &&
959             !ext2fs_dirent_has_tail(fs, (struct ext2_dir_entry *)buf)) {
960                 de_csum_size = 0;
961                 if (e2fsck_dir_will_be_rehashed(ctx, ino) ||
962                     !fix_problem(cd->ctx, PR_2_LEAF_NODE_MISSING_CSUM,
963                                  &cd->pctx))
964                         goto skip_checksum;
965                 e2fsck_rehash_dir_later(ctx, ino);
966                 goto skip_checksum;
967         }
968         /* htree nodes don't use fake dirents to store checksums */
969         if (!is_leaf)
970                 de_csum_size = 0;
971
972 skip_checksum:
973         dict_init(&de_dict, DICTCOUNT_T_MAX, dict_de_cmp);
974         prev = 0;
975         do {
976                 dgrp_t group;
977                 ext2_ino_t first_unused_inode;
978                 unsigned int name_len;
979
980                 problem = 0;
981                 if (!inline_data_size || dot_state > 1) {
982                         size_t max_block_size = fs->blocksize - de_csum_size;
983
984                         if (inline_data_size)
985                                 max_block_size = inline_data_size;
986                         dirent = (struct ext2_dir_entry *) (buf + offset);
987                         (void) ext2fs_get_rec_len(fs, dirent, &rec_len);
988                         cd->pctx.dirent = dirent;
989                         cd->pctx.num = offset;
990                         if (((offset + rec_len) > fs->blocksize) ||
991                             (inline_data_size > 0 &&
992                              (offset + rec_len) > inline_data_size) ||
993                             (rec_len < 12) ||
994                             ((rec_len % 4) != 0) ||
995                             ((ext2fs_dirent_name_len(dirent) + 8) > rec_len)) {
996                                 if (fix_problem(ctx, PR_2_DIR_CORRUPTED,
997                                                 &cd->pctx)) {
998                                         salvage_directory(fs, dirent, prev,
999                                                           &offset,
1000                                                           max_block_size);
1001                                         dir_modified++;
1002                                         continue;
1003                                 } else
1004                                         goto abort_free_dict;
1005                         }
1006                 } else {
1007                         if (dot_state == 0) {
1008                                 memset(&dot, 0, sizeof(dot));
1009                                 dirent = &dot;
1010                                 dirent->inode = ino;
1011                                 dirent->rec_len = EXT2_DIR_REC_LEN(1);
1012                                 dirent->name_len = 1 | filetype;
1013                                 dirent->name[0] = '.';
1014                         } else if (dot_state == 1) {
1015                                 memset(&dotdot, 0, sizeof(dotdot));
1016                                 dirent = &dotdot;
1017                                 dirent->inode =
1018                                         ((struct ext2_dir_entry *)buf)->inode;
1019                                 dirent->rec_len = EXT2_DIR_REC_LEN(2);
1020                                 dirent->name_len = 2 | filetype;
1021                                 dirent->name[0] = '.';
1022                                 dirent->name[1] = '.';
1023                         } else {
1024                                 fatal_error(ctx, _("Can not continue."));
1025                         }
1026                         cd->pctx.dirent = dirent;
1027                         cd->pctx.num = offset;
1028                 }
1029
1030                 if (dot_state == 0) {
1031                         if (check_dot(ctx, dirent, ino, &cd->pctx))
1032                                 dir_modified++;
1033                 } else if (dot_state == 1) {
1034                         ret = check_dotdot(ctx, dirent, ino, &cd->pctx);
1035                         if (ret < 0)
1036                                 goto abort_free_dict;
1037                         if (ret)
1038                                 dir_modified++;
1039                 } else if (dirent->inode == ino) {
1040                         problem = PR_2_LINK_DOT;
1041                         if (fix_problem(ctx, PR_2_LINK_DOT, &cd->pctx)) {
1042                                 dirent->inode = 0;
1043                                 dir_modified++;
1044                                 goto next;
1045                         }
1046                 }
1047                 if (!dirent->inode)
1048                         goto next;
1049
1050                 /*
1051                  * Make sure the inode listed is a legal one.
1052                  */
1053                 name_len = ext2fs_dirent_name_len(dirent);
1054                 if (((dirent->inode != EXT2_ROOT_INO) &&
1055                      (dirent->inode < EXT2_FIRST_INODE(fs->super))) ||
1056                     (dirent->inode > fs->super->s_inodes_count)) {
1057                         problem = PR_2_BAD_INO;
1058                 } else if (ctx->inode_bb_map &&
1059                            (ext2fs_test_inode_bitmap2(ctx->inode_bb_map,
1060                                                      dirent->inode))) {
1061                         /*
1062                          * If the inode is in a bad block, offer to
1063                          * clear it.
1064                          */
1065                         problem = PR_2_BB_INODE;
1066                 } else if ((dot_state > 1) && (name_len == 1) &&
1067                            (dirent->name[0] == '.')) {
1068                         /*
1069                          * If there's a '.' entry in anything other
1070                          * than the first directory entry, it's a
1071                          * duplicate entry that should be removed.
1072                          */
1073                         problem = PR_2_DUP_DOT;
1074                 } else if ((dot_state > 1) && (name_len == 2) &&
1075                            (dirent->name[0] == '.') &&
1076                            (dirent->name[1] == '.')) {
1077                         /*
1078                          * If there's a '..' entry in anything other
1079                          * than the second directory entry, it's a
1080                          * duplicate entry that should be removed.
1081                          */
1082                         problem = PR_2_DUP_DOT_DOT;
1083                 } else if ((dot_state > 1) &&
1084                            (dirent->inode == EXT2_ROOT_INO)) {
1085                         /*
1086                          * Don't allow links to the root directory.
1087                          * We check this specially to make sure we
1088                          * catch this error case even if the root
1089                          * directory hasn't been created yet.
1090                          */
1091                         problem = PR_2_LINK_ROOT;
1092                 } else if ((dot_state > 1) && (name_len == 0)) {
1093                         /*
1094                          * Don't allow zero-length directory names.
1095                          */
1096                         problem = PR_2_NULL_NAME;
1097                 }
1098
1099                 if (problem) {
1100                         if (fix_problem(ctx, problem, &cd->pctx)) {
1101                                 dirent->inode = 0;
1102                                 dir_modified++;
1103                                 goto next;
1104                         } else {
1105                                 ext2fs_unmark_valid(fs);
1106                                 if (problem == PR_2_BAD_INO)
1107                                         goto next;
1108                         }
1109                 }
1110
1111                 /*
1112                  * If the inode was marked as having bad fields in
1113                  * pass1, process it and offer to fix/clear it.
1114                  * (We wait until now so that we can display the
1115                  * pathname to the user.)
1116                  */
1117                 if (ctx->inode_bad_map &&
1118                     ext2fs_test_inode_bitmap2(ctx->inode_bad_map,
1119                                              dirent->inode)) {
1120                         if (e2fsck_process_bad_inode(ctx, ino,
1121                                                      dirent->inode,
1122                                                      buf + fs->blocksize)) {
1123                                 dirent->inode = 0;
1124                                 dir_modified++;
1125                                 goto next;
1126                         }
1127                         if (ctx->flags & E2F_FLAG_SIGNAL_MASK)
1128                                 return DIRENT_ABORT;
1129                 }
1130
1131                 group = ext2fs_group_of_ino(fs, dirent->inode);
1132                 first_unused_inode = group * fs->super->s_inodes_per_group +
1133                                         1 + fs->super->s_inodes_per_group -
1134                                         ext2fs_bg_itable_unused(fs, group);
1135                 cd->pctx.group = group;
1136
1137                 /*
1138                  * Check if the inode was missed out because
1139                  * _INODE_UNINIT flag was set or bg_itable_unused was
1140                  * incorrect.  If so, clear the _INODE_UNINIT flag and
1141                  * restart e2fsck.  In the future it would be nice if
1142                  * we could call a function in pass1.c that checks the
1143                  * newly visible inodes.
1144                  */
1145                 if (ext2fs_bg_flags_test(fs, group, EXT2_BG_INODE_UNINIT)) {
1146                         pctx.num = dirent->inode;
1147                         if (fix_problem(ctx, PR_2_INOREF_BG_INO_UNINIT,
1148                                         &cd->pctx)){
1149                                 ext2fs_bg_flags_clear(fs, group,
1150                                                       EXT2_BG_INODE_UNINIT);
1151                                 ext2fs_mark_super_dirty(fs);
1152                                 ctx->flags |= E2F_FLAG_RESTART_LATER;
1153                         } else {
1154                                 ext2fs_unmark_valid(fs);
1155                                 if (problem == PR_2_BAD_INO)
1156                                         goto next;
1157                         }
1158                 } else if (dirent->inode >= first_unused_inode) {
1159                         pctx.num = dirent->inode;
1160                         if (fix_problem(ctx, PR_2_INOREF_IN_UNUSED, &cd->pctx)){
1161                                 ext2fs_bg_itable_unused_set(fs, group, 0);
1162                                 ext2fs_mark_super_dirty(fs);
1163                                 ctx->flags |= E2F_FLAG_RESTART_LATER;
1164                         } else {
1165                                 ext2fs_unmark_valid(fs);
1166                                 if (problem == PR_2_BAD_INO)
1167                                         goto next;
1168                         }
1169                 }
1170
1171                 /* 
1172                  * Offer to clear unused inodes; if we are going to be
1173                  * restarting the scan due to bg_itable_unused being
1174                  * wrong, then don't clear any inodes to avoid zapping
1175                  * inodes that were skipped during pass1 due to an
1176                  * incorrect bg_itable_unused; we'll get any real
1177                  * problems after we restart.
1178                  */
1179                 if (!(ctx->flags & E2F_FLAG_RESTART_LATER) &&
1180                     !(ext2fs_test_inode_bitmap2(ctx->inode_used_map,
1181                                                 dirent->inode)))
1182                         problem = PR_2_UNUSED_INODE;
1183
1184                 if (problem) {
1185                         if (fix_problem(ctx, problem, &cd->pctx)) {
1186                                 dirent->inode = 0;
1187                                 dir_modified++;
1188                                 goto next;
1189                         } else {
1190                                 ext2fs_unmark_valid(fs);
1191                                 if (problem == PR_2_BAD_INO)
1192                                         goto next;
1193                         }
1194                 }
1195
1196                 if (check_name(ctx, dirent, ino, &cd->pctx))
1197                         dir_modified++;
1198
1199                 if (check_filetype(ctx, dirent, ino, &cd->pctx))
1200                         dir_modified++;
1201
1202 #ifdef ENABLE_HTREE
1203                 if (dx_db) {
1204                         ext2fs_dirhash(dx_dir->hashversion, dirent->name,
1205                                        ext2fs_dirent_name_len(dirent),
1206                                        fs->super->s_hash_seed, &hash, 0);
1207                         if (hash < dx_db->min_hash)
1208                                 dx_db->min_hash = hash;
1209                         if (hash > dx_db->max_hash)
1210                                 dx_db->max_hash = hash;
1211                 }
1212 #endif
1213
1214                 /*
1215                  * If this is a directory, then mark its parent in its
1216                  * dir_info structure.  If the parent field is already
1217                  * filled in, then this directory has more than one
1218                  * hard link.  We assume the first link is correct,
1219                  * and ask the user if he/she wants to clear this one.
1220                  */
1221                 if ((dot_state > 1) &&
1222                     (ext2fs_test_inode_bitmap2(ctx->inode_dir_map,
1223                                               dirent->inode))) {
1224                         if (e2fsck_dir_info_get_parent(ctx, dirent->inode,
1225                                                        &subdir_parent)) {
1226                                 cd->pctx.ino = dirent->inode;
1227                                 fix_problem(ctx, PR_2_NO_DIRINFO, &cd->pctx);
1228                                 goto abort_free_dict;
1229                         }
1230                         if (subdir_parent) {
1231                                 cd->pctx.ino2 = subdir_parent;
1232                                 if (fix_problem(ctx, PR_2_LINK_DIR,
1233                                                 &cd->pctx)) {
1234                                         dirent->inode = 0;
1235                                         dir_modified++;
1236                                         goto next;
1237                                 }
1238                                 cd->pctx.ino2 = 0;
1239                         } else {
1240                                 (void) e2fsck_dir_info_set_parent(ctx,
1241                                                   dirent->inode, ino);
1242                         }
1243                 }
1244
1245                 if (dups_found) {
1246                         ;
1247                 } else if (dict_lookup(&de_dict, dirent)) {
1248                         clear_problem_context(&pctx);
1249                         pctx.ino = ino;
1250                         pctx.dirent = dirent;
1251                         fix_problem(ctx, PR_2_REPORT_DUP_DIRENT, &pctx);
1252                         e2fsck_rehash_dir_later(ctx, ino);
1253                         dups_found++;
1254                 } else
1255                         dict_alloc_insert(&de_dict, dirent, dirent);
1256
1257                 ext2fs_icount_increment(ctx->inode_count, dirent->inode,
1258                                         &links);
1259                 if (links > 1)
1260                         ctx->fs_links_count++;
1261                 ctx->fs_total_count++;
1262         next:
1263                 prev = dirent;
1264                 if (dir_modified)
1265                         (void) ext2fs_get_rec_len(fs, dirent, &rec_len);
1266                 if (!inline_data_size || dot_state > 1) {
1267                         offset += rec_len;
1268                 } else {
1269                         if (dot_state == 1)
1270                                 offset = 4;
1271                 }
1272                 dot_state++;
1273         } while (is_last_entry(fs, inline_data_size, offset, de_csum_size));
1274 #if 0
1275         printf("\n");
1276 #endif
1277 #ifdef ENABLE_HTREE
1278         if (dx_db) {
1279 #ifdef DX_DEBUG
1280                 printf("db_block %d, type %d, min_hash 0x%0x, max_hash 0x%0x\n",
1281                        db->blockcnt, dx_db->type,
1282                        dx_db->min_hash, dx_db->max_hash);
1283 #endif
1284                 cd->pctx.dir = cd->pctx.ino;
1285                 if ((dx_db->type == DX_DIRBLOCK_ROOT) ||
1286                     (dx_db->type == DX_DIRBLOCK_NODE))
1287                         parse_int_node(fs, db, cd, dx_dir, buf, failed_csum);
1288         }
1289 #endif /* ENABLE_HTREE */
1290
1291         if (inline_data_size) {
1292                 if (offset != inline_data_size) {
1293                         cd->pctx.num = rec_len + offset - inline_data_size;
1294                         if (fix_problem(ctx, PR_2_FINAL_RECLEN, &cd->pctx)) {
1295                                 dirent->rec_len = cd->pctx.num;
1296                                 dir_modified++;
1297                         }
1298                 }
1299         } else {
1300                 if (offset != fs->blocksize - de_csum_size) {
1301                         cd->pctx.num = rec_len - (fs->blocksize - de_csum_size) +
1302                                        offset;
1303                         if (fix_problem(ctx, PR_2_FINAL_RECLEN, &cd->pctx)) {
1304                                 dirent->rec_len = cd->pctx.num;
1305                                 dir_modified++;
1306                         }
1307                 }
1308         }
1309         if (dir_modified) {
1310                 int     flags, will_rehash;
1311                 /* leaf block with no tail?  Rehash dirs later. */
1312                 if (EXT2_HAS_RO_COMPAT_FEATURE(fs->super,
1313                                 EXT4_FEATURE_RO_COMPAT_METADATA_CSUM) &&
1314                     is_leaf &&
1315                     !inline_data_size &&
1316                     !ext2fs_dirent_has_tail(fs, (struct ext2_dir_entry *)buf)) {
1317                         if (insert_dirent_tail(fs, buf) == 0)
1318                                 goto write_and_fix;
1319                         e2fsck_rehash_dir_later(ctx, ino);
1320                 }
1321
1322 write_and_fix:
1323                 will_rehash = e2fsck_dir_will_be_rehashed(ctx, ino);
1324                 if (will_rehash) {
1325                         flags = ctx->fs->flags;
1326                         ctx->fs->flags |= EXT2_FLAG_IGNORE_CSUM_ERRORS;
1327                 }
1328                 if (inline_data_size) {
1329 #ifdef WORDS_BIGENDIAN
1330                         *((__u32 *)buf) = ext2fs_le32_to_cpu(*((__u32 *)buf));
1331                         cd->pctx.errcode = ext2fs_dirent_swab_out2(fs,
1332                                         buf + EXT4_INLINE_DATA_DOTDOT_SIZE,
1333                                         inline_data_size -
1334                                         EXT4_INLINE_DATA_DOTDOT_SIZE,
1335                                         0);
1336                         if (cd->pctx.errcode &&
1337                             !fix_problem(ctx, PR_2_WRITE_DIRBLOCK, &cd->pctx))
1338                                 goto abort_free_dict;
1339 #endif
1340                         cd->pctx.errcode =
1341                                 ext2fs_inline_data_set(fs, ino, 0, buf,
1342                                                        inline_data_size);
1343                 } else
1344                         cd->pctx.errcode = ext2fs_write_dir_block4(fs, block_nr,
1345                                                                    buf, 0, ino);
1346                 if (will_rehash)
1347                         ctx->fs->flags = (flags &
1348                                           EXT2_FLAG_IGNORE_CSUM_ERRORS) |
1349                                          (ctx->fs->flags &
1350                                           ~EXT2_FLAG_IGNORE_CSUM_ERRORS);
1351                 if (cd->pctx.errcode) {
1352                         if (!fix_problem(ctx, PR_2_WRITE_DIRBLOCK,
1353                                          &cd->pctx))
1354                                 goto abort_free_dict;
1355                 }
1356                 ext2fs_mark_changed(fs);
1357         } else if (is_leaf && failed_csum && !dir_modified) {
1358                 /*
1359                  * If a leaf node that fails csum makes it this far without
1360                  * alteration, ask the user if the checksum should be fixed.
1361                  */
1362                 if (fix_problem(ctx, PR_2_LEAF_NODE_ONLY_CSUM_INVALID,
1363                                 &cd->pctx))
1364                         goto write_and_fix;
1365         }
1366         dict_free_nodes(&de_dict);
1367         return 0;
1368 abort_free_dict:
1369         ctx->flags |= E2F_FLAG_ABORT;
1370         dict_free_nodes(&de_dict);
1371         return DIRENT_ABORT;
1372 }
1373
1374 struct del_block {
1375         e2fsck_t        ctx;
1376         e2_blkcnt_t     num;
1377 };
1378
1379 /*
1380  * This function is called to deallocate a block, and is an interator
1381  * functioned called by deallocate inode via ext2fs_iterate_block().
1382  */
1383 static int deallocate_inode_block(ext2_filsys fs,
1384                                   blk64_t       *block_nr,
1385                                   e2_blkcnt_t blockcnt EXT2FS_ATTR((unused)),
1386                                   blk64_t ref_block EXT2FS_ATTR((unused)),
1387                                   int ref_offset EXT2FS_ATTR((unused)),
1388                                   void *priv_data)
1389 {
1390         struct del_block *p = priv_data;
1391
1392         if (HOLE_BLKADDR(*block_nr))
1393                 return 0;
1394         if ((*block_nr < fs->super->s_first_data_block) ||
1395             (*block_nr >= ext2fs_blocks_count(fs->super)))
1396                 return 0;
1397         if ((*block_nr % EXT2FS_CLUSTER_RATIO(fs)) == 0)
1398                 ext2fs_block_alloc_stats2(fs, *block_nr, -1);
1399         p->num++;
1400         return 0;
1401 }
1402
1403 /*
1404  * This fuction deallocates an inode
1405  */
1406 static void deallocate_inode(e2fsck_t ctx, ext2_ino_t ino, char* block_buf)
1407 {
1408         ext2_filsys fs = ctx->fs;
1409         struct ext2_inode       inode;
1410         struct problem_context  pctx;
1411         __u32                   count;
1412         struct del_block        del_block;
1413
1414         e2fsck_read_inode(ctx, ino, &inode, "deallocate_inode");
1415         clear_problem_context(&pctx);
1416         pctx.ino = ino;
1417
1418         /*
1419          * Fix up the bitmaps...
1420          */
1421         e2fsck_read_bitmaps(ctx);
1422         ext2fs_inode_alloc_stats2(fs, ino, -1, LINUX_S_ISDIR(inode.i_mode));
1423
1424         if (ext2fs_file_acl_block(fs, &inode) &&
1425             (fs->super->s_feature_compat & EXT2_FEATURE_COMPAT_EXT_ATTR)) {
1426                 pctx.errcode = ext2fs_adjust_ea_refcount3(fs,
1427                                 ext2fs_file_acl_block(fs, &inode),
1428                                 block_buf, -1, &count, ino);
1429                 if (pctx.errcode == EXT2_ET_BAD_EA_BLOCK_NUM) {
1430                         pctx.errcode = 0;
1431                         count = 1;
1432                 }
1433                 if (pctx.errcode) {
1434                         pctx.blk = ext2fs_file_acl_block(fs, &inode);
1435                         fix_problem(ctx, PR_2_ADJ_EA_REFCOUNT, &pctx);
1436                         ctx->flags |= E2F_FLAG_ABORT;
1437                         return;
1438                 }
1439                 if (count == 0) {
1440                         ext2fs_block_alloc_stats2(fs,
1441                                   ext2fs_file_acl_block(fs, &inode), -1);
1442                 }
1443                 ext2fs_file_acl_block_set(fs, &inode, 0);
1444         }
1445
1446         if (!ext2fs_inode_has_valid_blocks2(fs, &inode))
1447                 goto clear_inode;
1448
1449         /* Inline data inodes don't have blocks to iterate */
1450         if (inode.i_flags & EXT4_INLINE_DATA_FL)
1451                 goto clear_inode;
1452
1453         if (LINUX_S_ISREG(inode.i_mode) &&
1454             ext2fs_needs_large_file_feature(EXT2_I_SIZE(&inode)))
1455                 ctx->large_files--;
1456
1457         del_block.ctx = ctx;
1458         del_block.num = 0;
1459         pctx.errcode = ext2fs_block_iterate3(fs, ino, 0, block_buf,
1460                                              deallocate_inode_block,
1461                                              &del_block);
1462         if (pctx.errcode) {
1463                 fix_problem(ctx, PR_2_DEALLOC_INODE, &pctx);
1464                 ctx->flags |= E2F_FLAG_ABORT;
1465                 return;
1466         }
1467 clear_inode:
1468         /* Inode may have changed by block_iterate, so reread it */
1469         e2fsck_read_inode(ctx, ino, &inode, "deallocate_inode");
1470         e2fsck_clear_inode(ctx, ino, &inode, 0, "deallocate_inode");
1471 }
1472
1473 /*
1474  * This fuction clears the htree flag on an inode
1475  */
1476 static void clear_htree(e2fsck_t ctx, ext2_ino_t ino)
1477 {
1478         struct ext2_inode       inode;
1479
1480         e2fsck_read_inode(ctx, ino, &inode, "clear_htree");
1481         inode.i_flags = inode.i_flags & ~EXT2_INDEX_FL;
1482         e2fsck_write_inode(ctx, ino, &inode, "clear_htree");
1483         if (ctx->dirs_to_hash)
1484                 ext2fs_u32_list_add(ctx->dirs_to_hash, ino);
1485 }
1486
1487
1488 int e2fsck_process_bad_inode(e2fsck_t ctx, ext2_ino_t dir,
1489                              ext2_ino_t ino, char *buf)
1490 {
1491         ext2_filsys fs = ctx->fs;
1492         struct ext2_inode       inode;
1493         int                     inode_modified = 0;
1494         int                     not_fixed = 0;
1495         unsigned char           *frag, *fsize;
1496         struct problem_context  pctx;
1497         problem_t               problem = 0;
1498
1499         e2fsck_read_inode(ctx, ino, &inode, "process_bad_inode");
1500
1501         clear_problem_context(&pctx);
1502         pctx.ino = ino;
1503         pctx.dir = dir;
1504         pctx.inode = &inode;
1505
1506         if (ext2fs_file_acl_block(fs, &inode) &&
1507             !(fs->super->s_feature_compat & EXT2_FEATURE_COMPAT_EXT_ATTR)) {
1508                 if (fix_problem(ctx, PR_2_FILE_ACL_ZERO, &pctx)) {
1509                         ext2fs_file_acl_block_set(fs, &inode, 0);
1510                         inode_modified++;
1511                 } else
1512                         not_fixed++;
1513         }
1514
1515         if (!LINUX_S_ISDIR(inode.i_mode) && !LINUX_S_ISREG(inode.i_mode) &&
1516             !LINUX_S_ISCHR(inode.i_mode) && !LINUX_S_ISBLK(inode.i_mode) &&
1517             !LINUX_S_ISLNK(inode.i_mode) && !LINUX_S_ISFIFO(inode.i_mode) &&
1518             !(LINUX_S_ISSOCK(inode.i_mode)))
1519                 problem = PR_2_BAD_MODE;
1520         else if (LINUX_S_ISCHR(inode.i_mode)
1521                  && !e2fsck_pass1_check_device_inode(fs, &inode))
1522                 problem = PR_2_BAD_CHAR_DEV;
1523         else if (LINUX_S_ISBLK(inode.i_mode)
1524                  && !e2fsck_pass1_check_device_inode(fs, &inode))
1525                 problem = PR_2_BAD_BLOCK_DEV;
1526         else if (LINUX_S_ISFIFO(inode.i_mode)
1527                  && !e2fsck_pass1_check_device_inode(fs, &inode))
1528                 problem = PR_2_BAD_FIFO;
1529         else if (LINUX_S_ISSOCK(inode.i_mode)
1530                  && !e2fsck_pass1_check_device_inode(fs, &inode))
1531                 problem = PR_2_BAD_SOCKET;
1532         else if (LINUX_S_ISLNK(inode.i_mode)
1533                  && !e2fsck_pass1_check_symlink(fs, ino, &inode, buf)) {
1534                 problem = PR_2_INVALID_SYMLINK;
1535         }
1536
1537         if (problem) {
1538                 if (fix_problem(ctx, problem, &pctx)) {
1539                         deallocate_inode(ctx, ino, 0);
1540                         if (ctx->flags & E2F_FLAG_SIGNAL_MASK)
1541                                 return 0;
1542                         return 1;
1543                 } else
1544                         not_fixed++;
1545                 problem = 0;
1546         }
1547
1548         if (inode.i_faddr) {
1549                 if (fix_problem(ctx, PR_2_FADDR_ZERO, &pctx)) {
1550                         inode.i_faddr = 0;
1551                         inode_modified++;
1552                 } else
1553                         not_fixed++;
1554         }
1555
1556         switch (fs->super->s_creator_os) {
1557             case EXT2_OS_HURD:
1558                 frag = &inode.osd2.hurd2.h_i_frag;
1559                 fsize = &inode.osd2.hurd2.h_i_fsize;
1560                 break;
1561             default:
1562                 frag = fsize = 0;
1563         }
1564         if (frag && *frag) {
1565                 pctx.num = *frag;
1566                 if (fix_problem(ctx, PR_2_FRAG_ZERO, &pctx)) {
1567                         *frag = 0;
1568                         inode_modified++;
1569                 } else
1570                         not_fixed++;
1571                 pctx.num = 0;
1572         }
1573         if (fsize && *fsize) {
1574                 pctx.num = *fsize;
1575                 if (fix_problem(ctx, PR_2_FSIZE_ZERO, &pctx)) {
1576                         *fsize = 0;
1577                         inode_modified++;
1578                 } else
1579                         not_fixed++;
1580                 pctx.num = 0;
1581         }
1582
1583         if ((fs->super->s_creator_os == EXT2_OS_LINUX) &&
1584             !(fs->super->s_feature_ro_compat &
1585               EXT4_FEATURE_RO_COMPAT_HUGE_FILE) &&
1586             (inode.osd2.linux2.l_i_blocks_hi != 0)) {
1587                 pctx.num = inode.osd2.linux2.l_i_blocks_hi;
1588                 if (fix_problem(ctx, PR_2_BLOCKS_HI_ZERO, &pctx)) {
1589                         inode.osd2.linux2.l_i_blocks_hi = 0;
1590                         inode_modified++;
1591                 }
1592         }
1593
1594         if (!(fs->super->s_feature_incompat & 
1595              EXT4_FEATURE_INCOMPAT_64BIT) &&
1596             inode.osd2.linux2.l_i_file_acl_high != 0) {
1597                 pctx.num = inode.osd2.linux2.l_i_file_acl_high;
1598                 if (fix_problem(ctx, PR_2_I_FILE_ACL_HI_ZERO, &pctx)) {
1599                         inode.osd2.linux2.l_i_file_acl_high = 0;
1600                         inode_modified++;
1601                 } else
1602                         not_fixed++;
1603         }
1604
1605         if (ext2fs_file_acl_block(fs, &inode) &&
1606             ((ext2fs_file_acl_block(fs, &inode) < fs->super->s_first_data_block) ||
1607              (ext2fs_file_acl_block(fs, &inode) >= ext2fs_blocks_count(fs->super)))) {
1608                 if (fix_problem(ctx, PR_2_FILE_ACL_BAD, &pctx)) {
1609                         ext2fs_file_acl_block_set(fs, &inode, 0);
1610                         inode_modified++;
1611                 } else
1612                         not_fixed++;
1613         }
1614         if (inode.i_dir_acl &&
1615             LINUX_S_ISDIR(inode.i_mode)) {
1616                 if (fix_problem(ctx, PR_2_DIR_ACL_ZERO, &pctx)) {
1617                         inode.i_dir_acl = 0;
1618                         inode_modified++;
1619                 } else
1620                         not_fixed++;
1621         }
1622
1623         if (inode_modified)
1624                 e2fsck_write_inode(ctx, ino, &inode, "process_bad_inode");
1625         if (!not_fixed && ctx->inode_bad_map)
1626                 ext2fs_unmark_inode_bitmap2(ctx->inode_bad_map, ino);
1627         return 0;
1628 }
1629
1630 /*
1631  * allocate_dir_block --- this function allocates a new directory
1632  *      block for a particular inode; this is done if a directory has
1633  *      a "hole" in it, or if a directory has a illegal block number
1634  *      that was zeroed out and now needs to be replaced.
1635  */
1636 static int allocate_dir_block(e2fsck_t ctx,
1637                               struct ext2_db_entry2 *db,
1638                               char *buf EXT2FS_ATTR((unused)),
1639                               struct problem_context *pctx)
1640 {
1641         ext2_filsys fs = ctx->fs;
1642         blk64_t                 blk = 0;
1643         char                    *block;
1644         struct ext2_inode       inode;
1645
1646         if (fix_problem(ctx, PR_2_DIRECTORY_HOLE, pctx) == 0)
1647                 return 1;
1648
1649         /*
1650          * Read the inode and block bitmaps in; we'll be messing with
1651          * them.
1652          */
1653         e2fsck_read_bitmaps(ctx);
1654
1655         /*
1656          * First, find a free block
1657          */
1658         e2fsck_read_inode(ctx, db->ino, &inode, "allocate_dir_block");
1659         pctx->errcode = ext2fs_map_cluster_block(fs, db->ino, &inode,
1660                                                  db->blockcnt, &blk);
1661         if (pctx->errcode || blk == 0) {
1662                 pctx->errcode = ext2fs_new_block2(fs, 0,
1663                                                   ctx->block_found_map, &blk);
1664                 if (pctx->errcode) {
1665                         pctx->str = "ext2fs_new_block";
1666                         fix_problem(ctx, PR_2_ALLOC_DIRBOCK, pctx);
1667                         return 1;
1668                 }
1669         }
1670         ext2fs_mark_block_bitmap2(ctx->block_found_map, blk);
1671         ext2fs_mark_block_bitmap2(fs->block_map, blk);
1672         ext2fs_mark_bb_dirty(fs);
1673
1674         /*
1675          * Now let's create the actual data block for the inode
1676          */
1677         if (db->blockcnt)
1678                 pctx->errcode = ext2fs_new_dir_block(fs, 0, 0, &block);
1679         else
1680                 pctx->errcode = ext2fs_new_dir_block(fs, db->ino,
1681                                                      EXT2_ROOT_INO, &block);
1682
1683         if (pctx->errcode) {
1684                 pctx->str = "ext2fs_new_dir_block";
1685                 fix_problem(ctx, PR_2_ALLOC_DIRBOCK, pctx);
1686                 return 1;
1687         }
1688
1689         pctx->errcode = ext2fs_write_dir_block4(fs, blk, block, 0, db->ino);
1690         ext2fs_free_mem(&block);
1691         if (pctx->errcode) {
1692                 pctx->str = "ext2fs_write_dir_block";
1693                 fix_problem(ctx, PR_2_ALLOC_DIRBOCK, pctx);
1694                 return 1;
1695         }
1696
1697         /*
1698          * Update the inode block count
1699          */
1700         ext2fs_iblk_add_blocks(fs, &inode, 1);
1701         if (EXT2_I_SIZE(&inode) < (db->blockcnt+1) * fs->blocksize) {
1702                 pctx->errcode = ext2fs_inode_size_set(fs, &inode,
1703                                         (db->blockcnt+1) * fs->blocksize);
1704                 if (pctx->errcode) {
1705                         pctx->str = "ext2fs_inode_size_set";
1706                         fix_problem(ctx, PR_2_ALLOC_DIRBOCK, pctx);
1707                         return 1;
1708                 }
1709         }
1710         e2fsck_write_inode(ctx, db->ino, &inode, "allocate_dir_block");
1711
1712         /*
1713          * Finally, update the block pointers for the inode
1714          */
1715         db->blk = blk;
1716         pctx->errcode = ext2fs_bmap2(fs, db->ino, &inode, 0, BMAP_SET,
1717                                      db->blockcnt, 0, &blk);
1718         if (pctx->errcode) {
1719                 pctx->str = "ext2fs_block_iterate";
1720                 fix_problem(ctx, PR_2_ALLOC_DIRBOCK, pctx);
1721                 return 1;
1722         }
1723
1724         return 0;
1725 }