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