xref: /freebsd/usr.sbin/bsdinstall/scripts/zfsboot (revision cc68614da8232d8baaca0ae0d0dd8f890f06623e)
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="FreeBSD 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	# Debugging
537	if [ "$debug" ]; then
538		local disk_names=
539		for disk in $disks; do
540			debug= $disk get name name
541			disk_names="$disk_names $name"
542		done
543		f_dprintf "$funcname: disks=[%s]" "${disk_names# }"
544	fi
545
546	if [ ! "$disks" ]; then
547		f_dprintf "No disk(s) present to configure"
548		f_show_err "$msg_no_disks_present_to_configure"
549		return $FAILURE
550	fi
551
552	# Lets sort the disks array to be more user friendly
553	f_device_sort_by name disks disks
554
555	#
556	# Operate in a loop so we can (if interactive) repeat if not enough
557	# disks are selected to satisfy the chosen vdev type or user wants to
558	# back-up to the previous menu.
559	#
560	local vardisk ndisks onoff selections vdev_choice breakout device
561	local valid_disks all_valid want_disks desc height width rows
562	while :; do
563		#
564		# Confirm the vdev type that was selected
565		#
566		if f_interactive && [ "$ZFSBOOT_CONFIRM_LAYOUT" ]; then
567			vdev_choice=$( eval $DIALOG \
568				--title \"\$title\"              \
569				--backtitle \"\$btitle\"         \
570				--hline \"\$vdev_hline\"         \
571				--ok-label \"\$msg_ok\"          \
572				--cancel-label \"\$msg_cancel\"  \
573				--item-help                      \
574				--default-item \"\$ZFSBOOT_VDEV_TYPE\" \
575				--menu \"\$vdev_prompt\"         \
576				$vheight $vwidth $vrows          \
577				$vdev_menu_list                  \
578				2>&1 >&$DIALOG_TERMINAL_PASSTHRU_FD
579			) || return $?
580				# Exit if user pressed ESC or chose Cancel/No
581			f_dialog_data_sanitize vdev_choice
582
583			ZFSBOOT_VDEV_TYPE="$vdev_choice"
584			f_dprintf "$funcname: ZFSBOOT_VDEV_TYPE=[%s]" \
585			          "$ZFSBOOT_VDEV_TYPE"
586		fi
587
588		# Determine the number of disks needed for this vdev type
589		want_disks=0
590		case "$ZFSBOOT_VDEV_TYPE" in
591		stripe) want_disks=1 ;;
592		mirror) want_disks=2 ;;
593		raid10) want_disks=4 ;;
594		raidz1) want_disks=3 ;;
595		raidz2) want_disks=4 ;;
596		raidz3) want_disks=5 ;;
597		esac
598
599		#
600		# Warn the user if any scripted disks are invalid
601		#
602		valid_disks= all_valid=${ZFSBOOT_DISKS:+1} # optimism
603		for disk in $ZFSBOOT_DISKS; do
604			if debug= f_device_find -1 \
605				$disk $DEVICE_TYPE_DISK device
606			then
607				valid_disks="$valid_disks $disk"
608				continue
609			fi
610			f_dprintf "$funcname: \`%s' is not a real disk" "$disk"
611			all_valid=
612		done
613		if [ ! "$all_valid" ]; then
614			if [ "$ZFSBOOT_DISKS" ]; then
615				f_show_err \
616				    "$msg_missing_one_or_more_scripted_disks"
617			else
618				f_dprintf "No disks selected."
619				f_interactive ||
620					f_show_err "$msg_no_disks_selected"
621			fi
622			f_interactive || return $FAILURE
623		fi
624		ZFSBOOT_DISKS="${valid_disks# }"
625
626		#
627		# Short-circuit if we're running non-interactively
628		#
629		if ! f_interactive || [ ! "$ZFSBOOT_CONFIRM_LAYOUT" ]; then
630			f_count ndisks $ZFSBOOT_DISKS
631			[ $ndisks -ge $want_disks ] && break # to success
632
633			# Not enough disks selected
634			f_dprintf "$funcname: %s: %s (%u < %u minimum)" \
635				  "$ZFSBOOT_VDEV_TYPE" \
636				  "Not enough disks selected." \
637				  $ndisks $want_disks
638			f_interactive || return $FAILURE
639			msg_yes="$msg_change_selection" msg_no="$msg_cancel" \
640				f_yesno "%s: $msg_not_enough_disks_selected" \
641				"$ZFSBOOT_VDEV_TYPE" $ndisks $want_disks ||
642				return $FAILURE
643		fi
644
645		#
646		# Confirm the disks that were selected
647		# Loop until the user cancels or selects enough disks
648		#
649		breakout=
650		while :; do
651			# Loop over list of available disks, resetting state
652			for disk in $disks; do
653				f_isset _${disk}_status && _${disk}_status=
654			done
655
656			# Loop over list of selected disks and create temporary
657			# locals to map statuses onto up-to-date list of disks
658			for disk in $ZFSBOOT_DISKS; do
659				debug= f_device_find -1 \
660					$disk $DEVICE_TYPE_DISK disk
661				f_isset _${disk}_status ||
662					local _${disk}_status
663				_${disk}_status=on
664			done
665
666			# Create the checklist menu of discovered disk devices
667			disk_check_list=
668			for disk in $disks; do
669				desc=
670				$disk get name name
671				$disk get desc desc
672				f_shell_escape "$desc" desc
673				f_getvar _${disk}_status:-off onoff
674				disk_check_list="$disk_check_list
675					$name '$desc' $onoff"
676			done
677
678			eval f_dialog_checklist_size height width rows \
679				\"\$title\" \"\$btitle\" \"\$prompt\" \
680				\"\$hline\" $disk_check_list
681
682			selections=$( eval $DIALOG \
683				--title \"\$DIALOG_TITLE\"         \
684				--backtitle \"\$DIALOG_BACKTITLE\" \
685				--separate-output                  \
686				--hline \"\$hline\"                \
687				--ok-label \"\$msg_ok\"            \
688				--cancel-label \"\$msg_back\"      \
689				--checklist \"\$prompt\"           \
690				$height $width $rows               \
691				$disk_check_list                   \
692				2>&1 >&$DIALOG_TERMINAL_PASSTHRU_FD
693			) || break
694				# Loop if user pressed ESC or chose Cancel/No
695			f_dialog_data_sanitize selections
696
697			ZFSBOOT_DISKS="$selections"
698			f_dprintf "$funcname: ZFSBOOT_DISKS=[%s]" \
699			          "$ZFSBOOT_DISKS"
700
701			f_count ndisks $ZFSBOOT_DISKS
702
703			if [ "$ZFSBOOT_VDEV_TYPE" == "raid10" ] &&
704			    [ $(( $ndisks % 2 )) -ne 0 ]; then
705				f_dprintf "$funcname: %s: %s (%u %% 2 = %u)" \
706					  "$ZFSBOOT_VDEV_TYPE" \
707					  "Number of disks not even:" \
708					  $ndisks $(( $ndisks % 2 ))
709				msg_yes="$msg_change_selection" \
710					msg_no="$msg_cancel" \
711					f_yesno "%s: $msg_odd_disk_selected" \
712						"$ZFSBOOT_VDEV_TYPE" $ndisks ||
713						break
714				continue
715			fi
716
717			[ $ndisks -ge $want_disks ] &&
718				breakout=break && break
719
720			# Not enough disks selected
721			f_dprintf "$funcname: %s: %s (%u < %u minimum)" \
722				  "$ZFSBOOT_VDEV_TYPE" \
723			          "Not enough disks selected." \
724			          $ndisks $want_disks
725			msg_yes="$msg_change_selection" msg_no="$msg_cancel" \
726				f_yesno "%s: $msg_not_enough_disks_selected" \
727				"$ZFSBOOT_VDEV_TYPE" $ndisks $want_disks ||
728				break
729		done
730		[ "$breakout" = "break" ] && break
731		[ "$ZFSBOOT_CONFIRM_LAYOUT" ] || return $FAILURE
732	done
733
734	return $DIALOG_OK
735}
736
737# zfs_create_diskpart $disk $index
738#
739# For each block device to be used in the zpool, rather than just create the
740# zpool with the raw block devices (e.g., da0, da1, etc.) we create partitions
741# so we can have some real swap. This also provides wiggle room incase your
742# replacement drivers do not have the exact same sector counts.
743#
744# NOTE: $swapsize and $bootsize should be defined by the calling function.
745# NOTE: Sets $bootpart and $targetpart for the calling function.
746#
747zfs_create_diskpart()
748{
749	local funcname=zfs_create_diskpart
750	local disk="$1" index="$2"
751
752	# Check arguments
753	if [ ! "$disk" ]; then
754		f_dprintf "$funcname: NULL disk argument"
755		msg_error="$msg_error: $funcname" \
756			f_show_err "$msg_null_disk_argument"
757		return $FAILURE
758	fi
759	if [ "${disk#*[$IFS]}" != "$disk" ]; then
760		f_dprintf "$funcname: Invalid disk argument \`%s'" "$disk"
761		msg_error="$msg_error: $funcname" \
762			f_show_err "$msg_invalid_disk_argument" "$disk"
763		return $FAILURE
764	fi
765	if [ ! "$index" ]; then
766		f_dprintf "$funcname: NULL index argument"
767		msg_error="$msg_error: $funcname" \
768			f_show_err "$msg_null_index_argument"
769		return $FAILURE
770	fi
771	if ! f_isinteger "$index"; then
772		f_dprintf "$funcname: Invalid index argument \`%s'" "$index"
773		msg_error="$msg_error: $funcname" \
774			f_show_err "$msg_invalid_index_argument" "$index"
775		return $FAILURE
776	fi
777	f_dprintf "$funcname: disk=[%s] index=[%s]" "$disk" "$index"
778
779	# Check for unknown partition scheme before proceeding further
780	case "$ZFSBOOT_PARTITION_SCHEME" in
781	""|MBR|GPT*) : known good ;;
782	*)
783		f_dprintf "$funcname: %s is an unsupported partition scheme" \
784		          "$ZFSBOOT_PARTITION_SCHEME"
785		msg_error="$msg_error: $funcname" f_show_err \
786			"$msg_unsupported_partition_scheme" \
787			"$ZFSBOOT_PARTITION_SCHEME"
788		return $FAILURE
789	esac
790
791	#
792	# Destroy whatever partition layout is currently on disk.
793	# NOTE: `-F' required to destroy if partitions still exist.
794	# NOTE: Failure is ok here, blank disk will have nothing to destroy.
795	#
796	f_dprintf "$funcname: Exporting ZFS pools..."
797	zpool list -Ho name | while read z_name; do
798		f_eval_catch -d $funcname zpool "$ZPOOL_EXPORT_F" $z_name
799	done
800	f_dprintf "$funcname: Detaching all GELI providers..."
801	geli status | tail -n +2 | while read g_name g_status g_component; do
802		f_eval_catch -d $funcname geli "$GELI_DETACH_F" $g_name
803	done
804	f_dprintf "$funcname: Destroying all data/layouts on \`%s'..." "$disk"
805	f_eval_catch -d $funcname gpart "$GPART_DESTROY_F" $disk
806	f_eval_catch -d $funcname graid "$GRAID_DELETE" $disk
807	f_eval_catch -d $funcname zpool "$ZPOOL_LABELCLEAR_F" /dev/$disk
808
809	# Make doubly-sure backup GPT is destroyed
810	f_eval_catch -d $funcname gpart "$GPART_CREATE" gpt $disk
811	f_eval_catch -d $funcname gpart "$GPART_DESTROY_F" $disk
812
813	#
814	# Lay down the desired type of partition scheme
815	#
816	local setsize mbrindex align_small align_big
817	#
818	# If user has requested 4 K alignment, add these params to the
819	# gpart add calls. With GPT, we align large partitions to 1 M for
820	# improved performance on SSDs. MBR does not always play well with gaps
821	# between partitions, so all alignment is only 4k for that case.
822	# With MBR, we align the BSD partition that contains the MBR, otherwise
823	# the system fails to boot.
824	#
825	if [ "$ZFSBOOT_FORCE_4K_SECTORS" ]; then
826		align_small="-a 4k"
827		align_big="-a 1m"
828	fi
829
830	case "$ZFSBOOT_PARTITION_SCHEME" in
831	""|GPT*) f_dprintf "$funcname: Creating GPT layout..."
832		#
833		# 1. Create GPT layout using labels
834		#
835		f_eval_catch $funcname gpart "$GPART_CREATE" gpt $disk ||
836		             return $FAILURE
837
838		#
839		# Apply workarounds if requested by the user
840		#
841		if [ "$ZFSBOOT_PARTITION_SCHEME" = "GPT + Lenovo Fix" ]; then
842			f_eval_catch $funcname gpart "$GPART_SET_LENOVOFIX" \
843			             $disk || return $FAILURE
844		elif [ "$ZFSBOOT_PARTITION_SCHEME" = "GPT + Active" ]; then
845			f_eval_catch $funcname gpart "$GPART_SET_PMBR_ACTIVE" \
846			             $disk || return $FAILURE
847		fi
848
849		#
850		# 2. Add small freebsd-boot and/or efi partition
851		#
852		if [ "$ZFSBOOT_BOOT_TYPE" = "UEFI" -o \
853		     "$ZFSBOOT_BOOT_TYPE" = "BIOS+UEFI" ]
854		then
855			f_eval_catch -k justaddedpart $funcname gpart \
856			             "$GPART_ADD_ALIGN_LABEL_WITH_SIZE" \
857			             "$align_small" efiboot$index efi 260M \
858			             $disk || return $FAILURE
859
860			# We'll configure the ESP in bootconfig
861			if [ -z "$efibootpart" ]; then
862				efibootpart="/dev/$(echo $justaddedpart | cut -f 1 -d ' ')"
863				f_dprintf "$funcname: configuring ESP at [%s]" \
864				          "${efibootpart}"
865
866				f_eval_catch $funcname newfs_msdos "$NEWFS_ESP"\
867				             "$efibootpart" \
868				             || return $FAILURE
869				f_eval_catch $funcname printf "$PRINTF_FSTAB" \
870					     $efibootpart /boot/efi msdosfs \
871				             rw 2 2 "$BSDINSTALL_TMPETC/fstab" \
872				             || return $FAILURE
873			fi
874		fi
875
876		if [ "$ZFSBOOT_BOOT_TYPE" = "BIOS" -o \
877		     "$ZFSBOOT_BOOT_TYPE" = "BIOS+UEFI" ]
878		then
879			f_eval_catch $funcname gpart \
880			             "$GPART_ADD_ALIGN_LABEL_WITH_SIZE" \
881			             "$align_small" gptboot$index \
882			             freebsd-boot 512k $disk || return $FAILURE
883			if [ "$ZFSBOOT_BOOT_TYPE" = "BIOS" ]; then
884				f_eval_catch $funcname gpart \
885				             "$GPART_BOOTCODE_PART" \
886				             /boot/pmbr /boot/gptzfsboot 1 \
887				             $disk || return $FAILURE
888			else
889				f_eval_catch $funcname gpart \
890				             "$GPART_BOOTCODE_PART" \
891				             /boot/pmbr /boot/gptzfsboot 2 \
892				             $disk || return $FAILURE
893			fi
894		fi
895
896		# NB: zpool will use the `zfs#' GPT labels
897		if [ "$ZFSBOOT_BOOT_TYPE" = "BIOS+UEFI" ]; then
898			if [ "$ZFSBOOT_BOOT_POOL" ]; then
899				bootpart=p3 swappart=p4 targetpart=p4
900				[ ${swapsize:-0} -gt 0 ] && targetpart=p5
901			else
902				# Bootpart unused
903				bootpart=p3 swappart=p3 targetpart=p3
904				[ ${swapsize:-0} -gt 0 ] && targetpart=p4
905			fi
906		else
907			if [ "$ZFSBOOT_BOOT_POOL" ]; then
908				bootpart=p2 swappart=p3 targetpart=p3
909				[ ${swapsize:-0} -gt 0 ] && targetpart=p4
910			else
911				# Bootpart unused
912				bootpart=p2 swappart=p2 targetpart=p2
913				[ ${swapsize:-0} -gt 0 ] && targetpart=p3
914			fi
915		fi
916
917		#
918		# Prepare boot pool if enabled (e.g., for geli(8))
919		#
920		if [ "$ZFSBOOT_BOOT_POOL" ]; then
921			f_eval_catch $funcname gpart \
922			             "$GPART_ADD_ALIGN_LABEL_WITH_SIZE" \
923			             "$align_big" boot$index freebsd-zfs \
924			             ${bootsize}b $disk || return $FAILURE
925			# Pedantically nuke any old labels
926			f_eval_catch -d $funcname zpool "$ZPOOL_LABELCLEAR_F" \
927			                /dev/$disk$bootpart
928			if [ "$ZFSBOOT_GELI_ENCRYPTION" ]; then
929				# Pedantically detach targetpart for later
930				f_eval_catch -d $funcname geli \
931				                "$GELI_DETACH_F" \
932				                /dev/$disk$targetpart
933			fi
934		fi
935
936		#
937		# 3. Add freebsd-swap partition labeled `swap#'
938		#
939		if [ ${swapsize:-0} -gt 0 ]; then
940			f_eval_catch $funcname gpart \
941			             "$GPART_ADD_ALIGN_LABEL_WITH_SIZE" \
942			             "$align_big" swap$index freebsd-swap \
943			             ${swapsize}b $disk || return $FAILURE
944			# Pedantically nuke any old labels on the swap
945			f_eval_catch -d $funcname zpool "$ZPOOL_LABELCLEAR_F" \
946			                /dev/$disk$swappart
947		fi
948
949		#
950		# 4. Add freebsd-zfs partition labeled `zfs#' for zroot
951		#
952		if [ "$ZFSBOOT_POOL_SIZE" ]; then
953			f_eval_catch $funcname gpart "$GPART_ADD_ALIGN_LABEL_WITH_SIZE" \
954					"$align_big" zfs$index freebsd-zfs $ZFSBOOT_POOL_SIZE $disk ||
955					return $FAILURE
956		else
957			f_eval_catch $funcname gpart "$GPART_ADD_ALIGN_LABEL" \
958					"$align_big" zfs$index freebsd-zfs $disk ||
959					return $FAILURE
960		fi
961		f_eval_catch -d $funcname zpool "$ZPOOL_LABELCLEAR_F" \
962		                /dev/$disk$targetpart
963		;;
964
965	MBR) f_dprintf "$funcname: Creating MBR layout..."
966		#
967		# Enable boot pool if encryption is desired
968		#
969		[ "$ZFSBOOT_GELI_ENCRYPTION" ] && ZFSBOOT_BOOT_POOL=1
970		#
971		# 1. Create MBR layout (no labels)
972		#
973		f_eval_catch $funcname gpart "$GPART_CREATE" mbr $disk ||
974		             return $FAILURE
975		f_eval_catch $funcname gpart "$GPART_BOOTCODE" /boot/mbr \
976		             $disk || return $FAILURE
977
978		#
979		# 2. Add freebsd slice with all available space
980		#
981		f_eval_catch $funcname gpart "$GPART_ADD_ALIGN" \
982		             "$align_small" freebsd $disk || return $FAILURE
983		f_eval_catch $funcname gpart "$GPART_SET_ACTIVE" 1 $disk ||
984		             return $FAILURE
985		# Pedantically nuke any old labels
986		f_eval_catch -d $funcname zpool "$ZPOOL_LABELCLEAR_F" \
987		                /dev/${disk}s1
988		# Pedantically nuke any old scheme
989		f_eval_catch -d $funcname gpart "$GPART_DESTROY_F" ${disk}s1
990
991		#
992		# 3. Write BSD scheme to the freebsd slice
993		#
994		f_eval_catch $funcname gpart "$GPART_CREATE" BSD ${disk}s1 ||
995		             return $FAILURE
996
997		# NB: zpool will use s1a (no labels)
998		bootpart=s1a swappart=s1b targetpart=s1d mbrindex=4
999
1000		#
1001		# Always prepare a boot pool on MBR
1002		# Do not align this partition, there must not be a gap
1003		#
1004		ZFSBOOT_BOOT_POOL=1
1005		f_eval_catch $funcname gpart \
1006		             "$GPART_ADD_ALIGN_INDEX_WITH_SIZE" \
1007		             "" 1 freebsd-zfs ${bootsize}b ${disk}s1 ||
1008		             return $FAILURE
1009		# Pedantically nuke any old labels
1010		f_eval_catch -d $funcname zpool "$ZPOOL_LABELCLEAR_F" \
1011		                /dev/$disk$bootpart
1012		if [ "$ZFSBOOT_GELI_ENCRYPTION" ]; then
1013			# Pedantically detach targetpart for later
1014			f_eval_catch -d $funcname geli \
1015			                "$GELI_DETACH_F" \
1016					/dev/$disk$targetpart
1017		fi
1018
1019		#
1020		# 4. Add freebsd-swap partition
1021		#
1022		if [ ${swapsize:-0} -gt 0 ]; then
1023			f_eval_catch $funcname gpart \
1024			             "$GPART_ADD_ALIGN_INDEX_WITH_SIZE" \
1025			             "$align_small" 2 freebsd-swap \
1026			             ${swapsize}b ${disk}s1 || return $FAILURE
1027			# Pedantically nuke any old labels on the swap
1028			f_eval_catch -d $funcname zpool "$ZPOOL_LABELCLEAR_F" \
1029			                /dev/${disk}s1b
1030		fi
1031
1032		#
1033		# 5. Add freebsd-zfs partition for zroot
1034		#
1035		if [ "$ZFSBOOT_POOL_SIZE" ]; then
1036			f_eval_catch $funcname gpart "$GPART_ADD_ALIGN_INDEX_WITH_SIZE" \
1037					"$align_small" $mbrindex freebsd-zfs $ZFSBOOT_POOL_SIZE ${disk}s1 || return $FAILURE
1038		else
1039			f_eval_catch $funcname gpart "$GPART_ADD_ALIGN_INDEX" \
1040					"$align_small" $mbrindex freebsd-zfs ${disk}s1 || return $FAILURE
1041		fi
1042		f_eval_catch -d $funcname zpool "$ZPOOL_LABELCLEAR_F" \
1043		                /dev/$disk$targetpart # Pedantic
1044		f_eval_catch $funcname dd "$DD_WITH_OPTIONS" \
1045		             /boot/zfsboot /dev/${disk}s1 count=1 ||
1046		             return $FAILURE
1047		;;
1048
1049	esac # $ZFSBOOT_PARTITION_SCHEME
1050
1051	# Update fstab(5)
1052	local swapsize
1053	f_expand_number "$ZFSBOOT_SWAP_SIZE" swapsize
1054	if [ "$isswapmirror" ]; then
1055		# This is not the first disk in the mirror, do nothing
1056	elif [ ${swapsize:-0} -eq 0 ]; then
1057		# If swap is 0 sized, don't add it to fstab
1058	elif [ "$ZFSBOOT_SWAP_ENCRYPTION" -a "$ZFSBOOT_SWAP_MIRROR" ]; then
1059		f_eval_catch $funcname printf "$PRINTF_FSTAB" \
1060		             /dev/mirror/swap.eli none swap sw 0 0 \
1061		             $BSDINSTALL_TMPETC/fstab || return $FAILURE
1062		isswapmirror=1
1063	elif [ "$ZFSBOOT_SWAP_MIRROR" ]; then
1064		f_eval_catch $funcname printf "$PRINTF_FSTAB" \
1065		             /dev/mirror/swap none swap sw 0 0 \
1066		             $BSDINSTALL_TMPETC/fstab || return $FAILURE
1067		isswapmirror=1
1068	elif [ "$ZFSBOOT_SWAP_ENCRYPTION" ]; then
1069		f_eval_catch $funcname printf "$PRINTF_FSTAB" \
1070		             /dev/$disk${swappart}.eli none swap sw 0 0 \
1071		             $BSDINSTALL_TMPETC/fstab || return $FAILURE
1072	else
1073		f_eval_catch $funcname printf "$PRINTF_FSTAB" \
1074		             /dev/$disk$swappart none swap sw 0 0 \
1075		             $BSDINSTALL_TMPETC/fstab || return $FAILURE
1076	fi
1077
1078	return $SUCCESS
1079}
1080
1081# zfs_create_boot $poolname $vdev_type $disks ...
1082#
1083# Creates boot pool and dataset layout. Returns error if something goes wrong.
1084# Errors are printed to stderr for collection and display.
1085#
1086zfs_create_boot()
1087{
1088	local funcname=zfs_create_boot
1089	local zroot_name="$1"
1090	local zroot_vdevtype="$2"
1091	local zroot_vdevs= # Calculated below
1092	local swap_devs= # Calculated below
1093	local boot_vdevs= # Used for geli(8) and/or MBR layouts
1094	shift 2 # poolname vdev_type
1095	local disks="$*" disk
1096	local isswapmirror
1097	local bootpart targetpart swappart # Set by zfs_create_diskpart() below
1098	local create_options
1099	local efibootpart
1100
1101	#
1102	# Pedantic checks; should never be seen
1103	#
1104	if [ ! "$zroot_name" ]; then
1105		f_dprintf "$funcname: NULL poolname"
1106		msg_error="$msg_error: $funcname" \
1107			f_show_err "$msg_null_poolname"
1108		return $FAILURE
1109	fi
1110	if [ $# -lt 1 ]; then
1111		f_dprintf "$funcname: missing disk arguments"
1112		msg_error="$msg_error: $funcname" \
1113			f_show_err "$msg_missing_disk_arguments"
1114		return $FAILURE
1115	fi
1116	f_dprintf "$funcname: poolname=[%s] vdev_type=[%s]" \
1117	          "$zroot_name" "$zroot_vdevtype"
1118
1119	#
1120	# Initialize fstab(5)
1121	#
1122	f_dprintf "$funcname: Initializing temporary fstab(5) file..."
1123	f_eval_catch $funcname sh "$SHELL_TRUNCATE" $BSDINSTALL_TMPETC/fstab ||
1124	             return $FAILURE
1125	f_eval_catch $funcname printf "$PRINTF_FSTAB" \
1126	             "# Device" Mountpoint FStype Options Dump "Pass#" \
1127	             $BSDINSTALL_TMPETC/fstab || return $FAILURE
1128
1129	#
1130	# Expand SI units in desired sizes
1131	#
1132	f_dprintf "$funcname: Expanding supplied size values..."
1133	local swapsize bootsize poolsize
1134	if ! f_expand_number "$ZFSBOOT_SWAP_SIZE" swapsize; then
1135		f_dprintf "$funcname: Invalid swap size \`%s'" \
1136		          "$ZFSBOOT_SWAP_SIZE"
1137		f_show_err "$msg_invalid_swap_size" "$ZFSBOOT_SWAP_SIZE"
1138		return $FAILURE
1139	fi
1140	if ! f_expand_number "$ZFSBOOT_BOOT_POOL_SIZE" bootsize; then
1141		f_dprintf "$funcname: Invalid boot pool size \`%s'" \
1142		          "$ZFSBOOT_BOOT_POOL_SIZE"
1143		f_show_err "$msg_invalid_boot_pool_size" \
1144		           "$ZFSBOOT_BOOT_POOL_SIZE"
1145		return $FAILURE
1146	fi
1147	if [ "$ZFSBOOT_POOL_SIZE" ]; then
1148		if ! f_expand_number "$ZFSBOOT_POOL_SIZE" poolsize; then
1149			f_dprintf "$funcname: Invalid pool size \`%s'" \
1150				  "$ZFSBOOT_POOL_SIZE"
1151			f_show_err "$msg_invalid_pool_size" \
1152				   "$ZFSBOOT_POOL_SIZE"
1153		fi
1154		f_dprintf "$funcname: ZFSBOOT_POOL_SIZE=[%s] poolsize=[%s]" \
1155			  "$ZFSBOOT_POOL_SIZE" "$poolsize"
1156	fi
1157	f_dprintf "$funcname: ZFSBOOT_SWAP_SIZE=[%s] swapsize=[%s]" \
1158	          "$ZFSBOOT_SWAP_SIZE" "$swapsize"
1159	f_dprintf "$funcname: ZFSBOOT_BOOT_POOL_SIZE=[%s] bootsize=[%s]" \
1160	          "$ZFSBOOT_BOOT_POOL_SIZE" "$bootsize"
1161
1162	#
1163	# Destroy the pool in-case this is our second time 'round (case of
1164	# failure and installer presented ``Retry'' option to come back).
1165	#
1166	# NB: If we don't destroy the pool, later gpart(8) destroy commands
1167	# that try to clear existing partitions (see zfs_create_diskpart())
1168	# will fail with a `Device Busy' error, leading to `GEOM exists'.
1169	#
1170	f_eval_catch -d $funcname zpool "$ZPOOL_DESTROY" "$zroot_name"
1171
1172	#
1173	# Prepare the disks and build pool device list(s)
1174	#
1175	f_dprintf "$funcname: Preparing disk partitions for ZFS pool..."
1176
1177	# Force 4K sectors using vfs.zfs.min_auto_ashift=12
1178	if [ "$ZFSBOOT_FORCE_4K_SECTORS" ]; then
1179		f_dprintf "$funcname: With 4K sectors..."
1180		f_eval_catch $funcname sysctl "$SYSCTL_ZFS_MIN_ASHIFT_12" \
1181		    || return $FAILURE
1182		sysctl kern.geom.part.mbr.enforce_chs=0
1183	fi
1184	local n=0
1185	for disk in $disks; do
1186		zfs_create_diskpart $disk $n || return $FAILURE
1187		# Now $bootpart, $targetpart, and $swappart are set (suffix
1188		# for $disk)
1189		if [ "$ZFSBOOT_BOOT_POOL" ]; then
1190			boot_vdevs="$boot_vdevs $disk$bootpart"
1191		fi
1192		zroot_vdevs="$zroot_vdevs $disk$targetpart"
1193		if [ "$ZFSBOOT_GELI_ENCRYPTION" ]; then
1194			zroot_vdevs="$zroot_vdevs.eli"
1195		fi
1196
1197		n=$(( $n + 1 ))
1198	done # disks
1199
1200	#
1201	# If we need/want a boot pool, create it
1202	#
1203	if [ "$ZFSBOOT_BOOT_POOL" ]; then
1204		local bootpool_vdevtype= # Calculated below
1205		local bootpool_options= # Calculated below
1206		local bootpool_name="$ZFSBOOT_BOOT_POOL_NAME"
1207		local bootpool="$BSDINSTALL_CHROOT/$bootpool_name"
1208		local zroot_key="${ZFSBOOT_GELI_KEY_FILE#/}"
1209
1210		f_dprintf "$funcname: Setting up boot pool..."
1211		[ "$ZFSBOOT_GELI_ENCRYPTION" ] &&
1212			f_dprintf "$funcname: For encrypted root disk..."
1213
1214		# Create parent directory for boot pool
1215		f_eval_catch -d $funcname umount "$UMOUNT" "$BSDINSTALL_CHROOT"
1216		f_eval_catch $funcname mount "$MOUNT_TYPE" tmpfs none \
1217		             $BSDINSTALL_CHROOT || return $FAILURE
1218
1219		# Create mirror across the boot partition on all disks
1220		local nvdevs
1221		f_count nvdevs $boot_vdevs
1222		[ $nvdevs -gt 1 ] && bootpool_vdevtype=mirror
1223
1224		create_options="$ZFSBOOT_BOOT_POOL_CREATE_OPTIONS"
1225		bootpool_options="-o altroot=$BSDINSTALL_CHROOT"
1226		bootpool_options="$bootpool_options $create_options"
1227		bootpool_options="$bootpool_options -m \"/$bootpool_name\" -f"
1228		f_eval_catch $funcname zpool "$ZPOOL_CREATE_WITH_OPTIONS" \
1229		             "$bootpool_options" "$bootpool_name" \
1230		             "$bootpool_vdevtype" "$boot_vdevs" ||
1231		             return $FAILURE
1232
1233		f_eval_catch $funcname mkdir "$MKDIR_P" "$bootpool/boot" ||
1234		             return $FAILURE
1235
1236		if [ "$ZFSBOOT_GELI_ENCRYPTION" ]; then
1237			# Generate an encryption key using random(4)
1238			f_eval_catch $funcname dd "$DD_WITH_OPTIONS" \
1239			             /dev/random "$bootpool/$zroot_key" \
1240			             "bs=4096 count=1" || return $FAILURE
1241			f_eval_catch $funcname chmod "$CHMOD_MODE" \
1242			             go-wrx "$bootpool/$zroot_key" ||
1243			             return $FAILURE
1244		fi
1245
1246	fi
1247
1248	#
1249	# Create the geli(8) GEOMS
1250	#
1251	if [ "$ZFSBOOT_GELI_ENCRYPTION" ]; then
1252		#
1253		# Load the AES-NI kernel module to accelerate encryption
1254		#
1255		f_eval_catch -d $funcname kldload "$KLDLOAD" "aesni"
1256		# Prompt user for password (twice)
1257		if ! msg_enter_new_password="$msg_geli_password" \
1258			f_dialog_input_password
1259		then
1260			f_dprintf "$funcname: User cancelled"
1261			f_show_err "$msg_user_cancelled"
1262			return $FAILURE
1263		fi
1264
1265		# Initialize geli(8) on each of the target partitions
1266		for disk in $disks; do
1267			f_dialog_info "$msg_geli_setup" \
1268				2>&1 >&$DIALOG_TERMINAL_PASSTHRU_FD
1269			if [ "$ZFSBOOT_BOOT_POOL" ]; then
1270				if ! echo "$pw_password" | f_eval_catch \
1271					$funcname geli "$GELI_PASSWORD_INIT" \
1272					"$bootpool/boot/$disk$targetpart.eli" \
1273					AES-XTS "$bootpool/$zroot_key" \
1274					$disk$targetpart
1275				then
1276					f_interactive || f_die
1277					unset pw_password # Sensitive info
1278					return $FAILURE
1279				fi
1280				if ! echo "$pw_password" | f_eval_catch \
1281					$funcname geli "$GELI_ATTACH" \
1282					"$bootpool/$zroot_key" $disk$targetpart
1283				then
1284					f_interactive || f_die
1285					unset pw_password # Sensitive info
1286					return $FAILURE
1287				fi
1288			else
1289				# With no bootpool, there is no place to store
1290				# the key files, use only a password
1291				if ! echo "$pw_password" | f_eval_catch \
1292					$funcname geli \
1293					"$GELI_PASSWORD_GELIBOOT_INIT" \
1294					AES-XTS $disk$targetpart
1295				then
1296					f_interactive || f_die
1297					unset pw_password # Sensitive info
1298					return $FAILURE
1299				fi
1300				if ! echo "$pw_password" | f_eval_catch \
1301					$funcname geli "$GELI_ATTACH_NOKEY" \
1302					$disk$targetpart
1303				then
1304					f_interactive || f_die
1305					unset pw_password # Sensitive info
1306					return $FAILURE
1307				fi
1308			fi
1309		done
1310		unset pw_password # Sensitive info
1311	fi
1312
1313	if [ "$ZFSBOOT_BOOT_POOL" ]; then
1314		# Clean up
1315		f_eval_catch $funcname zfs "$ZFS_UNMOUNT" "$bootpool_name" ||
1316			return $FAILURE
1317		# tmpfs
1318		f_eval_catch -d $funcname umount "$UMOUNT" "$BSDINSTALL_CHROOT"
1319	fi
1320
1321	#
1322	# Create the gmirror(8) GEOMS for swap
1323	#
1324	if [ ${swapsize:-0} -gt 0 -a "$ZFSBOOT_SWAP_MIRROR" ]; then
1325		for disk in $disks; do
1326			swap_devs="$swap_devs $disk$swappart"
1327		done
1328		f_eval_catch $funcname gmirror "$SWAP_GMIRROR_LABEL" \
1329			"$swap_devs" || return $FAILURE
1330	fi
1331
1332	#
1333	# Create the ZFS root pool with desired type and disk devices
1334	#
1335	f_dprintf "$funcname: Creating root pool..."
1336	create_options="$ZFSBOOT_POOL_CREATE_OPTIONS"
1337	if [ "$zroot_vdevtype" == "raid10" ]; then
1338		raid10_vdevs=""
1339		for vdev in $zroot_vdevs; do
1340			f_count nvdev $raid10_vdevs
1341			if [ $(( $nvdev % 3 )) -eq 0 ]; then
1342				raid10_vdevs="$raid10_vdevs mirror"
1343			fi
1344			raid10_vdevs="$raid10_vdevs $vdev"
1345		done
1346		f_eval_catch $funcname zpool "$ZPOOL_CREATE_WITH_OPTIONS" \
1347			"-o altroot=$BSDINSTALL_CHROOT $create_options -m none -f" \
1348			"$zroot_name" "" "$raid10_vdevs" || return $FAILURE
1349	else
1350		f_eval_catch $funcname zpool "$ZPOOL_CREATE_WITH_OPTIONS" \
1351			"-o altroot=$BSDINSTALL_CHROOT $create_options -m none -f" \
1352			"$zroot_name" "$zroot_vdevtype" "$zroot_vdevs" ||
1353			return $FAILURE
1354	fi
1355
1356	#
1357	# Create ZFS dataset layout within the new root pool
1358	#
1359	f_dprintf "$funcname: Creating ZFS datasets..."
1360	echo "$ZFSBOOT_DATASETS" | while read dataset options; do
1361		# Skip blank lines and comments
1362		case "$dataset" in "#"*|"") continue; esac
1363		# Remove potential inline comments in options
1364		options="${options%%#*}"
1365		# Replace tabs with spaces
1366		f_replaceall "$options" "	" " " options
1367		# Reduce contiguous runs of space to one single space
1368		oldoptions=
1369		while [ "$oldoptions" != "$options" ]; do
1370			oldoptions="$options"
1371			f_replaceall "$options" "  " " " options
1372		done
1373		# Replace both commas and spaces with ` -o '
1374		f_replaceall "$options" "[ ,]" " -o " options
1375		# Create the dataset with desired options
1376		f_eval_catch $funcname zfs "$ZFS_CREATE_WITH_OPTIONS" \
1377		             "${options:+-o $options}" "$zroot_name$dataset" ||
1378		             return $FAILURE
1379	done
1380
1381	#
1382	# Set a mountpoint for the root of the pool so newly created datasets
1383	# have a mountpoint to inherit
1384	#
1385	f_dprintf "$funcname: Setting mountpoint for root of the pool..."
1386	f_eval_catch $funcname zfs "$ZFS_SET" \
1387		"mountpoint=/$zroot_name" "$zroot_name" || return $FAILURE
1388
1389	# Touch up permissions on the tmp directories
1390	f_dprintf "$funcname: Modifying directory permissions..."
1391	local dir
1392	for dir in /tmp /var/tmp; do
1393		f_eval_catch $funcname mkdir "$MKDIR_P" \
1394		             $BSDINSTALL_CHROOT$dir || return $FAILURE
1395		f_eval_catch $funcname chmod "$CHMOD_MODE" 1777 \
1396		             $BSDINSTALL_CHROOT$dir || return $FAILURE
1397	done
1398
1399	# Set bootfs property
1400	local zroot_bootfs="$ZFSBOOT_BEROOT_NAME/$ZFSBOOT_BOOTFS_NAME"
1401	f_dprintf "$funcname: Setting bootfs property..."
1402	f_eval_catch $funcname zpool "$ZPOOL_SET" \
1403		"bootfs=\"$zroot_name/$zroot_bootfs\"" "$zroot_name" ||
1404		return $FAILURE
1405
1406	# MBR boot loader touch-up
1407	if [ "$ZFSBOOT_PARTITION_SCHEME" = "MBR" ]; then
1408		# Export the pool(s)
1409		f_dprintf "$funcname: Temporarily exporting ZFS pool(s)..."
1410		f_eval_catch $funcname zpool "$ZPOOL_EXPORT" "$zroot_name" ||
1411			     return $FAILURE
1412		if [ "$ZFSBOOT_BOOT_POOL" ]; then
1413			f_eval_catch $funcname zpool "$ZPOOL_EXPORT" \
1414				     "$bootpool_name" || return $FAILURE
1415		fi
1416
1417		f_dprintf "$funcname: Updating MBR boot loader on disks..."
1418		# Stick the ZFS boot loader in the "convenient hole" after
1419		# the ZFS internal metadata
1420		for disk in $disks; do
1421			f_eval_catch $funcname dd "$DD_WITH_OPTIONS" \
1422			             /boot/zfsboot /dev/$disk$bootpart \
1423			             "skip=1 seek=1024" || return $FAILURE
1424		done
1425
1426		# Re-import the ZFS pool(s)
1427		f_dprintf "$funcname: Re-importing ZFS pool(s)..."
1428		f_eval_catch $funcname zpool "$ZPOOL_IMPORT_WITH_OPTIONS" \
1429			     "-o altroot=\"$BSDINSTALL_CHROOT\"" \
1430			     "$zroot_name" || return $FAILURE
1431		if [ "$ZFSBOOT_BOOT_POOL" ]; then
1432			# Import the bootpool, but do not mount it yet
1433			f_eval_catch $funcname zpool \
1434				     "$ZPOOL_IMPORT_WITH_OPTIONS" \
1435				     "-o altroot=\"$BSDINSTALL_CHROOT\" -N" \
1436				     "$bootpool_name" || return $FAILURE
1437		fi
1438	fi
1439
1440	# Remount bootpool and create symlink(s)
1441	if [ "$ZFSBOOT_BOOT_POOL" ]; then
1442		f_eval_catch $funcname zfs "$ZFS_MOUNT" "$bootpool_name" ||
1443			return $FAILURE
1444		f_dprintf "$funcname: Creating /boot symlink for boot pool..."
1445		f_eval_catch $funcname ln "$LN_SF" "$bootpool_name/boot" \
1446		             $BSDINSTALL_CHROOT/boot || return $FAILURE
1447	fi
1448
1449	# zpool.cache is required to mount more than one pool at boot time
1450	f_dprintf "$funcname: Configuring zpool.cache for zroot..."
1451	f_eval_catch $funcname mkdir "$MKDIR_P" $BSDINSTALL_CHROOT/boot/zfs ||
1452	             return $FAILURE
1453	f_eval_catch $funcname zpool "$ZPOOL_SET" \
1454	             "cachefile=\"$BSDINSTALL_CHROOT/boot/zfs/zpool.cache\"" \
1455	             "$zroot_name" || return $FAILURE
1456
1457	if [ "$ZFSBOOT_BOOT_POOL" ]; then
1458		f_eval_catch $funcname printf "$PRINTF_CONF" \
1459			vfs.root.mountfrom \
1460			"\"zfs:$zroot_name/$zroot_bootfs\"" \
1461			$BSDINSTALL_TMPBOOT/loader.conf.root || return $FAILURE
1462	fi
1463	#
1464	# Set canmount=noauto so that the default Boot Environment (BE) does
1465	# not get mounted if a different BE is selected from the beastie menu
1466	#
1467	f_dprintf "$funcname: Set canmount=noauto for the root of the pool..."
1468	f_eval_catch $funcname zfs "$ZFS_SET" "canmount=noauto" \
1469		"$zroot_name/$ZFSBOOT_BEROOT_NAME/$ZFSBOOT_BOOTFS_NAME"
1470
1471	# Last, but not least... required lines for rc.conf(5)/loader.conf(5)
1472	# NOTE: We later concatenate these into their destination
1473	f_dprintf "%s: Configuring rc.conf(5)/loader.conf(5) additions..." \
1474	          "$funcname"
1475	f_eval_catch $funcname echo "$ECHO_APPEND" 'zfs_enable=\"YES\"' \
1476	             $BSDINSTALL_TMPETC/rc.conf.zfs || return $FAILURE
1477	f_eval_catch $funcname echo "$ECHO_APPEND" \
1478	             'kern.geom.label.disk_ident.enable=\"0\"' \
1479	             $BSDINSTALL_TMPBOOT/loader.conf.zfs || return $FAILURE
1480	f_eval_catch $funcname echo "$ECHO_APPEND" \
1481	             'kern.geom.label.gptid.enable=\"0\"' \
1482	             $BSDINSTALL_TMPBOOT/loader.conf.zfs || return $FAILURE
1483
1484	if [ "$ZFSBOOT_FORCE_4K_SECTORS" ]; then
1485		f_eval_catch $funcname echo "$ECHO_APPEND" \
1486	             'vfs.zfs.min_auto_ashift=12' \
1487	             $BSDINSTALL_TMPETC/sysctl.conf.zfs || return $FAILURE
1488	fi
1489
1490	if [ "$ZFSBOOT_SWAP_MIRROR" ]; then
1491		f_eval_catch $funcname echo "$ECHO_APPEND" \
1492		             'geom_mirror_load=\"YES\"' \
1493		             $BSDINSTALL_TMPBOOT/loader.conf.gmirror ||
1494		             return $FAILURE
1495	fi
1496
1497	# We're all done unless we should go on to do encryption
1498	[ "$ZFSBOOT_GELI_ENCRYPTION" ] || return $SUCCESS
1499
1500	#
1501	# Configure geli(8)-based encryption
1502	#
1503	f_dprintf "$funcname: Configuring disk encryption..."
1504	f_eval_catch $funcname echo "$ECHO_APPEND" 'aesni_load=\"YES\"' \
1505		$BSDINSTALL_TMPBOOT/loader.conf.aesni || return $FAILURE
1506	f_eval_catch $funcname echo "$ECHO_APPEND" 'geom_eli_load=\"YES\"' \
1507		$BSDINSTALL_TMPBOOT/loader.conf.geli || return $FAILURE
1508
1509	# We're all done unless we should go on for boot pool
1510	[ "$ZFSBOOT_BOOT_POOL" ] || return $SUCCESS
1511
1512	for disk in $disks; do
1513		f_eval_catch $funcname printf "$PRINTF_CONF" \
1514			geli_%s_keyfile0_load "$disk$targetpart YES" \
1515			$BSDINSTALL_TMPBOOT/loader.conf.$disk$targetpart ||
1516			return $FAILURE
1517		f_eval_catch $funcname printf "$PRINTF_CONF" \
1518			geli_%s_keyfile0_type \
1519			"$disk$targetpart $disk$targetpart:geli_keyfile0" \
1520			$BSDINSTALL_TMPBOOT/loader.conf.$disk$targetpart ||
1521			return $FAILURE
1522		f_eval_catch $funcname printf "$PRINTF_CONF" \
1523			geli_%s_keyfile0_name \
1524			"$disk$targetpart \"$ZFSBOOT_GELI_KEY_FILE\"" \
1525			$BSDINSTALL_TMPBOOT/loader.conf.$disk$targetpart ||
1526			return $FAILURE
1527	done
1528
1529	# Set cachefile for boot pool so it auto-imports at system start
1530	f_dprintf "$funcname: Configuring zpool.cache for boot pool..."
1531	f_eval_catch $funcname zpool "$ZPOOL_SET" \
1532	             "cachefile=\"$BSDINSTALL_CHROOT/boot/zfs/zpool.cache\"" \
1533	             "$bootpool_name" || return $FAILURE
1534
1535	# Some additional geli(8) requirements for loader.conf(5)
1536	for option in \
1537		'zpool_cache_load=\"YES\"' \
1538		'zpool_cache_type=\"/boot/zfs/zpool.cache\"' \
1539		'zpool_cache_name=\"/boot/zfs/zpool.cache\"' \
1540		'geom_eli_passphrase_prompt=\"YES\"' \
1541	; do
1542		f_eval_catch $funcname echo "$ECHO_APPEND" "$option" \
1543		             $BSDINSTALL_TMPBOOT/loader.conf.zfs ||
1544		             return $FAILURE
1545	done
1546	return $SUCCESS
1547}
1548
1549# dialog_menu_diskinfo
1550#
1551# Prompt the user to select a disk and then provide detailed info on it.
1552#
1553dialog_menu_diskinfo()
1554{
1555	local device disk
1556
1557	#
1558	# Break from loop when user cancels disk selection
1559	#
1560	while :; do
1561		device=$( msg_cancel="$msg_back" f_device_menu \
1562			"$DIALOG_TITLE" "$msg_select_a_disk_device" "" \
1563			$DEVICE_TYPE_DISK 2>&1 ) || break
1564		$device get name disk
1565
1566		# Show gpart(8) `show' and camcontrol(8) `inquiry' data
1567		f_show_msg "$msg_detailed_disk_info" \
1568			"$disk" "$( gpart show $disk 2> /dev/null )" \
1569			"$disk" "$( camcontrol inquiry $disk 2> /dev/null )" \
1570			"$disk" "$( camcontrol identify $disk 2> /dev/null )"
1571	done
1572
1573	return $SUCCESS
1574}
1575
1576dialog_zpool_name()
1577{
1578	local prompt="$* is already taken, please enter a name for the ZFS pool \
1579	(Or confirm using the same name by just pressing enter)"
1580	local hline=
1581	local value="$*"
1582	local height width
1583
1584	f_dialog_inputbox_size height width \
1585		"$DIALOG_TITLE" "$DIALOG_BACKTITLE" "$prompt" "$value" "$hline"
1586
1587	$DIALOG \
1588		--title "$DIALOG_TITLE"         \
1589		--backtitle "$DIALOG_BACKTITLE" \
1590		--hline "$hline"                \
1591		--ok-label "Ok"                 \
1592		--no-cancel                     \
1593		--inputbox "$prompt"            \
1594		$height $width "$value"         \
1595		2>&1 >&$DIALOG_TERMINAL_PASSTHRU_FD
1596}
1597
1598############################################################ MAIN
1599
1600#
1601# Initialize
1602#
1603f_dialog_title "$msg_zfs_configuration"
1604f_dialog_backtitle "$msg_freebsd_installer"
1605
1606# User may have specifically requested ZFS-related operations be interactive
1607! f_interactive && f_zfsinteractive && unset $VAR_NONINTERACTIVE
1608
1609#
1610# Debugging
1611#
1612f_dprintf "BSDINSTALL_CHROOT=[%s]" "$BSDINSTALL_CHROOT"
1613f_dprintf "BSDINSTALL_TMPETC=[%s]" "$BSDINSTALL_TMPETC"
1614f_dprintf "FSTAB_FMT=[%s]" "$FSTAB_FMT"
1615
1616pools=$(zpool import | awk '$1 == "pool:" { print $2}')
1617for pool in ${pools}; do
1618	f_dprintf "Checking ${pool} against ${ZFSBOOT_POOL_NAME}"
1619	if [ "${pool}" = "${ZFSBOOT_POOL_NAME}" ]; then
1620		f_dprintf "Pool ${pool} already taken"
1621		ZFSBOOT_POOL_NAME=$(dialog_zpool_name "${ZFSBOOT_POOL_NAME}")
1622		break;
1623	fi
1624done
1625
1626#
1627# Determine default boot type
1628#
1629case $(uname -m) in
1630arm64|riscv)
1631	# We support only UEFI boot for arm64 and riscv.
1632	: ${ZFSBOOT_BOOT_TYPE:=UEFI}
1633	: ${ZFSBOOT_PARTITION_SCHEME:=GPT}
1634	;;
1635*)
1636	# If the system was booted with UEFI, set the default boot type to UEFI
1637	bootmethod=$( sysctl -n machdep.bootmethod )
1638	f_dprintf "machdep.bootmethod=[%s]" "$bootmethod"
1639	if [ "$bootmethod" = "UEFI" ]; then
1640		: ${ZFSBOOT_BOOT_TYPE:=BIOS+UEFI}
1641		: ${ZFSBOOT_PARTITION_SCHEME:=GPT}
1642	else
1643		: ${ZFSBOOT_BOOT_TYPE:=BIOS}
1644		: ${ZFSBOOT_PARTITION_SCHEME:=GPT}
1645	fi
1646	;;
1647esac
1648
1649#
1650# Loop over the main menu until we've accomplished what we came here to do
1651#
1652while :; do
1653	if ! f_interactive; then
1654		retval=$DIALOG_OK
1655		mtag=">>> $msg_install"
1656	else
1657		dialog_menu_main
1658		retval=$?
1659		f_dialog_menutag_fetch mtag
1660	fi
1661
1662	f_dprintf "retval=%u mtag=[%s]" $retval "$mtag"
1663	[ $retval -eq $DIALOG_OK ] || f_die
1664
1665	case "$mtag" in
1666	">>> $msg_install")
1667		#
1668		# First, validate the user's selections
1669		#
1670
1671		# Make sure they gave us a name for the pool
1672		if [ ! "$ZFSBOOT_POOL_NAME" ]; then
1673			f_dprintf "Pool name cannot be empty."
1674			f_show_err "$msg_pool_name_cannot_be_empty"
1675			continue
1676		fi
1677
1678		# Validate vdev type against number of disks selected/scripted
1679		# (also validates that ZFSBOOT_DISKS are real [probed] disks)
1680		# NB: dialog_menu_layout supports running non-interactively
1681		dialog_menu_layout || continue
1682
1683		# Make sure each disk will have room for ZFS
1684		if f_expand_number "$ZFSBOOT_SWAP_SIZE" swapsize &&
1685		   f_expand_number "$ZFSBOOT_BOOT_POOL_SIZE" bootsize &&
1686		   f_expand_number "1g" zpoolmin
1687		then
1688			minsize=$swapsize teeny_disks=
1689			if [ "$ZFSBOOT_POOL_SIZE" ]; then
1690				f_expand_number "$ZFSBOOT_POOL_SIZE" poolsize
1691				minsize=$(( $minsize + $poolsize ))
1692			fi
1693			[ "$ZFSBOOT_BOOT_POOL" ] &&
1694				minsize=$(( $minsize + $bootsize ))
1695			for disk in $ZFSBOOT_DISKS; do
1696				debug= f_device_find -1 \
1697					$disk $DEVICE_TYPE_DISK device
1698				$device get capacity disksize || continue
1699				[ ${disksize:-0} -ge 0 ] || disksize=0
1700				[ $disksize -lt $minsize ] &&
1701					teeny_disks="$teeny_disks $disk"
1702			done
1703			if [ "$teeny_disks" ]; then
1704				f_dprintf "swapsize=[%s] bootsize[%s] %s" \
1705				          "$ZFSBOOT_SWAP_SIZE" \
1706				          "$ZFSBOOT_BOOT_POOL_SIZE" \
1707				          "minsize=[$minsize]"
1708				f_dprintf "These disks are too small: %s" \
1709				          "$teeny_disks"
1710				f_show_err "$msg_these_disks_are_too_small" \
1711				           "$ZFSBOOT_SWAP_SIZE" \
1712				           "$ZFSBOOT_BOOT_POOL_SIZE" \
1713				           "$teeny_disks"
1714				continue
1715			fi
1716		fi
1717
1718		#
1719		# Last Chance!
1720		#
1721		if f_interactive; then
1722			dialog_last_chance $ZFSBOOT_DISKS || continue
1723		fi
1724
1725		#
1726		# Let's do this
1727		#
1728
1729		vdev_type="$ZFSBOOT_VDEV_TYPE"
1730
1731		# Blank the vdev type for the default layout
1732		[ "$vdev_type" = "stripe" ] && vdev_type=
1733
1734		zfs_create_boot "$ZFSBOOT_POOL_NAME" \
1735		                "$vdev_type" $ZFSBOOT_DISKS || continue
1736
1737		# To be reused by bootconfig
1738		echo "$ZFSBOOT_DISKS" > ${TMPDIR:-"/tmp"}/bsdinstall-zfsboot
1739
1740		break # to success
1741		;;
1742	?" $msg_pool_type_disks")
1743		ZFSBOOT_CONFIRM_LAYOUT=1
1744		dialog_menu_layout
1745		# User has poked settings, disable later confirmation
1746		ZFSBOOT_CONFIRM_LAYOUT=
1747		;;
1748	"- $msg_rescan_devices") f_device_rescan ;;
1749	"- $msg_disk_info") dialog_menu_diskinfo ;;
1750	?" $msg_pool_name")
1751		# Prompt the user to input/change the name for the new pool
1752		f_dialog_input input \
1753			"$msg_please_enter_a_name_for_your_zpool" \
1754			"$ZFSBOOT_POOL_NAME" &&
1755			ZFSBOOT_POOL_NAME="$input"
1756		;;
1757	?" $msg_force_4k_sectors")
1758		# Toggle the variable referenced both by the menu and later
1759		if [ "$ZFSBOOT_FORCE_4K_SECTORS" ]; then
1760			ZFSBOOT_FORCE_4K_SECTORS=
1761		else
1762			ZFSBOOT_FORCE_4K_SECTORS=1
1763		fi
1764		;;
1765	?" $msg_encrypt_disks")
1766		# Toggle the variable referenced both by the menu and later
1767		if [ "$ZFSBOOT_GELI_ENCRYPTION" ]; then
1768			ZFSBOOT_GELI_ENCRYPTION=
1769		else
1770			ZFSBOOT_FORCE_4K_SECTORS=1
1771			ZFSBOOT_GELI_ENCRYPTION=1
1772		fi
1773		;;
1774	?" $msg_partition_scheme")
1775		# Toggle between GPT (BIOS), GPT (UEFI) and MBR
1776		if [ "$ZFSBOOT_PARTITION_SCHEME" = "GPT" -a \
1777		     "$ZFSBOOT_BOOT_TYPE" = "BIOS" ]
1778		then
1779			ZFSBOOT_PARTITION_SCHEME="GPT"
1780			ZFSBOOT_BOOT_TYPE="UEFI"
1781		elif [ "$ZFSBOOT_PARTITION_SCHEME" = "GPT" -a \
1782		       "$ZFSBOOT_BOOT_TYPE" = "UEFI" ]
1783		then
1784			ZFSBOOT_PARTITION_SCHEME="GPT"
1785			ZFSBOOT_BOOT_TYPE="BIOS+UEFI"
1786		elif [ "$ZFSBOOT_PARTITION_SCHEME" = "GPT" ]; then
1787			ZFSBOOT_PARTITION_SCHEME="MBR"
1788			ZFSBOOT_BOOT_TYPE="BIOS"
1789		elif [ "$ZFSBOOT_PARTITION_SCHEME" = "MBR" ]; then
1790			ZFSBOOT_PARTITION_SCHEME="GPT + Active"
1791			ZFSBOOT_BOOT_TYPE="BIOS"
1792		elif [ "$ZFSBOOT_PARTITION_SCHEME" = "GPT + Active" ]; then
1793			ZFSBOOT_PARTITION_SCHEME="GPT + Lenovo Fix"
1794			ZFSBOOT_BOOT_TYPE="BIOS"
1795		else
1796			ZFSBOOT_PARTITION_SCHEME="GPT"
1797			ZFSBOOT_BOOT_TYPE="BIOS"
1798		fi
1799		;;
1800	?" $msg_swap_size")
1801		# Prompt the user to input/change the swap size for each disk
1802		while :; do
1803		    f_dialog_input input \
1804			    "$msg_please_enter_amount_of_swap_space" \
1805			    "$ZFSBOOT_SWAP_SIZE" &&
1806			    ZFSBOOT_SWAP_SIZE="${input:-0}"
1807		    if f_expand_number "$ZFSBOOT_SWAP_SIZE" swapsize
1808		    then
1809			if [ $swapsize -ne 0 -a $swapsize -lt 104857600 ]; then
1810			    f_show_err "$msg_swap_toosmall" \
1811				       "$ZFSBOOT_SWAP_SIZE"
1812			    continue;
1813			else
1814			    break;
1815			fi
1816		    else
1817			f_show_err "$msg_swap_invalid" \
1818				   "$ZFSBOOT_SWAP_SIZE"
1819			continue;
1820		    fi
1821		done
1822		;;
1823	?" $msg_swap_mirror")
1824		# Toggle the variable referenced both by the menu and later
1825		if [ "$ZFSBOOT_SWAP_MIRROR" ]; then
1826			ZFSBOOT_SWAP_MIRROR=
1827		else
1828			ZFSBOOT_SWAP_MIRROR=1
1829		fi
1830		;;
1831	?" $msg_swap_encrypt")
1832		# Toggle the variable referenced both by the menu and later
1833		if [ "$ZFSBOOT_SWAP_ENCRYPTION" ]; then
1834			ZFSBOOT_SWAP_ENCRYPTION=
1835		else
1836			ZFSBOOT_SWAP_ENCRYPTION=1
1837		fi
1838		;;
1839	esac
1840done
1841
1842exit $SUCCESS
1843
1844################################################################################
1845# END
1846################################################################################
1847