Home | History | Annotate | Line # | Download | only in efiboot
efiblock.c revision 1.2.2.4
      1 /* $NetBSD: efiblock.c,v 1.2.2.4 2018/11/26 01:52:52 pgoyette Exp $ */
      2 
      3 /*-
      4  * Copyright (c) 2016 Kimihiro Nonaka <nonaka (at) netbsd.org>
      5  * Copyright (c) 2018 Jared McNeill <jmcneill (at) invisible.ca>
      6  * All rights reserved.
      7  *
      8  * Redistribution and use in source and binary forms, with or without
      9  * modification, are permitted provided that the following conditions
     10  * are met:
     11  * 1. Redistributions of source code must retain the above copyright
     12  *    notice, this list of conditions and the following disclaimer.
     13  * 2. Redistributions in binary form must reproduce the above copyright
     14  *    notice, this list of conditions and the following disclaimer in the
     15  *    documentation and/or other materials provided with the distribution.
     16  *
     17  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     27  * SUCH DAMAGE.
     28  */
     29 
     30 #define FSTYPENAMES
     31 
     32 #include <sys/param.h>
     33 #include <sys/md5.h>
     34 #include <sys/uuid.h>
     35 
     36 #include "efiboot.h"
     37 #include "efiblock.h"
     38 
     39 static EFI_HANDLE *efi_block;
     40 static UINTN efi_nblock;
     41 static struct efi_block_part *efi_block_booted = NULL;
     42 
     43 static TAILQ_HEAD(, efi_block_dev) efi_block_devs = TAILQ_HEAD_INITIALIZER(efi_block_devs);
     44 
     45 static int
     46 efi_block_parse(const char *fname, struct efi_block_part **pbpart, char **pfile)
     47 {
     48 	struct efi_block_dev *bdev;
     49 	struct efi_block_part *bpart;
     50 	char pathbuf[PATH_MAX], *default_device, *ep = NULL;
     51 	const char *full_path;
     52 	intmax_t dev;
     53 	int part;
     54 
     55 	default_device = get_default_device();
     56 	if (strchr(fname, ':') == NULL) {
     57 		if (strlen(default_device) > 0) {
     58 			snprintf(pathbuf, sizeof(pathbuf), "%s:%s", default_device, fname);
     59 			full_path = pathbuf;
     60 			*pfile = __UNCONST(fname);
     61 		} else {
     62 			return EINVAL;
     63 		}
     64 	} else {
     65 		full_path = fname;
     66 		*pfile = strchr(fname, ':') + 1;
     67 	}
     68 
     69 	if (strncasecmp(full_path, "hd", 2) != 0)
     70 		return EINVAL;
     71 	dev = strtoimax(full_path + 2, &ep, 10);
     72 	if (dev < 0 || dev >= efi_nblock)
     73 		return ENXIO;
     74 	if (ep[0] < 'a' || ep[0] >= 'a' + MAXPARTITIONS || ep[1] != ':')
     75 		return EINVAL;
     76 	part = ep[0] - 'a';
     77 	TAILQ_FOREACH(bdev, &efi_block_devs, entries) {
     78 		if (bdev->index == dev) {
     79 			TAILQ_FOREACH(bpart, &bdev->partitions, entries) {
     80 				if (bpart->index == part) {
     81 					*pbpart = bpart;
     82 					return 0;
     83 				}
     84 			}
     85 		}
     86 	}
     87 
     88 	return ENOENT;
     89 }
     90 
     91 static void
     92 efi_block_generate_hash_mbr(struct efi_block_part *bpart, struct mbr_sector *mbr)
     93 {
     94 	MD5_CTX md5ctx;
     95 
     96 	MD5Init(&md5ctx);
     97 	MD5Update(&md5ctx, (void *)mbr, sizeof(*mbr));
     98 	MD5Final(bpart->hash, &md5ctx);
     99 }
    100 
    101 static int
    102 efi_block_find_partitions_disklabel(struct efi_block_dev *bdev, struct mbr_sector *mbr, uint32_t start, uint32_t size)
    103 {
    104 	struct efi_block_part *bpart;
    105 	struct disklabel d;
    106 	struct partition *p;
    107 	EFI_STATUS status;
    108 	EFI_LBA lba;
    109 	uint8_t *buf;
    110 	UINT32 sz;
    111 	int n;
    112 
    113 	sz = __MAX(sizeof(d), bdev->bio->Media->BlockSize);
    114 	sz = roundup(sz, bdev->bio->Media->BlockSize);
    115 	buf = AllocatePool(sz);
    116 	if (!buf)
    117 		return ENOMEM;
    118 
    119 	lba = (((EFI_LBA)start + LABELSECTOR) * DEV_BSIZE) / bdev->bio->Media->BlockSize;
    120 	status = uefi_call_wrapper(bdev->bio->ReadBlocks, 5, bdev->bio, bdev->media_id, lba, sz, buf);
    121 	if (EFI_ERROR(status) || getdisklabel(buf, &d) != NULL) {
    122 		FreePool(buf);
    123 		return EIO;
    124 	}
    125 	FreePool(buf);
    126 
    127 	if (le32toh(d.d_magic) != DISKMAGIC || le32toh(d.d_magic2) != DISKMAGIC)
    128 		return EINVAL;
    129 	if (le16toh(d.d_npartitions) > MAXPARTITIONS)
    130 		return EINVAL;
    131 
    132 	for (n = 0; n < le16toh(d.d_npartitions); n++) {
    133 		p = &d.d_partitions[n];
    134 		switch (p->p_fstype) {
    135 		case FS_BSDFFS:
    136 		case FS_MSDOS:
    137 		case FS_BSDLFS:
    138 			break;
    139 		default:
    140 			continue;
    141 		}
    142 
    143 		bpart = alloc(sizeof(*bpart));
    144 		bpart->index = n;
    145 		bpart->bdev = bdev;
    146 		bpart->type = EFI_BLOCK_PART_DISKLABEL;
    147 		bpart->disklabel.secsize = le32toh(d.d_secsize);
    148 		bpart->disklabel.part = *p;
    149 		efi_block_generate_hash_mbr(bpart, mbr);
    150 		TAILQ_INSERT_TAIL(&bdev->partitions, bpart, entries);
    151 	}
    152 
    153 	return 0;
    154 }
    155 
    156 static int
    157 efi_block_find_partitions_mbr(struct efi_block_dev *bdev)
    158 {
    159 	struct mbr_sector mbr;
    160 	struct mbr_partition *mbr_part;
    161 	EFI_STATUS status;
    162 	uint8_t *buf;
    163 	UINT32 sz;
    164 	int n;
    165 
    166 	sz = __MAX(sizeof(mbr), bdev->bio->Media->BlockSize);
    167 	sz = roundup(sz, bdev->bio->Media->BlockSize);
    168 	buf = AllocatePool(sz);
    169 	if (!buf)
    170 		return ENOMEM;
    171 
    172 	status = uefi_call_wrapper(bdev->bio->ReadBlocks, 5, bdev->bio, bdev->media_id, 0, sz, buf);
    173 	if (EFI_ERROR(status)) {
    174 		FreePool(buf);
    175 		return EIO;
    176 	}
    177 	memcpy(&mbr, buf, sizeof(mbr));
    178 	FreePool(buf);
    179 
    180 	if (le32toh(mbr.mbr_magic) != MBR_MAGIC)
    181 		return ENOENT;
    182 
    183 	for (n = 0; n < MBR_PART_COUNT; n++) {
    184 		mbr_part = &mbr.mbr_parts[n];
    185 		if (le32toh(mbr_part->mbrp_size) == 0)
    186 			continue;
    187 		if (mbr_part->mbrp_type == MBR_PTYPE_NETBSD) {
    188 			efi_block_find_partitions_disklabel(bdev, &mbr, le32toh(mbr_part->mbrp_start), le32toh(mbr_part->mbrp_size));
    189 			break;
    190 		}
    191 	}
    192 
    193 	return 0;
    194 }
    195 
    196 static const struct {
    197 	struct uuid guid;
    198 	uint8_t fstype;
    199 } gpt_guid_to_str[] = {
    200 	{ GPT_ENT_TYPE_NETBSD_FFS,		FS_BSDFFS },
    201 	{ GPT_ENT_TYPE_NETBSD_LFS,		FS_BSDLFS },
    202 	{ GPT_ENT_TYPE_NETBSD_RAIDFRAME,	FS_RAID },
    203 	{ GPT_ENT_TYPE_NETBSD_CCD,		FS_CCD },
    204 	{ GPT_ENT_TYPE_NETBSD_CGD,		FS_CGD },
    205 	{ GPT_ENT_TYPE_MS_BASIC_DATA,		FS_MSDOS },	/* or NTFS? ambiguous */
    206 };
    207 
    208 static int
    209 efi_block_find_partitions_gpt_entry(struct efi_block_dev *bdev, struct gpt_hdr *hdr, struct gpt_ent *ent, UINT32 index)
    210 {
    211 	struct efi_block_part *bpart;
    212 	uint8_t fstype = FS_UNUSED;
    213 	struct uuid uuid;
    214 	int n;
    215 
    216 	memcpy(&uuid, ent->ent_type, sizeof(uuid));
    217 	for (n = 0; n < __arraycount(gpt_guid_to_str); n++)
    218 		if (memcmp(ent->ent_type, &gpt_guid_to_str[n].guid, sizeof(ent->ent_type)) == 0) {
    219 			fstype = gpt_guid_to_str[n].fstype;
    220 			break;
    221 		}
    222 	if (fstype == FS_UNUSED)
    223 		return 0;
    224 
    225 	bpart = alloc(sizeof(*bpart));
    226 	bpart->index = index;
    227 	bpart->bdev = bdev;
    228 	bpart->type = EFI_BLOCK_PART_GPT;
    229 	bpart->gpt.fstype = fstype;
    230 	bpart->gpt.ent = *ent;
    231 	memcpy(bpart->hash, ent->ent_guid, sizeof(bpart->hash));
    232 	TAILQ_INSERT_TAIL(&bdev->partitions, bpart, entries);
    233 
    234 	return 0;
    235 }
    236 
    237 static int
    238 efi_block_find_partitions_gpt(struct efi_block_dev *bdev)
    239 {
    240 	struct gpt_hdr hdr;
    241 	struct gpt_ent ent;
    242 	EFI_STATUS status;
    243 	UINT32 sz, entry;
    244 	uint8_t *buf;
    245 
    246 	sz = __MAX(sizeof(hdr), bdev->bio->Media->BlockSize);
    247 	sz = roundup(sz, bdev->bio->Media->BlockSize);
    248 	buf = AllocatePool(sz);
    249 	if (!buf)
    250 		return ENOMEM;
    251 
    252 	status = uefi_call_wrapper(bdev->bio->ReadBlocks, 5, bdev->bio, bdev->media_id, GPT_HDR_BLKNO, sz, buf);
    253 	if (EFI_ERROR(status)) {
    254 		FreePool(buf);
    255 		return EIO;
    256 	}
    257 	memcpy(&hdr, buf, sizeof(hdr));
    258 	FreePool(buf);
    259 
    260 	if (memcmp(hdr.hdr_sig, GPT_HDR_SIG, sizeof(hdr.hdr_sig)) != 0)
    261 		return ENOENT;
    262 	if (le32toh(hdr.hdr_entsz) < sizeof(ent))
    263 		return EINVAL;
    264 
    265 	sz = __MAX(le32toh(hdr.hdr_entsz) * le32toh(hdr.hdr_entries), bdev->bio->Media->BlockSize);
    266 	sz = roundup(sz, bdev->bio->Media->BlockSize);
    267 	buf = AllocatePool(sz);
    268 	if (!buf)
    269 		return ENOMEM;
    270 
    271 	status = uefi_call_wrapper(bdev->bio->ReadBlocks, 5, bdev->bio, bdev->media_id, le64toh(hdr.hdr_lba_table), sz, buf);
    272 	if (EFI_ERROR(status)) {
    273 		FreePool(buf);
    274 		return EIO;
    275 	}
    276 
    277 	for (entry = 0; entry < le32toh(hdr.hdr_entries); entry++) {
    278 		memcpy(&ent, buf + (entry * le32toh(hdr.hdr_entsz)), sizeof(ent));
    279 		efi_block_find_partitions_gpt_entry(bdev, &hdr, &ent, entry);
    280 	}
    281 
    282 	FreePool(buf);
    283 
    284 	return 0;
    285 }
    286 
    287 static int
    288 efi_block_find_partitions(struct efi_block_dev *bdev)
    289 {
    290 	int error;
    291 
    292 	error = efi_block_find_partitions_gpt(bdev);
    293 	if (error)
    294 		error = efi_block_find_partitions_mbr(bdev);
    295 
    296 	return error;
    297 }
    298 
    299 void
    300 efi_block_probe(void)
    301 {
    302 	struct efi_block_dev *bdev;
    303 	struct efi_block_part *bpart;
    304 	EFI_BLOCK_IO *bio;
    305 	EFI_STATUS status;
    306 	uint16_t devindex = 0;
    307 	int depth = -1;
    308 	int n;
    309 
    310 	status = LibLocateHandle(ByProtocol, &BlockIoProtocol, NULL, &efi_nblock, &efi_block);
    311 	if (EFI_ERROR(status))
    312 		return;
    313 
    314 	if (efi_bootdp) {
    315 		depth = efi_device_path_depth(efi_bootdp, MEDIA_DEVICE_PATH);
    316 		if (depth == 0)
    317 			depth = 1;
    318 	}
    319 
    320 	for (n = 0; n < efi_nblock; n++) {
    321 		status = uefi_call_wrapper(BS->HandleProtocol, 3, efi_block[n], &BlockIoProtocol, (void **)&bio);
    322 		if (EFI_ERROR(status) || !bio->Media->MediaPresent)
    323 			continue;
    324 
    325 		if (bio->Media->LogicalPartition)
    326 			continue;
    327 
    328 		bdev = alloc(sizeof(*bdev));
    329 		bdev->index = devindex++;
    330 		bdev->bio = bio;
    331 		bdev->media_id = bio->Media->MediaId;
    332 		bdev->path = DevicePathFromHandle(efi_block[n]);
    333 		TAILQ_INIT(&bdev->partitions);
    334 		TAILQ_INSERT_TAIL(&efi_block_devs, bdev, entries);
    335 
    336 		efi_block_find_partitions(bdev);
    337 
    338 		if (depth > 0 && efi_device_path_ncmp(efi_bootdp, DevicePathFromHandle(efi_block[n]), depth) == 0) {
    339 			TAILQ_FOREACH(bpart, &bdev->partitions, entries) {
    340 				uint8_t fstype = FS_UNUSED;
    341 				switch (bpart->type) {
    342 				case EFI_BLOCK_PART_DISKLABEL:
    343 					fstype = bpart->disklabel.part.p_fstype;
    344 					break;
    345 				case EFI_BLOCK_PART_GPT:
    346 					fstype = bpart->gpt.fstype;
    347 					break;
    348 				}
    349 				if (fstype == FS_BSDFFS) {
    350 					char devname[9];
    351 					snprintf(devname, sizeof(devname), "hd%u%c", bdev->index, bpart->index + 'a');
    352 					set_default_device(devname);
    353 					break;
    354 				}
    355 			}
    356 		}
    357 	}
    358 }
    359 
    360 static void
    361 print_guid(const uint8_t *guid)
    362 {
    363 	const int index[] = { 3, 2, 1, 0, 5, 4, 7, 6, 8, 9, 10, 11, 12, 13, 14, 15 };
    364 	int i;
    365 
    366 	for (i = 0; i < 16; i++) {
    367 		printf("%02x", guid[index[i]]);
    368 		if (i == 3 || i == 5 || i == 7 || i == 9)
    369 			printf("-");
    370 	}
    371 }
    372 
    373 void
    374 efi_block_show(void)
    375 {
    376 	struct efi_block_dev *bdev;
    377 	struct efi_block_part *bpart;
    378 	uint64_t size;
    379 	CHAR16 *path;
    380 
    381 	TAILQ_FOREACH(bdev, &efi_block_devs, entries) {
    382 		printf("hd%u (", bdev->index);
    383 
    384 		/* Size in MB */
    385 		size = ((bdev->bio->Media->LastBlock + 1) * bdev->bio->Media->BlockSize) / (1024 * 1024);
    386 		if (size >= 10000)
    387 			printf("%"PRIu64" GB", size / 1024);
    388 		else
    389 			printf("%"PRIu64" MB", size);
    390 		printf("): ");
    391 
    392 		path = DevicePathToStr(bdev->path);
    393 		Print(L"%s", path);
    394 		FreePool(path);
    395 
    396 		printf("\n");
    397 
    398 		TAILQ_FOREACH(bpart, &bdev->partitions, entries) {
    399 			switch (bpart->type) {
    400 			case EFI_BLOCK_PART_DISKLABEL:
    401 				printf("  hd%u%c (", bdev->index, bpart->index + 'a');
    402 
    403 				/* Size in MB */
    404 				size = ((uint64_t)bpart->disklabel.secsize * bpart->disklabel.part.p_size) / (1024 * 1024);
    405 				if (size >= 10000)
    406 					printf("%"PRIu64" GB", size / 1024);
    407 				else
    408 					printf("%"PRIu64" MB", size);
    409 				printf("): ");
    410 
    411 				printf("%s\n", fstypenames[bpart->disklabel.part.p_fstype]);
    412 				break;
    413 			case EFI_BLOCK_PART_GPT:
    414 				printf("  hd%u%c ", bdev->index, bpart->index + 'a');
    415 
    416 				if (bpart->gpt.ent.ent_name[0] == 0x0000) {
    417 					printf("\"");
    418 					print_guid(bpart->gpt.ent.ent_guid);
    419 					printf("\"");
    420 				} else {
    421 					Print(L"\"%s\"", bpart->gpt.ent.ent_name);
    422 				}
    423 
    424 				/* Size in MB */
    425 				size = (le64toh(bpart->gpt.ent.ent_lba_end) - le64toh(bpart->gpt.ent.ent_lba_start)) * bdev->bio->Media->BlockSize;
    426 				size /= (1024 * 1024);
    427 				if (size >= 10000)
    428 					printf(" (%"PRIu64" GB): ", size / 1024);
    429 				else
    430 					printf(" (%"PRIu64" MB): ", size);
    431 
    432 				printf("%s\n", fstypenames[bpart->gpt.fstype]);
    433 				break;
    434 			default:
    435 				break;
    436 			}
    437 		}
    438 	}
    439 }
    440 
    441 struct efi_block_part *
    442 efi_block_boot_part(void)
    443 {
    444 	return efi_block_booted;
    445 }
    446 
    447 int
    448 efi_block_open(struct open_file *f, ...)
    449 {
    450 	struct efi_block_part *bpart;
    451 	const char *fname;
    452 	char **file;
    453 	char *path;
    454 	va_list ap;
    455 	int rv, n;
    456 
    457 	va_start(ap, f);
    458 	fname = va_arg(ap, const char *);
    459 	file = va_arg(ap, char **);
    460 	va_end(ap);
    461 
    462 	rv = efi_block_parse(fname, &bpart, &path);
    463 	if (rv != 0)
    464 		return rv;
    465 
    466 	for (n = 0; n < ndevs; n++)
    467 		if (strcmp(DEV_NAME(&devsw[n]), "efiblock") == 0) {
    468 			f->f_dev = &devsw[n];
    469 			break;
    470 		}
    471 	if (n == ndevs)
    472 		return ENXIO;
    473 
    474 	f->f_devdata = bpart;
    475 
    476 	*file = path;
    477 
    478 	efi_block_booted = bpart;
    479 
    480 	return 0;
    481 }
    482 
    483 int
    484 efi_block_close(struct open_file *f)
    485 {
    486 	return 0;
    487 }
    488 
    489 int
    490 efi_block_strategy(void *devdata, int rw, daddr_t dblk, size_t size, void *buf, size_t *rsize)
    491 {
    492 	struct efi_block_part *bpart = devdata;
    493 	EFI_STATUS status;
    494 
    495 	if (rw != F_READ)
    496 		return EROFS;
    497 
    498 	switch (bpart->type) {
    499 	case EFI_BLOCK_PART_DISKLABEL:
    500 		if (bpart->bdev->bio->Media->BlockSize != bpart->disklabel.secsize) {
    501 			printf("%s: unsupported block size %d (expected %d)\n", __func__,
    502 			    bpart->bdev->bio->Media->BlockSize, bpart->disklabel.secsize);
    503 			return EIO;
    504 		}
    505 		dblk += bpart->disklabel.part.p_offset;
    506 		break;
    507 	case EFI_BLOCK_PART_GPT:
    508 		if (bpart->bdev->bio->Media->BlockSize != DEV_BSIZE) {
    509 			printf("%s: unsupported block size %d (expected %d)\n", __func__,
    510 			    bpart->bdev->bio->Media->BlockSize, DEV_BSIZE);
    511 			return EIO;
    512 		}
    513 		dblk += le64toh(bpart->gpt.ent.ent_lba_start);
    514 		break;
    515 	default:
    516 		return EINVAL;
    517 	}
    518 
    519 	status = uefi_call_wrapper(bpart->bdev->bio->ReadBlocks, 5, bpart->bdev->bio, bpart->bdev->media_id, dblk, size, buf);
    520 	if (EFI_ERROR(status))
    521 		return EIO;
    522 
    523 	*rsize = size;
    524 
    525 	return 0;
    526 }
    527