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