1/*
2 * Copyright (c) 1998 Robert Nordier
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 *    notice, this list of conditions and the following disclaimer in
12 *    the documentation and/or other materials provided with the
13 *    distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS
16 * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
17 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY
19 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
21 * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
23 * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
24 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
25 * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28#ifndef lint
29static const char rcsid[] =
30  "$FreeBSD$";
31#endif /* not lint */
32
33#include <sys/param.h>
34#include <sys/fdcio.h>
35#include <sys/disk.h>
36#include <sys/disklabel.h>
37#include <sys/mount.h>
38#include <sys/stat.h>
39#include <sys/time.h>
40
41#include <ctype.h>
42#include <err.h>
43#include <errno.h>
44#include <fcntl.h>
45#include <inttypes.h>
46#include <paths.h>
47#include <signal.h>
48#include <stdio.h>
49#include <stdlib.h>
50#include <string.h>
51#include <time.h>
52#include <unistd.h>
53
54#define MAXU16	  0xffff	/* maximum unsigned 16-bit quantity */
55#define BPN	  4		/* bits per nibble */
56#define NPB	  2		/* nibbles per byte */
57
58#define DOSMAGIC  0xaa55	/* DOS magic number */
59#define MINBPS	  512		/* minimum bytes per sector */
60#define MAXSPC	  128		/* maximum sectors per cluster */
61#define MAXNFT	  16		/* maximum number of FATs */
62#define DEFBLK	  4096		/* default block size */
63#define DEFBLK16  2048		/* default block size FAT16 */
64#define DEFRDE	  512		/* default root directory entries */
65#define RESFTE	  2		/* reserved FAT entries */
66#define MINCLS12  1U		/* minimum FAT12 clusters */
67#define MINCLS16  0x1000U	/* minimum FAT16 clusters */
68#define MINCLS32  2U		/* minimum FAT32 clusters */
69#define MAXCLS12  0xfedU	/* maximum FAT12 clusters */
70#define MAXCLS16  0xfff5U	/* maximum FAT16 clusters */
71#define MAXCLS32  0xffffff5U	/* maximum FAT32 clusters */
72
73#define mincls(fat)  ((fat) == 12 ? MINCLS12 :	\
74		      (fat) == 16 ? MINCLS16 :	\
75				    MINCLS32)
76
77#define maxcls(fat)  ((fat) == 12 ? MAXCLS12 :	\
78		      (fat) == 16 ? MAXCLS16 :	\
79				    MAXCLS32)
80
81#define mk1(p, x)				\
82    (p) = (u_int8_t)(x)
83
84#define mk2(p, x)				\
85    (p)[0] = (u_int8_t)(x),			\
86    (p)[1] = (u_int8_t)((x) >> 010)
87
88#define mk4(p, x)				\
89    (p)[0] = (u_int8_t)(x),			\
90    (p)[1] = (u_int8_t)((x) >> 010),		\
91    (p)[2] = (u_int8_t)((x) >> 020),		\
92    (p)[3] = (u_int8_t)((x) >> 030)
93
94#define argto1(arg, lo, msg)  argtou(arg, lo, 0xff, msg)
95#define argto2(arg, lo, msg)  argtou(arg, lo, 0xffff, msg)
96#define argto4(arg, lo, msg)  argtou(arg, lo, 0xffffffff, msg)
97#define argtox(arg, lo, msg)  argtou(arg, lo, UINT_MAX, msg)
98
99struct bs {
100    u_int8_t bsJump[3];			/* bootstrap entry point */
101    u_int8_t bsOemName[8];		/* OEM name and version */
102} __packed;
103
104struct bsbpb {
105    u_int8_t bpbBytesPerSec[2];		/* bytes per sector */
106    u_int8_t bpbSecPerClust;		/* sectors per cluster */
107    u_int8_t bpbResSectors[2];		/* reserved sectors */
108    u_int8_t bpbFATs;			/* number of FATs */
109    u_int8_t bpbRootDirEnts[2];		/* root directory entries */
110    u_int8_t bpbSectors[2];		/* total sectors */
111    u_int8_t bpbMedia;			/* media descriptor */
112    u_int8_t bpbFATsecs[2];		/* sectors per FAT */
113    u_int8_t bpbSecPerTrack[2];		/* sectors per track */
114    u_int8_t bpbHeads[2];		/* drive heads */
115    u_int8_t bpbHiddenSecs[4];		/* hidden sectors */
116    u_int8_t bpbHugeSectors[4];		/* big total sectors */
117} __packed;
118
119struct bsxbpb {
120    u_int8_t bpbBigFATsecs[4];		/* big sectors per FAT */
121    u_int8_t bpbExtFlags[2];		/* FAT control flags */
122    u_int8_t bpbFSVers[2];		/* file system version */
123    u_int8_t bpbRootClust[4];		/* root directory start cluster */
124    u_int8_t bpbFSInfo[2];		/* file system info sector */
125    u_int8_t bpbBackup[2];		/* backup boot sector */
126    u_int8_t bpbReserved[12];		/* reserved */
127} __packed;
128
129struct bsx {
130    u_int8_t exDriveNumber;		/* drive number */
131    u_int8_t exReserved1;		/* reserved */
132    u_int8_t exBootSignature;		/* extended boot signature */
133    u_int8_t exVolumeID[4];		/* volume ID number */
134    u_int8_t exVolumeLabel[11]; 	/* volume label */
135    u_int8_t exFileSysType[8];		/* file system type */
136} __packed;
137
138struct de {
139    u_int8_t deName[11];		/* name and extension */
140    u_int8_t deAttributes;		/* attributes */
141    u_int8_t rsvd[10];			/* reserved */
142    u_int8_t deMTime[2];		/* last-modified time */
143    u_int8_t deMDate[2];		/* last-modified date */
144    u_int8_t deStartCluster[2];		/* starting cluster */
145    u_int8_t deFileSize[4];		/* size */
146} __packed;
147
148struct bpb {
149    u_int bpbBytesPerSec;		/* bytes per sector */
150    u_int bpbSecPerClust;		/* sectors per cluster */
151    u_int bpbResSectors;		/* reserved sectors */
152    u_int bpbFATs;			/* number of FATs */
153    u_int bpbRootDirEnts;		/* root directory entries */
154    u_int bpbSectors;			/* total sectors */
155    u_int bpbMedia;			/* media descriptor */
156    u_int bpbFATsecs;			/* sectors per FAT */
157    u_int bpbSecPerTrack;		/* sectors per track */
158    u_int bpbHeads;			/* drive heads */
159    u_int bpbHiddenSecs;		/* hidden sectors */
160    u_int bpbHugeSectors; 		/* big total sectors */
161    u_int bpbBigFATsecs; 		/* big sectors per FAT */
162    u_int bpbRootClust; 		/* root directory start cluster */
163    u_int bpbFSInfo; 			/* file system info sector */
164    u_int bpbBackup; 			/* backup boot sector */
165};
166
167#define BPBGAP 0, 0, 0, 0, 0, 0
168
169static struct {
170    const char *name;
171    struct bpb bpb;
172} const stdfmt[] = {
173    {"160",  {512, 1, 1, 2,  64,  320, 0xfe, 1,  8, 1, BPBGAP}},
174    {"180",  {512, 1, 1, 2,  64,  360, 0xfc, 2,  9, 1, BPBGAP}},
175    {"320",  {512, 2, 1, 2, 112,  640, 0xff, 1,  8, 2, BPBGAP}},
176    {"360",  {512, 2, 1, 2, 112,  720, 0xfd, 2,  9, 2, BPBGAP}},
177    {"640",  {512, 2, 1, 2, 112, 1280, 0xfb, 2,  8, 2, BPBGAP}},
178    {"720",  {512, 2, 1, 2, 112, 1440, 0xf9, 3,  9, 2, BPBGAP}},
179    {"1200", {512, 1, 1, 2, 224, 2400, 0xf9, 7, 15, 2, BPBGAP}},
180    {"1232", {1024,1, 1, 2, 192, 1232, 0xfe, 2,  8, 2, BPBGAP}},
181    {"1440", {512, 1, 1, 2, 224, 2880, 0xf0, 9, 18, 2, BPBGAP}},
182    {"2880", {512, 2, 1, 2, 240, 5760, 0xf0, 9, 36, 2, BPBGAP}}
183};
184
185static const u_int8_t bootcode[] = {
186    0xfa,			/* cli		    */
187    0x31, 0xc0, 		/* xor	   ax,ax    */
188    0x8e, 0xd0, 		/* mov	   ss,ax    */
189    0xbc, 0x00, 0x7c,		/* mov	   sp,7c00h */
190    0xfb,			/* sti		    */
191    0x8e, 0xd8, 		/* mov	   ds,ax    */
192    0xe8, 0x00, 0x00,		/* call    $ + 3    */
193    0x5e,			/* pop	   si	    */
194    0x83, 0xc6, 0x19,		/* add	   si,+19h  */
195    0xbb, 0x07, 0x00,		/* mov	   bx,0007h */
196    0xfc,			/* cld		    */
197    0xac,			/* lodsb	    */
198    0x84, 0xc0, 		/* test    al,al    */
199    0x74, 0x06, 		/* jz	   $ + 8    */
200    0xb4, 0x0e, 		/* mov	   ah,0eh   */
201    0xcd, 0x10, 		/* int	   10h	    */
202    0xeb, 0xf5, 		/* jmp	   $ - 9    */
203    0x30, 0xe4, 		/* xor	   ah,ah    */
204    0xcd, 0x16, 		/* int	   16h	    */
205    0xcd, 0x19, 		/* int	   19h	    */
206    0x0d, 0x0a,
207    'N', 'o', 'n', '-', 's', 'y', 's', 't',
208    'e', 'm', ' ', 'd', 'i', 's', 'k',
209    0x0d, 0x0a,
210    'P', 'r', 'e', 's', 's', ' ', 'a', 'n',
211    'y', ' ', 'k', 'e', 'y', ' ', 't', 'o',
212    ' ', 'r', 'e', 'b', 'o', 'o', 't',
213    0x0d, 0x0a,
214    0
215};
216
217static volatile sig_atomic_t got_siginfo;
218static void infohandler(int);
219
220static void check_mounted(const char *, mode_t);
221static void getstdfmt(const char *, struct bpb *);
222static void getdiskinfo(int, const char *, const char *, int,
223			struct bpb *);
224static void print_bpb(struct bpb *);
225static u_int ckgeom(const char *, u_int, const char *);
226static u_int argtou(const char *, u_int, u_int, const char *);
227static off_t argtooff(const char *, const char *);
228static int oklabel(const char *);
229static void mklabel(u_int8_t *, const char *);
230static void setstr(u_int8_t *, const char *, size_t);
231static void usage(void);
232
233/*
234 * Construct a FAT12, FAT16, or FAT32 file system.
235 */
236int
237main(int argc, char *argv[])
238{
239    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:";
240    const char *opt_B = NULL, *opt_L = NULL, *opt_O = NULL, *opt_f = NULL;
241    u_int opt_F = 0, opt_I = 0, opt_S = 0, opt_a = 0, opt_b = 0, opt_c = 0;
242    u_int opt_e = 0, opt_h = 0, opt_i = 0, opt_k = 0, opt_m = 0, opt_n = 0;
243    u_int opt_o = 0, opt_r = 0, opt_s = 0, opt_u = 0;
244    int opt_N = 0;
245    int Iflag = 0, mflag = 0, oflag = 0;
246    char buf[MAXPATHLEN];
247    struct sigaction si_sa;
248    struct stat sb;
249    struct timeval tv;
250    struct bpb bpb;
251    struct tm *tm;
252    struct bs *bs;
253    struct bsbpb *bsbpb;
254    struct bsxbpb *bsxbpb;
255    struct bsx *bsx;
256    struct de *de;
257    u_int8_t *img;
258    const char *fname, *dtype, *bname;
259    ssize_t n;
260    time_t now;
261    u_int fat, bss, rds, cls, dir, lsn, x, x1, x2;
262    int ch, fd, fd1;
263    off_t opt_create = 0, opt_ofs = 0;
264
265    while ((ch = getopt(argc, argv, opts)) != -1)
266	switch (ch) {
267	case '@':
268	    opt_ofs = argtooff(optarg, "offset");
269	    break;
270	case 'N':
271	    opt_N = 1;
272	    break;
273	case 'B':
274	    opt_B = optarg;
275	    break;
276	case 'C':
277	    opt_create = argtooff(optarg, "create size");
278	    break;
279	case 'F':
280	    if (strcmp(optarg, "12") &&
281		strcmp(optarg, "16") &&
282		strcmp(optarg, "32"))
283		errx(1, "%s: bad FAT type", optarg);
284	    opt_F = atoi(optarg);
285	    break;
286	case 'I':
287	    opt_I = argto4(optarg, 0, "volume ID");
288	    Iflag = 1;
289	    break;
290	case 'L':
291	    if (!oklabel(optarg))
292		errx(1, "%s: bad volume label", optarg);
293	    opt_L = optarg;
294	    break;
295	case 'O':
296	    if (strlen(optarg) > 8)
297		errx(1, "%s: bad OEM string", optarg);
298	    opt_O = optarg;
299	    break;
300	case 'S':
301	    opt_S = argto2(optarg, 1, "bytes/sector");
302	    break;
303	case 'a':
304	    opt_a = argto4(optarg, 1, "sectors/FAT");
305	    break;
306	case 'b':
307	    opt_b = argtox(optarg, 1, "block size");
308	    opt_c = 0;
309	    break;
310	case 'c':
311	    opt_c = argto1(optarg, 1, "sectors/cluster");
312	    opt_b = 0;
313	    break;
314	case 'e':
315	    opt_e = argto2(optarg, 1, "directory entries");
316	    break;
317	case 'f':
318	    opt_f = optarg;
319	    break;
320	case 'h':
321	    opt_h = argto2(optarg, 1, "drive heads");
322	    break;
323	case 'i':
324	    opt_i = argto2(optarg, 1, "info sector");
325	    break;
326	case 'k':
327	    opt_k = argto2(optarg, 1, "backup sector");
328	    break;
329	case 'm':
330	    opt_m = argto1(optarg, 0, "media descriptor");
331	    mflag = 1;
332	    break;
333	case 'n':
334	    opt_n = argto1(optarg, 1, "number of FATs");
335	    break;
336	case 'o':
337	    opt_o = argto4(optarg, 0, "hidden sectors");
338	    oflag = 1;
339	    break;
340	case 'r':
341	    opt_r = argto2(optarg, 1, "reserved sectors");
342	    break;
343	case 's':
344	    opt_s = argto4(optarg, 1, "file system size");
345	    break;
346	case 'u':
347	    opt_u = argto2(optarg, 1, "sectors/track");
348	    break;
349	default:
350	    usage();
351	}
352    argc -= optind;
353    argv += optind;
354    if (argc < 1 || argc > 2)
355	usage();
356    fname = *argv++;
357    if (!opt_create && !strchr(fname, '/')) {
358	snprintf(buf, sizeof(buf), "%s%s", _PATH_DEV, fname);
359	if (!(fname = strdup(buf)))
360	    err(1, NULL);
361    }
362    dtype = *argv;
363    if (opt_create) {
364	if (opt_N)
365	    errx(1, "create (-C) is incompatible with -N");
366	fd = open(fname, O_RDWR | O_CREAT | O_TRUNC, 0644);
367	if (fd == -1)
368	    errx(1, "failed to create %s", fname);
369	if (ftruncate(fd, opt_create))
370	    errx(1, "failed to initialize %jd bytes", (intmax_t)opt_create);
371    } else if ((fd = open(fname, opt_N ? O_RDONLY : O_RDWR)) == -1)
372	err(1, "%s", fname);
373    if (fstat(fd, &sb))
374	err(1, "%s", fname);
375    if (opt_create) {
376	if (!S_ISREG(sb.st_mode))
377	    warnx("warning, %s is not a regular file", fname);
378    } else {
379	if (!S_ISCHR(sb.st_mode))
380	    warnx("warning, %s is not a character device", fname);
381    }
382    if (!opt_N)
383	check_mounted(fname, sb.st_mode);
384    if (opt_ofs && opt_ofs != lseek(fd, opt_ofs, SEEK_SET))
385	errx(1, "cannot seek to %jd", (intmax_t)opt_ofs);
386    memset(&bpb, 0, sizeof(bpb));
387    if (opt_f) {
388	getstdfmt(opt_f, &bpb);
389	bpb.bpbHugeSectors = bpb.bpbSectors;
390	bpb.bpbSectors = 0;
391	bpb.bpbBigFATsecs = bpb.bpbFATsecs;
392	bpb.bpbFATsecs = 0;
393    }
394    if (opt_h)
395	bpb.bpbHeads = opt_h;
396    if (opt_u)
397	bpb.bpbSecPerTrack = opt_u;
398    if (opt_S)
399	bpb.bpbBytesPerSec = opt_S;
400    if (opt_s)
401	bpb.bpbHugeSectors = opt_s;
402    if (oflag)
403	bpb.bpbHiddenSecs = opt_o;
404    if (!(opt_f || (opt_h && opt_u && opt_S && opt_s && oflag))) {
405	off_t delta;
406	getdiskinfo(fd, fname, dtype, oflag, &bpb);
407	bpb.bpbHugeSectors -= (opt_ofs / bpb.bpbBytesPerSec);
408	delta = bpb.bpbHugeSectors % bpb.bpbSecPerTrack;
409	if (delta != 0) {
410	    warnx("trim %d sectors to adjust to a multiple of %d",
411		(int)delta, bpb.bpbSecPerTrack);
412	    bpb.bpbHugeSectors -= delta;
413	}
414	if (bpb.bpbSecPerClust == 0) {	/* set defaults */
415	    if (bpb.bpbHugeSectors <= 6000)	/* about 3MB -> 512 bytes */
416		bpb.bpbSecPerClust = 1;
417	    else if (bpb.bpbHugeSectors <= (1<<17)) /* 64M -> 4k */
418		bpb.bpbSecPerClust = 8;
419	    else if (bpb.bpbHugeSectors <= (1<<19)) /* 256M -> 8k */
420		bpb.bpbSecPerClust = 16;
421	    else if (bpb.bpbHugeSectors <= (1<<21)) /* 1G -> 16k */
422		bpb.bpbSecPerClust = 32;
423	    else
424		bpb.bpbSecPerClust = 64;		/* otherwise 32k */
425	}
426    }
427    if (!powerof2(bpb.bpbBytesPerSec))
428	errx(1, "bytes/sector (%u) is not a power of 2", bpb.bpbBytesPerSec);
429    if (bpb.bpbBytesPerSec < MINBPS)
430	errx(1, "bytes/sector (%u) is too small; minimum is %u",
431	     bpb.bpbBytesPerSec, MINBPS);
432    if (!(fat = opt_F)) {
433	if (opt_f)
434	    fat = 12;
435	else if (!opt_e && (opt_i || opt_k))
436	    fat = 32;
437    }
438    if ((fat == 32 && opt_e) || (fat != 32 && (opt_i || opt_k)))
439	errx(1, "-%c is not a legal FAT%s option",
440	     fat == 32 ? 'e' : opt_i ? 'i' : 'k',
441	     fat == 32 ? "32" : "12/16");
442    if (opt_f && fat == 32)
443	bpb.bpbRootDirEnts = 0;
444    if (opt_b) {
445	if (!powerof2(opt_b))
446	    errx(1, "block size (%u) is not a power of 2", opt_b);
447	if (opt_b < bpb.bpbBytesPerSec)
448	    errx(1, "block size (%u) is too small; minimum is %u",
449		 opt_b, bpb.bpbBytesPerSec);
450	if (opt_b > bpb.bpbBytesPerSec * MAXSPC)
451	    errx(1, "block size (%u) is too large; maximum is %u",
452		 opt_b, bpb.bpbBytesPerSec * MAXSPC);
453	bpb.bpbSecPerClust = opt_b / bpb.bpbBytesPerSec;
454    }
455    if (opt_c) {
456	if (!powerof2(opt_c))
457	    errx(1, "sectors/cluster (%u) is not a power of 2", opt_c);
458	bpb.bpbSecPerClust = opt_c;
459    }
460    if (opt_r)
461	bpb.bpbResSectors = opt_r;
462    if (opt_n) {
463	if (opt_n > MAXNFT)
464	    errx(1, "number of FATs (%u) is too large; maximum is %u",
465		 opt_n, MAXNFT);
466	bpb.bpbFATs = opt_n;
467    }
468    if (opt_e)
469	bpb.bpbRootDirEnts = opt_e;
470    if (mflag) {
471	if (opt_m < 0xf0)
472	    errx(1, "illegal media descriptor (%#x)", opt_m);
473	bpb.bpbMedia = opt_m;
474    }
475    if (opt_a)
476	bpb.bpbBigFATsecs = opt_a;
477    if (opt_i)
478	bpb.bpbFSInfo = opt_i;
479    if (opt_k)
480	bpb.bpbBackup = opt_k;
481    bss = 1;
482    bname = NULL;
483    fd1 = -1;
484    if (opt_B) {
485	bname = opt_B;
486	if (!strchr(bname, '/')) {
487	    snprintf(buf, sizeof(buf), "/boot/%s", bname);
488	    if (!(bname = strdup(buf)))
489		err(1, NULL);
490	}
491	if ((fd1 = open(bname, O_RDONLY)) == -1 || fstat(fd1, &sb))
492	    err(1, "%s", bname);
493	if (!S_ISREG(sb.st_mode) || sb.st_size % bpb.bpbBytesPerSec ||
494	    sb.st_size < bpb.bpbBytesPerSec ||
495	    sb.st_size > bpb.bpbBytesPerSec * MAXU16)
496	    errx(1, "%s: inappropriate file type or format", bname);
497	bss = sb.st_size / bpb.bpbBytesPerSec;
498    }
499    if (!bpb.bpbFATs)
500	bpb.bpbFATs = 2;
501    if (!fat) {
502	if (bpb.bpbHugeSectors < (bpb.bpbResSectors ? bpb.bpbResSectors : bss) +
503	    howmany((RESFTE + (bpb.bpbSecPerClust ? MINCLS16 : MAXCLS12 + 1)) *
504		(bpb.bpbSecPerClust ? 16 : 12) / BPN,
505		bpb.bpbBytesPerSec * NPB) *
506	    bpb.bpbFATs +
507	    howmany(bpb.bpbRootDirEnts ? bpb.bpbRootDirEnts : DEFRDE,
508		    bpb.bpbBytesPerSec / sizeof(struct de)) +
509	    (bpb.bpbSecPerClust ? MINCLS16 : MAXCLS12 + 1) *
510	    (bpb.bpbSecPerClust ? bpb.bpbSecPerClust :
511	     howmany(DEFBLK, bpb.bpbBytesPerSec)))
512	    fat = 12;
513	else if (bpb.bpbRootDirEnts || bpb.bpbHugeSectors <
514		 (bpb.bpbResSectors ? bpb.bpbResSectors : bss) +
515		 howmany((RESFTE + MAXCLS16) * 2, bpb.bpbBytesPerSec) *
516		 bpb.bpbFATs +
517		 howmany(DEFRDE, bpb.bpbBytesPerSec / sizeof(struct de)) +
518		 (MAXCLS16 + 1) *
519		 (bpb.bpbSecPerClust ? bpb.bpbSecPerClust :
520		  howmany(8192, bpb.bpbBytesPerSec)))
521	    fat = 16;
522	else
523	    fat = 32;
524    }
525    x = bss;
526    if (fat == 32) {
527	if (!bpb.bpbFSInfo) {
528	    if (x == MAXU16 || x == bpb.bpbBackup)
529		errx(1, "no room for info sector");
530	    bpb.bpbFSInfo = x;
531	}
532	if (bpb.bpbFSInfo != MAXU16 && x <= bpb.bpbFSInfo)
533	    x = bpb.bpbFSInfo + 1;
534	if (!bpb.bpbBackup) {
535	    if (x == MAXU16)
536		errx(1, "no room for backup sector");
537	    bpb.bpbBackup = x;
538	} else if (bpb.bpbBackup != MAXU16 && bpb.bpbBackup == bpb.bpbFSInfo)
539	    errx(1, "backup sector would overwrite info sector");
540	if (bpb.bpbBackup != MAXU16 && x <= bpb.bpbBackup)
541	    x = bpb.bpbBackup + 1;
542    }
543    if (!bpb.bpbResSectors)
544	bpb.bpbResSectors = fat == 32 ?
545	    MAX(x, MAX(16384 / bpb.bpbBytesPerSec, 4)) : x;
546    else if (bpb.bpbResSectors < x)
547	errx(1, "too few reserved sectors (need %d have %d)", x,
548	     bpb.bpbResSectors);
549    if (fat != 32 && !bpb.bpbRootDirEnts)
550	bpb.bpbRootDirEnts = DEFRDE;
551    rds = howmany(bpb.bpbRootDirEnts, bpb.bpbBytesPerSec / sizeof(struct de));
552    if (!bpb.bpbSecPerClust)
553	for (bpb.bpbSecPerClust = howmany(fat == 16 ? DEFBLK16 :
554					  DEFBLK, bpb.bpbBytesPerSec);
555	     bpb.bpbSecPerClust < MAXSPC &&
556	     bpb.bpbResSectors +
557	     howmany((RESFTE + maxcls(fat)) * (fat / BPN),
558		     bpb.bpbBytesPerSec * NPB) *
559	     bpb.bpbFATs +
560	     rds +
561	     (u_int64_t) (maxcls(fat) + 1) *
562	     bpb.bpbSecPerClust <= bpb.bpbHugeSectors;
563	     bpb.bpbSecPerClust <<= 1)
564	    continue;
565    if (fat != 32 && bpb.bpbBigFATsecs > MAXU16)
566	errx(1, "too many sectors/FAT for FAT12/16");
567    x1 = bpb.bpbResSectors + rds;
568    x = bpb.bpbBigFATsecs ? bpb.bpbBigFATsecs : 1;
569    if (x1 + (u_int64_t)x * bpb.bpbFATs > bpb.bpbHugeSectors)
570	errx(1, "meta data exceeds file system size");
571    x1 += x * bpb.bpbFATs;
572    x = (u_int64_t)(bpb.bpbHugeSectors - x1) * bpb.bpbBytesPerSec * NPB /
573	(bpb.bpbSecPerClust * bpb.bpbBytesPerSec * NPB + fat /
574	 BPN * bpb.bpbFATs);
575    x2 = howmany((RESFTE + MIN(x, maxcls(fat))) * (fat / BPN),
576		 bpb.bpbBytesPerSec * NPB);
577    if (!bpb.bpbBigFATsecs) {
578	bpb.bpbBigFATsecs = x2;
579	x1 += (bpb.bpbBigFATsecs - 1) * bpb.bpbFATs;
580    }
581    cls = (bpb.bpbHugeSectors - x1) / bpb.bpbSecPerClust;
582    x = (u_int64_t)bpb.bpbBigFATsecs * bpb.bpbBytesPerSec * NPB / (fat / BPN) -
583	RESFTE;
584    if (cls > x)
585	cls = x;
586    if (bpb.bpbBigFATsecs < x2)
587	warnx("warning: sectors/FAT limits file system to %u clusters",
588	      cls);
589    if (cls < mincls(fat))
590	errx(1, "%u clusters too few clusters for FAT%u, need %u", cls, fat,
591	    mincls(fat));
592    if (cls > maxcls(fat)) {
593	cls = maxcls(fat);
594	bpb.bpbHugeSectors = x1 + (cls + 1) * bpb.bpbSecPerClust - 1;
595	warnx("warning: FAT type limits file system to %u sectors",
596	      bpb.bpbHugeSectors);
597    }
598    printf("%s: %u sector%s in %u FAT%u cluster%s "
599	   "(%u bytes/cluster)\n", fname, cls * bpb.bpbSecPerClust,
600	   cls * bpb.bpbSecPerClust == 1 ? "" : "s", cls, fat,
601	   cls == 1 ? "" : "s", bpb.bpbBytesPerSec * bpb.bpbSecPerClust);
602    if (!bpb.bpbMedia)
603	bpb.bpbMedia = !bpb.bpbHiddenSecs ? 0xf0 : 0xf8;
604    if (fat == 32)
605	bpb.bpbRootClust = RESFTE;
606    if (bpb.bpbHiddenSecs + bpb.bpbHugeSectors <= MAXU16) {
607	bpb.bpbSectors = bpb.bpbHugeSectors;
608	bpb.bpbHugeSectors = 0;
609    }
610    if (fat != 32) {
611	bpb.bpbFATsecs = bpb.bpbBigFATsecs;
612	bpb.bpbBigFATsecs = 0;
613    }
614    print_bpb(&bpb);
615    if (!opt_N) {
616	gettimeofday(&tv, NULL);
617	now = tv.tv_sec;
618	tm = localtime(&now);
619	if (!(img = malloc(bpb.bpbBytesPerSec)))
620	    err(1, NULL);
621	dir = bpb.bpbResSectors + (bpb.bpbFATsecs ? bpb.bpbFATsecs :
622				   bpb.bpbBigFATsecs) * bpb.bpbFATs;
623	memset(&si_sa, 0, sizeof(si_sa));
624	si_sa.sa_handler = infohandler;
625	if (sigaction(SIGINFO, &si_sa, NULL) == -1)
626		err(1, "sigaction SIGINFO");
627	for (lsn = 0; lsn < dir + (fat == 32 ? bpb.bpbSecPerClust : rds); lsn++) {
628	    if (got_siginfo) {
629		    fprintf(stderr,"%s: writing sector %u of %u (%u%%)\n",
630			fname, lsn,
631			(dir + (fat == 32 ? bpb.bpbSecPerClust: rds)),
632			(lsn * 100) / (dir +
633			    (fat == 32 ? bpb.bpbSecPerClust: rds)));
634		    got_siginfo = 0;
635	    }
636	    x = lsn;
637	    if (opt_B &&
638		fat == 32 && bpb.bpbBackup != MAXU16 &&
639		bss <= bpb.bpbBackup && x >= bpb.bpbBackup) {
640		x -= bpb.bpbBackup;
641		if (!x && lseek(fd1, opt_ofs, SEEK_SET))
642		    err(1, "%s", bname);
643	    }
644	    if (opt_B && x < bss) {
645		if ((n = read(fd1, img, bpb.bpbBytesPerSec)) == -1)
646		    err(1, "%s", bname);
647		if ((unsigned)n != bpb.bpbBytesPerSec)
648		    errx(1, "%s: can't read sector %u", bname, x);
649	    } else
650		memset(img, 0, bpb.bpbBytesPerSec);
651	    if (!lsn ||
652		(fat == 32 && bpb.bpbBackup != MAXU16 &&
653		 lsn == bpb.bpbBackup)) {
654		x1 = sizeof(struct bs);
655		bsbpb = (struct bsbpb *)(img + x1);
656		mk2(bsbpb->bpbBytesPerSec, bpb.bpbBytesPerSec);
657		mk1(bsbpb->bpbSecPerClust, bpb.bpbSecPerClust);
658		mk2(bsbpb->bpbResSectors, bpb.bpbResSectors);
659		mk1(bsbpb->bpbFATs, bpb.bpbFATs);
660		mk2(bsbpb->bpbRootDirEnts, bpb.bpbRootDirEnts);
661		mk2(bsbpb->bpbSectors, bpb.bpbSectors);
662		mk1(bsbpb->bpbMedia, bpb.bpbMedia);
663		mk2(bsbpb->bpbFATsecs, bpb.bpbFATsecs);
664		mk2(bsbpb->bpbSecPerTrack, bpb.bpbSecPerTrack);
665		mk2(bsbpb->bpbHeads, bpb.bpbHeads);
666		mk4(bsbpb->bpbHiddenSecs, bpb.bpbHiddenSecs);
667		mk4(bsbpb->bpbHugeSectors, bpb.bpbHugeSectors);
668		x1 += sizeof(struct bsbpb);
669		if (fat == 32) {
670		    bsxbpb = (struct bsxbpb *)(img + x1);
671		    mk4(bsxbpb->bpbBigFATsecs, bpb.bpbBigFATsecs);
672		    mk2(bsxbpb->bpbExtFlags, 0);
673		    mk2(bsxbpb->bpbFSVers, 0);
674		    mk4(bsxbpb->bpbRootClust, bpb.bpbRootClust);
675		    mk2(bsxbpb->bpbFSInfo, bpb.bpbFSInfo);
676		    mk2(bsxbpb->bpbBackup, bpb.bpbBackup);
677		    x1 += sizeof(struct bsxbpb);
678		}
679		bsx = (struct bsx *)(img + x1);
680		mk1(bsx->exBootSignature, 0x29);
681		if (Iflag)
682		    x = opt_I;
683		else
684		    x = (((u_int)(1 + tm->tm_mon) << 8 |
685			  (u_int)tm->tm_mday) +
686			 ((u_int)tm->tm_sec << 8 |
687			  (u_int)(tv.tv_usec / 10))) << 16 |
688			((u_int)(1900 + tm->tm_year) +
689			 ((u_int)tm->tm_hour << 8 |
690			  (u_int)tm->tm_min));
691		mk4(bsx->exVolumeID, x);
692		mklabel(bsx->exVolumeLabel, opt_L ? opt_L : "NO_NAME");
693		sprintf(buf, "FAT%u", fat);
694		setstr(bsx->exFileSysType, buf, sizeof(bsx->exFileSysType));
695		if (!opt_B) {
696		    x1 += sizeof(struct bsx);
697		    bs = (struct bs *)img;
698		    mk1(bs->bsJump[0], 0xeb);
699		    mk1(bs->bsJump[1], x1 - 2);
700		    mk1(bs->bsJump[2], 0x90);
701		    setstr(bs->bsOemName, opt_O ? opt_O : "BSD4.4  ",
702			   sizeof(bs->bsOemName));
703		    memcpy(img + x1, bootcode, sizeof(bootcode));
704		    mk2(img + MINBPS - 2, DOSMAGIC);
705		}
706	    } else if (fat == 32 && bpb.bpbFSInfo != MAXU16 &&
707		       (lsn == bpb.bpbFSInfo ||
708			(bpb.bpbBackup != MAXU16 &&
709			 lsn == bpb.bpbBackup + bpb.bpbFSInfo))) {
710		mk4(img, 0x41615252);
711		mk4(img + MINBPS - 28, 0x61417272);
712		mk4(img + MINBPS - 24, 0xffffffff);
713		mk4(img + MINBPS - 20, bpb.bpbRootClust);
714		mk2(img + MINBPS - 2, DOSMAGIC);
715	    } else if (lsn >= bpb.bpbResSectors && lsn < dir &&
716		       !((lsn - bpb.bpbResSectors) %
717			 (bpb.bpbFATsecs ? bpb.bpbFATsecs :
718			  bpb.bpbBigFATsecs))) {
719		mk1(img[0], bpb.bpbMedia);
720		for (x = 1; x < fat * (fat == 32 ? 3 : 2) / 8; x++)
721		    mk1(img[x], fat == 32 && x % 4 == 3 ? 0x0f : 0xff);
722	    } else if (lsn == dir && opt_L) {
723		de = (struct de *)img;
724		mklabel(de->deName, opt_L);
725		mk1(de->deAttributes, 050);
726		x = (u_int)tm->tm_hour << 11 |
727		    (u_int)tm->tm_min << 5 |
728		    (u_int)tm->tm_sec >> 1;
729		mk2(de->deMTime, x);
730		x = (u_int)(tm->tm_year - 80) << 9 |
731		    (u_int)(tm->tm_mon + 1) << 5 |
732		    (u_int)tm->tm_mday;
733		mk2(de->deMDate, x);
734	    }
735	    if ((n = write(fd, img, bpb.bpbBytesPerSec)) == -1)
736		err(1, "%s", fname);
737	    if ((unsigned)n != bpb.bpbBytesPerSec)
738		errx(1, "%s: can't write sector %u", fname, lsn);
739	}
740    }
741    return 0;
742}
743
744/*
745 * Exit with error if file system is mounted.
746 */
747static void
748check_mounted(const char *fname, mode_t mode)
749{
750    struct statfs *mp;
751    const char *s1, *s2;
752    size_t len;
753    int n, r;
754
755    if (!(n = getmntinfo(&mp, MNT_NOWAIT)))
756	err(1, "getmntinfo");
757    len = strlen(_PATH_DEV);
758    s1 = fname;
759    if (!strncmp(s1, _PATH_DEV, len))
760	s1 += len;
761    r = S_ISCHR(mode) && s1 != fname && *s1 == 'r';
762    for (; n--; mp++) {
763	s2 = mp->f_mntfromname;
764	if (!strncmp(s2, _PATH_DEV, len))
765	    s2 += len;
766	if ((r && s2 != mp->f_mntfromname && !strcmp(s1 + 1, s2)) ||
767	    !strcmp(s1, s2))
768	    errx(1, "%s is mounted on %s", fname, mp->f_mntonname);
769    }
770}
771
772/*
773 * Get a standard format.
774 */
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		err(1, "cannot get sector size");
836
837	    dlp.d_secperunit = ms / dlp.d_secsize;
838
839	    if (bpb->bpbSecPerTrack == 0 && ioctl(fd, DIOCGFWSECTORS,
840						  &dlp.d_nsectors) == -1) {
841		warn("cannot get number of sectors per track");
842		dlp.d_nsectors = 63;
843	    }
844	    if (bpb->bpbHeads == 0 &&
845	        ioctl(fd, DIOCGFWHEADS, &dlp.d_ntracks) == -1) {
846		warn("cannot get number of heads");
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