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