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