xref: /netbsd-src/usr.sbin/sysinst/disks.c (revision deb6f0161a9109e7de9b519dc8dfb9478668dcdd)
1 /*	$NetBSD: disks.c,v 1.28 2018/11/27 17:13:41 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 > 16 * MEG;
141 }
142 
143 /* from src/sbin/atactl/atactl.c
144  * extract_string: copy a block of bytes out of ataparams and make
145  * a proper string out of it, truncating trailing spaces and preserving
146  * strict typing. And also, not doing unaligned accesses.
147  */
148 static void
149 ata_extract_string(char *buf, size_t bufmax,
150 		   uint8_t *bytes, unsigned numbytes,
151 		   int needswap)
152 {
153 	unsigned i;
154 	size_t j;
155 	unsigned char ch1, ch2;
156 
157 	for (i = 0, j = 0; i < numbytes; i += 2) {
158 		ch1 = bytes[i];
159 		ch2 = bytes[i+1];
160 		if (needswap && j < bufmax-1) {
161 			buf[j++] = ch2;
162 		}
163 		if (j < bufmax-1) {
164 			buf[j++] = ch1;
165 		}
166 		if (!needswap && j < bufmax-1) {
167 			buf[j++] = ch2;
168 		}
169 	}
170 	while (j > 0 && buf[j-1] == ' ') {
171 		j--;
172 	}
173 	buf[j] = '\0';
174 }
175 
176 /*
177  * from src/sbin/scsictl/scsi_subr.c
178  */
179 #define STRVIS_ISWHITE(x) ((x) == ' ' || (x) == '\0' || (x) == (u_char)'\377')
180 
181 static void
182 scsi_strvis(char *sdst, size_t dlen, const char *ssrc, size_t slen)
183 {
184 	u_char *dst = (u_char *)sdst;
185 	const u_char *src = (const u_char *)ssrc;
186 
187 	/* Trim leading and trailing blanks and NULs. */
188 	while (slen > 0 && STRVIS_ISWHITE(src[0]))
189 		++src, --slen;
190 	while (slen > 0 && STRVIS_ISWHITE(src[slen - 1]))
191 		--slen;
192 
193 	while (slen > 0) {
194 		if (*src < 0x20 || *src >= 0x80) {
195 			/* non-printable characters */
196 			dlen -= 4;
197 			if (dlen < 1)
198 				break;
199 			*dst++ = '\\';
200 			*dst++ = ((*src & 0300) >> 6) + '0';
201 			*dst++ = ((*src & 0070) >> 3) + '0';
202 			*dst++ = ((*src & 0007) >> 0) + '0';
203 		} else if (*src == '\\') {
204 			/* quote characters */
205 			dlen -= 2;
206 			if (dlen < 1)
207 				break;
208 			*dst++ = '\\';
209 			*dst++ = '\\';
210 		} else {
211 			/* normal characters */
212 			if (--dlen < 1)
213 				break;
214 			*dst++ = *src;
215 		}
216 		++src, --slen;
217 	}
218 
219 	*dst++ = 0;
220 }
221 
222 
223 static int
224 get_descr_scsi(struct disk_desc *dd, 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 /* does this device match any entry in the driver list? */
550 static bool
551 dev_in_list(const char *dev, const char **list)
552 {
553 
554 	for ( ; *list; list++) {
555 
556 		size_t len = strlen(*list);
557 
558 		/* start of name matches? */
559 		if (strncmp(dev, *list, len) == 0) {
560 			char *endp;
561 			int e;
562 
563 			/* remainder of name is a decimal number? */
564 			strtou(dev+len, &endp, 10, 0, INT_MAX, &e);
565 			if (endp && *endp == 0 && e == 0)
566 				return true;
567 		}
568 	}
569 
570 	return false;
571 }
572 
573 bool
574 is_bootable_device(const char *dev)
575 {
576 	static const char *non_bootable_devs[] = {
577 		"raid",	/* bootcode lives outside of raid */
578 		"xbd",	/* xen virtual device, can not boot from that */
579 		NULL
580 	};
581 
582 	return !dev_in_list(dev, non_bootable_devs);
583 }
584 
585 bool
586 is_partitionable_device(const char *dev)
587 {
588 	static const char *non_partitionable_devs[] = {
589 		"dk",	/* this is alreay a partioned slice */
590 		NULL
591 	};
592 
593 	return !dev_in_list(dev, non_partitionable_devs);
594 }
595 
596 /*
597  * Multi-purpose helper function:
598  * iterate all known disks, invoke a callback for each.
599  * Stop iteration when the callback returns false.
600  * Return true when iteration actually happend, false on error.
601  */
602 bool
603 enumerate_disks(void *state, bool (*func)(void *state, const char *dev))
604 {
605 	static const int mib[] = { CTL_HW, HW_DISKNAMES };
606 	static const unsigned int miblen = __arraycount(mib);
607 	const char *xd;
608 	char *disk_names;
609 	size_t len;
610 
611 	if (sysctl(mib, miblen, NULL, &len, NULL, 0) == -1)
612 		return false;
613 
614 	disk_names = malloc(len);
615 	if (disk_names == NULL)
616 		return false;
617 
618 	if (sysctl(mib, miblen, disk_names, &len, NULL, 0) == -1) {
619 		free(disk_names);
620 		return false;
621 	}
622 
623 	for (xd = strtok(disk_names, " "); xd != NULL; xd = strtok(NULL, " ")) {
624 		if (!(*func)(state, xd))
625 			break;
626 	}
627 	free(disk_names);
628 
629 	return true;
630 }
631 
632 /*
633  * Helper state for get_disks
634  */
635 struct get_disks_state {
636 	int numdisks;
637 	struct disk_desc *dd;
638 	bool with_non_partitionable;
639 };
640 
641 /*
642  * Helper function for get_disks enumartion
643  */
644 static bool
645 get_disks_helper(void *arg, const char *dev)
646 {
647 	struct get_disks_state *state = arg;
648 	struct disklabel l;
649 
650 	/* is this a CD device? */
651 	if (is_cdrom_device(dev, true))
652 		return true;
653 
654 	memset(state->dd, 0, sizeof(*state->dd));
655 	strlcpy(state->dd->dd_name, dev, sizeof state->dd->dd_name - 2);
656 	state->dd->dd_no_mbr = !is_bootable_device(dev);
657 	state->dd->dd_no_part = !is_partitionable_device(dev);
658 
659 	if (state->dd->dd_no_part && !state->with_non_partitionable)
660 		return true;
661 
662 	if (!get_geom(state->dd->dd_name, &l)) {
663 		if (errno == ENOENT)
664 			return true;
665 		if (errno != ENOTTY || !state->dd->dd_no_part)
666 			/*
667 			 * Allow plain partitions,
668 			 * like already existing wedges
669 			 * (like dk0) if marked as
670 			 * non-partitioning device.
671 			 * For all other cases, continue
672 			 * with the next disk.
673 			 */
674 			return true;
675 		if (!is_ffs_wedge(state->dd->dd_name))
676 			return true;
677 	}
678 
679 	/*
680 	 * Exclude a disk mounted as root partition,
681 	 * in case of install-image on a USB memstick.
682 	 */
683 	if (is_active_rootpart(state->dd->dd_name,
684 	    state->dd->dd_no_part ? -1 : 0))
685 		return true;
686 
687 	if (!state->dd->dd_no_part) {
688 		state->dd->dd_cyl = l.d_ncylinders;
689 		state->dd->dd_head = l.d_ntracks;
690 		state->dd->dd_sec = l.d_nsectors;
691 		state->dd->dd_secsize = l.d_secsize;
692 		state->dd->dd_totsec = l.d_secperunit;
693 	}
694 	if (state->dd->dd_no_part)
695 		get_wedge_descr(state->dd);
696 	else
697 		get_descr(state->dd);
698 	state->dd++;
699 	state->numdisks++;
700 	if (state->numdisks == MAX_DISKS)
701 		return false;
702 
703 	return true;
704 }
705 
706 /*
707  * Get all disk devices that are not CDs.
708  * Optionally leave out those that can not be partitioned further.
709  */
710 static int
711 get_disks(struct disk_desc *dd, bool with_non_partitionable)
712 {
713 	struct get_disks_state state;
714 
715 	/* initialize */
716 	state.numdisks = 0;
717 	state.dd = dd;
718 	state.with_non_partitionable = with_non_partitionable;
719 
720 	if (enumerate_disks(&state, get_disks_helper))
721 		return state.numdisks;
722 
723 	return 0;
724 }
725 
726 int
727 find_disks(const char *doingwhat)
728 {
729 	struct disk_desc disks[MAX_DISKS];
730 	menu_ent dsk_menu[nelem(disks) + 1]; // + 1 for extended partitioning entry
731 	struct disk_desc *disk;
732 	int i = 0, skipped = 0;
733 	int already_found, numdisks, selected_disk = -1;
734 	int menu_no;
735 	pm_devs_t *pm_i, *pm_last = NULL;
736 
737 	/* Find disks. */
738 	numdisks = get_disks(disks, partman_go <= 0);
739 
740 	/* need a redraw here, kernel messages hose everything */
741 	touchwin(stdscr);
742 	refresh();
743 	/* Kill typeahead, it won't be what the user had in mind */
744 	fpurge(stdin);
745 
746 	/*
747 	 * partman_go: <0 - we want to see menu with extended partitioning
748 	 *            ==0 - we want to see simple select disk menu
749 	 *             >0 - we do not want to see any menus, just detect
750 	 *                  all disks
751 	 */
752 	if (partman_go <= 0) {
753 		if (numdisks == 0) {
754 			/* No disks found! */
755 			msg_display(MSG_nodisk);
756 			process_menu(MENU_ok, NULL);
757 			/*endwin();*/
758 			return -1;
759 		} else {
760 			/* One or more disks found! */
761 			for (i = 0; i < numdisks; i++) {
762 				dsk_menu[i].opt_name =
763 				    disks[i].dd_descr;
764 				dsk_menu[i].opt_menu = OPT_NOMENU;
765 				dsk_menu[i].opt_flags = OPT_EXIT;
766 				dsk_menu[i].opt_action = set_menu_select;
767 			}
768 			if (partman_go < 0) {
769 				dsk_menu[i].opt_name = MSG_partman;
770 				dsk_menu[i].opt_menu = OPT_NOMENU;
771 				dsk_menu[i].opt_flags = OPT_EXIT;
772 				dsk_menu[i].opt_action = set_menu_select;
773 			}
774 			menu_no = new_menu(MSG_Available_disks,
775 				dsk_menu, numdisks
776 				 + ((partman_go<0)?1:0), -1,
777 				 4, 0, 0, MC_SCROLL,
778 				NULL, NULL, NULL, NULL, NULL);
779 			if (menu_no == -1)
780 				return -1;
781 			msg_display(MSG_ask_disk, doingwhat);
782 			process_menu(menu_no, &selected_disk);
783 			free_menu(menu_no);
784 		}
785 		if (partman_go < 0 && selected_disk == numdisks) {
786 			partman_go = 1;
787 			return -2;
788 		} else
789 			partman_go = 0;
790 		if (selected_disk < 0 || selected_disk >= numdisks)
791 			return -1;
792 	}
793 
794 	/* Fill pm struct with device(s) info */
795 	for (i = 0; i < numdisks; i++) {
796 		if (! partman_go)
797 			disk = disks + selected_disk;
798 		else {
799 			disk = disks + i;
800 			already_found = 0;
801 			SLIST_FOREACH(pm_i, &pm_head, l) {
802 				pm_last = pm_i;
803 				if (!already_found &&
804 				    strcmp(pm_i->diskdev, disk->dd_name) == 0) {
805 					pm_i->found = 1;
806 					break;
807 				}
808 			}
809 			if (pm_i != NULL && pm_i->found)
810 				/* We already added this device, skipping */
811 				continue;
812 		}
813 		pm = pm_new;
814 		pm->found = 1;
815 		pm->bootable = 0;
816 		pm->pi.menu_no = -1;
817 		pm->disktype = "unknown";
818 		pm->doessf = "";
819 		strlcpy(pm->diskdev, disk->dd_name, sizeof pm->diskdev);
820 		strlcpy(pm->diskdev_descr, disk->dd_descr, sizeof pm->diskdev_descr);
821 		/* Use as a default disk if the user has the sets on a local disk */
822 		strlcpy(localfs_dev, disk->dd_name, sizeof localfs_dev);
823 
824 		pm->gpt = is_gpt(pm->diskdev);
825 		pm->no_mbr = disk->dd_no_mbr || pm->gpt;
826 		pm->no_part = disk->dd_no_part;
827 		if (!pm->no_part) {
828 			pm->sectorsize = disk->dd_secsize;
829 			pm->dlcyl = disk->dd_cyl;
830 			pm->dlhead = disk->dd_head;
831 			pm->dlsec = disk->dd_sec;
832 			pm->dlsize = disk->dd_totsec;
833 			if (pm->dlsize == 0)
834 				pm->dlsize = disk->dd_cyl * disk->dd_head * disk->dd_sec;
835 			if (pm->dlsize > UINT32_MAX && ! partman_go) {
836 				if (logfp)
837 					fprintf(logfp, "Cannot process disk %s: too big size (%d)\n",
838 						pm->diskdev, (int)pm->dlsize);
839 				msg_display(MSG_toobigdisklabel);
840 				process_menu(MENU_ok, NULL);
841 				return -1;
842 			}
843 		} else {
844 			pm->sectorsize = 0;
845 			pm->dlcyl = 0;
846 			pm->dlhead = 0;
847 			pm->dlsec = 0;
848 			pm->dlsize = 0;
849 			pm->rootpart = -1;
850 			pm->no_mbr = 1;
851 			memset(&pm->bsdlabel, 0, sizeof(pm->bsdlabel));
852 		}
853 		pm->dlcylsize = pm->dlhead * pm->dlsec;
854 
855 		label_read();
856 		if (partman_go) {
857 			pm_getrefdev(pm_new);
858 			if (SLIST_EMPTY(&pm_head) || pm_last == NULL)
859 				 SLIST_INSERT_HEAD(&pm_head, pm_new, l);
860 			else
861 				 SLIST_INSERT_AFTER(pm_last, pm_new, l);
862 			pm_new = malloc(sizeof (pm_devs_t));
863 			memset(pm_new, 0, sizeof *pm_new);
864 		} else
865 			/* We is not in partman and do not want to process all devices, exit */
866 			break;
867 	}
868 
869 	return numdisks-skipped;
870 }
871 
872 
873 void
874 label_read(void)
875 {
876 
877 	if (pm->no_part)
878 		return;
879 
880 	check_available_binaries();
881 
882 	/* Get existing/default label */
883 	memset(&pm->oldlabel, 0, sizeof pm->oldlabel);
884 	if (!have_gpt || !pm->gpt)
885 		incorelabel(pm->diskdev, pm->oldlabel);
886 	else
887 		incoregpt(pm, pm->oldlabel);
888 	/* Set 'target' label to current label in case we don't change it */
889 	memcpy(&pm->bsdlabel, &pm->oldlabel, sizeof pm->bsdlabel);
890 #ifndef NO_DISKLABEL
891 	if (! pm->gpt)
892 		savenewlabel(pm->oldlabel, getmaxpartitions());
893 #endif
894 }
895 
896 void
897 fmt_fspart(menudesc *m, int ptn, void *arg)
898 {
899 	unsigned int poffset, psize, pend;
900 	const char *desc;
901 	static const char *Yes;
902 	partinfo *p = pm->bsdlabel + ptn;
903 
904 	if (Yes == NULL)
905 		Yes = msg_string(MSG_Yes);
906 
907 	poffset = p->pi_offset / sizemult;
908 	psize = p->pi_size / sizemult;
909 	if (psize == 0)
910 		pend = 0;
911 	else
912 		pend = (p->pi_offset + p->pi_size) / sizemult - 1;
913 
914 	if (p->pi_fstype == FS_BSDFFS)
915 		if (p->pi_flags & PIF_FFSv2)
916 			desc = "FFSv2";
917 		else
918 			desc = "FFSv1";
919 	else
920 		desc = getfslabelname(p->pi_fstype);
921 
922 #ifdef PART_BOOT
923 	if (ptn == PART_BOOT)
924 		desc = msg_string(MSG_Boot_partition_cant_change);
925 #endif
926 	if (ptn == getrawpartition())
927 		desc = msg_string(MSG_Whole_disk_cant_change);
928 	else {
929 		if (ptn == PART_C)
930 			desc = msg_string(MSG_NetBSD_partition_cant_change);
931 	}
932 
933 	wprintw(m->mw, msg_string(MSG_fspart_row),
934 			poffset, pend, psize, desc,
935 			p->pi_flags & PIF_NEWFS ? Yes : "",
936 			p->pi_flags & PIF_MOUNT ? Yes : "",
937 			p->pi_mount);
938 }
939 
940 /*
941  * Label a disk using an MD-specific string DISKLABEL_CMD for
942  * to invoke disklabel.
943  * if MD code does not define DISKLABEL_CMD, this is a no-op.
944  *
945  * i386 port uses "/sbin/disklabel -w -r", just like i386
946  * miniroot scripts, though this may leave a bogus incore label.
947  *
948  * Sun ports should use DISKLABEL_CMD "/sbin/disklabel -w"
949  * to get incore to ondisk inode translation for the Sun proms.
950  */
951 int
952 write_disklabel (void)
953 {
954 	int rv = 0;
955 
956 	if (pm && pm->no_part)
957 		return 0;
958 
959 #ifdef DISKLABEL_CMD
960 	/* disklabel the disk */
961 	rv = run_program(RUN_DISPLAY, "%s -f /tmp/disktab %s '%s'",
962 	    DISKLABEL_CMD, pm->diskdev, pm->bsddiskname);
963 	if (rv == 0)
964 		update_wedges(pm->diskdev);
965 #endif
966 	return rv;
967 }
968 
969 
970 static int
971 ptn_sort(const void *a, const void *b)
972 {
973 	return strcmp(pm->bsdlabel[*(const int *)a].pi_mount,
974 		      pm->bsdlabel[*(const int *)b].pi_mount);
975 }
976 
977 int
978 make_filesystems(void)
979 {
980 	unsigned int i;
981 	int ptn;
982 	int ptn_order[nelem(pm->bsdlabel)];
983 	int error = 0;
984 	unsigned int maxpart = getmaxpartitions();
985 	char *newfs = NULL, *dev = NULL, *devdev = NULL;
986 	partinfo *lbl;
987 
988 	if (pm->no_part) {
989 		/* check if this target device already has a ffs */
990 		error = fsck_preen(pm->diskdev, -1, "ffs", true);
991 		if (error) {
992 			if (!ask_noyes(MSG_No_filesystem_newfs))
993 				return EINVAL;
994 			error = run_program(RUN_DISPLAY | RUN_PROGRESS,
995 			    "/sbin/newfs -V2 -O2 /dev/r%s", pm->diskdev);
996 		}
997 
998 		md_pre_mount();
999 
1000 		make_target_dir("/");
1001 		asprintf(&devdev, "/dev/%s", pm->diskdev);
1002 		if (devdev == NULL)
1003 			return (ENOMEM);
1004 		error = target_mount_do("-o async", devdev, "/");
1005 		if (error) {
1006 			msg_display(MSG_mountfail, devdev, ' ',
1007 			    "/");
1008 			process_menu(MENU_ok, NULL);
1009 		}
1010 		free(devdev);
1011 		return error;
1012 	}
1013 
1014 	if (maxpart > nelem(pm->bsdlabel))
1015 		maxpart = nelem(pm->bsdlabel);
1016 
1017 	/* Making new file systems and mounting them */
1018 
1019 	/* sort to ensure /usr/local is mounted after /usr (etc) */
1020 	for (i = 0; i < maxpart; i++)
1021 		ptn_order[i] = i;
1022 	qsort(ptn_order, maxpart, sizeof ptn_order[0], ptn_sort);
1023 
1024 	for (i = 0; i < maxpart; i++) {
1025 		/*
1026 		 * newfs and mount. For now, process only BSD filesystems.
1027 		 * but if this is the mounted-on root, has no mount
1028 		 * point defined, or is marked preserve, don't touch it!
1029 		 */
1030 		ptn = ptn_order[i];
1031 		lbl = pm->bsdlabel + ptn;
1032 
1033 		if (is_active_rootpart(pm->diskdev, ptn))
1034 			continue;
1035 
1036 		if (*lbl->pi_mount == 0)
1037 			/* No mount point */
1038 			continue;
1039 
1040 		if (pm->isspecial) {
1041 			asprintf(&dev, "%s", pm->diskdev);
1042 			ptn = 0 - 'a';
1043 		} else {
1044 			asprintf(&dev, "%s%c", pm->diskdev, 'a' + ptn);
1045 		}
1046 		if (dev == NULL)
1047 			return (ENOMEM);
1048 		asprintf(&devdev, "/dev/%s", dev);
1049 		if (devdev == NULL)
1050 			return (ENOMEM);
1051 
1052 		newfs = NULL;
1053 		lbl->mnt_opts = NULL;
1054 		lbl->fsname = NULL;
1055 		switch (lbl->pi_fstype) {
1056 		case FS_APPLEUFS:
1057 			asprintf(&newfs, "/sbin/newfs %s%.0d",
1058 				lbl->pi_isize != 0 ? "-i" : "", lbl->pi_isize);
1059 			lbl->mnt_opts = "-tffs -o async";
1060 			lbl->fsname = "ffs";
1061 			break;
1062 		case FS_BSDFFS:
1063 			asprintf(&newfs,
1064 			    "/sbin/newfs -V2 -O %d -b %d -f %d%s%.0d",
1065 			    lbl->pi_flags & PIF_FFSv2 ? 2 : 1,
1066 			    lbl->pi_fsize * lbl->pi_frag, lbl->pi_fsize,
1067 			    lbl->pi_isize != 0 ? " -i " : "", lbl->pi_isize);
1068 			if (lbl->pi_flags & PIF_LOG)
1069 				lbl->mnt_opts = "-tffs -o log";
1070 			else
1071 				lbl->mnt_opts = "-tffs -o async";
1072 			lbl->fsname = "ffs";
1073 			break;
1074 		case FS_BSDLFS:
1075 			asprintf(&newfs, "/sbin/newfs_lfs -b %d",
1076 				lbl->pi_fsize * lbl->pi_frag);
1077 			lbl->mnt_opts = "-tlfs";
1078 			lbl->fsname = "lfs";
1079 			break;
1080 		case FS_MSDOS:
1081 #ifdef USE_NEWFS_MSDOS
1082 			asprintf(&newfs, "/sbin/newfs_msdos");
1083 #endif
1084 			lbl->mnt_opts = "-tmsdos";
1085 			lbl->fsname = "msdos";
1086 			break;
1087 #ifdef USE_SYSVBFS
1088 		case FS_SYSVBFS:
1089 			asprintf(&newfs, "/sbin/newfs_sysvbfs");
1090 			lbl->mnt_opts = "-tsysvbfs";
1091 			lbl->fsname = "sysvbfs";
1092 			break;
1093 #endif
1094 #ifdef USE_EXT2FS
1095 		case FS_EX2FS:
1096 			asprintf(&newfs, "/sbin/newfs_ext2fs");
1097 			lbl->mnt_opts = "-text2fs";
1098 			lbl->fsname = "ext2fs";
1099 			break;
1100 #endif
1101 		}
1102 		if (lbl->pi_flags & PIF_NEWFS && newfs != NULL) {
1103 #ifdef USE_NEWFS_MSDOS
1104 			if (lbl->pi_fstype == FS_MSDOS) {
1105 			        /* newfs only if mount fails */
1106 			        if (run_program(RUN_SILENT | RUN_ERROR_OK,
1107 				    "mount -rt msdos /dev/%s /mnt2", dev) != 0)
1108 					error = run_program(
1109 					    RUN_DISPLAY | RUN_PROGRESS,
1110 					    "%s /dev/r%s",
1111 					    newfs, dev);
1112 				else {
1113 					run_program(RUN_SILENT | RUN_ERROR_OK,
1114 					    "umount /mnt2");
1115 					error = 0;
1116 				}
1117 			} else
1118 #endif
1119 			error = run_program(RUN_DISPLAY | RUN_PROGRESS,
1120 			    "%s /dev/r%s", newfs, dev);
1121 		} else {
1122 			/* We'd better check it isn't dirty */
1123 			error = fsck_preen(pm->diskdev, ptn, lbl->fsname, false);
1124 		}
1125 		free(newfs);
1126 		if (error != 0) {
1127 			free(devdev);
1128 			free(dev);
1129 			return error;
1130 		}
1131 
1132 		lbl->pi_flags ^= PIF_NEWFS;
1133 		md_pre_mount();
1134 
1135 		if (partman_go == 0 && lbl->pi_flags & PIF_MOUNT &&
1136 				lbl->mnt_opts != NULL) {
1137 			make_target_dir(lbl->pi_mount);
1138 			error = target_mount_do(lbl->mnt_opts, devdev, lbl->pi_mount);
1139 			if (error) {
1140 				msg_display(MSG_mountfail, dev, ' ', lbl->pi_mount);
1141 				process_menu(MENU_ok, NULL);
1142 				free(devdev);
1143 				free(dev);
1144 				return error;
1145 			}
1146 		}
1147 		free(devdev);
1148 		free(dev);
1149 	}
1150 	return 0;
1151 }
1152 
1153 int
1154 make_fstab(void)
1155 {
1156 	FILE *f;
1157 	int i, swap_dev = -1;
1158 	const char *dump_dev;
1159 	char *dev = NULL;
1160 	pm_devs_t *pm_i;
1161 #ifndef HAVE_TMPFS
1162 	pm_devs_t *pm_with_swap = NULL;
1163 #endif
1164 
1165 	/* Create the fstab. */
1166 	make_target_dir("/etc");
1167 	f = target_fopen("/etc/fstab", "w");
1168 	scripting_fprintf(NULL, "cat <<EOF >%s/etc/fstab\n", target_prefix());
1169 
1170 	if (logfp)
1171 		(void)fprintf(logfp,
1172 		    "Making %s/etc/fstab (%s).\n", target_prefix(), pm->diskdev);
1173 
1174 	if (f == NULL) {
1175 		msg_display(MSG_createfstab);
1176 		if (logfp)
1177 			(void)fprintf(logfp, "Failed to make /etc/fstab!\n");
1178 		process_menu(MENU_ok, NULL);
1179 #ifndef DEBUG
1180 		return 1;
1181 #else
1182 		f = stdout;
1183 #endif
1184 	}
1185 
1186 	scripting_fprintf(f, "# NetBSD /etc/fstab\n# See /usr/share/examples/"
1187 			"fstab/ for more examples.\n");
1188 
1189 	if (pm->no_part) {
1190 		/* single dk? target */
1191 		char buf[200], parent[200], swap[200], *prompt;
1192 		int res;
1193 
1194 		if (!get_name_and_parent(pm->diskdev, buf, parent))
1195 			goto done_with_disks;
1196 		scripting_fprintf(f, "NAME=%s\t/\tffs\trw\t\t1 1\n",
1197 		    buf);
1198 		if (!find_swap_part_on(parent, swap))
1199 			goto done_with_disks;
1200 		asprintf(&prompt, msg_string(MSG_Auto_add_swap_part),
1201 		    swap, parent);
1202 		res = ask_yesno(prompt);
1203 		free(prompt);
1204 		if (res)
1205 			scripting_fprintf(f, "NAME=%s\tnone"
1206 			    "\tswap\tsw,dp\t\t0 0\n", swap);
1207 		goto done_with_disks;
1208 	}
1209 
1210 	if (! partman_go) {
1211 		/* We want to process only one disk... */
1212 		pm_i = pm;
1213 		goto onlyonediskinfstab;
1214 	}
1215 	SLIST_FOREACH(pm_i, &pm_head, l) {
1216 		onlyonediskinfstab:
1217 		for (i = 0; i < getmaxpartitions(); i++) {
1218 			const char *s = "";
1219 			const char *mp = pm_i->bsdlabel[i].pi_mount;
1220 			const char *fstype = "ffs";
1221 			int fsck_pass = 0, dump_freq = 0;
1222 
1223 			if (dev != NULL)
1224 				free(dev);
1225 			if (pm_i->isspecial)
1226 				asprintf(&dev, "%s", pm_i->diskdev);
1227 			else
1228 				asprintf(&dev, "%s%c", pm_i->diskdev, 'a' + i);
1229 			if (dev == NULL)
1230 				return (ENOMEM);
1231 
1232 			if (!*mp) {
1233 				/*
1234 				 * No mount point specified, comment out line and
1235 				 * use /mnt as a placeholder for the mount point.
1236 				 */
1237 				s = "# ";
1238 				mp = "/mnt";
1239 			}
1240 
1241 			switch (pm_i->bsdlabel[i].pi_fstype) {
1242 			case FS_UNUSED:
1243 				continue;
1244 			case FS_BSDLFS:
1245 				/* If there is no LFS, just comment it out. */
1246 				if (!check_lfs_progs())
1247 					s = "# ";
1248 				fstype = "lfs";
1249 				/* FALLTHROUGH */
1250 			case FS_BSDFFS:
1251 				fsck_pass = (strcmp(mp, "/") == 0) ? 1 : 2;
1252 				dump_freq = 1;
1253 				break;
1254 			case FS_MSDOS:
1255 				fstype = "msdos";
1256 				break;
1257 			case FS_SWAP:
1258 				if (pm_i->isspecial)
1259 					continue;
1260 				if (swap_dev == -1) {
1261 					swap_dev = i;
1262 					dump_dev = ",dp";
1263 #ifndef HAVE_TMPFS
1264 					pm_with_swap = pm_i;
1265 #endif
1266 				} else {
1267 					dump_dev = "";
1268 				}
1269 				scripting_fprintf(f, "/dev/%s\t\tnone\tswap\tsw%s\t\t 0 0\n",
1270 					dev, dump_dev);
1271 				continue;
1272 #ifdef USE_SYSVBFS
1273 			case FS_SYSVBFS:
1274 				fstype = "sysvbfs";
1275 				make_target_dir("/stand");
1276 				break;
1277 #endif
1278 			default:
1279 				fstype = "???";
1280 				s = "# ";
1281 				break;
1282 			}
1283 			/* The code that remounts root rw doesn't check the partition */
1284 			if (strcmp(mp, "/") == 0 && !(pm_i->bsdlabel[i].pi_flags & PIF_MOUNT))
1285 				s = "# ";
1286 
1287 	 		scripting_fprintf(f,
1288 			  "%s/dev/%s\t\t%s\t%s\trw%s%s%s%s%s%s%s%s\t\t %d %d\n",
1289 			   s, dev, mp, fstype,
1290 			   pm_i->bsdlabel[i].pi_flags & PIF_LOG ? ",log" : "",
1291 			   pm_i->bsdlabel[i].pi_flags & PIF_MOUNT ? "" : ",noauto",
1292 			   pm_i->bsdlabel[i].pi_flags & PIF_ASYNC ? ",async" : "",
1293 			   pm_i->bsdlabel[i].pi_flags & PIF_NOATIME ? ",noatime" : "",
1294 			   pm_i->bsdlabel[i].pi_flags & PIF_NODEV ? ",nodev" : "",
1295 			   pm_i->bsdlabel[i].pi_flags & PIF_NODEVMTIME ? ",nodevmtime" : "",
1296 			   pm_i->bsdlabel[i].pi_flags & PIF_NOEXEC ? ",noexec" : "",
1297 			   pm_i->bsdlabel[i].pi_flags & PIF_NOSUID ? ",nosuid" : "",
1298 			   dump_freq, fsck_pass);
1299 	 		if (pm_i->isspecial)
1300 	 			/* Special device (such as dk*) have only one partition */
1301 	 			break;
1302 		}
1303 		/* Simple install, only one disk */
1304 		if (!partman_go)
1305 			break;
1306 	}
1307 done_with_disks:
1308 	if (tmp_ramdisk_size != 0) {
1309 #ifdef HAVE_TMPFS
1310 		scripting_fprintf(f, "tmpfs\t\t/tmp\ttmpfs\trw,-m=1777,-s=%"
1311 		    PRIi64 "\n",
1312 		    tmp_ramdisk_size * 512);
1313 #else
1314 		if (swap_dev != -1 && pm_with_swap != NULL)
1315 			scripting_fprintf(f, "/dev/%s%c\t\t/tmp\tmfs\trw,-s=%"
1316 			    PRIi64 "\n",
1317 			    pm_with_swap->diskdev, 'a' + swap_dev, tmp_ramdisk_size);
1318 		else
1319 			scripting_fprintf(f, "swap\t\t/tmp\tmfs\trw,-s=%"
1320 			    PRIi64 "\n",
1321 			    tmp_ramdisk_size);
1322 #endif
1323 	}
1324 
1325 	if (cdrom_dev[0] == 0)
1326 		get_default_cdrom(cdrom_dev, sizeof(cdrom_dev));
1327 
1328 	/* Add /kern, /proc and /dev/pts to fstab and make mountpoint. */
1329 	scripting_fprintf(f, "kernfs\t\t/kern\tkernfs\trw\n");
1330 	scripting_fprintf(f, "ptyfs\t\t/dev/pts\tptyfs\trw\n");
1331 	scripting_fprintf(f, "procfs\t\t/proc\tprocfs\trw\n");
1332 	scripting_fprintf(f, "/dev/%s\t\t/cdrom\tcd9660\tro,noauto\n",
1333 	    cdrom_dev);
1334 	scripting_fprintf(f, "%stmpfs\t\t/var/shm\ttmpfs\trw,-m1777,-sram%%25\n",
1335 	    tmpfs_on_var_shm() ? "" : "#");
1336 	make_target_dir("/kern");
1337 	make_target_dir("/proc");
1338 	make_target_dir("/dev/pts");
1339 	make_target_dir("/cdrom");
1340 	make_target_dir("/var/shm");
1341 
1342 	scripting_fprintf(NULL, "EOF\n");
1343 
1344 	if (dev != NULL)
1345 		free(dev);
1346 	fclose(f);
1347 	fflush(NULL);
1348 	return 0;
1349 }
1350 
1351 
1352 
1353 static int
1354 /*ARGSUSED*/
1355 foundffs(struct data *list, size_t num)
1356 {
1357 	int error;
1358 
1359 	if (num < 2 || strcmp(list[1].u.s_val, "/") == 0 ||
1360 	    strstr(list[2].u.s_val, "noauto") != NULL)
1361 		return 0;
1362 
1363 	error = fsck_preen(list[0].u.s_val, ' '-'a', "ffs", false);
1364 	if (error != 0)
1365 		return error;
1366 
1367 	error = target_mount("", list[0].u.s_val, ' '-'a', list[1].u.s_val);
1368 	if (error != 0) {
1369 		msg_display(MSG_mount_failed, list[0].u.s_val);
1370 		if (!ask_noyes(NULL))
1371 			return error;
1372 	}
1373 	return 0;
1374 }
1375 
1376 #ifdef USE_SYSVBFS
1377 static int
1378 /*ARGSUSED*/
1379 foundsysvbfs(struct data *list, size_t num)
1380 {
1381 	int error;
1382 
1383 	if (num < 2 || strcmp(list[1].u.s_val, "/") == 0 ||
1384 	    strstr(list[2].u.s_val, "noauto") != NULL)
1385 		return 0;
1386 
1387 	error = target_mount("", list[0].u.s_val, ' '-'a', list[1].u.s_val);
1388 	if (error != 0)
1389 		return error;
1390 	return 0;
1391 }
1392 #endif
1393 
1394 /*
1395  * Do an fsck. On failure, inform the user by showing a warning
1396  * message and doing menu_ok() before proceeding.
1397  * Returns 0 on success, or nonzero return code from fsck() on failure.
1398  */
1399 static int
1400 fsck_preen(const char *disk, int ptn, const char *fsname, bool silent)
1401 {
1402 	char *prog;
1403 	int error;
1404 
1405 	ptn = (ptn < 0)? 0 : 'a' + ptn;
1406 	if (fsname == NULL)
1407 		return 0;
1408 	/* first, check if fsck program exists, if not, assume ok */
1409 	asprintf(&prog, "/sbin/fsck_%s", fsname);
1410 	if (prog == NULL)
1411 		return 0;
1412 	if (access(prog, X_OK) != 0) {
1413 		free(prog);
1414 		return 0;
1415 	}
1416 	if (!strcmp(fsname,"ffs"))
1417 		fixsb(prog, disk, ptn);
1418 	error = run_program(silent? RUN_SILENT|RUN_ERROR_OK : 0, "%s -p -q /dev/r%s%c", prog, disk, ptn);
1419 	free(prog);
1420 	if (error != 0 && !silent) {
1421 		msg_display(MSG_badfs, disk, ptn, error);
1422 		if (ask_noyes(NULL))
1423 			error = 0;
1424 		/* XXX at this point maybe we should run a full fsck? */
1425 	}
1426 	return error;
1427 }
1428 
1429 /* This performs the same function as the etc/rc.d/fixsb script
1430  * which attempts to correct problems with ffs1 filesystems
1431  * which may have been introduced by booting a netbsd-current kernel
1432  * from between April of 2003 and January 2004. For more information
1433  * This script was developed as a response to NetBSD pr install/25138
1434  * Additional prs regarding the original issue include:
1435  *  bin/17910 kern/21283 kern/21404 port-macppc/23925 port-macppc/23926
1436  */
1437 static void
1438 fixsb(const char *prog, const char *disk, char ptn)
1439 {
1440 	int fd;
1441 	int rval;
1442 	union {
1443 		struct fs fs;
1444 		char buf[SBLOCKSIZE];
1445 	} sblk;
1446 	struct fs *fs = &sblk.fs;
1447 
1448 	snprintf(sblk.buf, sizeof(sblk.buf), "/dev/r%s%c",
1449 		disk, ptn == ' ' ? 0 : ptn);
1450 	fd = open(sblk.buf, O_RDONLY);
1451 	if (fd == -1)
1452 		return;
1453 
1454 	/* Read ffsv1 main superblock */
1455 	rval = pread(fd, sblk.buf, sizeof sblk.buf, SBLOCK_UFS1);
1456 	close(fd);
1457 	if (rval != sizeof sblk.buf)
1458 		return;
1459 
1460 	if (fs->fs_magic != FS_UFS1_MAGIC &&
1461 	    fs->fs_magic != FS_UFS1_MAGIC_SWAPPED)
1462 		/* Not FFSv1 */
1463 		return;
1464 	if (fs->fs_old_flags & FS_FLAGS_UPDATED)
1465 		/* properly updated fslevel 4 */
1466 		return;
1467 	if (fs->fs_bsize != fs->fs_maxbsize)
1468 		/* not messed up */
1469 		return;
1470 
1471 	/*
1472 	 * OK we have a munged fs, first 'upgrade' to fslevel 4,
1473 	 * We specify -b16 in order to stop fsck bleating that the
1474 	 * sb doesn't match the first alternate.
1475 	 */
1476 	run_program(RUN_DISPLAY | RUN_PROGRESS,
1477 	    "%s -p -b 16 -c 4 /dev/r%s%c", prog, disk, ptn);
1478 	/* Then downgrade to fslevel 3 */
1479 	run_program(RUN_DISPLAY | RUN_PROGRESS,
1480 	    "%s -p -c 3 /dev/r%s%c", prog, disk, ptn);
1481 }
1482 
1483 /*
1484  * fsck and mount the root partition.
1485  */
1486 static int
1487 mount_root(void)
1488 {
1489 	int	error;
1490 	int ptn = (pm->isspecial)? 0 - 'a' : pm->rootpart;
1491 
1492 	error = fsck_preen(pm->diskdev, ptn, "ffs", false);
1493 	if (error != 0)
1494 		return error;
1495 
1496 	md_pre_mount();
1497 
1498 	/* Mount /dev/<diskdev>a on target's "".
1499 	 * If we pass "" as mount-on, Prefixing will DTRT.
1500 	 * for now, use no options.
1501 	 * XXX consider -o remount in case target root is
1502 	 * current root, still readonly from single-user?
1503 	 */
1504 	return target_mount("", pm->diskdev, ptn, "");
1505 }
1506 
1507 /* Get information on the file systems mounted from the root filesystem.
1508  * Offer to convert them into 4.4BSD inodes if they are not 4.4BSD
1509  * inodes.  Fsck them.  Mount them.
1510  */
1511 
1512 int
1513 mount_disks(void)
1514 {
1515 	char *fstab;
1516 	int   fstabsize;
1517 	int   error;
1518 
1519 	static struct lookfor fstabbuf[] = {
1520 		{"/dev/", "/dev/%s %s ffs %s", "c", NULL, 0, 0, foundffs},
1521 		{"/dev/", "/dev/%s %s ufs %s", "c", NULL, 0, 0, foundffs},
1522 #ifdef USE_SYSVBFS
1523 		{"/dev/", "/dev/%s %s sysvbfs %s", "c", NULL, 0, 0,
1524 		    foundsysvbfs},
1525 #endif
1526 	};
1527 	static size_t numfstabbuf = sizeof(fstabbuf) / sizeof(struct lookfor);
1528 
1529 	/* First the root device. */
1530 	if (target_already_root())
1531 		/* avoid needing to call target_already_root() again */
1532 		targetroot_mnt[0] = 0;
1533 	else {
1534 		error = mount_root();
1535 		if (error != 0 && error != EBUSY)
1536 			return -1;
1537 	}
1538 
1539 	/* Check the target /etc/fstab exists before trying to parse it. */
1540 	if (target_dir_exists_p("/etc") == 0 ||
1541 	    target_file_exists_p("/etc/fstab") == 0) {
1542 		msg_display(MSG_noetcfstab, pm->diskdev);
1543 		process_menu(MENU_ok, NULL);
1544 		return -1;
1545 	}
1546 
1547 
1548 	/* Get fstab entries from the target-root /etc/fstab. */
1549 	fstabsize = target_collect_file(T_FILE, &fstab, "/etc/fstab");
1550 	if (fstabsize < 0) {
1551 		/* error ! */
1552 		msg_display(MSG_badetcfstab, pm->diskdev);
1553 		process_menu(MENU_ok, NULL);
1554 		return -2;
1555 	}
1556 	error = walk(fstab, (size_t)fstabsize, fstabbuf, numfstabbuf);
1557 	free(fstab);
1558 
1559 	return error;
1560 }
1561 
1562 int
1563 set_swap_if_low_ram(const char *disk, partinfo *pp)
1564 {
1565 	if (get_ramsize() <= 32)
1566 		return set_swap(disk, pp);
1567 	return 0;
1568 }
1569 
1570 int
1571 set_swap(const char *disk, partinfo *pp)
1572 {
1573 	int i;
1574 	char *cp;
1575 	int rval;
1576 
1577 	if (pp == NULL)
1578 		pp = pm->oldlabel;
1579 
1580 	for (i = 0; i < MAXPARTITIONS; i++) {
1581 		if (pp[i].pi_fstype != FS_SWAP)
1582 			continue;
1583 		asprintf(&cp, "/dev/%s%c", disk, 'a' + i);
1584 		rval = swapctl(SWAP_ON, cp, 0);
1585 		free(cp);
1586 		if (rval != 0)
1587 			return -1;
1588 	}
1589 
1590 	return 0;
1591 }
1592 
1593 int
1594 check_swap(const char *disk, int remove_swap)
1595 {
1596 	struct swapent *swap;
1597 	char *cp;
1598 	int nswap;
1599 	int l;
1600 	int rval = 0;
1601 
1602 	nswap = swapctl(SWAP_NSWAP, 0, 0);
1603 	if (nswap <= 0)
1604 		return 0;
1605 
1606 	swap = malloc(nswap * sizeof *swap);
1607 	if (swap == NULL)
1608 		return -1;
1609 
1610 	nswap = swapctl(SWAP_STATS, swap, nswap);
1611 	if (nswap < 0)
1612 		goto bad_swap;
1613 
1614 	l = strlen(disk);
1615 	while (--nswap >= 0) {
1616 		/* Should we check the se_dev or se_path? */
1617 		cp = swap[nswap].se_path;
1618 		if (memcmp(cp, "/dev/", 5) != 0)
1619 			continue;
1620 		if (memcmp(cp + 5, disk, l) != 0)
1621 			continue;
1622 		if (!isalpha(*(unsigned char *)(cp + 5 + l)))
1623 			continue;
1624 		if (cp[5 + l + 1] != 0)
1625 			continue;
1626 		/* ok path looks like it is for this device */
1627 		if (!remove_swap) {
1628 			/* count active swap areas */
1629 			rval++;
1630 			continue;
1631 		}
1632 		if (swapctl(SWAP_OFF, cp, 0) == -1)
1633 			rval = -1;
1634 	}
1635 
1636     done:
1637 	free(swap);
1638 	return rval;
1639 
1640     bad_swap:
1641 	rval = -1;
1642 	goto done;
1643 }
1644 
1645 #ifdef HAVE_BOOTXX_xFS
1646 char *
1647 bootxx_name(void)
1648 {
1649 	int fstype;
1650 	const char *bootxxname;
1651 	char *bootxx;
1652 
1653 	/* check we have boot code for the root partition type */
1654 	fstype = pm->bsdlabel[pm->rootpart].pi_fstype;
1655 	switch (fstype) {
1656 #if defined(BOOTXX_FFSV1) || defined(BOOTXX_FFSV2)
1657 	case FS_BSDFFS:
1658 		if (pm->bsdlabel[pm->rootpart].pi_flags & PIF_FFSv2) {
1659 #ifdef BOOTXX_FFSV2
1660 			bootxxname = BOOTXX_FFSV2;
1661 #else
1662 			bootxxname = NULL;
1663 #endif
1664 		} else {
1665 #ifdef BOOTXX_FFSV1
1666 			bootxxname = BOOTXX_FFSV1;
1667 #else
1668 			bootxxname = NULL;
1669 #endif
1670 		}
1671 		break;
1672 #endif
1673 #ifdef BOOTXX_LFSV2
1674 	case FS_BSDLFS:
1675 		bootxxname = BOOTXX_LFSV2;
1676 		break;
1677 #endif
1678 	default:
1679 		bootxxname = NULL;
1680 		break;
1681 	}
1682 
1683 	if (bootxxname == NULL)
1684 		return NULL;
1685 
1686 	asprintf(&bootxx, "%s/%s", BOOTXXDIR, bootxxname);
1687 	return bootxx;
1688 }
1689 #endif
1690 
1691 static int
1692 get_fsid_by_gptuuid(const char *str)
1693 {
1694 	int i;
1695 	uuid_t uuid;
1696 	uint32_t status;
1697 
1698 	uuid_from_string(str, &uuid, &status);
1699 	if (status == uuid_s_ok) {
1700 		for (i = 0; gpt_filesystems[i].id > 0; i++)
1701 			if (uuid_equal(&uuid, &(gpt_filesystems[i].uuid), NULL))
1702 				return gpt_filesystems[i].id;
1703 	}
1704 	return FS_OTHER;
1705 }
1706 
1707 const char *
1708 get_gptfs_by_id(int filesystem)
1709 {
1710 	int i;
1711 	for (i = 0; gpt_filesystems[i].id > 0; i++)
1712 		if (filesystem == gpt_filesystems[i].id)
1713 			return gpt_filesystems[i].name;
1714 	return NULL;
1715 }
1716 
1717 /* from dkctl.c */
1718 static int
1719 get_dkwedges_sort(const void *a, const void *b)
1720 {
1721 	const struct dkwedge_info *dkwa = a, *dkwb = b;
1722 	const daddr_t oa = dkwa->dkw_offset, ob = dkwb->dkw_offset;
1723 	return (oa < ob) ? -1 : (oa > ob) ? 1 : 0;
1724 }
1725 
1726 int
1727 get_dkwedges(struct dkwedge_info **dkw, const char *diskdev)
1728 {
1729 	int fd;
1730 	char buf[STRSIZE];
1731 	size_t bufsize;
1732 	struct dkwedge_list dkwl;
1733 
1734 	*dkw = NULL;
1735 	dkwl.dkwl_buf = *dkw;
1736 	dkwl.dkwl_bufsize = 0;
1737 	fd = opendisk(diskdev, O_RDONLY, buf, STRSIZE, 0);
1738 	if (fd < 0)
1739 		return -1;
1740 
1741 	for (;;) {
1742 		if (ioctl(fd, DIOCLWEDGES, &dkwl) == -1)
1743 			return -2;
1744 		if (dkwl.dkwl_nwedges == dkwl.dkwl_ncopied)
1745 			break;
1746 		bufsize = dkwl.dkwl_nwedges * sizeof(**dkw);
1747 		if (dkwl.dkwl_bufsize < bufsize) {
1748 			*dkw = realloc(dkwl.dkwl_buf, bufsize);
1749 			if (*dkw == NULL)
1750 				return -3;
1751 			dkwl.dkwl_buf = *dkw;
1752 			dkwl.dkwl_bufsize = bufsize;
1753 		}
1754 	}
1755 
1756 	if (dkwl.dkwl_nwedges > 0 && *dkw != NULL)
1757 		qsort(*dkw, dkwl.dkwl_nwedges, sizeof(**dkw), get_dkwedges_sort);
1758 
1759 	close(fd);
1760 	return dkwl.dkwl_nwedges;
1761 }
1762 
1763 /* XXX: rewrite */
1764 static int
1765 incoregpt(pm_devs_t *pm_cur, partinfo *lp)
1766 {
1767 	int i, num;
1768 	unsigned int p_num;
1769 	uint64_t p_start, p_size;
1770 	char *textbuf, *t, *tt, p_type[STRSIZE];
1771 	struct dkwedge_info *dkw;
1772 
1773 	num = get_dkwedges(&dkw, pm_cur->diskdev);
1774 	if (dkw != NULL) {
1775 		for (i = 0; i < num && i < MAX_WEDGES; i++)
1776 			run_program(RUN_SILENT, "dkctl %s delwedge %s",
1777 				pm_cur->diskdev, dkw[i].dkw_devname);
1778 		free (dkw);
1779 	}
1780 
1781 	if (collect(T_OUTPUT, &textbuf, "gpt show -u %s 2>/dev/null", pm_cur->diskdev) < 1)
1782 		return -1;
1783 
1784 	(void)strtok(textbuf, "\n"); /* ignore first line */
1785 	while ((t = strtok(NULL, "\n")) != NULL) {
1786 		i = 0; p_start = 0; p_size = 0; p_num = 0; strcpy(p_type, ""); /* init */
1787 		while ((tt = strsep(&t, " \t")) != NULL) {
1788 			if (strlen(tt) == 0)
1789 				continue;
1790 			if (i == 0)
1791 				p_start = strtouq(tt, NULL, 10);
1792 			if (i == 1)
1793 				p_size = strtouq(tt, NULL, 10);
1794 			if (i == 2)
1795 				p_num = strtouq(tt, NULL, 10);
1796 			if (i > 2 || (i == 2 && p_num == 0))
1797 				if (
1798 					strcmp(tt, "GPT") &&
1799 					strcmp(tt, "part") &&
1800 					strcmp(tt, "-")
1801 					)
1802 						strlcat(p_type, tt, STRSIZE);
1803 			i++;
1804 		}
1805 		if (p_start == 0 || p_size == 0)
1806 			continue;
1807 		else if (! strcmp(p_type, "Pritable"))
1808 			pm_cur->ptstart = p_start + p_size;
1809 		else if (! strcmp(p_type, "Sectable"))
1810 			pm_cur->ptsize = p_start - pm_cur->ptstart - 1;
1811 		else if (p_num == 0 && strlen(p_type) > 0)
1812 			/* Utilitary entry (PMBR, etc) */
1813 			continue;
1814 		else if (p_num == 0) {
1815 			/* Free space */
1816 			continue;
1817 		} else {
1818 			/* Usual partition */
1819 			lp[p_num].pi_size = p_size;
1820 			lp[p_num].pi_offset = p_start;
1821 			lp[p_num].pi_fstype = get_fsid_by_gptuuid(p_type);
1822 		}
1823 	}
1824 	free(textbuf);
1825 
1826 	return 0;
1827 }
1828 
1829 static bool
1830 is_gpt(const char *dev)
1831 {
1832 
1833 	check_available_binaries();
1834 
1835 	if (!have_gpt)
1836 		return false;
1837 
1838 	return run_program(RUN_SILENT | RUN_ERROR_OK,
1839 		"gpt -qr header %s", dev) == 0;
1840 }
1841