xref: /openbsd/sbin/newfs_msdos/newfs_msdos.c (revision cca36db2)
1 /*	$OpenBSD: newfs_msdos.c,v 1.20 2010/05/18 04:41:14 dlg Exp $	*/
2 
3 /*
4  * Copyright (c) 1998 Robert Nordier
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in
14  *    the documentation and/or other materials provided with the
15  *    distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS
18  * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
19  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY
21  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
23  * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
25  * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
26  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
27  * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28  */
29 
30 #include <sys/param.h>
31 #include <sys/stat.h>
32 #include <sys/disklabel.h>
33 #include <sys/ioctl.h>
34 #include <sys/dkio.h>
35 #include <sys/mount.h>
36 
37 #include <ctype.h>
38 #include <err.h>
39 #include <errno.h>
40 #include <fcntl.h>
41 #include <paths.h>
42 #include <stdio.h>
43 #include <stdlib.h>
44 #include <string.h>
45 #include <unistd.h>
46 #include <util.h>
47 
48 #define MAXU16	  0xffff	/* maximum unsigned 16-bit quantity */
49 #define BPN	  4		/* bits per nibble */
50 #define NPB	  2		/* nibbles per byte */
51 
52 #define DOSMAGIC  0xaa55	/* DOS magic number */
53 #define MINBPS	  128		/* minimum bytes per sector */
54 #define MAXSPC	  128		/* maximum sectors per cluster */
55 #define MAXNFT	  16		/* maximum number of FATs */
56 #define DEFBLK	  4096		/* default block size */
57 #define DEFBLK16  2048		/* default block size FAT16 */
58 #define DEFRDE	  512		/* default root directory entries */
59 #define RESFTE	  2		/* reserved FAT entries */
60 #define MINCLS12  1		/* minimum FAT12 clusters */
61 #define MINCLS16  0x1000	/* minimum FAT16 clusters */
62 #define MINCLS32  2		/* minimum FAT32 clusters */
63 #define MAXCLS12  0xfed		/* maximum FAT12 clusters */
64 #define MAXCLS16  0xfff5	/* maximum FAT16 clusters */
65 #define MAXCLS32  0xffffff5	/* maximum FAT32 clusters */
66 
67 #define mincls(fat)  ((fat) == 12 ? MINCLS12 :	\
68 		      (fat) == 16 ? MINCLS16 :	\
69 				    MINCLS32)
70 
71 #define maxcls(fat)  ((fat) == 12 ? MAXCLS12 :	\
72 		      (fat) == 16 ? MAXCLS16 :	\
73 				    MAXCLS32)
74 
75 #define mk1(p, x)				\
76     (p) = (u_int8_t)(x)
77 
78 #define mk2(p, x)				\
79     (p)[0] = (u_int8_t)(x),			\
80     (p)[1] = (u_int8_t)((x) >> 010)
81 
82 #define mk4(p, x)				\
83     (p)[0] = (u_int8_t)(x),			\
84     (p)[1] = (u_int8_t)((x) >> 010),		\
85     (p)[2] = (u_int8_t)((x) >> 020),		\
86     (p)[3] = (u_int8_t)((x) >> 030)
87 
88 #define argto1(arg, lo, msg)  argtou(arg, lo, 0xff, msg)
89 #define argto2(arg, lo, msg)  argtou(arg, lo, 0xffff, msg)
90 #define argto4(arg, lo, msg)  argtou(arg, lo, 0xffffffff, msg)
91 #define argtox(arg, lo, msg)  argtou(arg, lo, UINT_MAX, msg)
92 
93 struct bs {
94     u_int8_t jmp[3];		/* bootstrap entry point */
95     u_int8_t oem[8];		/* OEM name and version */
96 };
97 
98 struct bsbpb {
99     u_int8_t bps[2];		/* bytes per sector */
100     u_int8_t spc;		/* sectors per cluster */
101     u_int8_t res[2];		/* reserved sectors */
102     u_int8_t nft;		/* number of FATs */
103     u_int8_t rde[2];		/* root directory entries */
104     u_int8_t sec[2];		/* total sectors */
105     u_int8_t mid;		/* media descriptor */
106     u_int8_t spf[2];		/* sectors per FAT */
107     u_int8_t spt[2];		/* sectors per track */
108     u_int8_t hds[2];		/* drive heads */
109     u_int8_t hid[4];		/* hidden sectors */
110     u_int8_t bsec[4];		/* big total sectors */
111 };
112 
113 struct bsxbpb {
114     u_int8_t bspf[4];		/* big sectors per FAT */
115     u_int8_t xflg[2];		/* FAT control flags */
116     u_int8_t vers[2];		/* file system version */
117     u_int8_t rdcl[4];		/* root directory start cluster */
118     u_int8_t infs[2];		/* file system info sector */
119     u_int8_t bkbs[2];		/* backup boot sector */
120     u_int8_t rsvd[12];		/* reserved */
121 };
122 
123 struct bsx {
124     u_int8_t drv;		/* drive number */
125     u_int8_t rsvd;		/* reserved */
126     u_int8_t sig;		/* extended boot signature */
127     u_int8_t volid[4];		/* volume ID number */
128     u_int8_t label[11];		/* volume label */
129     u_int8_t type[8];		/* file system type */
130 };
131 
132 struct de {
133     u_int8_t namext[11];	/* name and extension */
134     u_int8_t attr;		/* attributes */
135     u_int8_t rsvd[10];		/* reserved */
136     u_int8_t time[2];		/* creation time */
137     u_int8_t date[2];		/* creation date */
138     u_int8_t clus[2];		/* starting cluster */
139     u_int8_t size[4];		/* size */
140 };
141 
142 struct bpb {
143     u_int bps;			/* bytes per sector */
144     u_int spc;			/* sectors per cluster */
145     u_int res;			/* reserved sectors */
146     u_int nft;			/* number of FATs */
147     u_int rde;			/* root directory entries */
148     u_int sec;			/* total sectors */
149     u_int mid;			/* media descriptor */
150     u_int spf;			/* sectors per FAT */
151     u_int spt;			/* sectors per track */
152     u_int hds;			/* drive heads */
153     u_int hid;			/* hidden sectors */
154     u_int bsec;			/* big total sectors */
155     u_int bspf;			/* big sectors per FAT */
156     u_int rdcl; 		/* root directory start cluster */
157     u_int infs; 		/* file system info sector */
158     u_int bkbs; 		/* backup boot sector */
159 };
160 
161 static struct {
162     const char *name;
163     struct bpb bpb;
164 } stdfmt[] = {
165     {"160",  {512, 1, 1, 2,  64,  320, 0xfe, 1,  8, 1}},
166     {"180",  {512, 1, 1, 2,  64,  360, 0xfc, 2,  9, 1}},
167     {"320",  {512, 2, 1, 2, 112,  640, 0xff, 1,  8, 2}},
168     {"360",  {512, 2, 1, 2, 112,  720, 0xfd, 2,  9, 2}},
169     {"720",  {512, 2, 1, 2, 112, 1440, 0xf9, 3,  9, 2}},
170     {"1200", {512, 1, 1, 2, 224, 2400, 0xf9, 7, 15, 2}},
171     {"1440", {512, 1, 1, 2, 224, 2880, 0xf0, 9, 18, 2}},
172     {"2880", {512, 2, 1, 2, 240, 5760, 0xf0, 9, 36, 2}}
173 };
174 
175 static u_int8_t bootcode[] = {
176     0xfa,			/* cli		    */
177     0x31, 0xc0, 		/* xor	   ax,ax    */
178     0x8e, 0xd0, 		/* mov	   ss,ax    */
179     0xbc, 0x00, 0x7c,		/* mov	   sp,7c00h */
180     0xfb,			/* sti		    */
181     0x8e, 0xd8, 		/* mov	   ds,ax    */
182     0xe8, 0x00, 0x00,		/* call    $ + 3    */
183     0x5e,			/* pop	   si	    */
184     0x83, 0xc6, 0x19,		/* add	   si,+19h  */
185     0xbb, 0x07, 0x00,		/* mov	   bx,0007h */
186     0xfc,			/* cld		    */
187     0xac,			/* lodsb	    */
188     0x84, 0xc0, 		/* test    al,al    */
189     0x74, 0x06, 		/* jz	   $ + 8    */
190     0xb4, 0x0e, 		/* mov	   ah,0eh   */
191     0xcd, 0x10, 		/* int	   10h	    */
192     0xeb, 0xf5, 		/* jmp	   $ - 9    */
193     0x30, 0xe4, 		/* xor	   ah,ah    */
194     0xcd, 0x16, 		/* int	   16h	    */
195     0xcd, 0x19, 		/* int	   19h	    */
196     0x0d, 0x0a,
197     'N', 'o', 'n', '-', 's', 'y', 's', 't',
198     'e', 'm', ' ', 'd', 'i', 's', 'k',
199     0x0d, 0x0a,
200     'P', 'r', 'e', 's', 's', ' ', 'a', 'n',
201     'y', ' ', 'k', 'e', 'y', ' ', 't', 'o',
202     ' ', 'r', 'e', 'b', 'o', 'o', 't',
203     0x0d, 0x0a,
204     0
205 };
206 
207 static void check_mounted(const char *, mode_t);
208 static void getstdfmt(const char *, struct bpb *);
209 static void getdiskinfo(int, const char *, const char *, int,
210 			struct bpb *);
211 static void print_bpb(struct bpb *);
212 static u_int ckgeom(const char *, u_int, const char *);
213 static u_int argtou(const char *, u_int, u_int, const char *);
214 static int oklabel(const char *);
215 static void mklabel(u_int8_t *, const char *);
216 static void setstr(u_int8_t *, const char *, size_t);
217 static __dead void usage(void);
218 
219 /*
220  * Construct a FAT12, FAT16, or FAT32 file system.
221  */
222 int
223 main(int argc, char *argv[])
224 {
225     static char opts[] = "NB:F:I:L:O:S:a:b:c:e:f:h:i:k:m:n:o:qr:s:t:u:";
226     static const char *opt_B, *opt_L, *opt_O, *opt_f;
227     static u_int opt_F, opt_I, opt_S, opt_a, opt_b, opt_c, opt_e;
228     static u_int opt_h, opt_i, opt_k, opt_m, opt_n, opt_o, opt_r;
229     static u_int opt_s, opt_u;
230     static int opt_N;
231     static int Iflag, mflag, oflag;
232     char buf[MAXPATHLEN];
233     struct stat sb;
234     struct timeval tv;
235     struct bpb bpb;
236     struct tm *tm;
237     struct bs *bs;
238     struct bsbpb *bsbpb;
239     struct bsxbpb *bsxbpb;
240     struct bsx *bsx;
241     struct de *de;
242     u_int8_t *img;
243     const char *dtype, *bname;
244     char *sname, *fname;
245     ssize_t n;
246     time_t now;
247     u_int fat, bss, rds, cls, dir, lsn, x, x1, x2;
248     int ch, fd, fd1;
249 
250     while ((ch = getopt(argc, argv, opts)) != -1)
251 	switch (ch) {
252 	case 'N':
253 	    opt_N = 1;
254 	    break;
255 	case 'B':
256 	    opt_B = optarg;
257 	    break;
258 	case 'F':
259 	    if (strcmp(optarg, "12") &&
260 		strcmp(optarg, "16") &&
261 		strcmp(optarg, "32"))
262 		errx(1, "%s: bad FAT type", optarg);
263 	    opt_F = atoi(optarg);
264 	    break;
265 	case 'I':
266 	    opt_I = argto4(optarg, 0, "volume ID");
267 	    Iflag = 1;
268 	    break;
269 	case 'L':
270 	    if (!oklabel(optarg))
271 		errx(1, "%s: bad volume label", optarg);
272 	    opt_L = optarg;
273 	    break;
274 	case 'O':
275 	    if (strlen(optarg) > 8)
276 		errx(1, "%s: bad OEM string", optarg);
277 	    opt_O = optarg;
278 	    break;
279 	case 'S':
280 	    opt_S = argto2(optarg, 1, "bytes/sector");
281 	    break;
282 	case 'a':
283 	    opt_a = argto4(optarg, 1, "sectors/FAT");
284 	    break;
285 	case 'b':
286 	    opt_b = argtox(optarg, 1, "block size");
287 	    opt_c = 0;
288 	    break;
289 	case 'c':
290 	    opt_c = argto1(optarg, 1, "sectors/cluster");
291 	    opt_b = 0;
292 	    break;
293 	case 'e':
294 	    opt_e = argto2(optarg, 1, "directory entries");
295 	    break;
296 	case 'f':
297 	    opt_f = optarg;
298 	    break;
299 	case 'h':
300 	    opt_h = argto2(optarg, 1, "drive heads");
301 	    break;
302 	case 'i':
303 	    opt_i = argto2(optarg, 1, "info sector");
304 	    break;
305 	case 'k':
306 	    opt_k = argto2(optarg, 1, "backup sector");
307 	    break;
308 	case 'm':
309 	    opt_m = argto1(optarg, 0, "media descriptor");
310 	    mflag = 1;
311 	    break;
312 	case 'n':
313 	    opt_n = argto1(optarg, 1, "number of FATs");
314 	    break;
315 	case 'o':
316 	    opt_o = argto4(optarg, 0, "hidden sectors");
317 	    oflag = 1;
318 	    break;
319 	case 'q':			/* Compat with newfs -q */
320 	    break;
321 	case 'r':
322 	    opt_r = argto2(optarg, 1, "reserved sectors");
323 	    break;
324 	case 's':
325 	    opt_s = argto4(optarg, 1, "file system size");
326 	    break;
327 	case 't':			/* Compat with newfs -t */
328 	    break;
329 	case 'u':
330 	    opt_u = argto2(optarg, 1, "sectors/track");
331 	    break;
332 	default:
333 	    usage();
334 	}
335     argc -= optind;
336     argv += optind;
337     if (argc < 1 || argc > 2)
338 	usage();
339     sname = *argv++;
340     dtype = *argv;
341     if ((fd = opendev(sname, opt_N ? O_RDONLY : O_RDWR, 0, &fname)) == -1 ||
342 	fstat(fd, &sb))
343 	err(1, "%s", fname);
344     if (!opt_N)
345 	check_mounted(fname, sb.st_mode);
346     if (S_ISBLK(sb.st_mode))
347 	errx(1, "%s: block device", fname);
348     if (!S_ISCHR(sb.st_mode))
349 	warnx("warning: %s is not a character device", fname);
350     memset(&bpb, 0, sizeof(bpb));
351     if (opt_f) {
352 	getstdfmt(opt_f, &bpb);
353 	bpb.bsec = bpb.sec;
354 	bpb.sec = 0;
355 	bpb.bspf = bpb.spf;
356 	bpb.spf = 0;
357     }
358     if (opt_h)
359 	bpb.hds = opt_h;
360     if (opt_u)
361 	bpb.spt = opt_u;
362     if (opt_S)
363 	bpb.bps = opt_S;
364     if (opt_s)
365 	bpb.bsec = opt_s;
366     if (oflag)
367 	bpb.hid = opt_o;
368     if (!(opt_f || (opt_h && opt_u && opt_S && opt_s && oflag)))
369 	getdiskinfo(fd, fname, dtype, oflag, &bpb);
370     if (!powerof2(bpb.bps))
371 	errx(1, "bytes/sector (%u) is not a power of 2", bpb.bps);
372     if (bpb.bps < MINBPS)
373 	errx(1, "bytes/sector (%u) is too small; minimum is %u",
374 	     bpb.bps, MINBPS);
375     if (!(fat = opt_F)) {
376 	if (opt_f)
377 	    fat = 12;
378 	else if (!opt_e && (opt_i || opt_k))
379 	    fat = 32;
380     }
381     if ((fat == 32 && opt_e) || (fat != 32 && (opt_i || opt_k)))
382 	errx(1, "-%c is not a legal FAT%s option",
383 	     fat == 32 ? 'e' : opt_i ? 'i' : 'k',
384 	     fat == 32 ? "32" : "12/16");
385     if (opt_f && fat == 32)
386 	bpb.rde = 0;
387     if (opt_b) {
388 	if (!powerof2(opt_b))
389 	    errx(1, "block size (%u) is not a power of 2", opt_b);
390 	if (opt_b < bpb.bps)
391 	    errx(1, "block size (%u) is too small; minimum is %u",
392 		 opt_b, bpb.bps);
393 	if (opt_b > bpb.bps * MAXSPC)
394 	    errx(1, "block size (%u) is too large; maximum is %u",
395 		 opt_b, bpb.bps * MAXSPC);
396 	bpb.spc = opt_b / bpb.bps;
397     }
398     if (opt_c) {
399 	if (!powerof2(opt_c))
400 	    errx(1, "sectors/cluster (%u) is not a power of 2", opt_c);
401 	bpb.spc = opt_c;
402     }
403     if (opt_r)
404 	bpb.res = opt_r;
405     if (opt_n) {
406 	if (opt_n > MAXNFT)
407 	    errx(1, "number of FATs (%u) is too large; maximum is %u",
408 		 opt_n, MAXNFT);
409 	bpb.nft = opt_n;
410     }
411     if (opt_e)
412 	bpb.rde = opt_e;
413     if (mflag) {
414 	if (opt_m < 0xf0)
415 	    errx(1, "illegal media descriptor (%#x)", opt_m);
416 	bpb.mid = opt_m;
417     }
418     if (opt_a)
419 	bpb.bspf = opt_a;
420     if (opt_i)
421 	bpb.infs = opt_i;
422     if (opt_k)
423 	bpb.bkbs = opt_k;
424     bss = 1;
425     bname = NULL;
426     fd1 = -1;
427     if (opt_B) {
428 	bname = opt_B;
429 	if (!strchr(bname, '/')) {
430 	    snprintf(buf, sizeof(buf), "/boot/%s", bname);
431 	    if (!(bname = strdup(buf)))
432 		err(1, NULL);
433 	}
434 	if ((fd1 = open(bname, O_RDONLY)) == -1 || fstat(fd1, &sb))
435 	    err(1, "%s", bname);
436 	if (!S_ISREG(sb.st_mode) || sb.st_size % bpb.bps ||
437 	    sb.st_size < bpb.bps || sb.st_size > bpb.bps * MAXU16)
438 	    errx(1, "%s: inappropriate file type or format", bname);
439 	bss = sb.st_size / bpb.bps;
440     }
441     if (!bpb.nft)
442 	bpb.nft = 2;
443     if (!fat) {
444 	if (bpb.bsec < (bpb.res ? bpb.res : bss) +
445 	    howmany((RESFTE + (bpb.spc ? MINCLS16 : MAXCLS12 + 1)) *
446 		    ((bpb.spc ? 16 : 12) / BPN), bpb.bps * NPB) *
447 	    bpb.nft +
448 	    howmany(bpb.rde ? bpb.rde : DEFRDE,
449 		    bpb.bps / sizeof(struct de)) +
450 	    (bpb.spc ? MINCLS16 : MAXCLS12 + 1) *
451 	    (bpb.spc ? bpb.spc : howmany(DEFBLK, bpb.bps)))
452 	    fat = 12;
453 	else if (bpb.rde || bpb.bsec <
454 		 (bpb.res ? bpb.res : bss) +
455 		 howmany((RESFTE + MAXCLS16) * 2, bpb.bps) * bpb.nft +
456 		 howmany(DEFRDE, bpb.bps / sizeof(struct de)) +
457 		 (MAXCLS16 + 1) *
458 		 (bpb.spc ? bpb.spc : howmany(8192, bpb.bps)))
459 	    fat = 16;
460 	else
461 	    fat = 32;
462     }
463     x = bss;
464     if (fat == 32) {
465 	if (!bpb.infs) {
466 	    if (x == MAXU16 || x == bpb.bkbs)
467 		errx(1, "no room for info sector");
468 	    bpb.infs = x;
469 	}
470 	if (bpb.infs != MAXU16 && x <= bpb.infs)
471 	    x = bpb.infs + 1;
472 	if (!bpb.bkbs) {
473 	    if (x == MAXU16)
474 		errx(1, "no room for backup sector");
475 	    bpb.bkbs = x;
476 	} else if (bpb.bkbs != MAXU16 && bpb.bkbs == bpb.infs)
477 	    errx(1, "backup sector would overwrite info sector");
478 	if (bpb.bkbs != MAXU16 && x <= bpb.bkbs)
479 	    x = bpb.bkbs + 1;
480     }
481     if (!bpb.res)
482 	bpb.res = fat == 32 ? MAX(x, MAX(16384 / bpb.bps, 4)) : x;
483     else if (bpb.res < x)
484 	errx(1, "too few reserved sectors");
485     if (fat != 32 && !bpb.rde)
486 	bpb.rde = DEFRDE;
487     rds = howmany(bpb.rde, bpb.bps / sizeof(struct de));
488     if (!bpb.spc)
489 	for (bpb.spc = howmany(fat == 16 ? DEFBLK16 : DEFBLK, bpb.bps);
490 	     bpb.spc < MAXSPC &&
491 	     bpb.res +
492 	     howmany((RESFTE + maxcls(fat)) * (fat / BPN),
493 		     bpb.bps * NPB) * bpb.nft +
494 	     rds +
495 	     (u_int64_t)(maxcls(fat) + 1) * bpb.spc <= bpb.bsec;
496 	     bpb.spc <<= 1);
497     if (fat != 32 && bpb.bspf > MAXU16)
498 	errx(1, "too many sectors/FAT for FAT12/16");
499     x1 = bpb.res + rds;
500     x = bpb.bspf ? bpb.bspf : 1;
501     if (x1 + (u_int64_t)x * bpb.nft > bpb.bsec)
502 	errx(1, "meta data exceeds file system size");
503     x1 += x * bpb.nft;
504     x = (u_int64_t)(bpb.bsec - x1) * bpb.bps * NPB /
505 	(bpb.spc * bpb.bps * NPB + fat / BPN * bpb.nft);
506     x2 = howmany((RESFTE + MIN(x, maxcls(fat))) * (fat / BPN),
507 		 bpb.bps * NPB);
508     if (!bpb.bspf) {
509 	bpb.bspf = x2;
510 	x1 += (bpb.bspf - 1) * bpb.nft;
511     }
512     cls = (bpb.bsec - x1) / bpb.spc;
513     x = (u_int64_t)bpb.bspf * bpb.bps * NPB / (fat / BPN) - RESFTE;
514     if (cls > x)
515 	cls = x;
516     if (bpb.bspf < x2)
517 	warnx("warning: sectors/FAT limits file system to %u clusters",
518 	      cls);
519     if (cls < mincls(fat))
520 	errx(1, "%u clusters too few clusters for FAT%u, need %u", cls, fat,
521 	    mincls(fat));
522     if (cls > maxcls(fat)) {
523 	cls = maxcls(fat);
524 	bpb.bsec = x1 + (cls + 1) * bpb.spc - 1;
525 	warnx("warning: FAT type limits file system to %u sectors",
526 	      bpb.bsec);
527     }
528     printf("%s: %u sector%s in %u FAT%u cluster%s "
529 	   "(%u bytes/cluster)\n", fname, cls * bpb.spc,
530 	   cls * bpb.spc == 1 ? "" : "s", cls, fat,
531 	   cls == 1 ? "" : "s", bpb.bps * bpb.spc);
532     if (!bpb.mid)
533 	bpb.mid = !bpb.hid ? 0xf0 : 0xf8;
534     if (fat == 32)
535 	bpb.rdcl = RESFTE;
536     if (bpb.hid + bpb.bsec <= MAXU16) {
537 	bpb.sec = bpb.bsec;
538 	bpb.bsec = 0;
539     }
540     if (fat != 32) {
541 	bpb.spf = bpb.bspf;
542 	bpb.bspf = 0;
543     }
544     print_bpb(&bpb);
545     if (!opt_N) {
546 	gettimeofday(&tv, NULL);
547 	now = tv.tv_sec;
548 	tm = localtime(&now);
549 	if (!(img = malloc(bpb.bps)))
550 	    err(1, NULL);
551 	dir = bpb.res + (bpb.spf ? bpb.spf : bpb.bspf) * bpb.nft;
552 	for (lsn = 0; lsn < dir + (fat == 32 ? bpb.spc : rds); lsn++) {
553 	    x = lsn;
554 	    if (opt_B &&
555 		fat == 32 && bpb.bkbs != MAXU16 &&
556 		bss <= bpb.bkbs && x >= bpb.bkbs) {
557 		x -= bpb.bkbs;
558 		if (!x && lseek(fd1, 0, SEEK_SET))
559 		    err(1, "%s", bname);
560 	    }
561 	    if (opt_B && x < bss) {
562 		if ((n = read(fd1, img, bpb.bps)) == -1)
563 		    err(1, "%s", bname);
564 		if (n != bpb.bps)
565 		    errx(1, "%s: can't read sector %u", bname, x);
566 	    } else
567 		memset(img, 0, bpb.bps);
568 	    if (!lsn ||
569 	      (fat == 32 && bpb.bkbs != MAXU16 && lsn == bpb.bkbs)) {
570 		x1 = sizeof(struct bs);
571 		bsbpb = (struct bsbpb *)(img + x1);
572 		mk2(bsbpb->bps, bpb.bps);
573 		mk1(bsbpb->spc, bpb.spc);
574 		mk2(bsbpb->res, bpb.res);
575 		mk1(bsbpb->nft, bpb.nft);
576 		mk2(bsbpb->rde, bpb.rde);
577 		mk2(bsbpb->sec, bpb.sec);
578 		mk1(bsbpb->mid, bpb.mid);
579 		mk2(bsbpb->spf, bpb.spf);
580 		mk2(bsbpb->spt, bpb.spt);
581 		mk2(bsbpb->hds, bpb.hds);
582 		mk4(bsbpb->hid, bpb.hid);
583 		mk4(bsbpb->bsec, bpb.bsec);
584 		x1 += sizeof(struct bsbpb);
585 		if (fat == 32) {
586 		    bsxbpb = (struct bsxbpb *)(img + x1);
587 		    mk4(bsxbpb->bspf, bpb.bspf);
588 		    mk2(bsxbpb->xflg, 0);
589 		    mk2(bsxbpb->vers, 0);
590 		    mk4(bsxbpb->rdcl, bpb.rdcl);
591 		    mk2(bsxbpb->infs, bpb.infs);
592 		    mk2(bsxbpb->bkbs, bpb.bkbs);
593 		    x1 += sizeof(struct bsxbpb);
594 		}
595 		bsx = (struct bsx *)(img + x1);
596 		mk1(bsx->sig, 0x29);
597 		if (Iflag)
598 		    x = opt_I;
599 		else
600 		    x = (((u_int)(1 + tm->tm_mon) << 8 |
601 			  (u_int)tm->tm_mday) +
602 			 ((u_int)tm->tm_sec << 8 |
603 			  (u_int)(tv.tv_usec / 10))) << 16 |
604 			((u_int)(1900 + tm->tm_year) +
605 			 ((u_int)tm->tm_hour << 8 |
606 			  (u_int)tm->tm_min));
607 		mk4(bsx->volid, x);
608 		mklabel(bsx->label, opt_L ? opt_L : "NO NAME");
609 		snprintf(buf, sizeof buf, "FAT%u", fat);
610 		setstr(bsx->type, buf, sizeof(bsx->type));
611 		if (!opt_B) {
612 		    x1 += sizeof(struct bsx);
613 		    bs = (struct bs *)img;
614 		    mk1(bs->jmp[0], 0xeb);
615 		    mk1(bs->jmp[1], x1 - 2);
616 		    mk1(bs->jmp[2], 0x90);
617 		    setstr(bs->oem, opt_O ? opt_O : "BSD  4.4",
618 			   sizeof(bs->oem));
619 		    memcpy(img + x1, bootcode, sizeof(bootcode));
620 		    mk2(img + bpb.bps - 2, DOSMAGIC);
621 		}
622 	    } else if (fat == 32 && bpb.infs != MAXU16 &&
623 		       (lsn == bpb.infs ||
624 			(bpb.bkbs != MAXU16 &&
625 			 lsn == bpb.bkbs + bpb.infs))) {
626 		mk4(img, 0x41615252);
627 		mk4(img + bpb.bps - 28, 0x61417272);
628 		mk4(img + bpb.bps - 24, 0xffffffff);
629 		mk4(img + bpb.bps - 20, bpb.rdcl);
630 		mk2(img + bpb.bps - 2, DOSMAGIC);
631 	    } else if (lsn >= bpb.res && lsn < dir &&
632 		       !((lsn - bpb.res) %
633 			 (bpb.spf ? bpb.spf : bpb.bspf))) {
634 		mk1(img[0], bpb.mid);
635 		for (x = 1; x < fat * (fat == 32 ? 3 : 2) / 8; x++)
636 		    mk1(img[x], fat == 32 && x % 4 == 3 ? 0x0f : 0xff);
637 	    } else if (lsn == dir && opt_L) {
638 		de = (struct de *)img;
639 		mklabel(de->namext, opt_L);
640 		mk1(de->attr, 050);
641 		x = (u_int)tm->tm_hour << 11 |
642 		    (u_int)tm->tm_min << 5 |
643 		    (u_int)tm->tm_sec >> 1;
644 		mk2(de->time, x);
645 		x = (u_int)(tm->tm_year - 80) << 9 |
646 		    (u_int)(tm->tm_mon + 1) << 5 |
647 		    (u_int)tm->tm_mday;
648 		mk2(de->date, x);
649 	    }
650 	    if ((n = write(fd, img, bpb.bps)) == -1)
651 		err(1, "%s", fname);
652 	    if (n != bpb.bps)
653 		errx(1, "%s: can't write sector %u", fname, lsn);
654 	}
655     }
656     return 0;
657 }
658 
659 /*
660  * Exit with error if file system is mounted.
661  */
662 static void
663 check_mounted(const char *fname, mode_t mode)
664 {
665     struct statfs *mp;
666     const char *s1, *s2;
667     size_t len;
668     int n, r;
669 
670     if (!(n = getmntinfo(&mp, MNT_NOWAIT)))
671 	err(1, "getmntinfo");
672     len = sizeof(_PATH_DEV) - 1;
673     s1 = fname;
674     if (!strncmp(s1, _PATH_DEV, len))
675 	s1 += len;
676     r = S_ISCHR(mode) && s1 != fname && *s1 == 'r';
677     for (; n--; mp++) {
678 	s2 = mp->f_mntfromname;
679 	if (!strncmp(s2, _PATH_DEV, len))
680 	    s2 += len;
681 	if ((r && s2 != mp->f_mntfromname && !strcmp(s1 + 1, s2)) ||
682 	    !strcmp(s1, s2))
683 	    errx(1, "%s is mounted on %s", fname, mp->f_mntonname);
684     }
685 }
686 
687 /*
688  * Get a standard format.
689  */
690 static void
691 getstdfmt(const char *fmt, struct bpb *bpb)
692 {
693     u_int x, i;
694 
695     x = sizeof(stdfmt) / sizeof(stdfmt[0]);
696     for (i = 0; i < x && strcmp(fmt, stdfmt[i].name); i++);
697     if (i == x)
698 	errx(1, "%s: unknown standard format", fmt);
699     *bpb = stdfmt[i].bpb;
700 }
701 
702 /*
703  * Get disk slice, partition, and geometry information.
704  */
705 static void
706 getdiskinfo(int fd, const char *fname, const char *dtype, int oflag,
707 	    struct bpb *bpb)
708 {
709     struct disklabel dl, *lp;
710     const char *s1, *s2;
711     int part, i;
712 
713     part = -1;
714     s1 = fname;
715     if ((s2 = strrchr(s1, '/')))
716 	s1 = s2 + 1;
717     for (s2 = s1; *s2 && !isdigit(*s2); s2++);
718     if (!*s2 || s2 == s1)
719 	s2 = NULL;
720     else
721 	while (isdigit(*++s2));
722     s1 = s2;
723     if (s2 && *s2 >= 'a' && *s2 <= 'a' + MAXPARTITIONS - 1) {
724 	part = *s2++ - 'a';
725     }
726     if (!s2 || (*s2 && *s2 != '.'))
727 	errx(1, "%s: can't figure out partition info", fname);
728     if ((((!oflag && part != -1) || !bpb->bsec)) ||
729 	!bpb->bps || !bpb->spt || !bpb->hds) {
730 	lp = &dl;
731 	i = ioctl(fd, DIOCGDINFO, lp);
732 	if (i == -1) {
733 	    if (!dtype) {
734 		warn("ioctl (GDINFO)");
735 		errx(1, "%s: can't read disk label; "
736 		     "disk type must be specified", fname);
737 	    } else if (!(lp = getdiskbyname(dtype)))
738 		errx(1, "%s: unknown disk type", dtype);
739 	}
740 	if (part == -1)
741 	    part = RAW_PART;
742 	if (part >= lp->d_npartitions ||
743 	    !lp->d_partitions[part].p_size)
744 	    errx(1, "%s: partition is unavailable", fname);
745 	if (!oflag && part != -1)
746 	    bpb->hid += lp->d_partitions[part].p_offset;
747 	if (!bpb->bsec)
748 	    bpb->bsec = lp->d_partitions[part].p_size;
749 	if (!bpb->bps)
750 	    bpb->bps = ckgeom(fname, lp->d_secsize, "bytes/sector");
751 	if (!bpb->spt)
752 	    bpb->spt = ckgeom(fname, lp->d_nsectors, "sectors/track");
753 	if (!bpb->hds)
754 	    bpb->hds = ckgeom(fname, lp->d_ntracks, "drive heads");
755 	if (bpb->spt > 63) {
756 	    bpb->hds = bpb->hds * bpb->spt / 63;
757 	    bpb->spt = 63;
758 	}
759     }
760 }
761 
762 /*
763  * Print out BPB values.
764  */
765 static void
766 print_bpb(struct bpb *bpb)
767 {
768     printf("bps=%u spc=%u res=%u nft=%u", bpb->bps, bpb->spc, bpb->res,
769 	   bpb->nft);
770     if (bpb->rde)
771 	printf(" rde=%u", bpb->rde);
772     if (bpb->sec)
773 	printf(" sec=%u", bpb->sec);
774     printf(" mid=%#x", bpb->mid);
775     if (bpb->spf)
776 	printf(" spf=%u", bpb->spf);
777     printf(" spt=%u hds=%u hid=%u", bpb->spt, bpb->hds, bpb->hid);
778     if (bpb->bsec)
779 	printf(" bsec=%u", bpb->bsec);
780     if (!bpb->spf) {
781 	printf(" bspf=%u rdcl=%u", bpb->bspf, bpb->rdcl);
782 	printf(" infs=");
783 	printf(bpb->infs == MAXU16 ? "%#x" : "%u", bpb->infs);
784 	printf(" bkbs=");
785 	printf(bpb->bkbs == MAXU16 ? "%#x" : "%u", bpb->bkbs);
786     }
787     printf("\n");
788 }
789 
790 /*
791  * Check a disk geometry value.
792  */
793 static u_int
794 ckgeom(const char *fname, u_int val, const char *msg)
795 {
796     if (!val)
797 	errx(1, "%s: no default %s", fname, msg);
798     if (val > MAXU16)
799 	errx(1, "%s: illegal %s", fname, msg);
800     return val;
801 }
802 
803 /*
804  * Convert and check a numeric option argument.
805  */
806 static u_int
807 argtou(const char *arg, u_int lo, u_int hi, const char *msg)
808 {
809     char *s;
810     u_long x;
811 
812     errno = 0;
813     x = strtoul(arg, &s, 0);
814     if (errno || !*arg || *s || x < lo || x > hi)
815 	errx(1, "%s: bad %s", arg, msg);
816     return x;
817 }
818 
819 /*
820  * Check a volume label.
821  */
822 static int
823 oklabel(const char *src)
824 {
825     int c = 0, i;
826 
827     for (i = 0; i <= 11; i++) {
828 	c = (u_char)*src++;
829 	if (c < ' ' + !i || strchr("\"*+,./:;<=>?[\\]|", c))
830 	    break;
831     }
832     return i && !c;
833 }
834 
835 /*
836  * Make a volume label.
837  */
838 static void
839 mklabel(u_int8_t *dest, const char *src)
840 {
841     int c, i;
842 
843     for (i = 0; i < 11; i++) {
844 	c = *src ? toupper(*src++) : ' ';
845 	*dest++ = !i && c == '\xe5' ? 5 : c;
846     }
847 }
848 
849 /*
850  * Copy string, padding with spaces.
851  */
852 static void
853 setstr(u_int8_t *dest, const char *src, size_t len)
854 {
855     while (len--)
856 	*dest++ = *src ? *src++ : ' ';
857 }
858 
859 /*
860  * Print usage message.
861  */
862 static __dead void
863 usage(void)
864 {
865 	extern const char	*__progname;
866 
867 	fprintf(stderr, "usage: %s "
868 	    "[-N] [-a FAT-size] [-B boot] [-b block-size]\n"
869 	    "\t[-c cluster-size] [-e dirents] [-F FAT-type] [-f format]\n"
870 	    "\t[-h heads] [-I volid] [-i info] [-k backup] [-L label]\n"
871 	    "\t[-m media] [-n FATs] [-O OEM] [-o hidden] [-r reserved]\n"
872 	    "\t[-S sector-size] [-s total] [-u track-size] special\n"
873 	    "\t[disktype]\n",
874 	    __progname);
875 	exit(1);
876 }
877