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