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