1 /*	$OpenBSD: newfs_msdos.c,v 1.15 2004/10/01 04:08:45 jsg Exp $	*/
2 
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 #ifndef lint
31 static const char rcsid[] =
32   "$FreeBSD: src/sbin/newfs_msdos/newfs_msdos.c,v 1.9 1999/08/28 00:13:52 peter Exp $";
33 #endif /* not lint */
34 
35 #include <sys/param.h>
36 #include <sys/stat.h>
37 #ifdef __FreeBSD__
38 #include <sys/diskslice.h>
39 #endif
40 #include <sys/disklabel.h>
41 #ifndef __FreeBSD__
42 #include <sys/ioctl.h>
43 #endif
44 #include <sys/mount.h>
45 
46 #include <ctype.h>
47 #include <err.h>
48 #include <errno.h>
49 #include <fcntl.h>
50 #include <paths.h>
51 #include <stdio.h>
52 #include <stdlib.h>
53 #include <string.h>
54 #include <unistd.h>
55 #ifdef __OpenBSD__
56 #include <util.h>
57 #endif
58 
59 #define MAXU16	  0xffff	/* maximum unsigned 16-bit quantity */
60 #define BPN	  4		/* bits per nibble */
61 #define NPB	  2		/* nibbles per byte */
62 
63 #define DOSMAGIC  0xaa55	/* DOS magic number */
64 #define MINBPS	  128		/* minimum bytes per sector */
65 #define MAXSPC	  128		/* maximum sectors per cluster */
66 #define MAXNFT	  16		/* maximum number of FATs */
67 #define DEFBLK	  4096		/* default block size */
68 #define DEFBLK16  2048		/* default block size FAT16 */
69 #define DEFRDE	  512		/* default root directory entries */
70 #define RESFTE	  2		/* reserved FAT entries */
71 #define MINCLS12  1		/* minimum FAT12 clusters */
72 #define MINCLS16  0x1000	/* minimum FAT16 clusters */
73 #define MINCLS32  2		/* minimum FAT32 clusters */
74 #define MAXCLS12  0xfed		/* maximum FAT12 clusters */
75 #define MAXCLS16  0xfff5	/* maximum FAT16 clusters */
76 #define MAXCLS32  0xffffff5	/* maximum FAT32 clusters */
77 
78 #define mincls(fat)  ((fat) == 12 ? MINCLS12 :	\
79 		      (fat) == 16 ? MINCLS16 :	\
80 				    MINCLS32)
81 
82 #define maxcls(fat)  ((fat) == 12 ? MAXCLS12 :	\
83 		      (fat) == 16 ? MAXCLS16 :	\
84 				    MAXCLS32)
85 
86 #define mk1(p, x)				\
87     (p) = (u_int8_t)(x)
88 
89 #define mk2(p, x)				\
90     (p)[0] = (u_int8_t)(x),			\
91     (p)[1] = (u_int8_t)((x) >> 010)
92 
93 #define mk4(p, x)				\
94     (p)[0] = (u_int8_t)(x),			\
95     (p)[1] = (u_int8_t)((x) >> 010),		\
96     (p)[2] = (u_int8_t)((x) >> 020),		\
97     (p)[3] = (u_int8_t)((x) >> 030)
98 
99 #define argto1(arg, lo, msg)  argtou(arg, lo, 0xff, msg)
100 #define argto2(arg, lo, msg)  argtou(arg, lo, 0xffff, msg)
101 #define argto4(arg, lo, msg)  argtou(arg, lo, 0xffffffff, msg)
102 #define argtox(arg, lo, msg)  argtou(arg, lo, UINT_MAX, msg)
103 
104 struct bs {
105     u_int8_t jmp[3];		/* bootstrap entry point */
106     u_int8_t oem[8];		/* OEM name and version */
107 };
108 
109 struct bsbpb {
110     u_int8_t bps[2];		/* bytes per sector */
111     u_int8_t spc;		/* sectors per cluster */
112     u_int8_t res[2];		/* reserved sectors */
113     u_int8_t nft;		/* number of FATs */
114     u_int8_t rde[2];		/* root directory entries */
115     u_int8_t sec[2];		/* total sectors */
116     u_int8_t mid;		/* media descriptor */
117     u_int8_t spf[2];		/* sectors per FAT */
118     u_int8_t spt[2];		/* sectors per track */
119     u_int8_t hds[2];		/* drive heads */
120     u_int8_t hid[4];		/* hidden sectors */
121     u_int8_t bsec[4];		/* big total sectors */
122 };
123 
124 struct bsxbpb {
125     u_int8_t bspf[4];		/* big sectors per FAT */
126     u_int8_t xflg[2];		/* FAT control flags */
127     u_int8_t vers[2];		/* file system version */
128     u_int8_t rdcl[4];		/* root directory start cluster */
129     u_int8_t infs[2];		/* file system info sector */
130     u_int8_t bkbs[2];		/* backup boot sector */
131     u_int8_t rsvd[12];		/* reserved */
132 };
133 
134 struct bsx {
135     u_int8_t drv;		/* drive number */
136     u_int8_t rsvd;		/* reserved */
137     u_int8_t sig;		/* extended boot signature */
138     u_int8_t volid[4];		/* volume ID number */
139     u_int8_t label[11];		/* volume label */
140     u_int8_t type[8];		/* file system type */
141 };
142 
143 struct de {
144     u_int8_t namext[11];	/* name and extension */
145     u_int8_t attr;		/* attributes */
146     u_int8_t rsvd[10];		/* reserved */
147     u_int8_t time[2];		/* creation time */
148     u_int8_t date[2];		/* creation date */
149     u_int8_t clus[2];		/* starting cluster */
150     u_int8_t size[4];		/* size */
151 };
152 
153 struct bpb {
154     u_int bps;			/* bytes per sector */
155     u_int spc;			/* sectors per cluster */
156     u_int res;			/* reserved sectors */
157     u_int nft;			/* number of FATs */
158     u_int rde;			/* root directory entries */
159     u_int sec;			/* total sectors */
160     u_int mid;			/* media descriptor */
161     u_int spf;			/* sectors per FAT */
162     u_int spt;			/* sectors per track */
163     u_int hds;			/* drive heads */
164     u_int hid;			/* hidden sectors */
165     u_int bsec;			/* big total sectors */
166     u_int bspf;			/* big sectors per FAT */
167     u_int rdcl; 		/* root directory start cluster */
168     u_int infs; 		/* file system info sector */
169     u_int bkbs; 		/* backup boot sector */
170 };
171 
172 static struct {
173     const char *name;
174     struct bpb bpb;
175 } stdfmt[] = {
176     {"160",  {512, 1, 1, 2,  64,  320, 0xfe, 1,  8, 1}},
177     {"180",  {512, 1, 1, 2,  64,  360, 0xfc, 2,  9, 1}},
178     {"320",  {512, 2, 1, 2, 112,  640, 0xff, 1,  8, 2}},
179     {"360",  {512, 2, 1, 2, 112,  720, 0xfd, 2,  9, 2}},
180     {"720",  {512, 2, 1, 2, 112, 1440, 0xf9, 3,  9, 2}},
181     {"1200", {512, 1, 1, 2, 224, 2400, 0xf9, 7, 15, 2}},
182     {"1440", {512, 1, 1, 2, 224, 2880, 0xf0, 9, 18, 2}},
183     {"2880", {512, 2, 1, 2, 240, 5760, 0xf0, 9, 36, 2}}
184 };
185 
186 static u_int8_t bootcode[] = {
187     0xfa,			/* cli		    */
188     0x31, 0xc0, 		/* xor	   ax,ax    */
189     0x8e, 0xd0, 		/* mov	   ss,ax    */
190     0xbc, 0x00, 0x7c,		/* mov	   sp,7c00h */
191     0xfb,			/* sti		    */
192     0x8e, 0xd8, 		/* mov	   ds,ax    */
193     0xe8, 0x00, 0x00,		/* call    $ + 3    */
194     0x5e,			/* pop	   si	    */
195     0x83, 0xc6, 0x19,		/* add	   si,+19h  */
196     0xbb, 0x07, 0x00,		/* mov	   bx,0007h */
197     0xfc,			/* cld		    */
198     0xac,			/* lodsb	    */
199     0x84, 0xc0, 		/* test    al,al    */
200     0x74, 0x06, 		/* jz	   $ + 8    */
201     0xb4, 0x0e, 		/* mov	   ah,0eh   */
202     0xcd, 0x10, 		/* int	   10h	    */
203     0xeb, 0xf5, 		/* jmp	   $ - 9    */
204     0x30, 0xe4, 		/* xor	   ah,ah    */
205     0xcd, 0x16, 		/* int	   16h	    */
206     0xcd, 0x19, 		/* int	   19h	    */
207     0x0d, 0x0a,
208     'N', 'o', 'n', '-', 's', 'y', 's', 't',
209     'e', 'm', ' ', 'd', 'i', 's', 'k',
210     0x0d, 0x0a,
211     'P', 'r', 'e', 's', 's', ' ', 'a', 'n',
212     'y', ' ', 'k', 'e', 'y', ' ', 't', 'o',
213     ' ', 'r', 'e', 'b', 'o', 'o', 't',
214     0x0d, 0x0a,
215     0
216 };
217 
218 static void check_mounted(const char *, mode_t);
219 static void getstdfmt(const char *, struct bpb *);
220 static void getdiskinfo(int, const char *, const char *, int,
221 			struct bpb *);
222 static void print_bpb(struct bpb *);
223 static u_int ckgeom(const char *, u_int, const char *);
224 static u_int argtou(const char *, u_int, u_int, const char *);
225 static int oklabel(const char *);
226 static void mklabel(u_int8_t *, const char *);
227 static void setstr(u_int8_t *, const char *, size_t);
228 static void usage(void);
229 
230 /*
231  * Construct a FAT12, FAT16, or FAT32 file system.
232  */
233 int
main(int argc,char * argv[])234 main(int argc, char *argv[])
235 {
236     static char opts[] = "NB:F:I:L:O:S:a:b:c:e:f:h:i:k:m:n:o:qr:s:t:u:";
237     static const char *opt_B, *opt_L, *opt_O, *opt_f;
238     static u_int opt_F, opt_I, opt_S, opt_a, opt_b, opt_c, opt_e;
239     static u_int opt_h, opt_i, opt_k, opt_m, opt_n, opt_o, opt_r;
240     static u_int opt_s, opt_u;
241     static int opt_N;
242     static int Iflag, mflag, oflag;
243     char buf[MAXPATHLEN];
244     struct stat sb;
245     struct timeval tv;
246     struct bpb bpb;
247     struct tm *tm;
248     struct bs *bs;
249     struct bsbpb *bsbpb;
250     struct bsxbpb *bsxbpb;
251     struct bsx *bsx;
252     struct de *de;
253     u_int8_t *img;
254 #ifdef __FreeBSD__
255     const char *fname, *dtype, *bname;
256 #endif
257 #ifdef __OpenBSD__
258     const char *dtype, *bname;
259     char *sname, *fname;
260 #endif
261     ssize_t n;
262     time_t now;
263     u_int fat, bss, rds, cls, dir, lsn, x, x1, x2;
264     int ch, fd, fd1;
265 
266     while ((ch = getopt(argc, argv, opts)) != -1)
267 	switch (ch) {
268 	case 'N':
269 	    opt_N = 1;
270 	    break;
271 	case 'B':
272 	    opt_B = optarg;
273 	    break;
274 	case 'F':
275 	    if (strcmp(optarg, "12") &&
276 		strcmp(optarg, "16") &&
277 		strcmp(optarg, "32"))
278 		errx(1, "%s: bad FAT type", optarg);
279 	    opt_F = atoi(optarg);
280 	    break;
281 	case 'I':
282 	    opt_I = argto4(optarg, 0, "volume ID");
283 	    Iflag = 1;
284 	    break;
285 	case 'L':
286 	    if (!oklabel(optarg))
287 		errx(1, "%s: bad volume label", optarg);
288 	    opt_L = optarg;
289 	    break;
290 	case 'O':
291 	    if (strlen(optarg) > 8)
292 		errx(1, "%s: bad OEM string", optarg);
293 	    opt_O = optarg;
294 	    break;
295 	case 'S':
296 	    opt_S = argto2(optarg, 1, "bytes/sector");
297 	    break;
298 	case 'a':
299 	    opt_a = argto4(optarg, 1, "sectors/FAT");
300 	    break;
301 	case 'b':
302 	    opt_b = argtox(optarg, 1, "block size");
303 	    opt_c = 0;
304 	    break;
305 	case 'c':
306 	    opt_c = argto1(optarg, 1, "sectors/cluster");
307 	    opt_b = 0;
308 	    break;
309 	case 'e':
310 	    opt_e = argto2(optarg, 1, "directory entries");
311 	    break;
312 	case 'f':
313 	    opt_f = optarg;
314 	    break;
315 	case 'h':
316 	    opt_h = argto2(optarg, 1, "drive heads");
317 	    break;
318 	case 'i':
319 	    opt_i = argto2(optarg, 1, "info sector");
320 	    break;
321 	case 'k':
322 	    opt_k = argto2(optarg, 1, "backup sector");
323 	    break;
324 	case 'm':
325 	    opt_m = argto1(optarg, 0, "media descriptor");
326 	    mflag = 1;
327 	    break;
328 	case 'n':
329 	    opt_n = argto1(optarg, 1, "number of FATs");
330 	    break;
331 	case 'o':
332 	    opt_o = argto4(optarg, 0, "hidden sectors");
333 	    oflag = 1;
334 	    break;
335 	case 'q':			/* Compat with newfs -q */
336 	    break;
337 	case 'r':
338 	    opt_r = argto2(optarg, 1, "reserved sectors");
339 	    break;
340 	case 's':
341 	    opt_s = argto4(optarg, 1, "file system size");
342 	    break;
343 	case 't':			/* Compat with newfs -t */
344 	    break;
345 	case 'u':
346 	    opt_u = argto2(optarg, 1, "sectors/track");
347 	    break;
348 	default:
349 	    usage();
350 	}
351     argc -= optind;
352     argv += optind;
353     if (argc < 1 || argc > 2)
354 	usage();
355 #ifdef __FreeBSD__
356     fname = *argv++;
357     if (!strchr(fname, '/')) {
358 	snprintf(buf, sizeof(buf), "%sr%s", _PATH_DEV, fname);
359 	if (stat(buf, &sb))
360 	    snprintf(buf, sizeof(buf), "%s%s", _PATH_DEV, fname);
361 	if (!(fname = strdup(buf)))
362 	    err(1, NULL);
363     }
364 #endif
365 #ifdef __OpenBSD__
366     sname = *argv++;
367 #endif
368     dtype = *argv;
369 #ifdef __FreeBSD__
370     if ((fd = open(fname, opt_N ? O_RDONLY : O_RDWR)) == -1 ||
371 #else
372     if ((fd = opendev(sname, opt_N ? O_RDONLY : O_RDWR, 0, &fname)) == -1 ||
373 #endif
374 	fstat(fd, &sb))
375 	err(1, "%s", fname);
376     if (!opt_N)
377 	check_mounted(fname, sb.st_mode);
378     if (!S_ISCHR(sb.st_mode))
379 	warnx("warning: %s is not a character device", fname);
380     memset(&bpb, 0, sizeof(bpb));
381     if (opt_f) {
382 	getstdfmt(opt_f, &bpb);
383 	bpb.bsec = bpb.sec;
384 	bpb.sec = 0;
385 	bpb.bspf = bpb.spf;
386 	bpb.spf = 0;
387     }
388     if (opt_h)
389 	bpb.hds = opt_h;
390     if (opt_u)
391 	bpb.spt = opt_u;
392     if (opt_S)
393 	bpb.bps = opt_S;
394     if (opt_s)
395 	bpb.bsec = opt_s;
396     if (oflag)
397 	bpb.hid = opt_o;
398     if (!(opt_f || (opt_h && opt_u && opt_S && opt_s && oflag)))
399 	getdiskinfo(fd, fname, dtype, oflag, &bpb);
400     if (!powerof2(bpb.bps))
401 	errx(1, "bytes/sector (%u) is not a power of 2", bpb.bps);
402     if (bpb.bps < MINBPS)
403 	errx(1, "bytes/sector (%u) is too small; minimum is %u",
404 	     bpb.bps, MINBPS);
405     if (!(fat = opt_F)) {
406 	if (opt_f)
407 	    fat = 12;
408 	else if (!opt_e && (opt_i || opt_k))
409 	    fat = 32;
410     }
411     if ((fat == 32 && opt_e) || (fat != 32 && (opt_i || opt_k)))
412 	errx(1, "-%c is not a legal FAT%s option",
413 	     fat == 32 ? 'e' : opt_i ? 'i' : 'k',
414 	     fat == 32 ? "32" : "12/16");
415     if (opt_f && fat == 32)
416 	bpb.rde = 0;
417     if (opt_b) {
418 	if (!powerof2(opt_b))
419 	    errx(1, "block size (%u) is not a power of 2", opt_b);
420 	if (opt_b < bpb.bps)
421 	    errx(1, "block size (%u) is too small; minimum is %u",
422 		 opt_b, bpb.bps);
423 	if (opt_b > bpb.bps * MAXSPC)
424 	    errx(1, "block size (%u) is too large; maximum is %u",
425 		 opt_b, bpb.bps * MAXSPC);
426 	bpb.spc = opt_b / bpb.bps;
427     }
428     if (opt_c) {
429 	if (!powerof2(opt_c))
430 	    errx(1, "sectors/cluster (%u) is not a power of 2", opt_c);
431 	bpb.spc = opt_c;
432     }
433     if (opt_r)
434 	bpb.res = opt_r;
435     if (opt_n) {
436 	if (opt_n > MAXNFT)
437 	    errx(1, "number of FATs (%u) is too large; maximum is %u",
438 		 opt_n, MAXNFT);
439 	bpb.nft = opt_n;
440     }
441     if (opt_e)
442 	bpb.rde = opt_e;
443     if (mflag) {
444 	if (opt_m < 0xf0)
445 	    errx(1, "illegal media descriptor (%#x)", opt_m);
446 	bpb.mid = opt_m;
447     }
448     if (opt_a)
449 	bpb.bspf = opt_a;
450     if (opt_i)
451 	bpb.infs = opt_i;
452     if (opt_k)
453 	bpb.bkbs = opt_k;
454     bss = 1;
455     bname = NULL;
456     fd1 = -1;
457     if (opt_B) {
458 	bname = opt_B;
459 	if (!strchr(bname, '/')) {
460 	    snprintf(buf, sizeof(buf), "/boot/%s", bname);
461 	    if (!(bname = strdup(buf)))
462 		err(1, NULL);
463 	}
464 	if ((fd1 = open(bname, O_RDONLY)) == -1 || fstat(fd1, &sb))
465 	    err(1, "%s", bname);
466 	if (!S_ISREG(sb.st_mode) || sb.st_size % bpb.bps ||
467 	    sb.st_size < bpb.bps || sb.st_size > bpb.bps * MAXU16)
468 	    errx(1, "%s: inappropriate file type or format", bname);
469 	bss = sb.st_size / bpb.bps;
470     }
471     if (!bpb.nft)
472 	bpb.nft = 2;
473     if (!fat) {
474 	if (bpb.bsec < (bpb.res ? bpb.res : bss) +
475 	    howmany((RESFTE + (bpb.spc ? MINCLS16 : MAXCLS12 + 1)) *
476 		    ((bpb.spc ? 16 : 12) / BPN), bpb.bps * NPB) *
477 	    bpb.nft +
478 	    howmany(bpb.rde ? bpb.rde : DEFRDE,
479 		    bpb.bps / sizeof(struct de)) +
480 	    (bpb.spc ? MINCLS16 : MAXCLS12 + 1) *
481 	    (bpb.spc ? bpb.spc : howmany(DEFBLK, bpb.bps)))
482 	    fat = 12;
483 	else if (bpb.rde || bpb.bsec <
484 		 (bpb.res ? bpb.res : bss) +
485 		 howmany((RESFTE + MAXCLS16) * 2, bpb.bps) * bpb.nft +
486 		 howmany(DEFRDE, bpb.bps / sizeof(struct de)) +
487 		 (MAXCLS16 + 1) *
488 		 (bpb.spc ? bpb.spc : howmany(8192, bpb.bps)))
489 	    fat = 16;
490 	else
491 	    fat = 32;
492     }
493     x = bss;
494     if (fat == 32) {
495 	if (!bpb.infs) {
496 	    if (x == MAXU16 || x == bpb.bkbs)
497 		errx(1, "no room for info sector");
498 	    bpb.infs = x;
499 	}
500 	if (bpb.infs != MAXU16 && x <= bpb.infs)
501 	    x = bpb.infs + 1;
502 	if (!bpb.bkbs) {
503 	    if (x == MAXU16)
504 		errx(1, "no room for backup sector");
505 	    bpb.bkbs = x;
506 	} else if (bpb.bkbs != MAXU16 && bpb.bkbs == bpb.infs)
507 	    errx(1, "backup sector would overwrite info sector");
508 	if (bpb.bkbs != MAXU16 && x <= bpb.bkbs)
509 	    x = bpb.bkbs + 1;
510     }
511     if (!bpb.res)
512 	bpb.res = fat == 32 ? MAX(x, MAX(16384 / bpb.bps, 4)) : x;
513     else if (bpb.res < x)
514 	errx(1, "too few reserved sectors");
515     if (fat != 32 && !bpb.rde)
516 	bpb.rde = DEFRDE;
517     rds = howmany(bpb.rde, bpb.bps / sizeof(struct de));
518     if (!bpb.spc)
519 	for (bpb.spc = howmany(fat == 16 ? DEFBLK16 : DEFBLK, bpb.bps);
520 	     bpb.spc < MAXSPC &&
521 	     bpb.res +
522 	     howmany((RESFTE + maxcls(fat)) * (fat / BPN),
523 		     bpb.bps * NPB) * bpb.nft +
524 	     rds +
525 	     (u_int64_t)(maxcls(fat) + 1) * bpb.spc <= bpb.bsec;
526 	     bpb.spc <<= 1);
527     if (fat != 32 && bpb.bspf > MAXU16)
528 	errx(1, "too many sectors/FAT for FAT12/16");
529     x1 = bpb.res + rds;
530     x = bpb.bspf ? bpb.bspf : 1;
531     if (x1 + (u_int64_t)x * bpb.nft > bpb.bsec)
532 	errx(1, "meta data exceeds file system size");
533     x1 += x * bpb.nft;
534     x = (u_int64_t)(bpb.bsec - x1) * bpb.bps * NPB /
535 	(bpb.spc * bpb.bps * NPB + fat / BPN * bpb.nft);
536     x2 = howmany((RESFTE + MIN(x, maxcls(fat))) * (fat / BPN),
537 		 bpb.bps * NPB);
538     if (!bpb.bspf) {
539 	bpb.bspf = x2;
540 	x1 += (bpb.bspf - 1) * bpb.nft;
541     }
542     cls = (bpb.bsec - x1) / bpb.spc;
543     x = (u_int64_t)bpb.bspf * bpb.bps * NPB / (fat / BPN) - RESFTE;
544     if (cls > x)
545 	cls = x;
546     if (bpb.bspf < x2)
547 	warnx("warning: sectors/FAT limits file system to %u clusters",
548 	      cls);
549     if (cls < mincls(fat))
550 	errx(1, "%u clusters too few clusters for FAT%u, need %u", cls, fat,
551 	    mincls(fat));
552     if (cls > maxcls(fat)) {
553 	cls = maxcls(fat);
554 	bpb.bsec = x1 + (cls + 1) * bpb.spc - 1;
555 	warnx("warning: FAT type limits file system to %u sectors",
556 	      bpb.bsec);
557     }
558     printf("%s: %u sector%s in %u FAT%u cluster%s "
559 	   "(%u bytes/cluster)\n", fname, cls * bpb.spc,
560 	   cls * bpb.spc == 1 ? "" : "s", cls, fat,
561 	   cls == 1 ? "" : "s", bpb.bps * bpb.spc);
562     if (!bpb.mid)
563 	bpb.mid = !bpb.hid ? 0xf0 : 0xf8;
564     if (fat == 32)
565 	bpb.rdcl = RESFTE;
566     if (bpb.hid + bpb.bsec <= MAXU16) {
567 	bpb.sec = bpb.bsec;
568 	bpb.bsec = 0;
569     }
570     if (fat != 32) {
571 	bpb.spf = bpb.bspf;
572 	bpb.bspf = 0;
573     }
574     print_bpb(&bpb);
575     if (!opt_N) {
576 	gettimeofday(&tv, NULL);
577 	now = tv.tv_sec;
578 	tm = localtime(&now);
579 	if (!(img = malloc(bpb.bps)))
580 	    err(1, NULL);
581 	dir = bpb.res + (bpb.spf ? bpb.spf : bpb.bspf) * bpb.nft;
582 	for (lsn = 0; lsn < dir + (fat == 32 ? bpb.spc : rds); lsn++) {
583 	    x = lsn;
584 	    if (opt_B &&
585 		fat == 32 && bpb.bkbs != MAXU16 &&
586 		bss <= bpb.bkbs && x >= bpb.bkbs) {
587 		x -= bpb.bkbs;
588 		if (!x && lseek(fd1, 0, SEEK_SET))
589 		    err(1, "%s", bname);
590 	    }
591 	    if (opt_B && x < bss) {
592 		if ((n = read(fd1, img, bpb.bps)) == -1)
593 		    err(1, "%s", bname);
594 		if (n != bpb.bps)
595 		    errx(1, "%s: can't read sector %u", bname, x);
596 	    } else
597 		memset(img, 0, bpb.bps);
598 	    if (!lsn ||
599 	      (fat == 32 && bpb.bkbs != MAXU16 && lsn == bpb.bkbs)) {
600 		x1 = sizeof(struct bs);
601 		bsbpb = (struct bsbpb *)(img + x1);
602 		mk2(bsbpb->bps, bpb.bps);
603 		mk1(bsbpb->spc, bpb.spc);
604 		mk2(bsbpb->res, bpb.res);
605 		mk1(bsbpb->nft, bpb.nft);
606 		mk2(bsbpb->rde, bpb.rde);
607 		mk2(bsbpb->sec, bpb.sec);
608 		mk1(bsbpb->mid, bpb.mid);
609 		mk2(bsbpb->spf, bpb.spf);
610 		mk2(bsbpb->spt, bpb.spt);
611 		mk2(bsbpb->hds, bpb.hds);
612 		mk4(bsbpb->hid, bpb.hid);
613 		mk4(bsbpb->bsec, bpb.bsec);
614 		x1 += sizeof(struct bsbpb);
615 		if (fat == 32) {
616 		    bsxbpb = (struct bsxbpb *)(img + x1);
617 		    mk4(bsxbpb->bspf, bpb.bspf);
618 		    mk2(bsxbpb->xflg, 0);
619 		    mk2(bsxbpb->vers, 0);
620 		    mk4(bsxbpb->rdcl, bpb.rdcl);
621 		    mk2(bsxbpb->infs, bpb.infs);
622 		    mk2(bsxbpb->bkbs, bpb.bkbs);
623 		    x1 += sizeof(struct bsxbpb);
624 		}
625 		bsx = (struct bsx *)(img + x1);
626 		mk1(bsx->sig, 0x29);
627 		if (Iflag)
628 		    x = opt_I;
629 		else
630 		    x = (((u_int)(1 + tm->tm_mon) << 8 |
631 			  (u_int)tm->tm_mday) +
632 			 ((u_int)tm->tm_sec << 8 |
633 			  (u_int)(tv.tv_usec / 10))) << 16 |
634 			((u_int)(1900 + tm->tm_year) +
635 			 ((u_int)tm->tm_hour << 8 |
636 			  (u_int)tm->tm_min));
637 		mk4(bsx->volid, x);
638 		mklabel(bsx->label, opt_L ? opt_L : "NO NAME");
639 		snprintf(buf, sizeof buf, "FAT%u", fat);
640 		setstr(bsx->type, buf, sizeof(bsx->type));
641 		if (!opt_B) {
642 		    x1 += sizeof(struct bsx);
643 		    bs = (struct bs *)img;
644 		    mk1(bs->jmp[0], 0xeb);
645 		    mk1(bs->jmp[1], x1 - 2);
646 		    mk1(bs->jmp[2], 0x90);
647 		    setstr(bs->oem, opt_O ? opt_O : "BSD  4.4",
648 			   sizeof(bs->oem));
649 		    memcpy(img + x1, bootcode, sizeof(bootcode));
650 		    mk2(img + bpb.bps - 2, DOSMAGIC);
651 		}
652 	    } else if (fat == 32 && bpb.infs != MAXU16 &&
653 		       (lsn == bpb.infs ||
654 			(bpb.bkbs != MAXU16 &&
655 			 lsn == bpb.bkbs + bpb.infs))) {
656 		mk4(img, 0x41615252);
657 		mk4(img + bpb.bps - 28, 0x61417272);
658 		mk4(img + bpb.bps - 24, 0xffffffff);
659 		mk4(img + bpb.bps - 20, bpb.rdcl);
660 		mk2(img + bpb.bps - 2, DOSMAGIC);
661 	    } else if (lsn >= bpb.res && lsn < dir &&
662 		       !((lsn - bpb.res) %
663 			 (bpb.spf ? bpb.spf : bpb.bspf))) {
664 		mk1(img[0], bpb.mid);
665 		for (x = 1; x < fat * (fat == 32 ? 3 : 2) / 8; x++)
666 		    mk1(img[x], fat == 32 && x % 4 == 3 ? 0x0f : 0xff);
667 	    } else if (lsn == dir && opt_L) {
668 		de = (struct de *)img;
669 		mklabel(de->namext, opt_L);
670 		mk1(de->attr, 050);
671 		x = (u_int)tm->tm_hour << 11 |
672 		    (u_int)tm->tm_min << 5 |
673 		    (u_int)tm->tm_sec >> 1;
674 		mk2(de->time, x);
675 		x = (u_int)(tm->tm_year - 80) << 9 |
676 		    (u_int)(tm->tm_mon + 1) << 5 |
677 		    (u_int)tm->tm_mday;
678 		mk2(de->date, x);
679 	    }
680 	    if ((n = write(fd, img, bpb.bps)) == -1)
681 		err(1, "%s", fname);
682 	    if (n != bpb.bps)
683 		errx(1, "%s: can't write sector %u", fname, lsn);
684 	}
685     }
686     return 0;
687 }
688 
689 /*
690  * Exit with error if file system is mounted.
691  */
692 static void
check_mounted(const char * fname,mode_t mode)693 check_mounted(const char *fname, mode_t mode)
694 {
695     struct statfs *mp;
696     const char *s1, *s2;
697     size_t len;
698     int n, r;
699 
700     if (!(n = getmntinfo(&mp, MNT_NOWAIT)))
701 	err(1, "getmntinfo");
702     len = sizeof(_PATH_DEV) - 1;
703     s1 = fname;
704     if (!strncmp(s1, _PATH_DEV, len))
705 	s1 += len;
706     r = S_ISCHR(mode) && s1 != fname && *s1 == 'r';
707     for (; n--; mp++) {
708 	s2 = mp->f_mntfromname;
709 	if (!strncmp(s2, _PATH_DEV, len))
710 	    s2 += len;
711 	if ((r && s2 != mp->f_mntfromname && !strcmp(s1 + 1, s2)) ||
712 	    !strcmp(s1, s2))
713 	    errx(1, "%s is mounted on %s", fname, mp->f_mntonname);
714     }
715 }
716 
717 /*
718  * Get a standard format.
719  */
720 static void
getstdfmt(const char * fmt,struct bpb * bpb)721 getstdfmt(const char *fmt, struct bpb *bpb)
722 {
723     u_int x, i;
724 
725     x = sizeof(stdfmt) / sizeof(stdfmt[0]);
726     for (i = 0; i < x && strcmp(fmt, stdfmt[i].name); i++);
727     if (i == x)
728 	errx(1, "%s: unknown standard format", fmt);
729     *bpb = stdfmt[i].bpb;
730 }
731 
732 /*
733  * Get disk slice, partition, and geometry information.
734  */
735 static void
getdiskinfo(int fd,const char * fname,const char * dtype,int oflag,struct bpb * bpb)736 getdiskinfo(int fd, const char *fname, const char *dtype, int oflag,
737 	    struct bpb *bpb)
738 {
739 #ifdef __FreeBSD__
740     struct diskslices ds;
741     int slice = -1;
742     char *s;
743     int fd1, e;
744 #endif
745     struct disklabel dl, *lp;
746     const char *s1, *s2;
747     int part, i;
748 
749     part = -1;
750     s1 = fname;
751     if ((s2 = strrchr(s1, '/')))
752 	s1 = s2 + 1;
753     for (s2 = s1; *s2 && !isdigit(*s2); s2++);
754     if (!*s2 || s2 == s1)
755 	s2 = NULL;
756     else
757 	while (isdigit(*++s2));
758     s1 = s2;
759 #ifdef __FreeBSD__
760     if (s2 && *s2 == 's') {
761 	slice = strtol(s2 + 1, &s, 10);
762 	if (slice < 1 || slice > MAX_SLICES - BASE_SLICE)
763 	    s2 = NULL;
764 	else {
765 	    slice = BASE_SLICE + slice - 1;
766 	    s2 = s;
767 	}
768     }
769 #endif
770     if (s2 && *s2 >= 'a' && *s2 <= 'a' + MAXPARTITIONS - 1) {
771 #ifdef __FreeBSD__
772 	if (slice == -1)
773 	    slice = COMPATIBILITY_SLICE;
774 #endif
775 	part = *s2++ - 'a';
776     }
777     if (!s2 || (*s2 && *s2 != '.'))
778 	errx(1, "%s: can't figure out partition info", fname);
779 #ifdef __FreeBSD__
780     if (slice != -1 && (!oflag || (!bpb->bsec && part == -1))) {
781 	if (ioctl(fd, DIOCGSLICEINFO, &ds) == -1) {
782 	    warn("ioctl (GSLICEINFO)");
783 	    errx(1, "%s: can't get slice info", fname);
784 	}
785 	if (slice >= ds.dss_nslices || !ds.dss_slices[slice].ds_size)
786 	    errx(1, "%s: slice is unavailable", fname);
787 	if (!oflag)
788 	    bpb->hid = ds.dss_slices[slice].ds_offset;
789 	if (!bpb->bsec && part == -1)
790 	    bpb->bsec = ds.dss_slices[slice].ds_size;
791     }
792     if (((slice == -1 || part != -1) &&
793 	 ((!oflag && part != -1) || !bpb->bsec)) ||
794 	!bpb->bps || !bpb->spt || !bpb->hds) {
795 	lp = &dl;
796 	i = ioctl(fd, DIOCGDINFO, lp);
797 	if (i == -1 && slice != -1 && part == -1) {
798 	    e = errno;
799 	    if (!(s = strdup(fname)))
800 		err(1, NULL);
801 	    s[s1 - fname] = 0;
802 	    if ((fd1 = open(s, O_RDONLY)) != -1) {
803 		i = ioctl(fd1, DIOCGDINFO, lp);
804 		close(fd1);
805 	    }
806 	    free(s);
807 	    errno = e;
808 	}
809 	if (i == -1) {
810 	    if (!dtype) {
811 		warn("ioctl (GDINFO)");
812 		errx(1, "%s: can't read disk label; "
813 		     "disk type must be specified", fname);
814 	    } else if (!(lp = getdiskbyname(dtype)))
815 		errx(1, "%s: unknown disk type", dtype);
816 	}
817 	if (slice == -1 || part != -1) {
818 	    if (part == -1)
819 		part = RAW_PART;
820 	    if (part >= lp->d_npartitions ||
821 		!lp->d_partitions[part].p_size)
822 		errx(1, "%s: partition is unavailable", fname);
823 	    if (!oflag && part != -1)
824 		bpb->hid += lp->d_partitions[part].p_offset;
825 	    if (!bpb->bsec)
826 		bpb->bsec = lp->d_partitions[part].p_size;
827 	}
828 	if (!bpb->bps)
829 	    bpb->bps = ckgeom(fname, lp->d_secsize, "bytes/sector");
830 	if (!bpb->spt)
831 	    bpb->spt = ckgeom(fname, lp->d_nsectors, "sectors/track");
832 	if (!bpb->hds)
833 	    bpb->hds = ckgeom(fname, lp->d_ntracks, "drive heads");
834     }
835 #endif
836 #ifdef __OpenBSD__
837     if ((((!oflag && part != -1) || !bpb->bsec)) ||
838 	!bpb->bps || !bpb->spt || !bpb->hds) {
839 	lp = &dl;
840 	i = ioctl(fd, DIOCGDINFO, lp);
841 	if (i == -1) {
842 	    if (!dtype) {
843 		warn("ioctl (GDINFO)");
844 		errx(1, "%s: can't read disk label; "
845 		     "disk type must be specified", fname);
846 	    } else if (!(lp = getdiskbyname(dtype)))
847 		errx(1, "%s: unknown disk type", dtype);
848 	}
849 	if (part == -1)
850 	    part = RAW_PART;
851 	if (part >= lp->d_npartitions ||
852 	    !lp->d_partitions[part].p_size)
853 	    errx(1, "%s: partition is unavailable", fname);
854 	if (!oflag && part != -1)
855 	    bpb->hid += lp->d_partitions[part].p_offset;
856 	if (!bpb->bsec)
857 	    bpb->bsec = lp->d_partitions[part].p_size;
858 	if (!bpb->bps)
859 	    bpb->bps = ckgeom(fname, lp->d_secsize, "bytes/sector");
860 	if (!bpb->spt)
861 	    bpb->spt = ckgeom(fname, lp->d_nsectors, "sectors/track");
862 	if (!bpb->hds)
863 	    bpb->hds = ckgeom(fname, lp->d_ntracks, "drive heads");
864 	if (bpb->spt > 63) {
865 	    bpb->hds = bpb->hds * bpb->spt / 63;
866 	    bpb->spt = 63;
867 	}
868     }
869 #endif
870 }
871 
872 /*
873  * Print out BPB values.
874  */
875 static void
print_bpb(struct bpb * bpb)876 print_bpb(struct bpb *bpb)
877 {
878     printf("bps=%u spc=%u res=%u nft=%u", bpb->bps, bpb->spc, bpb->res,
879 	   bpb->nft);
880     if (bpb->rde)
881 	printf(" rde=%u", bpb->rde);
882     if (bpb->sec)
883 	printf(" sec=%u", bpb->sec);
884     printf(" mid=%#x", bpb->mid);
885     if (bpb->spf)
886 	printf(" spf=%u", bpb->spf);
887     printf(" spt=%u hds=%u hid=%u", bpb->spt, bpb->hds, bpb->hid);
888     if (bpb->bsec)
889 	printf(" bsec=%u", bpb->bsec);
890     if (!bpb->spf) {
891 	printf(" bspf=%u rdcl=%u", bpb->bspf, bpb->rdcl);
892 	printf(" infs=");
893 	printf(bpb->infs == MAXU16 ? "%#x" : "%u", bpb->infs);
894 	printf(" bkbs=");
895 	printf(bpb->bkbs == MAXU16 ? "%#x" : "%u", bpb->bkbs);
896     }
897     printf("\n");
898 }
899 
900 /*
901  * Check a disk geometry value.
902  */
903 static u_int
ckgeom(const char * fname,u_int val,const char * msg)904 ckgeom(const char *fname, u_int val, const char *msg)
905 {
906     if (!val)
907 	errx(1, "%s: no default %s", fname, msg);
908     if (val > MAXU16)
909 	errx(1, "%s: illegal %s", fname, msg);
910     return val;
911 }
912 
913 /*
914  * Convert and check a numeric option argument.
915  */
916 static u_int
argtou(const char * arg,u_int lo,u_int hi,const char * msg)917 argtou(const char *arg, u_int lo, u_int hi, const char *msg)
918 {
919     char *s;
920     u_long x;
921 
922     errno = 0;
923     x = strtoul(arg, &s, 0);
924     if (errno || !*arg || *s || x < lo || x > hi)
925 	errx(1, "%s: bad %s", arg, msg);
926     return x;
927 }
928 
929 /*
930  * Check a volume label.
931  */
932 static int
oklabel(const char * src)933 oklabel(const char *src)
934 {
935     int c = 0, i;
936 
937     for (i = 0; i <= 11; i++) {
938 	c = (u_char)*src++;
939 	if (c < ' ' + !i || strchr("\"*+,./:;<=>?[\\]|", c))
940 	    break;
941     }
942     return i && !c;
943 }
944 
945 /*
946  * Make a volume label.
947  */
948 static void
mklabel(u_int8_t * dest,const char * src)949 mklabel(u_int8_t *dest, const char *src)
950 {
951     int c, i;
952 
953     for (i = 0; i < 11; i++) {
954 	c = *src ? toupper(*src++) : ' ';
955 	*dest++ = !i && c == '\xe5' ? 5 : c;
956     }
957 }
958 
959 /*
960  * Copy string, padding with spaces.
961  */
962 static void
setstr(u_int8_t * dest,const char * src,size_t len)963 setstr(u_int8_t *dest, const char *src, size_t len)
964 {
965     while (len--)
966 	*dest++ = *src ? *src++ : ' ';
967 }
968 
969 /*
970  * Print usage message.
971  */
972 static void
usage(void)973 usage(void)
974 {
975     fprintf(stderr,
976 	    "usage: newfs_msdos [ -options ] special [disktype]\n");
977     fprintf(stderr, "where the options are:\n");
978     fprintf(stderr, "\t-N don't create file system: "
979 	    "just print out parameters\n");
980     fprintf(stderr, "\t-B get bootstrap from file\n");
981     fprintf(stderr, "\t-F FAT type (12, 16, or 32)\n");
982     fprintf(stderr, "\t-I volume ID\n");
983     fprintf(stderr, "\t-L volume label\n");
984     fprintf(stderr, "\t-O OEM string\n");
985     fprintf(stderr, "\t-S bytes/sector\n");
986     fprintf(stderr, "\t-a sectors/FAT\n");
987     fprintf(stderr, "\t-b block size\n");
988     fprintf(stderr, "\t-c sectors/cluster\n");
989     fprintf(stderr, "\t-e root directory entries\n");
990     fprintf(stderr, "\t-f standard format\n");
991     fprintf(stderr, "\t-h drive heads\n");
992     fprintf(stderr, "\t-i file system info sector\n");
993     fprintf(stderr, "\t-k backup boot sector\n");
994     fprintf(stderr, "\t-m media descriptor\n");
995     fprintf(stderr, "\t-n number of FATs\n");
996     fprintf(stderr, "\t-o hidden sectors\n");
997     fprintf(stderr, "\t-r reserved sectors\n");
998     fprintf(stderr, "\t-s file system size (sectors)\n");
999     fprintf(stderr, "\t-u sectors/track\n");
1000     exit(1);
1001 }
1002