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