5 Copyright (C) 2011, 2012 Andrew Nayenko
7 This program is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>.
21 #include <sys/types.h>
28 static int check_size(off_t volume_size)
30 const struct fs_object** pp;
33 for (pp = objects; *pp; pp++)
35 position = ROUND_UP(position, (*pp)->get_alignment());
36 position += (*pp)->get_size();
39 if (position > volume_size)
41 struct exfat_human_bytes vhb;
43 exfat_humanize_bytes(volume_size, &vhb);
44 exfat_error("too small device (%"PRIu64" %s)", vhb.value, vhb.unit);
52 static int erase_object(struct exfat_dev* dev, const void* block,
53 size_t block_size, off_t start, off_t size)
55 const off_t block_count = DIV_ROUND_UP(size, block_size);
58 if (exfat_seek(dev, start, SEEK_SET) == (off_t) -1)
60 exfat_error("seek to 0x%"PRIx64" failed", start);
63 for (i = 0; i < size; i += block_size)
65 if (exfat_write(dev, block, MIN(size - i, block_size)) < 0)
67 exfat_error("failed to erase block %"PRIu64"/%"PRIu64
68 " at 0x%"PRIx64, i + 1, block_count, start);
75 static int erase(struct exfat_dev* dev)
77 const struct fs_object** pp;
79 const size_t block_size = 1024 * 1024;
80 void* block = malloc(block_size);
84 exfat_error("failed to allocate erase block of %zu bytes", block_size);
87 memset(block, 0, block_size);
89 for (pp = objects; *pp; pp++)
91 position = ROUND_UP(position, (*pp)->get_alignment());
92 if (erase_object(dev, block, block_size, position,
93 (*pp)->get_size()) != 0)
98 position += (*pp)->get_size();
105 static int create(struct exfat_dev* dev)
107 const struct fs_object** pp;
110 for (pp = objects; *pp; pp++)
112 position = ROUND_UP(position, (*pp)->get_alignment());
113 if (exfat_seek(dev, position, SEEK_SET) == (off_t) -1)
115 exfat_error("seek to 0x%"PRIx64" failed", position);
118 if ((*pp)->write(dev) != 0)
120 position += (*pp)->get_size();
125 int mkfs(struct exfat_dev* dev, off_t volume_size)
127 if (check_size(volume_size) != 0)
130 fputs("Creating... ", stdout);
134 if (create(dev) != 0)
138 fputs("Flushing... ", stdout);
140 if (exfat_fsync(dev) != 0)
147 off_t get_position(const struct fs_object* object)
149 const struct fs_object** pp;
152 for (pp = objects; *pp; pp++)
154 position = ROUND_UP(position, (*pp)->get_alignment());
157 position += (*pp)->get_size();
159 exfat_bug("unknown object");