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