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