Whamcloud - gitweb
Merge branch 'maint' into next
[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, *dx_parent;
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) & 0x0ffffff;
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 & 0x0ffffff) : 0;
668
669                 if (hash < min_hash)
670                         min_hash = hash;
671                 if (hash > max_hash)
672                         max_hash = hash;
673                 dx_db->node_min_hash = hash;
674                 if ((i+1) < count)
675                         dx_db->node_max_hash =
676                           ext2fs_le32_to_cpu(ent[i+1].hash) & ~1;
677                 else {
678                         dx_db->node_max_hash = 0xfffffffe;
679                         dx_db->flags |= DX_FLAG_LAST;
680                 }
681                 if (i == 0)
682                         dx_db->flags |= DX_FLAG_FIRST;
683         }
684 #ifdef DX_DEBUG
685         printf("Blockcnt = %d, min hash 0x%08x, max hash 0x%08x\n",
686                db->blockcnt, min_hash, max_hash);
687 #endif
688         dx_db = &dx_dir->dx_block[db->blockcnt];
689         dx_db->min_hash = min_hash;
690         dx_db->max_hash = max_hash;
691         return;
692
693 clear_and_exit:
694         clear_htree(cd->ctx, cd->pctx.ino);
695         dx_dir->numblocks = 0;
696         e2fsck_rehash_dir_later(cd->ctx, cd->pctx.ino);
697 }
698
699 /*
700  * Given a busted directory, try to salvage it somehow.
701  *
702  */
703 static void salvage_directory(ext2_filsys fs,
704                               struct ext2_dir_entry *dirent,
705                               struct ext2_dir_entry *prev,
706                               unsigned int *offset,
707                               unsigned int block_len)
708 {
709         char    *cp = (char *) dirent;
710         int left;
711         unsigned int rec_len, prev_rec_len;
712         unsigned int name_len;
713
714         /*
715          * If the space left for the entry is too small to be an entry,
716          * we can't access dirent's fields, so plumb in the values needed
717          * so that the previous entry absorbs this one.
718          */
719         if (block_len - *offset < EXT2_DIR_ENTRY_HEADER_LEN) {
720                 name_len = 0;
721                 rec_len = block_len - *offset;
722         } else {
723                 name_len = ext2fs_dirent_name_len(dirent);
724                 (void) ext2fs_get_rec_len(fs, dirent, &rec_len);
725         }
726         left = block_len - *offset - rec_len;
727
728         /*
729          * Special case of directory entry of size 8: copy what's left
730          * of the directory block up to cover up the invalid hole.
731          */
732         if ((left >= 12) && (rec_len == EXT2_DIR_ENTRY_HEADER_LEN)) {
733                 memmove(cp, cp+EXT2_DIR_ENTRY_HEADER_LEN, left);
734                 memset(cp + left, 0, EXT2_DIR_ENTRY_HEADER_LEN);
735                 return;
736         }
737         /*
738          * If the directory entry overruns the end of the directory
739          * block, and the name is small enough to fit, then adjust the
740          * record length.
741          */
742         if ((left < 0) &&
743             ((int) rec_len + left > EXT2_DIR_ENTRY_HEADER_LEN) &&
744             ((int) name_len + EXT2_DIR_ENTRY_HEADER_LEN <= (int) rec_len + left) &&
745             dirent->inode <= fs->super->s_inodes_count &&
746             strnlen(dirent->name, name_len) == name_len) {
747                 (void) ext2fs_set_rec_len(fs, (int) rec_len + left, dirent);
748                 return;
749         }
750         /*
751          * If the record length of the directory entry is a multiple
752          * of four, and not too big, such that it is valid, let the
753          * previous directory entry absorb the invalid one.
754          */
755         if (prev && rec_len && (rec_len % 4) == 0 &&
756             (*offset + rec_len <= block_len)) {
757                 (void) ext2fs_get_rec_len(fs, prev, &prev_rec_len);
758                 prev_rec_len += rec_len;
759                 (void) ext2fs_set_rec_len(fs, prev_rec_len, prev);
760                 *offset += rec_len;
761                 return;
762         }
763         /*
764          * Default salvage method --- kill all of the directory
765          * entries for the rest of the block.  We will either try to
766          * absorb it into the previous directory entry, or create a
767          * new empty directory entry the rest of the directory block.
768          */
769         if (prev) {
770                 (void) ext2fs_get_rec_len(fs, prev, &prev_rec_len);
771                 prev_rec_len += block_len - *offset;
772                 (void) ext2fs_set_rec_len(fs, prev_rec_len, prev);
773                 *offset = fs->blocksize;
774         } else {
775                 rec_len = block_len - *offset;
776                 (void) ext2fs_set_rec_len(fs, rec_len, dirent);
777                 ext2fs_dirent_set_name_len(dirent, 0);
778                 ext2fs_dirent_set_file_type(dirent, EXT2_FT_UNKNOWN);
779                 dirent->inode = 0;
780         }
781 }
782
783 #define NEXT_DIRENT(d)  ((void *)((char *)(d) + (d)->rec_len))
784 static errcode_t insert_dirent_tail(ext2_filsys fs, void *dirbuf)
785 {
786         struct ext2_dir_entry *d;
787         void *top;
788         struct ext2_dir_entry_tail *t;
789
790         d = dirbuf;
791         top = EXT2_DIRENT_TAIL(dirbuf, fs->blocksize);
792
793         while (d->rec_len && !(d->rec_len & 0x3) && NEXT_DIRENT(d) <= top)
794                 d = NEXT_DIRENT(d);
795
796         if (d != top) {
797                 unsigned int min_size = EXT2_DIR_REC_LEN(
798                                 ext2fs_dirent_name_len(dirbuf));
799                 if (min_size > (char *)top - (char *)d)
800                         return EXT2_ET_DIR_NO_SPACE_FOR_CSUM;
801                 d->rec_len = (char *)top - (char *)d;
802         }
803
804         t = (struct ext2_dir_entry_tail *)top;
805         if (t->det_reserved_zero1 ||
806             t->det_rec_len != sizeof(struct ext2_dir_entry_tail) ||
807             t->det_reserved_name_len != EXT2_DIR_NAME_LEN_CSUM)
808                 ext2fs_initialize_dirent_tail(fs, t);
809
810         return 0;
811 }
812 #undef NEXT_DIRENT
813
814 static errcode_t fix_inline_dir_size(e2fsck_t ctx, ext2_ino_t ino,
815                                      size_t *inline_data_size,
816                                      struct problem_context *pctx,
817                                      char *buf)
818 {
819         ext2_filsys fs = ctx->fs;
820         struct ext2_inode inode;
821         size_t new_size, old_size;
822         errcode_t retval;
823
824         old_size = *inline_data_size;
825         /*
826          * If there's not enough bytes to start the "second" dir block
827          * (in the EA space) then truncate everything to the first block.
828          */
829         if (old_size > EXT4_MIN_INLINE_DATA_SIZE &&
830             old_size < EXT4_MIN_INLINE_DATA_SIZE +
831                        EXT2_DIR_REC_LEN(1)) {
832                 old_size = EXT4_MIN_INLINE_DATA_SIZE;
833                 new_size = old_size;
834         } else
835                 /* Increase to the next four-byte boundary for salvaging */
836                 new_size = old_size + (4 - (old_size & 3));
837         memset(buf + old_size, 0, new_size - old_size);
838         retval = ext2fs_inline_data_set(fs, ino, 0, buf, new_size);
839         if (retval == EXT2_ET_INLINE_DATA_NO_SPACE) {
840                 /* Or we can't, so truncate. */
841                 new_size -= 4;
842                 retval = ext2fs_inline_data_set(fs, ino, 0, buf, new_size);
843                 if (retval) {
844                         if (fix_problem(ctx, PR_2_FIX_INLINE_DIR_FAILED,
845                                         pctx)) {
846                                 new_size = 0;
847                                 goto write_inode;
848                         }
849                         goto err;
850                 }
851         } else if (retval) {
852                 if (fix_problem(ctx, PR_2_FIX_INLINE_DIR_FAILED,
853                                 pctx)) {
854                         new_size = 0;
855                         goto write_inode;
856                 }
857                 goto err;
858         }
859
860 write_inode:
861         retval = ext2fs_read_inode(fs, ino, &inode);
862         if (retval)
863                 goto err;
864
865         retval = ext2fs_inode_size_set(fs, &inode, new_size);
866         if (retval)
867                 goto err;
868         if (new_size == 0)
869                 inode.i_flags &= ~EXT4_INLINE_DATA_FL;
870         retval = ext2fs_write_inode(fs, ino, &inode);
871         if (retval)
872                 goto err;
873         *inline_data_size = new_size;
874
875 err:
876         return retval;
877 }
878
879 static int check_dir_block2(ext2_filsys fs,
880                            struct ext2_db_entry2 *db,
881                            void *priv_data)
882 {
883         int err;
884         struct check_dir_struct *cd = priv_data;
885
886         if (cd->ra_entries && cd->list_offset >= cd->next_ra_off) {
887                 err = e2fsck_readahead_dblist(fs,
888                                         E2FSCK_RA_DBLIST_IGNORE_BLOCKCNT,
889                                         fs->dblist,
890                                         cd->list_offset + cd->ra_entries / 8,
891                                         cd->ra_entries);
892                 if (err)
893                         cd->ra_entries = 0;
894                 cd->next_ra_off = cd->list_offset + (cd->ra_entries * 7 / 8);
895         }
896
897         err = check_dir_block(fs, db, priv_data);
898         cd->list_offset++;
899         return err;
900 }
901
902 static int check_dir_block(ext2_filsys fs,
903                            struct ext2_db_entry2 *db,
904                            void *priv_data)
905 {
906         struct dx_dir_info      *dx_dir;
907         struct dx_dirblock_info *dx_db = 0;
908         struct ext2_dir_entry   *dirent, *prev, dot, dotdot;
909         ext2_dirhash_t          hash;
910         unsigned int            offset = 0;
911         int                     dir_modified = 0;
912         int                     dot_state;
913         unsigned int            rec_len;
914         blk64_t                 block_nr = db->blk;
915         ext2_ino_t              ino = db->ino;
916         ext2_ino_t              subdir_parent;
917         __u16                   links;
918         struct check_dir_struct *cd;
919         char                    *buf, *ibuf;
920         e2fsck_t                ctx;
921         problem_t               problem;
922         struct ext2_dx_root_info *root;
923         struct ext2_dx_countlimit *limit;
924         static dict_t de_dict;
925         struct problem_context  pctx;
926         int     dups_found = 0;
927         int     ret;
928         int     dx_csum_size = 0, de_csum_size = 0;
929         int     failed_csum = 0;
930         int     is_leaf = 1;
931         size_t  inline_data_size = 0;
932         int     filetype = 0;
933         int     encrypted = 0;
934         size_t  max_block_size;
935
936         cd = (struct check_dir_struct *) priv_data;
937         ibuf = buf = cd->buf;
938         ctx = cd->ctx;
939
940         if (ctx->flags & E2F_FLAG_RUN_RETURN)
941                 return DIRENT_ABORT;
942
943         if (ctx->progress && (ctx->progress)(ctx, 2, cd->count++, cd->max))
944                 return DIRENT_ABORT;
945
946         if (ext2fs_has_feature_metadata_csum(fs->super)) {
947                 dx_csum_size = sizeof(struct ext2_dx_tail);
948                 de_csum_size = sizeof(struct ext2_dir_entry_tail);
949         }
950
951         if (ext2fs_has_feature_filetype(fs->super))
952                 filetype = EXT2_FT_DIR << 8;
953
954         /*
955          * Make sure the inode is still in use (could have been
956          * deleted in the duplicate/bad blocks pass.
957          */
958         if (!(ext2fs_test_inode_bitmap2(ctx->inode_used_map, ino)))
959                 return 0;
960
961         cd->pctx.ino = ino;
962         cd->pctx.blk = block_nr;
963         cd->pctx.blkcount = db->blockcnt;
964         cd->pctx.ino2 = 0;
965         cd->pctx.dirent = 0;
966         cd->pctx.num = 0;
967
968         if (ext2fs_has_feature_inline_data(fs->super)) {
969                 errcode_t ec;
970
971                 ec = ext2fs_inline_data_size(fs, ino, &inline_data_size);
972                 if (ec && ec != EXT2_ET_NO_INLINE_DATA)
973                         return DIRENT_ABORT;
974         }
975
976         /* This will allow (at some point in the future) to punch out empty
977          * directory blocks and reduce the space used by a directory that grows
978          * very large and then the files are deleted. For now, all that is
979          * needed is to avoid e2fsck filling in these holes as part of
980          * feature flag. */
981         if (db->blk == 0 && ext2fs_has_feature_largedir(fs->super))
982                 return 0;
983
984         if (db->blk == 0 && !inline_data_size) {
985                 if (allocate_dir_block(ctx, db, buf, &cd->pctx))
986                         return 0;
987                 block_nr = db->blk;
988         }
989
990         if (db->blockcnt)
991                 dot_state = 2;
992         else
993                 dot_state = 0;
994
995         if (ctx->dirs_to_hash &&
996             ext2fs_u32_list_test(ctx->dirs_to_hash, ino))
997                 dups_found++;
998
999 #if 0
1000         printf("In process_dir_block block %lu, #%d, inode %lu\n", block_nr,
1001                db->blockcnt, ino);
1002 #endif
1003
1004         ehandler_operation(_("reading directory block"));
1005         if (inline_data_size) {
1006                 memset(buf, 0, fs->blocksize - inline_data_size);
1007                 cd->pctx.errcode = ext2fs_inline_data_get(fs, ino, 0, buf, 0);
1008                 if (cd->pctx.errcode)
1009                         goto inline_read_fail;
1010 #ifdef WORDS_BIGENDIAN
1011                 if (db->blockcnt)
1012                         goto skip_first_read_swab;
1013                 *((__u32 *)buf) = ext2fs_le32_to_cpu(*((__u32 *)buf));
1014                 cd->pctx.errcode = ext2fs_dirent_swab_in2(fs,
1015                                 buf + EXT4_INLINE_DATA_DOTDOT_SIZE,
1016                                 EXT4_MIN_INLINE_DATA_SIZE - EXT4_INLINE_DATA_DOTDOT_SIZE,
1017                                 0);
1018                 if (cd->pctx.errcode)
1019                         goto inline_read_fail;
1020 skip_first_read_swab:
1021                 if (inline_data_size <= EXT4_MIN_INLINE_DATA_SIZE ||
1022                     !db->blockcnt)
1023                         goto inline_read_fail;
1024                 cd->pctx.errcode = ext2fs_dirent_swab_in2(fs,
1025                                 buf + EXT4_MIN_INLINE_DATA_SIZE,
1026                                 inline_data_size - EXT4_MIN_INLINE_DATA_SIZE,
1027                                 0);
1028 #endif
1029         } else
1030                 cd->pctx.errcode = ext2fs_read_dir_block4(fs, block_nr,
1031                                                           buf, 0, ino);
1032 inline_read_fail:
1033         pctx.ino = ino;
1034         pctx.num = inline_data_size;
1035         if (((inline_data_size & 3) ||
1036              (inline_data_size > EXT4_MIN_INLINE_DATA_SIZE &&
1037               inline_data_size < EXT4_MIN_INLINE_DATA_SIZE +
1038                                  EXT2_DIR_REC_LEN(1))) &&
1039             fix_problem(ctx, PR_2_BAD_INLINE_DIR_SIZE, &pctx)) {
1040                 errcode_t err = fix_inline_dir_size(ctx, ino,
1041                                                     &inline_data_size, &pctx,
1042                                                     buf);
1043                 if (err)
1044                         return DIRENT_ABORT;
1045
1046         }
1047         ehandler_operation(0);
1048         if (cd->pctx.errcode == EXT2_ET_DIR_CORRUPTED)
1049                 cd->pctx.errcode = 0; /* We'll handle this ourselves */
1050         else if (cd->pctx.errcode == EXT2_ET_DIR_CSUM_INVALID) {
1051                 cd->pctx.errcode = 0; /* We'll handle this ourselves */
1052                 failed_csum = 1;
1053         }
1054         if (cd->pctx.errcode) {
1055                 char *buf2;
1056                 if (!fix_problem(ctx, PR_2_READ_DIRBLOCK, &cd->pctx)) {
1057                         ctx->flags |= E2F_FLAG_ABORT;
1058                         return DIRENT_ABORT;
1059                 }
1060                 ext2fs_new_dir_block(fs, db->blockcnt == 0 ? ino : 0,
1061                                      EXT2_ROOT_INO, &buf2);
1062                 memcpy(buf, buf2, fs->blocksize);
1063                 ext2fs_free_mem(&buf2);
1064         }
1065         dx_dir = e2fsck_get_dx_dir_info(ctx, ino);
1066         if (dx_dir && dx_dir->numblocks) {
1067                 if (db->blockcnt >= dx_dir->numblocks) {
1068                         pctx.dir = ino;
1069                         if (fix_problem(ctx, PR_2_UNEXPECTED_HTREE_BLOCK,
1070                                         &pctx)) {
1071                                 clear_htree(ctx, ino);
1072                                 dx_dir->numblocks = 0;
1073                                 dx_db = 0;
1074                                 goto out_htree;
1075                         }
1076                         fatal_error(ctx, _("Can not continue."));
1077                 }
1078                 dx_db = &dx_dir->dx_block[db->blockcnt];
1079                 dx_db->type = DX_DIRBLOCK_LEAF;
1080                 dx_db->phys = block_nr;
1081                 dx_db->min_hash = ~0;
1082                 dx_db->max_hash = 0;
1083
1084                 dirent = (struct ext2_dir_entry *) buf;
1085                 (void) ext2fs_get_rec_len(fs, dirent, &rec_len);
1086                 limit = (struct ext2_dx_countlimit *) (buf+8);
1087                 if (db->blockcnt == 0) {
1088                         root = (struct ext2_dx_root_info *) (buf + 24);
1089                         dx_db->type = DX_DIRBLOCK_ROOT;
1090                         dx_db->flags |= DX_FLAG_FIRST | DX_FLAG_LAST;
1091                         if ((root->reserved_zero ||
1092                              root->info_length < 8 ||
1093                              root->indirect_levels >=
1094                              ext2_dir_htree_level(fs)) &&
1095                             fix_problem(ctx, PR_2_HTREE_BAD_ROOT, &cd->pctx)) {
1096                                 clear_htree(ctx, ino);
1097                                 dx_dir->numblocks = 0;
1098                                 dx_db = NULL;
1099                         }
1100                         dx_dir->hashversion = root->hash_version;
1101                         if ((dx_dir->hashversion <= EXT2_HASH_TEA) &&
1102                             (fs->super->s_flags & EXT2_FLAGS_UNSIGNED_HASH))
1103                                 dx_dir->hashversion += 3;
1104                         dx_dir->depth = root->indirect_levels + 1;
1105                 } else if ((dirent->inode == 0) &&
1106                            (rec_len == fs->blocksize) &&
1107                            (ext2fs_dirent_name_len(dirent) == 0) &&
1108                            (ext2fs_le16_to_cpu(limit->limit) ==
1109                             ((fs->blocksize - (8 + dx_csum_size)) /
1110                              sizeof(struct ext2_dx_entry)))) {
1111                         dx_db->type = DX_DIRBLOCK_NODE;
1112                 }
1113                 is_leaf = dx_db ? (dx_db->type == DX_DIRBLOCK_LEAF) : 0;
1114         }
1115 out_htree:
1116
1117         /* Leaf node with no space for csum?  Rebuild dirs in pass 3A. */
1118         if (is_leaf && !inline_data_size && failed_csum &&
1119             !ext2fs_dirent_has_tail(fs, (struct ext2_dir_entry *)buf)) {
1120                 de_csum_size = 0;
1121                 if (e2fsck_dir_will_be_rehashed(ctx, ino)) {
1122                         failed_csum = 0;
1123                         goto skip_checksum;
1124                 }
1125                 if (!fix_problem(cd->ctx, PR_2_LEAF_NODE_MISSING_CSUM,
1126                                  &cd->pctx))
1127                         goto skip_checksum;
1128                 e2fsck_rehash_dir_later(ctx, ino);
1129                 failed_csum = 0;
1130                 goto skip_checksum;
1131         }
1132         /* htree nodes don't use fake dirents to store checksums */
1133         if (!is_leaf)
1134                 de_csum_size = 0;
1135
1136 skip_checksum:
1137         if (inline_data_size) {
1138                 if (db->blockcnt) {
1139                         buf += EXT4_MIN_INLINE_DATA_SIZE;
1140                         max_block_size = inline_data_size - EXT4_MIN_INLINE_DATA_SIZE;
1141                         /* Zero-length second block, just exit */
1142                         if (max_block_size == 0)
1143                                 return 0;
1144                 } else {
1145                         max_block_size = EXT4_MIN_INLINE_DATA_SIZE;
1146                 }
1147         } else
1148                 max_block_size = fs->blocksize - de_csum_size;
1149
1150         if (ctx->encrypted_dirs)
1151                 encrypted = ext2fs_u32_list_test(ctx->encrypted_dirs, ino);
1152
1153         dict_init(&de_dict, DICTCOUNT_T_MAX, dict_de_cmp);
1154         prev = 0;
1155         do {
1156                 dgrp_t group;
1157                 ext2_ino_t first_unused_inode;
1158                 unsigned int name_len;
1159
1160                 problem = 0;
1161                 if (!inline_data_size || dot_state > 1) {
1162                         dirent = (struct ext2_dir_entry *) (buf + offset);
1163                         /*
1164                          * If there's not even space for the entry header,
1165                          * force salvaging this dir.
1166                          */
1167                         if (max_block_size - offset < EXT2_DIR_ENTRY_HEADER_LEN)
1168                                 rec_len = EXT2_DIR_REC_LEN(1);
1169                         else
1170                                 (void) ext2fs_get_rec_len(fs, dirent, &rec_len);
1171                         cd->pctx.dirent = dirent;
1172                         cd->pctx.num = offset;
1173                         if ((offset + rec_len > max_block_size) ||
1174                             (rec_len < 12) ||
1175                             ((rec_len % 4) != 0) ||
1176                             (((unsigned) ext2fs_dirent_name_len(dirent) + EXT2_DIR_ENTRY_HEADER_LEN) > rec_len)) {
1177                                 if (fix_problem(ctx, PR_2_DIR_CORRUPTED,
1178                                                 &cd->pctx)) {
1179 #ifdef WORDS_BIGENDIAN
1180                                         /*
1181                                          * On big-endian systems, if the dirent
1182                                          * swap routine finds a rec_len that it
1183                                          * doesn't like, it continues
1184                                          * processing the block as if rec_len
1185                                          * == EXT2_DIR_ENTRY_HEADER_LEN.  This means that the name
1186                                          * field gets byte swapped, which means
1187                                          * that salvage will not detect the
1188                                          * correct name length (unless the name
1189                                          * has a length that's an exact
1190                                          * multiple of four bytes), and it'll
1191                                          * discard the entry (unnecessarily)
1192                                          * and the rest of the dirent block.
1193                                          * Therefore, swap the rest of the
1194                                          * block back to disk order, run
1195                                          * salvage, and re-swap anything after
1196                                          * the salvaged dirent.
1197                                          */
1198                                         int need_reswab = 0;
1199                                         if (rec_len < EXT2_DIR_ENTRY_HEADER_LEN || rec_len % 4) {
1200                                                 need_reswab = 1;
1201                                                 ext2fs_dirent_swab_in2(fs,
1202                                                         ((char *)dirent) + EXT2_DIR_ENTRY_HEADER_LEN,
1203                                                         max_block_size - offset - EXT2_DIR_ENTRY_HEADER_LEN,
1204                                                         0);
1205                                         }
1206 #endif
1207                                         salvage_directory(fs, dirent, prev,
1208                                                           &offset,
1209                                                           max_block_size);
1210 #ifdef WORDS_BIGENDIAN
1211                                         if (need_reswab) {
1212                                                 (void) ext2fs_get_rec_len(fs,
1213                                                         dirent, &rec_len);
1214                                                 ext2fs_dirent_swab_in2(fs,
1215                                                         ((char *)dirent) + offset + rec_len,
1216                                                         max_block_size - offset - rec_len,
1217                                                         0);
1218                                         }
1219 #endif
1220                                         dir_modified++;
1221                                         continue;
1222                                 } else
1223                                         goto abort_free_dict;
1224                         }
1225                 } else {
1226                         if (dot_state == 0) {
1227                                 memset(&dot, 0, sizeof(dot));
1228                                 dirent = &dot;
1229                                 dirent->inode = ino;
1230                                 dirent->rec_len = EXT2_DIR_REC_LEN(1);
1231                                 dirent->name_len = 1 | filetype;
1232                                 dirent->name[0] = '.';
1233                         } else if (dot_state == 1) {
1234                                 memset(&dotdot, 0, sizeof(dotdot));
1235                                 dirent = &dotdot;
1236                                 dirent->inode =
1237                                         ((struct ext2_dir_entry *)buf)->inode;
1238                                 dirent->rec_len = EXT2_DIR_REC_LEN(2);
1239                                 dirent->name_len = 2 | filetype;
1240                                 dirent->name[0] = '.';
1241                                 dirent->name[1] = '.';
1242                         } else {
1243                                 fatal_error(ctx, _("Can not continue."));
1244                         }
1245                         cd->pctx.dirent = dirent;
1246                         cd->pctx.num = offset;
1247                 }
1248
1249                 if (dot_state == 0) {
1250                         if (check_dot(ctx, dirent, ino, &cd->pctx))
1251                                 dir_modified++;
1252                 } else if (dot_state == 1) {
1253                         ret = check_dotdot(ctx, dirent, ino, &cd->pctx);
1254                         if (ret < 0)
1255                                 goto abort_free_dict;
1256                         if (ret)
1257                                 dir_modified++;
1258                 } else if (dirent->inode == ino) {
1259                         problem = PR_2_LINK_DOT;
1260                         if (fix_problem(ctx, PR_2_LINK_DOT, &cd->pctx)) {
1261                                 dirent->inode = 0;
1262                                 dir_modified++;
1263                                 goto next;
1264                         }
1265                 }
1266                 if (!dirent->inode)
1267                         goto next;
1268
1269                 /*
1270                  * Make sure the inode listed is a legal one.
1271                  */
1272                 name_len = ext2fs_dirent_name_len(dirent);
1273                 if (((dirent->inode != EXT2_ROOT_INO) &&
1274                      (dirent->inode < EXT2_FIRST_INODE(fs->super))) ||
1275                     (dirent->inode > fs->super->s_inodes_count)) {
1276                         problem = PR_2_BAD_INO;
1277                 } else if (ctx->inode_bb_map &&
1278                            (ext2fs_test_inode_bitmap2(ctx->inode_bb_map,
1279                                                      dirent->inode))) {
1280                         /*
1281                          * If the inode is in a bad block, offer to
1282                          * clear it.
1283                          */
1284                         problem = PR_2_BB_INODE;
1285                 } else if ((dot_state > 1) && (name_len == 1) &&
1286                            (dirent->name[0] == '.')) {
1287                         /*
1288                          * If there's a '.' entry in anything other
1289                          * than the first directory entry, it's a
1290                          * duplicate entry that should be removed.
1291                          */
1292                         problem = PR_2_DUP_DOT;
1293                 } else if ((dot_state > 1) && (name_len == 2) &&
1294                            (dirent->name[0] == '.') &&
1295                            (dirent->name[1] == '.')) {
1296                         /*
1297                          * If there's a '..' entry in anything other
1298                          * than the second directory entry, it's a
1299                          * duplicate entry that should be removed.
1300                          */
1301                         problem = PR_2_DUP_DOT_DOT;
1302                 } else if ((dot_state > 1) &&
1303                            (dirent->inode == EXT2_ROOT_INO)) {
1304                         /*
1305                          * Don't allow links to the root directory.
1306                          * We check this specially to make sure we
1307                          * catch this error case even if the root
1308                          * directory hasn't been created yet.
1309                          */
1310                         problem = PR_2_LINK_ROOT;
1311                 } else if ((dot_state > 1) && (name_len == 0)) {
1312                         /*
1313                          * Don't allow zero-length directory names.
1314                          */
1315                         problem = PR_2_NULL_NAME;
1316                 }
1317
1318                 if (problem) {
1319                         if (fix_problem(ctx, problem, &cd->pctx)) {
1320                                 dirent->inode = 0;
1321                                 dir_modified++;
1322                                 goto next;
1323                         } else {
1324                                 ext2fs_unmark_valid(fs);
1325                                 if (problem == PR_2_BAD_INO)
1326                                         goto next;
1327                         }
1328                 }
1329
1330                 /*
1331                  * If the inode was marked as having bad fields in
1332                  * pass1, process it and offer to fix/clear it.
1333                  * (We wait until now so that we can display the
1334                  * pathname to the user.)
1335                  */
1336                 if (ctx->inode_bad_map &&
1337                     ext2fs_test_inode_bitmap2(ctx->inode_bad_map,
1338                                              dirent->inode)) {
1339                         if (e2fsck_process_bad_inode(ctx, ino,
1340                                                      dirent->inode,
1341                                                      buf + fs->blocksize)) {
1342                                 dirent->inode = 0;
1343                                 dir_modified++;
1344                                 goto next;
1345                         }
1346                         if (ctx->flags & E2F_FLAG_SIGNAL_MASK)
1347                                 return DIRENT_ABORT;
1348                 }
1349
1350                 group = ext2fs_group_of_ino(fs, dirent->inode);
1351                 first_unused_inode = group * fs->super->s_inodes_per_group +
1352                                         1 + fs->super->s_inodes_per_group -
1353                                         ext2fs_bg_itable_unused(fs, group);
1354                 cd->pctx.group = group;
1355
1356                 /*
1357                  * Check if the inode was missed out because
1358                  * _INODE_UNINIT flag was set or bg_itable_unused was
1359                  * incorrect.  If so, clear the _INODE_UNINIT flag and
1360                  * restart e2fsck.  In the future it would be nice if
1361                  * we could call a function in pass1.c that checks the
1362                  * newly visible inodes.
1363                  */
1364                 if (ext2fs_bg_flags_test(fs, group, EXT2_BG_INODE_UNINIT)) {
1365                         pctx.num = dirent->inode;
1366                         if (fix_problem(ctx, PR_2_INOREF_BG_INO_UNINIT,
1367                                         &cd->pctx)){
1368                                 ext2fs_bg_flags_clear(fs, group,
1369                                                       EXT2_BG_INODE_UNINIT);
1370                                 ext2fs_mark_super_dirty(fs);
1371                                 ctx->flags |= E2F_FLAG_RESTART_LATER;
1372                         } else {
1373                                 ext2fs_unmark_valid(fs);
1374                                 if (problem == PR_2_BAD_INO)
1375                                         goto next;
1376                         }
1377                 } else if (dirent->inode >= first_unused_inode) {
1378                         pctx.num = dirent->inode;
1379                         if (fix_problem(ctx, PR_2_INOREF_IN_UNUSED, &cd->pctx)){
1380                                 ext2fs_bg_itable_unused_set(fs, group, 0);
1381                                 ext2fs_mark_super_dirty(fs);
1382                                 ctx->flags |= E2F_FLAG_RESTART_LATER;
1383                         } else {
1384                                 ext2fs_unmark_valid(fs);
1385                                 if (problem == PR_2_BAD_INO)
1386                                         goto next;
1387                         }
1388                 }
1389
1390                 /* 
1391                  * Offer to clear unused inodes; if we are going to be
1392                  * restarting the scan due to bg_itable_unused being
1393                  * wrong, then don't clear any inodes to avoid zapping
1394                  * inodes that were skipped during pass1 due to an
1395                  * incorrect bg_itable_unused; we'll get any real
1396                  * problems after we restart.
1397                  */
1398                 if (!(ctx->flags & E2F_FLAG_RESTART_LATER) &&
1399                     !(ext2fs_test_inode_bitmap2(ctx->inode_used_map,
1400                                                 dirent->inode)))
1401                         problem = PR_2_UNUSED_INODE;
1402
1403                 if (problem) {
1404                         if (fix_problem(ctx, problem, &cd->pctx)) {
1405                                 dirent->inode = 0;
1406                                 dir_modified++;
1407                                 goto next;
1408                         } else {
1409                                 ext2fs_unmark_valid(fs);
1410                                 if (problem == PR_2_BAD_INO)
1411                                         goto next;
1412                         }
1413                 }
1414
1415                 if (!encrypted && check_name(ctx, dirent, &cd->pctx))
1416                         dir_modified++;
1417
1418                 if (encrypted && (dot_state) > 1 &&
1419                     encrypted_check_name(ctx, dirent, &cd->pctx)) {
1420                         dir_modified++;
1421                         goto next;
1422                 }
1423
1424                 if (check_filetype(ctx, dirent, ino, &cd->pctx))
1425                         dir_modified++;
1426
1427                 if (dx_db) {
1428                         ext2fs_dirhash(dx_dir->hashversion, dirent->name,
1429                                        ext2fs_dirent_name_len(dirent),
1430                                        fs->super->s_hash_seed, &hash, 0);
1431                         if (hash < dx_db->min_hash)
1432                                 dx_db->min_hash = hash;
1433                         if (hash > dx_db->max_hash)
1434                                 dx_db->max_hash = hash;
1435                 }
1436
1437                 /*
1438                  * If this is a directory, then mark its parent in its
1439                  * dir_info structure.  If the parent field is already
1440                  * filled in, then this directory has more than one
1441                  * hard link.  We assume the first link is correct,
1442                  * and ask the user if he/she wants to clear this one.
1443                  */
1444                 if ((dot_state > 1) &&
1445                     (ext2fs_test_inode_bitmap2(ctx->inode_dir_map,
1446                                               dirent->inode))) {
1447                         if (e2fsck_dir_info_get_parent(ctx, dirent->inode,
1448                                                        &subdir_parent)) {
1449                                 cd->pctx.ino = dirent->inode;
1450                                 fix_problem(ctx, PR_2_NO_DIRINFO, &cd->pctx);
1451                                 goto abort_free_dict;
1452                         }
1453                         if (subdir_parent) {
1454                                 cd->pctx.ino2 = subdir_parent;
1455                                 if (fix_problem(ctx, PR_2_LINK_DIR,
1456                                                 &cd->pctx)) {
1457                                         dirent->inode = 0;
1458                                         dir_modified++;
1459                                         goto next;
1460                                 }
1461                                 cd->pctx.ino2 = 0;
1462                         } else {
1463                                 (void) e2fsck_dir_info_set_parent(ctx,
1464                                                   dirent->inode, ino);
1465                         }
1466                 }
1467
1468                 if (dups_found) {
1469                         ;
1470                 } else if (dict_lookup(&de_dict, dirent)) {
1471                         clear_problem_context(&pctx);
1472                         pctx.ino = ino;
1473                         pctx.dirent = dirent;
1474                         fix_problem(ctx, PR_2_REPORT_DUP_DIRENT, &pctx);
1475                         e2fsck_rehash_dir_later(ctx, ino);
1476                         dups_found++;
1477                 } else
1478                         dict_alloc_insert(&de_dict, dirent, dirent);
1479
1480                 ext2fs_icount_increment(ctx->inode_count, dirent->inode,
1481                                         &links);
1482                 if (links > 1)
1483                         ctx->fs_links_count++;
1484                 ctx->fs_total_count++;
1485         next:
1486                 prev = dirent;
1487                 if (dir_modified)
1488                         (void) ext2fs_get_rec_len(fs, dirent, &rec_len);
1489                 if (!inline_data_size || dot_state > 1) {
1490                         offset += rec_len;
1491                 } else {
1492                         if (dot_state == 1) {
1493                                 offset = 4;
1494                                 /*
1495                                  * If we get here, we're checking an inline
1496                                  * directory and we've just checked a (fake)
1497                                  * dotdot entry that we created on the stack.
1498                                  * Therefore set 'prev' to NULL so that if we
1499                                  * call salvage_directory on the next entry,
1500                                  * it won't try to absorb the next entry into
1501                                  * the on-stack dotdot entry.
1502                                  */
1503                                 prev = NULL;
1504                         }
1505                 }
1506                 dot_state++;
1507         } while (offset < max_block_size);
1508 #if 0
1509         printf("\n");
1510 #endif
1511         if (dx_db) {
1512 #ifdef DX_DEBUG
1513                 printf("db_block %d, type %d, min_hash 0x%0x, max_hash 0x%0x\n",
1514                        db->blockcnt, dx_db->type,
1515                        dx_db->min_hash, dx_db->max_hash);
1516 #endif
1517                 cd->pctx.dir = cd->pctx.ino;
1518                 if ((dx_db->type == DX_DIRBLOCK_ROOT) ||
1519                     (dx_db->type == DX_DIRBLOCK_NODE))
1520                         parse_int_node(fs, db, cd, dx_dir, buf, failed_csum);
1521         }
1522
1523         if (offset != max_block_size) {
1524                 cd->pctx.num = rec_len + offset - max_block_size;
1525                 if (fix_problem(ctx, PR_2_FINAL_RECLEN, &cd->pctx)) {
1526                         dirent->rec_len = cd->pctx.num;
1527                         dir_modified++;
1528                 }
1529         }
1530         if (dir_modified) {
1531                 int     flags, will_rehash;
1532                 /* leaf block with no tail?  Rehash dirs later. */
1533                 if (ext2fs_has_feature_metadata_csum(fs->super) &&
1534                     is_leaf &&
1535                     !inline_data_size &&
1536                     !ext2fs_dirent_has_tail(fs, (struct ext2_dir_entry *)buf)) {
1537                         if (insert_dirent_tail(fs, buf) == 0)
1538                                 goto write_and_fix;
1539                         e2fsck_rehash_dir_later(ctx, ino);
1540                 }
1541
1542 write_and_fix:
1543                 will_rehash = e2fsck_dir_will_be_rehashed(ctx, ino);
1544                 if (will_rehash) {
1545                         flags = ctx->fs->flags;
1546                         ctx->fs->flags |= EXT2_FLAG_IGNORE_CSUM_ERRORS;
1547                 }
1548                 if (inline_data_size) {
1549                         buf = ibuf;
1550 #ifdef WORDS_BIGENDIAN
1551                         if (db->blockcnt)
1552                                 goto skip_first_write_swab;
1553                         *((__u32 *)buf) = ext2fs_le32_to_cpu(*((__u32 *)buf));
1554                         cd->pctx.errcode = ext2fs_dirent_swab_out2(fs,
1555                                         buf + EXT4_INLINE_DATA_DOTDOT_SIZE,
1556                                         EXT4_MIN_INLINE_DATA_SIZE -
1557                                         EXT4_INLINE_DATA_DOTDOT_SIZE,
1558                                         0);
1559                         if (cd->pctx.errcode)
1560                                 goto skip_second_write_swab;
1561 skip_first_write_swab:
1562                         if (inline_data_size <= EXT4_MIN_INLINE_DATA_SIZE ||
1563                             !db->blockcnt)
1564                                 goto skip_second_write_swab;
1565                         cd->pctx.errcode = ext2fs_dirent_swab_out2(fs,
1566                                         buf + EXT4_MIN_INLINE_DATA_SIZE,
1567                                         inline_data_size -
1568                                         EXT4_MIN_INLINE_DATA_SIZE,
1569                                         0);
1570 skip_second_write_swab:
1571                         if (cd->pctx.errcode &&
1572                             !fix_problem(ctx, PR_2_WRITE_DIRBLOCK, &cd->pctx))
1573                                 goto abort_free_dict;
1574 #endif
1575                         cd->pctx.errcode =
1576                                 ext2fs_inline_data_set(fs, ino, 0, buf,
1577                                                        inline_data_size);
1578                 } else
1579                         cd->pctx.errcode = ext2fs_write_dir_block4(fs, block_nr,
1580                                                                    buf, 0, ino);
1581                 if (will_rehash)
1582                         ctx->fs->flags = (flags &
1583                                           EXT2_FLAG_IGNORE_CSUM_ERRORS) |
1584                                          (ctx->fs->flags &
1585                                           ~EXT2_FLAG_IGNORE_CSUM_ERRORS);
1586                 if (cd->pctx.errcode) {
1587                         if (!fix_problem(ctx, PR_2_WRITE_DIRBLOCK,
1588                                          &cd->pctx))
1589                                 goto abort_free_dict;
1590                 }
1591                 ext2fs_mark_changed(fs);
1592         } else if (is_leaf && failed_csum && !dir_modified) {
1593                 /*
1594                  * If a leaf node that fails csum makes it this far without
1595                  * alteration, ask the user if the checksum should be fixed.
1596                  */
1597                 if (fix_problem(ctx, PR_2_LEAF_NODE_ONLY_CSUM_INVALID,
1598                                 &cd->pctx))
1599                         goto write_and_fix;
1600         }
1601         dict_free_nodes(&de_dict);
1602         return 0;
1603 abort_free_dict:
1604         ctx->flags |= E2F_FLAG_ABORT;
1605         dict_free_nodes(&de_dict);
1606         return DIRENT_ABORT;
1607 }
1608
1609 struct del_block {
1610         e2fsck_t        ctx;
1611         e2_blkcnt_t     num;
1612 };
1613
1614 /*
1615  * This function is called to deallocate a block, and is an interator
1616  * functioned called by deallocate inode via ext2fs_iterate_block().
1617  */
1618 static int deallocate_inode_block(ext2_filsys fs,
1619                                   blk64_t       *block_nr,
1620                                   e2_blkcnt_t blockcnt EXT2FS_ATTR((unused)),
1621                                   blk64_t ref_block EXT2FS_ATTR((unused)),
1622                                   int ref_offset EXT2FS_ATTR((unused)),
1623                                   void *priv_data)
1624 {
1625         struct del_block *p = priv_data;
1626
1627         if (*block_nr == 0)
1628                 return 0;
1629         if ((*block_nr < fs->super->s_first_data_block) ||
1630             (*block_nr >= ext2fs_blocks_count(fs->super)))
1631                 return 0;
1632         if ((*block_nr % EXT2FS_CLUSTER_RATIO(fs)) == 0)
1633                 ext2fs_block_alloc_stats2(fs, *block_nr, -1);
1634         p->num++;
1635         return 0;
1636 }
1637
1638 /*
1639  * This function deallocates an inode
1640  */
1641 static void deallocate_inode(e2fsck_t ctx, ext2_ino_t ino, char* block_buf)
1642 {
1643         ext2_filsys fs = ctx->fs;
1644         struct ext2_inode       inode;
1645         struct problem_context  pctx;
1646         __u32                   count;
1647         struct del_block        del_block;
1648
1649         e2fsck_read_inode(ctx, ino, &inode, "deallocate_inode");
1650         clear_problem_context(&pctx);
1651         pctx.ino = ino;
1652
1653         /*
1654          * Fix up the bitmaps...
1655          */
1656         e2fsck_read_bitmaps(ctx);
1657         ext2fs_inode_alloc_stats2(fs, ino, -1, LINUX_S_ISDIR(inode.i_mode));
1658
1659         if (ext2fs_file_acl_block(fs, &inode) &&
1660             ext2fs_has_feature_xattr(fs->super)) {
1661                 pctx.errcode = ext2fs_adjust_ea_refcount3(fs,
1662                                 ext2fs_file_acl_block(fs, &inode),
1663                                 block_buf, -1, &count, ino);
1664                 if (pctx.errcode == EXT2_ET_BAD_EA_BLOCK_NUM) {
1665                         pctx.errcode = 0;
1666                         count = 1;
1667                 }
1668                 if (pctx.errcode) {
1669                         pctx.blk = ext2fs_file_acl_block(fs, &inode);
1670                         fix_problem(ctx, PR_2_ADJ_EA_REFCOUNT, &pctx);
1671                         ctx->flags |= E2F_FLAG_ABORT;
1672                         return;
1673                 }
1674                 if (count == 0) {
1675                         ext2fs_block_alloc_stats2(fs,
1676                                   ext2fs_file_acl_block(fs, &inode), -1);
1677                 }
1678                 ext2fs_file_acl_block_set(fs, &inode, 0);
1679         }
1680
1681         if (!ext2fs_inode_has_valid_blocks2(fs, &inode))
1682                 goto clear_inode;
1683
1684         /* Inline data inodes don't have blocks to iterate */
1685         if (inode.i_flags & EXT4_INLINE_DATA_FL)
1686                 goto clear_inode;
1687
1688         if (LINUX_S_ISREG(inode.i_mode) &&
1689             ext2fs_needs_large_file_feature(EXT2_I_SIZE(&inode)))
1690                 ctx->large_files--;
1691
1692         del_block.ctx = ctx;
1693         del_block.num = 0;
1694         pctx.errcode = ext2fs_block_iterate3(fs, ino, 0, block_buf,
1695                                              deallocate_inode_block,
1696                                              &del_block);
1697         if (pctx.errcode) {
1698                 fix_problem(ctx, PR_2_DEALLOC_INODE, &pctx);
1699                 ctx->flags |= E2F_FLAG_ABORT;
1700                 return;
1701         }
1702 clear_inode:
1703         /* Inode may have changed by block_iterate, so reread it */
1704         e2fsck_read_inode(ctx, ino, &inode, "deallocate_inode");
1705         e2fsck_clear_inode(ctx, ino, &inode, 0, "deallocate_inode");
1706 }
1707
1708 /*
1709  * This function clears the htree flag on an inode
1710  */
1711 static void clear_htree(e2fsck_t ctx, ext2_ino_t ino)
1712 {
1713         struct ext2_inode       inode;
1714
1715         e2fsck_read_inode(ctx, ino, &inode, "clear_htree");
1716         inode.i_flags = inode.i_flags & ~EXT2_INDEX_FL;
1717         e2fsck_write_inode(ctx, ino, &inode, "clear_htree");
1718         if (ctx->dirs_to_hash)
1719                 ext2fs_u32_list_add(ctx->dirs_to_hash, ino);
1720 }
1721
1722
1723 int e2fsck_process_bad_inode(e2fsck_t ctx, ext2_ino_t dir,
1724                              ext2_ino_t ino, char *buf)
1725 {
1726         ext2_filsys fs = ctx->fs;
1727         struct ext2_inode       inode;
1728         int                     inode_modified = 0;
1729         int                     not_fixed = 0;
1730         unsigned char           *frag, *fsize;
1731         struct problem_context  pctx;
1732         problem_t               problem = 0;
1733
1734         e2fsck_read_inode(ctx, ino, &inode, "process_bad_inode");
1735
1736         clear_problem_context(&pctx);
1737         pctx.ino = ino;
1738         pctx.dir = dir;
1739         pctx.inode = &inode;
1740
1741         if (ext2fs_file_acl_block(fs, &inode) &&
1742             !ext2fs_has_feature_xattr(fs->super)) {
1743                 if (fix_problem(ctx, PR_2_FILE_ACL_ZERO, &pctx)) {
1744                         ext2fs_file_acl_block_set(fs, &inode, 0);
1745                         inode_modified++;
1746                 } else
1747                         not_fixed++;
1748         }
1749
1750         if (!LINUX_S_ISDIR(inode.i_mode) && !LINUX_S_ISREG(inode.i_mode) &&
1751             !LINUX_S_ISCHR(inode.i_mode) && !LINUX_S_ISBLK(inode.i_mode) &&
1752             !LINUX_S_ISLNK(inode.i_mode) && !LINUX_S_ISFIFO(inode.i_mode) &&
1753             !(LINUX_S_ISSOCK(inode.i_mode)))
1754                 problem = PR_2_BAD_MODE;
1755         else if (LINUX_S_ISCHR(inode.i_mode)
1756                  && !e2fsck_pass1_check_device_inode(fs, &inode))
1757                 problem = PR_2_BAD_CHAR_DEV;
1758         else if (LINUX_S_ISBLK(inode.i_mode)
1759                  && !e2fsck_pass1_check_device_inode(fs, &inode))
1760                 problem = PR_2_BAD_BLOCK_DEV;
1761         else if (LINUX_S_ISFIFO(inode.i_mode)
1762                  && !e2fsck_pass1_check_device_inode(fs, &inode))
1763                 problem = PR_2_BAD_FIFO;
1764         else if (LINUX_S_ISSOCK(inode.i_mode)
1765                  && !e2fsck_pass1_check_device_inode(fs, &inode))
1766                 problem = PR_2_BAD_SOCKET;
1767         else if (LINUX_S_ISLNK(inode.i_mode)
1768                  && !e2fsck_pass1_check_symlink(fs, ino, &inode, buf)) {
1769                 problem = PR_2_INVALID_SYMLINK;
1770         }
1771
1772         if (problem) {
1773                 if (fix_problem(ctx, problem, &pctx)) {
1774                         deallocate_inode(ctx, ino, 0);
1775                         if (ctx->flags & E2F_FLAG_SIGNAL_MASK)
1776                                 return 0;
1777                         return 1;
1778                 } else
1779                         not_fixed++;
1780                 problem = 0;
1781         }
1782
1783         if (inode.i_faddr) {
1784                 if (fix_problem(ctx, PR_2_FADDR_ZERO, &pctx)) {
1785                         inode.i_faddr = 0;
1786                         inode_modified++;
1787                 } else
1788                         not_fixed++;
1789         }
1790
1791         switch (fs->super->s_creator_os) {
1792             case EXT2_OS_HURD:
1793                 frag = &inode.osd2.hurd2.h_i_frag;
1794                 fsize = &inode.osd2.hurd2.h_i_fsize;
1795                 break;
1796             default:
1797                 frag = fsize = 0;
1798         }
1799         if (frag && *frag) {
1800                 pctx.num = *frag;
1801                 if (fix_problem(ctx, PR_2_FRAG_ZERO, &pctx)) {
1802                         *frag = 0;
1803                         inode_modified++;
1804                 } else
1805                         not_fixed++;
1806                 pctx.num = 0;
1807         }
1808         if (fsize && *fsize) {
1809                 pctx.num = *fsize;
1810                 if (fix_problem(ctx, PR_2_FSIZE_ZERO, &pctx)) {
1811                         *fsize = 0;
1812                         inode_modified++;
1813                 } else
1814                         not_fixed++;
1815                 pctx.num = 0;
1816         }
1817
1818         if ((fs->super->s_creator_os == EXT2_OS_LINUX) &&
1819             !ext2fs_has_feature_huge_file(fs->super) &&
1820             (inode.osd2.linux2.l_i_blocks_hi != 0)) {
1821                 pctx.num = inode.osd2.linux2.l_i_blocks_hi;
1822                 if (fix_problem(ctx, PR_2_BLOCKS_HI_ZERO, &pctx)) {
1823                         inode.osd2.linux2.l_i_blocks_hi = 0;
1824                         inode_modified++;
1825                 }
1826         }
1827
1828         if ((fs->super->s_creator_os == EXT2_OS_LINUX) &&
1829             !ext2fs_has_feature_64bit(fs->super) &&
1830             inode.osd2.linux2.l_i_file_acl_high != 0) {
1831                 pctx.num = inode.osd2.linux2.l_i_file_acl_high;
1832                 if (fix_problem(ctx, PR_2_I_FILE_ACL_HI_ZERO, &pctx)) {
1833                         inode.osd2.linux2.l_i_file_acl_high = 0;
1834                         inode_modified++;
1835                 } else
1836                         not_fixed++;
1837         }
1838
1839         if (ext2fs_file_acl_block(fs, &inode) &&
1840             ((ext2fs_file_acl_block(fs, &inode) < fs->super->s_first_data_block) ||
1841              (ext2fs_file_acl_block(fs, &inode) >= ext2fs_blocks_count(fs->super)))) {
1842                 if (fix_problem(ctx, PR_2_FILE_ACL_BAD, &pctx)) {
1843                         ext2fs_file_acl_block_set(fs, &inode, 0);
1844                         inode_modified++;
1845                 } else
1846                         not_fixed++;
1847         }
1848         if (inode.i_size_high && !ext2fs_has_feature_largedir(fs->super) &&
1849             LINUX_S_ISDIR(inode.i_mode)) {
1850                 if (fix_problem(ctx, PR_2_DIR_SIZE_HIGH_ZERO, &pctx)) {
1851                         inode.i_size_high = 0;
1852                         inode_modified++;
1853                 } else
1854                         not_fixed++;
1855         }
1856
1857         if (inode_modified)
1858                 e2fsck_write_inode(ctx, ino, &inode, "process_bad_inode");
1859         if (!not_fixed && ctx->inode_bad_map)
1860                 ext2fs_unmark_inode_bitmap2(ctx->inode_bad_map, ino);
1861         return 0;
1862 }
1863
1864 /*
1865  * allocate_dir_block --- this function allocates a new directory
1866  *      block for a particular inode; this is done if a directory has
1867  *      a "hole" in it, or if a directory has a illegal block number
1868  *      that was zeroed out and now needs to be replaced.
1869  */
1870 static int allocate_dir_block(e2fsck_t ctx,
1871                               struct ext2_db_entry2 *db,
1872                               char *buf EXT2FS_ATTR((unused)),
1873                               struct problem_context *pctx)
1874 {
1875         ext2_filsys fs = ctx->fs;
1876         blk64_t                 blk = 0;
1877         char                    *block;
1878         struct ext2_inode       inode;
1879
1880         if (fix_problem(ctx, PR_2_DIRECTORY_HOLE, pctx) == 0)
1881                 return 1;
1882
1883         /*
1884          * Read the inode and block bitmaps in; we'll be messing with
1885          * them.
1886          */
1887         e2fsck_read_bitmaps(ctx);
1888
1889         /*
1890          * First, find a free block
1891          */
1892         e2fsck_read_inode(ctx, db->ino, &inode, "allocate_dir_block");
1893         pctx->errcode = ext2fs_map_cluster_block(fs, db->ino, &inode,
1894                                                  db->blockcnt, &blk);
1895         if (pctx->errcode || blk == 0) {
1896                 blk = ext2fs_find_inode_goal(fs, db->ino, &inode, db->blockcnt);
1897                 pctx->errcode = ext2fs_new_block2(fs, blk,
1898                                                   ctx->block_found_map, &blk);
1899                 if (pctx->errcode) {
1900                         pctx->str = "ext2fs_new_block";
1901                         fix_problem(ctx, PR_2_ALLOC_DIRBOCK, pctx);
1902                         return 1;
1903                 }
1904         }
1905         ext2fs_mark_block_bitmap2(ctx->block_found_map, blk);
1906         ext2fs_mark_block_bitmap2(fs->block_map, blk);
1907         ext2fs_mark_bb_dirty(fs);
1908
1909         /*
1910          * Now let's create the actual data block for the inode
1911          */
1912         if (db->blockcnt)
1913                 pctx->errcode = ext2fs_new_dir_block(fs, 0, 0, &block);
1914         else
1915                 pctx->errcode = ext2fs_new_dir_block(fs, db->ino,
1916                                                      EXT2_ROOT_INO, &block);
1917
1918         if (pctx->errcode) {
1919                 pctx->str = "ext2fs_new_dir_block";
1920                 fix_problem(ctx, PR_2_ALLOC_DIRBOCK, pctx);
1921                 return 1;
1922         }
1923
1924         pctx->errcode = ext2fs_write_dir_block4(fs, blk, block, 0, db->ino);
1925         ext2fs_free_mem(&block);
1926         if (pctx->errcode) {
1927                 pctx->str = "ext2fs_write_dir_block";
1928                 fix_problem(ctx, PR_2_ALLOC_DIRBOCK, pctx);
1929                 return 1;
1930         }
1931
1932         /*
1933          * Update the inode block count
1934          */
1935         ext2fs_iblk_add_blocks(fs, &inode, 1);
1936         if (EXT2_I_SIZE(&inode) < ((__u64) db->blockcnt+1) * fs->blocksize) {
1937                 pctx->errcode = ext2fs_inode_size_set(fs, &inode,
1938                                         (db->blockcnt+1) * fs->blocksize);
1939                 if (pctx->errcode) {
1940                         pctx->str = "ext2fs_inode_size_set";
1941                         fix_problem(ctx, PR_2_ALLOC_DIRBOCK, pctx);
1942                         return 1;
1943                 }
1944         }
1945         e2fsck_write_inode(ctx, db->ino, &inode, "allocate_dir_block");
1946
1947         /*
1948          * Finally, update the block pointers for the inode
1949          */
1950         db->blk = blk;
1951         pctx->errcode = ext2fs_bmap2(fs, db->ino, &inode, 0, BMAP_SET,
1952                                      db->blockcnt, 0, &blk);
1953         if (pctx->errcode) {
1954                 pctx->str = "ext2fs_block_iterate";
1955                 fix_problem(ctx, PR_2_ALLOC_DIRBOCK, pctx);
1956                 return 1;
1957         }
1958
1959         return 0;
1960 }