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