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