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