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