• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * pass2.c --- check directory structure
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 2 of e2fsck iterates through all active directory inodes, and
12  * applies to following tests to each directory entry in the directory
13  * blocks in the inodes:
14  *
15  *	- The length of the directory entry (rec_len) should be at
16  * 		least 8 bytes, and no more than the remaining space
17  * 		left in the directory block.
18  * 	- The length of the name in the directory entry (name_len)
19  * 		should be less than (rec_len - 8).
20  *	- The inode number in the directory entry should be within
21  * 		legal bounds.
22  * 	- The inode number should refer to a in-use inode.
23  *	- The first entry should be '.', and its inode should be
24  * 		the inode of the directory.
25  * 	- The second entry should be '..'.
26  *
27  * To minimize disk seek time, the directory blocks are processed in
28  * sorted order of block numbers.
29  *
30  * Pass 2 also collects the following information:
31  * 	- The inode numbers of the subdirectories for each directory.
32  *
33  * Pass 2 relies on the following information from previous passes:
34  * 	- The directory information collected in pass 1.
35  * 	- The inode_used_map bitmap
36  * 	- The inode_bad_map bitmap
37  * 	- The inode_dir_map bitmap
38  * 	- The encrypted_file_info
39  *	- The inode_casefold_map bitmap
40  *
41  * Pass 2 frees the following data structures
42  * 	- The inode_bad_map bitmap
43  * 	- The inode_reg_map bitmap
44  * 	- The encrypted_file_info
45  *	- The inode_casefold_map bitmap
46  */
47 
48 #define _GNU_SOURCE 1 /* get strnlen() */
49 #include "config.h"
50 #include <string.h>
51 
52 #include "e2fsck.h"
53 #include "problem.h"
54 #include "support/dict.h"
55 
56 #ifdef NO_INLINE_FUNCS
57 #define _INLINE_
58 #else
59 #define _INLINE_ inline
60 #endif
61 
62 /* #define DX_DEBUG */
63 
64 /*
65  * Keeps track of how many times an inode is referenced.
66  */
67 static void deallocate_inode(e2fsck_t ctx, ext2_ino_t ino, char* block_buf);
68 static int check_dir_block2(ext2_filsys fs,
69 			   struct ext2_db_entry2 *dir_blocks_info,
70 			   void *priv_data);
71 static int check_dir_block(ext2_filsys fs,
72 			   struct ext2_db_entry2 *dir_blocks_info,
73 			   void *priv_data);
74 static int allocate_dir_block(e2fsck_t ctx,
75 			      struct ext2_db_entry2 *dir_blocks_info,
76 			      char *buf, struct problem_context *pctx);
77 static void clear_htree(e2fsck_t ctx, ext2_ino_t ino);
78 static short htree_depth(struct dx_dir_info *dx_dir,
79 			 struct dx_dirblock_info *dx_db);
80 static EXT2_QSORT_TYPE special_dir_block_cmp(const void *a, const void *b);
81 
82 struct check_dir_struct {
83 	char *buf;
84 	struct problem_context	pctx;
85 	int	count, max;
86 	e2fsck_t ctx;
87 	unsigned long long list_offset;
88 	unsigned long long ra_entries;
89 	unsigned long long next_ra_off;
90 };
91 
update_parents(struct dx_dir_info * dx_dir,int type)92 static void update_parents(struct dx_dir_info *dx_dir, int type)
93 {
94 	struct dx_dirblock_info *dx_db, *dx_parent, *dx_previous;
95 	blk_t b;
96 
97 	for (b = 0, dx_db = dx_dir->dx_block;
98 	     b < dx_dir->numblocks;
99 	     b++, dx_db++) {
100 		dx_parent = &dx_dir->dx_block[dx_db->parent];
101 		if (dx_db->type != type)
102 			continue;
103 
104 		/*
105 		 * XXX Make sure dx_parent->min_hash > dx_db->min_hash
106 		*/
107 		if (dx_db->flags & DX_FLAG_FIRST) {
108 			dx_parent->min_hash = dx_db->min_hash;
109 			if (dx_parent->previous) {
110 				dx_previous =
111 					&dx_dir->dx_block[dx_parent->previous];
112 				dx_previous->node_max_hash =
113 					dx_parent->min_hash;
114 			}
115 		}
116 		/*
117 		 * XXX Make sure dx_parent->max_hash < dx_db->max_hash
118 		 */
119 		if (dx_db->flags & DX_FLAG_LAST) {
120 			dx_parent->max_hash = dx_db->max_hash;
121 		}
122 	}
123 }
124 
e2fsck_pass2(e2fsck_t ctx)125 void e2fsck_pass2(e2fsck_t ctx)
126 {
127 	struct ext2_super_block *sb = ctx->fs->super;
128 	struct problem_context	pctx;
129 	ext2_filsys 		fs = ctx->fs;
130 	char			*buf = NULL;
131 #ifdef RESOURCE_TRACK
132 	struct resource_track	rtrack;
133 #endif
134 	struct check_dir_struct cd;
135 	struct dx_dir_info	*dx_dir;
136 	struct dx_dirblock_info	*dx_db;
137 	blk_t			b;
138 	ext2_ino_t		i;
139 	short			depth;
140 	problem_t		code;
141 	int			bad_dir;
142 	int (*check_dir_func)(ext2_filsys fs,
143 			      struct ext2_db_entry2 *dir_blocks_info,
144 			      void *priv_data);
145 
146 	init_resource_track(&rtrack, ctx->fs->io);
147 	clear_problem_context(&cd.pctx);
148 
149 #ifdef MTRACE
150 	mtrace_print("Pass 2");
151 #endif
152 
153 	if (!(ctx->options & E2F_OPT_PREEN))
154 		fix_problem(ctx, PR_2_PASS_HEADER, &cd.pctx);
155 
156 	cd.pctx.errcode = e2fsck_setup_icount(ctx, "inode_count",
157 				EXT2_ICOUNT_OPT_INCREMENT,
158 				ctx->inode_link_info, &ctx->inode_count);
159 	if (cd.pctx.errcode) {
160 		fix_problem(ctx, PR_2_ALLOCATE_ICOUNT, &cd.pctx);
161 		ctx->flags |= E2F_FLAG_ABORT;
162 		goto cleanup;
163 	}
164 	buf = (char *) e2fsck_allocate_memory(ctx, 2*fs->blocksize,
165 					      "directory scan buffer");
166 
167 	/*
168 	 * Set up the parent pointer for the root directory, if
169 	 * present.  (If the root directory is not present, we will
170 	 * create it in pass 3.)
171 	 */
172 	(void) e2fsck_dir_info_set_parent(ctx, EXT2_ROOT_INO, EXT2_ROOT_INO);
173 
174 	cd.buf = buf;
175 	cd.ctx = ctx;
176 	cd.count = 1;
177 	cd.max = ext2fs_dblist_count2(fs->dblist);
178 	cd.list_offset = 0;
179 	cd.ra_entries = ctx->readahead_kb * 1024 / ctx->fs->blocksize;
180 	cd.next_ra_off = 0;
181 
182 	if (ctx->progress)
183 		(void) (ctx->progress)(ctx, 2, 0, cd.max);
184 
185 	if (ext2fs_has_feature_dir_index(fs->super))
186 		ext2fs_dblist_sort2(fs->dblist, special_dir_block_cmp);
187 
188 	check_dir_func = cd.ra_entries ? check_dir_block2 : check_dir_block;
189 	cd.pctx.errcode = ext2fs_dblist_iterate2(fs->dblist, check_dir_func,
190 						 &cd);
191 	if (ctx->flags & E2F_FLAG_RESTART_LATER) {
192 		ctx->flags |= E2F_FLAG_RESTART;
193 		ctx->flags &= ~E2F_FLAG_RESTART_LATER;
194 	}
195 
196 	if (ctx->flags & E2F_FLAG_RUN_RETURN)
197 		goto cleanup;
198 
199 	if (cd.pctx.errcode) {
200 		fix_problem(ctx, PR_2_DBLIST_ITERATE, &cd.pctx);
201 		ctx->flags |= E2F_FLAG_ABORT;
202 		goto cleanup;
203 	}
204 
205 	for (i=0; (dx_dir = e2fsck_dx_dir_info_iter(ctx, &i)) != 0;) {
206 		if (ctx->flags & E2F_FLAG_SIGNAL_MASK)
207 			goto cleanup;
208 		if (e2fsck_dir_will_be_rehashed(ctx, dx_dir->ino) ||
209 		    dx_dir->numblocks == 0)
210 			continue;
211 		clear_problem_context(&pctx);
212 		bad_dir = 0;
213 		pctx.dir = dx_dir->ino;
214 		dx_db = dx_dir->dx_block;
215 		if (dx_db->flags & DX_FLAG_REFERENCED)
216 			dx_db->flags |= DX_FLAG_DUP_REF;
217 		else
218 			dx_db->flags |= DX_FLAG_REFERENCED;
219 		/*
220 		 * Find all of the first and last leaf blocks, and
221 		 * update their parent's min and max hash values
222 		 */
223 		update_parents(dx_dir, DX_DIRBLOCK_LEAF);
224 
225 		/* for 3 level htree: update 2 level parent's min
226 		 * and max hash values */
227 		update_parents(dx_dir, DX_DIRBLOCK_NODE);
228 
229 		for (b=0, dx_db = dx_dir->dx_block;
230 		     b < dx_dir->numblocks;
231 		     b++, dx_db++) {
232 			pctx.blkcount = b;
233 			pctx.group = dx_db->parent;
234 			code = 0;
235 			if (!(dx_db->flags & DX_FLAG_FIRST) &&
236 			    (dx_db->min_hash < dx_db->node_min_hash)) {
237 				pctx.blk = dx_db->min_hash;
238 				pctx.blk2 = dx_db->node_min_hash;
239 				code = PR_2_HTREE_MIN_HASH;
240 				fix_problem(ctx, code, &pctx);
241 				bad_dir++;
242 			}
243 			if (dx_db->type == DX_DIRBLOCK_LEAF) {
244 				depth = htree_depth(dx_dir, dx_db);
245 				if (depth != dx_dir->depth) {
246 					pctx.num = dx_dir->depth;
247 					code = PR_2_HTREE_BAD_DEPTH;
248 					fix_problem(ctx, code, &pctx);
249 					bad_dir++;
250 				}
251 			}
252 			/*
253 			 * This test doesn't apply for the root block
254 			 * at block #0
255 			 */
256 			if (b &&
257 			    (dx_db->max_hash > dx_db->node_max_hash)) {
258 				pctx.blk = dx_db->max_hash;
259 				pctx.blk2 = dx_db->node_max_hash;
260 				code = PR_2_HTREE_MAX_HASH;
261 				fix_problem(ctx, code, &pctx);
262 				bad_dir++;
263 			}
264 			if (!(dx_db->flags & DX_FLAG_REFERENCED)) {
265 				code = PR_2_HTREE_NOTREF;
266 				fix_problem(ctx, code, &pctx);
267 				bad_dir++;
268 			} else if (dx_db->flags & DX_FLAG_DUP_REF) {
269 				code = PR_2_HTREE_DUPREF;
270 				fix_problem(ctx, code, &pctx);
271 				bad_dir++;
272 			}
273 		}
274 		if (bad_dir && fix_problem(ctx, PR_2_HTREE_CLEAR, &pctx)) {
275 			clear_htree(ctx, dx_dir->ino);
276 			dx_dir->numblocks = 0;
277 		}
278 	}
279 	e2fsck_free_dx_dir_info(ctx);
280 
281 	ext2fs_free_mem(&buf);
282 	ext2fs_free_dblist(fs->dblist);
283 
284 	if (ctx->inode_bad_map) {
285 		ext2fs_free_inode_bitmap(ctx->inode_bad_map);
286 		ctx->inode_bad_map = 0;
287 	}
288 	if (ctx->inode_reg_map) {
289 		ext2fs_free_inode_bitmap(ctx->inode_reg_map);
290 		ctx->inode_reg_map = 0;
291 	}
292 	if (ctx->inode_casefold_map) {
293 		ext2fs_free_inode_bitmap(ctx->inode_casefold_map);
294 		ctx->inode_casefold_map = 0;
295 	}
296 	destroy_encrypted_file_info(ctx);
297 	if (ctx->casefolded_dirs) {
298 		ext2fs_u32_list_free(ctx->casefolded_dirs);
299 		ctx->casefolded_dirs = 0;
300 	}
301 
302 	clear_problem_context(&pctx);
303 	if (ctx->large_files) {
304 		if (!ext2fs_has_feature_large_file(sb) &&
305 		    fix_problem(ctx, PR_2_FEATURE_LARGE_FILES, &pctx)) {
306 			ext2fs_set_feature_large_file(sb);
307 			fs->flags &= ~EXT2_FLAG_MASTER_SB_ONLY;
308 			ext2fs_mark_super_dirty(fs);
309 		}
310 		if (sb->s_rev_level == EXT2_GOOD_OLD_REV &&
311 		    fix_problem(ctx, PR_1_FS_REV_LEVEL, &pctx)) {
312 			ext2fs_update_dynamic_rev(fs);
313 			ext2fs_mark_super_dirty(fs);
314 		}
315 	}
316 
317 	print_resource_track(ctx, _("Pass 2"), &rtrack, fs->io);
318 cleanup:
319 	ext2fs_free_mem(&buf);
320 }
321 
322 #define MAX_DEPTH 32000
htree_depth(struct dx_dir_info * dx_dir,struct dx_dirblock_info * dx_db)323 static short htree_depth(struct dx_dir_info *dx_dir,
324 			 struct dx_dirblock_info *dx_db)
325 {
326 	short depth = 0;
327 
328 	while (dx_db->type != DX_DIRBLOCK_ROOT && depth < MAX_DEPTH) {
329 		dx_db = &dx_dir->dx_block[dx_db->parent];
330 		depth++;
331 	}
332 	return depth;
333 }
334 
dict_de_cmp(const void * cmp_ctx EXT2FS_ATTR ((unused)),const void * a,const void * b)335 static int dict_de_cmp(const void *cmp_ctx EXT2FS_ATTR((unused)),
336 		       const void *a, const void *b)
337 {
338 	const struct ext2_dir_entry *de_a, *de_b;
339 	int	a_len, b_len;
340 
341 	de_a = (const struct ext2_dir_entry *) a;
342 	a_len = ext2fs_dirent_name_len(de_a);
343 	de_b = (const struct ext2_dir_entry *) b;
344 	b_len = ext2fs_dirent_name_len(de_b);
345 
346 	if (a_len != b_len)
347 		return (a_len - b_len);
348 
349 	return memcmp(de_a->name, de_b->name, a_len);
350 }
351 
dict_de_cf_cmp(const void * cmp_ctx,const void * a,const void * b)352 static int dict_de_cf_cmp(const void *cmp_ctx, const void *a, const void *b)
353 {
354 	const struct ext2fs_nls_table *tbl = cmp_ctx;
355 	const struct ext2_dir_entry *de_a, *de_b;
356 	int	a_len, b_len;
357 
358 	de_a = (const struct ext2_dir_entry *) a;
359 	a_len = ext2fs_dirent_name_len(de_a);
360 	de_b = (const struct ext2_dir_entry *) b;
361 	b_len = ext2fs_dirent_name_len(de_b);
362 
363 	return ext2fs_casefold_cmp(tbl, (unsigned char *) de_a->name, a_len,
364 				   (unsigned char *) de_b->name, b_len);
365 }
366 
367 /*
368  * This is special sort function that makes sure that directory blocks
369  * with a dirblock of zero are sorted to the beginning of the list.
370  * This guarantees that the root node of the htree directories are
371  * processed first, so we know what hash version to use.
372  */
special_dir_block_cmp(const void * a,const void * b)373 static EXT2_QSORT_TYPE special_dir_block_cmp(const void *a, const void *b)
374 {
375 	const struct ext2_db_entry2 *db_a =
376 		(const struct ext2_db_entry2 *) a;
377 	const struct ext2_db_entry2 *db_b =
378 		(const struct ext2_db_entry2 *) b;
379 
380 	if (db_a->blockcnt && !db_b->blockcnt)
381 		return 1;
382 
383 	if (!db_a->blockcnt && db_b->blockcnt)
384 		return -1;
385 
386 	if (db_a->blk != db_b->blk)
387 		return (int) (db_a->blk - db_b->blk);
388 
389 	if (db_a->ino != db_b->ino)
390 		return (int) (db_a->ino - db_b->ino);
391 
392 	return (int) (db_a->blockcnt - db_b->blockcnt);
393 }
394 
395 
396 /*
397  * Make sure the first entry in the directory is '.', and that the
398  * directory entry is sane.
399  */
check_dot(e2fsck_t ctx,struct ext2_dir_entry * dirent,ext2_ino_t ino,struct problem_context * pctx)400 static int check_dot(e2fsck_t ctx,
401 		     struct ext2_dir_entry *dirent,
402 		     ext2_ino_t ino, struct problem_context *pctx)
403 {
404 	struct ext2_dir_entry *nextdir;
405 	unsigned int	rec_len, new_len;
406 	int		status = 0;
407 	int		created = 0;
408 	problem_t	problem = 0;
409 
410 	if (!dirent->inode)
411 		problem = PR_2_MISSING_DOT;
412 	else if ((ext2fs_dirent_name_len(dirent) != 1) ||
413 		 (dirent->name[0] != '.'))
414 		problem = PR_2_1ST_NOT_DOT;
415 	else if (dirent->name[1] != '\0')
416 		problem = PR_2_DOT_NULL_TERM;
417 
418 	(void) ext2fs_get_rec_len(ctx->fs, dirent, &rec_len);
419 	if (problem) {
420 		if (fix_problem(ctx, problem, pctx)) {
421 			if (rec_len < 12)
422 				rec_len = dirent->rec_len = 12;
423 			dirent->inode = ino;
424 			ext2fs_dirent_set_name_len(dirent, 1);
425 			ext2fs_dirent_set_file_type(dirent, EXT2_FT_UNKNOWN);
426 			dirent->name[0] = '.';
427 			dirent->name[1] = '\0';
428 			status = 1;
429 			created = 1;
430 		}
431 	}
432 	if (dirent->inode != ino) {
433 		if (fix_problem(ctx, PR_2_BAD_INODE_DOT, pctx)) {
434 			dirent->inode = ino;
435 			status = 1;
436 		}
437 	}
438 	if (rec_len > 12) {
439 		new_len = rec_len - 12;
440 		if (new_len > 12) {
441 			if (created ||
442 			    fix_problem(ctx, PR_2_SPLIT_DOT, pctx)) {
443 				nextdir = (struct ext2_dir_entry *)
444 					((char *) dirent + 12);
445 				dirent->rec_len = 12;
446 				(void) ext2fs_set_rec_len(ctx->fs, new_len,
447 							  nextdir);
448 				nextdir->inode = 0;
449 				ext2fs_dirent_set_name_len(nextdir, 0);
450 				ext2fs_dirent_set_file_type(nextdir,
451 							    EXT2_FT_UNKNOWN);
452 				status = 1;
453 			}
454 		}
455 	}
456 	return status;
457 }
458 
459 /*
460  * Make sure the second entry in the directory is '..', and that the
461  * directory entry is sane.  We do not check the inode number of '..'
462  * here; this gets done in pass 3.
463  */
check_dotdot(e2fsck_t ctx,struct ext2_dir_entry * dirent,ext2_ino_t ino,struct problem_context * pctx)464 static int check_dotdot(e2fsck_t ctx,
465 			struct ext2_dir_entry *dirent,
466 			ext2_ino_t ino, struct problem_context *pctx)
467 {
468 	problem_t	problem = 0;
469 	unsigned int	rec_len;
470 
471 	if (!dirent->inode)
472 		problem = PR_2_MISSING_DOT_DOT;
473 	else if ((ext2fs_dirent_name_len(dirent) != 2) ||
474 		 (dirent->name[0] != '.') ||
475 		 (dirent->name[1] != '.'))
476 		problem = PR_2_2ND_NOT_DOT_DOT;
477 	else if (dirent->name[2] != '\0')
478 		problem = PR_2_DOT_DOT_NULL_TERM;
479 
480 	(void) ext2fs_get_rec_len(ctx->fs, dirent, &rec_len);
481 	if (problem) {
482 		if (fix_problem(ctx, problem, pctx)) {
483 			if (rec_len < 12)
484 				dirent->rec_len = 12;
485 			/*
486 			 * Note: we don't have the parent inode just
487 			 * yet, so we will fill it in with the root
488 			 * inode.  This will get fixed in pass 3.
489 			 */
490 			dirent->inode = EXT2_ROOT_INO;
491 			ext2fs_dirent_set_name_len(dirent, 2);
492 			ext2fs_dirent_set_file_type(dirent, EXT2_FT_UNKNOWN);
493 			dirent->name[0] = '.';
494 			dirent->name[1] = '.';
495 			dirent->name[2] = '\0';
496 			return 1;
497 		}
498 		return 0;
499 	}
500 	if (e2fsck_dir_info_set_dotdot(ctx, ino, dirent->inode)) {
501 		fix_problem(ctx, PR_2_NO_DIRINFO, pctx);
502 		return -1;
503 	}
504 	return 0;
505 }
506 
507 /*
508  * Check to make sure a directory entry doesn't contain any illegal
509  * characters.
510  */
check_name(e2fsck_t ctx,struct ext2_dir_entry * dirent,struct problem_context * pctx)511 static int check_name(e2fsck_t ctx,
512 		      struct ext2_dir_entry *dirent,
513 		      struct problem_context *pctx)
514 {
515 	int	i;
516 	int	fixup = -1;
517 	int	ret = 0;
518 
519 	for ( i = 0; i < ext2fs_dirent_name_len(dirent); i++) {
520 		if (dirent->name[i] != '/' && dirent->name[i] != '\0')
521 			continue;
522 		if (fixup < 0)
523 			fixup = fix_problem(ctx, PR_2_BAD_NAME, pctx);
524 		if (fixup == 0)
525 			return 0;
526 		dirent->name[i] = '.';
527 		ret = 1;
528 	}
529 	return ret;
530 }
531 
encrypted_check_name(e2fsck_t ctx,const struct ext2_dir_entry * dirent,struct problem_context * pctx)532 static int encrypted_check_name(e2fsck_t ctx,
533 				const struct ext2_dir_entry *dirent,
534 				struct problem_context *pctx)
535 {
536 	if (ext2fs_dirent_name_len(dirent) < EXT4_CRYPTO_BLOCK_SIZE) {
537 		if (fix_problem(ctx, PR_2_BAD_ENCRYPTED_NAME, pctx))
538 			return 1;
539 		ext2fs_unmark_valid(ctx->fs);
540 	}
541 	return 0;
542 }
543 
encoded_check_name(e2fsck_t ctx,struct ext2_dir_entry * dirent,struct problem_context * pctx)544 static int encoded_check_name(e2fsck_t ctx,
545 			      struct ext2_dir_entry *dirent,
546 			      struct problem_context *pctx)
547 {
548 	const struct ext2fs_nls_table *tbl = ctx->fs->encoding;
549 	int ret;
550 	int len = ext2fs_dirent_name_len(dirent);
551 	char *pos, *end;
552 
553 	ret = ext2fs_check_encoded_name(tbl, dirent->name, len, &pos);
554 	if (ret < 0) {
555 		fatal_error(ctx, _("NLS is broken."));
556 	} else if(ret > 0) {
557 		ret = fix_problem(ctx, PR_2_BAD_ENCODED_NAME, pctx);
558 		if (ret) {
559 			end = &dirent->name[len];
560 			for (; *pos && pos != end; pos++)
561 				*pos = '.';
562 		}
563 	}
564 
565 	return (ret || check_name(ctx, dirent, pctx));
566 }
567 
568 /*
569  * Check the directory filetype (if present)
570  */
check_filetype(e2fsck_t ctx,struct ext2_dir_entry * dirent,ext2_ino_t dir_ino EXT2FS_ATTR ((unused)),struct problem_context * pctx)571 static _INLINE_ int check_filetype(e2fsck_t ctx,
572 				   struct ext2_dir_entry *dirent,
573 				   ext2_ino_t dir_ino EXT2FS_ATTR((unused)),
574 				   struct problem_context *pctx)
575 {
576 	int	filetype = ext2fs_dirent_file_type(dirent);
577 	int	should_be = EXT2_FT_UNKNOWN;
578 	struct ext2_inode	inode;
579 
580 	if (!ext2fs_has_feature_filetype(ctx->fs->super)) {
581 		if (filetype == 0 ||
582 		    !fix_problem(ctx, PR_2_CLEAR_FILETYPE, pctx))
583 			return 0;
584 		ext2fs_dirent_set_file_type(dirent, EXT2_FT_UNKNOWN);
585 		return 1;
586 	}
587 
588 	if (ext2fs_test_inode_bitmap2(ctx->inode_dir_map, dirent->inode)) {
589 		should_be = EXT2_FT_DIR;
590 	} else if (ext2fs_test_inode_bitmap2(ctx->inode_reg_map,
591 					    dirent->inode)) {
592 		should_be = EXT2_FT_REG_FILE;
593 	} else if (ctx->inode_bad_map &&
594 		   ext2fs_test_inode_bitmap2(ctx->inode_bad_map,
595 					    dirent->inode))
596 		should_be = 0;
597 	else {
598 		e2fsck_read_inode(ctx, dirent->inode, &inode,
599 				  "check_filetype");
600 		should_be = ext2_file_type(inode.i_mode);
601 	}
602 	if (filetype == should_be)
603 		return 0;
604 	pctx->num = should_be;
605 
606 	if (fix_problem(ctx, filetype ? PR_2_BAD_FILETYPE : PR_2_SET_FILETYPE,
607 			pctx) == 0)
608 		return 0;
609 
610 	ext2fs_dirent_set_file_type(dirent, should_be);
611 	return 1;
612 }
613 
parse_int_node(ext2_filsys fs,struct ext2_db_entry2 * db,struct check_dir_struct * cd,struct dx_dir_info * dx_dir,char * block_buf,int failed_csum)614 static void parse_int_node(ext2_filsys fs,
615 			   struct ext2_db_entry2 *db,
616 			   struct check_dir_struct *cd,
617 			   struct dx_dir_info	*dx_dir,
618 			   char *block_buf, int failed_csum)
619 {
620 	struct		ext2_dx_root_info  *root;
621 	struct		ext2_dx_entry *ent;
622 	struct		ext2_dx_countlimit *limit;
623 	struct dx_dirblock_info	*dx_db;
624 	int		i, expect_limit, count;
625 	blk_t		blk;
626 	ext2_dirhash_t	min_hash = 0xffffffff;
627 	ext2_dirhash_t	max_hash = 0;
628 	ext2_dirhash_t	hash = 0, prev_hash;
629 	int		csum_size = 0;
630 
631 	if (db->blockcnt == 0) {
632 		root = (struct ext2_dx_root_info *) (block_buf + 24);
633 
634 #ifdef DX_DEBUG
635 		printf("Root node dump:\n");
636 		printf("\t Reserved zero: %u\n", root->reserved_zero);
637 		printf("\t Hash Version: %u\n", root->hash_version);
638 		printf("\t Info length: %u\n", root->info_length);
639 		printf("\t Indirect levels: %u\n", root->indirect_levels);
640 		printf("\t Flags: %x\n", root->unused_flags);
641 #endif
642 
643 		ent = (struct ext2_dx_entry *) (block_buf + 24 + root->info_length);
644 
645 		if (failed_csum &&
646 		    (e2fsck_dir_will_be_rehashed(cd->ctx, cd->pctx.ino) ||
647 		     fix_problem(cd->ctx, PR_2_HTREE_ROOT_CSUM_INVALID,
648 				&cd->pctx)))
649 			goto clear_and_exit;
650 	} else {
651 		ent = (struct ext2_dx_entry *) (block_buf+8);
652 
653 		if (failed_csum &&
654 		    (e2fsck_dir_will_be_rehashed(cd->ctx, cd->pctx.ino) ||
655 		     fix_problem(cd->ctx, PR_2_HTREE_NODE_CSUM_INVALID,
656 				&cd->pctx)))
657 			goto clear_and_exit;
658 	}
659 
660 	limit = (struct ext2_dx_countlimit *) ent;
661 
662 #ifdef DX_DEBUG
663 	printf("Number of entries (count): %d\n",
664 	       ext2fs_le16_to_cpu(limit->count));
665 	printf("Number of entries (limit): %d\n",
666 	       ext2fs_le16_to_cpu(limit->limit));
667 #endif
668 
669 	count = ext2fs_le16_to_cpu(limit->count);
670 	if (ext2fs_has_feature_metadata_csum(fs->super))
671 		csum_size = sizeof(struct ext2_dx_tail);
672 	expect_limit = (fs->blocksize -
673 			(csum_size + ((char *) ent - block_buf))) /
674 		       sizeof(struct ext2_dx_entry);
675 	if (ext2fs_le16_to_cpu(limit->limit) != expect_limit) {
676 		cd->pctx.num = ext2fs_le16_to_cpu(limit->limit);
677 		if (fix_problem(cd->ctx, PR_2_HTREE_BAD_LIMIT, &cd->pctx))
678 			goto clear_and_exit;
679 	}
680 	if (count > expect_limit) {
681 		cd->pctx.num = count;
682 		if (fix_problem(cd->ctx, PR_2_HTREE_BAD_COUNT, &cd->pctx))
683 			goto clear_and_exit;
684 		count = expect_limit;
685 	}
686 
687 	for (i=0; i < count; i++) {
688 		prev_hash = hash;
689 		hash = i ? (ext2fs_le32_to_cpu(ent[i].hash) & ~1) : 0;
690 #ifdef DX_DEBUG
691 		printf("Entry #%d: Hash 0x%08x, block %u\n", i,
692 		       hash, ext2fs_le32_to_cpu(ent[i].block));
693 #endif
694 		blk = ext2fs_le32_to_cpu(ent[i].block) & EXT4_DX_BLOCK_MASK;
695 		/* Check to make sure the block is valid */
696 		if (blk >= dx_dir->numblocks) {
697 			cd->pctx.blk = blk;
698 			if (fix_problem(cd->ctx, PR_2_HTREE_BADBLK,
699 					&cd->pctx))
700 				goto clear_and_exit;
701 			continue;
702 		}
703 		if (hash < prev_hash &&
704 		    fix_problem(cd->ctx, PR_2_HTREE_HASH_ORDER, &cd->pctx))
705 			goto clear_and_exit;
706 		dx_db = &dx_dir->dx_block[blk];
707 		if (dx_db->flags & DX_FLAG_REFERENCED) {
708 			dx_db->flags |= DX_FLAG_DUP_REF;
709 		} else {
710 			dx_db->flags |= DX_FLAG_REFERENCED;
711 			dx_db->parent = db->blockcnt;
712 		}
713 
714 		dx_db->previous =
715 			i ? (ext2fs_le32_to_cpu(ent[i-1].block) &
716 			     EXT4_DX_BLOCK_MASK) : 0;
717 
718 		if (hash < min_hash)
719 			min_hash = hash;
720 		if (hash > max_hash)
721 			max_hash = hash;
722 		dx_db->node_min_hash = hash;
723 		if ((i+1) < count)
724 			dx_db->node_max_hash =
725 			  ext2fs_le32_to_cpu(ent[i+1].hash) & ~1;
726 		else {
727 			dx_db->node_max_hash = 0xfffffffe;
728 			dx_db->flags |= DX_FLAG_LAST;
729 		}
730 		if (i == 0)
731 			dx_db->flags |= DX_FLAG_FIRST;
732 	}
733 #ifdef DX_DEBUG
734 	printf("Blockcnt = %d, min hash 0x%08x, max hash 0x%08x\n",
735 	       db->blockcnt, min_hash, max_hash);
736 #endif
737 	dx_db = &dx_dir->dx_block[db->blockcnt];
738 	dx_db->min_hash = min_hash;
739 	dx_db->max_hash = max_hash;
740 	return;
741 
742 clear_and_exit:
743 	clear_htree(cd->ctx, cd->pctx.ino);
744 	dx_dir->numblocks = 0;
745 	e2fsck_rehash_dir_later(cd->ctx, cd->pctx.ino);
746 }
747 
748 /*
749  * Given a busted directory, try to salvage it somehow.
750  *
751  */
salvage_directory(ext2_filsys fs,struct ext2_dir_entry * dirent,struct ext2_dir_entry * prev,unsigned int * offset,unsigned int block_len,int hash_in_dirent)752 static void salvage_directory(ext2_filsys fs,
753 			      struct ext2_dir_entry *dirent,
754 			      struct ext2_dir_entry *prev,
755 			      unsigned int *offset,
756 			      unsigned int block_len,
757 			      int hash_in_dirent)
758 {
759 	char	*cp = (char *) dirent;
760 	int left;
761 	unsigned int rec_len, prev_rec_len;
762 	unsigned int name_len;
763 
764 	/*
765 	 * If the space left for the entry is too small to be an entry,
766 	 * we can't access dirent's fields, so plumb in the values needed
767 	 * so that the previous entry absorbs this one.
768 	 */
769 	if (block_len - *offset < EXT2_DIR_ENTRY_HEADER_LEN) {
770 		name_len = 0;
771 		rec_len = block_len - *offset;
772 	} else {
773 		name_len = ext2fs_dirent_name_len(dirent);
774 		(void) ext2fs_get_rec_len(fs, dirent, &rec_len);
775 	}
776 	left = block_len - *offset - rec_len;
777 
778 	/*
779 	 * Special case of directory entry of size 8: copy what's left
780 	 * of the directory block up to cover up the invalid hole.
781 	 */
782 	if ((left >= ext2fs_dir_rec_len(1, hash_in_dirent)) &&
783 	     (rec_len == EXT2_DIR_ENTRY_HEADER_LEN)) {
784 		memmove(cp, cp+EXT2_DIR_ENTRY_HEADER_LEN, left);
785 		memset(cp + left, 0, EXT2_DIR_ENTRY_HEADER_LEN);
786 		return;
787 	}
788 	/*
789 	 * If the directory entry overruns the end of the directory
790 	 * block, and the name is small enough to fit, then adjust the
791 	 * record length.
792 	 */
793 	if ((left < 0) &&
794 	    ((int) rec_len + left > EXT2_DIR_ENTRY_HEADER_LEN) &&
795 	    ((int) ext2fs_dir_rec_len(name_len, hash_in_dirent) <= (int) rec_len + left) &&
796 	    dirent->inode <= fs->super->s_inodes_count &&
797 	    strnlen(dirent->name, name_len) == name_len) {
798 		(void) ext2fs_set_rec_len(fs, (int) rec_len + left, dirent);
799 		return;
800 	}
801 	/*
802 	 * If the record length of the directory entry is a multiple
803 	 * of four, and not too big, such that it is valid, let the
804 	 * previous directory entry absorb the invalid one.
805 	 */
806 	if (prev && rec_len && (rec_len % 4) == 0 &&
807 	    (*offset + rec_len <= block_len)) {
808 		(void) ext2fs_get_rec_len(fs, prev, &prev_rec_len);
809 		prev_rec_len += rec_len;
810 		(void) ext2fs_set_rec_len(fs, prev_rec_len, prev);
811 		*offset += rec_len;
812 		return;
813 	}
814 	/*
815 	 * Default salvage method --- kill all of the directory
816 	 * entries for the rest of the block.  We will either try to
817 	 * absorb it into the previous directory entry, or create a
818 	 * new empty directory entry the rest of the directory block.
819 	 */
820 	if (prev) {
821 		(void) ext2fs_get_rec_len(fs, prev, &prev_rec_len);
822 		prev_rec_len += block_len - *offset;
823 		(void) ext2fs_set_rec_len(fs, prev_rec_len, prev);
824 		*offset = fs->blocksize;
825 	} else {
826 		rec_len = block_len - *offset;
827 		(void) ext2fs_set_rec_len(fs, rec_len, dirent);
828 		ext2fs_dirent_set_name_len(dirent, 0);
829 		ext2fs_dirent_set_file_type(dirent, EXT2_FT_UNKNOWN);
830 		dirent->inode = 0;
831 	}
832 }
833 
834 #define NEXT_DIRENT(d)	((void *)((char *)(d) + (d)->rec_len))
insert_dirent_tail(ext2_filsys fs,void * dirbuf)835 static errcode_t insert_dirent_tail(ext2_filsys fs, void *dirbuf)
836 {
837 	struct ext2_dir_entry *d;
838 	void *top;
839 	struct ext2_dir_entry_tail *t;
840 
841 	d = dirbuf;
842 	top = EXT2_DIRENT_TAIL(dirbuf, fs->blocksize);
843 
844 	while (d->rec_len && !(d->rec_len & 0x3) && NEXT_DIRENT(d) <= top)
845 		d = NEXT_DIRENT(d);
846 
847 	if (d != top) {
848 		unsigned int min_size = EXT2_DIR_REC_LEN(
849 				ext2fs_dirent_name_len(dirbuf));
850 		if (min_size > (char *)top - (char *)d)
851 			return EXT2_ET_DIR_NO_SPACE_FOR_CSUM;
852 		d->rec_len = (char *)top - (char *)d;
853 	}
854 
855 	t = (struct ext2_dir_entry_tail *)top;
856 	if (t->det_reserved_zero1 ||
857 	    t->det_rec_len != sizeof(struct ext2_dir_entry_tail) ||
858 	    t->det_reserved_name_len != EXT2_DIR_NAME_LEN_CSUM)
859 		ext2fs_initialize_dirent_tail(fs, t);
860 
861 	return 0;
862 }
863 #undef NEXT_DIRENT
864 
fix_inline_dir_size(e2fsck_t ctx,ext2_ino_t ino,size_t * inline_data_size,struct problem_context * pctx,char * buf)865 static errcode_t fix_inline_dir_size(e2fsck_t ctx, ext2_ino_t ino,
866 				     size_t *inline_data_size,
867 				     struct problem_context *pctx,
868 				     char *buf)
869 {
870 	ext2_filsys fs = ctx->fs;
871 	struct ext2_inode inode;
872 	size_t new_size, old_size;
873 	errcode_t retval;
874 
875 	old_size = *inline_data_size;
876 	/*
877 	 * If there's not enough bytes to start the "second" dir block
878 	 * (in the EA space) then truncate everything to the first block.
879 	 */
880 	if (old_size > EXT4_MIN_INLINE_DATA_SIZE &&
881 	    old_size < EXT4_MIN_INLINE_DATA_SIZE +
882 		       EXT2_DIR_REC_LEN(1)) {
883 		old_size = EXT4_MIN_INLINE_DATA_SIZE;
884 		new_size = old_size;
885 	} else
886 		/* Increase to the next four-byte boundary for salvaging */
887 		new_size = old_size + (4 - (old_size & 3));
888 	memset(buf + old_size, 0, new_size - old_size);
889 	retval = ext2fs_inline_data_set(fs, ino, 0, buf, new_size);
890 	if (retval == EXT2_ET_INLINE_DATA_NO_SPACE) {
891 		/* Or we can't, so truncate. */
892 		new_size -= 4;
893 		retval = ext2fs_inline_data_set(fs, ino, 0, buf, new_size);
894 		if (retval) {
895 			if (fix_problem(ctx, PR_2_FIX_INLINE_DIR_FAILED,
896 					pctx)) {
897 				new_size = 0;
898 				goto write_inode;
899 			}
900 			goto err;
901 		}
902 	} else if (retval) {
903 		if (fix_problem(ctx, PR_2_FIX_INLINE_DIR_FAILED,
904 				pctx)) {
905 			new_size = 0;
906 			goto write_inode;
907 		}
908 		goto err;
909 	}
910 
911 write_inode:
912 	retval = ext2fs_read_inode(fs, ino, &inode);
913 	if (retval)
914 		goto err;
915 
916 	retval = ext2fs_inode_size_set(fs, &inode, new_size);
917 	if (retval)
918 		goto err;
919 	if (new_size == 0)
920 		inode.i_flags &= ~EXT4_INLINE_DATA_FL;
921 	retval = ext2fs_write_inode(fs, ino, &inode);
922 	if (retval)
923 		goto err;
924 	*inline_data_size = new_size;
925 
926 err:
927 	return retval;
928 }
929 
930 /* Return true if this type of file needs encryption */
needs_encryption(e2fsck_t ctx,const struct ext2_dir_entry * dirent)931 static int needs_encryption(e2fsck_t ctx, const struct ext2_dir_entry *dirent)
932 {
933 	int filetype = ext2fs_dirent_file_type(dirent);
934 	ext2_ino_t ino = dirent->inode;
935 	struct ext2_inode inode;
936 
937 	if (filetype != EXT2_FT_UNKNOWN)
938 		return filetype == EXT2_FT_REG_FILE ||
939 		       filetype == EXT2_FT_DIR ||
940 		       filetype == EXT2_FT_SYMLINK;
941 
942 	if (ext2fs_test_inode_bitmap2(ctx->inode_reg_map, ino) ||
943 	    ext2fs_test_inode_bitmap2(ctx->inode_dir_map, ino))
944 		return 1;
945 
946 	e2fsck_read_inode(ctx, ino, &inode, "check_encryption_policy");
947 	return LINUX_S_ISREG(inode.i_mode) ||
948 	       LINUX_S_ISDIR(inode.i_mode) ||
949 	       LINUX_S_ISLNK(inode.i_mode);
950 }
951 
952 /*
953  * All regular files, directories, and symlinks in encrypted directories must be
954  * encrypted using the same encryption policy as their directory.
955  *
956  * Returns 1 if the dirent should be cleared, otherwise 0.
957  */
check_encryption_policy(e2fsck_t ctx,const struct ext2_dir_entry * dirent,__u32 dir_encpolicy_id,struct problem_context * pctx)958 static int check_encryption_policy(e2fsck_t ctx,
959 				   const struct ext2_dir_entry *dirent,
960 				   __u32 dir_encpolicy_id,
961 				   struct problem_context *pctx)
962 {
963 	__u32 file_encpolicy_id = find_encryption_policy(ctx, dirent->inode);
964 
965 	/* Same policy or both UNRECOGNIZED_ENCRYPTION_POLICY? */
966 	if (file_encpolicy_id == dir_encpolicy_id)
967 		return 0;
968 
969 	if (file_encpolicy_id == NO_ENCRYPTION_POLICY) {
970 		if (!needs_encryption(ctx, dirent))
971 			return 0;
972 		return fix_problem(ctx, PR_2_UNENCRYPTED_FILE, pctx);
973 	}
974 
975 	return fix_problem(ctx, PR_2_INCONSISTENT_ENCRYPTION_POLICY, pctx);
976 }
977 
978 /*
979  * Check an encrypted directory entry.
980  *
981  * Returns 1 if the dirent should be cleared, otherwise 0.
982  */
check_encrypted_dirent(e2fsck_t ctx,const struct ext2_dir_entry * dirent,__u32 dir_encpolicy_id,struct problem_context * pctx)983 static int check_encrypted_dirent(e2fsck_t ctx,
984 				  const struct ext2_dir_entry *dirent,
985 				  __u32 dir_encpolicy_id,
986 				  struct problem_context *pctx)
987 {
988 	if (encrypted_check_name(ctx, dirent, pctx))
989 		return 1;
990 	if (check_encryption_policy(ctx, dirent, dir_encpolicy_id, pctx))
991 		return 1;
992 	return 0;
993 }
994 
check_dir_block2(ext2_filsys fs,struct ext2_db_entry2 * db,void * priv_data)995 static int check_dir_block2(ext2_filsys fs,
996 			   struct ext2_db_entry2 *db,
997 			   void *priv_data)
998 {
999 	int err;
1000 	struct check_dir_struct *cd = priv_data;
1001 
1002 	if (cd->ra_entries && cd->list_offset >= cd->next_ra_off) {
1003 		err = e2fsck_readahead_dblist(fs,
1004 					E2FSCK_RA_DBLIST_IGNORE_BLOCKCNT,
1005 					fs->dblist,
1006 					cd->list_offset + cd->ra_entries / 8,
1007 					cd->ra_entries);
1008 		if (err)
1009 			cd->ra_entries = 0;
1010 		cd->next_ra_off = cd->list_offset + (cd->ra_entries * 7 / 8);
1011 	}
1012 
1013 	err = check_dir_block(fs, db, priv_data);
1014 	cd->list_offset++;
1015 	return err;
1016 }
1017 
check_dir_block(ext2_filsys fs,struct ext2_db_entry2 * db,void * priv_data)1018 static int check_dir_block(ext2_filsys fs,
1019 			   struct ext2_db_entry2 *db,
1020 			   void *priv_data)
1021 {
1022  	struct dx_dir_info	*dx_dir;
1023 	struct dx_dirblock_info	*dx_db = 0;
1024 	struct ext2_dir_entry 	*dirent, *prev, dot, dotdot;
1025 	ext2_dirhash_t		hash;
1026 	unsigned int		offset = 0;
1027 	int			dir_modified = 0;
1028 	int			dot_state;
1029 	unsigned int		rec_len;
1030 	blk64_t			block_nr = db->blk;
1031 	ext2_ino_t 		ino = db->ino;
1032 	ext2_ino_t 		subdir_parent;
1033 	__u16			links;
1034 	struct check_dir_struct	*cd;
1035 	char			*buf, *ibuf;
1036 	e2fsck_t		ctx;
1037 	problem_t		problem;
1038 	struct ext2_dx_root_info *root;
1039 	struct ext2_dx_countlimit *limit;
1040 	static dict_t de_dict;
1041 	struct problem_context	pctx;
1042 	int	dups_found = 0;
1043 	int	ret;
1044 	int	dx_csum_size = 0, de_csum_size = 0;
1045 	int	failed_csum = 0;
1046 	int	is_leaf = 1;
1047 	size_t	inline_data_size = 0;
1048 	int	filetype = 0;
1049 	__u32   dir_encpolicy_id = NO_ENCRYPTION_POLICY;
1050 	int	hash_in_dirent = 0;
1051 	int	casefolded = 0;
1052 	size_t	max_block_size;
1053 	int	hash_flags = 0;
1054 	static char *eop_read_dirblock = NULL;
1055 	int cf_dir = 0;
1056 
1057 	cd = (struct check_dir_struct *) priv_data;
1058 	ibuf = buf = cd->buf;
1059 	ctx = cd->ctx;
1060 
1061 	/* We only want filename encoding verification on strict
1062 	 * mode or if explicitly requested by user. */
1063 	if (ext2fs_test_inode_bitmap2(ctx->inode_casefold_map, ino) &&
1064 	    ((ctx->fs->super->s_encoding_flags & EXT4_ENC_STRICT_MODE_FL) ||
1065 	     (ctx->options & E2F_OPT_CHECK_ENCODING)))
1066 		cf_dir = 1;
1067 
1068 	if (ctx->flags & E2F_FLAG_RUN_RETURN)
1069 		return DIRENT_ABORT;
1070 
1071 	if (ctx->progress && (ctx->progress)(ctx, 2, cd->count++, cd->max))
1072 		return DIRENT_ABORT;
1073 
1074 	if (ext2fs_has_feature_metadata_csum(fs->super)) {
1075 		dx_csum_size = sizeof(struct ext2_dx_tail);
1076 		de_csum_size = sizeof(struct ext2_dir_entry_tail);
1077 	}
1078 
1079 	if (ext2fs_has_feature_filetype(fs->super))
1080 		filetype = EXT2_FT_DIR << 8;
1081 
1082 	/*
1083 	 * Make sure the inode is still in use (could have been
1084 	 * deleted in the duplicate/bad blocks pass.
1085 	 */
1086 	if (!(ext2fs_test_inode_bitmap2(ctx->inode_used_map, ino)))
1087 		return 0;
1088 
1089 	cd->pctx.ino = ino;
1090 	cd->pctx.blk = block_nr;
1091 	cd->pctx.blkcount = db->blockcnt;
1092 	cd->pctx.ino2 = 0;
1093 	cd->pctx.dirent = 0;
1094 	cd->pctx.num = 0;
1095 
1096 	if (ext2fs_has_feature_inline_data(fs->super)) {
1097 		errcode_t ec;
1098 
1099 		ec = ext2fs_inline_data_size(fs, ino, &inline_data_size);
1100 		if (ec && ec != EXT2_ET_NO_INLINE_DATA)
1101 			return DIRENT_ABORT;
1102 	}
1103 
1104 	/* This will allow (at some point in the future) to punch out empty
1105 	 * directory blocks and reduce the space used by a directory that grows
1106 	 * very large and then the files are deleted. For now, all that is
1107 	 * needed is to avoid e2fsck filling in these holes as part of
1108 	 * feature flag. */
1109 	if (db->blk == 0 && ext2fs_has_feature_largedir(fs->super) &&
1110 	    !ext2fs_has_feature_inline_data(fs->super))
1111 		return 0;
1112 
1113 	if (db->blk == 0 && !inline_data_size) {
1114 		if (allocate_dir_block(ctx, db, buf, &cd->pctx))
1115 			return 0;
1116 		block_nr = db->blk;
1117 	}
1118 
1119 	if (db->blockcnt)
1120 		dot_state = 2;
1121 	else
1122 		dot_state = 0;
1123 
1124 	if (ctx->dirs_to_hash &&
1125 	    ext2fs_u32_list_test(ctx->dirs_to_hash, ino))
1126 		dups_found++;
1127 
1128 #if 0
1129 	printf("In process_dir_block block %lu, #%d, inode %lu\n", block_nr,
1130 	       db->blockcnt, ino);
1131 #endif
1132 
1133 	if (!eop_read_dirblock)
1134 		eop_read_dirblock = (char *) _("reading directory block");
1135 	ehandler_operation(eop_read_dirblock);
1136 	if (inline_data_size) {
1137 		memset(buf, 0, fs->blocksize - inline_data_size);
1138 		cd->pctx.errcode = ext2fs_inline_data_get(fs, ino, 0, buf, 0);
1139 		if (cd->pctx.errcode)
1140 			goto inline_read_fail;
1141 #ifdef WORDS_BIGENDIAN
1142 		if (db->blockcnt)
1143 			goto skip_first_read_swab;
1144 		*((__u32 *)buf) = ext2fs_le32_to_cpu(*((__u32 *)buf));
1145 		cd->pctx.errcode = ext2fs_dirent_swab_in2(fs,
1146 				buf + EXT4_INLINE_DATA_DOTDOT_SIZE,
1147 				EXT4_MIN_INLINE_DATA_SIZE - EXT4_INLINE_DATA_DOTDOT_SIZE,
1148 				0);
1149 		if (cd->pctx.errcode)
1150 			goto inline_read_fail;
1151 skip_first_read_swab:
1152 		if (inline_data_size <= EXT4_MIN_INLINE_DATA_SIZE ||
1153 		    !db->blockcnt)
1154 			goto inline_read_fail;
1155 		cd->pctx.errcode = ext2fs_dirent_swab_in2(fs,
1156 				buf + EXT4_MIN_INLINE_DATA_SIZE,
1157 				inline_data_size - EXT4_MIN_INLINE_DATA_SIZE,
1158 				0);
1159 #endif
1160 	} else
1161 		cd->pctx.errcode = ext2fs_read_dir_block4(fs, block_nr,
1162 							  buf, 0, ino);
1163 inline_read_fail:
1164 	pctx.ino = ino;
1165 	pctx.num = inline_data_size;
1166 	if (((inline_data_size & 3) ||
1167 	     (inline_data_size > EXT4_MIN_INLINE_DATA_SIZE &&
1168 	      inline_data_size < EXT4_MIN_INLINE_DATA_SIZE +
1169 				 EXT2_DIR_REC_LEN(1))) &&
1170 	    fix_problem(ctx, PR_2_BAD_INLINE_DIR_SIZE, &pctx)) {
1171 		errcode_t err = fix_inline_dir_size(ctx, ino,
1172 						    &inline_data_size, &pctx,
1173 						    buf);
1174 		if (err)
1175 			return DIRENT_ABORT;
1176 
1177 	}
1178 	ehandler_operation(0);
1179 	if (cd->pctx.errcode == EXT2_ET_DIR_CORRUPTED)
1180 		cd->pctx.errcode = 0; /* We'll handle this ourselves */
1181 	else if (cd->pctx.errcode == EXT2_ET_DIR_CSUM_INVALID) {
1182 		cd->pctx.errcode = 0; /* We'll handle this ourselves */
1183 		failed_csum = 1;
1184 	}
1185 	if (cd->pctx.errcode) {
1186 		char *buf2;
1187 		if (!fix_problem(ctx, PR_2_READ_DIRBLOCK, &cd->pctx)) {
1188 			ctx->flags |= E2F_FLAG_ABORT;
1189 			return DIRENT_ABORT;
1190 		}
1191 		ext2fs_new_dir_block(fs, db->blockcnt == 0 ? ino : 0,
1192 				     EXT2_ROOT_INO, &buf2);
1193 		memcpy(buf, buf2, fs->blocksize);
1194 		ext2fs_free_mem(&buf2);
1195 	}
1196 	dx_dir = e2fsck_get_dx_dir_info(ctx, ino);
1197 	if (dx_dir && dx_dir->numblocks) {
1198 		if (db->blockcnt >= dx_dir->numblocks) {
1199 			pctx.dir = ino;
1200 			if (fix_problem(ctx, PR_2_UNEXPECTED_HTREE_BLOCK,
1201 					&pctx)) {
1202 				clear_htree(ctx, ino);
1203 				dx_dir->numblocks = 0;
1204 				dx_db = 0;
1205 				goto out_htree;
1206 			}
1207 			fatal_error(ctx, _("Can not continue."));
1208 		}
1209 		dx_db = &dx_dir->dx_block[db->blockcnt];
1210 		dx_db->type = DX_DIRBLOCK_LEAF;
1211 		dx_db->phys = block_nr;
1212 		dx_db->min_hash = ~0;
1213 		dx_db->max_hash = 0;
1214 
1215 		dirent = (struct ext2_dir_entry *) buf;
1216 		(void) ext2fs_get_rec_len(fs, dirent, &rec_len);
1217 		limit = (struct ext2_dx_countlimit *) (buf+8);
1218 		if (db->blockcnt == 0) {
1219 			root = (struct ext2_dx_root_info *) (buf + 24);
1220 			dx_db->type = DX_DIRBLOCK_ROOT;
1221 			dx_db->flags |= DX_FLAG_FIRST | DX_FLAG_LAST;
1222 
1223 			/* large_dir was set in pass1 if large dirs were found,
1224 			 * so ext2_dir_htree_level() should now be correct */
1225 			if ((root->reserved_zero ||
1226 			     root->info_length < 8 ||
1227 			     root->indirect_levels >=
1228 			     ext2_dir_htree_level(fs)) &&
1229 			    fix_problem(ctx, PR_2_HTREE_BAD_ROOT, &cd->pctx)) {
1230 				clear_htree(ctx, ino);
1231 				dx_dir->numblocks = 0;
1232 				dx_db = NULL;
1233 			}
1234 			dx_dir->hashversion = root->hash_version;
1235 			if ((dx_dir->hashversion <= EXT2_HASH_TEA) &&
1236 			    (fs->super->s_flags & EXT2_FLAGS_UNSIGNED_HASH))
1237 				dx_dir->hashversion += 3;
1238 			dx_dir->depth = root->indirect_levels + 1;
1239 		} else if ((dirent->inode == 0) &&
1240 			   (rec_len == fs->blocksize) &&
1241 			   (ext2fs_dirent_name_len(dirent) == 0) &&
1242 			   (ext2fs_le16_to_cpu(limit->limit) ==
1243 			    ((fs->blocksize - (8 + dx_csum_size)) /
1244 			     sizeof(struct ext2_dx_entry)))) {
1245 			dx_db->type = DX_DIRBLOCK_NODE;
1246 		}
1247 		is_leaf = dx_db ? (dx_db->type == DX_DIRBLOCK_LEAF) : 0;
1248 	}
1249 out_htree:
1250 
1251 	/* Leaf node with no space for csum?  Rebuild dirs in pass 3A. */
1252 	if (is_leaf && !inline_data_size && failed_csum &&
1253 	    !ext2fs_dirent_has_tail(fs, (struct ext2_dir_entry *)buf)) {
1254 		de_csum_size = 0;
1255 		if (e2fsck_dir_will_be_rehashed(ctx, ino)) {
1256 			failed_csum = 0;
1257 			goto skip_checksum;
1258 		}
1259 		if (!fix_problem(cd->ctx, PR_2_LEAF_NODE_MISSING_CSUM,
1260 				 &cd->pctx))
1261 			goto skip_checksum;
1262 		e2fsck_rehash_dir_later(ctx, ino);
1263 		failed_csum = 0;
1264 		goto skip_checksum;
1265 	}
1266 	/* htree nodes don't use fake dirents to store checksums */
1267 	if (!is_leaf)
1268 		de_csum_size = 0;
1269 
1270 skip_checksum:
1271 	if (inline_data_size) {
1272 		if (db->blockcnt) {
1273 			buf += EXT4_MIN_INLINE_DATA_SIZE;
1274 			max_block_size = inline_data_size - EXT4_MIN_INLINE_DATA_SIZE;
1275 			/* Zero-length second block, just exit */
1276 			if (max_block_size == 0)
1277 				return 0;
1278 		} else {
1279 			max_block_size = EXT4_MIN_INLINE_DATA_SIZE;
1280 		}
1281 	} else
1282 		max_block_size = fs->blocksize - de_csum_size;
1283 
1284 	dir_encpolicy_id = find_encryption_policy(ctx, ino);
1285 
1286 	if (cf_dir) {
1287 		dict_init(&de_dict, DICTCOUNT_T_MAX, dict_de_cf_cmp);
1288 		dict_set_cmp_context(&de_dict, (void *)ctx->fs->encoding);
1289 	} else {
1290 		dict_init(&de_dict, DICTCOUNT_T_MAX, dict_de_cmp);
1291 	}
1292 	if (ctx->casefolded_dirs)
1293 		casefolded = ext2fs_u32_list_test(ctx->casefolded_dirs, ino);
1294 	hash_in_dirent = (casefolded &&
1295 			  (dir_encpolicy_id != NO_ENCRYPTION_POLICY));
1296 
1297 	prev = 0;
1298 	do {
1299 		dgrp_t group;
1300 		ext2_ino_t first_unused_inode;
1301 		unsigned int name_len;
1302 		/* csum entry is not checked here, so don't worry about it */
1303 		int extended = (dot_state > 1) && hash_in_dirent;
1304 		int min_dir_len = ext2fs_dir_rec_len(1, extended);
1305 
1306 		problem = 0;
1307 		if (!inline_data_size || dot_state > 1) {
1308 			dirent = (struct ext2_dir_entry *) (buf + offset);
1309 			/*
1310 			 * If there's not even space for the entry header,
1311 			 * force salvaging this dir.
1312 			 */
1313 			if (max_block_size - offset < EXT2_DIR_ENTRY_HEADER_LEN)
1314 				rec_len = ext2fs_dir_rec_len(1, extended);
1315 			else
1316 				(void) ext2fs_get_rec_len(fs, dirent, &rec_len);
1317 			cd->pctx.dirent = dirent;
1318 			cd->pctx.num = offset;
1319 			if ((offset + rec_len > max_block_size) ||
1320 			    (rec_len < min_dir_len) ||
1321 			    ((rec_len % 4) != 0) ||
1322 			    ((ext2fs_dir_rec_len(ext2fs_dirent_name_len(dirent),
1323 						 extended)) > rec_len)) {
1324 				if (fix_problem(ctx, PR_2_DIR_CORRUPTED,
1325 						&cd->pctx)) {
1326 #ifdef WORDS_BIGENDIAN
1327 					/*
1328 					 * On big-endian systems, if the dirent
1329 					 * swap routine finds a rec_len that it
1330 					 * doesn't like, it continues
1331 					 * processing the block as if rec_len
1332 					 * == EXT2_DIR_ENTRY_HEADER_LEN.  This means that the name
1333 					 * field gets byte swapped, which means
1334 					 * that salvage will not detect the
1335 					 * correct name length (unless the name
1336 					 * has a length that's an exact
1337 					 * multiple of four bytes), and it'll
1338 					 * discard the entry (unnecessarily)
1339 					 * and the rest of the dirent block.
1340 					 * Therefore, swap the rest of the
1341 					 * block back to disk order, run
1342 					 * salvage, and re-swap anything after
1343 					 * the salvaged dirent.
1344 					 */
1345 					int need_reswab = 0;
1346 					if (rec_len < EXT2_DIR_ENTRY_HEADER_LEN || rec_len % 4) {
1347 						need_reswab = 1;
1348 						ext2fs_dirent_swab_in2(fs,
1349 							((char *)dirent) + EXT2_DIR_ENTRY_HEADER_LEN,
1350 							max_block_size - offset - EXT2_DIR_ENTRY_HEADER_LEN,
1351 							0);
1352 					}
1353 #endif
1354 					salvage_directory(fs, dirent, prev,
1355 							  &offset,
1356 							  max_block_size,
1357 							  hash_in_dirent);
1358 #ifdef WORDS_BIGENDIAN
1359 					if (need_reswab) {
1360 						(void) ext2fs_get_rec_len(fs,
1361 							dirent, &rec_len);
1362 						ext2fs_dirent_swab_in2(fs,
1363 							((char *)dirent) + offset + rec_len,
1364 							max_block_size - offset - rec_len,
1365 							0);
1366 					}
1367 #endif
1368 					dir_modified++;
1369 					continue;
1370 				} else
1371 					goto abort_free_dict;
1372 			}
1373 		} else {
1374 			if (dot_state == 0) {
1375 				memset(&dot, 0, sizeof(dot));
1376 				dirent = &dot;
1377 				dirent->inode = ino;
1378 				dirent->rec_len = EXT2_DIR_REC_LEN(1);
1379 				dirent->name_len = 1 | filetype;
1380 				dirent->name[0] = '.';
1381 			} else if (dot_state == 1) {
1382 				memset(&dotdot, 0, sizeof(dotdot));
1383 				dirent = &dotdot;
1384 				dirent->inode =
1385 					((struct ext2_dir_entry *)buf)->inode;
1386 				dirent->rec_len = EXT2_DIR_REC_LEN(2);
1387 				dirent->name_len = 2 | filetype;
1388 				dirent->name[0] = '.';
1389 				dirent->name[1] = '.';
1390 			} else {
1391 				fatal_error(ctx, _("Can not continue."));
1392 			}
1393 			cd->pctx.dirent = dirent;
1394 			cd->pctx.num = offset;
1395 		}
1396 
1397 		if (dot_state == 0) {
1398 			if (check_dot(ctx, dirent, ino, &cd->pctx))
1399 				dir_modified++;
1400 		} else if (dot_state == 1) {
1401 			ret = check_dotdot(ctx, dirent, ino, &cd->pctx);
1402 			if (ret < 0)
1403 				goto abort_free_dict;
1404 			if (ret)
1405 				dir_modified++;
1406 		} else if (dirent->inode == ino) {
1407 			problem = PR_2_LINK_DOT;
1408 			if (fix_problem(ctx, PR_2_LINK_DOT, &cd->pctx)) {
1409 				dirent->inode = 0;
1410 				dir_modified++;
1411 				goto next;
1412 			}
1413 		}
1414 		if (!dirent->inode)
1415 			goto next;
1416 
1417 		/*
1418 		 * Make sure the inode listed is a legal one.
1419 		 */
1420 		name_len = ext2fs_dirent_name_len(dirent);
1421 		if (((dirent->inode != EXT2_ROOT_INO) &&
1422 		     (dirent->inode < EXT2_FIRST_INODE(fs->super))) ||
1423 		    (dirent->inode > fs->super->s_inodes_count)) {
1424 			problem = PR_2_BAD_INO;
1425 		} else if (ctx->inode_bb_map &&
1426 			   (ext2fs_test_inode_bitmap2(ctx->inode_bb_map,
1427 						     dirent->inode))) {
1428 			/*
1429 			 * If the inode is in a bad block, offer to
1430 			 * clear it.
1431 			 */
1432 			problem = PR_2_BB_INODE;
1433 		} else if ((dot_state > 1) && (name_len == 1) &&
1434 			   (dirent->name[0] == '.')) {
1435 			/*
1436 			 * If there's a '.' entry in anything other
1437 			 * than the first directory entry, it's a
1438 			 * duplicate entry that should be removed.
1439 			 */
1440 			problem = PR_2_DUP_DOT;
1441 		} else if ((dot_state > 1) && (name_len == 2) &&
1442 			   (dirent->name[0] == '.') &&
1443 			   (dirent->name[1] == '.')) {
1444 			/*
1445 			 * If there's a '..' entry in anything other
1446 			 * than the second directory entry, it's a
1447 			 * duplicate entry that should be removed.
1448 			 */
1449 			problem = PR_2_DUP_DOT_DOT;
1450 		} else if ((dot_state > 1) &&
1451 			   (dirent->inode == EXT2_ROOT_INO)) {
1452 			/*
1453 			 * Don't allow links to the root directory.
1454 			 * We check this specially to make sure we
1455 			 * catch this error case even if the root
1456 			 * directory hasn't been created yet.
1457 			 */
1458 			problem = PR_2_LINK_ROOT;
1459 		} else if ((dot_state > 1) && (name_len == 0)) {
1460 			/*
1461 			 * Don't allow zero-length directory names.
1462 			 */
1463 			problem = PR_2_NULL_NAME;
1464 		}
1465 
1466 		if (problem) {
1467 			if (fix_problem(ctx, problem, &cd->pctx)) {
1468 				dirent->inode = 0;
1469 				dir_modified++;
1470 				goto next;
1471 			} else {
1472 				ext2fs_unmark_valid(fs);
1473 				if (problem == PR_2_BAD_INO)
1474 					goto next;
1475 			}
1476 		}
1477 
1478 		/*
1479 		 * If the inode was marked as having bad fields in
1480 		 * pass1, process it and offer to fix/clear it.
1481 		 * (We wait until now so that we can display the
1482 		 * pathname to the user.)
1483 		 */
1484 		if (ctx->inode_bad_map &&
1485 		    ext2fs_test_inode_bitmap2(ctx->inode_bad_map,
1486 					     dirent->inode)) {
1487 			if (e2fsck_process_bad_inode(ctx, ino,
1488 						     dirent->inode,
1489 						     buf + fs->blocksize)) {
1490 				dirent->inode = 0;
1491 				dir_modified++;
1492 				goto next;
1493 			}
1494 			if (ctx->flags & E2F_FLAG_SIGNAL_MASK)
1495 				return DIRENT_ABORT;
1496 		}
1497 
1498 		group = ext2fs_group_of_ino(fs, dirent->inode);
1499 		first_unused_inode = group * fs->super->s_inodes_per_group +
1500 					1 + fs->super->s_inodes_per_group -
1501 					ext2fs_bg_itable_unused(fs, group);
1502 		cd->pctx.group = group;
1503 
1504 		/*
1505 		 * Check if the inode was missed out because
1506 		 * _INODE_UNINIT flag was set or bg_itable_unused was
1507 		 * incorrect.  If so, clear the _INODE_UNINIT flag and
1508 		 * restart e2fsck.  In the future it would be nice if
1509 		 * we could call a function in pass1.c that checks the
1510 		 * newly visible inodes.
1511 		 */
1512 		if (ext2fs_bg_flags_test(fs, group, EXT2_BG_INODE_UNINIT)) {
1513 			pctx.num = dirent->inode;
1514 			if (fix_problem(ctx, PR_2_INOREF_BG_INO_UNINIT,
1515 					&cd->pctx)){
1516 				ext2fs_bg_flags_clear(fs, group,
1517 						      EXT2_BG_INODE_UNINIT);
1518 				ext2fs_mark_super_dirty(fs);
1519 				ctx->flags |= E2F_FLAG_RESTART_LATER;
1520 			} else {
1521 				ext2fs_unmark_valid(fs);
1522 				if (problem == PR_2_BAD_INO)
1523 					goto next;
1524 			}
1525 		} else if (dirent->inode >= first_unused_inode) {
1526 			pctx.num = dirent->inode;
1527 			if (fix_problem(ctx, PR_2_INOREF_IN_UNUSED, &cd->pctx)){
1528 				ext2fs_bg_itable_unused_set(fs, group, 0);
1529 				ext2fs_mark_super_dirty(fs);
1530 				ctx->flags |= E2F_FLAG_RESTART_LATER;
1531 			} else {
1532 				ext2fs_unmark_valid(fs);
1533 				if (problem == PR_2_BAD_INO)
1534 					goto next;
1535 			}
1536 		}
1537 
1538 		/*
1539 		 * Offer to clear unused inodes; if we are going to be
1540 		 * restarting the scan due to bg_itable_unused being
1541 		 * wrong, then don't clear any inodes to avoid zapping
1542 		 * inodes that were skipped during pass1 due to an
1543 		 * incorrect bg_itable_unused; we'll get any real
1544 		 * problems after we restart.
1545 		 */
1546 		if (!(ctx->flags & E2F_FLAG_RESTART_LATER) &&
1547 		    !(ext2fs_test_inode_bitmap2(ctx->inode_used_map,
1548 						dirent->inode)))
1549 			problem = PR_2_UNUSED_INODE;
1550 
1551 		if (problem) {
1552 			if (fix_problem(ctx, problem, &cd->pctx)) {
1553 				dirent->inode = 0;
1554 				dir_modified++;
1555 				goto next;
1556 			} else {
1557 				ext2fs_unmark_valid(fs);
1558 				if (problem == PR_2_BAD_INO)
1559 					goto next;
1560 			}
1561 		}
1562 
1563 		if (check_filetype(ctx, dirent, ino, &cd->pctx))
1564 			dir_modified++;
1565 
1566 		if (dir_encpolicy_id != NO_ENCRYPTION_POLICY) {
1567 			/* Encrypted directory */
1568 			if (dot_state > 1 &&
1569 			    check_encrypted_dirent(ctx, dirent,
1570 						   dir_encpolicy_id,
1571 						   &cd->pctx)) {
1572 				dirent->inode = 0;
1573 				dir_modified++;
1574 				goto next;
1575 			}
1576 		} else if (cf_dir) {
1577 			/* Casefolded directory */
1578 			if (encoded_check_name(ctx, dirent, &cd->pctx))
1579 				dir_modified++;
1580 		} else {
1581 			/* Unencrypted and uncasefolded directory */
1582 			if (check_name(ctx, dirent, &cd->pctx))
1583 				dir_modified++;
1584 		}
1585 
1586 		if (dx_db) {
1587 			if (dx_dir->casefolded_hash)
1588 				hash_flags = EXT4_CASEFOLD_FL;
1589 
1590 			if (dx_dir->hashversion == EXT2_HASH_SIPHASH) {
1591 				if (dot_state > 1)
1592 					hash = EXT2_DIRENT_HASH(dirent);
1593 			} else {
1594 				ext2fs_dirhash2(dx_dir->hashversion,
1595 						dirent->name,
1596 						ext2fs_dirent_name_len(dirent),
1597 						fs->encoding, hash_flags,
1598 						fs->super->s_hash_seed,
1599 						&hash, 0);
1600 			}
1601 			if (hash < dx_db->min_hash)
1602 				dx_db->min_hash = hash;
1603 			if (hash > dx_db->max_hash)
1604 				dx_db->max_hash = hash;
1605 		}
1606 
1607 		/*
1608 		 * If this is a directory, then mark its parent in its
1609 		 * dir_info structure.  If the parent field is already
1610 		 * filled in, then this directory has more than one
1611 		 * hard link.  We assume the first link is correct,
1612 		 * and ask the user if he/she wants to clear this one.
1613 		 */
1614 		if ((dot_state > 1) &&
1615 		    (ext2fs_test_inode_bitmap2(ctx->inode_dir_map,
1616 					      dirent->inode))) {
1617 			if (e2fsck_dir_info_get_parent(ctx, dirent->inode,
1618 						       &subdir_parent)) {
1619 				cd->pctx.ino = dirent->inode;
1620 				fix_problem(ctx, PR_2_NO_DIRINFO, &cd->pctx);
1621 				goto abort_free_dict;
1622 			}
1623 			if (subdir_parent) {
1624 				cd->pctx.ino2 = subdir_parent;
1625 				if (fix_problem(ctx, PR_2_LINK_DIR,
1626 						&cd->pctx)) {
1627 					dirent->inode = 0;
1628 					dir_modified++;
1629 					goto next;
1630 				}
1631 				cd->pctx.ino2 = 0;
1632 			} else {
1633 				(void) e2fsck_dir_info_set_parent(ctx,
1634 						  dirent->inode, ino);
1635 			}
1636 		}
1637 
1638 		if (dups_found) {
1639 			;
1640 		} else if (dict_lookup(&de_dict, dirent)) {
1641 			clear_problem_context(&pctx);
1642 			pctx.ino = ino;
1643 			pctx.dirent = dirent;
1644 			fix_problem(ctx, PR_2_REPORT_DUP_DIRENT, &pctx);
1645 			e2fsck_rehash_dir_later(ctx, ino);
1646 			dups_found++;
1647 		} else
1648 			dict_alloc_insert(&de_dict, dirent, dirent);
1649 
1650 		ext2fs_icount_increment(ctx->inode_count, dirent->inode,
1651 					&links);
1652 		if (links > 1)
1653 			ctx->fs_links_count++;
1654 		ctx->fs_total_count++;
1655 	next:
1656 		prev = dirent;
1657 		if (dir_modified)
1658 			(void) ext2fs_get_rec_len(fs, dirent, &rec_len);
1659 		if (!inline_data_size || dot_state > 1) {
1660 			offset += rec_len;
1661 		} else {
1662 			if (dot_state == 1) {
1663 				offset = 4;
1664 				/*
1665 				 * If we get here, we're checking an inline
1666 				 * directory and we've just checked a (fake)
1667 				 * dotdot entry that we created on the stack.
1668 				 * Therefore set 'prev' to NULL so that if we
1669 				 * call salvage_directory on the next entry,
1670 				 * it won't try to absorb the next entry into
1671 				 * the on-stack dotdot entry.
1672 				 */
1673 				prev = NULL;
1674 			}
1675 		}
1676 		dot_state++;
1677 	} while (offset < max_block_size);
1678 #if 0
1679 	printf("\n");
1680 #endif
1681 	if (dx_db) {
1682 #ifdef DX_DEBUG
1683 		printf("db_block %d, type %d, min_hash 0x%0x, max_hash 0x%0x\n",
1684 		       db->blockcnt, dx_db->type,
1685 		       dx_db->min_hash, dx_db->max_hash);
1686 #endif
1687 		cd->pctx.dir = cd->pctx.ino;
1688 		if ((dx_db->type == DX_DIRBLOCK_ROOT) ||
1689 		    (dx_db->type == DX_DIRBLOCK_NODE))
1690 			parse_int_node(fs, db, cd, dx_dir, buf, failed_csum);
1691 	}
1692 
1693 	if (offset != max_block_size) {
1694 		cd->pctx.num = rec_len + offset - max_block_size;
1695 		if (fix_problem(ctx, PR_2_FINAL_RECLEN, &cd->pctx)) {
1696 			dirent->rec_len = cd->pctx.num;
1697 			dir_modified++;
1698 		}
1699 	}
1700 	if (dir_modified) {
1701 		int	flags, will_rehash;
1702 		/* leaf block with no tail?  Rehash dirs later. */
1703 		if (ext2fs_has_feature_metadata_csum(fs->super) &&
1704 		    is_leaf &&
1705 		    !inline_data_size &&
1706 		    !ext2fs_dirent_has_tail(fs, (struct ext2_dir_entry *)buf)) {
1707 			if (insert_dirent_tail(fs, buf) == 0)
1708 				goto write_and_fix;
1709 			e2fsck_rehash_dir_later(ctx, ino);
1710 		}
1711 
1712 write_and_fix:
1713 		will_rehash = e2fsck_dir_will_be_rehashed(ctx, ino);
1714 		if (will_rehash) {
1715 			flags = ctx->fs->flags;
1716 			ctx->fs->flags |= EXT2_FLAG_IGNORE_CSUM_ERRORS;
1717 		}
1718 		if (inline_data_size) {
1719 			buf = ibuf;
1720 #ifdef WORDS_BIGENDIAN
1721 			if (db->blockcnt)
1722 				goto skip_first_write_swab;
1723 			*((__u32 *)buf) = ext2fs_le32_to_cpu(*((__u32 *)buf));
1724 			cd->pctx.errcode = ext2fs_dirent_swab_out2(fs,
1725 					buf + EXT4_INLINE_DATA_DOTDOT_SIZE,
1726 					EXT4_MIN_INLINE_DATA_SIZE -
1727 					EXT4_INLINE_DATA_DOTDOT_SIZE,
1728 					0);
1729 			if (cd->pctx.errcode)
1730 				goto skip_second_write_swab;
1731 skip_first_write_swab:
1732 			if (inline_data_size <= EXT4_MIN_INLINE_DATA_SIZE ||
1733 			    !db->blockcnt)
1734 				goto skip_second_write_swab;
1735 			cd->pctx.errcode = ext2fs_dirent_swab_out2(fs,
1736 					buf + EXT4_MIN_INLINE_DATA_SIZE,
1737 					inline_data_size -
1738 					EXT4_MIN_INLINE_DATA_SIZE,
1739 					0);
1740 skip_second_write_swab:
1741 			if (cd->pctx.errcode &&
1742 			    !fix_problem(ctx, PR_2_WRITE_DIRBLOCK, &cd->pctx))
1743 				goto abort_free_dict;
1744 #endif
1745 			cd->pctx.errcode =
1746 				ext2fs_inline_data_set(fs, ino, 0, buf,
1747 						       inline_data_size);
1748 		} else
1749 			cd->pctx.errcode = ext2fs_write_dir_block4(fs, block_nr,
1750 								   buf, 0, ino);
1751 		if (will_rehash)
1752 			ctx->fs->flags = (flags &
1753 					  EXT2_FLAG_IGNORE_CSUM_ERRORS) |
1754 					 (ctx->fs->flags &
1755 					  ~EXT2_FLAG_IGNORE_CSUM_ERRORS);
1756 		if (cd->pctx.errcode) {
1757 			if (!fix_problem(ctx, PR_2_WRITE_DIRBLOCK,
1758 					 &cd->pctx))
1759 				goto abort_free_dict;
1760 		}
1761 		ext2fs_mark_changed(fs);
1762 	} else if (is_leaf && failed_csum && !dir_modified) {
1763 		/*
1764 		 * If a leaf node that fails csum makes it this far without
1765 		 * alteration, ask the user if the checksum should be fixed.
1766 		 */
1767 		if (fix_problem(ctx, PR_2_LEAF_NODE_ONLY_CSUM_INVALID,
1768 				&cd->pctx))
1769 			goto write_and_fix;
1770 	}
1771 	dict_free_nodes(&de_dict);
1772 	return 0;
1773 abort_free_dict:
1774 	ctx->flags |= E2F_FLAG_ABORT;
1775 	dict_free_nodes(&de_dict);
1776 	return DIRENT_ABORT;
1777 }
1778 
1779 struct del_block {
1780 	e2fsck_t	ctx;
1781 	e2_blkcnt_t	num;
1782 	blk64_t last_cluster;
1783 };
1784 
1785 /*
1786  * This function is called to deallocate a block, and is an interator
1787  * functioned called by deallocate inode via ext2fs_iterate_block().
1788  */
deallocate_inode_block(ext2_filsys fs,blk64_t * block_nr,e2_blkcnt_t blockcnt EXT2FS_ATTR ((unused)),blk64_t ref_block EXT2FS_ATTR ((unused)),int ref_offset EXT2FS_ATTR ((unused)),void * priv_data)1789 static int deallocate_inode_block(ext2_filsys fs,
1790 				  blk64_t	*block_nr,
1791 				  e2_blkcnt_t blockcnt EXT2FS_ATTR((unused)),
1792 				  blk64_t ref_block EXT2FS_ATTR((unused)),
1793 				  int ref_offset EXT2FS_ATTR((unused)),
1794 				  void *priv_data)
1795 {
1796 	struct del_block *p = priv_data;
1797 	blk64_t cluster = EXT2FS_B2C(fs, *block_nr);
1798 
1799 	if (*block_nr == 0)
1800 		return 0;
1801 
1802 	if (cluster == p->last_cluster)
1803 		return 0;
1804 
1805 	p->last_cluster = cluster;
1806 	if ((*block_nr < fs->super->s_first_data_block) ||
1807 	    (*block_nr >= ext2fs_blocks_count(fs->super)))
1808 		return 0;
1809 
1810         ext2fs_block_alloc_stats2(fs, *block_nr, -1);
1811 	p->num++;
1812 	return 0;
1813 }
1814 
1815 /*
1816  * This function deallocates an inode
1817  */
deallocate_inode(e2fsck_t ctx,ext2_ino_t ino,char * block_buf)1818 static void deallocate_inode(e2fsck_t ctx, ext2_ino_t ino, char* block_buf)
1819 {
1820 	ext2_filsys fs = ctx->fs;
1821 	struct ext2_inode	inode;
1822 	struct problem_context	pctx;
1823 	__u32			count;
1824 	struct del_block	del_block;
1825 
1826 	e2fsck_read_inode(ctx, ino, &inode, "deallocate_inode");
1827 	clear_problem_context(&pctx);
1828 	pctx.ino = ino;
1829 
1830 	/*
1831 	 * Fix up the bitmaps...
1832 	 */
1833 	e2fsck_read_bitmaps(ctx);
1834 	ext2fs_inode_alloc_stats2(fs, ino, -1, LINUX_S_ISDIR(inode.i_mode));
1835 
1836 	if (ext2fs_file_acl_block(fs, &inode) &&
1837 	    ext2fs_has_feature_xattr(fs->super)) {
1838 		pctx.errcode = ext2fs_adjust_ea_refcount3(fs,
1839 				ext2fs_file_acl_block(fs, &inode),
1840 				block_buf, -1, &count, ino);
1841 		if (pctx.errcode == EXT2_ET_BAD_EA_BLOCK_NUM) {
1842 			pctx.errcode = 0;
1843 			count = 1;
1844 		}
1845 		if (pctx.errcode) {
1846 			pctx.blk = ext2fs_file_acl_block(fs, &inode);
1847 			fix_problem(ctx, PR_2_ADJ_EA_REFCOUNT, &pctx);
1848 			ctx->flags |= E2F_FLAG_ABORT;
1849 			return;
1850 		}
1851 		if (count == 0) {
1852 			ext2fs_block_alloc_stats2(fs,
1853 				  ext2fs_file_acl_block(fs, &inode), -1);
1854 		}
1855 		ext2fs_file_acl_block_set(fs, &inode, 0);
1856 	}
1857 
1858 	if (!ext2fs_inode_has_valid_blocks2(fs, &inode))
1859 		goto clear_inode;
1860 
1861 	/* Inline data inodes don't have blocks to iterate */
1862 	if (inode.i_flags & EXT4_INLINE_DATA_FL)
1863 		goto clear_inode;
1864 
1865 	if (ext2fs_needs_large_file_feature(EXT2_I_SIZE(&inode))) {
1866 		if (LINUX_S_ISREG(inode.i_mode))
1867 		    ctx->large_files--;
1868 		else if (LINUX_S_ISDIR(inode.i_mode))
1869 		    ctx->large_dirs--;
1870 	}
1871 
1872 	del_block.ctx = ctx;
1873 	del_block.num = 0;
1874 	del_block.last_cluster = 0;
1875 	pctx.errcode = ext2fs_block_iterate3(fs, ino, 0, block_buf,
1876 					     deallocate_inode_block,
1877 					     &del_block);
1878 	if (pctx.errcode) {
1879 		fix_problem(ctx, PR_2_DEALLOC_INODE, &pctx);
1880 		ctx->flags |= E2F_FLAG_ABORT;
1881 		return;
1882 	}
1883 clear_inode:
1884 	/* Inode may have changed by block_iterate, so reread it */
1885 	e2fsck_read_inode(ctx, ino, &inode, "deallocate_inode");
1886 	e2fsck_clear_inode(ctx, ino, &inode, 0, "deallocate_inode");
1887 }
1888 
1889 /*
1890  * This function clears the htree flag on an inode
1891  */
clear_htree(e2fsck_t ctx,ext2_ino_t ino)1892 static void clear_htree(e2fsck_t ctx, ext2_ino_t ino)
1893 {
1894 	struct ext2_inode	inode;
1895 
1896 	e2fsck_read_inode(ctx, ino, &inode, "clear_htree");
1897 	inode.i_flags = inode.i_flags & ~EXT2_INDEX_FL;
1898 	e2fsck_write_inode(ctx, ino, &inode, "clear_htree");
1899 	if (ctx->dirs_to_hash)
1900 		ext2fs_u32_list_add(ctx->dirs_to_hash, ino);
1901 }
1902 
1903 
e2fsck_process_bad_inode(e2fsck_t ctx,ext2_ino_t dir,ext2_ino_t ino,char * buf)1904 int e2fsck_process_bad_inode(e2fsck_t ctx, ext2_ino_t dir,
1905 			     ext2_ino_t ino, char *buf)
1906 {
1907 	ext2_filsys fs = ctx->fs;
1908 	struct ext2_inode	inode;
1909 	int			inode_modified = 0;
1910 	int			not_fixed = 0;
1911 	unsigned char		*frag, *fsize;
1912 	struct problem_context	pctx;
1913 	problem_t		problem = 0;
1914 
1915 	e2fsck_read_inode(ctx, ino, &inode, "process_bad_inode");
1916 
1917 	clear_problem_context(&pctx);
1918 	pctx.ino = ino;
1919 	pctx.dir = dir;
1920 	pctx.inode = &inode;
1921 
1922 	if (ext2fs_file_acl_block(fs, &inode) &&
1923 	    !ext2fs_has_feature_xattr(fs->super)) {
1924 		if (fix_problem(ctx, PR_2_FILE_ACL_ZERO, &pctx)) {
1925 			ext2fs_file_acl_block_set(fs, &inode, 0);
1926 			inode_modified++;
1927 		} else
1928 			not_fixed++;
1929 	}
1930 
1931 	if (!LINUX_S_ISDIR(inode.i_mode) && !LINUX_S_ISREG(inode.i_mode) &&
1932 	    !LINUX_S_ISCHR(inode.i_mode) && !LINUX_S_ISBLK(inode.i_mode) &&
1933 	    !LINUX_S_ISLNK(inode.i_mode) && !LINUX_S_ISFIFO(inode.i_mode) &&
1934 	    !(LINUX_S_ISSOCK(inode.i_mode)))
1935 		problem = PR_2_BAD_MODE;
1936 	else if (LINUX_S_ISCHR(inode.i_mode)
1937 		 && !e2fsck_pass1_check_device_inode(fs, &inode))
1938 		problem = PR_2_BAD_CHAR_DEV;
1939 	else if (LINUX_S_ISBLK(inode.i_mode)
1940 		 && !e2fsck_pass1_check_device_inode(fs, &inode))
1941 		problem = PR_2_BAD_BLOCK_DEV;
1942 	else if (LINUX_S_ISFIFO(inode.i_mode)
1943 		 && !e2fsck_pass1_check_device_inode(fs, &inode))
1944 		problem = PR_2_BAD_FIFO;
1945 	else if (LINUX_S_ISSOCK(inode.i_mode)
1946 		 && !e2fsck_pass1_check_device_inode(fs, &inode))
1947 		problem = PR_2_BAD_SOCKET;
1948 	else if (LINUX_S_ISLNK(inode.i_mode)
1949 		 && !e2fsck_pass1_check_symlink(fs, ino, &inode, buf)) {
1950 		problem = PR_2_INVALID_SYMLINK;
1951 	}
1952 
1953 	if (problem) {
1954 		if (fix_problem(ctx, problem, &pctx)) {
1955 			deallocate_inode(ctx, ino, 0);
1956 			if (ctx->flags & E2F_FLAG_SIGNAL_MASK)
1957 				return 0;
1958 			return 1;
1959 		} else
1960 			not_fixed++;
1961 		problem = 0;
1962 	}
1963 
1964 	if (inode.i_faddr) {
1965 		if (fix_problem(ctx, PR_2_FADDR_ZERO, &pctx)) {
1966 			inode.i_faddr = 0;
1967 			inode_modified++;
1968 		} else
1969 			not_fixed++;
1970 	}
1971 
1972 	switch (fs->super->s_creator_os) {
1973 	    case EXT2_OS_HURD:
1974 		frag = &inode.osd2.hurd2.h_i_frag;
1975 		fsize = &inode.osd2.hurd2.h_i_fsize;
1976 		break;
1977 	    default:
1978 		frag = fsize = 0;
1979 	}
1980 	if (frag && *frag) {
1981 		pctx.num = *frag;
1982 		if (fix_problem(ctx, PR_2_FRAG_ZERO, &pctx)) {
1983 			*frag = 0;
1984 			inode_modified++;
1985 		} else
1986 			not_fixed++;
1987 		pctx.num = 0;
1988 	}
1989 	if (fsize && *fsize) {
1990 		pctx.num = *fsize;
1991 		if (fix_problem(ctx, PR_2_FSIZE_ZERO, &pctx)) {
1992 			*fsize = 0;
1993 			inode_modified++;
1994 		} else
1995 			not_fixed++;
1996 		pctx.num = 0;
1997 	}
1998 
1999 	if ((fs->super->s_creator_os == EXT2_OS_LINUX) &&
2000 	    !ext2fs_has_feature_huge_file(fs->super) &&
2001 	    (inode.osd2.linux2.l_i_blocks_hi != 0)) {
2002 		pctx.num = inode.osd2.linux2.l_i_blocks_hi;
2003 		if (fix_problem(ctx, PR_2_BLOCKS_HI_ZERO, &pctx)) {
2004 			inode.osd2.linux2.l_i_blocks_hi = 0;
2005 			inode_modified++;
2006 		}
2007 	}
2008 
2009 	if ((fs->super->s_creator_os == EXT2_OS_LINUX) &&
2010 	    !ext2fs_has_feature_64bit(fs->super) &&
2011 	    inode.osd2.linux2.l_i_file_acl_high != 0) {
2012 		pctx.num = inode.osd2.linux2.l_i_file_acl_high;
2013 		if (fix_problem(ctx, PR_2_I_FILE_ACL_HI_ZERO, &pctx)) {
2014 			inode.osd2.linux2.l_i_file_acl_high = 0;
2015 			inode_modified++;
2016 		} else
2017 			not_fixed++;
2018 	}
2019 
2020 	if (ext2fs_file_acl_block(fs, &inode) &&
2021 	    ((ext2fs_file_acl_block(fs, &inode) < fs->super->s_first_data_block) ||
2022 	     (ext2fs_file_acl_block(fs, &inode) >= ext2fs_blocks_count(fs->super)))) {
2023 		if (fix_problem(ctx, PR_2_FILE_ACL_BAD, &pctx)) {
2024 			ext2fs_file_acl_block_set(fs, &inode, 0);
2025 			inode_modified++;
2026 		} else
2027 			not_fixed++;
2028 	}
2029 	if (inode.i_size_high && !ext2fs_has_feature_largedir(fs->super) &&
2030 	    inode.i_blocks < 1ULL << (29 - EXT2_BLOCK_SIZE_BITS(fs->super)) &&
2031 	    LINUX_S_ISDIR(inode.i_mode)) {
2032 		if (fix_problem(ctx, PR_2_DIR_SIZE_HIGH_ZERO, &pctx)) {
2033 			inode.i_size_high = 0;
2034 			inode_modified++;
2035 		} else
2036 			not_fixed++;
2037 	}
2038 
2039 	if (inode_modified)
2040 		e2fsck_write_inode(ctx, ino, &inode, "process_bad_inode");
2041 	if (!not_fixed && ctx->inode_bad_map)
2042 		ext2fs_unmark_inode_bitmap2(ctx->inode_bad_map, ino);
2043 	return 0;
2044 }
2045 
2046 /*
2047  * allocate_dir_block --- this function allocates a new directory
2048  * 	block for a particular inode; this is done if a directory has
2049  * 	a "hole" in it, or if a directory has a illegal block number
2050  * 	that was zeroed out and now needs to be replaced.
2051  */
allocate_dir_block(e2fsck_t ctx,struct ext2_db_entry2 * db,char * buf EXT2FS_ATTR ((unused)),struct problem_context * pctx)2052 static int allocate_dir_block(e2fsck_t ctx,
2053 			      struct ext2_db_entry2 *db,
2054 			      char *buf EXT2FS_ATTR((unused)),
2055 			      struct problem_context *pctx)
2056 {
2057 	ext2_filsys fs = ctx->fs;
2058 	blk64_t			blk = 0;
2059 	char			*block;
2060 	struct ext2_inode	inode;
2061 
2062 	if (fix_problem(ctx, PR_2_DIRECTORY_HOLE, pctx) == 0)
2063 		return 1;
2064 
2065 	/*
2066 	 * Read the inode and block bitmaps in; we'll be messing with
2067 	 * them.
2068 	 */
2069 	e2fsck_read_bitmaps(ctx);
2070 
2071 	/*
2072 	 * First, find a free block
2073 	 */
2074 	e2fsck_read_inode(ctx, db->ino, &inode, "allocate_dir_block");
2075 	pctx->errcode = ext2fs_map_cluster_block(fs, db->ino, &inode,
2076 						 db->blockcnt, &blk);
2077 	if (pctx->errcode || blk == 0) {
2078 		blk = ext2fs_find_inode_goal(fs, db->ino, &inode, db->blockcnt);
2079 		pctx->errcode = ext2fs_new_block2(fs, blk,
2080 						  ctx->block_found_map, &blk);
2081 		if (pctx->errcode) {
2082 			pctx->str = "ext2fs_new_block";
2083 			fix_problem(ctx, PR_2_ALLOC_DIRBOCK, pctx);
2084 			return 1;
2085 		}
2086 	}
2087 	ext2fs_mark_block_bitmap2(ctx->block_found_map, blk);
2088 	ext2fs_mark_block_bitmap2(fs->block_map, blk);
2089 	ext2fs_mark_bb_dirty(fs);
2090 
2091 	/*
2092 	 * Now let's create the actual data block for the inode
2093 	 */
2094 	if (db->blockcnt)
2095 		pctx->errcode = ext2fs_new_dir_block(fs, 0, 0, &block);
2096 	else
2097 		pctx->errcode = ext2fs_new_dir_block(fs, db->ino,
2098 						     EXT2_ROOT_INO, &block);
2099 
2100 	if (pctx->errcode) {
2101 		pctx->str = "ext2fs_new_dir_block";
2102 		fix_problem(ctx, PR_2_ALLOC_DIRBOCK, pctx);
2103 		return 1;
2104 	}
2105 
2106 	pctx->errcode = ext2fs_write_dir_block4(fs, blk, block, 0, db->ino);
2107 	ext2fs_free_mem(&block);
2108 	if (pctx->errcode) {
2109 		pctx->str = "ext2fs_write_dir_block";
2110 		fix_problem(ctx, PR_2_ALLOC_DIRBOCK, pctx);
2111 		return 1;
2112 	}
2113 
2114 	/*
2115 	 * Update the inode block count
2116 	 */
2117 	ext2fs_iblk_add_blocks(fs, &inode, 1);
2118 	if (EXT2_I_SIZE(&inode) < ((__u64) db->blockcnt+1) * fs->blocksize) {
2119 		pctx->errcode = ext2fs_inode_size_set(fs, &inode,
2120 					(db->blockcnt+1) * fs->blocksize);
2121 		if (pctx->errcode) {
2122 			pctx->str = "ext2fs_inode_size_set";
2123 			fix_problem(ctx, PR_2_ALLOC_DIRBOCK, pctx);
2124 			return 1;
2125 		}
2126 	}
2127 	e2fsck_write_inode(ctx, db->ino, &inode, "allocate_dir_block");
2128 
2129 	/*
2130 	 * Finally, update the block pointers for the inode
2131 	 */
2132 	db->blk = blk;
2133 	pctx->errcode = ext2fs_bmap2(fs, db->ino, &inode, 0, BMAP_SET,
2134 				     db->blockcnt, 0, &blk);
2135 	if (pctx->errcode) {
2136 		pctx->str = "ext2fs_block_iterate";
2137 		fix_problem(ctx, PR_2_ALLOC_DIRBOCK, pctx);
2138 		return 1;
2139 	}
2140 
2141 	return 0;
2142 }
2143