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