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