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