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