Whamcloud - gitweb
LU-14953 e2fsck: pfsck progress report
[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         thread_context->expand_eisize_map = NULL;
2993         thread_context->inode_badness = NULL;
2994
2995         retval = e2fsck_allocate_block_bitmap(global_ctx->fs,
2996                                 _("in-use block map"), EXT2FS_BMAP64_RBTREE,
2997                                 "block_found_map", &thread_context->block_found_map);
2998         if (retval)
2999                 goto out_context;
3000
3001         thread_context->global_ctx = global_ctx;
3002         retval = ext2fs_get_mem(sizeof(struct struct_ext2_filsys), &thread_fs);
3003         if (retval) {
3004                 com_err(global_ctx->program_name, retval, "while allocating memory");
3005                 goto out_context;
3006         }
3007
3008         io_channel_flush_cleanup(global_fs->io);
3009         retval = e2fsck_pass1_copy_fs(thread_fs, global_ctx, global_fs);
3010         if (retval) {
3011                 com_err(global_ctx->program_name, retval, "while copying fs");
3012                 goto out_fs;
3013         }
3014         thread_fs->priv_data = thread_context;
3015
3016         thread_context->thread_info.et_thread_index = thread_index;
3017         set_up_logging(thread_context);
3018
3019         tinfo = &thread_context->thread_info;
3020         tinfo->et_group_start = average_group * thread_index;
3021         if (thread_index == global_fs->fs_num_threads - 1)
3022                 tinfo->et_group_end = thread_fs->group_desc_count;
3023         else
3024                 tinfo->et_group_end = average_group * (thread_index + 1);
3025         tinfo->et_group_next = tinfo->et_group_start;
3026         tinfo->et_inode_number = 0;
3027         tinfo->et_log_buf[0] = '\0';
3028         tinfo->et_log_length = 0;
3029         if (thread_context->options & E2F_OPT_MULTITHREAD)
3030                 log_out(thread_context, _("Scan group range [%d, %d)\n"),
3031                         tinfo->et_group_start, tinfo->et_group_end);
3032         thread_context->fs = thread_fs;
3033         retval = quota_init_context(&thread_context->qctx, thread_fs, 0);
3034         if (retval) {
3035                 com_err(global_ctx->program_name, retval,
3036                         "while init quota context");
3037                 goto out_fs;
3038         }
3039         *thread_ctx = thread_context;
3040         e2fsck_pass1_copy_invalid_bitmaps(global_ctx, thread_context);
3041         return 0;
3042 out_fs:
3043         ext2fs_free_mem(&thread_fs);
3044 out_context:
3045         if (thread_context->block_found_map)
3046                 ext2fs_free_mem(&thread_context->block_found_map);
3047         ext2fs_free_mem(&thread_context);
3048         return retval;
3049 }
3050
3051 static void e2fsck_pass1_merge_dir_info(e2fsck_t global_ctx, e2fsck_t thread_ctx)
3052 {
3053         if (thread_ctx->dir_info == NULL)
3054                 return;
3055
3056         if (global_ctx->dir_info == NULL) {
3057                 global_ctx->dir_info = thread_ctx->dir_info;
3058                 thread_ctx->dir_info = NULL;
3059                 return;
3060         }
3061
3062         e2fsck_merge_dir_info(global_ctx, thread_ctx->dir_info,
3063                               global_ctx->dir_info);
3064 }
3065
3066 static void e2fsck_pass1_merge_dx_dir(e2fsck_t global_ctx, e2fsck_t thread_ctx)
3067 {
3068         if (thread_ctx->dx_dir_info == NULL)
3069                 return;
3070
3071         if (global_ctx->dx_dir_info == NULL) {
3072                 global_ctx->dx_dir_info = thread_ctx->dx_dir_info;
3073                 global_ctx->dx_dir_info_size = thread_ctx->dx_dir_info_size;
3074                 global_ctx->dx_dir_info_count = thread_ctx->dx_dir_info_count;
3075                 thread_ctx->dx_dir_info = NULL;
3076                 return;
3077         }
3078
3079         e2fsck_merge_dx_dir(global_ctx, thread_ctx);
3080 }
3081
3082 static inline errcode_t
3083 e2fsck_pass1_merge_icount(ext2_icount_t *dest_icount,
3084                           ext2_icount_t *src_icount)
3085 {
3086         if (*src_icount) {
3087                 if (*dest_icount == NULL) {
3088                         *dest_icount = *src_icount;
3089                         *src_icount = NULL;
3090                 } else {
3091                         errcode_t ret;
3092
3093                         ret = ext2fs_icount_merge(*src_icount,
3094                                                   *dest_icount);
3095                         if (ret)
3096                                 return ret;
3097                 }
3098         }
3099
3100         return 0;
3101 }
3102
3103 static errcode_t e2fsck_pass1_merge_icounts(e2fsck_t global_ctx, e2fsck_t thread_ctx)
3104 {
3105         errcode_t ret;
3106
3107         ret = e2fsck_pass1_merge_icount(&global_ctx->inode_count,
3108                                         &thread_ctx->inode_count);
3109         if (ret)
3110                 return ret;
3111         ret = e2fsck_pass1_merge_icount(&global_ctx->inode_link_info,
3112                                         &thread_ctx->inode_link_info);
3113         if (ret)
3114                 return ret;
3115
3116         ret = e2fsck_pass1_merge_icount(&global_ctx->inode_badness,
3117                                         &thread_ctx->inode_badness);
3118
3119         return ret;
3120 }
3121
3122 static errcode_t e2fsck_pass1_merge_dirs_to_hash(e2fsck_t global_ctx,
3123                                                  e2fsck_t thread_ctx)
3124 {
3125         errcode_t retval = 0;
3126
3127         if (!thread_ctx->dirs_to_hash)
3128                 return 0;
3129
3130         if (!global_ctx->dirs_to_hash)
3131                 retval = ext2fs_badblocks_copy(thread_ctx->dirs_to_hash,
3132                                                &global_ctx->dirs_to_hash);
3133         else
3134                 retval = ext2fs_badblocks_merge(thread_ctx->dirs_to_hash,
3135                                                 global_ctx->dirs_to_hash);
3136
3137         return retval;
3138 }
3139
3140 static errcode_t e2fsck_pass1_merge_ea_inode_refs(e2fsck_t global_ctx,
3141                                                   e2fsck_t thread_ctx)
3142 {
3143         ea_value_t count;
3144         blk64_t blk;
3145         errcode_t retval;
3146
3147         if (!thread_ctx->ea_inode_refs)
3148                 return 0;
3149
3150         if (!global_ctx->ea_inode_refs) {
3151                 global_ctx->ea_inode_refs = thread_ctx->ea_inode_refs;
3152                 thread_ctx->ea_inode_refs = NULL;
3153                 return 0;
3154         }
3155
3156         ea_refcount_intr_begin(thread_ctx->ea_inode_refs);
3157         while (1) {
3158                 if ((blk = ea_refcount_intr_next(thread_ctx->ea_inode_refs,
3159                                                  &count)) == 0)
3160                         break;
3161                 if (!global_ctx->block_ea_map ||
3162                     !ext2fs_fast_test_block_bitmap2(global_ctx->block_ea_map,
3163                                                     blk)) {
3164                         retval = ea_refcount_store(global_ctx->ea_inode_refs,
3165                                                    blk, count);
3166                         if (retval)
3167                                 return retval;
3168                 }
3169         }
3170
3171         return retval;
3172 }
3173
3174 static ea_value_t ea_refcount_usage(e2fsck_t ctx, blk64_t blk,
3175                                     ea_value_t *orig)
3176 {
3177         ea_value_t count_cur;
3178         ea_value_t count_extra = 0;
3179         ea_value_t count_orig;
3180
3181         ea_refcount_fetch(ctx->refcount_orig, blk, &count_orig);
3182         ea_refcount_fetch(ctx->refcount, blk, &count_cur);
3183         /* most of time this is not needed */
3184         if (ctx->refcount_extra && count_cur == 0)
3185                 ea_refcount_fetch(ctx->refcount_extra, blk, &count_extra);
3186
3187         if (!count_orig)
3188                 count_orig = *orig;
3189         else if (orig)
3190                 *orig = count_orig;
3191
3192         return count_orig + count_extra - count_cur;
3193 }
3194
3195 static errcode_t e2fsck_pass1_merge_ea_refcount(e2fsck_t global_ctx,
3196                                                 e2fsck_t thread_ctx)
3197 {
3198         ea_value_t count;
3199         blk64_t blk;
3200         errcode_t retval = 0;
3201
3202         if (!thread_ctx->refcount)
3203                 return 0;
3204
3205         if (!global_ctx->refcount) {
3206                 global_ctx->refcount = thread_ctx->refcount;
3207                 thread_ctx->refcount = NULL;
3208                 global_ctx->refcount_extra = thread_ctx->refcount;
3209                 thread_ctx->refcount_extra = NULL;
3210                 return 0;
3211         }
3212
3213         ea_refcount_intr_begin(thread_ctx->refcount);
3214         while (1) {
3215                 if ((blk = ea_refcount_intr_next(thread_ctx->refcount,
3216                                                  &count)) == 0)
3217                         break;
3218                 /**
3219                  * this EA has never seen before, so just store its
3220                  * refcount and refcount_extra into global_ctx if needed.
3221                  */
3222                 if (!global_ctx->block_ea_map ||
3223                     !ext2fs_fast_test_block_bitmap2(global_ctx->block_ea_map,
3224                                                     blk)) {
3225                         ea_value_t extra;
3226
3227                         retval = ea_refcount_store(global_ctx->refcount,
3228                                                    blk, count);
3229                         if (retval)
3230                                 return retval;
3231
3232                         if (count > 0 || !thread_ctx->refcount_extra)
3233                                 continue;
3234                         ea_refcount_fetch(thread_ctx->refcount_extra, blk,
3235                                           &extra);
3236                         if (extra == 0)
3237                                 continue;
3238
3239                         if (!global_ctx->refcount_extra) {
3240                                 retval = ea_refcount_create(0,
3241                                                 &global_ctx->refcount_extra);
3242                                 if (retval)
3243                                         return retval;
3244                         }
3245                         retval = ea_refcount_store(global_ctx->refcount_extra,
3246                                                    blk, extra);
3247                         if (retval)
3248                                 return retval;
3249                 } else {
3250                         ea_value_t orig;
3251                         ea_value_t thread_usage;
3252                         ea_value_t global_usage;
3253                         ea_value_t new;
3254
3255                         thread_usage = ea_refcount_usage(thread_ctx,
3256                                                          blk, &orig);
3257                         global_usage = ea_refcount_usage(global_ctx,
3258                                                          blk, &orig);
3259                         if (thread_usage + global_usage <= orig) {
3260                                 new = orig - thread_usage - global_usage;
3261                                 retval = ea_refcount_store(global_ctx->refcount,
3262                                                            blk, new);
3263                                 if (retval)
3264                                         return retval;
3265                                 continue;
3266                         }
3267                         /* update it is as zero */
3268                         retval = ea_refcount_store(global_ctx->refcount,
3269                                                    blk, 0);
3270                         if (retval)
3271                                 return retval;
3272                         /* Ooops, this EA was referenced more than it stated */
3273                         if (!global_ctx->refcount_extra) {
3274                                 retval = ea_refcount_create(0,
3275                                                 &global_ctx->refcount_extra);
3276                                 if (retval)
3277                                         return retval;
3278                         }
3279                         new = global_usage + thread_usage - orig;
3280                         retval = ea_refcount_store(global_ctx->refcount_extra,
3281                                                    blk, new);
3282                         if (retval)
3283                                 return retval;
3284                 }
3285         }
3286
3287         return retval;
3288 }
3289
3290 static errcode_t e2fsck_pass1_merge_casefolded_dirs(e2fsck_t global_ctx,
3291                                                    e2fsck_t thread_ctx)
3292 {
3293         errcode_t retval = 0;
3294
3295         if (!thread_ctx->casefolded_dirs)
3296                 return 0;
3297
3298         if (!global_ctx->casefolded_dirs)
3299                 retval = ext2fs_badblocks_copy(thread_ctx->casefolded_dirs,
3300                                                &global_ctx->casefolded_dirs);
3301         else
3302                 retval = ext2fs_badblocks_merge(thread_ctx->casefolded_dirs,
3303                                                 global_ctx->casefolded_dirs);
3304
3305         return retval;
3306 }
3307
3308 static errcode_t e2fsck_pass1_merge_context(e2fsck_t global_ctx,
3309                                             e2fsck_t thread_ctx)
3310 {
3311         ext2_filsys global_fs = global_ctx->fs;
3312         errcode_t retval;
3313         int i;
3314
3315         global_ctx->fs_directory_count += thread_ctx->fs_directory_count;
3316         global_ctx->fs_regular_count += thread_ctx->fs_regular_count;
3317         global_ctx->fs_blockdev_count += thread_ctx->fs_blockdev_count;
3318         global_ctx->fs_chardev_count += thread_ctx->fs_chardev_count;
3319         global_ctx->fs_links_count += thread_ctx->fs_links_count;
3320         global_ctx->fs_symlinks_count += thread_ctx->fs_symlinks_count;
3321         global_ctx->fs_fast_symlinks_count += thread_ctx->fs_fast_symlinks_count;
3322         global_ctx->fs_fifo_count += thread_ctx->fs_fifo_count;
3323         global_ctx->fs_total_count += thread_ctx->fs_total_count;
3324         global_ctx->fs_badblocks_count += thread_ctx->fs_badblocks_count;
3325         global_ctx->fs_sockets_count += thread_ctx->fs_sockets_count;
3326         global_ctx->fs_ind_count += thread_ctx->fs_ind_count;
3327         global_ctx->fs_dind_count += thread_ctx->fs_dind_count;
3328         global_ctx->fs_tind_count += thread_ctx->fs_tind_count;
3329         global_ctx->fs_fragmented += thread_ctx->fs_fragmented;
3330         global_ctx->fs_fragmented_dir += thread_ctx->fs_fragmented_dir;
3331         global_ctx->large_files += thread_ctx->large_files;
3332         /* threads might enable E2F_OPT_YES */
3333         global_ctx->options |= thread_ctx->options;
3334         global_ctx->flags |= thread_ctx->flags;
3335         /*
3336          * The l+f inode may have been cleared, so zap it now and
3337          * later passes will recalculate it if necessary
3338          */
3339         global_ctx->lost_and_found = 0;
3340         /* merge extent depth count */
3341         for (i = 0; i < MAX_EXTENT_DEPTH_COUNT; i++)
3342                 global_ctx->extent_depth_count[i] +=
3343                         thread_ctx->extent_depth_count[i];
3344
3345         e2fsck_pass1_merge_dir_info(global_ctx, thread_ctx);
3346         e2fsck_pass1_merge_dx_dir(global_ctx, thread_ctx);
3347
3348         retval = e2fsck_pass1_merge_fs(global_ctx->fs, thread_ctx->fs);
3349         if (retval) {
3350                 com_err(global_ctx->program_name, 0, _("while merging fs\n"));
3351                 return retval;
3352         }
3353         retval = e2fsck_pass1_merge_icounts(global_ctx, thread_ctx);
3354         if (retval) {
3355                 com_err(global_ctx->program_name, 0,
3356                         _("while merging icounts\n"));
3357                 return retval;
3358         }
3359
3360         retval = e2fsck_pass1_merge_dirs_to_hash(global_ctx, thread_ctx);
3361         if (retval) {
3362                 com_err(global_ctx->program_name, 0,
3363                         _("while merging dirs to hash\n"));
3364                 return retval;
3365         }
3366
3367         e2fsck_pass1_merge_ea_inode_refs(global_ctx, thread_ctx);
3368         e2fsck_pass1_merge_ea_refcount(global_ctx, thread_ctx);
3369         retval = quota_merge_and_update_usage(global_ctx->qctx,
3370                                               thread_ctx->qctx);
3371         if (retval)
3372                 return retval;
3373
3374         retval = e2fsck_pass1_merge_casefolded_dirs(global_ctx, thread_ctx);
3375         if (retval) {
3376                 com_err(global_ctx->program_name, 0,
3377                         _("while merging casefolded dirs\n"));
3378                 return retval;
3379         }
3380
3381         e2fsck_pass1_merge_invalid_bitmaps(global_ctx, thread_ctx);
3382
3383         if (thread_ctx->min_extra_isize < global_ctx->min_extra_isize)
3384                 global_ctx->min_extra_isize = thread_ctx->min_extra_isize;
3385
3386         retval = e2fsck_pass1_merge_bitmap(global_fs,
3387                                 &thread_ctx->inode_used_map,
3388                                 &global_ctx->inode_used_map);
3389         if (retval)
3390                 return retval;
3391
3392         retval = e2fsck_pass1_merge_bitmap(global_fs,
3393                                         &thread_ctx->inode_dir_map,
3394                                         &global_ctx->inode_dir_map);
3395         if (retval)
3396                 return retval;
3397         retval = e2fsck_pass1_merge_bitmap(global_fs,
3398                                 &thread_ctx->inode_bb_map,
3399                                 &global_ctx->inode_bb_map);
3400         if (retval)
3401                 return retval;
3402         retval = e2fsck_pass1_merge_bitmap(global_fs,
3403                                 &thread_ctx->inode_imagic_map,
3404                                 &global_ctx->inode_imagic_map);
3405         if (retval)
3406                 return retval;
3407         retval = e2fsck_pass1_merge_bitmap(global_fs,
3408                                 &thread_ctx->inode_reg_map,
3409                                 &global_ctx->inode_reg_map);
3410         if (retval)
3411                 return retval;
3412         retval = e2fsck_pass1_merge_bitmap(global_fs,
3413                                 &thread_ctx->inodes_to_rebuild,
3414                                 &global_ctx->inodes_to_rebuild);
3415         if (retval)
3416                 return retval;
3417         retval = e2fsck_pass1_merge_bitmap(global_fs,
3418                                 &thread_ctx->block_ea_map,
3419                                 &global_ctx->block_ea_map);
3420         if (retval)
3421                 return retval;
3422
3423         retval = e2fsck_pass1_merge_bitmap(global_fs,
3424                                 &thread_ctx->expand_eisize_map,
3425                                 &global_ctx->expand_eisize_map);
3426         if (retval)
3427                 return retval;
3428
3429         if (ext2fs_has_feature_shared_blocks(global_fs->super) &&
3430             !(global_ctx->options & E2F_OPT_UNSHARE_BLOCKS))
3431                 return 0;
3432         /*
3433          * This need be done after merging block_ea_map
3434          * because ea block might be shared, we need exclude
3435          * them from dup blocks.
3436          */
3437         e2fsck_pass1_block_map_w_lock(thread_ctx);
3438         retval = ext2fs_merge_bitmap(thread_ctx->block_found_map,
3439                                      global_ctx->block_found_map,
3440                                      global_ctx->block_dup_map,
3441                                      global_ctx->block_ea_map);
3442         e2fsck_pass1_block_map_w_unlock(thread_ctx);
3443         if (retval == EEXIST)
3444                 global_ctx->flags |= E2F_FLAG_DUP_BLOCK;
3445
3446         return 0;
3447 }
3448
3449 static int e2fsck_pass1_thread_join(e2fsck_t global_ctx, e2fsck_t thread_ctx)
3450 {
3451         errcode_t       retval;
3452
3453         retval = e2fsck_pass1_merge_context(global_ctx, thread_ctx);
3454         ext2fs_free_mem(&thread_ctx->fs);
3455         if (thread_ctx->logf)
3456                 fclose(thread_ctx->logf);
3457         if (thread_ctx->problem_logf) {
3458                 fputs("</problem_log>\n", thread_ctx->problem_logf);
3459                 fclose(thread_ctx->problem_logf);
3460         }
3461
3462         quota_release_context(&thread_ctx->qctx);
3463         /*
3464          * @block_metadata_map and @block_dup_map are
3465          * shared, so we don't free them.
3466          */
3467         thread_ctx->block_metadata_map = NULL;
3468         thread_ctx->block_dup_map = NULL;
3469         e2fsck_reset_context(thread_ctx);
3470         ext2fs_free_mem(&thread_ctx);
3471
3472         return retval;
3473 }
3474
3475 static int e2fsck_pass1_threads_join(e2fsck_t global_ctx)
3476 {
3477         errcode_t rc;
3478         errcode_t ret = 0;
3479         struct e2fsck_thread_info *infos = global_ctx->infos;
3480         struct e2fsck_thread_info *pinfo;
3481         int num_threads = global_ctx->pfs_num_threads;
3482         int i;
3483
3484         /* merge invalid bitmaps will recalculate it */
3485         global_ctx->invalid_bitmaps = 0;
3486         for (i = 0; i < num_threads; i++) {
3487                 pinfo = &infos[i];
3488
3489                 if (!pinfo->eti_started)
3490                         continue;
3491
3492                 rc = pthread_join(pinfo->eti_thread_id, NULL);
3493                 if (rc) {
3494                         com_err(global_ctx->program_name, rc,
3495                                 _("while joining thread\n"));
3496                         if (ret == 0)
3497                                 ret = rc;
3498                 }
3499                 rc = e2fsck_pass1_thread_join(global_ctx, infos[i].eti_thread_ctx);
3500                 if (rc) {
3501                         com_err(global_ctx->program_name, rc,
3502                                 _("while joining pass1 thread\n"));
3503                         if (ret == 0)
3504                                 ret = rc;
3505                 }
3506         }
3507         free(infos);
3508         global_ctx->infos = NULL;
3509
3510         return ret;
3511 }
3512
3513 static void *e2fsck_pass1_thread(void *arg)
3514 {
3515         struct e2fsck_thread_info       *info = arg;
3516         e2fsck_t                         thread_ctx = info->eti_thread_ctx;
3517 #ifdef DEBUG_THREADS
3518         struct e2fsck_thread_debug      *thread_debug = info->eti_debug;
3519 #endif
3520
3521 #ifdef DEBUG_THREADS
3522         pthread_mutex_lock(&thread_debug->etd_mutex);
3523         while (info->eti_thread_index > thread_debug->etd_finished_threads) {
3524                 pthread_cond_wait(&thread_debug->etd_cond,
3525                                   &thread_debug->etd_mutex);
3526         }
3527         pthread_mutex_unlock(&thread_debug->etd_mutex);
3528 #endif
3529
3530 #ifdef HAVE_SETJMP_H
3531         /*
3532          * When fatal_error() happens, jump to here. The thread
3533          * context's flags will be saved, but its abort_loc will
3534          * be overwritten by original jump buffer for the later
3535          * tests.
3536          */
3537         if (setjmp(thread_ctx->abort_loc)) {
3538                 thread_ctx->flags &= ~E2F_FLAG_SETJMP_OK;
3539                 goto out;
3540         }
3541         thread_ctx->flags |= E2F_FLAG_SETJMP_OK;
3542 #endif
3543
3544         e2fsck_pass1_run(thread_ctx);
3545
3546 out:
3547         if (thread_ctx->options & E2F_OPT_MULTITHREAD)
3548                 log_out(thread_ctx,
3549                         _("Scanned group range [%u, %u), inodes %u\n"),
3550                         thread_ctx->thread_info.et_group_start,
3551                         thread_ctx->thread_info.et_group_end,
3552                         thread_ctx->thread_info.et_inode_number);
3553
3554 #ifdef DEBUG_THREADS
3555         pthread_mutex_lock(&thread_debug->etd_mutex);
3556         thread_debug->etd_finished_threads++;
3557         pthread_cond_broadcast(&thread_debug->etd_cond);
3558         pthread_mutex_unlock(&thread_debug->etd_mutex);
3559 #endif
3560
3561         return NULL;
3562 }
3563
3564 static dgrp_t ext2fs_get_avg_group(ext2_filsys fs)
3565 {
3566 #ifdef HAVE_PTHREAD
3567         dgrp_t average_group;
3568         unsigned flexbg_size;
3569
3570         if (fs->fs_num_threads <= 1)
3571                 return fs->group_desc_count;
3572
3573         average_group = fs->group_desc_count / fs->fs_num_threads;
3574         if (average_group <= 1)
3575                 return 1;
3576
3577         if (ext2fs_has_feature_flex_bg(fs->super)) {
3578                 int times = 1;
3579
3580                 flexbg_size = 1 << fs->super->s_log_groups_per_flex;
3581                 if (average_group % flexbg_size) {
3582                         times = average_group / flexbg_size;
3583                         average_group = times * flexbg_size;
3584                 }
3585         }
3586
3587         return average_group;
3588 #else
3589         return fs->group_desc_count;
3590 #endif
3591 }
3592
3593 static int e2fsck_pass1_threads_start(e2fsck_t global_ctx)
3594 {
3595         struct e2fsck_thread_info       *infos;
3596         pthread_attr_t                   attr;
3597         errcode_t                        retval;
3598         errcode_t                        ret;
3599         struct e2fsck_thread_info       *tmp_pinfo;
3600         int                              i;
3601         e2fsck_t                         thread_ctx;
3602         dgrp_t                           average_group;
3603         int num_threads = global_ctx->pfs_num_threads;
3604 #ifdef DEBUG_THREADS
3605         struct e2fsck_thread_debug       thread_debug =
3606                 {PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER, 0};
3607
3608         thread_debug.etd_finished_threads = 0;
3609 #endif
3610
3611         retval = pthread_attr_init(&attr);
3612         if (retval) {
3613                 com_err(global_ctx->program_name, retval,
3614                         _("while setting pthread attribute\n"));
3615                 return retval;
3616         }
3617
3618         infos = calloc(num_threads, sizeof(struct e2fsck_thread_info));
3619         if (infos == NULL) {
3620                 retval = -ENOMEM;
3621                 com_err(global_ctx->program_name, retval,
3622                         _("while allocating memory for threads\n"));
3623                 pthread_attr_destroy(&attr);
3624                 return retval;
3625         }
3626         global_ctx->infos = infos;
3627
3628         average_group = ext2fs_get_avg_group(global_ctx->fs);
3629         for (i = 0; i < num_threads; i++) {
3630                 tmp_pinfo = &infos[i];
3631                 tmp_pinfo->eti_thread_index = i;
3632 #ifdef DEBUG_THREADS
3633                 tmp_pinfo->eti_debug = &thread_debug;
3634 #endif
3635                 retval = e2fsck_pass1_thread_prepare(global_ctx, &thread_ctx,
3636                                                      i, num_threads,
3637                                                      average_group);
3638                 if (retval) {
3639                         com_err(global_ctx->program_name, retval,
3640                                 _("while preparing pass1 thread\n"));
3641                         break;
3642                 }
3643                 tmp_pinfo->eti_thread_ctx = thread_ctx;
3644
3645                 retval = pthread_create(&tmp_pinfo->eti_thread_id, &attr,
3646                                         &e2fsck_pass1_thread, tmp_pinfo);
3647                 if (retval) {
3648                         com_err(global_ctx->program_name, retval,
3649                                 _("while creating thread\n"));
3650                         e2fsck_pass1_thread_join(global_ctx, thread_ctx);
3651                         break;
3652                 }
3653
3654                 tmp_pinfo->eti_started = 1;
3655         }
3656
3657         /* destroy the thread attribute object, since it is no longer needed */
3658         ret = pthread_attr_destroy(&attr);
3659         if (ret) {
3660                 com_err(global_ctx->program_name, ret,
3661                         _("while destroying thread attribute\n"));
3662                 if (retval == 0)
3663                         retval = ret;
3664         }
3665
3666         if (retval) {
3667                 e2fsck_pass1_threads_join(global_ctx);
3668                 return retval;
3669         }
3670         return 0;
3671 }
3672
3673 static void e2fsck_pass1_multithread(e2fsck_t global_ctx)
3674 {
3675         errcode_t retval;
3676
3677         retval = e2fsck_pass1_threads_start(global_ctx);
3678         if (retval) {
3679                 com_err(global_ctx->program_name, retval,
3680                         _("while starting pass1 threads\n"));
3681                 goto out_abort;
3682         }
3683
3684         retval = e2fsck_pass1_threads_join(global_ctx);
3685         if (retval) {
3686                 com_err(global_ctx->program_name, retval,
3687                         _("while joining pass1 threads\n"));
3688                 goto out_abort;
3689         }
3690         return;
3691 out_abort:
3692         global_ctx->flags |= E2F_FLAG_ABORT;
3693         return;
3694 }
3695 #endif
3696
3697 void e2fsck_pass1(e2fsck_t ctx)
3698 {
3699         errcode_t retval;
3700         int need_single = 1;
3701
3702         retval = e2fsck_pass1_prepare(ctx);
3703         if (retval)
3704                 return;
3705 #ifdef HAVE_PTHREAD
3706         if (ctx->pfs_num_threads > 1 || ctx->options & E2F_OPT_MULTITHREAD) {
3707                 need_single = 0;
3708                 e2fsck_pass1_multithread(ctx);
3709         }
3710         /* No lock is needed at this time */
3711         ctx->fs_need_locking = 0;
3712 #endif
3713         if (need_single)
3714                 e2fsck_pass1_run(ctx);
3715         e2fsck_pass1_post(ctx);
3716 }
3717
3718 #undef FINISH_INODE_LOOP
3719
3720 /*
3721  * When the inode_scan routines call this callback at the end of the
3722  * glock group, call process_inodes.
3723  */
3724 static errcode_t scan_callback(ext2_filsys fs,
3725                                ext2_inode_scan scan EXT2FS_ATTR((unused)),
3726                                dgrp_t group, void * priv_data)
3727 {
3728         struct scan_callback_struct *scan_struct;
3729         e2fsck_t ctx;
3730         dgrp_t cur = group + 1;
3731         struct e2fsck_thread *tinfo;
3732         struct e2fsck_thread_info *pinfo, *infos;
3733         int i;
3734
3735         scan_struct = (struct scan_callback_struct *) priv_data;
3736         ctx = scan_struct->ctx;
3737
3738         process_inodes((e2fsck_t) fs->priv_data, scan_struct->block_buf,
3739                        scan_struct->inodes_to_process,
3740                        scan_struct->process_inode_count);
3741
3742 #ifdef HAVE_PTHREAD
3743         if (ctx->global_ctx) {
3744                 cur = 0;
3745                 infos = ctx->global_ctx->infos;
3746                 for (i = 0; i < ctx->global_ctx->pfs_num_threads; i++) {
3747                         pinfo = &infos[i];
3748
3749                         if (!pinfo->eti_started)
3750                                 continue;
3751
3752                         tinfo = &pinfo->eti_thread_ctx->thread_info;
3753                         if (ctx == pinfo->eti_thread_ctx)
3754                                 cur += group + 1 - tinfo->et_group_start;
3755                         else
3756                                 cur += tinfo->et_group_next -
3757                                         tinfo->et_group_start;
3758                 }
3759         }
3760 #endif
3761
3762         if (ctx->progress)
3763                 if ((ctx->progress)(ctx, 1, cur,
3764                                     ctx->fs->group_desc_count))
3765                         return EXT2_ET_CANCEL_REQUESTED;
3766
3767 #ifdef HAVE_PTHREAD
3768         if (ctx->global_ctx) {
3769                 tinfo = &ctx->thread_info;
3770                 tinfo->et_group_next++;
3771                 if (ctx->options & E2F_OPT_DEBUG &&
3772                     ctx->options & E2F_OPT_MULTITHREAD)
3773                         log_out(ctx, _("group %d finished\n"),
3774                                 tinfo->et_group_next);
3775                 if (tinfo->et_group_next >= tinfo->et_group_end)
3776                         return EXT2_ET_SCAN_FINISHED;
3777         }
3778 #endif
3779
3780         return 0;
3781 }
3782
3783 /*
3784  * Process the inodes in the "inodes to process" list.
3785  */
3786 static void process_inodes(e2fsck_t ctx, char *block_buf,
3787                            struct process_inode_block *inodes_to_process,
3788                            int *process_inode_count)
3789 {
3790         int                     i;
3791         struct ext2_inode       *old_stashed_inode;
3792         ext2_ino_t              old_stashed_ino;
3793         const char              *old_operation;
3794         char                    buf[80];
3795         struct problem_context  pctx;
3796
3797 #if 0
3798         printf("begin process_inodes: ");
3799 #endif
3800         if (*process_inode_count == 0)
3801                 return;
3802         old_operation = ehandler_operation(0);
3803         old_stashed_inode = ctx->stashed_inode;
3804         old_stashed_ino = ctx->stashed_ino;
3805         qsort(inodes_to_process, *process_inode_count,
3806                       sizeof(struct process_inode_block), process_inode_cmp);
3807         clear_problem_context(&pctx);
3808         for (i=0; i < *process_inode_count; i++) {
3809                 pctx.inode = ctx->stashed_inode =
3810                         (struct ext2_inode *) &inodes_to_process[i].inode;
3811                 pctx.ino = ctx->stashed_ino = inodes_to_process[i].ino;
3812
3813 #if 0
3814                 printf("%u ", pctx.ino);
3815 #endif
3816                 sprintf(buf, _("reading indirect blocks of inode %u"),
3817                         pctx.ino);
3818                 ehandler_operation(buf);
3819                 check_blocks(ctx, &pctx, block_buf,
3820                              &inodes_to_process[i].ea_ibody_quota);
3821                 if (e2fsck_should_abort(ctx))
3822                         break;
3823         }
3824         ctx->stashed_inode = old_stashed_inode;
3825         ctx->stashed_ino = old_stashed_ino;
3826         *process_inode_count = 0;
3827 #if 0
3828         printf("end process inodes\n");
3829 #endif
3830         ehandler_operation(old_operation);
3831 }
3832
3833 static EXT2_QSORT_TYPE process_inode_cmp(const void *a, const void *b)
3834 {
3835         const struct process_inode_block *ib_a =
3836                 (const struct process_inode_block *) a;
3837         const struct process_inode_block *ib_b =
3838                 (const struct process_inode_block *) b;
3839         int     ret;
3840
3841         ret = (ib_a->inode.i_block[EXT2_IND_BLOCK] -
3842                ib_b->inode.i_block[EXT2_IND_BLOCK]);
3843         if (ret == 0)
3844                 /*
3845                  * We only call process_inodes() for non-extent
3846                  * inodes, so it's OK to pass NULL to
3847                  * ext2fs_file_acl_block() here.
3848                  */
3849                 ret = ext2fs_file_acl_block(0, ext2fs_const_inode(&ib_a->inode)) -
3850                         ext2fs_file_acl_block(0, ext2fs_const_inode(&ib_b->inode));
3851         if (ret == 0)
3852                 ret = ib_a->ino - ib_b->ino;
3853         return ret;
3854 }
3855
3856 /*
3857  * Mark an inode as being bad and increment its badness counter.
3858  */
3859 void e2fsck_mark_inode_bad_loc(e2fsck_t ctx, struct problem_context *pctx,
3860                                __u32 code, int badness, const char *func,
3861                                const int line)
3862 {
3863         __u16 badness_before, badness_after;
3864         __u64 pctx_num_sav = pctx->num;
3865
3866         if (!ctx->inode_badness_threshold)      /* badness is disabled */
3867                 return;
3868
3869         if (!ctx->inode_badness) {
3870                 errcode_t retval;
3871
3872                 retval = ext2fs_create_icount2(ctx->fs, 0, 0, NULL,
3873                                                &ctx->inode_badness);
3874                 if (retval) {
3875                         pctx->errcode = retval;
3876                         fix_problem(ctx, PR_1_ALLOCATE_ICOUNT, pctx);
3877                         ctx->flags |= E2F_FLAG_ABORT;
3878                         return;
3879                 }
3880         }
3881         ext2fs_icount_fetch(ctx->inode_badness, pctx->ino, &badness_before);
3882         if (badness + badness_before > BADNESS_MAX)
3883                 badness_after = BADNESS_MAX;
3884         else if (badness < 0 && badness_before < -badness)
3885                 badness_after = 0;
3886         else
3887                 badness_after = badness_before + badness;
3888         ext2fs_icount_store(ctx->inode_badness, pctx->ino, badness_after);
3889
3890         if (ctx->options & E2F_OPT_DEBUG)
3891                 log_out(ctx,
3892                         "%s:%d: increase inode %lu badness %u to %u for %x\n",
3893                         func, line, (unsigned long)pctx->ino, badness_before,
3894                         badness_after, code);
3895 }
3896
3897 static void add_casefolded_dir(e2fsck_t ctx, ino_t ino)
3898 {
3899         struct          problem_context pctx;
3900
3901         if (!ctx->casefolded_dirs) {
3902                 pctx.errcode = ext2fs_u32_list_create(&ctx->casefolded_dirs, 0);
3903                 if (pctx.errcode)
3904                         goto error;
3905         }
3906         pctx.errcode = ext2fs_u32_list_add(ctx->casefolded_dirs, ino);
3907         if (pctx.errcode == 0)
3908                 return;
3909 error:
3910         fix_problem(ctx, PR_1_ALLOCATE_CASEFOLDED_DIRLIST, &pctx);
3911         /* Should never get here */
3912         ctx->flags |= E2F_FLAG_ABORT;
3913 }
3914
3915 /*
3916  * This procedure will allocate the inode "bb" (badblock) map table
3917  */
3918 static void alloc_bb_map(e2fsck_t ctx)
3919 {
3920         struct          problem_context pctx;
3921
3922         clear_problem_context(&pctx);
3923         pctx.errcode = e2fsck_allocate_inode_bitmap(ctx->fs,
3924                         _("inode in bad block map"), EXT2FS_BMAP64_RBTREE,
3925                         "inode_bb_map", &ctx->inode_bb_map);
3926         if (pctx.errcode) {
3927                 pctx.num = 4;
3928                 fix_problem(ctx, PR_1_ALLOCATE_IBITMAP_ERROR, &pctx);
3929                 /* Should never get here */
3930                 ctx->flags |= E2F_FLAG_ABORT;
3931                 return;
3932         }
3933 }
3934
3935 /*
3936  * This procedure will allocate the inode imagic table
3937  */
3938 static void alloc_imagic_map(e2fsck_t ctx)
3939 {
3940         struct          problem_context pctx;
3941
3942         clear_problem_context(&pctx);
3943         pctx.errcode = e2fsck_allocate_inode_bitmap(ctx->fs,
3944                         _("imagic inode map"), EXT2FS_BMAP64_RBTREE,
3945                         "inode_imagic_map", &ctx->inode_imagic_map);
3946         if (pctx.errcode) {
3947                 pctx.num = 5;
3948                 fix_problem(ctx, PR_1_ALLOCATE_IBITMAP_ERROR, &pctx);
3949                 /* Should never get here */
3950                 ctx->flags |= E2F_FLAG_ABORT;
3951                 return;
3952         }
3953 }
3954
3955 /*
3956  * Marks a block as in use, setting the dup_map if it's been set
3957  * already.  Called by process_block and process_bad_block.
3958  *
3959  * WARNING: Assumes checks have already been done to make sure block
3960  * is valid.  This is true in both process_block and process_bad_block.
3961  */
3962 static _INLINE_ void mark_block_used(e2fsck_t ctx, blk64_t block)
3963 {
3964         struct problem_context pctx;
3965         e2fsck_t global_ctx = ctx->global_ctx ? ctx->global_ctx : ctx;
3966
3967         clear_problem_context(&pctx);
3968
3969         if (is_blocks_used(ctx, block, 1)) {
3970                 if (ext2fs_has_feature_shared_blocks(ctx->fs->super) &&
3971                     !(ctx->options & E2F_OPT_UNSHARE_BLOCKS)) {
3972                         return;
3973                 }
3974                 ctx->flags |= E2F_FLAG_DUP_BLOCK;
3975                 e2fsck_pass1_block_map_w_lock(ctx);
3976                 ext2fs_fast_mark_block_bitmap2(global_ctx->block_dup_map, block);
3977                 e2fsck_pass1_block_map_w_unlock(ctx);
3978         } else {
3979                 ext2fs_fast_mark_block_bitmap2(ctx->block_found_map, block);
3980         }
3981 }
3982
3983 /*
3984  * When cluster size is greater than one block, it is caller's responsibility
3985  * to make sure block parameter starts at a cluster boundary.
3986  */
3987 static _INLINE_ void mark_blocks_used(e2fsck_t ctx, blk64_t block,
3988                                       unsigned int num)
3989 {
3990         if (!is_blocks_used(ctx, block, num)) {
3991                 ext2fs_mark_block_bitmap_range2(ctx->block_found_map, block, num);
3992         } else {
3993                 unsigned int i;
3994
3995                 for (i = 0; i < num; i += EXT2FS_CLUSTER_RATIO(ctx->fs))
3996                         mark_block_used(ctx, block + i);
3997         }
3998 }
3999
4000 static errcode_t _INLINE_ e2fsck_write_ext_attr3(e2fsck_t ctx, blk64_t block,
4001                                                  void *inbuf, ext2_ino_t inum)
4002 {
4003         errcode_t retval;
4004         ext2_filsys fs = ctx->fs;
4005
4006         e2fsck_pass1_fix_lock(ctx);
4007         retval = ext2fs_write_ext_attr3(fs, block, inbuf, inum);
4008         e2fsck_pass1_fix_unlock(ctx);
4009
4010         return retval;
4011 }
4012 /*
4013  * Adjust the extended attribute block's reference counts at the end
4014  * of pass 1, either by subtracting out references for EA blocks that
4015  * are still referenced in ctx->refcount, or by adding references for
4016  * EA blocks that had extra references as accounted for in
4017  * ctx->refcount_extra.
4018  */
4019 static void adjust_extattr_refcount(e2fsck_t ctx, ext2_refcount_t refcount,
4020                                     char *block_buf, int adjust_sign)
4021 {
4022         struct ext2_ext_attr_header     *header;
4023         struct problem_context          pctx;
4024         ext2_filsys                     fs = ctx->fs;
4025         blk64_t                         blk;
4026         __u32                           should_be;
4027         ea_value_t                      count;
4028
4029         clear_problem_context(&pctx);
4030
4031         ea_refcount_intr_begin(refcount);
4032         while (1) {
4033                 if ((blk = ea_refcount_intr_next(refcount, &count)) == 0)
4034                         break;
4035                 pctx.blk = blk;
4036                 pctx.errcode = ext2fs_read_ext_attr3(fs, blk, block_buf,
4037                                                      pctx.ino);
4038                 /* We already checked this block, shouldn't happen */
4039                 if (pctx.errcode) {
4040                         fix_problem(ctx, PR_1_EXTATTR_READ_ABORT, &pctx);
4041                         return;
4042                 }
4043                 header = BHDR(block_buf);
4044                 if (header->h_magic != EXT2_EXT_ATTR_MAGIC) {
4045                         fix_problem(ctx, PR_1_EXTATTR_READ_ABORT, &pctx);
4046                         return;
4047                 }
4048
4049                 pctx.blkcount = header->h_refcount;
4050                 should_be = header->h_refcount + adjust_sign * (int)count;
4051                 pctx.num = should_be;
4052                 if (fix_problem(ctx, PR_1_EXTATTR_REFCOUNT, &pctx)) {
4053                         header->h_refcount = should_be;
4054                         pctx.errcode = e2fsck_write_ext_attr3(ctx, blk,
4055                                                              block_buf,
4056                                                              pctx.ino);
4057                         if (pctx.errcode) {
4058                                 fix_problem(ctx, PR_1_EXTATTR_WRITE_ABORT,
4059                                             &pctx);
4060                                 continue;
4061                         }
4062                 }
4063         }
4064 }
4065
4066 /*
4067  * Handle processing the extended attribute blocks
4068  */
4069 static int check_ext_attr(e2fsck_t ctx, struct problem_context *pctx,
4070                            char *block_buf, struct ea_quota *ea_block_quota)
4071 {
4072         ext2_filsys fs = ctx->fs;
4073         ext2_ino_t      ino = pctx->ino;
4074         struct ext2_inode *inode = pctx->inode;
4075         blk64_t         blk;
4076         char *          end;
4077         struct ext2_ext_attr_header *header;
4078         struct ext2_ext_attr_entry *first, *entry;
4079         blk64_t         quota_blocks = EXT2FS_C2B(fs, 1);
4080         __u64           quota_inodes = 0;
4081         region_t        region = 0;
4082         int             failed_csum = 0;
4083
4084         ea_block_quota->blocks = 0;
4085         ea_block_quota->inodes = 0;
4086
4087         blk = ext2fs_file_acl_block(fs, inode);
4088         if (blk == 0)
4089                 return 0;
4090
4091         /*
4092          * If the Extended attribute flag isn't set, then a non-zero
4093          * file acl means that the inode is corrupted.
4094          *
4095          * Or if the extended attribute block is an invalid block,
4096          * then the inode is also corrupted.
4097          */
4098         if (!ext2fs_has_feature_xattr(fs->super) ||
4099             (blk < fs->super->s_first_data_block) ||
4100             (blk >= ext2fs_blocks_count(fs->super))) {
4101                 /* Fixed in pass2, e2fsck_process_bad_inode(). */
4102                 e2fsck_mark_inode_bad(ctx, pctx, PR_2_FILE_ACL_ZERO);
4103                 return 0;
4104         }
4105
4106         /* If ea bitmap hasn't been allocated, create it */
4107         if (!ctx->block_ea_map) {
4108                 pctx->errcode = e2fsck_allocate_block_bitmap(fs,
4109                                         _("ext attr block map"),
4110                                         EXT2FS_BMAP64_RBTREE, "block_ea_map",
4111                                         &ctx->block_ea_map);
4112                 if (pctx->errcode) {
4113                         pctx->num = 2;
4114                         fix_problem(ctx, PR_1_ALLOCATE_BBITMAP_ERROR, pctx);
4115                         ctx->flags |= E2F_FLAG_ABORT;
4116                         return 0;
4117                 }
4118         }
4119
4120         /* Create the EA refcount structure if necessary */
4121         if (!ctx->refcount) {
4122                 pctx->errcode = ea_refcount_create(0,
4123                                         &ctx->refcount_orig);
4124                 if (pctx->errcode) {
4125                         pctx->num = 1;
4126                         fix_problem(ctx, PR_1_ALLOCATE_REFCOUNT, pctx);
4127                         ctx->flags |= E2F_FLAG_ABORT;
4128                         return 0;
4129                 }
4130
4131                 pctx->errcode = ea_refcount_create(0, &ctx->refcount);
4132                 if (pctx->errcode) {
4133                         pctx->num = 1;
4134                         fix_problem(ctx, PR_1_ALLOCATE_REFCOUNT, pctx);
4135                         ctx->flags |= E2F_FLAG_ABORT;
4136                         return 0;
4137                 }
4138         }
4139
4140 #if 0
4141         /* Debugging text */
4142         printf("Inode %u has EA block %u\n", ino, blk);
4143 #endif
4144
4145         /* Have we seen this EA block before? */
4146         if (ext2fs_fast_test_block_bitmap2(ctx->block_ea_map, blk)) {
4147                 ea_block_quota->blocks = EXT2FS_C2B(fs, 1);
4148                 ea_block_quota->inodes = 0;
4149
4150                 if (ctx->ea_block_quota_blocks) {
4151                         ea_refcount_fetch(ctx->ea_block_quota_blocks, blk,
4152                                           &quota_blocks);
4153                         if (quota_blocks)
4154                                 ea_block_quota->blocks = quota_blocks;
4155                 }
4156
4157                 if (ctx->ea_block_quota_inodes)
4158                         ea_refcount_fetch(ctx->ea_block_quota_inodes, blk,
4159                                           &ea_block_quota->inodes);
4160
4161                 if (ea_refcount_decrement(ctx->refcount, blk, 0) == 0)
4162                         return 1;
4163                 /* Ooops, this EA was referenced more than it stated */
4164                 if (!ctx->refcount_extra) {
4165                         pctx->errcode = ea_refcount_create(0,
4166                                            &ctx->refcount_extra);
4167                         if (pctx->errcode) {
4168                                 pctx->num = 2;
4169                                 fix_problem(ctx, PR_1_ALLOCATE_REFCOUNT, pctx);
4170                                 ctx->flags |= E2F_FLAG_ABORT;
4171                                 return 0;
4172                         }
4173                 }
4174                 ea_refcount_increment(ctx->refcount_extra, blk, 0);
4175                 return 1;
4176         }
4177
4178         /*
4179          * OK, we haven't seen this EA block yet.  So we need to
4180          * validate it
4181          */
4182         pctx->blk = blk;
4183         pctx->errcode = ext2fs_read_ext_attr3(fs, blk, block_buf, pctx->ino);
4184         if (pctx->errcode == EXT2_ET_EXT_ATTR_CSUM_INVALID) {
4185                 pctx->errcode = 0;
4186                 failed_csum = 1;
4187         } else if (pctx->errcode == EXT2_ET_BAD_EA_HEADER)
4188                 pctx->errcode = 0;
4189
4190         if (pctx->errcode &&
4191             fix_problem(ctx, PR_1_READ_EA_BLOCK, pctx)) {
4192                 pctx->errcode = 0;
4193                 goto clear_extattr;
4194         }
4195         header = BHDR(block_buf);
4196         pctx->blk = ext2fs_file_acl_block(fs, inode);
4197         if (((ctx->ext_attr_ver == 1) &&
4198              (header->h_magic != EXT2_EXT_ATTR_MAGIC_v1)) ||
4199             ((ctx->ext_attr_ver == 2) &&
4200              (header->h_magic != EXT2_EXT_ATTR_MAGIC))) {
4201                 if (fix_problem(ctx, PR_1_BAD_EA_BLOCK, pctx))
4202                         goto clear_extattr;
4203         }
4204
4205         if (header->h_blocks != 1) {
4206                 if (fix_problem(ctx, PR_1_EA_MULTI_BLOCK, pctx))
4207                         goto clear_extattr;
4208         }
4209
4210         if (pctx->errcode && fix_problem(ctx, PR_1_READ_EA_BLOCK, pctx))
4211                 goto clear_extattr;
4212
4213         region = region_create(0, fs->blocksize);
4214         if (!region) {
4215                 fix_problem(ctx, PR_1_EA_ALLOC_REGION_ABORT, pctx);
4216                 ctx->flags |= E2F_FLAG_ABORT;
4217                 return 0;
4218         }
4219         if (region_allocate(region, 0, sizeof(struct ext2_ext_attr_header))) {
4220                 if (fix_problem(ctx, PR_1_EA_ALLOC_COLLISION, pctx))
4221                         goto clear_extattr;
4222         }
4223
4224         first = (struct ext2_ext_attr_entry *)(header+1);
4225         end = block_buf + fs->blocksize;
4226         entry = first;
4227         while ((char *)entry < end && *(__u32 *)entry) {
4228                 __u32 hash;
4229
4230                 if (region_allocate(region, (char *)entry - (char *)header,
4231                                    EXT2_EXT_ATTR_LEN(entry->e_name_len))) {
4232                         if (fix_problem(ctx, PR_1_EA_ALLOC_COLLISION, pctx))
4233                                 goto clear_extattr;
4234                         break;
4235                 }
4236                 if ((ctx->ext_attr_ver == 1 &&
4237                      (entry->e_name_len == 0 || entry->e_name_index != 0)) ||
4238                     (ctx->ext_attr_ver == 2 &&
4239                      entry->e_name_index == 0)) {
4240                         if (fix_problem(ctx, PR_1_EA_BAD_NAME, pctx))
4241                                 goto clear_extattr;
4242                         break;
4243                 }
4244                 if (entry->e_value_inum == 0) {
4245                         if (entry->e_value_offs + entry->e_value_size >
4246                             fs->blocksize) {
4247                                 if (fix_problem(ctx, PR_1_EA_BAD_VALUE, pctx))
4248                                         goto clear_extattr;
4249                                 break;
4250                         }
4251                         if (entry->e_value_size &&
4252                             region_allocate(region, entry->e_value_offs,
4253                                             EXT2_EXT_ATTR_SIZE(entry->e_value_size))) {
4254                                 if (fix_problem(ctx, PR_1_EA_ALLOC_COLLISION,
4255                                                 pctx))
4256                                         goto clear_extattr;
4257                         }
4258
4259                         hash = ext2fs_ext_attr_hash_entry(entry, block_buf +
4260                                                           entry->e_value_offs);
4261
4262                         if (entry->e_hash != hash) {
4263                                 pctx->num = entry->e_hash;
4264                                 if (fix_problem(ctx, PR_1_ATTR_HASH, pctx))
4265                                         goto clear_extattr;
4266                                 entry->e_hash = hash;
4267                         }
4268                 } else {
4269                         problem_t problem;
4270                         blk64_t entry_quota_blocks;
4271
4272                         problem = check_large_ea_inode(ctx, entry, pctx,
4273                                                        &entry_quota_blocks);
4274                         if (problem && fix_problem(ctx, problem, pctx))
4275                                 goto clear_extattr;
4276
4277                         quota_blocks += entry_quota_blocks;
4278                         quota_inodes++;
4279                 }
4280
4281                 entry = EXT2_EXT_ATTR_NEXT(entry);
4282         }
4283         if (region_allocate(region, (char *)entry - (char *)header, 4)) {
4284                 if (fix_problem(ctx, PR_1_EA_ALLOC_COLLISION, pctx))
4285                         goto clear_extattr;
4286         }
4287         region_free(region);
4288
4289         /*
4290          * We only get here if there was no other errors that were fixed.
4291          * If there was a checksum fail, ask to correct it.
4292          */
4293         if (failed_csum &&
4294             fix_problem(ctx, PR_1_EA_BLOCK_ONLY_CSUM_INVALID, pctx)) {
4295                 pctx->errcode = e2fsck_write_ext_attr3(ctx, blk, block_buf,
4296                                                        pctx->ino);
4297                 if (pctx->errcode)
4298                         return 0;
4299         }
4300
4301         if (quota_blocks != EXT2FS_C2B(fs, 1U)) {
4302                 if (!ctx->ea_block_quota_blocks) {
4303                         pctx->errcode = ea_refcount_create(0,
4304                                                 &ctx->ea_block_quota_blocks);
4305                         if (pctx->errcode) {
4306                                 pctx->num = 3;
4307                                 goto refcount_fail;
4308                         }
4309                 }
4310                 ea_refcount_store(ctx->ea_block_quota_blocks, blk,
4311                                   quota_blocks);
4312         }
4313
4314         if (quota_inodes) {
4315                 if (!ctx->ea_block_quota_inodes) {
4316                         pctx->errcode = ea_refcount_create(0,
4317                                                 &ctx->ea_block_quota_inodes);
4318                         if (pctx->errcode) {
4319                                 pctx->num = 4;
4320 refcount_fail:
4321                                 fix_problem(ctx, PR_1_ALLOCATE_REFCOUNT, pctx);
4322                                 ctx->flags |= E2F_FLAG_ABORT;
4323                                 return 0;
4324                         }
4325                 }
4326
4327                 ea_refcount_store(ctx->ea_block_quota_inodes, blk,
4328                                   quota_inodes);
4329         }
4330         ea_block_quota->blocks = quota_blocks;
4331         ea_block_quota->inodes = quota_inodes;
4332
4333         inc_ea_inode_refs(ctx, pctx, first, end);
4334         ea_refcount_store(ctx->refcount, blk, header->h_refcount - 1);
4335         ea_refcount_store(ctx->refcount_orig, blk, header->h_refcount);
4336         /**
4337          * It might be racy that this block has been merged in the
4338          * global found map.
4339          */
4340         if (!is_blocks_used(ctx, blk, 1))
4341                 ext2fs_fast_mark_block_bitmap2(ctx->block_found_map, blk);
4342         ext2fs_fast_mark_block_bitmap2(ctx->block_ea_map, blk);
4343         return 1;
4344
4345 clear_extattr:
4346         if (region)
4347                 region_free(region);
4348         ext2fs_file_acl_block_set(fs, inode, 0);
4349         e2fsck_write_inode(ctx, ino, inode, "check_ext_attr");
4350         return 0;
4351 }
4352
4353 /* Returns 1 if bad htree, 0 if OK */
4354 static int handle_htree(e2fsck_t ctx, struct problem_context *pctx,
4355                         ext2_ino_t ino, struct ext2_inode *inode,
4356                         char *block_buf)
4357 {
4358         struct ext2_dx_root_info        *root;
4359         ext2_filsys                     fs = ctx->fs;
4360         errcode_t                       retval;
4361         blk64_t                         blk;
4362
4363         if ((!LINUX_S_ISDIR(inode->i_mode) &&
4364              fix_problem(ctx, PR_1_HTREE_NODIR, pctx)) ||
4365             (!ext2fs_has_feature_dir_index(fs->super) &&
4366              fix_problem(ctx, PR_1_HTREE_SET, pctx)))
4367                 return 1;
4368
4369         pctx->errcode = ext2fs_bmap2(fs, ino, inode, 0, 0, 0, 0, &blk);
4370
4371         if ((pctx->errcode) ||
4372             (blk == 0) ||
4373             (blk < fs->super->s_first_data_block) ||
4374             (blk >= ext2fs_blocks_count(fs->super))) {
4375                 if (fix_problem(ctx, PR_1_HTREE_BADROOT, pctx))
4376                         return 1;
4377                 else
4378                         return 0;
4379         }
4380
4381         retval = io_channel_read_blk64(fs->io, blk, 1, block_buf);
4382         if (retval) {
4383                 if (fix_problem(ctx, PR_1_HTREE_BADROOT, pctx))
4384                         return 1;
4385         }
4386
4387         /* XXX should check that beginning matches a directory */
4388         root = get_ext2_dx_root_info(fs, block_buf);
4389
4390         if ((root->reserved_zero || root->info_length < 8) &&
4391             fix_problem(ctx, PR_1_HTREE_BADROOT, pctx))
4392                 return 1;
4393
4394         pctx->num = root->hash_version;
4395         if ((root->hash_version != EXT2_HASH_LEGACY) &&
4396             (root->hash_version != EXT2_HASH_HALF_MD4) &&
4397             (root->hash_version != EXT2_HASH_TEA) &&
4398             (root->hash_version != EXT2_HASH_SIPHASH) &&
4399             fix_problem(ctx, PR_1_HTREE_HASHV, pctx))
4400                 return 1;
4401
4402         if (ext4_hash_in_dirent(inode)) {
4403                 if (root->hash_version != EXT2_HASH_SIPHASH &&
4404                     fix_problem(ctx, PR_1_HTREE_NEEDS_SIPHASH, pctx))
4405                         return 1;
4406         } else {
4407                 if (root->hash_version == EXT2_HASH_SIPHASH &&
4408                    fix_problem(ctx, PR_1_HTREE_CANNOT_SIPHASH, pctx))
4409                         return 1;
4410         }
4411
4412         if ((root->unused_flags & EXT2_HASH_FLAG_INCOMPAT) &&
4413             fix_problem(ctx, PR_1_HTREE_INCOMPAT, pctx))
4414                 return 1;
4415
4416         pctx->num = root->indirect_levels;
4417         /* if htree level is clearly too high, consider it to be broken */
4418         if (root->indirect_levels > EXT4_HTREE_LEVEL &&
4419             fix_problem(ctx, PR_1_HTREE_DEPTH, pctx))
4420                 return 1;
4421
4422         /* if level is only maybe too high, LARGE_DIR feature could be unset */
4423         if (root->indirect_levels > ext2_dir_htree_level(fs) &&
4424             !ext2fs_has_feature_largedir(fs->super)) {
4425                 int blockbits = EXT2_BLOCK_SIZE_BITS(fs->super) + 10;
4426                 int idx_pb = 1 << (blockbits - 3);
4427
4428                 /* compare inode size/blocks vs. max-sized 2-level htree */
4429                 if (EXT2_I_SIZE(pctx->inode) <
4430                     (idx_pb - 1) * (idx_pb - 2) << blockbits &&
4431                     pctx->inode->i_blocks <
4432                     (idx_pb - 1) * (idx_pb - 2) << (blockbits - 9) &&
4433                     fix_problem(ctx, PR_1_HTREE_DEPTH, pctx))
4434                         return 1;
4435         }
4436
4437         if (root->indirect_levels > EXT4_HTREE_LEVEL_COMPAT ||
4438             ext2fs_needs_large_file_feature(EXT2_I_SIZE(inode)))
4439                 ctx->large_dirs++;
4440
4441         return 0;
4442 }
4443
4444 void e2fsck_clear_inode(e2fsck_t ctx, ext2_ino_t ino,
4445                         struct ext2_inode *inode, int restart_flag,
4446                         const char *source)
4447 {
4448         inode->i_flags = 0;
4449         inode->i_links_count = 0;
4450         ext2fs_icount_store(ctx->inode_link_info, ino, 0);
4451         inode->i_dtime = ctx->now;
4452
4453         /*
4454          * If a special inode has such rotten block mappings that we
4455          * want to clear the whole inode, be sure to actually zap
4456          * the block maps because i_links_count isn't checked for
4457          * special inodes, and we'll end up right back here the next
4458          * time we run fsck.
4459          */
4460         if (ino < EXT2_FIRST_INODE(ctx->fs->super))
4461                 memset(inode->i_block, 0, sizeof(inode->i_block));
4462
4463         ext2fs_unmark_inode_bitmap2(ctx->inode_dir_map, ino);
4464         ext2fs_unmark_inode_bitmap2(ctx->inode_used_map, ino);
4465         if (ctx->inode_reg_map)
4466                 ext2fs_unmark_inode_bitmap2(ctx->inode_reg_map, ino);
4467         if (ctx->inode_badness)
4468                 ext2fs_icount_store(ctx->inode_badness, ino, 0);
4469
4470         /*
4471          * If the inode was partially accounted for before processing
4472          * was aborted, we need to restart the pass 1 scan.
4473          */
4474         ctx->flags |= restart_flag;
4475
4476         if (ino == EXT2_BAD_INO)
4477                 memset(inode, 0, sizeof(struct ext2_inode));
4478
4479         e2fsck_write_inode(ctx, ino, inode, source);
4480 }
4481
4482 /*
4483  * Use the multiple-blocks reclamation code to fix alignment problems in
4484  * a bigalloc filesystem.  We want a logical cluster to map to *only* one
4485  * physical cluster, and we want the block offsets within that cluster to
4486  * line up.
4487  */
4488 static int has_unaligned_cluster_map(e2fsck_t ctx,
4489                                      blk64_t last_pblk, blk64_t last_lblk,
4490                                      blk64_t pblk, blk64_t lblk)
4491 {
4492         blk64_t cluster_mask;
4493
4494         if (!ctx->fs->cluster_ratio_bits)
4495                 return 0;
4496         cluster_mask = EXT2FS_CLUSTER_MASK(ctx->fs);
4497
4498         /*
4499          * If the block in the logical cluster doesn't align with the block in
4500          * the physical cluster...
4501          */
4502         if ((lblk & cluster_mask) != (pblk & cluster_mask))
4503                 return 1;
4504
4505         /*
4506          * If we cross a physical cluster boundary within a logical cluster...
4507          */
4508         if (last_pblk && (lblk & cluster_mask) != 0 &&
4509             EXT2FS_B2C(ctx->fs, lblk) == EXT2FS_B2C(ctx->fs, last_lblk) &&
4510             EXT2FS_B2C(ctx->fs, pblk) != EXT2FS_B2C(ctx->fs, last_pblk))
4511                 return 1;
4512
4513         return 0;
4514 }
4515
4516 static void scan_extent_node(e2fsck_t ctx, struct problem_context *pctx,
4517                              struct process_block_struct *pb,
4518                              blk64_t start_block, blk64_t end_block,
4519                              blk64_t eof_block,
4520                              ext2_extent_handle_t ehandle,
4521                              int try_repairs)
4522 {
4523         struct ext2fs_extent    extent;
4524         blk64_t                 blk, last_lblk;
4525         unsigned int            i, n;
4526         int                     is_dir, is_leaf;
4527         problem_t               problem;
4528         struct ext2_extent_info info;
4529         int                     failed_csum = 0;
4530
4531         if (pctx->errcode == EXT2_ET_EXTENT_CSUM_INVALID)
4532                 failed_csum = 1;
4533
4534         pctx->errcode = ext2fs_extent_get_info(ehandle, &info);
4535         if (pctx->errcode)
4536                 return;
4537         if (!(ctx->options & E2F_OPT_FIXES_ONLY) &&
4538             !pb->eti.force_rebuild) {
4539                 struct extent_tree_level *etl;
4540
4541                 etl = pb->eti.ext_info + info.curr_level;
4542                 etl->num_extents += info.num_entries;
4543                 etl->max_extents += info.max_entries;
4544                 /*
4545                  * Implementation wart: Splitting extent blocks when appending
4546                  * will leave the old block with one free entry.  Therefore
4547                  * unless the node is totally full, pretend that a non-root
4548                  * extent block can hold one fewer entry than it actually does,
4549                  * so that we don't repeatedly rebuild the extent tree.
4550                  */
4551                 if (info.curr_level && info.num_entries < info.max_entries)
4552                         etl->max_extents--;
4553         }
4554
4555         pctx->errcode = ext2fs_extent_get(ehandle, EXT2_EXTENT_FIRST_SIB,
4556                                           &extent);
4557         while ((pctx->errcode == 0 ||
4558                 pctx->errcode == EXT2_ET_EXTENT_CSUM_INVALID) &&
4559                info.num_entries-- > 0) {
4560                 is_leaf = extent.e_flags & EXT2_EXTENT_FLAGS_LEAF;
4561                 is_dir = LINUX_S_ISDIR(pctx->inode->i_mode);
4562                 last_lblk = extent.e_lblk + extent.e_len - 1;
4563
4564                 problem = 0;
4565                 pctx->blk = extent.e_pblk;
4566                 pctx->blk2 = extent.e_lblk;
4567                 pctx->num = extent.e_len;
4568                 pctx->blkcount = extent.e_lblk + extent.e_len;
4569
4570                 if (extent.e_pblk == 0 ||
4571                     extent.e_pblk < ctx->fs->super->s_first_data_block ||
4572                     extent.e_pblk >= ext2fs_blocks_count(ctx->fs->super))
4573                         problem = PR_1_EXTENT_BAD_START_BLK;
4574                 else if (extent.e_lblk < start_block)
4575                         problem = PR_1_OUT_OF_ORDER_EXTENTS;
4576                 else if ((end_block && last_lblk > end_block) &&
4577                          !(last_lblk > eof_block &&
4578                            ((extent.e_flags & EXT2_EXTENT_FLAGS_UNINIT) ||
4579                             (pctx->inode->i_flags & EXT4_VERITY_FL))))
4580                         problem = PR_1_EXTENT_END_OUT_OF_BOUNDS;
4581                 else if (is_leaf && extent.e_len == 0)
4582                         problem = PR_1_EXTENT_LENGTH_ZERO;
4583                 else if (is_leaf &&
4584                          (extent.e_pblk + extent.e_len) >
4585                          ext2fs_blocks_count(ctx->fs->super))
4586                         problem = PR_1_EXTENT_ENDS_BEYOND;
4587                 else if (is_leaf && is_dir && !pctx->inode->i_size_high &&
4588                          !ext2fs_has_feature_largedir(ctx->fs->super) &&
4589                          ((extent.e_lblk + extent.e_len) >
4590                           (1U << (21 - ctx->fs->super->s_log_block_size))))
4591                         problem = PR_1_TOOBIG_DIR;
4592
4593                 if (is_leaf && problem == 0 && extent.e_len > 0) {
4594 #if 0
4595                         printf("extent_region(ino=%u, expect=%llu, "
4596                                "lblk=%llu, len=%u)\n", pb->ino,
4597                                (unsigned long long) pb->next_lblock,
4598                                (unsigned long long) extent.e_lblk,
4599                                extent.e_len);
4600 #endif
4601                         if (extent.e_lblk < pb->next_lblock)
4602                                 problem = PR_1_EXTENT_COLLISION;
4603                         else if (extent.e_lblk + extent.e_len > pb->next_lblock)
4604                                 pb->next_lblock = extent.e_lblk + extent.e_len;
4605                 }
4606
4607                 /*
4608                  * Uninitialized blocks in a directory?  Clear the flag and
4609                  * we'll interpret the blocks later.
4610                  */
4611                 if (try_repairs && is_dir && problem == 0 &&
4612                     (extent.e_flags & EXT2_EXTENT_FLAGS_UNINIT) &&
4613                     fix_problem(ctx, PR_1_UNINIT_DBLOCK, pctx)) {
4614                         e2fsck_pass1_fix_lock(ctx);
4615                         extent.e_flags &= ~EXT2_EXTENT_FLAGS_UNINIT;
4616                         pb->inode_modified = 1;
4617                         pctx->errcode = ext2fs_extent_replace(ehandle, 0,
4618                                                               &extent);
4619                         e2fsck_pass1_fix_unlock(ctx);
4620                         if (pctx->errcode)
4621                                 return;
4622                         failed_csum = 0;
4623                 }
4624 #ifdef CONFIG_DEVELOPER_FEATURES
4625                 if (try_repairs && !is_dir && problem == 0 &&
4626                     (ctx->options & E2F_OPT_CLEAR_UNINIT) &&
4627                     (extent.e_flags & EXT2_EXTENT_FLAGS_UNINIT) &&
4628                     fix_problem(ctx, PR_1_CLEAR_UNINIT_EXTENT, pctx)) {
4629                         extent.e_flags &= ~EXT2_EXTENT_FLAGS_UNINIT;
4630                         pb->inode_modified = 1;
4631                         pctx->errcode = ext2fs_extent_replace(ehandle, 0,
4632                                                               &extent);
4633                         if (pctx->errcode)
4634                                 return;
4635                         failed_csum = 0;
4636                 }
4637 #endif
4638                 if (try_repairs && problem) {
4639 report_problem:
4640                         /* Record badness only if extent is within inode */
4641                         if (fix_problem_bad(ctx, problem, pctx,
4642                                             info.curr_level == 0)) {
4643                                 if (ctx->invalid_bitmaps) {
4644                                         /*
4645                                          * If fsck knows the bitmaps are bad,
4646                                          * skip to the next extent and
4647                                          * try to clear this extent again
4648                                          * after fixing the bitmaps, by
4649                                          * restarting fsck.
4650                                          */
4651                                         pctx->errcode = ext2fs_extent_get(
4652                                                           ehandle,
4653                                                           EXT2_EXTENT_NEXT_SIB,
4654                                                           &extent);
4655                                         ctx->flags |= E2F_FLAG_RESTART_LATER;
4656                                         if (pctx->errcode ==
4657                                                     EXT2_ET_NO_CURRENT_NODE) {
4658                                                 pctx->errcode = 0;
4659                                                 break;
4660                                         }
4661                                         continue;
4662                                 }
4663                                 e2fsck_pass1_fix_lock(ctx);
4664                                 e2fsck_read_bitmaps(ctx);
4665                                 pb->inode_modified = 1;
4666                                 pctx->errcode =
4667                                         ext2fs_extent_delete(ehandle, 0);
4668                                 e2fsck_pass1_fix_unlock(ctx);
4669                                 if (pctx->errcode) {
4670                                         pctx->str = "ext2fs_extent_delete";
4671                                         return;
4672                                 }
4673                                 e2fsck_pass1_fix_lock(ctx);
4674                                 pctx->errcode = ext2fs_extent_fix_parents(ehandle);
4675                                 e2fsck_pass1_fix_unlock(ctx);
4676                                 if (pctx->errcode &&
4677                                     pctx->errcode != EXT2_ET_NO_CURRENT_NODE) {
4678                                         pctx->str = "ext2fs_extent_fix_parents";
4679                                         return;
4680                                 }
4681                                 pctx->errcode = ext2fs_extent_get(ehandle,
4682                                                                   EXT2_EXTENT_CURRENT,
4683                                                                   &extent);
4684                                 if (pctx->errcode == EXT2_ET_NO_CURRENT_NODE) {
4685                                         pctx->errcode = 0;
4686                                         break;
4687                                 }
4688                                 failed_csum = 0;
4689                                 continue;
4690                         }
4691                         goto next;
4692                 }
4693
4694                 if (!is_leaf) {
4695                         blk64_t lblk = extent.e_lblk;
4696                         int next_try_repairs = 1;
4697
4698                         blk = extent.e_pblk;
4699
4700                         /*
4701                          * If this lower extent block collides with critical
4702                          * metadata, don't try to repair the damage.  Pass 1b
4703                          * will reallocate the block; then we can try again.
4704                          */
4705                         if (pb->ino != EXT2_RESIZE_INO &&
4706                             extent.e_pblk < ctx->fs->super->s_blocks_count &&
4707                             ext2fs_test_block_bitmap2(ctx->block_metadata_map,
4708                                                       extent.e_pblk)) {
4709                                 next_try_repairs = 0;
4710                                 pctx->blk = blk;
4711                                 fix_problem_bad(ctx,
4712                                             PR_1_CRITICAL_METADATA_COLLISION,
4713                                             pctx, 2);
4714                                 if ((ctx->options & E2F_OPT_NO) == 0)
4715                                         ctx->flags |= E2F_FLAG_RESTART_LATER;
4716                         }
4717                         pctx->errcode = ext2fs_extent_get(ehandle,
4718                                                   EXT2_EXTENT_DOWN, &extent);
4719                         if (pctx->errcode &&
4720                             pctx->errcode != EXT2_ET_EXTENT_CSUM_INVALID) {
4721                                 pctx->str = "EXT2_EXTENT_DOWN";
4722                                 problem = PR_1_EXTENT_HEADER_INVALID;
4723                                 if (!next_try_repairs)
4724                                         return;
4725                                 if (pctx->errcode == EXT2_ET_EXTENT_HEADER_BAD)
4726                                         goto report_problem;
4727                                 return;
4728                         }
4729                         /* The next extent should match this index's logical start */
4730                         if (extent.e_lblk != lblk) {
4731                                 struct ext2_extent_info e_info;
4732
4733                                 pctx->errcode = ext2fs_extent_get_info(ehandle,
4734                                                                        &e_info);
4735                                 if (pctx->errcode) {
4736                                         pctx->str = "ext2fs_extent_get_info";
4737                                         return;
4738                                 }
4739                                 pctx->blk = lblk;
4740                                 pctx->blk2 = extent.e_lblk;
4741                                 pctx->num = e_info.curr_level - 1;
4742                                 problem = PR_1_EXTENT_INDEX_START_INVALID;
4743                                 if (fix_problem(ctx, problem, pctx)) {
4744                                         e2fsck_pass1_fix_lock(ctx);
4745                                         pb->inode_modified = 1;
4746                                         pctx->errcode =
4747                                                 ext2fs_extent_fix_parents(ehandle);
4748                                         e2fsck_pass1_fix_unlock(ctx);
4749                                         if (pctx->errcode) {
4750                                                 pctx->str = "ext2fs_extent_fix_parents";
4751                                                 return;
4752                                         }
4753                                 }
4754                         }
4755                         scan_extent_node(ctx, pctx, pb, extent.e_lblk,
4756                                          last_lblk, eof_block, ehandle,
4757                                          next_try_repairs);
4758                         if (pctx->errcode)
4759                                 return;
4760                         pctx->errcode = ext2fs_extent_get(ehandle,
4761                                                   EXT2_EXTENT_UP, &extent);
4762                         if (pctx->errcode) {
4763                                 pctx->str = "EXT2_EXTENT_UP";
4764                                 return;
4765                         }
4766                         mark_block_used(ctx, blk);
4767                         pb->num_blocks++;
4768                         goto next;
4769                 }
4770
4771                 if ((pb->previous_block != 0) &&
4772                     (pb->previous_block+1 != extent.e_pblk)) {
4773                         if (ctx->options & E2F_OPT_FRAGCHECK) {
4774                                 char type = '?';
4775
4776                                 if (pb->is_dir)
4777                                         type = 'd';
4778                                 else if (pb->is_reg)
4779                                         type = 'f';
4780
4781                                 printf(("%6lu(%c): expecting %6lu "
4782                                         "actual extent "
4783                                         "phys %6lu log %lu len %lu\n"),
4784                                        (unsigned long) pctx->ino, type,
4785                                        (unsigned long) pb->previous_block+1,
4786                                        (unsigned long) extent.e_pblk,
4787                                        (unsigned long) extent.e_lblk,
4788                                        (unsigned long) extent.e_len);
4789                         }
4790                         pb->fragmented = 1;
4791                 }
4792                 /*
4793                  * If we notice a gap in the logical block mappings of an
4794                  * extent-mapped directory, offer to close the hole by
4795                  * moving the logical block down, otherwise we'll go mad in
4796                  * pass 3 allocating empty directory blocks to fill the hole.
4797                  */
4798                 if (try_repairs && is_dir &&
4799                     pb->last_block + 1 < extent.e_lblk) {
4800                         blk64_t new_lblk;
4801
4802                         new_lblk = pb->last_block + 1;
4803                         if (EXT2FS_CLUSTER_RATIO(ctx->fs) > 1)
4804                                 new_lblk = ((new_lblk +
4805                                              EXT2FS_CLUSTER_RATIO(ctx->fs) - 1) &
4806                                             ~EXT2FS_CLUSTER_MASK(ctx->fs)) |
4807                                            (extent.e_pblk &
4808                                             EXT2FS_CLUSTER_MASK(ctx->fs));
4809                         pctx->blk = extent.e_lblk;
4810                         pctx->blk2 = new_lblk;
4811                         if (fix_problem(ctx, PR_1_COLLAPSE_DBLOCK, pctx)) {
4812                                 e2fsck_pass1_fix_lock(ctx);
4813                                 extent.e_lblk = new_lblk;
4814                                 pb->inode_modified = 1;
4815                                 pctx->errcode = ext2fs_extent_replace(ehandle,
4816                                                                 0, &extent);
4817                                 e2fsck_pass1_fix_unlock(ctx);
4818                                 if (pctx->errcode) {
4819                                         pctx->errcode = 0;
4820                                         goto alloc_later;
4821                                 }
4822                                 e2fsck_pass1_fix_lock(ctx);
4823                                 pctx->errcode = ext2fs_extent_fix_parents(ehandle);
4824                                 e2fsck_pass1_fix_unlock(ctx);
4825                                 if (pctx->errcode)
4826                                         goto failed_add_dir_block;
4827                                 pctx->errcode = ext2fs_extent_goto(ehandle,
4828                                                                 extent.e_lblk);
4829                                 if (pctx->errcode)
4830                                         goto failed_add_dir_block;
4831                                 last_lblk = extent.e_lblk + extent.e_len - 1;
4832                                 failed_csum = 0;
4833                         }
4834                 }
4835 alloc_later:
4836                 if (is_dir) {
4837                         while (++pb->last_db_block <
4838                                (e2_blkcnt_t) extent.e_lblk) {
4839                                 pctx->errcode = ext2fs_add_dir_block2(
4840                                                         ctx->fs->dblist,
4841                                                         pb->ino, 0,
4842                                                         pb->last_db_block);
4843                                 if (pctx->errcode) {
4844                                         pctx->blk = 0;
4845                                         pctx->num = pb->last_db_block;
4846                                         goto failed_add_dir_block;
4847                                 }
4848                         }
4849
4850                         for (i = 0; i < extent.e_len; i++) {
4851                                 pctx->errcode = ext2fs_add_dir_block2(
4852                                                         ctx->fs->dblist,
4853                                                         pctx->ino,
4854                                                         extent.e_pblk + i,
4855                                                         extent.e_lblk + i);
4856                                 if (pctx->errcode) {
4857                                         pctx->blk = extent.e_pblk + i;
4858                                         pctx->num = extent.e_lblk + i;
4859                                 failed_add_dir_block:
4860                                         fix_problem(ctx, PR_1_ADD_DBLOCK, pctx);
4861                                         /* Should never get here */
4862                                         ctx->flags |= E2F_FLAG_ABORT;
4863                                         return;
4864                                 }
4865                         }
4866                         if (extent.e_len > 0)
4867                                 pb->last_db_block = extent.e_lblk + extent.e_len - 1;
4868                 }
4869                 if (has_unaligned_cluster_map(ctx, pb->previous_block,
4870                                               pb->last_block,
4871                                               extent.e_pblk,
4872                                               extent.e_lblk)) {
4873                         for (i = 0; i < extent.e_len; i++) {
4874                                 pctx->blk = extent.e_lblk + i;
4875                                 pctx->blk2 = extent.e_pblk + i;
4876                                 fix_problem(ctx, PR_1_MISALIGNED_CLUSTER, pctx);
4877                                 mark_block_used(ctx, extent.e_pblk + i);
4878                                 mark_block_used(ctx, extent.e_pblk + i);
4879                         }
4880                 }
4881
4882                 /*
4883                  * Check whether first cluster got marked in previous iteration.
4884                  */
4885                 if (ctx->fs->cluster_ratio_bits &&
4886                     pb->previous_block &&
4887                     (EXT2FS_B2C(ctx->fs, extent.e_pblk) ==
4888                      EXT2FS_B2C(ctx->fs, pb->previous_block)))
4889                         /* Set blk to the beginning of next cluster. */
4890                         blk = EXT2FS_C2B(
4891                                 ctx->fs,
4892                                 EXT2FS_B2C(ctx->fs, extent.e_pblk) + 1);
4893                 else
4894                         /* Set blk to the beginning of current cluster. */
4895                         blk = EXT2FS_C2B(ctx->fs,
4896                                          EXT2FS_B2C(ctx->fs, extent.e_pblk));
4897
4898                 if (blk < extent.e_pblk + extent.e_len) {
4899                         mark_blocks_used(ctx, blk,
4900                                          extent.e_pblk + extent.e_len - blk);
4901                         n = DIV_ROUND_UP(extent.e_pblk + extent.e_len - blk,
4902                                          EXT2FS_CLUSTER_RATIO(ctx->fs));
4903                         pb->num_blocks += n;
4904                 }
4905                 pb->last_block = extent.e_lblk + extent.e_len - 1;
4906                 pb->previous_block = extent.e_pblk + extent.e_len - 1;
4907                 start_block = pb->last_block = last_lblk;
4908                 if (is_leaf && !is_dir &&
4909                     !(extent.e_flags & EXT2_EXTENT_FLAGS_UNINIT))
4910                         pb->last_init_lblock = last_lblk;
4911         next:
4912                 pctx->errcode = ext2fs_extent_get(ehandle,
4913                                                   EXT2_EXTENT_NEXT_SIB,
4914                                                   &extent);
4915         }
4916
4917         /* Failed csum but passes checks?  Ask to fix checksum. */
4918         if (failed_csum &&
4919             fix_problem(ctx, PR_1_EXTENT_ONLY_CSUM_INVALID, pctx)) {
4920                 e2fsck_pass1_fix_lock(ctx);
4921                 pb->inode_modified = 1;
4922                 pctx->errcode = ext2fs_extent_replace(ehandle, 0, &extent);
4923                 e2fsck_pass1_fix_unlock(ctx);
4924                 if (pctx->errcode)
4925                         return;
4926         }
4927
4928         if (pctx->errcode == EXT2_ET_EXTENT_NO_NEXT)
4929                 pctx->errcode = 0;
4930 }
4931
4932 static void check_blocks_extents(e2fsck_t ctx, struct problem_context *pctx,
4933                                  struct process_block_struct *pb)
4934 {
4935         struct ext2_extent_info info;
4936         struct ext2_inode       *inode = pctx->inode;
4937         ext2_extent_handle_t    ehandle;
4938         ext2_filsys             fs = ctx->fs;
4939         ext2_ino_t              ino = pctx->ino;
4940         errcode_t               retval;
4941         blk64_t                 eof_lblk;
4942         struct ext3_extent_header       *eh;
4943
4944         /* Check for a proper extent header... */
4945         eh = (struct ext3_extent_header *) &inode->i_block[0];
4946         retval = ext2fs_extent_header_verify(eh, sizeof(inode->i_block));
4947         if (retval) {
4948                 if (fix_problem(ctx, PR_1_MISSING_EXTENT_HEADER, pctx))
4949                         e2fsck_clear_inode(ctx, ino, inode, 0,
4950                                            "check_blocks_extents");
4951                 pctx->errcode = 0;
4952                 return;
4953         }
4954
4955         /* ...since this function doesn't fail if i_block is zeroed. */
4956         pctx->errcode = ext2fs_extent_open2(fs, ino, inode, &ehandle);
4957         if (pctx->errcode) {
4958                 if (fix_problem(ctx, PR_1_READ_EXTENT, pctx))
4959                         e2fsck_clear_inode(ctx, ino, inode, 0,
4960                                            "check_blocks_extents");
4961                 pctx->errcode = 0;
4962                 return;
4963         }
4964
4965         retval = ext2fs_extent_get_info(ehandle, &info);
4966         if (retval == 0) {
4967                 int max_depth = info.max_depth;
4968
4969                 if (max_depth >= MAX_EXTENT_DEPTH_COUNT)
4970                         max_depth = MAX_EXTENT_DEPTH_COUNT-1;
4971                 ctx->extent_depth_count[max_depth]++;
4972         }
4973
4974         /* Check maximum extent depth */
4975         pctx->blk = info.max_depth;
4976         pctx->blk2 = ext2fs_max_extent_depth(ehandle);
4977         if (pctx->blk2 < pctx->blk &&
4978             fix_problem(ctx, PR_1_EXTENT_BAD_MAX_DEPTH, pctx))
4979                 pb->eti.force_rebuild = 1;
4980
4981         /* Can we collect extent tree level stats? */
4982         pctx->blk = MAX_EXTENT_DEPTH_COUNT;
4983         if (pctx->blk2 > pctx->blk)
4984                 fix_problem(ctx, PR_1E_MAX_EXTENT_TREE_DEPTH, pctx);
4985         memset(pb->eti.ext_info, 0, sizeof(pb->eti.ext_info));
4986         pb->eti.ino = pb->ino;
4987
4988         pb->next_lblock = 0;
4989
4990         eof_lblk = ((EXT2_I_SIZE(inode) + fs->blocksize - 1) >>
4991                 EXT2_BLOCK_SIZE_BITS(fs->super)) - 1;
4992         scan_extent_node(ctx, pctx, pb, 0, 0, eof_lblk, ehandle, 1);
4993         if (pctx->errcode &&
4994             fix_problem(ctx, PR_1_EXTENT_ITERATE_FAILURE, pctx)) {
4995                 pb->num_blocks = 0;
4996                 inode->i_blocks = 0;
4997                 e2fsck_clear_inode(ctx, ino, inode, E2F_FLAG_RESTART,
4998                                    "check_blocks_extents");
4999                 pctx->errcode = 0;
5000         }
5001         ext2fs_extent_free(ehandle);
5002
5003         /* Rebuild unless it's a dir and we're rehashing it */
5004         if (LINUX_S_ISDIR(inode->i_mode) &&
5005             e2fsck_dir_will_be_rehashed(ctx, ino))
5006                 return;
5007
5008         if (ctx->options & E2F_OPT_CONVERT_BMAP)
5009                 e2fsck_rebuild_extents_later(ctx, ino);
5010         else
5011                 e2fsck_should_rebuild_extents(ctx, pctx, &pb->eti, &info);
5012 }
5013
5014 /*
5015  * In fact we don't need to check blocks for an inode with inline data
5016  * because this inode doesn't have any blocks.  In this function all
5017  * we need to do is add this inode into dblist when it is a directory.
5018  */
5019 static void check_blocks_inline_data(e2fsck_t ctx, struct problem_context *pctx,
5020                                      struct process_block_struct *pb)
5021 {
5022         int     flags;
5023         size_t  inline_data_size = 0;
5024
5025         if (!pb->is_dir) {
5026                 pctx->errcode = 0;
5027                 return;
5028         }
5029
5030         /* Process the dirents in i_block[] as the "first" block. */
5031         pctx->errcode = ext2fs_add_dir_block2(ctx->fs->dblist, pb->ino, 0, 0);
5032         if (pctx->errcode)
5033                 goto err;
5034
5035         /* Process the dirents in the EA as a "second" block. */
5036         flags = ctx->fs->flags;
5037         ctx->fs->flags |= EXT2_FLAG_IGNORE_CSUM_ERRORS;
5038         pctx->errcode = ext2fs_inline_data_size(ctx->fs, pb->ino,
5039                                                 &inline_data_size);
5040         ctx->fs->flags = (flags & EXT2_FLAG_IGNORE_CSUM_ERRORS) |
5041                          (ctx->fs->flags & ~EXT2_FLAG_IGNORE_CSUM_ERRORS);
5042         if (pctx->errcode) {
5043                 pctx->errcode = 0;
5044                 return;
5045         }
5046
5047         if (inline_data_size <= EXT4_MIN_INLINE_DATA_SIZE)
5048                 return;
5049
5050         pctx->errcode = ext2fs_add_dir_block2(ctx->fs->dblist, pb->ino, 0, 1);
5051         if (pctx->errcode)
5052                 goto err;
5053
5054         return;
5055 err:
5056         pctx->blk = 0;
5057         pctx->num = 0;
5058         fix_problem(ctx, PR_1_ADD_DBLOCK, pctx);
5059         ctx->flags |= E2F_FLAG_ABORT;
5060 }
5061
5062 /*
5063  * This subroutine is called on each inode to account for all of the
5064  * blocks used by that inode.
5065  */
5066 static void check_blocks(e2fsck_t ctx, struct problem_context *pctx,
5067                          char *block_buf, const struct ea_quota *ea_ibody_quota)
5068 {
5069         ext2_filsys fs = ctx->fs;
5070         struct process_block_struct pb;
5071         ext2_ino_t      ino = pctx->ino;
5072         struct ext2_inode *inode = pctx->inode;
5073         unsigned        bad_size = 0;
5074         int             dirty_inode = 0;
5075         int             extent_fs;
5076         int             inlinedata_fs;
5077         __u64           size;
5078         struct ea_quota ea_block_quota;
5079
5080         pb.ino = ino;
5081         pb.num_blocks = EXT2FS_B2C(ctx->fs,
5082                                    ea_ibody_quota ? ea_ibody_quota->blocks : 0);
5083         pb.last_block = ~0;
5084         pb.last_init_lblock = -1;
5085         pb.last_db_block = -1;
5086         pb.num_illegal_blocks = 0;
5087         pb.suppress = 0; pb.clear = 0;
5088         pb.fragmented = 0;
5089         pb.compressed = 0;
5090         pb.previous_block = 0;
5091         pb.is_dir = LINUX_S_ISDIR(inode->i_mode);
5092         pb.is_reg = LINUX_S_ISREG(inode->i_mode);
5093         pb.max_blocks = 1U << (31 - fs->super->s_log_block_size);
5094         pb.inode = inode;
5095         pb.pctx = pctx;
5096         pb.ctx = ctx;
5097         pb.inode_modified = 0;
5098         pb.eti.force_rebuild = 0;
5099         pctx->ino = ino;
5100         pctx->errcode = 0;
5101
5102         extent_fs = ext2fs_has_feature_extents(ctx->fs->super);
5103         inlinedata_fs = ext2fs_has_feature_inline_data(ctx->fs->super);
5104
5105         if (check_ext_attr(ctx, pctx, block_buf, &ea_block_quota)) {
5106                 if (e2fsck_should_abort(ctx))
5107                         goto out;
5108                 pb.num_blocks += EXT2FS_B2C(ctx->fs, ea_block_quota.blocks);
5109         }
5110
5111         if (inlinedata_fs && (inode->i_flags & EXT4_INLINE_DATA_FL))
5112                 check_blocks_inline_data(ctx, pctx, &pb);
5113         else if (ext2fs_inode_has_valid_blocks2(fs, inode)) {
5114                 if (extent_fs && (inode->i_flags & EXT4_EXTENTS_FL))
5115                         check_blocks_extents(ctx, pctx, &pb);
5116                 else {
5117                         int flags;
5118                         /*
5119                          * If we've modified the inode, write it out before
5120                          * iterate() tries to use it.
5121                          */
5122                         if (dirty_inode) {
5123                                 e2fsck_write_inode(ctx, ino, inode,
5124                                                    "check_blocks");
5125                                 dirty_inode = 0;
5126                         }
5127                         flags = fs->flags;
5128                         fs->flags |= EXT2_FLAG_IGNORE_CSUM_ERRORS;
5129                         pctx->errcode = ext2fs_block_iterate3(fs, ino,
5130                                                 pb.is_dir ? BLOCK_FLAG_HOLE : 0,
5131                                                 block_buf, process_block, &pb);
5132                         /*
5133                          * We do not have uninitialized extents in non extent
5134                          * files.
5135                          */
5136                         pb.last_init_lblock = pb.last_block;
5137                         /*
5138                          * If iterate() changed a block mapping, we have to
5139                          * re-read the inode.  If we decide to clear the
5140                          * inode after clearing some stuff, we'll re-write the
5141                          * bad mappings into the inode!
5142                          */
5143                         if (pb.inode_modified)
5144                                 e2fsck_read_inode(ctx, ino, inode,
5145                                                   "check_blocks");
5146                         fs->flags = (flags & EXT2_FLAG_IGNORE_CSUM_ERRORS) |
5147                                     (fs->flags & ~EXT2_FLAG_IGNORE_CSUM_ERRORS);
5148
5149                         if (ctx->options & E2F_OPT_CONVERT_BMAP) {
5150 #ifdef DEBUG
5151                                 printf("bmap rebuild ino=%d\n", ino);
5152 #endif
5153                                 if (!LINUX_S_ISDIR(inode->i_mode) ||
5154                                     !e2fsck_dir_will_be_rehashed(ctx, ino))
5155                                         e2fsck_rebuild_extents_later(ctx, ino);
5156                         }
5157                 }
5158         }
5159         end_problem_latch(ctx, PR_LATCH_BLOCK);
5160         end_problem_latch(ctx, PR_LATCH_TOOBIG);
5161         if (e2fsck_should_abort(ctx))
5162                 goto out;
5163         if (pctx->errcode)
5164                 fix_problem(ctx, PR_1_BLOCK_ITERATE, pctx);
5165
5166         if (pb.fragmented && pb.num_blocks < fs->super->s_blocks_per_group) {
5167                 if (LINUX_S_ISDIR(inode->i_mode))
5168                         ctx->fs_fragmented_dir++;
5169                 else
5170                         ctx->fs_fragmented++;
5171         }
5172
5173         if (pb.clear) {
5174                 e2fsck_clear_inode(ctx, ino, inode, E2F_FLAG_RESTART,
5175                                    "check_blocks");
5176                 return;
5177         }
5178
5179         if (inode->i_flags & EXT2_INDEX_FL) {
5180                 if (handle_htree(ctx, pctx, ino, inode, block_buf)) {
5181                         inode->i_flags &= ~EXT2_INDEX_FL;
5182                         dirty_inode++;
5183                 } else {
5184                         e2fsck_add_dx_dir(ctx, ino, inode, pb.last_block+1);
5185                 }
5186         }
5187
5188         if (!pb.num_blocks && pb.is_dir &&
5189             !(inode->i_flags & EXT4_INLINE_DATA_FL)) {
5190                 /*
5191                  * The mode might be in-correct. Increasing the badness by
5192                  * small amount won't hurt much.
5193                  */
5194                 if (fix_problem(ctx, PR_1_ZERO_LENGTH_DIR, pctx)) {
5195                         e2fsck_clear_inode(ctx, ino, inode, 0, "check_blocks");
5196                         ctx->fs_directory_count--;
5197                         return;
5198                 }
5199         }
5200
5201         if (ino != quota_type2inum(PRJQUOTA, fs->super) &&
5202             (ino == EXT2_ROOT_INO || ino >= EXT2_FIRST_INODE(ctx->fs->super)) &&
5203             !(inode->i_flags & EXT4_EA_INODE_FL)) {
5204                 quota_data_add(ctx->qctx, (struct ext2_inode_large *) inode,
5205                                ino,
5206                                pb.num_blocks * EXT2_CLUSTER_SIZE(fs->super));
5207                 quota_data_inodes(ctx->qctx, (struct ext2_inode_large *) inode,
5208                                   ino, (ea_ibody_quota ?
5209                                         ea_ibody_quota->inodes : 0) +
5210                                                 ea_block_quota.inodes + 1);
5211         }
5212
5213         if (!ext2fs_has_feature_huge_file(fs->super) ||
5214             !(inode->i_flags & EXT4_HUGE_FILE_FL))
5215                 pb.num_blocks *= (fs->blocksize / 512);
5216         pb.num_blocks *= EXT2FS_CLUSTER_RATIO(fs);
5217 #if 0
5218         printf("inode %u, i_size = %u, last_block = %llu, i_blocks=%llu, num_blocks = %llu\n",
5219                ino, inode->i_size, (unsigned long long) pb.last_block,
5220                (unsigned long long) ext2fs_inode_i_blocks(fs, inode),
5221                (unsigned long long) pb.num_blocks);
5222 #endif
5223         size = EXT2_I_SIZE(inode);
5224         if (pb.is_dir) {
5225                 unsigned nblock = size >> EXT2_BLOCK_SIZE_BITS(fs->super);
5226                 if (inode->i_flags & EXT4_INLINE_DATA_FL) {
5227                         int flags;
5228                         size_t sz = 0;
5229                         errcode_t err;
5230
5231                         flags = ctx->fs->flags;
5232                         ctx->fs->flags |= EXT2_FLAG_IGNORE_CSUM_ERRORS;
5233                         err = ext2fs_inline_data_size(ctx->fs, pctx->ino,
5234                                                       &sz);
5235                         ctx->fs->flags = (flags &
5236                                           EXT2_FLAG_IGNORE_CSUM_ERRORS) |
5237                                          (ctx->fs->flags &
5238                                           ~EXT2_FLAG_IGNORE_CSUM_ERRORS);
5239                         if (err || sz != size) {
5240                                 bad_size = 7;
5241                                 pctx->num = sz;
5242                         }
5243                 } else if (size & (fs->blocksize - 1))
5244                         bad_size = 5;
5245                 else if (nblock > (pb.last_block + 1))
5246                         bad_size = 1;
5247                 else if (nblock < (pb.last_block + 1)) {
5248                         if (((pb.last_block + 1) - nblock) >
5249                             fs->super->s_prealloc_dir_blocks)
5250                                 bad_size = 2;
5251                 }
5252         } else {
5253                 if ((pb.last_init_lblock >= 0) &&
5254                     /* Do not allow initialized allocated blocks past i_size*/
5255                     (size < (__u64)pb.last_init_lblock * fs->blocksize) &&
5256                     !(inode->i_flags & EXT4_VERITY_FL))
5257                         bad_size = 3;
5258                 else if (!(extent_fs && (inode->i_flags & EXT4_EXTENTS_FL)) &&
5259                          size > ext2_max_sizes[fs->super->s_log_block_size])
5260                         /* too big for a direct/indirect-mapped file */
5261                         bad_size = 4;
5262                 else if ((extent_fs && (inode->i_flags & EXT4_EXTENTS_FL)) &&
5263                          size >
5264                          ((1ULL << (32 + EXT2_BLOCK_SIZE_BITS(fs->super))) - 1))
5265                         /* too big for an extent-based file - 32bit ee_block */
5266                         bad_size = 6;
5267         }
5268         /* i_size for symlinks is checked elsewhere */
5269         if (bad_size && !LINUX_S_ISLNK(inode->i_mode)) {
5270                 /* Did inline_data set pctx->num earlier? */
5271                 if (bad_size != 7)
5272                         pctx->num = (pb.last_block + 1) * fs->blocksize;
5273                 pctx->group = bad_size;
5274                 if (fix_problem(ctx, PR_1_BAD_I_SIZE, pctx)) {
5275                         ext2fs_inode_size_set(fs, inode, pctx->num);
5276                         if (EXT2_I_SIZE(inode) == 0 &&
5277                             (inode->i_flags & EXT4_INLINE_DATA_FL)) {
5278                                 memset(inode->i_block, 0,
5279                                        sizeof(inode->i_block));
5280                                 inode->i_flags &= ~EXT4_INLINE_DATA_FL;
5281                         }
5282                         dirty_inode++;
5283                 }
5284                 pctx->num = 0;
5285         }
5286         if (LINUX_S_ISREG(inode->i_mode) &&
5287             ext2fs_needs_large_file_feature(EXT2_I_SIZE(inode)))
5288                 ctx->large_files++;
5289         if ((fs->super->s_creator_os != EXT2_OS_HURD) &&
5290             ((pb.num_blocks != ext2fs_inode_i_blocks(fs, inode)) ||
5291              (ext2fs_has_feature_huge_file(fs->super) &&
5292               (inode->i_flags & EXT4_HUGE_FILE_FL) &&
5293               (inode->osd2.linux2.l_i_blocks_hi != 0)))) {
5294                 pctx->num = pb.num_blocks;
5295                 if (fix_problem(ctx, PR_1_BAD_I_BLOCKS, pctx)) {
5296                         inode->i_blocks = pb.num_blocks;
5297                         inode->osd2.linux2.l_i_blocks_hi = pb.num_blocks >> 32;
5298                         dirty_inode++;
5299                 }
5300                 pctx->num = 0;
5301         }
5302
5303         /*
5304          * The kernel gets mad if we ask it to allocate bigalloc clusters to
5305          * a block mapped file, so rebuild it as an extent file.  We can skip
5306          * symlinks because they're never rewritten.
5307          */
5308         if (ext2fs_has_feature_bigalloc(fs->super) &&
5309             (LINUX_S_ISREG(inode->i_mode) || LINUX_S_ISDIR(inode->i_mode)) &&
5310             ext2fs_inode_data_blocks2(fs, inode) > 0 &&
5311             (ino == EXT2_ROOT_INO || ino >= EXT2_FIRST_INO(fs->super)) &&
5312             !(inode->i_flags & (EXT4_EXTENTS_FL | EXT4_INLINE_DATA_FL)) &&
5313             fix_problem(ctx, PR_1_NO_BIGALLOC_BLOCKMAP_FILES, pctx)) {
5314                 pctx->errcode = e2fsck_rebuild_extents_later(ctx, ino);
5315                 if (pctx->errcode)
5316                         goto out;
5317         }
5318
5319         if (ctx->dirs_to_hash && pb.is_dir &&
5320             !(ctx->lost_and_found && ctx->lost_and_found == ino) &&
5321             !(inode->i_flags & EXT2_INDEX_FL) &&
5322             ((inode->i_size / fs->blocksize) >= 3))
5323                 e2fsck_rehash_dir_later(ctx, ino);
5324
5325 out:
5326         /* need restart if clearing bad inode after block processing */
5327         if (e2fsck_fix_bad_inode(ctx, pctx))
5328                 e2fsck_clear_inode(ctx, ino, inode, E2F_FLAG_RESTART,
5329                                    "check_blocks_bad");
5330         else if (dirty_inode)
5331                 e2fsck_write_inode(ctx, ino, inode, "check_blocks");
5332 }
5333
5334 #if 0
5335 /*
5336  * Helper function called by process block when an illegal block is
5337  * found.  It returns a description about why the block is illegal
5338  */
5339 static char *describe_illegal_block(ext2_filsys fs, blk64_t block)
5340 {
5341         blk64_t super;
5342         int     i;
5343         static char     problem[80];
5344
5345         super = fs->super->s_first_data_block;
5346         strcpy(problem, "PROGRAMMING ERROR: Unknown reason for illegal block");
5347         if (block < super) {
5348                 sprintf(problem, "< FIRSTBLOCK (%u)", super);
5349                 return(problem);
5350         } else if (block >= ext2fs_blocks_count(fs->super)) {
5351                 sprintf(problem, "> BLOCKS (%u)", ext2fs_blocks_count(fs->super));
5352                 return(problem);
5353         }
5354         for (i = 0; i < fs->group_desc_count; i++) {
5355                 if (block == super) {
5356                         sprintf(problem, "is the superblock in group %d", i);
5357                         break;
5358                 }
5359                 if (block > super &&
5360                     block <= (super + fs->desc_blocks)) {
5361                         sprintf(problem, "is in the group descriptors "
5362                                 "of group %d", i);
5363                         break;
5364                 }
5365                 if (block == ext2fs_block_bitmap_loc(fs, i)) {
5366                         sprintf(problem, "is the block bitmap of group %d", i);
5367                         break;
5368                 }
5369                 if (block == ext2fs_inode_bitmap_loc(fs, i)) {
5370                         sprintf(problem, "is the inode bitmap of group %d", i);
5371                         break;
5372                 }
5373                 if (block >= ext2fs_inode_table_loc(fs, i) &&
5374                     (block < ext2fs_inode_table_loc(fs, i)
5375                      + fs->inode_blocks_per_group)) {
5376                         sprintf(problem, "is in the inode table of group %d",
5377                                 i);
5378                         break;
5379                 }
5380                 super += fs->super->s_blocks_per_group;
5381         }
5382         return(problem);
5383 }
5384 #endif
5385
5386 /*
5387  * This is a helper function for check_blocks().
5388  */
5389 static int process_block(ext2_filsys fs,
5390                   blk64_t       *block_nr,
5391                   e2_blkcnt_t blockcnt,
5392                   blk64_t ref_block EXT2FS_ATTR((unused)),
5393                   int ref_offset EXT2FS_ATTR((unused)),
5394                   void *priv_data)
5395 {
5396         struct process_block_struct *p;
5397         struct problem_context *pctx;
5398         blk64_t blk = *block_nr;
5399         int     ret_code = 0;
5400         problem_t       problem = 0;
5401         e2fsck_t        ctx;
5402
5403         p = (struct process_block_struct *) priv_data;
5404         pctx = p->pctx;
5405         ctx = p->ctx;
5406
5407         /*
5408          * For a directory, add logical block zero for processing even if it's
5409          * not mapped or we'll be perennially stuck with broken "." and ".."
5410          * entries.
5411          */
5412         if (p->is_dir && blockcnt == 0 && blk == 0) {
5413                 pctx->errcode = ext2fs_add_dir_block2(fs->dblist, p->ino, 0, 0);
5414                 if (pctx->errcode) {
5415                         pctx->blk = blk;
5416                         pctx->num = blockcnt;
5417                         goto failed_add_dir_block;
5418                 }
5419                 p->last_db_block++;
5420         }
5421
5422         if (blk == 0)
5423                 return 0;
5424
5425 #if 0
5426         printf("Process_block, inode %lu, block %u, #%d\n", p->ino, blk,
5427                blockcnt);
5428 #endif
5429
5430         /*
5431          * Simplistic fragmentation check.  We merely require that the
5432          * file be contiguous.  (Which can never be true for really
5433          * big files that are greater than a block group.)
5434          */
5435         if (p->previous_block && p->ino != EXT2_RESIZE_INO) {
5436                 if (p->previous_block+1 != blk) {
5437                         if (ctx->options & E2F_OPT_FRAGCHECK) {
5438                                 char type = '?';
5439
5440                                 if (p->is_dir)
5441                                         type = 'd';
5442                                 else if (p->is_reg)
5443                                         type = 'f';
5444
5445                                 printf(_("%6lu(%c): expecting %6lu "
5446                                          "got phys %6lu (blkcnt %lld)\n"),
5447                                        (unsigned long) pctx->ino, type,
5448                                        (unsigned long) p->previous_block+1,
5449                                        (unsigned long) blk,
5450                                        (long long) blockcnt);
5451                         }
5452                         p->fragmented = 1;
5453                 }
5454         }
5455
5456         if (p->is_dir && !ext2fs_has_feature_largedir(fs->super) &&
5457             !pctx->inode->i_size_high &&
5458             blockcnt > (1 << (21 - fs->super->s_log_block_size)))
5459                 problem = PR_1_TOOBIG_DIR;
5460         if (p->is_dir && p->num_blocks + 1 >= p->max_blocks)
5461                 problem = PR_1_TOOBIG_DIR;
5462         if (p->is_reg && p->num_blocks + 1 >= p->max_blocks)
5463                 problem = PR_1_TOOBIG_REG;
5464         if (!p->is_dir && !p->is_reg && blockcnt > 0)
5465                 problem = PR_1_TOOBIG_SYMLINK;
5466
5467         if (blk < fs->super->s_first_data_block ||
5468             blk >= ext2fs_blocks_count(fs->super))
5469                 problem = PR_1_ILLEGAL_BLOCK_NUM;
5470
5471         /*
5472          * If this IND/DIND/TIND block is squatting atop some critical metadata
5473          * (group descriptors, superblock, bitmap, inode table), any write to
5474          * "fix" mapping problems will destroy the metadata.  We'll let pass 1b
5475          * fix that and restart fsck.
5476          */
5477         if (blockcnt < 0 &&
5478             p->ino != EXT2_RESIZE_INO &&
5479             blk < ctx->fs->super->s_blocks_count &&
5480             ext2fs_test_block_bitmap2(ctx->block_metadata_map, blk)) {
5481                 pctx->blk = blk;
5482                 fix_problem_bad(ctx, PR_1_CRITICAL_METADATA_COLLISION, pctx, 2);
5483                 if ((ctx->options & E2F_OPT_NO) == 0)
5484                         ctx->flags |= E2F_FLAG_RESTART_LATER;
5485         }
5486
5487         if (problem) {
5488                 p->num_illegal_blocks++;
5489                 /*
5490                  * A bit of subterfuge here -- we're trying to fix a block
5491                  * mapping, but the IND/DIND/TIND block could have collided
5492                  * with some critical metadata.  So, fix the in-core mapping so
5493                  * iterate won't go insane, but return 0 instead of
5494                  * BLOCK_CHANGED so that it won't write the remapping out to
5495                  * our multiply linked block.
5496                  *
5497                  * Even if we previously determined that an *IND block
5498                  * conflicts with critical metadata, we must still try to
5499                  * iterate the *IND block as if it is an *IND block to find and
5500                  * mark the blocks it points to.  Better to be overly cautious
5501                  * with the used_blocks map so that we don't move the *IND
5502                  * block to a block that's really in use!
5503                  */
5504                 if (p->ino != EXT2_RESIZE_INO &&
5505                     ref_block != 0 &&
5506                     ext2fs_test_block_bitmap2(ctx->block_metadata_map,
5507                                               ref_block)) {
5508                         *block_nr = 0;
5509                         return 0;
5510                 }
5511                 if (!p->suppress && (p->num_illegal_blocks % 12) == 0) {
5512                         if (fix_problem(ctx, PR_1_TOO_MANY_BAD_BLOCKS, pctx)) {
5513                                 p->clear = 1;
5514                                 return BLOCK_ABORT;
5515                         }
5516                         if (fix_problem(ctx, PR_1_SUPPRESS_MESSAGES, pctx)) {
5517                                 p->suppress = 1;
5518                                 set_latch_flags(PR_LATCH_BLOCK,
5519                                                 PRL_SUPPRESS, 0);
5520                         }
5521                 }
5522                 pctx->blk = blk;
5523                 pctx->blkcount = blockcnt;
5524                 if (fix_problem(ctx, problem, pctx)) {
5525                         blk = *block_nr = 0;
5526                         ret_code = BLOCK_CHANGED;
5527                         p->inode_modified = 1;
5528                         /*
5529                          * If the directory block is too big and is beyond the
5530                          * end of the FS, don't bother trying to add it for
5531                          * processing -- the kernel would never have created a
5532                          * directory this large, and we risk an ENOMEM abort.
5533                          * In any case, the toobig handler for extent-based
5534                          * directories also doesn't feed toobig blocks to
5535                          * pass 2.
5536                          */
5537                         if (problem == PR_1_TOOBIG_DIR)
5538                                 return ret_code;
5539                         goto mark_dir;
5540                 } else
5541                         return 0;
5542         }
5543
5544         if (p->ino == EXT2_RESIZE_INO) {
5545                 /*
5546                  * The resize inode has already be sanity checked
5547                  * during pass #0 (the superblock checks).  All we
5548                  * have to do is mark the double indirect block as
5549                  * being in use; all of the other blocks are handled
5550                  * by mark_table_blocks()).
5551                  */
5552                 if (blockcnt == BLOCK_COUNT_DIND)
5553                         mark_block_used(ctx, blk);
5554                 p->num_blocks++;
5555         } else if (!(ctx->fs->cluster_ratio_bits &&
5556                      p->previous_block &&
5557                      (EXT2FS_B2C(ctx->fs, blk) ==
5558                       EXT2FS_B2C(ctx->fs, p->previous_block)) &&
5559                      (blk & EXT2FS_CLUSTER_MASK(ctx->fs)) ==
5560                      ((unsigned) blockcnt & EXT2FS_CLUSTER_MASK(ctx->fs)))) {
5561                 mark_block_used(ctx, blk);
5562                 p->num_blocks++;
5563         } else if (has_unaligned_cluster_map(ctx, p->previous_block,
5564                                              p->last_block, blk, blockcnt)) {
5565                 pctx->blk = blockcnt;
5566                 pctx->blk2 = blk;
5567                 fix_problem(ctx, PR_1_MISALIGNED_CLUSTER, pctx);
5568                 mark_block_used(ctx, blk);
5569                 mark_block_used(ctx, blk);
5570         }
5571         if (blockcnt >= 0)
5572                 p->last_block = blockcnt;
5573         p->previous_block = blk;
5574 mark_dir:
5575         if (p->is_dir && (blockcnt >= 0)) {
5576                 while (++p->last_db_block < blockcnt) {
5577                         pctx->errcode = ext2fs_add_dir_block2(fs->dblist,
5578                                                               p->ino, 0,
5579                                                               p->last_db_block);
5580                         if (pctx->errcode) {
5581                                 pctx->blk = 0;
5582                                 pctx->num = p->last_db_block;
5583                                 goto failed_add_dir_block;
5584                         }
5585                 }
5586                 pctx->errcode = ext2fs_add_dir_block2(fs->dblist, p->ino,
5587                                                       blk, blockcnt);
5588                 if (pctx->errcode) {
5589                         pctx->blk = blk;
5590                         pctx->num = blockcnt;
5591                 failed_add_dir_block:
5592                         fix_problem(ctx, PR_1_ADD_DBLOCK, pctx);
5593                         /* Should never get here */
5594                         ctx->flags |= E2F_FLAG_ABORT;
5595                         return BLOCK_ABORT;
5596                 }
5597         }
5598         return ret_code;
5599 }
5600
5601 static int process_bad_block(ext2_filsys fs,
5602                       blk64_t *block_nr,
5603                       e2_blkcnt_t blockcnt,
5604                       blk64_t ref_block EXT2FS_ATTR((unused)),
5605                       int ref_offset EXT2FS_ATTR((unused)),
5606                       void *priv_data)
5607 {
5608         struct process_block_struct *p;
5609         blk64_t         blk = *block_nr;
5610         blk64_t         first_block;
5611         dgrp_t          i;
5612         struct problem_context *pctx;
5613         e2fsck_t        ctx;
5614
5615         if (!blk)
5616                 return 0;
5617
5618         p = (struct process_block_struct *) priv_data;
5619         ctx = p->ctx;
5620         pctx = p->pctx;
5621
5622         pctx->ino = EXT2_BAD_INO;
5623         pctx->blk = blk;
5624         pctx->blkcount = blockcnt;
5625
5626         if ((blk < fs->super->s_first_data_block) ||
5627             (blk >= ext2fs_blocks_count(fs->super))) {
5628                 if (fix_problem(ctx, PR_1_BB_ILLEGAL_BLOCK_NUM, pctx)) {
5629                         *block_nr = 0;
5630                         return BLOCK_CHANGED;
5631                 } else
5632                         return 0;
5633         }
5634
5635         if (blockcnt < 0) {
5636                 if (ext2fs_test_block_bitmap2(p->fs_meta_blocks, blk)) {
5637                         p->bbcheck = 1;
5638                         if (fix_problem(ctx, PR_1_BB_FS_BLOCK, pctx)) {
5639                                 *block_nr = 0;
5640                                 return BLOCK_CHANGED;
5641                         }
5642                 } else if (is_blocks_used(ctx, blk, 1)) {
5643                         p->bbcheck = 1;
5644                         if (fix_problem(ctx, PR_1_BBINODE_BAD_METABLOCK,
5645                                         pctx)) {
5646                                 *block_nr = 0;
5647                                 return BLOCK_CHANGED;
5648                         }
5649                         if (e2fsck_should_abort(ctx))
5650                                 return BLOCK_ABORT;
5651                 } else {
5652                         mark_block_used(ctx, blk);
5653                 }
5654                 return 0;
5655         }
5656 #if 0
5657         printf ("DEBUG: Marking %u as bad.\n", blk);
5658 #endif
5659         ctx->fs_badblocks_count++;
5660         /*
5661          * If the block is not used, then mark it as used and return.
5662          * If it is already marked as found, this must mean that
5663          * there's an overlap between the filesystem table blocks
5664          * (bitmaps and inode table) and the bad block list.
5665          */
5666         if (!is_blocks_used(ctx, blk, 1)) {
5667                 ext2fs_mark_block_bitmap2(ctx->block_found_map, blk);
5668                 return 0;
5669         }
5670         /*
5671          * Try to find the where the filesystem block was used...
5672          */
5673         first_block = fs->super->s_first_data_block;
5674
5675         for (i = 0; i < fs->group_desc_count; i++ ) {
5676                 pctx->group = i;
5677                 pctx->blk = blk;
5678                 if (!ext2fs_bg_has_super(fs, i))
5679                         goto skip_super;
5680                 if (blk == first_block) {
5681                         if (i == 0) {
5682                                 if (fix_problem(ctx,
5683                                                 PR_1_BAD_PRIMARY_SUPERBLOCK,
5684                                                 pctx)) {
5685                                         *block_nr = 0;
5686                                         return BLOCK_CHANGED;
5687                                 }
5688                                 return 0;
5689                         }
5690                         fix_problem(ctx, PR_1_BAD_SUPERBLOCK, pctx);
5691                         return 0;
5692                 }
5693                 if ((blk > first_block) &&
5694                     (blk <= first_block + fs->desc_blocks)) {
5695                         if (i == 0) {
5696                                 pctx->blk = *block_nr;
5697                                 if (fix_problem(ctx,
5698                         PR_1_BAD_PRIMARY_GROUP_DESCRIPTOR, pctx)) {
5699                                         *block_nr = 0;
5700                                         return BLOCK_CHANGED;
5701                                 }
5702                                 return 0;
5703                         }
5704                         fix_problem(ctx, PR_1_BAD_GROUP_DESCRIPTORS, pctx);
5705                         return 0;
5706                 }
5707         skip_super:
5708                 if (blk == ext2fs_block_bitmap_loc(fs, i)) {
5709                         if (fix_problem(ctx, PR_1_BB_BAD_BLOCK, pctx)) {
5710                                 ctx->invalid_block_bitmap_flag[i]++;
5711                                 ctx->invalid_bitmaps++;
5712                         }
5713                         return 0;
5714                 }
5715                 if (blk == ext2fs_inode_bitmap_loc(fs, i)) {
5716                         if (fix_problem(ctx, PR_1_IB_BAD_BLOCK, pctx)) {
5717                                 ctx->invalid_inode_bitmap_flag[i]++;
5718                                 ctx->invalid_bitmaps++;
5719                         }
5720                         return 0;
5721                 }
5722                 if ((blk >= ext2fs_inode_table_loc(fs, i)) &&
5723                     (blk < (ext2fs_inode_table_loc(fs, i) +
5724                             fs->inode_blocks_per_group))) {
5725                         /*
5726                          * If there are bad blocks in the inode table,
5727                          * the inode scan code will try to do
5728                          * something reasonable automatically.
5729                          */
5730                         return 0;
5731                 }
5732                 first_block += fs->super->s_blocks_per_group;
5733         }
5734         /*
5735          * If we've gotten to this point, then the only
5736          * possibility is that the bad block inode meta data
5737          * is using a bad block.
5738          */
5739         if ((blk == p->inode->i_block[EXT2_IND_BLOCK]) ||
5740             (blk == p->inode->i_block[EXT2_DIND_BLOCK]) ||
5741             (blk == p->inode->i_block[EXT2_TIND_BLOCK])) {
5742                 p->bbcheck = 1;
5743                 if (fix_problem(ctx, PR_1_BBINODE_BAD_METABLOCK, pctx)) {
5744                         *block_nr = 0;
5745                         return BLOCK_CHANGED;
5746                 }
5747                 if (e2fsck_should_abort(ctx))
5748                         return BLOCK_ABORT;
5749                 return 0;
5750         }
5751
5752         pctx->group = -1;
5753
5754         /* Warn user that the block wasn't claimed */
5755         fix_problem(ctx, PR_1_PROGERR_CLAIMED_BLOCK, pctx);
5756
5757         return 0;
5758 }
5759
5760 static void new_table_block(e2fsck_t ctx, blk64_t first_block, dgrp_t group,
5761                             const char *name, int num, blk64_t *new_block)
5762 {
5763         ext2_filsys fs = ctx->fs;
5764         dgrp_t          last_grp;
5765         blk64_t         old_block = *new_block;
5766         blk64_t         last_block;
5767         dgrp_t          flexbg;
5768         unsigned        flexbg_size;
5769         int             i, is_flexbg;
5770         char            *buf;
5771         struct problem_context  pctx;
5772
5773         clear_problem_context(&pctx);
5774
5775         pctx.group = group;
5776         pctx.blk = old_block;
5777         pctx.str = name;
5778
5779         /*
5780          * For flex_bg filesystems, first try to allocate the metadata
5781          * within the flex_bg, and if that fails then try finding the
5782          * space anywhere in the filesystem.
5783          */
5784         is_flexbg = ext2fs_has_feature_flex_bg(fs->super);
5785         if (is_flexbg) {
5786                 flexbg_size = 1 << fs->super->s_log_groups_per_flex;
5787                 flexbg = group / flexbg_size;
5788                 first_block = ext2fs_group_first_block2(fs,
5789                                                         flexbg_size * flexbg);
5790                 last_grp = group | (flexbg_size - 1);
5791                 if (last_grp >= fs->group_desc_count)
5792                         last_grp = fs->group_desc_count - 1;
5793                 last_block = ext2fs_group_last_block2(fs, last_grp);
5794         } else
5795                 last_block = ext2fs_group_last_block2(fs, group);
5796         pctx.errcode = ext2fs_get_free_blocks2(fs, first_block, last_block,
5797                                                num, ctx->block_found_map,
5798                                                new_block);
5799         if (is_flexbg && (pctx.errcode == EXT2_ET_BLOCK_ALLOC_FAIL))
5800                 pctx.errcode = ext2fs_get_free_blocks2(fs,
5801                                 fs->super->s_first_data_block,
5802                                 ext2fs_blocks_count(fs->super),
5803                                 num, ctx->block_found_map, new_block);
5804         if (pctx.errcode) {
5805                 pctx.num = num;
5806                 fix_problem(ctx, PR_1_RELOC_BLOCK_ALLOCATE, &pctx);
5807                 ext2fs_unmark_valid(fs);
5808                 ctx->flags |= E2F_FLAG_ABORT;
5809                 return;
5810         }
5811         pctx.errcode = ext2fs_get_mem(fs->blocksize, &buf);
5812         if (pctx.errcode) {
5813                 fix_problem(ctx, PR_1_RELOC_MEMORY_ALLOCATE, &pctx);
5814                 ext2fs_unmark_valid(fs);
5815                 ctx->flags |= E2F_FLAG_ABORT;
5816                 return;
5817         }
5818         ext2fs_mark_super_dirty(fs);
5819         fs->flags &= ~EXT2_FLAG_MASTER_SB_ONLY;
5820         pctx.blk2 = *new_block;
5821         fix_problem(ctx, (old_block ? PR_1_RELOC_FROM_TO :
5822                           PR_1_RELOC_TO), &pctx);
5823         pctx.blk2 = 0;
5824         for (i = 0; i < num; i++) {
5825                 pctx.blk = i;
5826                 ext2fs_mark_block_bitmap2(ctx->block_found_map, (*new_block)+i);
5827                 if (old_block) {
5828                         pctx.errcode = io_channel_read_blk64(fs->io,
5829                                    old_block + i, 1, buf);
5830                         if (pctx.errcode)
5831                                 fix_problem(ctx, PR_1_RELOC_READ_ERR, &pctx);
5832                         pctx.blk = (*new_block) + i;
5833                         pctx.errcode = io_channel_write_blk64(fs->io, pctx.blk,
5834                                                               1, buf);
5835                 } else {
5836                         pctx.blk = (*new_block) + i;
5837                         pctx.errcode = ext2fs_zero_blocks2(fs, pctx.blk, 1,
5838                                                            NULL, NULL);
5839                 }
5840
5841                 if (pctx.errcode)
5842                         fix_problem(ctx, PR_1_RELOC_WRITE_ERR, &pctx);
5843         }
5844         ext2fs_free_mem(&buf);
5845 }
5846
5847 /*
5848  * This routine gets called at the end of pass 1 if bad blocks are
5849  * detected in the superblock, group descriptors, inode_bitmaps, or
5850  * block bitmaps.  At this point, all of the blocks have been mapped
5851  * out, so we can try to allocate new block(s) to replace the bad
5852  * blocks.
5853  */
5854 static void handle_fs_bad_blocks(e2fsck_t ctx)
5855 {
5856         ext2_filsys fs = ctx->fs;
5857         dgrp_t          i;
5858         blk64_t         first_block;
5859         blk64_t         new_blk;
5860
5861         for (i = 0; i < fs->group_desc_count; i++) {
5862                 first_block = ext2fs_group_first_block2(fs, i);
5863
5864                 if (ctx->invalid_block_bitmap_flag[i]) {
5865                         new_blk = ext2fs_block_bitmap_loc(fs, i);
5866                         new_table_block(ctx, first_block, i, _("block bitmap"),
5867                                         1, &new_blk);
5868                         ext2fs_block_bitmap_loc_set(fs, i, new_blk);
5869                 }
5870                 if (ctx->invalid_inode_bitmap_flag[i]) {
5871                         new_blk = ext2fs_inode_bitmap_loc(fs, i);
5872                         new_table_block(ctx, first_block, i, _("inode bitmap"),
5873                                         1, &new_blk);
5874                         ext2fs_inode_bitmap_loc_set(fs, i, new_blk);
5875                 }
5876                 if (ctx->invalid_inode_table_flag[i]) {
5877                         new_blk = ext2fs_inode_table_loc(fs, i);
5878                         new_table_block(ctx, first_block, i, _("inode table"),
5879                                         fs->inode_blocks_per_group,
5880                                         &new_blk);
5881                         ext2fs_inode_table_loc_set(fs, i, new_blk);
5882                         ctx->flags |= E2F_FLAG_RESTART;
5883                 }
5884         }
5885         ctx->invalid_bitmaps = 0;
5886 }
5887
5888 /*
5889  * This routine marks all blocks which are used by the superblock,
5890  * group descriptors, inode bitmaps, and block bitmaps.
5891  */
5892 static void mark_table_blocks(e2fsck_t ctx)
5893 {
5894         ext2_filsys fs = ctx->fs;
5895         blk64_t b;
5896         dgrp_t  i;
5897         unsigned int    j;
5898         struct problem_context pctx;
5899
5900         clear_problem_context(&pctx);
5901
5902         for (i = 0; i < fs->group_desc_count; i++) {
5903                 pctx.group = i;
5904
5905                 ext2fs_reserve_super_and_bgd(fs, i, ctx->block_found_map);
5906                 ext2fs_reserve_super_and_bgd(fs, i, ctx->block_metadata_map);
5907
5908                 /*
5909                  * Mark the blocks used for the inode table
5910                  */
5911                 if (ext2fs_inode_table_loc(fs, i)) {
5912                         for (j = 0, b = ext2fs_inode_table_loc(fs, i);
5913                              j < fs->inode_blocks_per_group;
5914                              j++, b++) {
5915                                 if (ext2fs_test_block_bitmap2(ctx->block_found_map,
5916                                                              b)) {
5917                                         pctx.blk = b;
5918                                         if (!ctx->invalid_inode_table_flag[i] &&
5919                                             fix_problem(ctx,
5920                                                 PR_1_ITABLE_CONFLICT, &pctx)) {
5921                                                 ctx->invalid_inode_table_flag[i]++;
5922                                                 ctx->invalid_bitmaps++;
5923                                         }
5924                                 } else {
5925                                     ext2fs_mark_block_bitmap2(
5926                                                 ctx->block_found_map, b);
5927                                     ext2fs_mark_block_bitmap2(
5928                                                 ctx->block_metadata_map, b);
5929                                 }
5930                         }
5931                 }
5932
5933                 /*
5934                  * Mark block used for the block bitmap
5935                  */
5936                 if (ext2fs_block_bitmap_loc(fs, i)) {
5937                         if (ext2fs_test_block_bitmap2(ctx->block_found_map,
5938                                      ext2fs_block_bitmap_loc(fs, i))) {
5939                                 pctx.blk = ext2fs_block_bitmap_loc(fs, i);
5940                                 if (fix_problem(ctx, PR_1_BB_CONFLICT, &pctx)) {
5941                                         ctx->invalid_block_bitmap_flag[i]++;
5942                                         ctx->invalid_bitmaps++;
5943                                 }
5944                         } else {
5945                             ext2fs_mark_block_bitmap2(ctx->block_found_map,
5946                                      ext2fs_block_bitmap_loc(fs, i));
5947                             ext2fs_mark_block_bitmap2(ctx->block_metadata_map,
5948                                      ext2fs_block_bitmap_loc(fs, i));
5949                         }
5950                 }
5951                 /*
5952                  * Mark block used for the inode bitmap
5953                  */
5954                 if (ext2fs_inode_bitmap_loc(fs, i)) {
5955                         if (ext2fs_test_block_bitmap2(ctx->block_found_map,
5956                                      ext2fs_inode_bitmap_loc(fs, i))) {
5957                                 pctx.blk = ext2fs_inode_bitmap_loc(fs, i);
5958                                 if (fix_problem(ctx, PR_1_IB_CONFLICT, &pctx)) {
5959                                         ctx->invalid_inode_bitmap_flag[i]++;
5960                                         ctx->invalid_bitmaps++;
5961                                 }
5962                         } else {
5963                             ext2fs_mark_block_bitmap2(ctx->block_metadata_map,
5964                                      ext2fs_inode_bitmap_loc(fs, i));
5965                             ext2fs_mark_block_bitmap2(ctx->block_found_map,
5966                                      ext2fs_inode_bitmap_loc(fs, i));
5967                         }
5968                 }
5969         }
5970 }
5971
5972 /*
5973  * These subroutines short circuits ext2fs_get_blocks and
5974  * ext2fs_check_directory; we use them since we already have the inode
5975  * structure, so there's no point in letting the ext2fs library read
5976  * the inode again.
5977  */
5978 static errcode_t pass1_get_blocks(ext2_filsys fs, ext2_ino_t ino,
5979                                   blk_t *blocks)
5980 {
5981         e2fsck_t ctx = (e2fsck_t) fs->priv_data;
5982         int     i;
5983
5984         if ((ino != ctx->stashed_ino) || !ctx->stashed_inode)
5985                 return EXT2_ET_CALLBACK_NOTHANDLED;
5986
5987         for (i=0; i < EXT2_N_BLOCKS; i++)
5988                 blocks[i] = ctx->stashed_inode->i_block[i];
5989         return 0;
5990 }
5991
5992 static errcode_t pass1_read_inode(ext2_filsys fs, ext2_ino_t ino,
5993                                   struct ext2_inode *inode)
5994 {
5995         e2fsck_t ctx = (e2fsck_t) fs->priv_data;
5996
5997         if ((ino != ctx->stashed_ino) || !ctx->stashed_inode)
5998                 return EXT2_ET_CALLBACK_NOTHANDLED;
5999         *inode = *ctx->stashed_inode;
6000         return 0;
6001 }
6002
6003 static errcode_t pass1_write_inode(ext2_filsys fs, ext2_ino_t ino,
6004                             struct ext2_inode *inode)
6005 {
6006         e2fsck_t ctx = (e2fsck_t) fs->priv_data;
6007
6008         if ((ino == ctx->stashed_ino) && ctx->stashed_inode &&
6009                 (inode != ctx->stashed_inode))
6010                 *ctx->stashed_inode = *inode;
6011         return EXT2_ET_CALLBACK_NOTHANDLED;
6012 }
6013
6014 static errcode_t pass1_check_directory(ext2_filsys fs, ext2_ino_t ino)
6015 {
6016         e2fsck_t ctx = (e2fsck_t) fs->priv_data;
6017
6018         if ((ino != ctx->stashed_ino) || !ctx->stashed_inode)
6019                 return EXT2_ET_CALLBACK_NOTHANDLED;
6020
6021         if (!LINUX_S_ISDIR(ctx->stashed_inode->i_mode))
6022                 return EXT2_ET_NO_DIRECTORY;
6023         return 0;
6024 }
6025
6026 static errcode_t e2fsck_get_alloc_block(ext2_filsys fs, blk64_t goal,
6027                                         blk64_t *ret)
6028 {
6029         e2fsck_t ctx = (e2fsck_t) fs->priv_data;
6030         errcode_t       retval;
6031         blk64_t         new_block;
6032
6033         if (ctx->block_found_map) {
6034                 retval = ext2fs_new_block2(fs, goal, ctx->block_found_map,
6035                                            &new_block);
6036                 if (retval)
6037                         return retval;
6038                 if (fs->block_map) {
6039                         ext2fs_mark_block_bitmap2(fs->block_map, new_block);
6040                         ext2fs_mark_bb_dirty(fs);
6041                 }
6042         } else {
6043                 if (!fs->block_map) {
6044                         retval = ext2fs_read_block_bitmap(fs);
6045                         if (retval)
6046                                 return retval;
6047                 }
6048
6049                 retval = ext2fs_new_block2(fs, goal, fs->block_map, &new_block);
6050                 if (retval)
6051                         return retval;
6052         }
6053
6054         *ret = new_block;
6055         return (0);
6056 }
6057
6058 static errcode_t e2fsck_new_range(ext2_filsys fs, int flags, blk64_t goal,
6059                                   blk64_t len, blk64_t *pblk, blk64_t *plen)
6060 {
6061         e2fsck_t ctx = (e2fsck_t) fs->priv_data;
6062         errcode_t       retval;
6063
6064         if (ctx->block_found_map)
6065                 return ext2fs_new_range(fs, flags, goal, len,
6066                                         ctx->block_found_map, pblk, plen);
6067
6068         if (!fs->block_map) {
6069                 retval = ext2fs_read_block_bitmap(fs);
6070                 if (retval)
6071                         return retval;
6072         }
6073
6074         return ext2fs_new_range(fs, flags, goal, len, fs->block_map,
6075                                 pblk, plen);
6076 }
6077
6078 static void e2fsck_block_alloc_stats(ext2_filsys fs, blk64_t blk, int inuse)
6079 {
6080         e2fsck_t ctx = (e2fsck_t) fs->priv_data;
6081
6082         /* Never free a critical metadata block */
6083         if (ctx->block_found_map &&
6084             ctx->block_metadata_map &&
6085             inuse < 0 &&
6086             ext2fs_test_block_bitmap2(ctx->block_metadata_map, blk))
6087                 return;
6088
6089         if (ctx->block_found_map) {
6090                 if (inuse > 0)
6091                         ext2fs_mark_block_bitmap2(ctx->block_found_map, blk);
6092                 else
6093                         ext2fs_unmark_block_bitmap2(ctx->block_found_map, blk);
6094         }
6095 }
6096
6097 static void e2fsck_block_alloc_stats_range(ext2_filsys fs, blk64_t blk,
6098                                            blk_t num, int inuse)
6099 {
6100         e2fsck_t ctx = (e2fsck_t) fs->priv_data;
6101
6102         /* Never free a critical metadata block */
6103         if (ctx->block_found_map &&
6104             ctx->block_metadata_map &&
6105             inuse < 0 &&
6106             ext2fs_test_block_bitmap_range2(ctx->block_metadata_map, blk, num))
6107                 return;
6108
6109         if (ctx->block_found_map) {
6110                 if (inuse > 0)
6111                         ext2fs_mark_block_bitmap_range2(ctx->block_found_map,
6112                                                         blk, num);
6113                 else
6114                         ext2fs_unmark_block_bitmap_range2(ctx->block_found_map,
6115                                                         blk, num);
6116         }
6117 }
6118
6119 void e2fsck_use_inode_shortcuts(e2fsck_t ctx, int use_shortcuts)
6120 {
6121         ext2_filsys fs = ctx->fs;
6122
6123         if (use_shortcuts) {
6124                 fs->get_blocks = pass1_get_blocks;
6125                 fs->check_directory = pass1_check_directory;
6126                 fs->read_inode = pass1_read_inode;
6127                 fs->write_inode = pass1_write_inode;
6128                 ctx->stashed_ino = 0;
6129         } else {
6130                 fs->get_blocks = 0;
6131                 fs->check_directory = 0;
6132                 fs->read_inode = 0;
6133                 fs->write_inode = 0;
6134         }
6135 }
6136
6137 void e2fsck_intercept_block_allocations(e2fsck_t ctx)
6138 {
6139         ext2fs_set_alloc_block_callback(ctx->fs, e2fsck_get_alloc_block, 0);
6140         ext2fs_set_block_alloc_stats_callback(ctx->fs,
6141                                                 e2fsck_block_alloc_stats, 0);
6142         ext2fs_set_new_range_callback(ctx->fs, e2fsck_new_range, NULL);
6143         ext2fs_set_block_alloc_stats_range_callback(ctx->fs,
6144                                         e2fsck_block_alloc_stats_range, NULL);
6145 }