OSDN Git Service

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