10 #include "create_fs.h"
14 #define ROOT_DIR_BLK 3
16 #define SECTOR_SIZE 512
18 void safe_strncpy(char *dest
, char *src
, int dest_size
)
20 strncpy(dest
, src
, dest_size
-1);
21 dest
[dest_size
-1] = 0;
24 void clear_dev(FILE *fp
, u64 sectors
)
27 char blk
[SECTOR_SIZE
];
31 memset(blk
, 0, sizeof(blk
));
32 for (i
=0; i
<sectors
; i
++)
34 fwrite(blk
, 1, sizeof(blk
), fp
);
39 int create_fs(FILE *fp
, u64 sectors
, fs_config_t
*config
)
42 int block_size
= config
->block_size
;
46 int blocks_per_sector
= block_size
/ SECTOR_SIZE
;
47 int blocks
= sectors
/ blocks_per_sector
;
49 if (config
->clear_dev
)
50 clear_dev(fp
, sectors
);
54 .s_root_block
= swap_be64(ROOT_BLK
),
55 .s_num_blocks
= swap_be64(blocks
),
56 .s_magic
= swap_be32(OMFS_MAGIC
),
57 .s_blocksize
= swap_be32(block_size
),
58 .s_mirrors
= swap_be32(2),
59 .s_sys_blocksize
= swap_be32(2048),
64 .r_head
.h_self
= swap_be64(ROOT_BLK
),
65 .r_head
.h_body_size
= swap_be32(sizeof(omfs_root_t
) - sizeof(struct omfs_header
)),
66 .r_head
.h_version
= 1,
67 .r_head
.h_type
= OMFS_INODE_SYSTEM
,
68 .r_head
.h_magic
= OMFS_IMAGIC
,
69 .r_num_blocks
= super
.s_num_blocks
,
70 .r_root_dir
= swap_be64(ROOT_DIR_BLK
),
71 .r_bitmap
= swap_be64(BITMAP_BLK
),
72 .r_blocksize
= super
.s_blocksize
,
73 .r_clustersize
= swap_be32(config
->cluster_size
),
74 .r_mirrors
= swap_be64(super
.s_mirrors
),
79 safe_strncpy(super
.s_name
, label
, OMFS_SUPER_NAMELEN
);
80 safe_strncpy(root
.r_name
, label
, OMFS_NAMELEN
);
85 info
.bitmap
= &bitmap
;
89 omfs_write_super(&info
);
90 omfs_write_root_block(&info
);
92 u64 now
= time(NULL
) * 1000LL;
95 omfs_inode_t root_ino
= {
96 .i_head
.h_self
= swap_be64(ROOT_DIR_BLK
),
97 .i_head
.h_body_size
= swap_be32(swap_be32(super
.s_sys_blocksize
) - sizeof(omfs_header_t
)),
98 .i_head
.h_version
= 1,
99 .i_head
.h_type
= OMFS_INODE_NORMAL
,
100 .i_head
.h_magic
= OMFS_IMAGIC
,
103 .i_ctime
= swap_be64(now
),
105 .i_fill2
= swap_be32(1),
106 .i_size
= swap_be64(swap_be32(super
.s_sys_blocksize
))
109 u8
*data
= calloc(1, swap_be32(super
.s_sys_blocksize
));
113 memcpy(data
, &root_ino
, sizeof (omfs_inode_t
));
114 memset(data
+ OMFS_DIR_START
, 0xff,
115 swap_be32(super
.s_sys_blocksize
) - OMFS_DIR_START
);
117 omfs_write_inode(&info
, (omfs_inode_t
*) data
);
121 // free space bitmap. We already know that blocks 0-5 are
122 // going to be set; the first available cluster has to take
123 // into account the size of the free space bitmap.
124 int bitmap_size
= (swap_be64(super
.s_num_blocks
) + 7)/8;
125 int dirty_size
= (bitmap_size
+ 7)/8;
126 int first_blk
= BITMAP_BLK
+ (bitmap_size
+
127 swap_be32(super
.s_blocksize
)-1) / swap_be32(super
.s_blocksize
);
129 bitmap
.bmap
= calloc(1, bitmap_size
);
131 for (i
=0; i
<first_blk
; i
++)
133 bitmap
.bmap
[i
/8] |= 1<<(i
& 7);
136 bitmap
.dirty
= malloc(dirty_size
);
137 memset(bitmap
.dirty
, 0xff, dirty_size
);
138 omfs_flush_bitmap(&info
);