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