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