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