Home | History | Annotate | Line # | Download | only in sysinst
gpt.c revision 1.13
      1 /*	$NetBSD: gpt.c,v 1.13 2019/12/13 22:12:41 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_unknown },
    111 	{ .name = "cgd",	.fstype = FS_CGD,	.ptype = PT_unknown },
    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 struct disk_partitions *
    443 gpt_create_new(const char *disk, daddr_t start, daddr_t len, daddr_t total,
    444     bool is_boot_drive)
    445 {
    446 	struct gpt_disk_partitions *parts;
    447 
    448 	if (start != 0) {
    449 		assert(0);
    450 		return NULL;
    451 	}
    452 
    453 	parts = calloc(1, sizeof(*parts));
    454 	if (!parts)
    455 		return NULL;
    456 
    457 	parts->dp.pscheme = &gpt_parts;
    458 	parts->dp.disk = strdup(disk);
    459 
    460 	gpt_md_init(is_boot_drive, &parts->max_num_parts, &parts->prologue,
    461 	    &parts->epilogue);
    462 
    463 	parts->dp.disk_start = start;
    464 	parts->dp.disk_size = len;
    465 	parts->dp.free_space = len - start - parts->prologue - parts->epilogue;
    466 	parts->has_gpt = false;
    467 
    468 	return &parts->dp;
    469 }
    470 
    471 static bool
    472 gpt_get_part_info(const struct disk_partitions *arg, part_id id,
    473     struct disk_part_info *info)
    474 {
    475 	static const struct part_type_desc gpt_unknown_type =
    476 		{ .generic_ptype = PT_undef,
    477 		  .short_desc = "<unknown>" };
    478 	const struct gpt_disk_partitions *parts =
    479 	    (const struct gpt_disk_partitions*)arg;
    480 	const struct gpt_part_entry *p = parts->partitions;
    481 	part_id no;
    482 
    483 	for (no = 0; p != NULL && no < id; no++)
    484 		p = p->gp_next;
    485 
    486 	if (no != id || p == NULL)
    487 		return false;
    488 
    489 	memset(info, 0, sizeof(*info));
    490 	info->start = p->gp_start;
    491 	info->size = p->gp_size;
    492 	if (p->gp_type)
    493 		info->nat_type = &p->gp_type->gent;
    494 	else
    495 		info->nat_type = &gpt_unknown_type;
    496 	info->last_mounted = p->last_mounted;
    497 	info->fs_type = p->fs_type;
    498 	info->fs_sub_type = p->fs_sub_type;
    499 
    500 	return true;
    501 }
    502 
    503 static bool
    504 gpt_get_part_attr_str(const struct disk_partitions *arg, part_id id,
    505     char *str, size_t avail_space)
    506 {
    507 	const struct gpt_disk_partitions *parts =
    508 	    (const struct gpt_disk_partitions*)arg;
    509 	const struct gpt_part_entry *p = parts->partitions;
    510 	part_id no;
    511 	static const char *flags = NULL;
    512 
    513 	for (no = 0; p != NULL && no < id; no++)
    514 		p = p->gp_next;
    515 
    516 	if (no != id || p == NULL)
    517 		return false;
    518 
    519 	if (flags == NULL)
    520 		flags = msg_string(MSG_gpt_flags);
    521 
    522 	if (avail_space < 2)
    523 		return false;
    524 
    525 	if (p->gp_attr & GPT_ATTR_BOOT)
    526 		*str++ = flags[0];
    527 	*str = 0;
    528 
    529 	return true;
    530 }
    531 
    532 /*
    533  * Find insert position and check for duplicates.
    534  * If all goes well, insert the new "entry" in the "list".
    535  * If there are collisions, report "no free space".
    536  * We keep all lists sorted by start sector number,
    537  */
    538 static bool
    539 gpt_insert_part_into_list(struct gpt_disk_partitions *parts,
    540     struct gpt_part_entry **list,
    541     struct gpt_part_entry *entry, const char **err_msg)
    542 {
    543 	struct gpt_part_entry *p, *last;
    544 
    545 	/* find the first entry past the new one (if any) */
    546 	for (last = NULL, p = *list; p != NULL; last = p, p = p->gp_next) {
    547 		if (p->gp_start > entry->gp_start)
    548 			break;
    549 	}
    550 
    551 	/* check if last partition overlaps with new one */
    552 	if (last) {
    553 		if (last->gp_start + last->gp_size > entry->gp_start) {
    554 			if (err_msg)
    555 				*err_msg = msg_string(MSG_No_free_space);
    556 			return false;
    557 		}
    558 	}
    559 
    560 	if (p == NULL) {
    561 		entry->gp_next = NULL;
    562 		if (last != NULL) {
    563 			last->gp_next = entry;
    564 		}
    565 	} else {
    566 		/* check if new entry overlaps with next */
    567 		if (entry->gp_start + entry->gp_size > p->gp_start) {
    568 			if (err_msg)
    569 				*err_msg = msg_string(MSG_No_free_space);
    570 			return false;
    571 		}
    572 
    573 		entry->gp_next = p;
    574 		if (last != NULL)
    575 			last->gp_next = entry;
    576 		else
    577 			*list = entry;
    578 	}
    579 	if (*list == NULL)
    580 		*list = entry;
    581 
    582 	return true;
    583 }
    584 
    585 static bool
    586 gpt_set_part_info(struct disk_partitions *arg, part_id id,
    587     const struct disk_part_info *info, const char **err_msg)
    588 {
    589 	struct gpt_disk_partitions *parts =
    590 	    (struct gpt_disk_partitions*)arg;
    591 	struct gpt_part_entry *p = parts->partitions, *n;
    592 	part_id no;
    593 	daddr_t lendiff;
    594 
    595 	for (no = 0; p != NULL && no < id; no++)
    596 		p = p->gp_next;
    597 
    598 	if (no != id || p == NULL)
    599 		return false;
    600 
    601 	if ((p->gp_flags & GPEF_ON_DISK)) {
    602 		if (info->start != p->gp_start) {
    603 			/* partition moved, we need to delete and re-add */
    604 			n = calloc(1, sizeof(*n));
    605 			if (n == NULL) {
    606 				if (err_msg)
    607 					*err_msg = err_outofmem;
    608 				return false;
    609 			}
    610 			*n = *p;
    611 			p->gp_flags &= ~GPEF_ON_DISK;
    612 			if (!gpt_insert_part_into_list(parts, &parts->obsolete,
    613 			    n, err_msg))
    614 				return false;
    615 		} else if (info->size != p->gp_size) {
    616 			p->gp_flags |= GPEF_RESIZED;
    617 		}
    618 	}
    619 
    620 	p->gp_flags |= GPEF_MODIFIED;
    621 
    622 	lendiff = info->size - p->gp_size;
    623 	parts->dp.free_space -= lendiff;
    624 	return gpt_info_to_part(p, info, err_msg);
    625 }
    626 
    627 static size_t
    628 gpt_get_free_spaces_internal(const struct gpt_disk_partitions *parts,
    629     struct disk_part_free_space *result, size_t max_num_result,
    630     daddr_t min_space_size, daddr_t align, daddr_t start, daddr_t ignore)
    631 {
    632 	size_t cnt = 0;
    633 	daddr_t s, e, from, size, end_of_disk;
    634 	struct gpt_part_entry *p;
    635 
    636 	if (align > 1)
    637 		start = max(roundup(start, align), align);
    638 	if (start < 0 || start < (daddr_t)parts->prologue)
    639 		start = parts->prologue;
    640 	if (parts->dp.disk_start != 0 && parts->dp.disk_start > start)
    641 		start = parts->dp.disk_start;
    642 	if (min_space_size < 1)
    643 		min_space_size = 1;
    644 	end_of_disk = parts->dp.disk_start + parts->dp.disk_size
    645 	    - parts->epilogue;
    646 	from = start;
    647 	while (from < end_of_disk && cnt < max_num_result) {
    648 again:
    649 		size = parts->dp.disk_start + parts->dp.disk_size - from;
    650 		start = from;
    651 		if (start + size > end_of_disk)
    652 			size = end_of_disk - start;
    653 		for (p = parts->partitions; p != NULL; p = p->gp_next) {
    654 			s = p->gp_start;
    655 			e = p->gp_size + s;
    656 			if (s == ignore)
    657 				continue;
    658 			if (e < from)
    659 				continue;
    660 			if (s <= from && e > from) {
    661 				if (e - 1 >= end_of_disk)
    662 					return cnt;
    663 				from = e + 1;
    664 				if (align > 1) {
    665 					from = max(roundup(from, align), align);
    666 					if (from >= end_of_disk) {
    667 						size = 0;
    668 						break;
    669 					}
    670 				}
    671 				goto again;
    672 			}
    673 			if (s > from && s - from < size) {
    674 				size = s - from;
    675 			}
    676 		}
    677 		if (size >= min_space_size) {
    678 			result->start = start;
    679 			result->size = size;
    680 			result++;
    681 			cnt++;
    682 		}
    683 		from += size + 1;
    684 		if (align > 1)
    685 			from = max(roundup(from, align), align);
    686 	}
    687 
    688 	return cnt;
    689 }
    690 
    691 static daddr_t
    692 gpt_max_free_space_at(const struct disk_partitions *arg, daddr_t start)
    693 {
    694 	const struct gpt_disk_partitions *parts =
    695 	    (const struct gpt_disk_partitions*)arg;
    696 	struct disk_part_free_space space;
    697 
    698 	if (gpt_get_free_spaces_internal(parts, &space, 1, 1, 0,
    699 	    start, start) == 1)
    700 		return space.size;
    701 
    702 	return 0;
    703 }
    704 
    705 static size_t
    706 gpt_get_free_spaces(const struct disk_partitions *arg,
    707     struct disk_part_free_space *result, size_t max_num_result,
    708     daddr_t min_space_size, daddr_t align, daddr_t start,
    709     daddr_t ignore)
    710 {
    711 	const struct gpt_disk_partitions *parts =
    712 	    (const struct gpt_disk_partitions*)arg;
    713 
    714 	return gpt_get_free_spaces_internal(parts, result,
    715 	    max_num_result, min_space_size, align, start, ignore);
    716 }
    717 
    718 static void
    719 gpt_match_ptype(const char *name, struct gpt_ptype_desc *t)
    720 {
    721 	size_t i;
    722 
    723 	for (i = 0; i < __arraycount(gpt_fs_types); i++) {
    724 		if (strcmp(name, gpt_fs_types[i].name) == 0) {
    725 			t->gent.generic_ptype = gpt_fs_types[i].ptype;
    726 			t->fsflags = gpt_fs_types[i].fsflags;
    727 			t->default_fs_type = gpt_fs_types[i].fstype;
    728 
    729 			/* recongnize special entries */
    730 			if (gpt_native_root == NULL && i == 0)
    731 				gpt_native_root = &t->gent;
    732 
    733 			return;
    734 		}
    735 	}
    736 
    737 	t->gent.generic_ptype = PT_unknown;
    738 	t->fsflags = 0;
    739 	t->default_fs_type = FS_BSDFFS;
    740 }
    741 
    742 static void
    743 gpt_internal_add_ptype(const char *uid, const char *name, const char *desc)
    744 {
    745 	if (gpt_ptype_cnt >= gpt_ptype_alloc) {
    746 		gpt_ptype_alloc = gpt_ptype_alloc ? 2*gpt_ptype_alloc
    747 		    : GPT_PTYPE_ALLOC;
    748 		struct gpt_ptype_desc *nptypes = realloc(gpt_ptype_descs,
    749 		    gpt_ptype_alloc*sizeof(*gpt_ptype_descs));
    750 		if (nptypes == 0)
    751 			errx(EXIT_FAILURE, "out of memory");
    752 		gpt_ptype_descs = nptypes;
    753 	}
    754 
    755 	strlcpy(gpt_ptype_descs[gpt_ptype_cnt].tid, uid,
    756 	    sizeof(gpt_ptype_descs[gpt_ptype_cnt].tid));
    757 	gpt_ptype_descs[gpt_ptype_cnt].gent.short_desc = strdup(name);
    758 	gpt_ptype_descs[gpt_ptype_cnt].gent.description = strdup(desc);
    759 	gpt_match_ptype(name, &gpt_ptype_descs[gpt_ptype_cnt]);
    760 	gpt_ptype_cnt++;
    761 }
    762 
    763 static void
    764 gpt_init_ptypes(void)
    765 {
    766 	if (gpt_ptype_cnt == 0)
    767 		gpt_uuid_query(gpt_internal_add_ptype);
    768 }
    769 
    770 static void
    771 gpt_cleanup(void)
    772 {
    773 	/* free all of gpt_ptype_descs */
    774 	for (size_t i = 0; i < gpt_ptype_cnt; i++) {
    775 		free(__UNCONST(gpt_ptype_descs[i].gent.short_desc));
    776 		free(__UNCONST(gpt_ptype_descs[i].gent.description));
    777 	}
    778 	free(gpt_ptype_descs);
    779 	gpt_ptype_descs = NULL;
    780 	gpt_ptype_cnt = gpt_ptype_alloc = 0;
    781 }
    782 
    783 static size_t
    784 gpt_type_count(void)
    785 {
    786 	if (gpt_ptype_cnt == 0)
    787 		gpt_init_ptypes();
    788 
    789 	return gpt_ptype_cnt;
    790 }
    791 
    792 static const struct part_type_desc *
    793 gpt_get_ptype(size_t ndx)
    794 {
    795 	if (gpt_ptype_cnt == 0)
    796 		gpt_init_ptypes();
    797 
    798 	if (ndx >= gpt_ptype_cnt)
    799 		return NULL;
    800 
    801 	return &gpt_ptype_descs[ndx].gent;
    802 }
    803 
    804 static const struct part_type_desc *
    805 gpt_get_generic_type(enum part_type gent)
    806 {
    807 	if (gpt_ptype_cnt == 0)
    808 		gpt_init_ptypes();
    809 
    810 	if (gent == PT_root)
    811 		return gpt_native_root;
    812 	if (gent == PT_unknown)
    813 		return NULL;
    814 
    815 	for (size_t i = 0; i < gpt_ptype_cnt; i++)
    816 		if (gpt_ptype_descs[i].gent.generic_ptype == gent)
    817 			return &gpt_ptype_descs[i].gent;
    818 
    819 	return NULL;
    820 }
    821 
    822 static const struct gpt_ptype_desc *
    823 gpt_find_native_type(const struct part_type_desc *gent)
    824 {
    825 	if (gpt_ptype_cnt == 0)
    826 		gpt_init_ptypes();
    827 
    828 	if (gent == NULL)
    829 		return NULL;
    830 
    831 	for (size_t i = 0; i < gpt_ptype_cnt; i++)
    832 		if (gent == &gpt_ptype_descs[i].gent)
    833 			return &gpt_ptype_descs[i];
    834 
    835 	gent = gpt_get_generic_type(gent->generic_ptype);
    836 	if (gent == NULL)
    837 		return NULL;
    838 
    839 	/* this can not recurse deeper than once, we would not have found a
    840 	 * generic type a few lines above if it would. */
    841 	return gpt_find_native_type(gent);
    842 }
    843 
    844 static const struct gpt_ptype_desc *
    845 gpt_find_guid_type(const char *uid)
    846 {
    847 	if (gpt_ptype_cnt == 0)
    848 		gpt_init_ptypes();
    849 
    850 	if (uid == NULL || uid[0] == 0)
    851 		return NULL;
    852 
    853 	for (size_t i = 0; i < gpt_ptype_cnt; i++)
    854 		if (strcmp(gpt_ptype_descs[i].tid, uid) == 0)
    855 			return &gpt_ptype_descs[i];
    856 
    857 	return NULL;
    858 }
    859 
    860 static const struct part_type_desc *
    861 gpt_find_type(const char *desc)
    862 {
    863 	if (gpt_ptype_cnt == 0)
    864 		gpt_init_ptypes();
    865 
    866 	if (desc == NULL || desc[0] == 0)
    867 		return NULL;
    868 
    869 	for (size_t i = 0; i < gpt_ptype_cnt; i++)
    870 		if (strcmp(gpt_ptype_descs[i].gent.short_desc, desc) == 0)
    871 			return &gpt_ptype_descs[i].gent;
    872 
    873 	return NULL;
    874 }
    875 
    876 static const struct part_type_desc *
    877 gpt_get_fs_part_type(enum part_type pt, unsigned fstype, unsigned fs_sub_type)
    878 {
    879 	size_t i;
    880 
    881 	/* Try with complet match (including part_type) first */
    882 	for (i = 0; i < __arraycount(gpt_fs_types); i++)
    883 		if (fstype == gpt_fs_types[i].fstype &&
    884 		    pt == gpt_fs_types[i].ptype)
    885 			return gpt_find_type(gpt_fs_types[i].name);
    886 
    887 	/* If that did not work, ignore part_type */
    888 	for (i = 0; i < __arraycount(gpt_fs_types); i++)
    889 		if (fstype == gpt_fs_types[i].fstype)
    890 			return gpt_find_type(gpt_fs_types[i].name);
    891 
    892 	return NULL;
    893 }
    894 
    895 static const struct part_type_desc *
    896 gpt_get_uuid_part_type(const uuid_t *id)
    897 {
    898 	char str[GUID_STR_LEN], desc[GUID_STR_LEN + MENUSTRSIZE];
    899 	const struct gpt_ptype_desc *t;
    900 	char *guid = NULL;
    901 	uint32_t err;
    902 
    903 	uuid_to_string(id, &guid, &err);
    904 	strlcpy(str, err == uuid_s_ok ? guid : "-", sizeof str);
    905 	free(guid);
    906 
    907 	t = gpt_find_guid_type(str);
    908 	if (t == NULL) {
    909 		snprintf(desc, sizeof desc, "%s (%s)",
    910 		    msg_string(MSG_custom_type), str);
    911 		gpt_internal_add_ptype(str, str, desc);
    912 		t = gpt_find_guid_type(str);
    913 		assert(t != NULL);
    914 	}
    915 	return &t->gent;
    916 }
    917 
    918 static const struct part_type_desc *
    919 gpt_create_custom_part_type(const char *custom, const char **err_msg)
    920 {
    921 	uuid_t id;
    922 	uint32_t err;
    923 
    924 	uuid_from_string(custom, &id, &err);
    925 	if (err_msg != NULL &&
    926 	   (err == uuid_s_invalid_string_uuid || err == uuid_s_bad_version)) {
    927 		*err_msg = MSG_invalid_guid;
    928 		return NULL;
    929 	}
    930 	if (err != uuid_s_ok)
    931 		return NULL;
    932 
    933 	return gpt_get_uuid_part_type(&id);
    934 }
    935 
    936 static const struct part_type_desc *
    937 gpt_create_unknown_part_type(void)
    938 {
    939 	uuid_t id;
    940 	uint32_t err;
    941 
    942 	uuid_create(&id, &err);
    943 	if (err != uuid_s_ok)
    944 		return NULL;
    945 
    946 	return gpt_get_uuid_part_type(&id);
    947 }
    948 
    949 static daddr_t
    950 gpt_get_part_alignment(const struct disk_partitions *parts)
    951 {
    952 
    953 	assert(parts->disk_size > 0);
    954 	if (parts->disk_size < 0)
    955 		return 1;
    956 
    957 	/* Use 1MB offset/alignemnt for large (>128GB) disks */
    958 	if (parts->disk_size > HUGE_DISK_SIZE)
    959 		return 2048;
    960 	else if (parts->disk_size > TINY_DISK_SIZE)
    961 		return 64;
    962 	else
    963 		return 4;
    964 }
    965 
    966 static bool
    967 gpt_can_add_partition(const struct disk_partitions *arg)
    968 {
    969 	const struct gpt_disk_partitions *parts =
    970 	    (const struct gpt_disk_partitions*)arg;
    971 	struct disk_part_free_space space;
    972 	daddr_t align;
    973 
    974 	if (parts->dp.num_part >= parts->max_num_parts)
    975 		return false;
    976 
    977 	align = gpt_get_part_alignment(arg);
    978 	if (parts->dp.free_space <= align)
    979 		return false;
    980 
    981 	if (gpt_get_free_spaces_internal(parts, &space, 1, align, align,
    982 	    0, -1) < 1)
    983 		return false;
    984 
    985 	return true;
    986 }
    987 
    988 static bool
    989 gpt_info_to_part(struct gpt_part_entry *p, const struct disk_part_info *info,
    990     const char **err_msg)
    991 {
    992 	p->gp_type = gpt_find_native_type(info->nat_type);
    993 	p->gp_start = info->start;
    994 	p->gp_size = info->size;
    995 	if (info->last_mounted != NULL && info->last_mounted !=
    996 	    p->last_mounted) {
    997 		free(__UNCONST(p->last_mounted));
    998 		p->last_mounted = strdup(info->last_mounted);
    999 	}
   1000 	p->fs_type = info->fs_type;
   1001 	p->fs_sub_type = info->fs_sub_type;
   1002 
   1003 	return true;
   1004 }
   1005 
   1006 static part_id
   1007 gpt_add_part(struct disk_partitions *arg,
   1008     const struct disk_part_info *info, const char **err_msg)
   1009 {
   1010 	struct gpt_disk_partitions *parts =
   1011 	    (struct gpt_disk_partitions*)arg;
   1012 	struct disk_part_free_space space;
   1013 	struct disk_part_info data = *info;
   1014 	struct gpt_part_entry *p;
   1015 	bool ok;
   1016 
   1017 	if (err_msg != NULL)
   1018 		*err_msg = NULL;
   1019 
   1020 	if (gpt_get_free_spaces_internal(parts, &space, 1, 1, 1,
   1021 	    info->start, -1) < 1) {
   1022 		if (err_msg)
   1023 			*err_msg = msg_string(MSG_No_free_space);
   1024 		return NO_PART;
   1025 	}
   1026 	if (parts->dp.num_part >= parts->max_num_parts) {
   1027 		if (err_msg)
   1028 			*err_msg = msg_string(MSG_err_too_many_partitions);
   1029 		return NO_PART;
   1030 	}
   1031 
   1032 	if (data.size > space.size)
   1033 		data.size = space.size;
   1034 
   1035 	p = calloc(1, sizeof(*p));
   1036 	if (p == NULL) {
   1037 		if (err_msg != NULL)
   1038 			*err_msg = INTERNAL_ERROR;
   1039 		return NO_PART;
   1040 	}
   1041 	if (!gpt_info_to_part(p, &data, err_msg)) {
   1042 		free(p);
   1043 		return NO_PART;
   1044 	}
   1045 	p->gp_flags |= GPEF_MODIFIED;
   1046 	ok = gpt_insert_part_into_list(parts, &parts->partitions, p, err_msg);
   1047 	if (ok) {
   1048 		parts->dp.num_part++;
   1049 		parts->dp.free_space -= p->gp_size;
   1050 		return parts->dp.num_part-1;
   1051 	} else {
   1052 		free(p);
   1053 		return NO_PART;
   1054 	}
   1055 }
   1056 
   1057 static bool
   1058 gpt_delete_partition(struct disk_partitions *arg, part_id id,
   1059     const char **err_msg)
   1060 {
   1061 	struct gpt_disk_partitions *parts = (struct gpt_disk_partitions*)arg;
   1062 	struct gpt_part_entry *p, *last = NULL;
   1063 	part_id i;
   1064 	bool res;
   1065 
   1066 	if (parts->dp.num_part == 0)
   1067 		return false;
   1068 
   1069 	for (i = 0, p = parts->partitions;
   1070 	    i != id && i < parts->dp.num_part && p != NULL;
   1071 	    i++, p = p->gp_next)
   1072 		last = p;
   1073 
   1074 	if (p == NULL) {
   1075 		if (err_msg)
   1076 			*err_msg = INTERNAL_ERROR;
   1077 		return false;
   1078 	}
   1079 
   1080 	if (last == NULL)
   1081 		parts->partitions = p->gp_next;
   1082 	else
   1083 		last->gp_next = p->gp_next;
   1084 
   1085 	res = true;
   1086 	if (p->gp_flags & GPEF_ON_DISK) {
   1087 		if (!gpt_insert_part_into_list(parts, &parts->obsolete,
   1088 		    p, err_msg))
   1089 			res = false;
   1090 	} else {
   1091 		free(p);
   1092 	}
   1093 
   1094 	if (res) {
   1095 		parts->dp.num_part--;
   1096 		parts->dp.free_space += p->gp_size;
   1097 	}
   1098 
   1099 	return res;
   1100 }
   1101 
   1102 static bool
   1103 gpt_delete_all_partitions(struct disk_partitions *arg)
   1104 {
   1105 	struct gpt_disk_partitions *parts = (struct gpt_disk_partitions*)arg;
   1106 
   1107 	while (parts->dp.num_part > 0) {
   1108 		if (!gpt_delete_partition(&parts->dp, 0, NULL))
   1109 			return false;
   1110 	}
   1111 
   1112 	return true;
   1113 }
   1114 
   1115 static bool
   1116 gpt_read_part(const char *disk, daddr_t start, struct gpt_part_entry *p)
   1117 {
   1118 	char *textbuf, *t, *tt;
   1119 	static const char expected_hdr[] = "Details for index ";
   1120 
   1121 	/* run gpt show for this partition */
   1122 	if (collect(T_OUTPUT, &textbuf,
   1123 	    "gpt -r show -b %" PRIu64 " %s 2>/dev/null", start, disk) < 1)
   1124 		return false;
   1125 
   1126 	/*
   1127 	 * gpt show should respond with single partition details, but will
   1128 	 * fall back to "show -a" output if something is wrong
   1129 	 */
   1130 	t = strtok(textbuf, "\n"); /* first line is special */
   1131 	if (strncmp(t, expected_hdr, sizeof(expected_hdr)-1) != 0) {
   1132 		free(textbuf);
   1133 		return false;
   1134 	}
   1135 
   1136 	/* parse output into "old" */
   1137 	while ((t = strtok(NULL, "\n")) != NULL) {
   1138 		tt = strsep(&t, " \t");
   1139 		if (strlen(tt) == 0)
   1140 			continue;
   1141 		gpt_add_info(p, tt, t, true);
   1142 	}
   1143 	free(textbuf);
   1144 
   1145 	return true;
   1146 }
   1147 
   1148 static bool
   1149 gpt_apply_attr(const char *disk, const char *cmd, off_t start, uint todo)
   1150 {
   1151 	size_t i;
   1152 	char attr_str[STRSIZE];
   1153 
   1154 	if (todo == 0)
   1155 		return true;
   1156 
   1157 	strcpy(attr_str, "-a ");
   1158 	for (i = 0; todo != 0; i++) {
   1159 		if (!(gpt_avail_attrs[i].flag & todo))
   1160 			continue;
   1161 		todo &= ~gpt_avail_attrs[i].flag;
   1162 		if (attr_str[0])
   1163 			strlcat(attr_str, ",",
   1164 			    sizeof(attr_str));
   1165 		strlcat(attr_str,
   1166 		    gpt_avail_attrs[i].name,
   1167 		    sizeof(attr_str));
   1168 	}
   1169 	if (run_program(RUN_SILENT,
   1170 	    "gpt %s %s -b %" PRIu64 " %s", cmd, attr_str, start, disk) != 0)
   1171 		return false;
   1172 	return true;
   1173 }
   1174 
   1175 /*
   1176  * Modify an existing on-disk partition.
   1177  * Start and size can not be changed here, caller needs to deal
   1178  * with that kind of changes upfront.
   1179  */
   1180 static bool
   1181 gpt_modify_part(const char *disk, struct gpt_part_entry *p)
   1182 {
   1183 	struct gpt_part_entry old;
   1184 	uint todo_set, todo_unset;
   1185 
   1186 	/*
   1187 	 * Query current on-disk state
   1188 	 */
   1189 	memset(&old, 0, sizeof old);
   1190 	if (!gpt_read_part(disk, p->gp_start, &old))
   1191 		return false;
   1192 
   1193 	/* Reject unsupported changes */
   1194 	if (old.gp_start != p->gp_start || old.gp_size != p->gp_size)
   1195 		return false;
   1196 
   1197 	/*
   1198 	 * GUID should never change, but the internal copy
   1199 	 * may not yet know it.
   1200 	 */
   1201 	strcpy(p->gp_id, old.gp_id);
   1202 
   1203 	/* Check type */
   1204 	if (p->gp_type != old.gp_type) {
   1205 		if (run_program(RUN_SILENT,
   1206 		    "gpt label -b %" PRIu64 " -T %s %s",
   1207 		    p->gp_start, p->gp_type->tid, disk) != 0)
   1208 			return false;
   1209 	}
   1210 
   1211 	/* Check label */
   1212 	if (strcmp(p->gp_label, old.gp_label) != 0) {
   1213 		if (run_program(RUN_SILENT,
   1214 		    "gpt label -b %" PRIu64 " -l \'%s\' %s",
   1215 		    p->gp_start, p->gp_label, disk) != 0)
   1216 			return false;
   1217 	}
   1218 
   1219 	/* Check attributes */
   1220 	if (p->gp_attr != old.gp_attr) {
   1221 		if (p->gp_attr == 0) {
   1222 			if (run_program(RUN_SILENT,
   1223 			    "gpt set -N -b %" PRIu64 " %s",
   1224 			    p->gp_start, disk) != 0)
   1225 				return false;
   1226 		} else {
   1227 			todo_set = (p->gp_attr ^ old.gp_attr) & p->gp_attr;
   1228 			todo_unset = (p->gp_attr ^ old.gp_attr) & old.gp_attr;
   1229 			if (!gpt_apply_attr(disk, "unset", p->gp_start,
   1230 			    todo_unset))
   1231 				return false;
   1232 			if (!gpt_apply_attr(disk, "set", p->gp_start,
   1233 			    todo_set))
   1234 				return false;
   1235 		}
   1236 	}
   1237 
   1238 	return true;
   1239 }
   1240 
   1241 /*
   1242  * verbatim copy from sys/dev/dkwedge/dkwedge_bsdlabel.c:
   1243  *  map FS_* to wedge strings
   1244  */
   1245 static const char *
   1246 bsdlabel_fstype_to_str(uint8_t fstype)
   1247 {
   1248 	const char *str;
   1249 
   1250 	/*
   1251 	 * For each type known to FSTYPE_DEFN (from <sys/disklabel.h>),
   1252 	 * a suitable case branch will convert the type number to a string.
   1253 	 */
   1254 	switch (fstype) {
   1255 #define FSTYPE_TO_STR_CASE(tag, number, name, fsck, mount) \
   1256 	case __CONCAT(FS_,tag):	str = __CONCAT(DKW_PTYPE_,tag);			break;
   1257 	FSTYPE_DEFN(FSTYPE_TO_STR_CASE)
   1258 #undef FSTYPE_TO_STR_CASE
   1259 	default:		str = NULL;			break;
   1260 	}
   1261 
   1262 	return (str);
   1263 }
   1264 
   1265 static bool
   1266 gpt_add_wedge(const char *disk, struct gpt_part_entry *p)
   1267 {
   1268 	struct dkwedge_info dkw;
   1269 	const char *tname;
   1270 	char diskpath[MAXPATHLEN];
   1271 	int fd;
   1272 
   1273 	memset(&dkw, 0, sizeof(dkw));
   1274 	tname = bsdlabel_fstype_to_str(p->fs_type);
   1275 	if (tname)
   1276 		strlcpy(dkw.dkw_ptype, tname, sizeof(dkw.dkw_ptype));
   1277 
   1278 	strlcpy((char*)&dkw.dkw_wname, p->gp_id, sizeof(dkw.dkw_wname));
   1279 	dkw.dkw_offset = p->gp_start;
   1280 	dkw.dkw_size = p->gp_size;
   1281 
   1282 	fd = opendisk(disk, O_RDWR, diskpath, sizeof(diskpath), 0);
   1283 	if (fd < 0)
   1284 		return false;
   1285 	if (ioctl(fd, DIOCAWEDGE, &dkw) == -1) {
   1286 		close(fd);
   1287 		return false;
   1288 	}
   1289 	close(fd);
   1290 
   1291 	strlcpy(p->gp_dev_name, dkw.dkw_devname, sizeof(p->gp_dev_name));
   1292 	p->gp_flags |= GPEF_WEDGE;
   1293 	return true;
   1294 }
   1295 
   1296 static void
   1297 escape_spaces(char *dest, const char *src)
   1298 {
   1299 	unsigned char c;
   1300 
   1301 	while (*src) {
   1302 		c = *src++;
   1303 		if (isspace(c) || c == '\\')
   1304 			*dest++ = '\\';
   1305 		*dest++ = c;
   1306 	}
   1307 	*dest = 0;
   1308 }
   1309 
   1310 static bool
   1311 gpt_get_part_device(const struct disk_partitions *arg,
   1312     part_id id, char *devname, size_t max_devname_len, int *part,
   1313     enum dev_name_usage usage, bool with_path)
   1314 {
   1315 	const struct gpt_disk_partitions *parts =
   1316 	    (const struct gpt_disk_partitions*)arg;
   1317 	struct  gpt_part_entry *p = parts->partitions;
   1318 	char tmpname[GPT_LABEL_LEN*2];
   1319 	part_id no;
   1320 
   1321 
   1322 	for (no = 0; p != NULL && no < id; no++)
   1323 		p = p->gp_next;
   1324 
   1325 	if (no != id || p == NULL)
   1326 		return false;
   1327 
   1328 	if (part)
   1329 		*part = -1;
   1330 
   1331 	if (!(p->gp_flags & GPEF_WEDGE) &&
   1332 	    (usage == plain_name || usage == raw_dev_name))
   1333 		gpt_add_wedge(arg->disk, p);
   1334 
   1335 	switch (usage) {
   1336 	case logical_name:
   1337 		if (p->gp_label[0] != 0) {
   1338 			escape_spaces(tmpname, p->gp_label);
   1339 			snprintf(devname, max_devname_len,
   1340 			    "NAME=%s", tmpname);
   1341 		} else {
   1342 			snprintf(devname, max_devname_len,
   1343 			    "NAME=%s", p->gp_id);
   1344 		}
   1345 		break;
   1346 	case plain_name:
   1347 		assert(p->gp_flags & GPEF_WEDGE);
   1348 		if (with_path)
   1349 			snprintf(devname, max_devname_len, _PATH_DEV "%s",
   1350 			    p->gp_dev_name);
   1351 		else
   1352 			strlcpy(devname, p->gp_dev_name, max_devname_len);
   1353 		break;
   1354 	case raw_dev_name:
   1355 		assert(p->gp_flags & GPEF_WEDGE);
   1356 		if (with_path)
   1357 			snprintf(devname, max_devname_len, _PATH_DEV "r%s",
   1358 			    p->gp_dev_name);
   1359 		else
   1360 			snprintf(devname, max_devname_len, "r%s",
   1361 			    p->gp_dev_name);
   1362 		break;
   1363 	default:
   1364 		return false;
   1365 	}
   1366 
   1367 	return true;
   1368 }
   1369 
   1370 static bool
   1371 gpt_write_to_disk(struct disk_partitions *arg)
   1372 {
   1373 	struct gpt_disk_partitions *parts = (struct gpt_disk_partitions*)arg;
   1374 	struct gpt_part_entry *p, *n;
   1375 	char label_arg[sizeof(p->gp_label) + 10];
   1376 	char diskpath[MAXPATHLEN];
   1377 	int fd, bits = 0;
   1378 	bool root_is_new = false, efi_is_new = false;
   1379 	part_id root_id = NO_PART, efi_id = NO_PART, pno;
   1380 
   1381 	/*
   1382 	 * Remove all wedges on this disk - they may become invalid and we
   1383 	 * have no easy way to associate them with the partitioning data.
   1384 	 * Instead we will explicitly request creation of wedges on demand
   1385 	 * later.
   1386 	 */
   1387 	fd = opendisk(arg->disk, O_RDWR, diskpath, sizeof(diskpath), 0);
   1388 	if (fd < 0)
   1389 		return false;
   1390 	if (ioctl(fd, DIOCRMWEDGES, &bits) == -1)
   1391 		return false;
   1392 	close(fd);
   1393 
   1394 	/*
   1395 	 * Collect first root and efi partition (if available), clear
   1396 	 * "have wedge" flags.
   1397 	 */
   1398 	for (pno = 0, p = parts->partitions; p != NULL; p = p->gp_next, pno++) {
   1399 		p->gp_flags &= ~GPEF_WEDGE;
   1400 		if (root_id == NO_PART && p->gp_type != NULL) {
   1401 			if (p->gp_type->gent.generic_ptype == PT_root &&
   1402 			    p->gp_start == pm->ptstart) {
   1403 				root_id = pno;
   1404 				root_is_new = !(p->gp_flags & GPEF_ON_DISK);
   1405 			} else if (efi_id == NO_PART &&
   1406 			    p->gp_type->gent.generic_ptype == PT_EFI_SYSTEM) {
   1407 				efi_id = pno;
   1408 				efi_is_new = !(p->gp_flags & GPEF_ON_DISK);
   1409 			}
   1410 		}
   1411 	}
   1412 
   1413 	/*
   1414 	 * If no GPT on disk yet, create it.
   1415 	 */
   1416 	if (!parts->has_gpt) {
   1417 		char limit[30];
   1418 
   1419 		if (parts->max_num_parts > 0)
   1420 			sprintf(limit, "-p %zu", parts->max_num_parts);
   1421 		else
   1422 			limit[0] = 0;
   1423 		if (run_program(RUN_SILENT, "gpt create %s %s",
   1424 		    limit, parts->dp.disk))
   1425 			return false;
   1426 		parts->has_gpt = true;
   1427 	}
   1428 
   1429 	/*
   1430 	 * Delete all old partitions
   1431 	 */
   1432 	for (p = parts->obsolete; p != NULL; p = n) {
   1433 		run_program(RUN_SILENT, "gpt -n remove -b %" PRIu64 " %s",
   1434 		    p->gp_start, arg->disk);
   1435 		n = p->gp_next;
   1436 		free(p);
   1437 	}
   1438 	parts->obsolete = NULL;
   1439 
   1440 	/*
   1441 	 * Modify existing but changed partitions
   1442 	 */
   1443 	for (p = parts->partitions; p != NULL; p = p->gp_next) {
   1444 		if (!(p->gp_flags & GPEF_ON_DISK))
   1445 			continue;
   1446 
   1447 		if (p->gp_flags & GPEF_RESIZED) {
   1448 			run_program(RUN_SILENT,
   1449 			    "gpt -n resize -b %" PRIu64 " -s %" PRIu64 "s %s",
   1450 			    p->gp_start, p->gp_size, arg->disk);
   1451 			p->gp_flags &= ~GPEF_RESIZED;
   1452 		}
   1453 
   1454 		if (!(p->gp_flags & GPEF_MODIFIED))
   1455 			continue;
   1456 
   1457 		if (!gpt_modify_part(parts->dp.disk, p))
   1458 			return false;
   1459 	}
   1460 
   1461 	/*
   1462 	 * Add new partitions
   1463 	 */
   1464 	for (p = parts->partitions; p != NULL; p = p->gp_next) {
   1465 		if (p->gp_flags & GPEF_ON_DISK)
   1466 			continue;
   1467 		if (!(p->gp_flags & GPEF_MODIFIED))
   1468 			continue;
   1469 
   1470 		if (p->gp_label[0] == 0)
   1471 			label_arg[0] = 0;
   1472 		else
   1473 			sprintf(label_arg, "-l \'%s\'", p->gp_label);
   1474 
   1475 		if (p->gp_type != NULL)
   1476 			run_program(RUN_SILENT,
   1477 			    "gpt -n add -b %" PRIu64 " -s %" PRIu64
   1478 			    "s -t %s %s %s",
   1479 			    p->gp_start, p->gp_size, p->gp_type->tid,
   1480 			    label_arg, arg->disk);
   1481 		else
   1482 			run_program(RUN_SILENT,
   1483 			    "gpt -n add -b %" PRIu64 " -s %" PRIu64
   1484 			    "s %s %s",
   1485 			    p->gp_start, p->gp_size, label_arg, arg->disk);
   1486 		gpt_apply_attr(arg->disk, "set", p->gp_start, p->gp_attr);
   1487 		gpt_read_part(arg->disk, p->gp_start, p);
   1488 		p->gp_flags |= GPEF_ON_DISK;
   1489 	}
   1490 
   1491 	/*
   1492 	 * Additional MD bootloader magic...
   1493 	 */
   1494 	if (!md_gpt_post_write(&parts->dp, root_id, root_is_new, efi_id,
   1495 	    efi_is_new))
   1496 		return false;
   1497 
   1498 	return true;
   1499 }
   1500 
   1501 static part_id
   1502 gpt_find_by_name(struct disk_partitions *arg, const char *name)
   1503 {
   1504 	struct gpt_disk_partitions *parts = (struct gpt_disk_partitions*)arg;
   1505 	struct gpt_part_entry *p;
   1506 	part_id pno;
   1507 
   1508 	for (pno = 0, p = parts->partitions; p != NULL;
   1509 	    p = p->gp_next, pno++) {
   1510 		if (strcmp(p->gp_label, name) == 0)
   1511 			return pno;
   1512 		if (strcmp(p->gp_id, name) == 0)
   1513 			return pno;
   1514 	}
   1515 
   1516 	return NO_PART;
   1517 }
   1518 
   1519 bool
   1520 gpt_parts_check(void)
   1521 {
   1522 
   1523 	check_available_binaries();
   1524 
   1525 	return have_gpt && have_dk;
   1526 }
   1527 
   1528 static void
   1529 gpt_free(struct disk_partitions *arg)
   1530 {
   1531 	struct gpt_disk_partitions *parts = (struct gpt_disk_partitions*)arg;
   1532 	struct gpt_part_entry *p, *n;
   1533 
   1534 	assert(parts != NULL);
   1535 	for (p = parts->partitions; p != NULL; p = n) {
   1536 		free(__UNCONST(p->last_mounted));
   1537 		n = p->gp_next;
   1538 		free(p);
   1539 	}
   1540 	free(__UNCONST(parts->dp.disk));
   1541 	free(parts);
   1542 }
   1543 
   1544 static bool
   1545 gpt_custom_attribute_writable(const struct disk_partitions *arg,
   1546     part_id ptn, size_t attr_no)
   1547 {
   1548 	const struct gpt_disk_partitions *parts =
   1549 	    (const struct gpt_disk_partitions*)arg;
   1550 	size_t i;
   1551 	struct gpt_part_entry *p;
   1552 
   1553 	if (attr_no >= arg->pscheme->custom_attribute_count)
   1554 		return false;
   1555 
   1556 	const msg label = arg->pscheme->custom_attributes[attr_no].label;
   1557 
   1558 	/* we can not edit the uuid attribute */
   1559 	if (label == MSG_ptn_uuid)
   1560 		return false;
   1561 
   1562 	/* the label is always editable */
   1563 	if (label == MSG_ptn_label)
   1564 		return true;
   1565 
   1566 	/* the GPT type is read only */
   1567 	if (label == MSG_ptn_gpt_type)
   1568 		return false;
   1569 
   1570 	/* BOOTME makes no sense on swap partitions */
   1571 	for (i = 0, p = parts->partitions; p != NULL; i++, p = p->gp_next)
   1572 		if (i == ptn)
   1573 			break;
   1574 
   1575 	if (p == NULL)
   1576 		return false;
   1577 
   1578 	if (p->fs_type == FS_SWAP ||
   1579 	    (p->gp_type != NULL && p->gp_type->gent.generic_ptype == PT_swap))
   1580 		return false;
   1581 
   1582 	return true;
   1583 }
   1584 
   1585 static const char *
   1586 gpt_get_label_str(const struct disk_partitions *arg, part_id ptn)
   1587 {
   1588 	const struct gpt_disk_partitions *parts =
   1589 	    (const struct gpt_disk_partitions*)arg;
   1590 	size_t i;
   1591 	struct gpt_part_entry *p;
   1592 
   1593 	for (i = 0, p = parts->partitions; p != NULL; i++, p = p->gp_next)
   1594 		if (i == ptn)
   1595 			break;
   1596 
   1597 	if (p == NULL)
   1598 		return NULL;
   1599 
   1600 	if (p->gp_label[0] != 0)
   1601 		return p->gp_label;
   1602 	return p->gp_id;
   1603 }
   1604 
   1605 static bool
   1606 gpt_format_custom_attribute(const struct disk_partitions *arg,
   1607     part_id ptn, size_t attr_no, const struct disk_part_info *info,
   1608     char *out, size_t out_space)
   1609 {
   1610 	const struct gpt_disk_partitions *parts =
   1611 	    (const struct gpt_disk_partitions*)arg;
   1612 	size_t i;
   1613 	struct gpt_part_entry *p, data;
   1614 
   1615 	for (i = 0, p = parts->partitions; p != NULL; i++, p = p->gp_next)
   1616 		if (i == ptn)
   1617 			break;
   1618 
   1619 	if (p == NULL)
   1620 		return false;
   1621 
   1622 	if (attr_no >= parts->dp.pscheme->custom_attribute_count)
   1623 		return false;
   1624 
   1625 	const msg label = parts->dp.pscheme->custom_attributes[attr_no].label;
   1626 
   1627 	if (info != NULL) {
   1628 		data = *p;
   1629 		gpt_info_to_part(&data, info, NULL);
   1630 		p = &data;
   1631 	}
   1632 
   1633 	if (label == MSG_ptn_label)
   1634 		strlcpy(out, p->gp_label, out_space);
   1635 	else if (label == MSG_ptn_uuid)
   1636 		strlcpy(out, p->gp_id, out_space);
   1637 	else if (label == MSG_ptn_gpt_type) {
   1638 		if (p->gp_type != NULL)
   1639 			strlcpy(out, p->gp_type->gent.description, out_space);
   1640 		else if (out_space > 1)
   1641 			out[0] = 0;
   1642 	} else if (label == MSG_ptn_boot)
   1643 		strlcpy(out, msg_string(p->gp_attr & GPT_ATTR_BOOT ?
   1644 		    MSG_Yes : MSG_No), out_space);
   1645 	else
   1646 		return false;
   1647 
   1648 	return true;
   1649 }
   1650 
   1651 static bool
   1652 gpt_custom_attribute_toggle(struct disk_partitions *arg,
   1653     part_id ptn, size_t attr_no)
   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;
   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 	if (label != MSG_ptn_boot)
   1672 		return false;
   1673 
   1674 	if (p->gp_attr & GPT_ATTR_BOOT) {
   1675 		p->gp_attr &= ~GPT_ATTR_BOOT;
   1676 	} else {
   1677 		for (i = 0, p = parts->partitions; p != NULL;
   1678 		    i++, p = p->gp_next)
   1679 			if (i == ptn)
   1680 				p->gp_attr |= GPT_ATTR_BOOT;
   1681 			else
   1682 				p->gp_attr &= ~GPT_ATTR_BOOT;
   1683 	}
   1684 	return true;
   1685 }
   1686 
   1687 static bool
   1688 gpt_custom_attribute_set_str(struct disk_partitions *arg,
   1689     part_id ptn, size_t attr_no, const char *new_val)
   1690 {
   1691 	const struct gpt_disk_partitions *parts =
   1692 	    (const struct gpt_disk_partitions*)arg;
   1693 	size_t i;
   1694 	struct gpt_part_entry *p;
   1695 
   1696 	for (i = 0, p = parts->partitions; p != NULL; i++, p = p->gp_next)
   1697 		if (i == ptn)
   1698 			break;
   1699 
   1700 	if (p == NULL)
   1701 		return false;
   1702 
   1703 	if (attr_no >= parts->dp.pscheme->custom_attribute_count)
   1704 		return false;
   1705 
   1706 	const msg label = parts->dp.pscheme->custom_attributes[attr_no].label;
   1707 
   1708 	if (label != MSG_ptn_label)
   1709 		return false;
   1710 
   1711 	strlcpy(p->gp_label, new_val, sizeof(p->gp_label));
   1712 	return true;
   1713 }
   1714 
   1715 static bool
   1716 gpt_have_boot_support(const char *disk)
   1717 {
   1718 #ifdef	HAVE_GPT_BOOT
   1719 	return true;
   1720 #else
   1721 	return false;
   1722 #endif
   1723 }
   1724 
   1725 const struct disk_part_custom_attribute gpt_custom_attrs[] = {
   1726 	{ .label = MSG_ptn_label,	.type = pet_str },
   1727 	{ .label = MSG_ptn_uuid,	.type = pet_str },
   1728 	{ .label = MSG_ptn_gpt_type,	.type = pet_str },
   1729 	{ .label = MSG_ptn_boot,	.type = pet_bool },
   1730 };
   1731 
   1732 const struct disk_partitioning_scheme
   1733 gpt_parts = {
   1734 	.name = MSG_parttype_gpt,
   1735 	.short_name = MSG_parttype_gpt_short,
   1736 	.part_flag_desc = MSG_gpt_flag_desc,
   1737 	.custom_attribute_count = __arraycount(gpt_custom_attrs),
   1738 	.custom_attributes = gpt_custom_attrs,
   1739 	.get_part_types_count = gpt_type_count,
   1740 	.get_part_type = gpt_get_ptype,
   1741 	.get_generic_part_type = gpt_get_generic_type,
   1742 	.get_fs_part_type = gpt_get_fs_part_type,
   1743 	.create_custom_part_type = gpt_create_custom_part_type,
   1744 	.create_unknown_part_type = gpt_create_unknown_part_type,
   1745 	.get_part_alignment = gpt_get_part_alignment,
   1746 	.read_from_disk = gpt_read_from_disk,
   1747 	.create_new_for_disk = gpt_create_new,
   1748 	.have_boot_support = gpt_have_boot_support,
   1749 	.find_by_name = gpt_find_by_name,
   1750 	.can_add_partition = gpt_can_add_partition,
   1751 	.custom_attribute_writable = gpt_custom_attribute_writable,
   1752 	.format_custom_attribute = gpt_format_custom_attribute,
   1753 	.custom_attribute_toggle = gpt_custom_attribute_toggle,
   1754 	.custom_attribute_set_str = gpt_custom_attribute_set_str,
   1755 	.other_partition_identifier = gpt_get_label_str,
   1756 	.get_part_device = gpt_get_part_device,
   1757 	.max_free_space_at = gpt_max_free_space_at,
   1758 	.get_free_spaces = gpt_get_free_spaces,
   1759 	.adapt_foreign_part_info = generic_adapt_foreign_part_info,
   1760 	.get_part_info = gpt_get_part_info,
   1761 	.get_part_attr_str = gpt_get_part_attr_str,
   1762 	.set_part_info = gpt_set_part_info,
   1763 	.add_partition = gpt_add_part,
   1764 	.delete_all_partitions = gpt_delete_all_partitions,
   1765 	.delete_partition = gpt_delete_partition,
   1766 	.write_to_disk = gpt_write_to_disk,
   1767 	.free = gpt_free,
   1768 	.cleanup = gpt_cleanup,
   1769 };
   1770