]> CyberLeo.Net >> Repos - FreeBSD/releng/7.2.git/blob - sys/geom/part/g_part_gpt.c
Create releng/7.2 from stable/7 in preparation for 7.2-RELEASE.
[FreeBSD/releng/7.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 const char *g_part_gpt_type(struct g_part_table *, struct g_part_entry *,
104     char *, size_t);
105 static int g_part_gpt_write(struct g_part_table *, struct g_consumer *);
106
107 static kobj_method_t g_part_gpt_methods[] = {
108         KOBJMETHOD(g_part_add,          g_part_gpt_add),
109         KOBJMETHOD(g_part_bootcode,     g_part_gpt_bootcode),
110         KOBJMETHOD(g_part_create,       g_part_gpt_create),
111         KOBJMETHOD(g_part_destroy,      g_part_gpt_destroy),
112         KOBJMETHOD(g_part_dumpconf,     g_part_gpt_dumpconf),
113         KOBJMETHOD(g_part_dumpto,       g_part_gpt_dumpto),
114         KOBJMETHOD(g_part_modify,       g_part_gpt_modify),
115         KOBJMETHOD(g_part_name,         g_part_gpt_name),
116         KOBJMETHOD(g_part_probe,        g_part_gpt_probe),
117         KOBJMETHOD(g_part_read,         g_part_gpt_read),
118         KOBJMETHOD(g_part_type,         g_part_gpt_type),
119         KOBJMETHOD(g_part_write,        g_part_gpt_write),
120         { 0, 0 }
121 };
122
123 static struct g_part_scheme g_part_gpt_scheme = {
124         "GPT",
125         g_part_gpt_methods,
126         sizeof(struct g_part_gpt_table),
127         .gps_entrysz = sizeof(struct g_part_gpt_entry),
128         .gps_minent = 128,
129         .gps_maxent = INT_MAX,
130         .gps_bootcodesz = MBRSIZE,
131 };
132 G_PART_SCHEME_DECLARE(g_part_gpt);
133
134 static struct uuid gpt_uuid_efi = GPT_ENT_TYPE_EFI;
135 static struct uuid gpt_uuid_freebsd = GPT_ENT_TYPE_FREEBSD;
136 static struct uuid gpt_uuid_freebsd_boot = GPT_ENT_TYPE_FREEBSD_BOOT;
137 static struct uuid gpt_uuid_freebsd_swap = GPT_ENT_TYPE_FREEBSD_SWAP;
138 static struct uuid gpt_uuid_freebsd_ufs = GPT_ENT_TYPE_FREEBSD_UFS;
139 static struct uuid gpt_uuid_freebsd_vinum = GPT_ENT_TYPE_FREEBSD_VINUM;
140 static struct uuid gpt_uuid_freebsd_zfs = GPT_ENT_TYPE_FREEBSD_ZFS;
141 static struct uuid gpt_uuid_linux_swap = GPT_ENT_TYPE_LINUX_SWAP;
142 static struct uuid gpt_uuid_mbr = GPT_ENT_TYPE_MBR;
143 static struct uuid gpt_uuid_unused = GPT_ENT_TYPE_UNUSED;
144
145 static void
146 gpt_read_hdr(struct g_part_gpt_table *table, struct g_consumer *cp,
147     enum gpt_elt elt, struct gpt_hdr *hdr)
148 {
149         struct uuid uuid;
150         struct g_provider *pp;
151         char *buf;
152         quad_t lba, last;
153         int error;
154         uint32_t crc, sz;
155
156         pp = cp->provider;
157         last = (pp->mediasize / pp->sectorsize) - 1;
158         table->lba[elt] = (elt == GPT_ELT_PRIHDR) ? 1 : last;
159         table->state[elt] = GPT_STATE_MISSING;
160         buf = g_read_data(cp, table->lba[elt] * pp->sectorsize, pp->sectorsize,
161             &error);
162         if (buf == NULL)
163                 return;
164         bcopy(buf, hdr, sizeof(*hdr));
165         if (memcmp(hdr->hdr_sig, GPT_HDR_SIG, sizeof(hdr->hdr_sig)) != 0)
166                 return;
167
168         table->state[elt] = GPT_STATE_CORRUPT;
169         sz = le32toh(hdr->hdr_size);
170         if (sz < 92 || sz > pp->sectorsize)
171                 return;
172         crc = le32toh(hdr->hdr_crc_self);
173         hdr->hdr_crc_self = 0;
174         if (crc32(hdr, sz) != crc)
175                 return;
176         hdr->hdr_size = sz;
177         hdr->hdr_crc_self = crc;
178
179         table->state[elt] = GPT_STATE_INVALID;
180         hdr->hdr_revision = le32toh(hdr->hdr_revision);
181         if (hdr->hdr_revision < 0x00010000)
182                 return;
183         hdr->hdr_lba_self = le64toh(hdr->hdr_lba_self);
184         if (hdr->hdr_lba_self != table->lba[elt])
185                 return;
186         hdr->hdr_lba_alt = le64toh(hdr->hdr_lba_alt);
187
188         /* Check the managed area. */
189         hdr->hdr_lba_start = le64toh(hdr->hdr_lba_start);
190         if (hdr->hdr_lba_start < 2 || hdr->hdr_lba_start >= last)
191                 return;
192         hdr->hdr_lba_end = le64toh(hdr->hdr_lba_end);
193         if (hdr->hdr_lba_end < hdr->hdr_lba_start || hdr->hdr_lba_end >= last)
194                 return;
195
196         /* Check the table location and size of the table. */
197         hdr->hdr_entries = le32toh(hdr->hdr_entries);
198         hdr->hdr_entsz = le32toh(hdr->hdr_entsz);
199         if (hdr->hdr_entries == 0 || hdr->hdr_entsz < 128 ||
200             (hdr->hdr_entsz & 7) != 0)
201                 return;
202         hdr->hdr_lba_table = le64toh(hdr->hdr_lba_table);
203         if (hdr->hdr_lba_table < 2 || hdr->hdr_lba_table >= last)
204                 return;
205         if (hdr->hdr_lba_table >= hdr->hdr_lba_start &&
206             hdr->hdr_lba_table <= hdr->hdr_lba_end)
207                 return;
208         lba = hdr->hdr_lba_table +
209             (hdr->hdr_entries * hdr->hdr_entsz + pp->sectorsize - 1) /
210             pp->sectorsize - 1;
211         if (lba >= last)
212                 return;
213         if (lba >= hdr->hdr_lba_start && lba <= hdr->hdr_lba_end)
214                 return;
215
216         table->state[elt] = GPT_STATE_OK;
217         le_uuid_dec(&hdr->hdr_uuid, &uuid);
218         hdr->hdr_uuid = uuid;
219         hdr->hdr_crc_table = le32toh(hdr->hdr_crc_table);
220 }
221
222 static struct gpt_ent *
223 gpt_read_tbl(struct g_part_gpt_table *table, struct g_consumer *cp,
224     enum gpt_elt elt, struct gpt_hdr *hdr)
225 {
226         struct g_provider *pp;
227         struct gpt_ent *ent, *tbl;
228         char *buf, *p;
229         unsigned int idx, sectors, tblsz;
230         int error;
231
232         pp = cp->provider;
233         table->lba[elt] = hdr->hdr_lba_table;
234
235         table->state[elt] = GPT_STATE_MISSING;
236         tblsz = hdr->hdr_entries * hdr->hdr_entsz;
237         sectors = (tblsz + pp->sectorsize - 1) / pp->sectorsize;
238         buf = g_read_data(cp, table->lba[elt] * pp->sectorsize, 
239             sectors * pp->sectorsize, &error);
240         if (buf == NULL)
241                 return (NULL);
242
243         table->state[elt] = GPT_STATE_CORRUPT;
244         if (crc32(buf, tblsz) != hdr->hdr_crc_table) {
245                 g_free(buf);
246                 return (NULL);
247         }
248
249         table->state[elt] = GPT_STATE_OK;
250         tbl = g_malloc(hdr->hdr_entries * sizeof(struct gpt_ent),
251             M_WAITOK | M_ZERO);
252
253         for (idx = 0, ent = tbl, p = buf;
254              idx < hdr->hdr_entries;
255              idx++, ent++, p += hdr->hdr_entsz) {
256                 le_uuid_dec(p, &ent->ent_type);
257                 le_uuid_dec(p + 16, &ent->ent_uuid);
258                 ent->ent_lba_start = le64dec(p + 32);
259                 ent->ent_lba_end = le64dec(p + 40);
260                 ent->ent_attr = le64dec(p + 48);
261                 /* Keep UTF-16 in little-endian. */
262                 bcopy(p + 56, ent->ent_name, sizeof(ent->ent_name));
263         }
264
265         g_free(buf);
266         return (tbl);
267 }
268
269 static int
270 gpt_matched_hdrs(struct gpt_hdr *pri, struct gpt_hdr *sec)
271 {
272
273         if (!EQUUID(&pri->hdr_uuid, &sec->hdr_uuid))
274                 return (0);
275         return ((pri->hdr_revision == sec->hdr_revision &&
276             pri->hdr_size == sec->hdr_size &&
277             pri->hdr_lba_start == sec->hdr_lba_start &&
278             pri->hdr_lba_end == sec->hdr_lba_end &&
279             pri->hdr_entries == sec->hdr_entries &&
280             pri->hdr_entsz == sec->hdr_entsz &&
281             pri->hdr_crc_table == sec->hdr_crc_table) ? 1 : 0);
282 }
283
284 static int
285 gpt_parse_type(const char *type, struct uuid *uuid)
286 {
287         struct uuid tmp;
288         const char *alias;
289         int error;
290
291         if (type[0] == '!') {
292                 error = parse_uuid(type + 1, &tmp);
293                 if (error)
294                         return (error);
295                 if (EQUUID(&tmp, &gpt_uuid_unused))
296                         return (EINVAL);
297                 *uuid = tmp;
298                 return (0);
299         }
300         alias = g_part_alias_name(G_PART_ALIAS_EFI);
301         if (!strcasecmp(type, alias)) {
302                 *uuid = gpt_uuid_efi;
303                 return (0);
304         }
305         alias = g_part_alias_name(G_PART_ALIAS_FREEBSD);
306         if (!strcasecmp(type, alias)) {
307                 *uuid = gpt_uuid_freebsd;
308                 return (0);
309         }
310         alias = g_part_alias_name(G_PART_ALIAS_FREEBSD_BOOT);
311         if (!strcasecmp(type, alias)) {
312                 *uuid = gpt_uuid_freebsd_boot;
313                 return (0);
314         }
315         alias = g_part_alias_name(G_PART_ALIAS_FREEBSD_SWAP);
316         if (!strcasecmp(type, alias)) {
317                 *uuid = gpt_uuid_freebsd_swap;
318                 return (0);
319         }
320         alias = g_part_alias_name(G_PART_ALIAS_FREEBSD_UFS);
321         if (!strcasecmp(type, alias)) {
322                 *uuid = gpt_uuid_freebsd_ufs;
323                 return (0);
324         }
325         alias = g_part_alias_name(G_PART_ALIAS_FREEBSD_VINUM);
326         if (!strcasecmp(type, alias)) {
327                 *uuid = gpt_uuid_freebsd_vinum;
328                 return (0);
329         }
330         alias = g_part_alias_name(G_PART_ALIAS_FREEBSD_ZFS);
331         if (!strcasecmp(type, alias)) {
332                 *uuid = gpt_uuid_freebsd_zfs;
333                 return (0);
334         }
335         alias = g_part_alias_name(G_PART_ALIAS_MBR);
336         if (!strcasecmp(type, alias)) {
337                 *uuid = gpt_uuid_mbr;
338                 return (0);
339         }
340         return (EINVAL);
341 }
342
343 static int
344 g_part_gpt_add(struct g_part_table *basetable, struct g_part_entry *baseentry,
345     struct g_part_parms *gpp)
346 {
347         struct g_part_gpt_entry *entry;
348         int error;
349
350         entry = (struct g_part_gpt_entry *)baseentry;
351         error = gpt_parse_type(gpp->gpp_type, &entry->ent.ent_type);
352         if (error)
353                 return (error);
354         kern_uuidgen(&entry->ent.ent_uuid, 1);
355         entry->ent.ent_lba_start = baseentry->gpe_start;
356         entry->ent.ent_lba_end = baseentry->gpe_end;
357         if (baseentry->gpe_deleted) {
358                 entry->ent.ent_attr = 0;
359                 bzero(entry->ent.ent_name, sizeof(entry->ent.ent_name));
360         }
361         if (gpp->gpp_parms & G_PART_PARM_LABEL)
362                 g_gpt_utf8_to_utf16(gpp->gpp_label, entry->ent.ent_name,
363                     sizeof(entry->ent.ent_name));
364         return (0);
365 }
366
367 static int
368 g_part_gpt_bootcode(struct g_part_table *basetable, struct g_part_parms *gpp)
369 {
370         struct g_part_gpt_table *table;
371         size_t codesz;
372
373         codesz = DOSPARTOFF;
374         table = (struct g_part_gpt_table *)basetable;
375         bzero(table->mbr, codesz);
376         codesz = MIN(codesz, gpp->gpp_codesize);
377         if (codesz > 0)
378                 bcopy(gpp->gpp_codeptr, table->mbr, codesz);
379         return (0);
380 }
381
382 static int
383 g_part_gpt_create(struct g_part_table *basetable, struct g_part_parms *gpp)
384 {
385         struct g_provider *pp;
386         struct g_part_gpt_table *table;
387         quad_t last;
388         size_t tblsz;
389
390         table = (struct g_part_gpt_table *)basetable;
391         pp = gpp->gpp_provider;
392         tblsz = (basetable->gpt_entries * sizeof(struct gpt_ent) +
393             pp->sectorsize - 1) / pp->sectorsize;
394         if (pp->sectorsize < MBRSIZE ||
395             pp->mediasize < (3 + 2 * tblsz + basetable->gpt_entries) *
396             pp->sectorsize)
397                 return (ENOSPC);
398
399         last = (pp->mediasize / pp->sectorsize) - 1;
400
401         le16enc(table->mbr + DOSMAGICOFFSET, DOSMAGIC);
402         table->mbr[DOSPARTOFF + 1] = 0xff;              /* shd */
403         table->mbr[DOSPARTOFF + 2] = 0xff;              /* ssect */
404         table->mbr[DOSPARTOFF + 3] = 0xff;              /* scyl */
405         table->mbr[DOSPARTOFF + 4] = 0xee;              /* typ */
406         table->mbr[DOSPARTOFF + 5] = 0xff;              /* ehd */
407         table->mbr[DOSPARTOFF + 6] = 0xff;              /* esect */
408         table->mbr[DOSPARTOFF + 7] = 0xff;              /* ecyl */
409         le32enc(table->mbr + DOSPARTOFF + 8, 1);        /* start */
410         le32enc(table->mbr + DOSPARTOFF + 12, MIN(last, 0xffffffffLL));
411
412         table->lba[GPT_ELT_PRIHDR] = 1;
413         table->lba[GPT_ELT_PRITBL] = 2;
414         table->lba[GPT_ELT_SECHDR] = last;
415         table->lba[GPT_ELT_SECTBL] = last - tblsz;
416
417         bcopy(GPT_HDR_SIG, table->hdr.hdr_sig, sizeof(table->hdr.hdr_sig));
418         table->hdr.hdr_revision = GPT_HDR_REVISION;
419         table->hdr.hdr_size = offsetof(struct gpt_hdr, padding);
420         table->hdr.hdr_lba_start = 2 + tblsz;
421         table->hdr.hdr_lba_end = last - tblsz - 1;
422         kern_uuidgen(&table->hdr.hdr_uuid, 1);
423         table->hdr.hdr_entries = basetable->gpt_entries;
424         table->hdr.hdr_entsz = sizeof(struct gpt_ent);
425
426         basetable->gpt_first = table->hdr.hdr_lba_start;
427         basetable->gpt_last = table->hdr.hdr_lba_end;
428         return (0);
429 }
430
431 static int
432 g_part_gpt_destroy(struct g_part_table *basetable, struct g_part_parms *gpp)
433 {
434
435         /*
436          * Wipe the first 2 sectors as well as the last to clear the
437          * partitioning.
438          */
439         basetable->gpt_smhead |= 3;
440         basetable->gpt_smtail |= 1;
441         return (0);
442 }
443
444 static void
445 g_part_gpt_dumpconf(struct g_part_table *table, struct g_part_entry *baseentry, 
446     struct sbuf *sb, const char *indent)
447 {
448         struct g_part_gpt_entry *entry;
449  
450         entry = (struct g_part_gpt_entry *)baseentry;
451         if (indent == NULL) {
452                 /* conftxt: libdisk compatibility */
453                 sbuf_printf(sb, " xs GPT xt ");
454                 sbuf_printf_uuid(sb, &entry->ent.ent_type);
455         } else if (entry != NULL) {
456                 /* confxml: partition entry information */
457                 sbuf_printf(sb, "%s<label>", indent);
458                 g_gpt_printf_utf16(sb, entry->ent.ent_name,
459                     sizeof(entry->ent.ent_name) >> 1);
460                 sbuf_printf(sb, "</label>\n");
461                 sbuf_printf(sb, "%s<rawtype>", indent);
462                 sbuf_printf_uuid(sb, &entry->ent.ent_type);
463                 sbuf_printf(sb, "</rawtype>\n");
464         } else {
465                 /* confxml: scheme information */
466         }
467 }
468
469 static int
470 g_part_gpt_dumpto(struct g_part_table *table, struct g_part_entry *baseentry)  
471 {
472         struct g_part_gpt_entry *entry;
473
474         entry = (struct g_part_gpt_entry *)baseentry;
475         return ((EQUUID(&entry->ent.ent_type, &gpt_uuid_freebsd_swap) ||
476             EQUUID(&entry->ent.ent_type, &gpt_uuid_linux_swap)) ? 1 : 0);
477 }
478
479 static int
480 g_part_gpt_modify(struct g_part_table *basetable,
481     struct g_part_entry *baseentry, struct g_part_parms *gpp)
482 {
483         struct g_part_gpt_entry *entry;
484         int error;
485
486         entry = (struct g_part_gpt_entry *)baseentry;
487         if (gpp->gpp_parms & G_PART_PARM_TYPE) {
488                 error = gpt_parse_type(gpp->gpp_type, &entry->ent.ent_type);
489                 if (error)
490                         return (error);
491         }
492         if (gpp->gpp_parms & G_PART_PARM_LABEL)
493                 g_gpt_utf8_to_utf16(gpp->gpp_label, entry->ent.ent_name,
494                     sizeof(entry->ent.ent_name));
495         return (0);
496 }
497
498 static const char *
499 g_part_gpt_name(struct g_part_table *table, struct g_part_entry *baseentry,
500     char *buf, size_t bufsz)
501 {
502         struct g_part_gpt_entry *entry;
503         char c;
504
505         entry = (struct g_part_gpt_entry *)baseentry;
506         c = (EQUUID(&entry->ent.ent_type, &gpt_uuid_freebsd)) ? 's' : 'p';
507         snprintf(buf, bufsz, "%c%d", c, baseentry->gpe_index);
508         return (buf);
509 }
510
511 static int
512 g_part_gpt_probe(struct g_part_table *table, struct g_consumer *cp)
513 {
514         struct g_provider *pp;
515         char *buf;
516         int error, res;
517
518         /* We don't nest, which means that our depth should be 0. */
519         if (table->gpt_depth != 0)
520                 return (ENXIO);
521
522         pp = cp->provider;
523
524         /*
525          * Sanity-check the provider. Since the first sector on the provider
526          * must be a PMBR and a PMBR is 512 bytes large, the sector size
527          * must be at least 512 bytes.  Also, since the theoretical minimum
528          * number of sectors needed by GPT is 6, any medium that has less
529          * than 6 sectors is never going to be able to hold a GPT. The
530          * number 6 comes from:
531          *      1 sector for the PMBR
532          *      2 sectors for the GPT headers (each 1 sector)
533          *      2 sectors for the GPT tables (each 1 sector)
534          *      1 sector for an actual partition
535          * It's better to catch this pathological case early than behaving
536          * pathologically later on...
537          */
538         if (pp->sectorsize < MBRSIZE || pp->mediasize < 6 * pp->sectorsize)
539                 return (ENOSPC);
540
541         /* Check that there's a MBR. */
542         buf = g_read_data(cp, 0L, pp->sectorsize, &error);
543         if (buf == NULL)
544                 return (error);
545         res = le16dec(buf + DOSMAGICOFFSET);
546         g_free(buf);
547         if (res != DOSMAGIC) 
548                 return (ENXIO);
549
550         /* Check that there's a primary header. */
551         buf = g_read_data(cp, pp->sectorsize, pp->sectorsize, &error);
552         if (buf == NULL)
553                 return (error);
554         res = memcmp(buf, GPT_HDR_SIG, 8);
555         g_free(buf);
556         if (res == 0)
557                 return (G_PART_PROBE_PRI_HIGH);
558
559         /* No primary? Check that there's a secondary. */
560         buf = g_read_data(cp, pp->mediasize - pp->sectorsize, pp->sectorsize,
561             &error);
562         if (buf == NULL)
563                 return (error);
564         res = memcmp(buf, GPT_HDR_SIG, 8); 
565         g_free(buf);
566         return ((res == 0) ? G_PART_PROBE_PRI_HIGH : ENXIO);
567 }
568
569 static int
570 g_part_gpt_read(struct g_part_table *basetable, struct g_consumer *cp)
571 {
572         struct gpt_hdr prihdr, sechdr;
573         struct gpt_ent *tbl, *pritbl, *sectbl;
574         struct g_provider *pp;
575         struct g_part_gpt_table *table;
576         struct g_part_gpt_entry *entry;
577         u_char *buf;
578         int error, index;
579
580         table = (struct g_part_gpt_table *)basetable;
581         pp = cp->provider;
582
583         /* Read the PMBR */
584         buf = g_read_data(cp, 0, pp->sectorsize, &error);
585         if (buf == NULL)
586                 return (error);
587         bcopy(buf, table->mbr, MBRSIZE);
588         g_free(buf);
589
590         /* Read the primary header and table. */
591         gpt_read_hdr(table, cp, GPT_ELT_PRIHDR, &prihdr);
592         if (table->state[GPT_ELT_PRIHDR] == GPT_STATE_OK) {
593                 pritbl = gpt_read_tbl(table, cp, GPT_ELT_PRITBL, &prihdr);
594         } else {
595                 table->state[GPT_ELT_PRITBL] = GPT_STATE_MISSING;
596                 pritbl = NULL;
597         }
598
599         /* Read the secondary header and table. */
600         gpt_read_hdr(table, cp, GPT_ELT_SECHDR, &sechdr);
601         if (table->state[GPT_ELT_SECHDR] == GPT_STATE_OK) {
602                 sectbl = gpt_read_tbl(table, cp, GPT_ELT_SECTBL, &sechdr);
603         } else {
604                 table->state[GPT_ELT_SECTBL] = GPT_STATE_MISSING;
605                 sectbl = NULL;
606         }
607
608         /* Fail if we haven't got any good tables at all. */
609         if (table->state[GPT_ELT_PRITBL] != GPT_STATE_OK &&
610             table->state[GPT_ELT_SECTBL] != GPT_STATE_OK) {
611                 printf("GEOM: %s: corrupt or invalid GPT detected.\n",
612                     pp->name);
613                 printf("GEOM: %s: GPT rejected -- may not be recoverable.\n",
614                     pp->name);
615                 return (EINVAL);
616         }
617
618         /*
619          * If both headers are good but they disagree with each other,
620          * then invalidate one. We prefer to keep the primary header,
621          * unless the primary table is corrupt.
622          */
623         if (table->state[GPT_ELT_PRIHDR] == GPT_STATE_OK &&
624             table->state[GPT_ELT_SECHDR] == GPT_STATE_OK &&
625             !gpt_matched_hdrs(&prihdr, &sechdr)) {
626                 if (table->state[GPT_ELT_PRITBL] == GPT_STATE_OK) {
627                         table->state[GPT_ELT_SECHDR] = GPT_STATE_INVALID;
628                         table->state[GPT_ELT_SECTBL] = GPT_STATE_MISSING;
629                 } else {
630                         table->state[GPT_ELT_PRIHDR] = GPT_STATE_INVALID;
631                         table->state[GPT_ELT_PRITBL] = GPT_STATE_MISSING;
632                 }
633         }
634
635         if (table->state[GPT_ELT_PRITBL] != GPT_STATE_OK) {
636                 printf("GEOM: %s: the primary GPT table is corrupt or "
637                     "invalid.\n", pp->name);
638                 printf("GEOM: %s: using the secondary instead -- recovery "
639                     "strongly advised.\n", pp->name);
640                 table->hdr = sechdr;
641                 tbl = sectbl;
642                 if (pritbl != NULL)
643                         g_free(pritbl);
644         } else {
645                 if (table->state[GPT_ELT_SECTBL] != GPT_STATE_OK) {
646                         printf("GEOM: %s: the secondary GPT table is corrupt "
647                             "or invalid.\n", pp->name);
648                         printf("GEOM: %s: using the primary only -- recovery "
649                             "suggested.\n", pp->name);
650                 }
651                 table->hdr = prihdr;
652                 tbl = pritbl;
653                 if (sectbl != NULL)
654                         g_free(sectbl);
655         }
656
657         basetable->gpt_first = table->hdr.hdr_lba_start;
658         basetable->gpt_last = table->hdr.hdr_lba_end;
659         basetable->gpt_entries = table->hdr.hdr_entries;
660
661         for (index = basetable->gpt_entries - 1; index >= 0; index--) {
662                 if (EQUUID(&tbl[index].ent_type, &gpt_uuid_unused))
663                         continue;
664                 entry = (struct g_part_gpt_entry *)g_part_new_entry(basetable,  
665                     index+1, tbl[index].ent_lba_start, tbl[index].ent_lba_end);
666                 entry->ent = tbl[index];
667         }
668
669         g_free(tbl);
670         return (0);
671 }
672
673 static const char *
674 g_part_gpt_type(struct g_part_table *basetable, struct g_part_entry *baseentry, 
675     char *buf, size_t bufsz)
676 {
677         struct g_part_gpt_entry *entry;
678         struct uuid *type;
679  
680         entry = (struct g_part_gpt_entry *)baseentry;
681         type = &entry->ent.ent_type;
682         if (EQUUID(type, &gpt_uuid_efi))
683                 return (g_part_alias_name(G_PART_ALIAS_EFI));
684         if (EQUUID(type, &gpt_uuid_freebsd))
685                 return (g_part_alias_name(G_PART_ALIAS_FREEBSD));
686         if (EQUUID(type, &gpt_uuid_freebsd_boot))
687                 return (g_part_alias_name(G_PART_ALIAS_FREEBSD_BOOT));
688         if (EQUUID(type, &gpt_uuid_freebsd_swap))
689                 return (g_part_alias_name(G_PART_ALIAS_FREEBSD_SWAP));
690         if (EQUUID(type, &gpt_uuid_freebsd_ufs))
691                 return (g_part_alias_name(G_PART_ALIAS_FREEBSD_UFS));
692         if (EQUUID(type, &gpt_uuid_freebsd_vinum))
693                 return (g_part_alias_name(G_PART_ALIAS_FREEBSD_VINUM));
694         if (EQUUID(type, &gpt_uuid_freebsd_zfs))
695                 return (g_part_alias_name(G_PART_ALIAS_FREEBSD_ZFS));
696         if (EQUUID(type, &gpt_uuid_mbr))
697                 return (g_part_alias_name(G_PART_ALIAS_MBR));
698         buf[0] = '!';
699         snprintf_uuid(buf + 1, bufsz - 1, type);
700         return (buf);
701 }
702
703 static int
704 g_part_gpt_write(struct g_part_table *basetable, struct g_consumer *cp)
705 {
706         unsigned char *buf, *bp;
707         struct g_provider *pp;
708         struct g_part_entry *baseentry;
709         struct g_part_gpt_entry *entry;
710         struct g_part_gpt_table *table;
711         size_t tlbsz;
712         uint32_t crc;
713         int error, index;
714
715         pp = cp->provider;
716         table = (struct g_part_gpt_table *)basetable;
717         tlbsz = (table->hdr.hdr_entries * table->hdr.hdr_entsz +
718             pp->sectorsize - 1) / pp->sectorsize;
719
720         /* Write the PMBR */
721         buf = g_malloc(pp->sectorsize, M_WAITOK | M_ZERO);
722         bcopy(table->mbr, buf, MBRSIZE);
723         error = g_write_data(cp, 0, buf, pp->sectorsize);
724         g_free(buf);
725         if (error)
726                 return (error);
727
728         /* Allocate space for the header and entries. */
729         buf = g_malloc((tlbsz + 1) * pp->sectorsize, M_WAITOK | M_ZERO);
730
731         memcpy(buf, table->hdr.hdr_sig, sizeof(table->hdr.hdr_sig));
732         le32enc(buf + 8, table->hdr.hdr_revision);
733         le32enc(buf + 12, table->hdr.hdr_size);
734         le64enc(buf + 40, table->hdr.hdr_lba_start);
735         le64enc(buf + 48, table->hdr.hdr_lba_end);
736         le_uuid_enc(buf + 56, &table->hdr.hdr_uuid);
737         le32enc(buf + 80, table->hdr.hdr_entries);
738         le32enc(buf + 84, table->hdr.hdr_entsz);
739
740         LIST_FOREACH(baseentry, &basetable->gpt_entry, gpe_entry) {
741                 if (baseentry->gpe_deleted)
742                         continue;
743                 entry = (struct g_part_gpt_entry *)baseentry;
744                 index = baseentry->gpe_index - 1;
745                 bp = buf + pp->sectorsize + table->hdr.hdr_entsz * index;
746                 le_uuid_enc(bp, &entry->ent.ent_type);
747                 le_uuid_enc(bp + 16, &entry->ent.ent_uuid);
748                 le64enc(bp + 32, entry->ent.ent_lba_start);
749                 le64enc(bp + 40, entry->ent.ent_lba_end);
750                 le64enc(bp + 48, entry->ent.ent_attr);
751                 memcpy(bp + 56, entry->ent.ent_name,
752                     sizeof(entry->ent.ent_name));
753         }
754
755         crc = crc32(buf + pp->sectorsize,
756             table->hdr.hdr_entries * table->hdr.hdr_entsz);
757         le32enc(buf + 88, crc);
758
759         /* Write primary meta-data. */
760         le32enc(buf + 16, 0);   /* hdr_crc_self. */
761         le64enc(buf + 24, table->lba[GPT_ELT_PRIHDR]);  /* hdr_lba_self. */
762         le64enc(buf + 32, table->lba[GPT_ELT_SECHDR]);  /* hdr_lba_alt. */
763         le64enc(buf + 72, table->lba[GPT_ELT_PRITBL]);  /* hdr_lba_table. */
764         crc = crc32(buf, table->hdr.hdr_size);
765         le32enc(buf + 16, crc);
766
767         error = g_write_data(cp, table->lba[GPT_ELT_PRITBL] * pp->sectorsize,
768             buf + pp->sectorsize, tlbsz * pp->sectorsize);
769         if (error)
770                 goto out;
771         error = g_write_data(cp, table->lba[GPT_ELT_PRIHDR] * pp->sectorsize,
772             buf, pp->sectorsize);
773         if (error)
774                 goto out;
775
776         /* Write secondary meta-data. */
777         le32enc(buf + 16, 0);   /* hdr_crc_self. */
778         le64enc(buf + 24, table->lba[GPT_ELT_SECHDR]);  /* hdr_lba_self. */
779         le64enc(buf + 32, table->lba[GPT_ELT_PRIHDR]);  /* hdr_lba_alt. */
780         le64enc(buf + 72, table->lba[GPT_ELT_SECTBL]);  /* hdr_lba_table. */
781         crc = crc32(buf, table->hdr.hdr_size);
782         le32enc(buf + 16, crc);
783
784         error = g_write_data(cp, table->lba[GPT_ELT_SECTBL] * pp->sectorsize,
785             buf + pp->sectorsize, tlbsz * pp->sectorsize);
786         if (error)
787                 goto out;
788         error = g_write_data(cp, table->lba[GPT_ELT_SECHDR] * pp->sectorsize,
789             buf, pp->sectorsize);
790
791  out:
792         g_free(buf);
793         return (error);
794 }
795
796 static void
797 g_gpt_printf_utf16(struct sbuf *sb, uint16_t *str, size_t len)
798 {
799         u_int bo;
800         uint32_t ch;
801         uint16_t c;
802
803         bo = LITTLE_ENDIAN;     /* GPT is little-endian */
804         while (len > 0 && *str != 0) {
805                 ch = (bo == BIG_ENDIAN) ? be16toh(*str) : le16toh(*str);
806                 str++, len--;
807                 if ((ch & 0xf800) == 0xd800) {
808                         if (len > 0) {
809                                 c = (bo == BIG_ENDIAN) ? be16toh(*str)
810                                     : le16toh(*str);
811                                 str++, len--;
812                         } else
813                                 c = 0xfffd;
814                         if ((ch & 0x400) == 0 && (c & 0xfc00) == 0xdc00) {
815                                 ch = ((ch & 0x3ff) << 10) + (c & 0x3ff);
816                                 ch += 0x10000;
817                         } else
818                                 ch = 0xfffd;
819                 } else if (ch == 0xfffe) { /* BOM (U+FEFF) swapped. */
820                         bo = (bo == BIG_ENDIAN) ? LITTLE_ENDIAN : BIG_ENDIAN;
821                         continue;
822                 } else if (ch == 0xfeff) /* BOM (U+FEFF) unswapped. */
823                         continue;
824
825                 /* Write the Unicode character in UTF-8 */
826                 if (ch < 0x80)
827                         sbuf_printf(sb, "%c", ch);
828                 else if (ch < 0x800)
829                         sbuf_printf(sb, "%c%c", 0xc0 | (ch >> 6),
830                             0x80 | (ch & 0x3f));
831                 else if (ch < 0x10000)
832                         sbuf_printf(sb, "%c%c%c", 0xe0 | (ch >> 12),
833                             0x80 | ((ch >> 6) & 0x3f), 0x80 | (ch & 0x3f));
834                 else if (ch < 0x200000)
835                         sbuf_printf(sb, "%c%c%c%c", 0xf0 | (ch >> 18),
836                             0x80 | ((ch >> 12) & 0x3f),
837                             0x80 | ((ch >> 6) & 0x3f), 0x80 | (ch & 0x3f));
838         }
839 }
840
841 static void
842 g_gpt_utf8_to_utf16(const uint8_t *s8, uint16_t *s16, size_t s16len)
843 {
844         size_t s16idx, s8idx;
845         uint32_t utfchar;
846         unsigned int c, utfbytes;
847
848         s8idx = s16idx = 0;
849         utfchar = 0;
850         utfbytes = 0;
851         bzero(s16, s16len << 1);
852         while (s8[s8idx] != 0 && s16idx < s16len) {
853                 c = s8[s8idx++];
854                 if ((c & 0xc0) != 0x80) {
855                         /* Initial characters. */
856                         if (utfbytes != 0) {
857                                 /* Incomplete encoding of previous char. */
858                                 s16[s16idx++] = htole16(0xfffd);
859                         }
860                         if ((c & 0xf8) == 0xf0) {
861                                 utfchar = c & 0x07;
862                                 utfbytes = 3;
863                         } else if ((c & 0xf0) == 0xe0) {
864                                 utfchar = c & 0x0f;
865                                 utfbytes = 2;
866                         } else if ((c & 0xe0) == 0xc0) {
867                                 utfchar = c & 0x1f;
868                                 utfbytes = 1;
869                         } else {
870                                 utfchar = c & 0x7f;
871                                 utfbytes = 0;
872                         }
873                 } else {
874                         /* Followup characters. */
875                         if (utfbytes > 0) {
876                                 utfchar = (utfchar << 6) + (c & 0x3f);
877                                 utfbytes--;
878                         } else if (utfbytes == 0)
879                                 utfbytes = ~0;
880                 }
881                 /*
882                  * Write the complete Unicode character as UTF-16 when we
883                  * have all the UTF-8 charactars collected.
884                  */
885                 if (utfbytes == 0) {
886                         /*
887                          * If we need to write 2 UTF-16 characters, but
888                          * we only have room for 1, then we truncate the
889                          * string by writing a 0 instead.
890                          */
891                         if (utfchar >= 0x10000 && s16idx < s16len - 1) {
892                                 s16[s16idx++] =
893                                     htole16(0xd800 | ((utfchar >> 10) - 0x40));
894                                 s16[s16idx++] =
895                                     htole16(0xdc00 | (utfchar & 0x3ff));
896                         } else
897                                 s16[s16idx++] = (utfchar >= 0x10000) ? 0 :
898                                     htole16(utfchar);
899                 }
900         }
901         /*
902          * If our input string was truncated, append an invalid encoding
903          * character to the output string.
904          */
905         if (utfbytes != 0 && s16idx < s16len)
906                 s16[s16idx++] = htole16(0xfffd);
907 }