GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: usr.sbin/makefs/msdos/mkfs_msdos.c Lines: 0 433 0.0 %
Date: 2017-11-07 Branches: 0 408 0.0 %

Line Branch Exec Source
1
/*	$OpenBSD: mkfs_msdos.c,v 1.4 2017/03/28 00:08:39 jsg Exp $	*/
2
/*	$NetBSD: mkfs_msdos.c,v 1.10 2016/04/03 11:00:13 mlelstv Exp $	*/
3
4
/*
5
 * Copyright (c) 1998 Robert Nordier
6
 * All rights reserved.
7
 *
8
 * Redistribution and use in source and binary forms, with or without
9
 * modification, are permitted provided that the following conditions
10
 * are met:
11
 * 1. Redistributions of source code must retain the above copyright
12
 *    notice, this list of conditions and the following disclaimer.
13
 * 2. Redistributions in binary form must reproduce the above copyright
14
 *    notice, this list of conditions and the following disclaimer in
15
 *    the documentation and/or other materials provided with the
16
 *    distribution.
17
 *
18
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS
19
 * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY
22
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
24
 * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
26
 * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
27
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
28
 * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29
 */
30
31
#include <sys/param.h>
32
#include <sys/stat.h>
33
#include <sys/time.h>
34
35
#include <ctype.h>
36
#include <err.h>
37
#include <errno.h>
38
#include <fcntl.h>
39
#include <paths.h>
40
#include <stdio.h>
41
#include <stdint.h>
42
#include <stdlib.h>
43
#include <string.h>
44
#include <time.h>
45
#include <unistd.h>
46
#include <signal.h>
47
48
#include <util.h>
49
#include <disktab.h>
50
51
#include "msdos/mkfs_msdos.h"
52
53
#define MAXU16	  0xffff	/* maximum unsigned 16-bit quantity */
54
#define BPN	  4		/* bits per nibble */
55
#define NPB	  2		/* nibbles per byte */
56
57
#define DOSMAGIC  0xaa55	/* DOS magic number */
58
#define MINBPS	  512		/* minimum bytes per sector */
59
#define MAXSPC	  128		/* maximum sectors per cluster */
60
#define MAXNFT	  16		/* maximum number of FATs */
61
#define DEFBLK	  4096		/* default block size */
62
#define DEFBLK16  2048		/* default block size FAT16 */
63
#define DEFRDE	  512		/* default root directory entries */
64
#define RESFTE	  2		/* reserved FAT entries */
65
#define MINCLS12  1		/* minimum FAT12 clusters */
66
#define MINCLS16  0xff5		/* minimum FAT16 clusters */
67
#define MINCLS32  0xfff5	/* minimum FAT32 clusters */
68
#define MAXCLS12  0xff4		/* maximum FAT12 clusters */
69
#define MAXCLS16  0xfff4	/* maximum FAT16 clusters */
70
#define MAXCLS32  0xffffff4	/* maximum FAT32 clusters */
71
72
#define mincls(fat_type)  ((fat_type) == 12 ? MINCLS12 :	\
73
		      (fat_type) == 16 ? MINCLS16 :	\
74
				    MINCLS32)
75
76
#define maxcls(fat_type)  ((fat_type) == 12 ? MAXCLS12 :	\
77
		      (fat_type) == 16 ? MAXCLS16 :	\
78
				    MAXCLS32)
79
80
#define mk1(p, x)				\
81
    (p) = (u_int8_t)(x)
82
83
#define mk2(p, x)				\
84
    (p)[0] = (u_int8_t)(x),			\
85
    (p)[1] = (u_int8_t)((x) >> 010)
86
87
#define mk4(p, x)				\
88
    (p)[0] = (u_int8_t)(x),			\
89
    (p)[1] = (u_int8_t)((x) >> 010),		\
90
    (p)[2] = (u_int8_t)((x) >> 020),		\
91
    (p)[3] = (u_int8_t)((x) >> 030)
