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