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