92
93
struct bs {
94
    u_int8_t jmp[3];		/* bootstrap entry point */
95
    u_int8_t oem[8];		/* OEM name and version */
96
};
97
98
struct bsbpb {
99
    u_int8_t bps[2];		/* bytes per sector */
100
    u_int8_t spc;		/* sectors per cluster */
101
    u_int8_t res[2];		/* reserved sectors */
102
    u_int8_t nft;		/* number of FATs */
103
    u_int8_t rde[2];		/* root directory entries */
104
    u_int8_t sec[2];		/* total sectors */
105
    u_int8_t mid;		/* media descriptor */
106
    u_int8_t spf[2];		/* sectors per FAT */
107
    u_int8_t spt[2];		/* sectors per track */
108
    u_int8_t hds[2];		/* drive heads */
109
    u_int8_t hid[4];		/* hidden sectors */
110
    u_int8_t bsec[4];		/* big total sectors */
111
};
112
113
struct bsxbpb {
114
    u_int8_t bspf[4];		/* big sectors per FAT */
115
    u_int8_t xflg[2];		/* FAT control flags */
116
    u_int8_t vers[2];		/* file system version */
117
    u_int8_t rdcl[4];		/* root directory start cluster */
118
    u_int8_t infs[2];		/* file system info sector */
119
    u_int8_t bkbs[2];		/* backup boot sector */
120
    u_int8_t rsvd[12];		/* reserved */
121
};
122
123
struct bsx {
124
    u_int8_t drv;		/* drive number */
125
    u_int8_t rsvd;		/* reserved */
126
    u_int8_t sig;		/* extended boot signature */
127
    u_int8_t volid[4];		/* volume ID number */
128
    u_int8_t label[11];		/* volume label */
129
    u_int8_t type[8];		/* file system type */
130
};
131
132
struct de {
133
    u_int8_t namext[11];	/* name and extension */
134
    u_int8_t attr;		/* attributes */
135
    u_int8_t rsvd[10];		/* reserved */
136
    u_int8_t time[2];		/* creation time */
137
    u_int8_t date[2];		/* creation date */
138
    u_int8_t clus[2];		/* starting cluster */
139
    u_int8_t size[4];		/* size */
140
};
141
142
struct bpb {
143
    u_int bps;			/* bytes per sector */
144
    u_int spc;			/* sectors per cluster */
145
    u_int res;			/* reserved sectors */
146
    u_int nft;			/* number of FATs */
147
    u_int rde;			/* root directory entries */
148
    u_int sec;			/* total sectors */
149
    u_int mid;			/* media descriptor */
150
    u_int spf;			/* sectors per FAT */
151
    u_int spt;			/* sectors per track */
152
    u_int hds;			/* drive heads */
153
    u_int hid;			/* hidden sectors */
154
    u_int bsec;			/* big total sectors */
155
    u_int bspf;			/* big sectors per FAT */
156
    u_int rdcl;			/* root directory start cluster */
157
    u_int infs;			/* file system info sector */
158
    u_int bkbs;			/* backup boot sector */
159
};
160
161
#define INIT(a, b, c, d, e, f, g, h, i, j) \
162
    { .bps = a, .spc = b, .res = c, .nft = d, .rde = e, \
163
      .sec = f, .mid = g, .spf = h, .spt = i, .hds = j, }
