gptboot.c revision 176644
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: head/sys/boot/i386/gptboot/gptboot.c 176644 2008-02-28 17:08:05Z jhb $");
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
27#include <stdarg.h>
28
29#include <a.out.h>
30
31#include <btxv86.h>
32
33#include "lib.h"
34
35#define IO_KEYBOARD	1
36#define IO_SERIAL	2
37
38#define SECOND		18	/* Circa that many ticks in a second. */
39
40#define RBX_ASKNAME	0x0	/* -a */
41#define RBX_SINGLE	0x1	/* -s */
42/* 0x2 is reserved for log2(RB_NOSYNC). */
43/* 0x3 is reserved for log2(RB_HALT). */
44/* 0x4 is reserved for log2(RB_INITNAME). */
45#define RBX_DFLTROOT	0x5	/* -r */
46#define RBX_KDB 	0x6	/* -d */
47/* 0x7 is reserved for log2(RB_RDONLY). */
48/* 0x8 is reserved for log2(RB_DUMP). */
49/* 0x9 is reserved for log2(RB_MINIROOT). */
50#define RBX_CONFIG	0xa	/* -c */
51#define RBX_VERBOSE	0xb	/* -v */
52#define RBX_SERIAL	0xc	/* -h */
53#define RBX_CDROM	0xd	/* -C */
54/* 0xe is reserved for log2(RB_POWEROFF). */
55#define RBX_GDB 	0xf	/* -g */
56#define RBX_MUTE	0x10	/* -m */
57/* 0x11 is reserved for log2(RB_SELFTEST). */
58/* 0x12 is reserved for boot programs. */
59/* 0x13 is reserved for boot programs. */
60#define RBX_PAUSE	0x14	/* -p */
61#define RBX_QUIET	0x15	/* -q */
62#define RBX_NOINTR	0x1c	/* -n */
63/* 0x1d is reserved for log2(RB_MULTIPLE) and is just misnamed here. */
64#define RBX_DUAL	0x1d	/* -D */
65/* 0x1f is reserved for log2(RB_BOOTINFO). */
66
67/* pass: -a, -s, -r, -d, -c, -v, -h, -C, -g, -m, -p, -D */
68#define RBX_MASK	(OPT_SET(RBX_ASKNAME) | OPT_SET(RBX_SINGLE) | \
69			OPT_SET(RBX_DFLTROOT) | OPT_SET(RBX_KDB ) | \
70			OPT_SET(RBX_CONFIG) | OPT_SET(RBX_VERBOSE) | \
71			OPT_SET(RBX_SERIAL) | OPT_SET(RBX_CDROM) | \
72			OPT_SET(RBX_GDB ) | OPT_SET(RBX_MUTE) | \
73			OPT_SET(RBX_PAUSE) | OPT_SET(RBX_DUAL))
74
75#define PATH_CONFIG	"/boot.config"
76#define PATH_BOOT3	"/boot/loader"
77#define PATH_KERNEL	"/boot/kernel/kernel"
78
79#define ARGS		0x900
80#define NOPT		14
81#define NDEV		3
82#define MEM_BASE	0x12
83#define MEM_EXT 	0x15
84#define V86_CY(x)	((x) & 1)
85#define V86_ZR(x)	((x) & 0x40)
86
87#define DRV_HARD	0x80
88#define DRV_MASK	0x7f
89
90#define TYPE_AD		0
91#define TYPE_DA		1
92#define TYPE_MAXHARD	TYPE_DA
93#define TYPE_FD		2
94
95#define OPT_SET(opt)	(1 << (opt))
96#define OPT_CHECK(opt)	((opts) & OPT_SET(opt))
97
98extern uint32_t _end;
99
100static const uuid_t freebsd_ufs_uuid = GPT_ENT_TYPE_FREEBSD_UFS;
101static const char optstr[NOPT] = "DhaCcdgmnpqrsv"; /* Also 'P', 'S' */
102static const unsigned char flags[NOPT] = {
103    RBX_DUAL,
104    RBX_SERIAL,
105    RBX_ASKNAME,
106    RBX_CDROM,
107    RBX_CONFIG,
108    RBX_KDB,
109    RBX_GDB,
110    RBX_MUTE,
111    RBX_NOINTR,
112    RBX_PAUSE,
113    RBX_QUIET,
114    RBX_DFLTROOT,
115    RBX_SINGLE,
116    RBX_VERBOSE
117};
118
119static const char *const dev_nm[NDEV] = {"ad", "da", "fd"};
120static const unsigned char dev_maj[NDEV] = {30, 4, 2};
121
122static struct dsk {
123    unsigned drive;
124    unsigned type;
125    unsigned unit;
126    int part;
127    daddr_t start;
128    int init;
129} dsk;
130static char cmd[512], cmddup[512];
131static char kname[1024];
132static uint32_t opts;
133static int comspeed = SIOSPD;
134static struct bootinfo bootinfo;
135static uint8_t ioctrl = IO_KEYBOARD;
136
137void exit(int);
138static int bcmp(const void *, const void *, size_t);
139static void load(void);
140static int parse(void);
141static int xfsread(ino_t, void *, size_t);
142static int dskread(void *, daddr_t, unsigned);
143static void printf(const char *,...);
144static void putchar(int);
145static void memcpy(void *, const void *, int);
146static uint32_t memsize(void);
147static int drvread(void *, daddr_t, unsigned);
148static int keyhit(unsigned);
149static int xputc(int);
150static int xgetc(int);
151static int getc(int);
152
153static void
154memcpy(void *dst, const void *src, int len)
155{
156    const char *s = src;
157    char *d = dst;
158
159    while (len--)
160        *d++ = *s++;
161}
162
163static inline int
164strcmp(const char *s1, const char *s2)
165{
166    for (; *s1 == *s2 && *s1; s1++, s2++);
167    return (unsigned char)*s1 - (unsigned char)*s2;
168}
169
170#include "ufsread.c"
171
172static inline int
173xfsread(ino_t inode, void *buf, size_t nbyte)
174{
175    if ((size_t)fsread(inode, buf, nbyte) != nbyte) {
176	printf("Invalid %s\n", "format");
177	return -1;
178    }
179    return 0;
180}
181
182static inline uint32_t
183memsize(void)
184{
185    v86.addr = MEM_EXT;
186    v86.eax = 0x8800;
187    v86int();
188    return v86.eax;
189}
190
191static inline void
192getstr(void)
193{
194    char *s;
195    int c;
196
197    s = cmd;
198    for (;;) {
199	switch (c = xgetc(0)) {
200	case 0:
201	    break;
202	case '\177':
203	case '\b':
204	    if (s > cmd) {
205		s--;
206		printf("\b \b");
207	    }
208	    break;
209	case '\n':
210	case '\r':
211	    *s = 0;
212	    return;
213	default:
214	    if (s - cmd < sizeof(cmd) - 1)
215		*s++ = c;
216	    putchar(c);
217	}
218    }
219}
220
221static inline void
222putc(int c)
223{
224    v86.addr = 0x10;
225    v86.eax = 0xe00 | (c & 0xff);
226    v86.ebx = 0x7;
227    v86int();
228}
229
230int
231main(void)
232{
233    int autoboot;
234    ino_t ino;
235
236    dmadat = (void *)(roundup2(__base + (int32_t)&_end, 0x10000) - __base);
237    v86.ctl = V86_FLAGS;
238    dsk.drive = *(uint8_t *)PTOV(ARGS);
239    dsk.type = dsk.drive & DRV_HARD ? TYPE_AD : TYPE_FD;
240    dsk.unit = dsk.drive & DRV_MASK;
241    dsk.part = -1;
242    bootinfo.bi_version = BOOTINFO_VERSION;
243    bootinfo.bi_size = sizeof(bootinfo);
244    bootinfo.bi_basemem = 0;	/* XXX will be filled by loader or kernel */
245    bootinfo.bi_extmem = memsize();
246    bootinfo.bi_memsizes_valid++;
247
248    /* Process configuration file */
249
250    autoboot = 1;
251
252    if ((ino = lookup(PATH_CONFIG)))
253	fsread(ino, cmd, sizeof(cmd));
254
255    if (*cmd) {
256	memcpy(cmddup, cmd, sizeof(cmd));
257	if (parse())
258	    autoboot = 0;
259	if (!OPT_CHECK(RBX_QUIET))
260	    printf("%s: %s", PATH_CONFIG, cmddup);
261	/* Do not process this command twice */
262	*cmd = 0;
263    }
264
265    /*
266     * Try to exec stage 3 boot loader. If interrupted by a keypress,
267     * or in case of failure, try to load a kernel directly instead.
268     */
269
270    if (autoboot && !*kname) {
271	memcpy(kname, PATH_BOOT3, sizeof(PATH_BOOT3));
272	if (!keyhit(3*SECOND)) {
273	    load();
274	    memcpy(kname, PATH_KERNEL, sizeof(PATH_KERNEL));
275	}
276    }
277
278    /* Present the user with the boot2 prompt. */
279
280    for (;;) {
281	if (!autoboot || !OPT_CHECK(RBX_QUIET))
282	    printf("\nFreeBSD/i386 boot\n"
283		   "Default: %u:%s(%up%u)%s\n"
284		   "boot: ",
285		   dsk.drive & DRV_MASK, dev_nm[dsk.type], dsk.unit,
286		   dsk.part, kname);
287	if (ioctrl & IO_SERIAL)
288	    sio_flush();
289	if (!autoboot || keyhit(5*SECOND))
290	    getstr();
291	else if (!autoboot || !OPT_CHECK(RBX_QUIET))
292	    putchar('\n');
293	autoboot = 0;
294	if (parse())
295	    putchar('\a');
296	else
297	    load();
298    }
299}
300
301/* XXX - Needed for btxld to link the boot2 binary; do not remove. */
302void
303exit(int x)
304{
305}
306
307static void
308load(void)
309{
310    union {
311	struct exec ex;
312	Elf32_Ehdr eh;
313    } hdr;
314    static Elf32_Phdr ep[2];
315    static Elf32_Shdr es[2];
316    caddr_t p;
317    ino_t ino;
318    uint32_t addr, x;
319    int fmt, i, j;
320
321    if (!(ino = lookup(kname))) {
322	if (!ls)
323	    printf("No %s\n", kname);
324	return;
325    }
326    if (xfsread(ino, &hdr, sizeof(hdr)))
327	return;
328    if (N_GETMAGIC(hdr.ex) == ZMAGIC)
329	fmt = 0;
330    else if (IS_ELF(hdr.eh))
331	fmt = 1;
332    else {
333	printf("Invalid %s\n", "format");
334	return;
335    }
336    if (fmt == 0) {
337	addr = hdr.ex.a_entry & 0xffffff;
338	p = PTOV(addr);
339	fs_off = PAGE_SIZE;
340	if (xfsread(ino, p, hdr.ex.a_text))
341	    return;
342	p += roundup2(hdr.ex.a_text, PAGE_SIZE);
343	if (xfsread(ino, p, hdr.ex.a_data))
344	    return;
345	p += hdr.ex.a_data + roundup2(hdr.ex.a_bss, PAGE_SIZE);
346	bootinfo.bi_symtab = VTOP(p);
347	memcpy(p, &hdr.ex.a_syms, sizeof(hdr.ex.a_syms));
348	p += sizeof(hdr.ex.a_syms);
349	if (hdr.ex.a_syms) {
350	    if (xfsread(ino, p, hdr.ex.a_syms))
351		return;
352	    p += hdr.ex.a_syms;
353	    if (xfsread(ino, p, sizeof(int)))
354		return;
355	    x = *(uint32_t *)p;
356	    p += sizeof(int);
357	    x -= sizeof(int);
358	    if (xfsread(ino, p, x))
359		return;
360	    p += x;
361	}
362    } else {
363	fs_off = hdr.eh.e_phoff;
364	for (j = i = 0; i < hdr.eh.e_phnum && j < 2; i++) {
365	    if (xfsread(ino, ep + j, sizeof(ep[0])))
366		return;
367	    if (ep[j].p_type == PT_LOAD)
368		j++;
369	}
370	for (i = 0; i < 2; i++) {
371	    p = PTOV(ep[i].p_paddr & 0xffffff);
372	    fs_off = ep[i].p_offset;
373	    if (xfsread(ino, p, ep[i].p_filesz))
374		return;
375	}
376	p += roundup2(ep[1].p_memsz, PAGE_SIZE);
377	bootinfo.bi_symtab = VTOP(p);
378	if (hdr.eh.e_shnum == hdr.eh.e_shstrndx + 3) {
379	    fs_off = hdr.eh.e_shoff + sizeof(es[0]) *
380		(hdr.eh.e_shstrndx + 1);
381	    if (xfsread(ino, &es, sizeof(es)))
382		return;
383	    for (i = 0; i < 2; i++) {
384		memcpy(p, &es[i].sh_size, sizeof(es[i].sh_size));
385		p += sizeof(es[i].sh_size);
386		fs_off = es[i].sh_offset;
387		if (xfsread(ino, p, es[i].sh_size))
388		    return;
389		p += es[i].sh_size;
390	    }
391	}
392	addr = hdr.eh.e_entry & 0xffffff;
393    }
394    bootinfo.bi_esymtab = VTOP(p);
395    bootinfo.bi_kernelname = VTOP(kname);
396    bootinfo.bi_bios_dev = dsk.drive;
397    __exec((caddr_t)addr, RB_BOOTINFO | (opts & RBX_MASK),
398	   MAKEBOOTDEV(dev_maj[dsk.type], dsk.part + 1, dsk.unit, 0xff),
399	   0, 0, 0, VTOP(&bootinfo));
400}
401
402static int
403parse(void)
404{
405    char *arg = cmd;
406    char *ep, *p, *q;
407    const char *cp;
408    unsigned int drv;
409    int c, i, j;
410
411    while ((c = *arg++)) {
412	if (c == ' ' || c == '\t' || c == '\n')
413	    continue;
414	for (p = arg; *p && *p != '\n' && *p != ' ' && *p != '\t'; p++);
415	ep = p;
416	if (*p)
417	    *p++ = 0;
418	if (c == '-') {
419	    while ((c = *arg++)) {
420		if (c == 'P') {
421		    if (*(uint8_t *)PTOV(0x496) & 0x10) {
422			cp = "yes";
423		    } else {
424			opts |= OPT_SET(RBX_DUAL) | OPT_SET(RBX_SERIAL);
425			cp = "no";
426		    }
427		    printf("Keyboard: %s\n", cp);
428		    continue;
429		} else if (c == 'S') {
430		    j = 0;
431		    while ((unsigned int)(i = *arg++ - '0') <= 9)
432			j = j * 10 + i;
433		    if (j > 0 && i == -'0') {
434			comspeed = j;
435			break;
436		    }
437		    /* Fall through to error below ('S' not in optstr[]). */
438		}
439		for (i = 0; c != optstr[i]; i++)
440		    if (i == NOPT - 1)
441			return -1;
442		opts ^= OPT_SET(flags[i]);
443	    }
444	    ioctrl = OPT_CHECK(RBX_DUAL) ? (IO_SERIAL|IO_KEYBOARD) :
445		     OPT_CHECK(RBX_SERIAL) ? IO_SERIAL : IO_KEYBOARD;
446	    if (ioctrl & IO_SERIAL)
447	        sio_init(115200 / comspeed);
448	} else {
449	    for (q = arg--; *q && *q != '('; q++);
450	    if (*q) {
451		drv = -1;
452		if (arg[1] == ':') {
453		    drv = *arg - '0';
454		    if (drv > 9)
455			return (-1);
456		    arg += 2;
457		}
458		if (q - arg != 2)
459		    return -1;
460		for (i = 0; arg[0] != dev_nm[i][0] ||
461			    arg[1] != dev_nm[i][1]; i++)
462		    if (i == NDEV - 1)
463			return -1;
464		dsk.type = i;
465		arg += 3;
466		dsk.unit = *arg - '0';
467		if (arg[1] != ',' || dsk.unit > 9)
468		    return -1;
469		arg += 2;
470		dsk.part = -1;
471		if (arg[1] == ',') {
472		    dsk.part = *arg - '0';
473		    if (dsk.part < 1 || dsk.part > 9)
474			return -1;
475		    arg += 2;
476		}
477		if (arg[0] != ')')
478		    return -1;
479		arg++;
480		if (drv == -1)
481		    drv = dsk.unit;
482		dsk.drive = (dsk.type <= TYPE_MAXHARD
483			     ? DRV_HARD : 0) + drv;
484		dsk_meta = 0;
485	    }
486	    if ((i = ep - arg)) {
487		if ((size_t)i >= sizeof(kname))
488		    return -1;
489		memcpy(kname, arg, i + 1);
490	    }
491	}
492	arg = p;
493    }
494    return 0;
495}
496
497static int
498dskread(void *buf, daddr_t lba, unsigned nblk)
499{
500    struct gpt_hdr hdr;
501    struct gpt_ent *ent;
502    char *sec;
503    daddr_t slba, elba;
504    int part, entries_per_sec;
505
506    if (!dsk_meta) {
507	/* Read and verify GPT. */
508	sec = dmadat->secbuf;
509	dsk.start = 0;
510	if (drvread(sec, 1, 1))
511	    return -1;
512	memcpy(&hdr, sec, sizeof(hdr));
513	if (bcmp(hdr.hdr_sig, GPT_HDR_SIG, sizeof(hdr.hdr_sig)) != 0 ||
514	    hdr.hdr_lba_self != 1 || hdr.hdr_revision < 0x00010000 ||
515	    hdr.hdr_entsz < sizeof(*ent) || DEV_BSIZE % hdr.hdr_entsz != 0) {
516	    printf("Invalid GPT header\n");
517	    return -1;
518	}
519
520	/* XXX: CRC check? */
521
522	/*
523	 * If the partition isn't specified, then search for the first UFS
524	 * partition and hope it is /.  Perhaps we should be using an OS
525	 * flag in the GPT entry to mark / partitions.
526	 *
527	 * If the partition is specified, then figure out the LBA for the
528	 * sector containing that partition index and load it.
529	 */
530	entries_per_sec = DEV_BSIZE / hdr.hdr_entsz;
531	if (dsk.part == -1) {
532	    slba = hdr.hdr_lba_table;
533	    elba = slba + hdr.hdr_entries / entries_per_sec;
534	    while (slba < elba && dsk.part == -1) {
535		if (drvread(sec, slba, 1))
536		    return -1;
537		for (part = 0; part < entries_per_sec; part++) {
538		    ent = (struct gpt_ent *)(sec + part * hdr.hdr_entsz);
539		    if (bcmp(&ent->ent_type, &freebsd_ufs_uuid,
540			sizeof(uuid_t)) == 0) {
541			dsk.part = (slba - hdr.hdr_lba_table) *
542			    entries_per_sec + part + 1;
543			dsk.start = ent->ent_lba_start;
544			break;
545		    }
546		}
547		slba++;
548	    }
549	    if (dsk.part == -1) {
550		printf("No UFS partition was found\n");
551		return -1;
552	    }
553	} else {
554	    if (dsk.part > hdr.hdr_entries) {
555		printf("Invalid partition index\n");
556		return -1;
557	    }
558	    slba = hdr.hdr_lba_table + (dsk.part - 1) / entries_per_sec;
559	    if (drvread(sec, slba, 1))
560		return -1;
561	    part = (dsk.part - 1) % entries_per_sec;
562	    ent = (struct gpt_ent *)(sec + part * hdr.hdr_entsz);
563	    if (bcmp(&ent->ent_type, &freebsd_ufs_uuid, sizeof(uuid_t)) != 0) {
564		printf("Specified partition is not UFS\n");
565		return -1;
566	    }
567	    dsk.start = ent->ent_lba_start;
568	}
569	/*
570	 * XXX: No way to detect SCSI vs. ATA currently.
571	 */
572#if 0
573	if (!dsk.init) {
574	    if (d->d_type == DTYPE_SCSI)
575		dsk.type = TYPE_DA;
576	    dsk.init++;
577	}
578#endif
579    }
580    return drvread(buf, dsk.start + lba, nblk);
581}
582
583static void
584printf(const char *fmt,...)
585{
586    va_list ap;
587    char buf[10];
588    char *s;
589    unsigned u;
590    int c;
591
592    va_start(ap, fmt);
593    while ((c = *fmt++)) {
594	if (c == '%') {
595	    c = *fmt++;
596	    switch (c) {
597	    case 'c':
598		putchar(va_arg(ap, int));
599		continue;
600	    case 's':
601		for (s = va_arg(ap, char *); *s; s++)
602		    putchar(*s);
603		continue;
604	    case 'u':
605		u = va_arg(ap, unsigned);
606		s = buf;
607		do
608		    *s++ = '0' + u % 10U;
609		while (u /= 10U);
610		while (--s >= buf)
611		    putchar(*s);
612		continue;
613	    }
614	}
615	putchar(c);
616    }
617    va_end(ap);
618    return;
619}
620
621static void
622putchar(int c)
623{
624    if (c == '\n')
625	xputc('\r');
626    xputc(c);
627}
628
629static int
630bcmp(const void *b1, const void *b2, size_t length)
631{
632    const char *p1 = b1, *p2 = b2;
633
634    if (length == 0)
635	return (0);
636    do {
637	if (*p1++ != *p2++)
638	    break;
639    } while (--length);
640    return (length);
641}
642
643static struct {
644	uint16_t len;
645	uint16_t count;
646	uint16_t seg;
647	uint16_t off;
648	uint64_t lba;
649} packet;
650
651static int
652drvread(void *buf, daddr_t lba, unsigned nblk)
653{
654    static unsigned c = 0x2d5c7c2f;
655
656    if (!OPT_CHECK(RBX_QUIET))
657	printf("%c\b", c = c << 8 | c >> 24);
658    packet.len = 0x10;
659    packet.count = nblk;
660    packet.seg = VTOPOFF(buf);
661    packet.off = VTOPSEG(buf);
662    packet.lba = lba;
663    v86.ctl = V86_FLAGS;
664    v86.addr = 0x13;
665    v86.eax = 0x4200;
666    v86.edx = dsk.drive;
667    v86.ds = VTOPSEG(&packet);
668    v86.esi = VTOPOFF(&packet);
669    v86int();
670    if (V86_CY(v86.efl)) {
671	printf("error %u lba %u\n", v86.eax >> 8 & 0xff, lba);
672	return -1;
673    }
674    return 0;
675}
676
677static int
678keyhit(unsigned ticks)
679{
680    uint32_t t0, t1;
681
682    if (OPT_CHECK(RBX_NOINTR))
683	return 0;
684    t0 = 0;
685    for (;;) {
686	if (xgetc(1))
687	    return 1;
688	t1 = *(uint32_t *)PTOV(0x46c);
689	if (!t0)
690	    t0 = t1;
691	if (t1 < t0 || t1 >= t0 + ticks)
692	    return 0;
693    }
694}
695
696static int
697xputc(int c)
698{
699    if (ioctrl & IO_KEYBOARD)
700	putc(c);
701    if (ioctrl & IO_SERIAL)
702	sio_putc(c);
703    return c;
704}
705
706static int
707xgetc(int fn)
708{
709    if (OPT_CHECK(RBX_NOINTR))
710	return 0;
711    for (;;) {
712	if (ioctrl & IO_KEYBOARD && getc(1))
713	    return fn ? 1 : getc(0);
714	if (ioctrl & IO_SERIAL && sio_ischar())
715	    return fn ? 1 : sio_getc();
716	if (fn)
717	    return 0;
718    }
719}
720
721static int
722getc(int fn)
723{
724    v86.addr = 0x16;
725    v86.eax = fn << 8;
726    v86int();
727    return fn == 0 ? v86.eax & 0xff : !V86_ZR(v86.efl);
728}
729