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