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