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