newfs_msdos.c revision 231162
16059Samurai/*
26059Samurai * Copyright (c) 1998 Robert Nordier
36059Samurai * All rights reserved.
46059Samurai *
56059Samurai * Redistribution and use in source and binary forms, with or without
66059Samurai * modification, are permitted provided that the following conditions
76059Samurai * are met:
86059Samurai * 1. Redistributions of source code must retain the above copyright
96059Samurai *    notice, this list of conditions and the following disclaimer.
106059Samurai * 2. Redistributions in binary form must reproduce the above copyright
116059Samurai *    notice, this list of conditions and the following disclaimer in
126059Samurai *    the documentation and/or other materials provided with the
136059Samurai *    distribution.
146059Samurai *
156059Samurai * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS
166059Samurai * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
176059Samurai * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
186059Samurai * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY
198857Srgrimes * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
2050479Speter * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
218857Srgrimes * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
226059Samurai * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
236059Samurai * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
2443313Sbrian * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
2530715Sbrian * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2636285Sbrian */
2736285Sbrian
2836285Sbrian#ifndef lint
2930715Sbrianstatic const char rcsid[] =
3043888Sbrian  "$FreeBSD: stable/9/sbin/newfs_msdos/newfs_msdos.c 231162 2012-02-07 21:56:58Z delphij $";
3143888Sbrian#endif /* not lint */
3237192Sbrian
3336287Sbrian#include <sys/param.h>
3437192Sbrian#include <sys/fdcio.h>
3530715Sbrian#include <sys/disk.h>
3643888Sbrian#include <sys/disklabel.h>
3743888Sbrian#include <sys/mount.h>
3849976Sbrian#include <sys/stat.h>
3930715Sbrian#include <sys/time.h>
4044106Sbrian
4143888Sbrian#include <ctype.h>
4236285Sbrian#include <err.h>
4343888Sbrian#include <errno.h>
4429840Sbrian#include <fcntl.h>
4546686Sbrian#include <inttypes.h>
4630715Sbrian#include <paths.h>
4730715Sbrian#include <signal.h>
4830715Sbrian#include <stdio.h>
4930715Sbrian#include <stdlib.h>
506059Samurai#include <string.h>
5146686Sbrian#include <time.h>
526059Samurai#include <unistd.h>
5336285Sbrian
546059Samurai#define MAXU16	  0xffff	/* maximum unsigned 16-bit quantity */
556735Samurai#define BPN	  4		/* bits per nibble */
5636285Sbrian#define NPB	  2		/* nibbles per byte */
5736285Sbrian
5836285Sbrian#define DOSMAGIC  0xaa55	/* DOS magic number */
5943888Sbrian#define MINBPS	  512		/* minimum bytes per sector */
6036285Sbrian#define MAXSPC	  128		/* maximum sectors per cluster */
6136285Sbrian#define MAXNFT	  16		/* maximum number of FATs */
6236285Sbrian#define DEFBLK	  4096		/* default block size */
6336285Sbrian#define DEFBLK16  2048		/* default block size FAT16 */
6436285Sbrian#define DEFRDE	  512		/* default root directory entries */
6536285Sbrian#define RESFTE	  2		/* reserved FAT entries */
6636285Sbrian#define MINCLS12  1U		/* minimum FAT12 clusters */
6736285Sbrian#define MINCLS16  0x1000U	/* minimum FAT16 clusters */
6843313Sbrian#define MINCLS32  2U		/* minimum FAT32 clusters */
6943313Sbrian#define MAXCLS12  0xfedU	/* maximum FAT12 clusters */
7043313Sbrian#define MAXCLS16  0xfff5U	/* maximum FAT16 clusters */
7136285Sbrian#define MAXCLS32  0xffffff5U	/* maximum FAT32 clusters */
7236285Sbrian
7338174Sbrian#define mincls(fat)  ((fat) == 12 ? MINCLS12 :	\
7443888Sbrian		      (fat) == 16 ? MINCLS16 :	\
7536285Sbrian				    MINCLS32)
7637192Sbrian
7736287Sbrian#define maxcls(fat)  ((fat) == 12 ? MAXCLS12 :	\
7837192Sbrian		      (fat) == 16 ? MAXCLS16 :	\
796059Samurai				    MAXCLS32)
8031343Sbrian
8119866Sphk#define mk1(p, x)				\
826059Samurai    (p) = (u_int8_t)(x)
8343693Sbrian
846059Samurai#define mk2(p, x)				\
8530715Sbrian    (p)[0] = (u_int8_t)(x),			\
8636285Sbrian    (p)[1] = (u_int8_t)((x) >> 010)
8743693Sbrian
886059Samurai#define mk4(p, x)				\
896059Samurai    (p)[0] = (u_int8_t)(x),			\
906059Samurai    (p)[1] = (u_int8_t)((x) >> 010),		\
916059Samurai    (p)[2] = (u_int8_t)((x) >> 020),		\
926059Samurai    (p)[3] = (u_int8_t)((x) >> 030)
9328679Sbrian
946059Samurai#define argto1(arg, lo, msg)  argtou(arg, lo, 0xff, msg)
956059Samurai#define argto2(arg, lo, msg)  argtou(arg, lo, 0xffff, msg)
966059Samurai#define argto4(arg, lo, msg)  argtou(arg, lo, 0xffffffff, msg)
9754912Sbrian#define argtox(arg, lo, msg)  argtou(arg, lo, UINT_MAX, msg)
9830715Sbrian
996059Samuraistruct bs {
10030715Sbrian    u_int8_t bsJump[3];			/* bootstrap entry point */
10136285Sbrian    u_int8_t bsOemName[8];		/* OEM name and version */
10237926Sbrian} __packed;
10337926Sbrian
10437926Sbrianstruct bsbpb {
10537926Sbrian    u_int8_t bpbBytesPerSec[2];		/* bytes per sector */
10646686Sbrian    u_int8_t bpbSecPerClust;		/* sectors per cluster */
10750867Sbrian    u_int8_t bpbResSectors[2];		/* reserved sectors */
1086059Samurai    u_int8_t bpbFATs;			/* number of FATs */
1096059Samurai    u_int8_t bpbRootDirEnts[2];		/* root directory entries */
11043693Sbrian    u_int8_t bpbSectors[2];		/* total sectors */
11144123Sbrian    u_int8_t bpbMedia;			/* media descriptor */
11244123Sbrian    u_int8_t bpbFATsecs[2];		/* sectors per FAT */
11344123Sbrian    u_int8_t bpbSecPerTrack[2];		/* sectors per track */
11444123Sbrian    u_int8_t bpbHeads[2];		/* drive heads */
11544123Sbrian    u_int8_t bpbHiddenSecs[4];		/* hidden sectors */
1166059Samurai    u_int8_t bpbHugeSectors[4];		/* big total sectors */
11743693Sbrian} __packed;
11843693Sbrian
11943693Sbrianstruct bsxbpb {
12043693Sbrian    u_int8_t bpbBigFATsecs[4];		/* big sectors per FAT */
12143693Sbrian    u_int8_t bpbExtFlags[2];		/* FAT control flags */
12243693Sbrian    u_int8_t bpbFSVers[2];		/* file system version */
12343693Sbrian    u_int8_t bpbRootClust[4];		/* root directory start cluster */
12444106Sbrian    u_int8_t bpbFSInfo[2];		/* file system info sector */
12543693Sbrian    u_int8_t bpbBackup[2];		/* backup boot sector */
12643693Sbrian    u_int8_t bpbReserved[12];		/* reserved */
12743693Sbrian} __packed;
12843693Sbrian
12943693Sbrianstruct bsx {
13043693Sbrian    u_int8_t exDriveNumber;		/* drive number */
13143693Sbrian    u_int8_t exReserved1;		/* reserved */
13244106Sbrian    u_int8_t exBootSignature;		/* extended boot signature */
13344106Sbrian    u_int8_t exVolumeID[4];		/* volume ID number */
13444106Sbrian    u_int8_t exVolumeLabel[11]; 	/* volume label */
13544106Sbrian    u_int8_t exFileSysType[8];		/* file system type */
13644106Sbrian} __packed;
13744106Sbrian
13844106Sbrianstruct de {
13944106Sbrian    u_int8_t deName[11];		/* name and extension */
14044106Sbrian    u_int8_t deAttributes;		/* attributes */
14143693Sbrian    u_int8_t rsvd[10];			/* reserved */
14244106Sbrian    u_int8_t deMTime[2];		/* creation time */
14344106Sbrian    u_int8_t deMDate[2];		/* creation date */
14444106Sbrian    u_int8_t deStartCluster[2];		/* starting cluster */
14544106Sbrian    u_int8_t deFileSize[4];		/* size */
14644106Sbrian} __packed;
14744106Sbrian
14844106Sbrianstruct bpb {
14944106Sbrian    u_int bpbBytesPerSec;		/* bytes per sector */
15044106Sbrian    u_int bpbSecPerClust;		/* sectors per cluster */
15144106Sbrian    u_int bpbResSectors;		/* reserved sectors */
15244106Sbrian    u_int bpbFATs;			/* number of FATs */
15344106Sbrian    u_int bpbRootDirEnts;		/* root directory entries */
15444106Sbrian    u_int bpbSectors;			/* total sectors */
15544106Sbrian    u_int bpbMedia;			/* media descriptor */
15644106Sbrian    u_int bpbFATsecs;			/* sectors per FAT */
15744106Sbrian    u_int bpbSecPerTrack;		/* sectors per track */
15844106Sbrian    u_int bpbHeads;			/* drive heads */
15944106Sbrian    u_int bpbHiddenSecs;		/* hidden sectors */
16044106Sbrian    u_int bpbHugeSectors; 		/* big total sectors */
16143693Sbrian    u_int bpbBigFATsecs; 		/* big sectors per FAT */
16243693Sbrian    u_int bpbRootClust; 		/* root directory start cluster */
16344106Sbrian    u_int bpbFSInfo; 			/* file system info sector */
16444106Sbrian    u_int bpbBackup; 			/* backup boot sector */
16544106Sbrian};
16644106Sbrian
16744106Sbrian#define BPBGAP 0, 0, 0, 0, 0, 0
16843693Sbrian
16943693Sbrianstatic struct {
17043693Sbrian    const char *name;
17143693Sbrian    struct bpb bpb;
17243693Sbrian} const stdfmt[] = {
17343693Sbrian    {"160",  {512, 1, 1, 2,  64,  320, 0xfe, 1,  8, 1, BPBGAP}},
17443693Sbrian    {"180",  {512, 1, 1, 2,  64,  360, 0xfc, 2,  9, 1, BPBGAP}},
17543693Sbrian    {"320",  {512, 2, 1, 2, 112,  640, 0xff, 1,  8, 2, BPBGAP}},
17643693Sbrian    {"360",  {512, 2, 1, 2, 112,  720, 0xfd, 2,  9, 2, BPBGAP}},
17743693Sbrian    {"640",  {512, 2, 1, 2, 112, 1280, 0xfb, 2,  8, 2, BPBGAP}},
17843693Sbrian    {"720",  {512, 2, 1, 2, 112, 1440, 0xf9, 3,  9, 2, BPBGAP}},
17943693Sbrian    {"1200", {512, 1, 1, 2, 224, 2400, 0xf9, 7, 15, 2, BPBGAP}},
18043693Sbrian    {"1232", {1024,1, 1, 2, 192, 1232, 0xfe, 2,  8, 2, BPBGAP}},
18143693Sbrian    {"1440", {512, 1, 1, 2, 224, 2880, 0xf0, 9, 18, 2, BPBGAP}},
18243693Sbrian    {"2880", {512, 2, 1, 2, 240, 5760, 0xf0, 9, 36, 2, BPBGAP}}
18343693Sbrian};
18443693Sbrian
18543693Sbrianstatic const u_int8_t bootcode[] = {
18643693Sbrian    0xfa,			/* cli		    */
18743693Sbrian    0x31, 0xc0, 		/* xor	   ax,ax    */
18843693Sbrian    0x8e, 0xd0, 		/* mov	   ss,ax    */
18943693Sbrian    0xbc, 0x00, 0x7c,		/* mov	   sp,7c00h */
19043693Sbrian    0xfb,			/* sti		    */
19143693Sbrian    0x8e, 0xd8, 		/* mov	   ds,ax    */
19243693Sbrian    0xe8, 0x00, 0x00,		/* call    $ + 3    */
19343693Sbrian    0x5e,			/* pop	   si	    */
19443693Sbrian    0x83, 0xc6, 0x19,		/* add	   si,+19h  */
19543693Sbrian    0xbb, 0x07, 0x00,		/* mov	   bx,0007h */
19643888Sbrian    0xfc,			/* cld		    */
19743888Sbrian    0xac,			/* lodsb	    */
19843888Sbrian    0x84, 0xc0, 		/* test    al,al    */
19943888Sbrian    0x74, 0x06, 		/* jz	   $ + 8    */
20043888Sbrian    0xb4, 0x0e, 		/* mov	   ah,0eh   */
20147849Sbrian    0xcd, 0x10, 		/* int	   10h	    */
20243888Sbrian    0xeb, 0xf5, 		/* jmp	   $ - 9    */
20343888Sbrian    0x30, 0xe4, 		/* xor	   ah,ah    */
20443888Sbrian    0xcd, 0x16, 		/* int	   16h	    */
20543888Sbrian    0xcd, 0x19, 		/* int	   19h	    */
20643888Sbrian    0x0d, 0x0a,
20743888Sbrian    'N', 'o', 'n', '-', 's', 'y', 's', 't',
20843888Sbrian    'e', 'm', ' ', 'd', 'i', 's', 'k',
20943888Sbrian    0x0d, 0x0a,
21043888Sbrian    'P', 'r', 'e', 's', 's', ' ', 'a', 'n',
21143888Sbrian    'y', ' ', 'k', 'e', 'y', ' ', 't', 'o',
21243888Sbrian    ' ', 'r', 'e', 'b', 'o', 'o', 't',
21343888Sbrian    0x0d, 0x0a,
21443888Sbrian    0
21543888Sbrian};
21643888Sbrian
21743888Sbrianstatic volatile sig_atomic_t got_siginfo;
21843888Sbrianstatic void infohandler(int);
21943888Sbrian
22047849Sbrianstatic void check_mounted(const char *, mode_t);
22143888Sbrianstatic void getstdfmt(const char *, struct bpb *);
22243888Sbrianstatic void getdiskinfo(int, const char *, const char *, int,
22343888Sbrian			struct bpb *);
22443888Sbrianstatic void print_bpb(struct bpb *);
22543888Sbrianstatic u_int ckgeom(const char *, u_int, const char *);
22643888Sbrianstatic u_int argtou(const char *, u_int, u_int, const char *);
22743888Sbrianstatic off_t argtooff(const char *, const char *);
22843888Sbrianstatic int oklabel(const char *);
22943888Sbrianstatic void mklabel(u_int8_t *, const char *);
23043888Sbrianstatic void setstr(u_int8_t *, const char *, size_t);
23143888Sbrianstatic void usage(void);
23243888Sbrian
23343888Sbrian/*
23443888Sbrian * Construct a FAT12, FAT16, or FAT32 file system.
23549976Sbrian */
23649976Sbrianint
23743888Sbrianmain(int argc, char *argv[])
23843888Sbrian{
23949976Sbrian    static const char opts[] = "@:NB:C:F:I:L:O:S:a:b:c:e:f:h:i:k:m:n:o:r:s:u:";
24049976Sbrian    const char *opt_B = NULL, *opt_L = NULL, *opt_O = NULL, *opt_f = NULL;
24143888Sbrian    u_int opt_F = 0, opt_I = 0, opt_S = 0, opt_a = 0, opt_b = 0, opt_c = 0;
24243888Sbrian    u_int opt_e = 0, opt_h = 0, opt_i = 0, opt_k = 0, opt_m = 0, opt_n = 0;
24343888Sbrian    u_int opt_o = 0, opt_r = 0, opt_s = 0, opt_u = 0;
24443888Sbrian    int opt_N = 0;
24549976Sbrian    int Iflag = 0, mflag = 0, oflag = 0;
24649976Sbrian    char buf[MAXPATHLEN];
24743888Sbrian    struct sigaction si_sa;
24843888Sbrian    struct stat sb;
24943888Sbrian    struct timeval tv;
25047849Sbrian    struct bpb bpb;
25143888Sbrian    struct tm *tm;
25249976Sbrian    struct bs *bs;
25349976Sbrian    struct bsbpb *bsbpb;
25443888Sbrian    struct bsxbpb *bsxbpb;
25543888Sbrian    struct bsx *bsx;
25643888Sbrian    struct de *de;
25743888Sbrian    u_int8_t *img;
25843888Sbrian    const char *fname, *dtype, *bname;
25943888Sbrian    ssize_t n;
26043888Sbrian    time_t now;
26143888Sbrian    u_int fat, bss, rds, cls, dir, lsn, x, x1, x2;
26245907Sbrian    int ch, fd, fd1;
26343888Sbrian    off_t opt_create = 0, opt_ofs = 0;
26443888Sbrian
26543888Sbrian    while ((ch = getopt(argc, argv, opts)) != -1)
26643888Sbrian	switch (ch) {
26743888Sbrian	case '@':
26843888Sbrian	    opt_ofs = argtooff(optarg, "offset");
26943888Sbrian	    break;
27043888Sbrian	case 'N':
27143888Sbrian	    opt_N = 1;
27243888Sbrian	    break;
27343888Sbrian	case 'B':
27443888Sbrian	    opt_B = optarg;
27543888Sbrian	    break;
27643888Sbrian	case 'C':
27743888Sbrian	    opt_create = argtooff(optarg, "create size");
27843888Sbrian	    break;
27943888Sbrian	case 'F':
28043888Sbrian	    if (strcmp(optarg, "12") &&
28143888Sbrian		strcmp(optarg, "16") &&
28243888Sbrian		strcmp(optarg, "32"))
28343888Sbrian		errx(1, "%s: bad FAT type", optarg);
28443888Sbrian	    opt_F = atoi(optarg);
28543888Sbrian	    break;
28643888Sbrian	case 'I':
28743888Sbrian	    opt_I = argto4(optarg, 0, "volume ID");
28843888Sbrian	    Iflag = 1;
28943888Sbrian	    break;
29043888Sbrian	case 'L':
29145907Sbrian	    if (!oklabel(optarg))
29244123Sbrian		errx(1, "%s: bad volume label", optarg);
29344106Sbrian	    opt_L = optarg;
29444123Sbrian	    break;
29543888Sbrian	case 'O':
29643888Sbrian	    if (strlen(optarg) > 8)
29743888Sbrian		errx(1, "%s: bad OEM string", optarg);
29844123Sbrian	    opt_O = optarg;
29944123Sbrian	    break;
30044123Sbrian	case 'S':
30144123Sbrian	    opt_S = argto2(optarg, 1, "bytes/sector");
30244123Sbrian	    break;
30343888Sbrian	case 'a':
30444106Sbrian	    opt_a = argto4(optarg, 1, "sectors/FAT");
30543888Sbrian	    break;
30645907Sbrian	case 'b':
30744123Sbrian	    opt_b = argtox(optarg, 1, "block size");
30844123Sbrian	    opt_c = 0;
30944123Sbrian	    break;
31044123Sbrian	case 'c':
31143888Sbrian	    opt_c = argto1(optarg, 1, "sectors/cluster");
31243888Sbrian	    opt_b = 0;
31343888Sbrian	    break;
31443888Sbrian	case 'e':
31544123Sbrian	    opt_e = argto2(optarg, 1, "directory entries");
31644106Sbrian	    break;
31744123Sbrian	case 'f':
31843888Sbrian	    opt_f = optarg;
31943888Sbrian	    break;
32043888Sbrian	case 'h':
32143888Sbrian	    opt_h = argto2(optarg, 1, "drive heads");
32243888Sbrian	    break;
32343888Sbrian	case 'i':
32443888Sbrian	    opt_i = argto2(optarg, 1, "info sector");
32543888Sbrian	    break;
32643888Sbrian	case 'k':
32743888Sbrian	    opt_k = argto2(optarg, 1, "backup sector");
32843888Sbrian	    break;
32943888Sbrian	case 'm':
33043888Sbrian	    opt_m = argto1(optarg, 0, "media descriptor");
33143888Sbrian	    mflag = 1;
33243888Sbrian	    break;
33343888Sbrian	case 'n':
33443888Sbrian	    opt_n = argto1(optarg, 1, "number of FATs");
33543888Sbrian	    break;
33643888Sbrian	case 'o':
33743888Sbrian	    opt_o = argto4(optarg, 0, "hidden sectors");
33843888Sbrian	    oflag = 1;
33943888Sbrian	    break;
34043888Sbrian	case 'r':
34143888Sbrian	    opt_r = argto2(optarg, 1, "reserved sectors");
34243888Sbrian	    break;
34343888Sbrian	case 's':
34443888Sbrian	    opt_s = argto4(optarg, 1, "file system size");
34543888Sbrian	    break;
34643888Sbrian	case 'u':
34743888Sbrian	    opt_u = argto2(optarg, 1, "sectors/track");
34843888Sbrian	    break;
34943888Sbrian	default:
35043888Sbrian	    usage();
35143888Sbrian	}
35243888Sbrian    argc -= optind;
35343888Sbrian    argv += optind;
35443888Sbrian    if (argc < 1 || argc > 2)
35543888Sbrian	usage();
35643888Sbrian    fname = *argv++;
35743888Sbrian    if (!opt_create && !strchr(fname, '/')) {
35843888Sbrian	snprintf(buf, sizeof(buf), "%s%s", _PATH_DEV, fname);
35943888Sbrian	if (!(fname = strdup(buf)))
36043888Sbrian	    err(1, NULL);
36143888Sbrian    }
36243888Sbrian    dtype = *argv;
36343888Sbrian    if (opt_create) {
36443888Sbrian	if (opt_N)
36543888Sbrian	    errx(1, "create (-C) is incompatible with -N");
36643888Sbrian	fd = open(fname, O_RDWR | O_CREAT | O_TRUNC, 0644);
36743888Sbrian	if (fd == -1)
36843888Sbrian	    errx(1, "failed to create %s", fname);
36943888Sbrian	if (ftruncate(fd, opt_create))
37043888Sbrian	    errx(1, "failed to initialize %jd bytes", (intmax_t)opt_create);
37143888Sbrian    } else if ((fd = open(fname, opt_N ? O_RDONLY : O_RDWR)) == -1)
37243888Sbrian	err(1, "%s", fname);
37343888Sbrian    if (fstat(fd, &sb))
37443888Sbrian	err(1, "%s", fname);
37543888Sbrian    if (opt_create) {
37643888Sbrian	if (!S_ISREG(sb.st_mode))
37743888Sbrian	    warnx("warning, %s is not a regular file", fname);
37843888Sbrian    } else {
37943888Sbrian	if (!S_ISCHR(sb.st_mode))
38044123Sbrian	    warnx("warning, %s is not a character device", fname);
38144106Sbrian    }
38244106Sbrian    if (!opt_N)
38344106Sbrian	check_mounted(fname, sb.st_mode);
38444106Sbrian    if (opt_ofs && opt_ofs != lseek(fd, opt_ofs, SEEK_SET))
38544123Sbrian	errx(1, "cannot seek to %jd", (intmax_t)opt_ofs);
38644106Sbrian    memset(&bpb, 0, sizeof(bpb));
38743888Sbrian    if (opt_f) {
38843888Sbrian	getstdfmt(opt_f, &bpb);
38943888Sbrian	bpb.bpbHugeSectors = bpb.bpbSectors;
39043888Sbrian	bpb.bpbSectors = 0;
39143888Sbrian	bpb.bpbBigFATsecs = bpb.bpbFATsecs;
39243888Sbrian	bpb.bpbFATsecs = 0;
39343888Sbrian    }
39444123Sbrian    if (opt_h)
39544123Sbrian	bpb.bpbHeads = opt_h;
39644123Sbrian    if (opt_u)
39744123Sbrian	bpb.bpbSecPerTrack = opt_u;
39844123Sbrian    if (opt_S)
39943888Sbrian	bpb.bpbBytesPerSec = opt_S;
40043888Sbrian    if (opt_s)
40143888Sbrian	bpb.bpbHugeSectors = opt_s;
40243888Sbrian    if (oflag)
40343888Sbrian	bpb.bpbHiddenSecs = opt_o;
40443888Sbrian    if (!(opt_f || (opt_h && opt_u && opt_S && opt_s && oflag))) {
40543888Sbrian	off_t delta;
40643888Sbrian	getdiskinfo(fd, fname, dtype, oflag, &bpb);
40743888Sbrian	bpb.bpbHugeSectors -= (opt_ofs / bpb.bpbBytesPerSec);
40843888Sbrian	delta = bpb.bpbHugeSectors % bpb.bpbSecPerTrack;
40943888Sbrian	if (delta != 0) {
41043888Sbrian	    warnx("trim %d sectors to adjust to a multiple of %d",
41143888Sbrian		(int)delta, bpb.bpbSecPerTrack);
41243888Sbrian	    bpb.bpbHugeSectors -= delta;
41343693Sbrian	}
41443693Sbrian	if (bpb.bpbSecPerClust == 0) {	/* set defaults */
41543693Sbrian	    if (bpb.bpbHugeSectors <= 6000)	/* about 3MB -> 512 bytes */
41613379Sphk		bpb.bpbSecPerClust = 1;
4176059Samurai	    else if (bpb.bpbHugeSectors <= (1<<17)) /* 64M -> 4k */
4186059Samurai		bpb.bpbSecPerClust = 8;
41943888Sbrian	    else if (bpb.bpbHugeSectors <= (1<<19)) /* 256M -> 8k */
42043401Sbrian		bpb.bpbSecPerClust = 16;
42145907Sbrian	    else if (bpb.bpbHugeSectors <= (1<<21)) /* 1G -> 16k */
42243888Sbrian		bpb.bpbSecPerClust = 32;
42345907Sbrian	    else
42443888Sbrian		bpb.bpbSecPerClust = 64;		/* otherwise 32k */
42543313Sbrian	}
42643888Sbrian    }
42743888Sbrian    if (!powerof2(bpb.bpbBytesPerSec))
42843888Sbrian	errx(1, "bytes/sector (%u) is not a power of 2", bpb.bpbBytesPerSec);
42943888Sbrian    if (bpb.bpbBytesPerSec < MINBPS)
43043888Sbrian	errx(1, "bytes/sector (%u) is too small; minimum is %u",
43143888Sbrian	     bpb.bpbBytesPerSec, MINBPS);
43243313Sbrian    if (!(fat = opt_F)) {
43343888Sbrian	if (opt_f)
43444106Sbrian	    fat = 12;
43544106Sbrian	else if (!opt_e && (opt_i || opt_k))
43644106Sbrian	    fat = 32;
43744106Sbrian    }
43844106Sbrian    if ((fat == 32 && opt_e) || (fat != 32 && (opt_i || opt_k)))
43944106Sbrian	errx(1, "-%c is not a legal FAT%s option",
44045907Sbrian	     fat == 32 ? 'e' : opt_i ? 'i' : 'k',
44143888Sbrian	     fat == 32 ? "32" : "12/16");
44243888Sbrian    if (opt_f && fat == 32)
44343888Sbrian	bpb.bpbRootDirEnts = 0;
44443313Sbrian    if (opt_b) {
44545907Sbrian	if (!powerof2(opt_b))
44645907Sbrian	    errx(1, "block size (%u) is not a power of 2", opt_b);
4476059Samurai	if (opt_b < bpb.bpbBytesPerSec)
4486059Samurai	    errx(1, "block size (%u) is too small; minimum is %u",
44930715Sbrian		 opt_b, bpb.bpbBytesPerSec);
45043693Sbrian	if (opt_b > bpb.bpbBytesPerSec * MAXSPC)
4516059Samurai	    errx(1, "block size (%u) is too large; maximum is %u",
45243693Sbrian		 opt_b, bpb.bpbBytesPerSec * MAXSPC);
45343693Sbrian	bpb.bpbSecPerClust = opt_b / bpb.bpbBytesPerSec;
45443693Sbrian    }
45543693Sbrian    if (opt_c) {
45643693Sbrian	if (!powerof2(opt_c))
4576059Samurai	    errx(1, "sectors/cluster (%u) is not a power of 2", opt_c);
45843693Sbrian	bpb.bpbSecPerClust = opt_c;
45943693Sbrian    }
46043693Sbrian    if (opt_r)
46143693Sbrian	bpb.bpbResSectors = opt_r;
46243693Sbrian    if (opt_n) {
46343693Sbrian	if (opt_n > MAXNFT)
46443693Sbrian	    errx(1, "number of FATs (%u) is too large; maximum is %u",
4656059Samurai		 opt_n, MAXNFT);
46643693Sbrian	bpb.bpbFATs = opt_n;
46743693Sbrian    }
46843693Sbrian    if (opt_e)
46943693Sbrian	bpb.bpbRootDirEnts = opt_e;
47043693Sbrian    if (mflag) {
47143693Sbrian	if (opt_m < 0xf0)
47237926Sbrian	    errx(1, "illegal media descriptor (%#x)", opt_m);
47344106Sbrian	bpb.bpbMedia = opt_m;
47444123Sbrian    }
47544123Sbrian    if (opt_a)
47644123Sbrian	bpb.bpbBigFATsecs = opt_a;
47744123Sbrian    if (opt_i)
47844123Sbrian	bpb.bpbFSInfo = opt_i;
47944106Sbrian    if (opt_k)
48044106Sbrian	bpb.bpbBackup = opt_k;
48144106Sbrian    bss = 1;
48244123Sbrian    bname = NULL;
48344106Sbrian    fd1 = -1;
48444106Sbrian    if (opt_B) {
48544106Sbrian	bname = opt_B;
48644106Sbrian	if (!strchr(bname, '/')) {
48744106Sbrian	    snprintf(buf, sizeof(buf), "/boot/%s", bname);
48844123Sbrian	    if (!(bname = strdup(buf)))
48944123Sbrian		err(1, NULL);
49044123Sbrian	}
49144106Sbrian	if ((fd1 = open(bname, O_RDONLY)) == -1 || fstat(fd1, &sb))
49244106Sbrian	    err(1, "%s", bname);
49344106Sbrian	if (!S_ISREG(sb.st_mode) || sb.st_size % bpb.bpbBytesPerSec ||
49444106Sbrian	    sb.st_size < bpb.bpbBytesPerSec ||
49544106Sbrian	    sb.st_size > bpb.bpbBytesPerSec * MAXU16)
49644123Sbrian	    errx(1, "%s: inappropriate file type or format", bname);
49744106Sbrian	bss = sb.st_size / bpb.bpbBytesPerSec;
49844106Sbrian    }
49944106Sbrian    if (!bpb.bpbFATs)
50044106Sbrian	bpb.bpbFATs = 2;
50144106Sbrian    if (!fat) {
50245907Sbrian	if (bpb.bpbHugeSectors < (bpb.bpbResSectors ? bpb.bpbResSectors : bss) +
50344106Sbrian	    howmany((RESFTE + (bpb.bpbSecPerClust ? MINCLS16 : MAXCLS12 + 1)) *
50444106Sbrian		(bpb.bpbSecPerClust ? 16 : 12) / BPN,
50544106Sbrian		bpb.bpbBytesPerSec * NPB) *
50644106Sbrian	    bpb.bpbFATs +
50744106Sbrian	    howmany(bpb.bpbRootDirEnts ? bpb.bpbRootDirEnts : DEFRDE,
50844106Sbrian		    bpb.bpbBytesPerSec / sizeof(struct de)) +
50944123Sbrian	    (bpb.bpbSecPerClust ? MINCLS16 : MAXCLS12 + 1) *
51044106Sbrian	    (bpb.bpbSecPerClust ? bpb.bpbSecPerClust :
51143693Sbrian	     howmany(DEFBLK, bpb.bpbBytesPerSec)))
51243693Sbrian	    fat = 12;
51343693Sbrian	else if (bpb.bpbRootDirEnts || bpb.bpbHugeSectors <
51443888Sbrian		 (bpb.bpbResSectors ? bpb.bpbResSectors : bss) +
51543888Sbrian		 howmany((RESFTE + MAXCLS16) * 2, bpb.bpbBytesPerSec) *
51643888Sbrian		 bpb.bpbFATs +
51743888Sbrian		 howmany(DEFRDE, bpb.bpbBytesPerSec / sizeof(struct de)) +
51843888Sbrian		 (MAXCLS16 + 1) *
51943888Sbrian		 (bpb.bpbSecPerClust ? bpb.bpbSecPerClust :
52043888Sbrian		  howmany(8192, bpb.bpbBytesPerSec)))
52143693Sbrian	    fat = 16;
52245907Sbrian	else
52344123Sbrian	    fat = 32;
52444106Sbrian    }
52544106Sbrian    x = bss;
52644123Sbrian    if (fat == 32) {
52743693Sbrian	if (!bpb.bpbFSInfo) {
52829840Sbrian	    if (x == MAXU16 || x == bpb.bpbBackup)
52943693Sbrian		errx(1, "no room for info sector");
53043888Sbrian	    bpb.bpbFSInfo = x;
53143888Sbrian	}
53243888Sbrian	if (bpb.bpbFSInfo != MAXU16 && x <= bpb.bpbFSInfo)
53343888Sbrian	    x = bpb.bpbFSInfo + 1;
53443888Sbrian	if (!bpb.bpbBackup) {
53546686Sbrian	    if (x == MAXU16)
53646686Sbrian		errx(1, "no room for backup sector");
53743693Sbrian	    bpb.bpbBackup = x;
53846686Sbrian	} else if (bpb.bpbBackup != MAXU16 && bpb.bpbBackup == bpb.bpbFSInfo)
53943693Sbrian	    errx(1, "backup sector would overwrite info sector");
54044106Sbrian	if (bpb.bpbBackup != MAXU16 && x <= bpb.bpbBackup)
54144123Sbrian	    x = bpb.bpbBackup + 1;
54248817Sbrian    }
54344123Sbrian    if (!bpb.bpbResSectors)
54444123Sbrian	bpb.bpbResSectors = fat == 32 ?
54544123Sbrian	    MAX(x, MAX(16384 / bpb.bpbBytesPerSec, 4)) : x;
54629840Sbrian    else if (bpb.bpbResSectors < x)
54746686Sbrian	errx(1, "too few reserved sectors (need %d have %d)", x,
54846686Sbrian	     bpb.bpbResSectors);
54954912Sbrian    if (fat != 32 && !bpb.bpbRootDirEnts)
55046686Sbrian	bpb.bpbRootDirEnts = DEFRDE;
55146686Sbrian    rds = howmany(bpb.bpbRootDirEnts, bpb.bpbBytesPerSec / sizeof(struct de));
55246686Sbrian    if (!bpb.bpbSecPerClust)
55346686Sbrian	for (bpb.bpbSecPerClust = howmany(fat == 16 ? DEFBLK16 :
55446686Sbrian					  DEFBLK, bpb.bpbBytesPerSec);
55545220Sbrian	     bpb.bpbSecPerClust < MAXSPC &&
55654912Sbrian	     bpb.bpbResSectors +
55746686Sbrian	     howmany((RESFTE + maxcls(fat)) * (fat / BPN),
55845220Sbrian		     bpb.bpbBytesPerSec * NPB) *
55945220Sbrian	     bpb.bpbFATs +
56054912Sbrian	     rds +
56144159Sbrian	     (u_int64_t) (maxcls(fat) + 1) *
56244159Sbrian	     bpb.bpbSecPerClust <= bpb.bpbHugeSectors;
56344159Sbrian	     bpb.bpbSecPerClust <<= 1)
56443693Sbrian	    continue;
56543693Sbrian    if (fat != 32 && bpb.bpbBigFATsecs > MAXU16)
56643693Sbrian	errx(1, "too many sectors/FAT for FAT12/16");
56743693Sbrian    x1 = bpb.bpbResSectors + rds;
56854912Sbrian    x = bpb.bpbBigFATsecs ? bpb.bpbBigFATsecs : 1;
56943693Sbrian    if (x1 + (u_int64_t)x * bpb.bpbFATs > bpb.bpbHugeSectors)
57043693Sbrian	errx(1, "meta data exceeds file system size");
57143693Sbrian    x1 += x * bpb.bpbFATs;
57243693Sbrian    x = (u_int64_t)(bpb.bpbHugeSectors - x1) * bpb.bpbBytesPerSec * NPB /
57346686Sbrian	(bpb.bpbSecPerClust * bpb.bpbBytesPerSec * NPB + fat /
57443693Sbrian	 BPN * bpb.bpbFATs);
57543693Sbrian    x2 = howmany((RESFTE + MIN(x, maxcls(fat))) * (fat / BPN),
57643693Sbrian		 bpb.bpbBytesPerSec * NPB);
57743693Sbrian    if (!bpb.bpbBigFATsecs) {
57854912Sbrian	bpb.bpbBigFATsecs = x2;
57946686Sbrian	x1 += (bpb.bpbBigFATsecs - 1) * bpb.bpbFATs;
58025630Sbrian    }
58143693Sbrian    cls = (bpb.bpbHugeSectors - x1) / bpb.bpbSecPerClust;
58229840Sbrian    x = (u_int64_t)bpb.bpbBigFATsecs * bpb.bpbBytesPerSec * NPB / (fat / BPN) -
58344123Sbrian	RESFTE;
58444106Sbrian    if (cls > x)
58544123Sbrian	cls = x;
58643693Sbrian    if (bpb.bpbBigFATsecs < x2)
58743693Sbrian	warnx("warning: sectors/FAT limits file system to %u clusters",
58844106Sbrian	      cls);
58944106Sbrian    if (cls < mincls(fat))
59043693Sbrian	errx(1, "%u clusters too few clusters for FAT%u, need %u", cls, fat,
59143693Sbrian	    mincls(fat));
59254912Sbrian    if (cls > maxcls(fat)) {
59346686Sbrian	cls = maxcls(fat);
59443693Sbrian	bpb.bpbHugeSectors = x1 + (cls + 1) * bpb.bpbSecPerClust - 1;
59545907Sbrian	warnx("warning: FAT type limits file system to %u sectors",
59645907Sbrian	      bpb.bpbHugeSectors);
59743693Sbrian    }
59844123Sbrian    printf("%s: %u sector%s in %u FAT%u cluster%s "
59944106Sbrian	   "(%u bytes/cluster)\n", fname, cls * bpb.bpbSecPerClust,
60044106Sbrian	   cls * bpb.bpbSecPerClust == 1 ? "" : "s", cls, fat,
60144106Sbrian	   cls == 1 ? "" : "s", bpb.bpbBytesPerSec * bpb.bpbSecPerClust);
60244123Sbrian    if (!bpb.bpbMedia)
60343693Sbrian	bpb.bpbMedia = !bpb.bpbHiddenSecs ? 0xf0 : 0xf8;
60443313Sbrian    if (fat == 32)
60543693Sbrian	bpb.bpbRootClust = RESFTE;
60643693Sbrian    if (bpb.bpbHiddenSecs + bpb.bpbHugeSectors <= MAXU16) {
60743693Sbrian	bpb.bpbSectors = bpb.bpbHugeSectors;
60843693Sbrian	bpb.bpbHugeSectors = 0;
60943693Sbrian    }
61043693Sbrian    if (fat != 32) {
61154912Sbrian	bpb.bpbFATsecs = bpb.bpbBigFATsecs;
61246686Sbrian	bpb.bpbBigFATsecs = 0;
61343693Sbrian    }
61443693Sbrian    print_bpb(&bpb);
61543693Sbrian    if (!opt_N) {
61654912Sbrian	gettimeofday(&tv, NULL);
61746686Sbrian	now = tv.tv_sec;
61843693Sbrian	tm = localtime(&now);
61943693Sbrian	if (!(img = malloc(bpb.bpbBytesPerSec)))
62043693Sbrian	    err(1, NULL);
62143693Sbrian	dir = bpb.bpbResSectors + (bpb.bpbFATsecs ? bpb.bpbFATsecs :
62243693Sbrian				   bpb.bpbBigFATsecs) * bpb.bpbFATs;
62344123Sbrian	memset(&si_sa, 0, sizeof(si_sa));
62444106Sbrian	si_sa.sa_handler = infohandler;
62544123Sbrian	if (sigaction(SIGINFO, &si_sa, NULL) == -1)
62643693Sbrian		err(1, "sigaction SIGINFO");
62743313Sbrian	for (lsn = 0; lsn < dir + (fat == 32 ? bpb.bpbSecPerClust : rds); lsn++) {
62843693Sbrian	    if (got_siginfo) {
62943693Sbrian		    fprintf(stderr,"%s: writing sector %u of %u (%u%%)\n",
63043693Sbrian			fname, lsn,
63143693Sbrian			(dir + (fat == 32 ? bpb.bpbSecPerClust: rds)),
63243693Sbrian			(lsn * 100) / (dir +
63354912Sbrian			    (fat == 32 ? bpb.bpbSecPerClust: rds)));
63446686Sbrian		    got_siginfo = 0;
63543693Sbrian	    }
63643693Sbrian	    x = lsn;
63743693Sbrian	    if (opt_B &&
63843693Sbrian		fat == 32 && bpb.bpbBackup != MAXU16 &&
63943401Sbrian		bss <= bpb.bpbBackup && x >= bpb.bpbBackup) {
64036285Sbrian		x -= bpb.bpbBackup;
64143693Sbrian		if (!x && lseek(fd1, opt_ofs, SEEK_SET))
64243693Sbrian		    err(1, "%s", bname);
64343693Sbrian	    }
64443693Sbrian	    if (opt_B && x < bss) {
64544106Sbrian		if ((n = read(fd1, img, bpb.bpbBytesPerSec)) == -1)
64644106Sbrian		    err(1, "%s", bname);
64744106Sbrian		if ((unsigned)n != bpb.bpbBytesPerSec)
64844123Sbrian		    errx(1, "%s: can't read sector %u", bname, x);
64944106Sbrian	    } else
65044123Sbrian		memset(img, 0, bpb.bpbBytesPerSec);
65144123Sbrian	    if (!lsn ||
65244123Sbrian		(fat == 32 && bpb.bpbBackup != MAXU16 &&
65343693Sbrian		 lsn == bpb.bpbBackup)) {
65444106Sbrian		x1 = sizeof(struct bs);
65544106Sbrian		bsbpb = (struct bsbpb *)(img + x1);
65644123Sbrian		mk2(bsbpb->bpbBytesPerSec, bpb.bpbBytesPerSec);
65744106Sbrian		mk1(bsbpb->bpbSecPerClust, bpb.bpbSecPerClust);
65844123Sbrian		mk2(bsbpb->bpbResSectors, bpb.bpbResSectors);
65944123Sbrian		mk1(bsbpb->bpbFATs, bpb.bpbFATs);
66044123Sbrian		mk2(bsbpb->bpbRootDirEnts, bpb.bpbRootDirEnts);
66143693Sbrian		mk2(bsbpb->bpbSectors, bpb.bpbSectors);
66236285Sbrian		mk1(bsbpb->bpbMedia, bpb.bpbMedia);
66343693Sbrian		mk2(bsbpb->bpbFATsecs, bpb.bpbFATsecs);
66443693Sbrian		mk2(bsbpb->bpbSecPerTrack, bpb.bpbSecPerTrack);
66543693Sbrian		mk2(bsbpb->bpbHeads, bpb.bpbHeads);
66643693Sbrian		mk4(bsbpb->bpbHiddenSecs, bpb.bpbHiddenSecs);
66743693Sbrian		mk4(bsbpb->bpbHugeSectors, bpb.bpbHugeSectors);
66843693Sbrian		x1 += sizeof(struct bsbpb);
66943693Sbrian		if (fat == 32) {
67043693Sbrian		    bsxbpb = (struct bsxbpb *)(img + x1);
67143693Sbrian		    mk4(bsxbpb->bpbBigFATsecs, bpb.bpbBigFATsecs);
6726059Samurai		    mk2(bsxbpb->bpbExtFlags, 0);
6736059Samurai		    mk2(bsxbpb->bpbFSVers, 0);
67443693Sbrian		    mk4(bsxbpb->bpbRootClust, bpb.bpbRootClust);
67543693Sbrian		    mk2(bsxbpb->bpbFSInfo, bpb.bpbFSInfo);
67646686Sbrian		    mk2(bsxbpb->bpbBackup, bpb.bpbBackup);
67746686Sbrian		    x1 += sizeof(struct bsxbpb);
67846686Sbrian		}
67943888Sbrian		bsx = (struct bsx *)(img + x1);
68046686Sbrian		mk1(bsx->exBootSignature, 0x29);
68146686Sbrian		if (Iflag)
68244123Sbrian		    x = opt_I;
68344123Sbrian		else
68444123Sbrian		    x = (((u_int)(1 + tm->tm_mon) << 8 |
68544123Sbrian			  (u_int)tm->tm_mday) +
68643693Sbrian			 ((u_int)tm->tm_sec << 8 |
6876059Samurai			  (u_int)(tv.tv_usec / 10))) << 16 |
68843693Sbrian			((u_int)(1900 + tm->tm_year) +
68943693Sbrian			 ((u_int)tm->tm_hour << 8 |
69043693Sbrian			  (u_int)tm->tm_min));
69143693Sbrian		mk4(bsx->exVolumeID, x);
69246686Sbrian		mklabel(bsx->exVolumeLabel, opt_L ? opt_L : "NO_NAME");
69348817Sbrian		sprintf(buf, "FAT%u", fat);
69448817Sbrian		setstr(bsx->exFileSysType, buf, sizeof(bsx->exFileSysType));
69545907Sbrian		if (!opt_B) {
69645907Sbrian		    x1 += sizeof(struct bsx);
69746686Sbrian		    bs = (struct bs *)img;
69845907Sbrian		    mk1(bs->bsJump[0], 0xeb);
69945907Sbrian		    mk1(bs->bsJump[1], x1 - 2);
70045907Sbrian		    mk1(bs->bsJump[2], 0x90);
70143693Sbrian		    setstr(bs->bsOemName, opt_O ? opt_O : "BSD4.4  ",
70243693Sbrian			   sizeof(bs->bsOemName));
70343693Sbrian		    memcpy(img + x1, bootcode, sizeof(bootcode));
70446686Sbrian		    mk2(img + MINBPS - 2, DOSMAGIC);
70543693Sbrian		}
70644106Sbrian	    } else if (fat == 32 && bpb.bpbFSInfo != MAXU16 &&
70744123Sbrian		       (lsn == bpb.bpbFSInfo ||
70844106Sbrian			(bpb.bpbBackup != MAXU16 &&
70944106Sbrian			 lsn == bpb.bpbBackup + bpb.bpbFSInfo))) {
71044106Sbrian		mk4(img, 0x41615252);
71144106Sbrian		mk4(img + MINBPS - 28, 0x61417272);
71243693Sbrian		mk4(img + MINBPS - 24, 0xffffffff);
71344122Sbrian		mk4(img + MINBPS - 20, bpb.bpbRootClust);
71444122Sbrian		mk2(img + MINBPS - 2, DOSMAGIC);
71544106Sbrian	    } else if (lsn >= bpb.bpbResSectors && lsn < dir &&
71644106Sbrian		       !((lsn - bpb.bpbResSectors) %
71744106Sbrian			 (bpb.bpbFATsecs ? bpb.bpbFATsecs :
71844106Sbrian			  bpb.bpbBigFATsecs))) {
71944123Sbrian		mk1(img[0], bpb.bpbMedia);
72044123Sbrian		for (x = 1; x < fat * (fat == 32 ? 3 : 2) / 8; x++)
72144123Sbrian		    mk1(img[x], fat == 32 && x % 4 == 3 ? 0x0f : 0xff);
72244106Sbrian	    } else if (lsn == dir && opt_L) {
72345907Sbrian		de = (struct de *)img;
72444123Sbrian		mklabel(de->deName, opt_L);
72544123Sbrian		mk1(de->deAttributes, 050);
72644123Sbrian		x = (u_int)tm->tm_hour << 11 |
72744123Sbrian		    (u_int)tm->tm_min << 5 |
72844123Sbrian		    (u_int)tm->tm_sec >> 1;
72944106Sbrian		mk2(de->deMTime, x);
73043693Sbrian		x = (u_int)(tm->tm_year - 80) << 9 |
73144106Sbrian		    (u_int)(tm->tm_mon + 1) << 5 |
73244123Sbrian		    (u_int)tm->tm_mday;
73344123Sbrian		mk2(de->deMDate, x);
73444123Sbrian	    }
73544123Sbrian	    if ((n = write(fd, img, bpb.bpbBytesPerSec)) == -1)
73644123Sbrian		err(1, "%s", fname);
73744123Sbrian	    if ((unsigned)n != bpb.bpbBytesPerSec)
73844106Sbrian		errx(1, "%s: can't write sector %u", fname, lsn);
73944106Sbrian	}
74044106Sbrian    }
74143693Sbrian    return 0;
74243693Sbrian}
7436059Samurai
74443693Sbrian/*
74543693Sbrian * Exit with error if file system is mounted.
74643693Sbrian */
74743693Sbrianstatic void
74843693Sbriancheck_mounted(const char *fname, mode_t mode)
7496059Samurai{
75043693Sbrian    struct statfs *mp;
7516059Samurai    const char *s1, *s2;
7526059Samurai    size_t len;
75343693Sbrian    int n, r;
75443693Sbrian
75543693Sbrian    if (!(n = getmntinfo(&mp, MNT_NOWAIT)))
75643693Sbrian	err(1, "getmntinfo");
75743693Sbrian    len = strlen(_PATH_DEV);
75843693Sbrian    s1 = fname;
75943693Sbrian    if (!strncmp(s1, _PATH_DEV, len))
76043693Sbrian	s1 += len;
76143693Sbrian    r = S_ISCHR(mode) && s1 != fname && *s1 == 'r';
76243693Sbrian    for (; n--; mp++) {
76343693Sbrian	s2 = mp->f_mntfromname;
76443693Sbrian	if (!strncmp(s2, _PATH_DEV, len))
7656059Samurai	    s2 += len;
76643693Sbrian	if ((r && s2 != mp->f_mntfromname && !strcmp(s1 + 1, s2)) ||
76743693Sbrian	    !strcmp(s1, s2))
7686059Samurai	    errx(1, "%s is mounted on %s", fname, mp->f_mntonname);
76943693Sbrian    }
7706059Samurai}
77143693Sbrian
77254912Sbrian/*
77346686Sbrian * Get a standard format.
7746059Samurai */
775static void
776getstdfmt(const char *fmt, struct bpb *bpb)
777{
778    u_int x, i;
779
780    x = sizeof(stdfmt) / sizeof(stdfmt[0]);
781    for (i = 0; i < x && strcmp(fmt, stdfmt[i].name); i++);
782    if (i == x)
783	errx(1, "%s: unknown standard format", fmt);
784    *bpb = stdfmt[i].bpb;
785}
786
787/*
788 * Get disk slice, partition, and geometry information.
789 */
790static void
791getdiskinfo(int fd, const char *fname, const char *dtype, __unused int oflag,
792	    struct bpb *bpb)
793{
794    struct disklabel *lp, dlp;
795    struct fd_type type;
796    off_t ms, hs = 0;
797
798    lp = NULL;
799
800    /* If the user specified a disk type, try to use that */
801    if (dtype != NULL) {
802	lp = getdiskbyname(dtype);
803    }
804
805    /* Maybe it's a floppy drive */
806    if (lp == NULL) {
807	if (ioctl(fd, DIOCGMEDIASIZE, &ms) == -1) {
808	    struct stat st;
809
810	    if (fstat(fd, &st))
811		err(1, "Cannot get disk size");
812	    /* create a fake geometry for a file image */
813	    ms = st.st_size;
814	    dlp.d_secsize = 512;
815	    dlp.d_nsectors = 63;
816	    dlp.d_ntracks = 255;
817	    dlp.d_secperunit = ms / dlp.d_secsize;
818	    lp = &dlp;
819	} else if (ioctl(fd, FD_GTYPE, &type) != -1) {
820	    dlp.d_secsize = 128 << type.secsize;
821	    dlp.d_nsectors = type.sectrac;
822	    dlp.d_ntracks = type.heads;
823	    dlp.d_secperunit = ms / dlp.d_secsize;
824	    lp = &dlp;
825	}
826    }
827
828    /* Maybe it's a fixed drive */
829    if (lp == NULL) {
830	if (bpb->bpbBytesPerSec)
831	    dlp.d_secsize = bpb->bpbBytesPerSec;
832	if (ioctl(fd, DIOCGDINFO, &dlp) == -1) {
833	    if (bpb->bpbBytesPerSec == 0 && ioctl(fd, DIOCGSECTORSIZE,
834						  &dlp.d_secsize) == -1)
835		errx(1, "Cannot get sector size, %s", strerror(errno));
836
837	    dlp.d_secperunit = ms / dlp.d_secsize;
838
839	    if (bpb->bpbSecPerTrack == 0 && ioctl(fd, DIOCGFWSECTORS,
840						  &dlp.d_nsectors) == -1) {
841		warnx("Cannot get number of sectors per track, %s", strerror(errno));
842		dlp.d_nsectors = 63;
843	    }
844	    if (bpb->bpbHeads == 0 &&
845	        ioctl(fd, DIOCGFWHEADS, &dlp.d_ntracks) == -1) {
846		warnx("Cannot get number of heads, %s", strerror(errno));
847		if (dlp.d_secperunit <= 63*1*1024)
848		    dlp.d_ntracks = 1;
849		else if (dlp.d_secperunit <= 63*16*1024)
850		    dlp.d_ntracks = 16;
851		else
852		    dlp.d_ntracks = 255;
853	    }
854	}
855
856	hs = (ms / dlp.d_secsize) - dlp.d_secperunit;
857	lp = &dlp;
858    }
859
860    if (bpb->bpbBytesPerSec == 0)
861	bpb->bpbBytesPerSec = ckgeom(fname, lp->d_secsize, "bytes/sector");
862    if (bpb->bpbSecPerTrack == 0)
863	bpb->bpbSecPerTrack = ckgeom(fname, lp->d_nsectors, "sectors/track");
864    if (bpb->bpbHeads == 0)
865	bpb->bpbHeads = ckgeom(fname, lp->d_ntracks, "drive heads");
866    if (bpb->bpbHugeSectors == 0)
867	bpb->bpbHugeSectors = lp->d_secperunit;
868    if (bpb->bpbHiddenSecs == 0)
869	bpb->bpbHiddenSecs = hs;
870}
871
872/*
873 * Print out BPB values.
874 */
875static void
876print_bpb(struct bpb *bpb)
877{
878    printf("BytesPerSec=%u SecPerClust=%u ResSectors=%u FATs=%u",
879	   bpb->bpbBytesPerSec, bpb->bpbSecPerClust, bpb->bpbResSectors,
880	   bpb->bpbFATs);
881    if (bpb->bpbRootDirEnts)
882	printf(" RootDirEnts=%u", bpb->bpbRootDirEnts);
883    if (bpb->bpbSectors)
884	printf(" Sectors=%u", bpb->bpbSectors);
885    printf(" Media=%#x", bpb->bpbMedia);
886    if (bpb->bpbFATsecs)
887	printf(" FATsecs=%u", bpb->bpbFATsecs);
888    printf(" SecPerTrack=%u Heads=%u HiddenSecs=%u", bpb->bpbSecPerTrack,
889	   bpb->bpbHeads, bpb->bpbHiddenSecs);
890    if (bpb->bpbHugeSectors)
891	printf(" HugeSectors=%u", bpb->bpbHugeSectors);
892    if (!bpb->bpbFATsecs) {
893	printf(" FATsecs=%u RootCluster=%u", bpb->bpbBigFATsecs,
894	       bpb->bpbRootClust);
895	printf(" FSInfo=");
896	printf(bpb->bpbFSInfo == MAXU16 ? "%#x" : "%u", bpb->bpbFSInfo);
897	printf(" Backup=");
898	printf(bpb->bpbBackup == MAXU16 ? "%#x" : "%u", bpb->bpbBackup);
899    }
900    printf("\n");
901}
902
903/*
904 * Check a disk geometry value.
905 */
906static u_int
907ckgeom(const char *fname, u_int val, const char *msg)
908{
909    if (!val)
910	errx(1, "%s: no default %s", fname, msg);
911    if (val > MAXU16)
912	errx(1, "%s: illegal %s %d", fname, msg, val);
913    return val;
914}
915
916/*
917 * Convert and check a numeric option argument.
918 */
919static u_int
920argtou(const char *arg, u_int lo, u_int hi, const char *msg)
921{
922    char *s;
923    u_long x;
924
925    errno = 0;
926    x = strtoul(arg, &s, 0);
927    if (errno || !*arg || *s || x < lo || x > hi)
928	errx(1, "%s: bad %s", arg, msg);
929    return x;
930}
931
932/*
933 * Same for off_t, with optional skmgpP suffix
934 */
935static off_t
936argtooff(const char *arg, const char *msg)
937{
938    char *s;
939    off_t x;
940
941    errno = 0;
942    x = strtoll(arg, &s, 0);
943    /* allow at most one extra char */
944    if (errno || x < 0 || (s[0] && s[1]) )
945	errx(1, "%s: bad %s", arg, msg);
946    if (*s) {	/* the extra char is the multiplier */
947	switch (*s) {
948	default:
949	    errx(1, "%s: bad %s", arg, msg);
950	    /* notreached */
951
952	case 's':		/* sector */
953	case 'S':
954	    x <<= 9;		/* times 512 */
955	    break;
956
957	case 'k':		/* kilobyte */
958	case 'K':
959	    x <<= 10;		/* times 1024 */
960	    break;
961
962	case 'm':		/* megabyte */
963	case 'M':
964	    x <<= 20;		/* times 1024*1024 */
965	    break;
966
967	case 'g':		/* gigabyte */
968	case 'G':
969	    x <<= 30;		/* times 1024*1024*1024 */
970	    break;
971
972	case 'p':		/* partition start */
973	case 'P':
974	case 'l':		/* partition length */
975	case 'L':
976	    errx(1, "%s: not supported yet %s", arg, msg);
977	    /* notreached */
978	}
979    }
980    return x;
981}
982
983/*
984 * Check a volume label.
985 */
986static int
987oklabel(const char *src)
988{
989    int c, i;
990
991    for (i = 0; i <= 11; i++) {
992	c = (u_char)*src++;
993	if (c < ' ' + !i || strchr("\"*+,./:;<=>?[\\]|", c))
994	    break;
995    }
996    return i && !c;
997}
998
999/*
1000 * Make a volume label.
1001 */
1002static void
1003mklabel(u_int8_t *dest, const char *src)
1004{
1005    int c, i;
1006
1007    for (i = 0; i < 11; i++) {
1008	c = *src ? toupper(*src++) : ' ';
1009	*dest++ = !i && c == '\xe5' ? 5 : c;
1010    }
1011}
1012
1013/*
1014 * Copy string, padding with spaces.
1015 */
1016static void
1017setstr(u_int8_t *dest, const char *src, size_t len)
1018{
1019    while (len--)
1020	*dest++ = *src ? *src++ : ' ';
1021}
1022
1023/*
1024 * Print usage message.
1025 */
1026static void
1027usage(void)
1028{
1029	fprintf(stderr,
1030	    "usage: newfs_msdos [ -options ] special [disktype]\n"
1031	    "where the options are:\n"
1032	    "\t-@ create file system at specified offset\n"
1033	    "\t-B get bootstrap from file\n"
1034	    "\t-C create image file with specified size\n"
1035	    "\t-F FAT type (12, 16, or 32)\n"
1036	    "\t-I volume ID\n"
1037	    "\t-L volume label\n"
1038	    "\t-N don't create file system: just print out parameters\n"
1039	    "\t-O OEM string\n"
1040	    "\t-S bytes/sector\n"
1041	    "\t-a sectors/FAT\n"
1042	    "\t-b block size\n"
1043	    "\t-c sectors/cluster\n"
1044	    "\t-e root directory entries\n"
1045	    "\t-f standard format\n"
1046	    "\t-h drive heads\n"
1047	    "\t-i file system info sector\n"
1048	    "\t-k backup boot sector\n"
1049	    "\t-m media descriptor\n"
1050	    "\t-n number of FATs\n"
1051	    "\t-o hidden sectors\n"
1052	    "\t-r reserved sectors\n"
1053	    "\t-s file system size (sectors)\n"
1054	    "\t-u sectors/track\n");
1055	exit(1);
1056}
1057
1058static void
1059infohandler(int sig __unused)
1060{
1061
1062	got_siginfo = 1;
1063}
1064