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