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