164
static struct {
165
    const char *name;
166
    struct bpb bpb;
167
} stdfmt[] = {
168
    {"160",  INIT(512, 1, 1, 2,  64,  320, 0xfe, 1,  8, 1)},
169
    {"180",  INIT(512, 1, 1, 2,  64,  360, 0xfc, 2,  9, 1)},
170
    {"320",  INIT(512, 2, 1, 2, 112,  640, 0xff, 1,  8, 2)},
171
    {"360",  INIT(512, 2, 1, 2, 112,  720, 0xfd, 2,  9, 2)},
172
    {"640",  INIT(512, 2, 1, 2, 112, 1280, 0xfb, 2,  8, 2)},
173
    {"720",  INIT(512, 2, 1, 2, 112, 1440, 0xf9, 3,  9, 2)},
174
    {"1200", INIT(512, 1, 1, 2, 224, 2400, 0xf9, 7, 15, 2)},
175
    {"1232", INIT(1024,1, 1, 2, 192, 1232, 0xfe, 2,  8, 2)},
176
    {"1440", INIT(512, 1, 1, 2, 224, 2880, 0xf0, 9, 18, 2)},
177
    {"2880", INIT(512, 2, 1, 2, 240, 5760, 0xf0, 9, 36, 2)}
178
};
179
180
static u_int8_t bootcode[] = {
181
    0xfa,			/* cli		    */
182
    0x31, 0xc0,			/* xor	   ax,ax    */
183
    0x8e, 0xd0,			/* mov	   ss,ax    */
184
    0xbc, 0x00, 0x7c,		/* mov	   sp,7c00h */
185
    0xfb,			/* sti		    */
186
    0x8e, 0xd8,			/* mov	   ds,ax    */
187
    0xe8, 0x00, 0x00,		/* call    $ + 3    */
188
    0x5e,			/* pop	   si	    */
189
    0x83, 0xc6, 0x19,		/* add	   si,+19h  */
190
    0xbb, 0x07, 0x00,		/* mov	   bx,0007h */
191
    0xfc,			/* cld		    */
192
    0xac,			/* lodsb	    */
193
    0x84, 0xc0,			/* test    al,al    */
194
    0x74, 0x06,			/* jz	   $ + 8    */
195
    0xb4, 0x0e,			/* mov	   ah,0eh   */
196
    0xcd, 0x10,			/* int	   10h	    */
197
    0xeb, 0xf5,			/* jmp	   $ - 9    */
198
    0x30, 0xe4,			/* xor	   ah,ah    */
199
    0xcd, 0x16,			/* int	   16h	    */
200
    0xcd, 0x19,			/* int	   19h	    */
201
    0x0d, 0x0a,
202
    'N', 'o', 'n', '-', 's', 'y', 's', 't',
203
    'e', 'm', ' ', 'd', 'i', 's', 'k',
204
    0x0d, 0x0a,
205
    'P', 'r', 'e', 's', 's', ' ', 'a', 'n',
206
    'y', ' ', 'k', 'e', 'y', ' ', 't', 'o',
207
    ' ', 'r', 'e', 'b', 'o', 'o', 't',
208
    0x0d, 0x0a,
209
    0
210
};
211
212
static int got_siginfo = 0; /* received a SIGINFO */
213
214
static int getstdfmt(const char *, struct bpb *);
215
static int getbpbinfo(int, const char *, const char *, int, struct bpb *, int);
216
static void print_bpb(struct bpb *);
217
static int ckgeom(const char *, u_int, const char *);
218
static int oklabel(const char *);
219
static void mklabel(u_int8_t *, const char *);
220
static void setstr(u_int8_t *, const char *, size_t);
221
static void infohandler(int sig);
222
223
int
224
mkfs_msdos(const char *fname, const char *dtype, const struct msdos_options *op)
225
{
226
    char buf[MAXPATHLEN];
227
    struct stat sb;
228
    struct timeval tv;
229
    struct bpb bpb;
230
    struct tm *tm;
231
    struct bs *bs;
232
    struct bsbpb *bsbpb;
233
    struct bsxbpb *bsxbpb;
234
    struct bsx *bsx;
235
    struct de *de;
236
    u_int8_t *img;
237
    const char *bname;
238
    ssize_t n;
239
    time_t now;
240
    u_int bss, rds, cls, dir, lsn, x, x1, x2;
241
    int ch, fd, fd1;
242
    struct msdos_options o = *op;
243
    int oflags = O_RDWR | O_CREAT;
244
245
    if (o.block_size && o.sectors_per_cluster) {
246
	warnx("Cannot specify both block size and sectors per cluster");
247
	return -1;
248
    }
249
    if (o.OEM_string && strlen(o.OEM_string) > 8) {
250
	warnx("%s: bad OEM string", o.OEM_string);
251
	return -1;
252
    }
253
    if (o.create_size) {
254
	if (o.offset == 0)
255
		oflags |= O_TRUNC;
256
	fd = open(fname, oflags, 0644);
257
	if (fd == -1) {
258
	    warnx("failed to create %s", fname);
259
	    return -1;
260
	}
261
	(void)lseek(fd, o.create_size - 1, SEEK_SET);
262
	if (write(fd, "\0", 1) != 1) {
263
	    warn("failed to set file size");
264
	    return -1;
265
	}
266
	(void)lseek(fd, 0, SEEK_SET);
267
    } else if ((fd = open(fname, O_RDWR)) == -1 ||
268
	fstat(fd, &sb)) {
269
	warn("%s", fname);
270
	return -1;
271
    }
272
    if (!S_ISCHR(sb.st_mode) && !o.create_size) {
273
	warnx("warning, %s is not a character device", fname);
274
	return -1;
275
    }
276
    if (o.offset && o.offset != lseek(fd, o.offset, SEEK_SET)) {
277
	warnx("cannot seek to %jd", (intmax_t)o.offset);
278
	return -1;
279
    }
280
    memset(&bpb, 0, sizeof(bpb));
281
    if (o.floppy) {
282
	if (getstdfmt(o.floppy, &bpb) == -1)
283
	    return -1;
284
	bpb.bsec = bpb.sec;
285
	bpb.sec = 0;
286
	bpb.bspf = bpb.spf;
287
	bpb.spf = 0;
288
    }
289
    if (o.drive_heads)
290
	bpb.hds = o.drive_heads;
291
    if (o.sectors_per_track)
292
	bpb.spt = o.sectors_per_track;
293
    if (o.bytes_per_sector)
294
	bpb.bps = o.bytes_per_sector;
295
    if (o.size)
296
	bpb.bsec = o.size;
297
    if (o.hidden_sectors_set)
298
	bpb.hid = o.hidden_sectors;
299
    if (!(o.floppy || (o.drive_heads && o.sectors_per_track &&
300
	o.bytes_per_sector && o.size && o.hidden_sectors_set))) {
301
	if (getbpbinfo(fd, fname, dtype, o.hidden_sectors_set, &bpb,
302
	    o.create_size != 0) == -1)
303
	    return -1;
304
	bpb.bsec -= (o.offset / bpb.bps);
305
	if (bpb.spc == 0) {     /* set defaults */
306
	    /* minimum cluster size */
307
	    switch (o.fat_type) {
308
	    case 12:
309
		bpb.spc = 1;            /* use 512 bytes */
310
		x = 2;                  /* up to 2MB */
311
		break;
312
	    case 16:
313
		bpb.spc = 1;            /* use 512 bytes */
314
		x = 32;                 /* up to 32MB */
315
		break;
316
	    default:
317
		bpb.spc = 8;            /* use 4k */
318
		x = 8192;               /* up to 8GB */
319
		break;
320
	    }
321
	    x1 = howmany(bpb.bsec, (1048576 / 512)); /* -> MB */
322
	    while (bpb.spc < 128 && x < x1) {
323
		x *= 2;
324
		bpb.spc *= 2;
325
	    }
326
	}
327
    }
328
329
    if (o.volume_label && !oklabel(o.volume_label)) {
330
	warnx("%s: bad volume label", o.volume_label);
331
	return -1;
332
    }
333
334
    switch (o.fat_type) {
335
    case 0:
336
	if (o.floppy)
337
	    o.fat_type = 12;
338
	else if (!o.directory_entries && (o.info_sector || o.backup_sector))
339
	    o.fat_type = 32;
340
	break;
341
    case 12:
342
    case 16:
343
	if (o.info_sector) {
344
	    warnx("Cannot specify info sector with FAT%u", o.fat_type);
345
	    return -1;
346
	}
347
	if (o.backup_sector) {
348
	    warnx("Cannot specify backup sector with FAT%u", o.fat_type);
349
	    return -1;
350
	}
351
	break;
352
    case 32:
353
	if (o.directory_entries) {
354
	    warnx("Cannot specify directory entries with FAT32");
355
	    return -1;
356
	}
357
	break;
358
    default:
359
	warnx("%d: bad FAT type", o.fat_type);
360
	return -1;
361
    }
362
    if (!powerof2(bpb.bps)) {
363
	warnx("bytes/sector (%u) is not a power of 2", bpb.bps);
364
	return -1;
365
    }
366
    if (bpb.bps < MINBPS) {
367
	warnx("bytes/sector (%u) is too small; minimum is %u",
368
	     bpb.bps, MINBPS);
369
	return -1;
370
    }
371
372
    if (o.floppy && o.fat_type == 32)
373
	bpb.rde = 0;
374
    if (o.block_size) {
375
	if (!powerof2(o.block_size)) {
376
	    warnx("block size (%u) is not a power of 2", o.block_size);
377
	    return -1;
378
	}
379
	if (o.block_size < bpb.bps) {
380
	    warnx("block size (%u) is too small; minimum is %u",
381
		o.block_size, bpb.bps);
382
	    return -1;
383
	}
384
	if (o.block_size > bpb.bps * MAXSPC) {
385
	    warnx("block size (%u) is too large; maximum is %u",
386
		o.block_size, bpb.bps * MAXSPC);
387
	    return -1;
388
	}
389
	bpb.spc = o.block_size / bpb.bps;
390
    }
391
    if (o.sectors_per_cluster) {
392
	if (!powerof2(o.sectors_per_cluster)) {
393
	    warnx("sectors/cluster (%u) is not a power of 2",
394
		o.sectors_per_cluster);
395
	    return -1;
396
	}
397
	bpb.spc = o.sectors_per_cluster;
398
    }
399
    if (o.reserved_sectors)
400
	bpb.res = o.reserved_sectors;
401
    if (o.num_FAT) {
402
	if (o.num_FAT > MAXNFT) {
403
	    warnx("number of FATs (%u) is too large; maximum is %u",
404
		 o.num_FAT, MAXNFT);
405
	    return -1;
406
	}
407
	bpb.nft = o.num_FAT;
408
    }
409
    if (o.directory_entries)
410
	bpb.rde = o.directory_entries;
411
    if (o.media_descriptor_set) {
412
	if (o.media_descriptor < 0xf0) {
413
	    warnx("illegal media descriptor (%#x)", o.media_descriptor);
414
	    return -1;
415
	}
416
	bpb.mid = o.media_descriptor;
417
    }
418
    if (o.sectors_per_fat)
419
	bpb.bspf = o.sectors_per_fat;
420
    if (o.info_sector)
421
	bpb.infs = o.info_sector;
422
    if (o.backup_sector)
423
	bpb.bkbs = o.backup_sector;
424
    bss = 1;
425
    bname = NULL;
426
    fd1 = -1;
427
    if (o.bootstrap) {
428
	bname = o.bootstrap;
429
	if (!strchr(bname, '/')) {
430
	    snprintf(buf, sizeof(buf), "/boot/%s", bname);
431
	    if (!(bname = strdup(buf))) {
432
		warn(NULL);
433
		return -1;
434
	    }
435
	}
436
	if ((fd1 = open(bname, O_RDONLY)) == -1 || fstat(fd1, &sb)) {
437
	    warn("%s", bname);
438
	    return -1;
439
	}
440
	if (!S_ISREG(sb.st_mode) || sb.st_size % bpb.bps ||
441
	    sb.st_size < bpb.bps || sb.st_size > bpb.bps * MAXU16) {
442
	    warnx("%s: inappropriate file type or format", bname);
443
	    return -1;
444
	}
445
	bss = sb.st_size / bpb.bps;
446
    }
447
    if (!bpb.nft)
448
	bpb.nft = 2;
449
    if (!o.fat_type) {
450
	if (bpb.bsec < (bpb.res ? bpb.res : bss) +
451
	    howmany((RESFTE + (bpb.spc ? MINCLS16 : MAXCLS12 + 1)) *
452
		    ((bpb.spc ? 16 : 12) / BPN), bpb.bps * NPB) *
453
	    bpb.nft +
454
	    howmany(bpb.rde ? bpb.rde : DEFRDE,
455
		    bpb.bps / sizeof(struct de)) +
456
	    (bpb.spc ? MINCLS16 : MAXCLS12 + 1) *
457
	    (bpb.spc ? bpb.spc : howmany(DEFBLK, bpb.bps)))
458
	    o.fat_type = 12;
459
	else if (bpb.rde || bpb.bsec <
460
		 (bpb.res ? bpb.res : bss) +
461
		 howmany((RESFTE + MAXCLS16) * 2, bpb.bps) * bpb.nft +
462
		 howmany(DEFRDE, bpb.bps / sizeof(struct de)) +
463
		 (MAXCLS16 + 1) *
464
		 (bpb.spc ? bpb.spc : howmany(8192, bpb.bps)))
465
	    o.fat_type = 16;
466
	else
467
	    o.fat_type = 32;
468
    }
469
    x = bss;
470
    if (o.fat_type == 32) {
471
	if (!bpb.infs) {
472
	    if (x == MAXU16 || x == bpb.bkbs) {
473
		warnx("no room for info sector");
474
		return -1;
475
	    }
476
	    bpb.infs = x;
477
	}
478
	if (bpb.infs != MAXU16 && x <= bpb.infs)
479
	    x = bpb.infs + 1;
480
	if (!bpb.bkbs) {
481
	    if (x == MAXU16) {
482
		warnx("no room for backup sector");
483
		return -1;
484
	    }
485
	    bpb.bkbs = x;
486
	} else if (bpb.bkbs != MAXU16 && bpb.bkbs == bpb.infs) {
487
	    warnx("backup sector would overwrite info sector");
488
	    return -1;
489
	}
490
	if (bpb.bkbs != MAXU16 && x <= bpb.bkbs)
491
	    x = bpb.bkbs + 1;
492
    }
493
    if (!bpb.res)
494
	bpb.res = o.fat_type == 32 ? MAX(x, MAX(16384 / bpb.bps, 4)) : x;
495
    else if (bpb.res < x) {
496
	warnx("too few reserved sectors (need %d have %d)", x, bpb.res);
497
	return -1;
498
    }
499
    if (o.fat_type != 32 && !bpb.rde)
500
	bpb.rde = DEFRDE;
501
    rds = howmany(bpb.rde, bpb.bps / sizeof(struct de));
502
    if (!bpb.spc)
503
	for (bpb.spc = howmany(o.fat_type == 16 ? DEFBLK16 : DEFBLK, bpb.bps);
504
	     bpb.spc < MAXSPC &&
505
	     bpb.res +
506
	     howmany((RESFTE + maxcls(o.fat_type)) * (o.fat_type / BPN),
507
		     bpb.bps * NPB) * bpb.nft +
508
	     rds +
509
	     (u_int64_t)(maxcls(o.fat_type) + 1) * bpb.spc <= bpb.bsec;
510
	     bpb.spc <<= 1);
511
    if (o.fat_type != 32 && bpb.bspf > MAXU16) {
512
	warnx("too many sectors/FAT for FAT12/16");
513
	return -1;
514
    }
515
    x1 = bpb.res + rds;
516
    x = bpb.bspf ? bpb.bspf : 1;
517
    if (x1 + (u_int64_t)x * bpb.nft > bpb.bsec) {
518
	warnx("meta data exceeds file system size");
519
	return -1;
520
    }
521
    x1 += x * bpb.nft;
522
    x = (u_int64_t)(bpb.bsec - x1) * bpb.bps * NPB /
523
	(bpb.spc * bpb.bps * NPB + o.fat_type / BPN * bpb.nft);
524
    x2 = howmany((RESFTE + MIN(x, maxcls(o.fat_type))) * (o.fat_type / BPN),
525
		 bpb.bps * NPB);
526
    if (!bpb.bspf) {
527
	bpb.bspf = x2;
528
	x1 += (bpb.bspf - 1) * bpb.nft;
529
    }
530
    cls = (bpb.bsec - x1) / bpb.spc;
531
    x = (u_int64_t)bpb.bspf * bpb.bps * NPB / (o.fat_type / BPN) - RESFTE;
532
    if (cls > x)
533
	cls = x;
534
    if (bpb.bspf < x2) {
535
	warnx("warning: sectors/FAT limits file system to %u clusters",
536
	      cls);
537
	return -1;
538
    }
539
    if (cls < mincls(o.fat_type)) {
540
	warnx("%u clusters too few clusters for FAT%u, need %u", cls,
541
	    o.fat_type, mincls(o.fat_type));
542
	return -1;
543
    }
544
    if (cls > maxcls(o.fat_type)) {
545
	cls = maxcls(o.fat_type);
546
	bpb.bsec = x1 + (cls + 1) * bpb.spc - 1;
547
	warnx("warning: FAT type limits file system to %u sectors",
548
	      bpb.bsec);
549
	return -1;
550
    }
551
    printf("%s: %u sector%s in %u FAT%u cluster%s "
552
	   "(%u bytes/cluster)\n", fname, cls * bpb.spc,
553
	   cls * bpb.spc == 1 ? "" : "s", cls, o.fat_type,
554
	   cls == 1 ? "" : "s", bpb.bps * bpb.spc);
555
    if (!bpb.mid)
556
	bpb.mid = !bpb.hid ? 0xf0 : 0xf8;
557
    if (o.fat_type == 32)
558
	bpb.rdcl = RESFTE;
559
    if (bpb.hid + bpb.bsec <= MAXU16) {
560
	bpb.sec = bpb.bsec;
561
	bpb.bsec = 0;
562
    }
563
    if (o.fat_type != 32) {
564
	bpb.spf = bpb.bspf;
565
	bpb.bspf = 0;
566
    }
567
    ch = 0;
568
    if (o.fat_type == 12)
569
	ch = 1;			/* 001 Primary DOS with 12 bit FAT */
570
    else if (o.fat_type == 16) {
571
	if (bpb.bsec == 0)
572
	    ch = 4;		/* 004 Primary DOS with 16 bit FAT <32M */
573
	else
574
	    ch = 6;		/* 006 Primary 'big' DOS, 16-bit FAT (> 32MB) */
575
				/*
576
				 * XXX: what about:
577
				 * 014 DOS (16-bit FAT) - LBA
578
				 *  ?
579
				 */
580
    } else if (o.fat_type == 32) {
581
	ch = 11;		/* 011 Primary DOS with 32 bit FAT */
582
				/*
583
				 * XXX: what about:
584
				 * 012 Primary DOS with 32 bit FAT - LBA
585
				 *  ?
586
				 */
587
    }
588
    if (ch != 0)
589
	printf("MBR type: %d\n", ch);
590
    print_bpb(&bpb);
591
592
    gettimeofday(&tv, NULL);
593
    now = tv.tv_sec;
594
    tm = localtime(&now);
595
    if (!(img = malloc(bpb.bps)))
596
        err(1, NULL);
597
    dir = bpb.res + (bpb.spf ? bpb.spf : bpb.bspf) * bpb.nft;
598
    signal(SIGINFO, infohandler);
599
    for (lsn = 0; lsn < dir + (o.fat_type == 32 ? bpb.spc : rds); lsn++) {
600
        if (got_siginfo) {
601
            fprintf(stderr,"%s: writing sector %u of %u (%u%%)\n",
602
                fname,lsn,(dir + (o.fat_type == 32 ? bpb.spc : rds)),
603
                (lsn*100)/(dir + (o.fat_type == 32 ? bpb.spc : rds)));
604
            got_siginfo = 0;
605
        }
606
        x = lsn;
607
        if (o.bootstrap &&
608
            o.fat_type == 32 && bpb.bkbs != MAXU16 &&
609
            bss <= bpb.bkbs && x >= bpb.bkbs) {
610
            x -= bpb.bkbs;
611
            if (!x && lseek(fd1, o.offset, SEEK_SET)) {
612
                warn("%s", bname);
613
                return -1;
614
            }
615
        }
616
        if (o.bootstrap && x < bss) {
617
            if ((n = read(fd1, img, bpb.bps)) == -1) {
618
                warn("%s", bname);
619
                return -1;
620
            }
621
            if ((size_t)n != bpb.bps) {
622
                warnx("%s: can't read sector %u", bname, x);
623
                return -1;
624
            }
625
        } else
626
            memset(img, 0, bpb.bps);
627
        if (!lsn ||
628
          (o.fat_type == 32 && bpb.bkbs != MAXU16 && lsn == bpb.bkbs)) {
629
            x1 = sizeof(struct bs);
630
            bsbpb = (struct bsbpb *)(img + x1);
631
            mk2(bsbpb->bps, bpb.bps);
632
            mk1(bsbpb->spc, bpb.spc);
633
            mk2(bsbpb->res, bpb.res);
634
            mk1(bsbpb->nft, bpb.nft);
635
            mk2(bsbpb->rde, bpb.rde);
636
            mk2(bsbpb->sec, bpb.sec);
637
            mk1(bsbpb->mid, bpb.mid);
638
            mk2(bsbpb->spf, bpb.spf);
639
            mk2(bsbpb->spt, bpb.spt);
640
            mk2(bsbpb->hds, bpb.hds);
641
            mk4(bsbpb->hid, bpb.hid);
642
            mk4(bsbpb->bsec, bpb.bsec);
643
            x1 += sizeof(struct bsbpb);
644
            if (o.fat_type == 32) {
645
                bsxbpb = (struct bsxbpb *)(img + x1);
646
                mk4(bsxbpb->bspf, bpb.bspf);
647
                mk2(bsxbpb->xflg, 0);
648
                mk2(bsxbpb->vers, 0);
649
                mk4(bsxbpb->rdcl, bpb.rdcl);
650
                mk2(bsxbpb->infs, bpb.infs);
651
                mk2(bsxbpb->bkbs, bpb.bkbs);
652
                x1 += sizeof(struct bsxbpb);
653
            }
654
            bsx = (struct bsx *)(img + x1);
655
            mk1(bsx->sig, 0x29);
656
            if (o.volume_id_set)
657
                x = o.volume_id;
658
            else
659
                x = (((u_int)(1 + tm->tm_mon) << 8 |
660
                      (u_int)tm->tm_mday) +
661
                     ((u_int)tm->tm_sec << 8 |
662
                      (u_int)(tv.tv_usec / 10))) << 16 |
663
                    ((u_int)(1900 + tm->tm_year) +
664
                     ((u_int)tm->tm_hour << 8 |
665
                      (u_int)tm->tm_min));
666
            mk4(bsx->volid, x);
667
            mklabel(bsx->label, o.volume_label ? o.volume_label : "NO NAME");
668
            snprintf(buf, sizeof(buf), "FAT%u", o.fat_type);
669
            setstr(bsx->type, buf, sizeof(bsx->type));
670
            if (!o.bootstrap) {
671
                x1 += sizeof(struct bsx);
672
                bs = (struct bs *)img;
673
                mk1(bs->jmp[0], 0xeb);
674
                mk1(bs->jmp[1], x1 - 2);
675
                mk1(bs->jmp[2], 0x90);
676
                setstr(bs->oem, o.OEM_string ? o.OEM_string : "NetBSD",
677
                       sizeof(bs->oem));
678
                memcpy(img + x1, bootcode, sizeof(bootcode));
679
                mk2(img + MINBPS - 2, DOSMAGIC);
680
            }
681
        } else if (o.fat_type == 32 && bpb.infs != MAXU16 &&
682
                   (lsn == bpb.infs ||
683
                    (bpb.bkbs != MAXU16 &&
684
                     lsn == bpb.bkbs + bpb.infs))) {
685
            mk4(img, 0x41615252);
686
            mk4(img + MINBPS - 28, 0x61417272);
687
            mk4(img + MINBPS - 24, 0xffffffff);
688
            mk4(img + MINBPS - 20, 0xffffffff);
689
            mk2(img + MINBPS - 2, DOSMAGIC);
690
        } else if (lsn >= bpb.res && lsn < dir &&
691
                   !((lsn - bpb.res) %
692
                     (bpb.spf ? bpb.spf : bpb.bspf))) {
693
            mk1(img[0], bpb.mid);
694
            for (x = 1; x < o.fat_type * (o.fat_type == 32 ? 3U : 2U) / 8U; x++)
695
                mk1(img[x], o.fat_type == 32 && x % 4 == 3 ? 0x0f : 0xff);
696
        } else if (lsn == dir && o.volume_label) {
697
            de = (struct de *)img;
698
            mklabel(de->namext, o.volume_label);
699
            mk1(de->attr, 050);
700
            x = (u_int)tm->tm_hour << 11 |
701
                (u_int)tm->tm_min << 5 |
702
                (u_int)tm->tm_sec >> 1;
703
            mk2(de->time, x);
704
            x = (u_int)(tm->tm_year - 80) << 9 |
705
                (u_int)(tm->tm_mon + 1) << 5 |
706
                (u_int)tm->tm_mday;
707
            mk2(de->date, x);
708
        }
709
        if ((n = write(fd, img, bpb.bps)) == -1) {
710
            warn("%s", fname);
711
            return -1;
712
        }
713
        if ((size_t)n != bpb.bps) {
714
            warnx("%s: can't write sector %u", fname, lsn);
715
            return -1;
716
        }
717
    }
718
    return 0;
719
}
720
721
722
/*
723
 * Get a standard format.
724
 */
