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