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