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