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