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