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