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