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