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