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