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 			free(vptr);
472 			*vtoc = NULL;
473 			return (VT_ERROR);
474 		} else {
475 			vptr = tmp;
476 			rval = efi_read(fd, vptr);
477 		}
478 	}
479 
480 	if (rval < 0) {
481 		if (efi_debug) {
482 			(void) fprintf(stderr,
483 			    "read of EFI table failed, rval=%d\n", rval);
484 		}
485 		free(vptr);
486 		*vtoc = NULL;
487 	} else {
488 		*vtoc = vptr;
489 	}
490 
491 	return (rval);
492 }
493 
494 static int
495 efi_ioctl(int fd, int cmd, dk_efi_t *dk_ioc)
496 {
497 	void *data = dk_ioc->dki_data;
498 	int error;
499 	diskaddr_t capacity;
500 	uint_t lbsize;
501 
502 	/*
503 	 * When the IO is not being performed in kernel as an ioctl we need
504 	 * to know the sector size so we can seek to the proper byte offset.
505 	 */
506 	if (read_disk_info(fd, &capacity, &lbsize) == -1) {
507 		if (efi_debug)
508 			fprintf(stderr, "unable to read disk info: %d", errno);
509 
510 		errno = EIO;
511 		return (-1);
512 	}
513 
514 	switch (cmd) {
515 	case DKIOCGETEFI:
516 		if (lbsize == 0) {
517 			if (efi_debug)
518 				(void) fprintf(stderr, "DKIOCGETEFI assuming "
519 				    "LBA %d bytes\n", DEV_BSIZE);
520 
521 			lbsize = DEV_BSIZE;
522 		}
523 
524 		error = lseek(fd, dk_ioc->dki_lba * lbsize, SEEK_SET);
525 		if (error == -1) {
526 			if (efi_debug)
527 				(void) fprintf(stderr, "DKIOCGETEFI lseek "
528 				    "error: %d\n", errno);
529 			return (error);
530 		}
531 
532 		error = read(fd, data, dk_ioc->dki_length);
533 		if (error == -1) {
534 			if (efi_debug)
535 				(void) fprintf(stderr, "DKIOCGETEFI read "
536 				    "error: %d\n", errno);
537 			return (error);
538 		}
539 
540 		if (error != dk_ioc->dki_length) {
541 			if (efi_debug)
542 				(void) fprintf(stderr, "DKIOCGETEFI short "
543 				    "read of %d bytes\n", error);
544 			errno = EIO;
545 			return (-1);
546 		}
547 		error = 0;
548 		break;
549 
550 	case DKIOCSETEFI:
551 		if (lbsize == 0) {
552 			if (efi_debug)
553 				(void) fprintf(stderr, "DKIOCSETEFI unknown "
554 				    "LBA size\n");
555 			errno = EIO;
556 			return (-1);
557 		}
558 
559 		error = lseek(fd, dk_ioc->dki_lba * lbsize, SEEK_SET);
560 		if (error == -1) {
561 			if (efi_debug)
562 				(void) fprintf(stderr, "DKIOCSETEFI lseek "
563 				    "error: %d\n", errno);
564 			return (error);
565 		}
566 
567 		error = write(fd, data, dk_ioc->dki_length);
568 		if (error == -1) {
569 			if (efi_debug)
570 				(void) fprintf(stderr, "DKIOCSETEFI write "
571 				    "error: %d\n", errno);
572 			return (error);
573 		}
574 
575 		if (error != dk_ioc->dki_length) {
576 			if (efi_debug)
577 				(void) fprintf(stderr, "DKIOCSETEFI short "
578 				    "write of %d bytes\n", error);
579 			errno = EIO;
580 			return (-1);
581 		}
582 
583 		/* Sync the new EFI table to disk */
584 		error = fsync(fd);
585 		if (error == -1)
586 			return (error);
587 
588 		/* Ensure any local disk cache is also flushed */
589 		if (ioctl(fd, BLKFLSBUF, 0) == -1)
590 			return (error);
591 
592 		error = 0;
593 		break;
594 
595 	default:
596 		if (efi_debug)
597 			(void) fprintf(stderr, "unsupported ioctl()\n");
598 
599 		errno = EIO;
600 		return (-1);
601 	}
602 
603 	return (error);
604 }
605 
606 int
607 efi_rescan(int fd)
608 {
609 	int retry = 10;
610 	int error;
611 
612 	/* Notify the kernel a devices partition table has been updated */
613 	while ((error = ioctl(fd, BLKRRPART)) != 0) {
614 		if ((--retry == 0) || (errno != EBUSY)) {
615 			(void) fprintf(stderr, "the kernel failed to rescan "
616 			    "the partition table: %d\n", errno);
617 			return (-1);
618 		}
619 		usleep(50000);
620 	}
621 
622 	return (0);
623 }
624 
625 static int
626 check_label(int fd, dk_efi_t *dk_ioc)
627 {
628 	efi_gpt_t		*efi;
629 	uint_t			crc;
630 
631 	if (efi_ioctl(fd, DKIOCGETEFI, dk_ioc) == -1) {
632 		switch (errno) {
633 		case EIO:
634 			return (VT_EIO);
635 		default:
636 			return (VT_ERROR);
637 		}
638 	}
639 	efi = dk_ioc->dki_data;
640 	if (efi->efi_gpt_Signature != LE_64(EFI_SIGNATURE)) {
641 		if (efi_debug)
642 			(void) fprintf(stderr,
643 			    "Bad EFI signature: 0x%llx != 0x%llx\n",
644 			    (long long)efi->efi_gpt_Signature,
645 			    (long long)LE_64(EFI_SIGNATURE));
646 		return (VT_EINVAL);
647 	}
648 
649 	/*
650 	 * check CRC of the header; the size of the header should
651 	 * never be larger than one block
652 	 */
653 	crc = efi->efi_gpt_HeaderCRC32;
654 	efi->efi_gpt_HeaderCRC32 = 0;
655 	len_t headerSize = (len_t)LE_32(efi->efi_gpt_HeaderSize);
656 
657 	if (headerSize < EFI_MIN_LABEL_SIZE || headerSize > EFI_LABEL_SIZE) {
658 		if (efi_debug)
659 			(void) fprintf(stderr,
660 			    "Invalid EFI HeaderSize %llu.  Assuming %d.\n",
661 			    headerSize, EFI_MIN_LABEL_SIZE);
662 	}
663 
664 	if ((headerSize > dk_ioc->dki_length) ||
665 	    crc != LE_32(efi_crc32((unsigned char *)efi, headerSize))) {
666 		if (efi_debug)
667 			(void) fprintf(stderr,
668 			    "Bad EFI CRC: 0x%x != 0x%x\n",
669 			    crc, LE_32(efi_crc32((unsigned char *)efi,
670 			    headerSize)));
671 		return (VT_EINVAL);
672 	}
673 
674 	return (0);
675 }
676 
677 static int
678 efi_read(int fd, struct dk_gpt *vtoc)
679 {
680 	int			i, j;
681 	int			label_len;
682 	int			rval = 0;
683 	int			md_flag = 0;
684 	int			vdc_flag = 0;
685 	diskaddr_t		capacity = 0;
686 	uint_t			lbsize = 0;
687 	struct dk_minfo		disk_info;
688 	dk_efi_t		dk_ioc;
689 	efi_gpt_t		*efi;
690 	efi_gpe_t		*efi_parts;
691 	struct dk_cinfo		dki_info;
692 	uint32_t		user_length;
693 	boolean_t		legacy_label = B_FALSE;
694 
695 	/*
696 	 * get the partition number for this file descriptor.
697 	 */
698 	if ((rval = efi_get_info(fd, &dki_info)) != 0)
699 		return (rval);
700 
701 	if ((strncmp(dki_info.dki_cname, "pseudo", 7) == 0) &&
702 	    (strncmp(dki_info.dki_dname, "md", 3) == 0)) {
703 		md_flag++;
704 	} else if ((strncmp(dki_info.dki_cname, "vdc", 4) == 0) &&
705 	    (strncmp(dki_info.dki_dname, "vdc", 4) == 0)) {
706 		/*
707 		 * The controller and drive name "vdc" (virtual disk client)
708 		 * indicates a LDoms virtual disk.
709 		 */
710 		vdc_flag++;
711 	}
712 
713 	/* get the LBA size */
714 	if (read_disk_info(fd, &capacity, &lbsize) == -1) {
715 		if (efi_debug) {
716 			(void) fprintf(stderr,
717 			    "unable to read disk info: %d",
718 			    errno);
719 		}
720 		return (VT_EINVAL);
721 	}
722 
723 	disk_info.dki_lbsize = lbsize;
724 	disk_info.dki_capacity = capacity;
725 
726 	if (disk_info.dki_lbsize == 0) {
727 		if (efi_debug) {
728 			(void) fprintf(stderr,
729 			    "efi_read: assuming LBA 512 bytes\n");
730 		}
731 		disk_info.dki_lbsize = DEV_BSIZE;
732 	}
733 	/*
734 	 * Read the EFI GPT to figure out how many partitions we need
735 	 * to deal with.
736 	 */
737 	dk_ioc.dki_lba = 1;
738 	if (NBLOCKS(vtoc->efi_nparts, disk_info.dki_lbsize) < 34) {
739 		label_len = EFI_MIN_ARRAY_SIZE + disk_info.dki_lbsize;
740 	} else {
741 		label_len = vtoc->efi_nparts * (int) sizeof (efi_gpe_t) +
742 		    disk_info.dki_lbsize;
743 		if (label_len % disk_info.dki_lbsize) {
744 			/* pad to physical sector size */
745 			label_len += disk_info.dki_lbsize;
746 			label_len &= ~(disk_info.dki_lbsize - 1);
747 		}
748 	}
749 
750 	if (posix_memalign((void **)&dk_ioc.dki_data,
751 	    disk_info.dki_lbsize, label_len))
752 		return (VT_ERROR);
753 
754 	memset(dk_ioc.dki_data, 0, label_len);
755 	dk_ioc.dki_length = disk_info.dki_lbsize;
756 	user_length = vtoc->efi_nparts;
757 	efi = dk_ioc.dki_data;
758 	if (md_flag) {
759 		dk_ioc.dki_length = label_len;
760 		if (efi_ioctl(fd, DKIOCGETEFI, &dk_ioc) == -1) {
761 			switch (errno) {
762 			case EIO:
763 				return (VT_EIO);
764 			default:
765 				return (VT_ERROR);
766 			}
767 		}
768 	} else if ((rval = check_label(fd, &dk_ioc)) == VT_EINVAL) {
769 		/*
770 		 * No valid label here; try the alternate. Note that here
771 		 * we just read GPT header and save it into dk_ioc.data,
772 		 * Later, we will read GUID partition entry array if we
773 		 * can get valid GPT header.
774 		 */
775 
776 		/*
777 		 * This is a workaround for legacy systems. In the past, the
778 		 * last sector of SCSI disk was invisible on x86 platform. At
779 		 * that time, backup label was saved on the next to the last
780 		 * sector. It is possible for users to move a disk from previous
781 		 * solaris system to present system. Here, we attempt to search
782 		 * legacy backup EFI label first.
783 		 */
784 		dk_ioc.dki_lba = disk_info.dki_capacity - 2;
785 		dk_ioc.dki_length = disk_info.dki_lbsize;
786 		rval = check_label(fd, &dk_ioc);
787 		if (rval == VT_EINVAL) {
788 			/*
789 			 * we didn't find legacy backup EFI label, try to
790 			 * search backup EFI label in the last block.
791 			 */
792 			dk_ioc.dki_lba = disk_info.dki_capacity - 1;
793 			dk_ioc.dki_length = disk_info.dki_lbsize;
794 			rval = check_label(fd, &dk_ioc);
795 			if (rval == 0) {
796 				legacy_label = B_TRUE;
797 				if (efi_debug)
798 					(void) fprintf(stderr,
799 					    "efi_read: primary label corrupt; "
800 					    "using EFI backup label located on"
801 					    " the last block\n");
802 			}
803 		} else {
804 			if ((efi_debug) && (rval == 0))
805 				(void) fprintf(stderr, "efi_read: primary label"
806 				    " corrupt; using legacy EFI backup label "
807 				    " located on the next to last block\n");
808 		}
809 
810 		if (rval == 0) {
811 			dk_ioc.dki_lba = LE_64(efi->efi_gpt_PartitionEntryLBA);
812 			vtoc->efi_flags |= EFI_GPT_PRIMARY_CORRUPT;
813 			vtoc->efi_nparts =
814 			    LE_32(efi->efi_gpt_NumberOfPartitionEntries);
815 			/*
816 			 * Partition tables are between backup GPT header
817 			 * table and ParitionEntryLBA (the starting LBA of
818 			 * the GUID partition entries array). Now that we
819 			 * already got valid GPT header and saved it in
820 			 * dk_ioc.dki_data, we try to get GUID partition
821 			 * entry array here.
822 			 */
823 			/* LINTED */
824 			dk_ioc.dki_data = (efi_gpt_t *)((char *)dk_ioc.dki_data
825 			    + disk_info.dki_lbsize);
826 			if (legacy_label)
827 				dk_ioc.dki_length = disk_info.dki_capacity - 1 -
828 				    dk_ioc.dki_lba;
829 			else
830 				dk_ioc.dki_length = disk_info.dki_capacity - 2 -
831 				    dk_ioc.dki_lba;
832 			dk_ioc.dki_length *= disk_info.dki_lbsize;
833 			if (dk_ioc.dki_length >
834 			    ((len_t)label_len - sizeof (*dk_ioc.dki_data))) {
835 				rval = VT_EINVAL;
836 			} else {
837 				/*
838 				 * read GUID partition entry array
839 				 */
840 				rval = efi_ioctl(fd, DKIOCGETEFI, &dk_ioc);
841 			}
842 		}
843 
844 	} else if (rval == 0) {
845 
846 		dk_ioc.dki_lba = LE_64(efi->efi_gpt_PartitionEntryLBA);
847 		/* LINTED */
848 		dk_ioc.dki_data = (efi_gpt_t *)((char *)dk_ioc.dki_data
849 		    + disk_info.dki_lbsize);
850 		dk_ioc.dki_length = label_len - disk_info.dki_lbsize;
851 		rval = efi_ioctl(fd, DKIOCGETEFI, &dk_ioc);
852 
853 	} else if (vdc_flag && rval == VT_ERROR && errno == EINVAL) {
854 		/*
855 		 * When the device is a LDoms virtual disk, the DKIOCGETEFI
856 		 * ioctl can fail with EINVAL if the virtual disk backend
857 		 * is a ZFS volume serviced by a domain running an old version
858 		 * of Solaris. This is because the DKIOCGETEFI ioctl was
859 		 * initially incorrectly implemented for a ZFS volume and it
860 		 * expected the GPT and GPE to be retrieved with a single ioctl.
861 		 * So we try to read the GPT and the GPE using that old style
862 		 * ioctl.
863 		 */
864 		dk_ioc.dki_lba = 1;
865 		dk_ioc.dki_length = label_len;
866 		rval = check_label(fd, &dk_ioc);
867 	}
868 
869 	if (rval < 0) {
870 		free(efi);
871 		return (rval);
872 	}
873 
874 	/* LINTED -- always longlong aligned */
875 	efi_parts = (efi_gpe_t *)(((char *)efi) + disk_info.dki_lbsize);
876 
877 	/*
878 	 * Assemble this into a "dk_gpt" struct for easier
879 	 * digestibility by applications.
880 	 */
881 	vtoc->efi_version = LE_32(efi->efi_gpt_Revision);
882 	vtoc->efi_nparts = LE_32(efi->efi_gpt_NumberOfPartitionEntries);
883 	vtoc->efi_part_size = LE_32(efi->efi_gpt_SizeOfPartitionEntry);
884 	vtoc->efi_lbasize = disk_info.dki_lbsize;
885 	vtoc->efi_last_lba = disk_info.dki_capacity - 1;
886 	vtoc->efi_first_u_lba = LE_64(efi->efi_gpt_FirstUsableLBA);
887 	vtoc->efi_last_u_lba = LE_64(efi->efi_gpt_LastUsableLBA);
888 	vtoc->efi_altern_lba = LE_64(efi->efi_gpt_AlternateLBA);
889 	UUID_LE_CONVERT(vtoc->efi_disk_uguid, efi->efi_gpt_DiskGUID);
890 
891 	/*
892 	 * If the array the user passed in is too small, set the length
893 	 * to what it needs to be and return
894 	 */
895 	if (user_length < vtoc->efi_nparts) {
896 		return (VT_EINVAL);
897 	}
898 
899 	for (i = 0; i < vtoc->efi_nparts; i++) {
900 
901 		UUID_LE_CONVERT(vtoc->efi_parts[i].p_guid,
902 		    efi_parts[i].efi_gpe_PartitionTypeGUID);
903 
904 		for (j = 0;
905 		    j < sizeof (conversion_array)
906 		    / sizeof (struct uuid_to_ptag); j++) {
907 
908 			if (bcmp(&vtoc->efi_parts[i].p_guid,
909 			    &conversion_array[j].uuid,
910 			    sizeof (struct uuid)) == 0) {
911 				vtoc->efi_parts[i].p_tag = j;
912 				break;
913 			}
914 		}
915 		if (vtoc->efi_parts[i].p_tag == V_UNASSIGNED)
916 			continue;
917 		vtoc->efi_parts[i].p_flag =
918 		    LE_16(efi_parts[i].efi_gpe_Attributes.PartitionAttrs);
919 		vtoc->efi_parts[i].p_start =
920 		    LE_64(efi_parts[i].efi_gpe_StartingLBA);
921 		vtoc->efi_parts[i].p_size =
922 		    LE_64(efi_parts[i].efi_gpe_EndingLBA) -
923 		    vtoc->efi_parts[i].p_start + 1;
924 		for (j = 0; j < EFI_PART_NAME_LEN; j++) {
925 			vtoc->efi_parts[i].p_name[j] =
926 			    (uchar_t)LE_16(
927 			    efi_parts[i].efi_gpe_PartitionName[j]);
928 		}
929 
930 		UUID_LE_CONVERT(vtoc->efi_parts[i].p_uguid,
931 		    efi_parts[i].efi_gpe_UniquePartitionGUID);
932 	}
933 	free(efi);
934 
935 	return (dki_info.dki_partition);
936 }
937 
938 /* writes a "protective" MBR */
939 static int
940 write_pmbr(int fd, struct dk_gpt *vtoc)
941 {
942 	dk_efi_t	dk_ioc;
943 	struct mboot	mb;
944 	uchar_t		*cp;
945 	diskaddr_t	size_in_lba;
946 	uchar_t		*buf;
947 	int		len;
948 
949 	len = (vtoc->efi_lbasize == 0) ? sizeof (mb) : vtoc->efi_lbasize;
950 	if (posix_memalign((void **)&buf, len, len))
951 		return (VT_ERROR);
952 
953 	/*
954 	 * Preserve any boot code and disk signature if the first block is
955 	 * already an MBR.
956 	 */
957 	memset(buf, 0, len);
958 	dk_ioc.dki_lba = 0;
959 	dk_ioc.dki_length = len;
960 	/* LINTED -- always longlong aligned */
961 	dk_ioc.dki_data = (efi_gpt_t *)buf;
962 	if (efi_ioctl(fd, DKIOCGETEFI, &dk_ioc) == -1) {
963 		(void) memcpy(&mb, buf, sizeof (mb));
964 		bzero(&mb, sizeof (mb));
965 		mb.signature = LE_16(MBB_MAGIC);
966 	} else {
967 		(void) memcpy(&mb, buf, sizeof (mb));
968 		if (mb.signature != LE_16(MBB_MAGIC)) {
969 			bzero(&mb, sizeof (mb));
970 			mb.signature = LE_16(MBB_MAGIC);
971 		}
972 	}
973 
974 	bzero(&mb.parts, sizeof (mb.parts));
975 	cp = (uchar_t *)&mb.parts[0];
976 	/* bootable or not */
977 	*cp++ = 0;
978 	/* beginning CHS; 0xffffff if not representable */
979 	*cp++ = 0xff;
980 	*cp++ = 0xff;
981 	*cp++ = 0xff;
982 	/* OS type */
983 	*cp++ = EFI_PMBR;
984 	/* ending CHS; 0xffffff if not representable */
985 	*cp++ = 0xff;
986 	*cp++ = 0xff;
987 	*cp++ = 0xff;
988 	/* starting LBA: 1 (little endian format) by EFI definition */
989 	*cp++ = 0x01;
990 	*cp++ = 0x00;
991 	*cp++ = 0x00;
992 	*cp++ = 0x00;
993 	/* ending LBA: last block on the disk (little endian format) */
994 	size_in_lba = vtoc->efi_last_lba;
995 	if (size_in_lba < 0xffffffff) {
996 		*cp++ = (size_in_lba & 0x000000ff);
997 		*cp++ = (size_in_lba & 0x0000ff00) >> 8;
998 		*cp++ = (size_in_lba & 0x00ff0000) >> 16;
999 		*cp++ = (size_in_lba & 0xff000000) >> 24;
1000 	} else {
1001 		*cp++ = 0xff;
1002 		*cp++ = 0xff;
1003 		*cp++ = 0xff;
1004 		*cp++ = 0xff;
1005 	}
1006 
1007 	(void) memcpy(buf, &mb, sizeof (mb));
1008 	/* LINTED -- always longlong aligned */
1009 	dk_ioc.dki_data = (efi_gpt_t *)buf;
1010 	dk_ioc.dki_lba = 0;
1011 	dk_ioc.dki_length = len;
1012 	if (efi_ioctl(fd, DKIOCSETEFI, &dk_ioc) == -1) {
1013 		free(buf);
1014 		switch (errno) {
1015 		case EIO:
1016 			return (VT_EIO);
1017 		case EINVAL:
1018 			return (VT_EINVAL);
1019 		default:
1020 			return (VT_ERROR);
1021 		}
1022 	}
1023 	free(buf);
1024 	return (0);
1025 }
1026 
1027 /* make sure the user specified something reasonable */
1028 static int
1029 check_input(struct dk_gpt *vtoc)
1030 {
1031 	int			resv_part = -1;
1032 	int			i, j;
1033 	diskaddr_t		istart, jstart, isize, jsize, endsect;
1034 
1035 	/*
1036 	 * Sanity-check the input (make sure no partitions overlap)
1037 	 */
1038 	for (i = 0; i < vtoc->efi_nparts; i++) {
1039 		/* It can't be unassigned and have an actual size */
1040 		if ((vtoc->efi_parts[i].p_tag == V_UNASSIGNED) &&
1041 		    (vtoc->efi_parts[i].p_size != 0)) {
1042 			if (efi_debug) {
1043 				(void) fprintf(stderr, "partition %d is "
1044 				    "\"unassigned\" but has a size of %llu",
1045 				    i, vtoc->efi_parts[i].p_size);
1046 			}
1047 			return (VT_EINVAL);
1048 		}
1049 		if (vtoc->efi_parts[i].p_tag == V_UNASSIGNED) {
1050 			if (uuid_is_null((uchar_t *)&vtoc->efi_parts[i].p_guid))
1051 				continue;
1052 			/* we have encountered an unknown uuid */
1053 			vtoc->efi_parts[i].p_tag = 0xff;
1054 		}
1055 		if (vtoc->efi_parts[i].p_tag == V_RESERVED) {
1056 			if (resv_part != -1) {
1057 				if (efi_debug) {
1058 					(void) fprintf(stderr, "found "
1059 					    "duplicate reserved partition "
1060 					    "at %d\n", i);
1061 				}
1062 				return (VT_EINVAL);
1063 			}
1064 			resv_part = i;
1065 		}
1066 		if ((vtoc->efi_parts[i].p_start < vtoc->efi_first_u_lba) ||
1067 		    (vtoc->efi_parts[i].p_start > vtoc->efi_last_u_lba)) {
1068 			if (efi_debug) {
1069 				(void) fprintf(stderr,
1070 				    "Partition %d starts at %llu.  ",
1071 				    i,
1072 				    vtoc->efi_parts[i].p_start);
1073 				(void) fprintf(stderr,
1074 				    "It must be between %llu and %llu.\n",
1075 				    vtoc->efi_first_u_lba,
1076 				    vtoc->efi_last_u_lba);
1077 			}
1078 			return (VT_EINVAL);
1079 		}
1080 		if ((vtoc->efi_parts[i].p_start +
1081 		    vtoc->efi_parts[i].p_size <
1082 		    vtoc->efi_first_u_lba) ||
1083 		    (vtoc->efi_parts[i].p_start +
1084 		    vtoc->efi_parts[i].p_size >
1085 		    vtoc->efi_last_u_lba + 1)) {
1086 			if (efi_debug) {
1087 				(void) fprintf(stderr,
1088 				    "Partition %d ends at %llu.  ",
1089 				    i,
1090 				    vtoc->efi_parts[i].p_start +
1091 				    vtoc->efi_parts[i].p_size);
1092 				(void) fprintf(stderr,
1093 				    "It must be between %llu and %llu.\n",
1094 				    vtoc->efi_first_u_lba,
1095 				    vtoc->efi_last_u_lba);
1096 			}
1097 			return (VT_EINVAL);
1098 		}
1099 
1100 		for (j = 0; j < vtoc->efi_nparts; j++) {
1101 			isize = vtoc->efi_parts[i].p_size;
1102 			jsize = vtoc->efi_parts[j].p_size;
1103 			istart = vtoc->efi_parts[i].p_start;
1104 			jstart = vtoc->efi_parts[j].p_start;
1105 			if ((i != j) && (isize != 0) && (jsize != 0)) {
1106 				endsect = jstart + jsize -1;
1107 				if ((jstart <= istart) &&
1108 				    (istart <= endsect)) {
1109 					if (efi_debug) {
1110 						(void) fprintf(stderr,
1111 						    "Partition %d overlaps "
1112 						    "partition %d.", i, j);
1113 					}
1114 					return (VT_EINVAL);
1115 				}
1116 			}
1117 		}
1118 	}
1119 	/* just a warning for now */
1120 	if ((resv_part == -1) && efi_debug) {
1121 		(void) fprintf(stderr,
1122 		    "no reserved partition found\n");
1123 	}
1124 	return (0);
1125 }
1126 
1127 static int
1128 call_blkpg_ioctl(int fd, int command, diskaddr_t start,
1129     diskaddr_t size, uint_t pno)
1130 {
1131 	struct blkpg_ioctl_arg ioctl_arg;
1132 	struct blkpg_partition  linux_part;
1133 	memset(&linux_part, 0, sizeof (linux_part));
1134 
1135 	char *path = efi_get_devname(fd);
1136 	if (path == NULL) {
1137 		(void) fprintf(stderr, "failed to retrieve device name\n");
1138 		return (VT_EINVAL);
1139 	}
1140 
1141 	linux_part.start = start;
1142 	linux_part.length = size;
1143 	linux_part.pno = pno;
1144 	snprintf(linux_part.devname, BLKPG_DEVNAMELTH - 1, "%s%u", path, pno);
1145 	linux_part.devname[BLKPG_DEVNAMELTH - 1] = '\0';
1146 	free(path);
1147 
1148 	ioctl_arg.op = command;
1149 	ioctl_arg.flags = 0;
1150 	ioctl_arg.datalen = sizeof (struct blkpg_partition);
1151 	ioctl_arg.data = &linux_part;
1152 
1153 	return (ioctl(fd, BLKPG, &ioctl_arg));
1154 }
1155 
1156 /*
1157  * add all the unallocated space to the current label
1158  */
1159 int
1160 efi_use_whole_disk(int fd)
1161 {
1162 	struct dk_gpt *efi_label = NULL;
1163 	int rval;
1164 	int i;
1165 	uint_t resv_index = 0, data_index = 0;
1166 	diskaddr_t resv_start = 0, data_start = 0;
1167 	diskaddr_t data_size, limit, difference;
1168 	boolean_t sync_needed = B_FALSE;
1169 	uint_t nblocks;
1170 
1171 	rval = efi_alloc_and_read(fd, &efi_label);
1172 	if (rval < 0) {
1173 		if (efi_label != NULL)
1174 			efi_free(efi_label);
1175 		return (rval);
1176 	}
1177 
1178 	/*
1179 	 * Find the last physically non-zero partition.
1180 	 * This should be the reserved partition.
1181 	 */
1182 	for (i = 0; i < efi_label->efi_nparts; i ++) {
1183 		if (resv_start < efi_label->efi_parts[i].p_start) {
1184 			resv_start = efi_label->efi_parts[i].p_start;
1185 			resv_index = i;
1186 		}
1187 	}
1188 
1189 	/*
1190 	 * Find the last physically non-zero partition before that.
1191 	 * This is the data partition.
1192 	 */
1193 	for (i = 0; i < resv_index; i ++) {
1194 		if (data_start < efi_label->efi_parts[i].p_start) {
1195 			data_start = efi_label->efi_parts[i].p_start;
1196 			data_index = i;
1197 		}
1198 	}
1199 	data_size = efi_label->efi_parts[data_index].p_size;
1200 
1201 	/*
1202 	 * See the "efi_alloc_and_init" function for more information
1203 	 * about where this "nblocks" value comes from.
1204 	 */
1205 	nblocks = efi_label->efi_first_u_lba - 1;
1206 
1207 	/*
1208 	 * Determine if the EFI label is out of sync. We check that:
1209 	 *
1210 	 * 1. the data partition ends at the limit we set, and
1211 	 * 2. the reserved partition starts at the limit we set.
1212 	 *
1213 	 * If either of these conditions is not met, then we need to
1214 	 * resync the EFI label.
1215 	 *
1216 	 * The limit is the last usable LBA, determined by the last LBA
1217 	 * and the first usable LBA fields on the EFI label of the disk
1218 	 * (see the lines directly above). Additionally, we factor in
1219 	 * EFI_MIN_RESV_SIZE (per its use in "zpool_label_disk") and
1220 	 * P2ALIGN it to ensure the partition boundaries are aligned
1221 	 * (for performance reasons). The alignment should match the
1222 	 * alignment used by the "zpool_label_disk" function.
1223 	 */
1224 	limit = P2ALIGN(efi_label->efi_last_lba - nblocks - EFI_MIN_RESV_SIZE,
1225 	    PARTITION_END_ALIGNMENT);
1226 	if (data_start + data_size != limit || resv_start != limit)
1227 		sync_needed = B_TRUE;
1228 
1229 	if (efi_debug && sync_needed)
1230 		(void) fprintf(stderr, "efi_use_whole_disk: sync needed\n");
1231 
1232 	/*
1233 	 * If alter_lba is 1, we are using the backup label.
1234 	 * Since we can locate the backup label by disk capacity,
1235 	 * there must be no unallocated space.
1236 	 */
1237 	if ((efi_label->efi_altern_lba == 1) || (efi_label->efi_altern_lba
1238 	    >= efi_label->efi_last_lba && !sync_needed)) {
1239 		if (efi_debug) {
1240 			(void) fprintf(stderr,
1241 			    "efi_use_whole_disk: requested space not found\n");
1242 		}
1243 		efi_free(efi_label);
1244 		return (VT_ENOSPC);
1245 	}
1246 
1247 	/*
1248 	 * Verify that we've found the reserved partition by checking
1249 	 * that it looks the way it did when we created it in zpool_label_disk.
1250 	 * If we've found the incorrect partition, then we know that this
1251 	 * device was reformatted and no longer is solely used by ZFS.
1252 	 */
1253 	if ((efi_label->efi_parts[resv_index].p_size != EFI_MIN_RESV_SIZE) ||
1254 	    (efi_label->efi_parts[resv_index].p_tag != V_RESERVED) ||
1255 	    (resv_index != 8)) {
1256 		if (efi_debug) {
1257 			(void) fprintf(stderr,
1258 			    "efi_use_whole_disk: wholedisk not available\n");
1259 		}
1260 		efi_free(efi_label);
1261 		return (VT_ENOSPC);
1262 	}
1263 
1264 	if (data_start + data_size != resv_start) {
1265 		if (efi_debug) {
1266 			(void) fprintf(stderr,
1267 			    "efi_use_whole_disk: "
1268 			    "data_start (%lli) + "
1269 			    "data_size (%lli) != "
1270 			    "resv_start (%lli)\n",
1271 			    data_start, data_size, resv_start);
1272 		}
1273 
1274 		return (VT_EINVAL);
1275 	}
1276 
1277 	if (limit < resv_start) {
1278 		if (efi_debug) {
1279 			(void) fprintf(stderr,
1280 			    "efi_use_whole_disk: "
1281 			    "limit (%lli) < resv_start (%lli)\n",
1282 			    limit, resv_start);
1283 		}
1284 
1285 		return (VT_EINVAL);
1286 	}
1287 
1288 	difference = limit - resv_start;
1289 
1290 	if (efi_debug)
1291 		(void) fprintf(stderr,
1292 		    "efi_use_whole_disk: difference is %lli\n", difference);
1293 
1294 	/*
1295 	 * Move the reserved partition. There is currently no data in
1296 	 * here except fabricated devids (which get generated via
1297 	 * efi_write()). So there is no need to copy data.
1298 	 */
1299 	efi_label->efi_parts[data_index].p_size += difference;
1300 	efi_label->efi_parts[resv_index].p_start += difference;
1301 	efi_label->efi_last_u_lba = efi_label->efi_last_lba - nblocks;
1302 
1303 	/*
1304 	 * Rescanning the partition table in the kernel can result
1305 	 * in the device links to be removed (see comment in vdev_disk_open).
1306 	 * If BLKPG_RESIZE_PARTITION is available, then we can resize
1307 	 * the partition table online and avoid having to remove the device
1308 	 * links used by the pool. This provides a very deterministic
1309 	 * approach to resizing devices and does not require any
1310 	 * loops waiting for devices to reappear.
1311 	 */
1312 #ifdef BLKPG_RESIZE_PARTITION
1313 	/*
1314 	 * Delete the reserved partition since we're about to expand
1315 	 * the data partition and it would overlap with the reserved
1316 	 * partition.
1317 	 * NOTE: The starting index for the ioctl is 1 while for the
1318 	 * EFI partitions it's 0. For that reason we have to add one
1319 	 * whenever we make an ioctl call.
1320 	 */
1321 	rval = call_blkpg_ioctl(fd, BLKPG_DEL_PARTITION, 0, 0, resv_index + 1);
1322 	if (rval != 0)
1323 		goto out;
1324 
1325 	/*
1326 	 * Expand the data partition
1327 	 */
1328 	rval = call_blkpg_ioctl(fd, BLKPG_RESIZE_PARTITION,
1329 	    efi_label->efi_parts[data_index].p_start * efi_label->efi_lbasize,
1330 	    efi_label->efi_parts[data_index].p_size * efi_label->efi_lbasize,
1331 	    data_index + 1);
1332 	if (rval != 0) {
1333 		(void) fprintf(stderr, "Unable to resize data "
1334 		    "partition:  %d\n", rval);
1335 		/*
1336 		 * Since we failed to resize, we need to reset the start
1337 		 * of the reserve partition and re-create it.
1338 		 */
1339 		efi_label->efi_parts[resv_index].p_start -= difference;
1340 	}
1341 
1342 	/*
1343 	 * Re-add the reserved partition. If we've expanded the data partition
1344 	 * then we'll move the reserve partition to the end of the data
1345 	 * partition. Otherwise, we'll recreate the partition in its original
1346 	 * location. Note that we do this as best-effort and ignore any
1347 	 * errors that may arise here. This will ensure that we finish writing
1348 	 * the EFI label.
1349 	 */
1350 	(void) call_blkpg_ioctl(fd, BLKPG_ADD_PARTITION,
1351 	    efi_label->efi_parts[resv_index].p_start * efi_label->efi_lbasize,
1352 	    efi_label->efi_parts[resv_index].p_size * efi_label->efi_lbasize,
1353 	    resv_index + 1);
1354 #endif
1355 
1356 	/*
1357 	 * We're now ready to write the EFI label.
1358 	 */
1359 	if (rval == 0) {
1360 		rval = efi_write(fd, efi_label);
1361 		if (rval < 0 && efi_debug) {
1362 			(void) fprintf(stderr, "efi_use_whole_disk:fail "
1363 			    "to write label, rval=%d\n", rval);
1364 		}
1365 	}
1366 
1367 out:
1368 	efi_free(efi_label);
1369 	return (rval);
1370 }
1371 
1372 /*
1373  * write EFI label and backup label
1374  */
1375 int
1376 efi_write(int fd, struct dk_gpt *vtoc)
1377 {
1378 	dk_efi_t		dk_ioc;
1379 	efi_gpt_t		*efi;
1380 	efi_gpe_t		*efi_parts;
1381 	int			i, j;
1382 	struct dk_cinfo		dki_info;
1383 	int			rval;
1384 	int			md_flag = 0;
1385 	int			nblocks;
1386 	diskaddr_t		lba_backup_gpt_hdr;
1387 
1388 	if ((rval = efi_get_info(fd, &dki_info)) != 0)
1389 		return (rval);
1390 
1391 	/* check if we are dealing with a metadevice */
1392 	if ((strncmp(dki_info.dki_cname, "pseudo", 7) == 0) &&
1393 	    (strncmp(dki_info.dki_dname, "md", 3) == 0)) {
1394 		md_flag = 1;
1395 	}
1396 
1397 	if (check_input(vtoc)) {
1398 		/*
1399 		 * not valid; if it's a metadevice just pass it down
1400 		 * because SVM will do its own checking
1401 		 */
1402 		if (md_flag == 0) {
1403 			return (VT_EINVAL);
1404 		}
1405 	}
1406 
1407 	dk_ioc.dki_lba = 1;
1408 	if (NBLOCKS(vtoc->efi_nparts, vtoc->efi_lbasize) < 34) {
1409 		dk_ioc.dki_length = EFI_MIN_ARRAY_SIZE + vtoc->efi_lbasize;
1410 	} else {
1411 		dk_ioc.dki_length = NBLOCKS(vtoc->efi_nparts,
1412 		    vtoc->efi_lbasize) *
1413 		    vtoc->efi_lbasize;
1414 	}
1415 
1416 	/*
1417 	 * the number of blocks occupied by GUID partition entry array
1418 	 */
1419 	nblocks = dk_ioc.dki_length / vtoc->efi_lbasize - 1;
1420 
1421 	/*
1422 	 * Backup GPT header is located on the block after GUID
1423 	 * partition entry array. Here, we calculate the address
1424 	 * for backup GPT header.
1425 	 */
1426 	lba_backup_gpt_hdr = vtoc->efi_last_u_lba + 1 + nblocks;
1427 	if (posix_memalign((void **)&dk_ioc.dki_data,
1428 	    vtoc->efi_lbasize, dk_ioc.dki_length))
1429 		return (VT_ERROR);
1430 
1431 	memset(dk_ioc.dki_data, 0, dk_ioc.dki_length);
1432 	efi = dk_ioc.dki_data;
1433 
1434 	/* stuff user's input into EFI struct */
1435 	efi->efi_gpt_Signature = LE_64(EFI_SIGNATURE);
1436 	efi->efi_gpt_Revision = LE_32(vtoc->efi_version); /* 0x02000100 */
1437 	efi->efi_gpt_HeaderSize = LE_32(sizeof (struct efi_gpt) - LEN_EFI_PAD);
1438 	efi->efi_gpt_Reserved1 = 0;
1439 	efi->efi_gpt_MyLBA = LE_64(1ULL);
1440 	efi->efi_gpt_AlternateLBA = LE_64(lba_backup_gpt_hdr);
1441 	efi->efi_gpt_FirstUsableLBA = LE_64(vtoc->efi_first_u_lba);
1442 	efi->efi_gpt_LastUsableLBA = LE_64(vtoc->efi_last_u_lba);
1443 	efi->efi_gpt_PartitionEntryLBA = LE_64(2ULL);
1444 	efi->efi_gpt_NumberOfPartitionEntries = LE_32(vtoc->efi_nparts);
1445 	efi->efi_gpt_SizeOfPartitionEntry = LE_32(sizeof (struct efi_gpe));
1446 	UUID_LE_CONVERT(efi->efi_gpt_DiskGUID, vtoc->efi_disk_uguid);
1447 
1448 	/* LINTED -- always longlong aligned */
1449 	efi_parts = (efi_gpe_t *)((char *)dk_ioc.dki_data + vtoc->efi_lbasize);
1450 
1451 	for (i = 0; i < vtoc->efi_nparts; i++) {
1452 		for (j = 0;
1453 		    j < sizeof (conversion_array) /
1454 		    sizeof (struct uuid_to_ptag); j++) {
1455 
1456 			if (vtoc->efi_parts[i].p_tag == j) {
1457 				UUID_LE_CONVERT(
1458 				    efi_parts[i].efi_gpe_PartitionTypeGUID,
1459 				    conversion_array[j].uuid);
1460 				break;
1461 			}
1462 		}
1463 
1464 		if (j == sizeof (conversion_array) /
1465 		    sizeof (struct uuid_to_ptag)) {
1466 			/*
1467 			 * If we didn't have a matching uuid match, bail here.
1468 			 * Don't write a label with unknown uuid.
1469 			 */
1470 			if (efi_debug) {
1471 				(void) fprintf(stderr,
1472 				    "Unknown uuid for p_tag %d\n",
1473 				    vtoc->efi_parts[i].p_tag);
1474 			}
1475 			return (VT_EINVAL);
1476 		}
1477 
1478 		/* Zero's should be written for empty partitions */
1479 		if (vtoc->efi_parts[i].p_tag == V_UNASSIGNED)
1480 			continue;
1481 
1482 		efi_parts[i].efi_gpe_StartingLBA =
1483 		    LE_64(vtoc->efi_parts[i].p_start);
1484 		efi_parts[i].efi_gpe_EndingLBA =
1485 		    LE_64(vtoc->efi_parts[i].p_start +
1486 		    vtoc->efi_parts[i].p_size - 1);
1487 		efi_parts[i].efi_gpe_Attributes.PartitionAttrs =
1488 		    LE_16(vtoc->efi_parts[i].p_flag);
1489 		for (j = 0; j < EFI_PART_NAME_LEN; j++) {
1490 			efi_parts[i].efi_gpe_PartitionName[j] =
1491 			    LE_16((ushort_t)vtoc->efi_parts[i].p_name[j]);
1492 		}
1493 		if ((vtoc->efi_parts[i].p_tag != V_UNASSIGNED) &&
1494 		    uuid_is_null((uchar_t *)&vtoc->efi_parts[i].p_uguid)) {
1495 			(void) uuid_generate((uchar_t *)
1496 			    &vtoc->efi_parts[i].p_uguid);
1497 		}
1498 		bcopy(&vtoc->efi_parts[i].p_uguid,
1499 		    &efi_parts[i].efi_gpe_UniquePartitionGUID,
1500 		    sizeof (uuid_t));
1501 	}
1502 	efi->efi_gpt_PartitionEntryArrayCRC32 =
1503 	    LE_32(efi_crc32((unsigned char *)efi_parts,
1504 	    vtoc->efi_nparts * (int)sizeof (struct efi_gpe)));
1505 	efi->efi_gpt_HeaderCRC32 =
1506 	    LE_32(efi_crc32((unsigned char *)efi,
1507 	    LE_32(efi->efi_gpt_HeaderSize)));
1508 
1509 	if (efi_ioctl(fd, DKIOCSETEFI, &dk_ioc) == -1) {
1510 		free(dk_ioc.dki_data);
1511 		switch (errno) {
1512 		case EIO:
1513 			return (VT_EIO);
1514 		case EINVAL:
1515 			return (VT_EINVAL);
1516 		default:
1517 			return (VT_ERROR);
1518 		}
1519 	}
1520 	/* if it's a metadevice we're done */
1521 	if (md_flag) {
1522 		free(dk_ioc.dki_data);
1523 		return (0);
1524 	}
1525 
1526 	/* write backup partition array */
1527 	dk_ioc.dki_lba = vtoc->efi_last_u_lba + 1;
1528 	dk_ioc.dki_length -= vtoc->efi_lbasize;
1529 	/* LINTED */
1530 	dk_ioc.dki_data = (efi_gpt_t *)((char *)dk_ioc.dki_data +
1531 	    vtoc->efi_lbasize);
1532 
1533 	if (efi_ioctl(fd, DKIOCSETEFI, &dk_ioc) == -1) {
1534 		/*
1535 		 * we wrote the primary label okay, so don't fail
1536 		 */
1537 		if (efi_debug) {
1538 			(void) fprintf(stderr,
1539 			    "write of backup partitions to block %llu "
1540 			    "failed, errno %d\n",
1541 			    vtoc->efi_last_u_lba + 1,
1542 			    errno);
1543 		}
1544 	}
1545 	/*
1546 	 * now swap MyLBA and AlternateLBA fields and write backup
1547 	 * partition table header
1548 	 */
1549 	dk_ioc.dki_lba = lba_backup_gpt_hdr;
1550 	dk_ioc.dki_length = vtoc->efi_lbasize;
1551 	/* LINTED */
1552 	dk_ioc.dki_data = (efi_gpt_t *)((char *)dk_ioc.dki_data -
1553 	    vtoc->efi_lbasize);
1554 	efi->efi_gpt_AlternateLBA = LE_64(1ULL);
1555 	efi->efi_gpt_MyLBA = LE_64(lba_backup_gpt_hdr);
1556 	efi->efi_gpt_PartitionEntryLBA = LE_64(vtoc->efi_last_u_lba + 1);
1557 	efi->efi_gpt_HeaderCRC32 = 0;
1558 	efi->efi_gpt_HeaderCRC32 =
1559 	    LE_32(efi_crc32((unsigned char *)dk_ioc.dki_data,
1560 	    LE_32(efi->efi_gpt_HeaderSize)));
1561 
1562 	if (efi_ioctl(fd, DKIOCSETEFI, &dk_ioc) == -1) {
1563 		if (efi_debug) {
1564 			(void) fprintf(stderr,
1565 			    "write of backup header to block %llu failed, "
1566 			    "errno %d\n",
1567 			    lba_backup_gpt_hdr,
1568 			    errno);
1569 		}
1570 	}
1571 	/* write the PMBR */
1572 	(void) write_pmbr(fd, vtoc);
1573 	free(dk_ioc.dki_data);
1574 
1575 	return (0);
1576 }
1577 
1578 void
1579 efi_free(struct dk_gpt *ptr)
1580 {
1581 	free(ptr);
1582 }
1583 
1584 /*
1585  * Input: File descriptor
1586  * Output: 1 if disk has an EFI label, or > 2TB with no VTOC or legacy MBR.
1587  * Otherwise 0.
1588  */
1589 int
1590 efi_type(int fd)
1591 {
1592 #if 0
1593 	struct vtoc vtoc;
1594 	struct extvtoc extvtoc;
1595 
1596 	if (ioctl(fd, DKIOCGEXTVTOC, &extvtoc) == -1) {
1597 		if (errno == ENOTSUP)
1598 			return (1);
1599 		else if (errno == ENOTTY) {
1600 			if (ioctl(fd, DKIOCGVTOC, &vtoc) == -1)
1601 				if (errno == ENOTSUP)
1602 					return (1);
1603 		}
1604 	}
1605 	return (0);
1606 #else
1607 	return (ENOSYS);
1608 #endif
1609 }
1610 
1611 void
1612 efi_err_check(struct dk_gpt *vtoc)
1613 {
1614 	int			resv_part = -1;
1615 	int			i, j;
1616 	diskaddr_t		istart, jstart, isize, jsize, endsect;
1617 	int			overlap = 0;
1618 
1619 	/*
1620 	 * make sure no partitions overlap
1621 	 */
1622 	for (i = 0; i < vtoc->efi_nparts; i++) {
1623 		/* It can't be unassigned and have an actual size */
1624 		if ((vtoc->efi_parts[i].p_tag == V_UNASSIGNED) &&
1625 		    (vtoc->efi_parts[i].p_size != 0)) {
1626 			(void) fprintf(stderr,
1627 			    "partition %d is \"unassigned\" but has a size "
1628 			    "of %llu\n", i, vtoc->efi_parts[i].p_size);
1629 		}
1630 		if (vtoc->efi_parts[i].p_tag == V_UNASSIGNED) {
1631 			continue;
1632 		}
1633 		if (vtoc->efi_parts[i].p_tag == V_RESERVED) {
1634 			if (resv_part != -1) {
1635 				(void) fprintf(stderr,
1636 				    "found duplicate reserved partition at "
1637 				    "%d\n", i);
1638 			}
1639 			resv_part = i;
1640 			if (vtoc->efi_parts[i].p_size != EFI_MIN_RESV_SIZE)
1641 				(void) fprintf(stderr,
1642 				    "Warning: reserved partition size must "
1643 				    "be %d sectors\n", EFI_MIN_RESV_SIZE);
1644 		}
1645 		if ((vtoc->efi_parts[i].p_start < vtoc->efi_first_u_lba) ||
1646 		    (vtoc->efi_parts[i].p_start > vtoc->efi_last_u_lba)) {
1647 			(void) fprintf(stderr,
1648 			    "Partition %d starts at %llu\n",
1649 			    i,
1650 			    vtoc->efi_parts[i].p_start);
1651 			(void) fprintf(stderr,
1652 			    "It must be between %llu and %llu.\n",
1653 			    vtoc->efi_first_u_lba,
1654 			    vtoc->efi_last_u_lba);
1655 		}
1656 		if ((vtoc->efi_parts[i].p_start +
1657 		    vtoc->efi_parts[i].p_size <
1658 		    vtoc->efi_first_u_lba) ||
1659 		    (vtoc->efi_parts[i].p_start +
1660 		    vtoc->efi_parts[i].p_size >
1661 		    vtoc->efi_last_u_lba + 1)) {
1662 			(void) fprintf(stderr,
1663 			    "Partition %d ends at %llu\n",
1664 			    i,
1665 			    vtoc->efi_parts[i].p_start +
1666 			    vtoc->efi_parts[i].p_size);
1667 			(void) fprintf(stderr,
1668 			    "It must be between %llu and %llu.\n",
1669 			    vtoc->efi_first_u_lba,
1670 			    vtoc->efi_last_u_lba);
1671 		}
1672 
1673 		for (j = 0; j < vtoc->efi_nparts; j++) {
1674 			isize = vtoc->efi_parts[i].p_size;
1675 			jsize = vtoc->efi_parts[j].p_size;
1676 			istart = vtoc->efi_parts[i].p_start;
1677 			jstart = vtoc->efi_parts[j].p_start;
1678 			if ((i != j) && (isize != 0) && (jsize != 0)) {
1679 				endsect = jstart + jsize -1;
1680 				if ((jstart <= istart) &&
1681 				    (istart <= endsect)) {
1682 					if (!overlap) {
1683 					(void) fprintf(stderr,
1684 					    "label error: EFI Labels do not "
1685 					    "support overlapping partitions\n");
1686 					}
1687 					(void) fprintf(stderr,
1688 					    "Partition %d overlaps partition "
1689 					    "%d.\n", i, j);
1690 					overlap = 1;
1691 				}
1692 			}
1693 		}
1694 	}
1695 	/* make sure there is a reserved partition */
1696 	if (resv_part == -1) {
1697 		(void) fprintf(stderr,
1698 		    "no reserved partition found\n");
1699 	}
1700 }
1701 
1702 /*
1703  * We need to get information necessary to construct a *new* efi
1704  * label type
1705  */
1706 int
1707 efi_auto_sense(int fd, struct dk_gpt **vtoc)
1708 {
1709 
1710 	int	i;
1711 
1712 	/*
1713 	 * Now build the default partition table
1714 	 */
1715 	if (efi_alloc_and_init(fd, EFI_NUMPAR, vtoc) != 0) {
1716 		if (efi_debug) {
1717 			(void) fprintf(stderr, "efi_alloc_and_init failed.\n");
1718 		}
1719 		return (-1);
1720 	}
1721 
1722 	for (i = 0; i < MIN((*vtoc)->efi_nparts, V_NUMPAR); i++) {
1723 		(*vtoc)->efi_parts[i].p_tag = default_vtoc_map[i].p_tag;
1724 		(*vtoc)->efi_parts[i].p_flag = default_vtoc_map[i].p_flag;
1725 		(*vtoc)->efi_parts[i].p_start = 0;
1726 		(*vtoc)->efi_parts[i].p_size = 0;
1727 	}
1728 	/*
1729 	 * Make constants first
1730 	 * and variable partitions later
1731 	 */
1732 
1733 	/* root partition - s0 128 MB */
1734 	(*vtoc)->efi_parts[0].p_start = 34;
1735 	(*vtoc)->efi_parts[0].p_size = 262144;
1736 
1737 	/* partition - s1  128 MB */
1738 	(*vtoc)->efi_parts[1].p_start = 262178;
1739 	(*vtoc)->efi_parts[1].p_size = 262144;
1740 
1741 	/* partition -s2 is NOT the Backup disk */
1742 	(*vtoc)->efi_parts[2].p_tag = V_UNASSIGNED;
1743 
1744 	/* partition -s6 /usr partition - HOG */
1745 	(*vtoc)->efi_parts[6].p_start = 524322;
1746 	(*vtoc)->efi_parts[6].p_size = (*vtoc)->efi_last_u_lba - 524322
1747 	    - (1024 * 16);
1748 
1749 	/* efi reserved partition - s9 16K */
1750 	(*vtoc)->efi_parts[8].p_start = (*vtoc)->efi_last_u_lba - (1024 * 16);
1751 	(*vtoc)->efi_parts[8].p_size = (1024 * 16);
1752 	(*vtoc)->efi_parts[8].p_tag = V_RESERVED;
1753 	return (0);
1754 }
1755