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