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