xref: /netbsd-src/usr.sbin/sysinst/gpt.c (revision 181254a7b1bdde6873432bffef2d2decc4b5c22f)
1 /*	$NetBSD: gpt.c,v 1.18 2020/03/30 12:19:28 martin Exp $	*/
2 
3 /*
4  * Copyright 2018 The NetBSD Foundation, Inc.
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  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY PIERMONT INFORMATION SYSTEMS INC. ``AS IS''
17  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED. IN NO EVENT SHALL PIERMONT INFORMATION SYSTEMS INC. BE
20  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
26  * THE POSSIBILITY OF SUCH DAMAGE.
27  *
28  */
29 
30 #include "defs.h"
31 #include "mbr.h"
32 #include "md.h"
33 #include "gpt_uuid.h"
34 #include <assert.h>
35 #include <err.h>
36 #include <paths.h>
37 #include <sys/param.h>
38 #include <sys/ioctl.h>
39 #include <util.h>
40 #include <uuid.h>
41 
42 bool	gpt_parts_check(void);	/* check for needed binaries */
43 
44 
45 /*************** GPT ************************************************/
46 /* a GPT based disk_partitions interface */
47 
48 #define GUID_STR_LEN	40
49 #define	GPT_PTYPE_ALLOC	32	/* initial type array allocation, should be >
50 				 * gpt type -l | wc -l */
51 #define	GPT_DEV_LEN	16	/* dkNN */
52 
53 #define	GPT_PARTS_PER_SEC	4	/* a 512 byte sector holds 4 entries */
54 #define	GPT_DEFAULT_MAX_PARTS	128
55 
56 /* a usable label will be short, so we can get away with an arbitrary limit */
57 #define	GPT_LABEL_LEN		96
58 
59 #define	GPT_ATTR_BIOSBOOT	1
60 #define	GPT_ATTR_BOOTME		2
61 #define	GPT_ATTR_BOOTONCE	4
62 #define	GPT_ATTR_BOOTFAILED	8
63 #define	GPT_ATTR_NOBLOCKIO	16
64 #define	GPT_ATTR_REQUIRED	32
65 
66 /* when we don't care for BIOS or UEFI boot, use the combined boot flags */
67 #define	GPT_ATTR_BOOT	(GPT_ATTR_BIOSBOOT|GPT_ATTR_BOOTME)
68 
69 struct gpt_attr_desc {
70 	const char *name;
71 	uint flag;
72 };
73 static const struct gpt_attr_desc gpt_avail_attrs[] = {
74 	{ "biosboot", GPT_ATTR_BIOSBOOT },
75 	{ "bootme", GPT_ATTR_BOOTME },
76 	{ "bootonce", GPT_ATTR_BOOTONCE },
77 	{ "bootfailed", GPT_ATTR_BOOTFAILED },
78 	{ "noblockio", GPT_ATTR_NOBLOCKIO },
79 	{ "required", GPT_ATTR_REQUIRED },
80 	{ NULL, 0 }
81 };
82 
83 struct gpt_ptype_desc {
84 	struct part_type_desc gent;
85 	char tid[GUID_STR_LEN];
86 	uint fsflags, default_fs_type;
87 };
88 
89 static const
90 struct {
91 	const char *name;
92 	uint fstype;
93 	enum part_type ptype;
94 	uint fsflags;
95 } gpt_fs_types[] = {
96 	{ .name = "ffs",	.fstype = FS_BSDFFS,	.ptype = PT_root,
97 	  .fsflags = GLM_LIKELY_FFS },
98 	{ .name = "swap",	.fstype = FS_SWAP,	.ptype = PT_swap },
99 	{ .name = "windows",	.fstype = FS_MSDOS,	.ptype = PT_FAT,
100 	  .fsflags = GLM_MAYBE_FAT32|GLM_MAYBE_NTFS },
101 	{ .name = "windows",	.fstype = FS_NTFS,	.ptype = PT_FAT,
102 	  .fsflags = GLM_MAYBE_FAT32|GLM_MAYBE_NTFS },
103 	{ .name = "efi",	.fstype = FS_MSDOS,	.ptype = PT_EFI_SYSTEM,
104 	  .fsflags = GLM_MAYBE_FAT32 },
105 	{ .name = "bios",	.fstype = FS_MSDOS,	.ptype = PT_FAT,
106 	  .fsflags = GLM_MAYBE_FAT32 },
107 	{ .name = "lfs",	.fstype = FS_BSDLFS,	.ptype = PT_root },
108 	{ .name = "linux-data",	.fstype = FS_EX2FS,	.ptype = PT_root },
109 	{ .name = "apple",	.fstype = FS_HFS,	.ptype = PT_unknown },
110 	{ .name = "ccd",	.fstype = FS_CCD,	.ptype = PT_root },
111 	{ .name = "cgd",	.fstype = FS_CGD,	.ptype = PT_root },
112 	{ .name = "raid",	.fstype = FS_RAID,	.ptype = PT_root },
113 	{ .name = "vmcore",	.fstype = FS_VMKCORE,	.ptype = PT_unknown },
114 	{ .name = "vmfs",	.fstype = FS_VMFS,	.ptype = PT_unknown },
115 	{ .name = "vmresered",	.fstype = FS_VMWRESV,	.ptype = PT_unknown },
116 	{ .name = "zfs",	.fstype = FS_ZFS,	.ptype = PT_root },
117 };
118 
119 static size_t gpt_ptype_cnt = 0, gpt_ptype_alloc = 0;
120 static struct gpt_ptype_desc *gpt_ptype_descs = NULL;
121 
122 /* "well" known types with special handling */
123 static const struct part_type_desc *gpt_native_root;
124 
125 /* similar to struct gpt_ent, but matching our needs */
126 struct gpt_part_entry {
127 	const struct gpt_ptype_desc *gp_type;
128 	char gp_id[GUID_STR_LEN];	/* partition guid as string */
129 	daddr_t gp_start, gp_size;
130 	uint gp_attr;			/* various attribute bits */
131 	char gp_label[GPT_LABEL_LEN];	/* user defined label */
132 	char gp_dev_name[GPT_DEV_LEN];	/* name of wedge */
133 	const char *last_mounted;	/* last mounted if known */
134 	uint fs_type, fs_sub_type;	/* FS_* and maybe sub type */
135 	uint gp_flags;
136 #define	GPEF_ON_DISK	1		/* This entry exists on-disk */
137 #define	GPEF_MODIFIED	2		/* this entry has been changed */
138 #define	GPEF_WEDGE	4		/* wedge for this exists */
139 #define	GPEF_RESIZED	8		/* size has changed */
140 	struct gpt_part_entry *gp_next;
141 };
142 
143 static const struct gpt_ptype_desc *gpt_find_native_type(
144     const struct part_type_desc *gent);
145 static const struct gpt_ptype_desc *gpt_find_guid_type(const char*);
146 static bool
147 gpt_info_to_part(struct gpt_part_entry *p, const struct disk_part_info *info,
148     const char **err_msg);
149 
150 const struct disk_partitioning_scheme gpt_parts;
151 struct gpt_disk_partitions {
152 	struct disk_partitions dp;
153 	/*
154 	 * We keep a list of our current valid partitions, pointed
155 	 * to by "partitions".
156 	 * dp.num_part is the number of entries in "partitions".
157 	 * When partitions that have a representation on disk already
158 	 * are deleted, we move them to the "obsolete" list so we
159 	 * can issue the proper commands to remove it when writing back.
160 	 */
161 	struct gpt_part_entry *partitions,	/* current partitions */
162 	    *obsolete;				/* deleted partitions */
163 	size_t max_num_parts;			/* how many entries max? */
164 	size_t prologue, epilogue;		/* number of sectors res. */
165 	bool has_gpt;	/* disk already has a GPT */
166 };
167 
168 /*
169  * Init global variables from MD details
170  */
171 static void
172 gpt_md_init(bool is_boot_disk, size_t *max_parts, size_t *head, size_t *tail)
173 {
174 	size_t num;
175 
176 	if (is_boot_disk) {
177 #ifdef MD_GPT_INITIAL_SIZE
178 #if MD_GPT_INITIAL_SIZE < 2*512
179 #error	impossible small GPT prologue
180 #endif
181 		num = ((MD_GPT_INITIAL_SIZE-(2*512))/512)*GPT_PARTS_PER_SEC;
182 #else
183 		num = GPT_DEFAULT_MAX_PARTS;
184 #endif
185 	} else {
186 		num = GPT_DEFAULT_MAX_PARTS;
187 	}
188 	*max_parts = num;
189 	*head = 2 + num/GPT_PARTS_PER_SEC;
190 	*tail = 1 + num/GPT_PARTS_PER_SEC;
191 }
192 
193 /*
194  * Parse a part of "gpt show" output into a struct gpt_part_entry.
195  * Output is from "show -a" format if details = false, otherwise
196  * from details for a specific partition (show -i or show -b)
197  */
198 static void
199 gpt_add_info(struct gpt_part_entry *part, const char *tag, char *val,
200     bool details)
201 {
202 	char *s, *e;
203 
204 	if (details && strcmp(tag, "Start:") == 0) {
205 		part->gp_start = strtouq(val, NULL, 10);
206 	} else if (details && strcmp(tag, "Size:") == 0) {
207 		part->gp_size = strtouq(val, NULL, 10);
208 	} else if (details && strcmp(tag, "Type:") == 0) {
209 		s = strchr(val, '(');
210 		if (!s)
211 			return;
212 		e = strchr(s, ')');
213 		if (!e)
214 			return;
215 		*e = 0;
216 		part->gp_type = gpt_find_guid_type(s+1);
217 	} else if (strcmp(tag, "TypeID:") == 0) {
218 		part->gp_type = gpt_find_guid_type(val);
219 	} else if (strcmp(tag, "GUID:") == 0) {
220 		strlcpy(part->gp_id, val, sizeof(part->gp_id));
221 	} else if (strcmp(tag, "Label:") == 0) {
222 		strlcpy(part->gp_label, val, sizeof(part->gp_label));
223 	} else if (strcmp(tag, "Attributes:") == 0) {
224 		char *n;
225 
226 		while ((n = strsep(&val, ", ")) != NULL) {
227 			if (*n == 0)
228 				continue;
229 			for (const struct gpt_attr_desc *p = gpt_avail_attrs;
230 			    p->name != NULL; p++) {
231 				if (strcmp(p->name, n) == 0)
232 					part->gp_attr |= p->flag;
233 			}
234 		}
235 	}
236 }
237 
238 /*
239  * Find the partition matching this wedge info and record that we
240  * have a wedge already.
241  */
242 static void
243 update_part_from_wedge_info(struct gpt_disk_partitions *parts,
244     const struct dkwedge_info *dkw)
245 {
246 	for (struct gpt_part_entry *p = parts->partitions; p != NULL;
247 	    p = p->gp_next) {
248 		if (p->gp_start != dkw->dkw_offset ||
249 		    (uint64_t)p->gp_size != dkw->dkw_size)
250 			continue;
251 		p->gp_flags |= GPEF_WEDGE;
252 		strlcpy(p->gp_dev_name, dkw->dkw_devname,
253 		    sizeof p->gp_dev_name);
254 		return;
255 	}
256 }
257 
258 static struct disk_partitions *
259 gpt_read_from_disk(const char *dev, daddr_t start, daddr_t len, size_t bps,
260     const struct disk_partitioning_scheme *scheme)
261 {
262 	char diskpath[MAXPATHLEN];
263 	int fd;
264 	struct dkwedge_info *dkw;
265 	struct dkwedge_list dkwl;
266 	size_t bufsize, dk;
267 
268 	assert(start == 0);
269 	assert(have_gpt);
270 
271 	if (run_program(RUN_SILENT | RUN_ERROR_OK,
272 	    "gpt -rq header %s", dev) != 0)
273 		return NULL;
274 
275 	/* read the partitions */
276 	int i;
277 	unsigned int p_index;
278 	daddr_t p_start = 0, p_size = 0, avail_start = 0, avail_size = 0,
279 	    disk_size = 0;
280 	char *textbuf, *t, *tt, p_type[STRSIZE];
281 	static const char regpart_prefix[] = "GPT part - ";
282 	struct gpt_disk_partitions *parts;
283 	struct gpt_part_entry *last = NULL, *add_to = NULL;
284 
285 	if (collect(T_OUTPUT, &textbuf, "gpt -r show -a %s 2>/dev/null", dev)
286 	    < 1)
287 		return NULL;
288 
289 	/* parse output and create our list */
290 	parts = calloc(1, sizeof(*parts));
291 	if (parts == NULL)
292 		return NULL;
293 
294 	(void)strtok(textbuf, "\n"); /* ignore first line */
295 	while ((t = strtok(NULL, "\n")) != NULL) {
296 		i = 0; p_start = 0; p_size = 0; p_index = 0;
297 		p_type[0] = 0;
298 		while ((tt = strsep(&t, " \t")) != NULL) {
299 			if (strlen(tt) == 0)
300 				continue;
301 			if (i == 0) {
302 				if (add_to != NULL)
303 					gpt_add_info(add_to, tt, t, false);
304 				p_start = strtouq(tt, NULL, 10);
305 				if (p_start == 0 && add_to != NULL)
306 					break;
307 				else
308 					add_to = NULL;
309 			}
310 			if (i == 1)
311 				p_size = strtouq(tt, NULL, 10);
312 			if (i == 2)
313 				p_index = strtouq(tt, NULL, 10);
314 			if (i > 2 || (i == 2 && p_index == 0)) {
315 				if (p_type[0])
316 					strlcat(p_type, " ", STRSIZE);
317 				strlcat(p_type, tt, STRSIZE);
318 			}
319 			i++;
320 		}
321 
322 		if (p_start == 0 || p_size == 0)
323 			continue;
324 		else if (strcmp(p_type, "Pri GPT table") == 0) {
325 			avail_start = p_start + p_size;
326 			parts->prologue = avail_start;
327 			parts->epilogue = p_size + 1;
328 			parts->max_num_parts = p_size * GPT_PARTS_PER_SEC;
329 		} else if (strcmp(p_type, "Sec GPT table") == 0)
330 			avail_size = p_start - avail_start;
331 		else if(strcmp(p_type, "Sec GPT header") == 0)
332 			disk_size = p_start + p_size;
333 		else if (p_index == 0 && strlen(p_type) > 0)
334 			/* Utilitary entry (PMBR, etc) */
335 			continue;
336 		else if (p_index == 0) {
337 			/* Free space */
338 			continue;
339 		} else {
340 			/* Usual partition */
341 			tt = p_type;
342 			if (strncmp(tt, regpart_prefix,
343 			    strlen(regpart_prefix)) == 0)
344 				tt += strlen(regpart_prefix);
345 
346 			/* Add to our linked list */
347 			struct gpt_part_entry *np = calloc(1, sizeof(*np));
348 			if (np == NULL)
349 				break;
350 
351 			strlcpy(np->gp_label, tt, sizeof(np->gp_label));
352 			np->gp_start = p_start;
353 			np->gp_size = p_size;
354 			np->gp_flags |= GPEF_ON_DISK;
355 
356 			if (last == NULL)
357 				parts->partitions = np;
358 			else
359 				last->gp_next = np;
360 			last = np;
361 			add_to = np;
362 			parts->dp.num_part++;
363 		}
364 	}
365 	free(textbuf);
366 
367 	/* If the GPT was not complete (e.g. truncated image), barf */
368 	if (disk_size <= 0) {
369 		free(parts);
370 		return NULL;
371 	}
372 
373 	parts->dp.pscheme = scheme;
374 	parts->dp.disk = strdup(dev);
375 	parts->dp.disk_start = start;
376 	parts->dp.disk_size = disk_size;
377 	parts->dp.free_space = avail_size;
378 	parts->dp.bytes_per_sector = bps;
379 	parts->has_gpt = true;
380 
381 	fd = opendisk(parts->dp.disk, O_RDONLY, diskpath, sizeof(diskpath), 0);
382 	for (struct gpt_part_entry *p = parts->partitions; p != NULL;
383 	    p = p->gp_next) {
384 #ifdef DEFAULT_UFS2
385 		bool fs_is_default = false;
386 #endif
387 
388 		if (p->gp_type != NULL) {
389 
390 			if (p->gp_type->fsflags != 0) {
391 				const char *lm = get_last_mounted(fd,
392 				    p->gp_start, &p->fs_type,
393 				    &p->fs_sub_type, p->gp_type->fsflags);
394 				if (lm != NULL && *lm != 0) {
395 					char *path = strdup(lm);
396 					canonicalize_last_mounted(path);
397 					p->last_mounted = path;
398 				} else {
399 					p->fs_type = p->gp_type->
400 					    default_fs_type;
401 #ifdef DEFAULT_UFS2
402 					fs_is_default = true;
403 #endif
404 				}
405 			} else {
406 				p->fs_type = p->gp_type->default_fs_type;
407 #ifdef DEFAULT_UFS2
408 				fs_is_default = true;
409 #endif
410 			}
411 #ifdef DEFAULT_UFS2
412 			if (fs_is_default && p->fs_type == FS_BSDFFS)
413 				p->fs_sub_type = 2;
414 #endif
415 		}
416 
417 		parts->dp.free_space -= p->gp_size;
418 	}
419 
420 	/*
421 	 * Check if we have any (matching/auto-configured) wedges already
422 	 */
423 	dkw = NULL;
424 	dkwl.dkwl_buf = dkw;
425 	dkwl.dkwl_bufsize = 0;
426 	if (ioctl(fd, DIOCLWEDGES, &dkwl) == 0) {
427 		/* do not even try to deal with any races at this point */
428 		bufsize = dkwl.dkwl_nwedges * sizeof(*dkw);
429 		dkw = malloc(bufsize);
430 		dkwl.dkwl_buf = dkw;
431 		dkwl.dkwl_bufsize = bufsize;
432 		if (dkw != NULL && ioctl(fd, DIOCLWEDGES, &dkwl) == 0) {
433 			for (dk = 0; dk < dkwl.dkwl_ncopied; dk++)
434 				update_part_from_wedge_info(parts, &dkw[dk]);
435 		}
436 		free(dkw);
437 	}
438 
439 	close(fd);
440 
441 	return &parts->dp;
442 }
443 
444 static size_t
445 gpt_cyl_size(const struct disk_partitions *arg)
446 {
447 	return MEG / 512;
448 }
449 
450 static struct disk_partitions *
451 gpt_create_new(const char *disk, daddr_t start, daddr_t len,
452     bool is_boot_drive, struct disk_partitions *parent)
453 {
454 	struct gpt_disk_partitions *parts;
455 	struct disk_geom geo;
456 
457 	if (start != 0) {
458 		assert(0);
459 		return NULL;
460 	}
461 
462 	if (!get_disk_geom(disk, &geo))
463 		return NULL;
464 
465 	parts = calloc(1, sizeof(*parts));
466 	if (!parts)
467 		return NULL;
468 
469 	parts->dp.pscheme = &gpt_parts;
470 	parts->dp.disk = strdup(disk);
471 
472 	gpt_md_init(is_boot_drive, &parts->max_num_parts, &parts->prologue,
473 	    &parts->epilogue);
474 
475 	parts->dp.disk_start = start;
476 	parts->dp.disk_size = len;
477 	parts->dp.bytes_per_sector = geo.dg_secsize;
478 	parts->dp.free_space = len - start - parts->prologue - parts->epilogue;
479 	parts->has_gpt = false;
480 
481 	return &parts->dp;
482 }
483 
484 static bool
485 gpt_get_part_info(const struct disk_partitions *arg, part_id id,
486     struct disk_part_info *info)
487 {
488 	static const struct part_type_desc gpt_unknown_type =
489 		{ .generic_ptype = PT_undef,
490 		  .short_desc = "<unknown>" };
491 	const struct gpt_disk_partitions *parts =
492 	    (const struct gpt_disk_partitions*)arg;
493 	const struct gpt_part_entry *p = parts->partitions;
494 	part_id no;
495 
496 	for (no = 0; p != NULL && no < id; no++)
497 		p = p->gp_next;
498 
499 	if (no != id || p == NULL)
500 		return false;
501 
502 	memset(info, 0, sizeof(*info));
503 	info->start = p->gp_start;
504 	info->size = p->gp_size;
505 	if (p->gp_type)
506 		info->nat_type = &p->gp_type->gent;
507 	else
508 		info->nat_type = &gpt_unknown_type;
509 	info->last_mounted = p->last_mounted;
510 	info->fs_type = p->fs_type;
511 	info->fs_sub_type = p->fs_sub_type;
512 
513 	return true;
514 }
515 
516 static bool
517 gpt_get_part_attr_str(const struct disk_partitions *arg, part_id id,
518     char *str, size_t avail_space)
519 {
520 	const struct gpt_disk_partitions *parts =
521 	    (const struct gpt_disk_partitions*)arg;
522 	const struct gpt_part_entry *p = parts->partitions;
523 	part_id no;
524 	static const char *flags = NULL;
525 
526 	for (no = 0; p != NULL && no < id; no++)
527 		p = p->gp_next;
528 
529 	if (no != id || p == NULL)
530 		return false;
531 
532 	if (flags == NULL)
533 		flags = msg_string(MSG_gpt_flags);
534 
535 	if (avail_space < 2)
536 		return false;
537 
538 	if (p->gp_attr & GPT_ATTR_BOOT)
539 		*str++ = flags[0];
540 	*str = 0;
541 
542 	return true;
543 }
544 
545 /*
546  * Find insert position and check for duplicates.
547  * If all goes well, insert the new "entry" in the "list".
548  * If there are collisions, report "no free space".
549  * We keep all lists sorted by start sector number,
550  */
551 static bool
552 gpt_insert_part_into_list(struct gpt_disk_partitions *parts,
553     struct gpt_part_entry **list,
554     struct gpt_part_entry *entry, const char **err_msg)
555 {
556 	struct gpt_part_entry *p, *last;
557 
558 	/* find the first entry past the new one (if any) */
559 	for (last = NULL, p = *list; p != NULL; last = p, p = p->gp_next) {
560 		if (p->gp_start > entry->gp_start)
561 			break;
562 	}
563 
564 	/* check if last partition overlaps with new one */
565 	if (last) {
566 		if (last->gp_start + last->gp_size > entry->gp_start) {
567 			if (err_msg)
568 				*err_msg = msg_string(MSG_No_free_space);
569 			return false;
570 		}
571 	}
572 
573 	if (p == NULL) {
574 		entry->gp_next = NULL;
575 		if (last != NULL) {
576 			last->gp_next = entry;
577 		}
578 	} else {
579 		/* check if new entry overlaps with next */
580 		if (entry->gp_start + entry->gp_size > p->gp_start) {
581 			if (err_msg)
582 				*err_msg = msg_string(MSG_No_free_space);
583 			return false;
584 		}
585 
586 		entry->gp_next = p;
587 		if (last != NULL)
588 			last->gp_next = entry;
589 		else
590 			*list = entry;
591 	}
592 	if (*list == NULL)
593 		*list = entry;
594 
595 	return true;
596 }
597 
598 static bool
599 gpt_set_part_info(struct disk_partitions *arg, part_id id,
600     const struct disk_part_info *info, const char **err_msg)
601 {
602 	struct gpt_disk_partitions *parts =
603 	    (struct gpt_disk_partitions*)arg;
604 	struct gpt_part_entry *p = parts->partitions, *n;
605 	part_id no;
606 	daddr_t lendiff;
607 
608 	for (no = 0; p != NULL && no < id; no++)
609 		p = p->gp_next;
610 
611 	if (no != id || p == NULL)
612 		return false;
613 
614 	if ((p->gp_flags & GPEF_ON_DISK)) {
615 		if (info->start != p->gp_start) {
616 			/* partition moved, we need to delete and re-add */
617 			n = calloc(1, sizeof(*n));
618 			if (n == NULL) {
619 				if (err_msg)
620 					*err_msg = err_outofmem;
621 				return false;
622 			}
623 			*n = *p;
624 			p->gp_flags &= ~GPEF_ON_DISK;
625 			if (!gpt_insert_part_into_list(parts, &parts->obsolete,
626 			    n, err_msg))
627 				return false;
628 		} else if (info->size != p->gp_size) {
629 			p->gp_flags |= GPEF_RESIZED;
630 		}
631 	}
632 
633 	p->gp_flags |= GPEF_MODIFIED;
634 
635 	lendiff = info->size - p->gp_size;
636 	parts->dp.free_space -= lendiff;
637 	return gpt_info_to_part(p, info, err_msg);
638 }
639 
640 static size_t
641 gpt_get_free_spaces_internal(const struct gpt_disk_partitions *parts,
642     struct disk_part_free_space *result, size_t max_num_result,
643     daddr_t min_space_size, daddr_t align, daddr_t start, daddr_t ignore)
644 {
645 	size_t cnt = 0;
646 	daddr_t s, e, from, size, end_of_disk;
647 	struct gpt_part_entry *p;
648 
649 	if (align > 1)
650 		start = max(roundup(start, align), align);
651 	if (start < 0 || start < (daddr_t)parts->prologue)
652 		start = parts->prologue;
653 	if (parts->dp.disk_start != 0 && parts->dp.disk_start > start)
654 		start = parts->dp.disk_start;
655 	if (min_space_size < 1)
656 		min_space_size = 1;
657 	end_of_disk = parts->dp.disk_start + parts->dp.disk_size
658 	    - parts->epilogue;
659 	from = start;
660 	while (from < end_of_disk && cnt < max_num_result) {
661 again:
662 		size = parts->dp.disk_start + parts->dp.disk_size - from;
663 		start = from;
664 		if (start + size > end_of_disk)
665 			size = end_of_disk - start;
666 		for (p = parts->partitions; p != NULL; p = p->gp_next) {
667 			s = p->gp_start;
668 			e = p->gp_size + s;
669 			if (s == ignore)
670 				continue;
671 			if (e < from)
672 				continue;
673 			if (s <= from && e > from) {
674 				if (e - 1 >= end_of_disk)
675 					return cnt;
676 				from = e + 1;
677 				if (align > 1) {
678 					from = max(roundup(from, align), align);
679 					if (from >= end_of_disk) {
680 						size = 0;
681 						break;
682 					}
683 				}
684 				goto again;
685 			}
686 			if (s > from && s - from < size) {
687 				size = s - from;
688 			}
689 		}
690 		if (size >= min_space_size) {
691 			result->start = start;
692 			result->size = size;
693 			result++;
694 			cnt++;
695 		}
696 		from += size + 1;
697 		if (align > 1)
698 			from = max(roundup(from, align), align);
699 	}
700 
701 	return cnt;
702 }
703 
704 static daddr_t
705 gpt_max_free_space_at(const struct disk_partitions *arg, daddr_t start)
706 {
707 	const struct gpt_disk_partitions *parts =
708 	    (const struct gpt_disk_partitions*)arg;
709 	struct disk_part_free_space space;
710 
711 	if (gpt_get_free_spaces_internal(parts, &space, 1, 1, 0,
712 	    start, start) == 1)
713 		return space.size;
714 
715 	return 0;
716 }
717 
718 static size_t
719 gpt_get_free_spaces(const struct disk_partitions *arg,
720     struct disk_part_free_space *result, size_t max_num_result,
721     daddr_t min_space_size, daddr_t align, daddr_t start,
722     daddr_t ignore)
723 {
724 	const struct gpt_disk_partitions *parts =
725 	    (const struct gpt_disk_partitions*)arg;
726 
727 	return gpt_get_free_spaces_internal(parts, result,
728 	    max_num_result, min_space_size, align, start, ignore);
729 }
730 
731 static void
732 gpt_match_ptype(const char *name, struct gpt_ptype_desc *t)
733 {
734 	size_t i;
735 
736 	for (i = 0; i < __arraycount(gpt_fs_types); i++) {
737 		if (strcmp(name, gpt_fs_types[i].name) == 0) {
738 			t->gent.generic_ptype = gpt_fs_types[i].ptype;
739 			t->fsflags = gpt_fs_types[i].fsflags;
740 			t->default_fs_type = gpt_fs_types[i].fstype;
741 
742 			/* recongnize special entries */
743 			if (gpt_native_root == NULL && i == 0)
744 				gpt_native_root = &t->gent;
745 
746 			return;
747 		}
748 	}
749 
750 	t->gent.generic_ptype = PT_unknown;
751 	t->fsflags = 0;
752 	t->default_fs_type = FS_BSDFFS;
753 }
754 
755 static void
756 gpt_internal_add_ptype(const char *uid, const char *name, const char *desc)
757 {
758 	if (gpt_ptype_cnt >= gpt_ptype_alloc) {
759 		gpt_ptype_alloc = gpt_ptype_alloc ? 2*gpt_ptype_alloc
760 		    : GPT_PTYPE_ALLOC;
761 		struct gpt_ptype_desc *nptypes = realloc(gpt_ptype_descs,
762 		    gpt_ptype_alloc*sizeof(*gpt_ptype_descs));
763 		if (nptypes == 0)
764 			errx(EXIT_FAILURE, "out of memory");
765 		gpt_ptype_descs = nptypes;
766 	}
767 
768 	strlcpy(gpt_ptype_descs[gpt_ptype_cnt].tid, uid,
769 	    sizeof(gpt_ptype_descs[gpt_ptype_cnt].tid));
770 	gpt_ptype_descs[gpt_ptype_cnt].gent.short_desc = strdup(name);
771 	gpt_ptype_descs[gpt_ptype_cnt].gent.description = strdup(desc);
772 	gpt_match_ptype(name, &gpt_ptype_descs[gpt_ptype_cnt]);
773 	gpt_ptype_cnt++;
774 }
775 
776 static void
777 gpt_init_ptypes(void)
778 {
779 	if (gpt_ptype_cnt == 0)
780 		gpt_uuid_query(gpt_internal_add_ptype);
781 }
782 
783 static void
784 gpt_cleanup(void)
785 {
786 	/* free all of gpt_ptype_descs */
787 	for (size_t i = 0; i < gpt_ptype_cnt; i++) {
788 		free(__UNCONST(gpt_ptype_descs[i].gent.short_desc));
789 		free(__UNCONST(gpt_ptype_descs[i].gent.description));
790 	}
791 	free(gpt_ptype_descs);
792 	gpt_ptype_descs = NULL;
793 	gpt_ptype_cnt = gpt_ptype_alloc = 0;
794 }
795 
796 static size_t
797 gpt_type_count(void)
798 {
799 	if (gpt_ptype_cnt == 0)
800 		gpt_init_ptypes();
801 
802 	return gpt_ptype_cnt;
803 }
804 
805 static const struct part_type_desc *
806 gpt_get_ptype(size_t ndx)
807 {
808 	if (gpt_ptype_cnt == 0)
809 		gpt_init_ptypes();
810 
811 	if (ndx >= gpt_ptype_cnt)
812 		return NULL;
813 
814 	return &gpt_ptype_descs[ndx].gent;
815 }
816 
817 static const struct part_type_desc *
818 gpt_get_generic_type(enum part_type gent)
819 {
820 	if (gpt_ptype_cnt == 0)
821 		gpt_init_ptypes();
822 
823 	if (gent == PT_root)
824 		return gpt_native_root;
825 	if (gent == PT_unknown)
826 		return NULL;
827 
828 	for (size_t i = 0; i < gpt_ptype_cnt; i++)
829 		if (gpt_ptype_descs[i].gent.generic_ptype == gent)
830 			return &gpt_ptype_descs[i].gent;
831 
832 	return NULL;
833 }
834 
835 static const struct gpt_ptype_desc *
836 gpt_find_native_type(const struct part_type_desc *gent)
837 {
838 	if (gpt_ptype_cnt == 0)
839 		gpt_init_ptypes();
840 
841 	if (gent == NULL)
842 		return NULL;
843 
844 	for (size_t i = 0; i < gpt_ptype_cnt; i++)
845 		if (gent == &gpt_ptype_descs[i].gent)
846 			return &gpt_ptype_descs[i];
847 
848 	gent = gpt_get_generic_type(gent->generic_ptype);
849 	if (gent == NULL)
850 		return NULL;
851 
852 	/* this can not recurse deeper than once, we would not have found a
853 	 * generic type a few lines above if it would. */
854 	return gpt_find_native_type(gent);
855 }
856 
857 static const struct gpt_ptype_desc *
858 gpt_find_guid_type(const char *uid)
859 {
860 	if (gpt_ptype_cnt == 0)
861 		gpt_init_ptypes();
862 
863 	if (uid == NULL || uid[0] == 0)
864 		return NULL;
865 
866 	for (size_t i = 0; i < gpt_ptype_cnt; i++)
867 		if (strcmp(gpt_ptype_descs[i].tid, uid) == 0)
868 			return &gpt_ptype_descs[i];
869 
870 	return NULL;
871 }
872 
873 static const struct part_type_desc *
874 gpt_find_type(const char *desc)
875 {
876 	if (gpt_ptype_cnt == 0)
877 		gpt_init_ptypes();
878 
879 	if (desc == NULL || desc[0] == 0)
880 		return NULL;
881 
882 	for (size_t i = 0; i < gpt_ptype_cnt; i++)
883 		if (strcmp(gpt_ptype_descs[i].gent.short_desc, desc) == 0)
884 			return &gpt_ptype_descs[i].gent;
885 
886 	return NULL;
887 }
888 
889 static const struct part_type_desc *
890 gpt_get_fs_part_type(enum part_type pt, unsigned fstype, unsigned fs_sub_type)
891 {
892 	size_t i;
893 
894 	/* Try with complete match (including part_type) first */
895 	for (i = 0; i < __arraycount(gpt_fs_types); i++)
896 		if (fstype == gpt_fs_types[i].fstype &&
897 		    pt == gpt_fs_types[i].ptype)
898 			return gpt_find_type(gpt_fs_types[i].name);
899 
900 	/* If that did not work, ignore part_type */
901 	for (i = 0; i < __arraycount(gpt_fs_types); i++)
902 		if (fstype == gpt_fs_types[i].fstype)
903 			return gpt_find_type(gpt_fs_types[i].name);
904 
905 	return NULL;
906 }
907 
908 static bool
909 gpt_get_default_fstype(const struct part_type_desc *nat_type,
910     unsigned *fstype, unsigned *fs_sub_type)
911 {
912 	const struct gpt_ptype_desc *gtype;
913 
914 	gtype = gpt_find_native_type(nat_type);
915 	if (gtype == NULL)
916 		return false;
917 
918 	*fstype = gtype->default_fs_type;
919 #ifdef DEFAULT_UFS2
920 	if (gtype->default_fs_type == FS_BSDFFS)
921 		*fs_sub_type = 2;
922 	else
923 #endif
924 		*fs_sub_type = 0;
925 	return true;
926 }
927 
928 static const struct part_type_desc *
929 gpt_get_uuid_part_type(const uuid_t *id)
930 {
931 	char str[GUID_STR_LEN], desc[GUID_STR_LEN + MENUSTRSIZE];
932 	const struct gpt_ptype_desc *t;
933 	char *guid = NULL;
934 	uint32_t err;
935 
936 	uuid_to_string(id, &guid, &err);
937 	strlcpy(str, err == uuid_s_ok ? guid : "-", sizeof str);
938 	free(guid);
939 
940 	t = gpt_find_guid_type(str);
941 	if (t == NULL) {
942 		snprintf(desc, sizeof desc, "%s (%s)",
943 		    msg_string(MSG_custom_type), str);
944 		gpt_internal_add_ptype(str, str, desc);
945 		t = gpt_find_guid_type(str);
946 		assert(t != NULL);
947 	}
948 	return &t->gent;
949 }
950 
951 static const struct part_type_desc *
952 gpt_create_custom_part_type(const char *custom, const char **err_msg)
953 {
954 	uuid_t id;
955 	uint32_t err;
956 
957 	uuid_from_string(custom, &id, &err);
958 	if (err_msg != NULL &&
959 	   (err == uuid_s_invalid_string_uuid || err == uuid_s_bad_version)) {
960 		*err_msg = MSG_invalid_guid;
961 		return NULL;
962 	}
963 	if (err != uuid_s_ok)
964 		return NULL;
965 
966 	return gpt_get_uuid_part_type(&id);
967 }
968 
969 static const struct part_type_desc *
970 gpt_create_unknown_part_type(void)
971 {
972 	uuid_t id;
973 	uint32_t err;
974 
975 	uuid_create(&id, &err);
976 	if (err != uuid_s_ok)
977 		return NULL;
978 
979 	return gpt_get_uuid_part_type(&id);
980 }
981 
982 static daddr_t
983 gpt_get_part_alignment(const struct disk_partitions *parts)
984 {
985 
986 	assert(parts->disk_size > 0);
987 	if (parts->disk_size < 0)
988 		return 1;
989 
990 	/* Use 1MB offset/alignemnt for large (>128GB) disks */
991 	if (parts->disk_size > HUGE_DISK_SIZE)
992 		return 2048;
993 	else if (parts->disk_size > TINY_DISK_SIZE)
994 		return 64;
995 	else
996 		return 4;
997 }
998 
999 static bool
1000 gpt_can_add_partition(const struct disk_partitions *arg)
1001 {
1002 	const struct gpt_disk_partitions *parts =
1003 	    (const struct gpt_disk_partitions*)arg;
1004 	struct disk_part_free_space space;
1005 	daddr_t align;
1006 
1007 	if (parts->dp.num_part >= parts->max_num_parts)
1008 		return false;
1009 
1010 	align = gpt_get_part_alignment(arg);
1011 	if (parts->dp.free_space <= align)
1012 		return false;
1013 
1014 	if (gpt_get_free_spaces_internal(parts, &space, 1, align, align,
1015 	    0, -1) < 1)
1016 		return false;
1017 
1018 	return true;
1019 }
1020 
1021 static bool
1022 gpt_info_to_part(struct gpt_part_entry *p, const struct disk_part_info *info,
1023     const char **err_msg)
1024 {
1025 	p->gp_type = gpt_find_native_type(info->nat_type);
1026 	p->gp_start = info->start;
1027 	p->gp_size = info->size;
1028 	if (info->last_mounted != NULL && info->last_mounted !=
1029 	    p->last_mounted) {
1030 		free(__UNCONST(p->last_mounted));
1031 		p->last_mounted = strdup(info->last_mounted);
1032 	}
1033 	p->fs_type = info->fs_type;
1034 	p->fs_sub_type = info->fs_sub_type;
1035 
1036 	return true;
1037 }
1038 
1039 static part_id
1040 gpt_add_part(struct disk_partitions *arg,
1041     const struct disk_part_info *info, const char **err_msg)
1042 {
1043 	struct gpt_disk_partitions *parts =
1044 	    (struct gpt_disk_partitions*)arg;
1045 	struct disk_part_free_space space;
1046 	struct disk_part_info data = *info;
1047 	struct gpt_part_entry *p;
1048 	bool ok;
1049 
1050 	if (err_msg != NULL)
1051 		*err_msg = NULL;
1052 
1053 	if (gpt_get_free_spaces_internal(parts, &space, 1, 1, 1,
1054 	    info->start, -1) < 1) {
1055 		if (err_msg)
1056 			*err_msg = msg_string(MSG_No_free_space);
1057 		return NO_PART;
1058 	}
1059 	if (parts->dp.num_part >= parts->max_num_parts) {
1060 		if (err_msg)
1061 			*err_msg = msg_string(MSG_err_too_many_partitions);
1062 		return NO_PART;
1063 	}
1064 
1065 	if (data.size > space.size)
1066 		data.size = space.size;
1067 
1068 	p = calloc(1, sizeof(*p));
1069 	if (p == NULL) {
1070 		if (err_msg != NULL)
1071 			*err_msg = INTERNAL_ERROR;
1072 		return NO_PART;
1073 	}
1074 	if (!gpt_info_to_part(p, &data, err_msg)) {
1075 		free(p);
1076 		return NO_PART;
1077 	}
1078 	p->gp_flags |= GPEF_MODIFIED;
1079 	ok = gpt_insert_part_into_list(parts, &parts->partitions, p, err_msg);
1080 	if (ok) {
1081 		parts->dp.num_part++;
1082 		parts->dp.free_space -= p->gp_size;
1083 		return parts->dp.num_part-1;
1084 	} else {
1085 		free(p);
1086 		return NO_PART;
1087 	}
1088 }
1089 
1090 static bool
1091 gpt_delete_partition(struct disk_partitions *arg, part_id id,
1092     const char **err_msg)
1093 {
1094 	struct gpt_disk_partitions *parts = (struct gpt_disk_partitions*)arg;
1095 	struct gpt_part_entry *p, *last = NULL;
1096 	part_id i;
1097 	bool res;
1098 
1099 	if (parts->dp.num_part == 0)
1100 		return false;
1101 
1102 	for (i = 0, p = parts->partitions;
1103 	    i != id && i < parts->dp.num_part && p != NULL;
1104 	    i++, p = p->gp_next)
1105 		last = p;
1106 
1107 	if (p == NULL) {
1108 		if (err_msg)
1109 			*err_msg = INTERNAL_ERROR;
1110 		return false;
1111 	}
1112 
1113 	if (last == NULL)
1114 		parts->partitions = p->gp_next;
1115 	else
1116 		last->gp_next = p->gp_next;
1117 
1118 	res = true;
1119 	if (p->gp_flags & GPEF_ON_DISK) {
1120 		if (!gpt_insert_part_into_list(parts, &parts->obsolete,
1121 		    p, err_msg))
1122 			res = false;
1123 	} else {
1124 		free(p);
1125 	}
1126 
1127 	if (res) {
1128 		parts->dp.num_part--;
1129 		parts->dp.free_space += p->gp_size;
1130 	}
1131 
1132 	return res;
1133 }
1134 
1135 static bool
1136 gpt_delete_all_partitions(struct disk_partitions *arg)
1137 {
1138 	struct gpt_disk_partitions *parts = (struct gpt_disk_partitions*)arg;
1139 
1140 	while (parts->dp.num_part > 0) {
1141 		if (!gpt_delete_partition(&parts->dp, 0, NULL))
1142 			return false;
1143 	}
1144 
1145 	return true;
1146 }
1147 
1148 static bool
1149 gpt_read_part(const char *disk, daddr_t start, struct gpt_part_entry *p)
1150 {
1151 	char *textbuf, *t, *tt;
1152 	static const char expected_hdr[] = "Details for index ";
1153 
1154 	/* run gpt show for this partition */
1155 	if (collect(T_OUTPUT, &textbuf,
1156 	    "gpt -r show -b %" PRIu64 " %s 2>/dev/null", start, disk) < 1)
1157 		return false;
1158 
1159 	/*
1160 	 * gpt show should respond with single partition details, but will
1161 	 * fall back to "show -a" output if something is wrong
1162 	 */
1163 	t = strtok(textbuf, "\n"); /* first line is special */
1164 	if (strncmp(t, expected_hdr, sizeof(expected_hdr)-1) != 0) {
1165 		free(textbuf);
1166 		return false;
1167 	}
1168 
1169 	/* parse output into "old" */
1170 	while ((t = strtok(NULL, "\n")) != NULL) {
1171 		tt = strsep(&t, " \t");
1172 		if (strlen(tt) == 0)
1173 			continue;
1174 		gpt_add_info(p, tt, t, true);
1175 	}
1176 	free(textbuf);
1177 
1178 	return true;
1179 }
1180 
1181 static bool
1182 gpt_apply_attr(const char *disk, const char *cmd, off_t start, uint todo)
1183 {
1184 	size_t i;
1185 	char attr_str[STRSIZE];
1186 
1187 	if (todo == 0)
1188 		return true;
1189 
1190 	strcpy(attr_str, "-a ");
1191 	for (i = 0; todo != 0; i++) {
1192 		if (!(gpt_avail_attrs[i].flag & todo))
1193 			continue;
1194 		todo &= ~gpt_avail_attrs[i].flag;
1195 		if (attr_str[0])
1196 			strlcat(attr_str, ",",
1197 			    sizeof(attr_str));
1198 		strlcat(attr_str,
1199 		    gpt_avail_attrs[i].name,
1200 		    sizeof(attr_str));
1201 	}
1202 	if (run_program(RUN_SILENT,
1203 	    "gpt %s %s -b %" PRIu64 " %s", cmd, attr_str, start, disk) != 0)
1204 		return false;
1205 	return true;
1206 }
1207 
1208 /*
1209  * Modify an existing on-disk partition.
1210  * Start and size can not be changed here, caller needs to deal
1211  * with that kind of changes upfront.
1212  */
1213 static bool
1214 gpt_modify_part(const char *disk, struct gpt_part_entry *p)
1215 {
1216 	struct gpt_part_entry old;
1217 	uint todo_set, todo_unset;
1218 
1219 	/*
1220 	 * Query current on-disk state
1221 	 */
1222 	memset(&old, 0, sizeof old);
1223 	if (!gpt_read_part(disk, p->gp_start, &old))
1224 		return false;
1225 
1226 	/* Reject unsupported changes */
1227 	if (old.gp_start != p->gp_start || old.gp_size != p->gp_size)
1228 		return false;
1229 
1230 	/*
1231 	 * GUID should never change, but the internal copy
1232 	 * may not yet know it.
1233 	 */
1234 	strcpy(p->gp_id, old.gp_id);
1235 
1236 	/* Check type */
1237 	if (p->gp_type != old.gp_type) {
1238 		if (run_program(RUN_SILENT,
1239 		    "gpt label -b %" PRIu64 " -T %s %s",
1240 		    p->gp_start, p->gp_type->tid, disk) != 0)
1241 			return false;
1242 	}
1243 
1244 	/* Check label */
1245 	if (strcmp(p->gp_label, old.gp_label) != 0) {
1246 		if (run_program(RUN_SILENT,
1247 		    "gpt label -b %" PRIu64 " -l \'%s\' %s",
1248 		    p->gp_start, p->gp_label, disk) != 0)
1249 			return false;
1250 	}
1251 
1252 	/* Check attributes */
1253 	if (p->gp_attr != old.gp_attr) {
1254 		if (p->gp_attr == 0) {
1255 			if (run_program(RUN_SILENT,
1256 			    "gpt set -N -b %" PRIu64 " %s",
1257 			    p->gp_start, disk) != 0)
1258 				return false;
1259 		} else {
1260 			todo_set = (p->gp_attr ^ old.gp_attr) & p->gp_attr;
1261 			todo_unset = (p->gp_attr ^ old.gp_attr) & old.gp_attr;
1262 			if (!gpt_apply_attr(disk, "unset", p->gp_start,
1263 			    todo_unset))
1264 				return false;
1265 			if (!gpt_apply_attr(disk, "set", p->gp_start,
1266 			    todo_set))
1267 				return false;
1268 		}
1269 	}
1270 
1271 	return true;
1272 }
1273 
1274 /*
1275  * verbatim copy from sys/dev/dkwedge/dkwedge_bsdlabel.c:
1276  *  map FS_* to wedge strings
1277  */
1278 static const char *
1279 bsdlabel_fstype_to_str(uint8_t fstype)
1280 {
1281 	const char *str;
1282 
1283 	/*
1284 	 * For each type known to FSTYPE_DEFN (from <sys/disklabel.h>),
1285 	 * a suitable case branch will convert the type number to a string.
1286 	 */
1287 	switch (fstype) {
1288 #define FSTYPE_TO_STR_CASE(tag, number, name, fsck, mount) \
1289 	case __CONCAT(FS_,tag):	str = __CONCAT(DKW_PTYPE_,tag);			break;
1290 	FSTYPE_DEFN(FSTYPE_TO_STR_CASE)
1291 #undef FSTYPE_TO_STR_CASE
1292 	default:		str = NULL;			break;
1293 	}
1294 
1295 	return (str);
1296 }
1297 
1298 static bool
1299 gpt_add_wedge(const char *disk, struct gpt_part_entry *p)
1300 {
1301 	struct dkwedge_info dkw;
1302 	const char *tname;
1303 	char diskpath[MAXPATHLEN];
1304 	int fd;
1305 
1306 	memset(&dkw, 0, sizeof(dkw));
1307 	tname = bsdlabel_fstype_to_str(p->fs_type);
1308 	if (tname)
1309 		strlcpy(dkw.dkw_ptype, tname, sizeof(dkw.dkw_ptype));
1310 
1311 	strlcpy((char*)&dkw.dkw_wname, p->gp_id, sizeof(dkw.dkw_wname));
1312 	dkw.dkw_offset = p->gp_start;
1313 	dkw.dkw_size = p->gp_size;
1314 	if (dkw.dkw_wname[0] == 0) {
1315 		if (p->gp_label[0] != 0)
1316 				strlcpy((char*)&dkw.dkw_wname,
1317 				    p->gp_label, sizeof(dkw.dkw_wname));
1318 	}
1319 	if (dkw.dkw_wname[0] == 0) {
1320 		snprintf((char*)dkw.dkw_wname, sizeof dkw.dkw_wname,
1321 		    "%s_%" PRIi64 "@%" PRIi64, disk, p->gp_size, p->gp_start);
1322 	}
1323 
1324 	fd = opendisk(disk, O_RDWR, diskpath, sizeof(diskpath), 0);
1325 	if (fd < 0)
1326 		return false;
1327 	if (ioctl(fd, DIOCAWEDGE, &dkw) == -1) {
1328 		close(fd);
1329 		return false;
1330 	}
1331 	close(fd);
1332 
1333 	strlcpy(p->gp_dev_name, dkw.dkw_devname, sizeof(p->gp_dev_name));
1334 	p->gp_flags |= GPEF_WEDGE;
1335 	return true;
1336 }
1337 
1338 static void
1339 escape_spaces(char *dest, const char *src)
1340 {
1341 	unsigned char c;
1342 
1343 	while (*src) {
1344 		c = *src++;
1345 		if (isspace(c) || c == '\\')
1346 			*dest++ = '\\';
1347 		*dest++ = c;
1348 	}
1349 	*dest = 0;
1350 }
1351 
1352 static bool
1353 gpt_get_part_device(const struct disk_partitions *arg,
1354     part_id id, char *devname, size_t max_devname_len, int *part,
1355     enum dev_name_usage usage, bool with_path, bool life)
1356 {
1357 	const struct gpt_disk_partitions *parts =
1358 	    (const struct gpt_disk_partitions*)arg;
1359 	struct  gpt_part_entry *p = parts->partitions;
1360 	char tmpname[GPT_LABEL_LEN*2];
1361 	part_id no;
1362 
1363 
1364 	for (no = 0; p != NULL && no < id; no++)
1365 		p = p->gp_next;
1366 
1367 	if (no != id || p == NULL)
1368 		return false;
1369 
1370 	if (part)
1371 		*part = -1;
1372 
1373 	if (usage == logical_name && p->gp_label[0] == 0 && p->gp_id[0] == 0)
1374 		usage = plain_name;
1375 	if (usage == plain_name || usage == raw_dev_name)
1376 		life = true;
1377 	if (!(p->gp_flags & GPEF_WEDGE) && life)
1378 		gpt_add_wedge(arg->disk, p);
1379 
1380 	switch (usage) {
1381 	case logical_name:
1382 		if (p->gp_label[0] != 0) {
1383 			escape_spaces(tmpname, p->gp_label);
1384 			snprintf(devname, max_devname_len,
1385 			    "NAME=%s", tmpname);
1386 		} else {
1387 			snprintf(devname, max_devname_len,
1388 			    "NAME=%s", p->gp_id);
1389 		}
1390 		break;
1391 	case plain_name:
1392 		assert(p->gp_flags & GPEF_WEDGE);
1393 		if (with_path)
1394 			snprintf(devname, max_devname_len, _PATH_DEV "%s",
1395 			    p->gp_dev_name);
1396 		else
1397 			strlcpy(devname, p->gp_dev_name, max_devname_len);
1398 		break;
1399 	case raw_dev_name:
1400 		assert(p->gp_flags & GPEF_WEDGE);
1401 		if (with_path)
1402 			snprintf(devname, max_devname_len, _PATH_DEV "r%s",
1403 			    p->gp_dev_name);
1404 		else
1405 			snprintf(devname, max_devname_len, "r%s",
1406 			    p->gp_dev_name);
1407 		break;
1408 	default:
1409 		return false;
1410 	}
1411 
1412 	return true;
1413 }
1414 
1415 static bool
1416 gpt_write_to_disk(struct disk_partitions *arg)
1417 {
1418 	struct gpt_disk_partitions *parts = (struct gpt_disk_partitions*)arg;
1419 	struct gpt_part_entry *p, *n;
1420 	char label_arg[sizeof(p->gp_label) + 10];
1421 	char diskpath[MAXPATHLEN];
1422 	int fd, bits = 0;
1423 	bool root_is_new = false, efi_is_new = false;
1424 	part_id root_id = NO_PART, efi_id = NO_PART, pno;
1425 
1426 	/*
1427 	 * Remove all wedges on this disk - they may become invalid and we
1428 	 * have no easy way to associate them with the partitioning data.
1429 	 * Instead we will explicitly request creation of wedges on demand
1430 	 * later.
1431 	 */
1432 	fd = opendisk(arg->disk, O_RDWR, diskpath, sizeof(diskpath), 0);
1433 	if (fd < 0)
1434 		return false;
1435 	if (ioctl(fd, DIOCRMWEDGES, &bits) == -1)
1436 		return false;
1437 	close(fd);
1438 
1439 	/*
1440 	 * Collect first root and efi partition (if available), clear
1441 	 * "have wedge" flags.
1442 	 */
1443 	for (pno = 0, p = parts->partitions; p != NULL; p = p->gp_next, pno++) {
1444 		p->gp_flags &= ~GPEF_WEDGE;
1445 		if (root_id == NO_PART && p->gp_type != NULL) {
1446 			if (p->gp_type->gent.generic_ptype == PT_root &&
1447 			    p->gp_start == pm->ptstart) {
1448 				root_id = pno;
1449 				root_is_new = !(p->gp_flags & GPEF_ON_DISK);
1450 			} else if (efi_id == NO_PART &&
1451 			    p->gp_type->gent.generic_ptype == PT_EFI_SYSTEM) {
1452 				efi_id = pno;
1453 				efi_is_new = !(p->gp_flags & GPEF_ON_DISK);
1454 			}
1455 		}
1456 	}
1457 
1458 	/*
1459 	 * If no GPT on disk yet, create it.
1460 	 */
1461 	if (!parts->has_gpt) {
1462 		char limit[30];
1463 
1464 		if (parts->max_num_parts > 0)
1465 			sprintf(limit, "-p %zu", parts->max_num_parts);
1466 		else
1467 			limit[0] = 0;
1468 		if (run_program(RUN_SILENT, "gpt create %s %s",
1469 		    limit, parts->dp.disk))
1470 			return false;
1471 		parts->has_gpt = true;
1472 	}
1473 
1474 	/*
1475 	 * Delete all old partitions
1476 	 */
1477 	for (p = parts->obsolete; p != NULL; p = n) {
1478 		run_program(RUN_SILENT, "gpt -n remove -b %" PRIu64 " %s",
1479 		    p->gp_start, arg->disk);
1480 		n = p->gp_next;
1481 		free(p);
1482 	}
1483 	parts->obsolete = NULL;
1484 
1485 	/*
1486 	 * Modify existing but changed partitions
1487 	 */
1488 	for (p = parts->partitions; p != NULL; p = p->gp_next) {
1489 		if (!(p->gp_flags & GPEF_ON_DISK))
1490 			continue;
1491 
1492 		if (p->gp_flags & GPEF_RESIZED) {
1493 			run_program(RUN_SILENT,
1494 			    "gpt -n resize -b %" PRIu64 " -s %" PRIu64 "s %s",
1495 			    p->gp_start, p->gp_size, arg->disk);
1496 			p->gp_flags &= ~GPEF_RESIZED;
1497 		}
1498 
1499 		if (!(p->gp_flags & GPEF_MODIFIED))
1500 			continue;
1501 
1502 		if (!gpt_modify_part(parts->dp.disk, p))
1503 			return false;
1504 	}
1505 
1506 	/*
1507 	 * Add new partitions
1508 	 */
1509 	for (p = parts->partitions; p != NULL; p = p->gp_next) {
1510 		if (p->gp_flags & GPEF_ON_DISK)
1511 			continue;
1512 		if (!(p->gp_flags & GPEF_MODIFIED))
1513 			continue;
1514 
1515 		if (p->gp_label[0] == 0)
1516 			label_arg[0] = 0;
1517 		else
1518 			sprintf(label_arg, "-l \'%s\'", p->gp_label);
1519 
1520 		if (p->gp_type != NULL)
1521 			run_program(RUN_SILENT,
1522 			    "gpt -n add -b %" PRIu64 " -s %" PRIu64
1523 			    "s -t %s %s %s",
1524 			    p->gp_start, p->gp_size, p->gp_type->tid,
1525 			    label_arg, arg->disk);
1526 		else
1527 			run_program(RUN_SILENT,
1528 			    "gpt -n add -b %" PRIu64 " -s %" PRIu64
1529 			    "s %s %s",
1530 			    p->gp_start, p->gp_size, label_arg, arg->disk);
1531 		gpt_apply_attr(arg->disk, "set", p->gp_start, p->gp_attr);
1532 		gpt_read_part(arg->disk, p->gp_start, p);
1533 		p->gp_flags |= GPEF_ON_DISK;
1534 	}
1535 
1536 	/*
1537 	 * Additional MD bootloader magic...
1538 	 */
1539 	if (!md_gpt_post_write(&parts->dp, root_id, root_is_new, efi_id,
1540 	    efi_is_new))
1541 		return false;
1542 
1543 	return true;
1544 }
1545 
1546 static part_id
1547 gpt_find_by_name(struct disk_partitions *arg, const char *name)
1548 {
1549 	struct gpt_disk_partitions *parts = (struct gpt_disk_partitions*)arg;
1550 	struct gpt_part_entry *p;
1551 	part_id pno;
1552 
1553 	for (pno = 0, p = parts->partitions; p != NULL;
1554 	    p = p->gp_next, pno++) {
1555 		if (strcmp(p->gp_label, name) == 0)
1556 			return pno;
1557 		if (strcmp(p->gp_id, name) == 0)
1558 			return pno;
1559 	}
1560 
1561 	return NO_PART;
1562 }
1563 
1564 bool
1565 gpt_parts_check(void)
1566 {
1567 
1568 	check_available_binaries();
1569 
1570 	return have_gpt && have_dk;
1571 }
1572 
1573 static void
1574 gpt_free(struct disk_partitions *arg)
1575 {
1576 	struct gpt_disk_partitions *parts = (struct gpt_disk_partitions*)arg;
1577 	struct gpt_part_entry *p, *n;
1578 
1579 	assert(parts != NULL);
1580 	for (p = parts->partitions; p != NULL; p = n) {
1581 		free(__UNCONST(p->last_mounted));
1582 		n = p->gp_next;
1583 		free(p);
1584 	}
1585 	free(__UNCONST(parts->dp.disk));
1586 	free(parts);
1587 }
1588 
1589 static bool
1590 gpt_custom_attribute_writable(const struct disk_partitions *arg,
1591     part_id ptn, size_t attr_no)
1592 {
1593 	const struct gpt_disk_partitions *parts =
1594 	    (const struct gpt_disk_partitions*)arg;
1595 	size_t i;
1596 	struct gpt_part_entry *p;
1597 
1598 	if (attr_no >= arg->pscheme->custom_attribute_count)
1599 		return false;
1600 
1601 	const msg label = arg->pscheme->custom_attributes[attr_no].label;
1602 
1603 	/* we can not edit the uuid attribute */
1604 	if (label == MSG_ptn_uuid)
1605 		return false;
1606 
1607 	/* the label is always editable */
1608 	if (label == MSG_ptn_label)
1609 		return true;
1610 
1611 	/* the GPT type is read only */
1612 	if (label == MSG_ptn_gpt_type)
1613 		return false;
1614 
1615 	/* BOOTME makes no sense on swap partitions */
1616 	for (i = 0, p = parts->partitions; p != NULL; i++, p = p->gp_next)
1617 		if (i == ptn)
1618 			break;
1619 
1620 	if (p == NULL)
1621 		return false;
1622 
1623 	if (p->fs_type == FS_SWAP ||
1624 	    (p->gp_type != NULL && p->gp_type->gent.generic_ptype == PT_swap))
1625 		return false;
1626 
1627 	return true;
1628 }
1629 
1630 static const char *
1631 gpt_get_label_str(const struct disk_partitions *arg, part_id ptn)
1632 {
1633 	const struct gpt_disk_partitions *parts =
1634 	    (const struct gpt_disk_partitions*)arg;
1635 	size_t i;
1636 	struct gpt_part_entry *p;
1637 
1638 	for (i = 0, p = parts->partitions; p != NULL; i++, p = p->gp_next)
1639 		if (i == ptn)
1640 			break;
1641 
1642 	if (p == NULL)
1643 		return NULL;
1644 
1645 	if (p->gp_label[0] != 0)
1646 		return p->gp_label;
1647 	return p->gp_id;
1648 }
1649 
1650 static bool
1651 gpt_format_custom_attribute(const struct disk_partitions *arg,
1652     part_id ptn, size_t attr_no, const struct disk_part_info *info,
1653     char *out, size_t out_space)
1654 {
1655 	const struct gpt_disk_partitions *parts =
1656 	    (const struct gpt_disk_partitions*)arg;
1657 	size_t i;
1658 	struct gpt_part_entry *p, data;
1659 
1660 	for (i = 0, p = parts->partitions; p != NULL; i++, p = p->gp_next)
1661 		if (i == ptn)
1662 			break;
1663 
1664 	if (p == NULL)
1665 		return false;
1666 
1667 	if (attr_no >= parts->dp.pscheme->custom_attribute_count)
1668 		return false;
1669 
1670 	const msg label = parts->dp.pscheme->custom_attributes[attr_no].label;
1671 
1672 	if (info != NULL) {
1673 		data = *p;
1674 		gpt_info_to_part(&data, info, NULL);
1675 		p = &data;
1676 	}
1677 
1678 	if (label == MSG_ptn_label)
1679 		strlcpy(out, p->gp_label, out_space);
1680 	else if (label == MSG_ptn_uuid)
1681 		strlcpy(out, p->gp_id, out_space);
1682 	else if (label == MSG_ptn_gpt_type) {
1683 		if (p->gp_type != NULL)
1684 			strlcpy(out, p->gp_type->gent.description, out_space);
1685 		else if (out_space > 1)
1686 			out[0] = 0;
1687 	} else if (label == MSG_ptn_boot)
1688 		strlcpy(out, msg_string(p->gp_attr & GPT_ATTR_BOOT ?
1689 		    MSG_Yes : MSG_No), out_space);
1690 	else
1691 		return false;
1692 
1693 	return true;
1694 }
1695 
1696 static bool
1697 gpt_custom_attribute_toggle(struct disk_partitions *arg,
1698     part_id ptn, size_t attr_no)
1699 {
1700 	const struct gpt_disk_partitions *parts =
1701 	    (const struct gpt_disk_partitions*)arg;
1702 	size_t i;
1703 	struct gpt_part_entry *p;
1704 
1705 	for (i = 0, p = parts->partitions; p != NULL; i++, p = p->gp_next)
1706 		if (i == ptn)
1707 			break;
1708 
1709 	if (p == NULL)
1710 		return false;
1711 
1712 	if (attr_no >= parts->dp.pscheme->custom_attribute_count)
1713 		return false;
1714 
1715 	const msg label = parts->dp.pscheme->custom_attributes[attr_no].label;
1716 	if (label != MSG_ptn_boot)
1717 		return false;
1718 
1719 	if (p->gp_attr & GPT_ATTR_BOOT) {
1720 		p->gp_attr &= ~GPT_ATTR_BOOT;
1721 	} else {
1722 		for (i = 0, p = parts->partitions; p != NULL;
1723 		    i++, p = p->gp_next)
1724 			if (i == ptn)
1725 				p->gp_attr |= GPT_ATTR_BOOT;
1726 			else
1727 				p->gp_attr &= ~GPT_ATTR_BOOT;
1728 	}
1729 	return true;
1730 }
1731 
1732 static bool
1733 gpt_custom_attribute_set_str(struct disk_partitions *arg,
1734     part_id ptn, size_t attr_no, const char *new_val)
1735 {
1736 	const struct gpt_disk_partitions *parts =
1737 	    (const struct gpt_disk_partitions*)arg;
1738 	size_t i;
1739 	struct gpt_part_entry *p;
1740 
1741 	for (i = 0, p = parts->partitions; p != NULL; i++, p = p->gp_next)
1742 		if (i == ptn)
1743 			break;
1744 
1745 	if (p == NULL)
1746 		return false;
1747 
1748 	if (attr_no >= parts->dp.pscheme->custom_attribute_count)
1749 		return false;
1750 
1751 	const msg label = parts->dp.pscheme->custom_attributes[attr_no].label;
1752 
1753 	if (label != MSG_ptn_label)
1754 		return false;
1755 
1756 	strlcpy(p->gp_label, new_val, sizeof(p->gp_label));
1757 	return true;
1758 }
1759 
1760 static bool
1761 gpt_have_boot_support(const char *disk)
1762 {
1763 #ifdef	HAVE_GPT_BOOT
1764 	return true;
1765 #else
1766 	return false;
1767 #endif
1768 }
1769 
1770 const struct disk_part_custom_attribute gpt_custom_attrs[] = {
1771 	{ .label = MSG_ptn_label,	.type = pet_str },
1772 	{ .label = MSG_ptn_uuid,	.type = pet_str },
1773 	{ .label = MSG_ptn_gpt_type,	.type = pet_str },
1774 	{ .label = MSG_ptn_boot,	.type = pet_bool },
1775 };
1776 
1777 const struct disk_partitioning_scheme
1778 gpt_parts = {
1779 	.name = MSG_parttype_gpt,
1780 	.short_name = MSG_parttype_gpt_short,
1781 	.part_flag_desc = MSG_gpt_flag_desc,
1782 	.custom_attribute_count = __arraycount(gpt_custom_attrs),
1783 	.custom_attributes = gpt_custom_attrs,
1784 	.get_part_types_count = gpt_type_count,
1785 	.get_part_type = gpt_get_ptype,
1786 	.get_generic_part_type = gpt_get_generic_type,
1787 	.get_fs_part_type = gpt_get_fs_part_type,
1788 	.get_default_fstype = gpt_get_default_fstype,
1789 	.create_custom_part_type = gpt_create_custom_part_type,
1790 	.create_unknown_part_type = gpt_create_unknown_part_type,
1791 	.get_part_alignment = gpt_get_part_alignment,
1792 	.read_from_disk = gpt_read_from_disk,
1793 	.get_cylinder_size = gpt_cyl_size,
1794 	.create_new_for_disk = gpt_create_new,
1795 	.have_boot_support = gpt_have_boot_support,
1796 	.find_by_name = gpt_find_by_name,
1797 	.can_add_partition = gpt_can_add_partition,
1798 	.custom_attribute_writable = gpt_custom_attribute_writable,
1799 	.format_custom_attribute = gpt_format_custom_attribute,
1800 	.custom_attribute_toggle = gpt_custom_attribute_toggle,
1801 	.custom_attribute_set_str = gpt_custom_attribute_set_str,
1802 	.other_partition_identifier = gpt_get_label_str,
1803 	.get_part_device = gpt_get_part_device,
1804 	.max_free_space_at = gpt_max_free_space_at,
1805 	.get_free_spaces = gpt_get_free_spaces,
1806 	.adapt_foreign_part_info = generic_adapt_foreign_part_info,
1807 	.get_part_info = gpt_get_part_info,
1808 	.get_part_attr_str = gpt_get_part_attr_str,
1809 	.set_part_info = gpt_set_part_info,
1810 	.add_partition = gpt_add_part,
1811 	.delete_all_partitions = gpt_delete_all_partitions,
1812 	.delete_partition = gpt_delete_partition,
1813 	.write_to_disk = gpt_write_to_disk,
1814 	.free = gpt_free,
1815 	.cleanup = gpt_cleanup,
1816 };
1817