Home | History | Annotate | Line # | Download | only in arch
i386.c revision 1.27
      1 /* $NetBSD: i386.c,v 1.27 2007/06/23 23:07:44 dogcow Exp $ */
      2 
      3 /*-
      4  * Copyright (c) 2003 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by David Laight.
      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. All advertising materials mentioning features or use of this software
     19  *    must display the following acknowledgement:
     20  *        This product includes software developed by the NetBSD
     21  *        Foundation, Inc. and its contributors.
     22  * 4. Neither the name of The NetBSD Foundation nor the names of its
     23  *    contributors may be used to endorse or promote products derived
     24  *    from this software without specific prior written permission.
     25  *
     26  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     27  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     28  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     29  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     30  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     31  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     32  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     33  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     34  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     35  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     36  * POSSIBILITY OF SUCH DAMAGE.
     37  */
     38 
     39 #if HAVE_NBTOOL_CONFIG_H
     40 #include "nbtool_config.h"
     41 #endif
     42 
     43 #include <sys/cdefs.h>
     44 #if !defined(__lint)
     45 __RCSID("$NetBSD: i386.c,v 1.27 2007/06/23 23:07:44 dogcow Exp $");
     46 #endif /* !__lint */
     47 
     48 #include <sys/param.h>
     49 #ifndef HAVE_NBTOOL_CONFIG_H
     50 #include <sys/ioctl.h>
     51 #include <sys/dkio.h>
     52 #endif
     53 
     54 #include <assert.h>
     55 #include <errno.h>
     56 #include <err.h>
     57 #include <md5.h>
     58 #include <stddef.h>
     59 #include <stdio.h>
     60 #include <stdlib.h>
     61 #include <string.h>
     62 #include <unistd.h>
     63 
     64 #include "installboot.h"
     65 
     66 #define nelem(x) (sizeof (x)/sizeof *(x))
     67 #ifndef __arraycount
     68 #define __arraycount(__x) (sizeof(__x) / sizeof(__x[0]))
     69 #endif
     70 
     71 static const struct console_name {
     72 	const char	*name;		/* Name of console selection */
     73 	const int	dev;		/* value matching CONSDEV_* from sys/arch/i386/stand/lib/libi386.h */
     74 } consoles[] = {
     75 	{ "pc",		0 /* CONSDEV_PC */ },
     76 	{ "com0",	1 /* CONSDEV_COM0 */ },
     77 	{ "com1",	2 /* CONSDEV_COM1 */ },
     78 	{ "com2",	3 /* CONSDEV_COM2 */ },
     79 	{ "com3",	4 /* CONSDEV_COM3 */ },
     80 	{ "com0kbd",	5 /* CONSDEV_COM0KBD */ },
     81 	{ "com1kbd",	6 /* CONSDEV_COM1KBD */ },
     82 	{ "com2kbd",	7 /* CONSDEV_COM2KBD */ },
     83 	{ "com3kbd",	8 /* CONSDEV_COM3KBD */ },
     84 	{ "auto",	-1 /* CONSDEV_AUTO */ },
     85 };
     86 
     87 static int i386_setboot(ib_params *);
     88 static int i386_editboot(ib_params *);
     89 
     90 struct ib_mach ib_mach_i386 =
     91 	{ "i386", i386_setboot, no_clearboot, i386_editboot,
     92 		IB_RESETVIDEO | IB_CONSOLE | IB_CONSPEED | IB_CONSADDR |
     93 		IB_KEYMAP | IB_PASSWORD | IB_TIMEOUT };
     94 
     95 struct ib_mach ib_mach_amd64 =
     96 	{ "amd64", i386_setboot, no_clearboot, i386_editboot,
     97 		IB_RESETVIDEO | IB_CONSOLE | IB_CONSPEED | IB_CONSADDR |
     98 		IB_KEYMAP | IB_PASSWORD | IB_TIMEOUT };
     99 
    100 /*
    101  * Attempting to write the 'labelsector' (or a sector near it - within 8k?)
    102  * using the non-raw disk device fails silently.  This can be detected (today)
    103  * by doing a fsync() and a read back.
    104  * This is very likely to affect installboot, indeed the code may need to
    105  * be written into the 'labelsector' itself - especially on non-512 byte media.
    106  * We do all writes with a read verify.
    107  * If EROFS is returned we also try to enable writes to the label sector.
    108  * (Maybe these functions should be in the generic part of installboot.)
    109  */
    110 static int
    111 pwrite_validate(int fd, const void *buf, size_t n_bytes, off_t offset)
    112 {
    113 	void *r_buf;
    114 	ssize_t rv;
    115 
    116 	r_buf = malloc(n_bytes);
    117 	if (r_buf == NULL)
    118 		return -1;
    119 	rv = pwrite(fd, buf, n_bytes, offset);
    120 	if (rv == -1) {
    121 		free(r_buf);
    122 		return -1;
    123 	}
    124 	fsync(fd);
    125 	if (pread(fd, r_buf, rv, offset) == rv && memcmp(r_buf, buf, rv) == 0)
    126 		return rv;
    127 	errno = EROFS;
    128 	return -1;
    129 }
    130 
    131 static int
    132 write_boot_area(ib_params *params, void *v_buf, int len)
    133 {
    134 	int rv, i;
    135 	uint8_t *buf = v_buf;
    136 
    137 	/*
    138 	 * Writing the 'label' sector (likely to be bytes 512-1023) could
    139 	 * fail, so we try to avoid writing that area.
    140 	 * Unfortunately, if we are accessing the raw disk, and the sector
    141 	 * size is larger than 512 bytes that is also doomed.
    142 	 * See how we get on....
    143 	 *
    144 	 * NB: Even if the physical sector size is not 512, the space for
    145 	 * the label is 512 bytes from the start of the disk.
    146 	 * So all the '512' constants in these functions are correct.
    147 	 */
    148 
    149 	/* Write out first 512 bytes - the pbr code */
    150 	rv = pwrite_validate(params->fsfd, buf, 512, 0);
    151 	if (rv == 512) {
    152 		/* That worked, do the rest */
    153 		if (len == 512)
    154 			return 1;
    155 		len -= 512 * 2;
    156 		rv = pwrite_validate(params->fsfd, buf + 512 * 2, len, 512 * 2);
    157 		if (rv != len)
    158 			goto bad_write;
    159 		return 1;
    160 	}
    161 	if (rv != -1 || (errno != EINVAL && errno != EROFS))
    162 		goto bad_write;
    163 
    164 	if (errno == EINVAL) {
    165 		/* Assume the failure was due to to the sector size > 512 */
    166 		rv = pwrite_validate(params->fsfd, buf, len, 0);
    167 		if (rv == len)
    168 			return 1;
    169 		if (rv != -1 || (errno != EROFS))
    170 			goto bad_write;
    171 	}
    172 
    173 #ifdef DIOCWLABEL
    174 	/* Pesky label is protected, try to unprotect it */
    175 	i = 1;
    176 	rv = ioctl(params->fsfd, DIOCWLABEL, &i);
    177 	if (rv != 0) {
    178 		warn("Cannot enable writes to the label sector");
    179 		return 0;
    180 	}
    181 	/* Try again with label write-enabled */
    182 	rv = pwrite_validate(params->fsfd, buf, len, 0);
    183 
    184 	/* Reset write-protext */
    185 	i = 0;
    186 	ioctl(params->fsfd, DIOCWLABEL, &i);
    187 	if (rv == len)
    188 		return 1;
    189 #endif
    190 
    191   bad_write:
    192 	if (rv == -1)
    193 		warn("Writing `%s'", params->filesystem);
    194 	else
    195 		warnx("Writing `%s': short write, %u bytes",
    196 			params->filesystem, rv);
    197 	return 0;
    198 }
    199 
    200 static void
    201 show_i386_boot_params(struct x86_boot_params  *bpp)
    202 {
    203 	size_t i;
    204 
    205 	printf("Boot options:        ");
    206 	printf("timeout %d, ", le32toh(bpp->bp_timeout));
    207 	printf("flags %x, ", le32toh(bpp->bp_flags));
    208 	printf("speed %d, ", le32toh(bpp->bp_conspeed));
    209 	printf("ioaddr %x, ", le32toh(bpp->bp_consaddr));
    210 	for (i = 0; i < __arraycount(consoles); i++) {
    211 		if (consoles[i].dev == le32toh(bpp->bp_consdev))
    212 			break;
    213 	}
    214 	if (i == __arraycount(consoles))
    215 		printf("console %d\n", le32toh(bpp->bp_consdev));
    216 	else
    217 		printf("console %s\n", consoles[i].name);
    218 	if (bpp->bp_keymap[0])
    219 		printf("                     keymap %s\n", bpp->bp_keymap);
    220 }
    221 
    222 static int
    223 is_zero(const uint8_t *p, unsigned int len)
    224 {
    225 	return len == 0 || (p[0] == 0 && memcmp(p, p + 1, len - 1) == 0);
    226 }
    227 
    228 static int
    229 update_i386_boot_params(ib_params *params, struct x86_boot_params  *bpp)
    230 {
    231 	struct x86_boot_params bp;
    232 	int bplen;
    233 	size_t i;
    234 
    235 	bplen = le32toh(bpp->bp_length);
    236 	if (bplen > sizeof bp)
    237 		/* Ignore pad space in bootxx */
    238 		bplen = sizeof bp;
    239 
    240 	/* Take (and update) local copy so we handle size mismatches */
    241 	memset(&bp, 0, sizeof bp);
    242 	memcpy(&bp, bpp, bplen);
    243 
    244 	if (params->flags & IB_TIMEOUT)
    245 		bp.bp_timeout = htole32(params->timeout);
    246 	if (params->flags & IB_RESETVIDEO)
    247 		bp.bp_flags ^= htole32(X86_BP_FLAGS_RESET_VIDEO);
    248 	if (params->flags & IB_CONSPEED)
    249 		bp.bp_conspeed = htole32(params->conspeed);
    250 	if (params->flags & IB_CONSADDR)
    251 		bp.bp_consaddr = htole32(params->consaddr);
    252 	if (params->flags & IB_CONSOLE) {
    253 		for (i = 0; i < __arraycount(consoles); i++)
    254 			if (strcmp(consoles[i].name, params->console) == 0)
    255 				break;
    256 
    257 		if (i == __arraycount(consoles)) {
    258 			warnx("invalid console name, valid names are:");
    259 			(void)fprintf(stderr, "\t%s", consoles[0].name);
    260 			for (i = 1; consoles[i].name != NULL; i++)
    261 				(void)fprintf(stderr, ", %s", consoles[i].name);
    262 			(void)fprintf(stderr, "\n");
    263 			return 1;
    264 		}
    265 		bp.bp_consdev = htole32(consoles[i].dev);
    266 	}
    267 	if (params->flags & IB_PASSWORD) {
    268 		if (params->password[0]) {
    269 			MD5_CTX md5ctx;
    270 			MD5Init(&md5ctx);
    271 			MD5Update(&md5ctx, params->password,
    272 			    strlen(params->password));
    273 			MD5Final(bp.bp_password, &md5ctx);
    274 			bp.bp_flags |= htole32(X86_BP_FLAGS_PASSWORD);
    275 		} else {
    276 			memset(&bp.bp_password, 0, sizeof bp.bp_password);
    277 			bp.bp_flags &= ~htole32(X86_BP_FLAGS_PASSWORD);
    278 		}
    279 	}
    280 	if (params->flags & IB_KEYMAP)
    281 		strlcpy(bp.bp_keymap, params->keymap, sizeof bp.bp_keymap);
    282 
    283 	if (params->flags & (IB_NOWRITE | IB_VERBOSE))
    284 		show_i386_boot_params(&bp);
    285 
    286 	/* Check we aren't trying to set anything we can't save */
    287 	if (!is_zero((char *)&bp + bplen, sizeof bp - bplen)) {
    288 		warnx("Patch area in stage1 bootstrap is too small");
    289 		return 1;
    290 	}
    291 	memcpy(bpp, &bp, bplen);
    292 	return 0;
    293 }
    294 
    295 static int
    296 i386_setboot(ib_params *params)
    297 {
    298 	unsigned int	u;
    299 	ssize_t		rv;
    300 	uint32_t	*magic, expected_magic;
    301 	union {
    302 	    struct mbr_sector	mbr;
    303 	    uint8_t		b[8192];
    304 	} disk_buf, bootstrap;
    305 
    306 	assert(params != NULL);
    307 	assert(params->fsfd != -1);
    308 	assert(params->filesystem != NULL);
    309 	assert(params->s1fd != -1);
    310 	assert(params->stage1 != NULL);
    311 
    312 	/*
    313 	 * There is only 8k of space in a UFSv1 partition (and ustarfs)
    314 	 * so ensure we don't splat over anything important.
    315 	 */
    316 	if (params->s1stat.st_size > sizeof bootstrap) {
    317 		warnx("stage1 bootstrap `%s' (%u bytes) is larger than 8192 bytes",
    318 			params->stage1, (unsigned int)params->s1stat.st_size);
    319 		return 0;
    320 	}
    321 	if (params->s1stat.st_size < 3 * 512 && params->s1stat.st_size != 512) {
    322 		warnx("stage1 bootstrap `%s' (%u bytes) is too small",
    323 			params->stage1, (unsigned int)params->s1stat.st_size);
    324 		return 0;
    325 	}
    326 
    327 	/* Read in the existing disk header and boot code */
    328 	rv = pread(params->fsfd, &disk_buf, sizeof (disk_buf), 0);
    329 	if (rv != sizeof(disk_buf)) {
    330 		if (rv == -1)
    331 			warn("Reading `%s'", params->filesystem);
    332 		else
    333 			warnx("Reading `%s': short read, %ld bytes"
    334 			    " (should be %ld)", params->filesystem, (long)rv,
    335 			    (long)sizeof(disk_buf));
    336 		return 0;
    337 	}
    338 
    339 	if (disk_buf.mbr.mbr_magic != le16toh(MBR_MAGIC)) {
    340 		if (params->flags & IB_VERBOSE) {
    341 			printf(
    342 		    "Ignoring PBR with invalid magic in sector 0 of `%s'\n",
    343 			    params->filesystem);
    344 		}
    345 		memset(&disk_buf, 0, 512);
    346 	}
    347 
    348 	/* Read the new bootstrap code. */
    349 	rv = pread(params->s1fd, &bootstrap, params->s1stat.st_size, 0);
    350 	if (rv != params->s1stat.st_size) {
    351 		if (rv == -1)
    352 			warn("Reading `%s'", params->stage1);
    353 		else
    354 			warnx("Reading `%s': short read, %ld bytes"
    355 			    " (should be %ld)", params->stage1, (long)rv,
    356 			    (long)params->s1stat.st_size);
    357 		return 0;
    358 	}
    359 
    360 	/*
    361 	 * The bootstrap code is either 512 bytes for booting FAT16, or best
    362 	 * part of 8k (with bytes 512-1023 all zeros).
    363 	 */
    364 	if (params->s1stat.st_size == 512) {
    365 		/* Magic number is at end of pbr code */
    366 		magic = (void *)(bootstrap.b + 512 - 16 + 4);
    367 		expected_magic = htole32(X86_BOOT_MAGIC_FAT);
    368 	} else {
    369 		/* Magic number is at start of sector following label */
    370 		magic = (void *)(bootstrap.b + 512 * 2 + 4);
    371 		expected_magic = htole32(X86_BOOT_MAGIC_1);
    372 		/*
    373 		 * For a variety of reasons we restrict our 'normal' partition
    374 		 * boot code to a size which enable it to be used as mbr code.
    375 		 * IMHO this is bugus (dsl).
    376 		 */
    377 		if (!is_zero(bootstrap.b + 512-2-64, 64)) {
    378 			warnx("Data in mbr partition table of new bootstrap");
    379 			return 0;
    380 		}
    381 		if (!is_zero(bootstrap.b + 512, 512)) {
    382 			warnx("Data in label part of new bootstrap");
    383 			return 0;
    384 		}
    385 		/* Copy mbr table and label from existing disk buffer */
    386 		memcpy(bootstrap.b + 512-2-64, disk_buf.b + 512-2-64, 64);
    387 		memcpy(bootstrap.b + 512, disk_buf.b + 512, 512);
    388 	}
    389 
    390 	/* Validate the 'magic number' that marks the parameter block */
    391 	if (*magic != expected_magic) {
    392 		warnx("Invalid magic in stage1 bootstrap %x != %x",
    393 				*magic, expected_magic);
    394 		return 0;
    395 	}
    396 
    397 	/*
    398 	 * If the partion has a FAT (or NTFS) filesystem, then we must
    399 	 * preserve the BIOS Parameter Block (BPB).
    400 	 * It is also very likely that there isn't 8k of space available
    401 	 * for (say) bootxx_msdos, and that blindly installing it will trash
    402 	 * the FAT filesystem.
    403 	 * To avoid this we check the number of 'reserved' sectors to ensure
    404 	 * there there is enough space.
    405 	 * Unfortunately newfs(8) doesn't (yet) splat the BPB (which is
    406 	 * effectively the FAT superblock) when a filesystem is initailised
    407 	 * so this code tends to complain rather too often,
    408 	 * Specifying 'installboot -f' will delete the old BPB info.
    409 	 */
    410 	if (!(params->flags & IB_FORCE)) {
    411 		/*
    412 		 * For FAT compatibility, the pbr code starts 'jmp xx; nop'
    413 		 * followed by the BIOS Parameter Block (BPB).
    414 		 * The 2nd byte (jump offset) is the size of the nop + BPB.
    415 		 */
    416 		if (bootstrap.b[0] != 0xeb || bootstrap.b[2] != 0x90) {
    417 			warnx("No BPB in new bootstrap %02x:%02x:%02x, use -f",
    418 				bootstrap.b[0], bootstrap.b[1], bootstrap.b[2]);
    419 			return 0;
    420 		}
    421 
    422 		/* Find size of old BPB, and copy into new bootcode */
    423 		if (!is_zero(disk_buf.b + 3 + 8, disk_buf.b[1] - 1 - 8)) {
    424 			struct mbr_bpbFAT16 *bpb = (void *)(disk_buf.b + 3 + 8);
    425 			/* Check enough space before the FAT for the bootcode */
    426 			u = le16toh(bpb->bpbBytesPerSec)
    427 			    * le16toh(bpb->bpbResSectors);
    428 			if (u != 0 && u < params->s1stat.st_size) {
    429 				warnx("Insufficient reserved space before FAT (%u bytes available), use -f", u);
    430 				return 0;
    431 			}
    432 			/* Check we have enough space for the old bpb */
    433 			if (disk_buf.b[1] > bootstrap.b[1]) {
    434 				/* old BPB is larger, allow if extra zeros */
    435 				if (!is_zero(disk_buf.b + 2 + bootstrap.b[1],
    436 				    disk_buf.b[1] - bootstrap.b[1])) {
    437 					warnx("Old BPB too big, use -f");
    438 					    return 0;
    439 				}
    440 				u = bootstrap.b[1];
    441 			} else {
    442 				/* Old BPB is shorter, leave zero filled */
    443 				u = disk_buf.b[1];
    444 			}
    445 			memcpy(bootstrap.b + 2, disk_buf.b + 2, u);
    446 		}
    447 	}
    448 
    449 	/*
    450 	 * Fill in any user-specified options into the
    451 	 *      struct x86_boot_params
    452 	 * that follows the magic number.
    453 	 * See sys/arch/i386/stand/bootxx/bootxx.S for more information.
    454 	 */
    455 	if (update_i386_boot_params(params, (void *)(magic + 1)))
    456 		return 0;
    457 
    458 	if (params->flags & IB_NOWRITE) {
    459 		return 1;
    460 	}
    461 
    462 	/* Copy new bootstrap data into disk buffer, ignoring label area */
    463 	memcpy(&disk_buf, &bootstrap, 512);
    464 	if (params->s1stat.st_size > 512 * 2) {
    465 		memcpy(disk_buf.b + 2 * 512, bootstrap.b + 2 * 512,
    466 		    params->s1stat.st_size - 2 * 512);
    467 		/* Zero pad to 512 byte sector boundary */
    468 		memset(disk_buf.b + params->s1stat.st_size, 0,
    469 			(8192 - params->s1stat.st_size) & 511);
    470 	}
    471 
    472 	return write_boot_area(params, &disk_buf, sizeof disk_buf);
    473 }
    474 
    475 static int
    476 i386_editboot(ib_params *params)
    477 {
    478 	int		retval;
    479 	uint8_t		buf[512];
    480 	ssize_t		rv;
    481 	uint32_t	magic;
    482 	uint32_t	offset;
    483 	struct x86_boot_params	*bpp;
    484 
    485 	assert(params != NULL);
    486 	assert(params->fsfd != -1);
    487 	assert(params->filesystem != NULL);
    488 
    489 	retval = 0;
    490 
    491 	/*
    492 	 * Read in the existing bootstrap.
    493 	 * Look in any of the first 4 sectors.
    494 	 */
    495 
    496 	bpp = NULL;
    497 	for (offset = 0; offset < 4 * 512; offset += 512) {
    498 		rv = pread(params->fsfd, &buf, sizeof buf, offset);
    499 		if (rv == -1) {
    500 			warn("Reading `%s'", params->filesystem);
    501 			goto done;
    502 		} else if (rv != sizeof buf) {
    503 			warnx("Reading `%s': short read", params->filesystem);
    504 			goto done;
    505 		}
    506 
    507 		/* Magic number is 4 bytes in (to allow for a jmps) */
    508 		/* Also allow any of the magic numbers. */
    509 		magic = le32toh(*(uint32_t *)(buf + 4)) | 0xf;
    510 		if (magic != (X86_BOOT_MAGIC_1 | 0xf))
    511 			continue;
    512 
    513 		/* The parameters are just after the magic number */
    514 		bpp = (void *)(buf + 8);
    515 		break;
    516 	}
    517 	if (bpp == NULL) {
    518 		warnx("Invalid magic in existing bootstrap");
    519 		goto done;
    520 	}
    521 
    522 	/*
    523 	 * Fill in any user-specified options into the
    524 	 *      struct x86_boot_params
    525 	 * that's 8 bytes in from the start of the third sector.
    526 	 * See sys/arch/i386/stand/bootxx/bootxx.S for more information.
    527 	 */
    528 	if (update_i386_boot_params(params, bpp))
    529 		goto done;
    530 
    531 	if (params->flags & IB_NOWRITE) {
    532 		retval = 1;
    533 		goto done;
    534 	}
    535 
    536 	/*
    537 	 * Write boot code back
    538 	 */
    539 	rv = pwrite(params->fsfd, buf, sizeof buf, offset);
    540 	if (rv == -1) {
    541 		warn("Writing `%s'", params->filesystem);
    542 		goto done;
    543 	} else if (rv != sizeof buf) {
    544 		warnx("Writing `%s': short write, %ld bytes (should be %ld)",
    545 		    params->filesystem, (long)rv, (long)sizeof(buf));
    546 		goto done;
    547 	}
    548 
    549 	retval = 1;
    550 
    551  done:
    552 	return retval;
    553 }
    554