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