Whamcloud - gitweb
ebf35f287f0ea2c412c6010d0545922e5bc0d821
[tools/e2fsprogs.git] / e2fsck / pass2.c
1 /*
2  * pass2.c --- check directory structure
3  *
4  * Copyright (C) 1993, 1994, 1995, 1996, 1997 Theodore Ts'o
5  *
6  * %Begin-Header%
7  * This file may be redistributed under the terms of the GNU Public
8  * License.
9  * %End-Header%
10  *
11  * Pass 2 of e2fsck iterates through all active directory inodes, and
12  * applies to following tests to each directory entry in the directory
13  * blocks in the inodes:
14  *
15  *      - The length of the directory entry (rec_len) should be at
16  *              least 8 bytes, and no more than the remaining space
17  *              left in the directory block.
18  *      - The length of the name in the directory entry (name_len)
19  *              should be less than (rec_len - 8).
20  *      - The inode number in the directory entry should be within
21  *              legal bounds.
22  *      - The inode number should refer to a in-use inode.
23  *      - The first entry should be '.', and its inode should be
24  *              the inode of the directory.
25  *      - The second entry should be '..'.
26  *
27  * To minimize disk seek time, the directory blocks are processed in
28  * sorted order of block numbers.
29  *
30  * Pass 2 also collects the following information:
31  *      - The inode numbers of the subdirectories for each directory.
32  *
33  * Pass 2 relies on the following information from previous passes:
34  *      - The directory information collected in pass 1.
35  *      - The inode_used_map bitmap
36  *      - The inode_badness bitmap
37  *      - The inode_dir_map bitmap
38  *
39  * Pass 2 frees the following data structures
40  *      - The inode_reg_map bitmap
41  */
42
43 #define _GNU_SOURCE 1 /* get strnlen() */
44 #include "config.h"
45 #include <string.h>
46
47 #include "e2fsck.h"
48 #include "problem.h"
49 #include "dict.h"
50
51 #ifdef NO_INLINE_FUNCS
52 #define _INLINE_
53 #else
54 #define _INLINE_ inline
55 #endif
56
57 /* #define DX_DEBUG */
58
59 /*
60  * Keeps track of how many times an inode is referenced.
61  */
62 static void deallocate_inode(e2fsck_t ctx, ext2_ino_t ino, char* block_buf);
63 static int check_dir_block(ext2_filsys fs,
64                            struct ext2_db_entry2 *dir_blocks_info,
65                            void *priv_data);
66 static int allocate_dir_block(e2fsck_t ctx,
67                               struct ext2_db_entry2 *dir_blocks_info,
68                               char *buf, struct problem_context *pctx);
69 static void clear_htree(e2fsck_t ctx, ext2_ino_t ino);
70 static int htree_depth(struct dx_dir_info *dx_dir,
71                        struct dx_dirblock_info *dx_db);
72 static EXT2_QSORT_TYPE special_dir_block_cmp(const void *a, const void *b);
73
74 struct check_dir_struct {
75         char *buf;
76         struct problem_context  pctx;
77         int     count, max;
78         e2fsck_t ctx;
79 };
80
81 void e2fsck_pass2(e2fsck_t ctx)
82 {
83         struct ext2_super_block *sb = ctx->fs->super;
84         struct problem_context  pctx;
85         ext2_filsys             fs = ctx->fs;
86         char                    *buf;
87 #ifdef RESOURCE_TRACK
88         struct resource_track   rtrack;
89 #endif
90         struct check_dir_struct cd;
91         struct dx_dir_info      *dx_dir;
92         struct dx_dirblock_info *dx_db, *dx_parent;
93         unsigned int            save_type;
94         int                     b;
95         int                     i, depth;
96         problem_t               code;
97         int                     bad_dir;
98
99         init_resource_track(&rtrack, ctx->fs->io);
100         clear_problem_context(&cd.pctx);
101
102 #ifdef MTRACE
103         mtrace_print("Pass 2");
104 #endif
105
106         if (!(ctx->options & E2F_OPT_PREEN))
107                 fix_problem(ctx, PR_2_PASS_HEADER, &cd.pctx);
108
109         e2fsck_setup_tdb_icount(ctx, EXT2_ICOUNT_OPT_INCREMENT,
110                                 &ctx->inode_count);
111         if (ctx->inode_count)
112                 cd.pctx.errcode = 0;
113         else {
114                 e2fsck_set_bitmap_type(fs, EXT2FS_BMAP64_RBTREE,
115                                        "inode_count", &save_type);
116                 cd.pctx.errcode = ext2fs_create_icount2(fs,
117                                                 EXT2_ICOUNT_OPT_INCREMENT,
118                                                 0, ctx->inode_link_info,
119                                                 &ctx->inode_count);
120                 fs->default_bitmap_type = save_type;
121         }
122         if (cd.pctx.errcode) {
123                 fix_problem(ctx, PR_2_ALLOCATE_ICOUNT, &cd.pctx);
124                 ctx->flags |= E2F_FLAG_ABORT;
125                 return;
126         }
127         buf = (char *) e2fsck_allocate_memory(ctx, 2*fs->blocksize,
128                                               "directory scan buffer");
129
130         /*
131          * Set up the parent pointer for the root directory, if
132          * present.  (If the root directory is not present, we will
133          * create it in pass 3.)
134          */
135         (void) e2fsck_dir_info_set_parent(ctx, EXT2_ROOT_INO, EXT2_ROOT_INO);
136
137         cd.buf = buf;
138         cd.ctx = ctx;
139         cd.count = 1;
140         cd.max = ext2fs_dblist_count2(fs->dblist);
141
142         if (ctx->progress)
143                 (void) (ctx->progress)(ctx, 2, 0, cd.max);
144
145         if (fs->super->s_feature_compat & EXT2_FEATURE_COMPAT_DIR_INDEX)
146                 ext2fs_dblist_sort2(fs->dblist, special_dir_block_cmp);
147
148         cd.pctx.errcode = ext2fs_dblist_iterate2(fs->dblist, check_dir_block,
149                                                  &cd);
150         if (ctx->flags & E2F_FLAG_SIGNAL_MASK || ctx->flags & E2F_FLAG_RESTART)
151                 return;
152
153         if (ctx->flags & E2F_FLAG_RESTART_LATER) {
154                 ctx->flags |= E2F_FLAG_RESTART;
155                 return;
156         }
157
158         if (cd.pctx.errcode) {
159                 fix_problem(ctx, PR_2_DBLIST_ITERATE, &cd.pctx);
160                 ctx->flags |= E2F_FLAG_ABORT;
161                 return;
162         }
163
164 #ifdef ENABLE_HTREE
165         for (i=0; (dx_dir = e2fsck_dx_dir_info_iter(ctx, &i)) != 0;) {
166                 if (ctx->flags & E2F_FLAG_SIGNAL_MASK)
167                         return;
168                 if (dx_dir->numblocks == 0)
169                         continue;
170                 clear_problem_context(&pctx);
171                 bad_dir = 0;
172                 pctx.dir = dx_dir->ino;
173                 dx_db = dx_dir->dx_block;
174                 if (dx_db->flags & DX_FLAG_REFERENCED)
175                         dx_db->flags |= DX_FLAG_DUP_REF;
176                 else
177                         dx_db->flags |= DX_FLAG_REFERENCED;
178                 /*
179                  * Find all of the first and last leaf blocks, and
180                  * update their parent's min and max hash values
181                  */
182                 for (b=0, dx_db = dx_dir->dx_block;
183                      b < dx_dir->numblocks;
184                      b++, dx_db++) {
185                         if ((dx_db->type != DX_DIRBLOCK_LEAF) ||
186                             !(dx_db->flags & (DX_FLAG_FIRST | DX_FLAG_LAST)))
187                                 continue;
188                         dx_parent = &dx_dir->dx_block[dx_db->parent];
189                         /*
190                          * XXX Make sure dx_parent->min_hash > dx_db->min_hash
191                          */
192                         if (dx_db->flags & DX_FLAG_FIRST)
193                                 dx_parent->min_hash = dx_db->min_hash;
194                         /*
195                          * XXX Make sure dx_parent->max_hash < dx_db->max_hash
196                          */
197                         if (dx_db->flags & DX_FLAG_LAST)
198                                 dx_parent->max_hash = dx_db->max_hash;
199                 }
200
201                 for (b=0, dx_db = dx_dir->dx_block;
202                      b < dx_dir->numblocks;
203                      b++, dx_db++) {
204                         pctx.blkcount = b;
205                         pctx.group = dx_db->parent;
206                         code = 0;
207                         if (!(dx_db->flags & DX_FLAG_FIRST) &&
208                             (dx_db->min_hash < dx_db->node_min_hash)) {
209                                 pctx.blk = dx_db->min_hash;
210                                 pctx.blk2 = dx_db->node_min_hash;
211                                 code = PR_2_HTREE_MIN_HASH;
212                                 fix_problem(ctx, code, &pctx);
213                                 bad_dir++;
214                         }
215                         if (dx_db->type == DX_DIRBLOCK_LEAF) {
216                                 depth = htree_depth(dx_dir, dx_db);
217                                 if (depth != dx_dir->depth) {
218                                         pctx.num = dx_dir->depth;
219                                         code = PR_2_HTREE_BAD_DEPTH;
220                                         fix_problem(ctx, code, &pctx);
221                                         bad_dir++;
222                                 }
223                         }
224                         /*
225                          * This test doesn't apply for the root block
226                          * at block #0
227                          */
228                         if (b &&
229                             (dx_db->max_hash > dx_db->node_max_hash)) {
230                                 pctx.blk = dx_db->max_hash;
231                                 pctx.blk2 = dx_db->node_max_hash;
232                                 code = PR_2_HTREE_MAX_HASH;
233                                 fix_problem(ctx, code, &pctx);
234                                 bad_dir++;
235                         }
236                         if (!(dx_db->flags & DX_FLAG_REFERENCED)) {
237                                 code = PR_2_HTREE_NOTREF;
238                                 fix_problem(ctx, code, &pctx);
239                                 bad_dir++;
240                         } else if (dx_db->flags & DX_FLAG_DUP_REF) {
241                                 code = PR_2_HTREE_DUPREF;
242                                 fix_problem(ctx, code, &pctx);
243                                 bad_dir++;
244                         }
245                 }
246                 if (bad_dir && fix_problem(ctx, PR_2_HTREE_CLEAR, &pctx)) {
247                         clear_htree(ctx, dx_dir->ino);
248                         dx_dir->numblocks = 0;
249                 }
250         }
251         e2fsck_free_dx_dir_info(ctx);
252 #endif
253         ext2fs_free_mem(&buf);
254         ext2fs_free_dblist(fs->dblist);
255
256         if (ctx->inode_reg_map) {
257                 ext2fs_free_inode_bitmap(ctx->inode_reg_map);
258                 ctx->inode_reg_map = 0;
259         }
260
261         clear_problem_context(&pctx);
262         if (ctx->large_files) {
263                 if (!(sb->s_feature_ro_compat &
264                       EXT2_FEATURE_RO_COMPAT_LARGE_FILE) &&
265                     fix_problem(ctx, PR_2_FEATURE_LARGE_FILES, &pctx)) {
266                         sb->s_feature_ro_compat |=
267                                 EXT2_FEATURE_RO_COMPAT_LARGE_FILE;
268                         fs->flags &= ~EXT2_FLAG_MASTER_SB_ONLY;
269                         ext2fs_mark_super_dirty(fs);
270                 }
271                 if (sb->s_rev_level == EXT2_GOOD_OLD_REV &&
272                     fix_problem(ctx, PR_1_FS_REV_LEVEL, &pctx)) {
273                         ext2fs_update_dynamic_rev(fs);
274                         ext2fs_mark_super_dirty(fs);
275                 }
276         }
277
278         print_resource_track(ctx, _("Pass 2"), &rtrack, fs->io);
279 }
280
281 #define MAX_DEPTH 32000
282 static int htree_depth(struct dx_dir_info *dx_dir,
283                        struct dx_dirblock_info *dx_db)
284 {
285         int     depth = 0;
286
287         while (dx_db->type != DX_DIRBLOCK_ROOT && depth < MAX_DEPTH) {
288                 dx_db = &dx_dir->dx_block[dx_db->parent];
289                 depth++;
290         }
291         return depth;
292 }
293
294 static int dict_de_cmp(const void *a, const void *b)
295 {
296         const struct ext2_dir_entry *de_a, *de_b;
297         int     a_len, b_len;
298
299         de_a = (const struct ext2_dir_entry *) a;
300         a_len = de_a->name_len & 0xFF;
301         de_b = (const struct ext2_dir_entry *) b;
302         b_len = de_b->name_len & 0xFF;
303
304         if (a_len != b_len)
305                 return (a_len - b_len);
306
307         return strncmp(de_a->name, de_b->name, a_len);
308 }
309
310 /*
311  * This is special sort function that makes sure that directory blocks
312  * with a dirblock of zero are sorted to the beginning of the list.
313  * This guarantees that the root node of the htree directories are
314  * processed first, so we know what hash version to use.
315  */
316 static EXT2_QSORT_TYPE special_dir_block_cmp(const void *a, const void *b)
317 {
318         const struct ext2_db_entry2 *db_a =
319                 (const struct ext2_db_entry2 *) a;
320         const struct ext2_db_entry2 *db_b =
321                 (const struct ext2_db_entry2 *) b;
322
323         if (db_a->blockcnt && !db_b->blockcnt)
324                 return 1;
325
326         if (!db_a->blockcnt && db_b->blockcnt)
327                 return -1;
328
329         if (db_a->blk != db_b->blk)
330                 return (int) (db_a->blk - db_b->blk);
331
332         if (db_a->ino != db_b->ino)
333                 return (int) (db_a->ino - db_b->ino);
334
335         return (int) (db_a->blockcnt - db_b->blockcnt);
336 }
337
338
339 /*
340  * Make sure the first entry in the directory is '.', and that the
341  * directory entry is sane.
342  */
343 static int check_dot(e2fsck_t ctx,
344                      struct ext2_dir_entry *dirent,
345                      ext2_ino_t ino, struct problem_context *pctx)
346 {
347         struct ext2_dir_entry *nextdir;
348         unsigned int    rec_len, new_len;
349         int             status = 0;
350         int             created = 0;
351         problem_t       problem = 0;
352
353         if (!dirent->inode)
354                 problem = PR_2_MISSING_DOT;
355         else if (((dirent->name_len & 0xFF) != 1) ||
356                  (dirent->name[0] != '.'))
357                 problem = PR_2_1ST_NOT_DOT;
358         else if (dirent->name[1] != '\0')
359                 problem = PR_2_DOT_NULL_TERM;
360
361         (void) ext2fs_get_rec_len(ctx->fs, dirent, &rec_len);
362         if (problem) {
363                 if (fix_problem(ctx, problem, pctx)) {
364                         if (rec_len < 12)
365                                 rec_len = dirent->rec_len = 12;
366                         dirent->inode = ino;
367                         dirent->name_len = 1;
368                         dirent->name[0] = '.';
369                         dirent->name[1] = '\0';
370                         status = 1;
371                         created = 1;
372                 }
373         }
374         if (dirent->inode != ino) {
375                 if (fix_problem(ctx, PR_2_BAD_INODE_DOT, pctx)) {
376                         dirent->inode = ino;
377                         status = 1;
378                 }
379         }
380         if (rec_len > 12) {
381                 new_len = rec_len - 12;
382                 if (new_len > 12) {
383                         if (created ||
384                             fix_problem(ctx, PR_2_SPLIT_DOT, pctx)) {
385                                 nextdir = (struct ext2_dir_entry *)
386                                         ((char *) dirent + 12);
387                                 dirent->rec_len = 12;
388                                 (void) ext2fs_set_rec_len(ctx->fs, new_len,
389                                                           nextdir);
390                                 nextdir->inode = 0;
391                                 nextdir->name_len = 0;
392                                 status = 1;
393                         }
394                 }
395         }
396         return status;
397 }
398
399 /*
400  * Make sure the second entry in the directory is '..', and that the
401  * directory entry is sane.  We do not check the inode number of '..'
402  * here; this gets done in pass 3.
403  */
404 static int check_dotdot(e2fsck_t ctx,
405                         struct ext2_dir_entry *dirent,
406                         ext2_ino_t ino, struct problem_context *pctx)
407 {
408         problem_t       problem = 0;
409         unsigned int    rec_len;
410
411         if (!dirent->inode)
412                 problem = PR_2_MISSING_DOT_DOT;
413         else if (((dirent->name_len & 0xFF) != 2) ||
414                  (dirent->name[0] != '.') ||
415                  (dirent->name[1] != '.'))
416                 problem = PR_2_2ND_NOT_DOT_DOT;
417         else if (dirent->name[2] != '\0')
418                 problem = PR_2_DOT_DOT_NULL_TERM;
419
420         (void) ext2fs_get_rec_len(ctx->fs, dirent, &rec_len);
421         if (problem) {
422                 if (fix_problem(ctx, problem, pctx)) {
423                         if (rec_len < 12)
424                                 dirent->rec_len = 12;
425                         /*
426                          * Note: we don't have the parent inode just
427                          * yet, so we will fill it in with the root
428                          * inode.  This will get fixed in pass 3.
429                          */
430                         dirent->inode = EXT2_ROOT_INO;
431                         dirent->name_len = 2;
432                         dirent->name[0] = '.';
433                         dirent->name[1] = '.';
434                         dirent->name[2] = '\0';
435                         return 1;
436                 }
437                 return 0;
438         }
439         if (e2fsck_dir_info_set_dotdot(ctx, ino, dirent->inode)) {
440                 fix_problem(ctx, PR_2_NO_DIRINFO, pctx);
441                 return -1;
442         }
443         return 0;
444 }
445
446 /*
447  * Check to make sure a directory entry doesn't contain any illegal
448  * characters.
449  */
450 static int check_name(e2fsck_t ctx,
451                       struct ext2_dir_entry *dirent,
452                       ext2_ino_t dir_ino EXT2FS_ATTR((unused)),
453                       struct problem_context *pctx)
454 {
455         int     i;
456         int     fixup = -1;
457         int     ret = 0;
458
459         for ( i = 0; i < (dirent->name_len & 0xFF); i++) {
460                 if (dirent->name[i] == '/' || dirent->name[i] == '\0') {
461                         if (fixup < 0) {
462                                 fixup = fix_problem(ctx, PR_2_BAD_NAME, pctx);
463                         }
464                         if (fixup) {
465                                 dirent->name[i] = '.';
466                                 ret = 1;
467                         }
468                 }
469         }
470         return ret;
471 }
472
473 /*
474  * Check the directory filetype (if present)
475  */
476 static _INLINE_ int check_filetype(e2fsck_t ctx,
477                                    struct ext2_dir_entry *dirent,
478                                    ext2_ino_t dir_ino EXT2FS_ATTR((unused)),
479                                    struct problem_context *pctx)
480 {
481         int     filetype = dirent->name_len >> 8;
482         int     should_be = EXT2_FT_UNKNOWN;
483         __u16   result;
484         struct ext2_inode       inode;
485
486         if (!(ctx->fs->super->s_feature_incompat &
487               EXT2_FEATURE_INCOMPAT_FILETYPE)) {
488                 if (filetype == 0 ||
489                     !fix_problem(ctx, PR_2_CLEAR_FILETYPE, pctx))
490                         return 0;
491                 dirent->name_len = dirent->name_len & 0xFF;
492                 return 1;
493         }
494
495         if (ctx->inode_badness)
496                 ext2fs_icount_fetch(ctx->inode_badness, dirent->inode,
497                                         &result);
498
499         if (ext2fs_test_inode_bitmap2(ctx->inode_dir_map, dirent->inode)) {
500                 should_be = EXT2_FT_DIR;
501         } else if (ext2fs_test_inode_bitmap2(ctx->inode_reg_map,
502                                             dirent->inode)) {
503                 should_be = EXT2_FT_REG_FILE;
504         } else if (ctx->inode_badness && result >= BADNESS_BAD_MODE) {
505                 should_be = 0;
506         } else {
507                 e2fsck_read_inode(ctx, dirent->inode, &inode,
508                                   "check_filetype");
509                 should_be = ext2_file_type(inode.i_mode);
510         }
511         if (filetype == should_be)
512                 return 0;
513         pctx->num = should_be;
514
515         if (fix_problem(ctx, filetype ? PR_2_BAD_FILETYPE : PR_2_SET_FILETYPE,
516                         pctx) == 0)
517                 return 0;
518
519         dirent->name_len = (dirent->name_len & 0xFF) | should_be << 8;
520         return 1;
521 }
522
523 #ifdef ENABLE_HTREE
524 static void parse_int_node(ext2_filsys fs,
525                            struct ext2_db_entry2 *db,
526                            struct check_dir_struct *cd,
527                            struct dx_dir_info   *dx_dir,
528                            char *block_buf)
529 {
530         struct          ext2_dx_root_info  *root;
531         struct          ext2_dx_entry *ent;
532         struct          ext2_dx_countlimit *limit;
533         struct dx_dirblock_info *dx_db;
534         int             i, expect_limit, count;
535         blk_t           blk;
536         ext2_dirhash_t  min_hash = 0xffffffff;
537         ext2_dirhash_t  max_hash = 0;
538         ext2_dirhash_t  hash = 0, prev_hash;
539
540         if (db->blockcnt == 0) {
541                 root = (struct ext2_dx_root_info *) (block_buf + 24);
542
543 #ifdef DX_DEBUG
544                 printf("Root node dump:\n");
545                 printf("\t Reserved zero: %u\n", root->reserved_zero);
546                 printf("\t Hash Version: %d\n", root->hash_version);
547                 printf("\t Info length: %d\n", root->info_length);
548                 printf("\t Indirect levels: %d\n", root->indirect_levels);
549                 printf("\t Flags: %d\n", root->unused_flags);
550 #endif
551
552                 ent = (struct ext2_dx_entry *) (block_buf + 24 + root->info_length);
553         } else {
554                 ent = (struct ext2_dx_entry *) (block_buf+8);
555         }
556         limit = (struct ext2_dx_countlimit *) ent;
557
558 #ifdef DX_DEBUG
559         printf("Number of entries (count): %d\n",
560                ext2fs_le16_to_cpu(limit->count));
561         printf("Number of entries (limit): %d\n",
562                ext2fs_le16_to_cpu(limit->limit));
563 #endif
564
565         count = ext2fs_le16_to_cpu(limit->count);
566         expect_limit = (fs->blocksize - ((char *) ent - block_buf)) /
567                 sizeof(struct ext2_dx_entry);
568         if (ext2fs_le16_to_cpu(limit->limit) != expect_limit) {
569                 cd->pctx.num = ext2fs_le16_to_cpu(limit->limit);
570                 if (fix_problem(cd->ctx, PR_2_HTREE_BAD_LIMIT, &cd->pctx))
571                         goto clear_and_exit;
572         }
573         if (count > expect_limit) {
574                 cd->pctx.num = count;
575                 if (fix_problem(cd->ctx, PR_2_HTREE_BAD_COUNT, &cd->pctx))
576                         goto clear_and_exit;
577                 count = expect_limit;
578         }
579
580         for (i=0; i < count; i++) {
581                 prev_hash = hash;
582                 hash = i ? (ext2fs_le32_to_cpu(ent[i].hash) & ~1) : 0;
583 #ifdef DX_DEBUG
584                 printf("Entry #%d: Hash 0x%08x, block %u\n", i,
585                        hash, ext2fs_le32_to_cpu(ent[i].block));
586 #endif
587                 blk = ext2fs_le32_to_cpu(ent[i].block) & 0x0ffffff;
588                 /* Check to make sure the block is valid */
589                 if (blk >= (blk_t) dx_dir->numblocks) {
590                         cd->pctx.blk = blk;
591                         if (fix_problem(cd->ctx, PR_2_HTREE_BADBLK,
592                                         &cd->pctx))
593                                 goto clear_and_exit;
594                         continue;
595                 }
596                 if (hash < prev_hash &&
597                     fix_problem(cd->ctx, PR_2_HTREE_HASH_ORDER, &cd->pctx))
598                         goto clear_and_exit;
599                 dx_db = &dx_dir->dx_block[blk];
600                 if (dx_db->flags & DX_FLAG_REFERENCED) {
601                         dx_db->flags |= DX_FLAG_DUP_REF;
602                 } else {
603                         dx_db->flags |= DX_FLAG_REFERENCED;
604                         dx_db->parent = db->blockcnt;
605                 }
606                 if (hash < min_hash)
607                         min_hash = hash;
608                 if (hash > max_hash)
609                         max_hash = hash;
610                 dx_db->node_min_hash = hash;
611                 if ((i+1) < count)
612                         dx_db->node_max_hash =
613                           ext2fs_le32_to_cpu(ent[i+1].hash) & ~1;
614                 else {
615                         dx_db->node_max_hash = 0xfffffffe;
616                         dx_db->flags |= DX_FLAG_LAST;
617                 }
618                 if (i == 0)
619                         dx_db->flags |= DX_FLAG_FIRST;
620         }
621 #ifdef DX_DEBUG
622         printf("Blockcnt = %d, min hash 0x%08x, max hash 0x%08x\n",
623                db->blockcnt, min_hash, max_hash);
624 #endif
625         dx_db = &dx_dir->dx_block[db->blockcnt];
626         dx_db->min_hash = min_hash;
627         dx_db->max_hash = max_hash;
628         return;
629
630 clear_and_exit:
631         clear_htree(cd->ctx, cd->pctx.ino);
632         dx_dir->numblocks = 0;
633 }
634 #endif /* ENABLE_HTREE */
635
636 /*
637  * Given a busted directory, try to salvage it somehow.
638  *
639  */
640 static void salvage_directory(ext2_filsys fs,
641                               struct ext2_dir_entry *dirent,
642                               struct ext2_dir_entry *prev,
643                               unsigned int *offset)
644 {
645         char    *cp = (char *) dirent;
646         int left;
647         unsigned int rec_len, prev_rec_len;
648         unsigned int name_len = dirent->name_len & 0xFF;
649
650         (void) ext2fs_get_rec_len(fs, dirent, &rec_len);
651         left = fs->blocksize - *offset - rec_len;
652
653         /*
654          * Special case of directory entry of size 8: copy what's left
655          * of the directory block up to cover up the invalid hole.
656          */
657         if ((left >= 12) && (rec_len == 8)) {
658                 memmove(cp, cp+8, left);
659                 memset(cp + left, 0, 8);
660                 return;
661         }
662         /*
663          * If the directory entry overruns the end of the directory
664          * block, and the name is small enough to fit, then adjust the
665          * record length.
666          */
667         if ((left < 0) &&
668             ((int) rec_len + left > 8) &&
669             ((int) name_len + 8 <= (int) rec_len + left) &&
670             dirent->inode <= fs->super->s_inodes_count &&
671             strnlen(dirent->name, name_len) == name_len) {
672                 (void) ext2fs_set_rec_len(fs, (int) rec_len + left, dirent);
673                 return;
674         }
675         /*
676          * If the record length of the directory entry is a multiple
677          * of four, and not too big, such that it is valid, let the
678          * previous directory entry absorb the invalid one.
679          */
680         if (prev && rec_len && (rec_len % 4) == 0 &&
681             (*offset + rec_len <= fs->blocksize)) {
682                 (void) ext2fs_get_rec_len(fs, prev, &prev_rec_len);
683                 prev_rec_len += rec_len;
684                 (void) ext2fs_set_rec_len(fs, prev_rec_len, prev);
685                 *offset += rec_len;
686                 return;
687         }
688         /*
689          * Default salvage method --- kill all of the directory
690          * entries for the rest of the block.  We will either try to
691          * absorb it into the previous directory entry, or create a
692          * new empty directory entry the rest of the directory block.
693          */
694         if (prev) {
695                 (void) ext2fs_get_rec_len(fs, prev, &prev_rec_len);
696                 prev_rec_len += fs->blocksize - *offset;
697                 (void) ext2fs_set_rec_len(fs, prev_rec_len, prev);
698                 *offset = fs->blocksize;
699         } else {
700                 rec_len = fs->blocksize - *offset;
701                 (void) ext2fs_set_rec_len(fs, rec_len, dirent);
702                 dirent->name_len = 0;
703                 dirent->inode = 0;
704         }
705 }
706
707 static int check_dir_block(ext2_filsys fs,
708                            struct ext2_db_entry2 *db,
709                            void *priv_data)
710 {
711         struct dx_dir_info      *dx_dir;
712 #ifdef ENABLE_HTREE
713         struct dx_dirblock_info *dx_db = 0;
714 #endif /* ENABLE_HTREE */
715         struct ext2_dir_entry   *dirent, *prev;
716         ext2_dirhash_t          hash;
717         unsigned int            offset = 0;
718         int                     dir_modified = 0;
719         int                     dot_state;
720         unsigned int            rec_len;
721         blk64_t                 block_nr = db->blk;
722         ext2_ino_t              ino = db->ino;
723         ext2_ino_t              subdir_parent;
724         __u16                   links;
725         struct check_dir_struct *cd;
726         char                    *buf;
727         e2fsck_t                ctx;
728         problem_t               problem;
729         struct ext2_dx_root_info *root;
730         struct ext2_dx_countlimit *limit;
731         static dict_t de_dict;
732         struct problem_context  pctx;
733         int     dups_found = 0;
734         int     ret;
735
736         cd = (struct check_dir_struct *) priv_data;
737         buf = cd->buf;
738         ctx = cd->ctx;
739
740         if (ctx->flags & E2F_FLAG_SIGNAL_MASK || ctx->flags & E2F_FLAG_RESTART)
741                 return DIRENT_ABORT;
742
743         if (ctx->progress && (ctx->progress)(ctx, 2, cd->count++, cd->max))
744                 return DIRENT_ABORT;
745
746         /*
747          * Make sure the inode is still in use (could have been
748          * deleted in the duplicate/bad blocks pass.
749          */
750         if (!(ext2fs_test_inode_bitmap2(ctx->inode_used_map, ino)))
751                 return 0;
752
753         cd->pctx.ino = ino;
754         cd->pctx.blk = block_nr;
755         cd->pctx.blkcount = db->blockcnt;
756         cd->pctx.ino2 = 0;
757         cd->pctx.dirent = 0;
758         cd->pctx.num = 0;
759
760         if (db->blk == 0) {
761                 if (allocate_dir_block(ctx, db, buf, &cd->pctx))
762                         return 0;
763                 block_nr = db->blk;
764         }
765
766         if (db->blockcnt)
767                 dot_state = 2;
768         else
769                 dot_state = 0;
770
771         if (ctx->dirs_to_hash &&
772             ext2fs_u32_list_test(ctx->dirs_to_hash, ino))
773                 dups_found++;
774
775 #if 0
776         printf("In process_dir_block block %lu, #%d, inode %lu\n", block_nr,
777                db->blockcnt, ino);
778 #endif
779
780         ehandler_operation(_("reading directory block"));
781         cd->pctx.errcode = ext2fs_read_dir_block3(fs, block_nr, buf, 0);
782         ehandler_operation(0);
783         if (cd->pctx.errcode == EXT2_ET_DIR_CORRUPTED)
784                 cd->pctx.errcode = 0; /* We'll handle this ourselves */
785         if (cd->pctx.errcode) {
786                 if (!fix_problem(ctx, PR_2_READ_DIRBLOCK, &cd->pctx)) {
787                         ctx->flags |= E2F_FLAG_ABORT;
788                         return DIRENT_ABORT;
789                 }
790                 memset(buf, 0, fs->blocksize);
791         }
792 #ifdef ENABLE_HTREE
793         dx_dir = e2fsck_get_dx_dir_info(ctx, ino);
794         if (dx_dir && dx_dir->numblocks) {
795                 if (db->blockcnt >= dx_dir->numblocks) {
796                         pctx.dir = ino;
797                         if (fix_problem(ctx, PR_2_UNEXPECTED_HTREE_BLOCK,
798                                         &pctx)) {
799                                 clear_htree(ctx, ino);
800                                 dx_dir->numblocks = 0;
801                                 dx_db = 0;
802                                 goto out_htree;
803                         }
804                         fatal_error(ctx, _("Can not continue."));
805                 }
806                 dx_db = &dx_dir->dx_block[db->blockcnt];
807                 dx_db->type = DX_DIRBLOCK_LEAF;
808                 dx_db->phys = block_nr;
809                 dx_db->min_hash = ~0;
810                 dx_db->max_hash = 0;
811
812                 dirent = (struct ext2_dir_entry *) buf;
813                 (void) ext2fs_get_rec_len(fs, dirent, &rec_len);
814                 limit = (struct ext2_dx_countlimit *) (buf+8);
815                 if (db->blockcnt == 0) {
816                         root = (struct ext2_dx_root_info *) (buf + 24);
817                         dx_db->type = DX_DIRBLOCK_ROOT;
818                         dx_db->flags |= DX_FLAG_FIRST | DX_FLAG_LAST;
819                         if ((root->reserved_zero ||
820                              root->info_length < 8 ||
821                              root->indirect_levels > 1) &&
822                             fix_problem(ctx, PR_2_HTREE_BAD_ROOT, &cd->pctx)) {
823                                 clear_htree(ctx, ino);
824                                 dx_dir->numblocks = 0;
825                                 dx_db = 0;
826                         }
827                         dx_dir->hashversion = root->hash_version;
828                         if ((dx_dir->hashversion <= EXT2_HASH_TEA) &&
829                             (fs->super->s_flags & EXT2_FLAGS_UNSIGNED_HASH))
830                                 dx_dir->hashversion += 3;
831                         dx_dir->depth = root->indirect_levels + 1;
832                 } else if ((dirent->inode == 0) &&
833                            (rec_len == fs->blocksize) &&
834                            (dirent->name_len == 0) &&
835                            (ext2fs_le16_to_cpu(limit->limit) ==
836                             ((fs->blocksize-8) /
837                              sizeof(struct ext2_dx_entry))))
838                         dx_db->type = DX_DIRBLOCK_NODE;
839         }
840 out_htree:
841 #endif /* ENABLE_HTREE */
842
843         dict_init(&de_dict, DICTCOUNT_T_MAX, dict_de_cmp);
844         prev = 0;
845         do {
846                 dgrp_t group;
847                 ext2_ino_t first_unused_inode;
848
849                 problem = 0;
850                 dirent = (struct ext2_dir_entry *) (buf + offset);
851                 (void) ext2fs_get_rec_len(fs, dirent, &rec_len);
852                 cd->pctx.dirent = dirent;
853                 cd->pctx.num = offset;
854                 if (((offset + rec_len) > fs->blocksize) ||
855                     (rec_len < 12) ||
856                     ((rec_len % 4) != 0) ||
857                     (((dirent->name_len & (unsigned) 0xFF)+8) > rec_len)) {
858                         if (fix_problem(ctx, PR_2_DIR_CORRUPTED, &cd->pctx)) {
859                                 salvage_directory(fs, dirent, prev, &offset);
860                                 dir_modified++;
861                                 continue;
862                         } else
863                                 goto abort_free_dict;
864                 }
865
866                 if (dot_state == 0) {
867                         if (check_dot(ctx, dirent, ino, &cd->pctx))
868                                 dir_modified++;
869                 } else if (dot_state == 1) {
870                         ret = check_dotdot(ctx, dirent, ino, &cd->pctx);
871                         if (ret < 0)
872                                 goto abort_free_dict;
873                         if (ret)
874                                 dir_modified++;
875                 } else if (dirent->inode == ino) {
876                         problem = PR_2_LINK_DOT;
877                         if (fix_problem(ctx, PR_2_LINK_DOT, &cd->pctx)) {
878                                 dirent->inode = 0;
879                                 dir_modified++;
880                                 goto next;
881                         }
882                 }
883                 if (!dirent->inode)
884                         goto next;
885
886                 /*
887                  * Make sure the inode listed is a legal one.
888                  */
889                 if (((dirent->inode != EXT2_ROOT_INO) &&
890                      (dirent->inode < EXT2_FIRST_INODE(fs->super))) ||
891                     (dirent->inode > fs->super->s_inodes_count)) {
892                         problem = PR_2_BAD_INO;
893                 } else if (ctx->inode_bb_map &&
894                            (ext2fs_test_inode_bitmap2(ctx->inode_bb_map,
895                                                      dirent->inode))) {
896                         /*
897                          * If the inode is in a bad block, offer to
898                          * clear it.
899                          */
900                         problem = PR_2_BB_INODE;
901                 } else if ((dot_state > 1) &&
902                            ((dirent->name_len & 0xFF) == 1) &&
903                            (dirent->name[0] == '.')) {
904                         /*
905                          * If there's a '.' entry in anything other
906                          * than the first directory entry, it's a
907                          * duplicate entry that should be removed.
908                          */
909                         problem = PR_2_DUP_DOT;
910                 } else if ((dot_state > 1) &&
911                            ((dirent->name_len & 0xFF) == 2) &&
912                            (dirent->name[0] == '.') &&
913                            (dirent->name[1] == '.')) {
914                         /*
915                          * If there's a '..' entry in anything other
916                          * than the second directory entry, it's a
917                          * duplicate entry that should be removed.
918                          */
919                         problem = PR_2_DUP_DOT_DOT;
920                 } else if ((dot_state > 1) &&
921                            (dirent->inode == EXT2_ROOT_INO)) {
922                         /*
923                          * Don't allow links to the root directory.
924                          * We check this specially to make sure we
925                          * catch this error case even if the root
926                          * directory hasn't been created yet.
927                          */
928                         problem = PR_2_LINK_ROOT;
929                 } else if ((dot_state > 1) &&
930                            (dirent->name_len & 0xFF) == 0) {
931                         /*
932                          * Don't allow zero-length directory names.
933                          */
934                         problem = PR_2_NULL_NAME;
935                 }
936
937                 if (problem) {
938                         if (fix_problem(ctx, problem, &cd->pctx)) {
939                                 dirent->inode = 0;
940                                 dir_modified++;
941                                 goto next;
942                         } else {
943                                 ext2fs_unmark_valid(fs);
944                                 if (problem == PR_2_BAD_INO)
945                                         goto next;
946                         }
947                 }
948
949                 /*
950                  * If the inode was marked as having bad fields in
951                  * pass1, process it and offer to fix/clear it.
952                  * (We wait until now so that we can display the
953                  * pathname to the user.)
954                  */
955                 if (ctx->inode_badness &&
956                     ext2fs_icount_is_set(ctx->inode_badness, dirent->inode)) {
957                         if (e2fsck_process_bad_inode(ctx, ino, dirent->inode,
958                                                      buf + fs->blocksize)) {
959                                 dirent->inode = 0;
960                                 dir_modified++;
961                                 goto next;
962                         }
963                         if (ctx->flags & E2F_FLAG_SIGNAL_MASK)
964                                 return DIRENT_ABORT;
965                 }
966
967                 group = ext2fs_group_of_ino(fs, dirent->inode);
968                 first_unused_inode = group * fs->super->s_inodes_per_group +
969                                         1 + fs->super->s_inodes_per_group -
970                                         ext2fs_bg_itable_unused(fs, group);
971                 cd->pctx.group = group;
972
973                 /*
974                  * Check if the inode was missed out because
975                  * _INODE_UNINIT flag was set or bg_itable_unused was
976                  * incorrect.  If so, clear the _INODE_UNINIT flag and
977                  * restart e2fsck.  In the future it would be nice if
978                  * we could call a function in pass1.c that checks the
979                  * newly visible inodes.
980                  */
981                 if (ext2fs_bg_flags_test(fs, group, EXT2_BG_INODE_UNINIT)) {
982                         pctx.num = dirent->inode;
983                         if (fix_problem(ctx, PR_2_INOREF_BG_INO_UNINIT,
984                                         &cd->pctx)){
985                                 ext2fs_bg_flags_clear(fs, group,
986                                                       EXT2_BG_INODE_UNINIT);
987                                 ext2fs_mark_super_dirty(fs);
988                                 ctx->flags |= E2F_FLAG_RESTART_LATER;
989                         } else {
990                                 ext2fs_unmark_valid(fs);
991                                 if (problem == PR_2_BAD_INO)
992                                         goto next;
993                         }
994                 } else if (dirent->inode >= first_unused_inode) {
995                         pctx.num = dirent->inode;
996                         if (fix_problem(ctx, PR_2_INOREF_IN_UNUSED, &cd->pctx)){
997                                 ext2fs_bg_itable_unused_set(fs, group, 0);
998                                 ext2fs_mark_super_dirty(fs);
999                                 ctx->flags |= E2F_FLAG_RESTART_LATER;
1000                         } else {
1001                                 ext2fs_unmark_valid(fs);
1002                                 if (problem == PR_2_BAD_INO)
1003                                         goto next;
1004                         }
1005                 }
1006
1007                 /* 
1008                  * Offer to clear unused inodes; if we are going to be
1009                  * restarting the scan due to bg_itable_unused being
1010                  * wrong, then don't clear any inodes to avoid zapping
1011                  * inodes that were skipped during pass1 due to an
1012                  * incorrect bg_itable_unused; we'll get any real
1013                  * problems after we restart.
1014                  */
1015                 if (!(ctx->flags & E2F_FLAG_RESTART_LATER) &&
1016                     !(ext2fs_test_inode_bitmap2(ctx->inode_used_map,
1017                                                 dirent->inode)))
1018                         problem = PR_2_UNUSED_INODE;
1019
1020                 if (problem) {
1021                         if (fix_problem(ctx, problem, &cd->pctx)) {
1022                                 dirent->inode = 0;
1023                                 dir_modified++;
1024                                 goto next;
1025                         } else {
1026                                 ext2fs_unmark_valid(fs);
1027                                 if (problem == PR_2_BAD_INO)
1028                                         goto next;
1029                         }
1030                 }
1031
1032                 if (check_name(ctx, dirent, ino, &cd->pctx))
1033                         dir_modified++;
1034
1035                 if (check_filetype(ctx, dirent, ino, &cd->pctx))
1036                         dir_modified++;
1037
1038 #ifdef ENABLE_HTREE
1039                 if (dx_db) {
1040                         ext2fs_dirhash(dx_dir->hashversion, dirent->name,
1041                                        (dirent->name_len & 0xFF),
1042                                        fs->super->s_hash_seed, &hash, 0);
1043                         if (hash < dx_db->min_hash)
1044                                 dx_db->min_hash = hash;
1045                         if (hash > dx_db->max_hash)
1046                                 dx_db->max_hash = hash;
1047                 }
1048 #endif
1049
1050                 /*
1051                  * If this is a directory, then mark its parent in its
1052                  * dir_info structure.  If the parent field is already
1053                  * filled in, then this directory has more than one
1054                  * hard link.  We assume the first link is correct,
1055                  * and ask the user if he/she wants to clear this one.
1056                  */
1057                 if ((dot_state > 1) &&
1058                     (ext2fs_test_inode_bitmap2(ctx->inode_dir_map,
1059                                               dirent->inode))) {
1060                         if (e2fsck_dir_info_get_parent(ctx, dirent->inode,
1061                                                        &subdir_parent)) {
1062                                 cd->pctx.ino = dirent->inode;
1063                                 fix_problem(ctx, PR_2_NO_DIRINFO, &cd->pctx);
1064                                 goto abort_free_dict;
1065                         }
1066                         if (subdir_parent) {
1067                                 cd->pctx.ino2 = subdir_parent;
1068                                 if (fix_problem(ctx, PR_2_LINK_DIR,
1069                                                 &cd->pctx)) {
1070                                         dirent->inode = 0;
1071                                         dir_modified++;
1072                                         goto next;
1073                                 }
1074                                 cd->pctx.ino2 = 0;
1075                         } else {
1076                                 (void) e2fsck_dir_info_set_parent(ctx,
1077                                                   dirent->inode, ino);
1078                         }
1079                 }
1080
1081                 if (dups_found) {
1082                         ;
1083                 } else if (dict_lookup(&de_dict, dirent)) {
1084                         clear_problem_context(&pctx);
1085                         pctx.ino = ino;
1086                         pctx.dirent = dirent;
1087                         fix_problem(ctx, PR_2_REPORT_DUP_DIRENT, &pctx);
1088                         if (!ctx->dirs_to_hash)
1089                                 ext2fs_u32_list_create(&ctx->dirs_to_hash, 50);
1090                         if (ctx->dirs_to_hash)
1091                                 ext2fs_u32_list_add(ctx->dirs_to_hash, ino);
1092                         dups_found++;
1093                 } else
1094                         dict_alloc_insert(&de_dict, dirent, dirent);
1095
1096                 ext2fs_icount_increment(ctx->inode_count, dirent->inode,
1097                                         &links);
1098                 if (links > 1)
1099                         ctx->fs_links_count++;
1100                 ctx->fs_total_count++;
1101         next:
1102                 prev = dirent;
1103                 if (dir_modified)
1104                         (void) ext2fs_get_rec_len(fs, dirent, &rec_len);
1105                 offset += rec_len;
1106                 dot_state++;
1107         } while (offset < fs->blocksize);
1108 #if 0
1109         printf("\n");
1110 #endif
1111 #ifdef ENABLE_HTREE
1112         if (dx_db) {
1113 #ifdef DX_DEBUG
1114                 printf("db_block %d, type %d, min_hash 0x%0x, max_hash 0x%0x\n",
1115                        db->blockcnt, dx_db->type,
1116                        dx_db->min_hash, dx_db->max_hash);
1117 #endif
1118                 cd->pctx.dir = cd->pctx.ino;
1119                 if ((dx_db->type == DX_DIRBLOCK_ROOT) ||
1120                     (dx_db->type == DX_DIRBLOCK_NODE))
1121                         parse_int_node(fs, db, cd, dx_dir, buf);
1122         }
1123 #endif /* ENABLE_HTREE */
1124         if (offset != fs->blocksize) {
1125                 cd->pctx.num = rec_len - fs->blocksize + offset;
1126                 if (fix_problem(ctx, PR_2_FINAL_RECLEN, &cd->pctx)) {
1127                         dirent->rec_len = cd->pctx.num;
1128                         dir_modified++;
1129                 }
1130         }
1131         if (dir_modified) {
1132                 cd->pctx.errcode = ext2fs_write_dir_block3(fs, block_nr, buf, 0);
1133                 if (cd->pctx.errcode) {
1134                         if (!fix_problem(ctx, PR_2_WRITE_DIRBLOCK,
1135                                          &cd->pctx))
1136                                 goto abort_free_dict;
1137                 }
1138                 ext2fs_mark_changed(fs);
1139         }
1140         dict_free_nodes(&de_dict);
1141         return 0;
1142 abort_free_dict:
1143         ctx->flags |= E2F_FLAG_ABORT;
1144         dict_free_nodes(&de_dict);
1145         return DIRENT_ABORT;
1146 }
1147
1148 struct del_block {
1149         e2fsck_t        ctx;
1150         e2_blkcnt_t     num;
1151 };
1152
1153 /*
1154  * This function is called to deallocate a block, and is an interator
1155  * functioned called by deallocate inode via ext2fs_iterate_block().
1156  */
1157 static int deallocate_inode_block(ext2_filsys fs,
1158                                   blk64_t       *block_nr,
1159                                   e2_blkcnt_t blockcnt EXT2FS_ATTR((unused)),
1160                                   blk64_t ref_block EXT2FS_ATTR((unused)),
1161                                   int ref_offset EXT2FS_ATTR((unused)),
1162                                   void *priv_data)
1163 {
1164         struct del_block *p = priv_data;
1165
1166         if (HOLE_BLKADDR(*block_nr))
1167                 return 0;
1168         if ((*block_nr < fs->super->s_first_data_block) ||
1169             (*block_nr >= ext2fs_blocks_count(fs->super)))
1170                 return 0;
1171         if ((*block_nr % EXT2FS_CLUSTER_RATIO(fs)) == 0)
1172                 ext2fs_block_alloc_stats2(fs, *block_nr, -1);
1173         p->num++;
1174         return 0;
1175 }
1176
1177 /*
1178  * This fuction deallocates an inode
1179  */
1180 static void deallocate_inode(e2fsck_t ctx, ext2_ino_t ino, char* block_buf)
1181 {
1182         ext2_filsys fs = ctx->fs;
1183         struct ext2_inode       inode;
1184         struct problem_context  pctx;
1185         __u32                   count;
1186         struct del_block        del_block;
1187         int extent_fs = 0;
1188
1189         e2fsck_read_inode(ctx, ino, &inode, "deallocate_inode");
1190         /* ext2fs_block_iterate2() depends on the extents flags */
1191         if (inode.i_flags & EXT4_EXTENTS_FL)
1192                 extent_fs = 1;
1193         e2fsck_clear_inode(ctx, ino, &inode, 0, "deallocate_inode");
1194         if (extent_fs) {
1195                 inode.i_flags |= EXT4_EXTENTS_FL;
1196                 e2fsck_write_inode(ctx, ino, &inode, "deallocate_inode");
1197         }
1198         clear_problem_context(&pctx);
1199         pctx.ino = ino;
1200
1201         /*
1202          * Fix up the bitmaps...
1203          */
1204         e2fsck_read_bitmaps(ctx);
1205         ext2fs_inode_alloc_stats2(fs, ino, -1, LINUX_S_ISDIR(inode.i_mode));
1206
1207         if (ext2fs_file_acl_block(fs, &inode) &&
1208             (fs->super->s_feature_compat & EXT2_FEATURE_COMPAT_EXT_ATTR)) {
1209                 pctx.errcode = ext2fs_adjust_ea_refcount2(fs,
1210                                         ext2fs_file_acl_block(fs, &inode),
1211                                         block_buf, -1, &count);
1212                 if (pctx.errcode == EXT2_ET_BAD_EA_BLOCK_NUM) {
1213                         pctx.errcode = 0;
1214                         count = 1;
1215                 }
1216                 if (pctx.errcode) {
1217                         pctx.blk = ext2fs_file_acl_block(fs, &inode);
1218                         fix_problem(ctx, PR_2_ADJ_EA_REFCOUNT, &pctx);
1219                         ctx->flags |= E2F_FLAG_ABORT;
1220                         return;
1221                 }
1222                 if (count == 0) {
1223                         ext2fs_block_alloc_stats2(fs,
1224                                   ext2fs_file_acl_block(fs, &inode), -1);
1225                 }
1226                 if (ctx->inode_badness)
1227                         ext2fs_icount_store(ctx->inode_badness, ino, 0);
1228                 ext2fs_file_acl_block_set(fs, &inode, 0);
1229         }
1230
1231         if (!ext2fs_inode_has_valid_blocks2(fs, &inode))
1232                 goto clear_inode;
1233
1234         if (LINUX_S_ISREG(inode.i_mode) &&
1235             ext2fs_needs_large_file_feature(EXT2_I_SIZE(&inode)))
1236                 ctx->large_files--;
1237
1238         del_block.ctx = ctx;
1239         del_block.num = 0;
1240         pctx.errcode = ext2fs_block_iterate3(fs, ino, 0, block_buf,
1241                                              deallocate_inode_block,
1242                                              &del_block);
1243         if (pctx.errcode) {
1244                 fix_problem(ctx, PR_2_DEALLOC_INODE, &pctx);
1245                 ctx->flags |= E2F_FLAG_ABORT;
1246                 return;
1247         }
1248 clear_inode:
1249         /* Inode may have changed by block_iterate, so reread it */
1250         e2fsck_read_inode(ctx, ino, &inode, "deallocate_inode");
1251         e2fsck_clear_inode(ctx, ino, &inode, 0, "deallocate_inode");
1252 }
1253
1254 /*
1255  * This fuction clears the htree flag on an inode
1256  */
1257 static void clear_htree(e2fsck_t ctx, ext2_ino_t ino)
1258 {
1259         struct ext2_inode       inode;
1260
1261         e2fsck_read_inode(ctx, ino, &inode, "clear_htree");
1262         inode.i_flags = inode.i_flags & ~EXT2_INDEX_FL;
1263         e2fsck_write_inode(ctx, ino, &inode, "clear_htree");
1264         if (ctx->dirs_to_hash)
1265                 ext2fs_u32_list_add(ctx->dirs_to_hash, ino);
1266 }
1267
1268
1269 int e2fsck_process_bad_inode(e2fsck_t ctx, ext2_ino_t dir,
1270                              ext2_ino_t ino, char *buf)
1271 {
1272         ext2_filsys fs = ctx->fs;
1273         struct ext2_inode       inode;
1274         int                     inode_modified = 0;
1275         int                     not_fixed = 0;
1276         unsigned char           *frag, *fsize;
1277         struct problem_context  pctx;
1278         problem_t               problem = 0;
1279         __u16                   badness;
1280
1281         if (ctx->inode_badness)
1282                 ext2fs_icount_fetch(ctx->inode_badness, ino, &badness);
1283         e2fsck_read_inode(ctx, ino, &inode, "process_bad_inode");
1284
1285         clear_problem_context(&pctx);
1286         pctx.ino = ino;
1287         pctx.dir = dir;
1288         pctx.inode = &inode;
1289
1290         if (ext2fs_file_acl_block(fs, &inode) &&
1291             !(fs->super->s_feature_compat & EXT2_FEATURE_COMPAT_EXT_ATTR)) {
1292                 if (fix_problem(ctx, PR_2_FILE_ACL_ZERO, &pctx)) {
1293                         ext2fs_file_acl_block_set(fs, &inode, 0);
1294                         inode_modified++;
1295                 } else
1296                         not_fixed++;
1297                 badness += BADNESS_NORMAL;
1298         }
1299
1300         if (!LINUX_S_ISDIR(inode.i_mode) && !LINUX_S_ISREG(inode.i_mode) &&
1301             !LINUX_S_ISCHR(inode.i_mode) && !LINUX_S_ISBLK(inode.i_mode) &&
1302             !LINUX_S_ISLNK(inode.i_mode) && !LINUX_S_ISFIFO(inode.i_mode) &&
1303             !(LINUX_S_ISSOCK(inode.i_mode)))
1304                 problem = PR_2_BAD_MODE;
1305         else if (LINUX_S_ISCHR(inode.i_mode)
1306                  && !e2fsck_pass1_check_device_inode(fs, &inode))
1307                 problem = PR_2_BAD_CHAR_DEV;
1308         else if (LINUX_S_ISBLK(inode.i_mode)
1309                  && !e2fsck_pass1_check_device_inode(fs, &inode))
1310                 problem = PR_2_BAD_BLOCK_DEV;
1311         else if (LINUX_S_ISFIFO(inode.i_mode)
1312                  && !e2fsck_pass1_check_device_inode(fs, &inode))
1313                 problem = PR_2_BAD_FIFO;
1314         else if (LINUX_S_ISSOCK(inode.i_mode)
1315                  && !e2fsck_pass1_check_device_inode(fs, &inode))
1316                 problem = PR_2_BAD_SOCKET;
1317         else if (LINUX_S_ISLNK(inode.i_mode)
1318                  && !e2fsck_pass1_check_symlink(fs, ino, &inode, buf)) {
1319                 problem = PR_2_INVALID_SYMLINK;
1320         }
1321
1322         if (problem) {
1323                 if (fix_problem(ctx, problem, &pctx)) {
1324                         deallocate_inode(ctx, ino, 0);
1325                         if (ctx->flags & E2F_FLAG_SIGNAL_MASK)
1326                                 return 0;
1327                         return 1;
1328                 } else
1329                         not_fixed++;
1330                 problem = 0;
1331                 /*
1332                  * A high value is associated with bad mode in order to detect
1333                  * that mode was corrupt in check_filetype()
1334                  */
1335                 badness += BADNESS_BAD_MODE;
1336         }
1337
1338         if (inode.i_faddr) {
1339                 if (fix_problem(ctx, PR_2_FADDR_ZERO, &pctx)) {
1340                         inode.i_faddr = 0;
1341                         inode_modified++;
1342                 } else
1343                         not_fixed++;
1344                 badness += BADNESS_NORMAL;
1345         }
1346
1347         switch (fs->super->s_creator_os) {
1348             case EXT2_OS_HURD:
1349                 frag = &inode.osd2.hurd2.h_i_frag;
1350                 fsize = &inode.osd2.hurd2.h_i_fsize;
1351                 break;
1352             default:
1353                 frag = fsize = 0;
1354         }
1355         if (frag && *frag) {
1356                 pctx.num = *frag;
1357                 if (fix_problem(ctx, PR_2_FRAG_ZERO, &pctx)) {
1358                         *frag = 0;
1359                         inode_modified++;
1360                 } else
1361                         not_fixed++;
1362                 badness += BADNESS_NORMAL;
1363                 pctx.num = 0;
1364         }
1365         if (fsize && *fsize) {
1366                 pctx.num = *fsize;
1367                 if (fix_problem(ctx, PR_2_FSIZE_ZERO, &pctx)) {
1368                         *fsize = 0;
1369                         inode_modified++;
1370                 } else
1371                         not_fixed++;
1372                 badness += BADNESS_NORMAL;
1373                 pctx.num = 0;
1374         }
1375
1376         /* In pass1 these conditions were used to mark inode bad so that
1377          * it calls e2fsck_process_bad_inode and make an extensive check
1378          * plus prompt for action to be taken. To compensate for badness
1379          * incremented in pass1 by this condition, decrease it.
1380          */
1381         if ((inode.i_faddr || frag || fsize ||
1382              (LINUX_S_ISDIR(inode.i_mode) && inode.i_dir_acl)) ||
1383             (inode.i_file_acl &&
1384              (!(fs->super->s_feature_compat & EXT2_FEATURE_COMPAT_EXT_ATTR) ||
1385               (inode.i_file_acl < fs->super->s_first_data_block) ||
1386               (inode.i_file_acl >= fs->super->s_blocks_count)))) {
1387                 /* badness can be 0 if called from pass4. */
1388                 if (badness)
1389                         badness -= BADNESS_NORMAL;
1390         }
1391
1392         if ((fs->super->s_creator_os == EXT2_OS_LINUX) &&
1393             !(fs->super->s_feature_ro_compat &
1394               EXT4_FEATURE_RO_COMPAT_HUGE_FILE) &&
1395             (inode.osd2.linux2.l_i_blocks_hi != 0)) {
1396                 pctx.num = inode.osd2.linux2.l_i_blocks_hi;
1397                 if (fix_problem(ctx, PR_2_BLOCKS_HI_ZERO, &pctx)) {
1398                         inode.osd2.linux2.l_i_blocks_hi = 0;
1399                         inode_modified++;
1400                 }
1401                 /* Badness was increased in pass1 for this condition */
1402                 /* badness += BADNESS_NORMAL; */
1403         }
1404
1405         if ((fs->super->s_creator_os == EXT2_OS_LINUX) &&
1406             !(fs->super->s_feature_incompat &
1407              EXT4_FEATURE_INCOMPAT_64BIT) &&
1408             inode.osd2.linux2.l_i_file_acl_high != 0) {
1409                 pctx.num = inode.osd2.linux2.l_i_file_acl_high;
1410                 if (fix_problem(ctx, PR_2_I_FILE_ACL_HI_ZERO, &pctx)) {
1411                         inode.osd2.linux2.l_i_file_acl_high = 0;
1412                         inode_modified++;
1413                 } else
1414                         not_fixed++;
1415                 badness += BADNESS_NORMAL;
1416         }
1417
1418         if (ext2fs_file_acl_block(fs, &inode) &&
1419             ((ext2fs_file_acl_block(fs, &inode) < fs->super->s_first_data_block) ||
1420              (ext2fs_file_acl_block(fs, &inode) >= ext2fs_blocks_count(fs->super)))) {
1421                 if (fix_problem(ctx, PR_2_FILE_ACL_BAD, &pctx)) {
1422                         ext2fs_file_acl_block_set(fs, &inode, 0);
1423                         inode_modified++;
1424                 } else
1425                         not_fixed++;
1426                 badness += BADNESS_NORMAL;
1427         }
1428         if (inode.i_dir_acl &&
1429             LINUX_S_ISDIR(inode.i_mode)) {
1430                 if (fix_problem(ctx, PR_2_DIR_ACL_ZERO, &pctx)) {
1431                         inode.i_dir_acl = 0;
1432                         inode_modified++;
1433                 } else
1434                         not_fixed++;
1435                 badness += BADNESS_NORMAL;
1436         }
1437
1438         /*
1439          * The high value due to BADNESS_BAD_MODE should not delete the inode.
1440          */
1441         if (ctx->inode_badness && (badness - (badness >= BADNESS_BAD_MODE ?
1442                                               BADNESS_BAD_MODE : 0)) >=
1443             ctx->inode_badness_threshold) {
1444                 pctx.num = badness;
1445                 if (fix_problem(ctx, PR_2_INODE_TOOBAD, &pctx)) {
1446                         deallocate_inode(ctx, ino, 0);
1447                         if (ctx->flags & E2F_FLAG_SIGNAL_MASK)
1448                                 return 0;
1449                         return 1;
1450                 }
1451                 not_fixed++;
1452         }
1453
1454         if (inode_modified)
1455                 e2fsck_write_inode(ctx, ino, &inode, "process_bad_inode");
1456         if (ctx->inode_badness)
1457                 ext2fs_icount_store(ctx->inode_badness, ino, 0);
1458         return 0;
1459 }
1460
1461
1462 /*
1463  * allocate_dir_block --- this function allocates a new directory
1464  *      block for a particular inode; this is done if a directory has
1465  *      a "hole" in it, or if a directory has a illegal block number
1466  *      that was zeroed out and now needs to be replaced.
1467  */
1468 static int allocate_dir_block(e2fsck_t ctx,
1469                               struct ext2_db_entry2 *db,
1470                               char *buf EXT2FS_ATTR((unused)),
1471                               struct problem_context *pctx)
1472 {
1473         ext2_filsys fs = ctx->fs;
1474         blk64_t                 blk = 0;
1475         char                    *block;
1476         struct ext2_inode       inode;
1477
1478         if (fix_problem(ctx, PR_2_DIRECTORY_HOLE, pctx) == 0)
1479                 return 1;
1480
1481         /*
1482          * Read the inode and block bitmaps in; we'll be messing with
1483          * them.
1484          */
1485         e2fsck_read_bitmaps(ctx);
1486
1487         /*
1488          * First, find a free block
1489          */
1490         e2fsck_read_inode(ctx, db->ino, &inode, "allocate_dir_block");
1491         pctx->errcode = ext2fs_map_cluster_block(fs, db->ino, &inode,
1492                                                  db->blockcnt, &blk);
1493         if (pctx->errcode || blk == 0) {
1494                 pctx->errcode = ext2fs_new_block2(fs, 0,
1495                                                   ctx->block_found_map, &blk);
1496                 if (pctx->errcode) {
1497                         pctx->str = "ext2fs_new_block";
1498                         fix_problem(ctx, PR_2_ALLOC_DIRBOCK, pctx);
1499                         return 1;
1500                 }
1501         }
1502         ext2fs_mark_block_bitmap2(ctx->block_found_map, blk);
1503         ext2fs_mark_block_bitmap2(fs->block_map, blk);
1504         ext2fs_mark_bb_dirty(fs);
1505
1506         /*
1507          * Now let's create the actual data block for the inode
1508          */
1509         if (db->blockcnt)
1510                 pctx->errcode = ext2fs_new_dir_block(fs, 0, 0, &block);
1511         else
1512                 pctx->errcode = ext2fs_new_dir_block(fs, db->ino,
1513                                                      EXT2_ROOT_INO, &block);
1514
1515         if (pctx->errcode) {
1516                 pctx->str = "ext2fs_new_dir_block";
1517                 fix_problem(ctx, PR_2_ALLOC_DIRBOCK, pctx);
1518                 return 1;
1519         }
1520
1521         pctx->errcode = ext2fs_write_dir_block3(fs, blk, block, 0);
1522         ext2fs_free_mem(&block);
1523         if (pctx->errcode) {
1524                 pctx->str = "ext2fs_write_dir_block";
1525                 fix_problem(ctx, PR_2_ALLOC_DIRBOCK, pctx);
1526                 return 1;
1527         }
1528
1529         /*
1530          * Update the inode block count
1531          */
1532         ext2fs_iblk_add_blocks(fs, &inode, 1);
1533         if (EXT2_I_SIZE(&inode) < (db->blockcnt+1) * fs->blocksize) {
1534                 pctx->errcode = ext2fs_inode_size_set(fs, &inode,
1535                                         (db->blockcnt+1) * fs->blocksize);
1536                 if (pctx->errcode) {
1537                         pctx->str = "ext2fs_inode_size_set";
1538                         fix_problem(ctx, PR_2_ALLOC_DIRBOCK, pctx);
1539                         return 1;
1540                 }
1541         }
1542         e2fsck_write_inode(ctx, db->ino, &inode, "allocate_dir_block");
1543
1544         /*
1545          * Finally, update the block pointers for the inode
1546          */
1547         db->blk = blk;
1548         pctx->errcode = ext2fs_bmap2(fs, db->ino, &inode, 0, BMAP_SET,
1549                                      db->blockcnt, 0, &blk);
1550         if (pctx->errcode) {
1551                 pctx->str = "ext2fs_block_iterate";
1552                 fix_problem(ctx, PR_2_ALLOC_DIRBOCK, pctx);
1553                 return 1;
1554         }
1555
1556         return 0;
1557 }