xref: /openbsd-src/usr.sbin/installboot/i386_installboot.c (revision 3374c67d44f9b75b98444cbf63020f777792342e)
1 /*	$OpenBSD: i386_installboot.c,v 1.44 2022/11/06 12:33:41 krw Exp $	*/
2 /*	$NetBSD: installboot.c,v 1.5 1995/11/17 23:23:50 gwr Exp $ */
3 
4 /*
5  * Copyright (c) 2013 Pedro Martelletto
6  * Copyright (c) 2011 Joel Sing <jsing@openbsd.org>
7  * Copyright (c) 2003 Tom Cosgrove <tom.cosgrove@arches-consulting.com>
8  * Copyright (c) 1997 Michael Shalayeff
9  * Copyright (c) 1994 Paul Kranenburg
10  * All rights reserved.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  * 3. All advertising materials mentioning features or use of this software
21  *    must display the following acknowledgement:
22  *      This product includes software developed by Paul Kranenburg.
23  * 4. The name of the author may not be used to endorse or promote products
24  *    derived from this software without specific prior written permission
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
27  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
28  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
29  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
30  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
31  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
32  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
33  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
34  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
35  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36  */
37 
38 #define ELFSIZE 32
39 
40 #include <sys/param.h>	/* DEV_BSIZE */
41 #include <sys/disklabel.h>
42 #include <sys/dkio.h>
43 #include <sys/ioctl.h>
44 #include <sys/mount.h>
45 #include <sys/reboot.h>
46 #include <sys/stat.h>
47 #include <sys/sysctl.h>
48 #include <sys/time.h>
49 
50 #include <ufs/ufs/dinode.h>
51 #include <ufs/ufs/dir.h>
52 #include <ufs/ffs/fs.h>
53 
54 #include <machine/cpu.h>
55 #include <machine/biosvar.h>
56 
57 #include <elf.h>
58 #include <err.h>
59 #include <errno.h>
60 #include <fcntl.h>
61 #include <nlist.h>
62 #include <stdlib.h>
63 #include <stdio.h>
64 #include <stdint.h>
65 #include <string.h>
66 #include <unistd.h>
67 #include <util.h>
68 #include <uuid.h>
69 
70 #include "installboot.h"
71 #include "i386_installboot.h"
72 
73 char	*bootldr;
74 
75 char	*blkstore;
76 size_t	blksize;
77 
78 struct sym_data pbr_symbols[] = {
79 	{"_fs_bsize_p",	2},
80 	{"_fs_bsize_s",	2},
81 	{"_fsbtodb",	1},
82 	{"_p_offset",	4},
83 	{"_inodeblk",	4},
84 	{"_inodedbl",	4},
85 	{"_nblocks",	2},
86 	{"_blkincr",	1},
87 	{NULL}
88 };
89 
90 static void	devread(int, void *, daddr_t, size_t, char *);
91 static u_int	findopenbsd(int, struct disklabel *);
92 static int	getbootparams(char *, int, struct disklabel *);
93 static char	*loadproto(char *, long *);
94 static int	gpt_chk_mbr(struct dos_partition *, u_int64_t);
95 static int	sbchk(struct fs *, daddr_t);
96 static void	sbread(int, daddr_t, struct fs **, char *);
97 
98 static const daddr_t sbtry[] = SBLOCKSEARCH;
99 
100 /*
101  * Read information about /boot's inode and filesystem parameters, then
102  * put biosboot (partition boot record) on the target drive with these
103  * parameters patched in.
104  */
105 
106 void
107 md_init(void)
108 {
109 	stages = 2;
110 	stage1 = "/usr/mdec/biosboot";
111 	stage2 = "/usr/mdec/boot";
112 
113 	bootldr = "/boot";
114 }
115 
116 void
117 md_loadboot(void)
118 {
119 	/* Load prototype boot blocks. */
120 	if ((blkstore = loadproto(stage1, &blksize)) == NULL)
121 		exit(1);
122 
123 	/* XXX - Paranoia: Make sure size is aligned! */
124 	if (blksize & (DEV_BSIZE - 1))
125 		errx(1, "proto %s bad size=%ld", stage1, blksize);
126 
127 	if (blksize > SBSIZE - DEV_BSIZE)
128 		errx(1, "proto bootblocks too big");
129 }
130 
131 void
132 md_prepareboot(int devfd, char *dev)
133 {
134 	struct disklabel dl;
135 	int part;
136 
137 	/* Get and check disklabel. */
138 	if (ioctl(devfd, DIOCGDINFO, &dl) == -1)
139 		err(1, "disklabel: %s", dev);
140 	if (dl.d_magic != DISKMAGIC)
141 		errx(1, "bad disklabel magic=0x%08x", dl.d_magic);
142 
143 	/* Warn on unknown disklabel types. */
144 	if (dl.d_type == 0)
145 		warnx("disklabel type unknown");
146 
147 	part = findgptefisys(devfd, &dl);
148 	if (part != -1) {
149 		create_filesystem(&dl, (char)part);
150 		return;
151 	}
152 }
153 
154 void
155 md_installboot(int devfd, char *dev)
156 {
157 	struct disklabel dl;
158 	int part;
159 
160 	/* Get and check disklabel. */
161 	if (ioctl(devfd, DIOCGDINFO, &dl) == -1)
162 		err(1, "disklabel: %s", dev);
163 	if (dl.d_magic != DISKMAGIC)
164 		errx(1, "bad disklabel magic=0x%08x", dl.d_magic);
165 
166 	/* Warn on unknown disklabel types. */
167 	if (dl.d_type == 0)
168 		warnx("disklabel type unknown");
169 
170 	part = findgptefisys(devfd, &dl);
171 	if (part != -1) {
172 		write_filesystem(&dl, (char)part);
173 		return;
174 	}
175 
176 	bootldr = fileprefix(root, bootldr);
177 	if (bootldr == NULL)
178 		exit(1);
179 	if (verbose)
180 		fprintf(stderr, "%s %s to %s\n",
181 		    (nowrite ? "would copy" : "copying"), stage2, bootldr);
182 	if (!nowrite)
183 		if (filecopy(stage2, bootldr) == -1)
184 			exit(1);
185 
186 	/* Get bootstrap parameters to patch into proto. */
187 	if (getbootparams(bootldr, devfd, &dl) != 0)
188 		exit(1);
189 
190 	/* Write boot blocks to device. */
191 	write_bootblocks(devfd, dev, &dl);
192 }
193 
194 void
195 write_bootblocks(int devfd, char *dev, struct disklabel *dl)
196 {
197 	struct stat	sb;
198 	u_int8_t	*secbuf;
199 	u_int		start = 0;
200 
201 	/* Write patched proto bootblock(s) into the superblock. */
202 	if (fstat(devfd, &sb) == -1)
203 		err(1, "fstat: %s", dev);
204 
205 	if (!S_ISCHR(sb.st_mode))
206 		errx(1, "%s: not a character device", dev);
207 
208 	/* Patch the parameters into the proto bootstrap sector. */
209 	pbr_set_symbols(stage1, blkstore, pbr_symbols);
210 
211 	if (!nowrite) {
212 		/* Sync filesystems (to clean in-memory superblock?). */
213 		sync(); sleep(1);
214 	}
215 
216 	/*
217 	 * Find OpenBSD partition. Floppies are special, getting an
218 	 * everything-in-one /boot starting at sector 0.
219 	 */
220 	if (dl->d_type != DTYPE_FLOPPY) {
221 		start = findopenbsd(devfd, dl);
222 		if (start == (u_int)-1)
223 			errx(1, "no OpenBSD partition");
224 	}
225 
226 	if (verbose)
227 		fprintf(stderr, "%s will be written at sector %u\n",
228 		    stage1, start);
229 
230 	if (start + (blksize / dl->d_secsize) > BOOTBIOS_MAXSEC)
231 		warnx("%s extends beyond sector %u. OpenBSD might not boot.",
232 		    stage1, BOOTBIOS_MAXSEC);
233 
234 	if (!nowrite) {
235 		secbuf = calloc(1, dl->d_secsize);
236 		if (pread(devfd, secbuf, dl->d_secsize, (off_t)start *
237 		    dl->d_secsize) != dl->d_secsize)
238 			err(1, "pread boot sector");
239 		bcopy(blkstore, secbuf, blksize);
240 		if (pwrite(devfd, secbuf, dl->d_secsize, (off_t)start *
241 		    dl->d_secsize) != dl->d_secsize)
242 			err(1, "pwrite bootstrap");
243 		free(secbuf);
244 	}
245 }
246 
247 int
248 create_filesystem(struct disklabel *dl, char part)
249 {
250 	static const char *newfsfmt = "/sbin/newfs -t msdos %s >/dev/null";
251 	struct msdosfs_args args;
252 	char cmd[60];
253 	int rslt;
254 
255 	/* Mount <duid>.<part> as msdos filesystem. */
256 	memset(&args, 0, sizeof(args));
257 	rslt = asprintf(&args.fspec,
258 	    "%02hhx%02hhx%02hhx%02hhx%02hhx%02hhx%02hhx%02hhx.%c",
259             dl->d_uid[0], dl->d_uid[1], dl->d_uid[2], dl->d_uid[3],
260             dl->d_uid[4], dl->d_uid[5], dl->d_uid[6], dl->d_uid[7],
261 	    part);
262 	if (rslt == -1) {
263 		warn("bad special device");
264 		return rslt;
265 	}
266 
267 	rslt = snprintf(cmd, sizeof(cmd), newfsfmt, args.fspec);
268 	if (rslt >= sizeof(cmd)) {
269 		warnx("can't build newfs command");
270 		free(args.fspec);
271 		rslt = -1;
272 		return rslt;
273 	}
274 
275 	if (verbose)
276 		fprintf(stderr, "%s %s\n",
277 		    (nowrite ? "would newfs" : "newfsing"), args.fspec);
278 	if (!nowrite) {
279 		rslt = system(cmd);
280 		if (rslt == -1) {
281 			warn("system('%s') failed", cmd);
282 			free(args.fspec);
283 			return rslt;
284 		}
285 	}
286 
287 	free(args.fspec);
288 	return 0;
289 }
290 
291 void
292 write_filesystem(struct disklabel *dl, char part)
293 {
294 	static const char *fsckfmt = "/sbin/fsck -t msdos %s >/dev/null";
295 	struct msdosfs_args args;
296 	char cmd[60];
297 	char dst[PATH_MAX];
298 	char *src;
299 	size_t mntlen, pathlen, srclen;
300 	int rslt;
301 
302 	src = NULL;
303 
304 	/* Create directory for temporary mount point. */
305 	strlcpy(dst, "/tmp/installboot.XXXXXXXXXX", sizeof(dst));
306 	if (mkdtemp(dst) == NULL)
307 		err(1, "mkdtemp('%s') failed", dst);
308 	mntlen = strlen(dst);
309 
310 	/* Mount <duid>.<part> as msdos filesystem. */
311 	memset(&args, 0, sizeof(args));
312 	rslt = asprintf(&args.fspec,
313 	    "%02hhx%02hhx%02hhx%02hhx%02hhx%02hhx%02hhx%02hhx.%c",
314             dl->d_uid[0], dl->d_uid[1], dl->d_uid[2], dl->d_uid[3],
315             dl->d_uid[4], dl->d_uid[5], dl->d_uid[6], dl->d_uid[7],
316 	    part);
317 	if (rslt == -1) {
318 		warn("bad special device");
319 		goto rmdir;
320 	}
321 
322 	args.export_info.ex_root = -2;	/* unchecked anyway on DOS fs */
323 	args.export_info.ex_flags = 0;
324 	args.flags = MSDOSFSMNT_LONGNAME;
325 
326 	if (mount(MOUNT_MSDOS, dst, 0, &args) == -1) {
327 		/* Try fsck'ing it. */
328 		rslt = snprintf(cmd, sizeof(cmd), fsckfmt, args.fspec);
329 		if (rslt >= sizeof(cmd)) {
330 			warnx("can't build fsck command");
331 			rslt = -1;
332 			goto rmdir;
333 		}
334 		rslt = system(cmd);
335 		if (rslt == -1) {
336 			warn("system('%s') failed", cmd);
337 			goto rmdir;
338 		}
339 		if (mount(MOUNT_MSDOS, dst, 0, &args) == -1) {
340 			/* Try newfs'ing it. */
341 			rslt = create_filesystem(dl, part);
342 			if (rslt == -1)
343 				goto rmdir;
344 			rslt = mount(MOUNT_MSDOS, dst, 0, &args);
345 			if (rslt == -1) {
346 				warn("unable to mount EFI System partition");
347 				goto rmdir;
348 			}
349 		}
350 	}
351 
352 	/* Create "/efi/BOOT" directory in <duid>.<part>. */
353 	if (strlcat(dst, "/efi", sizeof(dst)) >= sizeof(dst)) {
354 		rslt = -1;
355 		warn("unable to build /efi directory");
356 		goto umount;
357 	}
358 	rslt = mkdir(dst, 0);
359 	if (rslt == -1 && errno != EEXIST) {
360 		warn("mkdir('%s') failed", dst);
361 		goto umount;
362 	}
363 	if (strlcat(dst, "/BOOT", sizeof(dst)) >= sizeof(dst)) {
364 		rslt = -1;
365 		warn("unable to build /BOOT directory");
366 		goto umount;
367 	}
368 	rslt = mkdir(dst, 0);
369 	if (rslt == -1 && errno != EEXIST) {
370 		warn("mkdir('%s') failed", dst);
371 		goto umount;
372 	}
373 
374 	/*
375 	 * Copy BOOTIA32.EFI and BOOTX64.EFI to /efi/BOOT/.
376 	 *
377 	 * N.B.: BOOTIA32.EFI is longer than BOOTX64.EFI, so src can be reused!
378 	 */
379 	pathlen = strlen(dst);
380 	if (strlcat(dst, "/BOOTIA32.EFI", sizeof(dst)) >= sizeof(dst)) {
381 		rslt = -1;
382 		warn("unable to build /BOOTIA32.EFI path");
383 		goto umount;
384 	}
385 	src = fileprefix(root, "/usr/mdec/BOOTIA32.EFI");
386 	if (src == NULL) {
387 		rslt = -1;
388 		goto umount;
389 	}
390 	srclen = strlen(src);
391 	if (verbose)
392 		fprintf(stderr, "%s %s to %s\n",
393 		    (nowrite ? "would copy" : "copying"), src, dst);
394 	if (!nowrite) {
395 		rslt = filecopy(src, dst);
396 		if (rslt == -1)
397 			goto umount;
398 	}
399 	src[srclen - strlen("/BOOTIA32.EFI")] = '\0';
400 
401 	dst[pathlen] = '\0';
402 	if (strlcat(dst, "/BOOTX64.EFI", sizeof(dst)) >= sizeof(dst)) {
403 		rslt = -1;
404 		warn("unable to build /BOOTX64.EFI dst path");
405 		goto umount;
406 	}
407 	if (strlcat(src, "/BOOTX64.EFI", srclen+1) >= srclen+1) {
408 		rslt = -1;
409 		warn("unable to build /BOOTX64.EFI src path");
410 		goto umount;
411 	}
412 	if (verbose)
413 		fprintf(stderr, "%s %s to %s\n",
414 		    (nowrite ? "would copy" : "copying"), src, dst);
415 	if (!nowrite) {
416 		rslt = filecopy(src, dst);
417 		if (rslt == -1)
418 			goto umount;
419 	}
420 
421 	rslt = 0;
422 
423 umount:
424 	dst[mntlen] = '\0';
425 	if (unmount(dst, MNT_FORCE) == -1)
426 		err(1, "unmount('%s') failed", dst);
427 
428 rmdir:
429 	free(args.fspec);
430 	dst[mntlen] = '\0';
431 	if (rmdir(dst) == -1)
432 		err(1, "rmdir('%s') failed", dst);
433 
434 	free(src);
435 
436 	if (rslt == -1)
437 		exit(1);
438 }
439 
440 u_int
441 findopenbsd(int devfd, struct disklabel *dl)
442 {
443 	struct		dos_mbr mbr;
444 	u_int		mbroff = DOSBBSECTOR;
445 	u_int		mbr_eoff = DOSBBSECTOR; /* Offset of extended part. */
446 	struct		dos_partition *dp;
447 	u_int8_t	*secbuf;
448 	u_int		maxebr = DOS_MAXEBR, nextebr;
449 	int		i;
450 
451 again:
452 	if (!maxebr--) {
453 		if (verbose)
454 			fprintf(stderr, "Traversed more than %d Extended Boot "
455 			    "Records (EBRs)\n", DOS_MAXEBR);
456 		return ((u_int)-1);
457 	}
458 
459 	if (verbose)
460 		fprintf(stderr, "%s boot record (%cBR) at sector %u\n",
461 		    (mbroff == DOSBBSECTOR) ? "master" : "extended",
462 		    (mbroff == DOSBBSECTOR) ? 'M' : 'E', mbroff);
463 
464 	if ((secbuf = malloc(dl->d_secsize)) == NULL)
465 		err(1, NULL);
466 	if (pread(devfd, secbuf, dl->d_secsize, (off_t)mbroff * dl->d_secsize)
467 	    < (ssize_t)sizeof(mbr))
468 		err(4, "can't pread boot record");
469 	bcopy(secbuf, &mbr, sizeof(mbr));
470 	free(secbuf);
471 
472 	if (mbr.dmbr_sign != DOSMBR_SIGNATURE)
473 		errx(1, "invalid boot record signature (0x%04X) @ sector %u",
474 		    mbr.dmbr_sign, mbroff);
475 
476 	nextebr = 0;
477 	for (i = 0; i < NDOSPART; i++) {
478 		dp = &mbr.dmbr_parts[i];
479 		if (!dp->dp_size)
480 			continue;
481 
482 		if (verbose)
483 			fprintf(stderr,
484 			    "\tpartition %d: type 0x%02X offset %u size %u\n",
485 			    i, dp->dp_typ, dp->dp_start, dp->dp_size);
486 
487 		if (dp->dp_typ == DOSPTYP_OPENBSD) {
488 			if (dp->dp_start > (dp->dp_start + mbroff))
489 				continue;
490 			return (dp->dp_start + mbroff);
491 		}
492 
493 		if (!nextebr && (dp->dp_typ == DOSPTYP_EXTEND ||
494 		    dp->dp_typ == DOSPTYP_EXTENDL)) {
495 			nextebr = dp->dp_start + mbr_eoff;
496 			if (nextebr < dp->dp_start)
497 				nextebr = (u_int)-1;
498 			if (mbr_eoff == DOSBBSECTOR)
499 				mbr_eoff = dp->dp_start;
500 		}
501 	}
502 
503 	if (nextebr && nextebr != (u_int)-1) {
504 		mbroff = nextebr;
505 		goto again;
506 	}
507 
508 	return ((u_int)-1);
509 }
510 
511 /*
512  * Returns 0 if the MBR with the provided partition array is a GPT protective
513  * MBR, and returns 1 otherwise. A GPT protective MBR would have one and only
514  * one MBR partition, an EFI partition that either covers the whole disk or as
515  * much of it as is possible with a 32bit size field.
516  *
517  * NOTE: MS always uses a size of UINT32_MAX for the EFI partition!**
518  */
519 static int
520 gpt_chk_mbr(struct dos_partition *dp, u_int64_t dsize)
521 {
522 	struct dos_partition *dp2;
523 	int efi, found, i;
524 	u_int32_t psize;
525 
526 	found = efi = 0;
527 	for (dp2=dp, i=0; i < NDOSPART; i++, dp2++) {
528 		if (dp2->dp_typ == DOSPTYP_UNUSED)
529 			continue;
530 		found++;
531 		if (dp2->dp_typ != DOSPTYP_EFI)
532 			continue;
533 		if (letoh32(dp2->dp_start) != GPTSECTOR)
534 			continue;
535 		psize = letoh32(dp2->dp_size);
536 		if (psize <= (dsize - GPTSECTOR) || psize == UINT32_MAX)
537 			efi++;
538 	}
539 	if (found == 1 && efi == 1)
540 		return (0);
541 
542 	return (1);
543 }
544 
545 int
546 findgptefisys(int devfd, struct disklabel *dl)
547 {
548 	struct gpt_partition	 gp[NGPTPARTITIONS];
549 	struct gpt_header	 gh;
550 	struct dos_partition	 dp[NDOSPART];
551 	struct uuid		 efisys_uuid;
552 	const char		 efisys_uuid_code[] = GPT_UUID_EFI_SYSTEM;
553 	off_t			 off;
554 	ssize_t			 len;
555 	u_int64_t		 start;
556 	int			 i;
557 	uint32_t		 orig_csum, new_csum;
558 	uint32_t		 ghsize, ghpartsize, ghpartnum, ghpartspersec;
559 	u_int8_t		*secbuf;
560 
561 	/* Prepare EFI System UUID */
562 	uuid_dec_be(efisys_uuid_code, &efisys_uuid);
563 
564 	if ((secbuf = malloc(dl->d_secsize)) == NULL)
565 		err(1, NULL);
566 
567 	/* Check that there is a protective MBR. */
568 	len = pread(devfd, secbuf, dl->d_secsize, 0);
569 	if (len != dl->d_secsize)
570 		err(4, "can't read mbr");
571 	memcpy(dp, &secbuf[DOSPARTOFF], sizeof(dp));
572 	if (gpt_chk_mbr(dp, DL_GETDSIZE(dl))) {
573 		free(secbuf);
574 		return (-1);
575 	}
576 
577 	/* Check GPT Header. */
578 	off = dl->d_secsize;	/* Read header from sector 1. */
579 	len = pread(devfd, secbuf, dl->d_secsize, off);
580 	if (len != dl->d_secsize)
581 		err(4, "can't pread gpt header");
582 
583 	memcpy(&gh, secbuf, sizeof(gh));
584 	free(secbuf);
585 
586 	/* Check signature */
587 	if (letoh64(gh.gh_sig) != GPTSIGNATURE)
588 		return (-1);
589 
590 	if (letoh32(gh.gh_rev) != GPTREVISION)
591 		return (-1);
592 
593 	ghsize = letoh32(gh.gh_size);
594 	if (ghsize < GPTMINHDRSIZE || ghsize > sizeof(struct gpt_header))
595 		return (-1);
596 
597 	/* Check checksum */
598 	orig_csum = gh.gh_csum;
599 	gh.gh_csum = 0;
600 	new_csum = crc32((unsigned char *)&gh, ghsize);
601 	gh.gh_csum = orig_csum;
602 	if (letoh32(orig_csum) != new_csum)
603 		return (-1);
604 
605 	off = letoh64(gh.gh_part_lba) * dl->d_secsize;
606 	ghpartsize = letoh32(gh.gh_part_size);
607 	ghpartspersec = dl->d_secsize / ghpartsize;
608 	ghpartnum = letoh32(gh.gh_part_num);
609 	if ((secbuf = malloc(dl->d_secsize)) == NULL)
610 		err(1, NULL);
611 	for (i = 0; i < (ghpartnum + ghpartspersec - 1) / ghpartspersec; i++) {
612 		len = pread(devfd, secbuf, dl->d_secsize, off);
613 		if (len != dl->d_secsize) {
614 			free(secbuf);
615 			return (-1);
616 		}
617 		memcpy(gp + i * ghpartspersec, secbuf,
618 		    ghpartspersec * sizeof(struct gpt_partition));
619 		off += dl->d_secsize;
620 	}
621 	free(secbuf);
622 	new_csum = crc32((unsigned char *)&gp, ghpartnum * ghpartsize);
623 	if (new_csum != letoh32(gh.gh_part_csum))
624 		return (-1);
625 
626 	start = 0;
627 	for (i = 0; i < ghpartnum && start == 0; i++) {
628 		if (memcmp(&gp[i].gp_type, &efisys_uuid,
629 		    sizeof(struct uuid)) == 0)
630 			start = letoh64(gp[i].gp_lba_start);
631 	}
632 
633 	if (start) {
634 		for (i = 0; i < MAXPARTITIONS; i++) {
635 			if (DL_GETPSIZE(&dl->d_partitions[i]) > 0 &&
636 			    DL_GETPOFFSET(&dl->d_partitions[i]) == start)
637 				return ('a' + i);
638 		}
639 	}
640 
641 	return (-1);
642 }
643 
644 /*
645  * Load the prototype boot sector (biosboot) into memory.
646  */
647 static char *
648 loadproto(char *fname, long *size)
649 {
650 	int	fd;
651 	size_t	tdsize;		/* text+data size */
652 	char	*bp;
653 	Elf_Ehdr eh;
654 	Elf_Word phsize;
655 	Elf_Phdr *ph;
656 
657 	if ((fd = open(fname, O_RDONLY)) == -1)
658 		err(1, "%s", fname);
659 
660 	if (read(fd, &eh, sizeof(eh)) != sizeof(eh))
661 		errx(1, "%s: read failed", fname);
662 
663 	if (!IS_ELF(eh))
664 		errx(1, "%s: bad magic: 0x%02x%02x%02x%02x", fname,
665 		    eh.e_ident[EI_MAG0], eh.e_ident[EI_MAG1],
666 		    eh.e_ident[EI_MAG2], eh.e_ident[EI_MAG3]);
667 
668 	/*
669 	 * We have to include the exec header in the beginning of
670 	 * the buffer, and leave extra space at the end in case
671 	 * the actual write to disk wants to skip the header.
672 	 */
673 
674 	/* Program load header. */
675 	if (eh.e_phnum != 1)
676 		errx(1, "%s: %u ELF load sections (only support 1)",
677 		    fname, eh.e_phnum);
678 
679 	ph = reallocarray(NULL, eh.e_phnum, sizeof(Elf_Phdr));
680 	if (ph == NULL)
681 		err(1, NULL);
682 	phsize = eh.e_phnum * sizeof(Elf_Phdr);
683 
684 	if (pread(fd, ph, phsize, eh.e_phoff) != phsize)
685 		errx(1, "%s: can't pread header", fname);
686 
687 	tdsize = ph->p_filesz;
688 
689 	/*
690 	 * Allocate extra space here because the caller may copy
691 	 * the boot block starting at the end of the exec header.
692 	 * This prevents reading beyond the end of the buffer.
693 	 */
694 	if ((bp = calloc(tdsize, 1)) == NULL)
695 		err(1, NULL);
696 
697 	/* Read the rest of the file. */
698 	if (pread(fd, bp, tdsize, ph->p_offset) != (ssize_t)tdsize)
699 		errx(1, "%s: pread failed", fname);
700 
701 	*size = tdsize;	/* not aligned to DEV_BSIZE */
702 
703 	close(fd);
704 	return bp;
705 }
706 
707 static void
708 devread(int fd, void *buf, daddr_t blk, size_t size, char *msg)
709 {
710 	if (pread(fd, buf, size, dbtob((off_t)blk)) != (ssize_t)size)
711 		err(1, "%s: devread: pread", msg);
712 }
713 
714 /*
715  * Read information about /boot's inode, then put this and filesystem
716  * parameters from the superblock into pbr_symbols.
717  */
718 static int
719 getbootparams(char *boot, int devfd, struct disklabel *dl)
720 {
721 	int		fd;
722 	struct stat	dsb, fsb;
723 	struct statfs	fssb;
724 	struct partition *pp;
725 	struct fs	*fs;
726 	char		*sblock, *buf;
727 	u_int		blk, *ap;
728 	int		ndb;
729 	int		mib[3];
730 	size_t		size;
731 	dev_t		dev;
732 	int		incr;
733 
734 	/*
735 	 * Open 2nd-level boot program and record enough details about
736 	 * where it is on the filesystem represented by `devfd'
737 	 * (inode block, offset within that block, and various filesystem
738 	 * parameters essentially taken from the superblock) for biosboot
739 	 * to be able to load it later.
740 	 */
741 
742 	/* Make sure the (probably new) boot file is on disk. */
743 	sync(); sleep(1);
744 
745 	if ((fd = open(boot, O_RDONLY)) == -1)
746 		err(1, "open: %s", boot);
747 
748 	if (fstatfs(fd, &fssb) == -1)
749 		err(1, "statfs: %s", boot);
750 
751 	if (strncmp(fssb.f_fstypename, "ffs", MFSNAMELEN) &&
752 	    strncmp(fssb.f_fstypename, "ufs", MFSNAMELEN) )
753 		errx(1, "%s: not on an FFS filesystem", boot);
754 
755 #if 0
756 	if (read(fd, &eh, sizeof(eh)) != sizeof(eh))
757 		errx(1, "read: %s", boot);
758 
759 	if (!IS_ELF(eh)) {
760 		errx(1, "%s: bad magic: 0x%02x%02x%02x%02x",
761 		    boot,
762 		    eh.e_ident[EI_MAG0], eh.e_ident[EI_MAG1],
763 		    eh.e_ident[EI_MAG2], eh.e_ident[EI_MAG3]);
764 	}
765 #endif
766 
767 	if (fsync(fd) != 0)
768 		err(1, "fsync: %s", boot);
769 
770 	if (fstat(fd, &fsb) != 0)
771 		err(1, "fstat: %s", boot);
772 
773 	if (fstat(devfd, &dsb) != 0)
774 		err(1, "fstat: %d", devfd);
775 
776 	/* Check devices. */
777 	mib[0] = CTL_MACHDEP;
778 	mib[1] = CPU_CHR2BLK;
779 	mib[2] = dsb.st_rdev;
780 	size = sizeof(dev);
781 	if (sysctl(mib, 3, &dev, &size, NULL, 0) >= 0) {
782 		if (fsb.st_dev / MAXPARTITIONS != dev / MAXPARTITIONS)
783 			errx(1, "cross-device install");
784 	}
785 
786 	pp = &dl->d_partitions[DISKPART(fsb.st_dev)];
787 	close(fd);
788 
789 	if ((sblock = malloc(SBSIZE)) == NULL)
790 		err(1, NULL);
791 
792 	sbread(devfd, DL_SECTOBLK(dl, pp->p_offset), &fs, sblock);
793 
794 	/* Read inode. */
795 	if ((buf = malloc(fs->fs_bsize)) == NULL)
796 		err(1, NULL);
797 
798 	blk = fsbtodb(fs, ino_to_fsba(fs, fsb.st_ino));
799 
800 	/*
801 	 * Have the inode.  Figure out how many filesystem blocks (not disk
802 	 * sectors) there are for biosboot to load.
803 	 */
804 	devread(devfd, buf, DL_SECTOBLK(dl, pp->p_offset) + blk,
805 	    fs->fs_bsize, "inode");
806 	if (fs->fs_magic == FS_UFS2_MAGIC) {
807 		struct ufs2_dinode *ip2 = (struct ufs2_dinode *)(buf) +
808 		    ino_to_fsbo(fs, fsb.st_ino);
809 		ndb = howmany(ip2->di_size, fs->fs_bsize);
810 		ap = (u_int *)ip2->di_db;
811 		incr = sizeof(u_int32_t);
812 	} else {
813 		struct ufs1_dinode *ip1 = (struct ufs1_dinode *)(buf) +
814 		    ino_to_fsbo(fs, fsb.st_ino);
815 		ndb = howmany(ip1->di_size, fs->fs_bsize);
816 		ap = (u_int *)ip1->di_db;
817 		incr = 0;
818 	}
819 
820 	if (ndb <= 0)
821 		errx(1, "No blocks to load");
822 
823 	/*
824 	 * Now set the values that will need to go into biosboot
825 	 * (the partition boot record, a.k.a. the PBR).
826 	 */
827 	sym_set_value(pbr_symbols, "_fs_bsize_p", (fs->fs_bsize / 16));
828 	sym_set_value(pbr_symbols, "_fs_bsize_s", (fs->fs_bsize /
829 	    dl->d_secsize));
830 
831 	/*
832 	 * fs_fsbtodb is the shift to convert fs_fsize to DEV_BSIZE. The
833 	 * ino_to_fsba() return value is the number of fs_fsize units.
834 	 * Calculate the shift to convert fs_fsize into physical sectors,
835 	 * which are added to p_offset to get the sector address BIOS
836 	 * will use.
837 	 *
838 	 * N.B.: ASSUMES fs_fsize is a power of 2 of d_secsize.
839 	 */
840 	sym_set_value(pbr_symbols, "_fsbtodb",
841 	    ffs(fs->fs_fsize / dl->d_secsize) - 1);
842 
843 	sym_set_value(pbr_symbols, "_p_offset", pp->p_offset);
844 	sym_set_value(pbr_symbols, "_inodeblk",
845 	    ino_to_fsba(fs, fsb.st_ino));
846 	sym_set_value(pbr_symbols, "_inodedbl",
847 	    ((((char *)ap) - buf) + INODEOFF));
848 	sym_set_value(pbr_symbols, "_nblocks", ndb);
849 	sym_set_value(pbr_symbols, "_blkincr", incr);
850 
851 	if (verbose) {
852 		fprintf(stderr, "%s is %d blocks x %d bytes\n",
853 		    boot, ndb, fs->fs_bsize);
854 		fprintf(stderr, "fs block shift %u; part offset %u; "
855 		    "inode block %lld, offset %u\n",
856 		    ffs(fs->fs_fsize / dl->d_secsize) - 1,
857 		    pp->p_offset,
858 		    ino_to_fsba(fs, fsb.st_ino),
859 		    (unsigned int)((((char *)ap) - buf) + INODEOFF));
860 		fprintf(stderr, "expecting %d-bit fs blocks (incr %d)\n",
861 		    incr ? 64 : 32, incr);
862 	}
863 
864 	free (sblock);
865 	free (buf);
866 
867 	return 0;
868 }
869 
870 void
871 sym_set_value(struct sym_data *sym_list, char *sym, u_int32_t value)
872 {
873 	struct sym_data *p;
874 
875 	for (p = sym_list; p->sym_name != NULL; p++) {
876 		if (strcmp(p->sym_name, sym) == 0)
877 			break;
878 	}
879 
880 	if (p->sym_name == NULL)
881 		errx(1, "%s: no such symbol", sym);
882 
883 	p->sym_value = value;
884 	p->sym_set = 1;
885 }
886 
887 /*
888  * Write the parameters stored in sym_list into the in-memory copy of
889  * the prototype biosboot (proto), ready for it to be written to disk.
890  */
891 void
892 pbr_set_symbols(char *fname, char *proto, struct sym_data *sym_list)
893 {
894 	struct sym_data *sym;
895 	struct nlist	*nl;
896 	char		*vp;
897 	u_int32_t	*lp;
898 	u_int16_t	*wp;
899 	u_int8_t	*bp;
900 
901 	for (sym = sym_list; sym->sym_name != NULL; sym++) {
902 		if (!sym->sym_set)
903 			errx(1, "%s not set", sym->sym_name);
904 
905 		/* Allocate space for 2; second is null-terminator for list. */
906 		nl = calloc(2, sizeof(struct nlist));
907 		if (nl == NULL)
908 			err(1, NULL);
909 
910 		nl->n_name = sym->sym_name;
911 
912 		if (nlist_elf32(fname, nl) != 0)
913 			errx(1, "%s: symbol %s not found",
914 			    fname, sym->sym_name);
915 
916 		if (nl->n_type != (N_TEXT))
917 			errx(1, "%s: %s: wrong type (%x)",
918 			    fname, sym->sym_name, nl->n_type);
919 
920 		/* Get a pointer to where the symbol's value needs to go. */
921 		vp = proto + nl->n_value;
922 
923 		switch (sym->sym_size) {
924 		case 4:					/* u_int32_t */
925 			lp = (u_int32_t *) vp;
926 			*lp = sym->sym_value;
927 			break;
928 		case 2:					/* u_int16_t */
929 			if (sym->sym_value >= 0x10000)	/* out of range */
930 				errx(1, "%s: symbol out of range (%u)",
931 				    sym->sym_name, sym->sym_value);
932 			wp = (u_int16_t *) vp;
933 			*wp = (u_int16_t) sym->sym_value;
934 			break;
935 		case 1:					/* u_int16_t */
936 			if (sym->sym_value >= 0x100)	/* out of range */
937 				errx(1, "%s: symbol out of range (%u)",
938 				    sym->sym_name, sym->sym_value);
939 			bp = (u_int8_t *) vp;
940 			*bp = (u_int8_t) sym->sym_value;
941 			break;
942 		default:
943 			errx(1, "%s: bad symbol size %d",
944 			    sym->sym_name, sym->sym_size);
945 			/* NOTREACHED */
946 		}
947 
948 		free(nl);
949 	}
950 }
951 
952 static int
953 sbchk(struct fs *fs, daddr_t sbloc)
954 {
955 	if (verbose)
956 		fprintf(stderr, "looking for superblock at %lld\n", sbloc);
957 
958 	if (fs->fs_magic != FS_UFS2_MAGIC && fs->fs_magic != FS_UFS1_MAGIC) {
959 		if (verbose)
960 			fprintf(stderr, "bad superblock magic 0x%x\n",
961 			    fs->fs_magic);
962 		return (0);
963 	}
964 
965 	/*
966 	 * Looking for an FFS1 file system at SBLOCK_UFS2 will find the
967 	 * wrong superblock for file systems with 64k block size.
968 	 */
969 	if (fs->fs_magic == FS_UFS1_MAGIC && sbloc == SBLOCK_UFS2) {
970 		if (verbose)
971 			fprintf(stderr, "skipping ffs1 superblock at %lld\n",
972 			    sbloc);
973 		return (0);
974 	}
975 
976 	if (fs->fs_bsize <= 0 || fs->fs_bsize < sizeof(struct fs) ||
977 	    fs->fs_bsize > MAXBSIZE) {
978 		if (verbose)
979 			fprintf(stderr, "invalid superblock block size %d\n",
980 			    fs->fs_bsize);
981 		return (0);
982 	}
983 
984 	if (fs->fs_sbsize <= 0 || fs->fs_sbsize > SBSIZE) {
985 		if (verbose)
986 			fprintf(stderr, "invalid superblock size %d\n",
987 			    fs->fs_sbsize);
988 		return (0);
989 	}
990 
991 	if (fs->fs_inopb <= 0) {
992 		if (verbose)
993 			fprintf(stderr, "invalid superblock inodes/block %d\n",
994 			    fs->fs_inopb);
995 		return (0);
996 	}
997 
998 	if (verbose)
999 		fprintf(stderr, "found valid %s superblock\n",
1000 		    fs->fs_magic == FS_UFS2_MAGIC ? "ffs2" : "ffs1");
1001 
1002 	return (1);
1003 }
1004 
1005 static void
1006 sbread(int fd, daddr_t poffset, struct fs **fs, char *sblock)
1007 {
1008 	int i;
1009 	daddr_t sboff;
1010 
1011 	for (i = 0; sbtry[i] != -1; i++) {
1012 		sboff = sbtry[i] / DEV_BSIZE;
1013 		devread(fd, sblock, poffset + sboff, SBSIZE, "superblock");
1014 		*fs = (struct fs *)sblock;
1015 		if (sbchk(*fs, sbtry[i]))
1016 			break;
1017 	}
1018 
1019 	if (sbtry[i] == -1)
1020 		errx(1, "couldn't find ffs superblock");
1021 }
1022