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