Whamcloud - gitweb
libext2fs: provide functions to safely access name_len and file_type
[tools/e2fsprogs.git] / e2fsck / rehash.c
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. */
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. */
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 struct fill_dir_struct {
75         char *buf;
76         struct ext2_inode *inode;
77         int err;
78         e2fsck_t ctx;
79         struct hash_entry *harray;
80         int max_array, num_array;
81         unsigned int dir_size;
82         int compress;
83         ino_t parent;
84         ext2_ino_t dir;
85 };
86
87 struct hash_entry {
88         ext2_dirhash_t  hash;
89         ext2_dirhash_t  minor_hash;
90         ino_t           ino;
91         struct ext2_dir_entry   *dir;
92 };
93
94 struct out_dir {
95         int             num;
96         int             max;
97         char            *buf;
98         ext2_dirhash_t  *hashes;
99 };
100
101 static int fill_dir_block(ext2_filsys fs,
102                           blk64_t *block_nr,
103                           e2_blkcnt_t blockcnt,
104                           blk64_t ref_block EXT2FS_ATTR((unused)),
105                           int ref_offset EXT2FS_ATTR((unused)),
106                           void *priv_data)
107 {
108         struct fill_dir_struct  *fd = (struct fill_dir_struct *) priv_data;
109         struct hash_entry       *new_array, *ent;
110         struct ext2_dir_entry   *dirent;
111         char                    *dir;
112         unsigned int            offset, dir_offset, rec_len, name_len;
113         int                     hash_alg;
114
115         if (blockcnt < 0)
116                 return 0;
117
118         offset = blockcnt * fs->blocksize;
119         if (offset + fs->blocksize > fd->inode->i_size) {
120                 fd->err = EXT2_ET_DIR_CORRUPTED;
121                 return BLOCK_ABORT;
122         }
123         dir = (fd->buf+offset);
124         if (HOLE_BLKADDR(*block_nr)) {
125                 memset(dir, 0, fs->blocksize);
126                 dirent = (struct ext2_dir_entry *) dir;
127                 (void) ext2fs_set_rec_len(fs, fs->blocksize, dirent);
128         } else {
129                 fs->flags |= EXT2_FLAG_IGNORE_CSUM_ERRORS;
130                 fd->err = ext2fs_read_dir_block4(fs, *block_nr, dir, 0,
131                                                  fd->dir);
132                 fs->flags &= ~EXT2_FLAG_IGNORE_CSUM_ERRORS;
133                 if (fd->err)
134                         return BLOCK_ABORT;
135         }
136         hash_alg = fs->super->s_def_hash_version;
137         if ((hash_alg <= EXT2_HASH_TEA) &&
138             (fs->super->s_flags & EXT2_FLAGS_UNSIGNED_HASH))
139                 hash_alg += 3;
140         /* While the directory block is "hot", index it. */
141         dir_offset = 0;
142         while (dir_offset < fs->blocksize) {
143                 dirent = (struct ext2_dir_entry *) (dir + dir_offset);
144                 (void) ext2fs_get_rec_len(fs, dirent, &rec_len);
145                 name_len = ext2fs_dirent_name_len(dirent);
146                 if (((dir_offset + rec_len) > fs->blocksize) ||
147                     (rec_len < 8) ||
148                     ((rec_len % 4) != 0) ||
149                     (name_len + 8 > rec_len)) {
150                         fd->err = EXT2_ET_DIR_CORRUPTED;
151                         return BLOCK_ABORT;
152                 }
153                 dir_offset += rec_len;
154                 if (dirent->inode == 0)
155                         continue;
156                 if (!fd->compress && (name_len == 1) &&
157                     (dirent->name[0] == '.'))
158                         continue;
159                 if (!fd->compress && (name_len == 2) &&
160                     (dirent->name[0] == '.') && (dirent->name[1] == '.')) {
161                         fd->parent = dirent->inode;
162                         continue;
163                 }
164                 if (fd->num_array >= fd->max_array) {
165                         new_array = realloc(fd->harray,
166                             sizeof(struct hash_entry) * (fd->max_array+500));
167                         if (!new_array) {
168                                 fd->err = ENOMEM;
169                                 return BLOCK_ABORT;
170                         }
171                         fd->harray = new_array;
172                         fd->max_array += 500;
173                 }
174                 ent = fd->harray + fd->num_array++;
175                 ent->dir = dirent;
176                 fd->dir_size += EXT2_DIR_REC_LEN(name_len);
177                 ent->ino = dirent->inode;
178                 if (fd->compress)
179                         ent->hash = ent->minor_hash = 0;
180                 else {
181                         fd->err = ext2fs_dirhash(hash_alg, dirent->name,
182                                                  name_len,
183                                                  fs->super->s_hash_seed,
184                                                  &ent->hash, &ent->minor_hash);
185                         if (fd->err)
186                                 return BLOCK_ABORT;
187                 }
188         }
189
190         return 0;
191 }
192
193 /* Used for sorting the hash entry */
194 static EXT2_QSORT_TYPE ino_cmp(const void *a, const void *b)
195 {
196         const struct hash_entry *he_a = (const struct hash_entry *) a;
197         const struct hash_entry *he_b = (const struct hash_entry *) b;
198
199         return (he_a->ino - he_b->ino);
200 }
201
202 /* Used for sorting the hash entry */
203 static EXT2_QSORT_TYPE name_cmp(const void *a, const void *b)
204 {
205         const struct hash_entry *he_a = (const struct hash_entry *) a;
206         const struct hash_entry *he_b = (const struct hash_entry *) b;
207         unsigned int he_a_len, he_b_len;
208         int     ret;
209         int     min_len;
210
211         he_a_len = ext2fs_dirent_name_len(he_a->dir);
212         he_b_len = ext2fs_dirent_name_len(he_b->dir);
213         min_len = he_a_len;
214         if (min_len > he_b_len)
215                 min_len = he_b_len;
216
217         ret = strncmp(he_a->dir->name, he_b->dir->name, min_len);
218         if (ret == 0) {
219                 if (he_a_len > he_b_len)
220                         ret = 1;
221                 else if (he_a_len < he_b_len)
222                         ret = -1;
223                 else
224                         ret = he_b->dir->inode - he_a->dir->inode;
225         }
226         return ret;
227 }
228
229 /* Used for sorting the hash entry */
230 static EXT2_QSORT_TYPE hash_cmp(const void *a, const void *b)
231 {
232         const struct hash_entry *he_a = (const struct hash_entry *) a;
233         const struct hash_entry *he_b = (const struct hash_entry *) b;
234         int     ret;
235
236         if (he_a->hash > he_b->hash)
237                 ret = 1;
238         else if (he_a->hash < he_b->hash)
239                 ret = -1;
240         else {
241                 if (he_a->minor_hash > he_b->minor_hash)
242                         ret = 1;
243                 else if (he_a->minor_hash < he_b->minor_hash)
244                         ret = -1;
245                 else
246                         ret = name_cmp(a, b);
247         }
248         return ret;
249 }
250
251 static errcode_t alloc_size_dir(ext2_filsys fs, struct out_dir *outdir,
252                                 int blocks)
253 {
254         void                    *new_mem;
255
256         if (outdir->max) {
257                 new_mem = realloc(outdir->buf, blocks * fs->blocksize);
258                 if (!new_mem)
259                         return ENOMEM;
260                 outdir->buf = new_mem;
261                 new_mem = realloc(outdir->hashes,
262                                   blocks * sizeof(ext2_dirhash_t));
263                 if (!new_mem)
264                         return ENOMEM;
265                 outdir->hashes = new_mem;
266         } else {
267                 outdir->buf = malloc(blocks * fs->blocksize);
268                 outdir->hashes = malloc(blocks * sizeof(ext2_dirhash_t));
269                 outdir->num = 0;
270         }
271         outdir->max = blocks;
272         return 0;
273 }
274
275 static void free_out_dir(struct out_dir *outdir)
276 {
277         free(outdir->buf);
278         free(outdir->hashes);
279         outdir->max = 0;
280         outdir->num =0;
281 }
282
283 static errcode_t get_next_block(ext2_filsys fs, struct out_dir *outdir,
284                          char ** ret)
285 {
286         errcode_t       retval;
287
288         if (outdir->num >= outdir->max) {
289                 retval = alloc_size_dir(fs, outdir, outdir->max + 50);
290                 if (retval)
291                         return retval;
292         }
293         *ret = outdir->buf + (outdir->num++ * fs->blocksize);
294         memset(*ret, 0, fs->blocksize);
295         return 0;
296 }
297
298 /*
299  * This function is used to make a unique filename.  We do this by
300  * appending ~0, and then incrementing the number.  However, we cannot
301  * expand the length of the filename beyond the padding available in
302  * the directory entry.
303  */
304 static void mutate_name(char *str, unsigned int *len)
305 {
306         int     i;
307         unsigned int l = *len;
308
309         /*
310          * First check to see if it looks the name has been mutated
311          * already
312          */
313         for (i = l-1; i > 0; i--) {
314                 if (!isdigit(str[i]))
315                         break;
316         }
317         if ((i == l-1) || (str[i] != '~')) {
318                 if (((l-1) & 3) < 2)
319                         l += 2;
320                 else
321                         l = (l+3) & ~3;
322                 str[l-2] = '~';
323                 str[l-1] = '0';
324                 *len = l;
325                 return;
326         }
327         for (i = l-1; i >= 0; i--) {
328                 if (isdigit(str[i])) {
329                         if (str[i] == '9')
330                                 str[i] = '0';
331                         else {
332                                 str[i]++;
333                                 return;
334                         }
335                         continue;
336                 }
337                 if (i == 1) {
338                         if (str[0] == 'z')
339                                 str[0] = 'A';
340                         else if (str[0] == 'Z') {
341                                 str[0] = '~';
342                                 str[1] = '0';
343                         } else
344                                 str[0]++;
345                 } else if (i > 0) {
346                         str[i] = '1';
347                         str[i-1] = '~';
348                 } else {
349                         if (str[0] == '~')
350                                 str[0] = 'a';
351                         else
352                                 str[0]++;
353                 }
354                 break;
355         }
356 }
357
358 static int duplicate_search_and_fix(e2fsck_t ctx, ext2_filsys fs,
359                                     ext2_ino_t ino,
360                                     struct fill_dir_struct *fd)
361 {
362         struct problem_context  pctx;
363         struct hash_entry       *ent, *prev;
364         int                     i, j;
365         int                     fixed = 0;
366         char                    new_name[256];
367         unsigned int            new_len;
368         int                     hash_alg;
369
370         clear_problem_context(&pctx);
371         pctx.ino = ino;
372
373         hash_alg = fs->super->s_def_hash_version;
374         if ((hash_alg <= EXT2_HASH_TEA) &&
375             (fs->super->s_flags & EXT2_FLAGS_UNSIGNED_HASH))
376                 hash_alg += 3;
377
378         for (i=1; i < fd->num_array; i++) {
379                 ent = fd->harray + i;
380                 prev = ent - 1;
381                 if (!ent->dir->inode ||
382                     (ext2fs_dirent_name_len(ent->dir) !=
383                      ext2fs_dirent_name_len(prev->dir)) ||
384                     strncmp(ent->dir->name, prev->dir->name,
385                              ext2fs_dirent_name_len(ent->dir)))
386                         continue;
387                 pctx.dirent = ent->dir;
388                 if ((ent->dir->inode == prev->dir->inode) &&
389                     fix_problem(ctx, PR_2_DUPLICATE_DIRENT, &pctx)) {
390                         e2fsck_adjust_inode_count(ctx, ent->dir->inode, -1);
391                         ent->dir->inode = 0;
392                         fixed++;
393                         continue;
394                 }
395                 new_len = ext2fs_dirent_name_len(ent->dir);
396                 memcpy(new_name, ent->dir->name, new_len);
397                 mutate_name(new_name, &new_len);
398                 for (j=0; j < fd->num_array; j++) {
399                         if ((i==j) ||
400                             (new_len !=
401                              ext2fs_dirent_name_len(fd->harray[j].dir)) ||
402                             strncmp(new_name, fd->harray[j].dir->name, new_len))
403                                 continue;
404                         mutate_name(new_name, &new_len);
405
406                         j = -1;
407                 }
408                 new_name[new_len] = 0;
409                 pctx.str = new_name;
410                 if (fix_problem(ctx, PR_2_NON_UNIQUE_FILE, &pctx)) {
411                         memcpy(ent->dir->name, new_name, new_len);
412                         ext2fs_dirent_set_name_len(ent->dir, new_len);
413                         ext2fs_dirhash(hash_alg, ent->dir->name, new_len,
414                                        fs->super->s_hash_seed,
415                                        &ent->hash, &ent->minor_hash);
416                         fixed++;
417                 }
418         }
419         return fixed;
420 }
421
422
423 static errcode_t copy_dir_entries(e2fsck_t ctx,
424                                   struct fill_dir_struct *fd,
425                                   struct out_dir *outdir)
426 {
427         ext2_filsys             fs = ctx->fs;
428         errcode_t               retval;
429         char                    *block_start;
430         struct hash_entry       *ent;
431         struct ext2_dir_entry   *dirent;
432         unsigned int            rec_len, prev_rec_len, left, slack, offset;
433         int                     i;
434         ext2_dirhash_t          prev_hash;
435         int                     csum_size = 0;
436         struct                  ext2_dir_entry_tail *t;
437
438         if (ctx->htree_slack_percentage == 255) {
439                 profile_get_uint(ctx->profile, "options",
440                                  "indexed_dir_slack_percentage",
441                                  0, 20,
442                                  &ctx->htree_slack_percentage);
443                 if (ctx->htree_slack_percentage > 100)
444                         ctx->htree_slack_percentage = 20;
445         }
446
447         if (EXT2_HAS_RO_COMPAT_FEATURE(fs->super,
448                                        EXT4_FEATURE_RO_COMPAT_METADATA_CSUM))
449                 csum_size = sizeof(struct ext2_dir_entry_tail);
450
451         outdir->max = 0;
452         retval = alloc_size_dir(fs, outdir,
453                                 (fd->dir_size / fs->blocksize) + 2);
454         if (retval)
455                 return retval;
456         outdir->num = fd->compress ? 0 : 1;
457         offset = 0;
458         outdir->hashes[0] = 0;
459         prev_hash = 1;
460         if ((retval = get_next_block(fs, outdir, &block_start)))
461                 return retval;
462         dirent = (struct ext2_dir_entry *) block_start;
463         prev_rec_len = 0;
464         rec_len = 0;
465         left = fs->blocksize - csum_size;
466         slack = fd->compress ? 12 :
467                 ((fs->blocksize - csum_size) * ctx->htree_slack_percentage)/100;
468         if (slack < 12)
469                 slack = 12;
470         for (i = 0; i < fd->num_array; i++) {
471                 ent = fd->harray + i;
472                 if (ent->dir->inode == 0)
473                         continue;
474                 rec_len = EXT2_DIR_REC_LEN(ext2fs_dirent_name_len(ent->dir));
475                 if (rec_len > left) {
476                         if (left) {
477                                 left += prev_rec_len;
478                                 retval = ext2fs_set_rec_len(fs, left, dirent);
479                                 if (retval)
480                                         return retval;
481                         }
482                         if (csum_size) {
483                                 t = EXT2_DIRENT_TAIL(block_start,
484                                                      fs->blocksize);
485                                 ext2fs_initialize_dirent_tail(fs, t);
486                         }
487                         if ((retval = get_next_block(fs, outdir,
488                                                       &block_start)))
489                                 return retval;
490                         offset = 0;
491                 }
492                 left = (fs->blocksize - csum_size) - offset;
493                 dirent = (struct ext2_dir_entry *) (block_start + offset);
494                 if (offset == 0) {
495                         if (ent->hash == prev_hash)
496                                 outdir->hashes[outdir->num-1] = ent->hash | 1;
497                         else
498                                 outdir->hashes[outdir->num-1] = ent->hash;
499                 }
500                 dirent->inode = ent->dir->inode;
501                 ext2fs_dirent_set_name_len(dirent,
502                                            ext2fs_dirent_name_len(ent->dir));
503                 ext2fs_dirent_set_file_type(dirent,
504                                             ext2fs_dirent_file_type(ent->dir));
505                 retval = ext2fs_set_rec_len(fs, rec_len, dirent);
506                 if (retval)
507                         return retval;
508                 prev_rec_len = rec_len;
509                 memcpy(dirent->name, ent->dir->name,
510                        ext2fs_dirent_name_len(dirent));
511                 offset += rec_len;
512                 left -= rec_len;
513                 if (left < slack) {
514                         prev_rec_len += left;
515                         retval = ext2fs_set_rec_len(fs, prev_rec_len, dirent);
516                         if (retval)
517                                 return retval;
518                         offset += left;
519                         left = 0;
520                 }
521                 prev_hash = ent->hash;
522         }
523         if (left)
524                 retval = ext2fs_set_rec_len(fs, rec_len + left, dirent);
525         if (csum_size) {
526                 t = EXT2_DIRENT_TAIL(block_start, fs->blocksize);
527                 ext2fs_initialize_dirent_tail(fs, t);
528         }
529
530         return retval;
531 }
532
533
534 static struct ext2_dx_root_info *set_root_node(ext2_filsys fs, char *buf,
535                                     ext2_ino_t ino, ext2_ino_t parent)
536 {
537         struct ext2_dir_entry           *dir;
538         struct ext2_dx_root_info        *root;
539         struct ext2_dx_countlimit       *limits;
540         int                             filetype = 0;
541         int                             csum_size = 0;
542
543         if (fs->super->s_feature_incompat & EXT2_FEATURE_INCOMPAT_FILETYPE)
544                 filetype = EXT2_FT_DIR;
545
546         memset(buf, 0, fs->blocksize);
547         dir = (struct ext2_dir_entry *) buf;
548         dir->inode = ino;
549         dir->name[0] = '.';
550         ext2fs_dirent_set_name_len(dir, 1);
551         ext2fs_dirent_set_file_type(dir, filetype);
552         dir->rec_len = 12;
553         dir = (struct ext2_dir_entry *) (buf + 12);
554         dir->inode = parent;
555         dir->name[0] = '.';
556         dir->name[1] = '.';
557         ext2fs_dirent_set_name_len(dir, 2);
558         ext2fs_dirent_set_file_type(dir, filetype);
559         dir->rec_len = fs->blocksize - 12;
560
561         root = (struct ext2_dx_root_info *) (buf+24);
562         root->reserved_zero = 0;
563         root->hash_version = fs->super->s_def_hash_version;
564         root->info_length = 8;
565         root->indirect_levels = 0;
566         root->unused_flags = 0;
567
568         if (EXT2_HAS_RO_COMPAT_FEATURE(fs->super,
569                                         EXT4_FEATURE_RO_COMPAT_METADATA_CSUM))
570                 csum_size = sizeof(struct ext2_dx_tail);
571
572         limits = (struct ext2_dx_countlimit *) (buf+32);
573         limits->limit = (fs->blocksize - (32 + csum_size)) /
574                         sizeof(struct ext2_dx_entry);
575         limits->count = 0;
576
577         return root;
578 }
579
580
581 static struct ext2_dx_entry *set_int_node(ext2_filsys fs, char *buf)
582 {
583         struct ext2_dir_entry           *dir;
584         struct ext2_dx_countlimit       *limits;
585         int                             csum_size = 0;
586
587         memset(buf, 0, fs->blocksize);
588         dir = (struct ext2_dir_entry *) buf;
589         dir->inode = 0;
590         (void) ext2fs_set_rec_len(fs, fs->blocksize, dir);
591
592         if (EXT2_HAS_RO_COMPAT_FEATURE(fs->super,
593                                         EXT4_FEATURE_RO_COMPAT_METADATA_CSUM))
594                 csum_size = sizeof(struct ext2_dx_tail);
595
596         limits = (struct ext2_dx_countlimit *) (buf+8);
597         limits->limit = (fs->blocksize - (8 + csum_size)) /
598                         sizeof(struct ext2_dx_entry);
599         limits->count = 0;
600
601         return (struct ext2_dx_entry *) limits;
602 }
603
604 /*
605  * This function takes the leaf nodes which have been written in
606  * outdir, and populates the root node and any necessary interior nodes.
607  */
608 static errcode_t calculate_tree(ext2_filsys fs,
609                                 struct out_dir *outdir,
610                                 ext2_ino_t ino,
611                                 ext2_ino_t parent)
612 {
613         struct ext2_dx_root_info        *root_info;
614         struct ext2_dx_entry            *root, *dx_ent = 0;
615         struct ext2_dx_countlimit       *root_limit, *limit;
616         errcode_t                       retval;
617         char                            * block_start;
618         int                             i, c1, c2, nblks;
619         int                             limit_offset, root_offset;
620
621         root_info = set_root_node(fs, outdir->buf, ino, parent);
622         root_offset = limit_offset = ((char *) root_info - outdir->buf) +
623                 root_info->info_length;
624         root_limit = (struct ext2_dx_countlimit *) (outdir->buf + limit_offset);
625         c1 = root_limit->limit;
626         nblks = outdir->num;
627
628         /* Write out the pointer blocks */
629         if (nblks-1 <= c1) {
630                 /* Just write out the root block, and we're done */
631                 root = (struct ext2_dx_entry *) (outdir->buf + root_offset);
632                 for (i=1; i < nblks; i++) {
633                         root->block = ext2fs_cpu_to_le32(i);
634                         if (i != 1)
635                                 root->hash =
636                                         ext2fs_cpu_to_le32(outdir->hashes[i]);
637                         root++;
638                         c1--;
639                 }
640         } else {
641                 c2 = 0;
642                 limit = 0;
643                 root_info->indirect_levels = 1;
644                 for (i=1; i < nblks; i++) {
645                         if (c1 == 0)
646                                 return ENOSPC;
647                         if (c2 == 0) {
648                                 if (limit)
649                                         limit->limit = limit->count =
650                 ext2fs_cpu_to_le16(limit->limit);
651                                 root = (struct ext2_dx_entry *)
652                                         (outdir->buf + root_offset);
653                                 root->block = ext2fs_cpu_to_le32(outdir->num);
654                                 if (i != 1)
655                                         root->hash =
656                         ext2fs_cpu_to_le32(outdir->hashes[i]);
657                                 if ((retval =  get_next_block(fs, outdir,
658                                                               &block_start)))
659                                         return retval;
660                                 dx_ent = set_int_node(fs, block_start);
661                                 limit = (struct ext2_dx_countlimit *) dx_ent;
662                                 c2 = limit->limit;
663                                 root_offset += sizeof(struct ext2_dx_entry);
664                                 c1--;
665                         }
666                         dx_ent->block = ext2fs_cpu_to_le32(i);
667                         if (c2 != limit->limit)
668                                 dx_ent->hash =
669                                         ext2fs_cpu_to_le32(outdir->hashes[i]);
670                         dx_ent++;
671                         c2--;
672                 }
673                 limit->count = ext2fs_cpu_to_le16(limit->limit - c2);
674                 limit->limit = ext2fs_cpu_to_le16(limit->limit);
675         }
676         root_limit = (struct ext2_dx_countlimit *) (outdir->buf + limit_offset);
677         root_limit->count = ext2fs_cpu_to_le16(root_limit->limit - c1);
678         root_limit->limit = ext2fs_cpu_to_le16(root_limit->limit);
679
680         return 0;
681 }
682
683 struct write_dir_struct {
684         struct out_dir *outdir;
685         errcode_t       err;
686         e2fsck_t        ctx;
687         int             cleared;
688         ext2_ino_t      dir;
689 };
690
691 /*
692  * Helper function which writes out a directory block.
693  */
694 static int write_dir_block(ext2_filsys fs,
695                            blk64_t *block_nr,
696                            e2_blkcnt_t blockcnt,
697                            blk64_t ref_block EXT2FS_ATTR((unused)),
698                            int ref_offset EXT2FS_ATTR((unused)),
699                            void *priv_data)
700 {
701         struct write_dir_struct *wd = (struct write_dir_struct *) priv_data;
702         blk64_t blk;
703         char    *dir, *buf = 0;
704
705         if (*block_nr == 0)
706                 return 0;
707         if (blockcnt < 0)
708                 return 0;
709         if (blockcnt < wd->outdir->num)
710                 dir = wd->outdir->buf + (blockcnt * fs->blocksize);
711         else if (wd->ctx->lost_and_found == wd->dir) {
712                 /* Don't release any extra directory blocks for lost+found */
713                 wd->err = ext2fs_new_dir_block(fs, 0, 0, &buf);
714                 if (wd->err)
715                         return BLOCK_ABORT;
716                 dir = buf;
717                 wd->outdir->num++;
718         } else {
719                 /* We don't need this block, so release it */
720                 e2fsck_read_bitmaps(wd->ctx);
721                 blk = *block_nr;
722                 ext2fs_unmark_block_bitmap2(wd->ctx->block_found_map, blk);
723                 ext2fs_block_alloc_stats2(fs, blk, -1);
724                 *block_nr = 0;
725                 wd->cleared++;
726                 return BLOCK_CHANGED;
727         }
728
729         wd->err = ext2fs_write_dir_block4(fs, *block_nr, dir, 0, wd->dir);
730         if (buf)
731                 ext2fs_free_mem(&buf);
732
733         if (wd->err)
734                 return BLOCK_ABORT;
735         return 0;
736 }
737
738 static errcode_t write_directory(e2fsck_t ctx, ext2_filsys fs,
739                                  struct out_dir *outdir,
740                                  ext2_ino_t ino, int compress)
741 {
742         struct write_dir_struct wd;
743         errcode_t       retval;
744         struct ext2_inode       inode;
745
746         retval = e2fsck_expand_directory(ctx, ino, -1, outdir->num);
747         if (retval)
748                 return retval;
749
750         wd.outdir = outdir;
751         wd.err = 0;
752         wd.ctx = ctx;
753         wd.cleared = 0;
754         wd.dir = ino;
755
756         retval = ext2fs_block_iterate3(fs, ino, 0, 0,
757                                        write_dir_block, &wd);
758         if (retval)
759                 return retval;
760         if (wd.err)
761                 return wd.err;
762
763         e2fsck_read_inode(ctx, ino, &inode, "rehash_dir");
764         if (compress)
765                 inode.i_flags &= ~EXT2_INDEX_FL;
766         else
767                 inode.i_flags |= EXT2_INDEX_FL;
768         inode.i_size = outdir->num * fs->blocksize;
769         ext2fs_iblk_sub_blocks(fs, &inode, wd.cleared);
770         e2fsck_write_inode(ctx, ino, &inode, "rehash_dir");
771
772         return 0;
773 }
774
775 errcode_t e2fsck_rehash_dir(e2fsck_t ctx, ext2_ino_t ino)
776 {
777         ext2_filsys             fs = ctx->fs;
778         errcode_t               retval;
779         struct ext2_inode       inode;
780         char                    *dir_buf = 0;
781         struct fill_dir_struct  fd;
782         struct out_dir          outdir;
783
784         outdir.max = outdir.num = 0;
785         outdir.buf = 0;
786         outdir.hashes = 0;
787         e2fsck_read_inode(ctx, ino, &inode, "rehash_dir");
788
789         retval = ENOMEM;
790         fd.harray = 0;
791         dir_buf = malloc(inode.i_size);
792         if (!dir_buf)
793                 goto errout;
794
795         fd.max_array = inode.i_size / 32;
796         fd.num_array = 0;
797         fd.harray = malloc(fd.max_array * sizeof(struct hash_entry));
798         if (!fd.harray)
799                 goto errout;
800
801         fd.ctx = ctx;
802         fd.buf = dir_buf;
803         fd.inode = &inode;
804         fd.err = 0;
805         fd.dir_size = 0;
806         fd.compress = 0;
807         fd.dir = ino;
808         if (!(fs->super->s_feature_compat & EXT2_FEATURE_COMPAT_DIR_INDEX) ||
809             (inode.i_size / fs->blocksize) < 2)
810                 fd.compress = 1;
811         fd.parent = 0;
812
813 retry_nohash:
814         /* Read in the entire directory into memory */
815         retval = ext2fs_block_iterate3(fs, ino, 0, 0,
816                                        fill_dir_block, &fd);
817         if (fd.err) {
818                 retval = fd.err;
819                 goto errout;
820         }
821
822         /* 
823          * If the entries read are less than a block, then don't index
824          * the directory
825          */
826         if (!fd.compress && (fd.dir_size < (fs->blocksize - 24))) {
827                 fd.compress = 1;
828                 fd.dir_size = 0;
829                 fd.num_array = 0;
830                 goto retry_nohash;
831         }
832
833 #if 0
834         printf("%d entries (%d bytes) found in inode %d\n",
835                fd.num_array, fd.dir_size, ino);
836 #endif
837
838         /* Sort the list */
839 resort:
840         if (fd.compress)
841                 qsort(fd.harray+2, fd.num_array-2, sizeof(struct hash_entry),
842                       hash_cmp);
843         else
844                 qsort(fd.harray, fd.num_array, sizeof(struct hash_entry),
845                       hash_cmp);
846
847         /*
848          * Look for duplicates
849          */
850         if (duplicate_search_and_fix(ctx, fs, ino, &fd))
851                 goto resort;
852
853         if (ctx->options & E2F_OPT_NO) {
854                 retval = 0;
855                 goto errout;
856         }
857
858         /* Sort non-hashed directories by inode number */
859         if (fd.compress)
860                 qsort(fd.harray+2, fd.num_array-2,
861                       sizeof(struct hash_entry), ino_cmp);
862
863         /*
864          * Copy the directory entries.  In a htree directory these
865          * will become the leaf nodes.
866          */
867         retval = copy_dir_entries(ctx, &fd, &outdir);
868         if (retval)
869                 goto errout;
870
871         free(dir_buf); dir_buf = 0;
872
873         if (!fd.compress) {
874                 /* Calculate the interior nodes */
875                 retval = calculate_tree(fs, &outdir, ino, fd.parent);
876                 if (retval)
877                         goto errout;
878         }
879
880         retval = write_directory(ctx, fs, &outdir, ino, fd.compress);
881         if (retval)
882                 goto errout;
883
884 errout:
885         free(dir_buf);
886         free(fd.harray);
887
888         free_out_dir(&outdir);
889         return retval;
890 }
891
892 void e2fsck_rehash_directories(e2fsck_t ctx)
893 {
894         struct problem_context  pctx;
895 #ifdef RESOURCE_TRACK
896         struct resource_track   rtrack;
897 #endif
898         struct dir_info         *dir;
899         ext2_u32_iterate        iter;
900         struct dir_info_iter *  dirinfo_iter = 0;
901         ext2_ino_t              ino;
902         errcode_t               retval;
903         int                     cur, max, all_dirs, first = 1;
904
905         init_resource_track(&rtrack, ctx->fs->io);
906         all_dirs = ctx->options & E2F_OPT_COMPRESS_DIRS;
907
908         if (!ctx->dirs_to_hash && !all_dirs)
909                 return;
910
911         (void) e2fsck_get_lost_and_found(ctx, 0);
912
913         clear_problem_context(&pctx);
914
915         cur = 0;
916         if (all_dirs) {
917                 dirinfo_iter = e2fsck_dir_info_iter_begin(ctx);
918                 max = e2fsck_get_num_dirinfo(ctx);
919         } else {
920                 retval = ext2fs_u32_list_iterate_begin(ctx->dirs_to_hash,
921                                                        &iter);
922                 if (retval) {
923                         pctx.errcode = retval;
924                         fix_problem(ctx, PR_3A_OPTIMIZE_ITER, &pctx);
925                         return;
926                 }
927                 max = ext2fs_u32_list_count(ctx->dirs_to_hash);
928         }
929         while (1) {
930                 if (all_dirs) {
931                         if ((dir = e2fsck_dir_info_iter(ctx,
932                                                         dirinfo_iter)) == 0)
933                                 break;
934                         ino = dir->ino;
935                 } else {
936                         if (!ext2fs_u32_list_iterate(iter, &ino))
937                                 break;
938                 }
939
940                 pctx.dir = ino;
941                 if (first) {
942                         fix_problem(ctx, PR_3A_PASS_HEADER, &pctx);
943                         first = 0;
944                 }
945 #if 0
946                 fix_problem(ctx, PR_3A_OPTIMIZE_DIR, &pctx);
947 #endif
948                 pctx.errcode = e2fsck_rehash_dir(ctx, ino);
949                 if (pctx.errcode) {
950                         end_problem_latch(ctx, PR_LATCH_OPTIMIZE_DIR);
951                         fix_problem(ctx, PR_3A_OPTIMIZE_DIR_ERR, &pctx);
952                 }
953                 if (ctx->progress && !ctx->progress_fd)
954                         e2fsck_simple_progress(ctx, "Rebuilding directory",
955                                100.0 * (float) (++cur) / (float) max, ino);
956         }
957         end_problem_latch(ctx, PR_LATCH_OPTIMIZE_DIR);
958         if (all_dirs)
959                 e2fsck_dir_info_iter_end(ctx, dirinfo_iter);
960         else
961                 ext2fs_u32_list_iterate_end(iter);
962
963         if (ctx->dirs_to_hash)
964                 ext2fs_u32_list_free(ctx->dirs_to_hash);
965         ctx->dirs_to_hash = 0;
966
967         print_resource_track(ctx, "Pass 3A", &rtrack, ctx->fs->io);
968 }