]> CyberLeo.Net >> Repos - FreeBSD/releng/8.2.git/blob - sys/geom/part/g_part_gpt.c
MFC r216454:
[FreeBSD/releng/8.2.git] / sys / geom / part / g_part_gpt.c
1 /*-
2  * Copyright (c) 2002, 2005, 2006, 2007 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/uuid.h>
45 #include <geom/geom.h>
46 #include <geom/part/g_part.h>
47
48 #include "g_part_if.h"
49
50 CTASSERT(offsetof(struct gpt_hdr, padding) == 92);
51 CTASSERT(sizeof(struct gpt_ent) == 128);
52
53 #define EQUUID(a,b)     (memcmp(a, b, sizeof(struct uuid)) == 0)
54
55 #define MBRSIZE         512
56
57 enum gpt_elt {
58         GPT_ELT_PRIHDR,
59         GPT_ELT_PRITBL,
60         GPT_ELT_SECHDR,
61         GPT_ELT_SECTBL,
62         GPT_ELT_COUNT
63 };
64
65 enum gpt_state {
66         GPT_STATE_UNKNOWN,      /* Not determined. */
67         GPT_STATE_MISSING,      /* No signature found. */
68         GPT_STATE_CORRUPT,      /* Checksum mismatch. */
69         GPT_STATE_INVALID,      /* Nonconformant/invalid. */
70         GPT_STATE_OK            /* Perfectly fine. */
71 };
72
73 struct g_part_gpt_table {
74         struct g_part_table     base;
75         u_char                  mbr[MBRSIZE];
76         struct gpt_hdr          *hdr;
77         quad_t                  lba[GPT_ELT_COUNT];
78         enum gpt_state          state[GPT_ELT_COUNT];
79 };
80
81 struct g_part_gpt_entry {
82         struct g_part_entry     base;
83         struct gpt_ent          ent;
84 };
85
86 static void g_gpt_printf_utf16(struct sbuf *, uint16_t *, size_t);
87 static void g_gpt_utf8_to_utf16(const uint8_t *, uint16_t *, size_t);
88
89 static int g_part_gpt_add(struct g_part_table *, struct g_part_entry *,
90     struct g_part_parms *);
91 static int g_part_gpt_bootcode(struct g_part_table *, struct g_part_parms *);
92 static int g_part_gpt_create(struct g_part_table *, struct g_part_parms *);
93 static int g_part_gpt_destroy(struct g_part_table *, struct g_part_parms *);
94 static void g_part_gpt_dumpconf(struct g_part_table *, struct g_part_entry *,
95     struct sbuf *, const char *);
96 static int g_part_gpt_dumpto(struct g_part_table *, struct g_part_entry *);
97 static int g_part_gpt_modify(struct g_part_table *, struct g_part_entry *,
98     struct g_part_parms *);
99 static const char *g_part_gpt_name(struct g_part_table *, struct g_part_entry *,
100     char *, size_t);
101 static int g_part_gpt_probe(struct g_part_table *, struct g_consumer *);
102 static int g_part_gpt_read(struct g_part_table *, struct g_consumer *);
103 static int g_part_gpt_setunset(struct g_part_table *table,
104     struct g_part_entry *baseentry, const char *attrib, unsigned int set);
105 static const char *g_part_gpt_type(struct g_part_table *, struct g_part_entry *,
106     char *, size_t);
107 static int g_part_gpt_write(struct g_part_table *, struct g_consumer *);
108 static int g_part_gpt_resize(struct g_part_table *, struct g_part_entry *,
109     struct g_part_parms *);
110 static int g_part_gpt_recover(struct g_part_table *);
111
112 static kobj_method_t g_part_gpt_methods[] = {
113         KOBJMETHOD(g_part_add,          g_part_gpt_add),
114         KOBJMETHOD(g_part_bootcode,     g_part_gpt_bootcode),
115         KOBJMETHOD(g_part_create,       g_part_gpt_create),
116         KOBJMETHOD(g_part_destroy,      g_part_gpt_destroy),
117         KOBJMETHOD(g_part_dumpconf,     g_part_gpt_dumpconf),
118         KOBJMETHOD(g_part_dumpto,       g_part_gpt_dumpto),
119         KOBJMETHOD(g_part_modify,       g_part_gpt_modify),
120         KOBJMETHOD(g_part_resize,       g_part_gpt_resize),
121         KOBJMETHOD(g_part_name,         g_part_gpt_name),
122         KOBJMETHOD(g_part_probe,        g_part_gpt_probe),
123         KOBJMETHOD(g_part_read,         g_part_gpt_read),
124         KOBJMETHOD(g_part_recover,      g_part_gpt_recover),
125         KOBJMETHOD(g_part_setunset,     g_part_gpt_setunset),
126         KOBJMETHOD(g_part_type,         g_part_gpt_type),
127         KOBJMETHOD(g_part_write,        g_part_gpt_write),
128         { 0, 0 }
129 };
130
131 static struct g_part_scheme g_part_gpt_scheme = {
132         "GPT",
133         g_part_gpt_methods,
134         sizeof(struct g_part_gpt_table),
135         .gps_entrysz = sizeof(struct g_part_gpt_entry),
136         .gps_minent = 128,
137         .gps_maxent = INT_MAX,
138         .gps_bootcodesz = MBRSIZE,
139 };
140 G_PART_SCHEME_DECLARE(g_part_gpt);
141
142 static struct uuid gpt_uuid_apple_boot = GPT_ENT_TYPE_APPLE_BOOT;
143 static struct uuid gpt_uuid_apple_hfs = GPT_ENT_TYPE_APPLE_HFS;
144 static struct uuid gpt_uuid_apple_label = GPT_ENT_TYPE_APPLE_LABEL;
145 static struct uuid gpt_uuid_apple_raid = GPT_ENT_TYPE_APPLE_RAID;
146 static struct uuid gpt_uuid_apple_raid_offline = GPT_ENT_TYPE_APPLE_RAID_OFFLINE;
147 static struct uuid gpt_uuid_apple_tv_recovery = GPT_ENT_TYPE_APPLE_TV_RECOVERY;
148 static struct uuid gpt_uuid_apple_ufs = GPT_ENT_TYPE_APPLE_UFS;
149 static struct uuid gpt_uuid_efi = GPT_ENT_TYPE_EFI;
150 static struct uuid gpt_uuid_freebsd = GPT_ENT_TYPE_FREEBSD;
151 static struct uuid gpt_uuid_freebsd_boot = GPT_ENT_TYPE_FREEBSD_BOOT;
152 static struct uuid gpt_uuid_freebsd_swap = GPT_ENT_TYPE_FREEBSD_SWAP;
153 static struct uuid gpt_uuid_freebsd_ufs = GPT_ENT_TYPE_FREEBSD_UFS;
154 static struct uuid gpt_uuid_freebsd_vinum = GPT_ENT_TYPE_FREEBSD_VINUM;
155 static struct uuid gpt_uuid_freebsd_zfs = GPT_ENT_TYPE_FREEBSD_ZFS;
156 static struct uuid gpt_uuid_linux_data = GPT_ENT_TYPE_LINUX_DATA;
157 static struct uuid gpt_uuid_linux_lvm = GPT_ENT_TYPE_LINUX_LVM;
158 static struct uuid gpt_uuid_linux_raid = GPT_ENT_TYPE_LINUX_RAID;
159 static struct uuid gpt_uuid_linux_swap = GPT_ENT_TYPE_LINUX_SWAP;
160 static struct uuid gpt_uuid_ms_basic_data = GPT_ENT_TYPE_MS_BASIC_DATA;
161 static struct uuid gpt_uuid_ms_reserved = GPT_ENT_TYPE_MS_RESERVED;
162 static struct uuid gpt_uuid_ms_ldm_data = GPT_ENT_TYPE_MS_LDM_DATA;
163 static struct uuid gpt_uuid_ms_ldm_metadata = GPT_ENT_TYPE_MS_LDM_METADATA;
164 static struct uuid gpt_uuid_netbsd_ccd = GPT_ENT_TYPE_NETBSD_CCD;
165 static struct uuid gpt_uuid_netbsd_cgd = GPT_ENT_TYPE_NETBSD_CGD;
166 static struct uuid gpt_uuid_netbsd_ffs = GPT_ENT_TYPE_NETBSD_FFS;
167 static struct uuid gpt_uuid_netbsd_lfs = GPT_ENT_TYPE_NETBSD_LFS;
168 static struct uuid gpt_uuid_netbsd_raid = GPT_ENT_TYPE_NETBSD_RAID;
169 static struct uuid gpt_uuid_netbsd_swap = GPT_ENT_TYPE_NETBSD_SWAP;
170 static struct uuid gpt_uuid_mbr = GPT_ENT_TYPE_MBR;
171 static struct uuid gpt_uuid_unused = GPT_ENT_TYPE_UNUSED;
172
173 static struct g_part_uuid_alias {
174         struct uuid *uuid;
175         int alias;
176 } gpt_uuid_alias_match[] = {
177         { &gpt_uuid_apple_boot,         G_PART_ALIAS_APPLE_BOOT },
178         { &gpt_uuid_apple_hfs,          G_PART_ALIAS_APPLE_HFS },
179         { &gpt_uuid_apple_label,        G_PART_ALIAS_APPLE_LABEL },
180         { &gpt_uuid_apple_raid,         G_PART_ALIAS_APPLE_RAID },
181         { &gpt_uuid_apple_raid_offline, G_PART_ALIAS_APPLE_RAID_OFFLINE },
182         { &gpt_uuid_apple_tv_recovery,  G_PART_ALIAS_APPLE_TV_RECOVERY },
183         { &gpt_uuid_apple_ufs,          G_PART_ALIAS_APPLE_UFS },
184         { &gpt_uuid_efi,                G_PART_ALIAS_EFI },
185         { &gpt_uuid_freebsd,            G_PART_ALIAS_FREEBSD },
186         { &gpt_uuid_freebsd_boot,       G_PART_ALIAS_FREEBSD_BOOT },
187         { &gpt_uuid_freebsd_swap,       G_PART_ALIAS_FREEBSD_SWAP },
188         { &gpt_uuid_freebsd_ufs,        G_PART_ALIAS_FREEBSD_UFS },
189         { &gpt_uuid_freebsd_vinum,      G_PART_ALIAS_FREEBSD_VINUM },
190         { &gpt_uuid_freebsd_zfs,        G_PART_ALIAS_FREEBSD_ZFS },
191         { &gpt_uuid_linux_data,         G_PART_ALIAS_LINUX_DATA },
192         { &gpt_uuid_linux_lvm,          G_PART_ALIAS_LINUX_LVM },
193         { &gpt_uuid_linux_raid,         G_PART_ALIAS_LINUX_RAID },
194         { &gpt_uuid_linux_swap,         G_PART_ALIAS_LINUX_SWAP },
195         { &gpt_uuid_mbr,                G_PART_ALIAS_MBR },
196         { &gpt_uuid_ms_basic_data,      G_PART_ALIAS_MS_BASIC_DATA },
197         { &gpt_uuid_ms_ldm_data,        G_PART_ALIAS_MS_LDM_DATA },
198         { &gpt_uuid_ms_ldm_metadata,    G_PART_ALIAS_MS_LDM_METADATA },
199         { &gpt_uuid_ms_reserved,        G_PART_ALIAS_MS_RESERVED },
200         { &gpt_uuid_netbsd_ccd,         G_PART_ALIAS_NETBSD_CCD },
201         { &gpt_uuid_netbsd_cgd,         G_PART_ALIAS_NETBSD_CGD },
202         { &gpt_uuid_netbsd_ffs,         G_PART_ALIAS_NETBSD_FFS },
203         { &gpt_uuid_netbsd_lfs,         G_PART_ALIAS_NETBSD_LFS },
204         { &gpt_uuid_netbsd_raid,        G_PART_ALIAS_NETBSD_RAID },
205         { &gpt_uuid_netbsd_swap,        G_PART_ALIAS_NETBSD_SWAP },
206
207         { NULL, 0 }
208 };
209
210 static struct gpt_hdr *
211 gpt_read_hdr(struct g_part_gpt_table *table, struct g_consumer *cp,
212     enum gpt_elt elt)
213 {
214         struct gpt_hdr *buf, *hdr;
215         struct g_provider *pp;
216         quad_t lba, last;
217         int error;
218         uint32_t crc, sz;
219
220         pp = cp->provider;
221         last = (pp->mediasize / pp->sectorsize) - 1;
222         table->state[elt] = GPT_STATE_MISSING;
223         /*
224          * If the primary header is valid look for secondary
225          * header in AlternateLBA, otherwise in the last medium's LBA.
226          */
227         if (elt == GPT_ELT_SECHDR) {
228                 if (table->state[GPT_ELT_PRIHDR] != GPT_STATE_OK)
229                         table->lba[elt] = last;
230         } else
231                 table->lba[elt] = 1;
232         buf = g_read_data(cp, table->lba[elt] * pp->sectorsize, pp->sectorsize,
233             &error);
234         if (buf == NULL)
235                 return (NULL);
236         hdr = NULL;
237         if (memcmp(buf->hdr_sig, GPT_HDR_SIG, sizeof(buf->hdr_sig)) != 0)
238                 goto fail;
239
240         table->state[elt] = GPT_STATE_CORRUPT;
241         sz = le32toh(buf->hdr_size);
242         if (sz < 92 || sz > pp->sectorsize)
243                 goto fail;
244
245         hdr = g_malloc(sz, M_WAITOK | M_ZERO);
246         bcopy(buf, hdr, sz);
247         hdr->hdr_size = sz;
248
249         crc = le32toh(buf->hdr_crc_self);
250         buf->hdr_crc_self = 0;
251         if (crc32(buf, sz) != crc)
252                 goto fail;
253         hdr->hdr_crc_self = crc;
254
255         table->state[elt] = GPT_STATE_INVALID;
256         hdr->hdr_revision = le32toh(buf->hdr_revision);
257         if (hdr->hdr_revision < GPT_HDR_REVISION)
258                 goto fail;
259         hdr->hdr_lba_self = le64toh(buf->hdr_lba_self);
260         if (hdr->hdr_lba_self != table->lba[elt])
261                 goto fail;
262         hdr->hdr_lba_alt = le64toh(buf->hdr_lba_alt);
263         if (hdr->hdr_lba_alt == hdr->hdr_lba_self ||
264             hdr->hdr_lba_alt > last)
265                 goto fail;
266
267         /* Check the managed area. */
268         hdr->hdr_lba_start = le64toh(buf->hdr_lba_start);
269         if (hdr->hdr_lba_start < 2 || hdr->hdr_lba_start >= last)
270                 goto fail;
271         hdr->hdr_lba_end = le64toh(buf->hdr_lba_end);
272         if (hdr->hdr_lba_end < hdr->hdr_lba_start || hdr->hdr_lba_end >= last)
273                 goto fail;
274
275         /* Check the table location and size of the table. */
276         hdr->hdr_entries = le32toh(buf->hdr_entries);
277         hdr->hdr_entsz = le32toh(buf->hdr_entsz);
278         if (hdr->hdr_entries == 0 || hdr->hdr_entsz < 128 ||
279             (hdr->hdr_entsz & 7) != 0)
280                 goto fail;
281         hdr->hdr_lba_table = le64toh(buf->hdr_lba_table);
282         if (hdr->hdr_lba_table < 2 || hdr->hdr_lba_table >= last)
283                 goto fail;
284         if (hdr->hdr_lba_table >= hdr->hdr_lba_start &&
285             hdr->hdr_lba_table <= hdr->hdr_lba_end)
286                 goto fail;
287         lba = hdr->hdr_lba_table +
288             (hdr->hdr_entries * hdr->hdr_entsz + pp->sectorsize - 1) /
289             pp->sectorsize - 1;
290         if (lba >= last)
291                 goto fail;
292         if (lba >= hdr->hdr_lba_start && lba <= hdr->hdr_lba_end)
293                 goto fail;
294
295         table->state[elt] = GPT_STATE_OK;
296         le_uuid_dec(&buf->hdr_uuid, &hdr->hdr_uuid);
297         hdr->hdr_crc_table = le32toh(buf->hdr_crc_table);
298
299         /* save LBA for secondary header */
300         if (elt == GPT_ELT_PRIHDR)
301                 table->lba[GPT_ELT_SECHDR] = hdr->hdr_lba_alt;
302
303         g_free(buf);
304         return (hdr);
305
306  fail:
307         if (hdr != NULL)
308                 g_free(hdr);
309         g_free(buf);
310         return (NULL);
311 }
312
313 static struct gpt_ent *
314 gpt_read_tbl(struct g_part_gpt_table *table, struct g_consumer *cp,
315     enum gpt_elt elt, struct gpt_hdr *hdr)
316 {
317         struct g_provider *pp;
318         struct gpt_ent *ent, *tbl;
319         char *buf, *p;
320         unsigned int idx, sectors, tblsz;
321         int error;
322
323         if (hdr == NULL)
324                 return (NULL);
325
326         pp = cp->provider;
327         table->lba[elt] = hdr->hdr_lba_table;
328
329         table->state[elt] = GPT_STATE_MISSING;
330         tblsz = hdr->hdr_entries * hdr->hdr_entsz;
331         sectors = (tblsz + pp->sectorsize - 1) / pp->sectorsize;
332         buf = g_read_data(cp, table->lba[elt] * pp->sectorsize, 
333             sectors * pp->sectorsize, &error);
334         if (buf == NULL)
335                 return (NULL);
336
337         table->state[elt] = GPT_STATE_CORRUPT;
338         if (crc32(buf, tblsz) != hdr->hdr_crc_table) {
339                 g_free(buf);
340                 return (NULL);
341         }
342
343         table->state[elt] = GPT_STATE_OK;
344         tbl = g_malloc(hdr->hdr_entries * sizeof(struct gpt_ent),
345             M_WAITOK | M_ZERO);
346
347         for (idx = 0, ent = tbl, p = buf;
348              idx < hdr->hdr_entries;
349              idx++, ent++, p += hdr->hdr_entsz) {
350                 le_uuid_dec(p, &ent->ent_type);
351                 le_uuid_dec(p + 16, &ent->ent_uuid);
352                 ent->ent_lba_start = le64dec(p + 32);
353                 ent->ent_lba_end = le64dec(p + 40);
354                 ent->ent_attr = le64dec(p + 48);
355                 /* Keep UTF-16 in little-endian. */
356                 bcopy(p + 56, ent->ent_name, sizeof(ent->ent_name));
357         }
358
359         g_free(buf);
360         return (tbl);
361 }
362
363 static int
364 gpt_matched_hdrs(struct gpt_hdr *pri, struct gpt_hdr *sec)
365 {
366
367         if (pri == NULL || sec == NULL)
368                 return (0);
369
370         if (!EQUUID(&pri->hdr_uuid, &sec->hdr_uuid))
371                 return (0);
372         return ((pri->hdr_revision == sec->hdr_revision &&
373             pri->hdr_size == sec->hdr_size &&
374             pri->hdr_lba_start == sec->hdr_lba_start &&
375             pri->hdr_lba_end == sec->hdr_lba_end &&
376             pri->hdr_entries == sec->hdr_entries &&
377             pri->hdr_entsz == sec->hdr_entsz &&
378             pri->hdr_crc_table == sec->hdr_crc_table) ? 1 : 0);
379 }
380
381 static int
382 gpt_parse_type(const char *type, struct uuid *uuid)
383 {
384         struct uuid tmp;
385         const char *alias;
386         int error;
387         struct g_part_uuid_alias *uap;
388
389         if (type[0] == '!') {
390                 error = parse_uuid(type + 1, &tmp);
391                 if (error)
392                         return (error);
393                 if (EQUUID(&tmp, &gpt_uuid_unused))
394                         return (EINVAL);
395                 *uuid = tmp;
396                 return (0);
397         }
398         for (uap = &gpt_uuid_alias_match[0]; uap->uuid; uap++) {
399                 alias = g_part_alias_name(uap->alias);
400                 if (!strcasecmp(type, alias)) {
401                         *uuid = *uap->uuid;
402                         return (0);
403                 }
404         }
405         return (EINVAL);
406 }
407
408 static int
409 g_part_gpt_add(struct g_part_table *basetable, struct g_part_entry *baseentry,
410     struct g_part_parms *gpp)
411 {
412         struct g_part_gpt_entry *entry;
413         int error;
414
415         entry = (struct g_part_gpt_entry *)baseentry;
416         error = gpt_parse_type(gpp->gpp_type, &entry->ent.ent_type);
417         if (error)
418                 return (error);
419         kern_uuidgen(&entry->ent.ent_uuid, 1);
420         entry->ent.ent_lba_start = baseentry->gpe_start;
421         entry->ent.ent_lba_end = baseentry->gpe_end;
422         if (baseentry->gpe_deleted) {
423                 entry->ent.ent_attr = 0;
424                 bzero(entry->ent.ent_name, sizeof(entry->ent.ent_name));
425         }
426         if (gpp->gpp_parms & G_PART_PARM_LABEL)
427                 g_gpt_utf8_to_utf16(gpp->gpp_label, entry->ent.ent_name,
428                     sizeof(entry->ent.ent_name));
429         return (0);
430 }
431
432 static int
433 g_part_gpt_bootcode(struct g_part_table *basetable, struct g_part_parms *gpp)
434 {
435         struct g_part_gpt_table *table;
436         size_t codesz;
437
438         codesz = DOSPARTOFF;
439         table = (struct g_part_gpt_table *)basetable;
440         bzero(table->mbr, codesz);
441         codesz = MIN(codesz, gpp->gpp_codesize);
442         if (codesz > 0)
443                 bcopy(gpp->gpp_codeptr, table->mbr, codesz);
444
445         /* Mark the PMBR active since some BIOS require it */
446         table->mbr[DOSPARTOFF] = 0x80;          /* status */
447         return (0);
448 }
449
450 static int
451 g_part_gpt_create(struct g_part_table *basetable, struct g_part_parms *gpp)
452 {
453         struct g_provider *pp;
454         struct g_part_gpt_table *table;
455         quad_t last;
456         size_t tblsz;
457
458         /* We don't nest, which means that our depth should be 0. */
459         if (basetable->gpt_depth != 0)
460                 return (ENXIO);
461
462         table = (struct g_part_gpt_table *)basetable;
463         pp = gpp->gpp_provider;
464         tblsz = (basetable->gpt_entries * sizeof(struct gpt_ent) +
465             pp->sectorsize - 1) / pp->sectorsize;
466         if (pp->sectorsize < MBRSIZE ||
467             pp->mediasize < (3 + 2 * tblsz + basetable->gpt_entries) *
468             pp->sectorsize)
469                 return (ENOSPC);
470
471         last = (pp->mediasize / pp->sectorsize) - 1;
472
473         le16enc(table->mbr + DOSMAGICOFFSET, DOSMAGIC);
474         table->mbr[DOSPARTOFF + 1] = 0x01;              /* shd */
475         table->mbr[DOSPARTOFF + 2] = 0x01;              /* ssect */
476         table->mbr[DOSPARTOFF + 3] = 0x00;              /* scyl */
477         table->mbr[DOSPARTOFF + 4] = 0xee;              /* typ */
478         table->mbr[DOSPARTOFF + 5] = 0xff;              /* ehd */
479         table->mbr[DOSPARTOFF + 6] = 0xff;              /* esect */
480         table->mbr[DOSPARTOFF + 7] = 0xff;              /* ecyl */
481         le32enc(table->mbr + DOSPARTOFF + 8, 1);        /* start */
482         le32enc(table->mbr + DOSPARTOFF + 12, MIN(last, 0xffffffffLL));
483
484         table->lba[GPT_ELT_PRIHDR] = 1;
485         table->lba[GPT_ELT_PRITBL] = 2;
486         table->lba[GPT_ELT_SECHDR] = last;
487         table->lba[GPT_ELT_SECTBL] = last - tblsz;
488
489         /* Allocate space for the header */
490         table->hdr = g_malloc(sizeof(struct gpt_hdr), M_WAITOK | M_ZERO);
491
492         bcopy(GPT_HDR_SIG, table->hdr->hdr_sig, sizeof(table->hdr->hdr_sig));
493         table->hdr->hdr_revision = GPT_HDR_REVISION;
494         table->hdr->hdr_size = offsetof(struct gpt_hdr, padding);
495         table->hdr->hdr_lba_start = 2 + tblsz;
496         table->hdr->hdr_lba_end = last - tblsz - 1;
497         kern_uuidgen(&table->hdr->hdr_uuid, 1);
498         table->hdr->hdr_entries = basetable->gpt_entries;
499         table->hdr->hdr_entsz = sizeof(struct gpt_ent);
500
501         basetable->gpt_first = table->hdr->hdr_lba_start;
502         basetable->gpt_last = table->hdr->hdr_lba_end;
503         return (0);
504 }
505
506 static int
507 g_part_gpt_destroy(struct g_part_table *basetable, struct g_part_parms *gpp)
508 {
509         struct g_part_gpt_table *table;
510         struct g_provider *pp;
511
512         table = (struct g_part_gpt_table *)basetable;
513         pp = LIST_FIRST(&basetable->gpt_gp->consumer)->provider;
514         g_free(table->hdr);
515         table->hdr = NULL;
516
517         /*
518          * Wipe the first 2 sectors to clear the partitioning. Wipe the last
519          * sector only if it has valid secondary header.
520          */
521         basetable->gpt_smhead |= 3;
522         if (table->state[GPT_ELT_SECHDR] == GPT_STATE_OK &&
523             table->lba[GPT_ELT_SECHDR] == pp->mediasize / pp->sectorsize - 1)
524                 basetable->gpt_smtail |= 1;
525         return (0);
526 }
527
528 static void
529 g_part_gpt_dumpconf(struct g_part_table *table, struct g_part_entry *baseentry, 
530     struct sbuf *sb, const char *indent)
531 {
532         struct g_part_gpt_entry *entry;
533  
534         entry = (struct g_part_gpt_entry *)baseentry;
535         if (indent == NULL) {
536                 /* conftxt: libdisk compatibility */
537                 sbuf_printf(sb, " xs GPT xt ");
538                 sbuf_printf_uuid(sb, &entry->ent.ent_type);
539         } else if (entry != NULL) {
540                 /* confxml: partition entry information */
541                 sbuf_printf(sb, "%s<label>", indent);
542                 g_gpt_printf_utf16(sb, entry->ent.ent_name,
543                     sizeof(entry->ent.ent_name) >> 1);
544                 sbuf_printf(sb, "</label>\n");
545                 if (entry->ent.ent_attr & GPT_ENT_ATTR_BOOTME)
546                         sbuf_printf(sb, "%s<attrib>bootme</attrib>\n", indent);
547                 if (entry->ent.ent_attr & GPT_ENT_ATTR_BOOTONCE) {
548                         sbuf_printf(sb, "%s<attrib>bootonce</attrib>\n",
549                             indent);
550                 }
551                 if (entry->ent.ent_attr & GPT_ENT_ATTR_BOOTFAILED) {
552                         sbuf_printf(sb, "%s<attrib>bootfailed</attrib>\n",
553                             indent);
554                 }
555                 sbuf_printf(sb, "%s<rawtype>", indent);
556                 sbuf_printf_uuid(sb, &entry->ent.ent_type);
557                 sbuf_printf(sb, "</rawtype>\n");
558                 sbuf_printf(sb, "%s<rawuuid>", indent);
559                 sbuf_printf_uuid(sb, &entry->ent.ent_uuid);
560                 sbuf_printf(sb, "</rawuuid>\n");
561         } else {
562                 /* confxml: scheme information */
563         }
564 }
565
566 static int
567 g_part_gpt_dumpto(struct g_part_table *table, struct g_part_entry *baseentry)  
568 {
569         struct g_part_gpt_entry *entry;
570
571         entry = (struct g_part_gpt_entry *)baseentry;
572         return ((EQUUID(&entry->ent.ent_type, &gpt_uuid_freebsd_swap) ||
573             EQUUID(&entry->ent.ent_type, &gpt_uuid_linux_swap)) ? 1 : 0);
574 }
575
576 static int
577 g_part_gpt_modify(struct g_part_table *basetable,
578     struct g_part_entry *baseentry, struct g_part_parms *gpp)
579 {
580         struct g_part_gpt_entry *entry;
581         int error;
582
583         entry = (struct g_part_gpt_entry *)baseentry;
584         if (gpp->gpp_parms & G_PART_PARM_TYPE) {
585                 error = gpt_parse_type(gpp->gpp_type, &entry->ent.ent_type);
586                 if (error)
587                         return (error);
588         }
589         if (gpp->gpp_parms & G_PART_PARM_LABEL)
590                 g_gpt_utf8_to_utf16(gpp->gpp_label, entry->ent.ent_name,
591                     sizeof(entry->ent.ent_name));
592         return (0);
593 }
594
595 static int
596 g_part_gpt_resize(struct g_part_table *basetable,
597     struct g_part_entry *baseentry, struct g_part_parms *gpp)
598 {
599         struct g_part_gpt_entry *entry;
600         entry = (struct g_part_gpt_entry *)baseentry;
601
602         baseentry->gpe_end = baseentry->gpe_start + gpp->gpp_size - 1;
603         entry->ent.ent_lba_end = baseentry->gpe_end;
604
605         return (0);
606 }
607
608 static const char *
609 g_part_gpt_name(struct g_part_table *table, struct g_part_entry *baseentry,
610     char *buf, size_t bufsz)
611 {
612         struct g_part_gpt_entry *entry;
613         char c;
614
615         entry = (struct g_part_gpt_entry *)baseentry;
616         c = (EQUUID(&entry->ent.ent_type, &gpt_uuid_freebsd)) ? 's' : 'p';
617         snprintf(buf, bufsz, "%c%d", c, baseentry->gpe_index);
618         return (buf);
619 }
620
621 static int
622 g_part_gpt_probe(struct g_part_table *table, struct g_consumer *cp)
623 {
624         struct g_provider *pp;
625         char *buf;
626         int error, res;
627
628         /* We don't nest, which means that our depth should be 0. */
629         if (table->gpt_depth != 0)
630                 return (ENXIO);
631
632         pp = cp->provider;
633
634         /*
635          * Sanity-check the provider. Since the first sector on the provider
636          * must be a PMBR and a PMBR is 512 bytes large, the sector size
637          * must be at least 512 bytes.  Also, since the theoretical minimum
638          * number of sectors needed by GPT is 6, any medium that has less
639          * than 6 sectors is never going to be able to hold a GPT. The
640          * number 6 comes from:
641          *      1 sector for the PMBR
642          *      2 sectors for the GPT headers (each 1 sector)
643          *      2 sectors for the GPT tables (each 1 sector)
644          *      1 sector for an actual partition
645          * It's better to catch this pathological case early than behaving
646          * pathologically later on...
647          */
648         if (pp->sectorsize < MBRSIZE || pp->mediasize < 6 * pp->sectorsize)
649                 return (ENOSPC);
650
651         /* Check that there's a MBR. */
652         buf = g_read_data(cp, 0L, pp->sectorsize, &error);
653         if (buf == NULL)
654                 return (error);
655         res = le16dec(buf + DOSMAGICOFFSET);
656         g_free(buf);
657         if (res != DOSMAGIC) 
658                 return (ENXIO);
659
660         /* Check that there's a primary header. */
661         buf = g_read_data(cp, pp->sectorsize, pp->sectorsize, &error);
662         if (buf == NULL)
663                 return (error);
664         res = memcmp(buf, GPT_HDR_SIG, 8);
665         g_free(buf);
666         if (res == 0)
667                 return (G_PART_PROBE_PRI_HIGH);
668
669         /* No primary? Check that there's a secondary. */
670         buf = g_read_data(cp, pp->mediasize - pp->sectorsize, pp->sectorsize,
671             &error);
672         if (buf == NULL)
673                 return (error);
674         res = memcmp(buf, GPT_HDR_SIG, 8); 
675         g_free(buf);
676         return ((res == 0) ? G_PART_PROBE_PRI_HIGH : ENXIO);
677 }
678
679 static int
680 g_part_gpt_read(struct g_part_table *basetable, struct g_consumer *cp)
681 {
682         struct gpt_hdr *prihdr, *sechdr;
683         struct gpt_ent *tbl, *pritbl, *sectbl;
684         struct g_provider *pp;
685         struct g_part_gpt_table *table;
686         struct g_part_gpt_entry *entry;
687         u_char *buf;
688         uint64_t last;
689         int error, index;
690
691         table = (struct g_part_gpt_table *)basetable;
692         pp = cp->provider;
693         last = (pp->mediasize / pp->sectorsize) - 1;
694
695         /* Read the PMBR */
696         buf = g_read_data(cp, 0, pp->sectorsize, &error);
697         if (buf == NULL)
698                 return (error);
699         bcopy(buf, table->mbr, MBRSIZE);
700         g_free(buf);
701
702         /* Read the primary header and table. */
703         prihdr = gpt_read_hdr(table, cp, GPT_ELT_PRIHDR);
704         if (table->state[GPT_ELT_PRIHDR] == GPT_STATE_OK) {
705                 pritbl = gpt_read_tbl(table, cp, GPT_ELT_PRITBL, prihdr);
706         } else {
707                 table->state[GPT_ELT_PRITBL] = GPT_STATE_MISSING;
708                 pritbl = NULL;
709         }
710
711         /* Read the secondary header and table. */
712         sechdr = gpt_read_hdr(table, cp, GPT_ELT_SECHDR);
713         if (table->state[GPT_ELT_SECHDR] == GPT_STATE_OK) {
714                 sectbl = gpt_read_tbl(table, cp, GPT_ELT_SECTBL, sechdr);
715         } else {
716                 table->state[GPT_ELT_SECTBL] = GPT_STATE_MISSING;
717                 sectbl = NULL;
718         }
719
720         /* Fail if we haven't got any good tables at all. */
721         if (table->state[GPT_ELT_PRITBL] != GPT_STATE_OK &&
722             table->state[GPT_ELT_SECTBL] != GPT_STATE_OK) {
723                 printf("GEOM: %s: corrupt or invalid GPT detected.\n",
724                     pp->name);
725                 printf("GEOM: %s: GPT rejected -- may not be recoverable.\n",
726                     pp->name);
727                 return (EINVAL);
728         }
729
730         /*
731          * If both headers are good but they disagree with each other,
732          * then invalidate one. We prefer to keep the primary header,
733          * unless the primary table is corrupt.
734          */
735         if (table->state[GPT_ELT_PRIHDR] == GPT_STATE_OK &&
736             table->state[GPT_ELT_SECHDR] == GPT_STATE_OK &&
737             !gpt_matched_hdrs(prihdr, sechdr)) {
738                 if (table->state[GPT_ELT_PRITBL] == GPT_STATE_OK) {
739                         table->state[GPT_ELT_SECHDR] = GPT_STATE_INVALID;
740                         table->state[GPT_ELT_SECTBL] = GPT_STATE_MISSING;
741                         g_free(sechdr);
742                         sechdr = NULL;
743                 } else {
744                         table->state[GPT_ELT_PRIHDR] = GPT_STATE_INVALID;
745                         table->state[GPT_ELT_PRITBL] = GPT_STATE_MISSING;
746                         g_free(prihdr);
747                         prihdr = NULL;
748                 }
749         }
750
751         if (table->state[GPT_ELT_PRITBL] != GPT_STATE_OK) {
752                 printf("GEOM: %s: the primary GPT table is corrupt or "
753                     "invalid.\n", pp->name);
754                 printf("GEOM: %s: using the secondary instead -- recovery "
755                     "strongly advised.\n", pp->name);
756                 table->hdr = sechdr;
757                 basetable->gpt_corrupt = 1;
758                 if (prihdr != NULL)
759                         g_free(prihdr);
760                 tbl = sectbl;
761                 if (pritbl != NULL)
762                         g_free(pritbl);
763         } else {
764                 if (table->state[GPT_ELT_SECTBL] != GPT_STATE_OK) {
765                         printf("GEOM: %s: the secondary GPT table is corrupt "
766                             "or invalid.\n", pp->name);
767                         printf("GEOM: %s: using the primary only -- recovery "
768                             "suggested.\n", pp->name);
769                         basetable->gpt_corrupt = 1;
770                 } else if (table->lba[GPT_ELT_SECHDR] != last) {
771                         printf( "GEOM: %s: the secondary GPT header is not in "
772                             "the last LBA.\n", pp->name);
773                         basetable->gpt_corrupt = 1;
774                 }
775                 table->hdr = prihdr;
776                 if (sechdr != NULL)
777                         g_free(sechdr);
778                 tbl = pritbl;
779                 if (sectbl != NULL)
780                         g_free(sectbl);
781         }
782
783         basetable->gpt_first = table->hdr->hdr_lba_start;
784         basetable->gpt_last = table->hdr->hdr_lba_end;
785         basetable->gpt_entries = table->hdr->hdr_entries;
786
787         for (index = basetable->gpt_entries - 1; index >= 0; index--) {
788                 if (EQUUID(&tbl[index].ent_type, &gpt_uuid_unused))
789                         continue;
790                 entry = (struct g_part_gpt_entry *)g_part_new_entry(
791                     basetable, index + 1, tbl[index].ent_lba_start,
792                     tbl[index].ent_lba_end);
793                 entry->ent = tbl[index];
794         }
795
796         g_free(tbl);
797         return (0);
798 }
799
800 static int
801 g_part_gpt_recover(struct g_part_table *basetable)
802 {
803         struct g_part_gpt_table *table;
804         struct g_provider *pp;
805         uint64_t last;
806         size_t tblsz;
807
808         table = (struct g_part_gpt_table *)basetable;
809         pp = LIST_FIRST(&basetable->gpt_gp->consumer)->provider;
810         last = pp->mediasize / pp->sectorsize - 1;
811         tblsz = (table->hdr->hdr_entries * table->hdr->hdr_entsz +
812             pp->sectorsize - 1) / pp->sectorsize;
813
814         table->lba[GPT_ELT_PRIHDR] = 1;
815         table->lba[GPT_ELT_PRITBL] = 2;
816         table->lba[GPT_ELT_SECHDR] = last;
817         table->lba[GPT_ELT_SECTBL] = last - tblsz;
818         table->state[GPT_ELT_PRIHDR] = GPT_STATE_OK;
819         table->state[GPT_ELT_PRITBL] = GPT_STATE_OK;
820         table->state[GPT_ELT_SECHDR] = GPT_STATE_OK;
821         table->state[GPT_ELT_SECTBL] = GPT_STATE_OK;
822         table->hdr->hdr_lba_start = 2 + tblsz;
823         table->hdr->hdr_lba_end = last - tblsz - 1;
824
825         basetable->gpt_first = table->hdr->hdr_lba_start;
826         basetable->gpt_last = table->hdr->hdr_lba_end;
827         basetable->gpt_corrupt = 0;
828
829         return (0);
830 }
831
832 static int
833 g_part_gpt_setunset(struct g_part_table *table, struct g_part_entry *baseentry,
834     const char *attrib, unsigned int set)
835 {
836         struct g_part_entry *iter;
837         struct g_part_gpt_entry *entry;
838         int changed, bootme, bootonce, bootfailed;
839
840         bootme = bootonce = bootfailed = 0;
841         if (strcasecmp(attrib, "bootme") == 0) {
842                 bootme = 1;
843         } else if (strcasecmp(attrib, "bootonce") == 0) {
844                 /* BOOTME is set automatically with BOOTONCE, but not unset. */
845                 bootonce = 1;
846                 if (set)
847                         bootme = 1;
848         } else if (strcasecmp(attrib, "bootfailed") == 0) {
849                 /*
850                  * It should only be possible to unset BOOTFAILED, but it might
851                  * be useful for test purposes to also be able to set it.
852                  */
853                 bootfailed = 1;
854         }
855         if (!bootme && !bootonce && !bootfailed)
856                 return (EINVAL);
857
858         LIST_FOREACH(iter, &table->gpt_entry, gpe_entry) {
859                 if (iter->gpe_deleted)
860                         continue;
861                 if (iter != baseentry)
862                         continue;
863                 changed = 0;
864                 entry = (struct g_part_gpt_entry *)iter;
865                 if (set) {
866                         if (bootme &&
867                             !(entry->ent.ent_attr & GPT_ENT_ATTR_BOOTME)) {
868                                 entry->ent.ent_attr |= GPT_ENT_ATTR_BOOTME;
869                                 changed = 1;
870                         }
871                         if (bootonce &&
872                             !(entry->ent.ent_attr & GPT_ENT_ATTR_BOOTONCE)) {
873                                 entry->ent.ent_attr |= GPT_ENT_ATTR_BOOTONCE;
874                                 changed = 1;
875                         }
876                         if (bootfailed &&
877                             !(entry->ent.ent_attr & GPT_ENT_ATTR_BOOTFAILED)) {
878                                 entry->ent.ent_attr |= GPT_ENT_ATTR_BOOTFAILED;
879                                 changed = 1;
880                         }
881                 } else {
882                         if (bootme &&
883                             (entry->ent.ent_attr & GPT_ENT_ATTR_BOOTME)) {
884                                 entry->ent.ent_attr &= ~GPT_ENT_ATTR_BOOTME;
885                                 changed = 1;
886                         }
887                         if (bootonce &&
888                             (entry->ent.ent_attr & GPT_ENT_ATTR_BOOTONCE)) {
889                                 entry->ent.ent_attr &= ~GPT_ENT_ATTR_BOOTONCE;
890                                 changed = 1;
891                         }
892                         if (bootfailed &&
893                             (entry->ent.ent_attr & GPT_ENT_ATTR_BOOTFAILED)) {
894                                 entry->ent.ent_attr &= ~GPT_ENT_ATTR_BOOTFAILED;
895                                 changed = 1;
896                         }
897                 }
898                 if (changed && !iter->gpe_created)
899                         iter->gpe_modified = 1;
900         }
901         return (0);
902 }
903
904 static const char *
905 g_part_gpt_type(struct g_part_table *basetable, struct g_part_entry *baseentry, 
906     char *buf, size_t bufsz)
907 {
908         struct g_part_gpt_entry *entry;
909         struct uuid *type;
910         struct g_part_uuid_alias *uap;
911  
912         entry = (struct g_part_gpt_entry *)baseentry;
913         type = &entry->ent.ent_type;
914         for (uap = &gpt_uuid_alias_match[0]; uap->uuid; uap++)
915                 if (EQUUID(type, uap->uuid))
916                         return (g_part_alias_name(uap->alias));
917         buf[0] = '!';
918         snprintf_uuid(buf + 1, bufsz - 1, type);
919
920         return (buf);
921 }
922
923 static int
924 g_part_gpt_write(struct g_part_table *basetable, struct g_consumer *cp)
925 {
926         unsigned char *buf, *bp;
927         struct g_provider *pp;
928         struct g_part_entry *baseentry;
929         struct g_part_gpt_entry *entry;
930         struct g_part_gpt_table *table;
931         size_t tblsz;
932         uint32_t crc;
933         int error, index;
934
935         pp = cp->provider;
936         table = (struct g_part_gpt_table *)basetable;
937         tblsz = (table->hdr->hdr_entries * table->hdr->hdr_entsz +
938             pp->sectorsize - 1) / pp->sectorsize;
939
940         /* Write the PMBR */
941         buf = g_malloc(pp->sectorsize, M_WAITOK | M_ZERO);
942         bcopy(table->mbr, buf, MBRSIZE);
943         error = g_write_data(cp, 0, buf, pp->sectorsize);
944         g_free(buf);
945         if (error)
946                 return (error);
947
948         /* Allocate space for the header and entries. */
949         buf = g_malloc((tblsz + 1) * pp->sectorsize, M_WAITOK | M_ZERO);
950
951         memcpy(buf, table->hdr->hdr_sig, sizeof(table->hdr->hdr_sig));
952         le32enc(buf + 8, table->hdr->hdr_revision);
953         le32enc(buf + 12, table->hdr->hdr_size);
954         le64enc(buf + 40, table->hdr->hdr_lba_start);
955         le64enc(buf + 48, table->hdr->hdr_lba_end);
956         le_uuid_enc(buf + 56, &table->hdr->hdr_uuid);
957         le32enc(buf + 80, table->hdr->hdr_entries);
958         le32enc(buf + 84, table->hdr->hdr_entsz);
959
960         LIST_FOREACH(baseentry, &basetable->gpt_entry, gpe_entry) {
961                 if (baseentry->gpe_deleted)
962                         continue;
963                 entry = (struct g_part_gpt_entry *)baseentry;
964                 index = baseentry->gpe_index - 1;
965                 bp = buf + pp->sectorsize + table->hdr->hdr_entsz * index;
966                 le_uuid_enc(bp, &entry->ent.ent_type);
967                 le_uuid_enc(bp + 16, &entry->ent.ent_uuid);
968                 le64enc(bp + 32, entry->ent.ent_lba_start);
969                 le64enc(bp + 40, entry->ent.ent_lba_end);
970                 le64enc(bp + 48, entry->ent.ent_attr);
971                 memcpy(bp + 56, entry->ent.ent_name,
972                     sizeof(entry->ent.ent_name));
973         }
974
975         crc = crc32(buf + pp->sectorsize,
976             table->hdr->hdr_entries * table->hdr->hdr_entsz);
977         le32enc(buf + 88, crc);
978
979         /* Write primary meta-data. */
980         le32enc(buf + 16, 0);   /* hdr_crc_self. */
981         le64enc(buf + 24, table->lba[GPT_ELT_PRIHDR]);  /* hdr_lba_self. */
982         le64enc(buf + 32, table->lba[GPT_ELT_SECHDR]);  /* hdr_lba_alt. */
983         le64enc(buf + 72, table->lba[GPT_ELT_PRITBL]);  /* hdr_lba_table. */
984         crc = crc32(buf, table->hdr->hdr_size);
985         le32enc(buf + 16, crc);
986
987         error = g_write_data(cp, table->lba[GPT_ELT_PRITBL] * pp->sectorsize,
988             buf + pp->sectorsize, tblsz * pp->sectorsize);
989         if (error)
990                 goto out;
991         error = g_write_data(cp, table->lba[GPT_ELT_PRIHDR] * pp->sectorsize,
992             buf, pp->sectorsize);
993         if (error)
994                 goto out;
995
996         /* Write secondary meta-data. */
997         le32enc(buf + 16, 0);   /* hdr_crc_self. */
998         le64enc(buf + 24, table->lba[GPT_ELT_SECHDR]);  /* hdr_lba_self. */
999         le64enc(buf + 32, table->lba[GPT_ELT_PRIHDR]);  /* hdr_lba_alt. */
1000         le64enc(buf + 72, table->lba[GPT_ELT_SECTBL]);  /* hdr_lba_table. */
1001         crc = crc32(buf, table->hdr->hdr_size);
1002         le32enc(buf + 16, crc);
1003
1004         error = g_write_data(cp, table->lba[GPT_ELT_SECTBL] * pp->sectorsize,
1005             buf + pp->sectorsize, tblsz * pp->sectorsize);
1006         if (error)
1007                 goto out;
1008         error = g_write_data(cp, table->lba[GPT_ELT_SECHDR] * pp->sectorsize,
1009             buf, pp->sectorsize);
1010
1011  out:
1012         g_free(buf);
1013         return (error);
1014 }
1015
1016 static void
1017 g_gpt_printf_utf16(struct sbuf *sb, uint16_t *str, size_t len)
1018 {
1019         u_int bo;
1020         uint32_t ch;
1021         uint16_t c;
1022
1023         bo = LITTLE_ENDIAN;     /* GPT is little-endian */
1024         while (len > 0 && *str != 0) {
1025                 ch = (bo == BIG_ENDIAN) ? be16toh(*str) : le16toh(*str);
1026                 str++, len--;
1027                 if ((ch & 0xf800) == 0xd800) {
1028                         if (len > 0) {
1029                                 c = (bo == BIG_ENDIAN) ? be16toh(*str)
1030                                     : le16toh(*str);
1031                                 str++, len--;
1032                         } else
1033                                 c = 0xfffd;
1034                         if ((ch & 0x400) == 0 && (c & 0xfc00) == 0xdc00) {
1035                                 ch = ((ch & 0x3ff) << 10) + (c & 0x3ff);
1036                                 ch += 0x10000;
1037                         } else
1038                                 ch = 0xfffd;
1039                 } else if (ch == 0xfffe) { /* BOM (U+FEFF) swapped. */
1040                         bo = (bo == BIG_ENDIAN) ? LITTLE_ENDIAN : BIG_ENDIAN;
1041                         continue;
1042                 } else if (ch == 0xfeff) /* BOM (U+FEFF) unswapped. */
1043                         continue;
1044
1045                 /* Write the Unicode character in UTF-8 */
1046                 if (ch < 0x80)
1047                         sbuf_printf(sb, "%c", ch);
1048                 else if (ch < 0x800)
1049                         sbuf_printf(sb, "%c%c", 0xc0 | (ch >> 6),
1050                             0x80 | (ch & 0x3f));
1051                 else if (ch < 0x10000)
1052                         sbuf_printf(sb, "%c%c%c", 0xe0 | (ch >> 12),
1053                             0x80 | ((ch >> 6) & 0x3f), 0x80 | (ch & 0x3f));
1054                 else if (ch < 0x200000)
1055                         sbuf_printf(sb, "%c%c%c%c", 0xf0 | (ch >> 18),
1056                             0x80 | ((ch >> 12) & 0x3f),
1057                             0x80 | ((ch >> 6) & 0x3f), 0x80 | (ch & 0x3f));
1058         }
1059 }
1060
1061 static void
1062 g_gpt_utf8_to_utf16(const uint8_t *s8, uint16_t *s16, size_t s16len)
1063 {
1064         size_t s16idx, s8idx;
1065         uint32_t utfchar;
1066         unsigned int c, utfbytes;
1067
1068         s8idx = s16idx = 0;
1069         utfchar = 0;
1070         utfbytes = 0;
1071         bzero(s16, s16len << 1);
1072         while (s8[s8idx] != 0 && s16idx < s16len) {
1073                 c = s8[s8idx++];
1074                 if ((c & 0xc0) != 0x80) {
1075                         /* Initial characters. */
1076                         if (utfbytes != 0) {
1077                                 /* Incomplete encoding of previous char. */
1078                                 s16[s16idx++] = htole16(0xfffd);
1079                         }
1080                         if ((c & 0xf8) == 0xf0) {
1081                                 utfchar = c & 0x07;
1082                                 utfbytes = 3;
1083                         } else if ((c & 0xf0) == 0xe0) {
1084                                 utfchar = c & 0x0f;
1085                                 utfbytes = 2;
1086                         } else if ((c & 0xe0) == 0xc0) {
1087                                 utfchar = c & 0x1f;
1088                                 utfbytes = 1;
1089                         } else {
1090                                 utfchar = c & 0x7f;
1091                                 utfbytes = 0;
1092                         }
1093                 } else {
1094                         /* Followup characters. */
1095                         if (utfbytes > 0) {
1096                                 utfchar = (utfchar << 6) + (c & 0x3f);
1097                                 utfbytes--;
1098                         } else if (utfbytes == 0)
1099                                 utfbytes = ~0;
1100                 }
1101                 /*
1102                  * Write the complete Unicode character as UTF-16 when we
1103                  * have all the UTF-8 charactars collected.
1104                  */
1105                 if (utfbytes == 0) {
1106                         /*
1107                          * If we need to write 2 UTF-16 characters, but
1108                          * we only have room for 1, then we truncate the
1109                          * string by writing a 0 instead.
1110                          */
1111                         if (utfchar >= 0x10000 && s16idx < s16len - 1) {
1112                                 s16[s16idx++] =
1113                                     htole16(0xd800 | ((utfchar >> 10) - 0x40));
1114                                 s16[s16idx++] =
1115                                     htole16(0xdc00 | (utfchar & 0x3ff));
1116                         } else
1117                                 s16[s16idx++] = (utfchar >= 0x10000) ? 0 :
1118                                     htole16(utfchar);
1119                 }
1120         }
1121         /*
1122          * If our input string was truncated, append an invalid encoding
1123          * character to the output string.
1124          */
1125         if (utfbytes != 0 && s16idx < s16len)
1126                 s16[s16idx++] = htole16(0xfffd);
1127 }