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