1/*
2 * Copyright (c) 2000-2006, 2008, 2010-2011 Apple Inc. All rights reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
11 * file.
12 *
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
20 *
21 * @APPLE_LICENSE_HEADER_END@
22 */
23/*
24 * Copyright (c) 1998 Robert Nordier
25 * All rights reserved.
26 *
27 * Redistribution and use in source and binary forms, with or without
28 * modification, are permitted provided that the following conditions
29 * are met:
30 * 1. Redistributions of source code must retain the above copyright
31 *    notice, this list of conditions and the following disclaimer.
32 * 2. Redistributions in binary form must reproduce the above copyright
33 *    notice, this list of conditions and the following disclaimer in
34 *    the documentation and/or other materials provided with the
35 *    distribution.
36 *
37 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS
38 * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
39 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
40 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY
41 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
42 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
43 * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
44 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
45 * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
46 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
47 * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
48 */
49
50
51#include <sys/param.h>
52#include <sys/time.h>
53#include <sys/stat.h>
54#include <sys/mount.h>
55#include <sys/ioctl.h>
56#include <sys/disk.h>
57
58#include <ctype.h>
59#include <err.h>
60#include <errno.h>
61#include <fcntl.h>
62#include <paths.h>
63#include <stdio.h>
64#include <stdlib.h>
65#include <string.h>
66#include <unistd.h>
67#include <wipefs.h>
68
69#include <IOKit/IOKitLib.h>
70#include <IOKit/storage/IOStorageCardCharacteristics.h>
71
72/* ioctl selector to get the offset of the current partition
73 * from the start of the disk to initialize hidden sectors
74 * value in the boot sector.
75 *
76 * Note: This ioctl selector is not available in userspace
77 * and we are assuming its existence by defining it here.
78 * This behavior can change in future.
79 */
80#ifndef DKIOCGETBASE
81#define DKIOCGETBASE	_IOR('d', 73, uint64_t)
82#endif
83
84#define MAXU16	  0xffff	/* maximum unsigned 16-bit quantity */
85#define BPN	  4		/* bits per nibble */
86#define NPB	  2		/* nibbles per byte */
87
88#define DOSMAGIC  0xaa55	/* DOS magic number */
89#define MINBPS	  128		/* minimum bytes per sector */
90#define MAXBPS    4096		/* maximum bytes per sector */
91#define MAXSPC	  128		/* maximum sectors per cluster */
92#define MAXNFT	  16		/* maximum number of FATs */
93#define DEFBLK	  4096		/* default block size */
94#define DEFBLK16  2048		/* default block size FAT16 */
95#define DEFRDE	  512		/* default root directory entries */
96#define RESFTE	  2		/* reserved FAT entries */
97
98/*
99 * The size of our in-memory I/O buffer.  This is the size of the writes we
100 * do to the device (except perhaps a few odd sectors at the end).
101 *
102 * This must be a multiple of the sector size.  Larger is generally faster,
103 * but some old devices have bugs if you ask them to do more than 128KB
104 * per I/O.
105 */
106#define IO_BUFFER_SIZE	(128*1024)
107
108/*
109 * [2873845]  FAT12 volumes can have 1..4084 clusters.  FAT16 can have
110 * 4085..65524 clusters.  FAT32 is 65525 clusters or more.
111 * Since many other implementations are off by 1, 2, 4, 8, 10, or 16,
112 * Microsoft recommends staying at least 16 clusters away from these
113 * boundary points.  They also recommend that FAT32 volumes avoid
114 * making the bad cluster mark an allocatable cluster number.
115 *
116 * So, the minimum and maximum values listed below aren't the strict
117 * limits (smaller or larger values may work on more robust implementations).
118 * The limits below are safe limits that should be compatible with a
119 * wide variety of implementations.
120 */
121#define MINCLS12  1		/* minimum FAT12 clusters */
122#define MINCLS16  4085		/* minimum FAT16 clusters */
123#define MINCLS32  65525		/* minimum FAT32 clusters */
124#define MAXCLS12  4084 		/* maximum FAT12 clusters */
125#define MAXCLS16  65524		/* maximum FAT16 clusters */
126#define MAXCLS32  0x0FFFFFF5	/* maximum FAT32 clusters */
127
128#define BACKUP_BOOT_SECTOR 6	/* Default location for backup boot sector on FAT32 */
129#define FAT32_RESERVED_SECTORS 32
130
131#define mincls(fat)  ((fat) == 12 ? MINCLS12 :	\
132		      (fat) == 16 ? MINCLS16 :	\
133				    MINCLS32)
134
135#define maxcls(fat)  ((fat) == 12 ? MAXCLS12 :	\
136		      (fat) == 16 ? MAXCLS16 :	\
137				    MAXCLS32)
138
139#define mk1(p, x)				\
140    (p) = (u_int8_t)(x)
141
142#define mk2(p, x)				\
143    (p)[0] = (u_int8_t)(x),			\
144    (p)[1] = (u_int8_t)((x) >> 010)
145
146#define mk4(p, x)				\
147    (p)[0] = (u_int8_t)(x),			\
148    (p)[1] = (u_int8_t)((x) >> 010),		\
149    (p)[2] = (u_int8_t)((x) >> 020),		\
150    (p)[3] = (u_int8_t)((x) >> 030)
151
152#define argto1(arg, lo, msg)  argtou(arg, lo, 0xff, msg)
153#define argto2(arg, lo, msg)  argtou(arg, lo, 0xffff, msg)
154#define argto4(arg, lo, msg)  argtou(arg, lo, 0xffffffff, msg)
155#define argtox(arg, lo, msg)  argtou(arg, lo, UINT_MAX, msg)
156
157struct bs {
158    u_int8_t jmp[3];		/* bootstrap entry point */
159    u_int8_t oem[8];		/* OEM name and version */
160};
161
162struct bsbpb {
163    u_int8_t bps[2];		/* bytes per sector */
164    u_int8_t spc;		/* sectors per cluster */
165    u_int8_t res[2];		/* reserved sectors */
166    u_int8_t nft;		/* number of FATs */
167    u_int8_t rde[2];		/* root directory entries */
168    u_int8_t sec[2];		/* total sectors */
169    u_int8_t mid;		/* media descriptor */
170    u_int8_t spf[2];		/* sectors per FAT */
171    u_int8_t spt[2];		/* sectors per track */
172    u_int8_t hds[2];		/* drive heads */
173    u_int8_t hid[4];		/* hidden sectors */
174    u_int8_t bsec[4];		/* big total sectors */
175};
176
177struct bsxbpb {
178    u_int8_t bspf[4];		/* big sectors per FAT */
179    u_int8_t xflg[2];		/* FAT control flags */
180    u_int8_t vers[2];		/* file system version */
181    u_int8_t rdcl[4];		/* root directory start cluster */
182    u_int8_t infs[2];		/* file system info sector */
183    u_int8_t bkbs[2];		/* backup boot sector */
184    u_int8_t rsvd[12];		/* reserved */
185};
186
187struct bsx {
188    u_int8_t drv;		/* drive number */
189    u_int8_t rsvd;		/* reserved */
190    u_int8_t sig;		/* extended boot signature */
191    u_int8_t volid[4];		/* volume ID number */
192    u_int8_t label[11]; 	/* volume label */
193    u_int8_t type[8];		/* file system type */
194};
195
196struct de {
197    u_int8_t namext[11];	/* name and extension */
198    u_int8_t attr;		/* attributes */
199    u_int8_t rsvd[10];		/* reserved */
200    u_int8_t time[2];		/* creation time */
201    u_int8_t date[2];		/* creation date */
202    u_int8_t clus[2];		/* starting cluster */
203    u_int8_t size[4];		/* size */
204};
205
206struct bpb {
207    u_int bps;			/* bytes per sector */
208    u_int spc;			/* sectors per cluster */
209    u_int res;			/* reserved sectors */
210    u_int nft;			/* number of FATs */
211    u_int rde;			/* root directory entries */
212    u_int sec;			/* total sectors */
213    u_int mid;			/* media descriptor */
214    u_int spf;			/* sectors per FAT */
215    u_int spt;			/* sectors per track */
216    u_int hds;			/* drive heads */
217    u_int hid;			/* hidden sectors */
218    u_int bsec; 		/* big total sectors */
219    u_int bspf; 		/* big sectors per FAT */
220    u_int rdcl; 		/* root directory start cluster */
221    u_int infs; 		/* file system info sector */
222    u_int bkbs; 		/* backup boot sector */
223    u_int driveNum;             /* INT 0x13 drive number (0x00 or 0x80) */
224};
225
226static struct {
227    const char *name;
228    struct bpb bpb;
229} stdfmt[] = {
230    {"160",  {512, 1, 1, 2,  64,  320, 0xfe, 1,  8, 1}},
231    {"180",  {512, 1, 1, 2,  64,  360, 0xfc, 2,  9, 1}},
232    {"320",  {512, 2, 1, 2, 112,  640, 0xff, 1,  8, 2}},
233    {"360",  {512, 2, 1, 2, 112,  720, 0xfd, 2,  9, 2}},
234    {"640",  {512, 2, 1, 2, 112, 1280, 0xfb, 2,  8, 2}},
235    {"720",  {512, 2, 1, 2, 112, 1440, 0xf9, 3,  9, 2}},
236    {"1200", {512, 1, 1, 2, 224, 2400, 0xf9, 7, 15, 2}},
237    {"1232", {1024,1, 1, 2, 192, 1232, 0xfe, 2,  8, 2}},
238    {"1440", {512, 1, 1, 2, 224, 2880, 0xf0, 9, 18, 2}},
239    {"2880", {512, 2, 1, 2, 240, 5760, 0xf0, 9, 36, 2}}
240};
241
242static u_int8_t bootcode[] = {
243    0xfa,			/* cli		    */
244    0x31, 0xc0, 		/* xor	   ax,ax    */
245    0x8e, 0xd0, 		/* mov	   ss,ax    */
246    0xbc, 0x00, 0x7c,		/* mov	   sp,7c00h */
247    0xfb,			/* sti		    */
248    0x8e, 0xd8, 		/* mov	   ds,ax    */
249    0xe8, 0x00, 0x00,		/* call    $ + 3    */
250    0x5e,			/* pop	   si	    */
251    0x83, 0xc6, 0x19,		/* add	   si,+19h  */
252    0xbb, 0x07, 0x00,		/* mov	   bx,0007h */
253    0xfc,			/* cld		    */
254    0xac,			/* lodsb	    */
255    0x84, 0xc0, 		/* test    al,al    */
256    0x74, 0x06, 		/* jz	   $ + 8    */
257    0xb4, 0x0e, 		/* mov	   ah,0eh   */
258    0xcd, 0x10, 		/* int	   10h	    */
259    0xeb, 0xf5, 		/* jmp	   $ - 9    */
260    0x30, 0xe4, 		/* xor	   ah,ah    */
261    0xcd, 0x16, 		/* int	   16h	    */
262    0xcd, 0x19, 		/* int	   19h	    */
263    0x0d, 0x0a,
264    'N', 'o', 'n', '-', 's', 'y', 's', 't',
265    'e', 'm', ' ', 'd', 'i', 's', 'k',
266    0x0d, 0x0a,
267    'P', 'r', 'e', 's', 's', ' ', 'a', 'n',
268    'y', ' ', 'k', 'e', 'y', ' ', 't', 'o',
269    ' ', 'r', 'e', 'b', 'o', 'o', 't',
270    0x0d, 0x0a,
271    0
272};
273
274/*
275 * These values define the default crossover points for selecting the default
276 * FAT type.  The intent here is to have the crossover points be the same as
277 * Microsoft documents, at least for 512 bytes per sector devices.  As much
278 * as possible, the same crossover point (in terms of bytes per volume) is used
279 * for larger sector sizes.  But the 4.1MB crossover between FAT12 and FAT16
280 * is not achievable for sector sizes larger than 1KB since it would result
281 * in fewer than 4085 clusters, making FAT16 impossible; in that case, the
282 * crossover is in terms of sectors, not bytes.
283 *
284 * Note that the FAT16 to FAT32 crossover is only good for sector sizes up to
285 * and including 4KB.  For larger sector sizes, there would be too few clusters
286 * for FAT32.
287 */
288enum {
289    MAX_SEC_FAT12_512	= 8400,	    /* (4.1 MB) Maximum 512 byte sectors to default to FAT12 */
290    MAX_SEC_FAT12	= 4200,	    /* Maximum sectors (>512 bytes) to default to FAT12 */
291    MAX_KB_FAT16	= 524288    /* (512 MiB) Maximum kilobytes to default to FAT16 */
292};
293
294/*
295 * [2873851] Tables of default cluster sizes for FAT16 and FAT32.
296 *
297 * These constants are derived from Microsoft's documentation, but adjusted
298 * to represent kilobytes of volume size, not a number of 512-byte sectors.
299 * Also, this table uses default cluster size, not sectors per cluster, so
300 * that it can be independent of sector size.
301 */
302
303struct DiskSizeToClusterSize {
304    u_int32_t kilobytes;	    /* input: maximum kilobytes */
305    u_int32_t bytes_per_cluster;    /* output: desired cluster size (in bytes) */
306};
307
308struct DiskSizeToClusterSize fat16Sizes[] = {
309    {   4200,        0},    /* Disks up to 4.1 MB; the 0 triggers an error */
310    {  16340,     1024},    /* Disks up to  16 MB => 1 KB cluster */
311    { 131072,     2048},    /* Disks up to 128 MB => 2 KB cluster */
312    { 262144,     4096},    /* Disks up to 256 MB => 4 KB cluster */
313    { 524288,     8192},    /* Disks up to 512 MB => 8 KB cluster */
314    /* The following entries are used only if FAT16 is forced */
315    {1048576,    16384},    /* Disks up to 1 GB => 16 KB cluster */
316    {UINT32_MAX, 32768}	    /* Disks over 2 GB => 32KB cluster (total size may be limited) */
317};
318struct DiskSizeToClusterSize fat32Sizes[] = {
319    {   33300,       0},    /* Disks up to 32.5 MB; the 0 triggers an error */
320    {  266240,     512},    /* Disks up to 260 MB => 512 byte cluster; not used unles FAT32 forced */
321    { 8388608,    4096},    /* Disks up to   8 GB =>  4 KB cluster */
322    {16777216,    8192},    /* Disks up to  16 GB =>  8 KB cluster */
323    {33554432,   16384},    /* Disks up to  32 GB => 16 KB cluster */
324    {UINT32_MAX, 32768}	    /* Disks over 32 GB => 32 KB cluster */
325};
326
327enum SDCardType {
328    kCardTypeNone   =	0,
329    kCardTypeSDSC,
330    kCardTypeSDHC,
331    kCardTypeSDXC
332};
333
334static void check_mounted(const char *, mode_t);
335static void getstdfmt(const char *, struct bpb *);
336static void getdiskinfo(int, const char *, const char *, int,
337			struct bpb *);
338static enum SDCardType sd_card_type_for_path(const char *path);
339static void sd_card_set_defaults(const char *path, u_int *fat, struct bpb *bpb);
340static void print_bpb(struct bpb *);
341static u_int argtou(const char *, u_int, u_int, const char *);
342static int oklabel(const char *);
343static void mklabel(u_int8_t *, const char *);
344static void setstr(u_int8_t *, const char *, size_t);
345static void usage(void);
346
347/*
348 * Construct a FAT12, FAT16, or FAT32 file system.
349 */
350int
351main(int argc, char *argv[])
352{
353    static char opts[] = "NB:F:I:O:S:P:a:b:c:e:f:h:i:k:m:n:o:r:s:u:v:";
354    static const char *opt_B, *opt_v, *opt_O, *opt_f;
355    static u_int opt_F, opt_I, opt_S, opt_a, opt_b, opt_c, opt_e;
356    static u_int opt_h, opt_i, opt_k, opt_m, opt_n, opt_o, opt_r;
357    static u_int opt_s, opt_u, opt_P;
358    static int opt_N;
359    static int Iflag, mflag, oflag;
360    char buf[MAXPATHLEN];
361    struct stat sb;
362    struct timeval tv;
363    struct bpb bpb;
364    struct tm *tm;
365    struct bs *bs;
366    struct bsbpb *bsbpb;
367    struct bsxbpb *bsxbpb;
368    struct bsx *bsx;
369    struct de *de;
370    u_int8_t *bpb_buffer;
371    u_int8_t *io_buffer;    /* The buffer for sectors being constructed/written */
372    u_int8_t *img;	    /* Current sector within io_buffer */
373    const char *fname, *dtype, *bname;
374    ssize_t n;
375    time_t now;
376    u_int fat, bss, rds, cls, dir, lsn, x, x1, x2;
377    int ch, fd, fd1;
378
379    while ((ch = getopt(argc, argv, opts)) != -1)
380	switch (ch) {
381	case 'N':
382	    opt_N = 1;
383	    break;
384	case 'B':
385	    opt_B = optarg;
386	    break;
387	case 'F':
388	    if (strcmp(optarg, "12") &&
389		strcmp(optarg, "16") &&
390		strcmp(optarg, "32"))
391		errx(1, "%s: bad FAT type", optarg);
392	    opt_F = atoi(optarg);
393	    break;
394	case 'I':
395	    opt_I = argto4(optarg, 0, "volume ID");
396	    Iflag = 1;
397	    break;
398	case 'O':
399	    if (strlen(optarg) > 8)
400		errx(1, "%s: bad OEM string", optarg);
401	    opt_O = optarg;
402	    break;
403	case 'S':
404	    opt_S = argto2(optarg, 1, "bytes/sector");
405	    break;
406	case 'P':
407	    opt_P = argto2(optarg, 1, "physical bytes/sector");
408	    break;
409	case 'a':
410	    opt_a = argto4(optarg, 1, "sectors/FAT");
411	    break;
412	case 'b':
413	    opt_b = argtox(optarg, 1, "block size");
414	    opt_c = 0;
415	    break;
416	case 'c':
417	    opt_c = argto1(optarg, 1, "sectors/cluster");
418	    opt_b = 0;
419	    break;
420	case 'e':
421	    opt_e = argto2(optarg, 1, "directory entries");
422	    break;
423	case 'f':
424	    opt_f = optarg;
425	    break;
426	case 'h':
427	    opt_h = argto2(optarg, 1, "drive heads");
428	    break;
429	case 'i':
430	    opt_i = argto2(optarg, 1, "info sector");
431	    break;
432	case 'k':
433	    opt_k = argto2(optarg, 1, "backup sector");
434	    break;
435	case 'm':
436	    opt_m = argto1(optarg, 0, "media descriptor");
437	    mflag = 1;
438	    break;
439	case 'n':
440	    opt_n = argto1(optarg, 1, "number of FATs");
441	    break;
442	case 'o':
443	    opt_o = argto4(optarg, 0, "hidden sectors");
444	    oflag = 1;
445	    break;
446	case 'r':
447	    opt_r = argto2(optarg, 1, "reserved sectors");
448	    break;
449	case 's':
450	    opt_s = argto4(optarg, 1, "file system size (in sectors)");
451	    break;
452	case 'u':
453	    opt_u = argto2(optarg, 1, "sectors/track");
454	    break;
455	case 'v':
456	    if (!oklabel(optarg))
457		errx(1, "%s: bad volume name", optarg);
458	    opt_v = optarg;
459	    break;
460	default:
461	    usage();
462	}
463    argc -= optind;
464    argv += optind;
465    if (argc < 1 || argc > 2)
466	usage();
467    fname = *argv++;
468    if (!strchr(fname, '/')) {
469	snprintf(buf, sizeof(buf), "%sr%s", _PATH_DEV, fname);
470	if (stat(buf, &sb))
471	    snprintf(buf, sizeof(buf), "%s%s", _PATH_DEV, fname);
472	if (!(fname = strdup(buf)))
473	    err(1, NULL);
474    }
475    dtype = *argv;
476    if ((fd = open(fname, opt_N ? O_RDONLY : O_RDWR)) == -1 ||
477	fstat(fd, &sb))
478	err(1, "%s", fname);
479    if (!opt_N)
480	check_mounted(fname, sb.st_mode);
481    if (!S_ISCHR(sb.st_mode))
482	warnx("warning: %s is not a character device", fname);
483    memset(&bpb, 0, sizeof(bpb));
484    if (opt_f) {
485	getstdfmt(opt_f, &bpb);
486	bpb.bsec = bpb.sec;
487	bpb.sec = 0;
488	bpb.bspf = bpb.spf;
489	bpb.spf = 0;
490    }
491    if (opt_h)
492	bpb.hds = opt_h;
493    if (opt_u)
494	bpb.spt = opt_u;
495    if (opt_S)
496	bpb.bps = opt_S;
497    if (opt_s)
498	bpb.bsec = opt_s;
499    if (oflag)
500	bpb.hid = opt_o;
501    if (!(opt_f || (opt_h && opt_u && opt_S && opt_s && oflag)))
502	getdiskinfo(fd, fname, dtype, oflag, &bpb);
503    if (!powerof2(bpb.bps))
504	errx(1, "bytes/sector (%u) is not a power of 2", bpb.bps);
505    if (bpb.bps < MINBPS)
506	errx(1, "bytes/sector (%u) is too small; minimum is %u",
507	     bpb.bps, MINBPS);
508    if (bpb.bps > MAXBPS)
509	errx(1, "bytes/sector (%u) is too large; maximum is %u",
510	     bpb.bps, MAXBPS);
511    if (opt_P != 0 && !powerof2(opt_P))
512	errx(1, "physical bytes/sector (%u) is not a power of 2", opt_P);
513    if (opt_P != 0 && opt_P < bpb.bps)
514	errx(1, "physical bytes/sector (%u) is less than logical bytes/sector (%u)", opt_P, bpb.bps);
515    if (opt_P == 0) {
516	uint32_t phys_block_size;
517
518	if (ioctl(fd, DKIOCGETPHYSICALBLOCKSIZE, &phys_block_size) == -1) {
519	    printf("ioctl(DKIOCGETPHYSICALBLOCKSIZE) not supported\n");
520	    opt_P = bpb.bps;
521	} else {
522	    printf("%u bytes per physical sector\n", phys_block_size);
523	    opt_P = phys_block_size;
524	}
525    }
526    if (!(fat = opt_F)) {
527	if (opt_f)
528	    fat = 12;
529	else if (!opt_e && (opt_i || opt_k))
530	    fat = 32;
531    }
532    if ((fat == 32 && opt_e) || (fat != 32 && (opt_i || opt_k)))
533	errx(1, "-%c is not a legal FAT%s option",
534	     fat == 32 ? 'e' : opt_i ? 'i' : 'k',
535	     fat == 32 ? "32" : "12/16");
536    if (opt_f && fat == 32)
537	bpb.rde = 0;
538    if (opt_b) {
539	if (!powerof2(opt_b))
540	    errx(1, "block size (%u) is not a power of 2", opt_b);
541	if (opt_b < bpb.bps)
542	    errx(1, "block size (%u) is too small; minimum is %u",
543		 opt_b, bpb.bps);
544	if (opt_b > bpb.bps * MAXSPC)
545	    errx(1, "block size (%u) is too large; maximum is %u",
546		 opt_b, bpb.bps * MAXSPC);
547	bpb.spc = opt_b / bpb.bps;
548    }
549    if (opt_c) {
550	if (!powerof2(opt_c))
551	    errx(1, "sectors/cluster (%u) is not a power of 2", opt_c);
552	bpb.spc = opt_c;
553    }
554    if (opt_r)
555	bpb.res = opt_r;
556    if (opt_n) {
557	if (opt_n > MAXNFT)
558	    errx(1, "number of FATs (%u) is too large; maximum is %u",
559		 opt_n, MAXNFT);
560	bpb.nft = opt_n;
561    }
562    if (opt_e)
563	bpb.rde = opt_e;
564    if (mflag) {
565	if (opt_m < 0xf0)
566	    errx(1, "illegal media descriptor (%#x)", opt_m);
567	bpb.mid = opt_m;
568    }
569    if (opt_a)
570	bpb.bspf = opt_a;
571    if (opt_i)
572	bpb.infs = opt_i;
573    if (opt_k)
574	bpb.bkbs = opt_k;
575    bss = 1;
576    bname = NULL;
577    fd1 = -1;
578    if (opt_B) {
579	bname = opt_B;
580	if (!strchr(bname, '/')) {
581	    snprintf(buf, sizeof(buf), "/boot/%s", bname);
582	    if (!(bname = strdup(buf)))
583		err(1, NULL);
584	}
585	if ((fd1 = open(bname, O_RDONLY)) == -1 || fstat(fd1, &sb))
586	    err(1, "%s", bname);
587	if (!S_ISREG(sb.st_mode) || sb.st_size % bpb.bps ||
588	    sb.st_size < bpb.bps || sb.st_size > bpb.bps * MAXU16)
589	    errx(1, "%s: inappropriate file type or format", bname);
590	bss = (u_int)(sb.st_size / bpb.bps);
591    }
592    if (!bpb.nft)
593	bpb.nft = 2;
594
595    sd_card_set_defaults(fname, &fat, &bpb);
596
597    /*
598     * [2873851] If the FAT type or sectors per cluster were not explicitly specified,
599     * set them to default values.
600     */
601    if (!bpb.spc)
602    {
603	u_int64_t kilobytes = (u_int64_t) bpb.bps * (u_int64_t) bpb.bsec / 1024U;
604	u_int32_t bytes_per_cluster;
605
606	/*
607	 * If the user didn't specify the FAT type, then pick a default based on
608	 * the size of the volume.
609	 */
610	if (!fat)
611	{
612	    if (bpb.bps == 512 && bpb.bsec <= MAX_SEC_FAT12_512)
613		fat = 12;
614	    else if (bpb.bps != 512 && bpb.bsec <= MAX_SEC_FAT12)
615		fat = 12;
616	    else if (kilobytes <= MAX_KB_FAT16)
617		fat = 16;
618	    else
619		fat = 32;
620	}
621
622	switch (fat)
623	{
624	case 12:
625	    /*
626	     * There is no general table for FAT12, so try all possible
627	     * bytes-per-cluster values until it all fits, or we try the
628	     * maximum cluster size.
629	     */
630	    for (bytes_per_cluster = bpb.bps; bytes_per_cluster <= 32768; bytes_per_cluster *= 2)
631	    {
632		bpb.spc = bytes_per_cluster / bpb.bps;
633
634		/* Start with number of reserved sectors */
635		x = bpb.res ? bpb.res : bss;
636		/* Plus number of sectors used by FAT */
637		x += howmany((RESFTE+MAXCLS12+1)*(12/BPN), bpb.bps*NPB) * bpb.nft;
638		/* Plus root directory */
639		x += howmany(bpb.rde ? bpb.rde : DEFRDE, bpb.bps / sizeof(struct de));
640		/* Plus data clusters */
641		x += (MAXCLS12+1) * bpb.spc;
642
643		/*
644		 * We now know how many sectors the volume would occupy with the given
645		 * sectors per cluster, and the maximum number of FAT12 clusters.  If
646		 * this is as big as or bigger than the actual volume, we've found the
647		 * minimum sectors per cluster.
648		 */
649		if (x >= bpb.bsec)
650		    break;
651	    }
652	    break;
653	case 16:
654	    for (x=0; kilobytes > fat16Sizes[x].kilobytes; ++x)
655		;
656	    bytes_per_cluster = fat16Sizes[x].bytes_per_cluster;
657	    if (bytes_per_cluster < bpb.bps)
658		bytes_per_cluster = bpb.bps;
659	    bpb.spc = bytes_per_cluster / bpb.bps;
660	    break;
661	case 32:
662	    for (x=0; kilobytes > fat32Sizes[x].kilobytes; ++x)
663		;
664	    bytes_per_cluster = fat32Sizes[x].bytes_per_cluster;
665	    if (bytes_per_cluster < bpb.bps)
666		bytes_per_cluster = bpb.bps;
667	    bpb.spc = bytes_per_cluster / bpb.bps;
668	    break;
669	default:
670	    errx(1, "Invalid FAT type: %d", fat);
671	    break;
672	}
673
674	if (bpb.spc == 0)
675	    errx(1, "FAT%d is impossible with %u sectors", fat, bpb.bsec);
676    }
677    else
678    {
679	/*
680	 * User explicitly specified sectors per cluster.  If they didn't
681	 * specify the FAT type, pick one that uses up the available sectors.
682	 */
683	if (!fat)
684	{
685	    /* See if a maximum number of FAT clusters would fill it up. */
686	    if (bpb.bsec < (bpb.res ? bpb.res : bss) +
687		howmany((RESFTE+MAXCLS12+1) * (12/BPN), bpb.bps * BPN) * bpb.nft +
688		howmany(bpb.rde ? bpb.rde : DEFRDE, bpb.bps / sizeof(struct de)) +
689		(MAXCLS12+1) * bpb.spc)
690	    {
691		fat = 12;
692	    }
693	    else if (bpb.bsec < (bpb.res ? bpb.res : bss) +
694		howmany((RESFTE+MAXCLS16) * 2, bpb.bps) * bpb.nft +
695		howmany(bpb.rde ? bpb.rde : DEFRDE, bpb.bps / sizeof(struct de)) +
696		(MAXCLS16+1) * bpb.spc)
697	    {
698		fat = 16;
699	    }
700	    else
701	    {
702		fat = 32;
703	    }
704	}
705    }
706
707    x = bss;
708    if (fat == 32) {
709	if (!bpb.infs) {
710	    if (x == MAXU16 || x == bpb.bkbs)
711		errx(1, "no room for info sector");
712	    bpb.infs = x;
713	}
714	if (bpb.infs != MAXU16 && x <= bpb.infs)
715	    x = bpb.infs + 1;
716	if (!bpb.bkbs) {
717	    if (x == MAXU16)
718		errx(1, "no room for backup sector");
719	    if (x <= BACKUP_BOOT_SECTOR)
720		bpb.bkbs = BACKUP_BOOT_SECTOR;
721	    else
722		bpb.bkbs = x;
723	} else if (bpb.bkbs != MAXU16 && bpb.bkbs == bpb.infs)
724	    errx(1, "backup sector would overwrite info sector");
725	if (bpb.bkbs != MAXU16 && x <= bpb.bkbs)
726	    x = bpb.bkbs + 1;
727    }
728    if (!bpb.res)
729	bpb.res = fat == 32 ? MAX(x, FAT32_RESERVED_SECTORS) : x;
730    else if (bpb.res < x)
731	errx(1, "too few reserved sectors");
732    if (fat != 32 && !bpb.rde)
733	bpb.rde = DEFRDE;
734    rds = howmany(bpb.rde, bpb.bps / sizeof(struct de));
735    if (fat != 32 && bpb.bspf > MAXU16)
736	errx(1, "too many sectors/FAT for FAT12/16");
737    x1 = bpb.res + rds;
738    x = bpb.bspf ? bpb.bspf : 1;
739    if (x1 + (u_int64_t)x * bpb.nft > bpb.bsec)
740	errx(1, "meta data exceeds file system size");
741    x1 += x * bpb.nft;
742    x = (u_int)((u_int64_t)(bpb.bsec - x1) * bpb.bps * NPB /
743	(bpb.spc * bpb.bps * NPB + fat / BPN * bpb.nft));
744    x2 = howmany((RESFTE + MIN(x, maxcls(fat))) * (fat / BPN),
745		 bpb.bps * NPB);
746    if (!bpb.bspf) {
747	bpb.bspf = x2;
748
749	/* Round up bspf to a multiple of physical sector size */
750	if (opt_P > bpb.bps) {
751	    u_int phys_per_log = opt_P / bpb.bps;
752	    u_int remainder = bpb.bspf % phys_per_log;
753	    if (remainder) {
754		bpb.bspf += phys_per_log - remainder;
755	    }
756	}
757
758	x1 += (bpb.bspf - 1) * bpb.nft;
759    }
760    cls = (bpb.bsec - x1) / bpb.spc;
761    x = (u_int)((u_int64_t)bpb.bspf * bpb.bps * NPB / (fat / BPN) - RESFTE);
762    if (cls > x)
763    {
764    	/*
765    	 * This indicates that there are more sectors available
766    	 * for data clusters than there are usable entries in the
767    	 * FAT.  In this case, we need to limit the number of
768    	 * clusters, and also reduce the number of sectors.
769    	 */
770	bpb.bsec = bpb.res + bpb.bspf*bpb.nft + rds + x*bpb.spc;
771	warnx("warning: sectors/FAT limits sectors to %u, clusters to %u", bpb.bsec, x);
772	cls = x;
773    }
774    if (bpb.bspf < x2)
775	warnx("warning: sectors/FAT limits file system to %u clusters",
776	      cls);
777    if (cls < mincls(fat))
778	errx(1, "%u clusters too few clusters for FAT%u, need %u", cls, fat,
779	    mincls(fat));
780    if (cls > maxcls(fat)) {
781	cls = maxcls(fat);
782	bpb.bsec = x1 + (cls + 1) * bpb.spc - 1;
783	warnx("warning: FAT type limits file system to %u sectors",
784	      bpb.bsec);
785    }
786    printf("%s: %u sector%s in %u FAT%u cluster%s "
787	   "(%u bytes/cluster)\n", fname, cls * bpb.spc,
788	   cls * bpb.spc == 1 ? "" : "s", cls, fat,
789	   cls == 1 ? "" : "s", bpb.bps * bpb.spc);
790    if (!bpb.mid)
791        bpb.mid = !bpb.hid ? 0xf0 : 0xf8;
792    if (fat == 32)
793        bpb.rdcl = RESFTE;
794    if (bpb.bsec <= MAXU16) {
795        bpb.sec = bpb.bsec;
796        bpb.bsec = 0;
797    }
798    if (fat != 32) {
799        bpb.spf = bpb.bspf;
800        bpb.bspf = 0;
801    } else {
802        if (bpb.bsec == 0)
803            bpb.bsec = bpb.sec;
804        bpb.spf = 0;
805        bpb.sec = 0;
806    }
807
808    print_bpb(&bpb);
809
810    if (!opt_N) {
811	u_int sectors_to_write;
812
813	/*
814	 * Get the current date and time in case we need it for the volume ID.
815	 */
816        gettimeofday(&tv, NULL);
817        now = tv.tv_sec;
818        tm = localtime(&now);
819
820	/*
821	 * Allocate a buffer for assembling the to-be-written sectors, and
822	 * a separate buffer for the boot sector (which will be written last).
823	 */
824        if (!(io_buffer = malloc(IO_BUFFER_SIZE)))
825            err(1, NULL);
826        if (!(bpb_buffer = malloc(bpb.bps)))
827            err(1, NULL);
828	img = io_buffer;
829        dir = bpb.res + (bpb.spf ? bpb.spf : bpb.bspf) * bpb.nft;
830	sectors_to_write = dir + (fat == 32 ? bpb.spc : rds);
831
832	/*
833	 * Invalidate any prior file system by overwriting their identifying
834	 * information.  NOTE: wipefs will also send a DKIOCDISCARD.
835	 */
836	wipefs_ctx wiper;
837	int error;
838	error = wipefs_alloc(fd, bpb.bps, &wiper);
839	if (error)
840	    errc(1, error, "%s: wipefs_alloc()", fname);
841	error = wipefs_except_blocks(wiper, 0, sectors_to_write);
842	if (error)
843	    errc(1, error, "%s: wipefs_except_blocks()", fname);
844	error = wipefs_wipe(wiper);
845	if (error)
846	    errc(1, error, "%s: wipefs_wipe()", fname);
847	wipefs_free(&wiper);
848
849	/*
850	 * Now start writing the new file system to disk.
851	 */
852	for (lsn = 0; lsn < sectors_to_write; lsn++) {
853	    x = lsn;
854	    if (opt_B &&
855		fat == 32 && bpb.bkbs != MAXU16 &&
856		bss <= bpb.bkbs && x >= bpb.bkbs) {
857		x -= bpb.bkbs;
858		if (!x && lseek(fd1, 0, SEEK_SET))
859		    err(1, "%s", bname);
860	    }
861	    if (opt_B && x < bss) {
862		if ((n = read(fd1, img, bpb.bps)) == -1)
863		    err(1, "%s", bname);
864		if (n != bpb.bps)
865		    errx(1, "%s: can't read sector %u", bname, x);
866	    } else
867		memset(img, 0, bpb.bps);
868	    if (!lsn ||
869	      (fat == 32 && bpb.bkbs != MAXU16 && lsn == bpb.bkbs)) {
870		x1 = sizeof(struct bs);
871		bsbpb = (struct bsbpb *)(img + x1);
872		mk2(bsbpb->bps, bpb.bps);
873		mk1(bsbpb->spc, bpb.spc);
874		mk2(bsbpb->res, bpb.res);
875		mk1(bsbpb->nft, bpb.nft);
876		mk2(bsbpb->rde, bpb.rde);
877		mk2(bsbpb->sec, bpb.sec);
878		mk1(bsbpb->mid, bpb.mid);
879		mk2(bsbpb->spf, bpb.spf);
880		mk2(bsbpb->spt, bpb.spt);
881		mk2(bsbpb->hds, bpb.hds);
882		mk4(bsbpb->hid, bpb.hid);
883		mk4(bsbpb->bsec, bpb.bsec);
884		x1 += sizeof(struct bsbpb);
885		if (fat == 32) {
886		    bsxbpb = (struct bsxbpb *)(img + x1);
887		    mk4(bsxbpb->bspf, bpb.bspf);
888		    mk2(bsxbpb->xflg, 0);
889		    mk2(bsxbpb->vers, 0);
890		    mk4(bsxbpb->rdcl, bpb.rdcl);
891		    mk2(bsxbpb->infs, bpb.infs);
892		    mk2(bsxbpb->bkbs, bpb.bkbs);
893		    x1 += sizeof(struct bsxbpb);
894		}
895		bsx = (struct bsx *)(img + x1);
896                mk1(bsx->drv, bpb.driveNum);
897		mk1(bsx->sig, 0x29);
898		if (Iflag)
899		    x = opt_I;
900		else
901		    x = (((u_int)(1 + tm->tm_mon) << 8 |
902			  (u_int)tm->tm_mday) +
903			 ((u_int)tm->tm_sec << 8 |
904			  (u_int)(tv.tv_usec / 10))) << 16 |
905			((u_int)(1900 + tm->tm_year) +
906			 ((u_int)tm->tm_hour << 8 |
907			  (u_int)tm->tm_min));
908		mk4(bsx->volid, x);
909		mklabel(bsx->label, opt_v ? opt_v : "NO NAME");
910		snprintf(buf, sizeof(buf), "FAT%u", fat);
911		setstr(bsx->type, buf, sizeof(bsx->type));
912		if (!opt_B) {
913		    x1 += sizeof(struct bsx);
914		    bs = (struct bs *)img;
915		    mk1(bs->jmp[0], 0xeb);
916		    mk1(bs->jmp[1], x1 - 2);
917		    mk1(bs->jmp[2], 0x90);
918		    setstr(bs->oem, opt_O ? opt_O : "BSD  4.4",
919			   sizeof(bs->oem));
920		    memcpy(img + x1, bootcode, sizeof(bootcode));
921		    mk2(img + 510, DOSMAGIC);
922		}
923	    } else if (fat == 32 && bpb.infs != MAXU16 &&
924		       (lsn == bpb.infs ||
925			(bpb.bkbs != MAXU16 &&
926			 lsn == bpb.bkbs + bpb.infs))) {
927		mk4(img, 0x41615252);
928		mk4(img + 484, 0x61417272);
929		mk4(img + 488, cls-1);
930		mk4(img + 492, bpb.rdcl+1);
931		/* Offsets 508-509 remain zero */
932		mk2(img + 510, DOSMAGIC);
933	    } else if (lsn >= bpb.res && lsn < dir &&
934		       !((lsn - bpb.res) %
935			 (bpb.spf ? bpb.spf : bpb.bspf))) {
936		mk1(img[0], bpb.mid);
937		for (x = 1; x < fat * (fat == 32 ? 3 : 2) / 8; x++)
938		    mk1(img[x], fat == 32 && x % 4 == 3 ? 0x0f : 0xff);
939	    } else if (lsn == dir && opt_v && *opt_v) {
940		de = (struct de *)img;
941		mklabel(de->namext, opt_v);
942		mk1(de->attr, 050);
943		x = (u_int)tm->tm_hour << 11 |
944		    (u_int)tm->tm_min << 5 |
945		    (u_int)tm->tm_sec >> 1;
946		mk2(de->time, x);
947		x = (u_int)(tm->tm_year - 80) << 9 |
948		    (u_int)(tm->tm_mon + 1) << 5 |
949		    (u_int)tm->tm_mday;
950		mk2(de->date, x);
951	    }
952	    img += bpb.bps;
953
954	    if (lsn == 0) {
955		/* Zero out boot sector for now and save it to be written at the end */
956		memcpy(bpb_buffer, io_buffer, bpb.bps);
957		bzero(io_buffer, bpb.bps);
958	    }
959
960	    if (img >= (io_buffer + IO_BUFFER_SIZE)) {
961		/* We filled the I/O buffer, so write it out now */
962		if ((n = write(fd, io_buffer, IO_BUFFER_SIZE)) == -1)
963		    err(1, "%s", fname);
964		if (n != IO_BUFFER_SIZE)
965		    errx(1, "%s: can't write sector %u", fname, lsn);
966		img = io_buffer;
967	    }
968	}
969	if (img != io_buffer) {
970	    /* The I/O buffer was partially full; write it out before exit */
971	    if ((n = write(fd, io_buffer, img-io_buffer)) == -1)
972		err(1, "%s", fname);
973	    if (n != (img-io_buffer))
974		errx(1, "%s: can't write sector %u", fname, lsn);
975	}
976	/* Write out boot sector at the end now */
977	if (lseek(fd, 0, SEEK_SET) == -1)
978		err(1, "lseek: %s", fname);
979	if ((n = write(fd, bpb_buffer, bpb.bps)) == -1)
980		err(1, "write: %s", fname);
981	if (n != bpb.bps)
982		errx(1, "%s: can't write boot sector", fname);
983    }
984    return 0;
985}
986
987/*
988 * Exit with error if file system is mounted.
989 */
990static void
991check_mounted(const char *fname, mode_t mode)
992{
993    struct statfs *mp;
994    const char *s1, *s2;
995    size_t len;
996    int n, r;
997
998    if (!(n = getmntinfo(&mp, MNT_NOWAIT)))
999	err(1, "getmntinfo");
1000    len = strlen(_PATH_DEV);
1001    s1 = fname;
1002    if (!strncmp(s1, _PATH_DEV, len))
1003	s1 += len;
1004    r = S_ISCHR(mode) && s1 != fname && *s1 == 'r';
1005    for (; n--; mp++) {
1006	s2 = mp->f_mntfromname;
1007	if (!strncmp(s2, _PATH_DEV, len))
1008	    s2 += len;
1009	if ((r && s2 != mp->f_mntfromname && !strcmp(s1 + 1, s2)) ||
1010	    !strcmp(s1, s2))
1011	    errx(1, "%s is mounted on %s", fname, mp->f_mntonname);
1012    }
1013}
1014
1015/*
1016 * Get a standard format.
1017 */
1018static void
1019getstdfmt(const char *fmt, struct bpb *bpb)
1020{
1021    u_int x, i;
1022
1023    x = sizeof(stdfmt) / sizeof(stdfmt[0]);
1024    for (i = 0; i < x && strcmp(fmt, stdfmt[i].name); i++);
1025    if (i == x)
1026	errx(1, "%s: unknown standard format", fmt);
1027    *bpb = stdfmt[i].bpb;
1028}
1029
1030/*
1031 * Get disk partition, and geometry information.
1032 */
1033static void
1034getdiskinfo(int fd, const char *fname, const char *dtype, int oflag,
1035	    struct bpb *bpb)
1036{
1037    uint64_t partition_offset = 0;	    /* in bytes from start of device */
1038    uint64_t block_count;
1039    uint32_t block_size;
1040
1041    if (ioctl(fd, DKIOCGETBASE, &partition_offset) == -1)
1042        err(1, "%s: Cannot get partition offset", fname);
1043
1044    /*
1045     * If we'll need the block count or block size, get them now.
1046     */
1047    if (!bpb->bsec || !bpb->hds)
1048    {
1049	if (ioctl(fd, DKIOCGETBLOCKCOUNT, &block_count) == -1)
1050	    err(1, "%s: Cannot get number of sectors", fname);
1051    }
1052    if (!bpb->bps || !bpb->bsec)
1053    {
1054	/*
1055	 * Note: if user specified bytes per sector, but not number of sectors,
1056	 * then we'll need the sector size in order to calculate the total
1057	 * bytes in this partition.
1058	 */
1059	if (ioctl(fd, DKIOCGETBLOCKSIZE, &block_size) == -1)
1060	    err(1, "%s: Cannot get number of sectors", fname);
1061    }
1062
1063    /*
1064     * If bytes-per-sector was explicitly specified, but total number of
1065     * sectors was not explicitly specified, then find out how many sectors
1066     * of the given size would fit into the given partition (calculate the
1067     * size of the partition in bytes, and divide by the desired bytes per
1068     * sector).
1069     *
1070     * This makes it possible to create a disk image, and format it in
1071     * preparation for copying to a device with a different sector size.
1072     */
1073    if (bpb->bps && !bpb->bsec)
1074	    bpb->bsec = (u_int)((block_count * block_size) / bpb->bps);
1075
1076    if (!bpb->bsec)
1077	    bpb->bsec = (u_int)block_count;
1078
1079    if (!bpb->bps)
1080	    bpb->bps = block_size;
1081
1082    if (!oflag)
1083	bpb->hid = (u_int)(partition_offset / bpb->bps);
1084
1085    /*
1086     * Set up the INT 0x13 style drive number for BIOS.  The FAT specification
1087     * says "0x00 for floppies, 0x80 for hard disks".  I assume that means
1088     * 0x80 if partitioned, and 0x000 otherwise.
1089     */
1090    bpb->driveNum = partition_offset != 0 ? 0x80 : 0x00;
1091
1092	/*
1093     * Compute default values for sectors per track and number of heads
1094     * (number of tracks per cylinder) if the user didn't explicitly provide
1095     * them.  This calculation mimics the dkdisklabel() routine from
1096     * disklib.
1097     */
1098    if (!bpb->spt)
1099        bpb->spt = 32;  /* The same constant that dkdisklabel() used. */
1100    if (!bpb->hds)
1101    {
1102        /*
1103         * These are the same values used by dkdisklabel().
1104         *
1105         * Note the use of block_count instead of bpb->bsec here.
1106         * dkdisklabel() computed its fake geometry based on the block
1107         * count returned by DKIOCGETBLOCKCOUNT, without adjusting for
1108         * a new block size.
1109         */
1110        if (block_count < 8*32*1024)
1111            bpb->hds = 16;
1112        else if (block_count < 16*32*1024)
1113            bpb->hds = 32;
1114        else if (block_count < 32*32*1024)
1115            bpb->hds = 54;  /* Should be 64?  Bug in dkdisklabel()? */
1116        else if (block_count < 64*32*1024)
1117            bpb->hds = 128;
1118        else
1119            bpb->hds = 255;
1120    }
1121}
1122
1123/*
1124 * Given the path we're formatting, see if it looks like an SD card.
1125 */
1126static enum SDCardType sd_card_type_for_path(const char *path)
1127{
1128    enum SDCardType result = kCardTypeNone;
1129    const char *disk = NULL;
1130    io_service_t obj = 0;
1131    CFDictionaryRef cardCharacteristics = NULL;
1132    CFStringRef cardType = NULL;
1133
1134    /*
1135     * We're looking for the "disk1s1" part of the path, so see if the
1136     * path starts with "/dev/" or "/dev/r" and point past that.
1137     */
1138    if (!strncmp(path, "/dev/", 5))
1139    {
1140	disk = path + 5;    /* Skip over "/dev/". */
1141	if (*disk == 'r')
1142	    ++disk;	    /* Skip over the "r" in "/dev/r". */
1143    }
1144
1145    /*
1146     * Look for an IOService with the given BSD disk name.
1147     */
1148    if (disk)
1149    {
1150	obj = IOServiceGetMatchingService(kIOMasterPortDefault,
1151					  IOBSDNameMatching(kIOMasterPortDefault, 0, disk));
1152    }
1153
1154    /* See if the object has a card characteristics dictionary. */
1155    if (obj)
1156    {
1157	cardCharacteristics = IORegistryEntrySearchCFProperty(
1158							      obj, kIOServicePlane,
1159							      CFSTR(kIOPropertyCardCharacteristicsKey),
1160							      kCFAllocatorDefault,
1161							      kIORegistryIterateRecursively|kIORegistryIterateParents);
1162    }
1163
1164    /* See if the dictionary contains a card type string. */
1165    if (cardCharacteristics && CFGetTypeID(cardCharacteristics) == CFDictionaryGetTypeID())
1166    {
1167	cardType = CFDictionaryGetValue(cardCharacteristics, CFSTR(kIOPropertyCardTypeKey));
1168    }
1169
1170    /* Turn the card type string into one of our constants. */
1171    if (cardType && CFGetTypeID(cardType) == CFStringGetTypeID())
1172    {
1173	if (CFEqual(cardType, CFSTR(kIOPropertyCardTypeSDSCKey)))
1174	    result = kCardTypeSDSC;
1175	else if (CFEqual(cardType, CFSTR(kIOPropertyCardTypeSDHCKey)))
1176	    result = kCardTypeSDHC;
1177	else if (CFEqual(cardType, CFSTR(kIOPropertyCardTypeSDXCKey)))
1178	    result = kCardTypeSDXC;
1179    }
1180
1181    if (cardCharacteristics)
1182	CFRelease(cardCharacteristics);
1183    if (obj)
1184	IOObjectRelease(obj);
1185
1186    return result;
1187}
1188
1189/*
1190 * If the given path is to some kind of SD card, then use the default FAT type
1191 * and cluster size specified by the SD Card Association.
1192 *
1193 * Note that their specification refers to card capacity, which means the size
1194 * of the entire media (not just the partition containing the file system).
1195 * Below, the size of the partition is being compared since that is what we
1196 * have most convenient access to, and its size is only slightly smaller than
1197 * the size of the entire media.  This program does not write the partition
1198 * map, so we can't enforce the recommended partition offset.
1199 */
1200static void sd_card_set_defaults(const char *path, u_int *fat, struct bpb *bpb)
1201{
1202    /*
1203     * Only use SD card defaults if the sector size is 512 bytes, and the
1204     * user did not explicitly specify the FAT type or cluster size.
1205     */
1206    if (*fat != 0 || bpb->spc != 0 || bpb->bps != 512)
1207	return;
1208
1209    enum SDCardType cardType = sd_card_type_for_path(path);
1210
1211    switch (cardType)
1212    {
1213	case kCardTypeNone:
1214	    break;
1215	case kCardTypeSDSC:
1216	    if (bpb->bsec < 16384)
1217	    {
1218		/* Up to 8MiB, use FAT12 and 16 sectors per cluster */
1219		*fat = 12;
1220		bpb->spc = 16;
1221	    }
1222	    else if (bpb->bsec < 128 * 1024)
1223	    {
1224		/* Up to 64MiB, use FAT12 and 32 sectors per cluster */
1225		*fat = 12;
1226		bpb->spc = 32;
1227	    }
1228	    else if (bpb->bsec < 2 * 1024 * 1024)
1229	    {
1230		/* Up to 1GiB, use FAT16 and 32 sectors per cluster */
1231		*fat = 16;
1232		bpb->spc = 32;
1233	    }
1234	    else
1235	    {
1236		/* 1GiB or larger, use FAT16 and 64 sectors per cluster */
1237		*fat = 16;
1238		bpb->spc = 64;
1239	    }
1240	    break;
1241	case kCardTypeSDHC:
1242	    *fat = 32;
1243	    bpb->spc = 64;
1244	    break;
1245	case kCardTypeSDXC:
1246	    warnx("%s: newfs_exfat should be used for SDXC media", path);
1247	    break;
1248    }
1249}
1250
1251/*
1252 * Print out BPB values.
1253 */
1254static void
1255print_bpb(struct bpb *bpb)
1256{
1257    printf("bps=%u spc=%u res=%u nft=%u", bpb->bps, bpb->spc, bpb->res,
1258	   bpb->nft);
1259    if (bpb->rde)
1260	printf(" rde=%u", bpb->rde);
1261    if (bpb->sec)
1262	printf(" sec=%u", bpb->sec);
1263    printf(" mid=%#x", bpb->mid);
1264    if (bpb->spf)
1265	printf(" spf=%u", bpb->spf);
1266    printf(" spt=%u hds=%u hid=%u drv=0x%02X", bpb->spt, bpb->hds, bpb->hid, bpb->driveNum);
1267    if (bpb->bsec)
1268	printf(" bsec=%u", bpb->bsec);
1269    if (!bpb->spf) {
1270	printf(" bspf=%u rdcl=%u", bpb->bspf, bpb->rdcl);
1271	printf(" infs=");
1272	printf(bpb->infs == MAXU16 ? "%#x" : "%u", bpb->infs);
1273	printf(" bkbs=");
1274	printf(bpb->bkbs == MAXU16 ? "%#x" : "%u", bpb->bkbs);
1275    }
1276    printf("\n");
1277}
1278
1279/*
1280 * Convert and check a numeric option argument.
1281 */
1282static u_int
1283argtou(const char *arg, u_int lo, u_int hi, const char *msg)
1284{
1285    char *s;
1286    u_long x;
1287
1288    errno = 0;
1289    x = strtoul(arg, &s, 0);
1290    if (errno || !*arg || *s || x < lo || x > hi)
1291	errx(1, "%s: bad %s", arg, msg);
1292    return (u_int)x;
1293}
1294
1295/*
1296 * Check a volume label.
1297 */
1298static int
1299oklabel(const char *src)
1300{
1301    int c, i;
1302
1303    for (i = 0; i <= 11; i++) {
1304	c = (u_char)*src++;
1305	if (c < ' ' + !i || strchr("\"*+,./:;<=>?[\\]|", c))
1306	    break;
1307    }
1308    return !c;
1309}
1310
1311/*
1312 * Make a volume label.
1313 */
1314static void
1315mklabel(u_int8_t *dest, const char *src)
1316{
1317    int c, i;
1318
1319    for (i = 0; i < 11; i++) {
1320	c = *src ? toupper(*src++) : ' ';
1321	*dest++ = !i && c == '\xe5' ? 5 : c;
1322    }
1323}
1324
1325/*
1326 * Copy string, padding with spaces.
1327 */
1328static void
1329setstr(u_int8_t *dest, const char *src, size_t len)
1330{
1331    while (len--)
1332	*dest++ = *src ? *src++ : ' ';
1333}
1334
1335/*
1336 * Print usage message.
1337 */
1338static void
1339usage(void)
1340{
1341    fprintf(stderr,
1342	    "usage: newfs_msdos [ -options ] special [disktype]\n");
1343    fprintf(stderr, "where the options are:\n");
1344    fprintf(stderr, "\t-N don't create file system: "
1345	    "just print out parameters\n");
1346    fprintf(stderr, "\t-B get bootstrap from file\n");
1347    fprintf(stderr, "\t-F FAT type (12, 16, or 32)\n");
1348    fprintf(stderr, "\t-I volume ID\n");
1349    fprintf(stderr, "\t-O OEM string\n");
1350    fprintf(stderr, "\t-S bytes/sector\n");
1351    fprintf(stderr, "\t-P physical bytes/sector\n");
1352    fprintf(stderr, "\t-a sectors/FAT\n");
1353    fprintf(stderr, "\t-b block size\n");
1354    fprintf(stderr, "\t-c sectors/cluster\n");
1355    fprintf(stderr, "\t-e root directory entries\n");
1356    fprintf(stderr, "\t-f standard format\n");
1357    fprintf(stderr, "\t-h drive heads\n");
1358    fprintf(stderr, "\t-i file system info sector\n");
1359    fprintf(stderr, "\t-k backup boot sector\n");
1360    fprintf(stderr, "\t-m media descriptor\n");
1361    fprintf(stderr, "\t-n number of FATs\n");
1362    fprintf(stderr, "\t-o hidden sectors\n");
1363    fprintf(stderr, "\t-r reserved sectors\n");
1364    fprintf(stderr, "\t-s file system size (in sectors)\n");
1365    fprintf(stderr, "\t-u sectors/track\n");
1366    fprintf(stderr, "\t-v filesystem/volume name\n");
1367    exit(1);
1368}
1369