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