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