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