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