]> CyberLeo.Net >> Repos - FreeBSD/releng/9.2.git/blob - sys/geom/part/g_part_gpt.c
- Copy stable/9 to releng/9.2 as part of the 9.2-RELEASE cycle.
[FreeBSD/releng/9.2.git] / sys / geom / part / g_part_gpt.c
1 /*-
2  * Copyright (c) 2002, 2005-2007, 2011 Marcel Moolenaar
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  */
26
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
29
30 #include <sys/param.h>
31 #include <sys/bio.h>
32 #include <sys/diskmbr.h>
33 #include <sys/endian.h>
34 #include <sys/gpt.h>
35 #include <sys/kernel.h>
36 #include <sys/kobj.h>
37 #include <sys/limits.h>
38 #include <sys/lock.h>
39 #include <sys/malloc.h>
40 #include <sys/mutex.h>
41 #include <sys/queue.h>
42 #include <sys/sbuf.h>
43 #include <sys/systm.h>
44 #include <sys/sysctl.h>
45 #include <sys/uuid.h>
46 #include <geom/geom.h>
47 #include <geom/part/g_part.h>
48
49 #include "g_part_if.h"
50
51 FEATURE(geom_part_gpt, "GEOM partitioning class for GPT partitions support");
52
53 CTASSERT(offsetof(struct gpt_hdr, padding) == 92);
54 CTASSERT(sizeof(struct gpt_ent) == 128);
55
56 #define EQUUID(a,b)     (memcmp(a, b, sizeof(struct uuid)) == 0)
57
58 #define MBRSIZE         512
59
60 enum gpt_elt {
61         GPT_ELT_PRIHDR,
62         GPT_ELT_PRITBL,
63         GPT_ELT_SECHDR,
64         GPT_ELT_SECTBL,
65         GPT_ELT_COUNT
66 };
67
68 enum gpt_state {
69         GPT_STATE_UNKNOWN,      /* Not determined. */
70         GPT_STATE_MISSING,      /* No signature found. */
71         GPT_STATE_CORRUPT,      /* Checksum mismatch. */
72         GPT_STATE_INVALID,      /* Nonconformant/invalid. */
73         GPT_STATE_OK            /* Perfectly fine. */
74 };
75
76 struct g_part_gpt_table {
77         struct g_part_table     base;
78         u_char                  mbr[MBRSIZE];
79         struct gpt_hdr          *hdr;
80         quad_t                  lba[GPT_ELT_COUNT];
81         enum gpt_state          state[GPT_ELT_COUNT];
82         int                     bootcamp;
83 };
84
85 struct g_part_gpt_entry {
86         struct g_part_entry     base;
87         struct gpt_ent          ent;
88 };
89
90 static void g_gpt_printf_utf16(struct sbuf *, uint16_t *, size_t);
91 static void g_gpt_utf8_to_utf16(const uint8_t *, uint16_t *, size_t);
92 static void g_gpt_set_defaults(struct g_part_table *, struct g_provider *);
93
94 static int g_part_gpt_add(struct g_part_table *, struct g_part_entry *,
95     struct g_part_parms *);
96 static int g_part_gpt_bootcode(struct g_part_table *, struct g_part_parms *);
97 static int g_part_gpt_create(struct g_part_table *, struct g_part_parms *);
98 static int g_part_gpt_destroy(struct g_part_table *, struct g_part_parms *);
99 static void g_part_gpt_dumpconf(struct g_part_table *, struct g_part_entry *,
100     struct sbuf *, const char *);
101 static int g_part_gpt_dumpto(struct g_part_table *, struct g_part_entry *);
102 static int g_part_gpt_modify(struct g_part_table *, struct g_part_entry *,
103     struct g_part_parms *);
104 static const char *g_part_gpt_name(struct g_part_table *, struct g_part_entry *,
105     char *, size_t);
106 static int g_part_gpt_probe(struct g_part_table *, struct g_consumer *);
107 static int g_part_gpt_read(struct g_part_table *, struct g_consumer *);
108 static int g_part_gpt_setunset(struct g_part_table *table,
109     struct g_part_entry *baseentry, const char *attrib, unsigned int set);
110 static const char *g_part_gpt_type(struct g_part_table *, struct g_part_entry *,
111     char *, size_t);
112 static int g_part_gpt_write(struct g_part_table *, struct g_consumer *);
113 static int g_part_gpt_resize(struct g_part_table *, struct g_part_entry *,
114     struct g_part_parms *);
115 static int g_part_gpt_recover(struct g_part_table *);
116
117 static kobj_method_t g_part_gpt_methods[] = {
118         KOBJMETHOD(g_part_add,          g_part_gpt_add),
119         KOBJMETHOD(g_part_bootcode,     g_part_gpt_bootcode),
120         KOBJMETHOD(g_part_create,       g_part_gpt_create),
121         KOBJMETHOD(g_part_destroy,      g_part_gpt_destroy),
122         KOBJMETHOD(g_part_dumpconf,     g_part_gpt_dumpconf),
123         KOBJMETHOD(g_part_dumpto,       g_part_gpt_dumpto),
124         KOBJMETHOD(g_part_modify,       g_part_gpt_modify),
125         KOBJMETHOD(g_part_resize,       g_part_gpt_resize),
126         KOBJMETHOD(g_part_name,         g_part_gpt_name),
127         KOBJMETHOD(g_part_probe,        g_part_gpt_probe),
128         KOBJMETHOD(g_part_read,         g_part_gpt_read),
129         KOBJMETHOD(g_part_recover,      g_part_gpt_recover),
130         KOBJMETHOD(g_part_setunset,     g_part_gpt_setunset),
131         KOBJMETHOD(g_part_type,         g_part_gpt_type),
132         KOBJMETHOD(g_part_write,        g_part_gpt_write),
133         { 0, 0 }
134 };
135
136 static struct g_part_scheme g_part_gpt_scheme = {
137         "GPT",
138         g_part_gpt_methods,
139         sizeof(struct g_part_gpt_table),
140         .gps_entrysz = sizeof(struct g_part_gpt_entry),
141         .gps_minent = 128,
142         .gps_maxent = 4096,
143         .gps_bootcodesz = MBRSIZE,
144 };
145 G_PART_SCHEME_DECLARE(g_part_gpt);
146
147 static struct uuid gpt_uuid_apple_boot = GPT_ENT_TYPE_APPLE_BOOT;
148 static struct uuid gpt_uuid_apple_hfs = GPT_ENT_TYPE_APPLE_HFS;
149 static struct uuid gpt_uuid_apple_label = GPT_ENT_TYPE_APPLE_LABEL;
150 static struct uuid gpt_uuid_apple_raid = GPT_ENT_TYPE_APPLE_RAID;
151 static struct uuid gpt_uuid_apple_raid_offline = GPT_ENT_TYPE_APPLE_RAID_OFFLINE;
152 static struct uuid gpt_uuid_apple_tv_recovery = GPT_ENT_TYPE_APPLE_TV_RECOVERY;
153 static struct uuid gpt_uuid_apple_ufs = GPT_ENT_TYPE_APPLE_UFS;
154 static struct uuid gpt_uuid_bios_boot = GPT_ENT_TYPE_BIOS_BOOT;
155 static struct uuid gpt_uuid_efi = GPT_ENT_TYPE_EFI;
156 static struct uuid gpt_uuid_freebsd = GPT_ENT_TYPE_FREEBSD;
157 static struct uuid gpt_uuid_freebsd_boot = GPT_ENT_TYPE_FREEBSD_BOOT;
158 static struct uuid gpt_uuid_freebsd_nandfs = GPT_ENT_TYPE_FREEBSD_NANDFS;
159 static struct uuid gpt_uuid_freebsd_swap = GPT_ENT_TYPE_FREEBSD_SWAP;
160 static struct uuid gpt_uuid_freebsd_ufs = GPT_ENT_TYPE_FREEBSD_UFS;
161 static struct uuid gpt_uuid_freebsd_vinum = GPT_ENT_TYPE_FREEBSD_VINUM;
162 static struct uuid gpt_uuid_freebsd_zfs = GPT_ENT_TYPE_FREEBSD_ZFS;
163 static struct uuid gpt_uuid_linux_data = GPT_ENT_TYPE_LINUX_DATA;
164 static struct uuid gpt_uuid_linux_lvm = GPT_ENT_TYPE_LINUX_LVM;
165 static struct uuid gpt_uuid_linux_raid = GPT_ENT_TYPE_LINUX_RAID;
166 static struct uuid gpt_uuid_linux_swap = GPT_ENT_TYPE_LINUX_SWAP;
167 static struct uuid gpt_uuid_vmfs = GPT_ENT_TYPE_VMFS;
168 static struct uuid gpt_uuid_vmkdiag = GPT_ENT_TYPE_VMKDIAG;
169 static struct uuid gpt_uuid_vmreserved = GPT_ENT_TYPE_VMRESERVED;
170 static struct uuid gpt_uuid_ms_basic_data = GPT_ENT_TYPE_MS_BASIC_DATA;
171 static struct uuid gpt_uuid_ms_reserved = GPT_ENT_TYPE_MS_RESERVED;
172 static struct uuid gpt_uuid_ms_ldm_data = GPT_ENT_TYPE_MS_LDM_DATA;
173 static struct uuid gpt_uuid_ms_ldm_metadata = GPT_ENT_TYPE_MS_LDM_METADATA;
174 static struct uuid gpt_uuid_netbsd_ccd = GPT_ENT_TYPE_NETBSD_CCD;
175 static struct uuid gpt_uuid_netbsd_cgd = GPT_ENT_TYPE_NETBSD_CGD;
176 static struct uuid gpt_uuid_netbsd_ffs = GPT_ENT_TYPE_NETBSD_FFS;
177 static struct uuid gpt_uuid_netbsd_lfs = GPT_ENT_TYPE_NETBSD_LFS;
178 static struct uuid gpt_uuid_netbsd_raid = GPT_ENT_TYPE_NETBSD_RAID;
179 static struct uuid gpt_uuid_netbsd_swap = GPT_ENT_TYPE_NETBSD_SWAP;
180 static struct uuid gpt_uuid_mbr = GPT_ENT_TYPE_MBR;
181 static struct uuid gpt_uuid_unused = GPT_ENT_TYPE_UNUSED;
182
183 static struct g_part_uuid_alias {
184         struct uuid *uuid;
185         int alias;
186         int mbrtype;
187 } gpt_uuid_alias_match[] = {
188         { &gpt_uuid_apple_boot,         G_PART_ALIAS_APPLE_BOOT,         0xab },
189         { &gpt_uuid_apple_hfs,          G_PART_ALIAS_APPLE_HFS,          0xaf },
190         { &gpt_uuid_apple_label,        G_PART_ALIAS_APPLE_LABEL,        0 },
191         { &gpt_uuid_apple_raid,         G_PART_ALIAS_APPLE_RAID,         0 },
192         { &gpt_uuid_apple_raid_offline, G_PART_ALIAS_APPLE_RAID_OFFLINE, 0 },
193         { &gpt_uuid_apple_tv_recovery,  G_PART_ALIAS_APPLE_TV_RECOVERY,  0 },
194         { &gpt_uuid_apple_ufs,          G_PART_ALIAS_APPLE_UFS,          0 },
195         { &gpt_uuid_bios_boot,          G_PART_ALIAS_BIOS_BOOT,          0 },
196         { &gpt_uuid_efi,                G_PART_ALIAS_EFI,                0xee },
197         { &gpt_uuid_freebsd,            G_PART_ALIAS_FREEBSD,            0xa5 },
198         { &gpt_uuid_freebsd_boot,       G_PART_ALIAS_FREEBSD_BOOT,       0 },
199         { &gpt_uuid_freebsd_nandfs,     G_PART_ALIAS_FREEBSD_NANDFS,     0 },
200         { &gpt_uuid_freebsd_swap,       G_PART_ALIAS_FREEBSD_SWAP,       0 },
201         { &gpt_uuid_freebsd_ufs,        G_PART_ALIAS_FREEBSD_UFS,        0 },
202         { &gpt_uuid_freebsd_vinum,      G_PART_ALIAS_FREEBSD_VINUM,      0 },
203         { &gpt_uuid_freebsd_zfs,        G_PART_ALIAS_FREEBSD_ZFS,        0 },
204         { &gpt_uuid_linux_data,         G_PART_ALIAS_LINUX_DATA,         0x0b },
205         { &gpt_uuid_linux_lvm,          G_PART_ALIAS_LINUX_LVM,          0 },
206         { &gpt_uuid_linux_raid,         G_PART_ALIAS_LINUX_RAID,         0 },
207         { &gpt_uuid_linux_swap,         G_PART_ALIAS_LINUX_SWAP,         0 },
208         { &gpt_uuid_vmfs,               G_PART_ALIAS_VMFS,               0 },
209         { &gpt_uuid_vmkdiag,            G_PART_ALIAS_VMKDIAG,            0 },
210         { &gpt_uuid_vmreserved,         G_PART_ALIAS_VMRESERVED,         0 },
211         { &gpt_uuid_mbr,                G_PART_ALIAS_MBR,                0 },
212         { &gpt_uuid_ms_basic_data,      G_PART_ALIAS_MS_BASIC_DATA,      0x0b },
213         { &gpt_uuid_ms_ldm_data,        G_PART_ALIAS_MS_LDM_DATA,        0 },
214         { &gpt_uuid_ms_ldm_metadata,    G_PART_ALIAS_MS_LDM_METADATA,    0 },
215         { &gpt_uuid_ms_reserved,        G_PART_ALIAS_MS_RESERVED,        0 },
216         { &gpt_uuid_netbsd_ccd,         G_PART_ALIAS_NETBSD_CCD,         0 },
217         { &gpt_uuid_netbsd_cgd,         G_PART_ALIAS_NETBSD_CGD,         0 },
218         { &gpt_uuid_netbsd_ffs,         G_PART_ALIAS_NETBSD_FFS,         0 },
219         { &gpt_uuid_netbsd_lfs,         G_PART_ALIAS_NETBSD_LFS,         0 },
220         { &gpt_uuid_netbsd_raid,        G_PART_ALIAS_NETBSD_RAID,        0 },
221         { &gpt_uuid_netbsd_swap,        G_PART_ALIAS_NETBSD_SWAP,        0 },
222         { NULL, 0, 0 }
223 };
224
225 static int
226 gpt_write_mbr_entry(u_char *mbr, int idx, int typ, quad_t start,
227     quad_t end)
228 {
229
230         if (typ == 0 || start > UINT32_MAX || end > UINT32_MAX)
231                 return (EINVAL);
232
233         mbr += DOSPARTOFF + idx * DOSPARTSIZE;
234         mbr[0] = 0;
235         if (start == 1) {
236                 /*
237                  * Treat the PMBR partition specially to maximize
238                  * interoperability with BIOSes.
239                  */
240                 mbr[1] = mbr[3] = 0;
241                 mbr[2] = 2;
242         } else
243                 mbr[1] = mbr[2] = mbr[3] = 0xff;
244         mbr[4] = typ;
245         mbr[5] = mbr[6] = mbr[7] = 0xff;
246         le32enc(mbr + 8, (uint32_t)start);
247         le32enc(mbr + 12, (uint32_t)(end - start + 1));
248         return (0);
249 }
250
251 static int
252 gpt_map_type(struct uuid *t)
253 {
254         struct g_part_uuid_alias *uap;
255
256         for (uap = &gpt_uuid_alias_match[0]; uap->uuid; uap++) {
257                 if (EQUUID(t, uap->uuid))
258                         return (uap->mbrtype);
259         }
260         return (0);
261 }
262
263 /*
264  * Under Boot Camp the PMBR partition (type 0xEE) doesn't cover the
265  * whole disk anymore. Rather, it covers the GPT table and the EFI
266  * system partition only. This way the HFS+ partition and any FAT
267  * partitions can be added to the MBR without creating an overlap.
268  */
269 static int
270 gpt_is_bootcamp(struct g_part_gpt_table *table, const char *provname)
271 {
272         uint8_t *p;
273
274         p = table->mbr + DOSPARTOFF;
275         if (p[4] != 0xee || le32dec(p + 8) != 1)
276                 return (0);
277
278         p += DOSPARTSIZE;
279         if (p[4] != 0xaf)
280                 return (0);
281
282         printf("GEOM: %s: enabling Boot Camp\n", provname);
283         return (1);
284 }
285
286 static void
287 gpt_update_bootcamp(struct g_part_table *basetable)
288 {
289         struct g_part_entry *baseentry;
290         struct g_part_gpt_entry *entry;
291         struct g_part_gpt_table *table;
292         int bootable, error, index, slices, typ;
293
294         table = (struct g_part_gpt_table *)basetable;
295
296         bootable = -1;
297         for (index = 0; index < NDOSPART; index++) {
298                 if (table->mbr[DOSPARTOFF + DOSPARTSIZE * index])
299                         bootable = index;
300         }
301
302         bzero(table->mbr + DOSPARTOFF, DOSPARTSIZE * NDOSPART);
303         slices = 0;
304         LIST_FOREACH(baseentry, &basetable->gpt_entry, gpe_entry) {
305                 if (baseentry->gpe_deleted)
306                         continue;
307                 index = baseentry->gpe_index - 1;
308                 if (index >= NDOSPART)
309                         continue;
310
311                 entry = (struct g_part_gpt_entry *)baseentry;
312
313                 switch (index) {
314                 case 0: /* This must be the EFI system partition. */
315                         if (!EQUUID(&entry->ent.ent_type, &gpt_uuid_efi))
316                                 goto disable;
317                         error = gpt_write_mbr_entry(table->mbr, index, 0xee,
318                             1ull, entry->ent.ent_lba_end);
319                         break;
320                 case 1: /* This must be the HFS+ partition. */
321                         if (!EQUUID(&entry->ent.ent_type, &gpt_uuid_apple_hfs))
322                                 goto disable;
323                         error = gpt_write_mbr_entry(table->mbr, index, 0xaf,
324                             entry->ent.ent_lba_start, entry->ent.ent_lba_end);
325                         break;
326                 default:
327                         typ = gpt_map_type(&entry->ent.ent_type);
328                         error = gpt_write_mbr_entry(table->mbr, index, typ,
329                             entry->ent.ent_lba_start, entry->ent.ent_lba_end);
330                         break;
331                 }
332                 if (error)
333                         continue;
334
335                 if (index == bootable)
336                         table->mbr[DOSPARTOFF + DOSPARTSIZE * index] = 0x80;
337                 slices |= 1 << index;
338         }
339         if ((slices & 3) == 3)
340                 return;
341
342  disable:
343         table->bootcamp = 0;
344 }
345
346 static struct gpt_hdr *
347 gpt_read_hdr(struct g_part_gpt_table *table, struct g_consumer *cp,
348     enum gpt_elt elt)
349 {
350         struct gpt_hdr *buf, *hdr;
351         struct g_provider *pp;
352         quad_t lba, last;
353         int error;
354         uint32_t crc, sz;
355
356         pp = cp->provider;
357         last = (pp->mediasize / pp->sectorsize) - 1;
358         table->state[elt] = GPT_STATE_MISSING;
359         /*
360          * If the primary header is valid look for secondary
361          * header in AlternateLBA, otherwise in the last medium's LBA.
362          */
363         if (elt == GPT_ELT_SECHDR) {
364                 if (table->state[GPT_ELT_PRIHDR] != GPT_STATE_OK)
365                         table->lba[elt] = last;
366         } else
367                 table->lba[elt] = 1;
368         buf = g_read_data(cp, table->lba[elt] * pp->sectorsize, pp->sectorsize,
369             &error);
370         if (buf == NULL)
371                 return (NULL);
372         hdr = NULL;
373         if (memcmp(buf->hdr_sig, GPT_HDR_SIG, sizeof(buf->hdr_sig)) != 0)
374                 goto fail;
375
376         table->state[elt] = GPT_STATE_CORRUPT;
377         sz = le32toh(buf->hdr_size);
378         if (sz < 92 || sz > pp->sectorsize)
379                 goto fail;
380
381         hdr = g_malloc(sz, M_WAITOK | M_ZERO);
382         bcopy(buf, hdr, sz);
383         hdr->hdr_size = sz;
384
385         crc = le32toh(buf->hdr_crc_self);
386         buf->hdr_crc_self = 0;
387         if (crc32(buf, sz) != crc)
388                 goto fail;
389         hdr->hdr_crc_self = crc;
390
391         table->state[elt] = GPT_STATE_INVALID;
392         hdr->hdr_revision = le32toh(buf->hdr_revision);
393         if (hdr->hdr_revision < GPT_HDR_REVISION)
394                 goto fail;
395         hdr->hdr_lba_self = le64toh(buf->hdr_lba_self);
396         if (hdr->hdr_lba_self != table->lba[elt])
397                 goto fail;
398         hdr->hdr_lba_alt = le64toh(buf->hdr_lba_alt);
399         if (hdr->hdr_lba_alt == hdr->hdr_lba_self ||
400             hdr->hdr_lba_alt > last)
401                 goto fail;
402
403         /* Check the managed area. */
404         hdr->hdr_lba_start = le64toh(buf->hdr_lba_start);
405         if (hdr->hdr_lba_start < 2 || hdr->hdr_lba_start >= last)
406                 goto fail;
407         hdr->hdr_lba_end = le64toh(buf->hdr_lba_end);
408         if (hdr->hdr_lba_end < hdr->hdr_lba_start || hdr->hdr_lba_end >= last)
409                 goto fail;
410
411         /* Check the table location and size of the table. */
412         hdr->hdr_entries = le32toh(buf->hdr_entries);
413         hdr->hdr_entsz = le32toh(buf->hdr_entsz);
414         if (hdr->hdr_entries == 0 || hdr->hdr_entsz < 128 ||
415             (hdr->hdr_entsz & 7) != 0)
416                 goto fail;
417         hdr->hdr_lba_table = le64toh(buf->hdr_lba_table);
418         if (hdr->hdr_lba_table < 2 || hdr->hdr_lba_table >= last)
419                 goto fail;
420         if (hdr->hdr_lba_table >= hdr->hdr_lba_start &&
421             hdr->hdr_lba_table <= hdr->hdr_lba_end)
422                 goto fail;
423         lba = hdr->hdr_lba_table +
424             (hdr->hdr_entries * hdr->hdr_entsz + pp->sectorsize - 1) /
425             pp->sectorsize - 1;
426         if (lba >= last)
427                 goto fail;
428         if (lba >= hdr->hdr_lba_start && lba <= hdr->hdr_lba_end)
429                 goto fail;
430
431         table->state[elt] = GPT_STATE_OK;
432         le_uuid_dec(&buf->hdr_uuid, &hdr->hdr_uuid);
433         hdr->hdr_crc_table = le32toh(buf->hdr_crc_table);
434
435         /* save LBA for secondary header */
436         if (elt == GPT_ELT_PRIHDR)
437                 table->lba[GPT_ELT_SECHDR] = hdr->hdr_lba_alt;
438
439         g_free(buf);
440         return (hdr);
441
442  fail:
443         if (hdr != NULL)
444                 g_free(hdr);
445         g_free(buf);
446         return (NULL);
447 }
448
449 static struct gpt_ent *
450 gpt_read_tbl(struct g_part_gpt_table *table, struct g_consumer *cp,
451     enum gpt_elt elt, struct gpt_hdr *hdr)
452 {
453         struct g_provider *pp;
454         struct gpt_ent *ent, *tbl;
455         char *buf, *p;
456         unsigned int idx, sectors, tblsz, size;
457         int error;
458
459         if (hdr == NULL)
460                 return (NULL);
461
462         pp = cp->provider;
463         table->lba[elt] = hdr->hdr_lba_table;
464
465         table->state[elt] = GPT_STATE_MISSING;
466         tblsz = hdr->hdr_entries * hdr->hdr_entsz;
467         sectors = (tblsz + pp->sectorsize - 1) / pp->sectorsize;
468         buf = g_malloc(sectors * pp->sectorsize, M_WAITOK | M_ZERO);
469         for (idx = 0; idx < sectors; idx += MAXPHYS / pp->sectorsize) {
470                 size = (sectors - idx > MAXPHYS / pp->sectorsize) ?  MAXPHYS:
471                     (sectors - idx) * pp->sectorsize;
472                 p = g_read_data(cp, (table->lba[elt] + idx) * pp->sectorsize,
473                     size, &error);
474                 if (p == NULL) {
475                         g_free(buf);
476                         return (NULL);
477                 }
478                 bcopy(p, buf + idx * pp->sectorsize, size);
479                 g_free(p);
480         }
481         table->state[elt] = GPT_STATE_CORRUPT;
482         if (crc32(buf, tblsz) != hdr->hdr_crc_table) {
483                 g_free(buf);
484                 return (NULL);
485         }
486
487         table->state[elt] = GPT_STATE_OK;
488         tbl = g_malloc(hdr->hdr_entries * sizeof(struct gpt_ent),
489             M_WAITOK | M_ZERO);
490
491         for (idx = 0, ent = tbl, p = buf;
492              idx < hdr->hdr_entries;
493              idx++, ent++, p += hdr->hdr_entsz) {
494                 le_uuid_dec(p, &ent->ent_type);
495                 le_uuid_dec(p + 16, &ent->ent_uuid);
496                 ent->ent_lba_start = le64dec(p + 32);
497                 ent->ent_lba_end = le64dec(p + 40);
498                 ent->ent_attr = le64dec(p + 48);
499                 /* Keep UTF-16 in little-endian. */
500                 bcopy(p + 56, ent->ent_name, sizeof(ent->ent_name));
501         }
502
503         g_free(buf);
504         return (tbl);
505 }
506
507 static int
508 gpt_matched_hdrs(struct gpt_hdr *pri, struct gpt_hdr *sec)
509 {
510
511         if (pri == NULL || sec == NULL)
512                 return (0);
513
514         if (!EQUUID(&pri->hdr_uuid, &sec->hdr_uuid))
515                 return (0);
516         return ((pri->hdr_revision == sec->hdr_revision &&
517             pri->hdr_size == sec->hdr_size &&
518             pri->hdr_lba_start == sec->hdr_lba_start &&
519             pri->hdr_lba_end == sec->hdr_lba_end &&
520             pri->hdr_entries == sec->hdr_entries &&
521             pri->hdr_entsz == sec->hdr_entsz &&
522             pri->hdr_crc_table == sec->hdr_crc_table) ? 1 : 0);
523 }
524
525 static int
526 gpt_parse_type(const char *type, struct uuid *uuid)
527 {
528         struct uuid tmp;
529         const char *alias;
530         int error;
531         struct g_part_uuid_alias *uap;
532
533         if (type[0] == '!') {
534                 error = parse_uuid(type + 1, &tmp);
535                 if (error)
536                         return (error);
537                 if (EQUUID(&tmp, &gpt_uuid_unused))
538                         return (EINVAL);
539                 *uuid = tmp;
540                 return (0);
541         }
542         for (uap = &gpt_uuid_alias_match[0]; uap->uuid; uap++) {
543                 alias = g_part_alias_name(uap->alias);
544                 if (!strcasecmp(type, alias)) {
545                         *uuid = *uap->uuid;
546                         return (0);
547                 }
548         }
549         return (EINVAL);
550 }
551
552 static int
553 g_part_gpt_add(struct g_part_table *basetable, struct g_part_entry *baseentry,
554     struct g_part_parms *gpp)
555 {
556         struct g_part_gpt_entry *entry;
557         int error;
558
559         entry = (struct g_part_gpt_entry *)baseentry;
560         error = gpt_parse_type(gpp->gpp_type, &entry->ent.ent_type);
561         if (error)
562                 return (error);
563         kern_uuidgen(&entry->ent.ent_uuid, 1);
564         entry->ent.ent_lba_start = baseentry->gpe_start;
565         entry->ent.ent_lba_end = baseentry->gpe_end;
566         if (baseentry->gpe_deleted) {
567                 entry->ent.ent_attr = 0;
568                 bzero(entry->ent.ent_name, sizeof(entry->ent.ent_name));
569         }
570         if (gpp->gpp_parms & G_PART_PARM_LABEL)
571                 g_gpt_utf8_to_utf16(gpp->gpp_label, entry->ent.ent_name,
572                     sizeof(entry->ent.ent_name) /
573                     sizeof(entry->ent.ent_name[0]));
574         return (0);
575 }
576
577 static int
578 g_part_gpt_bootcode(struct g_part_table *basetable, struct g_part_parms *gpp)
579 {
580         struct g_part_gpt_table *table;
581         size_t codesz;
582
583         codesz = DOSPARTOFF;
584         table = (struct g_part_gpt_table *)basetable;
585         bzero(table->mbr, codesz);
586         codesz = MIN(codesz, gpp->gpp_codesize);
587         if (codesz > 0)
588                 bcopy(gpp->gpp_codeptr, table->mbr, codesz);
589         return (0);
590 }
591
592 static int
593 g_part_gpt_create(struct g_part_table *basetable, struct g_part_parms *gpp)
594 {
595         struct g_provider *pp;
596         struct g_part_gpt_table *table;
597         size_t tblsz;
598
599         /* We don't nest, which means that our depth should be 0. */
600         if (basetable->gpt_depth != 0)
601                 return (ENXIO);
602
603         table = (struct g_part_gpt_table *)basetable;
604         pp = gpp->gpp_provider;
605         tblsz = (basetable->gpt_entries * sizeof(struct gpt_ent) +
606             pp->sectorsize - 1) / pp->sectorsize;
607         if (pp->sectorsize < MBRSIZE ||
608             pp->mediasize < (3 + 2 * tblsz + basetable->gpt_entries) *
609             pp->sectorsize)
610                 return (ENOSPC);
611
612         /* Allocate space for the header */
613         table->hdr = g_malloc(sizeof(struct gpt_hdr), M_WAITOK | M_ZERO);
614
615         bcopy(GPT_HDR_SIG, table->hdr->hdr_sig, sizeof(table->hdr->hdr_sig));
616         table->hdr->hdr_revision = GPT_HDR_REVISION;
617         table->hdr->hdr_size = offsetof(struct gpt_hdr, padding);
618         kern_uuidgen(&table->hdr->hdr_uuid, 1);
619         table->hdr->hdr_entries = basetable->gpt_entries;
620         table->hdr->hdr_entsz = sizeof(struct gpt_ent);
621
622         g_gpt_set_defaults(basetable, pp);
623         return (0);
624 }
625
626 static int
627 g_part_gpt_destroy(struct g_part_table *basetable, struct g_part_parms *gpp)
628 {
629         struct g_part_gpt_table *table;
630         struct g_provider *pp;
631
632         table = (struct g_part_gpt_table *)basetable;
633         pp = LIST_FIRST(&basetable->gpt_gp->consumer)->provider;
634         g_free(table->hdr);
635         table->hdr = NULL;
636
637         /*
638          * Wipe the first 2 sectors to clear the partitioning. Wipe the last
639          * sector only if it has valid secondary header.
640          */
641         basetable->gpt_smhead |= 3;
642         if (table->state[GPT_ELT_SECHDR] == GPT_STATE_OK &&
643             table->lba[GPT_ELT_SECHDR] == pp->mediasize / pp->sectorsize - 1)
644                 basetable->gpt_smtail |= 1;
645         return (0);
646 }
647
648 static void
649 g_part_gpt_dumpconf(struct g_part_table *table, struct g_part_entry *baseentry, 
650     struct sbuf *sb, const char *indent)
651 {
652         struct g_part_gpt_entry *entry;
653  
654         entry = (struct g_part_gpt_entry *)baseentry;
655         if (indent == NULL) {
656                 /* conftxt: libdisk compatibility */
657                 sbuf_printf(sb, " xs GPT xt ");
658                 sbuf_printf_uuid(sb, &entry->ent.ent_type);
659         } else if (entry != NULL) {
660                 /* confxml: partition entry information */
661                 sbuf_printf(sb, "%s<label>", indent);
662                 g_gpt_printf_utf16(sb, entry->ent.ent_name,
663                     sizeof(entry->ent.ent_name) >> 1);
664                 sbuf_printf(sb, "</label>\n");
665                 if (entry->ent.ent_attr & GPT_ENT_ATTR_BOOTME)
666                         sbuf_printf(sb, "%s<attrib>bootme</attrib>\n", indent);
667                 if (entry->ent.ent_attr & GPT_ENT_ATTR_BOOTONCE) {
668                         sbuf_printf(sb, "%s<attrib>bootonce</attrib>\n",
669                             indent);
670                 }
671                 if (entry->ent.ent_attr & GPT_ENT_ATTR_BOOTFAILED) {
672                         sbuf_printf(sb, "%s<attrib>bootfailed</attrib>\n",
673                             indent);
674                 }
675                 sbuf_printf(sb, "%s<rawtype>", indent);
676                 sbuf_printf_uuid(sb, &entry->ent.ent_type);
677                 sbuf_printf(sb, "</rawtype>\n");
678                 sbuf_printf(sb, "%s<rawuuid>", indent);
679                 sbuf_printf_uuid(sb, &entry->ent.ent_uuid);
680                 sbuf_printf(sb, "</rawuuid>\n");
681         } else {
682                 /* confxml: scheme information */
683         }
684 }
685
686 static int
687 g_part_gpt_dumpto(struct g_part_table *table, struct g_part_entry *baseentry)  
688 {
689         struct g_part_gpt_entry *entry;
690
691         entry = (struct g_part_gpt_entry *)baseentry;
692         return ((EQUUID(&entry->ent.ent_type, &gpt_uuid_freebsd_swap) ||
693             EQUUID(&entry->ent.ent_type, &gpt_uuid_linux_swap)) ? 1 : 0);
694 }
695
696 static int
697 g_part_gpt_modify(struct g_part_table *basetable,
698     struct g_part_entry *baseentry, struct g_part_parms *gpp)
699 {
700         struct g_part_gpt_entry *entry;
701         int error;
702
703         entry = (struct g_part_gpt_entry *)baseentry;
704         if (gpp->gpp_parms & G_PART_PARM_TYPE) {
705                 error = gpt_parse_type(gpp->gpp_type, &entry->ent.ent_type);
706                 if (error)
707                         return (error);
708         }
709         if (gpp->gpp_parms & G_PART_PARM_LABEL)
710                 g_gpt_utf8_to_utf16(gpp->gpp_label, entry->ent.ent_name,
711                     sizeof(entry->ent.ent_name) /
712                     sizeof(entry->ent.ent_name[0]));
713         return (0);
714 }
715
716 static int
717 g_part_gpt_resize(struct g_part_table *basetable,
718     struct g_part_entry *baseentry, struct g_part_parms *gpp)
719 {
720         struct g_part_gpt_entry *entry;
721         entry = (struct g_part_gpt_entry *)baseentry;
722
723         baseentry->gpe_end = baseentry->gpe_start + gpp->gpp_size - 1;
724         entry->ent.ent_lba_end = baseentry->gpe_end;
725
726         return (0);
727 }
728
729 static const char *
730 g_part_gpt_name(struct g_part_table *table, struct g_part_entry *baseentry,
731     char *buf, size_t bufsz)
732 {
733         struct g_part_gpt_entry *entry;
734         char c;
735
736         entry = (struct g_part_gpt_entry *)baseentry;
737         c = (EQUUID(&entry->ent.ent_type, &gpt_uuid_freebsd)) ? 's' : 'p';
738         snprintf(buf, bufsz, "%c%d", c, baseentry->gpe_index);
739         return (buf);
740 }
741
742 static int
743 g_part_gpt_probe(struct g_part_table *table, struct g_consumer *cp)
744 {
745         struct g_provider *pp;
746         char *buf;
747         int error, res;
748
749         /* We don't nest, which means that our depth should be 0. */
750         if (table->gpt_depth != 0)
751                 return (ENXIO);
752
753         pp = cp->provider;
754
755         /*
756          * Sanity-check the provider. Since the first sector on the provider
757          * must be a PMBR and a PMBR is 512 bytes large, the sector size
758          * must be at least 512 bytes.  Also, since the theoretical minimum
759          * number of sectors needed by GPT is 6, any medium that has less
760          * than 6 sectors is never going to be able to hold a GPT. The
761          * number 6 comes from:
762          *      1 sector for the PMBR
763          *      2 sectors for the GPT headers (each 1 sector)
764          *      2 sectors for the GPT tables (each 1 sector)
765          *      1 sector for an actual partition
766          * It's better to catch this pathological case early than behaving
767          * pathologically later on...
768          */
769         if (pp->sectorsize < MBRSIZE || pp->mediasize < 6 * pp->sectorsize)
770                 return (ENOSPC);
771
772         /* Check that there's a MBR. */
773         buf = g_read_data(cp, 0L, pp->sectorsize, &error);
774         if (buf == NULL)
775                 return (error);
776         res = le16dec(buf + DOSMAGICOFFSET);
777         g_free(buf);
778         if (res != DOSMAGIC) 
779                 return (ENXIO);
780
781         /* Check that there's a primary header. */
782         buf = g_read_data(cp, pp->sectorsize, pp->sectorsize, &error);
783         if (buf == NULL)
784                 return (error);
785         res = memcmp(buf, GPT_HDR_SIG, 8);
786         g_free(buf);
787         if (res == 0)
788                 return (G_PART_PROBE_PRI_HIGH);
789
790         /* No primary? Check that there's a secondary. */
791         buf = g_read_data(cp, pp->mediasize - pp->sectorsize, pp->sectorsize,
792             &error);
793         if (buf == NULL)
794                 return (error);
795         res = memcmp(buf, GPT_HDR_SIG, 8); 
796         g_free(buf);
797         return ((res == 0) ? G_PART_PROBE_PRI_HIGH : ENXIO);
798 }
799
800 static int
801 g_part_gpt_read(struct g_part_table *basetable, struct g_consumer *cp)
802 {
803         struct gpt_hdr *prihdr, *sechdr;
804         struct gpt_ent *tbl, *pritbl, *sectbl;
805         struct g_provider *pp;
806         struct g_part_gpt_table *table;
807         struct g_part_gpt_entry *entry;
808         u_char *buf;
809         uint64_t last;
810         int error, index;
811
812         table = (struct g_part_gpt_table *)basetable;
813         pp = cp->provider;
814         last = (pp->mediasize / pp->sectorsize) - 1;
815
816         /* Read the PMBR */
817         buf = g_read_data(cp, 0, pp->sectorsize, &error);
818         if (buf == NULL)
819                 return (error);
820         bcopy(buf, table->mbr, MBRSIZE);
821         g_free(buf);
822
823         /* Read the primary header and table. */
824         prihdr = gpt_read_hdr(table, cp, GPT_ELT_PRIHDR);
825         if (table->state[GPT_ELT_PRIHDR] == GPT_STATE_OK) {
826                 pritbl = gpt_read_tbl(table, cp, GPT_ELT_PRITBL, prihdr);
827         } else {
828                 table->state[GPT_ELT_PRITBL] = GPT_STATE_MISSING;
829                 pritbl = NULL;
830         }
831
832         /* Read the secondary header and table. */
833         sechdr = gpt_read_hdr(table, cp, GPT_ELT_SECHDR);
834         if (table->state[GPT_ELT_SECHDR] == GPT_STATE_OK) {
835                 sectbl = gpt_read_tbl(table, cp, GPT_ELT_SECTBL, sechdr);
836         } else {
837                 table->state[GPT_ELT_SECTBL] = GPT_STATE_MISSING;
838                 sectbl = NULL;
839         }
840
841         /* Fail if we haven't got any good tables at all. */
842         if (table->state[GPT_ELT_PRITBL] != GPT_STATE_OK &&
843             table->state[GPT_ELT_SECTBL] != GPT_STATE_OK) {
844                 printf("GEOM: %s: corrupt or invalid GPT detected.\n",
845                     pp->name);
846                 printf("GEOM: %s: GPT rejected -- may not be recoverable.\n",
847                     pp->name);
848                 return (EINVAL);
849         }
850
851         /*
852          * If both headers are good but they disagree with each other,
853          * then invalidate one. We prefer to keep the primary header,
854          * unless the primary table is corrupt.
855          */
856         if (table->state[GPT_ELT_PRIHDR] == GPT_STATE_OK &&
857             table->state[GPT_ELT_SECHDR] == GPT_STATE_OK &&
858             !gpt_matched_hdrs(prihdr, sechdr)) {
859                 if (table->state[GPT_ELT_PRITBL] == GPT_STATE_OK) {
860                         table->state[GPT_ELT_SECHDR] = GPT_STATE_INVALID;
861                         table->state[GPT_ELT_SECTBL] = GPT_STATE_MISSING;
862                         g_free(sechdr);
863                         sechdr = NULL;
864                 } else {
865                         table->state[GPT_ELT_PRIHDR] = GPT_STATE_INVALID;
866                         table->state[GPT_ELT_PRITBL] = GPT_STATE_MISSING;
867                         g_free(prihdr);
868                         prihdr = NULL;
869                 }
870         }
871
872         if (table->state[GPT_ELT_PRITBL] != GPT_STATE_OK) {
873                 printf("GEOM: %s: the primary GPT table is corrupt or "
874                     "invalid.\n", pp->name);
875                 printf("GEOM: %s: using the secondary instead -- recovery "
876                     "strongly advised.\n", pp->name);
877                 table->hdr = sechdr;
878                 basetable->gpt_corrupt = 1;
879                 if (prihdr != NULL)
880                         g_free(prihdr);
881                 tbl = sectbl;
882                 if (pritbl != NULL)
883                         g_free(pritbl);
884         } else {
885                 if (table->state[GPT_ELT_SECTBL] != GPT_STATE_OK) {
886                         printf("GEOM: %s: the secondary GPT table is corrupt "
887                             "or invalid.\n", pp->name);
888                         printf("GEOM: %s: using the primary only -- recovery "
889                             "suggested.\n", pp->name);
890                         basetable->gpt_corrupt = 1;
891                 } else if (table->lba[GPT_ELT_SECHDR] != last) {
892                         printf( "GEOM: %s: the secondary GPT header is not in "
893                             "the last LBA.\n", pp->name);
894                         basetable->gpt_corrupt = 1;
895                 }
896                 table->hdr = prihdr;
897                 if (sechdr != NULL)
898                         g_free(sechdr);
899                 tbl = pritbl;
900                 if (sectbl != NULL)
901                         g_free(sectbl);
902         }
903
904         basetable->gpt_first = table->hdr->hdr_lba_start;
905         basetable->gpt_last = table->hdr->hdr_lba_end;
906         basetable->gpt_entries = table->hdr->hdr_entries;
907
908         for (index = basetable->gpt_entries - 1; index >= 0; index--) {
909                 if (EQUUID(&tbl[index].ent_type, &gpt_uuid_unused))
910                         continue;
911                 entry = (struct g_part_gpt_entry *)g_part_new_entry(
912                     basetable, index + 1, tbl[index].ent_lba_start,
913                     tbl[index].ent_lba_end);
914                 entry->ent = tbl[index];
915         }
916
917         g_free(tbl);
918
919         /*
920          * Under Mac OS X, the MBR mirrors the first 4 GPT partitions
921          * if (and only if) any FAT32 or FAT16 partitions have been
922          * created. This happens irrespective of whether Boot Camp is
923          * used/enabled, though it's generally understood to be done
924          * to support legacy Windows under Boot Camp. We refer to this
925          * mirroring simply as Boot Camp. We try to detect Boot Camp
926          * so that we can update the MBR if and when GPT changes have
927          * been made. Note that we do not enable Boot Camp if not
928          * previously enabled because we can't assume that we're on a
929          * Mac alongside Mac OS X.
930          */
931         table->bootcamp = gpt_is_bootcamp(table, pp->name);
932
933         return (0);
934 }
935
936 static int
937 g_part_gpt_recover(struct g_part_table *basetable)
938 {
939
940         g_gpt_set_defaults(basetable,
941             LIST_FIRST(&basetable->gpt_gp->consumer)->provider);
942         basetable->gpt_corrupt = 0;
943         return (0);
944 }
945
946 static int
947 g_part_gpt_setunset(struct g_part_table *basetable,
948     struct g_part_entry *baseentry, const char *attrib, unsigned int set)
949 {
950         struct g_part_gpt_entry *entry;
951         struct g_part_gpt_table *table;
952         uint64_t attr;
953         int i;
954
955         table = (struct g_part_gpt_table *)basetable;
956         entry = (struct g_part_gpt_entry *)baseentry;
957
958         if (strcasecmp(attrib, "active") == 0) {
959                 if (!table->bootcamp || baseentry->gpe_index > NDOSPART)
960                         return (EINVAL);
961                 for (i = 0; i < NDOSPART; i++) {
962                         table->mbr[DOSPARTOFF + i * DOSPARTSIZE] =
963                             (i == baseentry->gpe_index - 1) ? 0x80 : 0;
964                 }
965                 return (0);
966         }
967
968         attr = 0;
969         if (strcasecmp(attrib, "bootme") == 0) {
970                 attr |= GPT_ENT_ATTR_BOOTME;
971         } else if (strcasecmp(attrib, "bootonce") == 0) {
972                 attr |= GPT_ENT_ATTR_BOOTONCE;
973                 if (set)
974                         attr |= GPT_ENT_ATTR_BOOTME;
975         } else if (strcasecmp(attrib, "bootfailed") == 0) {
976                 /*
977                  * It should only be possible to unset BOOTFAILED, but it might
978                  * be useful for test purposes to also be able to set it.
979                  */
980                 attr |= GPT_ENT_ATTR_BOOTFAILED;
981         }
982         if (attr == 0)
983                 return (EINVAL);
984
985         if (set)
986                 attr = entry->ent.ent_attr | attr;
987         else
988                 attr = entry->ent.ent_attr & ~attr;
989         if (attr != entry->ent.ent_attr) {
990                 entry->ent.ent_attr = attr;
991                 if (!baseentry->gpe_created)
992                         baseentry->gpe_modified = 1;
993         }
994         return (0);
995 }
996
997 static const char *
998 g_part_gpt_type(struct g_part_table *basetable, struct g_part_entry *baseentry, 
999     char *buf, size_t bufsz)
1000 {
1001         struct g_part_gpt_entry *entry;
1002         struct uuid *type;
1003         struct g_part_uuid_alias *uap;
1004  
1005         entry = (struct g_part_gpt_entry *)baseentry;
1006         type = &entry->ent.ent_type;
1007         for (uap = &gpt_uuid_alias_match[0]; uap->uuid; uap++)
1008                 if (EQUUID(type, uap->uuid))
1009                         return (g_part_alias_name(uap->alias));
1010         buf[0] = '!';
1011         snprintf_uuid(buf + 1, bufsz - 1, type);
1012
1013         return (buf);
1014 }
1015
1016 static int
1017 g_part_gpt_write(struct g_part_table *basetable, struct g_consumer *cp)
1018 {
1019         unsigned char *buf, *bp;
1020         struct g_provider *pp;
1021         struct g_part_entry *baseentry;
1022         struct g_part_gpt_entry *entry;
1023         struct g_part_gpt_table *table;
1024         size_t tblsz;
1025         uint32_t crc;
1026         int error, index;
1027
1028         pp = cp->provider;
1029         table = (struct g_part_gpt_table *)basetable;
1030         tblsz = (table->hdr->hdr_entries * table->hdr->hdr_entsz +
1031             pp->sectorsize - 1) / pp->sectorsize;
1032
1033         /* Reconstruct the MBR from the GPT if under Boot Camp. */
1034         if (table->bootcamp)
1035                 gpt_update_bootcamp(basetable);
1036
1037         /* Update partition entries in the PMBR if Boot Camp disabled. */
1038         if (!table->bootcamp) {
1039                 bzero(table->mbr + DOSPARTOFF, DOSPARTSIZE * NDOSPART);
1040                 gpt_write_mbr_entry(table->mbr, 0, 0xee, 1,
1041                     MIN(pp->mediasize / pp->sectorsize - 1, UINT32_MAX));
1042                 /* Mark the PMBR active since some BIOS require it. */
1043                 table->mbr[DOSPARTOFF] = 0x80;
1044         }
1045         le16enc(table->mbr + DOSMAGICOFFSET, DOSMAGIC);
1046
1047         /* Write the PMBR */
1048         buf = g_malloc(pp->sectorsize, M_WAITOK | M_ZERO);
1049         bcopy(table->mbr, buf, MBRSIZE);
1050         error = g_write_data(cp, 0, buf, pp->sectorsize);
1051         g_free(buf);
1052         if (error)
1053                 return (error);
1054
1055         /* Allocate space for the header and entries. */
1056         buf = g_malloc((tblsz + 1) * pp->sectorsize, M_WAITOK | M_ZERO);
1057
1058         memcpy(buf, table->hdr->hdr_sig, sizeof(table->hdr->hdr_sig));
1059         le32enc(buf + 8, table->hdr->hdr_revision);
1060         le32enc(buf + 12, table->hdr->hdr_size);
1061         le64enc(buf + 40, table->hdr->hdr_lba_start);
1062         le64enc(buf + 48, table->hdr->hdr_lba_end);
1063         le_uuid_enc(buf + 56, &table->hdr->hdr_uuid);
1064         le32enc(buf + 80, table->hdr->hdr_entries);
1065         le32enc(buf + 84, table->hdr->hdr_entsz);
1066
1067         LIST_FOREACH(baseentry, &basetable->gpt_entry, gpe_entry) {
1068                 if (baseentry->gpe_deleted)
1069                         continue;
1070                 entry = (struct g_part_gpt_entry *)baseentry;
1071                 index = baseentry->gpe_index - 1;
1072                 bp = buf + pp->sectorsize + table->hdr->hdr_entsz * index;
1073                 le_uuid_enc(bp, &entry->ent.ent_type);
1074                 le_uuid_enc(bp + 16, &entry->ent.ent_uuid);
1075                 le64enc(bp + 32, entry->ent.ent_lba_start);
1076                 le64enc(bp + 40, entry->ent.ent_lba_end);
1077                 le64enc(bp + 48, entry->ent.ent_attr);
1078                 memcpy(bp + 56, entry->ent.ent_name,
1079                     sizeof(entry->ent.ent_name));
1080         }
1081
1082         crc = crc32(buf + pp->sectorsize,
1083             table->hdr->hdr_entries * table->hdr->hdr_entsz);
1084         le32enc(buf + 88, crc);
1085
1086         /* Write primary meta-data. */
1087         le32enc(buf + 16, 0);   /* hdr_crc_self. */
1088         le64enc(buf + 24, table->lba[GPT_ELT_PRIHDR]);  /* hdr_lba_self. */
1089         le64enc(buf + 32, table->lba[GPT_ELT_SECHDR]);  /* hdr_lba_alt. */
1090         le64enc(buf + 72, table->lba[GPT_ELT_PRITBL]);  /* hdr_lba_table. */
1091         crc = crc32(buf, table->hdr->hdr_size);
1092         le32enc(buf + 16, crc);
1093
1094         for (index = 0; index < tblsz; index += MAXPHYS / pp->sectorsize) {
1095                 error = g_write_data(cp,
1096                     (table->lba[GPT_ELT_PRITBL] + index) * pp->sectorsize,
1097                     buf + (index + 1) * pp->sectorsize,
1098                     (tblsz - index > MAXPHYS / pp->sectorsize) ? MAXPHYS:
1099                     (tblsz - index) * pp->sectorsize);
1100                 if (error)
1101                         goto out;
1102         }
1103         error = g_write_data(cp, table->lba[GPT_ELT_PRIHDR] * pp->sectorsize,
1104             buf, pp->sectorsize);
1105         if (error)
1106                 goto out;
1107
1108         /* Write secondary meta-data. */
1109         le32enc(buf + 16, 0);   /* hdr_crc_self. */
1110         le64enc(buf + 24, table->lba[GPT_ELT_SECHDR]);  /* hdr_lba_self. */
1111         le64enc(buf + 32, table->lba[GPT_ELT_PRIHDR]);  /* hdr_lba_alt. */
1112         le64enc(buf + 72, table->lba[GPT_ELT_SECTBL]);  /* hdr_lba_table. */
1113         crc = crc32(buf, table->hdr->hdr_size);
1114         le32enc(buf + 16, crc);
1115
1116         for (index = 0; index < tblsz; index += MAXPHYS / pp->sectorsize) {
1117                 error = g_write_data(cp,
1118                     (table->lba[GPT_ELT_SECTBL] + index) * pp->sectorsize,
1119                     buf + (index + 1) * pp->sectorsize,
1120                     (tblsz - index > MAXPHYS / pp->sectorsize) ? MAXPHYS:
1121                     (tblsz - index) * pp->sectorsize);
1122                 if (error)
1123                         goto out;
1124         }
1125         error = g_write_data(cp, table->lba[GPT_ELT_SECHDR] * pp->sectorsize,
1126             buf, pp->sectorsize);
1127
1128  out:
1129         g_free(buf);
1130         return (error);
1131 }
1132
1133 static void
1134 g_gpt_set_defaults(struct g_part_table *basetable, struct g_provider *pp)
1135 {
1136         struct g_part_gpt_table *table;
1137         quad_t last;
1138         size_t tblsz;
1139
1140         table = (struct g_part_gpt_table *)basetable;
1141         last = pp->mediasize / pp->sectorsize - 1;
1142         tblsz = (basetable->gpt_entries * sizeof(struct gpt_ent) +
1143             pp->sectorsize - 1) / pp->sectorsize;
1144
1145         table->lba[GPT_ELT_PRIHDR] = 1;
1146         table->lba[GPT_ELT_PRITBL] = 2;
1147         table->lba[GPT_ELT_SECHDR] = last;
1148         table->lba[GPT_ELT_SECTBL] = last - tblsz;
1149         table->state[GPT_ELT_PRIHDR] = GPT_STATE_OK;
1150         table->state[GPT_ELT_PRITBL] = GPT_STATE_OK;
1151         table->state[GPT_ELT_SECHDR] = GPT_STATE_OK;
1152         table->state[GPT_ELT_SECTBL] = GPT_STATE_OK;
1153
1154         table->hdr->hdr_lba_start = 2 + tblsz;
1155         table->hdr->hdr_lba_end = last - tblsz - 1;
1156
1157         basetable->gpt_first = table->hdr->hdr_lba_start;
1158         basetable->gpt_last = table->hdr->hdr_lba_end;
1159 }
1160
1161 static void
1162 g_gpt_printf_utf16(struct sbuf *sb, uint16_t *str, size_t len)
1163 {
1164         u_int bo;
1165         uint32_t ch;
1166         uint16_t c;
1167
1168         bo = LITTLE_ENDIAN;     /* GPT is little-endian */
1169         while (len > 0 && *str != 0) {
1170                 ch = (bo == BIG_ENDIAN) ? be16toh(*str) : le16toh(*str);
1171                 str++, len--;
1172                 if ((ch & 0xf800) == 0xd800) {
1173                         if (len > 0) {
1174                                 c = (bo == BIG_ENDIAN) ? be16toh(*str)
1175                                     : le16toh(*str);
1176                                 str++, len--;
1177                         } else
1178                                 c = 0xfffd;
1179                         if ((ch & 0x400) == 0 && (c & 0xfc00) == 0xdc00) {
1180                                 ch = ((ch & 0x3ff) << 10) + (c & 0x3ff);
1181                                 ch += 0x10000;
1182                         } else
1183                                 ch = 0xfffd;
1184                 } else if (ch == 0xfffe) { /* BOM (U+FEFF) swapped. */
1185                         bo = (bo == BIG_ENDIAN) ? LITTLE_ENDIAN : BIG_ENDIAN;
1186                         continue;
1187                 } else if (ch == 0xfeff) /* BOM (U+FEFF) unswapped. */
1188                         continue;
1189
1190                 /* Write the Unicode character in UTF-8 */
1191                 if (ch < 0x80)
1192                         sbuf_printf(sb, "%c", ch);
1193                 else if (ch < 0x800)
1194                         sbuf_printf(sb, "%c%c", 0xc0 | (ch >> 6),
1195                             0x80 | (ch & 0x3f));
1196                 else if (ch < 0x10000)
1197                         sbuf_printf(sb, "%c%c%c", 0xe0 | (ch >> 12),
1198                             0x80 | ((ch >> 6) & 0x3f), 0x80 | (ch & 0x3f));
1199                 else if (ch < 0x200000)
1200                         sbuf_printf(sb, "%c%c%c%c", 0xf0 | (ch >> 18),
1201                             0x80 | ((ch >> 12) & 0x3f),
1202                             0x80 | ((ch >> 6) & 0x3f), 0x80 | (ch & 0x3f));
1203         }
1204 }
1205
1206 static void
1207 g_gpt_utf8_to_utf16(const uint8_t *s8, uint16_t *s16, size_t s16len)
1208 {
1209         size_t s16idx, s8idx;
1210         uint32_t utfchar;
1211         unsigned int c, utfbytes;
1212
1213         s8idx = s16idx = 0;
1214         utfchar = 0;
1215         utfbytes = 0;
1216         bzero(s16, s16len << 1);
1217         while (s8[s8idx] != 0 && s16idx < s16len) {
1218                 c = s8[s8idx++];
1219                 if ((c & 0xc0) != 0x80) {
1220                         /* Initial characters. */
1221                         if (utfbytes != 0) {
1222                                 /* Incomplete encoding of previous char. */
1223                                 s16[s16idx++] = htole16(0xfffd);
1224                         }
1225                         if ((c & 0xf8) == 0xf0) {
1226                                 utfchar = c & 0x07;
1227                                 utfbytes = 3;
1228                         } else if ((c & 0xf0) == 0xe0) {
1229                                 utfchar = c & 0x0f;
1230                                 utfbytes = 2;
1231                         } else if ((c & 0xe0) == 0xc0) {
1232                                 utfchar = c & 0x1f;
1233                                 utfbytes = 1;
1234                         } else {
1235                                 utfchar = c & 0x7f;
1236                                 utfbytes = 0;
1237                         }
1238                 } else {
1239                         /* Followup characters. */
1240                         if (utfbytes > 0) {
1241                                 utfchar = (utfchar << 6) + (c & 0x3f);
1242                                 utfbytes--;
1243                         } else if (utfbytes == 0)
1244                                 utfbytes = ~0;
1245                 }
1246                 /*
1247                  * Write the complete Unicode character as UTF-16 when we
1248                  * have all the UTF-8 charactars collected.
1249                  */
1250                 if (utfbytes == 0) {
1251                         /*
1252                          * If we need to write 2 UTF-16 characters, but
1253                          * we only have room for 1, then we truncate the
1254                          * string by writing a 0 instead.
1255                          */
1256                         if (utfchar >= 0x10000 && s16idx < s16len - 1) {
1257                                 s16[s16idx++] =
1258                                     htole16(0xd800 | ((utfchar >> 10) - 0x40));
1259                                 s16[s16idx++] =
1260                                     htole16(0xdc00 | (utfchar & 0x3ff));
1261                         } else
1262                                 s16[s16idx++] = (utfchar >= 0x10000) ? 0 :
1263                                     htole16(utfchar);
1264                 }
1265         }
1266         /*
1267          * If our input string was truncated, append an invalid encoding
1268          * character to the output string.
1269          */
1270         if (utfbytes != 0 && s16idx < s16len)
1271                 s16[s16idx++] = htole16(0xfffd);
1272 }