Whamcloud - gitweb
LU-14768 e2fsck: merge casefolded dir lists after thread finish
[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 are casefolded.      (inode_casefold_map)
28  *      - A bitmap of which inodes need to be expanded  (expand_eisize_map)
29  *      - A bitmap of which blocks are in use.          (block_found_map)
30  *      - A bitmap of which blocks are in use by two inodes     (block_dup_map)
31  *      - The data blocks of the directory inodes.      (dir_map)
32  *      - Ref counts for ea_inodes.                     (ea_inode_refs)
33  *      - The encryption policy ID of each encrypted inode. (encrypted_files)
34  *
35  * Pass 1 is designed to stash away enough information so that the
36  * other passes should not need to read in the inode information
37  * during the normal course of a filesystem check.  (Although if an
38  * inconsistency is detected, other passes may need to read in an
39  * inode to fix it.)
40  *
41  * Note that pass 1B will be invoked if there are any duplicate blocks
42  * found.
43  */
44
45 #define _GNU_SOURCE 1 /* get strnlen() */
46 #include "config.h"
47 #include <string.h>
48 #include <time.h>
49 #ifdef HAVE_ERRNO_H
50 #include <errno.h>
51 #endif
52 #include <assert.h>
53 #ifdef HAVE_PTHREAD
54 #include <pthread.h>
55 #endif
56
57 #include "e2fsck.h"
58 #include <ext2fs/ext2_ext_attr.h>
59 /* todo remove this finally */
60 #include <ext2fs/ext2fsP.h>
61 #include <e2p/e2p.h>
62
63 #include "problem.h"
64
65 #ifdef NO_INLINE_FUNCS
66 #define _INLINE_
67 #else
68 #define _INLINE_ inline
69 #endif
70
71 #undef DEBUG
72
73 struct ea_quota {
74         blk64_t blocks;
75         __u64 inodes;
76 };
77
78 static int process_block(ext2_filsys fs, blk64_t        *blocknr,
79                          e2_blkcnt_t blockcnt, blk64_t ref_blk,
80                          int ref_offset, void *priv_data);
81 static int process_bad_block(ext2_filsys fs, blk64_t *block_nr,
82                              e2_blkcnt_t blockcnt, blk64_t ref_blk,
83                              int ref_offset, void *priv_data);
84 static void check_blocks(e2fsck_t ctx, struct problem_context *pctx,
85                          char *block_buf,
86                          const struct ea_quota *ea_ibody_quota);
87 static void mark_table_blocks(e2fsck_t ctx);
88 static void alloc_bb_map(e2fsck_t ctx);
89 static void alloc_imagic_map(e2fsck_t ctx);
90 static void add_casefolded_dir(e2fsck_t ctx, ino_t ino);
91 static void handle_fs_bad_blocks(e2fsck_t ctx);
92 static EXT2_QSORT_TYPE process_inode_cmp(const void *a, const void *b);
93 static errcode_t scan_callback(ext2_filsys fs, ext2_inode_scan scan,
94                                   dgrp_t group, void * priv_data);
95 static void adjust_extattr_refcount(e2fsck_t ctx, ext2_refcount_t refcount,
96                                     char *block_buf, int adjust_sign);
97 /* static char *describe_illegal_block(ext2_filsys fs, blk64_t block); */
98
99 struct process_block_struct {
100         ext2_ino_t      ino;
101         unsigned        is_dir:1, is_reg:1, clear:1, suppress:1,
102                                 fragmented:1, compressed:1, bbcheck:1,
103                                 inode_modified:1;
104         blk64_t         num_blocks;
105         blk64_t         max_blocks;
106         blk64_t         last_block;
107         e2_blkcnt_t     last_init_lblock;
108         e2_blkcnt_t     last_db_block;
109         int             num_illegal_blocks;
110         blk64_t         previous_block;
111         struct ext2_inode *inode;
112         struct problem_context *pctx;
113         ext2fs_block_bitmap fs_meta_blocks;
114         e2fsck_t        ctx;
115         blk64_t         next_lblock;
116         struct extent_tree_info eti;
117 };
118
119 struct process_inode_block {
120         ext2_ino_t ino;
121         struct ea_quota ea_ibody_quota;
122         struct ext2_inode_large inode;
123 };
124
125 struct scan_callback_struct {
126         e2fsck_t                         ctx;
127         char                            *block_buf;
128         struct process_inode_block      *inodes_to_process;
129         int                             *process_inode_count;
130 };
131
132 static void process_inodes(e2fsck_t ctx, char *block_buf,
133                            struct process_inode_block *inodes_to_process,
134                            int *process_inode_count);
135
136 static __u64 ext2_max_sizes[EXT2_MAX_BLOCK_LOG_SIZE -
137                             EXT2_MIN_BLOCK_LOG_SIZE + 1];
138
139 /*
140  * Check to make sure a device inode is real.  Returns 1 if the device
141  * checks out, 0 if not.
142  *
143  * Note: this routine is now also used to check FIFO's and Sockets,
144  * since they have the same requirement; the i_block fields should be
145  * zero.
146  */
147 int e2fsck_pass1_check_device_inode(ext2_filsys fs EXT2FS_ATTR((unused)),
148                                     struct ext2_inode *inode)
149 {
150         int     i;
151
152         /*
153          * If the index or extents flag is set, then this is a bogus
154          * device/fifo/socket
155          */
156         if (inode->i_flags & (EXT2_INDEX_FL | EXT4_EXTENTS_FL))
157                 return 0;
158
159         /*
160          * We should be able to do the test below all the time, but
161          * because the kernel doesn't forcibly clear the device
162          * inode's additional i_block fields, there are some rare
163          * occasions when a legitimate device inode will have non-zero
164          * additional i_block fields.  So for now, we only complain
165          * when the immutable flag is set, which should never happen
166          * for devices.  (And that's when the problem is caused, since
167          * you can't set or clear immutable flags for devices.)  Once
168          * the kernel has been fixed we can change this...
169          */
170         if (inode->i_flags & (EXT2_IMMUTABLE_FL | EXT2_APPEND_FL)) {
171                 for (i=4; i < EXT2_N_BLOCKS; i++)
172                         if (inode->i_block[i])
173                                 return 0;
174         }
175         return 1;
176 }
177
178 /*
179  * Check to make sure a symlink inode is real.  Returns 1 if the symlink
180  * checks out, 0 if not.
181  */
182 static int check_symlink(e2fsck_t ctx, struct problem_context *pctx,
183                          ext2_ino_t ino, struct ext2_inode *inode, char *buf)
184 {
185         unsigned int buflen;
186         unsigned int len;
187         blk64_t blk;
188
189         if ((inode->i_size_high || inode->i_size == 0) ||
190             (inode->i_flags & EXT2_INDEX_FL))
191                 return 0;
192
193         if (inode->i_flags & EXT4_INLINE_DATA_FL) {
194                 size_t inline_size;
195
196                 if (inode->i_flags & EXT4_EXTENTS_FL)
197                         return 0;
198                 if (ext2fs_inline_data_size(ctx->fs, ino, &inline_size))
199                         return 0;
200                 if (inode->i_size != inline_size)
201                         return 0;
202
203                 return 1;
204         }
205
206         if (ext2fs_is_fast_symlink(inode)) {
207                 if (inode->i_flags & EXT4_EXTENTS_FL)
208                         return 0;
209                 buf = (char *)inode->i_block;
210                 buflen = sizeof(inode->i_block);
211         } else {
212                 ext2_extent_handle_t    handle;
213                 struct ext2_extent_info info;
214                 struct ext2fs_extent    extent;
215                 int i;
216
217                 if (inode->i_flags & EXT4_EXTENTS_FL) {
218                         if (ext2fs_extent_open2(ctx->fs, ino, inode, &handle))
219                                 return 0;
220                         if (ext2fs_extent_get_info(handle, &info) ||
221                             (info.num_entries != 1) ||
222                             (info.max_depth != 0)) {
223                                 ext2fs_extent_free(handle);
224                                 return 0;
225                         }
226                         if (ext2fs_extent_get(handle, EXT2_EXTENT_ROOT,
227                                               &extent) ||
228                             (extent.e_lblk != 0) ||
229                             (extent.e_len != 1)) {
230                                 ext2fs_extent_free(handle);
231                                 return 0;
232                         }
233                         blk = extent.e_pblk;
234                         ext2fs_extent_free(handle);
235                 } else {
236                         blk = inode->i_block[0];
237
238                         for (i = 1; i < EXT2_N_BLOCKS; i++)
239                                 if (inode->i_block[i])
240                                         return 0;
241                 }
242
243                 if (blk < ctx->fs->super->s_first_data_block ||
244                     blk >= ext2fs_blocks_count(ctx->fs->super))
245                         return 0;
246
247                 if (io_channel_read_blk64(ctx->fs->io, blk, 1, buf))
248                         return 0;
249
250                 buflen = ctx->fs->blocksize;
251         }
252
253         if (inode->i_flags & EXT4_ENCRYPT_FL)
254                 len = ext2fs_le16_to_cpu(*(__u16 *)buf) + 2;
255         else {
256                 len = strnlen(buf, buflen);
257
258                 /* Add missing NUL terminator at end of symlink (LU-1540),
259                  * but only offer to fix this in pass1, not from pass2. */
260                 if (len > inode->i_size && pctx != NULL &&
261                     fix_problem(ctx, PR_1_SYMLINK_NUL, pctx)) {
262                         buf[inode->i_size] = '\0';
263                         if (ext2fs_is_fast_symlink(inode)) {
264                                 e2fsck_write_inode(ctx, ino,
265                                                    inode, "check_ext_attr");
266                         } else {
267                                 if (io_channel_write_blk64(ctx->fs->io,
268                                                            blk, 1, buf))
269                                         return 0;
270                         }
271                         len = inode->i_size;
272                 }
273         }
274
275         if (len >= buflen)
276                 return 0;
277
278         if (len != inode->i_size)
279                 return 0;
280
281         return 1;
282 }
283
284 int e2fsck_pass1_check_symlink(e2fsck_t ctx, ext2_ino_t ino,
285                                struct ext2_inode *inode, char *buf)
286 {
287         return check_symlink(ctx, NULL, ino, inode, buf);
288 }
289
290 /*
291  * If the extents or inlinedata flags are set on the inode, offer to clear 'em.
292  */
293 #define BAD_SPECIAL_FLAGS (EXT4_EXTENTS_FL | EXT4_INLINE_DATA_FL)
294 static void check_extents_inlinedata(e2fsck_t ctx,
295                                      struct problem_context *pctx)
296 {
297         if (!(pctx->inode->i_flags & BAD_SPECIAL_FLAGS))
298                 return;
299
300         if (!fix_problem(ctx, PR_1_SPECIAL_EXTENTS_IDATA, pctx))
301                 return;
302
303         pctx->inode->i_flags &= ~BAD_SPECIAL_FLAGS;
304         e2fsck_write_inode(ctx, pctx->ino, pctx->inode, "pass1");
305 }
306 #undef BAD_SPECIAL_FLAGS
307
308 /*
309  * If the immutable (or append-only) flag is set on the inode, offer
310  * to clear it.
311  */
312 #define BAD_SPECIAL_FLAGS (EXT2_IMMUTABLE_FL | EXT2_APPEND_FL)
313 static void check_immutable(e2fsck_t ctx, struct problem_context *pctx)
314 {
315         if (!(pctx->inode->i_flags & BAD_SPECIAL_FLAGS))
316                 return;
317
318         if (!fix_problem(ctx, PR_1_SET_IMMUTABLE, pctx))
319                 return;
320
321         pctx->inode->i_flags &= ~BAD_SPECIAL_FLAGS;
322         e2fsck_write_inode(ctx, pctx->ino, pctx->inode, "pass1");
323 }
324
325 /*
326  * If device, fifo or socket, check size is zero -- if not offer to
327  * clear it
328  */
329 static void check_size(e2fsck_t ctx, struct problem_context *pctx)
330 {
331         struct ext2_inode *inode = pctx->inode;
332
333         if (EXT2_I_SIZE(inode) == 0)
334                 return;
335
336         if (!fix_problem(ctx, PR_1_SET_NONZSIZE, pctx))
337                 return;
338
339         ext2fs_inode_size_set(ctx->fs, inode, 0);
340         e2fsck_write_inode(ctx, pctx->ino, pctx->inode, "pass1");
341 }
342
343 /*
344  * For a given size, calculate how many blocks would be charged towards quota.
345  */
346 static blk64_t size_to_quota_blocks(ext2_filsys fs, size_t size)
347 {
348         blk64_t clusters;
349
350         clusters = DIV_ROUND_UP(size, fs->blocksize << fs->cluster_ratio_bits);
351         return EXT2FS_C2B(fs, clusters);
352 }
353
354 /*
355  * Check validity of EA inode. Return 0 if EA inode is valid, otherwise return
356  * the problem code.
357  */
358 static problem_t check_large_ea_inode(e2fsck_t ctx,
359                                       struct ext2_ext_attr_entry *entry,
360                                       struct problem_context *pctx,
361                                       blk64_t *quota_blocks)
362 {
363         struct ext2_inode inode;
364         __u32 hash;
365         errcode_t retval;
366
367         /* Check if inode is within valid range */
368         if ((entry->e_value_inum < EXT2_FIRST_INODE(ctx->fs->super)) ||
369             (entry->e_value_inum > ctx->fs->super->s_inodes_count)) {
370                 pctx->num = entry->e_value_inum;
371                 return PR_1_ATTR_VALUE_EA_INODE;
372         }
373
374         e2fsck_read_inode(ctx, entry->e_value_inum, &inode, "pass1");
375
376         retval = ext2fs_ext_attr_hash_entry2(ctx->fs, entry, NULL, &hash);
377         if (retval) {
378                 com_err("check_large_ea_inode", retval,
379                         _("while hashing entry with e_value_inum = %u"),
380                         entry->e_value_inum);
381                 fatal_error(ctx, 0);
382         }
383
384         if (hash == entry->e_hash) {
385                 *quota_blocks = size_to_quota_blocks(ctx->fs,
386                                                      entry->e_value_size);
387         } else {
388                 /* This might be an old Lustre-style ea_inode reference. */
389                 if (inode.i_mtime == pctx->ino &&
390                     inode.i_generation == pctx->inode->i_generation) {
391                         *quota_blocks = 0;
392                 } else {
393                         /* If target inode is also missing EA_INODE flag,
394                          * this is likely to be a bad reference.
395                          */
396                         if (!(inode.i_flags & EXT4_EA_INODE_FL)) {
397                                 pctx->num = entry->e_value_inum;
398                                 return PR_1_ATTR_VALUE_EA_INODE;
399                         } else {
400                                 pctx->num = entry->e_hash;
401                                 return PR_1_ATTR_HASH;
402                         }
403                 }
404         }
405
406         if (!(inode.i_flags & EXT4_EA_INODE_FL)) {
407                 pctx->num = entry->e_value_inum;
408                 if (fix_problem(ctx, PR_1_ATTR_SET_EA_INODE_FL, pctx)) {
409                         inode.i_flags |= EXT4_EA_INODE_FL;
410                         e2fsck_pass1_fix_lock(ctx);
411                         ext2fs_write_inode(ctx->fs, entry->e_value_inum,
412                                            &inode);
413                         e2fsck_pass1_fix_unlock(ctx);
414                 } else {
415                         return PR_1_ATTR_NO_EA_INODE_FL;
416                 }
417         }
418         return 0;
419 }
420
421 static void inc_ea_inode_refs(e2fsck_t ctx, struct problem_context *pctx,
422                               struct ext2_ext_attr_entry *first, void *end)
423 {
424         struct ext2_ext_attr_entry *entry;
425
426         for (entry = first;
427              (void *)entry < end && !EXT2_EXT_IS_LAST_ENTRY(entry);
428              entry = EXT2_EXT_ATTR_NEXT(entry)) {
429                 if (!entry->e_value_inum)
430                         continue;
431                 if (!ctx->ea_inode_refs) {
432                         pctx->errcode = ea_refcount_create(0,
433                                                            &ctx->ea_inode_refs);
434                         if (pctx->errcode) {
435                                 pctx->num = 4;
436                                 fix_problem(ctx, PR_1_ALLOCATE_REFCOUNT, pctx);
437                                 ctx->flags |= E2F_FLAG_ABORT;
438                                 return;
439                         }
440                 }
441                 ea_refcount_increment(ctx->ea_inode_refs, entry->e_value_inum,
442                                       0);
443         }
444 }
445
446 static void check_ea_in_inode(e2fsck_t ctx, struct problem_context *pctx,
447                               struct ea_quota *ea_ibody_quota)
448 {
449         struct ext2_super_block *sb = ctx->fs->super;
450         struct ext2_inode_large *inode;
451         struct ext2_ext_attr_entry *entry;
452         char *start, *header, *end;
453         unsigned int storage_size, remain;
454         problem_t problem = 0;
455         region_t region = 0;
456
457         ea_ibody_quota->blocks = 0;
458         ea_ibody_quota->inodes = 0;
459
460         inode = (struct ext2_inode_large *) pctx->inode;
461         storage_size = EXT2_INODE_SIZE(ctx->fs->super) -
462                 EXT2_GOOD_OLD_INODE_SIZE - inode->i_extra_isize;
463         header = ((char *) inode) + EXT2_GOOD_OLD_INODE_SIZE +
464                  inode->i_extra_isize;
465         end = header + storage_size;
466         entry = &IHDR(inode)->h_first_entry[0];
467         start = (char *)entry;
468
469         /* scan all entry's headers first */
470
471         /* take finish entry 0UL into account */
472         remain = storage_size - sizeof(__u32);
473
474         region = region_create(0, storage_size);
475         if (!region) {
476                 fix_problem(ctx, PR_1_EA_ALLOC_REGION_ABORT, pctx);
477                 problem = 0;
478                 ctx->flags |= E2F_FLAG_ABORT;
479                 return;
480         }
481         if (region_allocate(region, 0, sizeof(__u32))) {
482                 problem = PR_1_INODE_EA_ALLOC_COLLISION;
483                 goto fix;
484         }
485
486         while (remain >= sizeof(struct ext2_ext_attr_entry) &&
487                !EXT2_EXT_IS_LAST_ENTRY(entry)) {
488                 __u32 hash;
489
490                 if (region_allocate(region, (char *)entry - (char *)header,
491                                     EXT2_EXT_ATTR_LEN(entry->e_name_len))) {
492                         problem = PR_1_INODE_EA_ALLOC_COLLISION;
493                         goto fix;
494                 }
495
496                 /* header eats this space */
497                 remain -= sizeof(struct ext2_ext_attr_entry);
498
499                 /* is attribute name valid? */
500                 if (EXT2_EXT_ATTR_SIZE(entry->e_name_len) > remain) {
501                         pctx->num = entry->e_name_len;
502                         problem = PR_1_ATTR_NAME_LEN;
503                         goto fix;
504                 }
505
506                 /* attribute len eats this space */
507                 remain -= EXT2_EXT_ATTR_SIZE(entry->e_name_len);
508
509                 if (entry->e_value_inum == 0) {
510                         /* check value size */
511                         if (entry->e_value_size > remain) {
512                                 pctx->num = entry->e_value_size;
513                                 problem = PR_1_ATTR_VALUE_SIZE;
514                                 goto fix;
515                         }
516
517                         if (entry->e_value_size &&
518                             region_allocate(region,
519                                             sizeof(__u32) + entry->e_value_offs,
520                                             EXT2_EXT_ATTR_SIZE(
521                                                 entry->e_value_size))) {
522                                 problem = PR_1_INODE_EA_ALLOC_COLLISION;
523                                 goto fix;
524                         }
525
526                         hash = ext2fs_ext_attr_hash_entry(entry,
527                                                           start + entry->e_value_offs);
528
529                         /* e_hash may be 0 in older inode's ea */
530                         if (entry->e_hash != 0 && entry->e_hash != hash) {
531                                 pctx->num = entry->e_hash;
532                                 problem = PR_1_ATTR_HASH;
533                                 goto fix;
534                         }
535                 } else {
536                         blk64_t quota_blocks;
537
538                         problem = check_large_ea_inode(ctx, entry, pctx,
539                                                        &quota_blocks);
540                         if (problem != 0)
541                                 goto fix;
542
543                         ea_ibody_quota->blocks += quota_blocks;
544                         ea_ibody_quota->inodes++;
545                 }
546
547                 /* If EA value is stored in external inode then it does not
548                  * consume space here */
549                 if (entry->e_value_inum == 0)
550                         remain -= entry->e_value_size;
551
552                 entry = EXT2_EXT_ATTR_NEXT(entry);
553         }
554
555         if (region_allocate(region, (char *)entry - (char *)header,
556                             sizeof(__u32))) {
557                 problem = PR_1_INODE_EA_ALLOC_COLLISION;
558                 goto fix;
559         }
560 fix:
561         if (region)
562                 region_free(region);
563         /*
564          * it seems like a corruption. it's very unlikely we could repair
565          * EA(s) in automatic fashion -bzzz
566          */
567         if (problem == 0 || !fix_problem(ctx, problem, pctx)) {
568                 inc_ea_inode_refs(ctx, pctx,
569                                   (struct ext2_ext_attr_entry *)start, end);
570                 return;
571         }
572
573         /* simply remove all possible EA(s) */
574         *((__u32 *)header) = 0UL;
575         e2fsck_write_inode_full(ctx, pctx->ino, pctx->inode,
576                                 EXT2_INODE_SIZE(sb), "pass1");
577         ea_ibody_quota->blocks = 0;
578         ea_ibody_quota->inodes = 0;
579 }
580
581 static int check_inode_extra_negative_epoch(__u32 xtime, __u32 extra) {
582         return (xtime & (1U << 31)) != 0 &&
583                 (extra & EXT4_EPOCH_MASK) == EXT4_EPOCH_MASK;
584 }
585
586 #define CHECK_INODE_EXTRA_NEGATIVE_EPOCH(inode, xtime) \
587         check_inode_extra_negative_epoch(inode->i_##xtime, \
588                                          inode->i_##xtime##_extra)
589
590 /* When today's date is earlier than 2242, we assume that atimes,
591  * ctimes, crtimes, and mtimes with years in the range 2310..2378 are
592  * actually pre-1970 dates mis-encoded.
593  */
594 #define EXT4_EXTRA_NEGATIVE_DATE_CUTOFF 2 * (1LL << 32)
595
596 static void check_inode_extra_space(e2fsck_t ctx, struct problem_context *pctx,
597                                     struct ea_quota *ea_ibody_quota)
598 {
599         struct ext2_super_block *sb = ctx->fs->super;
600         struct ext2_inode_large *inode;
601         __u32 *eamagic;
602         int min, max, dirty = 0;
603
604         ea_ibody_quota->blocks = 0;
605         ea_ibody_quota->inodes = 0;
606
607         inode = (struct ext2_inode_large *) pctx->inode;
608         if (EXT2_INODE_SIZE(sb) == EXT2_GOOD_OLD_INODE_SIZE) {
609                 /* this isn't large inode. so, nothing to check */
610                 return;
611         }
612
613 #if 0
614         printf("inode #%u, i_extra_size %d\n", pctx->ino,
615                         inode->i_extra_isize);
616 #endif
617         /* i_extra_isize must cover i_extra_isize + i_checksum_hi at least */
618         min = sizeof(inode->i_extra_isize) + sizeof(inode->i_checksum_hi);
619         max = EXT2_INODE_SIZE(sb) - EXT2_GOOD_OLD_INODE_SIZE;
620         /*
621          * For now we will allow i_extra_isize to be 0, but really
622          * implementations should never allow i_extra_isize to be 0
623          */
624         if (inode->i_extra_isize &&
625             (inode->i_extra_isize < min || inode->i_extra_isize > max ||
626              inode->i_extra_isize & 3)) {
627                 if (!fix_problem(ctx, PR_1_EXTRA_ISIZE, pctx))
628                         return;
629                 if (inode->i_extra_isize < min || inode->i_extra_isize > max)
630                         inode->i_extra_isize = ctx->want_extra_isize;
631                 else
632                         inode->i_extra_isize = (inode->i_extra_isize + 3) & ~3;
633                 dirty = 1;
634
635                 goto out;
636         }
637
638         /* check if there is no place for an EA header */
639         if (inode->i_extra_isize >= max - sizeof(__u32))
640                 return;
641
642         eamagic = &IHDR(inode)->h_magic;
643         if (*eamagic != EXT2_EXT_ATTR_MAGIC &&
644             (ctx->flags & E2F_FLAG_EXPAND_EISIZE) &&
645             (inode->i_extra_isize < ctx->want_extra_isize)) {
646                 fix_problem(ctx, PR_1_EXPAND_EISIZE, pctx);
647                 memset((char *)inode + EXT2_GOOD_OLD_INODE_SIZE, 0,
648                         EXT2_INODE_SIZE(sb) - EXT2_GOOD_OLD_INODE_SIZE);
649                 inode->i_extra_isize = ctx->want_extra_isize;
650                 dirty = 1;
651                 if (inode->i_extra_isize < ctx->min_extra_isize)
652                         ctx->min_extra_isize = inode->i_extra_isize;
653         }
654
655         if (*eamagic == EXT2_EXT_ATTR_MAGIC)
656                 check_ea_in_inode(ctx, pctx, ea_ibody_quota);
657
658         if (EXT4_XTIME_FUTURE(ctx, sb, inode->i_crtime, ctx->time_fudge))
659                 e2fsck_mark_inode_bad(ctx, pctx, PR_1_CRTIME_BAD);
660         else if (EXT4_XTIME_ANCIENT(ctx, sb, inode->i_crtime, ctx->time_fudge))
661                 e2fsck_mark_inode_bad(ctx, pctx, PR_1_CRTIME_BAD);
662         /*
663          * If the inode's extended atime (ctime, crtime, mtime) is stored in
664          * the old, invalid format, repair it.
665          */
666         if (((sizeof(time_t) <= 4) ||
667              (((sizeof(time_t) > 4) &&
668                ctx->now < EXT4_EXTRA_NEGATIVE_DATE_CUTOFF))) &&
669             (CHECK_INODE_EXTRA_NEGATIVE_EPOCH(inode, atime) ||
670              CHECK_INODE_EXTRA_NEGATIVE_EPOCH(inode, ctime) ||
671              CHECK_INODE_EXTRA_NEGATIVE_EPOCH(inode, crtime) ||
672              CHECK_INODE_EXTRA_NEGATIVE_EPOCH(inode, mtime))) {
673
674                 if (!fix_problem_bad(ctx, PR_1_EA_TIME_OUT_OF_RANGE, pctx, 2))
675                         return;
676
677                 if (CHECK_INODE_EXTRA_NEGATIVE_EPOCH(inode, atime))
678                         inode->i_atime_extra &= ~EXT4_EPOCH_MASK;
679                 if (CHECK_INODE_EXTRA_NEGATIVE_EPOCH(inode, ctime))
680                         inode->i_ctime_extra &= ~EXT4_EPOCH_MASK;
681                 if (CHECK_INODE_EXTRA_NEGATIVE_EPOCH(inode, crtime))
682                         inode->i_crtime_extra &= ~EXT4_EPOCH_MASK;
683                 if (CHECK_INODE_EXTRA_NEGATIVE_EPOCH(inode, mtime))
684                         inode->i_mtime_extra &= ~EXT4_EPOCH_MASK;
685                 dirty = 1;
686         }
687
688 out:
689         if (dirty)
690                 e2fsck_write_inode_full(ctx, pctx->ino, pctx->inode,
691                                         EXT2_INODE_SIZE(sb), "pass1");
692 }
693
694 static _INLINE_ int is_blocks_used(e2fsck_t ctx, blk64_t block,
695                                    unsigned int num)
696 {
697         int retval;
698
699         /* used to avoid duplicate output from below */
700         retval = ext2fs_test_block_bitmap_range2_valid(ctx->block_found_map,
701                                                        block, num);
702         if (!retval)
703                 return 0;
704
705         retval = ext2fs_test_block_bitmap_range2(ctx->block_found_map, block, num);
706         if (retval) {
707                 e2fsck_pass1_block_map_r_lock(ctx);
708                 if (ctx->global_ctx)
709                         retval = ext2fs_test_block_bitmap_range2(
710                                         ctx->global_ctx->block_found_map, block, num);
711                 e2fsck_pass1_block_map_r_unlock(ctx);
712                 if (retval)
713                         return 0;
714         }
715
716         return 1;
717 }
718
719 /*
720  * Check to see if the inode might really be a directory, despite i_mode
721  *
722  * This is a lot of complexity for something for which I'm not really
723  * convinced happens frequently in the wild.  If for any reason this
724  * causes any problems, take this code out.
725  * [tytso:20070331.0827EDT]
726  */
727 static void check_is_really_dir(e2fsck_t ctx, struct problem_context *pctx,
728                                 char *buf)
729 {
730         struct ext2_inode *inode = pctx->inode;
731         struct ext2_dir_entry   *dirent;
732         errcode_t               retval;
733         blk64_t                 blk;
734         unsigned int            i, rec_len, not_device = 0;
735         int                     extent_fs;
736         int                     inlinedata_fs;
737
738         /*
739          * If the mode looks OK, we believe it.  If the first block in
740          * the i_block array is 0, this cannot be a directory. If the
741          * inode is extent-mapped, it is still the case that the latter
742          * cannot be 0 - the magic number in the extent header would make
743          * it nonzero.
744          */
745         if (LINUX_S_ISDIR(inode->i_mode) || LINUX_S_ISREG(inode->i_mode) ||
746             LINUX_S_ISLNK(inode->i_mode) || inode->i_block[0] == 0)
747                 return;
748
749         /*
750          * Check the block numbers in the i_block array for validity:
751          * zero blocks are skipped (but the first one cannot be zero -
752          * see above), other blocks are checked against the first and
753          * max data blocks (from the the superblock) and against the
754          * block bitmap. Any invalid block found means this cannot be
755          * a directory.
756          *
757          * If there are non-zero blocks past the fourth entry, then
758          * this cannot be a device file: we remember that for the next
759          * check.
760          *
761          * For extent mapped files, we don't do any sanity checking:
762          * just try to get the phys block of logical block 0 and run
763          * with it.
764          *
765          * For inline data files, we just try to get the size of inline
766          * data.  If it's true, we will treat it as a directory.
767          */
768
769         extent_fs = ext2fs_has_feature_extents(ctx->fs->super);
770         inlinedata_fs = ext2fs_has_feature_inline_data(ctx->fs->super);
771         if (inlinedata_fs && (inode->i_flags & EXT4_INLINE_DATA_FL)) {
772                 size_t size;
773                 __u32 dotdot;
774                 unsigned int rec_len2;
775                 struct ext2_dir_entry de;
776
777                 if (ext2fs_inline_data_size(ctx->fs, pctx->ino, &size))
778                         return;
779                 /*
780                  * If the size isn't a multiple of 4, it's probably not a
781                  * directory??
782                  */
783                 if (size & 3)
784                         return;
785                 /*
786                  * If the first 10 bytes don't look like a directory entry,
787                  * it's probably not a directory.
788                  */
789                 memcpy(&dotdot, inode->i_block, sizeof(dotdot));
790                 memcpy(&de, ((char *)inode->i_block) + EXT4_INLINE_DATA_DOTDOT_SIZE,
791                        EXT2_DIR_NAME_LEN(0));
792                 dotdot = ext2fs_le32_to_cpu(dotdot);
793                 de.inode = ext2fs_le32_to_cpu(de.inode);
794                 de.rec_len = ext2fs_le16_to_cpu(de.rec_len);
795                 ext2fs_get_rec_len(ctx->fs, &de, &rec_len2);
796                 if (dotdot >= ctx->fs->super->s_inodes_count ||
797                     (dotdot < EXT2_FIRST_INO(ctx->fs->super) &&
798                      dotdot != EXT2_ROOT_INO) ||
799                     de.inode >= ctx->fs->super->s_inodes_count ||
800                     (de.inode < EXT2_FIRST_INO(ctx->fs->super) &&
801                      de.inode != 0) ||
802                     rec_len2 > EXT4_MIN_INLINE_DATA_SIZE -
803                               EXT4_INLINE_DATA_DOTDOT_SIZE)
804                         return;
805                 /* device files never have a "system.data" entry */
806                 goto isdir;
807         } else if (extent_fs && (inode->i_flags & EXT4_EXTENTS_FL)) {
808                 /* extent mapped */
809                 if  (ext2fs_bmap2(ctx->fs, pctx->ino, inode, 0, 0, 0, 0,
810                                  &blk))
811                         return;
812                 /* device files are never extent mapped */
813                 not_device++;
814         } else {
815                 for (i=0; i < EXT2_N_BLOCKS; i++) {
816                         blk = inode->i_block[i];
817                         if (!blk)
818                                 continue;
819                         if (i >= 4)
820                                 not_device++;
821
822                         if (blk < ctx->fs->super->s_first_data_block ||
823                             blk >= ext2fs_blocks_count(ctx->fs->super) ||
824                             is_blocks_used(ctx, blk, 1))
825                                 return; /* Invalid block, can't be dir */
826                 }
827                 blk = inode->i_block[0];
828         }
829
830         /*
831          * If the mode says this is a device file and the i_links_count field
832          * is sane and we have not ruled it out as a device file previously,
833          * we declare it a device file, not a directory.
834          */
835         if ((LINUX_S_ISCHR(inode->i_mode) || LINUX_S_ISBLK(inode->i_mode)) &&
836             (inode->i_links_count == 1) && !not_device)
837                 return;
838
839         /* read the first block */
840         ehandler_operation(_("reading directory block"));
841         retval = ext2fs_read_dir_block4(ctx->fs, blk, buf, 0, pctx->ino);
842         ehandler_operation(0);
843         if (retval)
844                 return;
845
846         dirent = (struct ext2_dir_entry *) buf;
847         retval = ext2fs_get_rec_len(ctx->fs, dirent, &rec_len);
848         if (retval)
849                 return;
850         if ((ext2fs_dirent_name_len(dirent) != 1) ||
851             (dirent->name[0] != '.') ||
852             (dirent->inode != pctx->ino) ||
853             (rec_len < 12) ||
854             (rec_len % 4) ||
855             (rec_len >= ctx->fs->blocksize - 12))
856                 return;
857
858         dirent = (struct ext2_dir_entry *) (buf + rec_len);
859         retval = ext2fs_get_rec_len(ctx->fs, dirent, &rec_len);
860         if (retval)
861                 return;
862         if ((ext2fs_dirent_name_len(dirent) != 2) ||
863             (dirent->name[0] != '.') ||
864             (dirent->name[1] != '.') ||
865             (rec_len < 12) ||
866             (rec_len % 4))
867                 return;
868
869 isdir:
870         if (fix_problem(ctx, PR_1_TREAT_AS_DIRECTORY, pctx)) {
871                 inode->i_mode = (inode->i_mode & 07777) | LINUX_S_IFDIR;
872                 e2fsck_write_inode_full(ctx, pctx->ino, inode,
873                                         EXT2_INODE_SIZE(ctx->fs->super),
874                                         "check_is_really_dir");
875         }
876 }
877
878 extern errcode_t e2fsck_setup_icount(e2fsck_t ctx, const char *icount_name,
879                                      int flags, ext2_icount_t hint,
880                                      ext2_icount_t *ret)
881 {
882         unsigned int            threshold;
883         unsigned int            save_type;
884         ext2_ino_t              num_dirs;
885         errcode_t               retval;
886         char                    *tdb_dir;
887         int                     enable;
888
889         *ret = 0;
890
891         profile_get_string(ctx->profile, "scratch_files", "directory", 0, 0,
892                            &tdb_dir);
893         profile_get_uint(ctx->profile, "scratch_files",
894                          "numdirs_threshold", 0, 0, &threshold);
895         profile_get_boolean(ctx->profile, "scratch_files",
896                             "icount", 0, 1, &enable);
897
898         retval = ext2fs_get_num_dirs(ctx->fs, &num_dirs);
899         if (retval)
900                 num_dirs = 1024;        /* Guess */
901
902         if (enable && tdb_dir && !access(tdb_dir, W_OK) &&
903             (!threshold || num_dirs > threshold)) {
904                 retval = ext2fs_create_icount_tdb(ctx->fs, tdb_dir,
905                                                   flags, ret);
906                 if (retval == 0)
907                         return 0;
908         }
909         e2fsck_set_bitmap_type(ctx->fs, EXT2FS_BMAP64_RBTREE, icount_name,
910                                &save_type);
911         if (ctx->options & E2F_OPT_ICOUNT_FULLMAP)
912                 flags |= EXT2_ICOUNT_OPT_FULLMAP;
913         retval = ext2fs_create_icount2(ctx->fs, flags, 0, hint, ret);
914         ctx->fs->default_bitmap_type = save_type;
915         return retval;
916 }
917
918 static errcode_t recheck_bad_inode_checksum(ext2_filsys fs, ext2_ino_t ino,
919                                             e2fsck_t ctx,
920                                             struct problem_context *pctx)
921 {
922         errcode_t retval;
923         struct ext2_inode_large inode;
924
925         /*
926          * Reread inode.  If we don't see checksum error, then this inode
927          * has been fixed elsewhere.
928          */
929         ctx->stashed_ino = 0;
930         retval = ext2fs_read_inode_full(fs, ino, (struct ext2_inode *)&inode,
931                                         sizeof(inode));
932         if (retval && retval != EXT2_ET_INODE_CSUM_INVALID)
933                 return retval;
934         if (!retval)
935                 return 0;
936
937         /*
938          * Checksum still doesn't match.  That implies that the inode passes
939          * all the sanity checks, so maybe the checksum is simply corrupt.
940          * See if the user will go for fixing that.
941          */
942         if (!fix_problem(ctx, PR_1_INODE_ONLY_CSUM_INVALID, pctx))
943                 return 0;
944
945
946         e2fsck_pass1_fix_lock(ctx);
947         retval = ext2fs_write_inode_full(fs, ino, (struct ext2_inode *)&inode,
948                                          sizeof(inode));
949         e2fsck_pass1_fix_unlock(ctx);
950         return retval;
951 }
952
953 int e2fsck_pass1_delete_attr(e2fsck_t ctx, struct ext2_inode_large *inode,
954                              struct problem_context *pctx, int needed_size)
955 {
956         struct ext2_ext_attr_header *header;
957         struct ext2_ext_attr_entry *entry_ino, *entry_blk = NULL, *entry;
958         char *start, name[4096], block_buf[4096];
959         int len, index = EXT2_ATTR_INDEX_USER, entry_size, ea_size;
960         int in_inode = 1, error;
961         unsigned int freed_bytes = inode->i_extra_isize;
962
963         entry_ino = &IHDR(inode)->h_first_entry[0];
964         start = (char *)entry_ino;
965
966         if (inode->i_file_acl) {
967                 error = ext2fs_read_ext_attr(ctx->fs, inode->i_file_acl,
968                                              block_buf);
969                 /* We have already checked this block, shouldn't happen */
970                 if (error) {
971                         fix_problem(ctx, PR_1_EXTATTR_READ_ABORT, pctx);
972                         return 0;
973                 }
974                 header = BHDR(block_buf);
975                 if (header->h_magic != EXT2_EXT_ATTR_MAGIC) {
976                         fix_problem(ctx, PR_1_EXTATTR_READ_ABORT, pctx);
977                         return 0;
978                 }
979
980                 entry_blk = (struct ext2_ext_attr_entry *)(header+1);
981         }
982         entry = entry_ino;
983         len = sizeof(entry->e_name);
984         entry_size = ext2fs_attr_get_next_attr(entry, index, name, len, 1);
985
986         while (freed_bytes < needed_size) {
987                 if (entry_size && name[0] != '\0') {
988                         pctx->str = name;
989                         if (fix_problem(ctx, PR_1_EISIZE_DELETE_EA, pctx)) {
990                                 ea_size = EXT2_EXT_ATTR_LEN(entry->e_name_len) +
991                                           EXT2_EXT_ATTR_SIZE(entry->e_value_size);
992                                 error = ext2fs_attr_set(ctx->fs, pctx->ino,
993                                                         (struct ext2_inode *)inode,
994                                                         index, name, 0, 0, 0);
995                                 if (!error)
996                                         freed_bytes += ea_size;
997                         }
998                 }
999                 len = sizeof(entry->e_name);
1000                 entry_size = ext2fs_attr_get_next_attr(entry, index,name,len,0);
1001                 entry = EXT2_EXT_ATTR_NEXT(entry);
1002                 if (EXT2_EXT_IS_LAST_ENTRY(entry)) {
1003                         if (in_inode) {
1004                                 entry = entry_blk;
1005                                 len = sizeof(entry->e_name);
1006                                 entry_size = ext2fs_attr_get_next_attr(entry,
1007                                                         index, name, len, 1);
1008                                 in_inode = 0;
1009                         } else {
1010                                 index += 1;
1011                                 in_inode = 1;
1012                                 if (!entry && index < EXT2_ATTR_INDEX_MAX)
1013                                         entry = (struct ext2_ext_attr_entry *)start;
1014                                 else
1015                                         return freed_bytes;
1016                         }
1017                 }
1018         }
1019
1020         return freed_bytes;
1021 }
1022
1023 int e2fsck_pass1_expand_eisize(e2fsck_t ctx, struct ext2_inode_large *inode,
1024                                struct problem_context *pctx)
1025 {
1026         int needed_size = 0, retval, ret = EXT2_EXPAND_EISIZE_UNSAFE;
1027         static int message;
1028
1029 retry:
1030         retval = ext2fs_expand_extra_isize(ctx->fs, pctx->ino, inode,
1031                                            ctx->want_extra_isize, &ret,
1032                                            &needed_size);
1033         if (ret & EXT2_EXPAND_EISIZE_NEW_BLOCK)
1034                 goto mark_expand_eisize_map;
1035         if (!retval) {
1036                 e2fsck_write_inode_full(ctx, pctx->ino,
1037                                         (struct ext2_inode *)inode,
1038                                         EXT2_INODE_SIZE(ctx->fs->super),
1039                                         "pass1");
1040                 return 0;
1041         }
1042
1043         if (ret & EXT2_EXPAND_EISIZE_NOSPC) {
1044                 if (ctx->options & (E2F_OPT_PREEN | E2F_OPT_YES)) {
1045                         fix_problem(ctx, PR_1_EA_BLK_NOSPC, pctx);
1046                         ctx->flags |= E2F_FLAG_ABORT;
1047                         return -1;
1048                 }
1049
1050                 if (!message) {
1051                         pctx->num = ctx->fs->super->s_min_extra_isize;
1052                         fix_problem(ctx, PR_1_EXPAND_EISIZE_WARNING, pctx);
1053                         message = 1;
1054                 }
1055 delete_EA:
1056                 retval = e2fsck_pass1_delete_attr(ctx, inode, pctx,
1057                                                   needed_size);
1058                 if (retval >= ctx->want_extra_isize)
1059                         goto retry;
1060
1061                 needed_size -= retval;
1062
1063                 /*
1064                  * We loop here until either the user deletes EA(s) or
1065                  * EXTRA_ISIZE feature is disabled.
1066                  */
1067                 if (fix_problem(ctx, PR_1_CLEAR_EXTRA_ISIZE, pctx)) {
1068                         ctx->fs->super->s_feature_ro_compat &=
1069                                         ~EXT4_FEATURE_RO_COMPAT_EXTRA_ISIZE;
1070                         ext2fs_mark_super_dirty(ctx->fs);
1071                 } else {
1072                         goto delete_EA;
1073                 }
1074                 ctx->fs_unexpanded_inodes++;
1075
1076                 /* No EA was deleted, inode cannot be expanded */
1077                 return -1;
1078         }
1079
1080 mark_expand_eisize_map:
1081         if (!ctx->expand_eisize_map) {
1082                 pctx->errcode = ext2fs_allocate_inode_bitmap(ctx->fs,
1083                                          _("expand extrz isize map"),
1084                                          &ctx->expand_eisize_map);
1085                 if (pctx->errcode) {
1086                         fix_problem(ctx, PR_1_ALLOCATE_IBITMAP_ERROR,
1087                                     pctx);
1088                         exit(1);
1089                 }
1090         }
1091
1092         /* Add this inode to the expand_eisize_map */
1093         ext2fs_mark_inode_bitmap2(ctx->expand_eisize_map, pctx->ino);
1094         return 0;
1095 }
1096
1097 static void reserve_block_for_root_repair(e2fsck_t ctx)
1098 {
1099         blk64_t         blk = 0;
1100         errcode_t       err;
1101         ext2_filsys     fs = ctx->fs;
1102
1103         ctx->root_repair_block = 0;
1104         if (ext2fs_test_inode_bitmap2(ctx->inode_used_map, EXT2_ROOT_INO))
1105                 return;
1106
1107         err = ext2fs_new_block2(fs, 0, ctx->block_found_map, &blk);
1108         if (err)
1109                 return;
1110         ext2fs_mark_block_bitmap2(ctx->block_found_map, blk);
1111         ctx->root_repair_block = blk;
1112 }
1113
1114 static void reserve_block_for_lnf_repair(e2fsck_t ctx)
1115 {
1116         blk64_t         blk = 0;
1117         errcode_t       err;
1118         ext2_filsys     fs = ctx->fs;
1119         static const char name[] = "lost+found";
1120         ext2_ino_t      ino;
1121
1122         ctx->lnf_repair_block = 0;
1123         if (!ext2fs_lookup(fs, EXT2_ROOT_INO, name, sizeof(name)-1, 0, &ino))
1124                 return;
1125
1126         err = ext2fs_new_block2(fs, 0, ctx->block_found_map, &blk);
1127         if (err)
1128                 return;
1129         ext2fs_mark_block_bitmap2(ctx->block_found_map, blk);
1130         ctx->lnf_repair_block = blk;
1131         return;
1132 }
1133
1134 static errcode_t get_inline_data_ea_size(ext2_filsys fs, ext2_ino_t ino,
1135                                          size_t *sz)
1136 {
1137         void *p;
1138         struct ext2_xattr_handle *handle;
1139         errcode_t retval;
1140
1141         retval = ext2fs_xattrs_open(fs, ino, &handle);
1142         if (retval)
1143                 return retval;
1144
1145         retval = ext2fs_xattrs_read(handle);
1146         if (retval)
1147                 goto err;
1148
1149         retval = ext2fs_xattr_get(handle, "system.data", &p, sz);
1150         if (retval)
1151                 goto err;
1152         ext2fs_free_mem(&p);
1153 err:
1154         (void) ext2fs_xattrs_close(&handle);
1155         return retval;
1156 }
1157
1158 int e2fsck_fix_bad_inode(e2fsck_t ctx, struct problem_context *pctx)
1159 {
1160         __u16 badness;
1161         int rc = 0;
1162
1163         if (!ctx->inode_badness)
1164                 return 0;
1165
1166         if (ext2fs_icount_fetch(ctx->inode_badness, pctx->ino, &badness))
1167                 return 0;
1168
1169         if ((badness & ~BADNESS_BAD_MODE) > ctx->inode_badness_threshold) {
1170                 __u64 pctx_num_sav = pctx->num;
1171
1172                 pctx->num = badness;
1173                 rc = fix_problem_bad(ctx, PR_1B_INODE_TOOBAD, pctx, 0);
1174                 pctx->num = pctx_num_sav;
1175         }
1176
1177         return rc;
1178 }
1179
1180 static void finish_processing_inode(e2fsck_t ctx, ext2_ino_t ino,
1181                                     struct problem_context *pctx,
1182                                     int failed_csum)
1183 {
1184         if (!failed_csum)
1185                 return;
1186
1187         /*
1188          * If the inode failed the checksum and the user didn't
1189          * clear the inode, test the checksum again -- if it still
1190          * fails, ask the user if the checksum should be corrected.
1191          */
1192         pctx->errcode = recheck_bad_inode_checksum(ctx->fs, ino, ctx, pctx);
1193         if (pctx->errcode)
1194                 ctx->flags |= E2F_FLAG_ABORT;
1195 }
1196 #define FINISH_INODE_LOOP(ctx, ino, pctx, failed_csum) \
1197         do { \
1198                 finish_processing_inode((ctx), (ino), (pctx), (failed_csum)); \
1199                 if (e2fsck_should_abort(ctx)) { \
1200                         e2fsck_pass1_check_unlock(ctx); \
1201                         return; \
1202                 } \
1203         } while (0)
1204
1205 static int could_be_block_map(ext2_filsys fs, struct ext2_inode *inode)
1206 {
1207         __u32 x;
1208         int i;
1209
1210         for (i = 0; i < EXT2_N_BLOCKS; i++) {
1211                 x = inode->i_block[i];
1212 #ifdef WORDS_BIGENDIAN
1213                 x = ext2fs_swab32(x);
1214 #endif
1215                 if (x >= ext2fs_blocks_count(fs->super))
1216                         return 0;
1217         }
1218
1219         return 1;
1220 }
1221
1222 /*
1223  * Figure out what to do with an inode that has both extents and inline data
1224  * inode flags set.  Returns -1 if we decide to erase the inode, 0 otherwise.
1225  */
1226 static int fix_inline_data_extents_file(e2fsck_t ctx,
1227                                         ext2_ino_t ino,
1228                                         struct ext2_inode *inode,
1229                                         int inode_size,
1230                                         struct problem_context *pctx)
1231 {
1232         size_t max_inline_ea_size;
1233         ext2_filsys fs = ctx->fs;
1234         int dirty = 0;
1235
1236         /* Both feature flags not set?  Just run the regular checks */
1237         if (!ext2fs_has_feature_extents(fs->super) &&
1238             !ext2fs_has_feature_inline_data(fs->super))
1239                 return 0;
1240
1241         /* Clear both flags if it's a special file */
1242         if (LINUX_S_ISCHR(inode->i_mode) ||
1243             LINUX_S_ISBLK(inode->i_mode) ||
1244             LINUX_S_ISFIFO(inode->i_mode) ||
1245             LINUX_S_ISSOCK(inode->i_mode)) {
1246                 check_extents_inlinedata(ctx, pctx);
1247                 return 0;
1248         }
1249
1250         /* If it looks like an extent tree, try to clear inlinedata */
1251         if (ext2fs_extent_header_verify(inode->i_block,
1252                                  sizeof(inode->i_block)) == 0 &&
1253             fix_problem(ctx, PR_1_CLEAR_INLINE_DATA_FOR_EXTENT, pctx)) {
1254                 inode->i_flags &= ~EXT4_INLINE_DATA_FL;
1255                 dirty = 1;
1256                 goto out;
1257         }
1258
1259         /* If it looks short enough to be inline data, try to clear extents */
1260         if (inode_size > EXT2_GOOD_OLD_INODE_SIZE)
1261                 max_inline_ea_size = inode_size -
1262                                      (EXT2_GOOD_OLD_INODE_SIZE +
1263                                       ((struct ext2_inode_large *)inode)->i_extra_isize);
1264         else
1265                 max_inline_ea_size = 0;
1266         if (EXT2_I_SIZE(inode) <
1267             EXT4_MIN_INLINE_DATA_SIZE + max_inline_ea_size &&
1268             fix_problem(ctx, PR_1_CLEAR_EXTENT_FOR_INLINE_DATA, pctx)) {
1269                 inode->i_flags &= ~EXT4_EXTENTS_FL;
1270                 dirty = 1;
1271                 goto out;
1272         }
1273
1274         /*
1275          * Too big for inline data, but no evidence of extent tree -
1276          * maybe it's a block map file?  If the mappings all look valid?
1277          */
1278         if (could_be_block_map(fs, inode) &&
1279             fix_problem(ctx, PR_1_CLEAR_EXTENT_INLINE_DATA_FLAGS, pctx)) {
1280 #ifdef WORDS_BIGENDIAN
1281                 int i;
1282
1283                 for (i = 0; i < EXT2_N_BLOCKS; i++)
1284                         inode->i_block[i] = ext2fs_swab32(inode->i_block[i]);
1285 #endif
1286
1287                 inode->i_flags &= ~(EXT4_EXTENTS_FL | EXT4_INLINE_DATA_FL);
1288                 dirty = 1;
1289                 goto out;
1290         }
1291
1292         /* Oh well, just clear the busted inode. */
1293         if (fix_problem(ctx, PR_1_CLEAR_EXTENT_INLINE_DATA_INODE, pctx)) {
1294                 e2fsck_clear_inode(ctx, ino, inode, 0, "pass1");
1295                 return -1;
1296         }
1297
1298 out:
1299         if (dirty)
1300                 e2fsck_write_inode(ctx, ino, inode, "pass1");
1301
1302         return 0;
1303 }
1304
1305 static void pass1_readahead(e2fsck_t ctx, dgrp_t *group, ext2_ino_t *next_ino)
1306 {
1307         ext2_ino_t inodes_in_group = 0, inodes_per_block, inodes_per_buffer;
1308         dgrp_t start = *group, grp, grp_end = ctx->fs->group_desc_count;
1309         blk64_t blocks_to_read = 0;
1310         errcode_t err = EXT2_ET_INVALID_ARGUMENT;
1311
1312 #ifdef HAVE_PTHREAD
1313         if (ctx->fs->fs_num_threads > 1)
1314                 grp_end = ctx->thread_info.et_group_end;
1315 #endif
1316         if (ctx->readahead_kb == 0)
1317                 goto out;
1318
1319         /* Keep iterating groups until we have enough to readahead */
1320         inodes_per_block = EXT2_INODES_PER_BLOCK(ctx->fs->super);
1321         for (grp = start; grp < grp_end; grp++) {
1322                 if (ext2fs_bg_flags_test(ctx->fs, grp, EXT2_BG_INODE_UNINIT))
1323                         continue;
1324                 inodes_in_group = ctx->fs->super->s_inodes_per_group -
1325                                         ext2fs_bg_itable_unused(ctx->fs, grp);
1326                 blocks_to_read += (inodes_in_group + inodes_per_block - 1) /
1327                                         inodes_per_block;
1328                 if (blocks_to_read * ctx->fs->blocksize >
1329                     ctx->readahead_kb * 1024)
1330                         break;
1331         }
1332
1333         err = e2fsck_readahead(ctx->fs, E2FSCK_READA_ITABLE, start,
1334                                grp - start + 1);
1335         if (err == EAGAIN) {
1336                 ctx->readahead_kb /= 2;
1337                 err = 0;
1338         }
1339
1340 out:
1341         if (err) {
1342                 /* Error; disable itable readahead */
1343                 *group = ctx->fs->group_desc_count;
1344                 *next_ino = ctx->fs->super->s_inodes_count;
1345         } else {
1346                 /*
1347                  * Don't do more readahead until we've reached the first inode
1348                  * of the last inode scan buffer block for the last group.
1349                  */
1350                 *group = grp + 1;
1351                 inodes_per_buffer = (ctx->inode_buffer_blocks ?
1352                                      ctx->inode_buffer_blocks :
1353                                      EXT2_INODE_SCAN_DEFAULT_BUFFER_BLOCKS) *
1354                                     ctx->fs->blocksize /
1355                                     EXT2_INODE_SIZE(ctx->fs->super);
1356                 inodes_in_group--;
1357                 *next_ino = inodes_in_group -
1358                             (inodes_in_group % inodes_per_buffer) + 1 +
1359                             (grp * ctx->fs->super->s_inodes_per_group);
1360         }
1361 }
1362
1363 /*
1364  * Check if the passed ino is one of the used superblock quota inodes.
1365  *
1366  * Before the quota inodes were journaled, older superblock quota inodes
1367  * were just regular files in the filesystem and not reserved inodes.  This
1368  * checks if the passed ino is one of the s_*_quota_inum superblock fields,
1369  * which may not always be the same as the EXT4_*_QUOTA_INO fields.
1370  */
1371 static int quota_inum_is_super(struct ext2_super_block *sb, ext2_ino_t ino)
1372 {
1373         enum quota_type qtype;
1374
1375         for (qtype = 0; qtype < MAXQUOTAS; qtype++)
1376                 if (*quota_sb_inump(sb, qtype) == ino)
1377                         return 1;
1378
1379         return 0;
1380 }
1381
1382 /*
1383  * Check if the passed ino is one of the reserved quota inodes.
1384  * This checks if the inode number is one of the reserved EXT4_*_QUOTA_INO
1385  * inodes.  These inodes may or may not be in use by the quota feature.
1386  */
1387 static int quota_inum_is_reserved(ext2_filsys fs, ext2_ino_t ino)
1388 {
1389         enum quota_type qtype;
1390
1391         for (qtype = 0; qtype < MAXQUOTAS; qtype++)
1392                 if (quota_type2inum(qtype, fs->super) == ino)
1393                         return 1;
1394
1395         return 0;
1396 }
1397
1398 static int e2fsck_should_abort(e2fsck_t ctx)
1399 {
1400         e2fsck_t global_ctx;
1401
1402         if (ctx->flags & E2F_FLAG_SIGNAL_MASK)
1403                 return 1;
1404
1405         if (ctx->global_ctx) {
1406                 global_ctx = ctx->global_ctx;
1407                 if (global_ctx->flags & E2F_FLAG_SIGNAL_MASK)
1408                         return 1;
1409         }
1410         return 0;
1411 }
1412
1413 static void init_ext2_max_sizes()
1414 {
1415         int     i;
1416         __u64   max_sizes;
1417
1418         /*
1419          * Init ext2_max_sizes which will be immutable and shared between
1420          * threads
1421          */
1422 #define EXT2_BPP(bits) (1ULL << ((bits) - 2))
1423
1424         for (i = EXT2_MIN_BLOCK_LOG_SIZE; i <= EXT2_MAX_BLOCK_LOG_SIZE; i++) {
1425                 max_sizes = EXT2_NDIR_BLOCKS + EXT2_BPP(i);
1426                 max_sizes = max_sizes + EXT2_BPP(i) * EXT2_BPP(i);
1427                 max_sizes = max_sizes + EXT2_BPP(i) * EXT2_BPP(i) * EXT2_BPP(i);
1428                 max_sizes = (max_sizes * (1UL << i));
1429                 ext2_max_sizes[i - EXT2_MIN_BLOCK_LOG_SIZE] = max_sizes;
1430         }
1431 #undef EXT2_BPP
1432 }
1433
1434 #ifdef HAVE_PTHREAD
1435 /* TODO: tdb needs to be handled properly for multiple threads*/
1436 static int multiple_threads_supported(e2fsck_t ctx)
1437 {
1438 #ifdef  CONFIG_TDB
1439         unsigned int            threshold;
1440         ext2_ino_t              num_dirs;
1441         errcode_t               retval;
1442         char                    *tdb_dir;
1443         int                     enable;
1444
1445         profile_get_string(ctx->profile, "scratch_files", "directory", 0, 0,
1446                            &tdb_dir);
1447         profile_get_uint(ctx->profile, "scratch_files",
1448                          "numdirs_threshold", 0, 0, &threshold);
1449         profile_get_boolean(ctx->profile, "scratch_files",
1450                             "icount", 0, 1, &enable);
1451
1452         retval = ext2fs_get_num_dirs(ctx->fs, &num_dirs);
1453         if (retval)
1454                 num_dirs = 1024;        /* Guess */
1455
1456         /* tdb is unsupported now */
1457         if (enable && tdb_dir && !access(tdb_dir, W_OK) &&
1458             (!threshold || num_dirs > threshold))
1459                 return 0;
1460 #endif
1461         return 1;
1462 }
1463
1464 /**
1465  * Even though we could specify number of threads,
1466  * but it might be more than the whole filesystem
1467  * block groups, correct it here.
1468  */
1469 static void e2fsck_pass1_set_thread_num(e2fsck_t ctx)
1470 {
1471         unsigned flexbg_size = 1;
1472         ext2_filsys fs = ctx->fs;
1473         int num_threads = ctx->pfs_num_threads;
1474         int max_threads;
1475
1476         if (num_threads < 1) {
1477                 num_threads = 1;
1478                 goto out;
1479         }
1480
1481         if (!multiple_threads_supported(ctx)) {
1482                 num_threads = 1;
1483                 fprintf(stderr, "Fall through single thread for pass1 "
1484                         "because tdb could not handle properly\n");
1485                 goto out;
1486         }
1487
1488         if (ext2fs_has_feature_flex_bg(fs->super))
1489                 flexbg_size = 1 << fs->super->s_log_groups_per_flex;
1490         max_threads = fs->group_desc_count / flexbg_size;
1491         if (max_threads == 0)
1492                 max_threads = 1;
1493         if (max_threads > E2FSCK_MAX_THREADS)
1494                 max_threads = E2FSCK_MAX_THREADS;
1495
1496         if (num_threads > max_threads) {
1497                 fprintf(stderr, "Use max possible thread num: %d instead\n",
1498                                 max_threads);
1499                 num_threads = max_threads;
1500         }
1501 out:
1502         ctx->pfs_num_threads = num_threads;
1503         ctx->fs->fs_num_threads = num_threads;
1504 }
1505 #endif
1506
1507 /*
1508  * We need call mark_table_blocks() before multiple
1509  * thread start, since all known system blocks should be
1510  * marked and checked later.
1511  */
1512 static errcode_t e2fsck_pass1_prepare(e2fsck_t ctx)
1513 {
1514         struct problem_context pctx;
1515         ext2_filsys fs = ctx->fs;
1516         unsigned long long readahead_kb;
1517
1518         init_ext2_max_sizes();
1519 #ifdef HAVE_PTHREAD
1520         e2fsck_pass1_set_thread_num(ctx);
1521 #endif
1522         /* If we can do readahead, figure out how many groups to pull in. */
1523         if (!e2fsck_can_readahead(ctx->fs))
1524                 ctx->readahead_kb = 0;
1525         else if (ctx->readahead_kb == ~0ULL)
1526                 ctx->readahead_kb = e2fsck_guess_readahead(ctx->fs);
1527
1528 #ifdef HAVE_PTHREAD
1529         /* don't use more than 1/10 of memory for threads checking */
1530         readahead_kb = get_memory_size() / (10 * ctx->pfs_num_threads);
1531         /* maybe better disable RA if this is too small? */
1532         if (ctx->readahead_kb > readahead_kb)
1533                 ctx->readahead_kb = readahead_kb;
1534 #endif
1535         clear_problem_context(&pctx);
1536         if (!(ctx->options & E2F_OPT_PREEN))
1537                 fix_problem(ctx, PR_1_PASS_HEADER, &pctx);
1538
1539         pctx.errcode = e2fsck_allocate_subcluster_bitmap(ctx->fs,
1540                         _("in-use block map"), EXT2FS_BMAP64_RBTREE,
1541                         "block_found_map", &ctx->block_found_map);
1542         if (pctx.errcode) {
1543                 pctx.num = 1;
1544                 fix_problem(ctx, PR_1_ALLOCATE_BBITMAP_ERROR, &pctx);
1545                 ctx->flags |= E2F_FLAG_ABORT;
1546                 return pctx.errcode;
1547         }
1548         pctx.errcode = e2fsck_allocate_block_bitmap(ctx->fs,
1549                         _("metadata block map"), EXT2FS_BMAP64_RBTREE,
1550                         "block_metadata_map", &ctx->block_metadata_map);
1551         if (pctx.errcode) {
1552                 pctx.num = 1;
1553                 fix_problem(ctx, PR_1_ALLOCATE_BBITMAP_ERROR, &pctx);
1554                 ctx->flags |= E2F_FLAG_ABORT;
1555                 return pctx.errcode;
1556         }
1557
1558         mark_table_blocks(ctx);
1559         pctx.errcode = ext2fs_convert_subcluster_bitmap(ctx->fs,
1560                                                 &ctx->block_found_map);
1561         if (pctx.errcode) {
1562                 fix_problem(ctx, PR_1_CONVERT_SUBCLUSTER, &pctx);
1563                 ctx->flags |= E2F_FLAG_ABORT;
1564                 return pctx.errcode;
1565         }
1566
1567         pctx.errcode = e2fsck_allocate_block_bitmap(ctx->fs,
1568                         _("multiply claimed block map"),
1569                         EXT2FS_BMAP64_RBTREE, "block_dup_map",
1570                         &ctx->block_dup_map);
1571         if (pctx.errcode) {
1572                 pctx.num = 3;
1573                 fix_problem(ctx, PR_1_ALLOCATE_BBITMAP_ERROR,
1574                             &pctx);
1575                 /* Should never get here */
1576                 ctx->flags |= E2F_FLAG_ABORT;
1577                 return pctx.errcode;
1578         }
1579
1580         if (ext2fs_has_feature_mmp(fs->super) &&
1581             fs->super->s_mmp_block > fs->super->s_first_data_block &&
1582             fs->super->s_mmp_block < ext2fs_blocks_count(fs->super))
1583                 ext2fs_mark_block_bitmap2(ctx->block_found_map,
1584                                           fs->super->s_mmp_block);
1585 #ifdef  HAVE_PTHREAD
1586         pthread_rwlock_init(&ctx->fs_fix_rwlock, NULL);
1587         pthread_rwlock_init(&ctx->fs_block_map_rwlock, NULL);
1588         if (ctx->pfs_num_threads > 1)
1589                 ctx->fs_need_locking = 1;
1590 #endif
1591
1592         return 0;
1593 }
1594
1595 static void e2fsck_pass1_post(e2fsck_t ctx)
1596 {
1597         struct problem_context pctx;
1598         ext2_filsys fs = ctx->fs;
1599         char *block_buf;
1600
1601         if (e2fsck_should_abort(ctx))
1602                 return;
1603
1604         block_buf = (char *)e2fsck_allocate_memory(ctx, ctx->fs->blocksize * 3,
1605                                               "block interate buffer");
1606         reserve_block_for_root_repair(ctx);
1607         reserve_block_for_lnf_repair(ctx);
1608
1609         /*
1610          * If any extended attribute blocks' reference counts need to
1611          * be adjusted, either up (ctx->refcount_extra), or down
1612          * (ctx->refcount), then fix them.
1613          */
1614         if (ctx->refcount) {
1615                 adjust_extattr_refcount(ctx, ctx->refcount, block_buf, -1);
1616                 ea_refcount_free(ctx->refcount);
1617                 ctx->refcount = 0;
1618         }
1619         if (ctx->refcount_extra) {
1620                 adjust_extattr_refcount(ctx, ctx->refcount_extra,
1621                                         block_buf, +1);
1622                 ea_refcount_free(ctx->refcount_extra);
1623                 ctx->refcount_extra = 0;
1624         }
1625
1626         if (ctx->invalid_bitmaps)
1627                 handle_fs_bad_blocks(ctx);
1628
1629         /* We don't need the block_ea_map any more */
1630         if (ctx->block_ea_map) {
1631                 ext2fs_free_block_bitmap(ctx->block_ea_map);
1632                 ctx->block_ea_map = 0;
1633         }
1634
1635         if (ctx->flags & E2F_FLAG_RESIZE_INODE) {
1636                 struct ext2_inode *inode;
1637                 int inode_size = EXT2_INODE_SIZE(fs->super);
1638                 inode = e2fsck_allocate_memory(ctx, inode_size,
1639                                                "scratch inode");
1640
1641                 clear_problem_context(&pctx);
1642                 pctx.errcode = ext2fs_create_resize_inode(fs);
1643                 if (pctx.errcode) {
1644                         if (!fix_problem(ctx, PR_1_RESIZE_INODE_CREATE,
1645                                          &pctx)) {
1646                                 ctx->flags |= E2F_FLAG_ABORT;
1647                                 ext2fs_free_mem(&inode);
1648                                 ext2fs_free_mem(&block_buf);
1649                                 return;
1650                         }
1651                         pctx.errcode = 0;
1652                 }
1653                 if (!pctx.errcode) {
1654                         e2fsck_read_inode(ctx, EXT2_RESIZE_INO, inode,
1655                                           "recreate inode");
1656                         inode->i_mtime = ctx->now;
1657                         e2fsck_write_inode(ctx, EXT2_RESIZE_INO, inode,
1658                                            "recreate inode");
1659                 }
1660                 ctx->flags &= ~E2F_FLAG_RESIZE_INODE;
1661                 ext2fs_free_mem(&inode);
1662         }
1663
1664         if (ctx->flags & E2F_FLAG_RESTART) {
1665                 ext2fs_free_mem(&block_buf);
1666                 return;
1667         }
1668
1669         if (ctx->block_dup_map) {
1670                 if (!(ctx->flags & E2F_FLAG_DUP_BLOCK)) {
1671                         ext2fs_free_mem(&block_buf);
1672                         return;
1673                 }
1674                 if (ctx->options & E2F_OPT_PREEN) {
1675                         clear_problem_context(&pctx);
1676                         fix_problem(ctx, PR_1_DUP_BLOCKS_PREENSTOP, &pctx);
1677                 }
1678                 e2fsck_pass1_dupblocks(ctx, block_buf);
1679                 ext2fs_free_mem(&block_buf);
1680                 ctx->flags &= ~E2F_FLAG_DUP_BLOCK;
1681         }
1682
1683         ctx->flags |= E2F_FLAG_ALLOC_OK;
1684 }
1685
1686
1687 /*
1688  * Lustre FS creates special inodes - precreated objects.
1689  * They are zero-sized and have special attributes:
1690  * mode |= S_ISUID | S_ISGID;
1691  * valid |= LA_ATIME | LA_MTIME | LA_CTIME;
1692  * atime = 0;
1693  * mtime = 0;
1694  * ctime = 0;
1695  */
1696 static int precreated_object(struct ext2_inode *inode)
1697 {
1698         if (((inode->i_mode & (S_ISUID | S_ISGID)) == (S_ISUID | S_ISGID)) &&
1699              inode->i_ctime == 0)
1700                 return 1;
1701         return 0;
1702 }
1703
1704 void e2fsck_pass1_run(e2fsck_t ctx)
1705 {
1706         int     i;
1707         ext2_filsys fs = ctx->fs;
1708         ext2_ino_t      ino = 0;
1709         struct ext2_inode *inode = NULL;
1710         ext2_inode_scan scan = NULL;
1711         char            *block_buf = NULL;
1712 #ifdef RESOURCE_TRACK
1713         struct resource_track   rtrack;
1714 #endif
1715         unsigned char   frag, fsize;
1716         struct          problem_context pctx;
1717         struct          scan_callback_struct scan_struct;
1718         struct ext2_super_block *sb = ctx->fs->super;
1719         const char      *old_op;
1720         const char      *eop_next_inode = _("getting next inode from scan");
1721         int             imagic_fs, extent_fs, inlinedata_fs, casefold_fs;
1722         int             low_dtime_check = 1;
1723         unsigned int    inode_size = EXT2_INODE_SIZE(fs->super);
1724         unsigned int    bufsize;
1725         int             failed_csum = 0;
1726         ext2_ino_t      ino_threshold = 0;
1727         dgrp_t          ra_group = 0;
1728         struct ea_quota ea_ibody_quota;
1729         struct process_inode_block *inodes_to_process;
1730         int             process_inode_count, check_mmp;
1731         e2fsck_t        global_ctx = ctx->global_ctx ? ctx->global_ctx : ctx;
1732         int             inode_exp = 0;
1733
1734         init_resource_track(&rtrack, ctx->fs->io);
1735         clear_problem_context(&pctx);
1736
1737         pass1_readahead(ctx, &ra_group, &ino_threshold);
1738         if (ext2fs_has_feature_dir_index(fs->super) &&
1739             !(ctx->options & E2F_OPT_NO)) {
1740                 if (ext2fs_u32_list_create(&ctx->dirs_to_hash, 50))
1741                         ctx->dirs_to_hash = 0;
1742         }
1743
1744 #ifdef MTRACE
1745         mtrace_print("Pass 1");
1746 #endif
1747
1748         imagic_fs = ext2fs_has_feature_imagic_inodes(sb);
1749         extent_fs = ext2fs_has_feature_extents(sb);
1750         inlinedata_fs = ext2fs_has_feature_inline_data(sb);
1751         casefold_fs = ext2fs_has_feature_casefold(sb);
1752
1753         /*
1754          * Allocate bitmaps structures
1755          */
1756         pctx.errcode = e2fsck_allocate_inode_bitmap(fs, _("in-use inode map"),
1757                                                     EXT2FS_BMAP64_RBTREE,
1758                                                     "inode_used_map",
1759                                                     &ctx->inode_used_map);
1760         if (pctx.errcode) {
1761                 pctx.num = 1;
1762                 fix_problem(ctx, PR_1_ALLOCATE_IBITMAP_ERROR, &pctx);
1763                 ctx->flags |= E2F_FLAG_ABORT;
1764                 return;
1765         }
1766         pctx.errcode = e2fsck_allocate_inode_bitmap(fs,
1767                         _("directory inode map"),
1768                         ctx->global_ctx ? EXT2FS_BMAP64_RBTREE :
1769                         EXT2FS_BMAP64_AUTODIR,
1770                         "inode_dir_map", &ctx->inode_dir_map);
1771         if (pctx.errcode) {
1772                 pctx.num = 2;
1773                 fix_problem(ctx, PR_1_ALLOCATE_IBITMAP_ERROR, &pctx);
1774                 ctx->flags |= E2F_FLAG_ABORT;
1775                 return;
1776         }
1777         pctx.errcode = e2fsck_allocate_inode_bitmap(fs,
1778                         _("regular file inode map"), EXT2FS_BMAP64_RBTREE,
1779                         "inode_reg_map", &ctx->inode_reg_map);
1780         if (pctx.errcode) {
1781                 pctx.num = 6;
1782                 fix_problem(ctx, PR_1_ALLOCATE_IBITMAP_ERROR, &pctx);
1783                 ctx->flags |= E2F_FLAG_ABORT;
1784                 return;
1785         }
1786         if (casefold_fs) {
1787                 pctx.errcode =
1788                         e2fsck_allocate_inode_bitmap(fs,
1789                                                      _("inode casefold map"),
1790                                                      EXT2FS_BMAP64_RBTREE,
1791                                                      "inode_casefold_map",
1792                                                      &ctx->inode_casefold_map);
1793                 if (pctx.errcode) {
1794                         pctx.num = 1;
1795                         fix_problem(ctx, PR_1_ALLOCATE_IBITMAP_ERROR, &pctx);
1796                         ctx->flags |= E2F_FLAG_ABORT;
1797                         return;
1798                 }
1799         }
1800         pctx.errcode = e2fsck_setup_icount(ctx, "inode_link_info", 0, NULL,
1801                                            &ctx->inode_link_info);
1802         if (pctx.errcode) {
1803                 fix_problem(ctx, PR_1_ALLOCATE_ICOUNT, &pctx);
1804                 ctx->flags |= E2F_FLAG_ABORT;
1805                 return;
1806         }
1807         bufsize = inode_size;
1808         if (bufsize < sizeof(struct ext2_inode_large))
1809                 bufsize = sizeof(struct ext2_inode_large);
1810         inode = (struct ext2_inode *)
1811                 e2fsck_allocate_memory(ctx, bufsize, "scratch inode");
1812
1813         inodes_to_process = (struct process_inode_block *)
1814                 e2fsck_allocate_memory(ctx,
1815                                        (ctx->process_inode_size *
1816                                         sizeof(struct process_inode_block)),
1817                                        "array of inodes to process");
1818         process_inode_count = 0;
1819
1820         pctx.errcode = ext2fs_init_dblist(fs, 0);
1821         if (pctx.errcode) {
1822                 fix_problem(ctx, PR_1_ALLOCATE_DBCOUNT, &pctx);
1823                 ctx->flags |= E2F_FLAG_ABORT;
1824                 goto endit;
1825         }
1826
1827         /*
1828          * If the last orphan field is set, clear it, since the pass1
1829          * processing will automatically find and clear the orphans.
1830          * In the future, we may want to try using the last_orphan
1831          * linked list ourselves, but for now, we clear it so that the
1832          * ext3 mount code won't get confused.
1833          */
1834         if (!(ctx->options & E2F_OPT_READONLY)) {
1835                 if (fs->super->s_last_orphan) {
1836                         fs->super->s_last_orphan = 0;
1837                         ext2fs_mark_super_dirty(fs);
1838                 }
1839         }
1840
1841         block_buf = (char *) e2fsck_allocate_memory(ctx, fs->blocksize * 3,
1842                                                     "block interate buffer");
1843         if (EXT2_INODE_SIZE(fs->super) == EXT2_GOOD_OLD_INODE_SIZE)
1844                 e2fsck_use_inode_shortcuts(ctx, 1);
1845         e2fsck_intercept_block_allocations(ctx);
1846         old_op = ehandler_operation(_("opening inode scan"));
1847         pctx.errcode = ext2fs_open_inode_scan(fs, ctx->inode_buffer_blocks,
1848                                               &scan);
1849         ehandler_operation(old_op);
1850         if (pctx.errcode) {
1851                 fix_problem(ctx, PR_1_ISCAN_ERROR, &pctx);
1852                 ctx->flags |= E2F_FLAG_ABORT;
1853                 goto endit;
1854         }
1855         ext2fs_inode_scan_flags(scan, EXT2_SF_SKIP_MISSING_ITABLE |
1856                                       EXT2_SF_WARN_GARBAGE_INODES, 0);
1857         ctx->stashed_inode = inode;
1858         scan_struct.ctx = ctx;
1859         scan_struct.block_buf = block_buf;
1860         scan_struct.inodes_to_process = inodes_to_process;
1861         scan_struct.process_inode_count = &process_inode_count;
1862         ext2fs_set_inode_callback(scan, scan_callback, &scan_struct);
1863         if (ctx->progress && ((ctx->progress)(ctx, 1, 0,
1864                                               ctx->fs->group_desc_count)))
1865                 goto endit;
1866         if ((fs->super->s_wtime &&
1867              fs->super->s_wtime < fs->super->s_inodes_count) ||
1868             (fs->super->s_mtime &&
1869              fs->super->s_mtime < fs->super->s_inodes_count) ||
1870             (fs->super->s_mkfs_time &&
1871              fs->super->s_mkfs_time < fs->super->s_inodes_count))
1872                 low_dtime_check = 0;
1873
1874         /* Set up ctx->lost_and_found if possible */
1875         (void) e2fsck_get_lost_and_found(ctx, 0);
1876
1877 #ifdef HAVE_PTHREAD
1878         if (ctx->global_ctx) {
1879                 if (ctx->options & E2F_OPT_DEBUG &&
1880                     ctx->options & E2F_OPT_MULTITHREAD)
1881                         log_out(ctx, "jumping to group %u\n",
1882                                 ctx->thread_info.et_group_start);
1883                 pctx.errcode = ext2fs_inode_scan_goto_blockgroup(scan,
1884                                         ctx->thread_info.et_group_start);
1885                 if (pctx.errcode) {
1886                         fix_problem(ctx, PR_1_PASS_HEADER, &pctx);
1887                         ctx->flags |= E2F_FLAG_ABORT;
1888                         goto endit;
1889                 }
1890         }
1891 #endif
1892
1893         while (1) {
1894                 check_mmp = 0;
1895                 e2fsck_pass1_check_lock(ctx);
1896 #ifdef  HAVE_PTHREAD
1897                 if (!global_ctx->mmp_update_thread) {
1898                         e2fsck_pass1_block_map_w_lock(ctx);
1899                         if (!global_ctx->mmp_update_thread) {
1900                                 global_ctx->mmp_update_thread =
1901                                         ctx->thread_info.et_thread_index + 1;
1902                                 check_mmp = 1;
1903                         }
1904                         e2fsck_pass1_block_map_w_unlock(ctx);
1905                 }
1906
1907                 /* only one active thread could update mmp block. */
1908                 e2fsck_pass1_block_map_r_lock(ctx);
1909                 if (global_ctx->mmp_update_thread ==
1910                     ctx->thread_info.et_thread_index + 1)
1911                         check_mmp = 1;
1912                 e2fsck_pass1_block_map_r_unlock(ctx);
1913 #else
1914                 check_mmp = 1;
1915 #endif
1916
1917                 if (check_mmp && (ino % (fs->super->s_inodes_per_group * 4) == 1)) {
1918                         if (e2fsck_mmp_update(fs))
1919                                 fatal_error(ctx, 0);
1920                 }
1921                 old_op = ehandler_operation(eop_next_inode);
1922                 pctx.errcode = ext2fs_get_next_inode_full(scan, &ino,
1923                                                           inode, inode_size);
1924                 if (ino > ino_threshold)
1925                         pass1_readahead(ctx, &ra_group, &ino_threshold);
1926                 ehandler_operation(old_op);
1927                 if (e2fsck_should_abort(ctx)) {
1928                         e2fsck_pass1_check_unlock(ctx);
1929                         goto endit;
1930                 }
1931                 if (pctx.errcode == EXT2_ET_BAD_BLOCK_IN_INODE_TABLE) {
1932                         /*
1933                          * If badblocks says badblocks is bad, offer to clear
1934                          * the list, update the in-core bb list, and restart
1935                          * the inode scan.
1936                          */
1937                         if (ino == EXT2_BAD_INO &&
1938                             fix_problem(ctx, PR_1_BADBLOCKS_IN_BADBLOCKS,
1939                                         &pctx)) {
1940                                 errcode_t err;
1941
1942                                 e2fsck_clear_inode(ctx, ino, inode, 0, "pass1");
1943                                 ext2fs_badblocks_list_free(ctx->fs->badblocks);
1944                                 ctx->fs->badblocks = NULL;
1945                                 err = ext2fs_read_bb_inode(ctx->fs,
1946                                                         &ctx->fs->badblocks);
1947                                 if (err) {
1948                                         fix_problem(ctx, PR_1_ISCAN_ERROR,
1949                                                     &pctx);
1950                                         ctx->flags |= E2F_FLAG_ABORT;
1951                                         e2fsck_pass1_check_unlock(ctx);
1952                                         goto endit;
1953                                 } else
1954                                         ctx->flags |= E2F_FLAG_RESTART;
1955                                 err = ext2fs_inode_scan_goto_blockgroup(scan,
1956                                                                         0);
1957                                 if (err) {
1958                                         fix_problem(ctx, PR_1_ISCAN_ERROR,
1959                                                     &pctx);
1960                                         ctx->flags |= E2F_FLAG_ABORT;
1961                                         e2fsck_pass1_check_unlock(ctx);
1962                                         goto endit;
1963                                 }
1964                                 e2fsck_pass1_check_unlock(ctx);
1965                                 continue;
1966                         }
1967                         if (!ctx->inode_bb_map)
1968                                 alloc_bb_map(ctx);
1969                         ext2fs_mark_inode_bitmap2(ctx->inode_bb_map, ino);
1970                         ext2fs_mark_inode_bitmap2(ctx->inode_used_map, ino);
1971                         e2fsck_pass1_check_unlock(ctx);
1972                         continue;
1973                 }
1974                 if (pctx.errcode == EXT2_ET_SCAN_FINISHED) {
1975                         e2fsck_pass1_check_unlock(ctx);
1976                         break;
1977                 }
1978                 if (pctx.errcode &&
1979                     pctx.errcode != EXT2_ET_INODE_CSUM_INVALID &&
1980                     pctx.errcode != EXT2_ET_INODE_IS_GARBAGE) {
1981                         fix_problem(ctx, PR_1_ISCAN_ERROR, &pctx);
1982                         ctx->flags |= E2F_FLAG_ABORT;
1983                         e2fsck_pass1_check_unlock(ctx);
1984                         goto endit;
1985                 }
1986                 if (!ino) {
1987                         e2fsck_pass1_check_unlock(ctx);
1988                         break;
1989                 }
1990 #ifdef HAVE_PTHREAD
1991                 if (ctx->global_ctx)
1992                         ctx->thread_info.et_inode_number++;
1993 #endif
1994                 pctx.ino = ino;
1995                 pctx.inode = inode;
1996                 ctx->stashed_ino = ino;
1997
1998                 /* Clear trashed inode? */
1999                 if (pctx.errcode == EXT2_ET_INODE_IS_GARBAGE &&
2000                     inode->i_links_count > 0 &&
2001                     fix_problem(ctx, PR_1_INODE_IS_GARBAGE, &pctx)) {
2002                         pctx.errcode = 0;
2003                         e2fsck_clear_inode(ctx, ino, inode, 0, "pass1");
2004                 }
2005                 failed_csum = pctx.errcode != 0;
2006
2007                 /*
2008                  * Check for inodes who might have been part of the
2009                  * orphaned list linked list.  They should have gotten
2010                  * dealt with by now, unless the list had somehow been
2011                  * corrupted.
2012                  *
2013                  * FIXME: In the future, inodes which are still in use
2014                  * (and which are therefore) pending truncation should
2015                  * be handled specially.  Right now we just clear the
2016                  * dtime field, and the normal e2fsck handling of
2017                  * inodes where i_size and the inode blocks are
2018                  * inconsistent is to fix i_size, instead of releasing
2019                  * the extra blocks.  This won't catch the inodes that
2020                  * was at the end of the orphan list, but it's better
2021                  * than nothing.  The right answer is that there
2022                  * shouldn't be any bugs in the orphan list handling.  :-)
2023                  */
2024                 if (inode->i_dtime && low_dtime_check &&
2025                     inode->i_dtime < ctx->fs->super->s_inodes_count) {
2026                         if (fix_problem(ctx, PR_1_LOW_DTIME, &pctx)) {
2027                                 inode->i_dtime = inode->i_links_count ?
2028                                         0 : ctx->now;
2029                                 e2fsck_write_inode(ctx, ino, inode,
2030                                                    "pass1");
2031                                 failed_csum = 0;
2032                         }
2033                 }
2034
2035                 if (inode->i_links_count) {
2036                         pctx.errcode = ext2fs_icount_store(ctx->inode_link_info,
2037                                            ino, inode->i_links_count);
2038                         if (pctx.errcode) {
2039                                 pctx.num = inode->i_links_count;
2040                                 fix_problem(ctx, PR_1_ICOUNT_STORE, &pctx);
2041                                 ctx->flags |= E2F_FLAG_ABORT;
2042                                 e2fsck_pass1_check_unlock(ctx);
2043                                 goto endit;
2044                         }
2045                 } else if ((ino >= EXT2_FIRST_INODE(fs->super)) &&
2046                            !quota_inum_is_reserved(fs, ino)) {
2047                         if (!inode->i_dtime && inode->i_mode) {
2048                                 if (fix_problem(ctx,
2049                                             PR_1_ZERO_DTIME, &pctx)) {
2050                                         inode->i_dtime = ctx->now;
2051                                         e2fsck_write_inode(ctx, ino, inode,
2052                                                            "pass1");
2053                                         failed_csum = 0;
2054                                 }
2055                         }
2056                         FINISH_INODE_LOOP(ctx, ino, &pctx, failed_csum);
2057                         e2fsck_pass1_check_unlock(ctx);
2058                         continue;
2059                 }
2060
2061                 if ((inode->i_flags & EXT4_CASEFOLD_FL) &&
2062                     ((!LINUX_S_ISDIR(inode->i_mode) &&
2063                       fix_problem(ctx, PR_1_CASEFOLD_NONDIR, &pctx)) ||
2064                      (!casefold_fs &&
2065                       fix_problem(ctx, PR_1_CASEFOLD_FEATURE, &pctx)))) {
2066                         inode->i_flags &= ~EXT4_CASEFOLD_FL;
2067                         e2fsck_write_inode(ctx, ino, inode, "pass1");
2068                 }
2069
2070                 /* Conflicting inlinedata/extents inode flags? */
2071                 if ((inode->i_flags & EXT4_INLINE_DATA_FL) &&
2072                     (inode->i_flags & EXT4_EXTENTS_FL)) {
2073                         int res = fix_inline_data_extents_file(ctx, ino, inode,
2074                                                                inode_size,
2075                                                                &pctx);
2076                         if (res < 0) {
2077                                 /* skip FINISH_INODE_LOOP */
2078                                 e2fsck_pass1_check_unlock(ctx);
2079                                 continue;
2080                         }
2081                 }
2082
2083                 /* Test for incorrect inline_data flags settings. */
2084                 if ((inode->i_flags & EXT4_INLINE_DATA_FL) && !inlinedata_fs &&
2085                     (ino >= EXT2_FIRST_INODE(fs->super))) {
2086                         size_t size = 0;
2087
2088                         pctx.errcode = get_inline_data_ea_size(fs, ino, &size);
2089                         if (!pctx.errcode &&
2090                             fix_problem(ctx, PR_1_INLINE_DATA_FEATURE, &pctx)) {
2091                                 e2fsck_pass1_fix_lock(ctx);
2092                                 ext2fs_set_feature_inline_data(sb);
2093                                 ext2fs_mark_super_dirty(fs);
2094                                 e2fsck_pass1_fix_unlock(ctx);
2095                                 inlinedata_fs = 1;
2096                         } else if (fix_problem(ctx, PR_1_INLINE_DATA_SET, &pctx)) {
2097                                 e2fsck_clear_inode(ctx, ino, inode, 0, "pass1");
2098                                 /* skip FINISH_INODE_LOOP */
2099                                 e2fsck_pass1_check_unlock(ctx);
2100                                 continue;
2101                         }
2102                 }
2103
2104                 /* Test for inline data flag but no attr */
2105                 if ((inode->i_flags & EXT4_INLINE_DATA_FL) && inlinedata_fs &&
2106                     (ino >= EXT2_FIRST_INODE(fs->super))) {
2107                         size_t size = 0;
2108                         errcode_t err;
2109                         int flags;
2110
2111                         flags = fs->flags;
2112                         if (failed_csum)
2113                                 fs->flags |= EXT2_FLAG_IGNORE_CSUM_ERRORS;
2114                         err = get_inline_data_ea_size(fs, ino, &size);
2115                         fs->flags = (flags & EXT2_FLAG_IGNORE_CSUM_ERRORS) |
2116                                     (fs->flags & ~EXT2_FLAG_IGNORE_CSUM_ERRORS);
2117
2118                         switch (err) {
2119                         case 0:
2120                                 /* Everything is awesome... */
2121                                 break;
2122                         case EXT2_ET_BAD_EA_BLOCK_NUM:
2123                         case EXT2_ET_BAD_EA_HASH:
2124                         case EXT2_ET_BAD_EA_HEADER:
2125                         case EXT2_ET_EA_BAD_NAME_LEN:
2126                         case EXT2_ET_EA_BAD_VALUE_SIZE:
2127                         case EXT2_ET_EA_KEY_NOT_FOUND:
2128                         case EXT2_ET_EA_NO_SPACE:
2129                         case EXT2_ET_MISSING_EA_FEATURE:
2130                         case EXT2_ET_INLINE_DATA_CANT_ITERATE:
2131                         case EXT2_ET_INLINE_DATA_NO_BLOCK:
2132                         case EXT2_ET_INLINE_DATA_NO_SPACE:
2133                         case EXT2_ET_NO_INLINE_DATA:
2134                         case EXT2_ET_EXT_ATTR_CSUM_INVALID:
2135                         case EXT2_ET_EA_BAD_VALUE_OFFSET:
2136                         case EXT2_ET_EA_INODE_CORRUPTED:
2137                                 /* broken EA or no system.data EA; truncate */
2138                                 if (fix_problem(ctx, PR_1_INLINE_DATA_NO_ATTR,
2139                                                 &pctx)) {
2140                                         err = ext2fs_inode_size_set(fs, inode, 0);
2141                                         if (err) {
2142                                                 pctx.errcode = err;
2143                                                 ctx->flags |= E2F_FLAG_ABORT;
2144                                                 e2fsck_pass1_check_unlock(ctx);
2145                                                 goto endit;
2146                                         }
2147                                         inode->i_flags &= ~EXT4_INLINE_DATA_FL;
2148                                         memset(&inode->i_block, 0,
2149                                                sizeof(inode->i_block));
2150                                         e2fsck_write_inode(ctx, ino, inode,
2151                                                            "pass1");
2152                                         failed_csum = 0;
2153                                 }
2154                                 break;
2155                         default:
2156                                 /* Some other kind of non-xattr error? */
2157                                 pctx.errcode = err;
2158                                 ctx->flags |= E2F_FLAG_ABORT;
2159                                 e2fsck_pass1_check_unlock(ctx);
2160                                 goto endit;
2161                         }
2162                 }
2163
2164                 /*
2165                  * Test for incorrect extent flag settings.
2166                  *
2167                  * On big-endian machines we must be careful:
2168                  * When the inode is read, the i_block array is not swapped
2169                  * if the extent flag is set.  Therefore if we are testing
2170                  * for or fixing a wrongly-set flag, we must potentially
2171                  * (un)swap before testing, or after fixing.
2172                  */
2173
2174                 /*
2175                  * In this case the extents flag was set when read, so
2176                  * extent_header_verify is ok.  If the inode is cleared,
2177                  * no need to swap... so no extra swapping here.
2178                  */
2179                 if ((inode->i_flags & EXT4_EXTENTS_FL) && !extent_fs &&
2180                     (inode->i_links_count || (ino == EXT2_BAD_INO) ||
2181                      (ino == EXT2_ROOT_INO) || (ino == EXT2_JOURNAL_INO))) {
2182                         if ((ext2fs_extent_header_verify(inode->i_block,
2183                                                  sizeof(inode->i_block)) == 0) &&
2184                             fix_problem(ctx, PR_1_EXTENT_FEATURE, &pctx)) {
2185                                 e2fsck_pass1_fix_lock(ctx);
2186                                 ext2fs_set_feature_extents(sb);
2187                                 ext2fs_mark_super_dirty(fs);
2188                                 extent_fs = 1;
2189                                 e2fsck_pass1_fix_unlock(ctx);
2190                         } else if (fix_problem(ctx, PR_1_EXTENTS_SET, &pctx)) {
2191                         clear_inode:
2192                                 e2fsck_clear_inode(ctx, ino, inode, 0, "pass1");
2193                                 if (ino == EXT2_BAD_INO)
2194                                         ext2fs_mark_inode_bitmap2(ctx->inode_used_map,
2195                                                                  ino);
2196                                 /* skip FINISH_INODE_LOOP */
2197                                 e2fsck_pass1_check_unlock(ctx);
2198                                 continue;
2199                         }
2200                 }
2201
2202                 /*
2203                  * For big-endian machines:
2204                  * If the inode didn't have the extents flag set when it
2205                  * was read, then the i_blocks array was swapped.  To test
2206                  * as an extents header, we must swap it back first.
2207                  * IF we then set the extents flag, the entire i_block
2208                  * array must be un/re-swapped to make it proper extents data.
2209                  */
2210                 if (extent_fs && !(inode->i_flags & EXT4_EXTENTS_FL) &&
2211                     (inode->i_links_count || (ino == EXT2_BAD_INO) ||
2212                      (ino == EXT2_ROOT_INO) || (ino == EXT2_JOURNAL_INO)) &&
2213                     (LINUX_S_ISREG(inode->i_mode) ||
2214                      LINUX_S_ISDIR(inode->i_mode))) {
2215                         void *ehp;
2216 #ifdef WORDS_BIGENDIAN
2217                         __u32 tmp_block[EXT2_N_BLOCKS];
2218
2219                         for (i = 0; i < EXT2_N_BLOCKS; i++)
2220                                 tmp_block[i] = ext2fs_swab32(inode->i_block[i]);
2221                         ehp = tmp_block;
2222 #else
2223                         ehp = inode->i_block;
2224 #endif
2225                         if ((ext2fs_extent_header_verify(ehp,
2226                                          sizeof(inode->i_block)) == 0) &&
2227                             (fix_problem(ctx, PR_1_UNSET_EXTENT_FL, &pctx))) {
2228                                 inode->i_flags |= EXT4_EXTENTS_FL;
2229 #ifdef WORDS_BIGENDIAN
2230                                 memcpy(inode->i_block, tmp_block,
2231                                        sizeof(inode->i_block));
2232 #endif
2233                                 e2fsck_write_inode(ctx, ino, inode, "pass1");
2234                                 failed_csum = 0;
2235                         }
2236                 }
2237
2238                 if (ino == EXT2_BAD_INO) {
2239                         struct process_block_struct pb;
2240
2241                         if ((failed_csum || inode->i_mode || inode->i_uid ||
2242                              inode->i_gid || inode->i_links_count ||
2243                              (inode->i_flags & EXT4_INLINE_DATA_FL) ||
2244                              inode->i_file_acl) &&
2245                             fix_problem(ctx, PR_1_INVALID_BAD_INODE, &pctx)) {
2246                                 memset(inode, 0, sizeof(struct ext2_inode));
2247                                 e2fsck_write_inode(ctx, ino, inode,
2248                                                    "clear bad inode");
2249                                 failed_csum = 0;
2250                         }
2251
2252                         e2fsck_pass1_block_map_r_lock(ctx);
2253                         pctx.errcode = ext2fs_copy_bitmap(ctx->global_ctx ?
2254                                         ctx->global_ctx->block_found_map :
2255                                         ctx->block_found_map, &pb.fs_meta_blocks);
2256                         e2fsck_pass1_block_map_r_unlock(ctx);
2257                         if (pctx.errcode) {
2258                                 pctx.num = 4;
2259                                 fix_problem(ctx, PR_1_ALLOCATE_BBITMAP_ERROR, &pctx);
2260                                 ctx->flags |= E2F_FLAG_ABORT;
2261                                 e2fsck_pass1_check_unlock(ctx);
2262                                 goto endit;
2263                         }
2264                         pb.ino = EXT2_BAD_INO;
2265                         pb.num_blocks = pb.last_block = 0;
2266                         pb.last_db_block = -1;
2267                         pb.num_illegal_blocks = 0;
2268                         pb.suppress = 0; pb.clear = 0; pb.is_dir = 0;
2269                         pb.is_reg = 0; pb.fragmented = 0; pb.bbcheck = 0;
2270                         pb.inode = inode;
2271                         pb.pctx = &pctx;
2272                         pb.ctx = ctx;
2273                         pctx.errcode = ext2fs_block_iterate3(fs, ino, 0,
2274                                      block_buf, process_bad_block, &pb);
2275                         ext2fs_free_block_bitmap(pb.fs_meta_blocks);
2276                         if (pctx.errcode) {
2277                                 fix_problem(ctx, PR_1_BLOCK_ITERATE, &pctx);
2278                                 ctx->flags |= E2F_FLAG_ABORT;
2279                                 e2fsck_pass1_check_unlock(ctx);
2280                                 goto endit;
2281                         }
2282                         if (pb.bbcheck)
2283                                 if (!fix_problem(ctx, PR_1_BBINODE_BAD_METABLOCK_PROMPT, &pctx)) {
2284                                 ctx->flags |= E2F_FLAG_ABORT;
2285                                 e2fsck_pass1_check_unlock(ctx);
2286                                 goto endit;
2287                         }
2288                         ext2fs_mark_inode_bitmap2(ctx->inode_used_map, ino);
2289                         clear_problem_context(&pctx);
2290                         FINISH_INODE_LOOP(ctx, ino, &pctx, failed_csum);
2291                         e2fsck_pass1_check_unlock(ctx);
2292                         continue;
2293                 } else if (ino == EXT2_ROOT_INO) {
2294                         /*
2295                          * Make sure the root inode is a directory; if
2296                          * not, offer to clear it.  It will be
2297                          * regenerated in pass #3.
2298                          */
2299                         if (!LINUX_S_ISDIR(inode->i_mode)) {
2300                                 if (fix_problem(ctx, PR_1_ROOT_NO_DIR, &pctx))
2301                                         goto clear_inode;
2302                         }
2303                         /*
2304                          * If dtime is set, offer to clear it.  mke2fs
2305                          * version 0.2b created filesystems with the
2306                          * dtime field set for the root and lost+found
2307                          * directories.  We won't worry about
2308                          * /lost+found, since that can be regenerated
2309                          * easily.  But we will fix the root directory
2310                          * as a special case.
2311                          */
2312                         if (inode->i_dtime && inode->i_links_count) {
2313                                 if (fix_problem(ctx, PR_1_ROOT_DTIME, &pctx)) {
2314                                         inode->i_dtime = 0;
2315                                         e2fsck_write_inode(ctx, ino, inode,
2316                                                            "pass1");
2317                                         failed_csum = 0;
2318                                 }
2319                         }
2320                 } else if (ino == EXT2_JOURNAL_INO) {
2321                         ext2fs_mark_inode_bitmap2(ctx->inode_used_map, ino);
2322                         if (fs->super->s_journal_inum == EXT2_JOURNAL_INO) {
2323                                 if (!LINUX_S_ISREG(inode->i_mode) &&
2324                                     fix_problem(ctx, PR_1_JOURNAL_BAD_MODE,
2325                                                 &pctx)) {
2326                                         inode->i_mode = LINUX_S_IFREG;
2327                                         e2fsck_write_inode(ctx, ino, inode,
2328                                                            "pass1");
2329                                         failed_csum = 0;
2330                                 }
2331                                 check_blocks(ctx, &pctx, block_buf, NULL);
2332                                 FINISH_INODE_LOOP(ctx, ino, &pctx, failed_csum);
2333                                 e2fsck_pass1_check_unlock(ctx);
2334                                 continue;
2335                         }
2336                         if ((inode->i_links_count ||
2337                              inode->i_blocks || inode->i_block[0]) &&
2338                             fix_problem(ctx, PR_1_JOURNAL_INODE_NOT_CLEAR,
2339                                         &pctx)) {
2340                                 memset(inode, 0, inode_size);
2341                                 ext2fs_icount_store(ctx->inode_link_info,
2342                                                     ino, 0);
2343                                 e2fsck_write_inode_full(ctx, ino, inode,
2344                                                         inode_size, "pass1");
2345                                 failed_csum = 0;
2346                         }
2347                 } else if (quota_inum_is_reserved(fs, ino)) {
2348                         ext2fs_mark_inode_bitmap2(ctx->inode_used_map, ino);
2349                         if (ext2fs_has_feature_quota(fs->super) &&
2350                             quota_inum_is_super(fs->super, ino)) {
2351                                 if (!LINUX_S_ISREG(inode->i_mode) &&
2352                                     fix_problem(ctx, PR_1_QUOTA_BAD_MODE,
2353                                                         &pctx)) {
2354                                         inode->i_mode = LINUX_S_IFREG;
2355                                         e2fsck_write_inode(ctx, ino, inode,
2356                                                         "pass1");
2357                                         failed_csum = 0;
2358                                 }
2359                                 check_blocks(ctx, &pctx, block_buf, NULL);
2360                                 FINISH_INODE_LOOP(ctx, ino, &pctx, failed_csum);
2361                                 e2fsck_pass1_check_unlock(ctx);
2362                                 continue;
2363                         }
2364                         if ((inode->i_links_count ||
2365                              inode->i_blocks || inode->i_block[0]) &&
2366                             fix_problem(ctx, PR_1_QUOTA_INODE_NOT_CLEAR,
2367                                         &pctx)) {
2368                                 memset(inode, 0, inode_size);
2369                                 ext2fs_icount_store(ctx->inode_link_info,
2370                                                     ino, 0);
2371                                 e2fsck_write_inode_full(ctx, ino, inode,
2372                                                         inode_size, "pass1");
2373                                 failed_csum = 0;
2374                         }
2375                 } else if (ino < EXT2_FIRST_INODE(fs->super)) {
2376                         problem_t problem = 0;
2377
2378                         ext2fs_mark_inode_bitmap2(ctx->inode_used_map, ino);
2379                         if (ino == EXT2_BOOT_LOADER_INO) {
2380                                 if (LINUX_S_ISDIR(inode->i_mode))
2381                                         problem = PR_1_RESERVED_BAD_MODE;
2382                         } else if (ino == EXT2_RESIZE_INO) {
2383                                 if (inode->i_mode &&
2384                                     !LINUX_S_ISREG(inode->i_mode))
2385                                         problem = PR_1_RESERVED_BAD_MODE;
2386                         } else {
2387                                 if (inode->i_mode != 0)
2388                                         problem = PR_1_RESERVED_BAD_MODE;
2389                         }
2390                         if (problem) {
2391                                 if (fix_problem(ctx, problem, &pctx)) {
2392                                         inode->i_mode = 0;
2393                                         e2fsck_write_inode(ctx, ino, inode,
2394                                                            "pass1");
2395                                         failed_csum = 0;
2396                                 }
2397                         }
2398                         check_blocks(ctx, &pctx, block_buf, NULL);
2399                         FINISH_INODE_LOOP(ctx, ino, &pctx, failed_csum);
2400                         e2fsck_pass1_check_unlock(ctx);
2401                         continue;
2402                 }
2403
2404                 if (!inode->i_links_count) {
2405                         FINISH_INODE_LOOP(ctx, ino, &pctx, failed_csum);
2406                         e2fsck_pass1_check_unlock(ctx);
2407                         continue;
2408                 }
2409                 /*
2410                  * n.b.  0.3c ext2fs code didn't clear i_links_count for
2411                  * deleted files.  Oops.
2412                  *
2413                  * Since all new ext2 implementations get this right,
2414                  * we now assume that the case of non-zero
2415                  * i_links_count and non-zero dtime means that we
2416                  * should keep the file, not delete it.
2417                  *
2418                  */
2419                 if (inode->i_dtime) {
2420                         if (fix_problem(ctx, PR_1_SET_DTIME, &pctx)) {
2421                                 inode->i_dtime = 0;
2422                                 e2fsck_write_inode(ctx, ino, inode, "pass1");
2423                                 failed_csum = 0;
2424                         }
2425                 }
2426
2427                 ext2fs_mark_inode_bitmap2(ctx->inode_used_map, ino);
2428                 switch (fs->super->s_creator_os) {
2429                     case EXT2_OS_HURD:
2430                         frag = inode->osd2.hurd2.h_i_frag;
2431                         fsize = inode->osd2.hurd2.h_i_fsize;
2432                         break;
2433                     default:
2434                         frag = fsize = 0;
2435                 }
2436
2437                 /* Fixed in pass2, e2fsck_process_bad_inode(). */
2438                 if (inode->i_faddr || frag || fsize ||
2439                     (!ext2fs_has_feature_largedir(fs->super) &&
2440                      LINUX_S_ISDIR(inode->i_mode) && inode->i_size_high))
2441                         e2fsck_mark_inode_bad(ctx, &pctx,
2442                                               PR_2_DIR_SIZE_HIGH_ZERO);
2443                 if ((fs->super->s_creator_os != EXT2_OS_HURD) &&
2444                     !ext2fs_has_feature_64bit(fs->super) &&
2445                     inode->osd2.linux2.l_i_file_acl_high != 0)
2446                         e2fsck_mark_inode_bad(ctx, &pctx,
2447                                               PR_2_I_FILE_ACL_HI_ZERO);
2448                 if ((fs->super->s_creator_os != EXT2_OS_HURD) &&
2449                     !ext2fs_has_feature_huge_file(fs->super) &&
2450                     (inode->osd2.linux2.l_i_blocks_hi != 0))
2451                         e2fsck_mark_inode_bad(ctx, &pctx, PR_2_BLOCKS_HI_ZERO);
2452                 if (inode->i_flags & EXT2_IMAGIC_FL) {
2453                         if (imagic_fs) {
2454                                 if (!ctx->inode_imagic_map)
2455                                         alloc_imagic_map(ctx);
2456                                 ext2fs_mark_inode_bitmap2(ctx->inode_imagic_map,
2457                                                          ino);
2458                         } else {
2459                                 if (fix_problem(ctx, PR_1_SET_IMAGIC, &pctx)) {
2460                                         inode->i_flags &= ~EXT2_IMAGIC_FL;
2461                                         e2fsck_write_inode(ctx, ino,
2462                                                            inode, "pass1");
2463                                         failed_csum = 0;
2464                                 }
2465                         }
2466                 }
2467
2468                 check_inode_extra_space(ctx, &pctx, &ea_ibody_quota);
2469                 check_is_really_dir(ctx, &pctx, block_buf);
2470
2471                 /*
2472                  * ext2fs_inode_has_valid_blocks2 does not actually look
2473                  * at i_block[] values, so not endian-sensitive here.
2474                  */
2475                 if (extent_fs && (inode->i_flags & EXT4_EXTENTS_FL) &&
2476                     LINUX_S_ISLNK(inode->i_mode) &&
2477                     !ext2fs_inode_has_valid_blocks2(fs, inode) &&
2478                     fix_problem(ctx, PR_1_FAST_SYMLINK_EXTENT_FL, &pctx)) {
2479                         inode->i_flags &= ~EXT4_EXTENTS_FL;
2480                         e2fsck_write_inode(ctx, ino, inode, "pass1");
2481                         failed_csum = 0;
2482                 }
2483
2484                 if ((inode->i_flags & EXT4_ENCRYPT_FL) &&
2485                     add_encrypted_file(ctx, &pctx) < 0)
2486                         goto clear_inode;
2487
2488                 if (casefold_fs && inode->i_flags & EXT4_CASEFOLD_FL)
2489                         ext2fs_mark_inode_bitmap2(ctx->inode_casefold_map, ino);
2490
2491                 if (LINUX_S_ISDIR(inode->i_mode)) {
2492                         ext2fs_mark_inode_bitmap2(ctx->inode_dir_map, ino);
2493                         e2fsck_add_dir_info(ctx, ino, 0);
2494                         ctx->fs_directory_count++;
2495                         if (inode->i_flags & EXT4_CASEFOLD_FL)
2496                                 add_casefolded_dir(ctx, ino);
2497                 } else if (LINUX_S_ISREG (inode->i_mode)) {
2498                         ext2fs_mark_inode_bitmap2(ctx->inode_reg_map, ino);
2499                         ctx->fs_regular_count++;
2500                 } else if (LINUX_S_ISCHR (inode->i_mode) &&
2501                            e2fsck_pass1_check_device_inode(fs, inode)) {
2502                         check_extents_inlinedata(ctx, &pctx);
2503                         check_immutable(ctx, &pctx);
2504                         check_size(ctx, &pctx);
2505                         ctx->fs_chardev_count++;
2506                 } else if (LINUX_S_ISBLK (inode->i_mode) &&
2507                            e2fsck_pass1_check_device_inode(fs, inode)) {
2508                         check_extents_inlinedata(ctx, &pctx);
2509                         check_immutable(ctx, &pctx);
2510                         check_size(ctx, &pctx);
2511                         ctx->fs_blockdev_count++;
2512                 } else if (LINUX_S_ISLNK (inode->i_mode) &&
2513                            check_symlink(ctx, &pctx, ino, inode, block_buf)) {
2514                         check_immutable(ctx, &pctx);
2515                         ctx->fs_symlinks_count++;
2516                         if (inode->i_flags & EXT4_INLINE_DATA_FL) {
2517                                 FINISH_INODE_LOOP(ctx, ino, &pctx, failed_csum);
2518                                 e2fsck_pass1_check_unlock(ctx);
2519                                 continue;
2520                         } else if (ext2fs_is_fast_symlink(inode)) {
2521                                 ctx->fs_fast_symlinks_count++;
2522                                 check_blocks(ctx, &pctx, block_buf,
2523                                              &ea_ibody_quota);
2524                                 FINISH_INODE_LOOP(ctx, ino, &pctx, failed_csum);
2525                                 e2fsck_pass1_check_unlock(ctx);
2526                                 continue;
2527                         }
2528                 }
2529                 else if (LINUX_S_ISFIFO (inode->i_mode) &&
2530                          e2fsck_pass1_check_device_inode(fs, inode)) {
2531                         check_extents_inlinedata(ctx, &pctx);
2532                         check_immutable(ctx, &pctx);
2533                         check_size(ctx, &pctx);
2534                         ctx->fs_fifo_count++;
2535                 } else if ((LINUX_S_ISSOCK (inode->i_mode)) &&
2536                            e2fsck_pass1_check_device_inode(fs, inode)) {
2537                         check_extents_inlinedata(ctx, &pctx);
2538                         check_immutable(ctx, &pctx);
2539                         check_size(ctx, &pctx);
2540                         ctx->fs_sockets_count++;
2541                 } else {
2542                         e2fsck_mark_inode_bad(ctx, &pctx, PR_2_BAD_MODE);
2543                 }
2544
2545                 /* Future atime/mtime may be valid in rare cases, but are more
2546                  * likely to indicate corruption.  Don't try to fix timestamps,
2547                  * but take into consideration whether inode is corrupted.  If
2548                  * no other problems with the inode, probably it is OK. */
2549                 if (EXT4_XTIME_FUTURE(ctx, sb, inode->i_atime, ctx->time_fudge))
2550                         e2fsck_mark_inode_bad(ctx, &pctx, PR_1_INODE_BAD_TIME);
2551                 if (EXT4_XTIME_FUTURE(ctx, sb, inode->i_mtime, ctx->time_fudge))
2552                         e2fsck_mark_inode_bad(ctx, &pctx, PR_1_INODE_BAD_TIME);
2553
2554                 /* Since ctime cannot be set directly from userspace, consider
2555                  * very old/future values worse than a bad atime/mtime. Same for
2556                  * crtime, but it is checked in check_inode_extra_space(). */
2557                 if (EXT4_XTIME_FUTURE(ctx, sb, inode->i_ctime, ctx->time_fudge))
2558                         e2fsck_mark_inode_badder(ctx, &pctx,
2559                                                  PR_1_INODE_BAD_TIME);
2560                 else if (!precreated_object(inode) &&
2561                          EXT4_XTIME_ANCIENT(ctx, sb, inode->i_ctime,
2562                                             ctx->time_fudge))
2563                         e2fsck_mark_inode_badder(ctx, &pctx,
2564                                                  PR_1_INODE_BAD_TIME);
2565
2566                 /* no restart if clearing bad inode before block processing */
2567                 if (e2fsck_fix_bad_inode(ctx, &pctx)) {
2568                         e2fsck_clear_inode(ctx, ino, inode, 0, "pass1");
2569                         goto next_unlock;
2570                 }
2571
2572                 if (!(inode->i_flags & EXT4_EXTENTS_FL) &&
2573                     !(inode->i_flags & EXT4_INLINE_DATA_FL)) {
2574                         if (inode->i_block[EXT2_IND_BLOCK])
2575                                 ctx->fs_ind_count++;
2576                         if (inode->i_block[EXT2_DIND_BLOCK])
2577                                 ctx->fs_dind_count++;
2578                         if (inode->i_block[EXT2_TIND_BLOCK])
2579                                 ctx->fs_tind_count++;
2580                 }
2581                 if (!(inode->i_flags & EXT4_EXTENTS_FL) &&
2582                     !(inode->i_flags & EXT4_INLINE_DATA_FL) &&
2583                     (inode->i_block[EXT2_IND_BLOCK] ||
2584                      inode->i_block[EXT2_DIND_BLOCK] ||
2585                      inode->i_block[EXT2_TIND_BLOCK] ||
2586                      ext2fs_file_acl_block(fs, inode))) {
2587                         struct process_inode_block *itp;
2588
2589                         itp = &inodes_to_process[process_inode_count];
2590                         itp->ino = ino;
2591                         itp->ea_ibody_quota = ea_ibody_quota;
2592                         if (inode_size < sizeof(struct ext2_inode_large))
2593                                 memcpy(&itp->inode, inode, inode_size);
2594                         else
2595                                 memcpy(&itp->inode, inode, sizeof(itp->inode));
2596                         process_inode_count++;
2597                 } else
2598                         check_blocks(ctx, &pctx, block_buf, &ea_ibody_quota);
2599
2600                 FINISH_INODE_LOOP(ctx, ino, &pctx, failed_csum);
2601
2602                 if (ctx->flags & E2F_FLAG_EXPAND_EISIZE) {
2603                         struct ext2_inode_large *inode_l;
2604
2605                         inode_l = (struct ext2_inode_large *)inode;
2606
2607                         if (inode_l->i_extra_isize < ctx->want_extra_isize) {
2608                                 fix_problem(ctx, PR_1_EXPAND_EISIZE, &pctx);
2609                                 inode_exp = e2fsck_pass1_expand_eisize(ctx,
2610                                                                        inode_l,
2611                                                                        &pctx);
2612                         }
2613                         if ((inode_l->i_extra_isize < ctx->min_extra_isize) &&
2614                             inode_exp == 0)
2615                                 ctx->min_extra_isize = inode_l->i_extra_isize;
2616                 }
2617
2618                 if (e2fsck_should_abort(ctx)) {
2619                         e2fsck_pass1_check_unlock(ctx);
2620                         goto endit;
2621                 }
2622
2623                 if (process_inode_count >= ctx->process_inode_size) {
2624                         process_inodes(ctx, block_buf, inodes_to_process,
2625                                        &process_inode_count);
2626
2627                         if (e2fsck_should_abort(ctx)) {
2628                                 e2fsck_pass1_check_unlock(ctx);
2629                                 goto endit;
2630                         }
2631                 }
2632         next_unlock:
2633                 e2fsck_pass1_check_unlock(ctx);
2634         }
2635         process_inodes(ctx, block_buf, inodes_to_process,
2636                        &process_inode_count);
2637         ext2fs_close_inode_scan(scan);
2638         scan = NULL;
2639
2640         if (ctx->ea_block_quota_blocks) {
2641                 ea_refcount_free(ctx->ea_block_quota_blocks);
2642                 ctx->ea_block_quota_blocks = 0;
2643         }
2644
2645         if (ctx->ea_block_quota_inodes) {
2646                 ea_refcount_free(ctx->ea_block_quota_inodes);
2647                 ctx->ea_block_quota_inodes = 0;
2648         }
2649
2650         /* We don't need the encryption policy => ID map any more */
2651         destroy_encryption_policy_map(ctx);
2652
2653         if (ctx->flags & E2F_FLAG_RESTART) {
2654                 /*
2655                  * Only the master copy of the superblock and block
2656                  * group descriptors are going to be written during a
2657                  * restart, so set the superblock to be used to be the
2658                  * master superblock.
2659                  */
2660                 ctx->use_superblock = 0;
2661                 goto endit;
2662         }
2663
2664         if (ctx->large_dirs && !ext2fs_has_feature_largedir(ctx->fs->super)) {
2665                 ext2_filsys fs = ctx->fs;
2666
2667                 if (fix_problem(ctx, PR_2_FEATURE_LARGE_DIRS, &pctx)) {
2668                         ext2fs_set_feature_largedir(fs->super);
2669                         fs->flags &= ~EXT2_FLAG_MASTER_SB_ONLY;
2670                         ext2fs_mark_super_dirty(fs);
2671                 }
2672                 if (fs->super->s_rev_level == EXT2_GOOD_OLD_REV &&
2673                     fix_problem(ctx, PR_1_FS_REV_LEVEL, &pctx)) {
2674                         ext2fs_update_dynamic_rev(fs);
2675                         ext2fs_mark_super_dirty(fs);
2676                 }
2677         }
2678
2679         ctx->flags |= E2F_FLAG_ALLOC_OK;
2680         ext2fs_free_mem(&inodes_to_process);
2681 endit:
2682         e2fsck_use_inode_shortcuts(ctx, 0);
2683         ext2fs_free_mem(&inodes_to_process);
2684         inodes_to_process = 0;
2685
2686         if (scan)
2687                 ext2fs_close_inode_scan(scan);
2688         if (block_buf)
2689                 ext2fs_free_mem(&block_buf);
2690         if (inode)
2691                 ext2fs_free_mem(&inode);
2692
2693         /*
2694          * The l+f inode may have been cleared, so zap it now and
2695          * later passes will recalculate it if necessary
2696          */
2697         ctx->lost_and_found = 0;
2698
2699         if ((ctx->flags & E2F_FLAG_SIGNAL_MASK) == 0)
2700                 print_resource_track(ctx, _("Pass 1"), &rtrack, ctx->fs->io);
2701         else
2702                 ctx->invalid_bitmaps++;
2703 #ifdef  HAVE_PTHREAD
2704         /* reset update_thread after this thread exit */
2705         e2fsck_pass1_block_map_w_lock(ctx);
2706         if (check_mmp)
2707                 global_ctx->mmp_update_thread = 0;
2708         e2fsck_pass1_block_map_w_unlock(ctx);
2709 #endif
2710 }
2711
2712 #ifdef HAVE_PTHREAD
2713 static errcode_t e2fsck_pass1_copy_bitmap(ext2_filsys fs, ext2fs_generic_bitmap *src,
2714                                           ext2fs_generic_bitmap *dest)
2715 {
2716         errcode_t ret;
2717
2718         ret = ext2fs_copy_bitmap(*src, dest);
2719         if (ret)
2720                 return ret;
2721
2722         (*dest)->fs = fs;
2723
2724         return 0;
2725 }
2726
2727 static void e2fsck_pass1_free_bitmap(ext2fs_generic_bitmap *bitmap)
2728 {
2729         if (*bitmap) {
2730                 ext2fs_free_generic_bmap(*bitmap);
2731                 *bitmap = NULL;
2732         }
2733
2734 }
2735
2736 static errcode_t e2fsck_pass1_merge_bitmap(ext2_filsys fs, ext2fs_generic_bitmap *src,
2737                                           ext2fs_generic_bitmap *dest)
2738 {
2739         errcode_t ret = 0;
2740
2741         if (*src) {
2742                 if (*dest == NULL) {
2743                         *dest = *src;
2744                         *src = NULL;
2745                 } else {
2746                         ret = ext2fs_merge_bitmap(*src, *dest, NULL, NULL);
2747                         if (ret)
2748                                 return ret;
2749                 }
2750                 (*dest)->fs = fs;
2751         }
2752
2753         return 0;
2754 }
2755
2756 static errcode_t e2fsck_pass1_copy_fs(ext2_filsys dest, e2fsck_t src_context,
2757                                       ext2_filsys src)
2758 {
2759         errcode_t       retval;
2760
2761         memcpy(dest, src, sizeof(struct struct_ext2_filsys));
2762         dest->inode_map = NULL;
2763         dest->block_map = NULL;
2764         dest->badblocks = NULL;
2765         if (dest->dblist)
2766                 dest->dblist->fs = dest;
2767         if (src->block_map) {
2768                 retval = e2fsck_pass1_copy_bitmap(dest, &src->block_map,
2769                                                   &dest->block_map);
2770                 if (retval)
2771                         return retval;
2772         }
2773         if (src->inode_map) {
2774                 retval = e2fsck_pass1_copy_bitmap(dest, &src->inode_map,
2775                                                   &dest->inode_map);
2776                 if (retval)
2777                         return retval;
2778         }
2779
2780         if (src->badblocks) {
2781                 retval = ext2fs_badblocks_copy(src->badblocks,
2782                                                &dest->badblocks);
2783                 if (retval)
2784                         return retval;
2785         }
2786
2787         /* disable it for now */
2788         src_context->openfs_flags &= ~EXT2_FLAG_EXCLUSIVE;
2789         retval = ext2fs_open_channel(dest, src_context->io_options,
2790                                      src_context->io_manager,
2791                                      src_context->openfs_flags,
2792                                      src->io->block_size);
2793         if (retval)
2794                 return retval;
2795
2796         /* Block size might not be default */
2797         io_channel_set_blksize(dest->io, src->io->block_size);
2798         ehandler_init(dest->io);
2799
2800         assert(dest->io->magic == src->io->magic);
2801         assert(dest->io->manager == src->io->manager);
2802         assert(strcmp(dest->io->name, src->io->name) == 0);
2803         assert(dest->io->block_size == src->io->block_size);
2804         assert(dest->io->read_error == src->io->read_error);
2805         assert(dest->io->write_error == src->io->write_error);
2806         assert(dest->io->refcount == src->io->refcount);
2807         assert(dest->io->flags == src->io->flags);
2808         assert(dest->io->app_data == dest);
2809         assert(src->io->app_data == src);
2810         assert(dest->io->align == src->io->align);
2811
2812         /* The data should be written to disk immediately */
2813         dest->io->flags |= CHANNEL_FLAGS_WRITETHROUGH;
2814         /* icache will be rebuilt if needed, so do not copy from @src */
2815         src->icache = NULL;
2816         return 0;
2817 }
2818
2819 static int e2fsck_pass1_merge_fs(ext2_filsys dest, ext2_filsys src)
2820 {
2821         struct ext2_inode_cache *icache = dest->icache;
2822         errcode_t retval = 0;
2823         io_channel dest_io;
2824         io_channel dest_image_io;
2825         ext2fs_inode_bitmap inode_map;
2826         ext2fs_block_bitmap block_map;
2827         ext2_badblocks_list badblocks;
2828         ext2_dblist dblist;
2829         int flags;
2830         e2fsck_t dest_ctx = dest->priv_data;
2831
2832         dest_io = dest->io;
2833         dest_image_io = dest->image_io;
2834         inode_map = dest->inode_map;
2835         block_map = dest->block_map;
2836         badblocks = dest->badblocks;
2837         dblist = dest->dblist;
2838         flags = dest->flags;
2839
2840         memcpy(dest, src, sizeof(struct struct_ext2_filsys));
2841         dest->io = dest_io;
2842         dest->image_io = dest_image_io;
2843         dest->icache = icache;
2844         dest->inode_map = inode_map;
2845         dest->block_map = block_map;
2846         dest->badblocks = badblocks;
2847         dest->dblist = dblist;
2848         dest->priv_data = dest_ctx;
2849         if (dest->dblist)
2850                 dest->dblist->fs = dest;
2851         dest->flags = src->flags | flags;
2852         if (!(src->flags & EXT2_FLAG_VALID) || !(flags & EXT2_FLAG_VALID))
2853                 ext2fs_unmark_valid(dest);
2854
2855         if (src->icache) {
2856                 ext2fs_free_inode_cache(src->icache);
2857                 src->icache = NULL;
2858         }
2859
2860         retval = e2fsck_pass1_merge_bitmap(dest, &src->inode_map,
2861                                            &dest->inode_map);
2862         if (retval)
2863                 goto out;
2864
2865         retval = e2fsck_pass1_merge_bitmap(dest, &src->block_map,
2866                                           &dest->block_map);
2867         if (retval)
2868                 goto out;
2869
2870         if (src->dblist) {
2871                 if (dest->dblist) {
2872                         retval = ext2fs_merge_dblist(src->dblist,
2873                                                      dest->dblist);
2874                         if (retval)
2875                                 goto out;
2876                 } else {
2877                         dest->dblist = src->dblist;
2878                         dest->dblist->fs = dest;
2879                         src->dblist = NULL;
2880                 }
2881         }
2882
2883         if (src->badblocks) {
2884                 if (dest->badblocks == NULL)
2885                         retval = ext2fs_badblocks_copy(src->badblocks,
2886                                                        &dest->badblocks);
2887                 else
2888                         retval = ext2fs_badblocks_merge(src->badblocks,
2889                                                         dest->badblocks);
2890         }
2891 out:
2892         io_channel_close(src->io);
2893         if (src->inode_map)
2894                 ext2fs_free_generic_bmap(src->inode_map);
2895         if (src->block_map)
2896                 ext2fs_free_generic_bmap(src->block_map);
2897         if (src->badblocks)
2898                 ext2fs_badblocks_list_free(src->badblocks);
2899         if (src->dblist)
2900                 ext2fs_free_dblist(src->dblist);
2901
2902         return retval;
2903 }
2904
2905 static void e2fsck_pass1_copy_invalid_bitmaps(e2fsck_t global_ctx,
2906                                               e2fsck_t thread_ctx)
2907 {
2908         dgrp_t i, j;
2909         dgrp_t grp_start = thread_ctx->thread_info.et_group_start;
2910         dgrp_t grp_end = thread_ctx->thread_info.et_group_end;
2911         dgrp_t total = grp_end - grp_start;
2912
2913         thread_ctx->invalid_inode_bitmap_flag =
2914                         e2fsck_allocate_memory(global_ctx, sizeof(int) * total,
2915                                                 "invalid_inode_bitmap");
2916         thread_ctx->invalid_block_bitmap_flag =
2917                         e2fsck_allocate_memory(global_ctx, sizeof(int) * total,
2918                                                "invalid_block_bitmap");
2919         thread_ctx->invalid_inode_table_flag =
2920                         e2fsck_allocate_memory(global_ctx, sizeof(int) * total,
2921                                                "invalid_inode_table");
2922
2923         memcpy(thread_ctx->invalid_block_bitmap_flag,
2924                &global_ctx->invalid_block_bitmap_flag[grp_start],
2925                total * sizeof(int));
2926         memcpy(thread_ctx->invalid_inode_bitmap_flag,
2927                &global_ctx->invalid_inode_bitmap_flag[grp_start],
2928                total * sizeof(int));
2929         memcpy(thread_ctx->invalid_inode_table_flag,
2930                &global_ctx->invalid_inode_table_flag[grp_start],
2931                total * sizeof(int));
2932
2933         thread_ctx->invalid_bitmaps = 0;
2934         for (i = grp_start, j = 0; i < grp_end; i++, j++) {
2935                 if (thread_ctx->invalid_block_bitmap_flag[j])
2936                         thread_ctx->invalid_bitmaps++;
2937                 if (thread_ctx->invalid_inode_bitmap_flag[j])
2938                         thread_ctx->invalid_bitmaps++;
2939                 if (thread_ctx->invalid_inode_table_flag[j])
2940                         thread_ctx->invalid_bitmaps++;
2941         }
2942 }
2943
2944 static void e2fsck_pass1_merge_invalid_bitmaps(e2fsck_t global_ctx,
2945                                                e2fsck_t thread_ctx)
2946 {
2947         dgrp_t i, j;
2948         dgrp_t grp_start = thread_ctx->thread_info.et_group_start;
2949         dgrp_t grp_end = thread_ctx->thread_info.et_group_end;
2950         dgrp_t total = grp_end - grp_start;
2951
2952         memcpy(&global_ctx->invalid_block_bitmap_flag[grp_start],
2953                thread_ctx->invalid_block_bitmap_flag, total * sizeof(int));
2954         memcpy(&global_ctx->invalid_inode_bitmap_flag[grp_start],
2955                thread_ctx->invalid_inode_bitmap_flag, total * sizeof(int));
2956         memcpy(&global_ctx->invalid_inode_table_flag[grp_start],
2957                thread_ctx->invalid_inode_table_flag, total * sizeof(int));
2958         global_ctx->invalid_bitmaps += thread_ctx->invalid_bitmaps;
2959 }
2960
2961 static errcode_t e2fsck_pass1_thread_prepare(e2fsck_t global_ctx, e2fsck_t *thread_ctx,
2962                                              int thread_index, int num_threads,
2963                                              dgrp_t average_group)
2964 {
2965         errcode_t               retval;
2966         e2fsck_t                thread_context;
2967         ext2_filsys             thread_fs;
2968         ext2_filsys             global_fs = global_ctx->fs;
2969         struct e2fsck_thread    *tinfo;
2970
2971         assert(global_ctx->inode_used_map == NULL);
2972         assert(global_ctx->inode_dir_map == NULL);
2973         assert(global_ctx->inode_bb_map == NULL);
2974         assert(global_ctx->inode_imagic_map == NULL);
2975         assert(global_ctx->inode_reg_map == NULL);
2976         assert(global_ctx->inodes_to_rebuild == NULL);
2977
2978         assert(global_ctx->block_found_map != NULL);
2979         assert(global_ctx->block_metadata_map != NULL);
2980         assert(global_ctx->block_dup_map != NULL);
2981         assert(global_ctx->block_ea_map == NULL);
2982         assert(global_ctx->fs->dblist == NULL);
2983
2984         retval = ext2fs_get_mem(sizeof(struct e2fsck_struct), &thread_context);
2985         if (retval) {
2986                 com_err(global_ctx->program_name, retval, "while allocating memory");
2987                 return retval;
2988         }
2989         memcpy(thread_context, global_ctx, sizeof(struct e2fsck_struct));
2990         thread_context->block_dup_map = NULL;
2991         thread_context->casefolded_dirs = NULL;
2992
2993         retval = e2fsck_allocate_block_bitmap(global_ctx->fs,
2994                                 _("in-use block map"), EXT2FS_BMAP64_RBTREE,
2995                                 "block_found_map", &thread_context->block_found_map);
2996         if (retval)
2997                 goto out_context;
2998
2999         thread_context->global_ctx = global_ctx;
3000         retval = ext2fs_get_mem(sizeof(struct struct_ext2_filsys), &thread_fs);
3001         if (retval) {
3002                 com_err(global_ctx->program_name, retval, "while allocating memory");
3003                 goto out_context;
3004         }
3005
3006         io_channel_flush_cleanup(global_fs->io);
3007         retval = e2fsck_pass1_copy_fs(thread_fs, global_ctx, global_fs);
3008         if (retval) {
3009                 com_err(global_ctx->program_name, retval, "while copying fs");
3010                 goto out_fs;
3011         }
3012         thread_fs->priv_data = thread_context;
3013
3014         thread_context->thread_info.et_thread_index = thread_index;
3015         set_up_logging(thread_context);
3016
3017         tinfo = &thread_context->thread_info;
3018         tinfo->et_group_start = average_group * thread_index;
3019         if (thread_index == global_fs->fs_num_threads - 1)
3020                 tinfo->et_group_end = thread_fs->group_desc_count;
3021         else
3022                 tinfo->et_group_end = average_group * (thread_index + 1);
3023         tinfo->et_group_next = tinfo->et_group_start;
3024         tinfo->et_inode_number = 0;
3025         tinfo->et_log_buf[0] = '\0';
3026         tinfo->et_log_length = 0;
3027         if (thread_context->options & E2F_OPT_MULTITHREAD)
3028                 log_out(thread_context, _("Scan group range [%d, %d)\n"),
3029                         tinfo->et_group_start, tinfo->et_group_end);
3030         thread_context->fs = thread_fs;
3031         retval = quota_init_context(&thread_context->qctx, thread_fs, 0);
3032         if (retval) {
3033                 com_err(global_ctx->program_name, retval,
3034                         "while init quota context");
3035                 goto out_fs;
3036         }
3037         *thread_ctx = thread_context;
3038         e2fsck_pass1_copy_invalid_bitmaps(global_ctx, thread_context);
3039         return 0;
3040 out_fs:
3041         ext2fs_free_mem(&thread_fs);
3042 out_context:
3043         if (thread_context->block_found_map)
3044                 ext2fs_free_mem(&thread_context->block_found_map);
3045         ext2fs_free_mem(&thread_context);
3046         return retval;
3047 }
3048
3049 static void e2fsck_pass1_merge_dir_info(e2fsck_t global_ctx, e2fsck_t thread_ctx)
3050 {
3051         if (thread_ctx->dir_info == NULL)
3052                 return;
3053
3054         if (global_ctx->dir_info == NULL) {
3055                 global_ctx->dir_info = thread_ctx->dir_info;
3056                 thread_ctx->dir_info = NULL;
3057                 return;
3058         }
3059
3060         e2fsck_merge_dir_info(global_ctx, thread_ctx->dir_info,
3061                               global_ctx->dir_info);
3062 }
3063
3064 static void e2fsck_pass1_merge_dx_dir(e2fsck_t global_ctx, e2fsck_t thread_ctx)
3065 {
3066         if (thread_ctx->dx_dir_info == NULL)
3067                 return;
3068
3069         if (global_ctx->dx_dir_info == NULL) {
3070                 global_ctx->dx_dir_info = thread_ctx->dx_dir_info;
3071                 global_ctx->dx_dir_info_size = thread_ctx->dx_dir_info_size;
3072                 global_ctx->dx_dir_info_count = thread_ctx->dx_dir_info_count;
3073                 thread_ctx->dx_dir_info = NULL;
3074                 return;
3075         }
3076
3077         e2fsck_merge_dx_dir(global_ctx, thread_ctx);
3078 }
3079
3080 static inline errcode_t
3081 e2fsck_pass1_merge_icount(ext2_icount_t *dest_icount,
3082                           ext2_icount_t *src_icount)
3083 {
3084         if (*src_icount) {
3085                 if (*dest_icount == NULL) {
3086                         *dest_icount = *src_icount;
3087                         *src_icount = NULL;
3088                 } else {
3089                         errcode_t ret;
3090
3091                         ret = ext2fs_icount_merge(*src_icount,
3092                                                   *dest_icount);
3093                         if (ret)
3094                                 return ret;
3095                 }
3096         }
3097
3098         return 0;
3099 }
3100
3101 static errcode_t e2fsck_pass1_merge_icounts(e2fsck_t global_ctx, e2fsck_t thread_ctx)
3102 {
3103         errcode_t ret;
3104
3105         ret = e2fsck_pass1_merge_icount(&global_ctx->inode_count,
3106                                         &thread_ctx->inode_count);
3107         if (ret)
3108                 return ret;
3109         ret = e2fsck_pass1_merge_icount(&global_ctx->inode_link_info,
3110                                         &thread_ctx->inode_link_info);
3111         if (ret)
3112                 return ret;
3113
3114         ret = e2fsck_pass1_merge_icount(&global_ctx->inode_badness,
3115                                         &thread_ctx->inode_badness);
3116
3117         return ret;
3118 }
3119
3120 static errcode_t e2fsck_pass1_merge_dirs_to_hash(e2fsck_t global_ctx,
3121                                                  e2fsck_t thread_ctx)
3122 {
3123         errcode_t retval = 0;
3124
3125         if (!thread_ctx->dirs_to_hash)
3126                 return 0;
3127
3128         if (!global_ctx->dirs_to_hash)
3129                 retval = ext2fs_badblocks_copy(thread_ctx->dirs_to_hash,
3130                                                &global_ctx->dirs_to_hash);
3131         else
3132                 retval = ext2fs_badblocks_merge(thread_ctx->dirs_to_hash,
3133                                                 global_ctx->dirs_to_hash);
3134
3135         return retval;
3136 }
3137
3138 static errcode_t e2fsck_pass1_merge_ea_inode_refs(e2fsck_t global_ctx,
3139                                                   e2fsck_t thread_ctx)
3140 {
3141         ea_value_t count;
3142         blk64_t blk;
3143         errcode_t retval;
3144
3145         if (!thread_ctx->ea_inode_refs)
3146                 return 0;
3147
3148         if (!global_ctx->ea_inode_refs) {
3149                 global_ctx->ea_inode_refs = thread_ctx->ea_inode_refs;
3150                 thread_ctx->ea_inode_refs = NULL;
3151                 return 0;
3152         }
3153
3154         ea_refcount_intr_begin(thread_ctx->ea_inode_refs);
3155         while (1) {
3156                 if ((blk = ea_refcount_intr_next(thread_ctx->ea_inode_refs,
3157                                                  &count)) == 0)
3158                         break;
3159                 if (!global_ctx->block_ea_map ||
3160                     !ext2fs_fast_test_block_bitmap2(global_ctx->block_ea_map,
3161                                                     blk)) {
3162                         retval = ea_refcount_store(global_ctx->ea_inode_refs,
3163                                                    blk, count);
3164                         if (retval)
3165                                 return retval;
3166                 }
3167         }
3168
3169         return retval;
3170 }
3171
3172 static ea_value_t ea_refcount_usage(e2fsck_t ctx, blk64_t blk,
3173                                     ea_value_t *orig)
3174 {
3175         ea_value_t count_cur;
3176         ea_value_t count_extra = 0;
3177         ea_value_t count_orig;
3178
3179         ea_refcount_fetch(ctx->refcount_orig, blk, &count_orig);
3180         ea_refcount_fetch(ctx->refcount, blk, &count_cur);
3181         /* most of time this is not needed */
3182         if (ctx->refcount_extra && count_cur == 0)
3183                 ea_refcount_fetch(ctx->refcount_extra, blk, &count_extra);
3184
3185         if (!count_orig)
3186                 count_orig = *orig;
3187         else if (orig)
3188                 *orig = count_orig;
3189
3190         return count_orig + count_extra - count_cur;
3191 }
3192
3193 static errcode_t e2fsck_pass1_merge_ea_refcount(e2fsck_t global_ctx,
3194                                                 e2fsck_t thread_ctx)
3195 {
3196         ea_value_t count;
3197         blk64_t blk;
3198         errcode_t retval = 0;
3199
3200         if (!thread_ctx->refcount)
3201                 return 0;
3202
3203         if (!global_ctx->refcount) {
3204                 global_ctx->refcount = thread_ctx->refcount;
3205                 thread_ctx->refcount = NULL;
3206                 global_ctx->refcount_extra = thread_ctx->refcount;
3207                 thread_ctx->refcount_extra = NULL;
3208                 return 0;
3209         }
3210
3211         ea_refcount_intr_begin(thread_ctx->refcount);
3212         while (1) {
3213                 if ((blk = ea_refcount_intr_next(thread_ctx->refcount,
3214                                                  &count)) == 0)
3215                         break;
3216                 /**
3217                  * this EA has never seen before, so just store its
3218                  * refcount and refcount_extra into global_ctx if needed.
3219                  */
3220                 if (!global_ctx->block_ea_map ||
3221                     !ext2fs_fast_test_block_bitmap2(global_ctx->block_ea_map,
3222                                                     blk)) {
3223                         ea_value_t extra;
3224
3225                         retval = ea_refcount_store(global_ctx->refcount,
3226                                                    blk, count);
3227                         if (retval)
3228                                 return retval;
3229
3230                         if (count > 0 || !thread_ctx->refcount_extra)
3231                                 continue;
3232                         ea_refcount_fetch(thread_ctx->refcount_extra, blk,
3233                                           &extra);
3234                         if (extra == 0)
3235                                 continue;
3236
3237                         if (!global_ctx->refcount_extra) {
3238                                 retval = ea_refcount_create(0,
3239                                                 &global_ctx->refcount_extra);
3240                                 if (retval)
3241                                         return retval;
3242                         }
3243                         retval = ea_refcount_store(global_ctx->refcount_extra,
3244                                                    blk, extra);
3245                         if (retval)
3246                                 return retval;
3247                 } else {
3248                         ea_value_t orig;
3249                         ea_value_t thread_usage;
3250                         ea_value_t global_usage;
3251                         ea_value_t new;
3252
3253                         thread_usage = ea_refcount_usage(thread_ctx,
3254                                                          blk, &orig);
3255                         global_usage = ea_refcount_usage(global_ctx,
3256                                                          blk, &orig);
3257                         if (thread_usage + global_usage <= orig) {
3258                                 new = orig - thread_usage - global_usage;
3259                                 retval = ea_refcount_store(global_ctx->refcount,
3260                                                            blk, new);
3261                                 if (retval)
3262                                         return retval;
3263                                 continue;
3264                         }
3265                         /* update it is as zero */
3266                         retval = ea_refcount_store(global_ctx->refcount,
3267                                                    blk, 0);
3268                         if (retval)
3269                                 return retval;
3270                         /* Ooops, this EA was referenced more than it stated */
3271                         if (!global_ctx->refcount_extra) {
3272                                 retval = ea_refcount_create(0,
3273                                                 &global_ctx->refcount_extra);
3274                                 if (retval)
3275                                         return retval;
3276                         }
3277                         new = global_usage + thread_usage - orig;
3278                         retval = ea_refcount_store(global_ctx->refcount_extra,
3279                                                    blk, new);
3280                         if (retval)
3281                                 return retval;
3282                 }
3283         }
3284
3285         return retval;
3286 }
3287
3288 static errcode_t e2fsck_pass1_merge_casefolded_dirs(e2fsck_t global_ctx,
3289                                                    e2fsck_t thread_ctx)
3290 {
3291         errcode_t retval = 0;
3292
3293         if (!thread_ctx->casefolded_dirs)
3294                 return 0;
3295
3296         if (!global_ctx->casefolded_dirs)
3297                 retval = ext2fs_badblocks_copy(thread_ctx->casefolded_dirs,
3298                                                &global_ctx->casefolded_dirs);
3299         else
3300                 retval = ext2fs_badblocks_merge(thread_ctx->casefolded_dirs,
3301                                                 global_ctx->casefolded_dirs);
3302
3303         return retval;
3304 }
3305
3306 static errcode_t e2fsck_pass1_merge_context(e2fsck_t global_ctx,
3307                                             e2fsck_t thread_ctx)
3308 {
3309         ext2_filsys global_fs = global_ctx->fs;
3310         errcode_t retval;
3311         int i;
3312
3313         global_ctx->fs_directory_count += thread_ctx->fs_directory_count;
3314         global_ctx->fs_regular_count += thread_ctx->fs_regular_count;
3315         global_ctx->fs_blockdev_count += thread_ctx->fs_blockdev_count;
3316         global_ctx->fs_chardev_count += thread_ctx->fs_chardev_count;
3317         global_ctx->fs_links_count += thread_ctx->fs_links_count;
3318         global_ctx->fs_symlinks_count += thread_ctx->fs_symlinks_count;
3319         global_ctx->fs_fast_symlinks_count += thread_ctx->fs_fast_symlinks_count;
3320         global_ctx->fs_fifo_count += thread_ctx->fs_fifo_count;
3321         global_ctx->fs_total_count += thread_ctx->fs_total_count;
3322         global_ctx->fs_badblocks_count += thread_ctx->fs_badblocks_count;
3323         global_ctx->fs_sockets_count += thread_ctx->fs_sockets_count;
3324         global_ctx->fs_ind_count += thread_ctx->fs_ind_count;
3325         global_ctx->fs_dind_count += thread_ctx->fs_dind_count;
3326         global_ctx->fs_tind_count += thread_ctx->fs_tind_count;
3327         global_ctx->fs_fragmented += thread_ctx->fs_fragmented;
3328         global_ctx->fs_fragmented_dir += thread_ctx->fs_fragmented_dir;
3329         global_ctx->large_files += thread_ctx->large_files;
3330         /* threads might enable E2F_OPT_YES */
3331         global_ctx->options |= thread_ctx->options;
3332         global_ctx->flags |= thread_ctx->flags;
3333         /*
3334          * The l+f inode may have been cleared, so zap it now and
3335          * later passes will recalculate it if necessary
3336          */
3337         global_ctx->lost_and_found = 0;
3338         /* merge extent depth count */
3339         for (i = 0; i < MAX_EXTENT_DEPTH_COUNT; i++)
3340                 global_ctx->extent_depth_count[i] +=
3341                         thread_ctx->extent_depth_count[i];
3342
3343         e2fsck_pass1_merge_dir_info(global_ctx, thread_ctx);
3344         e2fsck_pass1_merge_dx_dir(global_ctx, thread_ctx);
3345
3346         retval = e2fsck_pass1_merge_fs(global_ctx->fs, thread_ctx->fs);
3347         if (retval) {
3348                 com_err(global_ctx->program_name, 0, _("while merging fs\n"));
3349                 return retval;
3350         }
3351         retval = e2fsck_pass1_merge_icounts(global_ctx, thread_ctx);
3352         if (retval) {
3353                 com_err(global_ctx->program_name, 0,
3354                         _("while merging icounts\n"));
3355                 return retval;
3356         }
3357
3358         retval = e2fsck_pass1_merge_dirs_to_hash(global_ctx, thread_ctx);
3359         if (retval) {
3360                 com_err(global_ctx->program_name, 0,
3361                         _("while merging dirs to hash\n"));
3362                 return retval;
3363         }
3364
3365         e2fsck_pass1_merge_ea_inode_refs(global_ctx, thread_ctx);
3366         e2fsck_pass1_merge_ea_refcount(global_ctx, thread_ctx);
3367         retval = quota_merge_and_update_usage(global_ctx->qctx,
3368                                               thread_ctx->qctx);
3369         if (retval)
3370                 return retval;
3371
3372         retval = e2fsck_pass1_merge_casefolded_dirs(global_ctx, thread_ctx);
3373         if (retval) {
3374                 com_err(global_ctx->program_name, 0,
3375                         _("while merging casefolded dirs\n"));
3376                 return retval;
3377         }
3378
3379         e2fsck_pass1_merge_invalid_bitmaps(global_ctx, thread_ctx);
3380
3381         retval = e2fsck_pass1_merge_bitmap(global_fs,
3382                                 &thread_ctx->inode_used_map,
3383                                 &global_ctx->inode_used_map);
3384         if (retval)
3385                 return retval;
3386
3387         retval = e2fsck_pass1_merge_bitmap(global_fs,
3388                                         &thread_ctx->inode_dir_map,
3389                                         &global_ctx->inode_dir_map);
3390         if (retval)
3391                 return retval;
3392         retval = e2fsck_pass1_merge_bitmap(global_fs,
3393                                 &thread_ctx->inode_bb_map,
3394                                 &global_ctx->inode_bb_map);
3395         if (retval)
3396                 return retval;
3397         retval = e2fsck_pass1_merge_bitmap(global_fs,
3398                                 &thread_ctx->inode_imagic_map,
3399                                 &global_ctx->inode_imagic_map);
3400         if (retval)
3401                 return retval;
3402         retval = e2fsck_pass1_merge_bitmap(global_fs,
3403                                 &thread_ctx->inode_reg_map,
3404                                 &global_ctx->inode_reg_map);
3405         if (retval)
3406                 return retval;
3407         retval = e2fsck_pass1_merge_bitmap(global_fs,
3408                                 &thread_ctx->inodes_to_rebuild,
3409                                 &global_ctx->inodes_to_rebuild);
3410         if (retval)
3411                 return retval;
3412         retval = e2fsck_pass1_merge_bitmap(global_fs,
3413                                 &thread_ctx->block_ea_map,
3414                                 &global_ctx->block_ea_map);
3415         if (retval)
3416                 return retval;
3417
3418         if (ext2fs_has_feature_shared_blocks(global_fs->super) &&
3419             !(global_ctx->options & E2F_OPT_UNSHARE_BLOCKS))
3420                 return 0;
3421         /*
3422          * This need be done after merging block_ea_map
3423          * because ea block might be shared, we need exclude
3424          * them from dup blocks.
3425          */
3426         e2fsck_pass1_block_map_w_lock(thread_ctx);
3427         retval = ext2fs_merge_bitmap(thread_ctx->block_found_map,
3428                                      global_ctx->block_found_map,
3429                                      global_ctx->block_dup_map,
3430                                      global_ctx->block_ea_map);
3431         e2fsck_pass1_block_map_w_unlock(thread_ctx);
3432         if (retval == EEXIST)
3433                 global_ctx->flags |= E2F_FLAG_DUP_BLOCK;
3434
3435         return 0;
3436 }
3437
3438 static int e2fsck_pass1_thread_join(e2fsck_t global_ctx, e2fsck_t thread_ctx)
3439 {
3440         errcode_t       retval;
3441
3442         retval = e2fsck_pass1_merge_context(global_ctx, thread_ctx);
3443         ext2fs_free_mem(&thread_ctx->fs);
3444         if (thread_ctx->logf)
3445                 fclose(thread_ctx->logf);
3446         if (thread_ctx->problem_logf) {
3447                 fputs("</problem_log>\n", thread_ctx->problem_logf);
3448                 fclose(thread_ctx->problem_logf);
3449         }
3450
3451         quota_release_context(&thread_ctx->qctx);
3452         /*
3453          * @block_metadata_map and @block_dup_map are
3454          * shared, so we don't free them.
3455          */
3456         thread_ctx->block_metadata_map = NULL;
3457         thread_ctx->block_dup_map = NULL;
3458         e2fsck_reset_context(thread_ctx);
3459         ext2fs_free_mem(&thread_ctx);
3460
3461         return retval;
3462 }
3463
3464 static int e2fsck_pass1_threads_join(struct e2fsck_thread_info *infos,
3465                                      e2fsck_t global_ctx)
3466 {
3467         errcode_t rc;
3468         errcode_t ret = 0;
3469         struct e2fsck_thread_info *pinfo;
3470         int num_threads = global_ctx->pfs_num_threads;
3471         int i;
3472
3473         /* merge invalid bitmaps will recalculate it */
3474         global_ctx->invalid_bitmaps = 0;
3475         for (i = 0; i < num_threads; i++) {
3476                 pinfo = &infos[i];
3477
3478                 if (!pinfo->eti_started)
3479                         continue;
3480
3481                 rc = pthread_join(pinfo->eti_thread_id, NULL);
3482                 if (rc) {
3483                         com_err(global_ctx->program_name, rc,
3484                                 _("while joining thread\n"));
3485                         if (ret == 0)
3486                                 ret = rc;
3487                 }
3488                 rc = e2fsck_pass1_thread_join(global_ctx, infos[i].eti_thread_ctx);
3489                 if (rc) {
3490                         com_err(global_ctx->program_name, rc,
3491                                 _("while joining pass1 thread\n"));
3492                         if (ret == 0)
3493                                 ret = rc;
3494                 }
3495         }
3496         free(infos);
3497
3498         return ret;
3499 }
3500
3501 static void *e2fsck_pass1_thread(void *arg)
3502 {
3503         struct e2fsck_thread_info       *info = arg;
3504         e2fsck_t                         thread_ctx = info->eti_thread_ctx;
3505 #ifdef DEBUG_THREADS
3506         struct e2fsck_thread_debug      *thread_debug = info->eti_debug;
3507 #endif
3508
3509 #ifdef DEBUG_THREADS
3510         pthread_mutex_lock(&thread_debug->etd_mutex);
3511         while (info->eti_thread_index > thread_debug->etd_finished_threads) {
3512                 pthread_cond_wait(&thread_debug->etd_cond,
3513                                   &thread_debug->etd_mutex);
3514         }
3515         pthread_mutex_unlock(&thread_debug->etd_mutex);
3516 #endif
3517
3518 #ifdef HAVE_SETJMP_H
3519         /*
3520          * When fatal_error() happens, jump to here. The thread
3521          * context's flags will be saved, but its abort_loc will
3522          * be overwritten by original jump buffer for the later
3523          * tests.
3524          */
3525         if (setjmp(thread_ctx->abort_loc)) {
3526                 thread_ctx->flags &= ~E2F_FLAG_SETJMP_OK;
3527                 goto out;
3528         }
3529         thread_ctx->flags |= E2F_FLAG_SETJMP_OK;
3530 #endif
3531
3532         e2fsck_pass1_run(thread_ctx);
3533
3534 out:
3535         if (thread_ctx->options & E2F_OPT_MULTITHREAD)
3536                 log_out(thread_ctx,
3537                         _("Scanned group range [%u, %u), inodes %u\n"),
3538                         thread_ctx->thread_info.et_group_start,
3539                         thread_ctx->thread_info.et_group_end,
3540                         thread_ctx->thread_info.et_inode_number);
3541
3542 #ifdef DEBUG_THREADS
3543         pthread_mutex_lock(&thread_debug->etd_mutex);
3544         thread_debug->etd_finished_threads++;
3545         pthread_cond_broadcast(&thread_debug->etd_cond);
3546         pthread_mutex_unlock(&thread_debug->etd_mutex);
3547 #endif
3548
3549         return NULL;
3550 }
3551
3552 static dgrp_t ext2fs_get_avg_group(ext2_filsys fs)
3553 {
3554 #ifdef HAVE_PTHREAD
3555         dgrp_t average_group;
3556         unsigned flexbg_size;
3557
3558         if (fs->fs_num_threads <= 1)
3559                 return fs->group_desc_count;
3560
3561         average_group = fs->group_desc_count / fs->fs_num_threads;
3562         if (average_group <= 1)
3563                 return 1;
3564
3565         if (ext2fs_has_feature_flex_bg(fs->super)) {
3566                 int times = 1;
3567
3568                 flexbg_size = 1 << fs->super->s_log_groups_per_flex;
3569                 if (average_group % flexbg_size) {
3570                         times = average_group / flexbg_size;
3571                         average_group = times * flexbg_size;
3572                 }
3573         }
3574
3575         return average_group;
3576 #else
3577         return fs->group_desc_count;
3578 #endif
3579 }
3580
3581 static int e2fsck_pass1_threads_start(struct e2fsck_thread_info **pinfo,
3582                                       e2fsck_t global_ctx)
3583 {
3584         struct e2fsck_thread_info       *infos;
3585         pthread_attr_t                   attr;
3586         errcode_t                        retval;
3587         errcode_t                        ret;
3588         struct e2fsck_thread_info       *tmp_pinfo;
3589         int                              i;
3590         e2fsck_t                         thread_ctx;
3591         dgrp_t                           average_group;
3592         int num_threads = global_ctx->pfs_num_threads;
3593 #ifdef DEBUG_THREADS
3594         struct e2fsck_thread_debug       thread_debug =
3595                 {PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER, 0};
3596
3597         thread_debug.etd_finished_threads = 0;
3598 #endif
3599
3600         retval = pthread_attr_init(&attr);
3601         if (retval) {
3602                 com_err(global_ctx->program_name, retval,
3603                         _("while setting pthread attribute\n"));
3604                 return retval;
3605         }
3606
3607         infos = calloc(num_threads, sizeof(struct e2fsck_thread_info));
3608         if (infos == NULL) {
3609                 retval = -ENOMEM;
3610                 com_err(global_ctx->program_name, retval,
3611                         _("while allocating memory for threads\n"));
3612                 pthread_attr_destroy(&attr);
3613                 return retval;
3614         }
3615
3616         average_group = ext2fs_get_avg_group(global_ctx->fs);
3617         for (i = 0; i < num_threads; i++) {
3618                 tmp_pinfo = &infos[i];
3619                 tmp_pinfo->eti_thread_index = i;
3620 #ifdef DEBUG_THREADS
3621                 tmp_pinfo->eti_debug = &thread_debug;
3622 #endif
3623                 retval = e2fsck_pass1_thread_prepare(global_ctx, &thread_ctx,
3624                                                      i, num_threads,
3625                                                      average_group);
3626                 if (retval) {
3627                         com_err(global_ctx->program_name, retval,
3628                                 _("while preparing pass1 thread\n"));
3629                         break;
3630                 }
3631                 tmp_pinfo->eti_thread_ctx = thread_ctx;
3632
3633                 retval = pthread_create(&tmp_pinfo->eti_thread_id, &attr,
3634                                         &e2fsck_pass1_thread, tmp_pinfo);
3635                 if (retval) {
3636                         com_err(global_ctx->program_name, retval,
3637                                 _("while creating thread\n"));
3638                         e2fsck_pass1_thread_join(global_ctx, thread_ctx);
3639                         break;
3640                 }
3641
3642                 tmp_pinfo->eti_started = 1;
3643         }
3644
3645         /* destroy the thread attribute object, since it is no longer needed */
3646         ret = pthread_attr_destroy(&attr);
3647         if (ret) {
3648                 com_err(global_ctx->program_name, ret,
3649                         _("while destroying thread attribute\n"));
3650                 if (retval == 0)
3651                         retval = ret;
3652         }
3653
3654         if (retval) {
3655                 e2fsck_pass1_threads_join(infos, global_ctx);
3656                 return retval;
3657         }
3658         *pinfo = infos;
3659         return 0;
3660 }
3661
3662 static void e2fsck_pass1_multithread(e2fsck_t global_ctx)
3663 {
3664         struct e2fsck_thread_info *infos = NULL;
3665         errcode_t retval;
3666
3667         retval = e2fsck_pass1_threads_start(&infos, global_ctx);
3668         if (retval) {
3669                 com_err(global_ctx->program_name, retval,
3670                         _("while starting pass1 threads\n"));
3671                 goto out_abort;
3672         }
3673
3674         retval = e2fsck_pass1_threads_join(infos, global_ctx);
3675         if (retval) {
3676                 com_err(global_ctx->program_name, retval,
3677                         _("while joining pass1 threads\n"));
3678                 goto out_abort;
3679         }
3680         return;
3681 out_abort:
3682         global_ctx->flags |= E2F_FLAG_ABORT;
3683         return;
3684 }
3685 #endif
3686
3687 void e2fsck_pass1(e2fsck_t ctx)
3688 {
3689         errcode_t retval;
3690         int need_single = 1;
3691
3692         retval = e2fsck_pass1_prepare(ctx);
3693         if (retval)
3694                 return;
3695 #ifdef HAVE_PTHREAD
3696         if (ctx->pfs_num_threads > 1 || ctx->options & E2F_OPT_MULTITHREAD) {
3697                 need_single = 0;
3698                 e2fsck_pass1_multithread(ctx);
3699         }
3700         /* No lock is needed at this time */
3701         ctx->fs_need_locking = 0;
3702 #endif
3703         if (need_single)
3704                 e2fsck_pass1_run(ctx);
3705         e2fsck_pass1_post(ctx);
3706 }
3707
3708 #undef FINISH_INODE_LOOP
3709
3710 /*
3711  * When the inode_scan routines call this callback at the end of the
3712  * glock group, call process_inodes.
3713  */
3714 static errcode_t scan_callback(ext2_filsys fs,
3715                                ext2_inode_scan scan EXT2FS_ATTR((unused)),
3716                                dgrp_t group, void * priv_data)
3717 {
3718         struct scan_callback_struct *scan_struct;
3719         e2fsck_t ctx;
3720         struct e2fsck_thread *tinfo;
3721
3722         scan_struct = (struct scan_callback_struct *) priv_data;
3723         ctx = scan_struct->ctx;
3724
3725         process_inodes((e2fsck_t) fs->priv_data, scan_struct->block_buf,
3726                        scan_struct->inodes_to_process,
3727                        scan_struct->process_inode_count);
3728
3729         if (ctx->progress)
3730                 if ((ctx->progress)(ctx, 1, group+1,
3731                                     ctx->fs->group_desc_count))
3732                         return EXT2_ET_CANCEL_REQUESTED;
3733
3734 #ifdef HAVE_PTHREAD
3735         if (ctx->global_ctx) {
3736                 tinfo = &ctx->thread_info;
3737                 tinfo->et_group_next++;
3738                 if (ctx->options & E2F_OPT_DEBUG &&
3739                     ctx->options & E2F_OPT_MULTITHREAD)
3740                         log_out(ctx, _("group %d finished\n"),
3741                                 tinfo->et_group_next);
3742                 if (tinfo->et_group_next >= tinfo->et_group_end)
3743                         return EXT2_ET_SCAN_FINISHED;
3744         }
3745 #endif
3746
3747         return 0;
3748 }
3749
3750 /*
3751  * Process the inodes in the "inodes to process" list.
3752  */
3753 static void process_inodes(e2fsck_t ctx, char *block_buf,
3754                            struct process_inode_block *inodes_to_process,
3755                            int *process_inode_count)
3756 {
3757         int                     i;
3758         struct ext2_inode       *old_stashed_inode;
3759         ext2_ino_t              old_stashed_ino;
3760         const char              *old_operation;
3761         char                    buf[80];
3762         struct problem_context  pctx;
3763
3764 #if 0
3765         printf("begin process_inodes: ");
3766 #endif
3767         if (*process_inode_count == 0)
3768                 return;
3769         old_operation = ehandler_operation(0);
3770         old_stashed_inode = ctx->stashed_inode;
3771         old_stashed_ino = ctx->stashed_ino;
3772         qsort(inodes_to_process, *process_inode_count,
3773                       sizeof(struct process_inode_block), process_inode_cmp);
3774         clear_problem_context(&pctx);
3775         for (i=0; i < *process_inode_count; i++) {
3776                 pctx.inode = ctx->stashed_inode =
3777                         (struct ext2_inode *) &inodes_to_process[i].inode;
3778                 pctx.ino = ctx->stashed_ino = inodes_to_process[i].ino;
3779
3780 #if 0
3781                 printf("%u ", pctx.ino);
3782 #endif
3783                 sprintf(buf, _("reading indirect blocks of inode %u"),
3784                         pctx.ino);
3785                 ehandler_operation(buf);
3786                 check_blocks(ctx, &pctx, block_buf,
3787                              &inodes_to_process[i].ea_ibody_quota);
3788                 if (e2fsck_should_abort(ctx))
3789                         break;
3790         }
3791         ctx->stashed_inode = old_stashed_inode;
3792         ctx->stashed_ino = old_stashed_ino;
3793         *process_inode_count = 0;
3794 #if 0
3795         printf("end process inodes\n");
3796 #endif
3797         ehandler_operation(old_operation);
3798 }
3799
3800 static EXT2_QSORT_TYPE process_inode_cmp(const void *a, const void *b)
3801 {
3802         const struct process_inode_block *ib_a =
3803                 (const struct process_inode_block *) a;
3804         const struct process_inode_block *ib_b =
3805                 (const struct process_inode_block *) b;
3806         int     ret;
3807
3808         ret = (ib_a->inode.i_block[EXT2_IND_BLOCK] -
3809                ib_b->inode.i_block[EXT2_IND_BLOCK]);
3810         if (ret == 0)
3811                 /*
3812                  * We only call process_inodes() for non-extent
3813                  * inodes, so it's OK to pass NULL to
3814                  * ext2fs_file_acl_block() here.
3815                  */
3816                 ret = ext2fs_file_acl_block(0, ext2fs_const_inode(&ib_a->inode)) -
3817                         ext2fs_file_acl_block(0, ext2fs_const_inode(&ib_b->inode));
3818         if (ret == 0)
3819                 ret = ib_a->ino - ib_b->ino;
3820         return ret;
3821 }
3822
3823 /*
3824  * Mark an inode as being bad and increment its badness counter.
3825  */
3826 void e2fsck_mark_inode_bad_loc(e2fsck_t ctx, struct problem_context *pctx,
3827                                __u32 code, int badness, const char *func,
3828                                const int line)
3829 {
3830         __u16 badness_before, badness_after;
3831         __u64 pctx_num_sav = pctx->num;
3832
3833         if (!ctx->inode_badness_threshold)      /* badness is disabled */
3834                 return;
3835
3836         if (!ctx->inode_badness) {
3837                 errcode_t retval;
3838
3839                 retval = ext2fs_create_icount2(ctx->fs, 0, 0, NULL,
3840                                                &ctx->inode_badness);
3841                 if (retval) {
3842                         pctx->errcode = retval;
3843                         fix_problem(ctx, PR_1_ALLOCATE_ICOUNT, pctx);
3844                         ctx->flags |= E2F_FLAG_ABORT;
3845                         return;
3846                 }
3847         }
3848         ext2fs_icount_fetch(ctx->inode_badness, pctx->ino, &badness_before);
3849         if (badness + badness_before > BADNESS_MAX)
3850                 badness_after = BADNESS_MAX;
3851         else if (badness < 0 && badness_before < -badness)
3852                 badness_after = 0;
3853         else
3854                 badness_after = badness_before + badness;
3855         ext2fs_icount_store(ctx->inode_badness, pctx->ino, badness_after);
3856
3857         if (ctx->options & E2F_OPT_DEBUG)
3858                 log_out(ctx,
3859                         "%s:%d: increase inode %lu badness %u to %u for %x\n",
3860                         func, line, (unsigned long)pctx->ino, badness_before,
3861                         badness_after, code);
3862 }
3863
3864 static void add_casefolded_dir(e2fsck_t ctx, ino_t ino)
3865 {
3866         struct          problem_context pctx;
3867
3868         if (!ctx->casefolded_dirs) {
3869                 pctx.errcode = ext2fs_u32_list_create(&ctx->casefolded_dirs, 0);
3870                 if (pctx.errcode)
3871                         goto error;
3872         }
3873         pctx.errcode = ext2fs_u32_list_add(ctx->casefolded_dirs, ino);
3874         if (pctx.errcode == 0)
3875                 return;
3876 error:
3877         fix_problem(ctx, PR_1_ALLOCATE_CASEFOLDED_DIRLIST, &pctx);
3878         /* Should never get here */
3879         ctx->flags |= E2F_FLAG_ABORT;
3880 }
3881
3882 /*
3883  * This procedure will allocate the inode "bb" (badblock) map table
3884  */
3885 static void alloc_bb_map(e2fsck_t ctx)
3886 {
3887         struct          problem_context pctx;
3888
3889         clear_problem_context(&pctx);
3890         pctx.errcode = e2fsck_allocate_inode_bitmap(ctx->fs,
3891                         _("inode in bad block map"), EXT2FS_BMAP64_RBTREE,
3892                         "inode_bb_map", &ctx->inode_bb_map);
3893         if (pctx.errcode) {
3894                 pctx.num = 4;
3895                 fix_problem(ctx, PR_1_ALLOCATE_IBITMAP_ERROR, &pctx);
3896                 /* Should never get here */
3897                 ctx->flags |= E2F_FLAG_ABORT;
3898                 return;
3899         }
3900 }
3901
3902 /*
3903  * This procedure will allocate the inode imagic table
3904  */
3905 static void alloc_imagic_map(e2fsck_t ctx)
3906 {
3907         struct          problem_context pctx;
3908
3909         clear_problem_context(&pctx);
3910         pctx.errcode = e2fsck_allocate_inode_bitmap(ctx->fs,
3911                         _("imagic inode map"), EXT2FS_BMAP64_RBTREE,
3912                         "inode_imagic_map", &ctx->inode_imagic_map);
3913         if (pctx.errcode) {
3914                 pctx.num = 5;
3915                 fix_problem(ctx, PR_1_ALLOCATE_IBITMAP_ERROR, &pctx);
3916                 /* Should never get here */
3917                 ctx->flags |= E2F_FLAG_ABORT;
3918                 return;
3919         }
3920 }
3921
3922 /*
3923  * Marks a block as in use, setting the dup_map if it's been set
3924  * already.  Called by process_block and process_bad_block.
3925  *
3926  * WARNING: Assumes checks have already been done to make sure block
3927  * is valid.  This is true in both process_block and process_bad_block.
3928  */
3929 static _INLINE_ void mark_block_used(e2fsck_t ctx, blk64_t block)
3930 {
3931         struct problem_context pctx;
3932         e2fsck_t global_ctx = ctx->global_ctx ? ctx->global_ctx : ctx;
3933
3934         clear_problem_context(&pctx);
3935
3936         if (is_blocks_used(ctx, block, 1)) {
3937                 if (ext2fs_has_feature_shared_blocks(ctx->fs->super) &&
3938                     !(ctx->options & E2F_OPT_UNSHARE_BLOCKS)) {
3939                         return;
3940                 }
3941                 ctx->flags |= E2F_FLAG_DUP_BLOCK;
3942                 e2fsck_pass1_block_map_w_lock(ctx);
3943                 ext2fs_fast_mark_block_bitmap2(global_ctx->block_dup_map, block);
3944                 e2fsck_pass1_block_map_w_unlock(ctx);
3945         } else {
3946                 ext2fs_fast_mark_block_bitmap2(ctx->block_found_map, block);
3947         }
3948 }
3949
3950 /*
3951  * When cluster size is greater than one block, it is caller's responsibility
3952  * to make sure block parameter starts at a cluster boundary.
3953  */
3954 static _INLINE_ void mark_blocks_used(e2fsck_t ctx, blk64_t block,
3955                                       unsigned int num)
3956 {
3957         if (!is_blocks_used(ctx, block, num)) {
3958                 ext2fs_mark_block_bitmap_range2(ctx->block_found_map, block, num);
3959         } else {
3960                 unsigned int i;
3961
3962                 for (i = 0; i < num; i += EXT2FS_CLUSTER_RATIO(ctx->fs))
3963                         mark_block_used(ctx, block + i);
3964         }
3965 }
3966
3967 static errcode_t _INLINE_ e2fsck_write_ext_attr3(e2fsck_t ctx, blk64_t block,
3968                                                  void *inbuf, ext2_ino_t inum)
3969 {
3970         errcode_t retval;
3971         ext2_filsys fs = ctx->fs;
3972
3973         e2fsck_pass1_fix_lock(ctx);
3974         retval = ext2fs_write_ext_attr3(fs, block, inbuf, inum);
3975         e2fsck_pass1_fix_unlock(ctx);
3976
3977         return retval;
3978 }
3979 /*
3980  * Adjust the extended attribute block's reference counts at the end
3981  * of pass 1, either by subtracting out references for EA blocks that
3982  * are still referenced in ctx->refcount, or by adding references for
3983  * EA blocks that had extra references as accounted for in
3984  * ctx->refcount_extra.
3985  */
3986 static void adjust_extattr_refcount(e2fsck_t ctx, ext2_refcount_t refcount,
3987                                     char *block_buf, int adjust_sign)
3988 {
3989         struct ext2_ext_attr_header     *header;
3990         struct problem_context          pctx;
3991         ext2_filsys                     fs = ctx->fs;
3992         blk64_t                         blk;
3993         __u32                           should_be;
3994         ea_value_t                      count;
3995
3996         clear_problem_context(&pctx);
3997
3998         ea_refcount_intr_begin(refcount);
3999         while (1) {
4000                 if ((blk = ea_refcount_intr_next(refcount, &count)) == 0)
4001                         break;
4002                 pctx.blk = blk;
4003                 pctx.errcode = ext2fs_read_ext_attr3(fs, blk, block_buf,
4004                                                      pctx.ino);
4005                 /* We already checked this block, shouldn't happen */
4006                 if (pctx.errcode) {
4007                         fix_problem(ctx, PR_1_EXTATTR_READ_ABORT, &pctx);
4008                         return;
4009                 }
4010                 header = BHDR(block_buf);
4011                 if (header->h_magic != EXT2_EXT_ATTR_MAGIC) {
4012                         fix_problem(ctx, PR_1_EXTATTR_READ_ABORT, &pctx);
4013                         return;
4014                 }
4015
4016                 pctx.blkcount = header->h_refcount;
4017                 should_be = header->h_refcount + adjust_sign * (int)count;
4018                 pctx.num = should_be;
4019                 if (fix_problem(ctx, PR_1_EXTATTR_REFCOUNT, &pctx)) {
4020                         header->h_refcount = should_be;
4021                         pctx.errcode = e2fsck_write_ext_attr3(ctx, blk,
4022                                                              block_buf,
4023                                                              pctx.ino);
4024                         if (pctx.errcode) {
4025                                 fix_problem(ctx, PR_1_EXTATTR_WRITE_ABORT,
4026                                             &pctx);
4027                                 continue;
4028                         }
4029                 }
4030         }
4031 }
4032
4033 /*
4034  * Handle processing the extended attribute blocks
4035  */
4036 static int check_ext_attr(e2fsck_t ctx, struct problem_context *pctx,
4037                            char *block_buf, struct ea_quota *ea_block_quota)
4038 {
4039         ext2_filsys fs = ctx->fs;
4040         ext2_ino_t      ino = pctx->ino;
4041         struct ext2_inode *inode = pctx->inode;
4042         blk64_t         blk;
4043         char *          end;
4044         struct ext2_ext_attr_header *header;
4045         struct ext2_ext_attr_entry *first, *entry;
4046         blk64_t         quota_blocks = EXT2FS_C2B(fs, 1);
4047         __u64           quota_inodes = 0;
4048         region_t        region = 0;
4049         int             failed_csum = 0;
4050
4051         ea_block_quota->blocks = 0;
4052         ea_block_quota->inodes = 0;
4053
4054         blk = ext2fs_file_acl_block(fs, inode);
4055         if (blk == 0)
4056                 return 0;
4057
4058         /*
4059          * If the Extended attribute flag isn't set, then a non-zero
4060          * file acl means that the inode is corrupted.
4061          *
4062          * Or if the extended attribute block is an invalid block,
4063          * then the inode is also corrupted.
4064          */
4065         if (!ext2fs_has_feature_xattr(fs->super) ||
4066             (blk < fs->super->s_first_data_block) ||
4067             (blk >= ext2fs_blocks_count(fs->super))) {
4068                 /* Fixed in pass2, e2fsck_process_bad_inode(). */
4069                 e2fsck_mark_inode_bad(ctx, pctx, PR_2_FILE_ACL_ZERO);
4070                 return 0;
4071         }
4072
4073         /* If ea bitmap hasn't been allocated, create it */
4074         if (!ctx->block_ea_map) {
4075                 pctx->errcode = e2fsck_allocate_block_bitmap(fs,
4076                                         _("ext attr block map"),
4077                                         EXT2FS_BMAP64_RBTREE, "block_ea_map",
4078                                         &ctx->block_ea_map);
4079                 if (pctx->errcode) {
4080                         pctx->num = 2;
4081                         fix_problem(ctx, PR_1_ALLOCATE_BBITMAP_ERROR, pctx);
4082                         ctx->flags |= E2F_FLAG_ABORT;
4083                         return 0;
4084                 }
4085         }
4086
4087         /* Create the EA refcount structure if necessary */
4088         if (!ctx->refcount) {
4089                 pctx->errcode = ea_refcount_create(0,
4090                                         &ctx->refcount_orig);
4091                 if (pctx->errcode) {
4092                         pctx->num = 1;
4093                         fix_problem(ctx, PR_1_ALLOCATE_REFCOUNT, pctx);
4094                         ctx->flags |= E2F_FLAG_ABORT;
4095                         return 0;
4096                 }
4097
4098                 pctx->errcode = ea_refcount_create(0, &ctx->refcount);
4099                 if (pctx->errcode) {
4100                         pctx->num = 1;
4101                         fix_problem(ctx, PR_1_ALLOCATE_REFCOUNT, pctx);
4102                         ctx->flags |= E2F_FLAG_ABORT;
4103                         return 0;
4104                 }
4105         }
4106
4107 #if 0
4108         /* Debugging text */
4109         printf("Inode %u has EA block %u\n", ino, blk);
4110 #endif
4111
4112         /* Have we seen this EA block before? */
4113         if (ext2fs_fast_test_block_bitmap2(ctx->block_ea_map, blk)) {
4114                 ea_block_quota->blocks = EXT2FS_C2B(fs, 1);
4115                 ea_block_quota->inodes = 0;
4116
4117                 if (ctx->ea_block_quota_blocks) {
4118                         ea_refcount_fetch(ctx->ea_block_quota_blocks, blk,
4119                                           &quota_blocks);
4120                         if (quota_blocks)
4121                                 ea_block_quota->blocks = quota_blocks;
4122                 }
4123
4124                 if (ctx->ea_block_quota_inodes)
4125                         ea_refcount_fetch(ctx->ea_block_quota_inodes, blk,
4126                                           &ea_block_quota->inodes);
4127
4128                 if (ea_refcount_decrement(ctx->refcount, blk, 0) == 0)
4129                         return 1;
4130                 /* Ooops, this EA was referenced more than it stated */
4131                 if (!ctx->refcount_extra) {
4132                         pctx->errcode = ea_refcount_create(0,
4133                                            &ctx->refcount_extra);
4134                         if (pctx->errcode) {
4135                                 pctx->num = 2;
4136                                 fix_problem(ctx, PR_1_ALLOCATE_REFCOUNT, pctx);
4137                                 ctx->flags |= E2F_FLAG_ABORT;
4138                                 return 0;
4139                         }
4140                 }
4141                 ea_refcount_increment(ctx->refcount_extra, blk, 0);
4142                 return 1;
4143         }
4144
4145         /*
4146          * OK, we haven't seen this EA block yet.  So we need to
4147          * validate it
4148          */
4149         pctx->blk = blk;
4150         pctx->errcode = ext2fs_read_ext_attr3(fs, blk, block_buf, pctx->ino);
4151         if (pctx->errcode == EXT2_ET_EXT_ATTR_CSUM_INVALID) {
4152                 pctx->errcode = 0;
4153                 failed_csum = 1;
4154         } else if (pctx->errcode == EXT2_ET_BAD_EA_HEADER)
4155                 pctx->errcode = 0;
4156
4157         if (pctx->errcode &&
4158             fix_problem(ctx, PR_1_READ_EA_BLOCK, pctx)) {
4159                 pctx->errcode = 0;
4160                 goto clear_extattr;
4161         }
4162         header = BHDR(block_buf);
4163         pctx->blk = ext2fs_file_acl_block(fs, inode);
4164         if (((ctx->ext_attr_ver == 1) &&
4165              (header->h_magic != EXT2_EXT_ATTR_MAGIC_v1)) ||
4166             ((ctx->ext_attr_ver == 2) &&
4167              (header->h_magic != EXT2_EXT_ATTR_MAGIC))) {
4168                 if (fix_problem(ctx, PR_1_BAD_EA_BLOCK, pctx))
4169                         goto clear_extattr;
4170         }
4171
4172         if (header->h_blocks != 1) {
4173                 if (fix_problem(ctx, PR_1_EA_MULTI_BLOCK, pctx))
4174                         goto clear_extattr;
4175         }
4176
4177         if (pctx->errcode && fix_problem(ctx, PR_1_READ_EA_BLOCK, pctx))
4178                 goto clear_extattr;
4179
4180         region = region_create(0, fs->blocksize);
4181         if (!region) {
4182                 fix_problem(ctx, PR_1_EA_ALLOC_REGION_ABORT, pctx);
4183                 ctx->flags |= E2F_FLAG_ABORT;
4184                 return 0;
4185         }
4186         if (region_allocate(region, 0, sizeof(struct ext2_ext_attr_header))) {
4187                 if (fix_problem(ctx, PR_1_EA_ALLOC_COLLISION, pctx))
4188                         goto clear_extattr;
4189         }
4190
4191         first = (struct ext2_ext_attr_entry *)(header+1);
4192         end = block_buf + fs->blocksize;
4193         entry = first;
4194         while ((char *)entry < end && *(__u32 *)entry) {
4195                 __u32 hash;
4196
4197                 if (region_allocate(region, (char *)entry - (char *)header,
4198                                    EXT2_EXT_ATTR_LEN(entry->e_name_len))) {
4199                         if (fix_problem(ctx, PR_1_EA_ALLOC_COLLISION, pctx))
4200                                 goto clear_extattr;
4201                         break;
4202                 }
4203                 if ((ctx->ext_attr_ver == 1 &&
4204                      (entry->e_name_len == 0 || entry->e_name_index != 0)) ||
4205                     (ctx->ext_attr_ver == 2 &&
4206                      entry->e_name_index == 0)) {
4207                         if (fix_problem(ctx, PR_1_EA_BAD_NAME, pctx))
4208                                 goto clear_extattr;
4209                         break;
4210                 }
4211                 if (entry->e_value_inum == 0) {
4212                         if (entry->e_value_offs + entry->e_value_size >
4213                             fs->blocksize) {
4214                                 if (fix_problem(ctx, PR_1_EA_BAD_VALUE, pctx))
4215                                         goto clear_extattr;
4216                                 break;
4217                         }
4218                         if (entry->e_value_size &&
4219                             region_allocate(region, entry->e_value_offs,
4220                                             EXT2_EXT_ATTR_SIZE(entry->e_value_size))) {
4221                                 if (fix_problem(ctx, PR_1_EA_ALLOC_COLLISION,
4222                                                 pctx))
4223                                         goto clear_extattr;
4224                         }
4225
4226                         hash = ext2fs_ext_attr_hash_entry(entry, block_buf +
4227                                                           entry->e_value_offs);
4228
4229                         if (entry->e_hash != hash) {
4230                                 pctx->num = entry->e_hash;
4231                                 if (fix_problem(ctx, PR_1_ATTR_HASH, pctx))
4232                                         goto clear_extattr;
4233                                 entry->e_hash = hash;
4234                         }
4235                 } else {
4236                         problem_t problem;
4237                         blk64_t entry_quota_blocks;
4238
4239                         problem = check_large_ea_inode(ctx, entry, pctx,
4240                                                        &entry_quota_blocks);
4241                         if (problem && fix_problem(ctx, problem, pctx))
4242                                 goto clear_extattr;
4243
4244                         quota_blocks += entry_quota_blocks;
4245                         quota_inodes++;
4246                 }
4247
4248                 entry = EXT2_EXT_ATTR_NEXT(entry);
4249         }
4250         if (region_allocate(region, (char *)entry - (char *)header, 4)) {
4251                 if (fix_problem(ctx, PR_1_EA_ALLOC_COLLISION, pctx))
4252                         goto clear_extattr;
4253         }
4254         region_free(region);
4255
4256         /*
4257          * We only get here if there was no other errors that were fixed.
4258          * If there was a checksum fail, ask to correct it.
4259          */
4260         if (failed_csum &&
4261             fix_problem(ctx, PR_1_EA_BLOCK_ONLY_CSUM_INVALID, pctx)) {
4262                 pctx->errcode = e2fsck_write_ext_attr3(ctx, blk, block_buf,
4263                                                        pctx->ino);
4264                 if (pctx->errcode)
4265                         return 0;
4266         }
4267
4268         if (quota_blocks != EXT2FS_C2B(fs, 1U)) {
4269                 if (!ctx->ea_block_quota_blocks) {
4270                         pctx->errcode = ea_refcount_create(0,
4271                                                 &ctx->ea_block_quota_blocks);
4272                         if (pctx->errcode) {
4273                                 pctx->num = 3;
4274                                 goto refcount_fail;
4275                         }
4276                 }
4277                 ea_refcount_store(ctx->ea_block_quota_blocks, blk,
4278                                   quota_blocks);
4279         }
4280
4281         if (quota_inodes) {
4282                 if (!ctx->ea_block_quota_inodes) {
4283                         pctx->errcode = ea_refcount_create(0,
4284                                                 &ctx->ea_block_quota_inodes);
4285                         if (pctx->errcode) {
4286                                 pctx->num = 4;
4287 refcount_fail:
4288                                 fix_problem(ctx, PR_1_ALLOCATE_REFCOUNT, pctx);
4289                                 ctx->flags |= E2F_FLAG_ABORT;
4290                                 return 0;
4291                         }
4292                 }
4293
4294                 ea_refcount_store(ctx->ea_block_quota_inodes, blk,
4295                                   quota_inodes);
4296         }
4297         ea_block_quota->blocks = quota_blocks;
4298         ea_block_quota->inodes = quota_inodes;
4299
4300         inc_ea_inode_refs(ctx, pctx, first, end);
4301         ea_refcount_store(ctx->refcount, blk, header->h_refcount - 1);
4302         ea_refcount_store(ctx->refcount_orig, blk, header->h_refcount);
4303         /**
4304          * It might be racy that this block has been merged in the
4305          * global found map.
4306          */
4307         if (!is_blocks_used(ctx, blk, 1))
4308                 ext2fs_fast_mark_block_bitmap2(ctx->block_found_map, blk);
4309         ext2fs_fast_mark_block_bitmap2(ctx->block_ea_map, blk);
4310         return 1;
4311
4312 clear_extattr:
4313         if (region)
4314                 region_free(region);
4315         ext2fs_file_acl_block_set(fs, inode, 0);
4316         e2fsck_write_inode(ctx, ino, inode, "check_ext_attr");
4317         return 0;
4318 }
4319
4320 /* Returns 1 if bad htree, 0 if OK */
4321 static int handle_htree(e2fsck_t ctx, struct problem_context *pctx,
4322                         ext2_ino_t ino, struct ext2_inode *inode,
4323                         char *block_buf)
4324 {
4325         struct ext2_dx_root_info        *root;
4326         ext2_filsys                     fs = ctx->fs;
4327         errcode_t                       retval;
4328         blk64_t                         blk;
4329
4330         if ((!LINUX_S_ISDIR(inode->i_mode) &&
4331              fix_problem(ctx, PR_1_HTREE_NODIR, pctx)) ||
4332             (!ext2fs_has_feature_dir_index(fs->super) &&
4333              fix_problem(ctx, PR_1_HTREE_SET, pctx)))
4334                 return 1;
4335
4336         pctx->errcode = ext2fs_bmap2(fs, ino, inode, 0, 0, 0, 0, &blk);
4337
4338         if ((pctx->errcode) ||
4339             (blk == 0) ||
4340             (blk < fs->super->s_first_data_block) ||
4341             (blk >= ext2fs_blocks_count(fs->super))) {
4342                 if (fix_problem(ctx, PR_1_HTREE_BADROOT, pctx))
4343                         return 1;
4344                 else
4345                         return 0;
4346         }
4347
4348         retval = io_channel_read_blk64(fs->io, blk, 1, block_buf);
4349         if (retval) {
4350                 if (fix_problem(ctx, PR_1_HTREE_BADROOT, pctx))
4351                         return 1;
4352         }
4353
4354         /* XXX should check that beginning matches a directory */
4355         root = get_ext2_dx_root_info(fs, block_buf);
4356
4357         if ((root->reserved_zero || root->info_length < 8) &&
4358             fix_problem(ctx, PR_1_HTREE_BADROOT, pctx))
4359                 return 1;
4360
4361         pctx->num = root->hash_version;
4362         if ((root->hash_version != EXT2_HASH_LEGACY) &&
4363             (root->hash_version != EXT2_HASH_HALF_MD4) &&
4364             (root->hash_version != EXT2_HASH_TEA) &&
4365             (root->hash_version != EXT2_HASH_SIPHASH) &&
4366             fix_problem(ctx, PR_1_HTREE_HASHV, pctx))
4367                 return 1;
4368
4369         if (ext4_hash_in_dirent(inode)) {
4370                 if (root->hash_version != EXT2_HASH_SIPHASH &&
4371                     fix_problem(ctx, PR_1_HTREE_NEEDS_SIPHASH, pctx))
4372                         return 1;
4373         } else {
4374                 if (root->hash_version == EXT2_HASH_SIPHASH &&
4375                    fix_problem(ctx, PR_1_HTREE_CANNOT_SIPHASH, pctx))
4376                         return 1;
4377         }
4378
4379         if ((root->unused_flags & EXT2_HASH_FLAG_INCOMPAT) &&
4380             fix_problem(ctx, PR_1_HTREE_INCOMPAT, pctx))
4381                 return 1;
4382
4383         pctx->num = root->indirect_levels;
4384         /* if htree level is clearly too high, consider it to be broken */
4385         if (root->indirect_levels > EXT4_HTREE_LEVEL &&
4386             fix_problem(ctx, PR_1_HTREE_DEPTH, pctx))
4387                 return 1;
4388
4389         /* if level is only maybe too high, LARGE_DIR feature could be unset */
4390         if (root->indirect_levels > ext2_dir_htree_level(fs) &&
4391             !ext2fs_has_feature_largedir(fs->super)) {
4392                 int blockbits = EXT2_BLOCK_SIZE_BITS(fs->super) + 10;
4393                 int idx_pb = 1 << (blockbits - 3);
4394
4395                 /* compare inode size/blocks vs. max-sized 2-level htree */
4396                 if (EXT2_I_SIZE(pctx->inode) <
4397                     (idx_pb - 1) * (idx_pb - 2) << blockbits &&
4398                     pctx->inode->i_blocks <
4399                     (idx_pb - 1) * (idx_pb - 2) << (blockbits - 9) &&
4400                     fix_problem(ctx, PR_1_HTREE_DEPTH, pctx))
4401                         return 1;
4402         }
4403
4404         if (root->indirect_levels > EXT4_HTREE_LEVEL_COMPAT ||
4405             ext2fs_needs_large_file_feature(EXT2_I_SIZE(inode)))
4406                 ctx->large_dirs++;
4407
4408         return 0;
4409 }
4410
4411 void e2fsck_clear_inode(e2fsck_t ctx, ext2_ino_t ino,
4412                         struct ext2_inode *inode, int restart_flag,
4413                         const char *source)
4414 {
4415         inode->i_flags = 0;
4416         inode->i_links_count = 0;
4417         ext2fs_icount_store(ctx->inode_link_info, ino, 0);
4418         inode->i_dtime = ctx->now;
4419
4420         /*
4421          * If a special inode has such rotten block mappings that we
4422          * want to clear the whole inode, be sure to actually zap
4423          * the block maps because i_links_count isn't checked for
4424          * special inodes, and we'll end up right back here the next
4425          * time we run fsck.
4426          */
4427         if (ino < EXT2_FIRST_INODE(ctx->fs->super))
4428                 memset(inode->i_block, 0, sizeof(inode->i_block));
4429
4430         ext2fs_unmark_inode_bitmap2(ctx->inode_dir_map, ino);
4431         ext2fs_unmark_inode_bitmap2(ctx->inode_used_map, ino);
4432         if (ctx->inode_reg_map)
4433                 ext2fs_unmark_inode_bitmap2(ctx->inode_reg_map, ino);
4434         if (ctx->inode_badness)
4435                 ext2fs_icount_store(ctx->inode_badness, ino, 0);
4436
4437         /*
4438          * If the inode was partially accounted for before processing
4439          * was aborted, we need to restart the pass 1 scan.
4440          */
4441         ctx->flags |= restart_flag;
4442
4443         if (ino == EXT2_BAD_INO)
4444                 memset(inode, 0, sizeof(struct ext2_inode));
4445
4446         e2fsck_write_inode(ctx, ino, inode, source);
4447 }
4448
4449 /*
4450  * Use the multiple-blocks reclamation code to fix alignment problems in
4451  * a bigalloc filesystem.  We want a logical cluster to map to *only* one
4452  * physical cluster, and we want the block offsets within that cluster to
4453  * line up.
4454  */
4455 static int has_unaligned_cluster_map(e2fsck_t ctx,
4456                                      blk64_t last_pblk, blk64_t last_lblk,
4457                                      blk64_t pblk, blk64_t lblk)
4458 {
4459         blk64_t cluster_mask;
4460
4461         if (!ctx->fs->cluster_ratio_bits)
4462                 return 0;
4463         cluster_mask = EXT2FS_CLUSTER_MASK(ctx->fs);
4464
4465         /*
4466          * If the block in the logical cluster doesn't align with the block in
4467          * the physical cluster...
4468          */
4469         if ((lblk & cluster_mask) != (pblk & cluster_mask))
4470                 return 1;
4471
4472         /*
4473          * If we cross a physical cluster boundary within a logical cluster...
4474          */
4475         if (last_pblk && (lblk & cluster_mask) != 0 &&
4476             EXT2FS_B2C(ctx->fs, lblk) == EXT2FS_B2C(ctx->fs, last_lblk) &&
4477             EXT2FS_B2C(ctx->fs, pblk) != EXT2FS_B2C(ctx->fs, last_pblk))
4478                 return 1;
4479
4480         return 0;
4481 }
4482
4483 static void scan_extent_node(e2fsck_t ctx, struct problem_context *pctx,
4484                              struct process_block_struct *pb,
4485                              blk64_t start_block, blk64_t end_block,
4486                              blk64_t eof_block,
4487                              ext2_extent_handle_t ehandle,
4488                              int try_repairs)
4489 {
4490         struct ext2fs_extent    extent;
4491         blk64_t                 blk, last_lblk;
4492         unsigned int            i, n;
4493         int                     is_dir, is_leaf;
4494         problem_t               problem;
4495         struct ext2_extent_info info;
4496         int                     failed_csum = 0;
4497
4498         if (pctx->errcode == EXT2_ET_EXTENT_CSUM_INVALID)
4499                 failed_csum = 1;
4500
4501         pctx->errcode = ext2fs_extent_get_info(ehandle, &info);
4502         if (pctx->errcode)
4503                 return;
4504         if (!(ctx->options & E2F_OPT_FIXES_ONLY) &&
4505             !pb->eti.force_rebuild) {
4506                 struct extent_tree_level *etl;
4507
4508                 etl = pb->eti.ext_info + info.curr_level;
4509                 etl->num_extents += info.num_entries;
4510                 etl->max_extents += info.max_entries;
4511                 /*
4512                  * Implementation wart: Splitting extent blocks when appending
4513                  * will leave the old block with one free entry.  Therefore
4514                  * unless the node is totally full, pretend that a non-root
4515                  * extent block can hold one fewer entry than it actually does,
4516                  * so that we don't repeatedly rebuild the extent tree.
4517                  */
4518                 if (info.curr_level && info.num_entries < info.max_entries)
4519                         etl->max_extents--;
4520         }
4521
4522         pctx->errcode = ext2fs_extent_get(ehandle, EXT2_EXTENT_FIRST_SIB,
4523                                           &extent);
4524         while ((pctx->errcode == 0 ||
4525                 pctx->errcode == EXT2_ET_EXTENT_CSUM_INVALID) &&
4526                info.num_entries-- > 0) {
4527                 is_leaf = extent.e_flags & EXT2_EXTENT_FLAGS_LEAF;
4528                 is_dir = LINUX_S_ISDIR(pctx->inode->i_mode);
4529                 last_lblk = extent.e_lblk + extent.e_len - 1;
4530
4531                 problem = 0;
4532                 pctx->blk = extent.e_pblk;
4533                 pctx->blk2 = extent.e_lblk;
4534                 pctx->num = extent.e_len;
4535                 pctx->blkcount = extent.e_lblk + extent.e_len;
4536
4537                 if (extent.e_pblk == 0 ||
4538                     extent.e_pblk < ctx->fs->super->s_first_data_block ||
4539                     extent.e_pblk >= ext2fs_blocks_count(ctx->fs->super))
4540                         problem = PR_1_EXTENT_BAD_START_BLK;
4541                 else if (extent.e_lblk < start_block)
4542                         problem = PR_1_OUT_OF_ORDER_EXTENTS;
4543                 else if ((end_block && last_lblk > end_block) &&
4544                          !(last_lblk > eof_block &&
4545                            ((extent.e_flags & EXT2_EXTENT_FLAGS_UNINIT) ||
4546                             (pctx->inode->i_flags & EXT4_VERITY_FL))))
4547                         problem = PR_1_EXTENT_END_OUT_OF_BOUNDS;
4548                 else if (is_leaf && extent.e_len == 0)
4549                         problem = PR_1_EXTENT_LENGTH_ZERO;
4550                 else if (is_leaf &&
4551                          (extent.e_pblk + extent.e_len) >
4552                          ext2fs_blocks_count(ctx->fs->super))
4553                         problem = PR_1_EXTENT_ENDS_BEYOND;
4554                 else if (is_leaf && is_dir && !pctx->inode->i_size_high &&
4555                          !ext2fs_has_feature_largedir(ctx->fs->super) &&
4556                          ((extent.e_lblk + extent.e_len) >
4557                           (1U << (21 - ctx->fs->super->s_log_block_size))))
4558                         problem = PR_1_TOOBIG_DIR;
4559
4560                 if (is_leaf && problem == 0 && extent.e_len > 0) {
4561 #if 0
4562                         printf("extent_region(ino=%u, expect=%llu, "
4563                                "lblk=%llu, len=%u)\n", pb->ino,
4564                                (unsigned long long) pb->next_lblock,
4565                                (unsigned long long) extent.e_lblk,
4566                                extent.e_len);
4567 #endif
4568                         if (extent.e_lblk < pb->next_lblock)
4569                                 problem = PR_1_EXTENT_COLLISION;
4570                         else if (extent.e_lblk + extent.e_len > pb->next_lblock)
4571                                 pb->next_lblock = extent.e_lblk + extent.e_len;
4572                 }
4573
4574                 /*
4575                  * Uninitialized blocks in a directory?  Clear the flag and
4576                  * we'll interpret the blocks later.
4577                  */
4578                 if (try_repairs && is_dir && problem == 0 &&
4579                     (extent.e_flags & EXT2_EXTENT_FLAGS_UNINIT) &&
4580                     fix_problem(ctx, PR_1_UNINIT_DBLOCK, pctx)) {
4581                         e2fsck_pass1_fix_lock(ctx);
4582                         extent.e_flags &= ~EXT2_EXTENT_FLAGS_UNINIT;
4583                         pb->inode_modified = 1;
4584                         pctx->errcode = ext2fs_extent_replace(ehandle, 0,
4585                                                               &extent);
4586                         e2fsck_pass1_fix_unlock(ctx);
4587                         if (pctx->errcode)
4588                                 return;
4589                         failed_csum = 0;
4590                 }
4591 #ifdef CONFIG_DEVELOPER_FEATURES
4592                 if (try_repairs && !is_dir && problem == 0 &&
4593                     (ctx->options & E2F_OPT_CLEAR_UNINIT) &&
4594                     (extent.e_flags & EXT2_EXTENT_FLAGS_UNINIT) &&
4595                     fix_problem(ctx, PR_1_CLEAR_UNINIT_EXTENT, pctx)) {
4596                         extent.e_flags &= ~EXT2_EXTENT_FLAGS_UNINIT;
4597                         pb->inode_modified = 1;
4598                         pctx->errcode = ext2fs_extent_replace(ehandle, 0,
4599                                                               &extent);
4600                         if (pctx->errcode)
4601                                 return;
4602                         failed_csum = 0;
4603                 }
4604 #endif
4605                 if (try_repairs && problem) {
4606 report_problem:
4607                         /* Record badness only if extent is within inode */
4608                         if (fix_problem_bad(ctx, problem, pctx,
4609                                             info.curr_level == 0)) {
4610                                 if (ctx->invalid_bitmaps) {
4611                                         /*
4612                                          * If fsck knows the bitmaps are bad,
4613                                          * skip to the next extent and
4614                                          * try to clear this extent again
4615                                          * after fixing the bitmaps, by
4616                                          * restarting fsck.
4617                                          */
4618                                         pctx->errcode = ext2fs_extent_get(
4619                                                           ehandle,
4620                                                           EXT2_EXTENT_NEXT_SIB,
4621                                                           &extent);
4622                                         ctx->flags |= E2F_FLAG_RESTART_LATER;
4623                                         if (pctx->errcode ==
4624                                                     EXT2_ET_NO_CURRENT_NODE) {
4625                                                 pctx->errcode = 0;
4626                                                 break;
4627                                         }
4628                                         continue;
4629                                 }
4630                                 e2fsck_pass1_fix_lock(ctx);
4631                                 e2fsck_read_bitmaps(ctx);
4632                                 pb->inode_modified = 1;
4633                                 pctx->errcode =
4634                                         ext2fs_extent_delete(ehandle, 0);
4635                                 e2fsck_pass1_fix_unlock(ctx);
4636                                 if (pctx->errcode) {
4637                                         pctx->str = "ext2fs_extent_delete";
4638                                         return;
4639                                 }
4640                                 e2fsck_pass1_fix_lock(ctx);
4641                                 pctx->errcode = ext2fs_extent_fix_parents(ehandle);
4642                                 e2fsck_pass1_fix_unlock(ctx);
4643                                 if (pctx->errcode &&
4644                                     pctx->errcode != EXT2_ET_NO_CURRENT_NODE) {
4645                                         pctx->str = "ext2fs_extent_fix_parents";
4646                                         return;
4647                                 }
4648                                 pctx->errcode = ext2fs_extent_get(ehandle,
4649                                                                   EXT2_EXTENT_CURRENT,
4650                                                                   &extent);
4651                                 if (pctx->errcode == EXT2_ET_NO_CURRENT_NODE) {
4652                                         pctx->errcode = 0;
4653                                         break;
4654                                 }
4655                                 failed_csum = 0;
4656                                 continue;
4657                         }
4658                         goto next;
4659                 }
4660
4661                 if (!is_leaf) {
4662                         blk64_t lblk = extent.e_lblk;
4663                         int next_try_repairs = 1;
4664
4665                         blk = extent.e_pblk;
4666
4667                         /*
4668                          * If this lower extent block collides with critical
4669                          * metadata, don't try to repair the damage.  Pass 1b
4670                          * will reallocate the block; then we can try again.
4671                          */
4672                         if (pb->ino != EXT2_RESIZE_INO &&
4673                             extent.e_pblk < ctx->fs->super->s_blocks_count &&
4674                             ext2fs_test_block_bitmap2(ctx->block_metadata_map,
4675                                                       extent.e_pblk)) {
4676                                 next_try_repairs = 0;
4677                                 pctx->blk = blk;
4678                                 fix_problem_bad(ctx,
4679                                             PR_1_CRITICAL_METADATA_COLLISION,
4680                                             pctx, 2);
4681                                 if ((ctx->options & E2F_OPT_NO) == 0)
4682                                         ctx->flags |= E2F_FLAG_RESTART_LATER;
4683                         }
4684                         pctx->errcode = ext2fs_extent_get(ehandle,
4685                                                   EXT2_EXTENT_DOWN, &extent);
4686                         if (pctx->errcode &&
4687                             pctx->errcode != EXT2_ET_EXTENT_CSUM_INVALID) {
4688                                 pctx->str = "EXT2_EXTENT_DOWN";
4689                                 problem = PR_1_EXTENT_HEADER_INVALID;
4690                                 if (!next_try_repairs)
4691                                         return;
4692                                 if (pctx->errcode == EXT2_ET_EXTENT_HEADER_BAD)
4693                                         goto report_problem;
4694                                 return;
4695                         }
4696                         /* The next extent should match this index's logical start */
4697                         if (extent.e_lblk != lblk) {
4698                                 struct ext2_extent_info e_info;
4699
4700                                 pctx->errcode = ext2fs_extent_get_info(ehandle,
4701                                                                        &e_info);
4702                                 if (pctx->errcode) {
4703                                         pctx->str = "ext2fs_extent_get_info";
4704                                         return;
4705                                 }
4706                                 pctx->blk = lblk;
4707                                 pctx->blk2 = extent.e_lblk;
4708                                 pctx->num = e_info.curr_level - 1;
4709                                 problem = PR_1_EXTENT_INDEX_START_INVALID;
4710                                 if (fix_problem(ctx, problem, pctx)) {
4711                                         e2fsck_pass1_fix_lock(ctx);
4712                                         pb->inode_modified = 1;
4713                                         pctx->errcode =
4714                                                 ext2fs_extent_fix_parents(ehandle);
4715                                         e2fsck_pass1_fix_unlock(ctx);
4716                                         if (pctx->errcode) {
4717                                                 pctx->str = "ext2fs_extent_fix_parents";
4718                                                 return;
4719                                         }
4720                                 }
4721                         }
4722                         scan_extent_node(ctx, pctx, pb, extent.e_lblk,
4723                                          last_lblk, eof_block, ehandle,
4724                                          next_try_repairs);
4725                         if (pctx->errcode)
4726                                 return;
4727                         pctx->errcode = ext2fs_extent_get(ehandle,
4728                                                   EXT2_EXTENT_UP, &extent);
4729                         if (pctx->errcode) {
4730                                 pctx->str = "EXT2_EXTENT_UP";
4731                                 return;
4732                         }
4733                         mark_block_used(ctx, blk);
4734                         pb->num_blocks++;
4735                         goto next;
4736                 }
4737
4738                 if ((pb->previous_block != 0) &&
4739                     (pb->previous_block+1 != extent.e_pblk)) {
4740                         if (ctx->options & E2F_OPT_FRAGCHECK) {
4741                                 char type = '?';
4742
4743                                 if (pb->is_dir)
4744                                         type = 'd';
4745                                 else if (pb->is_reg)
4746                                         type = 'f';
4747
4748                                 printf(("%6lu(%c): expecting %6lu "
4749                                         "actual extent "
4750                                         "phys %6lu log %lu len %lu\n"),
4751                                        (unsigned long) pctx->ino, type,
4752                                        (unsigned long) pb->previous_block+1,
4753                                        (unsigned long) extent.e_pblk,
4754                                        (unsigned long) extent.e_lblk,
4755                                        (unsigned long) extent.e_len);
4756                         }
4757                         pb->fragmented = 1;
4758                 }
4759                 /*
4760                  * If we notice a gap in the logical block mappings of an
4761                  * extent-mapped directory, offer to close the hole by
4762                  * moving the logical block down, otherwise we'll go mad in
4763                  * pass 3 allocating empty directory blocks to fill the hole.
4764                  */
4765                 if (try_repairs && is_dir &&
4766                     pb->last_block + 1 < extent.e_lblk) {
4767                         blk64_t new_lblk;
4768
4769                         new_lblk = pb->last_block + 1;
4770                         if (EXT2FS_CLUSTER_RATIO(ctx->fs) > 1)
4771                                 new_lblk = ((new_lblk +
4772                                              EXT2FS_CLUSTER_RATIO(ctx->fs) - 1) &
4773                                             ~EXT2FS_CLUSTER_MASK(ctx->fs)) |
4774                                            (extent.e_pblk &
4775                                             EXT2FS_CLUSTER_MASK(ctx->fs));
4776                         pctx->blk = extent.e_lblk;
4777                         pctx->blk2 = new_lblk;
4778                         if (fix_problem(ctx, PR_1_COLLAPSE_DBLOCK, pctx)) {
4779                                 e2fsck_pass1_fix_lock(ctx);
4780                                 extent.e_lblk = new_lblk;
4781                                 pb->inode_modified = 1;
4782                                 pctx->errcode = ext2fs_extent_replace(ehandle,
4783                                                                 0, &extent);
4784                                 e2fsck_pass1_fix_unlock(ctx);
4785                                 if (pctx->errcode) {
4786                                         pctx->errcode = 0;
4787                                         goto alloc_later;
4788                                 }
4789                                 e2fsck_pass1_fix_lock(ctx);
4790                                 pctx->errcode = ext2fs_extent_fix_parents(ehandle);
4791                                 e2fsck_pass1_fix_unlock(ctx);
4792                                 if (pctx->errcode)
4793                                         goto failed_add_dir_block;
4794                                 pctx->errcode = ext2fs_extent_goto(ehandle,
4795                                                                 extent.e_lblk);
4796                                 if (pctx->errcode)
4797                                         goto failed_add_dir_block;
4798                                 last_lblk = extent.e_lblk + extent.e_len - 1;
4799                                 failed_csum = 0;
4800                         }
4801                 }
4802 alloc_later:
4803                 if (is_dir) {
4804                         while (++pb->last_db_block <
4805                                (e2_blkcnt_t) extent.e_lblk) {
4806                                 pctx->errcode = ext2fs_add_dir_block2(
4807                                                         ctx->fs->dblist,
4808                                                         pb->ino, 0,
4809                                                         pb->last_db_block);
4810                                 if (pctx->errcode) {
4811                                         pctx->blk = 0;
4812                                         pctx->num = pb->last_db_block;
4813                                         goto failed_add_dir_block;
4814                                 }
4815                         }
4816
4817                         for (i = 0; i < extent.e_len; i++) {
4818                                 pctx->errcode = ext2fs_add_dir_block2(
4819                                                         ctx->fs->dblist,
4820                                                         pctx->ino,
4821                                                         extent.e_pblk + i,
4822                                                         extent.e_lblk + i);
4823                                 if (pctx->errcode) {
4824                                         pctx->blk = extent.e_pblk + i;
4825                                         pctx->num = extent.e_lblk + i;
4826                                 failed_add_dir_block:
4827                                         fix_problem(ctx, PR_1_ADD_DBLOCK, pctx);
4828                                         /* Should never get here */
4829                                         ctx->flags |= E2F_FLAG_ABORT;
4830                                         return;
4831                                 }
4832                         }
4833                         if (extent.e_len > 0)
4834                                 pb->last_db_block = extent.e_lblk + extent.e_len - 1;
4835                 }
4836                 if (has_unaligned_cluster_map(ctx, pb->previous_block,
4837                                               pb->last_block,
4838                                               extent.e_pblk,
4839                                               extent.e_lblk)) {
4840                         for (i = 0; i < extent.e_len; i++) {
4841                                 pctx->blk = extent.e_lblk + i;
4842                                 pctx->blk2 = extent.e_pblk + i;
4843                                 fix_problem(ctx, PR_1_MISALIGNED_CLUSTER, pctx);
4844                                 mark_block_used(ctx, extent.e_pblk + i);
4845                                 mark_block_used(ctx, extent.e_pblk + i);
4846                         }
4847                 }
4848
4849                 /*
4850                  * Check whether first cluster got marked in previous iteration.
4851                  */
4852                 if (ctx->fs->cluster_ratio_bits &&
4853                     pb->previous_block &&
4854                     (EXT2FS_B2C(ctx->fs, extent.e_pblk) ==
4855                      EXT2FS_B2C(ctx->fs, pb->previous_block)))
4856                         /* Set blk to the beginning of next cluster. */
4857                         blk = EXT2FS_C2B(
4858                                 ctx->fs,
4859                                 EXT2FS_B2C(ctx->fs, extent.e_pblk) + 1);
4860                 else
4861                         /* Set blk to the beginning of current cluster. */
4862                         blk = EXT2FS_C2B(ctx->fs,
4863                                          EXT2FS_B2C(ctx->fs, extent.e_pblk));
4864
4865                 if (blk < extent.e_pblk + extent.e_len) {
4866                         mark_blocks_used(ctx, blk,
4867                                          extent.e_pblk + extent.e_len - blk);
4868                         n = DIV_ROUND_UP(extent.e_pblk + extent.e_len - blk,
4869                                          EXT2FS_CLUSTER_RATIO(ctx->fs));
4870                         pb->num_blocks += n;
4871                 }
4872                 pb->last_block = extent.e_lblk + extent.e_len - 1;
4873                 pb->previous_block = extent.e_pblk + extent.e_len - 1;
4874                 start_block = pb->last_block = last_lblk;
4875                 if (is_leaf && !is_dir &&
4876                     !(extent.e_flags & EXT2_EXTENT_FLAGS_UNINIT))
4877                         pb->last_init_lblock = last_lblk;
4878         next:
4879                 pctx->errcode = ext2fs_extent_get(ehandle,
4880                                                   EXT2_EXTENT_NEXT_SIB,
4881                                                   &extent);
4882         }
4883
4884         /* Failed csum but passes checks?  Ask to fix checksum. */
4885         if (failed_csum &&
4886             fix_problem(ctx, PR_1_EXTENT_ONLY_CSUM_INVALID, pctx)) {
4887                 e2fsck_pass1_fix_lock(ctx);
4888                 pb->inode_modified = 1;
4889                 pctx->errcode = ext2fs_extent_replace(ehandle, 0, &extent);
4890                 e2fsck_pass1_fix_unlock(ctx);
4891                 if (pctx->errcode)
4892                         return;
4893         }
4894
4895         if (pctx->errcode == EXT2_ET_EXTENT_NO_NEXT)
4896                 pctx->errcode = 0;
4897 }
4898
4899 static void check_blocks_extents(e2fsck_t ctx, struct problem_context *pctx,
4900                                  struct process_block_struct *pb)
4901 {
4902         struct ext2_extent_info info;
4903         struct ext2_inode       *inode = pctx->inode;
4904         ext2_extent_handle_t    ehandle;
4905         ext2_filsys             fs = ctx->fs;
4906         ext2_ino_t              ino = pctx->ino;
4907         errcode_t               retval;
4908         blk64_t                 eof_lblk;
4909         struct ext3_extent_header       *eh;
4910
4911         /* Check for a proper extent header... */
4912         eh = (struct ext3_extent_header *) &inode->i_block[0];
4913         retval = ext2fs_extent_header_verify(eh, sizeof(inode->i_block));
4914         if (retval) {
4915                 if (fix_problem(ctx, PR_1_MISSING_EXTENT_HEADER, pctx))
4916                         e2fsck_clear_inode(ctx, ino, inode, 0,
4917                                            "check_blocks_extents");
4918                 pctx->errcode = 0;
4919                 return;
4920         }
4921
4922         /* ...since this function doesn't fail if i_block is zeroed. */
4923         pctx->errcode = ext2fs_extent_open2(fs, ino, inode, &ehandle);
4924         if (pctx->errcode) {
4925                 if (fix_problem(ctx, PR_1_READ_EXTENT, pctx))
4926                         e2fsck_clear_inode(ctx, ino, inode, 0,
4927                                            "check_blocks_extents");
4928                 pctx->errcode = 0;
4929                 return;
4930         }
4931
4932         retval = ext2fs_extent_get_info(ehandle, &info);
4933         if (retval == 0) {
4934                 int max_depth = info.max_depth;
4935
4936                 if (max_depth >= MAX_EXTENT_DEPTH_COUNT)
4937                         max_depth = MAX_EXTENT_DEPTH_COUNT-1;
4938                 ctx->extent_depth_count[max_depth]++;
4939         }
4940
4941         /* Check maximum extent depth */
4942         pctx->blk = info.max_depth;
4943         pctx->blk2 = ext2fs_max_extent_depth(ehandle);
4944         if (pctx->blk2 < pctx->blk &&
4945             fix_problem(ctx, PR_1_EXTENT_BAD_MAX_DEPTH, pctx))
4946                 pb->eti.force_rebuild = 1;
4947
4948         /* Can we collect extent tree level stats? */
4949         pctx->blk = MAX_EXTENT_DEPTH_COUNT;
4950         if (pctx->blk2 > pctx->blk)
4951                 fix_problem(ctx, PR_1E_MAX_EXTENT_TREE_DEPTH, pctx);
4952         memset(pb->eti.ext_info, 0, sizeof(pb->eti.ext_info));
4953         pb->eti.ino = pb->ino;
4954
4955         pb->next_lblock = 0;
4956
4957         eof_lblk = ((EXT2_I_SIZE(inode) + fs->blocksize - 1) >>
4958                 EXT2_BLOCK_SIZE_BITS(fs->super)) - 1;
4959         scan_extent_node(ctx, pctx, pb, 0, 0, eof_lblk, ehandle, 1);
4960         if (pctx->errcode &&
4961             fix_problem(ctx, PR_1_EXTENT_ITERATE_FAILURE, pctx)) {
4962                 pb->num_blocks = 0;
4963                 inode->i_blocks = 0;
4964                 e2fsck_clear_inode(ctx, ino, inode, E2F_FLAG_RESTART,
4965                                    "check_blocks_extents");
4966                 pctx->errcode = 0;
4967         }
4968         ext2fs_extent_free(ehandle);
4969
4970         /* Rebuild unless it's a dir and we're rehashing it */
4971         if (LINUX_S_ISDIR(inode->i_mode) &&
4972             e2fsck_dir_will_be_rehashed(ctx, ino))
4973                 return;
4974
4975         if (ctx->options & E2F_OPT_CONVERT_BMAP)
4976                 e2fsck_rebuild_extents_later(ctx, ino);
4977         else
4978                 e2fsck_should_rebuild_extents(ctx, pctx, &pb->eti, &info);
4979 }
4980
4981 /*
4982  * In fact we don't need to check blocks for an inode with inline data
4983  * because this inode doesn't have any blocks.  In this function all
4984  * we need to do is add this inode into dblist when it is a directory.
4985  */
4986 static void check_blocks_inline_data(e2fsck_t ctx, struct problem_context *pctx,
4987                                      struct process_block_struct *pb)
4988 {
4989         int     flags;
4990         size_t  inline_data_size = 0;
4991
4992         if (!pb->is_dir) {
4993                 pctx->errcode = 0;
4994                 return;
4995         }
4996
4997         /* Process the dirents in i_block[] as the "first" block. */
4998         pctx->errcode = ext2fs_add_dir_block2(ctx->fs->dblist, pb->ino, 0, 0);
4999         if (pctx->errcode)
5000                 goto err;
5001
5002         /* Process the dirents in the EA as a "second" block. */
5003         flags = ctx->fs->flags;
5004         ctx->fs->flags |= EXT2_FLAG_IGNORE_CSUM_ERRORS;
5005         pctx->errcode = ext2fs_inline_data_size(ctx->fs, pb->ino,
5006                                                 &inline_data_size);
5007         ctx->fs->flags = (flags & EXT2_FLAG_IGNORE_CSUM_ERRORS) |
5008                          (ctx->fs->flags & ~EXT2_FLAG_IGNORE_CSUM_ERRORS);
5009         if (pctx->errcode) {
5010                 pctx->errcode = 0;
5011                 return;
5012         }
5013
5014         if (inline_data_size <= EXT4_MIN_INLINE_DATA_SIZE)
5015                 return;
5016
5017         pctx->errcode = ext2fs_add_dir_block2(ctx->fs->dblist, pb->ino, 0, 1);
5018         if (pctx->errcode)
5019                 goto err;
5020
5021         return;
5022 err:
5023         pctx->blk = 0;
5024         pctx->num = 0;
5025         fix_problem(ctx, PR_1_ADD_DBLOCK, pctx);
5026         ctx->flags |= E2F_FLAG_ABORT;
5027 }
5028
5029 /*
5030  * This subroutine is called on each inode to account for all of the
5031  * blocks used by that inode.
5032  */
5033 static void check_blocks(e2fsck_t ctx, struct problem_context *pctx,
5034                          char *block_buf, const struct ea_quota *ea_ibody_quota)
5035 {
5036         ext2_filsys fs = ctx->fs;
5037         struct process_block_struct pb;
5038         ext2_ino_t      ino = pctx->ino;
5039         struct ext2_inode *inode = pctx->inode;
5040         unsigned        bad_size = 0;
5041         int             dirty_inode = 0;
5042         int             extent_fs;
5043         int             inlinedata_fs;
5044         __u64           size;
5045         struct ea_quota ea_block_quota;
5046
5047         pb.ino = ino;
5048         pb.num_blocks = EXT2FS_B2C(ctx->fs,
5049                                    ea_ibody_quota ? ea_ibody_quota->blocks : 0);
5050         pb.last_block = ~0;
5051         pb.last_init_lblock = -1;
5052         pb.last_db_block = -1;
5053         pb.num_illegal_blocks = 0;
5054         pb.suppress = 0; pb.clear = 0;
5055         pb.fragmented = 0;
5056         pb.compressed = 0;
5057         pb.previous_block = 0;
5058         pb.is_dir = LINUX_S_ISDIR(inode->i_mode);
5059         pb.is_reg = LINUX_S_ISREG(inode->i_mode);
5060         pb.max_blocks = 1U << (31 - fs->super->s_log_block_size);
5061         pb.inode = inode;
5062         pb.pctx = pctx;
5063         pb.ctx = ctx;
5064         pb.inode_modified = 0;
5065         pb.eti.force_rebuild = 0;
5066         pctx->ino = ino;
5067         pctx->errcode = 0;
5068
5069         extent_fs = ext2fs_has_feature_extents(ctx->fs->super);
5070         inlinedata_fs = ext2fs_has_feature_inline_data(ctx->fs->super);
5071
5072         if (check_ext_attr(ctx, pctx, block_buf, &ea_block_quota)) {
5073                 if (e2fsck_should_abort(ctx))
5074                         goto out;
5075                 pb.num_blocks += EXT2FS_B2C(ctx->fs, ea_block_quota.blocks);
5076         }
5077
5078         if (inlinedata_fs && (inode->i_flags & EXT4_INLINE_DATA_FL))
5079                 check_blocks_inline_data(ctx, pctx, &pb);
5080         else if (ext2fs_inode_has_valid_blocks2(fs, inode)) {
5081                 if (extent_fs && (inode->i_flags & EXT4_EXTENTS_FL))
5082                         check_blocks_extents(ctx, pctx, &pb);
5083                 else {
5084                         int flags;
5085                         /*
5086                          * If we've modified the inode, write it out before
5087                          * iterate() tries to use it.
5088                          */
5089                         if (dirty_inode) {
5090                                 e2fsck_write_inode(ctx, ino, inode,
5091                                                    "check_blocks");
5092                                 dirty_inode = 0;
5093                         }
5094                         flags = fs->flags;
5095                         fs->flags |= EXT2_FLAG_IGNORE_CSUM_ERRORS;
5096                         pctx->errcode = ext2fs_block_iterate3(fs, ino,
5097                                                 pb.is_dir ? BLOCK_FLAG_HOLE : 0,
5098                                                 block_buf, process_block, &pb);
5099                         /*
5100                          * We do not have uninitialized extents in non extent
5101                          * files.
5102                          */
5103                         pb.last_init_lblock = pb.last_block;
5104                         /*
5105                          * If iterate() changed a block mapping, we have to
5106                          * re-read the inode.  If we decide to clear the
5107                          * inode after clearing some stuff, we'll re-write the
5108                          * bad mappings into the inode!
5109                          */
5110                         if (pb.inode_modified)
5111                                 e2fsck_read_inode(ctx, ino, inode,
5112                                                   "check_blocks");
5113                         fs->flags = (flags & EXT2_FLAG_IGNORE_CSUM_ERRORS) |
5114                                     (fs->flags & ~EXT2_FLAG_IGNORE_CSUM_ERRORS);
5115
5116                         if (ctx->options & E2F_OPT_CONVERT_BMAP) {
5117 #ifdef DEBUG
5118                                 printf("bmap rebuild ino=%d\n", ino);
5119 #endif
5120                                 if (!LINUX_S_ISDIR(inode->i_mode) ||
5121                                     !e2fsck_dir_will_be_rehashed(ctx, ino))
5122                                         e2fsck_rebuild_extents_later(ctx, ino);
5123                         }
5124                 }
5125         }
5126         end_problem_latch(ctx, PR_LATCH_BLOCK);
5127         end_problem_latch(ctx, PR_LATCH_TOOBIG);
5128         if (e2fsck_should_abort(ctx))
5129                 goto out;
5130         if (pctx->errcode)
5131                 fix_problem(ctx, PR_1_BLOCK_ITERATE, pctx);
5132
5133         if (pb.fragmented && pb.num_blocks < fs->super->s_blocks_per_group) {
5134                 if (LINUX_S_ISDIR(inode->i_mode))
5135                         ctx->fs_fragmented_dir++;
5136                 else
5137                         ctx->fs_fragmented++;
5138         }
5139
5140         if (pb.clear) {
5141                 e2fsck_clear_inode(ctx, ino, inode, E2F_FLAG_RESTART,
5142                                    "check_blocks");
5143                 return;
5144         }
5145
5146         if (inode->i_flags & EXT2_INDEX_FL) {
5147                 if (handle_htree(ctx, pctx, ino, inode, block_buf)) {
5148                         inode->i_flags &= ~EXT2_INDEX_FL;
5149                         dirty_inode++;
5150                 } else {
5151                         e2fsck_add_dx_dir(ctx, ino, inode, pb.last_block+1);
5152                 }
5153         }
5154
5155         if (!pb.num_blocks && pb.is_dir &&
5156             !(inode->i_flags & EXT4_INLINE_DATA_FL)) {
5157                 /*
5158                  * The mode might be in-correct. Increasing the badness by
5159                  * small amount won't hurt much.
5160                  */
5161                 if (fix_problem(ctx, PR_1_ZERO_LENGTH_DIR, pctx)) {
5162                         e2fsck_clear_inode(ctx, ino, inode, 0, "check_blocks");
5163                         ctx->fs_directory_count--;
5164                         return;
5165                 }
5166         }
5167
5168         if (ino != quota_type2inum(PRJQUOTA, fs->super) &&
5169             (ino == EXT2_ROOT_INO || ino >= EXT2_FIRST_INODE(ctx->fs->super)) &&
5170             !(inode->i_flags & EXT4_EA_INODE_FL)) {
5171                 quota_data_add(ctx->qctx, (struct ext2_inode_large *) inode,
5172                                ino,
5173                                pb.num_blocks * EXT2_CLUSTER_SIZE(fs->super));
5174                 quota_data_inodes(ctx->qctx, (struct ext2_inode_large *) inode,
5175                                   ino, (ea_ibody_quota ?
5176                                         ea_ibody_quota->inodes : 0) +
5177                                                 ea_block_quota.inodes + 1);
5178         }
5179
5180         if (!ext2fs_has_feature_huge_file(fs->super) ||
5181             !(inode->i_flags & EXT4_HUGE_FILE_FL))
5182                 pb.num_blocks *= (fs->blocksize / 512);
5183         pb.num_blocks *= EXT2FS_CLUSTER_RATIO(fs);
5184 #if 0
5185         printf("inode %u, i_size = %u, last_block = %llu, i_blocks=%llu, num_blocks = %llu\n",
5186                ino, inode->i_size, (unsigned long long) pb.last_block,
5187                (unsigned long long) ext2fs_inode_i_blocks(fs, inode),
5188                (unsigned long long) pb.num_blocks);
5189 #endif
5190         size = EXT2_I_SIZE(inode);
5191         if (pb.is_dir) {
5192                 unsigned nblock = size >> EXT2_BLOCK_SIZE_BITS(fs->super);
5193                 if (inode->i_flags & EXT4_INLINE_DATA_FL) {
5194                         int flags;
5195                         size_t sz = 0;
5196                         errcode_t err;
5197
5198                         flags = ctx->fs->flags;
5199                         ctx->fs->flags |= EXT2_FLAG_IGNORE_CSUM_ERRORS;
5200                         err = ext2fs_inline_data_size(ctx->fs, pctx->ino,
5201                                                       &sz);
5202                         ctx->fs->flags = (flags &
5203                                           EXT2_FLAG_IGNORE_CSUM_ERRORS) |
5204                                          (ctx->fs->flags &
5205                                           ~EXT2_FLAG_IGNORE_CSUM_ERRORS);
5206                         if (err || sz != size) {
5207                                 bad_size = 7;
5208                                 pctx->num = sz;
5209                         }
5210                 } else if (size & (fs->blocksize - 1))
5211                         bad_size = 5;
5212                 else if (nblock > (pb.last_block + 1))
5213                         bad_size = 1;
5214                 else if (nblock < (pb.last_block + 1)) {
5215                         if (((pb.last_block + 1) - nblock) >
5216                             fs->super->s_prealloc_dir_blocks)
5217                                 bad_size = 2;
5218                 }
5219         } else {
5220                 if ((pb.last_init_lblock >= 0) &&
5221                     /* Do not allow initialized allocated blocks past i_size*/
5222                     (size < (__u64)pb.last_init_lblock * fs->blocksize) &&
5223                     !(inode->i_flags & EXT4_VERITY_FL))
5224                         bad_size = 3;
5225                 else if (!(extent_fs && (inode->i_flags & EXT4_EXTENTS_FL)) &&
5226                          size > ext2_max_sizes[fs->super->s_log_block_size])
5227                         /* too big for a direct/indirect-mapped file */
5228                         bad_size = 4;
5229                 else if ((extent_fs && (inode->i_flags & EXT4_EXTENTS_FL)) &&
5230                          size >
5231                          ((1ULL << (32 + EXT2_BLOCK_SIZE_BITS(fs->super))) - 1))
5232                         /* too big for an extent-based file - 32bit ee_block */
5233                         bad_size = 6;
5234         }
5235         /* i_size for symlinks is checked elsewhere */
5236         if (bad_size && !LINUX_S_ISLNK(inode->i_mode)) {
5237                 /* Did inline_data set pctx->num earlier? */
5238                 if (bad_size != 7)
5239                         pctx->num = (pb.last_block + 1) * fs->blocksize;
5240                 pctx->group = bad_size;
5241                 if (fix_problem(ctx, PR_1_BAD_I_SIZE, pctx)) {
5242                         ext2fs_inode_size_set(fs, inode, pctx->num);
5243                         if (EXT2_I_SIZE(inode) == 0 &&
5244                             (inode->i_flags & EXT4_INLINE_DATA_FL)) {
5245                                 memset(inode->i_block, 0,
5246                                        sizeof(inode->i_block));
5247                                 inode->i_flags &= ~EXT4_INLINE_DATA_FL;
5248                         }
5249                         dirty_inode++;
5250                 }
5251                 pctx->num = 0;
5252         }
5253         if (LINUX_S_ISREG(inode->i_mode) &&
5254             ext2fs_needs_large_file_feature(EXT2_I_SIZE(inode)))
5255                 ctx->large_files++;
5256         if ((fs->super->s_creator_os != EXT2_OS_HURD) &&
5257             ((pb.num_blocks != ext2fs_inode_i_blocks(fs, inode)) ||
5258              (ext2fs_has_feature_huge_file(fs->super) &&
5259               (inode->i_flags & EXT4_HUGE_FILE_FL) &&
5260               (inode->osd2.linux2.l_i_blocks_hi != 0)))) {
5261                 pctx->num = pb.num_blocks;
5262                 if (fix_problem(ctx, PR_1_BAD_I_BLOCKS, pctx)) {
5263                         inode->i_blocks = pb.num_blocks;
5264                         inode->osd2.linux2.l_i_blocks_hi = pb.num_blocks >> 32;
5265                         dirty_inode++;
5266                 }
5267                 pctx->num = 0;
5268         }
5269
5270         /*
5271          * The kernel gets mad if we ask it to allocate bigalloc clusters to
5272          * a block mapped file, so rebuild it as an extent file.  We can skip
5273          * symlinks because they're never rewritten.
5274          */
5275         if (ext2fs_has_feature_bigalloc(fs->super) &&
5276             (LINUX_S_ISREG(inode->i_mode) || LINUX_S_ISDIR(inode->i_mode)) &&
5277             ext2fs_inode_data_blocks2(fs, inode) > 0 &&
5278             (ino == EXT2_ROOT_INO || ino >= EXT2_FIRST_INO(fs->super)) &&
5279             !(inode->i_flags & (EXT4_EXTENTS_FL | EXT4_INLINE_DATA_FL)) &&
5280             fix_problem(ctx, PR_1_NO_BIGALLOC_BLOCKMAP_FILES, pctx)) {
5281                 pctx->errcode = e2fsck_rebuild_extents_later(ctx, ino);
5282                 if (pctx->errcode)
5283                         goto out;
5284         }
5285
5286         if (ctx->dirs_to_hash && pb.is_dir &&
5287             !(ctx->lost_and_found && ctx->lost_and_found == ino) &&
5288             !(inode->i_flags & EXT2_INDEX_FL) &&
5289             ((inode->i_size / fs->blocksize) >= 3))
5290                 e2fsck_rehash_dir_later(ctx, ino);
5291
5292 out:
5293         /* need restart if clearing bad inode after block processing */
5294         if (e2fsck_fix_bad_inode(ctx, pctx))
5295                 e2fsck_clear_inode(ctx, ino, inode, E2F_FLAG_RESTART,
5296                                    "check_blocks_bad");
5297         else if (dirty_inode)
5298                 e2fsck_write_inode(ctx, ino, inode, "check_blocks");
5299 }
5300
5301 #if 0
5302 /*
5303  * Helper function called by process block when an illegal block is
5304  * found.  It returns a description about why the block is illegal
5305  */
5306 static char *describe_illegal_block(ext2_filsys fs, blk64_t block)
5307 {
5308         blk64_t super;
5309         int     i;
5310         static char     problem[80];
5311
5312         super = fs->super->s_first_data_block;
5313         strcpy(problem, "PROGRAMMING ERROR: Unknown reason for illegal block");
5314         if (block < super) {
5315                 sprintf(problem, "< FIRSTBLOCK (%u)", super);
5316                 return(problem);
5317         } else if (block >= ext2fs_blocks_count(fs->super)) {
5318                 sprintf(problem, "> BLOCKS (%u)", ext2fs_blocks_count(fs->super));
5319                 return(problem);
5320         }
5321         for (i = 0; i < fs->group_desc_count; i++) {
5322                 if (block == super) {
5323                         sprintf(problem, "is the superblock in group %d", i);
5324                         break;
5325                 }
5326                 if (block > super &&
5327                     block <= (super + fs->desc_blocks)) {
5328                         sprintf(problem, "is in the group descriptors "
5329                                 "of group %d", i);
5330                         break;
5331                 }
5332                 if (block == ext2fs_block_bitmap_loc(fs, i)) {
5333                         sprintf(problem, "is the block bitmap of group %d", i);
5334                         break;
5335                 }
5336                 if (block == ext2fs_inode_bitmap_loc(fs, i)) {
5337                         sprintf(problem, "is the inode bitmap of group %d", i);
5338                         break;
5339                 }
5340                 if (block >= ext2fs_inode_table_loc(fs, i) &&
5341                     (block < ext2fs_inode_table_loc(fs, i)
5342                      + fs->inode_blocks_per_group)) {
5343                         sprintf(problem, "is in the inode table of group %d",
5344                                 i);
5345                         break;
5346                 }
5347                 super += fs->super->s_blocks_per_group;
5348         }
5349         return(problem);
5350 }
5351 #endif
5352
5353 /*
5354  * This is a helper function for check_blocks().
5355  */
5356 static int process_block(ext2_filsys fs,
5357                   blk64_t       *block_nr,
5358                   e2_blkcnt_t blockcnt,
5359                   blk64_t ref_block EXT2FS_ATTR((unused)),
5360                   int ref_offset EXT2FS_ATTR((unused)),
5361                   void *priv_data)
5362 {
5363         struct process_block_struct *p;
5364         struct problem_context *pctx;
5365         blk64_t blk = *block_nr;
5366         int     ret_code = 0;
5367         problem_t       problem = 0;
5368         e2fsck_t        ctx;
5369
5370         p = (struct process_block_struct *) priv_data;
5371         pctx = p->pctx;
5372         ctx = p->ctx;
5373
5374         /*
5375          * For a directory, add logical block zero for processing even if it's
5376          * not mapped or we'll be perennially stuck with broken "." and ".."
5377          * entries.
5378          */
5379         if (p->is_dir && blockcnt == 0 && blk == 0) {
5380                 pctx->errcode = ext2fs_add_dir_block2(fs->dblist, p->ino, 0, 0);
5381                 if (pctx->errcode) {
5382                         pctx->blk = blk;
5383                         pctx->num = blockcnt;
5384                         goto failed_add_dir_block;
5385                 }
5386                 p->last_db_block++;
5387         }
5388
5389         if (blk == 0)
5390                 return 0;
5391
5392 #if 0
5393         printf("Process_block, inode %lu, block %u, #%d\n", p->ino, blk,
5394                blockcnt);
5395 #endif
5396
5397         /*
5398          * Simplistic fragmentation check.  We merely require that the
5399          * file be contiguous.  (Which can never be true for really
5400          * big files that are greater than a block group.)
5401          */
5402         if (p->previous_block && p->ino != EXT2_RESIZE_INO) {
5403                 if (p->previous_block+1 != blk) {
5404                         if (ctx->options & E2F_OPT_FRAGCHECK) {
5405                                 char type = '?';
5406
5407                                 if (p->is_dir)
5408                                         type = 'd';
5409                                 else if (p->is_reg)
5410                                         type = 'f';
5411
5412                                 printf(_("%6lu(%c): expecting %6lu "
5413                                          "got phys %6lu (blkcnt %lld)\n"),
5414                                        (unsigned long) pctx->ino, type,
5415                                        (unsigned long) p->previous_block+1,
5416                                        (unsigned long) blk,
5417                                        (long long) blockcnt);
5418                         }
5419                         p->fragmented = 1;
5420                 }
5421         }
5422
5423         if (p->is_dir && !ext2fs_has_feature_largedir(fs->super) &&
5424             !pctx->inode->i_size_high &&
5425             blockcnt > (1 << (21 - fs->super->s_log_block_size)))
5426                 problem = PR_1_TOOBIG_DIR;
5427         if (p->is_dir && p->num_blocks + 1 >= p->max_blocks)
5428                 problem = PR_1_TOOBIG_DIR;
5429         if (p->is_reg && p->num_blocks + 1 >= p->max_blocks)
5430                 problem = PR_1_TOOBIG_REG;
5431         if (!p->is_dir && !p->is_reg && blockcnt > 0)
5432                 problem = PR_1_TOOBIG_SYMLINK;
5433
5434         if (blk < fs->super->s_first_data_block ||
5435             blk >= ext2fs_blocks_count(fs->super))
5436                 problem = PR_1_ILLEGAL_BLOCK_NUM;
5437
5438         /*
5439          * If this IND/DIND/TIND block is squatting atop some critical metadata
5440          * (group descriptors, superblock, bitmap, inode table), any write to
5441          * "fix" mapping problems will destroy the metadata.  We'll let pass 1b
5442          * fix that and restart fsck.
5443          */
5444         if (blockcnt < 0 &&
5445             p->ino != EXT2_RESIZE_INO &&
5446             blk < ctx->fs->super->s_blocks_count &&
5447             ext2fs_test_block_bitmap2(ctx->block_metadata_map, blk)) {
5448                 pctx->blk = blk;
5449                 fix_problem_bad(ctx, PR_1_CRITICAL_METADATA_COLLISION, pctx, 2);
5450                 if ((ctx->options & E2F_OPT_NO) == 0)
5451                         ctx->flags |= E2F_FLAG_RESTART_LATER;
5452         }
5453
5454         if (problem) {
5455                 p->num_illegal_blocks++;
5456                 /*
5457                  * A bit of subterfuge here -- we're trying to fix a block
5458                  * mapping, but the IND/DIND/TIND block could have collided
5459                  * with some critical metadata.  So, fix the in-core mapping so
5460                  * iterate won't go insane, but return 0 instead of
5461                  * BLOCK_CHANGED so that it won't write the remapping out to
5462                  * our multiply linked block.
5463                  *
5464                  * Even if we previously determined that an *IND block
5465                  * conflicts with critical metadata, we must still try to
5466                  * iterate the *IND block as if it is an *IND block to find and
5467                  * mark the blocks it points to.  Better to be overly cautious
5468                  * with the used_blocks map so that we don't move the *IND
5469                  * block to a block that's really in use!
5470                  */
5471                 if (p->ino != EXT2_RESIZE_INO &&
5472                     ref_block != 0 &&
5473                     ext2fs_test_block_bitmap2(ctx->block_metadata_map,
5474                                               ref_block)) {
5475                         *block_nr = 0;
5476                         return 0;
5477                 }
5478                 if (!p->suppress && (p->num_illegal_blocks % 12) == 0) {
5479                         if (fix_problem(ctx, PR_1_TOO_MANY_BAD_BLOCKS, pctx)) {
5480                                 p->clear = 1;
5481                                 return BLOCK_ABORT;
5482                         }
5483                         if (fix_problem(ctx, PR_1_SUPPRESS_MESSAGES, pctx)) {
5484                                 p->suppress = 1;
5485                                 set_latch_flags(PR_LATCH_BLOCK,
5486                                                 PRL_SUPPRESS, 0);
5487                         }
5488                 }
5489                 pctx->blk = blk;
5490                 pctx->blkcount = blockcnt;
5491                 if (fix_problem(ctx, problem, pctx)) {
5492                         blk = *block_nr = 0;
5493                         ret_code = BLOCK_CHANGED;
5494                         p->inode_modified = 1;
5495                         /*
5496                          * If the directory block is too big and is beyond the
5497                          * end of the FS, don't bother trying to add it for
5498                          * processing -- the kernel would never have created a
5499                          * directory this large, and we risk an ENOMEM abort.
5500                          * In any case, the toobig handler for extent-based
5501                          * directories also doesn't feed toobig blocks to
5502                          * pass 2.
5503                          */
5504                         if (problem == PR_1_TOOBIG_DIR)
5505                                 return ret_code;
5506                         goto mark_dir;
5507                 } else
5508                         return 0;
5509         }
5510
5511         if (p->ino == EXT2_RESIZE_INO) {
5512                 /*
5513                  * The resize inode has already be sanity checked
5514                  * during pass #0 (the superblock checks).  All we
5515                  * have to do is mark the double indirect block as
5516                  * being in use; all of the other blocks are handled
5517                  * by mark_table_blocks()).
5518                  */
5519                 if (blockcnt == BLOCK_COUNT_DIND)
5520                         mark_block_used(ctx, blk);
5521                 p->num_blocks++;
5522         } else if (!(ctx->fs->cluster_ratio_bits &&
5523                      p->previous_block &&
5524                      (EXT2FS_B2C(ctx->fs, blk) ==
5525                       EXT2FS_B2C(ctx->fs, p->previous_block)) &&
5526                      (blk & EXT2FS_CLUSTER_MASK(ctx->fs)) ==
5527                      ((unsigned) blockcnt & EXT2FS_CLUSTER_MASK(ctx->fs)))) {
5528                 mark_block_used(ctx, blk);
5529                 p->num_blocks++;
5530         } else if (has_unaligned_cluster_map(ctx, p->previous_block,
5531                                              p->last_block, blk, blockcnt)) {
5532                 pctx->blk = blockcnt;
5533                 pctx->blk2 = blk;
5534                 fix_problem(ctx, PR_1_MISALIGNED_CLUSTER, pctx);
5535                 mark_block_used(ctx, blk);
5536                 mark_block_used(ctx, blk);
5537         }
5538         if (blockcnt >= 0)
5539                 p->last_block = blockcnt;
5540         p->previous_block = blk;
5541 mark_dir:
5542         if (p->is_dir && (blockcnt >= 0)) {
5543                 while (++p->last_db_block < blockcnt) {
5544                         pctx->errcode = ext2fs_add_dir_block2(fs->dblist,
5545                                                               p->ino, 0,
5546                                                               p->last_db_block);
5547                         if (pctx->errcode) {
5548                                 pctx->blk = 0;
5549                                 pctx->num = p->last_db_block;
5550                                 goto failed_add_dir_block;
5551                         }
5552                 }
5553                 pctx->errcode = ext2fs_add_dir_block2(fs->dblist, p->ino,
5554                                                       blk, blockcnt);
5555                 if (pctx->errcode) {
5556                         pctx->blk = blk;
5557                         pctx->num = blockcnt;
5558                 failed_add_dir_block:
5559                         fix_problem(ctx, PR_1_ADD_DBLOCK, pctx);
5560                         /* Should never get here */
5561                         ctx->flags |= E2F_FLAG_ABORT;
5562                         return BLOCK_ABORT;
5563                 }
5564         }
5565         return ret_code;
5566 }
5567
5568 static int process_bad_block(ext2_filsys fs,
5569                       blk64_t *block_nr,
5570                       e2_blkcnt_t blockcnt,
5571                       blk64_t ref_block EXT2FS_ATTR((unused)),
5572                       int ref_offset EXT2FS_ATTR((unused)),
5573                       void *priv_data)
5574 {
5575         struct process_block_struct *p;
5576         blk64_t         blk = *block_nr;
5577         blk64_t         first_block;
5578         dgrp_t          i;
5579         struct problem_context *pctx;
5580         e2fsck_t        ctx;
5581
5582         if (!blk)
5583                 return 0;
5584
5585         p = (struct process_block_struct *) priv_data;
5586         ctx = p->ctx;
5587         pctx = p->pctx;
5588
5589         pctx->ino = EXT2_BAD_INO;
5590         pctx->blk = blk;
5591         pctx->blkcount = blockcnt;
5592
5593         if ((blk < fs->super->s_first_data_block) ||
5594             (blk >= ext2fs_blocks_count(fs->super))) {
5595                 if (fix_problem(ctx, PR_1_BB_ILLEGAL_BLOCK_NUM, pctx)) {
5596                         *block_nr = 0;
5597                         return BLOCK_CHANGED;
5598                 } else
5599                         return 0;
5600         }
5601
5602         if (blockcnt < 0) {
5603                 if (ext2fs_test_block_bitmap2(p->fs_meta_blocks, blk)) {
5604                         p->bbcheck = 1;
5605                         if (fix_problem(ctx, PR_1_BB_FS_BLOCK, pctx)) {
5606                                 *block_nr = 0;
5607                                 return BLOCK_CHANGED;
5608                         }
5609                 } else if (is_blocks_used(ctx, blk, 1)) {
5610                         p->bbcheck = 1;
5611                         if (fix_problem(ctx, PR_1_BBINODE_BAD_METABLOCK,
5612                                         pctx)) {
5613                                 *block_nr = 0;
5614                                 return BLOCK_CHANGED;
5615                         }
5616                         if (e2fsck_should_abort(ctx))
5617                                 return BLOCK_ABORT;
5618                 } else {
5619                         mark_block_used(ctx, blk);
5620                 }
5621                 return 0;
5622         }
5623 #if 0
5624         printf ("DEBUG: Marking %u as bad.\n", blk);
5625 #endif
5626         ctx->fs_badblocks_count++;
5627         /*
5628          * If the block is not used, then mark it as used and return.
5629          * If it is already marked as found, this must mean that
5630          * there's an overlap between the filesystem table blocks
5631          * (bitmaps and inode table) and the bad block list.
5632          */
5633         if (!is_blocks_used(ctx, blk, 1)) {
5634                 ext2fs_mark_block_bitmap2(ctx->block_found_map, blk);
5635                 return 0;
5636         }
5637         /*
5638          * Try to find the where the filesystem block was used...
5639          */
5640         first_block = fs->super->s_first_data_block;
5641
5642         for (i = 0; i < fs->group_desc_count; i++ ) {
5643                 pctx->group = i;
5644                 pctx->blk = blk;
5645                 if (!ext2fs_bg_has_super(fs, i))
5646                         goto skip_super;
5647                 if (blk == first_block) {
5648                         if (i == 0) {
5649                                 if (fix_problem(ctx,
5650                                                 PR_1_BAD_PRIMARY_SUPERBLOCK,
5651                                                 pctx)) {
5652                                         *block_nr = 0;
5653                                         return BLOCK_CHANGED;
5654                                 }
5655                                 return 0;
5656                         }
5657                         fix_problem(ctx, PR_1_BAD_SUPERBLOCK, pctx);
5658                         return 0;
5659                 }
5660                 if ((blk > first_block) &&
5661                     (blk <= first_block + fs->desc_blocks)) {
5662                         if (i == 0) {
5663                                 pctx->blk = *block_nr;
5664                                 if (fix_problem(ctx,
5665                         PR_1_BAD_PRIMARY_GROUP_DESCRIPTOR, pctx)) {
5666                                         *block_nr = 0;
5667                                         return BLOCK_CHANGED;
5668                                 }
5669                                 return 0;
5670                         }
5671                         fix_problem(ctx, PR_1_BAD_GROUP_DESCRIPTORS, pctx);
5672                         return 0;
5673                 }
5674         skip_super:
5675                 if (blk == ext2fs_block_bitmap_loc(fs, i)) {
5676                         if (fix_problem(ctx, PR_1_BB_BAD_BLOCK, pctx)) {
5677                                 ctx->invalid_block_bitmap_flag[i]++;
5678                                 ctx->invalid_bitmaps++;
5679                         }
5680                         return 0;
5681                 }
5682                 if (blk == ext2fs_inode_bitmap_loc(fs, i)) {
5683                         if (fix_problem(ctx, PR_1_IB_BAD_BLOCK, pctx)) {
5684                                 ctx->invalid_inode_bitmap_flag[i]++;
5685                                 ctx->invalid_bitmaps++;
5686                         }
5687                         return 0;
5688                 }
5689                 if ((blk >= ext2fs_inode_table_loc(fs, i)) &&
5690                     (blk < (ext2fs_inode_table_loc(fs, i) +
5691                             fs->inode_blocks_per_group))) {
5692                         /*
5693                          * If there are bad blocks in the inode table,
5694                          * the inode scan code will try to do
5695                          * something reasonable automatically.
5696                          */
5697                         return 0;
5698                 }
5699                 first_block += fs->super->s_blocks_per_group;
5700         }
5701         /*
5702          * If we've gotten to this point, then the only
5703          * possibility is that the bad block inode meta data
5704          * is using a bad block.
5705          */
5706         if ((blk == p->inode->i_block[EXT2_IND_BLOCK]) ||
5707             (blk == p->inode->i_block[EXT2_DIND_BLOCK]) ||
5708             (blk == p->inode->i_block[EXT2_TIND_BLOCK])) {
5709                 p->bbcheck = 1;
5710                 if (fix_problem(ctx, PR_1_BBINODE_BAD_METABLOCK, pctx)) {
5711                         *block_nr = 0;
5712                         return BLOCK_CHANGED;
5713                 }
5714                 if (e2fsck_should_abort(ctx))
5715                         return BLOCK_ABORT;
5716                 return 0;
5717         }
5718
5719         pctx->group = -1;
5720
5721         /* Warn user that the block wasn't claimed */
5722         fix_problem(ctx, PR_1_PROGERR_CLAIMED_BLOCK, pctx);
5723
5724         return 0;
5725 }
5726
5727 static void new_table_block(e2fsck_t ctx, blk64_t first_block, dgrp_t group,
5728                             const char *name, int num, blk64_t *new_block)
5729 {
5730         ext2_filsys fs = ctx->fs;
5731         dgrp_t          last_grp;
5732         blk64_t         old_block = *new_block;
5733         blk64_t         last_block;
5734         dgrp_t          flexbg;
5735         unsigned        flexbg_size;
5736         int             i, is_flexbg;
5737         char            *buf;
5738         struct problem_context  pctx;
5739
5740         clear_problem_context(&pctx);
5741
5742         pctx.group = group;
5743         pctx.blk = old_block;
5744         pctx.str = name;
5745
5746         /*
5747          * For flex_bg filesystems, first try to allocate the metadata
5748          * within the flex_bg, and if that fails then try finding the
5749          * space anywhere in the filesystem.
5750          */
5751         is_flexbg = ext2fs_has_feature_flex_bg(fs->super);
5752         if (is_flexbg) {
5753                 flexbg_size = 1 << fs->super->s_log_groups_per_flex;
5754                 flexbg = group / flexbg_size;
5755                 first_block = ext2fs_group_first_block2(fs,
5756                                                         flexbg_size * flexbg);
5757                 last_grp = group | (flexbg_size - 1);
5758                 if (last_grp >= fs->group_desc_count)
5759                         last_grp = fs->group_desc_count - 1;
5760                 last_block = ext2fs_group_last_block2(fs, last_grp);
5761         } else
5762                 last_block = ext2fs_group_last_block2(fs, group);
5763         pctx.errcode = ext2fs_get_free_blocks2(fs, first_block, last_block,
5764                                                num, ctx->block_found_map,
5765                                                new_block);
5766         if (is_flexbg && (pctx.errcode == EXT2_ET_BLOCK_ALLOC_FAIL))
5767                 pctx.errcode = ext2fs_get_free_blocks2(fs,
5768                                 fs->super->s_first_data_block,
5769                                 ext2fs_blocks_count(fs->super),
5770                                 num, ctx->block_found_map, new_block);
5771         if (pctx.errcode) {
5772                 pctx.num = num;
5773                 fix_problem(ctx, PR_1_RELOC_BLOCK_ALLOCATE, &pctx);
5774                 ext2fs_unmark_valid(fs);
5775                 ctx->flags |= E2F_FLAG_ABORT;
5776                 return;
5777         }
5778         pctx.errcode = ext2fs_get_mem(fs->blocksize, &buf);
5779         if (pctx.errcode) {
5780                 fix_problem(ctx, PR_1_RELOC_MEMORY_ALLOCATE, &pctx);
5781                 ext2fs_unmark_valid(fs);
5782                 ctx->flags |= E2F_FLAG_ABORT;
5783                 return;
5784         }
5785         ext2fs_mark_super_dirty(fs);
5786         fs->flags &= ~EXT2_FLAG_MASTER_SB_ONLY;
5787         pctx.blk2 = *new_block;
5788         fix_problem(ctx, (old_block ? PR_1_RELOC_FROM_TO :
5789                           PR_1_RELOC_TO), &pctx);
5790         pctx.blk2 = 0;
5791         for (i = 0; i < num; i++) {
5792                 pctx.blk = i;
5793                 ext2fs_mark_block_bitmap2(ctx->block_found_map, (*new_block)+i);
5794                 if (old_block) {
5795                         pctx.errcode = io_channel_read_blk64(fs->io,
5796                                    old_block + i, 1, buf);
5797                         if (pctx.errcode)
5798                                 fix_problem(ctx, PR_1_RELOC_READ_ERR, &pctx);
5799                         pctx.blk = (*new_block) + i;
5800                         pctx.errcode = io_channel_write_blk64(fs->io, pctx.blk,
5801                                                               1, buf);
5802                 } else {
5803                         pctx.blk = (*new_block) + i;
5804                         pctx.errcode = ext2fs_zero_blocks2(fs, pctx.blk, 1,
5805                                                            NULL, NULL);
5806                 }
5807
5808                 if (pctx.errcode)
5809                         fix_problem(ctx, PR_1_RELOC_WRITE_ERR, &pctx);
5810         }
5811         ext2fs_free_mem(&buf);
5812 }
5813
5814 /*
5815  * This routine gets called at the end of pass 1 if bad blocks are
5816  * detected in the superblock, group descriptors, inode_bitmaps, or
5817  * block bitmaps.  At this point, all of the blocks have been mapped
5818  * out, so we can try to allocate new block(s) to replace the bad
5819  * blocks.
5820  */
5821 static void handle_fs_bad_blocks(e2fsck_t ctx)
5822 {
5823         ext2_filsys fs = ctx->fs;
5824         dgrp_t          i;
5825         blk64_t         first_block;
5826         blk64_t         new_blk;
5827
5828         for (i = 0; i < fs->group_desc_count; i++) {
5829                 first_block = ext2fs_group_first_block2(fs, i);
5830
5831                 if (ctx->invalid_block_bitmap_flag[i]) {
5832                         new_blk = ext2fs_block_bitmap_loc(fs, i);
5833                         new_table_block(ctx, first_block, i, _("block bitmap"),
5834                                         1, &new_blk);
5835                         ext2fs_block_bitmap_loc_set(fs, i, new_blk);
5836                 }
5837                 if (ctx->invalid_inode_bitmap_flag[i]) {
5838                         new_blk = ext2fs_inode_bitmap_loc(fs, i);
5839                         new_table_block(ctx, first_block, i, _("inode bitmap"),
5840                                         1, &new_blk);
5841                         ext2fs_inode_bitmap_loc_set(fs, i, new_blk);
5842                 }
5843                 if (ctx->invalid_inode_table_flag[i]) {
5844                         new_blk = ext2fs_inode_table_loc(fs, i);
5845                         new_table_block(ctx, first_block, i, _("inode table"),
5846                                         fs->inode_blocks_per_group,
5847                                         &new_blk);
5848                         ext2fs_inode_table_loc_set(fs, i, new_blk);
5849                         ctx->flags |= E2F_FLAG_RESTART;
5850                 }
5851         }
5852         ctx->invalid_bitmaps = 0;
5853 }
5854
5855 /*
5856  * This routine marks all blocks which are used by the superblock,
5857  * group descriptors, inode bitmaps, and block bitmaps.
5858  */
5859 static void mark_table_blocks(e2fsck_t ctx)
5860 {
5861         ext2_filsys fs = ctx->fs;
5862         blk64_t b;
5863         dgrp_t  i;
5864         unsigned int    j;
5865         struct problem_context pctx;
5866
5867         clear_problem_context(&pctx);
5868
5869         for (i = 0; i < fs->group_desc_count; i++) {
5870                 pctx.group = i;
5871
5872                 ext2fs_reserve_super_and_bgd(fs, i, ctx->block_found_map);
5873                 ext2fs_reserve_super_and_bgd(fs, i, ctx->block_metadata_map);
5874
5875                 /*
5876                  * Mark the blocks used for the inode table
5877                  */
5878                 if (ext2fs_inode_table_loc(fs, i)) {
5879                         for (j = 0, b = ext2fs_inode_table_loc(fs, i);
5880                              j < fs->inode_blocks_per_group;
5881                              j++, b++) {
5882                                 if (ext2fs_test_block_bitmap2(ctx->block_found_map,
5883                                                              b)) {
5884                                         pctx.blk = b;
5885                                         if (!ctx->invalid_inode_table_flag[i] &&
5886                                             fix_problem(ctx,
5887                                                 PR_1_ITABLE_CONFLICT, &pctx)) {
5888                                                 ctx->invalid_inode_table_flag[i]++;
5889                                                 ctx->invalid_bitmaps++;
5890                                         }
5891                                 } else {
5892                                     ext2fs_mark_block_bitmap2(
5893                                                 ctx->block_found_map, b);
5894                                     ext2fs_mark_block_bitmap2(
5895                                                 ctx->block_metadata_map, b);
5896                                 }
5897                         }
5898                 }
5899
5900                 /*
5901                  * Mark block used for the block bitmap
5902                  */
5903                 if (ext2fs_block_bitmap_loc(fs, i)) {
5904                         if (ext2fs_test_block_bitmap2(ctx->block_found_map,
5905                                      ext2fs_block_bitmap_loc(fs, i))) {
5906                                 pctx.blk = ext2fs_block_bitmap_loc(fs, i);
5907                                 if (fix_problem(ctx, PR_1_BB_CONFLICT, &pctx)) {
5908                                         ctx->invalid_block_bitmap_flag[i]++;
5909                                         ctx->invalid_bitmaps++;
5910                                 }
5911                         } else {
5912                             ext2fs_mark_block_bitmap2(ctx->block_found_map,
5913                                      ext2fs_block_bitmap_loc(fs, i));
5914                             ext2fs_mark_block_bitmap2(ctx->block_metadata_map,
5915                                      ext2fs_block_bitmap_loc(fs, i));
5916                         }
5917                 }
5918                 /*
5919                  * Mark block used for the inode bitmap
5920                  */
5921                 if (ext2fs_inode_bitmap_loc(fs, i)) {
5922                         if (ext2fs_test_block_bitmap2(ctx->block_found_map,
5923                                      ext2fs_inode_bitmap_loc(fs, i))) {
5924                                 pctx.blk = ext2fs_inode_bitmap_loc(fs, i);
5925                                 if (fix_problem(ctx, PR_1_IB_CONFLICT, &pctx)) {
5926                                         ctx->invalid_inode_bitmap_flag[i]++;
5927                                         ctx->invalid_bitmaps++;
5928                                 }
5929                         } else {
5930                             ext2fs_mark_block_bitmap2(ctx->block_metadata_map,
5931                                      ext2fs_inode_bitmap_loc(fs, i));
5932                             ext2fs_mark_block_bitmap2(ctx->block_found_map,
5933                                      ext2fs_inode_bitmap_loc(fs, i));
5934                         }
5935                 }
5936         }
5937 }
5938
5939 /*
5940  * These subroutines short circuits ext2fs_get_blocks and
5941  * ext2fs_check_directory; we use them since we already have the inode
5942  * structure, so there's no point in letting the ext2fs library read
5943  * the inode again.
5944  */
5945 static errcode_t pass1_get_blocks(ext2_filsys fs, ext2_ino_t ino,
5946                                   blk_t *blocks)
5947 {
5948         e2fsck_t ctx = (e2fsck_t) fs->priv_data;
5949         int     i;
5950
5951         if ((ino != ctx->stashed_ino) || !ctx->stashed_inode)
5952                 return EXT2_ET_CALLBACK_NOTHANDLED;
5953
5954         for (i=0; i < EXT2_N_BLOCKS; i++)
5955                 blocks[i] = ctx->stashed_inode->i_block[i];
5956         return 0;
5957 }
5958
5959 static errcode_t pass1_read_inode(ext2_filsys fs, ext2_ino_t ino,
5960                                   struct ext2_inode *inode)
5961 {
5962         e2fsck_t ctx = (e2fsck_t) fs->priv_data;
5963
5964         if ((ino != ctx->stashed_ino) || !ctx->stashed_inode)
5965                 return EXT2_ET_CALLBACK_NOTHANDLED;
5966         *inode = *ctx->stashed_inode;
5967         return 0;
5968 }
5969
5970 static errcode_t pass1_write_inode(ext2_filsys fs, ext2_ino_t ino,
5971                             struct ext2_inode *inode)
5972 {
5973         e2fsck_t ctx = (e2fsck_t) fs->priv_data;
5974
5975         if ((ino == ctx->stashed_ino) && ctx->stashed_inode &&
5976                 (inode != ctx->stashed_inode))
5977                 *ctx->stashed_inode = *inode;
5978         return EXT2_ET_CALLBACK_NOTHANDLED;
5979 }
5980
5981 static errcode_t pass1_check_directory(ext2_filsys fs, ext2_ino_t ino)
5982 {
5983         e2fsck_t ctx = (e2fsck_t) fs->priv_data;
5984
5985         if ((ino != ctx->stashed_ino) || !ctx->stashed_inode)
5986                 return EXT2_ET_CALLBACK_NOTHANDLED;
5987
5988         if (!LINUX_S_ISDIR(ctx->stashed_inode->i_mode))
5989                 return EXT2_ET_NO_DIRECTORY;
5990         return 0;
5991 }
5992
5993 static errcode_t e2fsck_get_alloc_block(ext2_filsys fs, blk64_t goal,
5994                                         blk64_t *ret)
5995 {
5996         e2fsck_t ctx = (e2fsck_t) fs->priv_data;
5997         errcode_t       retval;
5998         blk64_t         new_block;
5999
6000         if (ctx->block_found_map) {
6001                 retval = ext2fs_new_block2(fs, goal, ctx->block_found_map,
6002                                            &new_block);
6003                 if (retval)
6004                         return retval;
6005                 if (fs->block_map) {
6006                         ext2fs_mark_block_bitmap2(fs->block_map, new_block);
6007                         ext2fs_mark_bb_dirty(fs);
6008                 }
6009         } else {
6010                 if (!fs->block_map) {
6011                         retval = ext2fs_read_block_bitmap(fs);
6012                         if (retval)
6013                                 return retval;
6014                 }
6015
6016                 retval = ext2fs_new_block2(fs, goal, fs->block_map, &new_block);
6017                 if (retval)
6018                         return retval;
6019         }
6020
6021         *ret = new_block;
6022         return (0);
6023 }
6024
6025 static errcode_t e2fsck_new_range(ext2_filsys fs, int flags, blk64_t goal,
6026                                   blk64_t len, blk64_t *pblk, blk64_t *plen)
6027 {
6028         e2fsck_t ctx = (e2fsck_t) fs->priv_data;
6029         errcode_t       retval;
6030
6031         if (ctx->block_found_map)
6032                 return ext2fs_new_range(fs, flags, goal, len,
6033                                         ctx->block_found_map, pblk, plen);
6034
6035         if (!fs->block_map) {
6036                 retval = ext2fs_read_block_bitmap(fs);
6037                 if (retval)
6038                         return retval;
6039         }
6040
6041         return ext2fs_new_range(fs, flags, goal, len, fs->block_map,
6042                                 pblk, plen);
6043 }
6044
6045 static void e2fsck_block_alloc_stats(ext2_filsys fs, blk64_t blk, int inuse)
6046 {
6047         e2fsck_t ctx = (e2fsck_t) fs->priv_data;
6048
6049         /* Never free a critical metadata block */
6050         if (ctx->block_found_map &&
6051             ctx->block_metadata_map &&
6052             inuse < 0 &&
6053             ext2fs_test_block_bitmap2(ctx->block_metadata_map, blk))
6054                 return;
6055
6056         if (ctx->block_found_map) {
6057                 if (inuse > 0)
6058                         ext2fs_mark_block_bitmap2(ctx->block_found_map, blk);
6059                 else
6060                         ext2fs_unmark_block_bitmap2(ctx->block_found_map, blk);
6061         }
6062 }
6063
6064 static void e2fsck_block_alloc_stats_range(ext2_filsys fs, blk64_t blk,
6065                                            blk_t num, int inuse)
6066 {
6067         e2fsck_t ctx = (e2fsck_t) fs->priv_data;
6068
6069         /* Never free a critical metadata block */
6070         if (ctx->block_found_map &&
6071             ctx->block_metadata_map &&
6072             inuse < 0 &&
6073             ext2fs_test_block_bitmap_range2(ctx->block_metadata_map, blk, num))
6074                 return;
6075
6076         if (ctx->block_found_map) {
6077                 if (inuse > 0)
6078                         ext2fs_mark_block_bitmap_range2(ctx->block_found_map,
6079                                                         blk, num);
6080                 else
6081                         ext2fs_unmark_block_bitmap_range2(ctx->block_found_map,
6082                                                         blk, num);
6083         }
6084 }
6085
6086 void e2fsck_use_inode_shortcuts(e2fsck_t ctx, int use_shortcuts)
6087 {
6088         ext2_filsys fs = ctx->fs;
6089
6090         if (use_shortcuts) {
6091                 fs->get_blocks = pass1_get_blocks;
6092                 fs->check_directory = pass1_check_directory;
6093                 fs->read_inode = pass1_read_inode;
6094                 fs->write_inode = pass1_write_inode;
6095                 ctx->stashed_ino = 0;
6096         } else {
6097                 fs->get_blocks = 0;
6098                 fs->check_directory = 0;
6099                 fs->read_inode = 0;
6100                 fs->write_inode = 0;
6101         }
6102 }
6103
6104 void e2fsck_intercept_block_allocations(e2fsck_t ctx)
6105 {
6106         ext2fs_set_alloc_block_callback(ctx->fs, e2fsck_get_alloc_block, 0);
6107         ext2fs_set_block_alloc_stats_callback(ctx->fs,
6108                                                 e2fsck_block_alloc_stats, 0);
6109         ext2fs_set_new_range_callback(ctx->fs, e2fsck_new_range, NULL);
6110         ext2fs_set_block_alloc_stats_range_callback(ctx->fs,
6111                                         e2fsck_block_alloc_stats_range, NULL);
6112 }