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