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