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