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