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