725
static int
726
getstdfmt(const char *fmt, struct bpb *bpb)
727
{
728
    u_int x, i;
729
730
    x = sizeof(stdfmt) / sizeof(stdfmt[0]);
731
    for (i = 0; i < x && strcmp(fmt, stdfmt[i].name); i++);
732
    if (i == x) {
733
	warnx("%s: unknown standard format", fmt);
734
	return -1;
735
    }
736
    *bpb = stdfmt[i].bpb;
737
    return 0;
738
}
739
740
/*
741
 * Get disk slice, partition, and geometry information.
742
 */
743
static int
744
getbpbinfo(int fd, const char *fname, const char *dtype, int iflag,
745
    struct bpb *bpb, int create)
746
{
747
    const char *s1, *s2;
748
    int part;
749
750
    part = -1;
751
    s1 = fname;
752
    if ((s2 = strrchr(s1, '/')))
753
	s1 = s2 + 1;
754
    for (s2 = s1; *s2 && !isdigit((unsigned char)*s2); s2++);
755
    if (!*s2 || s2 == s1)
756
	s2 = NULL;
757
    else
758
	while (isdigit((unsigned char)*++s2));
759
    s1 = s2;
760
761
    if (((part != -1) && ((!iflag && part != -1) || !bpb->bsec)) ||
762
	!bpb->bps || !bpb->spt || !bpb->hds) {
763
	u_int sector_size;
764
	u_int nsectors;
765
	u_int ntracks;
766
	u_int size;
767
	{
768
	    struct stat st;
769
770
	    if (fstat(fd, &st) == -1) {
771
		warnx("Can't get disk size for `%s'", fname);
772
		return -1;
773
	    }
774
	    /* create a fake geometry for a file image */
775
	    sector_size = 512;
776
	    nsectors = 63;
777
	    ntracks = 255;
778
	    size = st.st_size / sector_size;
779
	}
780
	if (!bpb->bps) {
781
	    if (ckgeom(fname, sector_size, "bytes/sector") == -1)
782
		return -1;
783
	    bpb->bps = sector_size;
784
	}
785
786
	if (nsectors > 63) {
787
		/*
788
		 * The kernel doesn't accept BPB with spt > 63.
789
		 * (see sys/fs/msdosfs/msdosfs_vfsops.c:msdosfs_mountfs())
790
		 * If values taken from disklabel don't match these
791
		 * restrictions, use popular BIOS default values instead.
792
		 */
793
		nsectors = 63;
794
	}
795
	if (!bpb->spt) {
796
	    if (ckgeom(fname, nsectors, "sectors/track") == -1)
797
		return -1;
798
	    bpb->spt = nsectors;
799
	}
800
	if (!bpb->hds) {
801
	    if (ckgeom(fname, ntracks, "drive heads") == -1)
802
		return -1;
803
	    bpb->hds = ntracks;
804
	}
805
	if (!bpb->bsec)
806
	    bpb->bsec = size;
807
    }
808
    return 0;
809
}
810
811
/*
812
 * Print out BPB values.
813
 */
