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