• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * rehash.c --- rebuild hash tree directories
3  *
4  * Copyright (C) 2002 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  * This algorithm is designed for simplicity of implementation and to
12  * pack the directory as much as possible.  It however requires twice
13  * as much memory as the size of the directory.  The maximum size
14  * directory supported using a 4k blocksize is roughly a gigabyte, and
15  * so there may very well be problems with machines that don't have
16  * virtual memory, and obscenely large directories.
17  *
18  * An alternate algorithm which is much more disk intensive could be
19  * written, and probably will need to be written in the future.  The
20  * design goals of such an algorithm are: (a) use (roughly) constant
21  * amounts of memory, no matter how large the directory, (b) the
22  * directory must be safe at all times, even if e2fsck is interrupted
23  * in the middle, (c) we must use minimal amounts of extra disk
24  * blocks.  This pretty much requires an incremental approach, where
25  * we are reading from one part of the directory, and inserting into
26  * the front half.  So the algorithm will have to keep track of a
27  * moving block boundary between the new tree and the old tree, and
28  * files will need to be moved from the old directory and inserted
29  * into the new tree.  If the new directory requires space which isn't
30  * yet available, blocks from the beginning part of the old directory
31  * may need to be moved to the end of the directory to make room for
32  * the new tree:
33  *
34  *    --------------------------------------------------------
35  *    |  new tree   |        | old tree                      |
36  *    --------------------------------------------------------
37  *                  ^ ptr    ^ptr
38  *                tail new   head old
39  *
40  * This is going to be a pain in the tuckus to implement, and will
41  * require a lot more disk accesses.  So I'm going to skip it for now;
42  * it's only really going to be an issue for really, really big
43  * filesystems (when we reach the level of tens of millions of files
44  * in a single directory).  It will probably be easier to simply
45  * require that e2fsck use VM first.
46  */
47 
48 #include "config.h"
49 #include <string.h>
50 #include <ctype.h>
51 #include <errno.h>
52 #include "e2fsck.h"
53 #include "problem.h"
54 
55 /* Schedule a dir to be rebuilt during pass 3A. */
e2fsck_rehash_dir_later(e2fsck_t ctx,ext2_ino_t ino)56 void e2fsck_rehash_dir_later(e2fsck_t ctx, ext2_ino_t ino)
57 {
58 	if (!ctx->dirs_to_hash)
59 		ext2fs_u32_list_create(&ctx->dirs_to_hash, 50);
60 	if (ctx->dirs_to_hash)
61 		ext2fs_u32_list_add(ctx->dirs_to_hash, ino);
62 }
63 
64 /* Ask if a dir will be rebuilt during pass 3A. */
e2fsck_dir_will_be_rehashed(e2fsck_t ctx,ext2_ino_t ino)65 int e2fsck_dir_will_be_rehashed(e2fsck_t ctx, ext2_ino_t ino)
66 {
67 	if (ctx->options & E2F_OPT_COMPRESS_DIRS)
68 		return 1;
69 	if (!ctx->dirs_to_hash)
70 		return 0;
71 	return ext2fs_u32_list_test(ctx->dirs_to_hash, ino);
72 }
73 
74 #undef REHASH_DEBUG
75 
76 struct fill_dir_struct {
77 	char *buf;
78 	struct ext2_inode *inode;
79 	ext2_ino_t ino;
80 	errcode_t err;
81 	e2fsck_t ctx;
82 	struct hash_entry *harray;
83 	blk_t max_array, num_array;
84 	ext2_off64_t dir_size;
85 	int compress;
86 	ext2_ino_t parent;
87 	ext2_ino_t dir;
88 };
89 
90 struct hash_entry {
91 	ext2_dirhash_t	hash;
92 	ext2_dirhash_t	minor_hash;
93 	ino_t		ino;
94 	struct ext2_dir_entry	*dir;
95 };
96 
97 struct out_dir {
98 	blk_t		num;
99 	blk_t		max;
100 	char		*buf;
101 	ext2_dirhash_t	*hashes;
102 };
103 
fill_dir_block(ext2_filsys fs,blk64_t * block_nr,e2_blkcnt_t blockcnt,blk64_t ref_block EXT2FS_ATTR ((unused)),int ref_offset EXT2FS_ATTR ((unused)),void * priv_data)104 static int fill_dir_block(ext2_filsys fs,
105 			  blk64_t *block_nr,
106 			  e2_blkcnt_t blockcnt,
107 			  blk64_t ref_block EXT2FS_ATTR((unused)),
108 			  int ref_offset EXT2FS_ATTR((unused)),
109 			  void *priv_data)
110 {
111 	struct fill_dir_struct	*fd = (struct fill_dir_struct *) priv_data;
112 	struct hash_entry 	*new_array, *ent;
113 	struct ext2_dir_entry 	*dirent;
114 	char			*dir;
115 	unsigned int		offset, dir_offset, rec_len, name_len;
116 	int			hash_alg, hash_flags;
117 
118 	if (blockcnt < 0)
119 		return 0;
120 
121 	offset = blockcnt * fs->blocksize;
122 	if (offset + fs->blocksize > fd->inode->i_size) {
123 		fd->err = EXT2_ET_DIR_CORRUPTED;
124 		return BLOCK_ABORT;
125 	}
126 
127 	dir = (fd->buf+offset);
128 	if (*block_nr == 0) {
129 		memset(dir, 0, fs->blocksize);
130 		dirent = (struct ext2_dir_entry *) dir;
131 		(void) ext2fs_set_rec_len(fs, fs->blocksize, dirent);
132 	} else {
133 		int flags = fs->flags;
134 		fs->flags |= EXT2_FLAG_IGNORE_CSUM_ERRORS;
135 		fd->err = ext2fs_read_dir_block4(fs, *block_nr, dir, 0,
136 						 fd->dir);
137 		fs->flags = (flags & EXT2_FLAG_IGNORE_CSUM_ERRORS) |
138 			    (fs->flags & ~EXT2_FLAG_IGNORE_CSUM_ERRORS);
139 		if (fd->err)
140 			return BLOCK_ABORT;
141 	}
142 	hash_flags = fd->inode->i_flags & EXT4_CASEFOLD_FL;
143 	hash_alg = fs->super->s_def_hash_version;
144 	if ((hash_alg <= EXT2_HASH_TEA) &&
145 	    (fs->super->s_flags & EXT2_FLAGS_UNSIGNED_HASH))
146 		hash_alg += 3;
147 	/* While the directory block is "hot", index it. */
148 	dir_offset = 0;
149 	while (dir_offset < fs->blocksize) {
150 		dirent = (struct ext2_dir_entry *) (dir + dir_offset);
151 		(void) ext2fs_get_rec_len(fs, dirent, &rec_len);
152 		name_len = ext2fs_dirent_name_len(dirent);
153 		if (((dir_offset + rec_len) > fs->blocksize) ||
154 		    (rec_len < 8) ||
155 		    ((rec_len % 4) != 0) ||
156 		    (name_len + 8 > rec_len)) {
157 			fd->err = EXT2_ET_DIR_CORRUPTED;
158 			return BLOCK_ABORT;
159 		}
160 		dir_offset += rec_len;
161 		if (dirent->inode == 0)
162 			continue;
163 		if ((name_len) == 0) {
164 			fd->err = EXT2_ET_DIR_CORRUPTED;
165 			return BLOCK_ABORT;
166 		}
167 		if (!fd->compress && (name_len == 1) &&
168 		    (dirent->name[0] == '.'))
169 			continue;
170 		if (!fd->compress && (name_len == 2) &&
171 		    (dirent->name[0] == '.') && (dirent->name[1] == '.')) {
172 			fd->parent = dirent->inode;
173 			continue;
174 		}
175 		if (fd->num_array >= fd->max_array) {
176 			errcode_t retval;
177 
178 			retval = ext2fs_resize_array(sizeof(struct hash_entry),
179 						     fd->max_array,
180 						     fd->max_array + 500,
181 						     &fd->harray);
182 			if (retval) {
183 				fd->err = retval;
184 				return BLOCK_ABORT;
185 			}
186 			fd->max_array += 500;
187 		}
188 		ent = fd->harray + fd->num_array++;
189 		ent->dir = dirent;
190 		fd->dir_size += EXT2_DIR_REC_LEN(name_len);
191 		ent->ino = dirent->inode;
192 		if (fd->compress)
193 			ent->hash = ent->minor_hash = 0;
194 		else {
195 			fd->err = ext2fs_dirhash2(hash_alg,
196 						  dirent->name, name_len,
197 						  fs->encoding, hash_flags,
198 						  fs->super->s_hash_seed,
199 						  &ent->hash, &ent->minor_hash);
200 			if (fd->err)
201 				return BLOCK_ABORT;
202 		}
203 	}
204 
205 	return 0;
206 }
207 
208 /* Used for sorting the hash entry */
ino_cmp(const void * a,const void * b)209 static EXT2_QSORT_TYPE ino_cmp(const void *a, const void *b)
210 {
211 	const struct hash_entry *he_a = (const struct hash_entry *) a;
212 	const struct hash_entry *he_b = (const struct hash_entry *) b;
213 
214 	return (he_a->ino - he_b->ino);
215 }
216 
217 /* Used for sorting the hash entry */
name_cmp(const void * a,const void * b)218 static EXT2_QSORT_TYPE name_cmp(const void *a, const void *b)
219 {
220 	const struct hash_entry *he_a = (const struct hash_entry *) a;
221 	const struct hash_entry *he_b = (const struct hash_entry *) b;
222 	unsigned int he_a_len, he_b_len, min_len;
223 	int	ret;
224 
225 	he_a_len = ext2fs_dirent_name_len(he_a->dir);
226 	he_b_len = ext2fs_dirent_name_len(he_b->dir);
227 	min_len = he_a_len;
228 	if (min_len > he_b_len)
229 		min_len = he_b_len;
230 
231 	ret = memcmp(he_a->dir->name, he_b->dir->name, min_len);
232 	if (ret == 0) {
233 		if (he_a_len > he_b_len)
234 			ret = 1;
235 		else if (he_a_len < he_b_len)
236 			ret = -1;
237 		else
238 			ret = he_b->dir->inode - he_a->dir->inode;
239 	}
240 	return ret;
241 }
242 
243 /* Used for sorting the hash entry */
hash_cmp(const void * a,const void * b)244 static EXT2_QSORT_TYPE hash_cmp(const void *a, const void *b)
245 {
246 	const struct hash_entry *he_a = (const struct hash_entry *) a;
247 	const struct hash_entry *he_b = (const struct hash_entry *) b;
248 	int	ret;
249 
250 	if (he_a->hash > he_b->hash)
251 		ret = 1;
252 	else if (he_a->hash < he_b->hash)
253 		ret = -1;
254 	else {
255 		if (he_a->minor_hash > he_b->minor_hash)
256 			ret = 1;
257 		else if (he_a->minor_hash < he_b->minor_hash)
258 			ret = -1;
259 		else
260 			ret = name_cmp(a, b);
261 	}
262 	return ret;
263 }
264 
alloc_size_dir(ext2_filsys fs,struct out_dir * outdir,blk_t blocks)265 static errcode_t alloc_size_dir(ext2_filsys fs, struct out_dir *outdir,
266 				blk_t blocks)
267 {
268 	errcode_t retval;
269 
270 	if (outdir->max) {
271 		retval = ext2fs_resize_array(fs->blocksize, outdir->max, blocks,
272 					     &outdir->buf);
273 		if (retval)
274 			return retval;
275 		retval = ext2fs_resize_array(sizeof(ext2_dirhash_t),
276 					     outdir->max, blocks,
277 					     &outdir->hashes);
278 		if (retval)
279 			return retval;
280 	} else {
281 		retval = ext2fs_get_array(fs->blocksize, blocks, &outdir->buf);
282 		if (retval)
283 			return retval;
284 		retval = ext2fs_get_array(sizeof(ext2_dirhash_t), blocks,
285 					  &outdir->hashes);
286 		if (retval)
287 			return retval;
288 		outdir->num = 0;
289 	}
290 	outdir->max = blocks;
291 	return 0;
292 }
293 
free_out_dir(struct out_dir * outdir)294 static void free_out_dir(struct out_dir *outdir)
295 {
296 	free(outdir->buf);
297 	free(outdir->hashes);
298 	outdir->max = 0;
299 	outdir->num =0;
300 }
301 
get_next_block(ext2_filsys fs,struct out_dir * outdir,char ** ret)302 static errcode_t get_next_block(ext2_filsys fs, struct out_dir *outdir,
303 			 char ** ret)
304 {
305 	errcode_t	retval;
306 
307 	if (outdir->num >= outdir->max) {
308 		int increment = outdir->max / 10;
309 
310 		if (increment < 50)
311 			increment = 50;
312 		retval = alloc_size_dir(fs, outdir, outdir->max + increment);
313 		if (retval)
314 			return retval;
315 	}
316 	*ret = outdir->buf + (size_t)outdir->num++ * fs->blocksize;
317 	memset(*ret, 0, fs->blocksize);
318 	return 0;
319 }
320 
321 /*
322  * This function is used to make a unique filename.  We do this by
323  * appending ~0, and then incrementing the number.  However, we cannot
324  * expand the length of the filename beyond the padding available in
325  * the directory entry.
326  */
mutate_name(char * str,unsigned int * len)327 static void mutate_name(char *str, unsigned int *len)
328 {
329 	int i;
330 	unsigned int l = *len;
331 
332 	/*
333 	 * First check to see if it looks the name has been mutated
334 	 * already
335 	 */
336 	for (i = l-1; i > 0; i--) {
337 		if (!isdigit(str[i]))
338 			break;
339 	}
340 	if ((i == (int)l - 1) || (str[i] != '~')) {
341 		if (((l-1) & 3) < 2)
342 			l += 2;
343 		else
344 			l = (l+3) & ~3;
345 		str[l-2] = '~';
346 		str[l-1] = '0';
347 		*len = l;
348 		return;
349 	}
350 	for (i = l-1; i >= 0; i--) {
351 		if (isdigit(str[i])) {
352 			if (str[i] == '9')
353 				str[i] = '0';
354 			else {
355 				str[i]++;
356 				return;
357 			}
358 			continue;
359 		}
360 		if (i == 1) {
361 			if (str[0] == 'z')
362 				str[0] = 'A';
363 			else if (str[0] == 'Z') {
364 				str[0] = '~';
365 				str[1] = '0';
366 			} else
367 				str[0]++;
368 		} else if (i > 0) {
369 			str[i] = '1';
370 			str[i-1] = '~';
371 		} else {
372 			if (str[0] == '~')
373 				str[0] = 'a';
374 			else
375 				str[0]++;
376 		}
377 		break;
378 	}
379 }
380 
duplicate_search_and_fix(e2fsck_t ctx,ext2_filsys fs,ext2_ino_t ino,struct fill_dir_struct * fd)381 static int duplicate_search_and_fix(e2fsck_t ctx, ext2_filsys fs,
382 				    ext2_ino_t ino,
383 				    struct fill_dir_struct *fd)
384 {
385 	struct problem_context	pctx;
386 	struct hash_entry	*ent, *prev;
387 	blk_t			i, j;
388 	int			fixed = 0;
389 	char			new_name[256];
390 	unsigned int		new_len;
391 	int			hash_alg;
392 	int hash_flags = fd->inode->i_flags & EXT4_CASEFOLD_FL;
393 
394 	clear_problem_context(&pctx);
395 	pctx.ino = ino;
396 
397 	hash_alg = fs->super->s_def_hash_version;
398 	if ((hash_alg <= EXT2_HASH_TEA) &&
399 	    (fs->super->s_flags & EXT2_FLAGS_UNSIGNED_HASH))
400 		hash_alg += 3;
401 
402 	for (i=1; i < fd->num_array; i++) {
403 		ent = fd->harray + i;
404 		prev = ent - 1;
405 		if (!ent->dir->inode ||
406 		    (ext2fs_dirent_name_len(ent->dir) !=
407 		     ext2fs_dirent_name_len(prev->dir)) ||
408 		    memcmp(ent->dir->name, prev->dir->name,
409 			     ext2fs_dirent_name_len(ent->dir)))
410 			continue;
411 		pctx.dirent = ent->dir;
412 		if ((ent->dir->inode == prev->dir->inode) &&
413 		    fix_problem(ctx, PR_2_DUPLICATE_DIRENT, &pctx)) {
414 			e2fsck_adjust_inode_count(ctx, ent->dir->inode, -1);
415 			ent->dir->inode = 0;
416 			fixed++;
417 			continue;
418 		}
419 		new_len = ext2fs_dirent_name_len(ent->dir);
420 		if (new_len == 0) {
421 			 /* should never happen */
422 			ext2fs_unmark_valid(fs);
423 			continue;
424 		}
425 		memcpy(new_name, ent->dir->name, new_len);
426 		mutate_name(new_name, &new_len);
427 		for (j=0; j < fd->num_array; j++) {
428 			if ((i==j) ||
429 			    (new_len !=
430 			     (unsigned) ext2fs_dirent_name_len(fd->harray[j].dir)) ||
431 			    memcmp(new_name, fd->harray[j].dir->name, new_len))
432 				continue;
433 			mutate_name(new_name, &new_len);
434 
435 			j = -1;
436 		}
437 		new_name[new_len] = 0;
438 		pctx.str = new_name;
439 		if (fix_problem(ctx, PR_2_NON_UNIQUE_FILE, &pctx)) {
440 			memcpy(ent->dir->name, new_name, new_len);
441 			ext2fs_dirent_set_name_len(ent->dir, new_len);
442 			ext2fs_dirhash2(hash_alg, new_name, new_len,
443 					fs->encoding, hash_flags,
444 					fs->super->s_hash_seed,
445 					&ent->hash, &ent->minor_hash);
446 			fixed++;
447 		}
448 	}
449 	return fixed;
450 }
451 
452 
copy_dir_entries(e2fsck_t ctx,struct fill_dir_struct * fd,struct out_dir * outdir)453 static errcode_t copy_dir_entries(e2fsck_t ctx,
454 				  struct fill_dir_struct *fd,
455 				  struct out_dir *outdir)
456 {
457 	ext2_filsys 		fs = ctx->fs;
458 	errcode_t		retval;
459 	char			*block_start;
460 	struct hash_entry 	*ent;
461 	struct ext2_dir_entry	*dirent;
462 	unsigned int		rec_len, prev_rec_len, left, slack, offset;
463 	int			i;
464 	ext2_dirhash_t		prev_hash;
465 	int			csum_size = 0;
466 	struct			ext2_dir_entry_tail *t;
467 
468 	if (ctx->htree_slack_percentage == 255) {
469 		profile_get_uint(ctx->profile, "options",
470 				 "indexed_dir_slack_percentage",
471 				 0, 20,
472 				 &ctx->htree_slack_percentage);
473 		if (ctx->htree_slack_percentage > 100)
474 			ctx->htree_slack_percentage = 20;
475 	}
476 
477 	if (ext2fs_has_feature_metadata_csum(fs->super))
478 		csum_size = sizeof(struct ext2_dir_entry_tail);
479 
480 	outdir->max = 0;
481 	retval = alloc_size_dir(fs, outdir,
482 				(fd->dir_size / fs->blocksize) + 2);
483 	if (retval)
484 		return retval;
485 	outdir->num = fd->compress ? 0 : 1;
486 	offset = 0;
487 	outdir->hashes[0] = 0;
488 	prev_hash = 1;
489 	if ((retval = get_next_block(fs, outdir, &block_start)))
490 		return retval;
491 	dirent = (struct ext2_dir_entry *) block_start;
492 	prev_rec_len = 0;
493 	rec_len = 0;
494 	left = fs->blocksize - csum_size;
495 	slack = fd->compress ? 12 :
496 		((fs->blocksize - csum_size) * ctx->htree_slack_percentage)/100;
497 	if (slack < 12)
498 		slack = 12;
499 	for (i = 0; i < fd->num_array; i++) {
500 		ent = fd->harray + i;
501 		if (ent->dir->inode == 0)
502 			continue;
503 		rec_len = EXT2_DIR_REC_LEN(ext2fs_dirent_name_len(ent->dir));
504 		if (rec_len > left) {
505 			if (left) {
506 				left += prev_rec_len;
507 				retval = ext2fs_set_rec_len(fs, left, dirent);
508 				if (retval)
509 					return retval;
510 			}
511 			if (csum_size) {
512 				t = EXT2_DIRENT_TAIL(block_start,
513 						     fs->blocksize);
514 				ext2fs_initialize_dirent_tail(fs, t);
515 			}
516 			if ((retval = get_next_block(fs, outdir,
517 						      &block_start)))
518 				return retval;
519 			offset = 0;
520 		}
521 		left = (fs->blocksize - csum_size) - offset;
522 		dirent = (struct ext2_dir_entry *) (block_start + offset);
523 		if (offset == 0) {
524 			if (ent->hash == prev_hash)
525 				outdir->hashes[outdir->num-1] = ent->hash | 1;
526 			else
527 				outdir->hashes[outdir->num-1] = ent->hash;
528 		}
529 		dirent->inode = ent->dir->inode;
530 		ext2fs_dirent_set_name_len(dirent,
531 					   ext2fs_dirent_name_len(ent->dir));
532 		ext2fs_dirent_set_file_type(dirent,
533 					    ext2fs_dirent_file_type(ent->dir));
534 		retval = ext2fs_set_rec_len(fs, rec_len, dirent);
535 		if (retval)
536 			return retval;
537 		prev_rec_len = rec_len;
538 		memcpy(dirent->name, ent->dir->name,
539 		       ext2fs_dirent_name_len(dirent));
540 		offset += rec_len;
541 		left -= rec_len;
542 		if (left < slack) {
543 			prev_rec_len += left;
544 			retval = ext2fs_set_rec_len(fs, prev_rec_len, dirent);
545 			if (retval)
546 				return retval;
547 			offset += left;
548 			left = 0;
549 		}
550 		prev_hash = ent->hash;
551 	}
552 	if (left)
553 		retval = ext2fs_set_rec_len(fs, rec_len + left, dirent);
554 	if (csum_size) {
555 		t = EXT2_DIRENT_TAIL(block_start, fs->blocksize);
556 		ext2fs_initialize_dirent_tail(fs, t);
557 	}
558 
559 	return retval;
560 }
561 
562 
set_root_node(ext2_filsys fs,char * buf,ext2_ino_t ino,ext2_ino_t parent)563 static struct ext2_dx_root_info *set_root_node(ext2_filsys fs, char *buf,
564 				    ext2_ino_t ino, ext2_ino_t parent)
565 {
566 	struct ext2_dir_entry 		*dir;
567 	struct ext2_dx_root_info  	*root;
568 	struct ext2_dx_countlimit	*limits;
569 	int				filetype = 0;
570 	int				csum_size = 0;
571 
572 	if (ext2fs_has_feature_filetype(fs->super))
573 		filetype = EXT2_FT_DIR;
574 
575 	memset(buf, 0, fs->blocksize);
576 	dir = (struct ext2_dir_entry *) buf;
577 	dir->inode = ino;
578 	dir->name[0] = '.';
579 	ext2fs_dirent_set_name_len(dir, 1);
580 	ext2fs_dirent_set_file_type(dir, filetype);
581 	dir->rec_len = 12;
582 	dir = (struct ext2_dir_entry *) (buf + 12);
583 	dir->inode = parent;
584 	dir->name[0] = '.';
585 	dir->name[1] = '.';
586 	ext2fs_dirent_set_name_len(dir, 2);
587 	ext2fs_dirent_set_file_type(dir, filetype);
588 	dir->rec_len = fs->blocksize - 12;
589 
590 	root = (struct ext2_dx_root_info *) (buf+24);
591 	root->reserved_zero = 0;
592 	root->hash_version = fs->super->s_def_hash_version;
593 	root->info_length = 8;
594 	root->indirect_levels = 0;
595 	root->unused_flags = 0;
596 
597 	if (ext2fs_has_feature_metadata_csum(fs->super))
598 		csum_size = sizeof(struct ext2_dx_tail);
599 
600 	limits = (struct ext2_dx_countlimit *) (buf+32);
601 	limits->limit = (fs->blocksize - (32 + csum_size)) /
602 			sizeof(struct ext2_dx_entry);
603 	limits->count = 0;
604 
605 	return root;
606 }
607 
608 
set_int_node(ext2_filsys fs,char * buf)609 static struct ext2_dx_entry *set_int_node(ext2_filsys fs, char *buf)
610 {
611 	struct ext2_dir_entry 		*dir;
612 	struct ext2_dx_countlimit	*limits;
613 	int				csum_size = 0;
614 
615 	memset(buf, 0, fs->blocksize);
616 	dir = (struct ext2_dir_entry *) buf;
617 	dir->inode = 0;
618 	(void) ext2fs_set_rec_len(fs, fs->blocksize, dir);
619 
620 	if (ext2fs_has_feature_metadata_csum(fs->super))
621 		csum_size = sizeof(struct ext2_dx_tail);
622 
623 	limits = (struct ext2_dx_countlimit *) (buf+8);
624 	limits->limit = (fs->blocksize - (8 + csum_size)) /
625 			sizeof(struct ext2_dx_entry);
626 	limits->count = 0;
627 
628 	return (struct ext2_dx_entry *) limits;
629 }
630 
alloc_blocks(ext2_filsys fs,struct ext2_dx_countlimit ** limit,struct ext2_dx_entry ** prev_ent,struct ext2_dx_entry ** next_ent,int * prev_offset,int * next_offset,struct out_dir * outdir,int i,int * prev_count,int * next_count)631 static int alloc_blocks(ext2_filsys fs,
632 			struct ext2_dx_countlimit **limit,
633 			struct ext2_dx_entry **prev_ent,
634 			struct ext2_dx_entry **next_ent,
635 			int *prev_offset, int *next_offset,
636 			struct out_dir *outdir, int i,
637 			int *prev_count, int *next_count)
638 {
639 	errcode_t	retval;
640 	char		*block_start;
641 
642 	if (*limit)
643 		(*limit)->limit = (*limit)->count =
644 			ext2fs_cpu_to_le16((*limit)->limit);
645 	*prev_ent = (struct ext2_dx_entry *) (outdir->buf + *prev_offset);
646 	(*prev_ent)->block = ext2fs_cpu_to_le32(outdir->num);
647 
648 	if (i != 1)
649 		(*prev_ent)->hash =
650 			ext2fs_cpu_to_le32(outdir->hashes[i]);
651 
652 	retval = get_next_block(fs, outdir, &block_start);
653 	if (retval)
654 		return retval;
655 
656 	/* outdir->buf might be reallocated */
657 	*prev_ent = (struct ext2_dx_entry *) (outdir->buf + *prev_offset);
658 
659 	*next_ent = set_int_node(fs, block_start);
660 	*limit = (struct ext2_dx_countlimit *)(*next_ent);
661 	if (next_offset)
662 		*next_offset = ((char *) *next_ent - outdir->buf);
663 
664 	*next_count = (*limit)->limit;
665 	(*prev_offset) += sizeof(struct ext2_dx_entry);
666 	(*prev_count)--;
667 
668 	return 0;
669 }
670 
671 /*
672  * This function takes the leaf nodes which have been written in
673  * outdir, and populates the root node and any necessary interior nodes.
674  */
calculate_tree(ext2_filsys fs,struct out_dir * outdir,ext2_ino_t ino,ext2_ino_t parent)675 static errcode_t calculate_tree(ext2_filsys fs,
676 				struct out_dir *outdir,
677 				ext2_ino_t ino,
678 				ext2_ino_t parent)
679 {
680 	struct ext2_dx_root_info	*root_info;
681 	struct ext2_dx_entry		*root, *int_ent, *dx_ent = 0;
682 	struct ext2_dx_countlimit	*root_limit, *int_limit, *limit;
683 	errcode_t			retval;
684 	int				i, c1, c2, c3, nblks;
685 	int				limit_offset, int_offset, root_offset;
686 
687 	root_info = set_root_node(fs, outdir->buf, ino, parent);
688 	root_offset = limit_offset = ((char *) root_info - outdir->buf) +
689 		root_info->info_length;
690 	root_limit = (struct ext2_dx_countlimit *) (outdir->buf + limit_offset);
691 	c1 = root_limit->limit;
692 	nblks = outdir->num;
693 
694 	/* Write out the pointer blocks */
695 	if (nblks - 1 <= c1) {
696 		/* Just write out the root block, and we're done */
697 		root = (struct ext2_dx_entry *) (outdir->buf + root_offset);
698 		for (i=1; i < nblks; i++) {
699 			root->block = ext2fs_cpu_to_le32(i);
700 			if (i != 1)
701 				root->hash =
702 					ext2fs_cpu_to_le32(outdir->hashes[i]);
703 			root++;
704 			c1--;
705 		}
706 	} else if (nblks - 1 <= ext2fs_htree_intnode_maxrecs(fs, c1)) {
707 		c2 = 0;
708 		limit = NULL;
709 		root_info->indirect_levels = 1;
710 		for (i=1; i < nblks; i++) {
711 			if (c2 == 0 && c1 == 0)
712 				return ENOSPC;
713 			if (c2 == 0) {
714 				retval = alloc_blocks(fs, &limit, &root,
715 						      &dx_ent, &root_offset,
716 						      NULL, outdir, i, &c1,
717 						      &c2);
718 				if (retval)
719 					return retval;
720 			}
721 			dx_ent->block = ext2fs_cpu_to_le32(i);
722 			if (c2 != limit->limit)
723 				dx_ent->hash =
724 					ext2fs_cpu_to_le32(outdir->hashes[i]);
725 			dx_ent++;
726 			c2--;
727 		}
728 		limit->count = ext2fs_cpu_to_le16(limit->limit - c2);
729 		limit->limit = ext2fs_cpu_to_le16(limit->limit);
730 	} else {
731 		c2 = 0;
732 		c3 = 0;
733 		limit = NULL;
734 		int_limit = 0;
735 		root_info->indirect_levels = 2;
736 		for (i = 1; i < nblks; i++) {
737 			if (c3 == 0 && c2 == 0 && c1 == 0)
738 				return ENOSPC;
739 			if (c3 == 0 && c2 == 0) {
740 				retval = alloc_blocks(fs, &int_limit, &root,
741 						      &int_ent, &root_offset,
742 						      &int_offset, outdir, i,
743 						      &c1, &c2);
744 				if (retval)
745 					return retval;
746 			}
747 			if (c3 == 0) {
748 				int delta1 = (char *)int_limit - outdir->buf;
749 				int delta2 = (char *)root - outdir->buf;
750 
751 				retval = alloc_blocks(fs, &limit, &int_ent,
752 						      &dx_ent, &int_offset,
753 						      NULL, outdir, i, &c2,
754 						      &c3);
755 				if (retval)
756 					return retval;
757 
758 				/* outdir->buf might be reallocated */
759 				int_limit = (struct ext2_dx_countlimit *)
760 					(outdir->buf + delta1);
761 				root = (struct ext2_dx_entry *)
762 					(outdir->buf + delta2);
763 			}
764 			dx_ent->block = ext2fs_cpu_to_le32(i);
765 			if (c3 != limit->limit)
766 				dx_ent->hash =
767 					ext2fs_cpu_to_le32(outdir->hashes[i]);
768 			dx_ent++;
769 			c3--;
770 		}
771 		int_limit->count = ext2fs_cpu_to_le16(limit->limit - c2);
772 		int_limit->limit = ext2fs_cpu_to_le16(limit->limit);
773 
774 		limit->count = ext2fs_cpu_to_le16(limit->limit - c3);
775 		limit->limit = ext2fs_cpu_to_le16(limit->limit);
776 
777 	}
778 	root_limit = (struct ext2_dx_countlimit *) (outdir->buf + limit_offset);
779 	root_limit->count = ext2fs_cpu_to_le16(root_limit->limit - c1);
780 	root_limit->limit = ext2fs_cpu_to_le16(root_limit->limit);
781 
782 	return 0;
783 }
784 
785 struct write_dir_struct {
786 	struct out_dir *outdir;
787 	errcode_t	err;
788 	ext2_ino_t	ino;
789 	e2fsck_t	ctx;
790 	ext2_ino_t	dir;
791 };
792 
793 /*
794  * Helper function which writes out a directory block.
795  */
write_dir_block(ext2_filsys fs,blk64_t * block_nr,e2_blkcnt_t blockcnt,blk64_t ref_block EXT2FS_ATTR ((unused)),int ref_offset EXT2FS_ATTR ((unused)),void * priv_data)796 static int write_dir_block(ext2_filsys fs,
797 			   blk64_t *block_nr,
798 			   e2_blkcnt_t blockcnt,
799 			   blk64_t ref_block EXT2FS_ATTR((unused)),
800 			   int ref_offset EXT2FS_ATTR((unused)),
801 			   void *priv_data)
802 {
803 	struct write_dir_struct	*wd = (struct write_dir_struct *) priv_data;
804 	char	*dir, *buf = 0;
805 
806 #ifdef REHASH_DEBUG
807 	printf("%u: write_dir_block %lld:%lld", wd->ino, blockcnt, *block_nr);
808 #endif
809 	if ((*block_nr == 0) || (blockcnt < 0)) {
810 #ifdef REHASH_DEBUG
811 		printf(" - skip\n");
812 #endif
813 		return 0;
814 	}
815 	if (blockcnt < wd->outdir->num)
816 		dir = wd->outdir->buf + (blockcnt * fs->blocksize);
817 	else if (wd->ctx->lost_and_found == wd->dir) {
818 		/* Don't release any extra directory blocks for lost+found */
819 		wd->err = ext2fs_new_dir_block(fs, 0, 0, &buf);
820 		if (wd->err)
821 			return BLOCK_ABORT;
822 		dir = buf;
823 		wd->outdir->num++;
824 	} else {
825 		/* Don't free blocks at the end of the directory, they
826 		 * will be truncated by the caller. */
827 #ifdef REHASH_DEBUG
828 		printf(" - not freed\n");
829 #endif
830 		return 0;
831 	}
832 	wd->err = ext2fs_write_dir_block4(fs, *block_nr, dir, 0, wd->dir);
833 	if (buf)
834 		ext2fs_free_mem(&buf);
835 
836 #ifdef REHASH_DEBUG
837 	printf(" - write (%d)\n", wd->err);
838 #endif
839 	if (wd->err)
840 		return BLOCK_ABORT;
841 	return 0;
842 }
843 
write_directory(e2fsck_t ctx,ext2_filsys fs,struct out_dir * outdir,ext2_ino_t ino,struct ext2_inode * inode,int compress)844 static errcode_t write_directory(e2fsck_t ctx, ext2_filsys fs,
845 				 struct out_dir *outdir,
846 				 ext2_ino_t ino, struct ext2_inode *inode,
847 				 int compress)
848 {
849 	struct write_dir_struct wd;
850 	errcode_t	retval;
851 
852 	retval = e2fsck_expand_directory(ctx, ino, -1, outdir->num);
853 	if (retval)
854 		return retval;
855 
856 	wd.outdir = outdir;
857 	wd.err = 0;
858 	wd.ino = ino;
859 	wd.ctx = ctx;
860 	wd.dir = ino;
861 
862 	retval = ext2fs_block_iterate3(fs, ino, 0, NULL,
863 				       write_dir_block, &wd);
864 	if (retval)
865 		return retval;
866 	if (wd.err)
867 		return wd.err;
868 
869 	e2fsck_read_inode(ctx, ino, inode, "rehash_dir");
870 	if (compress)
871 		inode->i_flags &= ~EXT2_INDEX_FL;
872 	else
873 		inode->i_flags |= EXT2_INDEX_FL;
874 #ifdef REHASH_DEBUG
875 	printf("%u: set inode size to %u blocks = %u bytes\n",
876 	       ino, outdir->num, outdir->num * fs->blocksize);
877 #endif
878 	retval = ext2fs_inode_size_set(fs, inode, (ext2_off64_t)outdir->num *
879 						   fs->blocksize);
880 	if (retval)
881 		return retval;
882 
883 	/* ext2fs_punch() calls ext2fs_write_inode() which writes the size */
884 	return ext2fs_punch(fs, ino, inode, NULL, outdir->num, ~0ULL);
885 }
886 
e2fsck_rehash_dir(e2fsck_t ctx,ext2_ino_t ino,struct problem_context * pctx)887 errcode_t e2fsck_rehash_dir(e2fsck_t ctx, ext2_ino_t ino,
888 			    struct problem_context *pctx)
889 {
890 	ext2_filsys 		fs = ctx->fs;
891 	errcode_t		retval;
892 	struct ext2_inode 	inode;
893 	char			*dir_buf = 0;
894 	struct fill_dir_struct	fd = { NULL, NULL, 0, 0, 0, NULL,
895 				       0, 0, 0, 0, 0, 0 };
896 	struct out_dir		outdir = { 0, 0, 0, 0 };
897 
898 	e2fsck_read_inode(ctx, ino, &inode, "rehash_dir");
899 
900 	if (ext2fs_has_feature_inline_data(fs->super) &&
901 	   (inode.i_flags & EXT4_INLINE_DATA_FL))
902 		return 0;
903 
904 	retval = ext2fs_get_mem(inode.i_size, &dir_buf);
905 	if (retval)
906 		goto errout;
907 
908 	fd.max_array = inode.i_size / 32;
909 	retval = ext2fs_get_array(sizeof(struct hash_entry),
910 				  fd.max_array, &fd.harray);
911 	if (retval)
912 		goto errout;
913 
914 	fd.ino = ino;
915 	fd.ctx = ctx;
916 	fd.buf = dir_buf;
917 	fd.inode = &inode;
918 	fd.dir = ino;
919 	if (!ext2fs_has_feature_dir_index(fs->super) ||
920 	    (inode.i_size / fs->blocksize) < 2)
921 		fd.compress = 1;
922 	fd.parent = 0;
923 
924 retry_nohash:
925 	/* Read in the entire directory into memory */
926 	retval = ext2fs_block_iterate3(fs, ino, 0, 0,
927 				       fill_dir_block, &fd);
928 	if (fd.err) {
929 		retval = fd.err;
930 		goto errout;
931 	}
932 
933 	/*
934 	 * If the entries read are less than a block, then don't index
935 	 * the directory
936 	 */
937 	if (!fd.compress && (fd.dir_size < (fs->blocksize - 24))) {
938 		fd.compress = 1;
939 		fd.dir_size = 0;
940 		fd.num_array = 0;
941 		goto retry_nohash;
942 	}
943 
944 #if 0
945 	printf("%d entries (%d bytes) found in inode %d\n",
946 	       fd.num_array, fd.dir_size, ino);
947 #endif
948 
949 	/* Sort the list */
950 resort:
951 	if (fd.compress && fd.num_array > 1)
952 		qsort(fd.harray+2, fd.num_array-2, sizeof(struct hash_entry),
953 		      hash_cmp);
954 	else
955 		qsort(fd.harray, fd.num_array, sizeof(struct hash_entry),
956 		      hash_cmp);
957 
958 	/*
959 	 * Look for duplicates
960 	 */
961 	if (duplicate_search_and_fix(ctx, fs, ino, &fd))
962 		goto resort;
963 
964 	if (ctx->options & E2F_OPT_NO) {
965 		retval = 0;
966 		goto errout;
967 	}
968 
969 	/* Sort non-hashed directories by inode number */
970 	if (fd.compress && fd.num_array > 1)
971 		qsort(fd.harray+2, fd.num_array-2,
972 		      sizeof(struct hash_entry), ino_cmp);
973 
974 	/*
975 	 * Copy the directory entries.  In a htree directory these
976 	 * will become the leaf nodes.
977 	 */
978 	retval = copy_dir_entries(ctx, &fd, &outdir);
979 	if (retval)
980 		goto errout;
981 
982 	free(dir_buf); dir_buf = 0;
983 
984 	if (!fd.compress) {
985 		/* Calculate the interior nodes */
986 		retval = calculate_tree(fs, &outdir, ino, fd.parent);
987 		if (retval)
988 			goto errout;
989 	}
990 
991 	retval = write_directory(ctx, fs, &outdir, ino, &inode, fd.compress);
992 	if (retval)
993 		goto errout;
994 
995 	if (ctx->options & E2F_OPT_CONVERT_BMAP)
996 		retval = e2fsck_rebuild_extents_later(ctx, ino);
997 	else
998 		retval = e2fsck_check_rebuild_extents(ctx, ino, &inode, pctx);
999 errout:
1000 	ext2fs_free_mem(&dir_buf);
1001 	ext2fs_free_mem(&fd.harray);
1002 
1003 	free_out_dir(&outdir);
1004 	return retval;
1005 }
1006 
e2fsck_rehash_directories(e2fsck_t ctx)1007 void e2fsck_rehash_directories(e2fsck_t ctx)
1008 {
1009 	struct problem_context	pctx;
1010 #ifdef RESOURCE_TRACK
1011 	struct resource_track	rtrack;
1012 #endif
1013 	struct dir_info		*dir;
1014 	ext2_u32_iterate 	iter;
1015 	struct dir_info_iter *	dirinfo_iter = 0;
1016 	ext2_ino_t		ino;
1017 	errcode_t		retval;
1018 	int			cur, max, all_dirs, first = 1;
1019 
1020 	init_resource_track(&rtrack, ctx->fs->io);
1021 	all_dirs = ctx->options & E2F_OPT_COMPRESS_DIRS;
1022 
1023 	if (!ctx->dirs_to_hash && !all_dirs)
1024 		return;
1025 
1026 	(void) e2fsck_get_lost_and_found(ctx, 0);
1027 
1028 	clear_problem_context(&pctx);
1029 
1030 	cur = 0;
1031 	if (all_dirs) {
1032 		dirinfo_iter = e2fsck_dir_info_iter_begin(ctx);
1033 		max = e2fsck_get_num_dirinfo(ctx);
1034 	} else {
1035 		retval = ext2fs_u32_list_iterate_begin(ctx->dirs_to_hash,
1036 						       &iter);
1037 		if (retval) {
1038 			pctx.errcode = retval;
1039 			fix_problem(ctx, PR_3A_OPTIMIZE_ITER, &pctx);
1040 			return;
1041 		}
1042 		max = ext2fs_u32_list_count(ctx->dirs_to_hash);
1043 	}
1044 	while (1) {
1045 		if (all_dirs) {
1046 			if ((dir = e2fsck_dir_info_iter(ctx,
1047 							dirinfo_iter)) == 0)
1048 				break;
1049 			ino = dir->ino;
1050 		} else {
1051 			if (!ext2fs_u32_list_iterate(iter, &ino))
1052 				break;
1053 		}
1054 		if (!ext2fs_test_inode_bitmap2(ctx->inode_dir_map, ino))
1055 			continue;
1056 
1057 		pctx.dir = ino;
1058 		if (first) {
1059 			fix_problem(ctx, PR_3A_PASS_HEADER, &pctx);
1060 			first = 0;
1061 		}
1062 #if 0
1063 		fix_problem(ctx, PR_3A_OPTIMIZE_DIR, &pctx);
1064 #endif
1065 		pctx.errcode = e2fsck_rehash_dir(ctx, ino, &pctx);
1066 		if (pctx.errcode) {
1067 			end_problem_latch(ctx, PR_LATCH_OPTIMIZE_DIR);
1068 			fix_problem(ctx, PR_3A_OPTIMIZE_DIR_ERR, &pctx);
1069 		}
1070 		if (ctx->progress && !ctx->progress_fd)
1071 			e2fsck_simple_progress(ctx, "Rebuilding directory",
1072 			       100.0 * (float) (++cur) / (float) max, ino);
1073 	}
1074 	end_problem_latch(ctx, PR_LATCH_OPTIMIZE_DIR);
1075 	if (all_dirs)
1076 		e2fsck_dir_info_iter_end(ctx, dirinfo_iter);
1077 	else
1078 		ext2fs_u32_list_iterate_end(iter);
1079 
1080 	if (ctx->dirs_to_hash)
1081 		ext2fs_u32_list_free(ctx->dirs_to_hash);
1082 	ctx->dirs_to_hash = 0;
1083 
1084 	print_resource_track(ctx, "Pass 3A", &rtrack, ctx->fs->io);
1085 }
1086