xref: /freebsd/sys/contrib/openzfs/lib/libefi/rdwr_efi.c (revision 22649d4dba730d46244fd2dff4fd174903c8379f)
1 // SPDX-License-Identifier: CDDL-1.0
2 /*
3  * This file and its contents are supplied under the terms of the
4  * Common Development and Distribution License ("CDDL"), version 1.0.
5  * You may only use this file in accordance with the terms of version
6  * 1.0 of the CDDL.
7  *
8  * A full copy of the text of the CDDL should have accompanied this
9  * source.  A copy of the CDDL is also available via the Internet at
10  * https://opensource.org/license/CDDL-1.0.
11  */
12 
13 /*
14  * Copyright (c) 2002, 2010, Oracle and/or its affiliates. All rights reserved.
15  * Copyright 2012 Nexenta Systems, Inc.  All rights reserved.
16  * Copyright (c) 2018 by Delphix. All rights reserved.
17  */
18 
19 #include <stdio.h>
20 #include <stdlib.h>
21 #include <errno.h>
22 #include <string.h>
23 #include <unistd.h>
24 #include <uuid/uuid.h>
25 #include <zlib.h>
26 #include <libintl.h>
27 #include <sys/types.h>
28 #include <sys/dkio.h>
29 #include <sys/mhd.h>
30 #include <sys/param.h>
31 #include <sys/dktp/fdisk.h>
32 #include <sys/efi_partition.h>
33 #include <sys/byteorder.h>
34 #include <sys/vdev_disk.h>
35 #include <linux/fs.h>
36 #include <linux/blkpg.h>
37 
38 static struct uuid_to_ptag {
39 	struct uuid	uuid;
40 } conversion_array[] = {
41 	{ EFI_UNUSED },
42 	{ EFI_BOOT },
43 	{ EFI_ROOT },
44 	{ EFI_SWAP },
45 	{ EFI_USR },
46 	{ EFI_BACKUP },
47 	{ EFI_UNUSED },		/* STAND is never used */
48 	{ EFI_VAR },
49 	{ EFI_HOME },
50 	{ EFI_ALTSCTR },
51 	{ EFI_UNUSED },		/* CACHE (cachefs) is never used */
52 	{ EFI_RESERVED },
53 	{ EFI_SYSTEM },
54 	{ EFI_LEGACY_MBR },
55 	{ EFI_SYMC_PUB },
56 	{ EFI_SYMC_CDS },
57 	{ EFI_MSFT_RESV },
58 	{ EFI_DELL_BASIC },
59 	{ EFI_DELL_RAID },
60 	{ EFI_DELL_SWAP },
61 	{ EFI_DELL_LVM },
62 	{ EFI_DELL_RESV },
63 	{ EFI_AAPL_HFS },
64 	{ EFI_AAPL_UFS },
65 	{ EFI_FREEBSD_BOOT },
66 	{ EFI_FREEBSD_SWAP },
67 	{ EFI_FREEBSD_UFS },
68 	{ EFI_FREEBSD_VINUM },
69 	{ EFI_FREEBSD_ZFS },
70 	{ EFI_BIOS_BOOT },
71 	{ EFI_INTC_RS },
72 	{ EFI_SNE_BOOT },
73 	{ EFI_LENOVO_BOOT },
74 	{ EFI_MSFT_LDMM },
75 	{ EFI_MSFT_LDMD },
76 	{ EFI_MSFT_RE },
77 	{ EFI_IBM_GPFS },
78 	{ EFI_MSFT_STORAGESPACES },
79 	{ EFI_HPQ_DATA },
80 	{ EFI_HPQ_SVC },
81 	{ EFI_RHT_DATA },
82 	{ EFI_RHT_HOME },
83 	{ EFI_RHT_SRV },
84 	{ EFI_RHT_DMCRYPT },
85 	{ EFI_RHT_LUKS },
86 	{ EFI_FREEBSD_DISKLABEL },
87 	{ EFI_AAPL_RAID },
88 	{ EFI_AAPL_RAIDOFFLINE },
89 	{ EFI_AAPL_BOOT },
90 	{ EFI_AAPL_LABEL },
91 	{ EFI_AAPL_TVRECOVERY },
92 	{ EFI_AAPL_CORESTORAGE },
93 	{ EFI_NETBSD_SWAP },
94 	{ EFI_NETBSD_FFS },
95 	{ EFI_NETBSD_LFS },
96 	{ EFI_NETBSD_RAID },
97 	{ EFI_NETBSD_CAT },
98 	{ EFI_NETBSD_CRYPT },
99 	{ EFI_GOOG_KERN },
100 	{ EFI_GOOG_ROOT },
101 	{ EFI_GOOG_RESV },
102 	{ EFI_HAIKU_BFS },
103 	{ EFI_MIDNIGHTBSD_BOOT },
104 	{ EFI_MIDNIGHTBSD_DATA },
105 	{ EFI_MIDNIGHTBSD_SWAP },
106 	{ EFI_MIDNIGHTBSD_UFS },
107 	{ EFI_MIDNIGHTBSD_VINUM },
108 	{ EFI_MIDNIGHTBSD_ZFS },
109 	{ EFI_CEPH_JOURNAL },
110 	{ EFI_CEPH_DMCRYPTJOURNAL },
111 	{ EFI_CEPH_OSD },
112 	{ EFI_CEPH_DMCRYPTOSD },
113 	{ EFI_CEPH_CREATE },
114 	{ EFI_CEPH_DMCRYPTCREATE },
115 	{ EFI_OPENBSD_DISKLABEL },
116 	{ EFI_BBRY_QNX },
117 	{ EFI_BELL_PLAN9 },
118 	{ EFI_VMW_KCORE },
119 	{ EFI_VMW_VMFS },
120 	{ EFI_VMW_RESV },
121 	{ EFI_RHT_ROOTX86 },
122 	{ EFI_RHT_ROOTAMD64 },
123 	{ EFI_RHT_ROOTARM },
124 	{ EFI_RHT_ROOTARM64 },
125 	{ EFI_ACRONIS_SECUREZONE },
126 	{ EFI_ONIE_BOOT },
127 	{ EFI_ONIE_CONFIG },
128 	{ EFI_IBM_PPRPBOOT },
129 	{ EFI_FREEDESKTOP_BOOT }
130 };
131 
132 int efi_debug = 0;
133 
134 static int efi_read(int, struct dk_gpt *);
135 
136 /*
137  * Return a 32-bit CRC of the contents of the buffer.  Pre-and-post
138  * one's conditioning will be handled by crc32() internally.
139  */
140 static uint32_t
efi_crc32(const unsigned char * buf,unsigned int size)141 efi_crc32(const unsigned char *buf, unsigned int size)
142 {
143 	uint32_t crc = crc32(0, Z_NULL, 0);
144 
145 	crc = crc32(crc, buf, size);
146 
147 	return (crc);
148 }
149 
150 static int
read_disk_info(int fd,diskaddr_t * capacity,uint_t * lbsize)151 read_disk_info(int fd, diskaddr_t *capacity, uint_t *lbsize)
152 {
153 	int sector_size;
154 	unsigned long long capacity_size;
155 
156 	if (ioctl(fd, BLKSSZGET, &sector_size) < 0)
157 		return (-1);
158 
159 	if (ioctl(fd, BLKGETSIZE64, &capacity_size) < 0)
160 		return (-1);
161 
162 	*lbsize = (uint_t)sector_size;
163 	*capacity = (diskaddr_t)(capacity_size / sector_size);
164 
165 	return (0);
166 }
167 
168 /*
169  * Return back the device name associated with the file descriptor. The
170  * caller is responsible for freeing the memory associated with the
171  * returned string.
172  */
173 static char *
efi_get_devname(int fd)174 efi_get_devname(int fd)
175 {
176 	char path[32];
177 
178 	/*
179 	 * The libefi API only provides the open fd and not the file path.
180 	 * To handle this realpath(3) is used to resolve the block device
181 	 * name from /proc/self/fd/<fd>.
182 	 */
183 	(void) snprintf(path, sizeof (path), "/proc/self/fd/%d", fd);
184 	return (realpath(path, NULL));
185 }
186 
187 static int
efi_get_info(int fd,struct dk_cinfo * dki_info)188 efi_get_info(int fd, struct dk_cinfo *dki_info)
189 {
190 	char *dev_path;
191 	int rval = 0;
192 
193 	memset(dki_info, 0, sizeof (*dki_info));
194 
195 	/*
196 	 * The simplest way to get the partition number under linux is
197 	 * to parse it out of the /dev/<disk><partition> block device name.
198 	 * The kernel creates this using the partition number when it
199 	 * populates /dev/ so it may be trusted.  The tricky bit here is
200 	 * that the naming convention is based on the block device type.
201 	 * So we need to take this in to account when parsing out the
202 	 * partition information.  Aside from the partition number we collect
203 	 * some additional device info.
204 	 */
205 	dev_path = efi_get_devname(fd);
206 	if (dev_path == NULL)
207 		goto error;
208 
209 	if ((strncmp(dev_path, "/dev/sd", 7) == 0)) {
210 		strcpy(dki_info->dki_cname, "sd");
211 		dki_info->dki_ctype = DKC_SCSI_CCS;
212 		rval = sscanf(dev_path, "/dev/%[a-zA-Z]%hu",
213 		    dki_info->dki_dname,
214 		    &dki_info->dki_partition);
215 	} else if ((strncmp(dev_path, "/dev/hd", 7) == 0)) {
216 		strcpy(dki_info->dki_cname, "hd");
217 		dki_info->dki_ctype = DKC_DIRECT;
218 		rval = sscanf(dev_path, "/dev/%[a-zA-Z]%hu",
219 		    dki_info->dki_dname,
220 		    &dki_info->dki_partition);
221 	} else if ((strncmp(dev_path, "/dev/md", 7) == 0)) {
222 		strcpy(dki_info->dki_cname, "pseudo");
223 		dki_info->dki_ctype = DKC_MD;
224 		strcpy(dki_info->dki_dname, "md");
225 		rval = sscanf(dev_path, "/dev/md%[0-9]p%hu",
226 		    dki_info->dki_dname + 2,
227 		    &dki_info->dki_partition);
228 	} else if ((strncmp(dev_path, "/dev/vd", 7) == 0)) {
229 		strcpy(dki_info->dki_cname, "vd");
230 		dki_info->dki_ctype = DKC_MD;
231 		rval = sscanf(dev_path, "/dev/%[a-zA-Z]%hu",
232 		    dki_info->dki_dname,
233 		    &dki_info->dki_partition);
234 	} else if ((strncmp(dev_path, "/dev/xvd", 8) == 0)) {
235 		strcpy(dki_info->dki_cname, "xvd");
236 		dki_info->dki_ctype = DKC_MD;
237 		rval = sscanf(dev_path, "/dev/%[a-zA-Z]%hu",
238 		    dki_info->dki_dname,
239 		    &dki_info->dki_partition);
240 	} else if ((strncmp(dev_path, "/dev/zd", 7) == 0)) {
241 		strcpy(dki_info->dki_cname, "zd");
242 		dki_info->dki_ctype = DKC_MD;
243 		strcpy(dki_info->dki_dname, "zd");
244 		rval = sscanf(dev_path, "/dev/zd%[0-9]p%hu",
245 		    dki_info->dki_dname + 2,
246 		    &dki_info->dki_partition);
247 	} else if ((strncmp(dev_path, "/dev/dm-", 8) == 0)) {
248 		strcpy(dki_info->dki_cname, "pseudo");
249 		dki_info->dki_ctype = DKC_VBD;
250 		strcpy(dki_info->dki_dname, "dm-");
251 		rval = sscanf(dev_path, "/dev/dm-%[0-9]p%hu",
252 		    dki_info->dki_dname + 3,
253 		    &dki_info->dki_partition);
254 	} else if ((strncmp(dev_path, "/dev/ram", 8) == 0)) {
255 		strcpy(dki_info->dki_cname, "pseudo");
256 		dki_info->dki_ctype = DKC_PCMCIA_MEM;
257 		strcpy(dki_info->dki_dname, "ram");
258 		rval = sscanf(dev_path, "/dev/ram%[0-9]p%hu",
259 		    dki_info->dki_dname + 3,
260 		    &dki_info->dki_partition);
261 	} else if ((strncmp(dev_path, "/dev/loop", 9) == 0)) {
262 		strcpy(dki_info->dki_cname, "pseudo");
263 		dki_info->dki_ctype = DKC_VBD;
264 		strcpy(dki_info->dki_dname, "loop");
265 		rval = sscanf(dev_path, "/dev/loop%[0-9]p%hu",
266 		    dki_info->dki_dname + 4,
267 		    &dki_info->dki_partition);
268 	} else if ((strncmp(dev_path, "/dev/nvme", 9) == 0)) {
269 		strcpy(dki_info->dki_cname, "nvme");
270 		dki_info->dki_ctype = DKC_SCSI_CCS;
271 		strcpy(dki_info->dki_dname, "nvme");
272 		(void) sscanf(dev_path, "/dev/nvme%[0-9]",
273 		    dki_info->dki_dname + 4);
274 		size_t controller_length = strlen(
275 		    dki_info->dki_dname);
276 		strcpy(dki_info->dki_dname + controller_length,
277 		    "n");
278 		rval = sscanf(dev_path,
279 		    "/dev/nvme%*[0-9]n%[0-9]p%hu",
280 		    dki_info->dki_dname + controller_length + 1,
281 		    &dki_info->dki_partition);
282 	} else {
283 		strcpy(dki_info->dki_dname, "unknown");
284 		strcpy(dki_info->dki_cname, "unknown");
285 		dki_info->dki_ctype = DKC_UNKNOWN;
286 	}
287 
288 	switch (rval) {
289 	case 0:
290 		errno = EINVAL;
291 		goto error;
292 	case 1:
293 		dki_info->dki_partition = 0;
294 	}
295 
296 	free(dev_path);
297 
298 	return (0);
299 error:
300 	if (efi_debug)
301 		(void) fprintf(stderr, "DKIOCINFO errno 0x%x\n", errno);
302 
303 	switch (errno) {
304 	case EIO:
305 		return (VT_EIO);
306 	case EINVAL:
307 		return (VT_EINVAL);
308 	default:
309 		return (VT_ERROR);
310 	}
311 }
312 
313 /*
314  * the number of blocks the EFI label takes up (round up to nearest
315  * block)
316  */
317 #define	NBLOCKS(p, l)	(1 + ((((p) * (int)sizeof (efi_gpe_t))  + \
318 				((l) - 1)) / (l)))
319 /* number of partitions -- limited by what we can malloc */
320 #define	MAX_PARTS	((4294967295UL - sizeof (struct dk_gpt)) / \
321 			    sizeof (struct dk_part))
322 
323 int
efi_alloc_and_init(int fd,uint32_t nparts,struct dk_gpt ** vtoc)324 efi_alloc_and_init(int fd, uint32_t nparts, struct dk_gpt **vtoc)
325 {
326 	diskaddr_t	capacity = 0;
327 	uint_t		lbsize = 0;
328 	uint_t		nblocks;
329 	size_t		length;
330 	struct dk_gpt	*vptr;
331 	struct uuid	uuid;
332 	struct dk_cinfo	dki_info;
333 
334 	if (read_disk_info(fd, &capacity, &lbsize) != 0)
335 		return (-1);
336 
337 	if (efi_get_info(fd, &dki_info) != 0)
338 		return (-1);
339 
340 	if (dki_info.dki_partition != 0)
341 		return (-1);
342 
343 	if ((dki_info.dki_ctype == DKC_PCMCIA_MEM) ||
344 	    (dki_info.dki_ctype == DKC_VBD) ||
345 	    (dki_info.dki_ctype == DKC_UNKNOWN))
346 		return (-1);
347 
348 	nblocks = NBLOCKS(nparts, lbsize);
349 	if ((nblocks * lbsize) < EFI_MIN_ARRAY_SIZE + lbsize) {
350 		/* 16K plus one block for the GPT */
351 		nblocks = EFI_MIN_ARRAY_SIZE / lbsize + 1;
352 	}
353 
354 	if (nparts > MAX_PARTS) {
355 		if (efi_debug) {
356 			(void) fprintf(stderr,
357 			"the maximum number of partitions supported is %lu\n",
358 			    MAX_PARTS);
359 		}
360 		return (-1);
361 	}
362 
363 	length = sizeof (struct dk_gpt) +
364 	    sizeof (struct dk_part) * (nparts - 1);
365 
366 	vptr = calloc(1, length);
367 	if (vptr == NULL)
368 		return (-1);
369 
370 	*vtoc = vptr;
371 
372 	vptr->efi_version = EFI_VERSION_CURRENT;
373 	vptr->efi_lbasize = lbsize;
374 	vptr->efi_nparts = nparts;
375 	/*
376 	 * add one block here for the PMBR; on disks with a 512 byte
377 	 * block size and 128 or fewer partitions, efi_first_u_lba
378 	 * should work out to "34"
379 	 */
380 	vptr->efi_first_u_lba = nblocks + 1;
381 	vptr->efi_last_lba = capacity - 1;
382 	vptr->efi_altern_lba = capacity -1;
383 	vptr->efi_last_u_lba = vptr->efi_last_lba - nblocks;
384 
385 	(void) uuid_generate((uchar_t *)&uuid);
386 	UUID_LE_CONVERT(vptr->efi_disk_uguid, uuid);
387 	return (0);
388 }
389 
390 /*
391  * Read EFI - return partition number upon success.
392  */
393 int
efi_alloc_and_read(int fd,struct dk_gpt ** vtoc)394 efi_alloc_and_read(int fd, struct dk_gpt **vtoc)
395 {
396 	int			rval;
397 	uint32_t		nparts;
398 	int			length;
399 	struct dk_gpt		*vptr;
400 
401 	/* figure out the number of entries that would fit into 16K */
402 	nparts = EFI_MIN_ARRAY_SIZE / sizeof (efi_gpe_t);
403 	length = (int)(sizeof (struct dk_gpt)) +
404 	    (int)(sizeof (struct dk_part)) * (nparts - 1);
405 	vptr = calloc(1, length);
406 
407 	if (vptr == NULL)
408 		return (VT_ERROR);
409 
410 	vptr->efi_nparts = nparts;
411 	rval = efi_read(fd, vptr);
412 
413 	if ((rval == VT_EINVAL) && vptr->efi_nparts > nparts) {
414 		void *tmp;
415 		length = (int)(sizeof (struct dk_gpt)) +
416 		    (int)(sizeof (struct dk_part)) * (vptr->efi_nparts - 1);
417 		if ((tmp = realloc(vptr, length)) == NULL) {
418 			/* cppcheck-suppress doubleFree */
419 			free(vptr);
420 			*vtoc = NULL;
421 			return (VT_ERROR);
422 		} else {
423 			vptr = tmp;
424 			rval = efi_read(fd, vptr);
425 		}
426 	}
427 
428 	if (rval < 0) {
429 		if (efi_debug) {
430 			(void) fprintf(stderr,
431 			    "read of EFI table failed, rval=%d\n", rval);
432 		}
433 		free(vptr);
434 		*vtoc = NULL;
435 	} else {
436 		*vtoc = vptr;
437 	}
438 
439 	return (rval);
440 }
441 
442 static int
efi_ioctl(int fd,int cmd,dk_efi_t * dk_ioc)443 efi_ioctl(int fd, int cmd, dk_efi_t *dk_ioc)
444 {
445 	void *data = dk_ioc->dki_data;
446 	int error;
447 	diskaddr_t capacity;
448 	uint_t lbsize;
449 
450 	/*
451 	 * When the IO is not being performed in kernel as an ioctl we need
452 	 * to know the sector size so we can seek to the proper byte offset.
453 	 */
454 	if (read_disk_info(fd, &capacity, &lbsize) == -1) {
455 		if (efi_debug)
456 			fprintf(stderr, "unable to read disk info: %d", errno);
457 
458 		errno = EIO;
459 		return (-1);
460 	}
461 
462 	switch (cmd) {
463 	case DKIOCGETEFI:
464 		if (lbsize == 0) {
465 			if (efi_debug)
466 				(void) fprintf(stderr, "DKIOCGETEFI assuming "
467 				    "LBA %d bytes\n", DEV_BSIZE);
468 
469 			lbsize = DEV_BSIZE;
470 		}
471 
472 		error = lseek(fd, dk_ioc->dki_lba * lbsize, SEEK_SET);
473 		if (error == -1) {
474 			if (efi_debug)
475 				(void) fprintf(stderr, "DKIOCGETEFI lseek "
476 				    "error: %d\n", errno);
477 			return (error);
478 		}
479 
480 		error = read(fd, data, dk_ioc->dki_length);
481 		if (error == -1) {
482 			if (efi_debug)
483 				(void) fprintf(stderr, "DKIOCGETEFI read "
484 				    "error: %d\n", errno);
485 			return (error);
486 		}
487 
488 		if (error != dk_ioc->dki_length) {
489 			if (efi_debug)
490 				(void) fprintf(stderr, "DKIOCGETEFI short "
491 				    "read of %d bytes\n", error);
492 			errno = EIO;
493 			return (-1);
494 		}
495 		error = 0;
496 		break;
497 
498 	case DKIOCSETEFI:
499 		if (lbsize == 0) {
500 			if (efi_debug)
501 				(void) fprintf(stderr, "DKIOCSETEFI unknown "
502 				    "LBA size\n");
503 			errno = EIO;
504 			return (-1);
505 		}
506 
507 		error = lseek(fd, dk_ioc->dki_lba * lbsize, SEEK_SET);
508 		if (error == -1) {
509 			if (efi_debug)
510 				(void) fprintf(stderr, "DKIOCSETEFI lseek "
511 				    "error: %d\n", errno);
512 			return (error);
513 		}
514 
515 		error = write(fd, data, dk_ioc->dki_length);
516 		if (error == -1) {
517 			if (efi_debug)
518 				(void) fprintf(stderr, "DKIOCSETEFI write "
519 				    "error: %d\n", errno);
520 			return (error);
521 		}
522 
523 		if (error != dk_ioc->dki_length) {
524 			if (efi_debug)
525 				(void) fprintf(stderr, "DKIOCSETEFI short "
526 				    "write of %d bytes\n", error);
527 			errno = EIO;
528 			return (-1);
529 		}
530 
531 		/* Sync the new EFI table to disk */
532 		error = fsync(fd);
533 		if (error == -1)
534 			return (error);
535 
536 		/* Ensure any local disk cache is also flushed */
537 		if (ioctl(fd, BLKFLSBUF, 0) == -1)
538 			return (error);
539 
540 		error = 0;
541 		break;
542 
543 	default:
544 		if (efi_debug)
545 			(void) fprintf(stderr, "unsupported ioctl()\n");
546 
547 		errno = EIO;
548 		return (-1);
549 	}
550 
551 	return (error);
552 }
553 
554 int
efi_rescan(int fd)555 efi_rescan(int fd)
556 {
557 	int retry = 10;
558 
559 	/* Notify the kernel a devices partition table has been updated */
560 	while (ioctl(fd, BLKRRPART) != 0) {
561 		if ((--retry == 0) || (errno != EBUSY)) {
562 			(void) fprintf(stderr, "the kernel failed to rescan "
563 			    "the partition table: %d\n", errno);
564 			return (-1);
565 		}
566 		usleep(50000);
567 	}
568 
569 	return (0);
570 }
571 
572 static int
check_label(int fd,dk_efi_t * dk_ioc)573 check_label(int fd, dk_efi_t *dk_ioc)
574 {
575 	efi_gpt_t		*efi;
576 	uint_t			crc;
577 
578 	if (efi_ioctl(fd, DKIOCGETEFI, dk_ioc) == -1) {
579 		switch (errno) {
580 		case EIO:
581 			return (VT_EIO);
582 		default:
583 			return (VT_ERROR);
584 		}
585 	}
586 	efi = dk_ioc->dki_data;
587 	if (efi->efi_gpt_Signature != LE_64(EFI_SIGNATURE)) {
588 		if (efi_debug)
589 			(void) fprintf(stderr,
590 			    "Bad EFI signature: 0x%llx != 0x%llx\n",
591 			    (long long)efi->efi_gpt_Signature,
592 			    (long long)LE_64(EFI_SIGNATURE));
593 		return (VT_EINVAL);
594 	}
595 
596 	/*
597 	 * check CRC of the header; the size of the header should
598 	 * never be larger than one block
599 	 */
600 	crc = efi->efi_gpt_HeaderCRC32;
601 	efi->efi_gpt_HeaderCRC32 = 0;
602 	len_t headerSize = (len_t)LE_32(efi->efi_gpt_HeaderSize);
603 
604 	if (headerSize < EFI_MIN_LABEL_SIZE || headerSize > EFI_LABEL_SIZE) {
605 		if (efi_debug)
606 			(void) fprintf(stderr,
607 			    "Invalid EFI HeaderSize %llu.  Assuming %d.\n",
608 			    headerSize, EFI_MIN_LABEL_SIZE);
609 	}
610 
611 	if ((headerSize > dk_ioc->dki_length) ||
612 	    crc != LE_32(efi_crc32((unsigned char *)efi, headerSize))) {
613 		if (efi_debug)
614 			(void) fprintf(stderr,
615 			    "Bad EFI CRC: 0x%x != 0x%x\n",
616 			    crc, LE_32(efi_crc32((unsigned char *)efi,
617 			    headerSize)));
618 		return (VT_EINVAL);
619 	}
620 
621 	return (0);
622 }
623 
624 static int
efi_read(int fd,struct dk_gpt * vtoc)625 efi_read(int fd, struct dk_gpt *vtoc)
626 {
627 	int			i, j;
628 	int			label_len;
629 	int			rval = 0;
630 	int			md_flag = 0;
631 	int			vdc_flag = 0;
632 	diskaddr_t		capacity = 0;
633 	uint_t			lbsize = 0;
634 	struct dk_minfo		disk_info;
635 	dk_efi_t		dk_ioc;
636 	efi_gpt_t		*efi;
637 	efi_gpe_t		*efi_parts;
638 	struct dk_cinfo		dki_info;
639 	uint32_t		user_length;
640 	boolean_t		legacy_label = B_FALSE;
641 
642 	/*
643 	 * get the partition number for this file descriptor.
644 	 */
645 	if ((rval = efi_get_info(fd, &dki_info)) != 0)
646 		return (rval);
647 
648 	if ((strncmp(dki_info.dki_cname, "pseudo", 7) == 0) &&
649 	    (strncmp(dki_info.dki_dname, "md", 3) == 0)) {
650 		md_flag++;
651 	} else if ((strncmp(dki_info.dki_cname, "vdc", 4) == 0) &&
652 	    (strncmp(dki_info.dki_dname, "vdc", 4) == 0)) {
653 		/*
654 		 * The controller and drive name "vdc" (virtual disk client)
655 		 * indicates a LDoms virtual disk.
656 		 */
657 		vdc_flag++;
658 	}
659 
660 	/* get the LBA size */
661 	if (read_disk_info(fd, &capacity, &lbsize) == -1) {
662 		if (efi_debug) {
663 			(void) fprintf(stderr,
664 			    "unable to read disk info: %d",
665 			    errno);
666 		}
667 		return (VT_EINVAL);
668 	}
669 
670 	disk_info.dki_lbsize = lbsize;
671 	disk_info.dki_capacity = capacity;
672 
673 	if (disk_info.dki_lbsize == 0) {
674 		if (efi_debug) {
675 			(void) fprintf(stderr,
676 			    "efi_read: assuming LBA 512 bytes\n");
677 		}
678 		disk_info.dki_lbsize = DEV_BSIZE;
679 	}
680 	/*
681 	 * Read the EFI GPT to figure out how many partitions we need
682 	 * to deal with.
683 	 */
684 	dk_ioc.dki_lba = 1;
685 	if (NBLOCKS(vtoc->efi_nparts, disk_info.dki_lbsize) < 34) {
686 		label_len = EFI_MIN_ARRAY_SIZE + disk_info.dki_lbsize;
687 	} else {
688 		label_len = vtoc->efi_nparts * (int)(sizeof (efi_gpe_t)) +
689 		    disk_info.dki_lbsize;
690 		if (label_len % disk_info.dki_lbsize) {
691 			/* pad to physical sector size */
692 			label_len += disk_info.dki_lbsize;
693 			label_len &= ~(disk_info.dki_lbsize - 1);
694 		}
695 	}
696 
697 	if (posix_memalign((void **)&dk_ioc.dki_data,
698 	    disk_info.dki_lbsize, label_len))
699 		return (VT_ERROR);
700 
701 	memset(dk_ioc.dki_data, 0, label_len);
702 	dk_ioc.dki_length = disk_info.dki_lbsize;
703 	user_length = vtoc->efi_nparts;
704 	efi = dk_ioc.dki_data;
705 	if (md_flag) {
706 		dk_ioc.dki_length = label_len;
707 		if (efi_ioctl(fd, DKIOCGETEFI, &dk_ioc) == -1) {
708 			switch (errno) {
709 			case EIO:
710 				return (VT_EIO);
711 			default:
712 				return (VT_ERROR);
713 			}
714 		}
715 	} else if ((rval = check_label(fd, &dk_ioc)) == VT_EINVAL) {
716 		/*
717 		 * No valid label here; try the alternate. Note that here
718 		 * we just read GPT header and save it into dk_ioc.data,
719 		 * Later, we will read GUID partition entry array if we
720 		 * can get valid GPT header.
721 		 */
722 
723 		/*
724 		 * This is a workaround for legacy systems. In the past, the
725 		 * last sector of SCSI disk was invisible on x86 platform. At
726 		 * that time, backup label was saved on the next to the last
727 		 * sector. It is possible for users to move a disk from previous
728 		 * solaris system to present system. Here, we attempt to search
729 		 * legacy backup EFI label first.
730 		 */
731 		dk_ioc.dki_lba = disk_info.dki_capacity - 2;
732 		dk_ioc.dki_length = disk_info.dki_lbsize;
733 		rval = check_label(fd, &dk_ioc);
734 		if (rval == VT_EINVAL) {
735 			/*
736 			 * we didn't find legacy backup EFI label, try to
737 			 * search backup EFI label in the last block.
738 			 */
739 			dk_ioc.dki_lba = disk_info.dki_capacity - 1;
740 			dk_ioc.dki_length = disk_info.dki_lbsize;
741 			rval = check_label(fd, &dk_ioc);
742 			if (rval == 0) {
743 				legacy_label = B_TRUE;
744 				if (efi_debug)
745 					(void) fprintf(stderr,
746 					    "efi_read: primary label corrupt; "
747 					    "using EFI backup label located on"
748 					    " the last block\n");
749 			}
750 		} else {
751 			if ((efi_debug) && (rval == 0))
752 				(void) fprintf(stderr, "efi_read: primary label"
753 				    " corrupt; using legacy EFI backup label "
754 				    " located on the next to last block\n");
755 		}
756 
757 		if (rval == 0) {
758 			dk_ioc.dki_lba = LE_64(efi->efi_gpt_PartitionEntryLBA);
759 			vtoc->efi_flags |= EFI_GPT_PRIMARY_CORRUPT;
760 			vtoc->efi_nparts =
761 			    LE_32(efi->efi_gpt_NumberOfPartitionEntries);
762 			/*
763 			 * Partition tables are between backup GPT header
764 			 * table and ParitionEntryLBA (the starting LBA of
765 			 * the GUID partition entries array). Now that we
766 			 * already got valid GPT header and saved it in
767 			 * dk_ioc.dki_data, we try to get GUID partition
768 			 * entry array here.
769 			 */
770 			/* LINTED */
771 			dk_ioc.dki_data = (efi_gpt_t *)((char *)dk_ioc.dki_data
772 			    + disk_info.dki_lbsize);
773 			if (legacy_label)
774 				dk_ioc.dki_length = disk_info.dki_capacity - 1 -
775 				    dk_ioc.dki_lba;
776 			else
777 				dk_ioc.dki_length = disk_info.dki_capacity - 2 -
778 				    dk_ioc.dki_lba;
779 			dk_ioc.dki_length *= disk_info.dki_lbsize;
780 			if (dk_ioc.dki_length >
781 			    ((len_t)label_len - sizeof (*dk_ioc.dki_data))) {
782 				rval = VT_EINVAL;
783 			} else {
784 				/*
785 				 * read GUID partition entry array
786 				 */
787 				rval = efi_ioctl(fd, DKIOCGETEFI, &dk_ioc);
788 			}
789 		}
790 
791 	} else if (rval == 0) {
792 
793 		dk_ioc.dki_lba = LE_64(efi->efi_gpt_PartitionEntryLBA);
794 		/* LINTED */
795 		dk_ioc.dki_data = (efi_gpt_t *)((char *)dk_ioc.dki_data
796 		    + disk_info.dki_lbsize);
797 		dk_ioc.dki_length = label_len - disk_info.dki_lbsize;
798 		rval = efi_ioctl(fd, DKIOCGETEFI, &dk_ioc);
799 
800 	} else if (vdc_flag && rval == VT_ERROR && errno == EINVAL) {
801 		/*
802 		 * When the device is a LDoms virtual disk, the DKIOCGETEFI
803 		 * ioctl can fail with EINVAL if the virtual disk backend
804 		 * is a ZFS volume serviced by a domain running an old version
805 		 * of Solaris. This is because the DKIOCGETEFI ioctl was
806 		 * initially incorrectly implemented for a ZFS volume and it
807 		 * expected the GPT and GPE to be retrieved with a single ioctl.
808 		 * So we try to read the GPT and the GPE using that old style
809 		 * ioctl.
810 		 */
811 		dk_ioc.dki_lba = 1;
812 		dk_ioc.dki_length = label_len;
813 		rval = check_label(fd, &dk_ioc);
814 	}
815 
816 	if (rval < 0) {
817 		free(efi);
818 		return (rval);
819 	}
820 
821 	/* LINTED -- always longlong aligned */
822 	efi_parts = (efi_gpe_t *)(((char *)efi) + disk_info.dki_lbsize);
823 
824 	/*
825 	 * Assemble this into a "dk_gpt" struct for easier
826 	 * digestibility by applications.
827 	 */
828 	vtoc->efi_version = LE_32(efi->efi_gpt_Revision);
829 	vtoc->efi_nparts = LE_32(efi->efi_gpt_NumberOfPartitionEntries);
830 	vtoc->efi_part_size = LE_32(efi->efi_gpt_SizeOfPartitionEntry);
831 	vtoc->efi_lbasize = disk_info.dki_lbsize;
832 	vtoc->efi_last_lba = disk_info.dki_capacity - 1;
833 	vtoc->efi_first_u_lba = LE_64(efi->efi_gpt_FirstUsableLBA);
834 	vtoc->efi_last_u_lba = LE_64(efi->efi_gpt_LastUsableLBA);
835 	vtoc->efi_altern_lba = LE_64(efi->efi_gpt_AlternateLBA);
836 	UUID_LE_CONVERT(vtoc->efi_disk_uguid, efi->efi_gpt_DiskGUID);
837 
838 	/*
839 	 * If the array the user passed in is too small, set the length
840 	 * to what it needs to be and return
841 	 */
842 	if (user_length < vtoc->efi_nparts) {
843 		return (VT_EINVAL);
844 	}
845 
846 	for (i = 0; i < vtoc->efi_nparts; i++) {
847 		UUID_LE_CONVERT(vtoc->efi_parts[i].p_guid,
848 		    efi_parts[i].efi_gpe_PartitionTypeGUID);
849 
850 		for (j = 0;
851 		    j < sizeof (conversion_array)
852 		    / sizeof (struct uuid_to_ptag); j++) {
853 
854 			if (memcmp(&vtoc->efi_parts[i].p_guid,
855 			    &conversion_array[j].uuid,
856 			    sizeof (struct uuid)) == 0) {
857 				vtoc->efi_parts[i].p_tag = j;
858 				break;
859 			}
860 		}
861 		if (vtoc->efi_parts[i].p_tag == V_UNASSIGNED)
862 			continue;
863 		vtoc->efi_parts[i].p_flag =
864 		    LE_16(efi_parts[i].efi_gpe_Attributes.PartitionAttrs);
865 		vtoc->efi_parts[i].p_start =
866 		    LE_64(efi_parts[i].efi_gpe_StartingLBA);
867 		vtoc->efi_parts[i].p_size =
868 		    LE_64(efi_parts[i].efi_gpe_EndingLBA) -
869 		    vtoc->efi_parts[i].p_start + 1;
870 		for (j = 0; j < EFI_PART_NAME_LEN; j++) {
871 			vtoc->efi_parts[i].p_name[j] =
872 			    (uchar_t)LE_16(
873 			    efi_parts[i].efi_gpe_PartitionName[j]);
874 		}
875 
876 		UUID_LE_CONVERT(vtoc->efi_parts[i].p_uguid,
877 		    efi_parts[i].efi_gpe_UniquePartitionGUID);
878 	}
879 	free(efi);
880 
881 	return (dki_info.dki_partition);
882 }
883 
884 /* writes a "protective" MBR */
885 static int
write_pmbr(int fd,struct dk_gpt * vtoc)886 write_pmbr(int fd, struct dk_gpt *vtoc)
887 {
888 	dk_efi_t	dk_ioc;
889 	struct mboot	mb;
890 	uchar_t		*cp;
891 	diskaddr_t	size_in_lba;
892 	uchar_t		*buf;
893 	int		len;
894 
895 	len = (vtoc->efi_lbasize == 0) ? sizeof (mb) : vtoc->efi_lbasize;
896 	if (posix_memalign((void **)&buf, len, len))
897 		return (VT_ERROR);
898 
899 	/*
900 	 * Preserve any boot code and disk signature if the first block is
901 	 * already an MBR.
902 	 */
903 	memset(buf, 0, len);
904 	dk_ioc.dki_lba = 0;
905 	dk_ioc.dki_length = len;
906 	/* LINTED -- always longlong aligned */
907 	dk_ioc.dki_data = (efi_gpt_t *)buf;
908 	if (efi_ioctl(fd, DKIOCGETEFI, &dk_ioc) == -1) {
909 		memset(&mb, 0, sizeof (mb));
910 		mb.signature = LE_16(MBB_MAGIC);
911 	} else {
912 		(void) memcpy(&mb, buf, sizeof (mb));
913 		if (mb.signature != LE_16(MBB_MAGIC)) {
914 			memset(&mb, 0, sizeof (mb));
915 			mb.signature = LE_16(MBB_MAGIC);
916 		}
917 	}
918 
919 	memset(&mb.parts, 0, sizeof (mb.parts));
920 	cp = (uchar_t *)&mb.parts[0];
921 	/* bootable or not */
922 	*cp++ = 0;
923 	/* beginning CHS; 0xffffff if not representable */
924 	*cp++ = 0xff;
925 	*cp++ = 0xff;
926 	*cp++ = 0xff;
927 	/* OS type */
928 	*cp++ = EFI_PMBR;
929 	/* ending CHS; 0xffffff if not representable */
930 	*cp++ = 0xff;
931 	*cp++ = 0xff;
932 	*cp++ = 0xff;
933 	/* starting LBA: 1 (little endian format) by EFI definition */
934 	*cp++ = 0x01;
935 	*cp++ = 0x00;
936 	*cp++ = 0x00;
937 	*cp++ = 0x00;
938 	/* ending LBA: last block on the disk (little endian format) */
939 	size_in_lba = vtoc->efi_last_lba;
940 	if (size_in_lba < 0xffffffff) {
941 		*cp++ = (size_in_lba & 0x000000ff);
942 		*cp++ = (size_in_lba & 0x0000ff00) >> 8;
943 		*cp++ = (size_in_lba & 0x00ff0000) >> 16;
944 		*cp++ = (size_in_lba & 0xff000000) >> 24;
945 	} else {
946 		*cp++ = 0xff;
947 		*cp++ = 0xff;
948 		*cp++ = 0xff;
949 		*cp++ = 0xff;
950 	}
951 
952 	(void) memcpy(buf, &mb, sizeof (mb));
953 	/* LINTED -- always longlong aligned */
954 	dk_ioc.dki_data = (efi_gpt_t *)buf;
955 	dk_ioc.dki_lba = 0;
956 	dk_ioc.dki_length = len;
957 	if (efi_ioctl(fd, DKIOCSETEFI, &dk_ioc) == -1) {
958 		free(buf);
959 		switch (errno) {
960 		case EIO:
961 			return (VT_EIO);
962 		case EINVAL:
963 			return (VT_EINVAL);
964 		default:
965 			return (VT_ERROR);
966 		}
967 	}
968 	free(buf);
969 	return (0);
970 }
971 
972 /* make sure the user specified something reasonable */
973 static int
check_input(struct dk_gpt * vtoc)974 check_input(struct dk_gpt *vtoc)
975 {
976 	int			resv_part = -1;
977 	int			i, j;
978 	diskaddr_t		istart, jstart, isize, jsize, endsect;
979 
980 	/*
981 	 * Sanity-check the input (make sure no partitions overlap)
982 	 */
983 	for (i = 0; i < vtoc->efi_nparts; i++) {
984 		/* It can't be unassigned and have an actual size */
985 		if ((vtoc->efi_parts[i].p_tag == V_UNASSIGNED) &&
986 		    (vtoc->efi_parts[i].p_size != 0)) {
987 			if (efi_debug) {
988 				(void) fprintf(stderr, "partition %d is "
989 				    "\"unassigned\" but has a size of %llu",
990 				    i, vtoc->efi_parts[i].p_size);
991 			}
992 			return (VT_EINVAL);
993 		}
994 		if (vtoc->efi_parts[i].p_tag == V_UNASSIGNED) {
995 			if (uuid_is_null((uchar_t *)&vtoc->efi_parts[i].p_guid))
996 				continue;
997 			/* we have encountered an unknown uuid */
998 			vtoc->efi_parts[i].p_tag = 0xff;
999 		}
1000 		if (vtoc->efi_parts[i].p_tag == V_RESERVED) {
1001 			if (resv_part != -1) {
1002 				if (efi_debug) {
1003 					(void) fprintf(stderr, "found "
1004 					    "duplicate reserved partition "
1005 					    "at %d\n", i);
1006 				}
1007 				return (VT_EINVAL);
1008 			}
1009 			resv_part = i;
1010 		}
1011 		if ((vtoc->efi_parts[i].p_start < vtoc->efi_first_u_lba) ||
1012 		    (vtoc->efi_parts[i].p_start > vtoc->efi_last_u_lba)) {
1013 			if (efi_debug) {
1014 				(void) fprintf(stderr,
1015 				    "Partition %d starts at %llu.  ",
1016 				    i,
1017 				    vtoc->efi_parts[i].p_start);
1018 				(void) fprintf(stderr,
1019 				    "It must be between %llu and %llu.\n",
1020 				    vtoc->efi_first_u_lba,
1021 				    vtoc->efi_last_u_lba);
1022 			}
1023 			return (VT_EINVAL);
1024 		}
1025 		if ((vtoc->efi_parts[i].p_start +
1026 		    vtoc->efi_parts[i].p_size <
1027 		    vtoc->efi_first_u_lba) ||
1028 		    (vtoc->efi_parts[i].p_start +
1029 		    vtoc->efi_parts[i].p_size >
1030 		    vtoc->efi_last_u_lba + 1)) {
1031 			if (efi_debug) {
1032 				(void) fprintf(stderr,
1033 				    "Partition %d ends at %llu.  ",
1034 				    i,
1035 				    vtoc->efi_parts[i].p_start +
1036 				    vtoc->efi_parts[i].p_size);
1037 				(void) fprintf(stderr,
1038 				    "It must be between %llu and %llu.\n",
1039 				    vtoc->efi_first_u_lba,
1040 				    vtoc->efi_last_u_lba);
1041 			}
1042 			return (VT_EINVAL);
1043 		}
1044 
1045 		for (j = 0; j < vtoc->efi_nparts; j++) {
1046 			isize = vtoc->efi_parts[i].p_size;
1047 			jsize = vtoc->efi_parts[j].p_size;
1048 			istart = vtoc->efi_parts[i].p_start;
1049 			jstart = vtoc->efi_parts[j].p_start;
1050 			if ((i != j) && (isize != 0) && (jsize != 0)) {
1051 				endsect = jstart + jsize -1;
1052 				if ((jstart <= istart) &&
1053 				    (istart <= endsect)) {
1054 					if (efi_debug) {
1055 						(void) fprintf(stderr,
1056 						    "Partition %d overlaps "
1057 						    "partition %d.", i, j);
1058 					}
1059 					return (VT_EINVAL);
1060 				}
1061 			}
1062 		}
1063 	}
1064 	/* just a warning for now */
1065 	if ((resv_part == -1) && efi_debug) {
1066 		(void) fprintf(stderr,
1067 		    "no reserved partition found\n");
1068 	}
1069 	return (0);
1070 }
1071 
1072 static int
call_blkpg_ioctl(int fd,int command,diskaddr_t start,diskaddr_t size,uint_t pno)1073 call_blkpg_ioctl(int fd, int command, diskaddr_t start,
1074     diskaddr_t size, uint_t pno)
1075 {
1076 	struct blkpg_ioctl_arg ioctl_arg;
1077 	struct blkpg_partition  linux_part;
1078 	memset(&linux_part, 0, sizeof (linux_part));
1079 
1080 	char *path = efi_get_devname(fd);
1081 	if (path == NULL) {
1082 		(void) fprintf(stderr, "failed to retrieve device name\n");
1083 		return (VT_EINVAL);
1084 	}
1085 
1086 	linux_part.start = start;
1087 	linux_part.length = size;
1088 	linux_part.pno = pno;
1089 	snprintf(linux_part.devname, BLKPG_DEVNAMELTH - 1, "%s%u", path, pno);
1090 	linux_part.devname[BLKPG_DEVNAMELTH - 1] = '\0';
1091 	free(path);
1092 
1093 	ioctl_arg.op = command;
1094 	ioctl_arg.flags = 0;
1095 	ioctl_arg.datalen = sizeof (struct blkpg_partition);
1096 	ioctl_arg.data = &linux_part;
1097 
1098 	return (ioctl(fd, BLKPG, &ioctl_arg));
1099 }
1100 
1101 /*
1102  * add all the unallocated space to the current label
1103  */
1104 int
efi_use_whole_disk(int fd)1105 efi_use_whole_disk(int fd)
1106 {
1107 	struct dk_gpt *efi_label = NULL;
1108 	int rval;
1109 	int i;
1110 	uint_t resv_index = 0, data_index = 0;
1111 	diskaddr_t resv_start = 0, data_start = 0;
1112 	diskaddr_t data_size, limit, difference;
1113 	boolean_t sync_needed = B_FALSE;
1114 	uint_t nblocks;
1115 
1116 	rval = efi_alloc_and_read(fd, &efi_label);
1117 	if (rval < 0) {
1118 		if (efi_label != NULL)
1119 			efi_free(efi_label);
1120 		return (rval);
1121 	}
1122 
1123 	/*
1124 	 * Find the last physically non-zero partition.
1125 	 * This should be the reserved partition.
1126 	 */
1127 	for (i = 0; i < efi_label->efi_nparts; i ++) {
1128 		if (resv_start < efi_label->efi_parts[i].p_start) {
1129 			resv_start = efi_label->efi_parts[i].p_start;
1130 			resv_index = i;
1131 		}
1132 	}
1133 
1134 	/*
1135 	 * Find the last physically non-zero partition before that.
1136 	 * This is the data partition.
1137 	 */
1138 	for (i = 0; i < resv_index; i ++) {
1139 		if (data_start < efi_label->efi_parts[i].p_start) {
1140 			data_start = efi_label->efi_parts[i].p_start;
1141 			data_index = i;
1142 		}
1143 	}
1144 	data_size = efi_label->efi_parts[data_index].p_size;
1145 
1146 	/*
1147 	 * See the "efi_alloc_and_init" function for more information
1148 	 * about where this "nblocks" value comes from.
1149 	 */
1150 	nblocks = efi_label->efi_first_u_lba - 1;
1151 
1152 	/*
1153 	 * Determine if the EFI label is out of sync. We check that:
1154 	 *
1155 	 * 1. the data partition ends at the limit we set, and
1156 	 * 2. the reserved partition starts at the limit we set.
1157 	 *
1158 	 * If either of these conditions is not met, then we need to
1159 	 * resync the EFI label.
1160 	 *
1161 	 * The limit is the last usable LBA, determined by the last LBA
1162 	 * and the first usable LBA fields on the EFI label of the disk
1163 	 * (see the lines directly above). Additionally, we factor in
1164 	 * EFI_MIN_RESV_SIZE (per its use in "zpool_label_disk") and
1165 	 * P2ALIGN it to ensure the partition boundaries are aligned
1166 	 * (for performance reasons). The alignment should match the
1167 	 * alignment used by the "zpool_label_disk" function.
1168 	 */
1169 	limit = P2ALIGN_TYPED(efi_label->efi_last_lba - nblocks -
1170 	    EFI_MIN_RESV_SIZE, PARTITION_END_ALIGNMENT, diskaddr_t);
1171 	if (data_start + data_size != limit || resv_start != limit)
1172 		sync_needed = B_TRUE;
1173 
1174 	if (efi_debug && sync_needed)
1175 		(void) fprintf(stderr, "efi_use_whole_disk: sync needed\n");
1176 
1177 	/*
1178 	 * If alter_lba is 1, we are using the backup label.
1179 	 * Since we can locate the backup label by disk capacity,
1180 	 * there must be no unallocated space.
1181 	 */
1182 	if ((efi_label->efi_altern_lba == 1) || (efi_label->efi_altern_lba
1183 	    >= efi_label->efi_last_lba && !sync_needed)) {
1184 		if (efi_debug) {
1185 			(void) fprintf(stderr,
1186 			    "efi_use_whole_disk: requested space not found\n");
1187 		}
1188 		efi_free(efi_label);
1189 		return (VT_ENOSPC);
1190 	}
1191 
1192 	/*
1193 	 * Verify that we've found the reserved partition by checking
1194 	 * that it looks the way it did when we created it in zpool_label_disk.
1195 	 * If we've found the incorrect partition, then we know that this
1196 	 * device was reformatted and no longer is solely used by ZFS.
1197 	 */
1198 	if ((efi_label->efi_parts[resv_index].p_size != EFI_MIN_RESV_SIZE) ||
1199 	    (efi_label->efi_parts[resv_index].p_tag != V_RESERVED) ||
1200 	    (resv_index != 8)) {
1201 		if (efi_debug) {
1202 			(void) fprintf(stderr,
1203 			    "efi_use_whole_disk: wholedisk not available\n");
1204 		}
1205 		efi_free(efi_label);
1206 		return (VT_ENOSPC);
1207 	}
1208 
1209 	if (data_start + data_size != resv_start) {
1210 		if (efi_debug) {
1211 			(void) fprintf(stderr,
1212 			    "efi_use_whole_disk: "
1213 			    "data_start (%lli) + "
1214 			    "data_size (%lli) != "
1215 			    "resv_start (%lli)\n",
1216 			    data_start, data_size, resv_start);
1217 		}
1218 
1219 		return (VT_EINVAL);
1220 	}
1221 
1222 	if (limit < resv_start) {
1223 		if (efi_debug) {
1224 			(void) fprintf(stderr,
1225 			    "efi_use_whole_disk: "
1226 			    "limit (%lli) < resv_start (%lli)\n",
1227 			    limit, resv_start);
1228 		}
1229 
1230 		return (VT_EINVAL);
1231 	}
1232 
1233 	difference = limit - resv_start;
1234 
1235 	if (efi_debug)
1236 		(void) fprintf(stderr,
1237 		    "efi_use_whole_disk: difference is %lli\n", difference);
1238 
1239 	/*
1240 	 * Move the reserved partition. There is currently no data in
1241 	 * here except fabricated devids (which get generated via
1242 	 * efi_write()). So there is no need to copy data.
1243 	 */
1244 	efi_label->efi_parts[data_index].p_size += difference;
1245 	efi_label->efi_parts[resv_index].p_start += difference;
1246 	efi_label->efi_last_u_lba = efi_label->efi_last_lba - nblocks;
1247 
1248 	/*
1249 	 * Rescanning the partition table in the kernel can result
1250 	 * in the device links to be removed (see comment in vdev_disk_open).
1251 	 * If BLKPG_RESIZE_PARTITION is available, then we can resize
1252 	 * the partition table online and avoid having to remove the device
1253 	 * links used by the pool. This provides a very deterministic
1254 	 * approach to resizing devices and does not require any
1255 	 * loops waiting for devices to reappear.
1256 	 */
1257 #ifdef BLKPG_RESIZE_PARTITION
1258 	/*
1259 	 * Delete the reserved partition since we're about to expand
1260 	 * the data partition and it would overlap with the reserved
1261 	 * partition.
1262 	 * NOTE: The starting index for the ioctl is 1 while for the
1263 	 * EFI partitions it's 0. For that reason we have to add one
1264 	 * whenever we make an ioctl call.
1265 	 */
1266 	rval = call_blkpg_ioctl(fd, BLKPG_DEL_PARTITION, 0, 0, resv_index + 1);
1267 	if (rval != 0)
1268 		goto out;
1269 
1270 	/*
1271 	 * Expand the data partition
1272 	 */
1273 	rval = call_blkpg_ioctl(fd, BLKPG_RESIZE_PARTITION,
1274 	    efi_label->efi_parts[data_index].p_start * efi_label->efi_lbasize,
1275 	    efi_label->efi_parts[data_index].p_size * efi_label->efi_lbasize,
1276 	    data_index + 1);
1277 	if (rval != 0) {
1278 		(void) fprintf(stderr, "Unable to resize data "
1279 		    "partition:  %d\n", rval);
1280 		/*
1281 		 * Since we failed to resize, we need to reset the start
1282 		 * of the reserve partition and re-create it.
1283 		 */
1284 		efi_label->efi_parts[resv_index].p_start -= difference;
1285 	}
1286 
1287 	/*
1288 	 * Re-add the reserved partition. If we've expanded the data partition
1289 	 * then we'll move the reserve partition to the end of the data
1290 	 * partition. Otherwise, we'll recreate the partition in its original
1291 	 * location. Note that we do this as best-effort and ignore any
1292 	 * errors that may arise here. This will ensure that we finish writing
1293 	 * the EFI label.
1294 	 */
1295 	(void) call_blkpg_ioctl(fd, BLKPG_ADD_PARTITION,
1296 	    efi_label->efi_parts[resv_index].p_start * efi_label->efi_lbasize,
1297 	    efi_label->efi_parts[resv_index].p_size * efi_label->efi_lbasize,
1298 	    resv_index + 1);
1299 #endif
1300 
1301 	/*
1302 	 * We're now ready to write the EFI label.
1303 	 */
1304 	if (rval == 0) {
1305 		rval = efi_write(fd, efi_label);
1306 		if (rval < 0 && efi_debug) {
1307 			(void) fprintf(stderr, "efi_use_whole_disk:fail "
1308 			    "to write label, rval=%d\n", rval);
1309 		}
1310 	}
1311 
1312 out:
1313 	efi_free(efi_label);
1314 	return (rval);
1315 }
1316 
1317 /*
1318  * write EFI label and backup label
1319  */
1320 int
efi_write(int fd,struct dk_gpt * vtoc)1321 efi_write(int fd, struct dk_gpt *vtoc)
1322 {
1323 	dk_efi_t		dk_ioc;
1324 	efi_gpt_t		*efi;
1325 	efi_gpe_t		*efi_parts;
1326 	int			i, j;
1327 	struct dk_cinfo		dki_info;
1328 	int			rval;
1329 	int			md_flag = 0;
1330 	int			nblocks;
1331 	diskaddr_t		lba_backup_gpt_hdr;
1332 
1333 	if ((rval = efi_get_info(fd, &dki_info)) != 0)
1334 		return (rval);
1335 
1336 	/* check if we are dealing with a metadevice */
1337 	if ((strncmp(dki_info.dki_cname, "pseudo", 7) == 0) &&
1338 	    (strncmp(dki_info.dki_dname, "md", 3) == 0)) {
1339 		md_flag = 1;
1340 	}
1341 
1342 	if (check_input(vtoc)) {
1343 		/*
1344 		 * not valid; if it's a metadevice just pass it down
1345 		 * because SVM will do its own checking
1346 		 */
1347 		if (md_flag == 0) {
1348 			return (VT_EINVAL);
1349 		}
1350 	}
1351 
1352 	dk_ioc.dki_lba = 1;
1353 	if (NBLOCKS(vtoc->efi_nparts, vtoc->efi_lbasize) < 34) {
1354 		dk_ioc.dki_length = EFI_MIN_ARRAY_SIZE + vtoc->efi_lbasize;
1355 	} else {
1356 		dk_ioc.dki_length = (len_t)NBLOCKS(vtoc->efi_nparts,
1357 		    vtoc->efi_lbasize) *
1358 		    vtoc->efi_lbasize;
1359 	}
1360 
1361 	/*
1362 	 * the number of blocks occupied by GUID partition entry array
1363 	 */
1364 	nblocks = dk_ioc.dki_length / vtoc->efi_lbasize - 1;
1365 
1366 	/*
1367 	 * Backup GPT header is located on the block after GUID
1368 	 * partition entry array. Here, we calculate the address
1369 	 * for backup GPT header.
1370 	 */
1371 	lba_backup_gpt_hdr = vtoc->efi_last_u_lba + 1 + nblocks;
1372 	if (posix_memalign((void **)&dk_ioc.dki_data,
1373 	    vtoc->efi_lbasize, dk_ioc.dki_length))
1374 		return (VT_ERROR);
1375 
1376 	memset(dk_ioc.dki_data, 0, dk_ioc.dki_length);
1377 	efi = dk_ioc.dki_data;
1378 
1379 	/* stuff user's input into EFI struct */
1380 	efi->efi_gpt_Signature = LE_64(EFI_SIGNATURE);
1381 	efi->efi_gpt_Revision = LE_32(vtoc->efi_version); /* 0x02000100 */
1382 	efi->efi_gpt_HeaderSize = LE_32(sizeof (struct efi_gpt) - LEN_EFI_PAD);
1383 	efi->efi_gpt_Reserved1 = 0;
1384 	efi->efi_gpt_MyLBA = LE_64(1ULL);
1385 	efi->efi_gpt_AlternateLBA = LE_64(lba_backup_gpt_hdr);
1386 	efi->efi_gpt_FirstUsableLBA = LE_64(vtoc->efi_first_u_lba);
1387 	efi->efi_gpt_LastUsableLBA = LE_64(vtoc->efi_last_u_lba);
1388 	efi->efi_gpt_PartitionEntryLBA = LE_64(2ULL);
1389 	efi->efi_gpt_NumberOfPartitionEntries = LE_32(vtoc->efi_nparts);
1390 	efi->efi_gpt_SizeOfPartitionEntry = LE_32(sizeof (struct efi_gpe));
1391 	UUID_LE_CONVERT(efi->efi_gpt_DiskGUID, vtoc->efi_disk_uguid);
1392 
1393 	/* LINTED -- always longlong aligned */
1394 	efi_parts = (efi_gpe_t *)((char *)dk_ioc.dki_data + vtoc->efi_lbasize);
1395 
1396 	for (i = 0; i < vtoc->efi_nparts; i++) {
1397 		for (j = 0;
1398 		    j < sizeof (conversion_array) /
1399 		    sizeof (struct uuid_to_ptag); j++) {
1400 
1401 			if (vtoc->efi_parts[i].p_tag == j) {
1402 				UUID_LE_CONVERT(
1403 				    efi_parts[i].efi_gpe_PartitionTypeGUID,
1404 				    conversion_array[j].uuid);
1405 				break;
1406 			}
1407 		}
1408 
1409 		if (j == sizeof (conversion_array) /
1410 		    sizeof (struct uuid_to_ptag)) {
1411 			/*
1412 			 * If we didn't have a matching uuid match, bail here.
1413 			 * Don't write a label with unknown uuid.
1414 			 */
1415 			if (efi_debug) {
1416 				(void) fprintf(stderr,
1417 				    "Unknown uuid for p_tag %d\n",
1418 				    vtoc->efi_parts[i].p_tag);
1419 			}
1420 			return (VT_EINVAL);
1421 		}
1422 
1423 		/* Zero's should be written for empty partitions */
1424 		if (vtoc->efi_parts[i].p_tag == V_UNASSIGNED)
1425 			continue;
1426 
1427 		efi_parts[i].efi_gpe_StartingLBA =
1428 		    LE_64(vtoc->efi_parts[i].p_start);
1429 		efi_parts[i].efi_gpe_EndingLBA =
1430 		    LE_64(vtoc->efi_parts[i].p_start +
1431 		    vtoc->efi_parts[i].p_size - 1);
1432 		efi_parts[i].efi_gpe_Attributes.PartitionAttrs =
1433 		    LE_16(vtoc->efi_parts[i].p_flag);
1434 		for (j = 0; j < EFI_PART_NAME_LEN; j++) {
1435 			efi_parts[i].efi_gpe_PartitionName[j] =
1436 			    LE_16((ushort_t)vtoc->efi_parts[i].p_name[j]);
1437 		}
1438 		if ((vtoc->efi_parts[i].p_tag != V_UNASSIGNED) &&
1439 		    uuid_is_null((uchar_t *)&vtoc->efi_parts[i].p_uguid)) {
1440 			(void) uuid_generate((uchar_t *)
1441 			    &vtoc->efi_parts[i].p_uguid);
1442 		}
1443 		memcpy(&efi_parts[i].efi_gpe_UniquePartitionGUID,
1444 		    &vtoc->efi_parts[i].p_uguid,
1445 		    sizeof (uuid_t));
1446 	}
1447 	efi->efi_gpt_PartitionEntryArrayCRC32 =
1448 	    LE_32(efi_crc32((unsigned char *)efi_parts,
1449 	    vtoc->efi_nparts * (int)sizeof (struct efi_gpe)));
1450 	efi->efi_gpt_HeaderCRC32 =
1451 	    LE_32(efi_crc32((unsigned char *)efi,
1452 	    LE_32(efi->efi_gpt_HeaderSize)));
1453 
1454 	if (efi_ioctl(fd, DKIOCSETEFI, &dk_ioc) == -1) {
1455 		free(dk_ioc.dki_data);
1456 		switch (errno) {
1457 		case EIO:
1458 			return (VT_EIO);
1459 		case EINVAL:
1460 			return (VT_EINVAL);
1461 		default:
1462 			return (VT_ERROR);
1463 		}
1464 	}
1465 	/* if it's a metadevice we're done */
1466 	if (md_flag) {
1467 		free(dk_ioc.dki_data);
1468 		return (0);
1469 	}
1470 
1471 	/* write backup partition array */
1472 	dk_ioc.dki_lba = vtoc->efi_last_u_lba + 1;
1473 	dk_ioc.dki_length -= vtoc->efi_lbasize;
1474 	/* LINTED */
1475 	dk_ioc.dki_data = (efi_gpt_t *)((char *)dk_ioc.dki_data +
1476 	    vtoc->efi_lbasize);
1477 
1478 	if (efi_ioctl(fd, DKIOCSETEFI, &dk_ioc) == -1) {
1479 		/*
1480 		 * we wrote the primary label okay, so don't fail
1481 		 */
1482 		if (efi_debug) {
1483 			(void) fprintf(stderr,
1484 			    "write of backup partitions to block %llu "
1485 			    "failed, errno %d\n",
1486 			    vtoc->efi_last_u_lba + 1,
1487 			    errno);
1488 		}
1489 	}
1490 	/*
1491 	 * now swap MyLBA and AlternateLBA fields and write backup
1492 	 * partition table header
1493 	 */
1494 	dk_ioc.dki_lba = lba_backup_gpt_hdr;
1495 	dk_ioc.dki_length = vtoc->efi_lbasize;
1496 	/* LINTED */
1497 	dk_ioc.dki_data = (efi_gpt_t *)((char *)dk_ioc.dki_data -
1498 	    vtoc->efi_lbasize);
1499 	efi->efi_gpt_AlternateLBA = LE_64(1ULL);
1500 	efi->efi_gpt_MyLBA = LE_64(lba_backup_gpt_hdr);
1501 	efi->efi_gpt_PartitionEntryLBA = LE_64(vtoc->efi_last_u_lba + 1);
1502 	efi->efi_gpt_HeaderCRC32 = 0;
1503 	efi->efi_gpt_HeaderCRC32 =
1504 	    LE_32(efi_crc32((unsigned char *)dk_ioc.dki_data,
1505 	    LE_32(efi->efi_gpt_HeaderSize)));
1506 
1507 	if (efi_ioctl(fd, DKIOCSETEFI, &dk_ioc) == -1) {
1508 		if (efi_debug) {
1509 			(void) fprintf(stderr,
1510 			    "write of backup header to block %llu failed, "
1511 			    "errno %d\n",
1512 			    lba_backup_gpt_hdr,
1513 			    errno);
1514 		}
1515 	}
1516 	/* write the PMBR */
1517 	(void) write_pmbr(fd, vtoc);
1518 	free(dk_ioc.dki_data);
1519 
1520 	return (0);
1521 }
1522 
1523 void
efi_free(struct dk_gpt * ptr)1524 efi_free(struct dk_gpt *ptr)
1525 {
1526 	free(ptr);
1527 }
1528 
1529 void
efi_err_check(struct dk_gpt * vtoc)1530 efi_err_check(struct dk_gpt *vtoc)
1531 {
1532 	int			resv_part = -1;
1533 	int			i, j;
1534 	diskaddr_t		istart, jstart, isize, jsize, endsect;
1535 	int			overlap = 0;
1536 
1537 	/*
1538 	 * make sure no partitions overlap
1539 	 */
1540 	for (i = 0; i < vtoc->efi_nparts; i++) {
1541 		/* It can't be unassigned and have an actual size */
1542 		if ((vtoc->efi_parts[i].p_tag == V_UNASSIGNED) &&
1543 		    (vtoc->efi_parts[i].p_size != 0)) {
1544 			(void) fprintf(stderr,
1545 			    "partition %d is \"unassigned\" but has a size "
1546 			    "of %llu\n", i, vtoc->efi_parts[i].p_size);
1547 		}
1548 		if (vtoc->efi_parts[i].p_tag == V_UNASSIGNED) {
1549 			continue;
1550 		}
1551 		if (vtoc->efi_parts[i].p_tag == V_RESERVED) {
1552 			if (resv_part != -1) {
1553 				(void) fprintf(stderr,
1554 				    "found duplicate reserved partition at "
1555 				    "%d\n", i);
1556 			}
1557 			resv_part = i;
1558 			if (vtoc->efi_parts[i].p_size != EFI_MIN_RESV_SIZE)
1559 				(void) fprintf(stderr,
1560 				    "Warning: reserved partition size must "
1561 				    "be %d sectors\n", EFI_MIN_RESV_SIZE);
1562 		}
1563 		if ((vtoc->efi_parts[i].p_start < vtoc->efi_first_u_lba) ||
1564 		    (vtoc->efi_parts[i].p_start > vtoc->efi_last_u_lba)) {
1565 			(void) fprintf(stderr,
1566 			    "Partition %d starts at %llu\n",
1567 			    i,
1568 			    vtoc->efi_parts[i].p_start);
1569 			(void) fprintf(stderr,
1570 			    "It must be between %llu and %llu.\n",
1571 			    vtoc->efi_first_u_lba,
1572 			    vtoc->efi_last_u_lba);
1573 		}
1574 		if ((vtoc->efi_parts[i].p_start +
1575 		    vtoc->efi_parts[i].p_size <
1576 		    vtoc->efi_first_u_lba) ||
1577 		    (vtoc->efi_parts[i].p_start +
1578 		    vtoc->efi_parts[i].p_size >
1579 		    vtoc->efi_last_u_lba + 1)) {
1580 			(void) fprintf(stderr,
1581 			    "Partition %d ends at %llu\n",
1582 			    i,
1583 			    vtoc->efi_parts[i].p_start +
1584 			    vtoc->efi_parts[i].p_size);
1585 			(void) fprintf(stderr,
1586 			    "It must be between %llu and %llu.\n",
1587 			    vtoc->efi_first_u_lba,
1588 			    vtoc->efi_last_u_lba);
1589 		}
1590 
1591 		for (j = 0; j < vtoc->efi_nparts; j++) {
1592 			isize = vtoc->efi_parts[i].p_size;
1593 			jsize = vtoc->efi_parts[j].p_size;
1594 			istart = vtoc->efi_parts[i].p_start;
1595 			jstart = vtoc->efi_parts[j].p_start;
1596 			if ((i != j) && (isize != 0) && (jsize != 0)) {
1597 				endsect = jstart + jsize -1;
1598 				if ((jstart <= istart) &&
1599 				    (istart <= endsect)) {
1600 					if (!overlap) {
1601 					(void) fprintf(stderr,
1602 					    "label error: EFI Labels do not "
1603 					    "support overlapping partitions\n");
1604 					}
1605 					(void) fprintf(stderr,
1606 					    "Partition %d overlaps partition "
1607 					    "%d.\n", i, j);
1608 					overlap = 1;
1609 				}
1610 			}
1611 		}
1612 	}
1613 	/* make sure there is a reserved partition */
1614 	if (resv_part == -1) {
1615 		(void) fprintf(stderr,
1616 		    "no reserved partition found\n");
1617 	}
1618 }
1619