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