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