Whamcloud - gitweb
2cd541d7f16bc3fb5b05b288f25ae62640beb5d2
[tools/e2fsprogs.git] / lib / ext2fs / newdir.c
1 /*
2  * newdir.c --- create a new directory block
3  *
4  * Copyright (C) 1994, 1995 Theodore Ts'o.
5  *
6  * %Begin-Header%
7  * This file may be redistributed under the terms of the GNU Library
8  * General Public License, version 2.
9  * %End-Header%
10  */
11
12 #include "config.h"
13 #include <stdio.h>
14 #include <string.h>
15 #if HAVE_UNISTD_H
16 #include <unistd.h>
17 #endif
18
19 #include "ext2_fs.h"
20 #include "ext2fs.h"
21
22 #ifndef EXT2_FT_DIR
23 #define EXT2_FT_DIR             2
24 #endif
25
26 /*
27  * Create new directory block
28  */
29 errcode_t ext2fs_new_dir_block(ext2_filsys fs, ext2_ino_t dir_ino,
30                                ext2_ino_t parent_ino, char **block)
31 {
32         struct ext2_dir_entry   *dir = NULL;
33         errcode_t               retval;
34         char                    *buf;
35         int                     rec_len;
36         int                     filetype = 0;
37         struct ext2_dir_entry_tail      *t;
38         int                     csum_size = 0;
39
40         EXT2_CHECK_MAGIC(fs, EXT2_ET_MAGIC_EXT2FS_FILSYS);
41
42         retval = ext2fs_get_mem(fs->blocksize, &buf);
43         if (retval)
44                 return retval;
45         memset(buf, 0, fs->blocksize);
46         dir = (struct ext2_dir_entry *) buf;
47
48         if (EXT2_HAS_RO_COMPAT_FEATURE(fs->super,
49                                        EXT4_FEATURE_RO_COMPAT_METADATA_CSUM))
50                 csum_size = sizeof(struct ext2_dir_entry_tail);
51
52         retval = ext2fs_set_rec_len(fs, fs->blocksize - csum_size, dir);
53         if (retval)
54                 return retval;
55
56         if (dir_ino) {
57                 if (fs->super->s_feature_incompat &
58                     EXT2_FEATURE_INCOMPAT_FILETYPE)
59                         filetype = EXT2_FT_DIR << 8;
60                 /*
61                  * Set up entry for '.'
62                  */
63                 dir->inode = dir_ino;
64                 dir->name_len = 1 | filetype;
65                 dir->name[0] = '.';
66                 rec_len = (fs->blocksize - csum_size) - EXT2_DIR_REC_LEN(1);
67                 dir->rec_len = EXT2_DIR_REC_LEN(1);
68
69                 /*
70                  * Set up entry for '..'
71                  */
72                 dir = (struct ext2_dir_entry *) (buf + dir->rec_len);
73                 retval = ext2fs_set_rec_len(fs, rec_len, dir);
74                 if (retval)
75                         return retval;
76                 dir->inode = parent_ino;
77                 dir->name_len = 2 | filetype;
78                 dir->name[0] = '.';
79                 dir->name[1] = '.';
80
81         }
82
83         if (csum_size) {
84                 t = EXT2_DIRENT_TAIL(buf, fs->blocksize);
85                 ext2fs_initialize_dirent_tail(fs, t);
86         }
87         *block = buf;
88         return 0;
89 }