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