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