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