Whamcloud - gitweb
e2fsck: add more checks for ea inode consistency
[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  *      - The encrypted_file_info
39  *      - The inode_casefold_map bitmap
40  *
41  * Pass 2 frees the following data structures
42  *      - The inode_bad_map bitmap
43  *      - The inode_reg_map bitmap
44  *      - The encrypted_file_info
45  *      - The inode_casefold_map bitmap
46  */
47
48 #define _GNU_SOURCE 1 /* get strnlen() */
49 #include "config.h"
50 #include <string.h>
51
52 #include "e2fsck.h"
53 #include "problem.h"
54 #include "support/dict.h"
55
56 #ifdef NO_INLINE_FUNCS
57 #define _INLINE_
58 #else
59 #define _INLINE_ inline
60 #endif
61
62 /* #define DX_DEBUG */
63
64 /*
65  * Keeps track of how many times an inode is referenced.
66  */
67 static void deallocate_inode(e2fsck_t ctx, ext2_ino_t ino, char* block_buf);
68 static int check_dir_block2(ext2_filsys fs,
69                            struct ext2_db_entry2 *dir_blocks_info,
70                            void *priv_data);
71 static int check_dir_block(ext2_filsys fs,
72                            struct ext2_db_entry2 *dir_blocks_info,
73                            void *priv_data);
74 static int allocate_dir_block(e2fsck_t ctx,
75                               struct ext2_db_entry2 *dir_blocks_info,
76                               char *buf, struct problem_context *pctx);
77 static void clear_htree(e2fsck_t ctx, ext2_ino_t ino);
78 static short htree_depth(struct dx_dir_info *dx_dir,
79                          struct dx_dirblock_info *dx_db);
80 static EXT2_QSORT_TYPE special_dir_block_cmp(const void *a, const void *b);
81
82 struct check_dir_struct {
83         char *buf;
84         struct problem_context  pctx;
85         int     count, max;
86         e2fsck_t ctx;
87         unsigned long long list_offset;
88         unsigned long long ra_entries;
89         unsigned long long next_ra_off;
90 };
91
92 static void update_parents(struct dx_dir_info *dx_dir, int type)
93 {
94         struct dx_dirblock_info *dx_db, *dx_parent, *dx_previous;
95         blk_t b;
96
97         for (b = 0, dx_db = dx_dir->dx_block;
98              b < dx_dir->numblocks;
99              b++, dx_db++) {
100                 dx_parent = &dx_dir->dx_block[dx_db->parent];
101                 if (dx_db->type != type)
102                         continue;
103
104                 /*
105                  * XXX Make sure dx_parent->min_hash > dx_db->min_hash
106                 */
107                 if (dx_db->flags & DX_FLAG_FIRST) {
108                         dx_parent->min_hash = dx_db->min_hash;
109                         if (dx_parent->previous) {
110                                 dx_previous =
111                                         &dx_dir->dx_block[dx_parent->previous];
112                                 dx_previous->node_max_hash =
113                                         dx_parent->min_hash;
114                         }
115                 }
116                 /*
117                  * XXX Make sure dx_parent->max_hash < dx_db->max_hash
118                  */
119                 if (dx_db->flags & DX_FLAG_LAST) {
120                         dx_parent->max_hash = dx_db->max_hash;
121                 }
122         }
123 }
124
125 void e2fsck_pass2(e2fsck_t ctx)
126 {
127         struct ext2_super_block *sb = ctx->fs->super;
128         struct problem_context  pctx;
129         ext2_filsys             fs = ctx->fs;
130         char                    *buf = NULL;
131 #ifdef RESOURCE_TRACK
132         struct resource_track   rtrack;
133 #endif
134         struct check_dir_struct cd;
135         struct dx_dir_info      *dx_dir;
136         struct dx_dirblock_info *dx_db;
137         blk_t                   b;
138         ext2_ino_t              i;
139         short                   depth;
140         problem_t               code;
141         int                     bad_dir;
142         int (*check_dir_func)(ext2_filsys fs,
143                               struct ext2_db_entry2 *dir_blocks_info,
144                               void *priv_data);
145
146         init_resource_track(&rtrack, ctx->fs->io);
147         clear_problem_context(&cd.pctx);
148
149 #ifdef MTRACE
150         mtrace_print("Pass 2");
151 #endif
152
153         fs->flags |= EXT2_FLAG_IGNORE_SWAP_DIRENT;
154         if (!(ctx->options & E2F_OPT_PREEN))
155                 fix_problem(ctx, PR_2_PASS_HEADER, &cd.pctx);
156
157         cd.pctx.errcode = e2fsck_setup_icount(ctx, "inode_count",
158                                 EXT2_ICOUNT_OPT_INCREMENT,
159                                 ctx->inode_link_info, &ctx->inode_count);
160         if (cd.pctx.errcode) {
161                 fix_problem(ctx, PR_2_ALLOCATE_ICOUNT, &cd.pctx);
162                 ctx->flags |= E2F_FLAG_ABORT;
163                 goto cleanup;
164         }
165         buf = (char *) e2fsck_allocate_memory(ctx, 2*fs->blocksize,
166                                               "directory scan buffer");
167
168         /*
169          * Set up the parent pointer for the root directory, if
170          * present.  (If the root directory is not present, we will
171          * create it in pass 3.)
172          */
173         (void) e2fsck_dir_info_set_parent(ctx, EXT2_ROOT_INO, EXT2_ROOT_INO);
174
175         cd.buf = buf;
176         cd.ctx = ctx;
177         cd.count = 1;
178         cd.max = ext2fs_dblist_count2(fs->dblist);
179         cd.list_offset = 0;
180         cd.ra_entries = ctx->readahead_kb * 1024 / ctx->fs->blocksize;
181         cd.next_ra_off = 0;
182
183         if (ctx->progress)
184                 (void) (ctx->progress)(ctx, 2, 0, cd.max);
185
186         if (ext2fs_has_feature_dir_index(fs->super))
187                 ext2fs_dblist_sort2(fs->dblist, special_dir_block_cmp);
188
189         check_dir_func = cd.ra_entries ? check_dir_block2 : check_dir_block;
190         cd.pctx.errcode = ext2fs_dblist_iterate2(fs->dblist, check_dir_func,
191                                                  &cd);
192         if (ctx->flags & E2F_FLAG_RESTART_LATER) {
193                 ctx->flags |= E2F_FLAG_RESTART;
194                 ctx->flags &= ~E2F_FLAG_RESTART_LATER;
195         }
196
197         if (ctx->flags & E2F_FLAG_RUN_RETURN)
198                 goto cleanup;
199
200         if (cd.pctx.errcode) {
201                 fix_problem(ctx, PR_2_DBLIST_ITERATE, &cd.pctx);
202                 ctx->flags |= E2F_FLAG_ABORT;
203                 goto cleanup;
204         }
205
206         for (i=0; (dx_dir = e2fsck_dx_dir_info_iter(ctx, &i)) != 0;) {
207                 if (ctx->flags & E2F_FLAG_SIGNAL_MASK)
208                         goto cleanup;
209                 if (e2fsck_dir_will_be_rehashed(ctx, dx_dir->ino) ||
210                     dx_dir->numblocks == 0)
211                         continue;
212                 clear_problem_context(&pctx);
213                 bad_dir = 0;
214                 pctx.dir = dx_dir->ino;
215                 dx_db = dx_dir->dx_block;
216                 if (dx_db->flags & DX_FLAG_REFERENCED)
217                         dx_db->flags |= DX_FLAG_DUP_REF;
218                 else
219                         dx_db->flags |= DX_FLAG_REFERENCED;
220                 /*
221                  * Find all of the first and last leaf blocks, and
222                  * update their parent's min and max hash values
223                  */
224                 update_parents(dx_dir, DX_DIRBLOCK_LEAF);
225
226                 /* for 3 level htree: update 2 level parent's min
227                  * and max hash values */
228                 update_parents(dx_dir, DX_DIRBLOCK_NODE);
229
230                 for (b=0, dx_db = dx_dir->dx_block;
231                      b < dx_dir->numblocks;
232                      b++, dx_db++) {
233                         pctx.blkcount = b;
234                         pctx.group = dx_db->parent;
235                         code = 0;
236                         if (!(dx_db->flags & DX_FLAG_FIRST) &&
237                             (dx_db->min_hash < dx_db->node_min_hash)) {
238                                 pctx.blk = dx_db->min_hash;
239                                 pctx.blk2 = dx_db->node_min_hash;
240                                 code = PR_2_HTREE_MIN_HASH;
241                                 fix_problem(ctx, code, &pctx);
242                                 bad_dir++;
243                         }
244                         if (dx_db->type == DX_DIRBLOCK_LEAF) {
245                                 depth = htree_depth(dx_dir, dx_db);
246                                 if (depth != dx_dir->depth) {
247                                         pctx.num = dx_dir->depth;
248                                         code = PR_2_HTREE_BAD_DEPTH;
249                                         fix_problem(ctx, code, &pctx);
250                                         bad_dir++;
251                                 }
252                         }
253                         /*
254                          * This test doesn't apply for the root block
255                          * at block #0
256                          */
257                         if (b &&
258                             (dx_db->max_hash > dx_db->node_max_hash)) {
259                                 pctx.blk = dx_db->max_hash;
260                                 pctx.blk2 = dx_db->node_max_hash;
261                                 code = PR_2_HTREE_MAX_HASH;
262                                 fix_problem(ctx, code, &pctx);
263                                 bad_dir++;
264                         }
265                         if (!(dx_db->flags & DX_FLAG_REFERENCED)) {
266                                 code = PR_2_HTREE_NOTREF;
267                                 fix_problem(ctx, code, &pctx);
268                                 bad_dir++;
269                         } else if (dx_db->flags & DX_FLAG_DUP_REF) {
270                                 code = PR_2_HTREE_DUPREF;
271                                 fix_problem(ctx, code, &pctx);
272                                 bad_dir++;
273                         }
274                 }
275                 if (bad_dir && fix_problem(ctx, PR_2_HTREE_CLEAR, &pctx)) {
276                         clear_htree(ctx, dx_dir->ino);
277                         dx_dir->numblocks = 0;
278                 }
279         }
280         e2fsck_free_dx_dir_info(ctx);
281
282         ext2fs_free_mem(&buf);
283         ext2fs_free_dblist(fs->dblist);
284
285         if (ctx->inode_bad_map) {
286                 ext2fs_free_inode_bitmap(ctx->inode_bad_map);
287                 ctx->inode_bad_map = 0;
288         }
289         if (ctx->inode_reg_map) {
290                 ext2fs_free_inode_bitmap(ctx->inode_reg_map);
291                 ctx->inode_reg_map = 0;
292         }
293         if (ctx->inode_casefold_map) {
294                 ext2fs_free_inode_bitmap(ctx->inode_casefold_map);
295                 ctx->inode_casefold_map = 0;
296         }
297         destroy_encrypted_file_info(ctx);
298         if (ctx->casefolded_dirs) {
299                 ext2fs_u32_list_free(ctx->casefolded_dirs);
300                 ctx->casefolded_dirs = 0;
301         }
302
303         clear_problem_context(&pctx);
304         if (ctx->large_files) {
305                 if (!ext2fs_has_feature_large_file(sb) &&
306                     fix_problem(ctx, PR_2_FEATURE_LARGE_FILES, &pctx)) {
307                         ext2fs_set_feature_large_file(sb);
308                         fs->flags &= ~EXT2_FLAG_MASTER_SB_ONLY;
309                         ext2fs_mark_super_dirty(fs);
310                 }
311                 if (sb->s_rev_level == EXT2_GOOD_OLD_REV &&
312                     fix_problem(ctx, PR_1_FS_REV_LEVEL, &pctx)) {
313                         ext2fs_update_dynamic_rev(fs);
314                         ext2fs_mark_super_dirty(fs);
315                 }
316         }
317
318         print_resource_track(ctx, _("Pass 2"), &rtrack, fs->io);
319 cleanup:
320         ext2fs_free_mem(&buf);
321         fs->flags &= ~EXT2_FLAG_IGNORE_SWAP_DIRENT;
322 }
323
324 #define MAX_DEPTH 32000
325 static short htree_depth(struct dx_dir_info *dx_dir,
326                          struct dx_dirblock_info *dx_db)
327 {
328         short depth = 0;
329
330         while (dx_db->type != DX_DIRBLOCK_ROOT && depth < MAX_DEPTH) {
331                 dx_db = &dx_dir->dx_block[dx_db->parent];
332                 depth++;
333         }
334         return depth;
335 }
336
337 static int dict_de_cmp(const void *cmp_ctx EXT2FS_ATTR((unused)),
338                        const void *a, const void *b)
339 {
340         const struct ext2_dir_entry *de_a, *de_b;
341         int     a_len, b_len;
342
343         de_a = (const struct ext2_dir_entry *) a;
344         a_len = ext2fs_dirent_name_len(de_a);
345         de_b = (const struct ext2_dir_entry *) b;
346         b_len = ext2fs_dirent_name_len(de_b);
347
348         if (a_len != b_len)
349                 return (a_len - b_len);
350
351         return memcmp(de_a->name, de_b->name, a_len);
352 }
353
354 static int dict_de_cf_cmp(const void *cmp_ctx, const void *a, const void *b)
355 {
356         const struct ext2fs_nls_table *tbl = cmp_ctx;
357         const struct ext2_dir_entry *de_a, *de_b;
358         int     a_len, b_len;
359
360         de_a = (const struct ext2_dir_entry *) a;
361         a_len = ext2fs_dirent_name_len(de_a);
362         de_b = (const struct ext2_dir_entry *) b;
363         b_len = ext2fs_dirent_name_len(de_b);
364
365         return ext2fs_casefold_cmp(tbl,
366                                    (const unsigned char *) de_a->name, a_len,
367                                    (const unsigned char *) de_b->name, b_len);
368 }
369
370 /*
371  * This is special sort function that makes sure that directory blocks
372  * with a dirblock of zero are sorted to the beginning of the list.
373  * This guarantees that the root node of the htree directories are
374  * processed first, so we know what hash version to use.
375  */
376 static EXT2_QSORT_TYPE special_dir_block_cmp(const void *a, const void *b)
377 {
378         const struct ext2_db_entry2 *db_a =
379                 (const struct ext2_db_entry2 *) a;
380         const struct ext2_db_entry2 *db_b =
381                 (const struct ext2_db_entry2 *) b;
382
383         if (db_a->blockcnt && !db_b->blockcnt)
384                 return 1;
385
386         if (!db_a->blockcnt && db_b->blockcnt)
387                 return -1;
388
389         if (db_a->blk != db_b->blk)
390                 return (int) (db_a->blk - db_b->blk);
391
392         if (db_a->ino != db_b->ino)
393                 return (int) (db_a->ino - db_b->ino);
394
395         return (int) (db_a->blockcnt - db_b->blockcnt);
396 }
397
398
399 /*
400  * Make sure the first entry in the directory is '.', and that the
401  * directory entry is sane.
402  */
403 static int check_dot(e2fsck_t ctx,
404                      struct ext2_dir_entry *dirent,
405                      ext2_ino_t ino, struct problem_context *pctx)
406 {
407         struct ext2_dir_entry *nextdir;
408         unsigned int    rec_len, new_len;
409         int             status = 0;
410         int             created = 0;
411         problem_t       problem = 0;
412         int             ftype = EXT2_FT_DIR;
413
414         if (!dirent->inode)
415                 problem = PR_2_MISSING_DOT;
416         else if ((ext2fs_dirent_name_len(dirent) != 1) ||
417                  (dirent->name[0] != '.'))
418                 problem = PR_2_1ST_NOT_DOT;
419         else if (dirent->name[1] != '\0')
420                 problem = PR_2_DOT_NULL_TERM;
421
422         (void) ext2fs_get_rec_len(ctx->fs, dirent, &rec_len);
423         if (problem) {
424                 if (!ext2fs_has_feature_filetype(ctx->fs->super))
425                         ftype = EXT2_FT_UNKNOWN;
426                 if (fix_problem(ctx, problem, pctx)) {
427                         if (rec_len < 12)
428                                 rec_len = dirent->rec_len = 12;
429                         dirent->inode = ino;
430                         ext2fs_dirent_set_name_len(dirent, 1);
431                         ext2fs_dirent_set_file_type(dirent, ftype);
432                         dirent->name[0] = '.';
433                         dirent->name[1] = '\0';
434                         status = 1;
435                         created = 1;
436                 }
437         }
438         if (dirent->inode != ino) {
439                 if (fix_problem(ctx, PR_2_BAD_INODE_DOT, pctx)) {
440                         dirent->inode = ino;
441                         status = 1;
442                 }
443         }
444         if (rec_len > 12) {
445                 new_len = rec_len - 12;
446                 if (new_len > 12) {
447                         if (created ||
448                             fix_problem(ctx, PR_2_SPLIT_DOT, pctx)) {
449                                 nextdir = (struct ext2_dir_entry *)
450                                         ((char *) dirent + 12);
451                                 dirent->rec_len = 12;
452                                 /* if the next entry looks like "..", leave it
453                                  * and let check_dotdot() verify the dirent,
454                                  * otherwise zap the following entry. */
455                                 if (strncmp(nextdir->name, "..", 3) != 0) {
456                                         (void)ext2fs_set_rec_len(ctx->fs,
457                                                                  new_len,
458                                                                  nextdir);
459                                         nextdir->inode = 0;
460                                         ext2fs_dirent_set_name_len(nextdir, 0);
461                                         ext2fs_dirent_set_file_type(nextdir,
462                                                                     ftype);
463 #ifdef WORDS_BIGENDIAN
464                                 } else {
465                                         (void) ext2fs_dirent_swab_in2(ctx->fs,
466                                                 (char *) nextdir,
467                                                 ctx->fs->blocksize - 12, 0);
468 #endif
469                                 }
470                                 status = 1;
471                         }
472                 }
473         }
474         return status;
475 }
476
477 /*
478  * Make sure the second entry in the directory is '..', and that the
479  * directory entry is sane.  We do not check the inode number of '..'
480  * here; this gets done in pass 3.
481  */
482 static int check_dotdot(e2fsck_t ctx,
483                         struct ext2_dir_entry *dirent,
484                         ext2_ino_t ino, struct problem_context *pctx)
485 {
486         problem_t       problem = 0;
487         unsigned int    rec_len;
488         int             ftype = EXT2_FT_DIR;
489
490         if (!dirent->inode)
491                 problem = PR_2_MISSING_DOT_DOT;
492         else if ((ext2fs_dirent_name_len(dirent) != 2) ||
493                  (dirent->name[0] != '.') ||
494                  (dirent->name[1] != '.'))
495                 problem = PR_2_2ND_NOT_DOT_DOT;
496         else if (dirent->name[2] != '\0')
497                 problem = PR_2_DOT_DOT_NULL_TERM;
498
499         (void) ext2fs_get_rec_len(ctx->fs, dirent, &rec_len);
500         if (problem) {
501                 if (!ext2fs_has_feature_filetype(ctx->fs->super))
502                         ftype = EXT2_FT_UNKNOWN;
503                 if (fix_problem(ctx, problem, pctx)) {
504                         if (rec_len < 12)
505                                 dirent->rec_len = 12;
506                         /*
507                          * Note: we don't have the parent inode just
508                          * yet, so we will fill it in with the root
509                          * inode.  This will get fixed in pass 3.
510                          */
511                         dirent->inode = EXT2_ROOT_INO;
512                         ext2fs_dirent_set_name_len(dirent, 2);
513                         ext2fs_dirent_set_file_type(dirent, ftype);
514                         dirent->name[0] = '.';
515                         dirent->name[1] = '.';
516                         dirent->name[2] = '\0';
517                         return 1;
518                 }
519                 return 0;
520         }
521         if (e2fsck_dir_info_set_dotdot(ctx, ino, dirent->inode)) {
522                 fix_problem(ctx, PR_2_NO_DIRINFO, pctx);
523                 return -1;
524         }
525         return 0;
526 }
527
528 /*
529  * Check to make sure a directory entry doesn't contain any illegal
530  * characters.
531  */
532 static int check_name(e2fsck_t ctx,
533                       struct ext2_dir_entry *dirent,
534                       struct problem_context *pctx)
535 {
536         int     i;
537         int     fixup = -1;
538         int     ret = 0;
539
540         for ( i = 0; i < ext2fs_dirent_name_len(dirent); i++) {
541                 if (dirent->name[i] != '/' && dirent->name[i] != '\0')
542                         continue;
543                 if (fixup < 0)
544                         fixup = fix_problem(ctx, PR_2_BAD_NAME, pctx);
545                 if (fixup == 0)
546                         return 0;
547                 dirent->name[i] = '.';
548                 ret = 1;
549         }
550         return ret;
551 }
552
553 static int encrypted_check_name(e2fsck_t ctx,
554                                 const struct ext2_dir_entry *dirent,
555                                 struct problem_context *pctx)
556 {
557         if (ext2fs_dirent_name_len(dirent) < EXT4_CRYPTO_BLOCK_SIZE) {
558                 if (fix_problem(ctx, PR_2_BAD_ENCRYPTED_NAME, pctx))
559                         return 1;
560                 ext2fs_unmark_valid(ctx->fs);
561         }
562         return 0;
563 }
564
565 static int encoded_check_name(e2fsck_t ctx,
566                               struct ext2_dir_entry *dirent,
567                               struct problem_context *pctx)
568 {
569         const struct ext2fs_nls_table *tbl = ctx->fs->encoding;
570         int ret;
571         int len = ext2fs_dirent_name_len(dirent);
572         char *pos, *end;
573
574         ret = ext2fs_check_encoded_name(tbl, dirent->name, len, &pos);
575         if (ret < 0) {
576                 fatal_error(ctx, _("NLS is broken."));
577         } else if(ret > 0) {
578                 ret = fix_problem(ctx, PR_2_BAD_ENCODED_NAME, pctx);
579                 if (ret) {
580                         end = &dirent->name[len];
581                         for (; *pos && pos != end; pos++)
582                                 *pos = '.';
583                 }
584         }
585
586         return (ret || check_name(ctx, dirent, pctx));
587 }
588
589 /*
590  * Check the directory filetype (if present)
591  */
592 static _INLINE_ int check_filetype(e2fsck_t ctx,
593                                    struct ext2_dir_entry *dirent,
594                                    ext2_ino_t dir_ino EXT2FS_ATTR((unused)),
595                                    struct problem_context *pctx)
596 {
597         int     filetype = ext2fs_dirent_file_type(dirent);
598         int     should_be = EXT2_FT_UNKNOWN;
599         struct ext2_inode       inode;
600
601         if (!ext2fs_has_feature_filetype(ctx->fs->super)) {
602                 if (filetype == 0 ||
603                     !fix_problem(ctx, PR_2_CLEAR_FILETYPE, pctx))
604                         return 0;
605                 ext2fs_dirent_set_file_type(dirent, EXT2_FT_UNKNOWN);
606                 return 1;
607         }
608
609         if (ext2fs_test_inode_bitmap2(ctx->inode_dir_map, dirent->inode)) {
610                 should_be = EXT2_FT_DIR;
611         } else if (ext2fs_test_inode_bitmap2(ctx->inode_reg_map,
612                                             dirent->inode)) {
613                 should_be = EXT2_FT_REG_FILE;
614         } else if (ctx->inode_bad_map &&
615                    ext2fs_test_inode_bitmap2(ctx->inode_bad_map,
616                                             dirent->inode))
617                 should_be = 0;
618         else {
619                 e2fsck_read_inode(ctx, dirent->inode, &inode,
620                                   "check_filetype");
621                 should_be = ext2_file_type(inode.i_mode);
622         }
623         if (filetype == should_be)
624                 return 0;
625         pctx->num = should_be;
626
627         if (fix_problem(ctx, filetype ? PR_2_BAD_FILETYPE : PR_2_SET_FILETYPE,
628                         pctx) == 0)
629                 return 0;
630
631         ext2fs_dirent_set_file_type(dirent, should_be);
632         return 1;
633 }
634
635 static void parse_int_node(ext2_filsys fs,
636                            struct ext2_db_entry2 *db,
637                            struct check_dir_struct *cd,
638                            struct dx_dir_info   *dx_dir,
639                            char *block_buf, int failed_csum)
640 {
641         struct          ext2_dx_root_info  *root;
642         struct          ext2_dx_entry *ent;
643         struct          ext2_dx_countlimit *limit;
644         struct dx_dirblock_info *dx_db;
645         int             i, expect_limit, count;
646         blk_t           blk;
647         ext2_dirhash_t  min_hash = 0xffffffff;
648         ext2_dirhash_t  max_hash = 0;
649         ext2_dirhash_t  hash = 0, prev_hash;
650         int             csum_size = 0;
651
652         if (db->blockcnt == 0) {
653                 root = (struct ext2_dx_root_info *) (block_buf + 24);
654
655 #ifdef DX_DEBUG
656                 printf("Root node dump:\n");
657                 printf("\t Reserved zero: %u\n", root->reserved_zero);
658                 printf("\t Hash Version: %u\n", root->hash_version);
659                 printf("\t Info length: %u\n", root->info_length);
660                 printf("\t Indirect levels: %u\n", root->indirect_levels);
661                 printf("\t Flags: %x\n", root->unused_flags);
662 #endif
663
664                 ent = (struct ext2_dx_entry *) (block_buf + 24 + root->info_length);
665
666                 if (failed_csum &&
667                     (e2fsck_dir_will_be_rehashed(cd->ctx, cd->pctx.ino) ||
668                      fix_problem(cd->ctx, PR_2_HTREE_ROOT_CSUM_INVALID,
669                                 &cd->pctx)))
670                         goto clear_and_exit;
671         } else {
672                 ent = (struct ext2_dx_entry *) (block_buf+8);
673
674                 if (failed_csum &&
675                     (e2fsck_dir_will_be_rehashed(cd->ctx, cd->pctx.ino) ||
676                      fix_problem(cd->ctx, PR_2_HTREE_NODE_CSUM_INVALID,
677                                 &cd->pctx)))
678                         goto clear_and_exit;
679         }
680
681         limit = (struct ext2_dx_countlimit *) ent;
682
683 #ifdef DX_DEBUG
684         printf("Number of entries (count): %d\n",
685                ext2fs_le16_to_cpu(limit->count));
686         printf("Number of entries (limit): %d\n",
687                ext2fs_le16_to_cpu(limit->limit));
688 #endif
689
690         count = ext2fs_le16_to_cpu(limit->count);
691         if (ext2fs_has_feature_metadata_csum(fs->super))
692                 csum_size = sizeof(struct ext2_dx_tail);
693         expect_limit = (fs->blocksize -
694                         (csum_size + ((char *) ent - block_buf))) /
695                        sizeof(struct ext2_dx_entry);
696         if (ext2fs_le16_to_cpu(limit->limit) != expect_limit) {
697                 cd->pctx.num = ext2fs_le16_to_cpu(limit->limit);
698                 if (fix_problem(cd->ctx, PR_2_HTREE_BAD_LIMIT, &cd->pctx))
699                         goto clear_and_exit;
700         }
701         if (count > expect_limit) {
702                 cd->pctx.num = count;
703                 if (fix_problem(cd->ctx, PR_2_HTREE_BAD_COUNT, &cd->pctx))
704                         goto clear_and_exit;
705                 count = expect_limit;
706         }
707
708         for (i=0; i < count; i++) {
709                 prev_hash = hash;
710                 hash = i ? (ext2fs_le32_to_cpu(ent[i].hash) & ~1) : 0;
711 #ifdef DX_DEBUG
712                 printf("Entry #%d: Hash 0x%08x, block %u\n", i,
713                        hash, ext2fs_le32_to_cpu(ent[i].block));
714 #endif
715                 blk = ext2fs_le32_to_cpu(ent[i].block) & EXT4_DX_BLOCK_MASK;
716                 /* Check to make sure the block is valid */
717                 if (blk >= dx_dir->numblocks) {
718                         cd->pctx.blk = blk;
719                         if (fix_problem(cd->ctx, PR_2_HTREE_BADBLK,
720                                         &cd->pctx))
721                                 goto clear_and_exit;
722                         continue;
723                 }
724                 if (hash < prev_hash &&
725                     fix_problem(cd->ctx, PR_2_HTREE_HASH_ORDER, &cd->pctx))
726                         goto clear_and_exit;
727                 dx_db = &dx_dir->dx_block[blk];
728                 if (dx_db->flags & DX_FLAG_REFERENCED) {
729                         dx_db->flags |= DX_FLAG_DUP_REF;
730                 } else {
731                         dx_db->flags |= DX_FLAG_REFERENCED;
732                         dx_db->parent = db->blockcnt;
733                 }
734
735                 dx_db->previous =
736                         i ? (ext2fs_le32_to_cpu(ent[i-1].block) &
737                              EXT4_DX_BLOCK_MASK) : 0;
738
739                 if (hash < min_hash)
740                         min_hash = hash;
741                 if (hash > max_hash)
742                         max_hash = hash;
743                 dx_db->node_min_hash = hash;
744                 if ((i+1) < count)
745                         dx_db->node_max_hash =
746                           ext2fs_le32_to_cpu(ent[i+1].hash) & ~1;
747                 else {
748                         dx_db->node_max_hash = 0xfffffffe;
749                         dx_db->flags |= DX_FLAG_LAST;
750                 }
751                 if (i == 0)
752                         dx_db->flags |= DX_FLAG_FIRST;
753         }
754 #ifdef DX_DEBUG
755         printf("Blockcnt = %d, min hash 0x%08x, max hash 0x%08x\n",
756                db->blockcnt, min_hash, max_hash);
757 #endif
758         dx_db = &dx_dir->dx_block[db->blockcnt];
759         dx_db->min_hash = min_hash;
760         dx_db->max_hash = max_hash;
761         return;
762
763 clear_and_exit:
764         clear_htree(cd->ctx, cd->pctx.ino);
765         dx_dir->numblocks = 0;
766         e2fsck_rehash_dir_later(cd->ctx, cd->pctx.ino);
767 }
768
769 /*
770  * Given a busted directory, try to salvage it somehow.
771  *
772  */
773 static void salvage_directory(ext2_filsys fs,
774                               struct ext2_dir_entry *dirent,
775                               struct ext2_dir_entry *prev,
776                               unsigned int *offset,
777                               unsigned int block_len,
778                               int hash_in_dirent)
779 {
780         char    *cp = (char *) dirent;
781         int left;
782         unsigned int rec_len, prev_rec_len;
783         unsigned int name_len;
784
785         /*
786          * If the space left for the entry is too small to be an entry,
787          * we can't access dirent's fields, so plumb in the values needed
788          * so that the previous entry absorbs this one.
789          */
790         if (block_len - *offset < EXT2_DIR_ENTRY_HEADER_LEN) {
791                 name_len = 0;
792                 rec_len = block_len - *offset;
793         } else {
794                 name_len = ext2fs_dirent_name_len(dirent);
795                 (void) ext2fs_get_rec_len(fs, dirent, &rec_len);
796         }
797         left = block_len - *offset - rec_len;
798
799         /*
800          * Special case of directory entry of size 8: copy what's left
801          * of the directory block up to cover up the invalid hole.
802          */
803         if ((left >= (int) ext2fs_dir_rec_len(1, hash_in_dirent)) &&
804              (rec_len == EXT2_DIR_ENTRY_HEADER_LEN)) {
805                 memmove(cp, cp+EXT2_DIR_ENTRY_HEADER_LEN, left);
806                 memset(cp + left, 0, EXT2_DIR_ENTRY_HEADER_LEN);
807                 return;
808         }
809         /*
810          * If the directory entry overruns the end of the directory
811          * block, and the name is small enough to fit, then adjust the
812          * record length.
813          */
814         if ((left < 0) &&
815             ((int) rec_len + left > EXT2_DIR_ENTRY_HEADER_LEN) &&
816             ((int) ext2fs_dir_rec_len(name_len, hash_in_dirent) <= (int) rec_len + left) &&
817             dirent->inode <= fs->super->s_inodes_count &&
818             strnlen(dirent->name, name_len) == name_len) {
819                 (void) ext2fs_set_rec_len(fs, (int) rec_len + left, dirent);
820                 return;
821         }
822         /*
823          * If the record length of the directory entry is a multiple
824          * of four, and not too big, such that it is valid, let the
825          * previous directory entry absorb the invalid one.
826          */
827         if (prev && rec_len && (rec_len % 4) == 0 &&
828             (*offset + rec_len <= block_len)) {
829                 (void) ext2fs_get_rec_len(fs, prev, &prev_rec_len);
830                 prev_rec_len += rec_len;
831                 (void) ext2fs_set_rec_len(fs, prev_rec_len, prev);
832                 *offset += rec_len;
833                 return;
834         }
835         /*
836          * Default salvage method --- kill all of the directory
837          * entries for the rest of the block.  We will either try to
838          * absorb it into the previous directory entry, or create a
839          * new empty directory entry the rest of the directory block.
840          */
841         if (prev) {
842                 (void) ext2fs_get_rec_len(fs, prev, &prev_rec_len);
843                 prev_rec_len += block_len - *offset;
844                 (void) ext2fs_set_rec_len(fs, prev_rec_len, prev);
845                 *offset = fs->blocksize;
846         } else {
847                 rec_len = block_len - *offset;
848                 (void) ext2fs_set_rec_len(fs, rec_len, dirent);
849                 ext2fs_dirent_set_name_len(dirent, 0);
850                 ext2fs_dirent_set_file_type(dirent, EXT2_FT_UNKNOWN);
851                 dirent->inode = 0;
852         }
853 }
854
855 #define NEXT_DIRENT(d)  ((void *)((char *)(d) + (d)->rec_len))
856 static errcode_t insert_dirent_tail(ext2_filsys fs, void *dirbuf)
857 {
858         struct ext2_dir_entry *d;
859         void *top;
860         struct ext2_dir_entry_tail *t;
861
862         d = dirbuf;
863         top = EXT2_DIRENT_TAIL(dirbuf, fs->blocksize);
864
865         while (d->rec_len && !(d->rec_len & 0x3) && NEXT_DIRENT(d) <= top)
866                 d = NEXT_DIRENT(d);
867
868         if (d != top) {
869                 unsigned int min_size = EXT2_DIR_REC_LEN(
870                                 ext2fs_dirent_name_len(dirbuf));
871                 if (min_size > (char *)top - (char *)d)
872                         return EXT2_ET_DIR_NO_SPACE_FOR_CSUM;
873                 d->rec_len = (char *)top - (char *)d;
874         }
875
876         t = (struct ext2_dir_entry_tail *)top;
877         if (t->det_reserved_zero1 ||
878             t->det_rec_len != sizeof(struct ext2_dir_entry_tail) ||
879             t->det_reserved_name_len != EXT2_DIR_NAME_LEN_CSUM)
880                 ext2fs_initialize_dirent_tail(fs, t);
881
882         return 0;
883 }
884 #undef NEXT_DIRENT
885
886 static errcode_t fix_inline_dir_size(e2fsck_t ctx, ext2_ino_t ino,
887                                      size_t *inline_data_size,
888                                      struct problem_context *pctx,
889                                      char *buf)
890 {
891         ext2_filsys fs = ctx->fs;
892         struct ext2_inode inode;
893         size_t new_size, old_size;
894         errcode_t retval;
895
896         old_size = *inline_data_size;
897         /*
898          * If there's not enough bytes to start the "second" dir block
899          * (in the EA space) then truncate everything to the first block.
900          */
901         if (old_size > EXT4_MIN_INLINE_DATA_SIZE &&
902             old_size < EXT4_MIN_INLINE_DATA_SIZE +
903                        EXT2_DIR_REC_LEN(1)) {
904                 old_size = EXT4_MIN_INLINE_DATA_SIZE;
905                 new_size = old_size;
906         } else
907                 /* Increase to the next four-byte boundary for salvaging */
908                 new_size = old_size + (4 - (old_size & 3));
909         memset(buf + old_size, 0, new_size - old_size);
910         retval = ext2fs_inline_data_set(fs, ino, 0, buf, new_size);
911         if (retval == EXT2_ET_INLINE_DATA_NO_SPACE) {
912                 /* Or we can't, so truncate. */
913                 new_size -= 4;
914                 retval = ext2fs_inline_data_set(fs, ino, 0, buf, new_size);
915                 if (retval) {
916                         if (fix_problem(ctx, PR_2_FIX_INLINE_DIR_FAILED,
917                                         pctx)) {
918                                 new_size = 0;
919                                 goto write_inode;
920                         }
921                         goto err;
922                 }
923         } else if (retval) {
924                 if (fix_problem(ctx, PR_2_FIX_INLINE_DIR_FAILED,
925                                 pctx)) {
926                         new_size = 0;
927                         goto write_inode;
928                 }
929                 goto err;
930         }
931
932 write_inode:
933         retval = ext2fs_read_inode(fs, ino, &inode);
934         if (retval)
935                 goto err;
936
937         retval = ext2fs_inode_size_set(fs, &inode, new_size);
938         if (retval)
939                 goto err;
940         if (new_size == 0)
941                 inode.i_flags &= ~EXT4_INLINE_DATA_FL;
942         retval = ext2fs_write_inode(fs, ino, &inode);
943         if (retval)
944                 goto err;
945         *inline_data_size = new_size;
946
947 err:
948         return retval;
949 }
950
951 /* Return true if this type of file needs encryption */
952 static int needs_encryption(e2fsck_t ctx, const struct ext2_dir_entry *dirent)
953 {
954         int filetype = ext2fs_dirent_file_type(dirent);
955         ext2_ino_t ino = dirent->inode;
956         struct ext2_inode inode;
957
958         if (filetype != EXT2_FT_UNKNOWN)
959                 return filetype == EXT2_FT_REG_FILE ||
960                        filetype == EXT2_FT_DIR ||
961                        filetype == EXT2_FT_SYMLINK;
962
963         if (ext2fs_test_inode_bitmap2(ctx->inode_reg_map, ino) ||
964             ext2fs_test_inode_bitmap2(ctx->inode_dir_map, ino))
965                 return 1;
966
967         e2fsck_read_inode(ctx, ino, &inode, "check_encryption_policy");
968         return LINUX_S_ISREG(inode.i_mode) ||
969                LINUX_S_ISDIR(inode.i_mode) ||
970                LINUX_S_ISLNK(inode.i_mode);
971 }
972
973 /*
974  * All regular files, directories, and symlinks in encrypted directories must be
975  * encrypted using the same encryption policy as their directory.
976  *
977  * Returns 1 if the dirent should be cleared, otherwise 0.
978  */
979 static int check_encryption_policy(e2fsck_t ctx,
980                                    const struct ext2_dir_entry *dirent,
981                                    __u32 dir_encpolicy_id,
982                                    struct problem_context *pctx)
983 {
984         __u32 file_encpolicy_id = find_encryption_policy(ctx, dirent->inode);
985
986         /* Same policy or both UNRECOGNIZED_ENCRYPTION_POLICY? */
987         if (file_encpolicy_id == dir_encpolicy_id)
988                 return 0;
989
990         if (file_encpolicy_id == NO_ENCRYPTION_POLICY) {
991                 if (!needs_encryption(ctx, dirent))
992                         return 0;
993                 return fix_problem(ctx, PR_2_UNENCRYPTED_FILE, pctx);
994         }
995
996         return fix_problem(ctx, PR_2_INCONSISTENT_ENCRYPTION_POLICY, pctx);
997 }
998
999 /*
1000  * Check an encrypted directory entry.
1001  *
1002  * Returns 1 if the dirent should be cleared, otherwise 0.
1003  */
1004 static int check_encrypted_dirent(e2fsck_t ctx,
1005                                   const struct ext2_dir_entry *dirent,
1006                                   __u32 dir_encpolicy_id,
1007                                   struct problem_context *pctx)
1008 {
1009         if (encrypted_check_name(ctx, dirent, pctx))
1010                 return 1;
1011         if (check_encryption_policy(ctx, dirent, dir_encpolicy_id, pctx))
1012                 return 1;
1013         return 0;
1014 }
1015
1016 static int check_dir_block2(ext2_filsys fs,
1017                            struct ext2_db_entry2 *db,
1018                            void *priv_data)
1019 {
1020         int err;
1021         struct check_dir_struct *cd = priv_data;
1022
1023         if (cd->ra_entries && cd->list_offset >= cd->next_ra_off) {
1024                 err = e2fsck_readahead_dblist(fs,
1025                                         E2FSCK_RA_DBLIST_IGNORE_BLOCKCNT,
1026                                         fs->dblist,
1027                                         cd->list_offset + cd->ra_entries / 8,
1028                                         cd->ra_entries);
1029                 if (err)
1030                         cd->ra_entries = 0;
1031                 cd->next_ra_off = cd->list_offset + (cd->ra_entries * 7 / 8);
1032         }
1033
1034         err = check_dir_block(fs, db, priv_data);
1035         cd->list_offset++;
1036         return err;
1037 }
1038
1039 static int check_dir_block(ext2_filsys fs,
1040                            struct ext2_db_entry2 *db,
1041                            void *priv_data)
1042 {
1043         struct dx_dir_info      *dx_dir;
1044         struct dx_dirblock_info *dx_db = 0;
1045         struct ext2_dir_entry   *dirent, *prev, dot, dotdot;
1046         ext2_dirhash_t          hash;
1047         unsigned int            offset = 0;
1048         int                     dir_modified = 0;
1049         int                     dot_state;
1050         unsigned int            rec_len;
1051         blk64_t                 block_nr = db->blk;
1052         ext2_ino_t              ino = db->ino;
1053         ext2_ino_t              subdir_parent;
1054         __u16                   links;
1055         struct check_dir_struct *cd;
1056         char                    *buf, *ibuf;
1057         e2fsck_t                ctx;
1058         problem_t               problem;
1059         struct ext2_dx_root_info *root;
1060         struct ext2_dx_countlimit *limit;
1061         static dict_t de_dict;
1062         struct problem_context  pctx;
1063         int     dups_found = 0;
1064         int     ret;
1065         int     dx_csum_size = 0, de_csum_size = 0;
1066         int     failed_csum = 0;
1067         int     is_leaf = 1;
1068         size_t  inline_data_size = 0;
1069         int     filetype = 0;
1070         __u32   dir_encpolicy_id = NO_ENCRYPTION_POLICY;
1071         int     hash_in_dirent = 0;
1072         int     casefolded = 0;
1073         size_t  max_block_size;
1074         int     hash_flags = 0;
1075         static char *eop_read_dirblock = NULL;
1076         int cf_dir = 0;
1077
1078         cd = (struct check_dir_struct *) priv_data;
1079         ibuf = buf = cd->buf;
1080         ctx = cd->ctx;
1081
1082         /* We only want filename encoding verification on strict
1083          * mode or if explicitly requested by user. */
1084         if (ext2fs_test_inode_bitmap2(ctx->inode_casefold_map, ino) &&
1085             ((ctx->fs->super->s_encoding_flags & EXT4_ENC_STRICT_MODE_FL) ||
1086              (ctx->options & E2F_OPT_CHECK_ENCODING)))
1087                 cf_dir = 1;
1088
1089         if (ctx->flags & E2F_FLAG_RUN_RETURN)
1090                 return DIRENT_ABORT;
1091
1092         if (ctx->progress && (ctx->progress)(ctx, 2, cd->count++, cd->max))
1093                 return DIRENT_ABORT;
1094
1095         if (ext2fs_has_feature_metadata_csum(fs->super)) {
1096                 dx_csum_size = sizeof(struct ext2_dx_tail);
1097                 de_csum_size = sizeof(struct ext2_dir_entry_tail);
1098         }
1099
1100         if (ext2fs_has_feature_filetype(fs->super))
1101                 filetype = EXT2_FT_DIR << 8;
1102
1103         /*
1104          * Make sure the inode is still in use (could have been
1105          * deleted in the duplicate/bad blocks pass.
1106          */
1107         if (!(ext2fs_test_inode_bitmap2(ctx->inode_used_map, ino)))
1108                 return 0;
1109
1110         cd->pctx.ino = ino;
1111         cd->pctx.blk = block_nr;
1112         cd->pctx.blkcount = db->blockcnt;
1113         cd->pctx.ino2 = 0;
1114         cd->pctx.dirent = 0;
1115         cd->pctx.num = 0;
1116
1117         if (ext2fs_has_feature_inline_data(fs->super)) {
1118                 errcode_t ec;
1119
1120                 ec = ext2fs_inline_data_size(fs, ino, &inline_data_size);
1121                 if (ec && ec != EXT2_ET_NO_INLINE_DATA)
1122                         return DIRENT_ABORT;
1123         }
1124
1125         /* This will allow (at some point in the future) to punch out empty
1126          * directory blocks and reduce the space used by a directory that grows
1127          * very large and then the files are deleted. For now, all that is
1128          * needed is to avoid e2fsck filling in these holes as part of
1129          * feature flag. */
1130         if (db->blk == 0 && ext2fs_has_feature_largedir(fs->super) &&
1131             !ext2fs_has_feature_inline_data(fs->super))
1132                 return 0;
1133
1134         if (db->blk == 0 && !inline_data_size) {
1135                 if (allocate_dir_block(ctx, db, buf, &cd->pctx))
1136                         return 0;
1137                 block_nr = db->blk;
1138         }
1139
1140         if (db->blockcnt)
1141                 dot_state = 2;
1142         else
1143                 dot_state = 0;
1144
1145         if (ctx->dirs_to_hash &&
1146             ext2fs_u32_list_test(ctx->dirs_to_hash, ino))
1147                 dups_found++;
1148
1149 #if 0
1150         printf("In process_dir_block block %lu, #%d, inode %lu\n", block_nr,
1151                db->blockcnt, ino);
1152 #endif
1153
1154         if (!eop_read_dirblock)
1155                 eop_read_dirblock = (char *) _("reading directory block");
1156         ehandler_operation(eop_read_dirblock);
1157         if (inline_data_size) {
1158                 memset(buf, 0, fs->blocksize - inline_data_size);
1159                 cd->pctx.errcode = ext2fs_inline_data_get(fs, ino, 0, buf, 0);
1160                 if (cd->pctx.errcode)
1161                         goto inline_read_fail;
1162 #ifdef WORDS_BIGENDIAN
1163                 if (db->blockcnt)
1164                         goto skip_first_read_swab;
1165                 *((__u32 *)buf) = ext2fs_le32_to_cpu(*((__u32 *)buf));
1166                 cd->pctx.errcode = ext2fs_dirent_swab_in2(fs,
1167                                 buf + EXT4_INLINE_DATA_DOTDOT_SIZE,
1168                                 EXT4_MIN_INLINE_DATA_SIZE - EXT4_INLINE_DATA_DOTDOT_SIZE,
1169                                 0);
1170                 if (cd->pctx.errcode)
1171                         goto inline_read_fail;
1172 skip_first_read_swab:
1173                 if (inline_data_size <= EXT4_MIN_INLINE_DATA_SIZE ||
1174                     !db->blockcnt)
1175                         goto inline_read_fail;
1176                 cd->pctx.errcode = ext2fs_dirent_swab_in2(fs,
1177                                 buf + EXT4_MIN_INLINE_DATA_SIZE,
1178                                 inline_data_size - EXT4_MIN_INLINE_DATA_SIZE,
1179                                 0);
1180 #endif
1181         } else
1182                 cd->pctx.errcode = ext2fs_read_dir_block4(fs, block_nr,
1183                                                           buf, 0, ino);
1184 inline_read_fail:
1185         pctx.ino = ino;
1186         pctx.num = inline_data_size;
1187         if (((inline_data_size & 3) ||
1188              (inline_data_size > EXT4_MIN_INLINE_DATA_SIZE &&
1189               inline_data_size < EXT4_MIN_INLINE_DATA_SIZE +
1190                                  EXT2_DIR_REC_LEN(1))) &&
1191             fix_problem(ctx, PR_2_BAD_INLINE_DIR_SIZE, &pctx)) {
1192                 errcode_t err = fix_inline_dir_size(ctx, ino,
1193                                                     &inline_data_size, &pctx,
1194                                                     buf);
1195                 if (err)
1196                         return DIRENT_ABORT;
1197
1198         }
1199         ehandler_operation(0);
1200         if (cd->pctx.errcode == EXT2_ET_DIR_CORRUPTED)
1201                 cd->pctx.errcode = 0; /* We'll handle this ourselves */
1202         else if (cd->pctx.errcode == EXT2_ET_DIR_CSUM_INVALID) {
1203                 cd->pctx.errcode = 0; /* We'll handle this ourselves */
1204                 failed_csum = 1;
1205         }
1206         if (cd->pctx.errcode) {
1207                 char *buf2;
1208                 if (!fix_problem(ctx, PR_2_READ_DIRBLOCK, &cd->pctx)) {
1209                         ctx->flags |= E2F_FLAG_ABORT;
1210                         return DIRENT_ABORT;
1211                 }
1212                 ext2fs_new_dir_block(fs, db->blockcnt == 0 ? ino : 0,
1213                                      EXT2_ROOT_INO, &buf2);
1214                 memcpy(buf, buf2, fs->blocksize);
1215                 ext2fs_free_mem(&buf2);
1216         }
1217         dx_dir = e2fsck_get_dx_dir_info(ctx, ino);
1218         if (dx_dir && dx_dir->numblocks) {
1219                 if (db->blockcnt >= dx_dir->numblocks) {
1220                         pctx.dir = ino;
1221                         if (fix_problem(ctx, PR_2_UNEXPECTED_HTREE_BLOCK,
1222                                         &pctx)) {
1223                                 clear_htree(ctx, ino);
1224                                 dx_dir->numblocks = 0;
1225                                 dx_db = 0;
1226                                 goto out_htree;
1227                         }
1228                         fatal_error(ctx, _("Can not continue."));
1229                 }
1230                 dx_db = &dx_dir->dx_block[db->blockcnt];
1231                 dx_db->type = DX_DIRBLOCK_LEAF;
1232                 dx_db->phys = block_nr;
1233                 dx_db->min_hash = ~0;
1234                 dx_db->max_hash = 0;
1235
1236                 dirent = (struct ext2_dir_entry *) buf;
1237                 (void) ext2fs_get_rec_len(fs, dirent, &rec_len);
1238                 limit = (struct ext2_dx_countlimit *) (buf+8);
1239                 if (db->blockcnt == 0) {
1240                         root = (struct ext2_dx_root_info *) (buf + 24);
1241                         dx_db->type = DX_DIRBLOCK_ROOT;
1242                         dx_db->flags |= DX_FLAG_FIRST | DX_FLAG_LAST;
1243
1244                         /* large_dir was set in pass1 if large dirs were found,
1245                          * so ext2_dir_htree_level() should now be correct */
1246                         if ((root->reserved_zero ||
1247                              root->info_length < 8 ||
1248                              root->indirect_levels >=
1249                              ext2_dir_htree_level(fs)) &&
1250                             fix_problem(ctx, PR_2_HTREE_BAD_ROOT, &cd->pctx)) {
1251                                 clear_htree(ctx, ino);
1252                                 dx_dir->numblocks = 0;
1253                                 dx_db = NULL;
1254                         }
1255                         dx_dir->hashversion = root->hash_version;
1256                         if ((dx_dir->hashversion <= EXT2_HASH_TEA) &&
1257                             (fs->super->s_flags & EXT2_FLAGS_UNSIGNED_HASH))
1258                                 dx_dir->hashversion += 3;
1259                         dx_dir->depth = root->indirect_levels + 1;
1260                 } else if ((dirent->inode == 0) &&
1261                            (rec_len == fs->blocksize) &&
1262                            (ext2fs_dirent_name_len(dirent) == 0) &&
1263                            (ext2fs_le16_to_cpu(limit->limit) ==
1264                             ((fs->blocksize - (8 + dx_csum_size)) /
1265                              sizeof(struct ext2_dx_entry)))) {
1266                         dx_db->type = DX_DIRBLOCK_NODE;
1267                 }
1268                 is_leaf = dx_db ? (dx_db->type == DX_DIRBLOCK_LEAF) : 0;
1269         }
1270 out_htree:
1271
1272         /* Leaf node with no space for csum?  Rebuild dirs in pass 3A. */
1273         if (is_leaf && !inline_data_size && failed_csum &&
1274             !ext2fs_dirent_has_tail(fs, (struct ext2_dir_entry *)buf)) {
1275                 de_csum_size = 0;
1276                 if (e2fsck_dir_will_be_rehashed(ctx, ino)) {
1277                         failed_csum = 0;
1278                         goto skip_checksum;
1279                 }
1280                 if (!fix_problem(cd->ctx, PR_2_LEAF_NODE_MISSING_CSUM,
1281                                  &cd->pctx))
1282                         goto skip_checksum;
1283                 e2fsck_rehash_dir_later(ctx, ino);
1284                 failed_csum = 0;
1285                 goto skip_checksum;
1286         }
1287         /* htree nodes don't use fake dirents to store checksums */
1288         if (!is_leaf)
1289                 de_csum_size = 0;
1290
1291 skip_checksum:
1292         if (inline_data_size) {
1293                 if (db->blockcnt) {
1294                         buf += EXT4_MIN_INLINE_DATA_SIZE;
1295                         max_block_size = inline_data_size - EXT4_MIN_INLINE_DATA_SIZE;
1296                         /* Zero-length second block, just exit */
1297                         if (max_block_size == 0)
1298                                 return 0;
1299                 } else {
1300                         max_block_size = EXT4_MIN_INLINE_DATA_SIZE;
1301                 }
1302         } else
1303                 max_block_size = fs->blocksize - de_csum_size;
1304
1305         dir_encpolicy_id = find_encryption_policy(ctx, ino);
1306
1307         if (cf_dir) {
1308                 dict_init(&de_dict, DICTCOUNT_T_MAX, dict_de_cf_cmp);
1309                 dict_set_cmp_context(&de_dict, (const void *)ctx->fs->encoding);
1310         } else {
1311                 dict_init(&de_dict, DICTCOUNT_T_MAX, dict_de_cmp);
1312         }
1313         if (ctx->casefolded_dirs)
1314                 casefolded = ext2fs_u32_list_test(ctx->casefolded_dirs, ino);
1315         hash_in_dirent = (casefolded &&
1316                           (dir_encpolicy_id != NO_ENCRYPTION_POLICY));
1317
1318         prev = 0;
1319         do {
1320                 dgrp_t group;
1321                 ext2_ino_t first_unused_inode;
1322                 unsigned int name_len;
1323                 /* csum entry is not checked here, so don't worry about it */
1324                 int extended = (dot_state > 1) && hash_in_dirent;
1325                 unsigned int min_dir_len = ext2fs_dir_rec_len(1, extended);
1326
1327                 problem = 0;
1328                 if (!inline_data_size || dot_state > 1) {
1329                         dirent = (struct ext2_dir_entry *) (buf + offset);
1330                         /*
1331                          * If there's not even space for the entry header,
1332                          * force salvaging this dir.
1333                          */
1334                         if (max_block_size - offset < EXT2_DIR_ENTRY_HEADER_LEN)
1335                                 rec_len = ext2fs_dir_rec_len(1, extended);
1336                         else
1337                                 (void) ext2fs_get_rec_len(fs, dirent, &rec_len);
1338                         cd->pctx.dirent = dirent;
1339                         cd->pctx.num = offset;
1340                         if ((offset + rec_len > max_block_size) ||
1341                             (rec_len < min_dir_len) ||
1342                             ((rec_len % 4) != 0) ||
1343                             ((ext2fs_dir_rec_len(ext2fs_dirent_name_len(dirent),
1344                                                  extended)) > rec_len))
1345                                 problem = PR_2_DIR_CORRUPTED;
1346                         if (problem) {
1347                                 if ((offset == 0) &&
1348                                     (rec_len == fs->blocksize) &&
1349                                     (dirent->inode == 0) &&
1350                                     e2fsck_dir_will_be_rehashed(ctx, ino)) {
1351                                         problem = 0;
1352                                         max_block_size = fs->blocksize;
1353                                 }
1354                         }
1355                         if (problem) {
1356 #ifdef WORDS_BIGENDIAN
1357                                 int need_reswab = 0;
1358 #endif
1359
1360                                 if (!fix_problem(ctx, PR_2_DIR_CORRUPTED,
1361                                                 &cd->pctx))
1362                                         goto abort_free_dict;
1363 #ifdef WORDS_BIGENDIAN
1364                                 /*
1365                                  * On big-endian systems, if the dirent
1366                                  * swap routine finds a rec_len that it
1367                                  * doesn't like, it continues processing
1368                                  * the block as if rec_len ==
1369                                  * EXT2_DIR_ENTRY_HEADER_LEN.  This means
1370                                  * that the name field gets byte swapped,
1371                                  * which means that salvage will not detect
1372                                  * the correct name length (unless the name
1373                                  * has a length that's an exact multiple of
1374                                  * four bytes), and it'll discard the entry
1375                                  * (unnecessarily) and the rest of the
1376                                  * dirent block.  Therefore, swap the rest
1377                                  * of the block back to disk order, run
1378                                  * salvage, and re-swap anything after the
1379                                  * salvaged dirent.
1380                                  */
1381                                 if (rec_len < EXT2_DIR_ENTRY_HEADER_LEN ||
1382                                     rec_len % 4) {
1383                                         need_reswab = 1;
1384                                         ext2fs_dirent_swab_in2(fs,
1385                         ((char *)dirent) + EXT2_DIR_ENTRY_HEADER_LEN,
1386                         max_block_size - offset - EXT2_DIR_ENTRY_HEADER_LEN, 0);
1387                                 }
1388 #endif
1389                                 salvage_directory(fs, dirent, prev, &offset,
1390                                                   max_block_size,
1391                                                   hash_in_dirent);
1392 #ifdef WORDS_BIGENDIAN
1393                                 if (need_reswab) {
1394                                         unsigned int len;
1395
1396                                         (void) ext2fs_get_rec_len(fs, dirent,
1397                                                                   &len);
1398                                         len += offset;
1399                                         if (max_block_size > len)
1400                                                 ext2fs_dirent_swab_in2(fs,
1401                         ((char *)dirent) + len, max_block_size - len, 0);
1402                                 }
1403 #endif
1404                                 dir_modified++;
1405                                 continue;
1406                         }
1407                 } else {
1408                         if (dot_state == 0) {
1409                                 memset(&dot, 0, sizeof(dot));
1410                                 dirent = &dot;
1411                                 dirent->inode = ino;
1412                                 dirent->rec_len = EXT2_DIR_REC_LEN(1);
1413                                 dirent->name_len = 1 | filetype;
1414                                 dirent->name[0] = '.';
1415                         } else if (dot_state == 1) {
1416                                 memset(&dotdot, 0, sizeof(dotdot));
1417                                 dirent = &dotdot;
1418                                 dirent->inode =
1419                                         ((struct ext2_dir_entry *)buf)->inode;
1420                                 dirent->rec_len = EXT2_DIR_REC_LEN(2);
1421                                 dirent->name_len = 2 | filetype;
1422                                 dirent->name[0] = '.';
1423                                 dirent->name[1] = '.';
1424                         } else {
1425                                 fatal_error(ctx, _("Can not continue."));
1426                         }
1427                         cd->pctx.dirent = dirent;
1428                         cd->pctx.num = offset;
1429                 }
1430
1431                 if (dot_state == 0) {
1432                         if (check_dot(ctx, dirent, ino, &cd->pctx))
1433                                 dir_modified++;
1434                 } else if (dot_state == 1) {
1435                         ret = check_dotdot(ctx, dirent, ino, &cd->pctx);
1436                         if (ret < 0)
1437                                 goto abort_free_dict;
1438                         if (ret)
1439                                 dir_modified++;
1440                 } else if (dirent->inode == ino) {
1441                         problem = PR_2_LINK_DOT;
1442                         if (fix_problem(ctx, PR_2_LINK_DOT, &cd->pctx)) {
1443                                 dirent->inode = 0;
1444                                 dir_modified++;
1445                                 goto next;
1446                         }
1447                 }
1448                 if (!dirent->inode)
1449                         goto next;
1450
1451                 /*
1452                  * Make sure the inode listed is a legal one.
1453                  */
1454                 name_len = ext2fs_dirent_name_len(dirent);
1455                 if (((dirent->inode != EXT2_ROOT_INO) &&
1456                      (dirent->inode < EXT2_FIRST_INODE(fs->super))) ||
1457                     (dirent->inode > fs->super->s_inodes_count) ||
1458                     (dirent->inode == fs->super->s_usr_quota_inum) ||
1459                     (dirent->inode == fs->super->s_grp_quota_inum) ||
1460                     (dirent->inode == fs->super->s_prj_quota_inum) ||
1461                     (dirent->inode == fs->super->s_orphan_file_inum)) {
1462                         problem = PR_2_BAD_INO;
1463                 } else if (ctx->inode_bb_map &&
1464                            (ext2fs_test_inode_bitmap2(ctx->inode_bb_map,
1465                                                      dirent->inode))) {
1466                         /*
1467                          * If the inode is in a bad block, offer to
1468                          * clear it.
1469                          */
1470                         problem = PR_2_BB_INODE;
1471                 } else if ((dot_state > 1) && (name_len == 1) &&
1472                            (dirent->name[0] == '.')) {
1473                         /*
1474                          * If there's a '.' entry in anything other
1475                          * than the first directory entry, it's a
1476                          * duplicate entry that should be removed.
1477                          */
1478                         problem = PR_2_DUP_DOT;
1479                 } else if ((dot_state > 1) && (name_len == 2) &&
1480                            (dirent->name[0] == '.') &&
1481                            (dirent->name[1] == '.')) {
1482                         /*
1483                          * If there's a '..' entry in anything other
1484                          * than the second directory entry, it's a
1485                          * duplicate entry that should be removed.
1486                          */
1487                         problem = PR_2_DUP_DOT_DOT;
1488                 } else if ((dot_state > 1) &&
1489                            (dirent->inode == EXT2_ROOT_INO)) {
1490                         /*
1491                          * Don't allow links to the root directory.
1492                          * We check this specially to make sure we
1493                          * catch this error case even if the root
1494                          * directory hasn't been created yet.
1495                          */
1496                         problem = PR_2_LINK_ROOT;
1497                 } else if ((dot_state > 1) && (name_len == 0)) {
1498                         /*
1499                          * Don't allow zero-length directory names.
1500                          */
1501                         problem = PR_2_NULL_NAME;
1502                 }
1503
1504                 /*
1505                  * Check if inode was tracked as EA inode and has actual
1506                  * references from xattrs. In that case dir entry is likely
1507                  * bogus and we want to clear it. The case of EA inode without
1508                  * references from xattrs will be handled in pass 4.
1509                  */
1510                 if (!problem && ctx->ea_inode_refs) {
1511                         ea_value_t refs;
1512
1513                         ea_refcount_fetch(ctx->ea_inode_refs, dirent->inode,
1514                                           &refs);
1515                         if (refs && refs != EA_INODE_NO_REFS)
1516                                 problem = PR_2_EA_INODE_DIR_LINK;
1517                 }
1518
1519                 if (problem) {
1520                         if (fix_problem(ctx, problem, &cd->pctx)) {
1521                                 dirent->inode = 0;
1522                                 dir_modified++;
1523                                 goto next;
1524                         } else {
1525                                 ext2fs_unmark_valid(fs);
1526                                 if (problem == PR_2_BAD_INO)
1527                                         goto next;
1528                         }
1529                 }
1530
1531                 /*
1532                  * If the inode was marked as having bad fields in
1533                  * pass1, process it and offer to fix/clear it.
1534                  * (We wait until now so that we can display the
1535                  * pathname to the user.)
1536                  */
1537                 if (ctx->inode_bad_map &&
1538                     ext2fs_test_inode_bitmap2(ctx->inode_bad_map,
1539                                              dirent->inode)) {
1540                         if (e2fsck_process_bad_inode(ctx, ino,
1541                                                      dirent->inode,
1542                                                      cd->buf + fs->blocksize)) {
1543                                 dirent->inode = 0;
1544                                 dir_modified++;
1545                                 goto next;
1546                         }
1547                         if (ctx->flags & E2F_FLAG_SIGNAL_MASK)
1548                                 return DIRENT_ABORT;
1549                 }
1550
1551                 group = ext2fs_group_of_ino(fs, dirent->inode);
1552                 first_unused_inode = group * fs->super->s_inodes_per_group +
1553                                         1 + fs->super->s_inodes_per_group -
1554                                         ext2fs_bg_itable_unused(fs, group);
1555                 cd->pctx.group = group;
1556
1557                 /*
1558                  * Check if the inode was missed out because
1559                  * _INODE_UNINIT flag was set or bg_itable_unused was
1560                  * incorrect.  If so, clear the _INODE_UNINIT flag and
1561                  * restart e2fsck.  In the future it would be nice if
1562                  * we could call a function in pass1.c that checks the
1563                  * newly visible inodes.
1564                  */
1565                 if (ext2fs_bg_flags_test(fs, group, EXT2_BG_INODE_UNINIT)) {
1566                         pctx.num = dirent->inode;
1567                         if (fix_problem(ctx, PR_2_INOREF_BG_INO_UNINIT,
1568                                         &cd->pctx)){
1569                                 ext2fs_bg_flags_clear(fs, group,
1570                                                       EXT2_BG_INODE_UNINIT);
1571                                 ext2fs_group_desc_csum_set(fs, group);
1572                                 ext2fs_mark_super_dirty(fs);
1573                                 ctx->flags |= E2F_FLAG_RESTART_LATER;
1574                         } else {
1575                                 ext2fs_unmark_valid(fs);
1576                                 if (problem == PR_2_BAD_INO)
1577                                         goto next;
1578                         }
1579                 } else if (dirent->inode >= first_unused_inode) {
1580                         pctx.num = dirent->inode;
1581                         if (fix_problem(ctx, PR_2_INOREF_IN_UNUSED, &cd->pctx)){
1582                                 ext2fs_bg_itable_unused_set(fs, group, 0);
1583                                 ext2fs_group_desc_csum_set(fs, group);
1584                                 ext2fs_mark_super_dirty(fs);
1585                                 ctx->flags |= E2F_FLAG_RESTART_LATER;
1586                         } else {
1587                                 ext2fs_unmark_valid(fs);
1588                                 if (problem == PR_2_BAD_INO)
1589                                         goto next;
1590                         }
1591                 }
1592
1593                 /* 
1594                  * Offer to clear unused inodes; if we are going to be
1595                  * restarting the scan due to bg_itable_unused being
1596                  * wrong, then don't clear any inodes to avoid zapping
1597                  * inodes that were skipped during pass1 due to an
1598                  * incorrect bg_itable_unused; we'll get any real
1599                  * problems after we restart.
1600                  */
1601                 if (!(ctx->flags & E2F_FLAG_RESTART_LATER) &&
1602                     !(ext2fs_test_inode_bitmap2(ctx->inode_used_map,
1603                                                 dirent->inode))
1604                         )
1605                         problem = PR_2_UNUSED_INODE;
1606
1607                 if (problem) {
1608                         if (fix_problem(ctx, problem, &cd->pctx)) {
1609                                 dirent->inode = 0;
1610                                 dir_modified++;
1611                                 goto next;
1612                         } else {
1613                                 ext2fs_unmark_valid(fs);
1614                                 if (problem == PR_2_BAD_INO)
1615                                         goto next;
1616                         }
1617                 }
1618
1619                 if (check_filetype(ctx, dirent, ino, &cd->pctx))
1620                         dir_modified++;
1621
1622                 if (dir_encpolicy_id != NO_ENCRYPTION_POLICY) {
1623                         /* Encrypted directory */
1624                         if (dot_state > 1 &&
1625                             check_encrypted_dirent(ctx, dirent,
1626                                                    dir_encpolicy_id,
1627                                                    &cd->pctx)) {
1628                                 dirent->inode = 0;
1629                                 dir_modified++;
1630                                 goto next;
1631                         }
1632                 } else if (cf_dir) {
1633                         /* Casefolded directory */
1634                         if (encoded_check_name(ctx, dirent, &cd->pctx))
1635                                 dir_modified++;
1636                 } else {
1637                         /* Unencrypted and uncasefolded directory */
1638                         if (check_name(ctx, dirent, &cd->pctx))
1639                                 dir_modified++;
1640                 }
1641
1642                 if (dx_db) {
1643                         if (dx_dir->casefolded_hash)
1644                                 hash_flags = EXT4_CASEFOLD_FL;
1645
1646                         if (dx_dir->hashversion == EXT2_HASH_SIPHASH) {
1647                                 if (dot_state > 1)
1648                                         hash = EXT2_DIRENT_HASH(dirent);
1649                         } else {
1650                                 ext2fs_dirhash2(dx_dir->hashversion,
1651                                                 dirent->name,
1652                                                 ext2fs_dirent_name_len(dirent),
1653                                                 fs->encoding, hash_flags,
1654                                                 fs->super->s_hash_seed,
1655                                                 &hash, 0);
1656                         }
1657                         if (hash < dx_db->min_hash)
1658                                 dx_db->min_hash = hash;
1659                         if (hash > dx_db->max_hash)
1660                                 dx_db->max_hash = hash;
1661                 }
1662
1663                 /*
1664                  * If this is a directory, then mark its parent in its
1665                  * dir_info structure.  If the parent field is already
1666                  * filled in, then this directory has more than one
1667                  * hard link.  We assume the first link is correct,
1668                  * and ask the user if he/she wants to clear this one.
1669                  */
1670                 if ((dot_state > 1) &&
1671                     (ext2fs_test_inode_bitmap2(ctx->inode_dir_map,
1672                                               dirent->inode))) {
1673                         if (e2fsck_dir_info_get_parent(ctx, dirent->inode,
1674                                                        &subdir_parent)) {
1675                                 cd->pctx.ino = dirent->inode;
1676                                 fix_problem(ctx, PR_2_NO_DIRINFO, &cd->pctx);
1677                                 goto abort_free_dict;
1678                         }
1679                         if (subdir_parent) {
1680                                 cd->pctx.ino2 = subdir_parent;
1681                                 if (fix_problem(ctx, PR_2_LINK_DIR,
1682                                                 &cd->pctx)) {
1683                                         dirent->inode = 0;
1684                                         dir_modified++;
1685                                         goto next;
1686                                 }
1687                                 cd->pctx.ino2 = 0;
1688                         } else {
1689                                 (void) e2fsck_dir_info_set_parent(ctx,
1690                                                   dirent->inode, ino);
1691                         }
1692                 }
1693
1694                 if (dups_found) {
1695                         ;
1696                 } else if (dict_lookup(&de_dict, dirent)) {
1697                         clear_problem_context(&pctx);
1698                         pctx.ino = ino;
1699                         pctx.dirent = dirent;
1700                         fix_problem(ctx, PR_2_REPORT_DUP_DIRENT, &pctx);
1701                         e2fsck_rehash_dir_later(ctx, ino);
1702                         dups_found++;
1703                 } else
1704                         dict_alloc_insert(&de_dict, dirent, dirent);
1705
1706                 ext2fs_icount_increment(ctx->inode_count, dirent->inode,
1707                                         &links);
1708                 if (links > 1)
1709                         ctx->fs_links_count++;
1710                 ctx->fs_total_count++;
1711         next:
1712                 prev = dirent;
1713                 if (dir_modified)
1714                         (void) ext2fs_get_rec_len(fs, dirent, &rec_len);
1715                 if (!inline_data_size || dot_state > 1) {
1716                         offset += rec_len;
1717                 } else {
1718                         if (dot_state == 1) {
1719                                 offset = 4;
1720                                 /*
1721                                  * If we get here, we're checking an inline
1722                                  * directory and we've just checked a (fake)
1723                                  * dotdot entry that we created on the stack.
1724                                  * Therefore set 'prev' to NULL so that if we
1725                                  * call salvage_directory on the next entry,
1726                                  * it won't try to absorb the next entry into
1727                                  * the on-stack dotdot entry.
1728                                  */
1729                                 prev = NULL;
1730                         }
1731                 }
1732                 dot_state++;
1733         } while (offset < max_block_size);
1734 #if 0
1735         printf("\n");
1736 #endif
1737         if (dx_db) {
1738 #ifdef DX_DEBUG
1739                 printf("db_block %d, type %d, min_hash 0x%0x, max_hash 0x%0x\n",
1740                        db->blockcnt, dx_db->type,
1741                        dx_db->min_hash, dx_db->max_hash);
1742 #endif
1743                 cd->pctx.dir = cd->pctx.ino;
1744                 if ((dx_db->type == DX_DIRBLOCK_ROOT) ||
1745                     (dx_db->type == DX_DIRBLOCK_NODE))
1746                         parse_int_node(fs, db, cd, dx_dir, buf, failed_csum);
1747         }
1748
1749         if (offset != max_block_size) {
1750                 cd->pctx.num = rec_len + offset - max_block_size;
1751                 if (fix_problem(ctx, PR_2_FINAL_RECLEN, &cd->pctx)) {
1752                         dirent->rec_len = cd->pctx.num;
1753                         dir_modified++;
1754                 }
1755         }
1756         if (dir_modified) {
1757                 int     flags, will_rehash;
1758                 /* leaf block with no tail?  Rehash dirs later. */
1759                 if (ext2fs_has_feature_metadata_csum(fs->super) &&
1760                     is_leaf &&
1761                     !inline_data_size &&
1762                     !ext2fs_dirent_has_tail(fs, (struct ext2_dir_entry *)buf)) {
1763                         if (insert_dirent_tail(fs, buf) == 0)
1764                                 goto write_and_fix;
1765                         e2fsck_rehash_dir_later(ctx, ino);
1766                 }
1767
1768 write_and_fix:
1769                 will_rehash = e2fsck_dir_will_be_rehashed(ctx, ino);
1770                 if (will_rehash) {
1771                         flags = ctx->fs->flags;
1772                         ctx->fs->flags |= EXT2_FLAG_IGNORE_CSUM_ERRORS;
1773                 }
1774                 if (inline_data_size) {
1775                         buf = ibuf;
1776 #ifdef WORDS_BIGENDIAN
1777                         if (db->blockcnt)
1778                                 goto skip_first_write_swab;
1779                         *((__u32 *)buf) = ext2fs_le32_to_cpu(*((__u32 *)buf));
1780                         cd->pctx.errcode = ext2fs_dirent_swab_out2(fs,
1781                                         buf + EXT4_INLINE_DATA_DOTDOT_SIZE,
1782                                         EXT4_MIN_INLINE_DATA_SIZE -
1783                                         EXT4_INLINE_DATA_DOTDOT_SIZE,
1784                                         0);
1785                         if (cd->pctx.errcode)
1786                                 goto skip_second_write_swab;
1787 skip_first_write_swab:
1788                         if (inline_data_size <= EXT4_MIN_INLINE_DATA_SIZE ||
1789                             !db->blockcnt)
1790                                 goto skip_second_write_swab;
1791                         cd->pctx.errcode = ext2fs_dirent_swab_out2(fs,
1792                                         buf + EXT4_MIN_INLINE_DATA_SIZE,
1793                                         inline_data_size -
1794                                         EXT4_MIN_INLINE_DATA_SIZE,
1795                                         0);
1796 skip_second_write_swab:
1797                         if (cd->pctx.errcode &&
1798                             !fix_problem(ctx, PR_2_WRITE_DIRBLOCK, &cd->pctx))
1799                                 goto abort_free_dict;
1800 #endif
1801                         cd->pctx.errcode =
1802                                 ext2fs_inline_data_set(fs, ino, 0, buf,
1803                                                        inline_data_size);
1804                 } else
1805                         cd->pctx.errcode = ext2fs_write_dir_block4(fs, block_nr,
1806                                                                    buf, 0, ino);
1807                 if (will_rehash)
1808                         ctx->fs->flags = (flags &
1809                                           EXT2_FLAG_IGNORE_CSUM_ERRORS) |
1810                                          (ctx->fs->flags &
1811                                           ~EXT2_FLAG_IGNORE_CSUM_ERRORS);
1812                 if (cd->pctx.errcode) {
1813                         if (!fix_problem(ctx, PR_2_WRITE_DIRBLOCK,
1814                                          &cd->pctx))
1815                                 goto abort_free_dict;
1816                 }
1817                 ext2fs_mark_changed(fs);
1818         } else if (is_leaf && failed_csum && !dir_modified) {
1819                 /*
1820                  * If a leaf node that fails csum makes it this far without
1821                  * alteration, ask the user if the checksum should be fixed.
1822                  */
1823                 if (fix_problem(ctx, PR_2_LEAF_NODE_ONLY_CSUM_INVALID,
1824                                 &cd->pctx))
1825                         goto write_and_fix;
1826         }
1827         dict_free_nodes(&de_dict);
1828         return 0;
1829 abort_free_dict:
1830         ctx->flags |= E2F_FLAG_ABORT;
1831         dict_free_nodes(&de_dict);
1832         return DIRENT_ABORT;
1833 }
1834
1835 struct del_block {
1836         e2fsck_t        ctx;
1837         e2_blkcnt_t     num;
1838         blk64_t last_cluster;
1839 };
1840
1841 /*
1842  * This function is called to deallocate a block, and is an iterator
1843  * functioned called by deallocate inode via ext2fs_iterate_block().
1844  */
1845 static int deallocate_inode_block(ext2_filsys fs,
1846                                   blk64_t       *block_nr,
1847                                   e2_blkcnt_t blockcnt EXT2FS_ATTR((unused)),
1848                                   blk64_t ref_block EXT2FS_ATTR((unused)),
1849                                   int ref_offset EXT2FS_ATTR((unused)),
1850                                   void *priv_data)
1851 {
1852         struct del_block *p = priv_data;
1853         blk64_t cluster = EXT2FS_B2C(fs, *block_nr);
1854
1855         if (*block_nr == 0)
1856                 return 0;
1857
1858         if (cluster == p->last_cluster)
1859                 return 0;
1860
1861         p->last_cluster = cluster;
1862         if ((*block_nr < fs->super->s_first_data_block) ||
1863             (*block_nr >= ext2fs_blocks_count(fs->super)))
1864                 return 0;
1865
1866         ext2fs_block_alloc_stats2(fs, *block_nr, -1);
1867         p->num++;
1868         return 0;
1869 }
1870
1871 /*
1872  * This function reverts various counters and bitmaps incremented in
1873  * pass1 for the inode, blocks, and quotas before it was decided the
1874  * inode was corrupt and needed to be cleared.  This avoids the need
1875  * to run e2fsck a second time (or have it restart itself) to repair
1876  * these counters.
1877  *
1878  * It does not modify any on-disk state, so even if the inode is bad
1879  * it _should_ reset in-memory state to before the inode was first
1880  * processed.
1881  */
1882 static void deallocate_inode(e2fsck_t ctx, ext2_ino_t ino, char* block_buf)
1883 {
1884         ext2_filsys fs = ctx->fs;
1885         struct ext2_inode_large inode;
1886         struct problem_context  pctx;
1887         __u32                   count;
1888         struct del_block        del_block;
1889
1890         e2fsck_read_inode_full(ctx, ino, EXT2_INODE(&inode),
1891                                sizeof(inode), "deallocate_inode");
1892         clear_problem_context(&pctx);
1893         pctx.ino = ino;
1894
1895         /*
1896          * Fix up the bitmaps...
1897          */
1898         e2fsck_read_bitmaps(ctx);
1899         ext2fs_inode_alloc_stats2(fs, ino, -1, LINUX_S_ISDIR(inode.i_mode));
1900
1901         if (ext2fs_file_acl_block(fs, EXT2_INODE(&inode)) &&
1902             ext2fs_has_feature_xattr(fs->super)) {
1903                 pctx.errcode = ext2fs_adjust_ea_refcount3(fs,
1904                                 ext2fs_file_acl_block(fs, EXT2_INODE(&inode)),
1905                                 block_buf, -1, &count, ino);
1906                 if (pctx.errcode == EXT2_ET_BAD_EA_BLOCK_NUM) {
1907                         pctx.errcode = 0;
1908                         count = 1;
1909                 }
1910                 if (pctx.errcode) {
1911                         pctx.blk = ext2fs_file_acl_block(fs, EXT2_INODE(&inode));
1912                         fix_problem(ctx, PR_2_ADJ_EA_REFCOUNT, &pctx);
1913                         ctx->flags |= E2F_FLAG_ABORT;
1914                         return;
1915                 }
1916                 if (count == 0) {
1917                         ext2fs_block_alloc_stats2(fs,
1918                                   ext2fs_file_acl_block(fs, EXT2_INODE(&inode)), -1);
1919                 }
1920                 ext2fs_file_acl_block_set(fs, EXT2_INODE(&inode), 0);
1921         }
1922
1923         if (!ext2fs_inode_has_valid_blocks2(fs, EXT2_INODE(&inode)))
1924                 goto clear_inode;
1925
1926         /* Inline data inodes don't have blocks to iterate */
1927         if (inode.i_flags & EXT4_INLINE_DATA_FL)
1928                 goto clear_inode;
1929
1930         if (ext2fs_needs_large_file_feature(EXT2_I_SIZE(&inode))) {
1931                 if (LINUX_S_ISREG(inode.i_mode))
1932                     ctx->large_files--;
1933                 else if (LINUX_S_ISDIR(inode.i_mode))
1934                     ctx->large_dirs--;
1935         }
1936
1937         del_block.ctx = ctx;
1938         del_block.num = 0;
1939         del_block.last_cluster = 0;
1940         pctx.errcode = ext2fs_block_iterate3(fs, ino, 0, block_buf,
1941                                              deallocate_inode_block,
1942                                              &del_block);
1943         if (pctx.errcode) {
1944                 fix_problem(ctx, PR_2_DEALLOC_INODE, &pctx);
1945                 ctx->flags |= E2F_FLAG_ABORT;
1946                 return;
1947         }
1948
1949         if ((ino != quota_type2inum(PRJQUOTA, fs->super)) &&
1950             (ino != fs->super->s_orphan_file_inum) &&
1951             (ino == EXT2_ROOT_INO || ino >= EXT2_FIRST_INODE(ctx->fs->super)) &&
1952             !(inode.i_flags & EXT4_EA_INODE_FL)) {
1953                 if (del_block.num > 0)
1954                         quota_data_sub(ctx->qctx, &inode, ino,
1955                                        del_block.num * EXT2_CLUSTER_SIZE(fs->super));
1956                 quota_data_inodes(ctx->qctx, (struct ext2_inode_large *)&inode,
1957                                   ino, -1);
1958         }
1959
1960 clear_inode:
1961         /* Inode may have changed by block_iterate, so reread it */
1962         e2fsck_read_inode(ctx, ino, EXT2_INODE(&inode), "deallocate_inode");
1963         e2fsck_clear_inode(ctx, ino, EXT2_INODE(&inode), 0, "deallocate_inode");
1964 }
1965
1966 /*
1967  * This function clears the htree flag on an inode
1968  */
1969 static void clear_htree(e2fsck_t ctx, ext2_ino_t ino)
1970 {
1971         struct ext2_inode       inode;
1972
1973         e2fsck_read_inode(ctx, ino, &inode, "clear_htree");
1974         inode.i_flags = inode.i_flags & ~EXT2_INDEX_FL;
1975         e2fsck_write_inode(ctx, ino, &inode, "clear_htree");
1976         if (ctx->dirs_to_hash)
1977                 ext2fs_u32_list_add(ctx->dirs_to_hash, ino);
1978 }
1979
1980
1981 int e2fsck_process_bad_inode(e2fsck_t ctx, ext2_ino_t dir,
1982                              ext2_ino_t ino, char *buf)
1983 {
1984         ext2_filsys fs = ctx->fs;
1985         struct ext2_inode       inode;
1986         int                     inode_modified = 0;
1987         int                     not_fixed = 0;
1988         unsigned char           *frag, *fsize;
1989         struct problem_context  pctx;
1990         problem_t               problem = 0;
1991
1992         e2fsck_read_inode(ctx, ino, &inode, "process_bad_inode");
1993
1994         clear_problem_context(&pctx);
1995         pctx.ino = ino;
1996         pctx.dir = dir;
1997         pctx.inode = &inode;
1998
1999         if (ext2fs_file_acl_block(fs, &inode) &&
2000             !ext2fs_has_feature_xattr(fs->super)) {
2001                 if (fix_problem(ctx, PR_2_FILE_ACL_ZERO, &pctx)) {
2002                         ext2fs_file_acl_block_set(fs, &inode, 0);
2003                         inode_modified++;
2004                 } else
2005                         not_fixed++;
2006         }
2007
2008         if (!LINUX_S_ISDIR(inode.i_mode) && !LINUX_S_ISREG(inode.i_mode) &&
2009             !LINUX_S_ISCHR(inode.i_mode) && !LINUX_S_ISBLK(inode.i_mode) &&
2010             !LINUX_S_ISLNK(inode.i_mode) && !LINUX_S_ISFIFO(inode.i_mode) &&
2011             !(LINUX_S_ISSOCK(inode.i_mode)))
2012                 problem = PR_2_BAD_MODE;
2013         else if (LINUX_S_ISCHR(inode.i_mode)
2014                  && !e2fsck_pass1_check_device_inode(fs, &inode))
2015                 problem = PR_2_BAD_CHAR_DEV;
2016         else if (LINUX_S_ISBLK(inode.i_mode)
2017                  && !e2fsck_pass1_check_device_inode(fs, &inode))
2018                 problem = PR_2_BAD_BLOCK_DEV;
2019         else if (LINUX_S_ISFIFO(inode.i_mode)
2020                  && !e2fsck_pass1_check_device_inode(fs, &inode))
2021                 problem = PR_2_BAD_FIFO;
2022         else if (LINUX_S_ISSOCK(inode.i_mode)
2023                  && !e2fsck_pass1_check_device_inode(fs, &inode))
2024                 problem = PR_2_BAD_SOCKET;
2025         else if (LINUX_S_ISLNK(inode.i_mode)
2026                  && !e2fsck_pass1_check_symlink(fs, ino, &inode, buf)) {
2027                 problem = PR_2_INVALID_SYMLINK;
2028         }
2029
2030         if (problem) {
2031                 if (fix_problem(ctx, problem, &pctx)) {
2032                         deallocate_inode(ctx, ino, 0);
2033                         if (ctx->flags & E2F_FLAG_SIGNAL_MASK)
2034                                 return 0;
2035                         return 1;
2036                 } else
2037                         not_fixed++;
2038                 problem = 0;
2039         }
2040
2041         if (inode.i_faddr) {
2042                 if (fix_problem(ctx, PR_2_FADDR_ZERO, &pctx)) {
2043                         inode.i_faddr = 0;
2044                         inode_modified++;
2045                 } else
2046                         not_fixed++;
2047         }
2048
2049         switch (fs->super->s_creator_os) {
2050             case EXT2_OS_HURD:
2051                 frag = &inode.osd2.hurd2.h_i_frag;
2052                 fsize = &inode.osd2.hurd2.h_i_fsize;
2053                 break;
2054             default:
2055                 frag = fsize = 0;
2056         }
2057         if (frag && *frag) {
2058                 pctx.num = *frag;
2059                 if (fix_problem(ctx, PR_2_FRAG_ZERO, &pctx)) {
2060                         *frag = 0;
2061                         inode_modified++;
2062                 } else
2063                         not_fixed++;
2064                 pctx.num = 0;
2065         }
2066         if (fsize && *fsize) {
2067                 pctx.num = *fsize;
2068                 if (fix_problem(ctx, PR_2_FSIZE_ZERO, &pctx)) {
2069                         *fsize = 0;
2070                         inode_modified++;
2071                 } else
2072                         not_fixed++;
2073                 pctx.num = 0;
2074         }
2075
2076         if ((fs->super->s_creator_os == EXT2_OS_LINUX) &&
2077             !ext2fs_has_feature_huge_file(fs->super) &&
2078             (inode.osd2.linux2.l_i_blocks_hi != 0)) {
2079                 pctx.num = inode.osd2.linux2.l_i_blocks_hi;
2080                 if (fix_problem(ctx, PR_2_BLOCKS_HI_ZERO, &pctx)) {
2081                         inode.osd2.linux2.l_i_blocks_hi = 0;
2082                         inode_modified++;
2083                 }
2084         }
2085
2086         if ((fs->super->s_creator_os == EXT2_OS_LINUX) &&
2087             !ext2fs_has_feature_64bit(fs->super) &&
2088             inode.osd2.linux2.l_i_file_acl_high != 0) {
2089                 pctx.num = inode.osd2.linux2.l_i_file_acl_high;
2090                 if (fix_problem(ctx, PR_2_I_FILE_ACL_HI_ZERO, &pctx)) {
2091                         inode.osd2.linux2.l_i_file_acl_high = 0;
2092                         inode_modified++;
2093                 } else
2094                         not_fixed++;
2095         }
2096
2097         if (ext2fs_file_acl_block(fs, &inode) &&
2098             ((ext2fs_file_acl_block(fs, &inode) < fs->super->s_first_data_block) ||
2099              (ext2fs_file_acl_block(fs, &inode) >= ext2fs_blocks_count(fs->super)))) {
2100                 if (fix_problem(ctx, PR_2_FILE_ACL_BAD, &pctx)) {
2101                         ext2fs_file_acl_block_set(fs, &inode, 0);
2102                         inode_modified++;
2103                 } else
2104                         not_fixed++;
2105         }
2106         if (inode.i_size_high && !ext2fs_has_feature_largedir(fs->super) &&
2107             inode.i_blocks < 1ULL << (29 - EXT2_BLOCK_SIZE_BITS(fs->super)) &&
2108             LINUX_S_ISDIR(inode.i_mode)) {
2109                 if (fix_problem(ctx, PR_2_DIR_SIZE_HIGH_ZERO, &pctx)) {
2110                         inode.i_size_high = 0;
2111                         inode_modified++;
2112                 } else
2113                         not_fixed++;
2114         }
2115
2116         if (inode_modified)
2117                 e2fsck_write_inode(ctx, ino, &inode, "process_bad_inode");
2118         if (!not_fixed && ctx->inode_bad_map)
2119                 ext2fs_unmark_inode_bitmap2(ctx->inode_bad_map, ino);
2120         return 0;
2121 }
2122
2123 /*
2124  * allocate_dir_block --- this function allocates a new directory
2125  *      block for a particular inode; this is done if a directory has
2126  *      a "hole" in it, or if a directory has a illegal block number
2127  *      that was zeroed out and now needs to be replaced.
2128  */
2129 static int allocate_dir_block(e2fsck_t ctx,
2130                               struct ext2_db_entry2 *db,
2131                               char *buf EXT2FS_ATTR((unused)),
2132                               struct problem_context *pctx)
2133 {
2134         ext2_filsys fs = ctx->fs;
2135         blk64_t                 blk = 0;
2136         char                    *block;
2137         struct ext2_inode       inode;
2138
2139         if (fix_problem(ctx, PR_2_DIRECTORY_HOLE, pctx) == 0)
2140                 return 1;
2141
2142         /*
2143          * Read the inode and block bitmaps in; we'll be messing with
2144          * them.
2145          */
2146         e2fsck_read_bitmaps(ctx);
2147
2148         /*
2149          * First, find a free block
2150          */
2151         e2fsck_read_inode(ctx, db->ino, &inode, "allocate_dir_block");
2152         pctx->errcode = ext2fs_map_cluster_block(fs, db->ino, &inode,
2153                                                  db->blockcnt, &blk);
2154         if (pctx->errcode || blk == 0) {
2155                 blk = ext2fs_find_inode_goal(fs, db->ino, &inode, db->blockcnt);
2156                 pctx->errcode = ext2fs_new_block2(fs, blk,
2157                                                   ctx->block_found_map, &blk);
2158                 if (pctx->errcode) {
2159                         pctx->str = "ext2fs_new_block";
2160                         fix_problem(ctx, PR_2_ALLOC_DIRBOCK, pctx);
2161                         return 1;
2162                 }
2163         }
2164         ext2fs_mark_block_bitmap2(ctx->block_found_map, blk);
2165         ext2fs_mark_block_bitmap2(fs->block_map, blk);
2166         ext2fs_mark_bb_dirty(fs);
2167
2168         /*
2169          * Now let's create the actual data block for the inode
2170          */
2171         if (db->blockcnt)
2172                 pctx->errcode = ext2fs_new_dir_block(fs, 0, 0, &block);
2173         else
2174                 pctx->errcode = ext2fs_new_dir_block(fs, db->ino,
2175                                                      EXT2_ROOT_INO, &block);
2176
2177         if (pctx->errcode) {
2178                 pctx->str = "ext2fs_new_dir_block";
2179                 fix_problem(ctx, PR_2_ALLOC_DIRBOCK, pctx);
2180                 return 1;
2181         }
2182
2183         pctx->errcode = ext2fs_write_dir_block4(fs, blk, block, 0, db->ino);
2184         ext2fs_free_mem(&block);
2185         if (pctx->errcode) {
2186                 pctx->str = "ext2fs_write_dir_block";
2187                 fix_problem(ctx, PR_2_ALLOC_DIRBOCK, pctx);
2188                 return 1;
2189         }
2190
2191         /*
2192          * Update the inode block count
2193          */
2194         ext2fs_iblk_add_blocks(fs, &inode, 1);
2195         if (EXT2_I_SIZE(&inode) < ((__u64) db->blockcnt+1) * fs->blocksize) {
2196                 pctx->errcode = ext2fs_inode_size_set(fs, &inode,
2197                                         (db->blockcnt+1) * fs->blocksize);
2198                 if (pctx->errcode) {
2199                         pctx->str = "ext2fs_inode_size_set";
2200                         fix_problem(ctx, PR_2_ALLOC_DIRBOCK, pctx);
2201                         return 1;
2202                 }
2203         }
2204         e2fsck_write_inode(ctx, db->ino, &inode, "allocate_dir_block");
2205
2206         /*
2207          * Finally, update the block pointers for the inode
2208          */
2209         db->blk = blk;
2210         pctx->errcode = ext2fs_bmap2(fs, db->ino, &inode, 0, BMAP_SET,
2211                                      db->blockcnt, 0, &blk);
2212         if (pctx->errcode) {
2213                 pctx->str = "ext2fs_block_iterate";
2214                 fix_problem(ctx, PR_2_ALLOC_DIRBOCK, pctx);
2215                 return 1;
2216         }
2217
2218         return 0;
2219 }