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