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