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