xref: /netbsd-src/usr.sbin/installboot/arch/i386.c (revision da9817918ec7e88db2912a2882967c7570a83f47)
1 /* $NetBSD: i386.c,v 1.33 2009/05/07 07:03:39 lukem 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.33 2009/05/07 07:03:39 lukem 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 
85 struct ib_mach ib_mach_amd64 =
86 	{ "amd64", i386_setboot, no_clearboot, i386_editboot,
87 		IB_RESETVIDEO | IB_CONSOLE | IB_CONSPEED | IB_CONSADDR |
88 		IB_KEYMAP | IB_PASSWORD | IB_TIMEOUT };
89 
90 /*
91  * Attempting to write the 'labelsector' (or a sector near it - within 8k?)
92  * using the non-raw disk device fails silently.  This can be detected (today)
93  * by doing a fsync() and a read back.
94  * This is very likely to affect installboot, indeed the code may need to
95  * be written into the 'labelsector' itself - especially on non-512 byte media.
96  * We do all writes with a read verify.
97  * If EROFS is returned we also try to enable writes to the label sector.
98  * (Maybe these functions should be in the generic part of installboot.)
99  */
100 static int
101 pwrite_validate(int fd, const void *buf, size_t n_bytes, off_t offset)
102 {
103 	void *r_buf;
104 	ssize_t rv;
105 
106 	r_buf = malloc(n_bytes);
107 	if (r_buf == NULL)
108 		return -1;
109 	rv = pwrite(fd, buf, n_bytes, offset);
110 	if (rv == -1) {
111 		free(r_buf);
112 		return -1;
113 	}
114 	fsync(fd);
115 	if (pread(fd, r_buf, rv, offset) == rv && memcmp(r_buf, buf, rv) == 0) {
116 		free(r_buf);
117 		return rv;
118 	}
119 	free(r_buf);
120 	errno = EROFS;
121 	return -1;
122 }
123 
124 static int
125 write_boot_area(ib_params *params, void *v_buf, int len)
126 {
127 	int rv, i;
128 	uint8_t *buf = v_buf;
129 
130 	/*
131 	 * Writing the 'label' sector (likely to be bytes 512-1023) could
132 	 * fail, so we try to avoid writing that area.
133 	 * Unfortunately, if we are accessing the raw disk, and the sector
134 	 * size is larger than 512 bytes that is also doomed.
135 	 * See how we get on....
136 	 *
137 	 * NB: Even if the physical sector size is not 512, the space for
138 	 * the label is 512 bytes from the start of the disk.
139 	 * So all the '512' constants in these functions are correct.
140 	 */
141 
142 	/* Write out first 512 bytes - the pbr code */
143 	rv = pwrite_validate(params->fsfd, buf, 512, 0);
144 	if (rv == 512) {
145 		/* That worked, do the rest */
146 		if (len == 512)
147 			return 1;
148 		len -= 512 * 2;
149 		rv = pwrite_validate(params->fsfd, buf + 512 * 2, len, 512 * 2);
150 		if (rv != len)
151 			goto bad_write;
152 		return 1;
153 	}
154 	if (rv != -1 || (errno != EINVAL && errno != EROFS))
155 		goto bad_write;
156 
157 	if (errno == EINVAL) {
158 		/* Assume the failure was due to to the sector size > 512 */
159 		rv = pwrite_validate(params->fsfd, buf, len, 0);
160 		if (rv == len)
161 			return 1;
162 		if (rv != -1 || (errno != EROFS))
163 			goto bad_write;
164 	}
165 
166 #ifdef DIOCWLABEL
167 	/* Pesky label is protected, try to unprotect it */
168 	i = 1;
169 	rv = ioctl(params->fsfd, DIOCWLABEL, &i);
170 	if (rv != 0) {
171 		warn("Cannot enable writes to the label sector");
172 		return 0;
173 	}
174 	/* Try again with label write-enabled */
175 	rv = pwrite_validate(params->fsfd, buf, len, 0);
176 
177 	/* Reset write-protext */
178 	i = 0;
179 	ioctl(params->fsfd, DIOCWLABEL, &i);
180 	if (rv == len)
181 		return 1;
182 #endif
183 
184   bad_write:
185 	if (rv == -1)
186 		warn("Writing `%s'", params->filesystem);
187 	else
188 		warnx("Writing `%s': short write, %u bytes",
189 			params->filesystem, rv);
190 	return 0;
191 }
192 
193 static void
194 show_i386_boot_params(struct x86_boot_params  *bpp)
195 {
196 	size_t i;
197 
198 	printf("Boot options:        ");
199 	printf("timeout %d, ", le32toh(bpp->bp_timeout));
200 	printf("flags %x, ", le32toh(bpp->bp_flags));
201 	printf("speed %d, ", le32toh(bpp->bp_conspeed));
202 	printf("ioaddr %x, ", le32toh(bpp->bp_consaddr));
203 	for (i = 0; i < nelem(consoles); i++) {
204 		if (consoles[i].dev == (int)le32toh(bpp->bp_consdev))
205 			break;
206 	}
207 	if (i == nelem(consoles))
208 		printf("console %d\n", le32toh(bpp->bp_consdev));
209 	else
210 		printf("console %s\n", consoles[i].name);
211 	if (bpp->bp_keymap[0])
212 		printf("                     keymap %s\n", bpp->bp_keymap);
213 }
214 
215 static int
216 is_zero(const uint8_t *p, unsigned int len)
217 {
218 	return len == 0 || (p[0] == 0 && memcmp(p, p + 1, len - 1) == 0);
219 }
220 
221 static int
222 update_i386_boot_params(ib_params *params, struct x86_boot_params  *bpp)
223 {
224 	struct x86_boot_params bp;
225 	uint32_t bplen;
226 	size_t i;
227 
228 	bplen = le32toh(bpp->bp_length);
229 	if (bplen > sizeof bp)
230 		/* Ignore pad space in bootxx */
231 		bplen = sizeof bp;
232 
233 	/* Take (and update) local copy so we handle size mismatches */
234 	memset(&bp, 0, sizeof bp);
235 	memcpy(&bp, bpp, bplen);
236 
237 	if (params->flags & IB_TIMEOUT)
238 		bp.bp_timeout = htole32(params->timeout);
239 	if (params->flags & IB_RESETVIDEO)
240 		bp.bp_flags ^= htole32(X86_BP_FLAGS_RESET_VIDEO);
241 	if (params->flags & IB_CONSPEED)
242 		bp.bp_conspeed = htole32(params->conspeed);
243 	if (params->flags & IB_CONSADDR)
244 		bp.bp_consaddr = htole32(params->consaddr);
245 	if (params->flags & IB_CONSOLE) {
246 		for (i = 0; i < nelem(consoles); i++)
247 			if (strcmp(consoles[i].name, params->console) == 0)
248 				break;
249 
250 		if (i == nelem(consoles)) {
251 			warnx("invalid console name, valid names are:");
252 			(void)fprintf(stderr, "\t%s", consoles[0].name);
253 			for (i = 1; consoles[i].name != NULL; i++)
254 				(void)fprintf(stderr, ", %s", consoles[i].name);
255 			(void)fprintf(stderr, "\n");
256 			return 1;
257 		}
258 		bp.bp_consdev = htole32(consoles[i].dev);
259 	}
260 	if (params->flags & IB_PASSWORD) {
261 		if (params->password[0]) {
262 			MD5_CTX md5ctx;
263 			MD5Init(&md5ctx);
264 			MD5Update(&md5ctx, params->password,
265 			    strlen(params->password));
266 			MD5Final(bp.bp_password, &md5ctx);
267 			bp.bp_flags |= htole32(X86_BP_FLAGS_PASSWORD);
268 		} else {
269 			memset(&bp.bp_password, 0, sizeof bp.bp_password);
270 			bp.bp_flags &= ~htole32(X86_BP_FLAGS_PASSWORD);
271 		}
272 	}
273 	if (params->flags & IB_KEYMAP)
274 		strlcpy(bp.bp_keymap, params->keymap, sizeof bp.bp_keymap);
275 
276 	if (params->flags & (IB_NOWRITE | IB_VERBOSE))
277 		show_i386_boot_params(&bp);
278 
279 	/* Check we aren't trying to set anything we can't save */
280 	if (!is_zero((char *)&bp + bplen, sizeof bp - bplen)) {
281 		warnx("Patch area in stage1 bootstrap is too small");
282 		return 1;
283 	}
284 	memcpy(bpp, &bp, bplen);
285 	return 0;
286 }
287 
288 static int
289 i386_setboot(ib_params *params)
290 {
291 	unsigned int	u;
292 	ssize_t		rv;
293 	uint32_t	*magic, expected_magic;
294 	union {
295 	    struct mbr_sector	mbr;
296 	    uint8_t		b[8192];
297 	} disk_buf, bootstrap;
298 
299 	assert(params != NULL);
300 	assert(params->fsfd != -1);
301 	assert(params->filesystem != NULL);
302 	assert(params->s1fd != -1);
303 	assert(params->stage1 != NULL);
304 
305 	/*
306 	 * There is only 8k of space in a FFSv1 partition (and ustarfs)
307 	 * so ensure we don't splat over anything important.
308 	 */
309 	if (params->s1stat.st_size > (off_t)(sizeof bootstrap)) {
310 		warnx("stage1 bootstrap `%s' (%u bytes) is larger than 8192 bytes",
311 			params->stage1, (unsigned int)params->s1stat.st_size);
312 		return 0;
313 	}
314 	if (params->s1stat.st_size < 3 * 512 && params->s1stat.st_size != 512) {
315 		warnx("stage1 bootstrap `%s' (%u bytes) is too small",
316 			params->stage1, (unsigned int)params->s1stat.st_size);
317 		return 0;
318 	}
319 
320 	/* Read in the existing disk header and boot code */
321 	rv = pread(params->fsfd, &disk_buf, sizeof (disk_buf), 0);
322 	if (rv != sizeof(disk_buf)) {
323 		if (rv == -1)
324 			warn("Reading `%s'", params->filesystem);
325 		else
326 			warnx("Reading `%s': short read, %ld bytes"
327 			    " (should be %ld)", params->filesystem, (long)rv,
328 			    (long)sizeof(disk_buf));
329 		return 0;
330 	}
331 
332 	if (disk_buf.mbr.mbr_magic != le16toh(MBR_MAGIC)) {
333 		if (params->flags & IB_VERBOSE) {
334 			printf(
335 		    "Ignoring PBR with invalid magic in sector 0 of `%s'\n",
336 			    params->filesystem);
337 		}
338 		memset(&disk_buf, 0, 512);
339 	}
340 
341 	/* Read the new bootstrap code. */
342 	rv = pread(params->s1fd, &bootstrap, params->s1stat.st_size, 0);
343 	if (rv != params->s1stat.st_size) {
344 		if (rv == -1)
345 			warn("Reading `%s'", params->stage1);
346 		else
347 			warnx("Reading `%s': short read, %ld bytes"
348 			    " (should be %ld)", params->stage1, (long)rv,
349 			    (long)params->s1stat.st_size);
350 		return 0;
351 	}
352 
353 	/*
354 	 * The bootstrap code is either 512 bytes for booting FAT16, or best
355 	 * part of 8k (with bytes 512-1023 all zeros).
356 	 */
357 	if (params->s1stat.st_size == 512) {
358 		/* Magic number is at end of pbr code */
359 		magic = (void *)(bootstrap.b + 512 - 16 + 4);
360 		expected_magic = htole32(X86_BOOT_MAGIC_FAT);
361 	} else {
362 		/* Magic number is at start of sector following label */
363 		magic = (void *)(bootstrap.b + 512 * 2 + 4);
364 		expected_magic = htole32(X86_BOOT_MAGIC_1);
365 		/*
366 		 * For a variety of reasons we restrict our 'normal' partition
367 		 * boot code to a size which enable it to be used as mbr code.
368 		 * IMHO this is bugus (dsl).
369 		 */
370 		if (!is_zero(bootstrap.b + 512-2-64, 64)) {
371 			warnx("Data in mbr partition table of new bootstrap");
372 			return 0;
373 		}
374 		if (!is_zero(bootstrap.b + 512, 512)) {
375 			warnx("Data in label part of new bootstrap");
376 			return 0;
377 		}
378 		/* Copy mbr table and label from existing disk buffer */
379 		memcpy(bootstrap.b + 512-2-64, disk_buf.b + 512-2-64, 64);
380 		memcpy(bootstrap.b + 512, disk_buf.b + 512, 512);
381 	}
382 
383 	/* Validate the 'magic number' that marks the parameter block */
384 	if (*magic != expected_magic) {
385 		warnx("Invalid magic in stage1 bootstrap %x != %x",
386 				*magic, expected_magic);
387 		return 0;
388 	}
389 
390 	/*
391 	 * If the partion has a FAT (or NTFS) filesystem, then we must
392 	 * preserve the BIOS Parameter Block (BPB).
393 	 * It is also very likely that there isn't 8k of space available
394 	 * for (say) bootxx_msdos, and that blindly installing it will trash
395 	 * the FAT filesystem.
396 	 * To avoid this we check the number of 'reserved' sectors to ensure
397 	 * there there is enough space.
398 	 * Unfortunately newfs(8) doesn't (yet) splat the BPB (which is
399 	 * effectively the FAT superblock) when a filesystem is initailised
400 	 * so this code tends to complain rather too often,
401 	 * Specifying 'installboot -f' will delete the old BPB info.
402 	 */
403 	if (!(params->flags & IB_FORCE)) {
404 		#define USE_F ", use -f (may invalidate filesystem)"
405 		/*
406 		 * For FAT compatibility, the pbr code starts 'jmp xx; nop'
407 		 * followed by the BIOS Parameter Block (BPB).
408 		 * The 2nd byte (jump offset) is the size of the nop + BPB.
409 		 */
410 		if (bootstrap.b[0] != 0xeb || bootstrap.b[2] != 0x90) {
411 			warnx("No BPB in new bootstrap %02x:%02x:%02x" USE_F,
412 				bootstrap.b[0], bootstrap.b[1], bootstrap.b[2]);
413 			return 0;
414 		}
415 
416 		/* Find size of old BPB, and copy into new bootcode */
417 		if (!is_zero(disk_buf.b + 3 + 8, disk_buf.b[1] - 1 - 8)) {
418 			struct mbr_bpbFAT16 *bpb = (void *)(disk_buf.b + 3 + 8);
419 			/* Check enough space before the FAT for the bootcode */
420 			u = le16toh(bpb->bpbBytesPerSec)
421 			    * le16toh(bpb->bpbResSectors);
422 			if (u != 0 && u < params->s1stat.st_size) {
423 				warnx("Insufficient reserved space before FAT "
424 					"(%u bytes available)" USE_F, u);
425 				return 0;
426 			}
427 			/* Check we have enough space for the old bpb */
428 			if (disk_buf.b[1] > bootstrap.b[1]) {
429 				/* old BPB is larger, allow if extra zeros */
430 				if (!is_zero(disk_buf.b + 2 + bootstrap.b[1],
431 				    disk_buf.b[1] - bootstrap.b[1])) {
432 					warnx("Old BPB too big" USE_F);
433 					    return 0;
434 				}
435 				u = bootstrap.b[1];
436 			} else {
437 				/* Old BPB is shorter, leave zero filled */
438 				u = disk_buf.b[1];
439 			}
440 			memcpy(bootstrap.b + 2, disk_buf.b + 2, u);
441 		}
442 		#undef USE_F
443 	}
444 
445 	/*
446 	 * Fill in any user-specified options into the
447 	 *      struct x86_boot_params
448 	 * that follows the magic number.
449 	 * See sys/arch/i386/stand/bootxx/bootxx.S for more information.
450 	 */
451 	if (update_i386_boot_params(params, (void *)(magic + 1)))
452 		return 0;
453 
454 	if (params->flags & IB_NOWRITE) {
455 		return 1;
456 	}
457 
458 	/* Copy new bootstrap data into disk buffer, ignoring label area */
459 	memcpy(&disk_buf, &bootstrap, 512);
460 	if (params->s1stat.st_size > 512 * 2) {
461 		memcpy(disk_buf.b + 2 * 512, bootstrap.b + 2 * 512,
462 		    params->s1stat.st_size - 2 * 512);
463 		/* Zero pad to 512 byte sector boundary */
464 		memset(disk_buf.b + params->s1stat.st_size, 0,
465 			(8192 - params->s1stat.st_size) & 511);
466 	}
467 
468 	return write_boot_area(params, &disk_buf, sizeof disk_buf);
469 }
470 
471 static int
472 i386_editboot(ib_params *params)
473 {
474 	int		retval;
475 	uint8_t		buf[512];
476 	ssize_t		rv;
477 	uint32_t	magic;
478 	uint32_t	offset;
479 	struct x86_boot_params	*bpp;
480 
481 	assert(params != NULL);
482 	assert(params->fsfd != -1);
483 	assert(params->filesystem != NULL);
484 
485 	retval = 0;
486 
487 	/*
488 	 * Read in the existing bootstrap.
489 	 * Look in any of the first 4 sectors.
490 	 */
491 
492 	bpp = NULL;
493 	for (offset = 0; offset < 4 * 512; offset += 512) {
494 		rv = pread(params->fsfd, &buf, sizeof buf, offset);
495 		if (rv == -1) {
496 			warn("Reading `%s'", params->filesystem);
497 			goto done;
498 		} else if (rv != sizeof buf) {
499 			warnx("Reading `%s': short read", params->filesystem);
500 			goto done;
501 		}
502 
503 		/* Magic number is 4 bytes in (to allow for a jmps) */
504 		/* Also allow any of the magic numbers. */
505 		magic = le32toh(*(uint32_t *)(buf + 4)) | 0xf;
506 		if (magic != (X86_BOOT_MAGIC_1 | 0xf))
507 			continue;
508 
509 		/* The parameters are just after the magic number */
510 		bpp = (void *)(buf + 8);
511 		break;
512 	}
513 	if (bpp == NULL) {
514 		warnx("Invalid magic in existing bootstrap");
515 		goto done;
516 	}
517 
518 	/*
519 	 * Fill in any user-specified options into the
520 	 *      struct x86_boot_params
521 	 * that's 8 bytes in from the start of the third sector.
522 	 * See sys/arch/i386/stand/bootxx/bootxx.S for more information.
523 	 */
524 	if (update_i386_boot_params(params, bpp))
525 		goto done;
526 
527 	if (params->flags & IB_NOWRITE) {
528 		retval = 1;
529 		goto done;
530 	}
531 
532 	/*
533 	 * Write boot code back
534 	 */
535 	rv = pwrite(params->fsfd, buf, sizeof buf, offset);
536 	if (rv == -1) {
537 		warn("Writing `%s'", params->filesystem);
538 		goto done;
539 	} else if (rv != sizeof buf) {
540 		warnx("Writing `%s': short write, %ld bytes (should be %ld)",
541 		    params->filesystem, (long)rv, (long)sizeof(buf));
542 		goto done;
543 	}
544 
545 	retval = 1;
546 
547  done:
548 	return retval;
549 }
550