xref: /freebsd/sbin/newfs_msdos/mkfs_msdos.c (revision 39ee7a7a6bdd1557b1c3532abf60d139798ac88b)
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 void check_mounted(const char *, mode_t);
218 static void getstdfmt(const char *, struct bpb *);
219 static void getdiskinfo(int, const char *, const char *, int,
220 			struct bpb *);
221 static void print_bpb(struct bpb *);
222 static u_int ckgeom(const char *, u_int, const char *);
223 static void mklabel(u_int8_t *, const char *);
224 static int oklabel(const char *);
225 static void setstr(u_int8_t *, const char *, size_t);
226 
227 int mkfs_msdos(const char *fname, const char *dtype,
228     const struct msdos_options *op)
229 {
230     char buf[MAXPATHLEN];
231     struct sigaction si_sa;
232     struct stat sb;
233     struct timeval tv;
234     struct bpb bpb;
235     struct tm *tm;
236     struct bs *bs;
237     struct bsbpb *bsbpb;
238     struct bsxbpb *bsxbpb;
239     struct bsx *bsx;
240     struct de *de;
241     u_int8_t *img;
242     const char *bname;
243     ssize_t n;
244     time_t now;
245     u_int fat, bss, rds, cls, dir, lsn, x, x1, x2;
246     int fd, fd1;
247     struct msdos_options o = *op;
248 
249     if (o.OEM_string && strlen(o.OEM_string) > 8) {
250 	errx(1, "%s: bad OEM string", o.OEM_string);
251     }
252     if (o.create_size) {
253 	if (o.no_create)
254 	    errx(1, "create (-C) is incompatible with -N");
255 	fd = open(fname, O_RDWR | O_CREAT | O_TRUNC, 0644);
256 	if (fd == -1)
257 	    errx(1, "failed to create %s", fname);
258 	if (ftruncate(fd, o.create_size))
259 	    errx(1, "failed to initialize %jd bytes", (intmax_t)o.create_size);
260     } else if ((fd = open(fname, o.no_create ? O_RDONLY : O_RDWR)) == -1)
261 	err(1, "%s", fname);
262     if (fstat(fd, &sb))
263 	err(1, "%s", fname);
264     if (o.create_size) {
265 	if (!S_ISREG(sb.st_mode))
266 	    warnx("warning, %s is not a regular file", fname);
267     } else {
268 	if (!S_ISCHR(sb.st_mode))
269 	    warnx("warning, %s is not a character device", fname);
270     }
271     if (!o.no_create)
272 	check_mounted(fname, sb.st_mode);
273     if (o.offset && o.offset != lseek(fd, o.offset, SEEK_SET))
274 	errx(1, "cannot seek to %jd", (intmax_t)o.offset);
275     memset(&bpb, 0, sizeof(bpb));
276     if (o.floppy) {
277 	getstdfmt(o.floppy, &bpb);
278 	bpb.bpbHugeSectors = bpb.bpbSectors;
279 	bpb.bpbSectors = 0;
280 	bpb.bpbBigFATsecs = bpb.bpbFATsecs;
281 	bpb.bpbFATsecs = 0;
282     }
283     if (o.drive_heads)
284 	bpb.bpbHeads = o.drive_heads;
285     if (o.sectors_per_track)
286 	bpb.bpbSecPerTrack = o.sectors_per_track;
287     if (o.bytes_per_sector)
288 	bpb.bpbBytesPerSec = o.bytes_per_sector;
289     if (o.size)
290 	bpb.bpbHugeSectors = o.size;
291     if (o.hidden_sectors_set)
292 	bpb.bpbHiddenSecs = o.hidden_sectors;
293     if (!(o.floppy || (o.drive_heads && o.sectors_per_track && o.bytes_per_sector && o.size && o.hidden_sectors_set))) {
294 	off_t delta;
295 	getdiskinfo(fd, fname, dtype, o.hidden_sectors_set, &bpb);
296 	bpb.bpbHugeSectors -= (o.offset / bpb.bpbBytesPerSec);
297 	delta = bpb.bpbHugeSectors % bpb.bpbSecPerTrack;
298 	if (delta != 0) {
299 	    warnx("trim %d sectors to adjust to a multiple of %d",
300 		(int)delta, bpb.bpbSecPerTrack);
301 	    bpb.bpbHugeSectors -= delta;
302 	}
303 	if (bpb.bpbSecPerClust == 0) {	/* set defaults */
304 	    if (bpb.bpbHugeSectors <= 6000)	/* about 3MB -> 512 bytes */
305 		bpb.bpbSecPerClust = 1;
306 	    else if (bpb.bpbHugeSectors <= (1<<17)) /* 64M -> 4k */
307 		bpb.bpbSecPerClust = 8;
308 	    else if (bpb.bpbHugeSectors <= (1<<19)) /* 256M -> 8k */
309 		bpb.bpbSecPerClust = 16;
310 	    else if (bpb.bpbHugeSectors <= (1<<21)) /* 1G -> 16k */
311 		bpb.bpbSecPerClust = 32;
312 	    else
313 		bpb.bpbSecPerClust = 64;		/* otherwise 32k */
314 	}
315     }
316     if (!powerof2(bpb.bpbBytesPerSec))
317 	errx(1, "bytes/sector (%u) is not a power of 2", bpb.bpbBytesPerSec);
318     if (bpb.bpbBytesPerSec < MINBPS)
319 	errx(1, "bytes/sector (%u) is too small; minimum is %u",
320 	     bpb.bpbBytesPerSec, MINBPS);
321     if (o.volume_label && !oklabel(o.volume_label))
322 	errx(1, "%s: bad volume label", o.volume_label);
323     if (!(fat = o.fat_type)) {
324 	if (o.floppy)
325 	    fat = 12;
326 	else if (!o.directory_entries && (o.info_sector || o.backup_sector))
327 	    fat = 32;
328     }
329     if ((fat == 32 && o.directory_entries) || (fat != 32 && (o.info_sector || o.backup_sector)))
330 	errx(1, "-%c is not a legal FAT%s option",
331 	     fat == 32 ? 'e' : o.info_sector ? 'i' : 'k',
332 	     fat == 32 ? "32" : "12/16");
333     if (o.floppy && fat == 32)
334 	bpb.bpbRootDirEnts = 0;
335     if (fat != 0 && fat != 12 && fat != 16 && fat != 32) {
336 	    errx(1, "%d: bad FAT type", fat);
337     }
338 
339     if (o.block_size) {
340 	if (!powerof2(o.block_size))
341 	    errx(1, "block size (%u) is not a power of 2", o.block_size);
342 	if (o.block_size < bpb.bpbBytesPerSec)
343 	    errx(1, "block size (%u) is too small; minimum is %u",
344 		 o.block_size, bpb.bpbBytesPerSec);
345 	if (o.block_size > bpb.bpbBytesPerSec * MAXSPC)
346 	    errx(1, "block size (%u) is too large; maximum is %u",
347 		 o.block_size, bpb.bpbBytesPerSec * MAXSPC);
348 	bpb.bpbSecPerClust = o.block_size / bpb.bpbBytesPerSec;
349     }
350     if (o.sectors_per_cluster) {
351 	if (!powerof2(o.sectors_per_cluster))
352 	    errx(1, "sectors/cluster (%u) is not a power of 2", o.sectors_per_cluster);
353 	bpb.bpbSecPerClust = o.sectors_per_cluster;
354     }
355     if (o.reserved_sectors)
356 	bpb.bpbResSectors = o.reserved_sectors;
357     if (o.num_FAT) {
358 	if (o.num_FAT > MAXNFT)
359 	    errx(1, "number of FATs (%u) is too large; maximum is %u",
360 		 o.num_FAT, MAXNFT);
361 	bpb.bpbFATs = o.num_FAT;
362     }
363     if (o.directory_entries)
364 	bpb.bpbRootDirEnts = o.directory_entries;
365     if (o.media_descriptor_set) {
366 	if (o.media_descriptor < 0xf0)
367 	    errx(1, "illegal media descriptor (%#x)", o.media_descriptor);
368 	bpb.bpbMedia = o.media_descriptor;
369     }
370     if (o.sectors_per_fat)
371 	bpb.bpbBigFATsecs = o.sectors_per_fat;
372     if (o.info_sector)
373 	bpb.bpbFSInfo = o.info_sector;
374     if (o.backup_sector)
375 	bpb.bpbBackup = o.backup_sector;
376     bss = 1;
377     bname = NULL;
378     fd1 = -1;
379     if (o.bootstrap) {
380 	bname = o.bootstrap;
381 	if (!strchr(bname, '/')) {
382 	    snprintf(buf, sizeof(buf), "/boot/%s", bname);
383 	    if (!(bname = strdup(buf)))
384 		err(1, NULL);
385 	}
386 	if ((fd1 = open(bname, O_RDONLY)) == -1 || fstat(fd1, &sb))
387 	    err(1, "%s", bname);
388 	if (!S_ISREG(sb.st_mode) || sb.st_size % bpb.bpbBytesPerSec ||
389 	    sb.st_size < bpb.bpbBytesPerSec ||
390 	    sb.st_size > bpb.bpbBytesPerSec * MAXU16)
391 	    errx(1, "%s: inappropriate file type or format", bname);
392 	bss = sb.st_size / bpb.bpbBytesPerSec;
393     }
394     if (!bpb.bpbFATs)
395 	bpb.bpbFATs = 2;
396     if (!fat) {
397 	if (bpb.bpbHugeSectors < (bpb.bpbResSectors ? bpb.bpbResSectors : bss) +
398 	    howmany((RESFTE + (bpb.bpbSecPerClust ? MINCLS16 : MAXCLS12 + 1)) *
399 		(bpb.bpbSecPerClust ? 16 : 12) / BPN,
400 		bpb.bpbBytesPerSec * NPB) *
401 	    bpb.bpbFATs +
402 	    howmany(bpb.bpbRootDirEnts ? bpb.bpbRootDirEnts : DEFRDE,
403 		    bpb.bpbBytesPerSec / sizeof(struct de)) +
404 	    (bpb.bpbSecPerClust ? MINCLS16 : MAXCLS12 + 1) *
405 	    (bpb.bpbSecPerClust ? bpb.bpbSecPerClust :
406 	     howmany(DEFBLK, bpb.bpbBytesPerSec)))
407 	    fat = 12;
408 	else if (bpb.bpbRootDirEnts || bpb.bpbHugeSectors <
409 		 (bpb.bpbResSectors ? bpb.bpbResSectors : bss) +
410 		 howmany((RESFTE + MAXCLS16) * 2, bpb.bpbBytesPerSec) *
411 		 bpb.bpbFATs +
412 		 howmany(DEFRDE, bpb.bpbBytesPerSec / sizeof(struct de)) +
413 		 (MAXCLS16 + 1) *
414 		 (bpb.bpbSecPerClust ? bpb.bpbSecPerClust :
415 		  howmany(8192, bpb.bpbBytesPerSec)))
416 	    fat = 16;
417 	else
418 	    fat = 32;
419     }
420     x = bss;
421     if (fat == 32) {
422 	if (!bpb.bpbFSInfo) {
423 	    if (x == MAXU16 || x == bpb.bpbBackup)
424 		errx(1, "no room for info sector");
425 	    bpb.bpbFSInfo = x;
426 	}
427 	if (bpb.bpbFSInfo != MAXU16 && x <= bpb.bpbFSInfo)
428 	    x = bpb.bpbFSInfo + 1;
429 	if (!bpb.bpbBackup) {
430 	    if (x == MAXU16)
431 		errx(1, "no room for backup sector");
432 	    bpb.bpbBackup = x;
433 	} else if (bpb.bpbBackup != MAXU16 && bpb.bpbBackup == bpb.bpbFSInfo)
434 	    errx(1, "backup sector would overwrite info sector");
435 	if (bpb.bpbBackup != MAXU16 && x <= bpb.bpbBackup)
436 	    x = bpb.bpbBackup + 1;
437     }
438     if (!bpb.bpbResSectors)
439 	bpb.bpbResSectors = fat == 32 ?
440 	    MAX(x, MAX(16384 / bpb.bpbBytesPerSec, 4)) : x;
441     else if (bpb.bpbResSectors < x)
442 	errx(1, "too few reserved sectors (need %d have %d)", x,
443 	     bpb.bpbResSectors);
444     if (fat != 32 && !bpb.bpbRootDirEnts)
445 	bpb.bpbRootDirEnts = DEFRDE;
446     rds = howmany(bpb.bpbRootDirEnts, bpb.bpbBytesPerSec / sizeof(struct de));
447     if (!bpb.bpbSecPerClust)
448 	for (bpb.bpbSecPerClust = howmany(fat == 16 ? DEFBLK16 :
449 					  DEFBLK, bpb.bpbBytesPerSec);
450 	     bpb.bpbSecPerClust < MAXSPC &&
451 	     bpb.bpbResSectors +
452 	     howmany((RESFTE + maxcls(fat)) * (fat / BPN),
453 		     bpb.bpbBytesPerSec * NPB) *
454 	     bpb.bpbFATs +
455 	     rds +
456 	     (u_int64_t) (maxcls(fat) + 1) *
457 	     bpb.bpbSecPerClust <= bpb.bpbHugeSectors;
458 	     bpb.bpbSecPerClust <<= 1)
459 	    continue;
460     if (fat != 32 && bpb.bpbBigFATsecs > MAXU16)
461 	errx(1, "too many sectors/FAT for FAT12/16");
462     x1 = bpb.bpbResSectors + rds;
463     x = bpb.bpbBigFATsecs ? bpb.bpbBigFATsecs : 1;
464     if (x1 + (u_int64_t)x * bpb.bpbFATs > bpb.bpbHugeSectors)
465 	errx(1, "meta data exceeds file system size");
466     x1 += x * bpb.bpbFATs;
467     x = (u_int64_t)(bpb.bpbHugeSectors - x1) * bpb.bpbBytesPerSec * NPB /
468 	(bpb.bpbSecPerClust * bpb.bpbBytesPerSec * NPB + fat /
469 	 BPN * bpb.bpbFATs);
470     x2 = howmany((RESFTE + MIN(x, maxcls(fat))) * (fat / BPN),
471 		 bpb.bpbBytesPerSec * NPB);
472     if (!bpb.bpbBigFATsecs) {
473 	bpb.bpbBigFATsecs = x2;
474 	x1 += (bpb.bpbBigFATsecs - 1) * bpb.bpbFATs;
475     }
476     cls = (bpb.bpbHugeSectors - x1) / bpb.bpbSecPerClust;
477     x = (u_int64_t)bpb.bpbBigFATsecs * bpb.bpbBytesPerSec * NPB / (fat / BPN) -
478 	RESFTE;
479     if (cls > x)
480 	cls = x;
481     if (bpb.bpbBigFATsecs < x2)
482 	warnx("warning: sectors/FAT limits file system to %u clusters",
483 	      cls);
484     if (cls < mincls(fat))
485 	errx(1, "%u clusters too few clusters for FAT%u, need %u", cls, fat,
486 	    mincls(fat));
487     if (cls > maxcls(fat)) {
488 	cls = maxcls(fat);
489 	bpb.bpbHugeSectors = x1 + (cls + 1) * bpb.bpbSecPerClust - 1;
490 	warnx("warning: FAT type limits file system to %u sectors",
491 	      bpb.bpbHugeSectors);
492     }
493     printf("%s: %u sector%s in %u FAT%u cluster%s "
494 	   "(%u bytes/cluster)\n", fname, cls * bpb.bpbSecPerClust,
495 	   cls * bpb.bpbSecPerClust == 1 ? "" : "s", cls, fat,
496 	   cls == 1 ? "" : "s", bpb.bpbBytesPerSec * bpb.bpbSecPerClust);
497     if (!bpb.bpbMedia)
498 	bpb.bpbMedia = !bpb.bpbHiddenSecs ? 0xf0 : 0xf8;
499     if (fat == 32)
500 	bpb.bpbRootClust = RESFTE;
501     if (bpb.bpbHiddenSecs + bpb.bpbHugeSectors <= MAXU16) {
502 	bpb.bpbSectors = bpb.bpbHugeSectors;
503 	bpb.bpbHugeSectors = 0;
504     }
505     if (fat != 32) {
506 	bpb.bpbFATsecs = bpb.bpbBigFATsecs;
507 	bpb.bpbBigFATsecs = 0;
508     }
509     print_bpb(&bpb);
510     if (!o.no_create) {
511 	gettimeofday(&tv, NULL);
512 	now = tv.tv_sec;
513 	tm = localtime(&now);
514 	if (!(img = malloc(bpb.bpbBytesPerSec)))
515 	    err(1, NULL);
516 	dir = bpb.bpbResSectors + (bpb.bpbFATsecs ? bpb.bpbFATsecs :
517 				   bpb.bpbBigFATsecs) * bpb.bpbFATs;
518 	memset(&si_sa, 0, sizeof(si_sa));
519 	si_sa.sa_handler = infohandler;
520 	if (sigaction(SIGINFO, &si_sa, NULL) == -1)
521 		err(1, "sigaction SIGINFO");
522 	for (lsn = 0; lsn < dir + (fat == 32 ? bpb.bpbSecPerClust : rds); lsn++) {
523 	    if (got_siginfo) {
524 		    fprintf(stderr,"%s: writing sector %u of %u (%u%%)\n",
525 			fname, lsn,
526 			(dir + (fat == 32 ? bpb.bpbSecPerClust: rds)),
527 			(lsn * 100) / (dir +
528 			    (fat == 32 ? bpb.bpbSecPerClust: rds)));
529 		    got_siginfo = 0;
530 	    }
531 	    x = lsn;
532 	    if (o.bootstrap &&
533 		fat == 32 && bpb.bpbBackup != MAXU16 &&
534 		bss <= bpb.bpbBackup && x >= bpb.bpbBackup) {
535 		x -= bpb.bpbBackup;
536 		if (!x && lseek(fd1, o.offset, SEEK_SET))
537 		    err(1, "%s", bname);
538 	    }
539 	    if (o.bootstrap && x < bss) {
540 		if ((n = read(fd1, img, bpb.bpbBytesPerSec)) == -1)
541 		    err(1, "%s", bname);
542 		if ((unsigned)n != bpb.bpbBytesPerSec)
543 		    errx(1, "%s: can't read sector %u", bname, x);
544 	    } else
545 		memset(img, 0, bpb.bpbBytesPerSec);
546 	    if (!lsn ||
547 		(fat == 32 && bpb.bpbBackup != MAXU16 &&
548 		 lsn == bpb.bpbBackup)) {
549 		x1 = sizeof(struct bs);
550 		bsbpb = (struct bsbpb *)(img + x1);
551 		mk2(bsbpb->bpbBytesPerSec, bpb.bpbBytesPerSec);
552 		mk1(bsbpb->bpbSecPerClust, bpb.bpbSecPerClust);
553 		mk2(bsbpb->bpbResSectors, bpb.bpbResSectors);
554 		mk1(bsbpb->bpbFATs, bpb.bpbFATs);
555 		mk2(bsbpb->bpbRootDirEnts, bpb.bpbRootDirEnts);
556 		mk2(bsbpb->bpbSectors, bpb.bpbSectors);
557 		mk1(bsbpb->bpbMedia, bpb.bpbMedia);
558 		mk2(bsbpb->bpbFATsecs, bpb.bpbFATsecs);
559 		mk2(bsbpb->bpbSecPerTrack, bpb.bpbSecPerTrack);
560 		mk2(bsbpb->bpbHeads, bpb.bpbHeads);
561 		mk4(bsbpb->bpbHiddenSecs, bpb.bpbHiddenSecs);
562 		mk4(bsbpb->bpbHugeSectors, bpb.bpbHugeSectors);
563 		x1 += sizeof(struct bsbpb);
564 		if (fat == 32) {
565 		    bsxbpb = (struct bsxbpb *)(img + x1);
566 		    mk4(bsxbpb->bpbBigFATsecs, bpb.bpbBigFATsecs);
567 		    mk2(bsxbpb->bpbExtFlags, 0);
568 		    mk2(bsxbpb->bpbFSVers, 0);
569 		    mk4(bsxbpb->bpbRootClust, bpb.bpbRootClust);
570 		    mk2(bsxbpb->bpbFSInfo, bpb.bpbFSInfo);
571 		    mk2(bsxbpb->bpbBackup, bpb.bpbBackup);
572 		    x1 += sizeof(struct bsxbpb);
573 		}
574 		bsx = (struct bsx *)(img + x1);
575 		mk1(bsx->exBootSignature, 0x29);
576 		if (o.volume_id_set)
577 		    x = o.volume_id;
578 		else
579 		    x = (((u_int)(1 + tm->tm_mon) << 8 |
580 			  (u_int)tm->tm_mday) +
581 			 ((u_int)tm->tm_sec << 8 |
582 			  (u_int)(tv.tv_usec / 10))) << 16 |
583 			((u_int)(1900 + tm->tm_year) +
584 			 ((u_int)tm->tm_hour << 8 |
585 			  (u_int)tm->tm_min));
586 		mk4(bsx->exVolumeID, x);
587 		mklabel(bsx->exVolumeLabel, o.volume_label ? o.volume_label : "NO NAME");
588 		snprintf(buf, sizeof(buf), "FAT%u", fat);
589 		setstr(bsx->exFileSysType, buf, sizeof(bsx->exFileSysType));
590 		if (!o.bootstrap) {
591 		    x1 += sizeof(struct bsx);
592 		    bs = (struct bs *)img;
593 		    mk1(bs->bsJump[0], 0xeb);
594 		    mk1(bs->bsJump[1], x1 - 2);
595 		    mk1(bs->bsJump[2], 0x90);
596 		    setstr(bs->bsOemName, o.OEM_string ? o.OEM_string : "BSD4.4  ",
597 			   sizeof(bs->bsOemName));
598 		    memcpy(img + x1, bootcode, sizeof(bootcode));
599 		    mk2(img + MINBPS - 2, DOSMAGIC);
600 		}
601 	    } else if (fat == 32 && bpb.bpbFSInfo != MAXU16 &&
602 		       (lsn == bpb.bpbFSInfo ||
603 			(bpb.bpbBackup != MAXU16 &&
604 			 lsn == bpb.bpbBackup + bpb.bpbFSInfo))) {
605 		mk4(img, 0x41615252);
606 		mk4(img + MINBPS - 28, 0x61417272);
607 		mk4(img + MINBPS - 24, 0xffffffff);
608 		mk4(img + MINBPS - 20, bpb.bpbRootClust);
609 		mk2(img + MINBPS - 2, DOSMAGIC);
610 	    } else if (lsn >= bpb.bpbResSectors && lsn < dir &&
611 		       !((lsn - bpb.bpbResSectors) %
612 			 (bpb.bpbFATsecs ? bpb.bpbFATsecs :
613 			  bpb.bpbBigFATsecs))) {
614 		mk1(img[0], bpb.bpbMedia);
615 		for (x = 1; x < fat * (fat == 32 ? 3 : 2) / 8; x++)
616 		    mk1(img[x], fat == 32 && x % 4 == 3 ? 0x0f : 0xff);
617 	    } else if (lsn == dir && o.volume_label) {
618 		de = (struct de *)img;
619 		mklabel(de->deName, o.volume_label);
620 		mk1(de->deAttributes, 050);
621 		x = (u_int)tm->tm_hour << 11 |
622 		    (u_int)tm->tm_min << 5 |
623 		    (u_int)tm->tm_sec >> 1;
624 		mk2(de->deMTime, x);
625 		x = (u_int)(tm->tm_year - 80) << 9 |
626 		    (u_int)(tm->tm_mon + 1) << 5 |
627 		    (u_int)tm->tm_mday;
628 		mk2(de->deMDate, x);
629 	    }
630 	    if ((n = write(fd, img, bpb.bpbBytesPerSec)) == -1)
631 		err(1, "%s", fname);
632 	    if ((unsigned)n != bpb.bpbBytesPerSec)
633 		errx(1, "%s: can't write sector %u", fname, lsn);
634 	}
635     }
636     return 0;
637 }
638 
639 /*
640  * Exit with error if file system is mounted.
641  */
642 static void
643 check_mounted(const char *fname, mode_t mode)
644 {
645     struct statfs *mp;
646     const char *s1, *s2;
647     size_t len;
648     int n, r;
649 
650     if (!(n = getmntinfo(&mp, MNT_NOWAIT)))
651 	err(1, "getmntinfo");
652     len = strlen(_PATH_DEV);
653     s1 = fname;
654     if (!strncmp(s1, _PATH_DEV, len))
655 	s1 += len;
656     r = S_ISCHR(mode) && s1 != fname && *s1 == 'r';
657     for (; n--; mp++) {
658 	s2 = mp->f_mntfromname;
659 	if (!strncmp(s2, _PATH_DEV, len))
660 	    s2 += len;
661 	if ((r && s2 != mp->f_mntfromname && !strcmp(s1 + 1, s2)) ||
662 	    !strcmp(s1, s2))
663 	    errx(1, "%s is mounted on %s", fname, mp->f_mntonname);
664     }
665 }
666 
667 /*
668  * Get a standard format.
669  */
670 static void
671 getstdfmt(const char *fmt, struct bpb *bpb)
672 {
673     u_int x, i;
674 
675     x = sizeof(stdfmt) / sizeof(stdfmt[0]);
676     for (i = 0; i < x && strcmp(fmt, stdfmt[i].name); i++);
677     if (i == x)
678 	errx(1, "%s: unknown standard format", fmt);
679     *bpb = stdfmt[i].bpb;
680 }
681 
682 /*
683  * Get disk slice, partition, and geometry information.
684  */
685 static void
686 getdiskinfo(int fd, const char *fname, const char *dtype, __unused int oflag,
687 	    struct bpb *bpb)
688 {
689     struct disklabel *lp, dlp;
690     struct fd_type type;
691     off_t ms, hs = 0;
692 
693     lp = NULL;
694 
695     /* If the user specified a disk type, try to use that */
696     if (dtype != NULL) {
697 	lp = getdiskbyname(dtype);
698     }
699 
700     /* Maybe it's a floppy drive */
701     if (lp == NULL) {
702 	if (ioctl(fd, DIOCGMEDIASIZE, &ms) == -1) {
703 	    struct stat st;
704 
705 	    if (fstat(fd, &st))
706 		err(1, "cannot get disk size");
707 	    /* create a fake geometry for a file image */
708 	    ms = st.st_size;
709 	    dlp.d_secsize = 512;
710 	    dlp.d_nsectors = 63;
711 	    dlp.d_ntracks = 255;
712 	    dlp.d_secperunit = ms / dlp.d_secsize;
713 	    lp = &dlp;
714 	} else if (ioctl(fd, FD_GTYPE, &type) != -1) {
715 	    dlp.d_secsize = 128 << type.secsize;
716 	    dlp.d_nsectors = type.sectrac;
717 	    dlp.d_ntracks = type.heads;
718 	    dlp.d_secperunit = ms / dlp.d_secsize;
719 	    lp = &dlp;
720 	}
721     }
722 
723     /* Maybe it's a fixed drive */
724     if (lp == NULL) {
725 	if (bpb->bpbBytesPerSec)
726 	    dlp.d_secsize = bpb->bpbBytesPerSec;
727 	if (bpb->bpbBytesPerSec == 0 && ioctl(fd, DIOCGSECTORSIZE,
728 					      &dlp.d_secsize) == -1)
729 	    err(1, "cannot get sector size");
730 
731 	dlp.d_secperunit = ms / dlp.d_secsize;
732 
733 	if (bpb->bpbSecPerTrack == 0 && ioctl(fd, DIOCGFWSECTORS,
734 					      &dlp.d_nsectors) == -1) {
735 	    warn("cannot get number of sectors per track");
736 	    dlp.d_nsectors = 63;
737 	}
738 	if (bpb->bpbHeads == 0 &&
739 	    ioctl(fd, DIOCGFWHEADS, &dlp.d_ntracks) == -1) {
740 	    warn("cannot get number of heads");
741 	    if (dlp.d_secperunit <= 63*1*1024)
742 		dlp.d_ntracks = 1;
743 	    else if (dlp.d_secperunit <= 63*16*1024)
744 		dlp.d_ntracks = 16;
745 	    else
746 		dlp.d_ntracks = 255;
747 	}
748 
749 	hs = (ms / dlp.d_secsize) - dlp.d_secperunit;
750 	lp = &dlp;
751     }
752 
753     if (bpb->bpbBytesPerSec == 0)
754 	bpb->bpbBytesPerSec = ckgeom(fname, lp->d_secsize, "bytes/sector");
755     if (bpb->bpbSecPerTrack == 0)
756 	bpb->bpbSecPerTrack = ckgeom(fname, lp->d_nsectors, "sectors/track");
757     if (bpb->bpbHeads == 0)
758 	bpb->bpbHeads = ckgeom(fname, lp->d_ntracks, "drive heads");
759     if (bpb->bpbHugeSectors == 0)
760 	bpb->bpbHugeSectors = lp->d_secperunit;
761     if (bpb->bpbHiddenSecs == 0)
762 	bpb->bpbHiddenSecs = hs;
763 }
764 
765 /*
766  * Print out BPB values.
767  */
768 static void
769 print_bpb(struct bpb *bpb)
770 {
771     printf("BytesPerSec=%u SecPerClust=%u ResSectors=%u FATs=%u",
772 	   bpb->bpbBytesPerSec, bpb->bpbSecPerClust, bpb->bpbResSectors,
773 	   bpb->bpbFATs);
774     if (bpb->bpbRootDirEnts)
775 	printf(" RootDirEnts=%u", bpb->bpbRootDirEnts);
776     if (bpb->bpbSectors)
777 	printf(" Sectors=%u", bpb->bpbSectors);
778     printf(" Media=%#x", bpb->bpbMedia);
779     if (bpb->bpbFATsecs)
780 	printf(" FATsecs=%u", bpb->bpbFATsecs);
781     printf(" SecPerTrack=%u Heads=%u HiddenSecs=%u", bpb->bpbSecPerTrack,
782 	   bpb->bpbHeads, bpb->bpbHiddenSecs);
783     if (bpb->bpbHugeSectors)
784 	printf(" HugeSectors=%u", bpb->bpbHugeSectors);
785     if (!bpb->bpbFATsecs) {
786 	printf(" FATsecs=%u RootCluster=%u", bpb->bpbBigFATsecs,
787 	       bpb->bpbRootClust);
788 	printf(" FSInfo=");
789 	printf(bpb->bpbFSInfo == MAXU16 ? "%#x" : "%u", bpb->bpbFSInfo);
790 	printf(" Backup=");
791 	printf(bpb->bpbBackup == MAXU16 ? "%#x" : "%u", bpb->bpbBackup);
792     }
793     printf("\n");
794 }
795 
796 /*
797  * Check a disk geometry value.
798  */
799 static u_int
800 ckgeom(const char *fname, u_int val, const char *msg)
801 {
802     if (!val)
803 	errx(1, "%s: no default %s", fname, msg);
804     if (val > MAXU16)
805 	errx(1, "%s: illegal %s %d", fname, msg, val);
806     return val;
807 }
808 
809 /*
810  * Check a volume label.
811  */
812 static int
813 oklabel(const char *src)
814 {
815     int c, i;
816 
817     for (i = 0; i <= 11; i++) {
818 	c = (u_char)*src++;
819 	if (c < ' ' + !i || strchr("\"*+,./:;<=>?[\\]|", c))
820 	    break;
821     }
822     return i && !c;
823 }
824 
825 /*
826  * Make a volume label.
827  */
828 static void
829 mklabel(u_int8_t *dest, const char *src)
830 {
831     int c, i;
832 
833     for (i = 0; i < 11; i++) {
834 	c = *src ? toupper(*src++) : ' ';
835 	*dest++ = !i && c == '\xe5' ? 5 : c;
836     }
837 }
838 
839 /*
840  * Copy string, padding with spaces.
841  */
842 static void
843 setstr(u_int8_t *dest, const char *src, size_t len)
844 {
845     while (len--)
846 	*dest++ = *src ? *src++ : ' ';
847 }
848 
849 static void
850 infohandler(int sig __unused)
851 {
852 
853 	got_siginfo = 1;
854 }
855