Whamcloud - gitweb
Merge branch 'maint' into next
[tools/e2fsprogs.git] / e2fsck / pass1.c
1 /*
2  * pass1.c -- pass #1 of e2fsck: sequential scan of the inode table
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 1 of e2fsck iterates over all the inodes in the filesystems,
12  * and applies the following tests to each inode:
13  *
14  *      - The mode field of the inode must be legal.
15  *      - The size and block count fields of the inode are correct.
16  *      - A data block must not be used by another inode
17  *
18  * Pass 1 also gathers the collects the following information:
19  *
20  *      - A bitmap of which inodes are in use.          (inode_used_map)
21  *      - A bitmap of which inodes are directories.     (inode_dir_map)
22  *      - A bitmap of which inodes are regular files.   (inode_reg_map)
23  *      - A bitmap of which inodes have bad fields.     (inode_bad_map)
24  *      - A bitmap of which inodes are in bad blocks.   (inode_bb_map)
25  *      - A bitmap of which inodes are imagic inodes.   (inode_imagic_map)
26  *      - A bitmap of which blocks are in use.          (block_found_map)
27  *      - A bitmap of which blocks are in use by two inodes     (block_dup_map)
28  *      - The data blocks of the directory inodes.      (dir_map)
29  *
30  * Pass 1 is designed to stash away enough information so that the
31  * other passes should not need to read in the inode information
32  * during the normal course of a filesystem check.  (Althogh if an
33  * inconsistency is detected, other passes may need to read in an
34  * inode to fix it.)
35  *
36  * Note that pass 1B will be invoked if there are any duplicate blocks
37  * found.
38  */
39
40 #define _GNU_SOURCE 1 /* get strnlen() */
41 #include "config.h"
42 #include <string.h>
43 #include <time.h>
44 #ifdef HAVE_ERRNO_H
45 #include <errno.h>
46 #endif
47
48 #include "e2fsck.h"
49 #include <ext2fs/ext2_ext_attr.h>
50
51 #include "problem.h"
52
53 #ifdef NO_INLINE_FUNCS
54 #define _INLINE_
55 #else
56 #define _INLINE_ inline
57 #endif
58
59 static int process_block(ext2_filsys fs, blk64_t        *blocknr,
60                          e2_blkcnt_t blockcnt, blk64_t ref_blk,
61                          int ref_offset, void *priv_data);
62 static int process_bad_block(ext2_filsys fs, blk64_t *block_nr,
63                              e2_blkcnt_t blockcnt, blk64_t ref_blk,
64                              int ref_offset, void *priv_data);
65 static void check_blocks(e2fsck_t ctx, struct problem_context *pctx,
66                          char *block_buf);
67 static void mark_table_blocks(e2fsck_t ctx);
68 static void alloc_bb_map(e2fsck_t ctx);
69 static void alloc_imagic_map(e2fsck_t ctx);
70 static void mark_inode_bad(e2fsck_t ctx, ino_t ino);
71 static void handle_fs_bad_blocks(e2fsck_t ctx);
72 static void process_inodes(e2fsck_t ctx, char *block_buf);
73 static EXT2_QSORT_TYPE process_inode_cmp(const void *a, const void *b);
74 static errcode_t scan_callback(ext2_filsys fs, ext2_inode_scan scan,
75                                   dgrp_t group, void * priv_data);
76 static void adjust_extattr_refcount(e2fsck_t ctx, ext2_refcount_t refcount,
77                                     char *block_buf, int adjust_sign);
78 /* static char *describe_illegal_block(ext2_filsys fs, blk64_t block); */
79
80 struct process_block_struct {
81         ext2_ino_t      ino;
82         unsigned        is_dir:1, is_reg:1, clear:1, suppress:1,
83                                 fragmented:1, compressed:1, bbcheck:1,
84                                 inode_modified:1;
85         blk64_t         num_blocks;
86         blk64_t         max_blocks;
87         e2_blkcnt_t     last_block;
88         e2_blkcnt_t     last_init_lblock;
89         e2_blkcnt_t     last_db_block;
90         int             num_illegal_blocks;
91         blk64_t         previous_block;
92         struct ext2_inode *inode;
93         struct problem_context *pctx;
94         ext2fs_block_bitmap fs_meta_blocks;
95         e2fsck_t        ctx;
96         blk64_t         bad_ref;
97 };
98
99 struct process_inode_block {
100         ext2_ino_t ino;
101         struct ext2_inode inode;
102 };
103
104 struct scan_callback_struct {
105         e2fsck_t        ctx;
106         char            *block_buf;
107 };
108
109 /*
110  * For the inodes to process list.
111  */
112 static struct process_inode_block *inodes_to_process;
113 static int process_inode_count;
114
115 static __u64 ext2_max_sizes[EXT2_MAX_BLOCK_LOG_SIZE -
116                             EXT2_MIN_BLOCK_LOG_SIZE + 1];
117
118 /*
119  * Free all memory allocated by pass1 in preparation for restarting
120  * things.
121  */
122 static void unwind_pass1(ext2_filsys fs EXT2FS_ATTR((unused)))
123 {
124         ext2fs_free_mem(&inodes_to_process);
125         inodes_to_process = 0;
126 }
127
128 /*
129  * Check to make sure a device inode is real.  Returns 1 if the device
130  * checks out, 0 if not.
131  *
132  * Note: this routine is now also used to check FIFO's and Sockets,
133  * since they have the same requirement; the i_block fields should be
134  * zero.
135  */
136 int e2fsck_pass1_check_device_inode(ext2_filsys fs EXT2FS_ATTR((unused)),
137                                     struct ext2_inode *inode)
138 {
139         int     i;
140
141         /*
142          * If the index flag is set, then this is a bogus
143          * device/fifo/socket
144          */
145         if (inode->i_flags & EXT2_INDEX_FL)
146                 return 0;
147
148         /*
149          * We should be able to do the test below all the time, but
150          * because the kernel doesn't forcibly clear the device
151          * inode's additional i_block fields, there are some rare
152          * occasions when a legitimate device inode will have non-zero
153          * additional i_block fields.  So for now, we only complain
154          * when the immutable flag is set, which should never happen
155          * for devices.  (And that's when the problem is caused, since
156          * you can't set or clear immutable flags for devices.)  Once
157          * the kernel has been fixed we can change this...
158          */
159         if (inode->i_flags & (EXT2_IMMUTABLE_FL | EXT2_APPEND_FL)) {
160                 for (i=4; i < EXT2_N_BLOCKS; i++)
161                         if (inode->i_block[i])
162                                 return 0;
163         }
164         return 1;
165 }
166
167 /*
168  * Check to make sure a symlink inode is real.  Returns 1 if the symlink
169  * checks out, 0 if not.
170  */
171 int e2fsck_pass1_check_symlink(ext2_filsys fs, ext2_ino_t ino,
172                                struct ext2_inode *inode, char *buf)
173 {
174         unsigned int len;
175         int i;
176         blk64_t blocks;
177         ext2_extent_handle_t    handle;
178         struct ext2_extent_info info;
179         struct ext2fs_extent    extent;
180
181         if ((inode->i_size_high || inode->i_size == 0) ||
182             (inode->i_flags & EXT2_INDEX_FL))
183                 return 0;
184
185         if (inode->i_flags & EXT4_EXTENTS_FL) {
186                 if (inode->i_size > fs->blocksize)
187                         return 0;
188                 if (ext2fs_extent_open2(fs, ino, inode, &handle))
189                         return 0;
190                 i = 0;
191                 if (ext2fs_extent_get_info(handle, &info) ||
192                     (info.num_entries != 1) ||
193                     (info.max_depth != 0))
194                         goto exit_extent;
195                 if (ext2fs_extent_get(handle, EXT2_EXTENT_ROOT, &extent) ||
196                     (extent.e_lblk != 0) ||
197                     (extent.e_len != 1) ||
198                     (extent.e_pblk < fs->super->s_first_data_block) ||
199                     (extent.e_pblk >= ext2fs_blocks_count(fs->super)))
200                         goto exit_extent;
201                 i = 1;
202         exit_extent:
203                 ext2fs_extent_free(handle);
204                 return i;
205         }
206
207         if (inode->i_flags & EXT4_INLINE_DATA_FL) {
208                 size_t inline_size;
209
210                 if (ext2fs_inline_data_size(fs, ino, &inline_size))
211                         return 0;
212                 if (inode->i_size != inline_size)
213                         return 0;
214
215                 return 1;
216         }
217
218         blocks = ext2fs_inode_data_blocks2(fs, inode);
219         if (blocks) {
220                 if ((inode->i_size >= fs->blocksize) ||
221                     (blocks != fs->blocksize >> 9) ||
222                     (inode->i_block[0] < fs->super->s_first_data_block) ||
223                     (inode->i_block[0] >= ext2fs_blocks_count(fs->super)))
224                         return 0;
225
226                 for (i = 1; i < EXT2_N_BLOCKS; i++)
227                         if (inode->i_block[i])
228                                 return 0;
229
230                 if (io_channel_read_blk64(fs->io, inode->i_block[0], 1, buf))
231                         return 0;
232
233                 len = strnlen(buf, fs->blocksize);
234                 if (len == fs->blocksize)
235                         return 0;
236         } else {
237                 if (inode->i_size >= sizeof(inode->i_block))
238                         return 0;
239
240                 len = strnlen((char *)inode->i_block, sizeof(inode->i_block));
241                 if (len == sizeof(inode->i_block))
242                         return 0;
243         }
244         if (len != inode->i_size)
245                 return 0;
246         return 1;
247 }
248
249 /*
250  * If the immutable (or append-only) flag is set on the inode, offer
251  * to clear it.
252  */
253 #define BAD_SPECIAL_FLAGS (EXT2_IMMUTABLE_FL | EXT2_APPEND_FL)
254 static void check_immutable(e2fsck_t ctx, struct problem_context *pctx)
255 {
256         if (!(pctx->inode->i_flags & BAD_SPECIAL_FLAGS))
257                 return;
258
259         if (!fix_problem(ctx, PR_1_SET_IMMUTABLE, pctx))
260                 return;
261
262         pctx->inode->i_flags &= ~BAD_SPECIAL_FLAGS;
263         e2fsck_write_inode(ctx, pctx->ino, pctx->inode, "pass1");
264 }
265
266 /*
267  * If device, fifo or socket, check size is zero -- if not offer to
268  * clear it
269  */
270 static void check_size(e2fsck_t ctx, struct problem_context *pctx)
271 {
272         struct ext2_inode *inode = pctx->inode;
273
274         if (EXT2_I_SIZE(inode) == 0)
275                 return;
276
277         if (!fix_problem(ctx, PR_1_SET_NONZSIZE, pctx))
278                 return;
279
280         inode->i_size = 0;
281         inode->i_size_high = 0;
282         e2fsck_write_inode(ctx, pctx->ino, pctx->inode, "pass1");
283 }
284
285 static void check_ea_in_inode(e2fsck_t ctx, struct problem_context *pctx)
286 {
287         struct ext2_super_block *sb = ctx->fs->super;
288         struct ext2_inode_large *inode;
289         struct ext2_ext_attr_entry *entry;
290         char *start;
291         unsigned int storage_size, remain;
292         problem_t problem = 0;
293
294         inode = (struct ext2_inode_large *) pctx->inode;
295         storage_size = EXT2_INODE_SIZE(ctx->fs->super) - EXT2_GOOD_OLD_INODE_SIZE -
296                 inode->i_extra_isize;
297         start = ((char *) inode) + EXT2_GOOD_OLD_INODE_SIZE +
298                 inode->i_extra_isize + sizeof(__u32);
299         entry = (struct ext2_ext_attr_entry *) start;
300
301         /* scan all entry's headers first */
302
303         /* take finish entry 0UL into account */
304         remain = storage_size - sizeof(__u32);
305
306         while (!EXT2_EXT_IS_LAST_ENTRY(entry)) {
307                 __u32 hash;
308
309                 /* header eats this space */
310                 remain -= sizeof(struct ext2_ext_attr_entry);
311
312                 /* is attribute name valid? */
313                 if (EXT2_EXT_ATTR_SIZE(entry->e_name_len) > remain) {
314                         pctx->num = entry->e_name_len;
315                         problem = PR_1_ATTR_NAME_LEN;
316                         goto fix;
317                 }
318
319                 /* attribute len eats this space */
320                 remain -= EXT2_EXT_ATTR_SIZE(entry->e_name_len);
321
322                 /* check value size */
323                 if (entry->e_value_size > remain) {
324                         pctx->num = entry->e_value_size;
325                         problem = PR_1_ATTR_VALUE_SIZE;
326                         goto fix;
327                 }
328
329                 /* e_value_block must be 0 in inode's ea */
330                 if (entry->e_value_block != 0) {
331                         pctx->num = entry->e_value_block;
332                         problem = PR_1_ATTR_VALUE_BLOCK;
333                         goto fix;
334                 }
335
336                 hash = ext2fs_ext_attr_hash_entry(entry,
337                                                   start + entry->e_value_offs);
338
339                 /* e_hash may be 0 in older inode's ea */
340                 if (entry->e_hash != 0 && entry->e_hash != hash) {
341                         pctx->num = entry->e_hash;
342                         problem = PR_1_ATTR_HASH;
343                         goto fix;
344                 }
345
346                 remain -= entry->e_value_size;
347
348                 entry = EXT2_EXT_ATTR_NEXT(entry);
349         }
350 fix:
351         /*
352          * it seems like a corruption. it's very unlikely we could repair
353          * EA(s) in automatic fashion -bzzz
354          */
355         if (problem == 0 || !fix_problem(ctx, problem, pctx))
356                 return;
357
358         /* simply remove all possible EA(s) */
359         *((__u32 *)start) = 0UL;
360         e2fsck_write_inode_full(ctx, pctx->ino, pctx->inode,
361                                 EXT2_INODE_SIZE(sb), "pass1");
362 }
363
364 static void check_inode_extra_space(e2fsck_t ctx, struct problem_context *pctx)
365 {
366         struct ext2_super_block *sb = ctx->fs->super;
367         struct ext2_inode_large *inode;
368         __u32 *eamagic;
369         int min, max;
370
371         inode = (struct ext2_inode_large *) pctx->inode;
372         if (EXT2_INODE_SIZE(sb) == EXT2_GOOD_OLD_INODE_SIZE) {
373                 /* this isn't large inode. so, nothing to check */
374                 return;
375         }
376
377 #if 0
378         printf("inode #%u, i_extra_size %d\n", pctx->ino,
379                         inode->i_extra_isize);
380 #endif
381         /* i_extra_isize must cover i_extra_isize + i_checksum_hi at least */
382         min = sizeof(inode->i_extra_isize) + sizeof(inode->i_checksum_hi);
383         max = EXT2_INODE_SIZE(sb) - EXT2_GOOD_OLD_INODE_SIZE;
384         /*
385          * For now we will allow i_extra_isize to be 0, but really
386          * implementations should never allow i_extra_isize to be 0
387          */
388         if (inode->i_extra_isize &&
389             (inode->i_extra_isize < min || inode->i_extra_isize > max)) {
390                 if (!fix_problem(ctx, PR_1_EXTRA_ISIZE, pctx))
391                         return;
392                 inode->i_extra_isize = min;
393                 e2fsck_write_inode_full(ctx, pctx->ino, pctx->inode,
394                                         EXT2_INODE_SIZE(sb), "pass1");
395                 return;
396         }
397
398         eamagic = (__u32 *) (((char *) inode) + EXT2_GOOD_OLD_INODE_SIZE +
399                         inode->i_extra_isize);
400         if (*eamagic == EXT2_EXT_ATTR_MAGIC) {
401                 /* it seems inode has an extended attribute(s) in body */
402                 check_ea_in_inode(ctx, pctx);
403         }
404 }
405
406 /*
407  * Check to see if the inode might really be a directory, despite i_mode
408  *
409  * This is a lot of complexity for something for which I'm not really
410  * convinced happens frequently in the wild.  If for any reason this
411  * causes any problems, take this code out.
412  * [tytso:20070331.0827EDT]
413  */
414 static void check_is_really_dir(e2fsck_t ctx, struct problem_context *pctx,
415                                 char *buf)
416 {
417         struct ext2_inode *inode = pctx->inode;
418         struct ext2_dir_entry   *dirent;
419         errcode_t               retval;
420         blk64_t                 blk;
421         unsigned int            i, rec_len, not_device = 0;
422         int                     extent_fs;
423         int                     inlinedata_fs;
424
425         /*
426          * If the mode looks OK, we believe it.  If the first block in
427          * the i_block array is 0, this cannot be a directory. If the
428          * inode is extent-mapped, it is still the case that the latter
429          * cannot be 0 - the magic number in the extent header would make
430          * it nonzero.
431          */
432         if (LINUX_S_ISDIR(inode->i_mode) || LINUX_S_ISREG(inode->i_mode) ||
433             LINUX_S_ISLNK(inode->i_mode) || inode->i_block[0] == 0)
434                 return;
435
436         /* 
437          * Check the block numbers in the i_block array for validity:
438          * zero blocks are skipped (but the first one cannot be zero -
439          * see above), other blocks are checked against the first and
440          * max data blocks (from the the superblock) and against the
441          * block bitmap. Any invalid block found means this cannot be
442          * a directory.
443          * 
444          * If there are non-zero blocks past the fourth entry, then
445          * this cannot be a device file: we remember that for the next
446          * check.
447          *
448          * For extent mapped files, we don't do any sanity checking:
449          * just try to get the phys block of logical block 0 and run
450          * with it.
451          *
452          * For inline data files, we just try to get the size of inline
453          * data.  If it's true, we will treat it as a directory.
454          */
455
456         extent_fs = (ctx->fs->super->s_feature_incompat &
457                      EXT3_FEATURE_INCOMPAT_EXTENTS);
458         inlinedata_fs = (ctx->fs->super->s_feature_incompat &
459                          EXT4_FEATURE_INCOMPAT_INLINE_DATA);
460         if (inlinedata_fs && (inode->i_flags & EXT4_INLINE_DATA_FL)) {
461                 size_t size;
462
463                 if (ext2fs_inline_data_size(ctx->fs, pctx->ino, &size))
464                         return;
465                 /* device files never have a "system.data" entry */
466                 goto isdir;
467         } else if (extent_fs && (inode->i_flags & EXT4_EXTENTS_FL)) {
468                 /* extent mapped */
469                 if  (ext2fs_bmap2(ctx->fs, pctx->ino, inode, 0, 0, 0, 0,
470                                  &blk))
471                         return;
472                 /* device files are never extent mapped */
473                 not_device++;
474         } else {
475                 for (i=0; i < EXT2_N_BLOCKS; i++) {
476                         blk = inode->i_block[i];
477                         if (!blk)
478                                 continue;
479                         if (i >= 4)
480                                 not_device++;
481
482                         if (blk < ctx->fs->super->s_first_data_block ||
483                             blk >= ext2fs_blocks_count(ctx->fs->super) ||
484                             ext2fs_fast_test_block_bitmap2(ctx->block_found_map,
485                                                            blk))
486                                 return; /* Invalid block, can't be dir */
487                 }
488                 blk = inode->i_block[0];
489         }
490
491         /*
492          * If the mode says this is a device file and the i_links_count field
493          * is sane and we have not ruled it out as a device file previously,
494          * we declare it a device file, not a directory.
495          */
496         if ((LINUX_S_ISCHR(inode->i_mode) || LINUX_S_ISBLK(inode->i_mode)) &&
497             (inode->i_links_count == 1) && !not_device)
498                 return;
499
500         /* read the first block */
501         ehandler_operation(_("reading directory block"));
502         retval = ext2fs_read_dir_block4(ctx->fs, blk, buf, 0, pctx->ino);
503         ehandler_operation(0);
504         if (retval)
505                 return;
506
507         dirent = (struct ext2_dir_entry *) buf;
508         retval = ext2fs_get_rec_len(ctx->fs, dirent, &rec_len);
509         if (retval)
510                 return;
511         if ((ext2fs_dirent_name_len(dirent) != 1) ||
512             (dirent->name[0] != '.') ||
513             (dirent->inode != pctx->ino) ||
514             (rec_len < 12) ||
515             (rec_len % 4) ||
516             (rec_len >= ctx->fs->blocksize - 12))
517                 return;
518
519         dirent = (struct ext2_dir_entry *) (buf + rec_len);
520         retval = ext2fs_get_rec_len(ctx->fs, dirent, &rec_len);
521         if (retval)
522                 return;
523         if ((ext2fs_dirent_name_len(dirent) != 2) ||
524             (dirent->name[0] != '.') ||
525             (dirent->name[1] != '.') ||
526             (rec_len < 12) ||
527             (rec_len % 4))
528                 return;
529
530 isdir:
531         if (fix_problem(ctx, PR_1_TREAT_AS_DIRECTORY, pctx)) {
532                 inode->i_mode = (inode->i_mode & 07777) | LINUX_S_IFDIR;
533                 e2fsck_write_inode_full(ctx, pctx->ino, inode,
534                                         EXT2_INODE_SIZE(ctx->fs->super),
535                                         "check_is_really_dir");
536         }
537 }
538
539 void e2fsck_setup_tdb_icount(e2fsck_t ctx, int flags,
540                              ext2_icount_t *ret)
541 {
542         unsigned int            threshold;
543         ext2_ino_t              num_dirs;
544         errcode_t               retval;
545         char                    *tdb_dir;
546         int                     enable;
547
548         *ret = 0;
549
550         profile_get_string(ctx->profile, "scratch_files", "directory", 0, 0,
551                            &tdb_dir);
552         profile_get_uint(ctx->profile, "scratch_files",
553                          "numdirs_threshold", 0, 0, &threshold);
554         profile_get_boolean(ctx->profile, "scratch_files",
555                             "icount", 0, 1, &enable);
556
557         retval = ext2fs_get_num_dirs(ctx->fs, &num_dirs);
558         if (retval)
559                 num_dirs = 1024;        /* Guess */
560
561         if (!enable || !tdb_dir || access(tdb_dir, W_OK) ||
562             (threshold && num_dirs <= threshold))
563                 return;
564
565         retval = ext2fs_create_icount_tdb(ctx->fs, tdb_dir, flags, ret);
566         if (retval)
567                 *ret = 0;
568 }
569
570 static errcode_t recheck_bad_inode_checksum(ext2_filsys fs, ext2_ino_t ino,
571                                             e2fsck_t ctx,
572                                             struct problem_context *pctx)
573 {
574         errcode_t retval;
575         struct ext2_inode_large inode;
576
577         /*
578          * Reread inode.  If we don't see checksum error, then this inode
579          * has been fixed elsewhere.
580          */
581         retval = ext2fs_read_inode_full(fs, ino, (struct ext2_inode *)&inode,
582                                         sizeof(inode));
583         if (retval && retval != EXT2_ET_INODE_CSUM_INVALID)
584                 return retval;
585         if (!retval)
586                 return 0;
587
588         /*
589          * Checksum still doesn't match.  That implies that the inode passes
590          * all the sanity checks, so maybe the checksum is simply corrupt.
591          * See if the user will go for fixing that.
592          */
593         if (!fix_problem(ctx, PR_1_INODE_ONLY_CSUM_INVALID, pctx))
594                 return 0;
595
596         retval = ext2fs_write_inode_full(fs, ino, (struct ext2_inode *)&inode,
597                                          sizeof(inode));
598         if (retval)
599                 return retval;
600
601         return 0;
602 }
603
604 void e2fsck_pass1(e2fsck_t ctx)
605 {
606         int     i;
607         __u64   max_sizes;
608         ext2_filsys fs = ctx->fs;
609         ext2_ino_t      ino = 0;
610         struct ext2_inode *inode = NULL;
611         ext2_inode_scan scan = NULL;
612         char            *block_buf = NULL;
613 #ifdef RESOURCE_TRACK
614         struct resource_track   rtrack;
615 #endif
616         unsigned char   frag, fsize;
617         struct          problem_context pctx;
618         struct          scan_callback_struct scan_struct;
619         struct ext2_super_block *sb = ctx->fs->super;
620         const char      *old_op;
621         unsigned int    save_type;
622         int             imagic_fs, extent_fs, inlinedata_fs;
623         int             low_dtime_check = 1;
624         int             inode_size;
625         int             failed_csum = 0;
626
627         init_resource_track(&rtrack, ctx->fs->io);
628         clear_problem_context(&pctx);
629
630         if (!(ctx->options & E2F_OPT_PREEN))
631                 fix_problem(ctx, PR_1_PASS_HEADER, &pctx);
632
633         if ((fs->super->s_feature_compat & EXT2_FEATURE_COMPAT_DIR_INDEX) &&
634             !(ctx->options & E2F_OPT_NO)) {
635                 if (ext2fs_u32_list_create(&ctx->dirs_to_hash, 50))
636                         ctx->dirs_to_hash = 0;
637         }
638
639 #ifdef MTRACE
640         mtrace_print("Pass 1");
641 #endif
642
643 #define EXT2_BPP(bits) (1ULL << ((bits) - 2))
644
645         for (i = EXT2_MIN_BLOCK_LOG_SIZE; i <= EXT2_MAX_BLOCK_LOG_SIZE; i++) {
646                 max_sizes = EXT2_NDIR_BLOCKS + EXT2_BPP(i);
647                 max_sizes = max_sizes + EXT2_BPP(i) * EXT2_BPP(i);
648                 max_sizes = max_sizes + EXT2_BPP(i) * EXT2_BPP(i) * EXT2_BPP(i);
649                 max_sizes = (max_sizes * (1UL << i));
650                 ext2_max_sizes[i - EXT2_MIN_BLOCK_LOG_SIZE] = max_sizes;
651         }
652 #undef EXT2_BPP
653
654         imagic_fs = (sb->s_feature_compat & EXT2_FEATURE_COMPAT_IMAGIC_INODES);
655         extent_fs = (sb->s_feature_incompat & EXT3_FEATURE_INCOMPAT_EXTENTS);
656         inlinedata_fs = (sb->s_feature_incompat &
657                         EXT4_FEATURE_INCOMPAT_INLINE_DATA);
658
659         /*
660          * Allocate bitmaps structures
661          */
662         pctx.errcode = e2fsck_allocate_inode_bitmap(fs, _("in-use inode map"),
663                                                     EXT2FS_BMAP64_RBTREE,
664                                                     "inode_used_map",
665                                                     &ctx->inode_used_map);
666         if (pctx.errcode) {
667                 pctx.num = 1;
668                 fix_problem(ctx, PR_1_ALLOCATE_IBITMAP_ERROR, &pctx);
669                 ctx->flags |= E2F_FLAG_ABORT;
670                 return;
671         }
672         pctx.errcode = e2fsck_allocate_inode_bitmap(fs,
673                         _("directory inode map"),
674                         EXT2FS_BMAP64_AUTODIR,
675                         "inode_dir_map", &ctx->inode_dir_map);
676         if (pctx.errcode) {
677                 pctx.num = 2;
678                 fix_problem(ctx, PR_1_ALLOCATE_IBITMAP_ERROR, &pctx);
679                 ctx->flags |= E2F_FLAG_ABORT;
680                 return;
681         }
682         pctx.errcode = e2fsck_allocate_inode_bitmap(fs,
683                         _("regular file inode map"), EXT2FS_BMAP64_RBTREE,
684                         "inode_reg_map", &ctx->inode_reg_map);
685         if (pctx.errcode) {
686                 pctx.num = 6;
687                 fix_problem(ctx, PR_1_ALLOCATE_IBITMAP_ERROR, &pctx);
688                 ctx->flags |= E2F_FLAG_ABORT;
689                 return;
690         }
691         pctx.errcode = e2fsck_allocate_subcluster_bitmap(fs,
692                         _("in-use block map"), EXT2FS_BMAP64_RBTREE,
693                         "block_found_map", &ctx->block_found_map);
694         if (pctx.errcode) {
695                 pctx.num = 1;
696                 fix_problem(ctx, PR_1_ALLOCATE_BBITMAP_ERROR, &pctx);
697                 ctx->flags |= E2F_FLAG_ABORT;
698                 return;
699         }
700         pctx.errcode = e2fsck_allocate_block_bitmap(fs,
701                         _("metadata block map"), EXT2FS_BMAP64_RBTREE,
702                         "block_metadata_map", &ctx->block_metadata_map);
703         if (pctx.errcode) {
704                 pctx.num = 1;
705                 fix_problem(ctx, PR_1_ALLOCATE_BBITMAP_ERROR, &pctx);
706                 ctx->flags |= E2F_FLAG_ABORT;
707                 return;
708         }
709         e2fsck_setup_tdb_icount(ctx, 0, &ctx->inode_link_info);
710         if (!ctx->inode_link_info) {
711                 e2fsck_set_bitmap_type(fs, EXT2FS_BMAP64_RBTREE,
712                                        "inode_link_info", &save_type);
713                 pctx.errcode = ext2fs_create_icount2(fs, 0, 0, 0,
714                                                      &ctx->inode_link_info);
715                 fs->default_bitmap_type = save_type;
716         }
717
718         if (pctx.errcode) {
719                 fix_problem(ctx, PR_1_ALLOCATE_ICOUNT, &pctx);
720                 ctx->flags |= E2F_FLAG_ABORT;
721                 return;
722         }
723         inode_size = EXT2_INODE_SIZE(fs->super);
724         inode = (struct ext2_inode *)
725                 e2fsck_allocate_memory(ctx, inode_size, "scratch inode");
726
727         inodes_to_process = (struct process_inode_block *)
728                 e2fsck_allocate_memory(ctx,
729                                        (ctx->process_inode_size *
730                                         sizeof(struct process_inode_block)),
731                                        "array of inodes to process");
732         process_inode_count = 0;
733
734         pctx.errcode = ext2fs_init_dblist(fs, 0);
735         if (pctx.errcode) {
736                 fix_problem(ctx, PR_1_ALLOCATE_DBCOUNT, &pctx);
737                 ctx->flags |= E2F_FLAG_ABORT;
738                 goto endit;
739         }
740
741         /*
742          * If the last orphan field is set, clear it, since the pass1
743          * processing will automatically find and clear the orphans.
744          * In the future, we may want to try using the last_orphan
745          * linked list ourselves, but for now, we clear it so that the
746          * ext3 mount code won't get confused.
747          */
748         if (!(ctx->options & E2F_OPT_READONLY)) {
749                 if (fs->super->s_last_orphan) {
750                         fs->super->s_last_orphan = 0;
751                         ext2fs_mark_super_dirty(fs);
752                 }
753         }
754
755         mark_table_blocks(ctx);
756         pctx.errcode = ext2fs_convert_subcluster_bitmap(fs,
757                                                 &ctx->block_found_map);
758         if (pctx.errcode) {
759                 fix_problem(ctx, PR_1_CONVERT_SUBCLUSTER, &pctx);
760                 ctx->flags |= E2F_FLAG_ABORT;
761                 goto endit;
762         }
763         block_buf = (char *) e2fsck_allocate_memory(ctx, fs->blocksize * 3,
764                                                     "block interate buffer");
765         if (EXT2_INODE_SIZE(fs->super) == EXT2_GOOD_OLD_INODE_SIZE)
766                 e2fsck_use_inode_shortcuts(ctx, 1);
767         e2fsck_intercept_block_allocations(ctx);
768         old_op = ehandler_operation(_("opening inode scan"));
769         pctx.errcode = ext2fs_open_inode_scan(fs, ctx->inode_buffer_blocks,
770                                               &scan);
771         ehandler_operation(old_op);
772         if (pctx.errcode) {
773                 fix_problem(ctx, PR_1_ISCAN_ERROR, &pctx);
774                 ctx->flags |= E2F_FLAG_ABORT;
775                 goto endit;
776         }
777         ext2fs_inode_scan_flags(scan, EXT2_SF_SKIP_MISSING_ITABLE, 0);
778         ctx->stashed_inode = inode;
779         scan_struct.ctx = ctx;
780         scan_struct.block_buf = block_buf;
781         ext2fs_set_inode_callback(scan, scan_callback, &scan_struct);
782         if (ctx->progress && ((ctx->progress)(ctx, 1, 0,
783                                               ctx->fs->group_desc_count)))
784                 goto endit;
785         if ((fs->super->s_wtime < fs->super->s_inodes_count) ||
786             (fs->super->s_mtime < fs->super->s_inodes_count) ||
787             (fs->super->s_mkfs_time &&
788              fs->super->s_mkfs_time < fs->super->s_inodes_count))
789                 low_dtime_check = 0;
790
791         if ((fs->super->s_feature_incompat & EXT4_FEATURE_INCOMPAT_MMP) &&
792             fs->super->s_mmp_block > fs->super->s_first_data_block &&
793             fs->super->s_mmp_block < ext2fs_blocks_count(fs->super))
794                 ext2fs_mark_block_bitmap2(ctx->block_found_map,
795                                           fs->super->s_mmp_block);
796
797         /* Set up ctx->lost_and_found if possible */
798         (void) e2fsck_get_lost_and_found(ctx, 0);
799
800         while (1) {
801                 if (ino % (fs->super->s_inodes_per_group * 4) == 1) {
802                         if (e2fsck_mmp_update(fs))
803                                 fatal_error(ctx, 0);
804                 }
805                 old_op = ehandler_operation(_("getting next inode from scan"));
806                 pctx.errcode = ext2fs_get_next_inode_full(scan, &ino,
807                                                           inode, inode_size);
808                 ehandler_operation(old_op);
809                 if (ctx->flags & E2F_FLAG_SIGNAL_MASK)
810                         return;
811                 if (pctx.errcode == EXT2_ET_BAD_BLOCK_IN_INODE_TABLE) {
812                         if (!ctx->inode_bb_map)
813                                 alloc_bb_map(ctx);
814                         ext2fs_mark_inode_bitmap2(ctx->inode_bb_map, ino);
815                         ext2fs_mark_inode_bitmap2(ctx->inode_used_map, ino);
816                         continue;
817                 }
818                 if (pctx.errcode &&
819                     pctx.errcode != EXT2_ET_INODE_CSUM_INVALID) {
820                         fix_problem(ctx, PR_1_ISCAN_ERROR, &pctx);
821                         ctx->flags |= E2F_FLAG_ABORT;
822                         goto endit;
823                 }
824                 if (!ino)
825                         break;
826                 pctx.ino = ino;
827                 pctx.inode = inode;
828                 ctx->stashed_ino = ino;
829
830                 /* Clear corrupt inode? */
831                 if (pctx.errcode == EXT2_ET_INODE_CSUM_INVALID) {
832                         if (fix_problem(ctx, PR_1_INODE_CSUM_INVALID, &pctx))
833                                 goto clear_inode;
834                         failed_csum = 1;
835                 }
836
837                 if (inode->i_links_count) {
838                         pctx.errcode = ext2fs_icount_store(ctx->inode_link_info,
839                                            ino, inode->i_links_count);
840                         if (pctx.errcode) {
841                                 pctx.num = inode->i_links_count;
842                                 fix_problem(ctx, PR_1_ICOUNT_STORE, &pctx);
843                                 ctx->flags |= E2F_FLAG_ABORT;
844                                 goto endit;
845                         }
846                 }
847
848                 /* Test for incorrect inline_data flags settings. */
849                 if ((inode->i_flags & EXT4_INLINE_DATA_FL) && !inlinedata_fs &&
850                     (ino >= EXT2_FIRST_INODE(fs->super))) {
851                         size_t size = 0;
852
853                         pctx.errcode = ext2fs_inline_data_size(fs, ino, &size);
854                         if (!pctx.errcode && size &&
855                             !fix_problem(ctx, PR_1_INLINE_DATA_FEATURE, &pctx)) {
856                                 sb->s_feature_incompat |=
857                                         EXT4_FEATURE_INCOMPAT_INLINE_DATA;
858                                 ext2fs_mark_super_dirty(fs);
859                                 inlinedata_fs = 1;
860                         } else if (!fix_problem(ctx, PR_1_INLINE_DATA_SET, &pctx)) {
861                                 e2fsck_clear_inode(ctx, ino, inode, 0, "pass1");
862                                 continue;
863                         }
864                 }
865
866                 /*
867                  * Test for incorrect extent flag settings.
868                  *
869                  * On big-endian machines we must be careful:
870                  * When the inode is read, the i_block array is not swapped
871                  * if the extent flag is set.  Therefore if we are testing
872                  * for or fixing a wrongly-set flag, we must potentially
873                  * (un)swap before testing, or after fixing.
874                  */
875
876                 /*
877                  * In this case the extents flag was set when read, so
878                  * extent_header_verify is ok.  If the inode is cleared,
879                  * no need to swap... so no extra swapping here.
880                  */
881                 if ((inode->i_flags & EXT4_EXTENTS_FL) && !extent_fs &&
882                     (inode->i_links_count || (ino == EXT2_BAD_INO) ||
883                      (ino == EXT2_ROOT_INO) || (ino == EXT2_JOURNAL_INO))) {
884                         if ((ext2fs_extent_header_verify(inode->i_block,
885                                                  sizeof(inode->i_block)) == 0) &&
886                             fix_problem(ctx, PR_1_EXTENT_FEATURE, &pctx)) {
887                                 sb->s_feature_incompat |= EXT3_FEATURE_INCOMPAT_EXTENTS;
888                                 ext2fs_mark_super_dirty(fs);
889                                 extent_fs = 1;
890                         } else if (fix_problem(ctx, PR_1_EXTENTS_SET, &pctx)) {
891                         clear_inode:
892                                 e2fsck_clear_inode(ctx, ino, inode, 0, "pass1");
893                                 if (ino == EXT2_BAD_INO)
894                                         ext2fs_mark_inode_bitmap2(ctx->inode_used_map,
895                                                                  ino);
896                                 continue;
897                         }
898                 }
899
900                 /*
901                  * For big-endian machines:
902                  * If the inode didn't have the extents flag set when it
903                  * was read, then the i_blocks array was swapped.  To test
904                  * as an extents header, we must swap it back first.
905                  * IF we then set the extents flag, the entire i_block
906                  * array must be un/re-swapped to make it proper extents data.
907                  */
908                 if (extent_fs && !(inode->i_flags & EXT4_EXTENTS_FL) &&
909                     (inode->i_links_count || (ino == EXT2_BAD_INO) ||
910                      (ino == EXT2_ROOT_INO) || (ino == EXT2_JOURNAL_INO)) &&
911                     (LINUX_S_ISREG(inode->i_mode) ||
912                      LINUX_S_ISDIR(inode->i_mode))) {
913                         void *ehp;
914 #ifdef WORDS_BIGENDIAN
915                         __u32 tmp_block[EXT2_N_BLOCKS];
916
917                         for (i = 0; i < EXT2_N_BLOCKS; i++)
918                                 tmp_block[i] = ext2fs_swab32(inode->i_block[i]);
919                         ehp = tmp_block;
920 #else
921                         ehp = inode->i_block;
922 #endif
923                         if ((ext2fs_extent_header_verify(ehp,
924                                          sizeof(inode->i_block)) == 0) &&
925                             (fix_problem(ctx, PR_1_UNSET_EXTENT_FL, &pctx))) {
926                                 inode->i_flags |= EXT4_EXTENTS_FL;
927 #ifdef WORDS_BIGENDIAN
928                                 memcpy(inode->i_block, tmp_block,
929                                        sizeof(inode->i_block));
930 #endif
931                                 e2fsck_write_inode(ctx, ino, inode, "pass1");
932                         }
933                 }
934
935                 if (ino == EXT2_BAD_INO) {
936                         struct process_block_struct pb;
937
938                         if ((inode->i_mode || inode->i_uid || inode->i_gid ||
939                              inode->i_links_count || inode->i_file_acl) &&
940                             fix_problem(ctx, PR_1_INVALID_BAD_INODE, &pctx)) {
941                                 memset(inode, 0, sizeof(struct ext2_inode));
942                                 e2fsck_write_inode(ctx, ino, inode,
943                                                    "clear bad inode");
944                         }
945
946                         pctx.errcode = ext2fs_copy_bitmap(ctx->block_found_map,
947                                                           &pb.fs_meta_blocks);
948                         if (pctx.errcode) {
949                                 pctx.num = 4;
950                                 fix_problem(ctx, PR_1_ALLOCATE_BBITMAP_ERROR, &pctx);
951                                 ctx->flags |= E2F_FLAG_ABORT;
952                                 goto endit;
953                         }
954                         pb.ino = EXT2_BAD_INO;
955                         pb.num_blocks = pb.last_block = 0;
956                         pb.last_db_block = -1;
957                         pb.num_illegal_blocks = 0;
958                         pb.suppress = 0; pb.clear = 0; pb.is_dir = 0;
959                         pb.is_reg = 0; pb.fragmented = 0; pb.bbcheck = 0;
960                         pb.inode = inode;
961                         pb.pctx = &pctx;
962                         pb.ctx = ctx;
963                         pctx.errcode = ext2fs_block_iterate3(fs, ino, 0,
964                                      block_buf, process_bad_block, &pb);
965                         ext2fs_free_block_bitmap(pb.fs_meta_blocks);
966                         if (pctx.errcode) {
967                                 fix_problem(ctx, PR_1_BLOCK_ITERATE, &pctx);
968                                 ctx->flags |= E2F_FLAG_ABORT;
969                                 goto endit;
970                         }
971                         if (pb.bbcheck)
972                                 if (!fix_problem(ctx, PR_1_BBINODE_BAD_METABLOCK_PROMPT, &pctx)) {
973                                 ctx->flags |= E2F_FLAG_ABORT;
974                                 goto endit;
975                         }
976                         ext2fs_mark_inode_bitmap2(ctx->inode_used_map, ino);
977                         clear_problem_context(&pctx);
978                         continue;
979                 } else if (ino == EXT2_ROOT_INO) {
980                         /*
981                          * Make sure the root inode is a directory; if
982                          * not, offer to clear it.  It will be
983                          * regnerated in pass #3.
984                          */
985                         if (!LINUX_S_ISDIR(inode->i_mode)) {
986                                 if (fix_problem(ctx, PR_1_ROOT_NO_DIR, &pctx))
987                                         goto clear_inode;
988                         }
989                         /*
990                          * If dtime is set, offer to clear it.  mke2fs
991                          * version 0.2b created filesystems with the
992                          * dtime field set for the root and lost+found
993                          * directories.  We won't worry about
994                          * /lost+found, since that can be regenerated
995                          * easily.  But we will fix the root directory
996                          * as a special case.
997                          */
998                         if (inode->i_dtime && inode->i_links_count) {
999                                 if (fix_problem(ctx, PR_1_ROOT_DTIME, &pctx)) {
1000                                         inode->i_dtime = 0;
1001                                         e2fsck_write_inode(ctx, ino, inode,
1002                                                            "pass1");
1003                                 }
1004                         }
1005                 } else if (ino == EXT2_JOURNAL_INO) {
1006                         ext2fs_mark_inode_bitmap2(ctx->inode_used_map, ino);
1007                         if (fs->super->s_journal_inum == EXT2_JOURNAL_INO) {
1008                                 if (!LINUX_S_ISREG(inode->i_mode) &&
1009                                     fix_problem(ctx, PR_1_JOURNAL_BAD_MODE,
1010                                                 &pctx)) {
1011                                         inode->i_mode = LINUX_S_IFREG;
1012                                         e2fsck_write_inode(ctx, ino, inode,
1013                                                            "pass1");
1014                                 }
1015                                 check_blocks(ctx, &pctx, block_buf);
1016                                 continue;
1017                         }
1018                         if ((inode->i_links_count ||
1019                              inode->i_blocks || inode->i_block[0]) &&
1020                             fix_problem(ctx, PR_1_JOURNAL_INODE_NOT_CLEAR,
1021                                         &pctx)) {
1022                                 memset(inode, 0, inode_size);
1023                                 ext2fs_icount_store(ctx->inode_link_info,
1024                                                     ino, 0);
1025                                 e2fsck_write_inode_full(ctx, ino, inode,
1026                                                         inode_size, "pass1");
1027                         }
1028                 } else if ((ino == EXT4_USR_QUOTA_INO) ||
1029                            (ino == EXT4_GRP_QUOTA_INO)) {
1030                         ext2fs_mark_inode_bitmap2(ctx->inode_used_map, ino);
1031                         if ((fs->super->s_feature_ro_compat &
1032                                         EXT4_FEATURE_RO_COMPAT_QUOTA) &&
1033                             ((fs->super->s_usr_quota_inum == ino) ||
1034                              (fs->super->s_grp_quota_inum == ino))) {
1035                                 if (!LINUX_S_ISREG(inode->i_mode) &&
1036                                     fix_problem(ctx, PR_1_QUOTA_BAD_MODE,
1037                                                         &pctx)) {
1038                                         inode->i_mode = LINUX_S_IFREG;
1039                                         e2fsck_write_inode(ctx, ino, inode,
1040                                                         "pass1");
1041                                 }
1042                                 check_blocks(ctx, &pctx, block_buf);
1043                                 continue;
1044                         }
1045                         if ((inode->i_links_count ||
1046                              inode->i_blocks || inode->i_block[0]) &&
1047                             fix_problem(ctx, PR_1_QUOTA_INODE_NOT_CLEAR,
1048                                         &pctx)) {
1049                                 memset(inode, 0, inode_size);
1050                                 ext2fs_icount_store(ctx->inode_link_info,
1051                                                     ino, 0);
1052                                 e2fsck_write_inode_full(ctx, ino, inode,
1053                                                         inode_size, "pass1");
1054                         }
1055                 } else if (ino < EXT2_FIRST_INODE(fs->super)) {
1056                         problem_t problem = 0;
1057
1058                         ext2fs_mark_inode_bitmap2(ctx->inode_used_map, ino);
1059                         if (ino == EXT2_BOOT_LOADER_INO) {
1060                                 if (LINUX_S_ISDIR(inode->i_mode))
1061                                         problem = PR_1_RESERVED_BAD_MODE;
1062                         } else if (ino == EXT2_RESIZE_INO) {
1063                                 if (inode->i_mode &&
1064                                     !LINUX_S_ISREG(inode->i_mode))
1065                                         problem = PR_1_RESERVED_BAD_MODE;
1066                         } else {
1067                                 if (inode->i_mode != 0)
1068                                         problem = PR_1_RESERVED_BAD_MODE;
1069                         }
1070                         if (problem) {
1071                                 if (fix_problem(ctx, problem, &pctx)) {
1072                                         inode->i_mode = 0;
1073                                         e2fsck_write_inode(ctx, ino, inode,
1074                                                            "pass1");
1075                                 }
1076                         }
1077                         check_blocks(ctx, &pctx, block_buf);
1078                         continue;
1079                 }
1080
1081                 /*
1082                  * Check for inodes who might have been part of the
1083                  * orphaned list linked list.  They should have gotten
1084                  * dealt with by now, unless the list had somehow been
1085                  * corrupted.
1086                  *
1087                  * FIXME: In the future, inodes which are still in use
1088                  * (and which are therefore) pending truncation should
1089                  * be handled specially.  Right now we just clear the
1090                  * dtime field, and the normal e2fsck handling of
1091                  * inodes where i_size and the inode blocks are
1092                  * inconsistent is to fix i_size, instead of releasing
1093                  * the extra blocks.  This won't catch the inodes that
1094                  * was at the end of the orphan list, but it's better
1095                  * than nothing.  The right answer is that there
1096                  * shouldn't be any bugs in the orphan list handling.  :-)
1097                  */
1098                 if (inode->i_dtime && low_dtime_check &&
1099                     inode->i_dtime < ctx->fs->super->s_inodes_count) {
1100                         if (fix_problem(ctx, PR_1_LOW_DTIME, &pctx)) {
1101                                 inode->i_dtime = inode->i_links_count ?
1102                                         0 : ctx->now;
1103                                 e2fsck_write_inode(ctx, ino, inode,
1104                                                    "pass1");
1105                         }
1106                 }
1107
1108                 /*
1109                  * This code assumes that deleted inodes have
1110                  * i_links_count set to 0.
1111                  */
1112                 if (!inode->i_links_count) {
1113                         if (!inode->i_dtime && inode->i_mode) {
1114                                 if (fix_problem(ctx,
1115                                             PR_1_ZERO_DTIME, &pctx)) {
1116                                         inode->i_dtime = ctx->now;
1117                                         e2fsck_write_inode(ctx, ino, inode,
1118                                                            "pass1");
1119                                 }
1120                         }
1121                         continue;
1122                 }
1123                 /*
1124                  * n.b.  0.3c ext2fs code didn't clear i_links_count for
1125                  * deleted files.  Oops.
1126                  *
1127                  * Since all new ext2 implementations get this right,
1128                  * we now assume that the case of non-zero
1129                  * i_links_count and non-zero dtime means that we
1130                  * should keep the file, not delete it.
1131                  *
1132                  */
1133                 if (inode->i_dtime) {
1134                         if (fix_problem(ctx, PR_1_SET_DTIME, &pctx)) {
1135                                 inode->i_dtime = 0;
1136                                 e2fsck_write_inode(ctx, ino, inode, "pass1");
1137                         }
1138                 }
1139
1140                 ext2fs_mark_inode_bitmap2(ctx->inode_used_map, ino);
1141                 switch (fs->super->s_creator_os) {
1142                     case EXT2_OS_HURD:
1143                         frag = inode->osd2.hurd2.h_i_frag;
1144                         fsize = inode->osd2.hurd2.h_i_fsize;
1145                         break;
1146                     default:
1147                         frag = fsize = 0;
1148                 }
1149
1150                 if (inode->i_faddr || frag || fsize ||
1151                     (LINUX_S_ISDIR(inode->i_mode) && inode->i_dir_acl))
1152                         mark_inode_bad(ctx, ino);
1153                 if (!(fs->super->s_feature_incompat & 
1154                       EXT4_FEATURE_INCOMPAT_64BIT) &&
1155                     inode->osd2.linux2.l_i_file_acl_high != 0)
1156                         mark_inode_bad(ctx, ino);
1157                 if ((fs->super->s_creator_os == EXT2_OS_LINUX) &&
1158                     !(fs->super->s_feature_ro_compat &
1159                       EXT4_FEATURE_RO_COMPAT_HUGE_FILE) &&
1160                     (inode->osd2.linux2.l_i_blocks_hi != 0))
1161                         mark_inode_bad(ctx, ino);
1162                 if (inode->i_flags & EXT2_IMAGIC_FL) {
1163                         if (imagic_fs) {
1164                                 if (!ctx->inode_imagic_map)
1165                                         alloc_imagic_map(ctx);
1166                                 ext2fs_mark_inode_bitmap2(ctx->inode_imagic_map,
1167                                                          ino);
1168                         } else {
1169                                 if (fix_problem(ctx, PR_1_SET_IMAGIC, &pctx)) {
1170                                         inode->i_flags &= ~EXT2_IMAGIC_FL;
1171                                         e2fsck_write_inode(ctx, ino,
1172                                                            inode, "pass1");
1173                                 }
1174                         }
1175                 }
1176
1177                 check_inode_extra_space(ctx, &pctx);
1178                 check_is_really_dir(ctx, &pctx, block_buf);
1179
1180                 /*
1181                  * ext2fs_inode_has_valid_blocks2 does not actually look
1182                  * at i_block[] values, so not endian-sensitive here.
1183                  */
1184                 if (extent_fs && (inode->i_flags & EXT4_EXTENTS_FL) &&
1185                     LINUX_S_ISLNK(inode->i_mode) &&
1186                     !ext2fs_inode_has_valid_blocks2(fs, inode) &&
1187                     fix_problem(ctx, PR_1_FAST_SYMLINK_EXTENT_FL, &pctx)) {
1188                         inode->i_flags &= ~EXT4_EXTENTS_FL;
1189                         e2fsck_write_inode(ctx, ino, inode, "pass1");
1190                 }
1191
1192                 if (LINUX_S_ISDIR(inode->i_mode)) {
1193                         ext2fs_mark_inode_bitmap2(ctx->inode_dir_map, ino);
1194                         e2fsck_add_dir_info(ctx, ino, 0);
1195                         ctx->fs_directory_count++;
1196                 } else if (LINUX_S_ISREG (inode->i_mode)) {
1197                         ext2fs_mark_inode_bitmap2(ctx->inode_reg_map, ino);
1198                         ctx->fs_regular_count++;
1199                 } else if (LINUX_S_ISCHR (inode->i_mode) &&
1200                            e2fsck_pass1_check_device_inode(fs, inode)) {
1201                         check_immutable(ctx, &pctx);
1202                         check_size(ctx, &pctx);
1203                         ctx->fs_chardev_count++;
1204                 } else if (LINUX_S_ISBLK (inode->i_mode) &&
1205                            e2fsck_pass1_check_device_inode(fs, inode)) {
1206                         check_immutable(ctx, &pctx);
1207                         check_size(ctx, &pctx);
1208                         ctx->fs_blockdev_count++;
1209                 } else if (LINUX_S_ISLNK (inode->i_mode) &&
1210                            e2fsck_pass1_check_symlink(fs, ino, inode,
1211                                                       block_buf)) {
1212                         check_immutable(ctx, &pctx);
1213                         ctx->fs_symlinks_count++;
1214                         if (inode->i_flags & EXT4_INLINE_DATA_FL) {
1215                                 continue;
1216                         } else if (ext2fs_inode_data_blocks(fs, inode) == 0) {
1217                                 ctx->fs_fast_symlinks_count++;
1218                                 check_blocks(ctx, &pctx, block_buf);
1219                                 continue;
1220                         }
1221                 }
1222                 else if (LINUX_S_ISFIFO (inode->i_mode) &&
1223                          e2fsck_pass1_check_device_inode(fs, inode)) {
1224                         check_immutable(ctx, &pctx);
1225                         check_size(ctx, &pctx);
1226                         ctx->fs_fifo_count++;
1227                 } else if ((LINUX_S_ISSOCK (inode->i_mode)) &&
1228                            e2fsck_pass1_check_device_inode(fs, inode)) {
1229                         check_immutable(ctx, &pctx);
1230                         check_size(ctx, &pctx);
1231                         ctx->fs_sockets_count++;
1232                 } else
1233                         mark_inode_bad(ctx, ino);
1234                 if (!(inode->i_flags & EXT4_EXTENTS_FL) &&
1235                     !(inode->i_flags & EXT4_INLINE_DATA_FL)) {
1236                         if (inode->i_block[EXT2_IND_BLOCK])
1237                                 ctx->fs_ind_count++;
1238                         if (inode->i_block[EXT2_DIND_BLOCK])
1239                                 ctx->fs_dind_count++;
1240                         if (inode->i_block[EXT2_TIND_BLOCK])
1241                                 ctx->fs_tind_count++;
1242                 }
1243                 if (!(inode->i_flags & EXT4_EXTENTS_FL) &&
1244                     !(inode->i_flags & EXT4_INLINE_DATA_FL) &&
1245                     (inode->i_block[EXT2_IND_BLOCK] ||
1246                      inode->i_block[EXT2_DIND_BLOCK] ||
1247                      inode->i_block[EXT2_TIND_BLOCK] ||
1248                      ext2fs_file_acl_block(fs, inode))) {
1249                         inodes_to_process[process_inode_count].ino = ino;
1250                         inodes_to_process[process_inode_count].inode = *inode;
1251                         process_inode_count++;
1252                 } else
1253                         check_blocks(ctx, &pctx, block_buf);
1254
1255                 /*
1256                  * If the inode failed the checksum and the user didn't
1257                  * clear the inode, test the checksum again -- if it still
1258                  * fails, ask the user if the checksum should be corrected.
1259                  */
1260                 if (failed_csum) {
1261                         pctx.errcode = recheck_bad_inode_checksum(fs, ino, ctx,
1262                                                                   &pctx);
1263                         if (pctx.errcode) {
1264                                 ctx->flags |= E2F_FLAG_ABORT;
1265                                 return;
1266                         }
1267                 }
1268
1269                 if (ctx->flags & E2F_FLAG_SIGNAL_MASK)
1270                         goto endit;
1271
1272                 if (process_inode_count >= ctx->process_inode_size) {
1273                         process_inodes(ctx, block_buf);
1274
1275                         if (ctx->flags & E2F_FLAG_SIGNAL_MASK)
1276                                 goto endit;
1277                 }
1278         }
1279         process_inodes(ctx, block_buf);
1280         ext2fs_close_inode_scan(scan);
1281         scan = NULL;
1282
1283         /*
1284          * If any extended attribute blocks' reference counts need to
1285          * be adjusted, either up (ctx->refcount_extra), or down
1286          * (ctx->refcount), then fix them.
1287          */
1288         if (ctx->refcount) {
1289                 adjust_extattr_refcount(ctx, ctx->refcount, block_buf, -1);
1290                 ea_refcount_free(ctx->refcount);
1291                 ctx->refcount = 0;
1292         }
1293         if (ctx->refcount_extra) {
1294                 adjust_extattr_refcount(ctx, ctx->refcount_extra,
1295                                         block_buf, +1);
1296                 ea_refcount_free(ctx->refcount_extra);
1297                 ctx->refcount_extra = 0;
1298         }
1299
1300         if (ctx->invalid_bitmaps)
1301                 handle_fs_bad_blocks(ctx);
1302
1303         /* We don't need the block_ea_map any more */
1304         if (ctx->block_ea_map) {
1305                 ext2fs_free_block_bitmap(ctx->block_ea_map);
1306                 ctx->block_ea_map = 0;
1307         }
1308
1309         if (ctx->flags & E2F_FLAG_RESIZE_INODE) {
1310                 clear_problem_context(&pctx);
1311                 pctx.errcode = ext2fs_create_resize_inode(fs);
1312                 if (pctx.errcode) {
1313                         if (!fix_problem(ctx, PR_1_RESIZE_INODE_CREATE,
1314                                          &pctx)) {
1315                                 ctx->flags |= E2F_FLAG_ABORT;
1316                                 goto endit;
1317                         }
1318                         pctx.errcode = 0;
1319                 }
1320                 if (!pctx.errcode) {
1321                         e2fsck_read_inode(ctx, EXT2_RESIZE_INO, inode,
1322                                           "recreate inode");
1323                         inode->i_mtime = ctx->now;
1324                         e2fsck_write_inode(ctx, EXT2_RESIZE_INO, inode,
1325                                            "recreate inode");
1326                 }
1327                 ctx->flags &= ~E2F_FLAG_RESIZE_INODE;
1328         }
1329
1330         if (ctx->flags & E2F_FLAG_RESTART) {
1331                 /*
1332                  * Only the master copy of the superblock and block
1333                  * group descriptors are going to be written during a
1334                  * restart, so set the superblock to be used to be the
1335                  * master superblock.
1336                  */
1337                 ctx->use_superblock = 0;
1338                 unwind_pass1(fs);
1339                 goto endit;
1340         }
1341
1342         if (ctx->block_dup_map) {
1343                 if (ctx->options & E2F_OPT_PREEN) {
1344                         clear_problem_context(&pctx);
1345                         fix_problem(ctx, PR_1_DUP_BLOCKS_PREENSTOP, &pctx);
1346                 }
1347                 e2fsck_pass1_dupblocks(ctx, block_buf);
1348         }
1349         ext2fs_free_mem(&inodes_to_process);
1350 endit:
1351         e2fsck_use_inode_shortcuts(ctx, 0);
1352
1353         if (scan)
1354                 ext2fs_close_inode_scan(scan);
1355         if (block_buf)
1356                 ext2fs_free_mem(&block_buf);
1357         if (inode)
1358                 ext2fs_free_mem(&inode);
1359
1360         /*
1361          * The l+f inode may have been cleared, so zap it now and
1362          * later passes will recalculate it if necessary
1363          */
1364         ctx->lost_and_found = 0;
1365
1366         if ((ctx->flags & E2F_FLAG_SIGNAL_MASK) == 0)
1367                 print_resource_track(ctx, _("Pass 1"), &rtrack, ctx->fs->io);
1368 }
1369
1370 /*
1371  * When the inode_scan routines call this callback at the end of the
1372  * glock group, call process_inodes.
1373  */
1374 static errcode_t scan_callback(ext2_filsys fs,
1375                                ext2_inode_scan scan EXT2FS_ATTR((unused)),
1376                                dgrp_t group, void * priv_data)
1377 {
1378         struct scan_callback_struct *scan_struct;
1379         e2fsck_t ctx;
1380
1381         scan_struct = (struct scan_callback_struct *) priv_data;
1382         ctx = scan_struct->ctx;
1383
1384         process_inodes((e2fsck_t) fs->priv_data, scan_struct->block_buf);
1385
1386         if (ctx->progress)
1387                 if ((ctx->progress)(ctx, 1, group+1,
1388                                     ctx->fs->group_desc_count))
1389                         return EXT2_ET_CANCEL_REQUESTED;
1390
1391         return 0;
1392 }
1393
1394 /*
1395  * Process the inodes in the "inodes to process" list.
1396  */
1397 static void process_inodes(e2fsck_t ctx, char *block_buf)
1398 {
1399         int                     i;
1400         struct ext2_inode       *old_stashed_inode;
1401         ext2_ino_t              old_stashed_ino;
1402         const char              *old_operation;
1403         char                    buf[80];
1404         struct problem_context  pctx;
1405
1406 #if 0
1407         printf("begin process_inodes: ");
1408 #endif
1409         if (process_inode_count == 0)
1410                 return;
1411         old_operation = ehandler_operation(0);
1412         old_stashed_inode = ctx->stashed_inode;
1413         old_stashed_ino = ctx->stashed_ino;
1414         qsort(inodes_to_process, process_inode_count,
1415                       sizeof(struct process_inode_block), process_inode_cmp);
1416         clear_problem_context(&pctx);
1417         for (i=0; i < process_inode_count; i++) {
1418                 pctx.inode = ctx->stashed_inode = &inodes_to_process[i].inode;
1419                 pctx.ino = ctx->stashed_ino = inodes_to_process[i].ino;
1420
1421 #if 0
1422                 printf("%u ", pctx.ino);
1423 #endif
1424                 sprintf(buf, _("reading indirect blocks of inode %u"),
1425                         pctx.ino);
1426                 ehandler_operation(buf);
1427                 check_blocks(ctx, &pctx, block_buf);
1428                 if (ctx->flags & E2F_FLAG_SIGNAL_MASK)
1429                         break;
1430         }
1431         ctx->stashed_inode = old_stashed_inode;
1432         ctx->stashed_ino = old_stashed_ino;
1433         process_inode_count = 0;
1434 #if 0
1435         printf("end process inodes\n");
1436 #endif
1437         ehandler_operation(old_operation);
1438 }
1439
1440 static EXT2_QSORT_TYPE process_inode_cmp(const void *a, const void *b)
1441 {
1442         const struct process_inode_block *ib_a =
1443                 (const struct process_inode_block *) a;
1444         const struct process_inode_block *ib_b =
1445                 (const struct process_inode_block *) b;
1446         int     ret;
1447
1448         ret = (ib_a->inode.i_block[EXT2_IND_BLOCK] -
1449                ib_b->inode.i_block[EXT2_IND_BLOCK]);
1450         if (ret == 0)
1451                 /*
1452                  * We only call process_inodes() for non-extent
1453                  * inodes, so it's OK to pass NULL to
1454                  * ext2fs_file_acl_block() here.
1455                  */
1456                 ret = ext2fs_file_acl_block(0, &(ib_a->inode)) -
1457                         ext2fs_file_acl_block(0, &(ib_b->inode));
1458         if (ret == 0)
1459                 ret = ib_a->ino - ib_b->ino;
1460         return ret;
1461 }
1462
1463 /*
1464  * Mark an inode as being bad in some what
1465  */
1466 static void mark_inode_bad(e2fsck_t ctx, ino_t ino)
1467 {
1468         struct          problem_context pctx;
1469
1470         if (!ctx->inode_bad_map) {
1471                 clear_problem_context(&pctx);
1472
1473                 pctx.errcode = e2fsck_allocate_inode_bitmap(ctx->fs,
1474                                 _("bad inode map"), EXT2FS_BMAP64_RBTREE,
1475                                 "inode_bad_map", &ctx->inode_bad_map);
1476                 if (pctx.errcode) {
1477                         pctx.num = 3;
1478                         fix_problem(ctx, PR_1_ALLOCATE_IBITMAP_ERROR, &pctx);
1479                         /* Should never get here */
1480                         ctx->flags |= E2F_FLAG_ABORT;
1481                         return;
1482                 }
1483         }
1484         ext2fs_mark_inode_bitmap2(ctx->inode_bad_map, ino);
1485 }
1486
1487
1488 /*
1489  * This procedure will allocate the inode "bb" (badblock) map table
1490  */
1491 static void alloc_bb_map(e2fsck_t ctx)
1492 {
1493         struct          problem_context pctx;
1494
1495         clear_problem_context(&pctx);
1496         pctx.errcode = e2fsck_allocate_inode_bitmap(ctx->fs,
1497                         _("inode in bad block map"), EXT2FS_BMAP64_RBTREE,
1498                         "inode_bb_map", &ctx->inode_bb_map);
1499         if (pctx.errcode) {
1500                 pctx.num = 4;
1501                 fix_problem(ctx, PR_1_ALLOCATE_IBITMAP_ERROR, &pctx);
1502                 /* Should never get here */
1503                 ctx->flags |= E2F_FLAG_ABORT;
1504                 return;
1505         }
1506 }
1507
1508 /*
1509  * This procedure will allocate the inode imagic table
1510  */
1511 static void alloc_imagic_map(e2fsck_t ctx)
1512 {
1513         struct          problem_context pctx;
1514
1515         clear_problem_context(&pctx);
1516         pctx.errcode = e2fsck_allocate_inode_bitmap(ctx->fs,
1517                         _("imagic inode map"), EXT2FS_BMAP64_RBTREE,
1518                         "inode_imagic_map", &ctx->inode_imagic_map);
1519         if (pctx.errcode) {
1520                 pctx.num = 5;
1521                 fix_problem(ctx, PR_1_ALLOCATE_IBITMAP_ERROR, &pctx);
1522                 /* Should never get here */
1523                 ctx->flags |= E2F_FLAG_ABORT;
1524                 return;
1525         }
1526 }
1527
1528 /*
1529  * Marks a block as in use, setting the dup_map if it's been set
1530  * already.  Called by process_block and process_bad_block.
1531  *
1532  * WARNING: Assumes checks have already been done to make sure block
1533  * is valid.  This is true in both process_block and process_bad_block.
1534  */
1535 static _INLINE_ void mark_block_used(e2fsck_t ctx, blk64_t block)
1536 {
1537         struct          problem_context pctx;
1538
1539         clear_problem_context(&pctx);
1540
1541         if (ext2fs_fast_test_block_bitmap2(ctx->block_found_map, block)) {
1542                 if (!ctx->block_dup_map) {
1543                         pctx.errcode = e2fsck_allocate_block_bitmap(ctx->fs,
1544                                         _("multiply claimed block map"),
1545                                         EXT2FS_BMAP64_RBTREE, "block_dup_map",
1546                                         &ctx->block_dup_map);
1547                         if (pctx.errcode) {
1548                                 pctx.num = 3;
1549                                 fix_problem(ctx, PR_1_ALLOCATE_BBITMAP_ERROR,
1550                                             &pctx);
1551                                 /* Should never get here */
1552                                 ctx->flags |= E2F_FLAG_ABORT;
1553                                 return;
1554                         }
1555                 }
1556                 ext2fs_fast_mark_block_bitmap2(ctx->block_dup_map, block);
1557         } else {
1558                 ext2fs_fast_mark_block_bitmap2(ctx->block_found_map, block);
1559         }
1560 }
1561
1562 static _INLINE_ void mark_blocks_used(e2fsck_t ctx, blk64_t block,
1563                                       unsigned int num)
1564 {
1565         if (ext2fs_test_block_bitmap_range2(ctx->block_found_map, block, num))
1566                 ext2fs_mark_block_bitmap_range2(ctx->block_found_map, block, num);
1567         else
1568                 while (num--)
1569                         mark_block_used(ctx, block++);
1570 }
1571
1572 /*
1573  * Adjust the extended attribute block's reference counts at the end
1574  * of pass 1, either by subtracting out references for EA blocks that
1575  * are still referenced in ctx->refcount, or by adding references for
1576  * EA blocks that had extra references as accounted for in
1577  * ctx->refcount_extra.
1578  */
1579 static void adjust_extattr_refcount(e2fsck_t ctx, ext2_refcount_t refcount,
1580                                     char *block_buf, int adjust_sign)
1581 {
1582         struct ext2_ext_attr_header     *header;
1583         struct problem_context          pctx;
1584         ext2_filsys                     fs = ctx->fs;
1585         blk64_t                         blk;
1586         __u32                           should_be;
1587         int                             count;
1588
1589         clear_problem_context(&pctx);
1590
1591         ea_refcount_intr_begin(refcount);
1592         while (1) {
1593                 if ((blk = ea_refcount_intr_next(refcount, &count)) == 0)
1594                         break;
1595                 pctx.blk = blk;
1596                 pctx.errcode = ext2fs_read_ext_attr3(fs, blk, block_buf,
1597                                                      pctx.ino);
1598                 if (pctx.errcode) {
1599                         fix_problem(ctx, PR_1_EXTATTR_READ_ABORT, &pctx);
1600                         return;
1601                 }
1602                 header = (struct ext2_ext_attr_header *) block_buf;
1603                 pctx.blkcount = header->h_refcount;
1604                 should_be = header->h_refcount + adjust_sign * count;
1605                 pctx.num = should_be;
1606                 if (fix_problem(ctx, PR_1_EXTATTR_REFCOUNT, &pctx)) {
1607                         header->h_refcount = should_be;
1608                         pctx.errcode = ext2fs_write_ext_attr3(fs, blk,
1609                                                              block_buf,
1610                                                              pctx.ino);
1611                         if (pctx.errcode) {
1612                                 fix_problem(ctx, PR_1_EXTATTR_WRITE_ABORT,
1613                                             &pctx);
1614                                 continue;
1615                         }
1616                 }
1617         }
1618 }
1619
1620 /*
1621  * Handle processing the extended attribute blocks
1622  */
1623 static int check_ext_attr(e2fsck_t ctx, struct problem_context *pctx,
1624                            char *block_buf)
1625 {
1626         ext2_filsys fs = ctx->fs;
1627         ext2_ino_t      ino = pctx->ino;
1628         struct ext2_inode *inode = pctx->inode;
1629         blk64_t         blk;
1630         char *          end;
1631         struct ext2_ext_attr_header *header;
1632         struct ext2_ext_attr_entry *entry;
1633         int             count;
1634         region_t        region = 0;
1635         int             failed_csum = 0;
1636
1637         blk = ext2fs_file_acl_block(fs, inode);
1638         if (blk == 0)
1639                 return 0;
1640
1641         /*
1642          * If the Extended attribute flag isn't set, then a non-zero
1643          * file acl means that the inode is corrupted.
1644          *
1645          * Or if the extended attribute block is an invalid block,
1646          * then the inode is also corrupted.
1647          */
1648         if (!(fs->super->s_feature_compat & EXT2_FEATURE_COMPAT_EXT_ATTR) ||
1649             (blk < fs->super->s_first_data_block) ||
1650             (blk >= ext2fs_blocks_count(fs->super))) {
1651                 mark_inode_bad(ctx, ino);
1652                 return 0;
1653         }
1654
1655         /* If ea bitmap hasn't been allocated, create it */
1656         if (!ctx->block_ea_map) {
1657                 pctx->errcode = e2fsck_allocate_block_bitmap(fs,
1658                                         _("ext attr block map"),
1659                                         EXT2FS_BMAP64_RBTREE, "block_ea_map",
1660                                         &ctx->block_ea_map);
1661                 if (pctx->errcode) {
1662                         pctx->num = 2;
1663                         fix_problem(ctx, PR_1_ALLOCATE_BBITMAP_ERROR, pctx);
1664                         ctx->flags |= E2F_FLAG_ABORT;
1665                         return 0;
1666                 }
1667         }
1668
1669         /* Create the EA refcount structure if necessary */
1670         if (!ctx->refcount) {
1671                 pctx->errcode = ea_refcount_create(0, &ctx->refcount);
1672                 if (pctx->errcode) {
1673                         pctx->num = 1;
1674                         fix_problem(ctx, PR_1_ALLOCATE_REFCOUNT, pctx);
1675                         ctx->flags |= E2F_FLAG_ABORT;
1676                         return 0;
1677                 }
1678         }
1679
1680 #if 0
1681         /* Debugging text */
1682         printf("Inode %u has EA block %u\n", ino, blk);
1683 #endif
1684
1685         /* Have we seen this EA block before? */
1686         if (ext2fs_fast_test_block_bitmap2(ctx->block_ea_map, blk)) {
1687                 if (ea_refcount_decrement(ctx->refcount, blk, 0) == 0)
1688                         return 1;
1689                 /* Ooops, this EA was referenced more than it stated */
1690                 if (!ctx->refcount_extra) {
1691                         pctx->errcode = ea_refcount_create(0,
1692                                            &ctx->refcount_extra);
1693                         if (pctx->errcode) {
1694                                 pctx->num = 2;
1695                                 fix_problem(ctx, PR_1_ALLOCATE_REFCOUNT, pctx);
1696                                 ctx->flags |= E2F_FLAG_ABORT;
1697                                 return 0;
1698                         }
1699                 }
1700                 ea_refcount_increment(ctx->refcount_extra, blk, 0);
1701                 return 1;
1702         }
1703
1704         /*
1705          * OK, we haven't seen this EA block yet.  So we need to
1706          * validate it
1707          */
1708         pctx->blk = blk;
1709         pctx->errcode = ext2fs_read_ext_attr3(fs, blk, block_buf, pctx->ino);
1710         if (pctx->errcode == EXT2_ET_EXT_ATTR_CSUM_INVALID) {
1711                 if (fix_problem(ctx, PR_1_EA_BLOCK_CSUM_INVALID, pctx))
1712                         goto clear_extattr;
1713                 failed_csum = 1;
1714         }
1715         if (pctx->errcode && fix_problem(ctx, PR_1_READ_EA_BLOCK, pctx))
1716                 goto clear_extattr;
1717         header = (struct ext2_ext_attr_header *) block_buf;
1718         pctx->blk = ext2fs_file_acl_block(fs, inode);
1719         if (((ctx->ext_attr_ver == 1) &&
1720              (header->h_magic != EXT2_EXT_ATTR_MAGIC_v1)) ||
1721             ((ctx->ext_attr_ver == 2) &&
1722              (header->h_magic != EXT2_EXT_ATTR_MAGIC))) {
1723                 if (fix_problem(ctx, PR_1_BAD_EA_BLOCK, pctx))
1724                         goto clear_extattr;
1725         }
1726
1727         if (header->h_blocks != 1) {
1728                 if (fix_problem(ctx, PR_1_EA_MULTI_BLOCK, pctx))
1729                         goto clear_extattr;
1730         }
1731
1732         region = region_create(0, fs->blocksize);
1733         if (!region) {
1734                 fix_problem(ctx, PR_1_EA_ALLOC_REGION_ABORT, pctx);
1735                 ctx->flags |= E2F_FLAG_ABORT;
1736                 return 0;
1737         }
1738         if (region_allocate(region, 0, sizeof(struct ext2_ext_attr_header))) {
1739                 if (fix_problem(ctx, PR_1_EA_ALLOC_COLLISION, pctx))
1740                         goto clear_extattr;
1741         }
1742
1743         entry = (struct ext2_ext_attr_entry *)(header+1);
1744         end = block_buf + fs->blocksize;
1745         while ((char *)entry < end && *(__u32 *)entry) {
1746                 __u32 hash;
1747
1748                 if (region_allocate(region, (char *)entry - (char *)header,
1749                                    EXT2_EXT_ATTR_LEN(entry->e_name_len))) {
1750                         if (fix_problem(ctx, PR_1_EA_ALLOC_COLLISION, pctx))
1751                                 goto clear_extattr;
1752                         break;
1753                 }
1754                 if ((ctx->ext_attr_ver == 1 &&
1755                      (entry->e_name_len == 0 || entry->e_name_index != 0)) ||
1756                     (ctx->ext_attr_ver == 2 &&
1757                      entry->e_name_index == 0)) {
1758                         if (fix_problem(ctx, PR_1_EA_BAD_NAME, pctx))
1759                                 goto clear_extattr;
1760                         break;
1761                 }
1762                 if (entry->e_value_block != 0) {
1763                         if (fix_problem(ctx, PR_1_EA_BAD_VALUE, pctx))
1764                                 goto clear_extattr;
1765                 }
1766                 if (entry->e_value_offs + entry->e_value_size > fs->blocksize) {
1767                         if (fix_problem(ctx, PR_1_EA_BAD_VALUE, pctx))
1768                                 goto clear_extattr;
1769                         break;
1770                 }
1771                 if (entry->e_value_size &&
1772                     region_allocate(region, entry->e_value_offs,
1773                                     EXT2_EXT_ATTR_SIZE(entry->e_value_size))) {
1774                         if (fix_problem(ctx, PR_1_EA_ALLOC_COLLISION, pctx))
1775                                 goto clear_extattr;
1776                 }
1777
1778                 hash = ext2fs_ext_attr_hash_entry(entry, block_buf +
1779                                                          entry->e_value_offs);
1780
1781                 if (entry->e_hash != hash) {
1782                         pctx->num = entry->e_hash;
1783                         if (fix_problem(ctx, PR_1_ATTR_HASH, pctx))
1784                                 goto clear_extattr;
1785                         entry->e_hash = hash;
1786                 }
1787
1788                 entry = EXT2_EXT_ATTR_NEXT(entry);
1789         }
1790         if (region_allocate(region, (char *)entry - (char *)header, 4)) {
1791                 if (fix_problem(ctx, PR_1_EA_ALLOC_COLLISION, pctx))
1792                         goto clear_extattr;
1793         }
1794         region_free(region);
1795
1796         /*
1797          * We only get here if there was no other errors that were fixed.
1798          * If there was a checksum fail, ask to correct it.
1799          */
1800         if (failed_csum &&
1801             fix_problem(ctx, PR_1_EA_BLOCK_ONLY_CSUM_INVALID, pctx)) {
1802                 pctx->errcode = ext2fs_write_ext_attr3(fs, blk, block_buf,
1803                                                        pctx->ino);
1804                 if (pctx->errcode)
1805                         return 0;
1806         }
1807
1808         count = header->h_refcount - 1;
1809         if (count)
1810                 ea_refcount_store(ctx->refcount, blk, count);
1811         mark_block_used(ctx, blk);
1812         ext2fs_fast_mark_block_bitmap2(ctx->block_ea_map, blk);
1813         return 1;
1814
1815 clear_extattr:
1816         if (region)
1817                 region_free(region);
1818         ext2fs_file_acl_block_set(fs, inode, 0);
1819         e2fsck_write_inode(ctx, ino, inode, "check_ext_attr");
1820         return 0;
1821 }
1822
1823 /* Returns 1 if bad htree, 0 if OK */
1824 static int handle_htree(e2fsck_t ctx, struct problem_context *pctx,
1825                         ext2_ino_t ino, struct ext2_inode *inode,
1826                         char *block_buf)
1827 {
1828         struct ext2_dx_root_info        *root;
1829         ext2_filsys                     fs = ctx->fs;
1830         errcode_t                       retval;
1831         blk64_t                         blk;
1832
1833         if ((!LINUX_S_ISDIR(inode->i_mode) &&
1834              fix_problem(ctx, PR_1_HTREE_NODIR, pctx)) ||
1835             (!(fs->super->s_feature_compat & EXT2_FEATURE_COMPAT_DIR_INDEX) &&
1836              fix_problem(ctx, PR_1_HTREE_SET, pctx)))
1837                 return 1;
1838
1839         pctx->errcode = ext2fs_bmap2(fs, ino, inode, 0, 0, 0, 0, &blk);
1840
1841         if ((pctx->errcode) ||
1842             (blk == 0) ||
1843             (blk < fs->super->s_first_data_block) ||
1844             (blk >= ext2fs_blocks_count(fs->super))) {
1845                 if (fix_problem(ctx, PR_1_HTREE_BADROOT, pctx))
1846                         return 1;
1847                 else
1848                         return 0;
1849         }
1850
1851         retval = io_channel_read_blk64(fs->io, blk, 1, block_buf);
1852         if (retval && fix_problem(ctx, PR_1_HTREE_BADROOT, pctx))
1853                 return 1;
1854
1855         /* XXX should check that beginning matches a directory */
1856         root = (struct ext2_dx_root_info *) (block_buf + 24);
1857
1858         if ((root->reserved_zero || root->info_length < 8) &&
1859             fix_problem(ctx, PR_1_HTREE_BADROOT, pctx))
1860                 return 1;
1861
1862         pctx->num = root->hash_version;
1863         if ((root->hash_version != EXT2_HASH_LEGACY) &&
1864             (root->hash_version != EXT2_HASH_HALF_MD4) &&
1865             (root->hash_version != EXT2_HASH_TEA) &&
1866             fix_problem(ctx, PR_1_HTREE_HASHV, pctx))
1867                 return 1;
1868
1869         if ((root->unused_flags & EXT2_HASH_FLAG_INCOMPAT) &&
1870             fix_problem(ctx, PR_1_HTREE_INCOMPAT, pctx))
1871                 return 1;
1872
1873         pctx->num = root->indirect_levels;
1874         if ((root->indirect_levels > 1) &&
1875             fix_problem(ctx, PR_1_HTREE_DEPTH, pctx))
1876                 return 1;
1877
1878         return 0;
1879 }
1880
1881 void e2fsck_clear_inode(e2fsck_t ctx, ext2_ino_t ino,
1882                         struct ext2_inode *inode, int restart_flag,
1883                         const char *source)
1884 {
1885         inode->i_flags = 0;
1886         inode->i_links_count = 0;
1887         ext2fs_icount_store(ctx->inode_link_info, ino, 0);
1888         inode->i_dtime = ctx->now;
1889
1890         ext2fs_unmark_inode_bitmap2(ctx->inode_dir_map, ino);
1891         ext2fs_unmark_inode_bitmap2(ctx->inode_used_map, ino);
1892         if (ctx->inode_reg_map)
1893                 ext2fs_unmark_inode_bitmap2(ctx->inode_reg_map, ino);
1894         if (ctx->inode_bad_map)
1895                 ext2fs_unmark_inode_bitmap2(ctx->inode_bad_map, ino);
1896
1897         /*
1898          * If the inode was partially accounted for before processing
1899          * was aborted, we need to restart the pass 1 scan.
1900          */
1901         ctx->flags |= restart_flag;
1902
1903         if (ino == EXT2_BAD_INO)
1904                 memset(inode, 0, sizeof(struct ext2_inode));
1905
1906         e2fsck_write_inode(ctx, ino, inode, source);
1907 }
1908
1909 static void scan_extent_node(e2fsck_t ctx, struct problem_context *pctx,
1910                              struct process_block_struct *pb,
1911                              blk64_t start_block, blk64_t end_block,
1912                              blk64_t eof_block,
1913                              ext2_extent_handle_t ehandle,
1914                              int try_repairs)
1915 {
1916         struct ext2fs_extent    extent;
1917         blk64_t                 blk, last_lblk;
1918         e2_blkcnt_t             blockcnt;
1919         unsigned int            i;
1920         int                     is_dir, is_leaf;
1921         problem_t               problem;
1922         struct ext2_extent_info info;
1923         int                     failed_csum;
1924
1925         pctx->errcode = ext2fs_extent_get_info(ehandle, &info);
1926         if (pctx->errcode)
1927                 return;
1928
1929         pctx->errcode = ext2fs_extent_get(ehandle, EXT2_EXTENT_FIRST_SIB,
1930                                           &extent);
1931         while ((pctx->errcode == 0 ||
1932                 pctx->errcode == EXT2_ET_EXTENT_CSUM_INVALID) &&
1933                info.num_entries-- > 0) {
1934                 failed_csum = 0;
1935                 is_leaf = extent.e_flags & EXT2_EXTENT_FLAGS_LEAF;
1936                 is_dir = LINUX_S_ISDIR(pctx->inode->i_mode);
1937                 last_lblk = extent.e_lblk + extent.e_len - 1;
1938
1939                 problem = 0;
1940                 /* Ask to clear a corrupt extent block */
1941                 if (try_repairs &&
1942                     pctx->errcode == EXT2_ET_EXTENT_CSUM_INVALID) {
1943                         pctx->blk = extent.e_pblk;
1944                         pctx->blk2 = extent.e_lblk;
1945                         pctx->num = extent.e_len;
1946                         problem = PR_1_EXTENT_CSUM_INVALID;
1947                         if (fix_problem(ctx, problem, pctx))
1948                                 goto fix_problem_now;
1949                         failed_csum = 1;
1950                 }
1951
1952                 if (extent.e_pblk == 0 ||
1953                     extent.e_pblk < ctx->fs->super->s_first_data_block ||
1954                     extent.e_pblk >= ext2fs_blocks_count(ctx->fs->super))
1955                         problem = PR_1_EXTENT_BAD_START_BLK;
1956                 else if (extent.e_lblk < start_block)
1957                         problem = PR_1_OUT_OF_ORDER_EXTENTS;
1958                 else if ((end_block && last_lblk > end_block) &&
1959                          (!(extent.e_flags & EXT2_EXTENT_FLAGS_UNINIT &&
1960                                 last_lblk > eof_block)))
1961                         problem = PR_1_EXTENT_END_OUT_OF_BOUNDS;
1962                 else if (is_leaf && extent.e_len == 0)
1963                         problem = PR_1_EXTENT_LENGTH_ZERO;
1964                 else if (is_leaf &&
1965                          (extent.e_pblk + extent.e_len) >
1966                          ext2fs_blocks_count(ctx->fs->super))
1967                         problem = PR_1_EXTENT_ENDS_BEYOND;
1968                 else if (is_leaf && is_dir &&
1969                          ((extent.e_lblk + extent.e_len) >
1970                           (1 << (21 - ctx->fs->super->s_log_block_size))))
1971                         problem = PR_1_TOOBIG_DIR;
1972
1973                 /* Corrupt but passes checks?  Ask to fix checksum. */
1974                 if (try_repairs && failed_csum) {
1975                         pctx->blk = extent.e_pblk;
1976                         pctx->blk2 = extent.e_lblk;
1977                         pctx->num = extent.e_len;
1978                         problem = 0;
1979                         if (fix_problem(ctx, PR_1_EXTENT_ONLY_CSUM_INVALID,
1980                                         pctx)) {
1981                                 pb->inode_modified = 1;
1982                                 ext2fs_extent_replace(ehandle, 0, &extent);
1983                         }
1984                 }
1985
1986                 /*
1987                  * Uninitialized blocks in a directory?  Clear the flag and
1988                  * we'll interpret the blocks later.
1989                  */
1990                 if (try_repairs && is_dir && problem == 0 &&
1991                     (extent.e_flags & EXT2_EXTENT_FLAGS_UNINIT) &&
1992                     fix_problem(ctx, PR_1_UNINIT_DBLOCK, pctx)) {
1993                         extent.e_flags &= ~EXT2_EXTENT_FLAGS_UNINIT;
1994                         pb->inode_modified = 1;
1995                         pctx->errcode = ext2fs_extent_replace(ehandle, 0,
1996                                                               &extent);
1997                         if (pctx->errcode)
1998                                 return;
1999                         failed_csum = 0;
2000                 }
2001
2002                 if (try_repairs && problem) {
2003 report_problem:
2004                         pctx->blk = extent.e_pblk;
2005                         pctx->blk2 = extent.e_lblk;
2006                         pctx->num = extent.e_len;
2007                         pctx->blkcount = extent.e_lblk + extent.e_len;
2008                         if (fix_problem(ctx, problem, pctx)) {
2009 fix_problem_now:
2010                                 if (ctx->invalid_bitmaps) {
2011                                         /*
2012                                          * If fsck knows the bitmaps are bad,
2013                                          * skip to the next extent and
2014                                          * try to clear this extent again
2015                                          * after fixing the bitmaps, by
2016                                          * restarting fsck.
2017                                          */
2018                                         pctx->errcode = ext2fs_extent_get(
2019                                                           ehandle,
2020                                                           EXT2_EXTENT_NEXT_SIB,
2021                                                           &extent);
2022                                         ctx->flags |= E2F_FLAG_RESTART_LATER;
2023                                         if (pctx->errcode ==
2024                                                     EXT2_ET_NO_CURRENT_NODE) {
2025                                                 pctx->errcode = 0;
2026                                                 break;
2027                                         }
2028                                         continue;
2029                                 }
2030                                 e2fsck_read_bitmaps(ctx);
2031                                 pb->inode_modified = 1;
2032                                 pctx->errcode =
2033                                         ext2fs_extent_delete(ehandle, 0);
2034                                 if (pctx->errcode) {
2035                                         pctx->str = "ext2fs_extent_delete";
2036                                         return;
2037                                 }
2038                                 pctx->errcode = ext2fs_extent_fix_parents(ehandle);
2039                                 if (pctx->errcode &&
2040                                     pctx->errcode != EXT2_ET_NO_CURRENT_NODE) {
2041                                         pctx->str = "ext2fs_extent_fix_parents";
2042                                         return;
2043                                 }
2044                                 pctx->errcode = ext2fs_extent_get(ehandle,
2045                                                                   EXT2_EXTENT_CURRENT,
2046                                                                   &extent);
2047                                 if (pctx->errcode == EXT2_ET_NO_CURRENT_NODE) {
2048                                         pctx->errcode = 0;
2049                                         break;
2050                                 }
2051                                 continue;
2052                         }
2053                         goto next;
2054                 }
2055
2056                 if (!is_leaf) {
2057                         blk64_t lblk = extent.e_lblk;
2058                         int next_try_repairs = 1;
2059
2060                         blk = extent.e_pblk;
2061
2062                         /*
2063                          * If this lower extent block collides with critical
2064                          * metadata, don't try to repair the damage.  Pass 1b
2065                          * will reallocate the block; then we can try again.
2066                          */
2067                         if (pb->ino != EXT2_RESIZE_INO &&
2068                             ext2fs_test_block_bitmap2(ctx->block_metadata_map,
2069                                                       extent.e_pblk)) {
2070                                 next_try_repairs = 0;
2071                                 pctx->blk = blk;
2072                                 fix_problem(ctx,
2073                                             PR_1_CRITICAL_METADATA_COLLISION,
2074                                             pctx);
2075                                 ctx->flags |= E2F_FLAG_RESTART_LATER;
2076                         }
2077                         pctx->errcode = ext2fs_extent_get(ehandle,
2078                                                   EXT2_EXTENT_DOWN, &extent);
2079                         if (pctx->errcode) {
2080                                 pctx->str = "EXT2_EXTENT_DOWN";
2081                                 problem = PR_1_EXTENT_HEADER_INVALID;
2082                                 if (!next_try_repairs)
2083                                         return;
2084                                 if (pctx->errcode ==
2085                                         EXT2_ET_EXTENT_HEADER_BAD ||
2086                                     pctx->errcode ==
2087                                         EXT2_ET_EXTENT_CSUM_INVALID)
2088                                         goto report_problem;
2089                                 return;
2090                         }
2091                         /* The next extent should match this index's logical start */
2092                         if (extent.e_lblk != lblk) {
2093                                 struct ext2_extent_info e_info;
2094
2095                                 ext2fs_extent_get_info(ehandle, &e_info);
2096                                 pctx->blk = lblk;
2097                                 pctx->blk2 = extent.e_lblk;
2098                                 pctx->num = e_info.curr_level - 1;
2099                                 problem = PR_1_EXTENT_INDEX_START_INVALID;
2100                                 if (fix_problem(ctx, problem, pctx)) {
2101                                         pb->inode_modified = 1;
2102                                         pctx->errcode =
2103                                                 ext2fs_extent_fix_parents(ehandle);
2104                                         if (pctx->errcode) {
2105                                                 pctx->str = "ext2fs_extent_fix_parents";
2106                                                 return;
2107                                         }
2108                                 }
2109                         }
2110                         scan_extent_node(ctx, pctx, pb, extent.e_lblk,
2111                                          last_lblk, eof_block, ehandle,
2112                                          next_try_repairs);
2113                         if (pctx->errcode)
2114                                 return;
2115                         pctx->errcode = ext2fs_extent_get(ehandle,
2116                                                   EXT2_EXTENT_UP, &extent);
2117                         if (pctx->errcode) {
2118                                 pctx->str = "EXT2_EXTENT_UP";
2119                                 return;
2120                         }
2121                         mark_block_used(ctx, blk);
2122                         pb->num_blocks++;
2123                         goto next;
2124                 }
2125
2126                 if ((pb->previous_block != 0) &&
2127                     (pb->previous_block+1 != extent.e_pblk)) {
2128                         if (ctx->options & E2F_OPT_FRAGCHECK) {
2129                                 char type = '?';
2130
2131                                 if (pb->is_dir)
2132                                         type = 'd';
2133                                 else if (pb->is_reg)
2134                                         type = 'f';
2135
2136                                 printf(("%6lu(%c): expecting %6lu "
2137                                         "actual extent "
2138                                         "phys %6lu log %lu len %lu\n"),
2139                                        (unsigned long) pctx->ino, type,
2140                                        (unsigned long) pb->previous_block+1,
2141                                        (unsigned long) extent.e_pblk,
2142                                        (unsigned long) extent.e_lblk,
2143                                        (unsigned long) extent.e_len);
2144                         }
2145                         pb->fragmented = 1;
2146                 }
2147                 /*
2148                  * If we notice a gap in the logical block mappings of an
2149                  * extent-mapped directory, offer to close the hole by
2150                  * moving the logical block down, otherwise we'll go mad in
2151                  * pass 3 allocating empty directory blocks to fill the hole.
2152                  */
2153                 if (try_repairs && is_dir &&
2154                     pb->last_block + 1 < (e2_blkcnt_t)extent.e_lblk) {
2155                         blk64_t new_lblk;
2156
2157                         new_lblk = pb->last_block + 1;
2158                         if (EXT2FS_CLUSTER_RATIO(ctx->fs) > 1)
2159                                 new_lblk = ((new_lblk +
2160                                              EXT2FS_CLUSTER_RATIO(ctx->fs)) &
2161                                             EXT2FS_CLUSTER_MASK(ctx->fs)) |
2162                                            (extent.e_lblk &
2163                                             EXT2FS_CLUSTER_MASK(ctx->fs));
2164                         pctx->blk = extent.e_lblk;
2165                         pctx->blk2 = new_lblk;
2166                         if (fix_problem(ctx, PR_1_COLLAPSE_DBLOCK, pctx)) {
2167                                 extent.e_lblk = new_lblk;
2168                                 pb->inode_modified = 1;
2169                                 pctx->errcode = ext2fs_extent_replace(ehandle,
2170                                                                 0, &extent);
2171                                 if (pctx->errcode) {
2172                                         pctx->errcode = 0;
2173                                         goto alloc_later;
2174                                 }
2175                                 pctx->errcode = ext2fs_extent_fix_parents(ehandle);
2176                                 if (pctx->errcode)
2177                                         goto failed_add_dir_block;
2178                                 pctx->errcode = ext2fs_extent_goto(ehandle,
2179                                                                 extent.e_lblk);
2180                                 if (pctx->errcode)
2181                                         goto failed_add_dir_block;
2182                                 last_lblk = extent.e_lblk + extent.e_len - 1;
2183                         }
2184                 }
2185 alloc_later:
2186                 while (is_dir && (++pb->last_db_block <
2187                                   (e2_blkcnt_t) extent.e_lblk)) {
2188                         pctx->errcode = ext2fs_add_dir_block2(ctx->fs->dblist,
2189                                                               pb->ino, 0,
2190                                                               pb->last_db_block);
2191                         if (pctx->errcode) {
2192                                 pctx->blk = 0;
2193                                 pctx->num = pb->last_db_block;
2194                                 goto failed_add_dir_block;
2195                         }
2196                 }
2197                 if (!ctx->fs->cluster_ratio_bits) {
2198                         mark_blocks_used(ctx, extent.e_pblk, extent.e_len);
2199                         pb->num_blocks += extent.e_len;
2200                 }
2201                 for (blk = extent.e_pblk, blockcnt = extent.e_lblk, i = 0;
2202                      i < extent.e_len;
2203                      blk++, blockcnt++, i++) {
2204                         if (ctx->fs->cluster_ratio_bits &&
2205                             !(pb->previous_block &&
2206                               (EXT2FS_B2C(ctx->fs, blk) ==
2207                                EXT2FS_B2C(ctx->fs, pb->previous_block)) &&
2208                               (blk & EXT2FS_CLUSTER_MASK(ctx->fs)) ==
2209                               ((unsigned) blockcnt & EXT2FS_CLUSTER_MASK(ctx->fs)))) {
2210                                 mark_block_used(ctx, blk);
2211                                 pb->num_blocks++;
2212                         }
2213
2214                         pb->previous_block = blk;
2215
2216                         if (is_dir) {
2217                                 pctx->errcode = ext2fs_add_dir_block2(ctx->fs->dblist, pctx->ino, blk, blockcnt);
2218                                 if (pctx->errcode) {
2219                                         pctx->blk = blk;
2220                                         pctx->num = blockcnt;
2221                                 failed_add_dir_block:
2222                                         fix_problem(ctx, PR_1_ADD_DBLOCK, pctx);
2223                                         /* Should never get here */
2224                                         ctx->flags |= E2F_FLAG_ABORT;
2225                                         return;
2226                                 }
2227                         }
2228                 }
2229                 if (is_dir && extent.e_len > 0)
2230                         pb->last_db_block = blockcnt - 1;
2231                 pb->previous_block = extent.e_pblk + extent.e_len - 1;
2232                 start_block = pb->last_block = last_lblk;
2233                 if (is_leaf && !is_dir &&
2234                     !(extent.e_flags & EXT2_EXTENT_FLAGS_UNINIT))
2235                         pb->last_init_lblock = last_lblk;
2236         next:
2237                 pctx->errcode = ext2fs_extent_get(ehandle,
2238                                                   EXT2_EXTENT_NEXT_SIB,
2239                                                   &extent);
2240         }
2241         if (pctx->errcode == EXT2_ET_EXTENT_NO_NEXT)
2242                 pctx->errcode = 0;
2243 }
2244
2245 static void check_blocks_extents(e2fsck_t ctx, struct problem_context *pctx,
2246                                  struct process_block_struct *pb)
2247 {
2248         struct ext2_extent_info info;
2249         struct ext2_inode       *inode = pctx->inode;
2250         ext2_extent_handle_t    ehandle;
2251         ext2_filsys             fs = ctx->fs;
2252         ext2_ino_t              ino = pctx->ino;
2253         errcode_t               retval;
2254         blk64_t                 eof_lblk;
2255
2256         pctx->errcode = ext2fs_extent_open2(fs, ino, inode, &ehandle);
2257         if (pctx->errcode) {
2258                 if (fix_problem(ctx, PR_1_READ_EXTENT, pctx))
2259                         e2fsck_clear_inode(ctx, ino, inode, 0,
2260                                            "check_blocks_extents");
2261                 pctx->errcode = 0;
2262                 return;
2263         }
2264
2265         retval = ext2fs_extent_get_info(ehandle, &info);
2266         if (retval == 0) {
2267                 if (info.max_depth >= MAX_EXTENT_DEPTH_COUNT)
2268                         info.max_depth = MAX_EXTENT_DEPTH_COUNT-1;
2269                 ctx->extent_depth_count[info.max_depth]++;
2270         }
2271
2272         eof_lblk = ((EXT2_I_SIZE(inode) + fs->blocksize - 1) >>
2273                 EXT2_BLOCK_SIZE_BITS(fs->super)) - 1;
2274         scan_extent_node(ctx, pctx, pb, 0, 0, eof_lblk, ehandle, 1);
2275         if (pctx->errcode &&
2276             fix_problem(ctx, PR_1_EXTENT_ITERATE_FAILURE, pctx)) {
2277                 pb->num_blocks = 0;
2278                 inode->i_blocks = 0;
2279                 e2fsck_clear_inode(ctx, ino, inode, E2F_FLAG_RESTART,
2280                                    "check_blocks_extents");
2281                 pctx->errcode = 0;
2282         }
2283         ext2fs_extent_free(ehandle);
2284 }
2285
2286 /*
2287  * In fact we don't need to check blocks for an inode with inline data
2288  * because this inode doesn't have any blocks.  In this function all
2289  * we need to do is add this inode into dblist when it is a directory.
2290  */
2291 static void check_blocks_inline_data(e2fsck_t ctx, struct problem_context *pctx,
2292                                      struct process_block_struct *pb)
2293 {
2294         if (!pb->is_dir) {
2295                 pctx->errcode = 0;
2296                 return;
2297         }
2298
2299         pctx->errcode = ext2fs_add_dir_block2(ctx->fs->dblist, pb->ino, 0, 0);
2300         if (pctx->errcode) {
2301                 pctx->blk = 0;
2302                 pctx->num = 0;
2303                 fix_problem(ctx, PR_1_ADD_DBLOCK, pctx);
2304                 ctx->flags |= E2F_FLAG_ABORT;
2305         }
2306 }
2307
2308 /*
2309  * This subroutine is called on each inode to account for all of the
2310  * blocks used by that inode.
2311  */
2312 static void check_blocks(e2fsck_t ctx, struct problem_context *pctx,
2313                          char *block_buf)
2314 {
2315         ext2_filsys fs = ctx->fs;
2316         struct process_block_struct pb;
2317         ext2_ino_t      ino = pctx->ino;
2318         struct ext2_inode *inode = pctx->inode;
2319         unsigned        bad_size = 0;
2320         int             dirty_inode = 0;
2321         int             extent_fs;
2322         int             inlinedata_fs;
2323         __u64           size;
2324
2325         pb.ino = ino;
2326         pb.num_blocks = 0;
2327         pb.last_block = -1;
2328         pb.last_init_lblock = -1;
2329         pb.last_db_block = -1;
2330         pb.num_illegal_blocks = 0;
2331         pb.suppress = 0; pb.clear = 0;
2332         pb.fragmented = 0;
2333         pb.compressed = 0;
2334         pb.previous_block = 0;
2335         pb.is_dir = LINUX_S_ISDIR(inode->i_mode);
2336         pb.is_reg = LINUX_S_ISREG(inode->i_mode);
2337         pb.max_blocks = 1 << (31 - fs->super->s_log_block_size);
2338         pb.inode = inode;
2339         pb.pctx = pctx;
2340         pb.ctx = ctx;
2341         pb.inode_modified = 0;
2342         pb.bad_ref = 0;
2343         pctx->ino = ino;
2344         pctx->errcode = 0;
2345
2346         extent_fs = (ctx->fs->super->s_feature_incompat &
2347                      EXT3_FEATURE_INCOMPAT_EXTENTS);
2348         inlinedata_fs = (ctx->fs->super->s_feature_incompat &
2349                          EXT4_FEATURE_INCOMPAT_INLINE_DATA);
2350
2351         if (inode->i_flags & EXT2_COMPRBLK_FL) {
2352                 if (fs->super->s_feature_incompat &
2353                     EXT2_FEATURE_INCOMPAT_COMPRESSION)
2354                         pb.compressed = 1;
2355                 else {
2356                         if (fix_problem(ctx, PR_1_COMPR_SET, pctx)) {
2357                                 inode->i_flags &= ~EXT2_COMPRBLK_FL;
2358                                 dirty_inode++;
2359                         }
2360                 }
2361         }
2362
2363         if (ext2fs_file_acl_block(fs, inode) &&
2364             check_ext_attr(ctx, pctx, block_buf)) {
2365                 if (ctx->flags & E2F_FLAG_SIGNAL_MASK)
2366                         goto out;
2367                 pb.num_blocks++;
2368         }
2369
2370         if (ext2fs_inode_has_valid_blocks2(fs, inode)) {
2371                 if (extent_fs && (inode->i_flags & EXT4_EXTENTS_FL))
2372                         check_blocks_extents(ctx, pctx, &pb);
2373                 else {
2374                         /*
2375                          * If we've modified the inode, write it out before
2376                          * iterate() tries to use it.
2377                          */
2378                         if (dirty_inode) {
2379                                 e2fsck_write_inode(ctx, ino, inode,
2380                                                    "check_blocks");
2381                                 dirty_inode = 0;
2382                         }
2383                         fs->flags |= EXT2_FLAG_IGNORE_CSUM_ERRORS;
2384                         pctx->errcode = ext2fs_block_iterate3(fs, ino,
2385                                                 pb.is_dir ? BLOCK_FLAG_HOLE : 0,
2386                                                 block_buf, process_block, &pb);
2387                         /*
2388                          * We do not have uninitialized extents in non extent
2389                          * files.
2390                          */
2391                         pb.last_init_lblock = pb.last_block;
2392                         /*
2393                          * If iterate() changed a block mapping, we have to
2394                          * re-read the inode.  If we decide to clear the
2395                          * inode after clearing some stuff, we'll re-write the
2396                          * bad mappings into the inode!
2397                          */
2398                         if (pb.inode_modified)
2399                                 e2fsck_read_inode(ctx, ino, inode,
2400                                                   "check_blocks");
2401                         fs->flags &= ~EXT2_FLAG_IGNORE_CSUM_ERRORS;
2402                 }
2403         } else {
2404                 /* check inline data */
2405                 if (inlinedata_fs && (inode->i_flags & EXT4_INLINE_DATA_FL))
2406                         check_blocks_inline_data(ctx, pctx, &pb);
2407         }
2408         end_problem_latch(ctx, PR_LATCH_BLOCK);
2409         end_problem_latch(ctx, PR_LATCH_TOOBIG);
2410         if (ctx->flags & E2F_FLAG_SIGNAL_MASK)
2411                 goto out;
2412         if (pctx->errcode)
2413                 fix_problem(ctx, PR_1_BLOCK_ITERATE, pctx);
2414
2415         if (pb.fragmented && pb.num_blocks < fs->super->s_blocks_per_group) {
2416                 if (LINUX_S_ISDIR(inode->i_mode))
2417                         ctx->fs_fragmented_dir++;
2418                 else
2419                         ctx->fs_fragmented++;
2420         }
2421
2422         if (pb.clear) {
2423                 e2fsck_clear_inode(ctx, ino, inode, E2F_FLAG_RESTART,
2424                                    "check_blocks");
2425                 return;
2426         }
2427
2428         if (inode->i_flags & EXT2_INDEX_FL) {
2429                 if (handle_htree(ctx, pctx, ino, inode, block_buf)) {
2430                         inode->i_flags &= ~EXT2_INDEX_FL;
2431                         dirty_inode++;
2432                 } else {
2433 #ifdef ENABLE_HTREE
2434                         e2fsck_add_dx_dir(ctx, ino, pb.last_block+1);
2435 #endif
2436                 }
2437         }
2438
2439         if (!pb.num_blocks && pb.is_dir &&
2440             !(inode->i_flags & EXT4_INLINE_DATA_FL)) {
2441                 if (fix_problem(ctx, PR_1_ZERO_LENGTH_DIR, pctx)) {
2442                         e2fsck_clear_inode(ctx, ino, inode, 0, "check_blocks");
2443                         ctx->fs_directory_count--;
2444                         return;
2445                 }
2446         }
2447
2448         if (ino == EXT2_ROOT_INO || ino >= EXT2_FIRST_INODE(ctx->fs->super)) {
2449                 quota_data_add(ctx->qctx, inode, ino,
2450                                pb.num_blocks * fs->blocksize);
2451                 quota_data_inodes(ctx->qctx, inode, ino, +1);
2452         }
2453
2454         if (!(fs->super->s_feature_ro_compat &
2455               EXT4_FEATURE_RO_COMPAT_HUGE_FILE) ||
2456             !(inode->i_flags & EXT4_HUGE_FILE_FL))
2457                 pb.num_blocks *= (fs->blocksize / 512);
2458         pb.num_blocks *= EXT2FS_CLUSTER_RATIO(fs);
2459 #if 0
2460         printf("inode %u, i_size = %u, last_block = %lld, i_blocks=%llu, num_blocks = %llu\n",
2461                ino, inode->i_size, pb.last_block, ext2fs_inode_i_blocks(fs, inode),
2462                pb.num_blocks);
2463 #endif
2464         if (pb.is_dir) {
2465                 int nblock = inode->i_size >> EXT2_BLOCK_SIZE_BITS(fs->super);
2466                 if (inode->i_flags & EXT4_INLINE_DATA_FL) {
2467                         size_t size;
2468
2469                         if (ext2fs_inline_data_size(ctx->fs, pctx->ino, &size))
2470                                 bad_size = 5;
2471                         if (size != inode->i_size)
2472                                 bad_size = 5;
2473                 } else if (inode->i_size & (fs->blocksize - 1))
2474                         bad_size = 5;
2475                 else if (nblock > (pb.last_block + 1))
2476                         bad_size = 1;
2477                 else if (nblock < (pb.last_block + 1)) {
2478                         if (((pb.last_block + 1) - nblock) >
2479                             fs->super->s_prealloc_dir_blocks)
2480                                 bad_size = 2;
2481                 }
2482         } else {
2483                 e2_blkcnt_t blkpg = ctx->blocks_per_page;
2484
2485                 size = EXT2_I_SIZE(inode);
2486                 if ((pb.last_init_lblock >= 0) &&
2487                     /* allow allocated blocks to end of PAGE_SIZE */
2488                     (size < (__u64)pb.last_init_lblock * fs->blocksize) &&
2489                     (pb.last_init_lblock / blkpg * blkpg != pb.last_init_lblock ||
2490                      size < (__u64)(pb.last_init_lblock & ~(blkpg-1)) *
2491                      fs->blocksize))
2492                         bad_size = 3;
2493                 else if (!(extent_fs && (inode->i_flags & EXT4_EXTENTS_FL)) &&
2494                          size > ext2_max_sizes[fs->super->s_log_block_size])
2495                         /* too big for a direct/indirect-mapped file */
2496                         bad_size = 4;
2497                 else if ((extent_fs && (inode->i_flags & EXT4_EXTENTS_FL)) &&
2498                          size >
2499                          ((1ULL << (32 + EXT2_BLOCK_SIZE_BITS(fs->super))) - 1))
2500                         /* too big for an extent-based file - 32bit ee_block */
2501                         bad_size = 6;
2502         }
2503         /* i_size for symlinks is checked elsewhere */
2504         if (bad_size && !LINUX_S_ISLNK(inode->i_mode)) {
2505                 pctx->num = (pb.last_block+1) * fs->blocksize;
2506                 pctx->group = bad_size;
2507                 if (fix_problem(ctx, PR_1_BAD_I_SIZE, pctx)) {
2508                         inode->i_size = pctx->num;
2509                         if (!LINUX_S_ISDIR(inode->i_mode))
2510                                 inode->i_size_high = pctx->num >> 32;
2511                         dirty_inode++;
2512                 }
2513                 pctx->num = 0;
2514         }
2515         if (LINUX_S_ISREG(inode->i_mode) &&
2516             ext2fs_needs_large_file_feature(EXT2_I_SIZE(inode)))
2517                 ctx->large_files++;
2518         if ((pb.num_blocks != ext2fs_inode_i_blocks(fs, inode)) ||
2519             ((fs->super->s_feature_ro_compat &
2520               EXT4_FEATURE_RO_COMPAT_HUGE_FILE) &&
2521              (inode->i_flags & EXT4_HUGE_FILE_FL) &&
2522              (inode->osd2.linux2.l_i_blocks_hi != 0))) {
2523                 pctx->num = pb.num_blocks;
2524                 if (fix_problem(ctx, PR_1_BAD_I_BLOCKS, pctx)) {
2525                         inode->i_blocks = pb.num_blocks;
2526                         inode->osd2.linux2.l_i_blocks_hi = pb.num_blocks >> 32;
2527                         dirty_inode++;
2528                 }
2529                 pctx->num = 0;
2530         }
2531
2532         if (ctx->dirs_to_hash && pb.is_dir &&
2533             !(ctx->lost_and_found && ctx->lost_and_found == ino) &&
2534             !(inode->i_flags & EXT2_INDEX_FL) &&
2535             ((inode->i_size / fs->blocksize) >= 3))
2536                 e2fsck_rehash_dir_later(ctx, ino);
2537
2538 out:
2539         if (dirty_inode)
2540                 e2fsck_write_inode(ctx, ino, inode, "check_blocks");
2541 }
2542
2543 #if 0
2544 /*
2545  * Helper function called by process block when an illegal block is
2546  * found.  It returns a description about why the block is illegal
2547  */
2548 static char *describe_illegal_block(ext2_filsys fs, blk64_t block)
2549 {
2550         blk64_t super;
2551         int     i;
2552         static char     problem[80];
2553
2554         super = fs->super->s_first_data_block;
2555         strcpy(problem, "PROGRAMMING ERROR: Unknown reason for illegal block");
2556         if (block < super) {
2557                 sprintf(problem, "< FIRSTBLOCK (%u)", super);
2558                 return(problem);
2559         } else if (block >= ext2fs_blocks_count(fs->super)) {
2560                 sprintf(problem, "> BLOCKS (%u)", ext2fs_blocks_count(fs->super));
2561                 return(problem);
2562         }
2563         for (i = 0; i < fs->group_desc_count; i++) {
2564                 if (block == super) {
2565                         sprintf(problem, "is the superblock in group %d", i);
2566                         break;
2567                 }
2568                 if (block > super &&
2569                     block <= (super + fs->desc_blocks)) {
2570                         sprintf(problem, "is in the group descriptors "
2571                                 "of group %d", i);
2572                         break;
2573                 }
2574                 if (block == ext2fs_block_bitmap_loc(fs, i)) {
2575                         sprintf(problem, "is the block bitmap of group %d", i);
2576                         break;
2577                 }
2578                 if (block == ext2fs_inode_bitmap_loc(fs, i)) {
2579                         sprintf(problem, "is the inode bitmap of group %d", i);
2580                         break;
2581                 }
2582                 if (block >= ext2fs_inode_table_loc(fs, i) &&
2583                     (block < ext2fs_inode_table_loc(fs, i)
2584                      + fs->inode_blocks_per_group)) {
2585                         sprintf(problem, "is in the inode table of group %d",
2586                                 i);
2587                         break;
2588                 }
2589                 super += fs->super->s_blocks_per_group;
2590         }
2591         return(problem);
2592 }
2593 #endif
2594
2595 /*
2596  * This is a helper function for check_blocks().
2597  */
2598 static int process_block(ext2_filsys fs,
2599                   blk64_t       *block_nr,
2600                   e2_blkcnt_t blockcnt,
2601                   blk64_t ref_block EXT2FS_ATTR((unused)),
2602                   int ref_offset EXT2FS_ATTR((unused)),
2603                   void *priv_data)
2604 {
2605         struct process_block_struct *p;
2606         struct problem_context *pctx;
2607         blk64_t blk = *block_nr;
2608         int     ret_code = 0;
2609         problem_t       problem = 0;
2610         e2fsck_t        ctx;
2611
2612         p = (struct process_block_struct *) priv_data;
2613         pctx = p->pctx;
2614         ctx = p->ctx;
2615
2616         if (p->compressed && (blk == EXT2FS_COMPRESSED_BLKADDR)) {
2617                 /* todo: Check that the comprblk_fl is high, that the
2618                    blkaddr pattern looks right (all non-holes up to
2619                    first EXT2FS_COMPRESSED_BLKADDR, then all
2620                    EXT2FS_COMPRESSED_BLKADDR up to end of cluster),
2621                    that the feature_incompat bit is high, and that the
2622                    inode is a regular file.  If we're doing a "full
2623                    check" (a concept introduced to e2fsck by e2compr,
2624                    meaning that we look at data blocks as well as
2625                    metadata) then call some library routine that
2626                    checks the compressed data.  I'll have to think
2627                    about this, because one particularly important
2628                    problem to be able to fix is to recalculate the
2629                    cluster size if necessary.  I think that perhaps
2630                    we'd better do most/all e2compr-specific checks
2631                    separately, after the non-e2compr checks.  If not
2632                    doing a full check, it may be useful to test that
2633                    the personality is linux; e.g. if it isn't then
2634                    perhaps this really is just an illegal block. */
2635                 return 0;
2636         }
2637
2638         /*
2639          * For a directory, add logical block zero for processing even if it's
2640          * not mapped or we'll be perennially stuck with broken "." and ".."
2641          * entries.
2642          */
2643         if (p->is_dir && blockcnt == 0 && blk == 0) {
2644                 pctx->errcode = ext2fs_add_dir_block2(fs->dblist, p->ino, 0, 0);
2645                 if (pctx->errcode) {
2646                         pctx->blk = blk;
2647                         pctx->num = blockcnt;
2648                         goto failed_add_dir_block;
2649                 }
2650                 p->last_db_block++;
2651         }
2652
2653         if (blk == 0)
2654                 return 0;
2655
2656 #if 0
2657         printf("Process_block, inode %lu, block %u, #%d\n", p->ino, blk,
2658                blockcnt);
2659 #endif
2660
2661         /*
2662          * Simplistic fragmentation check.  We merely require that the
2663          * file be contiguous.  (Which can never be true for really
2664          * big files that are greater than a block group.)
2665          */
2666         if (!HOLE_BLKADDR(p->previous_block) && p->ino != EXT2_RESIZE_INO) {
2667                 if (p->previous_block+1 != blk) {
2668                         if (ctx->options & E2F_OPT_FRAGCHECK) {
2669                                 char type = '?';
2670
2671                                 if (p->is_dir)
2672                                         type = 'd';
2673                                 else if (p->is_reg)
2674                                         type = 'f';
2675
2676                                 printf(_("%6lu(%c): expecting %6lu "
2677                                          "got phys %6lu (blkcnt %lld)\n"),
2678                                        (unsigned long) pctx->ino, type,
2679                                        (unsigned long) p->previous_block+1,
2680                                        (unsigned long) blk,
2681                                        blockcnt);
2682                         }
2683                         p->fragmented = 1;
2684                 }
2685         }
2686
2687         if (p->is_dir && blockcnt > (1 << (21 - fs->super->s_log_block_size)))
2688                 problem = PR_1_TOOBIG_DIR;
2689         if (p->is_reg && p->num_blocks+1 >= p->max_blocks)
2690                 problem = PR_1_TOOBIG_REG;
2691         if (!p->is_dir && !p->is_reg && blockcnt > 0)
2692                 problem = PR_1_TOOBIG_SYMLINK;
2693
2694         if (blk < fs->super->s_first_data_block ||
2695             blk >= ext2fs_blocks_count(fs->super))
2696                 problem = PR_1_ILLEGAL_BLOCK_NUM;
2697
2698         /*
2699          * If this IND/DIND/TIND block is squatting atop some critical metadata
2700          * (group descriptors, superblock, bitmap, inode table), any write to
2701          * "fix" mapping problems will destroy the metadata.  We'll let pass 1b
2702          * fix that and restart fsck.
2703          */
2704         if (blockcnt < 0 &&
2705             p->ino != EXT2_RESIZE_INO &&
2706             ext2fs_test_block_bitmap2(ctx->block_metadata_map, blk)) {
2707                 p->bad_ref = blk;
2708                 pctx->blk = blk;
2709                 fix_problem(ctx, PR_1_CRITICAL_METADATA_COLLISION, pctx);
2710                 ctx->flags |= E2F_FLAG_RESTART_LATER;
2711         }
2712
2713         if (problem) {
2714                 p->num_illegal_blocks++;
2715                 /*
2716                  * A bit of subterfuge here -- we're trying to fix a block
2717                  * mapping, but know that the IND/DIND/TIND block has collided
2718                  * with some critical metadata.  So, fix the in-core mapping so
2719                  * iterate won't go insane, but return 0 instead of
2720                  * BLOCK_CHANGED so that it won't write the remapping out to
2721                  * our multiply linked block.
2722                  */
2723                 if (p->bad_ref && ref_block == p->bad_ref) {
2724                         *block_nr = 0;
2725                         return 0;
2726                 }
2727                 if (!p->suppress && (p->num_illegal_blocks % 12) == 0) {
2728                         if (fix_problem(ctx, PR_1_TOO_MANY_BAD_BLOCKS, pctx)) {
2729                                 p->clear = 1;
2730                                 return BLOCK_ABORT;
2731                         }
2732                         if (fix_problem(ctx, PR_1_SUPPRESS_MESSAGES, pctx)) {
2733                                 p->suppress = 1;
2734                                 set_latch_flags(PR_LATCH_BLOCK,
2735                                                 PRL_SUPPRESS, 0);
2736                         }
2737                 }
2738                 pctx->blk = blk;
2739                 pctx->blkcount = blockcnt;
2740                 if (fix_problem(ctx, problem, pctx)) {
2741                         blk = *block_nr = 0;
2742                         ret_code = BLOCK_CHANGED;
2743                         p->inode_modified = 1;
2744                         /*
2745                          * If the directory block is too big and is beyond the
2746                          * end of the FS, don't bother trying to add it for
2747                          * processing -- the kernel would never have created a
2748                          * directory this large, and we risk an ENOMEM abort.
2749                          * In any case, the toobig handler for extent-based
2750                          * directories also doesn't feed toobig blocks to
2751                          * pass 2.
2752                          */
2753                         if (problem == PR_1_TOOBIG_DIR)
2754                                 return ret_code;
2755                         goto mark_dir;
2756                 } else
2757                         return 0;
2758         }
2759
2760         if (p->ino == EXT2_RESIZE_INO) {
2761                 /*
2762                  * The resize inode has already be sanity checked
2763                  * during pass #0 (the superblock checks).  All we
2764                  * have to do is mark the double indirect block as
2765                  * being in use; all of the other blocks are handled
2766                  * by mark_table_blocks()).
2767                  */
2768                 if (blockcnt == BLOCK_COUNT_DIND)
2769                         mark_block_used(ctx, blk);
2770                 p->num_blocks++;
2771         } else if (!(ctx->fs->cluster_ratio_bits &&
2772                      p->previous_block &&
2773                      (EXT2FS_B2C(ctx->fs, blk) ==
2774                       EXT2FS_B2C(ctx->fs, p->previous_block)) &&
2775                      (blk & EXT2FS_CLUSTER_MASK(ctx->fs)) ==
2776                      ((unsigned) blockcnt & EXT2FS_CLUSTER_MASK(ctx->fs)))) {
2777                 mark_block_used(ctx, blk);
2778                 p->num_blocks++;
2779         }
2780         if (blockcnt >= 0)
2781                 p->last_block = blockcnt;
2782         p->previous_block = blk;
2783 mark_dir:
2784         if (p->is_dir && (blockcnt >= 0)) {
2785                 while (++p->last_db_block < blockcnt) {
2786                         pctx->errcode = ext2fs_add_dir_block2(fs->dblist,
2787                                                               p->ino, 0,
2788                                                               p->last_db_block);
2789                         if (pctx->errcode) {
2790                                 pctx->blk = 0;
2791                                 pctx->num = p->last_db_block;
2792                                 goto failed_add_dir_block;
2793                         }
2794                 }
2795                 pctx->errcode = ext2fs_add_dir_block2(fs->dblist, p->ino,
2796                                                       blk, blockcnt);
2797                 if (pctx->errcode) {
2798                         pctx->blk = blk;
2799                         pctx->num = blockcnt;
2800                 failed_add_dir_block:
2801                         fix_problem(ctx, PR_1_ADD_DBLOCK, pctx);
2802                         /* Should never get here */
2803                         ctx->flags |= E2F_FLAG_ABORT;
2804                         return BLOCK_ABORT;
2805                 }
2806         }
2807         return ret_code;
2808 }
2809
2810 static int process_bad_block(ext2_filsys fs,
2811                       blk64_t *block_nr,
2812                       e2_blkcnt_t blockcnt,
2813                       blk64_t ref_block EXT2FS_ATTR((unused)),
2814                       int ref_offset EXT2FS_ATTR((unused)),
2815                       void *priv_data)
2816 {
2817         struct process_block_struct *p;
2818         blk64_t         blk = *block_nr;
2819         blk64_t         first_block;
2820         dgrp_t          i;
2821         struct problem_context *pctx;
2822         e2fsck_t        ctx;
2823
2824         /*
2825          * Note: This function processes blocks for the bad blocks
2826          * inode, which is never compressed.  So we don't use HOLE_BLKADDR().
2827          */
2828
2829         if (!blk)
2830                 return 0;
2831
2832         p = (struct process_block_struct *) priv_data;
2833         ctx = p->ctx;
2834         pctx = p->pctx;
2835
2836         pctx->ino = EXT2_BAD_INO;
2837         pctx->blk = blk;
2838         pctx->blkcount = blockcnt;
2839
2840         if ((blk < fs->super->s_first_data_block) ||
2841             (blk >= ext2fs_blocks_count(fs->super))) {
2842                 if (fix_problem(ctx, PR_1_BB_ILLEGAL_BLOCK_NUM, pctx)) {
2843                         *block_nr = 0;
2844                         return BLOCK_CHANGED;
2845                 } else
2846                         return 0;
2847         }
2848
2849         if (blockcnt < 0) {
2850                 if (ext2fs_test_block_bitmap2(p->fs_meta_blocks, blk)) {
2851                         p->bbcheck = 1;
2852                         if (fix_problem(ctx, PR_1_BB_FS_BLOCK, pctx)) {
2853                                 *block_nr = 0;
2854                                 return BLOCK_CHANGED;
2855                         }
2856                 } else if (ext2fs_test_block_bitmap2(ctx->block_found_map,
2857                                                     blk)) {
2858                         p->bbcheck = 1;
2859                         if (fix_problem(ctx, PR_1_BBINODE_BAD_METABLOCK,
2860                                         pctx)) {
2861                                 *block_nr = 0;
2862                                 return BLOCK_CHANGED;
2863                         }
2864                         if (ctx->flags & E2F_FLAG_SIGNAL_MASK)
2865                                 return BLOCK_ABORT;
2866                 } else
2867                         mark_block_used(ctx, blk);
2868                 return 0;
2869         }
2870 #if 0
2871         printf ("DEBUG: Marking %u as bad.\n", blk);
2872 #endif
2873         ctx->fs_badblocks_count++;
2874         /*
2875          * If the block is not used, then mark it as used and return.
2876          * If it is already marked as found, this must mean that
2877          * there's an overlap between the filesystem table blocks
2878          * (bitmaps and inode table) and the bad block list.
2879          */
2880         if (!ext2fs_test_block_bitmap2(ctx->block_found_map, blk)) {
2881                 ext2fs_mark_block_bitmap2(ctx->block_found_map, blk);
2882                 return 0;
2883         }
2884         /*
2885          * Try to find the where the filesystem block was used...
2886          */
2887         first_block = fs->super->s_first_data_block;
2888
2889         for (i = 0; i < fs->group_desc_count; i++ ) {
2890                 pctx->group = i;
2891                 pctx->blk = blk;
2892                 if (!ext2fs_bg_has_super(fs, i))
2893                         goto skip_super;
2894                 if (blk == first_block) {
2895                         if (i == 0) {
2896                                 if (fix_problem(ctx,
2897                                                 PR_1_BAD_PRIMARY_SUPERBLOCK,
2898                                                 pctx)) {
2899                                         *block_nr = 0;
2900                                         return BLOCK_CHANGED;
2901                                 }
2902                                 return 0;
2903                         }
2904                         fix_problem(ctx, PR_1_BAD_SUPERBLOCK, pctx);
2905                         return 0;
2906                 }
2907                 if ((blk > first_block) &&
2908                     (blk <= first_block + fs->desc_blocks)) {
2909                         if (i == 0) {
2910                                 pctx->blk = *block_nr;
2911                                 if (fix_problem(ctx,
2912                         PR_1_BAD_PRIMARY_GROUP_DESCRIPTOR, pctx)) {
2913                                         *block_nr = 0;
2914                                         return BLOCK_CHANGED;
2915                                 }
2916                                 return 0;
2917                         }
2918                         fix_problem(ctx, PR_1_BAD_GROUP_DESCRIPTORS, pctx);
2919                         return 0;
2920                 }
2921         skip_super:
2922                 if (blk == ext2fs_block_bitmap_loc(fs, i)) {
2923                         if (fix_problem(ctx, PR_1_BB_BAD_BLOCK, pctx)) {
2924                                 ctx->invalid_block_bitmap_flag[i]++;
2925                                 ctx->invalid_bitmaps++;
2926                         }
2927                         return 0;
2928                 }
2929                 if (blk == ext2fs_inode_bitmap_loc(fs, i)) {
2930                         if (fix_problem(ctx, PR_1_IB_BAD_BLOCK, pctx)) {
2931                                 ctx->invalid_inode_bitmap_flag[i]++;
2932                                 ctx->invalid_bitmaps++;
2933                         }
2934                         return 0;
2935                 }
2936                 if ((blk >= ext2fs_inode_table_loc(fs, i)) &&
2937                     (blk < (ext2fs_inode_table_loc(fs, i) +
2938                             fs->inode_blocks_per_group))) {
2939                         /*
2940                          * If there are bad blocks in the inode table,
2941                          * the inode scan code will try to do
2942                          * something reasonable automatically.
2943                          */
2944                         return 0;
2945                 }
2946                 first_block += fs->super->s_blocks_per_group;
2947         }
2948         /*
2949          * If we've gotten to this point, then the only
2950          * possibility is that the bad block inode meta data
2951          * is using a bad block.
2952          */
2953         if ((blk == p->inode->i_block[EXT2_IND_BLOCK]) ||
2954             (blk == p->inode->i_block[EXT2_DIND_BLOCK]) ||
2955             (blk == p->inode->i_block[EXT2_TIND_BLOCK])) {
2956                 p->bbcheck = 1;
2957                 if (fix_problem(ctx, PR_1_BBINODE_BAD_METABLOCK, pctx)) {
2958                         *block_nr = 0;
2959                         return BLOCK_CHANGED;
2960                 }
2961                 if (ctx->flags & E2F_FLAG_SIGNAL_MASK)
2962                         return BLOCK_ABORT;
2963                 return 0;
2964         }
2965
2966         pctx->group = -1;
2967
2968         /* Warn user that the block wasn't claimed */
2969         fix_problem(ctx, PR_1_PROGERR_CLAIMED_BLOCK, pctx);
2970
2971         return 0;
2972 }
2973
2974 static void new_table_block(e2fsck_t ctx, blk64_t first_block, dgrp_t group,
2975                             const char *name, int num, blk64_t *new_block)
2976 {
2977         ext2_filsys fs = ctx->fs;
2978         dgrp_t          last_grp;
2979         blk64_t         old_block = *new_block;
2980         blk64_t         last_block;
2981         dgrp_t          flexbg;
2982         unsigned        flexbg_size;
2983         int             i, is_flexbg;
2984         char            *buf;
2985         struct problem_context  pctx;
2986
2987         clear_problem_context(&pctx);
2988
2989         pctx.group = group;
2990         pctx.blk = old_block;
2991         pctx.str = name;
2992
2993         /*
2994          * For flex_bg filesystems, first try to allocate the metadata
2995          * within the flex_bg, and if that fails then try finding the
2996          * space anywhere in the filesystem.
2997          */
2998         is_flexbg = EXT2_HAS_INCOMPAT_FEATURE(fs->super,
2999                                               EXT4_FEATURE_INCOMPAT_FLEX_BG);
3000         if (is_flexbg) {
3001                 flexbg_size = 1 << fs->super->s_log_groups_per_flex;
3002                 flexbg = group / flexbg_size;
3003                 first_block = ext2fs_group_first_block2(fs,
3004                                                         flexbg_size * flexbg);
3005                 last_grp = group | (flexbg_size - 1);
3006                 if (last_grp >= fs->group_desc_count)
3007                         last_grp = fs->group_desc_count - 1;
3008                 last_block = ext2fs_group_last_block2(fs, last_grp);
3009         } else
3010                 last_block = ext2fs_group_last_block2(fs, group);
3011         pctx.errcode = ext2fs_get_free_blocks2(fs, first_block, last_block,
3012                                                num, ctx->block_found_map,
3013                                                new_block);
3014         if (is_flexbg && (pctx.errcode == EXT2_ET_BLOCK_ALLOC_FAIL))
3015                 pctx.errcode = ext2fs_get_free_blocks2(fs,
3016                                 fs->super->s_first_data_block,
3017                                 ext2fs_blocks_count(fs->super),
3018                                 num, ctx->block_found_map, new_block);
3019         if (pctx.errcode) {
3020                 pctx.num = num;
3021                 fix_problem(ctx, PR_1_RELOC_BLOCK_ALLOCATE, &pctx);
3022                 ext2fs_unmark_valid(fs);
3023                 ctx->flags |= E2F_FLAG_ABORT;
3024                 return;
3025         }
3026         pctx.errcode = ext2fs_get_mem(fs->blocksize, &buf);
3027         if (pctx.errcode) {
3028                 fix_problem(ctx, PR_1_RELOC_MEMORY_ALLOCATE, &pctx);
3029                 ext2fs_unmark_valid(fs);
3030                 ctx->flags |= E2F_FLAG_ABORT;
3031                 return;
3032         }
3033         ext2fs_mark_super_dirty(fs);
3034         fs->flags &= ~EXT2_FLAG_MASTER_SB_ONLY;
3035         pctx.blk2 = *new_block;
3036         fix_problem(ctx, (old_block ? PR_1_RELOC_FROM_TO :
3037                           PR_1_RELOC_TO), &pctx);
3038         pctx.blk2 = 0;
3039         for (i = 0; i < num; i++) {
3040                 pctx.blk = i;
3041                 ext2fs_mark_block_bitmap2(ctx->block_found_map, (*new_block)+i);
3042                 if (old_block) {
3043                         pctx.errcode = io_channel_read_blk64(fs->io,
3044                                    old_block + i, 1, buf);
3045                         if (pctx.errcode)
3046                                 fix_problem(ctx, PR_1_RELOC_READ_ERR, &pctx);
3047                 } else
3048                         memset(buf, 0, fs->blocksize);
3049
3050                 pctx.blk = (*new_block) + i;
3051                 pctx.errcode = io_channel_write_blk64(fs->io, pctx.blk,
3052                                               1, buf);
3053                 if (pctx.errcode)
3054                         fix_problem(ctx, PR_1_RELOC_WRITE_ERR, &pctx);
3055         }
3056         ext2fs_free_mem(&buf);
3057 }
3058
3059 /*
3060  * This routine gets called at the end of pass 1 if bad blocks are
3061  * detected in the superblock, group descriptors, inode_bitmaps, or
3062  * block bitmaps.  At this point, all of the blocks have been mapped
3063  * out, so we can try to allocate new block(s) to replace the bad
3064  * blocks.
3065  */
3066 static void handle_fs_bad_blocks(e2fsck_t ctx)
3067 {
3068         ext2_filsys fs = ctx->fs;
3069         dgrp_t          i;
3070         blk64_t         first_block;
3071         blk64_t         new_blk;
3072
3073         for (i = 0; i < fs->group_desc_count; i++) {
3074                 first_block = ext2fs_group_first_block2(fs, i);
3075
3076                 if (ctx->invalid_block_bitmap_flag[i]) {
3077                         new_blk = ext2fs_block_bitmap_loc(fs, i);
3078                         new_table_block(ctx, first_block, i, _("block bitmap"),
3079                                         1, &new_blk);
3080                         ext2fs_block_bitmap_loc_set(fs, i, new_blk);
3081                 }
3082                 if (ctx->invalid_inode_bitmap_flag[i]) {
3083                         new_blk = ext2fs_inode_bitmap_loc(fs, i);
3084                         new_table_block(ctx, first_block, i, _("inode bitmap"),
3085                                         1, &new_blk);
3086                         ext2fs_inode_bitmap_loc_set(fs, i, new_blk);
3087                 }
3088                 if (ctx->invalid_inode_table_flag[i]) {
3089                         new_blk = ext2fs_inode_table_loc(fs, i);
3090                         new_table_block(ctx, first_block, i, _("inode table"),
3091                                         fs->inode_blocks_per_group,
3092                                         &new_blk);
3093                         ext2fs_inode_table_loc_set(fs, i, new_blk);
3094                         ctx->flags |= E2F_FLAG_RESTART;
3095                 }
3096         }
3097         ctx->invalid_bitmaps = 0;
3098 }
3099
3100 /*
3101  * This routine marks all blocks which are used by the superblock,
3102  * group descriptors, inode bitmaps, and block bitmaps.
3103  */
3104 static void mark_table_blocks(e2fsck_t ctx)
3105 {
3106         ext2_filsys fs = ctx->fs;
3107         blk64_t b;
3108         dgrp_t  i;
3109         unsigned int    j;
3110         struct problem_context pctx;
3111
3112         clear_problem_context(&pctx);
3113
3114         for (i = 0; i < fs->group_desc_count; i++) {
3115                 pctx.group = i;
3116
3117                 ext2fs_reserve_super_and_bgd(fs, i, ctx->block_found_map);
3118                 ext2fs_reserve_super_and_bgd(fs, i, ctx->block_metadata_map);
3119
3120                 /*
3121                  * Mark the blocks used for the inode table
3122                  */
3123                 if (ext2fs_inode_table_loc(fs, i)) {
3124                         for (j = 0, b = ext2fs_inode_table_loc(fs, i);
3125                              j < fs->inode_blocks_per_group;
3126                              j++, b++) {
3127                                 if (ext2fs_test_block_bitmap2(ctx->block_found_map,
3128                                                              b)) {
3129                                         pctx.blk = b;
3130                                         if (!ctx->invalid_inode_table_flag[i] &&
3131                                             fix_problem(ctx,
3132                                                 PR_1_ITABLE_CONFLICT, &pctx)) {
3133                                                 ctx->invalid_inode_table_flag[i]++;
3134                                                 ctx->invalid_bitmaps++;
3135                                         }
3136                                 } else {
3137                                     ext2fs_mark_block_bitmap2(
3138                                                 ctx->block_found_map, b);
3139                                     ext2fs_mark_block_bitmap2(
3140                                                 ctx->block_metadata_map, b);
3141                                 }
3142                         }
3143                 }
3144
3145                 /*
3146                  * Mark block used for the block bitmap
3147                  */
3148                 if (ext2fs_block_bitmap_loc(fs, i)) {
3149                         if (ext2fs_test_block_bitmap2(ctx->block_found_map,
3150                                      ext2fs_block_bitmap_loc(fs, i))) {
3151                                 pctx.blk = ext2fs_block_bitmap_loc(fs, i);
3152                                 if (fix_problem(ctx, PR_1_BB_CONFLICT, &pctx)) {
3153                                         ctx->invalid_block_bitmap_flag[i]++;
3154                                         ctx->invalid_bitmaps++;
3155                                 }
3156                         } else {
3157                             ext2fs_mark_block_bitmap2(ctx->block_found_map,
3158                                      ext2fs_block_bitmap_loc(fs, i));
3159                             ext2fs_mark_block_bitmap2(ctx->block_metadata_map,
3160                                      ext2fs_block_bitmap_loc(fs, i));
3161                         }
3162                 }
3163                 /*
3164                  * Mark block used for the inode bitmap
3165                  */
3166                 if (ext2fs_inode_bitmap_loc(fs, i)) {
3167                         if (ext2fs_test_block_bitmap2(ctx->block_found_map,
3168                                      ext2fs_inode_bitmap_loc(fs, i))) {
3169                                 pctx.blk = ext2fs_inode_bitmap_loc(fs, i);
3170                                 if (fix_problem(ctx, PR_1_IB_CONFLICT, &pctx)) {
3171                                         ctx->invalid_inode_bitmap_flag[i]++;
3172                                         ctx->invalid_bitmaps++;
3173                                 }
3174                         } else {
3175                             ext2fs_mark_block_bitmap2(ctx->block_metadata_map,
3176                                      ext2fs_inode_bitmap_loc(fs, i));
3177                             ext2fs_mark_block_bitmap2(ctx->block_found_map,
3178                                      ext2fs_inode_bitmap_loc(fs, i));
3179                         }
3180                 }
3181         }
3182 }
3183
3184 /*
3185  * Thes subroutines short circuits ext2fs_get_blocks and
3186  * ext2fs_check_directory; we use them since we already have the inode
3187  * structure, so there's no point in letting the ext2fs library read
3188  * the inode again.
3189  */
3190 static errcode_t pass1_get_blocks(ext2_filsys fs, ext2_ino_t ino,
3191                                   blk_t *blocks)
3192 {
3193         e2fsck_t ctx = (e2fsck_t) fs->priv_data;
3194         int     i;
3195
3196         if ((ino != ctx->stashed_ino) || !ctx->stashed_inode)
3197                 return EXT2_ET_CALLBACK_NOTHANDLED;
3198
3199         for (i=0; i < EXT2_N_BLOCKS; i++)
3200                 blocks[i] = ctx->stashed_inode->i_block[i];
3201         return 0;
3202 }
3203
3204 static errcode_t pass1_read_inode(ext2_filsys fs, ext2_ino_t ino,
3205                                   struct ext2_inode *inode)
3206 {
3207         e2fsck_t ctx = (e2fsck_t) fs->priv_data;
3208
3209         if ((ino != ctx->stashed_ino) || !ctx->stashed_inode)
3210                 return EXT2_ET_CALLBACK_NOTHANDLED;
3211         *inode = *ctx->stashed_inode;
3212         return 0;
3213 }
3214
3215 static errcode_t pass1_write_inode(ext2_filsys fs, ext2_ino_t ino,
3216                             struct ext2_inode *inode)
3217 {
3218         e2fsck_t ctx = (e2fsck_t) fs->priv_data;
3219
3220         if ((ino == ctx->stashed_ino) && ctx->stashed_inode &&
3221                 (inode != ctx->stashed_inode))
3222                 *ctx->stashed_inode = *inode;
3223         return EXT2_ET_CALLBACK_NOTHANDLED;
3224 }
3225
3226 static errcode_t pass1_check_directory(ext2_filsys fs, ext2_ino_t ino)
3227 {
3228         e2fsck_t ctx = (e2fsck_t) fs->priv_data;
3229
3230         if ((ino != ctx->stashed_ino) || !ctx->stashed_inode)
3231                 return EXT2_ET_CALLBACK_NOTHANDLED;
3232
3233         if (!LINUX_S_ISDIR(ctx->stashed_inode->i_mode))
3234                 return EXT2_ET_NO_DIRECTORY;
3235         return 0;
3236 }
3237
3238 static errcode_t e2fsck_get_alloc_block(ext2_filsys fs, blk64_t goal,
3239                                         blk64_t *ret)
3240 {
3241         e2fsck_t ctx = (e2fsck_t) fs->priv_data;
3242         errcode_t       retval;
3243         blk64_t         new_block;
3244
3245         if (ctx->block_found_map) {
3246                 retval = ext2fs_new_block2(fs, goal, ctx->block_found_map,
3247                                            &new_block);
3248                 if (retval)
3249                         return retval;
3250                 if (fs->block_map) {
3251                         ext2fs_mark_block_bitmap2(fs->block_map, new_block);
3252                         ext2fs_mark_bb_dirty(fs);
3253                 }
3254         } else {
3255                 if (!fs->block_map) {
3256                         retval = ext2fs_read_block_bitmap(fs);
3257                         if (retval)
3258                                 return retval;
3259                 }
3260
3261                 retval = ext2fs_new_block2(fs, goal, 0, &new_block);
3262                 if (retval)
3263                         return retval;
3264         }
3265
3266         *ret = new_block;
3267         return (0);
3268 }
3269
3270 static void e2fsck_block_alloc_stats(ext2_filsys fs, blk64_t blk, int inuse)
3271 {
3272         e2fsck_t ctx = (e2fsck_t) fs->priv_data;
3273
3274         if (ctx->block_found_map) {
3275                 if (inuse > 0)
3276                         ext2fs_mark_block_bitmap2(ctx->block_found_map, blk);
3277                 else
3278                         ext2fs_unmark_block_bitmap2(ctx->block_found_map, blk);
3279         }
3280 }
3281
3282 void e2fsck_use_inode_shortcuts(e2fsck_t ctx, int use_shortcuts)
3283 {
3284         ext2_filsys fs = ctx->fs;
3285
3286         if (use_shortcuts) {
3287                 fs->get_blocks = pass1_get_blocks;
3288                 fs->check_directory = pass1_check_directory;
3289                 fs->read_inode = pass1_read_inode;
3290                 fs->write_inode = pass1_write_inode;
3291                 ctx->stashed_ino = 0;
3292         } else {
3293                 fs->get_blocks = 0;
3294                 fs->check_directory = 0;
3295                 fs->read_inode = 0;
3296                 fs->write_inode = 0;
3297         }
3298 }
3299
3300 void e2fsck_intercept_block_allocations(e2fsck_t ctx)
3301 {
3302         ext2fs_set_alloc_block_callback(ctx->fs, e2fsck_get_alloc_block, 0);
3303         ext2fs_set_block_alloc_stats_callback(ctx->fs,
3304                                                 e2fsck_block_alloc_stats, 0);
3305 }