814
static void
815
print_bpb(struct bpb *bpb)
816
{
817
    printf("bps=%u spc=%u res=%u nft=%u", bpb->bps, bpb->spc, bpb->res,
818
	   bpb->nft);
819
    if (bpb->rde)
820
	printf(" rde=%u", bpb->rde);
821
    if (bpb->sec)
822
	printf(" sec=%u", bpb->sec);
823
    printf(" mid=%#x", bpb->mid);
824
    if (bpb->spf)
825
	printf(" spf=%u", bpb->spf);
826
    printf(" spt=%u hds=%u hid=%u", bpb->spt, bpb->hds, bpb->hid);
827
    if (bpb->bsec)
828
	printf(" bsec=%u", bpb->bsec);
829
    if (!bpb->spf) {
830
	printf(" bspf=%u rdcl=%u", bpb->bspf, bpb->rdcl);
831
	printf(" infs=");
832
	printf(bpb->infs == MAXU16 ? "%#x" : "%u", bpb->infs);
833
	printf(" bkbs=");
834
	printf(bpb->bkbs == MAXU16 ? "%#x" : "%u", bpb->bkbs);
835
    }
836
    printf("\n");
837
}
838
839
/*
840
 * Check a disk geometry value.
841
 */
842
static int
843
ckgeom(const char *fname, u_int val, const char *msg)
844
{
845
    if (!val) {
846
	warnx("%s: no default %s", fname, msg);
847
	return -1;
848
    }
849
    if (val > MAXU16) {
850
	warnx("%s: illegal %s", fname, msg);
851
	return -1;
852
    }
853
    return 0;
854
}
855
/*
856
 * Check a volume label.
857
 */
858
static int
859
oklabel(const char *src)
860
{
861
    int c, i;
862
863
    for (i = 0; i <= 11; i++) {
864
	c = (u_char)*src++;
865
	if (c < ' ' + !i || strchr("\"*+,./:;<=>?[\\]|", c))
866
	    break;
867
    }
868
    return i && !c;
869
}
870
871
/*
872
 * Make a volume label.
873
 */
874
static void
875
mklabel(u_int8_t *dest, const char *src)
876
{
877
    int c, i;
878
879
    for (i = 0; i < 11; i++) {
880
	c = *src ? toupper((unsigned char)*src++) : ' ';
881
	*dest++ = !i && c == '\xe5' ? 5 : c;
882
    }
883
}
884
885
/*
886
 * Copy string, padding with spaces.
887
 */
888
static void
889
setstr(u_int8_t *dest, const char *src, size_t len)
890
{
891
    while (len--)
892
	*dest++ = *src ? *src++ : ' ';
893
}
894
895
static void
896
infohandler(int sig)
897
{
898
    got_siginfo = 1;
899
}