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