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