]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - stand/common/part.c
loader: variable i is unused without MBR/GPT support built in
[FreeBSD/FreeBSD.git] / stand / common / part.c
1 /*-
2  * Copyright (c) 2012 Andrey V. Elsukov <ae@FreeBSD.org>
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  */
26
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
29
30 #include <stand.h>
31 #include <sys/param.h>
32 #include <sys/diskmbr.h>
33 #include <sys/disklabel.h>
34 #include <sys/endian.h>
35 #include <sys/gpt.h>
36 #include <sys/stddef.h>
37 #include <sys/queue.h>
38 #include <sys/vtoc.h>
39
40 #include <fs/cd9660/iso.h>
41
42 #include <zlib.h>
43 #include <part.h>
44 #include <uuid.h>
45
46 #ifdef PART_DEBUG
47 #define DPRINTF(fmt, args...) printf("%s: " fmt "\n", __func__, ## args)
48 #else
49 #define DPRINTF(fmt, args...)   ((void)0)
50 #endif
51
52 #ifdef LOADER_GPT_SUPPORT
53 #define MAXTBLSZ        64
54 static const uuid_t gpt_uuid_unused = GPT_ENT_TYPE_UNUSED;
55 static const uuid_t gpt_uuid_ms_basic_data = GPT_ENT_TYPE_MS_BASIC_DATA;
56 static const uuid_t gpt_uuid_freebsd_ufs = GPT_ENT_TYPE_FREEBSD_UFS;
57 static const uuid_t gpt_uuid_efi = GPT_ENT_TYPE_EFI;
58 static const uuid_t gpt_uuid_freebsd = GPT_ENT_TYPE_FREEBSD;
59 static const uuid_t gpt_uuid_freebsd_boot = GPT_ENT_TYPE_FREEBSD_BOOT;
60 static const uuid_t gpt_uuid_freebsd_nandfs = GPT_ENT_TYPE_FREEBSD_NANDFS;
61 static const uuid_t gpt_uuid_freebsd_swap = GPT_ENT_TYPE_FREEBSD_SWAP;
62 static const uuid_t gpt_uuid_freebsd_zfs = GPT_ENT_TYPE_FREEBSD_ZFS;
63 static const uuid_t gpt_uuid_freebsd_vinum = GPT_ENT_TYPE_FREEBSD_VINUM;
64 static const uuid_t gpt_uuid_apple_apfs = GPT_ENT_TYPE_APPLE_APFS;
65 #endif
66
67 struct pentry {
68         struct ptable_entry     part;
69         uint64_t                flags;
70         union {
71                 uint8_t bsd;
72                 uint8_t mbr;
73                 uuid_t  gpt;
74                 uint16_t vtoc8;
75         } type;
76         STAILQ_ENTRY(pentry)    entry;
77 };
78
79 struct ptable {
80         enum ptable_type        type;
81         uint16_t                sectorsize;
82         uint64_t                sectors;
83
84         STAILQ_HEAD(, pentry)   entries;
85 };
86
87 static struct parttypes {
88         enum partition_type     type;
89         const char              *desc;
90 } ptypes[] = {
91         { PART_UNKNOWN,         "Unknown" },
92         { PART_EFI,             "EFI" },
93         { PART_FREEBSD,         "FreeBSD" },
94         { PART_FREEBSD_BOOT,    "FreeBSD boot" },
95         { PART_FREEBSD_NANDFS,  "FreeBSD nandfs" },
96         { PART_FREEBSD_UFS,     "FreeBSD UFS" },
97         { PART_FREEBSD_ZFS,     "FreeBSD ZFS" },
98         { PART_FREEBSD_SWAP,    "FreeBSD swap" },
99         { PART_FREEBSD_VINUM,   "FreeBSD vinum" },
100         { PART_LINUX,           "Linux" },
101         { PART_LINUX_SWAP,      "Linux swap" },
102         { PART_DOS,             "DOS/Windows" },
103         { PART_ISO9660,         "ISO9660" },
104         { PART_APFS,            "APFS" },
105 };
106
107 const char *
108 parttype2str(enum partition_type type)
109 {
110         size_t i;
111
112         for (i = 0; i < nitems(ptypes); i++)
113                 if (ptypes[i].type == type)
114                         return (ptypes[i].desc);
115         return (ptypes[0].desc);
116 }
117
118 #ifdef LOADER_GPT_SUPPORT
119 static void
120 uuid_letoh(uuid_t *uuid)
121 {
122
123         uuid->time_low = le32toh(uuid->time_low);
124         uuid->time_mid = le16toh(uuid->time_mid);
125         uuid->time_hi_and_version = le16toh(uuid->time_hi_and_version);
126 }
127
128 static enum partition_type
129 gpt_parttype(uuid_t type)
130 {
131
132         if (uuid_equal(&type, &gpt_uuid_efi, NULL))
133                 return (PART_EFI);
134         else if (uuid_equal(&type, &gpt_uuid_ms_basic_data, NULL))
135                 return (PART_DOS);
136         else if (uuid_equal(&type, &gpt_uuid_freebsd_boot, NULL))
137                 return (PART_FREEBSD_BOOT);
138         else if (uuid_equal(&type, &gpt_uuid_freebsd_ufs, NULL))
139                 return (PART_FREEBSD_UFS);
140         else if (uuid_equal(&type, &gpt_uuid_freebsd_zfs, NULL))
141                 return (PART_FREEBSD_ZFS);
142         else if (uuid_equal(&type, &gpt_uuid_freebsd_swap, NULL))
143                 return (PART_FREEBSD_SWAP);
144         else if (uuid_equal(&type, &gpt_uuid_freebsd_vinum, NULL))
145                 return (PART_FREEBSD_VINUM);
146         else if (uuid_equal(&type, &gpt_uuid_freebsd_nandfs, NULL))
147                 return (PART_FREEBSD_NANDFS);
148         else if (uuid_equal(&type, &gpt_uuid_freebsd, NULL))
149                 return (PART_FREEBSD);
150         else if (uuid_equal(&type, &gpt_uuid_apple_apfs, NULL))
151                 return (PART_APFS);
152         return (PART_UNKNOWN);
153 }
154
155 static struct gpt_hdr *
156 gpt_checkhdr(struct gpt_hdr *hdr, uint64_t lba_self, uint64_t lba_last,
157     uint16_t sectorsize)
158 {
159         uint32_t sz, crc;
160
161         if (memcmp(hdr->hdr_sig, GPT_HDR_SIG, sizeof(hdr->hdr_sig)) != 0) {
162                 DPRINTF("no GPT signature");
163                 return (NULL);
164         }
165         sz = le32toh(hdr->hdr_size);
166         if (sz < 92 || sz > sectorsize) {
167                 DPRINTF("invalid GPT header size: %d", sz);
168                 return (NULL);
169         }
170         crc = le32toh(hdr->hdr_crc_self);
171         hdr->hdr_crc_self = crc32(0, Z_NULL, 0);
172         if (crc32(hdr->hdr_crc_self, (const Bytef *)hdr, sz) != crc) {
173                 DPRINTF("GPT header's CRC doesn't match");
174                 return (NULL);
175         }
176         hdr->hdr_crc_self = crc;
177         hdr->hdr_revision = le32toh(hdr->hdr_revision);
178         if (hdr->hdr_revision < GPT_HDR_REVISION) {
179                 DPRINTF("unsupported GPT revision %d", hdr->hdr_revision);
180                 return (NULL);
181         }
182         hdr->hdr_lba_self = le64toh(hdr->hdr_lba_self);
183         if (hdr->hdr_lba_self != lba_self) {
184                 DPRINTF("self LBA doesn't match");
185                 return (NULL);
186         }
187         hdr->hdr_lba_alt = le64toh(hdr->hdr_lba_alt);
188         if (hdr->hdr_lba_alt == hdr->hdr_lba_self) {
189                 DPRINTF("invalid alternate LBA");
190                 return (NULL);
191         }
192         hdr->hdr_entries = le32toh(hdr->hdr_entries);
193         hdr->hdr_entsz = le32toh(hdr->hdr_entsz);
194         if (hdr->hdr_entries == 0 ||
195             hdr->hdr_entsz < sizeof(struct gpt_ent) ||
196             sectorsize % hdr->hdr_entsz != 0) {
197                 DPRINTF("invalid entry size or number of entries");
198                 return (NULL);
199         }
200         hdr->hdr_lba_start = le64toh(hdr->hdr_lba_start);
201         hdr->hdr_lba_end = le64toh(hdr->hdr_lba_end);
202         hdr->hdr_lba_table = le64toh(hdr->hdr_lba_table);
203         hdr->hdr_crc_table = le32toh(hdr->hdr_crc_table);
204         uuid_letoh(&hdr->hdr_uuid);
205         return (hdr);
206 }
207
208 static int
209 gpt_checktbl(const struct gpt_hdr *hdr, uint8_t *tbl, size_t size,
210     uint64_t lba_last)
211 {
212         struct gpt_ent *ent;
213         uint32_t i, cnt;
214
215         cnt = size / hdr->hdr_entsz;
216         if (hdr->hdr_entries <= cnt) {
217                 cnt = hdr->hdr_entries;
218                 /* Check CRC only when buffer size is enough for table. */
219                 if (hdr->hdr_crc_table !=
220                     crc32(0, tbl, hdr->hdr_entries * hdr->hdr_entsz)) {
221                         DPRINTF("GPT table's CRC doesn't match");
222                         return (-1);
223                 }
224         }
225         for (i = 0; i < cnt; i++) {
226                 ent = (struct gpt_ent *)(tbl + i * hdr->hdr_entsz);
227                 uuid_letoh(&ent->ent_type);
228                 if (uuid_equal(&ent->ent_type, &gpt_uuid_unused, NULL))
229                         continue;
230                 ent->ent_lba_start = le64toh(ent->ent_lba_start);
231                 ent->ent_lba_end = le64toh(ent->ent_lba_end);
232         }
233         return (0);
234 }
235
236 static struct ptable *
237 ptable_gptread(struct ptable *table, void *dev, diskread_t dread)
238 {
239         struct pentry *entry;
240         struct gpt_hdr *phdr, hdr;
241         struct gpt_ent *ent;
242         uint8_t *buf, *tbl;
243         uint64_t offset;
244         int pri, sec;
245         size_t size, i;
246
247         buf = malloc(table->sectorsize);
248         if (buf == NULL)
249                 return (NULL);
250         tbl = malloc(table->sectorsize * MAXTBLSZ);
251         if (tbl == NULL) {
252                 free(buf);
253                 return (NULL);
254         }
255         /* Read the primary GPT header. */
256         if (dread(dev, buf, 1, 1) != 0) {
257                 ptable_close(table);
258                 table = NULL;
259                 goto out;
260         }
261         pri = sec = 0;
262         /* Check the primary GPT header. */
263         phdr = gpt_checkhdr((struct gpt_hdr *)buf, 1, table->sectors - 1,
264             table->sectorsize);
265         if (phdr != NULL) {
266                 /* Read the primary GPT table. */
267                 size = MIN(MAXTBLSZ,
268                     howmany(phdr->hdr_entries * phdr->hdr_entsz,
269                         table->sectorsize));
270                 if (dread(dev, tbl, size, phdr->hdr_lba_table) == 0 &&
271                     gpt_checktbl(phdr, tbl, size * table->sectorsize,
272                     table->sectors - 1) == 0) {
273                         memcpy(&hdr, phdr, sizeof(hdr));
274                         pri = 1;
275                 }
276         }
277         offset = pri ? hdr.hdr_lba_alt: table->sectors - 1;
278         /* Read the backup GPT header. */
279         if (dread(dev, buf, 1, offset) != 0)
280                 phdr = NULL;
281         else
282                 phdr = gpt_checkhdr((struct gpt_hdr *)buf, offset,
283                     table->sectors - 1, table->sectorsize);
284         if (phdr != NULL) {
285                 /*
286                  * Compare primary and backup headers.
287                  * If they are equal, then we do not need to read backup
288                  * table. If they are different, then prefer backup header
289                  * and try to read backup table.
290                  */
291                 if (pri == 0 ||
292                     uuid_equal(&hdr.hdr_uuid, &phdr->hdr_uuid, NULL) == 0 ||
293                     hdr.hdr_revision != phdr->hdr_revision ||
294                     hdr.hdr_size != phdr->hdr_size ||
295                     hdr.hdr_lba_start != phdr->hdr_lba_start ||
296                     hdr.hdr_lba_end != phdr->hdr_lba_end ||
297                     hdr.hdr_entries != phdr->hdr_entries ||
298                     hdr.hdr_entsz != phdr->hdr_entsz ||
299                     hdr.hdr_crc_table != phdr->hdr_crc_table) {
300                         /* Read the backup GPT table. */
301                         size = MIN(MAXTBLSZ,
302                                    howmany(phdr->hdr_entries * phdr->hdr_entsz,
303                                        table->sectorsize));
304                         if (dread(dev, tbl, size, phdr->hdr_lba_table) == 0 &&
305                             gpt_checktbl(phdr, tbl, size * table->sectorsize,
306                             table->sectors - 1) == 0) {
307                                 memcpy(&hdr, phdr, sizeof(hdr));
308                                 sec = 1;
309                         }
310                 }
311         }
312         if (pri == 0 && sec == 0) {
313                 /* Both primary and backup tables are invalid. */
314                 table->type = PTABLE_NONE;
315                 goto out;
316         }
317         DPRINTF("GPT detected");
318         size = MIN(hdr.hdr_entries * hdr.hdr_entsz,
319             MAXTBLSZ * table->sectorsize);
320
321         /*
322          * If the disk's sector count is smaller than the sector count recorded
323          * in the disk's GPT table header, set the table->sectors to the value
324          * recorded in GPT tables. This is done to work around buggy firmware
325          * that returns truncated disk sizes.
326          *
327          * Note, this is still not a foolproof way to get disk's size. For
328          * example, an image file can be truncated when copied to smaller media.
329          */
330         table->sectors = hdr.hdr_lba_alt + 1;
331
332         for (i = 0; i < size / hdr.hdr_entsz; i++) {
333                 ent = (struct gpt_ent *)(tbl + i * hdr.hdr_entsz);
334                 if (uuid_equal(&ent->ent_type, &gpt_uuid_unused, NULL))
335                         continue;
336
337                 /* Simple sanity checks. */
338                 if (ent->ent_lba_start < hdr.hdr_lba_start ||
339                     ent->ent_lba_end > hdr.hdr_lba_end ||
340                     ent->ent_lba_start > ent->ent_lba_end)
341                         continue;
342
343                 entry = malloc(sizeof(*entry));
344                 if (entry == NULL)
345                         break;
346                 entry->part.start = ent->ent_lba_start;
347                 entry->part.end = ent->ent_lba_end;
348                 entry->part.index = i + 1;
349                 entry->part.type = gpt_parttype(ent->ent_type);
350                 entry->flags = le64toh(ent->ent_attr);
351                 memcpy(&entry->type.gpt, &ent->ent_type, sizeof(uuid_t));
352                 STAILQ_INSERT_TAIL(&table->entries, entry, entry);
353                 DPRINTF("new GPT partition added");
354         }
355 out:
356         free(buf);
357         free(tbl);
358         return (table);
359 }
360 #endif /* LOADER_GPT_SUPPORT */
361
362 #ifdef LOADER_MBR_SUPPORT
363 /* We do not need to support too many EBR partitions in the loader */
364 #define MAXEBRENTRIES           8
365 static enum partition_type
366 mbr_parttype(uint8_t type)
367 {
368
369         switch (type) {
370         case DOSPTYP_386BSD:
371                 return (PART_FREEBSD);
372         case DOSPTYP_LINSWP:
373                 return (PART_LINUX_SWAP);
374         case DOSPTYP_LINUX:
375                 return (PART_LINUX);
376         case 0x01:
377         case 0x04:
378         case 0x06:
379         case 0x07:
380         case 0x0b:
381         case 0x0c:
382         case 0x0e:
383                 return (PART_DOS);
384         }
385         return (PART_UNKNOWN);
386 }
387
388 static struct ptable *
389 ptable_ebrread(struct ptable *table, void *dev, diskread_t dread)
390 {
391         struct dos_partition *dp;
392         struct pentry *e1, *entry;
393         uint32_t start, end, offset;
394         u_char *buf;
395         int i, index;
396
397         STAILQ_FOREACH(e1, &table->entries, entry) {
398                 if (e1->type.mbr == DOSPTYP_EXT ||
399                     e1->type.mbr == DOSPTYP_EXTLBA)
400                         break;
401         }
402         if (e1 == NULL)
403                 return (table);
404         index = 5;
405         offset = e1->part.start;
406         buf = malloc(table->sectorsize);
407         if (buf == NULL)
408                 return (table);
409         DPRINTF("EBR detected");
410         for (i = 0; i < MAXEBRENTRIES; i++) {
411 #if 0   /* Some BIOSes return an incorrect number of sectors */
412                 if (offset >= table->sectors)
413                         break;
414 #endif
415                 if (dread(dev, buf, 1, offset) != 0)
416                         break;
417                 dp = (struct dos_partition *)(buf + DOSPARTOFF);
418                 if (dp[0].dp_typ == 0)
419                         break;
420                 start = le32toh(dp[0].dp_start);
421                 if (dp[0].dp_typ == DOSPTYP_EXT &&
422                     dp[1].dp_typ == 0) {
423                         offset = e1->part.start + start;
424                         continue;
425                 }
426                 end = le32toh(dp[0].dp_size);
427                 entry = malloc(sizeof(*entry));
428                 if (entry == NULL)
429                         break;
430                 entry->part.start = offset + start;
431                 entry->part.end = entry->part.start + end - 1;
432                 entry->part.index = index++;
433                 entry->part.type = mbr_parttype(dp[0].dp_typ);
434                 entry->flags = dp[0].dp_flag;
435                 entry->type.mbr = dp[0].dp_typ;
436                 STAILQ_INSERT_TAIL(&table->entries, entry, entry);
437                 DPRINTF("new EBR partition added");
438                 if (dp[1].dp_typ == 0)
439                         break;
440                 offset = e1->part.start + le32toh(dp[1].dp_start);
441         }
442         free(buf);
443         return (table);
444 }
445 #endif /* LOADER_MBR_SUPPORT */
446
447 static enum partition_type
448 bsd_parttype(uint8_t type)
449 {
450
451         switch (type) {
452         case FS_NANDFS:
453                 return (PART_FREEBSD_NANDFS);
454         case FS_SWAP:
455                 return (PART_FREEBSD_SWAP);
456         case FS_BSDFFS:
457                 return (PART_FREEBSD_UFS);
458         case FS_VINUM:
459                 return (PART_FREEBSD_VINUM);
460         case FS_ZFS:
461                 return (PART_FREEBSD_ZFS);
462         }
463         return (PART_UNKNOWN);
464 }
465
466 static struct ptable *
467 ptable_bsdread(struct ptable *table, void *dev, diskread_t dread)
468 {
469         struct disklabel *dl;
470         struct partition *part;
471         struct pentry *entry;
472         uint8_t *buf;
473         uint32_t raw_offset;
474         int i;
475
476         if (table->sectorsize < sizeof(struct disklabel)) {
477                 DPRINTF("Too small sectorsize");
478                 return (table);
479         }
480         buf = malloc(table->sectorsize);
481         if (buf == NULL)
482                 return (table);
483         if (dread(dev, buf, 1, 1) != 0) {
484                 DPRINTF("read failed");
485                 ptable_close(table);
486                 table = NULL;
487                 goto out;
488         }
489         dl = (struct disklabel *)buf;
490         if (le32toh(dl->d_magic) != DISKMAGIC &&
491             le32toh(dl->d_magic2) != DISKMAGIC)
492                 goto out;
493         if (le32toh(dl->d_secsize) != table->sectorsize) {
494                 DPRINTF("unsupported sector size");
495                 goto out;
496         }
497         dl->d_npartitions = le16toh(dl->d_npartitions);
498         if (dl->d_npartitions > 20 || dl->d_npartitions < 8) {
499                 DPRINTF("invalid number of partitions");
500                 goto out;
501         }
502         DPRINTF("BSD detected");
503         part = &dl->d_partitions[0];
504         raw_offset = le32toh(part[RAW_PART].p_offset);
505         for (i = 0; i < dl->d_npartitions; i++, part++) {
506                 if (i == RAW_PART)
507                         continue;
508                 if (part->p_size == 0)
509                         continue;
510                 entry = malloc(sizeof(*entry));
511                 if (entry == NULL)
512                         break;
513                 entry->part.start = le32toh(part->p_offset) - raw_offset;
514                 entry->part.end = entry->part.start +
515                     le32toh(part->p_size) - 1;
516                 entry->part.type = bsd_parttype(part->p_fstype);
517                 entry->part.index = i; /* starts from zero */
518                 entry->type.bsd = part->p_fstype;
519                 STAILQ_INSERT_TAIL(&table->entries, entry, entry);
520                 DPRINTF("new BSD partition added");
521         }
522         table->type = PTABLE_BSD;
523 out:
524         free(buf);
525         return (table);
526 }
527
528 #ifdef LOADER_VTOC8_SUPPORT
529 static enum partition_type
530 vtoc8_parttype(uint16_t type)
531 {
532
533         switch (type) {
534         case VTOC_TAG_FREEBSD_NANDFS:
535                 return (PART_FREEBSD_NANDFS);
536         case VTOC_TAG_FREEBSD_SWAP:
537                 return (PART_FREEBSD_SWAP);
538         case VTOC_TAG_FREEBSD_UFS:
539                 return (PART_FREEBSD_UFS);
540         case VTOC_TAG_FREEBSD_VINUM:
541                 return (PART_FREEBSD_VINUM);
542         case VTOC_TAG_FREEBSD_ZFS:
543                 return (PART_FREEBSD_ZFS);
544         }
545         return (PART_UNKNOWN);
546 }
547
548 static struct ptable *
549 ptable_vtoc8read(struct ptable *table, void *dev, diskread_t dread)
550 {
551         struct pentry *entry;
552         struct vtoc8 *dl;
553         uint8_t *buf;
554         uint16_t sum, heads, sectors;
555         int i;
556
557         if (table->sectorsize != sizeof(struct vtoc8))
558                 return (table);
559         buf = malloc(table->sectorsize);
560         if (buf == NULL)
561                 return (table);
562         if (dread(dev, buf, 1, 0) != 0) {
563                 DPRINTF("read failed");
564                 ptable_close(table);
565                 table = NULL;
566                 goto out;
567         }
568         dl = (struct vtoc8 *)buf;
569         /* Check the sum */
570         for (i = sum = 0; i < sizeof(struct vtoc8); i += sizeof(sum))
571                 sum ^= be16dec(buf + i);
572         if (sum != 0) {
573                 DPRINTF("incorrect checksum");
574                 goto out;
575         }
576         if (be16toh(dl->nparts) != VTOC8_NPARTS) {
577                 DPRINTF("invalid number of entries");
578                 goto out;
579         }
580         sectors = be16toh(dl->nsecs);
581         heads = be16toh(dl->nheads);
582         if (sectors * heads == 0) {
583                 DPRINTF("invalid geometry");
584                 goto out;
585         }
586         DPRINTF("VTOC8 detected");
587         for (i = 0; i < VTOC8_NPARTS; i++) {
588                 dl->part[i].tag = be16toh(dl->part[i].tag);
589                 if (i == VTOC_RAW_PART ||
590                     dl->part[i].tag == VTOC_TAG_UNASSIGNED)
591                         continue;
592                 entry = malloc(sizeof(*entry));
593                 if (entry == NULL)
594                         break;
595                 entry->part.start = be32toh(dl->map[i].cyl) * heads * sectors;
596                 entry->part.end = be32toh(dl->map[i].nblks) +
597                     entry->part.start - 1;
598                 entry->part.type = vtoc8_parttype(dl->part[i].tag);
599                 entry->part.index = i; /* starts from zero */
600                 entry->type.vtoc8 = dl->part[i].tag;
601                 STAILQ_INSERT_TAIL(&table->entries, entry, entry);
602                 DPRINTF("new VTOC8 partition added");
603         }
604         table->type = PTABLE_VTOC8;
605 out:
606         free(buf);
607         return (table);
608
609 }
610 #endif /* LOADER_VTOC8_SUPPORT */
611
612 #define cdb2devb(bno)   ((bno) * ISO_DEFAULT_BLOCK_SIZE / table->sectorsize)
613
614 static struct ptable *
615 ptable_iso9660read(struct ptable *table, void *dev, diskread_t dread)
616 {
617         uint8_t *buf;
618         struct iso_primary_descriptor *vd;
619         struct pentry *entry;
620
621         buf = malloc(table->sectorsize);
622         if (buf == NULL)
623                 return (table);
624                 
625         if (dread(dev, buf, 1, cdb2devb(16)) != 0) {
626                 DPRINTF("read failed");
627                 ptable_close(table);
628                 table = NULL;
629                 goto out;
630         }
631         vd = (struct iso_primary_descriptor *)buf;
632         if (bcmp(vd->id, ISO_STANDARD_ID, sizeof vd->id) != 0)
633                 goto out;
634
635         entry = malloc(sizeof(*entry));
636         if (entry == NULL)
637                 goto out;
638         entry->part.start = 0;
639         entry->part.end = table->sectors;
640         entry->part.type = PART_ISO9660;
641         entry->part.index = 0;
642         STAILQ_INSERT_TAIL(&table->entries, entry, entry);
643
644         table->type = PTABLE_ISO9660;
645
646 out:
647         free(buf);
648         return (table);
649 }
650
651 struct ptable *
652 ptable_open(void *dev, uint64_t sectors, uint16_t sectorsize,
653     diskread_t *dread)
654 {
655         struct dos_partition *dp;
656         struct ptable *table;
657         uint8_t *buf;
658 #ifdef LOADER_MBR_SUPPORT
659         struct pentry *entry;
660         uint32_t start, end;
661         int has_ext;
662 #endif
663         table = NULL;
664         dp = NULL;
665         buf = malloc(sectorsize);
666         if (buf == NULL)
667                 return (NULL);
668         /* First, read the MBR. */
669         if (dread(dev, buf, 1, DOSBBSECTOR) != 0) {
670                 DPRINTF("read failed");
671                 goto out;
672         }
673
674         table = malloc(sizeof(*table));
675         if (table == NULL)
676                 goto out;
677         table->sectors = sectors;
678         table->sectorsize = sectorsize;
679         table->type = PTABLE_NONE;
680         STAILQ_INIT(&table->entries);
681
682         if (ptable_iso9660read(table, dev, dread) == NULL) {
683                 /* Read error. */
684                 table = NULL;
685                 goto out;
686         } else if (table->type == PTABLE_ISO9660)
687                 goto out;
688
689 #ifdef LOADER_VTOC8_SUPPORT
690         if (be16dec(buf + offsetof(struct vtoc8, magic)) == VTOC_MAGIC) {
691                 if (ptable_vtoc8read(table, dev, dread) == NULL) {
692                         /* Read error. */
693                         table = NULL;
694                         goto out;
695                 } else if (table->type == PTABLE_VTOC8)
696                         goto out;
697         }
698 #endif
699         /* Check the BSD label. */
700         if (ptable_bsdread(table, dev, dread) == NULL) { /* Read error. */
701                 table = NULL;
702                 goto out;
703         } else if (table->type == PTABLE_BSD)
704                 goto out;
705
706 #if defined(LOADER_GPT_SUPPORT) || defined(LOADER_MBR_SUPPORT)
707         /* Check the MBR magic. */
708         if (buf[DOSMAGICOFFSET] != 0x55 ||
709             buf[DOSMAGICOFFSET + 1] != 0xaa) {
710                 DPRINTF("magic sequence not found");
711 #if defined(LOADER_GPT_SUPPORT)
712                 /* There is no PMBR, check that we have backup GPT */
713                 table->type = PTABLE_GPT;
714                 table = ptable_gptread(table, dev, dread);
715 #endif
716                 goto out;
717         }
718         /* Check that we have PMBR. Also do some validation. */
719         dp = malloc(NDOSPART * sizeof(struct dos_partition));
720         if (dp == NULL)
721                 goto out;
722         bcopy(buf + DOSPARTOFF, dp, NDOSPART * sizeof(struct dos_partition));
723
724         /*
725          * In mac we can have PMBR partition in hybrid MBR;
726          * that is, MBR partition which has DOSPTYP_PMBR entry defined as
727          * start sector 1. After DOSPTYP_PMBR, there may be other partitions.
728          * UEFI compliant PMBR has no other partitions.
729          */
730         for (int i = 0; i < NDOSPART; i++) {
731                 if (dp[i].dp_flag != 0 && dp[i].dp_flag != 0x80) {
732                         DPRINTF("invalid partition flag %x", dp[i].dp_flag);
733                         goto out;
734                 }
735 #ifdef LOADER_GPT_SUPPORT
736                 if (dp[i].dp_typ == DOSPTYP_PMBR && dp[i].dp_start == 1) {
737                         table->type = PTABLE_GPT;
738                         DPRINTF("PMBR detected");
739                 }
740 #endif
741         }
742 #ifdef LOADER_GPT_SUPPORT
743         if (table->type == PTABLE_GPT) {
744                 table = ptable_gptread(table, dev, dread);
745                 goto out;
746         }
747 #endif
748 #ifdef LOADER_MBR_SUPPORT
749         /* Read MBR. */
750         DPRINTF("MBR detected");
751         table->type = PTABLE_MBR;
752         for (int i = has_ext = 0; i < NDOSPART; i++) {
753                 if (dp[i].dp_typ == 0)
754                         continue;
755                 start = le32dec(&(dp[i].dp_start));
756                 end = le32dec(&(dp[i].dp_size));
757                 if (start == 0 || end == 0)
758                         continue;
759 #if 0   /* Some BIOSes return an incorrect number of sectors */
760                 if (start + end - 1 >= sectors)
761                         continue;       /* XXX: ignore */
762 #endif
763                 if (dp[i].dp_typ == DOSPTYP_EXT ||
764                     dp[i].dp_typ == DOSPTYP_EXTLBA)
765                         has_ext = 1;
766                 entry = malloc(sizeof(*entry));
767                 if (entry == NULL)
768                         break;
769                 entry->part.start = start;
770                 entry->part.end = start + end - 1;
771                 entry->part.index = i + 1;
772                 entry->part.type = mbr_parttype(dp[i].dp_typ);
773                 entry->flags = dp[i].dp_flag;
774                 entry->type.mbr = dp[i].dp_typ;
775                 STAILQ_INSERT_TAIL(&table->entries, entry, entry);
776                 DPRINTF("new MBR partition added");
777         }
778         if (has_ext) {
779                 table = ptable_ebrread(table, dev, dread);
780                 /* FALLTHROUGH */
781         }
782 #endif /* LOADER_MBR_SUPPORT */
783 #endif /* LOADER_MBR_SUPPORT || LOADER_GPT_SUPPORT */
784 out:
785         free(dp);
786         free(buf);
787         return (table);
788 }
789
790 void
791 ptable_close(struct ptable *table)
792 {
793         struct pentry *entry;
794
795         if (table == NULL)
796                 return;
797
798         while (!STAILQ_EMPTY(&table->entries)) {
799                 entry = STAILQ_FIRST(&table->entries);
800                 STAILQ_REMOVE_HEAD(&table->entries, entry);
801                 free(entry);
802         }
803         free(table);
804 }
805
806 enum ptable_type
807 ptable_gettype(const struct ptable *table)
808 {
809
810         return (table->type);
811 }
812
813 int
814 ptable_getsize(const struct ptable *table, uint64_t *sizep)
815 {
816         uint64_t tmp = table->sectors * table->sectorsize;
817
818         if (tmp < table->sectors)
819                 return (EOVERFLOW);
820
821         if (sizep != NULL)
822                 *sizep = tmp;
823         return (0);
824 }
825
826 int
827 ptable_getpart(const struct ptable *table, struct ptable_entry *part, int index)
828 {
829         struct pentry *entry;
830
831         if (part == NULL || table == NULL)
832                 return (EINVAL);
833
834         STAILQ_FOREACH(entry, &table->entries, entry) {
835                 if (entry->part.index != index)
836                         continue;
837                 memcpy(part, &entry->part, sizeof(*part));
838                 return (0);
839         }
840         return (ENOENT);
841 }
842
843 /*
844  * Search for a slice with the following preferences:
845  *
846  * 1: Active FreeBSD slice
847  * 2: Non-active FreeBSD slice
848  * 3: Active Linux slice
849  * 4: non-active Linux slice
850  * 5: Active FAT/FAT32 slice
851  * 6: non-active FAT/FAT32 slice
852  */
853 #define PREF_RAWDISK    0
854 #define PREF_FBSD_ACT   1
855 #define PREF_FBSD       2
856 #define PREF_LINUX_ACT  3
857 #define PREF_LINUX      4
858 #define PREF_DOS_ACT    5
859 #define PREF_DOS        6
860 #define PREF_NONE       7
861 int
862 ptable_getbestpart(const struct ptable *table, struct ptable_entry *part)
863 {
864         struct pentry *entry, *best;
865         int pref, preflevel;
866
867         if (part == NULL || table == NULL)
868                 return (EINVAL);
869
870         best = NULL;
871         preflevel = pref = PREF_NONE;
872         STAILQ_FOREACH(entry, &table->entries, entry) {
873 #ifdef LOADER_MBR_SUPPORT
874                 if (table->type == PTABLE_MBR) {
875                         switch (entry->type.mbr) {
876                         case DOSPTYP_386BSD:
877                                 pref = entry->flags & 0x80 ? PREF_FBSD_ACT:
878                                     PREF_FBSD;
879                                 break;
880                         case DOSPTYP_LINUX:
881                                 pref = entry->flags & 0x80 ? PREF_LINUX_ACT:
882                                     PREF_LINUX;
883                                 break;
884                         case 0x01:              /* DOS/Windows */
885                         case 0x04:
886                         case 0x06:
887                         case 0x0c:
888                         case 0x0e:
889                         case DOSPTYP_FAT32:
890                                 pref = entry->flags & 0x80 ? PREF_DOS_ACT:
891                                     PREF_DOS;
892                                 break;
893                         default:
894                                 pref = PREF_NONE;
895                         }
896                 }
897 #endif /* LOADER_MBR_SUPPORT */
898 #ifdef LOADER_GPT_SUPPORT
899                 if (table->type == PTABLE_GPT) {
900                         if (entry->part.type == PART_DOS)
901                                 pref = PREF_DOS;
902                         else if (entry->part.type == PART_FREEBSD_UFS ||
903                             entry->part.type == PART_FREEBSD_ZFS)
904                                 pref = PREF_FBSD;
905                         else
906                                 pref = PREF_NONE;
907                 }
908 #endif /* LOADER_GPT_SUPPORT */
909                 if (pref < preflevel) {
910                         preflevel = pref;
911                         best = entry;
912                 }
913         }
914         if (best != NULL) {
915                 memcpy(part, &best->part, sizeof(*part));
916                 return (0);
917         }
918         return (ENOENT);
919 }
920
921 int
922 ptable_iterate(const struct ptable *table, void *arg, ptable_iterate_t *iter)
923 {
924         struct pentry *entry;
925         char name[32];
926         int ret = 0;
927
928         name[0] = '\0';
929         STAILQ_FOREACH(entry, &table->entries, entry) {
930 #ifdef LOADER_MBR_SUPPORT
931                 if (table->type == PTABLE_MBR)
932                         sprintf(name, "s%d", entry->part.index);
933                 else
934 #endif
935 #ifdef LOADER_GPT_SUPPORT
936                 if (table->type == PTABLE_GPT)
937                         sprintf(name, "p%d", entry->part.index);
938                 else
939 #endif
940 #ifdef LOADER_VTOC8_SUPPORT
941                 if (table->type == PTABLE_VTOC8)
942                         sprintf(name, "%c", (uint8_t) 'a' +
943                             entry->part.index);
944                 else
945 #endif
946                 if (table->type == PTABLE_BSD)
947                         sprintf(name, "%c", (uint8_t) 'a' +
948                             entry->part.index);
949                 if ((ret = iter(arg, name, &entry->part)) != 0)
950                         return (ret);
951         }
952         return (ret);
953 }