xref: /freebsd/stand/i386/gptboot/gptboot.c (revision 60eddb209b5ad13a549ca74a41b7cb38a31da5ef)
1 /*-
2  * Copyright (c) 1998 Robert Nordier
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms are freely
6  * permitted provided that the above copyright notice and this
7  * paragraph and the following disclaimer are duplicated in all
8  * such forms.
9  *
10  * This software is provided "AS IS" and without any express or
11  * implied warranties, including, without limitation, the implied
12  * warranties of merchantability and fitness for a particular
13  * purpose.
14  */
15 
16 #include <sys/cdefs.h>
17 __FBSDID("$FreeBSD$");
18 
19 #include <sys/param.h>
20 #include <sys/gpt.h>
21 #include <sys/dirent.h>
22 #include <sys/reboot.h>
23 
24 #include <machine/bootinfo.h>
25 #include <machine/elf.h>
26 #include <machine/pc/bios.h>
27 #include <machine/psl.h>
28 
29 #include <stdarg.h>
30 
31 #include <a.out.h>
32 
33 #include <btxv86.h>
34 
35 #include "stand.h"
36 
37 #include "bootargs.h"
38 #include "lib.h"
39 #include "rbx.h"
40 #include "drv.h"
41 #include "cons.h"
42 #include "gpt.h"
43 #include "paths.h"
44 
45 #define ARGS		0x900
46 #define NOPT		14
47 #define NDEV		3
48 #define MEM_BASE	0x12
49 #define MEM_EXT 	0x15
50 
51 #define DRV_HARD	0x80
52 #define DRV_MASK	0x7f
53 
54 #define TYPE_AD		0
55 #define TYPE_DA		1
56 #define TYPE_MAXHARD	TYPE_DA
57 #define TYPE_FD		2
58 
59 extern uint32_t _end;
60 
61 static const uuid_t freebsd_ufs_uuid = GPT_ENT_TYPE_FREEBSD_UFS;
62 static const char optstr[NOPT] = "DhaCcdgmnpqrsv"; /* Also 'P', 'S' */
63 static const unsigned char flags[NOPT] = {
64 	RBX_DUAL,
65 	RBX_SERIAL,
66 	RBX_ASKNAME,
67 	RBX_CDROM,
68 	RBX_CONFIG,
69 	RBX_KDB,
70 	RBX_GDB,
71 	RBX_MUTE,
72 	RBX_NOINTR,
73 	RBX_PAUSE,
74 	RBX_QUIET,
75 	RBX_DFLTROOT,
76 	RBX_SINGLE,
77 	RBX_VERBOSE
78 };
79 uint32_t opts;
80 
81 static const char *const dev_nm[NDEV] = {"ad", "da", "fd"};
82 static const unsigned char dev_maj[NDEV] = {30, 4, 2};
83 
84 static struct dsk dsk;
85 static char kname[1024];
86 static int comspeed = SIOSPD;
87 static struct bootinfo bootinfo;
88 #ifdef LOADER_GELI_SUPPORT
89 static struct geli_boot_args geliargs;
90 #endif
91 
92 static vm_offset_t	high_heap_base;
93 static uint32_t		bios_basemem, bios_extmem, high_heap_size;
94 
95 static struct bios_smap smap;
96 
97 /*
98  * The minimum amount of memory to reserve in bios_extmem for the heap.
99  */
100 #define	HEAP_MIN	(3 * 1024 * 1024)
101 
102 static char *heap_next;
103 static char *heap_end;
104 
105 void exit(int);
106 static void load(void);
107 static int parse_cmds(char *, int *);
108 static int dskread(void *, daddr_t, unsigned);
109 #ifdef LOADER_GELI_SUPPORT
110 static int vdev_read(void *vdev __unused, void *priv, off_t off, void *buf,
111 	size_t bytes);
112 #endif
113 
114 #include "ufsread.c"
115 #include "gpt.c"
116 #ifdef LOADER_GELI_SUPPORT
117 #include "geliboot.c"
118 static char gelipw[GELI_PW_MAXLEN];
119 static struct keybuf *gelibuf;
120 #endif
121 
122 static inline int
123 xfsread(ufs_ino_t inode, void *buf, size_t nbyte)
124 {
125 
126 	if ((size_t)fsread(inode, buf, nbyte) != nbyte) {
127 		printf("Invalid %s\n", "format");
128 		return (-1);
129 	}
130 	return (0);
131 }
132 
133 static void
134 bios_getmem(void)
135 {
136     uint64_t size;
137 
138     /* Parse system memory map */
139     v86.ebx = 0;
140     do {
141 	v86.ctl = V86_FLAGS;
142 	v86.addr = MEM_EXT;		/* int 0x15 function 0xe820*/
143 	v86.eax = 0xe820;
144 	v86.ecx = sizeof(struct bios_smap);
145 	v86.edx = SMAP_SIG;
146 	v86.es = VTOPSEG(&smap);
147 	v86.edi = VTOPOFF(&smap);
148 	v86int();
149 	if ((v86.efl & 1) || (v86.eax != SMAP_SIG))
150 	    break;
151 	/* look for a low-memory segment that's large enough */
152 	if ((smap.type == SMAP_TYPE_MEMORY) && (smap.base == 0) &&
153 	    (smap.length >= (512 * 1024)))
154 	    bios_basemem = smap.length;
155 	/* look for the first segment in 'extended' memory */
156 	if ((smap.type == SMAP_TYPE_MEMORY) && (smap.base == 0x100000)) {
157 	    bios_extmem = smap.length;
158 	}
159 
160 	/*
161 	 * Look for the largest segment in 'extended' memory beyond
162 	 * 1MB but below 4GB.
163 	 */
164 	if ((smap.type == SMAP_TYPE_MEMORY) && (smap.base > 0x100000) &&
165 	    (smap.base < 0x100000000ull)) {
166 	    size = smap.length;
167 
168 	    /*
169 	     * If this segment crosses the 4GB boundary, truncate it.
170 	     */
171 	    if (smap.base + size > 0x100000000ull)
172 		size = 0x100000000ull - smap.base;
173 
174 	    if (size > high_heap_size) {
175 		high_heap_size = size;
176 		high_heap_base = smap.base;
177 	    }
178 	}
179     } while (v86.ebx != 0);
180 
181     /* Fall back to the old compatibility function for base memory */
182     if (bios_basemem == 0) {
183 	v86.ctl = 0;
184 	v86.addr = 0x12;		/* int 0x12 */
185 	v86int();
186 
187 	bios_basemem = (v86.eax & 0xffff) * 1024;
188     }
189 
190     /* Fall back through several compatibility functions for extended memory */
191     if (bios_extmem == 0) {
192 	v86.ctl = V86_FLAGS;
193 	v86.addr = 0x15;		/* int 0x15 function 0xe801*/
194 	v86.eax = 0xe801;
195 	v86int();
196 	if (!(v86.efl & 1)) {
197 	    bios_extmem = ((v86.ecx & 0xffff) + ((v86.edx & 0xffff) * 64)) * 1024;
198 	}
199     }
200     if (bios_extmem == 0) {
201 	v86.ctl = 0;
202 	v86.addr = 0x15;		/* int 0x15 function 0x88*/
203 	v86.eax = 0x8800;
204 	v86int();
205 	bios_extmem = (v86.eax & 0xffff) * 1024;
206     }
207 
208     /*
209      * If we have extended memory and did not find a suitable heap
210      * region in the SMAP, use the last 3MB of 'extended' memory as a
211      * high heap candidate.
212      */
213     if (bios_extmem >= HEAP_MIN && high_heap_size < HEAP_MIN) {
214 	high_heap_size = HEAP_MIN;
215 	high_heap_base = bios_extmem + 0x100000 - HEAP_MIN;
216     }
217 }
218 
219 static int
220 gptinit(void)
221 {
222 
223 	if (gptread(&freebsd_ufs_uuid, &dsk, dmadat->secbuf) == -1) {
224 		printf("%s: unable to load GPT\n", BOOTPROG);
225 		return (-1);
226 	}
227 	if (gptfind(&freebsd_ufs_uuid, &dsk, dsk.part) == -1) {
228 		printf("%s: no UFS partition was found\n", BOOTPROG);
229 		return (-1);
230 	}
231 #ifdef LOADER_GELI_SUPPORT
232 	if (geli_taste(vdev_read, &dsk, (gpttable[curent].ent_lba_end -
233 	    gpttable[curent].ent_lba_start)) == 0) {
234 		if (geli_havekey(&dsk) != 0 && geli_passphrase(gelipw,
235 		    dsk.unit, 'p', curent + 1, &dsk) != 0) {
236 			printf("%s: unable to decrypt GELI key\n", BOOTPROG);
237 			return (-1);
238 		}
239 	}
240 #endif
241 
242 	dsk_meta = 0;
243 	return (0);
244 }
245 
246 int main(void);
247 
248 int
249 main(void)
250 {
251 	char cmd[512], cmdtmp[512];
252 	ssize_t sz;
253 	int autoboot, dskupdated;
254 	ufs_ino_t ino;
255 
256 	dmadat = (void *)(roundup2(__base + (int32_t)&_end, 0x10000) - __base);
257 
258 	bios_getmem();
259 
260 	if (high_heap_size > 0) {
261 		heap_end = PTOV(high_heap_base + high_heap_size);
262 		heap_next = PTOV(high_heap_base);
263 	} else {
264 		heap_next = (char *)dmadat + sizeof(*dmadat);
265 		heap_end = (char *)PTOV(bios_basemem);
266 	}
267 	setheap(heap_next, heap_end);
268 
269 	v86.ctl = V86_FLAGS;
270 	v86.efl = PSL_RESERVED_DEFAULT | PSL_I;
271 	dsk.drive = *(uint8_t *)PTOV(ARGS);
272 	dsk.type = dsk.drive & DRV_HARD ? TYPE_AD : TYPE_FD;
273 	dsk.unit = dsk.drive & DRV_MASK;
274 	dsk.part = -1;
275 	dsk.start = 0;
276 	bootinfo.bi_version = BOOTINFO_VERSION;
277 	bootinfo.bi_size = sizeof(bootinfo);
278 	bootinfo.bi_basemem = bios_basemem / 1024;
279 	bootinfo.bi_extmem = bios_extmem / 1024;
280 	bootinfo.bi_memsizes_valid++;
281 	bootinfo.bi_bios_dev = dsk.drive;
282 
283 #ifdef LOADER_GELI_SUPPORT
284 	geli_init();
285 #endif
286 	/* Process configuration file */
287 
288 	if (gptinit() != 0)
289 		return (-1);
290 
291 	autoboot = 1;
292 	*cmd = '\0';
293 
294 	for (;;) {
295 		*kname = '\0';
296 		if ((ino = lookup(PATH_CONFIG)) ||
297 		    (ino = lookup(PATH_DOTCONFIG))) {
298 			sz = fsread(ino, cmd, sizeof(cmd) - 1);
299 			cmd[(sz < 0) ? 0 : sz] = '\0';
300 		}
301 		if (*cmd != '\0') {
302 			memcpy(cmdtmp, cmd, sizeof(cmdtmp));
303 			if (parse_cmds(cmdtmp, &dskupdated))
304 				break;
305 			if (dskupdated && gptinit() != 0)
306 				break;
307 			if (!OPT_CHECK(RBX_QUIET))
308 				printf("%s: %s", PATH_CONFIG, cmd);
309 			*cmd = '\0';
310 		}
311 
312 		if (autoboot && keyhit(3)) {
313 			if (*kname == '\0')
314 				memcpy(kname, PATH_LOADER, sizeof(PATH_LOADER));
315 			break;
316 		}
317 		autoboot = 0;
318 
319 		/*
320 		 * Try to exec stage 3 boot loader. If interrupted by a
321 		 * keypress, or in case of failure, try to load a kernel
322 		 * directly instead.
323 		 */
324 		if (*kname != '\0')
325 			load();
326 		memcpy(kname, PATH_LOADER, sizeof(PATH_LOADER));
327 		load();
328 		memcpy(kname, PATH_KERNEL, sizeof(PATH_KERNEL));
329 		load();
330 		gptbootfailed(&dsk);
331 		if (gptfind(&freebsd_ufs_uuid, &dsk, -1) == -1)
332 			break;
333 		dsk_meta = 0;
334 	}
335 
336 	/* Present the user with the boot2 prompt. */
337 
338 	for (;;) {
339 		if (!OPT_CHECK(RBX_QUIET)) {
340 			printf("\nFreeBSD/x86 boot\n"
341 			    "Default: %u:%s(%up%u)%s\n"
342 			    "boot: ",
343 			    dsk.drive & DRV_MASK, dev_nm[dsk.type], dsk.unit,
344 			    dsk.part, kname);
345 		}
346 		if (ioctrl & IO_SERIAL)
347 			sio_flush();
348 		*cmd = '\0';
349 		if (keyhit(0))
350 			getstr(cmd, sizeof(cmd));
351 		else if (!OPT_CHECK(RBX_QUIET))
352 			putchar('\n');
353 		if (parse_cmds(cmd, &dskupdated)) {
354 			putchar('\a');
355 			continue;
356 		}
357 		if (dskupdated && gptinit() != 0)
358 			continue;
359 		load();
360 	}
361 	/* NOTREACHED */
362 }
363 
364 /* XXX - Needed for btxld to link the boot2 binary; do not remove. */
365 void
366 exit(int x)
367 {
368 }
369 
370 static void
371 load(void)
372 {
373     union {
374 	struct exec ex;
375 	Elf32_Ehdr eh;
376     } hdr;
377     static Elf32_Phdr ep[2];
378     static Elf32_Shdr es[2];
379     caddr_t p;
380     ufs_ino_t ino;
381     uint32_t addr, x;
382     int fmt, i, j;
383 
384     if (!(ino = lookup(kname))) {
385 	if (!ls) {
386 	    printf("%s: No %s on %u:%s(%up%u)\n", BOOTPROG,
387 		kname, dsk.drive & DRV_MASK, dev_nm[dsk.type], dsk.unit,
388 		dsk.part);
389 	}
390 	return;
391     }
392     if (xfsread(ino, &hdr, sizeof(hdr)))
393 	return;
394     if (N_GETMAGIC(hdr.ex) == ZMAGIC)
395 	fmt = 0;
396     else if (IS_ELF(hdr.eh))
397 	fmt = 1;
398     else {
399 	printf("Invalid %s\n", "format");
400 	return;
401     }
402     if (fmt == 0) {
403 	addr = hdr.ex.a_entry & 0xffffff;
404 	p = PTOV(addr);
405 	fs_off = PAGE_SIZE;
406 	if (xfsread(ino, p, hdr.ex.a_text))
407 	    return;
408 	p += roundup2(hdr.ex.a_text, PAGE_SIZE);
409 	if (xfsread(ino, p, hdr.ex.a_data))
410 	    return;
411 	p += hdr.ex.a_data + roundup2(hdr.ex.a_bss, PAGE_SIZE);
412 	bootinfo.bi_symtab = VTOP(p);
413 	memcpy(p, &hdr.ex.a_syms, sizeof(hdr.ex.a_syms));
414 	p += sizeof(hdr.ex.a_syms);
415 	if (hdr.ex.a_syms) {
416 	    if (xfsread(ino, p, hdr.ex.a_syms))
417 		return;
418 	    p += hdr.ex.a_syms;
419 	    if (xfsread(ino, p, sizeof(int)))
420 		return;
421 	    x = *(uint32_t *)p;
422 	    p += sizeof(int);
423 	    x -= sizeof(int);
424 	    if (xfsread(ino, p, x))
425 		return;
426 	    p += x;
427 	}
428     } else {
429 	fs_off = hdr.eh.e_phoff;
430 	for (j = i = 0; i < hdr.eh.e_phnum && j < 2; i++) {
431 	    if (xfsread(ino, ep + j, sizeof(ep[0])))
432 		return;
433 	    if (ep[j].p_type == PT_LOAD)
434 		j++;
435 	}
436 	for (i = 0; i < 2; i++) {
437 	    p = PTOV(ep[i].p_paddr & 0xffffff);
438 	    fs_off = ep[i].p_offset;
439 	    if (xfsread(ino, p, ep[i].p_filesz))
440 		return;
441 	}
442 	p += roundup2(ep[1].p_memsz, PAGE_SIZE);
443 	bootinfo.bi_symtab = VTOP(p);
444 	if (hdr.eh.e_shnum == hdr.eh.e_shstrndx + 3) {
445 	    fs_off = hdr.eh.e_shoff + sizeof(es[0]) *
446 		(hdr.eh.e_shstrndx + 1);
447 	    if (xfsread(ino, &es, sizeof(es)))
448 		return;
449 	    for (i = 0; i < 2; i++) {
450 		memcpy(p, &es[i].sh_size, sizeof(es[i].sh_size));
451 		p += sizeof(es[i].sh_size);
452 		fs_off = es[i].sh_offset;
453 		if (xfsread(ino, p, es[i].sh_size))
454 		    return;
455 		p += es[i].sh_size;
456 	    }
457 	}
458 	addr = hdr.eh.e_entry & 0xffffff;
459     }
460     bootinfo.bi_esymtab = VTOP(p);
461     bootinfo.bi_kernelname = VTOP(kname);
462     bootinfo.bi_bios_dev = dsk.drive;
463 #ifdef LOADER_GELI_SUPPORT
464     geliargs.size = sizeof(geliargs);
465     explicit_bzero(gelipw, sizeof(gelipw));
466     gelibuf = malloc(sizeof(struct keybuf) + (GELI_MAX_KEYS * sizeof(struct keybuf_ent)));
467     geli_fill_keybuf(gelibuf);
468     geliargs.notapw = '\0';
469     geliargs.keybuf_sentinel = KEYBUF_SENTINEL;
470     geliargs.keybuf = gelibuf;
471 #endif
472     __exec((caddr_t)addr, RB_BOOTINFO | (opts & RBX_MASK),
473 	   MAKEBOOTDEV(dev_maj[dsk.type], dsk.part + 1, dsk.unit, 0xff),
474 	   KARGS_FLAGS_EXTARG, 0, 0, VTOP(&bootinfo)
475 #ifdef LOADER_GELI_SUPPORT
476 	   , geliargs
477 #endif
478 	   );
479 }
480 
481 static int
482 parse_cmds(char *cmdstr, int *dskupdated)
483 {
484     char *arg = cmdstr;
485     char *ep, *p, *q;
486     const char *cp;
487     unsigned int drv;
488     int c, i, j;
489 
490     *dskupdated = 0;
491     while ((c = *arg++)) {
492 	if (c == ' ' || c == '\t' || c == '\n')
493 	    continue;
494 	for (p = arg; *p && *p != '\n' && *p != ' ' && *p != '\t'; p++);
495 	ep = p;
496 	if (*p)
497 	    *p++ = 0;
498 	if (c == '-') {
499 	    while ((c = *arg++)) {
500 		if (c == 'P') {
501 		    if (*(uint8_t *)PTOV(0x496) & 0x10) {
502 			cp = "yes";
503 		    } else {
504 			opts |= OPT_SET(RBX_DUAL) | OPT_SET(RBX_SERIAL);
505 			cp = "no";
506 		    }
507 		    printf("Keyboard: %s\n", cp);
508 		    continue;
509 		} else if (c == 'S') {
510 		    j = 0;
511 		    while ((unsigned int)(i = *arg++ - '0') <= 9)
512 			j = j * 10 + i;
513 		    if (j > 0 && i == -'0') {
514 			comspeed = j;
515 			break;
516 		    }
517 		    /* Fall through to error below ('S' not in optstr[]). */
518 		}
519 		for (i = 0; c != optstr[i]; i++)
520 		    if (i == NOPT - 1)
521 			return -1;
522 		opts ^= OPT_SET(flags[i]);
523 	    }
524 	    ioctrl = OPT_CHECK(RBX_DUAL) ? (IO_SERIAL|IO_KEYBOARD) :
525 		     OPT_CHECK(RBX_SERIAL) ? IO_SERIAL : IO_KEYBOARD;
526 	    if (ioctrl & IO_SERIAL) {
527 	        if (sio_init(115200 / comspeed) != 0)
528 		    ioctrl &= ~IO_SERIAL;
529 	    }
530 	} else {
531 	    for (q = arg--; *q && *q != '('; q++);
532 	    if (*q) {
533 		drv = -1;
534 		if (arg[1] == ':') {
535 		    drv = *arg - '0';
536 		    if (drv > 9)
537 			return (-1);
538 		    arg += 2;
539 		}
540 		if (q - arg != 2)
541 		    return -1;
542 		for (i = 0; arg[0] != dev_nm[i][0] ||
543 			    arg[1] != dev_nm[i][1]; i++)
544 		    if (i == NDEV - 1)
545 			return -1;
546 		dsk.type = i;
547 		arg += 3;
548 		dsk.unit = *arg - '0';
549 		if (arg[1] != 'p' || dsk.unit > 9)
550 		    return -1;
551 		arg += 2;
552 		dsk.part = *arg - '0';
553 		if (dsk.part < 1 || dsk.part > 9)
554 		    return -1;
555 		arg++;
556 		if (arg[0] != ')')
557 		    return -1;
558 		arg++;
559 		if (drv == -1)
560 		    drv = dsk.unit;
561 		dsk.drive = (dsk.type <= TYPE_MAXHARD
562 			     ? DRV_HARD : 0) + drv;
563 		*dskupdated = 1;
564 	    }
565 	    if ((i = ep - arg)) {
566 		if ((size_t)i >= sizeof(kname))
567 		    return -1;
568 		memcpy(kname, arg, i + 1);
569 	    }
570 	}
571 	arg = p;
572     }
573     return 0;
574 }
575 
576 static int
577 dskread(void *buf, daddr_t lba, unsigned nblk)
578 {
579 	int err;
580 
581 	err = drvread(&dsk, buf, lba + dsk.start, nblk);
582 
583 #ifdef LOADER_GELI_SUPPORT
584 	if (err == 0 && is_geli(&dsk) == 0) {
585 		/* Decrypt */
586 		if (geli_read(&dsk, lba * DEV_BSIZE, buf, nblk * DEV_BSIZE))
587 			return (err);
588 	}
589 #endif
590 
591 	return (err);
592 }
593 
594 #ifdef LOADER_GELI_SUPPORT
595 /*
596  * Read function compartible with the ZFS callback, required to keep the GELI
597  * Implementation the same for both UFS and ZFS
598  */
599 static int
600 vdev_read(void *vdev __unused, void *priv, off_t off, void *buf, size_t bytes)
601 {
602 	char *p;
603 	daddr_t lba;
604 	unsigned int nb;
605 	struct dsk *dskp = (struct dsk *) priv;
606 
607 	if ((off & (DEV_BSIZE - 1)) || (bytes & (DEV_BSIZE - 1)))
608 		return (-1);
609 
610 	p = buf;
611 	lba = off / DEV_BSIZE;
612 	lba += dskp->start;
613 
614 	while (bytes > 0) {
615 		nb = bytes / DEV_BSIZE;
616 		if (nb > VBLKSIZE / DEV_BSIZE)
617 			nb = VBLKSIZE / DEV_BSIZE;
618 		if (drvread(dskp, dmadat->blkbuf, lba, nb))
619 			return (-1);
620 		memcpy(p, dmadat->blkbuf, nb * DEV_BSIZE);
621 		p += nb * DEV_BSIZE;
622 		lba += nb;
623 		bytes -= nb * DEV_BSIZE;
624 	}
625 
626 	return (0);
627 }
628 #endif /* LOADER_GELI_SUPPORT */
629