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