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