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