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