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