xref: /freebsd/usr.bin/mkimg/mkimg.c (revision 61c27edf3e00ead2bde9669c5917cb1fb32e19db)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2013,2014 Juniper Networks, Inc.
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 the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28 
29 #include <sys/param.h>
30 #include <sys/stat.h>
31 #include <errno.h>
32 #include <err.h>
33 #include <fcntl.h>
34 #include <getopt.h>
35 #include <libutil.h>
36 #include <limits.h>
37 #include <stdbool.h>
38 #include <stdint.h>
39 #include <stdio.h>
40 #include <stdlib.h>
41 #include <string.h>
42 #include <sysexits.h>
43 #include <unistd.h>
44 
45 #include "image.h"
46 #include "format.h"
47 #include "mkimg.h"
48 #include "scheme.h"
49 
50 #define	LONGOPT_FORMATS		0x01000001
51 #define	LONGOPT_SCHEMES		0x01000002
52 #define	LONGOPT_VERSION		0x01000003
53 #define	LONGOPT_CAPACITY	0x01000004
54 
55 static struct option longopts[] = {
56 	{ "formats", no_argument, NULL, LONGOPT_FORMATS },
57 	{ "schemes", no_argument, NULL, LONGOPT_SCHEMES },
58 	{ "version", no_argument, NULL, LONGOPT_VERSION },
59 	{ "capacity", required_argument, NULL, LONGOPT_CAPACITY },
60 	{ NULL, 0, NULL, 0 }
61 };
62 
63 static uint64_t min_capacity = 0;
64 static uint64_t max_capacity = 0;
65 
66 /* Fixed timestamp for reproducible builds. */
67 time_t timestamp = (time_t)-1;
68 
69 struct partlisthead partlist = TAILQ_HEAD_INITIALIZER(partlist);
70 u_int nparts = 0;
71 
72 u_int unit_testing;
73 u_int verbose;
74 
75 u_int ncyls = 0;
76 u_int nheads = 1;
77 u_int nsecs = 1;
78 u_int secsz = 512;
79 u_int blksz = 0;
80 uint32_t active_partition = 0;
81 
82 static void
print_formats(int usage)83 print_formats(int usage)
84 {
85 	struct mkimg_format *f;
86 	const char *sep;
87 
88 	if (usage) {
89 		fprintf(stderr, "    formats:\n");
90 		f = NULL;
91 		while ((f = format_iterate(f)) != NULL) {
92 			fprintf(stderr, "\t%s\t-  %s\n", f->name,
93 			    f->description);
94 		}
95 	} else {
96 		sep = "";
97 		f = NULL;
98 		while ((f = format_iterate(f)) != NULL) {
99 			printf("%s%s", sep, f->name);
100 			sep = " ";
101 		}
102 		putchar('\n');
103 	}
104 }
105 
106 static void
print_schemes(int usage)107 print_schemes(int usage)
108 {
109 	struct mkimg_scheme *s;
110 	const char *sep;
111 
112 	if (usage) {
113 		fprintf(stderr, "    schemes:\n");
114 		s = NULL;
115 		while ((s = scheme_iterate(s)) != NULL) {
116 			fprintf(stderr, "\t%s\t-  %s\n", s->name,
117 			    s->description);
118 		}
119 	} else {
120 		sep = "";
121 		s = NULL;
122 		while ((s = scheme_iterate(s)) != NULL) {
123 			printf("%s%s", sep, s->name);
124 			sep = " ";
125 		}
126 		putchar('\n');
127 	}
128 }
129 
130 static void
print_version(void)131 print_version(void)
132 {
133 	u_int width;
134 
135 #ifdef __LP64__
136 	width = 64;
137 #else
138 	width = 32;
139 #endif
140 	printf("mkimg %u (%u-bit)\n", MKIMG_VERSION, width);
141 }
142 
143 static void
usage(const char * why)144 usage(const char *why)
145 {
146 
147 	if (why != NULL) {
148 		warnx("error: %s", why);
149 		fputc('\n', stderr);
150 	}
151 	fprintf(stderr, "usage: %s <options>\n", getprogname());
152 
153 	fprintf(stderr, "    options:\n");
154 	fprintf(stderr, "\t--formats\t-  list image formats\n");
155 	fprintf(stderr, "\t--schemes\t-  list partition schemes\n");
156 	fprintf(stderr, "\t--version\t-  show version information\n");
157 	fprintf(stderr, "\t--capacity\t-  minimum and maximum capacity (in bytes)\n");
158 	fputc('\n', stderr);
159 	fprintf(stderr, "\t-a <num>\t-  mark num'th partition as active\n");
160 	fprintf(stderr, "\t-b <file>\t-  file containing boot code\n");
161 	fprintf(stderr, "\t-c <num>\t-  minimum capacity (in bytes) of the disk\n");
162 	fprintf(stderr, "\t-C <num>\t-  maximum capacity (in bytes) of the disk\n");
163 	fprintf(stderr, "\t-f <format>\n");
164 	fprintf(stderr, "\t-h\t\t-  show this usage information\n");
165 	fprintf(stderr, "\t-o <file>\t-  file to write image into\n");
166 	fprintf(stderr, "\t-p <partition>\n");
167 	fprintf(stderr, "\t-s <scheme>\n");
168 	fprintf(stderr, "\t-t <num>\t-  set timestamp (seconds since epoch)\n");
169 	fprintf(stderr, "\t-v\t\t-  increase verbosity\n");
170 	fprintf(stderr, "\t-y\t\t-  [developers] enable unit test\n");
171 	fprintf(stderr, "\t-H <num>\t-  number of heads to simulate\n");
172 	fprintf(stderr, "\t-P <num>\t-  physical sector size\n");
173 	fprintf(stderr, "\t-S <num>\t-  logical sector size\n");
174 	fprintf(stderr, "\t-T <num>\t-  number of tracks to simulate\n");
175 	fputc('\n', stderr);
176 	print_formats(1);
177 	fputc('\n', stderr);
178 	print_schemes(1);
179 	fputc('\n', stderr);
180 	fprintf(stderr, "    partition specification:\n");
181 	fprintf(stderr, "\t<type>[/<label>]::<size>[:[+]<offset>]\t-  "
182 	    "empty partition of given size and\n\t\t\t\t\t"
183 	    "   optional relative or absolute offset\n");
184 	fprintf(stderr, "\t<type>[/<label>]:=<file>[:[+]offset]\t-  partition "
185 	    "content and size are\n\t\t\t\t\t"
186 	    "   determined by the named file and\n"
187 	    "\t\t\t\t\t   optional relative or absolute offset\n");
188 	fprintf(stderr, "\t<type>[/<label>]:-<cmd>\t\t-  partition content and size "
189 	    "are taken\n\t\t\t\t\t   from the output of the command to run\n");
190 	fprintf(stderr, "\t-\t\t\t\t-  unused partition entry\n");
191 	fprintf(stderr, "\t    where:\n");
192 	fprintf(stderr, "\t\t<type>\t-  scheme neutral partition type\n");
193 	fprintf(stderr, "\t\t<label>\t-  optional scheme-dependent partition "
194 	    "label\n");
195 
196 	exit(EX_USAGE);
197 }
198 
199 static int
parse_uint32(uint32_t * valp,uint32_t min,uint32_t max,const char * arg)200 parse_uint32(uint32_t *valp, uint32_t min, uint32_t max, const char *arg)
201 {
202 	uint64_t val;
203 
204 	if (expand_number(arg, &val) == -1)
205 		return (errno);
206 	if (val > UINT_MAX || val < (uint64_t)min || val > (uint64_t)max)
207 		return (EINVAL);
208 	*valp = (uint32_t)val;
209 	return (0);
210 }
211 
212 static int
parse_uint64(uint64_t * valp,uint64_t min,uint64_t max,const char * arg)213 parse_uint64(uint64_t *valp, uint64_t min, uint64_t max, const char *arg)
214 {
215 	uint64_t val;
216 
217 	if (expand_number(arg, &val) == -1)
218 		return (errno);
219 	if (val < min || val > max)
220 		return (EINVAL);
221 	*valp = val;
222 	return (0);
223 }
224 
225 static int
pwr_of_two(u_int nr)226 pwr_of_two(u_int nr)
227 {
228 
229 	return (((nr & (nr - 1)) == 0) ? 1 : 0);
230 }
231 
232 /*
233  * A partition specification has the following format:
234  *	<type> ':' <kind> <contents>
235  * where:
236  *	type	  the partition type alias
237  *	kind	  the interpretation of the contents specification
238  *		  ':'   contents holds the size of an empty partition
239  *		  '='   contents holds the name of a file to read
240  *		  '-'   contents holds a command to run; the output of
241  *			which is the contents of the partition.
242  *	contents  the specification of a partition's contents
243  *
244  * A specification that is a single dash indicates an unused partition
245  * entry.
246  */
247 static int
parse_part(const char * spec)248 parse_part(const char *spec)
249 {
250 	struct part *part;
251 	const char *sep;
252 	char *asep;
253 	size_t len;
254 	int error;
255 
256 	if (strcmp(spec, "-") == 0) {
257 		nparts++;
258 		return (0);
259 	}
260 
261 	part = calloc(1, sizeof(struct part));
262 	if (part == NULL)
263 		return (ENOMEM);
264 
265 	sep = strchr(spec, ':');
266 	if (sep == NULL) {
267 		error = EINVAL;
268 		goto errout;
269 	}
270 	len = sep - spec + 1;
271 	if (len < 2) {
272 		error = EINVAL;
273 		goto errout;
274 	}
275 	part->alias = malloc(len);
276 	if (part->alias == NULL) {
277 		error = ENOMEM;
278 		goto errout;
279 	}
280 	strlcpy(part->alias, spec, len);
281 	spec = sep + 1;
282 
283 	switch (*spec) {
284 	case ':':
285 		part->kind = PART_KIND_SIZE;
286 		break;
287 	case '=':
288 		part->kind = PART_KIND_FILE;
289 		break;
290 	case '-':
291 		part->kind = PART_KIND_PIPE;
292 		break;
293 	default:
294 		error = EINVAL;
295 		goto errout;
296 	}
297 	spec++;
298 
299 	part->contents = strdup(spec);
300 	if (part->contents == NULL) {
301 		error = ENOMEM;
302 		goto errout;
303 	}
304 
305 	asep = strchr(part->alias, '/');
306 	if (asep != NULL) {
307 		*asep++ = '\0';
308 		if (strlen(part->alias) == 0 || strlen(asep) == 0) {
309 			error = EINVAL;
310 			goto errout;
311 		}
312 		part->label = strdup(asep);
313 		if (part->label == NULL) {
314 			error = ENOMEM;
315 			goto errout;
316 		}
317 	}
318 
319 	part->index = nparts;
320 	TAILQ_INSERT_TAIL(&partlist, part, link);
321 	nparts++;
322 	return (0);
323 
324  errout:
325 	if (part->alias != NULL)
326 		free(part->alias);
327 	free(part);
328 	return (error);
329 }
330 
331 #if defined(SPARSE_WRITE)
332 ssize_t
sparse_write(int fd,const void * ptr,size_t sz)333 sparse_write(int fd, const void *ptr, size_t sz)
334 {
335 	const char *buf, *p;
336 	off_t ofs;
337 	size_t len;
338 	ssize_t wr, wrsz;
339 
340 	buf = ptr;
341 	wrsz = 0;
342 	p = memchr(buf, 0, sz);
343 	while (sz > 0) {
344 		len = (p != NULL) ? (size_t)(p - buf) : sz;
345 		if (len > 0) {
346 			len = (len + secsz - 1) & ~(secsz - 1);
347 			if (len > sz)
348 				len = sz;
349 			wr = write(fd, buf, len);
350 			if (wr < 0)
351 				return (-1);
352 		} else {
353 			while (len < sz && *p++ == '\0')
354 				len++;
355 			if (len < sz)
356 				len &= ~(secsz - 1);
357 			if (len == 0)
358 				continue;
359 			ofs = lseek(fd, len, SEEK_CUR);
360 			if (ofs < 0)
361 				return (-1);
362 			wr = len;
363 		}
364 		buf += wr;
365 		sz -= wr;
366 		wrsz += wr;
367 		p = memchr(buf, 0, sz);
368 	}
369 	return (wrsz);
370 }
371 #endif /* SPARSE_WRITE */
372 
373 void
mkimg_chs(lba_t lba,u_int maxcyl,u_int * cylp,u_int * hdp,u_int * secp)374 mkimg_chs(lba_t lba, u_int maxcyl, u_int *cylp, u_int *hdp, u_int *secp)
375 {
376 	u_int hd, sec;
377 
378 	*cylp = *hdp = *secp = ~0U;
379 	if (nsecs == 1 || nheads == 1)
380 		return;
381 
382 	sec = lba % nsecs + 1;
383 	lba /= nsecs;
384 	hd = lba % nheads;
385 	lba /= nheads;
386 	if (lba > maxcyl)
387 		return;
388 
389 	*cylp = lba;
390 	*hdp = hd;
391 	*secp = sec;
392 }
393 
394 static int
capacity_resize(lba_t end)395 capacity_resize(lba_t end)
396 {
397 	lba_t min_capsz, max_capsz;
398 
399 	min_capsz = (min_capacity + secsz - 1) / secsz;
400 	max_capsz = (max_capacity + secsz - 1) / secsz;
401 
402 	if (max_capsz != 0 && end > max_capsz)
403 		return (ENOSPC);
404 	if (end >= min_capsz)
405 		return (0);
406 
407 	return (image_set_size(min_capsz));
408 }
409 
410 static void
mkimg_validate(void)411 mkimg_validate(void)
412 {
413 	struct part *part, *part2;
414 	lba_t start, end, start2, end2;
415 	int i, j;
416 
417 	i = 0;
418 
419 	TAILQ_FOREACH(part, &partlist, link) {
420 		start = part->block;
421 		end = part->block + part->size;
422 		j = i + 1;
423 		part2 = TAILQ_NEXT(part, link);
424 		if (part2 == NULL)
425 			break;
426 
427 		TAILQ_FOREACH_FROM(part2, &partlist, link) {
428 			start2 = part2->block;
429 			end2 = part2->block + part2->size;
430 
431 			if ((start >= start2 && start < end2) ||
432 			    (end > start2 && end <= end2)) {
433 				errx(1, "partition %d overlaps partition %d",
434 				    i, j);
435 			}
436 
437 			j++;
438 		}
439 
440 		i++;
441 	}
442 }
443 
444 static void
mkimg(void)445 mkimg(void)
446 {
447 	FILE *fp;
448 	struct part *part;
449 	struct stat sb;
450 	char *p;
451 	lba_t block, blkoffset;
452 	uint64_t bytesize, byteoffset;
453 	char *size, *offset;
454 	bool abs_offset;
455 	int error, fd;
456 
457 	/* First check partition information */
458 	TAILQ_FOREACH(part, &partlist, link) {
459 		error = scheme_check_part(part);
460 		if (error)
461 			errc(EX_DATAERR, error, "partition %d", part->index+1);
462 	}
463 
464 	block = scheme_metadata(SCHEME_META_IMG_START, 0);
465 	abs_offset = false;
466 	TAILQ_FOREACH(part, &partlist, link) {
467 		byteoffset = blkoffset = 0;
468 		abs_offset = false;
469 
470 		/* Look for an offset. Set size too if we can. */
471 		switch (part->kind) {
472 		case PART_KIND_SIZE:
473 			offset = part->contents;
474 			size = strsep(&offset, ":");
475 			if (expand_number(size, &bytesize) == -1)
476 				error = errno;
477 			break;
478 		case PART_KIND_FILE:
479 			size = part->contents;
480 			if (stat(part->contents, &sb) == 0) {
481 				if (S_ISDIR(sb.st_mode)) {
482 					errc(EX_IOERR, EISDIR, "partition %d",
483 					    part->index + 1);
484 				}
485 				offset = NULL;
486 			} else {
487 				p = strrchr(part->contents, ':');
488 				if (p != NULL) {
489 					*p = '\0';
490 					offset = p + 1;
491 				} else {
492 					offset = NULL;
493 				}
494 			}
495 			break;
496 		default:
497 			offset = NULL;
498 			break;
499 		}
500 
501 		if (offset != NULL) {
502 			if (*offset != '+')
503 				abs_offset = true;
504 			else
505 				offset++;
506 			if (expand_number(offset, &byteoffset) == -1)
507 				error = errno;
508 		}
509 
510 		/* Work out exactly where the partition starts. */
511 		blkoffset = (byteoffset + secsz - 1) / secsz;
512 		if (abs_offset)
513 			block = scheme_metadata(SCHEME_META_PART_ABSOLUTE,
514 			    blkoffset);
515 		else
516 			block = scheme_metadata(SCHEME_META_PART_BEFORE,
517 			    block + blkoffset);
518 		part->block = block;
519 
520 		if (verbose)
521 			fprintf(stderr, "partition %d: starting block %llu "
522 			    "... ", part->index + 1, (long long)part->block);
523 
524 		/* Pull in partition contents, set size if we haven't yet. */
525 		switch (part->kind) {
526 		case PART_KIND_FILE:
527 			fd = open(part->contents, O_RDONLY, 0);
528 			if (fd != -1) {
529 				error = image_copyin(block, fd, &bytesize);
530 				close(fd);
531 			} else
532 				error = errno;
533 			break;
534 		case PART_KIND_PIPE:
535 			fp = popen(part->contents, "r");
536 			if (fp != NULL) {
537 				fd = fileno(fp);
538 				error = image_copyin(block, fd, &bytesize);
539 				pclose(fp);
540 			} else
541 				error = errno;
542 			break;
543 		}
544 		if (error)
545 			errc(EX_IOERR, error, "partition %d", part->index + 1);
546 		part->size = (bytesize + secsz - 1) / secsz;
547 		if (verbose) {
548 			bytesize = part->size * secsz;
549 			fprintf(stderr, "size %llu bytes (%llu blocks)\n",
550 			     (long long)bytesize, (long long)part->size);
551 			if (abs_offset) {
552 				fprintf(stderr,
553 				    "    location %llu bytes (%llu blocks)\n",
554 				    (long long)byteoffset,
555 				    (long long)blkoffset);
556 			} else if (blkoffset > 0) {
557 				fprintf(stderr,
558 				    "    offset %llu bytes (%llu blocks)\n",
559 				    (long long)byteoffset,
560 				    (long long)blkoffset);
561 			}
562 		}
563 		block = scheme_metadata(SCHEME_META_PART_AFTER,
564 		    part->block + part->size);
565 	}
566 
567 	mkimg_validate();
568 
569 	block = scheme_metadata(SCHEME_META_IMG_END, block);
570 	error = image_set_size(block);
571 	if (!error) {
572 		error = capacity_resize(block);
573 		block = image_get_size();
574 	}
575 	if (!error) {
576 		error = format_resize(block);
577 		block = image_get_size();
578 	}
579 	if (error)
580 		errc(EX_IOERR, error, "image sizing");
581 	ncyls = block / (nsecs * nheads);
582 	error = scheme_write(block);
583 	if (error)
584 		errc(EX_IOERR, error, "writing metadata");
585 }
586 
587 int
main(int argc,char * argv[])588 main(int argc, char *argv[])
589 {
590 	const char *format_name;
591 	int bcfd, outfd;
592 	int c, error;
593 
594 	bcfd = -1;
595 	outfd = 1;	/* Write to stdout by default */
596 	while ((c = getopt_long(argc, argv, "a:b:c:C:f:ho:p:s:t:vyH:P:S:T:",
597 	    longopts, NULL)) != -1) {
598 		switch (c) {
599 		case 'a':	/* ACTIVE PARTITION, if supported */
600 			error = parse_uint32(&active_partition, 1, 100, optarg);
601 			if (error)
602 				errc(EX_DATAERR, error, "Partition ordinal");
603 			break;
604 		case 'b':	/* BOOT CODE */
605 			if (bcfd != -1)
606 				usage("multiple bootcode given");
607 			bcfd = open(optarg, O_RDONLY, 0);
608 			if (bcfd == -1)
609 				err(EX_UNAVAILABLE, "%s", optarg);
610 			break;
611 		case 'c':	/* MINIMUM CAPACITY */
612 			error = parse_uint64(&min_capacity, 1, INT64_MAX, optarg);
613 			if (error)
614 				errc(EX_DATAERR, error, "minimum capacity in bytes");
615 			break;
616 		case 'C':	/* MAXIMUM CAPACITY */
617 			error = parse_uint64(&max_capacity, 1, INT64_MAX, optarg);
618 			if (error)
619 				errc(EX_DATAERR, error, "maximum capacity in bytes");
620 			break;
621 		case 'f':	/* OUTPUT FORMAT */
622 			if (format_selected() != NULL)
623 				usage("multiple formats given");
624 			error = format_select(optarg);
625 			if (error)
626 				errc(EX_DATAERR, error, "format");
627 			break;
628 		case 'h':	/* HELP */
629 			usage(NULL);
630 			break;
631 		case 'o':	/* OUTPUT FILE */
632 			if (outfd != 1)
633 				usage("multiple output files given");
634 			outfd = open(optarg, O_WRONLY | O_CREAT | O_TRUNC,
635 			    S_IWUSR | S_IRUSR | S_IRGRP | S_IROTH);
636 			if (outfd == -1)
637 				err(EX_CANTCREAT, "%s", optarg);
638 			break;
639 		case 'p':	/* PARTITION */
640 			error = parse_part(optarg);
641 			if (error)
642 				errc(EX_DATAERR, error, "partition");
643 			break;
644 		case 's':	/* SCHEME */
645 			if (scheme_selected() != NULL)
646 				usage("multiple schemes given");
647 			error = scheme_select(optarg);
648 			if (error)
649 				errc(EX_DATAERR, error, "scheme");
650 			break;
651 		case 't': {
652 			char *ep;
653 			long long val;
654 
655 			errno = 0;
656 			val = strtoll(optarg, &ep, 0);
657 			if (ep == optarg || *ep != '\0')
658 				errno = EINVAL;
659 			if (errno != 0)
660 				errc(EX_DATAERR, errno, "timestamp");
661 			timestamp = (time_t)val;
662 			break;
663 		}
664 		case 'y':
665 			unit_testing++;
666 			break;
667 		case 'v':
668 			verbose++;
669 			break;
670 		case 'H':	/* GEOMETRY: HEADS */
671 			error = parse_uint32(&nheads, 1, 255, optarg);
672 			if (error)
673 				errc(EX_DATAERR, error, "number of heads");
674 			break;
675 		case 'P':	/* GEOMETRY: PHYSICAL SECTOR SIZE */
676 			error = parse_uint32(&blksz, 512, INT_MAX+1U, optarg);
677 			if (error == 0 && !pwr_of_two(blksz))
678 				error = EINVAL;
679 			if (error)
680 				errc(EX_DATAERR, error, "physical sector size");
681 			break;
682 		case 'S':	/* GEOMETRY: LOGICAL SECTOR SIZE */
683 			error = parse_uint32(&secsz, 512, INT_MAX+1U, optarg);
684 			if (error == 0 && !pwr_of_two(secsz))
685 				error = EINVAL;
686 			if (error)
687 				errc(EX_DATAERR, error, "logical sector size");
688 			break;
689 		case 'T':	/* GEOMETRY: TRACK SIZE */
690 			error = parse_uint32(&nsecs, 1, 63, optarg);
691 			if (error)
692 				errc(EX_DATAERR, error, "track size");
693 			break;
694 		case LONGOPT_FORMATS:
695 			print_formats(0);
696 			exit(EX_OK);
697 			/*NOTREACHED*/
698 		case LONGOPT_SCHEMES:
699 			print_schemes(0);
700 			exit(EX_OK);
701 			/*NOTREACHED*/
702 		case LONGOPT_VERSION:
703 			print_version();
704 			exit(EX_OK);
705 			/*NOTREACHED*/
706 		case LONGOPT_CAPACITY:
707 			error = parse_uint64(&min_capacity, 1, INT64_MAX, optarg);
708 			if (error)
709 				errc(EX_DATAERR, error, "capacity in bytes");
710 			max_capacity = min_capacity;
711 			break;
712 		default:
713 			usage("unknown option");
714 		}
715 	}
716 
717 	if (argc > optind)
718 		usage("trailing arguments");
719 	if (scheme_selected() == NULL && nparts > 0)
720 		usage("no scheme");
721 	if (nparts == 0 && min_capacity == 0)
722 		usage("no partitions");
723 	if (max_capacity != 0 && min_capacity > max_capacity)
724 		usage("minimum capacity cannot be larger than the maximum one");
725 
726 	if (secsz > blksz) {
727 		if (blksz != 0)
728 			errx(EX_DATAERR, "the physical block size cannot "
729 			    "be smaller than the sector size");
730 		blksz = secsz;
731 	}
732 
733 	if (secsz > scheme_max_secsz())
734 		errx(EX_DATAERR, "maximum sector size supported is %u; "
735 		    "size specified is %u", scheme_max_secsz(), secsz);
736 
737 	if (nparts > scheme_max_parts())
738 		errx(EX_DATAERR, "%d partitions supported; %d given",
739 		    scheme_max_parts(), nparts);
740 
741 	if (format_selected() == NULL)
742 		format_select("raw");
743 
744 	if (bcfd != -1) {
745 		error = scheme_bootcode(bcfd);
746 		close(bcfd);
747 		if (error)
748 			errc(EX_DATAERR, error, "boot code");
749 	}
750 
751 	format_name = format_selected()->name;
752 	if (verbose) {
753 		fprintf(stderr, "Logical sector size: %u\n", secsz);
754 		fprintf(stderr, "Physical block size: %u\n", blksz);
755 		fprintf(stderr, "Sectors per track:   %u\n", nsecs);
756 		fprintf(stderr, "Number of heads:     %u\n", nheads);
757 		fputc('\n', stderr);
758 		if (scheme_selected())
759 			fprintf(stderr, "Partitioning scheme: %s\n",
760 			    scheme_selected()->name);
761 		fprintf(stderr, "Output file format:  %s\n",
762 		    format_name);
763 		fputc('\n', stderr);
764 	}
765 
766 #if defined(SPARSE_WRITE)
767 	/*
768 	 * sparse_write() fails if output is not seekable so fail early
769 	 * not wasting some load unless output format is raw
770 	 */
771 	if (strcmp("raw", format_name) &&
772 	    lseek(outfd, (off_t)0, SEEK_CUR) == -1 && errno == ESPIPE)
773 		errx(EX_USAGE, "%s: output must be seekable", format_name);
774 #endif
775 
776 	error = image_init();
777 	if (error)
778 		errc(EX_OSERR, error, "cannot initialize");
779 
780 	mkimg();
781 
782 	if (verbose) {
783 		fputc('\n', stderr);
784 		fprintf(stderr, "Number of cylinders: %u\n", ncyls);
785 	}
786 
787 	error = format_write(outfd);
788 	if (error)
789 		errc(EX_IOERR, error, "writing image");
790 
791 	return (0);
792 }
793