xref: /freebsd/usr.sbin/bsdinstall/scripts/zfsboot (revision 788ca347b816afd83b2885e0c79aeeb88649b2ab)
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_mirror="Mirror Swap?"
291msg_swap_mirror_help="Mirror swap partitions for redundancy, breaks crash dumps"
292msg_swap_size="Swap Size"
293msg_swap_size_help="Customize how much swap space is allocated to each selected disk"
294msg_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."
295msg_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?"
296msg_unable_to_get_disk_capacity="Unable to get disk capacity of \`%s'"
297msg_unsupported_partition_scheme="%s is an unsupported partition scheme"
298msg_user_cancelled="User Cancelled."
299msg_yes="YES"
300msg_zfs_configuration="ZFS Configuration"
301
302############################################################ FUNCTIONS
303
304# dialog_menu_main
305#
306# Display the dialog(1)-based application main menu.
307#
308dialog_menu_main()
309{
310	local title="$DIALOG_TITLE"
311	local btitle="$DIALOG_BACKTITLE"
312	local prompt="$msg_configure_options"
313	local force4k="$msg_no"
314	local usegeli="$msg_no"
315	local swapgeli="$msg_no"
316	local swapmirror="$msg_no"
317	[ "$ZFSBOOT_FORCE_4K_SECTORS" ] && force4k="$msg_yes"
318	[ "$ZFSBOOT_GELI_ENCRYPTION" ] && usegeli="$msg_yes"
319	[ "$ZFSBOOT_SWAP_ENCRYPTION" ] && swapgeli="$msg_yes"
320	[ "$ZFSBOOT_SWAP_MIRROR" ] && swapmirror="$msg_yes"
321	local disks n disks_grammar
322	f_count n $ZFSBOOT_DISKS
323	{ [ $n -eq 1 ] && disks_grammar=$msg_disk_singular; } ||
324		disks_grammar=$msg_disk_plural # grammar
325	local menu_list="
326		'>>> $msg_install'      '$msg_install_desc'
327		                        '$msg_install_help'
328		'T $msg_pool_type_disks'
329		                        '$ZFSBOOT_VDEV_TYPE: $n $disks_grammar'
330		                        '$msg_pool_type_disks_help'
331		'- $msg_rescan_devices' '*'
332		                        '$msg_rescan_devices_help'
333		'- $msg_disk_info'      '*'
334		                        '$msg_disk_info_help'
335		'N $msg_pool_name'      '$ZFSBOOT_POOL_NAME'
336		                        '$msg_pool_name_help'
337		'4 $msg_force_4k_sectors'
338		                        '$force4k'
339		                        '$msg_force_4k_sectors_help'
340		'E $msg_encrypt_disks'  '$usegeli'
341		                        '$msg_encrypt_disks_help'
342		'P $msg_partition_scheme'
343		                        '$ZFSBOOT_PARTITION_SCHEME'
344		                        '$msg_partition_scheme_help'
345		'S $msg_swap_size'      '$ZFSBOOT_SWAP_SIZE'
346		                        '$msg_swap_size_help'
347		'M $msg_swap_mirror'    '$swapmirror'
348		                        '$msg_swap_mirror_help'
349		'W $msg_swap_encrypt'   '$swapgeli'
350		                        '$msg_swap_encrypt_help'
351	" # END-QUOTE
352	local defaultitem= # Calculated below
353	local hline="$hline_alnum_arrows_punc_tab_enter"
354
355	local height width rows
356	eval f_dialog_menu_with_help_size height width rows \
357		\"\$title\" \"\$btitle\" \"\$prompt\" \"\$hline\" $menu_list
358
359	# Obtain default-item from previously stored selection
360	f_dialog_default_fetch defaultitem
361
362	local menu_choice
363	menu_choice=$( eval $DIALOG \
364		--title \"\$title\"              \
365		--backtitle \"\$btitle\"         \
366		--hline \"\$hline\"              \
367		--item-help                      \
368		--ok-label \"\$msg_select\"      \
369		--cancel-label \"\$msg_cancel\"  \
370		--default-item \"\$defaultitem\" \
371		--menu \"\$prompt\"              \
372		$height $width $rows             \
373		$menu_list                       \
374		2>&1 >&$DIALOG_TERMINAL_PASSTHRU_FD
375	)
376	local retval=$?
377	f_dialog_data_sanitize menu_choice
378	f_dialog_menutag_store "$menu_choice"
379
380	# Only update default-item on success
381	[ $retval -eq $DIALOG_OK ] && f_dialog_default_store "$menu_choice"
382
383	return $retval
384}
385
386# dialog_last_chance $disks ...
387#
388# Display a list of the disks that the user is about to destroy. The default
389# action is to return error status unless the user explicitly (non-default)
390# selects "Yes" from the noyes dialog.
391#
392dialog_last_chance()
393{
394	local title="$DIALOG_TITLE"
395	local btitle="$DIALOG_BACKTITLE"
396	local prompt # Calculated below
397	local hline="$hline_arrows_tab_enter"
398
399	local height=8 width=50 prefix="   "
400	local plen=${#prefix} list= line=
401	local max_width=$(( $width - 3 - $plen ))
402
403	local yes no defaultno extra_args format
404	if [ "$USE_XDIALOG" ]; then
405		yes=ok no=cancel defaultno=default-no
406		extra_args="--wrap --left"
407		format="$msg_last_chance_are_you_sure"
408	else
409		yes=yes no=no defaultno=defaultno
410		extra_args="--colors --cr-wrap"
411		format="$msg_last_chance_are_you_sure_color"
412	fi
413
414	local disk line_width
415	for disk in $*; do
416		if [ "$line" ]; then
417			line_width=${#line}
418		else
419			line_width=$plen
420		fi
421		line_width=$(( $line_width + 1 + ${#disk} ))
422		# Add newline before disk if it would exceed max_width
423		if [ $line_width -gt $max_width ]; then
424			list="$list$line\n"
425			line="$prefix"
426			height=$(( $height + 1 ))
427		fi
428		# Add the disk to the list
429		line="$line $disk"
430	done
431	# Append the left-overs
432	if [ "${line#$prefix}" ]; then
433		list="$list$line"
434		height=$(( $height + 1 ))
435	fi
436
437	# Add height for Xdialog(1)
438	[ "$USE_XDIALOG" ] && height=$(( $height + $height / 5 + 3 ))
439
440	prompt=$( printf "$format" "$list" )
441	f_dprintf "%s: Last Chance!" "$0"
442	$DIALOG \
443		--title "$title"        \
444		--backtitle "$btitle"   \
445		--hline "$hline"        \
446		--$defaultno            \
447		--$yes-label "$msg_yes" \
448		--$no-label "$msg_no"   \
449		$extra_args             \
450		--yesno "$prompt" $height $width
451}
452
453# dialog_menu_layout
454#
455# Configure Virtual Device type and disks to use for the ZFS boot pool. User
456# must select enough disks to satisfy the chosen vdev type.
457#
458dialog_menu_layout()
459{
460	local funcname=dialog_menu_layout
461	local title="$DIALOG_TITLE"
462	local btitle="$DIALOG_BACKTITLE"
463	local vdev_prompt="$msg_select_virtual_device_type"
464	local disk_prompt="$msg_please_select_one_or_more_disks"
465	local vdev_menu_list="
466		'stripe' '$msg_stripe_desc' '$msg_stripe_help'
467		'mirror' '$msg_mirror_desc' '$msg_mirror_help'
468		'raidz1' '$msg_raidz1_desc' '$msg_raidz1_help'
469		'raidz2' '$msg_raidz2_desc' '$msg_raidz2_help'
470		'raidz3' '$msg_raidz3_desc' '$msg_raidz3_help'
471	" # END-QUOTE
472	local disk_check_list= # Calculated below
473	local vdev_hline="$hline_arrows_tab_enter"
474	local disk_hline="$hline_arrows_space_tab_enter"
475
476	# Warn the user if vdev type is not valid
477	case "$ZFSBOOT_VDEV_TYPE" in
478	stripe|mirror|raidz1|raidz2|raidz3) : known good ;;
479	*)
480		f_dprintf "%s: Invalid virtual device type \`%s'" \
481			  $funcname "$ZFSBOOT_VDEV_TYPE"
482		f_show_err "$msg_invalid_virtual_device_type" \
483			   "$ZFSBOOT_VDEV_TYPE"
484		f_interactive || return $FAILURE
485	esac
486
487	# Calculate size of vdev menu once only
488	local vheight vwidth vrows
489	eval f_dialog_menu_with_help_size vheight vwidth vrows \
490		\"\$title\" \"\$btitle\" \"\$vdev_prompt\" \"\$vdev_hline\" \
491		$vdev_menu_list
492
493	# Get a list of probed disk devices
494	local disks=
495	debug= f_device_find "" $DEVICE_TYPE_DISK disks
496
497	# Prune out mounted md(4) devices that may be part of the boot process
498	local disk name new_list=
499	for disk in $disks; do
500		debug= $disk get name name
501		case "$name" in
502		md[0-9]*) f_mounted -b "/dev/$name" && continue ;;
503		esac
504		new_list="$new_list $disk"
505	done
506	disks="${new_list# }"
507
508	# Debugging
509	if [ "$debug" ]; then
510		local disk_names=
511		for disk in $disks; do
512			debug= $disk get name name
513			disk_names="$disk_names $name"
514		done
515		f_dprintf "$funcname: disks=[%s]" "${disk_names# }"
516	fi
517
518	if [ ! "$disks" ]; then
519		f_dprintf "No disk(s) present to configure"
520		f_show_err "$msg_no_disks_present_to_configure"
521		return $FAILURE
522	fi
523
524	# Lets sort the disks array to be more user friendly
525	f_device_sort_by name disks disks
526
527	#
528	# Operate in a loop so we can (if interactive) repeat if not enough
529	# disks are selected to satisfy the chosen vdev type or user wants to
530	# back-up to the previous menu.
531	#
532	local vardisk ndisks onoff selections vdev_choice breakout device
533	local valid_disks all_valid want_disks desc height width rows
534	while :; do
535		#
536		# Confirm the vdev type that was selected
537		#
538		if f_interactive && [ "$ZFSBOOT_CONFIRM_LAYOUT" ]; then
539			vdev_choice=$( eval $DIALOG \
540				--title \"\$title\"              \
541				--backtitle \"\$btitle\"         \
542				--hline \"\$vdev_hline\"         \
543				--ok-label \"\$msg_ok\"          \
544				--cancel-label \"\$msg_cancel\"  \
545				--item-help                      \
546				--default-item \"\$ZFSBOOT_VDEV_TYPE\" \
547				--menu \"\$vdev_prompt\"         \
548				$vheight $vwidth $vrows          \
549				$vdev_menu_list                  \
550				2>&1 >&$DIALOG_TERMINAL_PASSTHRU_FD
551			) || return $?
552				# Exit if user pressed ESC or chose Cancel/No
553			f_dialog_data_sanitize vdev_choice
554
555			ZFSBOOT_VDEV_TYPE="$vdev_choice"
556			f_dprintf "$funcname: ZFSBOOT_VDEV_TYPE=[%s]" \
557			          "$ZFSBOOT_VDEV_TYPE"
558		fi
559
560		# Determine the number of disks needed for this vdev type
561		want_disks=0
562		case "$ZFSBOOT_VDEV_TYPE" in
563		stripe) want_disks=1 ;;
564		mirror) want_disks=2 ;;
565		raidz1) want_disks=3 ;;
566		raidz2) want_disks=4 ;;
567		raidz3) want_disks=5 ;;
568		esac
569
570		#
571		# Warn the user if any scripted disks are invalid
572		#
573		valid_disks= all_valid=${ZFSBOOT_DISKS:+1} # optimism
574		for disk in $ZFSBOOT_DISKS; do
575			if debug= f_device_find -1 \
576				$disk $DEVICE_TYPE_DISK device
577			then
578				valid_disks="$valid_disks $disk"
579				continue
580			fi
581			f_dprintf "$funcname: \`%s' is not a real disk" "$disk"
582			all_valid=
583		done
584		if [ ! "$all_valid" ]; then
585			if [ "$ZFSBOOT_DISKS" ]; then
586				f_show_err \
587				    "$msg_missing_one_or_more_scripted_disks"
588			else
589				f_dprintf "No disks selected."
590				f_interactive ||
591					f_show_err "$msg_no_disks_selected"
592			fi
593			f_interactive || return $FAILURE
594		fi
595		ZFSBOOT_DISKS="${valid_disks# }"
596
597		#
598		# Short-circuit if we're running non-interactively
599		#
600		if ! f_interactive || [ ! "$ZFSBOOT_CONFIRM_LAYOUT" ]; then
601			f_count ndisks $ZFSBOOT_DISKS
602			[ $ndisks -ge $want_disks ] && break # to success
603
604			# Not enough disks selected
605			f_dprintf "$funcname: %s: %s (%u < %u minimum)" \
606				  "$ZFSBOOT_VDEV_TYPE" \
607			          "Not enough disks selected." \
608				  $ndisks $want_disks
609			f_interactive || return $FAILURE
610			msg_yes="$msg_change_selection" msg_no="$msg_cancel" \
611				f_yesno "%s: $msg_not_enough_disks_selected" \
612				"$ZFSBOOT_VDEV_TYPE" $ndisks $want_disks ||
613				return $FAILURE
614		fi
615
616		#
617		# Confirm the disks that were selected
618		# Loop until the user cancels or selects enough disks
619		#
620		breakout=
621		while :; do
622			# Loop over list of available disks, resetting state
623			for disk in $disks; do
624				f_isset _${disk}_status && _${disk}_status=
625			done
626
627			# Loop over list of selected disks and create temporary
628			# locals to map statuses onto up-to-date list of disks
629			for disk in $ZFSBOOT_DISKS; do
630				debug= f_device_find -1 \
631					$disk $DEVICE_TYPE_DISK disk
632				f_isset _${disk}_status ||
633					local _${disk}_status
634				_${disk}_status=on
635			done
636
637			# Create the checklist menu of discovered disk devices
638			disk_check_list=
639			for disk in $disks; do
640				desc=
641				$disk get name name
642				$disk get desc desc
643				f_shell_escape "$desc" desc
644				f_getvar _${disk}_status:-off onoff
645				disk_check_list="$disk_check_list
646					$name '$desc' $onoff"
647			done
648
649			eval f_dialog_checklist_size height width rows \
650				\"\$title\" \"\$btitle\" \"\$prompt\" \
651				\"\$hline\" $disk_check_list
652
653			selections=$( eval $DIALOG \
654				--title \"\$DIALOG_TITLE\"         \
655				--backtitle \"\$DIALOG_BACKTITLE\" \
656				--separate-output                  \
657				--hline \"\$hline\"                \
658				--ok-label \"\$msg_ok\"            \
659				--cancel-label \"\$msg_back\"      \
660				--checklist \"\$prompt\"           \
661				$height $width $rows               \
662				$disk_check_list                   \
663				2>&1 >&$DIALOG_TERMINAL_PASSTHRU_FD
664			) || break
665				# Loop if user pressed ESC or chose Cancel/No
666			f_dialog_data_sanitize selections
667
668			ZFSBOOT_DISKS="$selections"
669			f_dprintf "$funcname: ZFSBOOT_DISKS=[%s]" \
670			          "$ZFSBOOT_DISKS"
671
672			f_count ndisks $ZFSBOOT_DISKS
673			[ $ndisks -ge $want_disks ] &&
674				breakout=break && break
675
676			# Not enough disks selected
677			f_dprintf "$funcname: %s: %s (%u < %u minimum)" \
678				  "$ZFSBOOT_VDEV_TYPE" \
679			          "Not enough disks selected." \
680			          $ndisks $want_disks
681			msg_yes="$msg_change_selection" msg_no="$msg_cancel" \
682				f_yesno "%s: $msg_not_enough_disks_selected" \
683				"$ZFSBOOT_VDEV_TYPE" $ndisks $want_disks ||
684				break
685		done
686		[ "$breakout" = "break" ] && break
687		[ "$ZFSBOOT_CONFIRM_LAYOUT" ] || return $FAILURE
688	done
689
690	return $DIALOG_OK
691}
692
693# dialog_uefi_prompt
694#
695# Confirm that the user wants to continue with the installation on a BIOS
696# system when they have booted with UEFI
697#
698dialog_uefi_prompt()
699{
700	local title="$DIALOG_TITLE"
701	local btitle="$DIALOG_BACKTITLE"
702	local prompt # Calculated below
703	local hline="$hline_arrows_tab_enter"
704
705	local height=8 width=50 prefix="   "
706	local plen=${#prefix} list= line=
707	local max_width=$(( $width - 3 - $plen ))
708
709	local yes no defaultno extra_args format
710	if [ "$USE_XDIALOG" ]; then
711		yes=ok no=cancel defaultno=default-no
712		extra_args="--wrap --left"
713		format="$msg_uefi_not_supported"
714	else
715		yes=yes no=no defaultno=defaultno
716		extra_args="--cr-wrap"
717		format="$msg_uefi_not_supported"
718	fi
719
720	# Add height for Xdialog(1)
721	[ "$USE_XDIALOG" ] && height=$(( $height + $height / 5 + 3 ))
722
723	prompt=$( printf "$format" )
724	f_dprintf "%s: UEFI prompt" "$0"
725	$DIALOG \
726		--title "$title"        \
727		--backtitle "$btitle"   \
728		--hline "$hline"        \
729		--$yes-label "$msg_yes" \
730		--$no-label "$msg_no"   \
731		$extra_args             \
732		--yesno "$prompt" $height $width
733}
734
735# zfs_create_diskpart $disk $index
736#
737# For each block device to be used in the zpool, rather than just create the
738# zpool with the raw block devices (e.g., da0, da1, etc.) we create partitions
739# so we can have some real swap. This also provides wiggle room incase your
740# replacement drivers do not have the exact same sector counts.
741#
742# NOTE: $swapsize and $bootsize should be defined by the calling function.
743# NOTE: Sets $bootpart and $targetpart for the calling function.
744#
745zfs_create_diskpart()
746{
747	local funcname=zfs_create_diskpart
748	local disk="$1" index="$2"
749
750	# Check arguments
751	if [ ! "$disk" ]; then
752		f_dprintf "$funcname: NULL disk argument"
753		msg_error="$msg_error: $funcname" \
754			f_show_err "$msg_null_disk_argument"
755		return $FAILURE
756	fi
757	if [ "${disk#*[$IFS]}" != "$disk" ]; then
758		f_dprintf "$funcname: Invalid disk argument \`%s'" "$disk"
759		msg_error="$msg_error: $funcname" \
760			f_show_err "$msg_invalid_disk_argument" "$disk"
761		return $FAILURE
762	fi
763	if [ ! "$index" ]; then
764		f_dprintf "$funcname: NULL index argument"
765		msg_error="$msg_error: $funcname" \
766			f_show_err "$msg_null_index_argument"
767		return $FAILURE
768	fi
769	if ! f_isinteger "$index"; then
770		f_dprintf "$funcname: Invalid index argument \`%s'" "$index"
771		msg_error="$msg_error: $funcname" \
772			f_show_err "$msg_invalid_index_argument" "$index"
773		return $FAILURE
774	fi
775	f_dprintf "$funcname: disk=[%s] index=[%s]" "$disk" "$index"
776
777	# Check for unknown partition scheme before proceeding further
778	case "$ZFSBOOT_PARTITION_SCHEME" in
779	""|MBR|GPT) : known good ;;
780	*)
781		f_dprintf "$funcname: %s is an unsupported partition scheme" \
782		          "$ZFSBOOT_PARTITION_SCHEME"
783		msg_error="$msg_error: $funcname" f_show_err \
784			"$msg_unsupported_partition_scheme" \
785			"$ZFSBOOT_PARTITION_SCHEME"
786		return $FAILURE
787	esac
788
789	#
790	# Destroy whatever partition layout is currently on disk.
791	# NOTE: `-F' required to destroy if partitions still exist.
792	# NOTE: Failure is ok here, blank disk will have nothing to destroy.
793	#
794	f_dprintf "$funcname: Destroying all data/layouts on \`%s'..." "$disk"
795	f_eval_catch -d $funcname gpart "$GPART_DESTROY_F" $disk
796	f_eval_catch -d $funcname graid "$GRAID_DELETE" $disk
797	f_eval_catch -d $funcname zpool "$ZPOOL_LABELCLEAR_F" /dev/$disk
798
799	# Make doubly-sure backup GPT is destroyed
800	f_eval_catch -d $funcname gpart "$GPART_CREATE" gpt $disk
801	f_eval_catch -d $funcname gpart "$GPART_DESTROY_F" $disk
802
803	#
804	# Enable boot pool if encryption is desired
805	#
806	[ "$ZFSBOOT_GELI_ENCRYPTION" ] && ZFSBOOT_BOOT_POOL=1
807
808	#
809	# Lay down the desired type of partition scheme
810	#
811	local setsize mbrindex
812	case "$ZFSBOOT_PARTITION_SCHEME" in
813	""|GPT) f_dprintf "$funcname: Creating GPT layout..."
814		#
815		# 1. Create GPT layout using labels
816		#
817		f_eval_catch $funcname gpart "$GPART_CREATE" gpt $disk ||
818		             return $FAILURE
819
820		#
821		# 2. Add small freebsd-boot partition labeled `boot#'
822		#
823		f_eval_catch $funcname gpart "$GPART_ADD_LABEL_WITH_SIZE" \
824		             gptboot$index freebsd-boot 512k $disk ||
825		             return $FAILURE
826		f_eval_catch $funcname gpart "$GPART_BOOTCODE_PART" \
827		             /boot/pmbr /boot/gptzfsboot 1 $disk ||
828		             return $FAILURE
829
830		# NB: zpool will use the `zfs#' GPT labels
831		bootpart=p2 swappart=p2 targetpart=p2
832		[ ${swapsize:-0} -gt 0 ] && targetpart=p3
833
834		#
835		# Prepare boot pool if enabled (e.g., for geli(8))
836		#
837		if [ "$ZFSBOOT_BOOT_POOL" ]; then
838			bootpart=p2 swappart=p3 targetpart=p3
839			[ ${swapsize:-0} -gt 0 ] && targetpart=p4
840			f_eval_catch $funcname gpart \
841			             "$GPART_ADD_LABEL_WITH_SIZE" boot$index \
842			             freebsd-zfs ${bootsize}b $disk ||
843			             return $FAILURE
844			# Pedantically nuke any old labels
845			f_eval_catch -d $funcname zpool "$ZPOOL_LABELCLEAR_F" \
846			                /dev/$disk$bootpart
847			if [ "$ZFSBOOT_GELI_ENCRYPTION" ]; then
848				# Pedantically detach targetpart for later
849				f_eval_catch -d $funcname geli \
850				                "$GELI_DETACH_F" \
851				                /dev/$disk$targetpart
852			fi
853		fi
854
855		#
856		# 3. Add freebsd-swap partition labeled `swap#'
857		#
858		if [ ${swapsize:-0} -gt 0 ]; then
859			f_eval_catch $funcname gpart \
860			             "$GPART_ADD_LABEL_WITH_SIZE" swap$index \
861			             freebsd-swap ${swapsize}b $disk ||
862			             return $FAILURE
863			# Pedantically nuke any old labels on the swap
864			f_eval_catch -d $funcname zpool "$ZPOOL_LABELCLEAR_F" \
865			                /dev/$disk$swappart
866		fi
867
868		#
869		# 4. Add freebsd-zfs partition labeled `zfs#' for zroot
870		#
871		f_eval_catch $funcname gpart "$GPART_ADD_LABEL" \
872		             zfs$index freebsd-zfs $disk || return $FAILURE
873		f_eval_catch -d $funcname zpool "$ZPOOL_LABELCLEAR_F" \
874		                /dev/$disk$targetpart
875		;;
876
877	MBR) f_dprintf "$funcname: Creating MBR layout..."
878		#
879		# 1. Create MBR layout (no labels)
880		#
881		f_eval_catch $funcname gpart "$GPART_CREATE" mbr $disk ||
882		             return $FAILURE
883		f_eval_catch $funcname gpart "$GPART_BOOTCODE" /boot/mbr \
884		             $disk || return $FAILURE
885
886		#
887		# 2. Add freebsd slice with all available space
888		#
889		f_eval_catch $funcname gpart "$GPART_ADD" freebsd $disk ||
890		             return $FAILURE
891		f_eval_catch $funcname gpart "$GPART_SET_ACTIVE" 1 $disk ||
892		             return $FAILURE
893		# Pedantically nuke any old labels
894		f_eval_catch -d $funcname zpool "$ZPOOL_LABELCLEAR_F" \
895		                /dev/${disk}s1
896		# Pedantically nuke any old scheme
897		f_eval_catch -d $funcname gpart "$GPART_DESTROY_F" ${disk}s1
898
899		#
900		# 3. Write BSD scheme to the freebsd slice
901		#
902		f_eval_catch $funcname gpart "$GPART_CREATE" BSD ${disk}s1 ||
903		             return $FAILURE
904
905		# NB: zpool will use s1a (no labels)
906		bootpart=s1a swappart=s1b targetpart=s1d mbrindex=4
907
908		#
909		# Always prepare a boot pool on MBR
910		#
911		ZFSBOOT_BOOT_POOL=1
912		f_eval_catch $funcname gpart \
913		             "$GPART_ADD_INDEX_WITH_SIZE" \
914		             1 freebsd-zfs ${bootsize}b ${disk}s1 ||
915		             return $FAILURE
916		# Pedantically nuke any old labels
917		f_eval_catch -d $funcname zpool "$ZPOOL_LABELCLEAR_F" \
918		                /dev/$disk$bootpart
919		if [ "$ZFSBOOT_GELI_ENCRYPTION" ]; then
920			# Pedantically detach targetpart for later
921			f_eval_catch -d $funcname geli \
922			                "$GELI_DETACH_F" \
923					/dev/$disk$targetpart
924		fi
925
926		#
927		# 4. Add freebsd-swap partition
928		#
929		if [ ${swapsize:-0} -gt 0 ]; then
930			f_eval_catch $funcname gpart \
931			             "$GPART_ADD_INDEX_WITH_SIZE" 2 \
932			             freebsd-swap ${swapsize}b ${disk}s1 ||
933			             return $FAILURE
934			# Pedantically nuke any old labels on the swap
935			f_eval_catch -d $funcname zpool "$ZPOOL_LABELCLEAR_F" \
936			                /dev/${disk}s1b
937		fi
938
939		#
940		# 5. Add freebsd-zfs partition for zroot
941		#
942		f_eval_catch $funcname gpart "$GPART_ADD_INDEX" \
943		             $mbrindex freebsd-zfs ${disk}s1 || return $FAILURE
944		f_eval_catch -d $funcname zpool "$ZPOOL_LABELCLEAR_F" \
945		                /dev/$disk$targetpart # Pedantic
946		f_eval_catch $funcname dd "$DD_WITH_OPTIONS" \
947		             /boot/zfsboot /dev/${disk}s1 count=1 ||
948		             return $FAILURE
949		;;
950
951	esac # $ZFSBOOT_PARTITION_SCHEME
952
953	# Update fstab(5)
954	if [ "$isswapmirror" ]; then
955		# This is not the first disk in the mirror, do nothing
956	elif [ "$ZFSBOOT_SWAP_ENCRYPTION" -a "$ZFSBOOT_SWAP_MIRROR" ]; then
957		f_eval_catch $funcname printf "$PRINTF_FSTAB" \
958		             /dev/mirror/swap.eli none swap sw 0 0 \
959		             $BSDINSTALL_TMPETC/fstab ||
960		             return $FAILURE
961		isswapmirror=1
962	elif [ "$ZFSBOOT_SWAP_MIRROR" ]; then
963		f_eval_catch $funcname printf "$PRINTF_FSTAB" \
964		             /dev/mirror/swap none swap sw 0 0 \
965		             $BSDINSTALL_TMPETC/fstab ||
966		             return $FAILURE
967		isswapmirror=1
968	elif [ "$ZFSBOOT_SWAP_ENCRYPTION" ]; then
969		f_eval_catch $funcname printf "$PRINTF_FSTAB" \
970		             /dev/$disk${swappart}.eli none swap sw 0 0 \
971		             $BSDINSTALL_TMPETC/fstab ||
972		             return $FAILURE
973	else
974		f_eval_catch $funcname printf "$PRINTF_FSTAB" \
975		             /dev/$disk$swappart none swap sw 0 0 \
976		             $BSDINSTALL_TMPETC/fstab ||
977		             return $FAILURE
978	fi
979
980	return $SUCCESS
981}
982
983# zfs_create_boot $poolname $vdev_type $disks ...
984#
985# Creates boot pool and dataset layout. Returns error if something goes wrong.
986# Errors are printed to stderr for collection and display.
987#
988zfs_create_boot()
989{
990	local funcname=zfs_create_boot
991	local zroot_name="$1"
992	local zroot_vdevtype="$2"
993	local zroot_vdevs= # Calculated below
994	local swap_devs= # Calculated below
995	local boot_vdevs= # Used for geli(8) and/or MBR layouts
996	shift 2 # poolname vdev_type
997	local disks="$*" disk
998	local isswapmirror
999	local bootpart targetpart swappart # Set by zfs_create_diskpart() below
1000	local create_options
1001
1002	#
1003	# Pedantic checks; should never be seen
1004	#
1005	if [ ! "$zroot_name" ]; then
1006		f_dprintf "$funcname: NULL poolname"
1007		msg_error="$msg_error: $funcname" \
1008			f_show_err "$msg_null_poolname"
1009		return $FAILURE
1010	fi
1011	if [ $# -lt 1 ]; then
1012		f_dprintf "$funcname: missing disk arguments"
1013		msg_error="$msg_error: $funcname" \
1014			f_show_err "$msg_missing_disk_arguments"
1015		return $FAILURE
1016	fi
1017	f_dprintf "$funcname: poolname=[%s] vdev_type=[%s]" \
1018	          "$zroot_name" "$zroot_vdevtype"
1019
1020	#
1021	# Initialize fstab(5)
1022	#
1023	f_dprintf "$funcname: Initializing temporary fstab(5) file..."
1024	f_eval_catch $funcname sh "$SHELL_TRUNCATE" $BSDINSTALL_TMPETC/fstab ||
1025	             return $FAILURE
1026	f_eval_catch $funcname printf "$PRINTF_FSTAB" \
1027	             "# Device" Mountpoint FStype Options Dump "Pass#" \
1028	             $BSDINSTALL_TMPETC/fstab || return $FAILURE
1029
1030	#
1031	# Expand SI units in desired sizes
1032	#
1033	f_dprintf "$funcname: Expanding supplied size values..."
1034	local swapsize bootsize
1035	if ! f_expand_number "$ZFSBOOT_SWAP_SIZE" swapsize; then
1036		f_dprintf "$funcname: Invalid swap size \`%s'" \
1037		          "$ZFSBOOT_SWAP_SIZE"
1038		f_show_err "$msg_invalid_swap_size" "$ZFSBOOT_SWAP_SIZE"
1039		return $FAILURE
1040	fi
1041	if ! f_expand_number "$ZFSBOOT_BOOT_POOL_SIZE" bootsize; then
1042		f_dprintf "$funcname: Invalid boot pool size \`%s'" \
1043		          "$ZFSBOOT_BOOT_POOL_SIZE"
1044		f_show_err "$msg_invalid_boot_pool_size" \
1045		           "$ZFSBOOT_BOOT_POOL_SIZE"
1046		return $FAILURE
1047	fi
1048	f_dprintf "$funcname: ZFSBOOT_SWAP_SIZE=[%s] swapsize=[%s]" \
1049	          "$ZFSBOOT_SWAP_SIZE" "$swapsize"
1050	f_dprintf "$funcname: ZFSBOOT_BOOT_POOL_SIZE=[%s] bootsize=[%s]" \
1051	          "$ZFSBOOT_BOOT_POOL_SIZE" "$bootsize"
1052
1053	#
1054	# Destroy the pool in-case this is our second time 'round (case of
1055	# failure and installer presented ``Retry'' option to come back).
1056	#
1057	# NB: If we don't destroy the pool, later gpart(8) destroy commands
1058	# that try to clear existing partitions (see zfs_create_diskpart())
1059	# will fail with a `Device Busy' error, leading to `GEOM exists'.
1060	#
1061	f_eval_catch -d $funcname zpool "$ZPOOL_DESTROY" "$zroot_name"
1062
1063	#
1064	# Prepare the disks and build pool device list(s)
1065	#
1066	f_dprintf "$funcname: Preparing disk partitions for ZFS pool..."
1067
1068	# Force 4K sectors using vfs.zfs.min_auto_ashift=12
1069	if [ "$ZFSBOOT_FORCE_4K_SECTORS" ]; then
1070		f_dprintf "$funcname: With 4K sectors..."
1071		f_eval_catch $funcname sysctl "$SYSCTL_ZFS_MIN_ASHIFT_12" \
1072		    || return $FAILURE
1073	fi
1074	local n=0
1075	for disk in $disks; do
1076		zfs_create_diskpart $disk $n || return $FAILURE
1077		# Now $bootpart, $targetpart, and $swappart are set (suffix
1078		# for $disk)
1079		if [ "$ZFSBOOT_BOOT_POOL" ]; then
1080			boot_vdevs="$boot_vdevs $disk$bootpart"
1081		fi
1082		zroot_vdevs="$zroot_vdevs $disk$targetpart"
1083		if [ "$ZFSBOOT_GELI_ENCRYPTION" ]; then
1084			zroot_vdevs="$zroot_vdevs.eli"
1085		fi
1086
1087		n=$(( $n + 1 ))
1088	done # disks
1089
1090	#
1091	# If we need/want a boot pool, create it
1092	#
1093	if [ "$ZFSBOOT_BOOT_POOL" ]; then
1094		local bootpool_vdevtype= # Calculated below
1095		local bootpool_options= # Calculated below
1096		local bootpool_name="$ZFSBOOT_BOOT_POOL_NAME"
1097		local bootpool="$BSDINSTALL_CHROOT/$bootpool_name"
1098		local zroot_key="${ZFSBOOT_GELI_KEY_FILE#/}"
1099
1100		f_dprintf "$funcname: Setting up boot pool..."
1101		[ "$ZFSBOOT_GELI_ENCRYPTION" ] &&
1102			f_dprintf "$funcname: For encrypted root disk..."
1103
1104		# Create parent directory for boot pool
1105		f_eval_catch -d $funcname umount "$UMOUNT" /mnt
1106		f_eval_catch $funcname mount "$MOUNT_TYPE" tmpfs none \
1107		             $BSDINSTALL_CHROOT || return $FAILURE
1108
1109		# Create mirror across the boot partition on all disks
1110		local nvdevs
1111		f_count nvdevs $boot_vdevs
1112		[ $nvdevs -gt 1 ] && bootpool_vdevtype=mirror
1113
1114		create_options="$ZFSBOOT_BOOT_POOL_CREATE_OPTIONS"
1115		bootpool_options="-o altroot=$BSDINSTALL_CHROOT"
1116		bootpool_options="$bootpool_options $create_options"
1117		bootpool_options="$bootpool_options -m \"/$bootpool_name\" -f"
1118		f_eval_catch $funcname zpool "$ZPOOL_CREATE_WITH_OPTIONS" \
1119		             "$bootpool_options" "$bootpool_name" \
1120		             "$bootpool_vdevtype" "$boot_vdevs" ||
1121		             return $FAILURE
1122
1123		f_eval_catch $funcname mkdir "$MKDIR_P" "$bootpool/boot" ||
1124		             return $FAILURE
1125
1126		if [ "$ZFSBOOT_GELI_ENCRYPTION" ]; then
1127			# Generate an encryption key using random(4)
1128			f_eval_catch $funcname dd "$DD_WITH_OPTIONS" \
1129			             /dev/random "$bootpool/$zroot_key" \
1130			             "bs=4096 count=1" || return $FAILURE
1131			f_eval_catch $funcname chmod "$CHMOD_MODE" \
1132			             go-wrx "$bootpool/$zroot_key" ||
1133			             return $FAILURE
1134		else
1135			# Clean up
1136			f_eval_catch $funcname zfs "$ZFS_UNMOUNT" \
1137			             "$bootpool_name" || return $FAILURE
1138			f_eval_catch -d $funcname umount "$UMOUNT" /mnt # tmpfs
1139		fi
1140
1141	fi
1142
1143	#
1144	# Create the geli(8) GEOMS
1145	#
1146	if [ "$ZFSBOOT_GELI_ENCRYPTION" ]; then
1147		# Prompt user for password (twice)
1148		if ! msg_enter_new_password="$msg_geli_password" \
1149			f_dialog_input_password
1150		then
1151			f_dprintf "$funcname: User cancelled"
1152			f_show_err "$msg_user_cancelled"
1153			return $FAILURE
1154		fi
1155
1156		# Initialize geli(8) on each of the target partitions
1157		for disk in $disks; do
1158			f_dialog_info "$msg_geli_setup" \
1159				2>&1 >&$DIALOG_TERMINAL_PASSTHRU_FD
1160			if ! echo "$pw_password" | f_eval_catch \
1161				$funcname geli "$GELI_PASSWORD_INIT" \
1162				"$bootpool/boot/$disk$targetpart.eli" \
1163				AES-XTS "$bootpool/$zroot_key" \
1164				$disk$targetpart
1165			then
1166				f_interactive || f_die
1167				unset pw_password # Sensitive info
1168				return $FAILURE
1169			fi
1170			if ! echo "$pw_password" | f_eval_catch \
1171				$funcname geli "$GELI_ATTACH" \
1172				"$bootpool/$zroot_key" $disk$targetpart
1173			then
1174				f_interactive || f_die
1175				unset pw_password # Sensitive info
1176				return $FAILURE
1177			fi
1178		done
1179		unset pw_password # Sensitive info
1180
1181		# Clean up
1182		f_eval_catch $funcname zfs "$ZFS_UNMOUNT" "$bootpool_name" ||
1183			return $FAILURE
1184		f_eval_catch -d $funcname umount "$UMOUNT" /mnt # tmpfs
1185	fi
1186
1187	#
1188	# Create the gmirror(8) GEOMS for swap
1189	#
1190	if [ "$ZFSBOOT_SWAP_MIRROR" ]; then
1191		for disk in $disks; do
1192			swap_devs="$swap_devs $disk$swappart"
1193		done
1194		f_eval_catch $funcname gmirror "$SWAP_GMIRROR_LABEL" \
1195			"$swap_devs" || return $FAILURE
1196	fi
1197
1198	#
1199	# Create the ZFS root pool with desired type and disk devices
1200	#
1201	f_dprintf "$funcname: Creating root pool..."
1202	create_options="$ZFSBOOT_POOL_CREATE_OPTIONS"
1203	f_eval_catch $funcname zpool "$ZPOOL_CREATE_WITH_OPTIONS" \
1204		"-o altroot=$BSDINSTALL_CHROOT $create_options -m none -f" \
1205		"$zroot_name" "$zroot_vdevtype" "$zroot_vdevs" ||
1206		return $FAILURE
1207
1208	#
1209	# Create ZFS dataset layout within the new root pool
1210	#
1211	f_dprintf "$funcname: Creating ZFS datasets..."
1212	echo "$ZFSBOOT_DATASETS" | while read dataset options; do
1213		# Skip blank lines and comments
1214		case "$dataset" in "#"*|"") continue; esac
1215		# Remove potential inline comments in options
1216		options="${options%%#*}"
1217		# Replace tabs with spaces
1218		f_replaceall "$options" "	" " " options
1219		# Reduce contiguous runs of space to one single space
1220		oldoptions=
1221		while [ "$oldoptions" != "$options" ]; do
1222			oldoptions="$options"
1223			f_replaceall "$options" "  " " " options
1224		done
1225		# Replace both commas and spaces with ` -o '
1226		f_replaceall "$options" "[ ,]" " -o " options
1227		# Create the dataset with desired options
1228		f_eval_catch $funcname zfs "$ZFS_CREATE_WITH_OPTIONS" \
1229		             "${options:+-o $options}" "$zroot_name$dataset" ||
1230		             return $FAILURE
1231	done
1232
1233	# Touch up permissions on the tmp directories
1234	f_dprintf "$funcname: Modifying directory permissions..."
1235	local dir
1236	for dir in /tmp /var/tmp; do
1237		f_eval_catch $funcname chmod "$CHMOD_MODE" 1777 \
1238		             $BSDINSTALL_CHROOTDIR$dir || return $FAILURE
1239	done
1240
1241	# Create symlink(s)
1242	if [ "$ZFSBOOT_BOOT_POOL" ]; then
1243		f_dprintf "$funcname: Creating /boot symlink for boot pool..."
1244		f_eval_catch $funcname ln "$LN_SF" "$bootpool_name/boot" \
1245		             $BSDINSTALL_CHROOT/boot || return $FAILURE
1246	fi
1247
1248	# Set bootfs property
1249	local zroot_bootfs="$ZFSBOOT_BEROOT_NAME/$ZFSBOOT_BOOTFS_NAME"
1250	f_dprintf "$funcname: Setting bootfs property..."
1251	f_eval_catch $funcname zpool "$ZPOOL_SET" \
1252		"bootfs=\"$zroot_name/$zroot_bootfs\"" "$zroot_name" ||
1253		return $FAILURE
1254
1255	# Export the pool(s)
1256	f_dprintf "$funcname: Temporarily exporting ZFS pool(s)..."
1257	f_eval_catch $funcname zpool "$ZPOOL_EXPORT" "$zroot_name" ||
1258	             return $FAILURE
1259	if [ "$ZFSBOOT_BOOT_POOL" ]; then
1260		f_eval_catch $funcname zpool "$ZPOOL_EXPORT" \
1261		             "$bootpool_name" || return $FAILURE
1262	fi
1263
1264	# MBR boot loader touch-up
1265	if [ "$ZFSBOOT_PARTITION_SCHEME" = "MBR" ]; then
1266		f_dprintf "$funcname: Updating MBR boot loader on disks..."
1267		# Stick the ZFS boot loader in the "convienient hole" after
1268		# the ZFS internal metadata
1269		for disk in $disks; do
1270			f_eval_catch $funcname dd "$DD_WITH_OPTIONS" \
1271			             /boot/zfsboot /dev/$disk$bootpart \
1272			             "skip=1 seek=1024" || return $FAILURE
1273		done
1274	fi
1275
1276	# Re-import the ZFS pool(s)
1277	f_dprintf "$funcname: Re-importing ZFS pool(s)..."
1278	f_eval_catch $funcname zpool "$ZPOOL_IMPORT_WITH_OPTIONS" \
1279	             "-o altroot=\"$BSDINSTALL_CHROOT\"" "$zroot_name" ||
1280	             return $FAILURE
1281	if [ "$ZFSBOOT_BOOT_POOL" ]; then
1282		f_eval_catch $funcname zpool "$ZPOOL_IMPORT_WITH_OPTIONS" \
1283		             "-o altroot=\"$BSDINSTALL_CHROOT\"" \
1284		             "$bootpool_name" || return $FAILURE
1285	fi
1286
1287	# While this is apparently not needed, it seems to help MBR
1288	f_dprintf "$funcname: Configuring zpool.cache for zroot..."
1289	f_eval_catch $funcname mkdir "$MKDIR_P" $BSDINSTALL_CHROOT/boot/zfs ||
1290	             return $FAILURE
1291	f_eval_catch $funcname zpool "$ZPOOL_SET" \
1292	             "cachefile=\"$BSDINSTALL_CHROOT/boot/zfs/zpool.cache\"" \
1293	             "$zroot_name" || return $FAILURE
1294
1295	# Last, but not least... required lines for rc.conf(5)/loader.conf(5)
1296	# NOTE: We later concatenate these into their destination
1297	f_dprintf "%s: Configuring rc.conf(5)/loader.conf(5) additions..." \
1298	          "$funcname"
1299	f_eval_catch $funcname echo "$ECHO_APPEND" 'zfs_enable=\"YES\"' \
1300	             $BSDINSTALL_TMPETC/rc.conf.zfs || return $FAILURE
1301	f_eval_catch $funcname echo "$ECHO_APPEND" \
1302	             'kern.geom.label.disk_ident.enable=\"0\"' \
1303	             $BSDINSTALL_TMPBOOT/loader.conf.zfs || return $FAILURE
1304	f_eval_catch $funcname echo "$ECHO_APPEND" \
1305	             'kern.geom.label.gptid.enable=\"0\"' \
1306	             $BSDINSTALL_TMPBOOT/loader.conf.zfs || return $FAILURE
1307
1308	if [ "$ZFSBOOT_SWAP_MIRROR" ]; then
1309		f_eval_catch $funcname echo "$ECHO_APPEND" \
1310		             'geom_mirror_load=\"YES\"' \
1311		             $BSDINSTALL_TMPBOOT/loader.conf.gmirror ||
1312		             return $FAILURE
1313	fi
1314
1315	# We're all done unless we should go on for boot pool
1316	[ "$ZFSBOOT_BOOT_POOL" ] || return $SUCCESS
1317
1318	# Set cachefile for boot pool so it auto-imports at system start
1319	f_dprintf "$funcname: Configuring zpool.cache for boot pool..."
1320	f_eval_catch $funcname zpool "$ZPOOL_SET" \
1321	             "cachefile=\"$BSDINSTALL_CHROOT/boot/zfs/zpool.cache\"" \
1322	             "$bootpool_name" || return $FAILURE
1323
1324	# Some additional geli(8) requirements for loader.conf(5)
1325	for option in \
1326		'zpool_cache_load=\"YES\"' \
1327		'zpool_cache_type=\"/boot/zfs/zpool.cache\"' \
1328		'zpool_cache_name=\"/boot/zfs/zpool.cache\"' \
1329	; do
1330		f_eval_catch $funcname echo "$ECHO_APPEND" "$option" \
1331		             $BSDINSTALL_TMPBOOT/loader.conf.zfs ||
1332		             return $FAILURE
1333	done
1334	f_eval_catch $funcname printf "$PRINTF_CONF" vfs.root.mountfrom \
1335		"\"zfs:$zroot_name/$zroot_bootfs\"" \
1336		$BSDINSTALL_TMPBOOT/loader.conf.root || return $FAILURE
1337
1338	# We're all done unless we should go on to do encryption
1339	[ "$ZFSBOOT_GELI_ENCRYPTION" ] || return $SUCCESS
1340
1341	#
1342	# Configure geli(8)-based encryption
1343	#
1344	f_dprintf "$funcname: Configuring disk encryption..."
1345	f_eval_catch $funcname echo "$ECHO_APPEND" 'aesni_load=\"YES\"' \
1346		$BSDINSTALL_TMPBOOT/loader.conf.aesni || return $FAILURE
1347	f_eval_catch $funcname echo "$ECHO_APPEND" 'geom_eli_load=\"YES\"' \
1348		$BSDINSTALL_TMPBOOT/loader.conf.geli || return $FAILURE
1349	f_eval_catch $funcname echo "$ECHO_APPEND" \
1350		'geom_eli_passphrase_prompt=\"YES\"' \
1351		$BSDINSTALL_TMPBOOT/loader.conf.geli || return $FAILURE
1352	for disk in $disks; do
1353		f_eval_catch $funcname printf "$PRINTF_CONF" \
1354			geli_%s_keyfile0_load "$disk$targetpart YES" \
1355			$BSDINSTALL_TMPBOOT/loader.conf.$disk$targetpart ||
1356			return $FAILURE
1357		f_eval_catch $funcname printf "$PRINTF_CONF" \
1358			geli_%s_keyfile0_type \
1359			"$disk$targetpart $disk$targetpart:geli_keyfile0" \
1360			$BSDINSTALL_TMPBOOT/loader.conf.$disk$targetpart ||
1361			return $FAILURE
1362		f_eval_catch $funcname printf "$PRINTF_CONF" \
1363			geli_%s_keyfile0_name \
1364			"$disk$targetpart \"$ZFSBOOT_GELI_KEY_FILE\"" \
1365			$BSDINSTALL_TMPBOOT/loader.conf.$disk$targetpart ||
1366			return $FAILURE
1367	done
1368
1369	return $SUCCESS
1370}
1371
1372# dialog_menu_diskinfo
1373#
1374# Prompt the user to select a disk and then provide detailed info on it.
1375#
1376dialog_menu_diskinfo()
1377{
1378	local device disk
1379
1380	#
1381	# Break from loop when user cancels disk selection
1382	#
1383	while :; do
1384		device=$( msg_cancel="$msg_back" f_device_menu \
1385			"$DIALOG_TITLE" "$msg_select_a_disk_device" "" \
1386			$DEVICE_TYPE_DISK 2>&1 ) || break
1387		$device get name disk
1388
1389		# Show gpart(8) `show' and camcontrol(8) `inquiry' data
1390		f_show_msg "$msg_detailed_disk_info" \
1391			"$disk" "$( gpart show $disk 2> /dev/null )" \
1392			"$disk" "$( camcontrol inquiry $disk 2> /dev/null )" \
1393			"$disk" "$( camcontrol identify $disk 2> /dev/null )"
1394	done
1395
1396	return $SUCCESS
1397}
1398
1399############################################################ MAIN
1400
1401#
1402# Initialize
1403#
1404f_dialog_title "$msg_zfs_configuration"
1405f_dialog_backtitle "$msg_freebsd_installer"
1406
1407# User may have specifically requested ZFS-related operations be interactive
1408! f_interactive && f_zfsinteractive && unset $VAR_NONINTERACTIVE
1409
1410#
1411# Debugging
1412#
1413f_dprintf "BSDINSTALL_CHROOT=[%s]" "$BSDINSTALL_CHROOT"
1414f_dprintf "BSDINSTALL_TMPETC=[%s]" "$BSDINSTALL_TMPETC"
1415f_dprintf "FSTAB_FMT=[%s]" "$FSTAB_FMT"
1416
1417#
1418# If the system was booted with UEFI, warn the user that FreeBSD can't do
1419# ZFS with UEFI yet
1420#
1421if f_interactive; then
1422	bootmethod=$( sysctl -n machdep.bootmethod )
1423	f_dprintf "machdep.bootmethod=[%s]" "$bootmethod"
1424	if [ "$bootmethod" != "BIOS" ]; then
1425		dialog_uefi_prompt
1426		retval=$?
1427		f_dprintf "uefi_prompt=[%s]" "$retval"
1428		[ $retval -eq $DIALOG_OK ] || f_die
1429	fi
1430fi
1431
1432#
1433# Loop over the main menu until we've accomplished what we came here to do
1434#
1435while :; do
1436	if ! f_interactive; then
1437		retval=$DIALOG_OK
1438		mtag=">>> $msg_install"
1439	else
1440		dialog_menu_main
1441		retval=$?
1442		f_dialog_menutag_fetch mtag
1443	fi
1444
1445	f_dprintf "retval=%u mtag=[%s]" $retval "$mtag"
1446	[ $retval -eq $DIALOG_OK ] || f_die
1447
1448	case "$mtag" in
1449	">>> $msg_install")
1450		#
1451		# First, validate the user's selections
1452		#
1453
1454		# Make sure they gave us a name for the pool
1455		if [ ! "$ZFSBOOT_POOL_NAME" ]; then
1456			f_dprintf "Pool name cannot be empty."
1457			f_show_err "$msg_pool_name_cannot_be_empty"
1458			continue
1459		fi
1460
1461		# Validate vdev type against number of disks selected/scripted
1462		# (also validates that ZFSBOOT_DISKS are real [probed] disks)
1463		# NB: dialog_menu_layout supports running non-interactively
1464		dialog_menu_layout || continue
1465
1466		# Make sure each disk will be at least 50% ZFS
1467		if f_expand_number "$ZFSBOOT_SWAP_SIZE" swapsize &&
1468		   f_expand_number "$ZFSBOOT_BOOT_POOL_SIZE" bootsize
1469		then
1470			minsize=$swapsize teeny_disks=
1471			[ "$ZFSBOOT_BOOT_POOL" ] &&
1472				minsize=$(( $minsize + $bootsize ))
1473			for disk in $ZFSBOOT_DISKS; do
1474				debug= f_device_find -1 \
1475					$disk $DEVICE_TYPE_DISK device
1476				$device get capacity disksize || continue
1477				[ ${disksize:-0} -ge 0 ] || disksize=0
1478				disksize=$(( $disksize - $minsize ))
1479				[ $disksize -lt $minsize ] &&
1480					teeny_disks="$teeny_disks $disk"
1481			done
1482			if [ "$teeny_disks" ]; then
1483				f_dprintf "swapsize=[%s] bootsize[%s] %s" \
1484				          "$ZFSBOOT_SWAP_SIZE" \
1485				          "$ZFSBOOT_BOOT_POOL_SIZE" \
1486				          "minsize=[$minsize]"
1487				f_dprintf "These disks are too small: %s" \
1488				          "$teeny_disks"
1489				f_show_err "$msg_these_disks_are_too_small" \
1490				           "$ZFSBOOT_SWAP_SIZE" \
1491				           "$ZFSBOOT_BOOT_POOL_SIZE" \
1492				           "$teeny_disks"
1493				continue
1494			fi
1495		fi
1496
1497		#
1498		# Last Chance!
1499		#
1500		if f_interactive; then
1501			dialog_last_chance $ZFSBOOT_DISKS || continue
1502		fi
1503
1504		#
1505		# Let's do this
1506		#
1507
1508		vdev_type="$ZFSBOOT_VDEV_TYPE"
1509
1510		# Blank the vdev type for the default layout
1511		[ "$vdev_type" = "stripe" ] && vdev_type=
1512
1513		zfs_create_boot "$ZFSBOOT_POOL_NAME" \
1514		                "$vdev_type" $ZFSBOOT_DISKS || continue
1515
1516		break # to success
1517		;;
1518	?" $msg_pool_type_disks")
1519		ZFSBOOT_CONFIRM_LAYOUT=1
1520		dialog_menu_layout
1521		# User has poked settings, disable later confirmation
1522		ZFSBOOT_CONFIRM_LAYOUT=
1523		;;
1524	"- $msg_rescan_devices") f_device_rescan ;;
1525	"- $msg_disk_info") dialog_menu_diskinfo ;;
1526	?" $msg_pool_name")
1527		# Prompt the user to input/change the name for the new pool
1528		f_dialog_input input \
1529			"$msg_please_enter_a_name_for_your_zpool" \
1530			"$ZFSBOOT_POOL_NAME" &&
1531			ZFSBOOT_POOL_NAME="$input"
1532		;;
1533	?" $msg_force_4k_sectors")
1534		# Toggle the variable referenced both by the menu and later
1535		if [ "$ZFSBOOT_FORCE_4K_SECTORS" ]; then
1536			ZFSBOOT_FORCE_4K_SECTORS=
1537		else
1538			ZFSBOOT_FORCE_4K_SECTORS=1
1539		fi
1540		;;
1541	?" $msg_encrypt_disks")
1542		# Toggle the variable referenced both by the menu and later
1543		if [ "$ZFSBOOT_GELI_ENCRYPTION" ]; then
1544			ZFSBOOT_GELI_ENCRYPTION=
1545		else
1546			ZFSBOOT_FORCE_4K_SECTORS=1
1547			ZFSBOOT_GELI_ENCRYPTION=1
1548		fi
1549		;;
1550	?" $msg_partition_scheme")
1551		# Toggle between GPT and MBR
1552		if [ "$ZFSBOOT_PARTITION_SCHEME" = GPT ]; then
1553			ZFSBOOT_PARTITION_SCHEME=MBR
1554		else
1555			ZFSBOOT_PARTITION_SCHEME=GPT
1556		fi
1557		;;
1558	?" $msg_swap_size")
1559		# Prompt the user to input/change the swap size for each disk
1560		f_dialog_input input \
1561			"$msg_please_enter_amount_of_swap_space" \
1562			"$ZFSBOOT_SWAP_SIZE" &&
1563			ZFSBOOT_SWAP_SIZE="${input:-0}"
1564		;;
1565	?" $msg_swap_mirror")
1566		# Toggle the variable referenced both by the menu and later
1567		if [ "$ZFSBOOT_SWAP_MIRROR" ]; then
1568			ZFSBOOT_SWAP_MIRROR=
1569		else
1570			ZFSBOOT_SWAP_MIRROR=1
1571		fi
1572		;;
1573	?" $msg_swap_encrypt")
1574		# Toggle the variable referenced both by the menu and later
1575		if [ "$ZFSBOOT_SWAP_ENCRYPTION" ]; then
1576			ZFSBOOT_SWAP_ENCRYPTION=
1577		else
1578			ZFSBOOT_SWAP_ENCRYPTION=1
1579		fi
1580		;;
1581	esac
1582done
1583
1584return $SUCCESS
1585
1586################################################################################
1587# END
1588################################################################################
1589