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