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