md.c revision 1.3
1/*	$NetBSD: md.c,v 1.3 2014/08/11 00:31:22 riz 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 <stdio.h>
45#include <stddef.h>
46#include <util.h>
47#include <dirent.h>
48#include <termios.h>
49
50#include "defs.h"
51#include "md.h"
52#include "endian.h"
53#include "msg_defs.h"
54#include "menu_defs.h"
55
56#ifdef NO_LBA_READS		/* for testing */
57#undef BIFLAG_EXTINT13
58#define BIFLAG_EXTINT13	0
59#endif
60
61static struct biosdisk_info *biosdisk = NULL;
62
63/* prototypes */
64
65static int get_bios_info(char *);
66static int mbr_root_above_chs(void);
67static void md_upgrade_mbrtype(void);
68static int md_read_bootcode(const char *, struct mbr_sector *);
69static unsigned int get_bootmodel(void);
70
71void
72md_init(void)
73{
74}
75
76void
77md_init_set_status(int flags)
78{
79	(void)flags;
80
81	/* Default to install same type of kernel as we are running */
82	set_kernel_set(get_bootmodel());
83}
84
85int
86md_get_info(void)
87{
88	mbr_info_t *ext;
89	struct mbr_partition *p;
90	const char *bootcode;
91	int i;
92	int names, fl, ofl;
93#define	ACTIVE_FOUND	0x0100
94#define	NETBSD_ACTIVE	0x0200
95#define	NETBSD_NAMED	0x0400
96#define	ACTIVE_NAMED	0x0800
97
98	if (pm->no_mbr)
99		return 1;
100
101	if (read_mbr(pm->diskdev, &mbr) < 0)
102		memset(&mbr.mbr, 0, sizeof mbr.mbr - 2);
103	get_bios_info(pm->diskdev);
104
105edit:
106	if (edit_mbr(&mbr) == 0)
107		return 0;
108
109	root_limit = 0;
110	if (biosdisk != NULL && (biosdisk->bi_flags & BIFLAG_EXTINT13) == 0) {
111		if (mbr_root_above_chs()) {
112			msg_display(MSG_partabovechs);
113			process_menu(MENU_noyes, NULL);
114			if (!yesno)
115				goto edit;
116			/* The user is shooting themselves in the foot here...*/
117		} else
118			root_limit = bcyl * bhead * bsec;
119	}
120
121	/*
122	 * Ensure the install partition (at sector pm->ptstart) and the active
123	 * partition are bootable.
124	 * Determine whether the bootselect code is needed.
125	 * Note that MBR_BS_NEWMBR is always set, so we ignore it!
126	 */
127	fl = 0;
128	names = 0;
129	for (ext = &mbr; ext != NULL; ext = ext->extended) {
130		p = ext->mbr.mbr_parts;
131		for (i = 0; i < MBR_PART_COUNT; p++, i++) {
132			if (p->mbrp_flag == MBR_PFLAG_ACTIVE) {
133				fl |= ACTIVE_FOUND;
134			    if (ext->sector + p->mbrp_start == pm->ptstart)
135				fl |= NETBSD_ACTIVE;
136			}
137			if (ext->mbrb.mbrbs_nametab[i][0] == 0) {
138				/* No bootmenu label... */
139				if (ext->sector == 0)
140					continue;
141				if (ext->sector + p->mbrp_start == pm->ptstart)
142					/*
143					 * Have installed into an extended ptn
144					 * force name & bootsel...
145					 */
146					names++;
147				continue;
148			}
149			/* Partition has a bootmenu label... */
150			if (ext->sector != 0)
151				fl |= MBR_BS_EXTLBA;
152			if (ext->sector + p->mbrp_start == pm->ptstart)
153				fl |= NETBSD_NAMED;
154			else if (p->mbrp_flag == MBR_PFLAG_ACTIVE)
155				fl |= ACTIVE_NAMED;
156			else
157				names++;
158		}
159	}
160	if (!(fl & ACTIVE_FOUND))
161		fl |= NETBSD_ACTIVE;
162	if (fl & NETBSD_NAMED && fl & NETBSD_ACTIVE)
163		fl |= ACTIVE_NAMED;
164
165	if ((names > 0 || !(fl & NETBSD_ACTIVE)) &&
166	    (!(fl & NETBSD_NAMED) || !(fl & ACTIVE_NAMED))) {
167		/*
168		 * There appear to be multiple bootable partitions, but they
169		 * don't all have bootmenu texts.
170		 */
171		msg_display(MSG_missing_bootmenu_text);
172		process_menu(MENU_yesno, NULL);
173		if (yesno)
174			goto edit;
175	}
176
177	if ((fl & MBR_BS_EXTLBA) &&
178	    (biosdisk == NULL || !(biosdisk->bi_flags & BIFLAG_EXTINT13))) {
179		/* Need unsupported LBA reads to read boot sectors */
180		msg_display(MSG_no_extended_bootmenu);
181		process_menu(MENU_noyes, NULL);
182		if (!yesno)
183			goto edit;
184	}
185
186	/* Sort out the name of the mbr code we need */
187	if (names > 0 || fl & (NETBSD_NAMED | ACTIVE_NAMED)) {
188		/* Need bootselect code */
189		fl |= MBR_BS_ACTIVE;
190		bootcode = fl & MBR_BS_EXTLBA ? _PATH_BOOTEXT : _PATH_BOOTSEL;
191	} else
192		bootcode = _PATH_MBR;
193
194	fl &=  MBR_BS_ACTIVE | MBR_BS_EXTLBA;
195
196	/* Look at what is installed */
197	ofl = mbr.mbrb.mbrbs_flags;
198	if (ofl == 0) {
199		/* Check there is some bootcode at all... */
200		if (mbr.mbr.mbr_magic != htole16(MBR_MAGIC) ||
201		    mbr.mbr.mbr_jmpboot[0] == 0 ||
202		    mbr_root_above_chs())
203			/* Existing won't do, force update */
204			fl |= MBR_BS_NEWMBR;
205	}
206	ofl = mbr.oflags & (MBR_BS_ACTIVE | MBR_BS_EXTLBA);
207
208	if (fl & ~ofl || (fl == 0 && ofl & MBR_BS_ACTIVE)) {
209		/* Existing boot code isn't the right one... */
210		if (fl & MBR_BS_ACTIVE)
211			msg_display(MSG_installbootsel);
212		else
213			msg_display(MSG_installmbr);
214	} else
215		/* Existing code would (probably) be ok */
216		msg_display(MSG_updatembr);
217
218	process_menu(MENU_yesno, NULL);
219	if (!yesno)
220		/* User doesn't want to update mbr code */
221		return 1;
222
223	if (md_read_bootcode(bootcode, &mbr.mbr) == 0)
224		/* update suceeded - to memory copy */
225		return 1;
226
227	/* This shouldn't happen since the files are in the floppy fs... */
228	msg_display("Can't find %s", bootcode);
229	process_menu(MENU_yesno, NULL);
230
231	return 1;
232}
233
234/*
235 * md back-end code for menu-driven BSD disklabel editor.
236 */
237int
238md_make_bsd_partitions(void)
239{
240	return make_bsd_partitions();
241}
242
243/*
244 * any additional partition validation
245 */
246int
247md_check_partitions(void)
248{
249	int rval;
250	char *bootxx;
251
252	/* check we have boot code for the root partition type */
253	bootxx = bootxx_name();
254	rval = access(bootxx, R_OK);
255	free(bootxx);
256	if (rval == 0)
257		return 1;
258	process_menu(MENU_ok, deconst(MSG_No_Bootcode));
259	return 0;
260}
261
262/*
263 * hook called before writing new disklabel.
264 */
265int
266md_pre_disklabel(void)
267{
268	if (pm->no_mbr)
269		return 0;
270
271	msg_display(MSG_dofdisk);
272
273	/* write edited MBR onto disk. */
274	if (write_mbr(pm->diskdev, &mbr, 1) != 0) {
275		msg_display(MSG_wmbrfail);
276		process_menu(MENU_ok, NULL);
277		return 1;
278	}
279	return 0;
280}
281
282/*
283 * hook called after writing disklabel to new target disk.
284 */
285int
286md_post_disklabel(void)
287{
288	if (get_ramsize() <= 32)
289		set_swap(pm->diskdev, pm->bsdlabel);
290
291	return 0;
292}
293
294/*
295 * hook called after upgrade() or install() has finished setting
296 * up the target disk but immediately before the user is given the
297 * ``disks are now set up'' message.
298 */
299int
300md_post_newfs(void)
301{
302	int ret;
303	size_t len;
304	char bootxx[8192 + 4];
305	char boot_options[1024];
306	char *bootxx_filename;
307	/*
308	 * XXX - this code retains a lot of cruft from when we went
309	 * to great pains to exclude installboot from the ramdisk
310	 * for size reasons and should be rewritten.
311	 */
312	static const char *consoles[]={
313        	"pc", /* CONSDEV_PC */
314		"com0", /* CONSDEV_COM0 */
315		"com1", /* CONSDEV_COM1 */
316		"com2", /* CONSDEV_COM2 */
317		"com3", /* CONSDEV_COM3 */
318		"com0kbd", /* CONSDEV_COM0KBD */
319		"com1kbd", /* CONSDEV_COM1KBD */
320		"com2kbd", /* CONSDEV_COM2KBD */
321		"com3kbd" /* CONSDEV_COM3KBD */ };
322	static struct x86_boot_params boottype =
323		{sizeof boottype, 0, 5, 0, 9600, { '\0' }, "", 0};
324	static int conmib[] = {CTL_MACHDEP, CPU_CONSDEV};
325	struct termios t;
326	dev_t condev;
327#define bp (*(struct x86_boot_params *)(bootxx + 512 * 2 + 8))
328
329	/*
330	 * Get console device, should either be ttyE0 or tty0n.
331	 * Too hard to double check, so just 'know' the device numbers.
332	 */
333	len = sizeof condev;
334	if (sysctl(conmib, nelem(conmib), &condev, &len, NULL, 0) != -1
335	    && (condev & ~3) == 0x800) {
336		/* Motherboard serial port */
337		boottype.bp_consdev = (condev & 3) + 1;
338		/* Defaulting the baud rate to that of stdin should suffice */
339		if (tcgetattr(0, &t) != -1)
340			boottype.bp_conspeed = t.c_ispeed;
341	}
342
343	process_menu(MENU_getboottype, &boottype);
344	msg_display(MSG_dobootblks, pm->diskdev);
345	if (bp.bp_consdev == ~0u)
346		return 0;
347
348	ret = cp_to_target("/usr/mdec/boot", "/boot");
349	if (ret)
350		return ret;
351
352        bootxx_filename = bootxx_name();
353        if (bootxx_filename != NULL) {
354		snprintf(boot_options, sizeof boot_options,
355		    "console=%s,speed=%u", consoles[boottype.bp_consdev],
356		    boottype.bp_conspeed);
357		if (pm->isspecial) {
358                	ret = run_program(RUN_DISPLAY | RUN_NO_CLEAR,
359                	    "/usr/sbin/installboot -o %s /dev/r%s %s",
360			    boot_options, pm->diskdev, bootxx_filename);
361		} else {
362                	ret = run_program(RUN_DISPLAY | RUN_NO_CLEAR,
363                	    "/usr/sbin/installboot -o %s /dev/r%s%c %s",
364			    boot_options, pm->diskdev, 'a' + pm->rootpart,
365			    bootxx_filename);
366		}
367                free(bootxx_filename);
368        } else
369                ret = -1;
370
371        if (ret != 0)
372                process_menu(MENU_ok,
373                    deconst("Warning: disk is probably not bootable"));
374
375	return ret;
376}
377
378int
379md_post_extract(void)
380{
381	return 0;
382}
383
384void
385md_cleanup_install(void)
386{
387#ifndef DEBUG
388	enable_rc_conf();
389	add_rc_conf("wscons=YES\n");
390
391# if defined(__i386__) && defined(SET_KERNEL_TINY)
392	/*
393	 * For GENERIC_TINY, do not enable any extra screens or wsmux.
394	 * Otherwise, run getty on 4 VTs.
395	 */
396	if (get_kernel_set() == SET_KERNEL_TINY)
397		run_program(RUN_CHROOT,
398                            "sed -an -e '/^screen/s/^/#/;/^mux/s/^/#/;"
399			    "H;$!d;g;w /etc/wscons.conf' /etc/wscons.conf");
400	else
401# endif
402		run_program(RUN_CHROOT,
403			    "sed -an -e '/^ttyE[1-9]/s/off/on/;"
404			    "H;$!d;g;w /etc/ttys' /etc/ttys");
405
406#endif
407}
408
409int
410md_pre_update(void)
411{
412	if (get_ramsize() <= 8)
413		set_swap(pm->diskdev, NULL);
414	return 1;
415}
416
417/* Upgrade support */
418int
419md_update(void)
420{
421	md_post_newfs();
422	md_upgrade_mbrtype();
423	return 1;
424}
425
426int
427md_check_mbr(mbr_info_t *mbri)
428{
429	return 2;
430}
431
432int
433md_mbr_use_wholedisk(mbr_info_t *mbri)
434{
435	return mbr_use_wholedisk(mbri);
436}
437
438static int
439get_bios_info(char *dev)
440{
441	static struct disklist *disklist = NULL;
442	static int mib[2] = {CTL_MACHDEP, CPU_DISKINFO};
443	int i;
444	size_t len;
445	struct biosdisk_info *bip;
446	struct nativedisk_info *nip = NULL, *nat;
447	int cyl, head;
448	daddr_t sec;
449
450	if (disklist == NULL) {
451		if (sysctl(mib, 2, NULL, &len, NULL, 0) < 0)
452			goto nogeom;
453		disklist = malloc(len);
454		if (disklist == NULL) {
455			fprintf(stderr, "Out of memory\n");
456			return -1;
457		}
458		sysctl(mib, 2, disklist, &len, NULL, 0);
459	}
460
461	for (i = 0; i < disklist->dl_nnativedisks; i++) {
462		nat = &disklist->dl_nativedisks[i];
463		if (!strcmp(dev, nat->ni_devname)) {
464			nip = nat;
465			break;
466		}
467	}
468	if (nip == NULL || nip->ni_nmatches == 0) {
469nogeom:
470		if (nip != NULL)
471			msg_display(MSG_nobiosgeom, pm->dlcyl, pm->dlhead, pm->dlsec);
472		if (guess_biosgeom_from_mbr(&mbr, &cyl, &head, &sec) >= 0
473		    && nip != NULL)
474			msg_display_add(MSG_biosguess, cyl, head, sec);
475		biosdisk = NULL;
476	} else {
477		guess_biosgeom_from_mbr(&mbr, &cyl, &head, &sec);
478		if (nip->ni_nmatches == 1) {
479			bip = &disklist->dl_biosdisks[nip->ni_biosmatches[0]];
480			msg_display(MSG_onebiosmatch);
481			msg_table_add(MSG_onebiosmatch_header);
482			msg_table_add(MSG_onebiosmatch_row, bip->bi_dev,
483			    bip->bi_cyl, bip->bi_head, bip->bi_sec,
484			    (unsigned)bip->bi_lbasecs,
485			    (unsigned)(bip->bi_lbasecs / (1000000000 / 512)));
486			msg_display_add(MSG_biosgeom_advise);
487			biosdisk = bip;
488			process_menu(MENU_biosonematch, &biosdisk);
489		} else {
490			msg_display(MSG_biosmultmatch);
491			msg_table_add(MSG_biosmultmatch_header);
492			for (i = 0; i < nip->ni_nmatches; i++) {
493				bip = &disklist->dl_biosdisks[
494							nip->ni_biosmatches[i]];
495				msg_table_add(MSG_biosmultmatch_row, i,
496				    bip->bi_dev, bip->bi_cyl, bip->bi_head,
497				    bip->bi_sec, (unsigned)bip->bi_lbasecs,
498				    (unsigned)bip->bi_lbasecs/(1000000000/512));
499			}
500			process_menu(MENU_biosmultmatch, &i);
501			if (i == -1)
502				biosdisk = NULL;
503			else
504				biosdisk = &disklist->dl_biosdisks[
505							nip->ni_biosmatches[i]];
506		}
507	}
508	if (biosdisk == NULL) {
509		if (nip != NULL) {
510			set_bios_geom(cyl, head, sec);
511		} else {
512			bcyl = cyl;
513			bhead = head;
514			bsec = sec;
515		}
516	} else {
517		bcyl = biosdisk->bi_cyl;
518		bhead = biosdisk->bi_head;
519		bsec = biosdisk->bi_sec;
520	}
521	return 0;
522}
523
524static int
525mbr_root_above_chs(void)
526{
527	return pm->ptstart + DEFROOTSIZE * (MEG / 512) >= bcyl * bhead * bsec;
528}
529
530static void
531md_upgrade_mbrtype(void)
532{
533	struct mbr_partition *mbrp;
534	int i, netbsdpart = -1, oldbsdpart = -1, oldbsdcount = 0;
535
536	if (pm->no_mbr)
537		return;
538
539	if (read_mbr(pm->diskdev, &mbr) < 0)
540		return;
541
542	mbrp = &mbr.mbr.mbr_parts[0];
543
544	for (i = 0; i < MBR_PART_COUNT; i++) {
545		if (mbrp[i].mbrp_type == MBR_PTYPE_386BSD) {
546			oldbsdpart = i;
547			oldbsdcount++;
548		} else if (mbrp[i].mbrp_type == MBR_PTYPE_NETBSD)
549			netbsdpart = i;
550	}
551
552	if (netbsdpart == -1 && oldbsdcount == 1) {
553		mbrp[oldbsdpart].mbrp_type = MBR_PTYPE_NETBSD;
554		write_mbr(pm->diskdev, &mbr, 0);
555	}
556}
557
558/*
559 * Read MBR code from a file.
560 * The existing partition table and bootselect configuration is kept.
561 */
562static int
563md_read_bootcode(const char *path, struct mbr_sector *mbrs)
564{
565	int fd;
566	struct stat st;
567	size_t len;
568	struct mbr_sector new_mbr;
569	uint32_t dsn;
570
571	fd = open(path, O_RDONLY);
572	if (fd < 0)
573		return -1;
574
575	if (fstat(fd, &st) < 0 || st.st_size != sizeof *mbrs) {
576		close(fd);
577		return -1;
578	}
579
580	if (read(fd, &new_mbr, sizeof new_mbr) != sizeof new_mbr) {
581		close(fd);
582		return -1;
583	}
584	close(fd);
585
586	if (new_mbr.mbr_bootsel_magic != htole16(MBR_BS_MAGIC))
587		return -1;
588
589	if (mbrs->mbr_bootsel_magic == htole16(MBR_BS_MAGIC)) {
590		len = offsetof(struct mbr_sector, mbr_bootsel);
591	} else
592		len = offsetof(struct mbr_sector, mbr_parts);
593
594	/* Preserve the 'drive serial number' - especially for Vista */
595	dsn = mbrs->mbr_dsn;
596	memcpy(mbrs, &new_mbr, len);
597	mbrs->mbr_dsn = dsn;
598
599	/* Keep flags from object file - indicate the properties */
600	mbrs->mbr_bootsel.mbrbs_flags = new_mbr.mbr_bootsel.mbrbs_flags;
601	mbrs->mbr_magic = htole16(MBR_MAGIC);
602
603	return 0;
604}
605
606static unsigned int
607get_bootmodel(void)
608{
609#if defined(__i386__)
610	struct utsname ut;
611#ifdef DEBUG
612	char *envstr;
613
614	envstr = getenv("BOOTMODEL");
615	if (envstr != NULL)
616		return atoi(envstr);
617#endif
618
619	if (uname(&ut) < 0)
620		ut.version[0] = 0;
621
622#if defined(SET_KERNEL_TINY)
623	if (strstr(ut.version, "TINY") != NULL)
624		return SET_KERNEL_TINY;
625#endif
626#if defined(SET_KERNEL_PS2)
627	if (strstr(ut.version, "PS2") != NULL)
628		return SET_KERNEL_PS2;
629#endif
630#endif
631	return SET_KERNEL_GENERIC;
632}
633
634
635int
636md_pre_mount()
637{
638	return 0;
639}
640