xref: /titanic_51/usr/src/lib/libefi/common/rdwr_efi.c (revision c5f9a89643b6d7175323dcb29f1a665661143c67)
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 2009 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <errno.h>
30 #include <strings.h>
31 #include <unistd.h>
32 #include <uuid/uuid.h>
33 #include <libintl.h>
34 #include <sys/types.h>
35 #include <sys/dkio.h>
36 #include <sys/vtoc.h>
37 #include <sys/mhd.h>
38 #include <sys/param.h>
39 #include <sys/dktp/fdisk.h>
40 #include <sys/efi_partition.h>
41 #include <sys/byteorder.h>
42 #include <sys/ddi.h>
43 
44 static struct uuid_to_ptag {
45 	struct uuid	uuid;
46 } conversion_array[] = {
47 	{ EFI_UNUSED },
48 	{ EFI_BOOT },
49 	{ EFI_ROOT },
50 	{ EFI_SWAP },
51 	{ EFI_USR },
52 	{ EFI_BACKUP },
53 	{ 0 },			/* STAND is never used */
54 	{ EFI_VAR },
55 	{ EFI_HOME },
56 	{ EFI_ALTSCTR },
57 	{ 0 },			/* CACHE (cachefs) is never used */
58 	{ EFI_RESERVED },
59 	{ EFI_SYSTEM },
60 	{ EFI_LEGACY_MBR },
61 	{ EFI_RESV3 },
62 	{ EFI_RESV4 },
63 	{ EFI_MSFT_RESV },
64 	{ EFI_DELL_BASIC },
65 	{ EFI_DELL_RAID },
66 	{ EFI_DELL_SWAP },
67 	{ EFI_DELL_LVM },
68 	{ EFI_DELL_RESV },
69 	{ EFI_AAPL_HFS },
70 	{ EFI_AAPL_UFS }
71 };
72 
73 /*
74  * Default vtoc information for non-SVr4 partitions
75  */
76 struct dk_map2  default_vtoc_map[NDKMAP] = {
77 	{	V_ROOT,		0	},		/* a - 0 */
78 	{	V_SWAP,		V_UNMNT	},		/* b - 1 */
79 	{	V_BACKUP,	V_UNMNT	},		/* c - 2 */
80 	{	V_UNASSIGNED,	0	},		/* d - 3 */
81 	{	V_UNASSIGNED,	0	},		/* e - 4 */
82 	{	V_UNASSIGNED,	0	},		/* f - 5 */
83 	{	V_USR,		0	},		/* g - 6 */
84 	{	V_UNASSIGNED,	0	},		/* h - 7 */
85 
86 #if defined(_SUNOS_VTOC_16)
87 
88 #if defined(i386) || defined(__amd64)
89 	{	V_BOOT,		V_UNMNT	},		/* i - 8 */
90 	{	V_ALTSCTR,	0	},		/* j - 9 */
91 
92 #else
93 #error No VTOC format defined.
94 #endif			/* defined(i386) */
95 
96 	{	V_UNASSIGNED,	0	},		/* k - 10 */
97 	{	V_UNASSIGNED,	0	},		/* l - 11 */
98 	{	V_UNASSIGNED,	0	},		/* m - 12 */
99 	{	V_UNASSIGNED,	0	},		/* n - 13 */
100 	{	V_UNASSIGNED,	0	},		/* o - 14 */
101 	{	V_UNASSIGNED,	0	},		/* p - 15 */
102 #endif			/* defined(_SUNOS_VTOC_16) */
103 };
104 
105 #ifdef DEBUG
106 int efi_debug = 1;
107 #else
108 int efi_debug = 0;
109 #endif
110 
111 extern unsigned int	efi_crc32(const unsigned char *, unsigned int);
112 static int		efi_read(int, struct dk_gpt *);
113 
114 static int
115 read_disk_info(int fd, diskaddr_t *capacity, uint_t *lbsize)
116 {
117 	struct dk_minfo		disk_info;
118 
119 	if ((ioctl(fd, DKIOCGMEDIAINFO, (caddr_t)&disk_info)) == -1)
120 		return (errno);
121 	*capacity = disk_info.dki_capacity;
122 	*lbsize = disk_info.dki_lbsize;
123 	return (0);
124 }
125 
126 /*
127  * the number of blocks the EFI label takes up (round up to nearest
128  * block)
129  */
130 #define	NBLOCKS(p, l)	(1 + ((((p) * (int)sizeof (efi_gpe_t))  + \
131 				((l) - 1)) / (l)))
132 /* number of partitions -- limited by what we can malloc */
133 #define	MAX_PARTS	((4294967295UL - sizeof (struct dk_gpt)) / \
134 			    sizeof (struct dk_part))
135 
136 int
137 efi_alloc_and_init(int fd, uint32_t nparts, struct dk_gpt **vtoc)
138 {
139 	diskaddr_t	capacity;
140 	uint_t		lbsize;
141 	uint_t		nblocks;
142 	size_t		length;
143 	struct dk_gpt	*vptr;
144 	struct uuid	uuid;
145 
146 	if (read_disk_info(fd, &capacity, &lbsize) != 0) {
147 		if (efi_debug)
148 			(void) fprintf(stderr,
149 			    "couldn't read disk information\n");
150 		return (-1);
151 	}
152 
153 	nblocks = NBLOCKS(nparts, lbsize);
154 	if ((nblocks * lbsize) < EFI_MIN_ARRAY_SIZE + lbsize) {
155 		/* 16K plus one block for the GPT */
156 		nblocks = EFI_MIN_ARRAY_SIZE / lbsize + 1;
157 	}
158 
159 	if (nparts > MAX_PARTS) {
160 		if (efi_debug) {
161 			(void) fprintf(stderr,
162 			"the maximum number of partitions supported is %lu\n",
163 			    MAX_PARTS);
164 		}
165 		return (-1);
166 	}
167 
168 	length = sizeof (struct dk_gpt) +
169 	    sizeof (struct dk_part) * (nparts - 1);
170 
171 	if ((*vtoc = calloc(length, 1)) == NULL)
172 		return (-1);
173 
174 	vptr = *vtoc;
175 
176 	vptr->efi_version = EFI_VERSION_CURRENT;
177 	vptr->efi_lbasize = lbsize;
178 	vptr->efi_nparts = nparts;
179 	/*
180 	 * add one block here for the PMBR; on disks with a 512 byte
181 	 * block size and 128 or fewer partitions, efi_first_u_lba
182 	 * should work out to "34"
183 	 */
184 	vptr->efi_first_u_lba = nblocks + 1;
185 	vptr->efi_last_lba = capacity - 1;
186 	vptr->efi_altern_lba = capacity -1;
187 	vptr->efi_last_u_lba = vptr->efi_last_lba - nblocks;
188 	(void) uuid_generate((uchar_t *)&uuid);
189 	UUID_LE_CONVERT(vptr->efi_disk_uguid, uuid);
190 	return (0);
191 }
192 
193 /*
194  * Read EFI - return partition number upon success.
195  */
196 int
197 efi_alloc_and_read(int fd, struct dk_gpt **vtoc)
198 {
199 	int			rval;
200 	uint32_t		nparts;
201 	int			length;
202 
203 	/* figure out the number of entries that would fit into 16K */
204 	nparts = EFI_MIN_ARRAY_SIZE / sizeof (efi_gpe_t);
205 	length = (int) sizeof (struct dk_gpt) +
206 	    (int) sizeof (struct dk_part) * (nparts - 1);
207 	if ((*vtoc = calloc(length, 1)) == NULL)
208 		return (VT_ERROR);
209 
210 	(*vtoc)->efi_nparts = nparts;
211 	rval = efi_read(fd, *vtoc);
212 
213 	if ((rval == VT_EINVAL) && (*vtoc)->efi_nparts > nparts) {
214 		void *tmp;
215 		length = (int) sizeof (struct dk_gpt) +
216 		    (int) sizeof (struct dk_part) *
217 		    ((*vtoc)->efi_nparts - 1);
218 		nparts = (*vtoc)->efi_nparts;
219 		if ((tmp = realloc(*vtoc, length)) == NULL) {
220 			free (*vtoc);
221 			*vtoc = NULL;
222 			return (VT_ERROR);
223 		} else {
224 			*vtoc = tmp;
225 			rval = efi_read(fd, *vtoc);
226 		}
227 	}
228 
229 	if (rval < 0) {
230 		if (efi_debug) {
231 			(void) fprintf(stderr,
232 			    "read of EFI table failed, rval=%d\n", rval);
233 		}
234 		free (*vtoc);
235 		*vtoc = NULL;
236 	}
237 
238 	return (rval);
239 }
240 
241 static int
242 efi_ioctl(int fd, int cmd, dk_efi_t *dk_ioc)
243 {
244 	void *data = dk_ioc->dki_data;
245 	int error;
246 
247 	dk_ioc->dki_data_64 = (uint64_t)(uintptr_t)data;
248 	error = ioctl(fd, cmd, (void *)dk_ioc);
249 	dk_ioc->dki_data = data;
250 
251 	return (error);
252 }
253 
254 static int
255 check_label(int fd, dk_efi_t *dk_ioc)
256 {
257 	efi_gpt_t		*efi;
258 	uint_t			crc;
259 
260 	if (efi_ioctl(fd, DKIOCGETEFI, dk_ioc) == -1) {
261 		switch (errno) {
262 		case EIO:
263 			return (VT_EIO);
264 		default:
265 			return (VT_ERROR);
266 		}
267 	}
268 	efi = dk_ioc->dki_data;
269 	if (efi->efi_gpt_Signature != LE_64(EFI_SIGNATURE)) {
270 		if (efi_debug)
271 			(void) fprintf(stderr,
272 			    "Bad EFI signature: 0x%llx != 0x%llx\n",
273 			    (long long)efi->efi_gpt_Signature,
274 			    (long long)LE_64(EFI_SIGNATURE));
275 		return (VT_EINVAL);
276 	}
277 
278 	/*
279 	 * check CRC of the header; the size of the header should
280 	 * never be larger than one block
281 	 */
282 	crc = efi->efi_gpt_HeaderCRC32;
283 	efi->efi_gpt_HeaderCRC32 = 0;
284 
285 	if (((len_t)LE_32(efi->efi_gpt_HeaderSize) > dk_ioc->dki_length) ||
286 	    crc != LE_32(efi_crc32((unsigned char *)efi,
287 	    LE_32(efi->efi_gpt_HeaderSize)))) {
288 		if (efi_debug)
289 			(void) fprintf(stderr,
290 			    "Bad EFI CRC: 0x%x != 0x%x\n",
291 			    crc,
292 			    LE_32(efi_crc32((unsigned char *)efi,
293 			    sizeof (struct efi_gpt))));
294 		return (VT_EINVAL);
295 	}
296 
297 	return (0);
298 }
299 
300 static int
301 efi_read(int fd, struct dk_gpt *vtoc)
302 {
303 	int			i, j;
304 	int			label_len;
305 	int			rval = 0;
306 	int			md_flag = 0;
307 	int			vdc_flag = 0;
308 	struct dk_minfo		disk_info;
309 	dk_efi_t		dk_ioc;
310 	efi_gpt_t		*efi;
311 	efi_gpe_t		*efi_parts;
312 	struct dk_cinfo		dki_info;
313 	uint32_t		user_length;
314 	boolean_t		legacy_label = B_FALSE;
315 
316 	/*
317 	 * get the partition number for this file descriptor.
318 	 */
319 	if (ioctl(fd, DKIOCINFO, (caddr_t)&dki_info) == -1) {
320 		if (efi_debug) {
321 			(void) fprintf(stderr, "DKIOCINFO errno 0x%x\n", errno);
322 		}
323 		switch (errno) {
324 		case EIO:
325 			return (VT_EIO);
326 		case EINVAL:
327 			return (VT_EINVAL);
328 		default:
329 			return (VT_ERROR);
330 		}
331 	}
332 	if ((strncmp(dki_info.dki_cname, "pseudo", 7) == 0) &&
333 	    (strncmp(dki_info.dki_dname, "md", 3) == 0)) {
334 		md_flag++;
335 	} else if ((strncmp(dki_info.dki_cname, "vdc", 4) == 0) &&
336 	    (strncmp(dki_info.dki_dname, "vdc", 4) == 0)) {
337 		/*
338 		 * The controller and drive name "vdc" (virtual disk client)
339 		 * indicates a LDoms virtual disk.
340 		 */
341 		vdc_flag++;
342 	}
343 
344 	/* get the LBA size */
345 	if (ioctl(fd, DKIOCGMEDIAINFO, (caddr_t)&disk_info) == -1) {
346 		if (efi_debug) {
347 			(void) fprintf(stderr,
348 			    "assuming LBA 512 bytes %d\n",
349 			    errno);
350 		}
351 		disk_info.dki_lbsize = DEV_BSIZE;
352 	}
353 	if (disk_info.dki_lbsize == 0) {
354 		if (efi_debug) {
355 			(void) fprintf(stderr,
356 			    "efi_read: assuming LBA 512 bytes\n");
357 		}
358 		disk_info.dki_lbsize = DEV_BSIZE;
359 	}
360 	/*
361 	 * Read the EFI GPT to figure out how many partitions we need
362 	 * to deal with.
363 	 */
364 	dk_ioc.dki_lba = 1;
365 	if (NBLOCKS(vtoc->efi_nparts, disk_info.dki_lbsize) < 34) {
366 		label_len = EFI_MIN_ARRAY_SIZE + disk_info.dki_lbsize;
367 	} else {
368 		label_len = vtoc->efi_nparts * (int) sizeof (efi_gpe_t) +
369 		    disk_info.dki_lbsize;
370 		if (label_len % disk_info.dki_lbsize) {
371 			/* pad to physical sector size */
372 			label_len += disk_info.dki_lbsize;
373 			label_len &= ~(disk_info.dki_lbsize - 1);
374 		}
375 	}
376 
377 	if ((dk_ioc.dki_data = calloc(label_len, 1)) == NULL)
378 		return (VT_ERROR);
379 
380 	dk_ioc.dki_length = disk_info.dki_lbsize;
381 	user_length = vtoc->efi_nparts;
382 	efi = dk_ioc.dki_data;
383 	if (md_flag) {
384 		dk_ioc.dki_length = label_len;
385 		if (efi_ioctl(fd, DKIOCGETEFI, &dk_ioc) == -1) {
386 			switch (errno) {
387 			case EIO:
388 				return (VT_EIO);
389 			default:
390 				return (VT_ERROR);
391 			}
392 		}
393 	} else if ((rval = check_label(fd, &dk_ioc)) == VT_EINVAL) {
394 		/*
395 		 * No valid label here; try the alternate. Note that here
396 		 * we just read GPT header and save it into dk_ioc.data,
397 		 * Later, we will read GUID partition entry array if we
398 		 * can get valid GPT header.
399 		 */
400 
401 		/*
402 		 * This is a workaround for legacy systems. In the past, the
403 		 * last sector of SCSI disk was invisible on x86 platform. At
404 		 * that time, backup label was saved on the next to the last
405 		 * sector. It is possible for users to move a disk from previous
406 		 * solaris system to present system. Here, we attempt to search
407 		 * legacy backup EFI label first.
408 		 */
409 		dk_ioc.dki_lba = disk_info.dki_capacity - 2;
410 		dk_ioc.dki_length = disk_info.dki_lbsize;
411 		rval = check_label(fd, &dk_ioc);
412 		if (rval == VT_EINVAL) {
413 			/*
414 			 * we didn't find legacy backup EFI label, try to
415 			 * search backup EFI label in the last block.
416 			 */
417 			dk_ioc.dki_lba = disk_info.dki_capacity - 1;
418 			dk_ioc.dki_length = disk_info.dki_lbsize;
419 			rval = check_label(fd, &dk_ioc);
420 			if (rval == 0) {
421 				legacy_label = B_TRUE;
422 				if (efi_debug)
423 					(void) fprintf(stderr,
424 					    "efi_read: primary label corrupt; "
425 					    "using EFI backup label located on"
426 					    " the last block\n");
427 			}
428 		} else {
429 			if ((efi_debug) && (rval == 0))
430 				(void) fprintf(stderr, "efi_read: primary label"
431 				    " corrupt; using legacy EFI backup label "
432 				    " located on the next to last block\n");
433 		}
434 
435 		if (rval == 0) {
436 			dk_ioc.dki_lba = LE_64(efi->efi_gpt_PartitionEntryLBA);
437 			vtoc->efi_flags |= EFI_GPT_PRIMARY_CORRUPT;
438 			vtoc->efi_nparts =
439 			    LE_32(efi->efi_gpt_NumberOfPartitionEntries);
440 
441 			/*
442 			 * Partition tables are between backup GPT header
443 			 * table and ParitionEntryLBA (the starting LBA of
444 			 * the GUID partition entries array). Now that we
445 			 * already got valid GPT header and saved it in
446 			 * dk_ioc.dki_data, we try to get GUID partition
447 			 * entry array here.
448 			 */
449 			dk_ioc.dki_data++;
450 			if (legacy_label)
451 				dk_ioc.dki_length = disk_info.dki_capacity - 1 -
452 				    dk_ioc.dki_lba;
453 			else
454 				dk_ioc.dki_length = disk_info.dki_capacity - 2 -
455 				    dk_ioc.dki_lba;
456 			dk_ioc.dki_length *= disk_info.dki_lbsize;
457 			if (dk_ioc.dki_length >
458 			    ((len_t)label_len - sizeof (*dk_ioc.dki_data))) {
459 				rval = VT_EINVAL;
460 			} else {
461 				/*
462 				 * read GUID partition entry array
463 				 */
464 				rval = efi_ioctl(fd, DKIOCGETEFI, &dk_ioc);
465 			}
466 		}
467 
468 	} else if (rval == 0) {
469 
470 		dk_ioc.dki_lba = LE_64(efi->efi_gpt_PartitionEntryLBA);
471 		dk_ioc.dki_data++;
472 		dk_ioc.dki_length = label_len - disk_info.dki_lbsize;
473 		rval = efi_ioctl(fd, DKIOCGETEFI, &dk_ioc);
474 
475 	} else if (vdc_flag && rval == VT_ERROR && errno == EINVAL) {
476 		/*
477 		 * When the device is a LDoms virtual disk, the DKIOCGETEFI
478 		 * ioctl can fail with EINVAL if the virtual disk backend
479 		 * is a ZFS volume serviced by a domain running an old version
480 		 * of Solaris. This is because the DKIOCGETEFI ioctl was
481 		 * initially incorrectly implemented for a ZFS volume and it
482 		 * expected the GPT and GPE to be retrieved with a single ioctl.
483 		 * So we try to read the GPT and the GPE using that old style
484 		 * ioctl.
485 		 */
486 		dk_ioc.dki_lba = 1;
487 		dk_ioc.dki_length = label_len;
488 		rval = check_label(fd, &dk_ioc);
489 	}
490 
491 	if (rval < 0) {
492 		free(efi);
493 		return (rval);
494 	}
495 
496 	/* LINTED -- always longlong aligned */
497 	efi_parts = (efi_gpe_t *)(((char *)efi) + disk_info.dki_lbsize);
498 
499 	/*
500 	 * Assemble this into a "dk_gpt" struct for easier
501 	 * digestibility by applications.
502 	 */
503 	vtoc->efi_version = LE_32(efi->efi_gpt_Revision);
504 	vtoc->efi_nparts = LE_32(efi->efi_gpt_NumberOfPartitionEntries);
505 	vtoc->efi_part_size = LE_32(efi->efi_gpt_SizeOfPartitionEntry);
506 	vtoc->efi_lbasize = disk_info.dki_lbsize;
507 	vtoc->efi_last_lba = disk_info.dki_capacity - 1;
508 	vtoc->efi_first_u_lba = LE_64(efi->efi_gpt_FirstUsableLBA);
509 	vtoc->efi_last_u_lba = LE_64(efi->efi_gpt_LastUsableLBA);
510 	vtoc->efi_altern_lba = LE_64(efi->efi_gpt_AlternateLBA);
511 	UUID_LE_CONVERT(vtoc->efi_disk_uguid, efi->efi_gpt_DiskGUID);
512 
513 	/*
514 	 * If the array the user passed in is too small, set the length
515 	 * to what it needs to be and return
516 	 */
517 	if (user_length < vtoc->efi_nparts) {
518 		return (VT_EINVAL);
519 	}
520 
521 	for (i = 0; i < vtoc->efi_nparts; i++) {
522 
523 		UUID_LE_CONVERT(vtoc->efi_parts[i].p_guid,
524 		    efi_parts[i].efi_gpe_PartitionTypeGUID);
525 
526 		for (j = 0;
527 		    j < sizeof (conversion_array)
528 		    / sizeof (struct uuid_to_ptag); j++) {
529 
530 			if (bcmp(&vtoc->efi_parts[i].p_guid,
531 			    &conversion_array[j].uuid,
532 			    sizeof (struct uuid)) == 0) {
533 				vtoc->efi_parts[i].p_tag = j;
534 				break;
535 			}
536 		}
537 		if (vtoc->efi_parts[i].p_tag == V_UNASSIGNED)
538 			continue;
539 		vtoc->efi_parts[i].p_flag =
540 		    LE_16(efi_parts[i].efi_gpe_Attributes.PartitionAttrs);
541 		vtoc->efi_parts[i].p_start =
542 		    LE_64(efi_parts[i].efi_gpe_StartingLBA);
543 		vtoc->efi_parts[i].p_size =
544 		    LE_64(efi_parts[i].efi_gpe_EndingLBA) -
545 		    vtoc->efi_parts[i].p_start + 1;
546 		for (j = 0; j < EFI_PART_NAME_LEN; j++) {
547 			vtoc->efi_parts[i].p_name[j] =
548 			    (uchar_t)LE_16(
549 			    efi_parts[i].efi_gpe_PartitionName[j]);
550 		}
551 
552 		UUID_LE_CONVERT(vtoc->efi_parts[i].p_uguid,
553 		    efi_parts[i].efi_gpe_UniquePartitionGUID);
554 	}
555 	free(efi);
556 
557 	return (dki_info.dki_partition);
558 }
559 
560 /* writes a "protective" MBR */
561 static int
562 write_pmbr(int fd, struct dk_gpt *vtoc)
563 {
564 	dk_efi_t	dk_ioc;
565 	struct mboot	mb;
566 	uchar_t		*cp;
567 	diskaddr_t	size_in_lba;
568 
569 	/*
570 	 * Preserve any boot code and disk signature if the first block is
571 	 * already an MBR.
572 	 */
573 	dk_ioc.dki_lba = 0;
574 	dk_ioc.dki_length = sizeof (mb);
575 	/* LINTED -- always longlong aligned */
576 	dk_ioc.dki_data = (efi_gpt_t *)&mb;
577 	if (efi_ioctl(fd, DKIOCGETEFI, &dk_ioc) == -1 ||
578 	    mb.signature != LE_16(MBB_MAGIC)) {
579 		bzero(&mb, sizeof (mb));
580 		mb.signature = LE_16(MBB_MAGIC);
581 	}
582 	bzero(&mb.parts, sizeof (mb.parts));
583 	cp = (uchar_t *)&mb.parts[0];
584 	/* bootable or not */
585 	*cp++ = 0;
586 	/* beginning CHS; 0xffffff if not representable */
587 	*cp++ = 0xff;
588 	*cp++ = 0xff;
589 	*cp++ = 0xff;
590 	/* OS type */
591 	*cp++ = EFI_PMBR;
592 	/* ending CHS; 0xffffff if not representable */
593 	*cp++ = 0xff;
594 	*cp++ = 0xff;
595 	*cp++ = 0xff;
596 	/* starting LBA: 1 (little endian format) by EFI definition */
597 	*cp++ = 0x01;
598 	*cp++ = 0x00;
599 	*cp++ = 0x00;
600 	*cp++ = 0x00;
601 	/* ending LBA: last block on the disk (little endian format) */
602 	size_in_lba = vtoc->efi_last_lba;
603 	if (size_in_lba < 0xffffffff) {
604 		*cp++ = (size_in_lba & 0x000000ff);
605 		*cp++ = (size_in_lba & 0x0000ff00) >> 8;
606 		*cp++ = (size_in_lba & 0x00ff0000) >> 16;
607 		*cp++ = (size_in_lba & 0xff000000) >> 24;
608 	} else {
609 		*cp++ = 0xff;
610 		*cp++ = 0xff;
611 		*cp++ = 0xff;
612 		*cp++ = 0xff;
613 	}
614 	/* LINTED -- always longlong aligned */
615 	dk_ioc.dki_data = (efi_gpt_t *)&mb;
616 	dk_ioc.dki_lba = 0;
617 	dk_ioc.dki_length = sizeof (mb);
618 	if (efi_ioctl(fd, DKIOCSETEFI, &dk_ioc) == -1) {
619 		switch (errno) {
620 		case EIO:
621 			return (VT_EIO);
622 		case EINVAL:
623 			return (VT_EINVAL);
624 		default:
625 			return (VT_ERROR);
626 		}
627 	}
628 	return (0);
629 }
630 
631 /* make sure the user specified something reasonable */
632 static int
633 check_input(struct dk_gpt *vtoc)
634 {
635 	int			resv_part = -1;
636 	int			i, j;
637 	diskaddr_t		istart, jstart, isize, jsize, endsect;
638 
639 	/*
640 	 * Sanity-check the input (make sure no partitions overlap)
641 	 */
642 	for (i = 0; i < vtoc->efi_nparts; i++) {
643 		/* It can't be unassigned and have an actual size */
644 		if ((vtoc->efi_parts[i].p_tag == V_UNASSIGNED) &&
645 		    (vtoc->efi_parts[i].p_size != 0)) {
646 			if (efi_debug) {
647 				(void) fprintf(stderr,
648 "partition %d is \"unassigned\" but has a size of %llu",
649 				    i,
650 				    vtoc->efi_parts[i].p_size);
651 			}
652 			return (VT_EINVAL);
653 		}
654 		if (vtoc->efi_parts[i].p_tag == V_UNASSIGNED) {
655 			if (uuid_is_null((uchar_t *)&vtoc->efi_parts[i].p_guid))
656 				continue;
657 			/* we have encountered an unknown uuid */
658 			vtoc->efi_parts[i].p_tag = 0xff;
659 		}
660 		if (vtoc->efi_parts[i].p_tag == V_RESERVED) {
661 			if (resv_part != -1) {
662 				if (efi_debug) {
663 					(void) fprintf(stderr,
664 "found duplicate reserved partition at %d\n",
665 					    i);
666 				}
667 				return (VT_EINVAL);
668 			}
669 			resv_part = i;
670 		}
671 		if ((vtoc->efi_parts[i].p_start < vtoc->efi_first_u_lba) ||
672 		    (vtoc->efi_parts[i].p_start > vtoc->efi_last_u_lba)) {
673 			if (efi_debug) {
674 				(void) fprintf(stderr,
675 				    "Partition %d starts at %llu.  ",
676 				    i,
677 				    vtoc->efi_parts[i].p_start);
678 				(void) fprintf(stderr,
679 				    "It must be between %llu and %llu.\n",
680 				    vtoc->efi_first_u_lba,
681 				    vtoc->efi_last_u_lba);
682 			}
683 			return (VT_EINVAL);
684 		}
685 		if ((vtoc->efi_parts[i].p_start +
686 		    vtoc->efi_parts[i].p_size <
687 		    vtoc->efi_first_u_lba) ||
688 		    (vtoc->efi_parts[i].p_start +
689 		    vtoc->efi_parts[i].p_size >
690 		    vtoc->efi_last_u_lba + 1)) {
691 			if (efi_debug) {
692 				(void) fprintf(stderr,
693 				    "Partition %d ends at %llu.  ",
694 				    i,
695 				    vtoc->efi_parts[i].p_start +
696 				    vtoc->efi_parts[i].p_size);
697 				(void) fprintf(stderr,
698 				    "It must be between %llu and %llu.\n",
699 				    vtoc->efi_first_u_lba,
700 				    vtoc->efi_last_u_lba);
701 			}
702 			return (VT_EINVAL);
703 		}
704 
705 		for (j = 0; j < vtoc->efi_nparts; j++) {
706 			isize = vtoc->efi_parts[i].p_size;
707 			jsize = vtoc->efi_parts[j].p_size;
708 			istart = vtoc->efi_parts[i].p_start;
709 			jstart = vtoc->efi_parts[j].p_start;
710 			if ((i != j) && (isize != 0) && (jsize != 0)) {
711 				endsect = jstart + jsize -1;
712 				if ((jstart <= istart) &&
713 				    (istart <= endsect)) {
714 					if (efi_debug) {
715 						(void) fprintf(stderr,
716 "Partition %d overlaps partition %d.",
717 						    i, j);
718 					}
719 					return (VT_EINVAL);
720 				}
721 			}
722 		}
723 	}
724 	/* just a warning for now */
725 	if ((resv_part == -1) && efi_debug) {
726 		(void) fprintf(stderr,
727 		    "no reserved partition found\n");
728 	}
729 	return (0);
730 }
731 
732 /*
733  * add all the unallocated space to the current label
734  */
735 int
736 efi_use_whole_disk(int fd)
737 {
738 	struct dk_gpt		*efi_label;
739 	int			rval;
740 	int			i;
741 	uint_t			phy_last_slice = 0;
742 	diskaddr_t		pl_start = 0;
743 	diskaddr_t		pl_size;
744 
745 	rval = efi_alloc_and_read(fd, &efi_label);
746 	if (rval < 0) {
747 		return (rval);
748 	}
749 
750 	/* find the last physically non-zero partition */
751 	for (i = 0; i < efi_label->efi_nparts - 2; i ++) {
752 		if (pl_start < efi_label->efi_parts[i].p_start) {
753 			pl_start = efi_label->efi_parts[i].p_start;
754 			phy_last_slice = i;
755 		}
756 	}
757 	pl_size = efi_label->efi_parts[phy_last_slice].p_size;
758 
759 	/*
760 	 * If alter_lba is 1, we are using the backup label.
761 	 * Since we can locate the backup label by disk capacity,
762 	 * there must be no unallocated space.
763 	 */
764 	if ((efi_label->efi_altern_lba == 1) || (efi_label->efi_altern_lba
765 	    >= efi_label->efi_last_lba)) {
766 		if (efi_debug) {
767 			(void) fprintf(stderr,
768 			    "efi_use_whole_disk: requested space not found\n");
769 		}
770 		efi_free(efi_label);
771 		return (VT_ENOSPC);
772 	}
773 
774 	/*
775 	 * If there is space between the last physically non-zero partition
776 	 * and the reserved partition, just add the unallocated space to this
777 	 * area. Otherwise, the unallocated space is added to the last
778 	 * physically non-zero partition.
779 	 */
780 	if (pl_start + pl_size - 1 == efi_label->efi_last_u_lba -
781 	    EFI_MIN_RESV_SIZE) {
782 		efi_label->efi_parts[phy_last_slice].p_size +=
783 		    efi_label->efi_last_lba - efi_label->efi_altern_lba;
784 	}
785 
786 	/*
787 	 * Move the reserved partition. There is currently no data in
788 	 * here except fabricated devids (which get generated via
789 	 * efi_write()). So there is no need to copy data.
790 	 */
791 	efi_label->efi_parts[efi_label->efi_nparts - 1].p_start +=
792 	    efi_label->efi_last_lba - efi_label->efi_altern_lba;
793 	efi_label->efi_last_u_lba += efi_label->efi_last_lba
794 	    - efi_label->efi_altern_lba;
795 
796 	rval = efi_write(fd, efi_label);
797 	if (rval < 0) {
798 		if (efi_debug) {
799 			(void) fprintf(stderr,
800 			    "efi_use_whole_disk:fail to write label, rval=%d\n",
801 			    rval);
802 		}
803 		efi_free(efi_label);
804 		return (rval);
805 	}
806 
807 	efi_free(efi_label);
808 	return (0);
809 }
810 
811 
812 /*
813  * write EFI label and backup label
814  */
815 int
816 efi_write(int fd, struct dk_gpt *vtoc)
817 {
818 	dk_efi_t		dk_ioc;
819 	efi_gpt_t		*efi;
820 	efi_gpe_t		*efi_parts;
821 	int			i, j;
822 	struct dk_cinfo		dki_info;
823 	int			md_flag = 0;
824 	int			nblocks;
825 	diskaddr_t		lba_backup_gpt_hdr;
826 
827 	if (ioctl(fd, DKIOCINFO, (caddr_t)&dki_info) == -1) {
828 		if (efi_debug)
829 			(void) fprintf(stderr, "DKIOCINFO errno 0x%x\n", errno);
830 		switch (errno) {
831 		case EIO:
832 			return (VT_EIO);
833 		case EINVAL:
834 			return (VT_EINVAL);
835 		default:
836 			return (VT_ERROR);
837 		}
838 	}
839 
840 	/* check if we are dealing wih a metadevice */
841 	if ((strncmp(dki_info.dki_cname, "pseudo", 7) == 0) &&
842 	    (strncmp(dki_info.dki_dname, "md", 3) == 0)) {
843 		md_flag = 1;
844 	}
845 
846 	if (check_input(vtoc)) {
847 		/*
848 		 * not valid; if it's a metadevice just pass it down
849 		 * because SVM will do its own checking
850 		 */
851 		if (md_flag == 0) {
852 			return (VT_EINVAL);
853 		}
854 	}
855 
856 	dk_ioc.dki_lba = 1;
857 	if (NBLOCKS(vtoc->efi_nparts, vtoc->efi_lbasize) < 34) {
858 		dk_ioc.dki_length = EFI_MIN_ARRAY_SIZE + vtoc->efi_lbasize;
859 	} else {
860 		dk_ioc.dki_length = NBLOCKS(vtoc->efi_nparts,
861 		    vtoc->efi_lbasize) *
862 		    vtoc->efi_lbasize;
863 	}
864 
865 	/*
866 	 * the number of blocks occupied by GUID partition entry array
867 	 */
868 	nblocks = dk_ioc.dki_length / vtoc->efi_lbasize - 1;
869 
870 	/*
871 	 * Backup GPT header is located on the block after GUID
872 	 * partition entry array. Here, we calculate the address
873 	 * for backup GPT header.
874 	 */
875 	lba_backup_gpt_hdr = vtoc->efi_last_u_lba + 1 + nblocks;
876 
877 	if ((dk_ioc.dki_data = calloc(dk_ioc.dki_length, 1)) == NULL)
878 		return (VT_ERROR);
879 
880 	efi = dk_ioc.dki_data;
881 
882 	/* stuff user's input into EFI struct */
883 	efi->efi_gpt_Signature = LE_64(EFI_SIGNATURE);
884 	efi->efi_gpt_Revision = LE_32(vtoc->efi_version); /* 0x02000100 */
885 	efi->efi_gpt_HeaderSize = LE_32(sizeof (struct efi_gpt));
886 	efi->efi_gpt_Reserved1 = 0;
887 	efi->efi_gpt_MyLBA = LE_64(1ULL);
888 	efi->efi_gpt_AlternateLBA = LE_64(lba_backup_gpt_hdr);
889 	efi->efi_gpt_FirstUsableLBA = LE_64(vtoc->efi_first_u_lba);
890 	efi->efi_gpt_LastUsableLBA = LE_64(vtoc->efi_last_u_lba);
891 	efi->efi_gpt_PartitionEntryLBA = LE_64(2ULL);
892 	efi->efi_gpt_NumberOfPartitionEntries = LE_32(vtoc->efi_nparts);
893 	efi->efi_gpt_SizeOfPartitionEntry = LE_32(sizeof (struct efi_gpe));
894 	UUID_LE_CONVERT(efi->efi_gpt_DiskGUID, vtoc->efi_disk_uguid);
895 
896 	/* LINTED -- always longlong aligned */
897 	efi_parts = (efi_gpe_t *)((char *)dk_ioc.dki_data + sizeof (efi_gpt_t));
898 
899 	for (i = 0; i < vtoc->efi_nparts; i++) {
900 		for (j = 0;
901 		    j < sizeof (conversion_array) /
902 		    sizeof (struct uuid_to_ptag); j++) {
903 
904 			if (vtoc->efi_parts[i].p_tag == j) {
905 				UUID_LE_CONVERT(
906 				    efi_parts[i].efi_gpe_PartitionTypeGUID,
907 				    conversion_array[j].uuid);
908 				break;
909 			}
910 		}
911 
912 		if (j == sizeof (conversion_array) /
913 		    sizeof (struct uuid_to_ptag)) {
914 			/*
915 			 * If we didn't have a matching uuid match, bail here.
916 			 * Don't write a label with unknown uuid.
917 			 */
918 			if (efi_debug) {
919 				(void) fprintf(stderr,
920 				    "Unknown uuid for p_tag %d\n",
921 				    vtoc->efi_parts[i].p_tag);
922 			}
923 			return (VT_EINVAL);
924 		}
925 
926 		efi_parts[i].efi_gpe_StartingLBA =
927 		    LE_64(vtoc->efi_parts[i].p_start);
928 		efi_parts[i].efi_gpe_EndingLBA =
929 		    LE_64(vtoc->efi_parts[i].p_start +
930 		    vtoc->efi_parts[i].p_size - 1);
931 		efi_parts[i].efi_gpe_Attributes.PartitionAttrs =
932 		    LE_16(vtoc->efi_parts[i].p_flag);
933 		for (j = 0; j < EFI_PART_NAME_LEN; j++) {
934 			efi_parts[i].efi_gpe_PartitionName[j] =
935 			    LE_16((ushort_t)vtoc->efi_parts[i].p_name[j]);
936 		}
937 		if ((vtoc->efi_parts[i].p_tag != V_UNASSIGNED) &&
938 		    uuid_is_null((uchar_t *)&vtoc->efi_parts[i].p_uguid)) {
939 			(void) uuid_generate((uchar_t *)
940 			    &vtoc->efi_parts[i].p_uguid);
941 		}
942 		bcopy(&vtoc->efi_parts[i].p_uguid,
943 		    &efi_parts[i].efi_gpe_UniquePartitionGUID,
944 		    sizeof (uuid_t));
945 	}
946 	efi->efi_gpt_PartitionEntryArrayCRC32 =
947 	    LE_32(efi_crc32((unsigned char *)efi_parts,
948 	    vtoc->efi_nparts * (int)sizeof (struct efi_gpe)));
949 	efi->efi_gpt_HeaderCRC32 =
950 	    LE_32(efi_crc32((unsigned char *)efi, sizeof (struct efi_gpt)));
951 
952 	if (efi_ioctl(fd, DKIOCSETEFI, &dk_ioc) == -1) {
953 		free(dk_ioc.dki_data);
954 		switch (errno) {
955 		case EIO:
956 			return (VT_EIO);
957 		case EINVAL:
958 			return (VT_EINVAL);
959 		default:
960 			return (VT_ERROR);
961 		}
962 	}
963 	/* if it's a metadevice we're done */
964 	if (md_flag) {
965 		free(dk_ioc.dki_data);
966 		return (0);
967 	}
968 	/* write backup partition array */
969 	dk_ioc.dki_lba = vtoc->efi_last_u_lba + 1;
970 	dk_ioc.dki_length -= vtoc->efi_lbasize;
971 	dk_ioc.dki_data++;
972 	if (efi_ioctl(fd, DKIOCSETEFI, &dk_ioc) == -1) {
973 		/*
974 		 * we wrote the primary label okay, so don't fail
975 		 */
976 		if (efi_debug) {
977 			(void) fprintf(stderr,
978 			    "write of backup partitions to block %llu "
979 			    "failed, errno %d\n",
980 			    vtoc->efi_last_u_lba + 1,
981 			    errno);
982 		}
983 	}
984 	/*
985 	 * now swap MyLBA and AlternateLBA fields and write backup
986 	 * partition table header
987 	 */
988 	dk_ioc.dki_lba = lba_backup_gpt_hdr;
989 	dk_ioc.dki_length = vtoc->efi_lbasize;
990 	dk_ioc.dki_data--;
991 	efi->efi_gpt_AlternateLBA = LE_64(1ULL);
992 	efi->efi_gpt_MyLBA = LE_64(lba_backup_gpt_hdr);
993 	efi->efi_gpt_PartitionEntryLBA = LE_64(vtoc->efi_last_u_lba + 1);
994 	efi->efi_gpt_HeaderCRC32 = 0;
995 	efi->efi_gpt_HeaderCRC32 =
996 	    LE_32(efi_crc32((unsigned char *)dk_ioc.dki_data,
997 	    sizeof (struct efi_gpt)));
998 
999 	if (efi_ioctl(fd, DKIOCSETEFI, &dk_ioc) == -1) {
1000 		if (efi_debug) {
1001 			(void) fprintf(stderr,
1002 			    "write of backup header to block %llu failed, "
1003 			    "errno %d\n",
1004 			    lba_backup_gpt_hdr,
1005 			    errno);
1006 		}
1007 	}
1008 	/* write the PMBR */
1009 	(void) write_pmbr(fd, vtoc);
1010 	free(dk_ioc.dki_data);
1011 	return (0);
1012 }
1013 
1014 void
1015 efi_free(struct dk_gpt *ptr)
1016 {
1017 	free(ptr);
1018 }
1019 
1020 /*
1021  * Input: File descriptor
1022  * Output: 1 if disk has an EFI label, or > 2TB with no VTOC or legacy MBR.
1023  * Otherwise 0.
1024  */
1025 int
1026 efi_type(int fd)
1027 {
1028 	struct vtoc vtoc;
1029 	struct extvtoc extvtoc;
1030 
1031 	if (ioctl(fd, DKIOCGEXTVTOC, &extvtoc) == -1) {
1032 		if (errno == ENOTSUP)
1033 			return (1);
1034 		else if (errno == ENOTTY) {
1035 			if (ioctl(fd, DKIOCGVTOC, &vtoc) == -1)
1036 				if (errno == ENOTSUP)
1037 					return (1);
1038 		}
1039 	}
1040 	return (0);
1041 }
1042 
1043 void
1044 efi_err_check(struct dk_gpt *vtoc)
1045 {
1046 	int			resv_part = -1;
1047 	int			i, j;
1048 	diskaddr_t		istart, jstart, isize, jsize, endsect;
1049 	int			overlap = 0;
1050 
1051 	/*
1052 	 * make sure no partitions overlap
1053 	 */
1054 	for (i = 0; i < vtoc->efi_nparts; i++) {
1055 		/* It can't be unassigned and have an actual size */
1056 		if ((vtoc->efi_parts[i].p_tag == V_UNASSIGNED) &&
1057 		    (vtoc->efi_parts[i].p_size != 0)) {
1058 			(void) fprintf(stderr,
1059 			    "partition %d is \"unassigned\" but has a size "
1060 			    "of %llu\n", i, vtoc->efi_parts[i].p_size);
1061 		}
1062 		if (vtoc->efi_parts[i].p_tag == V_UNASSIGNED) {
1063 			continue;
1064 		}
1065 		if (vtoc->efi_parts[i].p_tag == V_RESERVED) {
1066 			if (resv_part != -1) {
1067 				(void) fprintf(stderr,
1068 				    "found duplicate reserved partition at "
1069 				    "%d\n", i);
1070 			}
1071 			resv_part = i;
1072 			if (vtoc->efi_parts[i].p_size != EFI_MIN_RESV_SIZE)
1073 				(void) fprintf(stderr,
1074 				    "Warning: reserved partition size must "
1075 				    "be %d sectors\n", EFI_MIN_RESV_SIZE);
1076 		}
1077 		if ((vtoc->efi_parts[i].p_start < vtoc->efi_first_u_lba) ||
1078 		    (vtoc->efi_parts[i].p_start > vtoc->efi_last_u_lba)) {
1079 			(void) fprintf(stderr,
1080 			    "Partition %d starts at %llu\n",
1081 			    i,
1082 			    vtoc->efi_parts[i].p_start);
1083 			(void) fprintf(stderr,
1084 			    "It must be between %llu and %llu.\n",
1085 			    vtoc->efi_first_u_lba,
1086 			    vtoc->efi_last_u_lba);
1087 		}
1088 		if ((vtoc->efi_parts[i].p_start +
1089 		    vtoc->efi_parts[i].p_size <
1090 		    vtoc->efi_first_u_lba) ||
1091 		    (vtoc->efi_parts[i].p_start +
1092 		    vtoc->efi_parts[i].p_size >
1093 		    vtoc->efi_last_u_lba + 1)) {
1094 			(void) fprintf(stderr,
1095 			    "Partition %d ends at %llu\n",
1096 			    i,
1097 			    vtoc->efi_parts[i].p_start +
1098 			    vtoc->efi_parts[i].p_size);
1099 			(void) fprintf(stderr,
1100 			    "It must be between %llu and %llu.\n",
1101 			    vtoc->efi_first_u_lba,
1102 			    vtoc->efi_last_u_lba);
1103 		}
1104 
1105 		for (j = 0; j < vtoc->efi_nparts; j++) {
1106 			isize = vtoc->efi_parts[i].p_size;
1107 			jsize = vtoc->efi_parts[j].p_size;
1108 			istart = vtoc->efi_parts[i].p_start;
1109 			jstart = vtoc->efi_parts[j].p_start;
1110 			if ((i != j) && (isize != 0) && (jsize != 0)) {
1111 				endsect = jstart + jsize -1;
1112 				if ((jstart <= istart) &&
1113 				    (istart <= endsect)) {
1114 					if (!overlap) {
1115 					(void) fprintf(stderr,
1116 					    "label error: EFI Labels do not "
1117 					    "support overlapping partitions\n");
1118 					}
1119 					(void) fprintf(stderr,
1120 					    "Partition %d overlaps partition "
1121 					    "%d.\n", i, j);
1122 					overlap = 1;
1123 				}
1124 			}
1125 		}
1126 	}
1127 	/* make sure there is a reserved partition */
1128 	if (resv_part == -1) {
1129 		(void) fprintf(stderr,
1130 		    "no reserved partition found\n");
1131 	}
1132 }
1133 
1134 /*
1135  * We need to get information necessary to construct a *new* efi
1136  * label type
1137  */
1138 int
1139 efi_auto_sense(int fd, struct dk_gpt **vtoc)
1140 {
1141 
1142 	int	i;
1143 
1144 	/*
1145 	 * Now build the default partition table
1146 	 */
1147 	if (efi_alloc_and_init(fd, EFI_NUMPAR, vtoc) != 0) {
1148 		if (efi_debug) {
1149 			(void) fprintf(stderr, "efi_alloc_and_init failed.\n");
1150 		}
1151 		return (-1);
1152 	}
1153 
1154 	for (i = 0; i < min((*vtoc)->efi_nparts, V_NUMPAR); i++) {
1155 		(*vtoc)->efi_parts[i].p_tag = default_vtoc_map[i].p_tag;
1156 		(*vtoc)->efi_parts[i].p_flag = default_vtoc_map[i].p_flag;
1157 		(*vtoc)->efi_parts[i].p_start = 0;
1158 		(*vtoc)->efi_parts[i].p_size = 0;
1159 	}
1160 	/*
1161 	 * Make constants first
1162 	 * and variable partitions later
1163 	 */
1164 
1165 	/* root partition - s0 128 MB */
1166 	(*vtoc)->efi_parts[0].p_start = 34;
1167 	(*vtoc)->efi_parts[0].p_size = 262144;
1168 
1169 	/* partition - s1  128 MB */
1170 	(*vtoc)->efi_parts[1].p_start = 262178;
1171 	(*vtoc)->efi_parts[1].p_size = 262144;
1172 
1173 	/* partition -s2 is NOT the Backup disk */
1174 	(*vtoc)->efi_parts[2].p_tag = V_UNASSIGNED;
1175 
1176 	/* partition -s6 /usr partition - HOG */
1177 	(*vtoc)->efi_parts[6].p_start = 524322;
1178 	(*vtoc)->efi_parts[6].p_size = (*vtoc)->efi_last_u_lba - 524322
1179 	    - (1024 * 16);
1180 
1181 	/* efi reserved partition - s9 16K */
1182 	(*vtoc)->efi_parts[8].p_start = (*vtoc)->efi_last_u_lba - (1024 * 16);
1183 	(*vtoc)->efi_parts[8].p_size = (1024 * 16);
1184 	(*vtoc)->efi_parts[8].p_tag = V_RESERVED;
1185 	return (0);
1186 }
1187