Home | History | Annotate | Line # | Download | only in sysinst
disks.c revision 1.25
      1 /*	$NetBSD: disks.c,v 1.25 2018/11/11 10:06:09 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 <errno.h>
     39 #include <inttypes.h>
     40 #include <stdio.h>
     41 #include <stdlib.h>
     42 #include <unistd.h>
     43 #include <fcntl.h>
     44 #include <fnmatch.h>
     45 #include <util.h>
     46 #include <uuid.h>
     47 
     48 #include <sys/param.h>
     49 #include <sys/sysctl.h>
     50 #include <sys/swap.h>
     51 #include <ufs/ufs/dinode.h>
     52 #include <ufs/ffs/fs.h>
     53 #define FSTYPENAMES
     54 #include <sys/disklabel.h>
     55 #include <sys/disklabel_gpt.h>
     56 
     57 #include <dev/scsipi/scsipi_all.h>
     58 #include <sys/scsiio.h>
     59 
     60 #include <dev/ata/atareg.h>
     61 #include <sys/ataio.h>
     62 
     63 #include "defs.h"
     64 #include "md.h"
     65 #include "msg_defs.h"
     66 #include "menu_defs.h"
     67 #include "txtwalk.h"
     68 
     69 /* Disk descriptions */
     70 struct disk_desc {
     71 	char	dd_name[SSTRSIZE];
     72 	char	dd_descr[70];
     73 	bool	dd_no_mbr, dd_no_part;
     74 	uint	dd_cyl;
     75 	uint	dd_head;
     76 	uint	dd_sec;
     77 	uint	dd_secsize;
     78 	uint	dd_totsec;
     79 };
     80 
     81 /* gpt(8) use different filesystem names.
     82    So, we cant use ./common/lib/libutil/getfstypename.c */
     83 struct gptfs_t {
     84     const char *name;
     85     int id;
     86     uuid_t uuid;
     87 };
     88 static const struct gptfs_t gpt_filesystems[] = {
     89     { "swap", FS_SWAP, GPT_ENT_TYPE_NETBSD_SWAP, },
     90     { "ffs", FS_BSDFFS, GPT_ENT_TYPE_NETBSD_FFS, },
     91     { "lfs", FS_BSDLFS, GPT_ENT_TYPE_NETBSD_LFS, },
     92     { "linux", FS_EX2FS, GPT_ENT_TYPE_LINUX_DATA, },
     93     { "windows,", FS_MSDOS, GPT_ENT_TYPE_MS_BASIC_DATA, },
     94     { "hfs", FS_HFS, GPT_ENT_TYPE_APPLE_HFS, },
     95     { "ufs", FS_OTHER, GPT_ENT_TYPE_APPLE_UFS, },
     96     { "ccd", FS_CCD, GPT_ENT_TYPE_NETBSD_CCD, },
     97     { "raid", FS_RAID, GPT_ENT_TYPE_NETBSD_RAIDFRAME, },
     98     { "cgd", FS_CGD, GPT_ENT_TYPE_NETBSD_CGD, },
     99     { "efi", FS_OTHER, GPT_ENT_TYPE_EFI, },
    100     { "bios", FS_OTHER, GPT_ENT_TYPE_BIOS, },
    101     { NULL, -1, GPT_ENT_TYPE_UNUSED, },
    102 };
    103 
    104 /* Local prototypes */
    105 static int foundffs(struct data *, size_t);
    106 #ifdef USE_SYSVBFS
    107 static int foundsysvbfs(struct data *, size_t);
    108 #endif
    109 static int fsck_preen(const char *, int, const char *, bool silent);
    110 static void fixsb(const char *, const char *, char);
    111 static bool is_gpt(const char *);
    112 static int incoregpt(pm_devs_t *, partinfo *);
    113 
    114 
    115 static bool tmpfs_on_var_shm(void);
    116 
    117 const char *
    118 getfslabelname(uint8_t f)
    119 {
    120 	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 > 16UL*1024UL*1024UL;
    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, int fd)
    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 	int error;
    235 
    236 	memset(&inqbuf, 0, sizeof(inqbuf));
    237 	memset(&cmd, 0, sizeof(cmd));
    238 	memset(&req, 0, sizeof(req));
    239 
    240 	cmd.opcode = INQUIRY;
    241 	cmd.length = sizeof(inqbuf);
    242 	memcpy(req.cmd, &cmd, sizeof(cmd));
    243 	req.cmdlen = sizeof(cmd);
    244 	req.databuf = &inqbuf;
    245 	req.datalen = sizeof(inqbuf);
    246 	req.timeout = 10000;
    247 	req.flags = SCCMD_READ;
    248 	req.senselen = SENSEBUFLEN;
    249 
    250 	error = ioctl(fd, SCIOCCOMMAND, &req);
    251 	if (error == -1 || req.retsts != SCCMD_OK)
    252 		return 0;
    253 
    254 	scsi_strvis(vendor, sizeof(vendor), inqbuf.vendor,
    255 	    sizeof(inqbuf.vendor));
    256 	scsi_strvis(product, sizeof(product), inqbuf.product,
    257 	    sizeof(inqbuf.product));
    258 	scsi_strvis(revision, sizeof(revision), inqbuf.revision,
    259 	    sizeof(inqbuf.revision));
    260 
    261 	humanize_number(size, sizeof(size),
    262 	    (uint64_t)dd->dd_secsize * (uint64_t)dd->dd_totsec,
    263 	    "", HN_AUTOSCALE, HN_B | HN_NOSPACE | HN_DECIMAL);
    264 
    265 	snprintf(dd->dd_descr, sizeof(dd->dd_descr),
    266 	    "%s (%s, %s %s)",
    267 	    dd->dd_name, size, vendor, product);
    268 
    269 	return 1;
    270 }
    271 
    272 static int
    273 get_descr_ata(struct disk_desc *dd, int fd)
    274 {
    275 	struct atareq req;
    276 	static union {
    277 		unsigned char inbuf[DEV_BSIZE];
    278 		struct ataparams inqbuf;
    279 	} inbuf;
    280 	struct ataparams *inqbuf = &inbuf.inqbuf;
    281 	char model[sizeof(inqbuf->atap_model)+1];
    282 	char size[5];
    283 	int error, needswap = 0;
    284 
    285 	memset(&inbuf, 0, sizeof(inbuf));
    286 	memset(&req, 0, sizeof(req));
    287 
    288 	req.flags = ATACMD_READ;
    289 	req.command = WDCC_IDENTIFY;
    290 	req.databuf = (void *)&inbuf;
    291 	req.datalen = sizeof(inbuf);
    292 	req.timeout = 1000;
    293 
    294 	error = ioctl(fd, ATAIOCCOMMAND, &req);
    295 	if (error == -1 || req.retsts != ATACMD_OK)
    296 		return 0;
    297 
    298 #if BYTE_ORDER == LITTLE_ENDIAN
    299 	/*
    300 	 * On little endian machines, we need to shuffle the string
    301 	 * byte order.  However, we don't have to do this for NEC or
    302 	 * Mitsumi ATAPI devices
    303 	 */
    304 
    305 	if (!(inqbuf->atap_config != WDC_CFG_CFA_MAGIC &&
    306 	      (inqbuf->atap_config & WDC_CFG_ATAPI) &&
    307 	      ((inqbuf->atap_model[0] == 'N' &&
    308 	        inqbuf->atap_model[1] == 'E') ||
    309 	       (inqbuf->atap_model[0] == 'F' &&
    310 	        inqbuf->atap_model[1] == 'X')))) {
    311 		needswap = 1;
    312 	}
    313 #endif
    314 
    315 	ata_extract_string(model, sizeof(model),
    316 	    inqbuf->atap_model, sizeof(inqbuf->atap_model), needswap);
    317 	humanize_number(size, sizeof(size),
    318 	    (uint64_t)dd->dd_secsize * (uint64_t)dd->dd_totsec,
    319 	    "", HN_AUTOSCALE, HN_B | HN_NOSPACE | HN_DECIMAL);
    320 
    321 	snprintf(dd->dd_descr, sizeof(dd->dd_descr), "%s (%s, %s)",
    322 	    dd->dd_name, size, model);
    323 
    324 	return 1;
    325 }
    326 
    327 static void
    328 get_descr(struct disk_desc *dd)
    329 {
    330 	char diskpath[MAXPATHLEN];
    331 	int fd = -1;
    332 
    333 	fd = opendisk(dd->dd_name, O_RDONLY, diskpath, sizeof(diskpath), 0);
    334 	if (fd < 0)
    335 		goto done;
    336 
    337 	dd->dd_descr[0] = '\0';
    338 
    339 	/* try ATA */
    340 	if (get_descr_ata(dd, fd))
    341 		goto done;
    342 	/* try SCSI */
    343 	if (get_descr_scsi(dd, fd))
    344 		goto done;
    345 	/* XXX: get description from raid, cgd, vnd... */
    346 
    347 done:
    348 	if (fd >= 0)
    349 		close(fd);
    350 	if (strlen(dd->dd_descr) == 0)
    351 		strcpy(dd->dd_descr, dd->dd_name);
    352 }
    353 
    354 /*
    355  * State for helper callback for get_default_cdrom
    356  */
    357 struct default_cdrom_data {
    358 	char *device;
    359 	size_t max_len;
    360 	bool found;
    361 };
    362 
    363 /*
    364  * Helper function for get_default_cdrom, gets passed a device
    365  * name and a void pointer to default_cdrom_data.
    366  */
    367 static bool
    368 get_default_cdrom_helper(void *state, const char *dev)
    369 {
    370 	struct default_cdrom_data *data = state;
    371 
    372 	if (!is_cdrom_device(dev, false))
    373 		return true;
    374 
    375 	strlcpy(data->device, dev, data->max_len);
    376 	strlcat(data->device, "a", data->max_len); /* default to partition a */
    377 	data->found = true;
    378 
    379 	return false;	/* one is enough, stop iteration */
    380 }
    381 
    382 /*
    383  * Set the argument to the name of the first CD devices actually
    384  * available, leave it unmodified otherwise.
    385  * Return true if a device has been found.
    386  */
    387 bool
    388 get_default_cdrom(char *cd, size_t max_len)
    389 {
    390 	struct default_cdrom_data state;
    391 
    392 	state.device = cd;
    393 	state.max_len = max_len;
    394 	state.found = false;
    395 
    396 	if (enumerate_disks(&state, get_default_cdrom_helper))
    397 		return state.found;
    398 
    399 	return false;
    400 }
    401 
    402 static void
    403 get_wedge_descr(struct disk_desc *dd)
    404 {
    405 	struct dkwedge_info dkw;
    406 	char buf[MAXPATHLEN];
    407 	int fd;
    408 
    409 	fd = opendisk(dd->dd_name, O_RDONLY, buf, sizeof(buf), 0);
    410 	if (fd == -1)
    411 		return;
    412 
    413 	if (ioctl(fd, DIOCGWEDGEINFO, &dkw) == 0) {
    414 		fprintf(stderr, "device %s\n", dd->dd_name);
    415 		sprintf(dd->dd_descr, "%s (%s@%s)",
    416 		    dkw.dkw_wname, dkw.dkw_devname, dkw.dkw_parent);
    417 	}
    418 	close(fd);
    419 }
    420 
    421 static bool
    422 get_name_and_parent(const char *dev, char *name, char *parent)
    423 {
    424 	struct dkwedge_info dkw;
    425 	char buf[MAXPATHLEN];
    426 	int fd;
    427 	bool res = false;
    428 
    429 	fd = opendisk(dev, O_RDONLY, buf, sizeof(buf), 0);
    430 	if (fd == -1)
    431 		return false;
    432 
    433 	if (ioctl(fd, DIOCGWEDGEINFO, &dkw) == 0) {
    434 		strcpy(name, (const char *)dkw.dkw_wname);
    435 		strcpy(parent, dkw.dkw_parent);
    436 		res = true;
    437 	}
    438 	close(fd);
    439 	return res;
    440 }
    441 
    442 static bool
    443 find_swap_part_on(const char *dev, char *swap_name)
    444 {
    445 	struct dkwedge_info *dkw;
    446 	struct dkwedge_list dkwl;
    447 	char buf[MAXPATHLEN];
    448 	size_t bufsize;
    449 	int fd;
    450 	u_int i;
    451 	bool res = false;
    452 
    453 	dkw = NULL;
    454 	dkwl.dkwl_buf = dkw;
    455 	dkwl.dkwl_bufsize = 0;
    456 
    457 	fd = opendisk(dev, O_RDONLY, buf, sizeof(buf), 0);
    458 	if (fd == -1)
    459 		return false;
    460 
    461 	for (;;) {
    462 		if (ioctl(fd, DIOCLWEDGES, &dkwl) == -1) {
    463 			dkwl.dkwl_ncopied = 0;
    464 			break;
    465 		}
    466 		if (dkwl.dkwl_nwedges == dkwl.dkwl_ncopied)
    467 			break;
    468 		bufsize = dkwl.dkwl_nwedges * sizeof(*dkw);
    469 		if (dkwl.dkwl_bufsize < bufsize) {
    470 			dkw = realloc(dkwl.dkwl_buf, bufsize);
    471 			if (dkw == NULL)
    472 				break;
    473 			dkwl.dkwl_buf = dkw;
    474 			dkwl.dkwl_bufsize = bufsize;
    475 		}
    476 	}
    477 
    478 	for (i = 0; i < dkwl.dkwl_nwedges; i++) {
    479 		res = strcmp(dkw[i].dkw_ptype, DKW_PTYPE_SWAP) == 0;
    480 		if (res) {
    481 			strcpy(swap_name, (const char*)dkw[i].dkw_wname);
    482 			break;
    483 		}
    484 	}
    485 
    486 	close(fd);
    487 
    488 	return res;
    489 }
    490 
    491 static bool
    492 is_ffs_wedge(const char *dev)
    493 {
    494 	struct dkwedge_info dkw;
    495 	char buf[MAXPATHLEN];
    496 	int fd;
    497 	bool res;
    498 
    499 	fd = opendisk(dev, O_RDONLY, buf, sizeof(buf), 0);
    500 	if (fd == -1)
    501 		return false;
    502 
    503 	if (ioctl(fd, DIOCGWEDGEINFO, &dkw) == -1)
    504 		return false;
    505 
    506 	res = strcmp(dkw.dkw_ptype, DKW_PTYPE_FFS) == 0;
    507 	close(fd);
    508 
    509 	return res;
    510 }
    511 
    512 /*
    513  * Does this device match an entry in our default CDROM device list?
    514  * If looking for install targets, we also flag floopy devices.
    515  */
    516 bool
    517 is_cdrom_device(const char *dev, bool as_target)
    518 {
    519 	static const char *target_devices[] = {
    520 #ifdef CD_NAMES
    521 		CD_NAMES
    522 #endif
    523 #if defined(CD_NAMES) && defined(FLOPPY_NAMES)
    524 		,
    525 #endif
    526 #ifdef FLOPPY_NAMES
    527 		FLOPPY_NAMES
    528 #endif
    529 #if defined(CD_NAMES) || defined(FLOPPY_NAMES)
    530 		,
    531 #endif
    532 		0
    533 	};
    534 	static const char *src_devices[] = {
    535 #ifdef CD_NAMES
    536 		CD_NAMES ,
    537 #endif
    538 		0
    539 	};
    540 
    541 	for (const char **dev_pat = as_target ? target_devices : src_devices;
    542 	     *dev_pat; dev_pat++)
    543 		if (fnmatch(*dev_pat, dev, 0) == 0)
    544 			return true;
    545 
    546 	return false;
    547 }
    548 
    549 /*
    550  * Multi-purpose helper function:
    551  * iterate all known disks, invoke a callback for each.
    552  * Stop iteration when the callback returns false.
    553  * Return true when iteration actually happend, false on error.
    554  */
    555 bool
    556 enumerate_disks(void *state, bool (*func)(void *state, const char *dev))
    557 {
    558 	static const int mib[] = { CTL_HW, HW_DISKNAMES };
    559 	static const unsigned int miblen = __arraycount(mib);
    560 	const char *xd;
    561 	char *disk_names;
    562 	size_t len;
    563 
    564 	if (sysctl(mib, miblen, NULL, &len, NULL, 0) == -1)
    565 		return false;
    566 
    567 	disk_names = malloc(len);
    568 	if (disk_names == NULL)
    569 		return false;
    570 
    571 	if (sysctl(mib, miblen, disk_names, &len, NULL, 0) == -1) {
    572 		free(disk_names);
    573 		return false;
    574 	}
    575 
    576 	for (xd = strtok(disk_names, " "); xd != NULL; xd = strtok(NULL, " ")) {
    577 		if (!(*func)(state, xd))
    578 			break;
    579 	}
    580 	free(disk_names);
    581 
    582 	return true;
    583 }
    584 
    585 /*
    586  * Helper state for get_disks
    587  */
    588 struct get_disks_state {
    589 	int numdisks;
    590 	struct disk_desc *dd;
    591 	bool with_non_partitionable;
    592 };
    593 
    594 /*
    595  * Helper function for get_disks enumartion
    596  */
    597 static bool
    598 get_disks_helper(void *arg, const char *dev)
    599 {
    600 	struct get_disks_state *state = arg;
    601 	struct disklabel l;
    602 
    603 	/* is this a CD device? */
    604 	if (is_cdrom_device(dev, true))
    605 		return true;
    606 
    607 	strlcpy(state->dd->dd_name, dev, sizeof state->dd->dd_name - 2);
    608 	state->dd->dd_no_mbr = false;
    609 	state->dd->dd_no_part = false;
    610 
    611 	if (strncmp(dev, "dk", 2) == 0) {
    612 		char *endp;
    613 		int e;
    614 
    615 		/* if this device is dkNNNN, no partitioning is possible */
    616 		strtou(dev+2, &endp, 10, 0, INT_MAX, &e);
    617 		if (endp && *endp == 0 && e == 0)
    618 			state->dd->dd_no_part = true;
    619 	}
    620 	if (state->dd->dd_no_part && !state->with_non_partitionable)
    621 		return true;
    622 
    623 	if (!get_geom(state->dd->dd_name, &l)) {
    624 		if (errno == ENOENT)
    625 			return true;
    626 		if (errno != ENOTTY || !state->dd->dd_no_part)
    627 			/*
    628 			 * Allow plain partitions,
    629 			 * like already existing wedges
    630 			 * (like dk0) if marked as
    631 			 * non-partitioning device.
    632 			 * For all other cases, continue
    633 			 * with the next disk.
    634 			 */
    635 			return true;
    636 		if (!is_ffs_wedge(state->dd->dd_name))
    637 			return true;
    638 	}
    639 
    640 	/*
    641 	 * Exclude a disk mounted as root partition,
    642 	 * in case of install-image on a USB memstick.
    643 	 */
    644 	if (is_active_rootpart(state->dd->dd_name,
    645 	    state->dd->dd_no_part ? -1 : 0))
    646 		return true;
    647 
    648 	if (!state->dd->dd_no_part) {
    649 		state->dd->dd_cyl = l.d_ncylinders;
    650 		state->dd->dd_head = l.d_ntracks;
    651 		state->dd->dd_sec = l.d_nsectors;
    652 		state->dd->dd_secsize = l.d_secsize;
    653 		state->dd->dd_totsec = l.d_secperunit;
    654 	}
    655 	if (state->dd->dd_no_part)
    656 		get_wedge_descr(state->dd);
    657 	else
    658 		get_descr(state->dd);
    659 	state->dd++;
    660 	state->numdisks++;
    661 	if (state->numdisks == MAX_DISKS)
    662 		return false;
    663 
    664 	return true;
    665 }
    666 
    667 /*
    668  * Get all disk devices that are not CDs.
    669  * Optionally leave out those that can not be partitioned further.
    670  */
    671 static int
    672 get_disks(struct disk_desc *dd, bool with_non_partitionable)
    673 {
    674 	struct get_disks_state state;
    675 
    676 	/* initialize */
    677 	state.numdisks = 0;
    678 	state.dd = dd;
    679 	state.with_non_partitionable = with_non_partitionable;
    680 
    681 	if (enumerate_disks(&state, get_disks_helper))
    682 		return state.numdisks;
    683 
    684 	return 0;
    685 }
    686 
    687 int
    688 find_disks(const char *doingwhat)
    689 {
    690 	struct disk_desc disks[MAX_DISKS];
    691 	menu_ent dsk_menu[nelem(disks) + 1]; // + 1 for extended partitioning entry
    692 	struct disk_desc *disk;
    693 	int i = 0, skipped = 0;
    694 	int already_found, numdisks, selected_disk = -1;
    695 	int menu_no;
    696 	pm_devs_t *pm_i, *pm_last = NULL;
    697 
    698 	/* Find disks. */
    699 	numdisks = get_disks(disks, partman_go <= 0);
    700 
    701 	/* need a redraw here, kernel messages hose everything */
    702 	touchwin(stdscr);
    703 	refresh();
    704 	/* Kill typeahead, it won't be what the user had in mind */
    705 	fpurge(stdin);
    706 
    707 	/*
    708 	 * partman_go: <0 - we want to see menu with extended partitioning
    709 	 *            ==0 - we want to see simple select disk menu
    710 	 *             >0 - we do not want to see any menus, just detect
    711 	 *                  all disks
    712 	 */
    713 	if (partman_go <= 0) {
    714 		if (numdisks == 0) {
    715 			/* No disks found! */
    716 			msg_display(MSG_nodisk);
    717 			process_menu(MENU_ok, NULL);
    718 			/*endwin();*/
    719 			return -1;
    720 		} else {
    721 			/* One or more disks found! */
    722 			for (i = 0; i < numdisks; i++) {
    723 				dsk_menu[i].opt_name =
    724 				    disks[i].dd_descr;
    725 				dsk_menu[i].opt_menu = OPT_NOMENU;
    726 				dsk_menu[i].opt_flags = OPT_EXIT;
    727 				dsk_menu[i].opt_action = set_menu_select;
    728 			}
    729 			if (partman_go < 0) {
    730 				dsk_menu[i].opt_name = MSG_partman;
    731 				dsk_menu[i].opt_menu = OPT_NOMENU;
    732 				dsk_menu[i].opt_flags = OPT_EXIT;
    733 				dsk_menu[i].opt_action = set_menu_select;
    734 			}
    735 			menu_no = new_menu(MSG_Available_disks,
    736 				dsk_menu, numdisks
    737 				 + ((partman_go<0)?1:0), -1,
    738 				 4, 0, 0, MC_SCROLL,
    739 				NULL, NULL, NULL, NULL, NULL);
    740 			if (menu_no == -1)
    741 				return -1;
    742 			msg_display(MSG_ask_disk, doingwhat);
    743 			process_menu(menu_no, &selected_disk);
    744 			free_menu(menu_no);
    745 		}
    746 		if (partman_go < 0 && selected_disk == numdisks) {
    747 			partman_go = 1;
    748 			return -2;
    749 		} else
    750 			partman_go = 0;
    751 		if (selected_disk < 0 || selected_disk >= numdisks)
    752 			return -1;
    753 	}
    754 
    755 	/* Fill pm struct with device(s) info */
    756 	for (i = 0; i < numdisks; i++) {
    757 		if (! partman_go)
    758 			disk = disks + selected_disk;
    759 		else {
    760 			disk = disks + i;
    761 			already_found = 0;
    762 			SLIST_FOREACH(pm_i, &pm_head, l) {
    763 				pm_last = pm_i;
    764 				if (!already_found &&
    765 				    strcmp(pm_i->diskdev, disk->dd_name) == 0) {
    766 					pm_i->found = 1;
    767 					break;
    768 				}
    769 			}
    770 			if (pm_i != NULL && pm_i->found)
    771 				/* We already added this device, skipping */
    772 				continue;
    773 		}
    774 		pm = pm_new;
    775 		pm->found = 1;
    776 		pm->bootable = 0;
    777 		pm->pi.menu_no = -1;
    778 		pm->disktype = "unknown";
    779 		pm->doessf = "";
    780 		strlcpy(pm->diskdev, disk->dd_name, sizeof pm->diskdev);
    781 		strlcpy(pm->diskdev_descr, disk->dd_descr, sizeof pm->diskdev_descr);
    782 		/* Use as a default disk if the user has the sets on a local disk */
    783 		strlcpy(localfs_dev, disk->dd_name, sizeof localfs_dev);
    784 
    785 		pm->gpt = is_gpt(pm->diskdev);
    786 		pm->no_mbr = disk->dd_no_mbr || pm->gpt;
    787 		pm->no_part = disk->dd_no_part;
    788 		if (!pm->no_part) {
    789 			pm->sectorsize = disk->dd_secsize;
    790 			pm->dlcyl = disk->dd_cyl;
    791 			pm->dlhead = disk->dd_head;
    792 			pm->dlsec = disk->dd_sec;
    793 			pm->dlsize = disk->dd_totsec;
    794 			if (pm->dlsize == 0)
    795 				pm->dlsize = disk->dd_cyl * disk->dd_head * disk->dd_sec;
    796 			if (pm->dlsize > UINT32_MAX && ! partman_go) {
    797 				if (logfp)
    798 					fprintf(logfp, "Cannot process disk %s: too big size (%d)\n",
    799 						pm->diskdev, (int)pm->dlsize);
    800 				msg_display(MSG_toobigdisklabel);
    801 				process_menu(MENU_ok, NULL);
    802 				return -1;
    803 			}
    804 		} else {
    805 			pm->sectorsize = 0;
    806 			pm->dlcyl = 0;
    807 			pm->dlhead = 0;
    808 			pm->dlsec = 0;
    809 			pm->dlsize = 0;
    810 			pm->rootpart = -1;
    811 			pm->no_mbr = 1;
    812 			memset(&pm->bsdlabel, 0, sizeof(pm->bsdlabel));
    813 		}
    814 		pm->dlcylsize = pm->dlhead * pm->dlsec;
    815 
    816 		label_read();
    817 		if (partman_go) {
    818 			pm_getrefdev(pm_new);
    819 			if (SLIST_EMPTY(&pm_head) || pm_last == NULL)
    820 				 SLIST_INSERT_HEAD(&pm_head, pm_new, l);
    821 			else
    822 				 SLIST_INSERT_AFTER(pm_last, pm_new, l);
    823 			pm_new = malloc(sizeof (pm_devs_t));
    824 			memset(pm_new, 0, sizeof *pm_new);
    825 		} else
    826 			/* We is not in partman and do not want to process all devices, exit */
    827 			break;
    828 	}
    829 
    830 	return numdisks-skipped;
    831 }
    832 
    833 
    834 void
    835 label_read(void)
    836 {
    837 
    838 	if (pm->no_part)
    839 		return;
    840 
    841 	check_available_binaries();
    842 
    843 	/* Get existing/default label */
    844 	memset(&pm->oldlabel, 0, sizeof pm->oldlabel);
    845 	if (!have_gpt || !pm->gpt)
    846 		incorelabel(pm->diskdev, pm->oldlabel);
    847 	else
    848 		incoregpt(pm, pm->oldlabel);
    849 	/* Set 'target' label to current label in case we don't change it */
    850 	memcpy(&pm->bsdlabel, &pm->oldlabel, sizeof pm->bsdlabel);
    851 #ifndef NO_DISKLABEL
    852 	if (! pm->gpt)
    853 		savenewlabel(pm->oldlabel, getmaxpartitions());
    854 #endif
    855 }
    856 
    857 void
    858 fmt_fspart(menudesc *m, int ptn, void *arg)
    859 {
    860 	unsigned int poffset, psize, pend;
    861 	const char *desc;
    862 	static const char *Yes;
    863 	partinfo *p = pm->bsdlabel + ptn;
    864 
    865 	if (Yes == NULL)
    866 		Yes = msg_string(MSG_Yes);
    867 
    868 	poffset = p->pi_offset / sizemult;
    869 	psize = p->pi_size / sizemult;
    870 	if (psize == 0)
    871 		pend = 0;
    872 	else
    873 		pend = (p->pi_offset + p->pi_size) / sizemult - 1;
    874 
    875 	if (p->pi_fstype == FS_BSDFFS)
    876 		if (p->pi_flags & PIF_FFSv2)
    877 			desc = "FFSv2";
    878 		else
    879 			desc = "FFSv1";
    880 	else
    881 		desc = getfslabelname(p->pi_fstype);
    882 
    883 #ifdef PART_BOOT
    884 	if (ptn == PART_BOOT)
    885 		desc = msg_string(MSG_Boot_partition_cant_change);
    886 #endif
    887 	if (ptn == getrawpartition())
    888 		desc = msg_string(MSG_Whole_disk_cant_change);
    889 	else {
    890 		if (ptn == PART_C)
    891 			desc = msg_string(MSG_NetBSD_partition_cant_change);
    892 	}
    893 
    894 	wprintw(m->mw, msg_string(MSG_fspart_row),
    895 			poffset, pend, psize, desc,
    896 			p->pi_flags & PIF_NEWFS ? Yes : "",
    897 			p->pi_flags & PIF_MOUNT ? Yes : "",
    898 			p->pi_mount);
    899 }
    900 
    901 /*
    902  * Label a disk using an MD-specific string DISKLABEL_CMD for
    903  * to invoke disklabel.
    904  * if MD code does not define DISKLABEL_CMD, this is a no-op.
    905  *
    906  * i386 port uses "/sbin/disklabel -w -r", just like i386
    907  * miniroot scripts, though this may leave a bogus incore label.
    908  *
    909  * Sun ports should use DISKLABEL_CMD "/sbin/disklabel -w"
    910  * to get incore to ondisk inode translation for the Sun proms.
    911  */
    912 int
    913 write_disklabel (void)
    914 {
    915 	int rv = 0;
    916 
    917 	if (pm && pm->no_part)
    918 		return 0;
    919 
    920 #ifdef DISKLABEL_CMD
    921 	/* disklabel the disk */
    922 	rv = run_program(RUN_DISPLAY, "%s -f /tmp/disktab %s '%s'",
    923 	    DISKLABEL_CMD, pm->diskdev, pm->bsddiskname);
    924 	if (rv == 0)
    925 		update_wedges(pm->diskdev);
    926 #endif
    927 	return rv;
    928 }
    929 
    930 
    931 static int
    932 ptn_sort(const void *a, const void *b)
    933 {
    934 	return strcmp(pm->bsdlabel[*(const int *)a].pi_mount,
    935 		      pm->bsdlabel[*(const int *)b].pi_mount);
    936 }
    937 
    938 int
    939 make_filesystems(void)
    940 {
    941 	unsigned int i;
    942 	int ptn;
    943 	int ptn_order[nelem(pm->bsdlabel)];
    944 	int error = 0;
    945 	unsigned int maxpart = getmaxpartitions();
    946 	char *newfs = NULL, *dev = NULL, *devdev = NULL;
    947 	partinfo *lbl;
    948 
    949 	if (pm->no_part) {
    950 		/* check if this target device already has a ffs */
    951 		error = fsck_preen(pm->diskdev, -1, "ffs", true);
    952 		if (error) {
    953 			if (!ask_noyes(MSG_No_filesystem_newfs))
    954 				return EINVAL;
    955 			error = run_program(RUN_DISPLAY | RUN_PROGRESS,
    956 			    "/sbin/newfs -V2 -O2 /dev/r%s", pm->diskdev);
    957 		}
    958 
    959 		md_pre_mount();
    960 
    961 		make_target_dir("/");
    962 		asprintf(&devdev, "/dev/%s", pm->diskdev);
    963 		if (devdev == NULL)
    964 			return (ENOMEM);
    965 		error = target_mount_do("-o async", devdev, "/");
    966 		if (error) {
    967 			msg_display(MSG_mountfail, devdev, ' ',
    968 			    "/");
    969 			process_menu(MENU_ok, NULL);
    970 		}
    971 		free(devdev);
    972 		return error;
    973 	}
    974 
    975 	if (maxpart > nelem(pm->bsdlabel))
    976 		maxpart = nelem(pm->bsdlabel);
    977 
    978 	/* Making new file systems and mounting them */
    979 
    980 	/* sort to ensure /usr/local is mounted after /usr (etc) */
    981 	for (i = 0; i < maxpart; i++)
    982 		ptn_order[i] = i;
    983 	qsort(ptn_order, maxpart, sizeof ptn_order[0], ptn_sort);
    984 
    985 	for (i = 0; i < maxpart; i++) {
    986 		/*
    987 		 * newfs and mount. For now, process only BSD filesystems.
    988 		 * but if this is the mounted-on root, has no mount
    989 		 * point defined, or is marked preserve, don't touch it!
    990 		 */
    991 		ptn = ptn_order[i];
    992 		lbl = pm->bsdlabel + ptn;
    993 
    994 		if (is_active_rootpart(pm->diskdev, ptn))
    995 			continue;
    996 
    997 		if (*lbl->pi_mount == 0)
    998 			/* No mount point */
    999 			continue;
   1000 
   1001 		if (pm->isspecial) {
   1002 			asprintf(&dev, "%s", pm->diskdev);
   1003 			ptn = 0 - 'a';
   1004 		} else {
   1005 			asprintf(&dev, "%s%c", pm->diskdev, 'a' + ptn);
   1006 		}
   1007 		if (dev == NULL)
   1008 			return (ENOMEM);
   1009 		asprintf(&devdev, "/dev/%s", dev);
   1010 		if (devdev == NULL)
   1011 			return (ENOMEM);
   1012 
   1013 		newfs = NULL;
   1014 		lbl->mnt_opts = NULL;
   1015 		lbl->fsname = NULL;
   1016 		switch (lbl->pi_fstype) {
   1017 		case FS_APPLEUFS:
   1018 			asprintf(&newfs, "/sbin/newfs %s%.0d",
   1019 				lbl->pi_isize != 0 ? "-i" : "", lbl->pi_isize);
   1020 			lbl->mnt_opts = "-tffs -o async";
   1021 			lbl->fsname = "ffs";
   1022 			break;
   1023 		case FS_BSDFFS:
   1024 			asprintf(&newfs,
   1025 			    "/sbin/newfs -V2 -O %d -b %d -f %d%s%.0d",
   1026 			    lbl->pi_flags & PIF_FFSv2 ? 2 : 1,
   1027 			    lbl->pi_fsize * lbl->pi_frag, lbl->pi_fsize,
   1028 			    lbl->pi_isize != 0 ? " -i " : "", lbl->pi_isize);
   1029 			if (lbl->pi_flags & PIF_LOG)
   1030 				lbl->mnt_opts = "-tffs -o log";
   1031 			else
   1032 				lbl->mnt_opts = "-tffs -o async";
   1033 			lbl->fsname = "ffs";
   1034 			break;
   1035 		case FS_BSDLFS:
   1036 			asprintf(&newfs, "/sbin/newfs_lfs -b %d",
   1037 				lbl->pi_fsize * lbl->pi_frag);
   1038 			lbl->mnt_opts = "-tlfs";
   1039 			lbl->fsname = "lfs";
   1040 			break;
   1041 		case FS_MSDOS:
   1042 #ifdef USE_NEWFS_MSDOS
   1043 			asprintf(&newfs, "/sbin/newfs_msdos");
   1044 #endif
   1045 			lbl->mnt_opts = "-tmsdos";
   1046 			lbl->fsname = "msdos";
   1047 			break;
   1048 #ifdef USE_SYSVBFS
   1049 		case FS_SYSVBFS:
   1050 			asprintf(&newfs, "/sbin/newfs_sysvbfs");
   1051 			lbl->mnt_opts = "-tsysvbfs";
   1052 			lbl->fsname = "sysvbfs";
   1053 			break;
   1054 #endif
   1055 #ifdef USE_EXT2FS
   1056 		case FS_EX2FS:
   1057 			asprintf(&newfs, "/sbin/newfs_ext2fs");
   1058 			lbl->mnt_opts = "-text2fs";
   1059 			lbl->fsname = "ext2fs";
   1060 			break;
   1061 #endif
   1062 		}
   1063 		if (lbl->pi_flags & PIF_NEWFS && newfs != NULL) {
   1064 #ifdef USE_NEWFS_MSDOS
   1065 			if (lbl->pi_fstype == FS_MSDOS) {
   1066 			        /* newfs only if mount fails */
   1067 			        if (run_program(RUN_SILENT | RUN_ERROR_OK,
   1068 				    "mount -rt msdos /dev/%s /mnt2", dev) != 0)
   1069 					error = run_program(
   1070 					    RUN_DISPLAY | RUN_PROGRESS,
   1071 					    "%s /dev/r%s",
   1072 					    newfs, dev);
   1073 				else {
   1074 					run_program(RUN_SILENT | RUN_ERROR_OK,
   1075 					    "umount /mnt2");
   1076 					error = 0;
   1077 				}
   1078 			} else
   1079 #endif
   1080 			error = run_program(RUN_DISPLAY | RUN_PROGRESS,
   1081 			    "%s /dev/r%s", newfs, dev);
   1082 		} else {
   1083 			/* We'd better check it isn't dirty */
   1084 			error = fsck_preen(pm->diskdev, ptn, lbl->fsname, false);
   1085 		}
   1086 		free(newfs);
   1087 		if (error != 0) {
   1088 			free(devdev);
   1089 			free(dev);
   1090 			return error;
   1091 		}
   1092 
   1093 		lbl->pi_flags ^= PIF_NEWFS;
   1094 		md_pre_mount();
   1095 
   1096 		if (partman_go == 0 && lbl->pi_flags & PIF_MOUNT &&
   1097 				lbl->mnt_opts != NULL) {
   1098 			make_target_dir(lbl->pi_mount);
   1099 			error = target_mount_do(lbl->mnt_opts, devdev, lbl->pi_mount);
   1100 			if (error) {
   1101 				msg_display(MSG_mountfail, dev, ' ', lbl->pi_mount);
   1102 				process_menu(MENU_ok, NULL);
   1103 				free(devdev);
   1104 				free(dev);
   1105 				return error;
   1106 			}
   1107 		}
   1108 		free(devdev);
   1109 		free(dev);
   1110 	}
   1111 	return 0;
   1112 }
   1113 
   1114 int
   1115 make_fstab(void)
   1116 {
   1117 	FILE *f;
   1118 	int i, swap_dev = -1;
   1119 	const char *dump_dev;
   1120 	char *dev = NULL;
   1121 	pm_devs_t *pm_i;
   1122 #ifndef HAVE_TMPFS
   1123 	pm_devs_t *pm_with_swap = NULL;
   1124 #endif
   1125 
   1126 	/* Create the fstab. */
   1127 	make_target_dir("/etc");
   1128 	f = target_fopen("/etc/fstab", "w");
   1129 	scripting_fprintf(NULL, "cat <<EOF >%s/etc/fstab\n", target_prefix());
   1130 
   1131 	if (logfp)
   1132 		(void)fprintf(logfp,
   1133 		    "Making %s/etc/fstab (%s).\n", target_prefix(), pm->diskdev);
   1134 
   1135 	if (f == NULL) {
   1136 		msg_display(MSG_createfstab);
   1137 		if (logfp)
   1138 			(void)fprintf(logfp, "Failed to make /etc/fstab!\n");
   1139 		process_menu(MENU_ok, NULL);
   1140 #ifndef DEBUG
   1141 		return 1;
   1142 #else
   1143 		f = stdout;
   1144 #endif
   1145 	}
   1146 
   1147 	scripting_fprintf(f, "# NetBSD /etc/fstab\n# See /usr/share/examples/"
   1148 			"fstab/ for more examples.\n");
   1149 
   1150 	if (pm->no_part) {
   1151 		/* single dk? target */
   1152 		char buf[200], parent[200], swap[200], *prompt;
   1153 		int res;
   1154 
   1155 		if (!get_name_and_parent(pm->diskdev, buf, parent))
   1156 			goto done_with_disks;
   1157 		scripting_fprintf(f, "NAME=%s\t/\tffs\trw\t\t1 1\n",
   1158 		    buf);
   1159 		if (!find_swap_part_on(parent, swap))
   1160 			goto done_with_disks;
   1161 		asprintf(&prompt, msg_string(MSG_Auto_add_swap_part),
   1162 		    swap, parent);
   1163 		res = ask_yesno(prompt);
   1164 		free(prompt);
   1165 		if (res)
   1166 			scripting_fprintf(f, "NAME=%s\tnone"
   1167 			    "\tswap\tsw,dp\t\t0 0\n", swap);
   1168 		goto done_with_disks;
   1169 	}
   1170 
   1171 	if (! partman_go) {
   1172 		/* We want to process only one disk... */
   1173 		pm_i = pm;
   1174 		goto onlyonediskinfstab;
   1175 	}
   1176 	SLIST_FOREACH(pm_i, &pm_head, l) {
   1177 		onlyonediskinfstab:
   1178 		for (i = 0; i < getmaxpartitions(); i++) {
   1179 			const char *s = "";
   1180 			const char *mp = pm_i->bsdlabel[i].pi_mount;
   1181 			const char *fstype = "ffs";
   1182 			int fsck_pass = 0, dump_freq = 0;
   1183 
   1184 			if (dev != NULL)
   1185 				free(dev);
   1186 			if (pm_i->isspecial)
   1187 				asprintf(&dev, "%s", pm_i->diskdev);
   1188 			else
   1189 				asprintf(&dev, "%s%c", pm_i->diskdev, 'a' + i);
   1190 			if (dev == NULL)
   1191 				return (ENOMEM);
   1192 
   1193 			if (!*mp) {
   1194 				/*
   1195 				 * No mount point specified, comment out line and
   1196 				 * use /mnt as a placeholder for the mount point.
   1197 				 */
   1198 				s = "# ";
   1199 				mp = "/mnt";
   1200 			}
   1201 
   1202 			switch (pm_i->bsdlabel[i].pi_fstype) {
   1203 			case FS_UNUSED:
   1204 				continue;
   1205 			case FS_BSDLFS:
   1206 				/* If there is no LFS, just comment it out. */
   1207 				if (!check_lfs_progs())
   1208 					s = "# ";
   1209 				fstype = "lfs";
   1210 				/* FALLTHROUGH */
   1211 			case FS_BSDFFS:
   1212 				fsck_pass = (strcmp(mp, "/") == 0) ? 1 : 2;
   1213 				dump_freq = 1;
   1214 				break;
   1215 			case FS_MSDOS:
   1216 				fstype = "msdos";
   1217 				break;
   1218 			case FS_SWAP:
   1219 				if (pm_i->isspecial)
   1220 					continue;
   1221 				if (swap_dev == -1) {
   1222 					swap_dev = i;
   1223 					dump_dev = ",dp";
   1224 #ifndef HAVE_TMPFS
   1225 					pm_with_swap = pm_i;
   1226 #endif
   1227 				} else {
   1228 					dump_dev = "";
   1229 				}
   1230 				scripting_fprintf(f, "/dev/%s\t\tnone\tswap\tsw%s\t\t 0 0\n",
   1231 					dev, dump_dev);
   1232 				continue;
   1233 #ifdef USE_SYSVBFS
   1234 			case FS_SYSVBFS:
   1235 				fstype = "sysvbfs";
   1236 				make_target_dir("/stand");
   1237 				break;
   1238 #endif
   1239 			default:
   1240 				fstype = "???";
   1241 				s = "# ";
   1242 				break;
   1243 			}
   1244 			/* The code that remounts root rw doesn't check the partition */
   1245 			if (strcmp(mp, "/") == 0 && !(pm_i->bsdlabel[i].pi_flags & PIF_MOUNT))
   1246 				s = "# ";
   1247 
   1248 	 		scripting_fprintf(f,
   1249 			  "%s/dev/%s\t\t%s\t%s\trw%s%s%s%s%s%s%s%s\t\t %d %d\n",
   1250 			   s, dev, mp, fstype,
   1251 			   pm_i->bsdlabel[i].pi_flags & PIF_LOG ? ",log" : "",
   1252 			   pm_i->bsdlabel[i].pi_flags & PIF_MOUNT ? "" : ",noauto",
   1253 			   pm_i->bsdlabel[i].pi_flags & PIF_ASYNC ? ",async" : "",
   1254 			   pm_i->bsdlabel[i].pi_flags & PIF_NOATIME ? ",noatime" : "",
   1255 			   pm_i->bsdlabel[i].pi_flags & PIF_NODEV ? ",nodev" : "",
   1256 			   pm_i->bsdlabel[i].pi_flags & PIF_NODEVMTIME ? ",nodevmtime" : "",
   1257 			   pm_i->bsdlabel[i].pi_flags & PIF_NOEXEC ? ",noexec" : "",
   1258 			   pm_i->bsdlabel[i].pi_flags & PIF_NOSUID ? ",nosuid" : "",
   1259 			   dump_freq, fsck_pass);
   1260 	 		if (pm_i->isspecial)
   1261 	 			/* Special device (such as dk*) have only one partition */
   1262 	 			break;
   1263 		}
   1264 		/* Simple install, only one disk */
   1265 		if (!partman_go)
   1266 			break;
   1267 	}
   1268 done_with_disks:
   1269 	if (tmp_ramdisk_size != 0) {
   1270 #ifdef HAVE_TMPFS
   1271 		scripting_fprintf(f, "tmpfs\t\t/tmp\ttmpfs\trw,-m=1777,-s=%"
   1272 		    PRIi64 "\n",
   1273 		    tmp_ramdisk_size * 512);
   1274 #else
   1275 		if (swap_dev != -1 && pm_with_swap != NULL)
   1276 			scripting_fprintf(f, "/dev/%s%c\t\t/tmp\tmfs\trw,-s=%"
   1277 			    PRIi64 "\n",
   1278 			    pm_with_swap->diskdev, 'a' + swap_dev, tmp_ramdisk_size);
   1279 		else
   1280 			scripting_fprintf(f, "swap\t\t/tmp\tmfs\trw,-s=%"
   1281 			    PRIi64 "\n",
   1282 			    tmp_ramdisk_size);
   1283 #endif
   1284 	}
   1285 
   1286 	if (cdrom_dev[0] == 0)
   1287 		get_default_cdrom(cdrom_dev, sizeof(cdrom_dev));
   1288 
   1289 	/* Add /kern, /proc and /dev/pts to fstab and make mountpoint. */
   1290 	scripting_fprintf(f, "kernfs\t\t/kern\tkernfs\trw\n");
   1291 	scripting_fprintf(f, "ptyfs\t\t/dev/pts\tptyfs\trw\n");
   1292 	scripting_fprintf(f, "procfs\t\t/proc\tprocfs\trw\n");
   1293 	scripting_fprintf(f, "/dev/%s\t\t/cdrom\tcd9660\tro,noauto\n",
   1294 	    cdrom_dev);
   1295 	scripting_fprintf(f, "%stmpfs\t\t/var/shm\ttmpfs\trw,-m1777,-sram%%25\n",
   1296 	    tmpfs_on_var_shm() ? "" : "#");
   1297 	make_target_dir("/kern");
   1298 	make_target_dir("/proc");
   1299 	make_target_dir("/dev/pts");
   1300 	make_target_dir("/cdrom");
   1301 	make_target_dir("/var/shm");
   1302 
   1303 	scripting_fprintf(NULL, "EOF\n");
   1304 
   1305 	if (dev != NULL)
   1306 		free(dev);
   1307 	fclose(f);
   1308 	fflush(NULL);
   1309 	return 0;
   1310 }
   1311 
   1312 
   1313 
   1314 static int
   1315 /*ARGSUSED*/
   1316 foundffs(struct data *list, size_t num)
   1317 {
   1318 	int error;
   1319 
   1320 	if (num < 2 || strcmp(list[1].u.s_val, "/") == 0 ||
   1321 	    strstr(list[2].u.s_val, "noauto") != NULL)
   1322 		return 0;
   1323 
   1324 	error = fsck_preen(list[0].u.s_val, ' '-'a', "ffs", false);
   1325 	if (error != 0)
   1326 		return error;
   1327 
   1328 	error = target_mount("", list[0].u.s_val, ' '-'a', list[1].u.s_val);
   1329 	if (error != 0) {
   1330 		msg_display(MSG_mount_failed, list[0].u.s_val);
   1331 		if (!ask_noyes(NULL))
   1332 			return error;
   1333 	}
   1334 	return 0;
   1335 }
   1336 
   1337 #ifdef USE_SYSVBFS
   1338 static int
   1339 /*ARGSUSED*/
   1340 foundsysvbfs(struct data *list, size_t num)
   1341 {
   1342 	int error;
   1343 
   1344 	if (num < 2 || strcmp(list[1].u.s_val, "/") == 0 ||
   1345 	    strstr(list[2].u.s_val, "noauto") != NULL)
   1346 		return 0;
   1347 
   1348 	error = target_mount("", list[0].u.s_val, ' '-'a', list[1].u.s_val);
   1349 	if (error != 0)
   1350 		return error;
   1351 	return 0;
   1352 }
   1353 #endif
   1354 
   1355 /*
   1356  * Do an fsck. On failure, inform the user by showing a warning
   1357  * message and doing menu_ok() before proceeding.
   1358  * Returns 0 on success, or nonzero return code from fsck() on failure.
   1359  */
   1360 static int
   1361 fsck_preen(const char *disk, int ptn, const char *fsname, bool silent)
   1362 {
   1363 	char *prog;
   1364 	int error;
   1365 
   1366 	ptn = (ptn < 0)? 0 : 'a' + ptn;
   1367 	if (fsname == NULL)
   1368 		return 0;
   1369 	/* first, check if fsck program exists, if not, assume ok */
   1370 	asprintf(&prog, "/sbin/fsck_%s", fsname);
   1371 	if (prog == NULL)
   1372 		return 0;
   1373 	if (access(prog, X_OK) != 0) {
   1374 		free(prog);
   1375 		return 0;
   1376 	}
   1377 	if (!strcmp(fsname,"ffs"))
   1378 		fixsb(prog, disk, ptn);
   1379 	error = run_program(silent? RUN_SILENT|RUN_ERROR_OK : 0, "%s -p -q /dev/r%s%c", prog, disk, ptn);
   1380 	free(prog);
   1381 	if (error != 0 && !silent) {
   1382 		msg_display(MSG_badfs, disk, ptn, error);
   1383 		if (ask_noyes(NULL))
   1384 			error = 0;
   1385 		/* XXX at this point maybe we should run a full fsck? */
   1386 	}
   1387 	return error;
   1388 }
   1389 
   1390 /* This performs the same function as the etc/rc.d/fixsb script
   1391  * which attempts to correct problems with ffs1 filesystems
   1392  * which may have been introduced by booting a netbsd-current kernel
   1393  * from between April of 2003 and January 2004. For more information
   1394  * This script was developed as a response to NetBSD pr install/25138
   1395  * Additional prs regarding the original issue include:
   1396  *  bin/17910 kern/21283 kern/21404 port-macppc/23925 port-macppc/23926
   1397  */
   1398 static void
   1399 fixsb(const char *prog, const char *disk, char ptn)
   1400 {
   1401 	int fd;
   1402 	int rval;
   1403 	union {
   1404 		struct fs fs;
   1405 		char buf[SBLOCKSIZE];
   1406 	} sblk;
   1407 	struct fs *fs = &sblk.fs;
   1408 
   1409 	snprintf(sblk.buf, sizeof(sblk.buf), "/dev/r%s%c",
   1410 		disk, ptn == ' ' ? 0 : ptn);
   1411 	fd = open(sblk.buf, O_RDONLY);
   1412 	if (fd == -1)
   1413 		return;
   1414 
   1415 	/* Read ffsv1 main superblock */
   1416 	rval = pread(fd, sblk.buf, sizeof sblk.buf, SBLOCK_UFS1);
   1417 	close(fd);
   1418 	if (rval != sizeof sblk.buf)
   1419 		return;
   1420 
   1421 	if (fs->fs_magic != FS_UFS1_MAGIC &&
   1422 	    fs->fs_magic != FS_UFS1_MAGIC_SWAPPED)
   1423 		/* Not FFSv1 */
   1424 		return;
   1425 	if (fs->fs_old_flags & FS_FLAGS_UPDATED)
   1426 		/* properly updated fslevel 4 */
   1427 		return;
   1428 	if (fs->fs_bsize != fs->fs_maxbsize)
   1429 		/* not messed up */
   1430 		return;
   1431 
   1432 	/*
   1433 	 * OK we have a munged fs, first 'upgrade' to fslevel 4,
   1434 	 * We specify -b16 in order to stop fsck bleating that the
   1435 	 * sb doesn't match the first alternate.
   1436 	 */
   1437 	run_program(RUN_DISPLAY | RUN_PROGRESS,
   1438 	    "%s -p -b 16 -c 4 /dev/r%s%c", prog, disk, ptn);
   1439 	/* Then downgrade to fslevel 3 */
   1440 	run_program(RUN_DISPLAY | RUN_PROGRESS,
   1441 	    "%s -p -c 3 /dev/r%s%c", prog, disk, ptn);
   1442 }
   1443 
   1444 /*
   1445  * fsck and mount the root partition.
   1446  */
   1447 static int
   1448 mount_root(void)
   1449 {
   1450 	int	error;
   1451 	int ptn = (pm->isspecial)? 0 - 'a' : pm->rootpart;
   1452 
   1453 	error = fsck_preen(pm->diskdev, ptn, "ffs", false);
   1454 	if (error != 0)
   1455 		return error;
   1456 
   1457 	md_pre_mount();
   1458 
   1459 	/* Mount /dev/<diskdev>a on target's "".
   1460 	 * If we pass "" as mount-on, Prefixing will DTRT.
   1461 	 * for now, use no options.
   1462 	 * XXX consider -o remount in case target root is
   1463 	 * current root, still readonly from single-user?
   1464 	 */
   1465 	return target_mount("", pm->diskdev, ptn, "");
   1466 }
   1467 
   1468 /* Get information on the file systems mounted from the root filesystem.
   1469  * Offer to convert them into 4.4BSD inodes if they are not 4.4BSD
   1470  * inodes.  Fsck them.  Mount them.
   1471  */
   1472 
   1473 int
   1474 mount_disks(void)
   1475 {
   1476 	char *fstab;
   1477 	int   fstabsize;
   1478 	int   error;
   1479 
   1480 	static struct lookfor fstabbuf[] = {
   1481 		{"/dev/", "/dev/%s %s ffs %s", "c", NULL, 0, 0, foundffs},
   1482 		{"/dev/", "/dev/%s %s ufs %s", "c", NULL, 0, 0, foundffs},
   1483 #ifdef USE_SYSVBFS
   1484 		{"/dev/", "/dev/%s %s sysvbfs %s", "c", NULL, 0, 0,
   1485 		    foundsysvbfs},
   1486 #endif
   1487 	};
   1488 	static size_t numfstabbuf = sizeof(fstabbuf) / sizeof(struct lookfor);
   1489 
   1490 	/* First the root device. */
   1491 	if (target_already_root())
   1492 		/* avoid needing to call target_already_root() again */
   1493 		targetroot_mnt[0] = 0;
   1494 	else {
   1495 		error = mount_root();
   1496 		if (error != 0 && error != EBUSY)
   1497 			return -1;
   1498 	}
   1499 
   1500 	/* Check the target /etc/fstab exists before trying to parse it. */
   1501 	if (target_dir_exists_p("/etc") == 0 ||
   1502 	    target_file_exists_p("/etc/fstab") == 0) {
   1503 		msg_display(MSG_noetcfstab, pm->diskdev);
   1504 		process_menu(MENU_ok, NULL);
   1505 		return -1;
   1506 	}
   1507 
   1508 
   1509 	/* Get fstab entries from the target-root /etc/fstab. */
   1510 	fstabsize = target_collect_file(T_FILE, &fstab, "/etc/fstab");
   1511 	if (fstabsize < 0) {
   1512 		/* error ! */
   1513 		msg_display(MSG_badetcfstab, pm->diskdev);
   1514 		process_menu(MENU_ok, NULL);
   1515 		return -2;
   1516 	}
   1517 	error = walk(fstab, (size_t)fstabsize, fstabbuf, numfstabbuf);
   1518 	free(fstab);
   1519 
   1520 	return error;
   1521 }
   1522 
   1523 int
   1524 set_swap_if_low_ram(const char *disk, partinfo *pp)
   1525 {
   1526 	if (get_ramsize() <= 32)
   1527 		return set_swap(disk, pp);
   1528 	return 0;
   1529 }
   1530 
   1531 int
   1532 set_swap(const char *disk, partinfo *pp)
   1533 {
   1534 	int i;
   1535 	char *cp;
   1536 	int rval;
   1537 
   1538 	if (pp == NULL)
   1539 		pp = pm->oldlabel;
   1540 
   1541 	for (i = 0; i < MAXPARTITIONS; i++) {
   1542 		if (pp[i].pi_fstype != FS_SWAP)
   1543 			continue;
   1544 		asprintf(&cp, "/dev/%s%c", disk, 'a' + i);
   1545 		rval = swapctl(SWAP_ON, cp, 0);
   1546 		free(cp);
   1547 		if (rval != 0)
   1548 			return -1;
   1549 	}
   1550 
   1551 	return 0;
   1552 }
   1553 
   1554 int
   1555 check_swap(const char *disk, int remove_swap)
   1556 {
   1557 	struct swapent *swap;
   1558 	char *cp;
   1559 	int nswap;
   1560 	int l;
   1561 	int rval = 0;
   1562 
   1563 	nswap = swapctl(SWAP_NSWAP, 0, 0);
   1564 	if (nswap <= 0)
   1565 		return 0;
   1566 
   1567 	swap = malloc(nswap * sizeof *swap);
   1568 	if (swap == NULL)
   1569 		return -1;
   1570 
   1571 	nswap = swapctl(SWAP_STATS, swap, nswap);
   1572 	if (nswap < 0)
   1573 		goto bad_swap;
   1574 
   1575 	l = strlen(disk);
   1576 	while (--nswap >= 0) {
   1577 		/* Should we check the se_dev or se_path? */
   1578 		cp = swap[nswap].se_path;
   1579 		if (memcmp(cp, "/dev/", 5) != 0)
   1580 			continue;
   1581 		if (memcmp(cp + 5, disk, l) != 0)
   1582 			continue;
   1583 		if (!isalpha(*(unsigned char *)(cp + 5 + l)))
   1584 			continue;
   1585 		if (cp[5 + l + 1] != 0)
   1586 			continue;
   1587 		/* ok path looks like it is for this device */
   1588 		if (!remove_swap) {
   1589 			/* count active swap areas */
   1590 			rval++;
   1591 			continue;
   1592 		}
   1593 		if (swapctl(SWAP_OFF, cp, 0) == -1)
   1594 			rval = -1;
   1595 	}
   1596 
   1597     done:
   1598 	free(swap);
   1599 	return rval;
   1600 
   1601     bad_swap:
   1602 	rval = -1;
   1603 	goto done;
   1604 }
   1605 
   1606 #ifdef HAVE_BOOTXX_xFS
   1607 char *
   1608 bootxx_name(void)
   1609 {
   1610 	int fstype;
   1611 	const char *bootxxname;
   1612 	char *bootxx;
   1613 
   1614 	/* check we have boot code for the root partition type */
   1615 	fstype = pm->bsdlabel[pm->rootpart].pi_fstype;
   1616 	switch (fstype) {
   1617 #if defined(BOOTXX_FFSV1) || defined(BOOTXX_FFSV2)
   1618 	case FS_BSDFFS:
   1619 		if (pm->bsdlabel[pm->rootpart].pi_flags & PIF_FFSv2) {
   1620 #ifdef BOOTXX_FFSV2
   1621 			bootxxname = BOOTXX_FFSV2;
   1622 #else
   1623 			bootxxname = NULL;
   1624 #endif
   1625 		} else {
   1626 #ifdef BOOTXX_FFSV1
   1627 			bootxxname = BOOTXX_FFSV1;
   1628 #else
   1629 			bootxxname = NULL;
   1630 #endif
   1631 		}
   1632 		break;
   1633 #endif
   1634 #ifdef BOOTXX_LFSV2
   1635 	case FS_BSDLFS:
   1636 		bootxxname = BOOTXX_LFSV2;
   1637 		break;
   1638 #endif
   1639 	default:
   1640 		bootxxname = NULL;
   1641 		break;
   1642 	}
   1643 
   1644 	if (bootxxname == NULL)
   1645 		return NULL;
   1646 
   1647 	asprintf(&bootxx, "%s/%s", BOOTXXDIR, bootxxname);
   1648 	return bootxx;
   1649 }
   1650 #endif
   1651 
   1652 static int
   1653 get_fsid_by_gptuuid(const char *str)
   1654 {
   1655 	int i;
   1656 	uuid_t uuid;
   1657 	uint32_t status;
   1658 
   1659 	uuid_from_string(str, &uuid, &status);
   1660 	if (status == uuid_s_ok) {
   1661 		for (i = 0; gpt_filesystems[i].id > 0; i++)
   1662 			if (uuid_equal(&uuid, &(gpt_filesystems[i].uuid), NULL))
   1663 				return gpt_filesystems[i].id;
   1664 	}
   1665 	return FS_OTHER;
   1666 }
   1667 
   1668 const char *
   1669 get_gptfs_by_id(int filesystem)
   1670 {
   1671 	int i;
   1672 	for (i = 0; gpt_filesystems[i].id > 0; i++)
   1673 		if (filesystem == gpt_filesystems[i].id)
   1674 			return gpt_filesystems[i].name;
   1675 	return NULL;
   1676 }
   1677 
   1678 /* from dkctl.c */
   1679 static int
   1680 get_dkwedges_sort(const void *a, const void *b)
   1681 {
   1682 	const struct dkwedge_info *dkwa = a, *dkwb = b;
   1683 	const daddr_t oa = dkwa->dkw_offset, ob = dkwb->dkw_offset;
   1684 	return (oa < ob) ? -1 : (oa > ob) ? 1 : 0;
   1685 }
   1686 
   1687 int
   1688 get_dkwedges(struct dkwedge_info **dkw, const char *diskdev)
   1689 {
   1690 	int fd;
   1691 	char buf[STRSIZE];
   1692 	size_t bufsize;
   1693 	struct dkwedge_list dkwl;
   1694 
   1695 	*dkw = NULL;
   1696 	dkwl.dkwl_buf = *dkw;
   1697 	dkwl.dkwl_bufsize = 0;
   1698 	fd = opendisk(diskdev, O_RDONLY, buf, STRSIZE, 0);
   1699 	if (fd < 0)
   1700 		return -1;
   1701 
   1702 	for (;;) {
   1703 		if (ioctl(fd, DIOCLWEDGES, &dkwl) == -1)
   1704 			return -2;
   1705 		if (dkwl.dkwl_nwedges == dkwl.dkwl_ncopied)
   1706 			break;
   1707 		bufsize = dkwl.dkwl_nwedges * sizeof(**dkw);
   1708 		if (dkwl.dkwl_bufsize < bufsize) {
   1709 			*dkw = realloc(dkwl.dkwl_buf, bufsize);
   1710 			if (*dkw == NULL)
   1711 				return -3;
   1712 			dkwl.dkwl_buf = *dkw;
   1713 			dkwl.dkwl_bufsize = bufsize;
   1714 		}
   1715 	}
   1716 
   1717 	if (dkwl.dkwl_nwedges > 0 && *dkw != NULL)
   1718 		qsort(*dkw, dkwl.dkwl_nwedges, sizeof(**dkw), get_dkwedges_sort);
   1719 
   1720 	close(fd);
   1721 	return dkwl.dkwl_nwedges;
   1722 }
   1723 
   1724 /* XXX: rewrite */
   1725 static int
   1726 incoregpt(pm_devs_t *pm_cur, partinfo *lp)
   1727 {
   1728 	int i, num;
   1729 	unsigned int p_num;
   1730 	uint64_t p_start, p_size;
   1731 	char *textbuf, *t, *tt, p_type[STRSIZE];
   1732 	struct dkwedge_info *dkw;
   1733 
   1734 	num = get_dkwedges(&dkw, pm_cur->diskdev);
   1735 	if (dkw != NULL) {
   1736 		for (i = 0; i < num && i < MAX_WEDGES; i++)
   1737 			run_program(RUN_SILENT, "dkctl %s delwedge %s",
   1738 				pm_cur->diskdev, dkw[i].dkw_devname);
   1739 		free (dkw);
   1740 	}
   1741 
   1742 	if (collect(T_OUTPUT, &textbuf, "gpt show -u %s 2>/dev/null", pm_cur->diskdev) < 1)
   1743 		return -1;
   1744 
   1745 	(void)strtok(textbuf, "\n"); /* ignore first line */
   1746 	while ((t = strtok(NULL, "\n")) != NULL) {
   1747 		i = 0; p_start = 0; p_size = 0; p_num = 0; strcpy(p_type, ""); /* init */
   1748 		while ((tt = strsep(&t, " \t")) != NULL) {
   1749 			if (strlen(tt) == 0)
   1750 				continue;
   1751 			if (i == 0)
   1752 				p_start = strtouq(tt, NULL, 10);
   1753 			if (i == 1)
   1754 				p_size = strtouq(tt, NULL, 10);
   1755 			if (i == 2)
   1756 				p_num = strtouq(tt, NULL, 10);
   1757 			if (i > 2 || (i == 2 && p_num == 0))
   1758 				if (
   1759 					strcmp(tt, "GPT") &&
   1760 					strcmp(tt, "part") &&
   1761 					strcmp(tt, "-")
   1762 					)
   1763 						strlcat(p_type, tt, STRSIZE);
   1764 			i++;
   1765 		}
   1766 		if (p_start == 0 || p_size == 0)
   1767 			continue;
   1768 		else if (! strcmp(p_type, "Pritable"))
   1769 			pm_cur->ptstart = p_start + p_size;
   1770 		else if (! strcmp(p_type, "Sectable"))
   1771 			pm_cur->ptsize = p_start - pm_cur->ptstart - 1;
   1772 		else if (p_num == 0 && strlen(p_type) > 0)
   1773 			/* Utilitary entry (PMBR, etc) */
   1774 			continue;
   1775 		else if (p_num == 0) {
   1776 			/* Free space */
   1777 			continue;
   1778 		} else {
   1779 			/* Usual partition */
   1780 			lp[p_num].pi_size = p_size;
   1781 			lp[p_num].pi_offset = p_start;
   1782 			lp[p_num].pi_fstype = get_fsid_by_gptuuid(p_type);
   1783 		}
   1784 	}
   1785 	free(textbuf);
   1786 
   1787 	return 0;
   1788 }
   1789 
   1790 static bool
   1791 is_gpt(const char *dev)
   1792 {
   1793 
   1794 	check_available_binaries();
   1795 
   1796 	if (!have_gpt)
   1797 		return false;
   1798 
   1799 	return run_program(RUN_SILENT | RUN_ERROR_OK,
   1800 		"gpt -qr header %s", dev) == 0;
   1801 }
   1802