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