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