Home | History | Annotate | Line # | Download | only in sysinst
disks.c revision 1.14
      1 /*	$NetBSD: disks.c,v 1.14 2018/05/01 09:01:45 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 <stdio.h>
     40 #include <stdlib.h>
     41 #include <unistd.h>
     42 #include <fcntl.h>
     43 #include <util.h>
     44 #include <uuid.h>
     45 
     46 #include <sys/param.h>
     47 #include <sys/sysctl.h>
     48 #include <sys/swap.h>
     49 #include <ufs/ufs/dinode.h>
     50 #include <ufs/ffs/fs.h>
     51 #define FSTYPENAMES
     52 #include <sys/disklabel.h>
     53 #include <sys/disklabel_gpt.h>
     54 
     55 #include <dev/scsipi/scsipi_all.h>
     56 #include <sys/scsiio.h>
     57 
     58 #include <dev/ata/atareg.h>
     59 #include <sys/ataio.h>
     60 
     61 #include "defs.h"
     62 #include "md.h"
     63 #include "msg_defs.h"
     64 #include "menu_defs.h"
     65 #include "txtwalk.h"
     66 
     67 /* Disk descriptions */
     68 struct disk_desc {
     69 	char	dd_name[SSTRSIZE];
     70 	char	dd_descr[70];
     71 	uint	dd_no_mbr;
     72 	uint	dd_cyl;
     73 	uint	dd_head;
     74 	uint	dd_sec;
     75 	uint	dd_secsize;
     76 	uint	dd_totsec;
     77 };
     78 
     79 /* gpt(8) use different filesystem names.
     80    So, we cant use ./common/lib/libutil/getfstypename.c */
     81 struct gptfs_t {
     82     const char *name;
     83     int id;
     84     uuid_t uuid;
     85 };
     86 static const struct gptfs_t gpt_filesystems[] = {
     87     { "swap", FS_SWAP, GPT_ENT_TYPE_NETBSD_SWAP, },
     88     { "ffs", FS_BSDFFS, GPT_ENT_TYPE_NETBSD_FFS, },
     89     { "lfs", FS_BSDLFS, GPT_ENT_TYPE_NETBSD_LFS, },
     90     { "linux", FS_EX2FS, GPT_ENT_TYPE_LINUX_DATA, },
     91     { "windows,", FS_MSDOS, GPT_ENT_TYPE_MS_BASIC_DATA, },
     92     { "hfs", FS_HFS, GPT_ENT_TYPE_APPLE_HFS, },
     93     { "ufs", FS_OTHER, GPT_ENT_TYPE_APPLE_UFS, },
     94     { "ccd", FS_CCD, GPT_ENT_TYPE_NETBSD_CCD, },
     95     { "raid", FS_RAID, GPT_ENT_TYPE_NETBSD_RAIDFRAME, },
     96     { "cgd", FS_CGD, GPT_ENT_TYPE_NETBSD_CGD, },
     97     { "efi", FS_OTHER, GPT_ENT_TYPE_EFI, },
     98     { "bios", FS_OTHER, GPT_ENT_TYPE_BIOS, },
     99     { NULL, -1, GPT_ENT_TYPE_UNUSED, },
    100 };
    101 
    102 /* Local prototypes */
    103 static int foundffs(struct data *, size_t);
    104 #ifdef USE_SYSVBFS
    105 static int foundsysvbfs(struct data *, size_t);
    106 #endif
    107 static int fsck_preen(const char *, int, const char *);
    108 static void fixsb(const char *, const char *, char);
    109 static bool is_gpt(const char *);
    110 static int incoregpt(pm_devs_t *, partinfo *);
    111 
    112 #ifndef DISK_NAMES
    113 #define DISK_NAMES "wd", "sd", "ld", "raid"
    114 #endif
    115 
    116 static const char *disk_names[] = { DISK_NAMES, "vnd", "cgd", NULL };
    117 
    118 static bool tmpfs_on_var_shm(void);
    119 
    120 const char *
    121 getfslabelname(uint8_t f)
    122 {
    123 	if (f >= __arraycount(fstypenames) || fstypenames[f] == NULL)
    124 		return "invalid";
    125 	return fstypenames[f];
    126 }
    127 
    128 /*
    129  * Decide wether we want to mount a tmpfs on /var/shm: we do this always
    130  * when the machine has more than 16 MB of user memory. On smaller machines,
    131  * shm_open() and friends will not perform well anyway.
    132  */
    133 static bool
    134 tmpfs_on_var_shm()
    135 {
    136 	uint64_t ram;
    137 	size_t len;
    138 
    139 	len = sizeof(ram);
    140 	if (sysctlbyname("hw.usermem64", &ram, &len, NULL, 0))
    141 		return false;
    142 
    143 	return ram > 16UL*1024UL*1024UL;
    144 }
    145 
    146 /* from src/sbin/atactl/atactl.c
    147  * extract_string: copy a block of bytes out of ataparams and make
    148  * a proper string out of it, truncating trailing spaces and preserving
    149  * strict typing. And also, not doing unaligned accesses.
    150  */
    151 static void
    152 ata_extract_string(char *buf, size_t bufmax,
    153 		   uint8_t *bytes, unsigned numbytes,
    154 		   int needswap)
    155 {
    156 	unsigned i;
    157 	size_t j;
    158 	unsigned char ch1, ch2;
    159 
    160 	for (i = 0, j = 0; i < numbytes; i += 2) {
    161 		ch1 = bytes[i];
    162 		ch2 = bytes[i+1];
    163 		if (needswap && j < bufmax-1) {
    164 			buf[j++] = ch2;
    165 		}
    166 		if (j < bufmax-1) {
    167 			buf[j++] = ch1;
    168 		}
    169 		if (!needswap && j < bufmax-1) {
    170 			buf[j++] = ch2;
    171 		}
    172 	}
    173 	while (j > 0 && buf[j-1] == ' ') {
    174 		j--;
    175 	}
    176 	buf[j] = '\0';
    177 }
    178 
    179 /*
    180  * from src/sbin/scsictl/scsi_subr.c
    181  */
    182 #define STRVIS_ISWHITE(x) ((x) == ' ' || (x) == '\0' || (x) == (u_char)'\377')
    183 
    184 static void
    185 scsi_strvis(char *sdst, size_t dlen, const char *ssrc, size_t slen)
    186 {
    187 	u_char *dst = (u_char *)sdst;
    188 	const u_char *src = (const u_char *)ssrc;
    189 
    190 	/* Trim leading and trailing blanks and NULs. */
    191 	while (slen > 0 && STRVIS_ISWHITE(src[0]))
    192 		++src, --slen;
    193 	while (slen > 0 && STRVIS_ISWHITE(src[slen - 1]))
    194 		--slen;
    195 
    196 	while (slen > 0) {
    197 		if (*src < 0x20 || *src >= 0x80) {
    198 			/* non-printable characters */
    199 			dlen -= 4;
    200 			if (dlen < 1)
    201 				break;
    202 			*dst++ = '\\';
    203 			*dst++ = ((*src & 0300) >> 6) + '0';
    204 			*dst++ = ((*src & 0070) >> 3) + '0';
    205 			*dst++ = ((*src & 0007) >> 0) + '0';
    206 		} else if (*src == '\\') {
    207 			/* quote characters */
    208 			dlen -= 2;
    209 			if (dlen < 1)
    210 				break;
    211 			*dst++ = '\\';
    212 			*dst++ = '\\';
    213 		} else {
    214 			/* normal characters */
    215 			if (--dlen < 1)
    216 				break;
    217 			*dst++ = *src;
    218 		}
    219 		++src, --slen;
    220 	}
    221 
    222 	*dst++ = 0;
    223 }
    224 
    225 
    226 static int
    227 get_descr_scsi(struct disk_desc *dd, int fd)
    228 {
    229 	struct scsipi_inquiry_data inqbuf;
    230 	struct scsipi_inquiry cmd;
    231 	scsireq_t req;
    232         /* x4 in case every character is escaped, +1 for NUL. */
    233 	char vendor[(sizeof(inqbuf.vendor) * 4) + 1],
    234 	     product[(sizeof(inqbuf.product) * 4) + 1],
    235 	     revision[(sizeof(inqbuf.revision) * 4) + 1];
    236 	char size[5];
    237 	int error;
    238 
    239 	memset(&inqbuf, 0, sizeof(inqbuf));
    240 	memset(&cmd, 0, sizeof(cmd));
    241 	memset(&req, 0, sizeof(req));
    242 
    243 	cmd.opcode = INQUIRY;
    244 	cmd.length = sizeof(inqbuf);
    245 	memcpy(req.cmd, &cmd, sizeof(cmd));
    246 	req.cmdlen = sizeof(cmd);
    247 	req.databuf = &inqbuf;
    248 	req.datalen = sizeof(inqbuf);
    249 	req.timeout = 10000;
    250 	req.flags = SCCMD_READ;
    251 	req.senselen = SENSEBUFLEN;
    252 
    253 	error = ioctl(fd, SCIOCCOMMAND, &req);
    254 	if (error == -1 || req.retsts != SCCMD_OK)
    255 		return 0;
    256 
    257 	scsi_strvis(vendor, sizeof(vendor), inqbuf.vendor,
    258 	    sizeof(inqbuf.vendor));
    259 	scsi_strvis(product, sizeof(product), inqbuf.product,
    260 	    sizeof(inqbuf.product));
    261 	scsi_strvis(revision, sizeof(revision), inqbuf.revision,
    262 	    sizeof(inqbuf.revision));
    263 
    264 	humanize_number(size, sizeof(size),
    265 	    (uint64_t)dd->dd_secsize * (uint64_t)dd->dd_totsec,
    266 	    "", HN_AUTOSCALE, HN_B | HN_NOSPACE | HN_DECIMAL);
    267 
    268 	snprintf(dd->dd_descr, sizeof(dd->dd_descr),
    269 	    "%s (%s, %s %s)",
    270 	    dd->dd_name, size, vendor, product);
    271 
    272 	return 1;
    273 }
    274 
    275 static int
    276 get_descr_ata(struct disk_desc *dd, int fd)
    277 {
    278 	struct atareq req;
    279 	static union {
    280 		unsigned char inbuf[DEV_BSIZE];
    281 		struct ataparams inqbuf;
    282 	} inbuf;
    283 	struct ataparams *inqbuf = &inbuf.inqbuf;
    284 	char model[sizeof(inqbuf->atap_model)+1];
    285 	char size[5];
    286 	int error, needswap = 0;
    287 
    288 	memset(&inbuf, 0, sizeof(inbuf));
    289 	memset(&req, 0, sizeof(req));
    290 
    291 	req.flags = ATACMD_READ;
    292 	req.command = WDCC_IDENTIFY;
    293 	req.databuf = (void *)&inbuf;
    294 	req.datalen = sizeof(inbuf);
    295 	req.timeout = 1000;
    296 
    297 	error = ioctl(fd, ATAIOCCOMMAND, &req);
    298 	if (error == -1 || req.retsts != ATACMD_OK)
    299 		return 0;
    300 
    301 #if BYTE_ORDER == LITTLE_ENDIAN
    302 	/*
    303 	 * On little endian machines, we need to shuffle the string
    304 	 * byte order.  However, we don't have to do this for NEC or
    305 	 * Mitsumi ATAPI devices
    306 	 */
    307 
    308 	if (!(inqbuf->atap_config != WDC_CFG_CFA_MAGIC &&
    309 	      (inqbuf->atap_config & WDC_CFG_ATAPI) &&
    310 	      ((inqbuf->atap_model[0] == 'N' &&
    311 	        inqbuf->atap_model[1] == 'E') ||
    312 	       (inqbuf->atap_model[0] == 'F' &&
    313 	        inqbuf->atap_model[1] == 'X')))) {
    314 		needswap = 1;
    315 	}
    316 #endif
    317 
    318 	ata_extract_string(model, sizeof(model),
    319 	    inqbuf->atap_model, sizeof(inqbuf->atap_model), needswap);
    320 	humanize_number(size, sizeof(size),
    321 	    (uint64_t)dd->dd_secsize * (uint64_t)dd->dd_totsec,
    322 	    "", HN_AUTOSCALE, HN_B | HN_NOSPACE | HN_DECIMAL);
    323 
    324 	snprintf(dd->dd_descr, sizeof(dd->dd_descr), "%s (%s, %s)",
    325 	    dd->dd_name, size, model);
    326 
    327 	return 1;
    328 }
    329 
    330 static void
    331 get_descr(struct disk_desc *dd)
    332 {
    333 	char diskpath[MAXPATHLEN];
    334 	int fd = -1;
    335 
    336 	fd = opendisk(dd->dd_name, O_RDONLY, diskpath, sizeof(diskpath), 0);
    337 	if (fd < 0)
    338 		goto done;
    339 
    340 	dd->dd_descr[0] = '\0';
    341 
    342 	/* try ATA */
    343 	if (get_descr_ata(dd, fd))
    344 		goto done;
    345 	/* try SCSI */
    346 	if (get_descr_scsi(dd, fd))
    347 		goto done;
    348 	/* XXX: get description from raid, cgd, vnd... */
    349 
    350 done:
    351 	if (fd >= 0)
    352 		close(fd);
    353 	if (strlen(dd->dd_descr) == 0)
    354 		strcpy(dd->dd_descr, dd->dd_name);
    355 }
    356 
    357 /* disknames - contains device names without partition letters
    358  * cdrom_devices - contains devices including partition letters
    359  * returns the first entry in hw.disknames matching a cdrom_device, or
    360  * first entry on error or no match
    361  */
    362 const char *
    363 get_default_cdrom(void)
    364 {
    365 	static const char *cdrom_devices[] = { CD_NAMES, 0};
    366 	static const char mib_name[] = "hw.disknames";
    367 	size_t len;
    368 	char *disknames;
    369 	char *last;
    370 	char *name;
    371 	const char **arg;
    372 	const char *cd_dev;
    373 
    374 	/* On error just use first entry in cdrom_devices */
    375 	if (sysctlbyname(mib_name, NULL, &len, NULL, 0) == -1)
    376 		return cdrom_devices[0];
    377 	if ((disknames = malloc(len + 2)) == 0) /* skip on malloc fail */
    378 		return cdrom_devices[0];
    379 
    380 	(void)sysctlbyname(mib_name, disknames, &len, NULL, 0);
    381 	for ((name = strtok_r(disknames, " ", &last)); name;
    382 	    (name = strtok_r(NULL, " ", &last))) {
    383 		for (arg = cdrom_devices; *arg; ++arg) {
    384 			cd_dev = *arg;
    385 			/* skip unit and partition */
    386 			if (strncmp(cd_dev, name, strlen(cd_dev) - 2) != 0)
    387 				continue;
    388 			if (name != disknames)
    389 				strcpy(disknames, name);
    390 			strcat(disknames, "a");
    391 			/* XXX: leaks, but so what? */
    392 			return disknames;
    393 		}
    394 	}
    395 	free(disknames);
    396 	return cdrom_devices[0];
    397 }
    398 
    399 static int
    400 get_disks(struct disk_desc *dd)
    401 {
    402 	const char **xd;
    403 	char *cp;
    404 	struct disklabel l;
    405 	int i;
    406 	int numdisks;
    407 
    408 	/* initialize */
    409 	numdisks = 0;
    410 
    411 	for (xd = disk_names; *xd != NULL; xd++) {
    412 		for (i = 0; i < MAX_DISKS; i++) {
    413 			strlcpy(dd->dd_name, *xd, sizeof dd->dd_name - 2);
    414 			cp = strchr(dd->dd_name, ':');
    415 			if (cp != NULL)
    416 				dd->dd_no_mbr = !strcmp(cp, ":no_mbr");
    417 			else {
    418 				dd->dd_no_mbr = 0;
    419 				cp = strchr(dd->dd_name, 0);
    420 			}
    421 
    422 			snprintf(cp, 2 + 1, "%d", i);
    423 			if (!get_geom(dd->dd_name, &l)) {
    424 				if (errno == ENOENT)
    425 					break;
    426 				continue;
    427 			}
    428 
    429 			/*
    430 			 * Exclude a disk mounted as root partition,
    431 			 * in case of install-image on a USB memstick.
    432 			 */
    433 			if (is_active_rootpart(dd->dd_name, 0))
    434 				continue;
    435 
    436 			dd->dd_cyl = l.d_ncylinders;
    437 			dd->dd_head = l.d_ntracks;
    438 			dd->dd_sec = l.d_nsectors;
    439 			dd->dd_secsize = l.d_secsize;
    440 			dd->dd_totsec = l.d_secperunit;
    441 			get_descr(dd);
    442 			dd++;
    443 			numdisks++;
    444 			if (numdisks >= MAX_DISKS)
    445 				return numdisks;
    446 		}
    447 	}
    448 	return numdisks;
    449 }
    450 
    451 int
    452 find_disks(const char *doingwhat)
    453 {
    454 	struct disk_desc disks[MAX_DISKS];
    455 	menu_ent dsk_menu[nelem(disks) + 1]; // + 1 for extended partitioning entry
    456 	struct disk_desc *disk;
    457 	int i, already_found;
    458 	int numdisks, selected_disk = -1;
    459 	int menu_no;
    460 	pm_devs_t *pm_i, *pm_last = NULL;
    461 
    462 	/* Find disks. */
    463 	numdisks = get_disks(disks);
    464 
    465 	/* need a redraw here, kernel messages hose everything */
    466 	touchwin(stdscr);
    467 	refresh();
    468 	/* Kill typeahead, it won't be what the user had in mind */
    469 	fpurge(stdin);
    470 
    471 	/*
    472 	 * partman_go: <0 - we want to see menu with extended partitioning
    473 	 *            ==0 - we want to see simple select disk menu
    474 	 *             >0 - we do not want to see any menus, just detect
    475 	 *                  all disks
    476 	 */
    477 	if (partman_go <= 0) {
    478 		if (numdisks == 0) {
    479 			/* No disks found! */
    480 			msg_display(MSG_nodisk);
    481 			process_menu(MENU_ok, NULL);
    482 			/*endwin();*/
    483 			return -1;
    484 		} else {
    485 			/* One or more disks found! */
    486 			for (i = 0; i < numdisks; i++) {
    487 				dsk_menu[i].opt_name = disks[i].dd_descr;
    488 				dsk_menu[i].opt_menu = OPT_NOMENU;
    489 				dsk_menu[i].opt_flags = OPT_EXIT;
    490 				dsk_menu[i].opt_action = set_menu_select;
    491 			}
    492 			if (partman_go < 0) {
    493 				dsk_menu[i].opt_name = MSG_partman;
    494 				dsk_menu[i].opt_menu = OPT_NOMENU;
    495 				dsk_menu[i].opt_flags = OPT_EXIT;
    496 				dsk_menu[i].opt_action = set_menu_select;
    497 			}
    498 			menu_no = new_menu(MSG_Available_disks,
    499 				dsk_menu, numdisks + ((partman_go<0)?1:0), -1, 4, 0, 0, MC_SCROLL,
    500 				NULL, NULL, NULL, NULL, NULL);
    501 			if (menu_no == -1)
    502 				return -1;
    503 			msg_display(MSG_ask_disk, doingwhat);
    504 			process_menu(menu_no, &selected_disk);
    505 			free_menu(menu_no);
    506 		}
    507 		if (partman_go < 0 && selected_disk == numdisks) {
    508 			partman_go = 1;
    509 			return -2;
    510 		} else
    511 			partman_go = 0;
    512 		if (selected_disk < 0 || selected_disk >= numdisks)
    513 			return -1;
    514 	}
    515 
    516 	/* Fill pm struct with device(s) info */
    517 	for (i = 0; i < numdisks; i++) {
    518 		if (! partman_go)
    519 			disk = disks + selected_disk;
    520 		else {
    521 			disk = disks + i;
    522 			already_found = 0;
    523 			SLIST_FOREACH(pm_i, &pm_head, l) {
    524 				pm_last = pm_i;
    525 				if (!already_found &&
    526 				    strcmp(pm_i->diskdev, disk->dd_name) == 0) {
    527 					pm_i->found = 1;
    528 					break;
    529 				}
    530 			}
    531 			if (pm_i != NULL && pm_i->found)
    532 				/* We already added this device, skipping */
    533 				continue;
    534 		}
    535 		pm = pm_new;
    536 		pm->found = 1;
    537 		pm->bootable = 0;
    538 		pm->pi.menu_no = -1;
    539 		pm->disktype = "unknown";
    540 		pm->doessf = "";
    541 		strlcpy(pm->diskdev, disk->dd_name, sizeof pm->diskdev);
    542 		strlcpy(pm->diskdev_descr, disk->dd_descr, sizeof pm->diskdev_descr);
    543 		/* Use as a default disk if the user has the sets on a local disk */
    544 		strlcpy(localfs_dev, disk->dd_name, sizeof localfs_dev);
    545 
    546 		pm->gpt = is_gpt(pm->diskdev);
    547 		pm->no_mbr = disk->dd_no_mbr || pm->gpt;
    548 		pm->sectorsize = disk->dd_secsize;
    549 		pm->dlcyl = disk->dd_cyl;
    550 		pm->dlhead = disk->dd_head;
    551 		pm->dlsec = disk->dd_sec;
    552 		pm->dlsize = disk->dd_totsec;
    553 		if (pm->dlsize == 0)
    554 			pm->dlsize = disk->dd_cyl * disk->dd_head * disk->dd_sec;
    555 		if (pm->dlsize > UINT32_MAX && ! partman_go) {
    556 			if (logfp)
    557 				fprintf(logfp, "Cannot process disk %s: too big size (%d)\n",
    558 					pm->diskdev, (int)pm->dlsize);
    559 			msg_display(MSG_toobigdisklabel);
    560 			process_menu(MENU_ok, NULL);
    561 			return -1;
    562 		}
    563 		pm->dlcylsize = pm->dlhead * pm->dlsec;
    564 
    565 		label_read();
    566 		if (partman_go) {
    567 			pm_getrefdev(pm_new);
    568 			if (SLIST_EMPTY(&pm_head) || pm_last == NULL)
    569 				 SLIST_INSERT_HEAD(&pm_head, pm_new, l);
    570 			else
    571 				 SLIST_INSERT_AFTER(pm_last, pm_new, l);
    572 			pm_new = malloc(sizeof (pm_devs_t));
    573 			memset(pm_new, 0, sizeof *pm_new);
    574 		} else
    575 			/* We is not in partman and do not want to process all devices, exit */
    576 			break;
    577 	}
    578 
    579 	return numdisks;
    580 }
    581 
    582 
    583 void
    584 label_read(void)
    585 {
    586 	check_available_binaries();
    587 
    588 	/* Get existing/default label */
    589 	memset(&pm->oldlabel, 0, sizeof pm->oldlabel);
    590 	if (!have_gpt || !pm->gpt)
    591 		incorelabel(pm->diskdev, pm->oldlabel);
    592 	else
    593 		incoregpt(pm, pm->oldlabel);
    594 	/* Set 'target' label to current label in case we don't change it */
    595 	memcpy(&pm->bsdlabel, &pm->oldlabel, sizeof pm->bsdlabel);
    596 #ifndef NO_DISKLABEL
    597 	if (! pm->gpt)
    598 		savenewlabel(pm->oldlabel, getmaxpartitions());
    599 #endif
    600 }
    601 
    602 void
    603 fmt_fspart(menudesc *m, int ptn, void *arg)
    604 {
    605 	unsigned int poffset, psize, pend;
    606 	const char *desc;
    607 	static const char *Yes;
    608 	partinfo *p = pm->bsdlabel + ptn;
    609 
    610 	if (Yes == NULL)
    611 		Yes = msg_string(MSG_Yes);
    612 
    613 	poffset = p->pi_offset / sizemult;
    614 	psize = p->pi_size / sizemult;
    615 	if (psize == 0)
    616 		pend = 0;
    617 	else
    618 		pend = (p->pi_offset + p->pi_size) / sizemult - 1;
    619 
    620 	if (p->pi_fstype == FS_BSDFFS)
    621 		if (p->pi_flags & PIF_FFSv2)
    622 			desc = "FFSv2";
    623 		else
    624 			desc = "FFSv1";
    625 	else
    626 		desc = getfslabelname(p->pi_fstype);
    627 
    628 #ifdef PART_BOOT
    629 	if (ptn == PART_BOOT)
    630 		desc = msg_string(MSG_Boot_partition_cant_change);
    631 #endif
    632 	if (ptn == getrawpartition())
    633 		desc = msg_string(MSG_Whole_disk_cant_change);
    634 	else {
    635 		if (ptn == PART_C)
    636 			desc = msg_string(MSG_NetBSD_partition_cant_change);
    637 	}
    638 
    639 	wprintw(m->mw, msg_string(MSG_fspart_row),
    640 			poffset, pend, psize, desc,
    641 			p->pi_flags & PIF_NEWFS ? Yes : "",
    642 			p->pi_flags & PIF_MOUNT ? Yes : "",
    643 			p->pi_mount);
    644 }
    645 
    646 /*
    647  * Label a disk using an MD-specific string DISKLABEL_CMD for
    648  * to invoke disklabel.
    649  * if MD code does not define DISKLABEL_CMD, this is a no-op.
    650  *
    651  * i386 port uses "/sbin/disklabel -w -r", just like i386
    652  * miniroot scripts, though this may leave a bogus incore label.
    653  *
    654  * Sun ports should use DISKLABEL_CMD "/sbin/disklabel -w"
    655  * to get incore to ondisk inode translation for the Sun proms.
    656  */
    657 int
    658 write_disklabel (void)
    659 {
    660 	int rv = 0;
    661 
    662 #ifdef DISKLABEL_CMD
    663 	/* disklabel the disk */
    664 	rv = run_program(RUN_DISPLAY, "%s -f /tmp/disktab %s '%s'",
    665 	    DISKLABEL_CMD, pm->diskdev, pm->bsddiskname);
    666 	if (rv == 0)
    667 		update_wedges(pm->diskdev);
    668 #endif
    669 	return rv;
    670 }
    671 
    672 
    673 static int
    674 ptn_sort(const void *a, const void *b)
    675 {
    676 	return strcmp(pm->bsdlabel[*(const int *)a].pi_mount,
    677 		      pm->bsdlabel[*(const int *)b].pi_mount);
    678 }
    679 
    680 int
    681 make_filesystems(void)
    682 {
    683 	unsigned int i;
    684 	int ptn;
    685 	int ptn_order[nelem(pm->bsdlabel)];
    686 	int error = 0;
    687 	unsigned int maxpart = getmaxpartitions();
    688 	char *newfs = NULL, *dev = NULL, *devdev = NULL;
    689 	partinfo *lbl;
    690 
    691 	if (maxpart > nelem(pm->bsdlabel))
    692 		maxpart = nelem(pm->bsdlabel);
    693 
    694 	/* Making new file systems and mounting them */
    695 
    696 	/* sort to ensure /usr/local is mounted after /usr (etc) */
    697 	for (i = 0; i < maxpart; i++)
    698 		ptn_order[i] = i;
    699 	qsort(ptn_order, maxpart, sizeof ptn_order[0], ptn_sort);
    700 
    701 	for (i = 0; i < maxpart; i++) {
    702 		/*
    703 		 * newfs and mount. For now, process only BSD filesystems.
    704 		 * but if this is the mounted-on root, has no mount
    705 		 * point defined, or is marked preserve, don't touch it!
    706 		 */
    707 		ptn = ptn_order[i];
    708 		lbl = pm->bsdlabel + ptn;
    709 
    710 		if (is_active_rootpart(pm->diskdev, ptn))
    711 			continue;
    712 
    713 		if (*lbl->pi_mount == 0)
    714 			/* No mount point */
    715 			continue;
    716 
    717 		if (pm->isspecial) {
    718 			asprintf(&dev, "%s", pm->diskdev);
    719 			ptn = 0 - 'a';
    720 		} else {
    721 			asprintf(&dev, "%s%c", pm->diskdev, 'a' + ptn);
    722 		}
    723 		if (dev == NULL)
    724 			return (ENOMEM);
    725 		asprintf(&devdev, "/dev/%s", dev);
    726 		if (devdev == NULL)
    727 			return (ENOMEM);
    728 
    729 		newfs = NULL;
    730 		lbl->mnt_opts = NULL;
    731 		lbl->fsname = NULL;
    732 		switch (lbl->pi_fstype) {
    733 		case FS_APPLEUFS:
    734 			asprintf(&newfs, "/sbin/newfs %s%.0d",
    735 				lbl->pi_isize != 0 ? "-i" : "", lbl->pi_isize);
    736 			lbl->mnt_opts = "-tffs -o async";
    737 			lbl->fsname = "ffs";
    738 			break;
    739 		case FS_BSDFFS:
    740 			asprintf(&newfs,
    741 			    "/sbin/newfs -V2 -O %d -b %d -f %d%s%.0d",
    742 			    lbl->pi_flags & PIF_FFSv2 ? 2 : 1,
    743 			    lbl->pi_fsize * lbl->pi_frag, lbl->pi_fsize,
    744 			    lbl->pi_isize != 0 ? " -i " : "", lbl->pi_isize);
    745 			if (lbl->pi_flags & PIF_LOG)
    746 				lbl->mnt_opts = "-tffs -o log";
    747 			else
    748 				lbl->mnt_opts = "-tffs -o async";
    749 			lbl->fsname = "ffs";
    750 			break;
    751 		case FS_BSDLFS:
    752 			asprintf(&newfs, "/sbin/newfs_lfs -b %d",
    753 				lbl->pi_fsize * lbl->pi_frag);
    754 			lbl->mnt_opts = "-tlfs";
    755 			lbl->fsname = "lfs";
    756 			break;
    757 		case FS_MSDOS:
    758 #ifdef USE_NEWFS_MSDOS
    759 			asprintf(&newfs, "/sbin/newfs_msdos");
    760 #endif
    761 			lbl->mnt_opts = "-tmsdos";
    762 			lbl->fsname = "msdos";
    763 			break;
    764 #ifdef USE_SYSVBFS
    765 		case FS_SYSVBFS:
    766 			asprintf(&newfs, "/sbin/newfs_sysvbfs");
    767 			lbl->mnt_opts = "-tsysvbfs";
    768 			lbl->fsname = "sysvbfs";
    769 			break;
    770 #endif
    771 #ifdef USE_EXT2FS
    772 		case FS_EX2FS:
    773 			asprintf(&newfs, "/sbin/newfs_ext2fs");
    774 			lbl->mnt_opts = "-text2fs";
    775 			lbl->fsname = "ext2fs";
    776 			break;
    777 #endif
    778 		}
    779 		if (lbl->pi_flags & PIF_NEWFS && newfs != NULL) {
    780 #ifdef USE_NEWFS_MSDOS
    781 			if (lbl->pi_fstype == FS_MSDOS) {
    782 			        /* newfs only if mount fails */
    783 			        if (run_program(RUN_SILENT | RUN_ERROR_OK,
    784 				    "mount -rt msdos /dev/%s /mnt2", dev) != 0)
    785 					error = run_program(
    786 					    RUN_DISPLAY | RUN_PROGRESS,
    787 					    "%s /dev/r%s",
    788 					    newfs, dev);
    789 				else {
    790 					run_program(RUN_SILENT | RUN_ERROR_OK,
    791 					    "umount /mnt2");
    792 					error = 0;
    793 				}
    794 			} else
    795 #endif
    796 			error = run_program(RUN_DISPLAY | RUN_PROGRESS,
    797 			    "%s /dev/r%s", newfs, dev);
    798 		} else {
    799 			/* We'd better check it isn't dirty */
    800 			error = fsck_preen(pm->diskdev, ptn, lbl->fsname);
    801 		}
    802 		free(newfs);
    803 		if (error != 0) {
    804 			free(devdev);
    805 			free(dev);
    806 			return error;
    807 		}
    808 
    809 		lbl->pi_flags ^= PIF_NEWFS;
    810 		md_pre_mount();
    811 
    812 		if (partman_go == 0 && lbl->pi_flags & PIF_MOUNT &&
    813 				lbl->mnt_opts != NULL) {
    814 			make_target_dir(lbl->pi_mount);
    815 			error = target_mount_do(lbl->mnt_opts, devdev, lbl->pi_mount);
    816 			if (error) {
    817 				msg_display(MSG_mountfail, dev, ' ', lbl->pi_mount);
    818 				process_menu(MENU_ok, NULL);
    819 				free(devdev);
    820 				free(dev);
    821 				return error;
    822 			}
    823 		}
    824 		free(devdev);
    825 		free(dev);
    826 	}
    827 	return 0;
    828 }
    829 
    830 int
    831 make_fstab(void)
    832 {
    833 	FILE *f;
    834 	int i, swap_dev = -1;
    835 	const char *dump_dev;
    836 	char *dev = NULL;
    837 	pm_devs_t *pm_i;
    838 #ifndef HAVE_TMPFS
    839 	pm_devs_t *pm_with_swap = NULL;
    840 #endif
    841 
    842 	/* Create the fstab. */
    843 	make_target_dir("/etc");
    844 	f = target_fopen("/etc/fstab", "w");
    845 	scripting_fprintf(NULL, "cat <<EOF >%s/etc/fstab\n", target_prefix());
    846 
    847 	if (logfp)
    848 		(void)fprintf(logfp,
    849 		    "Making %s/etc/fstab (%s).\n", target_prefix(), pm->diskdev);
    850 
    851 	if (f == NULL) {
    852 		msg_display(MSG_createfstab);
    853 		if (logfp)
    854 			(void)fprintf(logfp, "Failed to make /etc/fstab!\n");
    855 		process_menu(MENU_ok, NULL);
    856 #ifndef DEBUG
    857 		return 1;
    858 #else
    859 		f = stdout;
    860 #endif
    861 	}
    862 
    863 	scripting_fprintf(f, "# NetBSD %s/etc/fstab\n# See /usr/share/examples/"
    864 			"fstab/ for more examples.\n", target_prefix());
    865 	if (! partman_go) {
    866 		/* We want to process only one disk... */
    867 		pm_i = pm;
    868 		goto onlyonediskinfstab;
    869 	}
    870 	SLIST_FOREACH(pm_i, &pm_head, l) {
    871 		onlyonediskinfstab:
    872 		for (i = 0; i < getmaxpartitions(); i++) {
    873 			const char *s = "";
    874 			const char *mp = pm_i->bsdlabel[i].pi_mount;
    875 			const char *fstype = "ffs";
    876 			int fsck_pass = 0, dump_freq = 0;
    877 
    878 			if (dev != NULL)
    879 				free(dev);
    880 			if (pm_i->isspecial)
    881 				asprintf(&dev, "%s", pm_i->diskdev);
    882 			else
    883 				asprintf(&dev, "%s%c", pm_i->diskdev, 'a' + i);
    884 			if (dev == NULL)
    885 				return (ENOMEM);
    886 
    887 			if (!*mp) {
    888 				/*
    889 				 * No mount point specified, comment out line and
    890 				 * use /mnt as a placeholder for the mount point.
    891 				 */
    892 				s = "# ";
    893 				mp = "/mnt";
    894 			}
    895 
    896 			switch (pm_i->bsdlabel[i].pi_fstype) {
    897 			case FS_UNUSED:
    898 				continue;
    899 			case FS_BSDLFS:
    900 				/* If there is no LFS, just comment it out. */
    901 				if (!check_lfs_progs())
    902 					s = "# ";
    903 				fstype = "lfs";
    904 				/* FALLTHROUGH */
    905 			case FS_BSDFFS:
    906 				fsck_pass = (strcmp(mp, "/") == 0) ? 1 : 2;
    907 				dump_freq = 1;
    908 				break;
    909 			case FS_MSDOS:
    910 				fstype = "msdos";
    911 				break;
    912 			case FS_SWAP:
    913 				if (pm_i->isspecial)
    914 					continue;
    915 				if (swap_dev == -1) {
    916 					swap_dev = i;
    917 					dump_dev = ",dp";
    918 #ifndef HAVE_TMPFS
    919 					pm_with_swap = pm_i;
    920 #endif
    921 				} else {
    922 					dump_dev = "";
    923 				}
    924 				scripting_fprintf(f, "/dev/%s\t\tnone\tswap\tsw%s\t\t 0 0\n",
    925 					dev, dump_dev);
    926 				continue;
    927 #ifdef USE_SYSVBFS
    928 			case FS_SYSVBFS:
    929 				fstype = "sysvbfs";
    930 				make_target_dir("/stand");
    931 				break;
    932 #endif
    933 			default:
    934 				fstype = "???";
    935 				s = "# ";
    936 				break;
    937 			}
    938 			/* The code that remounts root rw doesn't check the partition */
    939 			if (strcmp(mp, "/") == 0 && !(pm_i->bsdlabel[i].pi_flags & PIF_MOUNT))
    940 				s = "# ";
    941 
    942 	 		scripting_fprintf(f,
    943 			  "%s/dev/%s\t\t%s\t%s\trw%s%s%s%s%s%s%s%s\t\t %d %d\n",
    944 			   s, dev, mp, fstype,
    945 			   pm_i->bsdlabel[i].pi_flags & PIF_LOG ? ",log" : "",
    946 			   pm_i->bsdlabel[i].pi_flags & PIF_MOUNT ? "" : ",noauto",
    947 			   pm_i->bsdlabel[i].pi_flags & PIF_ASYNC ? ",async" : "",
    948 			   pm_i->bsdlabel[i].pi_flags & PIF_NOATIME ? ",noatime" : "",
    949 			   pm_i->bsdlabel[i].pi_flags & PIF_NODEV ? ",nodev" : "",
    950 			   pm_i->bsdlabel[i].pi_flags & PIF_NODEVMTIME ? ",nodevmtime" : "",
    951 			   pm_i->bsdlabel[i].pi_flags & PIF_NOEXEC ? ",noexec" : "",
    952 			   pm_i->bsdlabel[i].pi_flags & PIF_NOSUID ? ",nosuid" : "",
    953 			   dump_freq, fsck_pass);
    954 	 		if (pm_i->isspecial)
    955 	 			/* Special device (such as dk*) have only one partition */
    956 	 			break;
    957 		}
    958 		/* Simple install, only one disk */
    959 		if (!partman_go)
    960 			break;
    961 	}
    962 	if (tmp_ramdisk_size != 0) {
    963 #ifdef HAVE_TMPFS
    964 		scripting_fprintf(f, "tmpfs\t\t/tmp\ttmpfs\trw,-m=1777,-s=%"
    965 		    PRIi64 "\n",
    966 		    tmp_ramdisk_size * 512);
    967 #else
    968 		if (swap_dev != -1 && pm_with_swap != NULL)
    969 			scripting_fprintf(f, "/dev/%s%c\t\t/tmp\tmfs\trw,-s=%"
    970 			    PRIi64 "\n",
    971 			    pm_with_swap->diskdev, 'a' + swap_dev, tmp_ramdisk_size);
    972 		else
    973 			scripting_fprintf(f, "swap\t\t/tmp\tmfs\trw,-s=%"
    974 			    PRIi64 "\n",
    975 			    tmp_ramdisk_size);
    976 #endif
    977 	}
    978 
    979 	/* Add /kern, /proc and /dev/pts to fstab and make mountpoint. */
    980 	scripting_fprintf(f, "kernfs\t\t/kern\tkernfs\trw\n");
    981 	scripting_fprintf(f, "ptyfs\t\t/dev/pts\tptyfs\trw\n");
    982 	scripting_fprintf(f, "procfs\t\t/proc\tprocfs\trw\n");
    983 	scripting_fprintf(f, "/dev/%s\t\t/cdrom\tcd9660\tro,noauto\n",
    984 	    get_default_cdrom());
    985 	scripting_fprintf(f, "%stmpfs\t\t/var/shm\ttmpfs\trw,-m1777,-sram%%25\n",
    986 	    tmpfs_on_var_shm() ? "" : "#");
    987 	make_target_dir("/kern");
    988 	make_target_dir("/proc");
    989 	make_target_dir("/dev/pts");
    990 	make_target_dir("/cdrom");
    991 	make_target_dir("/var/shm");
    992 
    993 	scripting_fprintf(NULL, "EOF\n");
    994 
    995 	if (dev != NULL)
    996 		free(dev);
    997 	fclose(f);
    998 	fflush(NULL);
    999 	return 0;
   1000 }
   1001 
   1002 
   1003 
   1004 static int
   1005 /*ARGSUSED*/
   1006 foundffs(struct data *list, size_t num)
   1007 {
   1008 	int error;
   1009 
   1010 	if (num < 2 || strcmp(list[1].u.s_val, "/") == 0 ||
   1011 	    strstr(list[2].u.s_val, "noauto") != NULL)
   1012 		return 0;
   1013 
   1014 	error = fsck_preen(list[0].u.s_val, ' '-'a', "ffs");
   1015 	if (error != 0)
   1016 		return error;
   1017 
   1018 	error = target_mount("", list[0].u.s_val, ' '-'a', list[1].u.s_val);
   1019 	if (error != 0) {
   1020 		msg_display(MSG_mount_failed, list[0].u.s_val);
   1021 		if (!ask_noyes(NULL))
   1022 			return error;
   1023 	}
   1024 	return 0;
   1025 }
   1026 
   1027 #ifdef USE_SYSVBFS
   1028 static int
   1029 /*ARGSUSED*/
   1030 foundsysvbfs(struct data *list, size_t num)
   1031 {
   1032 	int error;
   1033 
   1034 	if (num < 2 || strcmp(list[1].u.s_val, "/") == 0 ||
   1035 	    strstr(list[2].u.s_val, "noauto") != NULL)
   1036 		return 0;
   1037 
   1038 	error = target_mount("", list[0].u.s_val, ' '-'a', list[1].u.s_val);
   1039 	if (error != 0)
   1040 		return error;
   1041 	return 0;
   1042 }
   1043 #endif
   1044 
   1045 /*
   1046  * Do an fsck. On failure, inform the user by showing a warning
   1047  * message and doing menu_ok() before proceeding.
   1048  * Returns 0 on success, or nonzero return code from fsck() on failure.
   1049  */
   1050 static int
   1051 fsck_preen(const char *disk, int ptn, const char *fsname)
   1052 {
   1053 	char *prog;
   1054 	int error;
   1055 
   1056 	ptn = (ptn < 0)? 0 : 'a' + ptn;
   1057 	if (fsname == NULL)
   1058 		return 0;
   1059 	/* first, check if fsck program exists, if not, assume ok */
   1060 	asprintf(&prog, "/sbin/fsck_%s", fsname);
   1061 	if (prog == NULL)
   1062 		return 0;
   1063 	if (access(prog, X_OK) != 0) {
   1064 		free(prog);
   1065 		return 0;
   1066 	}
   1067 	if (!strcmp(fsname,"ffs"))
   1068 		fixsb(prog, disk, ptn);
   1069 	error = run_program(0, "%s -p -q /dev/r%s%c", prog, disk, ptn);
   1070 	free(prog);
   1071 	if (error != 0) {
   1072 		msg_display(MSG_badfs, disk, ptn, error);
   1073 		if (ask_noyes(NULL))
   1074 			error = 0;
   1075 		/* XXX at this point maybe we should run a full fsck? */
   1076 	}
   1077 	return error;
   1078 }
   1079 
   1080 /* This performs the same function as the etc/rc.d/fixsb script
   1081  * which attempts to correct problems with ffs1 filesystems
   1082  * which may have been introduced by booting a netbsd-current kernel
   1083  * from between April of 2003 and January 2004. For more information
   1084  * This script was developed as a response to NetBSD pr install/25138
   1085  * Additional prs regarding the original issue include:
   1086  *  bin/17910 kern/21283 kern/21404 port-macppc/23925 port-macppc/23926
   1087  */
   1088 static void
   1089 fixsb(const char *prog, const char *disk, char ptn)
   1090 {
   1091 	int fd;
   1092 	int rval;
   1093 	union {
   1094 		struct fs fs;
   1095 		char buf[SBLOCKSIZE];
   1096 	} sblk;
   1097 	struct fs *fs = &sblk.fs;
   1098 
   1099 	snprintf(sblk.buf, sizeof(sblk.buf), "/dev/r%s%c",
   1100 		disk, ptn == ' ' ? 0 : ptn);
   1101 	fd = open(sblk.buf, O_RDONLY);
   1102 	if (fd == -1)
   1103 		return;
   1104 
   1105 	/* Read ffsv1 main superblock */
   1106 	rval = pread(fd, sblk.buf, sizeof sblk.buf, SBLOCK_UFS1);
   1107 	close(fd);
   1108 	if (rval != sizeof sblk.buf)
   1109 		return;
   1110 
   1111 	if (fs->fs_magic != FS_UFS1_MAGIC &&
   1112 	    fs->fs_magic != FS_UFS1_MAGIC_SWAPPED)
   1113 		/* Not FFSv1 */
   1114 		return;
   1115 	if (fs->fs_old_flags & FS_FLAGS_UPDATED)
   1116 		/* properly updated fslevel 4 */
   1117 		return;
   1118 	if (fs->fs_bsize != fs->fs_maxbsize)
   1119 		/* not messed up */
   1120 		return;
   1121 
   1122 	/*
   1123 	 * OK we have a munged fs, first 'upgrade' to fslevel 4,
   1124 	 * We specify -b16 in order to stop fsck bleating that the
   1125 	 * sb doesn't match the first alternate.
   1126 	 */
   1127 	run_program(RUN_DISPLAY | RUN_PROGRESS,
   1128 	    "%s -p -b 16 -c 4 /dev/r%s%c", prog, disk, ptn);
   1129 	/* Then downgrade to fslevel 3 */
   1130 	run_program(RUN_DISPLAY | RUN_PROGRESS,
   1131 	    "%s -p -c 3 /dev/r%s%c", prog, disk, ptn);
   1132 }
   1133 
   1134 /*
   1135  * fsck and mount the root partition.
   1136  */
   1137 static int
   1138 mount_root(void)
   1139 {
   1140 	int	error;
   1141 	int ptn = (pm->isspecial)? 0 - 'a' : pm->rootpart;
   1142 
   1143 	error = fsck_preen(pm->diskdev, ptn, "ffs");
   1144 	if (error != 0)
   1145 		return error;
   1146 
   1147 	md_pre_mount();
   1148 
   1149 	/* Mount /dev/<diskdev>a on target's "".
   1150 	 * If we pass "" as mount-on, Prefixing will DTRT.
   1151 	 * for now, use no options.
   1152 	 * XXX consider -o remount in case target root is
   1153 	 * current root, still readonly from single-user?
   1154 	 */
   1155 	return target_mount("", pm->diskdev, ptn, "");
   1156 }
   1157 
   1158 /* Get information on the file systems mounted from the root filesystem.
   1159  * Offer to convert them into 4.4BSD inodes if they are not 4.4BSD
   1160  * inodes.  Fsck them.  Mount them.
   1161  */
   1162 
   1163 int
   1164 mount_disks(void)
   1165 {
   1166 	char *fstab;
   1167 	int   fstabsize;
   1168 	int   error;
   1169 
   1170 	static struct lookfor fstabbuf[] = {
   1171 		{"/dev/", "/dev/%s %s ffs %s", "c", NULL, 0, 0, foundffs},
   1172 		{"/dev/", "/dev/%s %s ufs %s", "c", NULL, 0, 0, foundffs},
   1173 #ifdef USE_SYSVBFS
   1174 		{"/dev/", "/dev/%s %s sysvbfs %s", "c", NULL, 0, 0,
   1175 		    foundsysvbfs},
   1176 #endif
   1177 	};
   1178 	static size_t numfstabbuf = sizeof(fstabbuf) / sizeof(struct lookfor);
   1179 
   1180 	/* First the root device. */
   1181 	if (target_already_root())
   1182 		/* avoid needing to call target_already_root() again */
   1183 		targetroot_mnt[0] = 0;
   1184 	else {
   1185 		error = mount_root();
   1186 		if (error != 0 && error != EBUSY)
   1187 			return -1;
   1188 	}
   1189 
   1190 	/* Check the target /etc/fstab exists before trying to parse it. */
   1191 	if (target_dir_exists_p("/etc") == 0 ||
   1192 	    target_file_exists_p("/etc/fstab") == 0) {
   1193 		msg_display(MSG_noetcfstab, pm->diskdev);
   1194 		process_menu(MENU_ok, NULL);
   1195 		return -1;
   1196 	}
   1197 
   1198 
   1199 	/* Get fstab entries from the target-root /etc/fstab. */
   1200 	fstabsize = target_collect_file(T_FILE, &fstab, "/etc/fstab");
   1201 	if (fstabsize < 0) {
   1202 		/* error ! */
   1203 		msg_display(MSG_badetcfstab, pm->diskdev);
   1204 		process_menu(MENU_ok, NULL);
   1205 		return -2;
   1206 	}
   1207 	error = walk(fstab, (size_t)fstabsize, fstabbuf, numfstabbuf);
   1208 	free(fstab);
   1209 
   1210 	return error;
   1211 }
   1212 
   1213 int
   1214 set_swap_if_low_ram(const char *disk, partinfo *pp)
   1215 {
   1216 	if (get_ramsize() <= 32)
   1217 		return set_swap(disk, pp);
   1218 	return 0;
   1219 }
   1220 
   1221 int
   1222 set_swap(const char *disk, partinfo *pp)
   1223 {
   1224 	int i;
   1225 	char *cp;
   1226 	int rval;
   1227 
   1228 	if (pp == NULL)
   1229 		pp = pm->oldlabel;
   1230 
   1231 	for (i = 0; i < MAXPARTITIONS; i++) {
   1232 		if (pp[i].pi_fstype != FS_SWAP)
   1233 			continue;
   1234 		asprintf(&cp, "/dev/%s%c", disk, 'a' + i);
   1235 		rval = swapctl(SWAP_ON, cp, 0);
   1236 		free(cp);
   1237 		if (rval != 0)
   1238 			return -1;
   1239 	}
   1240 
   1241 	return 0;
   1242 }
   1243 
   1244 int
   1245 check_swap(const char *disk, int remove_swap)
   1246 {
   1247 	struct swapent *swap;
   1248 	char *cp;
   1249 	int nswap;
   1250 	int l;
   1251 	int rval = 0;
   1252 
   1253 	nswap = swapctl(SWAP_NSWAP, 0, 0);
   1254 	if (nswap <= 0)
   1255 		return 0;
   1256 
   1257 	swap = malloc(nswap * sizeof *swap);
   1258 	if (swap == NULL)
   1259 		return -1;
   1260 
   1261 	nswap = swapctl(SWAP_STATS, swap, nswap);
   1262 	if (nswap < 0)
   1263 		goto bad_swap;
   1264 
   1265 	l = strlen(disk);
   1266 	while (--nswap >= 0) {
   1267 		/* Should we check the se_dev or se_path? */
   1268 		cp = swap[nswap].se_path;
   1269 		if (memcmp(cp, "/dev/", 5) != 0)
   1270 			continue;
   1271 		if (memcmp(cp + 5, disk, l) != 0)
   1272 			continue;
   1273 		if (!isalpha(*(unsigned char *)(cp + 5 + l)))
   1274 			continue;
   1275 		if (cp[5 + l + 1] != 0)
   1276 			continue;
   1277 		/* ok path looks like it is for this device */
   1278 		if (!remove_swap) {
   1279 			/* count active swap areas */
   1280 			rval++;
   1281 			continue;
   1282 		}
   1283 		if (swapctl(SWAP_OFF, cp, 0) == -1)
   1284 			rval = -1;
   1285 	}
   1286 
   1287     done:
   1288 	free(swap);
   1289 	return rval;
   1290 
   1291     bad_swap:
   1292 	rval = -1;
   1293 	goto done;
   1294 }
   1295 
   1296 #ifdef HAVE_BOOTXX_xFS
   1297 char *
   1298 bootxx_name(void)
   1299 {
   1300 	int fstype;
   1301 	const char *bootxxname;
   1302 	char *bootxx;
   1303 
   1304 	/* check we have boot code for the root partition type */
   1305 	fstype = pm->bsdlabel[pm->rootpart].pi_fstype;
   1306 	switch (fstype) {
   1307 #if defined(BOOTXX_FFSV1) || defined(BOOTXX_FFSV2)
   1308 	case FS_BSDFFS:
   1309 		if (pm->bsdlabel[pm->rootpart].pi_flags & PIF_FFSv2) {
   1310 #ifdef BOOTXX_FFSV2
   1311 			bootxxname = BOOTXX_FFSV2;
   1312 #else
   1313 			bootxxname = NULL;
   1314 #endif
   1315 		} else {
   1316 #ifdef BOOTXX_FFSV1
   1317 			bootxxname = BOOTXX_FFSV1;
   1318 #else
   1319 			bootxxname = NULL;
   1320 #endif
   1321 		}
   1322 		break;
   1323 #endif
   1324 #ifdef BOOTXX_LFSV2
   1325 	case FS_BSDLFS:
   1326 		bootxxname = BOOTXX_LFSV2;
   1327 		break;
   1328 #endif
   1329 	default:
   1330 		bootxxname = NULL;
   1331 		break;
   1332 	}
   1333 
   1334 	if (bootxxname == NULL)
   1335 		return NULL;
   1336 
   1337 	asprintf(&bootxx, "%s/%s", BOOTXXDIR, bootxxname);
   1338 	return bootxx;
   1339 }
   1340 #endif
   1341 
   1342 static int
   1343 get_fsid_by_gptuuid(const char *str)
   1344 {
   1345 	int i;
   1346 	uuid_t uuid;
   1347 	uint32_t status;
   1348 
   1349 	uuid_from_string(str, &uuid, &status);
   1350 	if (status == uuid_s_ok) {
   1351 		for (i = 0; gpt_filesystems[i].id > 0; i++)
   1352 			if (uuid_equal(&uuid, &(gpt_filesystems[i].uuid), NULL))
   1353 				return gpt_filesystems[i].id;
   1354 	}
   1355 	return FS_OTHER;
   1356 }
   1357 
   1358 const char *
   1359 get_gptfs_by_id(int filesystem)
   1360 {
   1361 	int i;
   1362 	for (i = 0; gpt_filesystems[i].id > 0; i++)
   1363 		if (filesystem == gpt_filesystems[i].id)
   1364 			return gpt_filesystems[i].name;
   1365 	return NULL;
   1366 }
   1367 
   1368 /* from dkctl.c */
   1369 static int
   1370 get_dkwedges_sort(const void *a, const void *b)
   1371 {
   1372 	const struct dkwedge_info *dkwa = a, *dkwb = b;
   1373 	const daddr_t oa = dkwa->dkw_offset, ob = dkwb->dkw_offset;
   1374 	return (oa < ob) ? -1 : (oa > ob) ? 1 : 0;
   1375 }
   1376 
   1377 int
   1378 get_dkwedges(struct dkwedge_info **dkw, const char *diskdev)
   1379 {
   1380 	int fd;
   1381 	char buf[STRSIZE];
   1382 	size_t bufsize;
   1383 	struct dkwedge_list dkwl;
   1384 
   1385 	*dkw = NULL;
   1386 	dkwl.dkwl_buf = *dkw;
   1387 	dkwl.dkwl_bufsize = 0;
   1388 	fd = opendisk(diskdev, O_RDONLY, buf, STRSIZE, 0);
   1389 	if (fd < 0)
   1390 		return -1;
   1391 
   1392 	for (;;) {
   1393 		if (ioctl(fd, DIOCLWEDGES, &dkwl) == -1)
   1394 			return -2;
   1395 		if (dkwl.dkwl_nwedges == dkwl.dkwl_ncopied)
   1396 			break;
   1397 		bufsize = dkwl.dkwl_nwedges * sizeof(**dkw);
   1398 		if (dkwl.dkwl_bufsize < bufsize) {
   1399 			*dkw = realloc(dkwl.dkwl_buf, bufsize);
   1400 			if (*dkw == NULL)
   1401 				return -3;
   1402 			dkwl.dkwl_buf = *dkw;
   1403 			dkwl.dkwl_bufsize = bufsize;
   1404 		}
   1405 	}
   1406 
   1407 	if (dkwl.dkwl_nwedges > 0 && *dkw != NULL)
   1408 		qsort(*dkw, dkwl.dkwl_nwedges, sizeof(**dkw), get_dkwedges_sort);
   1409 
   1410 	close(fd);
   1411 	return dkwl.dkwl_nwedges;
   1412 }
   1413 
   1414 /* XXX: rewrite */
   1415 static int
   1416 incoregpt(pm_devs_t *pm_cur, partinfo *lp)
   1417 {
   1418 	int i, num;
   1419 	unsigned int p_num;
   1420 	uint64_t p_start, p_size;
   1421 	char *textbuf, *t, *tt, p_type[STRSIZE];
   1422 	struct dkwedge_info *dkw;
   1423 
   1424 	num = get_dkwedges(&dkw, pm_cur->diskdev);
   1425 	if (dkw != NULL) {
   1426 		for (i = 0; i < num && i < MAX_WEDGES; i++)
   1427 			run_program(RUN_SILENT, "dkctl %s delwedge %s",
   1428 				pm_cur->diskdev, dkw[i].dkw_devname);
   1429 		free (dkw);
   1430 	}
   1431 
   1432 	if (collect(T_OUTPUT, &textbuf, "gpt show -u %s 2>/dev/null", pm_cur->diskdev) < 1)
   1433 		return -1;
   1434 
   1435 	(void)strtok(textbuf, "\n"); /* ignore first line */
   1436 	while ((t = strtok(NULL, "\n")) != NULL) {
   1437 		i = 0; p_start = 0; p_size = 0; p_num = 0; strcpy(p_type, ""); /* init */
   1438 		while ((tt = strsep(&t, " \t")) != NULL) {
   1439 			if (strlen(tt) == 0)
   1440 				continue;
   1441 			if (i == 0)
   1442 				p_start = strtouq(tt, NULL, 10);
   1443 			if (i == 1)
   1444 				p_size = strtouq(tt, NULL, 10);
   1445 			if (i == 2)
   1446 				p_num = strtouq(tt, NULL, 10);
   1447 			if (i > 2 || (i == 2 && p_num == 0))
   1448 				if (
   1449 					strcmp(tt, "GPT") &&
   1450 					strcmp(tt, "part") &&
   1451 					strcmp(tt, "-")
   1452 					)
   1453 						strlcat(p_type, tt, STRSIZE);
   1454 			i++;
   1455 		}
   1456 		if (p_start == 0 || p_size == 0)
   1457 			continue;
   1458 		else if (! strcmp(p_type, "Pritable"))
   1459 			pm_cur->ptstart = p_start + p_size;
   1460 		else if (! strcmp(p_type, "Sectable"))
   1461 			pm_cur->ptsize = p_start - pm_cur->ptstart - 1;
   1462 		else if (p_num == 0 && strlen(p_type) > 0)
   1463 			/* Utilitary entry (PMBR, etc) */
   1464 			continue;
   1465 		else if (p_num == 0) {
   1466 			/* Free space */
   1467 			continue;
   1468 		} else {
   1469 			/* Usual partition */
   1470 			lp[p_num].pi_size = p_size;
   1471 			lp[p_num].pi_offset = p_start;
   1472 			lp[p_num].pi_fstype = get_fsid_by_gptuuid(p_type);
   1473 		}
   1474 	}
   1475 	free(textbuf);
   1476 
   1477 	return 0;
   1478 }
   1479 
   1480 static bool
   1481 is_gpt(const char *dev)
   1482 {
   1483 
   1484 	check_available_binaries();
   1485 
   1486 	if (!have_gpt)
   1487 		return false;
   1488 
   1489 	return run_program(RUN_SILENT | RUN_ERROR_OK,
   1490 		"gpt -qr header %s", dev) == 0;
   1491 }
   1492