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