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