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