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