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