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