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