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