xref: /dragonfly/sbin/newfs_msdos/mkfs_msdos.c (revision 8f2ce533)
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/sysctl.h>
35 #include <sys/time.h>
36 
37 #include <machine/ioctl_fd.h>
38 
39 #include <assert.h>
40 #include <ctype.h>
41 #include <disktab.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	MINBPS	  512		/* minimum bytes per sector */
61 #define	MAXBPS    4096		/* maximum 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) = (uint8_t)(x)
85 
86 #define	mk2(p, x)				\
87     (p)[0] = (uint8_t)(x),			\
88     (p)[1] = (uint8_t)((x) >> 010)
89 
90 #define	mk4(p, x)				\
91     (p)[0] = (uint8_t)(x),			\
92     (p)[1] = (uint8_t)((x) >> 010),		\
93     (p)[2] = (uint8_t)((x) >> 020),		\
94     (p)[3] = (uint8_t)((x) >> 030)
95 
96 struct bs {
97     uint8_t bsJump[3];			/* bootstrap entry point */
98     uint8_t bsOemName[8];		/* OEM name and version */
99 } __packed;
100 
101 struct bsbpb {
102     uint8_t bpbBytesPerSec[2];		/* bytes per sector */
103     uint8_t bpbSecPerClust;		/* sectors per cluster */
104     uint8_t bpbResSectors[2];		/* reserved sectors */
105     uint8_t bpbFATs;			/* number of FATs */
106     uint8_t bpbRootDirEnts[2];		/* root directory entries */
107     uint8_t bpbSectors[2];		/* total sectors */
108     uint8_t bpbMedia;			/* media descriptor */
109     uint8_t bpbFATsecs[2];		/* sectors per FAT */
110     uint8_t bpbSecPerTrack[2];		/* sectors per track */
111     uint8_t bpbHeads[2];		/* drive heads */
112     uint8_t bpbHiddenSecs[4];		/* hidden sectors */
113     uint8_t bpbHugeSectors[4];		/* big total sectors */
114 } __packed;
115 
116 struct bsxbpb {
117     uint8_t bpbBigFATsecs[4];		/* big sectors per FAT */
118     uint8_t bpbExtFlags[2];		/* FAT control flags */
119     uint8_t bpbFSVers[2];		/* file system version */
120     uint8_t bpbRootClust[4];		/* root directory start cluster */
121     uint8_t bpbFSInfo[2];		/* file system info sector */
122     uint8_t bpbBackup[2];		/* backup boot sector */
123     uint8_t bpbReserved[12];		/* reserved */
124 } __packed;
125 
126 struct bsx {
127     uint8_t exDriveNumber;		/* drive number */
128     uint8_t exReserved1;		/* reserved */
129     uint8_t exBootSignature;		/* extended boot signature */
130     uint8_t exVolumeID[4];		/* volume ID number */
131     uint8_t exVolumeLabel[11];		/* volume label */
132     uint8_t exFileSysType[8];		/* file system type */
133 } __packed;
134 
135 struct de {
136     uint8_t deName[11];			/* name and extension */
137     uint8_t deAttributes;		/* attributes */
138     uint8_t rsvd[10];			/* reserved */
139     uint8_t deMTime[2];			/* last-modified time */
140     uint8_t deMDate[2];			/* last-modified date */
141     uint8_t deStartCluster[2];		/* starting cluster */
142     uint8_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 uint8_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 #ifndef MAKEFS
218 static int check_mounted(const char *, mode_t);
219 #endif
220 static ssize_t getchunksize(void);
221 static int getstdfmt(const char *, struct bpb *);
222 static int getdiskinfo(int, const char *, const char *, int, struct bpb *);
223 static void print_bpb(struct bpb *);
224 static int ckgeom(const char *, u_int, const char *);
225 static void mklabel(uint8_t *, const char *);
226 static int oklabel(const char *);
227 static void setstr(uint8_t *, const char *, size_t);
228 
229 int
230 mkfs_msdos(const char *fname, const char *dtype, const struct msdos_options *op)
231 {
232     char buf[MAXPATHLEN];
233     struct sigaction si_sa;
234     struct stat sb;
235     struct timeval tv;
236     struct bpb bpb;
237     struct tm *tm;
238     struct bs *bs;
239     struct bsbpb *bsbpb;
240     struct bsxbpb *bsxbpb;
241     struct bsx *bsx;
242     struct de *de;
243     uint8_t *img;
244     uint8_t *physbuf, *physbuf_end;
245     const char *bname;
246     ssize_t n;
247     time_t now;
248     u_int fat, bss, rds, cls, dir, lsn, x, x1, x2;
249     u_int extra_res, alignment, saved_x, attempts=0;
250     bool set_res, set_spf, set_spc;
251     int fd, fd1, rv;
252     struct msdos_options o = *op;
253     ssize_t chunksize;
254 
255     physbuf = NULL;
256     rv = -1;
257     fd = fd1 = -1;
258 
259     if (o.block_size && o.sectors_per_cluster) {
260 	warnx("Cannot specify both block size and sectors per cluster");
261 	goto done;
262     }
263     if (o.OEM_string && strlen(o.OEM_string) > 8) {
264 	warnx("%s: bad OEM string", o.OEM_string);
265 	goto done;
266     }
267     if (o.create_size) {
268 	if (o.no_create) {
269 	    warnx("create (-C) is incompatible with -N");
270 	    goto done;
271 	}
272 	fd = open(fname, O_RDWR | O_CREAT | O_TRUNC, 0644);
273 	if (fd == -1) {
274 	    warnx("failed to create %s", fname);
275 	    goto done;
276 	}
277 	if (ftruncate(fd, o.create_size)) {
278 	    warnx("failed to initialize %jd bytes", (intmax_t)o.create_size);
279 	    goto done;
280 	}
281     } else if ((fd = open(fname, o.no_create ? O_RDONLY : O_RDWR)) == -1) {
282 	warn("%s", fname);
283 	goto done;
284     }
285     if (fstat(fd, &sb)) {
286 	warn("%s", fname);
287 	goto done;
288     }
289     if (o.create_size) {
290 	if (!S_ISREG(sb.st_mode))
291 	    warnx("warning, %s is not a regular file", fname);
292     } else {
293 #ifdef MAKEFS
294 	errx(1, "o.create_size must be set!");
295 #else
296 	if (!S_ISCHR(sb.st_mode))
297 	    warnx("warning, %s is not a character device", fname);
298 #endif
299     }
300 #ifndef MAKEFS
301     if (!o.no_create)
302 	if (check_mounted(fname, sb.st_mode) == -1)
303 	    goto done;
304 #endif
305     if (o.offset && o.offset != lseek(fd, o.offset, SEEK_SET)) {
306 	warnx("cannot seek to %jd", (intmax_t)o.offset);
307 	goto done;
308     }
309     memset(&bpb, 0, sizeof(bpb));
310     if (o.floppy) {
311 	if (getstdfmt(o.floppy, &bpb) == -1)
312 	    goto done;
313 	bpb.bpbHugeSectors = bpb.bpbSectors;
314 	bpb.bpbSectors = 0;
315 	bpb.bpbBigFATsecs = bpb.bpbFATsecs;
316 	bpb.bpbFATsecs = 0;
317     }
318     if (o.drive_heads)
319 	bpb.bpbHeads = o.drive_heads;
320     if (o.sectors_per_track)
321 	bpb.bpbSecPerTrack = o.sectors_per_track;
322     if (o.bytes_per_sector)
323 	bpb.bpbBytesPerSec = o.bytes_per_sector;
324     if (o.size)
325 	bpb.bpbHugeSectors = o.size;
326     if (o.hidden_sectors_set)
327 	bpb.bpbHiddenSecs = o.hidden_sectors;
328     if (!(o.floppy || (o.drive_heads && o.sectors_per_track &&
329 	o.bytes_per_sector && o.size && o.hidden_sectors_set))) {
330 	if (getdiskinfo(fd, fname, dtype, o.hidden_sectors_set, &bpb) == -1)
331 		goto done;
332 	bpb.bpbHugeSectors -= (o.offset / bpb.bpbBytesPerSec);
333 	if (bpb.bpbSecPerClust == 0) {	/* set defaults */
334 	    if (bpb.bpbHugeSectors <= 6000)	/* about 3MB -> 512 bytes */
335 		bpb.bpbSecPerClust = 1;
336 	    else if (bpb.bpbHugeSectors <= (1<<17)) /* 64M -> 4k */
337 		bpb.bpbSecPerClust = 8;
338 	    else if (bpb.bpbHugeSectors <= (1<<19)) /* 256M -> 8k */
339 		bpb.bpbSecPerClust = 16;
340 	    else if (bpb.bpbHugeSectors <= (1<<21)) /* 1G -> 16k */
341 		bpb.bpbSecPerClust = 32;
342 	    else
343 		bpb.bpbSecPerClust = 64;		/* otherwise 32k */
344 	}
345     }
346     if (bpb.bpbBytesPerSec < MINBPS ||
347         bpb.bpbBytesPerSec > MAXBPS ||
348 	!powerof2(bpb.bpbBytesPerSec)) {
349 	warnx("Invalid bytes/sector (%u): must be 512, 1024, 2048 or 4096",
350 	    bpb.bpbBytesPerSec);
351 	goto done;
352     }
353 
354     if (o.volume_label && !oklabel(o.volume_label)) {
355 	warnx("%s: bad volume label", o.volume_label);
356 	goto done;
357     }
358     if (!(fat = o.fat_type)) {
359 	if (o.floppy)
360 	    fat = 12;
361 	else if (!o.directory_entries && (o.info_sector || o.backup_sector))
362 	    fat = 32;
363     }
364     if ((fat == 32 && o.directory_entries) ||
365         (fat != 32 && (o.info_sector || o.backup_sector))) {
366 	warnx("-%c is not a legal FAT%s option",
367 	     fat == 32 ? 'e' : o.info_sector ? 'i' : 'k',
368 	     fat == 32 ? "32" : "12/16");
369 	goto done;
370     }
371     if (o.floppy && fat == 32)
372 	bpb.bpbRootDirEnts = 0;
373     if (fat != 0 && fat != 12 && fat != 16 && fat != 32) {
374 	warnx("%d: bad FAT type", fat);
375 	goto done;
376     }
377 
378     if (o.block_size) {
379 	if (!powerof2(o.block_size)) {
380 	    warnx("block size (%u) is not a power of 2", o.block_size);
381 	    goto done;
382 	}
383 	if (o.block_size < bpb.bpbBytesPerSec) {
384 	    warnx("block size (%u) is too small; minimum is %u",
385 		 o.block_size, bpb.bpbBytesPerSec);
386 	    goto done;
387 	}
388 	if (o.block_size > bpb.bpbBytesPerSec * MAXSPC) {
389 	    warnx("block size (%u) is too large; maximum is %u",
390 		 o.block_size, bpb.bpbBytesPerSec * MAXSPC);
391 	    goto done;
392 	}
393 	bpb.bpbSecPerClust = o.block_size / bpb.bpbBytesPerSec;
394     }
395     if (o.sectors_per_cluster) {
396 	if (!powerof2(o.sectors_per_cluster)) {
397 	    warnx("sectors/cluster (%u) is not a power of 2",
398 		o.sectors_per_cluster);
399 	    goto done;
400 	}
401 	bpb.bpbSecPerClust = o.sectors_per_cluster;
402     }
403     if (o.reserved_sectors)
404 	bpb.bpbResSectors = o.reserved_sectors;
405     if (o.num_FAT) {
406 	if (o.num_FAT > MAXNFT) {
407 	    warnx("number of FATs (%u) is too large; maximum is %u",
408 		 o.num_FAT, MAXNFT);
409 	    goto done;
410 	}
411 	bpb.bpbFATs = o.num_FAT;
412     }
413     if (o.directory_entries)
414 	bpb.bpbRootDirEnts = o.directory_entries;
415     if (o.media_descriptor_set) {
416 	if (o.media_descriptor < 0xf0) {
417 	    warnx("illegal media descriptor (%#x)", o.media_descriptor);
418 	    goto done;
419 	}
420 	bpb.bpbMedia = o.media_descriptor;
421     }
422     if (o.sectors_per_fat)
423 	bpb.bpbBigFATsecs = o.sectors_per_fat;
424     if (o.info_sector)
425 	bpb.bpbFSInfo = o.info_sector;
426     if (o.backup_sector)
427 	bpb.bpbBackup = o.backup_sector;
428     bss = 1;
429     bname = NULL;
430     fd1 = -1;
431     if (o.bootstrap) {
432 	bname = o.bootstrap;
433 	if (!strchr(bname, '/')) {
434 	    snprintf(buf, sizeof(buf), "/boot/%s", bname);
435 	    bname = buf;
436 	}
437 	if ((fd1 = open(bname, O_RDONLY)) == -1 || fstat(fd1, &sb)) {
438 	    warn("%s", bname);
439 	    goto done;
440 	}
441 	if (!S_ISREG(sb.st_mode) || sb.st_size % bpb.bpbBytesPerSec ||
442 	    sb.st_size < bpb.bpbBytesPerSec ||
443 	    sb.st_size > bpb.bpbBytesPerSec * MAXU16) {
444 	    warnx("%s: inappropriate file type or format", bname);
445 	    goto done;
446 	}
447 	bss = sb.st_size / bpb.bpbBytesPerSec;
448     }
449     if (!bpb.bpbFATs)
450 	bpb.bpbFATs = 2;
451     if (!fat) {
452 	if (bpb.bpbHugeSectors < (bpb.bpbResSectors ? bpb.bpbResSectors : bss) +
453 	    howmany((RESFTE + (bpb.bpbSecPerClust ? MINCLS16 : MAXCLS12 + 1)) *
454 		(bpb.bpbSecPerClust ? 16 : 12) / BPN,
455 		bpb.bpbBytesPerSec * NPB) *
456 	    bpb.bpbFATs +
457 	    howmany(bpb.bpbRootDirEnts ? bpb.bpbRootDirEnts : DEFRDE,
458 		    bpb.bpbBytesPerSec / sizeof(struct de)) +
459 	    (bpb.bpbSecPerClust ? MINCLS16 : MAXCLS12 + 1) *
460 	    (bpb.bpbSecPerClust ? bpb.bpbSecPerClust :
461 	     howmany(DEFBLK, bpb.bpbBytesPerSec)))
462 	    fat = 12;
463 	else if (bpb.bpbRootDirEnts || bpb.bpbHugeSectors <
464 		 (bpb.bpbResSectors ? bpb.bpbResSectors : bss) +
465 		 howmany((RESFTE + MAXCLS16) * 2, bpb.bpbBytesPerSec) *
466 		 bpb.bpbFATs +
467 		 howmany(DEFRDE, bpb.bpbBytesPerSec / sizeof(struct de)) +
468 		 (MAXCLS16 + 1) *
469 		 (bpb.bpbSecPerClust ? bpb.bpbSecPerClust :
470 		  howmany(8192, bpb.bpbBytesPerSec)))
471 	    fat = 16;
472 	else
473 	    fat = 32;
474     }
475     x = bss;
476     if (fat == 32) {
477 	if (!bpb.bpbFSInfo) {
478 	    if (x == MAXU16 || x == bpb.bpbBackup) {
479 		warnx("no room for info sector");
480 		goto done;
481 	    }
482 	    bpb.bpbFSInfo = x;
483 	}
484 	if (bpb.bpbFSInfo != MAXU16 && x <= bpb.bpbFSInfo)
485 	    x = bpb.bpbFSInfo + 1;
486 	if (!bpb.bpbBackup) {
487 	    if (x == MAXU16) {
488 		warnx("no room for backup sector");
489 		goto done;
490 	    }
491 	    bpb.bpbBackup = x;
492 	} else if (bpb.bpbBackup != MAXU16 && bpb.bpbBackup == bpb.bpbFSInfo) {
493 	    warnx("backup sector would overwrite info sector");
494 	    goto done;
495 	}
496 	if (bpb.bpbBackup != MAXU16 && x <= bpb.bpbBackup)
497 	    x = bpb.bpbBackup + 1;
498     }
499 
500     extra_res = 0;
501     alignment = 0;
502     set_res = (bpb.bpbResSectors == 0);
503     set_spf = (bpb.bpbBigFATsecs == 0);
504     set_spc = (bpb.bpbSecPerClust == 0);
505     saved_x = x;
506 
507     /*
508      * Attempt to align the root directory to cluster if o.align is set.
509      * This is done by padding with reserved blocks. Note that this can
510      * cause other factors to change, which can in turn change the alignment.
511      * This should take at most 2 iterations, as increasing the reserved
512      * amount may cause the FAT size to decrease by 1, requiring another
513      * bpbFATs reserved blocks. If bpbSecPerClust changes, it will
514      * be half of its previous size, and thus will not throw off alignment.
515      */
516     do {
517 	x = saved_x;
518 	if (set_res)
519 	    bpb.bpbResSectors = ((fat == 32) ?
520 		MAX(x, MAX(16384 / bpb.bpbBytesPerSec, 4)) : x) + extra_res;
521 	else if (bpb.bpbResSectors < x) {
522 	    warnx("too few reserved sectors (need %d have %d)", x,
523 		bpb.bpbResSectors);
524 	    goto done;
525 	}
526 	if (fat != 32 && !bpb.bpbRootDirEnts)
527 	    bpb.bpbRootDirEnts = DEFRDE;
528 	rds = howmany(bpb.bpbRootDirEnts,
529 	    bpb.bpbBytesPerSec / sizeof(struct de));
530 	if (set_spc) {
531 	    for (bpb.bpbSecPerClust = howmany(fat == 16 ? DEFBLK16 :
532 		    DEFBLK, bpb.bpbBytesPerSec);
533 		bpb.bpbSecPerClust < MAXSPC && (bpb.bpbResSectors +
534 		    howmany((RESFTE + maxcls(fat)) * (fat / BPN),
535 			bpb.bpbBytesPerSec * NPB) * bpb.bpbFATs +
536 		    rds +
537 		    (u_int64_t) (maxcls(fat) + 1) * bpb.bpbSecPerClust) <=
538 		    bpb.bpbHugeSectors;
539 		bpb.bpbSecPerClust <<= 1)
540 		    continue;
541 
542 	}
543 	if (fat != 32 && bpb.bpbBigFATsecs > MAXU16) {
544 	    warnx("too many sectors/FAT for FAT12/16");
545 	    goto done;
546 	}
547 	x1 = bpb.bpbResSectors + rds;
548 	x = bpb.bpbBigFATsecs ? bpb.bpbBigFATsecs : 1;
549 	if (x1 + (u_int64_t)x * bpb.bpbFATs > bpb.bpbHugeSectors) {
550 	    warnx("meta data exceeds file system size");
551 	    goto done;
552 	}
553 	x1 += x * bpb.bpbFATs;
554 	x = (u_int64_t)(bpb.bpbHugeSectors - x1) * bpb.bpbBytesPerSec * NPB /
555 	    (bpb.bpbSecPerClust * bpb.bpbBytesPerSec * NPB +
556 	    fat / BPN * bpb.bpbFATs);
557 	x2 = howmany((RESFTE + MIN(x, maxcls(fat))) * (fat / BPN),
558 	    bpb.bpbBytesPerSec * NPB);
559 	if (set_spf) {
560 	    if (bpb.bpbBigFATsecs == 0)
561 		bpb.bpbBigFATsecs = x2;
562 	    x1 += (bpb.bpbBigFATsecs - 1) * bpb.bpbFATs;
563 	}
564 	if (set_res) {
565 	    /* attempt to align root directory */
566 	    alignment = (bpb.bpbResSectors + bpb.bpbBigFATsecs * bpb.bpbFATs) %
567 		bpb.bpbSecPerClust;
568 	    if (o.align)
569 		extra_res += bpb.bpbSecPerClust - alignment;
570 	}
571 	attempts++;
572     } while (o.align && alignment != 0 && attempts < 2);
573     if (o.align && alignment != 0)
574 	warnx("warning: Alignment failed.");
575 
576     cls = (bpb.bpbHugeSectors - x1) / bpb.bpbSecPerClust;
577     x = (uint64_t)bpb.bpbBigFATsecs * bpb.bpbBytesPerSec * NPB / (fat / BPN) -
578 	RESFTE;
579     if (cls > x)
580 	cls = x;
581     if (bpb.bpbBigFATsecs < x2)
582 	warnx("warning: sectors/FAT limits file system to %u clusters",
583 	      cls);
584     if (cls < mincls(fat)) {
585 	warnx("%u clusters too few clusters for FAT%u, need %u", cls, fat,
586 	    mincls(fat));
587 	goto done;
588     }
589     if (cls > maxcls(fat)) {
590 	cls = maxcls(fat);
591 	bpb.bpbHugeSectors = x1 + (cls + 1) * bpb.bpbSecPerClust - 1;
592 	warnx("warning: FAT type limits file system to %u sectors",
593 	      bpb.bpbHugeSectors);
594     }
595     printf("%s: %u sector%s in %u FAT%u cluster%s "
596 	   "(%u bytes/cluster)\n", fname, cls * bpb.bpbSecPerClust,
597 	   cls * bpb.bpbSecPerClust == 1 ? "" : "s", cls, fat,
598 	   cls == 1 ? "" : "s", bpb.bpbBytesPerSec * bpb.bpbSecPerClust);
599     if (!bpb.bpbMedia)
600 	bpb.bpbMedia = !bpb.bpbHiddenSecs ? 0xf0 : 0xf8;
601     if (fat == 32)
602 	bpb.bpbRootClust = RESFTE;
603     if (bpb.bpbHugeSectors <= MAXU16) {
604 	bpb.bpbSectors = bpb.bpbHugeSectors;
605 	bpb.bpbHugeSectors = 0;
606     }
607     if (fat != 32) {
608 	bpb.bpbFATsecs = bpb.bpbBigFATsecs;
609 	bpb.bpbBigFATsecs = 0;
610     }
611     print_bpb(&bpb);
612     if (!o.no_create) {
613 	if (o.timestamp_set) {
614 	    tv.tv_sec = now = o.timestamp;
615 	    tv.tv_usec = 0;
616 	    tm = gmtime(&now);
617 	} else {
618 	    gettimeofday(&tv, NULL);
619 	    now = tv.tv_sec;
620 	    tm = localtime(&now);
621 	}
622 
623 	chunksize = getchunksize();
624 	physbuf = malloc(chunksize);
625 	if (physbuf == NULL) {
626 	    warn(NULL);
627 	    goto done;
628 	}
629 	physbuf_end = physbuf + chunksize;
630 	img = physbuf;
631 
632 	dir = bpb.bpbResSectors + (bpb.bpbFATsecs ? bpb.bpbFATsecs :
633 				   bpb.bpbBigFATsecs) * bpb.bpbFATs;
634 	memset(&si_sa, 0, sizeof(si_sa));
635 	si_sa.sa_handler = infohandler;
636 	if (sigaction(SIGINFO, &si_sa, NULL) == -1) {
637 	    warn("sigaction SIGINFO");
638 	    goto done;
639 	}
640 	for (lsn = 0; lsn < dir + (fat == 32 ? bpb.bpbSecPerClust : rds); lsn++) {
641 	    if (got_siginfo) {
642 		    fprintf(stderr,"%s: writing sector %u of %u (%u%%)\n",
643 			fname, lsn,
644 			(dir + (fat == 32 ? bpb.bpbSecPerClust: rds)),
645 			(lsn * 100) / (dir +
646 			    (fat == 32 ? bpb.bpbSecPerClust: rds)));
647 		    got_siginfo = 0;
648 	    }
649 	    x = lsn;
650 	    if (o.bootstrap &&
651 		fat == 32 && bpb.bpbBackup != MAXU16 &&
652 		bss <= bpb.bpbBackup && x >= bpb.bpbBackup) {
653 		x -= bpb.bpbBackup;
654 		if (!x && lseek(fd1, o.offset, SEEK_SET)) {
655 		    warn("%s", bname);
656 		    goto done;
657 		}
658 	    }
659 	    if (o.bootstrap && x < bss) {
660 		if ((n = read(fd1, img, bpb.bpbBytesPerSec)) == -1) {
661 		    warn("%s", bname);
662 		    goto done;
663 		}
664 		if ((unsigned)n != bpb.bpbBytesPerSec) {
665 		    warnx("%s: can't read sector %u", bname, x);
666 		    goto done;
667 		}
668 	    } else
669 		memset(img, 0, bpb.bpbBytesPerSec);
670 	    if (!lsn ||
671 		(fat == 32 && bpb.bpbBackup != MAXU16 &&
672 		 lsn == bpb.bpbBackup)) {
673 		x1 = sizeof(struct bs);
674 		bsbpb = (struct bsbpb *)(img + x1);
675 		mk2(bsbpb->bpbBytesPerSec, bpb.bpbBytesPerSec);
676 		mk1(bsbpb->bpbSecPerClust, bpb.bpbSecPerClust);
677 		mk2(bsbpb->bpbResSectors, bpb.bpbResSectors);
678 		mk1(bsbpb->bpbFATs, bpb.bpbFATs);
679 		mk2(bsbpb->bpbRootDirEnts, bpb.bpbRootDirEnts);
680 		mk2(bsbpb->bpbSectors, bpb.bpbSectors);
681 		mk1(bsbpb->bpbMedia, bpb.bpbMedia);
682 		mk2(bsbpb->bpbFATsecs, bpb.bpbFATsecs);
683 		mk2(bsbpb->bpbSecPerTrack, bpb.bpbSecPerTrack);
684 		mk2(bsbpb->bpbHeads, bpb.bpbHeads);
685 		mk4(bsbpb->bpbHiddenSecs, bpb.bpbHiddenSecs);
686 		mk4(bsbpb->bpbHugeSectors, bpb.bpbHugeSectors);
687 		x1 += sizeof(struct bsbpb);
688 		if (fat == 32) {
689 		    bsxbpb = (struct bsxbpb *)(img + x1);
690 		    mk4(bsxbpb->bpbBigFATsecs, bpb.bpbBigFATsecs);
691 		    mk2(bsxbpb->bpbExtFlags, 0);
692 		    mk2(bsxbpb->bpbFSVers, 0);
693 		    mk4(bsxbpb->bpbRootClust, bpb.bpbRootClust);
694 		    mk2(bsxbpb->bpbFSInfo, bpb.bpbFSInfo);
695 		    mk2(bsxbpb->bpbBackup, bpb.bpbBackup);
696 		    x1 += sizeof(struct bsxbpb);
697 		}
698 		bsx = (struct bsx *)(img + x1);
699 		mk1(bsx->exBootSignature, 0x29);
700 		if (o.volume_id_set)
701 		    x = o.volume_id;
702 		else
703 		    x = (((u_int)(1 + tm->tm_mon) << 8 |
704 			  (u_int)tm->tm_mday) +
705 			 ((u_int)tm->tm_sec << 8 |
706 			  (u_int)(tv.tv_usec / 10))) << 16 |
707 			((u_int)(1900 + tm->tm_year) +
708 			 ((u_int)tm->tm_hour << 8 |
709 			  (u_int)tm->tm_min));
710 		mk4(bsx->exVolumeID, x);
711 		mklabel(bsx->exVolumeLabel, o.volume_label ? o.volume_label : "NO NAME");
712 		snprintf(buf, sizeof(buf), "FAT%u", fat);
713 		setstr(bsx->exFileSysType, buf, sizeof(bsx->exFileSysType));
714 		if (!o.bootstrap) {
715 		    x1 += sizeof(struct bsx);
716 		    bs = (struct bs *)img;
717 		    mk1(bs->bsJump[0], 0xeb);
718 		    mk1(bs->bsJump[1], x1 - 2);
719 		    mk1(bs->bsJump[2], 0x90);
720 		    setstr(bs->bsOemName, o.OEM_string ? o.OEM_string : "BSD4.4  ",
721 			   sizeof(bs->bsOemName));
722 		    memcpy(img + x1, bootcode, sizeof(bootcode));
723 		    mk2(img + MINBPS - 2, DOSMAGIC);
724 		}
725 	    } else if (fat == 32 && bpb.bpbFSInfo != MAXU16 &&
726 		       (lsn == bpb.bpbFSInfo ||
727 			(bpb.bpbBackup != MAXU16 &&
728 			 lsn == bpb.bpbBackup + bpb.bpbFSInfo))) {
729 		mk4(img, 0x41615252);
730 		mk4(img + MINBPS - 28, 0x61417272);
731 		mk4(img + MINBPS - 24, 0xffffffff);
732 		mk4(img + MINBPS - 20, 0xffffffff);
733 		mk2(img + MINBPS - 2, DOSMAGIC);
734 	    } else if (lsn >= bpb.bpbResSectors && lsn < dir &&
735 		       !((lsn - bpb.bpbResSectors) %
736 			 (bpb.bpbFATsecs ? bpb.bpbFATsecs :
737 			  bpb.bpbBigFATsecs))) {
738 		mk1(img[0], bpb.bpbMedia);
739 		for (x = 1; x < fat * (fat == 32 ? 3 : 2) / 8; x++)
740 		    mk1(img[x], fat == 32 && x % 4 == 3 ? 0x0f : 0xff);
741 	    } else if (lsn == dir && o.volume_label) {
742 		de = (struct de *)img;
743 		mklabel(de->deName, o.volume_label);
744 		mk1(de->deAttributes, 050);
745 		x = (u_int)tm->tm_hour << 11 |
746 		    (u_int)tm->tm_min << 5 |
747 		    (u_int)tm->tm_sec >> 1;
748 		mk2(de->deMTime, x);
749 		x = (u_int)(tm->tm_year - 80) << 9 |
750 		    (u_int)(tm->tm_mon + 1) << 5 |
751 		    (u_int)tm->tm_mday;
752 		mk2(de->deMDate, x);
753 	    }
754 	    /*
755 	     * Issue a write of chunksize once we have collected
756 	     * enough sectors.
757 	     */
758 	    img += bpb.bpbBytesPerSec;
759 	    if (img >= physbuf_end) {
760 		n = write(fd, physbuf, chunksize);
761 		if (n != chunksize) {
762 		    warnx("%s: can't write sector %u", fname, lsn);
763 		    goto done;
764 		}
765 		img = physbuf;
766 	    }
767 	}
768 	/*
769 	 * Write remaining sectors, if the last write didn't end
770 	 * up filling a whole chunk.
771 	 */
772 	if (img != physbuf) {
773 		ssize_t tailsize = img - physbuf;
774 
775 		n = write(fd, physbuf, tailsize);
776 		if (n != tailsize) {
777 		    warnx("%s: can't write sector %u", fname, lsn);
778 		    goto done;
779 		}
780 	}
781     }
782     rv = 0;
783 done:
784     free(physbuf);
785     if (fd != -1)
786 	    close(fd);
787     if (fd1 != -1)
788 	    close(fd1);
789 
790     return rv;
791 }
792 
793 /*
794  * return -1 with error if file system is mounted.
795  */
796 #ifndef MAKEFS
797 static int
798 check_mounted(const char *fname, mode_t mode)
799 {
800 /*
801  * If getmntinfo() is not available (e.g. Linux) don't check. This should
802  * not be a problem since we will only be using makefs to create images.
803  */
804     struct statfs *mp;
805     const char *s1, *s2;
806     size_t len;
807     int n, r;
808 
809     if (!(n = getmntinfo(&mp, MNT_NOWAIT))) {
810 	warn("getmntinfo");
811 	return -1;
812     }
813     len = strlen(_PATH_DEV);
814     s1 = fname;
815     if (!strncmp(s1, _PATH_DEV, len))
816 	s1 += len;
817     r = S_ISCHR(mode) && s1 != fname && *s1 == 'r';
818     for (; n--; mp++) {
819 	s2 = mp->f_mntfromname;
820 	if (!strncmp(s2, _PATH_DEV, len))
821 	    s2 += len;
822 	if ((r && s2 != mp->f_mntfromname && !strcmp(s1 + 1, s2)) ||
823 	    !strcmp(s1, s2)) {
824 	    warnx("%s is mounted on %s", fname, mp->f_mntonname);
825 	    return -1;
826 	}
827     }
828     return 0;
829 }
830 #endif
831 
832 /*
833  * Get optimal I/O size
834  */
835 static ssize_t
836 getchunksize(void)
837 {
838 	static ssize_t chunksize;
839 
840 	if (chunksize != 0)
841 		return (chunksize);
842 
843 #if 0
844 	int mib[2];
845 	size_t len;
846 
847 	mib[0] = CTL_KERN;
848 	mib[1] = KERN_MAXPHYS;
849 	len = sizeof(chunksize);
850 
851 	if (sysctl(mib, 2, &chunksize, &len, NULL, 0) == -1) {
852 		warn("sysctl: KERN_MAXPHYS, using %zu", (size_t)MAXPHYS);
853 		chunksize = 0;
854 	}
855 #endif
856 	if (chunksize == 0)
857 		chunksize = MAXPHYS;
858 
859 	/*
860 	 * For better performance, we want to write larger chunks instead of
861 	 * individual sectors (the size can only be 512, 1024, 2048 or 4096
862 	 * bytes). Assert that chunksize can always hold an integer number of
863 	 * sectors by asserting that both are power of two numbers and the
864 	 * chunksize is greater than MAXBPS.
865 	 */
866 	static_assert(powerof2(MAXBPS), "MAXBPS is not power of 2");
867 	assert(powerof2(chunksize));
868 	assert(chunksize > MAXBPS);
869 
870 	return (chunksize);
871 }
872 
873 /*
874  * Get a standard format.
875  */
876 static int
877 getstdfmt(const char *fmt, struct bpb *bpb)
878 {
879     u_int x, i;
880 
881     x = NELEM(stdfmt);
882     for (i = 0; i < x && strcmp(fmt, stdfmt[i].name); i++);
883     if (i == x) {
884 	warnx("%s: unknown standard format", fmt);
885 	return -1;
886     }
887     *bpb = stdfmt[i].bpb;
888     return 0;
889 }
890 
891 static void
892 compute_geometry_from_file(int fd, const char *fname, struct disklabel32 *lp)
893 {
894 	struct stat st;
895 	off_t ms;
896 
897 	if (fstat(fd, &st))
898 		err(1, "cannot get disk size");
899 	if (!S_ISREG(st.st_mode))
900 		errx(1, "%s is not a regular file", fname);
901 	ms = st.st_size;
902 	lp->d_secsize = 512;
903 	lp->d_nsectors = 63;
904 	lp->d_ntracks = 255;
905 	lp->d_secperunit = ms / lp->d_secsize;
906 }
907 
908 /*
909  * Get disk slice, partition, and geometry information.
910  */
911 static int
912 getdiskinfo(int fd, const char *fname, const char *dtype, __unused int oflag,
913 	    struct bpb *bpb)
914 {
915     struct disklabel32 *lp, dlp;
916     off_t hs = 0;
917 #ifndef MAKEFS
918     off_t ms;
919     struct fd_type type;
920     struct partinfo pi;
921 
922     lp = NULL;
923 
924     /* If the user specified a disk type, try to use that */
925     if (dtype != NULL) {
926 	lp = getdiskbyname(dtype);
927     }
928 
929     /* Maybe it's a floppy drive */
930     if (lp == NULL) {
931 	if (ioctl(fd, DIOCGPART, &pi) == -1) {
932 	    /* create a fake geometry for a file image */
933 	    compute_geometry_from_file(fd, fname, &dlp);
934 	    lp = &dlp;
935 	} else if (ioctl(fd, FD_GTYPE, &type) != -1) {
936 	    ms = pi.media_size;
937 	    dlp.d_secsize = 128 << type.secsize;
938 	    dlp.d_nsectors = type.sectrac;
939 	    dlp.d_ntracks = type.heads;
940 	    dlp.d_secperunit = ms / dlp.d_secsize;
941 	    lp = &dlp;
942 	} else {
943 	    ms = pi.media_size;
944 	}
945     }
946 
947     /* Maybe it's a fixed drive */
948     if (lp == NULL) {
949 	if (ioctl(fd, DIOCGPART, &pi) == - 1)
950 	    err(1, "cannot get disk information");
951 	dlp.d_secsize = pi.media_blksize;
952 	dlp.d_nsectors = pi.d_secpertrack;
953 	dlp.d_ntracks = pi.d_nheads;
954 	if (bpb->bpbBytesPerSec)
955 	    dlp.d_secsize = bpb->bpbBytesPerSec;
956 
957 	dlp.d_secperunit = ms / dlp.d_secsize;
958 
959 	hs = (ms / dlp.d_secsize) - dlp.d_secperunit;
960 	lp = &dlp;
961     }
962 #else
963     (void)dtype;
964     /* In the makefs case we only support image files: */
965     compute_geometry_from_file(fd, fname, &dlp);
966     lp = &dlp;
967 #endif
968 
969     if (bpb->bpbBytesPerSec == 0) {
970 	if (ckgeom(fname, lp->d_secsize, "bytes/sector") == -1)
971 	    return -1;
972 	bpb->bpbBytesPerSec = lp->d_secsize;
973     }
974     if (bpb->bpbSecPerTrack == 0) {
975 	if (ckgeom(fname, lp->d_nsectors, "sectors/track") == -1)
976 	    return -1;
977 	bpb->bpbSecPerTrack = lp->d_nsectors;
978     }
979     if (bpb->bpbHeads == 0) {
980 	if (ckgeom(fname, lp->d_ntracks, "drive heads") == -1)
981 	    return -1;
982 	bpb->bpbHeads = lp->d_ntracks;
983     }
984     if (bpb->bpbHugeSectors == 0)
985 	bpb->bpbHugeSectors = lp->d_secperunit;
986     if (bpb->bpbHiddenSecs == 0)
987 	bpb->bpbHiddenSecs = hs;
988     return 0;
989 }
990 
991 /*
992  * Print out BPB values.
993  */
994 static void
995 print_bpb(struct bpb *bpb)
996 {
997     printf("BytesPerSec=%u SecPerClust=%u ResSectors=%u FATs=%u",
998 	   bpb->bpbBytesPerSec, bpb->bpbSecPerClust, bpb->bpbResSectors,
999 	   bpb->bpbFATs);
1000     if (bpb->bpbRootDirEnts)
1001 	printf(" RootDirEnts=%u", bpb->bpbRootDirEnts);
1002     if (bpb->bpbSectors)
1003 	printf(" Sectors=%u", bpb->bpbSectors);
1004     printf(" Media=%#x", bpb->bpbMedia);
1005     if (bpb->bpbFATsecs)
1006 	printf(" FATsecs=%u", bpb->bpbFATsecs);
1007     printf(" SecPerTrack=%u Heads=%u HiddenSecs=%u", bpb->bpbSecPerTrack,
1008 	   bpb->bpbHeads, bpb->bpbHiddenSecs);
1009     if (bpb->bpbHugeSectors)
1010 	printf(" HugeSectors=%u", bpb->bpbHugeSectors);
1011     if (!bpb->bpbFATsecs) {
1012 	printf(" FATsecs=%u RootCluster=%u", bpb->bpbBigFATsecs,
1013 	       bpb->bpbRootClust);
1014 	printf(" FSInfo=");
1015 	printf(bpb->bpbFSInfo == MAXU16 ? "%#x" : "%u", bpb->bpbFSInfo);
1016 	printf(" Backup=");
1017 	printf(bpb->bpbBackup == MAXU16 ? "%#x" : "%u", bpb->bpbBackup);
1018     }
1019     printf("\n");
1020 }
1021 
1022 /*
1023  * Check a disk geometry value.
1024  */
1025 static int
1026 ckgeom(const char *fname, u_int val, const char *msg)
1027 {
1028     if (!val) {
1029 	warnx("%s: no default %s", fname, msg);
1030 	return -1;
1031     }
1032     if (val > MAXU16) {
1033 	warnx("%s: illegal %s %d", fname, msg, val);
1034 	return -1;
1035     }
1036     return 0;
1037 }
1038 
1039 /*
1040  * Check a volume label.
1041  */
1042 static int
1043 oklabel(const char *src)
1044 {
1045     int c, i;
1046 
1047     for (i = 0; i <= 11; i++) {
1048 	c = (u_char)*src++;
1049 	if (c < ' ' + !i || strchr("\"*+,./:;<=>?[\\]|", c))
1050 	    break;
1051     }
1052     return i && !c;
1053 }
1054 
1055 /*
1056  * Make a volume label.
1057  */
1058 static void
1059 mklabel(uint8_t *dest, const char *src)
1060 {
1061     int c, i;
1062 
1063     for (i = 0; i < 11; i++) {
1064 	c = *src ? toupper(*src++) : ' ';
1065 	*dest++ = !i && c == '\xe5' ? 5 : c;
1066     }
1067 }
1068 
1069 /*
1070  * Copy string, padding with spaces.
1071  */
1072 static void
1073 setstr(uint8_t *dest, const char *src, size_t len)
1074 {
1075     while (len--)
1076 	*dest++ = *src ? *src++ : ' ';
1077 }
1078 
1079 static void
1080 infohandler(int sig __unused)
1081 {
1082 
1083 	got_siginfo = 1;
1084 }
1085