Home | History | Annotate | Line # | Download | only in sysinst
disks.c revision 1.81
      1 /*	$NetBSD: disks.c,v 1.81 2022/06/02 15:36:08 martin Exp $ */
      2 
      3 /*
      4  * Copyright 1997 Piermont Information Systems Inc.
      5  * All rights reserved.
      6  *
      7  * Written by Philip A. Nelson for Piermont Information Systems Inc.
      8  *
      9  * Redistribution and use in source and binary forms, with or without
     10  * modification, are permitted provided that the following conditions
     11  * are met:
     12  * 1. Redistributions of source code must retain the above copyright
     13  *    notice, this list of conditions and the following disclaimer.
     14  * 2. Redistributions in binary form must reproduce the above copyright
     15  *    notice, this list of conditions and the following disclaimer in the
     16  *    documentation and/or other materials provided with the distribution.
     17  * 3. The name of Piermont Information Systems Inc. may not be used to endorse
     18  *    or promote products derived from this software without specific prior
     19  *    written permission.
     20  *
     21  * THIS SOFTWARE IS PROVIDED BY PIERMONT INFORMATION SYSTEMS INC. ``AS IS''
     22  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     24  * ARE DISCLAIMED. IN NO EVENT SHALL PIERMONT INFORMATION SYSTEMS INC. BE
     25  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     26  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     27  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     28  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     29  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     30  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
     31  * THE POSSIBILITY OF SUCH DAMAGE.
     32  *
     33  */
     34 
     35 /* disks.c -- routines to deal with finding disks and labeling disks. */
     36 
     37 
     38 #include <assert.h>
     39 #include <errno.h>
     40 #include <inttypes.h>
     41 #include <stdio.h>
     42 #include <stdlib.h>
     43 #include <unistd.h>
     44 #include <fcntl.h>
     45 #include <fnmatch.h>
     46 #include <util.h>
     47 #include <uuid.h>
     48 #include <paths.h>
     49 #include <fstab.h>
     50 
     51 #include <sys/param.h>
     52 #include <sys/sysctl.h>
     53 #include <sys/swap.h>
     54 #include <sys/disklabel_gpt.h>
     55 #include <ufs/ufs/dinode.h>
     56 #include <ufs/ffs/fs.h>
     57 
     58 #include <dev/scsipi/scsipi_all.h>
     59 #include <sys/scsiio.h>
     60 
     61 #include <dev/ata/atareg.h>
     62 #include <sys/ataio.h>
     63 
     64 #include <sys/drvctlio.h>
     65 
     66 #include "defs.h"
     67 #include "md.h"
     68 #include "msg_defs.h"
     69 #include "menu_defs.h"
     70 #include "txtwalk.h"
     71 
     72 /* #define DEBUG_VERBOSE	1 */
     73 
     74 /* Disk descriptions */
     75 struct disk_desc {
     76 	char	dd_name[SSTRSIZE];
     77 	char	dd_descr[256];
     78 	bool	dd_no_mbr, dd_no_part;
     79 	uint	dd_cyl;
     80 	uint	dd_head;
     81 	uint	dd_sec;
     82 	uint	dd_secsize;
     83 	daddr_t	dd_totsec;
     84 };
     85 
     86 #define	NAME_PREFIX	"NAME="
     87 static const char name_prefix[] = NAME_PREFIX;
     88 
     89 /* things we could have as /sbin/newfs_* and /sbin/fsck_* */
     90 static const char *extern_fs_with_chk[] = {
     91 	"ext2fs", "lfs", "msdos", "v7fs"
     92 };
     93 
     94 /* things we could have as /sbin/newfs_* but not /sbin/fsck_* */
     95 static const char *extern_fs_newfs_only[] = {
     96 	"sysvbfs", "udf"
     97 };
     98 
     99 /* Local prototypes */
    100 static int found_fs(struct data *, size_t, const struct lookfor*);
    101 static int found_fs_nocheck(struct data *, size_t, const struct lookfor*);
    102 static int fsck_preen(const char *, const char *, bool silent);
    103 static void fixsb(const char *, const char *);
    104 
    105 
    106 static bool tmpfs_on_var_shm(void);
    107 
    108 const char *
    109 getfslabelname(uint f, uint f_version)
    110 {
    111 	if (f == FS_TMPFS)
    112 		return "tmpfs";
    113 	else if (f == FS_MFS)
    114 		return "mfs";
    115 	else if (f == FS_BSDFFS && f_version > 0)
    116 		return f_version == 2 ?
    117 		    msg_string(MSG_fs_type_ffsv2) : msg_string(MSG_fs_type_ffs);
    118 	else if (f == FS_EX2FS && f_version == 1)
    119 		return msg_string(MSG_fs_type_ext2old);
    120 	else if (f >= __arraycount(fstypenames) || fstypenames[f] == NULL)
    121 		return "invalid";
    122 	return fstypenames[f];
    123 }
    124 
    125 /*
    126  * Decide wether we want to mount a tmpfs on /var/shm: we do this always
    127  * when the machine has more than 16 MB of user memory. On smaller machines,
    128  * shm_open() and friends will not perform well anyway.
    129  */
    130 static bool
    131 tmpfs_on_var_shm()
    132 {
    133 	uint64_t ram;
    134 	size_t len;
    135 
    136 	len = sizeof(ram);
    137 	if (sysctlbyname("hw.usermem64", &ram, &len, NULL, 0))
    138 		return false;
    139 
    140 	return ram > 16 * MEG;
    141 }
    142 
    143 /* from src/sbin/atactl/atactl.c
    144  * extract_string: copy a block of bytes out of ataparams and make
    145  * a proper string out of it, truncating trailing spaces and preserving
    146  * strict typing. And also, not doing unaligned accesses.
    147  */
    148 static void
    149 ata_extract_string(char *buf, size_t bufmax,
    150 		   uint8_t *bytes, unsigned numbytes,
    151 		   int needswap)
    152 {
    153 	unsigned i;
    154 	size_t j;
    155 	unsigned char ch1, ch2;
    156 
    157 	for (i = 0, j = 0; i < numbytes; i += 2) {
    158 		ch1 = bytes[i];
    159 		ch2 = bytes[i+1];
    160 		if (needswap && j < bufmax-1) {
    161 			buf[j++] = ch2;
    162 		}
    163 		if (j < bufmax-1) {
    164 			buf[j++] = ch1;
    165 		}
    166 		if (!needswap && j < bufmax-1) {
    167 			buf[j++] = ch2;
    168 		}
    169 	}
    170 	while (j > 0 && buf[j-1] == ' ') {
    171 		j--;
    172 	}
    173 	buf[j] = '\0';
    174 }
    175 
    176 /*
    177  * from src/sbin/scsictl/scsi_subr.c
    178  */
    179 #define STRVIS_ISWHITE(x) ((x) == ' ' || (x) == '\0' || (x) == (u_char)'\377')
    180 
    181 static void
    182 scsi_strvis(char *sdst, size_t dlen, const char *ssrc, size_t slen)
    183 {
    184 	u_char *dst = (u_char *)sdst;
    185 	const u_char *src = (const u_char *)ssrc;
    186 
    187 	/* Trim leading and trailing blanks and NULs. */
    188 	while (slen > 0 && STRVIS_ISWHITE(src[0]))
    189 		++src, --slen;
    190 	while (slen > 0 && STRVIS_ISWHITE(src[slen - 1]))
    191 		--slen;
    192 
    193 	while (slen > 0) {
    194 		if (*src < 0x20 || *src >= 0x80) {
    195 			/* non-printable characters */
    196 			dlen -= 4;
    197 			if (dlen < 1)
    198 				break;
    199 			*dst++ = '\\';
    200 			*dst++ = ((*src & 0300) >> 6) + '0';
    201 			*dst++ = ((*src & 0070) >> 3) + '0';
    202 			*dst++ = ((*src & 0007) >> 0) + '0';
    203 		} else if (*src == '\\') {
    204 			/* quote characters */
    205 			dlen -= 2;
    206 			if (dlen < 1)
    207 				break;
    208 			*dst++ = '\\';
    209 			*dst++ = '\\';
    210 		} else {
    211 			/* normal characters */
    212 			if (--dlen < 1)
    213 				break;
    214 			*dst++ = *src;
    215 		}
    216 		++src, --slen;
    217 	}
    218 
    219 	*dst++ = 0;
    220 }
    221 
    222 
    223 static int
    224 get_descr_scsi(struct disk_desc *dd)
    225 {
    226 	struct scsipi_inquiry_data inqbuf;
    227 	struct scsipi_inquiry cmd;
    228 	scsireq_t req;
    229         /* x4 in case every character is escaped, +1 for NUL. */
    230 	char vendor[(sizeof(inqbuf.vendor) * 4) + 1],
    231 	     product[(sizeof(inqbuf.product) * 4) + 1],
    232 	     revision[(sizeof(inqbuf.revision) * 4) + 1];
    233 	char size[5];
    234 
    235 	memset(&inqbuf, 0, sizeof(inqbuf));
    236 	memset(&cmd, 0, sizeof(cmd));
    237 	memset(&req, 0, sizeof(req));
    238 
    239 	cmd.opcode = INQUIRY;
    240 	cmd.length = sizeof(inqbuf);
    241 	memcpy(req.cmd, &cmd, sizeof(cmd));
    242 	req.cmdlen = sizeof(cmd);
    243 	req.databuf = &inqbuf;
    244 	req.datalen = sizeof(inqbuf);
    245 	req.timeout = 10000;
    246 	req.flags = SCCMD_READ;
    247 	req.senselen = SENSEBUFLEN;
    248 
    249 	if (!disk_ioctl(dd->dd_name, SCIOCCOMMAND, &req)
    250 	    || req.retsts != SCCMD_OK)
    251 		return 0;
    252 
    253 	scsi_strvis(vendor, sizeof(vendor), inqbuf.vendor,
    254 	    sizeof(inqbuf.vendor));
    255 	scsi_strvis(product, sizeof(product), inqbuf.product,
    256 	    sizeof(inqbuf.product));
    257 	scsi_strvis(revision, sizeof(revision), inqbuf.revision,
    258 	    sizeof(inqbuf.revision));
    259 
    260 	humanize_number(size, sizeof(size),
    261 	    (uint64_t)dd->dd_secsize * (uint64_t)dd->dd_totsec,
    262 	    "", HN_AUTOSCALE, HN_B | HN_NOSPACE | HN_DECIMAL);
    263 
    264 	snprintf(dd->dd_descr, sizeof(dd->dd_descr),
    265 	    "%s (%s, %s %s)",
    266 	    dd->dd_name, size, vendor, product);
    267 
    268 	return 1;
    269 }
    270 
    271 static int
    272 get_descr_ata(struct disk_desc *dd)
    273 {
    274 	struct atareq req;
    275 	static union {
    276 		unsigned char inbuf[DEV_BSIZE];
    277 		struct ataparams inqbuf;
    278 	} inbuf;
    279 	struct ataparams *inqbuf = &inbuf.inqbuf;
    280 	char model[sizeof(inqbuf->atap_model)+1];
    281 	char size[5];
    282 	int needswap = 0;
    283 
    284 	memset(&inbuf, 0, sizeof(inbuf));
    285 	memset(&req, 0, sizeof(req));
    286 
    287 	req.flags = ATACMD_READ;
    288 	req.command = WDCC_IDENTIFY;
    289 	req.databuf = (void *)&inbuf;
    290 	req.datalen = sizeof(inbuf);
    291 	req.timeout = 1000;
    292 
    293 	if (!disk_ioctl(dd->dd_name, ATAIOCCOMMAND, &req)
    294 	    || req.retsts != ATACMD_OK)
    295 		return 0;
    296 
    297 #if BYTE_ORDER == LITTLE_ENDIAN
    298 	/*
    299 	 * On little endian machines, we need to shuffle the string
    300 	 * byte order.  However, we don't have to do this for NEC or
    301 	 * Mitsumi ATAPI devices
    302 	 */
    303 
    304 	if (!(inqbuf->atap_config != WDC_CFG_CFA_MAGIC &&
    305 	      (inqbuf->atap_config & WDC_CFG_ATAPI) &&
    306 	      ((inqbuf->atap_model[0] == 'N' &&
    307 	        inqbuf->atap_model[1] == 'E') ||
    308 	       (inqbuf->atap_model[0] == 'F' &&
    309 	        inqbuf->atap_model[1] == 'X')))) {
    310 		needswap = 1;
    311 	}
    312 #endif
    313 
    314 	ata_extract_string(model, sizeof(model),
    315 	    inqbuf->atap_model, sizeof(inqbuf->atap_model), needswap);
    316 	humanize_number(size, sizeof(size),
    317 	    (uint64_t)dd->dd_secsize * (uint64_t)dd->dd_totsec,
    318 	    "", HN_AUTOSCALE, HN_B | HN_NOSPACE | HN_DECIMAL);
    319 
    320 	snprintf(dd->dd_descr, sizeof(dd->dd_descr), "%s (%s, %s)",
    321 	    dd->dd_name, size, model);
    322 
    323 	return 1;
    324 }
    325 
    326 static int
    327 get_descr_drvctl(struct disk_desc *dd)
    328 {
    329 	prop_dictionary_t command_dict;
    330 	prop_dictionary_t args_dict;
    331 	prop_dictionary_t results_dict;
    332 	prop_dictionary_t props;
    333 	int8_t perr;
    334 	int error, fd;
    335 	bool rv;
    336 	char size[5];
    337 	const char *model;
    338 
    339 	fd = open("/dev/drvctl", O_RDONLY);
    340 	if (fd == -1)
    341 		return 0;
    342 
    343 	command_dict = prop_dictionary_create();
    344 	args_dict = prop_dictionary_create();
    345 
    346 	prop_dictionary_set_string_nocopy(command_dict, "drvctl-command",
    347 	    "get-properties");
    348 	prop_dictionary_set_string_nocopy(args_dict, "device-name",
    349 	    dd->dd_name);
    350 	prop_dictionary_set(command_dict, "drvctl-arguments", args_dict);
    351 	prop_object_release(args_dict);
    352 
    353 	error = prop_dictionary_sendrecv_ioctl(command_dict, fd,
    354 	    DRVCTLCOMMAND, &results_dict);
    355 	prop_object_release(command_dict);
    356 	close(fd);
    357 	if (error)
    358 		return 0;
    359 
    360 	rv = prop_dictionary_get_int8(results_dict, "drvctl-error", &perr);
    361 	if (rv == false || perr != 0) {
    362 		prop_object_release(results_dict);
    363 		return 0;
    364 	}
    365 
    366 	props = prop_dictionary_get(results_dict,
    367 	    "drvctl-result-data");
    368 	if (props == NULL) {
    369 		prop_object_release(results_dict);
    370 		return 0;
    371 	}
    372 	props = prop_dictionary_get(props, "disk-info");
    373 	if (props == NULL ||
    374 	    !prop_dictionary_get_string(props, "type", &model)) {
    375 		prop_object_release(results_dict);
    376 		return 0;
    377 	}
    378 
    379 	humanize_number(size, sizeof(size),
    380 	    (uint64_t)dd->dd_secsize * (uint64_t)dd->dd_totsec,
    381 	    "", HN_AUTOSCALE, HN_B | HN_NOSPACE | HN_DECIMAL);
    382 
    383 	snprintf(dd->dd_descr, sizeof(dd->dd_descr), "%s (%s, %s)",
    384 	    dd->dd_name, size, model);
    385 
    386 	prop_object_release(results_dict);
    387 
    388 	return 1;
    389 }
    390 
    391 static void
    392 get_descr(struct disk_desc *dd)
    393 {
    394 	char size[5];
    395 	dd->dd_descr[0] = '\0';
    396 
    397 	/* try drvctl first, fallback to direct probing */
    398 	if (get_descr_drvctl(dd))
    399 		return;
    400 	/* try ATA */
    401 	if (get_descr_ata(dd))
    402 		return;
    403 	/* try SCSI */
    404 	if (get_descr_scsi(dd))
    405 		return;
    406 
    407 	/* XXX: get description from raid, cgd, vnd... */
    408 
    409 	/* punt, just give some generic info */
    410 	humanize_number(size, sizeof(size),
    411 	    (uint64_t)dd->dd_secsize * (uint64_t)dd->dd_totsec,
    412 	    "", HN_AUTOSCALE, HN_B | HN_NOSPACE | HN_DECIMAL);
    413 
    414 	snprintf(dd->dd_descr, sizeof(dd->dd_descr),
    415 	    "%s (%s)", dd->dd_name, size);
    416 }
    417 
    418 /*
    419  * State for helper callback for get_default_cdrom
    420  */
    421 struct default_cdrom_data {
    422 	char *device;
    423 	size_t max_len;
    424 	bool found;
    425 };
    426 
    427 /*
    428  * Helper function for get_default_cdrom, gets passed a device
    429  * name and a void pointer to default_cdrom_data.
    430  */
    431 static bool
    432 get_default_cdrom_helper(void *state, const char *dev)
    433 {
    434 	struct default_cdrom_data *data = state;
    435 
    436 	if (!is_cdrom_device(dev, false))
    437 		return true;
    438 
    439 	strlcpy(data->device, dev, data->max_len);
    440 	strlcat(data->device, "a", data->max_len); /* default to partition a */
    441 	data->found = true;
    442 
    443 	return false;	/* one is enough, stop iteration */
    444 }
    445 
    446 /*
    447  * Set the argument to the name of the first CD devices actually
    448  * available, leave it unmodified otherwise.
    449  * Return true if a device has been found.
    450  */
    451 bool
    452 get_default_cdrom(char *cd, size_t max_len)
    453 {
    454 	struct default_cdrom_data state;
    455 
    456 	state.device = cd;
    457 	state.max_len = max_len;
    458 	state.found = false;
    459 
    460 	if (enumerate_disks(&state, get_default_cdrom_helper))
    461 		return state.found;
    462 
    463 	return false;
    464 }
    465 
    466 static bool
    467 get_wedge_descr(struct disk_desc *dd)
    468 {
    469 	struct dkwedge_info dkw;
    470 
    471 	if (!get_wedge_info(dd->dd_name, &dkw))
    472 		return false;
    473 
    474 	snprintf(dd->dd_descr, sizeof(dd->dd_descr), "%s (%s@%s)",
    475 	    dkw.dkw_wname, dkw.dkw_devname, dkw.dkw_parent);
    476 	return true;
    477 }
    478 
    479 static bool
    480 get_name_and_parent(const char *dev, char *name, char *parent)
    481 {
    482 	struct dkwedge_info dkw;
    483 
    484 	if (!get_wedge_info(dev, &dkw))
    485 		return false;
    486 	strcpy(name, (const char *)dkw.dkw_wname);
    487 	strcpy(parent, dkw.dkw_parent);
    488 	return true;
    489 }
    490 
    491 static bool
    492 find_swap_part_on(const char *dev, char *swap_name)
    493 {
    494 	struct dkwedge_list dkwl;
    495 	struct dkwedge_info *dkw;
    496 	u_int i;
    497 	bool res = false;
    498 
    499 	if (!get_wedge_list(dev, &dkwl))
    500 		return false;
    501 
    502 	dkw = dkwl.dkwl_buf;
    503 	for (i = 0; i < dkwl.dkwl_nwedges; i++) {
    504 		res = strcmp(dkw[i].dkw_ptype, DKW_PTYPE_SWAP) == 0;
    505 		if (res) {
    506 			strcpy(swap_name, (const char*)dkw[i].dkw_wname);
    507 			break;
    508 		}
    509 	}
    510 	free(dkwl.dkwl_buf);
    511 
    512 	return res;
    513 }
    514 
    515 static bool
    516 is_ffs_wedge(const char *dev)
    517 {
    518 	struct dkwedge_info dkw;
    519 
    520 	if (!get_wedge_info(dev, &dkw))
    521 		return false;
    522 
    523 	return strcmp(dkw.dkw_ptype, DKW_PTYPE_FFS) == 0;
    524 }
    525 
    526 /*
    527  * Does this device match an entry in our default CDROM device list?
    528  * If looking for install targets, we also flag floopy devices.
    529  */
    530 bool
    531 is_cdrom_device(const char *dev, bool as_target)
    532 {
    533 	static const char *target_devices[] = {
    534 #ifdef CD_NAMES
    535 		CD_NAMES
    536 #endif
    537 #if defined(CD_NAMES) && defined(FLOPPY_NAMES)
    538 		,
    539 #endif
    540 #ifdef FLOPPY_NAMES
    541 		FLOPPY_NAMES
    542 #endif
    543 #if defined(CD_NAMES) || defined(FLOPPY_NAMES)
    544 		,
    545 #endif
    546 		0
    547 	};
    548 	static const char *src_devices[] = {
    549 #ifdef CD_NAMES
    550 		CD_NAMES ,
    551 #endif
    552 		0
    553 	};
    554 
    555 	for (const char **dev_pat = as_target ? target_devices : src_devices;
    556 	     *dev_pat; dev_pat++)
    557 		if (fnmatch(*dev_pat, dev, 0) == 0)
    558 			return true;
    559 
    560 	return false;
    561 }
    562 
    563 /* does this device match any entry in the driver list? */
    564 static bool
    565 dev_in_list(const char *dev, const char **list)
    566 {
    567 
    568 	for ( ; *list; list++) {
    569 
    570 		size_t len = strlen(*list);
    571 
    572 		/* start of name matches? */
    573 		if (strncmp(dev, *list, len) == 0) {
    574 			char *endp;
    575 			int e;
    576 
    577 			/* remainder of name is a decimal number? */
    578 			strtou(dev+len, &endp, 10, 0, INT_MAX, &e);
    579 			if (endp && *endp == 0 && e == 0)
    580 				return true;
    581 		}
    582 	}
    583 
    584 	return false;
    585 }
    586 
    587 bool
    588 is_bootable_device(const char *dev)
    589 {
    590 	static const char *non_bootable_devs[] = {
    591 		"raid",	/* bootcode lives outside of raid */
    592 		"xbd",	/* xen virtual device, can not boot from that */
    593 		NULL
    594 	};
    595 
    596 	return !dev_in_list(dev, non_bootable_devs);
    597 }
    598 
    599 bool
    600 is_partitionable_device(const char *dev)
    601 {
    602 	static const char *non_partitionable_devs[] = {
    603 		"dk",	/* this is already a partitioned slice */
    604 		NULL
    605 	};
    606 
    607 	return !dev_in_list(dev, non_partitionable_devs);
    608 }
    609 
    610 /*
    611  * Multi-purpose helper function:
    612  * iterate all known disks, invoke a callback for each.
    613  * Stop iteration when the callback returns false.
    614  * Return true when iteration actually happened, false on error.
    615  */
    616 bool
    617 enumerate_disks(void *state, bool (*func)(void *state, const char *dev))
    618 {
    619 	static const int mib[] = { CTL_HW, HW_DISKNAMES };
    620 	static const unsigned int miblen = __arraycount(mib);
    621 	const char *xd;
    622 	char *disk_names;
    623 	size_t len;
    624 
    625 	if (sysctl(mib, miblen, NULL, &len, NULL, 0) == -1)
    626 		return false;
    627 
    628 	disk_names = malloc(len);
    629 	if (disk_names == NULL)
    630 		return false;
    631 
    632 	if (sysctl(mib, miblen, disk_names, &len, NULL, 0) == -1) {
    633 		free(disk_names);
    634 		return false;
    635 	}
    636 
    637 	for (xd = strtok(disk_names, " "); xd != NULL; xd = strtok(NULL, " ")) {
    638 		if (!(*func)(state, xd))
    639 			break;
    640 	}
    641 	free(disk_names);
    642 
    643 	return true;
    644 }
    645 
    646 /*
    647  * Helper state for get_disks
    648  */
    649 struct get_disks_state {
    650 	int numdisks;
    651 	struct disk_desc *dd;
    652 	bool with_non_partitionable;
    653 };
    654 
    655 /*
    656  * Helper function for get_disks enumartion
    657  */
    658 static bool
    659 get_disks_helper(void *arg, const char *dev)
    660 {
    661 	struct get_disks_state *state = arg;
    662 	struct disk_geom geo;
    663 
    664 	/* is this a CD device? */
    665 	if (is_cdrom_device(dev, true))
    666 		return true;
    667 
    668 	memset(state->dd, 0, sizeof(*state->dd));
    669 	strlcpy(state->dd->dd_name, dev, sizeof state->dd->dd_name - 2);
    670 	state->dd->dd_no_mbr = !is_bootable_device(dev);
    671 	state->dd->dd_no_part = !is_partitionable_device(dev);
    672 
    673 	if (state->dd->dd_no_part && !state->with_non_partitionable)
    674 		return true;
    675 
    676 	if (!get_disk_geom(state->dd->dd_name, &geo)) {
    677 		if (errno == ENOENT)
    678 			return true;
    679 		if (errno != ENOTTY || !state->dd->dd_no_part)
    680 			/*
    681 			 * Allow plain partitions,
    682 			 * like already existing wedges
    683 			 * (like dk0) if marked as
    684 			 * non-partitioning device.
    685 			 * For all other cases, continue
    686 			 * with the next disk.
    687 			 */
    688 			return true;
    689 		if (!is_ffs_wedge(state->dd->dd_name))
    690 			return true;
    691 	}
    692 
    693 	/*
    694 	 * Exclude a disk mounted as root partition,
    695 	 * in case of install-image on a USB memstick.
    696 	 */
    697 	if (is_active_rootpart(state->dd->dd_name,
    698 	    state->dd->dd_no_part ? -1 : 0))
    699 		return true;
    700 
    701 	state->dd->dd_cyl = geo.dg_ncylinders;
    702 	state->dd->dd_head = geo.dg_ntracks;
    703 	state->dd->dd_sec = geo.dg_nsectors;
    704 	state->dd->dd_secsize = geo.dg_secsize;
    705 	state->dd->dd_totsec = geo.dg_secperunit;
    706 
    707 	if (!state->dd->dd_no_part || !get_wedge_descr(state->dd))
    708 		get_descr(state->dd);
    709 	state->dd++;
    710 	state->numdisks++;
    711 	if (state->numdisks == MAX_DISKS)
    712 		return false;
    713 
    714 	return true;
    715 }
    716 
    717 /*
    718  * Get all disk devices that are not CDs.
    719  * Optionally leave out those that can not be partitioned further.
    720  */
    721 static int
    722 get_disks(struct disk_desc *dd, bool with_non_partitionable)
    723 {
    724 	struct get_disks_state state;
    725 
    726 	/* initialize */
    727 	state.numdisks = 0;
    728 	state.dd = dd;
    729 	state.with_non_partitionable = with_non_partitionable;
    730 
    731 	if (enumerate_disks(&state, get_disks_helper))
    732 		return state.numdisks;
    733 
    734 	return 0;
    735 }
    736 
    737 #ifdef DEBUG_VERBOSE
    738 static void
    739 dump_parts(const struct disk_partitions *parts)
    740 {
    741 	fprintf(stderr, "%s partitions on %s:\n",
    742 	    MSG_XLAT(parts->pscheme->short_name), parts->disk);
    743 
    744 	for (size_t p = 0; p < parts->num_part; p++) {
    745 		struct disk_part_info info;
    746 
    747 		if (parts->pscheme->get_part_info(
    748 		    parts, p, &info)) {
    749 			fprintf(stderr, " #%zu: start: %" PRIu64 " "
    750 			    "size: %" PRIu64 ", flags: %x\n",
    751 			    p, info.start, info.size,
    752 			    info.flags);
    753 			if (info.nat_type)
    754 				fprintf(stderr, "\ttype: %s\n",
    755 				    info.nat_type->description);
    756 		} else {
    757 			fprintf(stderr, "failed to get info "
    758 			    "for partition #%zu\n", p);
    759 		}
    760 	}
    761 	fprintf(stderr, "%" PRIu64 " sectors free, disk size %" PRIu64
    762 	    " sectors, %zu partitions used\n", parts->free_space,
    763 	    parts->disk_size, parts->num_part);
    764 }
    765 #endif
    766 
    767 static bool
    768 delete_scheme(struct pm_devs *p)
    769 {
    770 
    771 	if (!ask_noyes(MSG_removepartswarn))
    772 		return false;
    773 
    774 	p->parts->pscheme->free(p->parts);
    775 	p->parts = NULL;
    776 	return true;
    777 }
    778 
    779 
    780 static void
    781 convert_copy(struct disk_partitions *old_parts,
    782     struct disk_partitions *new_parts)
    783 {
    784 	struct disk_part_info oinfo, ninfo;
    785 	part_id i;
    786 
    787 	for (i = 0; i < old_parts->num_part; i++) {
    788 		if (!old_parts->pscheme->get_part_info(old_parts, i, &oinfo))
    789 			continue;
    790 
    791 		if (oinfo.flags & PTI_PSCHEME_INTERNAL)
    792 			continue;
    793 
    794 		if (oinfo.flags & PTI_SEC_CONTAINER) {
    795 		    	if (old_parts->pscheme->secondary_partitions) {
    796 				struct disk_partitions *sec_part =
    797 					old_parts->pscheme->
    798 					    secondary_partitions(
    799 					    old_parts, oinfo.start, false);
    800 				if (sec_part)
    801 					convert_copy(sec_part, new_parts);
    802 			}
    803 			continue;
    804 		}
    805 
    806 		if (!new_parts->pscheme->adapt_foreign_part_info(new_parts,
    807 			    &ninfo, old_parts->pscheme, &oinfo))
    808 			continue;
    809 		new_parts->pscheme->add_partition(new_parts, &ninfo, NULL);
    810 	}
    811 }
    812 
    813 bool
    814 convert_scheme(struct pm_devs *p, bool is_boot_drive, const char **err_msg)
    815 {
    816 	struct disk_partitions *old_parts, *new_parts;
    817 	const struct disk_partitioning_scheme *new_scheme;
    818 
    819 	*err_msg = NULL;
    820 
    821 	old_parts = p->parts;
    822 	new_scheme = select_part_scheme(p, old_parts->pscheme,
    823 	    false, MSG_select_other_partscheme);
    824 
    825 	if (new_scheme == NULL) {
    826 		if (err_msg)
    827 			*err_msg = INTERNAL_ERROR;
    828 		return false;
    829 	}
    830 
    831 	new_parts = new_scheme->create_new_for_disk(p->diskdev,
    832 	    0, p->dlsize, is_boot_drive, NULL);
    833 	if (new_parts == NULL) {
    834 		if (err_msg)
    835 			*err_msg = MSG_out_of_memory;
    836 		return false;
    837 	}
    838 
    839 	convert_copy(old_parts, new_parts);
    840 
    841 	if (new_parts->num_part == 0 && old_parts->num_part != 0) {
    842 		/* need to cleanup */
    843 		new_parts->pscheme->free(new_parts);
    844 		return false;
    845 	}
    846 
    847 	old_parts->pscheme->free(old_parts);
    848 	p->parts = new_parts;
    849 	return true;
    850 }
    851 
    852 static struct pm_devs *
    853 dummy_whole_system_pm(void)
    854 {
    855 	static struct pm_devs whole_system = {
    856 		.diskdev = "/",
    857 		.no_mbr = true,
    858 		.no_part = true,
    859 		.cur_system = true,
    860 	};
    861 	static bool init = false;
    862 
    863 	if (!init) {
    864 		strlcpy(whole_system.diskdev_descr,
    865 		    msg_string(MSG_running_system),
    866 		    sizeof whole_system.diskdev_descr);
    867 	}
    868 
    869 	return &whole_system;
    870 }
    871 
    872 int
    873 find_disks(const char *doingwhat, bool allow_cur_system)
    874 {
    875 	struct disk_desc disks[MAX_DISKS];
    876 	/* need two more menu entries: current system + extended partitioning */
    877 	menu_ent dsk_menu[__arraycount(disks) + 2],
    878 	    wedge_menu[__arraycount(dsk_menu)];
    879 	int disk_no[__arraycount(dsk_menu)], wedge_no[__arraycount(dsk_menu)];
    880 	struct disk_desc *disk;
    881 	int i = 0, dno, wno, skipped = 0;
    882 	int already_found, numdisks, selected_disk = -1;
    883 	int menu_no, w_menu_no;
    884 	size_t max_desc_len;
    885 	struct pm_devs *pm_i, *pm_last = NULL;
    886 	bool any_wedges = false;
    887 
    888 	memset(dsk_menu, 0, sizeof(dsk_menu));
    889 	memset(wedge_menu, 0, sizeof(wedge_menu));
    890 
    891 	/* Find disks. */
    892 	numdisks = get_disks(disks, partman_go <= 0);
    893 
    894 	/* need a redraw here, kernel messages hose everything */
    895 	touchwin(stdscr);
    896 	refresh();
    897 	/* Kill typeahead, it won't be what the user had in mind */
    898 	fpurge(stdin);
    899 	/*
    900 	 * we need space for the menu box and the row label,
    901 	 * this sums up to 7 characters.
    902 	 */
    903 	max_desc_len = getmaxx(stdscr) - 8;
    904 	if (max_desc_len >= __arraycount(disks[0].dd_descr))
    905 		max_desc_len = __arraycount(disks[0].dd_descr) - 1;
    906 
    907 	/*
    908 	 * partman_go: <0 - we want to see menu with extended partitioning
    909 	 *            ==0 - we want to see simple select disk menu
    910 	 *             >0 - we do not want to see any menus, just detect
    911 	 *                  all disks
    912 	 */
    913 	if (partman_go <= 0) {
    914 		if (numdisks == 0 && !allow_cur_system) {
    915 			/* No disks found! */
    916 			hit_enter_to_continue(MSG_nodisk, NULL);
    917 			/*endwin();*/
    918 			return -1;
    919 		} else {
    920 			/* One or more disks found or current system allowed */
    921 			dno = wno = 0;
    922 			if (allow_cur_system) {
    923 				dsk_menu[dno].opt_name = MSG_running_system;
    924 				dsk_menu[dno].opt_flags = OPT_EXIT;
    925 				dsk_menu[dno].opt_action = set_menu_select;
    926 				disk_no[dno] = -1;
    927 				i++; dno++;
    928 			}
    929 			for (i = 0; i < numdisks; i++) {
    930 				if (disks[i].dd_no_part) {
    931 					any_wedges = true;
    932 					wedge_menu[wno].opt_name =
    933 					    disks[i].dd_descr;
    934 					disks[i].dd_descr[max_desc_len] = 0;
    935 					wedge_menu[wno].opt_flags = OPT_EXIT;
    936 					wedge_menu[wno].opt_action =
    937 					    set_menu_select;
    938 					wedge_no[wno] = i;
    939 					wno++;
    940 				} else {
    941 					dsk_menu[dno].opt_name =
    942 					    disks[i].dd_descr;
    943 					disks[i].dd_descr[max_desc_len] = 0;
    944 					dsk_menu[dno].opt_flags = OPT_EXIT;
    945 					dsk_menu[dno].opt_action =
    946 					    set_menu_select;
    947 					disk_no[dno] = i;
    948 					dno++;
    949 				}
    950 			}
    951 			if (any_wedges) {
    952 				dsk_menu[dno].opt_name = MSG_selectwedge;
    953 				dsk_menu[dno].opt_flags = OPT_EXIT;
    954 				dsk_menu[dno].opt_action = set_menu_select;
    955 				disk_no[dno] = -2;
    956 				dno++;
    957 			}
    958 			if (partman_go < 0) {
    959 				dsk_menu[dno].opt_name = MSG_partman;
    960 				dsk_menu[dno].opt_flags = OPT_EXIT;
    961 				dsk_menu[dno].opt_action = set_menu_select;
    962 				disk_no[dno] = -3;
    963 				dno++;
    964 			}
    965 			w_menu_no = -1;
    966 			menu_no = new_menu(MSG_Available_disks,
    967 				dsk_menu, dno, -1,
    968 				 4, 0, 0, MC_SCROLL,
    969 				NULL, NULL, NULL, NULL, MSG_exit_menu_generic);
    970 			if (menu_no == -1)
    971 				return -1;
    972 			for (;;) {
    973 				msg_fmt_display(MSG_ask_disk, "%s", doingwhat);
    974 				i = -1;
    975 				process_menu(menu_no, &i);
    976 				if (disk_no[i] == -2) {
    977 					/* do wedges menu */
    978 					if (w_menu_no == -1) {
    979 						w_menu_no = new_menu(
    980 						    MSG_Available_wedges,
    981 						    wedge_menu, wno, -1,
    982 						    4, 0, 0, MC_SCROLL,
    983 						    NULL, NULL, NULL, NULL,
    984 						    MSG_exit_menu_generic);
    985 						if (w_menu_no == -1) {
    986 							selected_disk = -1;
    987 							break;
    988 						}
    989 					}
    990 					i = -1;
    991 					process_menu(w_menu_no, &i);
    992 					if (i == -1)
    993 						continue;
    994 					selected_disk = wedge_no[i];
    995 					break;
    996 				}
    997 				selected_disk = disk_no[i];
    998 				break;
    999 			}
   1000 			if (w_menu_no >= 0)
   1001 				free_menu(w_menu_no);
   1002 			free_menu(menu_no);
   1003 			if (allow_cur_system && selected_disk == -1) {
   1004 				pm = dummy_whole_system_pm();
   1005 				return 1;
   1006 			}
   1007 		}
   1008 		if (partman_go < 0 &&  selected_disk == -3) {
   1009 			partman_go = 1;
   1010 			return -2;
   1011 		} else
   1012 			partman_go = 0;
   1013 		if (selected_disk < 0 ||  selected_disk < 0
   1014 		    || selected_disk >= numdisks)
   1015 			return -1;
   1016 	}
   1017 
   1018 	/* Fill pm struct with device(s) info */
   1019 	for (i = 0; i < numdisks; i++) {
   1020 		if (! partman_go)
   1021 			disk = disks + selected_disk;
   1022 		else {
   1023 			disk = disks + i;
   1024 			already_found = 0;
   1025 			SLIST_FOREACH(pm_i, &pm_head, l) {
   1026 				pm_last = pm_i;
   1027 				if (strcmp(pm_i->diskdev, disk->dd_name) == 0) {
   1028 					already_found = 1;
   1029 					break;
   1030 				}
   1031 			}
   1032 			if (pm_i != NULL && already_found) {
   1033 				/*
   1034 				 * We already added this device, but
   1035 				 * partitions might have changed
   1036 				 */
   1037 				if (!pm_i->found) {
   1038 					pm_i->found = true;
   1039 					if (pm_i->parts == NULL) {
   1040 						pm_i->parts =
   1041 						    partitions_read_disk(
   1042 						    pm_i->diskdev,
   1043 						    disk->dd_totsec,
   1044 						    disk->dd_secsize,
   1045 						    disk->dd_no_mbr);
   1046 					}
   1047 				}
   1048 				continue;
   1049 			}
   1050 		}
   1051 		pm = pm_new;
   1052 		pm->found = 1;
   1053 		pm->ptstart = 0;
   1054 		pm->ptsize = 0;
   1055 		strlcpy(pm->diskdev, disk->dd_name, sizeof pm->diskdev);
   1056 		strlcpy(pm->diskdev_descr, disk->dd_descr, sizeof pm->diskdev_descr);
   1057 		/* Use as a default disk if the user has the sets on a local disk */
   1058 		strlcpy(localfs_dev, disk->dd_name, sizeof localfs_dev);
   1059 
   1060 		/*
   1061 		 * Init disk size and geometry
   1062 		 */
   1063 		pm->sectorsize = disk->dd_secsize;
   1064 		pm->dlcyl = disk->dd_cyl;
   1065 		pm->dlhead = disk->dd_head;
   1066 		pm->dlsec = disk->dd_sec;
   1067 		pm->dlsize = disk->dd_totsec;
   1068 		if (pm->dlsize == 0)
   1069 			pm->dlsize =
   1070 			    disk->dd_cyl * disk->dd_head * disk->dd_sec;
   1071 
   1072 		pm->parts = partitions_read_disk(pm->diskdev,
   1073 		    pm->dlsize, disk->dd_secsize, disk->dd_no_mbr);
   1074 
   1075 again:
   1076 
   1077 #ifdef DEBUG_VERBOSE
   1078 		if (pm->parts) {
   1079 			fputs("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", stderr);
   1080 			dump_parts(pm->parts);
   1081 
   1082 			if (pm->parts->pscheme->secondary_partitions) {
   1083 				const struct disk_partitions *sparts =
   1084 				    pm->parts->pscheme->secondary_partitions(
   1085 				    pm->parts, pm->ptstart, false);
   1086 				if (sparts != NULL)
   1087 					dump_parts(sparts);
   1088 			}
   1089 		}
   1090 #endif
   1091 
   1092 		pm->no_mbr = disk->dd_no_mbr;
   1093 		pm->no_part = disk->dd_no_part;
   1094 		if (!pm->no_part) {
   1095 			pm->sectorsize = disk->dd_secsize;
   1096 			pm->dlcyl = disk->dd_cyl;
   1097 			pm->dlhead = disk->dd_head;
   1098 			pm->dlsec = disk->dd_sec;
   1099 			pm->dlsize = disk->dd_totsec;
   1100 			if (pm->dlsize == 0)
   1101 				pm->dlsize =
   1102 				    disk->dd_cyl * disk->dd_head * disk->dd_sec;
   1103 
   1104 			if (pm->parts && pm->parts->pscheme->size_limit != 0
   1105 			    && pm->dlsize > pm->parts->pscheme->size_limit
   1106 			    && ! partman_go) {
   1107 
   1108 				char size[5], limit[5];
   1109 
   1110 				humanize_number(size, sizeof(size),
   1111 				    (uint64_t)pm->dlsize * pm->sectorsize,
   1112 				    "", HN_AUTOSCALE, HN_B | HN_NOSPACE
   1113 				    | HN_DECIMAL);
   1114 
   1115 				humanize_number(limit, sizeof(limit),
   1116 				    (uint64_t)pm->parts->pscheme->size_limit
   1117 					* 512U,
   1118 				    "", HN_AUTOSCALE, HN_B | HN_NOSPACE
   1119 				    | HN_DECIMAL);
   1120 
   1121 				if (logfp)
   1122 					fprintf(logfp,
   1123 					    "disk %s: is too big (%" PRIu64
   1124 					    " blocks, %s), will be truncated\n",
   1125 						pm->diskdev, pm->dlsize,
   1126 						size);
   1127 
   1128 				msg_display_subst(MSG_toobigdisklabel, 5,
   1129 				   pm->diskdev,
   1130 				   msg_string(pm->parts->pscheme->name),
   1131 				   msg_string(pm->parts->pscheme->short_name),
   1132 				   size, limit);
   1133 
   1134 				int sel = -1;
   1135 				const char *err = NULL;
   1136 				process_menu(MENU_convertscheme, &sel);
   1137 				if (sel == 1) {
   1138 					if (!delete_scheme(pm)) {
   1139 						return -1;
   1140 					}
   1141 					goto again;
   1142 				} else if (sel == 2) {
   1143 					if (!convert_scheme(pm,
   1144 					     partman_go < 0, &err)) {
   1145 						if (err != NULL)
   1146 							err_msg_win(err);
   1147 						return -1;
   1148 					}
   1149 					goto again;
   1150 				} else if (sel == 3) {
   1151 					return -1;
   1152 				}
   1153 				pm->dlsize = pm->parts->pscheme->size_limit;
   1154 			}
   1155 		} else {
   1156 			pm->sectorsize = 0;
   1157 			pm->dlcyl = 0;
   1158 			pm->dlhead = 0;
   1159 			pm->dlsec = 0;
   1160 			pm->dlsize = 0;
   1161 			pm->no_mbr = 1;
   1162 		}
   1163 		pm->dlcylsize = pm->dlhead * pm->dlsec;
   1164 
   1165 		if (partman_go) {
   1166 			pm_getrefdev(pm_new);
   1167 			if (SLIST_EMPTY(&pm_head) || pm_last == NULL)
   1168 				 SLIST_INSERT_HEAD(&pm_head, pm_new, l);
   1169 			else
   1170 				 SLIST_INSERT_AFTER(pm_last, pm_new, l);
   1171 			pm_new = malloc(sizeof (struct pm_devs));
   1172 			memset(pm_new, 0, sizeof *pm_new);
   1173 		} else
   1174 			/* We are not in partman and do not want to process
   1175 			 * all devices, exit */
   1176 			break;
   1177 	}
   1178 
   1179 	return numdisks-skipped;
   1180 }
   1181 
   1182 static int
   1183 sort_part_usage_by_mount(const void *a, const void *b)
   1184 {
   1185 	const struct part_usage_info *pa = a, *pb = b;
   1186 
   1187 	/* sort all real partitions by mount point */
   1188 	if ((pa->instflags & PUIINST_MOUNT) &&
   1189 	    (pb->instflags & PUIINST_MOUNT))
   1190 		return strcmp(pa->mount, pb->mount);
   1191 
   1192 	/* real partitions go first */
   1193 	if (pa->instflags & PUIINST_MOUNT)
   1194 		return -1;
   1195 	if (pb->instflags & PUIINST_MOUNT)
   1196 		return 1;
   1197 
   1198 	/* arbitrary order for all other partitions */
   1199 	if (pa->type == PT_swap)
   1200 		return -1;
   1201 	if (pb->type == PT_swap)
   1202 		return 1;
   1203 	if (pa->type < pb->type)
   1204 		return -1;
   1205 	if (pa->type > pb->type)
   1206 		return 1;
   1207 	if (pa->cur_part_id < pb->cur_part_id)
   1208 		return -1;
   1209 	if (pa->cur_part_id > pb->cur_part_id)
   1210 		return 1;
   1211 	return (uintptr_t)a < (uintptr_t)b ? -1 : 1;
   1212 }
   1213 
   1214 int
   1215 make_filesystems(struct install_partition_desc *install)
   1216 {
   1217 	int error = 0, partno = -1;
   1218 	char *newfs = NULL, devdev[PATH_MAX], rdev[PATH_MAX],
   1219 	    opts[200], opt[30];
   1220 	size_t i;
   1221 	struct part_usage_info *ptn;
   1222 	struct disk_partitions *parts;
   1223 	const char *mnt_opts = NULL, *fsname = NULL;
   1224 
   1225 	if (pm->cur_system)
   1226 		return 1;
   1227 
   1228 	if (pm->no_part) {
   1229 		/* check if this target device already has a ffs */
   1230 		snprintf(rdev, sizeof rdev, _PATH_DEV "/r%s", pm->diskdev);
   1231 		error = fsck_preen(rdev, "ffs", true);
   1232 		if (error) {
   1233 			if (!ask_noyes(MSG_No_filesystem_newfs))
   1234 				return EINVAL;
   1235 			error = run_program(RUN_DISPLAY | RUN_PROGRESS,
   1236 			    "/sbin/newfs -V2 -O2 %s", rdev);
   1237 		}
   1238 
   1239 		md_pre_mount(install, 0);
   1240 
   1241 		make_target_dir("/");
   1242 
   1243 		snprintf(devdev, sizeof devdev, _PATH_DEV "%s", pm->diskdev);
   1244 		error = target_mount_do("-o async", devdev, "/");
   1245 		if (error) {
   1246 			msg_display_subst(MSG_mountfail, 2, devdev, "/");
   1247 			hit_enter_to_continue(NULL, NULL);
   1248 		}
   1249 
   1250 		return error;
   1251 	}
   1252 
   1253 	/* Making new file systems and mounting them */
   1254 
   1255 	/* sort to ensure /usr/local is mounted after /usr (etc) */
   1256 	qsort(install->infos, install->num, sizeof(*install->infos),
   1257 	    sort_part_usage_by_mount);
   1258 
   1259 	for (i = 0; i < install->num; i++) {
   1260 		/*
   1261 		 * Newfs all file systems marked as needing this.
   1262 		 * Mount the ones that have a mountpoint in the target.
   1263 		 */
   1264 		ptn = &install->infos[i];
   1265 		parts = ptn->parts;
   1266 		newfs = NULL;
   1267 		fsname = NULL;
   1268 
   1269 		if (ptn->size == 0 || parts == NULL|| ptn->type == PT_swap)
   1270 			continue;
   1271 
   1272 		if (parts->pscheme->get_part_device(parts, ptn->cur_part_id,
   1273 		    devdev, sizeof devdev, &partno, parent_device_only, false,
   1274 		    false) && is_active_rootpart(devdev, partno))
   1275 			continue;
   1276 
   1277 		parts->pscheme->get_part_device(parts, ptn->cur_part_id,
   1278 		    devdev, sizeof devdev, &partno, plain_name, true, true);
   1279 
   1280 		parts->pscheme->get_part_device(parts, ptn->cur_part_id,
   1281 		    rdev, sizeof rdev, &partno, raw_dev_name, true, true);
   1282 
   1283 		opts[0] = 0;
   1284 		switch (ptn->fs_type) {
   1285 		case FS_APPLEUFS:
   1286 			if (ptn->fs_opt3 != 0)
   1287 				snprintf(opts, sizeof opts, "-i %u",
   1288 				    ptn->fs_opt3);
   1289 			asprintf(&newfs, "/sbin/newfs %s", opts);
   1290 			mnt_opts = "-tffs -o async";
   1291 			fsname = "ffs";
   1292 			break;
   1293 		case FS_BSDFFS:
   1294 			if (ptn->fs_opt3 != 0)
   1295 				snprintf(opts, sizeof opts, "-i %u ",
   1296 				    ptn->fs_opt3);
   1297 			if (ptn->fs_opt1 != 0) {
   1298 				snprintf(opt, sizeof opt, "-b %u ",
   1299 				    ptn->fs_opt1);
   1300 				strcat(opts, opt);
   1301 			}
   1302 			if (ptn->fs_opt2 != 0) {
   1303 				snprintf(opt, sizeof opt, "-f %u ",
   1304 				    ptn->fs_opt2);
   1305 				strcat(opts, opt);
   1306 			}
   1307 			asprintf(&newfs,
   1308 			    "/sbin/newfs -V2 -O %d %s",
   1309 			    ptn->fs_version == 2 ? 2 : 1, opts);
   1310 			if (ptn->mountflags & PUIMNT_LOG)
   1311 				mnt_opts = "-tffs -o log";
   1312 			else
   1313 				mnt_opts = "-tffs -o async";
   1314 			fsname = "ffs";
   1315 			break;
   1316 		case FS_BSDLFS:
   1317 			if (ptn->fs_opt1 != 0 && ptn->fs_opt2 != 0)
   1318 				snprintf(opts, sizeof opts, "-b %u",
   1319 				     ptn->fs_opt1 * ptn->fs_opt2);
   1320 			asprintf(&newfs, "/sbin/newfs_lfs %s", opts);
   1321 			mnt_opts = "-tlfs";
   1322 			fsname = "lfs";
   1323 			break;
   1324 		case FS_MSDOS:
   1325 			asprintf(&newfs, "/sbin/newfs_msdos");
   1326 			mnt_opts = "-tmsdos";
   1327 			fsname = "msdos";
   1328 			break;
   1329 		case FS_SYSVBFS:
   1330 			asprintf(&newfs, "/sbin/newfs_sysvbfs");
   1331 			mnt_opts = "-tsysvbfs";
   1332 			fsname = "sysvbfs";
   1333 			break;
   1334 		case FS_V7:
   1335 			asprintf(&newfs, "/sbin/newfs_v7fs");
   1336 			mnt_opts = "-tv7fs";
   1337 			fsname = "v7fs";
   1338 			break;
   1339 		case FS_EX2FS:
   1340 			asprintf(&newfs,
   1341 			    ptn->fs_version == 1 ?
   1342 				"/sbin/newfs_ext2fs -O 0" :
   1343 				"/sbin/newfs_ext2fs");
   1344 			mnt_opts = "-text2fs";
   1345 			fsname = "ext2fs";
   1346 			break;
   1347 		}
   1348 		if ((ptn->instflags & PUIINST_NEWFS) && newfs != NULL) {
   1349 			error = run_program(RUN_DISPLAY | RUN_PROGRESS,
   1350 			    "%s %s", newfs, rdev);
   1351 		} else if ((ptn->instflags & (PUIINST_MOUNT|PUIINST_BOOT))
   1352 		    && fsname != NULL) {
   1353 			/* We'd better check it isn't dirty */
   1354 			error = fsck_preen(devdev, fsname, false);
   1355 		}
   1356 		free(newfs);
   1357 		if (error != 0)
   1358 			return error;
   1359 
   1360 		ptn->instflags &= ~PUIINST_NEWFS;
   1361 		md_pre_mount(install, i);
   1362 
   1363 		if (partman_go == 0 && (ptn->instflags & PUIINST_MOUNT) &&
   1364 				mnt_opts != NULL) {
   1365 			make_target_dir(ptn->mount);
   1366 			error = target_mount_do(mnt_opts, devdev,
   1367 			    ptn->mount);
   1368 			if (error) {
   1369 				msg_display_subst(MSG_mountfail, 2, devdev,
   1370 				    ptn->mount);
   1371 				hit_enter_to_continue(NULL, NULL);
   1372 				return error;
   1373 			}
   1374 		}
   1375 	}
   1376 	return 0;
   1377 }
   1378 
   1379 int
   1380 make_fstab(struct install_partition_desc *install)
   1381 {
   1382 	FILE *f;
   1383 	const char *dump_dev = NULL;
   1384 	const char *dev;
   1385 	char dev_buf[PATH_MAX], swap_dev[PATH_MAX];
   1386 
   1387 	if (pm->cur_system)
   1388 		return 1;
   1389 
   1390 	swap_dev[0] = 0;
   1391 
   1392 	/* Create the fstab. */
   1393 	make_target_dir("/etc");
   1394 	f = target_fopen("/etc/fstab", "w");
   1395 	scripting_fprintf(NULL, "cat <<EOF >%s/etc/fstab\n", target_prefix());
   1396 
   1397 	if (logfp)
   1398 		(void)fprintf(logfp,
   1399 		    "Making %s/etc/fstab (%s).\n", target_prefix(),
   1400 		    pm->diskdev);
   1401 
   1402 	if (f == NULL) {
   1403 		msg_display(MSG_createfstab);
   1404 		if (logfp)
   1405 			(void)fprintf(logfp, "Failed to make /etc/fstab!\n");
   1406 		hit_enter_to_continue(NULL, NULL);
   1407 #ifndef DEBUG
   1408 		return 1;
   1409 #else
   1410 		f = stdout;
   1411 #endif
   1412 	}
   1413 
   1414 	scripting_fprintf(f, "# NetBSD /etc/fstab\n# See /usr/share/examples/"
   1415 			"fstab/ for more examples.\n");
   1416 
   1417 	if (pm->no_part) {
   1418 		/* single dk? target */
   1419 		char buf[200], parent[200], swap[200], *prompt;
   1420 		int res;
   1421 
   1422 		if (!get_name_and_parent(pm->diskdev, buf, parent))
   1423 			goto done_with_disks;
   1424 		scripting_fprintf(f, NAME_PREFIX "%s\t/\tffs\trw\t\t1 1\n",
   1425 		    buf);
   1426 		if (!find_swap_part_on(parent, swap))
   1427 			goto done_with_disks;
   1428 		const char *args[] = { parent, swap };
   1429 		prompt = str_arg_subst(msg_string(MSG_Auto_add_swap_part),
   1430 		    __arraycount(args), args);
   1431 		res = ask_yesno(prompt);
   1432 		free(prompt);
   1433 		if (res)
   1434 			scripting_fprintf(f, NAME_PREFIX "%s\tnone"
   1435 			    "\tswap\tsw,dp\t\t0 0\n", swap);
   1436 		goto done_with_disks;
   1437 	}
   1438 
   1439 	for (size_t i = 0; i < install->num; i++) {
   1440 
   1441 		const struct part_usage_info *ptn = &install->infos[i];
   1442 
   1443 		if (ptn->size == 0)
   1444 			continue;
   1445 
   1446 		bool is_tmpfs = ptn->type == PT_root &&
   1447 		    ptn->fs_type == FS_TMPFS &&
   1448 		    (ptn->flags & PUIFLG_JUST_MOUNTPOINT);
   1449 
   1450 		if (!is_tmpfs && ptn->type != PT_swap &&
   1451 		    (ptn->instflags & PUIINST_MOUNT) == 0)
   1452 			continue;
   1453 
   1454 		const char *s = "";
   1455 		const char *mp = ptn->mount;
   1456 		const char *fstype = "ffs";
   1457 		int fsck_pass = 0, dump_freq = 0;
   1458 
   1459 		if (ptn->parts->pscheme->get_part_device(ptn->parts,
   1460 			    ptn->cur_part_id, dev_buf, sizeof dev_buf, NULL,
   1461 			    logical_name, true, false))
   1462 			dev = dev_buf;
   1463 		else
   1464 			dev = NULL;
   1465 
   1466 		if (!*mp) {
   1467 			/*
   1468 			 * No mount point specified, comment out line and
   1469 			 * use /mnt as a placeholder for the mount point.
   1470 			 */
   1471 			s = "# ";
   1472 			mp = "/mnt";
   1473 		}
   1474 
   1475 		switch (ptn->fs_type) {
   1476 		case FS_UNUSED:
   1477 			continue;
   1478 		case FS_BSDLFS:
   1479 			/* If there is no LFS, just comment it out. */
   1480 			if (!check_lfs_progs())
   1481 				s = "# ";
   1482 			fstype = "lfs";
   1483 			/* FALLTHROUGH */
   1484 		case FS_BSDFFS:
   1485 			fsck_pass = (strcmp(mp, "/") == 0) ? 1 : 2;
   1486 			dump_freq = 1;
   1487 			break;
   1488 		case FS_MSDOS:
   1489 			fstype = "msdos";
   1490 			break;
   1491 		case FS_SWAP:
   1492 			if (swap_dev[0] == 0) {
   1493 				strlcpy(swap_dev, dev, sizeof swap_dev);
   1494 				dump_dev = ",dp";
   1495 			} else {
   1496 				dump_dev = "";
   1497 			}
   1498 			scripting_fprintf(f, "%s\t\tnone\tswap\tsw%s\t\t 0 0\n",
   1499 				dev, dump_dev);
   1500 			continue;
   1501 #ifdef HAVE_TMPFS
   1502 		case FS_TMPFS:
   1503 			if (ptn->size < 0)
   1504 				scripting_fprintf(f,
   1505 				    "tmpfs\t\t/tmp\ttmpfs\trw,-m=1777,"
   1506 				    "-s=ram%%%" PRIu64 "\n", -ptn->size);
   1507 			else
   1508 				scripting_fprintf(f,
   1509 				    "tmpfs\t\t/tmp\ttmpfs\trw,-m=1777,"
   1510 				    "-s=%" PRIu64 "M\n", ptn->size);
   1511 			continue;
   1512 #else
   1513 		case FS_MFS:
   1514 			if (swap_dev[0] != 0)
   1515 				scripting_fprintf(f,
   1516 				    "%s\t\t/tmp\tmfs\trw,-s=%"
   1517 				    PRIu64 "\n", swap_dev, ptn->size);
   1518 			else
   1519 				scripting_fprintf(f,
   1520 				    "swap\t\t/tmp\tmfs\trw,-s=%"
   1521 				    PRIu64 "\n", ptn->size);
   1522 			continue;
   1523 #endif
   1524 		case FS_SYSVBFS:
   1525 			fstype = "sysvbfs";
   1526 			make_target_dir("/stand");
   1527 			break;
   1528 		default:
   1529 			fstype = "???";
   1530 			s = "# ";
   1531 			break;
   1532 		}
   1533 		/* The code that remounts root rw doesn't check the partition */
   1534 		if (strcmp(mp, "/") == 0 &&
   1535 		    (ptn->instflags & PUIINST_MOUNT) == 0)
   1536 			s = "# ";
   1537 
   1538  		scripting_fprintf(f,
   1539 		  "%s%s\t\t%s\t%s\trw%s%s%s%s%s%s%s%s\t\t %d %d\n",
   1540 		   s, dev, mp, fstype,
   1541 		   ptn->mountflags & PUIMNT_LOG ? ",log" : "",
   1542 		   ptn->mountflags & PUIMNT_NOAUTO ? ",noauto" : "",
   1543 		   ptn->mountflags & PUIMNT_ASYNC ? ",async" : "",
   1544 		   ptn->mountflags & PUIMNT_NOATIME ? ",noatime" : "",
   1545 		   ptn->mountflags & PUIMNT_NODEV ? ",nodev" : "",
   1546 		   ptn->mountflags & PUIMNT_NODEVMTIME ? ",nodevmtime" : "",
   1547 		   ptn->mountflags & PUIMNT_NOEXEC ? ",noexec" : "",
   1548 		   ptn->mountflags & PUIMNT_NOSUID ? ",nosuid" : "",
   1549 		   dump_freq, fsck_pass);
   1550 	}
   1551 
   1552 done_with_disks:
   1553 	if (cdrom_dev[0] == 0)
   1554 		get_default_cdrom(cdrom_dev, sizeof(cdrom_dev));
   1555 
   1556 	/* Add /kern, /proc and /dev/pts to fstab and make mountpoint. */
   1557 	scripting_fprintf(f, "kernfs\t\t/kern\tkernfs\trw\n");
   1558 	scripting_fprintf(f, "ptyfs\t\t/dev/pts\tptyfs\trw\n");
   1559 	scripting_fprintf(f, "procfs\t\t/proc\tprocfs\trw\n");
   1560 	if (cdrom_dev[0] != 0)
   1561 		scripting_fprintf(f, "/dev/%s\t\t/cdrom\tcd9660\tro,noauto\n",
   1562 		    cdrom_dev);
   1563 	scripting_fprintf(f, "%stmpfs\t\t/var/shm\ttmpfs\trw,-m1777,-sram%%25\n",
   1564 	    tmpfs_on_var_shm() ? "" : "#");
   1565 	make_target_dir("/kern");
   1566 	make_target_dir("/proc");
   1567 	make_target_dir("/dev/pts");
   1568 	if (cdrom_dev[0] != 0)
   1569 		make_target_dir("/cdrom");
   1570 	make_target_dir("/var/shm");
   1571 
   1572 	scripting_fprintf(NULL, "EOF\n");
   1573 
   1574 	fclose(f);
   1575 	fflush(NULL);
   1576 	return 0;
   1577 }
   1578 
   1579 static bool
   1580 find_part_by_name(const char *name, struct disk_partitions **parts,
   1581     part_id *pno)
   1582 {
   1583 	struct pm_devs *i;
   1584 	struct disk_partitions *ps;
   1585 	part_id id;
   1586 	struct disk_desc disks[MAX_DISKS];
   1587 	int n, cnt;
   1588 
   1589 	if (SLIST_EMPTY(&pm_head)) {
   1590 		/*
   1591 		 * List has not been filled, only "pm" is valid - check
   1592 		 * that first.
   1593 		 */
   1594 		if (pm->parts != NULL &&
   1595 		    pm->parts->pscheme->find_by_name != NULL) {
   1596 			id = pm->parts->pscheme->find_by_name(pm->parts, name);
   1597 			if (id != NO_PART) {
   1598 				*pno = id;
   1599 				*parts = pm->parts;
   1600 				return true;
   1601 			}
   1602 		}
   1603 		/*
   1604 		 * Not that easy - check all other disks
   1605 		 */
   1606 		cnt = get_disks(disks, false);
   1607 		for (n = 0; n < cnt; n++) {
   1608 			if (strcmp(disks[n].dd_name, pm->diskdev) == 0)
   1609 				continue;
   1610 			ps = partitions_read_disk(disks[n].dd_name,
   1611 			    disks[n].dd_totsec,
   1612 			    disks[n].dd_secsize,
   1613 			    disks[n].dd_no_mbr);
   1614 			if (ps == NULL)
   1615 				continue;
   1616 			if (ps->pscheme->find_by_name == NULL)
   1617 				continue;
   1618 			id = ps->pscheme->find_by_name(ps, name);
   1619 			if (id != NO_PART) {
   1620 				*pno = id;
   1621 				*parts = ps;
   1622 				return true;	/* XXX this leaks memory */
   1623 			}
   1624 			ps->pscheme->free(ps);
   1625 		}
   1626 	} else {
   1627 		SLIST_FOREACH(i, &pm_head, l) {
   1628 			if (i->parts == NULL)
   1629 				continue;
   1630 			if (i->parts->pscheme->find_by_name == NULL)
   1631 				continue;
   1632 			id = i->parts->pscheme->find_by_name(i->parts, name);
   1633 			if (id == NO_PART)
   1634 				continue;
   1635 			*pno = id;
   1636 			*parts = i->parts;
   1637 			return true;
   1638 		}
   1639 	}
   1640 
   1641 	*pno = NO_PART;
   1642 	*parts = NULL;
   1643 	return false;
   1644 }
   1645 
   1646 static int
   1647 /*ARGSUSED*/
   1648 process_found_fs(struct data *list, size_t num, const struct lookfor *item,
   1649     bool with_fsck)
   1650 {
   1651 	int error;
   1652 	char rdev[PATH_MAX], dev[PATH_MAX],
   1653 	    options[STRSIZE], tmp[STRSIZE], *op, *last;
   1654 	const char *fsname = (const char*)item->var;
   1655 	part_id pno;
   1656 	struct disk_partitions *parts;
   1657 	size_t len;
   1658 	bool first, is_root;
   1659 
   1660 	if (num < 2 || strstr(list[2].u.s_val, "noauto") != NULL)
   1661 		return 0;
   1662 
   1663 	is_root = strcmp(list[1].u.s_val, "/") == 0;
   1664 	if (is_root && target_mounted())
   1665 		return 0;
   1666 
   1667 	if (strcmp(item->head, name_prefix) == 0) {
   1668 		/* this fstab entry uses NAME= syntax */
   1669 
   1670 		/* unescape */
   1671 		char *src, *dst;
   1672 		for (src = list[0].u.s_val, dst =src; src[0] != 0; ) {
   1673 			if (src[0] == '\\' && src[1] != 0)
   1674 				src++;
   1675 			*dst++ = *src++;
   1676 		}
   1677 		*dst = 0;
   1678 
   1679 		if (!find_part_by_name(list[0].u.s_val,
   1680 		    &parts, &pno) || parts == NULL || pno == NO_PART)
   1681 			return 0;
   1682 		parts->pscheme->get_part_device(parts, pno,
   1683 		    dev, sizeof(dev), NULL, plain_name, true, true);
   1684 		parts->pscheme->get_part_device(parts, pno,
   1685 		    rdev, sizeof(rdev), NULL, raw_dev_name, true, true);
   1686 	} else {
   1687 		/* this fstab entry uses the plain device name */
   1688 		if (is_root) {
   1689 			/*
   1690 			 * PR 54480: we can not use the current device name
   1691 			 * as it might be different from the real environment.
   1692 			 * This is an abuse of the functionality, but it used
   1693 			 * to work before (and still does work if only a single
   1694 			 * target disk is involved).
   1695 			 * Use the device name from the current "pm" instead.
   1696 			 */
   1697 			strcpy(rdev, "/dev/r");
   1698 			strlcat(rdev, pm->diskdev, sizeof(rdev));
   1699 			strcpy(dev, "/dev/");
   1700 			strlcat(dev, pm->diskdev, sizeof(dev));
   1701 			/* copy over the partition letter, if any */
   1702 			len = strlen(list[0].u.s_val);
   1703 			if (list[0].u.s_val[len-1] >= 'a' &&
   1704 			    list[0].u.s_val[len-1] <=
   1705 			    ('a' + getmaxpartitions())) {
   1706 				strlcat(rdev, &list[0].u.s_val[len-1],
   1707 				    sizeof(rdev));
   1708 				strlcat(dev, &list[0].u.s_val[len-1],
   1709 				    sizeof(dev));
   1710 			}
   1711 		} else {
   1712 			strcpy(rdev, "/dev/r");
   1713 			strlcat(rdev, list[0].u.s_val, sizeof(rdev));
   1714 			strcpy(dev, "/dev/");
   1715 			strlcat(dev, list[0].u.s_val, sizeof(dev));
   1716 		}
   1717 	}
   1718 
   1719 	if (with_fsck) {
   1720 		/* need the raw device for fsck_preen */
   1721 		error = fsck_preen(rdev, fsname, false);
   1722 		if (error != 0)
   1723 			return error;
   1724 	}
   1725 
   1726 	/* add mount option for fs type */
   1727 	strcpy(options, "-t ");
   1728 	strlcat(options, fsname, sizeof(options));
   1729 
   1730 	/* extract mount options from fstab */
   1731 	strlcpy(tmp, list[2].u.s_val, sizeof(tmp));
   1732 	for (first = true, op = strtok_r(tmp, ",", &last); op != NULL;
   1733 	    op = strtok_r(NULL, ",", &last)) {
   1734 		if (strcmp(op, FSTAB_RW) == 0 ||
   1735 		    strcmp(op, FSTAB_RQ) == 0 ||
   1736 		    strcmp(op, FSTAB_RO) == 0 ||
   1737 		    strcmp(op, FSTAB_SW) == 0 ||
   1738 		    strcmp(op, FSTAB_DP) == 0 ||
   1739 		    strcmp(op, FSTAB_XX) == 0)
   1740 			continue;
   1741 		if (first) {
   1742 			first = false;
   1743 			strlcat(options, " -o ", sizeof(options));
   1744 		} else {
   1745 			strlcat(options, ",", sizeof(options));
   1746 		}
   1747 		strlcat(options, op, sizeof(options));
   1748 	}
   1749 
   1750 	error = target_mount(options, dev, list[1].u.s_val);
   1751 	if (error != 0) {
   1752 		msg_fmt_display(MSG_mount_failed, "%s", list[0].u.s_val);
   1753 		if (!ask_noyes(NULL))
   1754 			return error;
   1755 	}
   1756 	return 0;
   1757 }
   1758 
   1759 static int
   1760 /*ARGSUSED*/
   1761 found_fs(struct data *list, size_t num, const struct lookfor *item)
   1762 {
   1763 	return process_found_fs(list, num, item, true);
   1764 }
   1765 
   1766 static int
   1767 /*ARGSUSED*/
   1768 found_fs_nocheck(struct data *list, size_t num, const struct lookfor *item)
   1769 {
   1770 	return process_found_fs(list, num, item, false);
   1771 }
   1772 
   1773 /*
   1774  * Do an fsck. On failure, inform the user by showing a warning
   1775  * message and doing menu_ok() before proceeding.
   1776  * The device passed should be the full qualified path to raw disk
   1777  * (e.g. /dev/rwd0a).
   1778  * Returns 0 on success, or nonzero return code from fsck() on failure.
   1779  */
   1780 static int
   1781 fsck_preen(const char *disk, const char *fsname, bool silent)
   1782 {
   1783 	char *prog, err[12];
   1784 	int error;
   1785 
   1786 	if (fsname == NULL)
   1787 		return 0;
   1788 	/* first, check if fsck program exists, if not, assume ok */
   1789 	asprintf(&prog, "/sbin/fsck_%s", fsname);
   1790 	if (prog == NULL)
   1791 		return 0;
   1792 	if (access(prog, X_OK) != 0) {
   1793 		free(prog);
   1794 		return 0;
   1795 	}
   1796 	if (!strcmp(fsname,"ffs"))
   1797 		fixsb(prog, disk);
   1798 	error = run_program(silent? RUN_SILENT|RUN_ERROR_OK : 0, "%s -p -q %s", prog, disk);
   1799 	free(prog);
   1800 	if (error != 0 && !silent) {
   1801 		sprintf(err, "%d", error);
   1802 		msg_display_subst(msg_string(MSG_badfs), 3,
   1803 		    disk, fsname, err);
   1804 		if (ask_noyes(NULL))
   1805 			error = 0;
   1806 		/* XXX at this point maybe we should run a full fsck? */
   1807 	}
   1808 	return error;
   1809 }
   1810 
   1811 /* This performs the same function as the etc/rc.d/fixsb script
   1812  * which attempts to correct problems with ffs1 filesystems
   1813  * which may have been introduced by booting a netbsd-current kernel
   1814  * from between April of 2003 and January 2004. For more information
   1815  * This script was developed as a response to NetBSD pr install/25138
   1816  * Additional prs regarding the original issue include:
   1817  *  bin/17910 kern/21283 kern/21404 port-macppc/23925 port-macppc/23926
   1818  */
   1819 static void
   1820 fixsb(const char *prog, const char *disk)
   1821 {
   1822 	int fd;
   1823 	int rval;
   1824 	union {
   1825 		struct fs fs;
   1826 		char buf[SBLOCKSIZE];
   1827 	} sblk;
   1828 	struct fs *fs = &sblk.fs;
   1829 
   1830 	fd = open(disk, O_RDONLY);
   1831 	if (fd == -1)
   1832 		return;
   1833 
   1834 	/* Read ffsv1 main superblock */
   1835 	rval = pread(fd, sblk.buf, sizeof sblk.buf, SBLOCK_UFS1);
   1836 	close(fd);
   1837 	if (rval != sizeof sblk.buf)
   1838 		return;
   1839 
   1840 	if (fs->fs_magic != FS_UFS1_MAGIC &&
   1841 	    fs->fs_magic != FS_UFS1_MAGIC_SWAPPED)
   1842 		/* Not FFSv1 */
   1843 		return;
   1844 	if (fs->fs_old_flags & FS_FLAGS_UPDATED)
   1845 		/* properly updated fslevel 4 */
   1846 		return;
   1847 	if (fs->fs_bsize != fs->fs_maxbsize)
   1848 		/* not messed up */
   1849 		return;
   1850 
   1851 	/*
   1852 	 * OK we have a munged fs, first 'upgrade' to fslevel 4,
   1853 	 * We specify -b16 in order to stop fsck bleating that the
   1854 	 * sb doesn't match the first alternate.
   1855 	 */
   1856 	run_program(RUN_DISPLAY | RUN_PROGRESS,
   1857 	    "%s -p -b 16 -c 4 %s", prog, disk);
   1858 	/* Then downgrade to fslevel 3 */
   1859 	run_program(RUN_DISPLAY | RUN_PROGRESS,
   1860 	    "%s -p -c 3 %s", prog, disk);
   1861 }
   1862 
   1863 /*
   1864  * fsck and mount the root partition.
   1865  * devdev is the fully qualified block device name.
   1866  */
   1867 static int
   1868 mount_root(const char *devdev, bool first, bool writeable,
   1869      struct install_partition_desc *install)
   1870 {
   1871 	int	error;
   1872 
   1873 	error = fsck_preen(devdev, "ffs", false);
   1874 	if (error != 0)
   1875 		return error;
   1876 
   1877 	if (first)
   1878 		md_pre_mount(install, 0);
   1879 
   1880 	/* Mount devdev on target's "".
   1881 	 * If we pass "" as mount-on, Prefixing will DTRT.
   1882 	 * for now, use no options.
   1883 	 * XXX consider -o remount in case target root is
   1884 	 * current root, still readonly from single-user?
   1885 	 */
   1886 	return target_mount(writeable? "" : "-r", devdev, "");
   1887 }
   1888 
   1889 /* Get information on the file systems mounted from the root filesystem.
   1890  * Offer to convert them into 4.4BSD inodes if they are not 4.4BSD
   1891  * inodes.  Fsck them.  Mount them.
   1892  */
   1893 
   1894 int
   1895 mount_disks(struct install_partition_desc *install)
   1896 {
   1897 	char *fstab;
   1898 	int   fstabsize;
   1899 	int   error;
   1900 	char devdev[PATH_MAX];
   1901 	size_t i, num_fs_types, num_entries;
   1902 	struct lookfor *fstabbuf, *l;
   1903 
   1904 	if (install->cur_system)
   1905 		return 0;
   1906 
   1907 	/*
   1908 	 * Check what file system tools are available and create parsers
   1909 	 * for the corresponding fstab(5) entries - all others will be
   1910 	 * ignored.
   1911 	 */
   1912 	num_fs_types = 1;	/* ffs is implicit */
   1913 	for (i = 0; i < __arraycount(extern_fs_with_chk); i++) {
   1914 		sprintf(devdev, "/sbin/newfs_%s", extern_fs_with_chk[i]);
   1915 		if (file_exists_p(devdev))
   1916 			num_fs_types++;
   1917 	}
   1918 	for (i = 0; i < __arraycount(extern_fs_newfs_only); i++) {
   1919 		sprintf(devdev, "/sbin/newfs_%s", extern_fs_newfs_only[i]);
   1920 		if (file_exists_p(devdev))
   1921 			num_fs_types++;
   1922 	}
   1923 	num_entries = 2 *  num_fs_types + 1;	/* +1 for "ufs" special case */
   1924 	fstabbuf = calloc(num_entries, sizeof(*fstabbuf));
   1925 	if (fstabbuf == NULL)
   1926 		return -1;
   1927 	l = fstabbuf;
   1928 	l->head = "/dev/";
   1929 	l->fmt = strdup("/dev/%s %s ffs %s");
   1930 	l->todo = "c";
   1931 	l->var = __UNCONST("ffs");
   1932 	l->func = found_fs;
   1933 	l++;
   1934 	l->head = "/dev/";
   1935 	l->fmt = strdup("/dev/%s %s ufs %s");
   1936 	l->todo = "c";
   1937 	l->var = __UNCONST("ffs");
   1938 	l->func = found_fs;
   1939 	l++;
   1940 	l->head = NAME_PREFIX;
   1941 	l->fmt = strdup(NAME_PREFIX "%s %s ffs %s");
   1942 	l->todo = "c";
   1943 	l->var = __UNCONST("ffs");
   1944 	l->func = found_fs;
   1945 	l++;
   1946 	for (i = 0; i < __arraycount(extern_fs_with_chk); i++) {
   1947 		sprintf(devdev, "/sbin/newfs_%s", extern_fs_with_chk[i]);
   1948 		if (!file_exists_p(devdev))
   1949 			continue;
   1950 		sprintf(devdev, "/dev/%%s %%s %s %%s", extern_fs_with_chk[i]);
   1951 		l->head = "/dev/";
   1952 		l->fmt = strdup(devdev);
   1953 		l->todo = "c";
   1954 		l->var = __UNCONST(extern_fs_with_chk[i]);
   1955 		l->func = found_fs;
   1956 		l++;
   1957 		sprintf(devdev, NAME_PREFIX "%%s %%s %s %%s",
   1958 		    extern_fs_with_chk[i]);
   1959 		l->head = NAME_PREFIX;
   1960 		l->fmt = strdup(devdev);
   1961 		l->todo = "c";
   1962 		l->var = __UNCONST(extern_fs_with_chk[i]);
   1963 		l->func = found_fs;
   1964 		l++;
   1965 	}
   1966 	for (i = 0; i < __arraycount(extern_fs_newfs_only); i++) {
   1967 		sprintf(devdev, "/sbin/newfs_%s", extern_fs_newfs_only[i]);
   1968 		if (!file_exists_p(devdev))
   1969 			continue;
   1970 		sprintf(devdev, "/dev/%%s %%s %s %%s", extern_fs_newfs_only[i]);
   1971 		l->head = "/dev/";
   1972 		l->fmt = strdup(devdev);
   1973 		l->todo = "c";
   1974 		l->var = __UNCONST(extern_fs_newfs_only[i]);
   1975 		l->func = found_fs_nocheck;
   1976 		l++;
   1977 		sprintf(devdev, NAME_PREFIX "%%s %%s %s %%s",
   1978 		    extern_fs_newfs_only[i]);
   1979 		l->head = NAME_PREFIX;
   1980 		l->fmt = strdup(devdev);
   1981 		l->todo = "c";
   1982 		l->var = __UNCONST(extern_fs_newfs_only[i]);
   1983 		l->func = found_fs_nocheck;
   1984 		l++;
   1985 	}
   1986 	assert((size_t)(l - fstabbuf) == num_entries);
   1987 
   1988 	/* First the root device. */
   1989 	if (target_already_root()) {
   1990 		/* avoid needing to call target_already_root() again */
   1991 		targetroot_mnt[0] = 0;
   1992 	} else if (pm->no_part) {
   1993 		snprintf(devdev, sizeof devdev, _PATH_DEV "%s", pm->diskdev);
   1994 		error = mount_root(devdev, true, false, install);
   1995 		if (error != 0 && error != EBUSY)
   1996 			return -1;
   1997 	} else {
   1998 		for (i = 0; i < install->num; i++) {
   1999 			if (is_root_part_mount(install->infos[i].mount))
   2000 				break;
   2001 		}
   2002 
   2003 		if (i >= install->num) {
   2004 			hit_enter_to_continue(MSG_noroot, NULL);
   2005 			return -1;
   2006 		}
   2007 
   2008 		if (!install->infos[i].parts->pscheme->get_part_device(
   2009 		    install->infos[i].parts, install->infos[i].cur_part_id,
   2010 		    devdev, sizeof devdev, NULL, plain_name, true, true))
   2011 			return -1;
   2012 		error = mount_root(devdev, true, false, install);
   2013 		if (error != 0 && error != EBUSY)
   2014 			return -1;
   2015 	}
   2016 
   2017 	/* Check the target /etc/fstab exists before trying to parse it. */
   2018 	if (target_dir_exists_p("/etc") == 0 ||
   2019 	    target_file_exists_p("/etc/fstab") == 0) {
   2020 		msg_fmt_display(MSG_noetcfstab, "%s", pm->diskdev);
   2021 		hit_enter_to_continue(NULL, NULL);
   2022 		return -1;
   2023 	}
   2024 
   2025 
   2026 	/* Get fstab entries from the target-root /etc/fstab. */
   2027 	fstabsize = target_collect_file(T_FILE, &fstab, "/etc/fstab");
   2028 	if (fstabsize < 0) {
   2029 		/* error ! */
   2030 		msg_fmt_display(MSG_badetcfstab, "%s", pm->diskdev);
   2031 		hit_enter_to_continue(NULL, NULL);
   2032 		umount_root();
   2033 		return -2;
   2034 	}
   2035 	/*
   2036 	 * We unmount the read-only root again, so we can mount it
   2037 	 * with proper options from /etc/fstab
   2038 	 */
   2039 	umount_root();
   2040 
   2041 	/*
   2042 	 * Now do all entries in /etc/fstab and mount them if required
   2043 	 */
   2044 	error = walk(fstab, (size_t)fstabsize, fstabbuf, num_entries);
   2045 	free(fstab);
   2046 	for (i = 0; i < num_entries; i++)
   2047 		free(__UNCONST(fstabbuf[i].fmt));
   2048 	free(fstabbuf);
   2049 
   2050 	return error;
   2051 }
   2052 
   2053 static char swap_dev[PATH_MAX];
   2054 
   2055 void
   2056 set_swap_if_low_ram(struct install_partition_desc *install)
   2057 {
   2058 	swap_dev[0] = 0;
   2059 	if (get_ramsize() <= TINY_RAM_SIZE)
   2060 		set_swap(install);
   2061 }
   2062 
   2063 void
   2064 set_swap(struct install_partition_desc *install)
   2065 {
   2066 	size_t i;
   2067 	int rval;
   2068 
   2069 	swap_dev[0] = 0;
   2070 	for (i = 0; i < install->num; i++) {
   2071 		if (install->infos[i].type == PT_swap)
   2072 			break;
   2073 	}
   2074 	if (i >= install->num)
   2075 		return;
   2076 
   2077 	if (!install->infos[i].parts->pscheme->get_part_device(
   2078 	    install->infos[i].parts, install->infos[i].cur_part_id, swap_dev,
   2079 	    sizeof swap_dev, NULL, plain_name, true, true))
   2080 		return;
   2081 
   2082 	rval = swapctl(SWAP_ON, swap_dev, 0);
   2083 	if (rval != 0)
   2084 		swap_dev[0] = 0;
   2085 }
   2086 
   2087 void
   2088 clear_swap(void)
   2089 {
   2090 
   2091 	if (swap_dev[0] == 0)
   2092 		return;
   2093 	swapctl(SWAP_OFF, swap_dev, 0);
   2094 	swap_dev[0] = 0;
   2095 }
   2096 
   2097 int
   2098 check_swap(const char *disk, int remove_swap)
   2099 {
   2100 	struct swapent *swap;
   2101 	char *cp;
   2102 	int nswap;
   2103 	int l;
   2104 	int rval = 0;
   2105 
   2106 	nswap = swapctl(SWAP_NSWAP, 0, 0);
   2107 	if (nswap <= 0)
   2108 		return 0;
   2109 
   2110 	swap = malloc(nswap * sizeof *swap);
   2111 	if (swap == NULL)
   2112 		return -1;
   2113 
   2114 	nswap = swapctl(SWAP_STATS, swap, nswap);
   2115 	if (nswap < 0)
   2116 		goto bad_swap;
   2117 
   2118 	l = strlen(disk);
   2119 	while (--nswap >= 0) {
   2120 		/* Should we check the se_dev or se_path? */
   2121 		cp = swap[nswap].se_path;
   2122 		if (memcmp(cp, "/dev/", 5) != 0)
   2123 			continue;
   2124 		if (memcmp(cp + 5, disk, l) != 0)
   2125 			continue;
   2126 		if (!isalpha(*(unsigned char *)(cp + 5 + l)))
   2127 			continue;
   2128 		if (cp[5 + l + 1] != 0)
   2129 			continue;
   2130 		/* ok path looks like it is for this device */
   2131 		if (!remove_swap) {
   2132 			/* count active swap areas */
   2133 			rval++;
   2134 			continue;
   2135 		}
   2136 		if (swapctl(SWAP_OFF, cp, 0) == -1)
   2137 			rval = -1;
   2138 	}
   2139 
   2140     done:
   2141 	free(swap);
   2142 	return rval;
   2143 
   2144     bad_swap:
   2145 	rval = -1;
   2146 	goto done;
   2147 }
   2148 
   2149 #ifdef HAVE_BOOTXX_xFS
   2150 char *
   2151 bootxx_name(struct install_partition_desc *install)
   2152 {
   2153 	size_t i;
   2154 	int fstype = -1;
   2155 	const char *bootxxname;
   2156 	char *bootxx;
   2157 
   2158 	/* find a partition to be mounted as / */
   2159 	for (i = 0; i < install->num; i++) {
   2160 		if ((install->infos[i].instflags & PUIINST_MOUNT)
   2161 		    && strcmp(install->infos[i].mount, "/") == 0) {
   2162 			fstype = install->infos[i].fs_type;
   2163 			break;
   2164 		}
   2165 	}
   2166 	if (fstype < 0) {
   2167 		/* not found? take first root type partition instead */
   2168 		for (i = 0; i < install->num; i++) {
   2169 			if (install->infos[i].type == PT_root) {
   2170 				fstype = install->infos[i].fs_type;
   2171 				break;
   2172 			}
   2173 		}
   2174 	}
   2175 
   2176 	/* check we have boot code for the root partition type */
   2177 	switch (fstype) {
   2178 #if defined(BOOTXX_FFSV1) || defined(BOOTXX_FFSV2)
   2179 	case FS_BSDFFS:
   2180 		if (install->infos[i].fs_version == 2) {
   2181 #ifdef BOOTXX_FFSV2
   2182 			bootxxname = BOOTXX_FFSV2;
   2183 #else
   2184 			bootxxname = NULL;
   2185 #endif
   2186 		} else {
   2187 #ifdef BOOTXX_FFSV1
   2188 			bootxxname = BOOTXX_FFSV1;
   2189 #else
   2190 			bootxxname = NULL;
   2191 #endif
   2192 		}
   2193 		break;
   2194 #endif
   2195 #ifdef BOOTXX_LFSV2
   2196 	case FS_BSDLFS:
   2197 		bootxxname = BOOTXX_LFSV2;
   2198 		break;
   2199 #endif
   2200 	default:
   2201 		bootxxname = NULL;
   2202 		break;
   2203 	}
   2204 
   2205 	if (bootxxname == NULL)
   2206 		return NULL;
   2207 
   2208 	asprintf(&bootxx, "%s/%s", BOOTXXDIR, bootxxname);
   2209 	return bootxx;
   2210 }
   2211 #endif
   2212 
   2213 /* from dkctl.c */
   2214 static int
   2215 get_dkwedges_sort(const void *a, const void *b)
   2216 {
   2217 	const struct dkwedge_info *dkwa = a, *dkwb = b;
   2218 	const daddr_t oa = dkwa->dkw_offset, ob = dkwb->dkw_offset;
   2219 	return (oa < ob) ? -1 : (oa > ob) ? 1 : 0;
   2220 }
   2221 
   2222 int
   2223 get_dkwedges(struct dkwedge_info **dkw, const char *diskdev)
   2224 {
   2225 	struct dkwedge_list dkwl;
   2226 
   2227 	*dkw = NULL;
   2228 	if (!get_wedge_list(diskdev, &dkwl))
   2229 		return -1;
   2230 
   2231 	if (dkwl.dkwl_nwedges > 0 && *dkw != NULL) {
   2232 		qsort(*dkw, dkwl.dkwl_nwedges, sizeof(**dkw),
   2233 		    get_dkwedges_sort);
   2234 	}
   2235 
   2236 	return dkwl.dkwl_nwedges;
   2237 }
   2238 
   2239 #ifndef NO_CLONES
   2240 /*
   2241  * Helper structures used in the partition select menu
   2242  */
   2243 struct single_partition {
   2244 	struct disk_partitions *parts;
   2245 	part_id id;
   2246 };
   2247 
   2248 struct sel_menu_data {
   2249 	struct single_partition *partitions;
   2250 	struct selected_partition result;
   2251 };
   2252 
   2253 static int
   2254 select_single_part(menudesc *m, void *arg)
   2255 {
   2256 	struct sel_menu_data *data = arg;
   2257 
   2258 	data->result.parts = data->partitions[m->cursel].parts;
   2259 	data->result.id = data->partitions[m->cursel].id;
   2260 
   2261 	return 1;
   2262 }
   2263 
   2264 static void
   2265 display_single_part(menudesc *m, int opt, void *arg)
   2266 {
   2267 	const struct sel_menu_data *data = arg;
   2268 	struct disk_part_info info;
   2269 	struct disk_partitions *parts = data->partitions[opt].parts;
   2270 	part_id id = data->partitions[opt].id;
   2271 	int l;
   2272 	const char *desc = NULL;
   2273 	char line[MENUSTRSIZE*2];
   2274 
   2275 	if (!parts->pscheme->get_part_info(parts, id, &info))
   2276 		return;
   2277 
   2278 	if (parts->pscheme->other_partition_identifier != NULL)
   2279 		desc = parts->pscheme->other_partition_identifier(
   2280 		    parts, id);
   2281 
   2282 	daddr_t start = info.start / sizemult;
   2283 	daddr_t size = info.size / sizemult;
   2284 	snprintf(line, sizeof line, "%s [%" PRIu64 " @ %" PRIu64 "]",
   2285 	    parts->disk, size, start);
   2286 
   2287 	if (info.nat_type != NULL) {
   2288 		strlcat(line, " ", sizeof line);
   2289 		strlcat(line, info.nat_type->description, sizeof line);
   2290 	}
   2291 
   2292 	if (desc != NULL) {
   2293 		strlcat(line, ": ", sizeof line);
   2294 		strlcat(line, desc, sizeof line);
   2295 	}
   2296 
   2297 	l = strlen(line);
   2298 	if (l >= (m->w))
   2299 		strcpy(line + (m->w-3), "...");
   2300 	wprintw(m->mw, "%s", line);
   2301 }
   2302 
   2303 /*
   2304  * is the given "test" partitions set used in the selected set?
   2305  */
   2306 static bool
   2307 selection_has_parts(struct selected_partitions *sel,
   2308     const struct disk_partitions *test)
   2309 {
   2310 	size_t i;
   2311 
   2312 	for (i = 0; i < sel->num_sel; i++) {
   2313 		if (sel->selection[i].parts == test)
   2314 			return true;
   2315 	}
   2316 	return false;
   2317 }
   2318 
   2319 /*
   2320  * is the given "test" partition in the selected set?
   2321  */
   2322 static bool
   2323 selection_has_partition(struct selected_partitions *sel,
   2324     const struct disk_partitions *test, part_id test_id)
   2325 {
   2326 	size_t i;
   2327 
   2328 	for (i = 0; i < sel->num_sel; i++) {
   2329 		if (sel->selection[i].parts == test &&
   2330 		    sel->selection[i].id == test_id)
   2331 			return true;
   2332 	}
   2333 	return false;
   2334 }
   2335 
   2336 /*
   2337  * let the user select a partition, optionally skipping all partitions
   2338  * on the "ignore" device
   2339  */
   2340 static bool
   2341 add_select_partition(struct selected_partitions *res,
   2342     struct disk_partitions **all_parts, size_t all_cnt)
   2343 {
   2344 	struct disk_partitions *ps;
   2345 	struct disk_part_info info;
   2346 	part_id id;
   2347 	struct single_partition *partitions, *pp;
   2348 	struct menu_ent *part_menu_opts, *menup;
   2349 	size_t n, part_cnt;
   2350 	int sel_menu;
   2351 
   2352 	/*
   2353 	 * count how many items our menu will have
   2354 	 */
   2355 	part_cnt = 0;
   2356 	for (n = 0; n < all_cnt; n++) {
   2357 		ps = all_parts[n];
   2358 		for (id = 0; id < ps->num_part; id++) {
   2359 			if (selection_has_partition(res, ps, id))
   2360 				continue;
   2361 			if (!ps->pscheme->get_part_info(ps, id, &info))
   2362 				continue;
   2363 			if (info.flags & (PTI_SEC_CONTAINER|PTI_WHOLE_DISK|
   2364 			    PTI_PSCHEME_INTERNAL|PTI_RAW_PART))
   2365 				continue;
   2366 			part_cnt++;
   2367 		}
   2368 	}
   2369 
   2370 	/*
   2371 	 * create a menu from this and let the user
   2372 	 * select one partition
   2373 	 */
   2374 	part_menu_opts = NULL;
   2375 	partitions = calloc(part_cnt, sizeof *partitions);
   2376 	if (partitions == NULL)
   2377 		goto done;
   2378 	part_menu_opts = calloc(part_cnt, sizeof *part_menu_opts);
   2379 	if (part_menu_opts == NULL)
   2380 		goto done;
   2381 	pp = partitions;
   2382 	menup = part_menu_opts;
   2383 	for (n = 0; n < all_cnt; n++) {
   2384 		ps = all_parts[n];
   2385 		for (id = 0; id < ps->num_part; id++) {
   2386 			if (selection_has_partition(res, ps, id))
   2387 				continue;
   2388 			if (!ps->pscheme->get_part_info(ps, id, &info))
   2389 				continue;
   2390 			if (info.flags & (PTI_SEC_CONTAINER|PTI_WHOLE_DISK|
   2391 			    PTI_PSCHEME_INTERNAL|PTI_RAW_PART))
   2392 				continue;
   2393 			pp->parts = ps;
   2394 			pp->id = id;
   2395 			pp++;
   2396 			menup->opt_action = select_single_part;
   2397 			menup++;
   2398 		}
   2399 	}
   2400 	sel_menu = new_menu(MSG_select_foreign_part, part_menu_opts, part_cnt,
   2401 	    3, 3, 0, 60,
   2402 	    MC_SUBMENU | MC_SCROLL | MC_NOCLEAR,
   2403 	    NULL, display_single_part, NULL,
   2404 	    NULL, MSG_exit_menu_generic);
   2405 	if (sel_menu != -1) {
   2406 		struct selected_partition *newsels;
   2407 		struct sel_menu_data data;
   2408 
   2409 		memset(&data, 0, sizeof data);
   2410 		data.partitions = partitions;
   2411 		process_menu(sel_menu, &data);
   2412 		free_menu(sel_menu);
   2413 
   2414 		if (data.result.parts != NULL) {
   2415 			newsels = realloc(res->selection,
   2416 			    sizeof(*res->selection)*(res->num_sel+1));
   2417 			if (newsels != NULL) {
   2418 				res->selection = newsels;
   2419 				newsels += res->num_sel++;
   2420 				newsels->parts = data.result.parts;
   2421 				newsels->id = data.result.id;
   2422 			}
   2423 		}
   2424 	}
   2425 
   2426 	/*
   2427 	 * Final cleanup
   2428 	 */
   2429 done:
   2430 	free(part_menu_opts);
   2431 	free(partitions);
   2432 
   2433 	return res->num_sel > 0;
   2434 }
   2435 
   2436 struct part_selection_and_all_parts {
   2437 	struct selected_partitions *selection;
   2438 	struct disk_partitions **all_parts;
   2439 	size_t all_cnt;
   2440 	char *title;
   2441 	bool cancelled;
   2442 };
   2443 
   2444 static int
   2445 toggle_clone_data(struct menudesc *m, void *arg)
   2446 {
   2447 	struct part_selection_and_all_parts *sel = arg;
   2448 
   2449 	sel->selection->with_data = !sel->selection->with_data;
   2450 	return 0;
   2451 }
   2452 
   2453 static int
   2454 add_another(struct menudesc *m, void *arg)
   2455 {
   2456 	struct part_selection_and_all_parts *sel = arg;
   2457 
   2458 	add_select_partition(sel->selection, sel->all_parts, sel->all_cnt);
   2459 	return 0;
   2460 }
   2461 
   2462 static int
   2463 cancel_clone(struct menudesc *m, void *arg)
   2464 {
   2465 	struct part_selection_and_all_parts *sel = arg;
   2466 
   2467 	sel->cancelled = true;
   2468 	return 1;
   2469 }
   2470 
   2471 static void
   2472 update_sel_part_title(struct part_selection_and_all_parts *sel)
   2473 {
   2474 	struct disk_part_info info;
   2475 	char *buf, line[MENUSTRSIZE];
   2476 	size_t buf_len, i;
   2477 
   2478 	buf_len = MENUSTRSIZE * (1+sel->selection->num_sel);
   2479 	buf = malloc(buf_len);
   2480 	if (buf == NULL)
   2481 		return;
   2482 
   2483 	strcpy(buf, msg_string(MSG_select_source_hdr));
   2484 	for (i = 0; i < sel->selection->num_sel; i++) {
   2485 		struct selected_partition *s =
   2486 		    &sel->selection->selection[i];
   2487 		if (!s->parts->pscheme->get_part_info(s->parts, s->id, &info))
   2488 			continue;
   2489 		daddr_t start = info.start / sizemult;
   2490 		daddr_t size = info.size / sizemult;
   2491 		sprintf(line, "\n  %s [%" PRIu64 " @ %" PRIu64 "] ",
   2492 		    s->parts->disk, size, start);
   2493 		if (info.nat_type != NULL)
   2494 			strlcat(line, info.nat_type->description, sizeof(line));
   2495 		strlcat(buf, line, buf_len);
   2496 	}
   2497 	free(sel->title);
   2498 	sel->title = buf;
   2499 }
   2500 
   2501 static void
   2502 post_sel_part(struct menudesc *m, void *arg)
   2503 {
   2504 	struct part_selection_and_all_parts *sel = arg;
   2505 
   2506 	if (m->mw == NULL)
   2507 		return;
   2508 	update_sel_part_title(sel);
   2509 	m->title = sel->title;
   2510 	m->h = 0;
   2511 	resize_menu_height(m);
   2512 }
   2513 
   2514 static void
   2515 fmt_sel_part_line(struct menudesc *m, int i, void *arg)
   2516 {
   2517 	struct part_selection_and_all_parts *sel = arg;
   2518 
   2519 	wprintw(m->mw, "%s: %s", msg_string(MSG_clone_with_data),
   2520 	    sel->selection->with_data ?
   2521 		msg_string(MSG_Yes) :
   2522 		 msg_string(MSG_No));
   2523 }
   2524 
   2525 bool
   2526 select_partitions(struct selected_partitions *res,
   2527     const struct disk_partitions *ignore)
   2528 {
   2529 	struct disk_desc disks[MAX_DISKS];
   2530 	struct disk_partitions *ps;
   2531 	struct part_selection_and_all_parts data;
   2532 	struct pm_devs *i;
   2533 	size_t j;
   2534 	int cnt, n, m;
   2535 	static menu_ent men[] = {
   2536 		{ .opt_name = MSG_select_source_add,
   2537 		  .opt_action = add_another },
   2538 		{ .opt_action = toggle_clone_data },
   2539 		{ .opt_name = MSG_cancel, .opt_action = cancel_clone },
   2540 	};
   2541 
   2542 	memset(res, 0, sizeof *res);
   2543 	memset(&data, 0, sizeof data);
   2544 	data.selection = res;
   2545 
   2546 	/*
   2547 	 * collect all available partition sets
   2548 	 */
   2549 	data.all_cnt = 0;
   2550 	if (SLIST_EMPTY(&pm_head)) {
   2551 		cnt = get_disks(disks, false);
   2552 		if (cnt <= 0)
   2553 			return false;
   2554 
   2555 		/*
   2556 		 * allocate two slots for each disk (primary/secondary)
   2557 		 */
   2558 		data.all_parts = calloc(2*cnt, sizeof *data.all_parts);
   2559 		if (data.all_parts == NULL)
   2560 			return false;
   2561 
   2562 		for (n = 0; n < cnt; n++) {
   2563 			if (ignore != NULL &&
   2564 			    strcmp(disks[n].dd_name, ignore->disk) == 0)
   2565 				continue;
   2566 
   2567 			ps = partitions_read_disk(disks[n].dd_name,
   2568 			    disks[n].dd_totsec,
   2569 			    disks[n].dd_secsize,
   2570 			    disks[n].dd_no_mbr);
   2571 			if (ps == NULL)
   2572 				continue;
   2573 			data.all_parts[data.all_cnt++] = ps;
   2574 			ps = get_inner_parts(ps);
   2575 			if (ps == NULL)
   2576 				continue;
   2577 			data.all_parts[data.all_cnt++] = ps;
   2578 		}
   2579 		if (data.all_cnt > 0)
   2580 			res->free_parts = true;
   2581 	} else {
   2582 		cnt = 0;
   2583 		SLIST_FOREACH(i, &pm_head, l)
   2584 			cnt++;
   2585 
   2586 		data.all_parts = calloc(cnt, sizeof *data.all_parts);
   2587 		if (data.all_parts == NULL)
   2588 			return false;
   2589 
   2590 		SLIST_FOREACH(i, &pm_head, l) {
   2591 			if (i->parts == NULL)
   2592 				continue;
   2593 			if (i->parts == ignore)
   2594 				continue;
   2595 			data.all_parts[data.all_cnt++] = i->parts;
   2596 		}
   2597 	}
   2598 
   2599 	if (!add_select_partition(res, data.all_parts, data.all_cnt))
   2600 		goto fail;
   2601 
   2602 	/* loop with menu */
   2603 	update_sel_part_title(&data);
   2604 	m = new_menu(data.title, men, __arraycount(men), 3, 2, 0, 65, MC_SCROLL,
   2605 	    post_sel_part, fmt_sel_part_line, NULL, NULL, MSG_clone_src_done);
   2606 	process_menu(m, &data);
   2607 	free(data.title);
   2608 	if (res->num_sel == 0)
   2609 		goto fail;
   2610 
   2611 	/* cleanup */
   2612 	if (res->free_parts) {
   2613 		for (j = 0; j < data.all_cnt; j++) {
   2614 			if (selection_has_parts(res, data.all_parts[j]))
   2615 				continue;
   2616 			if (data.all_parts[j]->parent != NULL)
   2617 				continue;
   2618 			data.all_parts[j]->pscheme->free(data.all_parts[j]);
   2619 		}
   2620 	}
   2621 	free(data.all_parts);
   2622 	return true;
   2623 
   2624 fail:
   2625 	if (res->free_parts) {
   2626 		for (j = 0; j < data.all_cnt; j++) {
   2627 			if (data.all_parts[j]->parent != NULL)
   2628 				continue;
   2629 			data.all_parts[j]->pscheme->free(data.all_parts[j]);
   2630 		}
   2631 	}
   2632 	free(data.all_parts);
   2633 	return false;
   2634 }
   2635 
   2636 void
   2637 free_selected_partitions(struct selected_partitions *selected)
   2638 {
   2639 	size_t i;
   2640 	struct disk_partitions *parts;
   2641 
   2642 	if (!selected->free_parts)
   2643 		return;
   2644 
   2645 	for (i = 0; i < selected->num_sel; i++) {
   2646 		parts = selected->selection[i].parts;
   2647 
   2648 		/* remove from list before testing for other instances */
   2649 		selected->selection[i].parts = NULL;
   2650 
   2651 		/* if this is the secondary partition set, the parent owns it */
   2652 		if (parts->parent != NULL)
   2653 			continue;
   2654 
   2655 		/* only free once (we use the last one) */
   2656 		if (selection_has_parts(selected, parts))
   2657 			continue;
   2658 		parts->pscheme->free(parts);
   2659 	}
   2660 	free(selected->selection);
   2661 }
   2662 
   2663 daddr_t
   2664 selected_parts_size(struct selected_partitions *selected)
   2665 {
   2666 	struct disk_part_info info;
   2667 	size_t i;
   2668 	daddr_t s = 0;
   2669 
   2670 	for (i = 0; i < selected->num_sel; i++) {
   2671 		if (!selected->selection[i].parts->pscheme->get_part_info(
   2672 		    selected->selection[i].parts,
   2673 		    selected->selection[i].id, &info))
   2674 			continue;
   2675 		s += info.size;
   2676 	}
   2677 
   2678 	return s;
   2679 }
   2680 
   2681 int
   2682 clone_target_select(menudesc *m, void *arg)
   2683 {
   2684 	struct clone_target_menu_data *data = arg;
   2685 
   2686 	data->res = m->cursel;
   2687 	return 1;
   2688 }
   2689 
   2690 bool
   2691 clone_partition_data(struct disk_partitions *dest_parts, part_id did,
   2692     struct disk_partitions *src_parts, part_id sid)
   2693 {
   2694 	char src_dev[MAXPATHLEN], target_dev[MAXPATHLEN];
   2695 
   2696 	if (!src_parts->pscheme->get_part_device(
   2697 	    src_parts, sid, src_dev, sizeof src_dev, NULL,
   2698 	    raw_dev_name, true, true))
   2699 		return false;
   2700 	if (!dest_parts->pscheme->get_part_device(
   2701 	    dest_parts, did, target_dev, sizeof target_dev, NULL,
   2702 	    raw_dev_name, true, true))
   2703 		return false;
   2704 
   2705 	return run_program(RUN_DISPLAY | RUN_PROGRESS,
   2706 	    "progress -f %s -b 1m dd bs=1m of=%s",
   2707 	    src_dev, target_dev) == 0;
   2708 }
   2709 #endif
   2710 
   2711