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