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