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