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