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