]> CyberLeo.Net >> Repos - FreeBSD/stable/8.git/blob - sys/geom/part/g_part_gpt.c
MFC r217040:
[FreeBSD/stable/8.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                     sizeof(entry->ent.ent_name[0]));
430         return (0);
431 }
432
433 static int
434 g_part_gpt_bootcode(struct g_part_table *basetable, struct g_part_parms *gpp)
435 {
436         struct g_part_gpt_table *table;
437         size_t codesz;
438
439         codesz = DOSPARTOFF;
440         table = (struct g_part_gpt_table *)basetable;
441         bzero(table->mbr, codesz);
442         codesz = MIN(codesz, gpp->gpp_codesize);
443         if (codesz > 0)
444                 bcopy(gpp->gpp_codeptr, table->mbr, codesz);
445
446         /* Mark the PMBR active since some BIOS require it */
447         table->mbr[DOSPARTOFF] = 0x80;          /* status */
448         return (0);
449 }
450
451 static int
452 g_part_gpt_create(struct g_part_table *basetable, struct g_part_parms *gpp)
453 {
454         struct g_provider *pp;
455         struct g_part_gpt_table *table;
456         quad_t last;
457         size_t tblsz;
458
459         /* We don't nest, which means that our depth should be 0. */
460         if (basetable->gpt_depth != 0)
461                 return (ENXIO);
462
463         table = (struct g_part_gpt_table *)basetable;
464         pp = gpp->gpp_provider;
465         tblsz = (basetable->gpt_entries * sizeof(struct gpt_ent) +
466             pp->sectorsize - 1) / pp->sectorsize;
467         if (pp->sectorsize < MBRSIZE ||
468             pp->mediasize < (3 + 2 * tblsz + basetable->gpt_entries) *
469             pp->sectorsize)
470                 return (ENOSPC);
471
472         last = (pp->mediasize / pp->sectorsize) - 1;
473
474         le16enc(table->mbr + DOSMAGICOFFSET, DOSMAGIC);
475         table->mbr[DOSPARTOFF + 1] = 0x01;              /* shd */
476         table->mbr[DOSPARTOFF + 2] = 0x01;              /* ssect */
477         table->mbr[DOSPARTOFF + 3] = 0x00;              /* scyl */
478         table->mbr[DOSPARTOFF + 4] = 0xee;              /* typ */
479         table->mbr[DOSPARTOFF + 5] = 0xff;              /* ehd */
480         table->mbr[DOSPARTOFF + 6] = 0xff;              /* esect */
481         table->mbr[DOSPARTOFF + 7] = 0xff;              /* ecyl */
482         le32enc(table->mbr + DOSPARTOFF + 8, 1);        /* start */
483         le32enc(table->mbr + DOSPARTOFF + 12, MIN(last, 0xffffffffLL));
484
485         table->lba[GPT_ELT_PRIHDR] = 1;
486         table->lba[GPT_ELT_PRITBL] = 2;
487         table->lba[GPT_ELT_SECHDR] = last;
488         table->lba[GPT_ELT_SECTBL] = last - tblsz;
489
490         /* Allocate space for the header */
491         table->hdr = g_malloc(sizeof(struct gpt_hdr), M_WAITOK | M_ZERO);
492
493         bcopy(GPT_HDR_SIG, table->hdr->hdr_sig, sizeof(table->hdr->hdr_sig));
494         table->hdr->hdr_revision = GPT_HDR_REVISION;
495         table->hdr->hdr_size = offsetof(struct gpt_hdr, padding);
496         table->hdr->hdr_lba_start = 2 + tblsz;
497         table->hdr->hdr_lba_end = last - tblsz - 1;
498         kern_uuidgen(&table->hdr->hdr_uuid, 1);
499         table->hdr->hdr_entries = basetable->gpt_entries;
500         table->hdr->hdr_entsz = sizeof(struct gpt_ent);
501
502         basetable->gpt_first = table->hdr->hdr_lba_start;
503         basetable->gpt_last = table->hdr->hdr_lba_end;
504         return (0);
505 }
506
507 static int
508 g_part_gpt_destroy(struct g_part_table *basetable, struct g_part_parms *gpp)
509 {
510         struct g_part_gpt_table *table;
511         struct g_provider *pp;
512
513         table = (struct g_part_gpt_table *)basetable;
514         pp = LIST_FIRST(&basetable->gpt_gp->consumer)->provider;
515         g_free(table->hdr);
516         table->hdr = NULL;
517
518         /*
519          * Wipe the first 2 sectors to clear the partitioning. Wipe the last
520          * sector only if it has valid secondary header.
521          */
522         basetable->gpt_smhead |= 3;
523         if (table->state[GPT_ELT_SECHDR] == GPT_STATE_OK &&
524             table->lba[GPT_ELT_SECHDR] == pp->mediasize / pp->sectorsize - 1)
525                 basetable->gpt_smtail |= 1;
526         return (0);
527 }
528
529 static void
530 g_part_gpt_dumpconf(struct g_part_table *table, struct g_part_entry *baseentry, 
531     struct sbuf *sb, const char *indent)
532 {
533         struct g_part_gpt_entry *entry;
534  
535         entry = (struct g_part_gpt_entry *)baseentry;
536         if (indent == NULL) {
537                 /* conftxt: libdisk compatibility */
538                 sbuf_printf(sb, " xs GPT xt ");
539                 sbuf_printf_uuid(sb, &entry->ent.ent_type);
540         } else if (entry != NULL) {
541                 /* confxml: partition entry information */
542                 sbuf_printf(sb, "%s<label>", indent);
543                 g_gpt_printf_utf16(sb, entry->ent.ent_name,
544                     sizeof(entry->ent.ent_name) >> 1);
545                 sbuf_printf(sb, "</label>\n");
546                 if (entry->ent.ent_attr & GPT_ENT_ATTR_BOOTME)
547                         sbuf_printf(sb, "%s<attrib>bootme</attrib>\n", indent);
548                 if (entry->ent.ent_attr & GPT_ENT_ATTR_BOOTONCE) {
549                         sbuf_printf(sb, "%s<attrib>bootonce</attrib>\n",
550                             indent);
551                 }
552                 if (entry->ent.ent_attr & GPT_ENT_ATTR_BOOTFAILED) {
553                         sbuf_printf(sb, "%s<attrib>bootfailed</attrib>\n",
554                             indent);
555                 }
556                 sbuf_printf(sb, "%s<rawtype>", indent);
557                 sbuf_printf_uuid(sb, &entry->ent.ent_type);
558                 sbuf_printf(sb, "</rawtype>\n");
559                 sbuf_printf(sb, "%s<rawuuid>", indent);
560                 sbuf_printf_uuid(sb, &entry->ent.ent_uuid);
561                 sbuf_printf(sb, "</rawuuid>\n");
562         } else {
563                 /* confxml: scheme information */
564         }
565 }
566
567 static int
568 g_part_gpt_dumpto(struct g_part_table *table, struct g_part_entry *baseentry)  
569 {
570         struct g_part_gpt_entry *entry;
571
572         entry = (struct g_part_gpt_entry *)baseentry;
573         return ((EQUUID(&entry->ent.ent_type, &gpt_uuid_freebsd_swap) ||
574             EQUUID(&entry->ent.ent_type, &gpt_uuid_linux_swap)) ? 1 : 0);
575 }
576
577 static int
578 g_part_gpt_modify(struct g_part_table *basetable,
579     struct g_part_entry *baseentry, struct g_part_parms *gpp)
580 {
581         struct g_part_gpt_entry *entry;
582         int error;
583
584         entry = (struct g_part_gpt_entry *)baseentry;
585         if (gpp->gpp_parms & G_PART_PARM_TYPE) {
586                 error = gpt_parse_type(gpp->gpp_type, &entry->ent.ent_type);
587                 if (error)
588                         return (error);
589         }
590         if (gpp->gpp_parms & G_PART_PARM_LABEL)
591                 g_gpt_utf8_to_utf16(gpp->gpp_label, entry->ent.ent_name,
592                     sizeof(entry->ent.ent_name) /
593                     sizeof(entry->ent.ent_name[0]));
594         return (0);
595 }
596
597 static int
598 g_part_gpt_resize(struct g_part_table *basetable,
599     struct g_part_entry *baseentry, struct g_part_parms *gpp)
600 {
601         struct g_part_gpt_entry *entry;
602         entry = (struct g_part_gpt_entry *)baseentry;
603
604         baseentry->gpe_end = baseentry->gpe_start + gpp->gpp_size - 1;
605         entry->ent.ent_lba_end = baseentry->gpe_end;
606
607         return (0);
608 }
609
610 static const char *
611 g_part_gpt_name(struct g_part_table *table, struct g_part_entry *baseentry,
612     char *buf, size_t bufsz)
613 {
614         struct g_part_gpt_entry *entry;
615         char c;
616
617         entry = (struct g_part_gpt_entry *)baseentry;
618         c = (EQUUID(&entry->ent.ent_type, &gpt_uuid_freebsd)) ? 's' : 'p';
619         snprintf(buf, bufsz, "%c%d", c, baseentry->gpe_index);
620         return (buf);
621 }
622
623 static int
624 g_part_gpt_probe(struct g_part_table *table, struct g_consumer *cp)
625 {
626         struct g_provider *pp;
627         char *buf;
628         int error, res;
629
630         /* We don't nest, which means that our depth should be 0. */
631         if (table->gpt_depth != 0)
632                 return (ENXIO);
633
634         pp = cp->provider;
635
636         /*
637          * Sanity-check the provider. Since the first sector on the provider
638          * must be a PMBR and a PMBR is 512 bytes large, the sector size
639          * must be at least 512 bytes.  Also, since the theoretical minimum
640          * number of sectors needed by GPT is 6, any medium that has less
641          * than 6 sectors is never going to be able to hold a GPT. The
642          * number 6 comes from:
643          *      1 sector for the PMBR
644          *      2 sectors for the GPT headers (each 1 sector)
645          *      2 sectors for the GPT tables (each 1 sector)
646          *      1 sector for an actual partition
647          * It's better to catch this pathological case early than behaving
648          * pathologically later on...
649          */
650         if (pp->sectorsize < MBRSIZE || pp->mediasize < 6 * pp->sectorsize)
651                 return (ENOSPC);
652
653         /* Check that there's a MBR. */
654         buf = g_read_data(cp, 0L, pp->sectorsize, &error);
655         if (buf == NULL)
656                 return (error);
657         res = le16dec(buf + DOSMAGICOFFSET);
658         g_free(buf);
659         if (res != DOSMAGIC) 
660                 return (ENXIO);
661
662         /* Check that there's a primary header. */
663         buf = g_read_data(cp, pp->sectorsize, pp->sectorsize, &error);
664         if (buf == NULL)
665                 return (error);
666         res = memcmp(buf, GPT_HDR_SIG, 8);
667         g_free(buf);
668         if (res == 0)
669                 return (G_PART_PROBE_PRI_HIGH);
670
671         /* No primary? Check that there's a secondary. */
672         buf = g_read_data(cp, pp->mediasize - pp->sectorsize, pp->sectorsize,
673             &error);
674         if (buf == NULL)
675                 return (error);
676         res = memcmp(buf, GPT_HDR_SIG, 8); 
677         g_free(buf);
678         return ((res == 0) ? G_PART_PROBE_PRI_HIGH : ENXIO);
679 }
680
681 static int
682 g_part_gpt_read(struct g_part_table *basetable, struct g_consumer *cp)
683 {
684         struct gpt_hdr *prihdr, *sechdr;
685         struct gpt_ent *tbl, *pritbl, *sectbl;
686         struct g_provider *pp;
687         struct g_part_gpt_table *table;
688         struct g_part_gpt_entry *entry;
689         u_char *buf;
690         uint64_t last;
691         int error, index;
692
693         table = (struct g_part_gpt_table *)basetable;
694         pp = cp->provider;
695         last = (pp->mediasize / pp->sectorsize) - 1;
696
697         /* Read the PMBR */
698         buf = g_read_data(cp, 0, pp->sectorsize, &error);
699         if (buf == NULL)
700                 return (error);
701         bcopy(buf, table->mbr, MBRSIZE);
702         g_free(buf);
703
704         /* Read the primary header and table. */
705         prihdr = gpt_read_hdr(table, cp, GPT_ELT_PRIHDR);
706         if (table->state[GPT_ELT_PRIHDR] == GPT_STATE_OK) {
707                 pritbl = gpt_read_tbl(table, cp, GPT_ELT_PRITBL, prihdr);
708         } else {
709                 table->state[GPT_ELT_PRITBL] = GPT_STATE_MISSING;
710                 pritbl = NULL;
711         }
712
713         /* Read the secondary header and table. */
714         sechdr = gpt_read_hdr(table, cp, GPT_ELT_SECHDR);
715         if (table->state[GPT_ELT_SECHDR] == GPT_STATE_OK) {
716                 sectbl = gpt_read_tbl(table, cp, GPT_ELT_SECTBL, sechdr);
717         } else {
718                 table->state[GPT_ELT_SECTBL] = GPT_STATE_MISSING;
719                 sectbl = NULL;
720         }
721
722         /* Fail if we haven't got any good tables at all. */
723         if (table->state[GPT_ELT_PRITBL] != GPT_STATE_OK &&
724             table->state[GPT_ELT_SECTBL] != GPT_STATE_OK) {
725                 printf("GEOM: %s: corrupt or invalid GPT detected.\n",
726                     pp->name);
727                 printf("GEOM: %s: GPT rejected -- may not be recoverable.\n",
728                     pp->name);
729                 return (EINVAL);
730         }
731
732         /*
733          * If both headers are good but they disagree with each other,
734          * then invalidate one. We prefer to keep the primary header,
735          * unless the primary table is corrupt.
736          */
737         if (table->state[GPT_ELT_PRIHDR] == GPT_STATE_OK &&
738             table->state[GPT_ELT_SECHDR] == GPT_STATE_OK &&
739             !gpt_matched_hdrs(prihdr, sechdr)) {
740                 if (table->state[GPT_ELT_PRITBL] == GPT_STATE_OK) {
741                         table->state[GPT_ELT_SECHDR] = GPT_STATE_INVALID;
742                         table->state[GPT_ELT_SECTBL] = GPT_STATE_MISSING;
743                         g_free(sechdr);
744                         sechdr = NULL;
745                 } else {
746                         table->state[GPT_ELT_PRIHDR] = GPT_STATE_INVALID;
747                         table->state[GPT_ELT_PRITBL] = GPT_STATE_MISSING;
748                         g_free(prihdr);
749                         prihdr = NULL;
750                 }
751         }
752
753         if (table->state[GPT_ELT_PRITBL] != GPT_STATE_OK) {
754                 printf("GEOM: %s: the primary GPT table is corrupt or "
755                     "invalid.\n", pp->name);
756                 printf("GEOM: %s: using the secondary instead -- recovery "
757                     "strongly advised.\n", pp->name);
758                 table->hdr = sechdr;
759                 basetable->gpt_corrupt = 1;
760                 if (prihdr != NULL)
761                         g_free(prihdr);
762                 tbl = sectbl;
763                 if (pritbl != NULL)
764                         g_free(pritbl);
765         } else {
766                 if (table->state[GPT_ELT_SECTBL] != GPT_STATE_OK) {
767                         printf("GEOM: %s: the secondary GPT table is corrupt "
768                             "or invalid.\n", pp->name);
769                         printf("GEOM: %s: using the primary only -- recovery "
770                             "suggested.\n", pp->name);
771                         basetable->gpt_corrupt = 1;
772                 } else if (table->lba[GPT_ELT_SECHDR] != last) {
773                         printf( "GEOM: %s: the secondary GPT header is not in "
774                             "the last LBA.\n", pp->name);
775                         basetable->gpt_corrupt = 1;
776                 }
777                 table->hdr = prihdr;
778                 if (sechdr != NULL)
779                         g_free(sechdr);
780                 tbl = pritbl;
781                 if (sectbl != NULL)
782                         g_free(sectbl);
783         }
784
785         basetable->gpt_first = table->hdr->hdr_lba_start;
786         basetable->gpt_last = table->hdr->hdr_lba_end;
787         basetable->gpt_entries = table->hdr->hdr_entries;
788
789         for (index = basetable->gpt_entries - 1; index >= 0; index--) {
790                 if (EQUUID(&tbl[index].ent_type, &gpt_uuid_unused))
791                         continue;
792                 entry = (struct g_part_gpt_entry *)g_part_new_entry(
793                     basetable, index + 1, tbl[index].ent_lba_start,
794                     tbl[index].ent_lba_end);
795                 entry->ent = tbl[index];
796         }
797
798         g_free(tbl);
799         return (0);
800 }
801
802 static int
803 g_part_gpt_recover(struct g_part_table *basetable)
804 {
805         struct g_part_gpt_table *table;
806         struct g_provider *pp;
807         uint64_t last;
808         size_t tblsz;
809
810         table = (struct g_part_gpt_table *)basetable;
811         pp = LIST_FIRST(&basetable->gpt_gp->consumer)->provider;
812         last = pp->mediasize / pp->sectorsize - 1;
813         tblsz = (table->hdr->hdr_entries * table->hdr->hdr_entsz +
814             pp->sectorsize - 1) / pp->sectorsize;
815
816         table->lba[GPT_ELT_PRIHDR] = 1;
817         table->lba[GPT_ELT_PRITBL] = 2;
818         table->lba[GPT_ELT_SECHDR] = last;
819         table->lba[GPT_ELT_SECTBL] = last - tblsz;
820         table->state[GPT_ELT_PRIHDR] = GPT_STATE_OK;
821         table->state[GPT_ELT_PRITBL] = GPT_STATE_OK;
822         table->state[GPT_ELT_SECHDR] = GPT_STATE_OK;
823         table->state[GPT_ELT_SECTBL] = GPT_STATE_OK;
824         table->hdr->hdr_lba_start = 2 + tblsz;
825         table->hdr->hdr_lba_end = last - tblsz - 1;
826
827         basetable->gpt_first = table->hdr->hdr_lba_start;
828         basetable->gpt_last = table->hdr->hdr_lba_end;
829         basetable->gpt_corrupt = 0;
830
831         return (0);
832 }
833
834 static int
835 g_part_gpt_setunset(struct g_part_table *table, struct g_part_entry *baseentry,
836     const char *attrib, unsigned int set)
837 {
838         struct g_part_entry *iter;
839         struct g_part_gpt_entry *entry;
840         int changed, bootme, bootonce, bootfailed;
841
842         bootme = bootonce = bootfailed = 0;
843         if (strcasecmp(attrib, "bootme") == 0) {
844                 bootme = 1;
845         } else if (strcasecmp(attrib, "bootonce") == 0) {
846                 /* BOOTME is set automatically with BOOTONCE, but not unset. */
847                 bootonce = 1;
848                 if (set)
849                         bootme = 1;
850         } else if (strcasecmp(attrib, "bootfailed") == 0) {
851                 /*
852                  * It should only be possible to unset BOOTFAILED, but it might
853                  * be useful for test purposes to also be able to set it.
854                  */
855                 bootfailed = 1;
856         }
857         if (!bootme && !bootonce && !bootfailed)
858                 return (EINVAL);
859
860         LIST_FOREACH(iter, &table->gpt_entry, gpe_entry) {
861                 if (iter->gpe_deleted)
862                         continue;
863                 if (iter != baseentry)
864                         continue;
865                 changed = 0;
866                 entry = (struct g_part_gpt_entry *)iter;
867                 if (set) {
868                         if (bootme &&
869                             !(entry->ent.ent_attr & GPT_ENT_ATTR_BOOTME)) {
870                                 entry->ent.ent_attr |= GPT_ENT_ATTR_BOOTME;
871                                 changed = 1;
872                         }
873                         if (bootonce &&
874                             !(entry->ent.ent_attr & GPT_ENT_ATTR_BOOTONCE)) {
875                                 entry->ent.ent_attr |= GPT_ENT_ATTR_BOOTONCE;
876                                 changed = 1;
877                         }
878                         if (bootfailed &&
879                             !(entry->ent.ent_attr & GPT_ENT_ATTR_BOOTFAILED)) {
880                                 entry->ent.ent_attr |= GPT_ENT_ATTR_BOOTFAILED;
881                                 changed = 1;
882                         }
883                 } else {
884                         if (bootme &&
885                             (entry->ent.ent_attr & GPT_ENT_ATTR_BOOTME)) {
886                                 entry->ent.ent_attr &= ~GPT_ENT_ATTR_BOOTME;
887                                 changed = 1;
888                         }
889                         if (bootonce &&
890                             (entry->ent.ent_attr & GPT_ENT_ATTR_BOOTONCE)) {
891                                 entry->ent.ent_attr &= ~GPT_ENT_ATTR_BOOTONCE;
892                                 changed = 1;
893                         }
894                         if (bootfailed &&
895                             (entry->ent.ent_attr & GPT_ENT_ATTR_BOOTFAILED)) {
896                                 entry->ent.ent_attr &= ~GPT_ENT_ATTR_BOOTFAILED;
897                                 changed = 1;
898                         }
899                 }
900                 if (changed && !iter->gpe_created)
901                         iter->gpe_modified = 1;
902         }
903         return (0);
904 }
905
906 static const char *
907 g_part_gpt_type(struct g_part_table *basetable, struct g_part_entry *baseentry, 
908     char *buf, size_t bufsz)
909 {
910         struct g_part_gpt_entry *entry;
911         struct uuid *type;
912         struct g_part_uuid_alias *uap;
913  
914         entry = (struct g_part_gpt_entry *)baseentry;
915         type = &entry->ent.ent_type;
916         for (uap = &gpt_uuid_alias_match[0]; uap->uuid; uap++)
917                 if (EQUUID(type, uap->uuid))
918                         return (g_part_alias_name(uap->alias));
919         buf[0] = '!';
920         snprintf_uuid(buf + 1, bufsz - 1, type);
921
922         return (buf);
923 }
924
925 static int
926 g_part_gpt_write(struct g_part_table *basetable, struct g_consumer *cp)
927 {
928         unsigned char *buf, *bp;
929         struct g_provider *pp;
930         struct g_part_entry *baseentry;
931         struct g_part_gpt_entry *entry;
932         struct g_part_gpt_table *table;
933         size_t tblsz;
934         uint32_t crc;
935         int error, index;
936
937         pp = cp->provider;
938         table = (struct g_part_gpt_table *)basetable;
939         tblsz = (table->hdr->hdr_entries * table->hdr->hdr_entsz +
940             pp->sectorsize - 1) / pp->sectorsize;
941
942         /* Write the PMBR */
943         buf = g_malloc(pp->sectorsize, M_WAITOK | M_ZERO);
944         bcopy(table->mbr, buf, MBRSIZE);
945         error = g_write_data(cp, 0, buf, pp->sectorsize);
946         g_free(buf);
947         if (error)
948                 return (error);
949
950         /* Allocate space for the header and entries. */
951         buf = g_malloc((tblsz + 1) * pp->sectorsize, M_WAITOK | M_ZERO);
952
953         memcpy(buf, table->hdr->hdr_sig, sizeof(table->hdr->hdr_sig));
954         le32enc(buf + 8, table->hdr->hdr_revision);
955         le32enc(buf + 12, table->hdr->hdr_size);
956         le64enc(buf + 40, table->hdr->hdr_lba_start);
957         le64enc(buf + 48, table->hdr->hdr_lba_end);
958         le_uuid_enc(buf + 56, &table->hdr->hdr_uuid);
959         le32enc(buf + 80, table->hdr->hdr_entries);
960         le32enc(buf + 84, table->hdr->hdr_entsz);
961
962         LIST_FOREACH(baseentry, &basetable->gpt_entry, gpe_entry) {
963                 if (baseentry->gpe_deleted)
964                         continue;
965                 entry = (struct g_part_gpt_entry *)baseentry;
966                 index = baseentry->gpe_index - 1;
967                 bp = buf + pp->sectorsize + table->hdr->hdr_entsz * index;
968                 le_uuid_enc(bp, &entry->ent.ent_type);
969                 le_uuid_enc(bp + 16, &entry->ent.ent_uuid);
970                 le64enc(bp + 32, entry->ent.ent_lba_start);
971                 le64enc(bp + 40, entry->ent.ent_lba_end);
972                 le64enc(bp + 48, entry->ent.ent_attr);
973                 memcpy(bp + 56, entry->ent.ent_name,
974                     sizeof(entry->ent.ent_name));
975         }
976
977         crc = crc32(buf + pp->sectorsize,
978             table->hdr->hdr_entries * table->hdr->hdr_entsz);
979         le32enc(buf + 88, crc);
980
981         /* Write primary meta-data. */
982         le32enc(buf + 16, 0);   /* hdr_crc_self. */
983         le64enc(buf + 24, table->lba[GPT_ELT_PRIHDR]);  /* hdr_lba_self. */
984         le64enc(buf + 32, table->lba[GPT_ELT_SECHDR]);  /* hdr_lba_alt. */
985         le64enc(buf + 72, table->lba[GPT_ELT_PRITBL]);  /* hdr_lba_table. */
986         crc = crc32(buf, table->hdr->hdr_size);
987         le32enc(buf + 16, crc);
988
989         error = g_write_data(cp, table->lba[GPT_ELT_PRITBL] * pp->sectorsize,
990             buf + pp->sectorsize, tblsz * pp->sectorsize);
991         if (error)
992                 goto out;
993         error = g_write_data(cp, table->lba[GPT_ELT_PRIHDR] * pp->sectorsize,
994             buf, pp->sectorsize);
995         if (error)
996                 goto out;
997
998         /* Write secondary meta-data. */
999         le32enc(buf + 16, 0);   /* hdr_crc_self. */
1000         le64enc(buf + 24, table->lba[GPT_ELT_SECHDR]);  /* hdr_lba_self. */
1001         le64enc(buf + 32, table->lba[GPT_ELT_PRIHDR]);  /* hdr_lba_alt. */
1002         le64enc(buf + 72, table->lba[GPT_ELT_SECTBL]);  /* hdr_lba_table. */
1003         crc = crc32(buf, table->hdr->hdr_size);
1004         le32enc(buf + 16, crc);
1005
1006         error = g_write_data(cp, table->lba[GPT_ELT_SECTBL] * pp->sectorsize,
1007             buf + pp->sectorsize, tblsz * pp->sectorsize);
1008         if (error)
1009                 goto out;
1010         error = g_write_data(cp, table->lba[GPT_ELT_SECHDR] * pp->sectorsize,
1011             buf, pp->sectorsize);
1012
1013  out:
1014         g_free(buf);
1015         return (error);
1016 }
1017
1018 static void
1019 g_gpt_printf_utf16(struct sbuf *sb, uint16_t *str, size_t len)
1020 {
1021         u_int bo;
1022         uint32_t ch;
1023         uint16_t c;
1024
1025         bo = LITTLE_ENDIAN;     /* GPT is little-endian */
1026         while (len > 0 && *str != 0) {
1027                 ch = (bo == BIG_ENDIAN) ? be16toh(*str) : le16toh(*str);
1028                 str++, len--;
1029                 if ((ch & 0xf800) == 0xd800) {
1030                         if (len > 0) {
1031                                 c = (bo == BIG_ENDIAN) ? be16toh(*str)
1032                                     : le16toh(*str);
1033                                 str++, len--;
1034                         } else
1035                                 c = 0xfffd;
1036                         if ((ch & 0x400) == 0 && (c & 0xfc00) == 0xdc00) {
1037                                 ch = ((ch & 0x3ff) << 10) + (c & 0x3ff);
1038                                 ch += 0x10000;
1039                         } else
1040                                 ch = 0xfffd;
1041                 } else if (ch == 0xfffe) { /* BOM (U+FEFF) swapped. */
1042                         bo = (bo == BIG_ENDIAN) ? LITTLE_ENDIAN : BIG_ENDIAN;
1043                         continue;
1044                 } else if (ch == 0xfeff) /* BOM (U+FEFF) unswapped. */
1045                         continue;
1046
1047                 /* Write the Unicode character in UTF-8 */
1048                 if (ch < 0x80)
1049                         sbuf_printf(sb, "%c", ch);
1050                 else if (ch < 0x800)
1051                         sbuf_printf(sb, "%c%c", 0xc0 | (ch >> 6),
1052                             0x80 | (ch & 0x3f));
1053                 else if (ch < 0x10000)
1054                         sbuf_printf(sb, "%c%c%c", 0xe0 | (ch >> 12),
1055                             0x80 | ((ch >> 6) & 0x3f), 0x80 | (ch & 0x3f));
1056                 else if (ch < 0x200000)
1057                         sbuf_printf(sb, "%c%c%c%c", 0xf0 | (ch >> 18),
1058                             0x80 | ((ch >> 12) & 0x3f),
1059                             0x80 | ((ch >> 6) & 0x3f), 0x80 | (ch & 0x3f));
1060         }
1061 }
1062
1063 static void
1064 g_gpt_utf8_to_utf16(const uint8_t *s8, uint16_t *s16, size_t s16len)
1065 {
1066         size_t s16idx, s8idx;
1067         uint32_t utfchar;
1068         unsigned int c, utfbytes;
1069
1070         s8idx = s16idx = 0;
1071         utfchar = 0;
1072         utfbytes = 0;
1073         bzero(s16, s16len << 1);
1074         while (s8[s8idx] != 0 && s16idx < s16len) {
1075                 c = s8[s8idx++];
1076                 if ((c & 0xc0) != 0x80) {
1077                         /* Initial characters. */
1078                         if (utfbytes != 0) {
1079                                 /* Incomplete encoding of previous char. */
1080                                 s16[s16idx++] = htole16(0xfffd);
1081                         }
1082                         if ((c & 0xf8) == 0xf0) {
1083                                 utfchar = c & 0x07;
1084                                 utfbytes = 3;
1085                         } else if ((c & 0xf0) == 0xe0) {
1086                                 utfchar = c & 0x0f;
1087                                 utfbytes = 2;
1088                         } else if ((c & 0xe0) == 0xc0) {
1089                                 utfchar = c & 0x1f;
1090                                 utfbytes = 1;
1091                         } else {
1092                                 utfchar = c & 0x7f;
1093                                 utfbytes = 0;
1094                         }
1095                 } else {
1096                         /* Followup characters. */
1097                         if (utfbytes > 0) {
1098                                 utfchar = (utfchar << 6) + (c & 0x3f);
1099                                 utfbytes--;
1100                         } else if (utfbytes == 0)
1101                                 utfbytes = ~0;
1102                 }
1103                 /*
1104                  * Write the complete Unicode character as UTF-16 when we
1105                  * have all the UTF-8 charactars collected.
1106                  */
1107                 if (utfbytes == 0) {
1108                         /*
1109                          * If we need to write 2 UTF-16 characters, but
1110                          * we only have room for 1, then we truncate the
1111                          * string by writing a 0 instead.
1112                          */
1113                         if (utfchar >= 0x10000 && s16idx < s16len - 1) {
1114                                 s16[s16idx++] =
1115                                     htole16(0xd800 | ((utfchar >> 10) - 0x40));
1116                                 s16[s16idx++] =
1117                                     htole16(0xdc00 | (utfchar & 0x3ff));
1118                         } else
1119                                 s16[s16idx++] = (utfchar >= 0x10000) ? 0 :
1120                                     htole16(utfchar);
1121                 }
1122         }
1123         /*
1124          * If our input string was truncated, append an invalid encoding
1125          * character to the output string.
1126          */
1127         if (utfbytes != 0 && s16idx < s16len)
1128                 s16[s16idx++] = htole16(0xfffd);
1129 }