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