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