1 /*
2 * Copyright (c) 1998 Robert Nordier
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in
12 * the documentation and/or other materials provided with the
13 * distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS
16 * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
17 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY
19 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
21 * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
23 * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
24 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
25 * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28 #ifndef lint
29 static const char rcsid[] =
30 "$FreeBSD$";
31 #endif /* not lint */
32
33 #include <sys/param.h>
34 #ifdef MAKEFS
35 /* In the makefs case we only want struct disklabel */
36 #include <sys/disk/bsd.h>
37 #elif defined(__linux__)
38 #include <linux/fs.h>
39 #include <linux/hdreg.h>
40 #include <sys/ioctl.h>
41 #else
42 #include <sys/fdcio.h>
43 #include <sys/disk.h>
44 #include <sys/disklabel.h>
45 #include <sys/mount.h>
46 #endif
47 #include <sys/stat.h>
48 // #include <sys/sysctl.h>
49 #include <sys/time.h>
50
51 #include <assert.h>
52 #include <ctype.h>
53 #include <err.h>
54 #include <errno.h>
55 #include <fcntl.h>
56 #include <inttypes.h>
57 #include <paths.h>
58 #include <signal.h>
59 #include <stdio.h>
60 #include <stdlib.h>
61 #include <string.h>
62 #include <time.h>
63 #include <unistd.h>
64
65 #include "mkfs_msdos.h"
66
67 #define MAXU16 0xffff /* maximum unsigned 16-bit quantity */
68 #define BPN 4 /* bits per nibble */
69 #define NPB 2 /* nibbles per byte */
70
71 #define DOSMAGIC 0xaa55 /* DOS magic number */
72 #define MINBPS 512 /* minimum bytes per sector */
73 #define MAXBPS 4096 /* maximum bytes per sector */
74 #define MAXSPC 128 /* maximum sectors per cluster */
75 #define MAXNFT 16 /* maximum number of FATs */
76 #define DEFBLK 4096 /* default block size */
77 #define DEFBLK16 2048 /* default block size FAT16 */
78 #define DEFRDE 512 /* default root directory entries */
79 #define RESFTE 2 /* reserved FAT entries */
80 #define MINCLS12 1U /* minimum FAT12 clusters */
81 #define MINCLS16 0xff5U /* minimum FAT16 clusters */
82 #define MINCLS32 0xfff5U /* minimum FAT32 clusters */
83 #define MAXCLS12 0xff4U /* maximum FAT12 clusters */
84 #define MAXCLS16 0xfff4U /* maximum FAT16 clusters */
85 #define MAXCLS32 0xffffff4U /* maximum FAT32 clusters */
86
87 #define mincls(fat) ((fat) == 12 ? MINCLS12 : \
88 (fat) == 16 ? MINCLS16 : \
89 MINCLS32)
90
91 #define maxcls(fat) ((fat) == 12 ? MAXCLS12 : \
92 (fat) == 16 ? MAXCLS16 : \
93 MAXCLS32)
94
95 #define mk1(p, x) \
96 (p) = (u_int8_t)(x)
97
98 #define mk2(p, x) \
99 (p)[0] = (u_int8_t)(x), \
100 (p)[1] = (u_int8_t)((x) >> 010)
101
102 #define mk4(p, x) \
103 (p)[0] = (u_int8_t)(x), \
104 (p)[1] = (u_int8_t)((x) >> 010), \
105 (p)[2] = (u_int8_t)((x) >> 020), \
106 (p)[3] = (u_int8_t)((x) >> 030)
107
108 struct bs {
109 u_int8_t bsJump[3]; /* bootstrap entry point */
110 u_int8_t bsOemName[8]; /* OEM name and version */
111 }/* __packed */;
112
113 struct bsbpb {
114 u_int8_t bpbBytesPerSec[2]; /* bytes per sector */
115 u_int8_t bpbSecPerClust; /* sectors per cluster */
116 u_int8_t bpbResSectors[2]; /* reserved sectors */
117 u_int8_t bpbFATs; /* number of FATs */
118 u_int8_t bpbRootDirEnts[2]; /* root directory entries */
119 u_int8_t bpbSectors[2]; /* total sectors */
120 u_int8_t bpbMedia; /* media descriptor */
121 u_int8_t bpbFATsecs[2]; /* sectors per FAT */
122 u_int8_t bpbSecPerTrack[2]; /* sectors per track */
123 u_int8_t bpbHeads[2]; /* drive heads */
124 u_int8_t bpbHiddenSecs[4]; /* hidden sectors */
125 u_int8_t bpbHugeSectors[4]; /* big total sectors */
126 }/* __packed */;
127
128 struct bsxbpb {
129 u_int8_t bpbBigFATsecs[4]; /* big sectors per FAT */
130 u_int8_t bpbExtFlags[2]; /* FAT control flags */
131 u_int8_t bpbFSVers[2]; /* file system version */
132 u_int8_t bpbRootClust[4]; /* root directory start cluster */
133 u_int8_t bpbFSInfo[2]; /* file system info sector */
134 u_int8_t bpbBackup[2]; /* backup boot sector */
135 u_int8_t bpbReserved[12]; /* reserved */
136 }/* __packed */;
137
138 struct bsx {
139 u_int8_t exDriveNumber; /* drive number */
140 u_int8_t exReserved1; /* reserved */
141 u_int8_t exBootSignature; /* extended boot signature */
142 u_int8_t exVolumeID[4]; /* volume ID number */
143 u_int8_t exVolumeLabel[11]; /* volume label */
144 u_int8_t exFileSysType[8]; /* file system type */
145 }/* __packed */;
146
147 struct de {
148 u_int8_t deName[11]; /* name and extension */
149 u_int8_t deAttributes; /* attributes */
150 u_int8_t rsvd[10]; /* reserved */
151 u_int8_t deMTime[2]; /* last-modified time */
152 u_int8_t deMDate[2]; /* last-modified date */
153 u_int8_t deStartCluster[2]; /* starting cluster */
154 u_int8_t deFileSize[4]; /* size */
155 }/* __packed */;
156
157 struct bpb {
158 u_int bpbBytesPerSec; /* bytes per sector */
159 u_int bpbSecPerClust; /* sectors per cluster */
160 u_int bpbResSectors; /* reserved sectors */
161 u_int bpbFATs; /* number of FATs */
162 u_int bpbRootDirEnts; /* root directory entries */
163 u_int bpbSectors; /* total sectors */
164 u_int bpbMedia; /* media descriptor */
165 u_int bpbFATsecs; /* sectors per FAT */
166 u_int bpbSecPerTrack; /* sectors per track */
167 u_int bpbHeads; /* drive heads */
168 u_int bpbHiddenSecs; /* hidden sectors */
169 u_int bpbHugeSectors; /* big total sectors */
170 u_int bpbBigFATsecs; /* big sectors per FAT */
171 u_int bpbRootClust; /* root directory start cluster */
172 u_int bpbFSInfo; /* file system info sector */
173 u_int bpbBackup; /* backup boot sector */
174 };
175
176 #define BPBGAP 0, 0, 0, 0, 0, 0
177
178 static struct {
179 const char *name;
180 struct bpb bpb;
181 } const stdfmt[] = {
182 {"160", {512, 1, 1, 2, 64, 320, 0xfe, 1, 8, 1, BPBGAP}},
183 {"180", {512, 1, 1, 2, 64, 360, 0xfc, 2, 9, 1, BPBGAP}},
184 {"320", {512, 2, 1, 2, 112, 640, 0xff, 1, 8, 2, BPBGAP}},
185 {"360", {512, 2, 1, 2, 112, 720, 0xfd, 2, 9, 2, BPBGAP}},
186 {"640", {512, 2, 1, 2, 112, 1280, 0xfb, 2, 8, 2, BPBGAP}},
187 {"720", {512, 2, 1, 2, 112, 1440, 0xf9, 3, 9, 2, BPBGAP}},
188 {"1200", {512, 1, 1, 2, 224, 2400, 0xf9, 7, 15, 2, BPBGAP}},
189 {"1232", {1024,1, 1, 2, 192, 1232, 0xfe, 2, 8, 2, BPBGAP}},
190 {"1440", {512, 1, 1, 2, 224, 2880, 0xf0, 9, 18, 2, BPBGAP}},
191 {"2880", {512, 2, 1, 2, 240, 5760, 0xf0, 9, 36, 2, BPBGAP}}
192 };
193
194 static const u_int8_t bootcode[] = {
195 0xfa, /* cli */
196 0x31, 0xc0, /* xor ax,ax */
197 0x8e, 0xd0, /* mov ss,ax */
198 0xbc, 0x00, 0x7c, /* mov sp,7c00h */
199 0xfb, /* sti */
200 0x8e, 0xd8, /* mov ds,ax */
201 0xe8, 0x00, 0x00, /* call $ + 3 */
202 0x5e, /* pop si */
203 0x83, 0xc6, 0x19, /* add si,+19h */
204 0xbb, 0x07, 0x00, /* mov bx,0007h */
205 0xfc, /* cld */
206 0xac, /* lodsb */
207 0x84, 0xc0, /* test al,al */
208 0x74, 0x06, /* jz $ + 8 */
209 0xb4, 0x0e, /* mov ah,0eh */
210 0xcd, 0x10, /* int 10h */
211 0xeb, 0xf5, /* jmp $ - 9 */
212 0x30, 0xe4, /* xor ah,ah */
213 0xcd, 0x16, /* int 16h */
214 0xcd, 0x19, /* int 19h */
215 0x0d, 0x0a,
216 'N', 'o', 'n', '-', 's', 'y', 's', 't',
217 'e', 'm', ' ', 'd', 'i', 's', 'k',
218 0x0d, 0x0a,
219 'P', 'r', 'e', 's', 's', ' ', 'a', 'n',
220 'y', ' ', 'k', 'e', 'y', ' ', 't', 'o',
221 ' ', 'r', 'e', 'b', 'o', 'o', 't',
222 0x0d, 0x0a,
223 0
224 };
225
226 static volatile sig_atomic_t got_siginfo;
227 static void infohandler(int);
228
229 static ssize_t getchunksize(void);
230 static int getstdfmt(const char *, struct bpb *);
231 static int getdiskinfo(int, const char *, const char *, int, struct bpb *);
232 static void print_bpb(struct bpb *);
233 static int ckgeom(const char *, u_int, const char *);
234 static void mklabel(u_int8_t *, const char *);
235 static int oklabel(const char *);
236 static void setstr(u_int8_t *, const char *, size_t);
237
238 int
mkfs_msdos(const char * fname,const char * dtype,const struct msdos_options * op)239 mkfs_msdos(const char *fname, const char *dtype, const struct msdos_options *op)
240 {
241 char buf[MAXPATHLEN];
242 struct sigaction si_sa;
243 struct stat sb;
244 struct timeval tv;
245 struct bpb bpb;
246 struct tm *tm;
247 struct bs *bs;
248 struct bsbpb *bsbpb;
249 struct bsxbpb *bsxbpb;
250 struct bsx *bsx;
251 struct de *de;
252 u_int8_t *img;
253 u_int8_t *physbuf, *physbuf_end;
254 const char *bname;
255 ssize_t n;
256 time_t now;
257 u_int fat, bss, rds, cls, dir, lsn, x, x1, x2;
258 u_int extra_res, alignment, saved_x, attempts=0;
259 bool set_res, set_spf, set_spc;
260 int fd, fd1, rv;
261 struct msdos_options o = *op;
262 ssize_t chunksize;
263
264 physbuf = NULL;
265 rv = -1;
266 fd = fd1 = -1;
267
268 if (o.block_size && o.sectors_per_cluster) {
269 warnx("Cannot specify both block size and sectors per cluster");
270 goto done;
271 }
272 if (o.OEM_string && strlen(o.OEM_string) > 8) {
273 warnx("%s: bad OEM string", o.OEM_string);
274 goto done;
275 }
276 if (o.create_size) {
277 if (o.no_create) {
278 warnx("create (-C) is incompatible with -N");
279 goto done;
280 }
281 fd = open(fname, O_RDWR | O_CREAT | O_TRUNC, 0644);
282 if (fd == -1) {
283 warnx("failed to create %s", fname);
284 goto done;
285 }
286 if (ftruncate(fd, o.create_size)) {
287 warnx("failed to initialize %jd bytes", (intmax_t)o.create_size);
288 goto done;
289 }
290 } else if ((fd = open(fname, o.no_create ? O_RDONLY : O_RDWR)) == -1) {
291 warn("%s", fname);
292 goto done;
293 }
294 if (fstat(fd, &sb)) {
295 warn("%s", fname);
296 goto done;
297 }
298 if (o.create_size) {
299 if (!S_ISREG(sb.st_mode))
300 warnx("warning, %s is not a regular file", fname);
301 } else {
302 #ifdef MAKEFS
303 errx(1, "o.create_size must be set!");
304 #else
305 if (!S_ISCHR(sb.st_mode))
306 warnx("warning, %s is not a character device", fname);
307 #endif
308 }
309 if (o.offset && o.offset != lseek(fd, o.offset, SEEK_SET)) {
310 warnx("cannot seek to %jd", (intmax_t)o.offset);
311 goto done;
312 }
313 memset(&bpb, 0, sizeof(bpb));
314 if (o.floppy) {
315 if (getstdfmt(o.floppy, &bpb) == -1)
316 goto done;
317 bpb.bpbHugeSectors = bpb.bpbSectors;
318 bpb.bpbSectors = 0;
319 bpb.bpbBigFATsecs = bpb.bpbFATsecs;
320 bpb.bpbFATsecs = 0;
321 }
322 if (o.drive_heads)
323 bpb.bpbHeads = o.drive_heads;
324 if (o.sectors_per_track)
325 bpb.bpbSecPerTrack = o.sectors_per_track;
326 if (o.bytes_per_sector)
327 bpb.bpbBytesPerSec = o.bytes_per_sector;
328 if (o.size)
329 bpb.bpbHugeSectors = o.size;
330 if (o.hidden_sectors_set)
331 bpb.bpbHiddenSecs = o.hidden_sectors;
332 if (!(o.floppy || (o.drive_heads && o.sectors_per_track &&
333 o.bytes_per_sector && o.size && o.hidden_sectors_set))) {
334 if (getdiskinfo(fd, fname, dtype, o.hidden_sectors_set, &bpb) == -1)
335 goto done;
336 bpb.bpbHugeSectors -= (o.offset / bpb.bpbBytesPerSec);
337 if (bpb.bpbSecPerClust == 0) { /* set defaults */
338 if (bpb.bpbHugeSectors <= 6000) /* about 3MB -> 512 bytes */
339 bpb.bpbSecPerClust = 1;
340 else if (bpb.bpbHugeSectors <= (1<<17)) /* 64M -> 4k */
341 bpb.bpbSecPerClust = 8;
342 else if (bpb.bpbHugeSectors <= (1<<19)) /* 256M -> 8k */
343 bpb.bpbSecPerClust = 16;
344 else if (bpb.bpbHugeSectors <= (1<<21)) /* 1G -> 16k */
345 bpb.bpbSecPerClust = 32;
346 else
347 bpb.bpbSecPerClust = 64; /* otherwise 32k */
348 }
349 }
350 if (bpb.bpbBytesPerSec < MINBPS ||
351 bpb.bpbBytesPerSec > MAXBPS ||
352 !powerof2(bpb.bpbBytesPerSec)) {
353 warnx("Invalid bytes/sector (%u): must be 512, 1024, 2048 or 4096",
354 bpb.bpbBytesPerSec);
355 goto done;
356 }
357
358 if (o.volume_label && !oklabel(o.volume_label)) {
359 warnx("%s: bad volume label", o.volume_label);
360 goto done;
361 }
362 if (!(fat = o.fat_type)) {
363 if (o.floppy)
364 fat = 12;
365 else if (!o.directory_entries && (o.info_sector || o.backup_sector))
366 fat = 32;
367 }
368 if ((fat == 32 && o.directory_entries) || (fat != 32 && (o.info_sector || o.backup_sector))) {
369 warnx("-%c is not a legal FAT%s option",
370 fat == 32 ? 'e' : o.info_sector ? 'i' : 'k',
371 fat == 32 ? "32" : "12/16");
372 goto done;
373 }
374 if (o.floppy && fat == 32)
375 bpb.bpbRootDirEnts = 0;
376 if (fat != 0 && fat != 12 && fat != 16 && fat != 32) {
377 warnx("%d: bad FAT type", fat);
378 goto done;
379 }
380
381 if (o.block_size) {
382 if (!powerof2(o.block_size)) {
383 warnx("block size (%u) is not a power of 2", o.block_size);
384 goto done;
385 }
386 if (o.block_size < bpb.bpbBytesPerSec) {
387 warnx("block size (%u) is too small; minimum is %u",
388 o.block_size, bpb.bpbBytesPerSec);
389 goto done;
390 }
391 if (o.block_size > bpb.bpbBytesPerSec * MAXSPC) {
392 warnx("block size (%u) is too large; maximum is %u",
393 o.block_size, bpb.bpbBytesPerSec * MAXSPC);
394 goto done;
395 }
396 bpb.bpbSecPerClust = o.block_size / bpb.bpbBytesPerSec;
397 }
398 if (o.sectors_per_cluster) {
399 if (!powerof2(o.sectors_per_cluster)) {
400 warnx("sectors/cluster (%u) is not a power of 2",
401 o.sectors_per_cluster);
402 goto done;
403 }
404 bpb.bpbSecPerClust = o.sectors_per_cluster;
405 }
406 if (o.reserved_sectors)
407 bpb.bpbResSectors = o.reserved_sectors;
408 if (o.num_FAT) {
409 if (o.num_FAT > MAXNFT) {
410 warnx("number of FATs (%u) is too large; maximum is %u",
411 o.num_FAT, MAXNFT);
412 goto done;
413 }
414 bpb.bpbFATs = o.num_FAT;
415 }
416 if (o.directory_entries)
417 bpb.bpbRootDirEnts = o.directory_entries;
418 if (o.media_descriptor_set) {
419 if (o.media_descriptor < 0xf0) {
420 warnx("illegal media descriptor (%#x)", o.media_descriptor);
421 goto done;
422 }
423 bpb.bpbMedia = o.media_descriptor;
424 }
425 if (o.sectors_per_fat)
426 bpb.bpbBigFATsecs = o.sectors_per_fat;
427 if (o.info_sector)
428 bpb.bpbFSInfo = o.info_sector;
429 if (o.backup_sector)
430 bpb.bpbBackup = o.backup_sector;
431 bss = 1;
432 bname = NULL;
433 fd1 = -1;
434 if (o.bootstrap) {
435 bname = o.bootstrap;
436 if (!strchr(bname, '/')) {
437 snprintf(buf, sizeof(buf), "/boot/%s", bname);
438 bname = buf;
439 }
440 if ((fd1 = open(bname, O_RDONLY)) == -1 || fstat(fd1, &sb)) {
441 warn("%s", bname);
442 goto done;
443 }
444 if (!S_ISREG(sb.st_mode) || sb.st_size % bpb.bpbBytesPerSec ||
445 sb.st_size < bpb.bpbBytesPerSec ||
446 sb.st_size > bpb.bpbBytesPerSec * MAXU16) {
447 warnx("%s: inappropriate file type or format", bname);
448 goto done;
449 }
450 bss = sb.st_size / bpb.bpbBytesPerSec;
451 }
452 if (!bpb.bpbFATs)
453 bpb.bpbFATs = 2;
454 if (!fat) {
455 if (bpb.bpbHugeSectors < (bpb.bpbResSectors ? bpb.bpbResSectors : bss) +
456 howmany((RESFTE + (bpb.bpbSecPerClust ? MINCLS16 : MAXCLS12 + 1)) *
457 (bpb.bpbSecPerClust ? 16 : 12) / BPN,
458 bpb.bpbBytesPerSec * NPB) *
459 bpb.bpbFATs +
460 howmany(bpb.bpbRootDirEnts ? bpb.bpbRootDirEnts : DEFRDE,
461 bpb.bpbBytesPerSec / sizeof(struct de)) +
462 (bpb.bpbSecPerClust ? MINCLS16 : MAXCLS12 + 1) *
463 (bpb.bpbSecPerClust ? bpb.bpbSecPerClust :
464 howmany(DEFBLK, bpb.bpbBytesPerSec)))
465 fat = 12;
466 else if (bpb.bpbRootDirEnts || bpb.bpbHugeSectors <
467 (bpb.bpbResSectors ? bpb.bpbResSectors : bss) +
468 howmany((RESFTE + MAXCLS16) * 2, bpb.bpbBytesPerSec) *
469 bpb.bpbFATs +
470 howmany(DEFRDE, bpb.bpbBytesPerSec / sizeof(struct de)) +
471 (MAXCLS16 + 1) *
472 (bpb.bpbSecPerClust ? bpb.bpbSecPerClust :
473 howmany(8192, bpb.bpbBytesPerSec)))
474 fat = 16;
475 else
476 fat = 32;
477 }
478 x = bss;
479 if (fat == 32) {
480 if (!bpb.bpbFSInfo) {
481 if (x == MAXU16 || x == bpb.bpbBackup) {
482 warnx("no room for info sector");
483 goto done;
484 }
485 bpb.bpbFSInfo = x;
486 }
487 if (bpb.bpbFSInfo != MAXU16 && x <= bpb.bpbFSInfo)
488 x = bpb.bpbFSInfo + 1;
489 if (!bpb.bpbBackup) {
490 if (x == MAXU16) {
491 warnx("no room for backup sector");
492 goto done;
493 }
494 bpb.bpbBackup = x;
495 } else if (bpb.bpbBackup != MAXU16 && bpb.bpbBackup == bpb.bpbFSInfo) {
496 warnx("backup sector would overwrite info sector");
497 goto done;
498 }
499 if (bpb.bpbBackup != MAXU16 && x <= bpb.bpbBackup)
500 x = bpb.bpbBackup + 1;
501 }
502
503 extra_res = 0;
504 alignment = 0;
505 set_res = (bpb.bpbResSectors == 0);
506 set_spf = (bpb.bpbBigFATsecs == 0);
507 set_spc = (bpb.bpbSecPerClust == 0);
508 saved_x = x;
509
510 /*
511 * Attempt to align the root directory to cluster if o.align is set.
512 * This is done by padding with reserved blocks. Note that this can
513 * cause other factors to change, which can in turn change the alignment.
514 * This should take at most 2 iterations, as increasing the reserved
515 * amount may cause the FAT size to decrease by 1, requiring another
516 * bpbFATs reserved blocks. If bpbSecPerClust changes, it will
517 * be half of its previous size, and thus will not throw off alignment.
518 */
519 do {
520 x = saved_x;
521 if (set_res)
522 bpb.bpbResSectors = ((fat == 32) ?
523 MAX(x, MAX(16384 / bpb.bpbBytesPerSec, 4)) : x) + extra_res;
524 else if (bpb.bpbResSectors < x) {
525 warnx("too few reserved sectors (need %d have %d)", x,
526 bpb.bpbResSectors);
527 goto done;
528 }
529 if (fat != 32 && !bpb.bpbRootDirEnts)
530 bpb.bpbRootDirEnts = DEFRDE;
531 rds = howmany(bpb.bpbRootDirEnts,
532 bpb.bpbBytesPerSec / sizeof(struct de));
533 if (set_spc) {
534 for (bpb.bpbSecPerClust = howmany(fat == 16 ? DEFBLK16 :
535 DEFBLK, bpb.bpbBytesPerSec);
536 bpb.bpbSecPerClust < MAXSPC && (bpb.bpbResSectors +
537 howmany((RESFTE + maxcls(fat)) * (fat / BPN),
538 bpb.bpbBytesPerSec * NPB) * bpb.bpbFATs +
539 rds +
540 (u_int64_t) (maxcls(fat) + 1) * bpb.bpbSecPerClust) <=
541 bpb.bpbHugeSectors;
542 bpb.bpbSecPerClust <<= 1)
543 continue;
544
545 }
546 if (fat != 32 && bpb.bpbBigFATsecs > MAXU16) {
547 warnx("too many sectors/FAT for FAT12/16");
548 goto done;
549 }
550 x1 = bpb.bpbResSectors + rds;
551 x = bpb.bpbBigFATsecs ? bpb.bpbBigFATsecs : 1;
552 if (x1 + (u_int64_t)x * bpb.bpbFATs > bpb.bpbHugeSectors) {
553 warnx("meta data exceeds file system size");
554 goto done;
555 }
556 x1 += x * bpb.bpbFATs;
557 x = (u_int64_t)(bpb.bpbHugeSectors - x1) * bpb.bpbBytesPerSec * NPB /
558 (bpb.bpbSecPerClust * bpb.bpbBytesPerSec * NPB +
559 fat / BPN * bpb.bpbFATs);
560 x2 = howmany((RESFTE + MIN(x, maxcls(fat))) * (fat / BPN),
561 bpb.bpbBytesPerSec * NPB);
562 if (set_spf) {
563 if (bpb.bpbBigFATsecs == 0)
564 bpb.bpbBigFATsecs = x2;
565 x1 += (bpb.bpbBigFATsecs - 1) * bpb.bpbFATs;
566 }
567 if (set_res) {
568 /* attempt to align root directory */
569 alignment = (bpb.bpbResSectors + bpb.bpbBigFATsecs * bpb.bpbFATs) %
570 bpb.bpbSecPerClust;
571 if (o.align)
572 extra_res += bpb.bpbSecPerClust - alignment;
573 }
574 attempts++;
575 } while (o.align && alignment != 0 && attempts < 2);
576 if (o.align && alignment != 0)
577 warnx("warning: Alignment failed.");
578
579 cls = (bpb.bpbHugeSectors - x1) / bpb.bpbSecPerClust;
580 x = (u_int64_t)bpb.bpbBigFATsecs * bpb.bpbBytesPerSec * NPB / (fat / BPN) -
581 RESFTE;
582 if (cls > x)
583 cls = x;
584 if (bpb.bpbBigFATsecs < x2)
585 warnx("warning: sectors/FAT limits file system to %u clusters",
586 cls);
587 if (cls < mincls(fat)) {
588 warnx("%u clusters too few clusters for FAT%u, need %u", cls, fat,
589 mincls(fat));
590 goto done;
591 }
592 if (cls > maxcls(fat)) {
593 cls = maxcls(fat);
594 bpb.bpbHugeSectors = x1 + (cls + 1) * bpb.bpbSecPerClust - 1;
595 warnx("warning: FAT type limits file system to %u sectors",
596 bpb.bpbHugeSectors);
597 }
598 printf("%s: %u sector%s in %u FAT%u cluster%s "
599 "(%u bytes/cluster)\n", fname, cls * bpb.bpbSecPerClust,
600 cls * bpb.bpbSecPerClust == 1 ? "" : "s", cls, fat,
601 cls == 1 ? "" : "s", bpb.bpbBytesPerSec * bpb.bpbSecPerClust);
602 if (!bpb.bpbMedia)
603 bpb.bpbMedia = !bpb.bpbHiddenSecs ? 0xf0 : 0xf8;
604 if (fat == 32)
605 bpb.bpbRootClust = RESFTE;
606 if (bpb.bpbHugeSectors <= MAXU16) {
607 bpb.bpbSectors = bpb.bpbHugeSectors;
608 bpb.bpbHugeSectors = 0;
609 }
610 if (fat != 32) {
611 bpb.bpbFATsecs = bpb.bpbBigFATsecs;
612 bpb.bpbBigFATsecs = 0;
613 }
614 print_bpb(&bpb);
615 if (!o.no_create) {
616 if (o.timestamp_set) {
617 tv.tv_sec = now = o.timestamp;
618 tv.tv_usec = 0;
619 tm = gmtime(&now);
620 } else {
621 gettimeofday(&tv, NULL);
622 now = tv.tv_sec;
623 tm = localtime(&now);
624 }
625
626 chunksize = getchunksize();
627 physbuf = malloc(chunksize);
628 if (physbuf == NULL) {
629 warn(NULL);
630 goto done;
631 }
632 physbuf_end = physbuf + chunksize;
633 img = physbuf;
634
635 dir = bpb.bpbResSectors + (bpb.bpbFATsecs ? bpb.bpbFATsecs :
636 bpb.bpbBigFATsecs) * bpb.bpbFATs;
637 memset(&si_sa, 0, sizeof(si_sa));
638 si_sa.sa_handler = infohandler;
639 #ifdef SIGINFO
640 if (sigaction(SIGINFO, &si_sa, NULL) == -1) {
641 warn("sigaction SIGINFO");
642 goto done;
643 }
644 #endif
645 for (lsn = 0; lsn < dir + (fat == 32 ? bpb.bpbSecPerClust : rds); lsn++) {
646 if (got_siginfo) {
647 fprintf(stderr,"%s: writing sector %u of %u (%u%%)\n",
648 fname, lsn,
649 (dir + (fat == 32 ? bpb.bpbSecPerClust: rds)),
650 (lsn * 100) / (dir +
651 (fat == 32 ? bpb.bpbSecPerClust: rds)));
652 got_siginfo = 0;
653 }
654 x = lsn;
655 if (o.bootstrap &&
656 fat == 32 && bpb.bpbBackup != MAXU16 &&
657 bss <= bpb.bpbBackup && x >= bpb.bpbBackup) {
658 x -= bpb.bpbBackup;
659 if (!x && lseek(fd1, o.offset, SEEK_SET)) {
660 warn("%s", bname);
661 goto done;
662 }
663 }
664 if (o.bootstrap && x < bss) {
665 if ((n = read(fd1, img, bpb.bpbBytesPerSec)) == -1) {
666 warn("%s", bname);
667 goto done;
668 }
669 if ((unsigned)n != bpb.bpbBytesPerSec) {
670 warnx("%s: can't read sector %u", bname, x);
671 goto done;
672 }
673 } else
674 memset(img, 0, bpb.bpbBytesPerSec);
675 if (!lsn ||
676 (fat == 32 && bpb.bpbBackup != MAXU16 &&
677 lsn == bpb.bpbBackup)) {
678 x1 = sizeof(struct bs);
679 bsbpb = (struct bsbpb *)(img + x1);
680 mk2(bsbpb->bpbBytesPerSec, bpb.bpbBytesPerSec);
681 mk1(bsbpb->bpbSecPerClust, bpb.bpbSecPerClust);
682 mk2(bsbpb->bpbResSectors, bpb.bpbResSectors);
683 mk1(bsbpb->bpbFATs, bpb.bpbFATs);
684 mk2(bsbpb->bpbRootDirEnts, bpb.bpbRootDirEnts);
685 mk2(bsbpb->bpbSectors, bpb.bpbSectors);
686 mk1(bsbpb->bpbMedia, bpb.bpbMedia);
687 mk2(bsbpb->bpbFATsecs, bpb.bpbFATsecs);
688 mk2(bsbpb->bpbSecPerTrack, bpb.bpbSecPerTrack);
689 mk2(bsbpb->bpbHeads, bpb.bpbHeads);
690 mk4(bsbpb->bpbHiddenSecs, bpb.bpbHiddenSecs);
691 mk4(bsbpb->bpbHugeSectors, bpb.bpbHugeSectors);
692 x1 += sizeof(struct bsbpb);
693 if (fat == 32) {
694 bsxbpb = (struct bsxbpb *)(img + x1);
695 mk4(bsxbpb->bpbBigFATsecs, bpb.bpbBigFATsecs);
696 mk2(bsxbpb->bpbExtFlags, 0);
697 mk2(bsxbpb->bpbFSVers, 0);
698 mk4(bsxbpb->bpbRootClust, bpb.bpbRootClust);
699 mk2(bsxbpb->bpbFSInfo, bpb.bpbFSInfo);
700 mk2(bsxbpb->bpbBackup, bpb.bpbBackup);
701 x1 += sizeof(struct bsxbpb);
702 }
703 bsx = (struct bsx *)(img + x1);
704 mk1(bsx->exBootSignature, 0x29);
705 if (o.volume_id_set)
706 x = o.volume_id;
707 else
708 x = (((u_int)(1 + tm->tm_mon) << 8 |
709 (u_int)tm->tm_mday) +
710 ((u_int)tm->tm_sec << 8 |
711 (u_int)(tv.tv_usec / 10))) << 16 |
712 ((u_int)(1900 + tm->tm_year) +
713 ((u_int)tm->tm_hour << 8 |
714 (u_int)tm->tm_min));
715 mk4(bsx->exVolumeID, x);
716 mklabel(bsx->exVolumeLabel, o.volume_label ? o.volume_label : "NO NAME");
717 snprintf(buf, sizeof(buf), "FAT%u", fat);
718 setstr(bsx->exFileSysType, buf, sizeof(bsx->exFileSysType));
719 if (!o.bootstrap) {
720 x1 += sizeof(struct bsx);
721 bs = (struct bs *)img;
722 mk1(bs->bsJump[0], 0xeb);
723 mk1(bs->bsJump[1], x1 - 2);
724 mk1(bs->bsJump[2], 0x90);
725 setstr(bs->bsOemName, o.OEM_string ? o.OEM_string : "BSD4.4 ",
726 sizeof(bs->bsOemName));
727 memcpy(img + x1, bootcode, sizeof(bootcode));
728 mk2(img + MINBPS - 2, DOSMAGIC);
729 }
730 } else if (fat == 32 && bpb.bpbFSInfo != MAXU16 &&
731 (lsn == bpb.bpbFSInfo ||
732 (bpb.bpbBackup != MAXU16 &&
733 lsn == bpb.bpbBackup + bpb.bpbFSInfo))) {
734 mk4(img, 0x41615252);
735 mk4(img + MINBPS - 28, 0x61417272);
736 mk4(img + MINBPS - 24, 0xffffffff);
737 mk4(img + MINBPS - 20, 0xffffffff);
738 mk2(img + MINBPS - 2, DOSMAGIC);
739 } else if (lsn >= bpb.bpbResSectors && lsn < dir &&
740 !((lsn - bpb.bpbResSectors) %
741 (bpb.bpbFATsecs ? bpb.bpbFATsecs :
742 bpb.bpbBigFATsecs))) {
743 mk1(img[0], bpb.bpbMedia);
744 for (x = 1; x < fat * (fat == 32 ? 3 : 2) / 8; x++)
745 mk1(img[x], fat == 32 && x % 4 == 3 ? 0x0f : 0xff);
746 } else if (lsn == dir && o.volume_label) {
747 de = (struct de *)img;
748 mklabel(de->deName, o.volume_label);
749 mk1(de->deAttributes, 050);
750 x = (u_int)tm->tm_hour << 11 |
751 (u_int)tm->tm_min << 5 |
752 (u_int)tm->tm_sec >> 1;
753 mk2(de->deMTime, x);
754 x = (u_int)(tm->tm_year - 80) << 9 |
755 (u_int)(tm->tm_mon + 1) << 5 |
756 (u_int)tm->tm_mday;
757 mk2(de->deMDate, x);
758 }
759 /*
760 * Issue a write of chunksize once we have collected
761 * enough sectors.
762 */
763 img += bpb.bpbBytesPerSec;
764 if (img >= physbuf_end) {
765 n = write(fd, physbuf, chunksize);
766 if (n != chunksize) {
767 warnx("%s: can't write sector %u", fname, lsn);
768 goto done;
769 }
770 img = physbuf;
771 }
772 }
773 /*
774 * Write remaining sectors, if the last write didn't end
775 * up filling a whole chunk.
776 */
777 if (img != physbuf) {
778 ssize_t tailsize = img - physbuf;
779
780 n = write(fd, physbuf, tailsize);
781 if (n != tailsize) {
782 warnx("%s: can't write sector %u", fname, lsn);
783 goto done;
784 }
785 }
786 }
787 rv = 0;
788 done:
789 free(physbuf);
790 if (fd != -1)
791 close(fd);
792 if (fd1 != -1)
793 close(fd1);
794
795 return rv;
796 }
797
798 /*
799 * Get optimal I/O size
800 */
801 static ssize_t
getchunksize(void)802 getchunksize(void)
803 {
804 static int chunksize;
805
806 if (chunksize != 0)
807 return ((ssize_t)chunksize);
808
809 #ifdef KERN_MAXPHYS
810 int mib[2];
811 size_t len;
812
813 mib[0] = CTL_KERN;
814 mib[1] = KERN_MAXPHYS;
815 len = sizeof(chunksize);
816
817 if (sysctl(mib, 2, &chunksize, &len, NULL, 0) == -1) {
818 warn("sysctl: KERN_MAXPHYS, using %zu", (size_t)MAXPHYS);
819 chunksize = 0;
820 }
821 #endif
822 if (chunksize == 0)
823 chunksize = MAXPHYS;
824
825 /*
826 * For better performance, we want to write larger chunks instead of
827 * individual sectors (the size can only be 512, 1024, 2048 or 4096
828 * bytes). Assert that chunksize can always hold an integer number of
829 * sectors by asserting that both are power of two numbers and the
830 * chunksize is greater than MAXBPS.
831 */
832 static_assert(powerof2(MAXBPS), "MAXBPS is not power of 2");
833 assert(powerof2(chunksize));
834 assert(chunksize > MAXBPS);
835
836 return ((ssize_t)chunksize);
837 }
838
839 /*
840 * Get a standard format.
841 */
842 static int
getstdfmt(const char * fmt,struct bpb * bpb)843 getstdfmt(const char *fmt, struct bpb *bpb)
844 {
845 u_int x, i;
846
847 x = nitems(stdfmt);
848 for (i = 0; i < x && strcmp(fmt, stdfmt[i].name); i++);
849 if (i == x) {
850 warnx("%s: unknown standard format", fmt);
851 return -1;
852 }
853 *bpb = stdfmt[i].bpb;
854 return 0;
855 }
856
857 /*
858 * Get disk slice, partition, and geometry information.
859 */
860 #if defined(__linux__)
861 static int
getdiskinfo(int fd,const char * fname,const char * dtype,int oflag,struct bpb * bpb)862 getdiskinfo(int fd, const char *fname, const char *dtype, int oflag,
863 struct bpb *bpb)
864 {
865 if (ioctl(fd, BLKSSZGET, &bpb->bpbBytesPerSec) == -1) {
866 err(1, "ioctl(BLKSSZGET) for bytes/sector failed");
867 }
868
869 if (ckgeom(fname, bpb->bpbBytesPerSec, "bytes/sector") == -1) return -1;
870
871 u_int64_t device_size;
872 if (ioctl(fd, BLKGETSIZE64, &device_size) == -1) {
873 err(1, "ioctl(BLKGETSIZE64) failed");
874 }
875
876 u_int64_t sectors = device_size/bpb->bpbBytesPerSec;
877 if (sectors > UINT_MAX) {
878 err(1, "too many sectors: %"PRIu64" (%"PRId64" byte device, %u bytes/sector)",
879 sectors, device_size, bpb->bpbBytesPerSec);
880 }
881 bpb->bpbHugeSectors = sectors;
882
883 bpb->bpbSecPerTrack = 63;
884 if (ckgeom(fname, bpb->bpbSecPerTrack, "sectors/track") == -1) return -1;
885
886 bpb->bpbHeads = 64;
887 if (ckgeom(fname, bpb->bpbHeads, "drive heads") == -1) return -1;
888 return 0;
889 }
890 #else
891 static int
getdiskinfo(int fd,const char * fname,const char * dtype,int oflag,struct bpb * bpb)892 getdiskinfo(int fd, const char *fname, const char *dtype, /* __unused */ int oflag,
893 struct bpb *bpb)
894 {
895 struct disklabel *lp, dlp;
896 off_t hs = 0;
897 #ifndef MAKEFS
898 off_t ms;
899 struct fd_type type;
900
901 lp = NULL;
902
903 /* If the user specified a disk type, try to use that */
904 if (dtype != NULL) {
905 lp = getdiskbyname(dtype);
906 }
907
908 /* Maybe it's a floppy drive */
909 if (lp == NULL) {
910 if (ioctl(fd, DIOCGMEDIASIZE, &ms) == -1) {
911 /* create a fake geometry for a file image */
912 compute_geometry_from_file(fd, fname, &dlp);
913 lp = &dlp;
914 } else if (ioctl(fd, FD_GTYPE, &type) != -1) {
915 dlp.d_secsize = 128 << type.secsize;
916 dlp.d_nsectors = type.sectrac;
917 dlp.d_ntracks = type.heads;
918 dlp.d_secperunit = ms / dlp.d_secsize;
919 lp = &dlp;
920 }
921 }
922
923 /* Maybe it's a fixed drive */
924 if (lp == NULL) {
925 if (bpb->bpbBytesPerSec)
926 dlp.d_secsize = bpb->bpbBytesPerSec;
927 if (bpb->bpbBytesPerSec == 0 && ioctl(fd, DIOCGSECTORSIZE,
928 &dlp.d_secsize) == -1)
929 err(1, "cannot get sector size");
930
931 dlp.d_secperunit = ms / dlp.d_secsize;
932
933 if (bpb->bpbSecPerTrack == 0 && ioctl(fd, DIOCGFWSECTORS,
934 &dlp.d_nsectors) == -1) {
935 warn("cannot get number of sectors per track");
936 dlp.d_nsectors = 63;
937 }
938 if (bpb->bpbHeads == 0 &&
939 ioctl(fd, DIOCGFWHEADS, &dlp.d_ntracks) == -1) {
940 warn("cannot get number of heads");
941 if (dlp.d_secperunit <= 63*1*1024)
942 dlp.d_ntracks = 1;
943 else if (dlp.d_secperunit <= 63*16*1024)
944 dlp.d_ntracks = 16;
945 else
946 dlp.d_ntracks = 255;
947 }
948
949 hs = (ms / dlp.d_secsize) - dlp.d_secperunit;
950 lp = &dlp;
951 }
952 #else
953 /* In the makefs case we only support image files: */
954 compute_geometry_from_file(fd, fname, &dlp);
955 lp = &dlp;
956 #endif
957
958 if (bpb->bpbBytesPerSec == 0) {
959 if (ckgeom(fname, lp->d_secsize, "bytes/sector") == -1)
960 return -1;
961 bpb->bpbBytesPerSec = lp->d_secsize;
962 }
963 if (bpb->bpbSecPerTrack == 0) {
964 if (ckgeom(fname, lp->d_nsectors, "sectors/track") == -1)
965 return -1;
966 bpb->bpbSecPerTrack = lp->d_nsectors;
967 }
968 if (bpb->bpbHeads == 0) {
969 if (ckgeom(fname, lp->d_ntracks, "drive heads") == -1)
970 return -1;
971 bpb->bpbHeads = lp->d_ntracks;
972 }
973 if (bpb->bpbHugeSectors == 0)
974 bpb->bpbHugeSectors = lp->d_secperunit;
975 if (bpb->bpbHiddenSecs == 0)
976 bpb->bpbHiddenSecs = hs;
977 return 0;
978 }
979 #endif
980 /*
981 * Print out BPB values.
982 */
983 static void
print_bpb(struct bpb * bpb)984 print_bpb(struct bpb *bpb)
985 {
986 printf("BytesPerSec=%u SecPerClust=%u ResSectors=%u FATs=%u",
987 bpb->bpbBytesPerSec, bpb->bpbSecPerClust, bpb->bpbResSectors,
988 bpb->bpbFATs);
989 if (bpb->bpbRootDirEnts)
990 printf(" RootDirEnts=%u", bpb->bpbRootDirEnts);
991 if (bpb->bpbSectors)
992 printf(" Sectors=%u", bpb->bpbSectors);
993 printf(" Media=%#x", bpb->bpbMedia);
994 if (bpb->bpbFATsecs)
995 printf(" FATsecs=%u", bpb->bpbFATsecs);
996 printf(" SecPerTrack=%u Heads=%u HiddenSecs=%u", bpb->bpbSecPerTrack,
997 bpb->bpbHeads, bpb->bpbHiddenSecs);
998 if (bpb->bpbHugeSectors)
999 printf(" HugeSectors=%u", bpb->bpbHugeSectors);
1000 if (!bpb->bpbFATsecs) {
1001 printf(" FATsecs=%u RootCluster=%u", bpb->bpbBigFATsecs,
1002 bpb->bpbRootClust);
1003 printf(" FSInfo=");
1004 printf(bpb->bpbFSInfo == MAXU16 ? "%#x" : "%u", bpb->bpbFSInfo);
1005 printf(" Backup=");
1006 printf(bpb->bpbBackup == MAXU16 ? "%#x" : "%u", bpb->bpbBackup);
1007 }
1008 printf("\n");
1009 }
1010
1011 /*
1012 * Check a disk geometry value.
1013 */
1014 static int
ckgeom(const char * fname,u_int val,const char * msg)1015 ckgeom(const char *fname, u_int val, const char *msg)
1016 {
1017 if (!val) {
1018 warnx("%s: no default %s", fname, msg);
1019 return -1;
1020 }
1021 if (val > MAXU16) {
1022 warnx("%s: illegal %s %d", fname, msg, val);
1023 return -1;
1024 }
1025 return 0;
1026 }
1027
1028 /*
1029 * Check a volume label.
1030 */
1031 static int
oklabel(const char * src)1032 oklabel(const char *src)
1033 {
1034 int c, i;
1035
1036 for (i = 0; i <= 11; i++) {
1037 c = (u_char)*src++;
1038 if (c < ' ' + !i || strchr("\"*+,./:;<=>?[\\]|", c))
1039 break;
1040 }
1041 return i && !c;
1042 }
1043
1044 /*
1045 * Make a volume label.
1046 */
1047 static void
mklabel(u_int8_t * dest,const char * src)1048 mklabel(u_int8_t *dest, const char *src)
1049 {
1050 int c, i;
1051
1052 for (i = 0; i < 11; i++) {
1053 c = *src ? toupper(*src++) : ' ';
1054 *dest++ = !i && c == '\xe5' ? 5 : c;
1055 }
1056 }
1057
1058 /*
1059 * Copy string, padding with spaces.
1060 */
1061 static void
setstr(u_int8_t * dest,const char * src,size_t len)1062 setstr(u_int8_t *dest, const char *src, size_t len)
1063 {
1064 while (len--)
1065 *dest++ = *src ? *src++ : ' ';
1066 }
1067
1068 static void
infohandler(int sig)1069 infohandler(int sig /* __unused */)
1070 {
1071
1072 got_siginfo = 1;
1073 }
1074