]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/boot/i386/zfsboot/zfsboot.c
MFC r308089: zfsbootcfg: a simple tool to set next boot (one time)
[FreeBSD/FreeBSD.git] / sys / boot / i386 / zfsboot / zfsboot.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/errno.h>
21 #include <sys/diskmbr.h>
22 #ifdef GPT
23 #include <sys/gpt.h>
24 #endif
25 #include <sys/reboot.h>
26 #include <sys/queue.h>
27
28 #include <machine/bootinfo.h>
29 #include <machine/elf.h>
30 #include <machine/pc/bios.h>
31
32 #include <stdarg.h>
33 #include <stddef.h>
34
35 #include <a.out.h>
36
37 #include <btxv86.h>
38
39 #include "lib.h"
40 #include "rbx.h"
41 #include "drv.h"
42 #include "util.h"
43 #include "cons.h"
44 #include "bootargs.h"
45 #include "paths.h"
46
47 #include "libzfs.h"
48
49 #define ARGS                    0x900
50 #define NOPT                    14
51 #define NDEV                    3
52
53 #define BIOS_NUMDRIVES          0x475
54 #define DRV_HARD                0x80
55 #define DRV_MASK                0x7f
56
57 #define TYPE_AD                 0
58 #define TYPE_DA                 1
59 #define TYPE_MAXHARD            TYPE_DA
60 #define TYPE_FD                 2
61
62 #define DEV_GELIBOOT_BSIZE      4096
63
64 extern uint32_t _end;
65
66 #ifdef GPT
67 static const uuid_t freebsd_zfs_uuid = GPT_ENT_TYPE_FREEBSD_ZFS;
68 #endif
69 static const char optstr[NOPT] = "DhaCcdgmnpqrsv"; /* Also 'P', 'S' */
70 static const unsigned char flags[NOPT] = {
71     RBX_DUAL,
72     RBX_SERIAL,
73     RBX_ASKNAME,
74     RBX_CDROM,
75     RBX_CONFIG,
76     RBX_KDB,
77     RBX_GDB,
78     RBX_MUTE,
79     RBX_NOINTR,
80     RBX_PAUSE,
81     RBX_QUIET,
82     RBX_DFLTROOT,
83     RBX_SINGLE,
84     RBX_VERBOSE
85 };
86 uint32_t opts;
87
88 static const unsigned char dev_maj[NDEV] = {30, 4, 2};
89
90 static char cmd[512];
91 static char cmddup[512];
92 static char kname[1024];
93 static char rootname[256];
94 static int comspeed = SIOSPD;
95 static struct bootinfo bootinfo;
96 static uint32_t bootdev;
97 static struct zfs_boot_args zfsargs;
98 static struct zfsmount zfsmount;
99
100 vm_offset_t     high_heap_base;
101 uint32_t        bios_basemem, bios_extmem, high_heap_size;
102
103 static struct bios_smap smap;
104
105 /*
106  * The minimum amount of memory to reserve in bios_extmem for the heap.
107  */
108 #define HEAP_MIN                (3 * 1024 * 1024)
109
110 static char *heap_next;
111 static char *heap_end;
112
113 /* Buffers that must not span a 64k boundary. */
114 #define READ_BUF_SIZE           8192
115 struct dmadat {
116         char rdbuf[READ_BUF_SIZE];      /* for reading large things */
117         char secbuf[READ_BUF_SIZE];     /* for MBR/disklabel */
118 };
119 static struct dmadat *dmadat;
120
121 void exit(int);
122 void reboot(void);
123 static void load(void);
124 static int parse(void);
125 static void bios_getmem(void);
126 void *malloc(size_t n);
127 void free(void *ptr);
128
129 void *
130 malloc(size_t n)
131 {
132         char *p = heap_next;
133         if (p + n > heap_end) {
134                 printf("malloc failure\n");
135                 for (;;)
136                     ;
137                 /* NOTREACHED */
138                 return (0);
139         }
140         heap_next += n;
141         return (p);
142 }
143
144 void
145 free(void *ptr)
146 {
147
148         return;
149 }
150
151 static char *
152 strdup(const char *s)
153 {
154         char *p = malloc(strlen(s) + 1);
155         strcpy(p, s);
156         return (p);
157 }
158
159 #ifdef LOADER_GELI_SUPPORT
160 #include "geliboot.c"
161 static char gelipw[GELI_PW_MAXLEN];
162 #endif
163
164 #include "zfsimpl.c"
165
166 /*
167  * Read from a dnode (which must be from a ZPL filesystem).
168  */
169 static int
170 zfs_read(spa_t *spa, const dnode_phys_t *dnode, off_t *offp, void *start, size_t size)
171 {
172         const znode_phys_t *zp = (const znode_phys_t *) dnode->dn_bonus;
173         size_t n;
174         int rc;
175
176         n = size;
177         if (*offp + n > zp->zp_size)
178                 n = zp->zp_size - *offp;
179
180         rc = dnode_read(spa, dnode, *offp, start, n);
181         if (rc)
182                 return (-1);
183         *offp += n;
184
185         return (n);
186 }
187
188 /*
189  * Current ZFS pool
190  */
191 static spa_t *spa;
192 static spa_t *primary_spa;
193 static vdev_t *primary_vdev;
194
195 /*
196  * A wrapper for dskread that doesn't have to worry about whether the
197  * buffer pointer crosses a 64k boundary.
198  */
199 static int
200 vdev_read(vdev_t *vdev, void *priv, off_t off, void *buf, size_t bytes)
201 {
202         char *p;
203         daddr_t lba, alignlba;
204         off_t diff;
205         unsigned int nb, alignnb;
206         struct dsk *dsk = (struct dsk *) priv;
207
208         if ((off & (DEV_BSIZE - 1)) || (bytes & (DEV_BSIZE - 1)))
209                 return -1;
210
211         p = buf;
212         lba = off / DEV_BSIZE;
213         lba += dsk->start;
214         /*
215          * Align reads to 4k else 4k sector GELIs will not decrypt.
216          * Round LBA down to nearest multiple of DEV_GELIBOOT_BSIZE bytes.
217          */
218         alignlba = rounddown2(off, DEV_GELIBOOT_BSIZE) / DEV_BSIZE;
219         /*
220          * The read must be aligned to DEV_GELIBOOT_BSIZE bytes relative to the
221          * start of the GELI partition, not the start of the actual disk.
222          */
223         alignlba += dsk->start;
224         diff = (lba - alignlba) * DEV_BSIZE;
225
226         while (bytes > 0) {
227                 nb = bytes / DEV_BSIZE;
228                 /*
229                  * Ensure that the read size plus the leading offset does not
230                  * exceed the size of the read buffer.
231                  */
232                 if (nb > (READ_BUF_SIZE - diff) / DEV_BSIZE)
233                         nb = (READ_BUF_SIZE - diff) / DEV_BSIZE;
234                 /*
235                  * Round the number of blocks to read up to the nearest multiple
236                  * of DEV_GELIBOOT_BSIZE.
237                  */
238                 alignnb = roundup2(nb * DEV_BSIZE + diff, DEV_GELIBOOT_BSIZE)
239                     / DEV_BSIZE;
240
241                 if (drvread(dsk, dmadat->rdbuf, alignlba, alignnb))
242                         return -1;
243 #ifdef LOADER_GELI_SUPPORT
244                 /* decrypt */
245                 if (is_geli(dsk) == 0) {
246                         if (geli_read(dsk, ((alignlba - dsk->start) *
247                             DEV_BSIZE), dmadat->rdbuf, alignnb * DEV_BSIZE))
248                                 return (-1);
249                 }
250 #endif
251                 memcpy(p, dmadat->rdbuf + diff, nb * DEV_BSIZE);
252                 p += nb * DEV_BSIZE;
253                 lba += nb;
254                 alignlba += alignnb;
255                 bytes -= nb * DEV_BSIZE;
256                 /* Don't need the leading offset after the first block. */
257                 diff = 0;
258         }
259
260         return 0;
261 }
262
263 static int
264 vdev_write(vdev_t *vdev, void *priv, off_t off, void *buf, size_t bytes)
265 {
266         char *p;
267         daddr_t lba;
268         unsigned int nb;
269         struct dsk *dsk = (struct dsk *) priv;
270
271         if ((off & (DEV_BSIZE - 1)) || (bytes & (DEV_BSIZE - 1)))
272                 return -1;
273
274         p = buf;
275         lba = off / DEV_BSIZE;
276         lba += dsk->start;
277         while (bytes > 0) {
278                 nb = bytes / DEV_BSIZE;
279                 if (nb > READ_BUF_SIZE / DEV_BSIZE)
280                         nb = READ_BUF_SIZE / DEV_BSIZE;
281                 memcpy(dmadat->rdbuf, p, nb * DEV_BSIZE);
282                 if (drvwrite(dsk, dmadat->rdbuf, lba, nb))
283                         return -1;
284                 p += nb * DEV_BSIZE;
285                 lba += nb;
286                 bytes -= nb * DEV_BSIZE;
287         }
288
289         return 0;
290 }
291
292 static int
293 xfsread(const dnode_phys_t *dnode, off_t *offp, void *buf, size_t nbyte)
294 {
295     if ((size_t)zfs_read(spa, dnode, offp, buf, nbyte) != nbyte) {
296         printf("Invalid format\n");
297         return -1;
298     }
299     return 0;
300 }
301
302 /*
303  * Read Pad2 (formerly "Boot Block Header") area of the first
304  * vdev label of the given vdev.
305  */
306 static int
307 vdev_read_pad2(vdev_t *vdev, char *buf, size_t size)
308 {
309         blkptr_t bp;
310         char *tmp = zap_scratch;
311         off_t off = offsetof(vdev_label_t, vl_pad2);
312
313         if (size > VDEV_PAD_SIZE)
314                 size = VDEV_PAD_SIZE;
315
316         BP_ZERO(&bp);
317         BP_SET_LSIZE(&bp, VDEV_PAD_SIZE);
318         BP_SET_PSIZE(&bp, VDEV_PAD_SIZE);
319         BP_SET_CHECKSUM(&bp, ZIO_CHECKSUM_LABEL);
320         BP_SET_COMPRESS(&bp, ZIO_COMPRESS_OFF);
321         DVA_SET_OFFSET(BP_IDENTITY(&bp), off);
322         if (vdev_read_phys(vdev, &bp, tmp, off, 0))
323                 return (EIO);
324         memcpy(buf, tmp, size);
325         return (0);
326 }
327
328 static int
329 vdev_clear_pad2(vdev_t *vdev)
330 {
331         char *zeroes = zap_scratch;
332         uint64_t *end;
333         off_t off = offsetof(vdev_label_t, vl_pad2);
334
335         memset(zeroes, 0, VDEV_PAD_SIZE);
336         end = (uint64_t *)(zeroes + VDEV_PAD_SIZE);
337         /* ZIO_CHECKSUM_LABEL magic and pre-calcualted checksum for all zeros */
338         end[-5] = 0x0210da7ab10c7a11;
339         end[-4] = 0x97f48f807f6e2a3f;
340         end[-3] = 0xaf909f1658aacefc;
341         end[-2] = 0xcbd1ea57ff6db48b;
342         end[-1] = 0x6ec692db0d465fab;
343         if (vdev_write(vdev, vdev->v_read_priv, off, zeroes, VDEV_PAD_SIZE))
344                 return (EIO);
345         return (0);
346 }
347
348 static void
349 bios_getmem(void)
350 {
351     uint64_t size;
352
353     /* Parse system memory map */
354     v86.ebx = 0;
355     do {
356         v86.ctl = V86_FLAGS;
357         v86.addr = 0x15;                /* int 0x15 function 0xe820*/
358         v86.eax = 0xe820;
359         v86.ecx = sizeof(struct bios_smap);
360         v86.edx = SMAP_SIG;
361         v86.es = VTOPSEG(&smap);
362         v86.edi = VTOPOFF(&smap);
363         v86int();
364         if (V86_CY(v86.efl) || (v86.eax != SMAP_SIG))
365             break;
366         /* look for a low-memory segment that's large enough */
367         if ((smap.type == SMAP_TYPE_MEMORY) && (smap.base == 0) &&
368             (smap.length >= (512 * 1024)))
369             bios_basemem = smap.length;
370         /* look for the first segment in 'extended' memory */
371         if ((smap.type == SMAP_TYPE_MEMORY) && (smap.base == 0x100000)) {
372             bios_extmem = smap.length;
373         }
374
375         /*
376          * Look for the largest segment in 'extended' memory beyond
377          * 1MB but below 4GB.
378          */
379         if ((smap.type == SMAP_TYPE_MEMORY) && (smap.base > 0x100000) &&
380             (smap.base < 0x100000000ull)) {
381             size = smap.length;
382
383             /*
384              * If this segment crosses the 4GB boundary, truncate it.
385              */
386             if (smap.base + size > 0x100000000ull)
387                 size = 0x100000000ull - smap.base;
388
389             if (size > high_heap_size) {
390                 high_heap_size = size;
391                 high_heap_base = smap.base;
392             }
393         }
394     } while (v86.ebx != 0);
395
396     /* Fall back to the old compatibility function for base memory */
397     if (bios_basemem == 0) {
398         v86.ctl = 0;
399         v86.addr = 0x12;                /* int 0x12 */
400         v86int();
401         
402         bios_basemem = (v86.eax & 0xffff) * 1024;
403     }
404
405     /* Fall back through several compatibility functions for extended memory */
406     if (bios_extmem == 0) {
407         v86.ctl = V86_FLAGS;
408         v86.addr = 0x15;                /* int 0x15 function 0xe801*/
409         v86.eax = 0xe801;
410         v86int();
411         if (!V86_CY(v86.efl)) {
412             bios_extmem = ((v86.ecx & 0xffff) + ((v86.edx & 0xffff) * 64)) * 1024;
413         }
414     }
415     if (bios_extmem == 0) {
416         v86.ctl = 0;
417         v86.addr = 0x15;                /* int 0x15 function 0x88*/
418         v86.eax = 0x8800;
419         v86int();
420         bios_extmem = (v86.eax & 0xffff) * 1024;
421     }
422
423     /*
424      * If we have extended memory and did not find a suitable heap
425      * region in the SMAP, use the last 3MB of 'extended' memory as a
426      * high heap candidate.
427      */
428     if (bios_extmem >= HEAP_MIN && high_heap_size < HEAP_MIN) {
429         high_heap_size = HEAP_MIN;
430         high_heap_base = bios_extmem + 0x100000 - HEAP_MIN;
431     }
432 }
433
434 /*
435  * Try to detect a device supported by the legacy int13 BIOS
436  */
437 static int
438 int13probe(int drive)
439 {
440     v86.ctl = V86_FLAGS;
441     v86.addr = 0x13;
442     v86.eax = 0x800;
443     v86.edx = drive;
444     v86int();
445     
446     if (!V86_CY(v86.efl) &&                             /* carry clear */
447         ((v86.edx & 0xff) != (drive & DRV_MASK))) {     /* unit # OK */
448         if ((v86.ecx & 0x3f) == 0) {                    /* absurd sector size */
449                 return(0);                              /* skip device */
450         }
451         return (1);
452     }
453     return(0);
454 }
455
456 /*
457  * We call this when we find a ZFS vdev - ZFS consumes the dsk
458  * structure so we must make a new one.
459  */
460 static struct dsk *
461 copy_dsk(struct dsk *dsk)
462 {
463     struct dsk *newdsk;
464
465     newdsk = malloc(sizeof(struct dsk));
466     *newdsk = *dsk;
467     return (newdsk);
468 }
469
470 static void
471 probe_drive(struct dsk *dsk)
472 {
473 #ifdef GPT
474     struct gpt_hdr hdr;
475     struct gpt_ent *ent;
476     unsigned part, entries_per_sec;
477     daddr_t slba;
478 #endif
479 #if defined(GPT) || defined(LOADER_GELI_SUPPORT)
480     daddr_t elba;
481 #endif
482
483     struct dos_partition *dp;
484     char *sec;
485     unsigned i;
486
487     /*
488      * If we find a vdev on the whole disk, stop here.
489      */
490     if (vdev_probe(vdev_read, dsk, NULL) == 0)
491         return;
492
493 #ifdef LOADER_GELI_SUPPORT
494     /*
495      * Taste the disk, if it is GELI encrypted, decrypt it and check to see if
496      * it is a usable vdev then. Otherwise dig
497      * out the partition table and probe each slice/partition
498      * in turn for a vdev or GELI encrypted vdev.
499      */
500     elba = drvsize(dsk);
501     if (elba > 0) {
502         elba--;
503     }
504     if (geli_taste(vdev_read, dsk, elba) == 0) {
505         if (geli_passphrase(&gelipw, dsk->unit, ':', 0, dsk) == 0) {
506             if (vdev_probe(vdev_read, dsk, NULL) == 0) {
507                 return;
508             }
509         }
510     }
511 #endif /* LOADER_GELI_SUPPORT */
512
513     sec = dmadat->secbuf;
514     dsk->start = 0;
515
516 #ifdef GPT
517     /*
518      * First check for GPT.
519      */
520     if (drvread(dsk, sec, 1, 1)) {
521         return;
522     }
523     memcpy(&hdr, sec, sizeof(hdr));
524     if (memcmp(hdr.hdr_sig, GPT_HDR_SIG, sizeof(hdr.hdr_sig)) != 0 ||
525         hdr.hdr_lba_self != 1 || hdr.hdr_revision < 0x00010000 ||
526         hdr.hdr_entsz < sizeof(*ent) || DEV_BSIZE % hdr.hdr_entsz != 0) {
527         goto trymbr;
528     }
529
530     /*
531      * Probe all GPT partitions for the presence of ZFS pools. We
532      * return the spa_t for the first we find (if requested). This
533      * will have the effect of booting from the first pool on the
534      * disk.
535      *
536      * If no vdev is found, GELI decrypting the device and try again
537      */
538     entries_per_sec = DEV_BSIZE / hdr.hdr_entsz;
539     slba = hdr.hdr_lba_table;
540     elba = slba + hdr.hdr_entries / entries_per_sec;
541     while (slba < elba) {
542         dsk->start = 0;
543         if (drvread(dsk, sec, slba, 1))
544             return;
545         for (part = 0; part < entries_per_sec; part++) {
546             ent = (struct gpt_ent *)(sec + part * hdr.hdr_entsz);
547             if (memcmp(&ent->ent_type, &freebsd_zfs_uuid,
548                      sizeof(uuid_t)) == 0) {
549                 dsk->start = ent->ent_lba_start;
550                 dsk->slice = part + 1;
551                 dsk->part = 255;
552                 if (vdev_probe(vdev_read, dsk, NULL) == 0) {
553                     /*
554                      * This slice had a vdev. We need a new dsk
555                      * structure now since the vdev now owns this one.
556                      */
557                     dsk = copy_dsk(dsk);
558                 }
559 #ifdef LOADER_GELI_SUPPORT
560                 else if (geli_taste(vdev_read, dsk, ent->ent_lba_end -
561                          ent->ent_lba_start) == 0) {
562                     if (geli_passphrase(&gelipw, dsk->unit, 'p', dsk->slice, dsk) == 0) {
563                         /*
564                          * This slice has GELI, check it for ZFS.
565                          */
566                         if (vdev_probe(vdev_read, dsk, NULL) == 0) {
567                             /*
568                              * This slice had a vdev. We need a new dsk
569                              * structure now since the vdev now owns this one.
570                              */
571                             dsk = copy_dsk(dsk);
572                         }
573                         break;
574                     }
575                 }
576 #endif /* LOADER_GELI_SUPPORT */
577             }
578         }
579         slba++;
580     }
581     return;
582 trymbr:
583 #endif /* GPT */
584
585     if (drvread(dsk, sec, DOSBBSECTOR, 1))
586         return;
587     dp = (void *)(sec + DOSPARTOFF);
588
589     for (i = 0; i < NDOSPART; i++) {
590         if (!dp[i].dp_typ)
591             continue;
592         dsk->start = dp[i].dp_start;
593         dsk->slice = i + 1;
594         if (vdev_probe(vdev_read, dsk, NULL) == 0) {
595             dsk = copy_dsk(dsk);
596         }
597 #ifdef LOADER_GELI_SUPPORT
598         else if (geli_taste(vdev_read, dsk, dp[i].dp_size -
599                  dp[i].dp_start) == 0) {
600             if (geli_passphrase(&gelipw, dsk->unit, 's', i, dsk) == 0) {
601                 /*
602                  * This slice has GELI, check it for ZFS.
603                  */
604                 if (vdev_probe(vdev_read, dsk, NULL) == 0) {
605                     /*
606                      * This slice had a vdev. We need a new dsk
607                      * structure now since the vdev now owns this one.
608                      */
609                     dsk = copy_dsk(dsk);
610                 }
611                 break;
612             }
613         }
614 #endif /* LOADER_GELI_SUPPORT */
615     }
616 }
617
618 int
619 main(void)
620 {
621     dnode_phys_t dn;
622     off_t off;
623     struct dsk *dsk;
624     int autoboot, i;
625     int nextboot;
626     int rc;
627
628     dmadat = (void *)(roundup2(__base + (int32_t)&_end, 0x10000) - __base);
629
630     bios_getmem();
631
632     if (high_heap_size > 0) {
633         heap_end = PTOV(high_heap_base + high_heap_size);
634         heap_next = PTOV(high_heap_base);
635     } else {
636         heap_next = (char *)dmadat + sizeof(*dmadat);
637         heap_end = (char *)PTOV(bios_basemem);
638     }
639
640     dsk = malloc(sizeof(struct dsk));
641     dsk->drive = *(uint8_t *)PTOV(ARGS);
642     dsk->type = dsk->drive & DRV_HARD ? TYPE_AD : TYPE_FD;
643     dsk->unit = dsk->drive & DRV_MASK;
644     dsk->slice = *(uint8_t *)PTOV(ARGS + 1) + 1;
645     dsk->part = 0;
646     dsk->start = 0;
647     dsk->init = 0;
648
649     bootinfo.bi_version = BOOTINFO_VERSION;
650     bootinfo.bi_size = sizeof(bootinfo);
651     bootinfo.bi_basemem = bios_basemem / 1024;
652     bootinfo.bi_extmem = bios_extmem / 1024;
653     bootinfo.bi_memsizes_valid++;
654     bootinfo.bi_bios_dev = dsk->drive;
655
656     bootdev = MAKEBOOTDEV(dev_maj[dsk->type],
657                           dsk->slice, dsk->unit, dsk->part);
658
659     /* Process configuration file */
660
661     autoboot = 1;
662
663 #ifdef LOADER_GELI_SUPPORT
664     geli_init();
665 #endif
666     zfs_init();
667
668     /*
669      * Probe the boot drive first - we will try to boot from whatever
670      * pool we find on that drive.
671      */
672     probe_drive(dsk);
673
674     /*
675      * Probe the rest of the drives that the bios knows about. This
676      * will find any other available pools and it may fill in missing
677      * vdevs for the boot pool.
678      */
679 #ifndef VIRTUALBOX
680     for (i = 0; i < *(unsigned char *)PTOV(BIOS_NUMDRIVES); i++)
681 #else
682     for (i = 0; i < MAXBDDEV; i++)
683 #endif
684     {
685         if ((i | DRV_HARD) == *(uint8_t *)PTOV(ARGS))
686             continue;
687
688         if (!int13probe(i | DRV_HARD))
689             break;
690
691         dsk = malloc(sizeof(struct dsk));
692         dsk->drive = i | DRV_HARD;
693         dsk->type = dsk->drive & TYPE_AD;
694         dsk->unit = i;
695         dsk->slice = 0;
696         dsk->part = 0;
697         dsk->start = 0;
698         dsk->init = 0;
699         probe_drive(dsk);
700     }
701
702     /*
703      * The first discovered pool, if any, is the pool.
704      */
705     spa = spa_get_primary();
706     if (!spa) {
707         printf("%s: No ZFS pools located, can't boot\n", BOOTPROG);
708         for (;;)
709             ;
710     }
711
712     primary_spa = spa;
713     primary_vdev = spa_get_primary_vdev(spa);
714
715     nextboot = 0;
716     rc  = vdev_read_pad2(primary_vdev, cmd, sizeof(cmd));
717     if (vdev_clear_pad2(primary_vdev))
718         printf("failed to clear pad2 area of primary vdev\n");
719     if (rc == 0) {
720         if (*cmd) {
721             /*
722              * We could find an old-style ZFS Boot Block header here.
723              * Simply ignore it.
724              */
725             if (*(uint64_t *)cmd != 0x2f5b007b10c) {
726                 /*
727                  * Note that parse() is destructive to cmd[] and we also want
728                  * to honor RBX_QUIET option that could be present in cmd[].
729                  */
730                 nextboot = 1;
731                 memcpy(cmddup, cmd, sizeof(cmd));
732                 if (parse()) {
733                     printf("failed to parse pad2 area of primary vdev\n");
734                     reboot();
735                 }
736                 if (!OPT_CHECK(RBX_QUIET))
737                     printf("zfs nextboot: %s\n", cmddup);
738             }
739             /* Do not process this command twice */
740             *cmd = 0;
741         }
742     } else
743         printf("failed to read pad2 area of primary vdev\n");
744
745     /* Mount ZFS only if it's not already mounted via nextboot parsing. */
746     if (zfsmount.spa == NULL &&
747         (zfs_spa_init(spa) != 0 || zfs_mount(spa, 0, &zfsmount) != 0)) {
748         printf("%s: failed to mount default pool %s\n",
749             BOOTPROG, spa->spa_name);
750         autoboot = 0;
751     } else if (zfs_lookup(&zfsmount, PATH_CONFIG, &dn) == 0 ||
752         zfs_lookup(&zfsmount, PATH_DOTCONFIG, &dn) == 0) {
753         off = 0;
754         zfs_read(spa, &dn, &off, cmd, sizeof(cmd));
755     }
756
757     if (*cmd) {
758         /*
759          * Note that parse() is destructive to cmd[] and we also want
760          * to honor RBX_QUIET option that could be present in cmd[].
761          */
762         memcpy(cmddup, cmd, sizeof(cmd));
763         if (parse())
764             autoboot = 0;
765         if (!OPT_CHECK(RBX_QUIET))
766             printf("%s: %s\n", PATH_CONFIG, cmddup);
767         /* Do not process this command twice */
768         *cmd = 0;
769     }
770
771     /* Do not risk waiting at the prompt forever. */
772     if (nextboot && !autoboot)
773         reboot();
774
775     /*
776      * Try to exec /boot/loader. If interrupted by a keypress,
777      * or in case of failure, try to load a kernel directly instead.
778      */
779
780     if (autoboot && !*kname) {
781         memcpy(kname, PATH_LOADER_ZFS, sizeof(PATH_LOADER_ZFS));
782         if (!keyhit(3)) {
783             load();
784             memcpy(kname, PATH_KERNEL, sizeof(PATH_KERNEL));
785         }
786     }
787
788     /* Present the user with the boot2 prompt. */
789
790     for (;;) {
791         if (!autoboot || !OPT_CHECK(RBX_QUIET)) {
792             printf("\nFreeBSD/x86 boot\n");
793             if (zfs_rlookup(spa, zfsmount.rootobj, rootname) != 0)
794                 printf("Default: %s/<0x%llx>:%s\n"
795                        "boot: ",
796                        spa->spa_name, zfsmount.rootobj, kname);
797             else if (rootname[0] != '\0')
798                 printf("Default: %s/%s:%s\n"
799                        "boot: ",
800                        spa->spa_name, rootname, kname);
801             else
802                 printf("Default: %s:%s\n"
803                        "boot: ",
804                        spa->spa_name, kname);
805         }
806         if (ioctrl & IO_SERIAL)
807             sio_flush();
808         if (!autoboot || keyhit(5))
809             getstr(cmd, sizeof(cmd));
810         else if (!autoboot || !OPT_CHECK(RBX_QUIET))
811             putchar('\n');
812         autoboot = 0;
813         if (parse())
814             putchar('\a');
815         else
816             load();
817     }
818 }
819
820 /* XXX - Needed for btxld to link the boot2 binary; do not remove. */
821 void
822 exit(int x)
823 {
824     __exit(x);
825 }
826
827 void
828 reboot(void)
829 {
830     __exit(0);
831 }
832
833 static void
834 load(void)
835 {
836     union {
837         struct exec ex;
838         Elf32_Ehdr eh;
839     } hdr;
840     static Elf32_Phdr ep[2];
841     static Elf32_Shdr es[2];
842     caddr_t p;
843     dnode_phys_t dn;
844     off_t off;
845     uint32_t addr, x;
846     int fmt, i, j;
847
848     if (zfs_lookup(&zfsmount, kname, &dn)) {
849         printf("\nCan't find %s\n", kname);
850         return;
851     }
852     off = 0;
853     if (xfsread(&dn, &off, &hdr, sizeof(hdr)))
854         return;
855     if (N_GETMAGIC(hdr.ex) == ZMAGIC)
856         fmt = 0;
857     else if (IS_ELF(hdr.eh))
858         fmt = 1;
859     else {
860         printf("Invalid %s\n", "format");
861         return;
862     }
863     if (fmt == 0) {
864         addr = hdr.ex.a_entry & 0xffffff;
865         p = PTOV(addr);
866         off = PAGE_SIZE;
867         if (xfsread(&dn, &off, p, hdr.ex.a_text))
868             return;
869         p += roundup2(hdr.ex.a_text, PAGE_SIZE);
870         if (xfsread(&dn, &off, p, hdr.ex.a_data))
871             return;
872         p += hdr.ex.a_data + roundup2(hdr.ex.a_bss, PAGE_SIZE);
873         bootinfo.bi_symtab = VTOP(p);
874         memcpy(p, &hdr.ex.a_syms, sizeof(hdr.ex.a_syms));
875         p += sizeof(hdr.ex.a_syms);
876         if (hdr.ex.a_syms) {
877             if (xfsread(&dn, &off, p, hdr.ex.a_syms))
878                 return;
879             p += hdr.ex.a_syms;
880             if (xfsread(&dn, &off, p, sizeof(int)))
881                 return;
882             x = *(uint32_t *)p;
883             p += sizeof(int);
884             x -= sizeof(int);
885             if (xfsread(&dn, &off, p, x))
886                 return;
887             p += x;
888         }
889     } else {
890         off = hdr.eh.e_phoff;
891         for (j = i = 0; i < hdr.eh.e_phnum && j < 2; i++) {
892             if (xfsread(&dn, &off, ep + j, sizeof(ep[0])))
893                 return;
894             if (ep[j].p_type == PT_LOAD)
895                 j++;
896         }
897         for (i = 0; i < 2; i++) {
898             p = PTOV(ep[i].p_paddr & 0xffffff);
899             off = ep[i].p_offset;
900             if (xfsread(&dn, &off, p, ep[i].p_filesz))
901                 return;
902         }
903         p += roundup2(ep[1].p_memsz, PAGE_SIZE);
904         bootinfo.bi_symtab = VTOP(p);
905         if (hdr.eh.e_shnum == hdr.eh.e_shstrndx + 3) {
906             off = hdr.eh.e_shoff + sizeof(es[0]) *
907                 (hdr.eh.e_shstrndx + 1);
908             if (xfsread(&dn, &off, &es, sizeof(es)))
909                 return;
910             for (i = 0; i < 2; i++) {
911                 memcpy(p, &es[i].sh_size, sizeof(es[i].sh_size));
912                 p += sizeof(es[i].sh_size);
913                 off = es[i].sh_offset;
914                 if (xfsread(&dn, &off, p, es[i].sh_size))
915                     return;
916                 p += es[i].sh_size;
917             }
918         }
919         addr = hdr.eh.e_entry & 0xffffff;
920     }
921     bootinfo.bi_esymtab = VTOP(p);
922     bootinfo.bi_kernelname = VTOP(kname);
923     zfsargs.size = sizeof(zfsargs);
924     zfsargs.pool = zfsmount.spa->spa_guid;
925     zfsargs.root = zfsmount.rootobj;
926     zfsargs.primary_pool = primary_spa->spa_guid;
927 #ifdef LOADER_GELI_SUPPORT
928     bcopy(gelipw, zfsargs.gelipw, sizeof(zfsargs.gelipw));
929     bzero(gelipw, sizeof(gelipw));
930 #else
931     zfsargs.gelipw[0] = '\0';
932 #endif
933     if (primary_vdev != NULL)
934         zfsargs.primary_vdev = primary_vdev->v_guid;
935     else
936         printf("failed to detect primary vdev\n");
937     __exec((caddr_t)addr, RB_BOOTINFO | (opts & RBX_MASK),
938            bootdev,
939            KARGS_FLAGS_ZFS | KARGS_FLAGS_EXTARG,
940            (uint32_t) spa->spa_guid,
941            (uint32_t) (spa->spa_guid >> 32),
942            VTOP(&bootinfo),
943            zfsargs);
944 }
945
946 static int
947 zfs_mount_ds(char *dsname)
948 {
949     uint64_t newroot;
950     spa_t *newspa;
951     char *q;
952
953     q = strchr(dsname, '/');
954     if (q)
955         *q++ = '\0';
956     newspa = spa_find_by_name(dsname);
957     if (newspa == NULL) {
958         printf("\nCan't find ZFS pool %s\n", dsname);
959         return -1;
960     }
961
962     if (zfs_spa_init(newspa))
963         return -1;
964
965     newroot = 0;
966     if (q) {
967         if (zfs_lookup_dataset(newspa, q, &newroot)) {
968             printf("\nCan't find dataset %s in ZFS pool %s\n",
969                     q, newspa->spa_name);
970             return -1;
971         }
972     }
973     if (zfs_mount(newspa, newroot, &zfsmount)) {
974         printf("\nCan't mount ZFS dataset\n");
975         return -1;
976     }
977     spa = newspa;
978     return (0);
979 }
980
981 static int
982 parse(void)
983 {
984     char *arg = cmd;
985     char *ep, *p, *q;
986     const char *cp;
987     int c, i, j;
988
989     while ((c = *arg++)) {
990         if (c == ' ' || c == '\t' || c == '\n')
991             continue;
992         for (p = arg; *p && *p != '\n' && *p != ' ' && *p != '\t'; p++);
993         ep = p;
994         if (*p)
995             *p++ = 0;
996         if (c == '-') {
997             while ((c = *arg++)) {
998                 if (c == 'P') {
999                     if (*(uint8_t *)PTOV(0x496) & 0x10) {
1000                         cp = "yes";
1001                     } else {
1002                         opts |= OPT_SET(RBX_DUAL) | OPT_SET(RBX_SERIAL);
1003                         cp = "no";
1004                     }
1005                     printf("Keyboard: %s\n", cp);
1006                     continue;
1007                 } else if (c == 'S') {
1008                     j = 0;
1009                     while ((unsigned int)(i = *arg++ - '0') <= 9)
1010                         j = j * 10 + i;
1011                     if (j > 0 && i == -'0') {
1012                         comspeed = j;
1013                         break;
1014                     }
1015                     /* Fall through to error below ('S' not in optstr[]). */
1016                 }
1017                 for (i = 0; c != optstr[i]; i++)
1018                     if (i == NOPT - 1)
1019                         return -1;
1020                 opts ^= OPT_SET(flags[i]);
1021             }
1022             ioctrl = OPT_CHECK(RBX_DUAL) ? (IO_SERIAL|IO_KEYBOARD) :
1023                      OPT_CHECK(RBX_SERIAL) ? IO_SERIAL : IO_KEYBOARD;
1024             if (ioctrl & IO_SERIAL) {
1025                 if (sio_init(115200 / comspeed) != 0)
1026                     ioctrl &= ~IO_SERIAL;
1027             }
1028         } if (c == '?') {
1029             dnode_phys_t dn;
1030
1031             if (zfs_lookup(&zfsmount, arg, &dn) == 0) {
1032                 zap_list(spa, &dn);
1033             }
1034             return -1;
1035         } else {
1036             arg--;
1037
1038             /*
1039              * Report pool status if the comment is 'status'. Lets
1040              * hope no-one wants to load /status as a kernel.
1041              */
1042             if (!strcmp(arg, "status")) {
1043                 spa_all_status();
1044                 return -1;
1045             }
1046
1047             /*
1048              * If there is "zfs:" prefix simply ignore it.
1049              */
1050             if (strncmp(arg, "zfs:", 4) == 0)
1051                 arg += 4;
1052
1053             /*
1054              * If there is a colon, switch pools.
1055              */
1056             q = strchr(arg, ':');
1057             if (q) {
1058                 *q++ = '\0';
1059                 if (zfs_mount_ds(arg) != 0)
1060                     return -1;
1061                 arg = q;
1062             }
1063             if ((i = ep - arg)) {
1064                 if ((size_t)i >= sizeof(kname))
1065                     return -1;
1066                 memcpy(kname, arg, i + 1);
1067             }
1068         }
1069         arg = p;
1070     }
1071     return 0;
1072 }