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