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