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