1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2011 Nathan Whitehorn
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 THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * 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 THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  *
28  * $FreeBSD$
29  */
30 
31 #include <sys/param.h>
32 #include <sys/stat.h>
33 #include <errno.h>
34 #include <libutil.h>
35 #include <inttypes.h>
36 
37 #include <libgeom.h>
38 #include <dialog.h>
39 #include <dlg_keys.h>
40 
41 #include "partedit.h"
42 
43 #define GPART_FLAGS "x" /* Do not commit changes by default */
44 
45 static void
46 gpart_show_error(const char *title, const char *explanation, const char *errstr)
47 {
48 	char *errmsg;
49 	char message[512];
50 	int error;
51 
52 	if (explanation == NULL)
53 		explanation = "";
54 
55 	error = strtol(errstr, &errmsg, 0);
56 	if (errmsg != errstr) {
57 		while (errmsg[0] == ' ')
58 			errmsg++;
59 		if (errmsg[0] != '\0')
60 			sprintf(message, "%s%s. %s", explanation,
61 			    strerror(error), errmsg);
62 		else
63 			sprintf(message, "%s%s", explanation, strerror(error));
64 	} else {
65 		sprintf(message, "%s%s", explanation, errmsg);
66 	}
67 
68 	dialog_msgbox(title, message, 0, 0, TRUE);
69 }
70 
71 static int
72 scheme_supports_labels(const char *scheme)
73 {
74 	if (strcmp(scheme, "APM") == 0)
75 		return (1);
76 	if (strcmp(scheme, "GPT") == 0)
77 		return (1);
78 
79 	return (0);
80 }
81 
82 static void
83 newfs_command(const char *fstype, char *command, int use_default)
84 {
85 	if (strcmp(fstype, "freebsd-ufs") == 0) {
86 		int i;
87 		DIALOG_LISTITEM items[] = {
88 			{"UFS1", "UFS Version 1",
89 			    "Use version 1 of the UFS file system instead "
90 			    "of version 2 (not recommended)", 0 },
91 			{"SU", "Softupdates",
92 			    "Enable softupdates (default)", 1 },
93 			{"SUJ", "Softupdates journaling",
94 			    "Enable file system journaling (default - "
95 			    "turn off for SSDs)", 1 },
96 			{"TRIM", "Enable SSD TRIM support",
97 			    "Enable TRIM support, useful on solid-state drives",
98 			    0 },
99 		};
100 
101 		if (!use_default) {
102 			int choice;
103 			choice = dlg_checklist("UFS Options", "", 0, 0, 0,
104 			    nitems(items), items, NULL,
105 			    FLAG_CHECK, &i);
106 			if (choice == 1) /* Cancel */
107 				return;
108 		}
109 
110 		strcpy(command, "newfs ");
111 		for (i = 0; i < (int)nitems(items); i++) {
112 			if (items[i].state == 0)
113 				continue;
114 			if (strcmp(items[i].name, "UFS1") == 0)
115 				strcat(command, "-O1 ");
116 			else if (strcmp(items[i].name, "SU") == 0)
117 				strcat(command, "-U ");
118 			else if (strcmp(items[i].name, "SUJ") == 0)
119 				strcat(command, "-j ");
120 			else if (strcmp(items[i].name, "TRIM") == 0)
121 				strcat(command, "-t ");
122 		}
123 	} else if (strcmp(fstype, "freebsd-zfs") == 0) {
124 		int i;
125 		DIALOG_LISTITEM items[] = {
126 			{"fletcher4", "checksum algorithm: fletcher4",
127 			    "Use fletcher4 for data integrity checking. "
128 			    "(default)", 1 },
129 			{"fletcher2", "checksum algorithm: fletcher2",
130 			    "Use fletcher2 for data integrity checking. "
131 			    "(not recommended)", 0 },
132 			{"sha256", "checksum algorithm: sha256",
133 			    "Use sha256 for data integrity checking. "
134 			    "(not recommended)", 0 },
135 			{"atime", "Update atimes for files",
136 			    "Disable atime update", 0 },
137 		};
138 
139 		if (!use_default) {
140 			int choice;
141 			choice = dlg_checklist("ZFS Options", "", 0, 0, 0,
142 			    nitems(items), items, NULL,
143 			    FLAG_CHECK, &i);
144 			if (choice == 1) /* Cancel */
145 				return;
146 		}
147 
148 		strcpy(command, "zpool create -f -m none ");
149 		if (getenv("BSDINSTALL_TMPBOOT") != NULL) {
150 			char zfsboot_path[MAXPATHLEN];
151 			snprintf(zfsboot_path, sizeof(zfsboot_path), "%s/zfs",
152 			    getenv("BSDINSTALL_TMPBOOT"));
153 			mkdir(zfsboot_path, S_IRWXU | S_IRGRP | S_IXGRP |
154 			    S_IROTH | S_IXOTH);
155 			sprintf(command, "%s -o cachefile=%s/zpool.cache ",
156 			    command, zfsboot_path);
157 		}
158 		for (i = 0; i < (int)nitems(items); i++) {
159 			if (items[i].state == 0)
160 				continue;
161 			if (strcmp(items[i].name, "fletcher4") == 0)
162 				strcat(command, "-O checksum=fletcher4 ");
163 			else if (strcmp(items[i].name, "fletcher2") == 0)
164 				strcat(command, "-O checksum=fletcher2 ");
165 			else if (strcmp(items[i].name, "sha256") == 0)
166 				strcat(command, "-O checksum=sha256 ");
167 			else if (strcmp(items[i].name, "atime") == 0)
168 				strcat(command, "-O atime=off ");
169 		}
170 	} else if (strcmp(fstype, "fat32") == 0 || strcmp(fstype, "efi") == 0) {
171 		int i;
172 		DIALOG_LISTITEM items[] = {
173 			{"FAT32", "FAT Type 32",
174 			    "Create a FAT32 filesystem (default)", 1 },
175 			{"FAT16", "FAT Type 16",
176 			    "Create a FAT16 filesystem", 0 },
177 			{"FAT12", "FAT Type 12",
178 			    "Create a FAT12 filesystem", 0 },
179 		};
180 
181 		if (!use_default) {
182 			int choice;
183 			choice = dlg_checklist("FAT Options", "", 0, 0, 0,
184 			    nitems(items), items, NULL,
185 			    FLAG_RADIO, &i);
186 			if (choice == 1) /* Cancel */
187 				return;
188 		}
189 
190 		strcpy(command, "newfs_msdos ");
191 		for (i = 0; i < (int)nitems(items); i++) {
192 			if (items[i].state == 0)
193 				continue;
194 			if (strcmp(items[i].name, "FAT16") == 0)
195 				strcat(command, "-F 16 ");
196 			else if (strcmp(items[i].name, "FAT12") == 0)
197 				strcat(command, "-F 12 ");
198 		}
199 	} else {
200 		if (!use_default)
201 			dialog_msgbox("Error", "No configurable options exist "
202 			    "for this filesystem.", 0, 0, TRUE);
203 		command[0] = '\0';
204 	}
205 }
206 
207 const char *
208 choose_part_type(const char *def_scheme)
209 {
210 	int cancel, choice;
211 	const char *scheme = NULL;
212 
213 	DIALOG_LISTITEM items[] = {
214 		{"APM", "Apple Partition Map",
215 		    "Bootable on PowerPC Apple Hardware", 0 },
216 		{"BSD", "BSD Labels",
217 		    "Bootable on most x86 systems", 0 },
218 		{"GPT", "GUID Partition Table",
219 		    "Bootable on most x86 systems and EFI aware ARM64", 0 },
220 		{"MBR", "DOS Partitions",
221 		    "Bootable on most x86 systems", 0 },
222 		{"VTOC8", "Sun VTOC8 Partition Table",
223 		    "Bootable on Sun SPARC systems", 0 },
224 	};
225 
226 parttypemenu:
227 	dialog_vars.default_item = __DECONST(char *, def_scheme);
228 	cancel = dlg_menu("Partition Scheme",
229 	    "Select a partition scheme for this volume:", 0, 0, 0,
230 	    nitems(items), items, &choice, NULL);
231 	dialog_vars.default_item = NULL;
232 
233 	if (cancel)
234 		return NULL;
235 
236 	if (!is_scheme_bootable(items[choice].name)) {
237 		char message[512];
238 		sprintf(message, "This partition scheme (%s) is not "
239 		    "bootable on this platform. Are you sure you want "
240 		    "to proceed?", items[choice].name);
241 		dialog_vars.defaultno = TRUE;
242 		cancel = dialog_yesno("Warning", message, 0, 0);
243 		dialog_vars.defaultno = FALSE;
244 		if (cancel) /* cancel */
245 			goto parttypemenu;
246 	}
247 
248 	scheme = items[choice].name;
249 
250 	return scheme;
251 }
252 
253 int
254 gpart_partition(const char *lg_name, const char *scheme)
255 {
256 	int cancel;
257 	struct gctl_req *r;
258 	const char *errstr;
259 
260 schememenu:
261 	if (scheme == NULL) {
262 		scheme = choose_part_type(default_scheme());
263 
264 		if (scheme == NULL)
265 			return (-1);
266 
267 		if (!is_scheme_bootable(scheme)) {
268 			char message[512];
269 			sprintf(message, "This partition scheme (%s) is not "
270 			    "bootable on this platform. Are you sure you want "
271 			    "to proceed?", scheme);
272 			dialog_vars.defaultno = TRUE;
273 			cancel = dialog_yesno("Warning", message, 0, 0);
274 			dialog_vars.defaultno = FALSE;
275 			if (cancel) { /* cancel */
276 				/* Reset scheme so user can choose another */
277 				scheme = NULL;
278 				goto schememenu;
279 			}
280 		}
281 	}
282 
283 	r = gctl_get_handle();
284 	gctl_ro_param(r, "class", -1, "PART");
285 	gctl_ro_param(r, "arg0", -1, lg_name);
286 	gctl_ro_param(r, "flags", -1, GPART_FLAGS);
287 	gctl_ro_param(r, "scheme", -1, scheme);
288 	gctl_ro_param(r, "verb", -1, "create");
289 
290 	errstr = gctl_issue(r);
291 	if (errstr != NULL && errstr[0] != '\0') {
292 		gpart_show_error("Error", NULL, errstr);
293 		gctl_free(r);
294 		scheme = NULL;
295 		goto schememenu;
296 	}
297 	gctl_free(r);
298 
299 	if (bootcode_path(scheme) != NULL)
300 		get_part_metadata(lg_name, 1)->bootcode = 1;
301 	return (0);
302 }
303 
304 static void
305 gpart_activate(struct gprovider *pp)
306 {
307 	struct gconfig *gc;
308 	struct gctl_req *r;
309 	const char *errstr, *scheme;
310 	const char *attribute = NULL;
311 	intmax_t idx;
312 
313 	/*
314 	 * Some partition schemes need this partition to be marked 'active'
315 	 * for it to be bootable.
316 	 */
317 	LIST_FOREACH(gc, &pp->lg_geom->lg_config, lg_config) {
318 		if (strcmp(gc->lg_name, "scheme") == 0) {
319 			scheme = gc->lg_val;
320 			break;
321 		}
322 	}
323 
324 	if (strcmp(scheme, "MBR") == 0 || strcmp(scheme, "EBR") == 0)
325 		attribute = "active";
326 	else
327 		return;
328 
329 	LIST_FOREACH(gc, &pp->lg_config, lg_config) {
330 		if (strcmp(gc->lg_name, "index") == 0) {
331 			idx = atoi(gc->lg_val);
332 			break;
333 		}
334 	}
335 
336 	r = gctl_get_handle();
337 	gctl_ro_param(r, "class", -1, "PART");
338 	gctl_ro_param(r, "arg0", -1, pp->lg_geom->lg_name);
339 	gctl_ro_param(r, "verb", -1, "set");
340 	gctl_ro_param(r, "attrib", -1, attribute);
341 	gctl_ro_param(r, "index", sizeof(idx), &idx);
342 
343 	errstr = gctl_issue(r);
344 	if (errstr != NULL && errstr[0] != '\0')
345 		gpart_show_error("Error", "Error marking partition active:",
346 		    errstr);
347 	gctl_free(r);
348 }
349 
350 void
351 gpart_set_root(const char *lg_name, const char *attribute)
352 {
353 	struct gctl_req *r;
354 	const char *errstr;
355 
356 	r = gctl_get_handle();
357 	gctl_ro_param(r, "class", -1, "PART");
358 	gctl_ro_param(r, "arg0", -1, lg_name);
359 	gctl_ro_param(r, "flags", -1, "C");
360 	gctl_ro_param(r, "verb", -1, "set");
361 	gctl_ro_param(r, "attrib", -1, attribute);
362 
363 	errstr = gctl_issue(r);
364 	if (errstr != NULL && errstr[0] != '\0')
365 		gpart_show_error("Error", "Error setting parameter on disk:",
366 		    errstr);
367 	gctl_free(r);
368 }
369 
370 static void
371 gpart_bootcode(struct ggeom *gp)
372 {
373 	const char *bootcode;
374 	struct gconfig *gc;
375 	struct gctl_req *r;
376 	const char *errstr, *scheme;
377 	uint8_t *boot;
378 	size_t bootsize, bytes;
379 	int bootfd;
380 
381 	/*
382 	 * Write default bootcode to the newly partitioned disk, if that
383 	 * applies on this platform.
384 	 */
385 	LIST_FOREACH(gc, &gp->lg_config, lg_config) {
386 		if (strcmp(gc->lg_name, "scheme") == 0) {
387 			scheme = gc->lg_val;
388 			break;
389 		}
390 	}
391 
392 	bootcode = bootcode_path(scheme);
393 	if (bootcode == NULL)
394 		return;
395 
396 	bootfd = open(bootcode, O_RDONLY);
397 	if (bootfd < 0) {
398 		dialog_msgbox("Bootcode Error", strerror(errno), 0, 0,
399 		    TRUE);
400 		return;
401 	}
402 
403 	bootsize = lseek(bootfd, 0, SEEK_END);
404 	boot = malloc(bootsize);
405 	lseek(bootfd, 0, SEEK_SET);
406 	bytes = 0;
407 	while (bytes < bootsize)
408 		bytes += read(bootfd, boot + bytes, bootsize - bytes);
409 	close(bootfd);
410 
411 	r = gctl_get_handle();
412 	gctl_ro_param(r, "class", -1, "PART");
413 	gctl_ro_param(r, "arg0", -1, gp->lg_name);
414 	gctl_ro_param(r, "verb", -1, "bootcode");
415 	gctl_ro_param(r, "bootcode", bootsize, boot);
416 
417 	errstr = gctl_issue(r);
418 	if (errstr != NULL && errstr[0] != '\0')
419 		gpart_show_error("Bootcode Error", NULL, errstr);
420 	gctl_free(r);
421 	free(boot);
422 }
423 
424 static void
425 gpart_partcode(struct gprovider *pp, const char *fstype)
426 {
427 	struct gconfig *gc;
428 	const char *scheme;
429 	const char *indexstr;
430 	char message[255], command[255];
431 
432 	LIST_FOREACH(gc, &pp->lg_geom->lg_config, lg_config) {
433 		if (strcmp(gc->lg_name, "scheme") == 0) {
434 			scheme = gc->lg_val;
435 			break;
436 		}
437 	}
438 
439 	/* Make sure this partition scheme needs partcode on this platform */
440 	if (partcode_path(scheme, fstype) == NULL)
441 		return;
442 
443 	LIST_FOREACH(gc, &pp->lg_config, lg_config) {
444 		if (strcmp(gc->lg_name, "index") == 0) {
445 			indexstr = gc->lg_val;
446 			break;
447 		}
448 	}
449 
450 	/* Shell out to gpart for partcode for now */
451 	sprintf(command, "gpart bootcode -p %s -i %s %s",
452 	    partcode_path(scheme, fstype), indexstr, pp->lg_geom->lg_name);
453 	if (system(command) != 0) {
454 		sprintf(message, "Error installing partcode on partition %s",
455 		    pp->lg_name);
456 		dialog_msgbox("Error", message, 0, 0, TRUE);
457 	}
458 }
459 
460 void
461 gpart_destroy(struct ggeom *lg_geom)
462 {
463 	struct gctl_req *r;
464 	struct gprovider *pp;
465 	const char *errstr;
466 	int force = 1;
467 
468 	/* Delete all child metadata */
469 	LIST_FOREACH(pp, &lg_geom->lg_provider, lg_provider)
470 		gpart_delete(pp);
471 
472 	/* Revert any local changes to get this geom into a pristine state */
473 	r = gctl_get_handle();
474 	gctl_ro_param(r, "class", -1, "PART");
475 	gctl_ro_param(r, "arg0", -1, lg_geom->lg_name);
476 	gctl_ro_param(r, "verb", -1, "undo");
477 	gctl_issue(r); /* Ignore errors -- these are non-fatal */
478 	gctl_free(r);
479 
480 	/* Now destroy the geom itself */
481 	r = gctl_get_handle();
482 	gctl_ro_param(r, "class", -1, "PART");
483 	gctl_ro_param(r, "arg0", -1, lg_geom->lg_name);
484 	gctl_ro_param(r, "flags", -1, GPART_FLAGS);
485 	gctl_ro_param(r, "force", sizeof(force), &force);
486 	gctl_ro_param(r, "verb", -1, "destroy");
487 	errstr = gctl_issue(r);
488 	if (errstr != NULL && errstr[0] != '\0') {
489 		/*
490 		 * Check if we reverted away the existence of the geom
491 		 * altogether. Show all other errors to the user.
492 		 */
493 		if (strtol(errstr, NULL, 0) != EINVAL)
494 			gpart_show_error("Error", NULL, errstr);
495 	}
496 	gctl_free(r);
497 
498 	/* And any metadata associated with the partition scheme itself */
499 	delete_part_metadata(lg_geom->lg_name);
500 }
501 
502 void
503 gpart_edit(struct gprovider *pp)
504 {
505 	struct gctl_req *r;
506 	struct gconfig *gc;
507 	struct gconsumer *cp;
508 	struct ggeom *geom;
509 	const char *errstr, *oldtype, *scheme;
510 	struct partition_metadata *md;
511 	char sizestr[32];
512 	char newfs[255];
513 	intmax_t idx;
514 	int hadlabel, choice, junk, nitems;
515 	unsigned i;
516 
517 	DIALOG_FORMITEM items[] = {
518 		{0, "Type:", 5, 0, 0, FALSE, "", 11, 0, 12, 15, 0,
519 		    FALSE, "Filesystem type (e.g. freebsd-ufs, freebsd-zfs, "
520 		    "freebsd-swap)", FALSE},
521 		{0, "Size:", 5, 1, 0, FALSE, "", 11, 1, 12, 0, 0,
522 		    FALSE, "Partition size. Append K, M, G for kilobytes, "
523 		    "megabytes or gigabytes.", FALSE},
524 		{0, "Mountpoint:", 11, 2, 0, FALSE, "", 11, 2, 12, 15, 0,
525 		    FALSE, "Path at which to mount this partition (leave blank "
526 		    "for swap, set to / for root filesystem)", FALSE},
527 		{0, "Label:", 7, 3, 0, FALSE, "", 11, 3, 12, 15, 0, FALSE,
528 		    "Partition name. Not all partition schemes support this.",
529 		    FALSE},
530 	};
531 
532 	/*
533 	 * Find the PART geom we are manipulating. This may be a consumer of
534 	 * this provider, or its parent. Check the consumer case first.
535 	 */
536 	geom = NULL;
537 	LIST_FOREACH(cp, &pp->lg_consumers, lg_consumers)
538 		if (strcmp(cp->lg_geom->lg_class->lg_name, "PART") == 0) {
539 			/* Check for zombie geoms, treating them as blank */
540 			scheme = NULL;
541 			LIST_FOREACH(gc, &cp->lg_geom->lg_config, lg_config) {
542 				if (strcmp(gc->lg_name, "scheme") == 0) {
543 					scheme = gc->lg_val;
544 					break;
545 				}
546 			}
547 			if (scheme == NULL || strcmp(scheme, "(none)") == 0) {
548 				gpart_partition(cp->lg_geom->lg_name, NULL);
549 				return;
550 			}
551 
552 			/* If this is a nested partition, edit as usual */
553 			if (strcmp(pp->lg_geom->lg_class->lg_name, "PART") == 0)
554 				break;
555 
556 			/* Destroy the geom and all sub-partitions */
557 			gpart_destroy(cp->lg_geom);
558 
559 			/* Now re-partition and return */
560 			gpart_partition(cp->lg_geom->lg_name, NULL);
561 			return;
562 		}
563 
564 	if (geom == NULL && strcmp(pp->lg_geom->lg_class->lg_name, "PART") == 0)
565 		geom = pp->lg_geom;
566 
567 	if (geom == NULL) {
568 		/* Disk not partitioned, so partition it */
569 		gpart_partition(pp->lg_name, NULL);
570 		return;
571 	}
572 
573 	LIST_FOREACH(gc, &geom->lg_config, lg_config) {
574 		if (strcmp(gc->lg_name, "scheme") == 0) {
575 			scheme = gc->lg_val;
576 			break;
577 		}
578 	}
579 
580 	nitems = scheme_supports_labels(scheme) ? 4 : 3;
581 
582 	/* Edit editable parameters of a partition */
583 	hadlabel = 0;
584 	LIST_FOREACH(gc, &pp->lg_config, lg_config) {
585 		if (strcmp(gc->lg_name, "type") == 0) {
586 			oldtype = gc->lg_val;
587 			items[0].text = gc->lg_val;
588 		}
589 		if (strcmp(gc->lg_name, "label") == 0 && gc->lg_val != NULL) {
590 			hadlabel = 1;
591 			items[3].text = gc->lg_val;
592 		}
593 		if (strcmp(gc->lg_name, "index") == 0)
594 			idx = atoi(gc->lg_val);
595 	}
596 
597 	TAILQ_FOREACH(md, &part_metadata, metadata) {
598 		if (md->name != NULL && strcmp(md->name, pp->lg_name) == 0) {
599 			if (md->fstab != NULL)
600 				items[2].text = md->fstab->fs_file;
601 			break;
602 		}
603 	}
604 
605 	humanize_number(sizestr, 7, pp->lg_mediasize, "B", HN_AUTOSCALE,
606 	    HN_NOSPACE | HN_DECIMAL);
607 	items[1].text = sizestr;
608 
609 editpart:
610 	choice = dlg_form("Edit Partition", "", 0, 0, 0, nitems, items, &junk);
611 
612 	if (choice) /* Cancel pressed */
613 		goto endedit;
614 
615 	/* If this is the root partition, check that this fs is bootable */
616 	if (strcmp(items[2].text, "/") == 0 && !is_fs_bootable(scheme,
617 	    items[0].text)) {
618 		char message[512];
619 		sprintf(message, "This file system (%s) is not bootable "
620 		    "on this system. Are you sure you want to proceed?",
621 		    items[0].text);
622 		dialog_vars.defaultno = TRUE;
623 		choice = dialog_yesno("Warning", message, 0, 0);
624 		dialog_vars.defaultno = FALSE;
625 		if (choice == 1) /* cancel */
626 			goto editpart;
627 	}
628 
629 	/* Check if the label has a / in it */
630 	if (strchr(items[3].text, '/') != NULL) {
631 		dialog_msgbox("Error", "Label contains a /, which is not an "
632 		    "allowed character.", 0, 0, TRUE);
633 		goto editpart;
634 	}
635 
636 	r = gctl_get_handle();
637 	gctl_ro_param(r, "class", -1, "PART");
638 	gctl_ro_param(r, "arg0", -1, geom->lg_name);
639 	gctl_ro_param(r, "flags", -1, GPART_FLAGS);
640 	gctl_ro_param(r, "verb", -1, "modify");
641 	gctl_ro_param(r, "index", sizeof(idx), &idx);
642 	if (hadlabel || items[3].text[0] != '\0')
643 		gctl_ro_param(r, "label", -1, items[3].text);
644 	gctl_ro_param(r, "type", -1, items[0].text);
645 	errstr = gctl_issue(r);
646 	if (errstr != NULL && errstr[0] != '\0') {
647 		gpart_show_error("Error", NULL, errstr);
648 		gctl_free(r);
649 		goto editpart;
650 	}
651 	gctl_free(r);
652 
653 	newfs_command(items[0].text, newfs, 1);
654 	set_default_part_metadata(pp->lg_name, scheme, items[0].text,
655 	    items[2].text, (strcmp(oldtype, items[0].text) != 0) ?
656 	    newfs : NULL);
657 
658 endedit:
659 	if (strcmp(oldtype, items[0].text) != 0 && cp != NULL)
660 		gpart_destroy(cp->lg_geom);
661 	if (strcmp(oldtype, items[0].text) != 0 && strcmp(items[0].text,
662 	    "freebsd") == 0)
663 		gpart_partition(pp->lg_name, "BSD");
664 
665 	for (i = 0; i < nitems(items); i++)
666 		if (items[i].text_free)
667 			free(items[i].text);
668 }
669 
670 void
671 set_default_part_metadata(const char *name, const char *scheme,
672     const char *type, const char *mountpoint, const char *newfs)
673 {
674 	struct partition_metadata *md;
675 	char *zpool_name = NULL;
676 	const char *default_bootmount = NULL;
677 	int i;
678 
679 	/* Set part metadata */
680 	md = get_part_metadata(name, 1);
681 
682 	if (newfs) {
683 		if (md->newfs != NULL) {
684 			free(md->newfs);
685 			md->newfs = NULL;
686 		}
687 
688 		if (newfs != NULL && newfs[0] != '\0') {
689 			md->newfs = malloc(strlen(newfs) + strlen(" /dev/") +
690 			    strlen(mountpoint) + 5 + strlen(name) + 1);
691 			if (strcmp("freebsd-zfs", type) == 0) {
692 				zpool_name = strdup((strlen(mountpoint) == 1) ?
693 				    "root" : &mountpoint[1]);
694 				for (i = 0; zpool_name[i] != 0; i++)
695 					if (!isalnum(zpool_name[i]))
696 						zpool_name[i] = '_';
697 				sprintf(md->newfs, "%s %s /dev/%s", newfs,
698 				    zpool_name, name);
699 			} else {
700 				sprintf(md->newfs, "%s /dev/%s", newfs, name);
701 			}
702 		}
703 	}
704 
705 	if (strcmp(type, "freebsd-swap") == 0)
706 		mountpoint = "none";
707 	if (strcmp(type, bootpart_type(scheme, &default_bootmount)) == 0) {
708 		if (default_bootmount == NULL)
709 			md->bootcode = 1;
710 		else if (mountpoint == NULL || strlen(mountpoint) == 0)
711 			mountpoint = default_bootmount;
712 	}
713 
714 	/* VTOC8 needs partcode at the start of partitions */
715 	if (strcmp(scheme, "VTOC8") == 0 && (strcmp(type, "freebsd-ufs") == 0
716 	    || strcmp(type, "freebsd-zfs") == 0))
717 		md->bootcode = 1;
718 
719 	if (mountpoint == NULL || mountpoint[0] == '\0') {
720 		if (md->fstab != NULL) {
721 			free(md->fstab->fs_spec);
722 			free(md->fstab->fs_file);
723 			free(md->fstab->fs_vfstype);
724 			free(md->fstab->fs_mntops);
725 			free(md->fstab->fs_type);
726 			free(md->fstab);
727 			md->fstab = NULL;
728 		}
729 	} else {
730 		if (md->fstab == NULL) {
731 			md->fstab = malloc(sizeof(struct fstab));
732 		} else {
733 			free(md->fstab->fs_spec);
734 			free(md->fstab->fs_file);
735 			free(md->fstab->fs_vfstype);
736 			free(md->fstab->fs_mntops);
737 			free(md->fstab->fs_type);
738 		}
739 		if (strcmp("freebsd-zfs", type) == 0) {
740 			md->fstab->fs_spec = strdup(zpool_name);
741 		} else {
742 			md->fstab->fs_spec = malloc(strlen(name) +
743 			    strlen("/dev/") + 1);
744 			sprintf(md->fstab->fs_spec, "/dev/%s", name);
745 		}
746 		md->fstab->fs_file = strdup(mountpoint);
747 		/* Get VFS from text after freebsd-, if possible */
748 		if (strncmp("freebsd-", type, 8) == 0)
749 			md->fstab->fs_vfstype = strdup(&type[8]);
750 		else if (strcmp("fat32", type) == 0 || strcmp("efi", type) == 0)
751 			md->fstab->fs_vfstype = strdup("msdosfs");
752 		else
753 			md->fstab->fs_vfstype = strdup(type); /* Guess */
754 		if (strcmp(type, "freebsd-swap") == 0) {
755 			md->fstab->fs_type = strdup(FSTAB_SW);
756 			md->fstab->fs_freq = 0;
757 			md->fstab->fs_passno = 0;
758 		} else if (strcmp(type, "freebsd-zfs") == 0) {
759 			md->fstab->fs_type = strdup(FSTAB_RW);
760 			md->fstab->fs_freq = 0;
761 			md->fstab->fs_passno = 0;
762 		} else {
763 			md->fstab->fs_type = strdup(FSTAB_RW);
764 			if (strcmp(mountpoint, "/") == 0) {
765 				md->fstab->fs_freq = 1;
766 				md->fstab->fs_passno = 1;
767 			} else {
768 				md->fstab->fs_freq = 2;
769 				md->fstab->fs_passno = 2;
770 			}
771 		}
772 		md->fstab->fs_mntops = strdup(md->fstab->fs_type);
773 	}
774 
775 	if (zpool_name != NULL)
776 		free(zpool_name);
777 }
778 
779 static
780 int part_compare(const void *xa, const void *xb)
781 {
782 	struct gprovider **a = (struct gprovider **)xa;
783 	struct gprovider **b = (struct gprovider **)xb;
784 	intmax_t astart, bstart;
785 	struct gconfig *gc;
786 
787 	astart = bstart = 0;
788 	LIST_FOREACH(gc, &(*a)->lg_config, lg_config)
789 		if (strcmp(gc->lg_name, "start") == 0) {
790 			astart = strtoimax(gc->lg_val, NULL, 0);
791 			break;
792 		}
793 	LIST_FOREACH(gc, &(*b)->lg_config, lg_config)
794 		if (strcmp(gc->lg_name, "start") == 0) {
795 			bstart = strtoimax(gc->lg_val, NULL, 0);
796 			break;
797 		}
798 
799 	if (astart < bstart)
800 		return -1;
801 	else if (astart > bstart)
802 		return 1;
803 	else
804 		return 0;
805 }
806 
807 intmax_t
808 gpart_max_free(struct ggeom *geom, intmax_t *npartstart)
809 {
810 	struct gconfig *gc;
811 	struct gprovider *pp, **providers;
812 	intmax_t sectorsize, stripesize, offset;
813 	intmax_t lastend;
814 	intmax_t start, end;
815 	intmax_t maxsize, maxstart;
816 	intmax_t partstart, partend;
817 	int i, nparts;
818 
819 	/* Now get the maximum free size and free start */
820 	start = end = 0;
821 	LIST_FOREACH(gc, &geom->lg_config, lg_config) {
822 		if (strcmp(gc->lg_name, "first") == 0)
823 			start = strtoimax(gc->lg_val, NULL, 0);
824 		if (strcmp(gc->lg_name, "last") == 0)
825 			end = strtoimax(gc->lg_val, NULL, 0);
826 	}
827 
828 	i = nparts = 0;
829 	LIST_FOREACH(pp, &geom->lg_provider, lg_provider)
830 		nparts++;
831 	providers = calloc(nparts, sizeof(providers[0]));
832 	LIST_FOREACH(pp, &geom->lg_provider, lg_provider)
833 		providers[i++] = pp;
834 	qsort(providers, nparts, sizeof(providers[0]), part_compare);
835 
836 	lastend = start - 1;
837 	maxsize = 0;
838 	for (i = 0; i < nparts; i++) {
839 		pp = providers[i];
840 
841 		LIST_FOREACH(gc, &pp->lg_config, lg_config) {
842 			if (strcmp(gc->lg_name, "start") == 0)
843 				partstart = strtoimax(gc->lg_val, NULL, 0);
844 			if (strcmp(gc->lg_name, "end") == 0)
845 				partend = strtoimax(gc->lg_val, NULL, 0);
846 		}
847 
848 		if (partstart - lastend > maxsize) {
849 			maxsize = partstart - lastend - 1;
850 			maxstart = lastend + 1;
851 		}
852 
853 		lastend = partend;
854 	}
855 
856 	if (end - lastend > maxsize) {
857 		maxsize = end - lastend - 1;
858 		maxstart = lastend + 1;
859 	}
860 
861 	pp = LIST_FIRST(&geom->lg_consumer)->lg_provider;
862 
863 	/*
864 	 * Round the start and size of the largest available space up to
865 	 * the nearest multiple of the adjusted stripe size.
866 	 *
867 	 * The adjusted stripe size is the least common multiple of the
868 	 * actual stripe size, or the sector size if no stripe size was
869 	 * reported, and 4096.  The reason for this is that contemporary
870 	 * disks often have 4096-byte physical sectors but report 512
871 	 * bytes instead for compatibility with older / broken operating
872 	 * systems and BIOSes.  For the same reasons, virtualized storage
873 	 * may also report a 512-byte stripe size, or none at all.
874 	 */
875 	sectorsize = pp->lg_sectorsize;
876 	if ((stripesize = pp->lg_stripesize) == 0)
877 		stripesize = sectorsize;
878 	while (stripesize % 4096 != 0)
879 		stripesize *= 2;
880 	if ((offset = maxstart * sectorsize % stripesize) != 0) {
881 		offset = (stripesize - offset) / sectorsize;
882 		maxstart += offset;
883 		maxsize -= offset;
884 	}
885 
886 	if (npartstart != NULL)
887 		*npartstart = maxstart;
888 
889 	return (maxsize);
890 }
891 
892 static size_t
893 add_boot_partition(struct ggeom *geom, struct gprovider *pp,
894     const char *scheme, int interactive)
895 {
896 	struct gconfig *gc;
897 	struct gprovider *ppi;
898 	int choice;
899 
900 	/* Check for existing freebsd-boot partition */
901 	LIST_FOREACH(ppi, &geom->lg_provider, lg_provider) {
902 		struct partition_metadata *md;
903 		const char *bootmount = NULL;
904 
905 		LIST_FOREACH(gc, &ppi->lg_config, lg_config)
906 			if (strcmp(gc->lg_name, "type") == 0)
907 				break;
908 		if (gc == NULL)
909 			continue;
910 		if (strcmp(gc->lg_val, bootpart_type(scheme, &bootmount)) != 0)
911 			continue;
912 
913 		/*
914 		 * If the boot partition is not mountable and needs partcode,
915 		 * but doesn't have it, it doesn't satisfy our requirements.
916 		 */
917 		md = get_part_metadata(ppi->lg_name, 0);
918 		if (bootmount == NULL && (md == NULL || !md->bootcode))
919 			continue;
920 
921 		/* If it is mountable, but mounted somewhere else, remount */
922 		if (bootmount != NULL && md != NULL && md->fstab != NULL
923 		    && strlen(md->fstab->fs_file) > 0
924 		    && strcmp(md->fstab->fs_file, bootmount) != 0)
925 			continue;
926 
927 		/* If it is mountable, but mountpoint is not set, mount it */
928 		if (bootmount != NULL && md == NULL)
929 			set_default_part_metadata(ppi->lg_name, scheme,
930 			    gc->lg_val, bootmount, NULL);
931 
932 		/* Looks good at this point, no added data needed */
933 		return (0);
934 	}
935 
936 	if (interactive)
937 		choice = dialog_yesno("Boot Partition",
938 		    "This partition scheme requires a boot partition "
939 		    "for the disk to be bootable. Would you like to "
940 		    "make one now?", 0, 0);
941 	else
942 		choice = 0;
943 
944 	if (choice == 0) { /* yes */
945 		struct partition_metadata *md;
946 		const char *bootmount = NULL;
947 		char *bootpartname = NULL;
948 		char sizestr[7];
949 
950 		humanize_number(sizestr, 7,
951 		    bootpart_size(scheme), "B", HN_AUTOSCALE,
952 		    HN_NOSPACE | HN_DECIMAL);
953 
954 		gpart_create(pp, bootpart_type(scheme, &bootmount),
955 		    sizestr, bootmount, &bootpartname, 0);
956 
957 		if (bootpartname == NULL) /* Error reported to user already */
958 			return 0;
959 
960 		/* If the part is not mountable, make sure newfs isn't set */
961 		if (bootmount == NULL) {
962 			md = get_part_metadata(bootpartname, 0);
963 			if (md != NULL && md->newfs != NULL) {
964 				free(md->newfs);
965 				md->newfs = NULL;
966 			}
967 		}
968 
969 		free(bootpartname);
970 
971 		return (bootpart_size(scheme));
972 	}
973 
974 	return (0);
975 }
976 
977 void
978 gpart_create(struct gprovider *pp, const char *default_type,
979     const char *default_size, const char *default_mountpoint,
980     char **partname, int interactive)
981 {
982 	struct gctl_req *r;
983 	struct gconfig *gc;
984 	struct gconsumer *cp;
985 	struct ggeom *geom;
986 	const char *errstr, *scheme;
987 	char sizestr[32], startstr[32], output[64], *newpartname;
988 	char newfs[255], options_fstype[64];
989 	intmax_t maxsize, size, sector, firstfree, stripe;
990 	uint64_t bytes;
991 	int nitems, choice, junk;
992 	unsigned i;
993 
994 	DIALOG_FORMITEM items[] = {
995 		{0, "Type:", 5, 0, 0, FALSE, "freebsd-ufs", 11, 0, 12, 15, 0,
996 		    FALSE, "Filesystem type (e.g. freebsd-ufs, freebsd-zfs, "
997 		    "freebsd-swap)", FALSE},
998 		{0, "Size:", 5, 1, 0, FALSE, "", 11, 1, 12, 15, 0,
999 		    FALSE, "Partition size. Append K, M, G for kilobytes, "
1000 		    "megabytes or gigabytes.", FALSE},
1001 		{0, "Mountpoint:", 11, 2, 0, FALSE, "", 11, 2, 12, 15, 0,
1002 		    FALSE, "Path at which to mount partition (blank for "
1003 		    "swap, / for root filesystem)", FALSE},
1004 		{0, "Label:", 7, 3, 0, FALSE, "", 11, 3, 12, 15, 0, FALSE,
1005 		    "Partition name. Not all partition schemes support this.",
1006 		    FALSE},
1007 	};
1008 
1009 	if (partname != NULL)
1010 		*partname = NULL;
1011 
1012 	/* Record sector and stripe sizes */
1013 	sector = pp->lg_sectorsize;
1014 	stripe = pp->lg_stripesize;
1015 
1016 	/*
1017 	 * Find the PART geom we are manipulating. This may be a consumer of
1018 	 * this provider, or its parent. Check the consumer case first.
1019 	 */
1020 	geom = NULL;
1021 	LIST_FOREACH(cp, &pp->lg_consumers, lg_consumers)
1022 		if (strcmp(cp->lg_geom->lg_class->lg_name, "PART") == 0) {
1023 			geom = cp->lg_geom;
1024 			break;
1025 		}
1026 
1027 	if (geom == NULL && strcmp(pp->lg_geom->lg_class->lg_name, "PART") == 0)
1028 		geom = pp->lg_geom;
1029 
1030 	/* Now get the partition scheme */
1031 	scheme = NULL;
1032 	if (geom != NULL) {
1033 		LIST_FOREACH(gc, &geom->lg_config, lg_config)
1034 			if (strcmp(gc->lg_name, "scheme") == 0)
1035 				scheme = gc->lg_val;
1036 	}
1037 
1038 	if (geom == NULL || scheme == NULL || strcmp(scheme, "(none)") == 0) {
1039 		if (gpart_partition(pp->lg_name, NULL) == 0)
1040 			dialog_msgbox("",
1041 			    "The partition table has been successfully created."
1042 			    " Please press Create again to create partitions.",
1043 			    0, 0, TRUE);
1044 
1045 		return;
1046 	}
1047 
1048 	/*
1049 	 * If we still don't have a geom, either the user has
1050 	 * canceled partitioning or there has been an error which has already
1051 	 * been displayed, so bail.
1052 	 */
1053 	if (geom == NULL)
1054 		return;
1055 
1056 	maxsize = size = gpart_max_free(geom, &firstfree);
1057 	if (size <= 0) {
1058 		dialog_msgbox("Error", "No free space left on device.", 0, 0,
1059 		    TRUE);
1060 		return;
1061 	}
1062 
1063 	humanize_number(sizestr, 7, size*sector, "B", HN_AUTOSCALE,
1064 	    HN_NOSPACE | HN_DECIMAL);
1065 	items[1].text = sizestr;
1066 
1067 	/* Special-case the MBR default type for nested partitions */
1068 	if (strcmp(scheme, "MBR") == 0) {
1069 		items[0].text = "freebsd";
1070 		items[0].help = "Filesystem type (e.g. freebsd, fat32)";
1071 	}
1072 
1073 	nitems = scheme_supports_labels(scheme) ? 4 : 3;
1074 
1075 	if (default_type != NULL)
1076 		items[0].text = (char *)default_type;
1077 	if (default_size != NULL)
1078 		items[1].text = (char *)default_size;
1079 	if (default_mountpoint != NULL)
1080 		items[2].text = (char *)default_mountpoint;
1081 
1082 	/* Default options */
1083 	strncpy(options_fstype, items[0].text,
1084 	    sizeof(options_fstype));
1085 	newfs_command(options_fstype, newfs, 1);
1086 addpartform:
1087 	if (interactive) {
1088 		dialog_vars.extra_label = "Options";
1089 		dialog_vars.extra_button = TRUE;
1090 		choice = dlg_form("Add Partition", "", 0, 0, 0, nitems,
1091 		    items, &junk);
1092 		dialog_vars.extra_button = FALSE;
1093 		switch (choice) {
1094 		case 0: /* OK */
1095 			break;
1096 		case 1: /* Cancel */
1097 			return;
1098 		case 3: /* Options */
1099 			strncpy(options_fstype, items[0].text,
1100 			    sizeof(options_fstype));
1101 			newfs_command(options_fstype, newfs, 0);
1102 			goto addpartform;
1103 		}
1104 	}
1105 
1106 	/*
1107 	 * If the user changed the fs type after specifying options, undo
1108 	 * their choices in favor of the new filesystem's defaults.
1109 	 */
1110 	if (strcmp(options_fstype, items[0].text) != 0) {
1111 		strncpy(options_fstype, items[0].text, sizeof(options_fstype));
1112 		newfs_command(options_fstype, newfs, 1);
1113 	}
1114 
1115 	size = maxsize;
1116 	if (strlen(items[1].text) > 0) {
1117 		if (expand_number(items[1].text, &bytes) != 0) {
1118 			char error[512];
1119 
1120 			sprintf(error, "Invalid size: %s\n", strerror(errno));
1121 			dialog_msgbox("Error", error, 0, 0, TRUE);
1122 			goto addpartform;
1123 		}
1124 		size = MIN((intmax_t)(bytes/sector), maxsize);
1125 	}
1126 
1127 	/* Check if the label has a / in it */
1128 	if (strchr(items[3].text, '/') != NULL) {
1129 		dialog_msgbox("Error", "Label contains a /, which is not an "
1130 		    "allowed character.", 0, 0, TRUE);
1131 		goto addpartform;
1132 	}
1133 
1134 	/* Warn if no mountpoint set */
1135 	if (strcmp(items[0].text, "freebsd-ufs") == 0 &&
1136 	    items[2].text[0] != '/') {
1137 		choice = 0;
1138 		if (interactive) {
1139 			dialog_vars.defaultno = TRUE;
1140 			choice = dialog_yesno("Warning",
1141 			    "This partition does not have a valid mountpoint "
1142 			    "(for the partition from which you intend to boot the "
1143 			    "operating system, the mountpoint should be /). Are you "
1144 			    "sure you want to continue?"
1145 			, 0, 0);
1146 			dialog_vars.defaultno = FALSE;
1147 		}
1148 		if (choice == 1) /* cancel */
1149 			goto addpartform;
1150 	}
1151 
1152 	/*
1153 	 * Error if this scheme needs nested partitions, this is one, and
1154 	 * a mountpoint was set.
1155 	 */
1156 	if (strcmp(items[0].text, "freebsd") == 0 &&
1157 	    strlen(items[2].text) > 0) {
1158 		dialog_msgbox("Error", "Partitions of type \"freebsd\" are "
1159 		    "nested BSD-type partition schemes and cannot have "
1160 		    "mountpoints. After creating one, select it and press "
1161 		    "Create again to add the actual file systems.", 0, 0, TRUE);
1162 		goto addpartform;
1163 	}
1164 
1165 	/* If this is the root partition, check that this scheme is bootable */
1166 	if (strcmp(items[2].text, "/") == 0 && !is_scheme_bootable(scheme)) {
1167 		char message[512];
1168 		sprintf(message, "This partition scheme (%s) is not bootable "
1169 		    "on this platform. Are you sure you want to proceed?",
1170 		    scheme);
1171 		dialog_vars.defaultno = TRUE;
1172 		choice = dialog_yesno("Warning", message, 0, 0);
1173 		dialog_vars.defaultno = FALSE;
1174 		if (choice == 1) /* cancel */
1175 			goto addpartform;
1176 	}
1177 
1178 	/* If this is the root partition, check that this fs is bootable */
1179 	if (strcmp(items[2].text, "/") == 0 && !is_fs_bootable(scheme,
1180 	    items[0].text)) {
1181 		char message[512];
1182 		sprintf(message, "This file system (%s) is not bootable "
1183 		    "on this system. Are you sure you want to proceed?",
1184 		    items[0].text);
1185 		dialog_vars.defaultno = TRUE;
1186 		choice = dialog_yesno("Warning", message, 0, 0);
1187 		dialog_vars.defaultno = FALSE;
1188 		if (choice == 1) /* cancel */
1189 			goto addpartform;
1190 	}
1191 
1192 	/*
1193 	 * If this is the root partition, and we need a boot partition, ask
1194 	 * the user to add one.
1195 	 */
1196 
1197 	if ((strcmp(items[0].text, "freebsd") == 0 ||
1198 	    strcmp(items[2].text, "/") == 0) && bootpart_size(scheme) > 0) {
1199 		size_t bytes = add_boot_partition(geom, pp, scheme,
1200 		    interactive);
1201 
1202 		/* Now adjust the part we are really adding forward */
1203 		if (bytes > 0) {
1204 			firstfree += bytes / sector;
1205 			size -= (bytes + stripe)/sector;
1206 			if (stripe > 0 && (firstfree*sector % stripe) != 0)
1207 				firstfree += (stripe - ((firstfree*sector) %
1208 				    stripe)) / sector;
1209 		}
1210 	}
1211 
1212 	r = gctl_get_handle();
1213 	gctl_ro_param(r, "class", -1, "PART");
1214 	gctl_ro_param(r, "arg0", -1, geom->lg_name);
1215 	gctl_ro_param(r, "flags", -1, GPART_FLAGS);
1216 	gctl_ro_param(r, "verb", -1, "add");
1217 
1218 	gctl_ro_param(r, "type", -1, items[0].text);
1219 	snprintf(sizestr, sizeof(sizestr), "%jd", size);
1220 	gctl_ro_param(r, "size", -1, sizestr);
1221 	snprintf(startstr, sizeof(startstr), "%jd", firstfree);
1222 	gctl_ro_param(r, "start", -1, startstr);
1223 	if (items[3].text[0] != '\0')
1224 		gctl_ro_param(r, "label", -1, items[3].text);
1225 	gctl_rw_param(r, "output", sizeof(output), output);
1226 	errstr = gctl_issue(r);
1227 	if (errstr != NULL && errstr[0] != '\0') {
1228 		gpart_show_error("Error", NULL, errstr);
1229 		gctl_free(r);
1230 		goto addpartform;
1231 	}
1232 	newpartname = strtok(output, " ");
1233 	gctl_free(r);
1234 
1235 	/*
1236 	 * Try to destroy any geom that gpart picked up already here from
1237 	 * dirty blocks.
1238 	 */
1239 	r = gctl_get_handle();
1240 	gctl_ro_param(r, "class", -1, "PART");
1241 	gctl_ro_param(r, "arg0", -1, newpartname);
1242 	gctl_ro_param(r, "flags", -1, GPART_FLAGS);
1243 	junk = 1;
1244 	gctl_ro_param(r, "force", sizeof(junk), &junk);
1245 	gctl_ro_param(r, "verb", -1, "destroy");
1246 	gctl_issue(r); /* Error usually expected and non-fatal */
1247 	gctl_free(r);
1248 
1249 
1250 	if (strcmp(items[0].text, "freebsd") == 0)
1251 		gpart_partition(newpartname, "BSD");
1252 	else
1253 		set_default_part_metadata(newpartname, scheme,
1254 		    items[0].text, items[2].text, newfs);
1255 
1256 	for (i = 0; i < nitems(items); i++)
1257 		if (items[i].text_free)
1258 			free(items[i].text);
1259 
1260 	if (partname != NULL)
1261 		*partname = strdup(newpartname);
1262 }
1263 
1264 void
1265 gpart_delete(struct gprovider *pp)
1266 {
1267 	struct gconfig *gc;
1268 	struct ggeom *geom;
1269 	struct gconsumer *cp;
1270 	struct gctl_req *r;
1271 	const char *errstr;
1272 	intmax_t idx;
1273 	int is_partition;
1274 
1275 	/* Is it a partition? */
1276 	is_partition = (strcmp(pp->lg_geom->lg_class->lg_name, "PART") == 0);
1277 
1278 	/* Find out if this is the root of a gpart geom */
1279 	geom = NULL;
1280 	LIST_FOREACH(cp, &pp->lg_consumers, lg_consumers)
1281 		if (strcmp(cp->lg_geom->lg_class->lg_name, "PART") == 0) {
1282 			geom = cp->lg_geom;
1283 			break;
1284 		}
1285 
1286 	/* If so, destroy all children */
1287 	if (geom != NULL) {
1288 		gpart_destroy(geom);
1289 
1290 		/* If this is a partition, revert it, so it can be deleted */
1291 		if (is_partition) {
1292 			r = gctl_get_handle();
1293 			gctl_ro_param(r, "class", -1, "PART");
1294 			gctl_ro_param(r, "arg0", -1, geom->lg_name);
1295 			gctl_ro_param(r, "verb", -1, "undo");
1296 			gctl_issue(r); /* Ignore non-fatal errors */
1297 			gctl_free(r);
1298 		}
1299 	}
1300 
1301 	/*
1302 	 * If this is not a partition, see if that is a problem, complain if
1303 	 * necessary, and return always, since we need not do anything further,
1304 	 * error or no.
1305 	 */
1306 	if (!is_partition) {
1307 		if (geom == NULL)
1308 			dialog_msgbox("Error",
1309 			    "Only partitions can be deleted.", 0, 0, TRUE);
1310 		return;
1311 	}
1312 
1313 	r = gctl_get_handle();
1314 	gctl_ro_param(r, "class", -1, pp->lg_geom->lg_class->lg_name);
1315 	gctl_ro_param(r, "arg0", -1, pp->lg_geom->lg_name);
1316 	gctl_ro_param(r, "flags", -1, GPART_FLAGS);
1317 	gctl_ro_param(r, "verb", -1, "delete");
1318 
1319 	LIST_FOREACH(gc, &pp->lg_config, lg_config) {
1320 		if (strcmp(gc->lg_name, "index") == 0) {
1321 			idx = atoi(gc->lg_val);
1322 			gctl_ro_param(r, "index", sizeof(idx), &idx);
1323 			break;
1324 		}
1325 	}
1326 
1327 	errstr = gctl_issue(r);
1328 	if (errstr != NULL && errstr[0] != '\0') {
1329 		gpart_show_error("Error", NULL, errstr);
1330 		gctl_free(r);
1331 		return;
1332 	}
1333 
1334 	gctl_free(r);
1335 
1336 	delete_part_metadata(pp->lg_name);
1337 }
1338 
1339 void
1340 gpart_revert_all(struct gmesh *mesh)
1341 {
1342 	struct gclass *classp;
1343 	struct gconfig *gc;
1344 	struct ggeom *gp;
1345 	struct gctl_req *r;
1346 	const char *modified;
1347 
1348 	LIST_FOREACH(classp, &mesh->lg_class, lg_class) {
1349 		if (strcmp(classp->lg_name, "PART") == 0)
1350 			break;
1351 	}
1352 
1353 	if (strcmp(classp->lg_name, "PART") != 0) {
1354 		dialog_msgbox("Error", "gpart not found!", 0, 0, TRUE);
1355 		return;
1356 	}
1357 
1358 	LIST_FOREACH(gp, &classp->lg_geom, lg_geom) {
1359 		modified = "true"; /* XXX: If we don't know (kernel too old),
1360 				    * assume there are modifications. */
1361 		LIST_FOREACH(gc, &gp->lg_config, lg_config) {
1362 			if (strcmp(gc->lg_name, "modified") == 0) {
1363 				modified = gc->lg_val;
1364 				break;
1365 			}
1366 		}
1367 
1368 		if (strcmp(modified, "false") == 0)
1369 			continue;
1370 
1371 		r = gctl_get_handle();
1372 		gctl_ro_param(r, "class", -1, "PART");
1373 		gctl_ro_param(r, "arg0", -1, gp->lg_name);
1374 		gctl_ro_param(r, "verb", -1, "undo");
1375 
1376 		gctl_issue(r);
1377 		gctl_free(r);
1378 	}
1379 }
1380 
1381 void
1382 gpart_commit(struct gmesh *mesh)
1383 {
1384 	struct partition_metadata *md;
1385 	struct gclass *classp;
1386 	struct ggeom *gp;
1387 	struct gconfig *gc;
1388 	struct gconsumer *cp;
1389 	struct gprovider *pp;
1390 	struct gctl_req *r;
1391 	const char *errstr;
1392 	const char *modified;
1393 	const char *rootfs;
1394 
1395 	LIST_FOREACH(classp, &mesh->lg_class, lg_class) {
1396 		if (strcmp(classp->lg_name, "PART") == 0)
1397 			break;
1398 	}
1399 
1400 	/* Figure out what filesystem / uses */
1401 	rootfs = "ufs"; /* Assume ufs if nothing else present */
1402 	TAILQ_FOREACH(md, &part_metadata, metadata) {
1403 		if (md->fstab != NULL && strcmp(md->fstab->fs_file, "/") == 0) {
1404 			rootfs = md->fstab->fs_vfstype;
1405 			break;
1406 		}
1407 	}
1408 
1409 	if (strcmp(classp->lg_name, "PART") != 0) {
1410 		dialog_msgbox("Error", "gpart not found!", 0, 0, TRUE);
1411 		return;
1412 	}
1413 
1414 	LIST_FOREACH(gp, &classp->lg_geom, lg_geom) {
1415 		modified = "true"; /* XXX: If we don't know (kernel too old),
1416 				    * assume there are modifications. */
1417 		LIST_FOREACH(gc, &gp->lg_config, lg_config) {
1418 			if (strcmp(gc->lg_name, "modified") == 0) {
1419 				modified = gc->lg_val;
1420 				break;
1421 			}
1422 		}
1423 
1424 		if (strcmp(modified, "false") == 0)
1425 			continue;
1426 
1427 		/* Add bootcode if necessary, before the commit */
1428 		md = get_part_metadata(gp->lg_name, 0);
1429 		if (md != NULL && md->bootcode)
1430 			gpart_bootcode(gp);
1431 
1432 		/* Now install partcode on its partitions, if necessary */
1433 		LIST_FOREACH(pp, &gp->lg_provider, lg_provider) {
1434 			md = get_part_metadata(pp->lg_name, 0);
1435 			if (md == NULL || !md->bootcode)
1436 				continue;
1437 
1438 			/* Mark this partition active if that's required */
1439 			gpart_activate(pp);
1440 
1441 			/* Check if the partition has sub-partitions */
1442 			LIST_FOREACH(cp, &pp->lg_consumers, lg_consumers)
1443 				if (strcmp(cp->lg_geom->lg_class->lg_name,
1444 				    "PART") == 0)
1445 					break;
1446 
1447 			if (cp == NULL) /* No sub-partitions */
1448 				gpart_partcode(pp, rootfs);
1449 		}
1450 
1451 		r = gctl_get_handle();
1452 		gctl_ro_param(r, "class", -1, "PART");
1453 		gctl_ro_param(r, "arg0", -1, gp->lg_name);
1454 		gctl_ro_param(r, "verb", -1, "commit");
1455 
1456 		errstr = gctl_issue(r);
1457 		if (errstr != NULL && errstr[0] != '\0')
1458 			gpart_show_error("Error", NULL, errstr);
1459 		gctl_free(r);
1460 	}
1461 }
1462 
1463