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