mkexfat: Fix FAT initialization
[helenos.git] / uspace / app / mkexfat / mkexfat.c
blob14331ba261a48807540864db59b1f8e4bf4abdc5
1 /*
2 * Copyright (c) 2012 Maurizio Lombardi
3 * All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
9 * - Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * - Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 * - The name of the author may not be used to endorse or promote products
15 * derived from this software without specific prior written permission.
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 /** @addtogroup fs
30 * @{
33 /**
34 * @file mkexfat.c
35 * @brief Tool for creating new exFAT file systems.
39 #include <stdio.h>
40 #include <libblock.h>
41 #include <assert.h>
42 #include <errno.h>
43 #include <malloc.h>
44 #include <byteorder.h>
45 #include <align.h>
46 #include <sys/types.h>
47 #include <sys/typefmt.h>
48 #include "exfat.h"
50 #define NAME "mkexfat"
52 /** First sector of the FAT */
53 #define FAT_SECTOR_START 128
55 /** First sector of the Main Extended Boot Region */
56 #define EBS_SECTOR_START 1
58 /** First sector of the Main Extended Boot Region Backup */
59 #define EBS_BACKUP_SECTOR_START 13
61 /** First sector of the Main Boot Sector */
62 #define MBS_SECTOR 0
64 /** First sector of the Main Boot Sector Backup */
65 #define MBS_BACKUP_SECTOR 12
67 /** Size of the Main Extended Boot Region */
68 #define EBS_SIZE 8
70 /** Divide and round up. */
71 #define div_round_up(a, b) (((a) + (b) - 1) / (b))
73 /** The default size of each cluster is 4096 byte */
74 #define DEFAULT_CLUSTER_SIZE 4096
76 typedef struct exfat_cfg {
77 aoff64_t volume_start;
78 aoff64_t volume_count;
79 unsigned long fat_sector_count;
80 unsigned long data_start_sector;
81 unsigned long rootdir_cluster;
82 unsigned long total_clusters;
83 size_t sector_size;
84 size_t cluster_size;
85 } exfat_cfg_t;
88 static unsigned log2(unsigned n);
90 static uint32_t
91 vbr_checksum_start(void const *octets, size_t nbytes);
93 static void
94 vbr_checksum_update(void const *octets, size_t nbytes, uint32_t *checksum);
96 static int
97 ebs_write(service_id_t service_id, exfat_cfg_t *cfg,
98 int base, uint32_t *chksum);
100 static void usage(void)
102 printf("Usage: mkexfat <device>\n");
105 /** Initialize the exFAT params structure.
107 * @param cfg Pointer to the exFAT params structure to initialize.
109 static void
110 cfg_params_initialize(exfat_cfg_t *cfg)
112 unsigned long fat_bytes;
113 aoff64_t const volume_bytes = (cfg->volume_count - FAT_SECTOR_START) *
114 cfg->sector_size;
116 aoff64_t n_req_clusters = volume_bytes / DEFAULT_CLUSTER_SIZE;
117 cfg->cluster_size = DEFAULT_CLUSTER_SIZE;
119 /* Compute the required cluster size to index
120 * the entire storage device and to keep the FAT
121 * size less or equal to 64 Mb.
123 while (n_req_clusters > 16000000ULL &&
124 (cfg->cluster_size < 32 * 1024 * 1024)) {
126 cfg->cluster_size <<= 1;
127 n_req_clusters = volume_bytes / cfg->cluster_size;
130 /* The first two clusters are reserved */
131 cfg->total_clusters = n_req_clusters + 2;
133 /* Compute the FAT size in sectors */
134 fat_bytes = (cfg->total_clusters + 1) * 4;
135 cfg->fat_sector_count = div_round_up(fat_bytes, cfg->sector_size);
137 /* Compute the number of the first data sector */
138 cfg->data_start_sector = ROUND_UP(FAT_SECTOR_START +
139 cfg->fat_sector_count, cfg->cluster_size / cfg->sector_size);
141 cfg->rootdir_cluster = 0;
143 /* The first sector of the partition is zero */
144 cfg->volume_start = 0;
147 /** Prints the exFAT structure values
149 * @param cfg Pointer to the exfat_cfg_t structure.
151 static void
152 cfg_print_info(exfat_cfg_t *cfg)
154 printf(NAME ": Sector size: %lu\n", cfg->sector_size);
155 printf(NAME ": Cluster size: %lu\n", cfg->cluster_size);
156 printf(NAME ": FAT size in sectors: %lu\n", cfg->fat_sector_count);
157 printf(NAME ": Data start sector: %lu\n", cfg->data_start_sector);
158 printf(NAME ": Total num of clusters: %lu\n", cfg->total_clusters);
161 /** Initialize the Main Boot Sector fields.
163 * @param mbs Pointer to the Main Boot Sector structure.
164 * @param cfg Pointer to the exFAT configuration structure.
165 * @return Initial checksum value.
167 static uint32_t
168 vbr_initialize(exfat_bs_t *mbs, exfat_cfg_t *cfg)
170 /* Fill the structure with zeroes */
171 memset(mbs, 0, sizeof(exfat_bs_t));
173 /* Init Jump Boot section */
174 mbs->jump[0] = 0xEB;
175 mbs->jump[1] = 0x76;
176 mbs->jump[2] = 0x90;
178 /* Set the filesystem name */
179 memcpy(mbs->oem_name, "EXFAT ", sizeof(mbs->oem_name));
181 mbs->volume_start = host2uint64_t_le(cfg->volume_start);
182 mbs->volume_count = host2uint64_t_le(cfg->volume_count);
183 mbs->fat_sector_start = host2uint32_t_le(FAT_SECTOR_START);
184 mbs->fat_sector_count = host2uint32_t_le(cfg->fat_sector_count);
185 mbs->data_start_sector = host2uint32_t_le(cfg->data_start_sector);
187 mbs->data_clusters = host2uint32_t_le(cfg->total_clusters -
188 div_round_up(cfg->data_start_sector, cfg->cluster_size));
190 mbs->rootdir_cluster = 0;
191 mbs->volume_serial = 0;
192 mbs->version.major = 1;
193 mbs->version.minor = 0;
194 mbs->volume_flags = host2uint16_t_le(0);
195 mbs->bytes_per_sector = log2(cfg->sector_size);
196 mbs->sec_per_cluster = log2(cfg->cluster_size / cfg->sector_size);
198 /* Maximum cluster size is 32 Mb */
199 assert((mbs->bytes_per_sector + mbs->sec_per_cluster) <= 25);
201 mbs->fat_count = 1;
202 mbs->drive_no = 0x80;
203 mbs->allocated_percent = 0;
204 mbs->signature = host2uint16_t_le(0xAA55);
206 return vbr_checksum_start(mbs, sizeof(exfat_bs_t));
209 static int
210 bootsec_write(service_id_t service_id, exfat_cfg_t *cfg)
212 exfat_bs_t mbs;
213 uint32_t vbr_checksum;
214 uint32_t initial_checksum;
215 int rc;
217 vbr_checksum = vbr_initialize(&mbs, cfg);
218 initial_checksum = vbr_checksum;
220 /* Write the Main Boot Sector to disk */
221 rc = block_write_direct(service_id, MBS_SECTOR, 1, &mbs);
222 if (rc != EOK)
223 return rc;
225 /* Write the Main extended boot sectors to disk */
226 rc = ebs_write(service_id, cfg, EBS_SECTOR_START, &vbr_checksum);
227 if (rc != EOK)
228 return rc;
230 /* Write the Main Boot Sector backup to disk */
231 rc = block_write_direct(service_id, MBS_BACKUP_SECTOR, 1, &mbs);
232 if (rc != EOK)
233 return rc;
235 /* Restore the checksum to its initial value */
236 vbr_checksum = initial_checksum;
238 /* Write the Main extended boot sectors backup to disk */
239 return ebs_write(service_id, cfg,
240 EBS_BACKUP_SECTOR_START, &vbr_checksum);
243 /** Write the Main Extended Boot Sector to disk
245 * @param service_id The service id.
246 * @param cfg Pointer to the exFAT configuration structure.
247 * @param base Base sector of the EBS.
248 * @return EOK on success or a negative error code.
250 static int
251 ebs_write(service_id_t service_id, exfat_cfg_t *cfg, int base, uint32_t *chksum)
253 uint32_t *ebs = calloc(cfg->sector_size, sizeof(uint8_t));
254 int i, rc;
255 unsigned idx;
257 if (!ebs)
258 return ENOMEM;
260 ebs[cfg->sector_size / 4 - 1] = host2uint32_t_le(0xAA550000);
262 for (i = 0; i < EBS_SIZE; ++i) {
263 vbr_checksum_update(ebs, cfg->sector_size, chksum);
265 rc = block_write_direct(service_id,
266 i + EBS_SECTOR_START + base, 1, ebs);
268 if (rc != EOK)
269 goto exit;
272 /* The OEM record is not yet used
273 * by the official exFAT implementation, we'll fill
274 * it with zeroes.
277 memset(ebs, 0, cfg->sector_size);
278 vbr_checksum_update(ebs, cfg->sector_size, chksum);
280 rc = block_write_direct(service_id, i++ + base, 1, ebs);
281 if (rc != EOK)
282 goto exit;
284 /* The next sector is reserved, fill it with zeroes too */
285 vbr_checksum_update(ebs, cfg->sector_size, chksum);
286 rc = block_write_direct(service_id, i++ + base, 1, ebs);
287 if (rc != EOK)
288 goto exit;
290 /* Write the checksum sector */
291 for (idx = 0; idx < cfg->sector_size / sizeof(uint32_t); ++idx)
292 ebs[idx] = host2uint32_t_le(*chksum);
294 rc = block_write_direct(service_id, i + base, 1, ebs);
296 exit:
297 free(ebs);
298 return rc;
301 /** Writes the FAT on disk.
303 * @param service_id The service id.
304 * @param cfg Pointer to the exfat_cfg structure.
305 * @return EOK on success or a negative error code.
307 static int
308 fat_write(service_id_t service_id, exfat_cfg_t *cfg)
310 unsigned long i;
311 uint32_t *pfat;
312 int rc;
314 pfat = calloc(cfg->fat_sector_count, cfg->sector_size);
315 if (!pfat)
316 return ENOMEM;
318 pfat[0] = host2uint32_t_le(0xFFFFFFF8);
319 pfat[1] = host2uint32_t_le(0xFFFFFFFF);
321 /* Allocate clusters for the bitmap, upcase table
322 * and the root directory.
324 pfat[2] = host2uint32_t_le(0xFFFFFFFF);
325 pfat[3] = host2uint32_t_le(0xFFFFFFFF);
326 pfat[4] = host2uint32_t_le(0xFFFFFFFF);
328 rc = block_write_direct(service_id, FAT_SECTOR_START, 1, pfat);
329 if (rc != EOK)
330 goto error;
332 memset(pfat, 0, 5 * sizeof(uint32_t));
334 for (i = 1; i < cfg->fat_sector_count + 1; ++i) {
335 rc = block_write_direct(service_id,
336 FAT_SECTOR_START + i, 1, pfat);
337 if (rc != EOK)
338 goto error;
341 error:
342 free(pfat);
343 return rc;
346 /** Given a number (n), returns the result of log2(n).
348 * It works only if n is a power of two.
350 static unsigned
351 log2(unsigned n)
353 unsigned r;
355 for (r = 0;n >> r != 1; ++r);
357 return r;
360 /** Initialize the VBR checksum calculation */
361 static uint32_t
362 vbr_checksum_start(void const *data, size_t nbytes)
364 uint32_t checksum = 0;
365 size_t index;
366 uint8_t const *octets = (uint8_t *) data;
368 for (index = 0; index < nbytes; ++index) {
369 if (index == 106 || index == 107 || index == 112) {
370 /* Skip volume_flags and allocated_percent fields */
371 continue;
374 checksum = ((checksum << 31) | (checksum >> 1)) + octets[index];
377 return checksum;
380 /** Update the VBR checksum */
381 static void
382 vbr_checksum_update(void const *data, size_t nbytes, uint32_t *checksum)
384 size_t index;
385 uint8_t const *octets = (uint8_t *) data;
387 for (index = 0; index < nbytes; ++index)
388 *checksum = ((*checksum << 31) | (*checksum >> 1)) + octets[index];
391 int main (int argc, char **argv)
393 exfat_cfg_t cfg;
394 char *dev_path;
395 service_id_t service_id;
396 int rc;
398 if (argc < 2) {
399 printf(NAME ": Error, argument missing\n");
400 usage();
401 return 1;
404 /* TODO: Add parameters */
406 ++argv;
407 dev_path = *argv;
409 printf(NAME ": Device = %s\n", dev_path);
411 rc = loc_service_get_id(dev_path, &service_id, 0);
412 if (rc != EOK) {
413 printf(NAME ": Error resolving device `%s'.\n", dev_path);
414 return 2;
417 rc = block_init(EXCHANGE_SERIALIZE, service_id, 2048);
418 if (rc != EOK) {
419 printf(NAME ": Error initializing libblock.\n");
420 return 2;
423 rc = block_get_bsize(service_id, &cfg.sector_size);
424 if (rc != EOK) {
425 printf(NAME ": Error determining device block size.\n");
426 return 2;
429 if (cfg.sector_size > 4096) {
430 printf(NAME ": Error, sector size can't be greater" \
431 " than 4096 bytes.\n");
432 return 2;
435 rc = block_get_nblocks(service_id, &cfg.volume_count);
436 if (rc != EOK) {
437 printf(NAME ": Warning, failed to obtain" \
438 " device block size.\n");
439 /* FIXME: the user should be able to specify the filesystem size */
440 return 1;
441 } else {
442 printf(NAME ": Block device has %" PRIuOFF64 " blocks.\n",
443 cfg.volume_count);
446 cfg_params_initialize(&cfg);
447 cfg_print_info(&cfg);
449 rc = bootsec_write(service_id, &cfg);
450 if (rc != EOK) {
451 printf(NAME ": Error, failed to write the VBR to disk\n");
452 return 2;
455 rc = fat_write(service_id, &cfg);
456 if (rc != EOK) {
457 printf(NAME ": Error, failed to write the FAT to disk\n");
458 return 2;
461 return 0;