zfsboot revision 267061
1#!/bin/sh
2#-
3# Copyright (c) 2013 Allan Jude
4# Copyright (c) 2013 Devin Teske
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: stable/10/usr.sbin/bsdinstall/scripts/zfsboot 267061 2014-06-04 15:31:57Z roberto $
29#
30############################################################ INCLUDES
31
32BSDCFG_SHARE="/usr/share/bsdconfig"
33. $BSDCFG_SHARE/common.subr || exit 1
34f_dprintf "%s: loading includes..." "$0"
35f_include $BSDCFG_SHARE/device.subr
36f_include $BSDCFG_SHARE/dialog.subr
37f_include $BSDCFG_SHARE/password/password.subr
38f_include $BSDCFG_SHARE/variable.subr
39
40############################################################ CONFIGURATION
41
42#
43# Default name of the boot-pool
44#
45: ${ZFSBOOT_POOL_NAME:=zroot}
46
47#
48# Default options to use when creating zroot pool
49#
50: ${ZFSBOOT_POOL_CREATE_OPTIONS:=-O compress=lz4 -O atime=off}
51
52#
53# Default name for the boot environment parent dataset
54#
55: ${ZFSBOOT_BEROOT_NAME:=ROOT}
56
57#
58# Default name for the primany boot environment
59#
60: ${ZFSBOOT_BOOTFS_NAME:=default}
61
62#
63# Default Virtual Device (vdev) type to create
64#
65: ${ZFSBOOT_VDEV_TYPE:=stripe}
66
67#
68# Should we use gnop(8) to configure a transparent mapping to 4K sectors?
69#
70: ${ZFSBOOT_GNOP_4K_FORCE_ALIGN:=1}
71
72#
73# Should we use geli(8) to encrypt the drives?
74# NB: Automatically enables ZFSBOOT_BOOT_POOL
75#
76: ${ZFSBOOT_GELI_ENCRYPTION=}
77
78#
79# Default path to the geli(8) keyfile used in drive encryption
80#
81: ${ZFSBOOT_GELI_KEY_FILE:=/boot/encryption.key}
82
83#
84# Create a separate boot pool?
85# NB: Automatically set when using geli(8) or MBR
86#
87: ${ZFSBOOT_BOOT_POOL=}
88
89#
90# Options to use when creating separate boot pool (if any)
91#
92: ${ZFSBOOT_BOOT_POOL_CREATE_OPTIONS:=}
93
94#
95# Default name for boot pool when enabled (e.g., geli(8) or MBR)
96#
97: ${ZFSBOOT_BOOT_POOL_NAME:=bootpool}
98
99#
100# Default size for boot pool when enabled (e.g., geli(8) or MBR)
101#
102: ${ZFSBOOT_BOOT_POOL_SIZE:=2g}
103
104#
105# Default disks to use (always empty unless being scripted)
106#
107: ${ZFSBOOT_DISKS:=}
108
109#
110# Default partitioning scheme to use on disks
111#
112: ${ZFSBOOT_PARTITION_SCHEME:=GPT}
113
114#
115# How much swap to put on each block device in the boot zpool
116# NOTE: Value passed to gpart(8); which supports SI unit suffixes.
117#
118: ${ZFSBOOT_SWAP_SIZE:=2g}
119
120#
121# Should we use geli(8) to encrypt the swap?
122#
123: ${ZFSBOOT_SWAP_ENCRYPTION=}
124
125#
126# Should we use gmirror(8) to mirror the swap?
127#
128: ${ZFSBOOT_SWAP_MIRROR=}
129
130#
131# Default ZFS datasets for root zpool
132#
133# NOTE: Requires /tmp, /var/tmp, /$ZFSBOOT_BOOTFS_NAME/$ZFSBOOT_BOOTFS_NAME
134# NOTE: Anything after pound/hash character [#] is ignored as a comment.
135#
136f_isset ZFSBOOT_DATASETS || ZFSBOOT_DATASETS="
137	# DATASET	OPTIONS (comma or space separated; or both)
138
139	# Boot Environment [BE] root and default boot dataset
140	/$ZFSBOOT_BEROOT_NAME				mountpoint=none
141	/$ZFSBOOT_BEROOT_NAME/$ZFSBOOT_BOOTFS_NAME	mountpoint=/
142
143	# Compress /tmp, allow exec but not setuid
144	/tmp		mountpoint=/tmp,exec=on,setuid=off
145
146	# Don't mount /usr so that 'base' files go to the BEROOT
147	/usr		mountpoint=/usr,canmount=off
148
149	# Home directories separated so they are common to all BEs
150	/usr/home	# NB: /home is a symlink to /usr/home
151
152	# Ports tree
153	/usr/ports	setuid=off
154
155	# Source tree (compressed)
156	/usr/src
157
158	# Create /var and friends
159	/var		mountpoint=/var
160	/var/crash	exec=off,setuid=off
161	/var/log	exec=off,setuid=off
162	/var/mail	atime=on
163	/var/tmp	setuid=off
164" # END-QUOTE
165
166#
167# If interactive and the user has not explicitly chosen a vdev type or disks,
168# make the user confirm scripted/default choices when proceeding to install.
169#
170: ${ZFSBOOT_CONFIRM_LAYOUT:=1}
171
172############################################################ GLOBALS
173
174#
175# Format of a line in printf(1) syntax to add to fstab(5)
176#
177FSTAB_FMT="%s\t\t%s\t%s\t%s\t\t%s\t%s\n"
178
179#
180# Command strings for various tasks
181#
182CHMOD_MODE='chmod %s "%s"'
183DD_WITH_OPTIONS='dd if="%s" of="%s" %s'
184ECHO_APPEND='echo "%s" >> "%s"'
185GELI_ATTACH='geli attach -j - -k "%s" "%s"'
186GELI_DETACH_F='geli detach -f "%s"'
187GELI_PASSWORD_INIT='geli init -b -B "%s" -e %s -J - -K "%s" -l 256 -s 4096 "%s"'
188GNOP_CREATE='gnop create -S 4096 "%s"'
189GNOP_DESTROY='gnop destroy "%s"'
190GPART_ADD='gpart add -t %s "%s"'
191GPART_ADD_INDEX='gpart add -i %s -t %s "%s"'
192GPART_ADD_INDEX_WITH_SIZE='gpart add -i %s -t %s -s %s "%s"'
193GPART_ADD_LABEL='gpart add -l %s -t %s "%s"'
194GPART_ADD_LABEL_WITH_SIZE='gpart add -l %s -t %s -s %s "%s"'
195GPART_BOOTCODE='gpart bootcode -b "%s" "%s"'
196GPART_BOOTCODE_PART='gpart bootcode -b "%s" -p "%s" -i %s "%s"'
197GPART_CREATE='gpart create -s %s "%s"'
198GPART_DESTROY_F='gpart destroy -F "%s"'
199GPART_SET_ACTIVE='gpart set -a active -i %s "%s"'
200GRAID_DELETE='graid delete "%s"'
201LN_SF='ln -sf "%s" "%s"'
202MKDIR_P='mkdir -p "%s"'
203MOUNT_TYPE='mount -t %s "%s" "%s"'
204PRINTF_CONF="printf '%s=\"%%s\"\\\n' %s >> \"%s\""
205PRINTF_FSTAB='printf "$FSTAB_FMT" "%s" "%s" "%s" "%s" "%s" "%s" >> "%s"'
206SHELL_TRUNCATE=':> "%s"'
207SWAP_GMIRROR_LABEL='gmirror label swap %s'
208UMOUNT='umount "%s"'
209ZFS_CREATE_WITH_OPTIONS='zfs create %s "%s"'
210ZFS_SET='zfs set "%s" "%s"'
211ZFS_UNMOUNT='zfs unmount "%s"'
212ZPOOL_CREATE_WITH_OPTIONS='zpool create %s "%s" %s %s'
213ZPOOL_DESTROY='zpool destroy "%s"'
214ZPOOL_EXPORT='zpool export "%s"'
215ZPOOL_IMPORT_WITH_OPTIONS='zpool import %s "%s"'
216ZPOOL_LABELCLEAR_F='zpool labelclear -f "%s"'
217ZPOOL_SET='zpool set %s "%s"'
218
219#
220# Strings that should be moved to an i18n file and loaded with f_include_lang()
221#
222hline_alnum_arrows_punc_tab_enter="Use alnum, arrows, punctuation, TAB or ENTER"
223hline_arrows_space_tab_enter="Use arrows, SPACE, TAB or ENTER"
224hline_arrows_tab_enter="Press arrows, TAB or ENTER"
225msg_an_unknown_error_occurred="An unknown error occurred"
226msg_back="Back"
227msg_cancel="Cancel"
228msg_change_selection="Change Selection"
229msg_configure_options="Configure Options:"
230msg_detailed_disk_info="gpart(8) show %s:\n%s\n\ncamcontrol(8) inquiry %s:\n%s\n\n\ncamcontrol(8) identify %s:\n%s\n"
231msg_disk_info="Disk Info"
232msg_disk_info_help="Get detailed information on disk device(s)"
233msg_disk_singular="disk"
234msg_disk_plural="disks"
235msg_encrypt_disks="Encrypt Disks?"
236msg_encrypt_disks_help="Use geli(8) to encrypt all data partitions"
237msg_error="Error"
238msg_force_4k_sectors="Force 4K Sectors?"
239msg_force_4k_sectors_help="Use gnop(8) to configure forced 4K sector alignment"
240msg_freebsd_installer="FreeBSD Installer"
241msg_geli_password="Enter a strong passphrase, used to protect your encryption keys. You will be required to enter this passphrase each time the system is booted"
242msg_geli_setup="Initializing encryption on selected disks,\n this will take several seconds per disk"
243msg_install="Install"
244msg_install_desc="Proceed with Installation"
245msg_install_help="Create ZFS boot pool with displayed options"
246msg_invalid_boot_pool_size="Invalid boot pool size \`%s'"
247msg_invalid_disk_argument="Invalid disk argument \`%s'"
248msg_invalid_index_argument="Invalid index argument \`%s'"
249msg_invalid_swap_size="Invalid swap size \`%s'"
250msg_invalid_virtual_device_type="Invalid Virtual Device type \`%s'"
251msg_last_chance_are_you_sure="Last Chance! Are you sure you want to destroy\nthe current contents of the following disks:\n\n   %s"
252msg_last_chance_are_you_sure_color='\\ZrLast Chance!\\ZR Are you \\Z1sure\\Zn you want to \\Zr\\Z1destroy\\Zn\nthe current contents of the following disks:\n\n   %s'
253msg_mirror_desc="Mirror - n-Way Mirroring"
254msg_mirror_help="[2+ Disks] Mirroring provides the best performance, but the least storage"
255msg_missing_disk_arguments="missing disk arguments"
256msg_missing_one_or_more_scripted_disks="Missing one or more scripted disks!"
257msg_no="NO"
258msg_no_disks_present_to_configure="No disk(s) present to configure"
259msg_no_disks_selected="No disks selected."
260msg_not_enough_disks_selected="Not enough disks selected. (%u < %u minimum)"
261msg_null_disk_argument="NULL disk argument"
262msg_null_index_argument="NULL index argument"
263msg_null_poolname="NULL poolname"
264msg_ok="OK"
265msg_partition_scheme="Partition Scheme"
266msg_partition_scheme_help="Toggle between GPT and MBR partitioning schemes"
267msg_please_enter_a_name_for_your_zpool="Please enter a name for your zpool:"
268msg_please_enter_amount_of_swap_space="Please enter amount of swap space (SI-Unit suffixes\nrecommended; e.g., \`2g' for 2 Gigabytes):"
269msg_please_select_one_or_more_disks="Please select one or more disks to create a zpool:"
270msg_pool_name="Pool Name"
271msg_pool_name_cannot_be_empty="Pool name cannot be empty."
272msg_pool_name_help="Customize the name of the zpool to be created (Required)"
273msg_pool_type_disks="Pool Type/Disks:"
274msg_pool_type_disks_help="Choose type of ZFS Virtual Device and disks to use (Required)"
275msg_processing_selection="Processing selection..."
276msg_raidz1_desc="RAID-Z1 - Single Redundant RAID"
277msg_raidz1_help="[3+ Disks] Withstand failure of 1 disk. Recommended for: 3, 5 or 9 disks"
278msg_raidz2_desc="RAID-Z2 - Double Redundant RAID"
279msg_raidz2_help="[4+ Disks] Withstand failure of 2 disks. Recommended for: 4, 6 or 10 disks"
280msg_raidz3_desc="RAID-Z3 - Triple Redundant RAID"
281msg_raidz3_help="[5+ Disks] Withstand failure of 3 disks. Recommended for: 5, 7 or 11 disks"
282msg_rescan_devices="Rescan Devices"
283msg_rescan_devices_help="Scan for device changes"
284msg_select="Select"
285msg_select_a_disk_device="Select a disk device"
286msg_select_virtual_device_type="Select Virtual Device type:"
287msg_stripe_desc="Stripe - No Redundancy"
288msg_stripe_help="[1+ Disks] Striping provides maximum storage but no redundancy"
289msg_swap_encrypt="Encrypt Swap?"
290msg_swap_encrypt_help="Encrypt swap partitions with temporary keys, discarded on reboot"
291msg_swap_mirror="Mirror Swap?"
292msg_swap_mirror_help="Mirror swap partitions for redundancy, breaks crash dumps"
293msg_swap_size="Swap Size"
294msg_swap_size_help="Customize how much swap space is allocated to each selected disk"
295msg_these_disks_are_too_small="These disks are too small given the amount of requested\nswap (%s) and/or geli(8) (%s) partitions, which would\ntake 50%% or more of each of the following selected disk\ndevices (not recommended):\n\n  %s\n\nRecommend changing partition size(s) and/or selecting a\ndifferent set of devices."
296msg_unable_to_get_disk_capacity="Unable to get disk capacity of \`%s'"
297msg_unsupported_partition_scheme="%s is an unsupported partition scheme"
298msg_user_cancelled="User Cancelled."
299msg_yes="YES"
300msg_zfs_configuration="ZFS Configuration"
301
302############################################################ FUNCTIONS
303
304# dialog_menu_main
305#
306# Display the dialog(1)-based application main menu.
307#
308dialog_menu_main()
309{
310	local title="$DIALOG_TITLE"
311	local btitle="$DIALOG_BACKTITLE"
312	local prompt="$msg_configure_options"
313	local force4k="$msg_no"
314	local usegeli="$msg_no"
315	local swapgeli="$msg_no"
316	local swapmirror="$msg_no"
317	[ "$ZFSBOOT_GNOP_4K_FORCE_ALIGN" ] && force4k="$msg_yes"
318	[ "$ZFSBOOT_GELI_ENCRYPTION" ] && usegeli="$msg_yes"
319	[ "$ZFSBOOT_SWAP_ENCRYPTION" ] && swapgeli="$msg_yes"
320	[ "$ZFSBOOT_SWAP_MIRROR" ] && swapmirror="$msg_yes"
321	local disks n disks_grammar
322	f_count n $ZFSBOOT_DISKS
323	{ [ $n -eq 1 ] && disks_grammar=$msg_disk_singular; } || 
324		disks_grammar=$msg_disk_plural # grammar
325	local menu_list="
326		'>>> $msg_install'        '$msg_install_desc'
327		                          '$msg_install_help'
328		'T $msg_pool_type_disks'  '$ZFSBOOT_VDEV_TYPE: $n $disks_grammar'
329                                          '$msg_pool_type_disks_help'
330		'- $msg_rescan_devices'   '*'
331		                          '$msg_rescan_devices_help'
332		'- $msg_disk_info'        '*'
333		                          '$msg_disk_info_help'
334		'N $msg_pool_name'        '$ZFSBOOT_POOL_NAME'
335		                          '$msg_pool_name_help'
336		'4 $msg_force_4k_sectors' '$force4k'
337		                          '$msg_force_4k_sectors_help'
338		'E $msg_encrypt_disks'    '$usegeli'
339		                          '$msg_encrypt_disks_help'
340		'P $msg_partition_scheme' '$ZFSBOOT_PARTITION_SCHEME'
341		                          '$msg_partition_scheme_help'
342		'S $msg_swap_size'        '$ZFSBOOT_SWAP_SIZE'
343		                          '$msg_swap_size_help'
344		'M $msg_swap_mirror'      '$swapmirror'
345		                          '$msg_swap_mirror_help'
346		'W $msg_swap_encrypt'     '$swapgeli'
347		                          '$msg_swap_encrypt_help'
348	" # END-QUOTE
349	local defaultitem= # Calculated below
350	local hline="$hline_alnum_arrows_punc_tab_enter"
351
352	local height width rows
353	eval f_dialog_menu_with_help_size height width rows \
354		\"\$title\" \"\$btitle\" \"\$prompt\" \"\$hline\" $menu_list
355
356	# Obtain default-item from previously stored selection
357	f_dialog_default_fetch defaultitem
358
359	local menu_choice
360	menu_choice=$( eval $DIALOG \
361		--title \"\$title\"              \
362		--backtitle \"\$btitle\"         \
363		--hline \"\$hline\"              \
364		--item-help                      \
365		--ok-label \"\$msg_select\"      \
366		--cancel-label \"\$msg_cancel\"  \
367		--default-item \"\$defaultitem\" \
368		--menu \"\$prompt\"              \
369		$height $width $rows             \
370		$menu_list                       \
371		2>&1 >&$DIALOG_TERMINAL_PASSTHRU_FD
372	)
373	local retval=$?
374	f_dialog_data_sanitize menu_choice
375	f_dialog_menutag_store "$menu_choice"
376
377	# Only update default-item on success
378	[ $retval -eq $DIALOG_OK ] && f_dialog_default_store "$menu_choice"
379
380	return $retval
381}
382
383# dialog_last_chance $disks ...
384#
385# Display a list of the disks that the user is about to destroy. The default
386# action is to return error status unless the user explicitly (non-default)
387# selects "Yes" from the noyes dialog.
388#
389dialog_last_chance()
390{
391	local title="$DIALOG_TITLE"
392	local btitle="$DIALOG_BACKTITLE"
393	local prompt # Calculated below
394	local hline="$hline_arrows_tab_enter"
395
396	local height=8 width=50 prefix="   "
397	local plen=${#prefix} list= line=
398	local max_width=$(( $width - 3 - $plen ))
399
400	local yes no defaultno extra_args format
401	if [ "$USE_XDIALOG" ]; then
402		yes=ok no=cancel defaultno=default-no
403		extra_args="--wrap --left"
404		format="$msg_last_chance_are_you_sure"
405	else
406		yes=yes no=no defaultno=defaultno
407		extra_args="--colors --cr-wrap"
408		format="$msg_last_chance_are_you_sure_color"
409	fi
410
411	local disk line_width
412	for disk in $*; do
413		if [ "$line" ]; then
414			line_width=${#line}
415		else
416			line_width=$plen
417		fi
418		line_width=$(( $line_width + 1 + ${#disk} ))
419		# Add newline before disk if it would exceed max_width
420		if [ $line_width -gt $max_width ]; then
421			list="$list$line\n"
422			line="$prefix"
423			height=$(( $height + 1 ))
424		fi
425		# Add the disk to the list
426		line="$line $disk"
427	done
428	# Append the left-overs
429	if [ "${line#$prefix}" ]; then
430		list="$list$line"
431		height=$(( $height + 1 ))
432	fi
433
434	# Add height for Xdialog(1)
435	[ "$USE_XDIALOG" ] && height=$(( $height + $height / 5 + 3 ))
436
437	prompt=$( printf "$format" "$list" )
438	f_dprintf "%s: Last Chance!" "$0"
439	$DIALOG \
440		--title "$title"        \
441		--backtitle "$btitle"   \
442		--hline "$hline"        \
443		--$defaultno            \
444		--$yes-label "$msg_yes" \
445		--$no-label "$msg_no"   \
446		$extra_args             \
447		--yesno "$prompt" $height $width
448}
449
450# dialog_menu_layout
451#
452# Configure Virtual Device type and disks to use for the ZFS boot pool. User
453# must select enough disks to satisfy the chosen vdev type.
454#
455dialog_menu_layout()
456{
457	local funcname=dialog_menu_layout
458	local title="$DIALOG_TITLE"
459	local btitle="$DIALOG_BACKTITLE"
460	local vdev_prompt="$msg_select_virtual_device_type"
461	local disk_prompt="$msg_please_select_one_or_more_disks"
462	local vdev_menu_list="
463		'stripe' '$msg_stripe_desc' '$msg_stripe_help'
464		'mirror' '$msg_mirror_desc' '$msg_mirror_help'
465		'raidz1' '$msg_raidz1_desc' '$msg_raidz1_help'
466		'raidz2' '$msg_raidz2_desc' '$msg_raidz2_help'
467		'raidz3' '$msg_raidz3_desc' '$msg_raidz3_help'
468	" # END-QUOTE
469	local disk_check_list= # Calculated below
470	local vdev_hline="$hline_arrows_tab_enter"
471	local disk_hline="$hline_arrows_space_tab_enter"
472
473	# Warn the user if vdev type is not valid
474	case "$ZFSBOOT_VDEV_TYPE" in
475	stripe|mirror|raidz1|raidz2|raidz3) : known good ;;
476	*)
477		f_dprintf "%s: Invalid virtual device type \`%s'" \
478			  $funcname "$ZFSBOOT_VDEV_TYPE"
479		f_show_err "$msg_invalid_virtual_device_type" \
480			   "$ZFSBOOT_VDEV_TYPE"
481		f_interactive || return $FAILURE
482	esac
483
484	# Calculate size of vdev menu once only
485	local vheight vwidth vrows
486	eval f_dialog_menu_with_help_size vheight vwidth vrows \
487		\"\$title\" \"\$btitle\" \"\$vdev_prompt\" \"\$vdev_hline\" \
488		$vdev_menu_list
489
490	# Get a list of probed disk devices
491	local disks=
492	debug= f_device_find "" $DEVICE_TYPE_DISK disks
493
494	# Prune out mounted md(4) devices that may be part of the boot process
495	local disk name new_list=
496	for disk in $disks; do
497		debug= $disk get name name
498		case "$name" in
499		md[0-9]*) f_mounted -b "/dev/$name" && continue ;;
500		esac
501		new_list="$new_list $disk"
502	done
503	disks="${new_list# }"
504
505	# Debugging
506	if [ "$debug" ]; then
507		local disk_names=
508		for disk in $disks; do
509			debug= $disk get name name
510			disk_names="$disk_names $name"
511		done
512		f_dprintf "$funcname: disks=[%s]" "${disk_names# }"
513	fi
514
515	if [ ! "$disks" ]; then
516		f_dprintf "No disk(s) present to configure"
517		f_show_err "$msg_no_disks_present_to_configure"
518		return $FAILURE
519	fi
520
521	# Lets sort the disks array to be more user friendly
522	f_device_sort_by name disks disks
523
524	#
525	# Operate in a loop so we can (if interactive) repeat if not enough
526	# disks are selected to satisfy the chosen vdev type or user wants to
527	# back-up to the previous menu.
528	#
529	local vardisk ndisks onoff selections vdev_choice breakout device
530	local valid_disks all_valid want_disks desc height width rows
531	while :; do
532		#
533		# Confirm the vdev type that was selected
534		#
535		if f_interactive && [ "$ZFSBOOT_CONFIRM_LAYOUT" ]; then
536			vdev_choice=$( eval $DIALOG \
537				--title \"\$title\"              \
538				--backtitle \"\$btitle\"         \
539				--hline \"\$vdev_hline\"         \
540				--ok-label \"\$msg_ok\"          \
541				--cancel-label \"\$msg_cancel\"  \
542				--item-help                      \
543				--default-item \"\$ZFSBOOT_VDEV_TYPE\" \
544				--menu \"\$vdev_prompt\"         \
545				$vheight $vwidth $vrows          \
546				$vdev_menu_list                  \
547				2>&1 >&$DIALOG_TERMINAL_PASSTHRU_FD
548			) || return $?
549				# Exit if user pressed ESC or chose Cancel/No
550			f_dialog_data_sanitize vdev_choice
551
552			ZFSBOOT_VDEV_TYPE="$vdev_choice"
553			f_dprintf "$funcname: ZFSBOOT_VDEV_TYPE=[%s]" \
554			          "$ZFSBOOT_VDEV_TYPE"
555		fi
556
557		# Determine the number of disks needed for this vdev type
558		want_disks=0
559		case "$ZFSBOOT_VDEV_TYPE" in
560		stripe) want_disks=1 ;;
561		mirror) want_disks=2 ;;
562		raidz1) want_disks=3 ;;
563		raidz2) want_disks=4 ;;
564		raidz3) want_disks=5 ;;
565		esac
566
567		#
568		# Warn the user if any scripted disks are invalid
569		#
570		valid_disks= all_valid=${ZFSBOOT_DISKS:+1} # optimism
571		for disk in $ZFSBOOT_DISKS; do
572			if debug= f_device_find -1 \
573				$disk $DEVICE_TYPE_DISK device
574			then
575				valid_disks="$valid_disks $disk"
576				continue
577			fi
578			f_dprintf "$funcname: \`%s' is not a real disk" "$disk"
579			all_valid=
580		done
581		if [ ! "$all_valid" ]; then
582			if [ "$ZFSBOOT_DISKS" ]; then
583				f_show_err \
584				    "$msg_missing_one_or_more_scripted_disks"
585			else
586				f_dprintf "No disks selected."
587				f_interactive ||
588					f_show_err "$msg_no_disks_selected"
589			fi
590			f_interactive || return $FAILURE
591		fi
592		ZFSBOOT_DISKS="${valid_disks# }"
593
594		#
595		# Short-circuit if we're running non-interactively
596		#
597		if ! f_interactive || [ ! "$ZFSBOOT_CONFIRM_LAYOUT" ]; then
598			f_count ndisks $ZFSBOOT_DISKS
599			[ $ndisks -ge $want_disks ] && break # to success
600
601			# Not enough disks selected
602			f_dprintf "$funcname: %s: %s (%u < %u minimum)" \
603				  "$ZFSBOOT_VDEV_TYPE" \
604			          "Not enough disks selected." \
605				  $ndisks $want_disks
606			f_interactive || return $FAILURE
607			msg_yes="$msg_change_selection" msg_no="$msg_cancel" \
608				f_yesno "%s: $msg_not_enough_disks_selected" \
609				"$ZFSBOOT_VDEV_TYPE" $ndisks $want_disks ||
610				return $FAILURE
611		fi
612
613		#
614		# Confirm the disks that were selected
615		# Loop until the user cancels or selects enough disks
616		#
617		breakout=
618		while :; do
619			# Loop over list of available disks, resetting state
620			for disk in $disks; do
621				f_isset _${disk}_status && _${disk}_status=
622			done
623
624			# Loop over list of selected disks and create temporary
625			# locals to map statuses onto up-to-date list of disks
626			for disk in $ZFSBOOT_DISKS; do
627				debug= f_device_find -1 \
628					$disk $DEVICE_TYPE_DISK disk
629				f_isset _${disk}_status ||
630					local _${disk}_status
631				_${disk}_status=on
632			done
633
634			# Create the checklist menu of discovered disk devices
635			disk_check_list=
636			for disk in $disks; do
637				desc=
638				$disk get name name
639				$disk get desc desc
640				f_shell_escape "$desc" desc
641				f_getvar _${disk}_status:-off onoff
642				disk_check_list="$disk_check_list
643					$name '$desc' $onoff"
644			done
645
646			eval f_dialog_checklist_size height width rows \
647				\"\$title\" \"\$btitle\" \"\$prompt\" \
648				\"\$hline\" $disk_check_list
649
650			selections=$( eval $DIALOG \
651				--title \"\$DIALOG_TITLE\"         \
652				--backtitle \"\$DIALOG_BACKTITLE\" \
653				--separate-output                  \
654				--hline \"\$hline\"                \
655				--ok-label \"\$msg_ok\"            \
656				--cancel-label \"\$msg_back\"      \
657				--checklist \"\$prompt\"           \
658				$height $width $rows               \
659				$disk_check_list                   \
660				2>&1 >&$DIALOG_TERMINAL_PASSTHRU_FD
661			) || break
662				# Loop if user pressed ESC or chose Cancel/No
663			f_dialog_data_sanitize selections
664
665			ZFSBOOT_DISKS="$selections"
666			f_dprintf "$funcname: ZFSBOOT_DISKS=[%s]" \
667			          "$ZFSBOOT_DISKS"
668
669			f_count ndisks $ZFSBOOT_DISKS
670			[ $ndisks -ge $want_disks ] &&
671				breakout=break && break
672
673			# Not enough disks selected
674			f_dprintf "$funcname: %s: %s (%u < %u minimum)" \
675				  "$ZFSBOOT_VDEV_TYPE" \
676			          "Not enough disks selected." \
677			          $ndisks $want_disks
678			msg_yes="$msg_change_selection" msg_no="$msg_cancel" \
679				f_yesno "%s: $msg_not_enough_disks_selected" \
680				"$ZFSBOOT_VDEV_TYPE" $ndisks $want_disks ||
681				break
682		done
683		[ "$breakout" = "break" ] && break
684		[ "$ZFSBOOT_CONFIRM_LAYOUT" ] || return $FAILURE
685	done
686
687	return $DIALOG_OK
688}
689
690# zfs_create_diskpart $disk $index
691#
692# For each block device to be used in the zpool, rather than just create the
693# zpool with the raw block devices (e.g., da0, da1, etc.) we create partitions
694# so we can have some real swap. This also provides wiggle room incase your
695# replacement drivers do not have the exact same sector counts.
696#
697# NOTE: $swapsize and $bootsize should be defined by the calling function.
698# NOTE: Sets $bootpart and $targetpart for the calling function.
699#
700zfs_create_diskpart()
701{
702	local funcname=zfs_create_diskpart
703	local disk="$1" index="$2"
704
705	# Check arguments
706	if [ ! "$disk" ]; then
707		f_dprintf "$funcname: NULL disk argument"
708		msg_error="$msg_error: $funcname" \
709			f_show_err "$msg_null_disk_argument"
710		return $FAILURE
711	fi
712	if [ "${disk#*[$IFS]}" != "$disk" ]; then
713		f_dprintf "$funcname: Invalid disk argument \`%s'" "$disk"
714		msg_error="$msg_error: $funcname" \
715			f_show_err "$msg_invalid_disk_argument" "$disk"
716		return $FAILURE
717	fi
718	if [ ! "$index" ]; then
719		f_dprintf "$funcname: NULL index argument"
720		msg_error="$msg_error: $funcname" \
721			f_show_err "$msg_null_index_argument"
722		return $FAILURE
723	fi
724	if ! f_isinteger "$index"; then
725		f_dprintf "$funcname: Invalid index argument \`%s'" "$index"
726		msg_error="$msg_error: $funcname" \
727			f_show_err "$msg_invalid_index_argument" "$index"
728		return $FAILURE
729	fi
730	f_dprintf "$funcname: disk=[%s] index=[%s]" "$disk" "$index"
731
732	# Check for unknown partition scheme before proceeding further
733	case "$ZFSBOOT_PARTITION_SCHEME" in
734	""|MBR|GPT) : known good ;;
735	*)
736		f_dprintf "$funcname: %s is an unsupported partition scheme" \
737		          "$ZFSBOOT_PARTITION_SCHEME"
738		msg_error="$msg_error: $funcname" f_show_err \
739			"$msg_unsupported_partition_scheme" \
740			"$ZFSBOOT_PARTITION_SCHEME"
741		return $FAILURE
742	esac
743
744	#
745	# Destroy whatever partition layout is currently on disk.
746	# NOTE: `-F' required to destroy if partitions still exist.
747	# NOTE: Failure is ok here, blank disk will have nothing to destroy.
748	#
749	f_dprintf "$funcname: Destroying all data/layouts on \`%s'..." "$disk"
750	f_eval_catch -d $funcname gpart "$GPART_DESTROY_F" $disk
751	f_eval_catch -d $funcname graid "$GRAID_DELETE" $disk
752	f_eval_catch -d $funcname zpool "$ZPOOL_LABELCLEAR_F" /dev/$disk
753
754	# Make doubly-sure backup GPT is destroyed
755	f_eval_catch -d $funcname gpart "$GPART_CREATE" gpt $disk
756	f_eval_catch -d $funcname gpart "$GPART_DESTROY_F" $disk
757
758	#
759	# Enable boot pool if encryption is desired
760	#
761	[ "$ZFSBOOT_GELI_ENCRYPTION" ] && ZFSBOOT_BOOT_POOL=1
762
763	#
764	# Lay down the desired type of partition scheme
765	#
766	local setsize mbrindex
767	case "$ZFSBOOT_PARTITION_SCHEME" in
768	""|GPT) f_dprintf "$funcname: Creating GPT layout..."
769		#
770		# 1. Create GPT layout using labels
771		#
772		f_eval_catch $funcname gpart "$GPART_CREATE" gpt $disk ||
773		             return $FAILURE
774
775		#
776		# 2. Add small freebsd-boot partition labeled `boot#'
777		#
778		f_eval_catch $funcname gpart "$GPART_ADD_LABEL_WITH_SIZE" \
779		             gptboot$index freebsd-boot 512k $disk ||
780		             return $FAILURE
781		f_eval_catch $funcname gpart "$GPART_BOOTCODE_PART" \
782		             /boot/pmbr /boot/gptzfsboot 1 $disk ||
783		             return $FAILURE
784
785		# NB: zpool will use the `zfs#' GPT labels
786		bootpart=p2 swappart=p2 targetpart=p2
787		[ ${swapsize:-0} -gt 0 ] && targetpart=p3
788
789		#
790		# Prepare boot pool if enabled (e.g., for geli(8))
791		#
792		if [ "$ZFSBOOT_BOOT_POOL" ]; then
793			bootpart=p2 swappart=p3 targetpart=p3
794			[ ${swapsize:-0} -gt 0 ] && targetpart=p4
795			f_eval_catch $funcname gpart \
796			             "$GPART_ADD_LABEL_WITH_SIZE" boot$index \
797			             freebsd-zfs ${bootsize}b $disk ||
798			             return $FAILURE
799			# Pedantically nuke any old labels
800			f_eval_catch -d $funcname zpool "$ZPOOL_LABELCLEAR_F" \
801			                /dev/$disk$bootpart
802			if [ "$ZFSBOOT_GELI_ENCRYPTION" ]; then
803				# Pedantically detach targetpart for later
804				f_eval_catch -d $funcname geli \
805				                "$GELI_DETACH_F" \
806				                /dev/$disk$targetpart
807			fi
808		fi
809
810		#
811		# 3. Add freebsd-swap partition labeled `swap#'
812		#
813		if [ ${swapsize:-0} -gt 0 ]; then
814			f_eval_catch $funcname gpart \
815			             "$GPART_ADD_LABEL_WITH_SIZE" swap$index \
816			             freebsd-swap ${swapsize}b $disk ||
817			             return $FAILURE
818			# Pedantically nuke any old labels on the swap
819			f_eval_catch -d $funcname zpool "$ZPOOL_LABELCLEAR_F" \
820			                /dev/$disk$swappart
821		fi
822
823		#
824		# 4. Add freebsd-zfs partition labeled `zfs#' for zroot
825		#
826		f_eval_catch $funcname gpart "$GPART_ADD_LABEL" \
827		             zfs$index freebsd-zfs $disk || return $FAILURE
828		f_eval_catch -d $funcname zpool "$ZPOOL_LABELCLEAR_F" \
829		                /dev/$disk$targetpart
830		;;
831
832	MBR) f_dprintf "$funcname: Creating MBR layout..."
833		#
834		# 1. Create MBR layout (no labels)
835		#
836		f_eval_catch $funcname gpart "$GPART_CREATE" mbr $disk ||
837		             return $FAILURE
838		f_eval_catch $funcname gpart "$GPART_BOOTCODE" /boot/mbr \
839		             $disk || return $FAILURE
840
841		#
842		# 2. Add freebsd slice with all available space
843		#
844		f_eval_catch $funcname gpart "$GPART_ADD" freebsd $disk ||
845		             return $FAILURE
846		f_eval_catch $funcname gpart "$GPART_SET_ACTIVE" 1 $disk ||
847		             return $FAILURE
848		# Pedantically nuke any old labels
849		f_eval_catch -d $funcname zpool "$ZPOOL_LABELCLEAR_F" \
850		                /dev/${disk}s1
851		# Pedantically nuke any old scheme
852		f_eval_catch -d $funcname gpart "$GPART_DESTROY_F" ${disk}s1
853
854		#
855		# 3. Write BSD scheme to the freebsd slice
856		#
857		f_eval_catch $funcname gpart "$GPART_CREATE" BSD ${disk}s1 ||
858		             return $FAILURE
859
860		# NB: zpool will use s1a (no labels)
861		bootpart=s1a swappart=s1b targetpart=s1d mbrindex=4
862
863		#
864		# Always prepare a boot pool on MBR
865		#
866		ZFSBOOT_BOOT_POOL=1
867		f_eval_catch $funcname gpart \
868		             "$GPART_ADD_INDEX_WITH_SIZE" \
869		             1 freebsd-zfs ${bootsize}b ${disk}s1 ||
870		             return $FAILURE
871		# Pedantically nuke any old labels
872		f_eval_catch -d $funcname zpool "$ZPOOL_LABELCLEAR_F" \
873		                /dev/$disk$bootpart
874		if [ "$ZFSBOOT_GELI_ENCRYPTION" ]; then
875			# Pedantically detach targetpart for later
876			f_eval_catch -d $funcname geli \
877			                "$GELI_DETACH_F" \
878					/dev/$disk$targetpart
879		fi
880
881		#
882		# 4. Add freebsd-swap partition
883		#
884		if [ ${swapsize:-0} -gt 0 ]; then
885			f_eval_catch $funcname gpart \
886			             "$GPART_ADD_INDEX_WITH_SIZE" 2 \
887			             freebsd-swap ${swapsize}b ${disk}s1 ||
888			             return $FAILURE
889			# Pedantically nuke any old labels on the swap
890			f_eval_catch -d $funcname zpool "$ZPOOL_LABELCLEAR_F" \
891			                /dev/${disk}s1b
892		fi
893
894		#
895		# 5. Add freebsd-zfs partition for zroot
896		#
897		f_eval_catch $funcname gpart "$GPART_ADD_INDEX" \
898			     $mbrindex freebsd-zfs ${disk}s1 || return $FAILURE
899		f_eval_catch -d $funcname zpool "$ZPOOL_LABELCLEAR_F" \
900				/dev/$disk$targetpart # Pedantic
901		f_eval_catch $funcname dd "$DD_WITH_OPTIONS" \
902			     /boot/zfsboot /dev/${disk}s1 count=1 ||
903			     return $FAILURE
904		;;
905
906	esac # $ZFSBOOT_PARTITION_SCHEME
907
908	# Update fstab(5)
909	if [ "$isswapmirror" ]; then
910		# This is not the first disk in the mirror, do nothing
911	elif [ "$ZFSBOOT_SWAP_ENCRYPTION" -a "$ZFSBOOT_SWAP_MIRROR" ]; then
912		f_eval_catch $funcname printf "$PRINTF_FSTAB" \
913		             /dev/mirror/swap.eli none swap sw 0 0 \
914		             $BSDINSTALL_TMPETC/fstab ||
915		             return $FAILURE
916		isswapmirror=1
917	elif [ "$ZFSBOOT_SWAP_MIRROR" ]; then
918		f_eval_catch $funcname printf "$PRINTF_FSTAB" \
919		             /dev/mirror/swap none swap sw 0 0 \
920		             $BSDINSTALL_TMPETC/fstab ||
921		             return $FAILURE
922		isswapmirror=1
923	elif [ "$ZFSBOOT_SWAP_ENCRYPTION" ]; then
924		f_eval_catch $funcname printf "$PRINTF_FSTAB" \
925		             /dev/$disk${swappart}.eli none swap sw 0 0 \
926		             $BSDINSTALL_TMPETC/fstab ||
927		             return $FAILURE
928	else
929		f_eval_catch $funcname printf "$PRINTF_FSTAB" \
930		             /dev/$disk$swappart none swap sw 0 0 \
931		             $BSDINSTALL_TMPETC/fstab ||
932		             return $FAILURE
933	fi
934
935	return $SUCCESS
936}
937
938# zfs_create_boot $poolname $vdev_type $disks ...
939#
940# Creates boot pool and dataset layout. Returns error if something goes wrong.
941# Errors are printed to stderr for collection and display.
942#
943zfs_create_boot()
944{
945	local funcname=zfs_create_boot
946	local zroot_name="$1"
947	local zroot_vdevtype="$2"
948	local zroot_vdevs= # Calculated below
949	local swap_devs= # Calculated below
950	local boot_vdevs= # Used for geli(8) and/or MBR layouts
951	shift 2 # poolname vdev_type
952	local disks="$*" disk
953	local isswapmirror
954	local bootpart targetpart swappart # Set by zfs_create_diskpart() below
955	local create_options
956
957	#
958	# Pedantic checks; should never be seen
959	#
960	if [ ! "$zroot_name" ]; then
961		f_dprintf "$funcname: NULL poolname"
962		msg_error="$msg_error: $funcname" \
963			f_show_err "$msg_null_poolname"
964		return $FAILURE
965	fi
966	if [ $# -lt 1 ]; then
967		f_dprintf "$funcname: missing disk arguments"
968		msg_error="$msg_error: $funcname" \
969			f_show_err "$msg_missing_disk_arguments"
970		return $FAILURE
971	fi
972	f_dprintf "$funcname: poolname=[%s] vdev_type=[%s]" \
973	          "$zroot_name" "$zroot_vdevtype"
974
975	#
976	# Initialize fstab(5)
977	#
978	f_dprintf "$funcname: Initializing temporary fstab(5) file..."
979	f_eval_catch $funcname sh "$SHELL_TRUNCATE" $BSDINSTALL_TMPETC/fstab ||
980	             return $FAILURE
981	f_eval_catch $funcname printf "$PRINTF_FSTAB" \
982	             "# Device" Mountpoint FStype Options Dump "Pass#" \
983	             $BSDINSTALL_TMPETC/fstab || return $FAILURE
984
985	#
986	# Expand SI units in desired sizes
987	#
988	f_dprintf "$funcname: Expanding supplied size values..."
989	local swapsize bootsize
990	if ! f_expand_number "$ZFSBOOT_SWAP_SIZE" swapsize; then
991		f_dprintf "$funcname: Invalid swap size \`%s'" \
992		          "$ZFSBOOT_SWAP_SIZE"
993		f_show_err "$msg_invalid_swap_size" "$ZFSBOOT_SWAP_SIZE"
994		return $FAILURE
995	fi
996	if ! f_expand_number "$ZFSBOOT_BOOT_POOL_SIZE" bootsize; then
997		f_dprintf "$funcname: Invalid boot pool size \`%s'" \
998		          "$ZFSBOOT_BOOT_POOL_SIZE"
999		f_show_err "$msg_invalid_boot_pool_size" \
1000		           "$ZFSBOOT_BOOT_POOL_SIZE"
1001		return $FAILURE
1002	fi
1003	f_dprintf "$funcname: ZFSBOOT_SWAP_SIZE=[%s] swapsize=[%s]" \
1004	          "$ZFSBOOT_SWAP_SIZE" "$swapsize"
1005	f_dprintf "$funcname: ZFSBOOT_BOOT_POOL_SIZE=[%s] bootsize=[%s]" \
1006	          "$ZFSBOOT_BOOT_POOL_SIZE" "$bootsize"
1007
1008	#
1009	# Destroy the pool in-case this is our second time 'round (case of
1010	# failure and installer presented ``Retry'' option to come back).
1011	#
1012	# NB: If we don't destroy the pool, later gpart(8) destroy commands
1013	# that try to clear existing partitions (see zfs_create_diskpart())
1014	# will fail with a `Device Busy' error, leading to `GEOM exists'.
1015	#
1016	f_eval_catch -d $funcname zpool "$ZPOOL_DESTROY" "$zroot_name"
1017
1018	#
1019	# Prepare the disks and build pool device list(s)
1020	#
1021	f_dprintf "$funcname: Preparing disk partitions for ZFS pool..."
1022	[ "$ZFSBOOT_GNOP_4K_FORCE_ALIGN" ] &&
1023		f_dprintf "$funcname: With 4k alignment using gnop(8)..."
1024	local n=0
1025	for disk in $disks; do
1026		zfs_create_diskpart $disk $n || return $FAILURE
1027		# Now $bootpart, $targetpart, and $swappart are set (suffix
1028		# for $disk)
1029		
1030		# Forced 4k alignment support using Geom NOP (see gnop(8))
1031		if [ "$ZFSBOOT_GNOP_4K_FORCE_ALIGN" ]; then
1032			if [ "$ZFSBOOT_BOOT_POOL" ]; then
1033				boot_vdevs="$boot_vdevs $disk$bootpart.nop"
1034				f_eval_catch $funcname gnop "$GNOP_CREATE" \
1035				             $disk$bootpart || return $FAILURE
1036			fi
1037			# Don't gnop encrypted partition
1038			if [ "$ZFSBOOT_GELI_ENCRYPTION" ]; then
1039				zroot_vdevs="$zroot_vdevs $disk$targetpart.eli"
1040			else
1041				zroot_vdevs="$zroot_vdevs $disk$targetpart.nop"
1042				f_eval_catch $funcname gnop "$GNOP_CREATE" \
1043					     $disk$targetpart ||
1044				             return $FAILURE
1045			fi
1046		else
1047			if [ "$ZFSBOOT_BOOT_POOL" ]; then
1048				boot_vdevs="$boot_vdevs $disk$bootpart"
1049			fi
1050			zroot_vdevs="$zroot_vdevs $disk$targetpart"
1051		fi
1052
1053		n=$(( $n + 1 ))
1054	done # disks
1055
1056	#
1057	# If we need/want a boot pool, create it
1058	#
1059	if [ "$ZFSBOOT_BOOT_POOL" ]; then
1060		local bootpool_vdevtype= # Calculated below
1061		local bootpool_options= # Calculated below
1062		local bootpool_name="$ZFSBOOT_BOOT_POOL_NAME"
1063		local bootpool="$BSDINSTALL_CHROOT/$bootpool_name"
1064		local zroot_key="${ZFSBOOT_GELI_KEY_FILE#/}"
1065
1066		f_dprintf "$funcname: Setting up boot pool..."
1067		[ "$ZFSBOOT_GELI_ENCRYPTION" ] &&
1068			f_dprintf "$funcname: For encrypted root disk..."
1069
1070		# Create parent directory for boot pool
1071		f_eval_catch -d $funcname umount "$UMOUNT" /mnt
1072		f_eval_catch $funcname mount "$MOUNT_TYPE" tmpfs none \
1073		             $BSDINSTALL_CHROOT || return $FAILURE
1074
1075		# Create mirror across the boot partition on all disks
1076		local nvdevs
1077		f_count nvdevs $boot_vdevs
1078		[ $nvdevs -gt 1 ] && bootpool_vdevtype=mirror
1079
1080		create_options="$ZFSBOOT_BOOT_POOL_CREATE_OPTIONS"
1081		bootpool_options="-o altroot=$BSDINSTALL_CHROOT"
1082		bootpool_options="$bootpool_options $create_options"
1083		bootpool_options="$bootpool_options -m \"/$bootpool_name\" -f"
1084		f_eval_catch $funcname zpool "$ZPOOL_CREATE_WITH_OPTIONS" \
1085		             "$bootpool_options" "$bootpool_name" \
1086		             "$bootpool_vdevtype" "$boot_vdevs" ||
1087		             return $FAILURE
1088
1089		f_eval_catch $funcname mkdir "$MKDIR_P" "$bootpool/boot" ||
1090		             return $FAILURE
1091
1092		if [ "$ZFSBOOT_GELI_ENCRYPTION" ]; then
1093			# Generate an encryption key using random(4)
1094			f_eval_catch $funcname dd "$DD_WITH_OPTIONS" \
1095				     /dev/random "$bootpool/$zroot_key" \
1096			             "bs=4096 count=1" || return $FAILURE
1097		else
1098			# Clean up
1099			f_eval_catch $funcname zfs "$ZFS_UNMOUNT" \
1100			             "$bootpool_name" || return $FAILURE
1101			f_eval_catch -d $funcname umount "$UMOUNT" /mnt # tmpfs
1102		fi
1103
1104	fi
1105
1106	#
1107	# Create the geli(8) GEOMS
1108	#
1109	if [ "$ZFSBOOT_GELI_ENCRYPTION" ]; then
1110		# Prompt user for password (twice)
1111		if ! msg_enter_new_password="$msg_geli_password" \
1112			f_dialog_input_password
1113		then
1114			f_dprintf "$funcname: User cancelled"
1115			f_show_err "$msg_user_cancelled"
1116			return $FAILURE
1117		fi
1118
1119		# Initialize geli(8) on each of the target partitions
1120		for disk in $disks; do
1121			f_dialog_info "$msg_geli_setup" \
1122				2>&1 >&$DIALOG_TERMINAL_PASSTHRU_FD
1123			if ! echo "$pw_password" | f_eval_catch \
1124				$funcname geli "$GELI_PASSWORD_INIT" \
1125				"$bootpool/boot/$disk$targetpart.eli" \
1126				AES-XTS "$bootpool/$zroot_key" \
1127				$disk$targetpart
1128			then
1129				f_interactive || f_die
1130				unset pw_password # Sensitive info
1131				return $FAILURE
1132			fi
1133			if ! echo "$pw_password" | f_eval_catch \
1134				$funcname geli "$GELI_ATTACH" \
1135				"$bootpool/$zroot_key" $disk$targetpart
1136			then
1137				f_interactive || f_die
1138				unset pw_password # Sensitive info
1139				return $FAILURE
1140			fi
1141		done
1142		unset pw_password # Sensitive info
1143
1144		# Clean up
1145		f_eval_catch $funcname zfs "$ZFS_UNMOUNT" "$bootpool_name" ||
1146			return $FAILURE
1147		f_eval_catch -d $funcname umount "$UMOUNT" /mnt # tmpfs
1148	fi
1149	#
1150	# Create the gmirror(8) GEOMS for swap
1151	#
1152	if [ "$ZFSBOOT_SWAP_MIRROR" ]; then
1153		for disk in $disks; do
1154			swap_devs="$swap_devs $disk$swappart"
1155		done
1156		f_eval_catch $funcname gmirror "$SWAP_GMIRROR_LABEL" \
1157			"$swap_devs" || return $FAILURE
1158	fi
1159
1160	#
1161	# Create the ZFS root pool with desired type and disk devices
1162	#
1163	f_dprintf "$funcname: Creating root pool..."
1164	create_options="$ZFSBOOT_POOL_CREATE_OPTIONS"
1165	f_eval_catch $funcname zpool "$ZPOOL_CREATE_WITH_OPTIONS" \
1166		"-o altroot=$BSDINSTALL_CHROOT $create_options -m none -f" \
1167		"$zroot_name" "$zroot_vdevtype" "$zroot_vdevs" ||
1168		return $FAILURE
1169
1170	#
1171	# Create ZFS dataset layout within the new root pool
1172	#
1173	f_dprintf "$funcname: Creating ZFS datasets..."
1174	echo "$ZFSBOOT_DATASETS" | while read dataset options; do
1175		# Skip blank lines and comments
1176		case "$dataset" in "#"*|"") continue; esac
1177		# Remove potential inline comments in options
1178		options="${options%%#*}"
1179		# Replace tabs with spaces
1180		f_replaceall "$options" "	" " " options
1181		# Reduce contiguous runs of space to one single space
1182		oldoptions=
1183		while [ "$oldoptions" != "$options" ]; do
1184			oldoptions="$options"
1185			f_replaceall "$options" "  " " " options
1186		done
1187		# Replace both commas and spaces with ` -o '
1188		f_replaceall "$options" "[ ,]" " -o " options
1189		# Create the dataset with desired options
1190		f_eval_catch $funcname zfs "$ZFS_CREATE_WITH_OPTIONS" \
1191		             "${options:+-o $options}" "$zroot_name$dataset" ||
1192		             return $FAILURE
1193	done
1194
1195	# Touch up permissions on the tmp directories
1196	f_dprintf "$funcname: Modifying directory permissions..."
1197	local dir
1198	for dir in /tmp /var/tmp; do
1199		f_eval_catch $funcname chmod "$CHMOD_MODE" 1777 \
1200		             $BSDINSTALL_CHROOTDIR$dir || return $FAILURE
1201	done
1202
1203	# Create symlink(s)
1204	if [ "$ZFSBOOT_BOOT_POOL" ]; then
1205		f_dprintf "$funcname: Creating /boot symlink for boot pool..."
1206		f_eval_catch $funcname ln "$LN_SF" "$bootpool_name/boot" \
1207		             $BSDINSTALL_CHROOT/boot || return $FAILURE
1208	fi
1209
1210	# Set bootfs property
1211	local zroot_bootfs="$ZFSBOOT_BEROOT_NAME/$ZFSBOOT_BOOTFS_NAME"
1212	f_dprintf "$funcname: Setting bootfs property..."
1213	f_eval_catch $funcname zpool "$ZPOOL_SET" \
1214		"bootfs=\"$zroot_name/$zroot_bootfs\"" "$zroot_name" ||
1215		return $FAILURE
1216
1217	# Export the pool(s)
1218	f_dprintf "$funcname: Temporarily exporting ZFS pool(s)..."
1219	f_eval_catch $funcname zpool "$ZPOOL_EXPORT" "$zroot_name" ||
1220	             return $FAILURE
1221	if [ "$ZFSBOOT_BOOT_POOL" ]; then
1222		f_eval_catch $funcname zpool "$ZPOOL_EXPORT" \
1223		             "$bootpool_name" || return $FAILURE
1224	fi
1225
1226	# Destroy the gnop devices (if enabled)
1227	for disk in ${ZFSBOOT_GNOP_4K_FORCE_ALIGN:+$disks}; do
1228		if [ "$ZFSBOOT_BOOT_POOL" ]; then
1229			f_eval_catch -d $funcname gnop "$GNOP_DESTROY" \
1230			                $disk$bootpart.nop
1231		fi
1232		if [ ! "$ZFSBOOT_GELI_ENCRYPTION" ]; then
1233			f_eval_catch -d $funcname gnop "$GNOP_DESTROY" \
1234			                $disk$targetpart.nop
1235		fi
1236	done
1237
1238	# MBR boot loader touch-up
1239	if [ "$ZFSBOOT_PARTITION_SCHEME" = "MBR" ]; then
1240		f_dprintf "$funcname: Updating MBR boot loader on disks..."
1241		# Stick the ZFS boot loader in the "convienient hole" after 
1242		# the ZFS internal metadata
1243		for disk in $disks; do
1244			f_eval_catch $funcname dd "$DD_WITH_OPTIONS" \
1245			             /boot/zfsboot /dev/$disk$bootpart \
1246			             "skip=1 seek=1024" || return $FAILURE
1247		done
1248	fi
1249
1250	# Re-import the ZFS pool(s)
1251	f_dprintf "$funcname: Re-importing ZFS pool(s)..."
1252	f_eval_catch $funcname zpool "$ZPOOL_IMPORT_WITH_OPTIONS" \
1253	             "-o altroot=\"$BSDINSTALL_CHROOT\"" "$zroot_name" ||
1254	             return $FAILURE
1255	if [ "$ZFSBOOT_BOOT_POOL" ]; then
1256		f_eval_catch $funcname zpool "$ZPOOL_IMPORT_WITH_OPTIONS" \
1257		             "-o altroot=\"$BSDINSTALL_CHROOT\"" \
1258		             "$bootpool_name" || return $FAILURE
1259	fi
1260
1261	# While this is apparently not needed, it seems to help MBR
1262	f_dprintf "$funcname: Configuring zpool.cache for zroot..."
1263	f_eval_catch $funcname mkdir "$MKDIR_P" $BSDINSTALL_CHROOT/boot/zfs ||
1264	             return $FAILURE
1265	f_eval_catch $funcname zpool "$ZPOOL_SET" \
1266	             "cachefile=\"$BSDINSTALL_CHROOT/boot/zfs/zpool.cache\"" \
1267	             "$zroot_name" || return $FAILURE
1268
1269	# Last, but not least... required lines for rc.conf(5)/loader.conf(5)
1270	# NOTE: We later concatenate these into their destination
1271	f_dprintf "%s: Configuring rc.conf(5)/loader.conf(5) additions..." \
1272	          "$funcname"
1273	f_eval_catch $funcname echo "$ECHO_APPEND" 'zfs_enable=\"YES\"' \
1274	             $BSDINSTALL_TMPETC/rc.conf.zfs || return $FAILURE
1275	f_eval_catch $funcname echo "$ECHO_APPEND" 'zfs_load=\"YES\"' \
1276	             $BSDINSTALL_TMPBOOT/loader.conf.zfs || return $FAILURE
1277	f_eval_catch $funcname echo "$ECHO_APPEND" \
1278	             'kern.geom.label.gptid.enable=\"0\"' \
1279	             $BSDINSTALL_TMPBOOT/loader.conf.zfs || return $FAILURE
1280
1281	if [ "$ZFSBOOT_SWAP_MIRROR" ]; then
1282		f_eval_catch $funcname echo "$ECHO_APPEND" 'geom_mirror_load=\"YES\"' \
1283		             $BSDINSTALL_TMPBOOT/loader.conf.gmirror || return $FAILURE
1284	fi
1285
1286	# We're all done unless we should go on for boot pool
1287	[ "$ZFSBOOT_BOOT_POOL" ] || return $SUCCESS
1288
1289	# Set cachefile for boot pool so it auto-imports at system start
1290	f_dprintf "$funcname: Configuring zpool.cache for boot pool..."
1291	f_eval_catch $funcname zpool "$ZPOOL_SET" \
1292	             "cachefile=\"$BSDINSTALL_CHROOT/boot/zfs/zpool.cache\"" \
1293	             "$bootpool_name" || return $FAILURE
1294
1295	# Some additional geli(8) requirements for loader.conf(5)
1296	for option in \
1297		'zpool_cache_load=\"YES\"' \
1298		'zpool_cache_type=\"/boot/zfs/zpool.cache\"' \
1299		'zpool_cache_name=\"/boot/zfs/zpool.cache\"' \
1300	; do
1301		f_eval_catch $funcname echo "$ECHO_APPEND" "$option" \
1302		             $BSDINSTALL_TMPBOOT/loader.conf.zfs ||
1303		             return $FAILURE
1304	done
1305	f_eval_catch $funcname printf "$PRINTF_CONF" vfs.root.mountfrom \
1306	    "\"zfs:$zroot_name/$zroot_bootfs\"" \
1307	    $BSDINSTALL_TMPBOOT/loader.conf.root || return $FAILURE
1308
1309	# We're all done unless we should go on to do encryption
1310	[ "$ZFSBOOT_GELI_ENCRYPTION" ] || return $SUCCESS
1311
1312	#
1313	# Configure geli(8)-based encryption
1314	#
1315	f_dprintf "$funcname: Configuring disk encryption..."
1316	f_eval_catch $funcname echo "$ECHO_APPEND" 'aesni_load=\"YES\"' \
1317	    $BSDINSTALL_TMPBOOT/loader.conf.aesni || return $FAILURE
1318	f_eval_catch $funcname echo "$ECHO_APPEND" 'geom_eli_load=\"YES\"' \
1319	    $BSDINSTALL_TMPBOOT/loader.conf.geli || return $FAILURE
1320	for disk in $disks; do
1321		f_eval_catch $funcname printf "$PRINTF_CONF" \
1322			geli_%s_keyfile0_load "$disk$targetpart YES" \
1323			$BSDINSTALL_TMPBOOT/loader.conf.$disk$targetpart ||
1324			return $FAILURE
1325		f_eval_catch $funcname printf "$PRINTF_CONF" \
1326			geli_%s_keyfile0_type \
1327			"$disk$targetpart $disk$targetpart:geli_keyfile0" \
1328			$BSDINSTALL_TMPBOOT/loader.conf.$disk$targetpart ||
1329			return $FAILURE
1330		f_eval_catch $funcname printf "$PRINTF_CONF" \
1331			geli_%s_keyfile0_name \
1332			"$disk$targetpart \"$ZFSBOOT_GELI_KEY_FILE\"" \
1333			$BSDINSTALL_TMPBOOT/loader.conf.$disk$targetpart ||
1334			return $FAILURE
1335	done
1336
1337	return $SUCCESS
1338}
1339
1340# dialog_menu_diskinfo
1341#
1342# Prompt the user to select a disk and then provide detailed info on it.
1343#
1344dialog_menu_diskinfo()
1345{
1346	local device disk
1347
1348	#
1349	# Break from loop when user cancels disk selection
1350	#
1351	while :; do
1352		device=$( msg_cancel="$msg_back" f_device_menu \
1353			"$DIALOG_TITLE" "$msg_select_a_disk_device" "" \
1354			$DEVICE_TYPE_DISK 2>&1 ) || break
1355		$device get name disk
1356
1357		# Show gpart(8) `show' and camcontrol(8) `inquiry' data
1358		f_show_msg "$msg_detailed_disk_info" \
1359			"$disk" "$( gpart show $disk 2> /dev/null )" \
1360			"$disk" "$( camcontrol inquiry $disk 2> /dev/null )" \
1361			"$disk" "$( camcontrol identify $disk 2> /dev/null )"
1362	done
1363
1364	return $SUCCESS
1365}
1366
1367############################################################ MAIN
1368
1369#
1370# Initialize
1371#
1372f_dialog_title "$msg_zfs_configuration"
1373f_dialog_backtitle "$msg_freebsd_installer"
1374
1375# User may have specifically requested ZFS-related operations be interactive
1376! f_interactive && f_zfsinteractive && unset $VAR_NONINTERACTIVE
1377
1378#
1379# Debugging
1380#
1381f_dprintf "BSDINSTALL_CHROOT=[%s]" "$BSDINSTALL_CHROOT"
1382f_dprintf "BSDINSTALL_TMPETC=[%s]" "$BSDINSTALL_TMPETC"
1383f_dprintf "FSTAB_FMT=[%s]" "$FSTAB_FMT"
1384
1385#
1386# Loop over the main menu until we've accomplished what we came here to do
1387#
1388while :; do
1389	if ! f_interactive; then
1390		retval=$DIALOG_OK
1391		mtag=">>> $msg_install"
1392	else
1393		dialog_menu_main
1394		retval=$?
1395		f_dialog_menutag_fetch mtag
1396	fi
1397
1398	f_dprintf "retval=%u mtag=[%s]" $retval "$mtag"
1399	[ $retval -eq $DIALOG_OK ] || f_die
1400
1401	case "$mtag" in
1402	">>> $msg_install")
1403		#
1404		# First, validate the user's selections
1405		#
1406
1407		# Make sure they gave us a name for the pool
1408		if [ ! "$ZFSBOOT_POOL_NAME" ]; then
1409			f_dprintf "Pool name cannot be empty."
1410			f_show_err "$msg_pool_name_cannot_be_empty"
1411			continue
1412		fi
1413
1414		# Validate vdev type against number of disks selected/scripted
1415		# (also validates that ZFSBOOT_DISKS are real [probed] disks)
1416		# NB: dialog_menu_layout supports running non-interactively
1417		dialog_menu_layout || continue
1418
1419		# Make sure each disk will be at least 50% ZFS
1420		if f_expand_number "$ZFSBOOT_SWAP_SIZE" swapsize &&
1421		   f_expand_number "$ZFSBOOT_BOOT_POOL_SIZE" bootsize
1422		then
1423			minsize=$swapsize teeny_disks=
1424			[ "$ZFSBOOT_BOOT_POOL" ] &&
1425				minsize=$(( $minsize + $bootsize ))
1426			for disk in $ZFSBOOT_DISKS; do
1427				debug= f_device_find -1 \
1428					$disk $DEVICE_TYPE_DISK device
1429				$device get capacity disksize || continue
1430				[ ${disksize:-0} -ge 0 ] || disksize=0
1431				disksize=$(( $disksize - $minsize ))
1432				[ $disksize -lt $minsize ] &&
1433					teeny_disks="$teeny_disks $disk"
1434			done
1435			if [ "$teeny_disks" ]; then
1436				f_dprintf "swapsize=[%s] bootsize[%s] %s" \
1437				          "$ZFSBOOT_SWAP_SIZE" \
1438				          "$ZFSBOOT_BOOT_POOL_SIZE" \
1439				          "minsize=[$minsize]"
1440				f_dprintf "These disks are too small: %s" \
1441				          "$teeny_disks"
1442				f_show_err "$msg_these_disks_are_too_small" \
1443				           "$ZFSBOOT_SWAP_SIZE" \
1444				           "$ZFSBOOT_BOOT_POOL_SIZE" \
1445				           "$teeny_disks"
1446				continue
1447			fi
1448		fi
1449
1450		#
1451		# Last Chance!
1452		#
1453		if f_interactive; then
1454			dialog_last_chance $ZFSBOOT_DISKS || continue
1455		fi
1456
1457		#
1458		# Let's do this
1459		#
1460
1461		vdev_type="$ZFSBOOT_VDEV_TYPE"
1462
1463		# Blank the vdev type for the default layout
1464		[ "$vdev_type" = "stripe" ] && vdev_type=
1465
1466		zfs_create_boot "$ZFSBOOT_POOL_NAME" \
1467		                "$vdev_type" $ZFSBOOT_DISKS || continue
1468
1469		break # to success
1470		;;
1471	?" $msg_pool_type_disks")
1472		ZFSBOOT_CONFIRM_LAYOUT=1
1473		dialog_menu_layout
1474		# User has poked settings, disable later confirmation
1475		ZFSBOOT_CONFIRM_LAYOUT=
1476		;;
1477	"- $msg_rescan_devices") f_device_rescan ;;
1478	"- $msg_disk_info") dialog_menu_diskinfo ;;
1479	?" $msg_pool_name")
1480		# Prompt the user to input/change the name for the new pool
1481		f_dialog_input input \
1482			"$msg_please_enter_a_name_for_your_zpool" \
1483			"$ZFSBOOT_POOL_NAME" &&
1484			ZFSBOOT_POOL_NAME="$input"
1485		;;
1486	?" $msg_force_4k_sectors")
1487		# Toggle the variable referenced both by the menu and later
1488		if [ "$ZFSBOOT_GNOP_4K_FORCE_ALIGN" ]; then
1489			ZFSBOOT_GNOP_4K_FORCE_ALIGN=
1490		else
1491			ZFSBOOT_GNOP_4K_FORCE_ALIGN=1
1492		fi
1493		;;
1494	?" $msg_encrypt_disks")
1495		# Toggle the variable referenced both by the menu and later
1496		if [ "$ZFSBOOT_GELI_ENCRYPTION" ]; then
1497			ZFSBOOT_GELI_ENCRYPTION=
1498		else
1499			ZFSBOOT_GNOP_4K_FORCE_ALIGN=1
1500			ZFSBOOT_GELI_ENCRYPTION=1
1501		fi
1502		;;
1503	?" $msg_partition_scheme")
1504		# Toggle between GPT and MBR
1505		if [ "$ZFSBOOT_PARTITION_SCHEME" = GPT ]; then
1506			ZFSBOOT_PARTITION_SCHEME=MBR
1507		else
1508			ZFSBOOT_PARTITION_SCHEME=GPT
1509		fi
1510		;;
1511	?" $msg_swap_size")
1512		# Prompt the user to input/change the swap size for each disk
1513		f_dialog_input input \
1514			"$msg_please_enter_amount_of_swap_space" \
1515			"$ZFSBOOT_SWAP_SIZE" &&
1516			ZFSBOOT_SWAP_SIZE="${input:-0}"
1517		;;
1518	?" $msg_swap_mirror")
1519		# Toggle the variable referenced both by the menu and later
1520		if [ "$ZFSBOOT_SWAP_MIRROR" ]; then
1521			ZFSBOOT_SWAP_MIRROR=
1522		else
1523			ZFSBOOT_SWAP_MIRROR=1
1524		fi
1525		;;
1526	?" $msg_swap_encrypt")
1527		# Toggle the variable referenced both by the menu and later
1528		if [ "$ZFSBOOT_SWAP_ENCRYPTION" ]; then
1529			ZFSBOOT_SWAP_ENCRYPTION=
1530		else
1531			ZFSBOOT_SWAP_ENCRYPTION=1
1532		fi
1533		;;
1534	esac
1535done
1536
1537return $SUCCESS
1538
1539################################################################################
1540# END
1541################################################################################
1542