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