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