Home | History | Annotate | Line # | Download | only in i386
md.c revision 1.33
      1 /*	$NetBSD: md.c,v 1.33 2020/10/23 19:03:42 martin Exp $ */
      2 
      3 /*
      4  * Copyright 1997 Piermont Information Systems Inc.
      5  * All rights reserved.
      6  *
      7  * Based on code written by Philip A. Nelson for Piermont Information
      8  * Systems Inc.
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     13  * 1. Redistributions of source code must retain the above copyright
     14  *    notice, this list of conditions and the following disclaimer.
     15  * 2. Redistributions in binary form must reproduce the above copyright
     16  *    notice, this list of conditions and the following disclaimer in the
     17  *    documentation and/or other materials provided with the distribution.
     18  * 3. The name of Piermont Information Systems Inc. may not be used to endorse
     19  *    or promote products derived from this software without specific prior
     20  *    written permission.
     21  *
     22  * THIS SOFTWARE IS PROVIDED BY PIERMONT INFORMATION SYSTEMS INC. ``AS IS''
     23  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     25  * ARE DISCLAIMED. IN NO EVENT SHALL PIERMONT INFORMATION SYSTEMS INC. BE
     26  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     27  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     28  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     29  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     30  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     31  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
     32  * THE POSSIBILITY OF SUCH DAMAGE.
     33  */
     34 
     35 /* md.c -- i386 machine specific routines - also used by amd64 */
     36 
     37 #include <sys/param.h>
     38 #include <sys/sysctl.h>
     39 #include <sys/exec.h>
     40 #include <sys/utsname.h>
     41 #include <sys/types.h>
     42 #include <sys/stat.h>
     43 #include <machine/cpu.h>
     44 #include <assert.h>
     45 #include <stdio.h>
     46 #include <stddef.h>
     47 #include <util.h>
     48 #include <dirent.h>
     49 #include <termios.h>
     50 
     51 #include "defs.h"
     52 #include "md.h"
     53 #include "endian.h"
     54 #include "msg_defs.h"
     55 #include "menu_defs.h"
     56 
     57 #ifdef NO_LBA_READS		/* for testing */
     58 #undef BIFLAG_EXTINT13
     59 #define BIFLAG_EXTINT13	0
     60 #endif
     61 
     62 static struct biosdisk_info *biosdisk = NULL;
     63 static bool uefi_boot;
     64 
     65 /* prototypes */
     66 
     67 static bool get_bios_info(const char*, struct disk_partitions*, int*, int*, int*);
     68 static int mbr_root_above_chs(daddr_t);
     69 static int md_read_bootcode(const char *, struct mbr_sector *);
     70 static unsigned int get_bootmodel(void);
     71 
     72 static int conmib[] = { CTL_MACHDEP, CPU_CONSDEV };
     73 
     74 #define	BOOT_PART	(128*(MEG/512))
     75 #define	BOOT_PART_TYPE	PT_EFI_SYSTEM
     76 
     77 static const char * uefi_bootloaders[] = {
     78 	"/usr/mdec/bootia32.efi",
     79 	"/usr/mdec/bootx64.efi",
     80 };
     81 
     82 void
     83 md_init(void)
     84 {
     85 	char boot_method[100];
     86 	size_t len;
     87 
     88 	len = sizeof(boot_method);
     89 	if (sysctlbyname("machdep.bootmethod", boot_method, &len, NULL, 0)
     90 	    != -1) {
     91 		if (strcmp(boot_method, "BIOS") == 0)
     92 			uefi_boot = false;
     93 		else if (strcmp(boot_method, "UEFI") == 0)
     94 			uefi_boot = true;
     95 	}
     96 }
     97 
     98 void
     99 md_init_set_status(int flags)
    100 {
    101 	(void)flags;
    102 
    103 	/* Default to install same type of kernel as we are running */
    104 	set_kernel_set(get_bootmodel());
    105 }
    106 
    107 bool
    108 md_get_info(struct install_partition_desc *install)
    109 {
    110 	int bcyl = 0, bhead = 0, bsec = 0, res;
    111 
    112 	if (pm->no_mbr || pm->no_part)
    113 		return true;
    114 
    115 again:
    116 	if (pm->parts == NULL) {
    117 
    118 		const struct disk_partitioning_scheme *ps =
    119 		    select_part_scheme(pm, NULL, true, NULL);
    120 
    121 		if (!ps)
    122 			return false;
    123 
    124 		struct disk_partitions *parts =
    125 		   (*ps->create_new_for_disk)(pm->diskdev,
    126 		   0, pm->dlsize, true, NULL);
    127 		if (!parts)
    128 			return false;
    129 
    130 		pm->parts = parts;
    131 		if (ps->size_limit > 0 && pm->dlsize > ps->size_limit)
    132 			pm->dlsize = ps->size_limit;
    133 	}
    134 
    135 	if (get_bios_info(pm->diskdev, pm->parts, &bcyl, &bhead, &bsec)
    136 	    && pm->parts->pscheme->change_disk_geom != NULL)
    137 		pm->parts->pscheme->change_disk_geom(pm->parts,
    138 		    bcyl, bhead, bsec);
    139 	else
    140 		set_default_sizemult(pm->diskdev, MEG, pm->sectorsize);
    141 
    142 	/*
    143 	 * If the selected scheme does not need two-stage partitioning
    144 	 * (like GPT), do not bother to edit the outer partitions.
    145 	 */
    146 	if (pm->parts->pscheme->secondary_partitions == NULL ||
    147 	    pm->parts->pscheme->secondary_scheme == NULL)
    148 		return true;
    149 
    150 	if (pm->no_mbr || pm->no_part)
    151 		return true;
    152 
    153 	res = edit_outer_parts(pm->parts);
    154 	if (res == 0)
    155 		return false;
    156 	else if (res == 1)
    157 		return true;
    158 
    159 	pm->parts->pscheme->destroy_part_scheme(pm->parts);
    160 	pm->parts = NULL;
    161 	goto again;
    162 }
    163 
    164 /*
    165  * md back-end code for menu-driven BSD disklabel editor.
    166  */
    167 int
    168 md_make_bsd_partitions(struct install_partition_desc *install)
    169 {
    170 	return make_bsd_partitions(install);
    171 }
    172 
    173 /*
    174  * any additional partition validation
    175  */
    176 bool
    177 md_check_partitions(struct install_partition_desc *install)
    178 {
    179 	int rval;
    180 	char *bootxx;
    181 
    182 	/* if booting via UEFI no boot blocks are needed */
    183 	if (uefi_boot)
    184 		return true;
    185 
    186 	/* check we have boot code for the root partition type */
    187 	bootxx = bootxx_name(install);
    188 	rval = access(bootxx, R_OK);
    189 	free(bootxx);
    190 	if (rval == 0)
    191 		return true;
    192 	process_menu(MENU_ok, __UNCONST(MSG_No_Bootcode));
    193 	return false;
    194 }
    195 
    196 /*
    197  * hook called before writing new disklabel.
    198  */
    199 bool
    200 md_pre_disklabel(struct install_partition_desc *install,
    201     struct disk_partitions *parts)
    202 {
    203 
    204 	if (parts->parent == NULL)
    205 		return true;	/* no outer partitions */
    206 
    207 	parts = parts->parent;
    208 
    209 	msg_display_subst(MSG_dofdisk, 3, parts->disk,
    210 	    msg_string(parts->pscheme->name),
    211 	    msg_string(parts->pscheme->short_name));
    212 
    213 	/* write edited "MBR" onto disk. */
    214 	if (!parts->pscheme->write_to_disk(parts)) {
    215 		msg_display(MSG_wmbrfail);
    216 		process_menu(MENU_ok, NULL);
    217 		return false;
    218 	}
    219 	return true;
    220 }
    221 
    222 /*
    223  * hook called after writing disklabel to new target disk.
    224  */
    225 bool
    226 md_post_disklabel(struct install_partition_desc *install,
    227     struct disk_partitions *parts)
    228 {
    229 	return true;
    230 }
    231 
    232 /*
    233  * Do all legacy bootblock update/setup here
    234  */
    235 static int
    236 md_post_newfs_bios(struct install_partition_desc *install)
    237 {
    238 	int ret;
    239 	size_t len;
    240 	char boot_options[1024];
    241 	char *bootxx_filename;
    242 	/*
    243 	 * XXX - this code retains a lot of cruft from when we went
    244 	 * to great pains to exclude installboot from the ramdisk
    245 	 * for size reasons and should be rewritten.
    246 	 */
    247 	static const char *consoles[]={
    248         	"pc", /* CONSDEV_PC */
    249 		"com0", /* CONSDEV_COM0 */
    250 		"com1", /* CONSDEV_COM1 */
    251 		"com2", /* CONSDEV_COM2 */
    252 		"com3", /* CONSDEV_COM3 */
    253 		"com0kbd", /* CONSDEV_COM0KBD */
    254 		"com1kbd", /* CONSDEV_COM1KBD */
    255 		"com2kbd", /* CONSDEV_COM2KBD */
    256 		"com3kbd" /* CONSDEV_COM3KBD */ };
    257 	static struct x86_boot_params boottype =
    258 		{sizeof boottype, 0, 5, 0, 9600, { '\0' }, "", 0};
    259 	struct termios t;
    260 	dev_t condev;
    261 
    262 	if (pm == NULL || !pm->no_part) {
    263 		/*
    264 		 * Get console device, should either be ttyE0 or tty0n.
    265 		 * Too hard to double check, so just 'know' the device numbers.
    266 		 */
    267 		len = sizeof condev;
    268 		if (sysctl(conmib, __arraycount(conmib), &condev, &len, NULL,
    269 		    0) != -1 && (condev & ~3) == 0x800) {
    270 			/* Motherboard serial port */
    271 			boottype.bp_consdev = (condev & 3) + 1;
    272 			/* Defaulting the baud rate to that of stdin should
    273 			   suffice */
    274 			if (tcgetattr(0, &t) != -1)
    275 				boottype.bp_conspeed = t.c_ispeed;
    276 		}
    277 
    278 		process_menu(MENU_getboottype, &boottype);
    279 		msg_fmt_display(MSG_dobootblks, "%s", pm->diskdev);
    280 		if (boottype.bp_consdev == ~0u)
    281 			/* Use existing bootblocks */
    282 			return 0;
    283 	}
    284 
    285 	ret = cp_to_target("/usr/mdec/boot", "/boot");
    286 	if (ret)
    287 		return ret;
    288 	if (pm && pm->no_part)
    289 		return 0;
    290 
    291         bootxx_filename = bootxx_name(install);
    292         if (bootxx_filename != NULL) {
    293 		char rdev[PATH_MAX];
    294 
    295 		install->infos[0].parts->pscheme->get_part_device(
    296 		    install->infos[0].parts, install->infos[0].cur_part_id,
    297 		    rdev, sizeof rdev, NULL, raw_dev_name, true, true);
    298 
    299 		snprintf(boot_options, sizeof boot_options,
    300 		    "console=%s,speed=%u", consoles[boottype.bp_consdev],
    301 		    boottype.bp_conspeed);
    302                	ret = run_program(RUN_DISPLAY,
    303                 	    "/usr/sbin/installboot -f -o %s %s %s",
    304 			    boot_options, rdev, bootxx_filename);
    305                 free(bootxx_filename);
    306         } else {
    307                 ret = -1;
    308 	}
    309 
    310         if (ret != 0)
    311                 process_menu(MENU_ok,
    312                     __UNCONST("Warning: disk is probably not bootable"));
    313 
    314 	return ret;
    315 }
    316 
    317 /*
    318  * Make sure our bootloader(s) are in the proper directory in the boot
    319  * boot partition (or update them).
    320  */
    321 static int
    322 copy_uefi_boot(const struct part_usage_info *boot)
    323 {
    324 	char dev[MAXPATHLEN], path[MAXPATHLEN];
    325 	size_t i;
    326 	int err;
    327 
    328 	if (!boot->parts->pscheme->get_part_device(boot->parts,
    329 	    boot->cur_part_id, dev, sizeof(dev), NULL, plain_name, true, true))
    330 		return -1;
    331 
    332 	/*
    333 	 * We should have a valid file system on that partition.
    334 	 * Try to mount it and check if there is a /EFI in there.
    335 	 */
    336 	if (boot->mount[0])
    337 		strlcpy(path, boot->mount, sizeof(path));
    338 	else
    339 		strcpy(path, "/mnt");
    340 
    341 	if (!(boot->instflags & PUIINST_MOUNT)) {
    342 		make_target_dir(path);
    343 		err = target_mount("", dev, path);
    344 		if (err != 0)
    345 			return err;
    346 	}
    347 
    348 	strlcat(path, "/EFI/boot", sizeof(path));
    349 	make_target_dir(path);
    350 
    351 	for (i = 0; i < __arraycount(uefi_bootloaders); i++) {
    352 		if (access(uefi_bootloaders[i], R_OK) != 0)
    353 			continue;
    354 		err = cp_to_target(uefi_bootloaders[i], path);
    355 		if (err)
    356 			return err;
    357 	}
    358 
    359 	return 0;
    360 }
    361 
    362 /*
    363  * Find (U)EFI boot partition and install/update bootloaders
    364  */
    365 static int
    366 md_post_newfs_uefi(struct install_partition_desc *install)
    367 {
    368 	size_t i;
    369 
    370 	for (i = 0; i < install->num; i++) {
    371 		if (!(install->infos[i].instflags & PUIINST_BOOT))
    372 			continue;
    373 
    374 		return copy_uefi_boot(&install->infos[i]);
    375 	}
    376 
    377 	return -1;	/* no EFI boot partition found */
    378 }
    379 
    380 /*
    381  * hook called after upgrade() or install() has finished setting
    382  * up the target disk but immediately before the user is given the
    383  * ``disks are now set up'' message.
    384  */
    385 int
    386 md_post_newfs(struct install_partition_desc *install)
    387 {
    388 
    389 	return uefi_boot ? md_post_newfs_uefi(install)
    390 	    : md_post_newfs_bios(install);
    391 }
    392 
    393 int
    394 md_post_extract(struct install_partition_desc *install)
    395 {
    396 #if defined(__amd64__)
    397 	if (get_kernel_set() == SET_KERNEL_2) {
    398 		int ret;
    399 
    400 		ret = cp_within_target("/usr/mdec/prekern", "/prekern", 0);
    401 		if (ret)
    402 			return ret;
    403 	}
    404 #endif
    405 	return 0;
    406 }
    407 
    408 void
    409 md_cleanup_install(struct install_partition_desc *install)
    410 {
    411 	size_t len;
    412 	dev_t condev;
    413 
    414 #ifndef DEBUG
    415 	enable_rc_conf();
    416 	add_rc_conf("wscons=YES\n");
    417 
    418 # if defined(__i386__) && defined(SET_KERNEL_TINY)
    419 	/*
    420 	 * For GENERIC_TINY, do not enable any extra screens or wsmux.
    421 	 * Otherwise, run getty on 4 VTs.
    422 	 */
    423 	if (get_kernel_set() == SET_KERNEL_TINY)
    424 		run_program(RUN_CHROOT,
    425                             "sed -an -e '/^screen/s/^/#/;/^mux/s/^/#/;"
    426 			    "H;$!d;g;w /etc/wscons.conf' /etc/wscons.conf");
    427 	else
    428 # endif
    429 		run_program(RUN_CHROOT,
    430 			    "sed -an -e '/^ttyE[1-9]/s/off/on/;"
    431 			    "H;$!d;g;w /etc/ttys' /etc/ttys");
    432 
    433 #endif
    434 
    435 	/*
    436 	 * Get console device, should either be ttyE0 or tty0n.
    437 	 * Too hard to double check, so just 'know' the device numbers.
    438 	 */
    439 	len = sizeof condev;
    440 	if (sysctl(conmib, __arraycount(conmib), &condev, &len, NULL, 0) != -1
    441 	    && (condev & ~3) != 0x800) {
    442 
    443 		/*
    444 		 * Current console is not com*, assume ttyE*.
    445 		 * Modify /etc/ttys to use wsvt25 for all ports.
    446 		 */
    447 
    448 		run_program(RUN_CHROOT,
    449 			    "sed -an -e 's/vt100/wsvt25/g;"
    450 			    "H;$!d;g;w  /etc/ttys' /etc/ttys");
    451 	}
    452 }
    453 
    454 int
    455 md_pre_update(struct install_partition_desc *install)
    456 {
    457 	return 1;
    458 }
    459 
    460 /* Upgrade support */
    461 int
    462 md_update(struct install_partition_desc *install)
    463 {
    464 	md_post_newfs(install);
    465 	return 1;
    466 }
    467 
    468 int
    469 md_check_mbr(struct disk_partitions *parts, mbr_info_t *mbri, bool quiet)
    470 {
    471 	mbr_info_t *ext;
    472 	struct mbr_partition *p;
    473 	const char *bootcode;
    474 	daddr_t inst_start, inst_size;
    475 	int i, names, fl, ofl;
    476 #define	ACTIVE_FOUND	0x0100
    477 #define	NETBSD_ACTIVE	0x0200
    478 #define	NETBSD_NAMED	0x0400
    479 #define	ACTIVE_NAMED	0x0800
    480 
    481 	root_limit = 0;
    482 	if (parts->pscheme->guess_install_target == NULL ||
    483 	    !parts->pscheme->guess_install_target(parts, &inst_start,
    484 	    &inst_size)) {
    485 		inst_start = parts->disk_start;
    486 		inst_size = parts->disk_size;
    487 	}
    488 
    489 	if (biosdisk != NULL && (biosdisk->bi_flags & BIFLAG_EXTINT13) == 0) {
    490 		if (mbr_root_above_chs(inst_start)) {
    491 			if (quiet)
    492 				return 0;
    493 			msg_display(MSG_partabovechs);
    494 			if (!ask_noyes(NULL))
    495 				return 1;
    496 			/* The user is shooting themselves in the foot here...*/
    497 		} else {
    498 			if (parts->pscheme->size_limit)
    499 				root_limit = min(parts->pscheme->size_limit,
    500 				    parts->disk_size);
    501 			else
    502 				root_limit = parts->disk_size;
    503 		}
    504 	}
    505 
    506 	/*
    507 	 * Ensure the install partition (at sector inst_start) and the active
    508 	 * partition are bootable.
    509 	 * Determine whether the bootselect code is needed.
    510 	 * Note that MBR_BS_NEWMBR is always set, so we ignore it!
    511 	 */
    512 	fl = 0;
    513 	names = 0;
    514 	for (ext = mbri; ext != NULL; ext = ext->extended) {
    515 		p = ext->mbr.mbr_parts;
    516 		for (i = 0; i < MBR_PART_COUNT; p++, i++) {
    517 			if (p->mbrp_flag == MBR_PFLAG_ACTIVE) {
    518 				fl |= ACTIVE_FOUND;
    519 			    if (ext->sector + p->mbrp_start == inst_start)
    520 				fl |= NETBSD_ACTIVE;
    521 			}
    522 			if (ext->mbrb.mbrbs_nametab[i][0] == 0) {
    523 				/* No bootmenu label... */
    524 				if (ext->sector == 0)
    525 					continue;
    526 				if (ext->sector + p->mbrp_start == inst_start)
    527 					/*
    528 					 * Have installed into an extended ptn
    529 					 * force name & bootsel...
    530 					 */
    531 					names++;
    532 				continue;
    533 			}
    534 			/* Partition has a bootmenu label... */
    535 			if (ext->sector != 0)
    536 				fl |= MBR_BS_EXTLBA;
    537 			if (ext->sector + p->mbrp_start == inst_start)
    538 				fl |= NETBSD_NAMED;
    539 			else if (p->mbrp_flag == MBR_PFLAG_ACTIVE)
    540 				fl |= ACTIVE_NAMED;
    541 			else
    542 				names++;
    543 		}
    544 	}
    545 	if (!(fl & ACTIVE_FOUND))
    546 		fl |= NETBSD_ACTIVE;
    547 	if (fl & NETBSD_NAMED && fl & NETBSD_ACTIVE)
    548 		fl |= ACTIVE_NAMED;
    549 
    550 	if ((names > 0 || !(fl & NETBSD_ACTIVE)) &&
    551 	    (!(fl & NETBSD_NAMED) || !(fl & ACTIVE_NAMED))) {
    552 		/*
    553 		 * There appear to be multiple bootable partitions, but they
    554 		 * don't all have bootmenu texts.
    555 		 */
    556 		if (quiet)
    557 			return 0;
    558 
    559 		msg_display(MSG_missing_bootmenu_text);
    560 		if (ask_yesno(NULL))
    561 			return 1;
    562 	}
    563 
    564 	if ((fl & MBR_BS_EXTLBA) &&
    565 	    (biosdisk == NULL || !(biosdisk->bi_flags & BIFLAG_EXTINT13))) {
    566 		/* Need unsupported LBA reads to read boot sectors */
    567 		if (quiet)
    568 			return 0;
    569 
    570 		msg_display(MSG_no_extended_bootmenu);
    571 		if (!ask_noyes(NULL))
    572 			return 1;
    573 	}
    574 
    575 	/* Sort out the name of the mbr code we need */
    576 	if (names > 1 ||
    577 	    (parts->num_part > 1 && (fl & (NETBSD_NAMED | ACTIVE_NAMED)))) {
    578 		/* Need bootselect code */
    579 		fl |= MBR_BS_ACTIVE;
    580 		bootcode = fl & MBR_BS_EXTLBA ? _PATH_BOOTEXT : _PATH_BOOTSEL;
    581 	} else {
    582 		bootcode = _PATH_MBR;
    583 	}
    584 
    585 	fl &=  MBR_BS_ACTIVE | MBR_BS_EXTLBA;
    586 
    587 	/* Look at what is installed */
    588 	ofl = mbri->mbrb.mbrbs_flags;
    589 	if (ofl == 0) {
    590 		/* Check there is some bootcode at all... */
    591 		if (mbri->mbr.mbr_magic != htole16(MBR_MAGIC) ||
    592 		    mbri->mbr.mbr_jmpboot[0] == 0 ||
    593 		    mbr_root_above_chs(inst_start))
    594 			/* Existing won't do, force update */
    595 			fl |= MBR_BS_NEWMBR;
    596 	}
    597 	ofl = mbri->oflags & (MBR_BS_ACTIVE | MBR_BS_EXTLBA);
    598 
    599 	if (!quiet) {
    600 		if (fl & ~ofl || (fl == 0 && ofl & MBR_BS_ACTIVE)) {
    601 			/* Existing boot code isn't the right one... */
    602 			if (fl & MBR_BS_ACTIVE)
    603 				msg_display(MSG_installbootsel);
    604 			else
    605 				msg_display(MSG_installmbr);
    606 		} else
    607 			/* Existing code would (probably) be ok */
    608 			msg_display(MSG_updatembr);
    609 
    610 		if (!ask_yesno(NULL))
    611 			/* User doesn't want to update mbr code */
    612 			return 2;
    613 	}
    614 
    615 	if (md_read_bootcode(bootcode, &mbri->mbr) == 0)
    616 		/* update suceeded - to memory copy */
    617 		return 2;
    618 
    619 	/* This shouldn't happen since the files are in the floppy fs... */
    620 	msg_fmt_display("Can't find %s", "%s", bootcode);
    621 	return ask_reedit(parts);
    622 }
    623 
    624 bool
    625 md_parts_use_wholedisk(struct disk_partitions *parts)
    626 {
    627 	struct disk_part_info boot_part = {
    628 		.size = BOOT_PART,
    629 		.fs_type = FS_MSDOS, .fs_sub_type = MBR_PTYPE_FAT32L,
    630 	};
    631 
    632 	if (!uefi_boot)
    633 		return parts_use_wholedisk(parts, 0, NULL);
    634 
    635 	boot_part.nat_type = parts->pscheme->get_generic_part_type(
    636 	    PT_EFI_SYSTEM);
    637 
    638 	return parts_use_wholedisk(parts, 1, &boot_part);
    639 }
    640 
    641 static bool
    642 get_bios_info(const char *dev, struct disk_partitions *parts, int *bcyl,
    643     int *bhead, int *bsec)
    644 {
    645 	static struct disklist *disklist = NULL;
    646 	static int mib[2] = {CTL_MACHDEP, CPU_DISKINFO};
    647 	int i;
    648 	size_t len;
    649 	struct biosdisk_info *bip;
    650 	struct nativedisk_info *nip = NULL, *nat;
    651 	int cyl, head, sec;
    652 
    653 	if (disklist == NULL) {
    654 		if (sysctl(mib, 2, NULL, &len, NULL, 0) < 0)
    655 			goto nogeom;
    656 		disklist = malloc(len);
    657 		if (disklist == NULL) {
    658 			fprintf(stderr, "Out of memory\n");
    659 			return false;
    660 		}
    661 		sysctl(mib, 2, disklist, &len, NULL, 0);
    662 	}
    663 
    664 	for (i = 0; i < disklist->dl_nnativedisks; i++) {
    665 		nat = &disklist->dl_nativedisks[i];
    666 		if (!strcmp(dev, nat->ni_devname)) {
    667 			nip = nat;
    668 			break;
    669 		}
    670 	}
    671 	if (nip == NULL || nip->ni_nmatches == 0) {
    672 nogeom:
    673 		if (nip != NULL)
    674 			msg_fmt_display(MSG_nobiosgeom, "%d%d%d",
    675 			    pm->dlcyl, pm->dlhead, pm->dlsec);
    676 		if (guess_biosgeom_from_parts(parts, &cyl, &head, &sec) >= 0
    677 		    && nip != NULL)
    678 		{
    679 			msg_fmt_display_add(MSG_biosguess, "%d%d%d",
    680 			    cyl, head, sec);
    681 		}
    682 		biosdisk = NULL;
    683 	} else {
    684 		guess_biosgeom_from_parts(parts, &cyl, &head, &sec);
    685 		if (nip->ni_nmatches == 1) {
    686 			bip = &disklist->dl_biosdisks[nip->ni_biosmatches[0]];
    687 			msg_display(MSG_onebiosmatch);
    688 			msg_table_add(MSG_onebiosmatch_header);
    689 			msg_fmt_table_add(MSG_onebiosmatch_row, "%d%d%d%d%u%u",
    690 			    bip->bi_dev, bip->bi_cyl, bip->bi_head, bip->bi_sec,
    691 			    (unsigned)bip->bi_lbasecs,
    692 			    (unsigned)(bip->bi_lbasecs / (1000000000 / 512)));
    693 			msg_display_add(MSG_biosgeom_advise);
    694 			biosdisk = bip;
    695 			process_menu(MENU_biosonematch, &biosdisk);
    696 		} else {
    697 			msg_display(MSG_biosmultmatch);
    698 			msg_table_add(MSG_biosmultmatch_header);
    699 			for (i = 0; i < nip->ni_nmatches; i++) {
    700 				bip = &disklist->dl_biosdisks[
    701 							nip->ni_biosmatches[i]];
    702 				msg_fmt_table_add(MSG_biosmultmatch_row,
    703 				    "%d%d%d%d%d%u%u", i,
    704 				    bip->bi_dev, bip->bi_cyl, bip->bi_head,
    705 				    bip->bi_sec, (unsigned)bip->bi_lbasecs,
    706 				    (unsigned)bip->bi_lbasecs/(1000000000/512));
    707 			}
    708 			process_menu(MENU_biosmultmatch, &i);
    709 			if (i == -1)
    710 				biosdisk = NULL;
    711 			else
    712 				biosdisk = &disklist->dl_biosdisks[
    713 							nip->ni_biosmatches[i]];
    714 		}
    715 	}
    716 	if (biosdisk == NULL) {
    717 		*bcyl = cyl;
    718 		*bhead = head;
    719 		*bsec = sec;
    720 		if (nip != NULL)
    721 			set_bios_geom(parts, bcyl, bhead, bsec);
    722 	} else {
    723 		*bcyl = biosdisk->bi_cyl;
    724 		*bhead = biosdisk->bi_head;
    725 		*bsec = biosdisk->bi_sec;
    726 	}
    727 	return true;
    728 }
    729 
    730 static int
    731 mbr_root_above_chs(daddr_t ptstart)
    732 {
    733 	return ptstart + (daddr_t)DEFROOTSIZE * (daddr_t)(MEG / 512)
    734 	    >= pm->max_chs;
    735 }
    736 
    737 /* returns false if no write-back of parts is required */
    738 bool
    739 md_mbr_update_check(struct disk_partitions *parts, mbr_info_t *mbri)
    740 {
    741 	struct mbr_partition *mbrp;
    742 	int i, netbsdpart = -1, oldbsdpart = -1, oldbsdcount = 0;
    743 
    744 	if (pm->no_mbr || pm->no_part)
    745 		return false;
    746 
    747 	mbrp = &mbri->mbr.mbr_parts[0];
    748 
    749 	for (i = 0; i < MBR_PART_COUNT; i++) {
    750 		if (mbrp[i].mbrp_type == MBR_PTYPE_386BSD) {
    751 			oldbsdpart = i;
    752 			oldbsdcount++;
    753 		} else if (mbrp[i].mbrp_type == MBR_PTYPE_NETBSD)
    754 			netbsdpart = i;
    755 	}
    756 
    757 	if (netbsdpart == -1 && oldbsdcount == 1) {
    758 		mbrp[oldbsdpart].mbrp_type = MBR_PTYPE_NETBSD;
    759 		return true;
    760 	}
    761 
    762 	return false;
    763 }
    764 
    765 /*
    766  * Read MBR code from a file.
    767  * The existing partition table and bootselect configuration is kept.
    768  */
    769 static int
    770 md_read_bootcode(const char *path, struct mbr_sector *mbrs)
    771 {
    772 	int fd;
    773 	struct stat st;
    774 	size_t len;
    775 	struct mbr_sector new_mbr;
    776 	uint32_t dsn;
    777 
    778 	fd = open(path, O_RDONLY);
    779 	if (fd < 0)
    780 		return -1;
    781 
    782 	if (fstat(fd, &st) < 0 || st.st_size != sizeof *mbrs) {
    783 		close(fd);
    784 		return -1;
    785 	}
    786 
    787 	if (read(fd, &new_mbr, sizeof new_mbr) != sizeof new_mbr) {
    788 		close(fd);
    789 		return -1;
    790 	}
    791 	close(fd);
    792 
    793 	if (new_mbr.mbr_bootsel_magic != htole16(MBR_BS_MAGIC))
    794 		return -1;
    795 
    796 	if (mbrs->mbr_bootsel_magic == htole16(MBR_BS_MAGIC)) {
    797 		len = offsetof(struct mbr_sector, mbr_bootsel);
    798 	} else
    799 		len = offsetof(struct mbr_sector, mbr_parts);
    800 
    801 	/* Preserve the 'drive serial number' - especially for Vista */
    802 	dsn = mbrs->mbr_dsn;
    803 	memcpy(mbrs, &new_mbr, len);
    804 	mbrs->mbr_dsn = dsn;
    805 
    806 	/* Keep flags from object file - indicate the properties */
    807 	mbrs->mbr_bootsel.mbrbs_flags = new_mbr.mbr_bootsel.mbrbs_flags;
    808 	mbrs->mbr_magic = htole16(MBR_MAGIC);
    809 
    810 	return 0;
    811 }
    812 
    813 static unsigned int
    814 get_bootmodel(void)
    815 {
    816 #if defined(__i386__)
    817 	struct utsname ut;
    818 #ifdef DEBUG
    819 	char *envstr;
    820 
    821 	envstr = getenv("BOOTMODEL");
    822 	if (envstr != NULL)
    823 		return atoi(envstr);
    824 #endif
    825 
    826 	if (uname(&ut) < 0)
    827 		ut.version[0] = 0;
    828 
    829 #if defined(SET_KERNEL_TINY)
    830 	if (strstr(ut.version, "TINY") != NULL)
    831 		return SET_KERNEL_TINY;
    832 #endif
    833 #if defined(SET_KERNEL_PS2)
    834 	if (strstr(ut.version, "PS2") != NULL)
    835 		return SET_KERNEL_PS2;
    836 #endif
    837 #endif
    838 	return SET_KERNEL_GENERIC;
    839 }
    840 
    841 
    842 int
    843 md_pre_mount(struct install_partition_desc *install, size_t ndx)
    844 {
    845 	return 0;
    846 }
    847 
    848 #ifdef HAVE_GPT
    849 /*
    850  * New GPT partitions have been written, update bootloader or remember
    851  * data untill needed in md_post_newfs
    852  */
    853 bool
    854 md_gpt_post_write(struct disk_partitions *parts, part_id root_id,
    855     bool root_is_new, part_id efi_id, bool efi_is_new)
    856 {
    857 	struct disk_part_info info;
    858 
    859 	if (root_id != NO_PART) {
    860 		/* we always update the gpt boot record for now */
    861 		if (!parts->pscheme->get_part_info(parts, root_id, &info))
    862 			return false;
    863 		if (run_program(RUN_SILENT, "gpt biosboot -b %" PRIu64 " %s",
    864 		    info.start, parts->disk) != 0)
    865 			return false;
    866 	}
    867 
    868 	return true;
    869 }
    870 #endif
    871 
    872 /*
    873  * When we do an UEFI install, we have completely different default
    874  * partitions and need to adjust the description at runtime.
    875  */
    876 void
    877 x86_md_part_defaults(struct pm_devs *cur_pm, struct part_usage_info **partsp,
    878     size_t *num_usage_infos)
    879 {
    880 	static const struct part_usage_info uefi_boot_part =
    881 	{
    882 		.size = BOOT_PART,
    883 		.type = BOOT_PART_TYPE,
    884 		.instflags = PUIINST_NEWFS|PUIINST_BOOT,
    885 		.fs_type = FS_MSDOS, .fs_version = MBR_PTYPE_FAT32L,
    886 		.flags = PUIFLAG_ADD_OUTER,
    887 	};
    888 
    889 	struct disk_partitions *parts;
    890 	struct part_usage_info *new_usage, *boot;
    891 	struct disk_part_info info;
    892 	size_t num;
    893 	part_id pno;
    894 
    895 	if (!uefi_boot)
    896 		return;		/* legacy defaults apply */
    897 
    898 	/*
    899 	 * Insert a UEFI boot partition at the beginning of the array
    900 	 */
    901 
    902 	/* create space for new description */
    903 	num = *num_usage_infos + 1;
    904 	new_usage = realloc(*partsp, sizeof(*new_usage)*num);
    905 	if (new_usage == NULL)
    906 		return;
    907 	*partsp = new_usage;
    908 	*num_usage_infos = num;
    909 	boot = new_usage;
    910 	memmove(boot+1, boot, sizeof(*boot)*(num-1));
    911 	*boot = uefi_boot_part;
    912 
    913 	/*
    914 	 * Check if the UEFI partition already exists
    915 	 */
    916 	parts = pm->parts;
    917 	if (parts->parent != NULL)
    918 		parts = parts->parent;
    919 	for (pno = 0; pno < parts->num_part; pno++) {
    920 		if (!parts->pscheme->get_part_info(parts, pno, &info))
    921 			continue;
    922 		if (info.nat_type->generic_ptype != boot->type)
    923 			continue;
    924 		boot->flags &= ~PUIFLAG_ADD_OUTER;
    925 		boot->flags |= PUIFLG_IS_OUTER|PUIFLG_ADD_INNER;
    926 		boot->size = info.size;
    927 		boot->cur_start = info.start;
    928 		boot->cur_flags = info.flags;
    929 		break;
    930 	}
    931 }
    932 
    933 /* no need to install bootblock if installing for UEFI */
    934 bool
    935 x86_md_need_bootblock(struct install_partition_desc *install)
    936 {
    937 
    938 	return !uefi_boot;
    939 }
    940