newfs_msdos.c revision 190927
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 190927 2009-04-11 14:24:54Z 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	off_t pos;
360
361	if (opt_N)
362	    errx(1, "create (-C) is incompatible with -N");
363	fd = open(fname, O_RDWR | O_CREAT | O_TRUNC, 0644);
364	if (fd == -1)
365	    errx(1, "failed to create %s", fname);
366	pos = lseek(fd, opt_create - 1, SEEK_SET);
367	if (write(fd, "\0", 1) != 1)
368	    errx(1, "failed to initialize %jd bytes", (intmax_t)opt_create);
369	pos = lseek(fd, 0, SEEK_SET);
370    } else if ((fd = open(fname, opt_N ? O_RDONLY : O_RDWR)) == -1 ||
371	fstat(fd, &sb))
372	err(1, "%s", fname);
373    if (!opt_N)
374	check_mounted(fname, sb.st_mode);
375    if (!S_ISCHR(sb.st_mode))
376	warnx("warning, %s is not a character device", fname);
377    if (opt_ofs && opt_ofs != lseek(fd, opt_ofs, SEEK_SET))
378	errx(1, "cannot seek to %jd", (intmax_t)opt_ofs);
379    memset(&bpb, 0, sizeof(bpb));
380    if (opt_f) {
381	getstdfmt(opt_f, &bpb);
382	bpb.bsec = bpb.sec;
383	bpb.sec = 0;
384	bpb.bspf = bpb.spf;
385	bpb.spf = 0;
386    }
387    if (opt_h)
388	bpb.hds = opt_h;
389    if (opt_u)
390	bpb.spt = opt_u;
391    if (opt_S)
392	bpb.bps = opt_S;
393    if (opt_s)
394	bpb.bsec = opt_s;
395    if (oflag)
396	bpb.hid = opt_o;
397    if (!(opt_f || (opt_h && opt_u && opt_S && opt_s && oflag))) {
398	off_t delta;
399	getdiskinfo(fd, fname, dtype, oflag, &bpb);
400	bpb.bsec -= (opt_ofs / bpb.bps);
401	delta = bpb.bsec % bpb.spt;
402	if (delta != 0) {
403	    warnx("trim %d sectors to adjust to a multiple of %d",
404		(int)delta, bpb.spt);
405	    bpb.bsec -= delta;
406	}
407	if (bpb.spc == 0) {	/* set defaults */
408	    if (bpb.bsec <= 6000)	/* about 3MB -> 512 bytes */
409		bpb.spc = 1;
410	    else if (bpb.bsec <= (1<<17)) /* 64M -> 4k */
411		bpb.spc = 8;
412	    else if (bpb.bsec <= (1<<19)) /* 256M -> 8k */
413		bpb.spc = 16;
414	    else if (bpb.bsec <= (1<<21)) /* 1G -> 16k */
415		bpb.spc = 32;
416	    else
417		bpb.spc = 64;		/* otherwise 32k */
418	}
419    }
420    if (!powerof2(bpb.bps))
421	errx(1, "bytes/sector (%u) is not a power of 2", bpb.bps);
422    if (bpb.bps < MINBPS)
423	errx(1, "bytes/sector (%u) is too small; minimum is %u",
424	     bpb.bps, MINBPS);
425    if (!(fat = opt_F)) {
426	if (opt_f)
427	    fat = 12;
428	else if (!opt_e && (opt_i || opt_k))
429	    fat = 32;
430    }
431    if ((fat == 32 && opt_e) || (fat != 32 && (opt_i || opt_k)))
432	errx(1, "-%c is not a legal FAT%s option",
433	     fat == 32 ? 'e' : opt_i ? 'i' : 'k',
434	     fat == 32 ? "32" : "12/16");
435    if (opt_f && fat == 32)
436	bpb.rde = 0;
437    if (opt_b) {
438	if (!powerof2(opt_b))
439	    errx(1, "block size (%u) is not a power of 2", opt_b);
440	if (opt_b < bpb.bps)
441	    errx(1, "block size (%u) is too small; minimum is %u",
442		 opt_b, bpb.bps);
443	if (opt_b > bpb.bps * MAXSPC)
444	    errx(1, "block size (%u) is too large; maximum is %u",
445		 opt_b, bpb.bps * MAXSPC);
446	bpb.spc = opt_b / bpb.bps;
447    }
448    if (opt_c) {
449	if (!powerof2(opt_c))
450	    errx(1, "sectors/cluster (%u) is not a power of 2", opt_c);
451	bpb.spc = opt_c;
452    }
453    if (opt_r)
454	bpb.res = opt_r;
455    if (opt_n) {
456	if (opt_n > MAXNFT)
457	    errx(1, "number of FATs (%u) is too large; maximum is %u",
458		 opt_n, MAXNFT);
459	bpb.nft = opt_n;
460    }
461    if (opt_e)
462	bpb.rde = opt_e;
463    if (mflag) {
464	if (opt_m < 0xf0)
465	    errx(1, "illegal media descriptor (%#x)", opt_m);
466	bpb.mid = opt_m;
467    }
468    if (opt_a)
469	bpb.bspf = opt_a;
470    if (opt_i)
471	bpb.infs = opt_i;
472    if (opt_k)
473	bpb.bkbs = opt_k;
474    bss = 1;
475    bname = NULL;
476    fd1 = -1;
477    if (opt_B) {
478	bname = opt_B;
479	if (!strchr(bname, '/')) {
480	    snprintf(buf, sizeof(buf), "/boot/%s", bname);
481	    if (!(bname = strdup(buf)))
482		err(1, NULL);
483	}
484	if ((fd1 = open(bname, O_RDONLY)) == -1 || fstat(fd1, &sb))
485	    err(1, "%s", bname);
486	if (!S_ISREG(sb.st_mode) || sb.st_size % bpb.bps ||
487	    sb.st_size < bpb.bps || sb.st_size > bpb.bps * MAXU16)
488	    errx(1, "%s: inappropriate file type or format", bname);
489	bss = sb.st_size / bpb.bps;
490    }
491    if (!bpb.nft)
492	bpb.nft = 2;
493    if (!fat) {
494	if (bpb.bsec < (bpb.res ? bpb.res : bss) +
495	    howmany((RESFTE + (bpb.spc ? MINCLS16 : MAXCLS12 + 1)) *
496		    ((bpb.spc ? 16 : 12) / BPN), bpb.bps * NPB) *
497	    bpb.nft +
498	    howmany(bpb.rde ? bpb.rde : DEFRDE,
499		    bpb.bps / sizeof(struct de)) +
500	    (bpb.spc ? MINCLS16 : MAXCLS12 + 1) *
501	    (bpb.spc ? bpb.spc : howmany(DEFBLK, bpb.bps)))
502	    fat = 12;
503	else if (bpb.rde || bpb.bsec <
504		 (bpb.res ? bpb.res : bss) +
505		 howmany((RESFTE + MAXCLS16) * 2, bpb.bps) * bpb.nft +
506		 howmany(DEFRDE, bpb.bps / sizeof(struct de)) +
507		 (MAXCLS16 + 1) *
508		 (bpb.spc ? bpb.spc : howmany(8192, bpb.bps)))
509	    fat = 16;
510	else
511	    fat = 32;
512    }
513    x = bss;
514    if (fat == 32) {
515	if (!bpb.infs) {
516	    if (x == MAXU16 || x == bpb.bkbs)
517		errx(1, "no room for info sector");
518	    bpb.infs = x;
519	}
520	if (bpb.infs != MAXU16 && x <= bpb.infs)
521	    x = bpb.infs + 1;
522	if (!bpb.bkbs) {
523	    if (x == MAXU16)
524		errx(1, "no room for backup sector");
525	    bpb.bkbs = x;
526	} else if (bpb.bkbs != MAXU16 && bpb.bkbs == bpb.infs)
527	    errx(1, "backup sector would overwrite info sector");
528	if (bpb.bkbs != MAXU16 && x <= bpb.bkbs)
529	    x = bpb.bkbs + 1;
530    }
531    if (!bpb.res)
532	bpb.res = fat == 32 ? MAX(x, MAX(16384 / bpb.bps, 4)) : x;
533    else if (bpb.res < x)
534	errx(1, "too few reserved sectors");
535    if (fat != 32 && !bpb.rde)
536	bpb.rde = DEFRDE;
537    rds = howmany(bpb.rde, bpb.bps / sizeof(struct de));
538    if (!bpb.spc)
539	for (bpb.spc = howmany(fat == 16 ? DEFBLK16 : DEFBLK, bpb.bps);
540	     bpb.spc < MAXSPC &&
541	     bpb.res +
542	     howmany((RESFTE + maxcls(fat)) * (fat / BPN),
543		     bpb.bps * NPB) * bpb.nft +
544	     rds +
545	     (u_int64_t)(maxcls(fat) + 1) * bpb.spc <= bpb.bsec;
546	     bpb.spc <<= 1);
547    if (fat != 32 && bpb.bspf > MAXU16)
548	errx(1, "too many sectors/FAT for FAT12/16");
549    x1 = bpb.res + rds;
550    x = bpb.bspf ? bpb.bspf : 1;
551    if (x1 + (u_int64_t)x * bpb.nft > bpb.bsec)
552	errx(1, "meta data exceeds file system size");
553    x1 += x * bpb.nft;
554    x = (u_int64_t)(bpb.bsec - x1) * bpb.bps * NPB /
555	(bpb.spc * bpb.bps * NPB + fat / BPN * bpb.nft);
556    x2 = howmany((RESFTE + MIN(x, maxcls(fat))) * (fat / BPN),
557		 bpb.bps * NPB);
558    if (!bpb.bspf) {
559	bpb.bspf = x2;
560	x1 += (bpb.bspf - 1) * bpb.nft;
561    }
562    cls = (bpb.bsec - x1) / bpb.spc;
563    x = (u_int64_t)bpb.bspf * bpb.bps * NPB / (fat / BPN) - RESFTE;
564    if (cls > x)
565	cls = x;
566    if (bpb.bspf < x2)
567	warnx("warning: sectors/FAT limits file system to %u clusters",
568	      cls);
569    if (cls < mincls(fat))
570	errx(1, "%u clusters too few clusters for FAT%u, need %u", cls, fat,
571	    mincls(fat));
572    if (cls > maxcls(fat)) {
573	cls = maxcls(fat);
574	bpb.bsec = x1 + (cls + 1) * bpb.spc - 1;
575	warnx("warning: FAT type limits file system to %u sectors",
576	      bpb.bsec);
577    }
578    printf("%s: %u sector%s in %u FAT%u cluster%s "
579	   "(%u bytes/cluster)\n", fname, cls * bpb.spc,
580	   cls * bpb.spc == 1 ? "" : "s", cls, fat,
581	   cls == 1 ? "" : "s", bpb.bps * bpb.spc);
582    if (!bpb.mid)
583	bpb.mid = !bpb.hid ? 0xf0 : 0xf8;
584    if (fat == 32)
585	bpb.rdcl = RESFTE;
586    if (bpb.hid + bpb.bsec <= MAXU16) {
587	bpb.sec = bpb.bsec;
588	bpb.bsec = 0;
589    }
590    if (fat != 32) {
591	bpb.spf = bpb.bspf;
592	bpb.bspf = 0;
593    }
594    print_bpb(&bpb);
595    if (!opt_N) {
596	gettimeofday(&tv, NULL);
597	now = tv.tv_sec;
598	tm = localtime(&now);
599	if (!(img = malloc(bpb.bps)))
600	    err(1, NULL);
601	dir = bpb.res + (bpb.spf ? bpb.spf : bpb.bspf) * bpb.nft;
602	for (lsn = 0; lsn < dir + (fat == 32 ? bpb.spc : rds); lsn++) {
603	    x = lsn;
604	    if (opt_B &&
605		fat == 32 && bpb.bkbs != MAXU16 &&
606		bss <= bpb.bkbs && x >= bpb.bkbs) {
607		x -= bpb.bkbs;
608		if (!x && lseek(fd1, opt_ofs, SEEK_SET))
609		    err(1, "%s", bname);
610	    }
611	    if (opt_B && x < bss) {
612		if ((n = read(fd1, img, bpb.bps)) == -1)
613		    err(1, "%s", bname);
614		if ((unsigned)n != bpb.bps)
615		    errx(1, "%s: can't read sector %u", bname, x);
616	    } else
617		memset(img, 0, bpb.bps);
618	    if (!lsn ||
619	      (fat == 32 && bpb.bkbs != MAXU16 && lsn == bpb.bkbs)) {
620		x1 = sizeof(struct bs);
621		bsbpb = (struct bsbpb *)(img + x1);
622		mk2(bsbpb->bps, bpb.bps);
623		mk1(bsbpb->spc, bpb.spc);
624		mk2(bsbpb->res, bpb.res);
625		mk1(bsbpb->nft, bpb.nft);
626		mk2(bsbpb->rde, bpb.rde);
627		mk2(bsbpb->sec, bpb.sec);
628		mk1(bsbpb->mid, bpb.mid);
629		mk2(bsbpb->spf, bpb.spf);
630		mk2(bsbpb->spt, bpb.spt);
631		mk2(bsbpb->hds, bpb.hds);
632		mk4(bsbpb->hid, bpb.hid);
633		mk4(bsbpb->bsec, bpb.bsec);
634		x1 += sizeof(struct bsbpb);
635		if (fat == 32) {
636		    bsxbpb = (struct bsxbpb *)(img + x1);
637		    mk4(bsxbpb->bspf, bpb.bspf);
638		    mk2(bsxbpb->xflg, 0);
639		    mk2(bsxbpb->vers, 0);
640		    mk4(bsxbpb->rdcl, bpb.rdcl);
641		    mk2(bsxbpb->infs, bpb.infs);
642		    mk2(bsxbpb->bkbs, bpb.bkbs);
643		    x1 += sizeof(struct bsxbpb);
644		}
645		bsx = (struct bsx *)(img + x1);
646		mk1(bsx->sig, 0x29);
647		if (Iflag)
648		    x = opt_I;
649		else
650		    x = (((u_int)(1 + tm->tm_mon) << 8 |
651			  (u_int)tm->tm_mday) +
652			 ((u_int)tm->tm_sec << 8 |
653			  (u_int)(tv.tv_usec / 10))) << 16 |
654			((u_int)(1900 + tm->tm_year) +
655			 ((u_int)tm->tm_hour << 8 |
656			  (u_int)tm->tm_min));
657		mk4(bsx->volid, x);
658		mklabel(bsx->label, opt_L ? opt_L : "NO NAME");
659		sprintf(buf, "FAT%u", fat);
660		setstr(bsx->type, buf, sizeof(bsx->type));
661		if (!opt_B) {
662		    x1 += sizeof(struct bsx);
663		    bs = (struct bs *)img;
664		    mk1(bs->jmp[0], 0xeb);
665		    mk1(bs->jmp[1], x1 - 2);
666		    mk1(bs->jmp[2], 0x90);
667		    setstr(bs->oem, opt_O ? opt_O : "BSD  4.4",
668			   sizeof(bs->oem));
669		    memcpy(img + x1, bootcode, sizeof(bootcode));
670		    mk2(img + MINBPS - 2, DOSMAGIC);
671		}
672	    } else if (fat == 32 && bpb.infs != MAXU16 &&
673		       (lsn == bpb.infs ||
674			(bpb.bkbs != MAXU16 &&
675			 lsn == bpb.bkbs + bpb.infs))) {
676		mk4(img, 0x41615252);
677		mk4(img + MINBPS - 28, 0x61417272);
678		mk4(img + MINBPS - 24, 0xffffffff);
679		mk4(img + MINBPS - 20, bpb.rdcl);
680		mk2(img + MINBPS - 2, DOSMAGIC);
681	    } else if (lsn >= bpb.res && lsn < dir &&
682		       !((lsn - bpb.res) %
683			 (bpb.spf ? bpb.spf : bpb.bspf))) {
684		mk1(img[0], bpb.mid);
685		for (x = 1; x < fat * (fat == 32 ? 3 : 2) / 8; x++)
686		    mk1(img[x], fat == 32 && x % 4 == 3 ? 0x0f : 0xff);
687	    } else if (lsn == dir && opt_L) {
688		de = (struct de *)img;
689		mklabel(de->namext, opt_L);
690		mk1(de->attr, 050);
691		x = (u_int)tm->tm_hour << 11 |
692		    (u_int)tm->tm_min << 5 |
693		    (u_int)tm->tm_sec >> 1;
694		mk2(de->time, x);
695		x = (u_int)(tm->tm_year - 80) << 9 |
696		    (u_int)(tm->tm_mon + 1) << 5 |
697		    (u_int)tm->tm_mday;
698		mk2(de->date, x);
699	    }
700	    if ((n = write(fd, img, bpb.bps)) == -1)
701		err(1, "%s", fname);
702	    if ((unsigned)n != bpb.bps)
703		errx(1, "%s: can't write sector %u", fname, lsn);
704	}
705    }
706    return 0;
707}
708
709/*
710 * Exit with error if file system is mounted.
711 */
712static void
713check_mounted(const char *fname, mode_t mode)
714{
715    struct statfs *mp;
716    const char *s1, *s2;
717    size_t len;
718    int n, r;
719
720    if (!(n = getmntinfo(&mp, MNT_NOWAIT)))
721	err(1, "getmntinfo");
722    len = strlen(_PATH_DEV);
723    s1 = fname;
724    if (!strncmp(s1, _PATH_DEV, len))
725	s1 += len;
726    r = S_ISCHR(mode) && s1 != fname && *s1 == 'r';
727    for (; n--; mp++) {
728	s2 = mp->f_mntfromname;
729	if (!strncmp(s2, _PATH_DEV, len))
730	    s2 += len;
731	if ((r && s2 != mp->f_mntfromname && !strcmp(s1 + 1, s2)) ||
732	    !strcmp(s1, s2))
733	    errx(1, "%s is mounted on %s", fname, mp->f_mntonname);
734    }
735}
736
737/*
738 * Get a standard format.
739 */
740static void
741getstdfmt(const char *fmt, struct bpb *bpb)
742{
743    u_int x, i;
744
745    x = sizeof(stdfmt) / sizeof(stdfmt[0]);
746    for (i = 0; i < x && strcmp(fmt, stdfmt[i].name); i++);
747    if (i == x)
748	errx(1, "%s: unknown standard format", fmt);
749    *bpb = stdfmt[i].bpb;
750}
751
752/*
753 * Get disk slice, partition, and geometry information.
754 */
755static void
756getdiskinfo(int fd, const char *fname, const char *dtype, __unused int oflag,
757	    struct bpb *bpb)
758{
759    struct disklabel *lp, dlp;
760    struct fd_type type;
761    off_t ms, hs = 0;
762
763    lp = NULL;
764
765    /* If the user specified a disk type, try to use that */
766    if (dtype != NULL) {
767	lp = getdiskbyname(dtype);
768    }
769
770    /* Maybe it's a floppy drive */
771    if (lp == NULL) {
772	if (ioctl(fd, DIOCGMEDIASIZE, &ms) == -1) {
773	    struct stat st;
774
775	    if (fstat(fd, &st))
776		err(1, "Cannot get disk size");
777	    /* create a fake geometry for a file image */
778	    ms = st.st_size;
779	    dlp.d_secsize = 512;
780	    dlp.d_nsectors = 63;
781	    dlp.d_ntracks = 255;
782	    dlp.d_secperunit = ms / dlp.d_secsize;
783	    lp = &dlp;
784	} else if (ioctl(fd, FD_GTYPE, &type) != -1) {
785	    dlp.d_secsize = 128 << type.secsize;
786	    dlp.d_nsectors = type.sectrac;
787	    dlp.d_ntracks = type.heads;
788	    dlp.d_secperunit = ms / dlp.d_secsize;
789	    lp = &dlp;
790	}
791    }
792
793    /* Maybe it's a fixed drive */
794    if (lp == NULL) {
795	if (ioctl(fd, DIOCGDINFO, &dlp) == -1) {
796	    if (bpb->bps == 0 && ioctl(fd, DIOCGSECTORSIZE, &dlp.d_secsize) == -1)
797		errx(1, "Cannot get sector size, %s", strerror(errno));
798
799	    /* XXX Should we use bpb->bps if it's set? */
800	    dlp.d_secperunit = ms / dlp.d_secsize;
801
802	    if (bpb->spt == 0 && ioctl(fd, DIOCGFWSECTORS, &dlp.d_nsectors) == -1) {
803		warnx("Cannot get number of sectors per track, %s", strerror(errno));
804		dlp.d_nsectors = 63;
805	    }
806	    if (bpb->hds == 0 && ioctl(fd, DIOCGFWHEADS, &dlp.d_ntracks) == -1) {
807		warnx("Cannot get number of heads, %s", strerror(errno));
808		if (dlp.d_secperunit <= 63*1*1024)
809		    dlp.d_ntracks = 1;
810		else if (dlp.d_secperunit <= 63*16*1024)
811		    dlp.d_ntracks = 16;
812		else
813		    dlp.d_ntracks = 255;
814	    }
815	}
816
817	hs = (ms / dlp.d_secsize) - dlp.d_secperunit;
818	lp = &dlp;
819    }
820
821    if (bpb->bps == 0)
822	bpb->bps = ckgeom(fname, lp->d_secsize, "bytes/sector");
823    if (bpb->spt == 0)
824	bpb->spt = ckgeom(fname, lp->d_nsectors, "sectors/track");
825    if (bpb->hds == 0)
826	bpb->hds = ckgeom(fname, lp->d_ntracks, "drive heads");
827    if (bpb->bsec == 0)
828	bpb->bsec = lp->d_secperunit;
829    if (bpb->hid == 0)
830	bpb->hid = hs;
831}
832
833/*
834 * Print out BPB values.
835 */
836static void
837print_bpb(struct bpb *bpb)
838{
839    printf("bps=%u spc=%u res=%u nft=%u", bpb->bps, bpb->spc, bpb->res,
840	   bpb->nft);
841    if (bpb->rde)
842	printf(" rde=%u", bpb->rde);
843    if (bpb->sec)
844	printf(" sec=%u", bpb->sec);
845    printf(" mid=%#x", bpb->mid);
846    if (bpb->spf)
847	printf(" spf=%u", bpb->spf);
848    printf(" spt=%u hds=%u hid=%u", bpb->spt, bpb->hds, bpb->hid);
849    if (bpb->bsec)
850	printf(" bsec=%u", bpb->bsec);
851    if (!bpb->spf) {
852	printf(" bspf=%u rdcl=%u", bpb->bspf, bpb->rdcl);
853	printf(" infs=");
854	printf(bpb->infs == MAXU16 ? "%#x" : "%u", bpb->infs);
855	printf(" bkbs=");
856	printf(bpb->bkbs == MAXU16 ? "%#x" : "%u", bpb->bkbs);
857    }
858    printf("\n");
859}
860
861/*
862 * Check a disk geometry value.
863 */
864static u_int
865ckgeom(const char *fname, u_int val, const char *msg)
866{
867    if (!val)
868	errx(1, "%s: no default %s", fname, msg);
869    if (val > MAXU16)
870	errx(1, "%s: illegal %s %d", fname, msg, val);
871    return val;
872}
873
874/*
875 * Convert and check a numeric option argument.
876 */
877static u_int
878argtou(const char *arg, u_int lo, u_int hi, const char *msg)
879{
880    char *s;
881    u_long x;
882
883    errno = 0;
884    x = strtoul(arg, &s, 0);
885    if (errno || !*arg || *s || x < lo || x > hi)
886	errx(1, "%s: bad %s", arg, msg);
887    return x;
888}
889
890/*
891 * Same for off_t, with optional skmgpP suffix
892 */
893static off_t
894argtooff(const char *arg, const char *msg)
895{
896    char *s;
897    off_t x;
898
899    x = strtoll(arg, &s, 0);
900    /* allow at most one extra char */
901    if (errno || x < 0 || (s[0] && s[1]) )
902	errx(1, "%s: bad %s", arg, msg);
903    if (*s) {	/* the extra char is the multiplier */
904	switch (*s) {
905	default:
906	    errx(1, "%s: bad %s", arg, msg);
907	    /* notreached */
908
909	case 's':	/* sector */
910	case 'S':
911	    x <<= 9;	/* times 512 */
912	    break;
913
914	case 'k':	/* kilobyte */
915	case 'K':
916	    x <<= 10;	/* times 1024 */
917	    break;
918
919	case 'm':	/* megabyte */
920	case 'M':
921	    x <<= 20;	/* times 1024*1024 */
922	    break;
923
924	case 'g':	/* gigabyte */
925	case 'G':
926	    x <<= 30;	/* times 1024*1024*1024 */
927	    break;
928
929	case 'p':	/* partition start */
930	case 'P':	/* partition start */
931	case 'l':	/* partition length */
932	case 'L':	/* partition length */
933	    errx(1, "%s: not supported yet %s", arg, msg);
934	    /* notreached */
935	}
936    }
937    return x;
938}
939
940/*
941 * Check a volume label.
942 */
943static int
944oklabel(const char *src)
945{
946    int c, i;
947
948    for (i = 0; i <= 11; i++) {
949	c = (u_char)*src++;
950	if (c < ' ' + !i || strchr("\"*+,./:;<=>?[\\]|", c))
951	    break;
952    }
953    return i && !c;
954}
955
956/*
957 * Make a volume label.
958 */
959static void
960mklabel(u_int8_t *dest, const char *src)
961{
962    int c, i;
963
964    for (i = 0; i < 11; i++) {
965	c = *src ? toupper(*src++) : ' ';
966	*dest++ = !i && c == '\xe5' ? 5 : c;
967    }
968}
969
970/*
971 * Copy string, padding with spaces.
972 */
973static void
974setstr(u_int8_t *dest, const char *src, size_t len)
975{
976    while (len--)
977	*dest++ = *src ? *src++ : ' ';
978}
979
980/*
981 * Print usage message.
982 */
983static void
984usage(void)
985{
986	fprintf(stderr,
987	    "usage: newfs_msdos [ -options ] special [disktype]\n"
988	    "where the options are:\n"
989	    "\t-@ create file system at specified offset\n"
990	    "\t-B get bootstrap from file\n"
991	    "\t-C create image file with specified size\n"
992	    "\t-F FAT type (12, 16, or 32)\n"
993	    "\t-I volume ID\n"
994	    "\t-L volume label\n"
995	    "\t-N don't create file system: just print out parameters\n"
996	    "\t-O OEM string\n"
997	    "\t-S bytes/sector\n"
998	    "\t-a sectors/FAT\n"
999	    "\t-b block size\n"
1000	    "\t-c sectors/cluster\n"
1001	    "\t-e root directory entries\n"
1002	    "\t-f standard format\n"
1003	    "\t-h drive heads\n"
1004	    "\t-i file system info sector\n"
1005	    "\t-k backup boot sector\n"
1006	    "\t-m media descriptor\n"
1007	    "\t-n number of FATs\n"
1008	    "\t-o hidden sectors\n"
1009	    "\t-r reserved sectors\n"
1010	    "\t-s file system size (sectors)\n"
1011	    "\t-u sectors/track\n");
1012	exit(1);
1013}
1014