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